-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathindex.tsx
More file actions
203 lines (176 loc) · 4.65 KB
/
index.tsx
File metadata and controls
203 lines (176 loc) · 4.65 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import * as React from "react";
import { isBrowser, isDev } from "./constants.macro";
export type LazyProps = {
ssrOnly?: boolean;
whenIdle?: boolean;
whenVisible?: boolean | IntersectionObserverInit;
noWrapper?: boolean | keyof JSX.IntrinsicElements;
didHydrate?: VoidFunction;
promise?: Promise<any>;
on?: (keyof HTMLElementEventMap)[] | keyof HTMLElementEventMap;
children: React.ReactElement;
};
type Props = Omit<React.HTMLProps<HTMLElement>, "dangerouslySetInnerHTML"> &
LazyProps;
type VoidFunction = () => void;
// React currently throws a warning when using useLayoutEffect on the server.
const useIsomorphicLayoutEffect = isBrowser
? React.useLayoutEffect
: React.useEffect;
function reducer() {
return true;
}
// find a visible node to observe
// NOTE: this just checks the first child at each level
function getFirstVisibleChild(el) {
const child = el.firstElementChild;
if (child) {
const style = getComputedStyle(child);
// element might contain visible children
if (!["contents"].includes(style.display)) {
return child;
}
return getFirstVisibleChild(child);
}
return child;
}
function LazyHydrate(props: Props) {
const childRef = React.useRef<HTMLElement>(null);
// Always render on server
const [hydrated, hydrate] = React.useReducer(reducer, !isBrowser);
const {
noWrapper,
ssrOnly,
whenIdle,
whenVisible,
promise, // pass a promise which hydrates
on = [],
children,
didHydrate, // callback for hydration
...rest
} = props;
if (
isDev &&
!ssrOnly &&
!whenIdle &&
!whenVisible &&
!on.length &&
!promise
) {
console.error(
`LazyHydration: Enable atleast one trigger for hydration.\n` +
`If you don't want to hydrate, use ssrOnly`
);
}
useIsomorphicLayoutEffect(() => {
// No SSR Content
if (!childRef.current.hasChildNodes()) {
hydrate();
}
}, []);
React.useEffect(() => {
if (hydrated && didHydrate) {
didHydrate();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hydrated]);
React.useEffect(() => {
if (ssrOnly || hydrated) return;
const rootElement = childRef.current;
const cleanupFns: VoidFunction[] = [];
function cleanup() {
cleanupFns.forEach(fn => {
fn();
});
}
if (promise) {
promise.then(hydrate, hydrate);
}
if (whenVisible) {
const element = noWrapper
? rootElement
: // As root node does not have any box model, it cannot intersect.
getFirstVisibleChild(rootElement);
if (element && typeof IntersectionObserver !== "undefined") {
const observerOptions =
typeof whenVisible === "object"
? whenVisible
: {
rootMargin: "250px"
};
const io = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting || entry.intersectionRatio > 0) {
hydrate();
}
});
}, observerOptions);
io.observe(element);
cleanupFns.push(() => {
io.disconnect();
});
} else {
return hydrate();
}
}
if (whenIdle) {
// @ts-ignore
if (typeof requestIdleCallback !== "undefined") {
// @ts-ignore
const idleCallbackId = requestIdleCallback(hydrate, { timeout: 500 });
cleanupFns.push(() => {
// @ts-ignore
cancelIdleCallback(idleCallbackId);
});
} else {
const id = setTimeout(hydrate, 2000);
cleanupFns.push(() => {
clearTimeout(id);
});
}
}
const events = ([] as Array<keyof HTMLElementEventMap>).concat(on);
events.forEach(event => {
rootElement.addEventListener(event, hydrate, {
once: true,
passive: true
});
cleanupFns.push(() => {
rootElement.removeEventListener(event, hydrate, {});
});
});
return cleanup;
}, [
hydrated,
on,
ssrOnly,
whenIdle,
whenVisible,
didHydrate,
promise,
noWrapper
]);
const WrapperElement = ((typeof noWrapper === "string"
? noWrapper
: "div") as unknown) as React.FC<React.HTMLProps<HTMLElement>>;
if (hydrated) {
if (noWrapper) {
return children;
}
return (
<WrapperElement ref={childRef} style={{ display: "contents" }} {...rest}>
{children}
</WrapperElement>
);
} else {
return (
<WrapperElement
{...rest}
ref={childRef}
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: "" }}
/>
);
}
}
export default LazyHydrate;