<template>
  <div id="text-slider">
    <div :style="{ backgroundImage: `linear-gradient`+'('+`to right, ${props.color} ,${props.color}, ${props.color}`+')'+`` }" id="text-slider-node">{{text}}</div>
  </div>
</template>

<script setup lang="ts">
import { onUpdated, ref, onMounted, onUnmounted, watch } from 'vue';
interface Prop {
  message: string
  speed?: number,
  color?: string,
  start: number
}
const props = withDefaults(defineProps<Prop>(), {
  speed: 40,
  color: "#fff7c9"
})
const text = ref("")

let timer:NodeJS.Timer;
const move = function() {
  // 获取文字text 的计算后宽度  （由于overflow的存在，直接获取不到，需要独立的node计算）
  const node = document.getElementById("text-slider-node")
  const width = node?.getBoundingClientRect().width as number;
  let distance = 0; // 位移距离
  timer = setInterval(function () {
    distance = distance - 1;
    // 如果位移超过文字宽度，则回到起点
    if (Math.abs(distance) >= width) {
      distance = props.start;
    }
    node!.style.transform = "translateX(" + distance + "px)";
  }, props.speed);
}

onUpdated(() => move())
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
watch(() => props.message, (message) => {
  text.value = message
})
onMounted(() => {
  text.value = props.message
})
</script>

<style lang="less" scoped>
  #text-slider {
    overflow: hidden;
    margin: 0 auto;
    width: 100%;
  }
  #text-slider-node {
    -webkit-background-clip: text; 
    -webkit-text-fill-color: transparent;
    font-size: 1vw;
  }
</style>
