<template>
  <Transition name="to-top">
    <a
      v-show="showing"
      href="javascript:;"
      class="to-top icon-top-bg-gray"
      @click="toTop"
    ></a>
  </Transition>
</template>
<script>
export default {
  name: 'ToTopButton',
  props: {
    threshold: {
      type: [Number, String],
      default: '20%',
    },
  },
  data() {
    return {
      showing: false,
    }
  },
  computed: {
    thresholdNumber() {
      const t = this.threshold
      if (typeof t === 'number') return t
      if (typeof t === 'string') {
        let m
        if ((m = /^(\d+)%$/.exec(t))) {
          return window.innerHeight * (+m[1] / 100)
        }
      }
      return 0
    },
  },
  created() {
    window.addEventListener('resize', this.onScroll)
    window.addEventListener('scroll', this.onScroll)
    this.onScroll()
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onScroll)
    window.removeEventListener('resize', this.onScroll)
  },
  methods: {
    onScroll() {
      const top = window.scrollY
      this.showing = top >= this.thresholdNumber
    },
    toTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth',
      })
    },
  },
}
</script>
<style lang="scss">
.to-top {
  position: fixed;
  z-index: 9999;
  right: 10vw;
  bottom: 10vh;
  display: block;
  width: 50px;
  height: 50px;
  opacity: 0.8;
}

.to-top-enter-active,
.to-top-leave-active {
  transition: 0.3s;
  background-repeat: no-repeat;
}

.to-top-enter,
.to-top-leave-to {
  opacity: 0;
  transform: translateY(50px);
  // background-position-y: 50px;
}
</style>
