-
Notifications
You must be signed in to change notification settings - Fork 17
/
TabPanel.tsx
62 lines (52 loc) · 1.47 KB
/
TabPanel.tsx
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
import * as React from "react";
function wait(fn: () => void, ms?: number): () => void {
if (!ms && "requestIdleCallback" in window) {
const ref = requestIdleCallback(fn);
return () => cancelIdleCallback(ref);
}
const ref = setTimeout(fn, ms);
return () => clearTimeout(ref);
}
export function TabPanel({
children,
render = "idle",
unmount = "never",
...props
}: React.HTMLAttributes<HTMLDivElement> & {
hidden: boolean;
} & (
| {
render?: "idle";
unmount?: "never" | number;
}
| {
render?: "lazy";
unmount?: "idle" | "never" | number;
}
)) {
const [shouldRender, setShouldRender] = React.useState(!props.hidden);
const renderRef = React.useRef<() => void>();
const unmountRef = React.useRef<() => void>();
React.useEffect(() => {
if (!props.hidden) {
setShouldRender(true);
} else if (render === "idle") {
renderRef.current = wait(() => setShouldRender(true));
} else if (unmount === "idle") {
unmountRef.current = wait(() => setShouldRender(false));
}
if (typeof unmount === "number") {
unmountRef.current = wait(
() => setShouldRender(!props.hidden),
unmount * 1000
);
}
return () => {
renderRef.current?.();
renderRef.current = undefined;
unmountRef.current?.();
unmountRef.current = undefined;
};
}, [props.hidden, render, unmount]);
return <div {...props}>{shouldRender ? children : null}</div>;
}