Update on "[compiler] Fix error message for custom hooks"

We were printing "Custom" instead of "custom hook".

[ghstack-poisoned]
This commit is contained in:
Joe Savona committed 2025-05-19 15:14:49 -07:00
commit df38acf4cc
20 files changed
+1237 -157

No files matched your search

+7 -3
View File
@@ -1,8 +1,12 @@
import React, {Fragment, Suspense} from 'react';
import React, {
Fragment,
Suspense,
unstable_SuspenseList as SuspenseList,
} from 'react';
export default function LargeContent() {
return (
<Fragment>
<SuspenseList revealOrder="forwards">
<Suspense fallback={null}>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
@@ -286,6 +290,6 @@ export default function LargeContent() {
interdum a. Proin nec odio in nulla vestibulum.
</p>
</Suspense>
</Fragment>
</SuspenseList>
);
}
@@ -23,6 +23,8 @@ export default function render(url, res) {
const {pipe, abort} = renderToPipeableStream(
<App assets={assets} initialURL={url} />,
{
// TODO: Temporary hack. Detect from attributes instead.
bootstrapScriptContent: 'window._useVT = true;',
bootstrapScripts: [assets['main.js']],
onShellReady() {
// If something errored before we started streaming, we set the error code appropriately.
+25 -13
View File
@@ -8,6 +8,7 @@ import React, {
useId,
useOptimistic,
startTransition,
Suspense,
} from 'react';
import {createPortal} from 'react-dom';
@@ -60,6 +61,12 @@ function Id() {
return <span id={useId()} />;
}
let wait;
function Suspend() {
if (!wait) wait = sleep(500);
return React.use(wait);
}
export default function Page({url, navigate}) {
const [renderedUrl, optimisticNavigate] = useOptimistic(
url,
@@ -93,7 +100,7 @@ export default function Page({url, navigate}) {
// a flushSync will.
// Promise.resolve().then(() => {
// flushSync(() => {
setCounter(c => c + 10);
// setCounter(c => c + 10);
// });
// });
}, [show]);
@@ -193,18 +200,23 @@ export default function Page({url, navigate}) {
<div>!!</div>
</ViewTransition>
</Activity>
<p>these</p>
<p>rows</p>
<p>exist</p>
<p>to</p>
<p>test</p>
<p>scrolling</p>
<p>content</p>
<p>out</p>
<p>of</p>
{portal}
<p>the</p>
<p>viewport</p>
<Suspense fallback="Loading">
<ViewTransition>
<p>these</p>
<p>rows</p>
<p>exist</p>
<p>to</p>
<p>test</p>
<p>scrolling</p>
<p>content</p>
<p>out</p>
<p>of</p>
{portal}
<p>the</p>
<p>viewport</p>
<Suspend />
</ViewTransition>
</Suspense>
{show ? <Component /> : null}
</div>
</ViewTransition>
@@ -515,6 +515,22 @@ const tests = {
`,
options: [{additionalHooks: 'useCustomEffect'}],
},
{
// behaves like no deps
code: normalizeIndent`
function MyComponent(props) {
useSpecialEffect(() => {
console.log(props.foo);
}, null);
}
`,
options: [
{
additionalHooks: 'useSpecialEffect',
experimental_autoDependenciesHooks: ['useSpecialEffect'],
},
],
},
{
code: normalizeIndent`
function MyComponent(props) {
@@ -1470,6 +1486,38 @@ const tests = {
},
],
invalid: [
{
code: normalizeIndent`
function MyComponent(props) {
useSpecialEffect(() => {
console.log(props.foo);
}, null);
}
`,
options: [{additionalHooks: 'useSpecialEffect'}],
errors: [
{
message:
"React Hook useSpecialEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies.",
},
{
message:
"React Hook useSpecialEffect has a missing dependency: 'props.foo'. Either include it or remove the dependency array.",
suggestions: [
{
desc: 'Update the dependencies array to be: [props.foo]',
output: normalizeIndent`
function MyComponent(props) {
useSpecialEffect(() => {
console.log(props.foo);
}, [props.foo]);
}
`,
},
],
},
],
},
{
code: normalizeIndent`
function MyComponent(props) {
@@ -7821,6 +7869,24 @@ const testsTypescript = {
}
`,
},
{
code: normalizeIndent`
function MyComponent() {
const [state, setState] = React.useState<number>(0);
useSpecialEffect(() => {
const someNumber: typeof state = 2;
setState(prevState => prevState + someNumber);
})
}
`,
options: [
{
additionalHooks: 'useSpecialEffect',
experimental_autoDependenciesHooks: ['useSpecialEffect'],
},
],
},
{
code: normalizeIndent`
function App() {
@@ -8176,6 +8242,48 @@ const testsTypescript = {
function MyComponent() {
const [state, setState] = React.useState<number>(0);
useSpecialEffect(() => {
const someNumber: typeof state = 2;
setState(prevState => prevState + someNumber + state);
}, [])
}
`,
options: [
{
additionalHooks: 'useSpecialEffect',
experimental_autoDependenciesHooks: ['useSpecialEffect'],
},
],
errors: [
{
message:
"React Hook useSpecialEffect has a missing dependency: 'state'. " +
'Either include it or remove the dependency array. ' +
`You can also do a functional update 'setState(s => ...)' ` +
`if you only need 'state' in the 'setState' call.`,
suggestions: [
{
desc: 'Update the dependencies array to be: [state]',
output: normalizeIndent`
function MyComponent() {
const [state, setState] = React.useState<number>(0);
useSpecialEffect(() => {
const someNumber: typeof state = 2;
setState(prevState => prevState + someNumber + state);
}, [state])
}
`,
},
],
},
],
},
{
code: normalizeIndent`
function MyComponent() {
const [state, setState] = React.useState<number>(0);
useMemo(() => {
const someNumber: typeof state = 2;
console.log(someNumber);
@@ -61,27 +61,38 @@ const rule = {
enableDangerousAutofixThisMayCauseInfiniteLoops: {
type: 'boolean',
},
experimental_autoDependenciesHooks: {
type: 'array',
items: {
type: 'string',
},
},
},
},
],
},
create(context: Rule.RuleContext) {
const rawOptions = context.options && context.options[0];
// Parse the `additionalHooks` regex.
const additionalHooks =
context.options &&
context.options[0] &&
context.options[0].additionalHooks
? new RegExp(context.options[0].additionalHooks)
rawOptions && rawOptions.additionalHooks
? new RegExp(rawOptions.additionalHooks)
: undefined;
const enableDangerousAutofixThisMayCauseInfiniteLoops: boolean =
(context.options &&
context.options[0] &&
context.options[0].enableDangerousAutofixThisMayCauseInfiniteLoops) ||
(rawOptions &&
rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops) ||
false;
const experimental_autoDependenciesHooks: ReadonlyArray<string> =
rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks)
? rawOptions.experimental_autoDependenciesHooks
: [];
const options = {
additionalHooks,
experimental_autoDependenciesHooks,
enableDangerousAutofixThisMayCauseInfiniteLoops,
};
@@ -162,6 +173,7 @@ const rule = {
reactiveHook: Node,
reactiveHookName: string,
isEffect: boolean,
isAutoDepsHook: boolean,
): void {
if (isEffect && node.async) {
reportProblem({
@@ -649,6 +661,9 @@ const rule = {
}
if (!declaredDependenciesNode) {
if (isAutoDepsHook) {
return;
}
// Check if there are any top-level setState() calls.
// Those tend to lead to infinite loops.
let setStateInsideEffectWithoutDeps: string | null = null;
@@ -711,6 +726,13 @@ const rule = {
}
return;
}
if (
isAutoDepsHook &&
declaredDependenciesNode.type === 'Literal' &&
declaredDependenciesNode.value === null
) {
return;
}
const declaredDependencies: Array<DeclaredDependency> = [];
const externalDependencies = new Set<string>();
@@ -1318,10 +1340,19 @@ const rule = {
return;
}
const isAutoDepsHook =
options.experimental_autoDependenciesHooks.includes(reactiveHookName);
// Check the declared dependencies for this reactive hook. If there is no
// second argument then the reactive callback will re-run on every render.
// So no need to check for dependency inclusion.
if (!declaredDependenciesNode && !isEffect) {
if (
(!declaredDependenciesNode ||
(isAutoDepsHook &&
declaredDependenciesNode.type === 'Literal' &&
declaredDependenciesNode.value === null)) &&
!isEffect
) {
// These are only used for optimization.
if (
reactiveHookName === 'useMemo' ||
@@ -1355,11 +1386,17 @@ const rule = {
reactiveHook,
reactiveHookName,
isEffect,
isAutoDepsHook,
);
return; // Handled
case 'Identifier':
if (!declaredDependenciesNode) {
// No deps, no problems.
if (
!declaredDependenciesNode ||
(isAutoDepsHook &&
declaredDependenciesNode.type === 'Literal' &&
declaredDependenciesNode.value === null)
) {
// Always runs, no problems.
return; // Handled
}
// The function passed as a callback is not written inline.
@@ -1408,6 +1445,7 @@ const rule = {
reactiveHook,
reactiveHookName,
isEffect,
isAutoDepsHook,
);
return; // Handled
case 'VariableDeclarator':
@@ -1427,6 +1465,7 @@ const rule = {
reactiveHook,
reactiveHookName,
isEffect,
isAutoDepsHook,
);
return; // Handled
}
+77 -23
View File
@@ -80,6 +80,7 @@ import isArray from 'shared/isArray';
import {
clientRenderBoundary as clientRenderFunction,
completeBoundary as completeBoundaryFunction,
completeBoundaryUpgradeToViewTransitions as upgradeToViewTransitionsInstruction,
completeBoundaryWithStyles as styleInsertionFunction,
completeSegment as completeSegmentFunction,
formReplaying as formReplayingRuntime,
@@ -123,14 +124,16 @@ const ScriptStreamingFormat: StreamingFormat = 0;
const DataStreamingFormat: StreamingFormat = 1;
export type InstructionState = number;
const NothingSent /* */ = 0b0000000;
const SentCompleteSegmentFunction /* */ = 0b0000001;
const SentCompleteBoundaryFunction /* */ = 0b0000010;
const SentClientRenderFunction /* */ = 0b0000100;
const SentStyleInsertionFunction /* */ = 0b0001000;
const SentFormReplayingRuntime /* */ = 0b0010000;
const SentCompletedShellId /* */ = 0b0100000;
const SentMarkShellTime /* */ = 0b1000000;
const NothingSent /* */ = 0b000000000;
const SentCompleteSegmentFunction /* */ = 0b000000001;
const SentCompleteBoundaryFunction /* */ = 0b000000010;
const SentClientRenderFunction /* */ = 0b000000100;
const SentStyleInsertionFunction /* */ = 0b000001000;
const SentFormReplayingRuntime /* */ = 0b000010000;
const SentCompletedShellId /* */ = 0b000100000;
const SentMarkShellTime /* */ = 0b001000000;
const NeedUpgradeToViewTransitions /* */ = 0b010000000;
const SentUpgradeToViewTransitions /* */ = 0b100000000;
// Per request, global state that is not contextual to the rendering subtree.
// This cannot be resumed and therefore should only contain things that are
@@ -742,12 +745,13 @@ const HTML_COLGROUP_MODE = 9;
type InsertionMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
const NO_SCOPE = /* */ 0b00000;
const NOSCRIPT_SCOPE = /* */ 0b00001;
const PICTURE_SCOPE = /* */ 0b00010;
const FALLBACK_SCOPE = /* */ 0b00100;
const EXIT_SCOPE = /* */ 0b01000; // A direct Instance below a Suspense fallback is the only thing that can "exit"
const ENTER_SCOPE = /* */ 0b10000; // A direct Instance below Suspense content is the only thing that can "enter"
const NO_SCOPE = /* */ 0b000000;
const NOSCRIPT_SCOPE = /* */ 0b000001;
const PICTURE_SCOPE = /* */ 0b000010;
const FALLBACK_SCOPE = /* */ 0b000100;
const EXIT_SCOPE = /* */ 0b001000; // A direct Instance below a Suspense fallback is the only thing that can "exit"
const ENTER_SCOPE = /* */ 0b010000; // A direct Instance below Suspense content is the only thing that can "enter"
const UPDATE_SCOPE = /* */ 0b100000; // Inside a scope that applies "update" ViewTransitions if anything mutates here.
// Everything not listed here are tracked for the whole subtree as opposed to just
// until the next Instance.
@@ -926,8 +930,15 @@ function getSuspenseViewTransition(
}
export function getSuspenseFallbackFormatContext(
resumableState: ResumableState,
parentContext: FormatContext,
): FormatContext {
if (parentContext.tagScope & UPDATE_SCOPE) {
// If we're rendering a Suspense in fallback mode and that is inside a ViewTransition,
// which hasn't disabled updates, then revealing it might animate the parent so we need
// the ViewTransition instructions.
resumableState.instructions |= NeedUpgradeToViewTransitions;
}
return createFormatContext(
parentContext.insertionMode,
parentContext.selectedValue,
@@ -937,6 +948,7 @@ export function getSuspenseFallbackFormatContext(
}
export function getSuspenseContentFormatContext(
resumableState: ResumableState,
parentContext: FormatContext,
): FormatContext {
return createFormatContext(
@@ -948,6 +960,7 @@ export function getSuspenseContentFormatContext(
}
export function getViewTransitionFormatContext(
resumableState: ResumableState,
parentContext: FormatContext,
update: ?string,
enter: ?string,
@@ -983,14 +996,26 @@ export function getViewTransitionFormatContext(
// exit because enter/exit will take precedence and if it's deeply nested
// it just animates along whatever the parent does when disabled.
share = null;
} else if (share == null) {
share = 'auto';
} else {
if (share == null) {
share = 'auto';
}
if (parentContext.tagScope & FALLBACK_SCOPE) {
// If we have an explicit name and share is not disabled, and we're inside
// a fallback, then that fallback might pair with content and so we might need
// the ViewTransition instructions to animate between them.
resumableState.instructions |= NeedUpgradeToViewTransitions;
}
}
if (!(parentContext.tagScope & EXIT_SCOPE)) {
exit = null; // exit is only relevant for the first ViewTransition inside fallback
} else {
resumableState.instructions |= NeedUpgradeToViewTransitions;
}
if (!(parentContext.tagScope & ENTER_SCOPE)) {
enter = null; // enter is only relevant for the first ViewTransition inside content
} else {
resumableState.instructions |= NeedUpgradeToViewTransitions;
}
const viewTransition: ViewTransitionContext = {
update,
@@ -1001,7 +1026,12 @@ export function getViewTransitionFormatContext(
autoName,
nameIdx: 0,
};
const subtreeScope = parentContext.tagScope & SUBTREE_SCOPE;
let subtreeScope = parentContext.tagScope & SUBTREE_SCOPE;
if (update !== 'none') {
subtreeScope |= UPDATE_SCOPE;
} else {
subtreeScope &= ~UPDATE_SCOPE;
}
return createFormatContext(
parentContext.insertionMode,
parentContext.selectedValue,
@@ -4780,9 +4810,8 @@ export function writeCompletedSegmentInstruction(
const completeBoundaryScriptFunctionOnly = stringToPrecomputedChunk(
completeBoundaryFunction,
);
const completeBoundaryScript1Full = stringToPrecomputedChunk(
completeBoundaryFunction + '$RC("',
);
const completeBoundaryUpgradeToViewTransitionsInstruction =
stringToPrecomputedChunk(upgradeToViewTransitionsInstruction);
const completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
const completeBoundaryWithStylesScript1FullPartial = stringToPrecomputedChunk(
@@ -4814,6 +4843,10 @@ export function writeCompletedBoundaryInstruction(
hoistableState: HoistableState,
): boolean {
const requiresStyleInsertion = renderState.stylesToHoist;
const requiresViewTransitions =
enableViewTransition &&
(resumableState.instructions & NeedUpgradeToViewTransitions) !==
NothingSent;
// If necessary stylesheets will be flushed with this instruction.
// Any style tags not yet hoisted in the Document will also be hoisted.
// We reset this state since after this instruction executes all styles
@@ -4842,6 +4875,17 @@ export function writeCompletedBoundaryInstruction(
resumableState.instructions |= SentCompleteBoundaryFunction;
writeChunk(destination, completeBoundaryScriptFunctionOnly);
}
if (
requiresViewTransitions &&
(resumableState.instructions & SentUpgradeToViewTransitions) ===
NothingSent
) {
resumableState.instructions |= SentUpgradeToViewTransitions;
writeChunk(
destination,
completeBoundaryUpgradeToViewTransitionsInstruction,
);
}
if (
(resumableState.instructions & SentStyleInsertionFunction) ===
NothingSent
@@ -4857,10 +4901,20 @@ export function writeCompletedBoundaryInstruction(
NothingSent
) {
resumableState.instructions |= SentCompleteBoundaryFunction;
writeChunk(destination, completeBoundaryScript1Full);
} else {
writeChunk(destination, completeBoundaryScript1Partial);
writeChunk(destination, completeBoundaryScriptFunctionOnly);
}
if (
requiresViewTransitions &&
(resumableState.instructions & SentUpgradeToViewTransitions) ===
NothingSent
) {
resumableState.instructions |= SentUpgradeToViewTransitions;
writeChunk(
destination,
completeBoundaryUpgradeToViewTransitionsInstruction,
);
}
writeChunk(destination, completeBoundaryScript1Partial);
}
} else {
if (requiresStyleInsertion) {
@@ -181,6 +181,7 @@ export {
import escapeTextForBrowser from './escapeTextForBrowser';
export function getViewTransitionFormatContext(
resumableState: ResumableState,
parentContext: FormatContext,
update: void | null | 'none' | 'auto' | string,
enter: void | null | 'none' | 'auto' | string,
@@ -1,7 +1,12 @@
import {completeBoundary} from './ReactDOMFizzInstructionSetShared';
import {
revealCompletedBoundaries,
completeBoundary,
} from './ReactDOMFizzInstructionSetShared';
// This is a string so Closure's advanced compilation mode doesn't mangle it.
// eslint-disable-next-line dot-notation
window['$RB'] = [];
// eslint-disable-next-line dot-notation
window['$RV'] = revealCompletedBoundaries;
// eslint-disable-next-line dot-notation
window['$RC'] = completeBoundary;
@@ -0,0 +1,10 @@
import {revealCompletedBoundariesWithViewTransitions} from './ReactDOMFizzInstructionSetShared';
// Upgrade the revealCompletedBoundaries instruction to support ViewTransitions.
// This is a string so Closure's advanced compilation mode doesn't mangle it.
// eslint-disable-next-line dot-notation
window['$RV'] = revealCompletedBoundariesWithViewTransitions.bind(
null,
// eslint-disable-next-line dot-notation
window['$RV'],
);
@@ -8,6 +8,8 @@ import {
completeBoundaryWithStyles,
completeSegment,
listenToFormSubmissionsForReplaying,
revealCompletedBoundaries,
revealCompletedBoundariesWithViewTransitions,
} from './ReactDOMFizzInstructionSetShared';
// This is a string so Closure's advanced compilation mode doesn't mangle it.
@@ -15,6 +17,10 @@ import {
window['$RM'] = new Map();
window['$RB'] = [];
window['$RX'] = clientRenderBoundary;
window['$RV'] = revealCompletedBoundariesWithViewTransitions.bind(
null,
revealCompletedBoundaries,
);
window['$RC'] = completeBoundary;
window['$RR'] = completeBoundaryWithStyles;
window['$RS'] = completeSegment;
@@ -6,7 +6,9 @@ export const markShellTime =
export const clientRenderBoundary =
'$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};';
export const completeBoundary =
'$RB=[];$RC=function(d,c){function m(){$RT=performance.now();var f=$RB;$RB=[];for(var e=0;e<f.length;e+=2){var a=f[e],l=f[e+1],g=a.parentNode;if(g){var h=a.previousSibling,k=0;do{if(a&&8===a.nodeType){var b=a.data;if("/$"===b||"/&"===b)if(0===k)break;else k--;else"$"!==b&&"$?"!==b&&"$~"!==b&&"$!"!==b&&"&"!==b||k++}b=a.nextSibling;g.removeChild(a);a=b}while(a);for(;l.firstChild;)g.insertBefore(l.firstChild,a);h.data="$";h._reactRetry&&h._reactRetry()}}}if(c=document.getElementById(c))if(c.parentNode.removeChild(c),d=\ndocument.getElementById(d))d.previousSibling.data="$~",$RB.push(d,c),2===$RB.length&&setTimeout(m,("number"!==typeof $RT?0:$RT)+300-performance.now())};';
'$RB=[];$RV=function(){$RT=performance.now();var d=$RB;$RB=[];for(var a=0;a<d.length;a+=2){var b=d[a],h=d[a+1],e=b.parentNode;if(e){var f=b.previousSibling,g=0;do{if(b&&8===b.nodeType){var c=b.data;if("/$"===c||"/&"===c)if(0===g)break;else g--;else"$"!==c&&"$?"!==c&&"$~"!==c&&"$!"!==c&&"&"!==c||g++}c=b.nextSibling;e.removeChild(b);b=c}while(b);for(;h.firstChild;)e.insertBefore(h.firstChild,b);f.data="$";f._reactRetry&&f._reactRetry()}}};$RC=function(d,a){if(a=document.getElementById(a))if(a.parentNode.removeChild(a),d=document.getElementById(d))d.previousSibling.data="$~",$RB.push(d,a),2===$RB.length&&setTimeout($RV,("number"!==typeof $RT?0:$RT)+300-performance.now())};';
export const completeBoundaryUpgradeToViewTransitions =
'$RV=function(a){try{var b=document.__reactViewTransition;if(b){b.finished.then($RV,$RV);return}if(window._useVT){var c=document.__reactViewTransition=document.startViewTransition({update:a,types:[]});c.finished.finally(function(){document.__reactViewTransition===c&&(document.__reactViewTransition=null)});return}}catch(d){}a()}.bind(null,$RV);';
export const completeBoundaryWithStyles =
'$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=\n"stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=\n"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};';
export const completeSegment =
@@ -18,6 +18,100 @@ const SUSPENSE_FALLBACK_START_DATA = '$!';
// working. Closure converts it to a dot access anyway, though, so it's not an
// urgent issue.
export function revealCompletedBoundaries() {
window['$RT'] = performance.now();
const batch = window['$RB'];
window['$RB'] = [];
for (let i = 0; i < batch.length; i += 2) {
const suspenseIdNode = batch[i];
const contentNode = batch[i + 1];
// Clear all the existing children. This is complicated because
// there can be embedded Suspense boundaries in the fallback.
// This is similar to clearSuspenseBoundary in ReactFiberConfigDOM.
// TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
// They never hydrate anyway. However, currently we support incrementally loading the fallback.
const parentInstance = suspenseIdNode.parentNode;
if (!parentInstance) {
// We may have client-rendered this boundary already. Skip it.
continue;
}
// Find the boundary around the fallback. This is always the previous node.
const suspenseNode = suspenseIdNode.previousSibling;
let node = suspenseIdNode;
let depth = 0;
do {
if (node && node.nodeType === COMMENT_NODE) {
const data = node.data;
if (data === SUSPENSE_END_DATA || data === ACTIVITY_END_DATA) {
if (depth === 0) {
break;
} else {
depth--;
}
} else if (
data === SUSPENSE_START_DATA ||
data === SUSPENSE_PENDING_START_DATA ||
data === SUSPENSE_QUEUED_START_DATA ||
data === SUSPENSE_FALLBACK_START_DATA ||
data === ACTIVITY_START_DATA
) {
depth++;
}
}
const nextNode = node.nextSibling;
parentInstance.removeChild(node);
node = nextNode;
} while (node);
const endOfBoundary = node;
// Insert all the children from the contentNode between the start and end of suspense boundary.
while (contentNode.firstChild) {
parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
}
suspenseNode.data = SUSPENSE_START_DATA;
if (suspenseNode['_reactRetry']) {
suspenseNode['_reactRetry']();
}
}
}
export function revealCompletedBoundariesWithViewTransitions(revealBoundaries) {
try {
const existingTransition = document['__reactViewTransition'];
if (existingTransition) {
// Retry after the previous ViewTransition finishes.
existingTransition.finished.then(window['$RV'], window['$RV']);
return;
}
const shouldStartViewTransition = window['_useVT']; // TODO: Detect.
if (shouldStartViewTransition) {
const transition = (document['__reactViewTransition'] = document[
'startViewTransition'
]({
update: revealBoundaries,
types: [], // TODO: Add a hard coded type for Suspense reveals.
}));
transition.finished.finally(() => {
if (document['__reactViewTransition'] === transition) {
document['__reactViewTransition'] = null;
}
});
return;
}
// Fall through to reveal.
} catch (x) {
// Fall through to reveal.
}
// ViewTransitions v2 not supported or no ViewTransitions found. Reveal immediately.
revealBoundaries();
}
export function clientRenderBoundary(
suspenseBoundaryID,
errorDigest,
@@ -71,69 +165,6 @@ export function completeBoundary(suspenseBoundaryID, contentID) {
return;
}
function revealCompletedBoundaries() {
window['$RT'] = performance.now();
const batch = window['$RB'];
window['$RB'] = [];
for (let i = 0; i < batch.length; i += 2) {
const suspenseIdNode = batch[i];
const contentNode = batch[i + 1];
// Clear all the existing children. This is complicated because
// there can be embedded Suspense boundaries in the fallback.
// This is similar to clearSuspenseBoundary in ReactFiberConfigDOM.
// TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
// They never hydrate anyway. However, currently we support incrementally loading the fallback.
const parentInstance = suspenseIdNode.parentNode;
if (!parentInstance) {
// We may have client-rendered this boundary already. Skip it.
continue;
}
// Find the boundary around the fallback. This is always the previous node.
const suspenseNode = suspenseIdNode.previousSibling;
let node = suspenseIdNode;
let depth = 0;
do {
if (node && node.nodeType === COMMENT_NODE) {
const data = node.data;
if (data === SUSPENSE_END_DATA || data === ACTIVITY_END_DATA) {
if (depth === 0) {
break;
} else {
depth--;
}
} else if (
data === SUSPENSE_START_DATA ||
data === SUSPENSE_PENDING_START_DATA ||
data === SUSPENSE_QUEUED_START_DATA ||
data === SUSPENSE_FALLBACK_START_DATA ||
data === ACTIVITY_START_DATA
) {
depth++;
}
}
const nextNode = node.nextSibling;
parentInstance.removeChild(node);
node = nextNode;
} while (node);
const endOfBoundary = node;
// Insert all the children from the contentNode between the start and end of suspense boundary.
while (contentNode.firstChild) {
parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
}
suspenseNode.data = SUSPENSE_START_DATA;
if (suspenseNode['_reactRetry']) {
suspenseNode['_reactRetry']();
}
}
}
// Mark this Suspense boundary as queued so we know not to client render it
// at the end of document load.
const suspenseNodeOuter = suspenseIdNodeOuter.previousSibling;
@@ -151,7 +182,7 @@ export function completeBoundary(suspenseBoundaryID, contentID) {
// We always schedule the flush in a timer even if it's very low or negative to allow
// for multiple completeBoundary calls that are already queued to have a chance to
// make the batch.
setTimeout(revealCompletedBoundaries, msUntilTimeout);
setTimeout(window['$RV'], msUntilTimeout);
}
}
@@ -1318,10 +1318,8 @@ describe('ReactDOMFizzServer', () => {
expect(ref.current).toBe(null);
expect(getVisibleChildren(container)).toEqual(
<div>
Loading A
{/* // TODO: This is incorrect. It should be "Loading B" but Fizz SuspenseList
// isn't implemented fully yet. */}
<span>B</span>
{'Loading A'}
{'Loading B'}
</div>,
);
@@ -1335,11 +1333,9 @@ describe('ReactDOMFizzServer', () => {
// We haven't resolved yet.
expect(getVisibleChildren(container)).toEqual(
<div>
Loading A
{/* // TODO: This is incorrect. It should be "Loading B" but Fizz SuspenseList
// isn't implemented fully yet. */}
<span>B</span>
Loading C
{'Loading A'}
{'Loading B'}
{'Loading C'}
</div>,
);
@@ -0,0 +1,327 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
*/
'use strict';
import {
insertNodesAndExecuteScripts,
getVisibleChildren,
} from '../test-utils/FizzTestUtils';
let JSDOM;
let React;
let Suspense;
let SuspenseList;
let assertLog;
let Scheduler;
let ReactDOMFizzServer;
let Stream;
let document;
let writable;
let container;
let buffer = '';
let hasErrored = false;
let fatalError = undefined;
describe('ReactDOMFizSuspenseList', () => {
beforeEach(() => {
jest.resetModules();
JSDOM = require('jsdom').JSDOM;
React = require('react');
assertLog = require('internal-test-utils').assertLog;
ReactDOMFizzServer = require('react-dom/server');
Stream = require('stream');
Suspense = React.Suspense;
SuspenseList = React.unstable_SuspenseList;
Scheduler = require('scheduler');
// Test Environment
const jsdom = new JSDOM(
'<!DOCTYPE html><html><head></head><body><div id="container">',
{
runScripts: 'dangerously',
},
);
document = jsdom.window.document;
container = document.getElementById('container');
global.window = jsdom.window;
// The Fizz runtime assumes requestAnimationFrame exists so we need to polyfill it.
global.requestAnimationFrame = global.window.requestAnimationFrame = cb =>
setTimeout(cb);
buffer = '';
hasErrored = false;
writable = new Stream.PassThrough();
writable.setEncoding('utf8');
writable.on('data', chunk => {
buffer += chunk;
});
writable.on('error', error => {
hasErrored = true;
fatalError = error;
});
});
afterEach(() => {
jest.restoreAllMocks();
});
async function serverAct(callback) {
await callback();
// Await one turn around the event loop.
// This assumes that we'll flush everything we have so far.
await new Promise(resolve => {
setImmediate(resolve);
});
if (hasErrored) {
throw fatalError;
}
// JSDOM doesn't support stream HTML parser so we need to give it a proper fragment.
// We also want to execute any scripts that are embedded.
// We assume that we have now received a proper fragment of HTML.
const bufferedContent = buffer;
buffer = '';
const temp = document.createElement('body');
temp.innerHTML = bufferedContent;
await insertNodesAndExecuteScripts(temp, container, null);
jest.runAllTimers();
}
function Text(props) {
Scheduler.log(props.text);
return <span>{props.text}</span>;
}
function createAsyncText(text) {
let resolved = false;
const Component = function () {
if (!resolved) {
Scheduler.log('Suspend! [' + text + ']');
throw promise;
}
return <Text text={text} />;
};
const promise = new Promise(resolve => {
Component.resolve = function () {
resolved = true;
return resolve();
};
});
return Component;
}
// @gate enableSuspenseList
it('shows content independently by default', async () => {
const A = createAsyncText('A');
const B = createAsyncText('B');
const C = createAsyncText('C');
function Foo() {
return (
<div>
<SuspenseList>
<Suspense fallback={<Text text="Loading A" />}>
<A />
</Suspense>
<Suspense fallback={<Text text="Loading B" />}>
<B />
</Suspense>
<Suspense fallback={<Text text="Loading C" />}>
<C />
</Suspense>
</SuspenseList>
</div>
);
}
await A.resolve();
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<Foo />);
pipe(writable);
});
assertLog(['A', 'Suspend! [B]', 'Suspend! [C]', 'Loading B', 'Loading C']);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>A</span>
<span>Loading B</span>
<span>Loading C</span>
</div>,
);
await serverAct(() => C.resolve());
assertLog(['C']);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>A</span>
<span>Loading B</span>
<span>C</span>
</div>,
);
await serverAct(() => B.resolve());
assertLog(['B']);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>A</span>
<span>B</span>
<span>C</span>
</div>,
);
});
// @gate enableSuspenseList
it('displays each items in "forwards" order', async () => {
const A = createAsyncText('A');
const B = createAsyncText('B');
const C = createAsyncText('C');
function Foo() {
return (
<div>
<SuspenseList revealOrder="forwards">
<Suspense fallback={<Text text="Loading A" />}>
<A />
</Suspense>
<Suspense fallback={<Text text="Loading B" />}>
<B />
</Suspense>
<Suspense fallback={<Text text="Loading C" />}>
<C />
</Suspense>
</SuspenseList>
</div>
);
}
await C.resolve();
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<Foo />);
pipe(writable);
});
assertLog([
'Suspend! [A]',
'Suspend! [B]', // TODO: Defer rendering the content after fallback if previous suspended,
'C',
'Loading A',
'Loading B',
'Loading C',
]);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>Loading A</span>
<span>Loading B</span>
<span>Loading C</span>
</div>,
);
await serverAct(() => A.resolve());
assertLog(['A']);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>A</span>
<span>Loading B</span>
<span>Loading C</span>
</div>,
);
await serverAct(() => B.resolve());
assertLog(['B']);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>A</span>
<span>B</span>
<span>C</span>
</div>,
);
});
// @gate enableSuspenseList
it('displays each items in "backwards" order', async () => {
const A = createAsyncText('A');
const B = createAsyncText('B');
const C = createAsyncText('C');
function Foo() {
return (
<div>
<SuspenseList revealOrder="backwards">
<Suspense fallback={<Text text="Loading A" />}>
<A />
</Suspense>
<Suspense fallback={<Text text="Loading B" />}>
<B />
</Suspense>
<Suspense fallback={<Text text="Loading C" />}>
<C />
</Suspense>
</SuspenseList>
</div>
);
}
await A.resolve();
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<Foo />);
pipe(writable);
});
assertLog([
'Suspend! [C]',
'Suspend! [B]', // TODO: Defer rendering the content after fallback if previous suspended,
'A',
'Loading C',
'Loading B',
'Loading A',
]);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>Loading A</span>
<span>Loading B</span>
<span>Loading C</span>
</div>,
);
await serverAct(() => C.resolve());
assertLog(['C']);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>Loading A</span>
<span>Loading B</span>
<span>C</span>
</div>,
);
await serverAct(() => B.resolve());
assertLog(['B']);
expect(getVisibleChildren(container)).toEqual(
<div>
<span>A</span>
<span>B</span>
<span>C</span>
</div>,
);
});
});
+1
View File
@@ -89,6 +89,7 @@ export {
import escapeTextForBrowser from 'react-dom-bindings/src/server/escapeTextForBrowser';
export function getViewTransitionFormatContext(
resumableState: ResumableState,
parentContext: FormatContext,
update: void | null | 'none' | 'auto' | string,
enter: void | null | 'none' | 'auto' | string,
+4 -4
View File
@@ -14,6 +14,9 @@ import type {
ViewTransitionProps,
ActivityProps,
SuspenseProps,
SuspenseListProps,
SuspenseListRevealOrder,
SuspenseListTailMode,
TracingMarkerProps,
CacheProps,
ProfilerProps,
@@ -26,7 +29,6 @@ import type {ActivityState} from './ReactFiberActivityComponent';
import type {
SuspenseState,
SuspenseListRenderState,
SuspenseListTailMode,
} from './ReactFiberSuspenseComponent';
import type {SuspenseContext} from './ReactFiberSuspenseContext';
import type {
@@ -3222,8 +3224,6 @@ function findLastContentRow(firstChild: null | Fiber): null | Fiber {
return lastContentRow;
}
type SuspenseListRevealOrder = 'forwards' | 'backwards' | 'together' | void;
function validateRevealOrder(revealOrder: SuspenseListRevealOrder) {
if (__DEV__) {
if (
@@ -3410,7 +3410,7 @@ function updateSuspenseListComponent(
workInProgress: Fiber,
renderLanes: Lanes,
) {
const nextProps = workInProgress.pendingProps;
const nextProps: SuspenseListProps = workInProgress.pendingProps;
const revealOrder: SuspenseListRevealOrder = nextProps.revealOrder;
const tailMode: SuspenseListTailMode = nextProps.tail;
const newChildren = nextProps.children;
@@ -7,7 +7,7 @@
* @flow
*/
import type {Wakeable} from 'shared/ReactTypes';
import type {Wakeable, SuspenseListTailMode} from 'shared/ReactTypes';
import type {Fiber} from './ReactInternalTypes';
import type {SuspenseInstance} from './ReactFiberConfig';
import type {Lane} from './ReactFiberLane';
@@ -42,8 +42,6 @@ export type SuspenseState = {
hydrationErrors: Array<CapturedValue<mixed>> | null,
};
export type SuspenseListTailMode = 'collapsed' | 'hidden' | void;
export type SuspenseListRenderState = {
isBackwards: boolean,
// The currently rendering tail row.
+482 -26
View File
@@ -24,6 +24,8 @@ import type {
ViewTransitionProps,
ActivityProps,
SuspenseProps,
SuspenseListProps,
SuspenseListRevealOrder,
} from 'shared/ReactTypes';
import type {LazyComponent as LazyComponentType} from 'react/src/ReactLazy';
import type {
@@ -231,6 +233,12 @@ type LegacyContext = {
[key: string]: any,
};
type SuspenseListRow = {
pendingTasks: number, // The number of tasks, previous rows and inner suspense boundaries blocking this row.
boundaries: null | Array<SuspenseBoundary>, // The boundaries in this row waiting to be unblocked by the previous row. (null means this row is not blocked)
next: null | SuspenseListRow, // The next row blocked by this one.
};
const CLIENT_RENDERED = 4; // if it errors or infinitely suspends
type SuspenseBoundary = {
@@ -238,6 +246,7 @@ type SuspenseBoundary = {
rootSegmentID: number,
parentFlushed: boolean,
pendingTasks: number, // when it reaches zero we can show this boundary's content
row: null | SuspenseListRow, // the row that this boundary blocks from completing.
completedSegments: Array<Segment>, // completed but not yet flushed segments.
byteSize: number, // used to determine whether to inline children boundaries.
fallbackAbortableTasks: Set<Task>, // used to cancel task on the fallback if the boundary completes or gets canceled.
@@ -268,11 +277,12 @@ type RenderTask = {
formatContext: FormatContext, // the format's specific context (e.g. HTML/SVG/MathML)
context: ContextSnapshot, // the current new context that this task is executing in
treeContext: TreeContext, // the current tree context that this task is executing in
row: null | SuspenseListRow, // the current SuspenseList row that this is rendering inside
componentStack: null | ComponentStackNode, // stack frame description of the currently rendering component
thenableState: null | ThenableState,
legacyContext: LegacyContext, // the current legacy context that this task is executing in
debugTask: null | ConsoleTask, // DEV only
// DON'T ANY MORE FIELDS. We at 16 already which otherwise requires converting to a constructor.
// DON'T ANY MORE FIELDS. We at 16 in prod already which otherwise requires converting to a constructor.
// Consider splitting into multiple objects or consolidating some fields.
};
@@ -298,12 +308,11 @@ type ReplayTask = {
formatContext: FormatContext, // the format's specific context (e.g. HTML/SVG/MathML)
context: ContextSnapshot, // the current new context that this task is executing in
treeContext: TreeContext, // the current tree context that this task is executing in
row: null | SuspenseListRow, // the current SuspenseList row that this is rendering inside
componentStack: null | ComponentStackNode, // stack frame description of the currently rendering component
thenableState: null | ThenableState,
legacyContext: LegacyContext, // the current legacy context that this task is executing in
debugTask: null | ConsoleTask, // DEV only
// DON'T ANY MORE FIELDS. We at 16 already which otherwise requires converting to a constructor.
// Consider splitting into multiple objects or consolidating some fields.
};
export type Task = RenderTask | ReplayTask;
@@ -542,6 +551,7 @@ export function createRequest(
rootContextSnapshot,
emptyTreeContext,
null,
null,
emptyContextObject,
null,
);
@@ -647,6 +657,7 @@ export function resumeRequest(
rootContextSnapshot,
emptyTreeContext,
null,
null,
emptyContextObject,
null,
);
@@ -674,6 +685,7 @@ export function resumeRequest(
rootContextSnapshot,
emptyTreeContext,
null,
null,
emptyContextObject,
null,
);
@@ -739,6 +751,7 @@ function pingTask(request: Request, task: Task): void {
function createSuspenseBoundary(
request: Request,
row: null | SuspenseListRow,
fallbackAbortableTasks: Set<Task>,
contentPreamble: null | Preamble,
fallbackPreamble: null | Preamble,
@@ -748,6 +761,7 @@ function createSuspenseBoundary(
rootSegmentID: -1,
parentFlushed: false,
pendingTasks: 0,
row: row,
completedSegments: [],
byteSize: 0,
fallbackAbortableTasks,
@@ -765,6 +779,17 @@ function createSuspenseBoundary(
boundary.errorStack = null;
boundary.errorComponentStack = null;
}
if (row !== null) {
// This boundary will block this row from completing.
row.pendingTasks++;
const blockedBoundaries = row.boundaries;
if (blockedBoundaries !== null) {
// Previous rows will block this boundary itself from completing.
request.allPendingTasks++;
boundary.pendingTasks++;
blockedBoundaries.push(boundary);
}
}
return boundary;
}
@@ -782,6 +807,7 @@ function createRenderTask(
formatContext: FormatContext,
context: ContextSnapshot,
treeContext: TreeContext,
row: null | SuspenseListRow,
componentStack: null | ComponentStackNode,
legacyContext: LegacyContext,
debugTask: null | ConsoleTask,
@@ -792,6 +818,9 @@ function createRenderTask(
} else {
blockedBoundary.pendingTasks++;
}
if (row !== null) {
row.pendingTasks++;
}
const task: RenderTask = ({
replay: null,
node,
@@ -806,6 +835,7 @@ function createRenderTask(
formatContext,
context,
treeContext,
row,
componentStack,
thenableState,
}: any);
@@ -832,6 +862,7 @@ function createReplayTask(
formatContext: FormatContext,
context: ContextSnapshot,
treeContext: TreeContext,
row: null | SuspenseListRow,
componentStack: null | ComponentStackNode,
legacyContext: LegacyContext,
debugTask: null | ConsoleTask,
@@ -842,6 +873,9 @@ function createReplayTask(
} else {
blockedBoundary.pendingTasks++;
}
if (row !== null) {
row.pendingTasks++;
}
replay.pendingTasks++;
const task: ReplayTask = ({
replay,
@@ -857,6 +891,7 @@ function createReplayTask(
formatContext,
context,
treeContext,
row,
componentStack,
thenableState,
}: any);
@@ -1145,14 +1180,20 @@ function renderSuspenseBoundary(
// so we can just render through it.
const prevKeyPath = someTask.keyPath;
const prevContext = someTask.formatContext;
const prevRow = someTask.row;
someTask.keyPath = keyPath;
someTask.formatContext = getSuspenseContentFormatContext(prevContext);
someTask.formatContext = getSuspenseContentFormatContext(
request.resumableState,
prevContext,
);
someTask.row = null;
const content: ReactNodeList = props.children;
try {
renderNode(request, someTask, content, -1);
} finally {
someTask.keyPath = prevKeyPath;
someTask.formatContext = prevContext;
someTask.row = prevRow;
}
return;
}
@@ -1161,6 +1202,7 @@ function renderSuspenseBoundary(
const prevKeyPath = task.keyPath;
const prevContext = task.formatContext;
const prevRow = task.row;
const parentBoundary = task.blockedBoundary;
const parentPreamble = task.blockedPreamble;
const parentHoistableState = task.hoistableState;
@@ -1178,12 +1220,19 @@ function renderSuspenseBoundary(
if (canHavePreamble(task.formatContext)) {
newBoundary = createSuspenseBoundary(
request,
task.row,
fallbackAbortSet,
createPreambleState(),
createPreambleState(),
);
} else {
newBoundary = createSuspenseBoundary(request, fallbackAbortSet, null, null);
newBoundary = createSuspenseBoundary(
request,
task.row,
fallbackAbortSet,
null,
null,
);
}
if (request.trackedPostpones !== null) {
newBoundary.trackedContentKeyPath = keyPath;
@@ -1239,7 +1288,10 @@ function renderSuspenseBoundary(
task.blockedSegment = boundarySegment;
task.blockedPreamble = newBoundary.fallbackPreamble;
task.keyPath = fallbackKeyPath;
task.formatContext = getSuspenseFallbackFormatContext(prevContext);
task.formatContext = getSuspenseFallbackFormatContext(
request.resumableState,
prevContext,
);
boundarySegment.status = RENDERING;
try {
renderNode(request, task, fallback, -1);
@@ -1278,9 +1330,13 @@ function renderSuspenseBoundary(
newBoundary.contentState,
task.abortSet,
keyPath,
getSuspenseContentFormatContext(task.formatContext),
getSuspenseContentFormatContext(
request.resumableState,
task.formatContext,
),
task.context,
task.treeContext,
null, // The row gets reset inside the Suspense boundary.
task.componentStack,
!disableLegacyContext ? task.legacyContext : emptyContextObject,
__DEV__ ? task.debugTask : null,
@@ -1305,7 +1361,11 @@ function renderSuspenseBoundary(
task.hoistableState = newBoundary.contentState;
task.blockedSegment = contentRootSegment;
task.keyPath = keyPath;
task.formatContext = getSuspenseContentFormatContext(prevContext);
task.formatContext = getSuspenseContentFormatContext(
request.resumableState,
prevContext,
);
task.row = null;
contentRootSegment.status = RENDERING;
try {
@@ -1327,6 +1387,14 @@ function renderSuspenseBoundary(
// the fallback. However, if this boundary ended up big enough to be eligible for outlining
// we can't do that because we might still need the fallback if we outline it.
if (!isEligibleForOutlining(request, newBoundary)) {
if (prevRow !== null) {
// If we have synchronously completed the boundary and it's not eligible for outlining
// then we don't have to wait for it to be flushed before we unblock future rows.
// This lets us inline small rows in order.
if (--prevRow.pendingTasks === 0) {
finishSuspenseListRow(request, prevRow);
}
}
if (request.pendingRootTasks === 0 && task.blockedPreamble) {
// The root is complete and this boundary may contribute part of the preamble.
// We eagerly attempt to prepare the preamble here because we expect most requests
@@ -1393,6 +1461,7 @@ function renderSuspenseBoundary(
task.blockedSegment = parentSegment;
task.keyPath = prevKeyPath;
task.formatContext = prevContext;
task.row = prevRow;
}
const fallbackKeyPath = [keyPath[0], 'Suspense Fallback', keyPath[2]];
@@ -1409,9 +1478,13 @@ function renderSuspenseBoundary(
newBoundary.fallbackState,
fallbackAbortSet,
fallbackKeyPath,
getSuspenseFallbackFormatContext(task.formatContext),
getSuspenseFallbackFormatContext(
request.resumableState,
task.formatContext,
),
task.context,
task.treeContext,
task.row,
task.componentStack,
!disableLegacyContext ? task.legacyContext : emptyContextObject,
__DEV__ ? task.debugTask : null,
@@ -1436,6 +1509,7 @@ function replaySuspenseBoundary(
): void {
const prevKeyPath = task.keyPath;
const prevContext = task.formatContext;
const prevRow = task.row;
const previousReplaySet: ReplaySet = task.replay;
const parentBoundary = task.blockedBoundary;
@@ -1449,6 +1523,7 @@ function replaySuspenseBoundary(
if (canHavePreamble(task.formatContext)) {
resumedBoundary = createSuspenseBoundary(
request,
task.row,
fallbackAbortSet,
createPreambleState(),
createPreambleState(),
@@ -1456,6 +1531,7 @@ function replaySuspenseBoundary(
} else {
resumedBoundary = createSuspenseBoundary(
request,
task.row,
fallbackAbortSet,
null,
null,
@@ -1471,7 +1547,11 @@ function replaySuspenseBoundary(
task.blockedBoundary = resumedBoundary;
task.hoistableState = resumedBoundary.contentState;
task.keyPath = keyPath;
task.formatContext = getSuspenseContentFormatContext(prevContext);
task.formatContext = getSuspenseContentFormatContext(
request.resumableState,
prevContext,
);
task.row = null;
task.replay = {nodes: childNodes, slots: childSlots, pendingTasks: 1};
try {
@@ -1548,6 +1628,7 @@ function replaySuspenseBoundary(
task.replay = previousReplaySet;
task.keyPath = prevKeyPath;
task.formatContext = prevContext;
task.row = prevRow;
}
const fallbackKeyPath = [keyPath[0], 'Suspense Fallback', keyPath[2]];
@@ -1569,9 +1650,13 @@ function replaySuspenseBoundary(
resumedBoundary.fallbackState,
fallbackAbortSet,
fallbackKeyPath,
getSuspenseFallbackFormatContext(task.formatContext),
getSuspenseFallbackFormatContext(
request.resumableState,
task.formatContext,
),
task.context,
task.treeContext,
task.row,
task.componentStack,
!disableLegacyContext ? task.legacyContext : emptyContextObject,
__DEV__ ? task.debugTask : null,
@@ -1583,6 +1668,317 @@ function replaySuspenseBoundary(
request.pingedTasks.push(suspendedFallbackTask);
}
function finishSuspenseListRow(request: Request, row: SuspenseListRow): void {
// This row finished. Now we have to unblock all the next rows that were blocked on this.
// We do this in a loop to avoid stack overflow for very long lists that get unblocked.
let unblockedRow = row.next;
while (unblockedRow !== null) {
// Unblocking the boundaries will decrement the count of this row but we keep it above
// zero so they never finish this row recursively.
const unblockedBoundaries = unblockedRow.boundaries;
if (unblockedBoundaries !== null) {
unblockedRow.boundaries = null;
for (let i = 0; i < unblockedBoundaries.length; i++) {
finishedTask(request, unblockedBoundaries[i], null, null);
}
}
// Instead we decrement at the end to keep it all in this loop.
unblockedRow.pendingTasks--;
if (unblockedRow.pendingTasks > 0) {
// Still blocked.
break;
}
unblockedRow = unblockedRow.next;
}
}
function createSuspenseListRow(
previousRow: null | SuspenseListRow,
): SuspenseListRow {
const newRow: SuspenseListRow = {
pendingTasks: 1, // At first the row is blocked on attempting rendering itself.
boundaries: null,
next: null,
};
if (previousRow !== null && previousRow.pendingTasks > 0) {
// If the previous row is not done yet, we add ourselves to be blocked on it.
// When it finishes, we'll decrement our pending tasks.
newRow.pendingTasks++;
newRow.boundaries = [];
previousRow.next = newRow;
}
return newRow;
}
function renderSuspenseListRows(
request: Request,
task: Task,
keyPath: KeyNode,
rows: Array<ReactNodeList>,
revealOrder: 'forwards' | 'backwards',
): void {
// This is a fork of renderChildrenArray that's aware of tracking rows.
const prevKeyPath = task.keyPath;
const previousComponentStack = task.componentStack;
let previousDebugTask = null;
if (__DEV__) {
previousDebugTask = task.debugTask;
// We read debugInfo from task.node.props.children instead of rows because it
// might have been an unwrapped iterable so we read from the original node.
pushServerComponentStack(task, (task.node: any).props.children._debugInfo);
}
const prevTreeContext = task.treeContext;
const prevRow = task.row;
const totalChildren = rows.length;
if (task.replay !== null) {
// Replay
// First we need to check if we have any resume slots at this level.
const resumeSlots = task.replay.slots;
if (resumeSlots !== null && typeof resumeSlots === 'object') {
let previousSuspenseListRow: null | SuspenseListRow = null;
for (let n = 0; n < totalChildren; n++) {
// Since we are going to resume into a slot whose order was already
// determined by the prerender, we can safely resume it even in reverse
// render order.
const i = revealOrder !== 'backwards' ? n : totalChildren - 1 - n;
const node = rows[i];
task.row = previousSuspenseListRow = createSuspenseListRow(
previousSuspenseListRow,
);
task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);
const resumeSegmentID = resumeSlots[i];
// TODO: If this errors we should still continue with the next sibling.
if (typeof resumeSegmentID === 'number') {
resumeNode(request, task, resumeSegmentID, node, i);
// We finished rendering this node, so now we can consume this
// slot. This must happen after in case we rerender this task.
delete resumeSlots[i];
} else {
renderNode(request, task, node, i);
}
if (--previousSuspenseListRow.pendingTasks === 0) {
finishSuspenseListRow(request, previousSuspenseListRow);
}
}
} else {
let previousSuspenseListRow: null | SuspenseListRow = null;
for (let n = 0; n < totalChildren; n++) {
// Since we are going to resume into a slot whose order was already
// determined by the prerender, we can safely resume it even in reverse
// render order.
const i = revealOrder !== 'backwards' ? n : totalChildren - 1 - n;
const node = rows[i];
if (__DEV__) {
warnForMissingKey(request, task, node);
}
task.row = previousSuspenseListRow = createSuspenseListRow(
previousSuspenseListRow,
);
task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);
renderNode(request, task, node, i);
if (--previousSuspenseListRow.pendingTasks === 0) {
finishSuspenseListRow(request, previousSuspenseListRow);
}
}
}
} else {
task = ((task: any): RenderTask); // Refined
if (revealOrder !== 'backwards') {
// Forwards direction
let previousSuspenseListRow: null | SuspenseListRow = null;
for (let i = 0; i < totalChildren; i++) {
const node = rows[i];
if (__DEV__) {
warnForMissingKey(request, task, node);
}
task.row = previousSuspenseListRow = createSuspenseListRow(
previousSuspenseListRow,
);
task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);
renderNode(request, task, node, i);
if (--previousSuspenseListRow.pendingTasks === 0) {
finishSuspenseListRow(request, previousSuspenseListRow);
}
}
} else {
// For backwards direction we need to do things a bit differently.
// We give each row its own segment so that we can render the content in
// reverse order but still emit it in the right order when we flush.
const parentSegment = task.blockedSegment;
const childIndex = parentSegment.children.length;
const insertionIndex = parentSegment.chunks.length;
let previousSuspenseListRow: null | SuspenseListRow = null;
for (let i = totalChildren - 1; i >= 0; i--) {
const node = rows[i];
task.row = previousSuspenseListRow = createSuspenseListRow(
previousSuspenseListRow,
);
task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);
const newSegment = createPendingSegment(
request,
insertionIndex,
null,
task.formatContext,
// Assume we are text embedded at the trailing edges
i === 0 ? parentSegment.lastPushedText : true,
true,
);
// Insert in the beginning of the sequence, which will insert before any previous rows.
parentSegment.children.splice(childIndex, 0, newSegment);
task.blockedSegment = newSegment;
if (__DEV__) {
warnForMissingKey(request, task, node);
}
try {
renderNode(request, task, node, i);
pushSegmentFinale(
newSegment.chunks,
request.renderState,
newSegment.lastPushedText,
newSegment.textEmbedded,
);
newSegment.status = COMPLETED;
finishedSegment(request, task.blockedBoundary, newSegment);
if (--previousSuspenseListRow.pendingTasks === 0) {
finishSuspenseListRow(request, previousSuspenseListRow);
}
} catch (thrownValue: mixed) {
if (request.status === ABORTING) {
newSegment.status = ABORTED;
} else {
newSegment.status = ERRORED;
}
throw thrownValue;
}
}
task.blockedSegment = parentSegment;
// Reset lastPushedText for current Segment since the new Segments "consumed" it
parentSegment.lastPushedText = false;
}
}
// Because this context is always set right before rendering every child, we
// only need to reset it to the previous value at the very end.
task.treeContext = prevTreeContext;
task.row = prevRow;
task.keyPath = prevKeyPath;
if (__DEV__) {
task.componentStack = previousComponentStack;
task.debugTask = previousDebugTask;
}
}
function renderSuspenseList(
request: Request,
task: Task,
keyPath: KeyNode,
props: SuspenseListProps,
): void {
const children: any = props.children;
const revealOrder: SuspenseListRevealOrder = props.revealOrder;
// TODO: Support tail hidden/collapsed modes.
// const tailMode: SuspenseListTailMode = props.tail;
if (revealOrder === 'forwards' || revealOrder === 'backwards') {
// For ordered reveal, we need to produce rows from the children.
if (isArray(children)) {
renderSuspenseListRows(request, task, keyPath, children, revealOrder);
return;
}
const iteratorFn = getIteratorFn(children);
if (iteratorFn) {
const iterator = iteratorFn.call(children);
if (iterator) {
if (__DEV__) {
validateIterable(task, children, -1, iterator, iteratorFn);
}
// TODO: We currently use the same id algorithm as regular nodes
// but we need a new algorithm for SuspenseList that doesn't require
// a full set to be loaded up front to support Async Iterable.
// When we have that, we shouldn't buffer anymore.
let step = iterator.next();
if (!step.done) {
const rows = [];
do {
rows.push(step.value);
step = iterator.next();
} while (!step.done);
renderSuspenseListRows(request, task, keyPath, children, revealOrder);
}
return;
}
}
if (
enableAsyncIterableChildren &&
typeof (children: any)[ASYNC_ITERATOR] === 'function'
) {
const iterator: AsyncIterator<ReactNodeList> = (children: any)[
ASYNC_ITERATOR
]();
if (iterator) {
if (__DEV__) {
validateAsyncIterable(task, (children: any), -1, iterator);
}
// TODO: Update the task.children to be the iterator to avoid asking
// for new iterators, but we currently warn for rendering these
// so needs some refactoring to deal with the warning.
// Restore the thenable state before resuming.
const prevThenableState = task.thenableState;
task.thenableState = null;
prepareToUseThenableState(prevThenableState);
// We need to know how many total rows are in this set, so that we
// can allocate enough id slots to acommodate them. So we must exhaust
// the iterator before we start recursively rendering the rows.
// TODO: This is not great but I think it's inherent to the id
// generation algorithm.
const rows = [];
let done = false;
if (iterator === children) {
// If it's an iterator we need to continue reading where we left
// off. We can do that by reading the first few rows from the previous
// thenable state.
// $FlowFixMe
let step = readPreviousThenableFromState();
while (step !== undefined) {
if (step.done) {
done = true;
break;
}
rows.push(step.value);
step = readPreviousThenableFromState();
}
}
if (!done) {
let step = unwrapThenable(iterator.next());
while (!step.done) {
rows.push(step.value);
step = unwrapThenable(iterator.next());
}
}
renderSuspenseListRows(request, task, keyPath, rows, revealOrder);
return;
}
}
// This case will warn on the client. It's the same as independent revealOrder.
}
if (revealOrder === 'together') {
// TODO
}
// For other reveal order modes, we just render it as a fragment.
const prevKeyPath = task.keyPath;
task.keyPath = keyPath;
renderNodeDestructive(request, task, children, -1);
task.keyPath = prevKeyPath;
}
function renderPreamble(
request: Request,
task: Task,
@@ -1613,6 +2009,7 @@ function renderPreamble(
task.formatContext,
task.context,
task.treeContext,
task.row,
task.componentStack,
!disableLegacyContext ? task.legacyContext : emptyContextObject,
__DEV__ ? task.debugTask : null,
@@ -2284,6 +2681,7 @@ function renderViewTransition(
request.resumableState,
);
task.formatContext = getViewTransitionFormatContext(
request.resumableState,
prevContext,
getViewTransitionClassName(props.default, props.update),
getViewTransitionClassName(props.default, props.enter),
@@ -2361,11 +2759,7 @@ function renderElement(
return;
}
case REACT_SUSPENSE_LIST_TYPE: {
// TODO: SuspenseList should control the boundaries.
const prevKeyPath = task.keyPath;
task.keyPath = keyPath;
renderNodeDestructive(request, task, props.children, -1);
task.keyPath = prevKeyPath;
renderSuspenseList(request, task, keyPath, props);
return;
}
case REACT_VIEW_TRANSITION_TYPE: {
@@ -3515,6 +3909,7 @@ function spawnNewSuspendedReplayTask(
task.formatContext,
task.context,
task.treeContext,
task.row,
task.componentStack,
!disableLegacyContext ? task.legacyContext : emptyContextObject,
__DEV__ ? task.debugTask : null,
@@ -3556,6 +3951,7 @@ function spawnNewSuspendedRenderTask(
task.formatContext,
task.context,
task.treeContext,
task.row,
task.componentStack,
!disableLegacyContext ? task.legacyContext : emptyContextObject,
__DEV__ ? task.debugTask : null,
@@ -3864,10 +4260,19 @@ function erroredReplay(
function erroredTask(
request: Request,
boundary: Root | SuspenseBoundary,
row: null | SuspenseListRow,
error: mixed,
errorInfo: ThrownInfo,
debugTask: null | ConsoleTask,
) {
if (row !== null) {
if (--row.pendingTasks === 0) {
finishSuspenseListRow(request, row);
}
}
request.allPendingTasks--;
// Report the error to a global handler.
let errorDigest;
// We don't handle halts here because we only halt when prerendering and
@@ -3919,7 +4324,6 @@ function erroredTask(
}
}
request.allPendingTasks--;
if (request.allPendingTasks === 0) {
completeAll(request);
}
@@ -3934,7 +4338,7 @@ function abortTaskSoft(this: Request, task: Task): void {
const segment = task.blockedSegment;
if (segment !== null) {
segment.status = ABORTED;
finishedTask(request, boundary, segment);
finishedTask(request, boundary, task.row, segment);
}
}
@@ -3948,6 +4352,7 @@ function abortRemainingSuspenseBoundary(
): void {
const resumedBoundary = createSuspenseBoundary(
request,
null,
new Set(),
null,
null,
@@ -4047,6 +4452,13 @@ function abortTask(task: Task, request: Request, error: mixed): void {
segment.status = ABORTED;
}
const row = task.row;
if (row !== null) {
if (--row.pendingTasks === 0) {
finishSuspenseListRow(request, row);
}
}
const errorInfo = getThrownInfo(task.componentStack);
if (boundary === null) {
@@ -4069,7 +4481,7 @@ function abortTask(task: Task, request: Request, error: mixed): void {
// we just need to mark it as postponed.
logPostpone(request, postponeInstance.message, errorInfo, null);
trackPostpone(request, trackedPostpones, task, segment);
finishedTask(request, null, segment);
finishedTask(request, null, row, segment);
} else {
const fatal = new Error(
'The render was aborted with postpone when the shell is incomplete. Reason: ' +
@@ -4088,7 +4500,7 @@ function abortTask(task: Task, request: Request, error: mixed): void {
// We log the error but we still resolve the prerender
logRecoverableError(request, error, errorInfo, null);
trackPostpone(request, trackedPostpones, task, segment);
finishedTask(request, null, segment);
finishedTask(request, null, row, segment);
} else {
logRecoverableError(request, error, errorInfo, null);
fatalError(request, error, errorInfo, null);
@@ -4160,7 +4572,7 @@ function abortTask(task: Task, request: Request, error: mixed): void {
abortTask(fallbackTask, request, error),
);
boundary.fallbackAbortableTasks.clear();
return finishedTask(request, boundary, segment);
return finishedTask(request, boundary, row, segment);
}
}
boundary.status = CLIENT_RENDERED;
@@ -4177,7 +4589,7 @@ function abortTask(task: Task, request: Request, error: mixed): void {
logPostpone(request, postponeInstance.message, errorInfo, null);
if (request.trackedPostpones !== null && segment !== null) {
trackPostpone(request, request.trackedPostpones, task, segment);
finishedTask(request, task.blockedBoundary, segment);
finishedTask(request, task.blockedBoundary, row, segment);
// If this boundary was still pending then we haven't already cancelled its fallbacks.
// We'll need to abort the fallbacks, which will also error that parent boundary.
@@ -4333,8 +4745,14 @@ function finishedSegment(
function finishedTask(
request: Request,
boundary: Root | SuspenseBoundary,
row: null | SuspenseListRow,
segment: null | Segment,
) {
if (row !== null) {
if (--row.pendingTasks === 0) {
finishSuspenseListRow(request, row);
}
}
request.allPendingTasks--;
if (boundary === null) {
if (segment !== null && segment.parentFlushed) {
@@ -4383,6 +4801,13 @@ function finishedTask(
if (!isEligibleForOutlining(request, boundary)) {
boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
boundary.fallbackAbortableTasks.clear();
const boundaryRow = boundary.row;
if (boundaryRow !== null) {
// If we aren't eligible for outlining, we don't have to wait until we flush it.
if (--boundaryRow.pendingTasks === 0) {
finishSuspenseListRow(request, boundaryRow);
}
}
}
if (
@@ -4481,7 +4906,7 @@ function retryRenderTask(
task.abortSet.delete(task);
segment.status = COMPLETED;
finishedSegment(request, task.blockedBoundary, segment);
finishedTask(request, task.blockedBoundary, segment);
finishedTask(request, task.blockedBoundary, task.row, segment);
} catch (thrownValue: mixed) {
resetHooksState();
@@ -4534,7 +4959,7 @@ function retryRenderTask(
}
trackPostpone(request, trackedPostpones, task, segment);
finishedTask(request, task.blockedBoundary, segment);
finishedTask(request, task.blockedBoundary, task.row, segment);
return;
}
@@ -4568,7 +4993,7 @@ function retryRenderTask(
__DEV__ ? task.debugTask : null,
);
trackPostpone(request, trackedPostpones, task, segment);
finishedTask(request, task.blockedBoundary, segment);
finishedTask(request, task.blockedBoundary, task.row, segment);
return;
}
}
@@ -4580,6 +5005,7 @@ function retryRenderTask(
erroredTask(
request,
task.blockedBoundary,
task.row,
x,
errorInfo,
__DEV__ ? task.debugTask : null,
@@ -4627,7 +5053,7 @@ function retryReplayTask(request: Request, task: ReplayTask): void {
task.replay.pendingTasks--;
task.abortSet.delete(task);
finishedTask(request, task.blockedBoundary, null);
finishedTask(request, task.blockedBoundary, task.row, null);
} catch (thrownValue) {
resetHooksState();
@@ -4939,6 +5365,16 @@ function flushSegment(
// Emit a client rendered suspense boundary wrapper.
// We never queue the inner boundary so we'll never emit its content or partial segments.
const row = boundary.row;
if (row !== null) {
// Since this boundary end up client rendered, we can unblock future suspense list rows.
// This means that they may appear out of order if the future rows succeed but this is
// a client rendered row.
if (--row.pendingTasks === 0) {
finishSuspenseListRow(request, row);
}
}
if (__DEV__) {
writeStartClientRenderedSuspenseBoundary(
destination,
@@ -5027,6 +5463,16 @@ function flushSegment(
if (hoistableState) {
hoistHoistables(hoistableState, boundary.contentState);
}
const row = boundary.row;
if (row !== null && isEligibleForOutlining(request, boundary)) {
// Once we have written the boundary, we can unblock the row and let future
// rows be written. This may schedule new completed boundaries.
if (--row.pendingTasks === 0) {
finishSuspenseListRow(request, row);
}
}
// We can inline this boundary's content as a complete boundary.
writeStartCompletedSuspenseBoundary(destination, request.renderState);
@@ -5105,6 +5551,15 @@ function flushCompletedBoundary(
}
completedSegments.length = 0;
const row = boundary.row;
if (row !== null && isEligibleForOutlining(request, boundary)) {
// Once we have written the boundary, we can unblock the row and let future
// rows be written. This may schedule new completed boundaries.
if (--row.pendingTasks === 0) {
finishSuspenseListRow(request, row);
}
}
writeHoistablesForBoundary(
destination,
boundary.contentState,
@@ -5297,6 +5752,7 @@ function flushCompletedQueues(
// Next we check the completed boundaries again. This may have had
// boundaries added to it in case they were too larged to be inlined.
// SuspenseListRows might have been unblocked as well.
// New ones might be added in this loop.
const largeBoundaries = request.completedBoundaries;
for (i = 0; i < largeBoundaries.length; i++) {
+24
View File
@@ -290,6 +290,30 @@ export type SuspenseProps = {
name?: string,
};
export type SuspenseListRevealOrder =
| 'forwards'
| 'backwards'
| 'together'
| void;
export type SuspenseListTailMode = 'collapsed' | 'hidden' | void;
type DirectionalSuspenseListProps = {
children?: ReactNodeList,
revealOrder: 'forwards' | 'backwards',
tail?: SuspenseListTailMode,
};
type NonDirectionalSuspenseListProps = {
children?: ReactNodeList,
revealOrder?: 'together' | void,
tail?: void,
};
export type SuspenseListProps =
| DirectionalSuspenseListProps
| NonDirectionalSuspenseListProps;
export type TracingMarkerProps = {
name: string,
children?: ReactNodeList,
@@ -25,6 +25,10 @@ const config = [
entry: 'ReactDOMFizzInlineCompleteBoundary.js',
exportName: 'completeBoundary',
},
{
entry: 'ReactDOMFizzInlineCompleteBoundaryUpgradeToViewTransitions.js',
exportName: 'completeBoundaryUpgradeToViewTransitions',
},
{
entry: 'ReactDOMFizzInlineCompleteBoundaryWithStyles.js',
exportName: 'completeBoundaryWithStyles',