-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathuseHeights.tsx
More file actions
69 lines (58 loc) · 1.94 KB
/
Copy pathuseHeights.tsx
File metadata and controls
69 lines (58 loc) · 1.94 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
import * as React from 'react';
import { useRef, useEffect } from 'react';
import findDOMNode from 'rc-util/lib/Dom/findDOMNode';
import raf from 'rc-util/lib/raf';
import type { GetKey } from '../interface';
import CacheMap from '../utils/CacheMap';
import { getOuterHeight } from '../utils/outerHeight';
export default function useHeights<T>(
getKey: GetKey<T>,
onItemAdd?: (item: T) => void,
onItemRemove?: (item: T) => void,
): [(item: T, instance: HTMLElement) => void, () => void, CacheMap, number] {
const [updatedMark, setUpdatedMark] = React.useState(0);
const instanceRef = useRef(new Map<React.Key, HTMLElement>());
const heightsRef = useRef(new CacheMap());
const collectRafRef = useRef<number>();
function cancelRaf() {
raf.cancel(collectRafRef.current);
}
function collectHeight() {
cancelRaf();
collectRafRef.current = raf(() => {
instanceRef.current.forEach((element, key) => {
if (element && element.offsetParent) {
const htmlElement = findDOMNode<HTMLElement>(element);
const outerHeight = getOuterHeight(htmlElement)
if (heightsRef.current.get(key) !== outerHeight) {
heightsRef.current.set(key, outerHeight);
}
}
});
// Always trigger update mark to tell parent that should re-calculate heights when resized
setUpdatedMark((c) => c + 1);
});
}
function setInstanceRef(item: T, instance: HTMLElement) {
const key = getKey(item);
const origin = instanceRef.current.get(key);
if (instance) {
instanceRef.current.set(key, instance);
collectHeight();
} else {
instanceRef.current.delete(key);
}
// Instance changed
if (!origin !== !instance) {
if (instance) {
onItemAdd?.(item);
} else {
onItemRemove?.(item);
}
}
}
useEffect(() => {
return cancelRaf;
}, []);
return [setInstanceRef, collectHeight, heightsRef.current, updatedMark];
}