forked from TanStack/react-charts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseRect.ts
68 lines (54 loc) · 1.21 KB
/
useRect.ts
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
import React from 'react'
export default function useRect(
element: Element | null | undefined,
enabled: boolean
): DOMRect {
const rerender = React.useReducer(() => ({}), [])[1]
const rectRef = React.useRef<DOMRect>({
width: 0,
height: 0,
x: 0,
y: 0,
left: 0,
top: 0,
right: 0,
bottom: 0,
} as DOMRect)
const measure = React.useCallback(() => {
if (element) {
rectRef.current = element.getBoundingClientRect()
}
}, [element])
if (!rectRef.current) {
measure()
}
React.useEffect(() => {
if (!element || !enabled) {
return
}
const cb = () => {
measure()
rerender()
}
document.addEventListener('scroll', cb, true)
return () => {
document.removeEventListener('scroll', cb, true)
}
}, [element, enabled, measure, rerender])
React.useEffect(() => {
if (!element || !enabled) {
return
}
measure()
rerender()
const observer = new ResizeObserver(() => {
measure()
rerender()
})
observer.observe(element as Element)
return () => {
observer.unobserve(element as Element)
}
}, [element, enabled, measure, rerender])
return rectRef.current
}