docs/.vitepress/theme/components/tabs/composables.ts
48 lines · 1301 bytes
2 symbols in this file
1import { nextTick, onBeforeMount, onUnmounted, type Ref, ref } from 'vue'
2
3export function useIsPrint() {
4 const matchMedia = typeof window !== 'undefined'
5 ? window.matchMedia('print')
6 : undefined
7 const value = ref(matchMedia?.matches)
8 const listener = () => {
9 value.value = matchMedia?.matches
10 }
11
12 onBeforeMount(() => {
13 matchMedia?.addEventListener('change', listener)
14 })
15 onUnmounted(() => {
16 matchMedia?.removeEventListener('change', listener)
17 })
18
19 return value
20}
21
22export function useStabilizeScrollPosition(
23 target: Ref<HTMLElement | undefined>
24) {
25 if (typeof document === 'undefined') {
26 return {
27 stabilizeScrollPosition:
28 <T extends (...args: any[]) => any>(func: T) =>
29 async (...args: Parameters<T>) => func(...args)
30 }
31 }
32
33 const scrollableElement = document.documentElement
34 const stabilizeScrollPosition =
35 <T extends (...args: any[]) => any>(func: T) =>
36 async (...args: Parameters<T>) => {
37 const result = func(...args)
38 const element = target.value
39 if (!element) return result
40
41 const offset = element.offsetTop - scrollableElement.scrollTop
42 await nextTick()
43 scrollableElement.scrollTop = element.offsetTop - offset
44 return result
45 }
46
47 return { stabilizeScrollPosition }
48}