<template>
  <div
    ref="ellipsisScrollDom"
    :class="[isScroll && 'isScroll', isScroll && props.autoScroll && 'autoScroll']"
    v-html="props.title"
    class="ellipsisScroll"
  ></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue"

const props = defineProps<{
  title: string
  autoScroll?: boolean
}>()

const ellipsisScrollDom = ref<HTMLElement>()
const isScroll = ref(false)

onMounted(() => {
  if (props?.autoScroll) {
    nextTick(() => {
      handleAutoScroll(ellipsisScrollDom.value)
    })
  } else {
    ellipsisScrollDom.value?.addEventListener("mouseenter", handleIsScroll)
    ellipsisScrollDom.value?.addEventListener("mouseleave", handleLeaveScroll)
  }
})
onUnmounted(() => {
  if (!props?.autoScroll) {
    ellipsisScrollDom.value?.removeEventListener("mouseenter", handleIsScroll)
    ellipsisScrollDom.value?.removeEventListener("mouseleave", handleLeaveScroll)
  }
})

let widthCalc = 0
function handleIsScroll(e: MouseEvent) {
  const target = e.target as HTMLElement
  widthCalc = target.scrollWidth - target.clientWidth
  if (widthCalc > 0) {
    isScroll.value = true
  } else {
    isScroll.value = false
  }
}
function handleAutoScroll(target: any) {
  widthCalc = target.scrollWidth - target.clientWidth
  if (widthCalc > 0) {
    isScroll.value = true
  } else {
    isScroll.value = false
  }
}
function handleLeaveScroll() {
  isScroll.value = false
}
</script>

<style lang="scss" scoped>
.ellipsisScroll {
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  @keyframes roll {
    0% {
      transform: translateX(0);
    }
    100% {
      transform: translateX(-100%);
    }
  }
  &.isScroll {
    &:hover {
      width: auto;
      overflow: initial;
      animation: 3s roll linear infinite normal;
    }
  }
  &.autoScroll {
    width: auto;
    overflow: initial;
    animation: 3s roll linear infinite normal;
  }
}
</style>
