forked from gravity-ui/uikit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseElementSize.ts
72 lines (60 loc) · 2.27 KB
/
useElementSize.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
69
70
71
72
import React from 'react';
import round from 'lodash/round';
import throttle from 'lodash/throttle';
const RESIZE_THROTTLE = 16;
const ROUND_PRECISION = 2;
export interface UseElementSizeResult {
width: number;
height: number;
}
export function useElementSize<T extends HTMLElement = HTMLDivElement>(
ref: React.MutableRefObject<T | null> | null,
// can be used, when it is needed to force reassign observer to element
// in order to get correct measures. might be related to below
// https://github.com/WICG/resize-observer/issues/65
key?: string,
) {
const [size, setSize] = React.useState<UseElementSizeResult>({
width: 0,
height: 0,
});
React.useLayoutEffect(() => {
const element = ref?.current;
if (!element) {
return undefined;
}
setSize({
width: round(element.offsetWidth, ROUND_PRECISION),
height: round(element.offsetHeight, ROUND_PRECISION),
});
const handleResize: ResizeObserverCallback = (entries) => {
if (!Array.isArray(entries)) {
return;
}
const entry = entries[0];
if (entry.borderBoxSize) {
const borderBoxSize = entry.borderBoxSize[0]
? entry.borderBoxSize[0]
: (entry.borderBoxSize as unknown as ResizeObserverSize);
// ...but old versions of Firefox treat it as a single item
// https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html#L88
setSize({
width: round(borderBoxSize.inlineSize, ROUND_PRECISION),
height: round(borderBoxSize.blockSize, ROUND_PRECISION),
});
} else {
const target = entry.target as HTMLElement;
setSize({
width: round(target.offsetWidth, ROUND_PRECISION),
height: round(target.offsetHeight, ROUND_PRECISION),
});
}
};
const observer = new ResizeObserver(throttle(handleResize, RESIZE_THROTTLE));
observer.observe(element);
return () => {
observer.disconnect();
};
}, [ref, key]);
return size;
}