-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathchunked.js
97 lines (83 loc) · 2.48 KB
/
chunked.js
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
import { renderToString } from '../index.js';
import { CHILD_DID_SUSPEND, COMPONENT, PARENT } from './constants.js';
import { Deferred } from './util.js';
import { createInitScript, createSubtree } from './client.js';
/**
* @param {VNode} vnode
* @param {RenderToChunksOptions} options
* @returns {Promise<void>}
*/
export async function renderToChunks(vnode, { context, onWrite, abortSignal }) {
context = context || {};
/** @type {RendererState} */
const renderer = {
start: Date.now(),
abortSignal,
onWrite,
onError: handleError,
suspended: []
};
// Synchronously render the shell
// @ts-ignore - using third internal RendererState argument
const shell = renderToString(vnode, context, renderer);
onWrite(shell);
// Wait for any suspended sub-trees if there are any
const len = renderer.suspended.length;
if (len > 0) {
onWrite('<div hidden>');
onWrite(createInitScript(len));
// We should keep checking all promises
await forkPromises(renderer);
onWrite('</div>');
}
}
async function forkPromises(renderer) {
if (renderer.suspended.length > 0) {
const suspensions = [...renderer.suspended];
await Promise.all(renderer.suspended.map((s) => s.promise));
renderer.suspended = renderer.suspended.filter(
(s) => !suspensions.includes(s)
);
await forkPromises(renderer);
}
}
/** @type {RendererErrorHandler} */
function handleError(error, vnode, renderChild) {
if (!error || !error.then) return;
// walk up to the Suspense boundary
while ((vnode = vnode[PARENT])) {
let component = vnode[COMPONENT];
if (component && component[CHILD_DID_SUSPEND]) {
break;
}
}
if (!vnode) return;
const id = vnode.__v;
const found = this.suspended.find((x) => x.id === id);
const race = new Deferred();
const abortSignal = this.abortSignal;
if (abortSignal) {
// @ts-ignore 2554 - implicit undefined arg
if (abortSignal.aborted) race.resolve();
else abortSignal.addEventListener('abort', race.resolve);
}
const promise = error.then(
() => {
if (abortSignal && abortSignal.aborted) return;
const child = renderChild(vnode.props.children);
if (child) this.onWrite(createSubtree(id, child));
},
// TODO: Abort and send hydration code snippet to client
// to attempt to recover during hydration
this.onError
);
this.suspended.push({
id,
vnode,
promise: Promise.race([promise, race.promise])
});
const fallback = renderChild(vnode.props.fallback);
return found
? ''
: `<!--preact-island:${id}-->${fallback}<!--/preact-island:${id}-->`;
}