Skip to content

Commit

Permalink
Suspensey commits in prerendered trees
Browse files Browse the repository at this point in the history
Prerendering a tree (i.e. with Offscreen) should not suspend the commit
phase, because the content is not yet visible. However, when revealing
a prerendered tree, we should suspend the commit phase if resources in
the prerendered tree haven't finished loading yet.

To do this properly, we need to visit all the visible nodes in the tree
that might possibly suspend. This includes nodes in the current tree,
because even though they were already "mounted", the resources might not
have loaded yet, because we didn't suspend when it was prerendered.

We will need to add this capability to the Offscreen component's
"manual" mode, too. Something like a `ready()` method that returns a
promise that resolves when the tree has fully loaded.
  • Loading branch information
acdlite committed Mar 26, 2023
1 parent 3646fa3 commit 907852c
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 27 deletions.
23 changes: 18 additions & 5 deletions packages/react-dom/src/__tests__/ReactDOMFloat-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2939,7 +2939,6 @@ body {
);
});

// @gate TODO
it('can interrupt a suspended commit with a new update', async () => {
function App({children}) {
return (
Expand All @@ -2949,9 +2948,13 @@ body {
);
}
const root = ReactDOMClient.createRoot(document);

// Do an initial render. This means subsequent insertions will suspend,
// unless they are wrapped inside a fresh Suspense boundary.
root.render(<App />);
await waitForAll([]);

// Insert a stylesheet. This will suspend because it's a transition.
React.startTransition(() => {
root.render(
<App>
Expand All @@ -2961,6 +2964,7 @@ body {
);
});
await waitForAll([]);
// Although the commit suspended, a preload was inserted.
expect(getMeaningfulChildren(document)).toEqual(
<html>
<head>
Expand All @@ -2970,6 +2974,9 @@ body {
</html>,
);

// Before the stylesheet has loaded, do an urgent update. This will insert a
// different stylesheet, and cancel the first one. This stylesheet will not
// suspend, even though it hasn't loaded, because it's an urgent update.
root.render(
<App>
hello2
Expand All @@ -2978,6 +2985,9 @@ body {
</App>,
);
await waitForAll([]);

// The bar stylesheet was inserted. There's still a "foo" preload, even
// though that update was superseded.
expect(getMeaningfulChildren(document)).toEqual(
<html>
<head>
Expand All @@ -2989,9 +2999,10 @@ body {
</html>,
);

// Even though foo was preloaded we don't see the stylesheet insert because the commit was cancelled.
// If we do a followup render that tries to recommit that resource it will insert right away because
// the preload is already loaded
// When "foo" finishes loading, nothing happens, because "foo" was not
// included in the last root update. However, if we insert "foo" again
// later, it should immediately commit without suspending, because it's
// been preloaded.
loadPreloads(['foo']);
assertLog(['load preload: foo']);
expect(getMeaningfulChildren(document)).toEqual(
Expand All @@ -3005,6 +3016,7 @@ body {
</html>,
);

// Now insert "foo" again.
React.startTransition(() => {
root.render(
<App>
Expand All @@ -3015,6 +3027,7 @@ body {
);
});
await waitForAll([]);
// Commits without suspending because "foo" was preloaded.
expect(getMeaningfulChildren(document)).toEqual(
<html>
<head>
Expand All @@ -3023,7 +3036,7 @@ body {
<link rel="preload" href="foo" as="style" />
<link rel="preload" href="bar" as="style" />
</head>
<body>hello2</body>
<body>hello3</body>
</html>,
);

Expand Down
47 changes: 41 additions & 6 deletions packages/react-reconciler/src/ReactFiberCommitWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ import {
LayoutMask,
PassiveMask,
Visibility,
SuspenseyCommit,
ShouldSuspendCommit,
MaySuspendCommit,
} from './ReactFiberFlags';
import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
import {
Expand Down Expand Up @@ -4065,12 +4066,23 @@ export function commitPassiveUnmountEffects(finishedWork: Fiber): void {
resetCurrentDebugFiberInDEV();
}

// If we're inside a brand new tree, or a tree that was already visible, then we
// should only suspend host components that have a ShouldSuspendCommit flag.
// Components without it haven't changed since the last commit, so we can skip
// over those.
//
// When we enter a tree that is being revealed (going from hidden -> visible),
// we need to suspend _any_ component that _may_ suspend. Even if they're
// already in the "current" tree. Because their visibility has changed, the
// browser may not have prerendered them yet. So we check the MaySuspendCommit
// flag instead.
let suspenseyCommitFlag = ShouldSuspendCommit;
export function accumulateSuspenseyCommit(finishedWork: Fiber): void {
accumulateSuspenseyCommitOnFiber(finishedWork);
}

function recursivelyAccumulateSuspenseyCommit(parentFiber: Fiber): void {
if (parentFiber.subtreeFlags & SuspenseyCommit) {
if (parentFiber.subtreeFlags & suspenseyCommitFlag) {
let child = parentFiber.child;
while (child !== null) {
accumulateSuspenseyCommitOnFiber(child);
Expand All @@ -4083,7 +4095,7 @@ function accumulateSuspenseyCommitOnFiber(fiber: Fiber) {
switch (fiber.tag) {
case HostHoistable: {
recursivelyAccumulateSuspenseyCommit(fiber);
if (fiber.flags & SuspenseyCommit) {
if (fiber.flags & suspenseyCommitFlag) {
if (fiber.memoizedState !== null) {
suspendResource(
// This should always be set by visiting HostRoot first
Expand All @@ -4101,7 +4113,7 @@ function accumulateSuspenseyCommitOnFiber(fiber: Fiber) {
}
case HostComponent: {
recursivelyAccumulateSuspenseyCommit(fiber);
if (fiber.flags & SuspenseyCommit) {
if (fiber.flags & suspenseyCommitFlag) {
const type = fiber.type;
const props = fiber.memoizedProps;
suspendInstance(type, props);
Expand All @@ -4117,10 +4129,33 @@ function accumulateSuspenseyCommitOnFiber(fiber: Fiber) {

recursivelyAccumulateSuspenseyCommit(fiber);
currentHoistableRoot = previousHoistableRoot;
break;
} else {
recursivelyAccumulateSuspenseyCommit(fiber);
}
break;
}
case OffscreenComponent: {
const isHidden = (fiber.memoizedState: OffscreenState | null) !== null;
if (isHidden) {
// Don't suspend in hidden trees
} else {
const current = fiber.alternate;
const wasHidden =
current !== null &&
(current.memoizedState: OffscreenState | null) !== null;
if (wasHidden) {
// This tree is being revealed. Visit all newly visible suspensey
// instances, even if they're in the current tree.
const prevFlags = suspenseyCommitFlag;
suspenseyCommitFlag = MaySuspendCommit;
recursivelyAccumulateSuspenseyCommit(fiber);
suspenseyCommitFlag = prevFlags;
} else {
recursivelyAccumulateSuspenseyCommit(fiber);
}
}
break;
}
// eslint-disable-next-line-no-fallthrough
default: {
recursivelyAccumulateSuspenseyCommit(fiber);
}
Expand Down
26 changes: 16 additions & 10 deletions packages/react-reconciler/src/ReactFiberCompleteWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ import {
MutationMask,
Passive,
ForceClientRender,
SuspenseyCommit,
MaySuspendCommit,
ScheduleRetry,
ShouldSuspendCommit,
} from './ReactFiberFlags';

import {
Expand Down Expand Up @@ -154,6 +155,7 @@ import {
getRenderTargetTime,
getWorkInProgressTransitions,
shouldRemainOnPreviousScreen,
getWorkInProgressRootRenderLanes,
} from './ReactFiberWorkLoop';
import {
OffscreenLane,
Expand Down Expand Up @@ -534,7 +536,7 @@ function preloadInstanceAndSuspendIfNeeded(
// return true, but if the renderer is reasonably confident that the
// underlying resource won't be evicted, it can return false as a
// performance optimization.
workInProgress.flags &= ~SuspenseyCommit;
workInProgress.flags &= ~MaySuspendCommit;
return;
}

Expand All @@ -543,7 +545,7 @@ function preloadInstanceAndSuspendIfNeeded(
// currently. We use this when revealing a prerendered tree, because
// even though the tree has "mounted", its resources might not have
// loaded yet.
workInProgress.flags |= SuspenseyCommit;
workInProgress.flags |= MaySuspendCommit;

// Check if we're rendering at a "non-urgent" priority. This is the same
// check that `useDeferredValue` does to determine whether it needs to
Expand All @@ -558,7 +560,8 @@ function preloadInstanceAndSuspendIfNeeded(
// a previous render.
// TODO: We may decide to expose a way to force a fallback even during a
// sync update.
if (!includesOnlyNonUrgentLanes(renderLanes)) {
const rootRenderLanes = getWorkInProgressRootRenderLanes();
if (!includesOnlyNonUrgentLanes(rootRenderLanes)) {
// This is an urgent render. Don't suspend or show a fallback. Also,
// there's no need to preload, because we're going to commit this
// synchronously anyway.
Expand All @@ -572,7 +575,9 @@ function preloadInstanceAndSuspendIfNeeded(
const isReady = preloadInstance(type, props);
if (!isReady) {
if (shouldRemainOnPreviousScreen()) {
// It's OK to suspend. Continue rendering.
// It's OK to suspend. Mark the fiber so we know to suspend before the
// commit phase. Then continue rendering.
workInProgress.flags |= ShouldSuspendCommit;
} else {
// Trigger a fallback rather than block the render.
suspendCommit();
Expand All @@ -590,19 +595,20 @@ function preloadResourceAndSuspendIfNeeded(
) {
// This is a fork of preloadInstanceAndSuspendIfNeeded, but for resources.
if (!mayResourceSuspendCommit(resource)) {
workInProgress.flags &= ~SuspenseyCommit;
workInProgress.flags &= ~MaySuspendCommit;
return;
}

workInProgress.flags |= SuspenseyCommit;
workInProgress.flags |= MaySuspendCommit;

if (!includesOnlyNonUrgentLanes(renderLanes)) {
const rootRenderLanes = getWorkInProgressRootRenderLanes();
if (!includesOnlyNonUrgentLanes(rootRenderLanes)) {
// This is an urgent render. Don't suspend or show a fallback.
} else {
const isReady = preloadResource(resource);
if (!isReady) {
if (shouldRemainOnPreviousScreen()) {
// It's OK to suspend. Continue rendering.
workInProgress.flags |= ShouldSuspendCommit;
} else {
suspendCommit();
}
Expand Down Expand Up @@ -1127,7 +1133,7 @@ function completeWork(

bubbleProperties(workInProgress);
if (nextResource === currentResource) {
workInProgress.flags &= ~SuspenseyCommit;
workInProgress.flags &= ~MaySuspendCommit;
} else {
preloadResourceAndSuspendIfNeeded(
workInProgress,
Expand Down
7 changes: 4 additions & 3 deletions packages/react-reconciler/src/ReactFiberFlags.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ export const Passive = /* */ 0b0000000000000000100000000000
export const Visibility = /* */ 0b0000000000000010000000000000;
export const StoreConsistency = /* */ 0b0000000000000100000000000000;

// It's OK to reuse this bit because these flags are mutually exclusive for
// It's OK to reuse these bits because these flags are mutually exclusive for
// different fiber types. We should really be doing this for as many flags as
// possible, because we're about to run out of bits.
export const ScheduleRetry = StoreConsistency;
export const ShouldSuspendCommit = Visibility;

export const LifecycleEffectMask =
Passive | Update | Callback | Ref | Snapshot | StoreConsistency;
Expand All @@ -63,7 +64,7 @@ export const Forked = /* */ 0b0000000100000000000000000000
export const RefStatic = /* */ 0b0000001000000000000000000000;
export const LayoutStatic = /* */ 0b0000010000000000000000000000;
export const PassiveStatic = /* */ 0b0000100000000000000000000000;
export const SuspenseyCommit = /* */ 0b0001000000000000000000000000;
export const MaySuspendCommit = /* */ 0b0001000000000000000000000000;

// Flag used to identify newly inserted fibers. It isn't reset after commit unlike `Placement`.
export const PlacementDEV = /* */ 0b0010000000000000000000000000;
Expand Down Expand Up @@ -103,4 +104,4 @@ export const PassiveMask = Passive | Visibility | ChildDeletion;
// This allows certain concepts to persist without recalculating them,
// e.g. whether a subtree contains passive effects or portals.
export const StaticMask =
LayoutStatic | PassiveStatic | RefStatic | SuspenseyCommit;
LayoutStatic | PassiveStatic | RefStatic | MaySuspendCommit;
16 changes: 14 additions & 2 deletions packages/react-reconciler/src/ReactFiberWorkLoop.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ import {
addTransitionToLanesMap,
getTransitionsForLanes,
includesOnlyNonUrgentLanes,
includesSomeLane,
OffscreenLane,
} from './ReactFiberLane';
import {
DiscreteEventPriority,
Expand Down Expand Up @@ -1997,17 +1999,27 @@ export function shouldRemainOnPreviousScreen(): boolean {
// parent Suspense boundary, even outside a transition. Somehow. Otherwise,
// an uncached promise can fall into an infinite loop.
} else {
if (includesOnlyRetries(workInProgressRootRenderLanes)) {
if (
includesOnlyRetries(workInProgressRootRenderLanes) ||
// In this context, an OffscreenLane counts as a Retry
// TODO: It's become increasingly clear that Retries and Offscreen are
// deeply connected. They probably can be unified further.
includesSomeLane(workInProgressRootRenderLanes, OffscreenLane)
) {
// During a retry, we can suspend rendering if the nearest Suspense boundary
// is the boundary of the "shell", because we're guaranteed not to block
// any new content from appearing.
//
// The reason we must check if this is a retry is because it guarantees
// that suspending the work loop won't block an actual update, because
// retries don't "update" anything; they fill in fallbacks that were left
// behind by a previous transition.
return handler === getShellBoundary();
}
}

// For all other Lanes besides Transitions and Retries, we should not wait
// for the data to load.
// TODO: We should wait during Offscreen prerendering, too.
return false;
}

Expand Down
Loading

0 comments on commit 907852c

Please sign in to comment.