zjk
2026-02-04 b4dc99a92c8fbdfefa48870fde72042e0d1e168a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import type { NScrollbar } from 'naive-ui'
import { ref, type Ref, watchEffect } from 'vue'
import { throttle } from 'radash'
 
export function useTabScroll(currentTabPath: Ref<string>) {
  const scrollbar = ref<InstanceType<typeof NScrollbar>>()
  const safeArea = ref(150)
 
  const handleTabSwitch = (distance: number) => {
    scrollbar.value?.scrollTo({
      left: distance,
      behavior: 'smooth',
    })
  }
 
  const scrollToCurrentTab = () => {
    nextTick(() => {
      const currentTabElement = document.querySelector(`[data-tab-path="${currentTabPath.value}"]`) as HTMLElement
      const tabBarScrollWrapper = document.querySelector('.tab-bar-scroller-wrapper .n-scrollbar-container')
      const tabBarScrollContent = document.querySelector('.tab-bar-scroller-content')
 
      if (currentTabElement && tabBarScrollContent && tabBarScrollWrapper) {
        const tabLeft = currentTabElement.offsetLeft
        const tabBarLeft = tabBarScrollWrapper.scrollLeft
        const wrapperWidth = tabBarScrollWrapper.getBoundingClientRect().width
        const tabWidth = currentTabElement.getBoundingClientRect().width
        const containerPR = Number.parseFloat(window.getComputedStyle(tabBarScrollContent).paddingRight)
 
        if (tabLeft + tabWidth + safeArea.value + containerPR > wrapperWidth + tabBarLeft) {
          handleTabSwitch(tabLeft + tabWidth + containerPR - wrapperWidth + safeArea.value)
        }
        else if (tabLeft - safeArea.value < tabBarLeft) {
          handleTabSwitch(tabLeft - safeArea.value)
        }
      }
    })
  }
 
  const handleScroll = throttle({ interval: 120 }, (step: number) => {
    scrollbar.value?.scrollBy({
      left: step * 400,
      behavior: 'smooth',
    })
  })
 
  const onWheel = (e: WheelEvent) => {
    e.preventDefault()
    if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
      handleScroll(e.deltaY > 0 ? 1 : -1)
    }
  }
 
  watchEffect(() => {
    if (currentTabPath.value) {
      scrollToCurrentTab()
    }
  })
 
  return {
    scrollbar,
    onWheel,
    safeArea,
    handleTabSwitch,
  }
}