From 907852cad8422126f56bfbd44bc9d5dbaabf8306 Mon Sep 17 00:00:00 2001 From: Andrew Clark Date: Mon, 20 Mar 2023 00:54:43 -0400 Subject: [PATCH] Suspensey commits in prerendered trees 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. --- .../src/__tests__/ReactDOMFloat-test.js | 23 +++++-- .../src/ReactFiberCommitWork.js | 47 +++++++++++-- .../src/ReactFiberCompleteWork.js | 26 ++++--- .../react-reconciler/src/ReactFiberFlags.js | 7 +- .../src/ReactFiberWorkLoop.js | 16 ++++- .../ReactSuspenseyCommitPhase-test.js | 68 ++++++++++++++++++- 6 files changed, 160 insertions(+), 27 deletions(-) diff --git a/packages/react-dom/src/__tests__/ReactDOMFloat-test.js b/packages/react-dom/src/__tests__/ReactDOMFloat-test.js index 7c9e3e75dc533..5bdca5d43f1f8 100644 --- a/packages/react-dom/src/__tests__/ReactDOMFloat-test.js +++ b/packages/react-dom/src/__tests__/ReactDOMFloat-test.js @@ -2939,7 +2939,6 @@ body { ); }); - // @gate TODO it('can interrupt a suspended commit with a new update', async () => { function App({children}) { return ( @@ -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(); await waitForAll([]); + // Insert a stylesheet. This will suspend because it's a transition. React.startTransition(() => { root.render( @@ -2961,6 +2964,7 @@ body { ); }); await waitForAll([]); + // Although the commit suspended, a preload was inserted. expect(getMeaningfulChildren(document)).toEqual( @@ -2970,6 +2974,9 @@ body { , ); + // 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( hello2 @@ -2978,6 +2985,9 @@ body { , ); await waitForAll([]); + + // The bar stylesheet was inserted. There's still a "foo" preload, even + // though that update was superseded. expect(getMeaningfulChildren(document)).toEqual( @@ -2989,9 +2999,10 @@ body { , ); - // 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( @@ -3005,6 +3016,7 @@ body { , ); + // Now insert "foo" again. React.startTransition(() => { root.render( @@ -3015,6 +3027,7 @@ body { ); }); await waitForAll([]); + // Commits without suspending because "foo" was preloaded. expect(getMeaningfulChildren(document)).toEqual( @@ -3023,7 +3036,7 @@ body { - hello2 + hello3 , ); diff --git a/packages/react-reconciler/src/ReactFiberCommitWork.js b/packages/react-reconciler/src/ReactFiberCommitWork.js index af086895f3559..18d36674bc27c 100644 --- a/packages/react-reconciler/src/ReactFiberCommitWork.js +++ b/packages/react-reconciler/src/ReactFiberCommitWork.js @@ -94,7 +94,8 @@ import { LayoutMask, PassiveMask, Visibility, - SuspenseyCommit, + ShouldSuspendCommit, + MaySuspendCommit, } from './ReactFiberFlags'; import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; import { @@ -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); @@ -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 @@ -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); @@ -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); } diff --git a/packages/react-reconciler/src/ReactFiberCompleteWork.js b/packages/react-reconciler/src/ReactFiberCompleteWork.js index 03890f516ba8b..870fdac06fcf4 100644 --- a/packages/react-reconciler/src/ReactFiberCompleteWork.js +++ b/packages/react-reconciler/src/ReactFiberCompleteWork.js @@ -87,8 +87,9 @@ import { MutationMask, Passive, ForceClientRender, - SuspenseyCommit, + MaySuspendCommit, ScheduleRetry, + ShouldSuspendCommit, } from './ReactFiberFlags'; import { @@ -154,6 +155,7 @@ import { getRenderTargetTime, getWorkInProgressTransitions, shouldRemainOnPreviousScreen, + getWorkInProgressRootRenderLanes, } from './ReactFiberWorkLoop'; import { OffscreenLane, @@ -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; } @@ -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 @@ -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. @@ -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(); @@ -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(); } @@ -1127,7 +1133,7 @@ function completeWork( bubbleProperties(workInProgress); if (nextResource === currentResource) { - workInProgress.flags &= ~SuspenseyCommit; + workInProgress.flags &= ~MaySuspendCommit; } else { preloadResourceAndSuspendIfNeeded( workInProgress, diff --git a/packages/react-reconciler/src/ReactFiberFlags.js b/packages/react-reconciler/src/ReactFiberFlags.js index c37a648973ef0..5febfa3d528dd 100644 --- a/packages/react-reconciler/src/ReactFiberFlags.js +++ b/packages/react-reconciler/src/ReactFiberFlags.js @@ -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; @@ -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; @@ -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; diff --git a/packages/react-reconciler/src/ReactFiberWorkLoop.js b/packages/react-reconciler/src/ReactFiberWorkLoop.js index e00d63769062e..14a1d9a4ddf1a 100644 --- a/packages/react-reconciler/src/ReactFiberWorkLoop.js +++ b/packages/react-reconciler/src/ReactFiberWorkLoop.js @@ -169,6 +169,8 @@ import { addTransitionToLanesMap, getTransitionsForLanes, includesOnlyNonUrgentLanes, + includesSomeLane, + OffscreenLane, } from './ReactFiberLane'; import { DiscreteEventPriority, @@ -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; } diff --git a/packages/react-reconciler/src/__tests__/ReactSuspenseyCommitPhase-test.js b/packages/react-reconciler/src/__tests__/ReactSuspenseyCommitPhase-test.js index 4acdc339e04c8..bbd2ae8c2edcb 100644 --- a/packages/react-reconciler/src/__tests__/ReactSuspenseyCommitPhase-test.js +++ b/packages/react-reconciler/src/__tests__/ReactSuspenseyCommitPhase-test.js @@ -4,7 +4,9 @@ let ReactNoop; let resolveSuspenseyThing; let getSuspenseyThingStatus; let Suspense; +let Offscreen; let SuspenseList; +let useMemo; let Scheduler; let act; let assertLog; @@ -18,10 +20,11 @@ describe('ReactSuspenseyCommitPhase', () => { ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); Suspense = React.Suspense; - SuspenseList = React.SuspenseList; if (gate(flags => flags.enableSuspenseList)) { SuspenseList = React.SuspenseList; } + Offscreen = React.unstable_Offscreen; + useMemo = React.useMemo; startTransition = React.startTransition; resolveSuspenseyThing = ReactNoop.resolveSuspenseyThing; getSuspenseyThingStatus = ReactNoop.getSuspenseyThingStatus; @@ -279,4 +282,67 @@ describe('ReactSuspenseyCommitPhase', () => { , ); }); + + // @gate enableOffscreen + test("host instances don't suspend during prerendering, but do suspend when they are revealed", async () => { + function More() { + Scheduler.log('More'); + return ; + } + + function Details({showMore}) { + Scheduler.log('Details'); + const more = useMemo(() => , []); + return ( + <> +
Main Content
+ {more} + + ); + } + + const root = ReactNoop.createRoot(); + await act(async () => { + root.render(
); + // First render the outer component, without the hidden content + await waitForPaint(['Details']); + expect(root).toMatchRenderedOutput(
Main Content
); + }); + // Then prerender the hidden content. + assertLog(['More', 'Image requested [More]']); + // The prerender should commit even though the image is still loading, + // because it's hidden. + expect(root).toMatchRenderedOutput( + <> +
Main Content
+