Line data Source code
1 : import { useMutationObserver, useResizeObserver } from '@vueuse/core'
2 : import { debounce } from 'es-toolkit/compat'
3 : import { readonly, ref, toValue } from 'vue'
4 : import type { MaybeRefOrGetter } from 'vue'
5 :
6 : /**
7 : * Observes an element for overflow changes and optionally debounces the check
8 : * @param element - The element to observe
9 : * @param options - The options for the observer
10 : * @param options.debounceTime - The time to debounce the check in milliseconds
11 : * @param options.useMutationObserver - Whether to use a mutation observer to check for overflow
12 : * @param options.useResizeObserver - Whether to use a resize observer to check for overflow
13 : * @returns An object containing the isOverflowing state and the checkOverflow function to manually trigger
14 : */
15 2355 : export const useOverflowObserver = (
16 : element: MaybeRefOrGetter<HTMLElement | null | undefined>,
17 : options?: {
18 : debounceTime?: number
19 : useMutationObserver?: boolean
20 : useResizeObserver?: boolean
21 : onCheck?: (isOverflowing: boolean) => void
22 : }
23 : ) => {
24 4029 : options = {
25 : debounceTime: 25,
26 : useMutationObserver: true,
27 : useResizeObserver: true,
28 : ...options
29 : }
30 :
31 4029 : const isOverflowing = ref(false)
32 4029 : const disposeFns: (() => void)[] = []
33 4029 : const disposed = ref(false)
34 :
35 4029 : const checkOverflowFn = () => {
36 7834 : const resolvedElement = toValue(element)
37 7834 : isOverflowing.value = resolvedElement
38 : ? resolvedElement.scrollWidth > resolvedElement.clientWidth
39 : : false
40 7834 : options.onCheck?.(isOverflowing.value)
41 : }
42 :
43 4029 : const checkOverflow = options.debounceTime
44 : ? debounce(checkOverflowFn, options.debounceTime)
45 : : checkOverflowFn
46 :
47 4029 : if (options.useMutationObserver) {
48 4029 : disposeFns.push(
49 : useMutationObserver(element, checkOverflow, {
50 : subtree: true,
51 : childList: true
52 : }).stop
53 : )
54 : }
55 4029 : if (options.useResizeObserver) {
56 2009 : disposeFns.push(useResizeObserver(element, checkOverflow).stop)
57 : }
58 :
59 4029 : return {
60 : isOverflowing: readonly(isOverflowing),
61 : disposed: readonly(disposed),
62 : checkOverflow,
63 : dispose: () => {
64 72 : disposed.value = true
65 72 : disposeFns.forEach((fn) => fn())
66 : }
67 : }
68 : }
|