Remove Reconciler fork (1/2) (#25774)
We've heard from multiple contributors that the Reconciler forking mechanism was confusing and/or annoying to deal with. Since it's currently unused and there's no immediate plans to start using it again, this removes the forking. Fully removing the fork is split into 2 steps to preserve file history: **This PR** - remove `enableNewReconciler` feature flag. - remove `unstable_isNewReconciler` export - remove eslint rules for cross fork imports - remove `*.new.js` files and update imports - merge non-suffixed files into `*.old` files where both exist (sometimes types were defined there) **#25775** - rename `*.old` files
Jan Kassens committed
Dec 1, 2022 at 23:06 UTC
420f0b7fa1fcc609fc7b438c4599d0f76fab4bc0
110 files changed
+71
-33065
.circleci/config.yml
-34
@@ -462,35 +462,6 @@ jobs:
462
cp ./scripts/release/ci-npmrc ~/.npmrc
463
scripts/release/publish.js --ci --tags << parameters.dist_tag >>
464
465
- # We don't always keep the reconciler forks in sync (otherwise it we wouldn't
466
- # have forked it) but during periods when they are meant to be in sync, we
467
- # use this job to confirm there are no differences.
468
- sync_reconciler_forks:
469
- docker: *docker
470
- environment: *environment
471
- steps:
472
- - checkout
473
- - *restore_node_modules
474
- - run:
475
- name: Fetch revisions that contain an intentional fork
476
- # This will fetch each revision listed in the `forked-revisions` file,
477
- # which may be necessary if it's not part of main. For example, it
478
- # may have been part of a PR branch that was squashed on merge.
479
- command: |
480
- cut -d " " -f 1 scripts/merge-fork/forked-revisions | xargs -r git fetch origin
481
- - run:
482
- name: Revert forked revisions
483
- # This will revert the changes without committing. At the end, it's
484
- # expected that both forks will be identical.
485
- command: |
486
- cut -d " " -f 1 scripts/merge-fork/forked-revisions | xargs -r git revert --no-commit
487
- - run:
488
- name: Confirm reconciler forks are the same
489
- command: |
490
- yarn replace-fork
491
- git diff --quiet || (echo "Reconciler forks are not the same! Run yarn replace-fork. Or, if this was intentional, add the commit SHA to scripts/merge-fork/forked-revisions." && false)
492
-
493
-
465
workflows:
466
version: 2
467
@@ -506,11 +477,6 @@ workflows:
477
- yarn_flow:
478
requires:
479
- setup
509
- # NOTE: This job is only enabled when we want the forks to be in sync.
510
- # When the forks intentionally diverge, comment out the job to disable it.
511
- - sync_reconciler_forks:
512
- requires:
513
- - setup
480
- check_generated_fizz_runtime:
481
requires:
482
- setup
.eslintrc.js
-8
@@ -112,14 +112,6 @@ module.exports = {
112
'react-internal/no-to-warn-dev-within-to-throw': ERROR,
113
'react-internal/warning-args': ERROR,
114
'react-internal/no-production-logging': ERROR,
115
- 'react-internal/no-cross-fork-imports': ERROR,
116
- 'react-internal/no-cross-fork-types': [
117
- ERROR,
118
- {
119
- old: [],
120
- new: [],
121
- },
122
- ],
115
},
116
117
overrides: [
package.json
-2
@@ -140,8 +140,6 @@
140
"prettier": "node ./scripts/prettier/index.js write-changed",
141
"prettier-all": "node ./scripts/prettier/index.js write",
142
"version-check": "node ./scripts/tasks/version-check.js",
143
- "merge-fork": "node ./scripts/merge-fork/merge-fork.js",
144
- "replace-fork": "node ./scripts/merge-fork/replace-fork.js",
143
"publish-prereleases": "node ./scripts/release/publish-using-ci-workflow.js",
144
"download-build": "node ./scripts/release/download-experimental-build.js",
145
"download-build-for-head": "node ./scripts/release/download-experimental-build.js --commit=$(git rev-parse HEAD)",
packages/react-art/src/ReactART.js
+1
-1
@@ -12,7 +12,7 @@ import {
12
createContainer,
13
updateContainer,
14
injectIntoDevTools,
15
-} from 'react-reconciler/src/ReactFiberReconciler';
15
+} from 'react-reconciler/src/ReactFiberReconciler.old';
16
import Transform from 'art/core/transform';
17
import Mode from 'art/modes/current';
18
import FastNoSideEffects from 'art/modes/fast-noSideEffects';
packages/react-art/src/ReactARTHostConfig.js
+1
-1
@@ -10,7 +10,7 @@ import Mode from 'art/modes/current';
10
11
import {TYPES, EVENT_TYPES, childrenAsString} from './ReactARTInternals';
12
13
-import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities';
13
+import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
14
15
const pooledTransform = new Transform();
16
packages/react-dom-bindings/src/client/ReactDOMFloatClient.js
+1
-1
@@ -29,7 +29,7 @@ import {
29
markNodeAsResource,
30
} from './ReactDOMComponentTree';
31
import {HTML_NAMESPACE, SVG_NAMESPACE} from '../shared/DOMNamespaces';
32
-import {getCurrentRootHostContainer} from 'react-reconciler/src/ReactFiberHostContext';
32
+import {getCurrentRootHostContainer} from 'react-reconciler/src/ReactFiberHostContext.old';
33
34
// The resource types we support. currently they match the form for the as argument.
35
// In the future this may need to change, especially when modules / scripts are supported
packages/react-dom-bindings/src/client/ReactDOMHostConfig.js
+2
-2
@@ -7,7 +7,7 @@
7
* @flow
8
*/
9
10
-import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities';
10
+import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
11
import type {DOMEventName} from '../events/DOMEventNames';
12
import type {Fiber, FiberRoot} from 'react-reconciler/src/ReactInternalTypes';
13
import type {
@@ -81,7 +81,7 @@ import {
81
} from 'react-reconciler/src/ReactWorkTags';
82
import {listenToAllSupportedEvents} from '../events/DOMPluginEventSystem';
83
84
-import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities';
84
+import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
85
86
// TODO: Remove this deep import when we delete the legacy root API
87
import {ConcurrentMode, NoMode} from 'react-reconciler/src/ReactTypeOfMode';
packages/react-dom-bindings/src/events/ReactDOMEventListener.js
+2
-2
@@ -7,7 +7,7 @@
7
* @flow
8
*/
9
10
-import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities';
10
+import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
11
import type {AnyNativeEvent} from '../events/PluginModuleType';
12
import type {Fiber, FiberRoot} from 'react-reconciler/src/ReactInternalTypes';
13
import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig';
@@ -52,7 +52,7 @@ import {
52
IdleEventPriority,
53
getCurrentUpdatePriority,
54
setCurrentUpdatePriority,
55
-} from 'react-reconciler/src/ReactEventPriorities';
55
+} from 'react-reconciler/src/ReactEventPriorities.old';
56
import ReactSharedInternals from 'shared/ReactSharedInternals';
57
import {isRootDehydrated} from 'react-reconciler/src/ReactFiberShellHydration';
58
packages/react-dom-bindings/src/events/ReactDOMEventReplaying.js
+2
-2
@@ -12,7 +12,7 @@ import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig';
12
import type {DOMEventName} from '../events/DOMEventNames';
13
import type {EventSystemFlags} from './EventSystemFlags';
14
import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes';
15
-import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities';
15
+import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
16
17
import {enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay} from 'shared/ReactFeatureFlags';
18
import {
@@ -35,7 +35,7 @@ import {
35
getClosestInstanceFromNode,
36
} from '../client/ReactDOMComponentTree';
37
import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags';
38
-import {isHigherEventPriority} from 'react-reconciler/src/ReactEventPriorities';
38
+import {isHigherEventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
39
import {isRootDehydrated} from 'react-reconciler/src/ReactFiberShellHydration';
40
41
let _attemptSynchronousHydration: (fiber: Object) => void;
packages/react-dom/index.classic.fb.js
-1
@@ -30,7 +30,6 @@ export {
30
unstable_batchedUpdates,
31
unstable_createEventHandle,
32
unstable_flushControlled,
33
- unstable_isNewReconciler,
33
unstable_renderSubtreeIntoContainer,
34
unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority.
35
preinit,
packages/react-dom/index.js
-1
@@ -22,7 +22,6 @@ export {
22
unstable_batchedUpdates,
23
unstable_createEventHandle,
24
unstable_flushControlled,
25
- unstable_isNewReconciler,
25
unstable_renderSubtreeIntoContainer,
26
unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority.
27
preinit,
packages/react-dom/index.modern.fb.js
-1
@@ -16,7 +16,6 @@ export {
16
unstable_batchedUpdates,
17
unstable_createEventHandle,
18
unstable_flushControlled,
19
- unstable_isNewReconciler,
19
unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority.
20
preinit,
21
preload,
packages/react-dom/src/__tests__/react-dom-server-rendering-stub-test.js
-1
@@ -36,7 +36,6 @@ describe('react-dom-server-rendering-stub', () => {
36
expect(ReactDOM.unstable_batchedUpdates).toBe(undefined);
37
expect(ReactDOM.unstable_createEventHandle).toBe(undefined);
38
expect(ReactDOM.unstable_flushControlled).toBe(undefined);
39
- expect(ReactDOM.unstable_isNewReconciler).toBe(undefined);
39
expect(ReactDOM.unstable_renderSubtreeIntoContainer).toBe(undefined);
40
expect(ReactDOM.unstable_runWithPriority).toBe(undefined);
41
});
packages/react-dom/src/client/ReactDOM.js
+2
-5
@@ -43,15 +43,14 @@ import {
43
attemptDiscreteHydration,
44
attemptContinuousHydration,
45
attemptHydrationAtCurrentPriority,
46
-} from 'react-reconciler/src/ReactFiberReconciler';
46
+} from 'react-reconciler/src/ReactFiberReconciler.old';
47
import {
48
runWithPriority,
49
getCurrentUpdatePriority,
50
-} from 'react-reconciler/src/ReactEventPriorities';
50
+} from 'react-reconciler/src/ReactEventPriorities.old';
51
import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal';
52
import {canUseDOM} from 'shared/ExecutionEnvironment';
53
import ReactVersion from 'shared/ReactVersion';
54
-import {enableNewReconciler} from 'shared/ReactFeatureFlags';
54
55
import {
56
getClosestInstanceFromNode,
@@ -256,5 +255,3 @@ if (__DEV__) {
255
}
256
}
257
}
259
-
260
-export const unstable_isNewReconciler = enableNewReconciler;
packages/react-dom/src/client/ReactDOMLegacy.js
+1
-1
@@ -37,7 +37,7 @@ import {
37
getPublicRootInstance,
38
findHostInstance,
39
findHostInstanceWithWarning,
40
-} from 'react-reconciler/src/ReactFiberReconciler';
40
+} from 'react-reconciler/src/ReactFiberReconciler.old';
41
import {LegacyRoot} from 'react-reconciler/src/ReactRootTags';
42
import getComponentNameFromType from 'shared/getComponentNameFromType';
43
import ReactSharedInternals from 'shared/ReactSharedInternals';
packages/react-dom/src/client/ReactDOMRoot.js
+1
-1
@@ -76,7 +76,7 @@ import {
76
registerMutableSourceForHydration,
77
flushSync,
78
isAlreadyRendering,
79
-} from 'react-reconciler/src/ReactFiberReconciler';
79
+} from 'react-reconciler/src/ReactFiberReconciler.old';
80
import {ConcurrentRoot} from 'react-reconciler/src/ReactRootTags';
81
82
/* global reportError */
packages/react-dom/unstable_testing.classic.fb.js
+1
-1
@@ -19,4 +19,4 @@ export {
19
findBoundingRects,
20
focusWithin,
21
observeVisibleRects,
22
-} from 'react-reconciler/src/ReactFiberReconciler';
22
+} from 'react-reconciler/src/ReactFiberReconciler.old';
packages/react-dom/unstable_testing.experimental.js
+1
-1
@@ -19,4 +19,4 @@ export {
19
findBoundingRects,
20
focusWithin,
21
observeVisibleRects,
22
-} from 'react-reconciler/src/ReactFiberReconciler';
22
+} from 'react-reconciler/src/ReactFiberReconciler.old';
packages/react-dom/unstable_testing.js
+1
-1
@@ -19,4 +19,4 @@ export {
19
findBoundingRects,
20
focusWithin,
21
observeVisibleRects,
22
-} from 'react-reconciler/src/ReactFiberReconciler';
22
+} from 'react-reconciler/src/ReactFiberReconciler.old';
packages/react-dom/unstable_testing.modern.fb.js
+1
-1
@@ -19,4 +19,4 @@ export {
19
findBoundingRects,
20
focusWithin,
21
observeVisibleRects,
22
-} from 'react-reconciler/src/ReactFiberReconciler';
22
+} from 'react-reconciler/src/ReactFiberReconciler.old';
packages/react-native-renderer/src/ReactFabric.js
+1
-1
@@ -22,7 +22,7 @@ import {
22
updateContainer,
23
injectIntoDevTools,
24
getPublicRootInstance,
25
-} from 'react-reconciler/src/ReactFiberReconciler';
25
+} from 'react-reconciler/src/ReactFiberReconciler.old';
26
27
import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal';
28
import {setBatchingImplementation} from './legacy-events/ReactGenericBatching';
packages/react-native-renderer/src/ReactFabricHostConfig.js
+1
-1
@@ -26,7 +26,7 @@ import {dispatchEvent} from './ReactFabricEventEmitter';
26
import {
27
DefaultEventPriority,
28
DiscreteEventPriority,
29
-} from 'react-reconciler/src/ReactEventPriorities';
29
+} from 'react-reconciler/src/ReactEventPriorities.old';
30
31
// Modules provided by RN:
32
import {
packages/react-native-renderer/src/ReactNativeHostConfig.js
+1
-1
@@ -24,7 +24,7 @@ import {
24
} from './ReactNativeComponentTree';
25
import ReactNativeFiberHostComponent from './ReactNativeFiberHostComponent';
26
27
-import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities';
27
+import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
28
29
const {get: getViewConfigForType} = ReactNativeViewConfigRegistry;
30
packages/react-native-renderer/src/ReactNativeRenderer.js
+1
-1
@@ -22,7 +22,7 @@ import {
22
updateContainer,
23
injectIntoDevTools,
24
getPublicRootInstance,
25
-} from 'react-reconciler/src/ReactFiberReconciler';
25
+} from 'react-reconciler/src/ReactFiberReconciler.old';
26
// TODO: direct imports like some-package/src/* are bad. Fix me.
27
import {getStackByFiberInDevAndProd} from 'react-reconciler/src/ReactFiberComponentStack';
28
import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal';
packages/react-noop-renderer/src/createReactNoop.js
+1
-1
@@ -18,7 +18,7 @@ import type {
18
Fiber,
19
TransitionTracingCallbacks,
20
} from 'react-reconciler/src/ReactInternalTypes';
21
-import type {UpdateQueue} from 'react-reconciler/src/ReactFiberClassUpdateQueue.new';
21
+import type {UpdateQueue} from 'react-reconciler/src/ReactFiberClassUpdateQueue';
22
import type {ReactNodeList} from 'shared/ReactTypes';
23
import type {RootTag} from 'react-reconciler/src/ReactRootTags';
24
packages/react-reconciler/index.js
+1
-1
@@ -7,4 +7,4 @@
7
* @flow
8
*/
9
10
-export * from './src/ReactFiberReconciler';
10
+export * from './src/ReactFiberReconciler.old';
packages/react-reconciler/src/ReactChildFiber.new.js
deleted
-1411
@@ -1,1411 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {ReactElement} from 'shared/ReactElementType';
11
-import type {ReactPortal} from 'shared/ReactTypes';
12
-import type {Fiber} from './ReactInternalTypes';
13
-import type {Lanes} from './ReactFiberLane.new';
14
-
15
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
16
-import {
17
- Placement,
18
- ChildDeletion,
19
- Forked,
20
- PlacementDEV,
21
-} from './ReactFiberFlags';
22
-import {
23
- getIteratorFn,
24
- REACT_ELEMENT_TYPE,
25
- REACT_FRAGMENT_TYPE,
26
- REACT_PORTAL_TYPE,
27
- REACT_LAZY_TYPE,
28
-} from 'shared/ReactSymbols';
29
-import {ClassComponent, HostText, HostPortal, Fragment} from './ReactWorkTags';
30
-import isArray from 'shared/isArray';
31
-import {warnAboutStringRefs} from 'shared/ReactFeatureFlags';
32
-import {checkPropStringCoercion} from 'shared/CheckStringCoercion';
33
-
34
-import {
35
- createWorkInProgress,
36
- resetWorkInProgress,
37
- createFiberFromElement,
38
- createFiberFromFragment,
39
- createFiberFromText,
40
- createFiberFromPortal,
41
-} from './ReactFiber.new';
42
-import {isCompatibleFamilyForHotReloading} from './ReactFiberHotReloading.new';
43
-import {StrictLegacyMode} from './ReactTypeOfMode';
44
-import {getIsHydrating} from './ReactFiberHydrationContext.new';
45
-import {pushTreeFork} from './ReactFiberTreeContext.new';
46
-
47
-let didWarnAboutMaps;
48
-let didWarnAboutGenerators;
49
-let didWarnAboutStringRefs;
50
-let ownerHasKeyUseWarning;
51
-let ownerHasFunctionTypeWarning;
52
-let warnForMissingKey = (child: mixed, returnFiber: Fiber) => {};
53
-
54
-if (__DEV__) {
55
- didWarnAboutMaps = false;
56
- didWarnAboutGenerators = false;
57
- didWarnAboutStringRefs = {};
58
-
59
- /**
60
- * Warn if there's no key explicitly set on dynamic arrays of children or
61
- * object keys are not valid. This allows us to keep track of children between
62
- * updates.
63
- */
64
- ownerHasKeyUseWarning = {};
65
- ownerHasFunctionTypeWarning = {};
66
-
67
- warnForMissingKey = (child: mixed, returnFiber: Fiber) => {
68
- if (child === null || typeof child !== 'object') {
69
- return;
70
- }
71
- if (!child._store || child._store.validated || child.key != null) {
72
- return;
73
- }
74
-
75
- if (typeof child._store !== 'object') {
76
- throw new Error(
77
- 'React Component in warnForMissingKey should have a _store. ' +
78
- 'This error is likely caused by a bug in React. Please file an issue.',
79
- );
80
- }
81
-
82
- // $FlowFixMe unable to narrow type from mixed to writable object
83
- child._store.validated = true;
84
-
85
- const componentName = getComponentNameFromFiber(returnFiber) || 'Component';
86
-
87
- if (ownerHasKeyUseWarning[componentName]) {
88
- return;
89
- }
90
- ownerHasKeyUseWarning[componentName] = true;
91
-
92
- console.error(
93
- 'Each child in a list should have a unique ' +
94
- '"key" prop. See https://reactjs.org/link/warning-keys for ' +
95
- 'more information.',
96
- );
97
- };
98
-}
99
-
100
-function isReactClass(type) {
101
- return type.prototype && type.prototype.isReactComponent;
102
-}
103
-
104
-function coerceRef(
105
- returnFiber: Fiber,
106
- current: Fiber | null,
107
- element: ReactElement,
108
-) {
109
- const mixedRef = element.ref;
110
- if (
111
- mixedRef !== null &&
112
- typeof mixedRef !== 'function' &&
113
- typeof mixedRef !== 'object'
114
- ) {
115
- if (__DEV__) {
116
- // TODO: Clean this up once we turn on the string ref warning for
117
- // everyone, because the strict mode case will no longer be relevant
118
- if (
119
- (returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) &&
120
- // We warn in ReactElement.js if owner and self are equal for string refs
121
- // because these cannot be automatically converted to an arrow function
122
- // using a codemod. Therefore, we don't have to warn about string refs again.
123
- !(
124
- element._owner &&
125
- element._self &&
126
- element._owner.stateNode !== element._self
127
- ) &&
128
- // Will already throw with "Function components cannot have string refs"
129
- !(
130
- element._owner &&
131
- ((element._owner: any): Fiber).tag !== ClassComponent
132
- ) &&
133
- // Will already warn with "Function components cannot be given refs"
134
- !(typeof element.type === 'function' && !isReactClass(element.type)) &&
135
- // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set"
136
- element._owner
137
- ) {
138
- const componentName =
139
- getComponentNameFromFiber(returnFiber) || 'Component';
140
- if (!didWarnAboutStringRefs[componentName]) {
141
- if (warnAboutStringRefs) {
142
- console.error(
143
- 'Component "%s" contains the string ref "%s". Support for string refs ' +
144
- 'will be removed in a future major release. We recommend using ' +
145
- 'useRef() or createRef() instead. ' +
146
- 'Learn more about using refs safely here: ' +
147
- 'https://reactjs.org/link/strict-mode-string-ref',
148
- componentName,
149
- mixedRef,
150
- );
151
- } else {
152
- console.error(
153
- 'A string ref, "%s", has been found within a strict mode tree. ' +
154
- 'String refs are a source of potential bugs and should be avoided. ' +
155
- 'We recommend using useRef() or createRef() instead. ' +
156
- 'Learn more about using refs safely here: ' +
157
- 'https://reactjs.org/link/strict-mode-string-ref',
158
- mixedRef,
159
- );
160
- }
161
- didWarnAboutStringRefs[componentName] = true;
162
- }
163
- }
164
- }
165
-
166
- if (element._owner) {
167
- const owner: ?Fiber = (element._owner: any);
168
- let inst;
169
- if (owner) {
170
- const ownerFiber = ((owner: any): Fiber);
171
-
172
- if (ownerFiber.tag !== ClassComponent) {
173
- throw new Error(
174
- 'Function components cannot have string refs. ' +
175
- 'We recommend using useRef() instead. ' +
176
- 'Learn more about using refs safely here: ' +
177
- 'https://reactjs.org/link/strict-mode-string-ref',
178
- );
179
- }
180
-
181
- inst = ownerFiber.stateNode;
182
- }
183
-
184
- if (!inst) {
185
- throw new Error(
186
- `Missing owner for string ref ${mixedRef}. This error is likely caused by a ` +
187
- 'bug in React. Please file an issue.',
188
- );
189
- }
190
- // Assigning this to a const so Flow knows it won't change in the closure
191
- const resolvedInst = inst;
192
-
193
- if (__DEV__) {
194
- checkPropStringCoercion(mixedRef, 'ref');
195
- }
196
- const stringRef = '' + mixedRef;
197
- // Check if previous string ref matches new string ref
198
- if (
199
- current !== null &&
200
- current.ref !== null &&
201
- typeof current.ref === 'function' &&
202
- current.ref._stringRef === stringRef
203
- ) {
204
- return current.ref;
205
- }
206
- const ref = function(value) {
207
- const refs = resolvedInst.refs;
208
- if (value === null) {
209
- delete refs[stringRef];
210
- } else {
211
- refs[stringRef] = value;
212
- }
213
- };
214
- ref._stringRef = stringRef;
215
- return ref;
216
- } else {
217
- if (typeof mixedRef !== 'string') {
218
- throw new Error(
219
- 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.',
220
- );
221
- }
222
-
223
- if (!element._owner) {
224
- throw new Error(
225
- `Element ref was specified as a string (${mixedRef}) but no owner was set. This could happen for one of` +
226
- ' the following reasons:\n' +
227
- '1. You may be adding a ref to a function component\n' +
228
- "2. You may be adding a ref to a component that was not created inside a component's render method\n" +
229
- '3. You have multiple copies of React loaded\n' +
230
- 'See https://reactjs.org/link/refs-must-have-owner for more information.',
231
- );
232
- }
233
- }
234
- }
235
- return mixedRef;
236
-}
237
-
238
-function throwOnInvalidObjectType(returnFiber: Fiber, newChild: Object) {
239
- // $FlowFixMe[method-unbinding]
240
- const childString = Object.prototype.toString.call(newChild);
241
-
242
- throw new Error(
243
- `Objects are not valid as a React child (found: ${
244
- childString === '[object Object]'
245
- ? 'object with keys {' + Object.keys(newChild).join(', ') + '}'
246
- : childString
247
- }). ` +
248
- 'If you meant to render a collection of children, use an array ' +
249
- 'instead.',
250
- );
251
-}
252
-
253
-function warnOnFunctionType(returnFiber: Fiber) {
254
- if (__DEV__) {
255
- const componentName = getComponentNameFromFiber(returnFiber) || 'Component';
256
-
257
- if (ownerHasFunctionTypeWarning[componentName]) {
258
- return;
259
- }
260
- ownerHasFunctionTypeWarning[componentName] = true;
261
-
262
- console.error(
263
- 'Functions are not valid as a React child. This may happen if ' +
264
- 'you return a Component instead of <Component /> from render. ' +
265
- 'Or maybe you meant to call this function rather than return it.',
266
- );
267
- }
268
-}
269
-
270
-function resolveLazy(lazyType) {
271
- const payload = lazyType._payload;
272
- const init = lazyType._init;
273
- return init(payload);
274
-}
275
-
276
-type ChildReconciler = (
277
- returnFiber: Fiber,
278
- currentFirstChild: Fiber | null,
279
- newChild: any,
280
- lanes: Lanes,
281
-) => Fiber | null;
282
-
283
-// This wrapper function exists because I expect to clone the code in each path
284
-// to be able to optimize each path individually by branching early. This needs
285
-// a compiler or we can do it manually. Helpers that don't need this branching
286
-// live outside of this function.
287
-function createChildReconciler(shouldTrackSideEffects): ChildReconciler {
288
- function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void {
289
- if (!shouldTrackSideEffects) {
290
- // Noop.
291
- return;
292
- }
293
- const deletions = returnFiber.deletions;
294
- if (deletions === null) {
295
- returnFiber.deletions = [childToDelete];
296
- returnFiber.flags |= ChildDeletion;
297
- } else {
298
- deletions.push(childToDelete);
299
- }
300
- }
301
-
302
- function deleteRemainingChildren(
303
- returnFiber: Fiber,
304
- currentFirstChild: Fiber | null,
305
- ): null {
306
- if (!shouldTrackSideEffects) {
307
- // Noop.
308
- return null;
309
- }
310
-
311
- // TODO: For the shouldClone case, this could be micro-optimized a bit by
312
- // assuming that after the first child we've already added everything.
313
- let childToDelete = currentFirstChild;
314
- while (childToDelete !== null) {
315
- deleteChild(returnFiber, childToDelete);
316
- childToDelete = childToDelete.sibling;
317
- }
318
- return null;
319
- }
320
-
321
- function mapRemainingChildren(
322
- returnFiber: Fiber,
323
- currentFirstChild: Fiber,
324
- ): Map<string | number, Fiber> {
325
- // Add the remaining children to a temporary map so that we can find them by
326
- // keys quickly. Implicit (null) keys get added to this set with their index
327
- // instead.
328
- const existingChildren: Map<string | number, Fiber> = new Map();
329
-
330
- let existingChild: null | Fiber = currentFirstChild;
331
- while (existingChild !== null) {
332
- if (existingChild.key !== null) {
333
- existingChildren.set(existingChild.key, existingChild);
334
- } else {
335
- existingChildren.set(existingChild.index, existingChild);
336
- }
337
- existingChild = existingChild.sibling;
338
- }
339
- return existingChildren;
340
- }
341
-
342
- function useFiber(fiber: Fiber, pendingProps: mixed): Fiber {
343
- // We currently set sibling to null and index to 0 here because it is easy
344
- // to forget to do before returning it. E.g. for the single child case.
345
- const clone = createWorkInProgress(fiber, pendingProps);
346
- clone.index = 0;
347
- clone.sibling = null;
348
- return clone;
349
- }
350
-
351
- function placeChild(
352
- newFiber: Fiber,
353
- lastPlacedIndex: number,
354
- newIndex: number,
355
- ): number {
356
- newFiber.index = newIndex;
357
- if (!shouldTrackSideEffects) {
358
- // During hydration, the useId algorithm needs to know which fibers are
359
- // part of a list of children (arrays, iterators).
360
- newFiber.flags |= Forked;
361
- return lastPlacedIndex;
362
- }
363
- const current = newFiber.alternate;
364
- if (current !== null) {
365
- const oldIndex = current.index;
366
- if (oldIndex < lastPlacedIndex) {
367
- // This is a move.
368
- newFiber.flags |= Placement | PlacementDEV;
369
- return lastPlacedIndex;
370
- } else {
371
- // This item can stay in place.
372
- return oldIndex;
373
- }
374
- } else {
375
- // This is an insertion.
376
- newFiber.flags |= Placement | PlacementDEV;
377
- return lastPlacedIndex;
378
- }
379
- }
380
-
381
- function placeSingleChild(newFiber: Fiber): Fiber {
382
- // This is simpler for the single child case. We only need to do a
383
- // placement for inserting new children.
384
- if (shouldTrackSideEffects && newFiber.alternate === null) {
385
- newFiber.flags |= Placement | PlacementDEV;
386
- }
387
- return newFiber;
388
- }
389
-
390
- function updateTextNode(
391
- returnFiber: Fiber,
392
- current: Fiber | null,
393
- textContent: string,
394
- lanes: Lanes,
395
- ) {
396
- if (current === null || current.tag !== HostText) {
397
- // Insert
398
- const created = createFiberFromText(textContent, returnFiber.mode, lanes);
399
- created.return = returnFiber;
400
- return created;
401
- } else {
402
- // Update
403
- const existing = useFiber(current, textContent);
404
- existing.return = returnFiber;
405
- return existing;
406
- }
407
- }
408
-
409
- function updateElement(
410
- returnFiber: Fiber,
411
- current: Fiber | null,
412
- element: ReactElement,
413
- lanes: Lanes,
414
- ): Fiber {
415
- const elementType = element.type;
416
- if (elementType === REACT_FRAGMENT_TYPE) {
417
- return updateFragment(
418
- returnFiber,
419
- current,
420
- element.props.children,
421
- lanes,
422
- element.key,
423
- );
424
- }
425
- if (current !== null) {
426
- if (
427
- current.elementType === elementType ||
428
- // Keep this check inline so it only runs on the false path:
429
- (__DEV__
430
- ? isCompatibleFamilyForHotReloading(current, element)
431
- : false) ||
432
- // Lazy types should reconcile their resolved type.
433
- // We need to do this after the Hot Reloading check above,
434
- // because hot reloading has different semantics than prod because
435
- // it doesn't resuspend. So we can't let the call below suspend.
436
- (typeof elementType === 'object' &&
437
- elementType !== null &&
438
- elementType.$$typeof === REACT_LAZY_TYPE &&
439
- resolveLazy(elementType) === current.type)
440
- ) {
441
- // Move based on index
442
- const existing = useFiber(current, element.props);
443
- existing.ref = coerceRef(returnFiber, current, element);
444
- existing.return = returnFiber;
445
- if (__DEV__) {
446
- existing._debugSource = element._source;
447
- existing._debugOwner = element._owner;
448
- }
449
- return existing;
450
- }
451
- }
452
- // Insert
453
- const created = createFiberFromElement(element, returnFiber.mode, lanes);
454
- created.ref = coerceRef(returnFiber, current, element);
455
- created.return = returnFiber;
456
- return created;
457
- }
458
-
459
- function updatePortal(
460
- returnFiber: Fiber,
461
- current: Fiber | null,
462
- portal: ReactPortal,
463
- lanes: Lanes,
464
- ): Fiber {
465
- if (
466
- current === null ||
467
- current.tag !== HostPortal ||
468
- current.stateNode.containerInfo !== portal.containerInfo ||
469
- current.stateNode.implementation !== portal.implementation
470
- ) {
471
- // Insert
472
- const created = createFiberFromPortal(portal, returnFiber.mode, lanes);
473
- created.return = returnFiber;
474
- return created;
475
- } else {
476
- // Update
477
- const existing = useFiber(current, portal.children || []);
478
- existing.return = returnFiber;
479
- return existing;
480
- }
481
- }
482
-
483
- function updateFragment(
484
- returnFiber: Fiber,
485
- current: Fiber | null,
486
- fragment: Iterable<React$Node>,
487
- lanes: Lanes,
488
- key: null | string,
489
- ): Fiber {
490
- if (current === null || current.tag !== Fragment) {
491
- // Insert
492
- const created = createFiberFromFragment(
493
- fragment,
494
- returnFiber.mode,
495
- lanes,
496
- key,
497
- );
498
- created.return = returnFiber;
499
- return created;
500
- } else {
501
- // Update
502
- const existing = useFiber(current, fragment);
503
- existing.return = returnFiber;
504
- return existing;
505
- }
506
- }
507
-
508
- function createChild(
509
- returnFiber: Fiber,
510
- newChild: any,
511
- lanes: Lanes,
512
- ): Fiber | null {
513
- if (
514
- (typeof newChild === 'string' && newChild !== '') ||
515
- typeof newChild === 'number'
516
- ) {
517
- // Text nodes don't have keys. If the previous node is implicitly keyed
518
- // we can continue to replace it without aborting even if it is not a text
519
- // node.
520
- const created = createFiberFromText(
521
- '' + newChild,
522
- returnFiber.mode,
523
- lanes,
524
- );
525
- created.return = returnFiber;
526
- return created;
527
- }
528
-
529
- if (typeof newChild === 'object' && newChild !== null) {
530
- switch (newChild.$$typeof) {
531
- case REACT_ELEMENT_TYPE: {
532
- const created = createFiberFromElement(
533
- newChild,
534
- returnFiber.mode,
535
- lanes,
536
- );
537
- created.ref = coerceRef(returnFiber, null, newChild);
538
- created.return = returnFiber;
539
- return created;
540
- }
541
- case REACT_PORTAL_TYPE: {
542
- const created = createFiberFromPortal(
543
- newChild,
544
- returnFiber.mode,
545
- lanes,
546
- );
547
- created.return = returnFiber;
548
- return created;
549
- }
550
- case REACT_LAZY_TYPE: {
551
- const payload = newChild._payload;
552
- const init = newChild._init;
553
- return createChild(returnFiber, init(payload), lanes);
554
- }
555
- }
556
-
557
- if (isArray(newChild) || getIteratorFn(newChild)) {
558
- const created = createFiberFromFragment(
559
- newChild,
560
- returnFiber.mode,
561
- lanes,
562
- null,
563
- );
564
- created.return = returnFiber;
565
- return created;
566
- }
567
-
568
- throwOnInvalidObjectType(returnFiber, newChild);
569
- }
570
-
571
- if (__DEV__) {
572
- if (typeof newChild === 'function') {
573
- warnOnFunctionType(returnFiber);
574
- }
575
- }
576
-
577
- return null;
578
- }
579
-
580
- function updateSlot(
581
- returnFiber: Fiber,
582
- oldFiber: Fiber | null,
583
- newChild: any,
584
- lanes: Lanes,
585
- ): Fiber | null {
586
- // Update the fiber if the keys match, otherwise return null.
587
-
588
- const key = oldFiber !== null ? oldFiber.key : null;
589
-
590
- if (
591
- (typeof newChild === 'string' && newChild !== '') ||
592
- typeof newChild === 'number'
593
- ) {
594
- // Text nodes don't have keys. If the previous node is implicitly keyed
595
- // we can continue to replace it without aborting even if it is not a text
596
- // node.
597
- if (key !== null) {
598
- return null;
599
- }
600
- return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes);
601
- }
602
-
603
- if (typeof newChild === 'object' && newChild !== null) {
604
- switch (newChild.$$typeof) {
605
- case REACT_ELEMENT_TYPE: {
606
- if (newChild.key === key) {
607
- return updateElement(returnFiber, oldFiber, newChild, lanes);
608
- } else {
609
- return null;
610
- }
611
- }
612
- case REACT_PORTAL_TYPE: {
613
- if (newChild.key === key) {
614
- return updatePortal(returnFiber, oldFiber, newChild, lanes);
615
- } else {
616
- return null;
617
- }
618
- }
619
- case REACT_LAZY_TYPE: {
620
- const payload = newChild._payload;
621
- const init = newChild._init;
622
- return updateSlot(returnFiber, oldFiber, init(payload), lanes);
623
- }
624
- }
625
-
626
- if (isArray(newChild) || getIteratorFn(newChild)) {
627
- if (key !== null) {
628
- return null;
629
- }
630
-
631
- return updateFragment(returnFiber, oldFiber, newChild, lanes, null);
632
- }
633
-
634
- throwOnInvalidObjectType(returnFiber, newChild);
635
- }
636
-
637
- if (__DEV__) {
638
- if (typeof newChild === 'function') {
639
- warnOnFunctionType(returnFiber);
640
- }
641
- }
642
-
643
- return null;
644
- }
645
-
646
- function updateFromMap(
647
- existingChildren: Map<string | number, Fiber>,
648
- returnFiber: Fiber,
649
- newIdx: number,
650
- newChild: any,
651
- lanes: Lanes,
652
- ): Fiber | null {
653
- if (
654
- (typeof newChild === 'string' && newChild !== '') ||
655
- typeof newChild === 'number'
656
- ) {
657
- // Text nodes don't have keys, so we neither have to check the old nor
658
- // new node for the key. If both are text nodes, they match.
659
- const matchedFiber = existingChildren.get(newIdx) || null;
660
- return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes);
661
- }
662
-
663
- if (typeof newChild === 'object' && newChild !== null) {
664
- switch (newChild.$$typeof) {
665
- case REACT_ELEMENT_TYPE: {
666
- const matchedFiber =
667
- existingChildren.get(
668
- newChild.key === null ? newIdx : newChild.key,
669
- ) || null;
670
- return updateElement(returnFiber, matchedFiber, newChild, lanes);
671
- }
672
- case REACT_PORTAL_TYPE: {
673
- const matchedFiber =
674
- existingChildren.get(
675
- newChild.key === null ? newIdx : newChild.key,
676
- ) || null;
677
- return updatePortal(returnFiber, matchedFiber, newChild, lanes);
678
- }
679
- case REACT_LAZY_TYPE:
680
- const payload = newChild._payload;
681
- const init = newChild._init;
682
- return updateFromMap(
683
- existingChildren,
684
- returnFiber,
685
- newIdx,
686
- init(payload),
687
- lanes,
688
- );
689
- }
690
-
691
- if (isArray(newChild) || getIteratorFn(newChild)) {
692
- const matchedFiber = existingChildren.get(newIdx) || null;
693
- return updateFragment(returnFiber, matchedFiber, newChild, lanes, null);
694
- }
695
-
696
- throwOnInvalidObjectType(returnFiber, newChild);
697
- }
698
-
699
- if (__DEV__) {
700
- if (typeof newChild === 'function') {
701
- warnOnFunctionType(returnFiber);
702
- }
703
- }
704
-
705
- return null;
706
- }
707
-
708
- /**
709
- * Warns if there is a duplicate or missing key
710
- */
711
- function warnOnInvalidKey(
712
- child: mixed,
713
- knownKeys: Set<string> | null,
714
- returnFiber: Fiber,
715
- ): Set<string> | null {
716
- if (__DEV__) {
717
- if (typeof child !== 'object' || child === null) {
718
- return knownKeys;
719
- }
720
- switch (child.$$typeof) {
721
- case REACT_ELEMENT_TYPE:
722
- case REACT_PORTAL_TYPE:
723
- warnForMissingKey(child, returnFiber);
724
- const key = child.key;
725
- if (typeof key !== 'string') {
726
- break;
727
- }
728
- if (knownKeys === null) {
729
- knownKeys = new Set();
730
- knownKeys.add(key);
731
- break;
732
- }
733
- if (!knownKeys.has(key)) {
734
- knownKeys.add(key);
735
- break;
736
- }
737
- console.error(
738
- 'Encountered two children with the same key, `%s`. ' +
739
- 'Keys should be unique so that components maintain their identity ' +
740
- 'across updates. Non-unique keys may cause children to be ' +
741
- 'duplicated and/or omitted — the behavior is unsupported and ' +
742
- 'could change in a future version.',
743
- key,
744
- );
745
- break;
746
- case REACT_LAZY_TYPE:
747
- const payload = child._payload;
748
- const init = (child._init: any);
749
- warnOnInvalidKey(init(payload), knownKeys, returnFiber);
750
- break;
751
- default:
752
- break;
753
- }
754
- }
755
- return knownKeys;
756
- }
757
-
758
- function reconcileChildrenArray(
759
- returnFiber: Fiber,
760
- currentFirstChild: Fiber | null,
761
- newChildren: Array<any>,
762
- lanes: Lanes,
763
- ): Fiber | null {
764
- // This algorithm can't optimize by searching from both ends since we
765
- // don't have backpointers on fibers. I'm trying to see how far we can get
766
- // with that model. If it ends up not being worth the tradeoffs, we can
767
- // add it later.
768
-
769
- // Even with a two ended optimization, we'd want to optimize for the case
770
- // where there are few changes and brute force the comparison instead of
771
- // going for the Map. It'd like to explore hitting that path first in
772
- // forward-only mode and only go for the Map once we notice that we need
773
- // lots of look ahead. This doesn't handle reversal as well as two ended
774
- // search but that's unusual. Besides, for the two ended optimization to
775
- // work on Iterables, we'd need to copy the whole set.
776
-
777
- // In this first iteration, we'll just live with hitting the bad case
778
- // (adding everything to a Map) in for every insert/move.
779
-
780
- // If you change this code, also update reconcileChildrenIterator() which
781
- // uses the same algorithm.
782
-
783
- if (__DEV__) {
784
- // First, validate keys.
785
- let knownKeys = null;
786
- for (let i = 0; i < newChildren.length; i++) {
787
- const child = newChildren[i];
788
- knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
789
- }
790
- }
791
-
792
- let resultingFirstChild: Fiber | null = null;
793
- let previousNewFiber: Fiber | null = null;
794
-
795
- let oldFiber = currentFirstChild;
796
- let lastPlacedIndex = 0;
797
- let newIdx = 0;
798
- let nextOldFiber = null;
799
- for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
800
- if (oldFiber.index > newIdx) {
801
- nextOldFiber = oldFiber;
802
- oldFiber = null;
803
- } else {
804
- nextOldFiber = oldFiber.sibling;
805
- }
806
- const newFiber = updateSlot(
807
- returnFiber,
808
- oldFiber,
809
- newChildren[newIdx],
810
- lanes,
811
- );
812
- if (newFiber === null) {
813
- // TODO: This breaks on empty slots like null children. That's
814
- // unfortunate because it triggers the slow path all the time. We need
815
- // a better way to communicate whether this was a miss or null,
816
- // boolean, undefined, etc.
817
- if (oldFiber === null) {
818
- oldFiber = nextOldFiber;
819
- }
820
- break;
821
- }
822
- if (shouldTrackSideEffects) {
823
- if (oldFiber && newFiber.alternate === null) {
824
- // We matched the slot, but we didn't reuse the existing fiber, so we
825
- // need to delete the existing child.
826
- deleteChild(returnFiber, oldFiber);
827
- }
828
- }
829
- lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
830
- if (previousNewFiber === null) {
831
- // TODO: Move out of the loop. This only happens for the first run.
832
- resultingFirstChild = newFiber;
833
- } else {
834
- // TODO: Defer siblings if we're not at the right index for this slot.
835
- // I.e. if we had null values before, then we want to defer this
836
- // for each null value. However, we also don't want to call updateSlot
837
- // with the previous one.
838
- previousNewFiber.sibling = newFiber;
839
- }
840
- previousNewFiber = newFiber;
841
- oldFiber = nextOldFiber;
842
- }
843
-
844
- if (newIdx === newChildren.length) {
845
- // We've reached the end of the new children. We can delete the rest.
846
- deleteRemainingChildren(returnFiber, oldFiber);
847
- if (getIsHydrating()) {
848
- const numberOfForks = newIdx;
849
- pushTreeFork(returnFiber, numberOfForks);
850
- }
851
- return resultingFirstChild;
852
- }
853
-
854
- if (oldFiber === null) {
855
- // If we don't have any more existing children we can choose a fast path
856
- // since the rest will all be insertions.
857
- for (; newIdx < newChildren.length; newIdx++) {
858
- const newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
859
- if (newFiber === null) {
860
- continue;
861
- }
862
- lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
863
- if (previousNewFiber === null) {
864
- // TODO: Move out of the loop. This only happens for the first run.
865
- resultingFirstChild = newFiber;
866
- } else {
867
- previousNewFiber.sibling = newFiber;
868
- }
869
- previousNewFiber = newFiber;
870
- }
871
- if (getIsHydrating()) {
872
- const numberOfForks = newIdx;
873
- pushTreeFork(returnFiber, numberOfForks);
874
- }
875
- return resultingFirstChild;
876
- }
877
-
878
- // Add all children to a key map for quick lookups.
879
- const existingChildren = mapRemainingChildren(returnFiber, oldFiber);
880
-
881
- // Keep scanning and use the map to restore deleted items as moves.
882
- for (; newIdx < newChildren.length; newIdx++) {
883
- const newFiber = updateFromMap(
884
- existingChildren,
885
- returnFiber,
886
- newIdx,
887
- newChildren[newIdx],
888
- lanes,
889
- );
890
- if (newFiber !== null) {
891
- if (shouldTrackSideEffects) {
892
- if (newFiber.alternate !== null) {
893
- // The new fiber is a work in progress, but if there exists a
894
- // current, that means that we reused the fiber. We need to delete
895
- // it from the child list so that we don't add it to the deletion
896
- // list.
897
- existingChildren.delete(
898
- newFiber.key === null ? newIdx : newFiber.key,
899
- );
900
- }
901
- }
902
- lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
903
- if (previousNewFiber === null) {
904
- resultingFirstChild = newFiber;
905
- } else {
906
- previousNewFiber.sibling = newFiber;
907
- }
908
- previousNewFiber = newFiber;
909
- }
910
- }
911
-
912
- if (shouldTrackSideEffects) {
913
- // Any existing children that weren't consumed above were deleted. We need
914
- // to add them to the deletion list.
915
- existingChildren.forEach(child => deleteChild(returnFiber, child));
916
- }
917
-
918
- if (getIsHydrating()) {
919
- const numberOfForks = newIdx;
920
- pushTreeFork(returnFiber, numberOfForks);
921
- }
922
- return resultingFirstChild;
923
- }
924
-
925
- function reconcileChildrenIterator(
926
- returnFiber: Fiber,
927
- currentFirstChild: Fiber | null,
928
- newChildrenIterable: Iterable<mixed>,
929
- lanes: Lanes,
930
- ): Fiber | null {
931
- // This is the same implementation as reconcileChildrenArray(),
932
- // but using the iterator instead.
933
-
934
- const iteratorFn = getIteratorFn(newChildrenIterable);
935
-
936
- if (typeof iteratorFn !== 'function') {
937
- throw new Error(
938
- 'An object is not an iterable. This error is likely caused by a bug in ' +
939
- 'React. Please file an issue.',
940
- );
941
- }
942
-
943
- if (__DEV__) {
944
- // We don't support rendering Generators because it's a mutation.
945
- // See https://github.com/facebook/react/issues/12995
946
- if (
947
- typeof Symbol === 'function' &&
948
- // $FlowFixMe Flow doesn't know about toStringTag
949
- newChildrenIterable[Symbol.toStringTag] === 'Generator'
950
- ) {
951
- if (!didWarnAboutGenerators) {
952
- console.error(
953
- 'Using Generators as children is unsupported and will likely yield ' +
954
- 'unexpected results because enumerating a generator mutates it. ' +
955
- 'You may convert it to an array with `Array.from()` or the ' +
956
- '`[...spread]` operator before rendering. Keep in mind ' +
957
- 'you might need to polyfill these features for older browsers.',
958
- );
959
- }
960
- didWarnAboutGenerators = true;
961
- }
962
-
963
- // Warn about using Maps as children
964
- if ((newChildrenIterable: any).entries === iteratorFn) {
965
- if (!didWarnAboutMaps) {
966
- console.error(
967
- 'Using Maps as children is not supported. ' +
968
- 'Use an array of keyed ReactElements instead.',
969
- );
970
- }
971
- didWarnAboutMaps = true;
972
- }
973
-
974
- // First, validate keys.
975
- // We'll get a different iterator later for the main pass.
976
- const newChildren = iteratorFn.call(newChildrenIterable);
977
- if (newChildren) {
978
- let knownKeys = null;
979
- let step = newChildren.next();
980
- for (; !step.done; step = newChildren.next()) {
981
- const child = step.value;
982
- knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
983
- }
984
- }
985
- }
986
-
987
- const newChildren = iteratorFn.call(newChildrenIterable);
988
-
989
- if (newChildren == null) {
990
- throw new Error('An iterable object provided no iterator.');
991
- }
992
-
993
- let resultingFirstChild: Fiber | null = null;
994
- let previousNewFiber: Fiber | null = null;
995
-
996
- let oldFiber = currentFirstChild;
997
- let lastPlacedIndex = 0;
998
- let newIdx = 0;
999
- let nextOldFiber = null;
1000
-
1001
- let step = newChildren.next();
1002
- for (
1003
- ;
1004
- oldFiber !== null && !step.done;
1005
- newIdx++, step = newChildren.next()
1006
- ) {
1007
- if (oldFiber.index > newIdx) {
1008
- nextOldFiber = oldFiber;
1009
- oldFiber = null;
1010
- } else {
1011
- nextOldFiber = oldFiber.sibling;
1012
- }
1013
- const newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
1014
- if (newFiber === null) {
1015
- // TODO: This breaks on empty slots like null children. That's
1016
- // unfortunate because it triggers the slow path all the time. We need
1017
- // a better way to communicate whether this was a miss or null,
1018
- // boolean, undefined, etc.
1019
- if (oldFiber === null) {
1020
- oldFiber = nextOldFiber;
1021
- }
1022
- break;
1023
- }
1024
- if (shouldTrackSideEffects) {
1025
- if (oldFiber && newFiber.alternate === null) {
1026
- // We matched the slot, but we didn't reuse the existing fiber, so we
1027
- // need to delete the existing child.
1028
- deleteChild(returnFiber, oldFiber);
1029
- }
1030
- }
1031
- lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
1032
- if (previousNewFiber === null) {
1033
- // TODO: Move out of the loop. This only happens for the first run.
1034
- resultingFirstChild = newFiber;
1035
- } else {
1036
- // TODO: Defer siblings if we're not at the right index for this slot.
1037
- // I.e. if we had null values before, then we want to defer this
1038
- // for each null value. However, we also don't want to call updateSlot
1039
- // with the previous one.
1040
- previousNewFiber.sibling = newFiber;
1041
- }
1042
- previousNewFiber = newFiber;
1043
- oldFiber = nextOldFiber;
1044
- }
1045
-
1046
- if (step.done) {
1047
- // We've reached the end of the new children. We can delete the rest.
1048
- deleteRemainingChildren(returnFiber, oldFiber);
1049
- if (getIsHydrating()) {
1050
- const numberOfForks = newIdx;
1051
- pushTreeFork(returnFiber, numberOfForks);
1052
- }
1053
- return resultingFirstChild;
1054
- }
1055
-
1056
- if (oldFiber === null) {
1057
- // If we don't have any more existing children we can choose a fast path
1058
- // since the rest will all be insertions.
1059
- for (; !step.done; newIdx++, step = newChildren.next()) {
1060
- const newFiber = createChild(returnFiber, step.value, lanes);
1061
- if (newFiber === null) {
1062
- continue;
1063
- }
1064
- lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
1065
- if (previousNewFiber === null) {
1066
- // TODO: Move out of the loop. This only happens for the first run.
1067
- resultingFirstChild = newFiber;
1068
- } else {
1069
- previousNewFiber.sibling = newFiber;
1070
- }
1071
- previousNewFiber = newFiber;
1072
- }
1073
- if (getIsHydrating()) {
1074
- const numberOfForks = newIdx;
1075
- pushTreeFork(returnFiber, numberOfForks);
1076
- }
1077
- return resultingFirstChild;
1078
- }
1079
-
1080
- // Add all children to a key map for quick lookups.
1081
- const existingChildren = mapRemainingChildren(returnFiber, oldFiber);
1082
-
1083
- // Keep scanning and use the map to restore deleted items as moves.
1084
- for (; !step.done; newIdx++, step = newChildren.next()) {
1085
- const newFiber = updateFromMap(
1086
- existingChildren,
1087
- returnFiber,
1088
- newIdx,
1089
- step.value,
1090
- lanes,
1091
- );
1092
- if (newFiber !== null) {
1093
- if (shouldTrackSideEffects) {
1094
- if (newFiber.alternate !== null) {
1095
- // The new fiber is a work in progress, but if there exists a
1096
- // current, that means that we reused the fiber. We need to delete
1097
- // it from the child list so that we don't add it to the deletion
1098
- // list.
1099
- existingChildren.delete(
1100
- newFiber.key === null ? newIdx : newFiber.key,
1101
- );
1102
- }
1103
- }
1104
- lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
1105
- if (previousNewFiber === null) {
1106
- resultingFirstChild = newFiber;
1107
- } else {
1108
- previousNewFiber.sibling = newFiber;
1109
- }
1110
- previousNewFiber = newFiber;
1111
- }
1112
- }
1113
-
1114
- if (shouldTrackSideEffects) {
1115
- // Any existing children that weren't consumed above were deleted. We need
1116
- // to add them to the deletion list.
1117
- existingChildren.forEach(child => deleteChild(returnFiber, child));
1118
- }
1119
-
1120
- if (getIsHydrating()) {
1121
- const numberOfForks = newIdx;
1122
- pushTreeFork(returnFiber, numberOfForks);
1123
- }
1124
- return resultingFirstChild;
1125
- }
1126
-
1127
- function reconcileSingleTextNode(
1128
- returnFiber: Fiber,
1129
- currentFirstChild: Fiber | null,
1130
- textContent: string,
1131
- lanes: Lanes,
1132
- ): Fiber {
1133
- // There's no need to check for keys on text nodes since we don't have a
1134
- // way to define them.
1135
- if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
1136
- // We already have an existing node so let's just update it and delete
1137
- // the rest.
1138
- deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
1139
- const existing = useFiber(currentFirstChild, textContent);
1140
- existing.return = returnFiber;
1141
- return existing;
1142
- }
1143
- // The existing first child is not a text node so we need to create one
1144
- // and delete the existing ones.
1145
- deleteRemainingChildren(returnFiber, currentFirstChild);
1146
- const created = createFiberFromText(textContent, returnFiber.mode, lanes);
1147
- created.return = returnFiber;
1148
- return created;
1149
- }
1150
-
1151
- function reconcileSingleElement(
1152
- returnFiber: Fiber,
1153
- currentFirstChild: Fiber | null,
1154
- element: ReactElement,
1155
- lanes: Lanes,
1156
- ): Fiber {
1157
- const key = element.key;
1158
- let child = currentFirstChild;
1159
- while (child !== null) {
1160
- // TODO: If key === null and child.key === null, then this only applies to
1161
- // the first item in the list.
1162
- if (child.key === key) {
1163
- const elementType = element.type;
1164
- if (elementType === REACT_FRAGMENT_TYPE) {
1165
- if (child.tag === Fragment) {
1166
- deleteRemainingChildren(returnFiber, child.sibling);
1167
- const existing = useFiber(child, element.props.children);
1168
- existing.return = returnFiber;
1169
- if (__DEV__) {
1170
- existing._debugSource = element._source;
1171
- existing._debugOwner = element._owner;
1172
- }
1173
- return existing;
1174
- }
1175
- } else {
1176
- if (
1177
- child.elementType === elementType ||
1178
- // Keep this check inline so it only runs on the false path:
1179
- (__DEV__
1180
- ? isCompatibleFamilyForHotReloading(child, element)
1181
- : false) ||
1182
- // Lazy types should reconcile their resolved type.
1183
- // We need to do this after the Hot Reloading check above,
1184
- // because hot reloading has different semantics than prod because
1185
- // it doesn't resuspend. So we can't let the call below suspend.
1186
- (typeof elementType === 'object' &&
1187
- elementType !== null &&
1188
- elementType.$$typeof === REACT_LAZY_TYPE &&
1189
- resolveLazy(elementType) === child.type)
1190
- ) {
1191
- deleteRemainingChildren(returnFiber, child.sibling);
1192
- const existing = useFiber(child, element.props);
1193
- existing.ref = coerceRef(returnFiber, child, element);
1194
- existing.return = returnFiber;
1195
- if (__DEV__) {
1196
- existing._debugSource = element._source;
1197
- existing._debugOwner = element._owner;
1198
- }
1199
- return existing;
1200
- }
1201
- }
1202
- // Didn't match.
1203
- deleteRemainingChildren(returnFiber, child);
1204
- break;
1205
- } else {
1206
- deleteChild(returnFiber, child);
1207
- }
1208
- child = child.sibling;
1209
- }
1210
-
1211
- if (element.type === REACT_FRAGMENT_TYPE) {
1212
- const created = createFiberFromFragment(
1213
- element.props.children,
1214
- returnFiber.mode,
1215
- lanes,
1216
- element.key,
1217
- );
1218
- created.return = returnFiber;
1219
- return created;
1220
- } else {
1221
- const created = createFiberFromElement(element, returnFiber.mode, lanes);
1222
- created.ref = coerceRef(returnFiber, currentFirstChild, element);
1223
- created.return = returnFiber;
1224
- return created;
1225
- }
1226
- }
1227
-
1228
- function reconcileSinglePortal(
1229
- returnFiber: Fiber,
1230
- currentFirstChild: Fiber | null,
1231
- portal: ReactPortal,
1232
- lanes: Lanes,
1233
- ): Fiber {
1234
- const key = portal.key;
1235
- let child = currentFirstChild;
1236
- while (child !== null) {
1237
- // TODO: If key === null and child.key === null, then this only applies to
1238
- // the first item in the list.
1239
- if (child.key === key) {
1240
- if (
1241
- child.tag === HostPortal &&
1242
- child.stateNode.containerInfo === portal.containerInfo &&
1243
- child.stateNode.implementation === portal.implementation
1244
- ) {
1245
- deleteRemainingChildren(returnFiber, child.sibling);
1246
- const existing = useFiber(child, portal.children || []);
1247
- existing.return = returnFiber;
1248
- return existing;
1249
- } else {
1250
- deleteRemainingChildren(returnFiber, child);
1251
- break;
1252
- }
1253
- } else {
1254
- deleteChild(returnFiber, child);
1255
- }
1256
- child = child.sibling;
1257
- }
1258
-
1259
- const created = createFiberFromPortal(portal, returnFiber.mode, lanes);
1260
- created.return = returnFiber;
1261
- return created;
1262
- }
1263
-
1264
- // This API will tag the children with the side-effect of the reconciliation
1265
- // itself. They will be added to the side-effect list as we pass through the
1266
- // children and the parent.
1267
- function reconcileChildFibers(
1268
- returnFiber: Fiber,
1269
- currentFirstChild: Fiber | null,
1270
- newChild: any,
1271
- lanes: Lanes,
1272
- ): Fiber | null {
1273
- // This function is not recursive.
1274
- // If the top level item is an array, we treat it as a set of children,
1275
- // not as a fragment. Nested arrays on the other hand will be treated as
1276
- // fragment nodes. Recursion happens at the normal flow.
1277
-
1278
- // Handle top level unkeyed fragments as if they were arrays.
1279
- // This leads to an ambiguity between <>{[...]}</> and <>...</>.
1280
- // We treat the ambiguous cases above the same.
1281
- const isUnkeyedTopLevelFragment =
1282
- typeof newChild === 'object' &&
1283
- newChild !== null &&
1284
- newChild.type === REACT_FRAGMENT_TYPE &&
1285
- newChild.key === null;
1286
- if (isUnkeyedTopLevelFragment) {
1287
- newChild = newChild.props.children;
1288
- }
1289
-
1290
- // Handle object types
1291
- if (typeof newChild === 'object' && newChild !== null) {
1292
- switch (newChild.$$typeof) {
1293
- case REACT_ELEMENT_TYPE:
1294
- return placeSingleChild(
1295
- reconcileSingleElement(
1296
- returnFiber,
1297
- currentFirstChild,
1298
- newChild,
1299
- lanes,
1300
- ),
1301
- );
1302
- case REACT_PORTAL_TYPE:
1303
- return placeSingleChild(
1304
- reconcileSinglePortal(
1305
- returnFiber,
1306
- currentFirstChild,
1307
- newChild,
1308
- lanes,
1309
- ),
1310
- );
1311
- case REACT_LAZY_TYPE:
1312
- const payload = newChild._payload;
1313
- const init = newChild._init;
1314
- // TODO: This function is supposed to be non-recursive.
1315
- return reconcileChildFibers(
1316
- returnFiber,
1317
- currentFirstChild,
1318
- init(payload),
1319
- lanes,
1320
- );
1321
- }
1322
-
1323
- if (isArray(newChild)) {
1324
- return reconcileChildrenArray(
1325
- returnFiber,
1326
- currentFirstChild,
1327
- newChild,
1328
- lanes,
1329
- );
1330
- }
1331
-
1332
- if (getIteratorFn(newChild)) {
1333
- return reconcileChildrenIterator(
1334
- returnFiber,
1335
- currentFirstChild,
1336
- newChild,
1337
- lanes,
1338
- );
1339
- }
1340
-
1341
- throwOnInvalidObjectType(returnFiber, newChild);
1342
- }
1343
-
1344
- if (
1345
- (typeof newChild === 'string' && newChild !== '') ||
1346
- typeof newChild === 'number'
1347
- ) {
1348
- return placeSingleChild(
1349
- reconcileSingleTextNode(
1350
- returnFiber,
1351
- currentFirstChild,
1352
- '' + newChild,
1353
- lanes,
1354
- ),
1355
- );
1356
- }
1357
-
1358
- if (__DEV__) {
1359
- if (typeof newChild === 'function') {
1360
- warnOnFunctionType(returnFiber);
1361
- }
1362
- }
1363
-
1364
- // Remaining cases are all treated as empty.
1365
- return deleteRemainingChildren(returnFiber, currentFirstChild);
1366
- }
1367
-
1368
- return reconcileChildFibers;
1369
-}
1370
-
1371
-export const reconcileChildFibers: ChildReconciler = createChildReconciler(
1372
- true,
1373
-);
1374
-export const mountChildFibers: ChildReconciler = createChildReconciler(false);
1375
-
1376
-export function cloneChildFibers(
1377
- current: Fiber | null,
1378
- workInProgress: Fiber,
1379
-): void {
1380
- if (current !== null && workInProgress.child !== current.child) {
1381
- throw new Error('Resuming work not yet implemented.');
1382
- }
1383
-
1384
- if (workInProgress.child === null) {
1385
- return;
1386
- }
1387
-
1388
- let currentChild = workInProgress.child;
1389
- let newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
1390
- workInProgress.child = newChild;
1391
-
1392
- newChild.return = workInProgress;
1393
- while (currentChild.sibling !== null) {
1394
- currentChild = currentChild.sibling;
1395
- newChild = newChild.sibling = createWorkInProgress(
1396
- currentChild,
1397
- currentChild.pendingProps,
1398
- );
1399
- newChild.return = workInProgress;
1400
- }
1401
- newChild.sibling = null;
1402
-}
1403
-
1404
-// Reset a workInProgress child set to prepare it for a second pass.
1405
-export function resetChildFibers(workInProgress: Fiber, lanes: Lanes): void {
1406
- let child = workInProgress.child;
1407
- while (child !== null) {
1408
- resetWorkInProgress(child, lanes);
1409
- child = child.sibling;
1410
- }
1411
-}
packages/react-reconciler/src/ReactEventPriorities.js
deleted
-74
@@ -1,74 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import {enableNewReconciler} from 'shared/ReactFeatureFlags';
11
-
12
-import {
13
- DiscreteEventPriority as DiscreteEventPriority_old,
14
- ContinuousEventPriority as ContinuousEventPriority_old,
15
- DefaultEventPriority as DefaultEventPriority_old,
16
- IdleEventPriority as IdleEventPriority_old,
17
- getCurrentUpdatePriority as getCurrentUpdatePriority_old,
18
- setCurrentUpdatePriority as setCurrentUpdatePriority_old,
19
- runWithPriority as runWithPriority_old,
20
- isHigherEventPriority as isHigherEventPriority_old,
21
-} from './ReactEventPriorities.old';
22
-
23
-import {
24
- DiscreteEventPriority as DiscreteEventPriority_new,
25
- ContinuousEventPriority as ContinuousEventPriority_new,
26
- DefaultEventPriority as DefaultEventPriority_new,
27
- IdleEventPriority as IdleEventPriority_new,
28
- getCurrentUpdatePriority as getCurrentUpdatePriority_new,
29
- setCurrentUpdatePriority as setCurrentUpdatePriority_new,
30
- runWithPriority as runWithPriority_new,
31
- isHigherEventPriority as isHigherEventPriority_new,
32
-} from './ReactEventPriorities.new';
33
-
34
-export opaque type EventPriority = number;
35
-
36
-export const DiscreteEventPriority: EventPriority = enableNewReconciler
37
- ? (DiscreteEventPriority_new: any)
38
- : (DiscreteEventPriority_old: any);
39
-export const ContinuousEventPriority: EventPriority = enableNewReconciler
40
- ? (ContinuousEventPriority_new: any)
41
- : (ContinuousEventPriority_old: any);
42
-export const DefaultEventPriority: EventPriority = enableNewReconciler
43
- ? (DefaultEventPriority_new: any)
44
- : (DefaultEventPriority_old: any);
45
-export const IdleEventPriority: EventPriority = enableNewReconciler
46
- ? (IdleEventPriority_new: any)
47
- : (IdleEventPriority_old: any);
48
-
49
-export function runWithPriority<T>(priority: EventPriority, fn: () => T): T {
50
- return enableNewReconciler
51
- ? runWithPriority_new((priority: any), fn)
52
- : runWithPriority_old((priority: any), fn);
53
-}
54
-
55
-export function getCurrentUpdatePriority(): EventPriority {
56
- return enableNewReconciler
57
- ? (getCurrentUpdatePriority_new(): any)
58
- : (getCurrentUpdatePriority_old(): any);
59
-}
60
-
61
-export function setCurrentUpdatePriority(priority: EventPriority): void {
62
- return enableNewReconciler
63
- ? setCurrentUpdatePriority_new((priority: any))
64
- : setCurrentUpdatePriority_old((priority: any));
65
-}
66
-
67
-export function isHigherEventPriority(
68
- a: EventPriority,
69
- b: EventPriority,
70
-): boolean {
71
- return enableNewReconciler
72
- ? isHigherEventPriority_new((a: any), (b: any))
73
- : isHigherEventPriority_old((a: any), (b: any));
74
-}
packages/react-reconciler/src/ReactEventPriorities.new.js
deleted
-82
@@ -1,82 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Lane, Lanes} from './ReactFiberLane.new';
11
-
12
-import {
13
- NoLane,
14
- SyncLane,
15
- InputContinuousLane,
16
- DefaultLane,
17
- IdleLane,
18
- getHighestPriorityLane,
19
- includesNonIdleWork,
20
-} from './ReactFiberLane.new';
21
-
22
-export opaque type EventPriority = Lane;
23
-
24
-export const DiscreteEventPriority: EventPriority = SyncLane;
25
-export const ContinuousEventPriority: EventPriority = InputContinuousLane;
26
-export const DefaultEventPriority: EventPriority = DefaultLane;
27
-export const IdleEventPriority: EventPriority = IdleLane;
28
-
29
-let currentUpdatePriority: EventPriority = NoLane;
30
-
31
-export function getCurrentUpdatePriority(): EventPriority {
32
- return currentUpdatePriority;
33
-}
34
-
35
-export function setCurrentUpdatePriority(newPriority: EventPriority) {
36
- currentUpdatePriority = newPriority;
37
-}
38
-
39
-export function runWithPriority<T>(priority: EventPriority, fn: () => T): T {
40
- const previousPriority = currentUpdatePriority;
41
- try {
42
- currentUpdatePriority = priority;
43
- return fn();
44
- } finally {
45
- currentUpdatePriority = previousPriority;
46
- }
47
-}
48
-
49
-export function higherEventPriority(
50
- a: EventPriority,
51
- b: EventPriority,
52
-): EventPriority {
53
- return a !== 0 && a < b ? a : b;
54
-}
55
-
56
-export function lowerEventPriority(
57
- a: EventPriority,
58
- b: EventPriority,
59
-): EventPriority {
60
- return a === 0 || a > b ? a : b;
61
-}
62
-
63
-export function isHigherEventPriority(
64
- a: EventPriority,
65
- b: EventPriority,
66
-): boolean {
67
- return a !== 0 && a < b;
68
-}
69
-
70
-export function lanesToEventPriority(lanes: Lanes): EventPriority {
71
- const lane = getHighestPriorityLane(lanes);
72
- if (!isHigherEventPriority(DiscreteEventPriority, lane)) {
73
- return DiscreteEventPriority;
74
- }
75
- if (!isHigherEventPriority(ContinuousEventPriority, lane)) {
76
- return ContinuousEventPriority;
77
- }
78
- if (includesNonIdleWork(lane)) {
79
- return DefaultEventPriority;
80
- }
81
- return IdleEventPriority;
82
-}
packages/react-reconciler/src/ReactFiber.new.js
deleted
-910
@@ -1,910 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {ReactElement} from 'shared/ReactElementType';
11
-import type {ReactFragment, ReactPortal, ReactScope} from 'shared/ReactTypes';
12
-import type {Fiber} from './ReactInternalTypes';
13
-import type {RootTag} from './ReactRootTags';
14
-import type {WorkTag} from './ReactWorkTags';
15
-import type {TypeOfMode} from './ReactTypeOfMode';
16
-import type {Lanes} from './ReactFiberLane.new';
17
-import type {SuspenseInstance} from './ReactFiberHostConfig';
18
-import type {
19
- OffscreenProps,
20
- OffscreenInstance,
21
-} from './ReactFiberOffscreenComponent';
22
-import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new';
23
-
24
-import {
25
- supportsResources,
26
- supportsSingletons,
27
- isHostResourceType,
28
- isHostSingletonType,
29
-} from './ReactFiberHostConfig';
30
-import {
31
- createRootStrictEffectsByDefault,
32
- enableCache,
33
- enableProfilerTimer,
34
- enableScopeAPI,
35
- enableLegacyHidden,
36
- enableSyncDefaultUpdates,
37
- allowConcurrentByDefault,
38
- enableTransitionTracing,
39
- enableDebugTracing,
40
- enableFloat,
41
- enableHostSingletons,
42
-} from 'shared/ReactFeatureFlags';
43
-import {NoFlags, Placement, StaticMask} from './ReactFiberFlags';
44
-import {ConcurrentRoot} from './ReactRootTags';
45
-import {
46
- IndeterminateComponent,
47
- ClassComponent,
48
- HostRoot,
49
- HostComponent,
50
- HostText,
51
- HostPortal,
52
- HostResource,
53
- HostSingleton,
54
- ForwardRef,
55
- Fragment,
56
- Mode,
57
- ContextProvider,
58
- ContextConsumer,
59
- Profiler,
60
- SuspenseComponent,
61
- SuspenseListComponent,
62
- DehydratedFragment,
63
- FunctionComponent,
64
- MemoComponent,
65
- SimpleMemoComponent,
66
- LazyComponent,
67
- ScopeComponent,
68
- OffscreenComponent,
69
- LegacyHiddenComponent,
70
- CacheComponent,
71
- TracingMarkerComponent,
72
-} from './ReactWorkTags';
73
-import {OffscreenVisible} from './ReactFiberOffscreenComponent';
74
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
75
-import {isDevToolsPresent} from './ReactFiberDevToolsHook.new';
76
-import {
77
- resolveClassForHotReloading,
78
- resolveFunctionForHotReloading,
79
- resolveForwardRefForHotReloading,
80
-} from './ReactFiberHotReloading.new';
81
-import {NoLanes} from './ReactFiberLane.new';
82
-import {
83
- NoMode,
84
- ConcurrentMode,
85
- DebugTracingMode,
86
- ProfileMode,
87
- StrictLegacyMode,
88
- StrictEffectsMode,
89
- ConcurrentUpdatesByDefaultMode,
90
-} from './ReactTypeOfMode';
91
-import {
92
- REACT_FORWARD_REF_TYPE,
93
- REACT_FRAGMENT_TYPE,
94
- REACT_DEBUG_TRACING_MODE_TYPE,
95
- REACT_STRICT_MODE_TYPE,
96
- REACT_PROFILER_TYPE,
97
- REACT_PROVIDER_TYPE,
98
- REACT_CONTEXT_TYPE,
99
- REACT_SUSPENSE_TYPE,
100
- REACT_SUSPENSE_LIST_TYPE,
101
- REACT_MEMO_TYPE,
102
- REACT_LAZY_TYPE,
103
- REACT_SCOPE_TYPE,
104
- REACT_OFFSCREEN_TYPE,
105
- REACT_LEGACY_HIDDEN_TYPE,
106
- REACT_CACHE_TYPE,
107
- REACT_TRACING_MARKER_TYPE,
108
-} from 'shared/ReactSymbols';
109
-import {TransitionTracingMarker} from './ReactFiberTracingMarkerComponent.new';
110
-import {detachOffscreenInstance} from './ReactFiberCommitWork.new';
111
-import {getHostContext} from './ReactFiberHostContext.new';
112
-
113
-export type {Fiber};
114
-
115
-let hasBadMapPolyfill;
116
-
117
-if (__DEV__) {
118
- hasBadMapPolyfill = false;
119
- try {
120
- const nonExtensibleObject = Object.preventExtensions({});
121
- /* eslint-disable no-new */
122
- new Map([[nonExtensibleObject, null]]);
123
- new Set([nonExtensibleObject]);
124
- /* eslint-enable no-new */
125
- } catch (e) {
126
- // TODO: Consider warning about bad polyfills
127
- hasBadMapPolyfill = true;
128
- }
129
-}
130
-
131
-function FiberNode(
132
- tag: WorkTag,
133
- pendingProps: mixed,
134
- key: null | string,
135
- mode: TypeOfMode,
136
-) {
137
- // Instance
138
- this.tag = tag;
139
- this.key = key;
140
- this.elementType = null;
141
- this.type = null;
142
- this.stateNode = null;
143
-
144
- // Fiber
145
- this.return = null;
146
- this.child = null;
147
- this.sibling = null;
148
- this.index = 0;
149
-
150
- this.ref = null;
151
- this.refCleanup = null;
152
-
153
- this.pendingProps = pendingProps;
154
- this.memoizedProps = null;
155
- this.updateQueue = null;
156
- this.memoizedState = null;
157
- this.dependencies = null;
158
-
159
- this.mode = mode;
160
-
161
- // Effects
162
- this.flags = NoFlags;
163
- this.subtreeFlags = NoFlags;
164
- this.deletions = null;
165
-
166
- this.lanes = NoLanes;
167
- this.childLanes = NoLanes;
168
-
169
- this.alternate = null;
170
-
171
- if (enableProfilerTimer) {
172
- // Note: The following is done to avoid a v8 performance cliff.
173
- //
174
- // Initializing the fields below to smis and later updating them with
175
- // double values will cause Fibers to end up having separate shapes.
176
- // This behavior/bug has something to do with Object.preventExtension().
177
- // Fortunately this only impacts DEV builds.
178
- // Unfortunately it makes React unusably slow for some applications.
179
- // To work around this, initialize the fields below with doubles.
180
- //
181
- // Learn more about this here:
182
- // https://github.com/facebook/react/issues/14365
183
- // https://bugs.chromium.org/p/v8/issues/detail?id=8538
184
- this.actualDuration = Number.NaN;
185
- this.actualStartTime = Number.NaN;
186
- this.selfBaseDuration = Number.NaN;
187
- this.treeBaseDuration = Number.NaN;
188
-
189
- // It's okay to replace the initial doubles with smis after initialization.
190
- // This won't trigger the performance cliff mentioned above,
191
- // and it simplifies other profiler code (including DevTools).
192
- this.actualDuration = 0;
193
- this.actualStartTime = -1;
194
- this.selfBaseDuration = 0;
195
- this.treeBaseDuration = 0;
196
- }
197
-
198
- if (__DEV__) {
199
- // This isn't directly used but is handy for debugging internals:
200
-
201
- this._debugSource = null;
202
- this._debugOwner = null;
203
- this._debugNeedsRemount = false;
204
- this._debugHookTypes = null;
205
- if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
206
- Object.preventExtensions(this);
207
- }
208
- }
209
-}
210
-
211
-// This is a constructor function, rather than a POJO constructor, still
212
-// please ensure we do the following:
213
-// 1) Nobody should add any instance methods on this. Instance methods can be
214
-// more difficult to predict when they get optimized and they are almost
215
-// never inlined properly in static compilers.
216
-// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
217
-// always know when it is a fiber.
218
-// 3) We might want to experiment with using numeric keys since they are easier
219
-// to optimize in a non-JIT environment.
220
-// 4) We can easily go from a constructor to a createFiber object literal if that
221
-// is faster.
222
-// 5) It should be easy to port this to a C struct and keep a C implementation
223
-// compatible.
224
-const createFiber = function(
225
- tag: WorkTag,
226
- pendingProps: mixed,
227
- key: null | string,
228
- mode: TypeOfMode,
229
-): Fiber {
230
- // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
231
- return new FiberNode(tag, pendingProps, key, mode);
232
-};
233
-
234
-function shouldConstruct(Component: Function) {
235
- const prototype = Component.prototype;
236
- return !!(prototype && prototype.isReactComponent);
237
-}
238
-
239
-export function isSimpleFunctionComponent(type: any): boolean {
240
- return (
241
- typeof type === 'function' &&
242
- !shouldConstruct(type) &&
243
- type.defaultProps === undefined
244
- );
245
-}
246
-
247
-export function resolveLazyComponentTag(Component: Function): WorkTag {
248
- if (typeof Component === 'function') {
249
- return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
250
- } else if (Component !== undefined && Component !== null) {
251
- const $$typeof = Component.$$typeof;
252
- if ($$typeof === REACT_FORWARD_REF_TYPE) {
253
- return ForwardRef;
254
- }
255
- if ($$typeof === REACT_MEMO_TYPE) {
256
- return MemoComponent;
257
- }
258
- }
259
- return IndeterminateComponent;
260
-}
261
-
262
-// This is used to create an alternate fiber to do work on.
263
-export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
264
- let workInProgress = current.alternate;
265
- if (workInProgress === null) {
266
- // We use a double buffering pooling technique because we know that we'll
267
- // only ever need at most two versions of a tree. We pool the "other" unused
268
- // node that we're free to reuse. This is lazily created to avoid allocating
269
- // extra objects for things that are never updated. It also allow us to
270
- // reclaim the extra memory if needed.
271
- workInProgress = createFiber(
272
- current.tag,
273
- pendingProps,
274
- current.key,
275
- current.mode,
276
- );
277
- workInProgress.elementType = current.elementType;
278
- workInProgress.type = current.type;
279
- workInProgress.stateNode = current.stateNode;
280
-
281
- if (__DEV__) {
282
- // DEV-only fields
283
-
284
- workInProgress._debugSource = current._debugSource;
285
- workInProgress._debugOwner = current._debugOwner;
286
- workInProgress._debugHookTypes = current._debugHookTypes;
287
- }
288
-
289
- workInProgress.alternate = current;
290
- current.alternate = workInProgress;
291
- } else {
292
- workInProgress.pendingProps = pendingProps;
293
- // Needed because Blocks store data on type.
294
- workInProgress.type = current.type;
295
-
296
- // We already have an alternate.
297
- // Reset the effect tag.
298
- workInProgress.flags = NoFlags;
299
-
300
- // The effects are no longer valid.
301
- workInProgress.subtreeFlags = NoFlags;
302
- workInProgress.deletions = null;
303
-
304
- if (enableProfilerTimer) {
305
- // We intentionally reset, rather than copy, actualDuration & actualStartTime.
306
- // This prevents time from endlessly accumulating in new commits.
307
- // This has the downside of resetting values for different priority renders,
308
- // But works for yielding (the common case) and should support resuming.
309
- workInProgress.actualDuration = 0;
310
- workInProgress.actualStartTime = -1;
311
- }
312
- }
313
-
314
- // Reset all effects except static ones.
315
- // Static effects are not specific to a render.
316
- workInProgress.flags = current.flags & StaticMask;
317
- workInProgress.childLanes = current.childLanes;
318
- workInProgress.lanes = current.lanes;
319
-
320
- workInProgress.child = current.child;
321
- workInProgress.memoizedProps = current.memoizedProps;
322
- workInProgress.memoizedState = current.memoizedState;
323
- workInProgress.updateQueue = current.updateQueue;
324
-
325
- // Clone the dependencies object. This is mutated during the render phase, so
326
- // it cannot be shared with the current fiber.
327
- const currentDependencies = current.dependencies;
328
- workInProgress.dependencies =
329
- currentDependencies === null
330
- ? null
331
- : {
332
- lanes: currentDependencies.lanes,
333
- firstContext: currentDependencies.firstContext,
334
- };
335
-
336
- // These will be overridden during the parent's reconciliation
337
- workInProgress.sibling = current.sibling;
338
- workInProgress.index = current.index;
339
- workInProgress.ref = current.ref;
340
- workInProgress.refCleanup = current.refCleanup;
341
-
342
- if (enableProfilerTimer) {
343
- workInProgress.selfBaseDuration = current.selfBaseDuration;
344
- workInProgress.treeBaseDuration = current.treeBaseDuration;
345
- }
346
-
347
- if (__DEV__) {
348
- workInProgress._debugNeedsRemount = current._debugNeedsRemount;
349
- switch (workInProgress.tag) {
350
- case IndeterminateComponent:
351
- case FunctionComponent:
352
- case SimpleMemoComponent:
353
- workInProgress.type = resolveFunctionForHotReloading(current.type);
354
- break;
355
- case ClassComponent:
356
- workInProgress.type = resolveClassForHotReloading(current.type);
357
- break;
358
- case ForwardRef:
359
- workInProgress.type = resolveForwardRefForHotReloading(current.type);
360
- break;
361
- default:
362
- break;
363
- }
364
- }
365
-
366
- return workInProgress;
367
-}
368
-
369
-// Used to reuse a Fiber for a second pass.
370
-export function resetWorkInProgress(
371
- workInProgress: Fiber,
372
- renderLanes: Lanes,
373
-): Fiber {
374
- // This resets the Fiber to what createFiber or createWorkInProgress would
375
- // have set the values to before during the first pass. Ideally this wouldn't
376
- // be necessary but unfortunately many code paths reads from the workInProgress
377
- // when they should be reading from current and writing to workInProgress.
378
-
379
- // We assume pendingProps, index, key, ref, return are still untouched to
380
- // avoid doing another reconciliation.
381
-
382
- // Reset the effect flags but keep any Placement tags, since that's something
383
- // that child fiber is setting, not the reconciliation.
384
- workInProgress.flags &= StaticMask | Placement;
385
-
386
- // The effects are no longer valid.
387
-
388
- const current = workInProgress.alternate;
389
- if (current === null) {
390
- // Reset to createFiber's initial values.
391
- workInProgress.childLanes = NoLanes;
392
- workInProgress.lanes = renderLanes;
393
-
394
- workInProgress.child = null;
395
- workInProgress.subtreeFlags = NoFlags;
396
- workInProgress.memoizedProps = null;
397
- workInProgress.memoizedState = null;
398
- workInProgress.updateQueue = null;
399
-
400
- workInProgress.dependencies = null;
401
-
402
- workInProgress.stateNode = null;
403
-
404
- if (enableProfilerTimer) {
405
- // Note: We don't reset the actualTime counts. It's useful to accumulate
406
- // actual time across multiple render passes.
407
- workInProgress.selfBaseDuration = 0;
408
- workInProgress.treeBaseDuration = 0;
409
- }
410
- } else {
411
- // Reset to the cloned values that createWorkInProgress would've.
412
- workInProgress.childLanes = current.childLanes;
413
- workInProgress.lanes = current.lanes;
414
-
415
- workInProgress.child = current.child;
416
- workInProgress.subtreeFlags = NoFlags;
417
- workInProgress.deletions = null;
418
- workInProgress.memoizedProps = current.memoizedProps;
419
- workInProgress.memoizedState = current.memoizedState;
420
- workInProgress.updateQueue = current.updateQueue;
421
- // Needed because Blocks store data on type.
422
- workInProgress.type = current.type;
423
-
424
- // Clone the dependencies object. This is mutated during the render phase, so
425
- // it cannot be shared with the current fiber.
426
- const currentDependencies = current.dependencies;
427
- workInProgress.dependencies =
428
- currentDependencies === null
429
- ? null
430
- : {
431
- lanes: currentDependencies.lanes,
432
- firstContext: currentDependencies.firstContext,
433
- };
434
-
435
- if (enableProfilerTimer) {
436
- // Note: We don't reset the actualTime counts. It's useful to accumulate
437
- // actual time across multiple render passes.
438
- workInProgress.selfBaseDuration = current.selfBaseDuration;
439
- workInProgress.treeBaseDuration = current.treeBaseDuration;
440
- }
441
- }
442
-
443
- return workInProgress;
444
-}
445
-
446
-export function createHostRootFiber(
447
- tag: RootTag,
448
- isStrictMode: boolean,
449
- concurrentUpdatesByDefaultOverride: null | boolean,
450
-): Fiber {
451
- let mode;
452
- if (tag === ConcurrentRoot) {
453
- mode = ConcurrentMode;
454
- if (isStrictMode === true || createRootStrictEffectsByDefault) {
455
- mode |= StrictLegacyMode | StrictEffectsMode;
456
- }
457
- if (
458
- // We only use this flag for our repo tests to check both behaviors.
459
- // TODO: Flip this flag and rename it something like "forceConcurrentByDefaultForTesting"
460
- !enableSyncDefaultUpdates ||
461
- // Only for internal experiments.
462
- (allowConcurrentByDefault && concurrentUpdatesByDefaultOverride)
463
- ) {
464
- mode |= ConcurrentUpdatesByDefaultMode;
465
- }
466
- } else {
467
- mode = NoMode;
468
- }
469
-
470
- if (enableProfilerTimer && isDevToolsPresent) {
471
- // Always collect profile timings when DevTools are present.
472
- // This enables DevTools to start capturing timing at any point–
473
- // Without some nodes in the tree having empty base times.
474
- mode |= ProfileMode;
475
- }
476
-
477
- return createFiber(HostRoot, null, null, mode);
478
-}
479
-
480
-export function createFiberFromTypeAndProps(
481
- type: any, // React$ElementType
482
- key: null | string,
483
- pendingProps: any,
484
- owner: null | Fiber,
485
- mode: TypeOfMode,
486
- lanes: Lanes,
487
-): Fiber {
488
- let fiberTag = IndeterminateComponent;
489
- // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
490
- let resolvedType = type;
491
- if (typeof type === 'function') {
492
- if (shouldConstruct(type)) {
493
- fiberTag = ClassComponent;
494
- if (__DEV__) {
495
- resolvedType = resolveClassForHotReloading(resolvedType);
496
- }
497
- } else {
498
- if (__DEV__) {
499
- resolvedType = resolveFunctionForHotReloading(resolvedType);
500
- }
501
- }
502
- } else if (typeof type === 'string') {
503
- if (
504
- enableFloat &&
505
- supportsResources &&
506
- enableHostSingletons &&
507
- supportsSingletons
508
- ) {
509
- const hostContext = getHostContext();
510
- fiberTag = isHostResourceType(type, pendingProps, hostContext)
511
- ? HostResource
512
- : isHostSingletonType(type)
513
- ? HostSingleton
514
- : HostComponent;
515
- } else if (enableFloat && supportsResources) {
516
- const hostContext = getHostContext();
517
- fiberTag = isHostResourceType(type, pendingProps, hostContext)
518
- ? HostResource
519
- : HostComponent;
520
- } else if (enableHostSingletons && supportsSingletons) {
521
- fiberTag = isHostSingletonType(type) ? HostSingleton : HostComponent;
522
- } else {
523
- fiberTag = HostComponent;
524
- }
525
- } else {
526
- getTag: switch (type) {
527
- case REACT_FRAGMENT_TYPE:
528
- return createFiberFromFragment(pendingProps.children, mode, lanes, key);
529
- case REACT_STRICT_MODE_TYPE:
530
- fiberTag = Mode;
531
- mode |= StrictLegacyMode;
532
- if ((mode & ConcurrentMode) !== NoMode) {
533
- // Strict effects should never run on legacy roots
534
- mode |= StrictEffectsMode;
535
- }
536
- break;
537
- case REACT_PROFILER_TYPE:
538
- return createFiberFromProfiler(pendingProps, mode, lanes, key);
539
- case REACT_SUSPENSE_TYPE:
540
- return createFiberFromSuspense(pendingProps, mode, lanes, key);
541
- case REACT_SUSPENSE_LIST_TYPE:
542
- return createFiberFromSuspenseList(pendingProps, mode, lanes, key);
543
- case REACT_OFFSCREEN_TYPE:
544
- return createFiberFromOffscreen(pendingProps, mode, lanes, key);
545
- case REACT_LEGACY_HIDDEN_TYPE:
546
- if (enableLegacyHidden) {
547
- return createFiberFromLegacyHidden(pendingProps, mode, lanes, key);
548
- }
549
- // eslint-disable-next-line no-fallthrough
550
- case REACT_SCOPE_TYPE:
551
- if (enableScopeAPI) {
552
- return createFiberFromScope(type, pendingProps, mode, lanes, key);
553
- }
554
- // eslint-disable-next-line no-fallthrough
555
- case REACT_CACHE_TYPE:
556
- if (enableCache) {
557
- return createFiberFromCache(pendingProps, mode, lanes, key);
558
- }
559
- // eslint-disable-next-line no-fallthrough
560
- case REACT_TRACING_MARKER_TYPE:
561
- if (enableTransitionTracing) {
562
- return createFiberFromTracingMarker(pendingProps, mode, lanes, key);
563
- }
564
- // eslint-disable-next-line no-fallthrough
565
- case REACT_DEBUG_TRACING_MODE_TYPE:
566
- if (enableDebugTracing) {
567
- fiberTag = Mode;
568
- mode |= DebugTracingMode;
569
- break;
570
- }
571
- // eslint-disable-next-line no-fallthrough
572
- default: {
573
- if (typeof type === 'object' && type !== null) {
574
- switch (type.$$typeof) {
575
- case REACT_PROVIDER_TYPE:
576
- fiberTag = ContextProvider;
577
- break getTag;
578
- case REACT_CONTEXT_TYPE:
579
- // This is a consumer
580
- fiberTag = ContextConsumer;
581
- break getTag;
582
- case REACT_FORWARD_REF_TYPE:
583
- fiberTag = ForwardRef;
584
- if (__DEV__) {
585
- resolvedType = resolveForwardRefForHotReloading(resolvedType);
586
- }
587
- break getTag;
588
- case REACT_MEMO_TYPE:
589
- fiberTag = MemoComponent;
590
- break getTag;
591
- case REACT_LAZY_TYPE:
592
- fiberTag = LazyComponent;
593
- resolvedType = null;
594
- break getTag;
595
- }
596
- }
597
- let info = '';
598
- if (__DEV__) {
599
- if (
600
- type === undefined ||
601
- (typeof type === 'object' &&
602
- type !== null &&
603
- Object.keys(type).length === 0)
604
- ) {
605
- info +=
606
- ' You likely forgot to export your component from the file ' +
607
- "it's defined in, or you might have mixed up default and " +
608
- 'named imports.';
609
- }
610
- const ownerName = owner ? getComponentNameFromFiber(owner) : null;
611
- if (ownerName) {
612
- info += '\n\nCheck the render method of `' + ownerName + '`.';
613
- }
614
- }
615
-
616
- throw new Error(
617
- 'Element type is invalid: expected a string (for built-in ' +
618
- 'components) or a class/function (for composite components) ' +
619
- `but got: ${type == null ? type : typeof type}.${info}`,
620
- );
621
- }
622
- }
623
- }
624
-
625
- const fiber = createFiber(fiberTag, pendingProps, key, mode);
626
- fiber.elementType = type;
627
- fiber.type = resolvedType;
628
- fiber.lanes = lanes;
629
-
630
- if (__DEV__) {
631
- fiber._debugOwner = owner;
632
- }
633
-
634
- return fiber;
635
-}
636
-
637
-export function createFiberFromElement(
638
- element: ReactElement,
639
- mode: TypeOfMode,
640
- lanes: Lanes,
641
-): Fiber {
642
- let owner = null;
643
- if (__DEV__) {
644
- owner = element._owner;
645
- }
646
- const type = element.type;
647
- const key = element.key;
648
- const pendingProps = element.props;
649
- const fiber = createFiberFromTypeAndProps(
650
- type,
651
- key,
652
- pendingProps,
653
- owner,
654
- mode,
655
- lanes,
656
- );
657
- if (__DEV__) {
658
- fiber._debugSource = element._source;
659
- fiber._debugOwner = element._owner;
660
- }
661
- return fiber;
662
-}
663
-
664
-export function createFiberFromFragment(
665
- elements: ReactFragment,
666
- mode: TypeOfMode,
667
- lanes: Lanes,
668
- key: null | string,
669
-): Fiber {
670
- const fiber = createFiber(Fragment, elements, key, mode);
671
- fiber.lanes = lanes;
672
- return fiber;
673
-}
674
-
675
-function createFiberFromScope(
676
- scope: ReactScope,
677
- pendingProps: any,
678
- mode: TypeOfMode,
679
- lanes: Lanes,
680
- key: null | string,
681
-) {
682
- const fiber = createFiber(ScopeComponent, pendingProps, key, mode);
683
- fiber.type = scope;
684
- fiber.elementType = scope;
685
- fiber.lanes = lanes;
686
- return fiber;
687
-}
688
-
689
-function createFiberFromProfiler(
690
- pendingProps: any,
691
- mode: TypeOfMode,
692
- lanes: Lanes,
693
- key: null | string,
694
-): Fiber {
695
- if (__DEV__) {
696
- if (typeof pendingProps.id !== 'string') {
697
- console.error(
698
- 'Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.',
699
- typeof pendingProps.id,
700
- );
701
- }
702
- }
703
-
704
- const fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
705
- fiber.elementType = REACT_PROFILER_TYPE;
706
- fiber.lanes = lanes;
707
-
708
- if (enableProfilerTimer) {
709
- fiber.stateNode = {
710
- effectDuration: 0,
711
- passiveEffectDuration: 0,
712
- };
713
- }
714
-
715
- return fiber;
716
-}
717
-
718
-export function createFiberFromSuspense(
719
- pendingProps: any,
720
- mode: TypeOfMode,
721
- lanes: Lanes,
722
- key: null | string,
723
-): Fiber {
724
- const fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
725
- fiber.elementType = REACT_SUSPENSE_TYPE;
726
- fiber.lanes = lanes;
727
- return fiber;
728
-}
729
-
730
-export function createFiberFromSuspenseList(
731
- pendingProps: any,
732
- mode: TypeOfMode,
733
- lanes: Lanes,
734
- key: null | string,
735
-): Fiber {
736
- const fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
737
- fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
738
- fiber.lanes = lanes;
739
- return fiber;
740
-}
741
-
742
-export function createFiberFromOffscreen(
743
- pendingProps: OffscreenProps,
744
- mode: TypeOfMode,
745
- lanes: Lanes,
746
- key: null | string,
747
-): Fiber {
748
- const fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
749
- fiber.elementType = REACT_OFFSCREEN_TYPE;
750
- fiber.lanes = lanes;
751
- const primaryChildInstance: OffscreenInstance = {
752
- _visibility: OffscreenVisible,
753
- _pendingMarkers: null,
754
- _retryCache: null,
755
- _transitions: null,
756
- _current: null,
757
- detach: () => detachOffscreenInstance(primaryChildInstance),
758
- };
759
- fiber.stateNode = primaryChildInstance;
760
- return fiber;
761
-}
762
-
763
-export function createFiberFromLegacyHidden(
764
- pendingProps: OffscreenProps,
765
- mode: TypeOfMode,
766
- lanes: Lanes,
767
- key: null | string,
768
-): Fiber {
769
- const fiber = createFiber(LegacyHiddenComponent, pendingProps, key, mode);
770
- fiber.elementType = REACT_LEGACY_HIDDEN_TYPE;
771
- fiber.lanes = lanes;
772
- // Adding a stateNode for legacy hidden because it's currently using
773
- // the offscreen implementation, which depends on a state node
774
- const instance: OffscreenInstance = {
775
- _visibility: OffscreenVisible,
776
- _pendingMarkers: null,
777
- _transitions: null,
778
- _retryCache: null,
779
- _current: null,
780
- detach: () => detachOffscreenInstance(instance),
781
- };
782
- fiber.stateNode = instance;
783
- return fiber;
784
-}
785
-
786
-export function createFiberFromCache(
787
- pendingProps: any,
788
- mode: TypeOfMode,
789
- lanes: Lanes,
790
- key: null | string,
791
-): Fiber {
792
- const fiber = createFiber(CacheComponent, pendingProps, key, mode);
793
- fiber.elementType = REACT_CACHE_TYPE;
794
- fiber.lanes = lanes;
795
- return fiber;
796
-}
797
-
798
-export function createFiberFromTracingMarker(
799
- pendingProps: any,
800
- mode: TypeOfMode,
801
- lanes: Lanes,
802
- key: null | string,
803
-): Fiber {
804
- const fiber = createFiber(TracingMarkerComponent, pendingProps, key, mode);
805
- fiber.elementType = REACT_TRACING_MARKER_TYPE;
806
- fiber.lanes = lanes;
807
- const tracingMarkerInstance: TracingMarkerInstance = {
808
- tag: TransitionTracingMarker,
809
- transitions: null,
810
- pendingBoundaries: null,
811
- aborts: null,
812
- name: pendingProps.name,
813
- };
814
- fiber.stateNode = tracingMarkerInstance;
815
- return fiber;
816
-}
817
-
818
-export function createFiberFromText(
819
- content: string,
820
- mode: TypeOfMode,
821
- lanes: Lanes,
822
-): Fiber {
823
- const fiber = createFiber(HostText, content, null, mode);
824
- fiber.lanes = lanes;
825
- return fiber;
826
-}
827
-
828
-export function createFiberFromHostInstanceForDeletion(): Fiber {
829
- const fiber = createFiber(HostComponent, null, null, NoMode);
830
- fiber.elementType = 'DELETED';
831
- return fiber;
832
-}
833
-
834
-export function createFiberFromDehydratedFragment(
835
- dehydratedNode: SuspenseInstance,
836
-): Fiber {
837
- const fiber = createFiber(DehydratedFragment, null, null, NoMode);
838
- fiber.stateNode = dehydratedNode;
839
- return fiber;
840
-}
841
-
842
-export function createFiberFromPortal(
843
- portal: ReactPortal,
844
- mode: TypeOfMode,
845
- lanes: Lanes,
846
-): Fiber {
847
- const pendingProps = portal.children !== null ? portal.children : [];
848
- const fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
849
- fiber.lanes = lanes;
850
- fiber.stateNode = {
851
- containerInfo: portal.containerInfo,
852
- pendingChildren: null, // Used by persistent updates
853
- implementation: portal.implementation,
854
- };
855
- return fiber;
856
-}
857
-
858
-// Used for stashing WIP properties to replay failed work in DEV.
859
-export function assignFiberPropertiesInDEV(
860
- target: Fiber | null,
861
- source: Fiber,
862
-): Fiber {
863
- if (target === null) {
864
- // This Fiber's initial properties will always be overwritten.
865
- // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
866
- target = createFiber(IndeterminateComponent, null, null, NoMode);
867
- }
868
-
869
- // This is intentionally written as a list of all properties.
870
- // We tried to use Object.assign() instead but this is called in
871
- // the hottest path, and Object.assign() was too slow:
872
- // https://github.com/facebook/react/issues/12502
873
- // This code is DEV-only so size is not a concern.
874
-
875
- target.tag = source.tag;
876
- target.key = source.key;
877
- target.elementType = source.elementType;
878
- target.type = source.type;
879
- target.stateNode = source.stateNode;
880
- target.return = source.return;
881
- target.child = source.child;
882
- target.sibling = source.sibling;
883
- target.index = source.index;
884
- target.ref = source.ref;
885
- target.refCleanup = source.refCleanup;
886
- target.pendingProps = source.pendingProps;
887
- target.memoizedProps = source.memoizedProps;
888
- target.updateQueue = source.updateQueue;
889
- target.memoizedState = source.memoizedState;
890
- target.dependencies = source.dependencies;
891
- target.mode = source.mode;
892
- target.flags = source.flags;
893
- target.subtreeFlags = source.subtreeFlags;
894
- target.deletions = source.deletions;
895
- target.lanes = source.lanes;
896
- target.childLanes = source.childLanes;
897
- target.alternate = source.alternate;
898
- if (enableProfilerTimer) {
899
- target.actualDuration = source.actualDuration;
900
- target.actualStartTime = source.actualStartTime;
901
- target.selfBaseDuration = source.selfBaseDuration;
902
- target.treeBaseDuration = source.treeBaseDuration;
903
- }
904
-
905
- target._debugSource = source._debugSource;
906
- target._debugOwner = source._debugOwner;
907
- target._debugNeedsRemount = source._debugNeedsRemount;
908
- target._debugHookTypes = source._debugHookTypes;
909
- return target;
910
-}
packages/react-reconciler/src/ReactFiberAct.new.js
deleted
-57
@@ -1,57 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactFiber.new';
11
-
12
-import ReactSharedInternals from 'shared/ReactSharedInternals';
13
-
14
-import {warnsIfNotActing} from './ReactFiberHostConfig';
15
-
16
-const {ReactCurrentActQueue} = ReactSharedInternals;
17
-
18
-export function isLegacyActEnvironment(fiber: Fiber): boolean {
19
- if (__DEV__) {
20
- // Legacy mode. We preserve the behavior of React 17's act. It assumes an
21
- // act environment whenever `jest` is defined, but you can still turn off
22
- // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly
23
- // to false.
24
-
25
- const isReactActEnvironmentGlobal =
26
- // $FlowFixMe – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
27
- typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined'
28
- ? IS_REACT_ACT_ENVIRONMENT
29
- : undefined;
30
-
31
- // $FlowFixMe - Flow doesn't know about jest
32
- const jestIsDefined = typeof jest !== 'undefined';
33
- return (
34
- warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false
35
- );
36
- }
37
- return false;
38
-}
39
-
40
-export function isConcurrentActEnvironment(): void | boolean {
41
- if (__DEV__) {
42
- const isReactActEnvironmentGlobal =
43
- typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined'
44
- ? IS_REACT_ACT_ENVIRONMENT
45
- : undefined;
46
-
47
- if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) {
48
- // TODO: Include link to relevant documentation page.
49
- console.error(
50
- 'The current testing environment is not configured to support ' +
51
- 'act(...)',
52
- );
53
- }
54
- return isReactActEnvironmentGlobal;
55
- }
56
- return false;
57
-}
packages/react-reconciler/src/ReactFiberBeginWork.new.js
deleted
-4212
@@ -1,4212 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {
11
- ReactProviderType,
12
- ReactContext,
13
- ReactNodeList,
14
- MutableSource,
15
-} from 'shared/ReactTypes';
16
-import type {LazyComponent as LazyComponentType} from 'react/src/ReactLazy';
17
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
18
-import type {TypeOfMode} from './ReactTypeOfMode';
19
-import type {Lanes, Lane} from './ReactFiberLane.new';
20
-import type {
21
- SuspenseState,
22
- SuspenseListRenderState,
23
- SuspenseListTailMode,
24
-} from './ReactFiberSuspenseComponent.new';
25
-import type {SuspenseContext} from './ReactFiberSuspenseContext.new';
26
-import type {
27
- OffscreenProps,
28
- OffscreenState,
29
- OffscreenQueue,
30
- OffscreenInstance,
31
-} from './ReactFiberOffscreenComponent';
32
-import {OffscreenDetached} from './ReactFiberOffscreenComponent';
33
-import type {
34
- Cache,
35
- CacheComponentState,
36
- SpawnedCachePool,
37
-} from './ReactFiberCacheComponent.new';
38
-import type {UpdateQueue} from './ReactFiberClassUpdateQueue.new';
39
-import type {RootState} from './ReactFiberRoot.new';
40
-import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new';
41
-
42
-import checkPropTypes from 'shared/checkPropTypes';
43
-import {
44
- markComponentRenderStarted,
45
- markComponentRenderStopped,
46
- setIsStrictModeForDevtools,
47
-} from './ReactFiberDevToolsHook.new';
48
-import {
49
- IndeterminateComponent,
50
- FunctionComponent,
51
- ClassComponent,
52
- HostRoot,
53
- HostComponent,
54
- HostResource,
55
- HostSingleton,
56
- HostText,
57
- HostPortal,
58
- ForwardRef,
59
- Fragment,
60
- Mode,
61
- ContextProvider,
62
- ContextConsumer,
63
- Profiler,
64
- SuspenseComponent,
65
- SuspenseListComponent,
66
- MemoComponent,
67
- SimpleMemoComponent,
68
- LazyComponent,
69
- IncompleteClassComponent,
70
- ScopeComponent,
71
- OffscreenComponent,
72
- LegacyHiddenComponent,
73
- CacheComponent,
74
- TracingMarkerComponent,
75
-} from './ReactWorkTags';
76
-import {
77
- NoFlags,
78
- PerformedWork,
79
- Placement,
80
- Hydrating,
81
- ContentReset,
82
- DidCapture,
83
- Update,
84
- Ref,
85
- RefStatic,
86
- ChildDeletion,
87
- ForceUpdateForLegacySuspense,
88
- StaticMask,
89
- ShouldCapture,
90
- ForceClientRender,
91
- Passive,
92
-} from './ReactFiberFlags';
93
-import ReactSharedInternals from 'shared/ReactSharedInternals';
94
-import {
95
- debugRenderPhaseSideEffectsForStrictMode,
96
- disableLegacyContext,
97
- disableModulePatternComponents,
98
- enableProfilerCommitHooks,
99
- enableProfilerTimer,
100
- warnAboutDefaultPropsOnFunctionComponents,
101
- enableScopeAPI,
102
- enableCache,
103
- enableLazyContextPropagation,
104
- enableSchedulingProfiler,
105
- enableTransitionTracing,
106
- enableLegacyHidden,
107
- enableCPUSuspense,
108
- enableUseMutableSource,
109
- enableFloat,
110
- enableHostSingletons,
111
-} from 'shared/ReactFeatureFlags';
112
-import isArray from 'shared/isArray';
113
-import shallowEqual from 'shared/shallowEqual';
114
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
115
-import getComponentNameFromType from 'shared/getComponentNameFromType';
116
-import ReactStrictModeWarnings from './ReactStrictModeWarnings.new';
117
-import {REACT_LAZY_TYPE, getIteratorFn} from 'shared/ReactSymbols';
118
-import {
119
- getCurrentFiberOwnerNameInDevOrNull,
120
- setIsRendering,
121
-} from './ReactCurrentFiber';
122
-import {
123
- resolveFunctionForHotReloading,
124
- resolveForwardRefForHotReloading,
125
- resolveClassForHotReloading,
126
-} from './ReactFiberHotReloading.new';
127
-
128
-import {
129
- mountChildFibers,
130
- reconcileChildFibers,
131
- cloneChildFibers,
132
-} from './ReactChildFiber.new';
133
-import {
134
- processUpdateQueue,
135
- cloneUpdateQueue,
136
- initializeUpdateQueue,
137
- enqueueCapturedUpdate,
138
-} from './ReactFiberClassUpdateQueue.new';
139
-import {
140
- NoLane,
141
- NoLanes,
142
- SyncLane,
143
- OffscreenLane,
144
- DefaultHydrationLane,
145
- SomeRetryLane,
146
- NoTimestamp,
147
- includesSomeLane,
148
- laneToLanes,
149
- removeLanes,
150
- mergeLanes,
151
- getBumpedLaneForHydration,
152
- pickArbitraryLane,
153
-} from './ReactFiberLane.new';
154
-import {
155
- ConcurrentMode,
156
- NoMode,
157
- ProfileMode,
158
- StrictLegacyMode,
159
-} from './ReactTypeOfMode';
160
-import {
161
- shouldSetTextContent,
162
- isSuspenseInstancePending,
163
- isSuspenseInstanceFallback,
164
- getSuspenseInstanceFallbackErrorDetails,
165
- registerSuspenseInstanceRetry,
166
- supportsHydration,
167
- supportsResources,
168
- supportsSingletons,
169
- isPrimaryRenderer,
170
- getResource,
171
-} from './ReactFiberHostConfig';
172
-import type {SuspenseInstance} from './ReactFiberHostConfig';
173
-import {shouldError, shouldSuspend} from './ReactFiberReconciler';
174
-import {pushHostContext, pushHostContainer} from './ReactFiberHostContext.new';
175
-import {
176
- suspenseStackCursor,
177
- pushSuspenseListContext,
178
- ForceSuspenseFallback,
179
- hasSuspenseListContext,
180
- setDefaultShallowSuspenseListContext,
181
- setShallowSuspenseListContext,
182
- pushPrimaryTreeSuspenseHandler,
183
- pushFallbackTreeSuspenseHandler,
184
- pushOffscreenSuspenseHandler,
185
- reuseSuspenseHandlerOnStack,
186
- popSuspenseHandler,
187
-} from './ReactFiberSuspenseContext.new';
188
-import {
189
- pushHiddenContext,
190
- reuseHiddenContextOnStack,
191
-} from './ReactFiberHiddenContext.new';
192
-import {findFirstSuspended} from './ReactFiberSuspenseComponent.new';
193
-import {
194
- pushProvider,
195
- propagateContextChange,
196
- lazilyPropagateParentContextChanges,
197
- propagateParentContextChangesToDeferredTree,
198
- checkIfContextChanged,
199
- readContext,
200
- prepareToReadContext,
201
- scheduleContextWorkOnParentPath,
202
-} from './ReactFiberNewContext.new';
203
-import {
204
- renderWithHooks,
205
- checkDidRenderIdHook,
206
- bailoutHooks,
207
- replaySuspendedComponentWithHooks,
208
-} from './ReactFiberHooks.new';
209
-import {stopProfilerTimerIfRunning} from './ReactProfilerTimer.new';
210
-import {
211
- getMaskedContext,
212
- getUnmaskedContext,
213
- hasContextChanged as hasLegacyContextChanged,
214
- pushContextProvider as pushLegacyContextProvider,
215
- isContextProvider as isLegacyContextProvider,
216
- pushTopLevelContextObject,
217
- invalidateContextProvider,
218
-} from './ReactFiberContext.new';
219
-import {
220
- getIsHydrating,
221
- enterHydrationState,
222
- reenterHydrationStateFromDehydratedSuspenseInstance,
223
- resetHydrationState,
224
- claimHydratableSingleton,
225
- tryToClaimNextHydratableInstance,
226
- warnIfHydrating,
227
- queueHydrationError,
228
-} from './ReactFiberHydrationContext.new';
229
-import {
230
- adoptClassInstance,
231
- constructClassInstance,
232
- mountClassInstance,
233
- resumeMountClassInstance,
234
- updateClassInstance,
235
-} from './ReactFiberClassComponent.new';
236
-import {resolveDefaultProps} from './ReactFiberLazyComponent.new';
237
-import {
238
- resolveLazyComponentTag,
239
- createFiberFromTypeAndProps,
240
- createFiberFromFragment,
241
- createFiberFromOffscreen,
242
- createWorkInProgress,
243
- isSimpleFunctionComponent,
244
-} from './ReactFiber.new';
245
-import {
246
- retryDehydratedSuspenseBoundary,
247
- scheduleUpdateOnFiber,
248
- renderDidSuspendDelayIfPossible,
249
- markSkippedUpdateLanes,
250
- getWorkInProgressRoot,
251
-} from './ReactFiberWorkLoop.new';
252
-import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates.new';
253
-import {setWorkInProgressVersion} from './ReactMutableSource.new';
254
-import {pushCacheProvider, CacheContext} from './ReactFiberCacheComponent.new';
255
-import {
256
- createCapturedValue,
257
- createCapturedValueAtFiber,
258
- type CapturedValue,
259
-} from './ReactCapturedValue';
260
-import {createClassErrorUpdate} from './ReactFiberThrow.new';
261
-import is from 'shared/objectIs';
262
-import {
263
- getForksAtLevel,
264
- isForkedChild,
265
- pushTreeId,
266
- pushMaterializedTreeId,
267
-} from './ReactFiberTreeContext.new';
268
-import {
269
- requestCacheFromPool,
270
- pushRootTransition,
271
- getSuspendedCache,
272
- pushTransition,
273
- getOffscreenDeferredCache,
274
- getPendingTransitions,
275
-} from './ReactFiberTransition.new';
276
-import {
277
- getMarkerInstances,
278
- pushMarkerInstance,
279
- pushRootMarkerInstance,
280
- TransitionTracingMarker,
281
-} from './ReactFiberTracingMarkerComponent.new';
282
-
283
-const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
284
-
285
-// A special exception that's used to unwind the stack when an update flows
286
-// into a dehydrated boundary.
287
-export const SelectiveHydrationException: mixed = new Error(
288
- "This is not a real error. It's an implementation detail of React's " +
289
- "selective hydration feature. If this leaks into userspace, it's a bug in " +
290
- 'React. Please file an issue.',
291
-);
292
-
293
-let didReceiveUpdate: boolean = false;
294
-
295
-let didWarnAboutBadClass;
296
-let didWarnAboutModulePatternComponent;
297
-let didWarnAboutContextTypeOnFunctionComponent;
298
-let didWarnAboutGetDerivedStateOnFunctionComponent;
299
-let didWarnAboutFunctionRefs;
300
-export let didWarnAboutReassigningProps: boolean;
301
-let didWarnAboutRevealOrder;
302
-let didWarnAboutTailOptions;
303
-let didWarnAboutDefaultPropsOnFunctionComponent;
304
-
305
-if (__DEV__) {
306
- didWarnAboutBadClass = {};
307
- didWarnAboutModulePatternComponent = {};
308
- didWarnAboutContextTypeOnFunctionComponent = {};
309
- didWarnAboutGetDerivedStateOnFunctionComponent = {};
310
- didWarnAboutFunctionRefs = {};
311
- didWarnAboutReassigningProps = false;
312
- didWarnAboutRevealOrder = {};
313
- didWarnAboutTailOptions = {};
314
- didWarnAboutDefaultPropsOnFunctionComponent = {};
315
-}
316
-
317
-export function reconcileChildren(
318
- current: Fiber | null,
319
- workInProgress: Fiber,
320
- nextChildren: any,
321
- renderLanes: Lanes,
322
-) {
323
- if (current === null) {
324
- // If this is a fresh new component that hasn't been rendered yet, we
325
- // won't update its child set by applying minimal side-effects. Instead,
326
- // we will add them all to the child before it gets rendered. That means
327
- // we can optimize this reconciliation pass by not tracking side-effects.
328
- workInProgress.child = mountChildFibers(
329
- workInProgress,
330
- null,
331
- nextChildren,
332
- renderLanes,
333
- );
334
- } else {
335
- // If the current child is the same as the work in progress, it means that
336
- // we haven't yet started any work on these children. Therefore, we use
337
- // the clone algorithm to create a copy of all the current children.
338
-
339
- // If we had any progressed work already, that is invalid at this point so
340
- // let's throw it out.
341
- workInProgress.child = reconcileChildFibers(
342
- workInProgress,
343
- current.child,
344
- nextChildren,
345
- renderLanes,
346
- );
347
- }
348
-}
349
-
350
-function forceUnmountCurrentAndReconcile(
351
- current: Fiber,
352
- workInProgress: Fiber,
353
- nextChildren: any,
354
- renderLanes: Lanes,
355
-) {
356
- // This function is fork of reconcileChildren. It's used in cases where we
357
- // want to reconcile without matching against the existing set. This has the
358
- // effect of all current children being unmounted; even if the type and key
359
- // are the same, the old child is unmounted and a new child is created.
360
- //
361
- // To do this, we're going to go through the reconcile algorithm twice. In
362
- // the first pass, we schedule a deletion for all the current children by
363
- // passing null.
364
- workInProgress.child = reconcileChildFibers(
365
- workInProgress,
366
- current.child,
367
- null,
368
- renderLanes,
369
- );
370
- // In the second pass, we mount the new children. The trick here is that we
371
- // pass null in place of where we usually pass the current child set. This has
372
- // the effect of remounting all children regardless of whether their
373
- // identities match.
374
- workInProgress.child = reconcileChildFibers(
375
- workInProgress,
376
- null,
377
- nextChildren,
378
- renderLanes,
379
- );
380
-}
381
-
382
-function updateForwardRef(
383
- current: Fiber | null,
384
- workInProgress: Fiber,
385
- Component: any,
386
- nextProps: any,
387
- renderLanes: Lanes,
388
-) {
389
- // TODO: current can be non-null here even if the component
390
- // hasn't yet mounted. This happens after the first render suspends.
391
- // We'll need to figure out if this is fine or can cause issues.
392
-
393
- if (__DEV__) {
394
- if (workInProgress.type !== workInProgress.elementType) {
395
- // Lazy component props can't be validated in createElement
396
- // because they're only guaranteed to be resolved here.
397
- const innerPropTypes = Component.propTypes;
398
- if (innerPropTypes) {
399
- checkPropTypes(
400
- innerPropTypes,
401
- nextProps, // Resolved props
402
- 'prop',
403
- getComponentNameFromType(Component),
404
- );
405
- }
406
- }
407
- }
408
-
409
- const render = Component.render;
410
- const ref = workInProgress.ref;
411
-
412
- // The rest is a fork of updateFunctionComponent
413
- let nextChildren;
414
- let hasId;
415
- prepareToReadContext(workInProgress, renderLanes);
416
- if (enableSchedulingProfiler) {
417
- markComponentRenderStarted(workInProgress);
418
- }
419
- if (__DEV__) {
420
- ReactCurrentOwner.current = workInProgress;
421
- setIsRendering(true);
422
- nextChildren = renderWithHooks(
423
- current,
424
- workInProgress,
425
- render,
426
- nextProps,
427
- ref,
428
- renderLanes,
429
- );
430
- hasId = checkDidRenderIdHook();
431
- setIsRendering(false);
432
- } else {
433
- nextChildren = renderWithHooks(
434
- current,
435
- workInProgress,
436
- render,
437
- nextProps,
438
- ref,
439
- renderLanes,
440
- );
441
- hasId = checkDidRenderIdHook();
442
- }
443
- if (enableSchedulingProfiler) {
444
- markComponentRenderStopped();
445
- }
446
-
447
- if (current !== null && !didReceiveUpdate) {
448
- bailoutHooks(current, workInProgress, renderLanes);
449
- return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
450
- }
451
-
452
- if (getIsHydrating() && hasId) {
453
- pushMaterializedTreeId(workInProgress);
454
- }
455
-
456
- // React DevTools reads this flag.
457
- workInProgress.flags |= PerformedWork;
458
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
459
- return workInProgress.child;
460
-}
461
-
462
-function updateMemoComponent(
463
- current: Fiber | null,
464
- workInProgress: Fiber,
465
- Component: any,
466
- nextProps: any,
467
- renderLanes: Lanes,
468
-): null | Fiber {
469
- if (current === null) {
470
- const type = Component.type;
471
- if (
472
- isSimpleFunctionComponent(type) &&
473
- Component.compare === null &&
474
- // SimpleMemoComponent codepath doesn't resolve outer props either.
475
- Component.defaultProps === undefined
476
- ) {
477
- let resolvedType = type;
478
- if (__DEV__) {
479
- resolvedType = resolveFunctionForHotReloading(type);
480
- }
481
- // If this is a plain function component without default props,
482
- // and with only the default shallow comparison, we upgrade it
483
- // to a SimpleMemoComponent to allow fast path updates.
484
- workInProgress.tag = SimpleMemoComponent;
485
- workInProgress.type = resolvedType;
486
- if (__DEV__) {
487
- validateFunctionComponentInDev(workInProgress, type);
488
- }
489
- return updateSimpleMemoComponent(
490
- current,
491
- workInProgress,
492
- resolvedType,
493
- nextProps,
494
- renderLanes,
495
- );
496
- }
497
- if (__DEV__) {
498
- const innerPropTypes = type.propTypes;
499
- if (innerPropTypes) {
500
- // Inner memo component props aren't currently validated in createElement.
501
- // We could move it there, but we'd still need this for lazy code path.
502
- checkPropTypes(
503
- innerPropTypes,
504
- nextProps, // Resolved props
505
- 'prop',
506
- getComponentNameFromType(type),
507
- );
508
- }
509
- if (
510
- warnAboutDefaultPropsOnFunctionComponents &&
511
- Component.defaultProps !== undefined
512
- ) {
513
- const componentName = getComponentNameFromType(type) || 'Unknown';
514
- if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
515
- console.error(
516
- '%s: Support for defaultProps will be removed from memo components ' +
517
- 'in a future major release. Use JavaScript default parameters instead.',
518
- componentName,
519
- );
520
- didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
521
- }
522
- }
523
- }
524
- const child = createFiberFromTypeAndProps(
525
- Component.type,
526
- null,
527
- nextProps,
528
- workInProgress,
529
- workInProgress.mode,
530
- renderLanes,
531
- );
532
- child.ref = workInProgress.ref;
533
- child.return = workInProgress;
534
- workInProgress.child = child;
535
- return child;
536
- }
537
- if (__DEV__) {
538
- const type = Component.type;
539
- const innerPropTypes = type.propTypes;
540
- if (innerPropTypes) {
541
- // Inner memo component props aren't currently validated in createElement.
542
- // We could move it there, but we'd still need this for lazy code path.
543
- checkPropTypes(
544
- innerPropTypes,
545
- nextProps, // Resolved props
546
- 'prop',
547
- getComponentNameFromType(type),
548
- );
549
- }
550
- }
551
- const currentChild = ((current.child: any): Fiber); // This is always exactly one child
552
- const hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(
553
- current,
554
- renderLanes,
555
- );
556
- if (!hasScheduledUpdateOrContext) {
557
- // This will be the props with resolved defaultProps,
558
- // unlike current.memoizedProps which will be the unresolved ones.
559
- const prevProps = currentChild.memoizedProps;
560
- // Default to shallow comparison
561
- let compare = Component.compare;
562
- compare = compare !== null ? compare : shallowEqual;
563
- if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
564
- return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
565
- }
566
- }
567
- // React DevTools reads this flag.
568
- workInProgress.flags |= PerformedWork;
569
- const newChild = createWorkInProgress(currentChild, nextProps);
570
- newChild.ref = workInProgress.ref;
571
- newChild.return = workInProgress;
572
- workInProgress.child = newChild;
573
- return newChild;
574
-}
575
-
576
-function updateSimpleMemoComponent(
577
- current: Fiber | null,
578
- workInProgress: Fiber,
579
- Component: any,
580
- nextProps: any,
581
- renderLanes: Lanes,
582
-): null | Fiber {
583
- // TODO: current can be non-null here even if the component
584
- // hasn't yet mounted. This happens when the inner render suspends.
585
- // We'll need to figure out if this is fine or can cause issues.
586
-
587
- if (__DEV__) {
588
- if (workInProgress.type !== workInProgress.elementType) {
589
- // Lazy component props can't be validated in createElement
590
- // because they're only guaranteed to be resolved here.
591
- let outerMemoType = workInProgress.elementType;
592
- if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
593
- // We warn when you define propTypes on lazy()
594
- // so let's just skip over it to find memo() outer wrapper.
595
- // Inner props for memo are validated later.
596
- const lazyComponent: LazyComponentType<any, any> = outerMemoType;
597
- const payload = lazyComponent._payload;
598
- const init = lazyComponent._init;
599
- try {
600
- outerMemoType = init(payload);
601
- } catch (x) {
602
- // $FlowFixMe[incompatible-type] found when upgrading Flow
603
- outerMemoType = null;
604
- }
605
- // Inner propTypes will be validated in the function component path.
606
- const outerPropTypes = outerMemoType && (outerMemoType: any).propTypes;
607
- if (outerPropTypes) {
608
- checkPropTypes(
609
- outerPropTypes,
610
- nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
611
- 'prop',
612
- getComponentNameFromType(outerMemoType),
613
- );
614
- }
615
- }
616
- }
617
- }
618
- if (current !== null) {
619
- const prevProps = current.memoizedProps;
620
- if (
621
- shallowEqual(prevProps, nextProps) &&
622
- current.ref === workInProgress.ref &&
623
- // Prevent bailout if the implementation changed due to hot reload.
624
- (__DEV__ ? workInProgress.type === current.type : true)
625
- ) {
626
- didReceiveUpdate = false;
627
-
628
- // The props are shallowly equal. Reuse the previous props object, like we
629
- // would during a normal fiber bailout.
630
- //
631
- // We don't have strong guarantees that the props object is referentially
632
- // equal during updates where we can't bail out anyway — like if the props
633
- // are shallowly equal, but there's a local state or context update in the
634
- // same batch.
635
- //
636
- // However, as a principle, we should aim to make the behavior consistent
637
- // across different ways of memoizing a component. For example, React.memo
638
- // has a different internal Fiber layout if you pass a normal function
639
- // component (SimpleMemoComponent) versus if you pass a different type
640
- // like forwardRef (MemoComponent). But this is an implementation detail.
641
- // Wrapping a component in forwardRef (or React.lazy, etc) shouldn't
642
- // affect whether the props object is reused during a bailout.
643
- workInProgress.pendingProps = nextProps = prevProps;
644
-
645
- if (!checkScheduledUpdateOrContext(current, renderLanes)) {
646
- // The pending lanes were cleared at the beginning of beginWork. We're
647
- // about to bail out, but there might be other lanes that weren't
648
- // included in the current render. Usually, the priority level of the
649
- // remaining updates is accumulated during the evaluation of the
650
- // component (i.e. when processing the update queue). But since since
651
- // we're bailing out early *without* evaluating the component, we need
652
- // to account for it here, too. Reset to the value of the current fiber.
653
- // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
654
- // because a MemoComponent fiber does not have hooks or an update queue;
655
- // rather, it wraps around an inner component, which may or may not
656
- // contains hooks.
657
- // TODO: Move the reset at in beginWork out of the common path so that
658
- // this is no longer necessary.
659
- workInProgress.lanes = current.lanes;
660
- return bailoutOnAlreadyFinishedWork(
661
- current,
662
- workInProgress,
663
- renderLanes,
664
- );
665
- } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
666
- // This is a special case that only exists for legacy mode.
667
- // See https://github.com/facebook/react/pull/19216.
668
- didReceiveUpdate = true;
669
- }
670
- }
671
- }
672
- return updateFunctionComponent(
673
- current,
674
- workInProgress,
675
- Component,
676
- nextProps,
677
- renderLanes,
678
- );
679
-}
680
-
681
-function updateOffscreenComponent(
682
- current: Fiber | null,
683
- workInProgress: Fiber,
684
- renderLanes: Lanes,
685
-) {
686
- const nextProps: OffscreenProps = workInProgress.pendingProps;
687
- const nextChildren = nextProps.children;
688
-
689
- const prevState: OffscreenState | null =
690
- current !== null ? current.memoizedState : null;
691
-
692
- markRef(current, workInProgress);
693
-
694
- if (
695
- nextProps.mode === 'hidden' ||
696
- (enableLegacyHidden &&
697
- nextProps.mode === 'unstable-defer-without-hiding') ||
698
- // TODO: remove read from stateNode.
699
- workInProgress.stateNode._visibility & OffscreenDetached
700
- ) {
701
- // Rendering a hidden tree.
702
-
703
- const didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;
704
- if (didSuspend) {
705
- // Something suspended inside a hidden tree
706
-
707
- // Include the base lanes from the last render
708
- const nextBaseLanes =
709
- prevState !== null
710
- ? mergeLanes(prevState.baseLanes, renderLanes)
711
- : renderLanes;
712
-
713
- if (current !== null) {
714
- // Reset to the current children
715
- let currentChild = (workInProgress.child = current.child);
716
-
717
- // The current render suspended, but there may be other lanes with
718
- // pending work. We can't read `childLanes` from the current Offscreen
719
- // fiber because we reset it when it was deferred; however, we can read
720
- // the pending lanes from the child fibers.
721
- let currentChildLanes = NoLanes;
722
- while (currentChild !== null) {
723
- currentChildLanes = mergeLanes(
724
- mergeLanes(currentChildLanes, currentChild.lanes),
725
- currentChild.childLanes,
726
- );
727
- currentChild = currentChild.sibling;
728
- }
729
- const lanesWeJustAttempted = nextBaseLanes;
730
- const remainingChildLanes = removeLanes(
731
- currentChildLanes,
732
- lanesWeJustAttempted,
733
- );
734
- workInProgress.childLanes = remainingChildLanes;
735
- } else {
736
- workInProgress.childLanes = NoLanes;
737
- workInProgress.child = null;
738
- }
739
-
740
- return deferHiddenOffscreenComponent(
741
- current,
742
- workInProgress,
743
- nextBaseLanes,
744
- renderLanes,
745
- );
746
- }
747
-
748
- if ((workInProgress.mode & ConcurrentMode) === NoMode) {
749
- // In legacy sync mode, don't defer the subtree. Render it now.
750
- // TODO: Consider how Offscreen should work with transitions in the future
751
- const nextState: OffscreenState = {
752
- baseLanes: NoLanes,
753
- cachePool: null,
754
- };
755
- workInProgress.memoizedState = nextState;
756
- if (enableCache) {
757
- // push the cache pool even though we're going to bail out
758
- // because otherwise there'd be a context mismatch
759
- if (current !== null) {
760
- pushTransition(workInProgress, null, null);
761
- }
762
- }
763
- reuseHiddenContextOnStack(workInProgress);
764
- pushOffscreenSuspenseHandler(workInProgress);
765
- } else if (!includesSomeLane(renderLanes, (OffscreenLane: Lane))) {
766
- // We're hidden, and we're not rendering at Offscreen. We will bail out
767
- // and resume this tree later.
768
-
769
- // Schedule this fiber to re-render at Offscreen priority
770
- workInProgress.lanes = workInProgress.childLanes = laneToLanes(
771
- OffscreenLane,
772
- );
773
-
774
- // Include the base lanes from the last render
775
- const nextBaseLanes =
776
- prevState !== null
777
- ? mergeLanes(prevState.baseLanes, renderLanes)
778
- : renderLanes;
779
-
780
- return deferHiddenOffscreenComponent(
781
- current,
782
- workInProgress,
783
- nextBaseLanes,
784
- renderLanes,
785
- );
786
- } else {
787
- // This is the second render. The surrounding visible content has already
788
- // committed. Now we resume rendering the hidden tree.
789
-
790
- // Rendering at offscreen, so we can clear the base lanes.
791
- const nextState: OffscreenState = {
792
- baseLanes: NoLanes,
793
- cachePool: null,
794
- };
795
- workInProgress.memoizedState = nextState;
796
- if (enableCache && current !== null) {
797
- // If the render that spawned this one accessed the cache pool, resume
798
- // using the same cache. Unless the parent changed, since that means
799
- // there was a refresh.
800
- const prevCachePool = prevState !== null ? prevState.cachePool : null;
801
- // TODO: Consider if and how Offscreen pre-rendering should
802
- // be attributed to the transition that spawned it
803
- pushTransition(workInProgress, prevCachePool, null);
804
- }
805
-
806
- // Push the lanes that were skipped when we bailed out.
807
- if (prevState !== null) {
808
- pushHiddenContext(workInProgress, prevState);
809
- } else {
810
- reuseHiddenContextOnStack(workInProgress);
811
- }
812
- pushOffscreenSuspenseHandler(workInProgress);
813
- }
814
- } else {
815
- // Rendering a visible tree.
816
- if (prevState !== null) {
817
- // We're going from hidden -> visible.
818
- let prevCachePool = null;
819
- if (enableCache) {
820
- // If the render that spawned this one accessed the cache pool, resume
821
- // using the same cache. Unless the parent changed, since that means
822
- // there was a refresh.
823
- prevCachePool = prevState.cachePool;
824
- }
825
-
826
- let transitions = null;
827
- if (enableTransitionTracing) {
828
- // We have now gone from hidden to visible, so any transitions should
829
- // be added to the stack to get added to any Offscreen/suspense children
830
- const instance: OffscreenInstance | null = workInProgress.stateNode;
831
- if (instance !== null && instance._transitions != null) {
832
- transitions = Array.from(instance._transitions);
833
- }
834
- }
835
-
836
- pushTransition(workInProgress, prevCachePool, transitions);
837
-
838
- // Push the lanes that were skipped when we bailed out.
839
- pushHiddenContext(workInProgress, prevState);
840
- reuseSuspenseHandlerOnStack(workInProgress);
841
-
842
- // Since we're not hidden anymore, reset the state
843
- workInProgress.memoizedState = null;
844
- } else {
845
- // We weren't previously hidden, and we still aren't, so there's nothing
846
- // special to do. Need to push to the stack regardless, though, to avoid
847
- // a push/pop misalignment.
848
-
849
- if (enableCache) {
850
- // If the render that spawned this one accessed the cache pool, resume
851
- // using the same cache. Unless the parent changed, since that means
852
- // there was a refresh.
853
- if (current !== null) {
854
- pushTransition(workInProgress, null, null);
855
- }
856
- }
857
-
858
- // We're about to bail out, but we need to push this to the stack anyway
859
- // to avoid a push/pop misalignment.
860
- reuseHiddenContextOnStack(workInProgress);
861
- reuseSuspenseHandlerOnStack(workInProgress);
862
- }
863
- }
864
-
865
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
866
- return workInProgress.child;
867
-}
868
-
869
-function deferHiddenOffscreenComponent(
870
- current: Fiber | null,
871
- workInProgress: Fiber,
872
- nextBaseLanes: Lanes,
873
- renderLanes: Lanes,
874
-) {
875
- const nextState: OffscreenState = {
876
- baseLanes: nextBaseLanes,
877
- // Save the cache pool so we can resume later.
878
- cachePool: enableCache ? getOffscreenDeferredCache() : null,
879
- };
880
- workInProgress.memoizedState = nextState;
881
- if (enableCache) {
882
- // push the cache pool even though we're going to bail out
883
- // because otherwise there'd be a context mismatch
884
- if (current !== null) {
885
- pushTransition(workInProgress, null, null);
886
- }
887
- }
888
-
889
- // We're about to bail out, but we need to push this to the stack anyway
890
- // to avoid a push/pop misalignment.
891
- reuseHiddenContextOnStack(workInProgress);
892
-
893
- pushOffscreenSuspenseHandler(workInProgress);
894
-
895
- if (enableLazyContextPropagation && current !== null) {
896
- // Since this tree will resume rendering in a separate render, we need
897
- // to propagate parent contexts now so we don't lose track of which
898
- // ones changed.
899
- propagateParentContextChangesToDeferredTree(
900
- current,
901
- workInProgress,
902
- renderLanes,
903
- );
904
- }
905
-
906
- return null;
907
-}
908
-
909
-// Note: These happen to have identical begin phases, for now. We shouldn't hold
910
-// ourselves to this constraint, though. If the behavior diverges, we should
911
-// fork the function.
912
-const updateLegacyHiddenComponent = updateOffscreenComponent;
913
-
914
-function updateCacheComponent(
915
- current: Fiber | null,
916
- workInProgress: Fiber,
917
- renderLanes: Lanes,
918
-) {
919
- if (!enableCache) {
920
- return null;
921
- }
922
-
923
- prepareToReadContext(workInProgress, renderLanes);
924
- const parentCache = readContext(CacheContext);
925
-
926
- if (current === null) {
927
- // Initial mount. Request a fresh cache from the pool.
928
- const freshCache = requestCacheFromPool(renderLanes);
929
- const initialState: CacheComponentState = {
930
- parent: parentCache,
931
- cache: freshCache,
932
- };
933
- workInProgress.memoizedState = initialState;
934
- initializeUpdateQueue(workInProgress);
935
- pushCacheProvider(workInProgress, freshCache);
936
- } else {
937
- // Check for updates
938
- if (includesSomeLane(current.lanes, renderLanes)) {
939
- cloneUpdateQueue(current, workInProgress);
940
- processUpdateQueue(workInProgress, null, null, renderLanes);
941
- }
942
- const prevState: CacheComponentState = current.memoizedState;
943
- const nextState: CacheComponentState = workInProgress.memoizedState;
944
-
945
- // Compare the new parent cache to the previous to see detect there was
946
- // a refresh.
947
- if (prevState.parent !== parentCache) {
948
- // Refresh in parent. Update the parent.
949
- const derivedState: CacheComponentState = {
950
- parent: parentCache,
951
- cache: parentCache,
952
- };
953
-
954
- // Copied from getDerivedStateFromProps implementation. Once the update
955
- // queue is empty, persist the derived state onto the base state.
956
- workInProgress.memoizedState = derivedState;
957
- if (workInProgress.lanes === NoLanes) {
958
- const updateQueue: UpdateQueue<any> = (workInProgress.updateQueue: any);
959
- workInProgress.memoizedState = updateQueue.baseState = derivedState;
960
- }
961
-
962
- pushCacheProvider(workInProgress, parentCache);
963
- // No need to propagate a context change because the refreshed parent
964
- // already did.
965
- } else {
966
- // The parent didn't refresh. Now check if this cache did.
967
- const nextCache = nextState.cache;
968
- pushCacheProvider(workInProgress, nextCache);
969
- if (nextCache !== prevState.cache) {
970
- // This cache refreshed. Propagate a context change.
971
- propagateContextChange(workInProgress, CacheContext, renderLanes);
972
- }
973
- }
974
- }
975
-
976
- const nextChildren = workInProgress.pendingProps.children;
977
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
978
- return workInProgress.child;
979
-}
980
-
981
-// This should only be called if the name changes
982
-function updateTracingMarkerComponent(
983
- current: Fiber | null,
984
- workInProgress: Fiber,
985
- renderLanes: Lanes,
986
-) {
987
- if (!enableTransitionTracing) {
988
- return null;
989
- }
990
-
991
- // TODO: (luna) Only update the tracing marker if it's newly rendered or it's name changed.
992
- // A tracing marker is only associated with the transitions that rendered
993
- // or updated it, so we can create a new set of transitions each time
994
- if (current === null) {
995
- const currentTransitions = getPendingTransitions();
996
- if (currentTransitions !== null) {
997
- const markerInstance: TracingMarkerInstance = {
998
- tag: TransitionTracingMarker,
999
- transitions: new Set(currentTransitions),
1000
- pendingBoundaries: null,
1001
- name: workInProgress.pendingProps.name,
1002
- aborts: null,
1003
- };
1004
- workInProgress.stateNode = markerInstance;
1005
-
1006
- // We call the marker complete callback when all child suspense boundaries resolve.
1007
- // We do this in the commit phase on Offscreen. If the marker has no child suspense
1008
- // boundaries, we need to schedule a passive effect to make sure we call the marker
1009
- // complete callback.
1010
- workInProgress.flags |= Passive;
1011
- }
1012
- } else {
1013
- if (__DEV__) {
1014
- if (current.memoizedProps.name !== workInProgress.pendingProps.name) {
1015
- console.error(
1016
- 'Changing the name of a tracing marker after mount is not supported. ' +
1017
- 'To remount the tracing marker, pass it a new key.',
1018
- );
1019
- }
1020
- }
1021
- }
1022
-
1023
- const instance: TracingMarkerInstance | null = workInProgress.stateNode;
1024
- if (instance !== null) {
1025
- pushMarkerInstance(workInProgress, instance);
1026
- }
1027
- const nextChildren = workInProgress.pendingProps.children;
1028
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1029
- return workInProgress.child;
1030
-}
1031
-
1032
-function updateFragment(
1033
- current: Fiber | null,
1034
- workInProgress: Fiber,
1035
- renderLanes: Lanes,
1036
-) {
1037
- const nextChildren = workInProgress.pendingProps;
1038
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1039
- return workInProgress.child;
1040
-}
1041
-
1042
-function updateMode(
1043
- current: Fiber | null,
1044
- workInProgress: Fiber,
1045
- renderLanes: Lanes,
1046
-) {
1047
- const nextChildren = workInProgress.pendingProps.children;
1048
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1049
- return workInProgress.child;
1050
-}
1051
-
1052
-function updateProfiler(
1053
- current: Fiber | null,
1054
- workInProgress: Fiber,
1055
- renderLanes: Lanes,
1056
-) {
1057
- if (enableProfilerTimer) {
1058
- workInProgress.flags |= Update;
1059
-
1060
- if (enableProfilerCommitHooks) {
1061
- // Reset effect durations for the next eventual effect phase.
1062
- // These are reset during render to allow the DevTools commit hook a chance to read them,
1063
- const stateNode = workInProgress.stateNode;
1064
- stateNode.effectDuration = 0;
1065
- stateNode.passiveEffectDuration = 0;
1066
- }
1067
- }
1068
- const nextProps = workInProgress.pendingProps;
1069
- const nextChildren = nextProps.children;
1070
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1071
- return workInProgress.child;
1072
-}
1073
-
1074
-function markRef(current: Fiber | null, workInProgress: Fiber) {
1075
- const ref = workInProgress.ref;
1076
- if (
1077
- (current === null && ref !== null) ||
1078
- (current !== null && current.ref !== ref)
1079
- ) {
1080
- // Schedule a Ref effect
1081
- workInProgress.flags |= Ref;
1082
- workInProgress.flags |= RefStatic;
1083
- }
1084
-}
1085
-
1086
-function updateFunctionComponent(
1087
- current,
1088
- workInProgress,
1089
- Component,
1090
- nextProps: any,
1091
- renderLanes,
1092
-) {
1093
- if (__DEV__) {
1094
- if (workInProgress.type !== workInProgress.elementType) {
1095
- // Lazy component props can't be validated in createElement
1096
- // because they're only guaranteed to be resolved here.
1097
- const innerPropTypes = Component.propTypes;
1098
- if (innerPropTypes) {
1099
- checkPropTypes(
1100
- innerPropTypes,
1101
- nextProps, // Resolved props
1102
- 'prop',
1103
- getComponentNameFromType(Component),
1104
- );
1105
- }
1106
- }
1107
- }
1108
-
1109
- let context;
1110
- if (!disableLegacyContext) {
1111
- const unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
1112
- context = getMaskedContext(workInProgress, unmaskedContext);
1113
- }
1114
-
1115
- let nextChildren;
1116
- let hasId;
1117
- prepareToReadContext(workInProgress, renderLanes);
1118
- if (enableSchedulingProfiler) {
1119
- markComponentRenderStarted(workInProgress);
1120
- }
1121
- if (__DEV__) {
1122
- ReactCurrentOwner.current = workInProgress;
1123
- setIsRendering(true);
1124
- nextChildren = renderWithHooks(
1125
- current,
1126
- workInProgress,
1127
- Component,
1128
- nextProps,
1129
- context,
1130
- renderLanes,
1131
- );
1132
- hasId = checkDidRenderIdHook();
1133
- setIsRendering(false);
1134
- } else {
1135
- nextChildren = renderWithHooks(
1136
- current,
1137
- workInProgress,
1138
- Component,
1139
- nextProps,
1140
- context,
1141
- renderLanes,
1142
- );
1143
- hasId = checkDidRenderIdHook();
1144
- }
1145
- if (enableSchedulingProfiler) {
1146
- markComponentRenderStopped();
1147
- }
1148
-
1149
- if (current !== null && !didReceiveUpdate) {
1150
- bailoutHooks(current, workInProgress, renderLanes);
1151
- return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
1152
- }
1153
-
1154
- if (getIsHydrating() && hasId) {
1155
- pushMaterializedTreeId(workInProgress);
1156
- }
1157
-
1158
- // React DevTools reads this flag.
1159
- workInProgress.flags |= PerformedWork;
1160
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1161
- return workInProgress.child;
1162
-}
1163
-
1164
-export function replayFunctionComponent(
1165
- current: Fiber | null,
1166
- workInProgress: Fiber,
1167
- nextProps: any,
1168
- Component: any,
1169
- renderLanes: Lanes,
1170
-): Fiber | null {
1171
- // This function is used to replay a component that previously suspended,
1172
- // after its data resolves. It's a simplified version of
1173
- // updateFunctionComponent that reuses the hooks from the previous attempt.
1174
-
1175
- let context;
1176
- if (!disableLegacyContext) {
1177
- const unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
1178
- context = getMaskedContext(workInProgress, unmaskedContext);
1179
- }
1180
-
1181
- prepareToReadContext(workInProgress, renderLanes);
1182
- if (enableSchedulingProfiler) {
1183
- markComponentRenderStarted(workInProgress);
1184
- }
1185
- const nextChildren = replaySuspendedComponentWithHooks(
1186
- current,
1187
- workInProgress,
1188
- Component,
1189
- nextProps,
1190
- context,
1191
- );
1192
- const hasId = checkDidRenderIdHook();
1193
- if (enableSchedulingProfiler) {
1194
- markComponentRenderStopped();
1195
- }
1196
-
1197
- if (current !== null && !didReceiveUpdate) {
1198
- bailoutHooks(current, workInProgress, renderLanes);
1199
- return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
1200
- }
1201
-
1202
- if (getIsHydrating() && hasId) {
1203
- pushMaterializedTreeId(workInProgress);
1204
- }
1205
-
1206
- // React DevTools reads this flag.
1207
- workInProgress.flags |= PerformedWork;
1208
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1209
- return workInProgress.child;
1210
-}
1211
-
1212
-function updateClassComponent(
1213
- current: Fiber | null,
1214
- workInProgress: Fiber,
1215
- Component: any,
1216
- nextProps: any,
1217
- renderLanes: Lanes,
1218
-) {
1219
- if (__DEV__) {
1220
- // This is used by DevTools to force a boundary to error.
1221
- switch (shouldError(workInProgress)) {
1222
- case false: {
1223
- const instance = workInProgress.stateNode;
1224
- const ctor = workInProgress.type;
1225
- // TODO This way of resetting the error boundary state is a hack.
1226
- // Is there a better way to do this?
1227
- const tempInstance = new ctor(
1228
- workInProgress.memoizedProps,
1229
- instance.context,
1230
- );
1231
- const state = tempInstance.state;
1232
- instance.updater.enqueueSetState(instance, state, null);
1233
- break;
1234
- }
1235
- case true: {
1236
- workInProgress.flags |= DidCapture;
1237
- workInProgress.flags |= ShouldCapture;
1238
- // eslint-disable-next-line react-internal/prod-error-codes
1239
- const error = new Error('Simulated error coming from DevTools');
1240
- const lane = pickArbitraryLane(renderLanes);
1241
- workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
1242
- // Schedule the error boundary to re-render using updated state
1243
- const update = createClassErrorUpdate(
1244
- workInProgress,
1245
- createCapturedValueAtFiber(error, workInProgress),
1246
- lane,
1247
- );
1248
- enqueueCapturedUpdate(workInProgress, update);
1249
- break;
1250
- }
1251
- }
1252
-
1253
- if (workInProgress.type !== workInProgress.elementType) {
1254
- // Lazy component props can't be validated in createElement
1255
- // because they're only guaranteed to be resolved here.
1256
- const innerPropTypes = Component.propTypes;
1257
- if (innerPropTypes) {
1258
- checkPropTypes(
1259
- innerPropTypes,
1260
- nextProps, // Resolved props
1261
- 'prop',
1262
- getComponentNameFromType(Component),
1263
- );
1264
- }
1265
- }
1266
- }
1267
-
1268
- // Push context providers early to prevent context stack mismatches.
1269
- // During mounting we don't know the child context yet as the instance doesn't exist.
1270
- // We will invalidate the child context in finishClassComponent() right after rendering.
1271
- let hasContext;
1272
- if (isLegacyContextProvider(Component)) {
1273
- hasContext = true;
1274
- pushLegacyContextProvider(workInProgress);
1275
- } else {
1276
- hasContext = false;
1277
- }
1278
- prepareToReadContext(workInProgress, renderLanes);
1279
-
1280
- const instance = workInProgress.stateNode;
1281
- let shouldUpdate;
1282
- if (instance === null) {
1283
- resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress);
1284
-
1285
- // In the initial pass we might need to construct the instance.
1286
- constructClassInstance(workInProgress, Component, nextProps);
1287
- mountClassInstance(workInProgress, Component, nextProps, renderLanes);
1288
- shouldUpdate = true;
1289
- } else if (current === null) {
1290
- // In a resume, we'll already have an instance we can reuse.
1291
- shouldUpdate = resumeMountClassInstance(
1292
- workInProgress,
1293
- Component,
1294
- nextProps,
1295
- renderLanes,
1296
- );
1297
- } else {
1298
- shouldUpdate = updateClassInstance(
1299
- current,
1300
- workInProgress,
1301
- Component,
1302
- nextProps,
1303
- renderLanes,
1304
- );
1305
- }
1306
- const nextUnitOfWork = finishClassComponent(
1307
- current,
1308
- workInProgress,
1309
- Component,
1310
- shouldUpdate,
1311
- hasContext,
1312
- renderLanes,
1313
- );
1314
- if (__DEV__) {
1315
- const inst = workInProgress.stateNode;
1316
- if (shouldUpdate && inst.props !== nextProps) {
1317
- if (!didWarnAboutReassigningProps) {
1318
- console.error(
1319
- 'It looks like %s is reassigning its own `this.props` while rendering. ' +
1320
- 'This is not supported and can lead to confusing bugs.',
1321
- getComponentNameFromFiber(workInProgress) || 'a component',
1322
- );
1323
- }
1324
- didWarnAboutReassigningProps = true;
1325
- }
1326
- }
1327
- return nextUnitOfWork;
1328
-}
1329
-
1330
-function finishClassComponent(
1331
- current: Fiber | null,
1332
- workInProgress: Fiber,
1333
- Component: any,
1334
- shouldUpdate: boolean,
1335
- hasContext: boolean,
1336
- renderLanes: Lanes,
1337
-) {
1338
- // Refs should update even if shouldComponentUpdate returns false
1339
- markRef(current, workInProgress);
1340
-
1341
- const didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags;
1342
-
1343
- if (!shouldUpdate && !didCaptureError) {
1344
- // Context providers should defer to sCU for rendering
1345
- if (hasContext) {
1346
- invalidateContextProvider(workInProgress, Component, false);
1347
- }
1348
-
1349
- return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
1350
- }
1351
-
1352
- const instance = workInProgress.stateNode;
1353
-
1354
- // Rerender
1355
- ReactCurrentOwner.current = workInProgress;
1356
- let nextChildren;
1357
- if (
1358
- didCaptureError &&
1359
- typeof Component.getDerivedStateFromError !== 'function'
1360
- ) {
1361
- // If we captured an error, but getDerivedStateFromError is not defined,
1362
- // unmount all the children. componentDidCatch will schedule an update to
1363
- // re-render a fallback. This is temporary until we migrate everyone to
1364
- // the new API.
1365
- // TODO: Warn in a future release.
1366
- nextChildren = null;
1367
-
1368
- if (enableProfilerTimer) {
1369
- stopProfilerTimerIfRunning(workInProgress);
1370
- }
1371
- } else {
1372
- if (enableSchedulingProfiler) {
1373
- markComponentRenderStarted(workInProgress);
1374
- }
1375
- if (__DEV__) {
1376
- setIsRendering(true);
1377
- nextChildren = instance.render();
1378
- if (
1379
- debugRenderPhaseSideEffectsForStrictMode &&
1380
- workInProgress.mode & StrictLegacyMode
1381
- ) {
1382
- setIsStrictModeForDevtools(true);
1383
- try {
1384
- instance.render();
1385
- } finally {
1386
- setIsStrictModeForDevtools(false);
1387
- }
1388
- }
1389
- setIsRendering(false);
1390
- } else {
1391
- nextChildren = instance.render();
1392
- }
1393
- if (enableSchedulingProfiler) {
1394
- markComponentRenderStopped();
1395
- }
1396
- }
1397
-
1398
- // React DevTools reads this flag.
1399
- workInProgress.flags |= PerformedWork;
1400
- if (current !== null && didCaptureError) {
1401
- // If we're recovering from an error, reconcile without reusing any of
1402
- // the existing children. Conceptually, the normal children and the children
1403
- // that are shown on error are two different sets, so we shouldn't reuse
1404
- // normal children even if their identities match.
1405
- forceUnmountCurrentAndReconcile(
1406
- current,
1407
- workInProgress,
1408
- nextChildren,
1409
- renderLanes,
1410
- );
1411
- } else {
1412
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1413
- }
1414
-
1415
- // Memoize state using the values we just used to render.
1416
- // TODO: Restructure so we never read values from the instance.
1417
- workInProgress.memoizedState = instance.state;
1418
-
1419
- // The context might have changed so we need to recalculate it.
1420
- if (hasContext) {
1421
- invalidateContextProvider(workInProgress, Component, true);
1422
- }
1423
-
1424
- return workInProgress.child;
1425
-}
1426
-
1427
-function pushHostRootContext(workInProgress) {
1428
- const root = (workInProgress.stateNode: FiberRoot);
1429
- if (root.pendingContext) {
1430
- pushTopLevelContextObject(
1431
- workInProgress,
1432
- root.pendingContext,
1433
- root.pendingContext !== root.context,
1434
- );
1435
- } else if (root.context) {
1436
- // Should always be set
1437
- pushTopLevelContextObject(workInProgress, root.context, false);
1438
- }
1439
- pushHostContainer(workInProgress, root.containerInfo);
1440
-}
1441
-
1442
-function updateHostRoot(current, workInProgress, renderLanes) {
1443
- pushHostRootContext(workInProgress);
1444
-
1445
- if (current === null) {
1446
- throw new Error('Should have a current fiber. This is a bug in React.');
1447
- }
1448
-
1449
- const nextProps = workInProgress.pendingProps;
1450
- const prevState = workInProgress.memoizedState;
1451
- const prevChildren = prevState.element;
1452
- cloneUpdateQueue(current, workInProgress);
1453
- processUpdateQueue(workInProgress, nextProps, null, renderLanes);
1454
-
1455
- const nextState: RootState = workInProgress.memoizedState;
1456
- const root: FiberRoot = workInProgress.stateNode;
1457
- pushRootTransition(workInProgress, root, renderLanes);
1458
-
1459
- if (enableTransitionTracing) {
1460
- pushRootMarkerInstance(workInProgress);
1461
- }
1462
-
1463
- if (enableCache) {
1464
- const nextCache: Cache = nextState.cache;
1465
- pushCacheProvider(workInProgress, nextCache);
1466
- if (nextCache !== prevState.cache) {
1467
- // The root cache refreshed.
1468
- propagateContextChange(workInProgress, CacheContext, renderLanes);
1469
- }
1470
- }
1471
-
1472
- // Caution: React DevTools currently depends on this property
1473
- // being called "element".
1474
- const nextChildren = nextState.element;
1475
- if (supportsHydration && prevState.isDehydrated) {
1476
- // This is a hydration root whose shell has not yet hydrated. We should
1477
- // attempt to hydrate.
1478
-
1479
- // Flip isDehydrated to false to indicate that when this render
1480
- // finishes, the root will no longer be dehydrated.
1481
- const overrideState: RootState = {
1482
- element: nextChildren,
1483
- isDehydrated: false,
1484
- cache: nextState.cache,
1485
- };
1486
- const updateQueue: UpdateQueue<RootState> = (workInProgress.updateQueue: any);
1487
- // `baseState` can always be the last state because the root doesn't
1488
- // have reducer functions so it doesn't need rebasing.
1489
- updateQueue.baseState = overrideState;
1490
- workInProgress.memoizedState = overrideState;
1491
-
1492
- if (workInProgress.flags & ForceClientRender) {
1493
- // Something errored during a previous attempt to hydrate the shell, so we
1494
- // forced a client render.
1495
- const recoverableError = createCapturedValueAtFiber(
1496
- new Error(
1497
- 'There was an error while hydrating. Because the error happened outside ' +
1498
- 'of a Suspense boundary, the entire root will switch to ' +
1499
- 'client rendering.',
1500
- ),
1501
- workInProgress,
1502
- );
1503
- return mountHostRootWithoutHydrating(
1504
- current,
1505
- workInProgress,
1506
- nextChildren,
1507
- renderLanes,
1508
- recoverableError,
1509
- );
1510
- } else if (nextChildren !== prevChildren) {
1511
- const recoverableError = createCapturedValueAtFiber(
1512
- new Error(
1513
- 'This root received an early update, before anything was able ' +
1514
- 'hydrate. Switched the entire root to client rendering.',
1515
- ),
1516
- workInProgress,
1517
- );
1518
- return mountHostRootWithoutHydrating(
1519
- current,
1520
- workInProgress,
1521
- nextChildren,
1522
- renderLanes,
1523
- recoverableError,
1524
- );
1525
- } else {
1526
- // The outermost shell has not hydrated yet. Start hydrating.
1527
- enterHydrationState(workInProgress);
1528
- if (enableUseMutableSource) {
1529
- const mutableSourceEagerHydrationData =
1530
- root.mutableSourceEagerHydrationData;
1531
- if (mutableSourceEagerHydrationData != null) {
1532
- for (let i = 0; i < mutableSourceEagerHydrationData.length; i += 2) {
1533
- const mutableSource = ((mutableSourceEagerHydrationData[
1534
- i
1535
- ]: any): MutableSource<any>);
1536
- const version = mutableSourceEagerHydrationData[i + 1];
1537
- setWorkInProgressVersion(mutableSource, version);
1538
- }
1539
- }
1540
- }
1541
-
1542
- const child = mountChildFibers(
1543
- workInProgress,
1544
- null,
1545
- nextChildren,
1546
- renderLanes,
1547
- );
1548
- workInProgress.child = child;
1549
-
1550
- let node = child;
1551
- while (node) {
1552
- // Mark each child as hydrating. This is a fast path to know whether this
1553
- // tree is part of a hydrating tree. This is used to determine if a child
1554
- // node has fully mounted yet, and for scheduling event replaying.
1555
- // Conceptually this is similar to Placement in that a new subtree is
1556
- // inserted into the React tree here. It just happens to not need DOM
1557
- // mutations because it already exists.
1558
- node.flags = (node.flags & ~Placement) | Hydrating;
1559
- node = node.sibling;
1560
- }
1561
- }
1562
- } else {
1563
- // Root is not dehydrated. Either this is a client-only root, or it
1564
- // already hydrated.
1565
- resetHydrationState();
1566
- if (nextChildren === prevChildren) {
1567
- return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
1568
- }
1569
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1570
- }
1571
- return workInProgress.child;
1572
-}
1573
-
1574
-function mountHostRootWithoutHydrating(
1575
- current: Fiber,
1576
- workInProgress: Fiber,
1577
- nextChildren: ReactNodeList,
1578
- renderLanes: Lanes,
1579
- recoverableError: CapturedValue<mixed>,
1580
-) {
1581
- // Revert to client rendering.
1582
- resetHydrationState();
1583
-
1584
- queueHydrationError(recoverableError);
1585
-
1586
- workInProgress.flags |= ForceClientRender;
1587
-
1588
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1589
- return workInProgress.child;
1590
-}
1591
-
1592
-function updateHostComponent(
1593
- current: Fiber | null,
1594
- workInProgress: Fiber,
1595
- renderLanes: Lanes,
1596
-) {
1597
- pushHostContext(workInProgress);
1598
-
1599
- if (current === null) {
1600
- tryToClaimNextHydratableInstance(workInProgress);
1601
- }
1602
-
1603
- const type = workInProgress.type;
1604
- const nextProps = workInProgress.pendingProps;
1605
- const prevProps = current !== null ? current.memoizedProps : null;
1606
-
1607
- let nextChildren = nextProps.children;
1608
- const isDirectTextChild = shouldSetTextContent(type, nextProps);
1609
-
1610
- if (isDirectTextChild) {
1611
- // We special case a direct text child of a host node. This is a common
1612
- // case. We won't handle it as a reified child. We will instead handle
1613
- // this in the host environment that also has access to this prop. That
1614
- // avoids allocating another HostText fiber and traversing it.
1615
- nextChildren = null;
1616
- } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
1617
- // If we're switching from a direct text child to a normal child, or to
1618
- // empty, we need to schedule the text content to be reset.
1619
- workInProgress.flags |= ContentReset;
1620
- }
1621
-
1622
- markRef(current, workInProgress);
1623
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1624
- return workInProgress.child;
1625
-}
1626
-
1627
-function updateHostResource(current, workInProgress, renderLanes) {
1628
- pushHostContext(workInProgress);
1629
- markRef(current, workInProgress);
1630
- const currentProps = current === null ? null : current.memoizedProps;
1631
- workInProgress.memoizedState = getResource(
1632
- workInProgress.type,
1633
- workInProgress.pendingProps,
1634
- currentProps,
1635
- );
1636
- // Resources never have reconciler managed children. It is possible for
1637
- // the host implementation of getResource to consider children in the
1638
- // resource construction but they will otherwise be discarded. In practice
1639
- // this precludes all but the simplest children and Host specific warnings
1640
- // should be implemented to warn when children are passsed when otherwise not
1641
- // expected
1642
- return null;
1643
-}
1644
-
1645
-function updateHostSingleton(
1646
- current: Fiber | null,
1647
- workInProgress: Fiber,
1648
- renderLanes: Lanes,
1649
-) {
1650
- pushHostContext(workInProgress);
1651
-
1652
- if (current === null) {
1653
- claimHydratableSingleton(workInProgress);
1654
- }
1655
-
1656
- const nextChildren = workInProgress.pendingProps.children;
1657
-
1658
- if (current === null && !getIsHydrating()) {
1659
- // Similar to Portals we append Singleton children in the commit phase. So we
1660
- // Track insertions even on mount.
1661
- // TODO: Consider unifying this with how the root works.
1662
- workInProgress.child = reconcileChildFibers(
1663
- workInProgress,
1664
- null,
1665
- nextChildren,
1666
- renderLanes,
1667
- );
1668
- } else {
1669
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
1670
- }
1671
- markRef(current, workInProgress);
1672
- return workInProgress.child;
1673
-}
1674
-
1675
-function updateHostText(current, workInProgress) {
1676
- if (current === null) {
1677
- tryToClaimNextHydratableInstance(workInProgress);
1678
- }
1679
- // Nothing to do here. This is terminal. We'll do the completion step
1680
- // immediately after.
1681
- return null;
1682
-}
1683
-
1684
-function mountLazyComponent(
1685
- _current,
1686
- workInProgress,
1687
- elementType,
1688
- renderLanes,
1689
-) {
1690
- resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
1691
-
1692
- const props = workInProgress.pendingProps;
1693
- const lazyComponent: LazyComponentType<any, any> = elementType;
1694
- const payload = lazyComponent._payload;
1695
- const init = lazyComponent._init;
1696
- let Component = init(payload);
1697
- // Store the unwrapped component in the type.
1698
- workInProgress.type = Component;
1699
- const resolvedTag = (workInProgress.tag = resolveLazyComponentTag(Component));
1700
- const resolvedProps = resolveDefaultProps(Component, props);
1701
- let child;
1702
- switch (resolvedTag) {
1703
- case FunctionComponent: {
1704
- if (__DEV__) {
1705
- validateFunctionComponentInDev(workInProgress, Component);
1706
- workInProgress.type = Component = resolveFunctionForHotReloading(
1707
- Component,
1708
- );
1709
- }
1710
- child = updateFunctionComponent(
1711
- null,
1712
- workInProgress,
1713
- Component,
1714
- resolvedProps,
1715
- renderLanes,
1716
- );
1717
- return child;
1718
- }
1719
- case ClassComponent: {
1720
- if (__DEV__) {
1721
- workInProgress.type = Component = resolveClassForHotReloading(
1722
- Component,
1723
- );
1724
- }
1725
- child = updateClassComponent(
1726
- null,
1727
- workInProgress,
1728
- Component,
1729
- resolvedProps,
1730
- renderLanes,
1731
- );
1732
- return child;
1733
- }
1734
- case ForwardRef: {
1735
- if (__DEV__) {
1736
- workInProgress.type = Component = resolveForwardRefForHotReloading(
1737
- Component,
1738
- );
1739
- }
1740
- child = updateForwardRef(
1741
- null,
1742
- workInProgress,
1743
- Component,
1744
- resolvedProps,
1745
- renderLanes,
1746
- );
1747
- return child;
1748
- }
1749
- case MemoComponent: {
1750
- if (__DEV__) {
1751
- if (workInProgress.type !== workInProgress.elementType) {
1752
- const outerPropTypes = Component.propTypes;
1753
- if (outerPropTypes) {
1754
- checkPropTypes(
1755
- outerPropTypes,
1756
- resolvedProps, // Resolved for outer only
1757
- 'prop',
1758
- getComponentNameFromType(Component),
1759
- );
1760
- }
1761
- }
1762
- }
1763
- child = updateMemoComponent(
1764
- null,
1765
- workInProgress,
1766
- Component,
1767
- resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
1768
- renderLanes,
1769
- );
1770
- return child;
1771
- }
1772
- }
1773
- let hint = '';
1774
- if (__DEV__) {
1775
- if (
1776
- Component !== null &&
1777
- typeof Component === 'object' &&
1778
- Component.$$typeof === REACT_LAZY_TYPE
1779
- ) {
1780
- hint = ' Did you wrap a component in React.lazy() more than once?';
1781
- }
1782
- }
1783
-
1784
- // This message intentionally doesn't mention ForwardRef or MemoComponent
1785
- // because the fact that it's a separate type of work is an
1786
- // implementation detail.
1787
- throw new Error(
1788
- `Element type is invalid. Received a promise that resolves to: ${Component}. ` +
1789
- `Lazy element type must resolve to a class or function.${hint}`,
1790
- );
1791
-}
1792
-
1793
-function mountIncompleteClassComponent(
1794
- _current,
1795
- workInProgress,
1796
- Component,
1797
- nextProps,
1798
- renderLanes,
1799
-) {
1800
- resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
1801
-
1802
- // Promote the fiber to a class and try rendering again.
1803
- workInProgress.tag = ClassComponent;
1804
-
1805
- // The rest of this function is a fork of `updateClassComponent`
1806
-
1807
- // Push context providers early to prevent context stack mismatches.
1808
- // During mounting we don't know the child context yet as the instance doesn't exist.
1809
- // We will invalidate the child context in finishClassComponent() right after rendering.
1810
- let hasContext;
1811
- if (isLegacyContextProvider(Component)) {
1812
- hasContext = true;
1813
- pushLegacyContextProvider(workInProgress);
1814
- } else {
1815
- hasContext = false;
1816
- }
1817
- prepareToReadContext(workInProgress, renderLanes);
1818
-
1819
- constructClassInstance(workInProgress, Component, nextProps);
1820
- mountClassInstance(workInProgress, Component, nextProps, renderLanes);
1821
-
1822
- return finishClassComponent(
1823
- null,
1824
- workInProgress,
1825
- Component,
1826
- true,
1827
- hasContext,
1828
- renderLanes,
1829
- );
1830
-}
1831
-
1832
-function mountIndeterminateComponent(
1833
- _current,
1834
- workInProgress,
1835
- Component,
1836
- renderLanes,
1837
-) {
1838
- resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
1839
-
1840
- const props = workInProgress.pendingProps;
1841
- let context;
1842
- if (!disableLegacyContext) {
1843
- const unmaskedContext = getUnmaskedContext(
1844
- workInProgress,
1845
- Component,
1846
- false,
1847
- );
1848
- context = getMaskedContext(workInProgress, unmaskedContext);
1849
- }
1850
-
1851
- prepareToReadContext(workInProgress, renderLanes);
1852
- let value;
1853
- let hasId;
1854
-
1855
- if (enableSchedulingProfiler) {
1856
- markComponentRenderStarted(workInProgress);
1857
- }
1858
- if (__DEV__) {
1859
- if (
1860
- Component.prototype &&
1861
- typeof Component.prototype.render === 'function'
1862
- ) {
1863
- const componentName = getComponentNameFromType(Component) || 'Unknown';
1864
-
1865
- if (!didWarnAboutBadClass[componentName]) {
1866
- console.error(
1867
- "The <%s /> component appears to have a render method, but doesn't extend React.Component. " +
1868
- 'This is likely to cause errors. Change %s to extend React.Component instead.',
1869
- componentName,
1870
- componentName,
1871
- );
1872
- didWarnAboutBadClass[componentName] = true;
1873
- }
1874
- }
1875
-
1876
- if (workInProgress.mode & StrictLegacyMode) {
1877
- ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
1878
- }
1879
-
1880
- setIsRendering(true);
1881
- ReactCurrentOwner.current = workInProgress;
1882
- value = renderWithHooks(
1883
- null,
1884
- workInProgress,
1885
- Component,
1886
- props,
1887
- context,
1888
- renderLanes,
1889
- );
1890
- hasId = checkDidRenderIdHook();
1891
- setIsRendering(false);
1892
- } else {
1893
- value = renderWithHooks(
1894
- null,
1895
- workInProgress,
1896
- Component,
1897
- props,
1898
- context,
1899
- renderLanes,
1900
- );
1901
- hasId = checkDidRenderIdHook();
1902
- }
1903
- if (enableSchedulingProfiler) {
1904
- markComponentRenderStopped();
1905
- }
1906
-
1907
- // React DevTools reads this flag.
1908
- workInProgress.flags |= PerformedWork;
1909
-
1910
- if (__DEV__) {
1911
- // Support for module components is deprecated and is removed behind a flag.
1912
- // Whether or not it would crash later, we want to show a good message in DEV first.
1913
- if (
1914
- typeof value === 'object' &&
1915
- value !== null &&
1916
- typeof value.render === 'function' &&
1917
- value.$$typeof === undefined
1918
- ) {
1919
- const componentName = getComponentNameFromType(Component) || 'Unknown';
1920
- if (!didWarnAboutModulePatternComponent[componentName]) {
1921
- console.error(
1922
- 'The <%s /> component appears to be a function component that returns a class instance. ' +
1923
- 'Change %s to a class that extends React.Component instead. ' +
1924
- "If you can't use a class try assigning the prototype on the function as a workaround. " +
1925
- "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " +
1926
- 'cannot be called with `new` by React.',
1927
- componentName,
1928
- componentName,
1929
- componentName,
1930
- );
1931
- didWarnAboutModulePatternComponent[componentName] = true;
1932
- }
1933
- }
1934
- }
1935
-
1936
- if (
1937
- // Run these checks in production only if the flag is off.
1938
- // Eventually we'll delete this branch altogether.
1939
- !disableModulePatternComponents &&
1940
- typeof value === 'object' &&
1941
- value !== null &&
1942
- typeof value.render === 'function' &&
1943
- value.$$typeof === undefined
1944
- ) {
1945
- if (__DEV__) {
1946
- const componentName = getComponentNameFromType(Component) || 'Unknown';
1947
- if (!didWarnAboutModulePatternComponent[componentName]) {
1948
- console.error(
1949
- 'The <%s /> component appears to be a function component that returns a class instance. ' +
1950
- 'Change %s to a class that extends React.Component instead. ' +
1951
- "If you can't use a class try assigning the prototype on the function as a workaround. " +
1952
- "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " +
1953
- 'cannot be called with `new` by React.',
1954
- componentName,
1955
- componentName,
1956
- componentName,
1957
- );
1958
- didWarnAboutModulePatternComponent[componentName] = true;
1959
- }
1960
- }
1961
-
1962
- // Proceed under the assumption that this is a class instance
1963
- workInProgress.tag = ClassComponent;
1964
-
1965
- // Throw out any hooks that were used.
1966
- workInProgress.memoizedState = null;
1967
- workInProgress.updateQueue = null;
1968
-
1969
- // Push context providers early to prevent context stack mismatches.
1970
- // During mounting we don't know the child context yet as the instance doesn't exist.
1971
- // We will invalidate the child context in finishClassComponent() right after rendering.
1972
- let hasContext = false;
1973
- if (isLegacyContextProvider(Component)) {
1974
- hasContext = true;
1975
- pushLegacyContextProvider(workInProgress);
1976
- } else {
1977
- hasContext = false;
1978
- }
1979
-
1980
- workInProgress.memoizedState =
1981
- value.state !== null && value.state !== undefined ? value.state : null;
1982
-
1983
- initializeUpdateQueue(workInProgress);
1984
-
1985
- adoptClassInstance(workInProgress, value);
1986
- mountClassInstance(workInProgress, Component, props, renderLanes);
1987
- return finishClassComponent(
1988
- null,
1989
- workInProgress,
1990
- Component,
1991
- true,
1992
- hasContext,
1993
- renderLanes,
1994
- );
1995
- } else {
1996
- // Proceed under the assumption that this is a function component
1997
- workInProgress.tag = FunctionComponent;
1998
- if (__DEV__) {
1999
- if (disableLegacyContext && Component.contextTypes) {
2000
- console.error(
2001
- '%s uses the legacy contextTypes API which is no longer supported. ' +
2002
- 'Use React.createContext() with React.useContext() instead.',
2003
- getComponentNameFromType(Component) || 'Unknown',
2004
- );
2005
- }
2006
- }
2007
-
2008
- if (getIsHydrating() && hasId) {
2009
- pushMaterializedTreeId(workInProgress);
2010
- }
2011
-
2012
- reconcileChildren(null, workInProgress, value, renderLanes);
2013
- if (__DEV__) {
2014
- validateFunctionComponentInDev(workInProgress, Component);
2015
- }
2016
- return workInProgress.child;
2017
- }
2018
-}
2019
-
2020
-function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) {
2021
- if (__DEV__) {
2022
- if (Component) {
2023
- if (Component.childContextTypes) {
2024
- console.error(
2025
- '%s(...): childContextTypes cannot be defined on a function component.',
2026
- Component.displayName || Component.name || 'Component',
2027
- );
2028
- }
2029
- }
2030
- if (workInProgress.ref !== null) {
2031
- let info = '';
2032
- const ownerName = getCurrentFiberOwnerNameInDevOrNull();
2033
- if (ownerName) {
2034
- info += '\n\nCheck the render method of `' + ownerName + '`.';
2035
- }
2036
-
2037
- let warningKey = ownerName || '';
2038
- const debugSource = workInProgress._debugSource;
2039
- if (debugSource) {
2040
- warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
2041
- }
2042
- if (!didWarnAboutFunctionRefs[warningKey]) {
2043
- didWarnAboutFunctionRefs[warningKey] = true;
2044
- console.error(
2045
- 'Function components cannot be given refs. ' +
2046
- 'Attempts to access this ref will fail. ' +
2047
- 'Did you mean to use React.forwardRef()?%s',
2048
- info,
2049
- );
2050
- }
2051
- }
2052
-
2053
- if (
2054
- warnAboutDefaultPropsOnFunctionComponents &&
2055
- Component.defaultProps !== undefined
2056
- ) {
2057
- const componentName = getComponentNameFromType(Component) || 'Unknown';
2058
-
2059
- if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
2060
- console.error(
2061
- '%s: Support for defaultProps will be removed from function components ' +
2062
- 'in a future major release. Use JavaScript default parameters instead.',
2063
- componentName,
2064
- );
2065
- didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
2066
- }
2067
- }
2068
-
2069
- if (typeof Component.getDerivedStateFromProps === 'function') {
2070
- const componentName = getComponentNameFromType(Component) || 'Unknown';
2071
-
2072
- if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
2073
- console.error(
2074
- '%s: Function components do not support getDerivedStateFromProps.',
2075
- componentName,
2076
- );
2077
- didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
2078
- }
2079
- }
2080
-
2081
- if (
2082
- typeof Component.contextType === 'object' &&
2083
- Component.contextType !== null
2084
- ) {
2085
- const componentName = getComponentNameFromType(Component) || 'Unknown';
2086
-
2087
- if (!didWarnAboutContextTypeOnFunctionComponent[componentName]) {
2088
- console.error(
2089
- '%s: Function components do not support contextType.',
2090
- componentName,
2091
- );
2092
- didWarnAboutContextTypeOnFunctionComponent[componentName] = true;
2093
- }
2094
- }
2095
- }
2096
-}
2097
-
2098
-const SUSPENDED_MARKER: SuspenseState = {
2099
- dehydrated: null,
2100
- treeContext: null,
2101
- retryLane: NoLane,
2102
-};
2103
-
2104
-function mountSuspenseOffscreenState(renderLanes: Lanes): OffscreenState {
2105
- return {
2106
- baseLanes: renderLanes,
2107
- cachePool: getSuspendedCache(),
2108
- };
2109
-}
2110
-
2111
-function updateSuspenseOffscreenState(
2112
- prevOffscreenState: OffscreenState,
2113
- renderLanes: Lanes,
2114
-): OffscreenState {
2115
- let cachePool: SpawnedCachePool | null = null;
2116
- if (enableCache) {
2117
- const prevCachePool: SpawnedCachePool | null = prevOffscreenState.cachePool;
2118
- if (prevCachePool !== null) {
2119
- const parentCache = isPrimaryRenderer
2120
- ? CacheContext._currentValue
2121
- : CacheContext._currentValue2;
2122
- if (prevCachePool.parent !== parentCache) {
2123
- // Detected a refresh in the parent. This overrides any previously
2124
- // suspended cache.
2125
- cachePool = {
2126
- parent: parentCache,
2127
- pool: parentCache,
2128
- };
2129
- } else {
2130
- // We can reuse the cache from last time. The only thing that would have
2131
- // overridden it is a parent refresh, which we checked for above.
2132
- cachePool = prevCachePool;
2133
- }
2134
- } else {
2135
- // If there's no previous cache pool, grab the current one.
2136
- cachePool = getSuspendedCache();
2137
- }
2138
- }
2139
- return {
2140
- baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes),
2141
- cachePool,
2142
- };
2143
-}
2144
-
2145
-// TODO: Probably should inline this back
2146
-function shouldRemainOnFallback(
2147
- current: null | Fiber,
2148
- workInProgress: Fiber,
2149
- renderLanes: Lanes,
2150
-) {
2151
- // If we're already showing a fallback, there are cases where we need to
2152
- // remain on that fallback regardless of whether the content has resolved.
2153
- // For example, SuspenseList coordinates when nested content appears.
2154
- if (current !== null) {
2155
- const suspenseState: SuspenseState = current.memoizedState;
2156
- if (suspenseState === null) {
2157
- // Currently showing content. Don't hide it, even if ForceSuspenseFallback
2158
- // is true. More precise name might be "ForceRemainSuspenseFallback".
2159
- // Note: This is a factoring smell. Can't remain on a fallback if there's
2160
- // no fallback to remain on.
2161
- return false;
2162
- }
2163
- }
2164
-
2165
- // Not currently showing content. Consult the Suspense context.
2166
- const suspenseContext: SuspenseContext = suspenseStackCursor.current;
2167
- return hasSuspenseListContext(
2168
- suspenseContext,
2169
- (ForceSuspenseFallback: SuspenseContext),
2170
- );
2171
-}
2172
-
2173
-function getRemainingWorkInPrimaryTree(current: Fiber, renderLanes) {
2174
- // TODO: Should not remove render lanes that were pinged during this render
2175
- return removeLanes(current.childLanes, renderLanes);
2176
-}
2177
-
2178
-function updateSuspenseComponent(current, workInProgress, renderLanes) {
2179
- const nextProps = workInProgress.pendingProps;
2180
-
2181
- // This is used by DevTools to force a boundary to suspend.
2182
- if (__DEV__) {
2183
- if (shouldSuspend(workInProgress)) {
2184
- workInProgress.flags |= DidCapture;
2185
- }
2186
- }
2187
-
2188
- let showFallback = false;
2189
- const didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;
2190
- if (
2191
- didSuspend ||
2192
- shouldRemainOnFallback(current, workInProgress, renderLanes)
2193
- ) {
2194
- // Something in this boundary's subtree already suspended. Switch to
2195
- // rendering the fallback children.
2196
- showFallback = true;
2197
- workInProgress.flags &= ~DidCapture;
2198
- }
2199
-
2200
- // OK, the next part is confusing. We're about to reconcile the Suspense
2201
- // boundary's children. This involves some custom reconciliation logic. Two
2202
- // main reasons this is so complicated.
2203
- //
2204
- // First, Legacy Mode has different semantics for backwards compatibility. The
2205
- // primary tree will commit in an inconsistent state, so when we do the
2206
- // second pass to render the fallback, we do some exceedingly, uh, clever
2207
- // hacks to make that not totally break. Like transferring effects and
2208
- // deletions from hidden tree. In Concurrent Mode, it's much simpler,
2209
- // because we bailout on the primary tree completely and leave it in its old
2210
- // state, no effects. Same as what we do for Offscreen (except that
2211
- // Offscreen doesn't have the first render pass).
2212
- //
2213
- // Second is hydration. During hydration, the Suspense fiber has a slightly
2214
- // different layout, where the child points to a dehydrated fragment, which
2215
- // contains the DOM rendered by the server.
2216
- //
2217
- // Third, even if you set all that aside, Suspense is like error boundaries in
2218
- // that we first we try to render one tree, and if that fails, we render again
2219
- // and switch to a different tree. Like a try/catch block. So we have to track
2220
- // which branch we're currently rendering. Ideally we would model this using
2221
- // a stack.
2222
- if (current === null) {
2223
- // Initial mount
2224
-
2225
- // Special path for hydration
2226
- // If we're currently hydrating, try to hydrate this boundary.
2227
- if (getIsHydrating()) {
2228
- // We must push the suspense handler context *before* attempting to
2229
- // hydrate, to avoid a mismatch in case it errors.
2230
- if (showFallback) {
2231
- pushPrimaryTreeSuspenseHandler(workInProgress);
2232
- } else {
2233
- pushFallbackTreeSuspenseHandler(workInProgress);
2234
- }
2235
- tryToClaimNextHydratableInstance(workInProgress);
2236
- // This could've been a dehydrated suspense component.
2237
- const suspenseState: null | SuspenseState = workInProgress.memoizedState;
2238
- if (suspenseState !== null) {
2239
- const dehydrated = suspenseState.dehydrated;
2240
- if (dehydrated !== null) {
2241
- return mountDehydratedSuspenseComponent(
2242
- workInProgress,
2243
- dehydrated,
2244
- renderLanes,
2245
- );
2246
- }
2247
- }
2248
- // If hydration didn't succeed, fall through to the normal Suspense path.
2249
- // To avoid a stack mismatch we need to pop the Suspense handler that we
2250
- // pushed above. This will become less awkward when move the hydration
2251
- // logic to its own fiber.
2252
- popSuspenseHandler(workInProgress);
2253
- }
2254
-
2255
- const nextPrimaryChildren = nextProps.children;
2256
- const nextFallbackChildren = nextProps.fallback;
2257
-
2258
- if (showFallback) {
2259
- pushFallbackTreeSuspenseHandler(workInProgress);
2260
-
2261
- const fallbackFragment = mountSuspenseFallbackChildren(
2262
- workInProgress,
2263
- nextPrimaryChildren,
2264
- nextFallbackChildren,
2265
- renderLanes,
2266
- );
2267
- const primaryChildFragment: Fiber = (workInProgress.child: any);
2268
- primaryChildFragment.memoizedState = mountSuspenseOffscreenState(
2269
- renderLanes,
2270
- );
2271
- workInProgress.memoizedState = SUSPENDED_MARKER;
2272
- if (enableTransitionTracing) {
2273
- const currentTransitions = getPendingTransitions();
2274
- if (currentTransitions !== null) {
2275
- const parentMarkerInstances = getMarkerInstances();
2276
- const offscreenQueue: OffscreenQueue | null = (primaryChildFragment.updateQueue: any);
2277
- if (offscreenQueue === null) {
2278
- const newOffscreenQueue: OffscreenQueue = {
2279
- transitions: currentTransitions,
2280
- markerInstances: parentMarkerInstances,
2281
- wakeables: null,
2282
- };
2283
- primaryChildFragment.updateQueue = newOffscreenQueue;
2284
- } else {
2285
- offscreenQueue.transitions = currentTransitions;
2286
- offscreenQueue.markerInstances = parentMarkerInstances;
2287
- }
2288
- }
2289
- }
2290
-
2291
- return fallbackFragment;
2292
- } else if (
2293
- enableCPUSuspense &&
2294
- typeof nextProps.unstable_expectedLoadTime === 'number'
2295
- ) {
2296
- // This is a CPU-bound tree. Skip this tree and show a placeholder to
2297
- // unblock the surrounding content. Then immediately retry after the
2298
- // initial commit.
2299
- pushFallbackTreeSuspenseHandler(workInProgress);
2300
- const fallbackFragment = mountSuspenseFallbackChildren(
2301
- workInProgress,
2302
- nextPrimaryChildren,
2303
- nextFallbackChildren,
2304
- renderLanes,
2305
- );
2306
- const primaryChildFragment: Fiber = (workInProgress.child: any);
2307
- primaryChildFragment.memoizedState = mountSuspenseOffscreenState(
2308
- renderLanes,
2309
- );
2310
- workInProgress.memoizedState = SUSPENDED_MARKER;
2311
-
2312
- // TODO: Transition Tracing is not yet implemented for CPU Suspense.
2313
-
2314
- // Since nothing actually suspended, there will nothing to ping this to
2315
- // get it started back up to attempt the next item. While in terms of
2316
- // priority this work has the same priority as this current render, it's
2317
- // not part of the same transition once the transition has committed. If
2318
- // it's sync, we still want to yield so that it can be painted.
2319
- // Conceptually, this is really the same as pinging. We can use any
2320
- // RetryLane even if it's the one currently rendering since we're leaving
2321
- // it behind on this node.
2322
- workInProgress.lanes = SomeRetryLane;
2323
- return fallbackFragment;
2324
- } else {
2325
- pushPrimaryTreeSuspenseHandler(workInProgress);
2326
- return mountSuspensePrimaryChildren(
2327
- workInProgress,
2328
- nextPrimaryChildren,
2329
- renderLanes,
2330
- );
2331
- }
2332
- } else {
2333
- // This is an update.
2334
-
2335
- // Special path for hydration
2336
- const prevState: null | SuspenseState = current.memoizedState;
2337
- if (prevState !== null) {
2338
- const dehydrated = prevState.dehydrated;
2339
- if (dehydrated !== null) {
2340
- return updateDehydratedSuspenseComponent(
2341
- current,
2342
- workInProgress,
2343
- didSuspend,
2344
- nextProps,
2345
- dehydrated,
2346
- prevState,
2347
- renderLanes,
2348
- );
2349
- }
2350
- }
2351
-
2352
- if (showFallback) {
2353
- pushFallbackTreeSuspenseHandler(workInProgress);
2354
-
2355
- const nextFallbackChildren = nextProps.fallback;
2356
- const nextPrimaryChildren = nextProps.children;
2357
- const fallbackChildFragment = updateSuspenseFallbackChildren(
2358
- current,
2359
- workInProgress,
2360
- nextPrimaryChildren,
2361
- nextFallbackChildren,
2362
- renderLanes,
2363
- );
2364
- const primaryChildFragment: Fiber = (workInProgress.child: any);
2365
- const prevOffscreenState: OffscreenState | null = (current.child: any)
2366
- .memoizedState;
2367
- primaryChildFragment.memoizedState =
2368
- prevOffscreenState === null
2369
- ? mountSuspenseOffscreenState(renderLanes)
2370
- : updateSuspenseOffscreenState(prevOffscreenState, renderLanes);
2371
- if (enableTransitionTracing) {
2372
- const currentTransitions = getPendingTransitions();
2373
- if (currentTransitions !== null) {
2374
- const parentMarkerInstances = getMarkerInstances();
2375
- const offscreenQueue: OffscreenQueue | null = (primaryChildFragment.updateQueue: any);
2376
- const currentOffscreenQueue: OffscreenQueue | null = (current.updateQueue: any);
2377
- if (offscreenQueue === null) {
2378
- const newOffscreenQueue: OffscreenQueue = {
2379
- transitions: currentTransitions,
2380
- markerInstances: parentMarkerInstances,
2381
- wakeables: null,
2382
- };
2383
- primaryChildFragment.updateQueue = newOffscreenQueue;
2384
- } else if (offscreenQueue === currentOffscreenQueue) {
2385
- // If the work-in-progress queue is the same object as current, we
2386
- // can't modify it without cloning it first.
2387
- const newOffscreenQueue: OffscreenQueue = {
2388
- transitions: currentTransitions,
2389
- markerInstances: parentMarkerInstances,
2390
- wakeables:
2391
- currentOffscreenQueue !== null
2392
- ? currentOffscreenQueue.wakeables
2393
- : null,
2394
- };
2395
- primaryChildFragment.updateQueue = newOffscreenQueue;
2396
- } else {
2397
- offscreenQueue.transitions = currentTransitions;
2398
- offscreenQueue.markerInstances = parentMarkerInstances;
2399
- }
2400
- }
2401
- }
2402
- primaryChildFragment.childLanes = getRemainingWorkInPrimaryTree(
2403
- current,
2404
- renderLanes,
2405
- );
2406
- workInProgress.memoizedState = SUSPENDED_MARKER;
2407
- return fallbackChildFragment;
2408
- } else {
2409
- pushPrimaryTreeSuspenseHandler(workInProgress);
2410
-
2411
- const nextPrimaryChildren = nextProps.children;
2412
- const primaryChildFragment = updateSuspensePrimaryChildren(
2413
- current,
2414
- workInProgress,
2415
- nextPrimaryChildren,
2416
- renderLanes,
2417
- );
2418
- workInProgress.memoizedState = null;
2419
- return primaryChildFragment;
2420
- }
2421
- }
2422
-}
2423
-
2424
-function mountSuspensePrimaryChildren(
2425
- workInProgress,
2426
- primaryChildren,
2427
- renderLanes,
2428
-) {
2429
- const mode = workInProgress.mode;
2430
- const primaryChildProps: OffscreenProps = {
2431
- mode: 'visible',
2432
- children: primaryChildren,
2433
- };
2434
- const primaryChildFragment = mountWorkInProgressOffscreenFiber(
2435
- primaryChildProps,
2436
- mode,
2437
- renderLanes,
2438
- );
2439
- primaryChildFragment.return = workInProgress;
2440
- workInProgress.child = primaryChildFragment;
2441
- return primaryChildFragment;
2442
-}
2443
-
2444
-function mountSuspenseFallbackChildren(
2445
- workInProgress,
2446
- primaryChildren,
2447
- fallbackChildren,
2448
- renderLanes,
2449
-) {
2450
- const mode = workInProgress.mode;
2451
- const progressedPrimaryFragment: Fiber | null = workInProgress.child;
2452
-
2453
- const primaryChildProps: OffscreenProps = {
2454
- mode: 'hidden',
2455
- children: primaryChildren,
2456
- };
2457
-
2458
- let primaryChildFragment;
2459
- let fallbackChildFragment;
2460
- if (
2461
- (mode & ConcurrentMode) === NoMode &&
2462
- progressedPrimaryFragment !== null
2463
- ) {
2464
- // In legacy mode, we commit the primary tree as if it successfully
2465
- // completed, even though it's in an inconsistent state.
2466
- primaryChildFragment = progressedPrimaryFragment;
2467
- primaryChildFragment.childLanes = NoLanes;
2468
- primaryChildFragment.pendingProps = primaryChildProps;
2469
-
2470
- if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
2471
- // Reset the durations from the first pass so they aren't included in the
2472
- // final amounts. This seems counterintuitive, since we're intentionally
2473
- // not measuring part of the render phase, but this makes it match what we
2474
- // do in Concurrent Mode.
2475
- primaryChildFragment.actualDuration = 0;
2476
- primaryChildFragment.actualStartTime = -1;
2477
- primaryChildFragment.selfBaseDuration = 0;
2478
- primaryChildFragment.treeBaseDuration = 0;
2479
- }
2480
-
2481
- fallbackChildFragment = createFiberFromFragment(
2482
- fallbackChildren,
2483
- mode,
2484
- renderLanes,
2485
- null,
2486
- );
2487
- } else {
2488
- primaryChildFragment = mountWorkInProgressOffscreenFiber(
2489
- primaryChildProps,
2490
- mode,
2491
- NoLanes,
2492
- );
2493
- fallbackChildFragment = createFiberFromFragment(
2494
- fallbackChildren,
2495
- mode,
2496
- renderLanes,
2497
- null,
2498
- );
2499
- }
2500
-
2501
- primaryChildFragment.return = workInProgress;
2502
- fallbackChildFragment.return = workInProgress;
2503
- primaryChildFragment.sibling = fallbackChildFragment;
2504
- workInProgress.child = primaryChildFragment;
2505
- return fallbackChildFragment;
2506
-}
2507
-
2508
-function mountWorkInProgressOffscreenFiber(
2509
- offscreenProps: OffscreenProps,
2510
- mode: TypeOfMode,
2511
- renderLanes: Lanes,
2512
-) {
2513
- // The props argument to `createFiberFromOffscreen` is `any` typed, so we use
2514
- // this wrapper function to constrain it.
2515
- return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);
2516
-}
2517
-
2518
-function updateWorkInProgressOffscreenFiber(
2519
- current: Fiber,
2520
- offscreenProps: OffscreenProps,
2521
-) {
2522
- // The props argument to `createWorkInProgress` is `any` typed, so we use this
2523
- // wrapper function to constrain it.
2524
- return createWorkInProgress(current, offscreenProps);
2525
-}
2526
-
2527
-function updateSuspensePrimaryChildren(
2528
- current,
2529
- workInProgress,
2530
- primaryChildren,
2531
- renderLanes,
2532
-) {
2533
- const currentPrimaryChildFragment: Fiber = (current.child: any);
2534
- const currentFallbackChildFragment: Fiber | null =
2535
- currentPrimaryChildFragment.sibling;
2536
-
2537
- const primaryChildFragment = updateWorkInProgressOffscreenFiber(
2538
- currentPrimaryChildFragment,
2539
- {
2540
- mode: 'visible',
2541
- children: primaryChildren,
2542
- },
2543
- );
2544
- if ((workInProgress.mode & ConcurrentMode) === NoMode) {
2545
- primaryChildFragment.lanes = renderLanes;
2546
- }
2547
- primaryChildFragment.return = workInProgress;
2548
- primaryChildFragment.sibling = null;
2549
- if (currentFallbackChildFragment !== null) {
2550
- // Delete the fallback child fragment
2551
- const deletions = workInProgress.deletions;
2552
- if (deletions === null) {
2553
- workInProgress.deletions = [currentFallbackChildFragment];
2554
- workInProgress.flags |= ChildDeletion;
2555
- } else {
2556
- deletions.push(currentFallbackChildFragment);
2557
- }
2558
- }
2559
-
2560
- workInProgress.child = primaryChildFragment;
2561
- return primaryChildFragment;
2562
-}
2563
-
2564
-function updateSuspenseFallbackChildren(
2565
- current,
2566
- workInProgress,
2567
- primaryChildren,
2568
- fallbackChildren,
2569
- renderLanes,
2570
-) {
2571
- const mode = workInProgress.mode;
2572
- const currentPrimaryChildFragment: Fiber = (current.child: any);
2573
- const currentFallbackChildFragment: Fiber | null =
2574
- currentPrimaryChildFragment.sibling;
2575
-
2576
- const primaryChildProps: OffscreenProps = {
2577
- mode: 'hidden',
2578
- children: primaryChildren,
2579
- };
2580
-
2581
- let primaryChildFragment;
2582
- if (
2583
- // In legacy mode, we commit the primary tree as if it successfully
2584
- // completed, even though it's in an inconsistent state.
2585
- (mode & ConcurrentMode) === NoMode &&
2586
- // Make sure we're on the second pass, i.e. the primary child fragment was
2587
- // already cloned. In legacy mode, the only case where this isn't true is
2588
- // when DevTools forces us to display a fallback; we skip the first render
2589
- // pass entirely and go straight to rendering the fallback. (In Concurrent
2590
- // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
2591
- // only codepath.)
2592
- workInProgress.child !== currentPrimaryChildFragment
2593
- ) {
2594
- const progressedPrimaryFragment: Fiber = (workInProgress.child: any);
2595
- primaryChildFragment = progressedPrimaryFragment;
2596
- primaryChildFragment.childLanes = NoLanes;
2597
- primaryChildFragment.pendingProps = primaryChildProps;
2598
-
2599
- if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
2600
- // Reset the durations from the first pass so they aren't included in the
2601
- // final amounts. This seems counterintuitive, since we're intentionally
2602
- // not measuring part of the render phase, but this makes it match what we
2603
- // do in Concurrent Mode.
2604
- primaryChildFragment.actualDuration = 0;
2605
- primaryChildFragment.actualStartTime = -1;
2606
- primaryChildFragment.selfBaseDuration =
2607
- currentPrimaryChildFragment.selfBaseDuration;
2608
- primaryChildFragment.treeBaseDuration =
2609
- currentPrimaryChildFragment.treeBaseDuration;
2610
- }
2611
-
2612
- // The fallback fiber was added as a deletion during the first pass.
2613
- // However, since we're going to remain on the fallback, we no longer want
2614
- // to delete it.
2615
- workInProgress.deletions = null;
2616
- } else {
2617
- primaryChildFragment = updateWorkInProgressOffscreenFiber(
2618
- currentPrimaryChildFragment,
2619
- primaryChildProps,
2620
- );
2621
- // Since we're reusing a current tree, we need to reuse the flags, too.
2622
- // (We don't do this in legacy mode, because in legacy mode we don't re-use
2623
- // the current tree; see previous branch.)
2624
- primaryChildFragment.subtreeFlags =
2625
- currentPrimaryChildFragment.subtreeFlags & StaticMask;
2626
- }
2627
- let fallbackChildFragment;
2628
- if (currentFallbackChildFragment !== null) {
2629
- fallbackChildFragment = createWorkInProgress(
2630
- currentFallbackChildFragment,
2631
- fallbackChildren,
2632
- );
2633
- } else {
2634
- fallbackChildFragment = createFiberFromFragment(
2635
- fallbackChildren,
2636
- mode,
2637
- renderLanes,
2638
- null,
2639
- );
2640
- // Needs a placement effect because the parent (the Suspense boundary) already
2641
- // mounted but this is a new fiber.
2642
- fallbackChildFragment.flags |= Placement;
2643
- }
2644
-
2645
- fallbackChildFragment.return = workInProgress;
2646
- primaryChildFragment.return = workInProgress;
2647
- primaryChildFragment.sibling = fallbackChildFragment;
2648
- workInProgress.child = primaryChildFragment;
2649
-
2650
- return fallbackChildFragment;
2651
-}
2652
-
2653
-function retrySuspenseComponentWithoutHydrating(
2654
- current: Fiber,
2655
- workInProgress: Fiber,
2656
- renderLanes: Lanes,
2657
- recoverableError: CapturedValue<mixed> | null,
2658
-) {
2659
- // Falling back to client rendering. Because this has performance
2660
- // implications, it's considered a recoverable error, even though the user
2661
- // likely won't observe anything wrong with the UI.
2662
- //
2663
- // The error is passed in as an argument to enforce that every caller provide
2664
- // a custom message, or explicitly opt out (currently the only path that opts
2665
- // out is legacy mode; every concurrent path provides an error).
2666
- if (recoverableError !== null) {
2667
- queueHydrationError(recoverableError);
2668
- }
2669
-
2670
- // This will add the old fiber to the deletion list
2671
- reconcileChildFibers(workInProgress, current.child, null, renderLanes);
2672
-
2673
- // We're now not suspended nor dehydrated.
2674
- const nextProps = workInProgress.pendingProps;
2675
- const primaryChildren = nextProps.children;
2676
- const primaryChildFragment = mountSuspensePrimaryChildren(
2677
- workInProgress,
2678
- primaryChildren,
2679
- renderLanes,
2680
- );
2681
- // Needs a placement effect because the parent (the Suspense boundary) already
2682
- // mounted but this is a new fiber.
2683
- primaryChildFragment.flags |= Placement;
2684
- workInProgress.memoizedState = null;
2685
-
2686
- return primaryChildFragment;
2687
-}
2688
-
2689
-function mountSuspenseFallbackAfterRetryWithoutHydrating(
2690
- current,
2691
- workInProgress,
2692
- primaryChildren,
2693
- fallbackChildren,
2694
- renderLanes,
2695
-) {
2696
- const fiberMode = workInProgress.mode;
2697
- const primaryChildProps: OffscreenProps = {
2698
- mode: 'visible',
2699
- children: primaryChildren,
2700
- };
2701
- const primaryChildFragment = mountWorkInProgressOffscreenFiber(
2702
- primaryChildProps,
2703
- fiberMode,
2704
- NoLanes,
2705
- );
2706
- const fallbackChildFragment = createFiberFromFragment(
2707
- fallbackChildren,
2708
- fiberMode,
2709
- renderLanes,
2710
- null,
2711
- );
2712
- // Needs a placement effect because the parent (the Suspense
2713
- // boundary) already mounted but this is a new fiber.
2714
- fallbackChildFragment.flags |= Placement;
2715
-
2716
- primaryChildFragment.return = workInProgress;
2717
- fallbackChildFragment.return = workInProgress;
2718
- primaryChildFragment.sibling = fallbackChildFragment;
2719
- workInProgress.child = primaryChildFragment;
2720
-
2721
- if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
2722
- // We will have dropped the effect list which contains the
2723
- // deletion. We need to reconcile to delete the current child.
2724
- reconcileChildFibers(workInProgress, current.child, null, renderLanes);
2725
- }
2726
-
2727
- return fallbackChildFragment;
2728
-}
2729
-
2730
-function mountDehydratedSuspenseComponent(
2731
- workInProgress: Fiber,
2732
- suspenseInstance: SuspenseInstance,
2733
- renderLanes: Lanes,
2734
-): null | Fiber {
2735
- // During the first pass, we'll bail out and not drill into the children.
2736
- // Instead, we'll leave the content in place and try to hydrate it later.
2737
- if ((workInProgress.mode & ConcurrentMode) === NoMode) {
2738
- if (__DEV__) {
2739
- console.error(
2740
- 'Cannot hydrate Suspense in legacy mode. Switch from ' +
2741
- 'ReactDOM.hydrate(element, container) to ' +
2742
- 'ReactDOMClient.hydrateRoot(container, <App />)' +
2743
- '.render(element) or remove the Suspense components from ' +
2744
- 'the server rendered components.',
2745
- );
2746
- }
2747
- workInProgress.lanes = laneToLanes(SyncLane);
2748
- } else if (isSuspenseInstanceFallback(suspenseInstance)) {
2749
- // This is a client-only boundary. Since we won't get any content from the server
2750
- // for this, we need to schedule that at a higher priority based on when it would
2751
- // have timed out. In theory we could render it in this pass but it would have the
2752
- // wrong priority associated with it and will prevent hydration of parent path.
2753
- // Instead, we'll leave work left on it to render it in a separate commit.
2754
-
2755
- // TODO This time should be the time at which the server rendered response that is
2756
- // a parent to this boundary was displayed. However, since we currently don't have
2757
- // a protocol to transfer that time, we'll just estimate it by using the current
2758
- // time. This will mean that Suspense timeouts are slightly shifted to later than
2759
- // they should be.
2760
- // Schedule a normal pri update to render this content.
2761
- workInProgress.lanes = laneToLanes(DefaultHydrationLane);
2762
- } else {
2763
- // We'll continue hydrating the rest at offscreen priority since we'll already
2764
- // be showing the right content coming from the server, it is no rush.
2765
- workInProgress.lanes = laneToLanes(OffscreenLane);
2766
- }
2767
- return null;
2768
-}
2769
-
2770
-function updateDehydratedSuspenseComponent(
2771
- current: Fiber,
2772
- workInProgress: Fiber,
2773
- didSuspend: boolean,
2774
- nextProps: any,
2775
- suspenseInstance: SuspenseInstance,
2776
- suspenseState: SuspenseState,
2777
- renderLanes: Lanes,
2778
-): null | Fiber {
2779
- if (!didSuspend) {
2780
- // This is the first render pass. Attempt to hydrate.
2781
- pushPrimaryTreeSuspenseHandler(workInProgress);
2782
-
2783
- // We should never be hydrating at this point because it is the first pass,
2784
- // but after we've already committed once.
2785
- warnIfHydrating();
2786
-
2787
- if ((workInProgress.mode & ConcurrentMode) === NoMode) {
2788
- return retrySuspenseComponentWithoutHydrating(
2789
- current,
2790
- workInProgress,
2791
- renderLanes,
2792
- null,
2793
- );
2794
- }
2795
-
2796
- if (isSuspenseInstanceFallback(suspenseInstance)) {
2797
- // This boundary is in a permanent fallback state. In this case, we'll never
2798
- // get an update and we'll never be able to hydrate the final content. Let's just try the
2799
- // client side render instead.
2800
- let digest, message, stack;
2801
- if (__DEV__) {
2802
- ({digest, message, stack} = getSuspenseInstanceFallbackErrorDetails(
2803
- suspenseInstance,
2804
- ));
2805
- } else {
2806
- ({digest} = getSuspenseInstanceFallbackErrorDetails(suspenseInstance));
2807
- }
2808
-
2809
- let error;
2810
- if (message) {
2811
- // eslint-disable-next-line react-internal/prod-error-codes
2812
- error = new Error(message);
2813
- } else {
2814
- error = new Error(
2815
- 'The server could not finish this Suspense boundary, likely ' +
2816
- 'due to an error during server rendering. Switched to ' +
2817
- 'client rendering.',
2818
- );
2819
- }
2820
- (error: any).digest = digest;
2821
- const capturedValue = createCapturedValue(error, digest, stack);
2822
- return retrySuspenseComponentWithoutHydrating(
2823
- current,
2824
- workInProgress,
2825
- renderLanes,
2826
- capturedValue,
2827
- );
2828
- }
2829
-
2830
- if (
2831
- enableLazyContextPropagation &&
2832
- // TODO: Factoring is a little weird, since we check this right below, too.
2833
- // But don't want to re-arrange the if-else chain until/unless this
2834
- // feature lands.
2835
- !didReceiveUpdate
2836
- ) {
2837
- // We need to check if any children have context before we decide to bail
2838
- // out, so propagate the changes now.
2839
- lazilyPropagateParentContextChanges(current, workInProgress, renderLanes);
2840
- }
2841
-
2842
- // We use lanes to indicate that a child might depend on context, so if
2843
- // any context has changed, we need to treat is as if the input might have changed.
2844
- const hasContextChanged = includesSomeLane(renderLanes, current.childLanes);
2845
- if (didReceiveUpdate || hasContextChanged) {
2846
- // This boundary has changed since the first render. This means that we are now unable to
2847
- // hydrate it. We might still be able to hydrate it using a higher priority lane.
2848
- const root = getWorkInProgressRoot();
2849
- if (root !== null) {
2850
- const attemptHydrationAtLane = getBumpedLaneForHydration(
2851
- root,
2852
- renderLanes,
2853
- );
2854
- if (
2855
- attemptHydrationAtLane !== NoLane &&
2856
- attemptHydrationAtLane !== suspenseState.retryLane
2857
- ) {
2858
- // Intentionally mutating since this render will get interrupted. This
2859
- // is one of the very rare times where we mutate the current tree
2860
- // during the render phase.
2861
- suspenseState.retryLane = attemptHydrationAtLane;
2862
- // TODO: Ideally this would inherit the event time of the current render
2863
- const eventTime = NoTimestamp;
2864
- enqueueConcurrentRenderForLane(current, attemptHydrationAtLane);
2865
- scheduleUpdateOnFiber(
2866
- root,
2867
- current,
2868
- attemptHydrationAtLane,
2869
- eventTime,
2870
- );
2871
-
2872
- // Throw a special object that signals to the work loop that it should
2873
- // interrupt the current render.
2874
- //
2875
- // Because we're inside a React-only execution stack, we don't
2876
- // strictly need to throw here — we could instead modify some internal
2877
- // work loop state. But using an exception means we don't need to
2878
- // check for this case on every iteration of the work loop. So doing
2879
- // it this way moves the check out of the fast path.
2880
- throw SelectiveHydrationException;
2881
- } else {
2882
- // We have already tried to ping at a higher priority than we're rendering with
2883
- // so if we got here, we must have failed to hydrate at those levels. We must
2884
- // now give up. Instead, we're going to delete the whole subtree and instead inject
2885
- // a new real Suspense boundary to take its place, which may render content
2886
- // or fallback. This might suspend for a while and if it does we might still have
2887
- // an opportunity to hydrate before this pass commits.
2888
- }
2889
- }
2890
-
2891
- // If we did not selectively hydrate, we'll continue rendering without
2892
- // hydrating. Mark this tree as suspended to prevent it from committing
2893
- // outside a transition.
2894
- //
2895
- // This path should only happen if the hydration lane already suspended.
2896
- // Currently, it also happens during sync updates because there is no
2897
- // hydration lane for sync updates.
2898
- // TODO: We should ideally have a sync hydration lane that we can apply to do
2899
- // a pass where we hydrate this subtree in place using the previous Context and then
2900
- // reapply the update afterwards.
2901
- renderDidSuspendDelayIfPossible();
2902
- return retrySuspenseComponentWithoutHydrating(
2903
- current,
2904
- workInProgress,
2905
- renderLanes,
2906
- null,
2907
- );
2908
- } else if (isSuspenseInstancePending(suspenseInstance)) {
2909
- // This component is still pending more data from the server, so we can't hydrate its
2910
- // content. We treat it as if this component suspended itself. It might seem as if
2911
- // we could just try to render it client-side instead. However, this will perform a
2912
- // lot of unnecessary work and is unlikely to complete since it often will suspend
2913
- // on missing data anyway. Additionally, the server might be able to render more
2914
- // than we can on the client yet. In that case we'd end up with more fallback states
2915
- // on the client than if we just leave it alone. If the server times out or errors
2916
- // these should update this boundary to the permanent Fallback state instead.
2917
- // Mark it as having captured (i.e. suspended).
2918
- workInProgress.flags |= DidCapture;
2919
- // Leave the child in place. I.e. the dehydrated fragment.
2920
- workInProgress.child = current.child;
2921
- // Register a callback to retry this boundary once the server has sent the result.
2922
- const retry = retryDehydratedSuspenseBoundary.bind(null, current);
2923
- registerSuspenseInstanceRetry(suspenseInstance, retry);
2924
- return null;
2925
- } else {
2926
- // This is the first attempt.
2927
- reenterHydrationStateFromDehydratedSuspenseInstance(
2928
- workInProgress,
2929
- suspenseInstance,
2930
- suspenseState.treeContext,
2931
- );
2932
- const primaryChildren = nextProps.children;
2933
- const primaryChildFragment = mountSuspensePrimaryChildren(
2934
- workInProgress,
2935
- primaryChildren,
2936
- renderLanes,
2937
- );
2938
- // Mark the children as hydrating. This is a fast path to know whether this
2939
- // tree is part of a hydrating tree. This is used to determine if a child
2940
- // node has fully mounted yet, and for scheduling event replaying.
2941
- // Conceptually this is similar to Placement in that a new subtree is
2942
- // inserted into the React tree here. It just happens to not need DOM
2943
- // mutations because it already exists.
2944
- primaryChildFragment.flags |= Hydrating;
2945
- return primaryChildFragment;
2946
- }
2947
- } else {
2948
- // This is the second render pass. We already attempted to hydrated, but
2949
- // something either suspended or errored.
2950
-
2951
- if (workInProgress.flags & ForceClientRender) {
2952
- // Something errored during hydration. Try again without hydrating.
2953
- pushPrimaryTreeSuspenseHandler(workInProgress);
2954
-
2955
- workInProgress.flags &= ~ForceClientRender;
2956
- const capturedValue = createCapturedValue(
2957
- new Error(
2958
- 'There was an error while hydrating this Suspense boundary. ' +
2959
- 'Switched to client rendering.',
2960
- ),
2961
- );
2962
- return retrySuspenseComponentWithoutHydrating(
2963
- current,
2964
- workInProgress,
2965
- renderLanes,
2966
- capturedValue,
2967
- );
2968
- } else if ((workInProgress.memoizedState: null | SuspenseState) !== null) {
2969
- // Something suspended and we should still be in dehydrated mode.
2970
- // Leave the existing child in place.
2971
-
2972
- // Push to avoid a mismatch
2973
- pushFallbackTreeSuspenseHandler(workInProgress);
2974
-
2975
- workInProgress.child = current.child;
2976
- // The dehydrated completion pass expects this flag to be there
2977
- // but the normal suspense pass doesn't.
2978
- workInProgress.flags |= DidCapture;
2979
- return null;
2980
- } else {
2981
- // Suspended but we should no longer be in dehydrated mode.
2982
- // Therefore we now have to render the fallback.
2983
- pushFallbackTreeSuspenseHandler(workInProgress);
2984
-
2985
- const nextPrimaryChildren = nextProps.children;
2986
- const nextFallbackChildren = nextProps.fallback;
2987
- const fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(
2988
- current,
2989
- workInProgress,
2990
- nextPrimaryChildren,
2991
- nextFallbackChildren,
2992
- renderLanes,
2993
- );
2994
- const primaryChildFragment: Fiber = (workInProgress.child: any);
2995
- primaryChildFragment.memoizedState = mountSuspenseOffscreenState(
2996
- renderLanes,
2997
- );
2998
- workInProgress.memoizedState = SUSPENDED_MARKER;
2999
- return fallbackChildFragment;
3000
- }
3001
- }
3002
-}
3003
-
3004
-function scheduleSuspenseWorkOnFiber(
3005
- fiber: Fiber,
3006
- renderLanes: Lanes,
3007
- propagationRoot: Fiber,
3008
-) {
3009
- fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
3010
- const alternate = fiber.alternate;
3011
- if (alternate !== null) {
3012
- alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
3013
- }
3014
- scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot);
3015
-}
3016
-
3017
-function propagateSuspenseContextChange(
3018
- workInProgress: Fiber,
3019
- firstChild: null | Fiber,
3020
- renderLanes: Lanes,
3021
-): void {
3022
- // Mark any Suspense boundaries with fallbacks as having work to do.
3023
- // If they were previously forced into fallbacks, they may now be able
3024
- // to unblock.
3025
- let node = firstChild;
3026
- while (node !== null) {
3027
- if (node.tag === SuspenseComponent) {
3028
- const state: SuspenseState | null = node.memoizedState;
3029
- if (state !== null) {
3030
- scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
3031
- }
3032
- } else if (node.tag === SuspenseListComponent) {
3033
- // If the tail is hidden there might not be an Suspense boundaries
3034
- // to schedule work on. In this case we have to schedule it on the
3035
- // list itself.
3036
- // We don't have to traverse to the children of the list since
3037
- // the list will propagate the change when it rerenders.
3038
- scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
3039
- } else if (node.child !== null) {
3040
- node.child.return = node;
3041
- node = node.child;
3042
- continue;
3043
- }
3044
- if (node === workInProgress) {
3045
- return;
3046
- }
3047
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3048
- while (node.sibling === null) {
3049
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3050
- if (node.return === null || node.return === workInProgress) {
3051
- return;
3052
- }
3053
- node = node.return;
3054
- }
3055
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3056
- node.sibling.return = node.return;
3057
- node = node.sibling;
3058
- }
3059
-}
3060
-
3061
-function findLastContentRow(firstChild: null | Fiber): null | Fiber {
3062
- // This is going to find the last row among these children that is already
3063
- // showing content on the screen, as opposed to being in fallback state or
3064
- // new. If a row has multiple Suspense boundaries, any of them being in the
3065
- // fallback state, counts as the whole row being in a fallback state.
3066
- // Note that the "rows" will be workInProgress, but any nested children
3067
- // will still be current since we haven't rendered them yet. The mounted
3068
- // order may not be the same as the new order. We use the new order.
3069
- let row = firstChild;
3070
- let lastContentRow: null | Fiber = null;
3071
- while (row !== null) {
3072
- const currentRow = row.alternate;
3073
- // New rows can't be content rows.
3074
- if (currentRow !== null && findFirstSuspended(currentRow) === null) {
3075
- lastContentRow = row;
3076
- }
3077
- row = row.sibling;
3078
- }
3079
- return lastContentRow;
3080
-}
3081
-
3082
-type SuspenseListRevealOrder = 'forwards' | 'backwards' | 'together' | void;
3083
-
3084
-function validateRevealOrder(revealOrder: SuspenseListRevealOrder) {
3085
- if (__DEV__) {
3086
- if (
3087
- revealOrder !== undefined &&
3088
- revealOrder !== 'forwards' &&
3089
- revealOrder !== 'backwards' &&
3090
- revealOrder !== 'together' &&
3091
- !didWarnAboutRevealOrder[revealOrder]
3092
- ) {
3093
- didWarnAboutRevealOrder[revealOrder] = true;
3094
- if (typeof revealOrder === 'string') {
3095
- switch (revealOrder.toLowerCase()) {
3096
- case 'together':
3097
- case 'forwards':
3098
- case 'backwards': {
3099
- console.error(
3100
- '"%s" is not a valid value for revealOrder on <SuspenseList />. ' +
3101
- 'Use lowercase "%s" instead.',
3102
- revealOrder,
3103
- revealOrder.toLowerCase(),
3104
- );
3105
- break;
3106
- }
3107
- case 'forward':
3108
- case 'backward': {
3109
- console.error(
3110
- '"%s" is not a valid value for revealOrder on <SuspenseList />. ' +
3111
- 'React uses the -s suffix in the spelling. Use "%ss" instead.',
3112
- revealOrder,
3113
- revealOrder.toLowerCase(),
3114
- );
3115
- break;
3116
- }
3117
- default:
3118
- console.error(
3119
- '"%s" is not a supported revealOrder on <SuspenseList />. ' +
3120
- 'Did you mean "together", "forwards" or "backwards"?',
3121
- revealOrder,
3122
- );
3123
- break;
3124
- }
3125
- } else {
3126
- console.error(
3127
- '%s is not a supported value for revealOrder on <SuspenseList />. ' +
3128
- 'Did you mean "together", "forwards" or "backwards"?',
3129
- revealOrder,
3130
- );
3131
- }
3132
- }
3133
- }
3134
-}
3135
-
3136
-function validateTailOptions(
3137
- tailMode: SuspenseListTailMode,
3138
- revealOrder: SuspenseListRevealOrder,
3139
-) {
3140
- if (__DEV__) {
3141
- if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
3142
- if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
3143
- didWarnAboutTailOptions[tailMode] = true;
3144
- console.error(
3145
- '"%s" is not a supported value for tail on <SuspenseList />. ' +
3146
- 'Did you mean "collapsed" or "hidden"?',
3147
- tailMode,
3148
- );
3149
- } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
3150
- didWarnAboutTailOptions[tailMode] = true;
3151
- console.error(
3152
- '<SuspenseList tail="%s" /> is only valid if revealOrder is ' +
3153
- '"forwards" or "backwards". ' +
3154
- 'Did you mean to specify revealOrder="forwards"?',
3155
- tailMode,
3156
- );
3157
- }
3158
- }
3159
- }
3160
-}
3161
-
3162
-function validateSuspenseListNestedChild(childSlot: mixed, index: number) {
3163
- if (__DEV__) {
3164
- const isAnArray = isArray(childSlot);
3165
- const isIterable =
3166
- !isAnArray && typeof getIteratorFn(childSlot) === 'function';
3167
- if (isAnArray || isIterable) {
3168
- const type = isAnArray ? 'array' : 'iterable';
3169
- console.error(
3170
- 'A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' +
3171
- 'an additional SuspenseList to configure its revealOrder: ' +
3172
- '<SuspenseList revealOrder=...> ... ' +
3173
- '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' +
3174
- '</SuspenseList>',
3175
- type,
3176
- index,
3177
- type,
3178
- );
3179
- return false;
3180
- }
3181
- }
3182
- return true;
3183
-}
3184
-
3185
-function validateSuspenseListChildren(
3186
- children: mixed,
3187
- revealOrder: SuspenseListRevealOrder,
3188
-) {
3189
- if (__DEV__) {
3190
- if (
3191
- (revealOrder === 'forwards' || revealOrder === 'backwards') &&
3192
- children !== undefined &&
3193
- children !== null &&
3194
- children !== false
3195
- ) {
3196
- if (isArray(children)) {
3197
- for (let i = 0; i < children.length; i++) {
3198
- if (!validateSuspenseListNestedChild(children[i], i)) {
3199
- return;
3200
- }
3201
- }
3202
- } else {
3203
- const iteratorFn = getIteratorFn(children);
3204
- if (typeof iteratorFn === 'function') {
3205
- const childrenIterator = iteratorFn.call(children);
3206
- if (childrenIterator) {
3207
- let step = childrenIterator.next();
3208
- let i = 0;
3209
- for (; !step.done; step = childrenIterator.next()) {
3210
- if (!validateSuspenseListNestedChild(step.value, i)) {
3211
- return;
3212
- }
3213
- i++;
3214
- }
3215
- }
3216
- } else {
3217
- console.error(
3218
- 'A single row was passed to a <SuspenseList revealOrder="%s" />. ' +
3219
- 'This is not useful since it needs multiple rows. ' +
3220
- 'Did you mean to pass multiple children or an array?',
3221
- revealOrder,
3222
- );
3223
- }
3224
- }
3225
- }
3226
- }
3227
-}
3228
-
3229
-function initSuspenseListRenderState(
3230
- workInProgress: Fiber,
3231
- isBackwards: boolean,
3232
- tail: null | Fiber,
3233
- lastContentRow: null | Fiber,
3234
- tailMode: SuspenseListTailMode,
3235
-): void {
3236
- const renderState: null | SuspenseListRenderState =
3237
- workInProgress.memoizedState;
3238
- if (renderState === null) {
3239
- workInProgress.memoizedState = ({
3240
- isBackwards: isBackwards,
3241
- rendering: null,
3242
- renderingStartTime: 0,
3243
- last: lastContentRow,
3244
- tail: tail,
3245
- tailMode: tailMode,
3246
- }: SuspenseListRenderState);
3247
- } else {
3248
- // We can reuse the existing object from previous renders.
3249
- renderState.isBackwards = isBackwards;
3250
- renderState.rendering = null;
3251
- renderState.renderingStartTime = 0;
3252
- renderState.last = lastContentRow;
3253
- renderState.tail = tail;
3254
- renderState.tailMode = tailMode;
3255
- }
3256
-}
3257
-
3258
-// This can end up rendering this component multiple passes.
3259
-// The first pass splits the children fibers into two sets. A head and tail.
3260
-// We first render the head. If anything is in fallback state, we do another
3261
-// pass through beginWork to rerender all children (including the tail) with
3262
-// the force suspend context. If the first render didn't have anything in
3263
-// in fallback state. Then we render each row in the tail one-by-one.
3264
-// That happens in the completeWork phase without going back to beginWork.
3265
-function updateSuspenseListComponent(
3266
- current: Fiber | null,
3267
- workInProgress: Fiber,
3268
- renderLanes: Lanes,
3269
-) {
3270
- const nextProps = workInProgress.pendingProps;
3271
- const revealOrder: SuspenseListRevealOrder = nextProps.revealOrder;
3272
- const tailMode: SuspenseListTailMode = nextProps.tail;
3273
- const newChildren = nextProps.children;
3274
-
3275
- validateRevealOrder(revealOrder);
3276
- validateTailOptions(tailMode, revealOrder);
3277
- validateSuspenseListChildren(newChildren, revealOrder);
3278
-
3279
- reconcileChildren(current, workInProgress, newChildren, renderLanes);
3280
-
3281
- let suspenseContext: SuspenseContext = suspenseStackCursor.current;
3282
-
3283
- const shouldForceFallback = hasSuspenseListContext(
3284
- suspenseContext,
3285
- (ForceSuspenseFallback: SuspenseContext),
3286
- );
3287
- if (shouldForceFallback) {
3288
- suspenseContext = setShallowSuspenseListContext(
3289
- suspenseContext,
3290
- ForceSuspenseFallback,
3291
- );
3292
- workInProgress.flags |= DidCapture;
3293
- } else {
3294
- const didSuspendBefore =
3295
- current !== null && (current.flags & DidCapture) !== NoFlags;
3296
- if (didSuspendBefore) {
3297
- // If we previously forced a fallback, we need to schedule work
3298
- // on any nested boundaries to let them know to try to render
3299
- // again. This is the same as context updating.
3300
- propagateSuspenseContextChange(
3301
- workInProgress,
3302
- workInProgress.child,
3303
- renderLanes,
3304
- );
3305
- }
3306
- suspenseContext = setDefaultShallowSuspenseListContext(suspenseContext);
3307
- }
3308
- pushSuspenseListContext(workInProgress, suspenseContext);
3309
-
3310
- if ((workInProgress.mode & ConcurrentMode) === NoMode) {
3311
- // In legacy mode, SuspenseList doesn't work so we just
3312
- // use make it a noop by treating it as the default revealOrder.
3313
- workInProgress.memoizedState = null;
3314
- } else {
3315
- switch (revealOrder) {
3316
- case 'forwards': {
3317
- const lastContentRow = findLastContentRow(workInProgress.child);
3318
- let tail;
3319
- if (lastContentRow === null) {
3320
- // The whole list is part of the tail.
3321
- // TODO: We could fast path by just rendering the tail now.
3322
- tail = workInProgress.child;
3323
- workInProgress.child = null;
3324
- } else {
3325
- // Disconnect the tail rows after the content row.
3326
- // We're going to render them separately later.
3327
- tail = lastContentRow.sibling;
3328
- lastContentRow.sibling = null;
3329
- }
3330
- initSuspenseListRenderState(
3331
- workInProgress,
3332
- false, // isBackwards
3333
- tail,
3334
- lastContentRow,
3335
- tailMode,
3336
- );
3337
- break;
3338
- }
3339
- case 'backwards': {
3340
- // We're going to find the first row that has existing content.
3341
- // At the same time we're going to reverse the list of everything
3342
- // we pass in the meantime. That's going to be our tail in reverse
3343
- // order.
3344
- let tail = null;
3345
- let row = workInProgress.child;
3346
- workInProgress.child = null;
3347
- while (row !== null) {
3348
- const currentRow = row.alternate;
3349
- // New rows can't be content rows.
3350
- if (currentRow !== null && findFirstSuspended(currentRow) === null) {
3351
- // This is the beginning of the main content.
3352
- workInProgress.child = row;
3353
- break;
3354
- }
3355
- const nextRow = row.sibling;
3356
- row.sibling = tail;
3357
- tail = row;
3358
- row = nextRow;
3359
- }
3360
- // TODO: If workInProgress.child is null, we can continue on the tail immediately.
3361
- initSuspenseListRenderState(
3362
- workInProgress,
3363
- true, // isBackwards
3364
- tail,
3365
- null, // last
3366
- tailMode,
3367
- );
3368
- break;
3369
- }
3370
- case 'together': {
3371
- initSuspenseListRenderState(
3372
- workInProgress,
3373
- false, // isBackwards
3374
- null, // tail
3375
- null, // last
3376
- undefined,
3377
- );
3378
- break;
3379
- }
3380
- default: {
3381
- // The default reveal order is the same as not having
3382
- // a boundary.
3383
- workInProgress.memoizedState = null;
3384
- }
3385
- }
3386
- }
3387
- return workInProgress.child;
3388
-}
3389
-
3390
-function updatePortalComponent(
3391
- current: Fiber | null,
3392
- workInProgress: Fiber,
3393
- renderLanes: Lanes,
3394
-) {
3395
- pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
3396
- const nextChildren = workInProgress.pendingProps;
3397
- if (current === null) {
3398
- // Portals are special because we don't append the children during mount
3399
- // but at commit. Therefore we need to track insertions which the normal
3400
- // flow doesn't do during mount. This doesn't happen at the root because
3401
- // the root always starts with a "current" with a null child.
3402
- // TODO: Consider unifying this with how the root works.
3403
- workInProgress.child = reconcileChildFibers(
3404
- workInProgress,
3405
- null,
3406
- nextChildren,
3407
- renderLanes,
3408
- );
3409
- } else {
3410
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
3411
- }
3412
- return workInProgress.child;
3413
-}
3414
-
3415
-let hasWarnedAboutUsingNoValuePropOnContextProvider = false;
3416
-
3417
-function updateContextProvider(
3418
- current: Fiber | null,
3419
- workInProgress: Fiber,
3420
- renderLanes: Lanes,
3421
-) {
3422
- const providerType: ReactProviderType<any> = workInProgress.type;
3423
- const context: ReactContext<any> = providerType._context;
3424
-
3425
- const newProps = workInProgress.pendingProps;
3426
- const oldProps = workInProgress.memoizedProps;
3427
-
3428
- const newValue = newProps.value;
3429
-
3430
- if (__DEV__) {
3431
- if (!('value' in newProps)) {
3432
- if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
3433
- hasWarnedAboutUsingNoValuePropOnContextProvider = true;
3434
- console.error(
3435
- 'The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?',
3436
- );
3437
- }
3438
- }
3439
- const providerPropTypes = workInProgress.type.propTypes;
3440
-
3441
- if (providerPropTypes) {
3442
- checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider');
3443
- }
3444
- }
3445
-
3446
- pushProvider(workInProgress, context, newValue);
3447
-
3448
- if (enableLazyContextPropagation) {
3449
- // In the lazy propagation implementation, we don't scan for matching
3450
- // consumers until something bails out, because until something bails out
3451
- // we're going to visit those nodes, anyway. The trade-off is that it shifts
3452
- // responsibility to the consumer to track whether something has changed.
3453
- } else {
3454
- if (oldProps !== null) {
3455
- const oldValue = oldProps.value;
3456
- if (is(oldValue, newValue)) {
3457
- // No change. Bailout early if children are the same.
3458
- if (
3459
- oldProps.children === newProps.children &&
3460
- !hasLegacyContextChanged()
3461
- ) {
3462
- return bailoutOnAlreadyFinishedWork(
3463
- current,
3464
- workInProgress,
3465
- renderLanes,
3466
- );
3467
- }
3468
- } else {
3469
- // The context value changed. Search for matching consumers and schedule
3470
- // them to update.
3471
- propagateContextChange(workInProgress, context, renderLanes);
3472
- }
3473
- }
3474
- }
3475
-
3476
- const newChildren = newProps.children;
3477
- reconcileChildren(current, workInProgress, newChildren, renderLanes);
3478
- return workInProgress.child;
3479
-}
3480
-
3481
-let hasWarnedAboutUsingContextAsConsumer = false;
3482
-
3483
-function updateContextConsumer(
3484
- current: Fiber | null,
3485
- workInProgress: Fiber,
3486
- renderLanes: Lanes,
3487
-) {
3488
- let context: ReactContext<any> = workInProgress.type;
3489
- // The logic below for Context differs depending on PROD or DEV mode. In
3490
- // DEV mode, we create a separate object for Context.Consumer that acts
3491
- // like a proxy to Context. This proxy object adds unnecessary code in PROD
3492
- // so we use the old behaviour (Context.Consumer references Context) to
3493
- // reduce size and overhead. The separate object references context via
3494
- // a property called "_context", which also gives us the ability to check
3495
- // in DEV mode if this property exists or not and warn if it does not.
3496
- if (__DEV__) {
3497
- if ((context: any)._context === undefined) {
3498
- // This may be because it's a Context (rather than a Consumer).
3499
- // Or it may be because it's older React where they're the same thing.
3500
- // We only want to warn if we're sure it's a new React.
3501
- if (context !== context.Consumer) {
3502
- if (!hasWarnedAboutUsingContextAsConsumer) {
3503
- hasWarnedAboutUsingContextAsConsumer = true;
3504
- console.error(
3505
- 'Rendering <Context> directly is not supported and will be removed in ' +
3506
- 'a future major release. Did you mean to render <Context.Consumer> instead?',
3507
- );
3508
- }
3509
- }
3510
- } else {
3511
- context = (context: any)._context;
3512
- }
3513
- }
3514
- const newProps = workInProgress.pendingProps;
3515
- const render = newProps.children;
3516
-
3517
- if (__DEV__) {
3518
- if (typeof render !== 'function') {
3519
- console.error(
3520
- 'A context consumer was rendered with multiple children, or a child ' +
3521
- "that isn't a function. A context consumer expects a single child " +
3522
- 'that is a function. If you did pass a function, make sure there ' +
3523
- 'is no trailing or leading whitespace around it.',
3524
- );
3525
- }
3526
- }
3527
-
3528
- prepareToReadContext(workInProgress, renderLanes);
3529
- const newValue = readContext(context);
3530
- if (enableSchedulingProfiler) {
3531
- markComponentRenderStarted(workInProgress);
3532
- }
3533
- let newChildren;
3534
- if (__DEV__) {
3535
- ReactCurrentOwner.current = workInProgress;
3536
- setIsRendering(true);
3537
- newChildren = render(newValue);
3538
- setIsRendering(false);
3539
- } else {
3540
- newChildren = render(newValue);
3541
- }
3542
- if (enableSchedulingProfiler) {
3543
- markComponentRenderStopped();
3544
- }
3545
-
3546
- // React DevTools reads this flag.
3547
- workInProgress.flags |= PerformedWork;
3548
- reconcileChildren(current, workInProgress, newChildren, renderLanes);
3549
- return workInProgress.child;
3550
-}
3551
-
3552
-function updateScopeComponent(current, workInProgress, renderLanes) {
3553
- const nextProps = workInProgress.pendingProps;
3554
- const nextChildren = nextProps.children;
3555
-
3556
- reconcileChildren(current, workInProgress, nextChildren, renderLanes);
3557
- return workInProgress.child;
3558
-}
3559
-
3560
-export function markWorkInProgressReceivedUpdate() {
3561
- didReceiveUpdate = true;
3562
-}
3563
-
3564
-export function checkIfWorkInProgressReceivedUpdate(): boolean {
3565
- return didReceiveUpdate;
3566
-}
3567
-
3568
-function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) {
3569
- if ((workInProgress.mode & ConcurrentMode) === NoMode) {
3570
- if (current !== null) {
3571
- // A lazy component only mounts if it suspended inside a non-
3572
- // concurrent tree, in an inconsistent state. We want to treat it like
3573
- // a new mount, even though an empty version of it already committed.
3574
- // Disconnect the alternate pointers.
3575
- current.alternate = null;
3576
- workInProgress.alternate = null;
3577
- // Since this is conceptually a new fiber, schedule a Placement effect
3578
- workInProgress.flags |= Placement;
3579
- }
3580
- }
3581
-}
3582
-
3583
-function bailoutOnAlreadyFinishedWork(
3584
- current: Fiber | null,
3585
- workInProgress: Fiber,
3586
- renderLanes: Lanes,
3587
-): Fiber | null {
3588
- if (current !== null) {
3589
- // Reuse previous dependencies
3590
- workInProgress.dependencies = current.dependencies;
3591
- }
3592
-
3593
- if (enableProfilerTimer) {
3594
- // Don't update "base" render times for bailouts.
3595
- stopProfilerTimerIfRunning(workInProgress);
3596
- }
3597
-
3598
- markSkippedUpdateLanes(workInProgress.lanes);
3599
-
3600
- // Check if the children have any pending work.
3601
- if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
3602
- // The children don't have any work either. We can skip them.
3603
- // TODO: Once we add back resuming, we should check if the children are
3604
- // a work-in-progress set. If so, we need to transfer their effects.
3605
-
3606
- if (enableLazyContextPropagation && current !== null) {
3607
- // Before bailing out, check if there are any context changes in
3608
- // the children.
3609
- lazilyPropagateParentContextChanges(current, workInProgress, renderLanes);
3610
- if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
3611
- return null;
3612
- }
3613
- } else {
3614
- return null;
3615
- }
3616
- }
3617
-
3618
- // This fiber doesn't have work, but its subtree does. Clone the child
3619
- // fibers and continue.
3620
- cloneChildFibers(current, workInProgress);
3621
- return workInProgress.child;
3622
-}
3623
-
3624
-function remountFiber(
3625
- current: Fiber,
3626
- oldWorkInProgress: Fiber,
3627
- newWorkInProgress: Fiber,
3628
-): Fiber | null {
3629
- if (__DEV__) {
3630
- const returnFiber = oldWorkInProgress.return;
3631
- if (returnFiber === null) {
3632
- // eslint-disable-next-line react-internal/prod-error-codes
3633
- throw new Error('Cannot swap the root fiber.');
3634
- }
3635
-
3636
- // Disconnect from the old current.
3637
- // It will get deleted.
3638
- current.alternate = null;
3639
- oldWorkInProgress.alternate = null;
3640
-
3641
- // Connect to the new tree.
3642
- newWorkInProgress.index = oldWorkInProgress.index;
3643
- newWorkInProgress.sibling = oldWorkInProgress.sibling;
3644
- newWorkInProgress.return = oldWorkInProgress.return;
3645
- newWorkInProgress.ref = oldWorkInProgress.ref;
3646
-
3647
- // Replace the child/sibling pointers above it.
3648
- if (oldWorkInProgress === returnFiber.child) {
3649
- returnFiber.child = newWorkInProgress;
3650
- } else {
3651
- let prevSibling = returnFiber.child;
3652
- if (prevSibling === null) {
3653
- // eslint-disable-next-line react-internal/prod-error-codes
3654
- throw new Error('Expected parent to have a child.');
3655
- }
3656
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3657
- while (prevSibling.sibling !== oldWorkInProgress) {
3658
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3659
- prevSibling = prevSibling.sibling;
3660
- if (prevSibling === null) {
3661
- // eslint-disable-next-line react-internal/prod-error-codes
3662
- throw new Error('Expected to find the previous sibling.');
3663
- }
3664
- }
3665
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3666
- prevSibling.sibling = newWorkInProgress;
3667
- }
3668
-
3669
- // Delete the old fiber and place the new one.
3670
- // Since the old fiber is disconnected, we have to schedule it manually.
3671
- const deletions = returnFiber.deletions;
3672
- if (deletions === null) {
3673
- returnFiber.deletions = [current];
3674
- returnFiber.flags |= ChildDeletion;
3675
- } else {
3676
- deletions.push(current);
3677
- }
3678
-
3679
- newWorkInProgress.flags |= Placement;
3680
-
3681
- // Restart work from the new fiber.
3682
- return newWorkInProgress;
3683
- } else {
3684
- throw new Error(
3685
- 'Did not expect this call in production. ' +
3686
- 'This is a bug in React. Please file an issue.',
3687
- );
3688
- }
3689
-}
3690
-
3691
-function checkScheduledUpdateOrContext(
3692
- current: Fiber,
3693
- renderLanes: Lanes,
3694
-): boolean {
3695
- // Before performing an early bailout, we must check if there are pending
3696
- // updates or context.
3697
- const updateLanes = current.lanes;
3698
- if (includesSomeLane(updateLanes, renderLanes)) {
3699
- return true;
3700
- }
3701
- // No pending update, but because context is propagated lazily, we need
3702
- // to check for a context change before we bail out.
3703
- if (enableLazyContextPropagation) {
3704
- const dependencies = current.dependencies;
3705
- if (dependencies !== null && checkIfContextChanged(dependencies)) {
3706
- return true;
3707
- }
3708
- }
3709
- return false;
3710
-}
3711
-
3712
-function attemptEarlyBailoutIfNoScheduledUpdate(
3713
- current: Fiber,
3714
- workInProgress: Fiber,
3715
- renderLanes: Lanes,
3716
-) {
3717
- // This fiber does not have any pending work. Bailout without entering
3718
- // the begin phase. There's still some bookkeeping we that needs to be done
3719
- // in this optimized path, mostly pushing stuff onto the stack.
3720
- switch (workInProgress.tag) {
3721
- case HostRoot:
3722
- pushHostRootContext(workInProgress);
3723
- const root: FiberRoot = workInProgress.stateNode;
3724
- pushRootTransition(workInProgress, root, renderLanes);
3725
-
3726
- if (enableTransitionTracing) {
3727
- pushRootMarkerInstance(workInProgress);
3728
- }
3729
-
3730
- if (enableCache) {
3731
- const cache: Cache = current.memoizedState.cache;
3732
- pushCacheProvider(workInProgress, cache);
3733
- }
3734
- resetHydrationState();
3735
- break;
3736
- case HostResource:
3737
- case HostSingleton:
3738
- case HostComponent:
3739
- pushHostContext(workInProgress);
3740
- break;
3741
- case ClassComponent: {
3742
- const Component = workInProgress.type;
3743
- if (isLegacyContextProvider(Component)) {
3744
- pushLegacyContextProvider(workInProgress);
3745
- }
3746
- break;
3747
- }
3748
- case HostPortal:
3749
- pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
3750
- break;
3751
- case ContextProvider: {
3752
- const newValue = workInProgress.memoizedProps.value;
3753
- const context: ReactContext<any> = workInProgress.type._context;
3754
- pushProvider(workInProgress, context, newValue);
3755
- break;
3756
- }
3757
- case Profiler:
3758
- if (enableProfilerTimer) {
3759
- // Profiler should only call onRender when one of its descendants actually rendered.
3760
- const hasChildWork = includesSomeLane(
3761
- renderLanes,
3762
- workInProgress.childLanes,
3763
- );
3764
- if (hasChildWork) {
3765
- workInProgress.flags |= Update;
3766
- }
3767
-
3768
- if (enableProfilerCommitHooks) {
3769
- // Reset effect durations for the next eventual effect phase.
3770
- // These are reset during render to allow the DevTools commit hook a chance to read them,
3771
- const stateNode = workInProgress.stateNode;
3772
- stateNode.effectDuration = 0;
3773
- stateNode.passiveEffectDuration = 0;
3774
- }
3775
- }
3776
- break;
3777
- case SuspenseComponent: {
3778
- const state: SuspenseState | null = workInProgress.memoizedState;
3779
- if (state !== null) {
3780
- if (state.dehydrated !== null) {
3781
- // We're not going to render the children, so this is just to maintain
3782
- // push/pop symmetry
3783
- pushPrimaryTreeSuspenseHandler(workInProgress);
3784
- // We know that this component will suspend again because if it has
3785
- // been unsuspended it has committed as a resolved Suspense component.
3786
- // If it needs to be retried, it should have work scheduled on it.
3787
- workInProgress.flags |= DidCapture;
3788
- // We should never render the children of a dehydrated boundary until we
3789
- // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork.
3790
- return null;
3791
- }
3792
-
3793
- // If this boundary is currently timed out, we need to decide
3794
- // whether to retry the primary children, or to skip over it and
3795
- // go straight to the fallback. Check the priority of the primary
3796
- // child fragment.
3797
- const primaryChildFragment: Fiber = (workInProgress.child: any);
3798
- const primaryChildLanes = primaryChildFragment.childLanes;
3799
- if (includesSomeLane(renderLanes, primaryChildLanes)) {
3800
- // The primary children have pending work. Use the normal path
3801
- // to attempt to render the primary children again.
3802
- return updateSuspenseComponent(current, workInProgress, renderLanes);
3803
- } else {
3804
- // The primary child fragment does not have pending work marked
3805
- // on it
3806
- pushPrimaryTreeSuspenseHandler(workInProgress);
3807
- // The primary children do not have pending work with sufficient
3808
- // priority. Bailout.
3809
- const child = bailoutOnAlreadyFinishedWork(
3810
- current,
3811
- workInProgress,
3812
- renderLanes,
3813
- );
3814
- if (child !== null) {
3815
- // The fallback children have pending work. Skip over the
3816
- // primary children and work on the fallback.
3817
- return child.sibling;
3818
- } else {
3819
- // Note: We can return `null` here because we already checked
3820
- // whether there were nested context consumers, via the call to
3821
- // `bailoutOnAlreadyFinishedWork` above.
3822
- return null;
3823
- }
3824
- }
3825
- } else {
3826
- pushPrimaryTreeSuspenseHandler(workInProgress);
3827
- }
3828
- break;
3829
- }
3830
- case SuspenseListComponent: {
3831
- const didSuspendBefore = (current.flags & DidCapture) !== NoFlags;
3832
-
3833
- let hasChildWork = includesSomeLane(
3834
- renderLanes,
3835
- workInProgress.childLanes,
3836
- );
3837
-
3838
- if (enableLazyContextPropagation && !hasChildWork) {
3839
- // Context changes may not have been propagated yet. We need to do
3840
- // that now, before we can decide whether to bail out.
3841
- // TODO: We use `childLanes` as a heuristic for whether there is
3842
- // remaining work in a few places, including
3843
- // `bailoutOnAlreadyFinishedWork` and
3844
- // `updateDehydratedSuspenseComponent`. We should maybe extract this
3845
- // into a dedicated function.
3846
- lazilyPropagateParentContextChanges(
3847
- current,
3848
- workInProgress,
3849
- renderLanes,
3850
- );
3851
- hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
3852
- }
3853
-
3854
- if (didSuspendBefore) {
3855
- if (hasChildWork) {
3856
- // If something was in fallback state last time, and we have all the
3857
- // same children then we're still in progressive loading state.
3858
- // Something might get unblocked by state updates or retries in the
3859
- // tree which will affect the tail. So we need to use the normal
3860
- // path to compute the correct tail.
3861
- return updateSuspenseListComponent(
3862
- current,
3863
- workInProgress,
3864
- renderLanes,
3865
- );
3866
- }
3867
- // If none of the children had any work, that means that none of
3868
- // them got retried so they'll still be blocked in the same way
3869
- // as before. We can fast bail out.
3870
- workInProgress.flags |= DidCapture;
3871
- }
3872
-
3873
- // If nothing suspended before and we're rendering the same children,
3874
- // then the tail doesn't matter. Anything new that suspends will work
3875
- // in the "together" mode, so we can continue from the state we had.
3876
- const renderState = workInProgress.memoizedState;
3877
- if (renderState !== null) {
3878
- // Reset to the "together" mode in case we've started a different
3879
- // update in the past but didn't complete it.
3880
- renderState.rendering = null;
3881
- renderState.tail = null;
3882
- renderState.lastEffect = null;
3883
- }
3884
- pushSuspenseListContext(workInProgress, suspenseStackCursor.current);
3885
-
3886
- if (hasChildWork) {
3887
- break;
3888
- } else {
3889
- // If none of the children had any work, that means that none of
3890
- // them got retried so they'll still be blocked in the same way
3891
- // as before. We can fast bail out.
3892
- return null;
3893
- }
3894
- }
3895
- case OffscreenComponent:
3896
- case LegacyHiddenComponent: {
3897
- // Need to check if the tree still needs to be deferred. This is
3898
- // almost identical to the logic used in the normal update path,
3899
- // so we'll just enter that. The only difference is we'll bail out
3900
- // at the next level instead of this one, because the child props
3901
- // have not changed. Which is fine.
3902
- // TODO: Probably should refactor `beginWork` to split the bailout
3903
- // path from the normal path. I'm tempted to do a labeled break here
3904
- // but I won't :)
3905
- workInProgress.lanes = NoLanes;
3906
- return updateOffscreenComponent(current, workInProgress, renderLanes);
3907
- }
3908
- case CacheComponent: {
3909
- if (enableCache) {
3910
- const cache: Cache = current.memoizedState.cache;
3911
- pushCacheProvider(workInProgress, cache);
3912
- }
3913
- break;
3914
- }
3915
- case TracingMarkerComponent: {
3916
- if (enableTransitionTracing) {
3917
- const instance: TracingMarkerInstance | null = workInProgress.stateNode;
3918
- if (instance !== null) {
3919
- pushMarkerInstance(workInProgress, instance);
3920
- }
3921
- }
3922
- }
3923
- }
3924
- return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
3925
-}
3926
-
3927
-function beginWork(
3928
- current: Fiber | null,
3929
- workInProgress: Fiber,
3930
- renderLanes: Lanes,
3931
-): Fiber | null {
3932
- if (__DEV__) {
3933
- if (workInProgress._debugNeedsRemount && current !== null) {
3934
- // This will restart the begin phase with a new fiber.
3935
- return remountFiber(
3936
- current,
3937
- workInProgress,
3938
- createFiberFromTypeAndProps(
3939
- workInProgress.type,
3940
- workInProgress.key,
3941
- workInProgress.pendingProps,
3942
- workInProgress._debugOwner || null,
3943
- workInProgress.mode,
3944
- workInProgress.lanes,
3945
- ),
3946
- );
3947
- }
3948
- }
3949
-
3950
- if (current !== null) {
3951
- const oldProps = current.memoizedProps;
3952
- const newProps = workInProgress.pendingProps;
3953
-
3954
- if (
3955
- oldProps !== newProps ||
3956
- hasLegacyContextChanged() ||
3957
- // Force a re-render if the implementation changed due to hot reload:
3958
- (__DEV__ ? workInProgress.type !== current.type : false)
3959
- ) {
3960
- // If props or context changed, mark the fiber as having performed work.
3961
- // This may be unset if the props are determined to be equal later (memo).
3962
- didReceiveUpdate = true;
3963
- } else {
3964
- // Neither props nor legacy context changes. Check if there's a pending
3965
- // update or context change.
3966
- const hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(
3967
- current,
3968
- renderLanes,
3969
- );
3970
- if (
3971
- !hasScheduledUpdateOrContext &&
3972
- // If this is the second pass of an error or suspense boundary, there
3973
- // may not be work scheduled on `current`, so we check for this flag.
3974
- (workInProgress.flags & DidCapture) === NoFlags
3975
- ) {
3976
- // No pending updates or context. Bail out now.
3977
- didReceiveUpdate = false;
3978
- return attemptEarlyBailoutIfNoScheduledUpdate(
3979
- current,
3980
- workInProgress,
3981
- renderLanes,
3982
- );
3983
- }
3984
- if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
3985
- // This is a special case that only exists for legacy mode.
3986
- // See https://github.com/facebook/react/pull/19216.
3987
- didReceiveUpdate = true;
3988
- } else {
3989
- // An update was scheduled on this fiber, but there are no new props
3990
- // nor legacy context. Set this to false. If an update queue or context
3991
- // consumer produces a changed value, it will set this to true. Otherwise,
3992
- // the component will assume the children have not changed and bail out.
3993
- didReceiveUpdate = false;
3994
- }
3995
- }
3996
- } else {
3997
- didReceiveUpdate = false;
3998
-
3999
- if (getIsHydrating() && isForkedChild(workInProgress)) {
4000
- // Check if this child belongs to a list of muliple children in
4001
- // its parent.
4002
- //
4003
- // In a true multi-threaded implementation, we would render children on
4004
- // parallel threads. This would represent the beginning of a new render
4005
- // thread for this subtree.
4006
- //
4007
- // We only use this for id generation during hydration, which is why the
4008
- // logic is located in this special branch.
4009
- const slotIndex = workInProgress.index;
4010
- const numberOfForks = getForksAtLevel(workInProgress);
4011
- pushTreeId(workInProgress, numberOfForks, slotIndex);
4012
- }
4013
- }
4014
-
4015
- // Before entering the begin phase, clear pending update priority.
4016
- // TODO: This assumes that we're about to evaluate the component and process
4017
- // the update queue. However, there's an exception: SimpleMemoComponent
4018
- // sometimes bails out later in the begin phase. This indicates that we should
4019
- // move this assignment out of the common path and into each branch.
4020
- workInProgress.lanes = NoLanes;
4021
-
4022
- switch (workInProgress.tag) {
4023
- case IndeterminateComponent: {
4024
- return mountIndeterminateComponent(
4025
- current,
4026
- workInProgress,
4027
- workInProgress.type,
4028
- renderLanes,
4029
- );
4030
- }
4031
- case LazyComponent: {
4032
- const elementType = workInProgress.elementType;
4033
- return mountLazyComponent(
4034
- current,
4035
- workInProgress,
4036
- elementType,
4037
- renderLanes,
4038
- );
4039
- }
4040
- case FunctionComponent: {
4041
- const Component = workInProgress.type;
4042
- const unresolvedProps = workInProgress.pendingProps;
4043
- const resolvedProps =
4044
- workInProgress.elementType === Component
4045
- ? unresolvedProps
4046
- : resolveDefaultProps(Component, unresolvedProps);
4047
- return updateFunctionComponent(
4048
- current,
4049
- workInProgress,
4050
- Component,
4051
- resolvedProps,
4052
- renderLanes,
4053
- );
4054
- }
4055
- case ClassComponent: {
4056
- const Component = workInProgress.type;
4057
- const unresolvedProps = workInProgress.pendingProps;
4058
- const resolvedProps =
4059
- workInProgress.elementType === Component
4060
- ? unresolvedProps
4061
- : resolveDefaultProps(Component, unresolvedProps);
4062
- return updateClassComponent(
4063
- current,
4064
- workInProgress,
4065
- Component,
4066
- resolvedProps,
4067
- renderLanes,
4068
- );
4069
- }
4070
- case HostRoot:
4071
- return updateHostRoot(current, workInProgress, renderLanes);
4072
- case HostResource:
4073
- if (enableFloat && supportsResources) {
4074
- return updateHostResource(current, workInProgress, renderLanes);
4075
- }
4076
- // eslint-disable-next-line no-fallthrough
4077
- case HostSingleton:
4078
- if (enableHostSingletons && supportsSingletons) {
4079
- return updateHostSingleton(current, workInProgress, renderLanes);
4080
- }
4081
- // eslint-disable-next-line no-fallthrough
4082
- case HostComponent:
4083
- return updateHostComponent(current, workInProgress, renderLanes);
4084
- case HostText:
4085
- return updateHostText(current, workInProgress);
4086
- case SuspenseComponent:
4087
- return updateSuspenseComponent(current, workInProgress, renderLanes);
4088
- case HostPortal:
4089
- return updatePortalComponent(current, workInProgress, renderLanes);
4090
- case ForwardRef: {
4091
- const type = workInProgress.type;
4092
- const unresolvedProps = workInProgress.pendingProps;
4093
- const resolvedProps =
4094
- workInProgress.elementType === type
4095
- ? unresolvedProps
4096
- : resolveDefaultProps(type, unresolvedProps);
4097
- return updateForwardRef(
4098
- current,
4099
- workInProgress,
4100
- type,
4101
- resolvedProps,
4102
- renderLanes,
4103
- );
4104
- }
4105
- case Fragment:
4106
- return updateFragment(current, workInProgress, renderLanes);
4107
- case Mode:
4108
- return updateMode(current, workInProgress, renderLanes);
4109
- case Profiler:
4110
- return updateProfiler(current, workInProgress, renderLanes);
4111
- case ContextProvider:
4112
- return updateContextProvider(current, workInProgress, renderLanes);
4113
- case ContextConsumer:
4114
- return updateContextConsumer(current, workInProgress, renderLanes);
4115
- case MemoComponent: {
4116
- const type = workInProgress.type;
4117
- const unresolvedProps = workInProgress.pendingProps;
4118
- // Resolve outer props first, then resolve inner props.
4119
- let resolvedProps = resolveDefaultProps(type, unresolvedProps);
4120
- if (__DEV__) {
4121
- if (workInProgress.type !== workInProgress.elementType) {
4122
- const outerPropTypes = type.propTypes;
4123
- if (outerPropTypes) {
4124
- checkPropTypes(
4125
- outerPropTypes,
4126
- resolvedProps, // Resolved for outer only
4127
- 'prop',
4128
- getComponentNameFromType(type),
4129
- );
4130
- }
4131
- }
4132
- }
4133
- resolvedProps = resolveDefaultProps(type.type, resolvedProps);
4134
- return updateMemoComponent(
4135
- current,
4136
- workInProgress,
4137
- type,
4138
- resolvedProps,
4139
- renderLanes,
4140
- );
4141
- }
4142
- case SimpleMemoComponent: {
4143
- return updateSimpleMemoComponent(
4144
- current,
4145
- workInProgress,
4146
- workInProgress.type,
4147
- workInProgress.pendingProps,
4148
- renderLanes,
4149
- );
4150
- }
4151
- case IncompleteClassComponent: {
4152
- const Component = workInProgress.type;
4153
- const unresolvedProps = workInProgress.pendingProps;
4154
- const resolvedProps =
4155
- workInProgress.elementType === Component
4156
- ? unresolvedProps
4157
- : resolveDefaultProps(Component, unresolvedProps);
4158
- return mountIncompleteClassComponent(
4159
- current,
4160
- workInProgress,
4161
- Component,
4162
- resolvedProps,
4163
- renderLanes,
4164
- );
4165
- }
4166
- case SuspenseListComponent: {
4167
- return updateSuspenseListComponent(current, workInProgress, renderLanes);
4168
- }
4169
- case ScopeComponent: {
4170
- if (enableScopeAPI) {
4171
- return updateScopeComponent(current, workInProgress, renderLanes);
4172
- }
4173
- break;
4174
- }
4175
- case OffscreenComponent: {
4176
- return updateOffscreenComponent(current, workInProgress, renderLanes);
4177
- }
4178
- case LegacyHiddenComponent: {
4179
- if (enableLegacyHidden) {
4180
- return updateLegacyHiddenComponent(
4181
- current,
4182
- workInProgress,
4183
- renderLanes,
4184
- );
4185
- }
4186
- break;
4187
- }
4188
- case CacheComponent: {
4189
- if (enableCache) {
4190
- return updateCacheComponent(current, workInProgress, renderLanes);
4191
- }
4192
- break;
4193
- }
4194
- case TracingMarkerComponent: {
4195
- if (enableTransitionTracing) {
4196
- return updateTracingMarkerComponent(
4197
- current,
4198
- workInProgress,
4199
- renderLanes,
4200
- );
4201
- }
4202
- break;
4203
- }
4204
- }
4205
-
4206
- throw new Error(
4207
- `Unknown unit of work tag (${workInProgress.tag}). This error is likely caused by a bug in ` +
4208
- 'React. Please file an issue.',
4209
- );
4210
-}
4211
-
4212
-export {beginWork};
packages/react-reconciler/src/ReactFiberBeginWork.old.js
+1
-1
@@ -170,7 +170,7 @@ import {
170
getResource,
171
} from './ReactFiberHostConfig';
172
import type {SuspenseInstance} from './ReactFiberHostConfig';
173
-import {shouldError, shouldSuspend} from './ReactFiberReconciler';
173
+import {shouldError, shouldSuspend} from './ReactFiberReconciler.old';
174
import {pushHostContext, pushHostContainer} from './ReactFiberHostContext.old';
175
import {
176
suspenseStackCursor,
packages/react-reconciler/src/ReactFiberCache.new.js
deleted
-41
@@ -1,41 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {CacheDispatcher} from './ReactInternalTypes';
11
-import type {Cache} from './ReactFiberCacheComponent.new';
12
-
13
-import {enableCache} from 'shared/ReactFeatureFlags';
14
-import {readContext} from './ReactFiberNewContext.new';
15
-import {CacheContext} from './ReactFiberCacheComponent.new';
16
-
17
-function getCacheSignal(): AbortSignal {
18
- if (!enableCache) {
19
- throw new Error('Not implemented.');
20
- }
21
- const cache: Cache = readContext(CacheContext);
22
- return cache.controller.signal;
23
-}
24
-
25
-function getCacheForType<T>(resourceType: () => T): T {
26
- if (!enableCache) {
27
- throw new Error('Not implemented.');
28
- }
29
- const cache: Cache = readContext(CacheContext);
30
- let cacheForType: T | void = (cache.data.get(resourceType): any);
31
- if (cacheForType === undefined) {
32
- cacheForType = resourceType();
33
- cache.data.set(resourceType, cacheForType);
34
- }
35
- return cacheForType;
36
-}
37
-
38
-export const DefaultCacheDispatcher: CacheDispatcher = {
39
- getCacheSignal,
40
- getCacheForType,
41
-};
packages/react-reconciler/src/ReactFiberCacheComponent.new.js
deleted
-147
@@ -1,147 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {ReactContext} from 'shared/ReactTypes';
11
-import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
12
-
13
-import {enableCache} from 'shared/ReactFeatureFlags';
14
-import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
15
-
16
-import {pushProvider, popProvider} from './ReactFiberNewContext.new';
17
-import * as Scheduler from 'scheduler';
18
-
19
-// In environments without AbortController (e.g. tests)
20
-// replace it with a lightweight shim that only has the features we use.
21
-const AbortControllerLocal: typeof AbortController = enableCache
22
- ? typeof AbortController !== 'undefined'
23
- ? AbortController
24
- : (function AbortControllerShim() {
25
- const listeners = [];
26
- const signal = (this.signal = {
27
- aborted: false,
28
- addEventListener: (type, listener) => {
29
- listeners.push(listener);
30
- },
31
- });
32
-
33
- this.abort = () => {
34
- signal.aborted = true;
35
- listeners.forEach(listener => listener());
36
- };
37
- }: AbortController)
38
- : (null: any);
39
-
40
-export type Cache = {
41
- controller: AbortControllerLocal,
42
- data: Map<() => mixed, mixed>,
43
- refCount: number,
44
-};
45
-
46
-export type CacheComponentState = {
47
- +parent: Cache,
48
- +cache: Cache,
49
-};
50
-
51
-export type SpawnedCachePool = {
52
- +parent: Cache,
53
- +pool: Cache,
54
-};
55
-
56
-// Intentionally not named imports because Rollup would
57
-// use dynamic dispatch for CommonJS interop named imports.
58
-const {
59
- unstable_scheduleCallback: scheduleCallback,
60
- unstable_NormalPriority: NormalPriority,
61
-} = Scheduler;
62
-
63
-export const CacheContext: ReactContext<Cache> = enableCache
64
- ? {
65
- $$typeof: REACT_CONTEXT_TYPE,
66
- // We don't use Consumer/Provider for Cache components. So we'll cheat.
67
- Consumer: (null: any),
68
- Provider: (null: any),
69
- // We'll initialize these at the root.
70
- _currentValue: (null: any),
71
- _currentValue2: (null: any),
72
- _threadCount: 0,
73
- _defaultValue: (null: any),
74
- _globalName: (null: any),
75
- }
76
- : (null: any);
77
-
78
-if (__DEV__ && enableCache) {
79
- CacheContext._currentRenderer = null;
80
- CacheContext._currentRenderer2 = null;
81
-}
82
-
83
-// Creates a new empty Cache instance with a ref-count of 0. The caller is responsible
84
-// for retaining the cache once it is in use (retainCache), and releasing the cache
85
-// once it is no longer needed (releaseCache).
86
-export function createCache(): Cache {
87
- if (!enableCache) {
88
- return (null: any);
89
- }
90
- const cache: Cache = {
91
- controller: new AbortControllerLocal(),
92
- data: new Map(),
93
- refCount: 0,
94
- };
95
-
96
- return cache;
97
-}
98
-
99
-export function retainCache(cache: Cache) {
100
- if (!enableCache) {
101
- return;
102
- }
103
- if (__DEV__) {
104
- if (cache.controller.signal.aborted) {
105
- console.warn(
106
- 'A cache instance was retained after it was already freed. ' +
107
- 'This likely indicates a bug in React.',
108
- );
109
- }
110
- }
111
- cache.refCount++;
112
-}
113
-
114
-// Cleanup a cache instance, potentially freeing it if there are no more references
115
-export function releaseCache(cache: Cache) {
116
- if (!enableCache) {
117
- return;
118
- }
119
- cache.refCount--;
120
- if (__DEV__) {
121
- if (cache.refCount < 0) {
122
- console.warn(
123
- 'A cache instance was released after it was already freed. ' +
124
- 'This likely indicates a bug in React.',
125
- );
126
- }
127
- }
128
- if (cache.refCount === 0) {
129
- scheduleCallback(NormalPriority, () => {
130
- cache.controller.abort();
131
- });
132
- }
133
-}
134
-
135
-export function pushCacheProvider(workInProgress: Fiber, cache: Cache) {
136
- if (!enableCache) {
137
- return;
138
- }
139
- pushProvider(workInProgress, CacheContext, cache);
140
-}
141
-
142
-export function popCacheProvider(workInProgress: Fiber, cache: Cache) {
143
- if (!enableCache) {
144
- return;
145
- }
146
- popProvider(CacheContext, workInProgress);
147
-}
packages/react-reconciler/src/ReactFiberClassComponent.new.js
deleted
-1248
@@ -1,1248 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-import type {Lanes} from './ReactFiberLane.new';
12
-import type {UpdateQueue} from './ReactFiberClassUpdateQueue.new';
13
-import type {Flags} from './ReactFiberFlags';
14
-
15
-import {
16
- LayoutStatic,
17
- Update,
18
- Snapshot,
19
- MountLayoutDev,
20
-} from './ReactFiberFlags';
21
-import {
22
- debugRenderPhaseSideEffectsForStrictMode,
23
- disableLegacyContext,
24
- enableDebugTracing,
25
- enableSchedulingProfiler,
26
- warnAboutDeprecatedLifecycles,
27
- enableLazyContextPropagation,
28
-} from 'shared/ReactFeatureFlags';
29
-import ReactStrictModeWarnings from './ReactStrictModeWarnings.new';
30
-import {isMounted} from './ReactFiberTreeReflection';
31
-import {get as getInstance, set as setInstance} from 'shared/ReactInstanceMap';
32
-import shallowEqual from 'shared/shallowEqual';
33
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
34
-import getComponentNameFromType from 'shared/getComponentNameFromType';
35
-import assign from 'shared/assign';
36
-import isArray from 'shared/isArray';
37
-import {REACT_CONTEXT_TYPE, REACT_PROVIDER_TYPE} from 'shared/ReactSymbols';
38
-
39
-import {resolveDefaultProps} from './ReactFiberLazyComponent.new';
40
-import {
41
- DebugTracingMode,
42
- NoMode,
43
- StrictLegacyMode,
44
- StrictEffectsMode,
45
-} from './ReactTypeOfMode';
46
-
47
-import {
48
- enqueueUpdate,
49
- entangleTransitions,
50
- processUpdateQueue,
51
- checkHasForceUpdateAfterProcessing,
52
- resetHasForceUpdateBeforeProcessing,
53
- createUpdate,
54
- ReplaceState,
55
- ForceUpdate,
56
- initializeUpdateQueue,
57
- cloneUpdateQueue,
58
-} from './ReactFiberClassUpdateQueue.new';
59
-import {NoLanes} from './ReactFiberLane.new';
60
-import {
61
- cacheContext,
62
- getMaskedContext,
63
- getUnmaskedContext,
64
- hasContextChanged,
65
- emptyContextObject,
66
-} from './ReactFiberContext.new';
67
-import {readContext, checkIfContextChanged} from './ReactFiberNewContext.new';
68
-import {
69
- requestEventTime,
70
- requestUpdateLane,
71
- scheduleUpdateOnFiber,
72
-} from './ReactFiberWorkLoop.new';
73
-import {logForceUpdateScheduled, logStateUpdateScheduled} from './DebugTracing';
74
-import {
75
- markForceUpdateScheduled,
76
- markStateUpdateScheduled,
77
- setIsStrictModeForDevtools,
78
-} from './ReactFiberDevToolsHook.new';
79
-
80
-const fakeInternalInstance = {};
81
-
82
-let didWarnAboutStateAssignmentForComponent;
83
-let didWarnAboutUninitializedState;
84
-let didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
85
-let didWarnAboutLegacyLifecyclesAndDerivedState;
86
-let didWarnAboutUndefinedDerivedState;
87
-let warnOnUndefinedDerivedState;
88
-let warnOnInvalidCallback;
89
-let didWarnAboutDirectlyAssigningPropsToState;
90
-let didWarnAboutContextTypeAndContextTypes;
91
-let didWarnAboutInvalidateContextType;
92
-
93
-if (__DEV__) {
94
- didWarnAboutStateAssignmentForComponent = new Set();
95
- didWarnAboutUninitializedState = new Set();
96
- didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
97
- didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
98
- didWarnAboutDirectlyAssigningPropsToState = new Set();
99
- didWarnAboutUndefinedDerivedState = new Set();
100
- didWarnAboutContextTypeAndContextTypes = new Set();
101
- didWarnAboutInvalidateContextType = new Set();
102
-
103
- const didWarnOnInvalidCallback = new Set();
104
-
105
- warnOnInvalidCallback = function(callback: mixed, callerName: string) {
106
- if (callback === null || typeof callback === 'function') {
107
- return;
108
- }
109
- const key = callerName + '_' + (callback: any);
110
- if (!didWarnOnInvalidCallback.has(key)) {
111
- didWarnOnInvalidCallback.add(key);
112
- console.error(
113
- '%s(...): Expected the last optional `callback` argument to be a ' +
114
- 'function. Instead received: %s.',
115
- callerName,
116
- callback,
117
- );
118
- }
119
- };
120
-
121
- warnOnUndefinedDerivedState = function(type, partialState) {
122
- if (partialState === undefined) {
123
- const componentName = getComponentNameFromType(type) || 'Component';
124
- if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
125
- didWarnAboutUndefinedDerivedState.add(componentName);
126
- console.error(
127
- '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' +
128
- 'You have returned undefined.',
129
- componentName,
130
- );
131
- }
132
- }
133
- };
134
-
135
- // This is so gross but it's at least non-critical and can be removed if
136
- // it causes problems. This is meant to give a nicer error message for
137
- // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
138
- // ...)) which otherwise throws a "_processChildContext is not a function"
139
- // exception.
140
- Object.defineProperty(fakeInternalInstance, '_processChildContext', {
141
- enumerable: false,
142
- value: function() {
143
- throw new Error(
144
- '_processChildContext is not available in React 16+. This likely ' +
145
- 'means you have multiple copies of React and are attempting to nest ' +
146
- 'a React 15 tree inside a React 16 tree using ' +
147
- "unstable_renderSubtreeIntoContainer, which isn't supported. Try " +
148
- 'to make sure you have only one copy of React (and ideally, switch ' +
149
- 'to ReactDOM.createPortal).',
150
- );
151
- },
152
- });
153
- Object.freeze(fakeInternalInstance);
154
-}
155
-
156
-function applyDerivedStateFromProps(
157
- workInProgress: Fiber,
158
- ctor: any,
159
- getDerivedStateFromProps: (props: any, state: any) => any,
160
- nextProps: any,
161
-) {
162
- const prevState = workInProgress.memoizedState;
163
- let partialState = getDerivedStateFromProps(nextProps, prevState);
164
- if (__DEV__) {
165
- if (
166
- debugRenderPhaseSideEffectsForStrictMode &&
167
- workInProgress.mode & StrictLegacyMode
168
- ) {
169
- setIsStrictModeForDevtools(true);
170
- try {
171
- // Invoke the function an extra time to help detect side-effects.
172
- partialState = getDerivedStateFromProps(nextProps, prevState);
173
- } finally {
174
- setIsStrictModeForDevtools(false);
175
- }
176
- }
177
- warnOnUndefinedDerivedState(ctor, partialState);
178
- }
179
- // Merge the partial state and the previous state.
180
- const memoizedState =
181
- partialState === null || partialState === undefined
182
- ? prevState
183
- : assign({}, prevState, partialState);
184
- workInProgress.memoizedState = memoizedState;
185
-
186
- // Once the update queue is empty, persist the derived state onto the
187
- // base state.
188
- if (workInProgress.lanes === NoLanes) {
189
- // Queue is always non-null for classes
190
- const updateQueue: UpdateQueue<any> = (workInProgress.updateQueue: any);
191
- updateQueue.baseState = memoizedState;
192
- }
193
-}
194
-
195
-const classComponentUpdater = {
196
- isMounted,
197
- enqueueSetState(inst, payload, callback) {
198
- const fiber = getInstance(inst);
199
- const eventTime = requestEventTime();
200
- const lane = requestUpdateLane(fiber);
201
-
202
- const update = createUpdate(eventTime, lane);
203
- update.payload = payload;
204
- if (callback !== undefined && callback !== null) {
205
- if (__DEV__) {
206
- warnOnInvalidCallback(callback, 'setState');
207
- }
208
- update.callback = callback;
209
- }
210
-
211
- const root = enqueueUpdate(fiber, update, lane);
212
- if (root !== null) {
213
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
214
- entangleTransitions(root, fiber, lane);
215
- }
216
-
217
- if (__DEV__) {
218
- if (enableDebugTracing) {
219
- if (fiber.mode & DebugTracingMode) {
220
- const name = getComponentNameFromFiber(fiber) || 'Unknown';
221
- logStateUpdateScheduled(name, lane, payload);
222
- }
223
- }
224
- }
225
-
226
- if (enableSchedulingProfiler) {
227
- markStateUpdateScheduled(fiber, lane);
228
- }
229
- },
230
- enqueueReplaceState(inst, payload, callback) {
231
- const fiber = getInstance(inst);
232
- const eventTime = requestEventTime();
233
- const lane = requestUpdateLane(fiber);
234
-
235
- const update = createUpdate(eventTime, lane);
236
- update.tag = ReplaceState;
237
- update.payload = payload;
238
-
239
- if (callback !== undefined && callback !== null) {
240
- if (__DEV__) {
241
- warnOnInvalidCallback(callback, 'replaceState');
242
- }
243
- update.callback = callback;
244
- }
245
-
246
- const root = enqueueUpdate(fiber, update, lane);
247
- if (root !== null) {
248
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
249
- entangleTransitions(root, fiber, lane);
250
- }
251
-
252
- if (__DEV__) {
253
- if (enableDebugTracing) {
254
- if (fiber.mode & DebugTracingMode) {
255
- const name = getComponentNameFromFiber(fiber) || 'Unknown';
256
- logStateUpdateScheduled(name, lane, payload);
257
- }
258
- }
259
- }
260
-
261
- if (enableSchedulingProfiler) {
262
- markStateUpdateScheduled(fiber, lane);
263
- }
264
- },
265
- enqueueForceUpdate(inst, callback) {
266
- const fiber = getInstance(inst);
267
- const eventTime = requestEventTime();
268
- const lane = requestUpdateLane(fiber);
269
-
270
- const update = createUpdate(eventTime, lane);
271
- update.tag = ForceUpdate;
272
-
273
- if (callback !== undefined && callback !== null) {
274
- if (__DEV__) {
275
- warnOnInvalidCallback(callback, 'forceUpdate');
276
- }
277
- update.callback = callback;
278
- }
279
-
280
- const root = enqueueUpdate(fiber, update, lane);
281
- if (root !== null) {
282
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
283
- entangleTransitions(root, fiber, lane);
284
- }
285
-
286
- if (__DEV__) {
287
- if (enableDebugTracing) {
288
- if (fiber.mode & DebugTracingMode) {
289
- const name = getComponentNameFromFiber(fiber) || 'Unknown';
290
- logForceUpdateScheduled(name, lane);
291
- }
292
- }
293
- }
294
-
295
- if (enableSchedulingProfiler) {
296
- markForceUpdateScheduled(fiber, lane);
297
- }
298
- },
299
-};
300
-
301
-function checkShouldComponentUpdate(
302
- workInProgress,
303
- ctor,
304
- oldProps,
305
- newProps,
306
- oldState,
307
- newState,
308
- nextContext,
309
-) {
310
- const instance = workInProgress.stateNode;
311
- if (typeof instance.shouldComponentUpdate === 'function') {
312
- let shouldUpdate = instance.shouldComponentUpdate(
313
- newProps,
314
- newState,
315
- nextContext,
316
- );
317
- if (__DEV__) {
318
- if (
319
- debugRenderPhaseSideEffectsForStrictMode &&
320
- workInProgress.mode & StrictLegacyMode
321
- ) {
322
- setIsStrictModeForDevtools(true);
323
- try {
324
- // Invoke the function an extra time to help detect side-effects.
325
- shouldUpdate = instance.shouldComponentUpdate(
326
- newProps,
327
- newState,
328
- nextContext,
329
- );
330
- } finally {
331
- setIsStrictModeForDevtools(false);
332
- }
333
- }
334
- if (shouldUpdate === undefined) {
335
- console.error(
336
- '%s.shouldComponentUpdate(): Returned undefined instead of a ' +
337
- 'boolean value. Make sure to return true or false.',
338
- getComponentNameFromType(ctor) || 'Component',
339
- );
340
- }
341
- }
342
-
343
- return shouldUpdate;
344
- }
345
-
346
- if (ctor.prototype && ctor.prototype.isPureReactComponent) {
347
- return (
348
- !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
349
- );
350
- }
351
-
352
- return true;
353
-}
354
-
355
-function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
356
- const instance = workInProgress.stateNode;
357
- if (__DEV__) {
358
- const name = getComponentNameFromType(ctor) || 'Component';
359
- const renderPresent = instance.render;
360
-
361
- if (!renderPresent) {
362
- if (ctor.prototype && typeof ctor.prototype.render === 'function') {
363
- console.error(
364
- '%s(...): No `render` method found on the returned component ' +
365
- 'instance: did you accidentally return an object from the constructor?',
366
- name,
367
- );
368
- } else {
369
- console.error(
370
- '%s(...): No `render` method found on the returned component ' +
371
- 'instance: you may have forgotten to define `render`.',
372
- name,
373
- );
374
- }
375
- }
376
-
377
- if (
378
- instance.getInitialState &&
379
- !instance.getInitialState.isReactClassApproved &&
380
- !instance.state
381
- ) {
382
- console.error(
383
- 'getInitialState was defined on %s, a plain JavaScript class. ' +
384
- 'This is only supported for classes created using React.createClass. ' +
385
- 'Did you mean to define a state property instead?',
386
- name,
387
- );
388
- }
389
- if (
390
- instance.getDefaultProps &&
391
- !instance.getDefaultProps.isReactClassApproved
392
- ) {
393
- console.error(
394
- 'getDefaultProps was defined on %s, a plain JavaScript class. ' +
395
- 'This is only supported for classes created using React.createClass. ' +
396
- 'Use a static property to define defaultProps instead.',
397
- name,
398
- );
399
- }
400
- if (instance.propTypes) {
401
- console.error(
402
- 'propTypes was defined as an instance property on %s. Use a static ' +
403
- 'property to define propTypes instead.',
404
- name,
405
- );
406
- }
407
- if (instance.contextType) {
408
- console.error(
409
- 'contextType was defined as an instance property on %s. Use a static ' +
410
- 'property to define contextType instead.',
411
- name,
412
- );
413
- }
414
-
415
- if (disableLegacyContext) {
416
- if (ctor.childContextTypes) {
417
- console.error(
418
- '%s uses the legacy childContextTypes API which is no longer supported. ' +
419
- 'Use React.createContext() instead.',
420
- name,
421
- );
422
- }
423
- if (ctor.contextTypes) {
424
- console.error(
425
- '%s uses the legacy contextTypes API which is no longer supported. ' +
426
- 'Use React.createContext() with static contextType instead.',
427
- name,
428
- );
429
- }
430
- } else {
431
- if (instance.contextTypes) {
432
- console.error(
433
- 'contextTypes was defined as an instance property on %s. Use a static ' +
434
- 'property to define contextTypes instead.',
435
- name,
436
- );
437
- }
438
-
439
- if (
440
- ctor.contextType &&
441
- ctor.contextTypes &&
442
- !didWarnAboutContextTypeAndContextTypes.has(ctor)
443
- ) {
444
- didWarnAboutContextTypeAndContextTypes.add(ctor);
445
- console.error(
446
- '%s declares both contextTypes and contextType static properties. ' +
447
- 'The legacy contextTypes property will be ignored.',
448
- name,
449
- );
450
- }
451
- }
452
-
453
- if (typeof instance.componentShouldUpdate === 'function') {
454
- console.error(
455
- '%s has a method called ' +
456
- 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
457
- 'The name is phrased as a question because the function is ' +
458
- 'expected to return a value.',
459
- name,
460
- );
461
- }
462
- if (
463
- ctor.prototype &&
464
- ctor.prototype.isPureReactComponent &&
465
- typeof instance.shouldComponentUpdate !== 'undefined'
466
- ) {
467
- console.error(
468
- '%s has a method called shouldComponentUpdate(). ' +
469
- 'shouldComponentUpdate should not be used when extending React.PureComponent. ' +
470
- 'Please extend React.Component if shouldComponentUpdate is used.',
471
- getComponentNameFromType(ctor) || 'A pure component',
472
- );
473
- }
474
- if (typeof instance.componentDidUnmount === 'function') {
475
- console.error(
476
- '%s has a method called ' +
477
- 'componentDidUnmount(). But there is no such lifecycle method. ' +
478
- 'Did you mean componentWillUnmount()?',
479
- name,
480
- );
481
- }
482
- if (typeof instance.componentDidReceiveProps === 'function') {
483
- console.error(
484
- '%s has a method called ' +
485
- 'componentDidReceiveProps(). But there is no such lifecycle method. ' +
486
- 'If you meant to update the state in response to changing props, ' +
487
- 'use componentWillReceiveProps(). If you meant to fetch data or ' +
488
- 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().',
489
- name,
490
- );
491
- }
492
- if (typeof instance.componentWillRecieveProps === 'function') {
493
- console.error(
494
- '%s has a method called ' +
495
- 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
496
- name,
497
- );
498
- }
499
- if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
500
- console.error(
501
- '%s has a method called ' +
502
- 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?',
503
- name,
504
- );
505
- }
506
- const hasMutatedProps = instance.props !== newProps;
507
- if (instance.props !== undefined && hasMutatedProps) {
508
- console.error(
509
- '%s(...): When calling super() in `%s`, make sure to pass ' +
510
- "up the same props that your component's constructor was passed.",
511
- name,
512
- name,
513
- );
514
- }
515
- if (instance.defaultProps) {
516
- console.error(
517
- 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' +
518
- ' Instead, define defaultProps as a static property on %s.',
519
- name,
520
- name,
521
- );
522
- }
523
-
524
- if (
525
- typeof instance.getSnapshotBeforeUpdate === 'function' &&
526
- typeof instance.componentDidUpdate !== 'function' &&
527
- !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)
528
- ) {
529
- didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
530
- console.error(
531
- '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' +
532
- 'This component defines getSnapshotBeforeUpdate() only.',
533
- getComponentNameFromType(ctor),
534
- );
535
- }
536
-
537
- if (typeof instance.getDerivedStateFromProps === 'function') {
538
- console.error(
539
- '%s: getDerivedStateFromProps() is defined as an instance method ' +
540
- 'and will be ignored. Instead, declare it as a static method.',
541
- name,
542
- );
543
- }
544
- if (typeof instance.getDerivedStateFromError === 'function') {
545
- console.error(
546
- '%s: getDerivedStateFromError() is defined as an instance method ' +
547
- 'and will be ignored. Instead, declare it as a static method.',
548
- name,
549
- );
550
- }
551
- if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
552
- console.error(
553
- '%s: getSnapshotBeforeUpdate() is defined as a static method ' +
554
- 'and will be ignored. Instead, declare it as an instance method.',
555
- name,
556
- );
557
- }
558
- const state = instance.state;
559
- if (state && (typeof state !== 'object' || isArray(state))) {
560
- console.error('%s.state: must be set to an object or null', name);
561
- }
562
- if (
563
- typeof instance.getChildContext === 'function' &&
564
- typeof ctor.childContextTypes !== 'object'
565
- ) {
566
- console.error(
567
- '%s.getChildContext(): childContextTypes must be defined in order to ' +
568
- 'use getChildContext().',
569
- name,
570
- );
571
- }
572
- }
573
-}
574
-
575
-function adoptClassInstance(workInProgress: Fiber, instance: any): void {
576
- instance.updater = classComponentUpdater;
577
- workInProgress.stateNode = instance;
578
- // The instance needs access to the fiber so that it can schedule updates
579
- setInstance(instance, workInProgress);
580
- if (__DEV__) {
581
- instance._reactInternalInstance = fakeInternalInstance;
582
- }
583
-}
584
-
585
-function constructClassInstance(
586
- workInProgress: Fiber,
587
- ctor: any,
588
- props: any,
589
-): any {
590
- let isLegacyContextConsumer = false;
591
- let unmaskedContext = emptyContextObject;
592
- let context = emptyContextObject;
593
- const contextType = ctor.contextType;
594
-
595
- if (__DEV__) {
596
- if ('contextType' in ctor) {
597
- const isValid =
598
- // Allow null for conditional declaration
599
- contextType === null ||
600
- (contextType !== undefined &&
601
- contextType.$$typeof === REACT_CONTEXT_TYPE &&
602
- contextType._context === undefined); // Not a <Context.Consumer>
603
-
604
- if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
605
- didWarnAboutInvalidateContextType.add(ctor);
606
-
607
- let addendum = '';
608
- if (contextType === undefined) {
609
- addendum =
610
- ' However, it is set to undefined. ' +
611
- 'This can be caused by a typo or by mixing up named and default imports. ' +
612
- 'This can also happen due to a circular dependency, so ' +
613
- 'try moving the createContext() call to a separate file.';
614
- } else if (typeof contextType !== 'object') {
615
- addendum = ' However, it is set to a ' + typeof contextType + '.';
616
- } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
617
- addendum = ' Did you accidentally pass the Context.Provider instead?';
618
- } else if (contextType._context !== undefined) {
619
- // <Context.Consumer>
620
- addendum = ' Did you accidentally pass the Context.Consumer instead?';
621
- } else {
622
- addendum =
623
- ' However, it is set to an object with keys {' +
624
- Object.keys(contextType).join(', ') +
625
- '}.';
626
- }
627
- console.error(
628
- '%s defines an invalid contextType. ' +
629
- 'contextType should point to the Context object returned by React.createContext().%s',
630
- getComponentNameFromType(ctor) || 'Component',
631
- addendum,
632
- );
633
- }
634
- }
635
- }
636
-
637
- if (typeof contextType === 'object' && contextType !== null) {
638
- context = readContext((contextType: any));
639
- } else if (!disableLegacyContext) {
640
- unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
641
- const contextTypes = ctor.contextTypes;
642
- isLegacyContextConsumer =
643
- contextTypes !== null && contextTypes !== undefined;
644
- context = isLegacyContextConsumer
645
- ? getMaskedContext(workInProgress, unmaskedContext)
646
- : emptyContextObject;
647
- }
648
-
649
- let instance = new ctor(props, context);
650
- // Instantiate twice to help detect side-effects.
651
- if (__DEV__) {
652
- if (
653
- debugRenderPhaseSideEffectsForStrictMode &&
654
- workInProgress.mode & StrictLegacyMode
655
- ) {
656
- setIsStrictModeForDevtools(true);
657
- try {
658
- instance = new ctor(props, context); // eslint-disable-line no-new
659
- } finally {
660
- setIsStrictModeForDevtools(false);
661
- }
662
- }
663
- }
664
-
665
- const state = (workInProgress.memoizedState =
666
- instance.state !== null && instance.state !== undefined
667
- ? instance.state
668
- : null);
669
- adoptClassInstance(workInProgress, instance);
670
-
671
- if (__DEV__) {
672
- if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
673
- const componentName = getComponentNameFromType(ctor) || 'Component';
674
- if (!didWarnAboutUninitializedState.has(componentName)) {
675
- didWarnAboutUninitializedState.add(componentName);
676
- console.error(
677
- '`%s` uses `getDerivedStateFromProps` but its initial state is ' +
678
- '%s. This is not recommended. Instead, define the initial state by ' +
679
- 'assigning an object to `this.state` in the constructor of `%s`. ' +
680
- 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.',
681
- componentName,
682
- instance.state === null ? 'null' : 'undefined',
683
- componentName,
684
- );
685
- }
686
- }
687
-
688
- // If new component APIs are defined, "unsafe" lifecycles won't be called.
689
- // Warn about these lifecycles if they are present.
690
- // Don't warn about react-lifecycles-compat polyfilled methods though.
691
- if (
692
- typeof ctor.getDerivedStateFromProps === 'function' ||
693
- typeof instance.getSnapshotBeforeUpdate === 'function'
694
- ) {
695
- let foundWillMountName = null;
696
- let foundWillReceivePropsName = null;
697
- let foundWillUpdateName = null;
698
- if (
699
- typeof instance.componentWillMount === 'function' &&
700
- instance.componentWillMount.__suppressDeprecationWarning !== true
701
- ) {
702
- foundWillMountName = 'componentWillMount';
703
- } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
704
- foundWillMountName = 'UNSAFE_componentWillMount';
705
- }
706
- if (
707
- typeof instance.componentWillReceiveProps === 'function' &&
708
- instance.componentWillReceiveProps.__suppressDeprecationWarning !== true
709
- ) {
710
- foundWillReceivePropsName = 'componentWillReceiveProps';
711
- } else if (
712
- typeof instance.UNSAFE_componentWillReceiveProps === 'function'
713
- ) {
714
- foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
715
- }
716
- if (
717
- typeof instance.componentWillUpdate === 'function' &&
718
- instance.componentWillUpdate.__suppressDeprecationWarning !== true
719
- ) {
720
- foundWillUpdateName = 'componentWillUpdate';
721
- } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
722
- foundWillUpdateName = 'UNSAFE_componentWillUpdate';
723
- }
724
- if (
725
- foundWillMountName !== null ||
726
- foundWillReceivePropsName !== null ||
727
- foundWillUpdateName !== null
728
- ) {
729
- const componentName = getComponentNameFromType(ctor) || 'Component';
730
- const newApiName =
731
- typeof ctor.getDerivedStateFromProps === 'function'
732
- ? 'getDerivedStateFromProps()'
733
- : 'getSnapshotBeforeUpdate()';
734
- if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(componentName)) {
735
- didWarnAboutLegacyLifecyclesAndDerivedState.add(componentName);
736
- console.error(
737
- 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
738
- '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' +
739
- 'The above lifecycles should be removed. Learn more about this warning here:\n' +
740
- 'https://reactjs.org/link/unsafe-component-lifecycles',
741
- componentName,
742
- newApiName,
743
- foundWillMountName !== null ? `\n ${foundWillMountName}` : '',
744
- foundWillReceivePropsName !== null
745
- ? `\n ${foundWillReceivePropsName}`
746
- : '',
747
- foundWillUpdateName !== null ? `\n ${foundWillUpdateName}` : '',
748
- );
749
- }
750
- }
751
- }
752
- }
753
-
754
- // Cache unmasked context so we can avoid recreating masked context unless necessary.
755
- // ReactFiberContext usually updates this cache but can't for newly-created instances.
756
- if (isLegacyContextConsumer) {
757
- cacheContext(workInProgress, unmaskedContext, context);
758
- }
759
-
760
- return instance;
761
-}
762
-
763
-function callComponentWillMount(workInProgress, instance) {
764
- const oldState = instance.state;
765
-
766
- if (typeof instance.componentWillMount === 'function') {
767
- instance.componentWillMount();
768
- }
769
- if (typeof instance.UNSAFE_componentWillMount === 'function') {
770
- instance.UNSAFE_componentWillMount();
771
- }
772
-
773
- if (oldState !== instance.state) {
774
- if (__DEV__) {
775
- console.error(
776
- '%s.componentWillMount(): Assigning directly to this.state is ' +
777
- "deprecated (except inside a component's " +
778
- 'constructor). Use setState instead.',
779
- getComponentNameFromFiber(workInProgress) || 'Component',
780
- );
781
- }
782
- classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
783
- }
784
-}
785
-
786
-function callComponentWillReceiveProps(
787
- workInProgress,
788
- instance,
789
- newProps,
790
- nextContext,
791
-) {
792
- const oldState = instance.state;
793
- if (typeof instance.componentWillReceiveProps === 'function') {
794
- instance.componentWillReceiveProps(newProps, nextContext);
795
- }
796
- if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
797
- instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
798
- }
799
-
800
- if (instance.state !== oldState) {
801
- if (__DEV__) {
802
- const componentName =
803
- getComponentNameFromFiber(workInProgress) || 'Component';
804
- if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
805
- didWarnAboutStateAssignmentForComponent.add(componentName);
806
- console.error(
807
- '%s.componentWillReceiveProps(): Assigning directly to ' +
808
- "this.state is deprecated (except inside a component's " +
809
- 'constructor). Use setState instead.',
810
- componentName,
811
- );
812
- }
813
- }
814
- classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
815
- }
816
-}
817
-
818
-// Invokes the mount life-cycles on a previously never rendered instance.
819
-function mountClassInstance(
820
- workInProgress: Fiber,
821
- ctor: any,
822
- newProps: any,
823
- renderLanes: Lanes,
824
-): void {
825
- if (__DEV__) {
826
- checkClassInstance(workInProgress, ctor, newProps);
827
- }
828
-
829
- const instance = workInProgress.stateNode;
830
- instance.props = newProps;
831
- instance.state = workInProgress.memoizedState;
832
- instance.refs = {};
833
-
834
- initializeUpdateQueue(workInProgress);
835
-
836
- const contextType = ctor.contextType;
837
- if (typeof contextType === 'object' && contextType !== null) {
838
- instance.context = readContext(contextType);
839
- } else if (disableLegacyContext) {
840
- instance.context = emptyContextObject;
841
- } else {
842
- const unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
843
- instance.context = getMaskedContext(workInProgress, unmaskedContext);
844
- }
845
-
846
- if (__DEV__) {
847
- if (instance.state === newProps) {
848
- const componentName = getComponentNameFromType(ctor) || 'Component';
849
- if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
850
- didWarnAboutDirectlyAssigningPropsToState.add(componentName);
851
- console.error(
852
- '%s: It is not recommended to assign props directly to state ' +
853
- "because updates to props won't be reflected in state. " +
854
- 'In most cases, it is better to use props directly.',
855
- componentName,
856
- );
857
- }
858
- }
859
-
860
- if (workInProgress.mode & StrictLegacyMode) {
861
- ReactStrictModeWarnings.recordLegacyContextWarning(
862
- workInProgress,
863
- instance,
864
- );
865
- }
866
-
867
- if (warnAboutDeprecatedLifecycles) {
868
- ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(
869
- workInProgress,
870
- instance,
871
- );
872
- }
873
- }
874
-
875
- instance.state = workInProgress.memoizedState;
876
-
877
- const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
878
- if (typeof getDerivedStateFromProps === 'function') {
879
- applyDerivedStateFromProps(
880
- workInProgress,
881
- ctor,
882
- getDerivedStateFromProps,
883
- newProps,
884
- );
885
- instance.state = workInProgress.memoizedState;
886
- }
887
-
888
- // In order to support react-lifecycles-compat polyfilled components,
889
- // Unsafe lifecycles should not be invoked for components using the new APIs.
890
- if (
891
- typeof ctor.getDerivedStateFromProps !== 'function' &&
892
- typeof instance.getSnapshotBeforeUpdate !== 'function' &&
893
- (typeof instance.UNSAFE_componentWillMount === 'function' ||
894
- typeof instance.componentWillMount === 'function')
895
- ) {
896
- callComponentWillMount(workInProgress, instance);
897
- // If we had additional state updates during this life-cycle, let's
898
- // process them now.
899
- processUpdateQueue(workInProgress, newProps, instance, renderLanes);
900
- instance.state = workInProgress.memoizedState;
901
- }
902
-
903
- if (typeof instance.componentDidMount === 'function') {
904
- let fiberFlags: Flags = Update | LayoutStatic;
905
- if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
906
- fiberFlags |= MountLayoutDev;
907
- }
908
- workInProgress.flags |= fiberFlags;
909
- }
910
-}
911
-
912
-function resumeMountClassInstance(
913
- workInProgress: Fiber,
914
- ctor: any,
915
- newProps: any,
916
- renderLanes: Lanes,
917
-): boolean {
918
- const instance = workInProgress.stateNode;
919
-
920
- const oldProps = workInProgress.memoizedProps;
921
- instance.props = oldProps;
922
-
923
- const oldContext = instance.context;
924
- const contextType = ctor.contextType;
925
- let nextContext = emptyContextObject;
926
- if (typeof contextType === 'object' && contextType !== null) {
927
- nextContext = readContext(contextType);
928
- } else if (!disableLegacyContext) {
929
- const nextLegacyUnmaskedContext = getUnmaskedContext(
930
- workInProgress,
931
- ctor,
932
- true,
933
- );
934
- nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
935
- }
936
-
937
- const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
938
- const hasNewLifecycles =
939
- typeof getDerivedStateFromProps === 'function' ||
940
- typeof instance.getSnapshotBeforeUpdate === 'function';
941
-
942
- // Note: During these life-cycles, instance.props/instance.state are what
943
- // ever the previously attempted to render - not the "current". However,
944
- // during componentDidUpdate we pass the "current" props.
945
-
946
- // In order to support react-lifecycles-compat polyfilled components,
947
- // Unsafe lifecycles should not be invoked for components using the new APIs.
948
- if (
949
- !hasNewLifecycles &&
950
- (typeof instance.UNSAFE_componentWillReceiveProps === 'function' ||
951
- typeof instance.componentWillReceiveProps === 'function')
952
- ) {
953
- if (oldProps !== newProps || oldContext !== nextContext) {
954
- callComponentWillReceiveProps(
955
- workInProgress,
956
- instance,
957
- newProps,
958
- nextContext,
959
- );
960
- }
961
- }
962
-
963
- resetHasForceUpdateBeforeProcessing();
964
-
965
- const oldState = workInProgress.memoizedState;
966
- let newState = (instance.state = oldState);
967
- processUpdateQueue(workInProgress, newProps, instance, renderLanes);
968
- newState = workInProgress.memoizedState;
969
- if (
970
- oldProps === newProps &&
971
- oldState === newState &&
972
- !hasContextChanged() &&
973
- !checkHasForceUpdateAfterProcessing()
974
- ) {
975
- // If an update was already in progress, we should schedule an Update
976
- // effect even though we're bailing out, so that cWU/cDU are called.
977
- if (typeof instance.componentDidMount === 'function') {
978
- let fiberFlags: Flags = Update | LayoutStatic;
979
- if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
980
- fiberFlags |= MountLayoutDev;
981
- }
982
- workInProgress.flags |= fiberFlags;
983
- }
984
- return false;
985
- }
986
-
987
- if (typeof getDerivedStateFromProps === 'function') {
988
- applyDerivedStateFromProps(
989
- workInProgress,
990
- ctor,
991
- getDerivedStateFromProps,
992
- newProps,
993
- );
994
- newState = workInProgress.memoizedState;
995
- }
996
-
997
- const shouldUpdate =
998
- checkHasForceUpdateAfterProcessing() ||
999
- checkShouldComponentUpdate(
1000
- workInProgress,
1001
- ctor,
1002
- oldProps,
1003
- newProps,
1004
- oldState,
1005
- newState,
1006
- nextContext,
1007
- );
1008
-
1009
- if (shouldUpdate) {
1010
- // In order to support react-lifecycles-compat polyfilled components,
1011
- // Unsafe lifecycles should not be invoked for components using the new APIs.
1012
- if (
1013
- !hasNewLifecycles &&
1014
- (typeof instance.UNSAFE_componentWillMount === 'function' ||
1015
- typeof instance.componentWillMount === 'function')
1016
- ) {
1017
- if (typeof instance.componentWillMount === 'function') {
1018
- instance.componentWillMount();
1019
- }
1020
- if (typeof instance.UNSAFE_componentWillMount === 'function') {
1021
- instance.UNSAFE_componentWillMount();
1022
- }
1023
- }
1024
- if (typeof instance.componentDidMount === 'function') {
1025
- let fiberFlags: Flags = Update | LayoutStatic;
1026
- if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
1027
- fiberFlags |= MountLayoutDev;
1028
- }
1029
- workInProgress.flags |= fiberFlags;
1030
- }
1031
- } else {
1032
- // If an update was already in progress, we should schedule an Update
1033
- // effect even though we're bailing out, so that cWU/cDU are called.
1034
- if (typeof instance.componentDidMount === 'function') {
1035
- let fiberFlags: Flags = Update | LayoutStatic;
1036
- if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
1037
- fiberFlags |= MountLayoutDev;
1038
- }
1039
- workInProgress.flags |= fiberFlags;
1040
- }
1041
-
1042
- // If shouldComponentUpdate returned false, we should still update the
1043
- // memoized state to indicate that this work can be reused.
1044
- workInProgress.memoizedProps = newProps;
1045
- workInProgress.memoizedState = newState;
1046
- }
1047
-
1048
- // Update the existing instance's state, props, and context pointers even
1049
- // if shouldComponentUpdate returns false.
1050
- instance.props = newProps;
1051
- instance.state = newState;
1052
- instance.context = nextContext;
1053
-
1054
- return shouldUpdate;
1055
-}
1056
-
1057
-// Invokes the update life-cycles and returns false if it shouldn't rerender.
1058
-function updateClassInstance(
1059
- current: Fiber,
1060
- workInProgress: Fiber,
1061
- ctor: any,
1062
- newProps: any,
1063
- renderLanes: Lanes,
1064
-): boolean {
1065
- const instance = workInProgress.stateNode;
1066
-
1067
- cloneUpdateQueue(current, workInProgress);
1068
-
1069
- const unresolvedOldProps = workInProgress.memoizedProps;
1070
- const oldProps =
1071
- workInProgress.type === workInProgress.elementType
1072
- ? unresolvedOldProps
1073
- : resolveDefaultProps(workInProgress.type, unresolvedOldProps);
1074
- instance.props = oldProps;
1075
- const unresolvedNewProps = workInProgress.pendingProps;
1076
-
1077
- const oldContext = instance.context;
1078
- const contextType = ctor.contextType;
1079
- let nextContext = emptyContextObject;
1080
- if (typeof contextType === 'object' && contextType !== null) {
1081
- nextContext = readContext(contextType);
1082
- } else if (!disableLegacyContext) {
1083
- const nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
1084
- nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
1085
- }
1086
-
1087
- const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
1088
- const hasNewLifecycles =
1089
- typeof getDerivedStateFromProps === 'function' ||
1090
- typeof instance.getSnapshotBeforeUpdate === 'function';
1091
-
1092
- // Note: During these life-cycles, instance.props/instance.state are what
1093
- // ever the previously attempted to render - not the "current". However,
1094
- // during componentDidUpdate we pass the "current" props.
1095
-
1096
- // In order to support react-lifecycles-compat polyfilled components,
1097
- // Unsafe lifecycles should not be invoked for components using the new APIs.
1098
- if (
1099
- !hasNewLifecycles &&
1100
- (typeof instance.UNSAFE_componentWillReceiveProps === 'function' ||
1101
- typeof instance.componentWillReceiveProps === 'function')
1102
- ) {
1103
- if (
1104
- unresolvedOldProps !== unresolvedNewProps ||
1105
- oldContext !== nextContext
1106
- ) {
1107
- callComponentWillReceiveProps(
1108
- workInProgress,
1109
- instance,
1110
- newProps,
1111
- nextContext,
1112
- );
1113
- }
1114
- }
1115
-
1116
- resetHasForceUpdateBeforeProcessing();
1117
-
1118
- const oldState = workInProgress.memoizedState;
1119
- let newState = (instance.state = oldState);
1120
- processUpdateQueue(workInProgress, newProps, instance, renderLanes);
1121
- newState = workInProgress.memoizedState;
1122
-
1123
- if (
1124
- unresolvedOldProps === unresolvedNewProps &&
1125
- oldState === newState &&
1126
- !hasContextChanged() &&
1127
- !checkHasForceUpdateAfterProcessing() &&
1128
- !(
1129
- enableLazyContextPropagation &&
1130
- current !== null &&
1131
- current.dependencies !== null &&
1132
- checkIfContextChanged(current.dependencies)
1133
- )
1134
- ) {
1135
- // If an update was already in progress, we should schedule an Update
1136
- // effect even though we're bailing out, so that cWU/cDU are called.
1137
- if (typeof instance.componentDidUpdate === 'function') {
1138
- if (
1139
- unresolvedOldProps !== current.memoizedProps ||
1140
- oldState !== current.memoizedState
1141
- ) {
1142
- workInProgress.flags |= Update;
1143
- }
1144
- }
1145
- if (typeof instance.getSnapshotBeforeUpdate === 'function') {
1146
- if (
1147
- unresolvedOldProps !== current.memoizedProps ||
1148
- oldState !== current.memoizedState
1149
- ) {
1150
- workInProgress.flags |= Snapshot;
1151
- }
1152
- }
1153
- return false;
1154
- }
1155
-
1156
- if (typeof getDerivedStateFromProps === 'function') {
1157
- applyDerivedStateFromProps(
1158
- workInProgress,
1159
- ctor,
1160
- getDerivedStateFromProps,
1161
- newProps,
1162
- );
1163
- newState = workInProgress.memoizedState;
1164
- }
1165
-
1166
- const shouldUpdate =
1167
- checkHasForceUpdateAfterProcessing() ||
1168
- checkShouldComponentUpdate(
1169
- workInProgress,
1170
- ctor,
1171
- oldProps,
1172
- newProps,
1173
- oldState,
1174
- newState,
1175
- nextContext,
1176
- ) ||
1177
- // TODO: In some cases, we'll end up checking if context has changed twice,
1178
- // both before and after `shouldComponentUpdate` has been called. Not ideal,
1179
- // but I'm loath to refactor this function. This only happens for memoized
1180
- // components so it's not that common.
1181
- (enableLazyContextPropagation &&
1182
- current !== null &&
1183
- current.dependencies !== null &&
1184
- checkIfContextChanged(current.dependencies));
1185
-
1186
- if (shouldUpdate) {
1187
- // In order to support react-lifecycles-compat polyfilled components,
1188
- // Unsafe lifecycles should not be invoked for components using the new APIs.
1189
- if (
1190
- !hasNewLifecycles &&
1191
- (typeof instance.UNSAFE_componentWillUpdate === 'function' ||
1192
- typeof instance.componentWillUpdate === 'function')
1193
- ) {
1194
- if (typeof instance.componentWillUpdate === 'function') {
1195
- instance.componentWillUpdate(newProps, newState, nextContext);
1196
- }
1197
- if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
1198
- instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
1199
- }
1200
- }
1201
- if (typeof instance.componentDidUpdate === 'function') {
1202
- workInProgress.flags |= Update;
1203
- }
1204
- if (typeof instance.getSnapshotBeforeUpdate === 'function') {
1205
- workInProgress.flags |= Snapshot;
1206
- }
1207
- } else {
1208
- // If an update was already in progress, we should schedule an Update
1209
- // effect even though we're bailing out, so that cWU/cDU are called.
1210
- if (typeof instance.componentDidUpdate === 'function') {
1211
- if (
1212
- unresolvedOldProps !== current.memoizedProps ||
1213
- oldState !== current.memoizedState
1214
- ) {
1215
- workInProgress.flags |= Update;
1216
- }
1217
- }
1218
- if (typeof instance.getSnapshotBeforeUpdate === 'function') {
1219
- if (
1220
- unresolvedOldProps !== current.memoizedProps ||
1221
- oldState !== current.memoizedState
1222
- ) {
1223
- workInProgress.flags |= Snapshot;
1224
- }
1225
- }
1226
-
1227
- // If shouldComponentUpdate returned false, we should still update the
1228
- // memoized props/state to indicate that this work can be reused.
1229
- workInProgress.memoizedProps = newProps;
1230
- workInProgress.memoizedState = newState;
1231
- }
1232
-
1233
- // Update the existing instance's state, props, and context pointers even
1234
- // if shouldComponentUpdate returns false.
1235
- instance.props = newProps;
1236
- instance.state = newState;
1237
- instance.context = nextContext;
1238
-
1239
- return shouldUpdate;
1240
-}
1241
-
1242
-export {
1243
- adoptClassInstance,
1244
- constructClassInstance,
1245
- mountClassInstance,
1246
- resumeMountClassInstance,
1247
- updateClassInstance,
1248
-};
packages/react-reconciler/src/ReactFiberClassUpdateQueue.new.js
deleted
-742
@@ -1,742 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-// UpdateQueue is a linked list of prioritized updates.
11
-//
12
-// Like fibers, update queues come in pairs: a current queue, which represents
13
-// the visible state of the screen, and a work-in-progress queue, which can be
14
-// mutated and processed asynchronously before it is committed — a form of
15
-// double buffering. If a work-in-progress render is discarded before finishing,
16
-// we create a new work-in-progress by cloning the current queue.
17
-//
18
-// Both queues share a persistent, singly-linked list structure. To schedule an
19
-// update, we append it to the end of both queues. Each queue maintains a
20
-// pointer to first update in the persistent list that hasn't been processed.
21
-// The work-in-progress pointer always has a position equal to or greater than
22
-// the current queue, since we always work on that one. The current queue's
23
-// pointer is only updated during the commit phase, when we swap in the
24
-// work-in-progress.
25
-//
26
-// For example:
27
-//
28
-// Current pointer: A - B - C - D - E - F
29
-// Work-in-progress pointer: D - E - F
30
-// ^
31
-// The work-in-progress queue has
32
-// processed more updates than current.
33
-//
34
-// The reason we append to both queues is because otherwise we might drop
35
-// updates without ever processing them. For example, if we only add updates to
36
-// the work-in-progress queue, some updates could be lost whenever a work-in
37
-// -progress render restarts by cloning from current. Similarly, if we only add
38
-// updates to the current queue, the updates will be lost whenever an already
39
-// in-progress queue commits and swaps with the current queue. However, by
40
-// adding to both queues, we guarantee that the update will be part of the next
41
-// work-in-progress. (And because the work-in-progress queue becomes the
42
-// current queue once it commits, there's no danger of applying the same
43
-// update twice.)
44
-//
45
-// Prioritization
46
-// --------------
47
-//
48
-// Updates are not sorted by priority, but by insertion; new updates are always
49
-// appended to the end of the list.
50
-//
51
-// The priority is still important, though. When processing the update queue
52
-// during the render phase, only the updates with sufficient priority are
53
-// included in the result. If we skip an update because it has insufficient
54
-// priority, it remains in the queue to be processed later, during a lower
55
-// priority render. Crucially, all updates subsequent to a skipped update also
56
-// remain in the queue *regardless of their priority*. That means high priority
57
-// updates are sometimes processed twice, at two separate priorities. We also
58
-// keep track of a base state, that represents the state before the first
59
-// update in the queue is applied.
60
-//
61
-// For example:
62
-//
63
-// Given a base state of '', and the following queue of updates
64
-//
65
-// A1 - B2 - C1 - D2
66
-//
67
-// where the number indicates the priority, and the update is applied to the
68
-// previous state by appending a letter, React will process these updates as
69
-// two separate renders, one per distinct priority level:
70
-//
71
-// First render, at priority 1:
72
-// Base state: ''
73
-// Updates: [A1, C1]
74
-// Result state: 'AC'
75
-//
76
-// Second render, at priority 2:
77
-// Base state: 'A' <- The base state does not include C1,
78
-// because B2 was skipped.
79
-// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
80
-// Result state: 'ABCD'
81
-//
82
-// Because we process updates in insertion order, and rebase high priority
83
-// updates when preceding updates are skipped, the final result is deterministic
84
-// regardless of priority. Intermediate state may vary according to system
85
-// resources, but the final state is always the same.
86
-
87
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
88
-import type {Lanes, Lane} from './ReactFiberLane.new';
89
-
90
-import {
91
- NoLane,
92
- NoLanes,
93
- OffscreenLane,
94
- isSubsetOfLanes,
95
- mergeLanes,
96
- removeLanes,
97
- isTransitionLane,
98
- intersectLanes,
99
- markRootEntangled,
100
-} from './ReactFiberLane.new';
101
-import {
102
- enterDisallowedContextReadInDEV,
103
- exitDisallowedContextReadInDEV,
104
-} from './ReactFiberNewContext.new';
105
-import {
106
- Callback,
107
- Visibility,
108
- ShouldCapture,
109
- DidCapture,
110
-} from './ReactFiberFlags';
111
-
112
-import {debugRenderPhaseSideEffectsForStrictMode} from 'shared/ReactFeatureFlags';
113
-
114
-import {StrictLegacyMode} from './ReactTypeOfMode';
115
-import {
116
- markSkippedUpdateLanes,
117
- isUnsafeClassRenderPhaseUpdate,
118
- getWorkInProgressRootRenderLanes,
119
-} from './ReactFiberWorkLoop.new';
120
-import {
121
- enqueueConcurrentClassUpdate,
122
- unsafe_markUpdateLaneFromFiberToRoot,
123
-} from './ReactFiberConcurrentUpdates.new';
124
-import {setIsStrictModeForDevtools} from './ReactFiberDevToolsHook.new';
125
-
126
-import assign from 'shared/assign';
127
-
128
-export type Update<State> = {
129
- // TODO: Temporary field. Will remove this by storing a map of
130
- // transition -> event time on the root.
131
- eventTime: number,
132
- lane: Lane,
133
-
134
- tag: 0 | 1 | 2 | 3,
135
- payload: any,
136
- callback: (() => mixed) | null,
137
-
138
- next: Update<State> | null,
139
-};
140
-
141
-export type SharedQueue<State> = {
142
- pending: Update<State> | null,
143
- lanes: Lanes,
144
- hiddenCallbacks: Array<() => mixed> | null,
145
-};
146
-
147
-export type UpdateQueue<State> = {
148
- baseState: State,
149
- firstBaseUpdate: Update<State> | null,
150
- lastBaseUpdate: Update<State> | null,
151
- shared: SharedQueue<State>,
152
- callbacks: Array<() => mixed> | null,
153
-};
154
-
155
-export const UpdateState = 0;
156
-export const ReplaceState = 1;
157
-export const ForceUpdate = 2;
158
-export const CaptureUpdate = 3;
159
-
160
-// Global state that is reset at the beginning of calling `processUpdateQueue`.
161
-// It should only be read right after calling `processUpdateQueue`, via
162
-// `checkHasForceUpdateAfterProcessing`.
163
-let hasForceUpdate = false;
164
-
165
-let didWarnUpdateInsideUpdate;
166
-let currentlyProcessingQueue;
167
-export let resetCurrentlyProcessingQueue: () => void;
168
-if (__DEV__) {
169
- didWarnUpdateInsideUpdate = false;
170
- currentlyProcessingQueue = null;
171
- resetCurrentlyProcessingQueue = () => {
172
- currentlyProcessingQueue = null;
173
- };
174
-}
175
-
176
-export function initializeUpdateQueue<State>(fiber: Fiber): void {
177
- const queue: UpdateQueue<State> = {
178
- baseState: fiber.memoizedState,
179
- firstBaseUpdate: null,
180
- lastBaseUpdate: null,
181
- shared: {
182
- pending: null,
183
- lanes: NoLanes,
184
- hiddenCallbacks: null,
185
- },
186
- callbacks: null,
187
- };
188
- fiber.updateQueue = queue;
189
-}
190
-
191
-export function cloneUpdateQueue<State>(
192
- current: Fiber,
193
- workInProgress: Fiber,
194
-): void {
195
- // Clone the update queue from current. Unless it's already a clone.
196
- const queue: UpdateQueue<State> = (workInProgress.updateQueue: any);
197
- const currentQueue: UpdateQueue<State> = (current.updateQueue: any);
198
- if (queue === currentQueue) {
199
- const clone: UpdateQueue<State> = {
200
- baseState: currentQueue.baseState,
201
- firstBaseUpdate: currentQueue.firstBaseUpdate,
202
- lastBaseUpdate: currentQueue.lastBaseUpdate,
203
- shared: currentQueue.shared,
204
- callbacks: null,
205
- };
206
- workInProgress.updateQueue = clone;
207
- }
208
-}
209
-
210
-export function createUpdate(eventTime: number, lane: Lane): Update<mixed> {
211
- const update: Update<mixed> = {
212
- eventTime,
213
- lane,
214
-
215
- tag: UpdateState,
216
- payload: null,
217
- callback: null,
218
-
219
- next: null,
220
- };
221
- return update;
222
-}
223
-
224
-export function enqueueUpdate<State>(
225
- fiber: Fiber,
226
- update: Update<State>,
227
- lane: Lane,
228
-): FiberRoot | null {
229
- const updateQueue = fiber.updateQueue;
230
- if (updateQueue === null) {
231
- // Only occurs if the fiber has been unmounted.
232
- return null;
233
- }
234
-
235
- const sharedQueue: SharedQueue<State> = (updateQueue: any).shared;
236
-
237
- if (__DEV__) {
238
- if (
239
- currentlyProcessingQueue === sharedQueue &&
240
- !didWarnUpdateInsideUpdate
241
- ) {
242
- console.error(
243
- 'An update (setState, replaceState, or forceUpdate) was scheduled ' +
244
- 'from inside an update function. Update functions should be pure, ' +
245
- 'with zero side-effects. Consider using componentDidUpdate or a ' +
246
- 'callback.',
247
- );
248
- didWarnUpdateInsideUpdate = true;
249
- }
250
- }
251
-
252
- if (isUnsafeClassRenderPhaseUpdate(fiber)) {
253
- // This is an unsafe render phase update. Add directly to the update
254
- // queue so we can process it immediately during the current render.
255
- const pending = sharedQueue.pending;
256
- if (pending === null) {
257
- // This is the first update. Create a circular list.
258
- update.next = update;
259
- } else {
260
- update.next = pending.next;
261
- pending.next = update;
262
- }
263
- sharedQueue.pending = update;
264
-
265
- // Update the childLanes even though we're most likely already rendering
266
- // this fiber. This is for backwards compatibility in the case where you
267
- // update a different component during render phase than the one that is
268
- // currently renderings (a pattern that is accompanied by a warning).
269
- return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane);
270
- } else {
271
- return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane);
272
- }
273
-}
274
-
275
-export function entangleTransitions(root: FiberRoot, fiber: Fiber, lane: Lane) {
276
- const updateQueue = fiber.updateQueue;
277
- if (updateQueue === null) {
278
- // Only occurs if the fiber has been unmounted.
279
- return;
280
- }
281
-
282
- const sharedQueue: SharedQueue<mixed> = (updateQueue: any).shared;
283
- if (isTransitionLane(lane)) {
284
- let queueLanes = sharedQueue.lanes;
285
-
286
- // If any entangled lanes are no longer pending on the root, then they must
287
- // have finished. We can remove them from the shared queue, which represents
288
- // a superset of the actually pending lanes. In some cases we may entangle
289
- // more than we need to, but that's OK. In fact it's worse if we *don't*
290
- // entangle when we should.
291
- queueLanes = intersectLanes(queueLanes, root.pendingLanes);
292
-
293
- // Entangle the new transition lane with the other transition lanes.
294
- const newQueueLanes = mergeLanes(queueLanes, lane);
295
- sharedQueue.lanes = newQueueLanes;
296
- // Even if queue.lanes already include lane, we don't know for certain if
297
- // the lane finished since the last time we entangled it. So we need to
298
- // entangle it again, just to be sure.
299
- markRootEntangled(root, newQueueLanes);
300
- }
301
-}
302
-
303
-export function enqueueCapturedUpdate<State>(
304
- workInProgress: Fiber,
305
- capturedUpdate: Update<State>,
306
-) {
307
- // Captured updates are updates that are thrown by a child during the render
308
- // phase. They should be discarded if the render is aborted. Therefore,
309
- // we should only put them on the work-in-progress queue, not the current one.
310
- let queue: UpdateQueue<State> = (workInProgress.updateQueue: any);
311
-
312
- // Check if the work-in-progress queue is a clone.
313
- const current = workInProgress.alternate;
314
- if (current !== null) {
315
- const currentQueue: UpdateQueue<State> = (current.updateQueue: any);
316
- if (queue === currentQueue) {
317
- // The work-in-progress queue is the same as current. This happens when
318
- // we bail out on a parent fiber that then captures an error thrown by
319
- // a child. Since we want to append the update only to the work-in
320
- // -progress queue, we need to clone the updates. We usually clone during
321
- // processUpdateQueue, but that didn't happen in this case because we
322
- // skipped over the parent when we bailed out.
323
- let newFirst = null;
324
- let newLast = null;
325
- const firstBaseUpdate = queue.firstBaseUpdate;
326
- if (firstBaseUpdate !== null) {
327
- // Loop through the updates and clone them.
328
- let update: Update<State> = firstBaseUpdate;
329
- do {
330
- const clone: Update<State> = {
331
- eventTime: update.eventTime,
332
- lane: update.lane,
333
-
334
- tag: update.tag,
335
- payload: update.payload,
336
- // When this update is rebased, we should not fire its
337
- // callback again.
338
- callback: null,
339
-
340
- next: null,
341
- };
342
- if (newLast === null) {
343
- newFirst = newLast = clone;
344
- } else {
345
- newLast.next = clone;
346
- newLast = clone;
347
- }
348
- // $FlowFixMe[incompatible-type] we bail out when we get a null
349
- update = update.next;
350
- } while (update !== null);
351
-
352
- // Append the captured update the end of the cloned list.
353
- if (newLast === null) {
354
- newFirst = newLast = capturedUpdate;
355
- } else {
356
- newLast.next = capturedUpdate;
357
- newLast = capturedUpdate;
358
- }
359
- } else {
360
- // There are no base updates.
361
- newFirst = newLast = capturedUpdate;
362
- }
363
- queue = {
364
- baseState: currentQueue.baseState,
365
- firstBaseUpdate: newFirst,
366
- lastBaseUpdate: newLast,
367
- shared: currentQueue.shared,
368
- callbacks: currentQueue.callbacks,
369
- };
370
- workInProgress.updateQueue = queue;
371
- return;
372
- }
373
- }
374
-
375
- // Append the update to the end of the list.
376
- const lastBaseUpdate = queue.lastBaseUpdate;
377
- if (lastBaseUpdate === null) {
378
- queue.firstBaseUpdate = capturedUpdate;
379
- } else {
380
- lastBaseUpdate.next = capturedUpdate;
381
- }
382
- queue.lastBaseUpdate = capturedUpdate;
383
-}
384
-
385
-function getStateFromUpdate<State>(
386
- workInProgress: Fiber,
387
- queue: UpdateQueue<State>,
388
- update: Update<State>,
389
- prevState: State,
390
- nextProps: any,
391
- instance: any,
392
-): any {
393
- switch (update.tag) {
394
- case ReplaceState: {
395
- const payload = update.payload;
396
- if (typeof payload === 'function') {
397
- // Updater function
398
- if (__DEV__) {
399
- enterDisallowedContextReadInDEV();
400
- }
401
- const nextState = payload.call(instance, prevState, nextProps);
402
- if (__DEV__) {
403
- if (
404
- debugRenderPhaseSideEffectsForStrictMode &&
405
- workInProgress.mode & StrictLegacyMode
406
- ) {
407
- setIsStrictModeForDevtools(true);
408
- try {
409
- payload.call(instance, prevState, nextProps);
410
- } finally {
411
- setIsStrictModeForDevtools(false);
412
- }
413
- }
414
- exitDisallowedContextReadInDEV();
415
- }
416
- return nextState;
417
- }
418
- // State object
419
- return payload;
420
- }
421
- case CaptureUpdate: {
422
- workInProgress.flags =
423
- (workInProgress.flags & ~ShouldCapture) | DidCapture;
424
- }
425
- // Intentional fallthrough
426
- case UpdateState: {
427
- const payload = update.payload;
428
- let partialState;
429
- if (typeof payload === 'function') {
430
- // Updater function
431
- if (__DEV__) {
432
- enterDisallowedContextReadInDEV();
433
- }
434
- partialState = payload.call(instance, prevState, nextProps);
435
- if (__DEV__) {
436
- if (
437
- debugRenderPhaseSideEffectsForStrictMode &&
438
- workInProgress.mode & StrictLegacyMode
439
- ) {
440
- setIsStrictModeForDevtools(true);
441
- try {
442
- payload.call(instance, prevState, nextProps);
443
- } finally {
444
- setIsStrictModeForDevtools(false);
445
- }
446
- }
447
- exitDisallowedContextReadInDEV();
448
- }
449
- } else {
450
- // Partial state object
451
- partialState = payload;
452
- }
453
- if (partialState === null || partialState === undefined) {
454
- // Null and undefined are treated as no-ops.
455
- return prevState;
456
- }
457
- // Merge the partial state and the previous state.
458
- return assign({}, prevState, partialState);
459
- }
460
- case ForceUpdate: {
461
- hasForceUpdate = true;
462
- return prevState;
463
- }
464
- }
465
- return prevState;
466
-}
467
-
468
-export function processUpdateQueue<State>(
469
- workInProgress: Fiber,
470
- props: any,
471
- instance: any,
472
- renderLanes: Lanes,
473
-): void {
474
- // This is always non-null on a ClassComponent or HostRoot
475
- const queue: UpdateQueue<State> = (workInProgress.updateQueue: any);
476
-
477
- hasForceUpdate = false;
478
-
479
- if (__DEV__) {
480
- // $FlowFixMe[escaped-generic] discovered when updating Flow
481
- currentlyProcessingQueue = queue.shared;
482
- }
483
-
484
- let firstBaseUpdate = queue.firstBaseUpdate;
485
- let lastBaseUpdate = queue.lastBaseUpdate;
486
-
487
- // Check if there are pending updates. If so, transfer them to the base queue.
488
- let pendingQueue = queue.shared.pending;
489
- if (pendingQueue !== null) {
490
- queue.shared.pending = null;
491
-
492
- // The pending queue is circular. Disconnect the pointer between first
493
- // and last so that it's non-circular.
494
- const lastPendingUpdate = pendingQueue;
495
- const firstPendingUpdate = lastPendingUpdate.next;
496
- lastPendingUpdate.next = null;
497
- // Append pending updates to base queue
498
- if (lastBaseUpdate === null) {
499
- firstBaseUpdate = firstPendingUpdate;
500
- } else {
501
- lastBaseUpdate.next = firstPendingUpdate;
502
- }
503
- lastBaseUpdate = lastPendingUpdate;
504
-
505
- // If there's a current queue, and it's different from the base queue, then
506
- // we need to transfer the updates to that queue, too. Because the base
507
- // queue is a singly-linked list with no cycles, we can append to both
508
- // lists and take advantage of structural sharing.
509
- // TODO: Pass `current` as argument
510
- const current = workInProgress.alternate;
511
- if (current !== null) {
512
- // This is always non-null on a ClassComponent or HostRoot
513
- const currentQueue: UpdateQueue<State> = (current.updateQueue: any);
514
- const currentLastBaseUpdate = currentQueue.lastBaseUpdate;
515
- if (currentLastBaseUpdate !== lastBaseUpdate) {
516
- if (currentLastBaseUpdate === null) {
517
- currentQueue.firstBaseUpdate = firstPendingUpdate;
518
- } else {
519
- currentLastBaseUpdate.next = firstPendingUpdate;
520
- }
521
- currentQueue.lastBaseUpdate = lastPendingUpdate;
522
- }
523
- }
524
- }
525
-
526
- // These values may change as we process the queue.
527
- if (firstBaseUpdate !== null) {
528
- // Iterate through the list of updates to compute the result.
529
- let newState = queue.baseState;
530
- // TODO: Don't need to accumulate this. Instead, we can remove renderLanes
531
- // from the original lanes.
532
- let newLanes = NoLanes;
533
-
534
- let newBaseState = null;
535
- let newFirstBaseUpdate = null;
536
- let newLastBaseUpdate = null;
537
-
538
- let update: Update<State> = firstBaseUpdate;
539
- do {
540
- // TODO: Don't need this field anymore
541
- const updateEventTime = update.eventTime;
542
-
543
- // An extra OffscreenLane bit is added to updates that were made to
544
- // a hidden tree, so that we can distinguish them from updates that were
545
- // already there when the tree was hidden.
546
- const updateLane = removeLanes(update.lane, OffscreenLane);
547
- const isHiddenUpdate = updateLane !== update.lane;
548
-
549
- // Check if this update was made while the tree was hidden. If so, then
550
- // it's not a "base" update and we should disregard the extra base lanes
551
- // that were added to renderLanes when we entered the Offscreen tree.
552
- const shouldSkipUpdate = isHiddenUpdate
553
- ? !isSubsetOfLanes(getWorkInProgressRootRenderLanes(), updateLane)
554
- : !isSubsetOfLanes(renderLanes, updateLane);
555
-
556
- if (shouldSkipUpdate) {
557
- // Priority is insufficient. Skip this update. If this is the first
558
- // skipped update, the previous update/state is the new base
559
- // update/state.
560
- const clone: Update<State> = {
561
- eventTime: updateEventTime,
562
- lane: updateLane,
563
-
564
- tag: update.tag,
565
- payload: update.payload,
566
- callback: update.callback,
567
-
568
- next: null,
569
- };
570
- if (newLastBaseUpdate === null) {
571
- newFirstBaseUpdate = newLastBaseUpdate = clone;
572
- newBaseState = newState;
573
- } else {
574
- newLastBaseUpdate = newLastBaseUpdate.next = clone;
575
- }
576
- // Update the remaining priority in the queue.
577
- newLanes = mergeLanes(newLanes, updateLane);
578
- } else {
579
- // This update does have sufficient priority.
580
-
581
- if (newLastBaseUpdate !== null) {
582
- const clone: Update<State> = {
583
- eventTime: updateEventTime,
584
- // This update is going to be committed so we never want uncommit
585
- // it. Using NoLane works because 0 is a subset of all bitmasks, so
586
- // this will never be skipped by the check above.
587
- lane: NoLane,
588
-
589
- tag: update.tag,
590
- payload: update.payload,
591
-
592
- // When this update is rebased, we should not fire its
593
- // callback again.
594
- callback: null,
595
-
596
- next: null,
597
- };
598
- newLastBaseUpdate = newLastBaseUpdate.next = clone;
599
- }
600
-
601
- // Process this update.
602
- newState = getStateFromUpdate(
603
- workInProgress,
604
- queue,
605
- update,
606
- newState,
607
- props,
608
- instance,
609
- );
610
- const callback = update.callback;
611
- if (callback !== null) {
612
- workInProgress.flags |= Callback;
613
- if (isHiddenUpdate) {
614
- workInProgress.flags |= Visibility;
615
- }
616
- const callbacks = queue.callbacks;
617
- if (callbacks === null) {
618
- queue.callbacks = [callback];
619
- } else {
620
- callbacks.push(callback);
621
- }
622
- }
623
- }
624
- // $FlowFixMe[incompatible-type] we bail out when we get a null
625
- update = update.next;
626
- if (update === null) {
627
- pendingQueue = queue.shared.pending;
628
- if (pendingQueue === null) {
629
- break;
630
- } else {
631
- // An update was scheduled from inside a reducer. Add the new
632
- // pending updates to the end of the list and keep processing.
633
- const lastPendingUpdate = pendingQueue;
634
- // Intentionally unsound. Pending updates form a circular list, but we
635
- // unravel them when transferring them to the base queue.
636
- const firstPendingUpdate = ((lastPendingUpdate.next: any): Update<State>);
637
- lastPendingUpdate.next = null;
638
- update = firstPendingUpdate;
639
- queue.lastBaseUpdate = lastPendingUpdate;
640
- queue.shared.pending = null;
641
- }
642
- }
643
- } while (true);
644
-
645
- if (newLastBaseUpdate === null) {
646
- newBaseState = newState;
647
- }
648
-
649
- queue.baseState = ((newBaseState: any): State);
650
- queue.firstBaseUpdate = newFirstBaseUpdate;
651
- queue.lastBaseUpdate = newLastBaseUpdate;
652
-
653
- if (firstBaseUpdate === null) {
654
- // `queue.lanes` is used for entangling transitions. We can set it back to
655
- // zero once the queue is empty.
656
- queue.shared.lanes = NoLanes;
657
- }
658
-
659
- // Set the remaining expiration time to be whatever is remaining in the queue.
660
- // This should be fine because the only two other things that contribute to
661
- // expiration time are props and context. We're already in the middle of the
662
- // begin phase by the time we start processing the queue, so we've already
663
- // dealt with the props. Context in components that specify
664
- // shouldComponentUpdate is tricky; but we'll have to account for
665
- // that regardless.
666
- markSkippedUpdateLanes(newLanes);
667
- workInProgress.lanes = newLanes;
668
- workInProgress.memoizedState = newState;
669
- }
670
-
671
- if (__DEV__) {
672
- currentlyProcessingQueue = null;
673
- }
674
-}
675
-
676
-function callCallback(callback, context) {
677
- if (typeof callback !== 'function') {
678
- throw new Error(
679
- 'Invalid argument passed as callback. Expected a function. Instead ' +
680
- `received: ${callback}`,
681
- );
682
- }
683
-
684
- callback.call(context);
685
-}
686
-
687
-export function resetHasForceUpdateBeforeProcessing() {
688
- hasForceUpdate = false;
689
-}
690
-
691
-export function checkHasForceUpdateAfterProcessing(): boolean {
692
- return hasForceUpdate;
693
-}
694
-
695
-export function deferHiddenCallbacks<State>(
696
- updateQueue: UpdateQueue<State>,
697
-): void {
698
- // When an update finishes on a hidden component, its callback should not
699
- // be fired until/unless the component is made visible again. Stash the
700
- // callback on the shared queue object so it can be fired later.
701
- const newHiddenCallbacks = updateQueue.callbacks;
702
- if (newHiddenCallbacks !== null) {
703
- const existingHiddenCallbacks = updateQueue.shared.hiddenCallbacks;
704
- if (existingHiddenCallbacks === null) {
705
- updateQueue.shared.hiddenCallbacks = newHiddenCallbacks;
706
- } else {
707
- updateQueue.shared.hiddenCallbacks = existingHiddenCallbacks.concat(
708
- newHiddenCallbacks,
709
- );
710
- }
711
- }
712
-}
713
-
714
-export function commitHiddenCallbacks<State>(
715
- updateQueue: UpdateQueue<State>,
716
- context: any,
717
-): void {
718
- // This component is switching from hidden -> visible. Commit any callbacks
719
- // that were previously deferred.
720
- const hiddenCallbacks = updateQueue.shared.hiddenCallbacks;
721
- if (hiddenCallbacks !== null) {
722
- updateQueue.shared.hiddenCallbacks = null;
723
- for (let i = 0; i < hiddenCallbacks.length; i++) {
724
- const callback = hiddenCallbacks[i];
725
- callCallback(callback, context);
726
- }
727
- }
728
-}
729
-
730
-export function commitCallbacks<State>(
731
- updateQueue: UpdateQueue<State>,
732
- context: any,
733
-): void {
734
- const callbacks = updateQueue.callbacks;
735
- if (callbacks !== null) {
736
- updateQueue.callbacks = null;
737
- for (let i = 0; i < callbacks.length; i++) {
738
- const callback = callbacks[i];
739
- callCallback(callback, context);
740
- }
741
- }
742
-}
packages/react-reconciler/src/ReactFiberCommitWork.new.js
deleted
-4450
@@ -1,4450 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {
11
- Instance,
12
- TextInstance,
13
- SuspenseInstance,
14
- Container,
15
- ChildSet,
16
- UpdatePayload,
17
-} from './ReactFiberHostConfig';
18
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
19
-import type {Lanes} from './ReactFiberLane.new';
20
-import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
21
-import type {UpdateQueue} from './ReactFiberClassUpdateQueue.new';
22
-import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new';
23
-import type {Wakeable} from 'shared/ReactTypes';
24
-import {isOffscreenManual} from './ReactFiberOffscreenComponent';
25
-import type {
26
- OffscreenState,
27
- OffscreenInstance,
28
- OffscreenQueue,
29
- OffscreenProps,
30
-} from './ReactFiberOffscreenComponent';
31
-import type {HookFlags} from './ReactHookEffectTags';
32
-import type {Cache} from './ReactFiberCacheComponent.new';
33
-import type {RootState} from './ReactFiberRoot.new';
34
-import type {
35
- Transition,
36
- TracingMarkerInstance,
37
- TransitionAbort,
38
-} from './ReactFiberTracingMarkerComponent.new';
39
-
40
-import {
41
- enableCreateEventHandleAPI,
42
- enableProfilerTimer,
43
- enableProfilerCommitHooks,
44
- enableProfilerNestedUpdatePhase,
45
- enableSchedulingProfiler,
46
- enableSuspenseCallback,
47
- enableScopeAPI,
48
- deletedTreeCleanUpLevel,
49
- enableUpdaterTracking,
50
- enableCache,
51
- enableTransitionTracing,
52
- enableUseEventHook,
53
- enableFloat,
54
- enableLegacyHidden,
55
- enableHostSingletons,
56
-} from 'shared/ReactFeatureFlags';
57
-import {
58
- FunctionComponent,
59
- ForwardRef,
60
- ClassComponent,
61
- HostRoot,
62
- HostComponent,
63
- HostResource,
64
- HostSingleton,
65
- HostText,
66
- HostPortal,
67
- Profiler,
68
- SuspenseComponent,
69
- DehydratedFragment,
70
- IncompleteClassComponent,
71
- MemoComponent,
72
- SimpleMemoComponent,
73
- SuspenseListComponent,
74
- ScopeComponent,
75
- OffscreenComponent,
76
- LegacyHiddenComponent,
77
- CacheComponent,
78
- TracingMarkerComponent,
79
-} from './ReactWorkTags';
80
-import {
81
- NoFlags,
82
- ContentReset,
83
- Placement,
84
- ChildDeletion,
85
- Snapshot,
86
- Update,
87
- Callback,
88
- Ref,
89
- Hydrating,
90
- Passive,
91
- BeforeMutationMask,
92
- MutationMask,
93
- LayoutMask,
94
- PassiveMask,
95
- Visibility,
96
-} from './ReactFiberFlags';
97
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
98
-import {
99
- resetCurrentFiber as resetCurrentDebugFiberInDEV,
100
- setCurrentFiber as setCurrentDebugFiberInDEV,
101
- getCurrentFiber as getCurrentDebugFiberInDEV,
102
-} from './ReactCurrentFiber';
103
-import {resolveDefaultProps} from './ReactFiberLazyComponent.new';
104
-import {
105
- isCurrentUpdateNested,
106
- getCommitTime,
107
- recordLayoutEffectDuration,
108
- startLayoutEffectTimer,
109
- recordPassiveEffectDuration,
110
- startPassiveEffectTimer,
111
-} from './ReactProfilerTimer.new';
112
-import {ConcurrentMode, NoMode, ProfileMode} from './ReactTypeOfMode';
113
-import {
114
- deferHiddenCallbacks,
115
- commitHiddenCallbacks,
116
- commitCallbacks,
117
-} from './ReactFiberClassUpdateQueue.new';
118
-import {
119
- getPublicInstance,
120
- supportsMutation,
121
- supportsPersistence,
122
- supportsHydration,
123
- supportsResources,
124
- supportsSingletons,
125
- commitMount,
126
- commitUpdate,
127
- resetTextContent,
128
- commitTextUpdate,
129
- appendChild,
130
- appendChildToContainer,
131
- insertBefore,
132
- insertInContainerBefore,
133
- removeChild,
134
- removeChildFromContainer,
135
- clearSuspenseBoundary,
136
- clearSuspenseBoundaryFromContainer,
137
- replaceContainerChildren,
138
- createContainerChildSet,
139
- hideInstance,
140
- hideTextInstance,
141
- unhideInstance,
142
- unhideTextInstance,
143
- commitHydratedContainer,
144
- commitHydratedSuspenseInstance,
145
- clearContainer,
146
- prepareScopeUpdate,
147
- prepareForCommit,
148
- beforeActiveInstanceBlur,
149
- detachDeletedInstance,
150
- acquireResource,
151
- releaseResource,
152
- clearSingleton,
153
- acquireSingletonInstance,
154
- releaseSingletonInstance,
155
- scheduleMicrotask,
156
-} from './ReactFiberHostConfig';
157
-import {
158
- captureCommitPhaseError,
159
- resolveRetryWakeable,
160
- markCommitTimeOfFallback,
161
- enqueuePendingPassiveProfilerEffect,
162
- restorePendingUpdaters,
163
- addTransitionStartCallbackToPendingTransition,
164
- addTransitionProgressCallbackToPendingTransition,
165
- addTransitionCompleteCallbackToPendingTransition,
166
- addMarkerProgressCallbackToPendingTransition,
167
- addMarkerIncompleteCallbackToPendingTransition,
168
- addMarkerCompleteCallbackToPendingTransition,
169
- setIsRunningInsertionEffect,
170
- getExecutionContext,
171
- CommitContext,
172
- RenderContext,
173
- NoContext,
174
-} from './ReactFiberWorkLoop.new';
175
-import {
176
- NoFlags as NoHookEffect,
177
- HasEffect as HookHasEffect,
178
- Layout as HookLayout,
179
- Insertion as HookInsertion,
180
- Passive as HookPassive,
181
-} from './ReactHookEffectTags';
182
-import {didWarnAboutReassigningProps} from './ReactFiberBeginWork.new';
183
-import {doesFiberContain} from './ReactFiberTreeReflection';
184
-import {invokeGuardedCallback, clearCaughtError} from 'shared/ReactErrorUtils';
185
-import {
186
- isDevToolsPresent,
187
- markComponentPassiveEffectMountStarted,
188
- markComponentPassiveEffectMountStopped,
189
- markComponentPassiveEffectUnmountStarted,
190
- markComponentPassiveEffectUnmountStopped,
191
- markComponentLayoutEffectMountStarted,
192
- markComponentLayoutEffectMountStopped,
193
- markComponentLayoutEffectUnmountStarted,
194
- markComponentLayoutEffectUnmountStopped,
195
- onCommitUnmount,
196
-} from './ReactFiberDevToolsHook.new';
197
-import {releaseCache, retainCache} from './ReactFiberCacheComponent.new';
198
-import {clearTransitionsForLanes} from './ReactFiberLane.new';
199
-import {
200
- OffscreenVisible,
201
- OffscreenDetached,
202
- OffscreenPassiveEffectsConnected,
203
-} from './ReactFiberOffscreenComponent';
204
-import {
205
- TransitionRoot,
206
- TransitionTracingMarker,
207
-} from './ReactFiberTracingMarkerComponent.new';
208
-
209
-let didWarnAboutUndefinedSnapshotBeforeUpdate: Set<mixed> | null = null;
210
-if (__DEV__) {
211
- didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
212
-}
213
-
214
-// Used during the commit phase to track the state of the Offscreen component stack.
215
-// Allows us to avoid traversing the return path to find the nearest Offscreen ancestor.
216
-let offscreenSubtreeIsHidden: boolean = false;
217
-let offscreenSubtreeWasHidden: boolean = false;
218
-
219
-const PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
220
-
221
-let nextEffect: Fiber | null = null;
222
-
223
-// Used for Profiling builds to track updaters.
224
-let inProgressLanes: Lanes | null = null;
225
-let inProgressRoot: FiberRoot | null = null;
226
-
227
-function shouldProfile(current: Fiber): boolean {
228
- return (
229
- enableProfilerTimer &&
230
- enableProfilerCommitHooks &&
231
- (current.mode & ProfileMode) !== NoMode &&
232
- (getExecutionContext() & CommitContext) !== NoContext
233
- );
234
-}
235
-
236
-export function reportUncaughtErrorInDEV(error: mixed) {
237
- // Wrapping each small part of the commit phase into a guarded
238
- // callback is a bit too slow (https://github.com/facebook/react/pull/21666).
239
- // But we rely on it to surface errors to DEV tools like overlays
240
- // (https://github.com/facebook/react/issues/21712).
241
- // As a compromise, rethrow only caught errors in a guard.
242
- if (__DEV__) {
243
- invokeGuardedCallback(null, () => {
244
- throw error;
245
- });
246
- clearCaughtError();
247
- }
248
-}
249
-
250
-const callComponentWillUnmountWithTimer = function(current, instance) {
251
- instance.props = current.memoizedProps;
252
- instance.state = current.memoizedState;
253
- if (shouldProfile(current)) {
254
- try {
255
- startLayoutEffectTimer();
256
- instance.componentWillUnmount();
257
- } finally {
258
- recordLayoutEffectDuration(current);
259
- }
260
- } else {
261
- instance.componentWillUnmount();
262
- }
263
-};
264
-
265
-// Capture errors so they don't interrupt unmounting.
266
-function safelyCallComponentWillUnmount(
267
- current: Fiber,
268
- nearestMountedAncestor: Fiber | null,
269
- instance: any,
270
-) {
271
- try {
272
- callComponentWillUnmountWithTimer(current, instance);
273
- } catch (error) {
274
- captureCommitPhaseError(current, nearestMountedAncestor, error);
275
- }
276
-}
277
-
278
-// Capture errors so they don't interrupt mounting.
279
-function safelyAttachRef(current: Fiber, nearestMountedAncestor: Fiber | null) {
280
- try {
281
- commitAttachRef(current);
282
- } catch (error) {
283
- captureCommitPhaseError(current, nearestMountedAncestor, error);
284
- }
285
-}
286
-
287
-function safelyDetachRef(current: Fiber, nearestMountedAncestor: Fiber | null) {
288
- const ref = current.ref;
289
- const refCleanup = current.refCleanup;
290
-
291
- if (ref !== null) {
292
- if (typeof refCleanup === 'function') {
293
- try {
294
- if (shouldProfile(current)) {
295
- try {
296
- startLayoutEffectTimer();
297
- refCleanup();
298
- } finally {
299
- recordLayoutEffectDuration(current);
300
- }
301
- } else {
302
- refCleanup();
303
- }
304
- } catch (error) {
305
- captureCommitPhaseError(current, nearestMountedAncestor, error);
306
- } finally {
307
- // `refCleanup` has been called. Nullify all references to it to prevent double invocation.
308
- current.refCleanup = null;
309
- const finishedWork = current.alternate;
310
- if (finishedWork != null) {
311
- finishedWork.refCleanup = null;
312
- }
313
- }
314
- } else if (typeof ref === 'function') {
315
- let retVal;
316
- try {
317
- if (shouldProfile(current)) {
318
- try {
319
- startLayoutEffectTimer();
320
- retVal = ref(null);
321
- } finally {
322
- recordLayoutEffectDuration(current);
323
- }
324
- } else {
325
- retVal = ref(null);
326
- }
327
- } catch (error) {
328
- captureCommitPhaseError(current, nearestMountedAncestor, error);
329
- }
330
- if (__DEV__) {
331
- if (typeof retVal === 'function') {
332
- console.error(
333
- 'Unexpected return value from a callback ref in %s. ' +
334
- 'A callback ref should not return a function.',
335
- getComponentNameFromFiber(current),
336
- );
337
- }
338
- }
339
- } else {
340
- // $FlowFixMe unable to narrow type to RefObject
341
- ref.current = null;
342
- }
343
- }
344
-}
345
-
346
-function safelyCallDestroy(
347
- current: Fiber,
348
- nearestMountedAncestor: Fiber | null,
349
- destroy: () => void,
350
-) {
351
- try {
352
- destroy();
353
- } catch (error) {
354
- captureCommitPhaseError(current, nearestMountedAncestor, error);
355
- }
356
-}
357
-
358
-let focusedInstanceHandle: null | Fiber = null;
359
-let shouldFireAfterActiveInstanceBlur: boolean = false;
360
-
361
-export function commitBeforeMutationEffects(
362
- root: FiberRoot,
363
- firstChild: Fiber,
364
-): boolean {
365
- focusedInstanceHandle = prepareForCommit(root.containerInfo);
366
-
367
- nextEffect = firstChild;
368
- commitBeforeMutationEffects_begin();
369
-
370
- // We no longer need to track the active instance fiber
371
- const shouldFire = shouldFireAfterActiveInstanceBlur;
372
- shouldFireAfterActiveInstanceBlur = false;
373
- focusedInstanceHandle = null;
374
-
375
- return shouldFire;
376
-}
377
-
378
-function commitBeforeMutationEffects_begin() {
379
- while (nextEffect !== null) {
380
- const fiber = nextEffect;
381
-
382
- // This phase is only used for beforeActiveInstanceBlur.
383
- // Let's skip the whole loop if it's off.
384
- if (enableCreateEventHandleAPI) {
385
- // TODO: Should wrap this in flags check, too, as optimization
386
- const deletions = fiber.deletions;
387
- if (deletions !== null) {
388
- for (let i = 0; i < deletions.length; i++) {
389
- const deletion = deletions[i];
390
- commitBeforeMutationEffectsDeletion(deletion);
391
- }
392
- }
393
- }
394
-
395
- const child = fiber.child;
396
- if (
397
- (fiber.subtreeFlags & BeforeMutationMask) !== NoFlags &&
398
- child !== null
399
- ) {
400
- child.return = fiber;
401
- nextEffect = child;
402
- } else {
403
- commitBeforeMutationEffects_complete();
404
- }
405
- }
406
-}
407
-
408
-function commitBeforeMutationEffects_complete() {
409
- while (nextEffect !== null) {
410
- const fiber = nextEffect;
411
- setCurrentDebugFiberInDEV(fiber);
412
- try {
413
- commitBeforeMutationEffectsOnFiber(fiber);
414
- } catch (error) {
415
- captureCommitPhaseError(fiber, fiber.return, error);
416
- }
417
- resetCurrentDebugFiberInDEV();
418
-
419
- const sibling = fiber.sibling;
420
- if (sibling !== null) {
421
- sibling.return = fiber.return;
422
- nextEffect = sibling;
423
- return;
424
- }
425
-
426
- nextEffect = fiber.return;
427
- }
428
-}
429
-
430
-function commitBeforeMutationEffectsOnFiber(finishedWork: Fiber) {
431
- const current = finishedWork.alternate;
432
- const flags = finishedWork.flags;
433
-
434
- if (enableCreateEventHandleAPI) {
435
- if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) {
436
- // Check to see if the focused element was inside of a hidden (Suspense) subtree.
437
- // TODO: Move this out of the hot path using a dedicated effect tag.
438
- if (
439
- finishedWork.tag === SuspenseComponent &&
440
- isSuspenseBoundaryBeingHidden(current, finishedWork) &&
441
- // $FlowFixMe[incompatible-call] found when upgrading Flow
442
- doesFiberContain(finishedWork, focusedInstanceHandle)
443
- ) {
444
- shouldFireAfterActiveInstanceBlur = true;
445
- beforeActiveInstanceBlur(finishedWork);
446
- }
447
- }
448
- }
449
-
450
- if ((flags & Snapshot) !== NoFlags) {
451
- setCurrentDebugFiberInDEV(finishedWork);
452
- }
453
-
454
- switch (finishedWork.tag) {
455
- case FunctionComponent: {
456
- if (enableUseEventHook) {
457
- if ((flags & Update) !== NoFlags) {
458
- commitUseEventMount(finishedWork);
459
- }
460
- }
461
- break;
462
- }
463
- case ForwardRef:
464
- case SimpleMemoComponent: {
465
- break;
466
- }
467
- case ClassComponent: {
468
- if ((flags & Snapshot) !== NoFlags) {
469
- if (current !== null) {
470
- const prevProps = current.memoizedProps;
471
- const prevState = current.memoizedState;
472
- const instance = finishedWork.stateNode;
473
- // We could update instance props and state here,
474
- // but instead we rely on them being set during last render.
475
- // TODO: revisit this when we implement resuming.
476
- if (__DEV__) {
477
- if (
478
- finishedWork.type === finishedWork.elementType &&
479
- !didWarnAboutReassigningProps
480
- ) {
481
- if (instance.props !== finishedWork.memoizedProps) {
482
- console.error(
483
- 'Expected %s props to match memoized props before ' +
484
- 'getSnapshotBeforeUpdate. ' +
485
- 'This might either be because of a bug in React, or because ' +
486
- 'a component reassigns its own `this.props`. ' +
487
- 'Please file an issue.',
488
- getComponentNameFromFiber(finishedWork) || 'instance',
489
- );
490
- }
491
- if (instance.state !== finishedWork.memoizedState) {
492
- console.error(
493
- 'Expected %s state to match memoized state before ' +
494
- 'getSnapshotBeforeUpdate. ' +
495
- 'This might either be because of a bug in React, or because ' +
496
- 'a component reassigns its own `this.state`. ' +
497
- 'Please file an issue.',
498
- getComponentNameFromFiber(finishedWork) || 'instance',
499
- );
500
- }
501
- }
502
- }
503
- const snapshot = instance.getSnapshotBeforeUpdate(
504
- finishedWork.elementType === finishedWork.type
505
- ? prevProps
506
- : resolveDefaultProps(finishedWork.type, prevProps),
507
- prevState,
508
- );
509
- if (__DEV__) {
510
- const didWarnSet = ((didWarnAboutUndefinedSnapshotBeforeUpdate: any): Set<mixed>);
511
- if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
512
- didWarnSet.add(finishedWork.type);
513
- console.error(
514
- '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' +
515
- 'must be returned. You have returned undefined.',
516
- getComponentNameFromFiber(finishedWork),
517
- );
518
- }
519
- }
520
- instance.__reactInternalSnapshotBeforeUpdate = snapshot;
521
- }
522
- }
523
- break;
524
- }
525
- case HostRoot: {
526
- if ((flags & Snapshot) !== NoFlags) {
527
- if (supportsMutation) {
528
- const root = finishedWork.stateNode;
529
- clearContainer(root.containerInfo);
530
- }
531
- }
532
- break;
533
- }
534
- case HostComponent:
535
- case HostResource:
536
- case HostSingleton:
537
- case HostText:
538
- case HostPortal:
539
- case IncompleteClassComponent:
540
- // Nothing to do for these component types
541
- break;
542
- default: {
543
- if ((flags & Snapshot) !== NoFlags) {
544
- throw new Error(
545
- 'This unit of work tag should not have side-effects. This error is ' +
546
- 'likely caused by a bug in React. Please file an issue.',
547
- );
548
- }
549
- }
550
- }
551
-
552
- if ((flags & Snapshot) !== NoFlags) {
553
- resetCurrentDebugFiberInDEV();
554
- }
555
-}
556
-
557
-function commitBeforeMutationEffectsDeletion(deletion: Fiber) {
558
- if (enableCreateEventHandleAPI) {
559
- // TODO (effects) It would be nice to avoid calling doesFiberContain()
560
- // Maybe we can repurpose one of the subtreeFlags positions for this instead?
561
- // Use it to store which part of the tree the focused instance is in?
562
- // This assumes we can safely determine that instance during the "render" phase.
563
- if (doesFiberContain(deletion, ((focusedInstanceHandle: any): Fiber))) {
564
- shouldFireAfterActiveInstanceBlur = true;
565
- beforeActiveInstanceBlur(deletion);
566
- }
567
- }
568
-}
569
-
570
-function commitHookEffectListUnmount(
571
- flags: HookFlags,
572
- finishedWork: Fiber,
573
- nearestMountedAncestor: Fiber | null,
574
-) {
575
- const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
576
- const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
577
- if (lastEffect !== null) {
578
- const firstEffect = lastEffect.next;
579
- let effect = firstEffect;
580
- do {
581
- if ((effect.tag & flags) === flags) {
582
- // Unmount
583
- const destroy = effect.destroy;
584
- effect.destroy = undefined;
585
- if (destroy !== undefined) {
586
- if (enableSchedulingProfiler) {
587
- if ((flags & HookPassive) !== NoHookEffect) {
588
- markComponentPassiveEffectUnmountStarted(finishedWork);
589
- } else if ((flags & HookLayout) !== NoHookEffect) {
590
- markComponentLayoutEffectUnmountStarted(finishedWork);
591
- }
592
- }
593
-
594
- if (__DEV__) {
595
- if ((flags & HookInsertion) !== NoHookEffect) {
596
- setIsRunningInsertionEffect(true);
597
- }
598
- }
599
- safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
600
- if (__DEV__) {
601
- if ((flags & HookInsertion) !== NoHookEffect) {
602
- setIsRunningInsertionEffect(false);
603
- }
604
- }
605
-
606
- if (enableSchedulingProfiler) {
607
- if ((flags & HookPassive) !== NoHookEffect) {
608
- markComponentPassiveEffectUnmountStopped();
609
- } else if ((flags & HookLayout) !== NoHookEffect) {
610
- markComponentLayoutEffectUnmountStopped();
611
- }
612
- }
613
- }
614
- }
615
- effect = effect.next;
616
- } while (effect !== firstEffect);
617
- }
618
-}
619
-
620
-function commitHookEffectListMount(flags: HookFlags, finishedWork: Fiber) {
621
- const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
622
- const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
623
- if (lastEffect !== null) {
624
- const firstEffect = lastEffect.next;
625
- let effect = firstEffect;
626
- do {
627
- if ((effect.tag & flags) === flags) {
628
- if (enableSchedulingProfiler) {
629
- if ((flags & HookPassive) !== NoHookEffect) {
630
- markComponentPassiveEffectMountStarted(finishedWork);
631
- } else if ((flags & HookLayout) !== NoHookEffect) {
632
- markComponentLayoutEffectMountStarted(finishedWork);
633
- }
634
- }
635
-
636
- // Mount
637
- const create = effect.create;
638
- if (__DEV__) {
639
- if ((flags & HookInsertion) !== NoHookEffect) {
640
- setIsRunningInsertionEffect(true);
641
- }
642
- }
643
- effect.destroy = create();
644
- if (__DEV__) {
645
- if ((flags & HookInsertion) !== NoHookEffect) {
646
- setIsRunningInsertionEffect(false);
647
- }
648
- }
649
-
650
- if (enableSchedulingProfiler) {
651
- if ((flags & HookPassive) !== NoHookEffect) {
652
- markComponentPassiveEffectMountStopped();
653
- } else if ((flags & HookLayout) !== NoHookEffect) {
654
- markComponentLayoutEffectMountStopped();
655
- }
656
- }
657
-
658
- if (__DEV__) {
659
- const destroy = effect.destroy;
660
- if (destroy !== undefined && typeof destroy !== 'function') {
661
- let hookName;
662
- if ((effect.tag & HookLayout) !== NoFlags) {
663
- hookName = 'useLayoutEffect';
664
- } else if ((effect.tag & HookInsertion) !== NoFlags) {
665
- hookName = 'useInsertionEffect';
666
- } else {
667
- hookName = 'useEffect';
668
- }
669
- let addendum;
670
- if (destroy === null) {
671
- addendum =
672
- ' You returned null. If your effect does not require clean ' +
673
- 'up, return undefined (or nothing).';
674
- } else if (typeof destroy.then === 'function') {
675
- addendum =
676
- '\n\nIt looks like you wrote ' +
677
- hookName +
678
- '(async () => ...) or returned a Promise. ' +
679
- 'Instead, write the async function inside your effect ' +
680
- 'and call it immediately:\n\n' +
681
- hookName +
682
- '(() => {\n' +
683
- ' async function fetchData() {\n' +
684
- ' // You can await here\n' +
685
- ' const response = await MyAPI.getData(someId);\n' +
686
- ' // ...\n' +
687
- ' }\n' +
688
- ' fetchData();\n' +
689
- `}, [someId]); // Or [] if effect doesn't need props or state\n\n` +
690
- 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';
691
- } else {
692
- addendum = ' You returned: ' + destroy;
693
- }
694
- console.error(
695
- '%s must not return anything besides a function, ' +
696
- 'which is used for clean-up.%s',
697
- hookName,
698
- addendum,
699
- );
700
- }
701
- }
702
- }
703
- effect = effect.next;
704
- } while (effect !== firstEffect);
705
- }
706
-}
707
-
708
-function commitUseEventMount(finishedWork: Fiber) {
709
- const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
710
- const eventPayloads = updateQueue !== null ? updateQueue.events : null;
711
- if (eventPayloads !== null) {
712
- for (let ii = 0; ii < eventPayloads.length; ii++) {
713
- const {ref, nextImpl} = eventPayloads[ii];
714
- ref.impl = nextImpl;
715
- }
716
- }
717
-}
718
-
719
-export function commitPassiveEffectDurations(
720
- finishedRoot: FiberRoot,
721
- finishedWork: Fiber,
722
-): void {
723
- if (
724
- enableProfilerTimer &&
725
- enableProfilerCommitHooks &&
726
- getExecutionContext() & CommitContext
727
- ) {
728
- // Only Profilers with work in their subtree will have an Update effect scheduled.
729
- if ((finishedWork.flags & Update) !== NoFlags) {
730
- switch (finishedWork.tag) {
731
- case Profiler: {
732
- const {passiveEffectDuration} = finishedWork.stateNode;
733
- const {id, onPostCommit} = finishedWork.memoizedProps;
734
-
735
- // This value will still reflect the previous commit phase.
736
- // It does not get reset until the start of the next commit phase.
737
- const commitTime = getCommitTime();
738
-
739
- let phase = finishedWork.alternate === null ? 'mount' : 'update';
740
- if (enableProfilerNestedUpdatePhase) {
741
- if (isCurrentUpdateNested()) {
742
- phase = 'nested-update';
743
- }
744
- }
745
-
746
- if (typeof onPostCommit === 'function') {
747
- onPostCommit(id, phase, passiveEffectDuration, commitTime);
748
- }
749
-
750
- // Bubble times to the next nearest ancestor Profiler.
751
- // After we process that Profiler, we'll bubble further up.
752
- let parentFiber = finishedWork.return;
753
- outer: while (parentFiber !== null) {
754
- switch (parentFiber.tag) {
755
- case HostRoot:
756
- const root = parentFiber.stateNode;
757
- root.passiveEffectDuration += passiveEffectDuration;
758
- break outer;
759
- case Profiler:
760
- const parentStateNode = parentFiber.stateNode;
761
- parentStateNode.passiveEffectDuration += passiveEffectDuration;
762
- break outer;
763
- }
764
- parentFiber = parentFiber.return;
765
- }
766
- break;
767
- }
768
- default:
769
- break;
770
- }
771
- }
772
- }
773
-}
774
-
775
-function commitHookLayoutEffects(finishedWork: Fiber, hookFlags: HookFlags) {
776
- // At this point layout effects have already been destroyed (during mutation phase).
777
- // This is done to prevent sibling component effects from interfering with each other,
778
- // e.g. a destroy function in one component should never override a ref set
779
- // by a create function in another component during the same commit.
780
- if (shouldProfile(finishedWork)) {
781
- try {
782
- startLayoutEffectTimer();
783
- commitHookEffectListMount(hookFlags, finishedWork);
784
- } catch (error) {
785
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
786
- }
787
- recordLayoutEffectDuration(finishedWork);
788
- } else {
789
- try {
790
- commitHookEffectListMount(hookFlags, finishedWork);
791
- } catch (error) {
792
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
793
- }
794
- }
795
-}
796
-
797
-function commitClassLayoutLifecycles(
798
- finishedWork: Fiber,
799
- current: Fiber | null,
800
-) {
801
- const instance = finishedWork.stateNode;
802
- if (current === null) {
803
- // We could update instance props and state here,
804
- // but instead we rely on them being set during last render.
805
- // TODO: revisit this when we implement resuming.
806
- if (__DEV__) {
807
- if (
808
- finishedWork.type === finishedWork.elementType &&
809
- !didWarnAboutReassigningProps
810
- ) {
811
- if (instance.props !== finishedWork.memoizedProps) {
812
- console.error(
813
- 'Expected %s props to match memoized props before ' +
814
- 'componentDidMount. ' +
815
- 'This might either be because of a bug in React, or because ' +
816
- 'a component reassigns its own `this.props`. ' +
817
- 'Please file an issue.',
818
- getComponentNameFromFiber(finishedWork) || 'instance',
819
- );
820
- }
821
- if (instance.state !== finishedWork.memoizedState) {
822
- console.error(
823
- 'Expected %s state to match memoized state before ' +
824
- 'componentDidMount. ' +
825
- 'This might either be because of a bug in React, or because ' +
826
- 'a component reassigns its own `this.state`. ' +
827
- 'Please file an issue.',
828
- getComponentNameFromFiber(finishedWork) || 'instance',
829
- );
830
- }
831
- }
832
- }
833
- if (shouldProfile(finishedWork)) {
834
- try {
835
- startLayoutEffectTimer();
836
- instance.componentDidMount();
837
- } catch (error) {
838
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
839
- }
840
- recordLayoutEffectDuration(finishedWork);
841
- } else {
842
- try {
843
- instance.componentDidMount();
844
- } catch (error) {
845
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
846
- }
847
- }
848
- } else {
849
- const prevProps =
850
- finishedWork.elementType === finishedWork.type
851
- ? current.memoizedProps
852
- : resolveDefaultProps(finishedWork.type, current.memoizedProps);
853
- const prevState = current.memoizedState;
854
- // We could update instance props and state here,
855
- // but instead we rely on them being set during last render.
856
- // TODO: revisit this when we implement resuming.
857
- if (__DEV__) {
858
- if (
859
- finishedWork.type === finishedWork.elementType &&
860
- !didWarnAboutReassigningProps
861
- ) {
862
- if (instance.props !== finishedWork.memoizedProps) {
863
- console.error(
864
- 'Expected %s props to match memoized props before ' +
865
- 'componentDidUpdate. ' +
866
- 'This might either be because of a bug in React, or because ' +
867
- 'a component reassigns its own `this.props`. ' +
868
- 'Please file an issue.',
869
- getComponentNameFromFiber(finishedWork) || 'instance',
870
- );
871
- }
872
- if (instance.state !== finishedWork.memoizedState) {
873
- console.error(
874
- 'Expected %s state to match memoized state before ' +
875
- 'componentDidUpdate. ' +
876
- 'This might either be because of a bug in React, or because ' +
877
- 'a component reassigns its own `this.state`. ' +
878
- 'Please file an issue.',
879
- getComponentNameFromFiber(finishedWork) || 'instance',
880
- );
881
- }
882
- }
883
- }
884
- if (shouldProfile(finishedWork)) {
885
- try {
886
- startLayoutEffectTimer();
887
- instance.componentDidUpdate(
888
- prevProps,
889
- prevState,
890
- instance.__reactInternalSnapshotBeforeUpdate,
891
- );
892
- } catch (error) {
893
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
894
- }
895
- recordLayoutEffectDuration(finishedWork);
896
- } else {
897
- try {
898
- instance.componentDidUpdate(
899
- prevProps,
900
- prevState,
901
- instance.__reactInternalSnapshotBeforeUpdate,
902
- );
903
- } catch (error) {
904
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
905
- }
906
- }
907
- }
908
-}
909
-
910
-function commitClassCallbacks(finishedWork: Fiber) {
911
- // TODO: I think this is now always non-null by the time it reaches the
912
- // commit phase. Consider removing the type check.
913
- const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any);
914
- if (updateQueue !== null) {
915
- const instance = finishedWork.stateNode;
916
- if (__DEV__) {
917
- if (
918
- finishedWork.type === finishedWork.elementType &&
919
- !didWarnAboutReassigningProps
920
- ) {
921
- if (instance.props !== finishedWork.memoizedProps) {
922
- console.error(
923
- 'Expected %s props to match memoized props before ' +
924
- 'processing the update queue. ' +
925
- 'This might either be because of a bug in React, or because ' +
926
- 'a component reassigns its own `this.props`. ' +
927
- 'Please file an issue.',
928
- getComponentNameFromFiber(finishedWork) || 'instance',
929
- );
930
- }
931
- if (instance.state !== finishedWork.memoizedState) {
932
- console.error(
933
- 'Expected %s state to match memoized state before ' +
934
- 'processing the update queue. ' +
935
- 'This might either be because of a bug in React, or because ' +
936
- 'a component reassigns its own `this.state`. ' +
937
- 'Please file an issue.',
938
- getComponentNameFromFiber(finishedWork) || 'instance',
939
- );
940
- }
941
- }
942
- }
943
- // We could update instance props and state here,
944
- // but instead we rely on them being set during last render.
945
- // TODO: revisit this when we implement resuming.
946
- try {
947
- commitCallbacks(updateQueue, instance);
948
- } catch (error) {
949
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
950
- }
951
- }
952
-}
953
-
954
-function commitHostComponentMount(finishedWork: Fiber) {
955
- const type = finishedWork.type;
956
- const props = finishedWork.memoizedProps;
957
- const instance: Instance = finishedWork.stateNode;
958
- try {
959
- commitMount(instance, type, props, finishedWork);
960
- } catch (error) {
961
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
962
- }
963
-}
964
-
965
-function commitProfilerUpdate(finishedWork: Fiber, current: Fiber | null) {
966
- if (enableProfilerTimer && getExecutionContext() & CommitContext) {
967
- try {
968
- const {onCommit, onRender} = finishedWork.memoizedProps;
969
- const {effectDuration} = finishedWork.stateNode;
970
-
971
- const commitTime = getCommitTime();
972
-
973
- let phase = current === null ? 'mount' : 'update';
974
- if (enableProfilerNestedUpdatePhase) {
975
- if (isCurrentUpdateNested()) {
976
- phase = 'nested-update';
977
- }
978
- }
979
-
980
- if (typeof onRender === 'function') {
981
- onRender(
982
- finishedWork.memoizedProps.id,
983
- phase,
984
- finishedWork.actualDuration,
985
- finishedWork.treeBaseDuration,
986
- finishedWork.actualStartTime,
987
- commitTime,
988
- );
989
- }
990
-
991
- if (enableProfilerCommitHooks) {
992
- if (typeof onCommit === 'function') {
993
- onCommit(
994
- finishedWork.memoizedProps.id,
995
- phase,
996
- effectDuration,
997
- commitTime,
998
- );
999
- }
1000
-
1001
- // Schedule a passive effect for this Profiler to call onPostCommit hooks.
1002
- // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
1003
- // because the effect is also where times bubble to parent Profilers.
1004
- enqueuePendingPassiveProfilerEffect(finishedWork);
1005
-
1006
- // Propagate layout effect durations to the next nearest Profiler ancestor.
1007
- // Do not reset these values until the next render so DevTools has a chance to read them first.
1008
- let parentFiber = finishedWork.return;
1009
- outer: while (parentFiber !== null) {
1010
- switch (parentFiber.tag) {
1011
- case HostRoot:
1012
- const root = parentFiber.stateNode;
1013
- root.effectDuration += effectDuration;
1014
- break outer;
1015
- case Profiler:
1016
- const parentStateNode = parentFiber.stateNode;
1017
- parentStateNode.effectDuration += effectDuration;
1018
- break outer;
1019
- }
1020
- parentFiber = parentFiber.return;
1021
- }
1022
- }
1023
- } catch (error) {
1024
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
1025
- }
1026
- }
1027
-}
1028
-
1029
-function commitLayoutEffectOnFiber(
1030
- finishedRoot: FiberRoot,
1031
- current: Fiber | null,
1032
- finishedWork: Fiber,
1033
- committedLanes: Lanes,
1034
-): void {
1035
- // When updating this function, also update reappearLayoutEffects, which does
1036
- // most of the same things when an offscreen tree goes from hidden -> visible.
1037
- const flags = finishedWork.flags;
1038
- switch (finishedWork.tag) {
1039
- case FunctionComponent:
1040
- case ForwardRef:
1041
- case SimpleMemoComponent: {
1042
- recursivelyTraverseLayoutEffects(
1043
- finishedRoot,
1044
- finishedWork,
1045
- committedLanes,
1046
- );
1047
- if (flags & Update) {
1048
- commitHookLayoutEffects(finishedWork, HookLayout | HookHasEffect);
1049
- }
1050
- break;
1051
- }
1052
- case ClassComponent: {
1053
- recursivelyTraverseLayoutEffects(
1054
- finishedRoot,
1055
- finishedWork,
1056
- committedLanes,
1057
- );
1058
- if (flags & Update) {
1059
- commitClassLayoutLifecycles(finishedWork, current);
1060
- }
1061
-
1062
- if (flags & Callback) {
1063
- commitClassCallbacks(finishedWork);
1064
- }
1065
-
1066
- if (flags & Ref) {
1067
- safelyAttachRef(finishedWork, finishedWork.return);
1068
- }
1069
- break;
1070
- }
1071
- case HostRoot: {
1072
- recursivelyTraverseLayoutEffects(
1073
- finishedRoot,
1074
- finishedWork,
1075
- committedLanes,
1076
- );
1077
- if (flags & Callback) {
1078
- // TODO: I think this is now always non-null by the time it reaches the
1079
- // commit phase. Consider removing the type check.
1080
- const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any);
1081
- if (updateQueue !== null) {
1082
- let instance = null;
1083
- if (finishedWork.child !== null) {
1084
- switch (finishedWork.child.tag) {
1085
- case HostSingleton:
1086
- case HostComponent:
1087
- instance = getPublicInstance(finishedWork.child.stateNode);
1088
- break;
1089
- case ClassComponent:
1090
- instance = finishedWork.child.stateNode;
1091
- break;
1092
- }
1093
- }
1094
- try {
1095
- commitCallbacks(updateQueue, instance);
1096
- } catch (error) {
1097
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
1098
- }
1099
- }
1100
- }
1101
- break;
1102
- }
1103
- case HostResource: {
1104
- if (enableFloat && supportsResources) {
1105
- recursivelyTraverseLayoutEffects(
1106
- finishedRoot,
1107
- finishedWork,
1108
- committedLanes,
1109
- );
1110
-
1111
- if (flags & Ref) {
1112
- safelyAttachRef(finishedWork, finishedWork.return);
1113
- }
1114
- break;
1115
- }
1116
- }
1117
- // eslint-disable-next-line-no-fallthrough
1118
- case HostSingleton:
1119
- case HostComponent: {
1120
- recursivelyTraverseLayoutEffects(
1121
- finishedRoot,
1122
- finishedWork,
1123
- committedLanes,
1124
- );
1125
-
1126
- // Renderers may schedule work to be done after host components are mounted
1127
- // (eg DOM renderer may schedule auto-focus for inputs and form controls).
1128
- // These effects should only be committed when components are first mounted,
1129
- // aka when there is no current/alternate.
1130
- if (current === null && flags & Update) {
1131
- commitHostComponentMount(finishedWork);
1132
- }
1133
-
1134
- if (flags & Ref) {
1135
- safelyAttachRef(finishedWork, finishedWork.return);
1136
- }
1137
- break;
1138
- }
1139
- case Profiler: {
1140
- recursivelyTraverseLayoutEffects(
1141
- finishedRoot,
1142
- finishedWork,
1143
- committedLanes,
1144
- );
1145
- // TODO: Should this fire inside an offscreen tree? Or should it wait to
1146
- // fire when the tree becomes visible again.
1147
- if (flags & Update) {
1148
- commitProfilerUpdate(finishedWork, current);
1149
- }
1150
- break;
1151
- }
1152
- case SuspenseComponent: {
1153
- recursivelyTraverseLayoutEffects(
1154
- finishedRoot,
1155
- finishedWork,
1156
- committedLanes,
1157
- );
1158
- if (flags & Update) {
1159
- commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
1160
- }
1161
- break;
1162
- }
1163
- case OffscreenComponent: {
1164
- const isModernRoot = (finishedWork.mode & ConcurrentMode) !== NoMode;
1165
- if (isModernRoot) {
1166
- const isHidden = finishedWork.memoizedState !== null;
1167
- const newOffscreenSubtreeIsHidden =
1168
- isHidden || offscreenSubtreeIsHidden;
1169
- if (newOffscreenSubtreeIsHidden) {
1170
- // The Offscreen tree is hidden. Skip over its layout effects.
1171
- } else {
1172
- // The Offscreen tree is visible.
1173
-
1174
- const wasHidden = current !== null && current.memoizedState !== null;
1175
- const newOffscreenSubtreeWasHidden =
1176
- wasHidden || offscreenSubtreeWasHidden;
1177
- const prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
1178
- const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
1179
- offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden;
1180
- offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden;
1181
-
1182
- if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) {
1183
- // This is the root of a reappearing boundary. As we continue
1184
- // traversing the layout effects, we must also re-mount layout
1185
- // effects that were unmounted when the Offscreen subtree was
1186
- // hidden. So this is a superset of the normal commitLayoutEffects.
1187
- const includeWorkInProgressEffects =
1188
- (finishedWork.subtreeFlags & LayoutMask) !== NoFlags;
1189
- recursivelyTraverseReappearLayoutEffects(
1190
- finishedRoot,
1191
- finishedWork,
1192
- includeWorkInProgressEffects,
1193
- );
1194
- } else {
1195
- recursivelyTraverseLayoutEffects(
1196
- finishedRoot,
1197
- finishedWork,
1198
- committedLanes,
1199
- );
1200
- }
1201
- offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
1202
- offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
1203
- }
1204
- } else {
1205
- recursivelyTraverseLayoutEffects(
1206
- finishedRoot,
1207
- finishedWork,
1208
- committedLanes,
1209
- );
1210
- }
1211
- if (flags & Ref) {
1212
- const props: OffscreenProps = finishedWork.memoizedProps;
1213
- if (props.mode === 'manual') {
1214
- safelyAttachRef(finishedWork, finishedWork.return);
1215
- } else {
1216
- safelyDetachRef(finishedWork, finishedWork.return);
1217
- }
1218
- }
1219
- break;
1220
- }
1221
- default: {
1222
- recursivelyTraverseLayoutEffects(
1223
- finishedRoot,
1224
- finishedWork,
1225
- committedLanes,
1226
- );
1227
- break;
1228
- }
1229
- }
1230
-}
1231
-
1232
-function abortRootTransitions(
1233
- root: FiberRoot,
1234
- abort: TransitionAbort,
1235
- deletedTransitions: Set<Transition>,
1236
- deletedOffscreenInstance: OffscreenInstance | null,
1237
- isInDeletedTree: boolean,
1238
-) {
1239
- if (enableTransitionTracing) {
1240
- const rootTransitions = root.incompleteTransitions;
1241
- deletedTransitions.forEach(transition => {
1242
- if (rootTransitions.has(transition)) {
1243
- const transitionInstance: TracingMarkerInstance = (rootTransitions.get(
1244
- transition,
1245
- ): any);
1246
- if (transitionInstance.aborts === null) {
1247
- transitionInstance.aborts = [];
1248
- }
1249
- transitionInstance.aborts.push(abort);
1250
-
1251
- if (deletedOffscreenInstance !== null) {
1252
- if (
1253
- transitionInstance.pendingBoundaries !== null &&
1254
- transitionInstance.pendingBoundaries.has(deletedOffscreenInstance)
1255
- ) {
1256
- // $FlowFixMe[incompatible-use] found when upgrading Flow
1257
- transitionInstance.pendingBoundaries.delete(
1258
- deletedOffscreenInstance,
1259
- );
1260
- }
1261
- }
1262
- }
1263
- });
1264
- }
1265
-}
1266
-
1267
-function abortTracingMarkerTransitions(
1268
- abortedFiber: Fiber,
1269
- abort: TransitionAbort,
1270
- deletedTransitions: Set<Transition>,
1271
- deletedOffscreenInstance: OffscreenInstance | null,
1272
- isInDeletedTree: boolean,
1273
-) {
1274
- if (enableTransitionTracing) {
1275
- const markerInstance: TracingMarkerInstance = abortedFiber.stateNode;
1276
- const markerTransitions = markerInstance.transitions;
1277
- const pendingBoundaries = markerInstance.pendingBoundaries;
1278
- if (markerTransitions !== null) {
1279
- // TODO: Refactor this code. Is there a way to move this code to
1280
- // the deletions phase instead of calculating it here while making sure
1281
- // complete is called appropriately?
1282
- deletedTransitions.forEach(transition => {
1283
- // If one of the transitions on the tracing marker is a transition
1284
- // that was in an aborted subtree, we will abort that tracing marker
1285
- if (
1286
- abortedFiber !== null &&
1287
- markerTransitions.has(transition) &&
1288
- (markerInstance.aborts === null ||
1289
- !markerInstance.aborts.includes(abort))
1290
- ) {
1291
- if (markerInstance.transitions !== null) {
1292
- if (markerInstance.aborts === null) {
1293
- markerInstance.aborts = [abort];
1294
- addMarkerIncompleteCallbackToPendingTransition(
1295
- abortedFiber.memoizedProps.name,
1296
- markerInstance.transitions,
1297
- markerInstance.aborts,
1298
- );
1299
- } else {
1300
- markerInstance.aborts.push(abort);
1301
- }
1302
-
1303
- // We only want to call onTransitionProgress when the marker hasn't been
1304
- // deleted
1305
- if (
1306
- deletedOffscreenInstance !== null &&
1307
- !isInDeletedTree &&
1308
- pendingBoundaries !== null &&
1309
- pendingBoundaries.has(deletedOffscreenInstance)
1310
- ) {
1311
- pendingBoundaries.delete(deletedOffscreenInstance);
1312
-
1313
- addMarkerProgressCallbackToPendingTransition(
1314
- abortedFiber.memoizedProps.name,
1315
- deletedTransitions,
1316
- pendingBoundaries,
1317
- );
1318
- }
1319
- }
1320
- }
1321
- });
1322
- }
1323
- }
1324
-}
1325
-
1326
-function abortParentMarkerTransitionsForDeletedFiber(
1327
- abortedFiber: Fiber,
1328
- abort: TransitionAbort,
1329
- deletedTransitions: Set<Transition>,
1330
- deletedOffscreenInstance: OffscreenInstance | null,
1331
- isInDeletedTree: boolean,
1332
-) {
1333
- if (enableTransitionTracing) {
1334
- // Find all pending markers that are waiting on child suspense boundaries in the
1335
- // aborted subtree and cancels them
1336
- let fiber: null | Fiber = abortedFiber;
1337
- while (fiber !== null) {
1338
- switch (fiber.tag) {
1339
- case TracingMarkerComponent:
1340
- abortTracingMarkerTransitions(
1341
- fiber,
1342
- abort,
1343
- deletedTransitions,
1344
- deletedOffscreenInstance,
1345
- isInDeletedTree,
1346
- );
1347
- break;
1348
- case HostRoot:
1349
- const root = fiber.stateNode;
1350
- abortRootTransitions(
1351
- root,
1352
- abort,
1353
- deletedTransitions,
1354
- deletedOffscreenInstance,
1355
- isInDeletedTree,
1356
- );
1357
-
1358
- break;
1359
- default:
1360
- break;
1361
- }
1362
-
1363
- fiber = fiber.return;
1364
- }
1365
- }
1366
-}
1367
-
1368
-function commitTransitionProgress(offscreenFiber: Fiber) {
1369
- if (enableTransitionTracing) {
1370
- // This function adds suspense boundaries to the root
1371
- // or tracing marker's pendingBoundaries map.
1372
- // When a suspense boundary goes from a resolved to a fallback
1373
- // state we add the boundary to the map, and when it goes from
1374
- // a fallback to a resolved state, we remove the boundary from
1375
- // the map.
1376
-
1377
- // We use stateNode on the Offscreen component as a stable object
1378
- // that doesnt change from render to render. This way we can
1379
- // distinguish between different Offscreen instances (vs. the same
1380
- // Offscreen instance with different fibers)
1381
- const offscreenInstance: OffscreenInstance = offscreenFiber.stateNode;
1382
-
1383
- let prevState: SuspenseState | null = null;
1384
- const previousFiber = offscreenFiber.alternate;
1385
- if (previousFiber !== null && previousFiber.memoizedState !== null) {
1386
- prevState = previousFiber.memoizedState;
1387
- }
1388
- const nextState: SuspenseState | null = offscreenFiber.memoizedState;
1389
-
1390
- const wasHidden = prevState !== null;
1391
- const isHidden = nextState !== null;
1392
-
1393
- const pendingMarkers = offscreenInstance._pendingMarkers;
1394
- // If there is a name on the suspense boundary, store that in
1395
- // the pending boundaries.
1396
- let name = null;
1397
- const parent = offscreenFiber.return;
1398
- if (
1399
- parent !== null &&
1400
- parent.tag === SuspenseComponent &&
1401
- parent.memoizedProps.unstable_name
1402
- ) {
1403
- name = parent.memoizedProps.unstable_name;
1404
- }
1405
-
1406
- if (!wasHidden && isHidden) {
1407
- // The suspense boundaries was just hidden. Add the boundary
1408
- // to the pending boundary set if it's there
1409
- if (pendingMarkers !== null) {
1410
- pendingMarkers.forEach(markerInstance => {
1411
- const pendingBoundaries = markerInstance.pendingBoundaries;
1412
- const transitions = markerInstance.transitions;
1413
- const markerName = markerInstance.name;
1414
- if (
1415
- pendingBoundaries !== null &&
1416
- !pendingBoundaries.has(offscreenInstance)
1417
- ) {
1418
- pendingBoundaries.set(offscreenInstance, {
1419
- name,
1420
- });
1421
- if (transitions !== null) {
1422
- if (
1423
- markerInstance.tag === TransitionTracingMarker &&
1424
- markerName !== null
1425
- ) {
1426
- addMarkerProgressCallbackToPendingTransition(
1427
- markerName,
1428
- transitions,
1429
- pendingBoundaries,
1430
- );
1431
- } else if (markerInstance.tag === TransitionRoot) {
1432
- transitions.forEach(transition => {
1433
- addTransitionProgressCallbackToPendingTransition(
1434
- transition,
1435
- pendingBoundaries,
1436
- );
1437
- });
1438
- }
1439
- }
1440
- }
1441
- });
1442
- }
1443
- } else if (wasHidden && !isHidden) {
1444
- // The suspense boundary went from hidden to visible. Remove
1445
- // the boundary from the pending suspense boundaries set
1446
- // if it's there
1447
- if (pendingMarkers !== null) {
1448
- pendingMarkers.forEach(markerInstance => {
1449
- const pendingBoundaries = markerInstance.pendingBoundaries;
1450
- const transitions = markerInstance.transitions;
1451
- const markerName = markerInstance.name;
1452
- if (
1453
- pendingBoundaries !== null &&
1454
- pendingBoundaries.has(offscreenInstance)
1455
- ) {
1456
- pendingBoundaries.delete(offscreenInstance);
1457
- if (transitions !== null) {
1458
- if (
1459
- markerInstance.tag === TransitionTracingMarker &&
1460
- markerName !== null
1461
- ) {
1462
- addMarkerProgressCallbackToPendingTransition(
1463
- markerName,
1464
- transitions,
1465
- pendingBoundaries,
1466
- );
1467
-
1468
- // If there are no more unresolved suspense boundaries, the interaction
1469
- // is considered finished
1470
- if (pendingBoundaries.size === 0) {
1471
- if (markerInstance.aborts === null) {
1472
- addMarkerCompleteCallbackToPendingTransition(
1473
- markerName,
1474
- transitions,
1475
- );
1476
- }
1477
- markerInstance.transitions = null;
1478
- markerInstance.pendingBoundaries = null;
1479
- markerInstance.aborts = null;
1480
- }
1481
- } else if (markerInstance.tag === TransitionRoot) {
1482
- transitions.forEach(transition => {
1483
- addTransitionProgressCallbackToPendingTransition(
1484
- transition,
1485
- pendingBoundaries,
1486
- );
1487
- });
1488
- }
1489
- }
1490
- }
1491
- });
1492
- }
1493
- }
1494
- }
1495
-}
1496
-
1497
-function hideOrUnhideAllChildren(finishedWork, isHidden) {
1498
- // Only hide or unhide the top-most host nodes.
1499
- let hostSubtreeRoot = null;
1500
-
1501
- if (supportsMutation) {
1502
- // We only have the top Fiber that was inserted but we need to recurse down its
1503
- // children to find all the terminal nodes.
1504
- let node: Fiber = finishedWork;
1505
- while (true) {
1506
- if (
1507
- node.tag === HostComponent ||
1508
- (enableFloat && supportsResources
1509
- ? node.tag === HostResource
1510
- : false) ||
1511
- (enableHostSingletons && supportsSingletons
1512
- ? node.tag === HostSingleton
1513
- : false)
1514
- ) {
1515
- if (hostSubtreeRoot === null) {
1516
- hostSubtreeRoot = node;
1517
- try {
1518
- const instance = node.stateNode;
1519
- if (isHidden) {
1520
- hideInstance(instance);
1521
- } else {
1522
- unhideInstance(node.stateNode, node.memoizedProps);
1523
- }
1524
- } catch (error) {
1525
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
1526
- }
1527
- }
1528
- } else if (node.tag === HostText) {
1529
- if (hostSubtreeRoot === null) {
1530
- try {
1531
- const instance = node.stateNode;
1532
- if (isHidden) {
1533
- hideTextInstance(instance);
1534
- } else {
1535
- unhideTextInstance(instance, node.memoizedProps);
1536
- }
1537
- } catch (error) {
1538
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
1539
- }
1540
- }
1541
- } else if (
1542
- (node.tag === OffscreenComponent ||
1543
- node.tag === LegacyHiddenComponent) &&
1544
- (node.memoizedState: OffscreenState) !== null &&
1545
- node !== finishedWork
1546
- ) {
1547
- // Found a nested Offscreen component that is hidden.
1548
- // Don't search any deeper. This tree should remain hidden.
1549
- } else if (node.child !== null) {
1550
- node.child.return = node;
1551
- node = node.child;
1552
- continue;
1553
- }
1554
-
1555
- if (node === finishedWork) {
1556
- return;
1557
- }
1558
- while (node.sibling === null) {
1559
- if (node.return === null || node.return === finishedWork) {
1560
- return;
1561
- }
1562
-
1563
- if (hostSubtreeRoot === node) {
1564
- hostSubtreeRoot = null;
1565
- }
1566
-
1567
- node = node.return;
1568
- }
1569
-
1570
- if (hostSubtreeRoot === node) {
1571
- hostSubtreeRoot = null;
1572
- }
1573
-
1574
- node.sibling.return = node.return;
1575
- node = node.sibling;
1576
- }
1577
- }
1578
-}
1579
-
1580
-function commitAttachRef(finishedWork: Fiber) {
1581
- const ref = finishedWork.ref;
1582
- if (ref !== null) {
1583
- const instance = finishedWork.stateNode;
1584
- let instanceToUse;
1585
- switch (finishedWork.tag) {
1586
- case HostResource:
1587
- case HostSingleton:
1588
- case HostComponent:
1589
- instanceToUse = getPublicInstance(instance);
1590
- break;
1591
- default:
1592
- instanceToUse = instance;
1593
- }
1594
- // Moved outside to ensure DCE works with this flag
1595
- if (enableScopeAPI && finishedWork.tag === ScopeComponent) {
1596
- instanceToUse = instance;
1597
- }
1598
- if (typeof ref === 'function') {
1599
- if (shouldProfile(finishedWork)) {
1600
- try {
1601
- startLayoutEffectTimer();
1602
- finishedWork.refCleanup = ref(instanceToUse);
1603
- } finally {
1604
- recordLayoutEffectDuration(finishedWork);
1605
- }
1606
- } else {
1607
- finishedWork.refCleanup = ref(instanceToUse);
1608
- }
1609
- } else {
1610
- if (__DEV__) {
1611
- if (!ref.hasOwnProperty('current')) {
1612
- console.error(
1613
- 'Unexpected ref object provided for %s. ' +
1614
- 'Use either a ref-setter function or React.createRef().',
1615
- getComponentNameFromFiber(finishedWork),
1616
- );
1617
- }
1618
- }
1619
-
1620
- // $FlowFixMe unable to narrow type to the non-function case
1621
- ref.current = instanceToUse;
1622
- }
1623
- }
1624
-}
1625
-
1626
-function detachFiberMutation(fiber: Fiber) {
1627
- // Cut off the return pointer to disconnect it from the tree.
1628
- // This enables us to detect and warn against state updates on an unmounted component.
1629
- // It also prevents events from bubbling from within disconnected components.
1630
- //
1631
- // Ideally, we should also clear the child pointer of the parent alternate to let this
1632
- // get GC:ed but we don't know which for sure which parent is the current
1633
- // one so we'll settle for GC:ing the subtree of this child.
1634
- // This child itself will be GC:ed when the parent updates the next time.
1635
- //
1636
- // Note that we can't clear child or sibling pointers yet.
1637
- // They're needed for passive effects and for findDOMNode.
1638
- // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects).
1639
- //
1640
- // Don't reset the alternate yet, either. We need that so we can detach the
1641
- // alternate's fields in the passive phase. Clearing the return pointer is
1642
- // sufficient for findDOMNode semantics.
1643
- const alternate = fiber.alternate;
1644
- if (alternate !== null) {
1645
- alternate.return = null;
1646
- }
1647
- fiber.return = null;
1648
-}
1649
-
1650
-function detachFiberAfterEffects(fiber: Fiber) {
1651
- const alternate = fiber.alternate;
1652
- if (alternate !== null) {
1653
- fiber.alternate = null;
1654
- detachFiberAfterEffects(alternate);
1655
- }
1656
-
1657
- // Note: Defensively using negation instead of < in case
1658
- // `deletedTreeCleanUpLevel` is undefined.
1659
- if (!(deletedTreeCleanUpLevel >= 2)) {
1660
- // This is the default branch (level 0).
1661
- fiber.child = null;
1662
- fiber.deletions = null;
1663
- fiber.dependencies = null;
1664
- fiber.memoizedProps = null;
1665
- fiber.memoizedState = null;
1666
- fiber.pendingProps = null;
1667
- fiber.sibling = null;
1668
- fiber.stateNode = null;
1669
- fiber.updateQueue = null;
1670
-
1671
- if (__DEV__) {
1672
- fiber._debugOwner = null;
1673
- }
1674
- } else {
1675
- // Clear cyclical Fiber fields. This level alone is designed to roughly
1676
- // approximate the planned Fiber refactor. In that world, `setState` will be
1677
- // bound to a special "instance" object instead of a Fiber. The Instance
1678
- // object will not have any of these fields. It will only be connected to
1679
- // the fiber tree via a single link at the root. So if this level alone is
1680
- // sufficient to fix memory issues, that bodes well for our plans.
1681
- fiber.child = null;
1682
- fiber.deletions = null;
1683
- fiber.sibling = null;
1684
-
1685
- // The `stateNode` is cyclical because on host nodes it points to the host
1686
- // tree, which has its own pointers to children, parents, and siblings.
1687
- // The other host nodes also point back to fibers, so we should detach that
1688
- // one, too.
1689
- if (fiber.tag === HostComponent) {
1690
- const hostInstance: Instance = fiber.stateNode;
1691
- if (hostInstance !== null) {
1692
- detachDeletedInstance(hostInstance);
1693
- }
1694
- }
1695
- fiber.stateNode = null;
1696
-
1697
- // I'm intentionally not clearing the `return` field in this level. We
1698
- // already disconnect the `return` pointer at the root of the deleted
1699
- // subtree (in `detachFiberMutation`). Besides, `return` by itself is not
1700
- // cyclical — it's only cyclical when combined with `child`, `sibling`, and
1701
- // `alternate`. But we'll clear it in the next level anyway, just in case.
1702
-
1703
- if (__DEV__) {
1704
- fiber._debugOwner = null;
1705
- }
1706
-
1707
- if (deletedTreeCleanUpLevel >= 3) {
1708
- // Theoretically, nothing in here should be necessary, because we already
1709
- // disconnected the fiber from the tree. So even if something leaks this
1710
- // particular fiber, it won't leak anything else
1711
- //
1712
- // The purpose of this branch is to be super aggressive so we can measure
1713
- // if there's any difference in memory impact. If there is, that could
1714
- // indicate a React leak we don't know about.
1715
- fiber.return = null;
1716
- fiber.dependencies = null;
1717
- fiber.memoizedProps = null;
1718
- fiber.memoizedState = null;
1719
- fiber.pendingProps = null;
1720
- fiber.stateNode = null;
1721
- // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead.
1722
- fiber.updateQueue = null;
1723
- }
1724
- }
1725
-}
1726
-
1727
-function emptyPortalContainer(current: Fiber) {
1728
- if (!supportsPersistence) {
1729
- return;
1730
- }
1731
-
1732
- const portal: {
1733
- containerInfo: Container,
1734
- pendingChildren: ChildSet,
1735
- ...
1736
- } = current.stateNode;
1737
- const {containerInfo} = portal;
1738
- const emptyChildSet = createContainerChildSet(containerInfo);
1739
- replaceContainerChildren(containerInfo, emptyChildSet);
1740
-}
1741
-
1742
-function getHostParentFiber(fiber: Fiber): Fiber {
1743
- let parent = fiber.return;
1744
- while (parent !== null) {
1745
- if (isHostParent(parent)) {
1746
- return parent;
1747
- }
1748
- parent = parent.return;
1749
- }
1750
-
1751
- throw new Error(
1752
- 'Expected to find a host parent. This error is likely caused by a bug ' +
1753
- 'in React. Please file an issue.',
1754
- );
1755
-}
1756
-
1757
-function isHostParent(fiber: Fiber): boolean {
1758
- return (
1759
- fiber.tag === HostComponent ||
1760
- fiber.tag === HostRoot ||
1761
- (enableFloat && supportsResources ? fiber.tag === HostResource : false) ||
1762
- (enableHostSingletons && supportsSingletons
1763
- ? fiber.tag === HostSingleton
1764
- : false) ||
1765
- fiber.tag === HostPortal
1766
- );
1767
-}
1768
-
1769
-function getHostSibling(fiber: Fiber): ?Instance {
1770
- // We're going to search forward into the tree until we find a sibling host
1771
- // node. Unfortunately, if multiple insertions are done in a row we have to
1772
- // search past them. This leads to exponential search for the next sibling.
1773
- // TODO: Find a more efficient way to do this.
1774
- let node: Fiber = fiber;
1775
- siblings: while (true) {
1776
- // If we didn't find anything, let's try the next sibling.
1777
- while (node.sibling === null) {
1778
- if (node.return === null || isHostParent(node.return)) {
1779
- // If we pop out of the root or hit the parent the fiber we are the
1780
- // last sibling.
1781
- return null;
1782
- }
1783
- // $FlowFixMe[incompatible-type] found when upgrading Flow
1784
- node = node.return;
1785
- }
1786
- node.sibling.return = node.return;
1787
- node = node.sibling;
1788
- while (
1789
- node.tag !== HostComponent &&
1790
- node.tag !== HostText &&
1791
- (!(enableHostSingletons && supportsSingletons)
1792
- ? true
1793
- : node.tag !== HostSingleton) &&
1794
- node.tag !== DehydratedFragment
1795
- ) {
1796
- // If it is not host node and, we might have a host node inside it.
1797
- // Try to search down until we find one.
1798
- if (node.flags & Placement) {
1799
- // If we don't have a child, try the siblings instead.
1800
- continue siblings;
1801
- }
1802
- // If we don't have a child, try the siblings instead.
1803
- // We also skip portals because they are not part of this host tree.
1804
- if (node.child === null || node.tag === HostPortal) {
1805
- continue siblings;
1806
- } else {
1807
- node.child.return = node;
1808
- node = node.child;
1809
- }
1810
- }
1811
- // Check if this host node is stable or about to be placed.
1812
- if (!(node.flags & Placement)) {
1813
- // Found it!
1814
- return node.stateNode;
1815
- }
1816
- }
1817
-}
1818
-
1819
-function commitPlacement(finishedWork: Fiber): void {
1820
- if (!supportsMutation) {
1821
- return;
1822
- }
1823
-
1824
- if (enableHostSingletons && supportsSingletons) {
1825
- if (finishedWork.tag === HostSingleton) {
1826
- // Singletons are already in the Host and don't need to be placed
1827
- // Since they operate somewhat like Portals though their children will
1828
- // have Placement and will get placed inside them
1829
- return;
1830
- }
1831
- }
1832
- // Recursively insert all host nodes into the parent.
1833
- const parentFiber = getHostParentFiber(finishedWork);
1834
-
1835
- switch (parentFiber.tag) {
1836
- case HostSingleton: {
1837
- if (enableHostSingletons && supportsSingletons) {
1838
- const parent: Instance = parentFiber.stateNode;
1839
- const before = getHostSibling(finishedWork);
1840
- // We only have the top Fiber that was inserted but we need to recurse down its
1841
- // children to find all the terminal nodes.
1842
- insertOrAppendPlacementNode(finishedWork, before, parent);
1843
- break;
1844
- }
1845
- }
1846
- // eslint-disable-next-line no-fallthrough
1847
- case HostComponent: {
1848
- const parent: Instance = parentFiber.stateNode;
1849
- if (parentFiber.flags & ContentReset) {
1850
- // Reset the text content of the parent before doing any insertions
1851
- resetTextContent(parent);
1852
- // Clear ContentReset from the effect tag
1853
- parentFiber.flags &= ~ContentReset;
1854
- }
1855
-
1856
- const before = getHostSibling(finishedWork);
1857
- // We only have the top Fiber that was inserted but we need to recurse down its
1858
- // children to find all the terminal nodes.
1859
- insertOrAppendPlacementNode(finishedWork, before, parent);
1860
- break;
1861
- }
1862
- case HostRoot:
1863
- case HostPortal: {
1864
- const parent: Container = parentFiber.stateNode.containerInfo;
1865
- const before = getHostSibling(finishedWork);
1866
- insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);
1867
- break;
1868
- }
1869
- // eslint-disable-next-line-no-fallthrough
1870
- default:
1871
- throw new Error(
1872
- 'Invalid host parent fiber. This error is likely caused by a bug ' +
1873
- 'in React. Please file an issue.',
1874
- );
1875
- }
1876
-}
1877
-
1878
-function insertOrAppendPlacementNodeIntoContainer(
1879
- node: Fiber,
1880
- before: ?Instance,
1881
- parent: Container,
1882
-): void {
1883
- const {tag} = node;
1884
- const isHost = tag === HostComponent || tag === HostText;
1885
- if (isHost) {
1886
- const stateNode = node.stateNode;
1887
- if (before) {
1888
- insertInContainerBefore(parent, stateNode, before);
1889
- } else {
1890
- appendChildToContainer(parent, stateNode);
1891
- }
1892
- } else if (
1893
- tag === HostPortal ||
1894
- (enableHostSingletons && supportsSingletons ? tag === HostSingleton : false)
1895
- ) {
1896
- // If the insertion itself is a portal, then we don't want to traverse
1897
- // down its children. Instead, we'll get insertions from each child in
1898
- // the portal directly.
1899
- // If the insertion is a HostSingleton then it will be placed independently
1900
- } else {
1901
- const child = node.child;
1902
- if (child !== null) {
1903
- insertOrAppendPlacementNodeIntoContainer(child, before, parent);
1904
- let sibling = child.sibling;
1905
- while (sibling !== null) {
1906
- insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
1907
- sibling = sibling.sibling;
1908
- }
1909
- }
1910
- }
1911
-}
1912
-
1913
-function insertOrAppendPlacementNode(
1914
- node: Fiber,
1915
- before: ?Instance,
1916
- parent: Instance,
1917
-): void {
1918
- const {tag} = node;
1919
- const isHost = tag === HostComponent || tag === HostText;
1920
- if (isHost) {
1921
- const stateNode = node.stateNode;
1922
- if (before) {
1923
- insertBefore(parent, stateNode, before);
1924
- } else {
1925
- appendChild(parent, stateNode);
1926
- }
1927
- } else if (
1928
- tag === HostPortal ||
1929
- (enableHostSingletons && supportsSingletons ? tag === HostSingleton : false)
1930
- ) {
1931
- // If the insertion itself is a portal, then we don't want to traverse
1932
- // down its children. Instead, we'll get insertions from each child in
1933
- // the portal directly.
1934
- // If the insertion is a HostSingleton then it will be placed independently
1935
- } else {
1936
- const child = node.child;
1937
- if (child !== null) {
1938
- insertOrAppendPlacementNode(child, before, parent);
1939
- let sibling = child.sibling;
1940
- while (sibling !== null) {
1941
- insertOrAppendPlacementNode(sibling, before, parent);
1942
- sibling = sibling.sibling;
1943
- }
1944
- }
1945
- }
1946
-}
1947
-
1948
-// These are tracked on the stack as we recursively traverse a
1949
-// deleted subtree.
1950
-// TODO: Update these during the whole mutation phase, not just during
1951
-// a deletion.
1952
-let hostParent: Instance | Container | null = null;
1953
-let hostParentIsContainer: boolean = false;
1954
-
1955
-function commitDeletionEffects(
1956
- root: FiberRoot,
1957
- returnFiber: Fiber,
1958
- deletedFiber: Fiber,
1959
-) {
1960
- if (supportsMutation) {
1961
- // We only have the top Fiber that was deleted but we need to recurse down its
1962
- // children to find all the terminal nodes.
1963
-
1964
- // Recursively delete all host nodes from the parent, detach refs, clean
1965
- // up mounted layout effects, and call componentWillUnmount.
1966
-
1967
- // We only need to remove the topmost host child in each branch. But then we
1968
- // still need to keep traversing to unmount effects, refs, and cWU. TODO: We
1969
- // could split this into two separate traversals functions, where the second
1970
- // one doesn't include any removeChild logic. This is maybe the same
1971
- // function as "disappearLayoutEffects" (or whatever that turns into after
1972
- // the layout phase is refactored to use recursion).
1973
-
1974
- // Before starting, find the nearest host parent on the stack so we know
1975
- // which instance/container to remove the children from.
1976
- // TODO: Instead of searching up the fiber return path on every deletion, we
1977
- // can track the nearest host component on the JS stack as we traverse the
1978
- // tree during the commit phase. This would make insertions faster, too.
1979
- let parent: null | Fiber = returnFiber;
1980
- findParent: while (parent !== null) {
1981
- switch (parent.tag) {
1982
- case HostSingleton:
1983
- case HostComponent: {
1984
- hostParent = parent.stateNode;
1985
- hostParentIsContainer = false;
1986
- break findParent;
1987
- }
1988
- case HostRoot: {
1989
- hostParent = parent.stateNode.containerInfo;
1990
- hostParentIsContainer = true;
1991
- break findParent;
1992
- }
1993
- case HostPortal: {
1994
- hostParent = parent.stateNode.containerInfo;
1995
- hostParentIsContainer = true;
1996
- break findParent;
1997
- }
1998
- }
1999
- parent = parent.return;
2000
- }
2001
- if (hostParent === null) {
2002
- throw new Error(
2003
- 'Expected to find a host parent. This error is likely caused by ' +
2004
- 'a bug in React. Please file an issue.',
2005
- );
2006
- }
2007
-
2008
- commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
2009
- hostParent = null;
2010
- hostParentIsContainer = false;
2011
- } else {
2012
- // Detach refs and call componentWillUnmount() on the whole subtree.
2013
- commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
2014
- }
2015
-
2016
- detachFiberMutation(deletedFiber);
2017
-}
2018
-
2019
-function recursivelyTraverseDeletionEffects(
2020
- finishedRoot,
2021
- nearestMountedAncestor,
2022
- parent,
2023
-) {
2024
- // TODO: Use a static flag to skip trees that don't have unmount effects
2025
- let child = parent.child;
2026
- while (child !== null) {
2027
- commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child);
2028
- child = child.sibling;
2029
- }
2030
-}
2031
-
2032
-function commitDeletionEffectsOnFiber(
2033
- finishedRoot: FiberRoot,
2034
- nearestMountedAncestor: Fiber,
2035
- deletedFiber: Fiber,
2036
-) {
2037
- onCommitUnmount(deletedFiber);
2038
-
2039
- // The cases in this outer switch modify the stack before they traverse
2040
- // into their subtree. There are simpler cases in the inner switch
2041
- // that don't modify the stack.
2042
- switch (deletedFiber.tag) {
2043
- case HostResource: {
2044
- if (enableFloat && supportsResources) {
2045
- if (!offscreenSubtreeWasHidden) {
2046
- safelyDetachRef(deletedFiber, nearestMountedAncestor);
2047
- }
2048
- recursivelyTraverseDeletionEffects(
2049
- finishedRoot,
2050
- nearestMountedAncestor,
2051
- deletedFiber,
2052
- );
2053
- if (deletedFiber.memoizedState) {
2054
- releaseResource(deletedFiber.memoizedState);
2055
- }
2056
- return;
2057
- }
2058
- }
2059
- // eslint-disable-next-line no-fallthrough
2060
- case HostSingleton: {
2061
- if (enableHostSingletons && supportsSingletons) {
2062
- if (!offscreenSubtreeWasHidden) {
2063
- safelyDetachRef(deletedFiber, nearestMountedAncestor);
2064
- }
2065
-
2066
- const prevHostParent = hostParent;
2067
- const prevHostParentIsContainer = hostParentIsContainer;
2068
- hostParent = deletedFiber.stateNode;
2069
- recursivelyTraverseDeletionEffects(
2070
- finishedRoot,
2071
- nearestMountedAncestor,
2072
- deletedFiber,
2073
- );
2074
-
2075
- // Normally this is called in passive unmount effect phase however with
2076
- // HostSingleton we warn if you acquire one that is already associated to
2077
- // a different fiber. To increase our chances of avoiding this, specifically
2078
- // if you keyed a HostSingleton so there will be a delete followed by a Placement
2079
- // we treat detach eagerly here
2080
- releaseSingletonInstance(deletedFiber.stateNode);
2081
-
2082
- hostParent = prevHostParent;
2083
- hostParentIsContainer = prevHostParentIsContainer;
2084
-
2085
- return;
2086
- }
2087
- }
2088
- // eslint-disable-next-line no-fallthrough
2089
- case HostComponent: {
2090
- if (!offscreenSubtreeWasHidden) {
2091
- safelyDetachRef(deletedFiber, nearestMountedAncestor);
2092
- }
2093
- // Intentional fallthrough to next branch
2094
- }
2095
- // eslint-disable-next-line-no-fallthrough
2096
- case HostText: {
2097
- // We only need to remove the nearest host child. Set the host parent
2098
- // to `null` on the stack to indicate that nested children don't
2099
- // need to be removed.
2100
- if (supportsMutation) {
2101
- const prevHostParent = hostParent;
2102
- const prevHostParentIsContainer = hostParentIsContainer;
2103
- hostParent = null;
2104
- recursivelyTraverseDeletionEffects(
2105
- finishedRoot,
2106
- nearestMountedAncestor,
2107
- deletedFiber,
2108
- );
2109
- hostParent = prevHostParent;
2110
- hostParentIsContainer = prevHostParentIsContainer;
2111
-
2112
- if (hostParent !== null) {
2113
- // Now that all the child effects have unmounted, we can remove the
2114
- // node from the tree.
2115
- if (hostParentIsContainer) {
2116
- removeChildFromContainer(
2117
- ((hostParent: any): Container),
2118
- (deletedFiber.stateNode: Instance | TextInstance),
2119
- );
2120
- } else {
2121
- removeChild(
2122
- ((hostParent: any): Instance),
2123
- (deletedFiber.stateNode: Instance | TextInstance),
2124
- );
2125
- }
2126
- }
2127
- } else {
2128
- recursivelyTraverseDeletionEffects(
2129
- finishedRoot,
2130
- nearestMountedAncestor,
2131
- deletedFiber,
2132
- );
2133
- }
2134
- return;
2135
- }
2136
- case DehydratedFragment: {
2137
- if (enableSuspenseCallback) {
2138
- const hydrationCallbacks = finishedRoot.hydrationCallbacks;
2139
- if (hydrationCallbacks !== null) {
2140
- const onDeleted = hydrationCallbacks.onDeleted;
2141
- if (onDeleted) {
2142
- onDeleted((deletedFiber.stateNode: SuspenseInstance));
2143
- }
2144
- }
2145
- }
2146
-
2147
- // Dehydrated fragments don't have any children
2148
-
2149
- // Delete the dehydrated suspense boundary and all of its content.
2150
- if (supportsMutation) {
2151
- if (hostParent !== null) {
2152
- if (hostParentIsContainer) {
2153
- clearSuspenseBoundaryFromContainer(
2154
- ((hostParent: any): Container),
2155
- (deletedFiber.stateNode: SuspenseInstance),
2156
- );
2157
- } else {
2158
- clearSuspenseBoundary(
2159
- ((hostParent: any): Instance),
2160
- (deletedFiber.stateNode: SuspenseInstance),
2161
- );
2162
- }
2163
- }
2164
- }
2165
- return;
2166
- }
2167
- case HostPortal: {
2168
- if (supportsMutation) {
2169
- // When we go into a portal, it becomes the parent to remove from.
2170
- const prevHostParent = hostParent;
2171
- const prevHostParentIsContainer = hostParentIsContainer;
2172
- hostParent = deletedFiber.stateNode.containerInfo;
2173
- hostParentIsContainer = true;
2174
- recursivelyTraverseDeletionEffects(
2175
- finishedRoot,
2176
- nearestMountedAncestor,
2177
- deletedFiber,
2178
- );
2179
- hostParent = prevHostParent;
2180
- hostParentIsContainer = prevHostParentIsContainer;
2181
- } else {
2182
- emptyPortalContainer(deletedFiber);
2183
-
2184
- recursivelyTraverseDeletionEffects(
2185
- finishedRoot,
2186
- nearestMountedAncestor,
2187
- deletedFiber,
2188
- );
2189
- }
2190
- return;
2191
- }
2192
- case FunctionComponent:
2193
- case ForwardRef:
2194
- case MemoComponent:
2195
- case SimpleMemoComponent: {
2196
- if (!offscreenSubtreeWasHidden) {
2197
- const updateQueue: FunctionComponentUpdateQueue | null = (deletedFiber.updateQueue: any);
2198
- if (updateQueue !== null) {
2199
- const lastEffect = updateQueue.lastEffect;
2200
- if (lastEffect !== null) {
2201
- const firstEffect = lastEffect.next;
2202
-
2203
- let effect = firstEffect;
2204
- do {
2205
- const {destroy, tag} = effect;
2206
- if (destroy !== undefined) {
2207
- if ((tag & HookInsertion) !== NoHookEffect) {
2208
- safelyCallDestroy(
2209
- deletedFiber,
2210
- nearestMountedAncestor,
2211
- destroy,
2212
- );
2213
- } else if ((tag & HookLayout) !== NoHookEffect) {
2214
- if (enableSchedulingProfiler) {
2215
- markComponentLayoutEffectUnmountStarted(deletedFiber);
2216
- }
2217
-
2218
- if (shouldProfile(deletedFiber)) {
2219
- startLayoutEffectTimer();
2220
- safelyCallDestroy(
2221
- deletedFiber,
2222
- nearestMountedAncestor,
2223
- destroy,
2224
- );
2225
- recordLayoutEffectDuration(deletedFiber);
2226
- } else {
2227
- safelyCallDestroy(
2228
- deletedFiber,
2229
- nearestMountedAncestor,
2230
- destroy,
2231
- );
2232
- }
2233
-
2234
- if (enableSchedulingProfiler) {
2235
- markComponentLayoutEffectUnmountStopped();
2236
- }
2237
- }
2238
- }
2239
- effect = effect.next;
2240
- } while (effect !== firstEffect);
2241
- }
2242
- }
2243
- }
2244
-
2245
- recursivelyTraverseDeletionEffects(
2246
- finishedRoot,
2247
- nearestMountedAncestor,
2248
- deletedFiber,
2249
- );
2250
- return;
2251
- }
2252
- case ClassComponent: {
2253
- if (!offscreenSubtreeWasHidden) {
2254
- safelyDetachRef(deletedFiber, nearestMountedAncestor);
2255
- const instance = deletedFiber.stateNode;
2256
- if (typeof instance.componentWillUnmount === 'function') {
2257
- safelyCallComponentWillUnmount(
2258
- deletedFiber,
2259
- nearestMountedAncestor,
2260
- instance,
2261
- );
2262
- }
2263
- }
2264
- recursivelyTraverseDeletionEffects(
2265
- finishedRoot,
2266
- nearestMountedAncestor,
2267
- deletedFiber,
2268
- );
2269
- return;
2270
- }
2271
- case ScopeComponent: {
2272
- if (enableScopeAPI) {
2273
- safelyDetachRef(deletedFiber, nearestMountedAncestor);
2274
- }
2275
- recursivelyTraverseDeletionEffects(
2276
- finishedRoot,
2277
- nearestMountedAncestor,
2278
- deletedFiber,
2279
- );
2280
- return;
2281
- }
2282
- case OffscreenComponent: {
2283
- safelyDetachRef(deletedFiber, nearestMountedAncestor);
2284
- if (deletedFiber.mode & ConcurrentMode) {
2285
- // If this offscreen component is hidden, we already unmounted it. Before
2286
- // deleting the children, track that it's already unmounted so that we
2287
- // don't attempt to unmount the effects again.
2288
- // TODO: If the tree is hidden, in most cases we should be able to skip
2289
- // over the nested children entirely. An exception is we haven't yet found
2290
- // the topmost host node to delete, which we already track on the stack.
2291
- // But the other case is portals, which need to be detached no matter how
2292
- // deeply they are nested. We should use a subtree flag to track whether a
2293
- // subtree includes a nested portal.
2294
- const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
2295
- offscreenSubtreeWasHidden =
2296
- prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null;
2297
-
2298
- recursivelyTraverseDeletionEffects(
2299
- finishedRoot,
2300
- nearestMountedAncestor,
2301
- deletedFiber,
2302
- );
2303
- offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
2304
- } else {
2305
- recursivelyTraverseDeletionEffects(
2306
- finishedRoot,
2307
- nearestMountedAncestor,
2308
- deletedFiber,
2309
- );
2310
- }
2311
- break;
2312
- }
2313
- default: {
2314
- recursivelyTraverseDeletionEffects(
2315
- finishedRoot,
2316
- nearestMountedAncestor,
2317
- deletedFiber,
2318
- );
2319
- return;
2320
- }
2321
- }
2322
-}
2323
-function commitSuspenseCallback(finishedWork: Fiber) {
2324
- // TODO: Move this to passive phase
2325
- const newState: SuspenseState | null = finishedWork.memoizedState;
2326
- if (enableSuspenseCallback && newState !== null) {
2327
- const suspenseCallback = finishedWork.memoizedProps.suspenseCallback;
2328
- if (typeof suspenseCallback === 'function') {
2329
- const wakeables: Set<Wakeable> | null = (finishedWork.updateQueue: any);
2330
- if (wakeables !== null) {
2331
- suspenseCallback(new Set(wakeables));
2332
- }
2333
- } else if (__DEV__) {
2334
- if (suspenseCallback !== undefined) {
2335
- console.error('Unexpected type for suspenseCallback.');
2336
- }
2337
- }
2338
- }
2339
-}
2340
-
2341
-function commitSuspenseHydrationCallbacks(
2342
- finishedRoot: FiberRoot,
2343
- finishedWork: Fiber,
2344
-) {
2345
- if (!supportsHydration) {
2346
- return;
2347
- }
2348
- const newState: SuspenseState | null = finishedWork.memoizedState;
2349
- if (newState === null) {
2350
- const current = finishedWork.alternate;
2351
- if (current !== null) {
2352
- const prevState: SuspenseState | null = current.memoizedState;
2353
- if (prevState !== null) {
2354
- const suspenseInstance = prevState.dehydrated;
2355
- if (suspenseInstance !== null) {
2356
- try {
2357
- commitHydratedSuspenseInstance(suspenseInstance);
2358
- if (enableSuspenseCallback) {
2359
- const hydrationCallbacks = finishedRoot.hydrationCallbacks;
2360
- if (hydrationCallbacks !== null) {
2361
- const onHydrated = hydrationCallbacks.onHydrated;
2362
- if (onHydrated) {
2363
- onHydrated(suspenseInstance);
2364
- }
2365
- }
2366
- }
2367
- } catch (error) {
2368
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2369
- }
2370
- }
2371
- }
2372
- }
2373
- }
2374
-}
2375
-
2376
-function getRetryCache(finishedWork) {
2377
- // TODO: Unify the interface for the retry cache so we don't have to switch
2378
- // on the tag like this.
2379
- switch (finishedWork.tag) {
2380
- case SuspenseComponent:
2381
- case SuspenseListComponent: {
2382
- let retryCache = finishedWork.stateNode;
2383
- if (retryCache === null) {
2384
- retryCache = finishedWork.stateNode = new PossiblyWeakSet();
2385
- }
2386
- return retryCache;
2387
- }
2388
- case OffscreenComponent: {
2389
- const instance: OffscreenInstance = finishedWork.stateNode;
2390
- // $FlowFixMe[incompatible-type-arg] found when upgrading Flow
2391
- let retryCache: null | Set<Wakeable> | WeakSet<Wakeable> =
2392
- // $FlowFixMe[incompatible-type] found when upgrading Flow
2393
- instance._retryCache;
2394
- if (retryCache === null) {
2395
- // $FlowFixMe[incompatible-type]
2396
- retryCache = instance._retryCache = new PossiblyWeakSet();
2397
- }
2398
- return retryCache;
2399
- }
2400
- default: {
2401
- throw new Error(
2402
- `Unexpected Suspense handler tag (${finishedWork.tag}). This is a ` +
2403
- 'bug in React.',
2404
- );
2405
- }
2406
- }
2407
-}
2408
-
2409
-export function detachOffscreenInstance(instance: OffscreenInstance): void {
2410
- const currentOffscreenFiber = instance._current;
2411
- if (currentOffscreenFiber === null) {
2412
- throw new Error(
2413
- 'Calling Offscreen.detach before instance handle has been set.',
2414
- );
2415
- }
2416
-
2417
- const executionContext = getExecutionContext();
2418
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
2419
- scheduleMicrotask(() => {
2420
- instance._visibility |= OffscreenDetached;
2421
- disappearLayoutEffects(currentOffscreenFiber);
2422
- disconnectPassiveEffect(currentOffscreenFiber);
2423
- });
2424
- } else {
2425
- instance._visibility |= OffscreenDetached;
2426
- disappearLayoutEffects(currentOffscreenFiber);
2427
- disconnectPassiveEffect(currentOffscreenFiber);
2428
- }
2429
-}
2430
-
2431
-function attachSuspenseRetryListeners(
2432
- finishedWork: Fiber,
2433
- wakeables: Set<Wakeable>,
2434
-) {
2435
- // If this boundary just timed out, then it will have a set of wakeables.
2436
- // For each wakeable, attach a listener so that when it resolves, React
2437
- // attempts to re-render the boundary in the primary (pre-timeout) state.
2438
- const retryCache = getRetryCache(finishedWork);
2439
- wakeables.forEach(wakeable => {
2440
- // Memoize using the boundary fiber to prevent redundant listeners.
2441
- const retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
2442
- if (!retryCache.has(wakeable)) {
2443
- retryCache.add(wakeable);
2444
-
2445
- if (enableUpdaterTracking) {
2446
- if (isDevToolsPresent) {
2447
- if (inProgressLanes !== null && inProgressRoot !== null) {
2448
- // If we have pending work still, associate the original updaters with it.
2449
- restorePendingUpdaters(inProgressRoot, inProgressLanes);
2450
- } else {
2451
- throw Error(
2452
- 'Expected finished root and lanes to be set. This is a bug in React.',
2453
- );
2454
- }
2455
- }
2456
- }
2457
-
2458
- wakeable.then(retry, retry);
2459
- }
2460
- });
2461
-}
2462
-
2463
-// This function detects when a Suspense boundary goes from visible to hidden.
2464
-// It returns false if the boundary is already hidden.
2465
-// TODO: Use an effect tag.
2466
-export function isSuspenseBoundaryBeingHidden(
2467
- current: Fiber | null,
2468
- finishedWork: Fiber,
2469
-): boolean {
2470
- if (current !== null) {
2471
- const oldState: SuspenseState | null = current.memoizedState;
2472
- if (oldState === null || oldState.dehydrated !== null) {
2473
- const newState: SuspenseState | null = finishedWork.memoizedState;
2474
- return newState !== null && newState.dehydrated === null;
2475
- }
2476
- }
2477
- return false;
2478
-}
2479
-
2480
-export function commitMutationEffects(
2481
- root: FiberRoot,
2482
- finishedWork: Fiber,
2483
- committedLanes: Lanes,
2484
-) {
2485
- inProgressLanes = committedLanes;
2486
- inProgressRoot = root;
2487
-
2488
- setCurrentDebugFiberInDEV(finishedWork);
2489
- commitMutationEffectsOnFiber(finishedWork, root, committedLanes);
2490
- setCurrentDebugFiberInDEV(finishedWork);
2491
-
2492
- inProgressLanes = null;
2493
- inProgressRoot = null;
2494
-}
2495
-
2496
-function recursivelyTraverseMutationEffects(
2497
- root: FiberRoot,
2498
- parentFiber: Fiber,
2499
- lanes: Lanes,
2500
-) {
2501
- // Deletions effects can be scheduled on any fiber type. They need to happen
2502
- // before the children effects hae fired.
2503
- const deletions = parentFiber.deletions;
2504
- if (deletions !== null) {
2505
- for (let i = 0; i < deletions.length; i++) {
2506
- const childToDelete = deletions[i];
2507
- try {
2508
- commitDeletionEffects(root, parentFiber, childToDelete);
2509
- } catch (error) {
2510
- captureCommitPhaseError(childToDelete, parentFiber, error);
2511
- }
2512
- }
2513
- }
2514
-
2515
- const prevDebugFiber = getCurrentDebugFiberInDEV();
2516
- if (parentFiber.subtreeFlags & MutationMask) {
2517
- let child = parentFiber.child;
2518
- while (child !== null) {
2519
- setCurrentDebugFiberInDEV(child);
2520
- commitMutationEffectsOnFiber(child, root, lanes);
2521
- child = child.sibling;
2522
- }
2523
- }
2524
- setCurrentDebugFiberInDEV(prevDebugFiber);
2525
-}
2526
-
2527
-function commitMutationEffectsOnFiber(
2528
- finishedWork: Fiber,
2529
- root: FiberRoot,
2530
- lanes: Lanes,
2531
-) {
2532
- const current = finishedWork.alternate;
2533
- const flags = finishedWork.flags;
2534
-
2535
- // The effect flag should be checked *after* we refine the type of fiber,
2536
- // because the fiber tag is more specific. An exception is any flag related
2537
- // to reconciliation, because those can be set on all fiber types.
2538
- switch (finishedWork.tag) {
2539
- case FunctionComponent:
2540
- case ForwardRef:
2541
- case MemoComponent:
2542
- case SimpleMemoComponent: {
2543
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2544
- commitReconciliationEffects(finishedWork);
2545
-
2546
- if (flags & Update) {
2547
- try {
2548
- commitHookEffectListUnmount(
2549
- HookInsertion | HookHasEffect,
2550
- finishedWork,
2551
- finishedWork.return,
2552
- );
2553
- commitHookEffectListMount(
2554
- HookInsertion | HookHasEffect,
2555
- finishedWork,
2556
- );
2557
- } catch (error) {
2558
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2559
- }
2560
- // Layout effects are destroyed during the mutation phase so that all
2561
- // destroy functions for all fibers are called before any create functions.
2562
- // This prevents sibling component effects from interfering with each other,
2563
- // e.g. a destroy function in one component should never override a ref set
2564
- // by a create function in another component during the same commit.
2565
- if (shouldProfile(finishedWork)) {
2566
- try {
2567
- startLayoutEffectTimer();
2568
- commitHookEffectListUnmount(
2569
- HookLayout | HookHasEffect,
2570
- finishedWork,
2571
- finishedWork.return,
2572
- );
2573
- } catch (error) {
2574
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2575
- }
2576
- recordLayoutEffectDuration(finishedWork);
2577
- } else {
2578
- try {
2579
- commitHookEffectListUnmount(
2580
- HookLayout | HookHasEffect,
2581
- finishedWork,
2582
- finishedWork.return,
2583
- );
2584
- } catch (error) {
2585
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2586
- }
2587
- }
2588
- }
2589
- return;
2590
- }
2591
- case ClassComponent: {
2592
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2593
- commitReconciliationEffects(finishedWork);
2594
-
2595
- if (flags & Ref) {
2596
- if (current !== null) {
2597
- safelyDetachRef(current, current.return);
2598
- }
2599
- }
2600
-
2601
- if (flags & Callback && offscreenSubtreeIsHidden) {
2602
- const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any);
2603
- if (updateQueue !== null) {
2604
- deferHiddenCallbacks(updateQueue);
2605
- }
2606
- }
2607
- return;
2608
- }
2609
- case HostResource: {
2610
- if (enableFloat && supportsResources) {
2611
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2612
- commitReconciliationEffects(finishedWork);
2613
-
2614
- if (flags & Ref) {
2615
- if (current !== null) {
2616
- safelyDetachRef(current, current.return);
2617
- }
2618
- }
2619
-
2620
- if (flags & Update) {
2621
- const newResource = finishedWork.memoizedState;
2622
- if (current !== null) {
2623
- const currentResource = current.memoizedState;
2624
- if (currentResource !== newResource) {
2625
- releaseResource(currentResource);
2626
- }
2627
- }
2628
- finishedWork.stateNode = newResource
2629
- ? acquireResource(newResource)
2630
- : null;
2631
- }
2632
- return;
2633
- }
2634
- }
2635
- // eslint-disable-next-line-no-fallthrough
2636
- case HostSingleton: {
2637
- if (enableHostSingletons && supportsSingletons) {
2638
- if (flags & Update) {
2639
- const previousWork = finishedWork.alternate;
2640
- if (previousWork === null) {
2641
- const singleton = finishedWork.stateNode;
2642
- const props = finishedWork.memoizedProps;
2643
- // This was a new mount, we need to clear and set initial properties
2644
- clearSingleton(singleton);
2645
- acquireSingletonInstance(
2646
- finishedWork.type,
2647
- props,
2648
- singleton,
2649
- finishedWork,
2650
- );
2651
- }
2652
- }
2653
- }
2654
- }
2655
- // eslint-disable-next-line-no-fallthrough
2656
- case HostComponent: {
2657
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2658
- commitReconciliationEffects(finishedWork);
2659
-
2660
- if (flags & Ref) {
2661
- if (current !== null) {
2662
- safelyDetachRef(current, current.return);
2663
- }
2664
- }
2665
- if (supportsMutation) {
2666
- // TODO: ContentReset gets cleared by the children during the commit
2667
- // phase. This is a refactor hazard because it means we must read
2668
- // flags the flags after `commitReconciliationEffects` has already run;
2669
- // the order matters. We should refactor so that ContentReset does not
2670
- // rely on mutating the flag during commit. Like by setting a flag
2671
- // during the render phase instead.
2672
- if (finishedWork.flags & ContentReset) {
2673
- const instance: Instance = finishedWork.stateNode;
2674
- try {
2675
- resetTextContent(instance);
2676
- } catch (error) {
2677
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2678
- }
2679
- }
2680
-
2681
- if (flags & Update) {
2682
- const instance: Instance = finishedWork.stateNode;
2683
- if (instance != null) {
2684
- // Commit the work prepared earlier.
2685
- const newProps = finishedWork.memoizedProps;
2686
- // For hydration we reuse the update path but we treat the oldProps
2687
- // as the newProps. The updatePayload will contain the real change in
2688
- // this case.
2689
- const oldProps =
2690
- current !== null ? current.memoizedProps : newProps;
2691
- const type = finishedWork.type;
2692
- // TODO: Type the updateQueue to be specific to host components.
2693
- const updatePayload: null | UpdatePayload = (finishedWork.updateQueue: any);
2694
- finishedWork.updateQueue = null;
2695
- if (updatePayload !== null) {
2696
- try {
2697
- commitUpdate(
2698
- instance,
2699
- updatePayload,
2700
- type,
2701
- oldProps,
2702
- newProps,
2703
- finishedWork,
2704
- );
2705
- } catch (error) {
2706
- captureCommitPhaseError(
2707
- finishedWork,
2708
- finishedWork.return,
2709
- error,
2710
- );
2711
- }
2712
- }
2713
- }
2714
- }
2715
- }
2716
- return;
2717
- }
2718
- case HostText: {
2719
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2720
- commitReconciliationEffects(finishedWork);
2721
-
2722
- if (flags & Update) {
2723
- if (supportsMutation) {
2724
- if (finishedWork.stateNode === null) {
2725
- throw new Error(
2726
- 'This should have a text node initialized. This error is likely ' +
2727
- 'caused by a bug in React. Please file an issue.',
2728
- );
2729
- }
2730
-
2731
- const textInstance: TextInstance = finishedWork.stateNode;
2732
- const newText: string = finishedWork.memoizedProps;
2733
- // For hydration we reuse the update path but we treat the oldProps
2734
- // as the newProps. The updatePayload will contain the real change in
2735
- // this case.
2736
- const oldText: string =
2737
- current !== null ? current.memoizedProps : newText;
2738
-
2739
- try {
2740
- commitTextUpdate(textInstance, oldText, newText);
2741
- } catch (error) {
2742
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2743
- }
2744
- }
2745
- }
2746
- return;
2747
- }
2748
- case HostRoot: {
2749
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2750
- commitReconciliationEffects(finishedWork);
2751
-
2752
- if (flags & Update) {
2753
- if (supportsMutation && supportsHydration) {
2754
- if (current !== null) {
2755
- const prevRootState: RootState = current.memoizedState;
2756
- if (prevRootState.isDehydrated) {
2757
- try {
2758
- commitHydratedContainer(root.containerInfo);
2759
- } catch (error) {
2760
- captureCommitPhaseError(
2761
- finishedWork,
2762
- finishedWork.return,
2763
- error,
2764
- );
2765
- }
2766
- }
2767
- }
2768
- }
2769
- if (supportsPersistence) {
2770
- const containerInfo = root.containerInfo;
2771
- const pendingChildren = root.pendingChildren;
2772
- try {
2773
- replaceContainerChildren(containerInfo, pendingChildren);
2774
- } catch (error) {
2775
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2776
- }
2777
- }
2778
- }
2779
- return;
2780
- }
2781
- case HostPortal: {
2782
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2783
- commitReconciliationEffects(finishedWork);
2784
-
2785
- if (flags & Update) {
2786
- if (supportsPersistence) {
2787
- const portal = finishedWork.stateNode;
2788
- const containerInfo = portal.containerInfo;
2789
- const pendingChildren = portal.pendingChildren;
2790
- try {
2791
- replaceContainerChildren(containerInfo, pendingChildren);
2792
- } catch (error) {
2793
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2794
- }
2795
- }
2796
- }
2797
- return;
2798
- }
2799
- case SuspenseComponent: {
2800
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2801
- commitReconciliationEffects(finishedWork);
2802
-
2803
- const offscreenFiber: Fiber = (finishedWork.child: any);
2804
-
2805
- if (offscreenFiber.flags & Visibility) {
2806
- const newState: OffscreenState | null = offscreenFiber.memoizedState;
2807
- const isHidden = newState !== null;
2808
- if (isHidden) {
2809
- const wasHidden =
2810
- offscreenFiber.alternate !== null &&
2811
- offscreenFiber.alternate.memoizedState !== null;
2812
- if (!wasHidden) {
2813
- // TODO: Move to passive phase
2814
- markCommitTimeOfFallback();
2815
- }
2816
- }
2817
- }
2818
-
2819
- if (flags & Update) {
2820
- try {
2821
- commitSuspenseCallback(finishedWork);
2822
- } catch (error) {
2823
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2824
- }
2825
- const wakeables: Set<Wakeable> | null = (finishedWork.updateQueue: any);
2826
- if (wakeables !== null) {
2827
- finishedWork.updateQueue = null;
2828
- attachSuspenseRetryListeners(finishedWork, wakeables);
2829
- }
2830
- }
2831
- return;
2832
- }
2833
- case OffscreenComponent: {
2834
- if (flags & Ref) {
2835
- if (current !== null) {
2836
- safelyDetachRef(current, current.return);
2837
- }
2838
- }
2839
-
2840
- const newState: OffscreenState | null = finishedWork.memoizedState;
2841
- const isHidden = newState !== null;
2842
- const wasHidden = current !== null && current.memoizedState !== null;
2843
-
2844
- if (finishedWork.mode & ConcurrentMode) {
2845
- // Before committing the children, track on the stack whether this
2846
- // offscreen subtree was already hidden, so that we don't unmount the
2847
- // effects again.
2848
- const prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
2849
- const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
2850
- offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || isHidden;
2851
- offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
2852
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2853
- offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
2854
- offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
2855
- } else {
2856
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2857
- }
2858
-
2859
- commitReconciliationEffects(finishedWork);
2860
- // TODO: Add explicit effect flag to set _current.
2861
- finishedWork.stateNode._current = finishedWork;
2862
-
2863
- if (flags & Visibility) {
2864
- const offscreenInstance: OffscreenInstance = finishedWork.stateNode;
2865
-
2866
- // Track the current state on the Offscreen instance so we can
2867
- // read it during an event
2868
- if (isHidden) {
2869
- offscreenInstance._visibility &= ~OffscreenVisible;
2870
- } else {
2871
- offscreenInstance._visibility |= OffscreenVisible;
2872
- }
2873
-
2874
- if (isHidden) {
2875
- const isUpdate = current !== null;
2876
- const wasHiddenByAncestorOffscreen =
2877
- offscreenSubtreeIsHidden || offscreenSubtreeWasHidden;
2878
- // Only trigger disapper layout effects if:
2879
- // - This is an update, not first mount.
2880
- // - This Offscreen was not hidden before.
2881
- // - Ancestor Offscreen was not hidden in previous commit.
2882
- if (isUpdate && !wasHidden && !wasHiddenByAncestorOffscreen) {
2883
- if ((finishedWork.mode & ConcurrentMode) !== NoMode) {
2884
- // Disappear the layout effects of all the children
2885
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
2886
- }
2887
- }
2888
- } else {
2889
- if (wasHidden) {
2890
- // TODO: Move re-appear call here for symmetry?
2891
- }
2892
- }
2893
-
2894
- // Offscreen with manual mode manages visibility manually.
2895
- if (supportsMutation && !isOffscreenManual(finishedWork)) {
2896
- // TODO: This needs to run whenever there's an insertion or update
2897
- // inside a hidden Offscreen tree.
2898
- hideOrUnhideAllChildren(finishedWork, isHidden);
2899
- }
2900
- }
2901
-
2902
- // TODO: Move to passive phase
2903
- if (flags & Update) {
2904
- const offscreenQueue: OffscreenQueue | null = (finishedWork.updateQueue: any);
2905
- if (offscreenQueue !== null) {
2906
- const wakeables = offscreenQueue.wakeables;
2907
- if (wakeables !== null) {
2908
- offscreenQueue.wakeables = null;
2909
- attachSuspenseRetryListeners(finishedWork, wakeables);
2910
- }
2911
- }
2912
- }
2913
- return;
2914
- }
2915
- case SuspenseListComponent: {
2916
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2917
- commitReconciliationEffects(finishedWork);
2918
-
2919
- if (flags & Update) {
2920
- const wakeables: Set<Wakeable> | null = (finishedWork.updateQueue: any);
2921
- if (wakeables !== null) {
2922
- finishedWork.updateQueue = null;
2923
- attachSuspenseRetryListeners(finishedWork, wakeables);
2924
- }
2925
- }
2926
- return;
2927
- }
2928
- case ScopeComponent: {
2929
- if (enableScopeAPI) {
2930
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2931
- commitReconciliationEffects(finishedWork);
2932
-
2933
- // TODO: This is a temporary solution that allowed us to transition away
2934
- // from React Flare on www.
2935
- if (flags & Ref) {
2936
- if (current !== null) {
2937
- safelyDetachRef(finishedWork, finishedWork.return);
2938
- }
2939
- safelyAttachRef(finishedWork, finishedWork.return);
2940
- }
2941
- if (flags & Update) {
2942
- const scopeInstance = finishedWork.stateNode;
2943
- prepareScopeUpdate(scopeInstance, finishedWork);
2944
- }
2945
- }
2946
- return;
2947
- }
2948
- default: {
2949
- recursivelyTraverseMutationEffects(root, finishedWork, lanes);
2950
- commitReconciliationEffects(finishedWork);
2951
-
2952
- return;
2953
- }
2954
- }
2955
-}
2956
-function commitReconciliationEffects(finishedWork: Fiber) {
2957
- // Placement effects (insertions, reorders) can be scheduled on any fiber
2958
- // type. They needs to happen after the children effects have fired, but
2959
- // before the effects on this fiber have fired.
2960
- const flags = finishedWork.flags;
2961
- if (flags & Placement) {
2962
- try {
2963
- commitPlacement(finishedWork);
2964
- } catch (error) {
2965
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
2966
- }
2967
- // Clear the "placement" from effect tag so that we know that this is
2968
- // inserted, before any life-cycles like componentDidMount gets called.
2969
- // TODO: findDOMNode doesn't rely on this any more but isMounted does
2970
- // and isMounted is deprecated anyway so we should be able to kill this.
2971
- finishedWork.flags &= ~Placement;
2972
- }
2973
- if (flags & Hydrating) {
2974
- finishedWork.flags &= ~Hydrating;
2975
- }
2976
-}
2977
-
2978
-export function commitLayoutEffects(
2979
- finishedWork: Fiber,
2980
- root: FiberRoot,
2981
- committedLanes: Lanes,
2982
-): void {
2983
- inProgressLanes = committedLanes;
2984
- inProgressRoot = root;
2985
-
2986
- const current = finishedWork.alternate;
2987
- commitLayoutEffectOnFiber(root, current, finishedWork, committedLanes);
2988
-
2989
- inProgressLanes = null;
2990
- inProgressRoot = null;
2991
-}
2992
-
2993
-function recursivelyTraverseLayoutEffects(
2994
- root: FiberRoot,
2995
- parentFiber: Fiber,
2996
- lanes: Lanes,
2997
-) {
2998
- const prevDebugFiber = getCurrentDebugFiberInDEV();
2999
- if (parentFiber.subtreeFlags & LayoutMask) {
3000
- let child = parentFiber.child;
3001
- while (child !== null) {
3002
- setCurrentDebugFiberInDEV(child);
3003
- const current = child.alternate;
3004
- commitLayoutEffectOnFiber(root, current, child, lanes);
3005
- child = child.sibling;
3006
- }
3007
- }
3008
- setCurrentDebugFiberInDEV(prevDebugFiber);
3009
-}
3010
-
3011
-export function disappearLayoutEffects(finishedWork: Fiber) {
3012
- switch (finishedWork.tag) {
3013
- case FunctionComponent:
3014
- case ForwardRef:
3015
- case MemoComponent:
3016
- case SimpleMemoComponent: {
3017
- // TODO (Offscreen) Check: flags & LayoutStatic
3018
- if (shouldProfile(finishedWork)) {
3019
- try {
3020
- startLayoutEffectTimer();
3021
- commitHookEffectListUnmount(
3022
- HookLayout,
3023
- finishedWork,
3024
- finishedWork.return,
3025
- );
3026
- } finally {
3027
- recordLayoutEffectDuration(finishedWork);
3028
- }
3029
- } else {
3030
- commitHookEffectListUnmount(
3031
- HookLayout,
3032
- finishedWork,
3033
- finishedWork.return,
3034
- );
3035
- }
3036
-
3037
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
3038
- break;
3039
- }
3040
- case ClassComponent: {
3041
- // TODO (Offscreen) Check: flags & RefStatic
3042
- safelyDetachRef(finishedWork, finishedWork.return);
3043
-
3044
- const instance = finishedWork.stateNode;
3045
- if (typeof instance.componentWillUnmount === 'function') {
3046
- safelyCallComponentWillUnmount(
3047
- finishedWork,
3048
- finishedWork.return,
3049
- instance,
3050
- );
3051
- }
3052
-
3053
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
3054
- break;
3055
- }
3056
- case HostResource:
3057
- case HostSingleton:
3058
- case HostComponent: {
3059
- // TODO (Offscreen) Check: flags & RefStatic
3060
- safelyDetachRef(finishedWork, finishedWork.return);
3061
-
3062
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
3063
- break;
3064
- }
3065
- case OffscreenComponent: {
3066
- // TODO (Offscreen) Check: flags & RefStatic
3067
- safelyDetachRef(finishedWork, finishedWork.return);
3068
-
3069
- const isHidden = finishedWork.memoizedState !== null;
3070
- if (isHidden) {
3071
- // Nested Offscreen tree is already hidden. Don't disappear
3072
- // its effects.
3073
- } else {
3074
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
3075
- }
3076
- break;
3077
- }
3078
- default: {
3079
- recursivelyTraverseDisappearLayoutEffects(finishedWork);
3080
- break;
3081
- }
3082
- }
3083
-}
3084
-
3085
-function recursivelyTraverseDisappearLayoutEffects(parentFiber: Fiber) {
3086
- // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)
3087
- let child = parentFiber.child;
3088
- while (child !== null) {
3089
- disappearLayoutEffects(child);
3090
- child = child.sibling;
3091
- }
3092
-}
3093
-
3094
-export function reappearLayoutEffects(
3095
- finishedRoot: FiberRoot,
3096
- current: Fiber | null,
3097
- finishedWork: Fiber,
3098
- // This function visits both newly finished work and nodes that were re-used
3099
- // from a previously committed tree. We cannot check non-static flags if the
3100
- // node was reused.
3101
- includeWorkInProgressEffects: boolean,
3102
-) {
3103
- // Turn on layout effects in a tree that previously disappeared.
3104
- const flags = finishedWork.flags;
3105
- switch (finishedWork.tag) {
3106
- case FunctionComponent:
3107
- case ForwardRef:
3108
- case SimpleMemoComponent: {
3109
- recursivelyTraverseReappearLayoutEffects(
3110
- finishedRoot,
3111
- finishedWork,
3112
- includeWorkInProgressEffects,
3113
- );
3114
- // TODO: Check flags & LayoutStatic
3115
- commitHookLayoutEffects(finishedWork, HookLayout);
3116
- break;
3117
- }
3118
- case ClassComponent: {
3119
- recursivelyTraverseReappearLayoutEffects(
3120
- finishedRoot,
3121
- finishedWork,
3122
- includeWorkInProgressEffects,
3123
- );
3124
-
3125
- // TODO: Check for LayoutStatic flag
3126
- const instance = finishedWork.stateNode;
3127
- if (typeof instance.componentDidMount === 'function') {
3128
- try {
3129
- instance.componentDidMount();
3130
- } catch (error) {
3131
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
3132
- }
3133
- }
3134
-
3135
- // Commit any callbacks that would have fired while the component
3136
- // was hidden.
3137
- const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any);
3138
- if (updateQueue !== null) {
3139
- commitHiddenCallbacks(updateQueue, instance);
3140
- }
3141
-
3142
- // If this is newly finished work, check for setState callbacks
3143
- if (includeWorkInProgressEffects && flags & Callback) {
3144
- commitClassCallbacks(finishedWork);
3145
- }
3146
-
3147
- // TODO: Check flags & RefStatic
3148
- safelyAttachRef(finishedWork, finishedWork.return);
3149
- break;
3150
- }
3151
- // Unlike commitLayoutEffectsOnFiber, we don't need to handle HostRoot
3152
- // because this function only visits nodes that are inside an
3153
- // Offscreen fiber.
3154
- // case HostRoot: {
3155
- // ...
3156
- // }
3157
- case HostResource:
3158
- case HostSingleton:
3159
- case HostComponent: {
3160
- recursivelyTraverseReappearLayoutEffects(
3161
- finishedRoot,
3162
- finishedWork,
3163
- includeWorkInProgressEffects,
3164
- );
3165
-
3166
- // Renderers may schedule work to be done after host components are mounted
3167
- // (eg DOM renderer may schedule auto-focus for inputs and form controls).
3168
- // These effects should only be committed when components are first mounted,
3169
- // aka when there is no current/alternate.
3170
- if (includeWorkInProgressEffects && current === null && flags & Update) {
3171
- commitHostComponentMount(finishedWork);
3172
- }
3173
-
3174
- // TODO: Check flags & Ref
3175
- safelyAttachRef(finishedWork, finishedWork.return);
3176
- break;
3177
- }
3178
- case Profiler: {
3179
- recursivelyTraverseReappearLayoutEffects(
3180
- finishedRoot,
3181
- finishedWork,
3182
- includeWorkInProgressEffects,
3183
- );
3184
- // TODO: Figure out how Profiler updates should work with Offscreen
3185
- if (includeWorkInProgressEffects && flags & Update) {
3186
- commitProfilerUpdate(finishedWork, current);
3187
- }
3188
- break;
3189
- }
3190
- case SuspenseComponent: {
3191
- recursivelyTraverseReappearLayoutEffects(
3192
- finishedRoot,
3193
- finishedWork,
3194
- includeWorkInProgressEffects,
3195
- );
3196
-
3197
- // TODO: Figure out how Suspense hydration callbacks should work
3198
- // with Offscreen.
3199
- if (includeWorkInProgressEffects && flags & Update) {
3200
- commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
3201
- }
3202
- break;
3203
- }
3204
- case OffscreenComponent: {
3205
- const offscreenState: OffscreenState = finishedWork.memoizedState;
3206
- const isHidden = offscreenState !== null;
3207
- if (isHidden) {
3208
- // Nested Offscreen tree is still hidden. Don't re-appear its effects.
3209
- } else {
3210
- recursivelyTraverseReappearLayoutEffects(
3211
- finishedRoot,
3212
- finishedWork,
3213
- includeWorkInProgressEffects,
3214
- );
3215
- }
3216
- // TODO: Check flags & Ref
3217
- safelyAttachRef(finishedWork, finishedWork.return);
3218
- break;
3219
- }
3220
- default: {
3221
- recursivelyTraverseReappearLayoutEffects(
3222
- finishedRoot,
3223
- finishedWork,
3224
- includeWorkInProgressEffects,
3225
- );
3226
- break;
3227
- }
3228
- }
3229
-}
3230
-
3231
-function recursivelyTraverseReappearLayoutEffects(
3232
- finishedRoot: FiberRoot,
3233
- parentFiber: Fiber,
3234
- includeWorkInProgressEffects: boolean,
3235
-) {
3236
- // This function visits both newly finished work and nodes that were re-used
3237
- // from a previously committed tree. We cannot check non-static flags if the
3238
- // node was reused.
3239
- const childShouldIncludeWorkInProgressEffects =
3240
- includeWorkInProgressEffects &&
3241
- (parentFiber.subtreeFlags & LayoutMask) !== NoFlags;
3242
-
3243
- // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)
3244
- const prevDebugFiber = getCurrentDebugFiberInDEV();
3245
- let child = parentFiber.child;
3246
- while (child !== null) {
3247
- const current = child.alternate;
3248
- reappearLayoutEffects(
3249
- finishedRoot,
3250
- current,
3251
- child,
3252
- childShouldIncludeWorkInProgressEffects,
3253
- );
3254
- child = child.sibling;
3255
- }
3256
- setCurrentDebugFiberInDEV(prevDebugFiber);
3257
-}
3258
-
3259
-function commitHookPassiveMountEffects(
3260
- finishedWork: Fiber,
3261
- hookFlags: HookFlags,
3262
-) {
3263
- if (shouldProfile(finishedWork)) {
3264
- startPassiveEffectTimer();
3265
- try {
3266
- commitHookEffectListMount(hookFlags, finishedWork);
3267
- } catch (error) {
3268
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
3269
- }
3270
- recordPassiveEffectDuration(finishedWork);
3271
- } else {
3272
- try {
3273
- commitHookEffectListMount(hookFlags, finishedWork);
3274
- } catch (error) {
3275
- captureCommitPhaseError(finishedWork, finishedWork.return, error);
3276
- }
3277
- }
3278
-}
3279
-
3280
-function commitOffscreenPassiveMountEffects(
3281
- current: Fiber | null,
3282
- finishedWork: Fiber,
3283
- instance: OffscreenInstance,
3284
-) {
3285
- if (enableCache) {
3286
- let previousCache: Cache | null = null;
3287
- if (
3288
- current !== null &&
3289
- current.memoizedState !== null &&
3290
- current.memoizedState.cachePool !== null
3291
- ) {
3292
- previousCache = current.memoizedState.cachePool.pool;
3293
- }
3294
- let nextCache: Cache | null = null;
3295
- if (
3296
- finishedWork.memoizedState !== null &&
3297
- finishedWork.memoizedState.cachePool !== null
3298
- ) {
3299
- nextCache = finishedWork.memoizedState.cachePool.pool;
3300
- }
3301
- // Retain/release the cache used for pending (suspended) nodes.
3302
- // Note that this is only reached in the non-suspended/visible case:
3303
- // when the content is suspended/hidden, the retain/release occurs
3304
- // via the parent Suspense component (see case above).
3305
- if (nextCache !== previousCache) {
3306
- if (nextCache != null) {
3307
- retainCache(nextCache);
3308
- }
3309
- if (previousCache != null) {
3310
- releaseCache(previousCache);
3311
- }
3312
- }
3313
- }
3314
-
3315
- if (enableTransitionTracing) {
3316
- // TODO: Pre-rendering should not be counted as part of a transition. We
3317
- // may add separate logs for pre-rendering, but it's not part of the
3318
- // primary metrics.
3319
- const offscreenState: OffscreenState = finishedWork.memoizedState;
3320
- const queue: OffscreenQueue | null = (finishedWork.updateQueue: any);
3321
-
3322
- const isHidden = offscreenState !== null;
3323
- if (queue !== null) {
3324
- if (isHidden) {
3325
- const transitions = queue.transitions;
3326
- if (transitions !== null) {
3327
- transitions.forEach(transition => {
3328
- // Add all the transitions saved in the update queue during
3329
- // the render phase (ie the transitions associated with this boundary)
3330
- // into the transitions set.
3331
- if (instance._transitions === null) {
3332
- instance._transitions = new Set();
3333
- }
3334
- instance._transitions.add(transition);
3335
- });
3336
- }
3337
-
3338
- const markerInstances = queue.markerInstances;
3339
- if (markerInstances !== null) {
3340
- markerInstances.forEach(markerInstance => {
3341
- const markerTransitions = markerInstance.transitions;
3342
- // There should only be a few tracing marker transitions because
3343
- // they should be only associated with the transition that
3344
- // caused them
3345
- if (markerTransitions !== null) {
3346
- markerTransitions.forEach(transition => {
3347
- if (instance._transitions === null) {
3348
- instance._transitions = new Set();
3349
- } else if (instance._transitions.has(transition)) {
3350
- if (markerInstance.pendingBoundaries === null) {
3351
- markerInstance.pendingBoundaries = new Map();
3352
- }
3353
- if (instance._pendingMarkers === null) {
3354
- instance._pendingMarkers = new Set();
3355
- }
3356
-
3357
- instance._pendingMarkers.add(markerInstance);
3358
- }
3359
- });
3360
- }
3361
- });
3362
- }
3363
- }
3364
-
3365
- finishedWork.updateQueue = null;
3366
- }
3367
-
3368
- commitTransitionProgress(finishedWork);
3369
-
3370
- // TODO: Refactor this into an if/else branch
3371
- if (!isHidden) {
3372
- instance._transitions = null;
3373
- instance._pendingMarkers = null;
3374
- }
3375
- }
3376
-}
3377
-
3378
-function commitCachePassiveMountEffect(
3379
- current: Fiber | null,
3380
- finishedWork: Fiber,
3381
-) {
3382
- if (enableCache) {
3383
- let previousCache: Cache | null = null;
3384
- if (finishedWork.alternate !== null) {
3385
- previousCache = finishedWork.alternate.memoizedState.cache;
3386
- }
3387
- const nextCache = finishedWork.memoizedState.cache;
3388
- // Retain/release the cache. In theory the cache component
3389
- // could be "borrowing" a cache instance owned by some parent,
3390
- // in which case we could avoid retaining/releasing. But it
3391
- // is non-trivial to determine when that is the case, so we
3392
- // always retain/release.
3393
- if (nextCache !== previousCache) {
3394
- retainCache(nextCache);
3395
- if (previousCache != null) {
3396
- releaseCache(previousCache);
3397
- }
3398
- }
3399
- }
3400
-}
3401
-
3402
-function commitTracingMarkerPassiveMountEffect(finishedWork: Fiber) {
3403
- // Get the transitions that were initiatized during the render
3404
- // and add a start transition callback for each of them
3405
- // We will only call this on initial mount of the tracing marker
3406
- // only if there are no suspense children
3407
- const instance = finishedWork.stateNode;
3408
- if (instance.transitions !== null && instance.pendingBoundaries === null) {
3409
- addMarkerCompleteCallbackToPendingTransition(
3410
- finishedWork.memoizedProps.name,
3411
- instance.transitions,
3412
- );
3413
- instance.transitions = null;
3414
- instance.pendingBoundaries = null;
3415
- instance.aborts = null;
3416
- instance.name = null;
3417
- }
3418
-}
3419
-
3420
-export function commitPassiveMountEffects(
3421
- root: FiberRoot,
3422
- finishedWork: Fiber,
3423
- committedLanes: Lanes,
3424
- committedTransitions: Array<Transition> | null,
3425
-): void {
3426
- setCurrentDebugFiberInDEV(finishedWork);
3427
- commitPassiveMountOnFiber(
3428
- root,
3429
- finishedWork,
3430
- committedLanes,
3431
- committedTransitions,
3432
- );
3433
- resetCurrentDebugFiberInDEV();
3434
-}
3435
-
3436
-function recursivelyTraversePassiveMountEffects(
3437
- root: FiberRoot,
3438
- parentFiber: Fiber,
3439
- committedLanes: Lanes,
3440
- committedTransitions: Array<Transition> | null,
3441
-) {
3442
- const prevDebugFiber = getCurrentDebugFiberInDEV();
3443
- if (parentFiber.subtreeFlags & PassiveMask) {
3444
- let child = parentFiber.child;
3445
- while (child !== null) {
3446
- setCurrentDebugFiberInDEV(child);
3447
- commitPassiveMountOnFiber(
3448
- root,
3449
- child,
3450
- committedLanes,
3451
- committedTransitions,
3452
- );
3453
- child = child.sibling;
3454
- }
3455
- }
3456
- setCurrentDebugFiberInDEV(prevDebugFiber);
3457
-}
3458
-
3459
-function commitPassiveMountOnFiber(
3460
- finishedRoot: FiberRoot,
3461
- finishedWork: Fiber,
3462
- committedLanes: Lanes,
3463
- committedTransitions: Array<Transition> | null,
3464
-): void {
3465
- // When updating this function, also update reconnectPassiveEffects, which does
3466
- // most of the same things when an offscreen tree goes from hidden -> visible,
3467
- // or when toggling effects inside a hidden tree.
3468
- const flags = finishedWork.flags;
3469
- switch (finishedWork.tag) {
3470
- case FunctionComponent:
3471
- case ForwardRef:
3472
- case SimpleMemoComponent: {
3473
- recursivelyTraversePassiveMountEffects(
3474
- finishedRoot,
3475
- finishedWork,
3476
- committedLanes,
3477
- committedTransitions,
3478
- );
3479
- if (flags & Passive) {
3480
- commitHookPassiveMountEffects(
3481
- finishedWork,
3482
- HookPassive | HookHasEffect,
3483
- );
3484
- }
3485
- break;
3486
- }
3487
- case HostRoot: {
3488
- recursivelyTraversePassiveMountEffects(
3489
- finishedRoot,
3490
- finishedWork,
3491
- committedLanes,
3492
- committedTransitions,
3493
- );
3494
- if (flags & Passive) {
3495
- if (enableCache) {
3496
- let previousCache: Cache | null = null;
3497
- if (finishedWork.alternate !== null) {
3498
- previousCache = finishedWork.alternate.memoizedState.cache;
3499
- }
3500
- const nextCache = finishedWork.memoizedState.cache;
3501
- // Retain/release the root cache.
3502
- // Note that on initial mount, previousCache and nextCache will be the same
3503
- // and this retain won't occur. To counter this, we instead retain the HostRoot's
3504
- // initial cache when creating the root itself (see createFiberRoot() in
3505
- // ReactFiberRoot.js). Subsequent updates that change the cache are reflected
3506
- // here, such that previous/next caches are retained correctly.
3507
- if (nextCache !== previousCache) {
3508
- retainCache(nextCache);
3509
- if (previousCache != null) {
3510
- releaseCache(previousCache);
3511
- }
3512
- }
3513
- }
3514
-
3515
- if (enableTransitionTracing) {
3516
- // Get the transitions that were initiatized during the render
3517
- // and add a start transition callback for each of them
3518
- const root: FiberRoot = finishedWork.stateNode;
3519
- const incompleteTransitions = root.incompleteTransitions;
3520
- // Initial render
3521
- if (committedTransitions !== null) {
3522
- committedTransitions.forEach(transition => {
3523
- addTransitionStartCallbackToPendingTransition(transition);
3524
- });
3525
-
3526
- clearTransitionsForLanes(finishedRoot, committedLanes);
3527
- }
3528
-
3529
- incompleteTransitions.forEach((markerInstance, transition) => {
3530
- const pendingBoundaries = markerInstance.pendingBoundaries;
3531
- if (pendingBoundaries === null || pendingBoundaries.size === 0) {
3532
- if (markerInstance.aborts === null) {
3533
- addTransitionCompleteCallbackToPendingTransition(transition);
3534
- }
3535
- incompleteTransitions.delete(transition);
3536
- }
3537
- });
3538
-
3539
- clearTransitionsForLanes(finishedRoot, committedLanes);
3540
- }
3541
- }
3542
- break;
3543
- }
3544
- case LegacyHiddenComponent: {
3545
- if (enableLegacyHidden) {
3546
- recursivelyTraversePassiveMountEffects(
3547
- finishedRoot,
3548
- finishedWork,
3549
- committedLanes,
3550
- committedTransitions,
3551
- );
3552
-
3553
- if (flags & Passive) {
3554
- const current = finishedWork.alternate;
3555
- const instance: OffscreenInstance = finishedWork.stateNode;
3556
- commitOffscreenPassiveMountEffects(current, finishedWork, instance);
3557
- }
3558
- }
3559
- break;
3560
- }
3561
- case OffscreenComponent: {
3562
- // TODO: Pass `current` as argument to this function
3563
- const instance: OffscreenInstance = finishedWork.stateNode;
3564
- const nextState: OffscreenState | null = finishedWork.memoizedState;
3565
-
3566
- const isHidden = nextState !== null;
3567
-
3568
- if (isHidden) {
3569
- if (instance._visibility & OffscreenPassiveEffectsConnected) {
3570
- // The effects are currently connected. Update them.
3571
- recursivelyTraversePassiveMountEffects(
3572
- finishedRoot,
3573
- finishedWork,
3574
- committedLanes,
3575
- committedTransitions,
3576
- );
3577
- } else {
3578
- if (finishedWork.mode & ConcurrentMode) {
3579
- // The effects are currently disconnected. Since the tree is hidden,
3580
- // don't connect them. This also applies to the initial render.
3581
- if (enableCache || enableTransitionTracing) {
3582
- // "Atomic" effects are ones that need to fire on every commit,
3583
- // even during pre-rendering. An example is updating the reference
3584
- // count on cache instances.
3585
- recursivelyTraverseAtomicPassiveEffects(
3586
- finishedRoot,
3587
- finishedWork,
3588
- committedLanes,
3589
- committedTransitions,
3590
- );
3591
- }
3592
- } else {
3593
- // Legacy Mode: Fire the effects even if the tree is hidden.
3594
- instance._visibility |= OffscreenPassiveEffectsConnected;
3595
- recursivelyTraversePassiveMountEffects(
3596
- finishedRoot,
3597
- finishedWork,
3598
- committedLanes,
3599
- committedTransitions,
3600
- );
3601
- }
3602
- }
3603
- } else {
3604
- // Tree is visible
3605
- if (instance._visibility & OffscreenPassiveEffectsConnected) {
3606
- // The effects are currently connected. Update them.
3607
- recursivelyTraversePassiveMountEffects(
3608
- finishedRoot,
3609
- finishedWork,
3610
- committedLanes,
3611
- committedTransitions,
3612
- );
3613
- } else {
3614
- // The effects are currently disconnected. Reconnect them, while also
3615
- // firing effects inside newly mounted trees. This also applies to
3616
- // the initial render.
3617
- instance._visibility |= OffscreenPassiveEffectsConnected;
3618
-
3619
- const includeWorkInProgressEffects =
3620
- (finishedWork.subtreeFlags & PassiveMask) !== NoFlags;
3621
- recursivelyTraverseReconnectPassiveEffects(
3622
- finishedRoot,
3623
- finishedWork,
3624
- committedLanes,
3625
- committedTransitions,
3626
- includeWorkInProgressEffects,
3627
- );
3628
- }
3629
- }
3630
-
3631
- if (flags & Passive) {
3632
- const current = finishedWork.alternate;
3633
- commitOffscreenPassiveMountEffects(current, finishedWork, instance);
3634
- }
3635
- break;
3636
- }
3637
- case CacheComponent: {
3638
- recursivelyTraversePassiveMountEffects(
3639
- finishedRoot,
3640
- finishedWork,
3641
- committedLanes,
3642
- committedTransitions,
3643
- );
3644
- if (flags & Passive) {
3645
- // TODO: Pass `current` as argument to this function
3646
- const current = finishedWork.alternate;
3647
- commitCachePassiveMountEffect(current, finishedWork);
3648
- }
3649
- break;
3650
- }
3651
- case TracingMarkerComponent: {
3652
- if (enableTransitionTracing) {
3653
- recursivelyTraversePassiveMountEffects(
3654
- finishedRoot,
3655
- finishedWork,
3656
- committedLanes,
3657
- committedTransitions,
3658
- );
3659
- if (flags & Passive) {
3660
- commitTracingMarkerPassiveMountEffect(finishedWork);
3661
- }
3662
- break;
3663
- }
3664
- // Intentional fallthrough to next branch
3665
- }
3666
- // eslint-disable-next-line-no-fallthrough
3667
- default: {
3668
- recursivelyTraversePassiveMountEffects(
3669
- finishedRoot,
3670
- finishedWork,
3671
- committedLanes,
3672
- committedTransitions,
3673
- );
3674
- break;
3675
- }
3676
- }
3677
-}
3678
-
3679
-function recursivelyTraverseReconnectPassiveEffects(
3680
- finishedRoot: FiberRoot,
3681
- parentFiber: Fiber,
3682
- committedLanes: Lanes,
3683
- committedTransitions: Array<Transition> | null,
3684
- includeWorkInProgressEffects: boolean,
3685
-) {
3686
- // This function visits both newly finished work and nodes that were re-used
3687
- // from a previously committed tree. We cannot check non-static flags if the
3688
- // node was reused.
3689
- const childShouldIncludeWorkInProgressEffects =
3690
- includeWorkInProgressEffects &&
3691
- (parentFiber.subtreeFlags & PassiveMask) !== NoFlags;
3692
-
3693
- // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)
3694
- const prevDebugFiber = getCurrentDebugFiberInDEV();
3695
- let child = parentFiber.child;
3696
- while (child !== null) {
3697
- reconnectPassiveEffects(
3698
- finishedRoot,
3699
- child,
3700
- committedLanes,
3701
- committedTransitions,
3702
- childShouldIncludeWorkInProgressEffects,
3703
- );
3704
- child = child.sibling;
3705
- }
3706
- setCurrentDebugFiberInDEV(prevDebugFiber);
3707
-}
3708
-
3709
-export function reconnectPassiveEffects(
3710
- finishedRoot: FiberRoot,
3711
- finishedWork: Fiber,
3712
- committedLanes: Lanes,
3713
- committedTransitions: Array<Transition> | null,
3714
- // This function visits both newly finished work and nodes that were re-used
3715
- // from a previously committed tree. We cannot check non-static flags if the
3716
- // node was reused.
3717
- includeWorkInProgressEffects: boolean,
3718
-) {
3719
- const flags = finishedWork.flags;
3720
- switch (finishedWork.tag) {
3721
- case FunctionComponent:
3722
- case ForwardRef:
3723
- case SimpleMemoComponent: {
3724
- recursivelyTraverseReconnectPassiveEffects(
3725
- finishedRoot,
3726
- finishedWork,
3727
- committedLanes,
3728
- committedTransitions,
3729
- includeWorkInProgressEffects,
3730
- );
3731
- // TODO: Check for PassiveStatic flag
3732
- commitHookPassiveMountEffects(finishedWork, HookPassive);
3733
- break;
3734
- }
3735
- // Unlike commitPassiveMountOnFiber, we don't need to handle HostRoot
3736
- // because this function only visits nodes that are inside an
3737
- // Offscreen fiber.
3738
- // case HostRoot: {
3739
- // ...
3740
- // }
3741
- case LegacyHiddenComponent: {
3742
- if (enableLegacyHidden) {
3743
- recursivelyTraverseReconnectPassiveEffects(
3744
- finishedRoot,
3745
- finishedWork,
3746
- committedLanes,
3747
- committedTransitions,
3748
- includeWorkInProgressEffects,
3749
- );
3750
-
3751
- if (includeWorkInProgressEffects && flags & Passive) {
3752
- // TODO: Pass `current` as argument to this function
3753
- const current: Fiber | null = finishedWork.alternate;
3754
- const instance: OffscreenInstance = finishedWork.stateNode;
3755
- commitOffscreenPassiveMountEffects(current, finishedWork, instance);
3756
- }
3757
- }
3758
- break;
3759
- }
3760
- case OffscreenComponent: {
3761
- const instance: OffscreenInstance = finishedWork.stateNode;
3762
- const nextState: OffscreenState | null = finishedWork.memoizedState;
3763
-
3764
- const isHidden = nextState !== null;
3765
-
3766
- if (isHidden) {
3767
- if (instance._visibility & OffscreenPassiveEffectsConnected) {
3768
- // The effects are currently connected. Update them.
3769
- recursivelyTraverseReconnectPassiveEffects(
3770
- finishedRoot,
3771
- finishedWork,
3772
- committedLanes,
3773
- committedTransitions,
3774
- includeWorkInProgressEffects,
3775
- );
3776
- } else {
3777
- if (finishedWork.mode & ConcurrentMode) {
3778
- // The effects are currently disconnected. Since the tree is hidden,
3779
- // don't connect them. This also applies to the initial render.
3780
- if (enableCache || enableTransitionTracing) {
3781
- // "Atomic" effects are ones that need to fire on every commit,
3782
- // even during pre-rendering. An example is updating the reference
3783
- // count on cache instances.
3784
- recursivelyTraverseAtomicPassiveEffects(
3785
- finishedRoot,
3786
- finishedWork,
3787
- committedLanes,
3788
- committedTransitions,
3789
- );
3790
- }
3791
- } else {
3792
- // Legacy Mode: Fire the effects even if the tree is hidden.
3793
- instance._visibility |= OffscreenPassiveEffectsConnected;
3794
- recursivelyTraverseReconnectPassiveEffects(
3795
- finishedRoot,
3796
- finishedWork,
3797
- committedLanes,
3798
- committedTransitions,
3799
- includeWorkInProgressEffects,
3800
- );
3801
- }
3802
- }
3803
- } else {
3804
- // Tree is visible
3805
-
3806
- // Since we're already inside a reconnecting tree, it doesn't matter
3807
- // whether the effects are currently connected. In either case, we'll
3808
- // continue traversing the tree and firing all the effects.
3809
- //
3810
- // We do need to set the "connected" flag on the instance, though.
3811
- instance._visibility |= OffscreenPassiveEffectsConnected;
3812
-
3813
- recursivelyTraverseReconnectPassiveEffects(
3814
- finishedRoot,
3815
- finishedWork,
3816
- committedLanes,
3817
- committedTransitions,
3818
- includeWorkInProgressEffects,
3819
- );
3820
- }
3821
-
3822
- if (includeWorkInProgressEffects && flags & Passive) {
3823
- // TODO: Pass `current` as argument to this function
3824
- const current: Fiber | null = finishedWork.alternate;
3825
- commitOffscreenPassiveMountEffects(current, finishedWork, instance);
3826
- }
3827
- break;
3828
- }
3829
- case CacheComponent: {
3830
- recursivelyTraverseReconnectPassiveEffects(
3831
- finishedRoot,
3832
- finishedWork,
3833
- committedLanes,
3834
- committedTransitions,
3835
- includeWorkInProgressEffects,
3836
- );
3837
- if (includeWorkInProgressEffects && flags & Passive) {
3838
- // TODO: Pass `current` as argument to this function
3839
- const current = finishedWork.alternate;
3840
- commitCachePassiveMountEffect(current, finishedWork);
3841
- }
3842
- break;
3843
- }
3844
- case TracingMarkerComponent: {
3845
- if (enableTransitionTracing) {
3846
- recursivelyTraverseReconnectPassiveEffects(
3847
- finishedRoot,
3848
- finishedWork,
3849
- committedLanes,
3850
- committedTransitions,
3851
- includeWorkInProgressEffects,
3852
- );
3853
- if (includeWorkInProgressEffects && flags & Passive) {
3854
- commitTracingMarkerPassiveMountEffect(finishedWork);
3855
- }
3856
- break;
3857
- }
3858
- // Intentional fallthrough to next branch
3859
- }
3860
- // eslint-disable-next-line-no-fallthrough
3861
- default: {
3862
- recursivelyTraverseReconnectPassiveEffects(
3863
- finishedRoot,
3864
- finishedWork,
3865
- committedLanes,
3866
- committedTransitions,
3867
- includeWorkInProgressEffects,
3868
- );
3869
- break;
3870
- }
3871
- }
3872
-}
3873
-
3874
-function recursivelyTraverseAtomicPassiveEffects(
3875
- finishedRoot: FiberRoot,
3876
- parentFiber: Fiber,
3877
- committedLanes: Lanes,
3878
- committedTransitions: Array<Transition> | null,
3879
-) {
3880
- // "Atomic" effects are ones that need to fire on every commit, even during
3881
- // pre-rendering. We call this function when traversing a hidden tree whose
3882
- // regular effects are currently disconnected.
3883
- const prevDebugFiber = getCurrentDebugFiberInDEV();
3884
- // TODO: Add special flag for atomic effects
3885
- if (parentFiber.subtreeFlags & PassiveMask) {
3886
- let child = parentFiber.child;
3887
- while (child !== null) {
3888
- setCurrentDebugFiberInDEV(child);
3889
- commitAtomicPassiveEffects(
3890
- finishedRoot,
3891
- child,
3892
- committedLanes,
3893
- committedTransitions,
3894
- );
3895
- child = child.sibling;
3896
- }
3897
- }
3898
- setCurrentDebugFiberInDEV(prevDebugFiber);
3899
-}
3900
-
3901
-function commitAtomicPassiveEffects(
3902
- finishedRoot: FiberRoot,
3903
- finishedWork: Fiber,
3904
- committedLanes: Lanes,
3905
- committedTransitions: Array<Transition> | null,
3906
-) {
3907
- // "Atomic" effects are ones that need to fire on every commit, even during
3908
- // pre-rendering. We call this function when traversing a hidden tree whose
3909
- // regular effects are currently disconnected.
3910
- const flags = finishedWork.flags;
3911
- switch (finishedWork.tag) {
3912
- case OffscreenComponent: {
3913
- recursivelyTraverseAtomicPassiveEffects(
3914
- finishedRoot,
3915
- finishedWork,
3916
- committedLanes,
3917
- committedTransitions,
3918
- );
3919
- if (flags & Passive) {
3920
- // TODO: Pass `current` as argument to this function
3921
- const current = finishedWork.alternate;
3922
- const instance: OffscreenInstance = finishedWork.stateNode;
3923
- commitOffscreenPassiveMountEffects(current, finishedWork, instance);
3924
- }
3925
- break;
3926
- }
3927
- case CacheComponent: {
3928
- recursivelyTraverseAtomicPassiveEffects(
3929
- finishedRoot,
3930
- finishedWork,
3931
- committedLanes,
3932
- committedTransitions,
3933
- );
3934
- if (flags & Passive) {
3935
- // TODO: Pass `current` as argument to this function
3936
- const current = finishedWork.alternate;
3937
- commitCachePassiveMountEffect(current, finishedWork);
3938
- }
3939
- break;
3940
- }
3941
- // eslint-disable-next-line-no-fallthrough
3942
- default: {
3943
- recursivelyTraverseAtomicPassiveEffects(
3944
- finishedRoot,
3945
- finishedWork,
3946
- committedLanes,
3947
- committedTransitions,
3948
- );
3949
- break;
3950
- }
3951
- }
3952
-}
3953
-
3954
-export function commitPassiveUnmountEffects(finishedWork: Fiber): void {
3955
- setCurrentDebugFiberInDEV(finishedWork);
3956
- commitPassiveUnmountOnFiber(finishedWork);
3957
- resetCurrentDebugFiberInDEV();
3958
-}
3959
-
3960
-function detachAlternateSiblings(parentFiber: Fiber) {
3961
- if (deletedTreeCleanUpLevel >= 1) {
3962
- // A fiber was deleted from this parent fiber, but it's still part of the
3963
- // previous (alternate) parent fiber's list of children. Because children
3964
- // are a linked list, an earlier sibling that's still alive will be
3965
- // connected to the deleted fiber via its `alternate`:
3966
- //
3967
- // live fiber --alternate--> previous live fiber --sibling--> deleted
3968
- // fiber
3969
- //
3970
- // We can't disconnect `alternate` on nodes that haven't been deleted yet,
3971
- // but we can disconnect the `sibling` and `child` pointers.
3972
-
3973
- const previousFiber = parentFiber.alternate;
3974
- if (previousFiber !== null) {
3975
- let detachedChild = previousFiber.child;
3976
- if (detachedChild !== null) {
3977
- previousFiber.child = null;
3978
- do {
3979
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3980
- const detachedSibling = detachedChild.sibling;
3981
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3982
- detachedChild.sibling = null;
3983
- detachedChild = detachedSibling;
3984
- } while (detachedChild !== null);
3985
- }
3986
- }
3987
- }
3988
-}
3989
-
3990
-function commitHookPassiveUnmountEffects(
3991
- finishedWork: Fiber,
3992
- nearestMountedAncestor,
3993
- hookFlags: HookFlags,
3994
-) {
3995
- if (shouldProfile(finishedWork)) {
3996
- startPassiveEffectTimer();
3997
- commitHookEffectListUnmount(
3998
- hookFlags,
3999
- finishedWork,
4000
- nearestMountedAncestor,
4001
- );
4002
- recordPassiveEffectDuration(finishedWork);
4003
- } else {
4004
- commitHookEffectListUnmount(
4005
- hookFlags,
4006
- finishedWork,
4007
- nearestMountedAncestor,
4008
- );
4009
- }
4010
-}
4011
-
4012
-function recursivelyTraversePassiveUnmountEffects(parentFiber: Fiber): void {
4013
- // Deletions effects can be scheduled on any fiber type. They need to happen
4014
- // before the children effects have fired.
4015
- const deletions = parentFiber.deletions;
4016
-
4017
- if ((parentFiber.flags & ChildDeletion) !== NoFlags) {
4018
- if (deletions !== null) {
4019
- for (let i = 0; i < deletions.length; i++) {
4020
- const childToDelete = deletions[i];
4021
- // TODO: Convert this to use recursion
4022
- nextEffect = childToDelete;
4023
- commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
4024
- childToDelete,
4025
- parentFiber,
4026
- );
4027
- }
4028
- }
4029
- detachAlternateSiblings(parentFiber);
4030
- }
4031
-
4032
- const prevDebugFiber = getCurrentDebugFiberInDEV();
4033
- // TODO: Split PassiveMask into separate masks for mount and unmount?
4034
- if (parentFiber.subtreeFlags & PassiveMask) {
4035
- let child = parentFiber.child;
4036
- while (child !== null) {
4037
- setCurrentDebugFiberInDEV(child);
4038
- commitPassiveUnmountOnFiber(child);
4039
- child = child.sibling;
4040
- }
4041
- }
4042
- setCurrentDebugFiberInDEV(prevDebugFiber);
4043
-}
4044
-
4045
-function commitPassiveUnmountOnFiber(finishedWork: Fiber): void {
4046
- switch (finishedWork.tag) {
4047
- case FunctionComponent:
4048
- case ForwardRef:
4049
- case SimpleMemoComponent: {
4050
- recursivelyTraversePassiveUnmountEffects(finishedWork);
4051
- if (finishedWork.flags & Passive) {
4052
- commitHookPassiveUnmountEffects(
4053
- finishedWork,
4054
- finishedWork.return,
4055
- HookPassive | HookHasEffect,
4056
- );
4057
- }
4058
- break;
4059
- }
4060
- case OffscreenComponent: {
4061
- const instance: OffscreenInstance = finishedWork.stateNode;
4062
- const nextState: OffscreenState | null = finishedWork.memoizedState;
4063
-
4064
- const isHidden = nextState !== null;
4065
-
4066
- if (
4067
- isHidden &&
4068
- instance._visibility & OffscreenPassiveEffectsConnected &&
4069
- // For backwards compatibility, don't unmount when a tree suspends. In
4070
- // the future we may change this to unmount after a delay.
4071
- (finishedWork.return === null ||
4072
- finishedWork.return.tag !== SuspenseComponent)
4073
- ) {
4074
- // The effects are currently connected. Disconnect them.
4075
- // TODO: Add option or heuristic to delay before disconnecting the
4076
- // effects. Then if the tree reappears before the delay has elapsed, we
4077
- // can skip toggling the effects entirely.
4078
- instance._visibility &= ~OffscreenPassiveEffectsConnected;
4079
- recursivelyTraverseDisconnectPassiveEffects(finishedWork);
4080
- } else {
4081
- recursivelyTraversePassiveUnmountEffects(finishedWork);
4082
- }
4083
-
4084
- break;
4085
- }
4086
- default: {
4087
- recursivelyTraversePassiveUnmountEffects(finishedWork);
4088
- break;
4089
- }
4090
- }
4091
-}
4092
-
4093
-function recursivelyTraverseDisconnectPassiveEffects(parentFiber: Fiber): void {
4094
- // Deletions effects can be scheduled on any fiber type. They need to happen
4095
- // before the children effects have fired.
4096
- const deletions = parentFiber.deletions;
4097
-
4098
- if ((parentFiber.flags & ChildDeletion) !== NoFlags) {
4099
- if (deletions !== null) {
4100
- for (let i = 0; i < deletions.length; i++) {
4101
- const childToDelete = deletions[i];
4102
- // TODO: Convert this to use recursion
4103
- nextEffect = childToDelete;
4104
- commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
4105
- childToDelete,
4106
- parentFiber,
4107
- );
4108
- }
4109
- }
4110
- detachAlternateSiblings(parentFiber);
4111
- }
4112
-
4113
- const prevDebugFiber = getCurrentDebugFiberInDEV();
4114
- // TODO: Check PassiveStatic flag
4115
- let child = parentFiber.child;
4116
- while (child !== null) {
4117
- setCurrentDebugFiberInDEV(child);
4118
- disconnectPassiveEffect(child);
4119
- child = child.sibling;
4120
- }
4121
- setCurrentDebugFiberInDEV(prevDebugFiber);
4122
-}
4123
-
4124
-export function disconnectPassiveEffect(finishedWork: Fiber): void {
4125
- switch (finishedWork.tag) {
4126
- case FunctionComponent:
4127
- case ForwardRef:
4128
- case SimpleMemoComponent: {
4129
- // TODO: Check PassiveStatic flag
4130
- commitHookPassiveUnmountEffects(
4131
- finishedWork,
4132
- finishedWork.return,
4133
- HookPassive,
4134
- );
4135
- // When disconnecting passive effects, we fire the effects in the same
4136
- // order as during a deletiong: parent before child
4137
- recursivelyTraverseDisconnectPassiveEffects(finishedWork);
4138
- break;
4139
- }
4140
- case OffscreenComponent: {
4141
- const instance: OffscreenInstance = finishedWork.stateNode;
4142
- if (instance._visibility & OffscreenPassiveEffectsConnected) {
4143
- instance._visibility &= ~OffscreenPassiveEffectsConnected;
4144
- recursivelyTraverseDisconnectPassiveEffects(finishedWork);
4145
- } else {
4146
- // The effects are already disconnected.
4147
- }
4148
- break;
4149
- }
4150
- default: {
4151
- recursivelyTraverseDisconnectPassiveEffects(finishedWork);
4152
- break;
4153
- }
4154
- }
4155
-}
4156
-
4157
-function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
4158
- deletedSubtreeRoot: Fiber,
4159
- nearestMountedAncestor: Fiber | null,
4160
-) {
4161
- while (nextEffect !== null) {
4162
- const fiber = nextEffect;
4163
-
4164
- // Deletion effects fire in parent -> child order
4165
- // TODO: Check if fiber has a PassiveStatic flag
4166
- setCurrentDebugFiberInDEV(fiber);
4167
- commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor);
4168
- resetCurrentDebugFiberInDEV();
4169
-
4170
- const child = fiber.child;
4171
- // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we
4172
- // do this, still need to handle `deletedTreeCleanUpLevel` correctly.)
4173
- if (child !== null) {
4174
- child.return = fiber;
4175
- nextEffect = child;
4176
- } else {
4177
- commitPassiveUnmountEffectsInsideOfDeletedTree_complete(
4178
- deletedSubtreeRoot,
4179
- );
4180
- }
4181
- }
4182
-}
4183
-
4184
-function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(
4185
- deletedSubtreeRoot: Fiber,
4186
-) {
4187
- while (nextEffect !== null) {
4188
- const fiber = nextEffect;
4189
- const sibling = fiber.sibling;
4190
- const returnFiber = fiber.return;
4191
-
4192
- if (deletedTreeCleanUpLevel >= 2) {
4193
- // Recursively traverse the entire deleted tree and clean up fiber fields.
4194
- // This is more aggressive than ideal, and the long term goal is to only
4195
- // have to detach the deleted tree at the root.
4196
- detachFiberAfterEffects(fiber);
4197
- if (fiber === deletedSubtreeRoot) {
4198
- nextEffect = null;
4199
- return;
4200
- }
4201
- } else {
4202
- // This is the default branch (level 0). We do not recursively clear all
4203
- // the fiber fields. Only the root of the deleted subtree.
4204
- if (fiber === deletedSubtreeRoot) {
4205
- detachFiberAfterEffects(fiber);
4206
- nextEffect = null;
4207
- return;
4208
- }
4209
- }
4210
-
4211
- if (sibling !== null) {
4212
- sibling.return = returnFiber;
4213
- nextEffect = sibling;
4214
- return;
4215
- }
4216
-
4217
- nextEffect = returnFiber;
4218
- }
4219
-}
4220
-
4221
-function commitPassiveUnmountInsideDeletedTreeOnFiber(
4222
- current: Fiber,
4223
- nearestMountedAncestor: Fiber | null,
4224
-): void {
4225
- switch (current.tag) {
4226
- case FunctionComponent:
4227
- case ForwardRef:
4228
- case SimpleMemoComponent: {
4229
- commitHookPassiveUnmountEffects(
4230
- current,
4231
- nearestMountedAncestor,
4232
- HookPassive,
4233
- );
4234
- break;
4235
- }
4236
- // TODO: run passive unmount effects when unmounting a root.
4237
- // Because passive unmount effects are not currently run,
4238
- // the cache instance owned by the root will never be freed.
4239
- // When effects are run, the cache should be freed here:
4240
- // case HostRoot: {
4241
- // if (enableCache) {
4242
- // const cache = current.memoizedState.cache;
4243
- // releaseCache(cache);
4244
- // }
4245
- // break;
4246
- // }
4247
- case LegacyHiddenComponent:
4248
- case OffscreenComponent: {
4249
- if (enableCache) {
4250
- if (
4251
- current.memoizedState !== null &&
4252
- current.memoizedState.cachePool !== null
4253
- ) {
4254
- const cache: Cache = current.memoizedState.cachePool.pool;
4255
- // Retain/release the cache used for pending (suspended) nodes.
4256
- // Note that this is only reached in the non-suspended/visible case:
4257
- // when the content is suspended/hidden, the retain/release occurs
4258
- // via the parent Suspense component (see case above).
4259
- if (cache != null) {
4260
- retainCache(cache);
4261
- }
4262
- }
4263
- }
4264
- break;
4265
- }
4266
- case SuspenseComponent: {
4267
- if (enableTransitionTracing) {
4268
- // We need to mark this fiber's parents as deleted
4269
- const offscreenFiber: Fiber = (current.child: any);
4270
- const instance: OffscreenInstance = offscreenFiber.stateNode;
4271
- const transitions = instance._transitions;
4272
- if (transitions !== null) {
4273
- const abortReason = {
4274
- reason: 'suspense',
4275
- name: current.memoizedProps.unstable_name || null,
4276
- };
4277
- if (
4278
- current.memoizedState === null ||
4279
- current.memoizedState.dehydrated === null
4280
- ) {
4281
- abortParentMarkerTransitionsForDeletedFiber(
4282
- offscreenFiber,
4283
- abortReason,
4284
- transitions,
4285
- instance,
4286
- true,
4287
- );
4288
-
4289
- if (nearestMountedAncestor !== null) {
4290
- abortParentMarkerTransitionsForDeletedFiber(
4291
- nearestMountedAncestor,
4292
- abortReason,
4293
- transitions,
4294
- instance,
4295
- false,
4296
- );
4297
- }
4298
- }
4299
- }
4300
- }
4301
- break;
4302
- }
4303
- case CacheComponent: {
4304
- if (enableCache) {
4305
- const cache = current.memoizedState.cache;
4306
- releaseCache(cache);
4307
- }
4308
- break;
4309
- }
4310
- case TracingMarkerComponent: {
4311
- if (enableTransitionTracing) {
4312
- // We need to mark this fiber's parents as deleted
4313
- const instance: TracingMarkerInstance = current.stateNode;
4314
- const transitions = instance.transitions;
4315
- if (transitions !== null) {
4316
- const abortReason = {
4317
- reason: 'marker',
4318
- name: current.memoizedProps.name,
4319
- };
4320
- abortParentMarkerTransitionsForDeletedFiber(
4321
- current,
4322
- abortReason,
4323
- transitions,
4324
- null,
4325
- true,
4326
- );
4327
-
4328
- if (nearestMountedAncestor !== null) {
4329
- abortParentMarkerTransitionsForDeletedFiber(
4330
- nearestMountedAncestor,
4331
- abortReason,
4332
- transitions,
4333
- null,
4334
- false,
4335
- );
4336
- }
4337
- }
4338
- }
4339
- break;
4340
- }
4341
- }
4342
-}
4343
-
4344
-function invokeLayoutEffectMountInDEV(fiber: Fiber): void {
4345
- if (__DEV__) {
4346
- // We don't need to re-check StrictEffectsMode here.
4347
- // This function is only called if that check has already passed.
4348
- switch (fiber.tag) {
4349
- case FunctionComponent:
4350
- case ForwardRef:
4351
- case SimpleMemoComponent: {
4352
- try {
4353
- commitHookEffectListMount(HookLayout | HookHasEffect, fiber);
4354
- } catch (error) {
4355
- captureCommitPhaseError(fiber, fiber.return, error);
4356
- }
4357
- break;
4358
- }
4359
- case ClassComponent: {
4360
- const instance = fiber.stateNode;
4361
- try {
4362
- instance.componentDidMount();
4363
- } catch (error) {
4364
- captureCommitPhaseError(fiber, fiber.return, error);
4365
- }
4366
- break;
4367
- }
4368
- }
4369
- }
4370
-}
4371
-
4372
-function invokePassiveEffectMountInDEV(fiber: Fiber): void {
4373
- if (__DEV__) {
4374
- // We don't need to re-check StrictEffectsMode here.
4375
- // This function is only called if that check has already passed.
4376
- switch (fiber.tag) {
4377
- case FunctionComponent:
4378
- case ForwardRef:
4379
- case SimpleMemoComponent: {
4380
- try {
4381
- commitHookEffectListMount(HookPassive | HookHasEffect, fiber);
4382
- } catch (error) {
4383
- captureCommitPhaseError(fiber, fiber.return, error);
4384
- }
4385
- break;
4386
- }
4387
- }
4388
- }
4389
-}
4390
-
4391
-function invokeLayoutEffectUnmountInDEV(fiber: Fiber): void {
4392
- if (__DEV__) {
4393
- // We don't need to re-check StrictEffectsMode here.
4394
- // This function is only called if that check has already passed.
4395
- switch (fiber.tag) {
4396
- case FunctionComponent:
4397
- case ForwardRef:
4398
- case SimpleMemoComponent: {
4399
- try {
4400
- commitHookEffectListUnmount(
4401
- HookLayout | HookHasEffect,
4402
- fiber,
4403
- fiber.return,
4404
- );
4405
- } catch (error) {
4406
- captureCommitPhaseError(fiber, fiber.return, error);
4407
- }
4408
- break;
4409
- }
4410
- case ClassComponent: {
4411
- const instance = fiber.stateNode;
4412
- if (typeof instance.componentWillUnmount === 'function') {
4413
- safelyCallComponentWillUnmount(fiber, fiber.return, instance);
4414
- }
4415
- break;
4416
- }
4417
- }
4418
- }
4419
-}
4420
-
4421
-function invokePassiveEffectUnmountInDEV(fiber: Fiber): void {
4422
- if (__DEV__) {
4423
- // We don't need to re-check StrictEffectsMode here.
4424
- // This function is only called if that check has already passed.
4425
- switch (fiber.tag) {
4426
- case FunctionComponent:
4427
- case ForwardRef:
4428
- case SimpleMemoComponent: {
4429
- try {
4430
- commitHookEffectListUnmount(
4431
- HookPassive | HookHasEffect,
4432
- fiber,
4433
- fiber.return,
4434
- );
4435
- } catch (error) {
4436
- captureCommitPhaseError(fiber, fiber.return, error);
4437
- }
4438
- }
4439
- }
4440
- }
4441
-}
4442
-
4443
-export {
4444
- commitPlacement,
4445
- commitAttachRef,
4446
- invokeLayoutEffectMountInDEV,
4447
- invokeLayoutEffectUnmountInDEV,
4448
- invokePassiveEffectMountInDEV,
4449
- invokePassiveEffectUnmountInDEV,
4450
-};
packages/react-reconciler/src/ReactFiberCompleteWork.new.js
deleted
-1686
@@ -1,1686 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
11
-import type {RootState} from './ReactFiberRoot.new';
12
-import type {Lanes, Lane} from './ReactFiberLane.new';
13
-import type {
14
- ReactScopeInstance,
15
- ReactContext,
16
- Wakeable,
17
-} from 'shared/ReactTypes';
18
-import type {
19
- Instance,
20
- Type,
21
- Props,
22
- Container,
23
- ChildSet,
24
-} from './ReactFiberHostConfig';
25
-import type {
26
- SuspenseState,
27
- SuspenseListRenderState,
28
-} from './ReactFiberSuspenseComponent.new';
29
-import {isOffscreenManual} from './ReactFiberOffscreenComponent';
30
-import type {OffscreenState} from './ReactFiberOffscreenComponent';
31
-import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new';
32
-import type {Cache} from './ReactFiberCacheComponent.new';
33
-import {
34
- enableLegacyHidden,
35
- enableHostSingletons,
36
- enableSuspenseCallback,
37
- enableScopeAPI,
38
- enableProfilerTimer,
39
- enableCache,
40
- enableTransitionTracing,
41
- enableFloat,
42
-} from 'shared/ReactFeatureFlags';
43
-
44
-import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.new';
45
-
46
-import {now} from './Scheduler';
47
-
48
-import {
49
- IndeterminateComponent,
50
- FunctionComponent,
51
- ClassComponent,
52
- HostRoot,
53
- HostComponent,
54
- HostResource,
55
- HostSingleton,
56
- HostText,
57
- HostPortal,
58
- ContextProvider,
59
- ContextConsumer,
60
- ForwardRef,
61
- Fragment,
62
- Mode,
63
- Profiler,
64
- SuspenseComponent,
65
- SuspenseListComponent,
66
- MemoComponent,
67
- SimpleMemoComponent,
68
- LazyComponent,
69
- IncompleteClassComponent,
70
- ScopeComponent,
71
- OffscreenComponent,
72
- LegacyHiddenComponent,
73
- CacheComponent,
74
- TracingMarkerComponent,
75
-} from './ReactWorkTags';
76
-import {NoMode, ConcurrentMode, ProfileMode} from './ReactTypeOfMode';
77
-import {
78
- Ref,
79
- RefStatic,
80
- Placement,
81
- Update,
82
- Visibility,
83
- NoFlags,
84
- DidCapture,
85
- Snapshot,
86
- ChildDeletion,
87
- StaticMask,
88
- MutationMask,
89
- Passive,
90
- Incomplete,
91
- ShouldCapture,
92
- ForceClientRender,
93
-} from './ReactFiberFlags';
94
-
95
-import {
96
- createInstance,
97
- createTextInstance,
98
- resolveSingletonInstance,
99
- appendInitialChild,
100
- finalizeInitialChildren,
101
- prepareUpdate,
102
- supportsMutation,
103
- supportsPersistence,
104
- supportsResources,
105
- supportsSingletons,
106
- cloneInstance,
107
- cloneHiddenInstance,
108
- cloneHiddenTextInstance,
109
- createContainerChildSet,
110
- appendChildToContainerChildSet,
111
- finalizeContainerChildren,
112
- preparePortalMount,
113
- prepareScopeUpdate,
114
-} from './ReactFiberHostConfig';
115
-import {
116
- getRootHostContainer,
117
- popHostContext,
118
- getHostContext,
119
- popHostContainer,
120
-} from './ReactFiberHostContext.new';
121
-import {
122
- suspenseStackCursor,
123
- popSuspenseListContext,
124
- popSuspenseHandler,
125
- pushSuspenseListContext,
126
- setShallowSuspenseListContext,
127
- ForceSuspenseFallback,
128
- setDefaultShallowSuspenseListContext,
129
- isBadSuspenseFallback,
130
-} from './ReactFiberSuspenseContext.new';
131
-import {popHiddenContext} from './ReactFiberHiddenContext.new';
132
-import {findFirstSuspended} from './ReactFiberSuspenseComponent.new';
133
-import {
134
- isContextProvider as isLegacyContextProvider,
135
- popContext as popLegacyContext,
136
- popTopLevelContextObject as popTopLevelLegacyContextObject,
137
-} from './ReactFiberContext.new';
138
-import {popProvider} from './ReactFiberNewContext.new';
139
-import {
140
- prepareToHydrateHostInstance,
141
- prepareToHydrateHostTextInstance,
142
- prepareToHydrateHostSuspenseInstance,
143
- warnIfUnhydratedTailNodes,
144
- popHydrationState,
145
- resetHydrationState,
146
- getIsHydrating,
147
- hasUnhydratedTailNodes,
148
- upgradeHydrationErrorsToRecoverable,
149
-} from './ReactFiberHydrationContext.new';
150
-import {
151
- renderDidSuspend,
152
- renderDidSuspendDelayIfPossible,
153
- renderHasNotSuspendedYet,
154
- getRenderTargetTime,
155
- getWorkInProgressTransitions,
156
-} from './ReactFiberWorkLoop.new';
157
-import {
158
- OffscreenLane,
159
- SomeRetryLane,
160
- NoLanes,
161
- includesSomeLane,
162
- mergeLanes,
163
-} from './ReactFiberLane.new';
164
-import {resetChildFibers} from './ReactChildFiber.new';
165
-import {createScopeInstance} from './ReactFiberScope.new';
166
-import {transferActualDuration} from './ReactProfilerTimer.new';
167
-import {popCacheProvider} from './ReactFiberCacheComponent.new';
168
-import {popTreeContext} from './ReactFiberTreeContext.new';
169
-import {popRootTransition, popTransition} from './ReactFiberTransition.new';
170
-import {
171
- popMarkerInstance,
172
- popRootMarkerInstance,
173
-} from './ReactFiberTracingMarkerComponent.new';
174
-
175
-function markUpdate(workInProgress: Fiber) {
176
- // Tag the fiber with an update effect. This turns a Placement into
177
- // a PlacementAndUpdate.
178
- workInProgress.flags |= Update;
179
-}
180
-
181
-function markRef(workInProgress: Fiber) {
182
- workInProgress.flags |= Ref | RefStatic;
183
-}
184
-
185
-function hadNoMutationsEffects(current: null | Fiber, completedWork: Fiber) {
186
- const didBailout = current !== null && current.child === completedWork.child;
187
- if (didBailout) {
188
- return true;
189
- }
190
-
191
- if ((completedWork.flags & ChildDeletion) !== NoFlags) {
192
- return false;
193
- }
194
-
195
- // TODO: If we move the `hadNoMutationsEffects` call after `bubbleProperties`
196
- // then we only have to check the `completedWork.subtreeFlags`.
197
- let child = completedWork.child;
198
- while (child !== null) {
199
- if (
200
- (child.flags & MutationMask) !== NoFlags ||
201
- (child.subtreeFlags & MutationMask) !== NoFlags
202
- ) {
203
- return false;
204
- }
205
- child = child.sibling;
206
- }
207
- return true;
208
-}
209
-
210
-let appendAllChildren;
211
-let updateHostContainer;
212
-let updateHostComponent;
213
-let updateHostText;
214
-if (supportsMutation) {
215
- // Mutation mode
216
-
217
- appendAllChildren = function(
218
- parent: Instance,
219
- workInProgress: Fiber,
220
- needsVisibilityToggle: boolean,
221
- isHidden: boolean,
222
- ) {
223
- // We only have the top Fiber that was created but we need recurse down its
224
- // children to find all the terminal nodes.
225
- let node = workInProgress.child;
226
- while (node !== null) {
227
- if (node.tag === HostComponent || node.tag === HostText) {
228
- appendInitialChild(parent, node.stateNode);
229
- } else if (
230
- node.tag === HostPortal ||
231
- (enableHostSingletons && supportsSingletons
232
- ? node.tag === HostSingleton
233
- : false)
234
- ) {
235
- // If we have a portal child, then we don't want to traverse
236
- // down its children. Instead, we'll get insertions from each child in
237
- // the portal directly.
238
- // If we have a HostSingleton it will be placed independently
239
- } else if (node.child !== null) {
240
- node.child.return = node;
241
- node = node.child;
242
- continue;
243
- }
244
- if (node === workInProgress) {
245
- return;
246
- }
247
- // $FlowFixMe[incompatible-use] found when upgrading Flow
248
- while (node.sibling === null) {
249
- // $FlowFixMe[incompatible-use] found when upgrading Flow
250
- if (node.return === null || node.return === workInProgress) {
251
- return;
252
- }
253
- node = node.return;
254
- }
255
- // $FlowFixMe[incompatible-use] found when upgrading Flow
256
- node.sibling.return = node.return;
257
- node = node.sibling;
258
- }
259
- };
260
-
261
- updateHostContainer = function(current: null | Fiber, workInProgress: Fiber) {
262
- // Noop
263
- };
264
- updateHostComponent = function(
265
- current: Fiber,
266
- workInProgress: Fiber,
267
- type: Type,
268
- newProps: Props,
269
- ) {
270
- // If we have an alternate, that means this is an update and we need to
271
- // schedule a side-effect to do the updates.
272
- const oldProps = current.memoizedProps;
273
- if (oldProps === newProps) {
274
- // In mutation mode, this is sufficient for a bailout because
275
- // we won't touch this node even if children changed.
276
- return;
277
- }
278
-
279
- // If we get updated because one of our children updated, we don't
280
- // have newProps so we'll have to reuse them.
281
- // TODO: Split the update API as separate for the props vs. children.
282
- // Even better would be if children weren't special cased at all tho.
283
- const instance: Instance = workInProgress.stateNode;
284
- const currentHostContext = getHostContext();
285
- // TODO: Experiencing an error where oldProps is null. Suggests a host
286
- // component is hitting the resume path. Figure out why. Possibly
287
- // related to `hidden`.
288
- const updatePayload = prepareUpdate(
289
- instance,
290
- type,
291
- oldProps,
292
- newProps,
293
- currentHostContext,
294
- );
295
- // TODO: Type this specific to this type of component.
296
- workInProgress.updateQueue = (updatePayload: any);
297
- // If the update payload indicates that there is a change or if there
298
- // is a new ref we mark this as an update. All the work is done in commitWork.
299
- if (updatePayload) {
300
- markUpdate(workInProgress);
301
- }
302
- };
303
- updateHostText = function(
304
- current: Fiber,
305
- workInProgress: Fiber,
306
- oldText: string,
307
- newText: string,
308
- ) {
309
- // If the text differs, mark it as an update. All the work in done in commitWork.
310
- if (oldText !== newText) {
311
- markUpdate(workInProgress);
312
- }
313
- };
314
-} else if (supportsPersistence) {
315
- // Persistent host tree mode
316
-
317
- appendAllChildren = function(
318
- parent: Instance,
319
- workInProgress: Fiber,
320
- needsVisibilityToggle: boolean,
321
- isHidden: boolean,
322
- ) {
323
- // We only have the top Fiber that was created but we need recurse down its
324
- // children to find all the terminal nodes.
325
- let node = workInProgress.child;
326
- while (node !== null) {
327
- // eslint-disable-next-line no-labels
328
- branches: if (node.tag === HostComponent) {
329
- let instance = node.stateNode;
330
- if (needsVisibilityToggle && isHidden) {
331
- // This child is inside a timed out tree. Hide it.
332
- const props = node.memoizedProps;
333
- const type = node.type;
334
- instance = cloneHiddenInstance(instance, type, props, node);
335
- }
336
- appendInitialChild(parent, instance);
337
- } else if (node.tag === HostText) {
338
- let instance = node.stateNode;
339
- if (needsVisibilityToggle && isHidden) {
340
- // This child is inside a timed out tree. Hide it.
341
- const text = node.memoizedProps;
342
- instance = cloneHiddenTextInstance(instance, text, node);
343
- }
344
- appendInitialChild(parent, instance);
345
- } else if (node.tag === HostPortal) {
346
- // If we have a portal child, then we don't want to traverse
347
- // down its children. Instead, we'll get insertions from each child in
348
- // the portal directly.
349
- } else if (
350
- node.tag === OffscreenComponent &&
351
- node.memoizedState !== null
352
- ) {
353
- // The children in this boundary are hidden. Toggle their visibility
354
- // before appending.
355
- const child = node.child;
356
- if (child !== null) {
357
- child.return = node;
358
- }
359
- appendAllChildren(parent, node, true, true);
360
- } else if (node.child !== null) {
361
- node.child.return = node;
362
- node = node.child;
363
- continue;
364
- }
365
- node = (node: Fiber);
366
- if (node === workInProgress) {
367
- return;
368
- }
369
- // $FlowFixMe[incompatible-use] found when upgrading Flow
370
- while (node.sibling === null) {
371
- // $FlowFixMe[incompatible-use] found when upgrading Flow
372
- if (node.return === null || node.return === workInProgress) {
373
- return;
374
- }
375
- node = node.return;
376
- }
377
- // $FlowFixMe[incompatible-use] found when upgrading Flow
378
- node.sibling.return = node.return;
379
- node = node.sibling;
380
- }
381
- };
382
-
383
- // An unfortunate fork of appendAllChildren because we have two different parent types.
384
- const appendAllChildrenToContainer = function(
385
- containerChildSet: ChildSet,
386
- workInProgress: Fiber,
387
- needsVisibilityToggle: boolean,
388
- isHidden: boolean,
389
- ) {
390
- // We only have the top Fiber that was created but we need recurse down its
391
- // children to find all the terminal nodes.
392
- let node = workInProgress.child;
393
- while (node !== null) {
394
- // eslint-disable-next-line no-labels
395
- branches: if (node.tag === HostComponent) {
396
- let instance = node.stateNode;
397
- if (needsVisibilityToggle && isHidden) {
398
- // This child is inside a timed out tree. Hide it.
399
- const props = node.memoizedProps;
400
- const type = node.type;
401
- instance = cloneHiddenInstance(instance, type, props, node);
402
- }
403
- appendChildToContainerChildSet(containerChildSet, instance);
404
- } else if (node.tag === HostText) {
405
- let instance = node.stateNode;
406
- if (needsVisibilityToggle && isHidden) {
407
- // This child is inside a timed out tree. Hide it.
408
- const text = node.memoizedProps;
409
- instance = cloneHiddenTextInstance(instance, text, node);
410
- }
411
- appendChildToContainerChildSet(containerChildSet, instance);
412
- } else if (node.tag === HostPortal) {
413
- // If we have a portal child, then we don't want to traverse
414
- // down its children. Instead, we'll get insertions from each child in
415
- // the portal directly.
416
- } else if (
417
- node.tag === OffscreenComponent &&
418
- node.memoizedState !== null
419
- ) {
420
- // The children in this boundary are hidden. Toggle their visibility
421
- // before appending.
422
- const child = node.child;
423
- if (child !== null) {
424
- child.return = node;
425
- }
426
- // If Offscreen is not in manual mode, detached tree is hidden from user space.
427
- const _needsVisibilityToggle = !isOffscreenManual(node);
428
- appendAllChildrenToContainer(
429
- containerChildSet,
430
- node,
431
- _needsVisibilityToggle,
432
- true,
433
- );
434
- } else if (node.child !== null) {
435
- node.child.return = node;
436
- node = node.child;
437
- continue;
438
- }
439
- node = (node: Fiber);
440
- if (node === workInProgress) {
441
- return;
442
- }
443
- // $FlowFixMe[incompatible-use] found when upgrading Flow
444
- while (node.sibling === null) {
445
- // $FlowFixMe[incompatible-use] found when upgrading Flow
446
- if (node.return === null || node.return === workInProgress) {
447
- return;
448
- }
449
- node = node.return;
450
- }
451
- // $FlowFixMe[incompatible-use] found when upgrading Flow
452
- node.sibling.return = node.return;
453
- node = node.sibling;
454
- }
455
- };
456
- updateHostContainer = function(current: null | Fiber, workInProgress: Fiber) {
457
- const portalOrRoot: {
458
- containerInfo: Container,
459
- pendingChildren: ChildSet,
460
- ...
461
- } = workInProgress.stateNode;
462
- const childrenUnchanged = hadNoMutationsEffects(current, workInProgress);
463
- if (childrenUnchanged) {
464
- // No changes, just reuse the existing instance.
465
- } else {
466
- const container = portalOrRoot.containerInfo;
467
- const newChildSet = createContainerChildSet(container);
468
- // If children might have changed, we have to add them all to the set.
469
- appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
470
- portalOrRoot.pendingChildren = newChildSet;
471
- // Schedule an update on the container to swap out the container.
472
- markUpdate(workInProgress);
473
- finalizeContainerChildren(container, newChildSet);
474
- }
475
- };
476
- updateHostComponent = function(
477
- current: Fiber,
478
- workInProgress: Fiber,
479
- type: Type,
480
- newProps: Props,
481
- ) {
482
- const currentInstance = current.stateNode;
483
- const oldProps = current.memoizedProps;
484
- // If there are no effects associated with this node, then none of our children had any updates.
485
- // This guarantees that we can reuse all of them.
486
- const childrenUnchanged = hadNoMutationsEffects(current, workInProgress);
487
- if (childrenUnchanged && oldProps === newProps) {
488
- // No changes, just reuse the existing instance.
489
- // Note that this might release a previous clone.
490
- workInProgress.stateNode = currentInstance;
491
- return;
492
- }
493
- const recyclableInstance: Instance = workInProgress.stateNode;
494
- const currentHostContext = getHostContext();
495
- let updatePayload = null;
496
- if (oldProps !== newProps) {
497
- updatePayload = prepareUpdate(
498
- recyclableInstance,
499
- type,
500
- oldProps,
501
- newProps,
502
- currentHostContext,
503
- );
504
- }
505
- if (childrenUnchanged && updatePayload === null) {
506
- // No changes, just reuse the existing instance.
507
- // Note that this might release a previous clone.
508
- workInProgress.stateNode = currentInstance;
509
- return;
510
- }
511
- const newInstance = cloneInstance(
512
- currentInstance,
513
- updatePayload,
514
- type,
515
- oldProps,
516
- newProps,
517
- workInProgress,
518
- childrenUnchanged,
519
- recyclableInstance,
520
- );
521
- if (
522
- finalizeInitialChildren(newInstance, type, newProps, currentHostContext)
523
- ) {
524
- markUpdate(workInProgress);
525
- }
526
- workInProgress.stateNode = newInstance;
527
- if (childrenUnchanged) {
528
- // If there are no other effects in this tree, we need to flag this node as having one.
529
- // Even though we're not going to use it for anything.
530
- // Otherwise parents won't know that there are new children to propagate upwards.
531
- markUpdate(workInProgress);
532
- } else {
533
- // If children might have changed, we have to add them all to the set.
534
- appendAllChildren(newInstance, workInProgress, false, false);
535
- }
536
- };
537
- updateHostText = function(
538
- current: Fiber,
539
- workInProgress: Fiber,
540
- oldText: string,
541
- newText: string,
542
- ) {
543
- if (oldText !== newText) {
544
- // If the text content differs, we'll create a new text instance for it.
545
- const rootContainerInstance = getRootHostContainer();
546
- const currentHostContext = getHostContext();
547
- workInProgress.stateNode = createTextInstance(
548
- newText,
549
- rootContainerInstance,
550
- currentHostContext,
551
- workInProgress,
552
- );
553
- // We'll have to mark it as having an effect, even though we won't use the effect for anything.
554
- // This lets the parents know that at least one of their children has changed.
555
- markUpdate(workInProgress);
556
- } else {
557
- workInProgress.stateNode = current.stateNode;
558
- }
559
- };
560
-} else {
561
- // No host operations
562
- updateHostContainer = function(current: null | Fiber, workInProgress: Fiber) {
563
- // Noop
564
- };
565
- updateHostComponent = function(
566
- current: Fiber,
567
- workInProgress: Fiber,
568
- type: Type,
569
- newProps: Props,
570
- ) {
571
- // Noop
572
- };
573
- updateHostText = function(
574
- current: Fiber,
575
- workInProgress: Fiber,
576
- oldText: string,
577
- newText: string,
578
- ) {
579
- // Noop
580
- };
581
-}
582
-
583
-function cutOffTailIfNeeded(
584
- renderState: SuspenseListRenderState,
585
- hasRenderedATailFallback: boolean,
586
-) {
587
- if (getIsHydrating()) {
588
- // If we're hydrating, we should consume as many items as we can
589
- // so we don't leave any behind.
590
- return;
591
- }
592
- switch (renderState.tailMode) {
593
- case 'hidden': {
594
- // Any insertions at the end of the tail list after this point
595
- // should be invisible. If there are already mounted boundaries
596
- // anything before them are not considered for collapsing.
597
- // Therefore we need to go through the whole tail to find if
598
- // there are any.
599
- let tailNode = renderState.tail;
600
- let lastTailNode = null;
601
- while (tailNode !== null) {
602
- if (tailNode.alternate !== null) {
603
- lastTailNode = tailNode;
604
- }
605
- tailNode = tailNode.sibling;
606
- }
607
- // Next we're simply going to delete all insertions after the
608
- // last rendered item.
609
- if (lastTailNode === null) {
610
- // All remaining items in the tail are insertions.
611
- renderState.tail = null;
612
- } else {
613
- // Detach the insertion after the last node that was already
614
- // inserted.
615
- lastTailNode.sibling = null;
616
- }
617
- break;
618
- }
619
- case 'collapsed': {
620
- // Any insertions at the end of the tail list after this point
621
- // should be invisible. If there are already mounted boundaries
622
- // anything before them are not considered for collapsing.
623
- // Therefore we need to go through the whole tail to find if
624
- // there are any.
625
- let tailNode = renderState.tail;
626
- let lastTailNode = null;
627
- while (tailNode !== null) {
628
- if (tailNode.alternate !== null) {
629
- lastTailNode = tailNode;
630
- }
631
- tailNode = tailNode.sibling;
632
- }
633
- // Next we're simply going to delete all insertions after the
634
- // last rendered item.
635
- if (lastTailNode === null) {
636
- // All remaining items in the tail are insertions.
637
- if (!hasRenderedATailFallback && renderState.tail !== null) {
638
- // We suspended during the head. We want to show at least one
639
- // row at the tail. So we'll keep on and cut off the rest.
640
- renderState.tail.sibling = null;
641
- } else {
642
- renderState.tail = null;
643
- }
644
- } else {
645
- // Detach the insertion after the last node that was already
646
- // inserted.
647
- lastTailNode.sibling = null;
648
- }
649
- break;
650
- }
651
- }
652
-}
653
-
654
-function bubbleProperties(completedWork: Fiber) {
655
- const didBailout =
656
- completedWork.alternate !== null &&
657
- completedWork.alternate.child === completedWork.child;
658
-
659
- let newChildLanes = NoLanes;
660
- let subtreeFlags = NoFlags;
661
-
662
- if (!didBailout) {
663
- // Bubble up the earliest expiration time.
664
- if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
665
- // In profiling mode, resetChildExpirationTime is also used to reset
666
- // profiler durations.
667
- let actualDuration = completedWork.actualDuration;
668
- let treeBaseDuration = ((completedWork.selfBaseDuration: any): number);
669
-
670
- let child = completedWork.child;
671
- while (child !== null) {
672
- newChildLanes = mergeLanes(
673
- newChildLanes,
674
- mergeLanes(child.lanes, child.childLanes),
675
- );
676
-
677
- subtreeFlags |= child.subtreeFlags;
678
- subtreeFlags |= child.flags;
679
-
680
- // When a fiber is cloned, its actualDuration is reset to 0. This value will
681
- // only be updated if work is done on the fiber (i.e. it doesn't bailout).
682
- // When work is done, it should bubble to the parent's actualDuration. If
683
- // the fiber has not been cloned though, (meaning no work was done), then
684
- // this value will reflect the amount of time spent working on a previous
685
- // render. In that case it should not bubble. We determine whether it was
686
- // cloned by comparing the child pointer.
687
- // $FlowFixMe[unsafe-addition] addition with possible null/undefined value
688
- actualDuration += child.actualDuration;
689
-
690
- // $FlowFixMe[unsafe-addition] addition with possible null/undefined value
691
- treeBaseDuration += child.treeBaseDuration;
692
- child = child.sibling;
693
- }
694
-
695
- completedWork.actualDuration = actualDuration;
696
- completedWork.treeBaseDuration = treeBaseDuration;
697
- } else {
698
- let child = completedWork.child;
699
- while (child !== null) {
700
- newChildLanes = mergeLanes(
701
- newChildLanes,
702
- mergeLanes(child.lanes, child.childLanes),
703
- );
704
-
705
- subtreeFlags |= child.subtreeFlags;
706
- subtreeFlags |= child.flags;
707
-
708
- // Update the return pointer so the tree is consistent. This is a code
709
- // smell because it assumes the commit phase is never concurrent with
710
- // the render phase. Will address during refactor to alternate model.
711
- child.return = completedWork;
712
-
713
- child = child.sibling;
714
- }
715
- }
716
-
717
- completedWork.subtreeFlags |= subtreeFlags;
718
- } else {
719
- // Bubble up the earliest expiration time.
720
- if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
721
- // In profiling mode, resetChildExpirationTime is also used to reset
722
- // profiler durations.
723
- let treeBaseDuration = ((completedWork.selfBaseDuration: any): number);
724
-
725
- let child = completedWork.child;
726
- while (child !== null) {
727
- newChildLanes = mergeLanes(
728
- newChildLanes,
729
- mergeLanes(child.lanes, child.childLanes),
730
- );
731
-
732
- // "Static" flags share the lifetime of the fiber/hook they belong to,
733
- // so we should bubble those up even during a bailout. All the other
734
- // flags have a lifetime only of a single render + commit, so we should
735
- // ignore them.
736
- subtreeFlags |= child.subtreeFlags & StaticMask;
737
- subtreeFlags |= child.flags & StaticMask;
738
-
739
- // $FlowFixMe[unsafe-addition] addition with possible null/undefined value
740
- treeBaseDuration += child.treeBaseDuration;
741
- child = child.sibling;
742
- }
743
-
744
- completedWork.treeBaseDuration = treeBaseDuration;
745
- } else {
746
- let child = completedWork.child;
747
- while (child !== null) {
748
- newChildLanes = mergeLanes(
749
- newChildLanes,
750
- mergeLanes(child.lanes, child.childLanes),
751
- );
752
-
753
- // "Static" flags share the lifetime of the fiber/hook they belong to,
754
- // so we should bubble those up even during a bailout. All the other
755
- // flags have a lifetime only of a single render + commit, so we should
756
- // ignore them.
757
- subtreeFlags |= child.subtreeFlags & StaticMask;
758
- subtreeFlags |= child.flags & StaticMask;
759
-
760
- // Update the return pointer so the tree is consistent. This is a code
761
- // smell because it assumes the commit phase is never concurrent with
762
- // the render phase. Will address during refactor to alternate model.
763
- child.return = completedWork;
764
-
765
- child = child.sibling;
766
- }
767
- }
768
-
769
- completedWork.subtreeFlags |= subtreeFlags;
770
- }
771
-
772
- completedWork.childLanes = newChildLanes;
773
-
774
- return didBailout;
775
-}
776
-
777
-function completeDehydratedSuspenseBoundary(
778
- current: Fiber | null,
779
- workInProgress: Fiber,
780
- nextState: SuspenseState | null,
781
-): boolean {
782
- if (
783
- hasUnhydratedTailNodes() &&
784
- (workInProgress.mode & ConcurrentMode) !== NoMode &&
785
- (workInProgress.flags & DidCapture) === NoFlags
786
- ) {
787
- warnIfUnhydratedTailNodes(workInProgress);
788
- resetHydrationState();
789
- workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture;
790
-
791
- return false;
792
- }
793
-
794
- const wasHydrated = popHydrationState(workInProgress);
795
-
796
- if (nextState !== null && nextState.dehydrated !== null) {
797
- // We might be inside a hydration state the first time we're picking up this
798
- // Suspense boundary, and also after we've reentered it for further hydration.
799
- if (current === null) {
800
- if (!wasHydrated) {
801
- throw new Error(
802
- 'A dehydrated suspense component was completed without a hydrated node. ' +
803
- 'This is probably a bug in React.',
804
- );
805
- }
806
- prepareToHydrateHostSuspenseInstance(workInProgress);
807
- bubbleProperties(workInProgress);
808
- if (enableProfilerTimer) {
809
- if ((workInProgress.mode & ProfileMode) !== NoMode) {
810
- const isTimedOutSuspense = nextState !== null;
811
- if (isTimedOutSuspense) {
812
- // Don't count time spent in a timed out Suspense subtree as part of the base duration.
813
- const primaryChildFragment = workInProgress.child;
814
- if (primaryChildFragment !== null) {
815
- // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
816
- workInProgress.treeBaseDuration -= ((primaryChildFragment.treeBaseDuration: any): number);
817
- }
818
- }
819
- }
820
- }
821
- return false;
822
- } else {
823
- // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration
824
- // state since we're now exiting out of it. popHydrationState doesn't do that for us.
825
- resetHydrationState();
826
- if ((workInProgress.flags & DidCapture) === NoFlags) {
827
- // This boundary did not suspend so it's now hydrated and unsuspended.
828
- workInProgress.memoizedState = null;
829
- }
830
- // If nothing suspended, we need to schedule an effect to mark this boundary
831
- // as having hydrated so events know that they're free to be invoked.
832
- // It's also a signal to replay events and the suspense callback.
833
- // If something suspended, schedule an effect to attach retry listeners.
834
- // So we might as well always mark this.
835
- workInProgress.flags |= Update;
836
- bubbleProperties(workInProgress);
837
- if (enableProfilerTimer) {
838
- if ((workInProgress.mode & ProfileMode) !== NoMode) {
839
- const isTimedOutSuspense = nextState !== null;
840
- if (isTimedOutSuspense) {
841
- // Don't count time spent in a timed out Suspense subtree as part of the base duration.
842
- const primaryChildFragment = workInProgress.child;
843
- if (primaryChildFragment !== null) {
844
- // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
845
- workInProgress.treeBaseDuration -= ((primaryChildFragment.treeBaseDuration: any): number);
846
- }
847
- }
848
- }
849
- }
850
- return false;
851
- }
852
- } else {
853
- // Successfully completed this tree. If this was a forced client render,
854
- // there may have been recoverable errors during first hydration
855
- // attempt. If so, add them to a queue so we can log them in the
856
- // commit phase.
857
- upgradeHydrationErrorsToRecoverable();
858
-
859
- // Fall through to normal Suspense path
860
- return true;
861
- }
862
-}
863
-
864
-function completeWork(
865
- current: Fiber | null,
866
- workInProgress: Fiber,
867
- renderLanes: Lanes,
868
-): Fiber | null {
869
- const newProps = workInProgress.pendingProps;
870
- // Note: This intentionally doesn't check if we're hydrating because comparing
871
- // to the current tree provider fiber is just as fast and less error-prone.
872
- // Ideally we would have a special version of the work loop only
873
- // for hydration.
874
- popTreeContext(workInProgress);
875
- switch (workInProgress.tag) {
876
- case IndeterminateComponent:
877
- case LazyComponent:
878
- case SimpleMemoComponent:
879
- case FunctionComponent:
880
- case ForwardRef:
881
- case Fragment:
882
- case Mode:
883
- case Profiler:
884
- case ContextConsumer:
885
- case MemoComponent:
886
- bubbleProperties(workInProgress);
887
- return null;
888
- case ClassComponent: {
889
- const Component = workInProgress.type;
890
- if (isLegacyContextProvider(Component)) {
891
- popLegacyContext(workInProgress);
892
- }
893
- bubbleProperties(workInProgress);
894
- return null;
895
- }
896
- case HostRoot: {
897
- const fiberRoot = (workInProgress.stateNode: FiberRoot);
898
-
899
- if (enableTransitionTracing) {
900
- const transitions = getWorkInProgressTransitions();
901
- // We set the Passive flag here because if there are new transitions,
902
- // we will need to schedule callbacks and process the transitions,
903
- // which we do in the passive phase
904
- if (transitions !== null) {
905
- workInProgress.flags |= Passive;
906
- }
907
- }
908
-
909
- if (enableCache) {
910
- let previousCache: Cache | null = null;
911
- if (current !== null) {
912
- previousCache = current.memoizedState.cache;
913
- }
914
- const cache: Cache = workInProgress.memoizedState.cache;
915
- if (cache !== previousCache) {
916
- // Run passive effects to retain/release the cache.
917
- workInProgress.flags |= Passive;
918
- }
919
- popCacheProvider(workInProgress, cache);
920
- }
921
-
922
- if (enableTransitionTracing) {
923
- popRootMarkerInstance(workInProgress);
924
- }
925
-
926
- popRootTransition(workInProgress, fiberRoot, renderLanes);
927
- popHostContainer(workInProgress);
928
- popTopLevelLegacyContextObject(workInProgress);
929
- resetMutableSourceWorkInProgressVersions();
930
- if (fiberRoot.pendingContext) {
931
- fiberRoot.context = fiberRoot.pendingContext;
932
- fiberRoot.pendingContext = null;
933
- }
934
- if (current === null || current.child === null) {
935
- // If we hydrated, pop so that we can delete any remaining children
936
- // that weren't hydrated.
937
- const wasHydrated = popHydrationState(workInProgress);
938
- if (wasHydrated) {
939
- // If we hydrated, then we'll need to schedule an update for
940
- // the commit side-effects on the root.
941
- markUpdate(workInProgress);
942
- } else {
943
- if (current !== null) {
944
- const prevState: RootState = current.memoizedState;
945
- if (
946
- // Check if this is a client root
947
- !prevState.isDehydrated ||
948
- // Check if we reverted to client rendering (e.g. due to an error)
949
- (workInProgress.flags & ForceClientRender) !== NoFlags
950
- ) {
951
- // Schedule an effect to clear this container at the start of the
952
- // next commit. This handles the case of React rendering into a
953
- // container with previous children. It's also safe to do for
954
- // updates too, because current.child would only be null if the
955
- // previous render was null (so the container would already
956
- // be empty).
957
- workInProgress.flags |= Snapshot;
958
-
959
- // If this was a forced client render, there may have been
960
- // recoverable errors during first hydration attempt. If so, add
961
- // them to a queue so we can log them in the commit phase.
962
- upgradeHydrationErrorsToRecoverable();
963
- }
964
- }
965
- }
966
- }
967
- updateHostContainer(current, workInProgress);
968
- bubbleProperties(workInProgress);
969
- if (enableTransitionTracing) {
970
- if ((workInProgress.subtreeFlags & Visibility) !== NoFlags) {
971
- // If any of our suspense children toggle visibility, this means that
972
- // the pending boundaries array needs to be updated, which we only
973
- // do in the passive phase.
974
- workInProgress.flags |= Passive;
975
- }
976
- }
977
- return null;
978
- }
979
- case HostResource: {
980
- if (enableFloat && supportsResources) {
981
- popHostContext(workInProgress);
982
- const currentRef = current ? current.ref : null;
983
- if (currentRef !== workInProgress.ref) {
984
- markRef(workInProgress);
985
- }
986
- if (
987
- current === null ||
988
- current.memoizedState !== workInProgress.memoizedState
989
- ) {
990
- // The workInProgress resource is different than the current one or the current
991
- // one does not exist
992
- markUpdate(workInProgress);
993
- }
994
- bubbleProperties(workInProgress);
995
- return null;
996
- }
997
- }
998
- // eslint-disable-next-line-no-fallthrough
999
- case HostSingleton: {
1000
- if (enableHostSingletons && supportsSingletons) {
1001
- popHostContext(workInProgress);
1002
- const rootContainerInstance = getRootHostContainer();
1003
- const type = workInProgress.type;
1004
- if (current !== null && workInProgress.stateNode != null) {
1005
- updateHostComponent(current, workInProgress, type, newProps);
1006
-
1007
- if (current.ref !== workInProgress.ref) {
1008
- markRef(workInProgress);
1009
- }
1010
- } else {
1011
- if (!newProps) {
1012
- if (workInProgress.stateNode === null) {
1013
- throw new Error(
1014
- 'We must have new props for new mounts. This error is likely ' +
1015
- 'caused by a bug in React. Please file an issue.',
1016
- );
1017
- }
1018
-
1019
- // This can happen when we abort work.
1020
- bubbleProperties(workInProgress);
1021
- return null;
1022
- }
1023
-
1024
- const currentHostContext = getHostContext();
1025
- const wasHydrated = popHydrationState(workInProgress);
1026
- if (wasHydrated) {
1027
- // We ignore the boolean indicating there is an updateQueue because
1028
- // it is used only to set text children and HostSingletons do not
1029
- // use them.
1030
- prepareToHydrateHostInstance(workInProgress, currentHostContext);
1031
- } else {
1032
- workInProgress.stateNode = resolveSingletonInstance(
1033
- type,
1034
- newProps,
1035
- rootContainerInstance,
1036
- currentHostContext,
1037
- true,
1038
- );
1039
- markUpdate(workInProgress);
1040
- }
1041
-
1042
- if (workInProgress.ref !== null) {
1043
- // If there is a ref on a host node we need to schedule a callback
1044
- markRef(workInProgress);
1045
- }
1046
- }
1047
- bubbleProperties(workInProgress);
1048
- return null;
1049
- }
1050
- }
1051
- // eslint-disable-next-line-no-fallthrough
1052
- case HostComponent: {
1053
- popHostContext(workInProgress);
1054
- const type = workInProgress.type;
1055
- if (current !== null && workInProgress.stateNode != null) {
1056
- updateHostComponent(current, workInProgress, type, newProps);
1057
-
1058
- if (current.ref !== workInProgress.ref) {
1059
- markRef(workInProgress);
1060
- }
1061
- } else {
1062
- if (!newProps) {
1063
- if (workInProgress.stateNode === null) {
1064
- throw new Error(
1065
- 'We must have new props for new mounts. This error is likely ' +
1066
- 'caused by a bug in React. Please file an issue.',
1067
- );
1068
- }
1069
-
1070
- // This can happen when we abort work.
1071
- bubbleProperties(workInProgress);
1072
- return null;
1073
- }
1074
-
1075
- const currentHostContext = getHostContext();
1076
- // TODO: Move createInstance to beginWork and keep it on a context
1077
- // "stack" as the parent. Then append children as we go in beginWork
1078
- // or completeWork depending on whether we want to add them top->down or
1079
- // bottom->up. Top->down is faster in IE11.
1080
- const wasHydrated = popHydrationState(workInProgress);
1081
- if (wasHydrated) {
1082
- // TODO: Move this and createInstance step into the beginPhase
1083
- // to consolidate.
1084
- if (
1085
- prepareToHydrateHostInstance(workInProgress, currentHostContext)
1086
- ) {
1087
- // If changes to the hydrated node need to be applied at the
1088
- // commit-phase we mark this as such.
1089
- markUpdate(workInProgress);
1090
- }
1091
- } else {
1092
- const rootContainerInstance = getRootHostContainer();
1093
- const instance = createInstance(
1094
- type,
1095
- newProps,
1096
- rootContainerInstance,
1097
- currentHostContext,
1098
- workInProgress,
1099
- );
1100
- appendAllChildren(instance, workInProgress, false, false);
1101
- workInProgress.stateNode = instance;
1102
-
1103
- // Certain renderers require commit-time effects for initial mount.
1104
- // (eg DOM renderer supports auto-focus for certain elements).
1105
- // Make sure such renderers get scheduled for later work.
1106
- if (
1107
- finalizeInitialChildren(
1108
- instance,
1109
- type,
1110
- newProps,
1111
- currentHostContext,
1112
- )
1113
- ) {
1114
- markUpdate(workInProgress);
1115
- }
1116
- }
1117
-
1118
- if (workInProgress.ref !== null) {
1119
- // If there is a ref on a host node we need to schedule a callback
1120
- markRef(workInProgress);
1121
- }
1122
- }
1123
- bubbleProperties(workInProgress);
1124
- return null;
1125
- }
1126
- case HostText: {
1127
- const newText = newProps;
1128
- if (current && workInProgress.stateNode != null) {
1129
- const oldText = current.memoizedProps;
1130
- // If we have an alternate, that means this is an update and we need
1131
- // to schedule a side-effect to do the updates.
1132
- updateHostText(current, workInProgress, oldText, newText);
1133
- } else {
1134
- if (typeof newText !== 'string') {
1135
- if (workInProgress.stateNode === null) {
1136
- throw new Error(
1137
- 'We must have new props for new mounts. This error is likely ' +
1138
- 'caused by a bug in React. Please file an issue.',
1139
- );
1140
- }
1141
- // This can happen when we abort work.
1142
- }
1143
- const rootContainerInstance = getRootHostContainer();
1144
- const currentHostContext = getHostContext();
1145
- const wasHydrated = popHydrationState(workInProgress);
1146
- if (wasHydrated) {
1147
- if (prepareToHydrateHostTextInstance(workInProgress)) {
1148
- markUpdate(workInProgress);
1149
- }
1150
- } else {
1151
- workInProgress.stateNode = createTextInstance(
1152
- newText,
1153
- rootContainerInstance,
1154
- currentHostContext,
1155
- workInProgress,
1156
- );
1157
- }
1158
- }
1159
- bubbleProperties(workInProgress);
1160
- return null;
1161
- }
1162
- case SuspenseComponent: {
1163
- popSuspenseHandler(workInProgress);
1164
- const nextState: null | SuspenseState = workInProgress.memoizedState;
1165
-
1166
- // Special path for dehydrated boundaries. We may eventually move this
1167
- // to its own fiber type so that we can add other kinds of hydration
1168
- // boundaries that aren't associated with a Suspense tree. In anticipation
1169
- // of such a refactor, all the hydration logic is contained in
1170
- // this branch.
1171
- if (
1172
- current === null ||
1173
- (current.memoizedState !== null &&
1174
- current.memoizedState.dehydrated !== null)
1175
- ) {
1176
- const fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(
1177
- current,
1178
- workInProgress,
1179
- nextState,
1180
- );
1181
- if (!fallthroughToNormalSuspensePath) {
1182
- if (workInProgress.flags & ShouldCapture) {
1183
- // Special case. There were remaining unhydrated nodes. We treat
1184
- // this as a mismatch. Revert to client rendering.
1185
- return workInProgress;
1186
- } else {
1187
- // Did not finish hydrating, either because this is the initial
1188
- // render or because something suspended.
1189
- return null;
1190
- }
1191
- }
1192
-
1193
- // Continue with the normal Suspense path.
1194
- }
1195
-
1196
- if ((workInProgress.flags & DidCapture) !== NoFlags) {
1197
- // Something suspended. Re-render with the fallback children.
1198
- workInProgress.lanes = renderLanes;
1199
- // Do not reset the effect list.
1200
- if (
1201
- enableProfilerTimer &&
1202
- (workInProgress.mode & ProfileMode) !== NoMode
1203
- ) {
1204
- transferActualDuration(workInProgress);
1205
- }
1206
- // Don't bubble properties in this case.
1207
- return workInProgress;
1208
- }
1209
-
1210
- const nextDidTimeout = nextState !== null;
1211
- const prevDidTimeout =
1212
- current !== null &&
1213
- (current.memoizedState: null | SuspenseState) !== null;
1214
-
1215
- if (enableCache && nextDidTimeout) {
1216
- const offscreenFiber: Fiber = (workInProgress.child: any);
1217
- let previousCache: Cache | null = null;
1218
- if (
1219
- offscreenFiber.alternate !== null &&
1220
- offscreenFiber.alternate.memoizedState !== null &&
1221
- offscreenFiber.alternate.memoizedState.cachePool !== null
1222
- ) {
1223
- previousCache = offscreenFiber.alternate.memoizedState.cachePool.pool;
1224
- }
1225
- let cache: Cache | null = null;
1226
- if (
1227
- offscreenFiber.memoizedState !== null &&
1228
- offscreenFiber.memoizedState.cachePool !== null
1229
- ) {
1230
- cache = offscreenFiber.memoizedState.cachePool.pool;
1231
- }
1232
- if (cache !== previousCache) {
1233
- // Run passive effects to retain/release the cache.
1234
- offscreenFiber.flags |= Passive;
1235
- }
1236
- }
1237
-
1238
- // If the suspended state of the boundary changes, we need to schedule
1239
- // a passive effect, which is when we process the transitions
1240
- if (nextDidTimeout !== prevDidTimeout) {
1241
- if (enableTransitionTracing) {
1242
- const offscreenFiber: Fiber = (workInProgress.child: any);
1243
- offscreenFiber.flags |= Passive;
1244
- }
1245
-
1246
- // If the suspended state of the boundary changes, we need to schedule
1247
- // an effect to toggle the subtree's visibility. When we switch from
1248
- // fallback -> primary, the inner Offscreen fiber schedules this effect
1249
- // as part of its normal complete phase. But when we switch from
1250
- // primary -> fallback, the inner Offscreen fiber does not have a complete
1251
- // phase. So we need to schedule its effect here.
1252
- //
1253
- // We also use this flag to connect/disconnect the effects, but the same
1254
- // logic applies: when re-connecting, the Offscreen fiber's complete
1255
- // phase will handle scheduling the effect. It's only when the fallback
1256
- // is active that we have to do anything special.
1257
- if (nextDidTimeout) {
1258
- const offscreenFiber: Fiber = (workInProgress.child: any);
1259
- offscreenFiber.flags |= Visibility;
1260
-
1261
- // TODO: This will still suspend a synchronous tree if anything
1262
- // in the concurrent tree already suspended during this render.
1263
- // This is a known bug.
1264
- if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
1265
- // TODO: Move this back to throwException because this is too late
1266
- // if this is a large tree which is common for initial loads. We
1267
- // don't know if we should restart a render or not until we get
1268
- // this marker, and this is too late.
1269
- // If this render already had a ping or lower pri updates,
1270
- // and this is the first time we know we're going to suspend we
1271
- // should be able to immediately restart from within throwException.
1272
- if (isBadSuspenseFallback(current, newProps)) {
1273
- renderDidSuspendDelayIfPossible();
1274
- } else {
1275
- renderDidSuspend();
1276
- }
1277
- }
1278
- }
1279
- }
1280
-
1281
- const wakeables: Set<Wakeable> | null = (workInProgress.updateQueue: any);
1282
- if (wakeables !== null) {
1283
- // Schedule an effect to attach a retry listener to the promise.
1284
- // TODO: Move to passive phase
1285
- workInProgress.flags |= Update;
1286
- }
1287
-
1288
- if (
1289
- enableSuspenseCallback &&
1290
- workInProgress.updateQueue !== null &&
1291
- workInProgress.memoizedProps.suspenseCallback != null
1292
- ) {
1293
- // Always notify the callback
1294
- // TODO: Move to passive phase
1295
- workInProgress.flags |= Update;
1296
- }
1297
- bubbleProperties(workInProgress);
1298
- if (enableProfilerTimer) {
1299
- if ((workInProgress.mode & ProfileMode) !== NoMode) {
1300
- if (nextDidTimeout) {
1301
- // Don't count time spent in a timed out Suspense subtree as part of the base duration.
1302
- const primaryChildFragment = workInProgress.child;
1303
- if (primaryChildFragment !== null) {
1304
- // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
1305
- workInProgress.treeBaseDuration -= ((primaryChildFragment.treeBaseDuration: any): number);
1306
- }
1307
- }
1308
- }
1309
- }
1310
- return null;
1311
- }
1312
- case HostPortal:
1313
- popHostContainer(workInProgress);
1314
- updateHostContainer(current, workInProgress);
1315
- if (current === null) {
1316
- preparePortalMount(workInProgress.stateNode.containerInfo);
1317
- }
1318
- bubbleProperties(workInProgress);
1319
- return null;
1320
- case ContextProvider:
1321
- // Pop provider fiber
1322
- const context: ReactContext<any> = workInProgress.type._context;
1323
- popProvider(context, workInProgress);
1324
- bubbleProperties(workInProgress);
1325
- return null;
1326
- case IncompleteClassComponent: {
1327
- // Same as class component case. I put it down here so that the tags are
1328
- // sequential to ensure this switch is compiled to a jump table.
1329
- const Component = workInProgress.type;
1330
- if (isLegacyContextProvider(Component)) {
1331
- popLegacyContext(workInProgress);
1332
- }
1333
- bubbleProperties(workInProgress);
1334
- return null;
1335
- }
1336
- case SuspenseListComponent: {
1337
- popSuspenseListContext(workInProgress);
1338
-
1339
- const renderState: null | SuspenseListRenderState =
1340
- workInProgress.memoizedState;
1341
-
1342
- if (renderState === null) {
1343
- // We're running in the default, "independent" mode.
1344
- // We don't do anything in this mode.
1345
- bubbleProperties(workInProgress);
1346
- return null;
1347
- }
1348
-
1349
- let didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags;
1350
-
1351
- const renderedTail = renderState.rendering;
1352
- if (renderedTail === null) {
1353
- // We just rendered the head.
1354
- if (!didSuspendAlready) {
1355
- // This is the first pass. We need to figure out if anything is still
1356
- // suspended in the rendered set.
1357
-
1358
- // If new content unsuspended, but there's still some content that
1359
- // didn't. Then we need to do a second pass that forces everything
1360
- // to keep showing their fallbacks.
1361
-
1362
- // We might be suspended if something in this render pass suspended, or
1363
- // something in the previous committed pass suspended. Otherwise,
1364
- // there's no chance so we can skip the expensive call to
1365
- // findFirstSuspended.
1366
- const cannotBeSuspended =
1367
- renderHasNotSuspendedYet() &&
1368
- (current === null || (current.flags & DidCapture) === NoFlags);
1369
- if (!cannotBeSuspended) {
1370
- let row = workInProgress.child;
1371
- while (row !== null) {
1372
- const suspended = findFirstSuspended(row);
1373
- if (suspended !== null) {
1374
- didSuspendAlready = true;
1375
- workInProgress.flags |= DidCapture;
1376
- cutOffTailIfNeeded(renderState, false);
1377
-
1378
- // If this is a newly suspended tree, it might not get committed as
1379
- // part of the second pass. In that case nothing will subscribe to
1380
- // its thenables. Instead, we'll transfer its thenables to the
1381
- // SuspenseList so that it can retry if they resolve.
1382
- // There might be multiple of these in the list but since we're
1383
- // going to wait for all of them anyway, it doesn't really matter
1384
- // which ones gets to ping. In theory we could get clever and keep
1385
- // track of how many dependencies remain but it gets tricky because
1386
- // in the meantime, we can add/remove/change items and dependencies.
1387
- // We might bail out of the loop before finding any but that
1388
- // doesn't matter since that means that the other boundaries that
1389
- // we did find already has their listeners attached.
1390
- const newThenables = suspended.updateQueue;
1391
- if (newThenables !== null) {
1392
- workInProgress.updateQueue = newThenables;
1393
- workInProgress.flags |= Update;
1394
- }
1395
-
1396
- // Rerender the whole list, but this time, we'll force fallbacks
1397
- // to stay in place.
1398
- // Reset the effect flags before doing the second pass since that's now invalid.
1399
- // Reset the child fibers to their original state.
1400
- workInProgress.subtreeFlags = NoFlags;
1401
- resetChildFibers(workInProgress, renderLanes);
1402
-
1403
- // Set up the Suspense List Context to force suspense and
1404
- // immediately rerender the children.
1405
- pushSuspenseListContext(
1406
- workInProgress,
1407
- setShallowSuspenseListContext(
1408
- suspenseStackCursor.current,
1409
- ForceSuspenseFallback,
1410
- ),
1411
- );
1412
- // Don't bubble properties in this case.
1413
- return workInProgress.child;
1414
- }
1415
- row = row.sibling;
1416
- }
1417
- }
1418
-
1419
- if (renderState.tail !== null && now() > getRenderTargetTime()) {
1420
- // We have already passed our CPU deadline but we still have rows
1421
- // left in the tail. We'll just give up further attempts to render
1422
- // the main content and only render fallbacks.
1423
- workInProgress.flags |= DidCapture;
1424
- didSuspendAlready = true;
1425
-
1426
- cutOffTailIfNeeded(renderState, false);
1427
-
1428
- // Since nothing actually suspended, there will nothing to ping this
1429
- // to get it started back up to attempt the next item. While in terms
1430
- // of priority this work has the same priority as this current render,
1431
- // it's not part of the same transition once the transition has
1432
- // committed. If it's sync, we still want to yield so that it can be
1433
- // painted. Conceptually, this is really the same as pinging.
1434
- // We can use any RetryLane even if it's the one currently rendering
1435
- // since we're leaving it behind on this node.
1436
- workInProgress.lanes = SomeRetryLane;
1437
- }
1438
- } else {
1439
- cutOffTailIfNeeded(renderState, false);
1440
- }
1441
- // Next we're going to render the tail.
1442
- } else {
1443
- // Append the rendered row to the child list.
1444
- if (!didSuspendAlready) {
1445
- const suspended = findFirstSuspended(renderedTail);
1446
- if (suspended !== null) {
1447
- workInProgress.flags |= DidCapture;
1448
- didSuspendAlready = true;
1449
-
1450
- // Ensure we transfer the update queue to the parent so that it doesn't
1451
- // get lost if this row ends up dropped during a second pass.
1452
- const newThenables = suspended.updateQueue;
1453
- if (newThenables !== null) {
1454
- workInProgress.updateQueue = newThenables;
1455
- workInProgress.flags |= Update;
1456
- }
1457
-
1458
- cutOffTailIfNeeded(renderState, true);
1459
- // This might have been modified.
1460
- if (
1461
- renderState.tail === null &&
1462
- renderState.tailMode === 'hidden' &&
1463
- !renderedTail.alternate &&
1464
- !getIsHydrating() // We don't cut it if we're hydrating.
1465
- ) {
1466
- // We're done.
1467
- bubbleProperties(workInProgress);
1468
- return null;
1469
- }
1470
- } else if (
1471
- // The time it took to render last row is greater than the remaining
1472
- // time we have to render. So rendering one more row would likely
1473
- // exceed it.
1474
- now() * 2 - renderState.renderingStartTime >
1475
- getRenderTargetTime() &&
1476
- renderLanes !== OffscreenLane
1477
- ) {
1478
- // We have now passed our CPU deadline and we'll just give up further
1479
- // attempts to render the main content and only render fallbacks.
1480
- // The assumption is that this is usually faster.
1481
- workInProgress.flags |= DidCapture;
1482
- didSuspendAlready = true;
1483
-
1484
- cutOffTailIfNeeded(renderState, false);
1485
-
1486
- // Since nothing actually suspended, there will nothing to ping this
1487
- // to get it started back up to attempt the next item. While in terms
1488
- // of priority this work has the same priority as this current render,
1489
- // it's not part of the same transition once the transition has
1490
- // committed. If it's sync, we still want to yield so that it can be
1491
- // painted. Conceptually, this is really the same as pinging.
1492
- // We can use any RetryLane even if it's the one currently rendering
1493
- // since we're leaving it behind on this node.
1494
- workInProgress.lanes = SomeRetryLane;
1495
- }
1496
- }
1497
- if (renderState.isBackwards) {
1498
- // The effect list of the backwards tail will have been added
1499
- // to the end. This breaks the guarantee that life-cycles fire in
1500
- // sibling order but that isn't a strong guarantee promised by React.
1501
- // Especially since these might also just pop in during future commits.
1502
- // Append to the beginning of the list.
1503
- renderedTail.sibling = workInProgress.child;
1504
- workInProgress.child = renderedTail;
1505
- } else {
1506
- const previousSibling = renderState.last;
1507
- if (previousSibling !== null) {
1508
- previousSibling.sibling = renderedTail;
1509
- } else {
1510
- workInProgress.child = renderedTail;
1511
- }
1512
- renderState.last = renderedTail;
1513
- }
1514
- }
1515
-
1516
- if (renderState.tail !== null) {
1517
- // We still have tail rows to render.
1518
- // Pop a row.
1519
- const next = renderState.tail;
1520
- renderState.rendering = next;
1521
- renderState.tail = next.sibling;
1522
- renderState.renderingStartTime = now();
1523
- next.sibling = null;
1524
-
1525
- // Restore the context.
1526
- // TODO: We can probably just avoid popping it instead and only
1527
- // setting it the first time we go from not suspended to suspended.
1528
- let suspenseContext = suspenseStackCursor.current;
1529
- if (didSuspendAlready) {
1530
- suspenseContext = setShallowSuspenseListContext(
1531
- suspenseContext,
1532
- ForceSuspenseFallback,
1533
- );
1534
- } else {
1535
- suspenseContext = setDefaultShallowSuspenseListContext(
1536
- suspenseContext,
1537
- );
1538
- }
1539
- pushSuspenseListContext(workInProgress, suspenseContext);
1540
- // Do a pass over the next row.
1541
- // Don't bubble properties in this case.
1542
- return next;
1543
- }
1544
- bubbleProperties(workInProgress);
1545
- return null;
1546
- }
1547
- case ScopeComponent: {
1548
- if (enableScopeAPI) {
1549
- if (current === null) {
1550
- const scopeInstance: ReactScopeInstance = createScopeInstance();
1551
- workInProgress.stateNode = scopeInstance;
1552
- prepareScopeUpdate(scopeInstance, workInProgress);
1553
- if (workInProgress.ref !== null) {
1554
- markRef(workInProgress);
1555
- markUpdate(workInProgress);
1556
- }
1557
- } else {
1558
- if (workInProgress.ref !== null) {
1559
- markUpdate(workInProgress);
1560
- }
1561
- if (current.ref !== workInProgress.ref) {
1562
- markRef(workInProgress);
1563
- }
1564
- }
1565
- bubbleProperties(workInProgress);
1566
- return null;
1567
- }
1568
- break;
1569
- }
1570
- case OffscreenComponent:
1571
- case LegacyHiddenComponent: {
1572
- popSuspenseHandler(workInProgress);
1573
- popHiddenContext(workInProgress);
1574
- const nextState: OffscreenState | null = workInProgress.memoizedState;
1575
- const nextIsHidden = nextState !== null;
1576
-
1577
- // Schedule a Visibility effect if the visibility has changed
1578
- if (enableLegacyHidden && workInProgress.tag === LegacyHiddenComponent) {
1579
- // LegacyHidden doesn't do any hiding — it only pre-renders.
1580
- } else {
1581
- if (current !== null) {
1582
- const prevState: OffscreenState | null = current.memoizedState;
1583
- const prevIsHidden = prevState !== null;
1584
- if (prevIsHidden !== nextIsHidden) {
1585
- workInProgress.flags |= Visibility;
1586
- }
1587
- } else {
1588
- // On initial mount, we only need a Visibility effect if the tree
1589
- // is hidden.
1590
- if (nextIsHidden) {
1591
- workInProgress.flags |= Visibility;
1592
- }
1593
- }
1594
- }
1595
-
1596
- if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) {
1597
- bubbleProperties(workInProgress);
1598
- } else {
1599
- // Don't bubble properties for hidden children unless we're rendering
1600
- // at offscreen priority.
1601
- if (
1602
- includesSomeLane(renderLanes, (OffscreenLane: Lane)) &&
1603
- // Also don't bubble if the tree suspended
1604
- (workInProgress.flags & DidCapture) === NoLanes
1605
- ) {
1606
- bubbleProperties(workInProgress);
1607
- // Check if there was an insertion or update in the hidden subtree.
1608
- // If so, we need to hide those nodes in the commit phase, so
1609
- // schedule a visibility effect.
1610
- if (
1611
- (!enableLegacyHidden ||
1612
- workInProgress.tag !== LegacyHiddenComponent) &&
1613
- workInProgress.subtreeFlags & (Placement | Update)
1614
- ) {
1615
- workInProgress.flags |= Visibility;
1616
- }
1617
- }
1618
- }
1619
-
1620
- if (workInProgress.updateQueue !== null) {
1621
- // Schedule an effect to attach Suspense retry listeners
1622
- // TODO: Move to passive phase
1623
- workInProgress.flags |= Update;
1624
- }
1625
-
1626
- if (enableCache) {
1627
- let previousCache: Cache | null = null;
1628
- if (
1629
- current !== null &&
1630
- current.memoizedState !== null &&
1631
- current.memoizedState.cachePool !== null
1632
- ) {
1633
- previousCache = current.memoizedState.cachePool.pool;
1634
- }
1635
- let cache: Cache | null = null;
1636
- if (
1637
- workInProgress.memoizedState !== null &&
1638
- workInProgress.memoizedState.cachePool !== null
1639
- ) {
1640
- cache = workInProgress.memoizedState.cachePool.pool;
1641
- }
1642
- if (cache !== previousCache) {
1643
- // Run passive effects to retain/release the cache.
1644
- workInProgress.flags |= Passive;
1645
- }
1646
- }
1647
-
1648
- popTransition(workInProgress, current);
1649
-
1650
- return null;
1651
- }
1652
- case CacheComponent: {
1653
- if (enableCache) {
1654
- let previousCache: Cache | null = null;
1655
- if (current !== null) {
1656
- previousCache = current.memoizedState.cache;
1657
- }
1658
- const cache: Cache = workInProgress.memoizedState.cache;
1659
- if (cache !== previousCache) {
1660
- // Run passive effects to retain/release the cache.
1661
- workInProgress.flags |= Passive;
1662
- }
1663
- popCacheProvider(workInProgress, cache);
1664
- bubbleProperties(workInProgress);
1665
- }
1666
- return null;
1667
- }
1668
- case TracingMarkerComponent: {
1669
- if (enableTransitionTracing) {
1670
- const instance: TracingMarkerInstance | null = workInProgress.stateNode;
1671
- if (instance !== null) {
1672
- popMarkerInstance(workInProgress);
1673
- }
1674
- bubbleProperties(workInProgress);
1675
- }
1676
- return null;
1677
- }
1678
- }
1679
-
1680
- throw new Error(
1681
- `Unknown unit of work tag (${workInProgress.tag}). This error is likely caused by a bug in ` +
1682
- 'React. Please file an issue.',
1683
- );
1684
-}
1685
-
1686
-export {completeWork};
packages/react-reconciler/src/ReactFiberConcurrentUpdates.new.js
deleted
-288
@@ -1,288 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
11
-import type {
12
- UpdateQueue as HookQueue,
13
- Update as HookUpdate,
14
-} from './ReactFiberHooks.new';
15
-import type {
16
- SharedQueue as ClassQueue,
17
- Update as ClassUpdate,
18
-} from './ReactFiberClassUpdateQueue.new';
19
-import type {Lane, Lanes} from './ReactFiberLane.new';
20
-import type {OffscreenInstance} from './ReactFiberOffscreenComponent';
21
-
22
-import {
23
- warnAboutUpdateOnNotYetMountedFiberInDEV,
24
- throwIfInfiniteUpdateLoopDetected,
25
- getWorkInProgressRoot,
26
-} from './ReactFiberWorkLoop.new';
27
-import {
28
- NoLane,
29
- NoLanes,
30
- mergeLanes,
31
- markHiddenUpdate,
32
-} from './ReactFiberLane.new';
33
-import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
34
-import {HostRoot, OffscreenComponent} from './ReactWorkTags';
35
-import {OffscreenVisible} from './ReactFiberOffscreenComponent';
36
-
37
-export type ConcurrentUpdate = {
38
- next: ConcurrentUpdate,
39
- lane: Lane,
40
-};
41
-
42
-type ConcurrentQueue = {
43
- pending: ConcurrentUpdate | null,
44
-};
45
-
46
-// If a render is in progress, and we receive an update from a concurrent event,
47
-// we wait until the current render is over (either finished or interrupted)
48
-// before adding it to the fiber/hook queue. Push to this array so we can
49
-// access the queue, fiber, update, et al later.
50
-const concurrentQueues: Array<any> = [];
51
-let concurrentQueuesIndex = 0;
52
-
53
-let concurrentlyUpdatedLanes: Lanes = NoLanes;
54
-
55
-export function finishQueueingConcurrentUpdates(): void {
56
- const endIndex = concurrentQueuesIndex;
57
- concurrentQueuesIndex = 0;
58
-
59
- concurrentlyUpdatedLanes = NoLanes;
60
-
61
- let i = 0;
62
- while (i < endIndex) {
63
- const fiber: Fiber = concurrentQueues[i];
64
- concurrentQueues[i++] = null;
65
- const queue: ConcurrentQueue = concurrentQueues[i];
66
- concurrentQueues[i++] = null;
67
- const update: ConcurrentUpdate = concurrentQueues[i];
68
- concurrentQueues[i++] = null;
69
- const lane: Lane = concurrentQueues[i];
70
- concurrentQueues[i++] = null;
71
-
72
- if (queue !== null && update !== null) {
73
- const pending = queue.pending;
74
- if (pending === null) {
75
- // This is the first update. Create a circular list.
76
- update.next = update;
77
- } else {
78
- update.next = pending.next;
79
- pending.next = update;
80
- }
81
- queue.pending = update;
82
- }
83
-
84
- if (lane !== NoLane) {
85
- markUpdateLaneFromFiberToRoot(fiber, update, lane);
86
- }
87
- }
88
-}
89
-
90
-export function getConcurrentlyUpdatedLanes(): Lanes {
91
- return concurrentlyUpdatedLanes;
92
-}
93
-
94
-function enqueueUpdate(
95
- fiber: Fiber,
96
- queue: ConcurrentQueue | null,
97
- update: ConcurrentUpdate | null,
98
- lane: Lane,
99
-) {
100
- // Don't update the `childLanes` on the return path yet. If we already in
101
- // the middle of rendering, wait until after it has completed.
102
- concurrentQueues[concurrentQueuesIndex++] = fiber;
103
- concurrentQueues[concurrentQueuesIndex++] = queue;
104
- concurrentQueues[concurrentQueuesIndex++] = update;
105
- concurrentQueues[concurrentQueuesIndex++] = lane;
106
-
107
- concurrentlyUpdatedLanes = mergeLanes(concurrentlyUpdatedLanes, lane);
108
-
109
- // The fiber's `lane` field is used in some places to check if any work is
110
- // scheduled, to perform an eager bailout, so we need to update it immediately.
111
- // TODO: We should probably move this to the "shared" queue instead.
112
- fiber.lanes = mergeLanes(fiber.lanes, lane);
113
- const alternate = fiber.alternate;
114
- if (alternate !== null) {
115
- alternate.lanes = mergeLanes(alternate.lanes, lane);
116
- }
117
-}
118
-
119
-export function enqueueConcurrentHookUpdate<S, A>(
120
- fiber: Fiber,
121
- queue: HookQueue<S, A>,
122
- update: HookUpdate<S, A>,
123
- lane: Lane,
124
-): FiberRoot | null {
125
- const concurrentQueue: ConcurrentQueue = (queue: any);
126
- const concurrentUpdate: ConcurrentUpdate = (update: any);
127
- enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane);
128
- return getRootForUpdatedFiber(fiber);
129
-}
130
-
131
-export function enqueueConcurrentHookUpdateAndEagerlyBailout<S, A>(
132
- fiber: Fiber,
133
- queue: HookQueue<S, A>,
134
- update: HookUpdate<S, A>,
135
-): void {
136
- // This function is used to queue an update that doesn't need a rerender. The
137
- // only reason we queue it is in case there's a subsequent higher priority
138
- // update that causes it to be rebased.
139
- const lane = NoLane;
140
- const concurrentQueue: ConcurrentQueue = (queue: any);
141
- const concurrentUpdate: ConcurrentUpdate = (update: any);
142
- enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane);
143
-
144
- // Usually we can rely on the upcoming render phase to process the concurrent
145
- // queue. However, since this is a bail out, we're not scheduling any work
146
- // here. So the update we just queued will leak until something else happens
147
- // to schedule work (if ever).
148
- //
149
- // Check if we're currently in the middle of rendering a tree, and if not,
150
- // process the queue immediately to prevent a leak.
151
- const isConcurrentlyRendering = getWorkInProgressRoot() !== null;
152
- if (!isConcurrentlyRendering) {
153
- finishQueueingConcurrentUpdates();
154
- }
155
-}
156
-
157
-export function enqueueConcurrentClassUpdate<State>(
158
- fiber: Fiber,
159
- queue: ClassQueue<State>,
160
- update: ClassUpdate<State>,
161
- lane: Lane,
162
-): FiberRoot | null {
163
- const concurrentQueue: ConcurrentQueue = (queue: any);
164
- const concurrentUpdate: ConcurrentUpdate = (update: any);
165
- enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane);
166
- return getRootForUpdatedFiber(fiber);
167
-}
168
-
169
-export function enqueueConcurrentRenderForLane(
170
- fiber: Fiber,
171
- lane: Lane,
172
-): FiberRoot | null {
173
- enqueueUpdate(fiber, null, null, lane);
174
- return getRootForUpdatedFiber(fiber);
175
-}
176
-
177
-// Calling this function outside this module should only be done for backwards
178
-// compatibility and should always be accompanied by a warning.
179
-export function unsafe_markUpdateLaneFromFiberToRoot(
180
- sourceFiber: Fiber,
181
- lane: Lane,
182
-): FiberRoot | null {
183
- // NOTE: For Hyrum's Law reasons, if an infinite update loop is detected, it
184
- // should throw before `markUpdateLaneFromFiberToRoot` is called. But this is
185
- // undefined behavior and we can change it if we need to; it just so happens
186
- // that, at the time of this writing, there's an internal product test that
187
- // happens to rely on this.
188
- const root = getRootForUpdatedFiber(sourceFiber);
189
- markUpdateLaneFromFiberToRoot(sourceFiber, null, lane);
190
- return root;
191
-}
192
-
193
-function markUpdateLaneFromFiberToRoot(
194
- sourceFiber: Fiber,
195
- update: ConcurrentUpdate | null,
196
- lane: Lane,
197
-): void {
198
- // Update the source fiber's lanes
199
- sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
200
- let alternate = sourceFiber.alternate;
201
- if (alternate !== null) {
202
- alternate.lanes = mergeLanes(alternate.lanes, lane);
203
- }
204
- // Walk the parent path to the root and update the child lanes.
205
- let isHidden = false;
206
- let parent = sourceFiber.return;
207
- let node = sourceFiber;
208
- while (parent !== null) {
209
- parent.childLanes = mergeLanes(parent.childLanes, lane);
210
- alternate = parent.alternate;
211
- if (alternate !== null) {
212
- alternate.childLanes = mergeLanes(alternate.childLanes, lane);
213
- }
214
-
215
- if (parent.tag === OffscreenComponent) {
216
- // Check if this offscreen boundary is currently hidden.
217
- //
218
- // The instance may be null if the Offscreen parent was unmounted. Usually
219
- // the parent wouldn't be reachable in that case because we disconnect
220
- // fibers from the tree when they are deleted. However, there's a weird
221
- // edge case where setState is called on a fiber that was interrupted
222
- // before it ever mounted. Because it never mounts, it also never gets
223
- // deleted. Because it never gets deleted, its return pointer never gets
224
- // disconnected. Which means it may be attached to a deleted Offscreen
225
- // parent node. (This discovery suggests it may be better for memory usage
226
- // if we don't attach the `return` pointer until the commit phase, though
227
- // in order to do that we'd need some other way to track the return
228
- // pointer during the initial render, like on the stack.)
229
- //
230
- // This case is always accompanied by a warning, but we still need to
231
- // account for it. (There may be other cases that we haven't discovered,
232
- // too.)
233
- const offscreenInstance: OffscreenInstance | null = parent.stateNode;
234
- if (
235
- offscreenInstance !== null &&
236
- !(offscreenInstance._visibility & OffscreenVisible)
237
- ) {
238
- isHidden = true;
239
- }
240
- }
241
-
242
- node = parent;
243
- parent = parent.return;
244
- }
245
-
246
- if (isHidden && update !== null && node.tag === HostRoot) {
247
- const root: FiberRoot = node.stateNode;
248
- markHiddenUpdate(root, update, lane);
249
- }
250
-}
251
-
252
-function getRootForUpdatedFiber(sourceFiber: Fiber): FiberRoot | null {
253
- // TODO: We will detect and infinite update loop and throw even if this fiber
254
- // has already unmounted. This isn't really necessary but it happens to be the
255
- // current behavior we've used for several release cycles. Consider not
256
- // performing this check if the updated fiber already unmounted, since it's
257
- // not possible for that to cause an infinite update loop.
258
- throwIfInfiniteUpdateLoopDetected();
259
-
260
- // When a setState happens, we must ensure the root is scheduled. Because
261
- // update queues do not have a backpointer to the root, the only way to do
262
- // this currently is to walk up the return path. This used to not be a big
263
- // deal because we would have to walk up the return path to set
264
- // the `childLanes`, anyway, but now those two traversals happen at
265
- // different times.
266
- // TODO: Consider adding a `root` backpointer on the update queue.
267
- detectUpdateOnUnmountedFiber(sourceFiber, sourceFiber);
268
- let node = sourceFiber;
269
- let parent = node.return;
270
- while (parent !== null) {
271
- detectUpdateOnUnmountedFiber(sourceFiber, node);
272
- node = parent;
273
- parent = node.return;
274
- }
275
- return node.tag === HostRoot ? (node.stateNode: FiberRoot) : null;
276
-}
277
-
278
-function detectUpdateOnUnmountedFiber(sourceFiber: Fiber, parent: Fiber) {
279
- if (__DEV__) {
280
- const alternate = parent.alternate;
281
- if (
282
- alternate === null &&
283
- (parent.flags & (Placement | Hydrating)) !== NoFlags
284
- ) {
285
- warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
286
- }
287
- }
288
-}
packages/react-reconciler/src/ReactFiberContext.new.js
deleted
-343
@@ -1,343 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-import type {StackCursor} from './ReactFiberStack.new';
12
-
13
-import {isFiberMounted} from './ReactFiberTreeReflection';
14
-import {disableLegacyContext} from 'shared/ReactFeatureFlags';
15
-import {ClassComponent, HostRoot} from './ReactWorkTags';
16
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
17
-import checkPropTypes from 'shared/checkPropTypes';
18
-
19
-import {createCursor, push, pop} from './ReactFiberStack.new';
20
-
21
-let warnedAboutMissingGetChildContext;
22
-
23
-if (__DEV__) {
24
- warnedAboutMissingGetChildContext = {};
25
-}
26
-
27
-// $FlowFixMe[incompatible-exact]
28
-export const emptyContextObject: {} = {};
29
-if (__DEV__) {
30
- Object.freeze(emptyContextObject);
31
-}
32
-
33
-// A cursor to the current merged context object on the stack.
34
-const contextStackCursor: StackCursor<Object> = createCursor(
35
- emptyContextObject,
36
-);
37
-// A cursor to a boolean indicating whether the context has changed.
38
-const didPerformWorkStackCursor: StackCursor<boolean> = createCursor(false);
39
-// Keep track of the previous context object that was on the stack.
40
-// We use this to get access to the parent context after we have already
41
-// pushed the next context provider, and now need to merge their contexts.
42
-let previousContext: Object = emptyContextObject;
43
-
44
-function getUnmaskedContext(
45
- workInProgress: Fiber,
46
- Component: Function,
47
- didPushOwnContextIfProvider: boolean,
48
-): Object {
49
- if (disableLegacyContext) {
50
- return emptyContextObject;
51
- } else {
52
- if (didPushOwnContextIfProvider && isContextProvider(Component)) {
53
- // If the fiber is a context provider itself, when we read its context
54
- // we may have already pushed its own child context on the stack. A context
55
- // provider should not "see" its own child context. Therefore we read the
56
- // previous (parent) context instead for a context provider.
57
- return previousContext;
58
- }
59
- return contextStackCursor.current;
60
- }
61
-}
62
-
63
-function cacheContext(
64
- workInProgress: Fiber,
65
- unmaskedContext: Object,
66
- maskedContext: Object,
67
-): void {
68
- if (disableLegacyContext) {
69
- return;
70
- } else {
71
- const instance = workInProgress.stateNode;
72
- instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
73
- instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
74
- }
75
-}
76
-
77
-function getMaskedContext(
78
- workInProgress: Fiber,
79
- unmaskedContext: Object,
80
-): Object {
81
- if (disableLegacyContext) {
82
- return emptyContextObject;
83
- } else {
84
- const type = workInProgress.type;
85
- const contextTypes = type.contextTypes;
86
- if (!contextTypes) {
87
- return emptyContextObject;
88
- }
89
-
90
- // Avoid recreating masked context unless unmasked context has changed.
91
- // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
92
- // This may trigger infinite loops if componentWillReceiveProps calls setState.
93
- const instance = workInProgress.stateNode;
94
- if (
95
- instance &&
96
- instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext
97
- ) {
98
- return instance.__reactInternalMemoizedMaskedChildContext;
99
- }
100
-
101
- const context = {};
102
- for (const key in contextTypes) {
103
- context[key] = unmaskedContext[key];
104
- }
105
-
106
- if (__DEV__) {
107
- const name = getComponentNameFromFiber(workInProgress) || 'Unknown';
108
- checkPropTypes(contextTypes, context, 'context', name);
109
- }
110
-
111
- // Cache unmasked context so we can avoid recreating masked context unless necessary.
112
- // Context is created before the class component is instantiated so check for instance.
113
- if (instance) {
114
- cacheContext(workInProgress, unmaskedContext, context);
115
- }
116
-
117
- return context;
118
- }
119
-}
120
-
121
-function hasContextChanged(): boolean {
122
- if (disableLegacyContext) {
123
- return false;
124
- } else {
125
- return didPerformWorkStackCursor.current;
126
- }
127
-}
128
-
129
-function isContextProvider(type: Function): boolean {
130
- if (disableLegacyContext) {
131
- return false;
132
- } else {
133
- const childContextTypes = type.childContextTypes;
134
- return childContextTypes !== null && childContextTypes !== undefined;
135
- }
136
-}
137
-
138
-function popContext(fiber: Fiber): void {
139
- if (disableLegacyContext) {
140
- return;
141
- } else {
142
- pop(didPerformWorkStackCursor, fiber);
143
- pop(contextStackCursor, fiber);
144
- }
145
-}
146
-
147
-function popTopLevelContextObject(fiber: Fiber): void {
148
- if (disableLegacyContext) {
149
- return;
150
- } else {
151
- pop(didPerformWorkStackCursor, fiber);
152
- pop(contextStackCursor, fiber);
153
- }
154
-}
155
-
156
-function pushTopLevelContextObject(
157
- fiber: Fiber,
158
- context: Object,
159
- didChange: boolean,
160
-): void {
161
- if (disableLegacyContext) {
162
- return;
163
- } else {
164
- if (contextStackCursor.current !== emptyContextObject) {
165
- throw new Error(
166
- 'Unexpected context found on stack. ' +
167
- 'This error is likely caused by a bug in React. Please file an issue.',
168
- );
169
- }
170
-
171
- push(contextStackCursor, context, fiber);
172
- push(didPerformWorkStackCursor, didChange, fiber);
173
- }
174
-}
175
-
176
-function processChildContext(
177
- fiber: Fiber,
178
- type: any,
179
- parentContext: Object,
180
-): Object {
181
- if (disableLegacyContext) {
182
- return parentContext;
183
- } else {
184
- const instance = fiber.stateNode;
185
- const childContextTypes = type.childContextTypes;
186
-
187
- // TODO (bvaughn) Replace this behavior with an invariant() in the future.
188
- // It has only been added in Fiber to match the (unintentional) behavior in Stack.
189
- if (typeof instance.getChildContext !== 'function') {
190
- if (__DEV__) {
191
- const componentName = getComponentNameFromFiber(fiber) || 'Unknown';
192
-
193
- if (!warnedAboutMissingGetChildContext[componentName]) {
194
- warnedAboutMissingGetChildContext[componentName] = true;
195
- console.error(
196
- '%s.childContextTypes is specified but there is no getChildContext() method ' +
197
- 'on the instance. You can either define getChildContext() on %s or remove ' +
198
- 'childContextTypes from it.',
199
- componentName,
200
- componentName,
201
- );
202
- }
203
- }
204
- return parentContext;
205
- }
206
-
207
- const childContext = instance.getChildContext();
208
- for (const contextKey in childContext) {
209
- if (!(contextKey in childContextTypes)) {
210
- throw new Error(
211
- `${getComponentNameFromFiber(fiber) ||
212
- 'Unknown'}.getChildContext(): key "${contextKey}" is not defined in childContextTypes.`,
213
- );
214
- }
215
- }
216
- if (__DEV__) {
217
- const name = getComponentNameFromFiber(fiber) || 'Unknown';
218
- checkPropTypes(childContextTypes, childContext, 'child context', name);
219
- }
220
-
221
- return {...parentContext, ...childContext};
222
- }
223
-}
224
-
225
-function pushContextProvider(workInProgress: Fiber): boolean {
226
- if (disableLegacyContext) {
227
- return false;
228
- } else {
229
- const instance = workInProgress.stateNode;
230
- // We push the context as early as possible to ensure stack integrity.
231
- // If the instance does not exist yet, we will push null at first,
232
- // and replace it on the stack later when invalidating the context.
233
- const memoizedMergedChildContext =
234
- (instance && instance.__reactInternalMemoizedMergedChildContext) ||
235
- emptyContextObject;
236
-
237
- // Remember the parent context so we can merge with it later.
238
- // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
239
- previousContext = contextStackCursor.current;
240
- push(contextStackCursor, memoizedMergedChildContext, workInProgress);
241
- push(
242
- didPerformWorkStackCursor,
243
- didPerformWorkStackCursor.current,
244
- workInProgress,
245
- );
246
-
247
- return true;
248
- }
249
-}
250
-
251
-function invalidateContextProvider(
252
- workInProgress: Fiber,
253
- type: any,
254
- didChange: boolean,
255
-): void {
256
- if (disableLegacyContext) {
257
- return;
258
- } else {
259
- const instance = workInProgress.stateNode;
260
-
261
- if (!instance) {
262
- throw new Error(
263
- 'Expected to have an instance by this point. ' +
264
- 'This error is likely caused by a bug in React. Please file an issue.',
265
- );
266
- }
267
-
268
- if (didChange) {
269
- // Merge parent and own context.
270
- // Skip this if we're not updating due to sCU.
271
- // This avoids unnecessarily recomputing memoized values.
272
- const mergedContext = processChildContext(
273
- workInProgress,
274
- type,
275
- previousContext,
276
- );
277
- instance.__reactInternalMemoizedMergedChildContext = mergedContext;
278
-
279
- // Replace the old (or empty) context with the new one.
280
- // It is important to unwind the context in the reverse order.
281
- pop(didPerformWorkStackCursor, workInProgress);
282
- pop(contextStackCursor, workInProgress);
283
- // Now push the new context and mark that it has changed.
284
- push(contextStackCursor, mergedContext, workInProgress);
285
- push(didPerformWorkStackCursor, didChange, workInProgress);
286
- } else {
287
- pop(didPerformWorkStackCursor, workInProgress);
288
- push(didPerformWorkStackCursor, didChange, workInProgress);
289
- }
290
- }
291
-}
292
-
293
-function findCurrentUnmaskedContext(fiber: Fiber): Object {
294
- if (disableLegacyContext) {
295
- return emptyContextObject;
296
- } else {
297
- // Currently this is only used with renderSubtreeIntoContainer; not sure if it
298
- // makes sense elsewhere
299
- if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) {
300
- throw new Error(
301
- 'Expected subtree parent to be a mounted class component. ' +
302
- 'This error is likely caused by a bug in React. Please file an issue.',
303
- );
304
- }
305
-
306
- let node: Fiber = fiber;
307
- do {
308
- switch (node.tag) {
309
- case HostRoot:
310
- return node.stateNode.context;
311
- case ClassComponent: {
312
- const Component = node.type;
313
- if (isContextProvider(Component)) {
314
- return node.stateNode.__reactInternalMemoizedMergedChildContext;
315
- }
316
- break;
317
- }
318
- }
319
- // $FlowFixMe[incompatible-type] we bail out when we get a null
320
- node = node.return;
321
- } while (node !== null);
322
-
323
- throw new Error(
324
- 'Found unexpected detached subtree parent. ' +
325
- 'This error is likely caused by a bug in React. Please file an issue.',
326
- );
327
- }
328
-}
329
-
330
-export {
331
- getUnmaskedContext,
332
- cacheContext,
333
- getMaskedContext,
334
- hasContextChanged,
335
- popContext,
336
- popTopLevelContextObject,
337
- pushTopLevelContextObject,
338
- processChildContext,
339
- isContextProvider,
340
- pushContextProvider,
341
- invalidateContextProvider,
342
- findCurrentUnmaskedContext,
343
-};
packages/react-reconciler/src/ReactFiberDevToolsHook.new.js
deleted
-540
@@ -1,540 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Lane, Lanes} from './ReactFiberLane.new';
11
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
12
-import type {ReactNodeList, Wakeable} from 'shared/ReactTypes';
13
-import type {EventPriority} from './ReactEventPriorities.new';
14
-// import type {DevToolsProfilingHooks} from 'react-devtools-shared/src/backend/types';
15
-// TODO: This import doesn't work because the DevTools depend on the DOM version of React
16
-// and to properly type check against DOM React we can't also type check again non-DOM
17
-// React which this hook might be in.
18
-type DevToolsProfilingHooks = any;
19
-
20
-import {
21
- getLabelForLane,
22
- TotalLanes,
23
-} from 'react-reconciler/src/ReactFiberLane.new';
24
-import {DidCapture} from './ReactFiberFlags';
25
-import {
26
- consoleManagedByDevToolsDuringStrictMode,
27
- enableProfilerTimer,
28
- enableSchedulingProfiler,
29
-} from 'shared/ReactFeatureFlags';
30
-import {
31
- DiscreteEventPriority,
32
- ContinuousEventPriority,
33
- DefaultEventPriority,
34
- IdleEventPriority,
35
-} from './ReactEventPriorities.new';
36
-import {
37
- ImmediatePriority as ImmediateSchedulerPriority,
38
- UserBlockingPriority as UserBlockingSchedulerPriority,
39
- NormalPriority as NormalSchedulerPriority,
40
- IdlePriority as IdleSchedulerPriority,
41
- unstable_yieldValue,
42
- unstable_setDisableYieldValue,
43
-} from './Scheduler';
44
-import {setSuppressWarning} from 'shared/consoleWithStackDev';
45
-import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev';
46
-
47
-declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void;
48
-
49
-let rendererID = null;
50
-let injectedHook = null;
51
-let injectedProfilingHooks: DevToolsProfilingHooks | null = null;
52
-let hasLoggedError = false;
53
-
54
-export const isDevToolsPresent =
55
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
56
-
57
-export function injectInternals(internals: Object): boolean {
58
- if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
59
- // No DevTools
60
- return false;
61
- }
62
- const hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
63
- if (hook.isDisabled) {
64
- // This isn't a real property on the hook, but it can be set to opt out
65
- // of DevTools integration and associated warnings and logs.
66
- // https://github.com/facebook/react/issues/3877
67
- return true;
68
- }
69
- if (!hook.supportsFiber) {
70
- if (__DEV__) {
71
- console.error(
72
- 'The installed version of React DevTools is too old and will not work ' +
73
- 'with the current version of React. Please update React DevTools. ' +
74
- 'https://reactjs.org/link/react-devtools',
75
- );
76
- }
77
- // DevTools exists, even though it doesn't support Fiber.
78
- return true;
79
- }
80
- try {
81
- if (enableSchedulingProfiler) {
82
- // Conditionally inject these hooks only if Timeline profiler is supported by this build.
83
- // This gives DevTools a way to feature detect that isn't tied to version number
84
- // (since profiling and timeline are controlled by different feature flags).
85
- internals = {
86
- ...internals,
87
- getLaneLabelMap,
88
- injectProfilingHooks,
89
- };
90
- }
91
-
92
- rendererID = hook.inject(internals);
93
-
94
- // We have successfully injected, so now it is safe to set up hooks.
95
- injectedHook = hook;
96
- } catch (err) {
97
- // Catch all errors because it is unsafe to throw during initialization.
98
- if (__DEV__) {
99
- console.error('React instrumentation encountered an error: %s.', err);
100
- }
101
- }
102
- if (hook.checkDCE) {
103
- // This is the real DevTools.
104
- return true;
105
- } else {
106
- // This is likely a hook installed by Fast Refresh runtime.
107
- return false;
108
- }
109
-}
110
-
111
-export function onScheduleRoot(root: FiberRoot, children: ReactNodeList) {
112
- if (__DEV__) {
113
- if (
114
- injectedHook &&
115
- typeof injectedHook.onScheduleFiberRoot === 'function'
116
- ) {
117
- try {
118
- injectedHook.onScheduleFiberRoot(rendererID, root, children);
119
- } catch (err) {
120
- if (__DEV__ && !hasLoggedError) {
121
- hasLoggedError = true;
122
- console.error('React instrumentation encountered an error: %s', err);
123
- }
124
- }
125
- }
126
- }
127
-}
128
-
129
-export function onCommitRoot(root: FiberRoot, eventPriority: EventPriority) {
130
- if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') {
131
- try {
132
- const didError = (root.current.flags & DidCapture) === DidCapture;
133
- if (enableProfilerTimer) {
134
- let schedulerPriority;
135
- switch (eventPriority) {
136
- case DiscreteEventPriority:
137
- schedulerPriority = ImmediateSchedulerPriority;
138
- break;
139
- case ContinuousEventPriority:
140
- schedulerPriority = UserBlockingSchedulerPriority;
141
- break;
142
- case DefaultEventPriority:
143
- schedulerPriority = NormalSchedulerPriority;
144
- break;
145
- case IdleEventPriority:
146
- schedulerPriority = IdleSchedulerPriority;
147
- break;
148
- default:
149
- schedulerPriority = NormalSchedulerPriority;
150
- break;
151
- }
152
- injectedHook.onCommitFiberRoot(
153
- rendererID,
154
- root,
155
- schedulerPriority,
156
- didError,
157
- );
158
- } else {
159
- injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError);
160
- }
161
- } catch (err) {
162
- if (__DEV__) {
163
- if (!hasLoggedError) {
164
- hasLoggedError = true;
165
- console.error('React instrumentation encountered an error: %s', err);
166
- }
167
- }
168
- }
169
- }
170
-}
171
-
172
-export function onPostCommitRoot(root: FiberRoot) {
173
- if (
174
- injectedHook &&
175
- typeof injectedHook.onPostCommitFiberRoot === 'function'
176
- ) {
177
- try {
178
- injectedHook.onPostCommitFiberRoot(rendererID, root);
179
- } catch (err) {
180
- if (__DEV__) {
181
- if (!hasLoggedError) {
182
- hasLoggedError = true;
183
- console.error('React instrumentation encountered an error: %s', err);
184
- }
185
- }
186
- }
187
- }
188
-}
189
-
190
-export function onCommitUnmount(fiber: Fiber) {
191
- if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
192
- try {
193
- injectedHook.onCommitFiberUnmount(rendererID, fiber);
194
- } catch (err) {
195
- if (__DEV__) {
196
- if (!hasLoggedError) {
197
- hasLoggedError = true;
198
- console.error('React instrumentation encountered an error: %s', err);
199
- }
200
- }
201
- }
202
- }
203
-}
204
-
205
-export function setIsStrictModeForDevtools(newIsStrictMode: boolean) {
206
- if (consoleManagedByDevToolsDuringStrictMode) {
207
- if (typeof unstable_yieldValue === 'function') {
208
- // We're in a test because Scheduler.unstable_yieldValue only exists
209
- // in SchedulerMock. To reduce the noise in strict mode tests,
210
- // suppress warnings and disable scheduler yielding during the double render
211
- unstable_setDisableYieldValue(newIsStrictMode);
212
- setSuppressWarning(newIsStrictMode);
213
- }
214
-
215
- if (injectedHook && typeof injectedHook.setStrictMode === 'function') {
216
- try {
217
- injectedHook.setStrictMode(rendererID, newIsStrictMode);
218
- } catch (err) {
219
- if (__DEV__) {
220
- if (!hasLoggedError) {
221
- hasLoggedError = true;
222
- console.error(
223
- 'React instrumentation encountered an error: %s',
224
- err,
225
- );
226
- }
227
- }
228
- }
229
- }
230
- } else {
231
- if (newIsStrictMode) {
232
- disableLogs();
233
- } else {
234
- reenableLogs();
235
- }
236
- }
237
-}
238
-
239
-// Profiler API hooks
240
-
241
-function injectProfilingHooks(profilingHooks: DevToolsProfilingHooks): void {
242
- injectedProfilingHooks = profilingHooks;
243
-}
244
-
245
-function getLaneLabelMap(): Map<Lane, string> | null {
246
- if (enableSchedulingProfiler) {
247
- const map: Map<Lane, string> = new Map();
248
-
249
- let lane = 1;
250
- for (let index = 0; index < TotalLanes; index++) {
251
- const label = ((getLabelForLane(lane): any): string);
252
- map.set(lane, label);
253
- lane *= 2;
254
- }
255
-
256
- return map;
257
- } else {
258
- return null;
259
- }
260
-}
261
-
262
-export function markCommitStarted(lanes: Lanes): void {
263
- if (enableSchedulingProfiler) {
264
- if (
265
- injectedProfilingHooks !== null &&
266
- typeof injectedProfilingHooks.markCommitStarted === 'function'
267
- ) {
268
- injectedProfilingHooks.markCommitStarted(lanes);
269
- }
270
- }
271
-}
272
-
273
-export function markCommitStopped(): void {
274
- if (enableSchedulingProfiler) {
275
- if (
276
- injectedProfilingHooks !== null &&
277
- typeof injectedProfilingHooks.markCommitStopped === 'function'
278
- ) {
279
- injectedProfilingHooks.markCommitStopped();
280
- }
281
- }
282
-}
283
-
284
-export function markComponentRenderStarted(fiber: Fiber): void {
285
- if (enableSchedulingProfiler) {
286
- if (
287
- injectedProfilingHooks !== null &&
288
- typeof injectedProfilingHooks.markComponentRenderStarted === 'function'
289
- ) {
290
- injectedProfilingHooks.markComponentRenderStarted(fiber);
291
- }
292
- }
293
-}
294
-
295
-export function markComponentRenderStopped(): void {
296
- if (enableSchedulingProfiler) {
297
- if (
298
- injectedProfilingHooks !== null &&
299
- typeof injectedProfilingHooks.markComponentRenderStopped === 'function'
300
- ) {
301
- injectedProfilingHooks.markComponentRenderStopped();
302
- }
303
- }
304
-}
305
-
306
-export function markComponentPassiveEffectMountStarted(fiber: Fiber): void {
307
- if (enableSchedulingProfiler) {
308
- if (
309
- injectedProfilingHooks !== null &&
310
- typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted ===
311
- 'function'
312
- ) {
313
- injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);
314
- }
315
- }
316
-}
317
-
318
-export function markComponentPassiveEffectMountStopped(): void {
319
- if (enableSchedulingProfiler) {
320
- if (
321
- injectedProfilingHooks !== null &&
322
- typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped ===
323
- 'function'
324
- ) {
325
- injectedProfilingHooks.markComponentPassiveEffectMountStopped();
326
- }
327
- }
328
-}
329
-
330
-export function markComponentPassiveEffectUnmountStarted(fiber: Fiber): void {
331
- if (enableSchedulingProfiler) {
332
- if (
333
- injectedProfilingHooks !== null &&
334
- typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted ===
335
- 'function'
336
- ) {
337
- injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);
338
- }
339
- }
340
-}
341
-
342
-export function markComponentPassiveEffectUnmountStopped(): void {
343
- if (enableSchedulingProfiler) {
344
- if (
345
- injectedProfilingHooks !== null &&
346
- typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped ===
347
- 'function'
348
- ) {
349
- injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();
350
- }
351
- }
352
-}
353
-
354
-export function markComponentLayoutEffectMountStarted(fiber: Fiber): void {
355
- if (enableSchedulingProfiler) {
356
- if (
357
- injectedProfilingHooks !== null &&
358
- typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted ===
359
- 'function'
360
- ) {
361
- injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);
362
- }
363
- }
364
-}
365
-
366
-export function markComponentLayoutEffectMountStopped(): void {
367
- if (enableSchedulingProfiler) {
368
- if (
369
- injectedProfilingHooks !== null &&
370
- typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped ===
371
- 'function'
372
- ) {
373
- injectedProfilingHooks.markComponentLayoutEffectMountStopped();
374
- }
375
- }
376
-}
377
-
378
-export function markComponentLayoutEffectUnmountStarted(fiber: Fiber): void {
379
- if (enableSchedulingProfiler) {
380
- if (
381
- injectedProfilingHooks !== null &&
382
- typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted ===
383
- 'function'
384
- ) {
385
- injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);
386
- }
387
- }
388
-}
389
-
390
-export function markComponentLayoutEffectUnmountStopped(): void {
391
- if (enableSchedulingProfiler) {
392
- if (
393
- injectedProfilingHooks !== null &&
394
- typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped ===
395
- 'function'
396
- ) {
397
- injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();
398
- }
399
- }
400
-}
401
-
402
-export function markComponentErrored(
403
- fiber: Fiber,
404
- thrownValue: mixed,
405
- lanes: Lanes,
406
-): void {
407
- if (enableSchedulingProfiler) {
408
- if (
409
- injectedProfilingHooks !== null &&
410
- typeof injectedProfilingHooks.markComponentErrored === 'function'
411
- ) {
412
- injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes);
413
- }
414
- }
415
-}
416
-
417
-export function markComponentSuspended(
418
- fiber: Fiber,
419
- wakeable: Wakeable,
420
- lanes: Lanes,
421
-): void {
422
- if (enableSchedulingProfiler) {
423
- if (
424
- injectedProfilingHooks !== null &&
425
- typeof injectedProfilingHooks.markComponentSuspended === 'function'
426
- ) {
427
- injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes);
428
- }
429
- }
430
-}
431
-
432
-export function markLayoutEffectsStarted(lanes: Lanes): void {
433
- if (enableSchedulingProfiler) {
434
- if (
435
- injectedProfilingHooks !== null &&
436
- typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function'
437
- ) {
438
- injectedProfilingHooks.markLayoutEffectsStarted(lanes);
439
- }
440
- }
441
-}
442
-
443
-export function markLayoutEffectsStopped(): void {
444
- if (enableSchedulingProfiler) {
445
- if (
446
- injectedProfilingHooks !== null &&
447
- typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function'
448
- ) {
449
- injectedProfilingHooks.markLayoutEffectsStopped();
450
- }
451
- }
452
-}
453
-
454
-export function markPassiveEffectsStarted(lanes: Lanes): void {
455
- if (enableSchedulingProfiler) {
456
- if (
457
- injectedProfilingHooks !== null &&
458
- typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function'
459
- ) {
460
- injectedProfilingHooks.markPassiveEffectsStarted(lanes);
461
- }
462
- }
463
-}
464
-
465
-export function markPassiveEffectsStopped(): void {
466
- if (enableSchedulingProfiler) {
467
- if (
468
- injectedProfilingHooks !== null &&
469
- typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function'
470
- ) {
471
- injectedProfilingHooks.markPassiveEffectsStopped();
472
- }
473
- }
474
-}
475
-
476
-export function markRenderStarted(lanes: Lanes): void {
477
- if (enableSchedulingProfiler) {
478
- if (
479
- injectedProfilingHooks !== null &&
480
- typeof injectedProfilingHooks.markRenderStarted === 'function'
481
- ) {
482
- injectedProfilingHooks.markRenderStarted(lanes);
483
- }
484
- }
485
-}
486
-
487
-export function markRenderYielded(): void {
488
- if (enableSchedulingProfiler) {
489
- if (
490
- injectedProfilingHooks !== null &&
491
- typeof injectedProfilingHooks.markRenderYielded === 'function'
492
- ) {
493
- injectedProfilingHooks.markRenderYielded();
494
- }
495
- }
496
-}
497
-
498
-export function markRenderStopped(): void {
499
- if (enableSchedulingProfiler) {
500
- if (
501
- injectedProfilingHooks !== null &&
502
- typeof injectedProfilingHooks.markRenderStopped === 'function'
503
- ) {
504
- injectedProfilingHooks.markRenderStopped();
505
- }
506
- }
507
-}
508
-
509
-export function markRenderScheduled(lane: Lane): void {
510
- if (enableSchedulingProfiler) {
511
- if (
512
- injectedProfilingHooks !== null &&
513
- typeof injectedProfilingHooks.markRenderScheduled === 'function'
514
- ) {
515
- injectedProfilingHooks.markRenderScheduled(lane);
516
- }
517
- }
518
-}
519
-
520
-export function markForceUpdateScheduled(fiber: Fiber, lane: Lane): void {
521
- if (enableSchedulingProfiler) {
522
- if (
523
- injectedProfilingHooks !== null &&
524
- typeof injectedProfilingHooks.markForceUpdateScheduled === 'function'
525
- ) {
526
- injectedProfilingHooks.markForceUpdateScheduled(fiber, lane);
527
- }
528
- }
529
-}
530
-
531
-export function markStateUpdateScheduled(fiber: Fiber, lane: Lane): void {
532
- if (enableSchedulingProfiler) {
533
- if (
534
- injectedProfilingHooks !== null &&
535
- typeof injectedProfilingHooks.markStateUpdateScheduled === 'function'
536
- ) {
537
- injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
538
- }
539
- }
540
-}
packages/react-reconciler/src/ReactFiberHiddenContext.new.js
deleted
-71
@@ -1,71 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-import type {StackCursor} from './ReactFiberStack.new';
12
-import type {Lanes} from './ReactFiberLane.new';
13
-
14
-import {createCursor, push, pop} from './ReactFiberStack.new';
15
-
16
-import {getRenderLanes, setRenderLanes} from './ReactFiberWorkLoop.new';
17
-import {NoLanes, mergeLanes} from './ReactFiberLane.new';
18
-
19
-// TODO: Remove `renderLanes` context in favor of hidden context
20
-type HiddenContext = {
21
- // Represents the lanes that must be included when processing updates in
22
- // order to reveal the hidden content.
23
- // TODO: Remove `subtreeLanes` context from work loop in favor of this one.
24
- baseLanes: number,
25
- ...
26
-};
27
-
28
-// TODO: This isn't being used yet, but it's intended to replace the
29
-// InvisibleParentContext that is currently managed by SuspenseContext.
30
-export const currentTreeHiddenStackCursor: StackCursor<HiddenContext | null> = createCursor(
31
- null,
32
-);
33
-export const prevRenderLanesStackCursor: StackCursor<Lanes> = createCursor(
34
- NoLanes,
35
-);
36
-
37
-export function pushHiddenContext(fiber: Fiber, context: HiddenContext): void {
38
- const prevRenderLanes = getRenderLanes();
39
- push(prevRenderLanesStackCursor, prevRenderLanes, fiber);
40
- push(currentTreeHiddenStackCursor, context, fiber);
41
-
42
- // When rendering a subtree that's currently hidden, we must include all
43
- // lanes that would have rendered if the hidden subtree hadn't been deferred.
44
- // That is, in order to reveal content from hidden -> visible, we must commit
45
- // all the updates that we skipped when we originally hid the tree.
46
- setRenderLanes(mergeLanes(prevRenderLanes, context.baseLanes));
47
-}
48
-
49
-export function reuseHiddenContextOnStack(fiber: Fiber): void {
50
- // This subtree is not currently hidden, so we don't need to add any lanes
51
- // to the render lanes. But we still need to push something to avoid a
52
- // context mismatch. Reuse the existing context on the stack.
53
- push(prevRenderLanesStackCursor, getRenderLanes(), fiber);
54
- push(
55
- currentTreeHiddenStackCursor,
56
- currentTreeHiddenStackCursor.current,
57
- fiber,
58
- );
59
-}
60
-
61
-export function popHiddenContext(fiber: Fiber): void {
62
- // Restore the previous render lanes from the stack
63
- setRenderLanes(prevRenderLanesStackCursor.current);
64
-
65
- pop(currentTreeHiddenStackCursor, fiber);
66
- pop(prevRenderLanesStackCursor, fiber);
67
-}
68
-
69
-export function isCurrentTreeHidden(): boolean {
70
- return currentTreeHiddenStackCursor.current !== null;
71
-}
packages/react-reconciler/src/ReactFiberHooks.new.js
deleted
-4099
@@ -1,4099 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {
11
- MutableSource,
12
- MutableSourceGetSnapshotFn,
13
- MutableSourceSubscribeFn,
14
- ReactContext,
15
- StartTransitionOptions,
16
- Usable,
17
- Thenable,
18
-} from 'shared/ReactTypes';
19
-import type {
20
- Fiber,
21
- FiberRoot,
22
- Dispatcher,
23
- HookType,
24
- MemoCache,
25
-} from './ReactInternalTypes';
26
-import type {Lanes, Lane} from './ReactFiberLane.new';
27
-import type {HookFlags} from './ReactHookEffectTags';
28
-import type {Flags} from './ReactFiberFlags';
29
-
30
-import ReactSharedInternals from 'shared/ReactSharedInternals';
31
-import {
32
- enableDebugTracing,
33
- enableSchedulingProfiler,
34
- enableNewReconciler,
35
- enableCache,
36
- enableUseRefAccessWarning,
37
- enableLazyContextPropagation,
38
- enableUseMutableSource,
39
- enableTransitionTracing,
40
- enableUseHook,
41
- enableUseMemoCacheHook,
42
- enableUseEventHook,
43
- enableLegacyCache,
44
- debugRenderPhaseSideEffectsForStrictMode,
45
-} from 'shared/ReactFeatureFlags';
46
-import {
47
- REACT_CONTEXT_TYPE,
48
- REACT_SERVER_CONTEXT_TYPE,
49
- REACT_MEMO_CACHE_SENTINEL,
50
-} from 'shared/ReactSymbols';
51
-
52
-import {
53
- NoMode,
54
- ConcurrentMode,
55
- DebugTracingMode,
56
- StrictEffectsMode,
57
- StrictLegacyMode,
58
-} from './ReactTypeOfMode';
59
-import {
60
- NoLane,
61
- SyncLane,
62
- OffscreenLane,
63
- NoLanes,
64
- isSubsetOfLanes,
65
- includesBlockingLane,
66
- includesOnlyNonUrgentLanes,
67
- claimNextTransitionLane,
68
- mergeLanes,
69
- removeLanes,
70
- intersectLanes,
71
- isTransitionLane,
72
- markRootEntangled,
73
- markRootMutableRead,
74
- NoTimestamp,
75
-} from './ReactFiberLane.new';
76
-import {
77
- ContinuousEventPriority,
78
- getCurrentUpdatePriority,
79
- setCurrentUpdatePriority,
80
- higherEventPriority,
81
-} from './ReactEventPriorities.new';
82
-import {readContext, checkIfContextChanged} from './ReactFiberNewContext.new';
83
-import {HostRoot, CacheComponent} from './ReactWorkTags';
84
-import {
85
- LayoutStatic as LayoutStaticEffect,
86
- Passive as PassiveEffect,
87
- PassiveStatic as PassiveStaticEffect,
88
- StaticMask as StaticMaskEffect,
89
- Update as UpdateEffect,
90
- StoreConsistency,
91
- MountLayoutDev as MountLayoutDevEffect,
92
- MountPassiveDev as MountPassiveDevEffect,
93
-} from './ReactFiberFlags';
94
-import {
95
- HasEffect as HookHasEffect,
96
- Layout as HookLayout,
97
- Passive as HookPassive,
98
- Insertion as HookInsertion,
99
-} from './ReactHookEffectTags';
100
-import {
101
- getWorkInProgressRoot,
102
- getWorkInProgressRootRenderLanes,
103
- scheduleUpdateOnFiber,
104
- requestUpdateLane,
105
- requestEventTime,
106
- markSkippedUpdateLanes,
107
- isInvalidExecutionContextForEventFunction,
108
-} from './ReactFiberWorkLoop.new';
109
-
110
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
111
-import is from 'shared/objectIs';
112
-import isArray from 'shared/isArray';
113
-import {
114
- markWorkInProgressReceivedUpdate,
115
- checkIfWorkInProgressReceivedUpdate,
116
-} from './ReactFiberBeginWork.new';
117
-import {getIsHydrating} from './ReactFiberHydrationContext.new';
118
-import {
119
- getWorkInProgressVersion,
120
- markSourceAsDirty,
121
- setWorkInProgressVersion,
122
- warnAboutMultipleRenderersDEV,
123
-} from './ReactMutableSource.new';
124
-import {logStateUpdateScheduled} from './DebugTracing';
125
-import {
126
- markStateUpdateScheduled,
127
- setIsStrictModeForDevtools,
128
-} from './ReactFiberDevToolsHook.new';
129
-import {createCache} from './ReactFiberCacheComponent.new';
130
-import {
131
- createUpdate as createLegacyQueueUpdate,
132
- enqueueUpdate as enqueueLegacyQueueUpdate,
133
- entangleTransitions as entangleLegacyQueueTransitions,
134
-} from './ReactFiberClassUpdateQueue.new';
135
-import {
136
- enqueueConcurrentHookUpdate,
137
- enqueueConcurrentHookUpdateAndEagerlyBailout,
138
- enqueueConcurrentRenderForLane,
139
-} from './ReactFiberConcurrentUpdates.new';
140
-import {getTreeId} from './ReactFiberTreeContext.new';
141
-import {now} from './Scheduler';
142
-import {
143
- trackUsedThenable,
144
- checkIfUseWrappedInTryCatch,
145
- createThenableState,
146
-} from './ReactFiberThenable.new';
147
-import type {ThenableState} from './ReactFiberThenable.new';
148
-
149
-const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;
150
-
151
-export type Update<S, A> = {
152
- lane: Lane,
153
- action: A,
154
- hasEagerState: boolean,
155
- eagerState: S | null,
156
- next: Update<S, A>,
157
-};
158
-
159
-export type UpdateQueue<S, A> = {
160
- pending: Update<S, A> | null,
161
- lanes: Lanes,
162
- dispatch: (A => mixed) | null,
163
- lastRenderedReducer: ((S, A) => S) | null,
164
- lastRenderedState: S | null,
165
-};
166
-
167
-let didWarnAboutMismatchedHooksForComponent;
168
-let didWarnUncachedGetSnapshot;
169
-let didWarnAboutUseWrappedInTryCatch;
170
-if (__DEV__) {
171
- didWarnAboutMismatchedHooksForComponent = new Set();
172
- didWarnAboutUseWrappedInTryCatch = new Set();
173
-}
174
-
175
-export type Hook = {
176
- memoizedState: any,
177
- baseState: any,
178
- baseQueue: Update<any, any> | null,
179
- queue: any,
180
- next: Hook | null,
181
-};
182
-
183
-export type Effect = {
184
- tag: HookFlags,
185
- create: () => (() => void) | void,
186
- destroy: (() => void) | void,
187
- deps: Array<mixed> | void | null,
188
- next: Effect,
189
-};
190
-
191
-type StoreInstance<T> = {
192
- value: T,
193
- getSnapshot: () => T,
194
-};
195
-
196
-type StoreConsistencyCheck<T> = {
197
- value: T,
198
- getSnapshot: () => T,
199
-};
200
-
201
-type EventFunctionPayload<Args, Return, F: (...Array<Args>) => Return> = {
202
- ref: {
203
- eventFn: F,
204
- impl: F,
205
- },
206
- nextImpl: F,
207
-};
208
-
209
-export type FunctionComponentUpdateQueue = {
210
- lastEffect: Effect | null,
211
- events: Array<EventFunctionPayload<any, any, any>> | null,
212
- stores: Array<StoreConsistencyCheck<any>> | null,
213
- // NOTE: optional, only set when enableUseMemoCacheHook is enabled
214
- memoCache?: MemoCache | null,
215
-};
216
-
217
-type BasicStateAction<S> = (S => S) | S;
218
-
219
-type Dispatch<A> = A => void;
220
-
221
-// These are set right before calling the component.
222
-let renderLanes: Lanes = NoLanes;
223
-// The work-in-progress fiber. I've named it differently to distinguish it from
224
-// the work-in-progress hook.
225
-let currentlyRenderingFiber: Fiber = (null: any);
226
-
227
-// Hooks are stored as a linked list on the fiber's memoizedState field. The
228
-// current hook list is the list that belongs to the current fiber. The
229
-// work-in-progress hook list is a new list that will be added to the
230
-// work-in-progress fiber.
231
-let currentHook: Hook | null = null;
232
-let workInProgressHook: Hook | null = null;
233
-
234
-// Whether an update was scheduled at any point during the render phase. This
235
-// does not get reset if we do another render pass; only when we're completely
236
-// finished evaluating this component. This is an optimization so we know
237
-// whether we need to clear render phase updates after a throw.
238
-let didScheduleRenderPhaseUpdate: boolean = false;
239
-// Where an update was scheduled only during the current render pass. This
240
-// gets reset after each attempt.
241
-// TODO: Maybe there's some way to consolidate this with
242
-// `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.
243
-let didScheduleRenderPhaseUpdateDuringThisPass: boolean = false;
244
-let shouldDoubleInvokeUserFnsInHooksDEV: boolean = false;
245
-// Counts the number of useId hooks in this component.
246
-let localIdCounter: number = 0;
247
-// Counts number of `use`-d thenables
248
-let thenableIndexCounter: number = 0;
249
-let thenableState: ThenableState | null = null;
250
-
251
-// Used for ids that are generated completely client-side (i.e. not during
252
-// hydration). This counter is global, so client ids are not stable across
253
-// render attempts.
254
-let globalClientIdCounter: number = 0;
255
-
256
-const RE_RENDER_LIMIT = 25;
257
-
258
-// In DEV, this is the name of the currently executing primitive hook
259
-let currentHookNameInDev: ?HookType = null;
260
-
261
-// In DEV, this list ensures that hooks are called in the same order between renders.
262
-// The list stores the order of hooks used during the initial render (mount).
263
-// Subsequent renders (updates) reference this list.
264
-let hookTypesDev: Array<HookType> | null = null;
265
-let hookTypesUpdateIndexDev: number = -1;
266
-
267
-// In DEV, this tracks whether currently rendering component needs to ignore
268
-// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
269
-// When true, such Hooks will always be "remounted". Only used during hot reload.
270
-let ignorePreviousDependencies: boolean = false;
271
-
272
-function mountHookTypesDev() {
273
- if (__DEV__) {
274
- const hookName = ((currentHookNameInDev: any): HookType);
275
-
276
- if (hookTypesDev === null) {
277
- hookTypesDev = [hookName];
278
- } else {
279
- hookTypesDev.push(hookName);
280
- }
281
- }
282
-}
283
-
284
-function updateHookTypesDev() {
285
- if (__DEV__) {
286
- const hookName = ((currentHookNameInDev: any): HookType);
287
-
288
- if (hookTypesDev !== null) {
289
- hookTypesUpdateIndexDev++;
290
- if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
291
- warnOnHookMismatchInDev(hookName);
292
- }
293
- }
294
- }
295
-}
296
-
297
-function checkDepsAreArrayDev(deps: mixed) {
298
- if (__DEV__) {
299
- if (deps !== undefined && deps !== null && !isArray(deps)) {
300
- // Verify deps, but only on mount to avoid extra checks.
301
- // It's unlikely their type would change as usually you define them inline.
302
- console.error(
303
- '%s received a final argument that is not an array (instead, received `%s`). When ' +
304
- 'specified, the final argument must be an array.',
305
- currentHookNameInDev,
306
- typeof deps,
307
- );
308
- }
309
- }
310
-}
311
-
312
-function warnOnHookMismatchInDev(currentHookName: HookType) {
313
- if (__DEV__) {
314
- const componentName = getComponentNameFromFiber(currentlyRenderingFiber);
315
- if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
316
- didWarnAboutMismatchedHooksForComponent.add(componentName);
317
-
318
- if (hookTypesDev !== null) {
319
- let table = '';
320
-
321
- const secondColumnStart = 30;
322
-
323
- for (let i = 0; i <= ((hookTypesUpdateIndexDev: any): number); i++) {
324
- const oldHookName = hookTypesDev[i];
325
- const newHookName =
326
- i === ((hookTypesUpdateIndexDev: any): number)
327
- ? currentHookName
328
- : oldHookName;
329
-
330
- let row = `${i + 1}. ${oldHookName}`;
331
-
332
- // Extra space so second column lines up
333
- // lol @ IE not supporting String#repeat
334
- while (row.length < secondColumnStart) {
335
- row += ' ';
336
- }
337
-
338
- row += newHookName + '\n';
339
-
340
- table += row;
341
- }
342
-
343
- console.error(
344
- 'React has detected a change in the order of Hooks called by %s. ' +
345
- 'This will lead to bugs and errors if not fixed. ' +
346
- 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' +
347
- ' Previous render Next render\n' +
348
- ' ------------------------------------------------------\n' +
349
- '%s' +
350
- ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',
351
- componentName,
352
- table,
353
- );
354
- }
355
- }
356
- }
357
-}
358
-
359
-function throwInvalidHookError() {
360
- throw new Error(
361
- 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
362
- ' one of the following reasons:\n' +
363
- '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
364
- '2. You might be breaking the Rules of Hooks\n' +
365
- '3. You might have more than one copy of React in the same app\n' +
366
- 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
367
- );
368
-}
369
-
370
-function areHookInputsEqual(
371
- nextDeps: Array<mixed>,
372
- prevDeps: Array<mixed> | null,
373
-) {
374
- if (__DEV__) {
375
- if (ignorePreviousDependencies) {
376
- // Only true when this component is being hot reloaded.
377
- return false;
378
- }
379
- }
380
-
381
- if (prevDeps === null) {
382
- if (__DEV__) {
383
- console.error(
384
- '%s received a final argument during this render, but not during ' +
385
- 'the previous render. Even though the final argument is optional, ' +
386
- 'its type cannot change between renders.',
387
- currentHookNameInDev,
388
- );
389
- }
390
- return false;
391
- }
392
-
393
- if (__DEV__) {
394
- // Don't bother comparing lengths in prod because these arrays should be
395
- // passed inline.
396
- if (nextDeps.length !== prevDeps.length) {
397
- console.error(
398
- 'The final argument passed to %s changed size between renders. The ' +
399
- 'order and size of this array must remain constant.\n\n' +
400
- 'Previous: %s\n' +
401
- 'Incoming: %s',
402
- currentHookNameInDev,
403
- `[${prevDeps.join(', ')}]`,
404
- `[${nextDeps.join(', ')}]`,
405
- );
406
- }
407
- }
408
- // $FlowFixMe[incompatible-use] found when upgrading Flow
409
- for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
410
- // $FlowFixMe[incompatible-use] found when upgrading Flow
411
- if (is(nextDeps[i], prevDeps[i])) {
412
- continue;
413
- }
414
- return false;
415
- }
416
- return true;
417
-}
418
-
419
-export function renderWithHooks<Props, SecondArg>(
420
- current: Fiber | null,
421
- workInProgress: Fiber,
422
- Component: (p: Props, arg: SecondArg) => any,
423
- props: Props,
424
- secondArg: SecondArg,
425
- nextRenderLanes: Lanes,
426
-): any {
427
- renderLanes = nextRenderLanes;
428
- currentlyRenderingFiber = workInProgress;
429
-
430
- if (__DEV__) {
431
- hookTypesDev =
432
- current !== null
433
- ? ((current._debugHookTypes: any): Array<HookType>)
434
- : null;
435
- hookTypesUpdateIndexDev = -1;
436
- // Used for hot reloading:
437
- ignorePreviousDependencies =
438
- current !== null && current.type !== workInProgress.type;
439
- }
440
-
441
- workInProgress.memoizedState = null;
442
- workInProgress.updateQueue = null;
443
- workInProgress.lanes = NoLanes;
444
-
445
- // The following should have already been reset
446
- // currentHook = null;
447
- // workInProgressHook = null;
448
-
449
- // didScheduleRenderPhaseUpdate = false;
450
- // localIdCounter = 0;
451
- // thenableIndexCounter = 0;
452
- // thenableState = null;
453
-
454
- // TODO Warn if no hooks are used at all during mount, then some are used during update.
455
- // Currently we will identify the update render as a mount because memoizedState === null.
456
- // This is tricky because it's valid for certain types of components (e.g. React.lazy)
457
-
458
- // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
459
- // Non-stateful hooks (e.g. context) don't get added to memoizedState,
460
- // so memoizedState would be null during updates and mounts.
461
- if (__DEV__) {
462
- if (current !== null && current.memoizedState !== null) {
463
- ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV;
464
- } else if (hookTypesDev !== null) {
465
- // This dispatcher handles an edge case where a component is updating,
466
- // but no stateful hooks have been used.
467
- // We want to match the production code behavior (which will use HooksDispatcherOnMount),
468
- // but with the extra DEV validation to ensure hooks ordering hasn't changed.
469
- // This dispatcher does that.
470
- ReactCurrentDispatcher.current = HooksDispatcherOnMountWithHookTypesInDEV;
471
- } else {
472
- ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV;
473
- }
474
- } else {
475
- ReactCurrentDispatcher.current =
476
- current === null || current.memoizedState === null
477
- ? HooksDispatcherOnMount
478
- : HooksDispatcherOnUpdate;
479
- }
480
-
481
- // In Strict Mode, during development, user functions are double invoked to
482
- // help detect side effects. The logic for how this is implemented for in
483
- // hook components is a bit complex so let's break it down.
484
- //
485
- // We will invoke the entire component function twice. However, during the
486
- // second invocation of the component, the hook state from the first
487
- // invocation will be reused. That means things like `useMemo` functions won't
488
- // run again, because the deps will match and the memoized result will
489
- // be reused.
490
- //
491
- // We want memoized functions to run twice, too, so account for this, user
492
- // functions are double invoked during the *first* invocation of the component
493
- // function, and are *not* double invoked during the second incovation:
494
- //
495
- // - First execution of component function: user functions are double invoked
496
- // - Second execution of component function (in Strict Mode, during
497
- // development): user functions are not double invoked.
498
- //
499
- // This is intentional for a few reasons; most importantly, it's because of
500
- // how `use` works when something suspends: it reuses the promise that was
501
- // passed during the first attempt. This is itself a form of memoization.
502
- // We need to be able to memoize the reactive inputs to the `use` call using
503
- // a hook (i.e. `useMemo`), which means, the reactive inputs to `use` must
504
- // come from the same component invocation as the output.
505
- //
506
- // There are plenty of tests to ensure this behavior is correct.
507
- const shouldDoubleRenderDEV =
508
- __DEV__ &&
509
- debugRenderPhaseSideEffectsForStrictMode &&
510
- (workInProgress.mode & StrictLegacyMode) !== NoMode;
511
-
512
- shouldDoubleInvokeUserFnsInHooksDEV = shouldDoubleRenderDEV;
513
- let children = Component(props, secondArg);
514
- shouldDoubleInvokeUserFnsInHooksDEV = false;
515
-
516
- // Check if there was a render phase update
517
- if (didScheduleRenderPhaseUpdateDuringThisPass) {
518
- // Keep rendering until the component stabilizes (there are no more render
519
- // phase updates).
520
- children = renderWithHooksAgain(
521
- workInProgress,
522
- Component,
523
- props,
524
- secondArg,
525
- );
526
- }
527
-
528
- if (shouldDoubleRenderDEV) {
529
- // In development, components are invoked twice to help detect side effects.
530
- setIsStrictModeForDevtools(true);
531
- try {
532
- children = renderWithHooksAgain(
533
- workInProgress,
534
- Component,
535
- props,
536
- secondArg,
537
- );
538
- } finally {
539
- setIsStrictModeForDevtools(false);
540
- }
541
- }
542
-
543
- finishRenderingHooks(current, workInProgress);
544
-
545
- return children;
546
-}
547
-
548
-function finishRenderingHooks(current: Fiber | null, workInProgress: Fiber) {
549
- // We can assume the previous dispatcher is always this one, since we set it
550
- // at the beginning of the render phase and there's no re-entrance.
551
- ReactCurrentDispatcher.current = ContextOnlyDispatcher;
552
-
553
- if (__DEV__) {
554
- workInProgress._debugHookTypes = hookTypesDev;
555
- }
556
-
557
- // This check uses currentHook so that it works the same in DEV and prod bundles.
558
- // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
559
- const didRenderTooFewHooks =
560
- currentHook !== null && currentHook.next !== null;
561
-
562
- renderLanes = NoLanes;
563
- currentlyRenderingFiber = (null: any);
564
-
565
- currentHook = null;
566
- workInProgressHook = null;
567
-
568
- if (__DEV__) {
569
- currentHookNameInDev = null;
570
- hookTypesDev = null;
571
- hookTypesUpdateIndexDev = -1;
572
-
573
- // Confirm that a static flag was not added or removed since the last
574
- // render. If this fires, it suggests that we incorrectly reset the static
575
- // flags in some other part of the codebase. This has happened before, for
576
- // example, in the SuspenseList implementation.
577
- if (
578
- current !== null &&
579
- (current.flags & StaticMaskEffect) !==
580
- (workInProgress.flags & StaticMaskEffect) &&
581
- // Disable this warning in legacy mode, because legacy Suspense is weird
582
- // and creates false positives. To make this work in legacy mode, we'd
583
- // need to mark fibers that commit in an incomplete state, somehow. For
584
- // now I'll disable the warning that most of the bugs that would trigger
585
- // it are either exclusive to concurrent mode or exist in both.
586
- (current.mode & ConcurrentMode) !== NoMode
587
- ) {
588
- console.error(
589
- 'Internal React error: Expected static flag was missing. Please ' +
590
- 'notify the React team.',
591
- );
592
- }
593
- }
594
-
595
- didScheduleRenderPhaseUpdate = false;
596
- // This is reset by checkDidRenderIdHook
597
- // localIdCounter = 0;
598
-
599
- thenableIndexCounter = 0;
600
- thenableState = null;
601
-
602
- if (didRenderTooFewHooks) {
603
- throw new Error(
604
- 'Rendered fewer hooks than expected. This may be caused by an accidental ' +
605
- 'early return statement.',
606
- );
607
- }
608
-
609
- if (enableLazyContextPropagation) {
610
- if (current !== null) {
611
- if (!checkIfWorkInProgressReceivedUpdate()) {
612
- // If there were no changes to props or state, we need to check if there
613
- // was a context change. We didn't already do this because there's no
614
- // 1:1 correspondence between dependencies and hooks. Although, because
615
- // there almost always is in the common case (`readContext` is an
616
- // internal API), we could compare in there. OTOH, we only hit this case
617
- // if everything else bails out, so on the whole it might be better to
618
- // keep the comparison out of the common path.
619
- const currentDependencies = current.dependencies;
620
- if (
621
- currentDependencies !== null &&
622
- checkIfContextChanged(currentDependencies)
623
- ) {
624
- markWorkInProgressReceivedUpdate();
625
- }
626
- }
627
- }
628
- }
629
-
630
- if (__DEV__) {
631
- if (checkIfUseWrappedInTryCatch()) {
632
- const componentName =
633
- getComponentNameFromFiber(workInProgress) || 'Unknown';
634
- if (!didWarnAboutUseWrappedInTryCatch.has(componentName)) {
635
- didWarnAboutUseWrappedInTryCatch.add(componentName);
636
- console.error(
637
- '`use` was called from inside a try/catch block. This is not allowed ' +
638
- 'and can lead to unexpected behavior. To handle errors triggered ' +
639
- 'by `use`, wrap your component in a error boundary.',
640
- );
641
- }
642
- }
643
- }
644
-}
645
-
646
-export function replaySuspendedComponentWithHooks<Props, SecondArg>(
647
- current: Fiber | null,
648
- workInProgress: Fiber,
649
- Component: (p: Props, arg: SecondArg) => any,
650
- props: Props,
651
- secondArg: SecondArg,
652
-): any {
653
- // This function is used to replay a component that previously suspended,
654
- // after its data resolves.
655
- //
656
- // It's a simplified version of renderWithHooks, but it doesn't need to do
657
- // most of the set up work because they weren't reset when we suspended; they
658
- // only get reset when the component either completes (finishRenderingHooks)
659
- // or unwinds (resetHooksOnUnwind).
660
- if (__DEV__) {
661
- hookTypesDev =
662
- current !== null
663
- ? ((current._debugHookTypes: any): Array<HookType>)
664
- : null;
665
- hookTypesUpdateIndexDev = -1;
666
- // Used for hot reloading:
667
- ignorePreviousDependencies =
668
- current !== null && current.type !== workInProgress.type;
669
- }
670
- const children = renderWithHooksAgain(
671
- workInProgress,
672
- Component,
673
- props,
674
- secondArg,
675
- );
676
- finishRenderingHooks(current, workInProgress);
677
- return children;
678
-}
679
-
680
-function renderWithHooksAgain<Props, SecondArg>(
681
- workInProgress: Fiber,
682
- Component: (p: Props, arg: SecondArg) => any,
683
- props: Props,
684
- secondArg: SecondArg,
685
-) {
686
- // This is used to perform another render pass. It's used when setState is
687
- // called during render, and for double invoking components in Strict Mode
688
- // during development.
689
- //
690
- // The state from the previous pass is reused whenever possible. So, state
691
- // updates that were already processed are not processed again, and memoized
692
- // functions (`useMemo`) are not invoked again.
693
- //
694
- // Keep rendering in a loop for as long as render phase updates continue to
695
- // be scheduled. Use a counter to prevent infinite loops.
696
- let numberOfReRenders: number = 0;
697
- let children;
698
- do {
699
- didScheduleRenderPhaseUpdateDuringThisPass = false;
700
- thenableIndexCounter = 0;
701
-
702
- if (numberOfReRenders >= RE_RENDER_LIMIT) {
703
- throw new Error(
704
- 'Too many re-renders. React limits the number of renders to prevent ' +
705
- 'an infinite loop.',
706
- );
707
- }
708
-
709
- numberOfReRenders += 1;
710
- if (__DEV__) {
711
- // Even when hot reloading, allow dependencies to stabilize
712
- // after first render to prevent infinite render phase updates.
713
- ignorePreviousDependencies = false;
714
- }
715
-
716
- // Start over from the beginning of the list
717
- currentHook = null;
718
- workInProgressHook = null;
719
-
720
- workInProgress.updateQueue = null;
721
-
722
- if (__DEV__) {
723
- // Also validate hook order for cascading updates.
724
- hookTypesUpdateIndexDev = -1;
725
- }
726
-
727
- ReactCurrentDispatcher.current = __DEV__
728
- ? HooksDispatcherOnRerenderInDEV
729
- : HooksDispatcherOnRerender;
730
-
731
- children = Component(props, secondArg);
732
- } while (didScheduleRenderPhaseUpdateDuringThisPass);
733
- return children;
734
-}
735
-
736
-export function checkDidRenderIdHook(): boolean {
737
- // This should be called immediately after every renderWithHooks call.
738
- // Conceptually, it's part of the return value of renderWithHooks; it's only a
739
- // separate function to avoid using an array tuple.
740
- const didRenderIdHook = localIdCounter !== 0;
741
- localIdCounter = 0;
742
- return didRenderIdHook;
743
-}
744
-
745
-export function bailoutHooks(
746
- current: Fiber,
747
- workInProgress: Fiber,
748
- lanes: Lanes,
749
-) {
750
- workInProgress.updateQueue = current.updateQueue;
751
- // TODO: Don't need to reset the flags here, because they're reset in the
752
- // complete phase (bubbleProperties).
753
- if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
754
- workInProgress.flags &= ~(
755
- MountPassiveDevEffect |
756
- MountLayoutDevEffect |
757
- PassiveEffect |
758
- UpdateEffect
759
- );
760
- } else {
761
- workInProgress.flags &= ~(PassiveEffect | UpdateEffect);
762
- }
763
- current.lanes = removeLanes(current.lanes, lanes);
764
-}
765
-
766
-export function resetHooksAfterThrow(): void {
767
- // This is called immediaetly after a throw. It shouldn't reset the entire
768
- // module state, because the work loop might decide to replay the component
769
- // again without rewinding.
770
- //
771
- // It should only reset things like the current dispatcher, to prevent hooks
772
- // from being called outside of a component.
773
-
774
- // We can assume the previous dispatcher is always this one, since we set it
775
- // at the beginning of the render phase and there's no re-entrance.
776
- ReactCurrentDispatcher.current = ContextOnlyDispatcher;
777
-}
778
-
779
-export function resetHooksOnUnwind(): void {
780
- if (didScheduleRenderPhaseUpdate) {
781
- // There were render phase updates. These are only valid for this render
782
- // phase, which we are now aborting. Remove the updates from the queues so
783
- // they do not persist to the next render. Do not remove updates from hooks
784
- // that weren't processed.
785
- //
786
- // Only reset the updates from the queue if it has a clone. If it does
787
- // not have a clone, that means it wasn't processed, and the updates were
788
- // scheduled before we entered the render phase.
789
- let hook: Hook | null = currentlyRenderingFiber.memoizedState;
790
- while (hook !== null) {
791
- const queue = hook.queue;
792
- if (queue !== null) {
793
- queue.pending = null;
794
- }
795
- hook = hook.next;
796
- }
797
- didScheduleRenderPhaseUpdate = false;
798
- }
799
-
800
- renderLanes = NoLanes;
801
- currentlyRenderingFiber = (null: any);
802
-
803
- currentHook = null;
804
- workInProgressHook = null;
805
-
806
- if (__DEV__) {
807
- hookTypesDev = null;
808
- hookTypesUpdateIndexDev = -1;
809
-
810
- currentHookNameInDev = null;
811
- }
812
-
813
- didScheduleRenderPhaseUpdateDuringThisPass = false;
814
- localIdCounter = 0;
815
- thenableIndexCounter = 0;
816
- thenableState = null;
817
-}
818
-
819
-function mountWorkInProgressHook(): Hook {
820
- const hook: Hook = {
821
- memoizedState: null,
822
-
823
- baseState: null,
824
- baseQueue: null,
825
- queue: null,
826
-
827
- next: null,
828
- };
829
-
830
- if (workInProgressHook === null) {
831
- // This is the first hook in the list
832
- currentlyRenderingFiber.memoizedState = workInProgressHook = hook;
833
- } else {
834
- // Append to the end of the list
835
- workInProgressHook = workInProgressHook.next = hook;
836
- }
837
- return workInProgressHook;
838
-}
839
-
840
-function updateWorkInProgressHook(): Hook {
841
- // This function is used both for updates and for re-renders triggered by a
842
- // render phase update. It assumes there is either a current hook we can
843
- // clone, or a work-in-progress hook from a previous render pass that we can
844
- // use as a base. When we reach the end of the base list, we must switch to
845
- // the dispatcher used for mounts.
846
- let nextCurrentHook: null | Hook;
847
- if (currentHook === null) {
848
- const current = currentlyRenderingFiber.alternate;
849
- if (current !== null) {
850
- nextCurrentHook = current.memoizedState;
851
- } else {
852
- nextCurrentHook = null;
853
- }
854
- } else {
855
- nextCurrentHook = currentHook.next;
856
- }
857
-
858
- let nextWorkInProgressHook: null | Hook;
859
- if (workInProgressHook === null) {
860
- nextWorkInProgressHook = currentlyRenderingFiber.memoizedState;
861
- } else {
862
- nextWorkInProgressHook = workInProgressHook.next;
863
- }
864
-
865
- if (nextWorkInProgressHook !== null) {
866
- // There's already a work-in-progress. Reuse it.
867
- workInProgressHook = nextWorkInProgressHook;
868
- nextWorkInProgressHook = workInProgressHook.next;
869
-
870
- currentHook = nextCurrentHook;
871
- } else {
872
- // Clone from the current hook.
873
-
874
- if (nextCurrentHook === null) {
875
- const currentFiber = currentlyRenderingFiber.alternate;
876
- if (currentFiber === null) {
877
- // This is the initial render. This branch is reached when the component
878
- // suspends, resumes, then renders an additional hook.
879
- const newHook: Hook = {
880
- memoizedState: null,
881
-
882
- baseState: null,
883
- baseQueue: null,
884
- queue: null,
885
-
886
- next: null,
887
- };
888
- nextCurrentHook = newHook;
889
- } else {
890
- // This is an update. We should always have a current hook.
891
- throw new Error('Rendered more hooks than during the previous render.');
892
- }
893
- }
894
-
895
- currentHook = nextCurrentHook;
896
-
897
- const newHook: Hook = {
898
- memoizedState: currentHook.memoizedState,
899
-
900
- baseState: currentHook.baseState,
901
- baseQueue: currentHook.baseQueue,
902
- queue: currentHook.queue,
903
-
904
- next: null,
905
- };
906
-
907
- if (workInProgressHook === null) {
908
- // This is the first hook in the list.
909
- currentlyRenderingFiber.memoizedState = workInProgressHook = newHook;
910
- } else {
911
- // Append to the end of the list.
912
- workInProgressHook = workInProgressHook.next = newHook;
913
- }
914
- }
915
- return workInProgressHook;
916
-}
917
-
918
-// NOTE: defining two versions of this function to avoid size impact when this feature is disabled.
919
-// Previously this function was inlined, the additional `memoCache` property makes it not inlined.
920
-let createFunctionComponentUpdateQueue: () => FunctionComponentUpdateQueue;
921
-if (enableUseMemoCacheHook) {
922
- createFunctionComponentUpdateQueue = () => {
923
- return {
924
- lastEffect: null,
925
- events: null,
926
- stores: null,
927
- memoCache: null,
928
- };
929
- };
930
-} else {
931
- createFunctionComponentUpdateQueue = () => {
932
- return {
933
- lastEffect: null,
934
- events: null,
935
- stores: null,
936
- };
937
- };
938
-}
939
-
940
-function use<T>(usable: Usable<T>): T {
941
- if (usable !== null && typeof usable === 'object') {
942
- // $FlowFixMe[method-unbinding]
943
- if (typeof usable.then === 'function') {
944
- // This is a thenable.
945
- const thenable: Thenable<T> = (usable: any);
946
-
947
- // Track the position of the thenable within this fiber.
948
- const index = thenableIndexCounter;
949
- thenableIndexCounter += 1;
950
-
951
- if (thenableState === null) {
952
- thenableState = createThenableState();
953
- }
954
- return trackUsedThenable(thenableState, thenable, index);
955
- } else if (
956
- usable.$$typeof === REACT_CONTEXT_TYPE ||
957
- usable.$$typeof === REACT_SERVER_CONTEXT_TYPE
958
- ) {
959
- const context: ReactContext<T> = (usable: any);
960
- return readContext(context);
961
- }
962
- }
963
-
964
- // eslint-disable-next-line react-internal/safe-string-coercion
965
- throw new Error('An unsupported type was passed to use(): ' + String(usable));
966
-}
967
-
968
-function useMemoCache(size: number): Array<any> {
969
- let memoCache = null;
970
- // Fast-path, load memo cache from wip fiber if already prepared
971
- let updateQueue: FunctionComponentUpdateQueue | null = (currentlyRenderingFiber.updateQueue: any);
972
- if (updateQueue !== null) {
973
- memoCache = updateQueue.memoCache;
974
- }
975
- // Otherwise clone from the current fiber
976
- if (memoCache == null) {
977
- const current: Fiber | null = currentlyRenderingFiber.alternate;
978
- if (current !== null) {
979
- const currentUpdateQueue: FunctionComponentUpdateQueue | null = (current.updateQueue: any);
980
- if (currentUpdateQueue !== null) {
981
- const currentMemoCache: ?MemoCache = currentUpdateQueue.memoCache;
982
- if (currentMemoCache != null) {
983
- memoCache = {
984
- data: currentMemoCache.data.map(array => array.slice()),
985
- index: 0,
986
- };
987
- }
988
- }
989
- }
990
- }
991
- // Finally fall back to allocating a fresh instance of the cache
992
- if (memoCache == null) {
993
- memoCache = {
994
- data: [],
995
- index: 0,
996
- };
997
- }
998
- if (updateQueue === null) {
999
- updateQueue = createFunctionComponentUpdateQueue();
1000
- currentlyRenderingFiber.updateQueue = updateQueue;
1001
- }
1002
- updateQueue.memoCache = memoCache;
1003
-
1004
- let data = memoCache.data[memoCache.index];
1005
- if (data === undefined) {
1006
- data = memoCache.data[memoCache.index] = new Array(size);
1007
- for (let i = 0; i < size; i++) {
1008
- data[i] = REACT_MEMO_CACHE_SENTINEL;
1009
- }
1010
- } else if (data.length !== size) {
1011
- // TODO: consider warning or throwing here
1012
- if (__DEV__) {
1013
- console.error(
1014
- 'Expected a constant size argument for each invocation of useMemoCache. ' +
1015
- 'The previous cache was allocated with size %s but size %s was requested.',
1016
- data.length,
1017
- size,
1018
- );
1019
- }
1020
- }
1021
- memoCache.index++;
1022
- return data;
1023
-}
1024
-
1025
-function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
1026
- // $FlowFixMe: Flow doesn't like mixed types
1027
- return typeof action === 'function' ? action(state) : action;
1028
-}
1029
-
1030
-function mountReducer<S, I, A>(
1031
- reducer: (S, A) => S,
1032
- initialArg: I,
1033
- init?: I => S,
1034
-): [S, Dispatch<A>] {
1035
- const hook = mountWorkInProgressHook();
1036
- let initialState;
1037
- if (init !== undefined) {
1038
- initialState = init(initialArg);
1039
- } else {
1040
- initialState = ((initialArg: any): S);
1041
- }
1042
- hook.memoizedState = hook.baseState = initialState;
1043
- const queue: UpdateQueue<S, A> = {
1044
- pending: null,
1045
- lanes: NoLanes,
1046
- dispatch: null,
1047
- lastRenderedReducer: reducer,
1048
- lastRenderedState: (initialState: any),
1049
- };
1050
- hook.queue = queue;
1051
- const dispatch: Dispatch<A> = (queue.dispatch = (dispatchReducerAction.bind(
1052
- null,
1053
- currentlyRenderingFiber,
1054
- queue,
1055
- ): any));
1056
- return [hook.memoizedState, dispatch];
1057
-}
1058
-
1059
-function updateReducer<S, I, A>(
1060
- reducer: (S, A) => S,
1061
- initialArg: I,
1062
- init?: I => S,
1063
-): [S, Dispatch<A>] {
1064
- const hook = updateWorkInProgressHook();
1065
- const queue = hook.queue;
1066
-
1067
- if (queue === null) {
1068
- throw new Error(
1069
- 'Should have a queue. This is likely a bug in React. Please file an issue.',
1070
- );
1071
- }
1072
-
1073
- queue.lastRenderedReducer = reducer;
1074
-
1075
- const current: Hook = (currentHook: any);
1076
-
1077
- // The last rebase update that is NOT part of the base state.
1078
- let baseQueue = current.baseQueue;
1079
-
1080
- // The last pending update that hasn't been processed yet.
1081
- const pendingQueue = queue.pending;
1082
- if (pendingQueue !== null) {
1083
- // We have new updates that haven't been processed yet.
1084
- // We'll add them to the base queue.
1085
- if (baseQueue !== null) {
1086
- // Merge the pending queue and the base queue.
1087
- const baseFirst = baseQueue.next;
1088
- const pendingFirst = pendingQueue.next;
1089
- baseQueue.next = pendingFirst;
1090
- pendingQueue.next = baseFirst;
1091
- }
1092
- if (__DEV__) {
1093
- if (current.baseQueue !== baseQueue) {
1094
- // Internal invariant that should never happen, but feasibly could in
1095
- // the future if we implement resuming, or some form of that.
1096
- console.error(
1097
- 'Internal error: Expected work-in-progress queue to be a clone. ' +
1098
- 'This is a bug in React.',
1099
- );
1100
- }
1101
- }
1102
- current.baseQueue = baseQueue = pendingQueue;
1103
- queue.pending = null;
1104
- }
1105
-
1106
- if (baseQueue !== null) {
1107
- // We have a queue to process.
1108
- const first = baseQueue.next;
1109
- let newState = current.baseState;
1110
-
1111
- let newBaseState = null;
1112
- let newBaseQueueFirst = null;
1113
- let newBaseQueueLast = null;
1114
- let update = first;
1115
- do {
1116
- // An extra OffscreenLane bit is added to updates that were made to
1117
- // a hidden tree, so that we can distinguish them from updates that were
1118
- // already there when the tree was hidden.
1119
- const updateLane = removeLanes(update.lane, OffscreenLane);
1120
- const isHiddenUpdate = updateLane !== update.lane;
1121
-
1122
- // Check if this update was made while the tree was hidden. If so, then
1123
- // it's not a "base" update and we should disregard the extra base lanes
1124
- // that were added to renderLanes when we entered the Offscreen tree.
1125
- const shouldSkipUpdate = isHiddenUpdate
1126
- ? !isSubsetOfLanes(getWorkInProgressRootRenderLanes(), updateLane)
1127
- : !isSubsetOfLanes(renderLanes, updateLane);
1128
-
1129
- if (shouldSkipUpdate) {
1130
- // Priority is insufficient. Skip this update. If this is the first
1131
- // skipped update, the previous update/state is the new base
1132
- // update/state.
1133
- const clone: Update<S, A> = {
1134
- lane: updateLane,
1135
- action: update.action,
1136
- hasEagerState: update.hasEagerState,
1137
- eagerState: update.eagerState,
1138
- next: (null: any),
1139
- };
1140
- if (newBaseQueueLast === null) {
1141
- newBaseQueueFirst = newBaseQueueLast = clone;
1142
- newBaseState = newState;
1143
- } else {
1144
- newBaseQueueLast = newBaseQueueLast.next = clone;
1145
- }
1146
- // Update the remaining priority in the queue.
1147
- // TODO: Don't need to accumulate this. Instead, we can remove
1148
- // renderLanes from the original lanes.
1149
- currentlyRenderingFiber.lanes = mergeLanes(
1150
- currentlyRenderingFiber.lanes,
1151
- updateLane,
1152
- );
1153
- markSkippedUpdateLanes(updateLane);
1154
- } else {
1155
- // This update does have sufficient priority.
1156
-
1157
- if (newBaseQueueLast !== null) {
1158
- const clone: Update<S, A> = {
1159
- // This update is going to be committed so we never want uncommit
1160
- // it. Using NoLane works because 0 is a subset of all bitmasks, so
1161
- // this will never be skipped by the check above.
1162
- lane: NoLane,
1163
- action: update.action,
1164
- hasEagerState: update.hasEagerState,
1165
- eagerState: update.eagerState,
1166
- next: (null: any),
1167
- };
1168
- newBaseQueueLast = newBaseQueueLast.next = clone;
1169
- }
1170
-
1171
- // Process this update.
1172
- const action = update.action;
1173
- if (shouldDoubleInvokeUserFnsInHooksDEV) {
1174
- reducer(newState, action);
1175
- }
1176
- if (update.hasEagerState) {
1177
- // If this update is a state update (not a reducer) and was processed eagerly,
1178
- // we can use the eagerly computed state
1179
- newState = ((update.eagerState: any): S);
1180
- } else {
1181
- newState = reducer(newState, action);
1182
- }
1183
- }
1184
- update = update.next;
1185
- } while (update !== null && update !== first);
1186
-
1187
- if (newBaseQueueLast === null) {
1188
- newBaseState = newState;
1189
- } else {
1190
- newBaseQueueLast.next = (newBaseQueueFirst: any);
1191
- }
1192
-
1193
- // Mark that the fiber performed work, but only if the new state is
1194
- // different from the current state.
1195
- if (!is(newState, hook.memoizedState)) {
1196
- markWorkInProgressReceivedUpdate();
1197
- }
1198
-
1199
- hook.memoizedState = newState;
1200
- hook.baseState = newBaseState;
1201
- hook.baseQueue = newBaseQueueLast;
1202
-
1203
- queue.lastRenderedState = newState;
1204
- }
1205
-
1206
- if (baseQueue === null) {
1207
- // `queue.lanes` is used for entangling transitions. We can set it back to
1208
- // zero once the queue is empty.
1209
- queue.lanes = NoLanes;
1210
- }
1211
-
1212
- const dispatch: Dispatch<A> = (queue.dispatch: any);
1213
- return [hook.memoizedState, dispatch];
1214
-}
1215
-
1216
-function rerenderReducer<S, I, A>(
1217
- reducer: (S, A) => S,
1218
- initialArg: I,
1219
- init?: I => S,
1220
-): [S, Dispatch<A>] {
1221
- const hook = updateWorkInProgressHook();
1222
- const queue = hook.queue;
1223
-
1224
- if (queue === null) {
1225
- throw new Error(
1226
- 'Should have a queue. This is likely a bug in React. Please file an issue.',
1227
- );
1228
- }
1229
-
1230
- queue.lastRenderedReducer = reducer;
1231
-
1232
- // This is a re-render. Apply the new render phase updates to the previous
1233
- // work-in-progress hook.
1234
- const dispatch: Dispatch<A> = (queue.dispatch: any);
1235
- const lastRenderPhaseUpdate = queue.pending;
1236
- let newState = hook.memoizedState;
1237
- if (lastRenderPhaseUpdate !== null) {
1238
- // The queue doesn't persist past this render pass.
1239
- queue.pending = null;
1240
-
1241
- const firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
1242
- let update = firstRenderPhaseUpdate;
1243
- do {
1244
- // Process this render phase update. We don't have to check the
1245
- // priority because it will always be the same as the current
1246
- // render's.
1247
- const action = update.action;
1248
- newState = reducer(newState, action);
1249
- update = update.next;
1250
- } while (update !== firstRenderPhaseUpdate);
1251
-
1252
- // Mark that the fiber performed work, but only if the new state is
1253
- // different from the current state.
1254
- if (!is(newState, hook.memoizedState)) {
1255
- markWorkInProgressReceivedUpdate();
1256
- }
1257
-
1258
- hook.memoizedState = newState;
1259
- // Don't persist the state accumulated from the render phase updates to
1260
- // the base state unless the queue is empty.
1261
- // TODO: Not sure if this is the desired semantics, but it's what we
1262
- // do for gDSFP. I can't remember why.
1263
- if (hook.baseQueue === null) {
1264
- hook.baseState = newState;
1265
- }
1266
-
1267
- queue.lastRenderedState = newState;
1268
- }
1269
- return [newState, dispatch];
1270
-}
1271
-
1272
-type MutableSourceMemoizedState<Source, Snapshot> = {
1273
- refs: {
1274
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
1275
- setSnapshot: Snapshot => void,
1276
- },
1277
- source: MutableSource<any>,
1278
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
1279
-};
1280
-
1281
-function readFromUnsubscribedMutableSource<Source, Snapshot>(
1282
- root: FiberRoot,
1283
- source: MutableSource<Source>,
1284
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
1285
-): Snapshot {
1286
- if (__DEV__) {
1287
- warnAboutMultipleRenderersDEV(source);
1288
- }
1289
-
1290
- const getVersion = source._getVersion;
1291
- const version = getVersion(source._source);
1292
-
1293
- // Is it safe for this component to read from this source during the current render?
1294
- let isSafeToReadFromSource = false;
1295
-
1296
- // Check the version first.
1297
- // If this render has already been started with a specific version,
1298
- // we can use it alone to determine if we can safely read from the source.
1299
- const currentRenderVersion = getWorkInProgressVersion(source);
1300
- if (currentRenderVersion !== null) {
1301
- // It's safe to read if the store hasn't been mutated since the last time
1302
- // we read something.
1303
- isSafeToReadFromSource = currentRenderVersion === version;
1304
- } else {
1305
- // If there's no version, then this is the first time we've read from the
1306
- // source during the current render pass, so we need to do a bit more work.
1307
- // What we need to determine is if there are any hooks that already
1308
- // subscribed to the source, and if so, whether there are any pending
1309
- // mutations that haven't been synchronized yet.
1310
- //
1311
- // If there are no pending mutations, then `root.mutableReadLanes` will be
1312
- // empty, and we know we can safely read.
1313
- //
1314
- // If there *are* pending mutations, we may still be able to safely read
1315
- // if the currently rendering lanes are inclusive of the pending mutation
1316
- // lanes, since that guarantees that the value we're about to read from
1317
- // the source is consistent with the values that we read during the most
1318
- // recent mutation.
1319
- isSafeToReadFromSource = isSubsetOfLanes(
1320
- renderLanes,
1321
- root.mutableReadLanes,
1322
- );
1323
-
1324
- if (isSafeToReadFromSource) {
1325
- // If it's safe to read from this source during the current render,
1326
- // store the version in case other components read from it.
1327
- // A changed version number will let those components know to throw and restart the render.
1328
- setWorkInProgressVersion(source, version);
1329
- }
1330
- }
1331
-
1332
- if (isSafeToReadFromSource) {
1333
- const snapshot = getSnapshot(source._source);
1334
- if (__DEV__) {
1335
- if (typeof snapshot === 'function') {
1336
- console.error(
1337
- 'Mutable source should not return a function as the snapshot value. ' +
1338
- 'Functions may close over mutable values and cause tearing.',
1339
- );
1340
- }
1341
- }
1342
- return snapshot;
1343
- } else {
1344
- // This handles the special case of a mutable source being shared between renderers.
1345
- // In that case, if the source is mutated between the first and second renderer,
1346
- // The second renderer don't know that it needs to reset the WIP version during unwind,
1347
- // (because the hook only marks sources as dirty if it's written to their WIP version).
1348
- // That would cause this tear check to throw again and eventually be visible to the user.
1349
- // We can avoid this infinite loop by explicitly marking the source as dirty.
1350
- //
1351
- // This can lead to tearing in the first renderer when it resumes,
1352
- // but there's nothing we can do about that (short of throwing here and refusing to continue the render).
1353
- markSourceAsDirty(source);
1354
-
1355
- // Intentioally throw an error to force React to retry synchronously. During
1356
- // the synchronous retry, it will block interleaved mutations, so we should
1357
- // get a consistent read. Therefore, the following error should never be
1358
- // visible to the user.
1359
-
1360
- // We expect this error not to be thrown during the synchronous retry,
1361
- // because we blocked interleaved mutations.
1362
- throw new Error(
1363
- 'Cannot read from mutable source during the current render without tearing. This may be a bug in React. Please file an issue.',
1364
- );
1365
- }
1366
-}
1367
-
1368
-function useMutableSource<Source, Snapshot>(
1369
- hook: Hook,
1370
- source: MutableSource<Source>,
1371
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
1372
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
1373
-): Snapshot {
1374
- if (!enableUseMutableSource) {
1375
- return (undefined: any);
1376
- }
1377
-
1378
- const root = ((getWorkInProgressRoot(): any): FiberRoot);
1379
-
1380
- if (root === null) {
1381
- throw new Error(
1382
- 'Expected a work-in-progress root. This is a bug in React. Please file an issue.',
1383
- );
1384
- }
1385
-
1386
- const getVersion = source._getVersion;
1387
- const version = getVersion(source._source);
1388
-
1389
- const dispatcher = ReactCurrentDispatcher.current;
1390
-
1391
- // eslint-disable-next-line prefer-const
1392
- let [currentSnapshot, setSnapshot] = dispatcher.useState(() =>
1393
- readFromUnsubscribedMutableSource(root, source, getSnapshot),
1394
- );
1395
- let snapshot = currentSnapshot;
1396
-
1397
- // Grab a handle to the state hook as well.
1398
- // We use it to clear the pending update queue if we have a new source.
1399
- const stateHook = ((workInProgressHook: any): Hook);
1400
-
1401
- const memoizedState = ((hook.memoizedState: any): MutableSourceMemoizedState<
1402
- Source,
1403
- Snapshot,
1404
- >);
1405
- const refs = memoizedState.refs;
1406
- const prevGetSnapshot = refs.getSnapshot;
1407
- const prevSource = memoizedState.source;
1408
- const prevSubscribe = memoizedState.subscribe;
1409
-
1410
- const fiber = currentlyRenderingFiber;
1411
-
1412
- hook.memoizedState = ({
1413
- refs,
1414
- source,
1415
- subscribe,
1416
- }: MutableSourceMemoizedState<Source, Snapshot>);
1417
-
1418
- // Sync the values needed by our subscription handler after each commit.
1419
- dispatcher.useEffect(() => {
1420
- refs.getSnapshot = getSnapshot;
1421
-
1422
- // Normally the dispatch function for a state hook never changes,
1423
- // but this hook recreates the queue in certain cases to avoid updates from stale sources.
1424
- // handleChange() below needs to reference the dispatch function without re-subscribing,
1425
- // so we use a ref to ensure that it always has the latest version.
1426
- refs.setSnapshot = setSnapshot;
1427
-
1428
- // Check for a possible change between when we last rendered now.
1429
- const maybeNewVersion = getVersion(source._source);
1430
- if (!is(version, maybeNewVersion)) {
1431
- const maybeNewSnapshot = getSnapshot(source._source);
1432
- if (__DEV__) {
1433
- if (typeof maybeNewSnapshot === 'function') {
1434
- console.error(
1435
- 'Mutable source should not return a function as the snapshot value. ' +
1436
- 'Functions may close over mutable values and cause tearing.',
1437
- );
1438
- }
1439
- }
1440
-
1441
- if (!is(snapshot, maybeNewSnapshot)) {
1442
- setSnapshot(maybeNewSnapshot);
1443
-
1444
- const lane = requestUpdateLane(fiber);
1445
- markRootMutableRead(root, lane);
1446
- }
1447
- // If the source mutated between render and now,
1448
- // there may be state updates already scheduled from the old source.
1449
- // Entangle the updates so that they render in the same batch.
1450
- markRootEntangled(root, root.mutableReadLanes);
1451
- }
1452
- }, [getSnapshot, source, subscribe]);
1453
-
1454
- // If we got a new source or subscribe function, re-subscribe in a passive effect.
1455
- dispatcher.useEffect(() => {
1456
- const handleChange = () => {
1457
- const latestGetSnapshot = refs.getSnapshot;
1458
- const latestSetSnapshot = refs.setSnapshot;
1459
-
1460
- try {
1461
- latestSetSnapshot(latestGetSnapshot(source._source));
1462
-
1463
- // Record a pending mutable source update with the same expiration time.
1464
- const lane = requestUpdateLane(fiber);
1465
-
1466
- markRootMutableRead(root, lane);
1467
- } catch (error) {
1468
- // A selector might throw after a source mutation.
1469
- // e.g. it might try to read from a part of the store that no longer exists.
1470
- // In this case we should still schedule an update with React.
1471
- // Worst case the selector will throw again and then an error boundary will handle it.
1472
- latestSetSnapshot(
1473
- (() => {
1474
- throw error;
1475
- }: any),
1476
- );
1477
- }
1478
- };
1479
-
1480
- const unsubscribe = subscribe(source._source, handleChange);
1481
- if (__DEV__) {
1482
- if (typeof unsubscribe !== 'function') {
1483
- console.error(
1484
- 'Mutable source subscribe function must return an unsubscribe function.',
1485
- );
1486
- }
1487
- }
1488
-
1489
- return unsubscribe;
1490
- }, [source, subscribe]);
1491
-
1492
- // If any of the inputs to useMutableSource change, reading is potentially unsafe.
1493
- //
1494
- // If either the source or the subscription have changed we can't can't trust the update queue.
1495
- // Maybe the source changed in a way that the old subscription ignored but the new one depends on.
1496
- //
1497
- // If the getSnapshot function changed, we also shouldn't rely on the update queue.
1498
- // It's possible that the underlying source was mutated between the when the last "change" event fired,
1499
- // and when the current render (with the new getSnapshot function) is processed.
1500
- //
1501
- // In both cases, we need to throw away pending updates (since they are no longer relevant)
1502
- // and treat reading from the source as we do in the mount case.
1503
- if (
1504
- !is(prevGetSnapshot, getSnapshot) ||
1505
- !is(prevSource, source) ||
1506
- !is(prevSubscribe, subscribe)
1507
- ) {
1508
- // Create a new queue and setState method,
1509
- // So if there are interleaved updates, they get pushed to the older queue.
1510
- // When this becomes current, the previous queue and dispatch method will be discarded,
1511
- // including any interleaving updates that occur.
1512
- const newQueue: UpdateQueue<Snapshot, BasicStateAction<Snapshot>> = {
1513
- pending: null,
1514
- lanes: NoLanes,
1515
- dispatch: null,
1516
- lastRenderedReducer: basicStateReducer,
1517
- lastRenderedState: snapshot,
1518
- };
1519
- newQueue.dispatch = setSnapshot = (dispatchSetState.bind(
1520
- null,
1521
- currentlyRenderingFiber,
1522
- newQueue,
1523
- ): any);
1524
- stateHook.queue = newQueue;
1525
- stateHook.baseQueue = null;
1526
- snapshot = readFromUnsubscribedMutableSource(root, source, getSnapshot);
1527
- stateHook.memoizedState = stateHook.baseState = snapshot;
1528
- }
1529
-
1530
- return snapshot;
1531
-}
1532
-
1533
-function mountMutableSource<Source, Snapshot>(
1534
- source: MutableSource<Source>,
1535
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
1536
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
1537
-): Snapshot {
1538
- if (!enableUseMutableSource) {
1539
- return (undefined: any);
1540
- }
1541
-
1542
- const hook = mountWorkInProgressHook();
1543
- hook.memoizedState = ({
1544
- refs: {
1545
- getSnapshot,
1546
- setSnapshot: (null: any),
1547
- },
1548
- source,
1549
- subscribe,
1550
- }: MutableSourceMemoizedState<Source, Snapshot>);
1551
- return useMutableSource(hook, source, getSnapshot, subscribe);
1552
-}
1553
-
1554
-function updateMutableSource<Source, Snapshot>(
1555
- source: MutableSource<Source>,
1556
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
1557
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
1558
-): Snapshot {
1559
- if (!enableUseMutableSource) {
1560
- return (undefined: any);
1561
- }
1562
-
1563
- const hook = updateWorkInProgressHook();
1564
- return useMutableSource(hook, source, getSnapshot, subscribe);
1565
-}
1566
-
1567
-function mountSyncExternalStore<T>(
1568
- subscribe: (() => void) => () => void,
1569
- getSnapshot: () => T,
1570
- getServerSnapshot?: () => T,
1571
-): T {
1572
- const fiber = currentlyRenderingFiber;
1573
- const hook = mountWorkInProgressHook();
1574
-
1575
- let nextSnapshot;
1576
- const isHydrating = getIsHydrating();
1577
- if (isHydrating) {
1578
- if (getServerSnapshot === undefined) {
1579
- throw new Error(
1580
- 'Missing getServerSnapshot, which is required for ' +
1581
- 'server-rendered content. Will revert to client rendering.',
1582
- );
1583
- }
1584
- nextSnapshot = getServerSnapshot();
1585
- if (__DEV__) {
1586
- if (!didWarnUncachedGetSnapshot) {
1587
- if (nextSnapshot !== getServerSnapshot()) {
1588
- console.error(
1589
- 'The result of getServerSnapshot should be cached to avoid an infinite loop',
1590
- );
1591
- didWarnUncachedGetSnapshot = true;
1592
- }
1593
- }
1594
- }
1595
- } else {
1596
- nextSnapshot = getSnapshot();
1597
- if (__DEV__) {
1598
- if (!didWarnUncachedGetSnapshot) {
1599
- const cachedSnapshot = getSnapshot();
1600
- if (!is(nextSnapshot, cachedSnapshot)) {
1601
- console.error(
1602
- 'The result of getSnapshot should be cached to avoid an infinite loop',
1603
- );
1604
- didWarnUncachedGetSnapshot = true;
1605
- }
1606
- }
1607
- }
1608
- // Unless we're rendering a blocking lane, schedule a consistency check.
1609
- // Right before committing, we will walk the tree and check if any of the
1610
- // stores were mutated.
1611
- //
1612
- // We won't do this if we're hydrating server-rendered content, because if
1613
- // the content is stale, it's already visible anyway. Instead we'll patch
1614
- // it up in a passive effect.
1615
- const root: FiberRoot | null = getWorkInProgressRoot();
1616
-
1617
- if (root === null) {
1618
- throw new Error(
1619
- 'Expected a work-in-progress root. This is a bug in React. Please file an issue.',
1620
- );
1621
- }
1622
-
1623
- if (!includesBlockingLane(root, renderLanes)) {
1624
- pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
1625
- }
1626
- }
1627
-
1628
- // Read the current snapshot from the store on every render. This breaks the
1629
- // normal rules of React, and only works because store updates are
1630
- // always synchronous.
1631
- hook.memoizedState = nextSnapshot;
1632
- const inst: StoreInstance<T> = {
1633
- value: nextSnapshot,
1634
- getSnapshot,
1635
- };
1636
- hook.queue = inst;
1637
-
1638
- // Schedule an effect to subscribe to the store.
1639
- mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]);
1640
-
1641
- // Schedule an effect to update the mutable instance fields. We will update
1642
- // this whenever subscribe, getSnapshot, or value changes. Because there's no
1643
- // clean-up function, and we track the deps correctly, we can call pushEffect
1644
- // directly, without storing any additional state. For the same reason, we
1645
- // don't need to set a static flag, either.
1646
- // TODO: We can move this to the passive phase once we add a pre-commit
1647
- // consistency check. See the next comment.
1648
- fiber.flags |= PassiveEffect;
1649
- pushEffect(
1650
- HookHasEffect | HookPassive,
1651
- updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot),
1652
- undefined,
1653
- null,
1654
- );
1655
-
1656
- return nextSnapshot;
1657
-}
1658
-
1659
-function updateSyncExternalStore<T>(
1660
- subscribe: (() => void) => () => void,
1661
- getSnapshot: () => T,
1662
- getServerSnapshot?: () => T,
1663
-): T {
1664
- const fiber = currentlyRenderingFiber;
1665
- const hook = updateWorkInProgressHook();
1666
- // Read the current snapshot from the store on every render. This breaks the
1667
- // normal rules of React, and only works because store updates are
1668
- // always synchronous.
1669
- const nextSnapshot = getSnapshot();
1670
- if (__DEV__) {
1671
- if (!didWarnUncachedGetSnapshot) {
1672
- const cachedSnapshot = getSnapshot();
1673
- if (!is(nextSnapshot, cachedSnapshot)) {
1674
- console.error(
1675
- 'The result of getSnapshot should be cached to avoid an infinite loop',
1676
- );
1677
- didWarnUncachedGetSnapshot = true;
1678
- }
1679
- }
1680
- }
1681
- const prevSnapshot = (currentHook || hook).memoizedState;
1682
- const snapshotChanged = !is(prevSnapshot, nextSnapshot);
1683
- if (snapshotChanged) {
1684
- hook.memoizedState = nextSnapshot;
1685
- markWorkInProgressReceivedUpdate();
1686
- }
1687
- const inst = hook.queue;
1688
-
1689
- updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
1690
- subscribe,
1691
- ]);
1692
-
1693
- // Whenever getSnapshot or subscribe changes, we need to check in the
1694
- // commit phase if there was an interleaved mutation. In concurrent mode
1695
- // this can happen all the time, but even in synchronous mode, an earlier
1696
- // effect may have mutated the store.
1697
- if (
1698
- inst.getSnapshot !== getSnapshot ||
1699
- snapshotChanged ||
1700
- // Check if the susbcribe function changed. We can save some memory by
1701
- // checking whether we scheduled a subscription effect above.
1702
- (workInProgressHook !== null &&
1703
- workInProgressHook.memoizedState.tag & HookHasEffect)
1704
- ) {
1705
- fiber.flags |= PassiveEffect;
1706
- pushEffect(
1707
- HookHasEffect | HookPassive,
1708
- updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot),
1709
- undefined,
1710
- null,
1711
- );
1712
-
1713
- // Unless we're rendering a blocking lane, schedule a consistency check.
1714
- // Right before committing, we will walk the tree and check if any of the
1715
- // stores were mutated.
1716
- const root: FiberRoot | null = getWorkInProgressRoot();
1717
-
1718
- if (root === null) {
1719
- throw new Error(
1720
- 'Expected a work-in-progress root. This is a bug in React. Please file an issue.',
1721
- );
1722
- }
1723
-
1724
- if (!includesBlockingLane(root, renderLanes)) {
1725
- pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
1726
- }
1727
- }
1728
-
1729
- return nextSnapshot;
1730
-}
1731
-
1732
-function pushStoreConsistencyCheck<T>(
1733
- fiber: Fiber,
1734
- getSnapshot: () => T,
1735
- renderedSnapshot: T,
1736
-) {
1737
- fiber.flags |= StoreConsistency;
1738
- const check: StoreConsistencyCheck<T> = {
1739
- getSnapshot,
1740
- value: renderedSnapshot,
1741
- };
1742
- let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any);
1743
- if (componentUpdateQueue === null) {
1744
- componentUpdateQueue = createFunctionComponentUpdateQueue();
1745
- currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any);
1746
- componentUpdateQueue.stores = [check];
1747
- } else {
1748
- const stores = componentUpdateQueue.stores;
1749
- if (stores === null) {
1750
- componentUpdateQueue.stores = [check];
1751
- } else {
1752
- stores.push(check);
1753
- }
1754
- }
1755
-}
1756
-
1757
-function updateStoreInstance<T>(
1758
- fiber: Fiber,
1759
- inst: StoreInstance<T>,
1760
- nextSnapshot: T,
1761
- getSnapshot: () => T,
1762
-) {
1763
- // These are updated in the passive phase
1764
- inst.value = nextSnapshot;
1765
- inst.getSnapshot = getSnapshot;
1766
-
1767
- // Something may have been mutated in between render and commit. This could
1768
- // have been in an event that fired before the passive effects, or it could
1769
- // have been in a layout effect. In that case, we would have used the old
1770
- // snapsho and getSnapshot values to bail out. We need to check one more time.
1771
- if (checkIfSnapshotChanged(inst)) {
1772
- // Force a re-render.
1773
- forceStoreRerender(fiber);
1774
- }
1775
-}
1776
-
1777
-function subscribeToStore<T>(fiber, inst: StoreInstance<T>, subscribe) {
1778
- const handleStoreChange = () => {
1779
- // The store changed. Check if the snapshot changed since the last time we
1780
- // read from the store.
1781
- if (checkIfSnapshotChanged(inst)) {
1782
- // Force a re-render.
1783
- forceStoreRerender(fiber);
1784
- }
1785
- };
1786
- // Subscribe to the store and return a clean-up function.
1787
- return subscribe(handleStoreChange);
1788
-}
1789
-
1790
-function checkIfSnapshotChanged<T>(inst: StoreInstance<T>): boolean {
1791
- const latestGetSnapshot = inst.getSnapshot;
1792
- const prevValue = inst.value;
1793
- try {
1794
- const nextValue = latestGetSnapshot();
1795
- return !is(prevValue, nextValue);
1796
- } catch (error) {
1797
- return true;
1798
- }
1799
-}
1800
-
1801
-function forceStoreRerender(fiber) {
1802
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
1803
- if (root !== null) {
1804
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
1805
- }
1806
-}
1807
-
1808
-function mountState<S>(
1809
- initialState: (() => S) | S,
1810
-): [S, Dispatch<BasicStateAction<S>>] {
1811
- const hook = mountWorkInProgressHook();
1812
- if (typeof initialState === 'function') {
1813
- // $FlowFixMe: Flow doesn't like mixed types
1814
- initialState = initialState();
1815
- }
1816
- hook.memoizedState = hook.baseState = initialState;
1817
- const queue: UpdateQueue<S, BasicStateAction<S>> = {
1818
- pending: null,
1819
- lanes: NoLanes,
1820
- dispatch: null,
1821
- lastRenderedReducer: basicStateReducer,
1822
- lastRenderedState: (initialState: any),
1823
- };
1824
- hook.queue = queue;
1825
- const dispatch: Dispatch<
1826
- BasicStateAction<S>,
1827
- > = (queue.dispatch = (dispatchSetState.bind(
1828
- null,
1829
- currentlyRenderingFiber,
1830
- queue,
1831
- ): any));
1832
- return [hook.memoizedState, dispatch];
1833
-}
1834
-
1835
-function updateState<S>(
1836
- initialState: (() => S) | S,
1837
-): [S, Dispatch<BasicStateAction<S>>] {
1838
- return updateReducer(basicStateReducer, (initialState: any));
1839
-}
1840
-
1841
-function rerenderState<S>(
1842
- initialState: (() => S) | S,
1843
-): [S, Dispatch<BasicStateAction<S>>] {
1844
- return rerenderReducer(basicStateReducer, (initialState: any));
1845
-}
1846
-
1847
-function pushEffect(tag, create, destroy, deps: Array<mixed> | void | null) {
1848
- const effect: Effect = {
1849
- tag,
1850
- create,
1851
- destroy,
1852
- deps,
1853
- // Circular
1854
- next: (null: any),
1855
- };
1856
- let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any);
1857
- if (componentUpdateQueue === null) {
1858
- componentUpdateQueue = createFunctionComponentUpdateQueue();
1859
- currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any);
1860
- componentUpdateQueue.lastEffect = effect.next = effect;
1861
- } else {
1862
- const lastEffect = componentUpdateQueue.lastEffect;
1863
- if (lastEffect === null) {
1864
- componentUpdateQueue.lastEffect = effect.next = effect;
1865
- } else {
1866
- const firstEffect = lastEffect.next;
1867
- lastEffect.next = effect;
1868
- effect.next = firstEffect;
1869
- componentUpdateQueue.lastEffect = effect;
1870
- }
1871
- }
1872
- return effect;
1873
-}
1874
-
1875
-let stackContainsErrorMessage: boolean | null = null;
1876
-
1877
-function getCallerStackFrame(): string {
1878
- // eslint-disable-next-line react-internal/prod-error-codes
1879
- const stackFrames = new Error('Error message').stack.split('\n');
1880
-
1881
- // Some browsers (e.g. Chrome) include the error message in the stack
1882
- // but others (e.g. Firefox) do not.
1883
- if (stackContainsErrorMessage === null) {
1884
- stackContainsErrorMessage = stackFrames[0].includes('Error message');
1885
- }
1886
-
1887
- return stackContainsErrorMessage
1888
- ? stackFrames.slice(3, 4).join('\n')
1889
- : stackFrames.slice(2, 3).join('\n');
1890
-}
1891
-
1892
-function mountRef<T>(initialValue: T): {current: T} {
1893
- const hook = mountWorkInProgressHook();
1894
- if (enableUseRefAccessWarning) {
1895
- if (__DEV__) {
1896
- // Support lazy initialization pattern shown in docs.
1897
- // We need to store the caller stack frame so that we don't warn on subsequent renders.
1898
- let hasBeenInitialized = initialValue != null;
1899
- let lazyInitGetterStack = null;
1900
- let didCheckForLazyInit = false;
1901
-
1902
- // Only warn once per component+hook.
1903
- let didWarnAboutRead = false;
1904
- let didWarnAboutWrite = false;
1905
-
1906
- let current = initialValue;
1907
- const ref = {
1908
- get current() {
1909
- if (!hasBeenInitialized) {
1910
- didCheckForLazyInit = true;
1911
- lazyInitGetterStack = getCallerStackFrame();
1912
- } else if (currentlyRenderingFiber !== null && !didWarnAboutRead) {
1913
- if (
1914
- lazyInitGetterStack === null ||
1915
- lazyInitGetterStack !== getCallerStackFrame()
1916
- ) {
1917
- didWarnAboutRead = true;
1918
- console.warn(
1919
- '%s: Unsafe read of a mutable value during render.\n\n' +
1920
- 'Reading from a ref during render is only safe if:\n' +
1921
- '1. The ref value has not been updated, or\n' +
1922
- '2. The ref holds a lazily-initialized value that is only set once.\n',
1923
- getComponentNameFromFiber(currentlyRenderingFiber) || 'Unknown',
1924
- );
1925
- }
1926
- }
1927
- return current;
1928
- },
1929
- set current(value) {
1930
- if (currentlyRenderingFiber !== null && !didWarnAboutWrite) {
1931
- if (hasBeenInitialized || !didCheckForLazyInit) {
1932
- didWarnAboutWrite = true;
1933
- console.warn(
1934
- '%s: Unsafe write of a mutable value during render.\n\n' +
1935
- 'Writing to a ref during render is only safe if the ref holds ' +
1936
- 'a lazily-initialized value that is only set once.\n',
1937
- getComponentNameFromFiber(currentlyRenderingFiber) || 'Unknown',
1938
- );
1939
- }
1940
- }
1941
-
1942
- hasBeenInitialized = true;
1943
- current = value;
1944
- },
1945
- };
1946
- Object.seal(ref);
1947
- hook.memoizedState = ref;
1948
- return ref;
1949
- } else {
1950
- const ref = {current: initialValue};
1951
- hook.memoizedState = ref;
1952
- return ref;
1953
- }
1954
- } else {
1955
- const ref = {current: initialValue};
1956
- hook.memoizedState = ref;
1957
- return ref;
1958
- }
1959
-}
1960
-
1961
-function updateRef<T>(initialValue: T): {current: T} {
1962
- const hook = updateWorkInProgressHook();
1963
- return hook.memoizedState;
1964
-}
1965
-
1966
-function mountEffectImpl(
1967
- fiberFlags,
1968
- hookFlags,
1969
- create,
1970
- deps: Array<mixed> | void | null,
1971
-): void {
1972
- const hook = mountWorkInProgressHook();
1973
- const nextDeps = deps === undefined ? null : deps;
1974
- currentlyRenderingFiber.flags |= fiberFlags;
1975
- hook.memoizedState = pushEffect(
1976
- HookHasEffect | hookFlags,
1977
- create,
1978
- undefined,
1979
- nextDeps,
1980
- );
1981
-}
1982
-
1983
-function updateEffectImpl(
1984
- fiberFlags,
1985
- hookFlags,
1986
- create,
1987
- deps: Array<mixed> | void | null,
1988
-): void {
1989
- const hook = updateWorkInProgressHook();
1990
- const nextDeps = deps === undefined ? null : deps;
1991
- let destroy = undefined;
1992
-
1993
- if (currentHook !== null) {
1994
- const prevEffect = currentHook.memoizedState;
1995
- destroy = prevEffect.destroy;
1996
- if (nextDeps !== null) {
1997
- const prevDeps = prevEffect.deps;
1998
- if (areHookInputsEqual(nextDeps, prevDeps)) {
1999
- hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps);
2000
- return;
2001
- }
2002
- }
2003
- }
2004
-
2005
- currentlyRenderingFiber.flags |= fiberFlags;
2006
-
2007
- hook.memoizedState = pushEffect(
2008
- HookHasEffect | hookFlags,
2009
- create,
2010
- destroy,
2011
- nextDeps,
2012
- );
2013
-}
2014
-
2015
-function mountEffect(
2016
- create: () => (() => void) | void,
2017
- deps: Array<mixed> | void | null,
2018
-): void {
2019
- if (
2020
- __DEV__ &&
2021
- (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode
2022
- ) {
2023
- return mountEffectImpl(
2024
- MountPassiveDevEffect | PassiveEffect | PassiveStaticEffect,
2025
- HookPassive,
2026
- create,
2027
- deps,
2028
- );
2029
- } else {
2030
- return mountEffectImpl(
2031
- PassiveEffect | PassiveStaticEffect,
2032
- HookPassive,
2033
- create,
2034
- deps,
2035
- );
2036
- }
2037
-}
2038
-
2039
-function updateEffect(
2040
- create: () => (() => void) | void,
2041
- deps: Array<mixed> | void | null,
2042
-): void {
2043
- return updateEffectImpl(PassiveEffect, HookPassive, create, deps);
2044
-}
2045
-
2046
-function useEventImpl<Args, Return, F: (...Array<Args>) => Return>(
2047
- payload: EventFunctionPayload<Args, Return, F>,
2048
-) {
2049
- currentlyRenderingFiber.flags |= UpdateEffect;
2050
- let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any);
2051
- if (componentUpdateQueue === null) {
2052
- componentUpdateQueue = createFunctionComponentUpdateQueue();
2053
- currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any);
2054
- componentUpdateQueue.events = [payload];
2055
- } else {
2056
- const events = componentUpdateQueue.events;
2057
- if (events === null) {
2058
- componentUpdateQueue.events = [payload];
2059
- } else {
2060
- events.push(payload);
2061
- }
2062
- }
2063
-}
2064
-
2065
-function mountEvent<Args, Return, F: (...Array<Args>) => Return>(
2066
- callback: F,
2067
-): F {
2068
- const hook = mountWorkInProgressHook();
2069
- const ref = {impl: callback};
2070
- hook.memoizedState = ref;
2071
- // $FlowIgnore[incompatible-return]
2072
- return function eventFn() {
2073
- if (isInvalidExecutionContextForEventFunction()) {
2074
- throw new Error(
2075
- "A function wrapped in useEvent can't be called during rendering.",
2076
- );
2077
- }
2078
- return ref.impl.apply(undefined, arguments);
2079
- };
2080
-}
2081
-
2082
-function updateEvent<Args, Return, F: (...Array<Args>) => Return>(
2083
- callback: F,
2084
-): F {
2085
- const hook = updateWorkInProgressHook();
2086
- const ref = hook.memoizedState;
2087
- useEventImpl({ref, nextImpl: callback});
2088
- // $FlowIgnore[incompatible-return]
2089
- return function eventFn() {
2090
- if (isInvalidExecutionContextForEventFunction()) {
2091
- throw new Error(
2092
- "A function wrapped in useEvent can't be called during rendering.",
2093
- );
2094
- }
2095
- return ref.impl.apply(undefined, arguments);
2096
- };
2097
-}
2098
-
2099
-function mountInsertionEffect(
2100
- create: () => (() => void) | void,
2101
- deps: Array<mixed> | void | null,
2102
-): void {
2103
- return mountEffectImpl(UpdateEffect, HookInsertion, create, deps);
2104
-}
2105
-
2106
-function updateInsertionEffect(
2107
- create: () => (() => void) | void,
2108
- deps: Array<mixed> | void | null,
2109
-): void {
2110
- return updateEffectImpl(UpdateEffect, HookInsertion, create, deps);
2111
-}
2112
-
2113
-function mountLayoutEffect(
2114
- create: () => (() => void) | void,
2115
- deps: Array<mixed> | void | null,
2116
-): void {
2117
- let fiberFlags: Flags = UpdateEffect | LayoutStaticEffect;
2118
- if (
2119
- __DEV__ &&
2120
- (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode
2121
- ) {
2122
- fiberFlags |= MountLayoutDevEffect;
2123
- }
2124
- return mountEffectImpl(fiberFlags, HookLayout, create, deps);
2125
-}
2126
-
2127
-function updateLayoutEffect(
2128
- create: () => (() => void) | void,
2129
- deps: Array<mixed> | void | null,
2130
-): void {
2131
- return updateEffectImpl(UpdateEffect, HookLayout, create, deps);
2132
-}
2133
-
2134
-function imperativeHandleEffect<T>(
2135
- create: () => T,
2136
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
2137
-) {
2138
- if (typeof ref === 'function') {
2139
- const refCallback = ref;
2140
- const inst = create();
2141
- refCallback(inst);
2142
- return () => {
2143
- refCallback(null);
2144
- };
2145
- } else if (ref !== null && ref !== undefined) {
2146
- const refObject = ref;
2147
- if (__DEV__) {
2148
- if (!refObject.hasOwnProperty('current')) {
2149
- console.error(
2150
- 'Expected useImperativeHandle() first argument to either be a ' +
2151
- 'ref callback or React.createRef() object. Instead received: %s.',
2152
- 'an object with keys {' + Object.keys(refObject).join(', ') + '}',
2153
- );
2154
- }
2155
- }
2156
- const inst = create();
2157
- refObject.current = inst;
2158
- return () => {
2159
- refObject.current = null;
2160
- };
2161
- }
2162
-}
2163
-
2164
-function mountImperativeHandle<T>(
2165
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
2166
- create: () => T,
2167
- deps: Array<mixed> | void | null,
2168
-): void {
2169
- if (__DEV__) {
2170
- if (typeof create !== 'function') {
2171
- console.error(
2172
- 'Expected useImperativeHandle() second argument to be a function ' +
2173
- 'that creates a handle. Instead received: %s.',
2174
- create !== null ? typeof create : 'null',
2175
- );
2176
- }
2177
- }
2178
-
2179
- // TODO: If deps are provided, should we skip comparing the ref itself?
2180
- const effectDeps =
2181
- deps !== null && deps !== undefined ? deps.concat([ref]) : null;
2182
-
2183
- let fiberFlags: Flags = UpdateEffect | LayoutStaticEffect;
2184
- if (
2185
- __DEV__ &&
2186
- (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode
2187
- ) {
2188
- fiberFlags |= MountLayoutDevEffect;
2189
- }
2190
- return mountEffectImpl(
2191
- fiberFlags,
2192
- HookLayout,
2193
- imperativeHandleEffect.bind(null, create, ref),
2194
- effectDeps,
2195
- );
2196
-}
2197
-
2198
-function updateImperativeHandle<T>(
2199
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
2200
- create: () => T,
2201
- deps: Array<mixed> | void | null,
2202
-): void {
2203
- if (__DEV__) {
2204
- if (typeof create !== 'function') {
2205
- console.error(
2206
- 'Expected useImperativeHandle() second argument to be a function ' +
2207
- 'that creates a handle. Instead received: %s.',
2208
- create !== null ? typeof create : 'null',
2209
- );
2210
- }
2211
- }
2212
-
2213
- // TODO: If deps are provided, should we skip comparing the ref itself?
2214
- const effectDeps =
2215
- deps !== null && deps !== undefined ? deps.concat([ref]) : null;
2216
-
2217
- return updateEffectImpl(
2218
- UpdateEffect,
2219
- HookLayout,
2220
- imperativeHandleEffect.bind(null, create, ref),
2221
- effectDeps,
2222
- );
2223
-}
2224
-
2225
-function mountDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
2226
- // This hook is normally a no-op.
2227
- // The react-debug-hooks package injects its own implementation
2228
- // so that e.g. DevTools can display custom hook values.
2229
-}
2230
-
2231
-const updateDebugValue = mountDebugValue;
2232
-
2233
-function mountCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
2234
- const hook = mountWorkInProgressHook();
2235
- const nextDeps = deps === undefined ? null : deps;
2236
- hook.memoizedState = [callback, nextDeps];
2237
- return callback;
2238
-}
2239
-
2240
-function updateCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
2241
- const hook = updateWorkInProgressHook();
2242
- const nextDeps = deps === undefined ? null : deps;
2243
- const prevState = hook.memoizedState;
2244
- if (prevState !== null) {
2245
- if (nextDeps !== null) {
2246
- const prevDeps: Array<mixed> | null = prevState[1];
2247
- if (areHookInputsEqual(nextDeps, prevDeps)) {
2248
- return prevState[0];
2249
- }
2250
- }
2251
- }
2252
- hook.memoizedState = [callback, nextDeps];
2253
- return callback;
2254
-}
2255
-
2256
-function mountMemo<T>(
2257
- nextCreate: () => T,
2258
- deps: Array<mixed> | void | null,
2259
-): T {
2260
- const hook = mountWorkInProgressHook();
2261
- const nextDeps = deps === undefined ? null : deps;
2262
- if (shouldDoubleInvokeUserFnsInHooksDEV) {
2263
- nextCreate();
2264
- }
2265
- const nextValue = nextCreate();
2266
- hook.memoizedState = [nextValue, nextDeps];
2267
- return nextValue;
2268
-}
2269
-
2270
-function updateMemo<T>(
2271
- nextCreate: () => T,
2272
- deps: Array<mixed> | void | null,
2273
-): T {
2274
- const hook = updateWorkInProgressHook();
2275
- const nextDeps = deps === undefined ? null : deps;
2276
- const prevState = hook.memoizedState;
2277
- if (prevState !== null) {
2278
- // Assume these are defined. If they're not, areHookInputsEqual will warn.
2279
- if (nextDeps !== null) {
2280
- const prevDeps: Array<mixed> | null = prevState[1];
2281
- if (areHookInputsEqual(nextDeps, prevDeps)) {
2282
- return prevState[0];
2283
- }
2284
- }
2285
- }
2286
- if (shouldDoubleInvokeUserFnsInHooksDEV) {
2287
- nextCreate();
2288
- }
2289
- const nextValue = nextCreate();
2290
- hook.memoizedState = [nextValue, nextDeps];
2291
- return nextValue;
2292
-}
2293
-
2294
-function mountDeferredValue<T>(value: T): T {
2295
- const hook = mountWorkInProgressHook();
2296
- hook.memoizedState = value;
2297
- return value;
2298
-}
2299
-
2300
-function updateDeferredValue<T>(value: T): T {
2301
- const hook = updateWorkInProgressHook();
2302
- const resolvedCurrentHook: Hook = (currentHook: any);
2303
- const prevValue: T = resolvedCurrentHook.memoizedState;
2304
- return updateDeferredValueImpl(hook, prevValue, value);
2305
-}
2306
-
2307
-function rerenderDeferredValue<T>(value: T): T {
2308
- const hook = updateWorkInProgressHook();
2309
- if (currentHook === null) {
2310
- // This is a rerender during a mount.
2311
- hook.memoizedState = value;
2312
- return value;
2313
- } else {
2314
- // This is a rerender during an update.
2315
- const prevValue: T = currentHook.memoizedState;
2316
- return updateDeferredValueImpl(hook, prevValue, value);
2317
- }
2318
-}
2319
-
2320
-function updateDeferredValueImpl<T>(hook: Hook, prevValue: T, value: T): T {
2321
- const shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes);
2322
- if (shouldDeferValue) {
2323
- // This is an urgent update. If the value has changed, keep using the
2324
- // previous value and spawn a deferred render to update it later.
2325
-
2326
- if (!is(value, prevValue)) {
2327
- // Schedule a deferred render
2328
- const deferredLane = claimNextTransitionLane();
2329
- currentlyRenderingFiber.lanes = mergeLanes(
2330
- currentlyRenderingFiber.lanes,
2331
- deferredLane,
2332
- );
2333
- markSkippedUpdateLanes(deferredLane);
2334
-
2335
- // Set this to true to indicate that the rendered value is inconsistent
2336
- // from the latest value. The name "baseState" doesn't really match how we
2337
- // use it because we're reusing a state hook field instead of creating a
2338
- // new one.
2339
- hook.baseState = true;
2340
- }
2341
-
2342
- // Reuse the previous value
2343
- return prevValue;
2344
- } else {
2345
- // This is not an urgent update, so we can use the latest value regardless
2346
- // of what it is. No need to defer it.
2347
-
2348
- // However, if we're currently inside a spawned render, then we need to mark
2349
- // this as an update to prevent the fiber from bailing out.
2350
- //
2351
- // `baseState` is true when the current value is different from the rendered
2352
- // value. The name doesn't really match how we use it because we're reusing
2353
- // a state hook field instead of creating a new one.
2354
- if (hook.baseState) {
2355
- // Flip this back to false.
2356
- hook.baseState = false;
2357
- markWorkInProgressReceivedUpdate();
2358
- }
2359
-
2360
- hook.memoizedState = value;
2361
- return value;
2362
- }
2363
-}
2364
-
2365
-function startTransition(setPending, callback, options) {
2366
- const previousPriority = getCurrentUpdatePriority();
2367
- setCurrentUpdatePriority(
2368
- higherEventPriority(previousPriority, ContinuousEventPriority),
2369
- );
2370
-
2371
- setPending(true);
2372
-
2373
- const prevTransition = ReactCurrentBatchConfig.transition;
2374
- ReactCurrentBatchConfig.transition = {};
2375
- const currentTransition = ReactCurrentBatchConfig.transition;
2376
-
2377
- if (enableTransitionTracing) {
2378
- if (options !== undefined && options.name !== undefined) {
2379
- ReactCurrentBatchConfig.transition.name = options.name;
2380
- ReactCurrentBatchConfig.transition.startTime = now();
2381
- }
2382
- }
2383
-
2384
- if (__DEV__) {
2385
- ReactCurrentBatchConfig.transition._updatedFibers = new Set();
2386
- }
2387
-
2388
- try {
2389
- setPending(false);
2390
- callback();
2391
- } finally {
2392
- setCurrentUpdatePriority(previousPriority);
2393
-
2394
- ReactCurrentBatchConfig.transition = prevTransition;
2395
-
2396
- if (__DEV__) {
2397
- if (prevTransition === null && currentTransition._updatedFibers) {
2398
- const updatedFibersCount = currentTransition._updatedFibers.size;
2399
- if (updatedFibersCount > 10) {
2400
- console.warn(
2401
- 'Detected a large number of updates inside startTransition. ' +
2402
- 'If this is due to a subscription please re-write it to use React provided hooks. ' +
2403
- 'Otherwise concurrent mode guarantees are off the table.',
2404
- );
2405
- }
2406
- currentTransition._updatedFibers.clear();
2407
- }
2408
- }
2409
- }
2410
-}
2411
-
2412
-function mountTransition(): [
2413
- boolean,
2414
- (callback: () => void, options?: StartTransitionOptions) => void,
2415
-] {
2416
- const [isPending, setPending] = mountState(false);
2417
- // The `start` method never changes.
2418
- const start = startTransition.bind(null, setPending);
2419
- const hook = mountWorkInProgressHook();
2420
- hook.memoizedState = start;
2421
- return [isPending, start];
2422
-}
2423
-
2424
-function updateTransition(): [
2425
- boolean,
2426
- (callback: () => void, options?: StartTransitionOptions) => void,
2427
-] {
2428
- const [isPending] = updateState(false);
2429
- const hook = updateWorkInProgressHook();
2430
- const start = hook.memoizedState;
2431
- return [isPending, start];
2432
-}
2433
-
2434
-function rerenderTransition(): [
2435
- boolean,
2436
- (callback: () => void, options?: StartTransitionOptions) => void,
2437
-] {
2438
- const [isPending] = rerenderState(false);
2439
- const hook = updateWorkInProgressHook();
2440
- const start = hook.memoizedState;
2441
- return [isPending, start];
2442
-}
2443
-
2444
-function mountId(): string {
2445
- const hook = mountWorkInProgressHook();
2446
-
2447
- const root = ((getWorkInProgressRoot(): any): FiberRoot);
2448
- // TODO: In Fizz, id generation is specific to each server config. Maybe we
2449
- // should do this in Fiber, too? Deferring this decision for now because
2450
- // there's no other place to store the prefix except for an internal field on
2451
- // the public createRoot object, which the fiber tree does not currently have
2452
- // a reference to.
2453
- const identifierPrefix = root.identifierPrefix;
2454
-
2455
- let id;
2456
- if (getIsHydrating()) {
2457
- const treeId = getTreeId();
2458
-
2459
- // Use a captial R prefix for server-generated ids.
2460
- id = ':' + identifierPrefix + 'R' + treeId;
2461
-
2462
- // Unless this is the first id at this level, append a number at the end
2463
- // that represents the position of this useId hook among all the useId
2464
- // hooks for this fiber.
2465
- const localId = localIdCounter++;
2466
- if (localId > 0) {
2467
- id += 'H' + localId.toString(32);
2468
- }
2469
-
2470
- id += ':';
2471
- } else {
2472
- // Use a lowercase r prefix for client-generated ids.
2473
- const globalClientId = globalClientIdCounter++;
2474
- id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':';
2475
- }
2476
-
2477
- hook.memoizedState = id;
2478
- return id;
2479
-}
2480
-
2481
-function updateId(): string {
2482
- const hook = updateWorkInProgressHook();
2483
- const id: string = hook.memoizedState;
2484
- return id;
2485
-}
2486
-
2487
-function mountRefresh() {
2488
- const hook = mountWorkInProgressHook();
2489
- const refresh = (hook.memoizedState = refreshCache.bind(
2490
- null,
2491
- currentlyRenderingFiber,
2492
- ));
2493
- return refresh;
2494
-}
2495
-
2496
-function updateRefresh() {
2497
- const hook = updateWorkInProgressHook();
2498
- return hook.memoizedState;
2499
-}
2500
-
2501
-function refreshCache<T>(fiber: Fiber, seedKey: ?() => T, seedValue: T) {
2502
- if (!enableCache) {
2503
- return;
2504
- }
2505
- // TODO: Does Cache work in legacy mode? Should decide and write a test.
2506
- // TODO: Consider warning if the refresh is at discrete priority, or if we
2507
- // otherwise suspect that it wasn't batched properly.
2508
- let provider = fiber.return;
2509
- while (provider !== null) {
2510
- switch (provider.tag) {
2511
- case CacheComponent:
2512
- case HostRoot: {
2513
- // Schedule an update on the cache boundary to trigger a refresh.
2514
- const lane = requestUpdateLane(provider);
2515
- const eventTime = requestEventTime();
2516
- const refreshUpdate = createLegacyQueueUpdate(eventTime, lane);
2517
- const root = enqueueLegacyQueueUpdate(provider, refreshUpdate, lane);
2518
- if (root !== null) {
2519
- scheduleUpdateOnFiber(root, provider, lane, eventTime);
2520
- entangleLegacyQueueTransitions(root, provider, lane);
2521
- }
2522
-
2523
- // TODO: If a refresh never commits, the new cache created here must be
2524
- // released. A simple case is start refreshing a cache boundary, but then
2525
- // unmount that boundary before the refresh completes.
2526
- const seededCache = createCache();
2527
- if (seedKey !== null && seedKey !== undefined && root !== null) {
2528
- if (enableLegacyCache) {
2529
- // Seed the cache with the value passed by the caller. This could be
2530
- // from a server mutation, or it could be a streaming response.
2531
- seededCache.data.set(seedKey, seedValue);
2532
- } else {
2533
- if (__DEV__) {
2534
- console.error(
2535
- 'The seed argument is not enabled outside experimental channels.',
2536
- );
2537
- }
2538
- }
2539
- }
2540
-
2541
- const payload = {
2542
- cache: seededCache,
2543
- };
2544
- refreshUpdate.payload = payload;
2545
- return;
2546
- }
2547
- }
2548
- provider = provider.return;
2549
- }
2550
- // TODO: Warn if unmounted?
2551
-}
2552
-
2553
-function dispatchReducerAction<S, A>(
2554
- fiber: Fiber,
2555
- queue: UpdateQueue<S, A>,
2556
- action: A,
2557
-) {
2558
- if (__DEV__) {
2559
- if (typeof arguments[3] === 'function') {
2560
- console.error(
2561
- "State updates from the useState() and useReducer() Hooks don't support the " +
2562
- 'second callback argument. To execute a side effect after ' +
2563
- 'rendering, declare it in the component body with useEffect().',
2564
- );
2565
- }
2566
- }
2567
-
2568
- const lane = requestUpdateLane(fiber);
2569
-
2570
- const update: Update<S, A> = {
2571
- lane,
2572
- action,
2573
- hasEagerState: false,
2574
- eagerState: null,
2575
- next: (null: any),
2576
- };
2577
-
2578
- if (isRenderPhaseUpdate(fiber)) {
2579
- enqueueRenderPhaseUpdate(queue, update);
2580
- } else {
2581
- const root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
2582
- if (root !== null) {
2583
- const eventTime = requestEventTime();
2584
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
2585
- entangleTransitionUpdate(root, queue, lane);
2586
- }
2587
- }
2588
-
2589
- markUpdateInDevTools(fiber, lane, action);
2590
-}
2591
-
2592
-function dispatchSetState<S, A>(
2593
- fiber: Fiber,
2594
- queue: UpdateQueue<S, A>,
2595
- action: A,
2596
-) {
2597
- if (__DEV__) {
2598
- if (typeof arguments[3] === 'function') {
2599
- console.error(
2600
- "State updates from the useState() and useReducer() Hooks don't support the " +
2601
- 'second callback argument. To execute a side effect after ' +
2602
- 'rendering, declare it in the component body with useEffect().',
2603
- );
2604
- }
2605
- }
2606
-
2607
- const lane = requestUpdateLane(fiber);
2608
-
2609
- const update: Update<S, A> = {
2610
- lane,
2611
- action,
2612
- hasEagerState: false,
2613
- eagerState: null,
2614
- next: (null: any),
2615
- };
2616
-
2617
- if (isRenderPhaseUpdate(fiber)) {
2618
- enqueueRenderPhaseUpdate(queue, update);
2619
- } else {
2620
- const alternate = fiber.alternate;
2621
- if (
2622
- fiber.lanes === NoLanes &&
2623
- (alternate === null || alternate.lanes === NoLanes)
2624
- ) {
2625
- // The queue is currently empty, which means we can eagerly compute the
2626
- // next state before entering the render phase. If the new state is the
2627
- // same as the current state, we may be able to bail out entirely.
2628
- const lastRenderedReducer = queue.lastRenderedReducer;
2629
- if (lastRenderedReducer !== null) {
2630
- let prevDispatcher;
2631
- if (__DEV__) {
2632
- prevDispatcher = ReactCurrentDispatcher.current;
2633
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
2634
- }
2635
- try {
2636
- const currentState: S = (queue.lastRenderedState: any);
2637
- const eagerState = lastRenderedReducer(currentState, action);
2638
- // Stash the eagerly computed state, and the reducer used to compute
2639
- // it, on the update object. If the reducer hasn't changed by the
2640
- // time we enter the render phase, then the eager state can be used
2641
- // without calling the reducer again.
2642
- update.hasEagerState = true;
2643
- update.eagerState = eagerState;
2644
- if (is(eagerState, currentState)) {
2645
- // Fast path. We can bail out without scheduling React to re-render.
2646
- // It's still possible that we'll need to rebase this update later,
2647
- // if the component re-renders for a different reason and by that
2648
- // time the reducer has changed.
2649
- // TODO: Do we still need to entangle transitions in this case?
2650
- enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update);
2651
- return;
2652
- }
2653
- } catch (error) {
2654
- // Suppress the error. It will throw again in the render phase.
2655
- } finally {
2656
- if (__DEV__) {
2657
- ReactCurrentDispatcher.current = prevDispatcher;
2658
- }
2659
- }
2660
- }
2661
- }
2662
-
2663
- const root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
2664
- if (root !== null) {
2665
- const eventTime = requestEventTime();
2666
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
2667
- entangleTransitionUpdate(root, queue, lane);
2668
- }
2669
- }
2670
-
2671
- markUpdateInDevTools(fiber, lane, action);
2672
-}
2673
-
2674
-function isRenderPhaseUpdate(fiber: Fiber) {
2675
- const alternate = fiber.alternate;
2676
- return (
2677
- fiber === currentlyRenderingFiber ||
2678
- (alternate !== null && alternate === currentlyRenderingFiber)
2679
- );
2680
-}
2681
-
2682
-function enqueueRenderPhaseUpdate<S, A>(
2683
- queue: UpdateQueue<S, A>,
2684
- update: Update<S, A>,
2685
-) {
2686
- // This is a render phase update. Stash it in a lazily-created map of
2687
- // queue -> linked list of updates. After this render pass, we'll restart
2688
- // and apply the stashed updates on top of the work-in-progress hook.
2689
- didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
2690
- const pending = queue.pending;
2691
- if (pending === null) {
2692
- // This is the first update. Create a circular list.
2693
- update.next = update;
2694
- } else {
2695
- update.next = pending.next;
2696
- pending.next = update;
2697
- }
2698
- queue.pending = update;
2699
-}
2700
-
2701
-// TODO: Move to ReactFiberConcurrentUpdates?
2702
-function entangleTransitionUpdate<S, A>(
2703
- root: FiberRoot,
2704
- queue: UpdateQueue<S, A>,
2705
- lane: Lane,
2706
-) {
2707
- if (isTransitionLane(lane)) {
2708
- let queueLanes = queue.lanes;
2709
-
2710
- // If any entangled lanes are no longer pending on the root, then they
2711
- // must have finished. We can remove them from the shared queue, which
2712
- // represents a superset of the actually pending lanes. In some cases we
2713
- // may entangle more than we need to, but that's OK. In fact it's worse if
2714
- // we *don't* entangle when we should.
2715
- queueLanes = intersectLanes(queueLanes, root.pendingLanes);
2716
-
2717
- // Entangle the new transition lane with the other transition lanes.
2718
- const newQueueLanes = mergeLanes(queueLanes, lane);
2719
- queue.lanes = newQueueLanes;
2720
- // Even if queue.lanes already include lane, we don't know for certain if
2721
- // the lane finished since the last time we entangled it. So we need to
2722
- // entangle it again, just to be sure.
2723
- markRootEntangled(root, newQueueLanes);
2724
- }
2725
-}
2726
-
2727
-function markUpdateInDevTools<A>(fiber, lane, action: A) {
2728
- if (__DEV__) {
2729
- if (enableDebugTracing) {
2730
- if (fiber.mode & DebugTracingMode) {
2731
- const name = getComponentNameFromFiber(fiber) || 'Unknown';
2732
- logStateUpdateScheduled(name, lane, action);
2733
- }
2734
- }
2735
- }
2736
-
2737
- if (enableSchedulingProfiler) {
2738
- markStateUpdateScheduled(fiber, lane);
2739
- }
2740
-}
2741
-
2742
-export const ContextOnlyDispatcher: Dispatcher = {
2743
- readContext,
2744
-
2745
- useCallback: throwInvalidHookError,
2746
- useContext: throwInvalidHookError,
2747
- useEffect: throwInvalidHookError,
2748
- useImperativeHandle: throwInvalidHookError,
2749
- useInsertionEffect: throwInvalidHookError,
2750
- useLayoutEffect: throwInvalidHookError,
2751
- useMemo: throwInvalidHookError,
2752
- useReducer: throwInvalidHookError,
2753
- useRef: throwInvalidHookError,
2754
- useState: throwInvalidHookError,
2755
- useDebugValue: throwInvalidHookError,
2756
- useDeferredValue: throwInvalidHookError,
2757
- useTransition: throwInvalidHookError,
2758
- useMutableSource: throwInvalidHookError,
2759
- useSyncExternalStore: throwInvalidHookError,
2760
- useId: throwInvalidHookError,
2761
-
2762
- unstable_isNewReconciler: enableNewReconciler,
2763
-};
2764
-if (enableCache) {
2765
- (ContextOnlyDispatcher: Dispatcher).useCacheRefresh = throwInvalidHookError;
2766
-}
2767
-if (enableUseHook) {
2768
- (ContextOnlyDispatcher: Dispatcher).use = throwInvalidHookError;
2769
-}
2770
-if (enableUseMemoCacheHook) {
2771
- (ContextOnlyDispatcher: Dispatcher).useMemoCache = throwInvalidHookError;
2772
-}
2773
-if (enableUseEventHook) {
2774
- (ContextOnlyDispatcher: Dispatcher).useEvent = throwInvalidHookError;
2775
-}
2776
-
2777
-const HooksDispatcherOnMount: Dispatcher = {
2778
- readContext,
2779
-
2780
- useCallback: mountCallback,
2781
- useContext: readContext,
2782
- useEffect: mountEffect,
2783
- useImperativeHandle: mountImperativeHandle,
2784
- useLayoutEffect: mountLayoutEffect,
2785
- useInsertionEffect: mountInsertionEffect,
2786
- useMemo: mountMemo,
2787
- useReducer: mountReducer,
2788
- useRef: mountRef,
2789
- useState: mountState,
2790
- useDebugValue: mountDebugValue,
2791
- useDeferredValue: mountDeferredValue,
2792
- useTransition: mountTransition,
2793
- useMutableSource: mountMutableSource,
2794
- useSyncExternalStore: mountSyncExternalStore,
2795
- useId: mountId,
2796
-
2797
- unstable_isNewReconciler: enableNewReconciler,
2798
-};
2799
-if (enableCache) {
2800
- // $FlowFixMe[escaped-generic] discovered when updating Flow
2801
- (HooksDispatcherOnMount: Dispatcher).useCacheRefresh = mountRefresh;
2802
-}
2803
-if (enableUseHook) {
2804
- (HooksDispatcherOnMount: Dispatcher).use = use;
2805
-}
2806
-if (enableUseMemoCacheHook) {
2807
- (HooksDispatcherOnMount: Dispatcher).useMemoCache = useMemoCache;
2808
-}
2809
-if (enableUseEventHook) {
2810
- (HooksDispatcherOnMount: Dispatcher).useEvent = mountEvent;
2811
-}
2812
-const HooksDispatcherOnUpdate: Dispatcher = {
2813
- readContext,
2814
-
2815
- useCallback: updateCallback,
2816
- useContext: readContext,
2817
- useEffect: updateEffect,
2818
- useImperativeHandle: updateImperativeHandle,
2819
- useInsertionEffect: updateInsertionEffect,
2820
- useLayoutEffect: updateLayoutEffect,
2821
- useMemo: updateMemo,
2822
- useReducer: updateReducer,
2823
- useRef: updateRef,
2824
- useState: updateState,
2825
- useDebugValue: updateDebugValue,
2826
- useDeferredValue: updateDeferredValue,
2827
- useTransition: updateTransition,
2828
- useMutableSource: updateMutableSource,
2829
- useSyncExternalStore: updateSyncExternalStore,
2830
- useId: updateId,
2831
-
2832
- unstable_isNewReconciler: enableNewReconciler,
2833
-};
2834
-if (enableCache) {
2835
- (HooksDispatcherOnUpdate: Dispatcher).useCacheRefresh = updateRefresh;
2836
-}
2837
-if (enableUseMemoCacheHook) {
2838
- (HooksDispatcherOnUpdate: Dispatcher).useMemoCache = useMemoCache;
2839
-}
2840
-if (enableUseHook) {
2841
- (HooksDispatcherOnUpdate: Dispatcher).use = use;
2842
-}
2843
-if (enableUseEventHook) {
2844
- (HooksDispatcherOnUpdate: Dispatcher).useEvent = updateEvent;
2845
-}
2846
-
2847
-const HooksDispatcherOnRerender: Dispatcher = {
2848
- readContext,
2849
-
2850
- useCallback: updateCallback,
2851
- useContext: readContext,
2852
- useEffect: updateEffect,
2853
- useImperativeHandle: updateImperativeHandle,
2854
- useInsertionEffect: updateInsertionEffect,
2855
- useLayoutEffect: updateLayoutEffect,
2856
- useMemo: updateMemo,
2857
- useReducer: rerenderReducer,
2858
- useRef: updateRef,
2859
- useState: rerenderState,
2860
- useDebugValue: updateDebugValue,
2861
- useDeferredValue: rerenderDeferredValue,
2862
- useTransition: rerenderTransition,
2863
- useMutableSource: updateMutableSource,
2864
- useSyncExternalStore: updateSyncExternalStore,
2865
- useId: updateId,
2866
-
2867
- unstable_isNewReconciler: enableNewReconciler,
2868
-};
2869
-if (enableCache) {
2870
- (HooksDispatcherOnRerender: Dispatcher).useCacheRefresh = updateRefresh;
2871
-}
2872
-if (enableUseHook) {
2873
- (HooksDispatcherOnRerender: Dispatcher).use = use;
2874
-}
2875
-if (enableUseMemoCacheHook) {
2876
- (HooksDispatcherOnRerender: Dispatcher).useMemoCache = useMemoCache;
2877
-}
2878
-if (enableUseEventHook) {
2879
- (HooksDispatcherOnRerender: Dispatcher).useEvent = updateEvent;
2880
-}
2881
-
2882
-let HooksDispatcherOnMountInDEV: Dispatcher | null = null;
2883
-let HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher | null = null;
2884
-let HooksDispatcherOnUpdateInDEV: Dispatcher | null = null;
2885
-let HooksDispatcherOnRerenderInDEV: Dispatcher | null = null;
2886
-let InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher | null = null;
2887
-let InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher | null = null;
2888
-let InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher | null = null;
2889
-
2890
-if (__DEV__) {
2891
- const warnInvalidContextAccess = () => {
2892
- console.error(
2893
- 'Context can only be read while React is rendering. ' +
2894
- 'In classes, you can read it in the render method or getDerivedStateFromProps. ' +
2895
- 'In function components, you can read it directly in the function body, but not ' +
2896
- 'inside Hooks like useReducer() or useMemo().',
2897
- );
2898
- };
2899
-
2900
- const warnInvalidHookAccess = () => {
2901
- console.error(
2902
- 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' +
2903
- 'You can only call Hooks at the top level of your React function. ' +
2904
- 'For more information, see ' +
2905
- 'https://reactjs.org/link/rules-of-hooks',
2906
- );
2907
- };
2908
-
2909
- HooksDispatcherOnMountInDEV = {
2910
- readContext<T>(context: ReactContext<T>): T {
2911
- return readContext(context);
2912
- },
2913
- useCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
2914
- currentHookNameInDev = 'useCallback';
2915
- mountHookTypesDev();
2916
- checkDepsAreArrayDev(deps);
2917
- return mountCallback(callback, deps);
2918
- },
2919
- useContext<T>(context: ReactContext<T>): T {
2920
- currentHookNameInDev = 'useContext';
2921
- mountHookTypesDev();
2922
- return readContext(context);
2923
- },
2924
- useEffect(
2925
- create: () => (() => void) | void,
2926
- deps: Array<mixed> | void | null,
2927
- ): void {
2928
- currentHookNameInDev = 'useEffect';
2929
- mountHookTypesDev();
2930
- checkDepsAreArrayDev(deps);
2931
- return mountEffect(create, deps);
2932
- },
2933
- useImperativeHandle<T>(
2934
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
2935
- create: () => T,
2936
- deps: Array<mixed> | void | null,
2937
- ): void {
2938
- currentHookNameInDev = 'useImperativeHandle';
2939
- mountHookTypesDev();
2940
- checkDepsAreArrayDev(deps);
2941
- return mountImperativeHandle(ref, create, deps);
2942
- },
2943
- useInsertionEffect(
2944
- create: () => (() => void) | void,
2945
- deps: Array<mixed> | void | null,
2946
- ): void {
2947
- currentHookNameInDev = 'useInsertionEffect';
2948
- mountHookTypesDev();
2949
- checkDepsAreArrayDev(deps);
2950
- return mountInsertionEffect(create, deps);
2951
- },
2952
- useLayoutEffect(
2953
- create: () => (() => void) | void,
2954
- deps: Array<mixed> | void | null,
2955
- ): void {
2956
- currentHookNameInDev = 'useLayoutEffect';
2957
- mountHookTypesDev();
2958
- checkDepsAreArrayDev(deps);
2959
- return mountLayoutEffect(create, deps);
2960
- },
2961
- useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T {
2962
- currentHookNameInDev = 'useMemo';
2963
- mountHookTypesDev();
2964
- checkDepsAreArrayDev(deps);
2965
- const prevDispatcher = ReactCurrentDispatcher.current;
2966
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
2967
- try {
2968
- return mountMemo(create, deps);
2969
- } finally {
2970
- ReactCurrentDispatcher.current = prevDispatcher;
2971
- }
2972
- },
2973
- useReducer<S, I, A>(
2974
- reducer: (S, A) => S,
2975
- initialArg: I,
2976
- init?: I => S,
2977
- ): [S, Dispatch<A>] {
2978
- currentHookNameInDev = 'useReducer';
2979
- mountHookTypesDev();
2980
- const prevDispatcher = ReactCurrentDispatcher.current;
2981
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
2982
- try {
2983
- return mountReducer(reducer, initialArg, init);
2984
- } finally {
2985
- ReactCurrentDispatcher.current = prevDispatcher;
2986
- }
2987
- },
2988
- useRef<T>(initialValue: T): {current: T} {
2989
- currentHookNameInDev = 'useRef';
2990
- mountHookTypesDev();
2991
- return mountRef(initialValue);
2992
- },
2993
- useState<S>(
2994
- initialState: (() => S) | S,
2995
- ): [S, Dispatch<BasicStateAction<S>>] {
2996
- currentHookNameInDev = 'useState';
2997
- mountHookTypesDev();
2998
- const prevDispatcher = ReactCurrentDispatcher.current;
2999
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
3000
- try {
3001
- return mountState(initialState);
3002
- } finally {
3003
- ReactCurrentDispatcher.current = prevDispatcher;
3004
- }
3005
- },
3006
- useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
3007
- currentHookNameInDev = 'useDebugValue';
3008
- mountHookTypesDev();
3009
- return mountDebugValue(value, formatterFn);
3010
- },
3011
- useDeferredValue<T>(value: T): T {
3012
- currentHookNameInDev = 'useDeferredValue';
3013
- mountHookTypesDev();
3014
- return mountDeferredValue(value);
3015
- },
3016
- useTransition(): [boolean, (() => void) => void] {
3017
- currentHookNameInDev = 'useTransition';
3018
- mountHookTypesDev();
3019
- return mountTransition();
3020
- },
3021
- useMutableSource<Source, Snapshot>(
3022
- source: MutableSource<Source>,
3023
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
3024
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
3025
- ): Snapshot {
3026
- currentHookNameInDev = 'useMutableSource';
3027
- mountHookTypesDev();
3028
- return mountMutableSource(source, getSnapshot, subscribe);
3029
- },
3030
- useSyncExternalStore<T>(
3031
- subscribe: (() => void) => () => void,
3032
- getSnapshot: () => T,
3033
- getServerSnapshot?: () => T,
3034
- ): T {
3035
- currentHookNameInDev = 'useSyncExternalStore';
3036
- mountHookTypesDev();
3037
- return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3038
- },
3039
- useId(): string {
3040
- currentHookNameInDev = 'useId';
3041
- mountHookTypesDev();
3042
- return mountId();
3043
- },
3044
-
3045
- unstable_isNewReconciler: enableNewReconciler,
3046
- };
3047
- if (enableCache) {
3048
- (HooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
3049
- currentHookNameInDev = 'useCacheRefresh';
3050
- mountHookTypesDev();
3051
- return mountRefresh();
3052
- };
3053
- }
3054
- if (enableUseHook) {
3055
- (HooksDispatcherOnMountInDEV: Dispatcher).use = use;
3056
- }
3057
- if (enableUseMemoCacheHook) {
3058
- (HooksDispatcherOnMountInDEV: Dispatcher).useMemoCache = useMemoCache;
3059
- }
3060
- if (enableUseEventHook) {
3061
- (HooksDispatcherOnMountInDEV: Dispatcher).useEvent = function useEvent<
3062
- Args,
3063
- Return,
3064
- F: (...Array<Args>) => Return,
3065
- >(callback: F): F {
3066
- currentHookNameInDev = 'useEvent';
3067
- mountHookTypesDev();
3068
- return mountEvent(callback);
3069
- };
3070
- }
3071
-
3072
- HooksDispatcherOnMountWithHookTypesInDEV = {
3073
- readContext<T>(context: ReactContext<T>): T {
3074
- return readContext(context);
3075
- },
3076
- useCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
3077
- currentHookNameInDev = 'useCallback';
3078
- updateHookTypesDev();
3079
- return mountCallback(callback, deps);
3080
- },
3081
- useContext<T>(context: ReactContext<T>): T {
3082
- currentHookNameInDev = 'useContext';
3083
- updateHookTypesDev();
3084
- return readContext(context);
3085
- },
3086
- useEffect(
3087
- create: () => (() => void) | void,
3088
- deps: Array<mixed> | void | null,
3089
- ): void {
3090
- currentHookNameInDev = 'useEffect';
3091
- updateHookTypesDev();
3092
- return mountEffect(create, deps);
3093
- },
3094
- useImperativeHandle<T>(
3095
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
3096
- create: () => T,
3097
- deps: Array<mixed> | void | null,
3098
- ): void {
3099
- currentHookNameInDev = 'useImperativeHandle';
3100
- updateHookTypesDev();
3101
- return mountImperativeHandle(ref, create, deps);
3102
- },
3103
- useInsertionEffect(
3104
- create: () => (() => void) | void,
3105
- deps: Array<mixed> | void | null,
3106
- ): void {
3107
- currentHookNameInDev = 'useInsertionEffect';
3108
- updateHookTypesDev();
3109
- return mountInsertionEffect(create, deps);
3110
- },
3111
- useLayoutEffect(
3112
- create: () => (() => void) | void,
3113
- deps: Array<mixed> | void | null,
3114
- ): void {
3115
- currentHookNameInDev = 'useLayoutEffect';
3116
- updateHookTypesDev();
3117
- return mountLayoutEffect(create, deps);
3118
- },
3119
- useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T {
3120
- currentHookNameInDev = 'useMemo';
3121
- updateHookTypesDev();
3122
- const prevDispatcher = ReactCurrentDispatcher.current;
3123
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
3124
- try {
3125
- return mountMemo(create, deps);
3126
- } finally {
3127
- ReactCurrentDispatcher.current = prevDispatcher;
3128
- }
3129
- },
3130
- useReducer<S, I, A>(
3131
- reducer: (S, A) => S,
3132
- initialArg: I,
3133
- init?: I => S,
3134
- ): [S, Dispatch<A>] {
3135
- currentHookNameInDev = 'useReducer';
3136
- updateHookTypesDev();
3137
- const prevDispatcher = ReactCurrentDispatcher.current;
3138
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
3139
- try {
3140
- return mountReducer(reducer, initialArg, init);
3141
- } finally {
3142
- ReactCurrentDispatcher.current = prevDispatcher;
3143
- }
3144
- },
3145
- useRef<T>(initialValue: T): {current: T} {
3146
- currentHookNameInDev = 'useRef';
3147
- updateHookTypesDev();
3148
- return mountRef(initialValue);
3149
- },
3150
- useState<S>(
3151
- initialState: (() => S) | S,
3152
- ): [S, Dispatch<BasicStateAction<S>>] {
3153
- currentHookNameInDev = 'useState';
3154
- updateHookTypesDev();
3155
- const prevDispatcher = ReactCurrentDispatcher.current;
3156
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
3157
- try {
3158
- return mountState(initialState);
3159
- } finally {
3160
- ReactCurrentDispatcher.current = prevDispatcher;
3161
- }
3162
- },
3163
- useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
3164
- currentHookNameInDev = 'useDebugValue';
3165
- updateHookTypesDev();
3166
- return mountDebugValue(value, formatterFn);
3167
- },
3168
- useDeferredValue<T>(value: T): T {
3169
- currentHookNameInDev = 'useDeferredValue';
3170
- updateHookTypesDev();
3171
- return mountDeferredValue(value);
3172
- },
3173
- useTransition(): [boolean, (() => void) => void] {
3174
- currentHookNameInDev = 'useTransition';
3175
- updateHookTypesDev();
3176
- return mountTransition();
3177
- },
3178
- useMutableSource<Source, Snapshot>(
3179
- source: MutableSource<Source>,
3180
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
3181
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
3182
- ): Snapshot {
3183
- currentHookNameInDev = 'useMutableSource';
3184
- updateHookTypesDev();
3185
- return mountMutableSource(source, getSnapshot, subscribe);
3186
- },
3187
- useSyncExternalStore<T>(
3188
- subscribe: (() => void) => () => void,
3189
- getSnapshot: () => T,
3190
- getServerSnapshot?: () => T,
3191
- ): T {
3192
- currentHookNameInDev = 'useSyncExternalStore';
3193
- updateHookTypesDev();
3194
- return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3195
- },
3196
- useId(): string {
3197
- currentHookNameInDev = 'useId';
3198
- updateHookTypesDev();
3199
- return mountId();
3200
- },
3201
-
3202
- unstable_isNewReconciler: enableNewReconciler,
3203
- };
3204
- if (enableCache) {
3205
- (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
3206
- currentHookNameInDev = 'useCacheRefresh';
3207
- updateHookTypesDev();
3208
- return mountRefresh();
3209
- };
3210
- }
3211
- if (enableUseHook) {
3212
- (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).use = use;
3213
- }
3214
- if (enableUseMemoCacheHook) {
3215
- (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useMemoCache = useMemoCache;
3216
- }
3217
- if (enableUseEventHook) {
3218
- (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useEvent = function useEvent<
3219
- Args,
3220
- Return,
3221
- F: (...Array<Args>) => Return,
3222
- >(callback: F): F {
3223
- currentHookNameInDev = 'useEvent';
3224
- updateHookTypesDev();
3225
- return mountEvent(callback);
3226
- };
3227
- }
3228
-
3229
- HooksDispatcherOnUpdateInDEV = {
3230
- readContext<T>(context: ReactContext<T>): T {
3231
- return readContext(context);
3232
- },
3233
- useCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
3234
- currentHookNameInDev = 'useCallback';
3235
- updateHookTypesDev();
3236
- return updateCallback(callback, deps);
3237
- },
3238
- useContext<T>(context: ReactContext<T>): T {
3239
- currentHookNameInDev = 'useContext';
3240
- updateHookTypesDev();
3241
- return readContext(context);
3242
- },
3243
- useEffect(
3244
- create: () => (() => void) | void,
3245
- deps: Array<mixed> | void | null,
3246
- ): void {
3247
- currentHookNameInDev = 'useEffect';
3248
- updateHookTypesDev();
3249
- return updateEffect(create, deps);
3250
- },
3251
- useImperativeHandle<T>(
3252
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
3253
- create: () => T,
3254
- deps: Array<mixed> | void | null,
3255
- ): void {
3256
- currentHookNameInDev = 'useImperativeHandle';
3257
- updateHookTypesDev();
3258
- return updateImperativeHandle(ref, create, deps);
3259
- },
3260
- useInsertionEffect(
3261
- create: () => (() => void) | void,
3262
- deps: Array<mixed> | void | null,
3263
- ): void {
3264
- currentHookNameInDev = 'useInsertionEffect';
3265
- updateHookTypesDev();
3266
- return updateInsertionEffect(create, deps);
3267
- },
3268
- useLayoutEffect(
3269
- create: () => (() => void) | void,
3270
- deps: Array<mixed> | void | null,
3271
- ): void {
3272
- currentHookNameInDev = 'useLayoutEffect';
3273
- updateHookTypesDev();
3274
- return updateLayoutEffect(create, deps);
3275
- },
3276
- useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T {
3277
- currentHookNameInDev = 'useMemo';
3278
- updateHookTypesDev();
3279
- const prevDispatcher = ReactCurrentDispatcher.current;
3280
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3281
- try {
3282
- return updateMemo(create, deps);
3283
- } finally {
3284
- ReactCurrentDispatcher.current = prevDispatcher;
3285
- }
3286
- },
3287
- useReducer<S, I, A>(
3288
- reducer: (S, A) => S,
3289
- initialArg: I,
3290
- init?: I => S,
3291
- ): [S, Dispatch<A>] {
3292
- currentHookNameInDev = 'useReducer';
3293
- updateHookTypesDev();
3294
- const prevDispatcher = ReactCurrentDispatcher.current;
3295
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3296
- try {
3297
- return updateReducer(reducer, initialArg, init);
3298
- } finally {
3299
- ReactCurrentDispatcher.current = prevDispatcher;
3300
- }
3301
- },
3302
- useRef<T>(initialValue: T): {current: T} {
3303
- currentHookNameInDev = 'useRef';
3304
- updateHookTypesDev();
3305
- return updateRef(initialValue);
3306
- },
3307
- useState<S>(
3308
- initialState: (() => S) | S,
3309
- ): [S, Dispatch<BasicStateAction<S>>] {
3310
- currentHookNameInDev = 'useState';
3311
- updateHookTypesDev();
3312
- const prevDispatcher = ReactCurrentDispatcher.current;
3313
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3314
- try {
3315
- return updateState(initialState);
3316
- } finally {
3317
- ReactCurrentDispatcher.current = prevDispatcher;
3318
- }
3319
- },
3320
- useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
3321
- currentHookNameInDev = 'useDebugValue';
3322
- updateHookTypesDev();
3323
- return updateDebugValue(value, formatterFn);
3324
- },
3325
- useDeferredValue<T>(value: T): T {
3326
- currentHookNameInDev = 'useDeferredValue';
3327
- updateHookTypesDev();
3328
- return updateDeferredValue(value);
3329
- },
3330
- useTransition(): [boolean, (() => void) => void] {
3331
- currentHookNameInDev = 'useTransition';
3332
- updateHookTypesDev();
3333
- return updateTransition();
3334
- },
3335
- useMutableSource<Source, Snapshot>(
3336
- source: MutableSource<Source>,
3337
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
3338
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
3339
- ): Snapshot {
3340
- currentHookNameInDev = 'useMutableSource';
3341
- updateHookTypesDev();
3342
- return updateMutableSource(source, getSnapshot, subscribe);
3343
- },
3344
- useSyncExternalStore<T>(
3345
- subscribe: (() => void) => () => void,
3346
- getSnapshot: () => T,
3347
- getServerSnapshot?: () => T,
3348
- ): T {
3349
- currentHookNameInDev = 'useSyncExternalStore';
3350
- updateHookTypesDev();
3351
- return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3352
- },
3353
- useId(): string {
3354
- currentHookNameInDev = 'useId';
3355
- updateHookTypesDev();
3356
- return updateId();
3357
- },
3358
-
3359
- unstable_isNewReconciler: enableNewReconciler,
3360
- };
3361
- if (enableCache) {
3362
- (HooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
3363
- currentHookNameInDev = 'useCacheRefresh';
3364
- updateHookTypesDev();
3365
- return updateRefresh();
3366
- };
3367
- }
3368
- if (enableUseHook) {
3369
- (HooksDispatcherOnUpdateInDEV: Dispatcher).use = use;
3370
- }
3371
- if (enableUseMemoCacheHook) {
3372
- (HooksDispatcherOnUpdateInDEV: Dispatcher).useMemoCache = useMemoCache;
3373
- }
3374
- if (enableUseEventHook) {
3375
- (HooksDispatcherOnUpdateInDEV: Dispatcher).useEvent = function useEvent<
3376
- Args,
3377
- Return,
3378
- F: (...Array<Args>) => Return,
3379
- >(callback: F): F {
3380
- currentHookNameInDev = 'useEvent';
3381
- updateHookTypesDev();
3382
- return updateEvent(callback);
3383
- };
3384
- }
3385
-
3386
- HooksDispatcherOnRerenderInDEV = {
3387
- readContext<T>(context: ReactContext<T>): T {
3388
- return readContext(context);
3389
- },
3390
-
3391
- useCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
3392
- currentHookNameInDev = 'useCallback';
3393
- updateHookTypesDev();
3394
- return updateCallback(callback, deps);
3395
- },
3396
- useContext<T>(context: ReactContext<T>): T {
3397
- currentHookNameInDev = 'useContext';
3398
- updateHookTypesDev();
3399
- return readContext(context);
3400
- },
3401
- useEffect(
3402
- create: () => (() => void) | void,
3403
- deps: Array<mixed> | void | null,
3404
- ): void {
3405
- currentHookNameInDev = 'useEffect';
3406
- updateHookTypesDev();
3407
- return updateEffect(create, deps);
3408
- },
3409
- useImperativeHandle<T>(
3410
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
3411
- create: () => T,
3412
- deps: Array<mixed> | void | null,
3413
- ): void {
3414
- currentHookNameInDev = 'useImperativeHandle';
3415
- updateHookTypesDev();
3416
- return updateImperativeHandle(ref, create, deps);
3417
- },
3418
- useInsertionEffect(
3419
- create: () => (() => void) | void,
3420
- deps: Array<mixed> | void | null,
3421
- ): void {
3422
- currentHookNameInDev = 'useInsertionEffect';
3423
- updateHookTypesDev();
3424
- return updateInsertionEffect(create, deps);
3425
- },
3426
- useLayoutEffect(
3427
- create: () => (() => void) | void,
3428
- deps: Array<mixed> | void | null,
3429
- ): void {
3430
- currentHookNameInDev = 'useLayoutEffect';
3431
- updateHookTypesDev();
3432
- return updateLayoutEffect(create, deps);
3433
- },
3434
- useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T {
3435
- currentHookNameInDev = 'useMemo';
3436
- updateHookTypesDev();
3437
- const prevDispatcher = ReactCurrentDispatcher.current;
3438
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
3439
- try {
3440
- return updateMemo(create, deps);
3441
- } finally {
3442
- ReactCurrentDispatcher.current = prevDispatcher;
3443
- }
3444
- },
3445
- useReducer<S, I, A>(
3446
- reducer: (S, A) => S,
3447
- initialArg: I,
3448
- init?: I => S,
3449
- ): [S, Dispatch<A>] {
3450
- currentHookNameInDev = 'useReducer';
3451
- updateHookTypesDev();
3452
- const prevDispatcher = ReactCurrentDispatcher.current;
3453
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
3454
- try {
3455
- return rerenderReducer(reducer, initialArg, init);
3456
- } finally {
3457
- ReactCurrentDispatcher.current = prevDispatcher;
3458
- }
3459
- },
3460
- useRef<T>(initialValue: T): {current: T} {
3461
- currentHookNameInDev = 'useRef';
3462
- updateHookTypesDev();
3463
- return updateRef(initialValue);
3464
- },
3465
- useState<S>(
3466
- initialState: (() => S) | S,
3467
- ): [S, Dispatch<BasicStateAction<S>>] {
3468
- currentHookNameInDev = 'useState';
3469
- updateHookTypesDev();
3470
- const prevDispatcher = ReactCurrentDispatcher.current;
3471
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
3472
- try {
3473
- return rerenderState(initialState);
3474
- } finally {
3475
- ReactCurrentDispatcher.current = prevDispatcher;
3476
- }
3477
- },
3478
- useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
3479
- currentHookNameInDev = 'useDebugValue';
3480
- updateHookTypesDev();
3481
- return updateDebugValue(value, formatterFn);
3482
- },
3483
- useDeferredValue<T>(value: T): T {
3484
- currentHookNameInDev = 'useDeferredValue';
3485
- updateHookTypesDev();
3486
- return rerenderDeferredValue(value);
3487
- },
3488
- useTransition(): [boolean, (() => void) => void] {
3489
- currentHookNameInDev = 'useTransition';
3490
- updateHookTypesDev();
3491
- return rerenderTransition();
3492
- },
3493
- useMutableSource<Source, Snapshot>(
3494
- source: MutableSource<Source>,
3495
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
3496
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
3497
- ): Snapshot {
3498
- currentHookNameInDev = 'useMutableSource';
3499
- updateHookTypesDev();
3500
- return updateMutableSource(source, getSnapshot, subscribe);
3501
- },
3502
- useSyncExternalStore<T>(
3503
- subscribe: (() => void) => () => void,
3504
- getSnapshot: () => T,
3505
- getServerSnapshot?: () => T,
3506
- ): T {
3507
- currentHookNameInDev = 'useSyncExternalStore';
3508
- updateHookTypesDev();
3509
- return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3510
- },
3511
- useId(): string {
3512
- currentHookNameInDev = 'useId';
3513
- updateHookTypesDev();
3514
- return updateId();
3515
- },
3516
-
3517
- unstable_isNewReconciler: enableNewReconciler,
3518
- };
3519
- if (enableCache) {
3520
- (HooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
3521
- currentHookNameInDev = 'useCacheRefresh';
3522
- updateHookTypesDev();
3523
- return updateRefresh();
3524
- };
3525
- }
3526
- if (enableUseHook) {
3527
- (HooksDispatcherOnRerenderInDEV: Dispatcher).use = use;
3528
- }
3529
- if (enableUseMemoCacheHook) {
3530
- (HooksDispatcherOnRerenderInDEV: Dispatcher).useMemoCache = useMemoCache;
3531
- }
3532
- if (enableUseEventHook) {
3533
- (HooksDispatcherOnRerenderInDEV: Dispatcher).useEvent = function useEvent<
3534
- Args,
3535
- Return,
3536
- F: (...Array<Args>) => Return,
3537
- >(callback: F): F {
3538
- currentHookNameInDev = 'useEvent';
3539
- updateHookTypesDev();
3540
- return updateEvent(callback);
3541
- };
3542
- }
3543
-
3544
- InvalidNestedHooksDispatcherOnMountInDEV = {
3545
- readContext<T>(context: ReactContext<T>): T {
3546
- warnInvalidContextAccess();
3547
- return readContext(context);
3548
- },
3549
- useCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
3550
- currentHookNameInDev = 'useCallback';
3551
- warnInvalidHookAccess();
3552
- mountHookTypesDev();
3553
- return mountCallback(callback, deps);
3554
- },
3555
- useContext<T>(context: ReactContext<T>): T {
3556
- currentHookNameInDev = 'useContext';
3557
- warnInvalidHookAccess();
3558
- mountHookTypesDev();
3559
- return readContext(context);
3560
- },
3561
- useEffect(
3562
- create: () => (() => void) | void,
3563
- deps: Array<mixed> | void | null,
3564
- ): void {
3565
- currentHookNameInDev = 'useEffect';
3566
- warnInvalidHookAccess();
3567
- mountHookTypesDev();
3568
- return mountEffect(create, deps);
3569
- },
3570
- useImperativeHandle<T>(
3571
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
3572
- create: () => T,
3573
- deps: Array<mixed> | void | null,
3574
- ): void {
3575
- currentHookNameInDev = 'useImperativeHandle';
3576
- warnInvalidHookAccess();
3577
- mountHookTypesDev();
3578
- return mountImperativeHandle(ref, create, deps);
3579
- },
3580
- useInsertionEffect(
3581
- create: () => (() => void) | void,
3582
- deps: Array<mixed> | void | null,
3583
- ): void {
3584
- currentHookNameInDev = 'useInsertionEffect';
3585
- warnInvalidHookAccess();
3586
- mountHookTypesDev();
3587
- return mountInsertionEffect(create, deps);
3588
- },
3589
- useLayoutEffect(
3590
- create: () => (() => void) | void,
3591
- deps: Array<mixed> | void | null,
3592
- ): void {
3593
- currentHookNameInDev = 'useLayoutEffect';
3594
- warnInvalidHookAccess();
3595
- mountHookTypesDev();
3596
- return mountLayoutEffect(create, deps);
3597
- },
3598
- useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T {
3599
- currentHookNameInDev = 'useMemo';
3600
- warnInvalidHookAccess();
3601
- mountHookTypesDev();
3602
- const prevDispatcher = ReactCurrentDispatcher.current;
3603
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
3604
- try {
3605
- return mountMemo(create, deps);
3606
- } finally {
3607
- ReactCurrentDispatcher.current = prevDispatcher;
3608
- }
3609
- },
3610
- useReducer<S, I, A>(
3611
- reducer: (S, A) => S,
3612
- initialArg: I,
3613
- init?: I => S,
3614
- ): [S, Dispatch<A>] {
3615
- currentHookNameInDev = 'useReducer';
3616
- warnInvalidHookAccess();
3617
- mountHookTypesDev();
3618
- const prevDispatcher = ReactCurrentDispatcher.current;
3619
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
3620
- try {
3621
- return mountReducer(reducer, initialArg, init);
3622
- } finally {
3623
- ReactCurrentDispatcher.current = prevDispatcher;
3624
- }
3625
- },
3626
- useRef<T>(initialValue: T): {current: T} {
3627
- currentHookNameInDev = 'useRef';
3628
- warnInvalidHookAccess();
3629
- mountHookTypesDev();
3630
- return mountRef(initialValue);
3631
- },
3632
- useState<S>(
3633
- initialState: (() => S) | S,
3634
- ): [S, Dispatch<BasicStateAction<S>>] {
3635
- currentHookNameInDev = 'useState';
3636
- warnInvalidHookAccess();
3637
- mountHookTypesDev();
3638
- const prevDispatcher = ReactCurrentDispatcher.current;
3639
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
3640
- try {
3641
- return mountState(initialState);
3642
- } finally {
3643
- ReactCurrentDispatcher.current = prevDispatcher;
3644
- }
3645
- },
3646
- useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
3647
- currentHookNameInDev = 'useDebugValue';
3648
- warnInvalidHookAccess();
3649
- mountHookTypesDev();
3650
- return mountDebugValue(value, formatterFn);
3651
- },
3652
- useDeferredValue<T>(value: T): T {
3653
- currentHookNameInDev = 'useDeferredValue';
3654
- warnInvalidHookAccess();
3655
- mountHookTypesDev();
3656
- return mountDeferredValue(value);
3657
- },
3658
- useTransition(): [boolean, (() => void) => void] {
3659
- currentHookNameInDev = 'useTransition';
3660
- warnInvalidHookAccess();
3661
- mountHookTypesDev();
3662
- return mountTransition();
3663
- },
3664
- useMutableSource<Source, Snapshot>(
3665
- source: MutableSource<Source>,
3666
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
3667
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
3668
- ): Snapshot {
3669
- currentHookNameInDev = 'useMutableSource';
3670
- warnInvalidHookAccess();
3671
- mountHookTypesDev();
3672
- return mountMutableSource(source, getSnapshot, subscribe);
3673
- },
3674
- useSyncExternalStore<T>(
3675
- subscribe: (() => void) => () => void,
3676
- getSnapshot: () => T,
3677
- getServerSnapshot?: () => T,
3678
- ): T {
3679
- currentHookNameInDev = 'useSyncExternalStore';
3680
- warnInvalidHookAccess();
3681
- mountHookTypesDev();
3682
- return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3683
- },
3684
- useId(): string {
3685
- currentHookNameInDev = 'useId';
3686
- warnInvalidHookAccess();
3687
- mountHookTypesDev();
3688
- return mountId();
3689
- },
3690
-
3691
- unstable_isNewReconciler: enableNewReconciler,
3692
- };
3693
- if (enableCache) {
3694
- (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
3695
- currentHookNameInDev = 'useCacheRefresh';
3696
- mountHookTypesDev();
3697
- return mountRefresh();
3698
- };
3699
- }
3700
- if (enableUseHook) {
3701
- (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).use = function<T>(
3702
- usable: Usable<T>,
3703
- ): T {
3704
- warnInvalidHookAccess();
3705
- return use(usable);
3706
- };
3707
- }
3708
- if (enableUseMemoCacheHook) {
3709
- (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useMemoCache = function(
3710
- size: number,
3711
- ): Array<any> {
3712
- warnInvalidHookAccess();
3713
- return useMemoCache(size);
3714
- };
3715
- }
3716
- if (enableUseEventHook) {
3717
- (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useEvent = function useEvent<
3718
- Args,
3719
- Return,
3720
- F: (...Array<Args>) => Return,
3721
- >(callback: F): F {
3722
- currentHookNameInDev = 'useEvent';
3723
- warnInvalidHookAccess();
3724
- mountHookTypesDev();
3725
- return mountEvent(callback);
3726
- };
3727
- }
3728
-
3729
- InvalidNestedHooksDispatcherOnUpdateInDEV = {
3730
- readContext<T>(context: ReactContext<T>): T {
3731
- warnInvalidContextAccess();
3732
- return readContext(context);
3733
- },
3734
- useCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
3735
- currentHookNameInDev = 'useCallback';
3736
- warnInvalidHookAccess();
3737
- updateHookTypesDev();
3738
- return updateCallback(callback, deps);
3739
- },
3740
- useContext<T>(context: ReactContext<T>): T {
3741
- currentHookNameInDev = 'useContext';
3742
- warnInvalidHookAccess();
3743
- updateHookTypesDev();
3744
- return readContext(context);
3745
- },
3746
- useEffect(
3747
- create: () => (() => void) | void,
3748
- deps: Array<mixed> | void | null,
3749
- ): void {
3750
- currentHookNameInDev = 'useEffect';
3751
- warnInvalidHookAccess();
3752
- updateHookTypesDev();
3753
- return updateEffect(create, deps);
3754
- },
3755
- useImperativeHandle<T>(
3756
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
3757
- create: () => T,
3758
- deps: Array<mixed> | void | null,
3759
- ): void {
3760
- currentHookNameInDev = 'useImperativeHandle';
3761
- warnInvalidHookAccess();
3762
- updateHookTypesDev();
3763
- return updateImperativeHandle(ref, create, deps);
3764
- },
3765
- useInsertionEffect(
3766
- create: () => (() => void) | void,
3767
- deps: Array<mixed> | void | null,
3768
- ): void {
3769
- currentHookNameInDev = 'useInsertionEffect';
3770
- warnInvalidHookAccess();
3771
- updateHookTypesDev();
3772
- return updateInsertionEffect(create, deps);
3773
- },
3774
- useLayoutEffect(
3775
- create: () => (() => void) | void,
3776
- deps: Array<mixed> | void | null,
3777
- ): void {
3778
- currentHookNameInDev = 'useLayoutEffect';
3779
- warnInvalidHookAccess();
3780
- updateHookTypesDev();
3781
- return updateLayoutEffect(create, deps);
3782
- },
3783
- useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T {
3784
- currentHookNameInDev = 'useMemo';
3785
- warnInvalidHookAccess();
3786
- updateHookTypesDev();
3787
- const prevDispatcher = ReactCurrentDispatcher.current;
3788
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3789
- try {
3790
- return updateMemo(create, deps);
3791
- } finally {
3792
- ReactCurrentDispatcher.current = prevDispatcher;
3793
- }
3794
- },
3795
- useReducer<S, I, A>(
3796
- reducer: (S, A) => S,
3797
- initialArg: I,
3798
- init?: I => S,
3799
- ): [S, Dispatch<A>] {
3800
- currentHookNameInDev = 'useReducer';
3801
- warnInvalidHookAccess();
3802
- updateHookTypesDev();
3803
- const prevDispatcher = ReactCurrentDispatcher.current;
3804
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3805
- try {
3806
- return updateReducer(reducer, initialArg, init);
3807
- } finally {
3808
- ReactCurrentDispatcher.current = prevDispatcher;
3809
- }
3810
- },
3811
- useRef<T>(initialValue: T): {current: T} {
3812
- currentHookNameInDev = 'useRef';
3813
- warnInvalidHookAccess();
3814
- updateHookTypesDev();
3815
- return updateRef(initialValue);
3816
- },
3817
- useState<S>(
3818
- initialState: (() => S) | S,
3819
- ): [S, Dispatch<BasicStateAction<S>>] {
3820
- currentHookNameInDev = 'useState';
3821
- warnInvalidHookAccess();
3822
- updateHookTypesDev();
3823
- const prevDispatcher = ReactCurrentDispatcher.current;
3824
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3825
- try {
3826
- return updateState(initialState);
3827
- } finally {
3828
- ReactCurrentDispatcher.current = prevDispatcher;
3829
- }
3830
- },
3831
- useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
3832
- currentHookNameInDev = 'useDebugValue';
3833
- warnInvalidHookAccess();
3834
- updateHookTypesDev();
3835
- return updateDebugValue(value, formatterFn);
3836
- },
3837
- useDeferredValue<T>(value: T): T {
3838
- currentHookNameInDev = 'useDeferredValue';
3839
- warnInvalidHookAccess();
3840
- updateHookTypesDev();
3841
- return updateDeferredValue(value);
3842
- },
3843
- useTransition(): [boolean, (() => void) => void] {
3844
- currentHookNameInDev = 'useTransition';
3845
- warnInvalidHookAccess();
3846
- updateHookTypesDev();
3847
- return updateTransition();
3848
- },
3849
- useMutableSource<Source, Snapshot>(
3850
- source: MutableSource<Source>,
3851
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
3852
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
3853
- ): Snapshot {
3854
- currentHookNameInDev = 'useMutableSource';
3855
- warnInvalidHookAccess();
3856
- updateHookTypesDev();
3857
- return updateMutableSource(source, getSnapshot, subscribe);
3858
- },
3859
- useSyncExternalStore<T>(
3860
- subscribe: (() => void) => () => void,
3861
- getSnapshot: () => T,
3862
- getServerSnapshot?: () => T,
3863
- ): T {
3864
- currentHookNameInDev = 'useSyncExternalStore';
3865
- warnInvalidHookAccess();
3866
- updateHookTypesDev();
3867
- return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3868
- },
3869
- useId(): string {
3870
- currentHookNameInDev = 'useId';
3871
- warnInvalidHookAccess();
3872
- updateHookTypesDev();
3873
- return updateId();
3874
- },
3875
-
3876
- unstable_isNewReconciler: enableNewReconciler,
3877
- };
3878
- if (enableCache) {
3879
- (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
3880
- currentHookNameInDev = 'useCacheRefresh';
3881
- updateHookTypesDev();
3882
- return updateRefresh();
3883
- };
3884
- }
3885
- if (enableUseHook) {
3886
- (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).use = function<T>(
3887
- usable: Usable<T>,
3888
- ): T {
3889
- warnInvalidHookAccess();
3890
- return use(usable);
3891
- };
3892
- }
3893
- if (enableUseMemoCacheHook) {
3894
- (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useMemoCache = function(
3895
- size: number,
3896
- ): Array<any> {
3897
- warnInvalidHookAccess();
3898
- return useMemoCache(size);
3899
- };
3900
- }
3901
- if (enableUseEventHook) {
3902
- (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useEvent = function useEvent<
3903
- Args,
3904
- Return,
3905
- F: (...Array<Args>) => Return,
3906
- >(callback: F): F {
3907
- currentHookNameInDev = 'useEvent';
3908
- warnInvalidHookAccess();
3909
- updateHookTypesDev();
3910
- return updateEvent(callback);
3911
- };
3912
- }
3913
-
3914
- InvalidNestedHooksDispatcherOnRerenderInDEV = {
3915
- readContext<T>(context: ReactContext<T>): T {
3916
- warnInvalidContextAccess();
3917
- return readContext(context);
3918
- },
3919
-
3920
- useCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
3921
- currentHookNameInDev = 'useCallback';
3922
- warnInvalidHookAccess();
3923
- updateHookTypesDev();
3924
- return updateCallback(callback, deps);
3925
- },
3926
- useContext<T>(context: ReactContext<T>): T {
3927
- currentHookNameInDev = 'useContext';
3928
- warnInvalidHookAccess();
3929
- updateHookTypesDev();
3930
- return readContext(context);
3931
- },
3932
- useEffect(
3933
- create: () => (() => void) | void,
3934
- deps: Array<mixed> | void | null,
3935
- ): void {
3936
- currentHookNameInDev = 'useEffect';
3937
- warnInvalidHookAccess();
3938
- updateHookTypesDev();
3939
- return updateEffect(create, deps);
3940
- },
3941
- useImperativeHandle<T>(
3942
- ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
3943
- create: () => T,
3944
- deps: Array<mixed> | void | null,
3945
- ): void {
3946
- currentHookNameInDev = 'useImperativeHandle';
3947
- warnInvalidHookAccess();
3948
- updateHookTypesDev();
3949
- return updateImperativeHandle(ref, create, deps);
3950
- },
3951
- useInsertionEffect(
3952
- create: () => (() => void) | void,
3953
- deps: Array<mixed> | void | null,
3954
- ): void {
3955
- currentHookNameInDev = 'useInsertionEffect';
3956
- warnInvalidHookAccess();
3957
- updateHookTypesDev();
3958
- return updateInsertionEffect(create, deps);
3959
- },
3960
- useLayoutEffect(
3961
- create: () => (() => void) | void,
3962
- deps: Array<mixed> | void | null,
3963
- ): void {
3964
- currentHookNameInDev = 'useLayoutEffect';
3965
- warnInvalidHookAccess();
3966
- updateHookTypesDev();
3967
- return updateLayoutEffect(create, deps);
3968
- },
3969
- useMemo<T>(create: () => T, deps: Array<mixed> | void | null): T {
3970
- currentHookNameInDev = 'useMemo';
3971
- warnInvalidHookAccess();
3972
- updateHookTypesDev();
3973
- const prevDispatcher = ReactCurrentDispatcher.current;
3974
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3975
- try {
3976
- return updateMemo(create, deps);
3977
- } finally {
3978
- ReactCurrentDispatcher.current = prevDispatcher;
3979
- }
3980
- },
3981
- useReducer<S, I, A>(
3982
- reducer: (S, A) => S,
3983
- initialArg: I,
3984
- init?: I => S,
3985
- ): [S, Dispatch<A>] {
3986
- currentHookNameInDev = 'useReducer';
3987
- warnInvalidHookAccess();
3988
- updateHookTypesDev();
3989
- const prevDispatcher = ReactCurrentDispatcher.current;
3990
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
3991
- try {
3992
- return rerenderReducer(reducer, initialArg, init);
3993
- } finally {
3994
- ReactCurrentDispatcher.current = prevDispatcher;
3995
- }
3996
- },
3997
- useRef<T>(initialValue: T): {current: T} {
3998
- currentHookNameInDev = 'useRef';
3999
- warnInvalidHookAccess();
4000
- updateHookTypesDev();
4001
- return updateRef(initialValue);
4002
- },
4003
- useState<S>(
4004
- initialState: (() => S) | S,
4005
- ): [S, Dispatch<BasicStateAction<S>>] {
4006
- currentHookNameInDev = 'useState';
4007
- warnInvalidHookAccess();
4008
- updateHookTypesDev();
4009
- const prevDispatcher = ReactCurrentDispatcher.current;
4010
- ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
4011
- try {
4012
- return rerenderState(initialState);
4013
- } finally {
4014
- ReactCurrentDispatcher.current = prevDispatcher;
4015
- }
4016
- },
4017
- useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void {
4018
- currentHookNameInDev = 'useDebugValue';
4019
- warnInvalidHookAccess();
4020
- updateHookTypesDev();
4021
- return updateDebugValue(value, formatterFn);
4022
- },
4023
- useDeferredValue<T>(value: T): T {
4024
- currentHookNameInDev = 'useDeferredValue';
4025
- warnInvalidHookAccess();
4026
- updateHookTypesDev();
4027
- return rerenderDeferredValue(value);
4028
- },
4029
- useTransition(): [boolean, (() => void) => void] {
4030
- currentHookNameInDev = 'useTransition';
4031
- warnInvalidHookAccess();
4032
- updateHookTypesDev();
4033
- return rerenderTransition();
4034
- },
4035
- useMutableSource<Source, Snapshot>(
4036
- source: MutableSource<Source>,
4037
- getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
4038
- subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
4039
- ): Snapshot {
4040
- currentHookNameInDev = 'useMutableSource';
4041
- warnInvalidHookAccess();
4042
- updateHookTypesDev();
4043
- return updateMutableSource(source, getSnapshot, subscribe);
4044
- },
4045
- useSyncExternalStore<T>(
4046
- subscribe: (() => void) => () => void,
4047
- getSnapshot: () => T,
4048
- getServerSnapshot?: () => T,
4049
- ): T {
4050
- currentHookNameInDev = 'useSyncExternalStore';
4051
- warnInvalidHookAccess();
4052
- updateHookTypesDev();
4053
- return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
4054
- },
4055
- useId(): string {
4056
- currentHookNameInDev = 'useId';
4057
- warnInvalidHookAccess();
4058
- updateHookTypesDev();
4059
- return updateId();
4060
- },
4061
-
4062
- unstable_isNewReconciler: enableNewReconciler,
4063
- };
4064
- if (enableCache) {
4065
- (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
4066
- currentHookNameInDev = 'useCacheRefresh';
4067
- updateHookTypesDev();
4068
- return updateRefresh();
4069
- };
4070
- }
4071
- if (enableUseHook) {
4072
- (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).use = function<T>(
4073
- usable: Usable<T>,
4074
- ): T {
4075
- warnInvalidHookAccess();
4076
- return use(usable);
4077
- };
4078
- }
4079
- if (enableUseMemoCacheHook) {
4080
- (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useMemoCache = function(
4081
- size: number,
4082
- ): Array<any> {
4083
- warnInvalidHookAccess();
4084
- return useMemoCache(size);
4085
- };
4086
- }
4087
- if (enableUseEventHook) {
4088
- (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useEvent = function useEvent<
4089
- Args,
4090
- Return,
4091
- F: (...Array<Args>) => Return,
4092
- >(callback: F): F {
4093
- currentHookNameInDev = 'useEvent';
4094
- warnInvalidHookAccess();
4095
- updateHookTypesDev();
4096
- return updateEvent(callback);
4097
- };
4098
- }
4099
-}
packages/react-reconciler/src/ReactFiberHooks.old.js
-23
@@ -31,7 +31,6 @@ import ReactSharedInternals from 'shared/ReactSharedInternals';
31
import {
32
enableDebugTracing,
33
enableSchedulingProfiler,
34
- enableNewReconciler,
34
enableCache,
35
enableUseRefAccessWarning,
36
enableLazyContextPropagation,
@@ -2758,8 +2757,6 @@ export const ContextOnlyDispatcher: Dispatcher = {
2757
useMutableSource: throwInvalidHookError,
2758
useSyncExternalStore: throwInvalidHookError,
2759
useId: throwInvalidHookError,
2761
-
2762
- unstable_isNewReconciler: enableNewReconciler,
2760
};
2761
if (enableCache) {
2762
(ContextOnlyDispatcher: Dispatcher).useCacheRefresh = throwInvalidHookError;
@@ -2793,8 +2790,6 @@ const HooksDispatcherOnMount: Dispatcher = {
2790
useMutableSource: mountMutableSource,
2791
useSyncExternalStore: mountSyncExternalStore,
2792
useId: mountId,
2796
-
2797
- unstable_isNewReconciler: enableNewReconciler,
2793
};
2794
if (enableCache) {
2795
// $FlowFixMe[escaped-generic] discovered when updating Flow
@@ -2828,8 +2823,6 @@ const HooksDispatcherOnUpdate: Dispatcher = {
2823
useMutableSource: updateMutableSource,
2824
useSyncExternalStore: updateSyncExternalStore,
2825
useId: updateId,
2831
-
2832
- unstable_isNewReconciler: enableNewReconciler,
2826
};
2827
if (enableCache) {
2828
(HooksDispatcherOnUpdate: Dispatcher).useCacheRefresh = updateRefresh;
@@ -2863,8 +2856,6 @@ const HooksDispatcherOnRerender: Dispatcher = {
2856
useMutableSource: updateMutableSource,
2857
useSyncExternalStore: updateSyncExternalStore,
2858
useId: updateId,
2866
-
2867
- unstable_isNewReconciler: enableNewReconciler,
2859
};
2860
if (enableCache) {
2861
(HooksDispatcherOnRerender: Dispatcher).useCacheRefresh = updateRefresh;
@@ -3041,8 +3032,6 @@ if (__DEV__) {
3032
mountHookTypesDev();
3033
return mountId();
3034
},
3044
-
3045
- unstable_isNewReconciler: enableNewReconciler,
3035
};
3036
if (enableCache) {
3037
(HooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
@@ -3198,8 +3187,6 @@ if (__DEV__) {
3187
updateHookTypesDev();
3188
return mountId();
3189
},
3201
-
3202
- unstable_isNewReconciler: enableNewReconciler,
3190
};
3191
if (enableCache) {
3192
(HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
@@ -3355,8 +3342,6 @@ if (__DEV__) {
3342
updateHookTypesDev();
3343
return updateId();
3344
},
3358
-
3359
- unstable_isNewReconciler: enableNewReconciler,
3345
};
3346
if (enableCache) {
3347
(HooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
@@ -3513,8 +3498,6 @@ if (__DEV__) {
3498
updateHookTypesDev();
3499
return updateId();
3500
},
3516
-
3517
- unstable_isNewReconciler: enableNewReconciler,
3501
};
3502
if (enableCache) {
3503
(HooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
@@ -3687,8 +3670,6 @@ if (__DEV__) {
3670
mountHookTypesDev();
3671
return mountId();
3672
},
3690
-
3691
- unstable_isNewReconciler: enableNewReconciler,
3673
};
3674
if (enableCache) {
3675
(InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
@@ -3872,8 +3853,6 @@ if (__DEV__) {
3853
updateHookTypesDev();
3854
return updateId();
3855
},
3875
-
3876
- unstable_isNewReconciler: enableNewReconciler,
3856
};
3857
if (enableCache) {
3858
(InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
@@ -4058,8 +4037,6 @@ if (__DEV__) {
4037
updateHookTypesDev();
4038
return updateId();
4039
},
4061
-
4062
- unstable_isNewReconciler: enableNewReconciler,
4040
};
4041
if (enableCache) {
4042
(InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() {
packages/react-reconciler/src/ReactFiberHostContext.js
deleted
-31
@@ -1,31 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Container, HostContext} from './ReactFiberHostConfig';
11
-import {enableNewReconciler} from 'shared/ReactFeatureFlags';
12
-
13
-import {
14
- getCurrentRootHostContainer as getCurrentRootHostContainer_old,
15
- getHostContext as getHostContext_old,
16
-} from './ReactFiberHostContext.old';
17
-
18
-import {
19
- getCurrentRootHostContainer as getCurrentRootHostContainer_new,
20
- getHostContext as getHostContext_new,
21
-} from './ReactFiberHostContext.new';
22
-
23
-export function getCurrentRootHostContainer(): null | Container {
24
- return enableNewReconciler
25
- ? getCurrentRootHostContainer_new()
26
- : getCurrentRootHostContainer_old();
27
-}
28
-
29
-export function getHostContext(): HostContext {
30
- return enableNewReconciler ? getHostContext_new() : getHostContext_old();
31
-}
packages/react-reconciler/src/ReactFiberHostContext.new.js
deleted
-109
@@ -1,109 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-import type {StackCursor} from './ReactFiberStack.new';
12
-import type {Container, HostContext} from './ReactFiberHostConfig';
13
-
14
-import {getChildHostContext, getRootHostContext} from './ReactFiberHostConfig';
15
-import {createCursor, push, pop} from './ReactFiberStack.new';
16
-
17
-const contextStackCursor: StackCursor<HostContext | null> = createCursor(null);
18
-const contextFiberStackCursor: StackCursor<Fiber | null> = createCursor(null);
19
-const rootInstanceStackCursor: StackCursor<Container | null> = createCursor(
20
- null,
21
-);
22
-
23
-function requiredContext<Value>(c: Value | null): Value {
24
- if (__DEV__) {
25
- if (c === null) {
26
- console.error(
27
- 'Expected host context to exist. This error is likely caused by a bug ' +
28
- 'in React. Please file an issue.',
29
- );
30
- }
31
- }
32
- return (c: any);
33
-}
34
-
35
-function getCurrentRootHostContainer(): null | Container {
36
- return rootInstanceStackCursor.current;
37
-}
38
-
39
-function getRootHostContainer(): Container {
40
- const rootInstance = requiredContext(rootInstanceStackCursor.current);
41
- return rootInstance;
42
-}
43
-
44
-function pushHostContainer(fiber: Fiber, nextRootInstance: Container) {
45
- // Push current root instance onto the stack;
46
- // This allows us to reset root when portals are popped.
47
- push(rootInstanceStackCursor, nextRootInstance, fiber);
48
- // Track the context and the Fiber that provided it.
49
- // This enables us to pop only Fibers that provide unique contexts.
50
- push(contextFiberStackCursor, fiber, fiber);
51
-
52
- // Finally, we need to push the host context to the stack.
53
- // However, we can't just call getRootHostContext() and push it because
54
- // we'd have a different number of entries on the stack depending on
55
- // whether getRootHostContext() throws somewhere in renderer code or not.
56
- // So we push an empty value first. This lets us safely unwind on errors.
57
- push(contextStackCursor, null, fiber);
58
- const nextRootContext = getRootHostContext(nextRootInstance);
59
- // Now that we know this function doesn't throw, replace it.
60
- pop(contextStackCursor, fiber);
61
- push(contextStackCursor, nextRootContext, fiber);
62
-}
63
-
64
-function popHostContainer(fiber: Fiber) {
65
- pop(contextStackCursor, fiber);
66
- pop(contextFiberStackCursor, fiber);
67
- pop(rootInstanceStackCursor, fiber);
68
-}
69
-
70
-function getHostContext(): HostContext {
71
- const context = requiredContext(contextStackCursor.current);
72
- return context;
73
-}
74
-
75
-function pushHostContext(fiber: Fiber): void {
76
- const context: HostContext = requiredContext(contextStackCursor.current);
77
- const nextContext = getChildHostContext(context, fiber.type);
78
-
79
- // Don't push this Fiber's context unless it's unique.
80
- if (context === nextContext) {
81
- return;
82
- }
83
-
84
- // Track the context and the Fiber that provided it.
85
- // This enables us to pop only Fibers that provide unique contexts.
86
- push(contextFiberStackCursor, fiber, fiber);
87
- push(contextStackCursor, nextContext, fiber);
88
-}
89
-
90
-function popHostContext(fiber: Fiber): void {
91
- // Do not pop unless this Fiber provided the current context.
92
- // pushHostContext() only pushes Fibers that provide unique contexts.
93
- if (contextFiberStackCursor.current !== fiber) {
94
- return;
95
- }
96
-
97
- pop(contextStackCursor, fiber);
98
- pop(contextFiberStackCursor, fiber);
99
-}
100
-
101
-export {
102
- getHostContext,
103
- getCurrentRootHostContainer,
104
- getRootHostContainer,
105
- popHostContainer,
106
- popHostContext,
107
- pushHostContainer,
108
- pushHostContext,
109
-};
packages/react-reconciler/src/ReactFiberHotReloading.js
deleted
-93
@@ -1,93 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
11
-import type {ReactElement} from '../../shared/ReactElementType';
12
-import type {Instance} from './ReactFiberHostConfig';
13
-import type {ReactNodeList} from 'shared/ReactTypes';
14
-
15
-import {enableNewReconciler} from 'shared/ReactFeatureFlags';
16
-
17
-import {
18
- setRefreshHandler as setRefreshHandler_old,
19
- resolveFunctionForHotReloading as resolveFunctionForHotReloading_old,
20
- resolveClassForHotReloading as resolveClassForHotReloading_old,
21
- resolveForwardRefForHotReloading as resolveForwardRefForHotReloading_old,
22
- isCompatibleFamilyForHotReloading as isCompatibleFamilyForHotReloading_old,
23
- markFailedErrorBoundaryForHotReloading as markFailedErrorBoundaryForHotReloading_old,
24
- scheduleRefresh as scheduleRefresh_old,
25
- scheduleRoot as scheduleRoot_old,
26
- findHostInstancesForRefresh as findHostInstancesForRefresh_old,
27
-} from './ReactFiberHotReloading.old';
28
-
29
-import {
30
- setRefreshHandler as setRefreshHandler_new,
31
- resolveFunctionForHotReloading as resolveFunctionForHotReloading_new,
32
- resolveClassForHotReloading as resolveClassForHotReloading_new,
33
- resolveForwardRefForHotReloading as resolveForwardRefForHotReloading_new,
34
- isCompatibleFamilyForHotReloading as isCompatibleFamilyForHotReloading_new,
35
- markFailedErrorBoundaryForHotReloading as markFailedErrorBoundaryForHotReloading_new,
36
- scheduleRefresh as scheduleRefresh_new,
37
- scheduleRoot as scheduleRoot_new,
38
- findHostInstancesForRefresh as findHostInstancesForRefresh_new,
39
-} from './ReactFiberHotReloading.new';
40
-
41
-export type Family = {
42
- current: any,
43
-};
44
-
45
-export type RefreshUpdate = {
46
- staleFamilies: Set<Family>,
47
- updatedFamilies: Set<Family>,
48
-};
49
-
50
-// Resolves type to a family.
51
-export type RefreshHandler = any => Family | void;
52
-
53
-// Used by React Refresh runtime through DevTools Global Hook.
54
-export type SetRefreshHandler = (handler: RefreshHandler | null) => void;
55
-export type ScheduleRefresh = (root: FiberRoot, update: RefreshUpdate) => void;
56
-export type ScheduleRoot = (root: FiberRoot, element: ReactNodeList) => void;
57
-export type FindHostInstancesForRefresh = (
58
- root: FiberRoot,
59
- families: Array<Family>,
60
-) => Set<Instance>;
61
-
62
-export const setRefreshHandler: (
63
- handler: RefreshHandler | null,
64
-) => void = enableNewReconciler ? setRefreshHandler_new : setRefreshHandler_old;
65
-export const resolveFunctionForHotReloading: typeof resolveFunctionForHotReloading_new = enableNewReconciler
66
- ? resolveFunctionForHotReloading_new
67
- : resolveFunctionForHotReloading_old;
68
-export const resolveClassForHotReloading: typeof resolveClassForHotReloading_new = enableNewReconciler
69
- ? resolveClassForHotReloading_new
70
- : resolveClassForHotReloading_old;
71
-export const resolveForwardRefForHotReloading: typeof resolveForwardRefForHotReloading_new = enableNewReconciler
72
- ? resolveForwardRefForHotReloading_new
73
- : resolveForwardRefForHotReloading_old;
74
-export const isCompatibleFamilyForHotReloading: (
75
- fiber: Fiber,
76
- element: ReactElement,
77
-) => boolean = enableNewReconciler
78
- ? isCompatibleFamilyForHotReloading_new
79
- : isCompatibleFamilyForHotReloading_old;
80
-export const markFailedErrorBoundaryForHotReloading: (
81
- fiber: Fiber,
82
-) => void = enableNewReconciler
83
- ? markFailedErrorBoundaryForHotReloading_new
84
- : markFailedErrorBoundaryForHotReloading_old;
85
-export const scheduleRefresh: ScheduleRefresh = enableNewReconciler
86
- ? scheduleRefresh_new
87
- : scheduleRefresh_old;
88
-export const scheduleRoot: ScheduleRoot = enableNewReconciler
89
- ? scheduleRoot_new
90
- : scheduleRoot_old;
91
-export const findHostInstancesForRefresh: FindHostInstancesForRefresh = enableNewReconciler
92
- ? findHostInstancesForRefresh_new
93
- : findHostInstancesForRefresh_old;
packages/react-reconciler/src/ReactFiberHotReloading.new.js
deleted
-487
@@ -1,487 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-/* eslint-disable react-internal/prod-error-codes */
11
-
12
-import type {ReactElement} from 'shared/ReactElementType';
13
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
14
-import type {Instance} from './ReactFiberHostConfig';
15
-import type {ReactNodeList} from 'shared/ReactTypes';
16
-
17
-import type {
18
- Family,
19
- FindHostInstancesForRefresh,
20
- RefreshHandler,
21
- RefreshUpdate,
22
- ScheduleRefresh,
23
- ScheduleRoot,
24
-} from './ReactFiberHotReloading';
25
-
26
-import {enableHostSingletons, enableFloat} from 'shared/ReactFeatureFlags';
27
-import {
28
- flushSync,
29
- scheduleUpdateOnFiber,
30
- flushPassiveEffects,
31
-} from './ReactFiberWorkLoop.new';
32
-import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates.new';
33
-import {updateContainer} from './ReactFiberReconciler.new';
34
-import {emptyContextObject} from './ReactFiberContext.new';
35
-import {SyncLane, NoTimestamp} from './ReactFiberLane.new';
36
-import {
37
- ClassComponent,
38
- FunctionComponent,
39
- ForwardRef,
40
- HostComponent,
41
- HostResource,
42
- HostSingleton,
43
- HostPortal,
44
- HostRoot,
45
- MemoComponent,
46
- SimpleMemoComponent,
47
-} from './ReactWorkTags';
48
-import {
49
- REACT_FORWARD_REF_TYPE,
50
- REACT_MEMO_TYPE,
51
- REACT_LAZY_TYPE,
52
-} from 'shared/ReactSymbols';
53
-import {supportsSingletons} from './ReactFiberHostConfig';
54
-
55
-let resolveFamily: RefreshHandler | null = null;
56
-let failedBoundaries: WeakSet<Fiber> | null = null;
57
-
58
-export const setRefreshHandler = (handler: RefreshHandler | null): void => {
59
- if (__DEV__) {
60
- resolveFamily = handler;
61
- }
62
-};
63
-
64
-export function resolveFunctionForHotReloading(type: any): any {
65
- if (__DEV__) {
66
- if (resolveFamily === null) {
67
- // Hot reloading is disabled.
68
- return type;
69
- }
70
- const family = resolveFamily(type);
71
- if (family === undefined) {
72
- return type;
73
- }
74
- // Use the latest known implementation.
75
- return family.current;
76
- } else {
77
- return type;
78
- }
79
-}
80
-
81
-export function resolveClassForHotReloading(type: any): any {
82
- // No implementation differences.
83
- return resolveFunctionForHotReloading(type);
84
-}
85
-
86
-export function resolveForwardRefForHotReloading(type: any): any {
87
- if (__DEV__) {
88
- if (resolveFamily === null) {
89
- // Hot reloading is disabled.
90
- return type;
91
- }
92
- const family = resolveFamily(type);
93
- if (family === undefined) {
94
- // Check if we're dealing with a real forwardRef. Don't want to crash early.
95
- if (
96
- type !== null &&
97
- type !== undefined &&
98
- typeof type.render === 'function'
99
- ) {
100
- // ForwardRef is special because its resolved .type is an object,
101
- // but it's possible that we only have its inner render function in the map.
102
- // If that inner render function is different, we'll build a new forwardRef type.
103
- const currentRender = resolveFunctionForHotReloading(type.render);
104
- if (type.render !== currentRender) {
105
- const syntheticType = {
106
- $$typeof: REACT_FORWARD_REF_TYPE,
107
- render: currentRender,
108
- };
109
- if (type.displayName !== undefined) {
110
- (syntheticType: any).displayName = type.displayName;
111
- }
112
- return syntheticType;
113
- }
114
- }
115
- return type;
116
- }
117
- // Use the latest known implementation.
118
- return family.current;
119
- } else {
120
- return type;
121
- }
122
-}
123
-
124
-export function isCompatibleFamilyForHotReloading(
125
- fiber: Fiber,
126
- element: ReactElement,
127
-): boolean {
128
- if (__DEV__) {
129
- if (resolveFamily === null) {
130
- // Hot reloading is disabled.
131
- return false;
132
- }
133
-
134
- const prevType = fiber.elementType;
135
- const nextType = element.type;
136
-
137
- // If we got here, we know types aren't === equal.
138
- let needsCompareFamilies = false;
139
-
140
- const $$typeofNextType =
141
- typeof nextType === 'object' && nextType !== null
142
- ? nextType.$$typeof
143
- : null;
144
-
145
- switch (fiber.tag) {
146
- case ClassComponent: {
147
- if (typeof nextType === 'function') {
148
- needsCompareFamilies = true;
149
- }
150
- break;
151
- }
152
- case FunctionComponent: {
153
- if (typeof nextType === 'function') {
154
- needsCompareFamilies = true;
155
- } else if ($$typeofNextType === REACT_LAZY_TYPE) {
156
- // We don't know the inner type yet.
157
- // We're going to assume that the lazy inner type is stable,
158
- // and so it is sufficient to avoid reconciling it away.
159
- // We're not going to unwrap or actually use the new lazy type.
160
- needsCompareFamilies = true;
161
- }
162
- break;
163
- }
164
- case ForwardRef: {
165
- if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
166
- needsCompareFamilies = true;
167
- } else if ($$typeofNextType === REACT_LAZY_TYPE) {
168
- needsCompareFamilies = true;
169
- }
170
- break;
171
- }
172
- case MemoComponent:
173
- case SimpleMemoComponent: {
174
- if ($$typeofNextType === REACT_MEMO_TYPE) {
175
- // TODO: if it was but can no longer be simple,
176
- // we shouldn't set this.
177
- needsCompareFamilies = true;
178
- } else if ($$typeofNextType === REACT_LAZY_TYPE) {
179
- needsCompareFamilies = true;
180
- }
181
- break;
182
- }
183
- default:
184
- return false;
185
- }
186
-
187
- // Check if both types have a family and it's the same one.
188
- if (needsCompareFamilies) {
189
- // Note: memo() and forwardRef() we'll compare outer rather than inner type.
190
- // This means both of them need to be registered to preserve state.
191
- // If we unwrapped and compared the inner types for wrappers instead,
192
- // then we would risk falsely saying two separate memo(Foo)
193
- // calls are equivalent because they wrap the same Foo function.
194
- const prevFamily = resolveFamily(prevType);
195
- // $FlowFixMe[not-a-function] found when upgrading Flow
196
- if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
197
- return true;
198
- }
199
- }
200
- return false;
201
- } else {
202
- return false;
203
- }
204
-}
205
-
206
-export function markFailedErrorBoundaryForHotReloading(fiber: Fiber) {
207
- if (__DEV__) {
208
- if (resolveFamily === null) {
209
- // Hot reloading is disabled.
210
- return;
211
- }
212
- if (typeof WeakSet !== 'function') {
213
- return;
214
- }
215
- if (failedBoundaries === null) {
216
- failedBoundaries = new WeakSet();
217
- }
218
- failedBoundaries.add(fiber);
219
- }
220
-}
221
-
222
-export const scheduleRefresh: ScheduleRefresh = (
223
- root: FiberRoot,
224
- update: RefreshUpdate,
225
-): void => {
226
- if (__DEV__) {
227
- if (resolveFamily === null) {
228
- // Hot reloading is disabled.
229
- return;
230
- }
231
- const {staleFamilies, updatedFamilies} = update;
232
- flushPassiveEffects();
233
- flushSync(() => {
234
- scheduleFibersWithFamiliesRecursively(
235
- root.current,
236
- updatedFamilies,
237
- staleFamilies,
238
- );
239
- });
240
- }
241
-};
242
-
243
-export const scheduleRoot: ScheduleRoot = (
244
- root: FiberRoot,
245
- element: ReactNodeList,
246
-): void => {
247
- if (__DEV__) {
248
- if (root.context !== emptyContextObject) {
249
- // Super edge case: root has a legacy _renderSubtree context
250
- // but we don't know the parentComponent so we can't pass it.
251
- // Just ignore. We'll delete this with _renderSubtree code path later.
252
- return;
253
- }
254
- flushPassiveEffects();
255
- flushSync(() => {
256
- updateContainer(element, root, null, null);
257
- });
258
- }
259
-};
260
-
261
-function scheduleFibersWithFamiliesRecursively(
262
- fiber: Fiber,
263
- updatedFamilies: Set<Family>,
264
- staleFamilies: Set<Family>,
265
-) {
266
- if (__DEV__) {
267
- const {alternate, child, sibling, tag, type} = fiber;
268
-
269
- let candidateType = null;
270
- switch (tag) {
271
- case FunctionComponent:
272
- case SimpleMemoComponent:
273
- case ClassComponent:
274
- candidateType = type;
275
- break;
276
- case ForwardRef:
277
- candidateType = type.render;
278
- break;
279
- default:
280
- break;
281
- }
282
-
283
- if (resolveFamily === null) {
284
- throw new Error('Expected resolveFamily to be set during hot reload.');
285
- }
286
-
287
- let needsRender = false;
288
- let needsRemount = false;
289
- if (candidateType !== null) {
290
- const family = resolveFamily(candidateType);
291
- if (family !== undefined) {
292
- if (staleFamilies.has(family)) {
293
- needsRemount = true;
294
- } else if (updatedFamilies.has(family)) {
295
- if (tag === ClassComponent) {
296
- needsRemount = true;
297
- } else {
298
- needsRender = true;
299
- }
300
- }
301
- }
302
- }
303
- if (failedBoundaries !== null) {
304
- if (
305
- failedBoundaries.has(fiber) ||
306
- // $FlowFixMe[incompatible-use] found when upgrading Flow
307
- (alternate !== null && failedBoundaries.has(alternate))
308
- ) {
309
- needsRemount = true;
310
- }
311
- }
312
-
313
- if (needsRemount) {
314
- fiber._debugNeedsRemount = true;
315
- }
316
- if (needsRemount || needsRender) {
317
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
318
- if (root !== null) {
319
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
320
- }
321
- }
322
- if (child !== null && !needsRemount) {
323
- scheduleFibersWithFamiliesRecursively(
324
- child,
325
- updatedFamilies,
326
- staleFamilies,
327
- );
328
- }
329
- if (sibling !== null) {
330
- scheduleFibersWithFamiliesRecursively(
331
- sibling,
332
- updatedFamilies,
333
- staleFamilies,
334
- );
335
- }
336
- }
337
-}
338
-
339
-export const findHostInstancesForRefresh: FindHostInstancesForRefresh = (
340
- root: FiberRoot,
341
- families: Array<Family>,
342
-): Set<Instance> => {
343
- if (__DEV__) {
344
- const hostInstances = new Set();
345
- const types = new Set(families.map(family => family.current));
346
- findHostInstancesForMatchingFibersRecursively(
347
- root.current,
348
- types,
349
- hostInstances,
350
- );
351
- return hostInstances;
352
- } else {
353
- throw new Error(
354
- 'Did not expect findHostInstancesForRefresh to be called in production.',
355
- );
356
- }
357
-};
358
-
359
-function findHostInstancesForMatchingFibersRecursively(
360
- fiber: Fiber,
361
- types: Set<any>,
362
- hostInstances: Set<Instance>,
363
-) {
364
- if (__DEV__) {
365
- const {child, sibling, tag, type} = fiber;
366
-
367
- let candidateType = null;
368
- switch (tag) {
369
- case FunctionComponent:
370
- case SimpleMemoComponent:
371
- case ClassComponent:
372
- candidateType = type;
373
- break;
374
- case ForwardRef:
375
- candidateType = type.render;
376
- break;
377
- default:
378
- break;
379
- }
380
-
381
- let didMatch = false;
382
- if (candidateType !== null) {
383
- if (types.has(candidateType)) {
384
- didMatch = true;
385
- }
386
- }
387
-
388
- if (didMatch) {
389
- // We have a match. This only drills down to the closest host components.
390
- // There's no need to search deeper because for the purpose of giving
391
- // visual feedback, "flashing" outermost parent rectangles is sufficient.
392
- findHostInstancesForFiberShallowly(fiber, hostInstances);
393
- } else {
394
- // If there's no match, maybe there will be one further down in the child tree.
395
- if (child !== null) {
396
- findHostInstancesForMatchingFibersRecursively(
397
- child,
398
- types,
399
- hostInstances,
400
- );
401
- }
402
- }
403
-
404
- if (sibling !== null) {
405
- findHostInstancesForMatchingFibersRecursively(
406
- sibling,
407
- types,
408
- hostInstances,
409
- );
410
- }
411
- }
412
-}
413
-
414
-function findHostInstancesForFiberShallowly(
415
- fiber: Fiber,
416
- hostInstances: Set<Instance>,
417
-): void {
418
- if (__DEV__) {
419
- const foundHostInstances = findChildHostInstancesForFiberShallowly(
420
- fiber,
421
- hostInstances,
422
- );
423
- if (foundHostInstances) {
424
- return;
425
- }
426
- // If we didn't find any host children, fallback to closest host parent.
427
- let node = fiber;
428
- while (true) {
429
- switch (node.tag) {
430
- case HostSingleton:
431
- case HostComponent:
432
- hostInstances.add(node.stateNode);
433
- return;
434
- case HostPortal:
435
- hostInstances.add(node.stateNode.containerInfo);
436
- return;
437
- case HostRoot:
438
- hostInstances.add(node.stateNode.containerInfo);
439
- return;
440
- }
441
- if (node.return === null) {
442
- throw new Error('Expected to reach root first.');
443
- }
444
- node = node.return;
445
- }
446
- }
447
-}
448
-
449
-function findChildHostInstancesForFiberShallowly(
450
- fiber: Fiber,
451
- hostInstances: Set<Instance>,
452
-): boolean {
453
- if (__DEV__) {
454
- let node: Fiber = fiber;
455
- let foundHostInstances = false;
456
- while (true) {
457
- if (
458
- node.tag === HostComponent ||
459
- (enableFloat ? node.tag === HostResource : false) ||
460
- (enableHostSingletons && supportsSingletons
461
- ? node.tag === HostSingleton
462
- : false)
463
- ) {
464
- // We got a match.
465
- foundHostInstances = true;
466
- hostInstances.add(node.stateNode);
467
- // There may still be more, so keep searching.
468
- } else if (node.child !== null) {
469
- node.child.return = node;
470
- node = node.child;
471
- continue;
472
- }
473
- if (node === fiber) {
474
- return foundHostInstances;
475
- }
476
- while (node.sibling === null) {
477
- if (node.return === null || node.return === fiber) {
478
- return foundHostInstances;
479
- }
480
- node = node.return;
481
- }
482
- node.sibling.return = node.return;
483
- node = node.sibling;
484
- }
485
- }
486
- return false;
487
-}
packages/react-reconciler/src/ReactFiberHotReloading.old.js
+21
-9
@@ -14,15 +14,6 @@ import type {Fiber, FiberRoot} from './ReactInternalTypes';
14
import type {Instance} from './ReactFiberHostConfig';
15
import type {ReactNodeList} from 'shared/ReactTypes';
16
17
-import type {
18
- Family,
19
- FindHostInstancesForRefresh,
20
- RefreshHandler,
21
- RefreshUpdate,
22
- ScheduleRefresh,
23
- ScheduleRoot,
24
-} from './ReactFiberHotReloading';
25
-
17
import {enableHostSingletons, enableFloat} from 'shared/ReactFeatureFlags';
18
import {
19
flushSync,
@@ -52,6 +43,27 @@ import {
43
} from 'shared/ReactSymbols';
44
import {supportsSingletons} from './ReactFiberHostConfig';
45
46
+export type Family = {
47
+ current: any,
48
+};
49
+
50
+export type RefreshUpdate = {
51
+ staleFamilies: Set<Family>,
52
+ updatedFamilies: Set<Family>,
53
+};
54
+
55
+// Resolves type to a family.
56
+type RefreshHandler = any => Family | void;
57
+
58
+// Used by React Refresh runtime through DevTools Global Hook.
59
+export type SetRefreshHandler = (handler: RefreshHandler | null) => void;
60
+export type ScheduleRefresh = (root: FiberRoot, update: RefreshUpdate) => void;
61
+export type ScheduleRoot = (root: FiberRoot, element: ReactNodeList) => void;
62
+export type FindHostInstancesForRefresh = (
63
+ root: FiberRoot,
64
+ families: Array<Family>,
65
+) => Set<Instance>;
66
+
67
let resolveFamily: RefreshHandler | null = null;
68
let failedBoundaries: WeakSet<Fiber> | null = null;
69
packages/react-reconciler/src/ReactFiberHydrationContext.new.js
deleted
-771
@@ -1,771 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-import {NoMode, ConcurrentMode} from './ReactTypeOfMode';
12
-import type {
13
- Instance,
14
- TextInstance,
15
- HydratableInstance,
16
- SuspenseInstance,
17
- Container,
18
- HostContext,
19
-} from './ReactFiberHostConfig';
20
-import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
21
-import type {TreeContext} from './ReactFiberTreeContext.new';
22
-import type {CapturedValue} from './ReactCapturedValue';
23
-
24
-import {
25
- HostComponent,
26
- HostSingleton,
27
- HostText,
28
- HostRoot,
29
- SuspenseComponent,
30
-} from './ReactWorkTags';
31
-import {
32
- ChildDeletion,
33
- Placement,
34
- Hydrating,
35
- NoFlags,
36
- DidCapture,
37
-} from './ReactFiberFlags';
38
-import {enableHostSingletons, enableFloat} from 'shared/ReactFeatureFlags';
39
-
40
-import {
41
- createFiberFromHostInstanceForDeletion,
42
- createFiberFromDehydratedFragment,
43
-} from './ReactFiber.new';
44
-import {
45
- shouldSetTextContent,
46
- supportsHydration,
47
- supportsSingletons,
48
- isHydratable,
49
- canHydrateInstance,
50
- canHydrateTextInstance,
51
- canHydrateSuspenseInstance,
52
- getNextHydratableSibling,
53
- getFirstHydratableChild,
54
- getFirstHydratableChildWithinContainer,
55
- getFirstHydratableChildWithinSuspenseInstance,
56
- hydrateInstance,
57
- hydrateTextInstance,
58
- hydrateSuspenseInstance,
59
- getNextHydratableInstanceAfterSuspenseInstance,
60
- shouldDeleteUnhydratedTailInstances,
61
- didNotMatchHydratedContainerTextInstance,
62
- didNotMatchHydratedTextInstance,
63
- didNotHydrateInstanceWithinContainer,
64
- didNotHydrateInstanceWithinSuspenseInstance,
65
- didNotHydrateInstance,
66
- didNotFindHydratableInstanceWithinContainer,
67
- didNotFindHydratableTextInstanceWithinContainer,
68
- didNotFindHydratableSuspenseInstanceWithinContainer,
69
- didNotFindHydratableInstanceWithinSuspenseInstance,
70
- didNotFindHydratableTextInstanceWithinSuspenseInstance,
71
- didNotFindHydratableSuspenseInstanceWithinSuspenseInstance,
72
- didNotFindHydratableInstance,
73
- didNotFindHydratableTextInstance,
74
- didNotFindHydratableSuspenseInstance,
75
- resolveSingletonInstance,
76
-} from './ReactFiberHostConfig';
77
-import {OffscreenLane} from './ReactFiberLane.new';
78
-import {
79
- getSuspendedTreeContext,
80
- restoreSuspendedTreeContext,
81
-} from './ReactFiberTreeContext.new';
82
-import {queueRecoverableErrors} from './ReactFiberWorkLoop.new';
83
-import {
84
- getRootHostContainer,
85
- getHostContext,
86
-} from './ReactFiberHostContext.new';
87
-
88
-// The deepest Fiber on the stack involved in a hydration context.
89
-// This may have been an insertion or a hydration.
90
-let hydrationParentFiber: null | Fiber = null;
91
-let nextHydratableInstance: null | HydratableInstance = null;
92
-let isHydrating: boolean = false;
93
-
94
-// This flag allows for warning supression when we expect there to be mismatches
95
-// due to earlier mismatches or a suspended fiber.
96
-let didSuspendOrErrorDEV: boolean = false;
97
-
98
-// Hydration errors that were thrown inside this boundary
99
-let hydrationErrors: Array<CapturedValue<mixed>> | null = null;
100
-
101
-function warnIfHydrating() {
102
- if (__DEV__) {
103
- if (isHydrating) {
104
- console.error(
105
- 'We should not be hydrating here. This is a bug in React. Please file a bug.',
106
- );
107
- }
108
- }
109
-}
110
-
111
-export function markDidThrowWhileHydratingDEV() {
112
- if (__DEV__) {
113
- didSuspendOrErrorDEV = true;
114
- }
115
-}
116
-
117
-export function didSuspendOrErrorWhileHydratingDEV(): boolean {
118
- if (__DEV__) {
119
- return didSuspendOrErrorDEV;
120
- }
121
- return false;
122
-}
123
-
124
-function enterHydrationState(fiber: Fiber): boolean {
125
- if (!supportsHydration) {
126
- return false;
127
- }
128
-
129
- const parentInstance: Container = fiber.stateNode.containerInfo;
130
- nextHydratableInstance = getFirstHydratableChildWithinContainer(
131
- parentInstance,
132
- );
133
- hydrationParentFiber = fiber;
134
- isHydrating = true;
135
- hydrationErrors = null;
136
- didSuspendOrErrorDEV = false;
137
- return true;
138
-}
139
-
140
-function reenterHydrationStateFromDehydratedSuspenseInstance(
141
- fiber: Fiber,
142
- suspenseInstance: SuspenseInstance,
143
- treeContext: TreeContext | null,
144
-): boolean {
145
- if (!supportsHydration) {
146
- return false;
147
- }
148
- nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(
149
- suspenseInstance,
150
- );
151
- hydrationParentFiber = fiber;
152
- isHydrating = true;
153
- hydrationErrors = null;
154
- didSuspendOrErrorDEV = false;
155
- if (treeContext !== null) {
156
- restoreSuspendedTreeContext(fiber, treeContext);
157
- }
158
- return true;
159
-}
160
-
161
-function warnUnhydratedInstance(
162
- returnFiber: Fiber,
163
- instance: HydratableInstance,
164
-) {
165
- if (__DEV__) {
166
- switch (returnFiber.tag) {
167
- case HostRoot: {
168
- didNotHydrateInstanceWithinContainer(
169
- returnFiber.stateNode.containerInfo,
170
- instance,
171
- );
172
- break;
173
- }
174
- case HostSingleton:
175
- case HostComponent: {
176
- const isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
177
- didNotHydrateInstance(
178
- returnFiber.type,
179
- returnFiber.memoizedProps,
180
- returnFiber.stateNode,
181
- instance,
182
- // TODO: Delete this argument when we remove the legacy root API.
183
- isConcurrentMode,
184
- );
185
- break;
186
- }
187
- case SuspenseComponent: {
188
- const suspenseState: SuspenseState = returnFiber.memoizedState;
189
- if (suspenseState.dehydrated !== null)
190
- didNotHydrateInstanceWithinSuspenseInstance(
191
- suspenseState.dehydrated,
192
- instance,
193
- );
194
- break;
195
- }
196
- }
197
- }
198
-}
199
-
200
-function deleteHydratableInstance(
201
- returnFiber: Fiber,
202
- instance: HydratableInstance,
203
-) {
204
- warnUnhydratedInstance(returnFiber, instance);
205
- const childToDelete = createFiberFromHostInstanceForDeletion();
206
- childToDelete.stateNode = instance;
207
- childToDelete.return = returnFiber;
208
-
209
- const deletions = returnFiber.deletions;
210
- if (deletions === null) {
211
- returnFiber.deletions = [childToDelete];
212
- returnFiber.flags |= ChildDeletion;
213
- } else {
214
- deletions.push(childToDelete);
215
- }
216
-}
217
-
218
-function warnNonhydratedInstance(returnFiber: Fiber, fiber: Fiber) {
219
- if (__DEV__) {
220
- if (didSuspendOrErrorDEV) {
221
- // Inside a boundary that already suspended. We're currently rendering the
222
- // siblings of a suspended node. The mismatch may be due to the missing
223
- // data, so it's probably a false positive.
224
- return;
225
- }
226
-
227
- switch (returnFiber.tag) {
228
- case HostRoot: {
229
- const parentContainer = returnFiber.stateNode.containerInfo;
230
- switch (fiber.tag) {
231
- case HostSingleton:
232
- case HostComponent:
233
- const type = fiber.type;
234
- const props = fiber.pendingProps;
235
- didNotFindHydratableInstanceWithinContainer(
236
- parentContainer,
237
- type,
238
- props,
239
- );
240
- break;
241
- case HostText:
242
- const text = fiber.pendingProps;
243
- didNotFindHydratableTextInstanceWithinContainer(
244
- parentContainer,
245
- text,
246
- );
247
- break;
248
- case SuspenseComponent:
249
- didNotFindHydratableSuspenseInstanceWithinContainer(
250
- parentContainer,
251
- );
252
- break;
253
- }
254
- break;
255
- }
256
- case HostSingleton:
257
- case HostComponent: {
258
- const parentType = returnFiber.type;
259
- const parentProps = returnFiber.memoizedProps;
260
- const parentInstance = returnFiber.stateNode;
261
- switch (fiber.tag) {
262
- case HostSingleton:
263
- case HostComponent: {
264
- const type = fiber.type;
265
- const props = fiber.pendingProps;
266
- const isConcurrentMode =
267
- (returnFiber.mode & ConcurrentMode) !== NoMode;
268
- didNotFindHydratableInstance(
269
- parentType,
270
- parentProps,
271
- parentInstance,
272
- type,
273
- props,
274
- // TODO: Delete this argument when we remove the legacy root API.
275
- isConcurrentMode,
276
- );
277
- break;
278
- }
279
- case HostText: {
280
- const text = fiber.pendingProps;
281
- const isConcurrentMode =
282
- (returnFiber.mode & ConcurrentMode) !== NoMode;
283
- didNotFindHydratableTextInstance(
284
- parentType,
285
- parentProps,
286
- parentInstance,
287
- text,
288
- // TODO: Delete this argument when we remove the legacy root API.
289
- isConcurrentMode,
290
- );
291
- break;
292
- }
293
- case SuspenseComponent: {
294
- didNotFindHydratableSuspenseInstance(
295
- parentType,
296
- parentProps,
297
- parentInstance,
298
- );
299
- break;
300
- }
301
- }
302
- break;
303
- }
304
- case SuspenseComponent: {
305
- const suspenseState: SuspenseState = returnFiber.memoizedState;
306
- const parentInstance = suspenseState.dehydrated;
307
- if (parentInstance !== null)
308
- switch (fiber.tag) {
309
- case HostSingleton:
310
- case HostComponent:
311
- const type = fiber.type;
312
- const props = fiber.pendingProps;
313
- didNotFindHydratableInstanceWithinSuspenseInstance(
314
- parentInstance,
315
- type,
316
- props,
317
- );
318
- break;
319
- case HostText:
320
- const text = fiber.pendingProps;
321
- didNotFindHydratableTextInstanceWithinSuspenseInstance(
322
- parentInstance,
323
- text,
324
- );
325
- break;
326
- case SuspenseComponent:
327
- didNotFindHydratableSuspenseInstanceWithinSuspenseInstance(
328
- parentInstance,
329
- );
330
- break;
331
- }
332
- break;
333
- }
334
- default:
335
- return;
336
- }
337
- }
338
-}
339
-function insertNonHydratedInstance(returnFiber: Fiber, fiber: Fiber) {
340
- fiber.flags = (fiber.flags & ~Hydrating) | Placement;
341
- warnNonhydratedInstance(returnFiber, fiber);
342
-}
343
-
344
-function tryHydrate(fiber, nextInstance) {
345
- switch (fiber.tag) {
346
- // HostSingleton is intentionally omitted. the hydration pathway for singletons is non-fallible
347
- // you can find it inlined in claimHydratableSingleton
348
- case HostComponent: {
349
- const type = fiber.type;
350
- const props = fiber.pendingProps;
351
- const instance = canHydrateInstance(nextInstance, type, props);
352
- if (instance !== null) {
353
- fiber.stateNode = (instance: Instance);
354
- hydrationParentFiber = fiber;
355
- nextHydratableInstance = getFirstHydratableChild(instance);
356
- return true;
357
- }
358
- return false;
359
- }
360
- case HostText: {
361
- const text = fiber.pendingProps;
362
- const textInstance = canHydrateTextInstance(nextInstance, text);
363
- if (textInstance !== null) {
364
- fiber.stateNode = (textInstance: TextInstance);
365
- hydrationParentFiber = fiber;
366
- // Text Instances don't have children so there's nothing to hydrate.
367
- nextHydratableInstance = null;
368
- return true;
369
- }
370
- return false;
371
- }
372
- case SuspenseComponent: {
373
- const suspenseInstance: null | SuspenseInstance = canHydrateSuspenseInstance(
374
- nextInstance,
375
- );
376
- if (suspenseInstance !== null) {
377
- const suspenseState: SuspenseState = {
378
- dehydrated: suspenseInstance,
379
- treeContext: getSuspendedTreeContext(),
380
- retryLane: OffscreenLane,
381
- };
382
- fiber.memoizedState = suspenseState;
383
- // Store the dehydrated fragment as a child fiber.
384
- // This simplifies the code for getHostSibling and deleting nodes,
385
- // since it doesn't have to consider all Suspense boundaries and
386
- // check if they're dehydrated ones or not.
387
- const dehydratedFragment = createFiberFromDehydratedFragment(
388
- suspenseInstance,
389
- );
390
- dehydratedFragment.return = fiber;
391
- fiber.child = dehydratedFragment;
392
- hydrationParentFiber = fiber;
393
- // While a Suspense Instance does have children, we won't step into
394
- // it during the first pass. Instead, we'll reenter it later.
395
- nextHydratableInstance = null;
396
- return true;
397
- }
398
- return false;
399
- }
400
- default:
401
- return false;
402
- }
403
-}
404
-
405
-function shouldClientRenderOnMismatch(fiber: Fiber) {
406
- return (
407
- (fiber.mode & ConcurrentMode) !== NoMode &&
408
- (fiber.flags & DidCapture) === NoFlags
409
- );
410
-}
411
-
412
-function throwOnHydrationMismatch(fiber: Fiber) {
413
- throw new Error(
414
- 'Hydration failed because the initial UI does not match what was ' +
415
- 'rendered on the server.',
416
- );
417
-}
418
-
419
-function claimHydratableSingleton(fiber: Fiber): void {
420
- if (enableHostSingletons && supportsSingletons) {
421
- if (!isHydrating) {
422
- return;
423
- }
424
- const currentRootContainer = getRootHostContainer();
425
- const currentHostContext = getHostContext();
426
- const instance = (fiber.stateNode = resolveSingletonInstance(
427
- fiber.type,
428
- fiber.pendingProps,
429
- currentRootContainer,
430
- currentHostContext,
431
- false,
432
- ));
433
- hydrationParentFiber = fiber;
434
- nextHydratableInstance = getFirstHydratableChild(instance);
435
- }
436
-}
437
-
438
-function tryToClaimNextHydratableInstance(fiber: Fiber): void {
439
- if (!isHydrating) {
440
- return;
441
- }
442
- if (enableFloat && !isHydratable(fiber.type, fiber.pendingProps)) {
443
- // This fiber never hydrates from the DOM and always does an insert
444
- fiber.flags = (fiber.flags & ~Hydrating) | Placement;
445
- isHydrating = false;
446
- hydrationParentFiber = fiber;
447
- return;
448
- }
449
- let nextInstance = nextHydratableInstance;
450
- if (!nextInstance) {
451
- if (shouldClientRenderOnMismatch(fiber)) {
452
- warnNonhydratedInstance((hydrationParentFiber: any), fiber);
453
- throwOnHydrationMismatch(fiber);
454
- }
455
- // Nothing to hydrate. Make it an insertion.
456
- insertNonHydratedInstance((hydrationParentFiber: any), fiber);
457
- isHydrating = false;
458
- hydrationParentFiber = fiber;
459
- return;
460
- }
461
- const firstAttemptedInstance = nextInstance;
462
- if (!tryHydrate(fiber, nextInstance)) {
463
- if (shouldClientRenderOnMismatch(fiber)) {
464
- warnNonhydratedInstance((hydrationParentFiber: any), fiber);
465
- throwOnHydrationMismatch(fiber);
466
- }
467
- // If we can't hydrate this instance let's try the next one.
468
- // We use this as a heuristic. It's based on intuition and not data so it
469
- // might be flawed or unnecessary.
470
- nextInstance = getNextHydratableSibling(firstAttemptedInstance);
471
- const prevHydrationParentFiber: Fiber = (hydrationParentFiber: any);
472
- if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
473
- // Nothing to hydrate. Make it an insertion.
474
- insertNonHydratedInstance((hydrationParentFiber: any), fiber);
475
- isHydrating = false;
476
- hydrationParentFiber = fiber;
477
- return;
478
- }
479
- // We matched the next one, we'll now assume that the first one was
480
- // superfluous and we'll delete it. Since we can't eagerly delete it
481
- // we'll have to schedule a deletion. To do that, this node needs a dummy
482
- // fiber associated with it.
483
- deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance);
484
- }
485
-}
486
-
487
-function prepareToHydrateHostInstance(
488
- fiber: Fiber,
489
- hostContext: HostContext,
490
-): boolean {
491
- if (!supportsHydration) {
492
- throw new Error(
493
- 'Expected prepareToHydrateHostInstance() to never be called. ' +
494
- 'This error is likely caused by a bug in React. Please file an issue.',
495
- );
496
- }
497
-
498
- const instance: Instance = fiber.stateNode;
499
- const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
500
- const updatePayload = hydrateInstance(
501
- instance,
502
- fiber.type,
503
- fiber.memoizedProps,
504
- hostContext,
505
- fiber,
506
- shouldWarnIfMismatchDev,
507
- );
508
- // TODO: Type this specific to this type of component.
509
- fiber.updateQueue = (updatePayload: any);
510
- // If the update payload indicates that there is a change or if there
511
- // is a new ref we mark this as an update.
512
- if (updatePayload !== null) {
513
- return true;
514
- }
515
- return false;
516
-}
517
-
518
-function prepareToHydrateHostTextInstance(fiber: Fiber): boolean {
519
- if (!supportsHydration) {
520
- throw new Error(
521
- 'Expected prepareToHydrateHostTextInstance() to never be called. ' +
522
- 'This error is likely caused by a bug in React. Please file an issue.',
523
- );
524
- }
525
-
526
- const textInstance: TextInstance = fiber.stateNode;
527
- const textContent: string = fiber.memoizedProps;
528
- const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
529
- const shouldUpdate = hydrateTextInstance(
530
- textInstance,
531
- textContent,
532
- fiber,
533
- shouldWarnIfMismatchDev,
534
- );
535
- if (shouldUpdate) {
536
- // We assume that prepareToHydrateHostTextInstance is called in a context where the
537
- // hydration parent is the parent host component of this host text.
538
- const returnFiber = hydrationParentFiber;
539
- if (returnFiber !== null) {
540
- switch (returnFiber.tag) {
541
- case HostRoot: {
542
- const parentContainer = returnFiber.stateNode.containerInfo;
543
- const isConcurrentMode =
544
- (returnFiber.mode & ConcurrentMode) !== NoMode;
545
- didNotMatchHydratedContainerTextInstance(
546
- parentContainer,
547
- textInstance,
548
- textContent,
549
- // TODO: Delete this argument when we remove the legacy root API.
550
- isConcurrentMode,
551
- shouldWarnIfMismatchDev,
552
- );
553
- break;
554
- }
555
- case HostSingleton:
556
- case HostComponent: {
557
- const parentType = returnFiber.type;
558
- const parentProps = returnFiber.memoizedProps;
559
- const parentInstance = returnFiber.stateNode;
560
- const isConcurrentMode =
561
- (returnFiber.mode & ConcurrentMode) !== NoMode;
562
- didNotMatchHydratedTextInstance(
563
- parentType,
564
- parentProps,
565
- parentInstance,
566
- textInstance,
567
- textContent,
568
- // TODO: Delete this argument when we remove the legacy root API.
569
- isConcurrentMode,
570
- shouldWarnIfMismatchDev,
571
- );
572
- break;
573
- }
574
- }
575
- }
576
- }
577
- return shouldUpdate;
578
-}
579
-
580
-function prepareToHydrateHostSuspenseInstance(fiber: Fiber): void {
581
- if (!supportsHydration) {
582
- throw new Error(
583
- 'Expected prepareToHydrateHostSuspenseInstance() to never be called. ' +
584
- 'This error is likely caused by a bug in React. Please file an issue.',
585
- );
586
- }
587
-
588
- const suspenseState: null | SuspenseState = fiber.memoizedState;
589
- const suspenseInstance: null | SuspenseInstance =
590
- suspenseState !== null ? suspenseState.dehydrated : null;
591
-
592
- if (!suspenseInstance) {
593
- throw new Error(
594
- 'Expected to have a hydrated suspense instance. ' +
595
- 'This error is likely caused by a bug in React. Please file an issue.',
596
- );
597
- }
598
-
599
- hydrateSuspenseInstance(suspenseInstance, fiber);
600
-}
601
-
602
-function skipPastDehydratedSuspenseInstance(
603
- fiber: Fiber,
604
-): null | HydratableInstance {
605
- if (!supportsHydration) {
606
- throw new Error(
607
- 'Expected skipPastDehydratedSuspenseInstance() to never be called. ' +
608
- 'This error is likely caused by a bug in React. Please file an issue.',
609
- );
610
- }
611
- const suspenseState: null | SuspenseState = fiber.memoizedState;
612
- const suspenseInstance: null | SuspenseInstance =
613
- suspenseState !== null ? suspenseState.dehydrated : null;
614
-
615
- if (!suspenseInstance) {
616
- throw new Error(
617
- 'Expected to have a hydrated suspense instance. ' +
618
- 'This error is likely caused by a bug in React. Please file an issue.',
619
- );
620
- }
621
-
622
- return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
623
-}
624
-
625
-function popToNextHostParent(fiber: Fiber): void {
626
- let parent = fiber.return;
627
- while (
628
- parent !== null &&
629
- parent.tag !== HostComponent &&
630
- parent.tag !== HostRoot &&
631
- parent.tag !== SuspenseComponent &&
632
- (!(enableHostSingletons && supportsSingletons)
633
- ? true
634
- : parent.tag !== HostSingleton)
635
- ) {
636
- parent = parent.return;
637
- }
638
- hydrationParentFiber = parent;
639
-}
640
-
641
-function popHydrationState(fiber: Fiber): boolean {
642
- if (!supportsHydration) {
643
- return false;
644
- }
645
- if (fiber !== hydrationParentFiber) {
646
- // We're deeper than the current hydration context, inside an inserted
647
- // tree.
648
- return false;
649
- }
650
- if (!isHydrating) {
651
- // If we're not currently hydrating but we're in a hydration context, then
652
- // we were an insertion and now need to pop up reenter hydration of our
653
- // siblings.
654
- popToNextHostParent(fiber);
655
- isHydrating = true;
656
- return false;
657
- }
658
-
659
- let shouldClear = false;
660
- if (enableHostSingletons && supportsSingletons) {
661
- // With float we never clear the Root, or Singleton instances. We also do not clear Instances
662
- // that have singleton text content
663
- if (
664
- fiber.tag !== HostRoot &&
665
- fiber.tag !== HostSingleton &&
666
- !(
667
- fiber.tag === HostComponent &&
668
- shouldSetTextContent(fiber.type, fiber.memoizedProps)
669
- )
670
- ) {
671
- shouldClear = true;
672
- }
673
- } else {
674
- // If we have any remaining hydratable nodes, we need to delete them now.
675
- // We only do this deeper than head and body since they tend to have random
676
- // other nodes in them. We also ignore components with pure text content in
677
- // side of them. We also don't delete anything inside the root container.
678
- if (
679
- fiber.tag !== HostRoot &&
680
- (fiber.tag !== HostComponent ||
681
- (shouldDeleteUnhydratedTailInstances(fiber.type) &&
682
- !shouldSetTextContent(fiber.type, fiber.memoizedProps)))
683
- ) {
684
- shouldClear = true;
685
- }
686
- }
687
- if (shouldClear) {
688
- let nextInstance = nextHydratableInstance;
689
- if (nextInstance) {
690
- if (shouldClientRenderOnMismatch(fiber)) {
691
- warnIfUnhydratedTailNodes(fiber);
692
- throwOnHydrationMismatch(fiber);
693
- } else {
694
- while (nextInstance) {
695
- deleteHydratableInstance(fiber, nextInstance);
696
- nextInstance = getNextHydratableSibling(nextInstance);
697
- }
698
- }
699
- }
700
- }
701
- popToNextHostParent(fiber);
702
- if (fiber.tag === SuspenseComponent) {
703
- nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
704
- } else {
705
- nextHydratableInstance = hydrationParentFiber
706
- ? getNextHydratableSibling(fiber.stateNode)
707
- : null;
708
- }
709
- return true;
710
-}
711
-
712
-function hasUnhydratedTailNodes(): boolean {
713
- return isHydrating && nextHydratableInstance !== null;
714
-}
715
-
716
-function warnIfUnhydratedTailNodes(fiber: Fiber) {
717
- let nextInstance = nextHydratableInstance;
718
- while (nextInstance) {
719
- warnUnhydratedInstance(fiber, nextInstance);
720
- nextInstance = getNextHydratableSibling(nextInstance);
721
- }
722
-}
723
-
724
-function resetHydrationState(): void {
725
- if (!supportsHydration) {
726
- return;
727
- }
728
-
729
- hydrationParentFiber = null;
730
- nextHydratableInstance = null;
731
- isHydrating = false;
732
- didSuspendOrErrorDEV = false;
733
-}
734
-
735
-export function upgradeHydrationErrorsToRecoverable(): void {
736
- if (hydrationErrors !== null) {
737
- // Successfully completed a forced client render. The errors that occurred
738
- // during the hydration attempt are now recovered. We will log them in
739
- // commit phase, once the entire tree has finished.
740
- queueRecoverableErrors(hydrationErrors);
741
- hydrationErrors = null;
742
- }
743
-}
744
-
745
-function getIsHydrating(): boolean {
746
- return isHydrating;
747
-}
748
-
749
-export function queueHydrationError(error: CapturedValue<mixed>): void {
750
- if (hydrationErrors === null) {
751
- hydrationErrors = [error];
752
- } else {
753
- hydrationErrors.push(error);
754
- }
755
-}
756
-
757
-export {
758
- warnIfHydrating,
759
- enterHydrationState,
760
- getIsHydrating,
761
- reenterHydrationStateFromDehydratedSuspenseInstance,
762
- resetHydrationState,
763
- claimHydratableSingleton,
764
- tryToClaimNextHydratableInstance,
765
- prepareToHydrateHostInstance,
766
- prepareToHydrateHostTextInstance,
767
- prepareToHydrateHostSuspenseInstance,
768
- popHydrationState,
769
- hasUnhydratedTailNodes,
770
- warnIfUnhydratedTailNodes,
771
-};
packages/react-reconciler/src/ReactFiberLane.new.js
deleted
-924
@@ -1,924 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
11
-import type {Transition} from './ReactFiberTracingMarkerComponent.new';
12
-import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates.new';
13
-
14
-// TODO: Ideally these types would be opaque but that doesn't work well with
15
-// our reconciler fork infra, since these leak into non-reconciler packages.
16
-
17
-export type Lanes = number;
18
-export type Lane = number;
19
-export type LaneMap<T> = Array<T>;
20
-
21
-import {
22
- enableSchedulingProfiler,
23
- enableUpdaterTracking,
24
- allowConcurrentByDefault,
25
- enableTransitionTracing,
26
-} from 'shared/ReactFeatureFlags';
27
-import {isDevToolsPresent} from './ReactFiberDevToolsHook.new';
28
-import {ConcurrentUpdatesByDefaultMode, NoMode} from './ReactTypeOfMode';
29
-import {clz32} from './clz32';
30
-
31
-// Lane values below should be kept in sync with getLabelForLane(), used by react-devtools-timeline.
32
-// If those values are changed that package should be rebuilt and redeployed.
33
-
34
-export const TotalLanes = 31;
35
-
36
-export const NoLanes: Lanes = /* */ 0b0000000000000000000000000000000;
37
-export const NoLane: Lane = /* */ 0b0000000000000000000000000000000;
38
-
39
-export const SyncHydrationLane: Lane = /* */ 0b0000000000000000000000000000001;
40
-export const SyncLane: Lane = /* */ 0b0000000000000000000000000000010;
41
-
42
-export const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000000100;
43
-export const InputContinuousLane: Lane = /* */ 0b0000000000000000000000000001000;
44
-
45
-export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000000010000;
46
-export const DefaultLane: Lane = /* */ 0b0000000000000000000000000100000;
47
-
48
-const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000001000000;
49
-const TransitionLanes: Lanes = /* */ 0b0000000011111111111111110000000;
50
-const TransitionLane1: Lane = /* */ 0b0000000000000000000000010000000;
51
-const TransitionLane2: Lane = /* */ 0b0000000000000000000000100000000;
52
-const TransitionLane3: Lane = /* */ 0b0000000000000000000001000000000;
53
-const TransitionLane4: Lane = /* */ 0b0000000000000000000010000000000;
54
-const TransitionLane5: Lane = /* */ 0b0000000000000000000100000000000;
55
-const TransitionLane6: Lane = /* */ 0b0000000000000000001000000000000;
56
-const TransitionLane7: Lane = /* */ 0b0000000000000000010000000000000;
57
-const TransitionLane8: Lane = /* */ 0b0000000000000000100000000000000;
58
-const TransitionLane9: Lane = /* */ 0b0000000000000001000000000000000;
59
-const TransitionLane10: Lane = /* */ 0b0000000000000010000000000000000;
60
-const TransitionLane11: Lane = /* */ 0b0000000000000100000000000000000;
61
-const TransitionLane12: Lane = /* */ 0b0000000000001000000000000000000;
62
-const TransitionLane13: Lane = /* */ 0b0000000000010000000000000000000;
63
-const TransitionLane14: Lane = /* */ 0b0000000000100000000000000000000;
64
-const TransitionLane15: Lane = /* */ 0b0000000001000000000000000000000;
65
-const TransitionLane16: Lane = /* */ 0b0000000010000000000000000000000;
66
-
67
-const RetryLanes: Lanes = /* */ 0b0000111100000000000000000000000;
68
-const RetryLane1: Lane = /* */ 0b0000000100000000000000000000000;
69
-const RetryLane2: Lane = /* */ 0b0000001000000000000000000000000;
70
-const RetryLane3: Lane = /* */ 0b0000010000000000000000000000000;
71
-const RetryLane4: Lane = /* */ 0b0000100000000000000000000000000;
72
-
73
-export const SomeRetryLane: Lane = RetryLane1;
74
-
75
-export const SelectiveHydrationLane: Lane = /* */ 0b0001000000000000000000000000000;
76
-
77
-const NonIdleLanes: Lanes = /* */ 0b0001111111111111111111111111111;
78
-
79
-export const IdleHydrationLane: Lane = /* */ 0b0010000000000000000000000000000;
80
-export const IdleLane: Lane = /* */ 0b0100000000000000000000000000000;
81
-
82
-export const OffscreenLane: Lane = /* */ 0b1000000000000000000000000000000;
83
-
84
-// This function is used for the experimental timeline (react-devtools-timeline)
85
-// It should be kept in sync with the Lanes values above.
86
-export function getLabelForLane(lane: Lane): string | void {
87
- if (enableSchedulingProfiler) {
88
- if (lane & SyncHydrationLane) {
89
- return 'SyncHydrationLane';
90
- }
91
- if (lane & SyncLane) {
92
- return 'Sync';
93
- }
94
- if (lane & InputContinuousHydrationLane) {
95
- return 'InputContinuousHydration';
96
- }
97
- if (lane & InputContinuousLane) {
98
- return 'InputContinuous';
99
- }
100
- if (lane & DefaultHydrationLane) {
101
- return 'DefaultHydration';
102
- }
103
- if (lane & DefaultLane) {
104
- return 'Default';
105
- }
106
- if (lane & TransitionHydrationLane) {
107
- return 'TransitionHydration';
108
- }
109
- if (lane & TransitionLanes) {
110
- return 'Transition';
111
- }
112
- if (lane & RetryLanes) {
113
- return 'Retry';
114
- }
115
- if (lane & SelectiveHydrationLane) {
116
- return 'SelectiveHydration';
117
- }
118
- if (lane & IdleHydrationLane) {
119
- return 'IdleHydration';
120
- }
121
- if (lane & IdleLane) {
122
- return 'Idle';
123
- }
124
- if (lane & OffscreenLane) {
125
- return 'Offscreen';
126
- }
127
- }
128
-}
129
-
130
-export const NoTimestamp = -1;
131
-
132
-let nextTransitionLane: Lane = TransitionLane1;
133
-let nextRetryLane: Lane = RetryLane1;
134
-
135
-function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes {
136
- switch (getHighestPriorityLane(lanes)) {
137
- case SyncHydrationLane:
138
- return SyncHydrationLane;
139
- case SyncLane:
140
- return SyncLane;
141
- case InputContinuousHydrationLane:
142
- return InputContinuousHydrationLane;
143
- case InputContinuousLane:
144
- return InputContinuousLane;
145
- case DefaultHydrationLane:
146
- return DefaultHydrationLane;
147
- case DefaultLane:
148
- return DefaultLane;
149
- case TransitionHydrationLane:
150
- return TransitionHydrationLane;
151
- case TransitionLane1:
152
- case TransitionLane2:
153
- case TransitionLane3:
154
- case TransitionLane4:
155
- case TransitionLane5:
156
- case TransitionLane6:
157
- case TransitionLane7:
158
- case TransitionLane8:
159
- case TransitionLane9:
160
- case TransitionLane10:
161
- case TransitionLane11:
162
- case TransitionLane12:
163
- case TransitionLane13:
164
- case TransitionLane14:
165
- case TransitionLane15:
166
- case TransitionLane16:
167
- return lanes & TransitionLanes;
168
- case RetryLane1:
169
- case RetryLane2:
170
- case RetryLane3:
171
- case RetryLane4:
172
- return lanes & RetryLanes;
173
- case SelectiveHydrationLane:
174
- return SelectiveHydrationLane;
175
- case IdleHydrationLane:
176
- return IdleHydrationLane;
177
- case IdleLane:
178
- return IdleLane;
179
- case OffscreenLane:
180
- return OffscreenLane;
181
- default:
182
- if (__DEV__) {
183
- console.error(
184
- 'Should have found matching lanes. This is a bug in React.',
185
- );
186
- }
187
- // This shouldn't be reachable, but as a fallback, return the entire bitmask.
188
- return lanes;
189
- }
190
-}
191
-
192
-export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes {
193
- // Early bailout if there's no pending work left.
194
- const pendingLanes = root.pendingLanes;
195
- if (pendingLanes === NoLanes) {
196
- return NoLanes;
197
- }
198
-
199
- let nextLanes = NoLanes;
200
-
201
- const suspendedLanes = root.suspendedLanes;
202
- const pingedLanes = root.pingedLanes;
203
-
204
- // Do not work on any idle work until all the non-idle work has finished,
205
- // even if the work is suspended.
206
- const nonIdlePendingLanes = pendingLanes & NonIdleLanes;
207
- if (nonIdlePendingLanes !== NoLanes) {
208
- const nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
209
- if (nonIdleUnblockedLanes !== NoLanes) {
210
- nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
211
- } else {
212
- const nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
213
- if (nonIdlePingedLanes !== NoLanes) {
214
- nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
215
- }
216
- }
217
- } else {
218
- // The only remaining work is Idle.
219
- const unblockedLanes = pendingLanes & ~suspendedLanes;
220
- if (unblockedLanes !== NoLanes) {
221
- nextLanes = getHighestPriorityLanes(unblockedLanes);
222
- } else {
223
- if (pingedLanes !== NoLanes) {
224
- nextLanes = getHighestPriorityLanes(pingedLanes);
225
- }
226
- }
227
- }
228
-
229
- if (nextLanes === NoLanes) {
230
- // This should only be reachable if we're suspended
231
- // TODO: Consider warning in this path if a fallback timer is not scheduled.
232
- return NoLanes;
233
- }
234
-
235
- // If we're already in the middle of a render, switching lanes will interrupt
236
- // it and we'll lose our progress. We should only do this if the new lanes are
237
- // higher priority.
238
- if (
239
- wipLanes !== NoLanes &&
240
- wipLanes !== nextLanes &&
241
- // If we already suspended with a delay, then interrupting is fine. Don't
242
- // bother waiting until the root is complete.
243
- (wipLanes & suspendedLanes) === NoLanes
244
- ) {
245
- const nextLane = getHighestPriorityLane(nextLanes);
246
- const wipLane = getHighestPriorityLane(wipLanes);
247
- if (
248
- // Tests whether the next lane is equal or lower priority than the wip
249
- // one. This works because the bits decrease in priority as you go left.
250
- nextLane >= wipLane ||
251
- // Default priority updates should not interrupt transition updates. The
252
- // only difference between default updates and transition updates is that
253
- // default updates do not support refresh transitions.
254
- (nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes)
255
- ) {
256
- // Keep working on the existing in-progress tree. Do not interrupt.
257
- return wipLanes;
258
- }
259
- }
260
-
261
- if (
262
- allowConcurrentByDefault &&
263
- (root.current.mode & ConcurrentUpdatesByDefaultMode) !== NoMode
264
- ) {
265
- // Do nothing, use the lanes as they were assigned.
266
- } else if ((nextLanes & InputContinuousLane) !== NoLanes) {
267
- // When updates are sync by default, we entangle continuous priority updates
268
- // and default updates, so they render in the same batch. The only reason
269
- // they use separate lanes is because continuous updates should interrupt
270
- // transitions, but default updates should not.
271
- nextLanes |= pendingLanes & DefaultLane;
272
- }
273
-
274
- // Check for entangled lanes and add them to the batch.
275
- //
276
- // A lane is said to be entangled with another when it's not allowed to render
277
- // in a batch that does not also include the other lane. Typically we do this
278
- // when multiple updates have the same source, and we only want to respond to
279
- // the most recent event from that source.
280
- //
281
- // Note that we apply entanglements *after* checking for partial work above.
282
- // This means that if a lane is entangled during an interleaved event while
283
- // it's already rendering, we won't interrupt it. This is intentional, since
284
- // entanglement is usually "best effort": we'll try our best to render the
285
- // lanes in the same batch, but it's not worth throwing out partially
286
- // completed work in order to do it.
287
- // TODO: Reconsider this. The counter-argument is that the partial work
288
- // represents an intermediate state, which we don't want to show to the user.
289
- // And by spending extra time finishing it, we're increasing the amount of
290
- // time it takes to show the final state, which is what they are actually
291
- // waiting for.
292
- //
293
- // For those exceptions where entanglement is semantically important, like
294
- // useMutableSource, we should ensure that there is no partial work at the
295
- // time we apply the entanglement.
296
- const entangledLanes = root.entangledLanes;
297
- if (entangledLanes !== NoLanes) {
298
- const entanglements = root.entanglements;
299
- let lanes = nextLanes & entangledLanes;
300
- while (lanes > 0) {
301
- const index = pickArbitraryLaneIndex(lanes);
302
- const lane = 1 << index;
303
-
304
- nextLanes |= entanglements[index];
305
-
306
- lanes &= ~lane;
307
- }
308
- }
309
-
310
- return nextLanes;
311
-}
312
-
313
-export function getMostRecentEventTime(root: FiberRoot, lanes: Lanes): number {
314
- const eventTimes = root.eventTimes;
315
-
316
- let mostRecentEventTime = NoTimestamp;
317
- while (lanes > 0) {
318
- const index = pickArbitraryLaneIndex(lanes);
319
- const lane = 1 << index;
320
-
321
- const eventTime = eventTimes[index];
322
- if (eventTime > mostRecentEventTime) {
323
- mostRecentEventTime = eventTime;
324
- }
325
-
326
- lanes &= ~lane;
327
- }
328
-
329
- return mostRecentEventTime;
330
-}
331
-
332
-function computeExpirationTime(lane: Lane, currentTime: number) {
333
- switch (lane) {
334
- case SyncHydrationLane:
335
- case SyncLane:
336
- case InputContinuousHydrationLane:
337
- case InputContinuousLane:
338
- // User interactions should expire slightly more quickly.
339
- //
340
- // NOTE: This is set to the corresponding constant as in Scheduler.js.
341
- // When we made it larger, a product metric in www regressed, suggesting
342
- // there's a user interaction that's being starved by a series of
343
- // synchronous updates. If that theory is correct, the proper solution is
344
- // to fix the starvation. However, this scenario supports the idea that
345
- // expiration times are an important safeguard when starvation
346
- // does happen.
347
- return currentTime + 250;
348
- case DefaultHydrationLane:
349
- case DefaultLane:
350
- case TransitionHydrationLane:
351
- case TransitionLane1:
352
- case TransitionLane2:
353
- case TransitionLane3:
354
- case TransitionLane4:
355
- case TransitionLane5:
356
- case TransitionLane6:
357
- case TransitionLane7:
358
- case TransitionLane8:
359
- case TransitionLane9:
360
- case TransitionLane10:
361
- case TransitionLane11:
362
- case TransitionLane12:
363
- case TransitionLane13:
364
- case TransitionLane14:
365
- case TransitionLane15:
366
- case TransitionLane16:
367
- return currentTime + 5000;
368
- case RetryLane1:
369
- case RetryLane2:
370
- case RetryLane3:
371
- case RetryLane4:
372
- // TODO: Retries should be allowed to expire if they are CPU bound for
373
- // too long, but when I made this change it caused a spike in browser
374
- // crashes. There must be some other underlying bug; not super urgent but
375
- // ideally should figure out why and fix it. Unfortunately we don't have
376
- // a repro for the crashes, only detected via production metrics.
377
- return NoTimestamp;
378
- case SelectiveHydrationLane:
379
- case IdleHydrationLane:
380
- case IdleLane:
381
- case OffscreenLane:
382
- // Anything idle priority or lower should never expire.
383
- return NoTimestamp;
384
- default:
385
- if (__DEV__) {
386
- console.error(
387
- 'Should have found matching lanes. This is a bug in React.',
388
- );
389
- }
390
- return NoTimestamp;
391
- }
392
-}
393
-
394
-export function markStarvedLanesAsExpired(
395
- root: FiberRoot,
396
- currentTime: number,
397
-): void {
398
- // TODO: This gets called every time we yield. We can optimize by storing
399
- // the earliest expiration time on the root. Then use that to quickly bail out
400
- // of this function.
401
-
402
- const pendingLanes = root.pendingLanes;
403
- const suspendedLanes = root.suspendedLanes;
404
- const pingedLanes = root.pingedLanes;
405
- const expirationTimes = root.expirationTimes;
406
-
407
- // Iterate through the pending lanes and check if we've reached their
408
- // expiration time. If so, we'll assume the update is being starved and mark
409
- // it as expired to force it to finish.
410
- //
411
- // We exclude retry lanes because those must always be time sliced, in order
412
- // to unwrap uncached promises.
413
- // TODO: Write a test for this
414
- let lanes = pendingLanes & ~RetryLanes;
415
- while (lanes > 0) {
416
- const index = pickArbitraryLaneIndex(lanes);
417
- const lane = 1 << index;
418
-
419
- const expirationTime = expirationTimes[index];
420
- if (expirationTime === NoTimestamp) {
421
- // Found a pending lane with no expiration time. If it's not suspended, or
422
- // if it's pinged, assume it's CPU-bound. Compute a new expiration time
423
- // using the current time.
424
- if (
425
- (lane & suspendedLanes) === NoLanes ||
426
- (lane & pingedLanes) !== NoLanes
427
- ) {
428
- // Assumes timestamps are monotonically increasing.
429
- expirationTimes[index] = computeExpirationTime(lane, currentTime);
430
- }
431
- } else if (expirationTime <= currentTime) {
432
- // This lane expired
433
- root.expiredLanes |= lane;
434
- }
435
-
436
- lanes &= ~lane;
437
- }
438
-}
439
-
440
-// This returns the highest priority pending lanes regardless of whether they
441
-// are suspended.
442
-export function getHighestPriorityPendingLanes(root: FiberRoot): Lanes {
443
- return getHighestPriorityLanes(root.pendingLanes);
444
-}
445
-
446
-export function getLanesToRetrySynchronouslyOnError(
447
- root: FiberRoot,
448
- originallyAttemptedLanes: Lanes,
449
-): Lanes {
450
- if (root.errorRecoveryDisabledLanes & originallyAttemptedLanes) {
451
- // The error recovery mechanism is disabled until these lanes are cleared.
452
- return NoLanes;
453
- }
454
-
455
- const everythingButOffscreen = root.pendingLanes & ~OffscreenLane;
456
- if (everythingButOffscreen !== NoLanes) {
457
- return everythingButOffscreen;
458
- }
459
- if (everythingButOffscreen & OffscreenLane) {
460
- return OffscreenLane;
461
- }
462
- return NoLanes;
463
-}
464
-
465
-export function includesSyncLane(lanes: Lanes): boolean {
466
- return (lanes & (SyncLane | SyncHydrationLane)) !== NoLanes;
467
-}
468
-
469
-export function includesNonIdleWork(lanes: Lanes): boolean {
470
- return (lanes & NonIdleLanes) !== NoLanes;
471
-}
472
-export function includesOnlyRetries(lanes: Lanes): boolean {
473
- return (lanes & RetryLanes) === lanes;
474
-}
475
-export function includesOnlyNonUrgentLanes(lanes: Lanes): boolean {
476
- // TODO: Should hydration lanes be included here? This function is only
477
- // used in `updateDeferredValueImpl`.
478
- const UrgentLanes = SyncLane | InputContinuousLane | DefaultLane;
479
- return (lanes & UrgentLanes) === NoLanes;
480
-}
481
-export function includesOnlyTransitions(lanes: Lanes): boolean {
482
- return (lanes & TransitionLanes) === lanes;
483
-}
484
-
485
-export function includesBlockingLane(root: FiberRoot, lanes: Lanes): boolean {
486
- if (
487
- allowConcurrentByDefault &&
488
- (root.current.mode & ConcurrentUpdatesByDefaultMode) !== NoMode
489
- ) {
490
- // Concurrent updates by default always use time slicing.
491
- return false;
492
- }
493
- const SyncDefaultLanes =
494
- InputContinuousHydrationLane |
495
- InputContinuousLane |
496
- DefaultHydrationLane |
497
- DefaultLane;
498
- return (lanes & SyncDefaultLanes) !== NoLanes;
499
-}
500
-
501
-export function includesExpiredLane(root: FiberRoot, lanes: Lanes): boolean {
502
- // This is a separate check from includesBlockingLane because a lane can
503
- // expire after a render has already started.
504
- return (lanes & root.expiredLanes) !== NoLanes;
505
-}
506
-
507
-export function isTransitionLane(lane: Lane): boolean {
508
- return (lane & TransitionLanes) !== NoLanes;
509
-}
510
-
511
-export function claimNextTransitionLane(): Lane {
512
- // Cycle through the lanes, assigning each new transition to the next lane.
513
- // In most cases, this means every transition gets its own lane, until we
514
- // run out of lanes and cycle back to the beginning.
515
- const lane = nextTransitionLane;
516
- nextTransitionLane <<= 1;
517
- if ((nextTransitionLane & TransitionLanes) === NoLanes) {
518
- nextTransitionLane = TransitionLane1;
519
- }
520
- return lane;
521
-}
522
-
523
-export function claimNextRetryLane(): Lane {
524
- const lane = nextRetryLane;
525
- nextRetryLane <<= 1;
526
- if ((nextRetryLane & RetryLanes) === NoLanes) {
527
- nextRetryLane = RetryLane1;
528
- }
529
- return lane;
530
-}
531
-
532
-export function getHighestPriorityLane(lanes: Lanes): Lane {
533
- return lanes & -lanes;
534
-}
535
-
536
-export function pickArbitraryLane(lanes: Lanes): Lane {
537
- // This wrapper function gets inlined. Only exists so to communicate that it
538
- // doesn't matter which bit is selected; you can pick any bit without
539
- // affecting the algorithms where its used. Here I'm using
540
- // getHighestPriorityLane because it requires the fewest operations.
541
- return getHighestPriorityLane(lanes);
542
-}
543
-
544
-function pickArbitraryLaneIndex(lanes: Lanes) {
545
- return 31 - clz32(lanes);
546
-}
547
-
548
-function laneToIndex(lane: Lane) {
549
- return pickArbitraryLaneIndex(lane);
550
-}
551
-
552
-export function includesSomeLane(a: Lanes | Lane, b: Lanes | Lane): boolean {
553
- return (a & b) !== NoLanes;
554
-}
555
-
556
-export function isSubsetOfLanes(set: Lanes, subset: Lanes | Lane): boolean {
557
- return (set & subset) === subset;
558
-}
559
-
560
-export function mergeLanes(a: Lanes | Lane, b: Lanes | Lane): Lanes {
561
- return a | b;
562
-}
563
-
564
-export function removeLanes(set: Lanes, subset: Lanes | Lane): Lanes {
565
- return set & ~subset;
566
-}
567
-
568
-export function intersectLanes(a: Lanes | Lane, b: Lanes | Lane): Lanes {
569
- return a & b;
570
-}
571
-
572
-// Seems redundant, but it changes the type from a single lane (used for
573
-// updates) to a group of lanes (used for flushing work).
574
-export function laneToLanes(lane: Lane): Lanes {
575
- return lane;
576
-}
577
-
578
-export function higherPriorityLane(a: Lane, b: Lane): Lane {
579
- // This works because the bit ranges decrease in priority as you go left.
580
- return a !== NoLane && a < b ? a : b;
581
-}
582
-
583
-export function createLaneMap<T>(initial: T): LaneMap<T> {
584
- // Intentionally pushing one by one.
585
- // https://v8.dev/blog/elements-kinds#avoid-creating-holes
586
- const laneMap = [];
587
- for (let i = 0; i < TotalLanes; i++) {
588
- laneMap.push(initial);
589
- }
590
- return laneMap;
591
-}
592
-
593
-export function markRootUpdated(
594
- root: FiberRoot,
595
- updateLane: Lane,
596
- eventTime: number,
597
-) {
598
- root.pendingLanes |= updateLane;
599
-
600
- // If there are any suspended transitions, it's possible this new update
601
- // could unblock them. Clear the suspended lanes so that we can try rendering
602
- // them again.
603
- //
604
- // TODO: We really only need to unsuspend only lanes that are in the
605
- // `subtreeLanes` of the updated fiber, or the update lanes of the return
606
- // path. This would exclude suspended updates in an unrelated sibling tree,
607
- // since there's no way for this update to unblock it.
608
- //
609
- // We don't do this if the incoming update is idle, because we never process
610
- // idle updates until after all the regular updates have finished; there's no
611
- // way it could unblock a transition.
612
- if (updateLane !== IdleLane) {
613
- root.suspendedLanes = NoLanes;
614
- root.pingedLanes = NoLanes;
615
- }
616
-
617
- const eventTimes = root.eventTimes;
618
- const index = laneToIndex(updateLane);
619
- // We can always overwrite an existing timestamp because we prefer the most
620
- // recent event, and we assume time is monotonically increasing.
621
- eventTimes[index] = eventTime;
622
-}
623
-
624
-export function markRootSuspended(root: FiberRoot, suspendedLanes: Lanes) {
625
- root.suspendedLanes |= suspendedLanes;
626
- root.pingedLanes &= ~suspendedLanes;
627
-
628
- // The suspended lanes are no longer CPU-bound. Clear their expiration times.
629
- const expirationTimes = root.expirationTimes;
630
- let lanes = suspendedLanes;
631
- while (lanes > 0) {
632
- const index = pickArbitraryLaneIndex(lanes);
633
- const lane = 1 << index;
634
-
635
- expirationTimes[index] = NoTimestamp;
636
-
637
- lanes &= ~lane;
638
- }
639
-}
640
-
641
-export function markRootPinged(
642
- root: FiberRoot,
643
- pingedLanes: Lanes,
644
- eventTime: number,
645
-) {
646
- root.pingedLanes |= root.suspendedLanes & pingedLanes;
647
-}
648
-
649
-export function markRootMutableRead(root: FiberRoot, updateLane: Lane) {
650
- root.mutableReadLanes |= updateLane & root.pendingLanes;
651
-}
652
-
653
-export function markRootFinished(root: FiberRoot, remainingLanes: Lanes) {
654
- const noLongerPendingLanes = root.pendingLanes & ~remainingLanes;
655
-
656
- root.pendingLanes = remainingLanes;
657
-
658
- // Let's try everything again
659
- root.suspendedLanes = NoLanes;
660
- root.pingedLanes = NoLanes;
661
-
662
- root.expiredLanes &= remainingLanes;
663
- root.mutableReadLanes &= remainingLanes;
664
-
665
- root.entangledLanes &= remainingLanes;
666
-
667
- root.errorRecoveryDisabledLanes &= remainingLanes;
668
-
669
- const entanglements = root.entanglements;
670
- const eventTimes = root.eventTimes;
671
- const expirationTimes = root.expirationTimes;
672
- const hiddenUpdates = root.hiddenUpdates;
673
-
674
- // Clear the lanes that no longer have pending work
675
- let lanes = noLongerPendingLanes;
676
- while (lanes > 0) {
677
- const index = pickArbitraryLaneIndex(lanes);
678
- const lane = 1 << index;
679
-
680
- entanglements[index] = NoLanes;
681
- eventTimes[index] = NoTimestamp;
682
- expirationTimes[index] = NoTimestamp;
683
-
684
- const hiddenUpdatesForLane = hiddenUpdates[index];
685
- if (hiddenUpdatesForLane !== null) {
686
- hiddenUpdates[index] = null;
687
- // "Hidden" updates are updates that were made to a hidden component. They
688
- // have special logic associated with them because they may be entangled
689
- // with updates that occur outside that tree. But once the outer tree
690
- // commits, they behave like regular updates.
691
- for (let i = 0; i < hiddenUpdatesForLane.length; i++) {
692
- const update = hiddenUpdatesForLane[i];
693
- if (update !== null) {
694
- update.lane &= ~OffscreenLane;
695
- }
696
- }
697
- }
698
-
699
- lanes &= ~lane;
700
- }
701
-}
702
-
703
-export function markRootEntangled(root: FiberRoot, entangledLanes: Lanes) {
704
- // In addition to entangling each of the given lanes with each other, we also
705
- // have to consider _transitive_ entanglements. For each lane that is already
706
- // entangled with *any* of the given lanes, that lane is now transitively
707
- // entangled with *all* the given lanes.
708
- //
709
- // Translated: If C is entangled with A, then entangling A with B also
710
- // entangles C with B.
711
- //
712
- // If this is hard to grasp, it might help to intentionally break this
713
- // function and look at the tests that fail in ReactTransition-test.js. Try
714
- // commenting out one of the conditions below.
715
-
716
- const rootEntangledLanes = (root.entangledLanes |= entangledLanes);
717
- const entanglements = root.entanglements;
718
- let lanes = rootEntangledLanes;
719
- while (lanes) {
720
- const index = pickArbitraryLaneIndex(lanes);
721
- const lane = 1 << index;
722
- if (
723
- // Is this one of the newly entangled lanes?
724
- (lane & entangledLanes) |
725
- // Is this lane transitively entangled with the newly entangled lanes?
726
- (entanglements[index] & entangledLanes)
727
- ) {
728
- entanglements[index] |= entangledLanes;
729
- }
730
- lanes &= ~lane;
731
- }
732
-}
733
-
734
-export function markHiddenUpdate(
735
- root: FiberRoot,
736
- update: ConcurrentUpdate,
737
- lane: Lane,
738
-) {
739
- const index = laneToIndex(lane);
740
- const hiddenUpdates = root.hiddenUpdates;
741
- const hiddenUpdatesForLane = hiddenUpdates[index];
742
- if (hiddenUpdatesForLane === null) {
743
- hiddenUpdates[index] = [update];
744
- } else {
745
- hiddenUpdatesForLane.push(update);
746
- }
747
- update.lane = lane | OffscreenLane;
748
-}
749
-
750
-export function getBumpedLaneForHydration(
751
- root: FiberRoot,
752
- renderLanes: Lanes,
753
-): Lane {
754
- const renderLane = getHighestPriorityLane(renderLanes);
755
-
756
- let lane;
757
- switch (renderLane) {
758
- case SyncLane:
759
- lane = SyncHydrationLane;
760
- break;
761
- case InputContinuousLane:
762
- lane = InputContinuousHydrationLane;
763
- break;
764
- case DefaultLane:
765
- lane = DefaultHydrationLane;
766
- break;
767
- case TransitionLane1:
768
- case TransitionLane2:
769
- case TransitionLane3:
770
- case TransitionLane4:
771
- case TransitionLane5:
772
- case TransitionLane6:
773
- case TransitionLane7:
774
- case TransitionLane8:
775
- case TransitionLane9:
776
- case TransitionLane10:
777
- case TransitionLane11:
778
- case TransitionLane12:
779
- case TransitionLane13:
780
- case TransitionLane14:
781
- case TransitionLane15:
782
- case TransitionLane16:
783
- case RetryLane1:
784
- case RetryLane2:
785
- case RetryLane3:
786
- case RetryLane4:
787
- lane = TransitionHydrationLane;
788
- break;
789
- case IdleLane:
790
- lane = IdleHydrationLane;
791
- break;
792
- default:
793
- // Everything else is already either a hydration lane, or shouldn't
794
- // be retried at a hydration lane.
795
- lane = NoLane;
796
- break;
797
- }
798
-
799
- // Check if the lane we chose is suspended. If so, that indicates that we
800
- // already attempted and failed to hydrate at that level. Also check if we're
801
- // already rendering that lane, which is rare but could happen.
802
- if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) {
803
- // Give up trying to hydrate and fall back to client render.
804
- return NoLane;
805
- }
806
-
807
- return lane;
808
-}
809
-
810
-export function addFiberToLanesMap(
811
- root: FiberRoot,
812
- fiber: Fiber,
813
- lanes: Lanes | Lane,
814
-) {
815
- if (!enableUpdaterTracking) {
816
- return;
817
- }
818
- if (!isDevToolsPresent) {
819
- return;
820
- }
821
- const pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
822
- while (lanes > 0) {
823
- const index = laneToIndex(lanes);
824
- const lane = 1 << index;
825
-
826
- const updaters = pendingUpdatersLaneMap[index];
827
- updaters.add(fiber);
828
-
829
- lanes &= ~lane;
830
- }
831
-}
832
-
833
-export function movePendingFibersToMemoized(root: FiberRoot, lanes: Lanes) {
834
- if (!enableUpdaterTracking) {
835
- return;
836
- }
837
- if (!isDevToolsPresent) {
838
- return;
839
- }
840
- const pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
841
- const memoizedUpdaters = root.memoizedUpdaters;
842
- while (lanes > 0) {
843
- const index = laneToIndex(lanes);
844
- const lane = 1 << index;
845
-
846
- const updaters = pendingUpdatersLaneMap[index];
847
- if (updaters.size > 0) {
848
- updaters.forEach(fiber => {
849
- const alternate = fiber.alternate;
850
- if (alternate === null || !memoizedUpdaters.has(alternate)) {
851
- memoizedUpdaters.add(fiber);
852
- }
853
- });
854
- updaters.clear();
855
- }
856
-
857
- lanes &= ~lane;
858
- }
859
-}
860
-
861
-export function addTransitionToLanesMap(
862
- root: FiberRoot,
863
- transition: Transition,
864
- lane: Lane,
865
-) {
866
- if (enableTransitionTracing) {
867
- const transitionLanesMap = root.transitionLanes;
868
- const index = laneToIndex(lane);
869
- let transitions = transitionLanesMap[index];
870
- if (transitions === null) {
871
- transitions = new Set();
872
- }
873
- transitions.add(transition);
874
-
875
- transitionLanesMap[index] = transitions;
876
- }
877
-}
878
-
879
-export function getTransitionsForLanes(
880
- root: FiberRoot,
881
- lanes: Lane | Lanes,
882
-): Array<Transition> | null {
883
- if (!enableTransitionTracing) {
884
- return null;
885
- }
886
-
887
- const transitionsForLanes = [];
888
- while (lanes > 0) {
889
- const index = laneToIndex(lanes);
890
- const lane = 1 << index;
891
- const transitions = root.transitionLanes[index];
892
- if (transitions !== null) {
893
- transitions.forEach(transition => {
894
- transitionsForLanes.push(transition);
895
- });
896
- }
897
-
898
- lanes &= ~lane;
899
- }
900
-
901
- if (transitionsForLanes.length === 0) {
902
- return null;
903
- }
904
-
905
- return transitionsForLanes;
906
-}
907
-
908
-export function clearTransitionsForLanes(root: FiberRoot, lanes: Lane | Lanes) {
909
- if (!enableTransitionTracing) {
910
- return;
911
- }
912
-
913
- while (lanes > 0) {
914
- const index = laneToIndex(lanes);
915
- const lane = 1 << index;
916
-
917
- const transitions = root.transitionLanes[index];
918
- if (transitions !== null) {
919
- root.transitionLanes[index] = null;
920
- }
921
-
922
- lanes &= ~lane;
923
- }
924
-}
packages/react-reconciler/src/ReactFiberLazyComponent.new.js
deleted
-25
@@ -1,25 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import assign from 'shared/assign';
11
-
12
-export function resolveDefaultProps(Component: any, baseProps: Object): Object {
13
- if (Component && Component.defaultProps) {
14
- // Resolve default props. Taken from ReactElement
15
- const props = assign({}, baseProps);
16
- const defaultProps = Component.defaultProps;
17
- for (const propName in defaultProps) {
18
- if (props[propName] === undefined) {
19
- props[propName] = defaultProps[propName];
20
- }
21
- }
22
- return props;
23
- }
24
- return baseProps;
25
-}
packages/react-reconciler/src/ReactFiberNewContext.new.js
deleted
-706
@@ -1,706 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {ReactContext, ReactProviderType} from 'shared/ReactTypes';
11
-import type {
12
- Fiber,
13
- ContextDependency,
14
- Dependencies,
15
-} from './ReactInternalTypes';
16
-import type {StackCursor} from './ReactFiberStack.new';
17
-import type {Lanes} from './ReactFiberLane.new';
18
-import type {SharedQueue} from './ReactFiberClassUpdateQueue.new';
19
-
20
-import {isPrimaryRenderer} from './ReactFiberHostConfig';
21
-import {createCursor, push, pop} from './ReactFiberStack.new';
22
-import {
23
- ContextProvider,
24
- ClassComponent,
25
- DehydratedFragment,
26
-} from './ReactWorkTags';
27
-import {
28
- NoLanes,
29
- NoTimestamp,
30
- isSubsetOfLanes,
31
- includesSomeLane,
32
- mergeLanes,
33
- pickArbitraryLane,
34
-} from './ReactFiberLane.new';
35
-import {
36
- NoFlags,
37
- DidPropagateContext,
38
- NeedsPropagation,
39
-} from './ReactFiberFlags';
40
-
41
-import is from 'shared/objectIs';
42
-import {createUpdate, ForceUpdate} from './ReactFiberClassUpdateQueue.new';
43
-import {markWorkInProgressReceivedUpdate} from './ReactFiberBeginWork.new';
44
-import {
45
- enableLazyContextPropagation,
46
- enableServerContext,
47
-} from 'shared/ReactFeatureFlags';
48
-import {REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED} from 'shared/ReactSymbols';
49
-
50
-const valueCursor: StackCursor<mixed> = createCursor(null);
51
-
52
-let rendererSigil;
53
-if (__DEV__) {
54
- // Use this to detect multiple renderers using the same context
55
- rendererSigil = {};
56
-}
57
-
58
-let currentlyRenderingFiber: Fiber | null = null;
59
-let lastContextDependency: ContextDependency<mixed> | null = null;
60
-let lastFullyObservedContext: ReactContext<any> | null = null;
61
-
62
-let isDisallowedContextReadInDEV: boolean = false;
63
-
64
-export function resetContextDependencies(): void {
65
- // This is called right before React yields execution, to ensure `readContext`
66
- // cannot be called outside the render phase.
67
- currentlyRenderingFiber = null;
68
- lastContextDependency = null;
69
- lastFullyObservedContext = null;
70
- if (__DEV__) {
71
- isDisallowedContextReadInDEV = false;
72
- }
73
-}
74
-
75
-export function enterDisallowedContextReadInDEV(): void {
76
- if (__DEV__) {
77
- isDisallowedContextReadInDEV = true;
78
- }
79
-}
80
-
81
-export function exitDisallowedContextReadInDEV(): void {
82
- if (__DEV__) {
83
- isDisallowedContextReadInDEV = false;
84
- }
85
-}
86
-
87
-export function pushProvider<T>(
88
- providerFiber: Fiber,
89
- context: ReactContext<T>,
90
- nextValue: T,
91
-): void {
92
- if (isPrimaryRenderer) {
93
- push(valueCursor, context._currentValue, providerFiber);
94
-
95
- context._currentValue = nextValue;
96
- if (__DEV__) {
97
- if (
98
- context._currentRenderer !== undefined &&
99
- context._currentRenderer !== null &&
100
- context._currentRenderer !== rendererSigil
101
- ) {
102
- console.error(
103
- 'Detected multiple renderers concurrently rendering the ' +
104
- 'same context provider. This is currently unsupported.',
105
- );
106
- }
107
- context._currentRenderer = rendererSigil;
108
- }
109
- } else {
110
- push(valueCursor, context._currentValue2, providerFiber);
111
-
112
- context._currentValue2 = nextValue;
113
- if (__DEV__) {
114
- if (
115
- context._currentRenderer2 !== undefined &&
116
- context._currentRenderer2 !== null &&
117
- context._currentRenderer2 !== rendererSigil
118
- ) {
119
- console.error(
120
- 'Detected multiple renderers concurrently rendering the ' +
121
- 'same context provider. This is currently unsupported.',
122
- );
123
- }
124
- context._currentRenderer2 = rendererSigil;
125
- }
126
- }
127
-}
128
-
129
-export function popProvider(
130
- context: ReactContext<any>,
131
- providerFiber: Fiber,
132
-): void {
133
- const currentValue = valueCursor.current;
134
- pop(valueCursor, providerFiber);
135
- if (isPrimaryRenderer) {
136
- if (
137
- enableServerContext &&
138
- currentValue === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED
139
- ) {
140
- context._currentValue = context._defaultValue;
141
- } else {
142
- context._currentValue = currentValue;
143
- }
144
- } else {
145
- if (
146
- enableServerContext &&
147
- currentValue === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED
148
- ) {
149
- context._currentValue2 = context._defaultValue;
150
- } else {
151
- context._currentValue2 = currentValue;
152
- }
153
- }
154
-}
155
-
156
-export function scheduleContextWorkOnParentPath(
157
- parent: Fiber | null,
158
- renderLanes: Lanes,
159
- propagationRoot: Fiber,
160
-) {
161
- // Update the child lanes of all the ancestors, including the alternates.
162
- let node = parent;
163
- while (node !== null) {
164
- const alternate = node.alternate;
165
- if (!isSubsetOfLanes(node.childLanes, renderLanes)) {
166
- node.childLanes = mergeLanes(node.childLanes, renderLanes);
167
- if (alternate !== null) {
168
- alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
169
- }
170
- } else if (
171
- alternate !== null &&
172
- !isSubsetOfLanes(alternate.childLanes, renderLanes)
173
- ) {
174
- alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
175
- } else {
176
- // Neither alternate was updated.
177
- // Normally, this would mean that the rest of the
178
- // ancestor path already has sufficient priority.
179
- // However, this is not necessarily true inside offscreen
180
- // or fallback trees because childLanes may be inconsistent
181
- // with the surroundings. This is why we continue the loop.
182
- }
183
- if (node === propagationRoot) {
184
- break;
185
- }
186
- node = node.return;
187
- }
188
- if (__DEV__) {
189
- if (node !== propagationRoot) {
190
- console.error(
191
- 'Expected to find the propagation root when scheduling context work. ' +
192
- 'This error is likely caused by a bug in React. Please file an issue.',
193
- );
194
- }
195
- }
196
-}
197
-
198
-export function propagateContextChange<T>(
199
- workInProgress: Fiber,
200
- context: ReactContext<T>,
201
- renderLanes: Lanes,
202
-): void {
203
- if (enableLazyContextPropagation) {
204
- // TODO: This path is only used by Cache components. Update
205
- // lazilyPropagateParentContextChanges to look for Cache components so they
206
- // can take advantage of lazy propagation.
207
- const forcePropagateEntireTree = true;
208
- propagateContextChanges(
209
- workInProgress,
210
- [context],
211
- renderLanes,
212
- forcePropagateEntireTree,
213
- );
214
- } else {
215
- propagateContextChange_eager(workInProgress, context, renderLanes);
216
- }
217
-}
218
-
219
-function propagateContextChange_eager<T>(
220
- workInProgress: Fiber,
221
- context: ReactContext<T>,
222
- renderLanes: Lanes,
223
-): void {
224
- // Only used by eager implementation
225
- if (enableLazyContextPropagation) {
226
- return;
227
- }
228
- let fiber = workInProgress.child;
229
- if (fiber !== null) {
230
- // Set the return pointer of the child to the work-in-progress fiber.
231
- fiber.return = workInProgress;
232
- }
233
- while (fiber !== null) {
234
- let nextFiber;
235
-
236
- // Visit this fiber.
237
- const list = fiber.dependencies;
238
- if (list !== null) {
239
- nextFiber = fiber.child;
240
-
241
- let dependency = list.firstContext;
242
- while (dependency !== null) {
243
- // Check if the context matches.
244
- if (dependency.context === context) {
245
- // Match! Schedule an update on this fiber.
246
- if (fiber.tag === ClassComponent) {
247
- // Schedule a force update on the work-in-progress.
248
- const lane = pickArbitraryLane(renderLanes);
249
- const update = createUpdate(NoTimestamp, lane);
250
- update.tag = ForceUpdate;
251
- // TODO: Because we don't have a work-in-progress, this will add the
252
- // update to the current fiber, too, which means it will persist even if
253
- // this render is thrown away. Since it's a race condition, not sure it's
254
- // worth fixing.
255
-
256
- // Inlined `enqueueUpdate` to remove interleaved update check
257
- const updateQueue = fiber.updateQueue;
258
- if (updateQueue === null) {
259
- // Only occurs if the fiber has been unmounted.
260
- } else {
261
- const sharedQueue: SharedQueue<any> = (updateQueue: any).shared;
262
- const pending = sharedQueue.pending;
263
- if (pending === null) {
264
- // This is the first update. Create a circular list.
265
- update.next = update;
266
- } else {
267
- update.next = pending.next;
268
- pending.next = update;
269
- }
270
- sharedQueue.pending = update;
271
- }
272
- }
273
-
274
- fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
275
- const alternate = fiber.alternate;
276
- if (alternate !== null) {
277
- alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
278
- }
279
- scheduleContextWorkOnParentPath(
280
- fiber.return,
281
- renderLanes,
282
- workInProgress,
283
- );
284
-
285
- // Mark the updated lanes on the list, too.
286
- list.lanes = mergeLanes(list.lanes, renderLanes);
287
-
288
- // Since we already found a match, we can stop traversing the
289
- // dependency list.
290
- break;
291
- }
292
- dependency = dependency.next;
293
- }
294
- } else if (fiber.tag === ContextProvider) {
295
- // Don't scan deeper if this is a matching provider
296
- nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
297
- } else if (fiber.tag === DehydratedFragment) {
298
- // If a dehydrated suspense boundary is in this subtree, we don't know
299
- // if it will have any context consumers in it. The best we can do is
300
- // mark it as having updates.
301
- const parentSuspense = fiber.return;
302
-
303
- if (parentSuspense === null) {
304
- throw new Error(
305
- 'We just came from a parent so we must have had a parent. This is a bug in React.',
306
- );
307
- }
308
-
309
- parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes);
310
- const alternate = parentSuspense.alternate;
311
- if (alternate !== null) {
312
- alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
313
- }
314
- // This is intentionally passing this fiber as the parent
315
- // because we want to schedule this fiber as having work
316
- // on its children. We'll use the childLanes on
317
- // this fiber to indicate that a context has changed.
318
- scheduleContextWorkOnParentPath(
319
- parentSuspense,
320
- renderLanes,
321
- workInProgress,
322
- );
323
- nextFiber = fiber.sibling;
324
- } else {
325
- // Traverse down.
326
- nextFiber = fiber.child;
327
- }
328
-
329
- if (nextFiber !== null) {
330
- // Set the return pointer of the child to the work-in-progress fiber.
331
- nextFiber.return = fiber;
332
- } else {
333
- // No child. Traverse to next sibling.
334
- nextFiber = fiber;
335
- while (nextFiber !== null) {
336
- if (nextFiber === workInProgress) {
337
- // We're back to the root of this subtree. Exit.
338
- nextFiber = null;
339
- break;
340
- }
341
- const sibling = nextFiber.sibling;
342
- if (sibling !== null) {
343
- // Set the return pointer of the sibling to the work-in-progress fiber.
344
- sibling.return = nextFiber.return;
345
- nextFiber = sibling;
346
- break;
347
- }
348
- // No more siblings. Traverse up.
349
- nextFiber = nextFiber.return;
350
- }
351
- }
352
- fiber = nextFiber;
353
- }
354
-}
355
-
356
-function propagateContextChanges<T>(
357
- workInProgress: Fiber,
358
- contexts: Array<any>,
359
- renderLanes: Lanes,
360
- forcePropagateEntireTree: boolean,
361
-): void {
362
- // Only used by lazy implementation
363
- if (!enableLazyContextPropagation) {
364
- return;
365
- }
366
- let fiber = workInProgress.child;
367
- if (fiber !== null) {
368
- // Set the return pointer of the child to the work-in-progress fiber.
369
- fiber.return = workInProgress;
370
- }
371
- while (fiber !== null) {
372
- let nextFiber;
373
-
374
- // Visit this fiber.
375
- const list = fiber.dependencies;
376
- if (list !== null) {
377
- nextFiber = fiber.child;
378
-
379
- let dep = list.firstContext;
380
- findChangedDep: while (dep !== null) {
381
- // Assigning these to constants to help Flow
382
- const dependency = dep;
383
- const consumer = fiber;
384
- findContext: for (let i = 0; i < contexts.length; i++) {
385
- const context: ReactContext<T> = contexts[i];
386
- // Check if the context matches.
387
- // TODO: Compare selected values to bail out early.
388
- if (dependency.context === context) {
389
- // Match! Schedule an update on this fiber.
390
-
391
- // In the lazy implementation, don't mark a dirty flag on the
392
- // dependency itself. Not all changes are propagated, so we can't
393
- // rely on the propagation function alone to determine whether
394
- // something has changed; the consumer will check. In the future, we
395
- // could add back a dirty flag as an optimization to avoid double
396
- // checking, but until we have selectors it's not really worth
397
- // the trouble.
398
- consumer.lanes = mergeLanes(consumer.lanes, renderLanes);
399
- const alternate = consumer.alternate;
400
- if (alternate !== null) {
401
- alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
402
- }
403
- scheduleContextWorkOnParentPath(
404
- consumer.return,
405
- renderLanes,
406
- workInProgress,
407
- );
408
-
409
- if (!forcePropagateEntireTree) {
410
- // During lazy propagation, when we find a match, we can defer
411
- // propagating changes to the children, because we're going to
412
- // visit them during render. We should continue propagating the
413
- // siblings, though
414
- nextFiber = null;
415
- }
416
-
417
- // Since we already found a match, we can stop traversing the
418
- // dependency list.
419
- break findChangedDep;
420
- }
421
- }
422
- dep = dependency.next;
423
- }
424
- } else if (fiber.tag === DehydratedFragment) {
425
- // If a dehydrated suspense boundary is in this subtree, we don't know
426
- // if it will have any context consumers in it. The best we can do is
427
- // mark it as having updates.
428
- const parentSuspense = fiber.return;
429
-
430
- if (parentSuspense === null) {
431
- throw new Error(
432
- 'We just came from a parent so we must have had a parent. This is a bug in React.',
433
- );
434
- }
435
-
436
- parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes);
437
- const alternate = parentSuspense.alternate;
438
- if (alternate !== null) {
439
- alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
440
- }
441
- // This is intentionally passing this fiber as the parent
442
- // because we want to schedule this fiber as having work
443
- // on its children. We'll use the childLanes on
444
- // this fiber to indicate that a context has changed.
445
- scheduleContextWorkOnParentPath(
446
- parentSuspense,
447
- renderLanes,
448
- workInProgress,
449
- );
450
- nextFiber = null;
451
- } else {
452
- // Traverse down.
453
- nextFiber = fiber.child;
454
- }
455
-
456
- if (nextFiber !== null) {
457
- // Set the return pointer of the child to the work-in-progress fiber.
458
- nextFiber.return = fiber;
459
- } else {
460
- // No child. Traverse to next sibling.
461
- nextFiber = fiber;
462
- while (nextFiber !== null) {
463
- if (nextFiber === workInProgress) {
464
- // We're back to the root of this subtree. Exit.
465
- nextFiber = null;
466
- break;
467
- }
468
- const sibling = nextFiber.sibling;
469
- if (sibling !== null) {
470
- // Set the return pointer of the sibling to the work-in-progress fiber.
471
- sibling.return = nextFiber.return;
472
- nextFiber = sibling;
473
- break;
474
- }
475
- // No more siblings. Traverse up.
476
- nextFiber = nextFiber.return;
477
- }
478
- }
479
- fiber = nextFiber;
480
- }
481
-}
482
-
483
-export function lazilyPropagateParentContextChanges(
484
- current: Fiber,
485
- workInProgress: Fiber,
486
- renderLanes: Lanes,
487
-) {
488
- const forcePropagateEntireTree = false;
489
- propagateParentContextChanges(
490
- current,
491
- workInProgress,
492
- renderLanes,
493
- forcePropagateEntireTree,
494
- );
495
-}
496
-
497
-// Used for propagating a deferred tree (Suspense, Offscreen). We must propagate
498
-// to the entire subtree, because we won't revisit it until after the current
499
-// render has completed, at which point we'll have lost track of which providers
500
-// have changed.
501
-export function propagateParentContextChangesToDeferredTree(
502
- current: Fiber,
503
- workInProgress: Fiber,
504
- renderLanes: Lanes,
505
-) {
506
- const forcePropagateEntireTree = true;
507
- propagateParentContextChanges(
508
- current,
509
- workInProgress,
510
- renderLanes,
511
- forcePropagateEntireTree,
512
- );
513
-}
514
-
515
-function propagateParentContextChanges(
516
- current: Fiber,
517
- workInProgress: Fiber,
518
- renderLanes: Lanes,
519
- forcePropagateEntireTree: boolean,
520
-) {
521
- if (!enableLazyContextPropagation) {
522
- return;
523
- }
524
-
525
- // Collect all the parent providers that changed. Since this is usually small
526
- // number, we use an Array instead of Set.
527
- let contexts = null;
528
- let parent: null | Fiber = workInProgress;
529
- let isInsidePropagationBailout = false;
530
- while (parent !== null) {
531
- if (!isInsidePropagationBailout) {
532
- if ((parent.flags & NeedsPropagation) !== NoFlags) {
533
- isInsidePropagationBailout = true;
534
- } else if ((parent.flags & DidPropagateContext) !== NoFlags) {
535
- break;
536
- }
537
- }
538
-
539
- if (parent.tag === ContextProvider) {
540
- const currentParent = parent.alternate;
541
-
542
- if (currentParent === null) {
543
- throw new Error('Should have a current fiber. This is a bug in React.');
544
- }
545
-
546
- const oldProps = currentParent.memoizedProps;
547
- if (oldProps !== null) {
548
- const providerType: ReactProviderType<any> = parent.type;
549
- const context: ReactContext<any> = providerType._context;
550
-
551
- const newProps = parent.pendingProps;
552
- const newValue = newProps.value;
553
-
554
- const oldValue = oldProps.value;
555
-
556
- if (!is(newValue, oldValue)) {
557
- if (contexts !== null) {
558
- contexts.push(context);
559
- } else {
560
- contexts = [context];
561
- }
562
- }
563
- }
564
- }
565
- parent = parent.return;
566
- }
567
-
568
- if (contexts !== null) {
569
- // If there were any changed providers, search through the children and
570
- // propagate their changes.
571
- propagateContextChanges(
572
- workInProgress,
573
- contexts,
574
- renderLanes,
575
- forcePropagateEntireTree,
576
- );
577
- }
578
-
579
- // This is an optimization so that we only propagate once per subtree. If a
580
- // deeply nested child bails out, and it calls this propagation function, it
581
- // uses this flag to know that the remaining ancestor providers have already
582
- // been propagated.
583
- //
584
- // NOTE: This optimization is only necessary because we sometimes enter the
585
- // begin phase of nodes that don't have any work scheduled on them —
586
- // specifically, the siblings of a node that _does_ have scheduled work. The
587
- // siblings will bail out and call this function again, even though we already
588
- // propagated content changes to it and its subtree. So we use this flag to
589
- // mark that the parent providers already propagated.
590
- //
591
- // Unfortunately, though, we need to ignore this flag when we're inside a
592
- // tree whose context propagation was deferred — that's what the
593
- // `NeedsPropagation` flag is for.
594
- //
595
- // If we could instead bail out before entering the siblings' begin phase,
596
- // then we could remove both `DidPropagateContext` and `NeedsPropagation`.
597
- // Consider this as part of the next refactor to the fiber tree structure.
598
- workInProgress.flags |= DidPropagateContext;
599
-}
600
-
601
-export function checkIfContextChanged(
602
- currentDependencies: Dependencies,
603
-): boolean {
604
- if (!enableLazyContextPropagation) {
605
- return false;
606
- }
607
- // Iterate over the current dependencies to see if something changed. This
608
- // only gets called if props and state has already bailed out, so it's a
609
- // relatively uncommon path, except at the root of a changed subtree.
610
- // Alternatively, we could move these comparisons into `readContext`, but
611
- // that's a much hotter path, so I think this is an appropriate trade off.
612
- let dependency = currentDependencies.firstContext;
613
- while (dependency !== null) {
614
- const context = dependency.context;
615
- const newValue = isPrimaryRenderer
616
- ? context._currentValue
617
- : context._currentValue2;
618
- const oldValue = dependency.memoizedValue;
619
- if (!is(newValue, oldValue)) {
620
- return true;
621
- }
622
- dependency = dependency.next;
623
- }
624
- return false;
625
-}
626
-
627
-export function prepareToReadContext(
628
- workInProgress: Fiber,
629
- renderLanes: Lanes,
630
-): void {
631
- currentlyRenderingFiber = workInProgress;
632
- lastContextDependency = null;
633
- lastFullyObservedContext = null;
634
-
635
- const dependencies = workInProgress.dependencies;
636
- if (dependencies !== null) {
637
- if (enableLazyContextPropagation) {
638
- // Reset the work-in-progress list
639
- dependencies.firstContext = null;
640
- } else {
641
- const firstContext = dependencies.firstContext;
642
- if (firstContext !== null) {
643
- if (includesSomeLane(dependencies.lanes, renderLanes)) {
644
- // Context list has a pending update. Mark that this fiber performed work.
645
- markWorkInProgressReceivedUpdate();
646
- }
647
- // Reset the work-in-progress list
648
- dependencies.firstContext = null;
649
- }
650
- }
651
- }
652
-}
653
-
654
-export function readContext<T>(context: ReactContext<T>): T {
655
- if (__DEV__) {
656
- // This warning would fire if you read context inside a Hook like useMemo.
657
- // Unlike the class check below, it's not enforced in production for perf.
658
- if (isDisallowedContextReadInDEV) {
659
- console.error(
660
- 'Context can only be read while React is rendering. ' +
661
- 'In classes, you can read it in the render method or getDerivedStateFromProps. ' +
662
- 'In function components, you can read it directly in the function body, but not ' +
663
- 'inside Hooks like useReducer() or useMemo().',
664
- );
665
- }
666
- }
667
-
668
- const value = isPrimaryRenderer
669
- ? context._currentValue
670
- : context._currentValue2;
671
-
672
- if (lastFullyObservedContext === context) {
673
- // Nothing to do. We already observe everything in this context.
674
- } else {
675
- const contextItem = {
676
- context: ((context: any): ReactContext<mixed>),
677
- memoizedValue: value,
678
- next: null,
679
- };
680
-
681
- if (lastContextDependency === null) {
682
- if (currentlyRenderingFiber === null) {
683
- throw new Error(
684
- 'Context can only be read while React is rendering. ' +
685
- 'In classes, you can read it in the render method or getDerivedStateFromProps. ' +
686
- 'In function components, you can read it directly in the function body, but not ' +
687
- 'inside Hooks like useReducer() or useMemo().',
688
- );
689
- }
690
-
691
- // This is the first dependency for this component. Create a new list.
692
- lastContextDependency = contextItem;
693
- currentlyRenderingFiber.dependencies = {
694
- lanes: NoLanes,
695
- firstContext: contextItem,
696
- };
697
- if (enableLazyContextPropagation) {
698
- currentlyRenderingFiber.flags |= NeedsPropagation;
699
- }
700
- } else {
701
- // Append a new context item.
702
- lastContextDependency = lastContextDependency.next = contextItem;
703
- }
704
- }
705
- return value;
706
-}
packages/react-reconciler/src/ReactFiberOffscreenComponent.js
+2
-2
@@ -9,12 +9,12 @@
9
10
import type {ReactNodeList, OffscreenMode, Wakeable} from 'shared/ReactTypes';
11
import type {Lanes} from './ReactFiberLane.old';
12
-import type {SpawnedCachePool} from './ReactFiberCacheComponent.new';
12
+import type {SpawnedCachePool} from './ReactFiberCacheComponent.old';
13
import type {Fiber} from './ReactInternalTypes';
14
import type {
15
Transition,
16
TracingMarkerInstance,
17
-} from './ReactFiberTracingMarkerComponent.new';
17
+} from './ReactFiberTracingMarkerComponent.old';
18
19
export type OffscreenProps = {
20
// TODO: Pick an API before exposing the Offscreen type. I've chosen an enum
packages/react-reconciler/src/ReactFiberReconciler.js
deleted
-202
@@ -1,202 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import {enableNewReconciler} from 'shared/ReactFeatureFlags';
11
-
12
-// The entry file imports either the old or new version of the reconciler.
13
-// During build and testing, this indirection is always shimmed with the actual
14
-// modules, otherwise both reconcilers would be initialized. So this is really
15
-// only here for Flow purposes.
16
-
17
-import {
18
- createContainer as createContainer_old,
19
- createHydrationContainer as createHydrationContainer_old,
20
- updateContainer as updateContainer_old,
21
- batchedUpdates as batchedUpdates_old,
22
- deferredUpdates as deferredUpdates_old,
23
- discreteUpdates as discreteUpdates_old,
24
- flushControlled as flushControlled_old,
25
- flushSync as flushSync_old,
26
- isAlreadyRendering as isAlreadyRendering_old,
27
- flushPassiveEffects as flushPassiveEffects_old,
28
- getPublicRootInstance as getPublicRootInstance_old,
29
- attemptSynchronousHydration as attemptSynchronousHydration_old,
30
- attemptDiscreteHydration as attemptDiscreteHydration_old,
31
- attemptContinuousHydration as attemptContinuousHydration_old,
32
- attemptHydrationAtCurrentPriority as attemptHydrationAtCurrentPriority_old,
33
- findHostInstance as findHostInstance_old,
34
- findHostInstanceWithWarning as findHostInstanceWithWarning_old,
35
- findHostInstanceWithNoPortals as findHostInstanceWithNoPortals_old,
36
- shouldError as shouldError_old,
37
- shouldSuspend as shouldSuspend_old,
38
- injectIntoDevTools as injectIntoDevTools_old,
39
- createPortal as createPortal_old,
40
- createComponentSelector as createComponentSelector_old,
41
- createHasPseudoClassSelector as createHasPseudoClassSelector_old,
42
- createRoleSelector as createRoleSelector_old,
43
- createTestNameSelector as createTestNameSelector_old,
44
- createTextSelector as createTextSelector_old,
45
- getFindAllNodesFailureDescription as getFindAllNodesFailureDescription_old,
46
- findAllNodes as findAllNodes_old,
47
- findBoundingRects as findBoundingRects_old,
48
- focusWithin as focusWithin_old,
49
- observeVisibleRects as observeVisibleRects_old,
50
- registerMutableSourceForHydration as registerMutableSourceForHydration_old,
51
- runWithPriority as runWithPriority_old,
52
- getCurrentUpdatePriority as getCurrentUpdatePriority_old,
53
-} from './ReactFiberReconciler.old';
54
-
55
-import {
56
- createContainer as createContainer_new,
57
- createHydrationContainer as createHydrationContainer_new,
58
- updateContainer as updateContainer_new,
59
- batchedUpdates as batchedUpdates_new,
60
- deferredUpdates as deferredUpdates_new,
61
- discreteUpdates as discreteUpdates_new,
62
- flushControlled as flushControlled_new,
63
- flushSync as flushSync_new,
64
- isAlreadyRendering as isAlreadyRendering_new,
65
- flushPassiveEffects as flushPassiveEffects_new,
66
- getPublicRootInstance as getPublicRootInstance_new,
67
- attemptSynchronousHydration as attemptSynchronousHydration_new,
68
- attemptDiscreteHydration as attemptDiscreteHydration_new,
69
- attemptContinuousHydration as attemptContinuousHydration_new,
70
- attemptHydrationAtCurrentPriority as attemptHydrationAtCurrentPriority_new,
71
- findHostInstance as findHostInstance_new,
72
- findHostInstanceWithWarning as findHostInstanceWithWarning_new,
73
- findHostInstanceWithNoPortals as findHostInstanceWithNoPortals_new,
74
- shouldError as shouldError_new,
75
- shouldSuspend as shouldSuspend_new,
76
- injectIntoDevTools as injectIntoDevTools_new,
77
- createPortal as createPortal_new,
78
- createComponentSelector as createComponentSelector_new,
79
- createHasPseudoClassSelector as createHasPseudoClassSelector_new,
80
- createRoleSelector as createRoleSelector_new,
81
- createTestNameSelector as createTestNameSelector_new,
82
- createTextSelector as createTextSelector_new,
83
- getFindAllNodesFailureDescription as getFindAllNodesFailureDescription_new,
84
- findAllNodes as findAllNodes_new,
85
- findBoundingRects as findBoundingRects_new,
86
- focusWithin as focusWithin_new,
87
- observeVisibleRects as observeVisibleRects_new,
88
- registerMutableSourceForHydration as registerMutableSourceForHydration_new,
89
- runWithPriority as runWithPriority_new,
90
- getCurrentUpdatePriority as getCurrentUpdatePriority_new,
91
-} from './ReactFiberReconciler.new';
92
-
93
-export const createContainer: typeof createContainer_new = enableNewReconciler
94
- ? createContainer_new
95
- : createContainer_old;
96
-export const createHydrationContainer: typeof createHydrationContainer_new = enableNewReconciler
97
- ? createHydrationContainer_new
98
- : createHydrationContainer_old;
99
-export const updateContainer: typeof updateContainer_new = enableNewReconciler
100
- ? updateContainer_new
101
- : updateContainer_old;
102
-export const batchedUpdates: typeof batchedUpdates_new = enableNewReconciler
103
- ? batchedUpdates_new
104
- : batchedUpdates_old;
105
-export const deferredUpdates: typeof deferredUpdates_new = enableNewReconciler
106
- ? deferredUpdates_new
107
- : deferredUpdates_old;
108
-export const discreteUpdates: typeof discreteUpdates_new = enableNewReconciler
109
- ? discreteUpdates_new
110
- : discreteUpdates_old;
111
-export const flushControlled: typeof flushControlled_new = enableNewReconciler
112
- ? flushControlled_new
113
- : flushControlled_old;
114
-export const flushSync: typeof flushSync_new = enableNewReconciler
115
- ? flushSync_new
116
- : flushSync_old;
117
-export const isAlreadyRendering: typeof isAlreadyRendering_new = enableNewReconciler
118
- ? isAlreadyRendering_new
119
- : isAlreadyRendering_old;
120
-export const flushPassiveEffects: typeof flushPassiveEffects_new = enableNewReconciler
121
- ? flushPassiveEffects_new
122
- : flushPassiveEffects_old;
123
-export const getPublicRootInstance: typeof getPublicRootInstance_new = enableNewReconciler
124
- ? getPublicRootInstance_new
125
- : getPublicRootInstance_old;
126
-export const attemptSynchronousHydration: typeof attemptSynchronousHydration_new = enableNewReconciler
127
- ? attemptSynchronousHydration_new
128
- : attemptSynchronousHydration_old;
129
-export const attemptDiscreteHydration: typeof attemptDiscreteHydration_new = enableNewReconciler
130
- ? attemptDiscreteHydration_new
131
- : attemptDiscreteHydration_old;
132
-export const attemptContinuousHydration: typeof attemptContinuousHydration_new = enableNewReconciler
133
- ? attemptContinuousHydration_new
134
- : attemptContinuousHydration_old;
135
-export const attemptHydrationAtCurrentPriority: typeof attemptHydrationAtCurrentPriority_new = enableNewReconciler
136
- ? attemptHydrationAtCurrentPriority_new
137
- : attemptHydrationAtCurrentPriority_old;
138
-export const getCurrentUpdatePriority: typeof getCurrentUpdatePriority_new = enableNewReconciler
139
- ? getCurrentUpdatePriority_new
140
- : /* $FlowFixMe[incompatible-type] opaque types EventPriority from new and old
141
- * are incompatible. */
142
- getCurrentUpdatePriority_old;
143
-export const findHostInstance: typeof findHostInstance_new = enableNewReconciler
144
- ? findHostInstance_new
145
- : findHostInstance_old;
146
-export const findHostInstanceWithWarning: typeof findHostInstanceWithWarning_new = enableNewReconciler
147
- ? findHostInstanceWithWarning_new
148
- : findHostInstanceWithWarning_old;
149
-export const findHostInstanceWithNoPortals: typeof findHostInstanceWithNoPortals_new = enableNewReconciler
150
- ? findHostInstanceWithNoPortals_new
151
- : findHostInstanceWithNoPortals_old;
152
-export const shouldError: typeof shouldError_new = enableNewReconciler
153
- ? shouldError_new
154
- : shouldError_old;
155
-export const shouldSuspend: typeof shouldSuspend_new = enableNewReconciler
156
- ? shouldSuspend_new
157
- : shouldSuspend_old;
158
-export const injectIntoDevTools: typeof injectIntoDevTools_new = enableNewReconciler
159
- ? injectIntoDevTools_new
160
- : injectIntoDevTools_old;
161
-export const createPortal: typeof createPortal_new = enableNewReconciler
162
- ? createPortal_new
163
- : createPortal_old;
164
-export const createComponentSelector: typeof createComponentSelector_new = enableNewReconciler
165
- ? createComponentSelector_new
166
- : createComponentSelector_old;
167
-
168
-export const createHasPseudoClassSelector: typeof createHasPseudoClassSelector_new = enableNewReconciler
169
- ? createHasPseudoClassSelector_new
170
- : createHasPseudoClassSelector_old;
171
-export const createRoleSelector: typeof createRoleSelector_new = enableNewReconciler
172
- ? createRoleSelector_new
173
- : createRoleSelector_old;
174
-export const createTextSelector: typeof createTextSelector_new = enableNewReconciler
175
- ? createTextSelector_new
176
- : createTextSelector_old;
177
-export const createTestNameSelector: typeof createTestNameSelector_new = enableNewReconciler
178
- ? createTestNameSelector_new
179
- : createTestNameSelector_old;
180
-export const getFindAllNodesFailureDescription: typeof getFindAllNodesFailureDescription_new = enableNewReconciler
181
- ? getFindAllNodesFailureDescription_new
182
- : getFindAllNodesFailureDescription_old;
183
-export const findAllNodes: typeof findAllNodes_new = enableNewReconciler
184
- ? findAllNodes_new
185
- : findAllNodes_old;
186
-export const findBoundingRects: typeof findBoundingRects_new = enableNewReconciler
187
- ? findBoundingRects_new
188
- : findBoundingRects_old;
189
-export const focusWithin: typeof focusWithin_new = enableNewReconciler
190
- ? focusWithin_new
191
- : focusWithin_old;
192
-export const observeVisibleRects: typeof observeVisibleRects_new = enableNewReconciler
193
- ? observeVisibleRects_new
194
- : observeVisibleRects_old;
195
-export const registerMutableSourceForHydration: typeof registerMutableSourceForHydration_new = enableNewReconciler
196
- ? registerMutableSourceForHydration_new
197
- : registerMutableSourceForHydration_old;
198
-/* $FlowFixMe[incompatible-type] opaque types EventPriority from new and old
199
- * are incompatible. */
200
-export const runWithPriority: typeof runWithPriority_new = enableNewReconciler
201
- ? runWithPriority_new
202
- : runWithPriority_old;
packages/react-reconciler/src/ReactFiberReconciler.new.js
deleted
-845
@@ -1,845 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {
11
- Fiber,
12
- FiberRoot,
13
- SuspenseHydrationCallbacks,
14
- TransitionTracingCallbacks,
15
-} from './ReactInternalTypes';
16
-import type {RootTag} from './ReactRootTags';
17
-import type {
18
- Instance,
19
- TextInstance,
20
- Container,
21
- PublicInstance,
22
- RendererInspectionConfig,
23
-} from './ReactFiberHostConfig';
24
-import type {ReactNodeList} from 'shared/ReactTypes';
25
-import type {Lane} from './ReactFiberLane.new';
26
-import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
27
-
28
-import {
29
- findCurrentHostFiber,
30
- findCurrentHostFiberWithNoPortals,
31
-} from './ReactFiberTreeReflection';
32
-import {get as getInstance} from 'shared/ReactInstanceMap';
33
-import {
34
- HostComponent,
35
- HostSingleton,
36
- ClassComponent,
37
- HostRoot,
38
- SuspenseComponent,
39
-} from './ReactWorkTags';
40
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
41
-import isArray from 'shared/isArray';
42
-import {enableSchedulingProfiler} from 'shared/ReactFeatureFlags';
43
-import ReactSharedInternals from 'shared/ReactSharedInternals';
44
-import {getPublicInstance} from './ReactFiberHostConfig';
45
-import {
46
- findCurrentUnmaskedContext,
47
- processChildContext,
48
- emptyContextObject,
49
- isContextProvider as isLegacyContextProvider,
50
-} from './ReactFiberContext.new';
51
-import {createFiberRoot} from './ReactFiberRoot.new';
52
-import {isRootDehydrated} from './ReactFiberShellHydration';
53
-import {
54
- injectInternals,
55
- markRenderScheduled,
56
- onScheduleRoot,
57
-} from './ReactFiberDevToolsHook.new';
58
-import {
59
- requestEventTime,
60
- requestUpdateLane,
61
- scheduleUpdateOnFiber,
62
- scheduleInitialHydrationOnRoot,
63
- flushRoot,
64
- batchedUpdates,
65
- flushSync,
66
- isAlreadyRendering,
67
- flushControlled,
68
- deferredUpdates,
69
- discreteUpdates,
70
- flushPassiveEffects,
71
-} from './ReactFiberWorkLoop.new';
72
-import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates.new';
73
-import {
74
- createUpdate,
75
- enqueueUpdate,
76
- entangleTransitions,
77
-} from './ReactFiberClassUpdateQueue.new';
78
-import {
79
- isRendering as ReactCurrentFiberIsRendering,
80
- current as ReactCurrentFiberCurrent,
81
- resetCurrentFiber as resetCurrentDebugFiberInDEV,
82
- setCurrentFiber as setCurrentDebugFiberInDEV,
83
-} from './ReactCurrentFiber';
84
-import {StrictLegacyMode} from './ReactTypeOfMode';
85
-import {
86
- SyncLane,
87
- SelectiveHydrationLane,
88
- NoTimestamp,
89
- getHighestPriorityPendingLanes,
90
- higherPriorityLane,
91
-} from './ReactFiberLane.new';
92
-import {
93
- getCurrentUpdatePriority,
94
- runWithPriority,
95
-} from './ReactEventPriorities.new';
96
-import {
97
- scheduleRefresh,
98
- scheduleRoot,
99
- setRefreshHandler,
100
- findHostInstancesForRefresh,
101
-} from './ReactFiberHotReloading.new';
102
-import ReactVersion from 'shared/ReactVersion';
103
-export {registerMutableSourceForHydration} from './ReactMutableSource.new';
104
-export {createPortal} from './ReactPortal';
105
-export {
106
- createComponentSelector,
107
- createHasPseudoClassSelector,
108
- createRoleSelector,
109
- createTestNameSelector,
110
- createTextSelector,
111
- getFindAllNodesFailureDescription,
112
- findAllNodes,
113
- findBoundingRects,
114
- focusWithin,
115
- observeVisibleRects,
116
-} from './ReactTestSelectors';
117
-
118
-type OpaqueRoot = FiberRoot;
119
-
120
-// 0 is PROD, 1 is DEV.
121
-// Might add PROFILE later.
122
-type BundleType = 0 | 1;
123
-
124
-type DevToolsConfig = {
125
- bundleType: BundleType,
126
- version: string,
127
- rendererPackageName: string,
128
- // Note: this actually *does* depend on Fiber internal fields.
129
- // Used by "inspect clicked DOM element" in React DevTools.
130
- findFiberByHostInstance?: (instance: Instance | TextInstance) => Fiber | null,
131
- rendererConfig?: RendererInspectionConfig,
132
-};
133
-
134
-let didWarnAboutNestedUpdates;
135
-let didWarnAboutFindNodeInStrictMode;
136
-
137
-if (__DEV__) {
138
- didWarnAboutNestedUpdates = false;
139
- didWarnAboutFindNodeInStrictMode = {};
140
-}
141
-
142
-function getContextForSubtree(
143
- parentComponent: ?React$Component<any, any>,
144
-): Object {
145
- if (!parentComponent) {
146
- return emptyContextObject;
147
- }
148
-
149
- const fiber = getInstance(parentComponent);
150
- const parentContext = findCurrentUnmaskedContext(fiber);
151
-
152
- if (fiber.tag === ClassComponent) {
153
- const Component = fiber.type;
154
- if (isLegacyContextProvider(Component)) {
155
- return processChildContext(fiber, Component, parentContext);
156
- }
157
- }
158
-
159
- return parentContext;
160
-}
161
-
162
-function findHostInstance(component: Object): PublicInstance | null {
163
- const fiber = getInstance(component);
164
- if (fiber === undefined) {
165
- if (typeof component.render === 'function') {
166
- throw new Error('Unable to find node on an unmounted component.');
167
- } else {
168
- const keys = Object.keys(component).join(',');
169
- throw new Error(
170
- `Argument appears to not be a ReactComponent. Keys: ${keys}`,
171
- );
172
- }
173
- }
174
- const hostFiber = findCurrentHostFiber(fiber);
175
- if (hostFiber === null) {
176
- return null;
177
- }
178
- return hostFiber.stateNode;
179
-}
180
-
181
-function findHostInstanceWithWarning(
182
- component: Object,
183
- methodName: string,
184
-): PublicInstance | null {
185
- if (__DEV__) {
186
- const fiber = getInstance(component);
187
- if (fiber === undefined) {
188
- if (typeof component.render === 'function') {
189
- throw new Error('Unable to find node on an unmounted component.');
190
- } else {
191
- const keys = Object.keys(component).join(',');
192
- throw new Error(
193
- `Argument appears to not be a ReactComponent. Keys: ${keys}`,
194
- );
195
- }
196
- }
197
- const hostFiber = findCurrentHostFiber(fiber);
198
- if (hostFiber === null) {
199
- return null;
200
- }
201
- if (hostFiber.mode & StrictLegacyMode) {
202
- const componentName = getComponentNameFromFiber(fiber) || 'Component';
203
- if (!didWarnAboutFindNodeInStrictMode[componentName]) {
204
- didWarnAboutFindNodeInStrictMode[componentName] = true;
205
-
206
- const previousFiber = ReactCurrentFiberCurrent;
207
- try {
208
- setCurrentDebugFiberInDEV(hostFiber);
209
- if (fiber.mode & StrictLegacyMode) {
210
- console.error(
211
- '%s is deprecated in StrictMode. ' +
212
- '%s was passed an instance of %s which is inside StrictMode. ' +
213
- 'Instead, add a ref directly to the element you want to reference. ' +
214
- 'Learn more about using refs safely here: ' +
215
- 'https://reactjs.org/link/strict-mode-find-node',
216
- methodName,
217
- methodName,
218
- componentName,
219
- );
220
- } else {
221
- console.error(
222
- '%s is deprecated in StrictMode. ' +
223
- '%s was passed an instance of %s which renders StrictMode children. ' +
224
- 'Instead, add a ref directly to the element you want to reference. ' +
225
- 'Learn more about using refs safely here: ' +
226
- 'https://reactjs.org/link/strict-mode-find-node',
227
- methodName,
228
- methodName,
229
- componentName,
230
- );
231
- }
232
- } finally {
233
- // Ideally this should reset to previous but this shouldn't be called in
234
- // render and there's another warning for that anyway.
235
- if (previousFiber) {
236
- setCurrentDebugFiberInDEV(previousFiber);
237
- } else {
238
- resetCurrentDebugFiberInDEV();
239
- }
240
- }
241
- }
242
- }
243
- return hostFiber.stateNode;
244
- }
245
- return findHostInstance(component);
246
-}
247
-
248
-export function createContainer(
249
- containerInfo: Container,
250
- tag: RootTag,
251
- hydrationCallbacks: null | SuspenseHydrationCallbacks,
252
- isStrictMode: boolean,
253
- concurrentUpdatesByDefaultOverride: null | boolean,
254
- identifierPrefix: string,
255
- onRecoverableError: (error: mixed) => void,
256
- transitionCallbacks: null | TransitionTracingCallbacks,
257
-): OpaqueRoot {
258
- const hydrate = false;
259
- const initialChildren = null;
260
- return createFiberRoot(
261
- containerInfo,
262
- tag,
263
- hydrate,
264
- initialChildren,
265
- hydrationCallbacks,
266
- isStrictMode,
267
- concurrentUpdatesByDefaultOverride,
268
- identifierPrefix,
269
- onRecoverableError,
270
- transitionCallbacks,
271
- );
272
-}
273
-
274
-export function createHydrationContainer(
275
- initialChildren: ReactNodeList,
276
- // TODO: Remove `callback` when we delete legacy mode.
277
- callback: ?Function,
278
- containerInfo: Container,
279
- tag: RootTag,
280
- hydrationCallbacks: null | SuspenseHydrationCallbacks,
281
- isStrictMode: boolean,
282
- concurrentUpdatesByDefaultOverride: null | boolean,
283
- identifierPrefix: string,
284
- onRecoverableError: (error: mixed) => void,
285
- transitionCallbacks: null | TransitionTracingCallbacks,
286
-): OpaqueRoot {
287
- const hydrate = true;
288
- const root = createFiberRoot(
289
- containerInfo,
290
- tag,
291
- hydrate,
292
- initialChildren,
293
- hydrationCallbacks,
294
- isStrictMode,
295
- concurrentUpdatesByDefaultOverride,
296
- identifierPrefix,
297
- onRecoverableError,
298
- transitionCallbacks,
299
- );
300
-
301
- // TODO: Move this to FiberRoot constructor
302
- root.context = getContextForSubtree(null);
303
-
304
- // Schedule the initial render. In a hydration root, this is different from
305
- // a regular update because the initial render must match was was rendered
306
- // on the server.
307
- // NOTE: This update intentionally doesn't have a payload. We're only using
308
- // the update to schedule work on the root fiber (and, for legacy roots, to
309
- // enqueue the callback if one is provided).
310
- const current = root.current;
311
- const eventTime = requestEventTime();
312
- const lane = requestUpdateLane(current);
313
- const update = createUpdate(eventTime, lane);
314
- update.callback =
315
- callback !== undefined && callback !== null ? callback : null;
316
- enqueueUpdate(current, update, lane);
317
- scheduleInitialHydrationOnRoot(root, lane, eventTime);
318
-
319
- return root;
320
-}
321
-
322
-export function updateContainer(
323
- element: ReactNodeList,
324
- container: OpaqueRoot,
325
- parentComponent: ?React$Component<any, any>,
326
- callback: ?Function,
327
-): Lane {
328
- if (__DEV__) {
329
- onScheduleRoot(container, element);
330
- }
331
- const current = container.current;
332
- const eventTime = requestEventTime();
333
- const lane = requestUpdateLane(current);
334
-
335
- if (enableSchedulingProfiler) {
336
- markRenderScheduled(lane);
337
- }
338
-
339
- const context = getContextForSubtree(parentComponent);
340
- if (container.context === null) {
341
- container.context = context;
342
- } else {
343
- container.pendingContext = context;
344
- }
345
-
346
- if (__DEV__) {
347
- if (
348
- ReactCurrentFiberIsRendering &&
349
- ReactCurrentFiberCurrent !== null &&
350
- !didWarnAboutNestedUpdates
351
- ) {
352
- didWarnAboutNestedUpdates = true;
353
- console.error(
354
- 'Render methods should be a pure function of props and state; ' +
355
- 'triggering nested component updates from render is not allowed. ' +
356
- 'If necessary, trigger nested updates in componentDidUpdate.\n\n' +
357
- 'Check the render method of %s.',
358
- getComponentNameFromFiber(ReactCurrentFiberCurrent) || 'Unknown',
359
- );
360
- }
361
- }
362
-
363
- const update = createUpdate(eventTime, lane);
364
- // Caution: React DevTools currently depends on this property
365
- // being called "element".
366
- update.payload = {element};
367
-
368
- callback = callback === undefined ? null : callback;
369
- if (callback !== null) {
370
- if (__DEV__) {
371
- if (typeof callback !== 'function') {
372
- console.error(
373
- 'render(...): Expected the last optional `callback` argument to be a ' +
374
- 'function. Instead received: %s.',
375
- callback,
376
- );
377
- }
378
- }
379
- update.callback = callback;
380
- }
381
-
382
- const root = enqueueUpdate(current, update, lane);
383
- if (root !== null) {
384
- scheduleUpdateOnFiber(root, current, lane, eventTime);
385
- entangleTransitions(root, current, lane);
386
- }
387
-
388
- return lane;
389
-}
390
-
391
-export {
392
- batchedUpdates,
393
- deferredUpdates,
394
- discreteUpdates,
395
- flushControlled,
396
- flushSync,
397
- isAlreadyRendering,
398
- flushPassiveEffects,
399
-};
400
-
401
-export function getPublicRootInstance(
402
- container: OpaqueRoot,
403
-): React$Component<any, any> | PublicInstance | null {
404
- const containerFiber = container.current;
405
- if (!containerFiber.child) {
406
- return null;
407
- }
408
- switch (containerFiber.child.tag) {
409
- case HostSingleton:
410
- case HostComponent:
411
- return getPublicInstance(containerFiber.child.stateNode);
412
- default:
413
- return containerFiber.child.stateNode;
414
- }
415
-}
416
-
417
-export function attemptSynchronousHydration(fiber: Fiber): void {
418
- switch (fiber.tag) {
419
- case HostRoot: {
420
- const root: FiberRoot = fiber.stateNode;
421
- if (isRootDehydrated(root)) {
422
- // Flush the first scheduled "update".
423
- const lanes = getHighestPriorityPendingLanes(root);
424
- flushRoot(root, lanes);
425
- }
426
- break;
427
- }
428
- case SuspenseComponent: {
429
- flushSync(() => {
430
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
431
- if (root !== null) {
432
- const eventTime = requestEventTime();
433
- scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime);
434
- }
435
- });
436
- // If we're still blocked after this, we need to increase
437
- // the priority of any promises resolving within this
438
- // boundary so that they next attempt also has higher pri.
439
- const retryLane = SyncLane;
440
- markRetryLaneIfNotHydrated(fiber, retryLane);
441
- break;
442
- }
443
- }
444
-}
445
-
446
-function markRetryLaneImpl(fiber: Fiber, retryLane: Lane) {
447
- const suspenseState: null | SuspenseState = fiber.memoizedState;
448
- if (suspenseState !== null && suspenseState.dehydrated !== null) {
449
- suspenseState.retryLane = higherPriorityLane(
450
- suspenseState.retryLane,
451
- retryLane,
452
- );
453
- }
454
-}
455
-
456
-// Increases the priority of thenables when they resolve within this boundary.
457
-function markRetryLaneIfNotHydrated(fiber: Fiber, retryLane: Lane) {
458
- markRetryLaneImpl(fiber, retryLane);
459
- const alternate = fiber.alternate;
460
- if (alternate) {
461
- markRetryLaneImpl(alternate, retryLane);
462
- }
463
-}
464
-
465
-export function attemptDiscreteHydration(fiber: Fiber): void {
466
- if (fiber.tag !== SuspenseComponent) {
467
- // We ignore HostRoots here because we can't increase
468
- // their priority and they should not suspend on I/O,
469
- // since you have to wrap anything that might suspend in
470
- // Suspense.
471
- return;
472
- }
473
- const lane = SyncLane;
474
- const root = enqueueConcurrentRenderForLane(fiber, lane);
475
- if (root !== null) {
476
- const eventTime = requestEventTime();
477
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
478
- }
479
- markRetryLaneIfNotHydrated(fiber, lane);
480
-}
481
-
482
-export function attemptContinuousHydration(fiber: Fiber): void {
483
- if (fiber.tag !== SuspenseComponent) {
484
- // We ignore HostRoots here because we can't increase
485
- // their priority and they should not suspend on I/O,
486
- // since you have to wrap anything that might suspend in
487
- // Suspense.
488
- return;
489
- }
490
- const lane = SelectiveHydrationLane;
491
- const root = enqueueConcurrentRenderForLane(fiber, lane);
492
- if (root !== null) {
493
- const eventTime = requestEventTime();
494
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
495
- }
496
- markRetryLaneIfNotHydrated(fiber, lane);
497
-}
498
-
499
-export function attemptHydrationAtCurrentPriority(fiber: Fiber): void {
500
- if (fiber.tag !== SuspenseComponent) {
501
- // We ignore HostRoots here because we can't increase
502
- // their priority other than synchronously flush it.
503
- return;
504
- }
505
- const lane = requestUpdateLane(fiber);
506
- const root = enqueueConcurrentRenderForLane(fiber, lane);
507
- if (root !== null) {
508
- const eventTime = requestEventTime();
509
- scheduleUpdateOnFiber(root, fiber, lane, eventTime);
510
- }
511
- markRetryLaneIfNotHydrated(fiber, lane);
512
-}
513
-
514
-export {getCurrentUpdatePriority, runWithPriority};
515
-
516
-export {findHostInstance};
517
-
518
-export {findHostInstanceWithWarning};
519
-
520
-export function findHostInstanceWithNoPortals(
521
- fiber: Fiber,
522
-): PublicInstance | null {
523
- const hostFiber = findCurrentHostFiberWithNoPortals(fiber);
524
- if (hostFiber === null) {
525
- return null;
526
- }
527
- return hostFiber.stateNode;
528
-}
529
-
530
-let shouldErrorImpl: Fiber => ?boolean = fiber => null;
531
-
532
-export function shouldError(fiber: Fiber): ?boolean {
533
- return shouldErrorImpl(fiber);
534
-}
535
-
536
-let shouldSuspendImpl = fiber => false;
537
-
538
-export function shouldSuspend(fiber: Fiber): boolean {
539
- return shouldSuspendImpl(fiber);
540
-}
541
-
542
-let overrideHookState = null;
543
-let overrideHookStateDeletePath = null;
544
-let overrideHookStateRenamePath = null;
545
-let overrideProps = null;
546
-let overridePropsDeletePath = null;
547
-let overridePropsRenamePath = null;
548
-let scheduleUpdate = null;
549
-let setErrorHandler = null;
550
-let setSuspenseHandler = null;
551
-
552
-if (__DEV__) {
553
- const copyWithDeleteImpl = (
554
- obj: Object | Array<any>,
555
- path: Array<string | number>,
556
- index: number,
557
- ) => {
558
- const key = path[index];
559
- const updated = isArray(obj) ? obj.slice() : {...obj};
560
- if (index + 1 === path.length) {
561
- if (isArray(updated)) {
562
- updated.splice(((key: any): number), 1);
563
- } else {
564
- delete updated[key];
565
- }
566
- return updated;
567
- }
568
- // $FlowFixMe number or string is fine here
569
- updated[key] = copyWithDeleteImpl(obj[key], path, index + 1);
570
- return updated;
571
- };
572
-
573
- const copyWithDelete = (
574
- obj: Object | Array<any>,
575
- path: Array<string | number>,
576
- ): Object | Array<any> => {
577
- return copyWithDeleteImpl(obj, path, 0);
578
- };
579
-
580
- const copyWithRenameImpl = (
581
- obj: Object | Array<any>,
582
- oldPath: Array<string | number>,
583
- newPath: Array<string | number>,
584
- index: number,
585
- ) => {
586
- const oldKey = oldPath[index];
587
- const updated = isArray(obj) ? obj.slice() : {...obj};
588
- if (index + 1 === oldPath.length) {
589
- const newKey = newPath[index];
590
- // $FlowFixMe number or string is fine here
591
- updated[newKey] = updated[oldKey];
592
- if (isArray(updated)) {
593
- updated.splice(((oldKey: any): number), 1);
594
- } else {
595
- delete updated[oldKey];
596
- }
597
- } else {
598
- // $FlowFixMe number or string is fine here
599
- updated[oldKey] = copyWithRenameImpl(
600
- // $FlowFixMe number or string is fine here
601
- obj[oldKey],
602
- oldPath,
603
- newPath,
604
- index + 1,
605
- );
606
- }
607
- return updated;
608
- };
609
-
610
- const copyWithRename = (
611
- obj: Object | Array<any>,
612
- oldPath: Array<string | number>,
613
- newPath: Array<string | number>,
614
- ): Object | Array<any> => {
615
- if (oldPath.length !== newPath.length) {
616
- console.warn('copyWithRename() expects paths of the same length');
617
- return;
618
- } else {
619
- for (let i = 0; i < newPath.length - 1; i++) {
620
- if (oldPath[i] !== newPath[i]) {
621
- console.warn(
622
- 'copyWithRename() expects paths to be the same except for the deepest key',
623
- );
624
- return;
625
- }
626
- }
627
- }
628
- return copyWithRenameImpl(obj, oldPath, newPath, 0);
629
- };
630
-
631
- const copyWithSetImpl = (
632
- obj: Object | Array<any>,
633
- path: Array<string | number>,
634
- index: number,
635
- value: any,
636
- ) => {
637
- if (index >= path.length) {
638
- return value;
639
- }
640
- const key = path[index];
641
- const updated = isArray(obj) ? obj.slice() : {...obj};
642
- // $FlowFixMe number or string is fine here
643
- updated[key] = copyWithSetImpl(obj[key], path, index + 1, value);
644
- return updated;
645
- };
646
-
647
- const copyWithSet = (
648
- obj: Object | Array<any>,
649
- path: Array<string | number>,
650
- value: any,
651
- ): Object | Array<any> => {
652
- return copyWithSetImpl(obj, path, 0, value);
653
- };
654
-
655
- const findHook = (fiber: Fiber, id: number) => {
656
- // For now, the "id" of stateful hooks is just the stateful hook index.
657
- // This may change in the future with e.g. nested hooks.
658
- let currentHook = fiber.memoizedState;
659
- while (currentHook !== null && id > 0) {
660
- currentHook = currentHook.next;
661
- id--;
662
- }
663
- return currentHook;
664
- };
665
-
666
- // Support DevTools editable values for useState and useReducer.
667
- overrideHookState = (
668
- fiber: Fiber,
669
- id: number,
670
- path: Array<string | number>,
671
- value: any,
672
- ) => {
673
- const hook = findHook(fiber, id);
674
- if (hook !== null) {
675
- const newState = copyWithSet(hook.memoizedState, path, value);
676
- hook.memoizedState = newState;
677
- hook.baseState = newState;
678
-
679
- // We aren't actually adding an update to the queue,
680
- // because there is no update we can add for useReducer hooks that won't trigger an error.
681
- // (There's no appropriate action type for DevTools overrides.)
682
- // As a result though, React will see the scheduled update as a noop and bailout.
683
- // Shallow cloning props works as a workaround for now to bypass the bailout check.
684
- fiber.memoizedProps = {...fiber.memoizedProps};
685
-
686
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
687
- if (root !== null) {
688
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
689
- }
690
- }
691
- };
692
- overrideHookStateDeletePath = (
693
- fiber: Fiber,
694
- id: number,
695
- path: Array<string | number>,
696
- ) => {
697
- const hook = findHook(fiber, id);
698
- if (hook !== null) {
699
- const newState = copyWithDelete(hook.memoizedState, path);
700
- hook.memoizedState = newState;
701
- hook.baseState = newState;
702
-
703
- // We aren't actually adding an update to the queue,
704
- // because there is no update we can add for useReducer hooks that won't trigger an error.
705
- // (There's no appropriate action type for DevTools overrides.)
706
- // As a result though, React will see the scheduled update as a noop and bailout.
707
- // Shallow cloning props works as a workaround for now to bypass the bailout check.
708
- fiber.memoizedProps = {...fiber.memoizedProps};
709
-
710
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
711
- if (root !== null) {
712
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
713
- }
714
- }
715
- };
716
- overrideHookStateRenamePath = (
717
- fiber: Fiber,
718
- id: number,
719
- oldPath: Array<string | number>,
720
- newPath: Array<string | number>,
721
- ) => {
722
- const hook = findHook(fiber, id);
723
- if (hook !== null) {
724
- const newState = copyWithRename(hook.memoizedState, oldPath, newPath);
725
- hook.memoizedState = newState;
726
- hook.baseState = newState;
727
-
728
- // We aren't actually adding an update to the queue,
729
- // because there is no update we can add for useReducer hooks that won't trigger an error.
730
- // (There's no appropriate action type for DevTools overrides.)
731
- // As a result though, React will see the scheduled update as a noop and bailout.
732
- // Shallow cloning props works as a workaround for now to bypass the bailout check.
733
- fiber.memoizedProps = {...fiber.memoizedProps};
734
-
735
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
736
- if (root !== null) {
737
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
738
- }
739
- }
740
- };
741
-
742
- // Support DevTools props for function components, forwardRef, memo, host components, etc.
743
- overrideProps = (fiber: Fiber, path: Array<string | number>, value: any) => {
744
- fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
745
- if (fiber.alternate) {
746
- fiber.alternate.pendingProps = fiber.pendingProps;
747
- }
748
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
749
- if (root !== null) {
750
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
751
- }
752
- };
753
- overridePropsDeletePath = (fiber: Fiber, path: Array<string | number>) => {
754
- fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
755
- if (fiber.alternate) {
756
- fiber.alternate.pendingProps = fiber.pendingProps;
757
- }
758
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
759
- if (root !== null) {
760
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
761
- }
762
- };
763
- overridePropsRenamePath = (
764
- fiber: Fiber,
765
- oldPath: Array<string | number>,
766
- newPath: Array<string | number>,
767
- ) => {
768
- fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
769
- if (fiber.alternate) {
770
- fiber.alternate.pendingProps = fiber.pendingProps;
771
- }
772
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
773
- if (root !== null) {
774
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
775
- }
776
- };
777
-
778
- scheduleUpdate = (fiber: Fiber) => {
779
- const root = enqueueConcurrentRenderForLane(fiber, SyncLane);
780
- if (root !== null) {
781
- scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
782
- }
783
- };
784
-
785
- setErrorHandler = (newShouldErrorImpl: Fiber => ?boolean) => {
786
- shouldErrorImpl = newShouldErrorImpl;
787
- };
788
-
789
- setSuspenseHandler = (newShouldSuspendImpl: Fiber => boolean) => {
790
- shouldSuspendImpl = newShouldSuspendImpl;
791
- };
792
-}
793
-
794
-function findHostInstanceByFiber(fiber: Fiber): Instance | TextInstance | null {
795
- const hostFiber = findCurrentHostFiber(fiber);
796
- if (hostFiber === null) {
797
- return null;
798
- }
799
- return hostFiber.stateNode;
800
-}
801
-
802
-function emptyFindFiberByHostInstance(
803
- instance: Instance | TextInstance,
804
-): Fiber | null {
805
- return null;
806
-}
807
-
808
-function getCurrentFiberForDevTools() {
809
- return ReactCurrentFiberCurrent;
810
-}
811
-
812
-export function injectIntoDevTools(devToolsConfig: DevToolsConfig): boolean {
813
- const {findFiberByHostInstance} = devToolsConfig;
814
- const {ReactCurrentDispatcher} = ReactSharedInternals;
815
-
816
- return injectInternals({
817
- bundleType: devToolsConfig.bundleType,
818
- version: devToolsConfig.version,
819
- rendererPackageName: devToolsConfig.rendererPackageName,
820
- rendererConfig: devToolsConfig.rendererConfig,
821
- overrideHookState,
822
- overrideHookStateDeletePath,
823
- overrideHookStateRenamePath,
824
- overrideProps,
825
- overridePropsDeletePath,
826
- overridePropsRenamePath,
827
- setErrorHandler,
828
- setSuspenseHandler,
829
- scheduleUpdate,
830
- currentDispatcherRef: ReactCurrentDispatcher,
831
- findHostInstanceByFiber,
832
- findFiberByHostInstance:
833
- findFiberByHostInstance || emptyFindFiberByHostInstance,
834
- // React Refresh
835
- findHostInstancesForRefresh: __DEV__ ? findHostInstancesForRefresh : null,
836
- scheduleRefresh: __DEV__ ? scheduleRefresh : null,
837
- scheduleRoot: __DEV__ ? scheduleRoot : null,
838
- setRefreshHandler: __DEV__ ? setRefreshHandler : null,
839
- // Enables DevTools to append owner stacks to error messages in DEV mode.
840
- getCurrentFiber: __DEV__ ? getCurrentFiberForDevTools : null,
841
- // Enables DevTools to detect reconciler version rather than renderer version
842
- // which may not match for third party renderers.
843
- reconcilerVersion: ReactVersion,
844
- });
845
-}
packages/react-reconciler/src/ReactFiberRoot.new.js
deleted
-204
@@ -1,204 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {ReactNodeList} from 'shared/ReactTypes';
11
-import type {
12
- FiberRoot,
13
- SuspenseHydrationCallbacks,
14
- TransitionTracingCallbacks,
15
-} from './ReactInternalTypes';
16
-import type {RootTag} from './ReactRootTags';
17
-import type {Cache} from './ReactFiberCacheComponent.new';
18
-import type {Container} from './ReactFiberHostConfig';
19
-
20
-import {noTimeout, supportsHydration} from './ReactFiberHostConfig';
21
-import {createHostRootFiber} from './ReactFiber.new';
22
-import {
23
- NoLane,
24
- NoLanes,
25
- NoTimestamp,
26
- TotalLanes,
27
- createLaneMap,
28
-} from './ReactFiberLane.new';
29
-import {
30
- enableSuspenseCallback,
31
- enableCache,
32
- enableProfilerCommitHooks,
33
- enableProfilerTimer,
34
- enableUpdaterTracking,
35
- enableTransitionTracing,
36
-} from 'shared/ReactFeatureFlags';
37
-import {initializeUpdateQueue} from './ReactFiberClassUpdateQueue.new';
38
-import {LegacyRoot, ConcurrentRoot} from './ReactRootTags';
39
-import {createCache, retainCache} from './ReactFiberCacheComponent.new';
40
-
41
-export type RootState = {
42
- element: any,
43
- isDehydrated: boolean,
44
- cache: Cache,
45
-};
46
-
47
-function FiberRootNode(
48
- containerInfo,
49
- tag,
50
- hydrate,
51
- identifierPrefix,
52
- onRecoverableError,
53
-) {
54
- this.tag = tag;
55
- this.containerInfo = containerInfo;
56
- this.pendingChildren = null;
57
- this.current = null;
58
- this.pingCache = null;
59
- this.finishedWork = null;
60
- this.timeoutHandle = noTimeout;
61
- this.context = null;
62
- this.pendingContext = null;
63
- this.callbackNode = null;
64
- this.callbackPriority = NoLane;
65
- this.eventTimes = createLaneMap(NoLanes);
66
- this.expirationTimes = createLaneMap(NoTimestamp);
67
-
68
- this.pendingLanes = NoLanes;
69
- this.suspendedLanes = NoLanes;
70
- this.pingedLanes = NoLanes;
71
- this.expiredLanes = NoLanes;
72
- this.mutableReadLanes = NoLanes;
73
- this.finishedLanes = NoLanes;
74
- this.errorRecoveryDisabledLanes = NoLanes;
75
-
76
- this.entangledLanes = NoLanes;
77
- this.entanglements = createLaneMap(NoLanes);
78
-
79
- this.hiddenUpdates = createLaneMap(null);
80
-
81
- this.identifierPrefix = identifierPrefix;
82
- this.onRecoverableError = onRecoverableError;
83
-
84
- if (enableCache) {
85
- this.pooledCache = null;
86
- this.pooledCacheLanes = NoLanes;
87
- }
88
-
89
- if (supportsHydration) {
90
- this.mutableSourceEagerHydrationData = null;
91
- }
92
-
93
- if (enableSuspenseCallback) {
94
- this.hydrationCallbacks = null;
95
- }
96
-
97
- this.incompleteTransitions = new Map();
98
- if (enableTransitionTracing) {
99
- this.transitionCallbacks = null;
100
- const transitionLanesMap = (this.transitionLanes = []);
101
- for (let i = 0; i < TotalLanes; i++) {
102
- transitionLanesMap.push(null);
103
- }
104
- }
105
-
106
- if (enableProfilerTimer && enableProfilerCommitHooks) {
107
- this.effectDuration = 0;
108
- this.passiveEffectDuration = 0;
109
- }
110
-
111
- if (enableUpdaterTracking) {
112
- this.memoizedUpdaters = new Set();
113
- const pendingUpdatersLaneMap = (this.pendingUpdatersLaneMap = []);
114
- for (let i = 0; i < TotalLanes; i++) {
115
- pendingUpdatersLaneMap.push(new Set());
116
- }
117
- }
118
-
119
- if (__DEV__) {
120
- switch (tag) {
121
- case ConcurrentRoot:
122
- this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()';
123
- break;
124
- case LegacyRoot:
125
- this._debugRootType = hydrate ? 'hydrate()' : 'render()';
126
- break;
127
- }
128
- }
129
-}
130
-
131
-export function createFiberRoot(
132
- containerInfo: Container,
133
- tag: RootTag,
134
- hydrate: boolean,
135
- initialChildren: ReactNodeList,
136
- hydrationCallbacks: null | SuspenseHydrationCallbacks,
137
- isStrictMode: boolean,
138
- concurrentUpdatesByDefaultOverride: null | boolean,
139
- // TODO: We have several of these arguments that are conceptually part of the
140
- // host config, but because they are passed in at runtime, we have to thread
141
- // them through the root constructor. Perhaps we should put them all into a
142
- // single type, like a DynamicHostConfig that is defined by the renderer.
143
- identifierPrefix: string,
144
- onRecoverableError: null | ((error: mixed) => void),
145
- transitionCallbacks: null | TransitionTracingCallbacks,
146
-): FiberRoot {
147
- // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions
148
- const root: FiberRoot = (new FiberRootNode(
149
- containerInfo,
150
- tag,
151
- hydrate,
152
- identifierPrefix,
153
- onRecoverableError,
154
- ): any);
155
- if (enableSuspenseCallback) {
156
- root.hydrationCallbacks = hydrationCallbacks;
157
- }
158
-
159
- if (enableTransitionTracing) {
160
- root.transitionCallbacks = transitionCallbacks;
161
- }
162
-
163
- // Cyclic construction. This cheats the type system right now because
164
- // stateNode is any.
165
- const uninitializedFiber = createHostRootFiber(
166
- tag,
167
- isStrictMode,
168
- concurrentUpdatesByDefaultOverride,
169
- );
170
- root.current = uninitializedFiber;
171
- uninitializedFiber.stateNode = root;
172
-
173
- if (enableCache) {
174
- const initialCache = createCache();
175
- retainCache(initialCache);
176
-
177
- // The pooledCache is a fresh cache instance that is used temporarily
178
- // for newly mounted boundaries during a render. In general, the
179
- // pooledCache is always cleared from the root at the end of a render:
180
- // it is either released when render commits, or moved to an Offscreen
181
- // component if rendering suspends. Because the lifetime of the pooled
182
- // cache is distinct from the main memoizedState.cache, it must be
183
- // retained separately.
184
- root.pooledCache = initialCache;
185
- retainCache(initialCache);
186
- const initialState: RootState = {
187
- element: initialChildren,
188
- isDehydrated: hydrate,
189
- cache: initialCache,
190
- };
191
- uninitializedFiber.memoizedState = initialState;
192
- } else {
193
- const initialState: RootState = {
194
- element: initialChildren,
195
- isDehydrated: hydrate,
196
- cache: (null: any), // not enabled yet
197
- };
198
- uninitializedFiber.memoizedState = initialState;
199
- }
200
-
201
- initializeUpdateQueue(uninitializedFiber);
202
-
203
- return root;
204
-}
packages/react-reconciler/src/ReactFiberScope.new.js
deleted
-199
@@ -1,199 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-import type {
12
- ReactScopeInstance,
13
- ReactContext,
14
- ReactScopeQuery,
15
-} from 'shared/ReactTypes';
16
-
17
-import {
18
- getPublicInstance,
19
- getInstanceFromNode,
20
- getInstanceFromScope,
21
-} from './ReactFiberHostConfig';
22
-import {isFiberSuspenseAndTimedOut} from './ReactFiberTreeReflection';
23
-
24
-import {HostComponent, ScopeComponent, ContextProvider} from './ReactWorkTags';
25
-import {enableScopeAPI} from 'shared/ReactFeatureFlags';
26
-
27
-function getSuspenseFallbackChild(fiber: Fiber): Fiber | null {
28
- return ((((fiber.child: any): Fiber).sibling: any): Fiber).child;
29
-}
30
-
31
-const emptyObject = {};
32
-
33
-function collectScopedNodes(
34
- node: Fiber,
35
- fn: ReactScopeQuery,
36
- scopedNodes: Array<any>,
37
-): void {
38
- if (enableScopeAPI) {
39
- if (node.tag === HostComponent) {
40
- const {type, memoizedProps, stateNode} = node;
41
- const instance = getPublicInstance(stateNode);
42
- if (
43
- instance !== null &&
44
- fn(type, memoizedProps || emptyObject, instance) === true
45
- ) {
46
- scopedNodes.push(instance);
47
- }
48
- }
49
- let child = node.child;
50
-
51
- if (isFiberSuspenseAndTimedOut(node)) {
52
- child = getSuspenseFallbackChild(node);
53
- }
54
- if (child !== null) {
55
- collectScopedNodesFromChildren(child, fn, scopedNodes);
56
- }
57
- }
58
-}
59
-
60
-function collectFirstScopedNode(
61
- node: Fiber,
62
- fn: ReactScopeQuery,
63
-): null | Object {
64
- if (enableScopeAPI) {
65
- if (node.tag === HostComponent) {
66
- const {type, memoizedProps, stateNode} = node;
67
- const instance = getPublicInstance(stateNode);
68
- if (instance !== null && fn(type, memoizedProps, instance) === true) {
69
- return instance;
70
- }
71
- }
72
- let child = node.child;
73
-
74
- if (isFiberSuspenseAndTimedOut(node)) {
75
- child = getSuspenseFallbackChild(node);
76
- }
77
- if (child !== null) {
78
- return collectFirstScopedNodeFromChildren(child, fn);
79
- }
80
- }
81
- return null;
82
-}
83
-
84
-function collectScopedNodesFromChildren(
85
- startingChild: Fiber,
86
- fn: ReactScopeQuery,
87
- scopedNodes: Array<any>,
88
-): void {
89
- let child: null | Fiber = startingChild;
90
- while (child !== null) {
91
- collectScopedNodes(child, fn, scopedNodes);
92
- child = child.sibling;
93
- }
94
-}
95
-
96
-function collectFirstScopedNodeFromChildren(
97
- startingChild: Fiber,
98
- fn: ReactScopeQuery,
99
-): Object | null {
100
- let child: null | Fiber = startingChild;
101
- while (child !== null) {
102
- const scopedNode = collectFirstScopedNode(child, fn);
103
- if (scopedNode !== null) {
104
- return scopedNode;
105
- }
106
- child = child.sibling;
107
- }
108
- return null;
109
-}
110
-
111
-function collectNearestContextValues<T>(
112
- node: Fiber,
113
- context: ReactContext<T>,
114
- childContextValues: Array<T>,
115
-): void {
116
- if (node.tag === ContextProvider && node.type._context === context) {
117
- const contextValue = node.memoizedProps.value;
118
- childContextValues.push(contextValue);
119
- } else {
120
- let child = node.child;
121
-
122
- if (isFiberSuspenseAndTimedOut(node)) {
123
- child = getSuspenseFallbackChild(node);
124
- }
125
- if (child !== null) {
126
- collectNearestChildContextValues(child, context, childContextValues);
127
- }
128
- }
129
-}
130
-
131
-function collectNearestChildContextValues<T>(
132
- startingChild: Fiber | null,
133
- context: ReactContext<T>,
134
- childContextValues: Array<T>,
135
-): void {
136
- let child = startingChild;
137
- while (child !== null) {
138
- collectNearestContextValues(child, context, childContextValues);
139
- child = child.sibling;
140
- }
141
-}
142
-
143
-function DO_NOT_USE_queryAllNodes(fn: ReactScopeQuery): null | Array<Object> {
144
- const currentFiber = getInstanceFromScope(this);
145
- if (currentFiber === null) {
146
- return null;
147
- }
148
- const child = currentFiber.child;
149
- const scopedNodes = [];
150
- if (child !== null) {
151
- collectScopedNodesFromChildren(child, fn, scopedNodes);
152
- }
153
- return scopedNodes.length === 0 ? null : scopedNodes;
154
-}
155
-
156
-function DO_NOT_USE_queryFirstNode(fn: ReactScopeQuery): null | Object {
157
- const currentFiber = getInstanceFromScope(this);
158
- if (currentFiber === null) {
159
- return null;
160
- }
161
- const child = currentFiber.child;
162
- if (child !== null) {
163
- return collectFirstScopedNodeFromChildren(child, fn);
164
- }
165
- return null;
166
-}
167
-
168
-function containsNode(node: Object): boolean {
169
- let fiber = getInstanceFromNode(node);
170
- while (fiber !== null) {
171
- if (fiber.tag === ScopeComponent && fiber.stateNode === this) {
172
- return true;
173
- }
174
- fiber = fiber.return;
175
- }
176
- return false;
177
-}
178
-
179
-function getChildContextValues<T>(context: ReactContext<T>): Array<T> {
180
- const currentFiber = getInstanceFromScope(this);
181
- if (currentFiber === null) {
182
- return [];
183
- }
184
- const child = currentFiber.child;
185
- const childContextValues = [];
186
- if (child !== null) {
187
- collectNearestChildContextValues(child, context, childContextValues);
188
- }
189
- return childContextValues;
190
-}
191
-
192
-export function createScopeInstance(): ReactScopeInstance {
193
- return {
194
- DO_NOT_USE_queryAllNodes,
195
- DO_NOT_USE_queryFirstNode,
196
- containsNode,
197
- getChildContextValues,
198
- };
199
-}
packages/react-reconciler/src/ReactFiberShellHydration.js
+1
-1
@@ -8,7 +8,7 @@
8
*/
9
10
import type {FiberRoot} from './ReactInternalTypes';
11
-import type {RootState} from './ReactFiberRoot.new';
11
+import type {RootState} from './ReactFiberRoot.old';
12
13
// This is imported by the event replaying implementation in React DOM. It's
14
// in a separate file to break a circular dependency between the renderer and
packages/react-reconciler/src/ReactFiberStack.new.js
deleted
-97
@@ -1,97 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-
12
-export type StackCursor<T> = {current: T};
13
-
14
-const valueStack: Array<any> = [];
15
-
16
-let fiberStack: Array<Fiber | null>;
17
-
18
-if (__DEV__) {
19
- fiberStack = [];
20
-}
21
-
22
-let index = -1;
23
-
24
-function createCursor<T>(defaultValue: T): StackCursor<T> {
25
- return {
26
- current: defaultValue,
27
- };
28
-}
29
-
30
-function isEmpty(): boolean {
31
- return index === -1;
32
-}
33
-
34
-function pop<T>(cursor: StackCursor<T>, fiber: Fiber): void {
35
- if (index < 0) {
36
- if (__DEV__) {
37
- console.error('Unexpected pop.');
38
- }
39
- return;
40
- }
41
-
42
- if (__DEV__) {
43
- if (fiber !== fiberStack[index]) {
44
- console.error('Unexpected Fiber popped.');
45
- }
46
- }
47
-
48
- cursor.current = valueStack[index];
49
-
50
- valueStack[index] = null;
51
-
52
- if (__DEV__) {
53
- fiberStack[index] = null;
54
- }
55
-
56
- index--;
57
-}
58
-
59
-function push<T>(cursor: StackCursor<T>, value: T, fiber: Fiber): void {
60
- index++;
61
-
62
- valueStack[index] = cursor.current;
63
-
64
- if (__DEV__) {
65
- fiberStack[index] = fiber;
66
- }
67
-
68
- cursor.current = value;
69
-}
70
-
71
-function checkThatStackIsEmpty() {
72
- if (__DEV__) {
73
- if (index !== -1) {
74
- console.error(
75
- 'Expected an empty stack. Something was not reset properly.',
76
- );
77
- }
78
- }
79
-}
80
-
81
-function resetStackAfterFatalErrorInDev() {
82
- if (__DEV__) {
83
- index = -1;
84
- valueStack.length = 0;
85
- fiberStack.length = 0;
86
- }
87
-}
88
-
89
-export {
90
- createCursor,
91
- isEmpty,
92
- pop,
93
- push,
94
- // DEV only:
95
- checkThatStackIsEmpty,
96
- resetStackAfterFatalErrorInDev,
97
-};
packages/react-reconciler/src/ReactFiberSuspenseComponent.new.js
deleted
-113
@@ -1,113 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {ReactNodeList, Wakeable} from 'shared/ReactTypes';
11
-import type {Fiber} from './ReactInternalTypes';
12
-import type {SuspenseInstance} from './ReactFiberHostConfig';
13
-import type {Lane} from './ReactFiberLane.new';
14
-import type {TreeContext} from './ReactFiberTreeContext.new';
15
-
16
-import {SuspenseComponent, SuspenseListComponent} from './ReactWorkTags';
17
-import {NoFlags, DidCapture} from './ReactFiberFlags';
18
-import {
19
- isSuspenseInstancePending,
20
- isSuspenseInstanceFallback,
21
-} from './ReactFiberHostConfig';
22
-
23
-export type SuspenseProps = {
24
- children?: ReactNodeList,
25
- fallback?: ReactNodeList,
26
-
27
- // TODO: Add "unstable_" prefix?
28
- suspenseCallback?: (Set<Wakeable> | null) => mixed,
29
-
30
- unstable_avoidThisFallback?: boolean,
31
- unstable_expectedLoadTime?: number,
32
- unstable_name?: string,
33
-};
34
-
35
-// A null SuspenseState represents an unsuspended normal Suspense boundary.
36
-// A non-null SuspenseState means that it is blocked for one reason or another.
37
-// - A non-null dehydrated field means it's blocked pending hydration.
38
-// - A non-null dehydrated field can use isSuspenseInstancePending or
39
-// isSuspenseInstanceFallback to query the reason for being dehydrated.
40
-// - A null dehydrated field means it's blocked by something suspending and
41
-// we're currently showing a fallback instead.
42
-export type SuspenseState = {
43
- // If this boundary is still dehydrated, we store the SuspenseInstance
44
- // here to indicate that it is dehydrated (flag) and for quick access
45
- // to check things like isSuspenseInstancePending.
46
- dehydrated: null | SuspenseInstance,
47
- treeContext: null | TreeContext,
48
- // Represents the lane we should attempt to hydrate a dehydrated boundary at.
49
- // OffscreenLane is the default for dehydrated boundaries.
50
- // NoLane is the default for normal boundaries, which turns into "normal" pri.
51
- retryLane: Lane,
52
-};
53
-
54
-export type SuspenseListTailMode = 'collapsed' | 'hidden' | void;
55
-
56
-export type SuspenseListRenderState = {
57
- isBackwards: boolean,
58
- // The currently rendering tail row.
59
- rendering: null | Fiber,
60
- // The absolute time when we started rendering the most recent tail row.
61
- renderingStartTime: number,
62
- // The last of the already rendered children.
63
- last: null | Fiber,
64
- // Remaining rows on the tail of the list.
65
- tail: null | Fiber,
66
- // Tail insertions setting.
67
- tailMode: SuspenseListTailMode,
68
-};
69
-
70
-export function findFirstSuspended(row: Fiber): null | Fiber {
71
- let node = row;
72
- while (node !== null) {
73
- if (node.tag === SuspenseComponent) {
74
- const state: SuspenseState | null = node.memoizedState;
75
- if (state !== null) {
76
- const dehydrated: null | SuspenseInstance = state.dehydrated;
77
- if (
78
- dehydrated === null ||
79
- isSuspenseInstancePending(dehydrated) ||
80
- isSuspenseInstanceFallback(dehydrated)
81
- ) {
82
- return node;
83
- }
84
- }
85
- } else if (
86
- node.tag === SuspenseListComponent &&
87
- // revealOrder undefined can't be trusted because it don't
88
- // keep track of whether it suspended or not.
89
- node.memoizedProps.revealOrder !== undefined
90
- ) {
91
- const didSuspend = (node.flags & DidCapture) !== NoFlags;
92
- if (didSuspend) {
93
- return node;
94
- }
95
- } else if (node.child !== null) {
96
- node.child.return = node;
97
- node = node.child;
98
- continue;
99
- }
100
- if (node === row) {
101
- return null;
102
- }
103
- while (node.sibling === null) {
104
- if (node.return === null || node.return === row) {
105
- return null;
106
- }
107
- node = node.return;
108
- }
109
- node.sibling.return = node.return;
110
- node = node.sibling;
111
- }
112
- return null;
113
-}
packages/react-reconciler/src/ReactFiberSuspenseContext.new.js
deleted
-182
@@ -1,182 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-import type {StackCursor} from './ReactFiberStack.new';
12
-import type {
13
- SuspenseState,
14
- SuspenseProps,
15
-} from './ReactFiberSuspenseComponent.new';
16
-
17
-import {enableSuspenseAvoidThisFallback} from 'shared/ReactFeatureFlags';
18
-import {createCursor, push, pop} from './ReactFiberStack.new';
19
-import {isCurrentTreeHidden} from './ReactFiberHiddenContext.new';
20
-import {SuspenseComponent, OffscreenComponent} from './ReactWorkTags';
21
-
22
-// The Suspense handler is the boundary that should capture if something
23
-// suspends, i.e. it's the nearest `catch` block on the stack.
24
-const suspenseHandlerStackCursor: StackCursor<Fiber | null> = createCursor(
25
- null,
26
-);
27
-
28
-function shouldAvoidedBoundaryCapture(
29
- workInProgress: Fiber,
30
- handlerOnStack: Fiber,
31
- props: any,
32
-): boolean {
33
- if (enableSuspenseAvoidThisFallback) {
34
- // If the parent is already showing content, and we're not inside a hidden
35
- // tree, then we should show the avoided fallback.
36
- if (handlerOnStack.alternate !== null && !isCurrentTreeHidden()) {
37
- return true;
38
- }
39
-
40
- // If the handler on the stack is also an avoided boundary, then we should
41
- // favor this inner one.
42
- if (
43
- handlerOnStack.tag === SuspenseComponent &&
44
- handlerOnStack.memoizedProps.unstable_avoidThisFallback === true
45
- ) {
46
- return true;
47
- }
48
-
49
- // If this avoided boundary is dehydrated, then it should capture.
50
- const suspenseState: SuspenseState | null = workInProgress.memoizedState;
51
- if (suspenseState !== null && suspenseState.dehydrated !== null) {
52
- return true;
53
- }
54
- }
55
-
56
- // If none of those cases apply, then we should avoid this fallback and show
57
- // the outer one instead.
58
- return false;
59
-}
60
-
61
-export function isBadSuspenseFallback(
62
- current: Fiber | null,
63
- nextProps: SuspenseProps,
64
-): boolean {
65
- // Check if this is a "bad" fallback state or a good one. A bad fallback state
66
- // is one that we only show as a last resort; if this is a transition, we'll
67
- // block it from displaying, and wait for more data to arrive.
68
- if (current !== null) {
69
- const prevState: SuspenseState = current.memoizedState;
70
- const isShowingFallback = prevState !== null;
71
- if (!isShowingFallback && !isCurrentTreeHidden()) {
72
- // It's bad to switch to a fallback if content is already visible
73
- return true;
74
- }
75
- }
76
-
77
- if (
78
- enableSuspenseAvoidThisFallback &&
79
- nextProps.unstable_avoidThisFallback === true
80
- ) {
81
- // Experimental: Some fallbacks are always bad
82
- return true;
83
- }
84
-
85
- return false;
86
-}
87
-
88
-export function pushPrimaryTreeSuspenseHandler(handler: Fiber): void {
89
- const props = handler.pendingProps;
90
- const handlerOnStack = suspenseHandlerStackCursor.current;
91
- if (
92
- enableSuspenseAvoidThisFallback &&
93
- props.unstable_avoidThisFallback === true &&
94
- handlerOnStack !== null &&
95
- !shouldAvoidedBoundaryCapture(handler, handlerOnStack, props)
96
- ) {
97
- // This boundary should not capture if something suspends. Reuse the
98
- // existing handler on the stack.
99
- push(suspenseHandlerStackCursor, handlerOnStack, handler);
100
- } else {
101
- // Push this handler onto the stack.
102
- push(suspenseHandlerStackCursor, handler, handler);
103
- }
104
-}
105
-
106
-export function pushFallbackTreeSuspenseHandler(fiber: Fiber): void {
107
- // We're about to render the fallback. If something in the fallback suspends,
108
- // it's akin to throwing inside of a `catch` block. This boundary should not
109
- // capture. Reuse the existing handler on the stack.
110
- reuseSuspenseHandlerOnStack(fiber);
111
-}
112
-
113
-export function pushOffscreenSuspenseHandler(fiber: Fiber): void {
114
- if (fiber.tag === OffscreenComponent) {
115
- push(suspenseHandlerStackCursor, fiber, fiber);
116
- } else {
117
- // This is a LegacyHidden component.
118
- reuseSuspenseHandlerOnStack(fiber);
119
- }
120
-}
121
-
122
-export function reuseSuspenseHandlerOnStack(fiber: Fiber) {
123
- push(suspenseHandlerStackCursor, getSuspenseHandler(), fiber);
124
-}
125
-
126
-export function getSuspenseHandler(): Fiber | null {
127
- return suspenseHandlerStackCursor.current;
128
-}
129
-
130
-export function popSuspenseHandler(fiber: Fiber): void {
131
- pop(suspenseHandlerStackCursor, fiber);
132
-}
133
-
134
-// SuspenseList context
135
-// TODO: Move to a separate module? We may change the SuspenseList
136
-// implementation to hide/show in the commit phase, anyway.
137
-export opaque type SuspenseContext = number;
138
-export opaque type SubtreeSuspenseContext: SuspenseContext = number;
139
-export opaque type ShallowSuspenseContext: SuspenseContext = number;
140
-
141
-const DefaultSuspenseContext: SuspenseContext = 0b00;
142
-
143
-const SubtreeSuspenseContextMask: SuspenseContext = 0b01;
144
-
145
-// ForceSuspenseFallback can be used by SuspenseList to force newly added
146
-// items into their fallback state during one of the render passes.
147
-export const ForceSuspenseFallback: ShallowSuspenseContext = 0b10;
148
-
149
-export const suspenseStackCursor: StackCursor<SuspenseContext> = createCursor(
150
- DefaultSuspenseContext,
151
-);
152
-
153
-export function hasSuspenseListContext(
154
- parentContext: SuspenseContext,
155
- flag: SuspenseContext,
156
-): boolean {
157
- return (parentContext & flag) !== 0;
158
-}
159
-
160
-export function setDefaultShallowSuspenseListContext(
161
- parentContext: SuspenseContext,
162
-): SuspenseContext {
163
- return parentContext & SubtreeSuspenseContextMask;
164
-}
165
-
166
-export function setShallowSuspenseListContext(
167
- parentContext: SuspenseContext,
168
- shallowContext: ShallowSuspenseContext,
169
-): SuspenseContext {
170
- return (parentContext & SubtreeSuspenseContextMask) | shallowContext;
171
-}
172
-
173
-export function pushSuspenseListContext(
174
- fiber: Fiber,
175
- newContext: SuspenseContext,
176
-): void {
177
- push(suspenseStackCursor, newContext, fiber);
178
-}
179
-
180
-export function popSuspenseListContext(fiber: Fiber): void {
181
- pop(suspenseStackCursor, fiber);
182
-}
packages/react-reconciler/src/ReactFiberSyncTaskQueue.new.js
deleted
-88
@@ -1,88 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {SchedulerCallback} from './Scheduler';
11
-
12
-import {
13
- DiscreteEventPriority,
14
- getCurrentUpdatePriority,
15
- setCurrentUpdatePriority,
16
-} from './ReactEventPriorities.new';
17
-import {ImmediatePriority, scheduleCallback} from './Scheduler';
18
-
19
-let syncQueue: Array<SchedulerCallback> | null = null;
20
-let includesLegacySyncCallbacks: boolean = false;
21
-let isFlushingSyncQueue: boolean = false;
22
-
23
-export function scheduleSyncCallback(callback: SchedulerCallback) {
24
- // Push this callback into an internal queue. We'll flush these either in
25
- // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
26
- if (syncQueue === null) {
27
- syncQueue = [callback];
28
- } else {
29
- // Push onto existing queue. Don't need to schedule a callback because
30
- // we already scheduled one when we created the queue.
31
- syncQueue.push(callback);
32
- }
33
-}
34
-
35
-export function scheduleLegacySyncCallback(callback: SchedulerCallback) {
36
- includesLegacySyncCallbacks = true;
37
- scheduleSyncCallback(callback);
38
-}
39
-
40
-export function flushSyncCallbacksOnlyInLegacyMode() {
41
- // Only flushes the queue if there's a legacy sync callback scheduled.
42
- // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So
43
- // it might make more sense for the queue to be a list of roots instead of a
44
- // list of generic callbacks. Then we can have two: one for legacy roots, one
45
- // for concurrent roots. And this method would only flush the legacy ones.
46
- if (includesLegacySyncCallbacks) {
47
- flushSyncCallbacks();
48
- }
49
-}
50
-
51
-export function flushSyncCallbacks(): null {
52
- if (!isFlushingSyncQueue && syncQueue !== null) {
53
- // Prevent re-entrance.
54
- isFlushingSyncQueue = true;
55
- let i = 0;
56
- const previousUpdatePriority = getCurrentUpdatePriority();
57
- try {
58
- const isSync = true;
59
- const queue = syncQueue;
60
- // TODO: Is this necessary anymore? The only user code that runs in this
61
- // queue is in the render or commit phases.
62
- setCurrentUpdatePriority(DiscreteEventPriority);
63
- // $FlowFixMe[incompatible-use] found when upgrading Flow
64
- for (; i < queue.length; i++) {
65
- // $FlowFixMe[incompatible-use] found when upgrading Flow
66
- let callback: SchedulerCallback = queue[i];
67
- do {
68
- // $FlowFixMe[incompatible-type] we bail out when we get a null
69
- callback = callback(isSync);
70
- } while (callback !== null);
71
- }
72
- syncQueue = null;
73
- includesLegacySyncCallbacks = false;
74
- } catch (error) {
75
- // If something throws, leave the remaining callbacks on the queue.
76
- if (syncQueue !== null) {
77
- syncQueue = syncQueue.slice(i + 1);
78
- }
79
- // Resume flushing in the next tick
80
- scheduleCallback(ImmediatePriority, flushSyncCallbacks);
81
- throw error;
82
- } finally {
83
- setCurrentUpdatePriority(previousUpdatePriority);
84
- isFlushingSyncQueue = false;
85
- }
86
- }
87
- return null;
88
-}
packages/react-reconciler/src/ReactFiberThenable.new.js
deleted
-175
@@ -1,175 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {
11
- Thenable,
12
- PendingThenable,
13
- FulfilledThenable,
14
- RejectedThenable,
15
-} from 'shared/ReactTypes';
16
-
17
-import ReactSharedInternals from 'shared/ReactSharedInternals';
18
-const {ReactCurrentActQueue} = ReactSharedInternals;
19
-
20
-export opaque type ThenableState = Array<Thenable<any>>;
21
-
22
-// An error that is thrown (e.g. by `use`) to trigger Suspense. If we
23
-// detect this is caught by userspace, we'll log a warning in development.
24
-export const SuspenseException: mixed = new Error(
25
- "Suspense Exception: This is not a real error! It's an implementation " +
26
- 'detail of `use` to interrupt the current render. You must either ' +
27
- 'rethrow it immediately, or move the `use` call outside of the ' +
28
- '`try/catch` block. Capturing without rethrowing will lead to ' +
29
- 'unexpected behavior.\n\n' +
30
- 'To handle async errors, wrap your component in an error boundary, or ' +
31
- "call the promise's `.catch` method and pass the result to `use`",
32
-);
33
-
34
-export function createThenableState(): ThenableState {
35
- // The ThenableState is created the first time a component suspends. If it
36
- // suspends again, we'll reuse the same state.
37
- return [];
38
-}
39
-
40
-export function isThenableResolved(thenable: Thenable<mixed>): boolean {
41
- const status = thenable.status;
42
- return status === 'fulfilled' || status === 'rejected';
43
-}
44
-
45
-function noop(): void {}
46
-
47
-export function trackUsedThenable<T>(
48
- thenableState: ThenableState,
49
- thenable: Thenable<T>,
50
- index: number,
51
-): T {
52
- if (__DEV__ && ReactCurrentActQueue.current !== null) {
53
- ReactCurrentActQueue.didUsePromise = true;
54
- }
55
-
56
- const previous = thenableState[index];
57
- if (previous === undefined) {
58
- thenableState.push(thenable);
59
- } else {
60
- if (previous !== thenable) {
61
- // Reuse the previous thenable, and drop the new one. We can assume
62
- // they represent the same value, because components are idempotent.
63
-
64
- // Avoid an unhandled rejection errors for the Promises that we'll
65
- // intentionally ignore.
66
- thenable.then(noop, noop);
67
- thenable = previous;
68
- }
69
- }
70
-
71
- // We use an expando to track the status and result of a thenable so that we
72
- // can synchronously unwrap the value. Think of this as an extension of the
73
- // Promise API, or a custom interface that is a superset of Thenable.
74
- //
75
- // If the thenable doesn't have a status, set it to "pending" and attach
76
- // a listener that will update its status and result when it resolves.
77
- switch (thenable.status) {
78
- case 'fulfilled': {
79
- const fulfilledValue: T = thenable.value;
80
- return fulfilledValue;
81
- }
82
- case 'rejected': {
83
- const rejectedError = thenable.reason;
84
- throw rejectedError;
85
- }
86
- default: {
87
- if (typeof thenable.status === 'string') {
88
- // Only instrument the thenable if the status if not defined. If
89
- // it's defined, but an unknown value, assume it's been instrumented by
90
- // some custom userspace implementation. We treat it as "pending".
91
- } else {
92
- const pendingThenable: PendingThenable<T> = (thenable: any);
93
- pendingThenable.status = 'pending';
94
- pendingThenable.then(
95
- fulfilledValue => {
96
- if (thenable.status === 'pending') {
97
- const fulfilledThenable: FulfilledThenable<T> = (thenable: any);
98
- fulfilledThenable.status = 'fulfilled';
99
- fulfilledThenable.value = fulfilledValue;
100
- }
101
- },
102
- (error: mixed) => {
103
- if (thenable.status === 'pending') {
104
- const rejectedThenable: RejectedThenable<T> = (thenable: any);
105
- rejectedThenable.status = 'rejected';
106
- rejectedThenable.reason = error;
107
- }
108
- },
109
- );
110
-
111
- // Check one more time in case the thenable resolved synchronously
112
- switch (thenable.status) {
113
- case 'fulfilled': {
114
- const fulfilledThenable: FulfilledThenable<T> = (thenable: any);
115
- return fulfilledThenable.value;
116
- }
117
- case 'rejected': {
118
- const rejectedThenable: RejectedThenable<T> = (thenable: any);
119
- throw rejectedThenable.reason;
120
- }
121
- }
122
- }
123
-
124
- // Suspend.
125
- //
126
- // Throwing here is an implementation detail that allows us to unwind the
127
- // call stack. But we shouldn't allow it to leak into userspace. Throw an
128
- // opaque placeholder value instead of the actual thenable. If it doesn't
129
- // get captured by the work loop, log a warning, because that means
130
- // something in userspace must have caught it.
131
- suspendedThenable = thenable;
132
- if (__DEV__) {
133
- needsToResetSuspendedThenableDEV = true;
134
- }
135
- throw SuspenseException;
136
- }
137
- }
138
-}
139
-
140
-// This is used to track the actual thenable that suspended so it can be
141
-// passed to the rest of the Suspense implementation — which, for historical
142
-// reasons, expects to receive a thenable.
143
-let suspendedThenable: Thenable<any> | null = null;
144
-let needsToResetSuspendedThenableDEV = false;
145
-export function getSuspendedThenable(): Thenable<mixed> {
146
- // This is called right after `use` suspends by throwing an exception. `use`
147
- // throws an opaque value instead of the thenable itself so that it can't be
148
- // caught in userspace. Then the work loop accesses the actual thenable using
149
- // this function.
150
- if (suspendedThenable === null) {
151
- throw new Error(
152
- 'Expected a suspended thenable. This is a bug in React. Please file ' +
153
- 'an issue.',
154
- );
155
- }
156
- const thenable = suspendedThenable;
157
- suspendedThenable = null;
158
- if (__DEV__) {
159
- needsToResetSuspendedThenableDEV = false;
160
- }
161
- return thenable;
162
-}
163
-
164
-export function checkIfUseWrappedInTryCatch(): boolean {
165
- if (__DEV__) {
166
- // This was set right before SuspenseException was thrown, and it should
167
- // have been cleared when the exception was handled. If it wasn't,
168
- // it must have been caught by userspace.
169
- if (needsToResetSuspendedThenableDEV) {
170
- needsToResetSuspendedThenableDEV = false;
171
- return true;
172
- }
173
- }
174
- return false;
175
-}
packages/react-reconciler/src/ReactFiberThrow.new.js
deleted
-529
@@ -1,529 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
11
-import type {Lane, Lanes} from './ReactFiberLane.new';
12
-import type {CapturedValue} from './ReactCapturedValue';
13
-import type {Update} from './ReactFiberClassUpdateQueue.new';
14
-import type {Wakeable} from 'shared/ReactTypes';
15
-import type {OffscreenQueue} from './ReactFiberOffscreenComponent';
16
-
17
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
18
-import {
19
- ClassComponent,
20
- HostRoot,
21
- IncompleteClassComponent,
22
- FunctionComponent,
23
- ForwardRef,
24
- SimpleMemoComponent,
25
- SuspenseComponent,
26
- OffscreenComponent,
27
-} from './ReactWorkTags';
28
-import {
29
- DidCapture,
30
- Incomplete,
31
- NoFlags,
32
- ShouldCapture,
33
- LifecycleEffectMask,
34
- ForceUpdateForLegacySuspense,
35
- ForceClientRender,
36
-} from './ReactFiberFlags';
37
-import {NoMode, ConcurrentMode, DebugTracingMode} from './ReactTypeOfMode';
38
-import {
39
- enableDebugTracing,
40
- enableLazyContextPropagation,
41
- enableUpdaterTracking,
42
-} from 'shared/ReactFeatureFlags';
43
-import {createCapturedValueAtFiber} from './ReactCapturedValue';
44
-import {
45
- enqueueCapturedUpdate,
46
- createUpdate,
47
- CaptureUpdate,
48
- ForceUpdate,
49
- enqueueUpdate,
50
-} from './ReactFiberClassUpdateQueue.new';
51
-import {markFailedErrorBoundaryForHotReloading} from './ReactFiberHotReloading.new';
52
-import {getSuspenseHandler} from './ReactFiberSuspenseContext.new';
53
-import {
54
- renderDidError,
55
- renderDidSuspendDelayIfPossible,
56
- onUncaughtError,
57
- markLegacyErrorBoundaryAsFailed,
58
- isAlreadyFailedLegacyErrorBoundary,
59
- attachPingListener,
60
- restorePendingUpdaters,
61
-} from './ReactFiberWorkLoop.new';
62
-import {propagateParentContextChangesToDeferredTree} from './ReactFiberNewContext.new';
63
-import {logCapturedError} from './ReactFiberErrorLogger';
64
-import {logComponentSuspended} from './DebugTracing';
65
-import {isDevToolsPresent} from './ReactFiberDevToolsHook.new';
66
-import {
67
- SyncLane,
68
- NoTimestamp,
69
- includesSomeLane,
70
- mergeLanes,
71
- pickArbitraryLane,
72
-} from './ReactFiberLane.new';
73
-import {
74
- getIsHydrating,
75
- markDidThrowWhileHydratingDEV,
76
- queueHydrationError,
77
-} from './ReactFiberHydrationContext.new';
78
-import {ConcurrentRoot} from './ReactRootTags';
79
-
80
-function createRootErrorUpdate(
81
- fiber: Fiber,
82
- errorInfo: CapturedValue<mixed>,
83
- lane: Lane,
84
-): Update<mixed> {
85
- const update = createUpdate(NoTimestamp, lane);
86
- // Unmount the root by rendering null.
87
- update.tag = CaptureUpdate;
88
- // Caution: React DevTools currently depends on this property
89
- // being called "element".
90
- update.payload = {element: null};
91
- const error = errorInfo.value;
92
- update.callback = () => {
93
- onUncaughtError(error);
94
- logCapturedError(fiber, errorInfo);
95
- };
96
- return update;
97
-}
98
-
99
-function createClassErrorUpdate(
100
- fiber: Fiber,
101
- errorInfo: CapturedValue<mixed>,
102
- lane: Lane,
103
-): Update<mixed> {
104
- const update = createUpdate(NoTimestamp, lane);
105
- update.tag = CaptureUpdate;
106
- const getDerivedStateFromError = fiber.type.getDerivedStateFromError;
107
- if (typeof getDerivedStateFromError === 'function') {
108
- const error = errorInfo.value;
109
- update.payload = () => {
110
- return getDerivedStateFromError(error);
111
- };
112
- update.callback = () => {
113
- if (__DEV__) {
114
- markFailedErrorBoundaryForHotReloading(fiber);
115
- }
116
- logCapturedError(fiber, errorInfo);
117
- };
118
- }
119
-
120
- const inst = fiber.stateNode;
121
- if (inst !== null && typeof inst.componentDidCatch === 'function') {
122
- update.callback = function callback() {
123
- if (__DEV__) {
124
- markFailedErrorBoundaryForHotReloading(fiber);
125
- }
126
- logCapturedError(fiber, errorInfo);
127
- if (typeof getDerivedStateFromError !== 'function') {
128
- // To preserve the preexisting retry behavior of error boundaries,
129
- // we keep track of which ones already failed during this batch.
130
- // This gets reset before we yield back to the browser.
131
- // TODO: Warn in strict mode if getDerivedStateFromError is
132
- // not defined.
133
- markLegacyErrorBoundaryAsFailed(this);
134
- }
135
- const error = errorInfo.value;
136
- const stack = errorInfo.stack;
137
- this.componentDidCatch(error, {
138
- componentStack: stack !== null ? stack : '',
139
- });
140
- if (__DEV__) {
141
- if (typeof getDerivedStateFromError !== 'function') {
142
- // If componentDidCatch is the only error boundary method defined,
143
- // then it needs to call setState to recover from errors.
144
- // If no state update is scheduled then the boundary will swallow the error.
145
- if (!includesSomeLane(fiber.lanes, (SyncLane: Lane))) {
146
- console.error(
147
- '%s: Error boundaries should implement getDerivedStateFromError(). ' +
148
- 'In that method, return a state update to display an error message or fallback UI.',
149
- getComponentNameFromFiber(fiber) || 'Unknown',
150
- );
151
- }
152
- }
153
- }
154
- };
155
- }
156
- return update;
157
-}
158
-
159
-function resetSuspendedComponent(sourceFiber: Fiber, rootRenderLanes: Lanes) {
160
- if (enableLazyContextPropagation) {
161
- const currentSourceFiber = sourceFiber.alternate;
162
- if (currentSourceFiber !== null) {
163
- // Since we never visited the children of the suspended component, we
164
- // need to propagate the context change now, to ensure that we visit
165
- // them during the retry.
166
- //
167
- // We don't have to do this for errors because we retry errors without
168
- // committing in between. So this is specific to Suspense.
169
- propagateParentContextChangesToDeferredTree(
170
- currentSourceFiber,
171
- sourceFiber,
172
- rootRenderLanes,
173
- );
174
- }
175
- }
176
-
177
- // Reset the memoizedState to what it was before we attempted to render it.
178
- // A legacy mode Suspense quirk, only relevant to hook components.
179
- const tag = sourceFiber.tag;
180
- if (
181
- (sourceFiber.mode & ConcurrentMode) === NoMode &&
182
- (tag === FunctionComponent ||
183
- tag === ForwardRef ||
184
- tag === SimpleMemoComponent)
185
- ) {
186
- const currentSource = sourceFiber.alternate;
187
- if (currentSource) {
188
- sourceFiber.updateQueue = currentSource.updateQueue;
189
- sourceFiber.memoizedState = currentSource.memoizedState;
190
- sourceFiber.lanes = currentSource.lanes;
191
- } else {
192
- sourceFiber.updateQueue = null;
193
- sourceFiber.memoizedState = null;
194
- }
195
- }
196
-}
197
-
198
-function markSuspenseBoundaryShouldCapture(
199
- suspenseBoundary: Fiber,
200
- returnFiber: Fiber,
201
- sourceFiber: Fiber,
202
- root: FiberRoot,
203
- rootRenderLanes: Lanes,
204
-): Fiber | null {
205
- // This marks a Suspense boundary so that when we're unwinding the stack,
206
- // it captures the suspended "exception" and does a second (fallback) pass.
207
- if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) {
208
- // Legacy Mode Suspense
209
- //
210
- // If the boundary is in legacy mode, we should *not*
211
- // suspend the commit. Pretend as if the suspended component rendered
212
- // null and keep rendering. When the Suspense boundary completes,
213
- // we'll do a second pass to render the fallback.
214
- if (suspenseBoundary === returnFiber) {
215
- // Special case where we suspended while reconciling the children of
216
- // a Suspense boundary's inner Offscreen wrapper fiber. This happens
217
- // when a React.lazy component is a direct child of a
218
- // Suspense boundary.
219
- //
220
- // Suspense boundaries are implemented as multiple fibers, but they
221
- // are a single conceptual unit. The legacy mode behavior where we
222
- // pretend the suspended fiber committed as `null` won't work,
223
- // because in this case the "suspended" fiber is the inner
224
- // Offscreen wrapper.
225
- //
226
- // Because the contents of the boundary haven't started rendering
227
- // yet (i.e. nothing in the tree has partially rendered) we can
228
- // switch to the regular, concurrent mode behavior: mark the
229
- // boundary with ShouldCapture and enter the unwind phase.
230
- suspenseBoundary.flags |= ShouldCapture;
231
- } else {
232
- suspenseBoundary.flags |= DidCapture;
233
- sourceFiber.flags |= ForceUpdateForLegacySuspense;
234
-
235
- // We're going to commit this fiber even though it didn't complete.
236
- // But we shouldn't call any lifecycle methods or callbacks. Remove
237
- // all lifecycle effect tags.
238
- sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
239
-
240
- if (sourceFiber.tag === ClassComponent) {
241
- const currentSourceFiber = sourceFiber.alternate;
242
- if (currentSourceFiber === null) {
243
- // This is a new mount. Change the tag so it's not mistaken for a
244
- // completed class component. For example, we should not call
245
- // componentWillUnmount if it is deleted.
246
- sourceFiber.tag = IncompleteClassComponent;
247
- } else {
248
- // When we try rendering again, we should not reuse the current fiber,
249
- // since it's known to be in an inconsistent state. Use a force update to
250
- // prevent a bail out.
251
- const update = createUpdate(NoTimestamp, SyncLane);
252
- update.tag = ForceUpdate;
253
- enqueueUpdate(sourceFiber, update, SyncLane);
254
- }
255
- }
256
-
257
- // The source fiber did not complete. Mark it with Sync priority to
258
- // indicate that it still has pending work.
259
- sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
260
- }
261
- return suspenseBoundary;
262
- }
263
- // Confirmed that the boundary is in a concurrent mode tree. Continue
264
- // with the normal suspend path.
265
- //
266
- // After this we'll use a set of heuristics to determine whether this
267
- // render pass will run to completion or restart or "suspend" the commit.
268
- // The actual logic for this is spread out in different places.
269
- //
270
- // This first principle is that if we're going to suspend when we complete
271
- // a root, then we should also restart if we get an update or ping that
272
- // might unsuspend it, and vice versa. The only reason to suspend is
273
- // because you think you might want to restart before committing. However,
274
- // it doesn't make sense to restart only while in the period we're suspended.
275
- //
276
- // Restarting too aggressively is also not good because it starves out any
277
- // intermediate loading state. So we use heuristics to determine when.
278
-
279
- // Suspense Heuristics
280
- //
281
- // If nothing threw a Promise or all the same fallbacks are already showing,
282
- // then don't suspend/restart.
283
- //
284
- // If this is an initial render of a new tree of Suspense boundaries and
285
- // those trigger a fallback, then don't suspend/restart. We want to ensure
286
- // that we can show the initial loading state as quickly as possible.
287
- //
288
- // If we hit a "Delayed" case, such as when we'd switch from content back into
289
- // a fallback, then we should always suspend/restart. Transitions apply
290
- // to this case. If none is defined, JND is used instead.
291
- //
292
- // If we're already showing a fallback and it gets "retried", allowing us to show
293
- // another level, but there's still an inner boundary that would show a fallback,
294
- // then we suspend/restart for 500ms since the last time we showed a fallback
295
- // anywhere in the tree. This effectively throttles progressive loading into a
296
- // consistent train of commits. This also gives us an opportunity to restart to
297
- // get to the completed state slightly earlier.
298
- //
299
- // If there's ambiguity due to batching it's resolved in preference of:
300
- // 1) "delayed", 2) "initial render", 3) "retry".
301
- //
302
- // We want to ensure that a "busy" state doesn't get force committed. We want to
303
- // ensure that new initial loading states can commit as soon as possible.
304
- suspenseBoundary.flags |= ShouldCapture;
305
- // TODO: I think we can remove this, since we now use `DidCapture` in
306
- // the begin phase to prevent an early bailout.
307
- suspenseBoundary.lanes = rootRenderLanes;
308
- return suspenseBoundary;
309
-}
310
-
311
-function throwException(
312
- root: FiberRoot,
313
- returnFiber: Fiber,
314
- sourceFiber: Fiber,
315
- value: mixed,
316
- rootRenderLanes: Lanes,
317
-): void {
318
- // The source fiber did not complete.
319
- sourceFiber.flags |= Incomplete;
320
-
321
- if (enableUpdaterTracking) {
322
- if (isDevToolsPresent) {
323
- // If we have pending work still, restore the original updaters
324
- restorePendingUpdaters(root, rootRenderLanes);
325
- }
326
- }
327
-
328
- if (
329
- value !== null &&
330
- typeof value === 'object' &&
331
- typeof value.then === 'function'
332
- ) {
333
- // This is a wakeable. The component suspended.
334
- const wakeable: Wakeable = (value: any);
335
- resetSuspendedComponent(sourceFiber, rootRenderLanes);
336
-
337
- if (__DEV__) {
338
- if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
339
- markDidThrowWhileHydratingDEV();
340
- }
341
- }
342
-
343
- if (__DEV__) {
344
- if (enableDebugTracing) {
345
- if (sourceFiber.mode & DebugTracingMode) {
346
- const name = getComponentNameFromFiber(sourceFiber) || 'Unknown';
347
- logComponentSuspended(name, wakeable);
348
- }
349
- }
350
- }
351
-
352
- // Schedule the nearest Suspense to re-render the timed out view.
353
- const suspenseBoundary = getSuspenseHandler();
354
- if (suspenseBoundary !== null) {
355
- switch (suspenseBoundary.tag) {
356
- case SuspenseComponent: {
357
- suspenseBoundary.flags &= ~ForceClientRender;
358
- markSuspenseBoundaryShouldCapture(
359
- suspenseBoundary,
360
- returnFiber,
361
- sourceFiber,
362
- root,
363
- rootRenderLanes,
364
- );
365
- // Retry listener
366
- //
367
- // If the fallback does commit, we need to attach a different type of
368
- // listener. This one schedules an update on the Suspense boundary to
369
- // turn the fallback state off.
370
- //
371
- // Stash the wakeable on the boundary fiber so we can access it in the
372
- // commit phase.
373
- //
374
- // When the wakeable resolves, we'll attempt to render the boundary
375
- // again ("retry").
376
- const wakeables: Set<Wakeable> | null = (suspenseBoundary.updateQueue: any);
377
- if (wakeables === null) {
378
- suspenseBoundary.updateQueue = new Set([wakeable]);
379
- } else {
380
- wakeables.add(wakeable);
381
- }
382
- break;
383
- }
384
- case OffscreenComponent: {
385
- if (suspenseBoundary.mode & ConcurrentMode) {
386
- suspenseBoundary.flags |= ShouldCapture;
387
- const offscreenQueue: OffscreenQueue | null = (suspenseBoundary.updateQueue: any);
388
- if (offscreenQueue === null) {
389
- const newOffscreenQueue: OffscreenQueue = {
390
- transitions: null,
391
- markerInstances: null,
392
- wakeables: new Set([wakeable]),
393
- };
394
- suspenseBoundary.updateQueue = newOffscreenQueue;
395
- } else {
396
- const wakeables = offscreenQueue.wakeables;
397
- if (wakeables === null) {
398
- offscreenQueue.wakeables = new Set([wakeable]);
399
- } else {
400
- wakeables.add(wakeable);
401
- }
402
- }
403
- break;
404
- }
405
- }
406
- // eslint-disable-next-line no-fallthrough
407
- default: {
408
- throw new Error(
409
- `Unexpected Suspense handler tag (${suspenseBoundary.tag}). This ` +
410
- 'is a bug in React.',
411
- );
412
- }
413
- }
414
- // We only attach ping listeners in concurrent mode. Legacy Suspense always
415
- // commits fallbacks synchronously, so there are no pings.
416
- if (suspenseBoundary.mode & ConcurrentMode) {
417
- attachPingListener(root, wakeable, rootRenderLanes);
418
- }
419
- return;
420
- } else {
421
- // No boundary was found. Unless this is a sync update, this is OK.
422
- // We can suspend and wait for more data to arrive.
423
-
424
- if (root.tag === ConcurrentRoot) {
425
- // In a concurrent root, suspending without a Suspense boundary is
426
- // allowed. It will suspend indefinitely without committing.
427
- //
428
- // TODO: Should we have different behavior for discrete updates? What
429
- // about flushSync? Maybe it should put the tree into an inert state,
430
- // and potentially log a warning. Revisit this for a future release.
431
- attachPingListener(root, wakeable, rootRenderLanes);
432
- renderDidSuspendDelayIfPossible();
433
- return;
434
- } else {
435
- // In a legacy root, suspending without a boundary is always an error.
436
- const uncaughtSuspenseError = new Error(
437
- 'A component suspended while responding to synchronous input. This ' +
438
- 'will cause the UI to be replaced with a loading indicator. To ' +
439
- 'fix, updates that suspend should be wrapped ' +
440
- 'with startTransition.',
441
- );
442
- value = uncaughtSuspenseError;
443
- }
444
- }
445
- } else {
446
- // This is a regular error, not a Suspense wakeable.
447
- if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
448
- markDidThrowWhileHydratingDEV();
449
- const suspenseBoundary = getSuspenseHandler();
450
- // If the error was thrown during hydration, we may be able to recover by
451
- // discarding the dehydrated content and switching to a client render.
452
- // Instead of surfacing the error, find the nearest Suspense boundary
453
- // and render it again without hydration.
454
- if (suspenseBoundary !== null) {
455
- if ((suspenseBoundary.flags & ShouldCapture) === NoFlags) {
456
- // Set a flag to indicate that we should try rendering the normal
457
- // children again, not the fallback.
458
- suspenseBoundary.flags |= ForceClientRender;
459
- }
460
- markSuspenseBoundaryShouldCapture(
461
- suspenseBoundary,
462
- returnFiber,
463
- sourceFiber,
464
- root,
465
- rootRenderLanes,
466
- );
467
-
468
- // Even though the user may not be affected by this error, we should
469
- // still log it so it can be fixed.
470
- queueHydrationError(createCapturedValueAtFiber(value, sourceFiber));
471
- return;
472
- }
473
- } else {
474
- // Otherwise, fall through to the error path.
475
- }
476
- }
477
-
478
- value = createCapturedValueAtFiber(value, sourceFiber);
479
- renderDidError(value);
480
-
481
- // We didn't find a boundary that could handle this type of exception. Start
482
- // over and traverse parent path again, this time treating the exception
483
- // as an error.
484
- let workInProgress: Fiber = returnFiber;
485
- do {
486
- switch (workInProgress.tag) {
487
- case HostRoot: {
488
- const errorInfo = value;
489
- workInProgress.flags |= ShouldCapture;
490
- const lane = pickArbitraryLane(rootRenderLanes);
491
- workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
492
- const update = createRootErrorUpdate(workInProgress, errorInfo, lane);
493
- enqueueCapturedUpdate(workInProgress, update);
494
- return;
495
- }
496
- case ClassComponent:
497
- // Capture and retry
498
- const errorInfo = value;
499
- const ctor = workInProgress.type;
500
- const instance = workInProgress.stateNode;
501
- if (
502
- (workInProgress.flags & DidCapture) === NoFlags &&
503
- (typeof ctor.getDerivedStateFromError === 'function' ||
504
- (instance !== null &&
505
- typeof instance.componentDidCatch === 'function' &&
506
- !isAlreadyFailedLegacyErrorBoundary(instance)))
507
- ) {
508
- workInProgress.flags |= ShouldCapture;
509
- const lane = pickArbitraryLane(rootRenderLanes);
510
- workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
511
- // Schedule the error boundary to re-render using updated state
512
- const update = createClassErrorUpdate(
513
- workInProgress,
514
- errorInfo,
515
- lane,
516
- );
517
- enqueueCapturedUpdate(workInProgress, update);
518
- return;
519
- }
520
- break;
521
- default:
522
- break;
523
- }
524
- // $FlowFixMe[incompatible-type] we bail out when we get a null
525
- workInProgress = workInProgress.return;
526
- } while (workInProgress !== null);
527
-}
528
-
529
-export {throwException, createRootErrorUpdate, createClassErrorUpdate};
packages/react-reconciler/src/ReactFiberTracingMarkerComponent.new.js
deleted
-271
@@ -1,271 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {
11
- TransitionTracingCallbacks,
12
- Fiber,
13
- FiberRoot,
14
-} from './ReactInternalTypes';
15
-import type {OffscreenInstance} from './ReactFiberOffscreenComponent';
16
-import type {StackCursor} from './ReactFiberStack.new';
17
-
18
-import {enableTransitionTracing} from 'shared/ReactFeatureFlags';
19
-import {createCursor, push, pop} from './ReactFiberStack.new';
20
-import {getWorkInProgressTransitions} from './ReactFiberWorkLoop.new';
21
-
22
-export type SuspenseInfo = {name: string | null};
23
-
24
-export type PendingTransitionCallbacks = {
25
- transitionStart: Array<Transition> | null,
26
- transitionProgress: Map<Transition, PendingBoundaries> | null,
27
- transitionComplete: Array<Transition> | null,
28
- markerProgress: Map<
29
- string,
30
- {pendingBoundaries: PendingBoundaries, transitions: Set<Transition>},
31
- > | null,
32
- markerIncomplete: Map<
33
- string,
34
- {aborts: Array<TransitionAbort>, transitions: Set<Transition>},
35
- > | null,
36
- markerComplete: Map<string, Set<Transition>> | null,
37
-};
38
-
39
-export type Transition = {
40
- name: string,
41
- startTime: number,
42
-};
43
-
44
-export type BatchConfigTransition = {
45
- name?: string,
46
- startTime?: number,
47
- _updatedFibers?: Set<Fiber>,
48
-};
49
-
50
-// TODO: Is there a way to not include the tag or name here?
51
-export type TracingMarkerInstance = {
52
- tag?: TracingMarkerTag,
53
- transitions: Set<Transition> | null,
54
- pendingBoundaries: PendingBoundaries | null,
55
- aborts: Array<TransitionAbort> | null,
56
- name: string | null,
57
-};
58
-
59
-export type TransitionAbort = {
60
- reason: 'error' | 'unknown' | 'marker' | 'suspense',
61
- name?: string | null,
62
-};
63
-
64
-export const TransitionRoot = 0;
65
-export const TransitionTracingMarker = 1;
66
-export type TracingMarkerTag = 0 | 1;
67
-
68
-export type PendingBoundaries = Map<OffscreenInstance, SuspenseInfo>;
69
-
70
-export function processTransitionCallbacks(
71
- pendingTransitions: PendingTransitionCallbacks,
72
- endTime: number,
73
- callbacks: TransitionTracingCallbacks,
74
-): void {
75
- if (enableTransitionTracing) {
76
- if (pendingTransitions !== null) {
77
- const transitionStart = pendingTransitions.transitionStart;
78
- const onTransitionStart = callbacks.onTransitionStart;
79
- if (transitionStart !== null && onTransitionStart != null) {
80
- transitionStart.forEach(transition =>
81
- onTransitionStart(transition.name, transition.startTime),
82
- );
83
- }
84
-
85
- const markerProgress = pendingTransitions.markerProgress;
86
- const onMarkerProgress = callbacks.onMarkerProgress;
87
- if (onMarkerProgress != null && markerProgress !== null) {
88
- markerProgress.forEach((markerInstance, markerName) => {
89
- if (markerInstance.transitions !== null) {
90
- // TODO: Clone the suspense object so users can't modify it
91
- const pending =
92
- markerInstance.pendingBoundaries !== null
93
- ? Array.from(markerInstance.pendingBoundaries.values())
94
- : [];
95
- markerInstance.transitions.forEach(transition => {
96
- onMarkerProgress(
97
- transition.name,
98
- markerName,
99
- transition.startTime,
100
- endTime,
101
- pending,
102
- );
103
- });
104
- }
105
- });
106
- }
107
-
108
- const markerComplete = pendingTransitions.markerComplete;
109
- const onMarkerComplete = callbacks.onMarkerComplete;
110
- if (markerComplete !== null && onMarkerComplete != null) {
111
- markerComplete.forEach((transitions, markerName) => {
112
- transitions.forEach(transition => {
113
- onMarkerComplete(
114
- transition.name,
115
- markerName,
116
- transition.startTime,
117
- endTime,
118
- );
119
- });
120
- });
121
- }
122
-
123
- const markerIncomplete = pendingTransitions.markerIncomplete;
124
- const onMarkerIncomplete = callbacks.onMarkerIncomplete;
125
- if (onMarkerIncomplete != null && markerIncomplete !== null) {
126
- markerIncomplete.forEach(({transitions, aborts}, markerName) => {
127
- transitions.forEach(transition => {
128
- const filteredAborts = [];
129
- aborts.forEach(abort => {
130
- switch (abort.reason) {
131
- case 'marker': {
132
- filteredAborts.push({
133
- type: 'marker',
134
- name: abort.name,
135
- endTime,
136
- });
137
- break;
138
- }
139
- case 'suspense': {
140
- filteredAborts.push({
141
- type: 'suspense',
142
- name: abort.name,
143
- endTime,
144
- });
145
- break;
146
- }
147
- default: {
148
- break;
149
- }
150
- }
151
- });
152
-
153
- if (filteredAborts.length > 0) {
154
- onMarkerIncomplete(
155
- transition.name,
156
- markerName,
157
- transition.startTime,
158
- filteredAborts,
159
- );
160
- }
161
- });
162
- });
163
- }
164
-
165
- const transitionProgress = pendingTransitions.transitionProgress;
166
- const onTransitionProgress = callbacks.onTransitionProgress;
167
- if (onTransitionProgress != null && transitionProgress !== null) {
168
- transitionProgress.forEach((pending, transition) => {
169
- onTransitionProgress(
170
- transition.name,
171
- transition.startTime,
172
- endTime,
173
- Array.from(pending.values()),
174
- );
175
- });
176
- }
177
-
178
- const transitionComplete = pendingTransitions.transitionComplete;
179
- const onTransitionComplete = callbacks.onTransitionComplete;
180
- if (transitionComplete !== null && onTransitionComplete != null) {
181
- transitionComplete.forEach(transition =>
182
- onTransitionComplete(transition.name, transition.startTime, endTime),
183
- );
184
- }
185
- }
186
- }
187
-}
188
-
189
-// For every tracing marker, store a pointer to it. We will later access it
190
-// to get the set of suspense boundaries that need to resolve before the
191
-// tracing marker can be logged as complete
192
-// This code lives separate from the ReactFiberTransition code because
193
-// we push and pop on the tracing marker, not the suspense boundary
194
-const markerInstanceStack: StackCursor<Array<TracingMarkerInstance> | null> = createCursor(
195
- null,
196
-);
197
-
198
-export function pushRootMarkerInstance(workInProgress: Fiber): void {
199
- if (enableTransitionTracing) {
200
- // On the root, every transition gets mapped to it's own map of
201
- // suspense boundaries. The transition is marked as complete when
202
- // the suspense boundaries map is empty. We do this because every
203
- // transition completes at different times and depends on different
204
- // suspense boundaries to complete. We store all the transitions
205
- // along with its map of suspense boundaries in the root incomplete
206
- // transitions map. Each entry in this map functions like a tracing
207
- // marker does, so we can push it onto the marker instance stack
208
- const transitions = getWorkInProgressTransitions();
209
- const root: FiberRoot = workInProgress.stateNode;
210
-
211
- if (transitions !== null) {
212
- transitions.forEach(transition => {
213
- if (!root.incompleteTransitions.has(transition)) {
214
- const markerInstance: TracingMarkerInstance = {
215
- tag: TransitionRoot,
216
- transitions: new Set([transition]),
217
- pendingBoundaries: null,
218
- aborts: null,
219
- name: null,
220
- };
221
- root.incompleteTransitions.set(transition, markerInstance);
222
- }
223
- });
224
- }
225
-
226
- const markerInstances = [];
227
- // For ever transition on the suspense boundary, we push the transition
228
- // along with its map of pending suspense boundaries onto the marker
229
- // instance stack.
230
- root.incompleteTransitions.forEach(markerInstance => {
231
- markerInstances.push(markerInstance);
232
- });
233
- push(markerInstanceStack, markerInstances, workInProgress);
234
- }
235
-}
236
-
237
-export function popRootMarkerInstance(workInProgress: Fiber) {
238
- if (enableTransitionTracing) {
239
- pop(markerInstanceStack, workInProgress);
240
- }
241
-}
242
-
243
-export function pushMarkerInstance(
244
- workInProgress: Fiber,
245
- markerInstance: TracingMarkerInstance,
246
-): void {
247
- if (enableTransitionTracing) {
248
- if (markerInstanceStack.current === null) {
249
- push(markerInstanceStack, [markerInstance], workInProgress);
250
- } else {
251
- push(
252
- markerInstanceStack,
253
- markerInstanceStack.current.concat(markerInstance),
254
- workInProgress,
255
- );
256
- }
257
- }
258
-}
259
-
260
-export function popMarkerInstance(workInProgress: Fiber): void {
261
- if (enableTransitionTracing) {
262
- pop(markerInstanceStack, workInProgress);
263
- }
264
-}
265
-
266
-export function getMarkerInstances(): Array<TracingMarkerInstance> | null {
267
- if (enableTransitionTracing) {
268
- return markerInstanceStack.current;
269
- }
270
- return null;
271
-}
packages/react-reconciler/src/ReactFiberTransition.js
deleted
-19
@@ -1,19 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import ReactSharedInternals from 'shared/ReactSharedInternals';
11
-import type {Transition} from './ReactFiberTracingMarkerComponent.new';
12
-
13
-const {ReactCurrentBatchConfig} = ReactSharedInternals;
14
-
15
-export const NoTransition = null;
16
-
17
-export function requestCurrentTransition(): Transition | null {
18
- return ReactCurrentBatchConfig.transition;
19
-}
packages/react-reconciler/src/ReactFiberTransition.new.js
deleted
-201
@@ -1,201 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
10
-import type {Lanes} from './ReactFiberLane.new';
11
-import type {StackCursor} from './ReactFiberStack.new';
12
-import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent.new';
13
-import type {Transition} from './ReactFiberTracingMarkerComponent.new';
14
-
15
-import {enableCache, enableTransitionTracing} from 'shared/ReactFeatureFlags';
16
-import {isPrimaryRenderer} from './ReactFiberHostConfig';
17
-import {createCursor, push, pop} from './ReactFiberStack.new';
18
-import {
19
- getWorkInProgressRoot,
20
- getWorkInProgressTransitions,
21
-} from './ReactFiberWorkLoop.new';
22
-import {
23
- createCache,
24
- retainCache,
25
- CacheContext,
26
-} from './ReactFiberCacheComponent.new';
27
-
28
-// When retrying a Suspense/Offscreen boundary, we restore the cache that was
29
-// used during the previous render by placing it here, on the stack.
30
-const resumedCache: StackCursor<Cache | null> = createCursor(null);
31
-
32
-// During the render/synchronous commit phase, we don't actually process the
33
-// transitions. Therefore, we want to lazily combine transitions. Instead of
34
-// comparing the arrays of transitions when we combine them and storing them
35
-// and filtering out the duplicates, we will instead store the unprocessed transitions
36
-// in an array and actually filter them in the passive phase.
37
-const transitionStack: StackCursor<Array<Transition> | null> = createCursor(
38
- null,
39
-);
40
-
41
-function peekCacheFromPool(): Cache | null {
42
- if (!enableCache) {
43
- return (null: any);
44
- }
45
-
46
- // Check if the cache pool already has a cache we can use.
47
-
48
- // If we're rendering inside a Suspense boundary that is currently hidden,
49
- // we should use the same cache that we used during the previous render, if
50
- // one exists.
51
- const cacheResumedFromPreviousRender = resumedCache.current;
52
- if (cacheResumedFromPreviousRender !== null) {
53
- return cacheResumedFromPreviousRender;
54
- }
55
-
56
- // Otherwise, check the root's cache pool.
57
- const root = (getWorkInProgressRoot(): any);
58
- const cacheFromRootCachePool = root.pooledCache;
59
-
60
- return cacheFromRootCachePool;
61
-}
62
-
63
-export function requestCacheFromPool(renderLanes: Lanes): Cache {
64
- // Similar to previous function, except if there's not already a cache in the
65
- // pool, we allocate a new one.
66
- const cacheFromPool = peekCacheFromPool();
67
- if (cacheFromPool !== null) {
68
- return cacheFromPool;
69
- }
70
-
71
- // Create a fresh cache and add it to the root cache pool. A cache can have
72
- // multiple owners:
73
- // - A cache pool that lives on the FiberRoot. This is where all fresh caches
74
- // are originally created (TODO: except during refreshes, until we implement
75
- // this correctly). The root takes ownership immediately when the cache is
76
- // created. Conceptually, root.pooledCache is an Option<Arc<Cache>> (owned),
77
- // and the return value of this function is a &Arc<Cache> (borrowed).
78
- // - One of several fiber types: host root, cache boundary, suspense
79
- // component. These retain and release in the commit phase.
80
-
81
- const root = (getWorkInProgressRoot(): any);
82
- const freshCache = createCache();
83
- root.pooledCache = freshCache;
84
- retainCache(freshCache);
85
- if (freshCache !== null) {
86
- root.pooledCacheLanes |= renderLanes;
87
- }
88
- return freshCache;
89
-}
90
-
91
-export function pushRootTransition(
92
- workInProgress: Fiber,
93
- root: FiberRoot,
94
- renderLanes: Lanes,
95
-) {
96
- if (enableTransitionTracing) {
97
- const rootTransitions = getWorkInProgressTransitions();
98
- push(transitionStack, rootTransitions, workInProgress);
99
- }
100
-}
101
-
102
-export function popRootTransition(
103
- workInProgress: Fiber,
104
- root: FiberRoot,
105
- renderLanes: Lanes,
106
-) {
107
- if (enableTransitionTracing) {
108
- pop(transitionStack, workInProgress);
109
- }
110
-}
111
-
112
-export function pushTransition(
113
- offscreenWorkInProgress: Fiber,
114
- prevCachePool: SpawnedCachePool | null,
115
- newTransitions: Array<Transition> | null,
116
-): void {
117
- if (enableCache) {
118
- if (prevCachePool === null) {
119
- push(resumedCache, resumedCache.current, offscreenWorkInProgress);
120
- } else {
121
- push(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
122
- }
123
- }
124
-
125
- if (enableTransitionTracing) {
126
- if (transitionStack.current === null) {
127
- push(transitionStack, newTransitions, offscreenWorkInProgress);
128
- } else if (newTransitions === null) {
129
- push(transitionStack, transitionStack.current, offscreenWorkInProgress);
130
- } else {
131
- push(
132
- transitionStack,
133
- transitionStack.current.concat(newTransitions),
134
- offscreenWorkInProgress,
135
- );
136
- }
137
- }
138
-}
139
-
140
-export function popTransition(workInProgress: Fiber, current: Fiber | null) {
141
- if (current !== null) {
142
- if (enableTransitionTracing) {
143
- pop(transitionStack, workInProgress);
144
- }
145
-
146
- if (enableCache) {
147
- pop(resumedCache, workInProgress);
148
- }
149
- }
150
-}
151
-
152
-export function getPendingTransitions(): Array<Transition> | null {
153
- if (!enableTransitionTracing) {
154
- return null;
155
- }
156
-
157
- return transitionStack.current;
158
-}
159
-
160
-export function getSuspendedCache(): SpawnedCachePool | null {
161
- if (!enableCache) {
162
- return null;
163
- }
164
- // This function is called when a Suspense boundary suspends. It returns the
165
- // cache that would have been used to render fresh data during this render,
166
- // if there was any, so that we can resume rendering with the same cache when
167
- // we receive more data.
168
- const cacheFromPool = peekCacheFromPool();
169
- if (cacheFromPool === null) {
170
- return null;
171
- }
172
-
173
- return {
174
- // We must also save the parent, so that when we resume we can detect
175
- // a refresh.
176
- parent: isPrimaryRenderer
177
- ? CacheContext._currentValue
178
- : CacheContext._currentValue2,
179
- pool: cacheFromPool,
180
- };
181
-}
182
-
183
-export function getOffscreenDeferredCache(): SpawnedCachePool | null {
184
- if (!enableCache) {
185
- return null;
186
- }
187
-
188
- const cacheFromPool = peekCacheFromPool();
189
- if (cacheFromPool === null) {
190
- return null;
191
- }
192
-
193
- return {
194
- // We must also store the parent, so that when we resume we can detect
195
- // a refresh.
196
- parent: isPrimaryRenderer
197
- ? CacheContext._currentValue
198
- : CacheContext._currentValue2,
199
- pool: cacheFromPool,
200
- };
201
-}
packages/react-reconciler/src/ReactFiberTransition.old.js
+10
@@ -25,6 +25,16 @@ import {
25
CacheContext,
26
} from './ReactFiberCacheComponent.old';
27
28
+import ReactSharedInternals from 'shared/ReactSharedInternals';
29
+
30
+const {ReactCurrentBatchConfig} = ReactSharedInternals;
31
+
32
+export const NoTransition = null;
33
+
34
+export function requestCurrentTransition(): Transition | null {
35
+ return ReactCurrentBatchConfig.transition;
36
+}
37
+
38
// When retrying a Suspense/Offscreen boundary, we restore the cache that was
39
// used during the previous render by placing it here, on the stack.
40
const resumedCache: StackCursor<Cache | null> = createCursor(null);
packages/react-reconciler/src/ReactFiberTransitionPool.old.js
deleted
-154
@@ -1,154 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
10
-import type {Lanes} from './ReactFiberLane.old';
11
-import type {StackCursor} from './ReactFiberStack.old';
12
-import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent.old';
13
-
14
-import {enableCache} from 'shared/ReactFeatureFlags';
15
-import {isPrimaryRenderer} from './ReactFiberHostConfig';
16
-import {createCursor, push, pop} from './ReactFiberStack.old';
17
-import {getWorkInProgressRoot} from './ReactFiberWorkLoop.old';
18
-import {
19
- createCache,
20
- retainCache,
21
- CacheContext,
22
-} from './ReactFiberCacheComponent.old';
23
-
24
-// When retrying a Suspense/Offscreen boundary, we restore the cache that was
25
-// used during the previous render by placing it here, on the stack.
26
-const resumedCache: StackCursor<Cache | null> = createCursor(null);
27
-
28
-function peekCacheFromPool(): Cache | null {
29
- if (!enableCache) {
30
- return (null: any);
31
- }
32
-
33
- // Check if the cache pool already has a cache we can use.
34
-
35
- // If we're rendering inside a Suspense boundary that is currently hidden,
36
- // we should use the same cache that we used during the previous render, if
37
- // one exists.
38
- const cacheResumedFromPreviousRender = resumedCache.current;
39
- if (cacheResumedFromPreviousRender !== null) {
40
- return cacheResumedFromPreviousRender;
41
- }
42
-
43
- // Otherwise, check the root's cache pool.
44
- const root = (getWorkInProgressRoot(): any);
45
- const cacheFromRootCachePool = root.pooledCache;
46
-
47
- return cacheFromRootCachePool;
48
-}
49
-
50
-export function requestCacheFromPool(renderLanes: Lanes): Cache {
51
- // Similar to previous function, except if there's not already a cache in the
52
- // pool, we allocate a new one.
53
- const cacheFromPool = peekCacheFromPool();
54
- if (cacheFromPool !== null) {
55
- return cacheFromPool;
56
- }
57
-
58
- // Create a fresh cache and add it to the root cache pool. A cache can have
59
- // multiple owners:
60
- // - A cache pool that lives on the FiberRoot. This is where all fresh caches
61
- // are originally created (TODO: except during refreshes, until we implement
62
- // this correctly). The root takes ownership immediately when the cache is
63
- // created. Conceptually, root.pooledCache is an Option<Arc<Cache>> (owned),
64
- // and the return value of this function is a &Arc<Cache> (borrowed).
65
- // - One of several fiber types: host root, cache boundary, suspense
66
- // component. These retain and release in the commit phase.
67
-
68
- const root = (getWorkInProgressRoot(): any);
69
- const freshCache = createCache();
70
- root.pooledCache = freshCache;
71
- retainCache(freshCache);
72
- if (freshCache !== null) {
73
- root.pooledCacheLanes |= renderLanes;
74
- }
75
- return freshCache;
76
-}
77
-
78
-export function pushRootTransitionPool(root: FiberRoot) {
79
- if (enableCache) {
80
- return;
81
- }
82
- // Note: This function currently does nothing but I'll leave it here for
83
- // code organization purposes in case that changes.
84
-}
85
-
86
-export function popRootTransitionPool(root: FiberRoot, renderLanes: Lanes) {
87
- if (enableCache) {
88
- return;
89
- }
90
- // Note: This function currently does nothing but I'll leave it here for
91
- // code organization purposes in case that changes.
92
-}
93
-
94
-export function pushTransitionPool(
95
- offscreenWorkInProgress: Fiber,
96
- prevCachePool: SpawnedCachePool | null,
97
-): void {
98
- if (enableCache) {
99
- if (prevCachePool === null) {
100
- push(resumedCache, resumedCache.current, offscreenWorkInProgress);
101
- } else {
102
- push(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
103
- }
104
- }
105
-}
106
-
107
-export function popTransitionPool(workInProgress: Fiber) {
108
- if (enableCache) {
109
- pop(resumedCache, workInProgress);
110
- }
111
-}
112
-
113
-export function getSuspendedCachePool(): SpawnedCachePool | null {
114
- if (!enableCache) {
115
- return null;
116
- }
117
- // This function is called when a Suspense boundary suspends. It returns the
118
- // cache that would have been used to render fresh data during this render,
119
- // if there was any, so that we can resume rendering with the same cache when
120
- // we receive more data.
121
- const cacheFromPool = peekCacheFromPool();
122
- if (cacheFromPool === null) {
123
- return null;
124
- }
125
-
126
- return {
127
- // We must also save the parent, so that when we resume we can detect
128
- // a refresh.
129
- parent: isPrimaryRenderer
130
- ? CacheContext._currentValue
131
- : CacheContext._currentValue2,
132
- pool: cacheFromPool,
133
- };
134
-}
135
-
136
-export function getOffscreenDeferredCachePool(): SpawnedCachePool | null {
137
- if (!enableCache) {
138
- return null;
139
- }
140
-
141
- const cacheFromPool = peekCacheFromPool();
142
- if (cacheFromPool === null) {
143
- return null;
144
- }
145
-
146
- return {
147
- // We must also store the parent, so that when we resume we can detect
148
- // a refresh.
149
- parent: isPrimaryRenderer
150
- ? CacheContext._currentValue
151
- : CacheContext._currentValue2,
152
- pool: cacheFromPool,
153
- };
154
-}
packages/react-reconciler/src/ReactFiberTreeContext.new.js
deleted
-289
@@ -1,289 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-// Ids are base 32 strings whose binary representation corresponds to the
11
-// position of a node in a tree.
12
-
13
-// Every time the tree forks into multiple children, we add additional bits to
14
-// the left of the sequence that represent the position of the child within the
15
-// current level of children.
16
-//
17
-// 00101 00010001011010101
18
-// ╰─┬─╯ ╰───────┬───────╯
19
-// Fork 5 of 20 Parent id
20
-//
21
-// The leading 0s are important. In the above example, you only need 3 bits to
22
-// represent slot 5. However, you need 5 bits to represent all the forks at
23
-// the current level, so we must account for the empty bits at the end.
24
-//
25
-// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
26
-// the zeroth id at a level would be indistinguishable from its parent.
27
-//
28
-// If a node has only one child, and does not materialize an id (i.e. does not
29
-// contain a useId hook), then we don't need to allocate any space in the
30
-// sequence. It's treated as a transparent indirection. For example, these two
31
-// trees produce the same ids:
32
-//
33
-// <> <>
34
-// <Indirection> <A />
35
-// <A /> <B />
36
-// </Indirection> </>
37
-// <B />
38
-// </>
39
-//
40
-// However, we cannot skip any node that materializes an id. Otherwise, a parent
41
-// id that does not fork would be indistinguishable from its child id. For
42
-// example, this tree does not fork, but the parent and child must have
43
-// different ids.
44
-//
45
-// <Parent>
46
-// <Child />
47
-// </Parent>
48
-//
49
-// To handle this scenario, every time we materialize an id, we allocate a
50
-// new level with a single slot. You can think of this as a fork with only one
51
-// prong, or an array of children with length 1.
52
-//
53
-// It's possible for the size of the sequence to exceed 32 bits, the max
54
-// size for bitwise operations. When this happens, we make more room by
55
-// converting the right part of the id to a string and storing it in an overflow
56
-// variable. We use a base 32 string representation, because 32 is the largest
57
-// power of 2 that is supported by toString(). We want the base to be large so
58
-// that the resulting ids are compact, and we want the base to be a power of 2
59
-// because every log2(base) bits corresponds to a single character, i.e. every
60
-// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
61
-// affecting the final result.
62
-
63
-import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
64
-
65
-import {getIsHydrating} from './ReactFiberHydrationContext.new';
66
-import {clz32} from './clz32';
67
-import {Forked, NoFlags} from './ReactFiberFlags';
68
-
69
-export type TreeContext = {
70
- id: number,
71
- overflow: string,
72
-};
73
-
74
-// TODO: Use the unified fiber stack module instead of this local one?
75
-// Intentionally not using it yet to derisk the initial implementation, because
76
-// the way we push/pop these values is a bit unusual. If there's a mistake, I'd
77
-// rather the ids be wrong than crash the whole reconciler.
78
-const forkStack: Array<any> = [];
79
-let forkStackIndex: number = 0;
80
-let treeForkProvider: Fiber | null = null;
81
-let treeForkCount: number = 0;
82
-
83
-const idStack: Array<any> = [];
84
-let idStackIndex: number = 0;
85
-let treeContextProvider: Fiber | null = null;
86
-let treeContextId: number = 1;
87
-let treeContextOverflow: string = '';
88
-
89
-export function isForkedChild(workInProgress: Fiber): boolean {
90
- warnIfNotHydrating();
91
- return (workInProgress.flags & Forked) !== NoFlags;
92
-}
93
-
94
-export function getForksAtLevel(workInProgress: Fiber): number {
95
- warnIfNotHydrating();
96
- return treeForkCount;
97
-}
98
-
99
-export function getTreeId(): string {
100
- const overflow = treeContextOverflow;
101
- const idWithLeadingBit = treeContextId;
102
- const id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
103
- return id.toString(32) + overflow;
104
-}
105
-
106
-export function pushTreeFork(
107
- workInProgress: Fiber,
108
- totalChildren: number,
109
-): void {
110
- // This is called right after we reconcile an array (or iterator) of child
111
- // fibers, because that's the only place where we know how many children in
112
- // the whole set without doing extra work later, or storing addtional
113
- // information on the fiber.
114
- //
115
- // That's why this function is separate from pushTreeId — it's called during
116
- // the render phase of the fork parent, not the child, which is where we push
117
- // the other context values.
118
- //
119
- // In the Fizz implementation this is much simpler because the child is
120
- // rendered in the same callstack as the parent.
121
- //
122
- // It might be better to just add a `forks` field to the Fiber type. It would
123
- // make this module simpler.
124
-
125
- warnIfNotHydrating();
126
-
127
- forkStack[forkStackIndex++] = treeForkCount;
128
- forkStack[forkStackIndex++] = treeForkProvider;
129
-
130
- treeForkProvider = workInProgress;
131
- treeForkCount = totalChildren;
132
-}
133
-
134
-export function pushTreeId(
135
- workInProgress: Fiber,
136
- totalChildren: number,
137
- index: number,
138
-) {
139
- warnIfNotHydrating();
140
-
141
- idStack[idStackIndex++] = treeContextId;
142
- idStack[idStackIndex++] = treeContextOverflow;
143
- idStack[idStackIndex++] = treeContextProvider;
144
-
145
- treeContextProvider = workInProgress;
146
-
147
- const baseIdWithLeadingBit = treeContextId;
148
- const baseOverflow = treeContextOverflow;
149
-
150
- // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
151
- // of the id; we use it to account for leading 0s.
152
- const baseLength = getBitLength(baseIdWithLeadingBit) - 1;
153
- const baseId = baseIdWithLeadingBit & ~(1 << baseLength);
154
-
155
- const slot = index + 1;
156
- const length = getBitLength(totalChildren) + baseLength;
157
-
158
- // 30 is the max length we can store without overflowing, taking into
159
- // consideration the leading 1 we use to mark the end of the sequence.
160
- if (length > 30) {
161
- // We overflowed the bitwise-safe range. Fall back to slower algorithm.
162
- // This branch assumes the length of the base id is greater than 5; it won't
163
- // work for smaller ids, because you need 5 bits per character.
164
- //
165
- // We encode the id in multiple steps: first the base id, then the
166
- // remaining digits.
167
- //
168
- // Each 5 bit sequence corresponds to a single base 32 character. So for
169
- // example, if the current id is 23 bits long, we can convert 20 of those
170
- // bits into a string of 4 characters, with 3 bits left over.
171
- //
172
- // First calculate how many bits in the base id represent a complete
173
- // sequence of characters.
174
- const numberOfOverflowBits = baseLength - (baseLength % 5);
175
-
176
- // Then create a bitmask that selects only those bits.
177
- const newOverflowBits = (1 << numberOfOverflowBits) - 1;
178
-
179
- // Select the bits, and convert them to a base 32 string.
180
- const newOverflow = (baseId & newOverflowBits).toString(32);
181
-
182
- // Now we can remove those bits from the base id.
183
- const restOfBaseId = baseId >> numberOfOverflowBits;
184
- const restOfBaseLength = baseLength - numberOfOverflowBits;
185
-
186
- // Finally, encode the rest of the bits using the normal algorithm. Because
187
- // we made more room, this time it won't overflow.
188
- const restOfLength = getBitLength(totalChildren) + restOfBaseLength;
189
- const restOfNewBits = slot << restOfBaseLength;
190
- const id = restOfNewBits | restOfBaseId;
191
- const overflow = newOverflow + baseOverflow;
192
-
193
- treeContextId = (1 << restOfLength) | id;
194
- treeContextOverflow = overflow;
195
- } else {
196
- // Normal path
197
- const newBits = slot << baseLength;
198
- const id = newBits | baseId;
199
- const overflow = baseOverflow;
200
-
201
- treeContextId = (1 << length) | id;
202
- treeContextOverflow = overflow;
203
- }
204
-}
205
-
206
-export function pushMaterializedTreeId(workInProgress: Fiber) {
207
- warnIfNotHydrating();
208
-
209
- // This component materialized an id. This will affect any ids that appear
210
- // in its children.
211
- const returnFiber = workInProgress.return;
212
- if (returnFiber !== null) {
213
- const numberOfForks = 1;
214
- const slotIndex = 0;
215
- pushTreeFork(workInProgress, numberOfForks);
216
- pushTreeId(workInProgress, numberOfForks, slotIndex);
217
- }
218
-}
219
-
220
-function getBitLength(number: number): number {
221
- return 32 - clz32(number);
222
-}
223
-
224
-function getLeadingBit(id: number) {
225
- return 1 << (getBitLength(id) - 1);
226
-}
227
-
228
-export function popTreeContext(workInProgress: Fiber) {
229
- // Restore the previous values.
230
-
231
- // This is a bit more complicated than other context-like modules in Fiber
232
- // because the same Fiber may appear on the stack multiple times and for
233
- // different reasons. We have to keep popping until the work-in-progress is
234
- // no longer at the top of the stack.
235
-
236
- while (workInProgress === treeForkProvider) {
237
- treeForkProvider = forkStack[--forkStackIndex];
238
- forkStack[forkStackIndex] = null;
239
- treeForkCount = forkStack[--forkStackIndex];
240
- forkStack[forkStackIndex] = null;
241
- }
242
-
243
- while (workInProgress === treeContextProvider) {
244
- treeContextProvider = idStack[--idStackIndex];
245
- idStack[idStackIndex] = null;
246
- treeContextOverflow = idStack[--idStackIndex];
247
- idStack[idStackIndex] = null;
248
- treeContextId = idStack[--idStackIndex];
249
- idStack[idStackIndex] = null;
250
- }
251
-}
252
-
253
-export function getSuspendedTreeContext(): TreeContext | null {
254
- warnIfNotHydrating();
255
- if (treeContextProvider !== null) {
256
- return {
257
- id: treeContextId,
258
- overflow: treeContextOverflow,
259
- };
260
- } else {
261
- return null;
262
- }
263
-}
264
-
265
-export function restoreSuspendedTreeContext(
266
- workInProgress: Fiber,
267
- suspendedContext: TreeContext,
268
-) {
269
- warnIfNotHydrating();
270
-
271
- idStack[idStackIndex++] = treeContextId;
272
- idStack[idStackIndex++] = treeContextOverflow;
273
- idStack[idStackIndex++] = treeContextProvider;
274
-
275
- treeContextId = suspendedContext.id;
276
- treeContextOverflow = suspendedContext.overflow;
277
- treeContextProvider = workInProgress;
278
-}
279
-
280
-function warnIfNotHydrating() {
281
- if (__DEV__) {
282
- if (!getIsHydrating()) {
283
- console.error(
284
- 'Expected to be hydrating. This is a bug in React. Please file ' +
285
- 'an issue.',
286
- );
287
- }
288
- }
289
-}
packages/react-reconciler/src/ReactFiberUnwindWork.new.js
deleted
-285
@@ -1,285 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {ReactContext} from 'shared/ReactTypes';
11
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
12
-import type {Lanes} from './ReactFiberLane.new';
13
-import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
14
-import type {Cache} from './ReactFiberCacheComponent.new';
15
-import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new';
16
-
17
-import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.new';
18
-import {
19
- ClassComponent,
20
- HostRoot,
21
- HostComponent,
22
- HostResource,
23
- HostSingleton,
24
- HostPortal,
25
- ContextProvider,
26
- SuspenseComponent,
27
- SuspenseListComponent,
28
- OffscreenComponent,
29
- LegacyHiddenComponent,
30
- CacheComponent,
31
- TracingMarkerComponent,
32
-} from './ReactWorkTags';
33
-import {DidCapture, NoFlags, ShouldCapture} from './ReactFiberFlags';
34
-import {NoMode, ProfileMode} from './ReactTypeOfMode';
35
-import {
36
- enableProfilerTimer,
37
- enableCache,
38
- enableTransitionTracing,
39
-} from 'shared/ReactFeatureFlags';
40
-
41
-import {popHostContainer, popHostContext} from './ReactFiberHostContext.new';
42
-import {
43
- popSuspenseListContext,
44
- popSuspenseHandler,
45
-} from './ReactFiberSuspenseContext.new';
46
-import {popHiddenContext} from './ReactFiberHiddenContext.new';
47
-import {resetHydrationState} from './ReactFiberHydrationContext.new';
48
-import {
49
- isContextProvider as isLegacyContextProvider,
50
- popContext as popLegacyContext,
51
- popTopLevelContextObject as popTopLevelLegacyContextObject,
52
-} from './ReactFiberContext.new';
53
-import {popProvider} from './ReactFiberNewContext.new';
54
-import {popCacheProvider} from './ReactFiberCacheComponent.new';
55
-import {transferActualDuration} from './ReactProfilerTimer.new';
56
-import {popTreeContext} from './ReactFiberTreeContext.new';
57
-import {popRootTransition, popTransition} from './ReactFiberTransition.new';
58
-import {
59
- popMarkerInstance,
60
- popRootMarkerInstance,
61
-} from './ReactFiberTracingMarkerComponent.new';
62
-
63
-function unwindWork(
64
- current: Fiber | null,
65
- workInProgress: Fiber,
66
- renderLanes: Lanes,
67
-): Fiber | null {
68
- // Note: This intentionally doesn't check if we're hydrating because comparing
69
- // to the current tree provider fiber is just as fast and less error-prone.
70
- // Ideally we would have a special version of the work loop only
71
- // for hydration.
72
- popTreeContext(workInProgress);
73
- switch (workInProgress.tag) {
74
- case ClassComponent: {
75
- const Component = workInProgress.type;
76
- if (isLegacyContextProvider(Component)) {
77
- popLegacyContext(workInProgress);
78
- }
79
- const flags = workInProgress.flags;
80
- if (flags & ShouldCapture) {
81
- workInProgress.flags = (flags & ~ShouldCapture) | DidCapture;
82
- if (
83
- enableProfilerTimer &&
84
- (workInProgress.mode & ProfileMode) !== NoMode
85
- ) {
86
- transferActualDuration(workInProgress);
87
- }
88
- return workInProgress;
89
- }
90
- return null;
91
- }
92
- case HostRoot: {
93
- const root: FiberRoot = workInProgress.stateNode;
94
- if (enableCache) {
95
- const cache: Cache = workInProgress.memoizedState.cache;
96
- popCacheProvider(workInProgress, cache);
97
- }
98
-
99
- if (enableTransitionTracing) {
100
- popRootMarkerInstance(workInProgress);
101
- }
102
-
103
- popRootTransition(workInProgress, root, renderLanes);
104
- popHostContainer(workInProgress);
105
- popTopLevelLegacyContextObject(workInProgress);
106
- resetMutableSourceWorkInProgressVersions();
107
- const flags = workInProgress.flags;
108
- if (
109
- (flags & ShouldCapture) !== NoFlags &&
110
- (flags & DidCapture) === NoFlags
111
- ) {
112
- // There was an error during render that wasn't captured by a suspense
113
- // boundary. Do a second pass on the root to unmount the children.
114
- workInProgress.flags = (flags & ~ShouldCapture) | DidCapture;
115
- return workInProgress;
116
- }
117
- // We unwound to the root without completing it. Exit.
118
- return null;
119
- }
120
- case HostResource:
121
- case HostSingleton:
122
- case HostComponent: {
123
- // TODO: popHydrationState
124
- popHostContext(workInProgress);
125
- return null;
126
- }
127
- case SuspenseComponent: {
128
- popSuspenseHandler(workInProgress);
129
- const suspenseState: null | SuspenseState = workInProgress.memoizedState;
130
- if (suspenseState !== null && suspenseState.dehydrated !== null) {
131
- if (workInProgress.alternate === null) {
132
- throw new Error(
133
- 'Threw in newly mounted dehydrated component. This is likely a bug in ' +
134
- 'React. Please file an issue.',
135
- );
136
- }
137
-
138
- resetHydrationState();
139
- }
140
-
141
- const flags = workInProgress.flags;
142
- if (flags & ShouldCapture) {
143
- workInProgress.flags = (flags & ~ShouldCapture) | DidCapture;
144
- // Captured a suspense effect. Re-render the boundary.
145
- if (
146
- enableProfilerTimer &&
147
- (workInProgress.mode & ProfileMode) !== NoMode
148
- ) {
149
- transferActualDuration(workInProgress);
150
- }
151
- return workInProgress;
152
- }
153
- return null;
154
- }
155
- case SuspenseListComponent: {
156
- popSuspenseListContext(workInProgress);
157
- // SuspenseList doesn't actually catch anything. It should've been
158
- // caught by a nested boundary. If not, it should bubble through.
159
- return null;
160
- }
161
- case HostPortal:
162
- popHostContainer(workInProgress);
163
- return null;
164
- case ContextProvider:
165
- const context: ReactContext<any> = workInProgress.type._context;
166
- popProvider(context, workInProgress);
167
- return null;
168
- case OffscreenComponent:
169
- case LegacyHiddenComponent: {
170
- popSuspenseHandler(workInProgress);
171
- popHiddenContext(workInProgress);
172
- popTransition(workInProgress, current);
173
- const flags = workInProgress.flags;
174
- if (flags & ShouldCapture) {
175
- workInProgress.flags = (flags & ~ShouldCapture) | DidCapture;
176
- // Captured a suspense effect. Re-render the boundary.
177
- if (
178
- enableProfilerTimer &&
179
- (workInProgress.mode & ProfileMode) !== NoMode
180
- ) {
181
- transferActualDuration(workInProgress);
182
- }
183
- return workInProgress;
184
- }
185
- return null;
186
- }
187
- case CacheComponent:
188
- if (enableCache) {
189
- const cache: Cache = workInProgress.memoizedState.cache;
190
- popCacheProvider(workInProgress, cache);
191
- }
192
- return null;
193
- case TracingMarkerComponent:
194
- if (enableTransitionTracing) {
195
- if (workInProgress.stateNode !== null) {
196
- popMarkerInstance(workInProgress);
197
- }
198
- }
199
- return null;
200
- default:
201
- return null;
202
- }
203
-}
204
-
205
-function unwindInterruptedWork(
206
- current: Fiber | null,
207
- interruptedWork: Fiber,
208
- renderLanes: Lanes,
209
-) {
210
- // Note: This intentionally doesn't check if we're hydrating because comparing
211
- // to the current tree provider fiber is just as fast and less error-prone.
212
- // Ideally we would have a special version of the work loop only
213
- // for hydration.
214
- popTreeContext(interruptedWork);
215
- switch (interruptedWork.tag) {
216
- case ClassComponent: {
217
- const childContextTypes = interruptedWork.type.childContextTypes;
218
- if (childContextTypes !== null && childContextTypes !== undefined) {
219
- popLegacyContext(interruptedWork);
220
- }
221
- break;
222
- }
223
- case HostRoot: {
224
- const root: FiberRoot = interruptedWork.stateNode;
225
- if (enableCache) {
226
- const cache: Cache = interruptedWork.memoizedState.cache;
227
- popCacheProvider(interruptedWork, cache);
228
- }
229
-
230
- if (enableTransitionTracing) {
231
- popRootMarkerInstance(interruptedWork);
232
- }
233
-
234
- popRootTransition(interruptedWork, root, renderLanes);
235
- popHostContainer(interruptedWork);
236
- popTopLevelLegacyContextObject(interruptedWork);
237
- resetMutableSourceWorkInProgressVersions();
238
- break;
239
- }
240
- case HostResource:
241
- case HostSingleton:
242
- case HostComponent: {
243
- popHostContext(interruptedWork);
244
- break;
245
- }
246
- case HostPortal:
247
- popHostContainer(interruptedWork);
248
- break;
249
- case SuspenseComponent:
250
- popSuspenseHandler(interruptedWork);
251
- break;
252
- case SuspenseListComponent:
253
- popSuspenseListContext(interruptedWork);
254
- break;
255
- case ContextProvider:
256
- const context: ReactContext<any> = interruptedWork.type._context;
257
- popProvider(context, interruptedWork);
258
- break;
259
- case OffscreenComponent:
260
- case LegacyHiddenComponent:
261
- popSuspenseHandler(interruptedWork);
262
- popHiddenContext(interruptedWork);
263
- popTransition(interruptedWork, current);
264
- break;
265
- case CacheComponent:
266
- if (enableCache) {
267
- const cache: Cache = interruptedWork.memoizedState.cache;
268
- popCacheProvider(interruptedWork, cache);
269
- }
270
- break;
271
- case TracingMarkerComponent:
272
- if (enableTransitionTracing) {
273
- const instance: TracingMarkerInstance | null =
274
- interruptedWork.stateNode;
275
- if (instance !== null) {
276
- popMarkerInstance(interruptedWork);
277
- }
278
- }
279
- break;
280
- default:
281
- break;
282
- }
283
-}
284
-
285
-export {unwindWork, unwindInterruptedWork};
packages/react-reconciler/src/ReactFiberWorkLoop.new.js
deleted
-4014
@@ -1,4014 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import {REACT_STRICT_MODE_TYPE} from 'shared/ReactSymbols';
11
-
12
-import type {Wakeable, Thenable} from 'shared/ReactTypes';
13
-import type {Fiber, FiberRoot} from './ReactInternalTypes';
14
-import type {Lanes, Lane} from './ReactFiberLane.new';
15
-import type {
16
- SuspenseProps,
17
- SuspenseState,
18
-} from './ReactFiberSuspenseComponent.new';
19
-import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new';
20
-import type {EventPriority} from './ReactEventPriorities.new';
21
-import type {
22
- PendingTransitionCallbacks,
23
- PendingBoundaries,
24
- Transition,
25
- TransitionAbort,
26
-} from './ReactFiberTracingMarkerComponent.new';
27
-import type {OffscreenInstance} from './ReactFiberOffscreenComponent';
28
-
29
-import {
30
- warnAboutDeprecatedLifecycles,
31
- replayFailedUnitOfWorkWithInvokeGuardedCallback,
32
- enableCreateEventHandleAPI,
33
- enableProfilerTimer,
34
- enableProfilerCommitHooks,
35
- enableProfilerNestedUpdatePhase,
36
- enableProfilerNestedUpdateScheduledHook,
37
- deferRenderPhaseUpdateToNextBatch,
38
- enableDebugTracing,
39
- enableSchedulingProfiler,
40
- disableSchedulerTimeoutInWorkLoop,
41
- skipUnmountedBoundaries,
42
- enableUpdaterTracking,
43
- enableCache,
44
- enableTransitionTracing,
45
- useModernStrictMode,
46
-} from 'shared/ReactFeatureFlags';
47
-import ReactSharedInternals from 'shared/ReactSharedInternals';
48
-import is from 'shared/objectIs';
49
-
50
-import {
51
- // Aliased because `act` will override and push to an internal queue
52
- scheduleCallback as Scheduler_scheduleCallback,
53
- cancelCallback as Scheduler_cancelCallback,
54
- shouldYield,
55
- requestPaint,
56
- now,
57
- ImmediatePriority as ImmediateSchedulerPriority,
58
- UserBlockingPriority as UserBlockingSchedulerPriority,
59
- NormalPriority as NormalSchedulerPriority,
60
- IdlePriority as IdleSchedulerPriority,
61
-} from './Scheduler';
62
-import {
63
- flushSyncCallbacks,
64
- flushSyncCallbacksOnlyInLegacyMode,
65
- scheduleSyncCallback,
66
- scheduleLegacySyncCallback,
67
-} from './ReactFiberSyncTaskQueue.new';
68
-import {
69
- logCommitStarted,
70
- logCommitStopped,
71
- logLayoutEffectsStarted,
72
- logLayoutEffectsStopped,
73
- logPassiveEffectsStarted,
74
- logPassiveEffectsStopped,
75
- logRenderStarted,
76
- logRenderStopped,
77
-} from './DebugTracing';
78
-
79
-import {
80
- resetAfterCommit,
81
- scheduleTimeout,
82
- cancelTimeout,
83
- noTimeout,
84
- afterActiveInstanceBlur,
85
- getCurrentEventPriority,
86
- supportsMicrotasks,
87
- errorHydratingContainer,
88
- scheduleMicrotask,
89
- prepareRendererToRender,
90
- resetRendererAfterRender,
91
-} from './ReactFiberHostConfig';
92
-
93
-import {
94
- createWorkInProgress,
95
- assignFiberPropertiesInDEV,
96
- resetWorkInProgress,
97
-} from './ReactFiber.new';
98
-import {isRootDehydrated} from './ReactFiberShellHydration';
99
-import {didSuspendOrErrorWhileHydratingDEV} from './ReactFiberHydrationContext.new';
100
-import {
101
- NoMode,
102
- ProfileMode,
103
- ConcurrentMode,
104
- StrictLegacyMode,
105
- StrictEffectsMode,
106
-} from './ReactTypeOfMode';
107
-import {
108
- HostRoot,
109
- IndeterminateComponent,
110
- ClassComponent,
111
- SuspenseComponent,
112
- SuspenseListComponent,
113
- OffscreenComponent,
114
- FunctionComponent,
115
- ForwardRef,
116
- MemoComponent,
117
- SimpleMemoComponent,
118
- Profiler,
119
-} from './ReactWorkTags';
120
-import {ConcurrentRoot, LegacyRoot} from './ReactRootTags';
121
-import type {Flags} from './ReactFiberFlags';
122
-import {
123
- NoFlags,
124
- Incomplete,
125
- StoreConsistency,
126
- HostEffectMask,
127
- ForceClientRender,
128
- BeforeMutationMask,
129
- MutationMask,
130
- LayoutMask,
131
- PassiveMask,
132
- PlacementDEV,
133
- Visibility,
134
- MountPassiveDev,
135
- MountLayoutDev,
136
-} from './ReactFiberFlags';
137
-import {
138
- NoLanes,
139
- NoLane,
140
- SyncLane,
141
- NoTimestamp,
142
- claimNextTransitionLane,
143
- claimNextRetryLane,
144
- includesSyncLane,
145
- isSubsetOfLanes,
146
- mergeLanes,
147
- removeLanes,
148
- pickArbitraryLane,
149
- includesNonIdleWork,
150
- includesOnlyRetries,
151
- includesOnlyTransitions,
152
- includesBlockingLane,
153
- includesExpiredLane,
154
- getNextLanes,
155
- markStarvedLanesAsExpired,
156
- getLanesToRetrySynchronouslyOnError,
157
- getMostRecentEventTime,
158
- markRootUpdated,
159
- markRootSuspended as markRootSuspended_dontCallThisOneDirectly,
160
- markRootPinged,
161
- markRootEntangled,
162
- markRootFinished,
163
- getHighestPriorityLane,
164
- addFiberToLanesMap,
165
- movePendingFibersToMemoized,
166
- addTransitionToLanesMap,
167
- getTransitionsForLanes,
168
-} from './ReactFiberLane.new';
169
-import {
170
- DiscreteEventPriority,
171
- ContinuousEventPriority,
172
- DefaultEventPriority,
173
- IdleEventPriority,
174
- getCurrentUpdatePriority,
175
- setCurrentUpdatePriority,
176
- lowerEventPriority,
177
- lanesToEventPriority,
178
-} from './ReactEventPriorities.new';
179
-import {requestCurrentTransition, NoTransition} from './ReactFiberTransition';
180
-import {
181
- SelectiveHydrationException,
182
- beginWork as originalBeginWork,
183
- replayFunctionComponent,
184
-} from './ReactFiberBeginWork.new';
185
-import {completeWork} from './ReactFiberCompleteWork.new';
186
-import {unwindWork, unwindInterruptedWork} from './ReactFiberUnwindWork.new';
187
-import {
188
- throwException,
189
- createRootErrorUpdate,
190
- createClassErrorUpdate,
191
-} from './ReactFiberThrow.new';
192
-import {
193
- commitBeforeMutationEffects,
194
- commitLayoutEffects,
195
- commitMutationEffects,
196
- commitPassiveEffectDurations,
197
- commitPassiveMountEffects,
198
- commitPassiveUnmountEffects,
199
- disappearLayoutEffects,
200
- reconnectPassiveEffects,
201
- reappearLayoutEffects,
202
- disconnectPassiveEffect,
203
- reportUncaughtErrorInDEV,
204
- invokeLayoutEffectMountInDEV,
205
- invokePassiveEffectMountInDEV,
206
- invokeLayoutEffectUnmountInDEV,
207
- invokePassiveEffectUnmountInDEV,
208
-} from './ReactFiberCommitWork.new';
209
-import {enqueueUpdate} from './ReactFiberClassUpdateQueue.new';
210
-import {resetContextDependencies} from './ReactFiberNewContext.new';
211
-import {
212
- resetHooksAfterThrow,
213
- resetHooksOnUnwind,
214
- ContextOnlyDispatcher,
215
-} from './ReactFiberHooks.new';
216
-import {DefaultCacheDispatcher} from './ReactFiberCache.new';
217
-import {
218
- createCapturedValueAtFiber,
219
- type CapturedValue,
220
-} from './ReactCapturedValue';
221
-import {
222
- enqueueConcurrentRenderForLane,
223
- finishQueueingConcurrentUpdates,
224
- getConcurrentlyUpdatedLanes,
225
-} from './ReactFiberConcurrentUpdates.new';
226
-
227
-import {
228
- markNestedUpdateScheduled,
229
- recordCommitTime,
230
- resetNestedUpdateFlag,
231
- startProfilerTimer,
232
- stopProfilerTimerIfRunningAndRecordDelta,
233
- syncNestedUpdateFlag,
234
-} from './ReactProfilerTimer.new';
235
-
236
-// DEV stuff
237
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
238
-import ReactStrictModeWarnings from './ReactStrictModeWarnings.new';
239
-import {
240
- isRendering as ReactCurrentDebugFiberIsRenderingInDEV,
241
- current as ReactCurrentFiberCurrent,
242
- resetCurrentFiber as resetCurrentDebugFiberInDEV,
243
- setCurrentFiber as setCurrentDebugFiberInDEV,
244
-} from './ReactCurrentFiber';
245
-import {
246
- invokeGuardedCallback,
247
- hasCaughtError,
248
- clearCaughtError,
249
-} from 'shared/ReactErrorUtils';
250
-import {
251
- isDevToolsPresent,
252
- markCommitStarted,
253
- markCommitStopped,
254
- markComponentRenderStopped,
255
- markComponentSuspended,
256
- markComponentErrored,
257
- markLayoutEffectsStarted,
258
- markLayoutEffectsStopped,
259
- markPassiveEffectsStarted,
260
- markPassiveEffectsStopped,
261
- markRenderStarted,
262
- markRenderYielded,
263
- markRenderStopped,
264
- onCommitRoot as onCommitRootDevTools,
265
- onPostCommitRoot as onPostCommitRootDevTools,
266
-} from './ReactFiberDevToolsHook.new';
267
-import {onCommitRoot as onCommitRootTestSelector} from './ReactTestSelectors';
268
-import {releaseCache} from './ReactFiberCacheComponent.new';
269
-import {
270
- isLegacyActEnvironment,
271
- isConcurrentActEnvironment,
272
-} from './ReactFiberAct.new';
273
-import {processTransitionCallbacks} from './ReactFiberTracingMarkerComponent.new';
274
-import {
275
- SuspenseException,
276
- getSuspendedThenable,
277
- isThenableResolved,
278
-} from './ReactFiberThenable.new';
279
-import {schedulePostPaintCallback} from './ReactPostPaintCallback';
280
-import {
281
- getSuspenseHandler,
282
- isBadSuspenseFallback,
283
-} from './ReactFiberSuspenseContext.new';
284
-import {resolveDefaultProps} from './ReactFiberLazyComponent.new';
285
-
286
-const ceil = Math.ceil;
287
-
288
-const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
289
-
290
-const {
291
- ReactCurrentDispatcher,
292
- ReactCurrentCache,
293
- ReactCurrentOwner,
294
- ReactCurrentBatchConfig,
295
- ReactCurrentActQueue,
296
-} = ReactSharedInternals;
297
-
298
-type ExecutionContext = number;
299
-
300
-export const NoContext = /* */ 0b000;
301
-const BatchedContext = /* */ 0b001;
302
-export const RenderContext = /* */ 0b010;
303
-export const CommitContext = /* */ 0b100;
304
-
305
-type RootExitStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6;
306
-const RootInProgress = 0;
307
-const RootFatalErrored = 1;
308
-const RootErrored = 2;
309
-const RootSuspended = 3;
310
-const RootSuspendedWithDelay = 4;
311
-const RootCompleted = 5;
312
-const RootDidNotComplete = 6;
313
-
314
-// Describes where we are in the React execution stack
315
-let executionContext: ExecutionContext = NoContext;
316
-// The root we're working on
317
-let workInProgressRoot: FiberRoot | null = null;
318
-// The fiber we're working on
319
-let workInProgress: Fiber | null = null;
320
-// The lanes we're rendering
321
-let workInProgressRootRenderLanes: Lanes = NoLanes;
322
-
323
-opaque type SuspendedReason = 0 | 1 | 2 | 3 | 4 | 5 | 6;
324
-const NotSuspended: SuspendedReason = 0;
325
-const SuspendedOnError: SuspendedReason = 1;
326
-const SuspendedOnData: SuspendedReason = 2;
327
-const SuspendedOnImmediate: SuspendedReason = 3;
328
-const SuspendedOnDeprecatedThrowPromise: SuspendedReason = 4;
329
-const SuspendedAndReadyToUnwind: SuspendedReason = 5;
330
-const SuspendedOnHydration: SuspendedReason = 6;
331
-
332
-// When this is true, the work-in-progress fiber just suspended (or errored) and
333
-// we've yet to unwind the stack. In some cases, we may yield to the main thread
334
-// after this happens. If the fiber is pinged before we resume, we can retry
335
-// immediately instead of unwinding the stack.
336
-let workInProgressSuspendedReason: SuspendedReason = NotSuspended;
337
-let workInProgressThrownValue: mixed = null;
338
-
339
-// Whether a ping listener was attached during this render. This is slightly
340
-// different that whether something suspended, because we don't add multiple
341
-// listeners to a promise we've already seen (per root and lane).
342
-let workInProgressRootDidAttachPingListener: boolean = false;
343
-
344
-// A contextual version of workInProgressRootRenderLanes. It is a superset of
345
-// the lanes that we started working on at the root. When we enter a subtree
346
-// that is currently hidden, we add the lanes that would have committed if
347
-// the hidden tree hadn't been deferred. This is modified by the
348
-// HiddenContext module.
349
-//
350
-// Most things in the work loop should deal with workInProgressRootRenderLanes.
351
-// Most things in begin/complete phases should deal with renderLanes.
352
-export let renderLanes: Lanes = NoLanes;
353
-
354
-// Whether to root completed, errored, suspended, etc.
355
-let workInProgressRootExitStatus: RootExitStatus = RootInProgress;
356
-// A fatal error, if one is thrown
357
-let workInProgressRootFatalError: mixed = null;
358
-// The work left over by components that were visited during this render. Only
359
-// includes unprocessed updates, not work in bailed out children.
360
-let workInProgressRootSkippedLanes: Lanes = NoLanes;
361
-// Lanes that were updated (in an interleaved event) during this render.
362
-let workInProgressRootInterleavedUpdatedLanes: Lanes = NoLanes;
363
-// Lanes that were updated during the render phase (*not* an interleaved event).
364
-let workInProgressRootRenderPhaseUpdatedLanes: Lanes = NoLanes;
365
-// Lanes that were pinged (in an interleaved event) during this render.
366
-let workInProgressRootPingedLanes: Lanes = NoLanes;
367
-// Errors that are thrown during the render phase.
368
-let workInProgressRootConcurrentErrors: Array<
369
- CapturedValue<mixed>,
370
-> | null = null;
371
-// These are errors that we recovered from without surfacing them to the UI.
372
-// We will log them once the tree commits.
373
-let workInProgressRootRecoverableErrors: Array<
374
- CapturedValue<mixed>,
375
-> | null = null;
376
-
377
-// The most recent time we committed a fallback. This lets us ensure a train
378
-// model where we don't commit new loading states in too quick succession.
379
-let globalMostRecentFallbackTime: number = 0;
380
-const FALLBACK_THROTTLE_MS: number = 500;
381
-
382
-// The absolute time for when we should start giving up on rendering
383
-// more and prefer CPU suspense heuristics instead.
384
-let workInProgressRootRenderTargetTime: number = Infinity;
385
-// How long a render is supposed to take before we start following CPU
386
-// suspense heuristics and opt out of rendering more content.
387
-const RENDER_TIMEOUT_MS = 500;
388
-
389
-let workInProgressTransitions: Array<Transition> | null = null;
390
-export function getWorkInProgressTransitions(): null | Array<Transition> {
391
- return workInProgressTransitions;
392
-}
393
-
394
-let currentPendingTransitionCallbacks: PendingTransitionCallbacks | null = null;
395
-let currentEndTime: number | null = null;
396
-
397
-export function addTransitionStartCallbackToPendingTransition(
398
- transition: Transition,
399
-) {
400
- if (enableTransitionTracing) {
401
- if (currentPendingTransitionCallbacks === null) {
402
- currentPendingTransitionCallbacks = {
403
- transitionStart: [],
404
- transitionProgress: null,
405
- transitionComplete: null,
406
- markerProgress: null,
407
- markerIncomplete: null,
408
- markerComplete: null,
409
- };
410
- }
411
-
412
- if (currentPendingTransitionCallbacks.transitionStart === null) {
413
- currentPendingTransitionCallbacks.transitionStart = [];
414
- }
415
-
416
- currentPendingTransitionCallbacks.transitionStart.push(transition);
417
- }
418
-}
419
-
420
-export function addMarkerProgressCallbackToPendingTransition(
421
- markerName: string,
422
- transitions: Set<Transition>,
423
- pendingBoundaries: PendingBoundaries,
424
-) {
425
- if (enableTransitionTracing) {
426
- if (currentPendingTransitionCallbacks === null) {
427
- currentPendingTransitionCallbacks = ({
428
- transitionStart: null,
429
- transitionProgress: null,
430
- transitionComplete: null,
431
- markerProgress: new Map(),
432
- markerIncomplete: null,
433
- markerComplete: null,
434
- }: PendingTransitionCallbacks);
435
- }
436
-
437
- if (currentPendingTransitionCallbacks.markerProgress === null) {
438
- currentPendingTransitionCallbacks.markerProgress = new Map();
439
- }
440
-
441
- currentPendingTransitionCallbacks.markerProgress.set(markerName, {
442
- pendingBoundaries,
443
- transitions,
444
- });
445
- }
446
-}
447
-
448
-export function addMarkerIncompleteCallbackToPendingTransition(
449
- markerName: string,
450
- transitions: Set<Transition>,
451
- aborts: Array<TransitionAbort>,
452
-) {
453
- if (enableTransitionTracing) {
454
- if (currentPendingTransitionCallbacks === null) {
455
- currentPendingTransitionCallbacks = {
456
- transitionStart: null,
457
- transitionProgress: null,
458
- transitionComplete: null,
459
- markerProgress: null,
460
- markerIncomplete: new Map(),
461
- markerComplete: null,
462
- };
463
- }
464
-
465
- if (currentPendingTransitionCallbacks.markerIncomplete === null) {
466
- currentPendingTransitionCallbacks.markerIncomplete = new Map();
467
- }
468
-
469
- currentPendingTransitionCallbacks.markerIncomplete.set(markerName, {
470
- transitions,
471
- aborts,
472
- });
473
- }
474
-}
475
-
476
-export function addMarkerCompleteCallbackToPendingTransition(
477
- markerName: string,
478
- transitions: Set<Transition>,
479
-) {
480
- if (enableTransitionTracing) {
481
- if (currentPendingTransitionCallbacks === null) {
482
- currentPendingTransitionCallbacks = {
483
- transitionStart: null,
484
- transitionProgress: null,
485
- transitionComplete: null,
486
- markerProgress: null,
487
- markerIncomplete: null,
488
- markerComplete: new Map(),
489
- };
490
- }
491
-
492
- if (currentPendingTransitionCallbacks.markerComplete === null) {
493
- currentPendingTransitionCallbacks.markerComplete = new Map();
494
- }
495
-
496
- currentPendingTransitionCallbacks.markerComplete.set(
497
- markerName,
498
- transitions,
499
- );
500
- }
501
-}
502
-
503
-export function addTransitionProgressCallbackToPendingTransition(
504
- transition: Transition,
505
- boundaries: PendingBoundaries,
506
-) {
507
- if (enableTransitionTracing) {
508
- if (currentPendingTransitionCallbacks === null) {
509
- currentPendingTransitionCallbacks = {
510
- transitionStart: null,
511
- transitionProgress: new Map(),
512
- transitionComplete: null,
513
- markerProgress: null,
514
- markerIncomplete: null,
515
- markerComplete: null,
516
- };
517
- }
518
-
519
- if (currentPendingTransitionCallbacks.transitionProgress === null) {
520
- currentPendingTransitionCallbacks.transitionProgress = new Map();
521
- }
522
-
523
- currentPendingTransitionCallbacks.transitionProgress.set(
524
- transition,
525
- boundaries,
526
- );
527
- }
528
-}
529
-
530
-export function addTransitionCompleteCallbackToPendingTransition(
531
- transition: Transition,
532
-) {
533
- if (enableTransitionTracing) {
534
- if (currentPendingTransitionCallbacks === null) {
535
- currentPendingTransitionCallbacks = {
536
- transitionStart: null,
537
- transitionProgress: null,
538
- transitionComplete: [],
539
- markerProgress: null,
540
- markerIncomplete: null,
541
- markerComplete: null,
542
- };
543
- }
544
-
545
- if (currentPendingTransitionCallbacks.transitionComplete === null) {
546
- currentPendingTransitionCallbacks.transitionComplete = [];
547
- }
548
-
549
- currentPendingTransitionCallbacks.transitionComplete.push(transition);
550
- }
551
-}
552
-
553
-function resetRenderTimer() {
554
- workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
555
-}
556
-
557
-export function getRenderTargetTime(): number {
558
- return workInProgressRootRenderTargetTime;
559
-}
560
-
561
-let hasUncaughtError = false;
562
-let firstUncaughtError = null;
563
-let legacyErrorBoundariesThatAlreadyFailed: Set<mixed> | null = null;
564
-
565
-// Only used when enableProfilerNestedUpdateScheduledHook is true;
566
-// to track which root is currently committing layout effects.
567
-let rootCommittingMutationOrLayoutEffects: FiberRoot | null = null;
568
-
569
-let rootDoesHavePassiveEffects: boolean = false;
570
-let rootWithPendingPassiveEffects: FiberRoot | null = null;
571
-let pendingPassiveEffectsLanes: Lanes = NoLanes;
572
-let pendingPassiveProfilerEffects: Array<Fiber> = [];
573
-let pendingPassiveEffectsRemainingLanes: Lanes = NoLanes;
574
-let pendingPassiveTransitions: Array<Transition> | null = null;
575
-
576
-// Use these to prevent an infinite loop of nested updates
577
-const NESTED_UPDATE_LIMIT = 50;
578
-let nestedUpdateCount: number = 0;
579
-let rootWithNestedUpdates: FiberRoot | null = null;
580
-let isFlushingPassiveEffects = false;
581
-let didScheduleUpdateDuringPassiveEffects = false;
582
-
583
-const NESTED_PASSIVE_UPDATE_LIMIT = 50;
584
-let nestedPassiveUpdateCount: number = 0;
585
-let rootWithPassiveNestedUpdates: FiberRoot | null = null;
586
-
587
-// If two updates are scheduled within the same event, we should treat their
588
-// event times as simultaneous, even if the actual clock time has advanced
589
-// between the first and second call.
590
-let currentEventTime: number = NoTimestamp;
591
-let currentEventTransitionLane: Lanes = NoLanes;
592
-
593
-let isRunningInsertionEffect = false;
594
-
595
-export function getWorkInProgressRoot(): FiberRoot | null {
596
- return workInProgressRoot;
597
-}
598
-
599
-export function getWorkInProgressRootRenderLanes(): Lanes {
600
- return workInProgressRootRenderLanes;
601
-}
602
-
603
-export function requestEventTime(): number {
604
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
605
- // We're inside React, so it's fine to read the actual time.
606
- return now();
607
- }
608
- // We're not inside React, so we may be in the middle of a browser event.
609
- if (currentEventTime !== NoTimestamp) {
610
- // Use the same start time for all updates until we enter React again.
611
- return currentEventTime;
612
- }
613
- // This is the first update since React yielded. Compute a new start time.
614
- currentEventTime = now();
615
- return currentEventTime;
616
-}
617
-
618
-export function getCurrentTime(): number {
619
- return now();
620
-}
621
-
622
-export function requestUpdateLane(fiber: Fiber): Lane {
623
- // Special cases
624
- const mode = fiber.mode;
625
- if ((mode & ConcurrentMode) === NoMode) {
626
- return (SyncLane: Lane);
627
- } else if (
628
- !deferRenderPhaseUpdateToNextBatch &&
629
- (executionContext & RenderContext) !== NoContext &&
630
- workInProgressRootRenderLanes !== NoLanes
631
- ) {
632
- // This is a render phase update. These are not officially supported. The
633
- // old behavior is to give this the same "thread" (lanes) as
634
- // whatever is currently rendering. So if you call `setState` on a component
635
- // that happens later in the same render, it will flush. Ideally, we want to
636
- // remove the special case and treat them as if they came from an
637
- // interleaved event. Regardless, this pattern is not officially supported.
638
- // This behavior is only a fallback. The flag only exists until we can roll
639
- // out the setState warning, since existing code might accidentally rely on
640
- // the current behavior.
641
- return pickArbitraryLane(workInProgressRootRenderLanes);
642
- }
643
-
644
- const isTransition = requestCurrentTransition() !== NoTransition;
645
- if (isTransition) {
646
- if (__DEV__ && ReactCurrentBatchConfig.transition !== null) {
647
- const transition = ReactCurrentBatchConfig.transition;
648
- if (!transition._updatedFibers) {
649
- transition._updatedFibers = new Set();
650
- }
651
-
652
- transition._updatedFibers.add(fiber);
653
- }
654
- // The algorithm for assigning an update to a lane should be stable for all
655
- // updates at the same priority within the same event. To do this, the
656
- // inputs to the algorithm must be the same.
657
- //
658
- // The trick we use is to cache the first of each of these inputs within an
659
- // event. Then reset the cached values once we can be sure the event is
660
- // over. Our heuristic for that is whenever we enter a concurrent work loop.
661
- if (currentEventTransitionLane === NoLane) {
662
- // All transitions within the same event are assigned the same lane.
663
- currentEventTransitionLane = claimNextTransitionLane();
664
- }
665
- return currentEventTransitionLane;
666
- }
667
-
668
- // Updates originating inside certain React methods, like flushSync, have
669
- // their priority set by tracking it with a context variable.
670
- //
671
- // The opaque type returned by the host config is internally a lane, so we can
672
- // use that directly.
673
- // TODO: Move this type conversion to the event priority module.
674
- const updateLane: Lane = (getCurrentUpdatePriority(): any);
675
- if (updateLane !== NoLane) {
676
- return updateLane;
677
- }
678
-
679
- // This update originated outside React. Ask the host environment for an
680
- // appropriate priority, based on the type of event.
681
- //
682
- // The opaque type returned by the host config is internally a lane, so we can
683
- // use that directly.
684
- // TODO: Move this type conversion to the event priority module.
685
- const eventLane: Lane = (getCurrentEventPriority(): any);
686
- return eventLane;
687
-}
688
-
689
-function requestRetryLane(fiber: Fiber) {
690
- // This is a fork of `requestUpdateLane` designed specifically for Suspense
691
- // "retries" — a special update that attempts to flip a Suspense boundary
692
- // from its placeholder state to its primary/resolved state.
693
-
694
- // Special cases
695
- const mode = fiber.mode;
696
- if ((mode & ConcurrentMode) === NoMode) {
697
- return (SyncLane: Lane);
698
- }
699
-
700
- return claimNextRetryLane();
701
-}
702
-
703
-export function scheduleUpdateOnFiber(
704
- root: FiberRoot,
705
- fiber: Fiber,
706
- lane: Lane,
707
- eventTime: number,
708
-) {
709
- if (__DEV__) {
710
- if (isRunningInsertionEffect) {
711
- console.error('useInsertionEffect must not schedule updates.');
712
- }
713
- }
714
-
715
- if (__DEV__) {
716
- if (isFlushingPassiveEffects) {
717
- didScheduleUpdateDuringPassiveEffects = true;
718
- }
719
- }
720
-
721
- // Check if the work loop is currently suspended and waiting for data to
722
- // finish loading.
723
- if (
724
- workInProgressSuspendedReason === SuspendedOnData &&
725
- root === workInProgressRoot
726
- ) {
727
- // The incoming update might unblock the current render. Interrupt the
728
- // current attempt and restart from the top.
729
- prepareFreshStack(root, NoLanes);
730
- markRootSuspended(root, workInProgressRootRenderLanes);
731
- }
732
-
733
- // Mark that the root has a pending update.
734
- markRootUpdated(root, lane, eventTime);
735
-
736
- if (
737
- (executionContext & RenderContext) !== NoLanes &&
738
- root === workInProgressRoot
739
- ) {
740
- // This update was dispatched during the render phase. This is a mistake
741
- // if the update originates from user space (with the exception of local
742
- // hook updates, which are handled differently and don't reach this
743
- // function), but there are some internal React features that use this as
744
- // an implementation detail, like selective hydration.
745
- warnAboutRenderPhaseUpdatesInDEV(fiber);
746
-
747
- // Track lanes that were updated during the render phase
748
- workInProgressRootRenderPhaseUpdatedLanes = mergeLanes(
749
- workInProgressRootRenderPhaseUpdatedLanes,
750
- lane,
751
- );
752
- } else {
753
- // This is a normal update, scheduled from outside the render phase. For
754
- // example, during an input event.
755
- if (enableUpdaterTracking) {
756
- if (isDevToolsPresent) {
757
- addFiberToLanesMap(root, fiber, lane);
758
- }
759
- }
760
-
761
- warnIfUpdatesNotWrappedWithActDEV(fiber);
762
-
763
- if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) {
764
- if (
765
- (executionContext & CommitContext) !== NoContext &&
766
- root === rootCommittingMutationOrLayoutEffects
767
- ) {
768
- if (fiber.mode & ProfileMode) {
769
- let current: null | Fiber = fiber;
770
- while (current !== null) {
771
- if (current.tag === Profiler) {
772
- const {id, onNestedUpdateScheduled} = current.memoizedProps;
773
- if (typeof onNestedUpdateScheduled === 'function') {
774
- onNestedUpdateScheduled(id);
775
- }
776
- }
777
- current = current.return;
778
- }
779
- }
780
- }
781
- }
782
-
783
- if (enableTransitionTracing) {
784
- const transition = ReactCurrentBatchConfig.transition;
785
- if (transition !== null && transition.name != null) {
786
- if (transition.startTime === -1) {
787
- transition.startTime = now();
788
- }
789
-
790
- addTransitionToLanesMap(root, transition, lane);
791
- }
792
- }
793
-
794
- if (root === workInProgressRoot) {
795
- // Received an update to a tree that's in the middle of rendering. Mark
796
- // that there was an interleaved update work on this root. Unless the
797
- // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
798
- // phase update. In that case, we don't treat render phase updates as if
799
- // they were interleaved, for backwards compat reasons.
800
- if (
801
- deferRenderPhaseUpdateToNextBatch ||
802
- (executionContext & RenderContext) === NoContext
803
- ) {
804
- workInProgressRootInterleavedUpdatedLanes = mergeLanes(
805
- workInProgressRootInterleavedUpdatedLanes,
806
- lane,
807
- );
808
- }
809
- if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
810
- // The root already suspended with a delay, which means this render
811
- // definitely won't finish. Since we have a new update, let's mark it as
812
- // suspended now, right before marking the incoming update. This has the
813
- // effect of interrupting the current render and switching to the update.
814
- // TODO: Make sure this doesn't override pings that happen while we've
815
- // already started rendering.
816
- markRootSuspended(root, workInProgressRootRenderLanes);
817
- }
818
- }
819
-
820
- ensureRootIsScheduled(root, eventTime);
821
- if (
822
- lane === SyncLane &&
823
- executionContext === NoContext &&
824
- (fiber.mode & ConcurrentMode) === NoMode &&
825
- // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
826
- !(__DEV__ && ReactCurrentActQueue.isBatchingLegacy)
827
- ) {
828
- // Flush the synchronous work now, unless we're already working or inside
829
- // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
830
- // scheduleCallbackForFiber to preserve the ability to schedule a callback
831
- // without immediately flushing it. We only do this for user-initiated
832
- // updates, to preserve historical behavior of legacy mode.
833
- resetRenderTimer();
834
- flushSyncCallbacksOnlyInLegacyMode();
835
- }
836
- }
837
-}
838
-
839
-export function scheduleInitialHydrationOnRoot(
840
- root: FiberRoot,
841
- lane: Lane,
842
- eventTime: number,
843
-) {
844
- // This is a special fork of scheduleUpdateOnFiber that is only used to
845
- // schedule the initial hydration of a root that has just been created. Most
846
- // of the stuff in scheduleUpdateOnFiber can be skipped.
847
- //
848
- // The main reason for this separate path, though, is to distinguish the
849
- // initial children from subsequent updates. In fully client-rendered roots
850
- // (createRoot instead of hydrateRoot), all top-level renders are modeled as
851
- // updates, but hydration roots are special because the initial render must
852
- // match what was rendered on the server.
853
- const current = root.current;
854
- current.lanes = lane;
855
- markRootUpdated(root, lane, eventTime);
856
- ensureRootIsScheduled(root, eventTime);
857
-}
858
-
859
-export function isUnsafeClassRenderPhaseUpdate(fiber: Fiber): boolean {
860
- // Check if this is a render phase update. Only called by class components,
861
- // which special (deprecated) behavior for UNSAFE_componentWillReceive props.
862
- return (
863
- // TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
864
- // decided not to enable it.
865
- (!deferRenderPhaseUpdateToNextBatch ||
866
- (fiber.mode & ConcurrentMode) === NoMode) &&
867
- (executionContext & RenderContext) !== NoContext
868
- );
869
-}
870
-
871
-// Use this function to schedule a task for a root. There's only one task per
872
-// root; if a task was already scheduled, we'll check to make sure the priority
873
-// of the existing task is the same as the priority of the next level that the
874
-// root has work on. This function is called on every update, and right before
875
-// exiting a task.
876
-function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
877
- const existingCallbackNode = root.callbackNode;
878
-
879
- // Check if any lanes are being starved by other work. If so, mark them as
880
- // expired so we know to work on those next.
881
- markStarvedLanesAsExpired(root, currentTime);
882
-
883
- // Determine the next lanes to work on, and their priority.
884
- const nextLanes = getNextLanes(
885
- root,
886
- root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes,
887
- );
888
-
889
- if (nextLanes === NoLanes) {
890
- // Special case: There's nothing to work on.
891
- if (existingCallbackNode !== null) {
892
- cancelCallback(existingCallbackNode);
893
- }
894
- root.callbackNode = null;
895
- root.callbackPriority = NoLane;
896
- return;
897
- }
898
-
899
- // We use the highest priority lane to represent the priority of the callback.
900
- const newCallbackPriority = getHighestPriorityLane(nextLanes);
901
-
902
- // Check if there's an existing task. We may be able to reuse it.
903
- const existingCallbackPriority = root.callbackPriority;
904
- if (
905
- existingCallbackPriority === newCallbackPriority &&
906
- // Special case related to `act`. If the currently scheduled task is a
907
- // Scheduler task, rather than an `act` task, cancel it and re-scheduled
908
- // on the `act` queue.
909
- !(
910
- __DEV__ &&
911
- ReactCurrentActQueue.current !== null &&
912
- existingCallbackNode !== fakeActCallbackNode
913
- )
914
- ) {
915
- if (__DEV__) {
916
- // If we're going to re-use an existing task, it needs to exist.
917
- // Assume that discrete update microtasks are non-cancellable and null.
918
- // TODO: Temporary until we confirm this warning is not fired.
919
- if (
920
- existingCallbackNode == null &&
921
- !includesSyncLane(existingCallbackPriority)
922
- ) {
923
- console.error(
924
- 'Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.',
925
- );
926
- }
927
- }
928
- // The priority hasn't changed. We can reuse the existing task. Exit.
929
- return;
930
- }
931
-
932
- if (existingCallbackNode != null) {
933
- // Cancel the existing callback. We'll schedule a new one below.
934
- cancelCallback(existingCallbackNode);
935
- }
936
-
937
- // Schedule a new callback.
938
- let newCallbackNode;
939
- if (includesSyncLane(newCallbackPriority)) {
940
- // Special case: Sync React callbacks are scheduled on a special
941
- // internal queue
942
- if (root.tag === LegacyRoot) {
943
- if (__DEV__ && ReactCurrentActQueue.isBatchingLegacy !== null) {
944
- ReactCurrentActQueue.didScheduleLegacyUpdate = true;
945
- }
946
- scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root));
947
- } else {
948
- scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
949
- }
950
- if (supportsMicrotasks) {
951
- // Flush the queue in a microtask.
952
- if (__DEV__ && ReactCurrentActQueue.current !== null) {
953
- // Inside `act`, use our internal `act` queue so that these get flushed
954
- // at the end of the current scope even when using the sync version
955
- // of `act`.
956
- ReactCurrentActQueue.current.push(flushSyncCallbacks);
957
- } else {
958
- scheduleMicrotask(() => {
959
- // In Safari, appending an iframe forces microtasks to run.
960
- // https://github.com/facebook/react/issues/22459
961
- // We don't support running callbacks in the middle of render
962
- // or commit so we need to check against that.
963
- if (
964
- (executionContext & (RenderContext | CommitContext)) ===
965
- NoContext
966
- ) {
967
- // Note that this would still prematurely flush the callbacks
968
- // if this happens outside render or commit phase (e.g. in an event).
969
- flushSyncCallbacks();
970
- }
971
- });
972
- }
973
- } else {
974
- // Flush the queue in an Immediate task.
975
- scheduleCallback(ImmediateSchedulerPriority, flushSyncCallbacks);
976
- }
977
- newCallbackNode = null;
978
- } else {
979
- let schedulerPriorityLevel;
980
- switch (lanesToEventPriority(nextLanes)) {
981
- case DiscreteEventPriority:
982
- schedulerPriorityLevel = ImmediateSchedulerPriority;
983
- break;
984
- case ContinuousEventPriority:
985
- schedulerPriorityLevel = UserBlockingSchedulerPriority;
986
- break;
987
- case DefaultEventPriority:
988
- schedulerPriorityLevel = NormalSchedulerPriority;
989
- break;
990
- case IdleEventPriority:
991
- schedulerPriorityLevel = IdleSchedulerPriority;
992
- break;
993
- default:
994
- schedulerPriorityLevel = NormalSchedulerPriority;
995
- break;
996
- }
997
- newCallbackNode = scheduleCallback(
998
- schedulerPriorityLevel,
999
- performConcurrentWorkOnRoot.bind(null, root),
1000
- );
1001
- }
1002
-
1003
- root.callbackPriority = newCallbackPriority;
1004
- root.callbackNode = newCallbackNode;
1005
-}
1006
-
1007
-// This is the entry point for every concurrent task, i.e. anything that
1008
-// goes through Scheduler.
1009
-function performConcurrentWorkOnRoot(root, didTimeout) {
1010
- if (enableProfilerTimer && enableProfilerNestedUpdatePhase) {
1011
- resetNestedUpdateFlag();
1012
- }
1013
-
1014
- // Since we know we're in a React event, we can clear the current
1015
- // event time. The next update will compute a new event time.
1016
- currentEventTime = NoTimestamp;
1017
- currentEventTransitionLane = NoLanes;
1018
-
1019
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
1020
- throw new Error('Should not already be working.');
1021
- }
1022
-
1023
- // Flush any pending passive effects before deciding which lanes to work on,
1024
- // in case they schedule additional work.
1025
- const originalCallbackNode = root.callbackNode;
1026
- const didFlushPassiveEffects = flushPassiveEffects();
1027
- if (didFlushPassiveEffects) {
1028
- // Something in the passive effect phase may have canceled the current task.
1029
- // Check if the task node for this root was changed.
1030
- if (root.callbackNode !== originalCallbackNode) {
1031
- // The current task was canceled. Exit. We don't need to call
1032
- // `ensureRootIsScheduled` because the check above implies either that
1033
- // there's a new task, or that there's no remaining work on this root.
1034
- return null;
1035
- } else {
1036
- // Current task was not canceled. Continue.
1037
- }
1038
- }
1039
-
1040
- // Determine the next lanes to work on, using the fields stored
1041
- // on the root.
1042
- let lanes = getNextLanes(
1043
- root,
1044
- root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes,
1045
- );
1046
- if (lanes === NoLanes) {
1047
- // Defensive coding. This is never expected to happen.
1048
- return null;
1049
- }
1050
-
1051
- // We disable time-slicing in some cases: if the work has been CPU-bound
1052
- // for too long ("expired" work, to prevent starvation), or we're in
1053
- // sync-updates-by-default mode.
1054
- // TODO: We only check `didTimeout` defensively, to account for a Scheduler
1055
- // bug we're still investigating. Once the bug in Scheduler is fixed,
1056
- // we can remove this, since we track expiration ourselves.
1057
- const shouldTimeSlice =
1058
- !includesBlockingLane(root, lanes) &&
1059
- !includesExpiredLane(root, lanes) &&
1060
- (disableSchedulerTimeoutInWorkLoop || !didTimeout);
1061
- let exitStatus = shouldTimeSlice
1062
- ? renderRootConcurrent(root, lanes)
1063
- : renderRootSync(root, lanes);
1064
- if (exitStatus !== RootInProgress) {
1065
- if (exitStatus === RootErrored) {
1066
- // If something threw an error, try rendering one more time. We'll
1067
- // render synchronously to block concurrent data mutations, and we'll
1068
- // includes all pending updates are included. If it still fails after
1069
- // the second attempt, we'll give up and commit the resulting tree.
1070
- const originallyAttemptedLanes = lanes;
1071
- const errorRetryLanes = getLanesToRetrySynchronouslyOnError(
1072
- root,
1073
- originallyAttemptedLanes,
1074
- );
1075
- if (errorRetryLanes !== NoLanes) {
1076
- lanes = errorRetryLanes;
1077
- exitStatus = recoverFromConcurrentError(
1078
- root,
1079
- originallyAttemptedLanes,
1080
- errorRetryLanes,
1081
- );
1082
- }
1083
- }
1084
- if (exitStatus === RootFatalErrored) {
1085
- const fatalError = workInProgressRootFatalError;
1086
- prepareFreshStack(root, NoLanes);
1087
- markRootSuspended(root, lanes);
1088
- ensureRootIsScheduled(root, now());
1089
- throw fatalError;
1090
- }
1091
-
1092
- if (exitStatus === RootDidNotComplete) {
1093
- // The render unwound without completing the tree. This happens in special
1094
- // cases where need to exit the current render without producing a
1095
- // consistent tree or committing.
1096
- markRootSuspended(root, lanes);
1097
- } else {
1098
- // The render completed.
1099
-
1100
- // Check if this render may have yielded to a concurrent event, and if so,
1101
- // confirm that any newly rendered stores are consistent.
1102
- // TODO: It's possible that even a concurrent render may never have yielded
1103
- // to the main thread, if it was fast enough, or if it expired. We could
1104
- // skip the consistency check in that case, too.
1105
- const renderWasConcurrent = !includesBlockingLane(root, lanes);
1106
- const finishedWork: Fiber = (root.current.alternate: any);
1107
- if (
1108
- renderWasConcurrent &&
1109
- !isRenderConsistentWithExternalStores(finishedWork)
1110
- ) {
1111
- // A store was mutated in an interleaved event. Render again,
1112
- // synchronously, to block further mutations.
1113
- exitStatus = renderRootSync(root, lanes);
1114
-
1115
- // We need to check again if something threw
1116
- if (exitStatus === RootErrored) {
1117
- const originallyAttemptedLanes = lanes;
1118
- const errorRetryLanes = getLanesToRetrySynchronouslyOnError(
1119
- root,
1120
- originallyAttemptedLanes,
1121
- );
1122
- if (errorRetryLanes !== NoLanes) {
1123
- lanes = errorRetryLanes;
1124
- exitStatus = recoverFromConcurrentError(
1125
- root,
1126
- originallyAttemptedLanes,
1127
- errorRetryLanes,
1128
- );
1129
- // We assume the tree is now consistent because we didn't yield to any
1130
- // concurrent events.
1131
- }
1132
- }
1133
- if (exitStatus === RootFatalErrored) {
1134
- const fatalError = workInProgressRootFatalError;
1135
- prepareFreshStack(root, NoLanes);
1136
- markRootSuspended(root, lanes);
1137
- ensureRootIsScheduled(root, now());
1138
- throw fatalError;
1139
- }
1140
-
1141
- // FIXME: Need to check for RootDidNotComplete again. The factoring here
1142
- // isn't ideal.
1143
- }
1144
-
1145
- // We now have a consistent tree. The next step is either to commit it,
1146
- // or, if something suspended, wait to commit it after a timeout.
1147
- root.finishedWork = finishedWork;
1148
- root.finishedLanes = lanes;
1149
- finishConcurrentRender(root, exitStatus, lanes);
1150
- }
1151
- }
1152
-
1153
- ensureRootIsScheduled(root, now());
1154
- if (root.callbackNode === originalCallbackNode) {
1155
- // The task node scheduled for this root is the same one that's
1156
- // currently executed. Need to return a continuation.
1157
- if (
1158
- workInProgressSuspendedReason === SuspendedOnData &&
1159
- workInProgressRoot === root
1160
- ) {
1161
- // Special case: The work loop is currently suspended and waiting for
1162
- // data to resolve. Unschedule the current task.
1163
- //
1164
- // TODO: The factoring is a little weird. Arguably this should be checked
1165
- // in ensureRootIsScheduled instead. I went back and forth, not totally
1166
- // sure yet.
1167
- root.callbackPriority = NoLane;
1168
- root.callbackNode = null;
1169
- return null;
1170
- }
1171
- return performConcurrentWorkOnRoot.bind(null, root);
1172
- }
1173
- return null;
1174
-}
1175
-
1176
-function recoverFromConcurrentError(
1177
- root,
1178
- originallyAttemptedLanes,
1179
- errorRetryLanes,
1180
-) {
1181
- // If an error occurred during hydration, discard server response and fall
1182
- // back to client side render.
1183
-
1184
- // Before rendering again, save the errors from the previous attempt.
1185
- const errorsFromFirstAttempt = workInProgressRootConcurrentErrors;
1186
-
1187
- const wasRootDehydrated = isRootDehydrated(root);
1188
- if (wasRootDehydrated) {
1189
- // The shell failed to hydrate. Set a flag to force a client rendering
1190
- // during the next attempt. To do this, we call prepareFreshStack now
1191
- // to create the root work-in-progress fiber. This is a bit weird in terms
1192
- // of factoring, because it relies on renderRootSync not calling
1193
- // prepareFreshStack again in the call below, which happens because the
1194
- // root and lanes haven't changed.
1195
- //
1196
- // TODO: I think what we should do is set ForceClientRender inside
1197
- // throwException, like we do for nested Suspense boundaries. The reason
1198
- // it's here instead is so we can switch to the synchronous work loop, too.
1199
- // Something to consider for a future refactor.
1200
- const rootWorkInProgress = prepareFreshStack(root, errorRetryLanes);
1201
- rootWorkInProgress.flags |= ForceClientRender;
1202
- if (__DEV__) {
1203
- errorHydratingContainer(root.containerInfo);
1204
- }
1205
- }
1206
-
1207
- const exitStatus = renderRootSync(root, errorRetryLanes);
1208
- if (exitStatus !== RootErrored) {
1209
- // Successfully finished rendering on retry
1210
-
1211
- if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
1212
- // During the synchronous render, we attached additional ping listeners.
1213
- // This is highly suggestive of an uncached promise (though it's not the
1214
- // only reason this would happen). If it was an uncached promise, then
1215
- // it may have masked a downstream error from ocurring without actually
1216
- // fixing it. Example:
1217
- //
1218
- // use(Promise.resolve('uncached'))
1219
- // throw new Error('Oops!')
1220
- //
1221
- // When this happens, there's a conflict between blocking potential
1222
- // concurrent data races and unwrapping uncached promise values. We
1223
- // have to choose one or the other. Because the data race recovery is
1224
- // a last ditch effort, we'll disable it.
1225
- root.errorRecoveryDisabledLanes = mergeLanes(
1226
- root.errorRecoveryDisabledLanes,
1227
- originallyAttemptedLanes,
1228
- );
1229
-
1230
- // Mark the current render as suspended and force it to restart. Once
1231
- // these lanes finish successfully, we'll re-enable the error recovery
1232
- // mechanism for subsequent updates.
1233
- workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes;
1234
- return RootSuspendedWithDelay;
1235
- }
1236
-
1237
- // The errors from the failed first attempt have been recovered. Add
1238
- // them to the collection of recoverable errors. We'll log them in the
1239
- // commit phase.
1240
- const errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
1241
- workInProgressRootRecoverableErrors = errorsFromFirstAttempt;
1242
- // The errors from the second attempt should be queued after the errors
1243
- // from the first attempt, to preserve the causal sequence.
1244
- if (errorsFromSecondAttempt !== null) {
1245
- queueRecoverableErrors(errorsFromSecondAttempt);
1246
- }
1247
- } else {
1248
- // The UI failed to recover.
1249
- }
1250
- return exitStatus;
1251
-}
1252
-
1253
-export function queueRecoverableErrors(errors: Array<CapturedValue<mixed>>) {
1254
- if (workInProgressRootRecoverableErrors === null) {
1255
- workInProgressRootRecoverableErrors = errors;
1256
- } else {
1257
- // $FlowFixMe[method-unbinding]
1258
- workInProgressRootRecoverableErrors.push.apply(
1259
- workInProgressRootRecoverableErrors,
1260
- errors,
1261
- );
1262
- }
1263
-}
1264
-
1265
-function finishConcurrentRender(root, exitStatus, lanes) {
1266
- switch (exitStatus) {
1267
- case RootInProgress:
1268
- case RootFatalErrored: {
1269
- throw new Error('Root did not complete. This is a bug in React.');
1270
- }
1271
- // Flow knows about invariant, so it complains if I add a break
1272
- // statement, but eslint doesn't know about invariant, so it complains
1273
- // if I do. eslint-disable-next-line no-fallthrough
1274
- case RootErrored: {
1275
- // We should have already attempted to retry this tree. If we reached
1276
- // this point, it errored again. Commit it.
1277
- commitRoot(
1278
- root,
1279
- workInProgressRootRecoverableErrors,
1280
- workInProgressTransitions,
1281
- );
1282
- break;
1283
- }
1284
- case RootSuspended: {
1285
- markRootSuspended(root, lanes);
1286
-
1287
- // We have an acceptable loading state. We need to figure out if we
1288
- // should immediately commit it or wait a bit.
1289
-
1290
- if (
1291
- includesOnlyRetries(lanes) &&
1292
- // do not delay if we're inside an act() scope
1293
- !shouldForceFlushFallbacksInDEV()
1294
- ) {
1295
- // This render only included retries, no updates. Throttle committing
1296
- // retries so that we don't show too many loading states too quickly.
1297
- const msUntilTimeout =
1298
- globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now();
1299
- // Don't bother with a very short suspense time.
1300
- if (msUntilTimeout > 10) {
1301
- const nextLanes = getNextLanes(root, NoLanes);
1302
- if (nextLanes !== NoLanes) {
1303
- // There's additional work on this root.
1304
- break;
1305
- }
1306
- const suspendedLanes = root.suspendedLanes;
1307
- if (!isSubsetOfLanes(suspendedLanes, lanes)) {
1308
- // We should prefer to render the fallback of at the last
1309
- // suspended level. Ping the last suspended level to try
1310
- // rendering it again.
1311
- // FIXME: What if the suspended lanes are Idle? Should not restart.
1312
- const eventTime = requestEventTime();
1313
- markRootPinged(root, suspendedLanes, eventTime);
1314
- break;
1315
- }
1316
-
1317
- // The render is suspended, it hasn't timed out, and there's no
1318
- // lower priority work to do. Instead of committing the fallback
1319
- // immediately, wait for more data to arrive.
1320
- root.timeoutHandle = scheduleTimeout(
1321
- commitRoot.bind(
1322
- null,
1323
- root,
1324
- workInProgressRootRecoverableErrors,
1325
- workInProgressTransitions,
1326
- ),
1327
- msUntilTimeout,
1328
- );
1329
- break;
1330
- }
1331
- }
1332
- // The work expired. Commit immediately.
1333
- commitRoot(
1334
- root,
1335
- workInProgressRootRecoverableErrors,
1336
- workInProgressTransitions,
1337
- );
1338
- break;
1339
- }
1340
- case RootSuspendedWithDelay: {
1341
- markRootSuspended(root, lanes);
1342
-
1343
- if (includesOnlyTransitions(lanes)) {
1344
- // This is a transition, so we should exit without committing a
1345
- // placeholder and without scheduling a timeout. Delay indefinitely
1346
- // until we receive more data.
1347
- break;
1348
- }
1349
-
1350
- if (!shouldForceFlushFallbacksInDEV()) {
1351
- // This is not a transition, but we did trigger an avoided state.
1352
- // Schedule a placeholder to display after a short delay, using the Just
1353
- // Noticeable Difference.
1354
- // TODO: Is the JND optimization worth the added complexity? If this is
1355
- // the only reason we track the event time, then probably not.
1356
- // Consider removing.
1357
-
1358
- const mostRecentEventTime = getMostRecentEventTime(root, lanes);
1359
- const eventTimeMs = mostRecentEventTime;
1360
- const timeElapsedMs = now() - eventTimeMs;
1361
- const msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs;
1362
-
1363
- // Don't bother with a very short suspense time.
1364
- if (msUntilTimeout > 10) {
1365
- // Instead of committing the fallback immediately, wait for more data
1366
- // to arrive.
1367
- root.timeoutHandle = scheduleTimeout(
1368
- commitRoot.bind(
1369
- null,
1370
- root,
1371
- workInProgressRootRecoverableErrors,
1372
- workInProgressTransitions,
1373
- ),
1374
- msUntilTimeout,
1375
- );
1376
- break;
1377
- }
1378
- }
1379
-
1380
- // Commit the placeholder.
1381
- commitRoot(
1382
- root,
1383
- workInProgressRootRecoverableErrors,
1384
- workInProgressTransitions,
1385
- );
1386
- break;
1387
- }
1388
- case RootCompleted: {
1389
- // The work completed. Ready to commit.
1390
- commitRoot(
1391
- root,
1392
- workInProgressRootRecoverableErrors,
1393
- workInProgressTransitions,
1394
- );
1395
- break;
1396
- }
1397
- default: {
1398
- throw new Error('Unknown root exit status.');
1399
- }
1400
- }
1401
-}
1402
-
1403
-function isRenderConsistentWithExternalStores(finishedWork: Fiber): boolean {
1404
- // Search the rendered tree for external store reads, and check whether the
1405
- // stores were mutated in a concurrent event. Intentionally using an iterative
1406
- // loop instead of recursion so we can exit early.
1407
- let node: Fiber = finishedWork;
1408
- while (true) {
1409
- if (node.flags & StoreConsistency) {
1410
- const updateQueue: FunctionComponentUpdateQueue | null = (node.updateQueue: any);
1411
- if (updateQueue !== null) {
1412
- const checks = updateQueue.stores;
1413
- if (checks !== null) {
1414
- for (let i = 0; i < checks.length; i++) {
1415
- const check = checks[i];
1416
- const getSnapshot = check.getSnapshot;
1417
- const renderedValue = check.value;
1418
- try {
1419
- if (!is(getSnapshot(), renderedValue)) {
1420
- // Found an inconsistent store.
1421
- return false;
1422
- }
1423
- } catch (error) {
1424
- // If `getSnapshot` throws, return `false`. This will schedule
1425
- // a re-render, and the error will be rethrown during render.
1426
- return false;
1427
- }
1428
- }
1429
- }
1430
- }
1431
- }
1432
- const child = node.child;
1433
- if (node.subtreeFlags & StoreConsistency && child !== null) {
1434
- child.return = node;
1435
- node = child;
1436
- continue;
1437
- }
1438
- if (node === finishedWork) {
1439
- return true;
1440
- }
1441
- while (node.sibling === null) {
1442
- if (node.return === null || node.return === finishedWork) {
1443
- return true;
1444
- }
1445
- node = node.return;
1446
- }
1447
- node.sibling.return = node.return;
1448
- node = node.sibling;
1449
- }
1450
- // Flow doesn't know this is unreachable, but eslint does
1451
- // eslint-disable-next-line no-unreachable
1452
- return true;
1453
-}
1454
-
1455
-function markRootSuspended(root, suspendedLanes) {
1456
- // When suspending, we should always exclude lanes that were pinged or (more
1457
- // rarely, since we try to avoid it) updated during the render phase.
1458
- // TODO: Lol maybe there's a better way to factor this besides this
1459
- // obnoxiously named function :)
1460
- suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
1461
- suspendedLanes = removeLanes(
1462
- suspendedLanes,
1463
- workInProgressRootInterleavedUpdatedLanes,
1464
- );
1465
- // $FlowFixMe[incompatible-call] found when upgrading Flow
1466
- markRootSuspended_dontCallThisOneDirectly(root, suspendedLanes);
1467
-}
1468
-
1469
-// This is the entry point for synchronous tasks that don't go
1470
-// through Scheduler
1471
-function performSyncWorkOnRoot(root) {
1472
- if (enableProfilerTimer && enableProfilerNestedUpdatePhase) {
1473
- syncNestedUpdateFlag();
1474
- }
1475
-
1476
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
1477
- throw new Error('Should not already be working.');
1478
- }
1479
-
1480
- flushPassiveEffects();
1481
-
1482
- let lanes = getNextLanes(root, NoLanes);
1483
- if (!includesSyncLane(lanes)) {
1484
- // There's no remaining sync work left.
1485
- ensureRootIsScheduled(root, now());
1486
- return null;
1487
- }
1488
-
1489
- let exitStatus = renderRootSync(root, lanes);
1490
- if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
1491
- // If something threw an error, try rendering one more time. We'll render
1492
- // synchronously to block concurrent data mutations, and we'll includes
1493
- // all pending updates are included. If it still fails after the second
1494
- // attempt, we'll give up and commit the resulting tree.
1495
- const originallyAttemptedLanes = lanes;
1496
- const errorRetryLanes = getLanesToRetrySynchronouslyOnError(
1497
- root,
1498
- originallyAttemptedLanes,
1499
- );
1500
- if (errorRetryLanes !== NoLanes) {
1501
- lanes = errorRetryLanes;
1502
- exitStatus = recoverFromConcurrentError(
1503
- root,
1504
- originallyAttemptedLanes,
1505
- errorRetryLanes,
1506
- );
1507
- }
1508
- }
1509
-
1510
- if (exitStatus === RootFatalErrored) {
1511
- const fatalError = workInProgressRootFatalError;
1512
- prepareFreshStack(root, NoLanes);
1513
- markRootSuspended(root, lanes);
1514
- ensureRootIsScheduled(root, now());
1515
- throw fatalError;
1516
- }
1517
-
1518
- if (exitStatus === RootDidNotComplete) {
1519
- // The render unwound without completing the tree. This happens in special
1520
- // cases where need to exit the current render without producing a
1521
- // consistent tree or committing.
1522
- markRootSuspended(root, lanes);
1523
- ensureRootIsScheduled(root, now());
1524
- return null;
1525
- }
1526
-
1527
- // We now have a consistent tree. Because this is a sync render, we
1528
- // will commit it even if something suspended.
1529
- const finishedWork: Fiber = (root.current.alternate: any);
1530
- root.finishedWork = finishedWork;
1531
- root.finishedLanes = lanes;
1532
- commitRoot(
1533
- root,
1534
- workInProgressRootRecoverableErrors,
1535
- workInProgressTransitions,
1536
- );
1537
-
1538
- // Before exiting, make sure there's a callback scheduled for the next
1539
- // pending level.
1540
- ensureRootIsScheduled(root, now());
1541
-
1542
- return null;
1543
-}
1544
-
1545
-export function flushRoot(root: FiberRoot, lanes: Lanes) {
1546
- if (lanes !== NoLanes) {
1547
- markRootEntangled(root, mergeLanes(lanes, SyncLane));
1548
- ensureRootIsScheduled(root, now());
1549
- if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
1550
- resetRenderTimer();
1551
- flushSyncCallbacks();
1552
- }
1553
- }
1554
-}
1555
-
1556
-export function getExecutionContext(): ExecutionContext {
1557
- return executionContext;
1558
-}
1559
-
1560
-export function deferredUpdates<A>(fn: () => A): A {
1561
- const previousPriority = getCurrentUpdatePriority();
1562
- const prevTransition = ReactCurrentBatchConfig.transition;
1563
-
1564
- try {
1565
- ReactCurrentBatchConfig.transition = null;
1566
- setCurrentUpdatePriority(DefaultEventPriority);
1567
- return fn();
1568
- } finally {
1569
- setCurrentUpdatePriority(previousPriority);
1570
- ReactCurrentBatchConfig.transition = prevTransition;
1571
- }
1572
-}
1573
-
1574
-export function batchedUpdates<A, R>(fn: A => R, a: A): R {
1575
- const prevExecutionContext = executionContext;
1576
- executionContext |= BatchedContext;
1577
- try {
1578
- return fn(a);
1579
- } finally {
1580
- executionContext = prevExecutionContext;
1581
- // If there were legacy sync updates, flush them at the end of the outer
1582
- // most batchedUpdates-like method.
1583
- if (
1584
- executionContext === NoContext &&
1585
- // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
1586
- !(__DEV__ && ReactCurrentActQueue.isBatchingLegacy)
1587
- ) {
1588
- resetRenderTimer();
1589
- flushSyncCallbacksOnlyInLegacyMode();
1590
- }
1591
- }
1592
-}
1593
-
1594
-export function discreteUpdates<A, B, C, D, R>(
1595
- fn: (A, B, C, D) => R,
1596
- a: A,
1597
- b: B,
1598
- c: C,
1599
- d: D,
1600
-): R {
1601
- const previousPriority = getCurrentUpdatePriority();
1602
- const prevTransition = ReactCurrentBatchConfig.transition;
1603
- try {
1604
- ReactCurrentBatchConfig.transition = null;
1605
- setCurrentUpdatePriority(DiscreteEventPriority);
1606
- return fn(a, b, c, d);
1607
- } finally {
1608
- setCurrentUpdatePriority(previousPriority);
1609
- ReactCurrentBatchConfig.transition = prevTransition;
1610
- if (executionContext === NoContext) {
1611
- resetRenderTimer();
1612
- }
1613
- }
1614
-}
1615
-
1616
-// Overload the definition to the two valid signatures.
1617
-// Warning, this opts-out of checking the function body.
1618
-declare function flushSync<R>(fn: () => R): R;
1619
-// eslint-disable-next-line no-redeclare
1620
-declare function flushSync(void): void;
1621
-// eslint-disable-next-line no-redeclare
1622
-export function flushSync<R>(fn: (() => R) | void): R | void {
1623
- // In legacy mode, we flush pending passive effects at the beginning of the
1624
- // next event, not at the end of the previous one.
1625
- if (
1626
- rootWithPendingPassiveEffects !== null &&
1627
- rootWithPendingPassiveEffects.tag === LegacyRoot &&
1628
- (executionContext & (RenderContext | CommitContext)) === NoContext
1629
- ) {
1630
- flushPassiveEffects();
1631
- }
1632
-
1633
- const prevExecutionContext = executionContext;
1634
- executionContext |= BatchedContext;
1635
-
1636
- const prevTransition = ReactCurrentBatchConfig.transition;
1637
- const previousPriority = getCurrentUpdatePriority();
1638
-
1639
- try {
1640
- ReactCurrentBatchConfig.transition = null;
1641
- setCurrentUpdatePriority(DiscreteEventPriority);
1642
- if (fn) {
1643
- return fn();
1644
- } else {
1645
- return undefined;
1646
- }
1647
- } finally {
1648
- setCurrentUpdatePriority(previousPriority);
1649
- ReactCurrentBatchConfig.transition = prevTransition;
1650
-
1651
- executionContext = prevExecutionContext;
1652
- // Flush the immediate callbacks that were scheduled during this batch.
1653
- // Note that this will happen even if batchedUpdates is higher up
1654
- // the stack.
1655
- if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
1656
- flushSyncCallbacks();
1657
- }
1658
- }
1659
-}
1660
-
1661
-export function isAlreadyRendering(): boolean {
1662
- // Used by the renderer to print a warning if certain APIs are called from
1663
- // the wrong context.
1664
- return (
1665
- __DEV__ &&
1666
- (executionContext & (RenderContext | CommitContext)) !== NoContext
1667
- );
1668
-}
1669
-
1670
-export function isInvalidExecutionContextForEventFunction(): boolean {
1671
- // Used to throw if certain APIs are called from the wrong context.
1672
- return (executionContext & RenderContext) !== NoContext;
1673
-}
1674
-
1675
-export function flushControlled(fn: () => mixed): void {
1676
- const prevExecutionContext = executionContext;
1677
- executionContext |= BatchedContext;
1678
- const prevTransition = ReactCurrentBatchConfig.transition;
1679
- const previousPriority = getCurrentUpdatePriority();
1680
- try {
1681
- ReactCurrentBatchConfig.transition = null;
1682
- setCurrentUpdatePriority(DiscreteEventPriority);
1683
- fn();
1684
- } finally {
1685
- setCurrentUpdatePriority(previousPriority);
1686
- ReactCurrentBatchConfig.transition = prevTransition;
1687
-
1688
- executionContext = prevExecutionContext;
1689
- if (executionContext === NoContext) {
1690
- // Flush the immediate callbacks that were scheduled during this batch
1691
- resetRenderTimer();
1692
- flushSyncCallbacks();
1693
- }
1694
- }
1695
-}
1696
-
1697
-// This is called by the HiddenContext module when we enter or leave a
1698
-// hidden subtree. The stack logic is managed there because that's the only
1699
-// place that ever modifies it. Which module it lives in doesn't matter for
1700
-// performance because this function will get inlined regardless
1701
-export function setRenderLanes(subtreeRenderLanes: Lanes) {
1702
- renderLanes = subtreeRenderLanes;
1703
-}
1704
-
1705
-export function getRenderLanes(): Lanes {
1706
- return renderLanes;
1707
-}
1708
-
1709
-function prepareFreshStack(root: FiberRoot, lanes: Lanes): Fiber {
1710
- root.finishedWork = null;
1711
- root.finishedLanes = NoLanes;
1712
-
1713
- const timeoutHandle = root.timeoutHandle;
1714
- if (timeoutHandle !== noTimeout) {
1715
- // The root previous suspended and scheduled a timeout to commit a fallback
1716
- // state. Now that we have additional work, cancel the timeout.
1717
- root.timeoutHandle = noTimeout;
1718
- // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
1719
- cancelTimeout(timeoutHandle);
1720
- }
1721
-
1722
- if (workInProgress !== null) {
1723
- let interruptedWork;
1724
- if (workInProgressSuspendedReason === NotSuspended) {
1725
- // Normal case. Work-in-progress hasn't started yet. Unwind all
1726
- // its parents.
1727
- interruptedWork = workInProgress.return;
1728
- } else {
1729
- // Work-in-progress is in suspended state. Reset the work loop and unwind
1730
- // both the suspended fiber and all its parents.
1731
- resetSuspendedWorkLoopOnUnwind();
1732
- interruptedWork = workInProgress;
1733
- }
1734
- while (interruptedWork !== null) {
1735
- const current = interruptedWork.alternate;
1736
- unwindInterruptedWork(
1737
- current,
1738
- interruptedWork,
1739
- workInProgressRootRenderLanes,
1740
- );
1741
- interruptedWork = interruptedWork.return;
1742
- }
1743
- }
1744
- workInProgressRoot = root;
1745
- const rootWorkInProgress = createWorkInProgress(root.current, null);
1746
- workInProgress = rootWorkInProgress;
1747
- workInProgressRootRenderLanes = renderLanes = lanes;
1748
- workInProgressSuspendedReason = NotSuspended;
1749
- workInProgressThrownValue = null;
1750
- workInProgressRootDidAttachPingListener = false;
1751
- workInProgressRootExitStatus = RootInProgress;
1752
- workInProgressRootFatalError = null;
1753
- workInProgressRootSkippedLanes = NoLanes;
1754
- workInProgressRootInterleavedUpdatedLanes = NoLanes;
1755
- workInProgressRootRenderPhaseUpdatedLanes = NoLanes;
1756
- workInProgressRootPingedLanes = NoLanes;
1757
- workInProgressRootConcurrentErrors = null;
1758
- workInProgressRootRecoverableErrors = null;
1759
-
1760
- finishQueueingConcurrentUpdates();
1761
-
1762
- if (__DEV__) {
1763
- ReactStrictModeWarnings.discardPendingWarnings();
1764
- }
1765
-
1766
- return rootWorkInProgress;
1767
-}
1768
-
1769
-function resetSuspendedWorkLoopOnUnwind() {
1770
- // Reset module-level state that was set during the render phase.
1771
- resetContextDependencies();
1772
- resetHooksOnUnwind();
1773
-}
1774
-
1775
-function handleThrow(root, thrownValue): void {
1776
- // A component threw an exception. Usually this is because it suspended, but
1777
- // it also includes regular program errors.
1778
- //
1779
- // We're either going to unwind the stack to show a Suspense or error
1780
- // boundary, or we're going to replay the component again. Like after a
1781
- // promise resolves.
1782
- //
1783
- // Until we decide whether we're going to unwind or replay, we should preserve
1784
- // the current state of the work loop without resetting anything.
1785
- //
1786
- // If we do decide to unwind the stack, module-level variables will be reset
1787
- // in resetSuspendedWorkLoopOnUnwind.
1788
-
1789
- // These should be reset immediately because they're only supposed to be set
1790
- // when React is executing user code.
1791
- resetHooksAfterThrow();
1792
- resetCurrentDebugFiberInDEV();
1793
- ReactCurrentOwner.current = null;
1794
-
1795
- if (thrownValue === SuspenseException) {
1796
- // This is a special type of exception used for Suspense. For historical
1797
- // reasons, the rest of the Suspense implementation expects the thrown value
1798
- // to be a thenable, because before `use` existed that was the (unstable)
1799
- // API for suspending. This implementation detail can change later, once we
1800
- // deprecate the old API in favor of `use`.
1801
- thrownValue = getSuspendedThenable();
1802
- workInProgressSuspendedReason = shouldAttemptToSuspendUntilDataResolves()
1803
- ? SuspendedOnData
1804
- : SuspendedOnImmediate;
1805
- } else if (thrownValue === SelectiveHydrationException) {
1806
- // An update flowed into a dehydrated boundary. Before we can apply the
1807
- // update, we need to finish hydrating. Interrupt the work-in-progress
1808
- // render so we can restart at the hydration lane.
1809
- //
1810
- // The ideal implementation would be able to switch contexts without
1811
- // unwinding the current stack.
1812
- //
1813
- // We could name this something more general but as of now it's the only
1814
- // case where we think this should happen.
1815
- workInProgressSuspendedReason = SuspendedOnHydration;
1816
- } else {
1817
- // This is a regular error.
1818
- const isWakeable =
1819
- thrownValue !== null &&
1820
- typeof thrownValue === 'object' &&
1821
- // $FlowFixMe[method-unbinding]
1822
- typeof thrownValue.then === 'function';
1823
-
1824
- workInProgressSuspendedReason = isWakeable
1825
- ? // A wakeable object was thrown by a legacy Suspense implementation.
1826
- // This has slightly different behavior than suspending with `use`.
1827
- SuspendedOnDeprecatedThrowPromise
1828
- : // This is a regular error. If something earlier in the component already
1829
- // suspended, we must clear the thenable state to unblock the work loop.
1830
- SuspendedOnError;
1831
- }
1832
-
1833
- workInProgressThrownValue = thrownValue;
1834
-
1835
- const erroredWork = workInProgress;
1836
- if (erroredWork === null) {
1837
- // This is a fatal error
1838
- workInProgressRootExitStatus = RootFatalErrored;
1839
- workInProgressRootFatalError = thrownValue;
1840
- return;
1841
- }
1842
-
1843
- if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
1844
- // Record the time spent rendering before an error was thrown. This
1845
- // avoids inaccurate Profiler durations in the case of a
1846
- // suspended render.
1847
- stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
1848
- }
1849
-
1850
- if (enableSchedulingProfiler) {
1851
- markComponentRenderStopped();
1852
- if (workInProgressSuspendedReason !== SuspendedOnError) {
1853
- const wakeable: Wakeable = (thrownValue: any);
1854
- markComponentSuspended(
1855
- erroredWork,
1856
- wakeable,
1857
- workInProgressRootRenderLanes,
1858
- );
1859
- } else {
1860
- markComponentErrored(
1861
- erroredWork,
1862
- thrownValue,
1863
- workInProgressRootRenderLanes,
1864
- );
1865
- }
1866
- }
1867
-}
1868
-
1869
-function shouldAttemptToSuspendUntilDataResolves() {
1870
- // TODO: We should be able to move the
1871
- // renderDidSuspend/renderDidSuspendDelayIfPossible logic into this function,
1872
- // instead of repeating it in the complete phase. Or something to that effect.
1873
-
1874
- if (includesOnlyRetries(workInProgressRootRenderLanes)) {
1875
- // We can always wait during a retry.
1876
- return true;
1877
- }
1878
-
1879
- // Check if there are other pending updates that might possibly unblock this
1880
- // component from suspending. This mirrors the check in
1881
- // renderDidSuspendDelayIfPossible. We should attempt to unify them somehow.
1882
- if (
1883
- includesNonIdleWork(workInProgressRootSkippedLanes) ||
1884
- includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes)
1885
- ) {
1886
- // Suspend normally. renderDidSuspendDelayIfPossible will handle
1887
- // interrupting the work loop.
1888
- return false;
1889
- }
1890
-
1891
- // TODO: We should be able to remove the equivalent check in
1892
- // finishConcurrentRender, and rely just on this one.
1893
- if (includesOnlyTransitions(workInProgressRootRenderLanes)) {
1894
- const suspenseHandler = getSuspenseHandler();
1895
- if (suspenseHandler !== null && suspenseHandler.tag === SuspenseComponent) {
1896
- const currentSuspenseHandler = suspenseHandler.alternate;
1897
- const nextProps: SuspenseProps = suspenseHandler.memoizedProps;
1898
- if (isBadSuspenseFallback(currentSuspenseHandler, nextProps)) {
1899
- // The nearest Suspense boundary is already showing content. We should
1900
- // avoid replacing it with a fallback, and instead wait until the
1901
- // data finishes loading.
1902
- return true;
1903
- } else {
1904
- // This is not a bad fallback condition. We should show a fallback
1905
- // immediately instead of waiting for the data to resolve. This includes
1906
- // when suspending inside new trees.
1907
- return false;
1908
- }
1909
- }
1910
-
1911
- // During a transition, if there is no Suspense boundary (i.e. suspending in
1912
- // the "shell" of an application), or if we're inside a hidden tree, then
1913
- // we should wait until the data finishes loading.
1914
- return true;
1915
- }
1916
-
1917
- // For all other Lanes besides Transitions and Retries, we should not wait
1918
- // for the data to load.
1919
- // TODO: We should wait during Offscreen prerendering, too.
1920
- return false;
1921
-}
1922
-
1923
-function pushDispatcher(container) {
1924
- prepareRendererToRender(container);
1925
- const prevDispatcher = ReactCurrentDispatcher.current;
1926
- ReactCurrentDispatcher.current = ContextOnlyDispatcher;
1927
- if (prevDispatcher === null) {
1928
- // The React isomorphic package does not include a default dispatcher.
1929
- // Instead the first renderer will lazily attach one, in order to give
1930
- // nicer error messages.
1931
- return ContextOnlyDispatcher;
1932
- } else {
1933
- return prevDispatcher;
1934
- }
1935
-}
1936
-
1937
-function popDispatcher(prevDispatcher) {
1938
- resetRendererAfterRender();
1939
- ReactCurrentDispatcher.current = prevDispatcher;
1940
-}
1941
-
1942
-function pushCacheDispatcher() {
1943
- if (enableCache) {
1944
- const prevCacheDispatcher = ReactCurrentCache.current;
1945
- ReactCurrentCache.current = DefaultCacheDispatcher;
1946
- return prevCacheDispatcher;
1947
- } else {
1948
- return null;
1949
- }
1950
-}
1951
-
1952
-function popCacheDispatcher(prevCacheDispatcher) {
1953
- if (enableCache) {
1954
- ReactCurrentCache.current = prevCacheDispatcher;
1955
- }
1956
-}
1957
-
1958
-export function markCommitTimeOfFallback() {
1959
- globalMostRecentFallbackTime = now();
1960
-}
1961
-
1962
-export function markSkippedUpdateLanes(lane: Lane | Lanes): void {
1963
- workInProgressRootSkippedLanes = mergeLanes(
1964
- lane,
1965
- workInProgressRootSkippedLanes,
1966
- );
1967
-}
1968
-
1969
-export function renderDidSuspend(): void {
1970
- if (workInProgressRootExitStatus === RootInProgress) {
1971
- workInProgressRootExitStatus = RootSuspended;
1972
- }
1973
-}
1974
-
1975
-export function renderDidSuspendDelayIfPossible(): void {
1976
- workInProgressRootExitStatus = RootSuspendedWithDelay;
1977
-
1978
- // Check if there are updates that we skipped tree that might have unblocked
1979
- // this render.
1980
- if (
1981
- workInProgressRoot !== null &&
1982
- (includesNonIdleWork(workInProgressRootSkippedLanes) ||
1983
- includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))
1984
- ) {
1985
- // Mark the current render as suspended so that we switch to working on
1986
- // the updates that were skipped. Usually we only suspend at the end of
1987
- // the render phase.
1988
- // TODO: We should probably always mark the root as suspended immediately
1989
- // (inside this function), since by suspending at the end of the render
1990
- // phase introduces a potential mistake where we suspend lanes that were
1991
- // pinged or updated while we were rendering.
1992
- markRootSuspended(workInProgressRoot, workInProgressRootRenderLanes);
1993
- }
1994
-}
1995
-
1996
-export function renderDidError(error: CapturedValue<mixed>) {
1997
- if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
1998
- workInProgressRootExitStatus = RootErrored;
1999
- }
2000
- if (workInProgressRootConcurrentErrors === null) {
2001
- workInProgressRootConcurrentErrors = [error];
2002
- } else {
2003
- workInProgressRootConcurrentErrors.push(error);
2004
- }
2005
-}
2006
-
2007
-// Called during render to determine if anything has suspended.
2008
-// Returns false if we're not sure.
2009
-export function renderHasNotSuspendedYet(): boolean {
2010
- // If something errored or completed, we can't really be sure,
2011
- // so those are false.
2012
- return workInProgressRootExitStatus === RootInProgress;
2013
-}
2014
-
2015
-// TODO: Over time, this function and renderRootConcurrent have become more
2016
-// and more similar. Not sure it makes sense to maintain forked paths. Consider
2017
-// unifying them again.
2018
-function renderRootSync(root: FiberRoot, lanes: Lanes) {
2019
- const prevExecutionContext = executionContext;
2020
- executionContext |= RenderContext;
2021
- const prevDispatcher = pushDispatcher(root.containerInfo);
2022
- const prevCacheDispatcher = pushCacheDispatcher();
2023
-
2024
- // If the root or lanes have changed, throw out the existing stack
2025
- // and prepare a fresh one. Otherwise we'll continue where we left off.
2026
- if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
2027
- if (enableUpdaterTracking) {
2028
- if (isDevToolsPresent) {
2029
- const memoizedUpdaters = root.memoizedUpdaters;
2030
- if (memoizedUpdaters.size > 0) {
2031
- restorePendingUpdaters(root, workInProgressRootRenderLanes);
2032
- memoizedUpdaters.clear();
2033
- }
2034
-
2035
- // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
2036
- // If we bailout on this work, we'll move them back (like above).
2037
- // It's important to move them now in case the work spawns more work at the same priority with different updaters.
2038
- // That way we can keep the current update and future updates separate.
2039
- movePendingFibersToMemoized(root, lanes);
2040
- }
2041
- }
2042
-
2043
- workInProgressTransitions = getTransitionsForLanes(root, lanes);
2044
- prepareFreshStack(root, lanes);
2045
- }
2046
-
2047
- if (__DEV__) {
2048
- if (enableDebugTracing) {
2049
- logRenderStarted(lanes);
2050
- }
2051
- }
2052
-
2053
- if (enableSchedulingProfiler) {
2054
- markRenderStarted(lanes);
2055
- }
2056
-
2057
- outer: do {
2058
- try {
2059
- if (
2060
- workInProgressSuspendedReason !== NotSuspended &&
2061
- workInProgress !== null
2062
- ) {
2063
- // The work loop is suspended. During a synchronous render, we don't
2064
- // yield to the main thread. Immediately unwind the stack. This will
2065
- // trigger either a fallback or an error boundary.
2066
- // TODO: For discrete and "default" updates (anything that's not
2067
- // flushSync), we want to wait for the microtasks the flush before
2068
- // unwinding. Will probably implement this using renderRootConcurrent,
2069
- // or merge renderRootSync and renderRootConcurrent into the same
2070
- // function and fork the behavior some other way.
2071
- const unitOfWork = workInProgress;
2072
- const thrownValue = workInProgressThrownValue;
2073
- switch (workInProgressSuspendedReason) {
2074
- case SuspendedOnHydration: {
2075
- // Selective hydration. An update flowed into a dehydrated tree.
2076
- // Interrupt the current render so the work loop can switch to the
2077
- // hydration lane.
2078
- workInProgress = null;
2079
- workInProgressRootExitStatus = RootDidNotComplete;
2080
- break outer;
2081
- }
2082
- default: {
2083
- // Continue with the normal work loop.
2084
- workInProgressSuspendedReason = NotSuspended;
2085
- workInProgressThrownValue = null;
2086
- unwindSuspendedUnitOfWork(unitOfWork, thrownValue);
2087
- break;
2088
- }
2089
- }
2090
- }
2091
- workLoopSync();
2092
- break;
2093
- } catch (thrownValue) {
2094
- handleThrow(root, thrownValue);
2095
- }
2096
- } while (true);
2097
- resetContextDependencies();
2098
-
2099
- executionContext = prevExecutionContext;
2100
- popDispatcher(prevDispatcher);
2101
- popCacheDispatcher(prevCacheDispatcher);
2102
-
2103
- if (workInProgress !== null) {
2104
- // This is a sync render, so we should have finished the whole tree.
2105
- throw new Error(
2106
- 'Cannot commit an incomplete root. This error is likely caused by a ' +
2107
- 'bug in React. Please file an issue.',
2108
- );
2109
- }
2110
-
2111
- if (__DEV__) {
2112
- if (enableDebugTracing) {
2113
- logRenderStopped();
2114
- }
2115
- }
2116
-
2117
- if (enableSchedulingProfiler) {
2118
- markRenderStopped();
2119
- }
2120
-
2121
- // Set this to null to indicate there's no in-progress render.
2122
- workInProgressRoot = null;
2123
- workInProgressRootRenderLanes = NoLanes;
2124
-
2125
- // It's safe to process the queue now that the render phase is complete.
2126
- finishQueueingConcurrentUpdates();
2127
-
2128
- return workInProgressRootExitStatus;
2129
-}
2130
-
2131
-// The work loop is an extremely hot path. Tell Closure not to inline it.
2132
-/** @noinline */
2133
-function workLoopSync() {
2134
- // Perform work without checking if we need to yield between fiber.
2135
- while (workInProgress !== null) {
2136
- performUnitOfWork(workInProgress);
2137
- }
2138
-}
2139
-
2140
-function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
2141
- const prevExecutionContext = executionContext;
2142
- executionContext |= RenderContext;
2143
- const prevDispatcher = pushDispatcher(root.containerInfo);
2144
- const prevCacheDispatcher = pushCacheDispatcher();
2145
-
2146
- // If the root or lanes have changed, throw out the existing stack
2147
- // and prepare a fresh one. Otherwise we'll continue where we left off.
2148
- if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
2149
- if (enableUpdaterTracking) {
2150
- if (isDevToolsPresent) {
2151
- const memoizedUpdaters = root.memoizedUpdaters;
2152
- if (memoizedUpdaters.size > 0) {
2153
- restorePendingUpdaters(root, workInProgressRootRenderLanes);
2154
- memoizedUpdaters.clear();
2155
- }
2156
-
2157
- // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
2158
- // If we bailout on this work, we'll move them back (like above).
2159
- // It's important to move them now in case the work spawns more work at the same priority with different updaters.
2160
- // That way we can keep the current update and future updates separate.
2161
- movePendingFibersToMemoized(root, lanes);
2162
- }
2163
- }
2164
-
2165
- workInProgressTransitions = getTransitionsForLanes(root, lanes);
2166
- resetRenderTimer();
2167
- prepareFreshStack(root, lanes);
2168
- }
2169
-
2170
- if (__DEV__) {
2171
- if (enableDebugTracing) {
2172
- logRenderStarted(lanes);
2173
- }
2174
- }
2175
-
2176
- if (enableSchedulingProfiler) {
2177
- markRenderStarted(lanes);
2178
- }
2179
-
2180
- outer: do {
2181
- try {
2182
- if (
2183
- workInProgressSuspendedReason !== NotSuspended &&
2184
- workInProgress !== null
2185
- ) {
2186
- // The work loop is suspended. We need to either unwind the stack or
2187
- // replay the suspended component.
2188
- const unitOfWork = workInProgress;
2189
- const thrownValue = workInProgressThrownValue;
2190
- switch (workInProgressSuspendedReason) {
2191
- case SuspendedOnError: {
2192
- // Unwind then continue with the normal work loop.
2193
- workInProgressSuspendedReason = NotSuspended;
2194
- workInProgressThrownValue = null;
2195
- unwindSuspendedUnitOfWork(unitOfWork, thrownValue);
2196
- break;
2197
- }
2198
- case SuspendedOnData: {
2199
- const thenable: Thenable<mixed> = (thrownValue: any);
2200
- if (isThenableResolved(thenable)) {
2201
- // The data resolved. Try rendering the component again.
2202
- workInProgressSuspendedReason = NotSuspended;
2203
- workInProgressThrownValue = null;
2204
- replaySuspendedUnitOfWork(unitOfWork);
2205
- break;
2206
- }
2207
- // The work loop is suspended on data. We should wait for it to
2208
- // resolve before continuing to render.
2209
- const onResolution = () => {
2210
- ensureRootIsScheduled(root, now());
2211
- };
2212
- thenable.then(onResolution, onResolution);
2213
- break outer;
2214
- }
2215
- case SuspendedOnImmediate: {
2216
- // If this fiber just suspended, it's possible the data is already
2217
- // cached. Yield to the main thread to give it a chance to ping. If
2218
- // it does, we can retry immediately without unwinding the stack.
2219
- workInProgressSuspendedReason = SuspendedAndReadyToUnwind;
2220
- break outer;
2221
- }
2222
- case SuspendedAndReadyToUnwind: {
2223
- const thenable: Thenable<mixed> = (thrownValue: any);
2224
- if (isThenableResolved(thenable)) {
2225
- // The data resolved. Try rendering the component again.
2226
- workInProgressSuspendedReason = NotSuspended;
2227
- workInProgressThrownValue = null;
2228
- replaySuspendedUnitOfWork(unitOfWork);
2229
- } else {
2230
- // Otherwise, unwind then continue with the normal work loop.
2231
- workInProgressSuspendedReason = NotSuspended;
2232
- workInProgressThrownValue = null;
2233
- unwindSuspendedUnitOfWork(unitOfWork, thrownValue);
2234
- }
2235
- break;
2236
- }
2237
- case SuspendedOnDeprecatedThrowPromise: {
2238
- // Suspended by an old implementation that uses the `throw promise`
2239
- // pattern. The newer replaying behavior can cause subtle issues
2240
- // like infinite ping loops. So we maintain the old behavior and
2241
- // always unwind.
2242
- workInProgressSuspendedReason = NotSuspended;
2243
- workInProgressThrownValue = null;
2244
- unwindSuspendedUnitOfWork(unitOfWork, thrownValue);
2245
- break;
2246
- }
2247
- case SuspendedOnHydration: {
2248
- // Selective hydration. An update flowed into a dehydrated tree.
2249
- // Interrupt the current render so the work loop can switch to the
2250
- // hydration lane.
2251
- workInProgress = null;
2252
- workInProgressRootExitStatus = RootDidNotComplete;
2253
- break outer;
2254
- }
2255
- default: {
2256
- throw new Error(
2257
- 'Unexpected SuspendedReason. This is a bug in React.',
2258
- );
2259
- }
2260
- }
2261
- }
2262
- workLoopConcurrent();
2263
- break;
2264
- } catch (thrownValue) {
2265
- handleThrow(root, thrownValue);
2266
- }
2267
- } while (true);
2268
- resetContextDependencies();
2269
-
2270
- popDispatcher(prevDispatcher);
2271
- popCacheDispatcher(prevCacheDispatcher);
2272
- executionContext = prevExecutionContext;
2273
-
2274
- if (__DEV__) {
2275
- if (enableDebugTracing) {
2276
- logRenderStopped();
2277
- }
2278
- }
2279
-
2280
- // Check if the tree has completed.
2281
- if (workInProgress !== null) {
2282
- // Still work remaining.
2283
- if (enableSchedulingProfiler) {
2284
- markRenderYielded();
2285
- }
2286
- return RootInProgress;
2287
- } else {
2288
- // Completed the tree.
2289
- if (enableSchedulingProfiler) {
2290
- markRenderStopped();
2291
- }
2292
-
2293
- // Set this to null to indicate there's no in-progress render.
2294
- workInProgressRoot = null;
2295
- workInProgressRootRenderLanes = NoLanes;
2296
-
2297
- // It's safe to process the queue now that the render phase is complete.
2298
- finishQueueingConcurrentUpdates();
2299
-
2300
- // Return the final exit status.
2301
- return workInProgressRootExitStatus;
2302
- }
2303
-}
2304
-
2305
-/** @noinline */
2306
-function workLoopConcurrent() {
2307
- // Perform work until Scheduler asks us to yield
2308
- while (workInProgress !== null && !shouldYield()) {
2309
- // $FlowFixMe[incompatible-call] found when upgrading Flow
2310
- performUnitOfWork(workInProgress);
2311
- }
2312
-}
2313
-
2314
-function performUnitOfWork(unitOfWork: Fiber): void {
2315
- // The current, flushed, state of this fiber is the alternate. Ideally
2316
- // nothing should rely on this, but relying on it here means that we don't
2317
- // need an additional field on the work in progress.
2318
- const current = unitOfWork.alternate;
2319
- setCurrentDebugFiberInDEV(unitOfWork);
2320
-
2321
- let next;
2322
- if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
2323
- startProfilerTimer(unitOfWork);
2324
- next = beginWork(current, unitOfWork, renderLanes);
2325
- stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
2326
- } else {
2327
- next = beginWork(current, unitOfWork, renderLanes);
2328
- }
2329
-
2330
- resetCurrentDebugFiberInDEV();
2331
- unitOfWork.memoizedProps = unitOfWork.pendingProps;
2332
- if (next === null) {
2333
- // If this doesn't spawn new work, complete the current work.
2334
- completeUnitOfWork(unitOfWork);
2335
- } else {
2336
- workInProgress = next;
2337
- }
2338
-
2339
- ReactCurrentOwner.current = null;
2340
-}
2341
-
2342
-function replaySuspendedUnitOfWork(unitOfWork: Fiber): void {
2343
- // This is a fork of performUnitOfWork specifcally for replaying a fiber that
2344
- // just suspended.
2345
- //
2346
- const current = unitOfWork.alternate;
2347
- setCurrentDebugFiberInDEV(unitOfWork);
2348
-
2349
- let next;
2350
- setCurrentDebugFiberInDEV(unitOfWork);
2351
- const isProfilingMode =
2352
- enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode;
2353
- if (isProfilingMode) {
2354
- startProfilerTimer(unitOfWork);
2355
- }
2356
- switch (unitOfWork.tag) {
2357
- case IndeterminateComponent: {
2358
- // Because it suspended with `use`, we can assume it's a
2359
- // function component.
2360
- unitOfWork.tag = FunctionComponent;
2361
- // Fallthrough to the next branch.
2362
- }
2363
- // eslint-disable-next-line no-fallthrough
2364
- case FunctionComponent:
2365
- case ForwardRef: {
2366
- // Resolve `defaultProps`. This logic is copied from `beginWork`.
2367
- // TODO: Consider moving this switch statement into that module. Also,
2368
- // could maybe use this as an opportunity to say `use` doesn't work with
2369
- // `defaultProps` :)
2370
- const Component = unitOfWork.type;
2371
- const unresolvedProps = unitOfWork.pendingProps;
2372
- const resolvedProps =
2373
- unitOfWork.elementType === Component
2374
- ? unresolvedProps
2375
- : resolveDefaultProps(Component, unresolvedProps);
2376
- next = replayFunctionComponent(
2377
- current,
2378
- unitOfWork,
2379
- resolvedProps,
2380
- Component,
2381
- workInProgressRootRenderLanes,
2382
- );
2383
- break;
2384
- }
2385
- case SimpleMemoComponent: {
2386
- const Component = unitOfWork.type;
2387
- const nextProps = unitOfWork.pendingProps;
2388
- next = replayFunctionComponent(
2389
- current,
2390
- unitOfWork,
2391
- nextProps,
2392
- Component,
2393
- workInProgressRootRenderLanes,
2394
- );
2395
- break;
2396
- }
2397
- default: {
2398
- if (__DEV__) {
2399
- console.error(
2400
- 'Unexpected type of work: %s, Currently only function ' +
2401
- 'components are replayed after suspending. This is a bug in React.',
2402
- unitOfWork.tag,
2403
- );
2404
- }
2405
- resetSuspendedWorkLoopOnUnwind();
2406
- unwindInterruptedWork(current, unitOfWork, workInProgressRootRenderLanes);
2407
- unitOfWork = workInProgress = resetWorkInProgress(
2408
- unitOfWork,
2409
- renderLanes,
2410
- );
2411
- next = beginWork(current, unitOfWork, renderLanes);
2412
- break;
2413
- }
2414
- }
2415
- if (isProfilingMode) {
2416
- stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
2417
- }
2418
-
2419
- // The begin phase finished successfully without suspending. Return to the
2420
- // normal work loop.
2421
-
2422
- resetCurrentDebugFiberInDEV();
2423
- unitOfWork.memoizedProps = unitOfWork.pendingProps;
2424
- if (next === null) {
2425
- // If this doesn't spawn new work, complete the current work.
2426
- completeUnitOfWork(unitOfWork);
2427
- } else {
2428
- workInProgress = next;
2429
- }
2430
-
2431
- ReactCurrentOwner.current = null;
2432
-}
2433
-
2434
-function unwindSuspendedUnitOfWork(unitOfWork: Fiber, thrownValue: mixed) {
2435
- // This is a fork of performUnitOfWork specifcally for unwinding a fiber
2436
- // that threw an exception.
2437
- //
2438
- // Return to the normal work loop. This will unwind the stack, and potentially
2439
- // result in showing a fallback.
2440
- resetSuspendedWorkLoopOnUnwind();
2441
-
2442
- const returnFiber = unitOfWork.return;
2443
- if (returnFiber === null || workInProgressRoot === null) {
2444
- // Expected to be working on a non-root fiber. This is a fatal error
2445
- // because there's no ancestor that can handle it; the root is
2446
- // supposed to capture all errors that weren't caught by an error
2447
- // boundary.
2448
- workInProgressRootExitStatus = RootFatalErrored;
2449
- workInProgressRootFatalError = thrownValue;
2450
- // Set `workInProgress` to null. This represents advancing to the next
2451
- // sibling, or the parent if there are no siblings. But since the root
2452
- // has no siblings nor a parent, we set it to null. Usually this is
2453
- // handled by `completeUnitOfWork` or `unwindWork`, but since we're
2454
- // intentionally not calling those, we need set it here.
2455
- // TODO: Consider calling `unwindWork` to pop the contexts.
2456
- workInProgress = null;
2457
- return;
2458
- }
2459
-
2460
- try {
2461
- // Find and mark the nearest Suspense or error boundary that can handle
2462
- // this "exception".
2463
- throwException(
2464
- workInProgressRoot,
2465
- returnFiber,
2466
- unitOfWork,
2467
- thrownValue,
2468
- workInProgressRootRenderLanes,
2469
- );
2470
- } catch (error) {
2471
- // We had trouble processing the error. An example of this happening is
2472
- // when accessing the `componentDidCatch` property of an error boundary
2473
- // throws an error. A weird edge case. There's a regression test for this.
2474
- // To prevent an infinite loop, bubble the error up to the next parent.
2475
- workInProgress = returnFiber;
2476
- throw error;
2477
- }
2478
-
2479
- // Return to the normal work loop.
2480
- completeUnitOfWork(unitOfWork);
2481
-}
2482
-
2483
-function completeUnitOfWork(unitOfWork: Fiber): void {
2484
- // Attempt to complete the current unit of work, then move to the next
2485
- // sibling. If there are no more siblings, return to the parent fiber.
2486
- let completedWork: Fiber = unitOfWork;
2487
- do {
2488
- // The current, flushed, state of this fiber is the alternate. Ideally
2489
- // nothing should rely on this, but relying on it here means that we don't
2490
- // need an additional field on the work in progress.
2491
- const current = completedWork.alternate;
2492
- const returnFiber = completedWork.return;
2493
-
2494
- // Check if the work completed or if something threw.
2495
- if ((completedWork.flags & Incomplete) === NoFlags) {
2496
- setCurrentDebugFiberInDEV(completedWork);
2497
- let next;
2498
- if (
2499
- !enableProfilerTimer ||
2500
- (completedWork.mode & ProfileMode) === NoMode
2501
- ) {
2502
- next = completeWork(current, completedWork, renderLanes);
2503
- } else {
2504
- startProfilerTimer(completedWork);
2505
- next = completeWork(current, completedWork, renderLanes);
2506
- // Update render duration assuming we didn't error.
2507
- stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
2508
- }
2509
- resetCurrentDebugFiberInDEV();
2510
-
2511
- if (next !== null) {
2512
- // Completing this fiber spawned new work. Work on that next.
2513
- workInProgress = next;
2514
- return;
2515
- }
2516
- } else {
2517
- // This fiber did not complete because something threw. Pop values off
2518
- // the stack without entering the complete phase. If this is a boundary,
2519
- // capture values if possible.
2520
- const next = unwindWork(current, completedWork, renderLanes);
2521
-
2522
- // Because this fiber did not complete, don't reset its lanes.
2523
-
2524
- if (next !== null) {
2525
- // If completing this work spawned new work, do that next. We'll come
2526
- // back here again.
2527
- // Since we're restarting, remove anything that is not a host effect
2528
- // from the effect tag.
2529
- next.flags &= HostEffectMask;
2530
- workInProgress = next;
2531
- return;
2532
- }
2533
-
2534
- if (
2535
- enableProfilerTimer &&
2536
- (completedWork.mode & ProfileMode) !== NoMode
2537
- ) {
2538
- // Record the render duration for the fiber that errored.
2539
- stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
2540
-
2541
- // Include the time spent working on failed children before continuing.
2542
- let actualDuration = completedWork.actualDuration;
2543
- let child = completedWork.child;
2544
- while (child !== null) {
2545
- // $FlowFixMe[unsafe-addition] addition with possible null/undefined value
2546
- actualDuration += child.actualDuration;
2547
- child = child.sibling;
2548
- }
2549
- completedWork.actualDuration = actualDuration;
2550
- }
2551
-
2552
- if (returnFiber !== null) {
2553
- // Mark the parent fiber as incomplete and clear its subtree flags.
2554
- returnFiber.flags |= Incomplete;
2555
- returnFiber.subtreeFlags = NoFlags;
2556
- returnFiber.deletions = null;
2557
- } else {
2558
- // We've unwound all the way to the root.
2559
- workInProgressRootExitStatus = RootDidNotComplete;
2560
- workInProgress = null;
2561
- return;
2562
- }
2563
- }
2564
-
2565
- const siblingFiber = completedWork.sibling;
2566
- if (siblingFiber !== null) {
2567
- // If there is more work to do in this returnFiber, do that next.
2568
- workInProgress = siblingFiber;
2569
- return;
2570
- }
2571
- // Otherwise, return to the parent
2572
- // $FlowFixMe[incompatible-type] we bail out when we get a null
2573
- completedWork = returnFiber;
2574
- // Update the next thing we're working on in case something throws.
2575
- workInProgress = completedWork;
2576
- } while (completedWork !== null);
2577
-
2578
- // We've reached the root.
2579
- if (workInProgressRootExitStatus === RootInProgress) {
2580
- workInProgressRootExitStatus = RootCompleted;
2581
- }
2582
-}
2583
-
2584
-function commitRoot(
2585
- root: FiberRoot,
2586
- recoverableErrors: null | Array<CapturedValue<mixed>>,
2587
- transitions: Array<Transition> | null,
2588
-) {
2589
- // TODO: This no longer makes any sense. We already wrap the mutation and
2590
- // layout phases. Should be able to remove.
2591
- const previousUpdateLanePriority = getCurrentUpdatePriority();
2592
- const prevTransition = ReactCurrentBatchConfig.transition;
2593
-
2594
- try {
2595
- ReactCurrentBatchConfig.transition = null;
2596
- setCurrentUpdatePriority(DiscreteEventPriority);
2597
- commitRootImpl(
2598
- root,
2599
- recoverableErrors,
2600
- transitions,
2601
- previousUpdateLanePriority,
2602
- );
2603
- } finally {
2604
- ReactCurrentBatchConfig.transition = prevTransition;
2605
- setCurrentUpdatePriority(previousUpdateLanePriority);
2606
- }
2607
-
2608
- return null;
2609
-}
2610
-
2611
-function commitRootImpl(
2612
- root: FiberRoot,
2613
- recoverableErrors: null | Array<CapturedValue<mixed>>,
2614
- transitions: Array<Transition> | null,
2615
- renderPriorityLevel: EventPriority,
2616
-) {
2617
- do {
2618
- // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
2619
- // means `flushPassiveEffects` will sometimes result in additional
2620
- // passive effects. So we need to keep flushing in a loop until there are
2621
- // no more pending effects.
2622
- // TODO: Might be better if `flushPassiveEffects` did not automatically
2623
- // flush synchronous work at the end, to avoid factoring hazards like this.
2624
- flushPassiveEffects();
2625
- } while (rootWithPendingPassiveEffects !== null);
2626
- flushRenderPhaseStrictModeWarningsInDEV();
2627
-
2628
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
2629
- throw new Error('Should not already be working.');
2630
- }
2631
-
2632
- const finishedWork = root.finishedWork;
2633
- const lanes = root.finishedLanes;
2634
-
2635
- if (__DEV__) {
2636
- if (enableDebugTracing) {
2637
- logCommitStarted(lanes);
2638
- }
2639
- }
2640
-
2641
- if (enableSchedulingProfiler) {
2642
- markCommitStarted(lanes);
2643
- }
2644
-
2645
- if (finishedWork === null) {
2646
- if (__DEV__) {
2647
- if (enableDebugTracing) {
2648
- logCommitStopped();
2649
- }
2650
- }
2651
-
2652
- if (enableSchedulingProfiler) {
2653
- markCommitStopped();
2654
- }
2655
-
2656
- return null;
2657
- } else {
2658
- if (__DEV__) {
2659
- if (lanes === NoLanes) {
2660
- console.error(
2661
- 'root.finishedLanes should not be empty during a commit. This is a ' +
2662
- 'bug in React.',
2663
- );
2664
- }
2665
- }
2666
- }
2667
- root.finishedWork = null;
2668
- root.finishedLanes = NoLanes;
2669
-
2670
- if (finishedWork === root.current) {
2671
- throw new Error(
2672
- 'Cannot commit the same tree as before. This error is likely caused by ' +
2673
- 'a bug in React. Please file an issue.',
2674
- );
2675
- }
2676
-
2677
- // commitRoot never returns a continuation; it always finishes synchronously.
2678
- // So we can clear these now to allow a new callback to be scheduled.
2679
- root.callbackNode = null;
2680
- root.callbackPriority = NoLane;
2681
-
2682
- // Check which lanes no longer have any work scheduled on them, and mark
2683
- // those as finished.
2684
- let remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
2685
-
2686
- // Make sure to account for lanes that were updated by a concurrent event
2687
- // during the render phase; don't mark them as finished.
2688
- const concurrentlyUpdatedLanes = getConcurrentlyUpdatedLanes();
2689
- remainingLanes = mergeLanes(remainingLanes, concurrentlyUpdatedLanes);
2690
-
2691
- markRootFinished(root, remainingLanes);
2692
-
2693
- if (root === workInProgressRoot) {
2694
- // We can reset these now that they are finished.
2695
- workInProgressRoot = null;
2696
- workInProgress = null;
2697
- workInProgressRootRenderLanes = NoLanes;
2698
- } else {
2699
- // This indicates that the last root we worked on is not the same one that
2700
- // we're committing now. This most commonly happens when a suspended root
2701
- // times out.
2702
- }
2703
-
2704
- // If there are pending passive effects, schedule a callback to process them.
2705
- // Do this as early as possible, so it is queued before anything else that
2706
- // might get scheduled in the commit phase. (See #16714.)
2707
- // TODO: Delete all other places that schedule the passive effect callback
2708
- // They're redundant.
2709
- if (
2710
- (finishedWork.subtreeFlags & PassiveMask) !== NoFlags ||
2711
- (finishedWork.flags & PassiveMask) !== NoFlags
2712
- ) {
2713
- if (!rootDoesHavePassiveEffects) {
2714
- rootDoesHavePassiveEffects = true;
2715
- pendingPassiveEffectsRemainingLanes = remainingLanes;
2716
- // workInProgressTransitions might be overwritten, so we want
2717
- // to store it in pendingPassiveTransitions until they get processed
2718
- // We need to pass this through as an argument to commitRoot
2719
- // because workInProgressTransitions might have changed between
2720
- // the previous render and commit if we throttle the commit
2721
- // with setTimeout
2722
- pendingPassiveTransitions = transitions;
2723
- scheduleCallback(NormalSchedulerPriority, () => {
2724
- flushPassiveEffects();
2725
- // This render triggered passive effects: release the root cache pool
2726
- // *after* passive effects fire to avoid freeing a cache pool that may
2727
- // be referenced by a node in the tree (HostRoot, Cache boundary etc)
2728
- return null;
2729
- });
2730
- }
2731
- }
2732
-
2733
- // Check if there are any effects in the whole tree.
2734
- // TODO: This is left over from the effect list implementation, where we had
2735
- // to check for the existence of `firstEffect` to satisfy Flow. I think the
2736
- // only other reason this optimization exists is because it affects profiling.
2737
- // Reconsider whether this is necessary.
2738
- const subtreeHasEffects =
2739
- (finishedWork.subtreeFlags &
2740
- (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !==
2741
- NoFlags;
2742
- const rootHasEffect =
2743
- (finishedWork.flags &
2744
- (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !==
2745
- NoFlags;
2746
-
2747
- if (subtreeHasEffects || rootHasEffect) {
2748
- const prevTransition = ReactCurrentBatchConfig.transition;
2749
- ReactCurrentBatchConfig.transition = null;
2750
- const previousPriority = getCurrentUpdatePriority();
2751
- setCurrentUpdatePriority(DiscreteEventPriority);
2752
-
2753
- const prevExecutionContext = executionContext;
2754
- executionContext |= CommitContext;
2755
-
2756
- // Reset this to null before calling lifecycles
2757
- ReactCurrentOwner.current = null;
2758
-
2759
- // The commit phase is broken into several sub-phases. We do a separate pass
2760
- // of the effect list for each phase: all mutation effects come before all
2761
- // layout effects, and so on.
2762
-
2763
- // The first phase a "before mutation" phase. We use this phase to read the
2764
- // state of the host tree right before we mutate it. This is where
2765
- // getSnapshotBeforeUpdate is called.
2766
- const shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(
2767
- root,
2768
- finishedWork,
2769
- );
2770
-
2771
- if (enableProfilerTimer) {
2772
- // Mark the current commit time to be shared by all Profilers in this
2773
- // batch. This enables them to be grouped later.
2774
- recordCommitTime();
2775
- }
2776
-
2777
- if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) {
2778
- // Track the root here, rather than in commitLayoutEffects(), because of ref setters.
2779
- // Updates scheduled during ref detachment should also be flagged.
2780
- rootCommittingMutationOrLayoutEffects = root;
2781
- }
2782
-
2783
- // The next phase is the mutation phase, where we mutate the host tree.
2784
- commitMutationEffects(root, finishedWork, lanes);
2785
-
2786
- if (enableCreateEventHandleAPI) {
2787
- if (shouldFireAfterActiveInstanceBlur) {
2788
- afterActiveInstanceBlur();
2789
- }
2790
- }
2791
- resetAfterCommit(root.containerInfo);
2792
-
2793
- // The work-in-progress tree is now the current tree. This must come after
2794
- // the mutation phase, so that the previous tree is still current during
2795
- // componentWillUnmount, but before the layout phase, so that the finished
2796
- // work is current during componentDidMount/Update.
2797
- root.current = finishedWork;
2798
-
2799
- // The next phase is the layout phase, where we call effects that read
2800
- // the host tree after it's been mutated. The idiomatic use case for this is
2801
- // layout, but class component lifecycles also fire here for legacy reasons.
2802
- if (__DEV__) {
2803
- if (enableDebugTracing) {
2804
- logLayoutEffectsStarted(lanes);
2805
- }
2806
- }
2807
- if (enableSchedulingProfiler) {
2808
- markLayoutEffectsStarted(lanes);
2809
- }
2810
- commitLayoutEffects(finishedWork, root, lanes);
2811
- if (__DEV__) {
2812
- if (enableDebugTracing) {
2813
- logLayoutEffectsStopped();
2814
- }
2815
- }
2816
-
2817
- if (enableSchedulingProfiler) {
2818
- markLayoutEffectsStopped();
2819
- }
2820
-
2821
- if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) {
2822
- rootCommittingMutationOrLayoutEffects = null;
2823
- }
2824
-
2825
- // Tell Scheduler to yield at the end of the frame, so the browser has an
2826
- // opportunity to paint.
2827
- requestPaint();
2828
-
2829
- executionContext = prevExecutionContext;
2830
-
2831
- // Reset the priority to the previous non-sync value.
2832
- setCurrentUpdatePriority(previousPriority);
2833
- ReactCurrentBatchConfig.transition = prevTransition;
2834
- } else {
2835
- // No effects.
2836
- root.current = finishedWork;
2837
- // Measure these anyway so the flamegraph explicitly shows that there were
2838
- // no effects.
2839
- // TODO: Maybe there's a better way to report this.
2840
- if (enableProfilerTimer) {
2841
- recordCommitTime();
2842
- }
2843
- }
2844
-
2845
- const rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
2846
-
2847
- if (rootDoesHavePassiveEffects) {
2848
- // This commit has passive effects. Stash a reference to them. But don't
2849
- // schedule a callback until after flushing layout work.
2850
- rootDoesHavePassiveEffects = false;
2851
- rootWithPendingPassiveEffects = root;
2852
- pendingPassiveEffectsLanes = lanes;
2853
- } else {
2854
- // There were no passive effects, so we can immediately release the cache
2855
- // pool for this render.
2856
- releaseRootPooledCache(root, remainingLanes);
2857
- if (__DEV__) {
2858
- nestedPassiveUpdateCount = 0;
2859
- rootWithPassiveNestedUpdates = null;
2860
- }
2861
- }
2862
-
2863
- // Read this again, since an effect might have updated it
2864
- remainingLanes = root.pendingLanes;
2865
-
2866
- // Check if there's remaining work on this root
2867
- // TODO: This is part of the `componentDidCatch` implementation. Its purpose
2868
- // is to detect whether something might have called setState inside
2869
- // `componentDidCatch`. The mechanism is known to be flawed because `setState`
2870
- // inside `componentDidCatch` is itself flawed — that's why we recommend
2871
- // `getDerivedStateFromError` instead. However, it could be improved by
2872
- // checking if remainingLanes includes Sync work, instead of whether there's
2873
- // any work remaining at all (which would also include stuff like Suspense
2874
- // retries or transitions). It's been like this for a while, though, so fixing
2875
- // it probably isn't that urgent.
2876
- if (remainingLanes === NoLanes) {
2877
- // If there's no remaining work, we can clear the set of already failed
2878
- // error boundaries.
2879
- legacyErrorBoundariesThatAlreadyFailed = null;
2880
- }
2881
-
2882
- if (__DEV__) {
2883
- if (!rootDidHavePassiveEffects) {
2884
- commitDoubleInvokeEffectsInDEV(root, false);
2885
- }
2886
- }
2887
-
2888
- onCommitRootDevTools(finishedWork.stateNode, renderPriorityLevel);
2889
-
2890
- if (enableUpdaterTracking) {
2891
- if (isDevToolsPresent) {
2892
- root.memoizedUpdaters.clear();
2893
- }
2894
- }
2895
-
2896
- if (__DEV__) {
2897
- onCommitRootTestSelector();
2898
- }
2899
-
2900
- // Always call this before exiting `commitRoot`, to ensure that any
2901
- // additional work on this root is scheduled.
2902
- ensureRootIsScheduled(root, now());
2903
-
2904
- if (recoverableErrors !== null) {
2905
- // There were errors during this render, but recovered from them without
2906
- // needing to surface it to the UI. We log them here.
2907
- const onRecoverableError = root.onRecoverableError;
2908
- for (let i = 0; i < recoverableErrors.length; i++) {
2909
- const recoverableError = recoverableErrors[i];
2910
- const errorInfo = makeErrorInfo(
2911
- recoverableError.digest,
2912
- recoverableError.stack,
2913
- );
2914
- onRecoverableError(recoverableError.value, errorInfo);
2915
- }
2916
- }
2917
-
2918
- if (hasUncaughtError) {
2919
- hasUncaughtError = false;
2920
- const error = firstUncaughtError;
2921
- firstUncaughtError = null;
2922
- throw error;
2923
- }
2924
-
2925
- // If the passive effects are the result of a discrete render, flush them
2926
- // synchronously at the end of the current task so that the result is
2927
- // immediately observable. Otherwise, we assume that they are not
2928
- // order-dependent and do not need to be observed by external systems, so we
2929
- // can wait until after paint.
2930
- // TODO: We can optimize this by not scheduling the callback earlier. Since we
2931
- // currently schedule the callback in multiple places, will wait until those
2932
- // are consolidated.
2933
- if (includesSyncLane(pendingPassiveEffectsLanes) && root.tag !== LegacyRoot) {
2934
- flushPassiveEffects();
2935
- }
2936
-
2937
- // Read this again, since a passive effect might have updated it
2938
- remainingLanes = root.pendingLanes;
2939
- if (includesSyncLane(remainingLanes)) {
2940
- if (enableProfilerTimer && enableProfilerNestedUpdatePhase) {
2941
- markNestedUpdateScheduled();
2942
- }
2943
-
2944
- // Count the number of times the root synchronously re-renders without
2945
- // finishing. If there are too many, it indicates an infinite update loop.
2946
- if (root === rootWithNestedUpdates) {
2947
- nestedUpdateCount++;
2948
- } else {
2949
- nestedUpdateCount = 0;
2950
- rootWithNestedUpdates = root;
2951
- }
2952
- } else {
2953
- nestedUpdateCount = 0;
2954
- }
2955
-
2956
- // If layout work was scheduled, flush it now.
2957
- flushSyncCallbacks();
2958
-
2959
- if (__DEV__) {
2960
- if (enableDebugTracing) {
2961
- logCommitStopped();
2962
- }
2963
- }
2964
-
2965
- if (enableSchedulingProfiler) {
2966
- markCommitStopped();
2967
- }
2968
-
2969
- if (enableTransitionTracing) {
2970
- // We process transitions during passive effects. However, passive effects can be
2971
- // processed synchronously during the commit phase as well as asynchronously after
2972
- // paint. At the end of the commit phase, we schedule a callback that will be called
2973
- // after the next paint. If the transitions have already been processed (passive
2974
- // effect phase happened synchronously), we will schedule a callback to process
2975
- // the transitions. However, if we don't have any pending transition callbacks, this
2976
- // means that the transitions have yet to be processed (passive effects processed after paint)
2977
- // so we will store the end time of paint so that we can process the transitions
2978
- // and then call the callback via the correct end time.
2979
- const prevRootTransitionCallbacks = root.transitionCallbacks;
2980
- if (prevRootTransitionCallbacks !== null) {
2981
- schedulePostPaintCallback(endTime => {
2982
- const prevPendingTransitionCallbacks = currentPendingTransitionCallbacks;
2983
- if (prevPendingTransitionCallbacks !== null) {
2984
- currentPendingTransitionCallbacks = null;
2985
- scheduleCallback(IdleSchedulerPriority, () => {
2986
- processTransitionCallbacks(
2987
- prevPendingTransitionCallbacks,
2988
- endTime,
2989
- prevRootTransitionCallbacks,
2990
- );
2991
- });
2992
- } else {
2993
- currentEndTime = endTime;
2994
- }
2995
- });
2996
- }
2997
- }
2998
-
2999
- return null;
3000
-}
3001
-
3002
-function makeErrorInfo(digest: ?string, componentStack: ?string) {
3003
- if (__DEV__) {
3004
- const errorInfo = {
3005
- componentStack,
3006
- digest,
3007
- };
3008
- Object.defineProperty(errorInfo, 'digest', {
3009
- configurable: false,
3010
- enumerable: true,
3011
- get() {
3012
- console.error(
3013
- 'You are accessing "digest" from the errorInfo object passed to onRecoverableError.' +
3014
- ' This property is deprecated and will be removed in a future version of React.' +
3015
- ' To access the digest of an Error look for this property on the Error instance itself.',
3016
- );
3017
- return digest;
3018
- },
3019
- });
3020
- return errorInfo;
3021
- } else {
3022
- return {
3023
- digest,
3024
- componentStack,
3025
- };
3026
- }
3027
-}
3028
-
3029
-function releaseRootPooledCache(root: FiberRoot, remainingLanes: Lanes) {
3030
- if (enableCache) {
3031
- const pooledCacheLanes = (root.pooledCacheLanes &= remainingLanes);
3032
- if (pooledCacheLanes === NoLanes) {
3033
- // None of the remaining work relies on the cache pool. Clear it so
3034
- // subsequent requests get a new cache
3035
- const pooledCache = root.pooledCache;
3036
- if (pooledCache != null) {
3037
- root.pooledCache = null;
3038
- releaseCache(pooledCache);
3039
- }
3040
- }
3041
- }
3042
-}
3043
-
3044
-export function flushPassiveEffects(): boolean {
3045
- // Returns whether passive effects were flushed.
3046
- // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should
3047
- // probably just combine the two functions. I believe they were only separate
3048
- // in the first place because we used to wrap it with
3049
- // `Scheduler.runWithPriority`, which accepts a function. But now we track the
3050
- // priority within React itself, so we can mutate the variable directly.
3051
- if (rootWithPendingPassiveEffects !== null) {
3052
- // Cache the root since rootWithPendingPassiveEffects is cleared in
3053
- // flushPassiveEffectsImpl
3054
- const root = rootWithPendingPassiveEffects;
3055
- // Cache and clear the remaining lanes flag; it must be reset since this
3056
- // method can be called from various places, not always from commitRoot
3057
- // where the remaining lanes are known
3058
- const remainingLanes = pendingPassiveEffectsRemainingLanes;
3059
- pendingPassiveEffectsRemainingLanes = NoLanes;
3060
-
3061
- const renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
3062
- const priority = lowerEventPriority(DefaultEventPriority, renderPriority);
3063
- const prevTransition = ReactCurrentBatchConfig.transition;
3064
- const previousPriority = getCurrentUpdatePriority();
3065
-
3066
- try {
3067
- ReactCurrentBatchConfig.transition = null;
3068
- setCurrentUpdatePriority(priority);
3069
- return flushPassiveEffectsImpl();
3070
- } finally {
3071
- setCurrentUpdatePriority(previousPriority);
3072
- ReactCurrentBatchConfig.transition = prevTransition;
3073
-
3074
- // Once passive effects have run for the tree - giving components a
3075
- // chance to retain cache instances they use - release the pooled
3076
- // cache at the root (if there is one)
3077
- releaseRootPooledCache(root, remainingLanes);
3078
- }
3079
- }
3080
- return false;
3081
-}
3082
-
3083
-export function enqueuePendingPassiveProfilerEffect(fiber: Fiber): void {
3084
- if (enableProfilerTimer && enableProfilerCommitHooks) {
3085
- pendingPassiveProfilerEffects.push(fiber);
3086
- if (!rootDoesHavePassiveEffects) {
3087
- rootDoesHavePassiveEffects = true;
3088
- scheduleCallback(NormalSchedulerPriority, () => {
3089
- flushPassiveEffects();
3090
- return null;
3091
- });
3092
- }
3093
- }
3094
-}
3095
-
3096
-function flushPassiveEffectsImpl() {
3097
- if (rootWithPendingPassiveEffects === null) {
3098
- return false;
3099
- }
3100
-
3101
- // Cache and clear the transitions flag
3102
- const transitions = pendingPassiveTransitions;
3103
- pendingPassiveTransitions = null;
3104
-
3105
- const root = rootWithPendingPassiveEffects;
3106
- const lanes = pendingPassiveEffectsLanes;
3107
- rootWithPendingPassiveEffects = null;
3108
- // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects.
3109
- // Figure out why and fix it. It's not causing any known issues (probably
3110
- // because it's only used for profiling), but it's a refactor hazard.
3111
- pendingPassiveEffectsLanes = NoLanes;
3112
-
3113
- if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
3114
- throw new Error('Cannot flush passive effects while already rendering.');
3115
- }
3116
-
3117
- if (__DEV__) {
3118
- isFlushingPassiveEffects = true;
3119
- didScheduleUpdateDuringPassiveEffects = false;
3120
-
3121
- if (enableDebugTracing) {
3122
- logPassiveEffectsStarted(lanes);
3123
- }
3124
- }
3125
-
3126
- if (enableSchedulingProfiler) {
3127
- markPassiveEffectsStarted(lanes);
3128
- }
3129
-
3130
- const prevExecutionContext = executionContext;
3131
- executionContext |= CommitContext;
3132
-
3133
- commitPassiveUnmountEffects(root.current);
3134
- commitPassiveMountEffects(root, root.current, lanes, transitions);
3135
-
3136
- // TODO: Move to commitPassiveMountEffects
3137
- if (enableProfilerTimer && enableProfilerCommitHooks) {
3138
- const profilerEffects = pendingPassiveProfilerEffects;
3139
- pendingPassiveProfilerEffects = [];
3140
- for (let i = 0; i < profilerEffects.length; i++) {
3141
- const fiber = ((profilerEffects[i]: any): Fiber);
3142
- commitPassiveEffectDurations(root, fiber);
3143
- }
3144
- }
3145
-
3146
- if (__DEV__) {
3147
- if (enableDebugTracing) {
3148
- logPassiveEffectsStopped();
3149
- }
3150
- }
3151
-
3152
- if (enableSchedulingProfiler) {
3153
- markPassiveEffectsStopped();
3154
- }
3155
-
3156
- if (__DEV__) {
3157
- commitDoubleInvokeEffectsInDEV(root, true);
3158
- }
3159
-
3160
- executionContext = prevExecutionContext;
3161
-
3162
- flushSyncCallbacks();
3163
-
3164
- if (enableTransitionTracing) {
3165
- const prevPendingTransitionCallbacks = currentPendingTransitionCallbacks;
3166
- const prevRootTransitionCallbacks = root.transitionCallbacks;
3167
- const prevEndTime = currentEndTime;
3168
- if (
3169
- prevPendingTransitionCallbacks !== null &&
3170
- prevRootTransitionCallbacks !== null &&
3171
- prevEndTime !== null
3172
- ) {
3173
- currentPendingTransitionCallbacks = null;
3174
- currentEndTime = null;
3175
- scheduleCallback(IdleSchedulerPriority, () => {
3176
- processTransitionCallbacks(
3177
- prevPendingTransitionCallbacks,
3178
- prevEndTime,
3179
- prevRootTransitionCallbacks,
3180
- );
3181
- });
3182
- }
3183
- }
3184
-
3185
- if (__DEV__) {
3186
- // If additional passive effects were scheduled, increment a counter. If this
3187
- // exceeds the limit, we'll fire a warning.
3188
- if (didScheduleUpdateDuringPassiveEffects) {
3189
- if (root === rootWithPassiveNestedUpdates) {
3190
- nestedPassiveUpdateCount++;
3191
- } else {
3192
- nestedPassiveUpdateCount = 0;
3193
- rootWithPassiveNestedUpdates = root;
3194
- }
3195
- } else {
3196
- nestedPassiveUpdateCount = 0;
3197
- }
3198
- isFlushingPassiveEffects = false;
3199
- didScheduleUpdateDuringPassiveEffects = false;
3200
- }
3201
-
3202
- // TODO: Move to commitPassiveMountEffects
3203
- onPostCommitRootDevTools(root);
3204
- if (enableProfilerTimer && enableProfilerCommitHooks) {
3205
- const stateNode = root.current.stateNode;
3206
- stateNode.effectDuration = 0;
3207
- stateNode.passiveEffectDuration = 0;
3208
- }
3209
-
3210
- return true;
3211
-}
3212
-
3213
-export function isAlreadyFailedLegacyErrorBoundary(instance: mixed): boolean {
3214
- return (
3215
- legacyErrorBoundariesThatAlreadyFailed !== null &&
3216
- legacyErrorBoundariesThatAlreadyFailed.has(instance)
3217
- );
3218
-}
3219
-
3220
-export function markLegacyErrorBoundaryAsFailed(instance: mixed) {
3221
- if (legacyErrorBoundariesThatAlreadyFailed === null) {
3222
- legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
3223
- } else {
3224
- legacyErrorBoundariesThatAlreadyFailed.add(instance);
3225
- }
3226
-}
3227
-
3228
-function prepareToThrowUncaughtError(error: mixed) {
3229
- if (!hasUncaughtError) {
3230
- hasUncaughtError = true;
3231
- firstUncaughtError = error;
3232
- }
3233
-}
3234
-export const onUncaughtError = prepareToThrowUncaughtError;
3235
-
3236
-function captureCommitPhaseErrorOnRoot(
3237
- rootFiber: Fiber,
3238
- sourceFiber: Fiber,
3239
- error: mixed,
3240
-) {
3241
- const errorInfo = createCapturedValueAtFiber(error, sourceFiber);
3242
- const update = createRootErrorUpdate(rootFiber, errorInfo, (SyncLane: Lane));
3243
- const root = enqueueUpdate(rootFiber, update, (SyncLane: Lane));
3244
- const eventTime = requestEventTime();
3245
- if (root !== null) {
3246
- markRootUpdated(root, SyncLane, eventTime);
3247
- ensureRootIsScheduled(root, eventTime);
3248
- }
3249
-}
3250
-
3251
-export function captureCommitPhaseError(
3252
- sourceFiber: Fiber,
3253
- nearestMountedAncestor: Fiber | null,
3254
- error: mixed,
3255
-) {
3256
- if (__DEV__) {
3257
- reportUncaughtErrorInDEV(error);
3258
- setIsRunningInsertionEffect(false);
3259
- }
3260
- if (sourceFiber.tag === HostRoot) {
3261
- // Error was thrown at the root. There is no parent, so the root
3262
- // itself should capture it.
3263
- captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
3264
- return;
3265
- }
3266
-
3267
- let fiber = null;
3268
- if (skipUnmountedBoundaries) {
3269
- fiber = nearestMountedAncestor;
3270
- } else {
3271
- fiber = sourceFiber.return;
3272
- }
3273
-
3274
- while (fiber !== null) {
3275
- if (fiber.tag === HostRoot) {
3276
- captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
3277
- return;
3278
- } else if (fiber.tag === ClassComponent) {
3279
- const ctor = fiber.type;
3280
- const instance = fiber.stateNode;
3281
- if (
3282
- typeof ctor.getDerivedStateFromError === 'function' ||
3283
- (typeof instance.componentDidCatch === 'function' &&
3284
- !isAlreadyFailedLegacyErrorBoundary(instance))
3285
- ) {
3286
- const errorInfo = createCapturedValueAtFiber(error, sourceFiber);
3287
- const update = createClassErrorUpdate(
3288
- fiber,
3289
- errorInfo,
3290
- (SyncLane: Lane),
3291
- );
3292
- const root = enqueueUpdate(fiber, update, (SyncLane: Lane));
3293
- const eventTime = requestEventTime();
3294
- if (root !== null) {
3295
- markRootUpdated(root, SyncLane, eventTime);
3296
- ensureRootIsScheduled(root, eventTime);
3297
- }
3298
- return;
3299
- }
3300
- }
3301
- fiber = fiber.return;
3302
- }
3303
-
3304
- if (__DEV__) {
3305
- // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning
3306
- // will fire for errors that are thrown by destroy functions inside deleted
3307
- // trees. What it should instead do is propagate the error to the parent of
3308
- // the deleted tree. In the meantime, do not add this warning to the
3309
- // allowlist; this is only for our internal use.
3310
- console.error(
3311
- 'Internal React error: Attempted to capture a commit phase error ' +
3312
- 'inside a detached tree. This indicates a bug in React. Likely ' +
3313
- 'causes include deleting the same fiber more than once, committing an ' +
3314
- 'already-finished tree, or an inconsistent return pointer.\n\n' +
3315
- 'Error message:\n\n%s',
3316
- error,
3317
- );
3318
- }
3319
-}
3320
-
3321
-export function attachPingListener(
3322
- root: FiberRoot,
3323
- wakeable: Wakeable,
3324
- lanes: Lanes,
3325
-) {
3326
- // Attach a ping listener
3327
- //
3328
- // The data might resolve before we have a chance to commit the fallback. Or,
3329
- // in the case of a refresh, we'll never commit a fallback. So we need to
3330
- // attach a listener now. When it resolves ("pings"), we can decide whether to
3331
- // try rendering the tree again.
3332
- //
3333
- // Only attach a listener if one does not already exist for the lanes
3334
- // we're currently rendering (which acts like a "thread ID" here).
3335
- //
3336
- // We only need to do this in concurrent mode. Legacy Suspense always
3337
- // commits fallbacks synchronously, so there are no pings.
3338
- let pingCache = root.pingCache;
3339
- let threadIDs;
3340
- if (pingCache === null) {
3341
- pingCache = root.pingCache = new PossiblyWeakMap();
3342
- threadIDs = new Set();
3343
- pingCache.set(wakeable, threadIDs);
3344
- } else {
3345
- threadIDs = pingCache.get(wakeable);
3346
- if (threadIDs === undefined) {
3347
- threadIDs = new Set();
3348
- pingCache.set(wakeable, threadIDs);
3349
- }
3350
- }
3351
- if (!threadIDs.has(lanes)) {
3352
- workInProgressRootDidAttachPingListener = true;
3353
-
3354
- // Memoize using the thread ID to prevent redundant listeners.
3355
- threadIDs.add(lanes);
3356
- const ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);
3357
- if (enableUpdaterTracking) {
3358
- if (isDevToolsPresent) {
3359
- // If we have pending work still, restore the original updaters
3360
- restorePendingUpdaters(root, lanes);
3361
- }
3362
- }
3363
- wakeable.then(ping, ping);
3364
- }
3365
-}
3366
-
3367
-function pingSuspendedRoot(
3368
- root: FiberRoot,
3369
- wakeable: Wakeable,
3370
- pingedLanes: Lanes,
3371
-) {
3372
- const pingCache = root.pingCache;
3373
- if (pingCache !== null) {
3374
- // The wakeable resolved, so we no longer need to memoize, because it will
3375
- // never be thrown again.
3376
- pingCache.delete(wakeable);
3377
- }
3378
-
3379
- const eventTime = requestEventTime();
3380
- markRootPinged(root, pingedLanes, eventTime);
3381
-
3382
- warnIfSuspenseResolutionNotWrappedWithActDEV(root);
3383
-
3384
- if (
3385
- workInProgressRoot === root &&
3386
- isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)
3387
- ) {
3388
- // Received a ping at the same priority level at which we're currently
3389
- // rendering. We might want to restart this render. This should mirror
3390
- // the logic of whether or not a root suspends once it completes.
3391
- // TODO: If we're rendering sync either due to Sync, Batched or expired,
3392
- // we should probably never restart.
3393
-
3394
- // If we're suspended with delay, or if it's a retry, we'll always suspend
3395
- // so we can always restart.
3396
- if (
3397
- workInProgressRootExitStatus === RootSuspendedWithDelay ||
3398
- (workInProgressRootExitStatus === RootSuspended &&
3399
- includesOnlyRetries(workInProgressRootRenderLanes) &&
3400
- now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS)
3401
- ) {
3402
- // Restart from the root.
3403
- prepareFreshStack(root, NoLanes);
3404
- } else {
3405
- // Even though we can't restart right now, we might get an
3406
- // opportunity later. So we mark this render as having a ping.
3407
- workInProgressRootPingedLanes = mergeLanes(
3408
- workInProgressRootPingedLanes,
3409
- pingedLanes,
3410
- );
3411
- }
3412
- }
3413
-
3414
- ensureRootIsScheduled(root, eventTime);
3415
-}
3416
-
3417
-function retryTimedOutBoundary(boundaryFiber: Fiber, retryLane: Lane) {
3418
- // The boundary fiber (a Suspense component or SuspenseList component)
3419
- // previously was rendered in its fallback state. One of the promises that
3420
- // suspended it has resolved, which means at least part of the tree was
3421
- // likely unblocked. Try rendering again, at a new lanes.
3422
- if (retryLane === NoLane) {
3423
- // TODO: Assign this to `suspenseState.retryLane`? to avoid
3424
- // unnecessary entanglement?
3425
- retryLane = requestRetryLane(boundaryFiber);
3426
- }
3427
- // TODO: Special case idle priority?
3428
- const eventTime = requestEventTime();
3429
- const root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
3430
- if (root !== null) {
3431
- markRootUpdated(root, retryLane, eventTime);
3432
- ensureRootIsScheduled(root, eventTime);
3433
- }
3434
-}
3435
-
3436
-export function retryDehydratedSuspenseBoundary(boundaryFiber: Fiber) {
3437
- const suspenseState: null | SuspenseState = boundaryFiber.memoizedState;
3438
- let retryLane = NoLane;
3439
- if (suspenseState !== null) {
3440
- retryLane = suspenseState.retryLane;
3441
- }
3442
- retryTimedOutBoundary(boundaryFiber, retryLane);
3443
-}
3444
-
3445
-export function resolveRetryWakeable(boundaryFiber: Fiber, wakeable: Wakeable) {
3446
- let retryLane = NoLane; // Default
3447
- let retryCache: WeakSet<Wakeable> | Set<Wakeable> | null;
3448
- switch (boundaryFiber.tag) {
3449
- case SuspenseComponent:
3450
- retryCache = boundaryFiber.stateNode;
3451
- const suspenseState: null | SuspenseState = boundaryFiber.memoizedState;
3452
- if (suspenseState !== null) {
3453
- retryLane = suspenseState.retryLane;
3454
- }
3455
- break;
3456
- case SuspenseListComponent:
3457
- retryCache = boundaryFiber.stateNode;
3458
- break;
3459
- case OffscreenComponent: {
3460
- const instance: OffscreenInstance = boundaryFiber.stateNode;
3461
- // $FlowFixMe[incompatible-type] found when upgrading Flow
3462
- retryCache = instance._retryCache;
3463
- break;
3464
- }
3465
- default:
3466
- throw new Error(
3467
- 'Pinged unknown suspense boundary type. ' +
3468
- 'This is probably a bug in React.',
3469
- );
3470
- }
3471
-
3472
- if (retryCache !== null) {
3473
- // The wakeable resolved, so we no longer need to memoize, because it will
3474
- // never be thrown again.
3475
- retryCache.delete(wakeable);
3476
- }
3477
-
3478
- retryTimedOutBoundary(boundaryFiber, retryLane);
3479
-}
3480
-
3481
-// Computes the next Just Noticeable Difference (JND) boundary.
3482
-// The theory is that a person can't tell the difference between small differences in time.
3483
-// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
3484
-// difference in the experience. However, waiting for longer might mean that we can avoid
3485
-// showing an intermediate loading state. The longer we have already waited, the harder it
3486
-// is to tell small differences in time. Therefore, the longer we've already waited,
3487
-// the longer we can wait additionally. At some point we have to give up though.
3488
-// We pick a train model where the next boundary commits at a consistent schedule.
3489
-// These particular numbers are vague estimates. We expect to adjust them based on research.
3490
-function jnd(timeElapsed: number) {
3491
- return timeElapsed < 120
3492
- ? 120
3493
- : timeElapsed < 480
3494
- ? 480
3495
- : timeElapsed < 1080
3496
- ? 1080
3497
- : timeElapsed < 1920
3498
- ? 1920
3499
- : timeElapsed < 3000
3500
- ? 3000
3501
- : timeElapsed < 4320
3502
- ? 4320
3503
- : ceil(timeElapsed / 1960) * 1960;
3504
-}
3505
-
3506
-export function throwIfInfiniteUpdateLoopDetected() {
3507
- if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
3508
- nestedUpdateCount = 0;
3509
- nestedPassiveUpdateCount = 0;
3510
- rootWithNestedUpdates = null;
3511
- rootWithPassiveNestedUpdates = null;
3512
-
3513
- throw new Error(
3514
- 'Maximum update depth exceeded. This can happen when a component ' +
3515
- 'repeatedly calls setState inside componentWillUpdate or ' +
3516
- 'componentDidUpdate. React limits the number of nested updates to ' +
3517
- 'prevent infinite loops.',
3518
- );
3519
- }
3520
-
3521
- if (__DEV__) {
3522
- if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
3523
- nestedPassiveUpdateCount = 0;
3524
- rootWithPassiveNestedUpdates = null;
3525
-
3526
- console.error(
3527
- 'Maximum update depth exceeded. This can happen when a component ' +
3528
- "calls setState inside useEffect, but useEffect either doesn't " +
3529
- 'have a dependency array, or one of the dependencies changes on ' +
3530
- 'every render.',
3531
- );
3532
- }
3533
- }
3534
-}
3535
-
3536
-function flushRenderPhaseStrictModeWarningsInDEV() {
3537
- if (__DEV__) {
3538
- ReactStrictModeWarnings.flushLegacyContextWarning();
3539
-
3540
- if (warnAboutDeprecatedLifecycles) {
3541
- ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
3542
- }
3543
- }
3544
-}
3545
-
3546
-function recursivelyTraverseAndDoubleInvokeEffectsInDEV(
3547
- root: FiberRoot,
3548
- parentFiber: Fiber,
3549
- isInStrictMode: boolean,
3550
-) {
3551
- if ((parentFiber.subtreeFlags & (PlacementDEV | Visibility)) === NoFlags) {
3552
- // Parent's descendants have already had effects double invoked.
3553
- // Early exit to avoid unnecessary tree traversal.
3554
- return;
3555
- }
3556
- let child = parentFiber.child;
3557
- while (child !== null) {
3558
- doubleInvokeEffectsInDEVIfNecessary(root, child, isInStrictMode);
3559
- child = child.sibling;
3560
- }
3561
-}
3562
-
3563
-// Unconditionally disconnects and connects passive and layout effects.
3564
-function doubleInvokeEffectsOnFiber(root: FiberRoot, fiber: Fiber) {
3565
- disappearLayoutEffects(fiber);
3566
- disconnectPassiveEffect(fiber);
3567
- reappearLayoutEffects(root, fiber.alternate, fiber, false);
3568
- reconnectPassiveEffects(root, fiber, NoLanes, null, false);
3569
-}
3570
-
3571
-function doubleInvokeEffectsInDEVIfNecessary(
3572
- root: FiberRoot,
3573
- fiber: Fiber,
3574
- parentIsInStrictMode: boolean,
3575
-) {
3576
- const isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE;
3577
- const isInStrictMode = parentIsInStrictMode || isStrictModeFiber;
3578
-
3579
- // First case: the fiber **is not** of type OffscreenComponent. No
3580
- // special rules apply to double invoking effects.
3581
- if (fiber.tag !== OffscreenComponent) {
3582
- if (fiber.flags & PlacementDEV) {
3583
- setCurrentDebugFiberInDEV(fiber);
3584
- if (isInStrictMode) {
3585
- doubleInvokeEffectsOnFiber(root, fiber);
3586
- }
3587
- resetCurrentDebugFiberInDEV();
3588
- } else {
3589
- recursivelyTraverseAndDoubleInvokeEffectsInDEV(
3590
- root,
3591
- fiber,
3592
- isInStrictMode,
3593
- );
3594
- }
3595
- return;
3596
- }
3597
-
3598
- // Second case: the fiber **is** of type OffscreenComponent.
3599
- // This branch contains cases specific to Offscreen.
3600
- if (fiber.memoizedState === null) {
3601
- // Only consider Offscreen that is visible.
3602
- // TODO (Offscreen) Handle manual mode.
3603
- setCurrentDebugFiberInDEV(fiber);
3604
- if (isInStrictMode && fiber.flags & Visibility) {
3605
- // Double invoke effects on Offscreen's subtree only
3606
- // if it is visible and its visibility has changed.
3607
- doubleInvokeEffectsOnFiber(root, fiber);
3608
- } else if (fiber.subtreeFlags & PlacementDEV) {
3609
- // Something in the subtree could have been suspended.
3610
- // We need to continue traversal and find newly inserted fibers.
3611
- recursivelyTraverseAndDoubleInvokeEffectsInDEV(
3612
- root,
3613
- fiber,
3614
- isInStrictMode,
3615
- );
3616
- }
3617
- resetCurrentDebugFiberInDEV();
3618
- }
3619
-}
3620
-
3621
-function commitDoubleInvokeEffectsInDEV(
3622
- root: FiberRoot,
3623
- hasPassiveEffects: boolean,
3624
-) {
3625
- if (__DEV__) {
3626
- if (useModernStrictMode) {
3627
- let doubleInvokeEffects = true;
3628
-
3629
- if (root.tag === LegacyRoot && !(root.current.mode & StrictLegacyMode)) {
3630
- doubleInvokeEffects = false;
3631
- }
3632
- if (
3633
- root.tag === ConcurrentRoot &&
3634
- !(root.current.mode & (StrictLegacyMode | StrictEffectsMode))
3635
- ) {
3636
- doubleInvokeEffects = false;
3637
- }
3638
- recursivelyTraverseAndDoubleInvokeEffectsInDEV(
3639
- root,
3640
- root.current,
3641
- doubleInvokeEffects,
3642
- );
3643
- } else {
3644
- legacyCommitDoubleInvokeEffectsInDEV(root.current, hasPassiveEffects);
3645
- }
3646
- }
3647
-}
3648
-
3649
-function legacyCommitDoubleInvokeEffectsInDEV(
3650
- fiber: Fiber,
3651
- hasPassiveEffects: boolean,
3652
-) {
3653
- // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects
3654
- // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level.
3655
- // Maybe not a big deal since this is DEV only behavior.
3656
-
3657
- setCurrentDebugFiberInDEV(fiber);
3658
- invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);
3659
- if (hasPassiveEffects) {
3660
- invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
3661
- }
3662
-
3663
- invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);
3664
- if (hasPassiveEffects) {
3665
- invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
3666
- }
3667
- resetCurrentDebugFiberInDEV();
3668
-}
3669
-
3670
-function invokeEffectsInDev(
3671
- firstChild: Fiber,
3672
- fiberFlags: Flags,
3673
- invokeEffectFn: (fiber: Fiber) => void,
3674
-) {
3675
- let current: null | Fiber = firstChild;
3676
- let subtreeRoot = null;
3677
- while (current != null) {
3678
- const primarySubtreeFlag = current.subtreeFlags & fiberFlags;
3679
- if (
3680
- current !== subtreeRoot &&
3681
- current.child != null &&
3682
- primarySubtreeFlag !== NoFlags
3683
- ) {
3684
- current = current.child;
3685
- } else {
3686
- if ((current.flags & fiberFlags) !== NoFlags) {
3687
- invokeEffectFn(current);
3688
- }
3689
-
3690
- if (current.sibling !== null) {
3691
- current = current.sibling;
3692
- } else {
3693
- current = subtreeRoot = current.return;
3694
- }
3695
- }
3696
- }
3697
-}
3698
-
3699
-let didWarnStateUpdateForNotYetMountedComponent: Set<string> | null = null;
3700
-export function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber: Fiber) {
3701
- if (__DEV__) {
3702
- if ((executionContext & RenderContext) !== NoContext) {
3703
- // We let the other warning about render phase updates deal with this one.
3704
- return;
3705
- }
3706
-
3707
- if (!(fiber.mode & ConcurrentMode)) {
3708
- return;
3709
- }
3710
-
3711
- const tag = fiber.tag;
3712
- if (
3713
- tag !== IndeterminateComponent &&
3714
- tag !== HostRoot &&
3715
- tag !== ClassComponent &&
3716
- tag !== FunctionComponent &&
3717
- tag !== ForwardRef &&
3718
- tag !== MemoComponent &&
3719
- tag !== SimpleMemoComponent
3720
- ) {
3721
- // Only warn for user-defined components, not internal ones like Suspense.
3722
- return;
3723
- }
3724
-
3725
- // We show the whole stack but dedupe on the top component's name because
3726
- // the problematic code almost always lies inside that component.
3727
- const componentName = getComponentNameFromFiber(fiber) || 'ReactComponent';
3728
- if (didWarnStateUpdateForNotYetMountedComponent !== null) {
3729
- if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
3730
- return;
3731
- }
3732
- // $FlowFixMe[incompatible-use] found when upgrading Flow
3733
- didWarnStateUpdateForNotYetMountedComponent.add(componentName);
3734
- } else {
3735
- didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
3736
- }
3737
-
3738
- const previousFiber = ReactCurrentFiberCurrent;
3739
- try {
3740
- setCurrentDebugFiberInDEV(fiber);
3741
- console.error(
3742
- "Can't perform a React state update on a component that hasn't mounted yet. " +
3743
- 'This indicates that you have a side-effect in your render function that ' +
3744
- 'asynchronously later calls tries to update the component. Move this work to ' +
3745
- 'useEffect instead.',
3746
- );
3747
- } finally {
3748
- if (previousFiber) {
3749
- setCurrentDebugFiberInDEV(fiber);
3750
- } else {
3751
- resetCurrentDebugFiberInDEV();
3752
- }
3753
- }
3754
- }
3755
-}
3756
-
3757
-let beginWork;
3758
-if (__DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
3759
- const dummyFiber = null;
3760
- beginWork = (current, unitOfWork, lanes) => {
3761
- // If a component throws an error, we replay it again in a synchronously
3762
- // dispatched event, so that the debugger will treat it as an uncaught
3763
- // error See ReactErrorUtils for more information.
3764
-
3765
- // Before entering the begin phase, copy the work-in-progress onto a dummy
3766
- // fiber. If beginWork throws, we'll use this to reset the state.
3767
- const originalWorkInProgressCopy = assignFiberPropertiesInDEV(
3768
- dummyFiber,
3769
- unitOfWork,
3770
- );
3771
- try {
3772
- return originalBeginWork(current, unitOfWork, lanes);
3773
- } catch (originalError) {
3774
- if (
3775
- didSuspendOrErrorWhileHydratingDEV() ||
3776
- originalError === SuspenseException ||
3777
- (originalError !== null &&
3778
- typeof originalError === 'object' &&
3779
- typeof originalError.then === 'function')
3780
- ) {
3781
- // Don't replay promises.
3782
- // Don't replay errors if we are hydrating and have already suspended or handled an error
3783
- throw originalError;
3784
- }
3785
-
3786
- // Don't reset current debug fiber, since we're about to work on the
3787
- // same fiber again.
3788
-
3789
- // Unwind the failed stack frame
3790
- resetSuspendedWorkLoopOnUnwind();
3791
- unwindInterruptedWork(current, unitOfWork, workInProgressRootRenderLanes);
3792
-
3793
- // Restore the original properties of the fiber.
3794
- assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
3795
-
3796
- if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
3797
- // Reset the profiler timer.
3798
- startProfilerTimer(unitOfWork);
3799
- }
3800
-
3801
- // Run beginWork again.
3802
- invokeGuardedCallback(
3803
- null,
3804
- originalBeginWork,
3805
- null,
3806
- current,
3807
- unitOfWork,
3808
- lanes,
3809
- );
3810
-
3811
- if (hasCaughtError()) {
3812
- const replayError = clearCaughtError();
3813
- if (
3814
- typeof replayError === 'object' &&
3815
- replayError !== null &&
3816
- replayError._suppressLogging &&
3817
- typeof originalError === 'object' &&
3818
- originalError !== null &&
3819
- !originalError._suppressLogging
3820
- ) {
3821
- // If suppressed, let the flag carry over to the original error which is the one we'll rethrow.
3822
- originalError._suppressLogging = true;
3823
- }
3824
- }
3825
- // We always throw the original error in case the second render pass is not idempotent.
3826
- // This can happen if a memoized function or CommonJS module doesn't throw after first invocation.
3827
- throw originalError;
3828
- }
3829
- };
3830
-} else {
3831
- beginWork = originalBeginWork;
3832
-}
3833
-
3834
-let didWarnAboutUpdateInRender = false;
3835
-let didWarnAboutUpdateInRenderForAnotherComponent;
3836
-if (__DEV__) {
3837
- didWarnAboutUpdateInRenderForAnotherComponent = new Set();
3838
-}
3839
-
3840
-function warnAboutRenderPhaseUpdatesInDEV(fiber) {
3841
- if (__DEV__) {
3842
- if (ReactCurrentDebugFiberIsRenderingInDEV) {
3843
- switch (fiber.tag) {
3844
- case FunctionComponent:
3845
- case ForwardRef:
3846
- case SimpleMemoComponent: {
3847
- const renderingComponentName =
3848
- (workInProgress && getComponentNameFromFiber(workInProgress)) ||
3849
- 'Unknown';
3850
- // Dedupe by the rendering component because it's the one that needs to be fixed.
3851
- const dedupeKey = renderingComponentName;
3852
- if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
3853
- didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
3854
- const setStateComponentName =
3855
- getComponentNameFromFiber(fiber) || 'Unknown';
3856
- console.error(
3857
- 'Cannot update a component (`%s`) while rendering a ' +
3858
- 'different component (`%s`). To locate the bad setState() call inside `%s`, ' +
3859
- 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render',
3860
- setStateComponentName,
3861
- renderingComponentName,
3862
- renderingComponentName,
3863
- );
3864
- }
3865
- break;
3866
- }
3867
- case ClassComponent: {
3868
- if (!didWarnAboutUpdateInRender) {
3869
- console.error(
3870
- 'Cannot update during an existing state transition (such as ' +
3871
- 'within `render`). Render methods should be a pure ' +
3872
- 'function of props and state.',
3873
- );
3874
- didWarnAboutUpdateInRender = true;
3875
- }
3876
- break;
3877
- }
3878
- }
3879
- }
3880
- }
3881
-}
3882
-
3883
-export function restorePendingUpdaters(root: FiberRoot, lanes: Lanes): void {
3884
- if (enableUpdaterTracking) {
3885
- if (isDevToolsPresent) {
3886
- const memoizedUpdaters = root.memoizedUpdaters;
3887
- memoizedUpdaters.forEach(schedulingFiber => {
3888
- addFiberToLanesMap(root, schedulingFiber, lanes);
3889
- });
3890
-
3891
- // This function intentionally does not clear memoized updaters.
3892
- // Those may still be relevant to the current commit
3893
- // and a future one (e.g. Suspense).
3894
- }
3895
- }
3896
-}
3897
-
3898
-const fakeActCallbackNode = {};
3899
-function scheduleCallback(priorityLevel, callback) {
3900
- if (__DEV__) {
3901
- // If we're currently inside an `act` scope, bypass Scheduler and push to
3902
- // the `act` queue instead.
3903
- const actQueue = ReactCurrentActQueue.current;
3904
- if (actQueue !== null) {
3905
- actQueue.push(callback);
3906
- return fakeActCallbackNode;
3907
- } else {
3908
- return Scheduler_scheduleCallback(priorityLevel, callback);
3909
- }
3910
- } else {
3911
- // In production, always call Scheduler. This function will be stripped out.
3912
- return Scheduler_scheduleCallback(priorityLevel, callback);
3913
- }
3914
-}
3915
-
3916
-function cancelCallback(callbackNode) {
3917
- if (__DEV__ && callbackNode === fakeActCallbackNode) {
3918
- return;
3919
- }
3920
- // In production, always call Scheduler. This function will be stripped out.
3921
- return Scheduler_cancelCallback(callbackNode);
3922
-}
3923
-
3924
-function shouldForceFlushFallbacksInDEV() {
3925
- // Never force flush in production. This function should get stripped out.
3926
- return __DEV__ && ReactCurrentActQueue.current !== null;
3927
-}
3928
-
3929
-function warnIfUpdatesNotWrappedWithActDEV(fiber: Fiber): void {
3930
- if (__DEV__) {
3931
- if (fiber.mode & ConcurrentMode) {
3932
- if (!isConcurrentActEnvironment()) {
3933
- // Not in an act environment. No need to warn.
3934
- return;
3935
- }
3936
- } else {
3937
- // Legacy mode has additional cases where we suppress a warning.
3938
- if (!isLegacyActEnvironment(fiber)) {
3939
- // Not in an act environment. No need to warn.
3940
- return;
3941
- }
3942
- if (executionContext !== NoContext) {
3943
- // Legacy mode doesn't warn if the update is batched, i.e.
3944
- // batchedUpdates or flushSync.
3945
- return;
3946
- }
3947
- if (
3948
- fiber.tag !== FunctionComponent &&
3949
- fiber.tag !== ForwardRef &&
3950
- fiber.tag !== SimpleMemoComponent
3951
- ) {
3952
- // For backwards compatibility with pre-hooks code, legacy mode only
3953
- // warns for updates that originate from a hook.
3954
- return;
3955
- }
3956
- }
3957
-
3958
- if (ReactCurrentActQueue.current === null) {
3959
- const previousFiber = ReactCurrentFiberCurrent;
3960
- try {
3961
- setCurrentDebugFiberInDEV(fiber);
3962
- console.error(
3963
- 'An update to %s inside a test was not wrapped in act(...).\n\n' +
3964
- 'When testing, code that causes React state updates should be ' +
3965
- 'wrapped into act(...):\n\n' +
3966
- 'act(() => {\n' +
3967
- ' /* fire events that update state */\n' +
3968
- '});\n' +
3969
- '/* assert on the output */\n\n' +
3970
- "This ensures that you're testing the behavior the user would see " +
3971
- 'in the browser.' +
3972
- ' Learn more at https://reactjs.org/link/wrap-tests-with-act',
3973
- getComponentNameFromFiber(fiber),
3974
- );
3975
- } finally {
3976
- if (previousFiber) {
3977
- setCurrentDebugFiberInDEV(fiber);
3978
- } else {
3979
- resetCurrentDebugFiberInDEV();
3980
- }
3981
- }
3982
- }
3983
- }
3984
-}
3985
-
3986
-function warnIfSuspenseResolutionNotWrappedWithActDEV(root: FiberRoot): void {
3987
- if (__DEV__) {
3988
- if (
3989
- root.tag !== LegacyRoot &&
3990
- isConcurrentActEnvironment() &&
3991
- ReactCurrentActQueue.current === null
3992
- ) {
3993
- console.error(
3994
- 'A suspended resource finished loading inside a test, but the event ' +
3995
- 'was not wrapped in act(...).\n\n' +
3996
- 'When testing, code that resolves suspended data should be wrapped ' +
3997
- 'into act(...):\n\n' +
3998
- 'act(() => {\n' +
3999
- ' /* finish loading suspended data */\n' +
4000
- '});\n' +
4001
- '/* assert on the output */\n\n' +
4002
- "This ensures that you're testing the behavior the user would see " +
4003
- 'in the browser.' +
4004
- ' Learn more at https://reactjs.org/link/wrap-tests-with-act',
4005
- );
4006
- }
4007
- }
4008
-}
4009
-
4010
-export function setIsRunningInsertionEffect(isRunning: boolean): void {
4011
- if (__DEV__) {
4012
- isRunningInsertionEffect = isRunning;
4013
- }
4014
-}
packages/react-reconciler/src/ReactFiberWorkLoop.old.js
+4
-1
@@ -176,7 +176,10 @@ import {
176
lowerEventPriority,
177
lanesToEventPriority,
178
} from './ReactEventPriorities.old';
179
-import {requestCurrentTransition, NoTransition} from './ReactFiberTransition';
179
+import {
180
+ requestCurrentTransition,
181
+ NoTransition,
182
+} from './ReactFiberTransition.old';
183
import {
184
SelectiveHydrationException,
185
beginWork as originalBeginWork,
packages/react-reconciler/src/ReactInternalTypes.js
+2
-6
@@ -31,13 +31,11 @@ import type {
31
SuspenseInstance,
32
} from './ReactFiberHostConfig';
33
import type {Cache} from './ReactFiberCacheComponent.old';
34
-// Doing this because there's a merge conflict because of the way sync-reconciler-fork
35
-// is implemented
34
import type {
35
TracingMarkerInstance,
36
Transition,
39
-} from './ReactFiberTracingMarkerComponent.new';
40
-import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates.new';
37
+} from './ReactFiberTracingMarkerComponent.old';
38
+import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates.old';
39
40
// Unwind Circular: moved from ReactFiberHooks.old
41
export type HookType =
@@ -416,8 +414,6 @@ export type Dispatcher = {
414
useId(): string,
415
useCacheRefresh?: () => <T>(?() => T, ?T) => void,
416
useMemoCache?: (size: number) => Array<any>,
419
-
420
- unstable_isNewReconciler?: boolean,
417
};
418
419
export type CacheDispatcher = {
packages/react-reconciler/src/ReactMutableSource.new.js
deleted
-108
@@ -1,108 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {MutableSource, MutableSourceVersion} from 'shared/ReactTypes';
11
-import type {FiberRoot} from './ReactInternalTypes';
12
-
13
-import {isPrimaryRenderer} from './ReactFiberHostConfig';
14
-
15
-// Work in progress version numbers only apply to a single render,
16
-// and should be reset before starting a new render.
17
-// This tracks which mutable sources need to be reset after a render.
18
-const workInProgressSources: Array<MutableSource<any>> = [];
19
-
20
-let rendererSigil;
21
-if (__DEV__) {
22
- // Used to detect multiple renderers using the same mutable source.
23
- rendererSigil = {};
24
-}
25
-
26
-export function markSourceAsDirty(mutableSource: MutableSource<any>): void {
27
- workInProgressSources.push(mutableSource);
28
-}
29
-
30
-export function resetWorkInProgressVersions(): void {
31
- for (let i = 0; i < workInProgressSources.length; i++) {
32
- const mutableSource = workInProgressSources[i];
33
- if (isPrimaryRenderer) {
34
- mutableSource._workInProgressVersionPrimary = null;
35
- } else {
36
- mutableSource._workInProgressVersionSecondary = null;
37
- }
38
- }
39
- workInProgressSources.length = 0;
40
-}
41
-
42
-export function getWorkInProgressVersion(
43
- mutableSource: MutableSource<any>,
44
-): null | MutableSourceVersion {
45
- if (isPrimaryRenderer) {
46
- return mutableSource._workInProgressVersionPrimary;
47
- } else {
48
- return mutableSource._workInProgressVersionSecondary;
49
- }
50
-}
51
-
52
-export function setWorkInProgressVersion(
53
- mutableSource: MutableSource<any>,
54
- version: MutableSourceVersion,
55
-): void {
56
- if (isPrimaryRenderer) {
57
- mutableSource._workInProgressVersionPrimary = version;
58
- } else {
59
- mutableSource._workInProgressVersionSecondary = version;
60
- }
61
- workInProgressSources.push(mutableSource);
62
-}
63
-
64
-export function warnAboutMultipleRenderersDEV(
65
- mutableSource: MutableSource<any>,
66
-): void {
67
- if (__DEV__) {
68
- if (isPrimaryRenderer) {
69
- if (mutableSource._currentPrimaryRenderer == null) {
70
- mutableSource._currentPrimaryRenderer = rendererSigil;
71
- } else if (mutableSource._currentPrimaryRenderer !== rendererSigil) {
72
- console.error(
73
- 'Detected multiple renderers concurrently rendering the ' +
74
- 'same mutable source. This is currently unsupported.',
75
- );
76
- }
77
- } else {
78
- if (mutableSource._currentSecondaryRenderer == null) {
79
- mutableSource._currentSecondaryRenderer = rendererSigil;
80
- } else if (mutableSource._currentSecondaryRenderer !== rendererSigil) {
81
- console.error(
82
- 'Detected multiple renderers concurrently rendering the ' +
83
- 'same mutable source. This is currently unsupported.',
84
- );
85
- }
86
- }
87
- }
88
-}
89
-
90
-// Eager reads the version of a mutable source and stores it on the root.
91
-// This ensures that the version used for server rendering matches the one
92
-// that is eventually read during hydration.
93
-// If they don't match there's a potential tear and a full deopt render is required.
94
-export function registerMutableSourceForHydration(
95
- root: FiberRoot,
96
- mutableSource: MutableSource<any>,
97
-): void {
98
- const getVersion = mutableSource._getVersion;
99
- const version = getVersion(mutableSource._source);
100
-
101
- // TODO Clear this data once all pending hydration work is finished.
102
- // Retaining it forever may interfere with GC.
103
- if (root.mutableSourceEagerHydrationData == null) {
104
- root.mutableSourceEagerHydrationData = [mutableSource, version];
105
- } else {
106
- root.mutableSourceEagerHydrationData.push(mutableSource, version);
107
- }
108
-}
packages/react-reconciler/src/ReactProfilerTimer.new.js
deleted
-240
@@ -1,240 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-
12
-import {
13
- enableProfilerCommitHooks,
14
- enableProfilerNestedUpdatePhase,
15
- enableProfilerTimer,
16
-} from 'shared/ReactFeatureFlags';
17
-import {HostRoot, Profiler} from './ReactWorkTags';
18
-
19
-// Intentionally not named imports because Rollup would use dynamic dispatch for
20
-// CommonJS interop named imports.
21
-import * as Scheduler from 'scheduler';
22
-
23
-const {unstable_now: now} = Scheduler;
24
-
25
-export type ProfilerTimer = {
26
- getCommitTime(): number,
27
- isCurrentUpdateNested(): boolean,
28
- markNestedUpdateScheduled(): void,
29
- recordCommitTime(): void,
30
- startProfilerTimer(fiber: Fiber): void,
31
- stopProfilerTimerIfRunning(fiber: Fiber): void,
32
- stopProfilerTimerIfRunningAndRecordDelta(fiber: Fiber): void,
33
- syncNestedUpdateFlag(): void,
34
- ...
35
-};
36
-
37
-let commitTime: number = 0;
38
-let layoutEffectStartTime: number = -1;
39
-let profilerStartTime: number = -1;
40
-let passiveEffectStartTime: number = -1;
41
-
42
-/**
43
- * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect).
44
- *
45
- * The overall sequence is:
46
- * 1. render
47
- * 2. commit (and call `onRender`, `onCommit`)
48
- * 3. check for nested updates
49
- * 4. flush passive effects (and call `onPostCommit`)
50
- *
51
- * Nested updates are identified in step 3 above,
52
- * but step 4 still applies to the work that was just committed.
53
- * We use two flags to track nested updates then:
54
- * one tracks whether the upcoming update is a nested update,
55
- * and the other tracks whether the current update was a nested update.
56
- * The first value gets synced to the second at the start of the render phase.
57
- */
58
-let currentUpdateIsNested: boolean = false;
59
-let nestedUpdateScheduled: boolean = false;
60
-
61
-function isCurrentUpdateNested(): boolean {
62
- return currentUpdateIsNested;
63
-}
64
-
65
-function markNestedUpdateScheduled(): void {
66
- if (enableProfilerNestedUpdatePhase) {
67
- nestedUpdateScheduled = true;
68
- }
69
-}
70
-
71
-function resetNestedUpdateFlag(): void {
72
- if (enableProfilerNestedUpdatePhase) {
73
- currentUpdateIsNested = false;
74
- nestedUpdateScheduled = false;
75
- }
76
-}
77
-
78
-function syncNestedUpdateFlag(): void {
79
- if (enableProfilerNestedUpdatePhase) {
80
- currentUpdateIsNested = nestedUpdateScheduled;
81
- nestedUpdateScheduled = false;
82
- }
83
-}
84
-
85
-function getCommitTime(): number {
86
- return commitTime;
87
-}
88
-
89
-function recordCommitTime(): void {
90
- if (!enableProfilerTimer) {
91
- return;
92
- }
93
- commitTime = now();
94
-}
95
-
96
-function startProfilerTimer(fiber: Fiber): void {
97
- if (!enableProfilerTimer) {
98
- return;
99
- }
100
-
101
- profilerStartTime = now();
102
-
103
- if (((fiber.actualStartTime: any): number) < 0) {
104
- fiber.actualStartTime = now();
105
- }
106
-}
107
-
108
-function stopProfilerTimerIfRunning(fiber: Fiber): void {
109
- if (!enableProfilerTimer) {
110
- return;
111
- }
112
- profilerStartTime = -1;
113
-}
114
-
115
-function stopProfilerTimerIfRunningAndRecordDelta(
116
- fiber: Fiber,
117
- overrideBaseTime: boolean,
118
-): void {
119
- if (!enableProfilerTimer) {
120
- return;
121
- }
122
-
123
- if (profilerStartTime >= 0) {
124
- const elapsedTime = now() - profilerStartTime;
125
- // $FlowFixMe[unsafe-addition] addition with possible null/undefined value
126
- fiber.actualDuration += elapsedTime;
127
- if (overrideBaseTime) {
128
- fiber.selfBaseDuration = elapsedTime;
129
- }
130
- profilerStartTime = -1;
131
- }
132
-}
133
-
134
-function recordLayoutEffectDuration(fiber: Fiber): void {
135
- if (!enableProfilerTimer || !enableProfilerCommitHooks) {
136
- return;
137
- }
138
-
139
- if (layoutEffectStartTime >= 0) {
140
- const elapsedTime = now() - layoutEffectStartTime;
141
-
142
- layoutEffectStartTime = -1;
143
-
144
- // Store duration on the next nearest Profiler ancestor
145
- // Or the root (for the DevTools Profiler to read)
146
- let parentFiber = fiber.return;
147
- while (parentFiber !== null) {
148
- switch (parentFiber.tag) {
149
- case HostRoot:
150
- const root = parentFiber.stateNode;
151
- root.effectDuration += elapsedTime;
152
- return;
153
- case Profiler:
154
- const parentStateNode = parentFiber.stateNode;
155
- parentStateNode.effectDuration += elapsedTime;
156
- return;
157
- }
158
- parentFiber = parentFiber.return;
159
- }
160
- }
161
-}
162
-
163
-function recordPassiveEffectDuration(fiber: Fiber): void {
164
- if (!enableProfilerTimer || !enableProfilerCommitHooks) {
165
- return;
166
- }
167
-
168
- if (passiveEffectStartTime >= 0) {
169
- const elapsedTime = now() - passiveEffectStartTime;
170
-
171
- passiveEffectStartTime = -1;
172
-
173
- // Store duration on the next nearest Profiler ancestor
174
- // Or the root (for the DevTools Profiler to read)
175
- let parentFiber = fiber.return;
176
- while (parentFiber !== null) {
177
- switch (parentFiber.tag) {
178
- case HostRoot:
179
- const root = parentFiber.stateNode;
180
- if (root !== null) {
181
- root.passiveEffectDuration += elapsedTime;
182
- }
183
- return;
184
- case Profiler:
185
- const parentStateNode = parentFiber.stateNode;
186
- if (parentStateNode !== null) {
187
- // Detached fibers have their state node cleared out.
188
- // In this case, the return pointer is also cleared out,
189
- // so we won't be able to report the time spent in this Profiler's subtree.
190
- parentStateNode.passiveEffectDuration += elapsedTime;
191
- }
192
- return;
193
- }
194
- parentFiber = parentFiber.return;
195
- }
196
- }
197
-}
198
-
199
-function startLayoutEffectTimer(): void {
200
- if (!enableProfilerTimer || !enableProfilerCommitHooks) {
201
- return;
202
- }
203
- layoutEffectStartTime = now();
204
-}
205
-
206
-function startPassiveEffectTimer(): void {
207
- if (!enableProfilerTimer || !enableProfilerCommitHooks) {
208
- return;
209
- }
210
- passiveEffectStartTime = now();
211
-}
212
-
213
-function transferActualDuration(fiber: Fiber): void {
214
- // Transfer time spent rendering these children so we don't lose it
215
- // after we rerender. This is used as a helper in special cases
216
- // where we should count the work of multiple passes.
217
- let child = fiber.child;
218
- while (child) {
219
- // $FlowFixMe[unsafe-addition] addition with possible null/undefined value
220
- fiber.actualDuration += child.actualDuration;
221
- child = child.sibling;
222
- }
223
-}
224
-
225
-export {
226
- getCommitTime,
227
- isCurrentUpdateNested,
228
- markNestedUpdateScheduled,
229
- recordCommitTime,
230
- recordLayoutEffectDuration,
231
- recordPassiveEffectDuration,
232
- resetNestedUpdateFlag,
233
- startLayoutEffectTimer,
234
- startPassiveEffectTimer,
235
- startProfilerTimer,
236
- stopProfilerTimerIfRunning,
237
- stopProfilerTimerIfRunningAndRecordDelta,
238
- syncNestedUpdateFlag,
239
- transferActualDuration,
240
-};
packages/react-reconciler/src/ReactReconcilerConstants.js
+1
-1
@@ -15,5 +15,5 @@ export {
15
ContinuousEventPriority,
16
DefaultEventPriority,
17
IdleEventPriority,
18
-} from './ReactEventPriorities';
18
+} from './ReactEventPriorities.old';
19
export {ConcurrentRoot, LegacyRoot} from './ReactRootTags';
packages/react-reconciler/src/ReactStrictModeWarnings.new.js
deleted
-370
@@ -1,370 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow
8
- */
9
-
10
-import type {Fiber} from './ReactInternalTypes';
11
-
12
-import {
13
- resetCurrentFiber as resetCurrentDebugFiberInDEV,
14
- setCurrentFiber as setCurrentDebugFiberInDEV,
15
-} from './ReactCurrentFiber';
16
-import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
17
-import {StrictLegacyMode} from './ReactTypeOfMode';
18
-
19
-type FiberArray = Array<Fiber>;
20
-type FiberToFiberComponentsMap = Map<Fiber, FiberArray>;
21
-
22
-const ReactStrictModeWarnings = {
23
- recordUnsafeLifecycleWarnings: (fiber: Fiber, instance: any): void => {},
24
- flushPendingUnsafeLifecycleWarnings: (): void => {},
25
- recordLegacyContextWarning: (fiber: Fiber, instance: any): void => {},
26
- flushLegacyContextWarning: (): void => {},
27
- discardPendingWarnings: (): void => {},
28
-};
29
-
30
-if (__DEV__) {
31
- const findStrictRoot = (fiber: Fiber): Fiber | null => {
32
- let maybeStrictRoot = null;
33
-
34
- let node: null | Fiber = fiber;
35
- while (node !== null) {
36
- if (node.mode & StrictLegacyMode) {
37
- maybeStrictRoot = node;
38
- }
39
- node = node.return;
40
- }
41
-
42
- return maybeStrictRoot;
43
- };
44
-
45
- const setToSortedString = set => {
46
- const array = [];
47
- set.forEach(value => {
48
- array.push(value);
49
- });
50
- return array.sort().join(', ');
51
- };
52
-
53
- let pendingComponentWillMountWarnings: Array<Fiber> = [];
54
- let pendingUNSAFE_ComponentWillMountWarnings: Array<Fiber> = [];
55
- let pendingComponentWillReceivePropsWarnings: Array<Fiber> = [];
56
- let pendingUNSAFE_ComponentWillReceivePropsWarnings: Array<Fiber> = [];
57
- let pendingComponentWillUpdateWarnings: Array<Fiber> = [];
58
- let pendingUNSAFE_ComponentWillUpdateWarnings: Array<Fiber> = [];
59
-
60
- // Tracks components we have already warned about.
61
- const didWarnAboutUnsafeLifecycles = new Set();
62
-
63
- ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = (
64
- fiber: Fiber,
65
- instance: any,
66
- ) => {
67
- // Dedupe strategy: Warn once per component.
68
- if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
69
- return;
70
- }
71
-
72
- if (
73
- typeof instance.componentWillMount === 'function' &&
74
- // Don't warn about react-lifecycles-compat polyfilled components.
75
- instance.componentWillMount.__suppressDeprecationWarning !== true
76
- ) {
77
- pendingComponentWillMountWarnings.push(fiber);
78
- }
79
-
80
- if (
81
- fiber.mode & StrictLegacyMode &&
82
- typeof instance.UNSAFE_componentWillMount === 'function'
83
- ) {
84
- pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
85
- }
86
-
87
- if (
88
- typeof instance.componentWillReceiveProps === 'function' &&
89
- instance.componentWillReceiveProps.__suppressDeprecationWarning !== true
90
- ) {
91
- pendingComponentWillReceivePropsWarnings.push(fiber);
92
- }
93
-
94
- if (
95
- fiber.mode & StrictLegacyMode &&
96
- typeof instance.UNSAFE_componentWillReceiveProps === 'function'
97
- ) {
98
- pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
99
- }
100
-
101
- if (
102
- typeof instance.componentWillUpdate === 'function' &&
103
- instance.componentWillUpdate.__suppressDeprecationWarning !== true
104
- ) {
105
- pendingComponentWillUpdateWarnings.push(fiber);
106
- }
107
-
108
- if (
109
- fiber.mode & StrictLegacyMode &&
110
- typeof instance.UNSAFE_componentWillUpdate === 'function'
111
- ) {
112
- pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
113
- }
114
- };
115
-
116
- ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = () => {
117
- // We do an initial pass to gather component names
118
- const componentWillMountUniqueNames = new Set();
119
- if (pendingComponentWillMountWarnings.length > 0) {
120
- pendingComponentWillMountWarnings.forEach(fiber => {
121
- componentWillMountUniqueNames.add(
122
- getComponentNameFromFiber(fiber) || 'Component',
123
- );
124
- didWarnAboutUnsafeLifecycles.add(fiber.type);
125
- });
126
- pendingComponentWillMountWarnings = [];
127
- }
128
-
129
- const UNSAFE_componentWillMountUniqueNames = new Set();
130
- if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
131
- pendingUNSAFE_ComponentWillMountWarnings.forEach(fiber => {
132
- UNSAFE_componentWillMountUniqueNames.add(
133
- getComponentNameFromFiber(fiber) || 'Component',
134
- );
135
- didWarnAboutUnsafeLifecycles.add(fiber.type);
136
- });
137
- pendingUNSAFE_ComponentWillMountWarnings = [];
138
- }
139
-
140
- const componentWillReceivePropsUniqueNames = new Set();
141
- if (pendingComponentWillReceivePropsWarnings.length > 0) {
142
- pendingComponentWillReceivePropsWarnings.forEach(fiber => {
143
- componentWillReceivePropsUniqueNames.add(
144
- getComponentNameFromFiber(fiber) || 'Component',
145
- );
146
- didWarnAboutUnsafeLifecycles.add(fiber.type);
147
- });
148
-
149
- pendingComponentWillReceivePropsWarnings = [];
150
- }
151
-
152
- const UNSAFE_componentWillReceivePropsUniqueNames = new Set();
153
- if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
154
- pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(fiber => {
155
- UNSAFE_componentWillReceivePropsUniqueNames.add(
156
- getComponentNameFromFiber(fiber) || 'Component',
157
- );
158
- didWarnAboutUnsafeLifecycles.add(fiber.type);
159
- });
160
-
161
- pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
162
- }
163
-
164
- const componentWillUpdateUniqueNames = new Set();
165
- if (pendingComponentWillUpdateWarnings.length > 0) {
166
- pendingComponentWillUpdateWarnings.forEach(fiber => {
167
- componentWillUpdateUniqueNames.add(
168
- getComponentNameFromFiber(fiber) || 'Component',
169
- );
170
- didWarnAboutUnsafeLifecycles.add(fiber.type);
171
- });
172
-
173
- pendingComponentWillUpdateWarnings = [];
174
- }
175
-
176
- const UNSAFE_componentWillUpdateUniqueNames = new Set();
177
- if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
178
- pendingUNSAFE_ComponentWillUpdateWarnings.forEach(fiber => {
179
- UNSAFE_componentWillUpdateUniqueNames.add(
180
- getComponentNameFromFiber(fiber) || 'Component',
181
- );
182
- didWarnAboutUnsafeLifecycles.add(fiber.type);
183
- });
184
-
185
- pendingUNSAFE_ComponentWillUpdateWarnings = [];
186
- }
187
-
188
- // Finally, we flush all the warnings
189
- // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
190
- if (UNSAFE_componentWillMountUniqueNames.size > 0) {
191
- const sortedNames = setToSortedString(
192
- UNSAFE_componentWillMountUniqueNames,
193
- );
194
- console.error(
195
- 'Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' +
196
- 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' +
197
- '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' +
198
- '\nPlease update the following components: %s',
199
- sortedNames,
200
- );
201
- }
202
-
203
- if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
204
- const sortedNames = setToSortedString(
205
- UNSAFE_componentWillReceivePropsUniqueNames,
206
- );
207
- console.error(
208
- 'Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' +
209
- 'and may indicate bugs in your code. ' +
210
- 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' +
211
- '* Move data fetching code or side effects to componentDidUpdate.\n' +
212
- "* If you're updating state whenever props change, " +
213
- 'refactor your code to use memoization techniques or move it to ' +
214
- 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' +
215
- '\nPlease update the following components: %s',
216
- sortedNames,
217
- );
218
- }
219
-
220
- if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
221
- const sortedNames = setToSortedString(
222
- UNSAFE_componentWillUpdateUniqueNames,
223
- );
224
- console.error(
225
- 'Using UNSAFE_componentWillUpdate in strict mode is not recommended ' +
226
- 'and may indicate bugs in your code. ' +
227
- 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' +
228
- '* Move data fetching code or side effects to componentDidUpdate.\n' +
229
- '\nPlease update the following components: %s',
230
- sortedNames,
231
- );
232
- }
233
-
234
- if (componentWillMountUniqueNames.size > 0) {
235
- const sortedNames = setToSortedString(componentWillMountUniqueNames);
236
-
237
- console.warn(
238
- 'componentWillMount has been renamed, and is not recommended for use. ' +
239
- 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' +
240
- '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' +
241
- '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' +
242
- 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' +
243
- 'To rename all deprecated lifecycles to their new names, you can run ' +
244
- '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' +
245
- '\nPlease update the following components: %s',
246
- sortedNames,
247
- );
248
- }
249
-
250
- if (componentWillReceivePropsUniqueNames.size > 0) {
251
- const sortedNames = setToSortedString(
252
- componentWillReceivePropsUniqueNames,
253
- );
254
-
255
- console.warn(
256
- 'componentWillReceiveProps has been renamed, and is not recommended for use. ' +
257
- 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' +
258
- '* Move data fetching code or side effects to componentDidUpdate.\n' +
259
- "* If you're updating state whenever props change, refactor your " +
260
- 'code to use memoization techniques or move it to ' +
261
- 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' +
262
- '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' +
263
- 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' +
264
- 'To rename all deprecated lifecycles to their new names, you can run ' +
265
- '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' +
266
- '\nPlease update the following components: %s',
267
- sortedNames,
268
- );
269
- }
270
-
271
- if (componentWillUpdateUniqueNames.size > 0) {
272
- const sortedNames = setToSortedString(componentWillUpdateUniqueNames);
273
-
274
- console.warn(
275
- 'componentWillUpdate has been renamed, and is not recommended for use. ' +
276
- 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' +
277
- '* Move data fetching code or side effects to componentDidUpdate.\n' +
278
- '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' +
279
- 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' +
280
- 'To rename all deprecated lifecycles to their new names, you can run ' +
281
- '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' +
282
- '\nPlease update the following components: %s',
283
- sortedNames,
284
- );
285
- }
286
- };
287
-
288
- let pendingLegacyContextWarning: FiberToFiberComponentsMap = new Map();
289
-
290
- // Tracks components we have already warned about.
291
- const didWarnAboutLegacyContext = new Set();
292
-
293
- ReactStrictModeWarnings.recordLegacyContextWarning = (
294
- fiber: Fiber,
295
- instance: any,
296
- ) => {
297
- const strictRoot = findStrictRoot(fiber);
298
- if (strictRoot === null) {
299
- console.error(
300
- 'Expected to find a StrictMode component in a strict mode tree. ' +
301
- 'This error is likely caused by a bug in React. Please file an issue.',
302
- );
303
- return;
304
- }
305
-
306
- // Dedup strategy: Warn once per component.
307
- if (didWarnAboutLegacyContext.has(fiber.type)) {
308
- return;
309
- }
310
-
311
- let warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
312
-
313
- if (
314
- fiber.type.contextTypes != null ||
315
- fiber.type.childContextTypes != null ||
316
- (instance !== null && typeof instance.getChildContext === 'function')
317
- ) {
318
- if (warningsForRoot === undefined) {
319
- warningsForRoot = [];
320
- pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
321
- }
322
- warningsForRoot.push(fiber);
323
- }
324
- };
325
-
326
- ReactStrictModeWarnings.flushLegacyContextWarning = () => {
327
- ((pendingLegacyContextWarning: any): FiberToFiberComponentsMap).forEach(
328
- (fiberArray: FiberArray, strictRoot) => {
329
- if (fiberArray.length === 0) {
330
- return;
331
- }
332
- const firstFiber = fiberArray[0];
333
-
334
- const uniqueNames = new Set();
335
- fiberArray.forEach(fiber => {
336
- uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
337
- didWarnAboutLegacyContext.add(fiber.type);
338
- });
339
-
340
- const sortedNames = setToSortedString(uniqueNames);
341
-
342
- try {
343
- setCurrentDebugFiberInDEV(firstFiber);
344
- console.error(
345
- 'Legacy context API has been detected within a strict-mode tree.' +
346
- '\n\nThe old API will be supported in all 16.x releases, but applications ' +
347
- 'using it should migrate to the new version.' +
348
- '\n\nPlease update the following components: %s' +
349
- '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context',
350
- sortedNames,
351
- );
352
- } finally {
353
- resetCurrentDebugFiberInDEV();
354
- }
355
- },
356
- );
357
- };
358
-
359
- ReactStrictModeWarnings.discardPendingWarnings = () => {
360
- pendingComponentWillMountWarnings = [];
361
- pendingUNSAFE_ComponentWillMountWarnings = [];
362
- pendingComponentWillReceivePropsWarnings = [];
363
- pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
364
- pendingComponentWillUpdateWarnings = [];
365
- pendingUNSAFE_ComponentWillUpdateWarnings = [];
366
- pendingLegacyContextWarning = new Map();
367
- };
368
-}
369
-
370
-export default ReactStrictModeWarnings;
packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js
+1
-1
@@ -24,7 +24,7 @@ describe('ReactFiberHostContext', () => {
24
ReactFiberReconciler = require('react-reconciler');
25
ConcurrentRoot = require('react-reconciler/src/ReactRootTags')
26
.ConcurrentRoot;
27
- DefaultEventPriority = require('react-reconciler/src/ReactEventPriorities')
27
+ DefaultEventPriority = require('react-reconciler/src/ReactEventPriorities.old')
28
.DefaultEventPriority;
29
});
30
packages/react-reconciler/src/__tests__/ReactIncrementalErrorReplay-test.internal.js
+1
-4
@@ -21,10 +21,7 @@ describe('ReactIncrementalErrorReplay-test', () => {
21
22
// This is the method we're going to test.
23
// If this is no longer used, you can delete this test file.;
24
-
25
- const assignFiberPropertiesInDEV = gate(flags => flags.new)
26
- ? require('../ReactFiber.new').assignFiberPropertiesInDEV
27
- : require('../ReactFiber.old').assignFiberPropertiesInDEV;
24
+ const {assignFiberPropertiesInDEV} = require('../ReactFiber.old');
25
26
// Get a real fiber.
27
const realFiber = ReactTestRenderer.create(<div />).root._currentFiber();
packages/react-reconciler/src/__tests__/ReactUpdaters-test.internal.js
-4
@@ -84,10 +84,6 @@ describe('updaters', () => {
84
'react-reconciler/src/ReactFiberDevToolsHook.old',
85
() => mockDevToolsHook,
86
);
87
- jest.mock(
88
- 'react-reconciler/src/ReactFiberDevToolsHook.new',
89
- () => mockDevToolsHook,
90
- );
87
88
React = require('react');
89
ReactDOM = require('react-dom');
packages/react-refresh/src/ReactFreshRuntime.js
+1
-1
@@ -16,7 +16,7 @@ import type {
16
ScheduleRoot,
17
FindHostInstancesForRefresh,
18
SetRefreshHandler,
19
-} from 'react-reconciler/src/ReactFiberHotReloading';
19
+} from 'react-reconciler/src/ReactFiberHotReloading.old';
20
import type {ReactNodeList} from 'shared/ReactTypes';
21
22
import {REACT_MEMO_TYPE, REACT_FORWARD_REF_TYPE} from 'shared/ReactSymbols';
packages/react-test-renderer/src/ReactTestHostConfig.js
+1
-1
@@ -8,7 +8,7 @@
8
*/
9
10
import isArray from 'shared/isArray';
11
-import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities';
11
+import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old';
12
13
export type Type = string;
14
export type Props = Object;
packages/react-test-renderer/src/ReactTestRenderer.js
+1
-1
@@ -23,7 +23,7 @@ import {
23
flushSync,
24
injectIntoDevTools,
25
batchedUpdates,
26
-} from 'react-reconciler/src/ReactFiberReconciler';
26
+} from 'react-reconciler/src/ReactFiberReconciler.old';
27
import {findCurrentFiberUsingSlowPath} from 'react-reconciler/src/ReactFiberTreeReflection';
28
import {
29
Fragment,
packages/react/src/ReactCurrentBatchConfig.js
+1
-1
@@ -7,7 +7,7 @@
7
* @flow
8
*/
9
10
-import type {BatchConfigTransition} from 'react-reconciler/src/ReactFiberTracingMarkerComponent.new';
10
+import type {BatchConfigTransition} from 'react-reconciler/src/ReactFiberTracingMarkerComponent.old';
11
12
type BatchConfig = {
13
transition: BatchConfigTransition | null,
packages/shared/ReactFeatureFlags.js
-4
@@ -68,10 +68,6 @@ export const enableScopeAPI = false;
68
// Experimental Create Event Handle API.
69
export const enableCreateEventHandleAPI = false;
70
71
-// This controls whether you get the `.old` modules or the `.new` modules in
72
-// the react-reconciler package.
73
-export const enableNewReconciler = false;
74
-
71
// Support legacy Primer support on internal FB www
72
export const enableLegacyFBSupport = false;
73
packages/shared/forks/ReactFeatureFlags.native-fb.js
-1
@@ -64,7 +64,6 @@ export const disableNativeComponentFrames = false;
64
export const skipUnmountedBoundaries = false;
65
export const deletedTreeCleanUpLevel = 3;
66
export const enableGetInspectorDataForInstanceInProduction = true;
67
-export const enableNewReconciler = false;
67
export const deferRenderPhaseUpdateToNextBatch = false;
68
69
export const createRootStrictEffectsByDefault = false;
packages/shared/forks/ReactFeatureFlags.native-oss.js
-1
@@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false;
54
export const skipUnmountedBoundaries = false;
55
export const deletedTreeCleanUpLevel = 3;
56
export const enableGetInspectorDataForInstanceInProduction = false;
57
-export const enableNewReconciler = false;
57
export const deferRenderPhaseUpdateToNextBatch = false;
58
59
export const createRootStrictEffectsByDefault = false;
packages/shared/forks/ReactFeatureFlags.test-renderer.js
-1
@@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false;
54
export const skipUnmountedBoundaries = false;
55
export const deletedTreeCleanUpLevel = 3;
56
export const enableGetInspectorDataForInstanceInProduction = false;
57
-export const enableNewReconciler = false;
57
export const deferRenderPhaseUpdateToNextBatch = false;
58
59
export const createRootStrictEffectsByDefault = false;
packages/shared/forks/ReactFeatureFlags.test-renderer.native.js
-1
@@ -46,7 +46,6 @@ export const disableNativeComponentFrames = false;
46
export const skipUnmountedBoundaries = false;
47
export const deletedTreeCleanUpLevel = 3;
48
export const enableGetInspectorDataForInstanceInProduction = false;
49
-export const enableNewReconciler = false;
49
export const deferRenderPhaseUpdateToNextBatch = false;
50
export const enableSuspenseAvoidThisFallback = false;
51
export const enableSuspenseAvoidThisFallbackFizz = false;
packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
-1
@@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false;
54
export const skipUnmountedBoundaries = false;
55
export const deletedTreeCleanUpLevel = 3;
56
export const enableGetInspectorDataForInstanceInProduction = false;
57
-export const enableNewReconciler = false;
57
export const deferRenderPhaseUpdateToNextBatch = false;
58
59
export const createRootStrictEffectsByDefault = false;
packages/shared/forks/ReactFeatureFlags.testing.js
-1
@@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false;
54
export const skipUnmountedBoundaries = false;
55
export const deletedTreeCleanUpLevel = 3;
56
export const enableGetInspectorDataForInstanceInProduction = false;
57
-export const enableNewReconciler = false;
57
export const deferRenderPhaseUpdateToNextBatch = false;
58
59
export const createRootStrictEffectsByDefault = false;
packages/shared/forks/ReactFeatureFlags.testing.www.js
-1
@@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false;
54
export const skipUnmountedBoundaries = true;
55
export const deletedTreeCleanUpLevel = 3;
56
export const enableGetInspectorDataForInstanceInProduction = false;
57
-export const enableNewReconciler = false;
57
export const deferRenderPhaseUpdateToNextBatch = false;
58
59
export const createRootStrictEffectsByDefault = false;
packages/shared/forks/ReactFeatureFlags.www.js
-5
@@ -95,11 +95,6 @@ export const enableComponentStackLocations = true;
95
96
export const disableTextareaChildren = __EXPERIMENTAL__;
97
98
-// Enable forked reconciler. Piggy-backing on the "variant" global so that we
99
-// don't have to add another test dimension. The build system will compile this
100
-// to the correct value.
101
-export const enableNewReconciler = __VARIANT__;
102
-
98
export const allowConcurrentByDefault = true;
99
100
export const deletedTreeCleanUpLevel = 3;
scripts/eslint-rules/__tests__/no-cross-fork-imports-test.internal.js
deleted
-122
@@ -1,122 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @emails react-core
8
- */
9
-
10
-'use strict';
11
-
12
-const rule = require('../no-cross-fork-imports');
13
-const {RuleTester} = require('eslint');
14
-const ruleTester = new RuleTester({
15
- parserOptions: {
16
- ecmaVersion: 8,
17
- sourceType: 'module',
18
- },
19
-});
20
-
21
-ruleTester.run('eslint-rules/no-cross-fork-imports', rule, {
22
- valid: [
23
- {
24
- code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop';",
25
- filename: 'ReactFiberWorkLoop.js',
26
- },
27
- {
28
- code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';",
29
- filename: 'ReactFiberWorkLoop.new.js',
30
- },
31
- {
32
- code:
33
- "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new.js';",
34
- filename: 'ReactFiberWorkLoop.new.js',
35
- },
36
- {
37
- code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';",
38
- filename: 'ReactFiberWorkLoop.old.js',
39
- },
40
- {
41
- code:
42
- "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old.js';",
43
- filename: 'ReactFiberWorkLoop.old.js',
44
- },
45
- ],
46
- invalid: [
47
- {
48
- code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';",
49
- filename: 'ReactFiberWorkLoop.old.js',
50
- errors: [
51
- {
52
- message:
53
- 'A module that belongs to the old fork cannot import a module ' +
54
- 'from the new fork.',
55
- },
56
- ],
57
- output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';",
58
- },
59
- {
60
- code:
61
- "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new.js';",
62
- filename: 'ReactFiberWorkLoop.old.js',
63
- errors: [
64
- {
65
- message:
66
- 'A module that belongs to the old fork cannot import a module ' +
67
- 'from the new fork.',
68
- },
69
- ],
70
- output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';",
71
- },
72
- {
73
- code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';",
74
- filename: 'ReactFiberWorkLoop.new.js',
75
- errors: [
76
- {
77
- message:
78
- 'A module that belongs to the new fork cannot import a module ' +
79
- 'from the old fork.',
80
- },
81
- ],
82
- output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';",
83
- },
84
- {
85
- code:
86
- "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old.js';",
87
- filename: 'ReactFiberWorkLoop.new.js',
88
- errors: [
89
- {
90
- message:
91
- 'A module that belongs to the new fork cannot import a module ' +
92
- 'from the old fork.',
93
- },
94
- ],
95
- output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';",
96
- },
97
- {
98
- code: "export {DiscreteEventPriority} from './ReactFiberLane.old.js';",
99
- filename: 'ReactFiberReconciler.new.js',
100
- errors: [
101
- {
102
- message:
103
- 'A module that belongs to the new fork cannot import a module ' +
104
- 'from the old fork.',
105
- },
106
- ],
107
- output: "export {DiscreteEventPriority} from './ReactFiberLane.new';",
108
- },
109
- {
110
- code: "export {DiscreteEventPriority} from './ReactFiberLane.new.js';",
111
- filename: 'ReactFiberReconciler.old.js',
112
- errors: [
113
- {
114
- message:
115
- 'A module that belongs to the old fork cannot import a module ' +
116
- 'from the new fork.',
117
- },
118
- ],
119
- output: "export {DiscreteEventPriority} from './ReactFiberLane.old';",
120
- },
121
- ],
122
-});
scripts/eslint-rules/__tests__/no-cross-fork-types-test.internal.js
deleted
-89
@@ -1,89 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @emails react-core
8
- */
9
-
10
-'use strict';
11
-
12
-const rule = require('../no-cross-fork-types');
13
-const {RuleTester} = require('eslint');
14
-const ruleTester = new RuleTester({
15
- parserOptions: {
16
- ecmaVersion: 8,
17
- sourceType: 'module',
18
- },
19
-});
20
-
21
-const newAccessWarning =
22
- 'Field cannot be accessed inside the old reconciler fork, only the ' +
23
- 'new fork.';
24
-
25
-const oldAccessWarning =
26
- 'Field cannot be accessed inside the new reconciler fork, only the ' +
27
- 'old fork.';
28
-
29
-ruleTester.run('eslint-rules/no-cross-fork-types', rule, {
30
- valid: [
31
- {
32
- code: `
33
-const a = obj.key_old;
34
-const b = obj.key_new;
35
-const {key_old, key_new} = obj;
36
-`,
37
- filename: 'ReactFiberWorkLoop.js',
38
- },
39
- {
40
- code: `
41
-const a = obj.key_old;
42
-const {key_old} = obj;
43
-`,
44
- filename: 'ReactFiberWorkLoop.old.js',
45
- },
46
- {
47
- code: `
48
-const a = obj.key_new;
49
-const {key_new} = obj;
50
-`,
51
- filename: 'ReactFiberWorkLoop.new.js',
52
- },
53
- ],
54
- invalid: [
55
- {
56
- code: 'const a = obj.key_new;',
57
- filename: 'ReactFiberWorkLoop.old.js',
58
- errors: [{message: newAccessWarning}],
59
- },
60
- {
61
- code: 'const a = obj.key_old;',
62
- filename: 'ReactFiberWorkLoop.new.js',
63
- errors: [{message: oldAccessWarning}],
64
- },
65
-
66
- {
67
- code: 'const {key_new} = obj;',
68
- filename: 'ReactFiberWorkLoop.old.js',
69
- errors: [{message: newAccessWarning}],
70
- },
71
- {
72
- code: 'const {key_old} = obj;',
73
- filename: 'ReactFiberWorkLoop.new.js',
74
- errors: [{message: oldAccessWarning}],
75
- },
76
- {
77
- code: 'const subtreeFlags = obj.subtreeFlags;',
78
- filename: 'ReactFiberWorkLoop.old.js',
79
- options: [{new: ['subtreeFlags']}],
80
- errors: [{message: newAccessWarning}],
81
- },
82
- {
83
- code: 'const firstEffect = obj.firstEffect;',
84
- filename: 'ReactFiberWorkLoop.new.js',
85
- options: [{old: ['firstEffect']}],
86
- errors: [{message: oldAccessWarning}],
87
- },
88
- ],
89
-});
scripts/eslint-rules/index.js
-2
@@ -7,8 +7,6 @@ module.exports = {
7
'warning-args': require('./warning-args'),
8
'prod-error-codes': require('./prod-error-codes'),
9
'no-production-logging': require('./no-production-logging'),
10
- 'no-cross-fork-imports': require('./no-cross-fork-imports'),
11
- 'no-cross-fork-types': require('./no-cross-fork-types'),
10
'safe-string-coercion': require('./safe-string-coercion'),
11
},
12
};
scripts/eslint-rules/no-cross-fork-imports.js
deleted
-87
@@ -1,87 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @emails react-core
8
- */
9
-
10
-'use strict';
11
-
12
-function isOldFork(filename) {
13
- return filename.endsWith('.old.js') || filename.endsWith('.old');
14
-}
15
-
16
-function isNewFork(filename) {
17
- return filename.endsWith('.new.js') || filename.endsWith('.new');
18
-}
19
-
20
-module.exports = {
21
- meta: {
22
- type: 'problem',
23
- fixable: 'code',
24
- },
25
- create(context) {
26
- const sourceFilename = context.getFilename();
27
-
28
- if (isOldFork(sourceFilename)) {
29
- const visitor = node => {
30
- const sourceNode = node.source;
31
- if (sourceNode === null) {
32
- return;
33
- }
34
- const filename = sourceNode.value;
35
- if (isNewFork(filename)) {
36
- context.report({
37
- node: sourceNode,
38
- message:
39
- 'A module that belongs to the old fork cannot import a module ' +
40
- 'from the new fork.',
41
- fix(fixer) {
42
- return fixer.replaceText(
43
- sourceNode,
44
- `'${filename.replace(/\.new(\.js)?$/, '.old')}'`
45
- );
46
- },
47
- });
48
- }
49
- };
50
- return {
51
- ImportDeclaration: visitor,
52
- ExportNamedDeclaration: visitor,
53
- };
54
- }
55
-
56
- if (isNewFork(sourceFilename)) {
57
- const visitor = node => {
58
- const sourceNode = node.source;
59
- if (sourceNode === null) {
60
- return;
61
- }
62
- const filename = sourceNode.value;
63
- if (isOldFork(filename)) {
64
- context.report({
65
- node: sourceNode,
66
- message:
67
- 'A module that belongs to the new fork cannot import a module ' +
68
- 'from the old fork.',
69
- fix(fixer) {
70
- return fixer.replaceText(
71
- sourceNode,
72
- `'${filename.replace(/\.old(\.js)?$/, '.new')}'`
73
- );
74
- },
75
- });
76
- }
77
- };
78
-
79
- return {
80
- ImportDeclaration: visitor,
81
- ExportNamedDeclaration: visitor,
82
- };
83
- }
84
-
85
- return {};
86
- },
87
-};
scripts/eslint-rules/no-cross-fork-types.js
deleted
-125
@@ -1,125 +0,0 @@
1
-/**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @emails react-core
8
- */
9
-
10
-/* eslint-disable no-for-of-loops/no-for-of-loops */
11
-
12
-'use strict';
13
-
14
-function isOldFork(filename) {
15
- return filename.endsWith('.old.js') || filename.endsWith('.old');
16
-}
17
-
18
-function isNewFork(filename) {
19
- return filename.endsWith('.new.js') || filename.endsWith('.new');
20
-}
21
-
22
-function warnIfNewField(context, newFields, identifier) {
23
- const name = identifier.name;
24
- if (name.endsWith('_new') || (newFields !== null && newFields.has(name))) {
25
- context.report({
26
- node: identifier,
27
- message:
28
- 'Field cannot be accessed inside the old reconciler fork, only the ' +
29
- 'new fork.',
30
- });
31
- }
32
-}
33
-
34
-function warnIfOldField(context, oldFields, identifier) {
35
- const name = identifier.name;
36
- if (name.endsWith('_old') || (oldFields !== null && oldFields.has(name))) {
37
- context.report({
38
- node: identifier,
39
- message:
40
- 'Field cannot be accessed inside the new reconciler fork, only the ' +
41
- 'old fork.',
42
- });
43
- }
44
-}
45
-
46
-module.exports = {
47
- meta: {
48
- type: 'problem',
49
- },
50
- create(context) {
51
- const sourceFilename = context.getFilename();
52
-
53
- if (isOldFork(sourceFilename)) {
54
- const options = context.options;
55
- let newFields = null;
56
- if (options !== null) {
57
- for (const option of options) {
58
- if (option.new !== undefined) {
59
- if (newFields === null) {
60
- newFields = new Set(option.new);
61
- } else {
62
- for (const field of option.new) {
63
- newFields.add(field);
64
- }
65
- }
66
- }
67
- }
68
- }
69
- return {
70
- MemberExpression(node) {
71
- const property = node.property;
72
- if (property.type === 'Identifier') {
73
- warnIfNewField(context, newFields, property);
74
- }
75
- },
76
-
77
- ObjectPattern(node) {
78
- for (const property of node.properties) {
79
- const key = property.key;
80
- if (key.type === 'Identifier') {
81
- warnIfNewField(context, newFields, key);
82
- }
83
- }
84
- },
85
- };
86
- }
87
-
88
- if (isNewFork(sourceFilename)) {
89
- const options = context.options;
90
- let oldFields = null;
91
- if (options !== null) {
92
- for (const option of options) {
93
- if (option.old !== undefined) {
94
- if (oldFields === null) {
95
- oldFields = new Set(option.old);
96
- } else {
97
- for (const field of option.new) {
98
- oldFields.add(field);
99
- }
100
- }
101
- }
102
- }
103
- }
104
- return {
105
- MemberExpression(node) {
106
- const property = node.property;
107
- if (property.type === 'Identifier') {
108
- warnIfOldField(context, oldFields, property);
109
- }
110
- },
111
-
112
- ObjectPattern(node) {
113
- for (const property of node.properties) {
114
- const key = property.key;
115
- if (key.type === 'Identifier') {
116
- warnIfOldField(context, oldFields, key);
117
- }
118
- }
119
- },
120
- };
121
- }
122
-
123
- return {};
124
- },
125
-};
scripts/jest/TestFlags.js
-4
@@ -75,10 +75,6 @@ function getTestFlags() {
75
// doesn't exist.
76
return new Proxy(
77
{
78
- // Feature flag aliases
79
- old: featureFlags.enableNewReconciler === false,
80
- new: featureFlags.enableNewReconciler === true,
81
-
78
channel: releaseChannel,
79
modern: releaseChannel === 'modern',
80
classic: releaseChannel === 'classic',
scripts/jest/setupHostConfigs.js
-8
@@ -58,14 +58,6 @@ jest.mock('react/react.shared-subset', () => {
58
return jest.requireActual(resolvedEntryPoint);
59
});
60
61
-jest.mock('react-reconciler/src/ReactFiberReconciler', () => {
62
- return jest.requireActual(
63
- __VARIANT__
64
- ? 'react-reconciler/src/ReactFiberReconciler.new'
65
- : 'react-reconciler/src/ReactFiberReconciler.old'
66
- );
67
-});
68
-
61
// When testing the custom renderer code path through `react-reconciler`,
62
// turn the export into a function, and use the argument as host config.
63
const shimHostConfigPath = 'react-reconciler/src/ReactFiberHostConfig';
scripts/merge-fork/README.md
deleted
-58
@@ -1,58 +0,0 @@
1
-# merge-fork
2
-
3
-Script for syncing changes between forked modules.
4
-
5
-## Basic example
6
-
7
-```sh
8
-yarn merge-fork --base-dir=packages/react-reconciler/src ReactFiberWorkLoop
9
-```
10
-
11
-This will take all the changes in `ReactFiberWorkLoop.new.js` and apply them to `ReactFiberWorkLoop.old.js`.
12
-
13
-## Syncing multiple modules at once
14
-
15
-You can merge multiple modules at a time:
16
-
17
-```sh
18
-yarn merge-fork \
19
- --base-dir=packages/react-reconciler/src \
20
- ReactFiberWorkLoop \
21
- ReactFiberBeginWork \
22
- ReactFiberCompleteWork \
23
- ReactFiberCommitWork
24
-```
25
-
26
-## Syncing modules with different names
27
-
28
-You can provide explicit "old" and "new" file names. This only works for one module at a time:
29
-
30
-```sh
31
-yarn merge-fork \
32
- --base-dir=packages/react-reconciler/src \
33
- --old=ReactFiberExpirationTime.js \
34
- --new=ReactFiberLane.js
35
-```
36
-
37
-## Syncing modules in the opposite direction (old -> new)
38
-
39
-The default is to merge changes from the new module to the old one. To merge changes in the opposite direction, use `--reverse`.
40
-
41
-```sh
42
-yarn merge-fork \
43
- --reverse \
44
- --base-dir=packages/react-reconciler/src \
45
- ReactFiberWorkLoop
46
-```
47
-
48
-## Comparing changes to an older base rev
49
-
50
-By default, the changes are compared to HEAD. You can use `--base-ref` to compare to any rev. For example, while working on a PR, you might make multiple commits to the new fork before you're ready to backport them to the old one. In that case, you want to compare to the merge base of your PR branch:
51
-
52
-```sh
53
-yarn merge-fork \
54
- --base-ref=$(git merge-base HEAD origin/main)
55
- --base-dir=packages/react-reconciler/src \
56
- ReactFiberWorkLoop
57
-```
58
-
scripts/merge-fork/forked-revisions
scripts/merge-fork/merge-fork.js
deleted
-109
@@ -1,109 +0,0 @@
1
-'use strict';
2
-
3
-/* eslint-disable no-for-of-loops/no-for-of-loops */
4
-
5
-const {writeFileSync} = require('fs');
6
-const path = require('path');
7
-const {spawnSync} = require('child_process');
8
-const minimist = require('minimist');
9
-const tmp = require('tmp');
10
-
11
-const argv = minimist(process.argv.slice(2), {
12
- boolean: ['reverse'],
13
- default: {
14
- 'base-ref': 'HEAD',
15
- },
16
-});
17
-
18
-const baseRef = argv['base-ref'];
19
-const baseDir = argv['base-dir'];
20
-
21
-function resolvePath(file) {
22
- return baseDir !== undefined ? path.join(baseDir, file) : file;
23
-}
24
-
25
-function getTransforms() {
26
- const old = argv.old;
27
- const base = argv.base;
28
- const _new = argv.new;
29
- if (old !== undefined) {
30
- if (_new === undefined) {
31
- throw Error('Cannot provide --old without also providing --new');
32
- }
33
- const oldPath = resolvePath(old);
34
- const newPath = resolvePath(_new);
35
-
36
- let basePath;
37
- let fromPath;
38
- let toPath;
39
- if (argv.reverse) {
40
- fromPath = oldPath;
41
- toPath = newPath;
42
- basePath = base !== undefined ? resolvePath(basePath) : oldPath;
43
- } else {
44
- fromPath = newPath;
45
- toPath = oldPath;
46
- basePath = base !== undefined ? resolvePath(basePath) : newPath;
47
- }
48
-
49
- return [
50
- {
51
- base: basePath,
52
- from: fromPath,
53
- to: toPath,
54
- },
55
- ];
56
- } else if (_new !== undefined) {
57
- throw Error('Cannot provide --new without also providing --old');
58
- }
59
- return argv._.map(filename => {
60
- const oldPath = resolvePath(filename + '.old.js');
61
- const newPath = resolvePath(filename + '.new.js');
62
-
63
- let basePath;
64
- let fromPath;
65
- let toPath;
66
- if (argv.reverse) {
67
- fromPath = oldPath;
68
- toPath = newPath;
69
- basePath = base !== undefined ? resolvePath(basePath) : oldPath;
70
- } else {
71
- fromPath = newPath;
72
- toPath = oldPath;
73
- basePath = base !== undefined ? resolvePath(basePath) : newPath;
74
- }
75
- return {
76
- base: basePath,
77
- from: fromPath,
78
- to: toPath,
79
- };
80
- });
81
-}
82
-
83
-for (const {base: baseFilename, from, to} of getTransforms()) {
84
- // Write the base file contents to a temporary file
85
- const gitShowResult = spawnSync(
86
- 'git',
87
- ['show', `${baseRef}:${baseFilename}`],
88
- {
89
- stdio: 'pipe',
90
- }
91
- );
92
- if (gitShowResult.status !== 0) {
93
- console.error(String(gitShowResult.stderr));
94
- continue;
95
- }
96
-
97
- const baseFileContents = gitShowResult.stdout;
98
- const base = tmp.fileSync().name;
99
- writeFileSync(base, baseFileContents);
100
-
101
- // Run the merge with `git merge-file`
102
- const mergeFileResult = spawnSync('git', ['merge-file', to, base, from], {
103
- stdio: 'pipe',
104
- });
105
-
106
- if (mergeFileResult.status !== 0) {
107
- console.error(String(mergeFileResult.stderr));
108
- }
109
-}
scripts/merge-fork/replace-fork.js
deleted
-118
@@ -1,118 +0,0 @@
1
-'use strict';
2
-
3
-/* eslint-disable no-for-of-loops/no-for-of-loops */
4
-
5
-// Copies the contents of the new fork into the old fork
6
-
7
-const chalk = require('chalk');
8
-const {promisify} = require('util');
9
-const glob = promisify(require('glob'));
10
-const {execSync, spawnSync} = require('child_process');
11
-const fs = require('fs');
12
-const minimist = require('minimist');
13
-
14
-const stat = promisify(fs.stat);
15
-const copyFile = promisify(fs.copyFile);
16
-
17
-const argv = minimist(process.argv.slice(2), {
18
- boolean: ['reverse'],
19
-});
20
-
21
-async function main() {
22
- const status = execSync('git status').toString();
23
- const hadUnstagedChanges = status.includes('Changes not staged for commit');
24
- if (hadUnstagedChanges) {
25
- const readline = require('readline');
26
- const rl = readline.createInterface({
27
- input: process.stdin,
28
- output: process.stdout,
29
- });
30
-
31
- await new Promise(resolve => {
32
- rl.question(
33
- `\n${chalk.yellow.bold(
34
- 'Unstaged changes were found in repository.'
35
- )} Do you want to continue? (Y/n) `,
36
- input => {
37
- switch (input.trim().toLowerCase()) {
38
- case '':
39
- case 'y':
40
- case 'yes':
41
- resolve();
42
- break;
43
- default:
44
- console.log('No modifications were made.');
45
- process.exit(0);
46
- break;
47
- }
48
- }
49
- );
50
- });
51
- }
52
-
53
- const oldFilenames = await glob('packages/react-reconciler/**/*.old.js');
54
- await Promise.all(oldFilenames.map(unforkFile));
55
-
56
- // Use ESLint to autofix imports
57
- const command = spawnSync('yarn', ['linc', '--fix'], {
58
- stdio: ['inherit', 'inherit', 'pipe'],
59
- });
60
- if (command.status === 1) {
61
- console.log(
62
- chalk.bold.red('\nreplace-fork script failed with the following error:')
63
- );
64
- console.error(Error(command.stderr));
65
-
66
- // If eslint crashes, it may not have successfully fixed all the imports,
67
- // which would leave the reconciler files in an inconsistent stat.
68
- // It would be nice to clean up the working directory in this case,
69
- // but it's only safe to do that if we aren't going to override any previous changes.
70
- if (!hadUnstagedChanges) {
71
- spawnSync('git', ['checkout', '.']);
72
- } else {
73
- console.log(
74
- `\n${chalk.yellow.bold(
75
- 'Unstaged changes were present when `replace-fork` was run.'
76
- )} ` +
77
- `To cleanup the repository run:\n ${chalk.bold(
78
- 'git checkout packages/react-reconciler'
79
- )}`
80
- );
81
- }
82
-
83
- process.exit(1);
84
- } else {
85
- process.exit(0);
86
- }
87
-}
88
-
89
-async function unforkFile(oldFilename) {
90
- let oldStats;
91
- try {
92
- oldStats = await stat(oldFilename);
93
- } catch {
94
- return;
95
- }
96
- if (!oldStats.isFile()) {
97
- return;
98
- }
99
-
100
- const newFilename = oldFilename.replace(/\.old.js$/, '.new.js');
101
- let newStats;
102
- try {
103
- newStats = await stat(newFilename);
104
- } catch {
105
- return;
106
- }
107
- if (!newStats.isFile()) {
108
- return;
109
- }
110
-
111
- if (argv.reverse) {
112
- await copyFile(oldFilename, newFilename);
113
- } else {
114
- await copyFile(newFilename, oldFilename);
115
- }
116
-}
117
-
118
-main();
scripts/rollup/build.js
-3
@@ -361,9 +361,6 @@ function getPlugins(
361
__UMD__: isUMDBundle ? 'true' : 'false',
362
'process.env.NODE_ENV': isProduction ? "'production'" : "'development'",
363
__EXPERIMENTAL__,
364
- // Enable forked reconciler.
365
- // NOTE: I did not put much thought into how to configure this.
366
- __VARIANT__: bundle.enableNewReconciler === true,
364
}),
365
// The CommonJS plugin *only* exists to pull "art" into "react-art".
366
// I'm going to port "art" to ES modules to avoid this problem.
scripts/rollup/bundles.js
-1
@@ -169,7 +169,6 @@ const bundles = [
169
bundleTypes: [FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING],
170
entry: 'react-dom',
171
global: 'ReactDOMForked',
172
- enableNewReconciler: true,
172
minifyWithProdErrorCodes: true,
173
wrapWithModuleBoundaries: true,
174
externals: ['react'],
scripts/rollup/forks.js
-60
@@ -224,66 +224,6 @@ const forks = Object.freeze({
224
}
225
},
226
227
- './packages/react-reconciler/src/ReactFiberReconciler.js': (
228
- bundleType,
229
- entry,
230
- dependencies,
231
- moduleType,
232
- bundle
233
- ) => {
234
- if (bundle.enableNewReconciler) {
235
- switch (bundleType) {
236
- case FB_WWW_DEV:
237
- case FB_WWW_PROD:
238
- case FB_WWW_PROFILING:
239
- // Use the forked version of the reconciler
240
- return './packages/react-reconciler/src/ReactFiberReconciler.new.js';
241
- }
242
- }
243
- // Otherwise, use the non-forked version.
244
- return './packages/react-reconciler/src/ReactFiberReconciler.old.js';
245
- },
246
-
247
- './packages/react-reconciler/src/ReactEventPriorities.js': (
248
- bundleType,
249
- entry,
250
- dependencies,
251
- moduleType,
252
- bundle
253
- ) => {
254
- if (bundle.enableNewReconciler) {
255
- switch (bundleType) {
256
- case FB_WWW_DEV:
257
- case FB_WWW_PROD:
258
- case FB_WWW_PROFILING:
259
- // Use the forked version of the reconciler
260
- return './packages/react-reconciler/src/ReactEventPriorities.new.js';
261
- }
262
- }
263
- // Otherwise, use the non-forked version.
264
- return './packages/react-reconciler/src/ReactEventPriorities.old.js';
265
- },
266
-
267
- './packages/react-reconciler/src/ReactFiberHotReloading.js': (
268
- bundleType,
269
- entry,
270
- dependencies,
271
- moduleType,
272
- bundle
273
- ) => {
274
- if (bundle.enableNewReconciler) {
275
- switch (bundleType) {
276
- case FB_WWW_DEV:
277
- case FB_WWW_PROD:
278
- case FB_WWW_PROFILING:
279
- // Use the forked version of the reconciler
280
- return './packages/react-reconciler/src/ReactFiberHotReloading.new.js';
281
- }
282
- }
283
- // Otherwise, use the non-forked version.
284
- return './packages/react-reconciler/src/ReactFiberHotReloading.old.js';
285
- },
286
-
227
// Different dialogs for caught errors.
228
'./packages/react-reconciler/src/ReactFiberErrorDialog.js': (
229
bundleType,