forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseElementSize.ts
More file actions
99 lines (78 loc) · 2.4 KB
/
useElementSize.ts
File metadata and controls
99 lines (78 loc) · 2.4 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { isRef, type MaybeRef, onMounted, onUnmounted, ref, unref, watch } from 'vue'
import { useDebounceFn } from './useDebounce'
type Options = {
debounce?: number
}
type Target = MaybeRef<Element | null | undefined> | string
export function useElementSize(target: Target, options?: Options) {
const { debounce = 0 } = options ?? {}
const width = ref(0)
const height = ref(0)
let observer: ResizeObserver | undefined
const getTargetElement = (): Element | null => {
const el = unref(target) ?? null
if (typeof el === 'string') {
return document.querySelector(el)
}
return el
}
const updateSize = (entry: ResizeObserverEntry) => {
if (entry.contentBoxSize?.[0]) {
width.value = entry.contentBoxSize[0].inlineSize
height.value = entry.contentBoxSize[0].blockSize
} else {
// fallback
width.value = entry.contentRect.width
height.value = entry.contentRect.height
}
}
const debouncedUpdateSize = useDebounceFn(
(entry: ResizeObserverEntry) => updateSize(entry),
debounce
)
const handleResize: ResizeObserverCallback = (entries: ResizeObserverEntry[]) => {
const entry = entries[0]
if (!entry) return
if (debounce > 0) {
debouncedUpdateSize(entry)
} else {
updateSize(entry)
}
}
const start = () => {
if (observer) return
const element = getTargetElement()
if (!element) {
console.warn('useElementSize: target element not found')
return
}
try {
observer = new ResizeObserver(handleResize)
observer.observe(element, { box: 'content-box' })
} catch (error) {
console.error('useElementSize: filed to create observer', error)
}
}
const stop = () => {
if (!observer) return
observer.disconnect()
observer = undefined
}
onMounted(() => {
if (!isRef(target)) {
return start()
}
watch(
() => getTargetElement(),
(newEl, oldEl) => {
if (newEl && newEl !== oldEl) {
stop()
start()
}
},
{ immediate: true }
)
})
onUnmounted(stop)
return { width, height }
}