Line data Source code
1 : <template>
2 4680 : <div
3 : ref="containerRef"
4 : :class="
5 : cn('overflow-hidden whitespace-nowrap', !isScrolling && 'text-ellipsis')
6 : "
7 : >
8 : <slot />
9 : </div>
10 : </template>
11 :
12 : <script setup lang="ts">
13 : import { useElementHover, useElementSize, useRafFn } from '@vueuse/core'
14 : import { ref, watch } from 'vue'
15 :
16 : import { cn } from '@comfyorg/tailwind-utils'
17 :
18 : const { speed = 70 } = defineProps<{
19 : /** Scroll speed in pixels per second */
20 : speed?: number
21 : }>()
22 :
23 4680 : const containerRef = ref<HTMLElement | null>(null)
24 4680 : const isHovered = useElementHover(containerRef, { delayEnter: 350 })
25 4680 : const { width: containerWidth } = useElementSize(containerRef)
26 4680 : const isScrolling = ref(false)
27 4680 : let scrollStartTime = 0
28 4680 : let overflowAmount = 0
29 :
30 4680 : const { pause, resume } = useRafFn(
31 : ({ timestamp }) => {
32 0 : const el = containerRef.value
33 0 : if (!el || overflowAmount <= 0) return pause()
34 :
35 0 : const elapsed = timestamp - scrollStartTime
36 0 : const duration = (overflowAmount / speed) * 1000
37 0 : const progress = Math.min(elapsed / duration, 1)
38 0 : el.scrollLeft = overflowAmount * progress
39 :
40 0 : if (progress >= 1) pause()
41 : },
42 : { immediate: false }
43 : )
44 :
45 0 : function startScroll() {
46 0 : const el = containerRef.value
47 0 : if (!el) return
48 :
49 0 : overflowAmount = el.scrollWidth - containerWidth.value
50 0 : if (overflowAmount <= 0) return
51 :
52 0 : isScrolling.value = true
53 0 : scrollStartTime = performance.now()
54 0 : resume()
55 : }
56 :
57 0 : function stopScroll() {
58 0 : pause()
59 0 : if (containerRef.value) {
60 0 : containerRef.value.scrollLeft = 0
61 : }
62 0 : isScrolling.value = false
63 : }
64 :
65 4680 : watch(isHovered, (hovered) => {
66 0 : if (hovered) startScroll()
67 0 : else stopScroll()
68 : })
69 : </script>
|