Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
79 changes: 79 additions & 0 deletions packages/react-devtools-shared/src/__tests__/store-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2696,4 +2696,83 @@ describe('Store', () => {
<ClientComponent key="D">
`);
});

// @reactVersion >= 18.0
it('can reconcile Suspense in fallback positions', async () => {
let resolveFallback;
const fallbackPromise = new Promise(resolve => {
resolveFallback = resolve;
});
let resolveContent;
const contentPromise = new Promise(resolve => {
resolveContent = resolve;
});

function Component({children, promise}) {
if (promise) {
React.use(promise);
}
return <div>{children}</div>;
}

await actAsync(() =>
render(
<React.Suspense
name="content"
fallback={
<React.Suspense
name="fallback"
fallback={
<Component key="fallback-fallback">
Loading fallback...
</Component>
}>
<Component key="fallback-content" promise={fallbackPromise}>
Loading...
</Component>
</React.Suspense>
}>
<Component key="content" promise={contentPromise}>
done
</Component>
</React.Suspense>,
),
);

expect(store).toMatchInlineSnapshot(`
[root]
▾ <Suspense name="content">
▾ <Suspense name="fallback">
<Component key="fallback-fallback">
[shell]
<Suspense name="content" rects={null}>
<Suspense name="fallback" rects={null}>
`);

await actAsync(() => {
resolveFallback();
});

expect(store).toMatchInlineSnapshot(`
[root]
▾ <Suspense name="content">
▾ <Suspense name="fallback">
<Component key="fallback-content">
[shell]
<Suspense name="content" rects={null}>
<Suspense name="fallback" rects={[{x:1,y:2,width:10,height:1}]}>
`);

await actAsync(() => {
resolveContent();
});

expect(store).toMatchInlineSnapshot(`
[root]
▾ <Suspense name="content">
<Component key="content">
[shell]
<Suspense name="content" rects={[{x:1,y:2,width:4,height:1}]}>
`);
});
});
104 changes: 94 additions & 10 deletions packages/react-devtools-shared/src/backend/fiber/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -4736,34 +4736,39 @@ export function attach(
);

shouldMeasureSuspenseNode = false;
if (nextFallbackFiber !== null) {
if (prevFallbackFiber !== null || nextFallbackFiber !== null) {
const fallbackStashedSuspenseParent = reconcilingParentSuspenseNode;
const fallbackStashedSuspensePrevious =
previouslyReconciledSiblingSuspenseNode;
const fallbackStashedSuspenseRemaining =
remainingReconcilingChildrenSuspenseNodes;
// Next, we'll pop back out of the SuspenseNode that we added above and now we'll
// reconcile the fallback, reconciling anything by inserting into the parent SuspenseNode.
// reconcile the fallback, reconciling anything in the context of the parent SuspenseNode.
// Since the fallback conceptually blocks the parent.
reconcilingParentSuspenseNode = stashedSuspenseParent;
previouslyReconciledSiblingSuspenseNode = stashedSuspensePrevious;
remainingReconcilingChildrenSuspenseNodes = stashedSuspenseRemaining;
try {
updateFlags |= updateVirtualChildrenRecursively(
nextFallbackFiber,
null,
prevFallbackFiber,
traceNearestHostComponentUpdate,
0,
);
if (nextFallbackFiber === null) {
unmountRemainingChildren();
} else {
updateFlags |= updateVirtualChildrenRecursively(
nextFallbackFiber,
null,
prevFallbackFiber,
traceNearestHostComponentUpdate,
0,
);
}
} finally {
reconcilingParentSuspenseNode = fallbackStashedSuspenseParent;
previouslyReconciledSiblingSuspenseNode =
fallbackStashedSuspensePrevious;
remainingReconcilingChildrenSuspenseNodes =
fallbackStashedSuspenseRemaining;
}
} else if (nextFiber.memoizedState === null) {
}
if (nextFiber.memoizedState === null) {
// Measure this Suspense node in case it changed. We don't update the rect while
// we're inside a disconnected subtree nor if we are the Suspense boundary that
// is suspended. This lets us keep the rectangle of the displayed content while
Expand Down Expand Up @@ -5268,6 +5273,18 @@ export function attach(
}
}

function getNearestSuspenseNode(instance: DevToolsInstance): SuspenseNode {
while (instance.suspenseNode === null) {
if (instance.parent === null) {
throw new Error(
'There should always be a SuspenseNode parent on a mounted instance.',
);
}
instance = instance.parent;
}
return instance.suspenseNode;
}

function getNearestMountedDOMNode(publicInstance: Element): null | Element {
let domNode: null | Element = publicInstance;
while (domNode && !publicInstanceToDevToolsInstanceMap.has(domNode)) {
Expand Down Expand Up @@ -5556,6 +5573,56 @@ export function attach(
return result;
}

const FALLBACK_THROTTLE_MS: number = 300;

function getSuspendedByRange(
suspenseNode: SuspenseNode,
): null | [number, number] {
let min = Infinity;
let max = -Infinity;
suspenseNode.suspendedBy.forEach((_, ioInfo) => {
if (ioInfo.end > max) {
max = ioInfo.end;
}
if (ioInfo.start < min) {
min = ioInfo.start;
}
});
const parentSuspenseNode = suspenseNode.parent;
if (parentSuspenseNode !== null) {
let parentMax = -Infinity;
parentSuspenseNode.suspendedBy.forEach((_, ioInfo) => {
if (ioInfo.end > parentMax) {
parentMax = ioInfo.end;
}
});
// The parent max is theoretically the earlier the parent could've committed.
// Therefore, the theoretical max that the child could be throttled is that plus 300ms.
const throttleTime = parentMax + FALLBACK_THROTTLE_MS;
if (throttleTime > max) {
// If the theoretical throttle time is later than the earliest reveal then we extend
// the max time to show that this is timespan could possibly get throttled.
max = throttleTime;
}

// We use the end of the previous boundary as the start time for this boundary unless,
// that's earlier than we'd need to expand to the full fallback throttle range. It
// suggests that the parent was loaded earlier than this one.
let startTime = max - FALLBACK_THROTTLE_MS;
if (parentMax > startTime) {
startTime = parentMax;
}
// If the first fetch of this boundary starts before that, then we use that as the start.
if (startTime < min) {
min = startTime;
}
}
if (min < Infinity && max > -Infinity) {
return [min, max];
}
return null;
}

function getAwaitStackFromHooks(
hooks: HooksTree,
asyncInfo: ReactAsyncInfo,
Expand Down Expand Up @@ -6009,6 +6076,11 @@ export function attach(
nativeTag = getNativeTag(fiber.stateNode);
}

let isSuspended: boolean | null = null;
if (tag === SuspenseComponent) {
isSuspended = memoizedState !== null;
}

const suspendedBy =
fiberInstance.suspenseNode !== null
? // If this is a Suspense boundary, then we include everything in the subtree that might suspend
Expand All @@ -6024,6 +6096,10 @@ export function attach(
: fiberInstance.suspendedBy.map(info =>
serializeAsyncInfo(info, fiberInstance, hooks),
);
const suspendedByRange = getSuspendedByRange(
getNearestSuspenseNode(fiberInstance),
);

return {
id: fiberInstance.id,

Expand Down Expand Up @@ -6055,6 +6131,7 @@ export function attach(
forceFallbackForFibers.has(fiber) ||
(fiber.alternate !== null &&
forceFallbackForFibers.has(fiber.alternate))),
isSuspended: isSuspended,

source,

Expand Down Expand Up @@ -6086,6 +6163,7 @@ export function attach(
: Array.from(componentLogsEntry.warnings.entries()),

suspendedBy: suspendedBy,
suspendedByRange: suspendedByRange,

// List of owners
owners,
Expand Down Expand Up @@ -6142,8 +6220,12 @@ export function attach(
const componentLogsEntry =
componentInfoToComponentLogsMap.get(componentInfo);

const isSuspended = null;
// Things that Suspended this Server Component (use(), awaits and direct child promises)
const suspendedBy = virtualInstance.suspendedBy;
const suspendedByRange = getSuspendedByRange(
getNearestSuspenseNode(virtualInstance),
);

return {
id: virtualInstance.id,
Expand All @@ -6160,6 +6242,7 @@ export function attach(
isErrored: false,

canToggleSuspense: supportsTogglingSuspense && hasSuspenseBoundary,
isSuspended: isSuspended,

source,

Expand Down Expand Up @@ -6196,6 +6279,7 @@ export function attach(
: suspendedBy.map(info =>
serializeAsyncInfo(info, virtualInstance, null),
),
suspendedByRange: suspendedByRange,

// List of owners
owners,
Expand Down
2 changes: 2 additions & 0 deletions packages/react-devtools-shared/src/backend/legacy/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,7 @@ export function attach(

// Suspense did not exist in legacy versions
canToggleSuspense: false,
isSuspended: null,

source: null,

Expand All @@ -858,6 +859,7 @@ export function attach(

// Not supported in legacy renderers.
suspendedBy: [],
suspendedByRange: null,

// List of owners
owners,
Expand Down
3 changes: 3 additions & 0 deletions packages/react-devtools-shared/src/backend/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,8 @@ export type InspectedElement = {

// Is this Suspense, and can its value be overridden now?
canToggleSuspense: boolean,
// If this Element is suspended. Currently only set on Suspense boundaries.
isSuspended: boolean | null,

// Does the component have legacy context attached to it.
hasLegacyContext: boolean,
Expand All @@ -300,6 +302,7 @@ export type InspectedElement = {

// Things that suspended this Instances
suspendedBy: Object, // DehydratedData or Array<SerializedAsyncInfo>
suspendedByRange: null | [number, number],

// List of owners
owners: Array<SerializedElement> | null,
Expand Down
4 changes: 4 additions & 0 deletions packages/react-devtools-shared/src/backendAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ export function convertInspectedElementBackendToFrontend(
canToggleError,
isErrored,
canToggleSuspense,
isSuspended,
hasLegacyContext,
id,
type,
Expand All @@ -270,6 +271,7 @@ export function convertInspectedElementBackendToFrontend(
errors,
warnings,
suspendedBy,
suspendedByRange,
nativeTag,
} = inspectedElementBackend;

Expand All @@ -286,6 +288,7 @@ export function convertInspectedElementBackendToFrontend(
canToggleError,
isErrored,
canToggleSuspense,
isSuspended,
hasLegacyContext,
id,
key,
Expand Down Expand Up @@ -313,6 +316,7 @@ export function convertInspectedElementBackendToFrontend(
hydratedSuspendedBy == null // backwards compat
? []
: hydratedSuspendedBy.map(backendToFrontendSerializedAsyncInfo),
suspendedByRange,
nativeTag,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export default function InspectedElementWrapper(_: Props): React.Node {
element !== null &&
element.type === ElementTypeSuspense &&
inspectedElement != null &&
inspectedElement.state != null;
inspectedElement.isSuspended;

const canToggleError =
!hideToggleErrorAction &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ export default function InspectedElementSuspendedBy({
inspectedElement,
store,
}: Props): React.Node {
const {suspendedBy} = inspectedElement;
const {suspendedBy, suspendedByRange} = inspectedElement;

// Skip the section if nothing suspended this component.
if (suspendedBy == null || suspendedBy.length === 0) {
Expand All @@ -306,6 +306,11 @@ export default function InspectedElementSuspendedBy({

let minTime = Infinity;
let maxTime = -Infinity;
if (suspendedByRange !== null) {
// The range of the whole suspense boundary.
minTime = suspendedByRange[0];
maxTime = suspendedByRange[1];
}
for (let i = 0; i < suspendedBy.length; i++) {
const asyncInfo: SerializedAsyncInfo = suspendedBy[i];
if (asyncInfo.awaited.start < minTime) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,13 @@ export default function InspectedElementSuspenseToggle({
}: Props): React.Node {
const {readOnly} = React.useContext(OptionsContext);

const {id, state, type} = inspectedElement;
const {id, isSuspended, type} = inspectedElement;
const canToggleSuspense = !readOnly && inspectedElement.canToggleSuspense;

if (type !== ElementTypeSuspense) {
return null;
}

const isSuspended = state !== null;

const toggleSuspense = (path: any, value: boolean) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID !== null) {
Expand Down
Loading
Loading