Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 122 additions & 5 deletions compat/src/suspense.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Component, Fragment, createElement, options } from 'preact';
import {
COMPONENT_FORCE,
MODE_HYDRATE,
MODE_SUSPENDED,
REF_DETACHED,
UNDEFINED,
VNODE_MARKER
Expand All @@ -15,10 +16,20 @@ function initSuspenseHooks() {
if (error && error.then) {
/** @type {import('./internal').Component} */
let component;
let vnode = newVNode;

while ((vnode = vnode._parent)) {
// Start at the vnode that threw: a boundary waiting to hydrate suspends itself
for (let vnode = newVNode; vnode; vnode = vnode._parent) {
if ((component = vnode._component) && component._childDidSuspend) {
// Below a boundary that is hydrating its server range, the
// boundary suspends instead, so the range stays intact
if (
component._excess &&
vnode != newVNode &&
newVNode._flags & MODE_SUSPENDED
) {
throw error;
}

// A component that suspends before ever committing has no state
// worth keeping; mounted ones keep their hooks while parked.
if (oldVNode && !oldVNode._component)
Expand All @@ -31,6 +42,30 @@ function initSuspenseHooks() {
oldCatchError(error, newVNode, oldVNode, errorInfo);
};

// Give a Suspense boundary the range the server marked for it: `$s=` has
// the content, `$s?id` is still streaming, `$s!` is left to the client.
options._claim = (component, nodes, cursor, end) => {
if (component._childDidSuspend) {
// Find the opening marker at or after the cursor
let i = nodes.indexOf(cursor),
range = [],
marker;
// (skipping the `$s` markers renderToStringAsync adds)
for (
i = i < 0 ? 0 : i;
(marker = nodes[i++]) === null ||
(marker && marker.nodeType > 6 && !/^\$s[=?!]/.test(marker.data));
);
if (marker && marker.nodeType == 8) {
// and its closer: content that doesn't hydrate is inserted before it
range.push((component._end = end((component._excess = marker), range)));
// Hide the range from the parent
nodes.fill(null, i - 1, i + range.length);
return range;
}
}
};

const oldUnmount = options.unmount;
options.unmount = vnode => {
/** @type {import('./internal').Component} */
Expand All @@ -43,8 +78,31 @@ function initSuspenseHooks() {
};
}

/** Detach a thrown away render from the server DOM it hydrated */
function discard(vnode, remove) {
if (vnode) {
// Portal DOM was created on the client
remove = remove || vnode.props._parentDom;
if (vnode._component) vnode._component._parentDom = null;
else if (vnode._dom) {
vnode._dom._listeners = null;
if (remove) vnode._dom.remove();
}
if (vnode._children) vnode._children.some(child => discard(child, remove));
}
}

function detachedClone(vnode, detachedParent, parentDom) {
if (vnode) {
// A boundary waiting to hydrate has nothing to park: drop its server
// range and mount it again on reveal
if (vnode._flags & MODE_SUSPENDED && vnode._component._childDidSuspend) {
const copy = assign({ constructor: VNODE_MARKER }, vnode);
vnode._component = vnode._dom = null;
vnode._flags &= ~MODE_SUSPENDED;
return copy;
}

const hooks = vnode._component && vnode._component.__hooks;
if (hooks) {
hooks._list.forEach(effect => {
Expand Down Expand Up @@ -155,8 +213,15 @@ function createSuspense() {
// Store and null _parentDom to prevent setState/forceUpdate from
// scheduling renders while suspended. Render would be a no-op anyway
// since process() checks _parentDom, but this avoids queue churn.
// A boundary waiting to hydrate suspends itself. Keep its _parentDom so
// onResolved knows it's mounted, and throw away its partial render.
const originalParentDom = suspendingComponent._parentDom;
suspendingComponent._parentDom = null;
if (suspendingComponent == this) {
discard(suspendingVNode);
this._parentDom = originalParentDom;
suspendingVNode._children = [];
}

const onSuspensionComplete = () => {
if (!--this._pendingSuspensionCount) {
Expand Down Expand Up @@ -193,7 +258,9 @@ function createSuspense() {
*/
if (
!this._pendingSuspensionCount++ &&
!(suspendingVNode._flags & MODE_HYDRATE)
!(suspendingVNode._flags & MODE_HYDRATE) &&
// A boundary waiting to hydrate keeps showing the server DOM
suspendingComponent != this
) {
this.setState({
_suspended: (this._detachOnNextRender = this._vnode._children[0])
Expand All @@ -202,6 +269,14 @@ function createSuspense() {
promise.then(onResolved, onResolved);
};

/**
* Ignore parent renders while waiting to hydrate, the retry uses forceUpdate()
* @this {import('./internal').SuspenseComponent}
*/
Suspense.prototype.shouldComponentUpdate = function () {
return !this._excess;
};

Suspense.prototype.componentWillUnmount = function () {
this._suspenders = [];
if (this.state._suspended) this._vnode._children[0] = this.state._suspended;
Expand All @@ -217,6 +292,48 @@ function createSuspense() {
// on when it resolves on the server or hydrates on the client.
this._mask || (this._mask = [useId(), 0]);

// Set while hydrating a server range
const marker = this._excess;
let fallback = state._suspended;
if (marker) {
// Restart useId numbering for this attempt
this._mask[1] = 0;

if (marker.data[2] == '?') {
// Wait for the chunk: the server script calls `__w` when it arrives.
// If nothing does (the chunk was cut off, or no script reaches the
// range), the document finishing loading ends the wait.
// (readyState 'loading')
if (marker.ownerDocument.readyState[0] == 'l') {
throw (
marker._promise ||
(marker._promise = new Promise(resolve =>
marker.ownerDocument.addEventListener(
'DOMContentLoaded',
(marker.__w = resolve)
)
))
);
}
// The document loaded without the chunk
marker.data = '$s!';
}

// `$s!`: hydrate the fallback, then render the content
fallback = marker.data[2] == '!';

// Remove the markers once hydrated (render callbacks also run after
// an sCU bailout, while still suspended)
this._renderCallbacks.push(() => {
if (this._excess && !(this._vnode._flags & MODE_SUSPENDED)) {
this._excess = null;
marker.remove();
(this._end || marker).remove();
if (fallback) this.forceUpdate();
}
});
}

if (this._detachOnNextRender) {
// When the Suspense's _vnode was created by a call to createVNode
// (i.e. due to a setState further up in the tree)
Expand All @@ -235,8 +352,8 @@ function createSuspense() {
}

return [
createElement(Fragment, null, state._suspended ? null : props.children),
state._suspended && createElement(Fragment, null, props.fallback)
createElement(Fragment, null, fallback ? null : props.children),
fallback && createElement(Fragment, null, props.fallback)
];
};

Expand Down
Loading