Skip to content

[DevTools] Send suspense nodes to frontend store #34070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
384 changes: 276 additions & 108 deletions packages/react-devtools-shared/src/backend/fiber/renderer.js

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions packages/react-devtools-shared/src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ export const TREE_OPERATION_UPDATE_TREE_BASE_DURATION = 4;
export const TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS = 5;
export const TREE_OPERATION_REMOVE_ROOT = 6;
export const TREE_OPERATION_SET_SUBTREE_MODE = 7;
export const SUSPENSE_TREE_OPERATION_ADD = 8;
export const SUSPENSE_TREE_OPERATION_REMOVE = 9;
export const SUSPENSE_TREE_OPERATION_REORDER_CHILDREN = 10;

export const PROFILING_FLAG_BASIC_SUPPORT = 0b01;
export const PROFILING_FLAG_TIMELINE_SUPPORT = 0b10;
Expand Down
227 changes: 218 additions & 9 deletions packages/react-devtools-shared/src/devtools/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ import {
TREE_OPERATION_SET_SUBTREE_MODE,
TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS,
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
SUSPENSE_TREE_OPERATION_ADD,
SUSPENSE_TREE_OPERATION_REMOVE,
SUSPENSE_TREE_OPERATION_REORDER_CHILDREN,
} from '../constants';
import {ElementTypeRoot} from '../frontend/types';
import {
Expand All @@ -44,6 +47,7 @@ import type {
Element,
ComponentFilter,
ElementType,
Suspense,
} from 'react-devtools-shared/src/frontend/types';
import type {
FrontendBridge,
Expand Down Expand Up @@ -100,11 +104,12 @@ export default class Store extends EventEmitter<{
hookSettings: [$ReadOnly<DevToolsHookSettings>],
hostInstanceSelected: [Element['id']],
settingsUpdated: [$ReadOnly<DevToolsHookSettings>],
mutated: [[Array<number>, Map<number, number>]],
mutated: [[Array<Element['id']>, Map<Element['id'], Element['id']>]],
recordChangeDescriptions: [],
roots: [],
rootSupportsBasicProfiling: [],
rootSupportsTimelineProfiling: [],
suspenseTreeMutated: [],
supportsNativeStyleEditor: [],
supportsReloadAndProfile: [],
unsupportedBridgeProtocolDetected: [],
Expand All @@ -127,16 +132,20 @@ export default class Store extends EventEmitter<{
_componentFilters: Array<ComponentFilter>;

// Map of ID to number of recorded error and warning message IDs.
_errorsAndWarnings: Map<number, {errorCount: number, warningCount: number}> =
new Map();
_errorsAndWarnings: Map<
Element['id'],
{errorCount: number, warningCount: number},
> = new Map();

// At least one of the injected renderers contains (DEV only) owner metadata.
_hasOwnerMetadata: boolean = false;

// Map of ID to (mutable) Element.
// Elements are mutated to avoid excessive cloning during tree updates.
// The InspectedElement Suspense cache also relies on this mutability for its WeakMap usage.
_idToElement: Map<number, Element> = new Map();
_idToElement: Map<Element['id'], Element> = new Map();

_idToSuspense: Map<Suspense['id'], Suspense> = new Map();

// Should the React Native style editor panel be shown?
_isNativeStyleEditorSupported: boolean = false;
Expand All @@ -149,7 +158,7 @@ export default class Store extends EventEmitter<{

// Map of element (id) to the set of elements (ids) it owns.
// This map enables getOwnersListForElement() to avoid traversing the entire tree.
_ownersMap: Map<number, Set<number>> = new Map();
_ownersMap: Map<Element['id'], Set<Element['id']>> = new Map();

_profilerStore: ProfilerStore;

Expand All @@ -158,15 +167,16 @@ export default class Store extends EventEmitter<{
// Incremented each time the store is mutated.
// This enables a passive effect to detect a mutation between render and commit phase.
_revision: number = 0;
_revisionSuspense: number = 0;

// This Array must be treated as immutable!
// Passive effects will check it for changes between render and mount.
_roots: $ReadOnlyArray<number> = [];
_roots: $ReadOnlyArray<Element['id']> = [];

_rootIDToCapabilities: Map<number, Capabilities> = new Map();
_rootIDToCapabilities: Map<Element['id'], Capabilities> = new Map();

// Renderer ID is needed to support inspection fiber props, state, and hooks.
_rootIDToRendererID: Map<number, number> = new Map();
_rootIDToRendererID: Map<Element['id'], number> = new Map();

// These options may be initially set by a configuration option when constructing the Store.
_supportsInspectMatchingDOMElement: boolean = false;
Expand Down Expand Up @@ -439,6 +449,9 @@ export default class Store extends EventEmitter<{
get revision(): number {
return this._revision;
}
get revisionSuspense(): number {
return this._revisionSuspense;
}

get rootIDToRendererID(): Map<number, number> {
return this._rootIDToRendererID;
Expand Down Expand Up @@ -595,6 +608,16 @@ export default class Store extends EventEmitter<{
return element;
}

getSuspenseByID(id: Suspense['id']): Suspense | null {
const suspense = this._idToSuspense.get(id);
if (suspense === undefined) {
console.warn(`No suspense found with id "${id}"`);
return null;
}

return suspense;
}

// Returns a tuple of [id, index]
getElementsWithErrorsAndWarnings(): ErrorAndWarningTuples {
if (!this._shouldShowWarningsAndErrors) {
Expand Down Expand Up @@ -989,6 +1012,7 @@ export default class Store extends EventEmitter<{

let haveRootsChanged = false;
let haveErrorsOrWarningsChanged = false;
let hasSuspenseTreeChanged = false;

// The first two values are always rendererID and rootID
const rendererID = operations[0];
Expand Down Expand Up @@ -1369,7 +1393,7 @@ export default class Store extends EventEmitter<{
// The profiler UI uses them lazily in order to generate the tree.
i += 3;
break;
case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS:
case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS: {
const id = operations[i + 1];
const errorCount = operations[i + 2];
const warningCount = operations[i + 3];
Expand All @@ -1383,6 +1407,184 @@ export default class Store extends EventEmitter<{
}
haveErrorsOrWarningsChanged = true;
break;
}
case SUSPENSE_TREE_OPERATION_ADD: {
const id = operations[i + 1];
const parentID = operations[i + 2];
const nameStringID = operations[i + 3];
let name = stringTable[nameStringID];

if (this._idToSuspense.has(id)) {
this._throwAndEmitError(
Error(
`Cannot add suspense node "${id}" because a suspense node with that id is already in the Store.`,
),
);
}

const element = this._idToElement.get(id);
if (element === undefined) {
this._throwAndEmitError(
Error(
`Cannot add suspense node "${id}" because no matching element was found in the Store.`,
),
);
} else {
if (name === null) {
// The boundary isn't explicitly named.
// Pick a sensible default.
// TODO: Use key
const owner = this._idToElement.get(element.ownerID);
if (owner !== undefined) {
// TODO: This is clowny
name = `${owner.displayName || 'Unknown'}>?`;
}
}
}

if (__DEBUG__) {
debug('Suspense Add', `node ${id} as child of ${parentID}`);
}

if (parentID !== 0) {
const parentSuspense = this._idToSuspense.get(parentID);
if (parentSuspense === undefined) {
this._throwAndEmitError(
Error(
`Cannot add suspense child "${id}" to parent suspense "${parentID}" because parent suspense node was not found in the Store.`,
),
);

break;
}

parentSuspense.children.push(id);
}

if (name === null) {
name = 'Unknown';
}

this._idToSuspense.set(id, {
id,
parentID,
children: [],
name,
});

i += 4;

hasSuspenseTreeChanged = true;
break;
}
case SUSPENSE_TREE_OPERATION_REMOVE: {
const removeLength = operations[i + 1];
i += 2;

for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) {
const id = operations[i];
const suspense = this._idToSuspense.get(id);

if (suspense === undefined) {
this._throwAndEmitError(
Error(
`Cannot remove suspense node "${id}" because no matching node was found in the Store.`,
),
);

break;
}

i += 1;

const {children, parentID} = suspense;
if (children.length > 0) {
this._throwAndEmitError(
Error(`Suspense node "${id}" was removed before its children.`),
);
}

this._idToSuspense.delete(id);

let parentSuspense: ?Suspense = null;
if (parentID === 0) {
if (__DEBUG__) {
debug('Suspense remove', `node ${id} root`);
}
} else {
if (__DEBUG__) {
debug('Suspense Remove', `node ${id} from parent ${parentID}`);
}

parentSuspense = this._idToSuspense.get(parentID);
if (parentSuspense === undefined) {
this._throwAndEmitError(
Error(
`Cannot remove suspense node "${id}" from parent "${parentID}" because no matching node was found in the Store.`,
),
);

break;
}

const index = parentSuspense.children.indexOf(id);
parentSuspense.children.splice(index, 1);
}
}

hasSuspenseTreeChanged = true;
break;
}
case SUSPENSE_TREE_OPERATION_REORDER_CHILDREN: {
const id = operations[i + 1];
const numChildren = operations[i + 2];
i += 3;

const suspense = this._idToSuspense.get(id);
if (suspense === undefined) {
this._throwAndEmitError(
Error(
`Cannot reorder children for suspense node "${id}" because no matching node was found in the Store.`,
),
);

break;
}

const children = suspense.children;
if (children.length !== numChildren) {
this._throwAndEmitError(
Error(
`Suspense children cannot be added or removed during a reorder operation.`,
),
);
}

for (let j = 0; j < numChildren; j++) {
const childID = operations[i + j];
children[j] = childID;
if (__DEV__) {
// This check is more expensive so it's gated by __DEV__.
const childSuspense = this._idToSuspense.get(childID);
if (childSuspense == null || childSuspense.parentID !== id) {
console.error(
`Suspense children cannot be added or removed during a reorder operation.`,
);
}
}
}
i += numChildren;

if (__DEBUG__) {
debug(
'Re-order',
`Suspense node ${id} children ${children.join(',')}`,
);
}

hasSuspenseTreeChanged = true;
break;
}
default:
this._throwAndEmitError(
new UnsupportedBridgeOperationError(
Expand All @@ -1393,6 +1595,9 @@ export default class Store extends EventEmitter<{
}

this._revision++;
if (hasSuspenseTreeChanged) {
this._revisionSuspense++;
}

// Any time the tree changes (e.g. elements added, removed, or reordered) cached indices may be invalid.
this._cachedErrorAndWarningTuples = null;
Expand Down Expand Up @@ -1451,6 +1656,10 @@ export default class Store extends EventEmitter<{
}
}

if (hasSuspenseTreeChanged) {
this.emit('suspenseTreeMutated');
}

if (__DEBUG__) {
console.log(printStore(this, true));
console.groupEnd();
Expand Down
Loading
Loading