github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/static_source/admin/src/hooks/event/useScrollTo.ts (about)

     1  import { ref, unref } from 'vue'
     2  
     3  export interface ScrollToParams {
     4    el: HTMLElement
     5    to: number
     6    position: string
     7    duration?: number
     8    callback?: () => void
     9  }
    10  
    11  const easeInOutQuad = (t: number, b: number, c: number, d: number) => {
    12    t /= d / 2
    13    if (t < 1) {
    14      return (c / 2) * t * t + b
    15    }
    16    t--
    17    return (-c / 2) * (t * (t - 2) - 1) + b
    18  }
    19  const move = (el: HTMLElement, position: string, amount: number) => {
    20    el[position] = amount
    21  }
    22  
    23  export function useScrollTo({
    24    el,
    25    position = 'scrollLeft',
    26    to,
    27    duration = 500,
    28    callback
    29  }: ScrollToParams) {
    30    const isActiveRef = ref(false)
    31    const start = el[position]
    32    const change = to - start
    33    const increment = 20
    34    let currentTime = 0
    35  
    36    function animateScroll() {
    37      if (!unref(isActiveRef)) {
    38        return
    39      }
    40      currentTime += increment
    41      const val = easeInOutQuad(currentTime, start, change, duration)
    42      move(el, position, val)
    43      if (currentTime < duration && unref(isActiveRef)) {
    44        requestAnimationFrame(animateScroll)
    45      } else {
    46        if (callback) {
    47          callback()
    48        }
    49      }
    50    }
    51  
    52    function run() {
    53      isActiveRef.value = true
    54      animateScroll()
    55    }
    56  
    57    function stop() {
    58      isActiveRef.value = false
    59    }
    60  
    61    return { start: run, stop }
    62  }