From 420f0b7fa1fcc609fc7b438c4599d0f76fab4bc0 Mon Sep 17 00:00:00 2001 From: Jan Kassens Date: Thu, 1 Dec 2022 23:06:25 -0500 Subject: [PATCH] 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 --- .circleci/config.yml | 34 - .eslintrc.js | 8 - package.json | 2 - packages/react-art/src/ReactART.js | 2 +- packages/react-art/src/ReactARTHostConfig.js | 2 +- .../src/client/ReactDOMFloatClient.js | 2 +- .../src/client/ReactDOMHostConfig.js | 4 +- .../src/events/ReactDOMEventListener.js | 4 +- .../src/events/ReactDOMEventReplaying.js | 4 +- packages/react-dom/index.classic.fb.js | 1 - packages/react-dom/index.js | 1 - packages/react-dom/index.modern.fb.js | 1 - .../react-dom-server-rendering-stub-test.js | 1 - packages/react-dom/src/client/ReactDOM.js | 7 +- .../react-dom/src/client/ReactDOMLegacy.js | 2 +- packages/react-dom/src/client/ReactDOMRoot.js | 2 +- .../react-dom/unstable_testing.classic.fb.js | 2 +- .../unstable_testing.experimental.js | 2 +- packages/react-dom/unstable_testing.js | 2 +- .../react-dom/unstable_testing.modern.fb.js | 2 +- .../react-native-renderer/src/ReactFabric.js | 2 +- .../src/ReactFabricHostConfig.js | 2 +- .../src/ReactNativeHostConfig.js | 2 +- .../src/ReactNativeRenderer.js | 2 +- .../src/createReactNoop.js | 2 +- packages/react-reconciler/index.js | 2 +- .../src/ReactChildFiber.new.js | 1411 ------ .../src/ReactEventPriorities.js | 74 - .../src/ReactEventPriorities.new.js | 82 - .../react-reconciler/src/ReactFiber.new.js | 910 ---- .../react-reconciler/src/ReactFiberAct.new.js | 57 - .../src/ReactFiberBeginWork.new.js | 4212 ---------------- .../src/ReactFiberBeginWork.old.js | 2 +- .../src/ReactFiberCache.new.js | 41 - .../src/ReactFiberCacheComponent.new.js | 147 - .../src/ReactFiberClassComponent.new.js | 1248 ----- .../src/ReactFiberClassUpdateQueue.new.js | 742 --- .../src/ReactFiberCommitWork.new.js | 4450 ----------------- .../src/ReactFiberCompleteWork.new.js | 1686 ------- .../src/ReactFiberConcurrentUpdates.new.js | 288 -- .../src/ReactFiberContext.new.js | 343 -- .../src/ReactFiberDevToolsHook.new.js | 540 -- .../src/ReactFiberHiddenContext.new.js | 71 - .../src/ReactFiberHooks.new.js | 4099 --------------- .../src/ReactFiberHooks.old.js | 23 - .../src/ReactFiberHostContext.js | 31 - .../src/ReactFiberHostContext.new.js | 109 - .../src/ReactFiberHotReloading.js | 93 - .../src/ReactFiberHotReloading.new.js | 487 -- .../src/ReactFiberHotReloading.old.js | 30 +- .../src/ReactFiberHydrationContext.new.js | 771 --- .../src/ReactFiberLane.new.js | 924 ---- .../src/ReactFiberLazyComponent.new.js | 25 - .../src/ReactFiberNewContext.new.js | 706 --- .../src/ReactFiberOffscreenComponent.js | 4 +- .../src/ReactFiberReconciler.js | 202 - .../src/ReactFiberReconciler.new.js | 845 ---- .../src/ReactFiberRoot.new.js | 204 - .../src/ReactFiberScope.new.js | 199 - .../src/ReactFiberShellHydration.js | 2 +- .../src/ReactFiberStack.new.js | 97 - .../src/ReactFiberSuspenseComponent.new.js | 113 - .../src/ReactFiberSuspenseContext.new.js | 182 - .../src/ReactFiberSyncTaskQueue.new.js | 88 - .../src/ReactFiberThenable.new.js | 175 - .../src/ReactFiberThrow.new.js | 529 -- .../ReactFiberTracingMarkerComponent.new.js | 271 - .../src/ReactFiberTransition.js | 19 - .../src/ReactFiberTransition.new.js | 201 - .../src/ReactFiberTransition.old.js | 10 + .../src/ReactFiberTransitionPool.old.js | 154 - .../src/ReactFiberTreeContext.new.js | 289 -- .../src/ReactFiberUnwindWork.new.js | 285 -- .../src/ReactFiberWorkLoop.new.js | 4014 --------------- .../src/ReactFiberWorkLoop.old.js | 5 +- .../src/ReactInternalTypes.js | 8 +- .../src/ReactMutableSource.new.js | 108 - .../src/ReactProfilerTimer.new.js | 240 - .../src/ReactReconcilerConstants.js | 2 +- .../src/ReactStrictModeWarnings.new.js | 370 -- .../ReactFiberHostContext-test.internal.js | 2 +- ...actIncrementalErrorReplay-test.internal.js | 5 +- .../__tests__/ReactUpdaters-test.internal.js | 4 - .../react-refresh/src/ReactFreshRuntime.js | 2 +- .../src/ReactTestHostConfig.js | 2 +- .../src/ReactTestRenderer.js | 2 +- packages/react/src/ReactCurrentBatchConfig.js | 2 +- packages/shared/ReactFeatureFlags.js | 4 - .../forks/ReactFeatureFlags.native-fb.js | 1 - .../forks/ReactFeatureFlags.native-oss.js | 1 - .../forks/ReactFeatureFlags.test-renderer.js | 1 - .../ReactFeatureFlags.test-renderer.native.js | 1 - .../ReactFeatureFlags.test-renderer.www.js | 1 - .../shared/forks/ReactFeatureFlags.testing.js | 1 - .../forks/ReactFeatureFlags.testing.www.js | 1 - .../shared/forks/ReactFeatureFlags.www.js | 5 - .../no-cross-fork-imports-test.internal.js | 122 - .../no-cross-fork-types-test.internal.js | 89 - scripts/eslint-rules/index.js | 2 - scripts/eslint-rules/no-cross-fork-imports.js | 87 - scripts/eslint-rules/no-cross-fork-types.js | 125 - scripts/jest/TestFlags.js | 4 - scripts/jest/setupHostConfigs.js | 8 - scripts/merge-fork/README.md | 58 - scripts/merge-fork/forked-revisions | 0 scripts/merge-fork/merge-fork.js | 109 - scripts/merge-fork/replace-fork.js | 118 - scripts/rollup/build.js | 3 - scripts/rollup/bundles.js | 1 - scripts/rollup/forks.js | 60 - 110 files changed, 71 insertions(+), 33065 deletions(-) delete mode 100644 packages/react-reconciler/src/ReactChildFiber.new.js delete mode 100644 packages/react-reconciler/src/ReactEventPriorities.js delete mode 100644 packages/react-reconciler/src/ReactEventPriorities.new.js delete mode 100644 packages/react-reconciler/src/ReactFiber.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberAct.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberBeginWork.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberCache.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberCacheComponent.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberClassComponent.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberClassUpdateQueue.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberCommitWork.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberCompleteWork.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberConcurrentUpdates.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberContext.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberDevToolsHook.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberHiddenContext.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberHooks.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberHostContext.js delete mode 100644 packages/react-reconciler/src/ReactFiberHostContext.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberHotReloading.js delete mode 100644 packages/react-reconciler/src/ReactFiberHotReloading.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberHydrationContext.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberLane.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberLazyComponent.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberNewContext.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberReconciler.js delete mode 100644 packages/react-reconciler/src/ReactFiberReconciler.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberRoot.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberScope.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberStack.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberSuspenseComponent.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberSuspenseContext.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberSyncTaskQueue.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberThenable.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberThrow.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberTracingMarkerComponent.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberTransition.js delete mode 100644 packages/react-reconciler/src/ReactFiberTransition.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberTransitionPool.old.js delete mode 100644 packages/react-reconciler/src/ReactFiberTreeContext.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberUnwindWork.new.js delete mode 100644 packages/react-reconciler/src/ReactFiberWorkLoop.new.js delete mode 100644 packages/react-reconciler/src/ReactMutableSource.new.js delete mode 100644 packages/react-reconciler/src/ReactProfilerTimer.new.js delete mode 100644 packages/react-reconciler/src/ReactStrictModeWarnings.new.js delete mode 100644 scripts/eslint-rules/__tests__/no-cross-fork-imports-test.internal.js delete mode 100644 scripts/eslint-rules/__tests__/no-cross-fork-types-test.internal.js delete mode 100644 scripts/eslint-rules/no-cross-fork-imports.js delete mode 100644 scripts/eslint-rules/no-cross-fork-types.js delete mode 100644 scripts/merge-fork/README.md delete mode 100644 scripts/merge-fork/forked-revisions delete mode 100644 scripts/merge-fork/merge-fork.js delete mode 100644 scripts/merge-fork/replace-fork.js diff --git a/.circleci/config.yml b/.circleci/config.yml index 59c6d267145d8..9b222f2b64153 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -462,35 +462,6 @@ jobs: cp ./scripts/release/ci-npmrc ~/.npmrc scripts/release/publish.js --ci --tags << parameters.dist_tag >> - # We don't always keep the reconciler forks in sync (otherwise it we wouldn't - # have forked it) but during periods when they are meant to be in sync, we - # use this job to confirm there are no differences. - sync_reconciler_forks: - docker: *docker - environment: *environment - steps: - - checkout - - *restore_node_modules - - run: - name: Fetch revisions that contain an intentional fork - # This will fetch each revision listed in the `forked-revisions` file, - # which may be necessary if it's not part of main. For example, it - # may have been part of a PR branch that was squashed on merge. - command: | - cut -d " " -f 1 scripts/merge-fork/forked-revisions | xargs -r git fetch origin - - run: - name: Revert forked revisions - # This will revert the changes without committing. At the end, it's - # expected that both forks will be identical. - command: | - cut -d " " -f 1 scripts/merge-fork/forked-revisions | xargs -r git revert --no-commit - - run: - name: Confirm reconciler forks are the same - command: | - yarn replace-fork - 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) - - workflows: version: 2 @@ -506,11 +477,6 @@ workflows: - yarn_flow: requires: - setup - # NOTE: This job is only enabled when we want the forks to be in sync. - # When the forks intentionally diverge, comment out the job to disable it. - - sync_reconciler_forks: - requires: - - setup - check_generated_fizz_runtime: requires: - setup diff --git a/.eslintrc.js b/.eslintrc.js index c5350074671ed..c14105b0c08a4 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -112,14 +112,6 @@ module.exports = { 'react-internal/no-to-warn-dev-within-to-throw': ERROR, 'react-internal/warning-args': ERROR, 'react-internal/no-production-logging': ERROR, - 'react-internal/no-cross-fork-imports': ERROR, - 'react-internal/no-cross-fork-types': [ - ERROR, - { - old: [], - new: [], - }, - ], }, overrides: [ diff --git a/package.json b/package.json index 3c72f0d80a83e..13bc6c18bdb54 100644 --- a/package.json +++ b/package.json @@ -140,8 +140,6 @@ "prettier": "node ./scripts/prettier/index.js write-changed", "prettier-all": "node ./scripts/prettier/index.js write", "version-check": "node ./scripts/tasks/version-check.js", - "merge-fork": "node ./scripts/merge-fork/merge-fork.js", - "replace-fork": "node ./scripts/merge-fork/replace-fork.js", "publish-prereleases": "node ./scripts/release/publish-using-ci-workflow.js", "download-build": "node ./scripts/release/download-experimental-build.js", "download-build-for-head": "node ./scripts/release/download-experimental-build.js --commit=$(git rev-parse HEAD)", diff --git a/packages/react-art/src/ReactART.js b/packages/react-art/src/ReactART.js index 2bd66260f6d78..6ad1dfb6753c2 100644 --- a/packages/react-art/src/ReactART.js +++ b/packages/react-art/src/ReactART.js @@ -12,7 +12,7 @@ import { createContainer, updateContainer, injectIntoDevTools, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; import Transform from 'art/core/transform'; import Mode from 'art/modes/current'; import FastNoSideEffects from 'art/modes/fast-noSideEffects'; diff --git a/packages/react-art/src/ReactARTHostConfig.js b/packages/react-art/src/ReactARTHostConfig.js index 493d2521ce5a5..101f8213bd325 100644 --- a/packages/react-art/src/ReactARTHostConfig.js +++ b/packages/react-art/src/ReactARTHostConfig.js @@ -10,7 +10,7 @@ import Mode from 'art/modes/current'; import {TYPES, EVENT_TYPES, childrenAsString} from './ReactARTInternals'; -import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; const pooledTransform = new Transform(); diff --git a/packages/react-dom-bindings/src/client/ReactDOMFloatClient.js b/packages/react-dom-bindings/src/client/ReactDOMFloatClient.js index b09789d436fb7..6e8e737070e6e 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMFloatClient.js +++ b/packages/react-dom-bindings/src/client/ReactDOMFloatClient.js @@ -29,7 +29,7 @@ import { markNodeAsResource, } from './ReactDOMComponentTree'; import {HTML_NAMESPACE, SVG_NAMESPACE} from '../shared/DOMNamespaces'; -import {getCurrentRootHostContainer} from 'react-reconciler/src/ReactFiberHostContext'; +import {getCurrentRootHostContainer} from 'react-reconciler/src/ReactFiberHostContext.old'; // The resource types we support. currently they match the form for the as argument. // In the future this may need to change, especially when modules / scripts are supported diff --git a/packages/react-dom-bindings/src/client/ReactDOMHostConfig.js b/packages/react-dom-bindings/src/client/ReactDOMHostConfig.js index db42f2ed243a3..e10a8772d04aa 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMHostConfig.js +++ b/packages/react-dom-bindings/src/client/ReactDOMHostConfig.js @@ -7,7 +7,7 @@ * @flow */ -import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; import type {DOMEventName} from '../events/DOMEventNames'; import type {Fiber, FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import type { @@ -81,7 +81,7 @@ import { } from 'react-reconciler/src/ReactWorkTags'; import {listenToAllSupportedEvents} from '../events/DOMPluginEventSystem'; -import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; // TODO: Remove this deep import when we delete the legacy root API import {ConcurrentMode, NoMode} from 'react-reconciler/src/ReactTypeOfMode'; diff --git a/packages/react-dom-bindings/src/events/ReactDOMEventListener.js b/packages/react-dom-bindings/src/events/ReactDOMEventListener.js index 2eca510571f12..241a7a1e48f82 100644 --- a/packages/react-dom-bindings/src/events/ReactDOMEventListener.js +++ b/packages/react-dom-bindings/src/events/ReactDOMEventListener.js @@ -7,7 +7,7 @@ * @flow */ -import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; import type {AnyNativeEvent} from '../events/PluginModuleType'; import type {Fiber, FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig'; @@ -52,7 +52,7 @@ import { IdleEventPriority, getCurrentUpdatePriority, setCurrentUpdatePriority, -} from 'react-reconciler/src/ReactEventPriorities'; +} from 'react-reconciler/src/ReactEventPriorities.old'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import {isRootDehydrated} from 'react-reconciler/src/ReactFiberShellHydration'; diff --git a/packages/react-dom-bindings/src/events/ReactDOMEventReplaying.js b/packages/react-dom-bindings/src/events/ReactDOMEventReplaying.js index a10524fdb4966..8157f9d3f07bd 100644 --- a/packages/react-dom-bindings/src/events/ReactDOMEventReplaying.js +++ b/packages/react-dom-bindings/src/events/ReactDOMEventReplaying.js @@ -12,7 +12,7 @@ import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig'; import type {DOMEventName} from '../events/DOMEventNames'; import type {EventSystemFlags} from './EventSystemFlags'; import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; -import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; import {enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay} from 'shared/ReactFeatureFlags'; import { @@ -35,7 +35,7 @@ import { getClosestInstanceFromNode, } from '../client/ReactDOMComponentTree'; import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags'; -import {isHigherEventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import {isHigherEventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; import {isRootDehydrated} from 'react-reconciler/src/ReactFiberShellHydration'; let _attemptSynchronousHydration: (fiber: Object) => void; diff --git a/packages/react-dom/index.classic.fb.js b/packages/react-dom/index.classic.fb.js index 4d05d28ae3348..3b559bb43c419 100644 --- a/packages/react-dom/index.classic.fb.js +++ b/packages/react-dom/index.classic.fb.js @@ -30,7 +30,6 @@ export { unstable_batchedUpdates, unstable_createEventHandle, unstable_flushControlled, - unstable_isNewReconciler, unstable_renderSubtreeIntoContainer, unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority. preinit, diff --git a/packages/react-dom/index.js b/packages/react-dom/index.js index a5627c22e7a3e..1ea57d00072e5 100644 --- a/packages/react-dom/index.js +++ b/packages/react-dom/index.js @@ -22,7 +22,6 @@ export { unstable_batchedUpdates, unstable_createEventHandle, unstable_flushControlled, - unstable_isNewReconciler, unstable_renderSubtreeIntoContainer, unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority. preinit, diff --git a/packages/react-dom/index.modern.fb.js b/packages/react-dom/index.modern.fb.js index 8422e6b9ac602..deddb938ec987 100644 --- a/packages/react-dom/index.modern.fb.js +++ b/packages/react-dom/index.modern.fb.js @@ -16,7 +16,6 @@ export { unstable_batchedUpdates, unstable_createEventHandle, unstable_flushControlled, - unstable_isNewReconciler, unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority. preinit, preload, diff --git a/packages/react-dom/src/__tests__/react-dom-server-rendering-stub-test.js b/packages/react-dom/src/__tests__/react-dom-server-rendering-stub-test.js index 153ea2d310bf2..a5772f968ff6c 100644 --- a/packages/react-dom/src/__tests__/react-dom-server-rendering-stub-test.js +++ b/packages/react-dom/src/__tests__/react-dom-server-rendering-stub-test.js @@ -36,7 +36,6 @@ describe('react-dom-server-rendering-stub', () => { expect(ReactDOM.unstable_batchedUpdates).toBe(undefined); expect(ReactDOM.unstable_createEventHandle).toBe(undefined); expect(ReactDOM.unstable_flushControlled).toBe(undefined); - expect(ReactDOM.unstable_isNewReconciler).toBe(undefined); expect(ReactDOM.unstable_renderSubtreeIntoContainer).toBe(undefined); expect(ReactDOM.unstable_runWithPriority).toBe(undefined); }); diff --git a/packages/react-dom/src/client/ReactDOM.js b/packages/react-dom/src/client/ReactDOM.js index a2246229b115f..316c4c5e0338e 100644 --- a/packages/react-dom/src/client/ReactDOM.js +++ b/packages/react-dom/src/client/ReactDOM.js @@ -43,15 +43,14 @@ import { attemptDiscreteHydration, attemptContinuousHydration, attemptHydrationAtCurrentPriority, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; import { runWithPriority, getCurrentUpdatePriority, -} from 'react-reconciler/src/ReactEventPriorities'; +} from 'react-reconciler/src/ReactEventPriorities.old'; import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal'; import {canUseDOM} from 'shared/ExecutionEnvironment'; import ReactVersion from 'shared/ReactVersion'; -import {enableNewReconciler} from 'shared/ReactFeatureFlags'; import { getClosestInstanceFromNode, @@ -256,5 +255,3 @@ if (__DEV__) { } } } - -export const unstable_isNewReconciler = enableNewReconciler; diff --git a/packages/react-dom/src/client/ReactDOMLegacy.js b/packages/react-dom/src/client/ReactDOMLegacy.js index 39e00ffc89a68..80e3315114ccb 100644 --- a/packages/react-dom/src/client/ReactDOMLegacy.js +++ b/packages/react-dom/src/client/ReactDOMLegacy.js @@ -37,7 +37,7 @@ import { getPublicRootInstance, findHostInstance, findHostInstanceWithWarning, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; import {LegacyRoot} from 'react-reconciler/src/ReactRootTags'; import getComponentNameFromType from 'shared/getComponentNameFromType'; import ReactSharedInternals from 'shared/ReactSharedInternals'; diff --git a/packages/react-dom/src/client/ReactDOMRoot.js b/packages/react-dom/src/client/ReactDOMRoot.js index a4b901d156d78..a2b4994952a12 100644 --- a/packages/react-dom/src/client/ReactDOMRoot.js +++ b/packages/react-dom/src/client/ReactDOMRoot.js @@ -76,7 +76,7 @@ import { registerMutableSourceForHydration, flushSync, isAlreadyRendering, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; import {ConcurrentRoot} from 'react-reconciler/src/ReactRootTags'; /* global reportError */ diff --git a/packages/react-dom/unstable_testing.classic.fb.js b/packages/react-dom/unstable_testing.classic.fb.js index 2f623787958d3..4c4700f6aa7b5 100644 --- a/packages/react-dom/unstable_testing.classic.fb.js +++ b/packages/react-dom/unstable_testing.classic.fb.js @@ -19,4 +19,4 @@ export { findBoundingRects, focusWithin, observeVisibleRects, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; diff --git a/packages/react-dom/unstable_testing.experimental.js b/packages/react-dom/unstable_testing.experimental.js index 3ed081d85b9b1..dc12b7042c38b 100644 --- a/packages/react-dom/unstable_testing.experimental.js +++ b/packages/react-dom/unstable_testing.experimental.js @@ -19,4 +19,4 @@ export { findBoundingRects, focusWithin, observeVisibleRects, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; diff --git a/packages/react-dom/unstable_testing.js b/packages/react-dom/unstable_testing.js index fdad56d13c77d..aaa570ca28985 100644 --- a/packages/react-dom/unstable_testing.js +++ b/packages/react-dom/unstable_testing.js @@ -19,4 +19,4 @@ export { findBoundingRects, focusWithin, observeVisibleRects, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; diff --git a/packages/react-dom/unstable_testing.modern.fb.js b/packages/react-dom/unstable_testing.modern.fb.js index c0a0e45ad79ca..cb9a8309d8e1a 100644 --- a/packages/react-dom/unstable_testing.modern.fb.js +++ b/packages/react-dom/unstable_testing.modern.fb.js @@ -19,4 +19,4 @@ export { findBoundingRects, focusWithin, observeVisibleRects, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; diff --git a/packages/react-native-renderer/src/ReactFabric.js b/packages/react-native-renderer/src/ReactFabric.js index 1e3d299ece9e8..fa26a33099228 100644 --- a/packages/react-native-renderer/src/ReactFabric.js +++ b/packages/react-native-renderer/src/ReactFabric.js @@ -22,7 +22,7 @@ import { updateContainer, injectIntoDevTools, getPublicRootInstance, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal'; import {setBatchingImplementation} from './legacy-events/ReactGenericBatching'; diff --git a/packages/react-native-renderer/src/ReactFabricHostConfig.js b/packages/react-native-renderer/src/ReactFabricHostConfig.js index 078bf1f11ac6f..43bb2f646d3cd 100644 --- a/packages/react-native-renderer/src/ReactFabricHostConfig.js +++ b/packages/react-native-renderer/src/ReactFabricHostConfig.js @@ -26,7 +26,7 @@ import {dispatchEvent} from './ReactFabricEventEmitter'; import { DefaultEventPriority, DiscreteEventPriority, -} from 'react-reconciler/src/ReactEventPriorities'; +} from 'react-reconciler/src/ReactEventPriorities.old'; // Modules provided by RN: import { diff --git a/packages/react-native-renderer/src/ReactNativeHostConfig.js b/packages/react-native-renderer/src/ReactNativeHostConfig.js index 03cfa415f6937..ae3ce588559be 100644 --- a/packages/react-native-renderer/src/ReactNativeHostConfig.js +++ b/packages/react-native-renderer/src/ReactNativeHostConfig.js @@ -24,7 +24,7 @@ import { } from './ReactNativeComponentTree'; import ReactNativeFiberHostComponent from './ReactNativeFiberHostComponent'; -import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; const {get: getViewConfigForType} = ReactNativeViewConfigRegistry; diff --git a/packages/react-native-renderer/src/ReactNativeRenderer.js b/packages/react-native-renderer/src/ReactNativeRenderer.js index d9577a6eb6d58..802cd831dd215 100644 --- a/packages/react-native-renderer/src/ReactNativeRenderer.js +++ b/packages/react-native-renderer/src/ReactNativeRenderer.js @@ -22,7 +22,7 @@ import { updateContainer, injectIntoDevTools, getPublicRootInstance, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; // TODO: direct imports like some-package/src/* are bad. Fix me. import {getStackByFiberInDevAndProd} from 'react-reconciler/src/ReactFiberComponentStack'; import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal'; diff --git a/packages/react-noop-renderer/src/createReactNoop.js b/packages/react-noop-renderer/src/createReactNoop.js index 5555657e3589c..47a62f2c15624 100644 --- a/packages/react-noop-renderer/src/createReactNoop.js +++ b/packages/react-noop-renderer/src/createReactNoop.js @@ -18,7 +18,7 @@ import type { Fiber, TransitionTracingCallbacks, } from 'react-reconciler/src/ReactInternalTypes'; -import type {UpdateQueue} from 'react-reconciler/src/ReactFiberClassUpdateQueue.new'; +import type {UpdateQueue} from 'react-reconciler/src/ReactFiberClassUpdateQueue'; import type {ReactNodeList} from 'shared/ReactTypes'; import type {RootTag} from 'react-reconciler/src/ReactRootTags'; diff --git a/packages/react-reconciler/index.js b/packages/react-reconciler/index.js index afffd715cffe5..0e41352a8c4e4 100644 --- a/packages/react-reconciler/index.js +++ b/packages/react-reconciler/index.js @@ -7,4 +7,4 @@ * @flow */ -export * from './src/ReactFiberReconciler'; +export * from './src/ReactFiberReconciler.old'; diff --git a/packages/react-reconciler/src/ReactChildFiber.new.js b/packages/react-reconciler/src/ReactChildFiber.new.js deleted file mode 100644 index ea72a3de92047..0000000000000 --- a/packages/react-reconciler/src/ReactChildFiber.new.js +++ /dev/null @@ -1,1411 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {ReactElement} from 'shared/ReactElementType'; -import type {ReactPortal} from 'shared/ReactTypes'; -import type {Fiber} from './ReactInternalTypes'; -import type {Lanes} from './ReactFiberLane.new'; - -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import { - Placement, - ChildDeletion, - Forked, - PlacementDEV, -} from './ReactFiberFlags'; -import { - getIteratorFn, - REACT_ELEMENT_TYPE, - REACT_FRAGMENT_TYPE, - REACT_PORTAL_TYPE, - REACT_LAZY_TYPE, -} from 'shared/ReactSymbols'; -import {ClassComponent, HostText, HostPortal, Fragment} from './ReactWorkTags'; -import isArray from 'shared/isArray'; -import {warnAboutStringRefs} from 'shared/ReactFeatureFlags'; -import {checkPropStringCoercion} from 'shared/CheckStringCoercion'; - -import { - createWorkInProgress, - resetWorkInProgress, - createFiberFromElement, - createFiberFromFragment, - createFiberFromText, - createFiberFromPortal, -} from './ReactFiber.new'; -import {isCompatibleFamilyForHotReloading} from './ReactFiberHotReloading.new'; -import {StrictLegacyMode} from './ReactTypeOfMode'; -import {getIsHydrating} from './ReactFiberHydrationContext.new'; -import {pushTreeFork} from './ReactFiberTreeContext.new'; - -let didWarnAboutMaps; -let didWarnAboutGenerators; -let didWarnAboutStringRefs; -let ownerHasKeyUseWarning; -let ownerHasFunctionTypeWarning; -let warnForMissingKey = (child: mixed, returnFiber: Fiber) => {}; - -if (__DEV__) { - didWarnAboutMaps = false; - didWarnAboutGenerators = false; - didWarnAboutStringRefs = {}; - - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - ownerHasKeyUseWarning = {}; - ownerHasFunctionTypeWarning = {}; - - warnForMissingKey = (child: mixed, returnFiber: Fiber) => { - if (child === null || typeof child !== 'object') { - return; - } - if (!child._store || child._store.validated || child.key != null) { - return; - } - - if (typeof child._store !== 'object') { - throw new Error( - 'React Component in warnForMissingKey should have a _store. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - // $FlowFixMe unable to narrow type from mixed to writable object - child._store.validated = true; - - const componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (ownerHasKeyUseWarning[componentName]) { - return; - } - ownerHasKeyUseWarning[componentName] = true; - - console.error( - 'Each child in a list should have a unique ' + - '"key" prop. See https://reactjs.org/link/warning-keys for ' + - 'more information.', - ); - }; -} - -function isReactClass(type) { - return type.prototype && type.prototype.isReactComponent; -} - -function coerceRef( - returnFiber: Fiber, - current: Fiber | null, - element: ReactElement, -) { - const mixedRef = element.ref; - if ( - mixedRef !== null && - typeof mixedRef !== 'function' && - typeof mixedRef !== 'object' - ) { - if (__DEV__) { - // TODO: Clean this up once we turn on the string ref warning for - // everyone, because the strict mode case will no longer be relevant - if ( - (returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && - // We warn in ReactElement.js if owner and self are equal for string refs - // because these cannot be automatically converted to an arrow function - // using a codemod. Therefore, we don't have to warn about string refs again. - !( - element._owner && - element._self && - element._owner.stateNode !== element._self - ) && - // Will already throw with "Function components cannot have string refs" - !( - element._owner && - ((element._owner: any): Fiber).tag !== ClassComponent - ) && - // Will already warn with "Function components cannot be given refs" - !(typeof element.type === 'function' && !isReactClass(element.type)) && - // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set" - element._owner - ) { - const componentName = - getComponentNameFromFiber(returnFiber) || 'Component'; - if (!didWarnAboutStringRefs[componentName]) { - if (warnAboutStringRefs) { - console.error( - 'Component "%s" contains the string ref "%s". Support for string refs ' + - 'will be removed in a future major release. We recommend using ' + - 'useRef() or createRef() instead. ' + - 'Learn more about using refs safely here: ' + - 'https://reactjs.org/link/strict-mode-string-ref', - componentName, - mixedRef, - ); - } else { - console.error( - 'A string ref, "%s", has been found within a strict mode tree. ' + - 'String refs are a source of potential bugs and should be avoided. ' + - 'We recommend using useRef() or createRef() instead. ' + - 'Learn more about using refs safely here: ' + - 'https://reactjs.org/link/strict-mode-string-ref', - mixedRef, - ); - } - didWarnAboutStringRefs[componentName] = true; - } - } - } - - if (element._owner) { - const owner: ?Fiber = (element._owner: any); - let inst; - if (owner) { - const ownerFiber = ((owner: any): Fiber); - - if (ownerFiber.tag !== ClassComponent) { - throw new Error( - 'Function components cannot have string refs. ' + - 'We recommend using useRef() instead. ' + - 'Learn more about using refs safely here: ' + - 'https://reactjs.org/link/strict-mode-string-ref', - ); - } - - inst = ownerFiber.stateNode; - } - - if (!inst) { - throw new Error( - `Missing owner for string ref ${mixedRef}. This error is likely caused by a ` + - 'bug in React. Please file an issue.', - ); - } - // Assigning this to a const so Flow knows it won't change in the closure - const resolvedInst = inst; - - if (__DEV__) { - checkPropStringCoercion(mixedRef, 'ref'); - } - const stringRef = '' + mixedRef; - // Check if previous string ref matches new string ref - if ( - current !== null && - current.ref !== null && - typeof current.ref === 'function' && - current.ref._stringRef === stringRef - ) { - return current.ref; - } - const ref = function(value) { - const refs = resolvedInst.refs; - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; - ref._stringRef = stringRef; - return ref; - } else { - if (typeof mixedRef !== 'string') { - throw new Error( - 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.', - ); - } - - if (!element._owner) { - throw new Error( - `Element ref was specified as a string (${mixedRef}) but no owner was set. This could happen for one of` + - ' the following reasons:\n' + - '1. You may be adding a ref to a function component\n' + - "2. You may be adding a ref to a component that was not created inside a component's render method\n" + - '3. You have multiple copies of React loaded\n' + - 'See https://reactjs.org/link/refs-must-have-owner for more information.', - ); - } - } - } - return mixedRef; -} - -function throwOnInvalidObjectType(returnFiber: Fiber, newChild: Object) { - // $FlowFixMe[method-unbinding] - const childString = Object.prototype.toString.call(newChild); - - throw new Error( - `Objects are not valid as a React child (found: ${ - childString === '[object Object]' - ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' - : childString - }). ` + - 'If you meant to render a collection of children, use an array ' + - 'instead.', - ); -} - -function warnOnFunctionType(returnFiber: Fiber) { - if (__DEV__) { - const componentName = getComponentNameFromFiber(returnFiber) || 'Component'; - - if (ownerHasFunctionTypeWarning[componentName]) { - return; - } - ownerHasFunctionTypeWarning[componentName] = true; - - console.error( - 'Functions are not valid as a React child. This may happen if ' + - 'you return a Component instead of from render. ' + - 'Or maybe you meant to call this function rather than return it.', - ); - } -} - -function resolveLazy(lazyType) { - const payload = lazyType._payload; - const init = lazyType._init; - return init(payload); -} - -type ChildReconciler = ( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - newChild: any, - lanes: Lanes, -) => Fiber | null; - -// This wrapper function exists because I expect to clone the code in each path -// to be able to optimize each path individually by branching early. This needs -// a compiler or we can do it manually. Helpers that don't need this branching -// live outside of this function. -function createChildReconciler(shouldTrackSideEffects): ChildReconciler { - function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void { - if (!shouldTrackSideEffects) { - // Noop. - return; - } - const deletions = returnFiber.deletions; - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } - } - - function deleteRemainingChildren( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - ): null { - if (!shouldTrackSideEffects) { - // Noop. - return null; - } - - // TODO: For the shouldClone case, this could be micro-optimized a bit by - // assuming that after the first child we've already added everything. - let childToDelete = currentFirstChild; - while (childToDelete !== null) { - deleteChild(returnFiber, childToDelete); - childToDelete = childToDelete.sibling; - } - return null; - } - - function mapRemainingChildren( - returnFiber: Fiber, - currentFirstChild: Fiber, - ): Map { - // Add the remaining children to a temporary map so that we can find them by - // keys quickly. Implicit (null) keys get added to this set with their index - // instead. - const existingChildren: Map = new Map(); - - let existingChild: null | Fiber = currentFirstChild; - while (existingChild !== null) { - if (existingChild.key !== null) { - existingChildren.set(existingChild.key, existingChild); - } else { - existingChildren.set(existingChild.index, existingChild); - } - existingChild = existingChild.sibling; - } - return existingChildren; - } - - function useFiber(fiber: Fiber, pendingProps: mixed): Fiber { - // We currently set sibling to null and index to 0 here because it is easy - // to forget to do before returning it. E.g. for the single child case. - const clone = createWorkInProgress(fiber, pendingProps); - clone.index = 0; - clone.sibling = null; - return clone; - } - - function placeChild( - newFiber: Fiber, - lastPlacedIndex: number, - newIndex: number, - ): number { - newFiber.index = newIndex; - if (!shouldTrackSideEffects) { - // During hydration, the useId algorithm needs to know which fibers are - // part of a list of children (arrays, iterators). - newFiber.flags |= Forked; - return lastPlacedIndex; - } - const current = newFiber.alternate; - if (current !== null) { - const oldIndex = current.index; - if (oldIndex < lastPlacedIndex) { - // This is a move. - newFiber.flags |= Placement | PlacementDEV; - return lastPlacedIndex; - } else { - // This item can stay in place. - return oldIndex; - } - } else { - // This is an insertion. - newFiber.flags |= Placement | PlacementDEV; - return lastPlacedIndex; - } - } - - function placeSingleChild(newFiber: Fiber): Fiber { - // This is simpler for the single child case. We only need to do a - // placement for inserting new children. - if (shouldTrackSideEffects && newFiber.alternate === null) { - newFiber.flags |= Placement | PlacementDEV; - } - return newFiber; - } - - function updateTextNode( - returnFiber: Fiber, - current: Fiber | null, - textContent: string, - lanes: Lanes, - ) { - if (current === null || current.tag !== HostText) { - // Insert - const created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - // Update - const existing = useFiber(current, textContent); - existing.return = returnFiber; - return existing; - } - } - - function updateElement( - returnFiber: Fiber, - current: Fiber | null, - element: ReactElement, - lanes: Lanes, - ): Fiber { - const elementType = element.type; - if (elementType === REACT_FRAGMENT_TYPE) { - return updateFragment( - returnFiber, - current, - element.props.children, - lanes, - element.key, - ); - } - if (current !== null) { - if ( - current.elementType === elementType || - // Keep this check inline so it only runs on the false path: - (__DEV__ - ? isCompatibleFamilyForHotReloading(current, element) - : false) || - // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - (typeof elementType === 'object' && - elementType !== null && - elementType.$$typeof === REACT_LAZY_TYPE && - resolveLazy(elementType) === current.type) - ) { - // Move based on index - const existing = useFiber(current, element.props); - existing.ref = coerceRef(returnFiber, current, element); - existing.return = returnFiber; - if (__DEV__) { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } - } - // Insert - const created = createFiberFromElement(element, returnFiber.mode, lanes); - created.ref = coerceRef(returnFiber, current, element); - created.return = returnFiber; - return created; - } - - function updatePortal( - returnFiber: Fiber, - current: Fiber | null, - portal: ReactPortal, - lanes: Lanes, - ): Fiber { - if ( - current === null || - current.tag !== HostPortal || - current.stateNode.containerInfo !== portal.containerInfo || - current.stateNode.implementation !== portal.implementation - ) { - // Insert - const created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } else { - // Update - const existing = useFiber(current, portal.children || []); - existing.return = returnFiber; - return existing; - } - } - - function updateFragment( - returnFiber: Fiber, - current: Fiber | null, - fragment: Iterable, - lanes: Lanes, - key: null | string, - ): Fiber { - if (current === null || current.tag !== Fragment) { - // Insert - const created = createFiberFromFragment( - fragment, - returnFiber.mode, - lanes, - key, - ); - created.return = returnFiber; - return created; - } else { - // Update - const existing = useFiber(current, fragment); - existing.return = returnFiber; - return existing; - } - } - - function createChild( - returnFiber: Fiber, - newChild: any, - lanes: Lanes, - ): Fiber | null { - if ( - (typeof newChild === 'string' && newChild !== '') || - typeof newChild === 'number' - ) { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - const created = createFiberFromText( - '' + newChild, - returnFiber.mode, - lanes, - ); - created.return = returnFiber; - return created; - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - const created = createFiberFromElement( - newChild, - returnFiber.mode, - lanes, - ); - created.ref = coerceRef(returnFiber, null, newChild); - created.return = returnFiber; - return created; - } - case REACT_PORTAL_TYPE: { - const created = createFiberFromPortal( - newChild, - returnFiber.mode, - lanes, - ); - created.return = returnFiber; - return created; - } - case REACT_LAZY_TYPE: { - const payload = newChild._payload; - const init = newChild._init; - return createChild(returnFiber, init(payload), lanes); - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - const created = createFiberFromFragment( - newChild, - returnFiber.mode, - lanes, - null, - ); - created.return = returnFiber; - return created; - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - if (__DEV__) { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - - function updateSlot( - returnFiber: Fiber, - oldFiber: Fiber | null, - newChild: any, - lanes: Lanes, - ): Fiber | null { - // Update the fiber if the keys match, otherwise return null. - - const key = oldFiber !== null ? oldFiber.key : null; - - if ( - (typeof newChild === 'string' && newChild !== '') || - typeof newChild === 'number' - ) { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - if (key !== null) { - return null; - } - return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - if (newChild.key === key) { - return updateElement(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - case REACT_PORTAL_TYPE: { - if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, lanes); - } else { - return null; - } - } - case REACT_LAZY_TYPE: { - const payload = newChild._payload; - const init = newChild._init; - return updateSlot(returnFiber, oldFiber, init(payload), lanes); - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - if (key !== null) { - return null; - } - - return updateFragment(returnFiber, oldFiber, newChild, lanes, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - if (__DEV__) { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - - function updateFromMap( - existingChildren: Map, - returnFiber: Fiber, - newIdx: number, - newChild: any, - lanes: Lanes, - ): Fiber | null { - if ( - (typeof newChild === 'string' && newChild !== '') || - typeof newChild === 'number' - ) { - // Text nodes don't have keys, so we neither have to check the old nor - // new node for the key. If both are text nodes, they match. - const matchedFiber = existingChildren.get(newIdx) || null; - return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - const matchedFiber = - existingChildren.get( - newChild.key === null ? newIdx : newChild.key, - ) || null; - return updateElement(returnFiber, matchedFiber, newChild, lanes); - } - case REACT_PORTAL_TYPE: { - const matchedFiber = - existingChildren.get( - newChild.key === null ? newIdx : newChild.key, - ) || null; - return updatePortal(returnFiber, matchedFiber, newChild, lanes); - } - case REACT_LAZY_TYPE: - const payload = newChild._payload; - const init = newChild._init; - return updateFromMap( - existingChildren, - returnFiber, - newIdx, - init(payload), - lanes, - ); - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - const matchedFiber = existingChildren.get(newIdx) || null; - return updateFragment(returnFiber, matchedFiber, newChild, lanes, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - if (__DEV__) { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - return null; - } - - /** - * Warns if there is a duplicate or missing key - */ - function warnOnInvalidKey( - child: mixed, - knownKeys: Set | null, - returnFiber: Fiber, - ): Set | null { - if (__DEV__) { - if (typeof child !== 'object' || child === null) { - return knownKeys; - } - switch (child.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - warnForMissingKey(child, returnFiber); - const key = child.key; - if (typeof key !== 'string') { - break; - } - if (knownKeys === null) { - knownKeys = new Set(); - knownKeys.add(key); - break; - } - if (!knownKeys.has(key)) { - knownKeys.add(key); - break; - } - console.error( - 'Encountered two children with the same key, `%s`. ' + - 'Keys should be unique so that components maintain their identity ' + - 'across updates. Non-unique keys may cause children to be ' + - 'duplicated and/or omitted — the behavior is unsupported and ' + - 'could change in a future version.', - key, - ); - break; - case REACT_LAZY_TYPE: - const payload = child._payload; - const init = (child._init: any); - warnOnInvalidKey(init(payload), knownKeys, returnFiber); - break; - default: - break; - } - } - return knownKeys; - } - - function reconcileChildrenArray( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - newChildren: Array, - lanes: Lanes, - ): Fiber | null { - // This algorithm can't optimize by searching from both ends since we - // don't have backpointers on fibers. I'm trying to see how far we can get - // with that model. If it ends up not being worth the tradeoffs, we can - // add it later. - - // Even with a two ended optimization, we'd want to optimize for the case - // where there are few changes and brute force the comparison instead of - // going for the Map. It'd like to explore hitting that path first in - // forward-only mode and only go for the Map once we notice that we need - // lots of look ahead. This doesn't handle reversal as well as two ended - // search but that's unusual. Besides, for the two ended optimization to - // work on Iterables, we'd need to copy the whole set. - - // In this first iteration, we'll just live with hitting the bad case - // (adding everything to a Map) in for every insert/move. - - // If you change this code, also update reconcileChildrenIterator() which - // uses the same algorithm. - - if (__DEV__) { - // First, validate keys. - let knownKeys = null; - for (let i = 0; i < newChildren.length; i++) { - const child = newChildren[i]; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - - let resultingFirstChild: Fiber | null = null; - let previousNewFiber: Fiber | null = null; - - let oldFiber = currentFirstChild; - let lastPlacedIndex = 0; - let newIdx = 0; - let nextOldFiber = null; - for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - const newFiber = updateSlot( - returnFiber, - oldFiber, - newChildren[newIdx], - lanes, - ); - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (newIdx === newChildren.length) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - if (getIsHydrating()) { - const numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; newIdx < newChildren.length; newIdx++) { - const newFiber = createChild(returnFiber, newChildren[newIdx], lanes); - if (newFiber === null) { - continue; - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - if (getIsHydrating()) { - const numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - - // Add all children to a key map for quick lookups. - const existingChildren = mapRemainingChildren(returnFiber, oldFiber); - - // Keep scanning and use the map to restore deleted items as moves. - for (; newIdx < newChildren.length; newIdx++) { - const newFiber = updateFromMap( - existingChildren, - returnFiber, - newIdx, - newChildren[newIdx], - lanes, - ); - if (newFiber !== null) { - if (shouldTrackSideEffects) { - if (newFiber.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete( - newFiber.key === null ? newIdx : newFiber.key, - ); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(child => deleteChild(returnFiber, child)); - } - - if (getIsHydrating()) { - const numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - - function reconcileChildrenIterator( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - newChildrenIterable: Iterable, - lanes: Lanes, - ): Fiber | null { - // This is the same implementation as reconcileChildrenArray(), - // but using the iterator instead. - - const iteratorFn = getIteratorFn(newChildrenIterable); - - if (typeof iteratorFn !== 'function') { - throw new Error( - 'An object is not an iterable. This error is likely caused by a bug in ' + - 'React. Please file an issue.', - ); - } - - if (__DEV__) { - // We don't support rendering Generators because it's a mutation. - // See https://github.com/facebook/react/issues/12995 - if ( - typeof Symbol === 'function' && - // $FlowFixMe Flow doesn't know about toStringTag - newChildrenIterable[Symbol.toStringTag] === 'Generator' - ) { - if (!didWarnAboutGenerators) { - console.error( - 'Using Generators as children is unsupported and will likely yield ' + - 'unexpected results because enumerating a generator mutates it. ' + - 'You may convert it to an array with `Array.from()` or the ' + - '`[...spread]` operator before rendering. Keep in mind ' + - 'you might need to polyfill these features for older browsers.', - ); - } - didWarnAboutGenerators = true; - } - - // Warn about using Maps as children - if ((newChildrenIterable: any).entries === iteratorFn) { - if (!didWarnAboutMaps) { - console.error( - 'Using Maps as children is not supported. ' + - 'Use an array of keyed ReactElements instead.', - ); - } - didWarnAboutMaps = true; - } - - // First, validate keys. - // We'll get a different iterator later for the main pass. - const newChildren = iteratorFn.call(newChildrenIterable); - if (newChildren) { - let knownKeys = null; - let step = newChildren.next(); - for (; !step.done; step = newChildren.next()) { - const child = step.value; - knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); - } - } - } - - const newChildren = iteratorFn.call(newChildrenIterable); - - if (newChildren == null) { - throw new Error('An iterable object provided no iterator.'); - } - - let resultingFirstChild: Fiber | null = null; - let previousNewFiber: Fiber | null = null; - - let oldFiber = currentFirstChild; - let lastPlacedIndex = 0; - let newIdx = 0; - let nextOldFiber = null; - - let step = newChildren.next(); - for ( - ; - oldFiber !== null && !step.done; - newIdx++, step = newChildren.next() - ) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - const newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (step.done) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - if (getIsHydrating()) { - const numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; !step.done; newIdx++, step = newChildren.next()) { - const newFiber = createChild(returnFiber, step.value, lanes); - if (newFiber === null) { - continue; - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - if (getIsHydrating()) { - const numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - - // Add all children to a key map for quick lookups. - const existingChildren = mapRemainingChildren(returnFiber, oldFiber); - - // Keep scanning and use the map to restore deleted items as moves. - for (; !step.done; newIdx++, step = newChildren.next()) { - const newFiber = updateFromMap( - existingChildren, - returnFiber, - newIdx, - step.value, - lanes, - ); - if (newFiber !== null) { - if (shouldTrackSideEffects) { - if (newFiber.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete( - newFiber.key === null ? newIdx : newFiber.key, - ); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(child => deleteChild(returnFiber, child)); - } - - if (getIsHydrating()) { - const numberOfForks = newIdx; - pushTreeFork(returnFiber, numberOfForks); - } - return resultingFirstChild; - } - - function reconcileSingleTextNode( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - textContent: string, - lanes: Lanes, - ): Fiber { - // There's no need to check for keys on text nodes since we don't have a - // way to define them. - if (currentFirstChild !== null && currentFirstChild.tag === HostText) { - // We already have an existing node so let's just update it and delete - // the rest. - deleteRemainingChildren(returnFiber, currentFirstChild.sibling); - const existing = useFiber(currentFirstChild, textContent); - existing.return = returnFiber; - return existing; - } - // The existing first child is not a text node so we need to create one - // and delete the existing ones. - deleteRemainingChildren(returnFiber, currentFirstChild); - const created = createFiberFromText(textContent, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - - function reconcileSingleElement( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - element: ReactElement, - lanes: Lanes, - ): Fiber { - const key = element.key; - let child = currentFirstChild; - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - const elementType = element.type; - if (elementType === REACT_FRAGMENT_TYPE) { - if (child.tag === Fragment) { - deleteRemainingChildren(returnFiber, child.sibling); - const existing = useFiber(child, element.props.children); - existing.return = returnFiber; - if (__DEV__) { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } - } else { - if ( - child.elementType === elementType || - // Keep this check inline so it only runs on the false path: - (__DEV__ - ? isCompatibleFamilyForHotReloading(child, element) - : false) || - // Lazy types should reconcile their resolved type. - // We need to do this after the Hot Reloading check above, - // because hot reloading has different semantics than prod because - // it doesn't resuspend. So we can't let the call below suspend. - (typeof elementType === 'object' && - elementType !== null && - elementType.$$typeof === REACT_LAZY_TYPE && - resolveLazy(elementType) === child.type) - ) { - deleteRemainingChildren(returnFiber, child.sibling); - const existing = useFiber(child, element.props); - existing.ref = coerceRef(returnFiber, child, element); - existing.return = returnFiber; - if (__DEV__) { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } - } - // Didn't match. - deleteRemainingChildren(returnFiber, child); - break; - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - - if (element.type === REACT_FRAGMENT_TYPE) { - const created = createFiberFromFragment( - element.props.children, - returnFiber.mode, - lanes, - element.key, - ); - created.return = returnFiber; - return created; - } else { - const created = createFiberFromElement(element, returnFiber.mode, lanes); - created.ref = coerceRef(returnFiber, currentFirstChild, element); - created.return = returnFiber; - return created; - } - } - - function reconcileSinglePortal( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - portal: ReactPortal, - lanes: Lanes, - ): Fiber { - const key = portal.key; - let child = currentFirstChild; - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if ( - child.tag === HostPortal && - child.stateNode.containerInfo === portal.containerInfo && - child.stateNode.implementation === portal.implementation - ) { - deleteRemainingChildren(returnFiber, child.sibling); - const existing = useFiber(child, portal.children || []); - existing.return = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - - const created = createFiberFromPortal(portal, returnFiber.mode, lanes); - created.return = returnFiber; - return created; - } - - // This API will tag the children with the side-effect of the reconciliation - // itself. They will be added to the side-effect list as we pass through the - // children and the parent. - function reconcileChildFibers( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - newChild: any, - lanes: Lanes, - ): Fiber | null { - // This function is not recursive. - // If the top level item is an array, we treat it as a set of children, - // not as a fragment. Nested arrays on the other hand will be treated as - // fragment nodes. Recursion happens at the normal flow. - - // Handle top level unkeyed fragments as if they were arrays. - // This leads to an ambiguity between <>{[...]} and <>.... - // We treat the ambiguous cases above the same. - const isUnkeyedTopLevelFragment = - typeof newChild === 'object' && - newChild !== null && - newChild.type === REACT_FRAGMENT_TYPE && - newChild.key === null; - if (isUnkeyedTopLevelFragment) { - newChild = newChild.props.children; - } - - // Handle object types - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - return placeSingleChild( - reconcileSingleElement( - returnFiber, - currentFirstChild, - newChild, - lanes, - ), - ); - case REACT_PORTAL_TYPE: - return placeSingleChild( - reconcileSinglePortal( - returnFiber, - currentFirstChild, - newChild, - lanes, - ), - ); - case REACT_LAZY_TYPE: - const payload = newChild._payload; - const init = newChild._init; - // TODO: This function is supposed to be non-recursive. - return reconcileChildFibers( - returnFiber, - currentFirstChild, - init(payload), - lanes, - ); - } - - if (isArray(newChild)) { - return reconcileChildrenArray( - returnFiber, - currentFirstChild, - newChild, - lanes, - ); - } - - if (getIteratorFn(newChild)) { - return reconcileChildrenIterator( - returnFiber, - currentFirstChild, - newChild, - lanes, - ); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - if ( - (typeof newChild === 'string' && newChild !== '') || - typeof newChild === 'number' - ) { - return placeSingleChild( - reconcileSingleTextNode( - returnFiber, - currentFirstChild, - '' + newChild, - lanes, - ), - ); - } - - if (__DEV__) { - if (typeof newChild === 'function') { - warnOnFunctionType(returnFiber); - } - } - - // Remaining cases are all treated as empty. - return deleteRemainingChildren(returnFiber, currentFirstChild); - } - - return reconcileChildFibers; -} - -export const reconcileChildFibers: ChildReconciler = createChildReconciler( - true, -); -export const mountChildFibers: ChildReconciler = createChildReconciler(false); - -export function cloneChildFibers( - current: Fiber | null, - workInProgress: Fiber, -): void { - if (current !== null && workInProgress.child !== current.child) { - throw new Error('Resuming work not yet implemented.'); - } - - if (workInProgress.child === null) { - return; - } - - let currentChild = workInProgress.child; - let newChild = createWorkInProgress(currentChild, currentChild.pendingProps); - workInProgress.child = newChild; - - newChild.return = workInProgress; - while (currentChild.sibling !== null) { - currentChild = currentChild.sibling; - newChild = newChild.sibling = createWorkInProgress( - currentChild, - currentChild.pendingProps, - ); - newChild.return = workInProgress; - } - newChild.sibling = null; -} - -// Reset a workInProgress child set to prepare it for a second pass. -export function resetChildFibers(workInProgress: Fiber, lanes: Lanes): void { - let child = workInProgress.child; - while (child !== null) { - resetWorkInProgress(child, lanes); - child = child.sibling; - } -} diff --git a/packages/react-reconciler/src/ReactEventPriorities.js b/packages/react-reconciler/src/ReactEventPriorities.js deleted file mode 100644 index 1aff2a4c91f80..0000000000000 --- a/packages/react-reconciler/src/ReactEventPriorities.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import {enableNewReconciler} from 'shared/ReactFeatureFlags'; - -import { - DiscreteEventPriority as DiscreteEventPriority_old, - ContinuousEventPriority as ContinuousEventPriority_old, - DefaultEventPriority as DefaultEventPriority_old, - IdleEventPriority as IdleEventPriority_old, - getCurrentUpdatePriority as getCurrentUpdatePriority_old, - setCurrentUpdatePriority as setCurrentUpdatePriority_old, - runWithPriority as runWithPriority_old, - isHigherEventPriority as isHigherEventPriority_old, -} from './ReactEventPriorities.old'; - -import { - DiscreteEventPriority as DiscreteEventPriority_new, - ContinuousEventPriority as ContinuousEventPriority_new, - DefaultEventPriority as DefaultEventPriority_new, - IdleEventPriority as IdleEventPriority_new, - getCurrentUpdatePriority as getCurrentUpdatePriority_new, - setCurrentUpdatePriority as setCurrentUpdatePriority_new, - runWithPriority as runWithPriority_new, - isHigherEventPriority as isHigherEventPriority_new, -} from './ReactEventPriorities.new'; - -export opaque type EventPriority = number; - -export const DiscreteEventPriority: EventPriority = enableNewReconciler - ? (DiscreteEventPriority_new: any) - : (DiscreteEventPriority_old: any); -export const ContinuousEventPriority: EventPriority = enableNewReconciler - ? (ContinuousEventPriority_new: any) - : (ContinuousEventPriority_old: any); -export const DefaultEventPriority: EventPriority = enableNewReconciler - ? (DefaultEventPriority_new: any) - : (DefaultEventPriority_old: any); -export const IdleEventPriority: EventPriority = enableNewReconciler - ? (IdleEventPriority_new: any) - : (IdleEventPriority_old: any); - -export function runWithPriority(priority: EventPriority, fn: () => T): T { - return enableNewReconciler - ? runWithPriority_new((priority: any), fn) - : runWithPriority_old((priority: any), fn); -} - -export function getCurrentUpdatePriority(): EventPriority { - return enableNewReconciler - ? (getCurrentUpdatePriority_new(): any) - : (getCurrentUpdatePriority_old(): any); -} - -export function setCurrentUpdatePriority(priority: EventPriority): void { - return enableNewReconciler - ? setCurrentUpdatePriority_new((priority: any)) - : setCurrentUpdatePriority_old((priority: any)); -} - -export function isHigherEventPriority( - a: EventPriority, - b: EventPriority, -): boolean { - return enableNewReconciler - ? isHigherEventPriority_new((a: any), (b: any)) - : isHigherEventPriority_old((a: any), (b: any)); -} diff --git a/packages/react-reconciler/src/ReactEventPriorities.new.js b/packages/react-reconciler/src/ReactEventPriorities.new.js deleted file mode 100644 index f9cc1e3ee9338..0000000000000 --- a/packages/react-reconciler/src/ReactEventPriorities.new.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Lane, Lanes} from './ReactFiberLane.new'; - -import { - NoLane, - SyncLane, - InputContinuousLane, - DefaultLane, - IdleLane, - getHighestPriorityLane, - includesNonIdleWork, -} from './ReactFiberLane.new'; - -export opaque type EventPriority = Lane; - -export const DiscreteEventPriority: EventPriority = SyncLane; -export const ContinuousEventPriority: EventPriority = InputContinuousLane; -export const DefaultEventPriority: EventPriority = DefaultLane; -export const IdleEventPriority: EventPriority = IdleLane; - -let currentUpdatePriority: EventPriority = NoLane; - -export function getCurrentUpdatePriority(): EventPriority { - return currentUpdatePriority; -} - -export function setCurrentUpdatePriority(newPriority: EventPriority) { - currentUpdatePriority = newPriority; -} - -export function runWithPriority(priority: EventPriority, fn: () => T): T { - const previousPriority = currentUpdatePriority; - try { - currentUpdatePriority = priority; - return fn(); - } finally { - currentUpdatePriority = previousPriority; - } -} - -export function higherEventPriority( - a: EventPriority, - b: EventPriority, -): EventPriority { - return a !== 0 && a < b ? a : b; -} - -export function lowerEventPriority( - a: EventPriority, - b: EventPriority, -): EventPriority { - return a === 0 || a > b ? a : b; -} - -export function isHigherEventPriority( - a: EventPriority, - b: EventPriority, -): boolean { - return a !== 0 && a < b; -} - -export function lanesToEventPriority(lanes: Lanes): EventPriority { - const lane = getHighestPriorityLane(lanes); - if (!isHigherEventPriority(DiscreteEventPriority, lane)) { - return DiscreteEventPriority; - } - if (!isHigherEventPriority(ContinuousEventPriority, lane)) { - return ContinuousEventPriority; - } - if (includesNonIdleWork(lane)) { - return DefaultEventPriority; - } - return IdleEventPriority; -} diff --git a/packages/react-reconciler/src/ReactFiber.new.js b/packages/react-reconciler/src/ReactFiber.new.js deleted file mode 100644 index 9a60de9797392..0000000000000 --- a/packages/react-reconciler/src/ReactFiber.new.js +++ /dev/null @@ -1,910 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {ReactElement} from 'shared/ReactElementType'; -import type {ReactFragment, ReactPortal, ReactScope} from 'shared/ReactTypes'; -import type {Fiber} from './ReactInternalTypes'; -import type {RootTag} from './ReactRootTags'; -import type {WorkTag} from './ReactWorkTags'; -import type {TypeOfMode} from './ReactTypeOfMode'; -import type {Lanes} from './ReactFiberLane.new'; -import type {SuspenseInstance} from './ReactFiberHostConfig'; -import type { - OffscreenProps, - OffscreenInstance, -} from './ReactFiberOffscreenComponent'; -import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new'; - -import { - supportsResources, - supportsSingletons, - isHostResourceType, - isHostSingletonType, -} from './ReactFiberHostConfig'; -import { - createRootStrictEffectsByDefault, - enableCache, - enableProfilerTimer, - enableScopeAPI, - enableLegacyHidden, - enableSyncDefaultUpdates, - allowConcurrentByDefault, - enableTransitionTracing, - enableDebugTracing, - enableFloat, - enableHostSingletons, -} from 'shared/ReactFeatureFlags'; -import {NoFlags, Placement, StaticMask} from './ReactFiberFlags'; -import {ConcurrentRoot} from './ReactRootTags'; -import { - IndeterminateComponent, - ClassComponent, - HostRoot, - HostComponent, - HostText, - HostPortal, - HostResource, - HostSingleton, - ForwardRef, - Fragment, - Mode, - ContextProvider, - ContextConsumer, - Profiler, - SuspenseComponent, - SuspenseListComponent, - DehydratedFragment, - FunctionComponent, - MemoComponent, - SimpleMemoComponent, - LazyComponent, - ScopeComponent, - OffscreenComponent, - LegacyHiddenComponent, - CacheComponent, - TracingMarkerComponent, -} from './ReactWorkTags'; -import {OffscreenVisible} from './ReactFiberOffscreenComponent'; -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import {isDevToolsPresent} from './ReactFiberDevToolsHook.new'; -import { - resolveClassForHotReloading, - resolveFunctionForHotReloading, - resolveForwardRefForHotReloading, -} from './ReactFiberHotReloading.new'; -import {NoLanes} from './ReactFiberLane.new'; -import { - NoMode, - ConcurrentMode, - DebugTracingMode, - ProfileMode, - StrictLegacyMode, - StrictEffectsMode, - ConcurrentUpdatesByDefaultMode, -} from './ReactTypeOfMode'; -import { - REACT_FORWARD_REF_TYPE, - REACT_FRAGMENT_TYPE, - REACT_DEBUG_TRACING_MODE_TYPE, - REACT_STRICT_MODE_TYPE, - REACT_PROFILER_TYPE, - REACT_PROVIDER_TYPE, - REACT_CONTEXT_TYPE, - REACT_SUSPENSE_TYPE, - REACT_SUSPENSE_LIST_TYPE, - REACT_MEMO_TYPE, - REACT_LAZY_TYPE, - REACT_SCOPE_TYPE, - REACT_OFFSCREEN_TYPE, - REACT_LEGACY_HIDDEN_TYPE, - REACT_CACHE_TYPE, - REACT_TRACING_MARKER_TYPE, -} from 'shared/ReactSymbols'; -import {TransitionTracingMarker} from './ReactFiberTracingMarkerComponent.new'; -import {detachOffscreenInstance} from './ReactFiberCommitWork.new'; -import {getHostContext} from './ReactFiberHostContext.new'; - -export type {Fiber}; - -let hasBadMapPolyfill; - -if (__DEV__) { - hasBadMapPolyfill = false; - try { - const nonExtensibleObject = Object.preventExtensions({}); - /* eslint-disable no-new */ - new Map([[nonExtensibleObject, null]]); - new Set([nonExtensibleObject]); - /* eslint-enable no-new */ - } catch (e) { - // TODO: Consider warning about bad polyfills - hasBadMapPolyfill = true; - } -} - -function FiberNode( - tag: WorkTag, - pendingProps: mixed, - key: null | string, - mode: TypeOfMode, -) { - // Instance - this.tag = tag; - this.key = key; - this.elementType = null; - this.type = null; - this.stateNode = null; - - // Fiber - this.return = null; - this.child = null; - this.sibling = null; - this.index = 0; - - this.ref = null; - this.refCleanup = null; - - this.pendingProps = pendingProps; - this.memoizedProps = null; - this.updateQueue = null; - this.memoizedState = null; - this.dependencies = null; - - this.mode = mode; - - // Effects - this.flags = NoFlags; - this.subtreeFlags = NoFlags; - this.deletions = null; - - this.lanes = NoLanes; - this.childLanes = NoLanes; - - this.alternate = null; - - if (enableProfilerTimer) { - // Note: The following is done to avoid a v8 performance cliff. - // - // Initializing the fields below to smis and later updating them with - // double values will cause Fibers to end up having separate shapes. - // This behavior/bug has something to do with Object.preventExtension(). - // Fortunately this only impacts DEV builds. - // Unfortunately it makes React unusably slow for some applications. - // To work around this, initialize the fields below with doubles. - // - // Learn more about this here: - // https://github.com/facebook/react/issues/14365 - // https://bugs.chromium.org/p/v8/issues/detail?id=8538 - this.actualDuration = Number.NaN; - this.actualStartTime = Number.NaN; - this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; - - // It's okay to replace the initial doubles with smis after initialization. - // This won't trigger the performance cliff mentioned above, - // and it simplifies other profiler code (including DevTools). - this.actualDuration = 0; - this.actualStartTime = -1; - this.selfBaseDuration = 0; - this.treeBaseDuration = 0; - } - - if (__DEV__) { - // This isn't directly used but is handy for debugging internals: - - this._debugSource = null; - this._debugOwner = null; - this._debugNeedsRemount = false; - this._debugHookTypes = null; - if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { - Object.preventExtensions(this); - } - } -} - -// This is a constructor function, rather than a POJO constructor, still -// please ensure we do the following: -// 1) Nobody should add any instance methods on this. Instance methods can be -// more difficult to predict when they get optimized and they are almost -// never inlined properly in static compilers. -// 2) Nobody should rely on `instanceof Fiber` for type testing. We should -// always know when it is a fiber. -// 3) We might want to experiment with using numeric keys since they are easier -// to optimize in a non-JIT environment. -// 4) We can easily go from a constructor to a createFiber object literal if that -// is faster. -// 5) It should be easy to port this to a C struct and keep a C implementation -// compatible. -const createFiber = function( - tag: WorkTag, - pendingProps: mixed, - key: null | string, - mode: TypeOfMode, -): Fiber { - // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors - return new FiberNode(tag, pendingProps, key, mode); -}; - -function shouldConstruct(Component: Function) { - const prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); -} - -export function isSimpleFunctionComponent(type: any): boolean { - return ( - typeof type === 'function' && - !shouldConstruct(type) && - type.defaultProps === undefined - ); -} - -export function resolveLazyComponentTag(Component: Function): WorkTag { - if (typeof Component === 'function') { - return shouldConstruct(Component) ? ClassComponent : FunctionComponent; - } else if (Component !== undefined && Component !== null) { - const $$typeof = Component.$$typeof; - if ($$typeof === REACT_FORWARD_REF_TYPE) { - return ForwardRef; - } - if ($$typeof === REACT_MEMO_TYPE) { - return MemoComponent; - } - } - return IndeterminateComponent; -} - -// This is used to create an alternate fiber to do work on. -export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber { - let workInProgress = current.alternate; - if (workInProgress === null) { - // We use a double buffering pooling technique because we know that we'll - // only ever need at most two versions of a tree. We pool the "other" unused - // node that we're free to reuse. This is lazily created to avoid allocating - // extra objects for things that are never updated. It also allow us to - // reclaim the extra memory if needed. - workInProgress = createFiber( - current.tag, - pendingProps, - current.key, - current.mode, - ); - workInProgress.elementType = current.elementType; - workInProgress.type = current.type; - workInProgress.stateNode = current.stateNode; - - if (__DEV__) { - // DEV-only fields - - workInProgress._debugSource = current._debugSource; - workInProgress._debugOwner = current._debugOwner; - workInProgress._debugHookTypes = current._debugHookTypes; - } - - workInProgress.alternate = current; - current.alternate = workInProgress; - } else { - workInProgress.pendingProps = pendingProps; - // Needed because Blocks store data on type. - workInProgress.type = current.type; - - // We already have an alternate. - // Reset the effect tag. - workInProgress.flags = NoFlags; - - // The effects are no longer valid. - workInProgress.subtreeFlags = NoFlags; - workInProgress.deletions = null; - - if (enableProfilerTimer) { - // We intentionally reset, rather than copy, actualDuration & actualStartTime. - // This prevents time from endlessly accumulating in new commits. - // This has the downside of resetting values for different priority renders, - // But works for yielding (the common case) and should support resuming. - workInProgress.actualDuration = 0; - workInProgress.actualStartTime = -1; - } - } - - // Reset all effects except static ones. - // Static effects are not specific to a render. - workInProgress.flags = current.flags & StaticMask; - workInProgress.childLanes = current.childLanes; - workInProgress.lanes = current.lanes; - - workInProgress.child = current.child; - workInProgress.memoizedProps = current.memoizedProps; - workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so - // it cannot be shared with the current fiber. - const currentDependencies = current.dependencies; - workInProgress.dependencies = - currentDependencies === null - ? null - : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext, - }; - - // These will be overridden during the parent's reconciliation - workInProgress.sibling = current.sibling; - workInProgress.index = current.index; - workInProgress.ref = current.ref; - workInProgress.refCleanup = current.refCleanup; - - if (enableProfilerTimer) { - workInProgress.selfBaseDuration = current.selfBaseDuration; - workInProgress.treeBaseDuration = current.treeBaseDuration; - } - - if (__DEV__) { - workInProgress._debugNeedsRemount = current._debugNeedsRemount; - switch (workInProgress.tag) { - case IndeterminateComponent: - case FunctionComponent: - case SimpleMemoComponent: - workInProgress.type = resolveFunctionForHotReloading(current.type); - break; - case ClassComponent: - workInProgress.type = resolveClassForHotReloading(current.type); - break; - case ForwardRef: - workInProgress.type = resolveForwardRefForHotReloading(current.type); - break; - default: - break; - } - } - - return workInProgress; -} - -// Used to reuse a Fiber for a second pass. -export function resetWorkInProgress( - workInProgress: Fiber, - renderLanes: Lanes, -): Fiber { - // This resets the Fiber to what createFiber or createWorkInProgress would - // have set the values to before during the first pass. Ideally this wouldn't - // be necessary but unfortunately many code paths reads from the workInProgress - // when they should be reading from current and writing to workInProgress. - - // We assume pendingProps, index, key, ref, return are still untouched to - // avoid doing another reconciliation. - - // Reset the effect flags but keep any Placement tags, since that's something - // that child fiber is setting, not the reconciliation. - workInProgress.flags &= StaticMask | Placement; - - // The effects are no longer valid. - - const current = workInProgress.alternate; - if (current === null) { - // Reset to createFiber's initial values. - workInProgress.childLanes = NoLanes; - workInProgress.lanes = renderLanes; - - workInProgress.child = null; - workInProgress.subtreeFlags = NoFlags; - workInProgress.memoizedProps = null; - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - - workInProgress.dependencies = null; - - workInProgress.stateNode = null; - - if (enableProfilerTimer) { - // Note: We don't reset the actualTime counts. It's useful to accumulate - // actual time across multiple render passes. - workInProgress.selfBaseDuration = 0; - workInProgress.treeBaseDuration = 0; - } - } else { - // Reset to the cloned values that createWorkInProgress would've. - workInProgress.childLanes = current.childLanes; - workInProgress.lanes = current.lanes; - - workInProgress.child = current.child; - workInProgress.subtreeFlags = NoFlags; - workInProgress.deletions = null; - workInProgress.memoizedProps = current.memoizedProps; - workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - // Needed because Blocks store data on type. - workInProgress.type = current.type; - - // Clone the dependencies object. This is mutated during the render phase, so - // it cannot be shared with the current fiber. - const currentDependencies = current.dependencies; - workInProgress.dependencies = - currentDependencies === null - ? null - : { - lanes: currentDependencies.lanes, - firstContext: currentDependencies.firstContext, - }; - - if (enableProfilerTimer) { - // Note: We don't reset the actualTime counts. It's useful to accumulate - // actual time across multiple render passes. - workInProgress.selfBaseDuration = current.selfBaseDuration; - workInProgress.treeBaseDuration = current.treeBaseDuration; - } - } - - return workInProgress; -} - -export function createHostRootFiber( - tag: RootTag, - isStrictMode: boolean, - concurrentUpdatesByDefaultOverride: null | boolean, -): Fiber { - let mode; - if (tag === ConcurrentRoot) { - mode = ConcurrentMode; - if (isStrictMode === true || createRootStrictEffectsByDefault) { - mode |= StrictLegacyMode | StrictEffectsMode; - } - if ( - // We only use this flag for our repo tests to check both behaviors. - // TODO: Flip this flag and rename it something like "forceConcurrentByDefaultForTesting" - !enableSyncDefaultUpdates || - // Only for internal experiments. - (allowConcurrentByDefault && concurrentUpdatesByDefaultOverride) - ) { - mode |= ConcurrentUpdatesByDefaultMode; - } - } else { - mode = NoMode; - } - - if (enableProfilerTimer && isDevToolsPresent) { - // Always collect profile timings when DevTools are present. - // This enables DevTools to start capturing timing at any point– - // Without some nodes in the tree having empty base times. - mode |= ProfileMode; - } - - return createFiber(HostRoot, null, null, mode); -} - -export function createFiberFromTypeAndProps( - type: any, // React$ElementType - key: null | string, - pendingProps: any, - owner: null | Fiber, - mode: TypeOfMode, - lanes: Lanes, -): Fiber { - let fiberTag = IndeterminateComponent; - // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - let resolvedType = type; - if (typeof type === 'function') { - if (shouldConstruct(type)) { - fiberTag = ClassComponent; - if (__DEV__) { - resolvedType = resolveClassForHotReloading(resolvedType); - } - } else { - if (__DEV__) { - resolvedType = resolveFunctionForHotReloading(resolvedType); - } - } - } else if (typeof type === 'string') { - if ( - enableFloat && - supportsResources && - enableHostSingletons && - supportsSingletons - ) { - const hostContext = getHostContext(); - fiberTag = isHostResourceType(type, pendingProps, hostContext) - ? HostResource - : isHostSingletonType(type) - ? HostSingleton - : HostComponent; - } else if (enableFloat && supportsResources) { - const hostContext = getHostContext(); - fiberTag = isHostResourceType(type, pendingProps, hostContext) - ? HostResource - : HostComponent; - } else if (enableHostSingletons && supportsSingletons) { - fiberTag = isHostSingletonType(type) ? HostSingleton : HostComponent; - } else { - fiberTag = HostComponent; - } - } else { - getTag: switch (type) { - case REACT_FRAGMENT_TYPE: - return createFiberFromFragment(pendingProps.children, mode, lanes, key); - case REACT_STRICT_MODE_TYPE: - fiberTag = Mode; - mode |= StrictLegacyMode; - if ((mode & ConcurrentMode) !== NoMode) { - // Strict effects should never run on legacy roots - mode |= StrictEffectsMode; - } - break; - case REACT_PROFILER_TYPE: - return createFiberFromProfiler(pendingProps, mode, lanes, key); - case REACT_SUSPENSE_TYPE: - return createFiberFromSuspense(pendingProps, mode, lanes, key); - case REACT_SUSPENSE_LIST_TYPE: - return createFiberFromSuspenseList(pendingProps, mode, lanes, key); - case REACT_OFFSCREEN_TYPE: - return createFiberFromOffscreen(pendingProps, mode, lanes, key); - case REACT_LEGACY_HIDDEN_TYPE: - if (enableLegacyHidden) { - return createFiberFromLegacyHidden(pendingProps, mode, lanes, key); - } - // eslint-disable-next-line no-fallthrough - case REACT_SCOPE_TYPE: - if (enableScopeAPI) { - return createFiberFromScope(type, pendingProps, mode, lanes, key); - } - // eslint-disable-next-line no-fallthrough - case REACT_CACHE_TYPE: - if (enableCache) { - return createFiberFromCache(pendingProps, mode, lanes, key); - } - // eslint-disable-next-line no-fallthrough - case REACT_TRACING_MARKER_TYPE: - if (enableTransitionTracing) { - return createFiberFromTracingMarker(pendingProps, mode, lanes, key); - } - // eslint-disable-next-line no-fallthrough - case REACT_DEBUG_TRACING_MODE_TYPE: - if (enableDebugTracing) { - fiberTag = Mode; - mode |= DebugTracingMode; - break; - } - // eslint-disable-next-line no-fallthrough - default: { - if (typeof type === 'object' && type !== null) { - switch (type.$$typeof) { - case REACT_PROVIDER_TYPE: - fiberTag = ContextProvider; - break getTag; - case REACT_CONTEXT_TYPE: - // This is a consumer - fiberTag = ContextConsumer; - break getTag; - case REACT_FORWARD_REF_TYPE: - fiberTag = ForwardRef; - if (__DEV__) { - resolvedType = resolveForwardRefForHotReloading(resolvedType); - } - break getTag; - case REACT_MEMO_TYPE: - fiberTag = MemoComponent; - break getTag; - case REACT_LAZY_TYPE: - fiberTag = LazyComponent; - resolvedType = null; - break getTag; - } - } - let info = ''; - if (__DEV__) { - if ( - type === undefined || - (typeof type === 'object' && - type !== null && - Object.keys(type).length === 0) - ) { - info += - ' You likely forgot to export your component from the file ' + - "it's defined in, or you might have mixed up default and " + - 'named imports.'; - } - const ownerName = owner ? getComponentNameFromFiber(owner) : null; - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - } - - throw new Error( - 'Element type is invalid: expected a string (for built-in ' + - 'components) or a class/function (for composite components) ' + - `but got: ${type == null ? type : typeof type}.${info}`, - ); - } - } - } - - const fiber = createFiber(fiberTag, pendingProps, key, mode); - fiber.elementType = type; - fiber.type = resolvedType; - fiber.lanes = lanes; - - if (__DEV__) { - fiber._debugOwner = owner; - } - - return fiber; -} - -export function createFiberFromElement( - element: ReactElement, - mode: TypeOfMode, - lanes: Lanes, -): Fiber { - let owner = null; - if (__DEV__) { - owner = element._owner; - } - const type = element.type; - const key = element.key; - const pendingProps = element.props; - const fiber = createFiberFromTypeAndProps( - type, - key, - pendingProps, - owner, - mode, - lanes, - ); - if (__DEV__) { - fiber._debugSource = element._source; - fiber._debugOwner = element._owner; - } - return fiber; -} - -export function createFiberFromFragment( - elements: ReactFragment, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - const fiber = createFiber(Fragment, elements, key, mode); - fiber.lanes = lanes; - return fiber; -} - -function createFiberFromScope( - scope: ReactScope, - pendingProps: any, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -) { - const fiber = createFiber(ScopeComponent, pendingProps, key, mode); - fiber.type = scope; - fiber.elementType = scope; - fiber.lanes = lanes; - return fiber; -} - -function createFiberFromProfiler( - pendingProps: any, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - if (__DEV__) { - if (typeof pendingProps.id !== 'string') { - console.error( - 'Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', - typeof pendingProps.id, - ); - } - } - - const fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - fiber.elementType = REACT_PROFILER_TYPE; - fiber.lanes = lanes; - - if (enableProfilerTimer) { - fiber.stateNode = { - effectDuration: 0, - passiveEffectDuration: 0, - }; - } - - return fiber; -} - -export function createFiberFromSuspense( - pendingProps: any, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - const fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.lanes = lanes; - return fiber; -} - -export function createFiberFromSuspenseList( - pendingProps: any, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - const fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); - fiber.elementType = REACT_SUSPENSE_LIST_TYPE; - fiber.lanes = lanes; - return fiber; -} - -export function createFiberFromOffscreen( - pendingProps: OffscreenProps, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - const fiber = createFiber(OffscreenComponent, pendingProps, key, mode); - fiber.elementType = REACT_OFFSCREEN_TYPE; - fiber.lanes = lanes; - const primaryChildInstance: OffscreenInstance = { - _visibility: OffscreenVisible, - _pendingMarkers: null, - _retryCache: null, - _transitions: null, - _current: null, - detach: () => detachOffscreenInstance(primaryChildInstance), - }; - fiber.stateNode = primaryChildInstance; - return fiber; -} - -export function createFiberFromLegacyHidden( - pendingProps: OffscreenProps, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - const fiber = createFiber(LegacyHiddenComponent, pendingProps, key, mode); - fiber.elementType = REACT_LEGACY_HIDDEN_TYPE; - fiber.lanes = lanes; - // Adding a stateNode for legacy hidden because it's currently using - // the offscreen implementation, which depends on a state node - const instance: OffscreenInstance = { - _visibility: OffscreenVisible, - _pendingMarkers: null, - _transitions: null, - _retryCache: null, - _current: null, - detach: () => detachOffscreenInstance(instance), - }; - fiber.stateNode = instance; - return fiber; -} - -export function createFiberFromCache( - pendingProps: any, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - const fiber = createFiber(CacheComponent, pendingProps, key, mode); - fiber.elementType = REACT_CACHE_TYPE; - fiber.lanes = lanes; - return fiber; -} - -export function createFiberFromTracingMarker( - pendingProps: any, - mode: TypeOfMode, - lanes: Lanes, - key: null | string, -): Fiber { - const fiber = createFiber(TracingMarkerComponent, pendingProps, key, mode); - fiber.elementType = REACT_TRACING_MARKER_TYPE; - fiber.lanes = lanes; - const tracingMarkerInstance: TracingMarkerInstance = { - tag: TransitionTracingMarker, - transitions: null, - pendingBoundaries: null, - aborts: null, - name: pendingProps.name, - }; - fiber.stateNode = tracingMarkerInstance; - return fiber; -} - -export function createFiberFromText( - content: string, - mode: TypeOfMode, - lanes: Lanes, -): Fiber { - const fiber = createFiber(HostText, content, null, mode); - fiber.lanes = lanes; - return fiber; -} - -export function createFiberFromHostInstanceForDeletion(): Fiber { - const fiber = createFiber(HostComponent, null, null, NoMode); - fiber.elementType = 'DELETED'; - return fiber; -} - -export function createFiberFromDehydratedFragment( - dehydratedNode: SuspenseInstance, -): Fiber { - const fiber = createFiber(DehydratedFragment, null, null, NoMode); - fiber.stateNode = dehydratedNode; - return fiber; -} - -export function createFiberFromPortal( - portal: ReactPortal, - mode: TypeOfMode, - lanes: Lanes, -): Fiber { - const pendingProps = portal.children !== null ? portal.children : []; - const fiber = createFiber(HostPortal, pendingProps, portal.key, mode); - fiber.lanes = lanes; - fiber.stateNode = { - containerInfo: portal.containerInfo, - pendingChildren: null, // Used by persistent updates - implementation: portal.implementation, - }; - return fiber; -} - -// Used for stashing WIP properties to replay failed work in DEV. -export function assignFiberPropertiesInDEV( - target: Fiber | null, - source: Fiber, -): Fiber { - if (target === null) { - // This Fiber's initial properties will always be overwritten. - // We only use a Fiber to ensure the same hidden class so DEV isn't slow. - target = createFiber(IndeterminateComponent, null, null, NoMode); - } - - // This is intentionally written as a list of all properties. - // We tried to use Object.assign() instead but this is called in - // the hottest path, and Object.assign() was too slow: - // https://github.com/facebook/react/issues/12502 - // This code is DEV-only so size is not a concern. - - target.tag = source.tag; - target.key = source.key; - target.elementType = source.elementType; - target.type = source.type; - target.stateNode = source.stateNode; - target.return = source.return; - target.child = source.child; - target.sibling = source.sibling; - target.index = source.index; - target.ref = source.ref; - target.refCleanup = source.refCleanup; - target.pendingProps = source.pendingProps; - target.memoizedProps = source.memoizedProps; - target.updateQueue = source.updateQueue; - target.memoizedState = source.memoizedState; - target.dependencies = source.dependencies; - target.mode = source.mode; - target.flags = source.flags; - target.subtreeFlags = source.subtreeFlags; - target.deletions = source.deletions; - target.lanes = source.lanes; - target.childLanes = source.childLanes; - target.alternate = source.alternate; - if (enableProfilerTimer) { - target.actualDuration = source.actualDuration; - target.actualStartTime = source.actualStartTime; - target.selfBaseDuration = source.selfBaseDuration; - target.treeBaseDuration = source.treeBaseDuration; - } - - target._debugSource = source._debugSource; - target._debugOwner = source._debugOwner; - target._debugNeedsRemount = source._debugNeedsRemount; - target._debugHookTypes = source._debugHookTypes; - return target; -} diff --git a/packages/react-reconciler/src/ReactFiberAct.new.js b/packages/react-reconciler/src/ReactFiberAct.new.js deleted file mode 100644 index 40f50d1952788..0000000000000 --- a/packages/react-reconciler/src/ReactFiberAct.new.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactFiber.new'; - -import ReactSharedInternals from 'shared/ReactSharedInternals'; - -import {warnsIfNotActing} from './ReactFiberHostConfig'; - -const {ReactCurrentActQueue} = ReactSharedInternals; - -export function isLegacyActEnvironment(fiber: Fiber): boolean { - if (__DEV__) { - // Legacy mode. We preserve the behavior of React 17's act. It assumes an - // act environment whenever `jest` is defined, but you can still turn off - // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly - // to false. - - const isReactActEnvironmentGlobal = - // $FlowFixMe – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global - typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' - ? IS_REACT_ACT_ENVIRONMENT - : undefined; - - // $FlowFixMe - Flow doesn't know about jest - const jestIsDefined = typeof jest !== 'undefined'; - return ( - warnsIfNotActing && jestIsDefined && isReactActEnvironmentGlobal !== false - ); - } - return false; -} - -export function isConcurrentActEnvironment(): void | boolean { - if (__DEV__) { - const isReactActEnvironmentGlobal = - typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' - ? IS_REACT_ACT_ENVIRONMENT - : undefined; - - if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { - // TODO: Include link to relevant documentation page. - console.error( - 'The current testing environment is not configured to support ' + - 'act(...)', - ); - } - return isReactActEnvironmentGlobal; - } - return false; -} diff --git a/packages/react-reconciler/src/ReactFiberBeginWork.new.js b/packages/react-reconciler/src/ReactFiberBeginWork.new.js deleted file mode 100644 index 50dd170a6028f..0000000000000 --- a/packages/react-reconciler/src/ReactFiberBeginWork.new.js +++ /dev/null @@ -1,4212 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type { - ReactProviderType, - ReactContext, - ReactNodeList, - MutableSource, -} from 'shared/ReactTypes'; -import type {LazyComponent as LazyComponentType} from 'react/src/ReactLazy'; -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {TypeOfMode} from './ReactTypeOfMode'; -import type {Lanes, Lane} from './ReactFiberLane.new'; -import type { - SuspenseState, - SuspenseListRenderState, - SuspenseListTailMode, -} from './ReactFiberSuspenseComponent.new'; -import type {SuspenseContext} from './ReactFiberSuspenseContext.new'; -import type { - OffscreenProps, - OffscreenState, - OffscreenQueue, - OffscreenInstance, -} from './ReactFiberOffscreenComponent'; -import {OffscreenDetached} from './ReactFiberOffscreenComponent'; -import type { - Cache, - CacheComponentState, - SpawnedCachePool, -} from './ReactFiberCacheComponent.new'; -import type {UpdateQueue} from './ReactFiberClassUpdateQueue.new'; -import type {RootState} from './ReactFiberRoot.new'; -import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new'; - -import checkPropTypes from 'shared/checkPropTypes'; -import { - markComponentRenderStarted, - markComponentRenderStopped, - setIsStrictModeForDevtools, -} from './ReactFiberDevToolsHook.new'; -import { - IndeterminateComponent, - FunctionComponent, - ClassComponent, - HostRoot, - HostComponent, - HostResource, - HostSingleton, - HostText, - HostPortal, - ForwardRef, - Fragment, - Mode, - ContextProvider, - ContextConsumer, - Profiler, - SuspenseComponent, - SuspenseListComponent, - MemoComponent, - SimpleMemoComponent, - LazyComponent, - IncompleteClassComponent, - ScopeComponent, - OffscreenComponent, - LegacyHiddenComponent, - CacheComponent, - TracingMarkerComponent, -} from './ReactWorkTags'; -import { - NoFlags, - PerformedWork, - Placement, - Hydrating, - ContentReset, - DidCapture, - Update, - Ref, - RefStatic, - ChildDeletion, - ForceUpdateForLegacySuspense, - StaticMask, - ShouldCapture, - ForceClientRender, - Passive, -} from './ReactFiberFlags'; -import ReactSharedInternals from 'shared/ReactSharedInternals'; -import { - debugRenderPhaseSideEffectsForStrictMode, - disableLegacyContext, - disableModulePatternComponents, - enableProfilerCommitHooks, - enableProfilerTimer, - warnAboutDefaultPropsOnFunctionComponents, - enableScopeAPI, - enableCache, - enableLazyContextPropagation, - enableSchedulingProfiler, - enableTransitionTracing, - enableLegacyHidden, - enableCPUSuspense, - enableUseMutableSource, - enableFloat, - enableHostSingletons, -} from 'shared/ReactFeatureFlags'; -import isArray from 'shared/isArray'; -import shallowEqual from 'shared/shallowEqual'; -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import getComponentNameFromType from 'shared/getComponentNameFromType'; -import ReactStrictModeWarnings from './ReactStrictModeWarnings.new'; -import {REACT_LAZY_TYPE, getIteratorFn} from 'shared/ReactSymbols'; -import { - getCurrentFiberOwnerNameInDevOrNull, - setIsRendering, -} from './ReactCurrentFiber'; -import { - resolveFunctionForHotReloading, - resolveForwardRefForHotReloading, - resolveClassForHotReloading, -} from './ReactFiberHotReloading.new'; - -import { - mountChildFibers, - reconcileChildFibers, - cloneChildFibers, -} from './ReactChildFiber.new'; -import { - processUpdateQueue, - cloneUpdateQueue, - initializeUpdateQueue, - enqueueCapturedUpdate, -} from './ReactFiberClassUpdateQueue.new'; -import { - NoLane, - NoLanes, - SyncLane, - OffscreenLane, - DefaultHydrationLane, - SomeRetryLane, - NoTimestamp, - includesSomeLane, - laneToLanes, - removeLanes, - mergeLanes, - getBumpedLaneForHydration, - pickArbitraryLane, -} from './ReactFiberLane.new'; -import { - ConcurrentMode, - NoMode, - ProfileMode, - StrictLegacyMode, -} from './ReactTypeOfMode'; -import { - shouldSetTextContent, - isSuspenseInstancePending, - isSuspenseInstanceFallback, - getSuspenseInstanceFallbackErrorDetails, - registerSuspenseInstanceRetry, - supportsHydration, - supportsResources, - supportsSingletons, - isPrimaryRenderer, - getResource, -} from './ReactFiberHostConfig'; -import type {SuspenseInstance} from './ReactFiberHostConfig'; -import {shouldError, shouldSuspend} from './ReactFiberReconciler'; -import {pushHostContext, pushHostContainer} from './ReactFiberHostContext.new'; -import { - suspenseStackCursor, - pushSuspenseListContext, - ForceSuspenseFallback, - hasSuspenseListContext, - setDefaultShallowSuspenseListContext, - setShallowSuspenseListContext, - pushPrimaryTreeSuspenseHandler, - pushFallbackTreeSuspenseHandler, - pushOffscreenSuspenseHandler, - reuseSuspenseHandlerOnStack, - popSuspenseHandler, -} from './ReactFiberSuspenseContext.new'; -import { - pushHiddenContext, - reuseHiddenContextOnStack, -} from './ReactFiberHiddenContext.new'; -import {findFirstSuspended} from './ReactFiberSuspenseComponent.new'; -import { - pushProvider, - propagateContextChange, - lazilyPropagateParentContextChanges, - propagateParentContextChangesToDeferredTree, - checkIfContextChanged, - readContext, - prepareToReadContext, - scheduleContextWorkOnParentPath, -} from './ReactFiberNewContext.new'; -import { - renderWithHooks, - checkDidRenderIdHook, - bailoutHooks, - replaySuspendedComponentWithHooks, -} from './ReactFiberHooks.new'; -import {stopProfilerTimerIfRunning} from './ReactProfilerTimer.new'; -import { - getMaskedContext, - getUnmaskedContext, - hasContextChanged as hasLegacyContextChanged, - pushContextProvider as pushLegacyContextProvider, - isContextProvider as isLegacyContextProvider, - pushTopLevelContextObject, - invalidateContextProvider, -} from './ReactFiberContext.new'; -import { - getIsHydrating, - enterHydrationState, - reenterHydrationStateFromDehydratedSuspenseInstance, - resetHydrationState, - claimHydratableSingleton, - tryToClaimNextHydratableInstance, - warnIfHydrating, - queueHydrationError, -} from './ReactFiberHydrationContext.new'; -import { - adoptClassInstance, - constructClassInstance, - mountClassInstance, - resumeMountClassInstance, - updateClassInstance, -} from './ReactFiberClassComponent.new'; -import {resolveDefaultProps} from './ReactFiberLazyComponent.new'; -import { - resolveLazyComponentTag, - createFiberFromTypeAndProps, - createFiberFromFragment, - createFiberFromOffscreen, - createWorkInProgress, - isSimpleFunctionComponent, -} from './ReactFiber.new'; -import { - retryDehydratedSuspenseBoundary, - scheduleUpdateOnFiber, - renderDidSuspendDelayIfPossible, - markSkippedUpdateLanes, - getWorkInProgressRoot, -} from './ReactFiberWorkLoop.new'; -import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates.new'; -import {setWorkInProgressVersion} from './ReactMutableSource.new'; -import {pushCacheProvider, CacheContext} from './ReactFiberCacheComponent.new'; -import { - createCapturedValue, - createCapturedValueAtFiber, - type CapturedValue, -} from './ReactCapturedValue'; -import {createClassErrorUpdate} from './ReactFiberThrow.new'; -import is from 'shared/objectIs'; -import { - getForksAtLevel, - isForkedChild, - pushTreeId, - pushMaterializedTreeId, -} from './ReactFiberTreeContext.new'; -import { - requestCacheFromPool, - pushRootTransition, - getSuspendedCache, - pushTransition, - getOffscreenDeferredCache, - getPendingTransitions, -} from './ReactFiberTransition.new'; -import { - getMarkerInstances, - pushMarkerInstance, - pushRootMarkerInstance, - TransitionTracingMarker, -} from './ReactFiberTracingMarkerComponent.new'; - -const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; - -// A special exception that's used to unwind the stack when an update flows -// into a dehydrated boundary. -export const SelectiveHydrationException: mixed = new Error( - "This is not a real error. It's an implementation detail of React's " + - "selective hydration feature. If this leaks into userspace, it's a bug in " + - 'React. Please file an issue.', -); - -let didReceiveUpdate: boolean = false; - -let didWarnAboutBadClass; -let didWarnAboutModulePatternComponent; -let didWarnAboutContextTypeOnFunctionComponent; -let didWarnAboutGetDerivedStateOnFunctionComponent; -let didWarnAboutFunctionRefs; -export let didWarnAboutReassigningProps: boolean; -let didWarnAboutRevealOrder; -let didWarnAboutTailOptions; -let didWarnAboutDefaultPropsOnFunctionComponent; - -if (__DEV__) { - didWarnAboutBadClass = {}; - didWarnAboutModulePatternComponent = {}; - didWarnAboutContextTypeOnFunctionComponent = {}; - didWarnAboutGetDerivedStateOnFunctionComponent = {}; - didWarnAboutFunctionRefs = {}; - didWarnAboutReassigningProps = false; - didWarnAboutRevealOrder = {}; - didWarnAboutTailOptions = {}; - didWarnAboutDefaultPropsOnFunctionComponent = {}; -} - -export function reconcileChildren( - current: Fiber | null, - workInProgress: Fiber, - nextChildren: any, - renderLanes: Lanes, -) { - if (current === null) { - // If this is a fresh new component that hasn't been rendered yet, we - // won't update its child set by applying minimal side-effects. Instead, - // we will add them all to the child before it gets rendered. That means - // we can optimize this reconciliation pass by not tracking side-effects. - workInProgress.child = mountChildFibers( - workInProgress, - null, - nextChildren, - renderLanes, - ); - } else { - // If the current child is the same as the work in progress, it means that - // we haven't yet started any work on these children. Therefore, we use - // the clone algorithm to create a copy of all the current children. - - // If we had any progressed work already, that is invalid at this point so - // let's throw it out. - workInProgress.child = reconcileChildFibers( - workInProgress, - current.child, - nextChildren, - renderLanes, - ); - } -} - -function forceUnmountCurrentAndReconcile( - current: Fiber, - workInProgress: Fiber, - nextChildren: any, - renderLanes: Lanes, -) { - // This function is fork of reconcileChildren. It's used in cases where we - // want to reconcile without matching against the existing set. This has the - // effect of all current children being unmounted; even if the type and key - // are the same, the old child is unmounted and a new child is created. - // - // To do this, we're going to go through the reconcile algorithm twice. In - // the first pass, we schedule a deletion for all the current children by - // passing null. - workInProgress.child = reconcileChildFibers( - workInProgress, - current.child, - null, - renderLanes, - ); - // In the second pass, we mount the new children. The trick here is that we - // pass null in place of where we usually pass the current child set. This has - // the effect of remounting all children regardless of whether their - // identities match. - workInProgress.child = reconcileChildFibers( - workInProgress, - null, - nextChildren, - renderLanes, - ); -} - -function updateForwardRef( - current: Fiber | null, - workInProgress: Fiber, - Component: any, - nextProps: any, - renderLanes: Lanes, -) { - // TODO: current can be non-null here even if the component - // hasn't yet mounted. This happens after the first render suspends. - // We'll need to figure out if this is fine or can cause issues. - - if (__DEV__) { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - const innerPropTypes = Component.propTypes; - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - 'prop', - getComponentNameFromType(Component), - ); - } - } - } - - const render = Component.render; - const ref = workInProgress.ref; - - // The rest is a fork of updateFunctionComponent - let nextChildren; - let hasId; - prepareToReadContext(workInProgress, renderLanes); - if (enableSchedulingProfiler) { - markComponentRenderStarted(workInProgress); - } - if (__DEV__) { - ReactCurrentOwner.current = workInProgress; - setIsRendering(true); - nextChildren = renderWithHooks( - current, - workInProgress, - render, - nextProps, - ref, - renderLanes, - ); - hasId = checkDidRenderIdHook(); - setIsRendering(false); - } else { - nextChildren = renderWithHooks( - current, - workInProgress, - render, - nextProps, - ref, - renderLanes, - ); - hasId = checkDidRenderIdHook(); - } - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - } - - if (current !== null && !didReceiveUpdate) { - bailoutHooks(current, workInProgress, renderLanes); - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } - - // React DevTools reads this flag. - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function updateMemoComponent( - current: Fiber | null, - workInProgress: Fiber, - Component: any, - nextProps: any, - renderLanes: Lanes, -): null | Fiber { - if (current === null) { - const type = Component.type; - if ( - isSimpleFunctionComponent(type) && - Component.compare === null && - // SimpleMemoComponent codepath doesn't resolve outer props either. - Component.defaultProps === undefined - ) { - let resolvedType = type; - if (__DEV__) { - resolvedType = resolveFunctionForHotReloading(type); - } - // If this is a plain function component without default props, - // and with only the default shallow comparison, we upgrade it - // to a SimpleMemoComponent to allow fast path updates. - workInProgress.tag = SimpleMemoComponent; - workInProgress.type = resolvedType; - if (__DEV__) { - validateFunctionComponentInDev(workInProgress, type); - } - return updateSimpleMemoComponent( - current, - workInProgress, - resolvedType, - nextProps, - renderLanes, - ); - } - if (__DEV__) { - const innerPropTypes = type.propTypes; - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - 'prop', - getComponentNameFromType(type), - ); - } - if ( - warnAboutDefaultPropsOnFunctionComponents && - Component.defaultProps !== undefined - ) { - const componentName = getComponentNameFromType(type) || 'Unknown'; - if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { - console.error( - '%s: Support for defaultProps will be removed from memo components ' + - 'in a future major release. Use JavaScript default parameters instead.', - componentName, - ); - didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; - } - } - } - const child = createFiberFromTypeAndProps( - Component.type, - null, - nextProps, - workInProgress, - workInProgress.mode, - renderLanes, - ); - child.ref = workInProgress.ref; - child.return = workInProgress; - workInProgress.child = child; - return child; - } - if (__DEV__) { - const type = Component.type; - const innerPropTypes = type.propTypes; - if (innerPropTypes) { - // Inner memo component props aren't currently validated in createElement. - // We could move it there, but we'd still need this for lazy code path. - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - 'prop', - getComponentNameFromType(type), - ); - } - } - const currentChild = ((current.child: any): Fiber); // This is always exactly one child - const hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( - current, - renderLanes, - ); - if (!hasScheduledUpdateOrContext) { - // This will be the props with resolved defaultProps, - // unlike current.memoizedProps which will be the unresolved ones. - const prevProps = currentChild.memoizedProps; - // Default to shallow comparison - let compare = Component.compare; - compare = compare !== null ? compare : shallowEqual; - if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - } - // React DevTools reads this flag. - workInProgress.flags |= PerformedWork; - const newChild = createWorkInProgress(currentChild, nextProps); - newChild.ref = workInProgress.ref; - newChild.return = workInProgress; - workInProgress.child = newChild; - return newChild; -} - -function updateSimpleMemoComponent( - current: Fiber | null, - workInProgress: Fiber, - Component: any, - nextProps: any, - renderLanes: Lanes, -): null | Fiber { - // TODO: current can be non-null here even if the component - // hasn't yet mounted. This happens when the inner render suspends. - // We'll need to figure out if this is fine or can cause issues. - - if (__DEV__) { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - let outerMemoType = workInProgress.elementType; - if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { - // We warn when you define propTypes on lazy() - // so let's just skip over it to find memo() outer wrapper. - // Inner props for memo are validated later. - const lazyComponent: LazyComponentType = outerMemoType; - const payload = lazyComponent._payload; - const init = lazyComponent._init; - try { - outerMemoType = init(payload); - } catch (x) { - // $FlowFixMe[incompatible-type] found when upgrading Flow - outerMemoType = null; - } - // Inner propTypes will be validated in the function component path. - const outerPropTypes = outerMemoType && (outerMemoType: any).propTypes; - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - nextProps, // Resolved (SimpleMemoComponent has no defaultProps) - 'prop', - getComponentNameFromType(outerMemoType), - ); - } - } - } - } - if (current !== null) { - const prevProps = current.memoizedProps; - if ( - shallowEqual(prevProps, nextProps) && - current.ref === workInProgress.ref && - // Prevent bailout if the implementation changed due to hot reload. - (__DEV__ ? workInProgress.type === current.type : true) - ) { - didReceiveUpdate = false; - - // The props are shallowly equal. Reuse the previous props object, like we - // would during a normal fiber bailout. - // - // We don't have strong guarantees that the props object is referentially - // equal during updates where we can't bail out anyway — like if the props - // are shallowly equal, but there's a local state or context update in the - // same batch. - // - // However, as a principle, we should aim to make the behavior consistent - // across different ways of memoizing a component. For example, React.memo - // has a different internal Fiber layout if you pass a normal function - // component (SimpleMemoComponent) versus if you pass a different type - // like forwardRef (MemoComponent). But this is an implementation detail. - // Wrapping a component in forwardRef (or React.lazy, etc) shouldn't - // affect whether the props object is reused during a bailout. - workInProgress.pendingProps = nextProps = prevProps; - - if (!checkScheduledUpdateOrContext(current, renderLanes)) { - // The pending lanes were cleared at the beginning of beginWork. We're - // about to bail out, but there might be other lanes that weren't - // included in the current render. Usually, the priority level of the - // remaining updates is accumulated during the evaluation of the - // component (i.e. when processing the update queue). But since since - // we're bailing out early *without* evaluating the component, we need - // to account for it here, too. Reset to the value of the current fiber. - // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, - // because a MemoComponent fiber does not have hooks or an update queue; - // rather, it wraps around an inner component, which may or may not - // contains hooks. - // TODO: Move the reset at in beginWork out of the common path so that - // this is no longer necessary. - workInProgress.lanes = current.lanes; - return bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes, - ); - } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - // This is a special case that only exists for legacy mode. - // See https://github.com/facebook/react/pull/19216. - didReceiveUpdate = true; - } - } - } - return updateFunctionComponent( - current, - workInProgress, - Component, - nextProps, - renderLanes, - ); -} - -function updateOffscreenComponent( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - const nextProps: OffscreenProps = workInProgress.pendingProps; - const nextChildren = nextProps.children; - - const prevState: OffscreenState | null = - current !== null ? current.memoizedState : null; - - markRef(current, workInProgress); - - if ( - nextProps.mode === 'hidden' || - (enableLegacyHidden && - nextProps.mode === 'unstable-defer-without-hiding') || - // TODO: remove read from stateNode. - workInProgress.stateNode._visibility & OffscreenDetached - ) { - // Rendering a hidden tree. - - const didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; - if (didSuspend) { - // Something suspended inside a hidden tree - - // Include the base lanes from the last render - const nextBaseLanes = - prevState !== null - ? mergeLanes(prevState.baseLanes, renderLanes) - : renderLanes; - - if (current !== null) { - // Reset to the current children - let currentChild = (workInProgress.child = current.child); - - // The current render suspended, but there may be other lanes with - // pending work. We can't read `childLanes` from the current Offscreen - // fiber because we reset it when it was deferred; however, we can read - // the pending lanes from the child fibers. - let currentChildLanes = NoLanes; - while (currentChild !== null) { - currentChildLanes = mergeLanes( - mergeLanes(currentChildLanes, currentChild.lanes), - currentChild.childLanes, - ); - currentChild = currentChild.sibling; - } - const lanesWeJustAttempted = nextBaseLanes; - const remainingChildLanes = removeLanes( - currentChildLanes, - lanesWeJustAttempted, - ); - workInProgress.childLanes = remainingChildLanes; - } else { - workInProgress.childLanes = NoLanes; - workInProgress.child = null; - } - - return deferHiddenOffscreenComponent( - current, - workInProgress, - nextBaseLanes, - renderLanes, - ); - } - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - // In legacy sync mode, don't defer the subtree. Render it now. - // TODO: Consider how Offscreen should work with transitions in the future - const nextState: OffscreenState = { - baseLanes: NoLanes, - cachePool: null, - }; - workInProgress.memoizedState = nextState; - if (enableCache) { - // push the cache pool even though we're going to bail out - // because otherwise there'd be a context mismatch - if (current !== null) { - pushTransition(workInProgress, null, null); - } - } - reuseHiddenContextOnStack(workInProgress); - pushOffscreenSuspenseHandler(workInProgress); - } else if (!includesSomeLane(renderLanes, (OffscreenLane: Lane))) { - // We're hidden, and we're not rendering at Offscreen. We will bail out - // and resume this tree later. - - // Schedule this fiber to re-render at Offscreen priority - workInProgress.lanes = workInProgress.childLanes = laneToLanes( - OffscreenLane, - ); - - // Include the base lanes from the last render - const nextBaseLanes = - prevState !== null - ? mergeLanes(prevState.baseLanes, renderLanes) - : renderLanes; - - return deferHiddenOffscreenComponent( - current, - workInProgress, - nextBaseLanes, - renderLanes, - ); - } else { - // This is the second render. The surrounding visible content has already - // committed. Now we resume rendering the hidden tree. - - // Rendering at offscreen, so we can clear the base lanes. - const nextState: OffscreenState = { - baseLanes: NoLanes, - cachePool: null, - }; - workInProgress.memoizedState = nextState; - if (enableCache && current !== null) { - // If the render that spawned this one accessed the cache pool, resume - // using the same cache. Unless the parent changed, since that means - // there was a refresh. - const prevCachePool = prevState !== null ? prevState.cachePool : null; - // TODO: Consider if and how Offscreen pre-rendering should - // be attributed to the transition that spawned it - pushTransition(workInProgress, prevCachePool, null); - } - - // Push the lanes that were skipped when we bailed out. - if (prevState !== null) { - pushHiddenContext(workInProgress, prevState); - } else { - reuseHiddenContextOnStack(workInProgress); - } - pushOffscreenSuspenseHandler(workInProgress); - } - } else { - // Rendering a visible tree. - if (prevState !== null) { - // We're going from hidden -> visible. - let prevCachePool = null; - if (enableCache) { - // If the render that spawned this one accessed the cache pool, resume - // using the same cache. Unless the parent changed, since that means - // there was a refresh. - prevCachePool = prevState.cachePool; - } - - let transitions = null; - if (enableTransitionTracing) { - // We have now gone from hidden to visible, so any transitions should - // be added to the stack to get added to any Offscreen/suspense children - const instance: OffscreenInstance | null = workInProgress.stateNode; - if (instance !== null && instance._transitions != null) { - transitions = Array.from(instance._transitions); - } - } - - pushTransition(workInProgress, prevCachePool, transitions); - - // Push the lanes that were skipped when we bailed out. - pushHiddenContext(workInProgress, prevState); - reuseSuspenseHandlerOnStack(workInProgress); - - // Since we're not hidden anymore, reset the state - workInProgress.memoizedState = null; - } else { - // We weren't previously hidden, and we still aren't, so there's nothing - // special to do. Need to push to the stack regardless, though, to avoid - // a push/pop misalignment. - - if (enableCache) { - // If the render that spawned this one accessed the cache pool, resume - // using the same cache. Unless the parent changed, since that means - // there was a refresh. - if (current !== null) { - pushTransition(workInProgress, null, null); - } - } - - // We're about to bail out, but we need to push this to the stack anyway - // to avoid a push/pop misalignment. - reuseHiddenContextOnStack(workInProgress); - reuseSuspenseHandlerOnStack(workInProgress); - } - } - - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function deferHiddenOffscreenComponent( - current: Fiber | null, - workInProgress: Fiber, - nextBaseLanes: Lanes, - renderLanes: Lanes, -) { - const nextState: OffscreenState = { - baseLanes: nextBaseLanes, - // Save the cache pool so we can resume later. - cachePool: enableCache ? getOffscreenDeferredCache() : null, - }; - workInProgress.memoizedState = nextState; - if (enableCache) { - // push the cache pool even though we're going to bail out - // because otherwise there'd be a context mismatch - if (current !== null) { - pushTransition(workInProgress, null, null); - } - } - - // We're about to bail out, but we need to push this to the stack anyway - // to avoid a push/pop misalignment. - reuseHiddenContextOnStack(workInProgress); - - pushOffscreenSuspenseHandler(workInProgress); - - if (enableLazyContextPropagation && current !== null) { - // Since this tree will resume rendering in a separate render, we need - // to propagate parent contexts now so we don't lose track of which - // ones changed. - propagateParentContextChangesToDeferredTree( - current, - workInProgress, - renderLanes, - ); - } - - return null; -} - -// Note: These happen to have identical begin phases, for now. We shouldn't hold -// ourselves to this constraint, though. If the behavior diverges, we should -// fork the function. -const updateLegacyHiddenComponent = updateOffscreenComponent; - -function updateCacheComponent( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - if (!enableCache) { - return null; - } - - prepareToReadContext(workInProgress, renderLanes); - const parentCache = readContext(CacheContext); - - if (current === null) { - // Initial mount. Request a fresh cache from the pool. - const freshCache = requestCacheFromPool(renderLanes); - const initialState: CacheComponentState = { - parent: parentCache, - cache: freshCache, - }; - workInProgress.memoizedState = initialState; - initializeUpdateQueue(workInProgress); - pushCacheProvider(workInProgress, freshCache); - } else { - // Check for updates - if (includesSomeLane(current.lanes, renderLanes)) { - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, null, null, renderLanes); - } - const prevState: CacheComponentState = current.memoizedState; - const nextState: CacheComponentState = workInProgress.memoizedState; - - // Compare the new parent cache to the previous to see detect there was - // a refresh. - if (prevState.parent !== parentCache) { - // Refresh in parent. Update the parent. - const derivedState: CacheComponentState = { - parent: parentCache, - cache: parentCache, - }; - - // Copied from getDerivedStateFromProps implementation. Once the update - // queue is empty, persist the derived state onto the base state. - workInProgress.memoizedState = derivedState; - if (workInProgress.lanes === NoLanes) { - const updateQueue: UpdateQueue = (workInProgress.updateQueue: any); - workInProgress.memoizedState = updateQueue.baseState = derivedState; - } - - pushCacheProvider(workInProgress, parentCache); - // No need to propagate a context change because the refreshed parent - // already did. - } else { - // The parent didn't refresh. Now check if this cache did. - const nextCache = nextState.cache; - pushCacheProvider(workInProgress, nextCache); - if (nextCache !== prevState.cache) { - // This cache refreshed. Propagate a context change. - propagateContextChange(workInProgress, CacheContext, renderLanes); - } - } - } - - const nextChildren = workInProgress.pendingProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -// This should only be called if the name changes -function updateTracingMarkerComponent( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - if (!enableTransitionTracing) { - return null; - } - - // TODO: (luna) Only update the tracing marker if it's newly rendered or it's name changed. - // A tracing marker is only associated with the transitions that rendered - // or updated it, so we can create a new set of transitions each time - if (current === null) { - const currentTransitions = getPendingTransitions(); - if (currentTransitions !== null) { - const markerInstance: TracingMarkerInstance = { - tag: TransitionTracingMarker, - transitions: new Set(currentTransitions), - pendingBoundaries: null, - name: workInProgress.pendingProps.name, - aborts: null, - }; - workInProgress.stateNode = markerInstance; - - // We call the marker complete callback when all child suspense boundaries resolve. - // We do this in the commit phase on Offscreen. If the marker has no child suspense - // boundaries, we need to schedule a passive effect to make sure we call the marker - // complete callback. - workInProgress.flags |= Passive; - } - } else { - if (__DEV__) { - if (current.memoizedProps.name !== workInProgress.pendingProps.name) { - console.error( - 'Changing the name of a tracing marker after mount is not supported. ' + - 'To remount the tracing marker, pass it a new key.', - ); - } - } - } - - const instance: TracingMarkerInstance | null = workInProgress.stateNode; - if (instance !== null) { - pushMarkerInstance(workInProgress, instance); - } - const nextChildren = workInProgress.pendingProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function updateFragment( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - const nextChildren = workInProgress.pendingProps; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function updateMode( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - const nextChildren = workInProgress.pendingProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function updateProfiler( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - if (enableProfilerTimer) { - workInProgress.flags |= Update; - - if (enableProfilerCommitHooks) { - // Reset effect durations for the next eventual effect phase. - // These are reset during render to allow the DevTools commit hook a chance to read them, - const stateNode = workInProgress.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - const nextProps = workInProgress.pendingProps; - const nextChildren = nextProps.children; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function markRef(current: Fiber | null, workInProgress: Fiber) { - const ref = workInProgress.ref; - if ( - (current === null && ref !== null) || - (current !== null && current.ref !== ref) - ) { - // Schedule a Ref effect - workInProgress.flags |= Ref; - workInProgress.flags |= RefStatic; - } -} - -function updateFunctionComponent( - current, - workInProgress, - Component, - nextProps: any, - renderLanes, -) { - if (__DEV__) { - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - const innerPropTypes = Component.propTypes; - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - 'prop', - getComponentNameFromType(Component), - ); - } - } - } - - let context; - if (!disableLegacyContext) { - const unmaskedContext = getUnmaskedContext(workInProgress, Component, true); - context = getMaskedContext(workInProgress, unmaskedContext); - } - - let nextChildren; - let hasId; - prepareToReadContext(workInProgress, renderLanes); - if (enableSchedulingProfiler) { - markComponentRenderStarted(workInProgress); - } - if (__DEV__) { - ReactCurrentOwner.current = workInProgress; - setIsRendering(true); - nextChildren = renderWithHooks( - current, - workInProgress, - Component, - nextProps, - context, - renderLanes, - ); - hasId = checkDidRenderIdHook(); - setIsRendering(false); - } else { - nextChildren = renderWithHooks( - current, - workInProgress, - Component, - nextProps, - context, - renderLanes, - ); - hasId = checkDidRenderIdHook(); - } - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - } - - if (current !== null && !didReceiveUpdate) { - bailoutHooks(current, workInProgress, renderLanes); - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } - - // React DevTools reads this flag. - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -export function replayFunctionComponent( - current: Fiber | null, - workInProgress: Fiber, - nextProps: any, - Component: any, - renderLanes: Lanes, -): Fiber | null { - // This function is used to replay a component that previously suspended, - // after its data resolves. It's a simplified version of - // updateFunctionComponent that reuses the hooks from the previous attempt. - - let context; - if (!disableLegacyContext) { - const unmaskedContext = getUnmaskedContext(workInProgress, Component, true); - context = getMaskedContext(workInProgress, unmaskedContext); - } - - prepareToReadContext(workInProgress, renderLanes); - if (enableSchedulingProfiler) { - markComponentRenderStarted(workInProgress); - } - const nextChildren = replaySuspendedComponentWithHooks( - current, - workInProgress, - Component, - nextProps, - context, - ); - const hasId = checkDidRenderIdHook(); - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - } - - if (current !== null && !didReceiveUpdate) { - bailoutHooks(current, workInProgress, renderLanes); - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } - - // React DevTools reads this flag. - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function updateClassComponent( - current: Fiber | null, - workInProgress: Fiber, - Component: any, - nextProps: any, - renderLanes: Lanes, -) { - if (__DEV__) { - // This is used by DevTools to force a boundary to error. - switch (shouldError(workInProgress)) { - case false: { - const instance = workInProgress.stateNode; - const ctor = workInProgress.type; - // TODO This way of resetting the error boundary state is a hack. - // Is there a better way to do this? - const tempInstance = new ctor( - workInProgress.memoizedProps, - instance.context, - ); - const state = tempInstance.state; - instance.updater.enqueueSetState(instance, state, null); - break; - } - case true: { - workInProgress.flags |= DidCapture; - workInProgress.flags |= ShouldCapture; - // eslint-disable-next-line react-internal/prod-error-codes - const error = new Error('Simulated error coming from DevTools'); - const lane = pickArbitraryLane(renderLanes); - workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); - // Schedule the error boundary to re-render using updated state - const update = createClassErrorUpdate( - workInProgress, - createCapturedValueAtFiber(error, workInProgress), - lane, - ); - enqueueCapturedUpdate(workInProgress, update); - break; - } - } - - if (workInProgress.type !== workInProgress.elementType) { - // Lazy component props can't be validated in createElement - // because they're only guaranteed to be resolved here. - const innerPropTypes = Component.propTypes; - if (innerPropTypes) { - checkPropTypes( - innerPropTypes, - nextProps, // Resolved props - 'prop', - getComponentNameFromType(Component), - ); - } - } - } - - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - let hasContext; - if (isLegacyContextProvider(Component)) { - hasContext = true; - pushLegacyContextProvider(workInProgress); - } else { - hasContext = false; - } - prepareToReadContext(workInProgress, renderLanes); - - const instance = workInProgress.stateNode; - let shouldUpdate; - if (instance === null) { - resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); - - // In the initial pass we might need to construct the instance. - constructClassInstance(workInProgress, Component, nextProps); - mountClassInstance(workInProgress, Component, nextProps, renderLanes); - shouldUpdate = true; - } else if (current === null) { - // In a resume, we'll already have an instance we can reuse. - shouldUpdate = resumeMountClassInstance( - workInProgress, - Component, - nextProps, - renderLanes, - ); - } else { - shouldUpdate = updateClassInstance( - current, - workInProgress, - Component, - nextProps, - renderLanes, - ); - } - const nextUnitOfWork = finishClassComponent( - current, - workInProgress, - Component, - shouldUpdate, - hasContext, - renderLanes, - ); - if (__DEV__) { - const inst = workInProgress.stateNode; - if (shouldUpdate && inst.props !== nextProps) { - if (!didWarnAboutReassigningProps) { - console.error( - 'It looks like %s is reassigning its own `this.props` while rendering. ' + - 'This is not supported and can lead to confusing bugs.', - getComponentNameFromFiber(workInProgress) || 'a component', - ); - } - didWarnAboutReassigningProps = true; - } - } - return nextUnitOfWork; -} - -function finishClassComponent( - current: Fiber | null, - workInProgress: Fiber, - Component: any, - shouldUpdate: boolean, - hasContext: boolean, - renderLanes: Lanes, -) { - // Refs should update even if shouldComponentUpdate returns false - markRef(current, workInProgress); - - const didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; - - if (!shouldUpdate && !didCaptureError) { - // Context providers should defer to sCU for rendering - if (hasContext) { - invalidateContextProvider(workInProgress, Component, false); - } - - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - - const instance = workInProgress.stateNode; - - // Rerender - ReactCurrentOwner.current = workInProgress; - let nextChildren; - if ( - didCaptureError && - typeof Component.getDerivedStateFromError !== 'function' - ) { - // If we captured an error, but getDerivedStateFromError is not defined, - // unmount all the children. componentDidCatch will schedule an update to - // re-render a fallback. This is temporary until we migrate everyone to - // the new API. - // TODO: Warn in a future release. - nextChildren = null; - - if (enableProfilerTimer) { - stopProfilerTimerIfRunning(workInProgress); - } - } else { - if (enableSchedulingProfiler) { - markComponentRenderStarted(workInProgress); - } - if (__DEV__) { - setIsRendering(true); - nextChildren = instance.render(); - if ( - debugRenderPhaseSideEffectsForStrictMode && - workInProgress.mode & StrictLegacyMode - ) { - setIsStrictModeForDevtools(true); - try { - instance.render(); - } finally { - setIsStrictModeForDevtools(false); - } - } - setIsRendering(false); - } else { - nextChildren = instance.render(); - } - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - } - } - - // React DevTools reads this flag. - workInProgress.flags |= PerformedWork; - if (current !== null && didCaptureError) { - // If we're recovering from an error, reconcile without reusing any of - // the existing children. Conceptually, the normal children and the children - // that are shown on error are two different sets, so we shouldn't reuse - // normal children even if their identities match. - forceUnmountCurrentAndReconcile( - current, - workInProgress, - nextChildren, - renderLanes, - ); - } else { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - - // Memoize state using the values we just used to render. - // TODO: Restructure so we never read values from the instance. - workInProgress.memoizedState = instance.state; - - // The context might have changed so we need to recalculate it. - if (hasContext) { - invalidateContextProvider(workInProgress, Component, true); - } - - return workInProgress.child; -} - -function pushHostRootContext(workInProgress) { - const root = (workInProgress.stateNode: FiberRoot); - if (root.pendingContext) { - pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context, - ); - } else if (root.context) { - // Should always be set - pushTopLevelContextObject(workInProgress, root.context, false); - } - pushHostContainer(workInProgress, root.containerInfo); -} - -function updateHostRoot(current, workInProgress, renderLanes) { - pushHostRootContext(workInProgress); - - if (current === null) { - throw new Error('Should have a current fiber. This is a bug in React.'); - } - - const nextProps = workInProgress.pendingProps; - const prevState = workInProgress.memoizedState; - const prevChildren = prevState.element; - cloneUpdateQueue(current, workInProgress); - processUpdateQueue(workInProgress, nextProps, null, renderLanes); - - const nextState: RootState = workInProgress.memoizedState; - const root: FiberRoot = workInProgress.stateNode; - pushRootTransition(workInProgress, root, renderLanes); - - if (enableTransitionTracing) { - pushRootMarkerInstance(workInProgress); - } - - if (enableCache) { - const nextCache: Cache = nextState.cache; - pushCacheProvider(workInProgress, nextCache); - if (nextCache !== prevState.cache) { - // The root cache refreshed. - propagateContextChange(workInProgress, CacheContext, renderLanes); - } - } - - // Caution: React DevTools currently depends on this property - // being called "element". - const nextChildren = nextState.element; - if (supportsHydration && prevState.isDehydrated) { - // This is a hydration root whose shell has not yet hydrated. We should - // attempt to hydrate. - - // Flip isDehydrated to false to indicate that when this render - // finishes, the root will no longer be dehydrated. - const overrideState: RootState = { - element: nextChildren, - isDehydrated: false, - cache: nextState.cache, - }; - const updateQueue: UpdateQueue = (workInProgress.updateQueue: any); - // `baseState` can always be the last state because the root doesn't - // have reducer functions so it doesn't need rebasing. - updateQueue.baseState = overrideState; - workInProgress.memoizedState = overrideState; - - if (workInProgress.flags & ForceClientRender) { - // Something errored during a previous attempt to hydrate the shell, so we - // forced a client render. - const recoverableError = createCapturedValueAtFiber( - new Error( - 'There was an error while hydrating. Because the error happened outside ' + - 'of a Suspense boundary, the entire root will switch to ' + - 'client rendering.', - ), - workInProgress, - ); - return mountHostRootWithoutHydrating( - current, - workInProgress, - nextChildren, - renderLanes, - recoverableError, - ); - } else if (nextChildren !== prevChildren) { - const recoverableError = createCapturedValueAtFiber( - new Error( - 'This root received an early update, before anything was able ' + - 'hydrate. Switched the entire root to client rendering.', - ), - workInProgress, - ); - return mountHostRootWithoutHydrating( - current, - workInProgress, - nextChildren, - renderLanes, - recoverableError, - ); - } else { - // The outermost shell has not hydrated yet. Start hydrating. - enterHydrationState(workInProgress); - if (enableUseMutableSource) { - const mutableSourceEagerHydrationData = - root.mutableSourceEagerHydrationData; - if (mutableSourceEagerHydrationData != null) { - for (let i = 0; i < mutableSourceEagerHydrationData.length; i += 2) { - const mutableSource = ((mutableSourceEagerHydrationData[ - i - ]: any): MutableSource); - const version = mutableSourceEagerHydrationData[i + 1]; - setWorkInProgressVersion(mutableSource, version); - } - } - } - - const child = mountChildFibers( - workInProgress, - null, - nextChildren, - renderLanes, - ); - workInProgress.child = child; - - let node = child; - while (node) { - // Mark each child as hydrating. This is a fast path to know whether this - // tree is part of a hydrating tree. This is used to determine if a child - // node has fully mounted yet, and for scheduling event replaying. - // Conceptually this is similar to Placement in that a new subtree is - // inserted into the React tree here. It just happens to not need DOM - // mutations because it already exists. - node.flags = (node.flags & ~Placement) | Hydrating; - node = node.sibling; - } - } - } else { - // Root is not dehydrated. Either this is a client-only root, or it - // already hydrated. - resetHydrationState(); - if (nextChildren === prevChildren) { - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); - } - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - return workInProgress.child; -} - -function mountHostRootWithoutHydrating( - current: Fiber, - workInProgress: Fiber, - nextChildren: ReactNodeList, - renderLanes: Lanes, - recoverableError: CapturedValue, -) { - // Revert to client rendering. - resetHydrationState(); - - queueHydrationError(recoverableError); - - workInProgress.flags |= ForceClientRender; - - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function updateHostComponent( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - pushHostContext(workInProgress); - - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } - - const type = workInProgress.type; - const nextProps = workInProgress.pendingProps; - const prevProps = current !== null ? current.memoizedProps : null; - - let nextChildren = nextProps.children; - const isDirectTextChild = shouldSetTextContent(type, nextProps); - - if (isDirectTextChild) { - // We special case a direct text child of a host node. This is a common - // case. We won't handle it as a reified child. We will instead handle - // this in the host environment that also has access to this prop. That - // avoids allocating another HostText fiber and traversing it. - nextChildren = null; - } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { - // If we're switching from a direct text child to a normal child, or to - // empty, we need to schedule the text content to be reset. - workInProgress.flags |= ContentReset; - } - - markRef(current, workInProgress); - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -function updateHostResource(current, workInProgress, renderLanes) { - pushHostContext(workInProgress); - markRef(current, workInProgress); - const currentProps = current === null ? null : current.memoizedProps; - workInProgress.memoizedState = getResource( - workInProgress.type, - workInProgress.pendingProps, - currentProps, - ); - // Resources never have reconciler managed children. It is possible for - // the host implementation of getResource to consider children in the - // resource construction but they will otherwise be discarded. In practice - // this precludes all but the simplest children and Host specific warnings - // should be implemented to warn when children are passsed when otherwise not - // expected - return null; -} - -function updateHostSingleton( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - pushHostContext(workInProgress); - - if (current === null) { - claimHydratableSingleton(workInProgress); - } - - const nextChildren = workInProgress.pendingProps.children; - - if (current === null && !getIsHydrating()) { - // Similar to Portals we append Singleton children in the commit phase. So we - // Track insertions even on mount. - // TODO: Consider unifying this with how the root works. - workInProgress.child = reconcileChildFibers( - workInProgress, - null, - nextChildren, - renderLanes, - ); - } else { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - markRef(current, workInProgress); - return workInProgress.child; -} - -function updateHostText(current, workInProgress) { - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } - // Nothing to do here. This is terminal. We'll do the completion step - // immediately after. - return null; -} - -function mountLazyComponent( - _current, - workInProgress, - elementType, - renderLanes, -) { - resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); - - const props = workInProgress.pendingProps; - const lazyComponent: LazyComponentType = elementType; - const payload = lazyComponent._payload; - const init = lazyComponent._init; - let Component = init(payload); - // Store the unwrapped component in the type. - workInProgress.type = Component; - const resolvedTag = (workInProgress.tag = resolveLazyComponentTag(Component)); - const resolvedProps = resolveDefaultProps(Component, props); - let child; - switch (resolvedTag) { - case FunctionComponent: { - if (__DEV__) { - validateFunctionComponentInDev(workInProgress, Component); - workInProgress.type = Component = resolveFunctionForHotReloading( - Component, - ); - } - child = updateFunctionComponent( - null, - workInProgress, - Component, - resolvedProps, - renderLanes, - ); - return child; - } - case ClassComponent: { - if (__DEV__) { - workInProgress.type = Component = resolveClassForHotReloading( - Component, - ); - } - child = updateClassComponent( - null, - workInProgress, - Component, - resolvedProps, - renderLanes, - ); - return child; - } - case ForwardRef: { - if (__DEV__) { - workInProgress.type = Component = resolveForwardRefForHotReloading( - Component, - ); - } - child = updateForwardRef( - null, - workInProgress, - Component, - resolvedProps, - renderLanes, - ); - return child; - } - case MemoComponent: { - if (__DEV__) { - if (workInProgress.type !== workInProgress.elementType) { - const outerPropTypes = Component.propTypes; - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - 'prop', - getComponentNameFromType(Component), - ); - } - } - } - child = updateMemoComponent( - null, - workInProgress, - Component, - resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too - renderLanes, - ); - return child; - } - } - let hint = ''; - if (__DEV__) { - if ( - Component !== null && - typeof Component === 'object' && - Component.$$typeof === REACT_LAZY_TYPE - ) { - hint = ' Did you wrap a component in React.lazy() more than once?'; - } - } - - // This message intentionally doesn't mention ForwardRef or MemoComponent - // because the fact that it's a separate type of work is an - // implementation detail. - throw new Error( - `Element type is invalid. Received a promise that resolves to: ${Component}. ` + - `Lazy element type must resolve to a class or function.${hint}`, - ); -} - -function mountIncompleteClassComponent( - _current, - workInProgress, - Component, - nextProps, - renderLanes, -) { - resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); - - // Promote the fiber to a class and try rendering again. - workInProgress.tag = ClassComponent; - - // The rest of this function is a fork of `updateClassComponent` - - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - let hasContext; - if (isLegacyContextProvider(Component)) { - hasContext = true; - pushLegacyContextProvider(workInProgress); - } else { - hasContext = false; - } - prepareToReadContext(workInProgress, renderLanes); - - constructClassInstance(workInProgress, Component, nextProps); - mountClassInstance(workInProgress, Component, nextProps, renderLanes); - - return finishClassComponent( - null, - workInProgress, - Component, - true, - hasContext, - renderLanes, - ); -} - -function mountIndeterminateComponent( - _current, - workInProgress, - Component, - renderLanes, -) { - resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); - - const props = workInProgress.pendingProps; - let context; - if (!disableLegacyContext) { - const unmaskedContext = getUnmaskedContext( - workInProgress, - Component, - false, - ); - context = getMaskedContext(workInProgress, unmaskedContext); - } - - prepareToReadContext(workInProgress, renderLanes); - let value; - let hasId; - - if (enableSchedulingProfiler) { - markComponentRenderStarted(workInProgress); - } - if (__DEV__) { - if ( - Component.prototype && - typeof Component.prototype.render === 'function' - ) { - const componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutBadClass[componentName]) { - console.error( - "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + - 'This is likely to cause errors. Change %s to extend React.Component instead.', - componentName, - componentName, - ); - didWarnAboutBadClass[componentName] = true; - } - } - - if (workInProgress.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); - } - - setIsRendering(true); - ReactCurrentOwner.current = workInProgress; - value = renderWithHooks( - null, - workInProgress, - Component, - props, - context, - renderLanes, - ); - hasId = checkDidRenderIdHook(); - setIsRendering(false); - } else { - value = renderWithHooks( - null, - workInProgress, - Component, - props, - context, - renderLanes, - ); - hasId = checkDidRenderIdHook(); - } - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - } - - // React DevTools reads this flag. - workInProgress.flags |= PerformedWork; - - if (__DEV__) { - // Support for module components is deprecated and is removed behind a flag. - // Whether or not it would crash later, we want to show a good message in DEV first. - if ( - typeof value === 'object' && - value !== null && - typeof value.render === 'function' && - value.$$typeof === undefined - ) { - const componentName = getComponentNameFromType(Component) || 'Unknown'; - if (!didWarnAboutModulePatternComponent[componentName]) { - console.error( - 'The <%s /> component appears to be a function component that returns a class instance. ' + - 'Change %s to a class that extends React.Component instead. ' + - "If you can't use a class try assigning the prototype on the function as a workaround. " + - "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + - 'cannot be called with `new` by React.', - componentName, - componentName, - componentName, - ); - didWarnAboutModulePatternComponent[componentName] = true; - } - } - } - - if ( - // Run these checks in production only if the flag is off. - // Eventually we'll delete this branch altogether. - !disableModulePatternComponents && - typeof value === 'object' && - value !== null && - typeof value.render === 'function' && - value.$$typeof === undefined - ) { - if (__DEV__) { - const componentName = getComponentNameFromType(Component) || 'Unknown'; - if (!didWarnAboutModulePatternComponent[componentName]) { - console.error( - 'The <%s /> component appears to be a function component that returns a class instance. ' + - 'Change %s to a class that extends React.Component instead. ' + - "If you can't use a class try assigning the prototype on the function as a workaround. " + - "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + - 'cannot be called with `new` by React.', - componentName, - componentName, - componentName, - ); - didWarnAboutModulePatternComponent[componentName] = true; - } - } - - // Proceed under the assumption that this is a class instance - workInProgress.tag = ClassComponent; - - // Throw out any hooks that were used. - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - let hasContext = false; - if (isLegacyContextProvider(Component)) { - hasContext = true; - pushLegacyContextProvider(workInProgress); - } else { - hasContext = false; - } - - workInProgress.memoizedState = - value.state !== null && value.state !== undefined ? value.state : null; - - initializeUpdateQueue(workInProgress); - - adoptClassInstance(workInProgress, value); - mountClassInstance(workInProgress, Component, props, renderLanes); - return finishClassComponent( - null, - workInProgress, - Component, - true, - hasContext, - renderLanes, - ); - } else { - // Proceed under the assumption that this is a function component - workInProgress.tag = FunctionComponent; - if (__DEV__) { - if (disableLegacyContext && Component.contextTypes) { - console.error( - '%s uses the legacy contextTypes API which is no longer supported. ' + - 'Use React.createContext() with React.useContext() instead.', - getComponentNameFromType(Component) || 'Unknown', - ); - } - } - - if (getIsHydrating() && hasId) { - pushMaterializedTreeId(workInProgress); - } - - reconcileChildren(null, workInProgress, value, renderLanes); - if (__DEV__) { - validateFunctionComponentInDev(workInProgress, Component); - } - return workInProgress.child; - } -} - -function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) { - if (__DEV__) { - if (Component) { - if (Component.childContextTypes) { - console.error( - '%s(...): childContextTypes cannot be defined on a function component.', - Component.displayName || Component.name || 'Component', - ); - } - } - if (workInProgress.ref !== null) { - let info = ''; - const ownerName = getCurrentFiberOwnerNameInDevOrNull(); - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - - let warningKey = ownerName || ''; - const debugSource = workInProgress._debugSource; - if (debugSource) { - warningKey = debugSource.fileName + ':' + debugSource.lineNumber; - } - if (!didWarnAboutFunctionRefs[warningKey]) { - didWarnAboutFunctionRefs[warningKey] = true; - console.error( - 'Function components cannot be given refs. ' + - 'Attempts to access this ref will fail. ' + - 'Did you mean to use React.forwardRef()?%s', - info, - ); - } - } - - if ( - warnAboutDefaultPropsOnFunctionComponents && - Component.defaultProps !== undefined - ) { - const componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { - console.error( - '%s: Support for defaultProps will be removed from function components ' + - 'in a future major release. Use JavaScript default parameters instead.', - componentName, - ); - didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; - } - } - - if (typeof Component.getDerivedStateFromProps === 'function') { - const componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) { - console.error( - '%s: Function components do not support getDerivedStateFromProps.', - componentName, - ); - didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true; - } - } - - if ( - typeof Component.contextType === 'object' && - Component.contextType !== null - ) { - const componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutContextTypeOnFunctionComponent[componentName]) { - console.error( - '%s: Function components do not support contextType.', - componentName, - ); - didWarnAboutContextTypeOnFunctionComponent[componentName] = true; - } - } - } -} - -const SUSPENDED_MARKER: SuspenseState = { - dehydrated: null, - treeContext: null, - retryLane: NoLane, -}; - -function mountSuspenseOffscreenState(renderLanes: Lanes): OffscreenState { - return { - baseLanes: renderLanes, - cachePool: getSuspendedCache(), - }; -} - -function updateSuspenseOffscreenState( - prevOffscreenState: OffscreenState, - renderLanes: Lanes, -): OffscreenState { - let cachePool: SpawnedCachePool | null = null; - if (enableCache) { - const prevCachePool: SpawnedCachePool | null = prevOffscreenState.cachePool; - if (prevCachePool !== null) { - const parentCache = isPrimaryRenderer - ? CacheContext._currentValue - : CacheContext._currentValue2; - if (prevCachePool.parent !== parentCache) { - // Detected a refresh in the parent. This overrides any previously - // suspended cache. - cachePool = { - parent: parentCache, - pool: parentCache, - }; - } else { - // We can reuse the cache from last time. The only thing that would have - // overridden it is a parent refresh, which we checked for above. - cachePool = prevCachePool; - } - } else { - // If there's no previous cache pool, grab the current one. - cachePool = getSuspendedCache(); - } - } - return { - baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), - cachePool, - }; -} - -// TODO: Probably should inline this back -function shouldRemainOnFallback( - current: null | Fiber, - workInProgress: Fiber, - renderLanes: Lanes, -) { - // If we're already showing a fallback, there are cases where we need to - // remain on that fallback regardless of whether the content has resolved. - // For example, SuspenseList coordinates when nested content appears. - if (current !== null) { - const suspenseState: SuspenseState = current.memoizedState; - if (suspenseState === null) { - // Currently showing content. Don't hide it, even if ForceSuspenseFallback - // is true. More precise name might be "ForceRemainSuspenseFallback". - // Note: This is a factoring smell. Can't remain on a fallback if there's - // no fallback to remain on. - return false; - } - } - - // Not currently showing content. Consult the Suspense context. - const suspenseContext: SuspenseContext = suspenseStackCursor.current; - return hasSuspenseListContext( - suspenseContext, - (ForceSuspenseFallback: SuspenseContext), - ); -} - -function getRemainingWorkInPrimaryTree(current: Fiber, renderLanes) { - // TODO: Should not remove render lanes that were pinged during this render - return removeLanes(current.childLanes, renderLanes); -} - -function updateSuspenseComponent(current, workInProgress, renderLanes) { - const nextProps = workInProgress.pendingProps; - - // This is used by DevTools to force a boundary to suspend. - if (__DEV__) { - if (shouldSuspend(workInProgress)) { - workInProgress.flags |= DidCapture; - } - } - - let showFallback = false; - const didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; - if ( - didSuspend || - shouldRemainOnFallback(current, workInProgress, renderLanes) - ) { - // Something in this boundary's subtree already suspended. Switch to - // rendering the fallback children. - showFallback = true; - workInProgress.flags &= ~DidCapture; - } - - // OK, the next part is confusing. We're about to reconcile the Suspense - // boundary's children. This involves some custom reconciliation logic. Two - // main reasons this is so complicated. - // - // First, Legacy Mode has different semantics for backwards compatibility. The - // primary tree will commit in an inconsistent state, so when we do the - // second pass to render the fallback, we do some exceedingly, uh, clever - // hacks to make that not totally break. Like transferring effects and - // deletions from hidden tree. In Concurrent Mode, it's much simpler, - // because we bailout on the primary tree completely and leave it in its old - // state, no effects. Same as what we do for Offscreen (except that - // Offscreen doesn't have the first render pass). - // - // Second is hydration. During hydration, the Suspense fiber has a slightly - // different layout, where the child points to a dehydrated fragment, which - // contains the DOM rendered by the server. - // - // Third, even if you set all that aside, Suspense is like error boundaries in - // that we first we try to render one tree, and if that fails, we render again - // and switch to a different tree. Like a try/catch block. So we have to track - // which branch we're currently rendering. Ideally we would model this using - // a stack. - if (current === null) { - // Initial mount - - // Special path for hydration - // If we're currently hydrating, try to hydrate this boundary. - if (getIsHydrating()) { - // We must push the suspense handler context *before* attempting to - // hydrate, to avoid a mismatch in case it errors. - if (showFallback) { - pushPrimaryTreeSuspenseHandler(workInProgress); - } else { - pushFallbackTreeSuspenseHandler(workInProgress); - } - tryToClaimNextHydratableInstance(workInProgress); - // This could've been a dehydrated suspense component. - const suspenseState: null | SuspenseState = workInProgress.memoizedState; - if (suspenseState !== null) { - const dehydrated = suspenseState.dehydrated; - if (dehydrated !== null) { - return mountDehydratedSuspenseComponent( - workInProgress, - dehydrated, - renderLanes, - ); - } - } - // If hydration didn't succeed, fall through to the normal Suspense path. - // To avoid a stack mismatch we need to pop the Suspense handler that we - // pushed above. This will become less awkward when move the hydration - // logic to its own fiber. - popSuspenseHandler(workInProgress); - } - - const nextPrimaryChildren = nextProps.children; - const nextFallbackChildren = nextProps.fallback; - - if (showFallback) { - pushFallbackTreeSuspenseHandler(workInProgress); - - const fallbackFragment = mountSuspenseFallbackChildren( - workInProgress, - nextPrimaryChildren, - nextFallbackChildren, - renderLanes, - ); - const primaryChildFragment: Fiber = (workInProgress.child: any); - primaryChildFragment.memoizedState = mountSuspenseOffscreenState( - renderLanes, - ); - workInProgress.memoizedState = SUSPENDED_MARKER; - if (enableTransitionTracing) { - const currentTransitions = getPendingTransitions(); - if (currentTransitions !== null) { - const parentMarkerInstances = getMarkerInstances(); - const offscreenQueue: OffscreenQueue | null = (primaryChildFragment.updateQueue: any); - if (offscreenQueue === null) { - const newOffscreenQueue: OffscreenQueue = { - transitions: currentTransitions, - markerInstances: parentMarkerInstances, - wakeables: null, - }; - primaryChildFragment.updateQueue = newOffscreenQueue; - } else { - offscreenQueue.transitions = currentTransitions; - offscreenQueue.markerInstances = parentMarkerInstances; - } - } - } - - return fallbackFragment; - } else if ( - enableCPUSuspense && - typeof nextProps.unstable_expectedLoadTime === 'number' - ) { - // This is a CPU-bound tree. Skip this tree and show a placeholder to - // unblock the surrounding content. Then immediately retry after the - // initial commit. - pushFallbackTreeSuspenseHandler(workInProgress); - const fallbackFragment = mountSuspenseFallbackChildren( - workInProgress, - nextPrimaryChildren, - nextFallbackChildren, - renderLanes, - ); - const primaryChildFragment: Fiber = (workInProgress.child: any); - primaryChildFragment.memoizedState = mountSuspenseOffscreenState( - renderLanes, - ); - workInProgress.memoizedState = SUSPENDED_MARKER; - - // TODO: Transition Tracing is not yet implemented for CPU Suspense. - - // Since nothing actually suspended, there will nothing to ping this to - // get it started back up to attempt the next item. While in terms of - // priority this work has the same priority as this current render, it's - // not part of the same transition once the transition has committed. If - // it's sync, we still want to yield so that it can be painted. - // Conceptually, this is really the same as pinging. We can use any - // RetryLane even if it's the one currently rendering since we're leaving - // it behind on this node. - workInProgress.lanes = SomeRetryLane; - return fallbackFragment; - } else { - pushPrimaryTreeSuspenseHandler(workInProgress); - return mountSuspensePrimaryChildren( - workInProgress, - nextPrimaryChildren, - renderLanes, - ); - } - } else { - // This is an update. - - // Special path for hydration - const prevState: null | SuspenseState = current.memoizedState; - if (prevState !== null) { - const dehydrated = prevState.dehydrated; - if (dehydrated !== null) { - return updateDehydratedSuspenseComponent( - current, - workInProgress, - didSuspend, - nextProps, - dehydrated, - prevState, - renderLanes, - ); - } - } - - if (showFallback) { - pushFallbackTreeSuspenseHandler(workInProgress); - - const nextFallbackChildren = nextProps.fallback; - const nextPrimaryChildren = nextProps.children; - const fallbackChildFragment = updateSuspenseFallbackChildren( - current, - workInProgress, - nextPrimaryChildren, - nextFallbackChildren, - renderLanes, - ); - const primaryChildFragment: Fiber = (workInProgress.child: any); - const prevOffscreenState: OffscreenState | null = (current.child: any) - .memoizedState; - primaryChildFragment.memoizedState = - prevOffscreenState === null - ? mountSuspenseOffscreenState(renderLanes) - : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); - if (enableTransitionTracing) { - const currentTransitions = getPendingTransitions(); - if (currentTransitions !== null) { - const parentMarkerInstances = getMarkerInstances(); - const offscreenQueue: OffscreenQueue | null = (primaryChildFragment.updateQueue: any); - const currentOffscreenQueue: OffscreenQueue | null = (current.updateQueue: any); - if (offscreenQueue === null) { - const newOffscreenQueue: OffscreenQueue = { - transitions: currentTransitions, - markerInstances: parentMarkerInstances, - wakeables: null, - }; - primaryChildFragment.updateQueue = newOffscreenQueue; - } else if (offscreenQueue === currentOffscreenQueue) { - // If the work-in-progress queue is the same object as current, we - // can't modify it without cloning it first. - const newOffscreenQueue: OffscreenQueue = { - transitions: currentTransitions, - markerInstances: parentMarkerInstances, - wakeables: - currentOffscreenQueue !== null - ? currentOffscreenQueue.wakeables - : null, - }; - primaryChildFragment.updateQueue = newOffscreenQueue; - } else { - offscreenQueue.transitions = currentTransitions; - offscreenQueue.markerInstances = parentMarkerInstances; - } - } - } - primaryChildFragment.childLanes = getRemainingWorkInPrimaryTree( - current, - renderLanes, - ); - workInProgress.memoizedState = SUSPENDED_MARKER; - return fallbackChildFragment; - } else { - pushPrimaryTreeSuspenseHandler(workInProgress); - - const nextPrimaryChildren = nextProps.children; - const primaryChildFragment = updateSuspensePrimaryChildren( - current, - workInProgress, - nextPrimaryChildren, - renderLanes, - ); - workInProgress.memoizedState = null; - return primaryChildFragment; - } - } -} - -function mountSuspensePrimaryChildren( - workInProgress, - primaryChildren, - renderLanes, -) { - const mode = workInProgress.mode; - const primaryChildProps: OffscreenProps = { - mode: 'visible', - children: primaryChildren, - }; - const primaryChildFragment = mountWorkInProgressOffscreenFiber( - primaryChildProps, - mode, - renderLanes, - ); - primaryChildFragment.return = workInProgress; - workInProgress.child = primaryChildFragment; - return primaryChildFragment; -} - -function mountSuspenseFallbackChildren( - workInProgress, - primaryChildren, - fallbackChildren, - renderLanes, -) { - const mode = workInProgress.mode; - const progressedPrimaryFragment: Fiber | null = workInProgress.child; - - const primaryChildProps: OffscreenProps = { - mode: 'hidden', - children: primaryChildren, - }; - - let primaryChildFragment; - let fallbackChildFragment; - if ( - (mode & ConcurrentMode) === NoMode && - progressedPrimaryFragment !== null - ) { - // In legacy mode, we commit the primary tree as if it successfully - // completed, even though it's in an inconsistent state. - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - - if (enableProfilerTimer && workInProgress.mode & ProfileMode) { - // Reset the durations from the first pass so they aren't included in the - // final amounts. This seems counterintuitive, since we're intentionally - // not measuring part of the render phase, but this makes it match what we - // do in Concurrent Mode. - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = 0; - primaryChildFragment.treeBaseDuration = 0; - } - - fallbackChildFragment = createFiberFromFragment( - fallbackChildren, - mode, - renderLanes, - null, - ); - } else { - primaryChildFragment = mountWorkInProgressOffscreenFiber( - primaryChildProps, - mode, - NoLanes, - ); - fallbackChildFragment = createFiberFromFragment( - fallbackChildren, - mode, - renderLanes, - null, - ); - } - - primaryChildFragment.return = workInProgress; - fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - return fallbackChildFragment; -} - -function mountWorkInProgressOffscreenFiber( - offscreenProps: OffscreenProps, - mode: TypeOfMode, - renderLanes: Lanes, -) { - // The props argument to `createFiberFromOffscreen` is `any` typed, so we use - // this wrapper function to constrain it. - return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); -} - -function updateWorkInProgressOffscreenFiber( - current: Fiber, - offscreenProps: OffscreenProps, -) { - // The props argument to `createWorkInProgress` is `any` typed, so we use this - // wrapper function to constrain it. - return createWorkInProgress(current, offscreenProps); -} - -function updateSuspensePrimaryChildren( - current, - workInProgress, - primaryChildren, - renderLanes, -) { - const currentPrimaryChildFragment: Fiber = (current.child: any); - const currentFallbackChildFragment: Fiber | null = - currentPrimaryChildFragment.sibling; - - const primaryChildFragment = updateWorkInProgressOffscreenFiber( - currentPrimaryChildFragment, - { - mode: 'visible', - children: primaryChildren, - }, - ); - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - primaryChildFragment.lanes = renderLanes; - } - primaryChildFragment.return = workInProgress; - primaryChildFragment.sibling = null; - if (currentFallbackChildFragment !== null) { - // Delete the fallback child fragment - const deletions = workInProgress.deletions; - if (deletions === null) { - workInProgress.deletions = [currentFallbackChildFragment]; - workInProgress.flags |= ChildDeletion; - } else { - deletions.push(currentFallbackChildFragment); - } - } - - workInProgress.child = primaryChildFragment; - return primaryChildFragment; -} - -function updateSuspenseFallbackChildren( - current, - workInProgress, - primaryChildren, - fallbackChildren, - renderLanes, -) { - const mode = workInProgress.mode; - const currentPrimaryChildFragment: Fiber = (current.child: any); - const currentFallbackChildFragment: Fiber | null = - currentPrimaryChildFragment.sibling; - - const primaryChildProps: OffscreenProps = { - mode: 'hidden', - children: primaryChildren, - }; - - let primaryChildFragment; - if ( - // In legacy mode, we commit the primary tree as if it successfully - // completed, even though it's in an inconsistent state. - (mode & ConcurrentMode) === NoMode && - // Make sure we're on the second pass, i.e. the primary child fragment was - // already cloned. In legacy mode, the only case where this isn't true is - // when DevTools forces us to display a fallback; we skip the first render - // pass entirely and go straight to rendering the fallback. (In Concurrent - // Mode, SuspenseList can also trigger this scenario, but this is a legacy- - // only codepath.) - workInProgress.child !== currentPrimaryChildFragment - ) { - const progressedPrimaryFragment: Fiber = (workInProgress.child: any); - primaryChildFragment = progressedPrimaryFragment; - primaryChildFragment.childLanes = NoLanes; - primaryChildFragment.pendingProps = primaryChildProps; - - if (enableProfilerTimer && workInProgress.mode & ProfileMode) { - // Reset the durations from the first pass so they aren't included in the - // final amounts. This seems counterintuitive, since we're intentionally - // not measuring part of the render phase, but this makes it match what we - // do in Concurrent Mode. - primaryChildFragment.actualDuration = 0; - primaryChildFragment.actualStartTime = -1; - primaryChildFragment.selfBaseDuration = - currentPrimaryChildFragment.selfBaseDuration; - primaryChildFragment.treeBaseDuration = - currentPrimaryChildFragment.treeBaseDuration; - } - - // The fallback fiber was added as a deletion during the first pass. - // However, since we're going to remain on the fallback, we no longer want - // to delete it. - workInProgress.deletions = null; - } else { - primaryChildFragment = updateWorkInProgressOffscreenFiber( - currentPrimaryChildFragment, - primaryChildProps, - ); - // Since we're reusing a current tree, we need to reuse the flags, too. - // (We don't do this in legacy mode, because in legacy mode we don't re-use - // the current tree; see previous branch.) - primaryChildFragment.subtreeFlags = - currentPrimaryChildFragment.subtreeFlags & StaticMask; - } - let fallbackChildFragment; - if (currentFallbackChildFragment !== null) { - fallbackChildFragment = createWorkInProgress( - currentFallbackChildFragment, - fallbackChildren, - ); - } else { - fallbackChildFragment = createFiberFromFragment( - fallbackChildren, - mode, - renderLanes, - null, - ); - // Needs a placement effect because the parent (the Suspense boundary) already - // mounted but this is a new fiber. - fallbackChildFragment.flags |= Placement; - } - - fallbackChildFragment.return = workInProgress; - primaryChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - - return fallbackChildFragment; -} - -function retrySuspenseComponentWithoutHydrating( - current: Fiber, - workInProgress: Fiber, - renderLanes: Lanes, - recoverableError: CapturedValue | null, -) { - // Falling back to client rendering. Because this has performance - // implications, it's considered a recoverable error, even though the user - // likely won't observe anything wrong with the UI. - // - // The error is passed in as an argument to enforce that every caller provide - // a custom message, or explicitly opt out (currently the only path that opts - // out is legacy mode; every concurrent path provides an error). - if (recoverableError !== null) { - queueHydrationError(recoverableError); - } - - // This will add the old fiber to the deletion list - reconcileChildFibers(workInProgress, current.child, null, renderLanes); - - // We're now not suspended nor dehydrated. - const nextProps = workInProgress.pendingProps; - const primaryChildren = nextProps.children; - const primaryChildFragment = mountSuspensePrimaryChildren( - workInProgress, - primaryChildren, - renderLanes, - ); - // Needs a placement effect because the parent (the Suspense boundary) already - // mounted but this is a new fiber. - primaryChildFragment.flags |= Placement; - workInProgress.memoizedState = null; - - return primaryChildFragment; -} - -function mountSuspenseFallbackAfterRetryWithoutHydrating( - current, - workInProgress, - primaryChildren, - fallbackChildren, - renderLanes, -) { - const fiberMode = workInProgress.mode; - const primaryChildProps: OffscreenProps = { - mode: 'visible', - children: primaryChildren, - }; - const primaryChildFragment = mountWorkInProgressOffscreenFiber( - primaryChildProps, - fiberMode, - NoLanes, - ); - const fallbackChildFragment = createFiberFromFragment( - fallbackChildren, - fiberMode, - renderLanes, - null, - ); - // Needs a placement effect because the parent (the Suspense - // boundary) already mounted but this is a new fiber. - fallbackChildFragment.flags |= Placement; - - primaryChildFragment.return = workInProgress; - fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - workInProgress.child = primaryChildFragment; - - if ((workInProgress.mode & ConcurrentMode) !== NoMode) { - // We will have dropped the effect list which contains the - // deletion. We need to reconcile to delete the current child. - reconcileChildFibers(workInProgress, current.child, null, renderLanes); - } - - return fallbackChildFragment; -} - -function mountDehydratedSuspenseComponent( - workInProgress: Fiber, - suspenseInstance: SuspenseInstance, - renderLanes: Lanes, -): null | Fiber { - // During the first pass, we'll bail out and not drill into the children. - // Instead, we'll leave the content in place and try to hydrate it later. - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - if (__DEV__) { - console.error( - 'Cannot hydrate Suspense in legacy mode. Switch from ' + - 'ReactDOM.hydrate(element, container) to ' + - 'ReactDOMClient.hydrateRoot(container, )' + - '.render(element) or remove the Suspense components from ' + - 'the server rendered components.', - ); - } - workInProgress.lanes = laneToLanes(SyncLane); - } else if (isSuspenseInstanceFallback(suspenseInstance)) { - // This is a client-only boundary. Since we won't get any content from the server - // for this, we need to schedule that at a higher priority based on when it would - // have timed out. In theory we could render it in this pass but it would have the - // wrong priority associated with it and will prevent hydration of parent path. - // Instead, we'll leave work left on it to render it in a separate commit. - - // TODO This time should be the time at which the server rendered response that is - // a parent to this boundary was displayed. However, since we currently don't have - // a protocol to transfer that time, we'll just estimate it by using the current - // time. This will mean that Suspense timeouts are slightly shifted to later than - // they should be. - // Schedule a normal pri update to render this content. - workInProgress.lanes = laneToLanes(DefaultHydrationLane); - } else { - // We'll continue hydrating the rest at offscreen priority since we'll already - // be showing the right content coming from the server, it is no rush. - workInProgress.lanes = laneToLanes(OffscreenLane); - } - return null; -} - -function updateDehydratedSuspenseComponent( - current: Fiber, - workInProgress: Fiber, - didSuspend: boolean, - nextProps: any, - suspenseInstance: SuspenseInstance, - suspenseState: SuspenseState, - renderLanes: Lanes, -): null | Fiber { - if (!didSuspend) { - // This is the first render pass. Attempt to hydrate. - pushPrimaryTreeSuspenseHandler(workInProgress); - - // We should never be hydrating at this point because it is the first pass, - // but after we've already committed once. - warnIfHydrating(); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - return retrySuspenseComponentWithoutHydrating( - current, - workInProgress, - renderLanes, - null, - ); - } - - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This boundary is in a permanent fallback state. In this case, we'll never - // get an update and we'll never be able to hydrate the final content. Let's just try the - // client side render instead. - let digest, message, stack; - if (__DEV__) { - ({digest, message, stack} = getSuspenseInstanceFallbackErrorDetails( - suspenseInstance, - )); - } else { - ({digest} = getSuspenseInstanceFallbackErrorDetails(suspenseInstance)); - } - - let error; - if (message) { - // eslint-disable-next-line react-internal/prod-error-codes - error = new Error(message); - } else { - error = new Error( - 'The server could not finish this Suspense boundary, likely ' + - 'due to an error during server rendering. Switched to ' + - 'client rendering.', - ); - } - (error: any).digest = digest; - const capturedValue = createCapturedValue(error, digest, stack); - return retrySuspenseComponentWithoutHydrating( - current, - workInProgress, - renderLanes, - capturedValue, - ); - } - - if ( - enableLazyContextPropagation && - // TODO: Factoring is a little weird, since we check this right below, too. - // But don't want to re-arrange the if-else chain until/unless this - // feature lands. - !didReceiveUpdate - ) { - // We need to check if any children have context before we decide to bail - // out, so propagate the changes now. - lazilyPropagateParentContextChanges(current, workInProgress, renderLanes); - } - - // We use lanes to indicate that a child might depend on context, so if - // any context has changed, we need to treat is as if the input might have changed. - const hasContextChanged = includesSomeLane(renderLanes, current.childLanes); - if (didReceiveUpdate || hasContextChanged) { - // This boundary has changed since the first render. This means that we are now unable to - // hydrate it. We might still be able to hydrate it using a higher priority lane. - const root = getWorkInProgressRoot(); - if (root !== null) { - const attemptHydrationAtLane = getBumpedLaneForHydration( - root, - renderLanes, - ); - if ( - attemptHydrationAtLane !== NoLane && - attemptHydrationAtLane !== suspenseState.retryLane - ) { - // Intentionally mutating since this render will get interrupted. This - // is one of the very rare times where we mutate the current tree - // during the render phase. - suspenseState.retryLane = attemptHydrationAtLane; - // TODO: Ideally this would inherit the event time of the current render - const eventTime = NoTimestamp; - enqueueConcurrentRenderForLane(current, attemptHydrationAtLane); - scheduleUpdateOnFiber( - root, - current, - attemptHydrationAtLane, - eventTime, - ); - - // Throw a special object that signals to the work loop that it should - // interrupt the current render. - // - // Because we're inside a React-only execution stack, we don't - // strictly need to throw here — we could instead modify some internal - // work loop state. But using an exception means we don't need to - // check for this case on every iteration of the work loop. So doing - // it this way moves the check out of the fast path. - throw SelectiveHydrationException; - } else { - // We have already tried to ping at a higher priority than we're rendering with - // so if we got here, we must have failed to hydrate at those levels. We must - // now give up. Instead, we're going to delete the whole subtree and instead inject - // a new real Suspense boundary to take its place, which may render content - // or fallback. This might suspend for a while and if it does we might still have - // an opportunity to hydrate before this pass commits. - } - } - - // If we did not selectively hydrate, we'll continue rendering without - // hydrating. Mark this tree as suspended to prevent it from committing - // outside a transition. - // - // This path should only happen if the hydration lane already suspended. - // Currently, it also happens during sync updates because there is no - // hydration lane for sync updates. - // TODO: We should ideally have a sync hydration lane that we can apply to do - // a pass where we hydrate this subtree in place using the previous Context and then - // reapply the update afterwards. - renderDidSuspendDelayIfPossible(); - return retrySuspenseComponentWithoutHydrating( - current, - workInProgress, - renderLanes, - null, - ); - } else if (isSuspenseInstancePending(suspenseInstance)) { - // This component is still pending more data from the server, so we can't hydrate its - // content. We treat it as if this component suspended itself. It might seem as if - // we could just try to render it client-side instead. However, this will perform a - // lot of unnecessary work and is unlikely to complete since it often will suspend - // on missing data anyway. Additionally, the server might be able to render more - // than we can on the client yet. In that case we'd end up with more fallback states - // on the client than if we just leave it alone. If the server times out or errors - // these should update this boundary to the permanent Fallback state instead. - // Mark it as having captured (i.e. suspended). - workInProgress.flags |= DidCapture; - // Leave the child in place. I.e. the dehydrated fragment. - workInProgress.child = current.child; - // Register a callback to retry this boundary once the server has sent the result. - const retry = retryDehydratedSuspenseBoundary.bind(null, current); - registerSuspenseInstanceRetry(suspenseInstance, retry); - return null; - } else { - // This is the first attempt. - reenterHydrationStateFromDehydratedSuspenseInstance( - workInProgress, - suspenseInstance, - suspenseState.treeContext, - ); - const primaryChildren = nextProps.children; - const primaryChildFragment = mountSuspensePrimaryChildren( - workInProgress, - primaryChildren, - renderLanes, - ); - // Mark the children as hydrating. This is a fast path to know whether this - // tree is part of a hydrating tree. This is used to determine if a child - // node has fully mounted yet, and for scheduling event replaying. - // Conceptually this is similar to Placement in that a new subtree is - // inserted into the React tree here. It just happens to not need DOM - // mutations because it already exists. - primaryChildFragment.flags |= Hydrating; - return primaryChildFragment; - } - } else { - // This is the second render pass. We already attempted to hydrated, but - // something either suspended or errored. - - if (workInProgress.flags & ForceClientRender) { - // Something errored during hydration. Try again without hydrating. - pushPrimaryTreeSuspenseHandler(workInProgress); - - workInProgress.flags &= ~ForceClientRender; - const capturedValue = createCapturedValue( - new Error( - 'There was an error while hydrating this Suspense boundary. ' + - 'Switched to client rendering.', - ), - ); - return retrySuspenseComponentWithoutHydrating( - current, - workInProgress, - renderLanes, - capturedValue, - ); - } else if ((workInProgress.memoizedState: null | SuspenseState) !== null) { - // Something suspended and we should still be in dehydrated mode. - // Leave the existing child in place. - - // Push to avoid a mismatch - pushFallbackTreeSuspenseHandler(workInProgress); - - workInProgress.child = current.child; - // The dehydrated completion pass expects this flag to be there - // but the normal suspense pass doesn't. - workInProgress.flags |= DidCapture; - return null; - } else { - // Suspended but we should no longer be in dehydrated mode. - // Therefore we now have to render the fallback. - pushFallbackTreeSuspenseHandler(workInProgress); - - const nextPrimaryChildren = nextProps.children; - const nextFallbackChildren = nextProps.fallback; - const fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating( - current, - workInProgress, - nextPrimaryChildren, - nextFallbackChildren, - renderLanes, - ); - const primaryChildFragment: Fiber = (workInProgress.child: any); - primaryChildFragment.memoizedState = mountSuspenseOffscreenState( - renderLanes, - ); - workInProgress.memoizedState = SUSPENDED_MARKER; - return fallbackChildFragment; - } - } -} - -function scheduleSuspenseWorkOnFiber( - fiber: Fiber, - renderLanes: Lanes, - propagationRoot: Fiber, -) { - fiber.lanes = mergeLanes(fiber.lanes, renderLanes); - const alternate = fiber.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); -} - -function propagateSuspenseContextChange( - workInProgress: Fiber, - firstChild: null | Fiber, - renderLanes: Lanes, -): void { - // Mark any Suspense boundaries with fallbacks as having work to do. - // If they were previously forced into fallbacks, they may now be able - // to unblock. - let node = firstChild; - while (node !== null) { - if (node.tag === SuspenseComponent) { - const state: SuspenseState | null = node.memoizedState; - if (state !== null) { - scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); - } - } else if (node.tag === SuspenseListComponent) { - // If the tail is hidden there might not be an Suspense boundaries - // to schedule work on. In this case we have to schedule it on the - // list itself. - // We don't have to traverse to the children of the list since - // the list will propagate the change when it rerenders. - scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress) { - return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - while (node.sibling === null) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (node.return === null || node.return === workInProgress) { - return; - } - node = node.return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - node.sibling.return = node.return; - node = node.sibling; - } -} - -function findLastContentRow(firstChild: null | Fiber): null | Fiber { - // This is going to find the last row among these children that is already - // showing content on the screen, as opposed to being in fallback state or - // new. If a row has multiple Suspense boundaries, any of them being in the - // fallback state, counts as the whole row being in a fallback state. - // Note that the "rows" will be workInProgress, but any nested children - // will still be current since we haven't rendered them yet. The mounted - // order may not be the same as the new order. We use the new order. - let row = firstChild; - let lastContentRow: null | Fiber = null; - while (row !== null) { - const currentRow = row.alternate; - // New rows can't be content rows. - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - lastContentRow = row; - } - row = row.sibling; - } - return lastContentRow; -} - -type SuspenseListRevealOrder = 'forwards' | 'backwards' | 'together' | void; - -function validateRevealOrder(revealOrder: SuspenseListRevealOrder) { - if (__DEV__) { - if ( - revealOrder !== undefined && - revealOrder !== 'forwards' && - revealOrder !== 'backwards' && - revealOrder !== 'together' && - !didWarnAboutRevealOrder[revealOrder] - ) { - didWarnAboutRevealOrder[revealOrder] = true; - if (typeof revealOrder === 'string') { - switch (revealOrder.toLowerCase()) { - case 'together': - case 'forwards': - case 'backwards': { - console.error( - '"%s" is not a valid value for revealOrder on . ' + - 'Use lowercase "%s" instead.', - revealOrder, - revealOrder.toLowerCase(), - ); - break; - } - case 'forward': - case 'backward': { - console.error( - '"%s" is not a valid value for revealOrder on . ' + - 'React uses the -s suffix in the spelling. Use "%ss" instead.', - revealOrder, - revealOrder.toLowerCase(), - ); - break; - } - default: - console.error( - '"%s" is not a supported revealOrder on . ' + - 'Did you mean "together", "forwards" or "backwards"?', - revealOrder, - ); - break; - } - } else { - console.error( - '%s is not a supported value for revealOrder on . ' + - 'Did you mean "together", "forwards" or "backwards"?', - revealOrder, - ); - } - } - } -} - -function validateTailOptions( - tailMode: SuspenseListTailMode, - revealOrder: SuspenseListRevealOrder, -) { - if (__DEV__) { - if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { - if (tailMode !== 'collapsed' && tailMode !== 'hidden') { - didWarnAboutTailOptions[tailMode] = true; - console.error( - '"%s" is not a supported value for tail on . ' + - 'Did you mean "collapsed" or "hidden"?', - tailMode, - ); - } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { - didWarnAboutTailOptions[tailMode] = true; - console.error( - ' is only valid if revealOrder is ' + - '"forwards" or "backwards". ' + - 'Did you mean to specify revealOrder="forwards"?', - tailMode, - ); - } - } - } -} - -function validateSuspenseListNestedChild(childSlot: mixed, index: number) { - if (__DEV__) { - const isAnArray = isArray(childSlot); - const isIterable = - !isAnArray && typeof getIteratorFn(childSlot) === 'function'; - if (isAnArray || isIterable) { - const type = isAnArray ? 'array' : 'iterable'; - console.error( - 'A nested %s was passed to row #%s in . Wrap it in ' + - 'an additional SuspenseList to configure its revealOrder: ' + - ' ... ' + - '{%s} ... ' + - '', - type, - index, - type, - ); - return false; - } - } - return true; -} - -function validateSuspenseListChildren( - children: mixed, - revealOrder: SuspenseListRevealOrder, -) { - if (__DEV__) { - if ( - (revealOrder === 'forwards' || revealOrder === 'backwards') && - children !== undefined && - children !== null && - children !== false - ) { - if (isArray(children)) { - for (let i = 0; i < children.length; i++) { - if (!validateSuspenseListNestedChild(children[i], i)) { - return; - } - } - } else { - const iteratorFn = getIteratorFn(children); - if (typeof iteratorFn === 'function') { - const childrenIterator = iteratorFn.call(children); - if (childrenIterator) { - let step = childrenIterator.next(); - let i = 0; - for (; !step.done; step = childrenIterator.next()) { - if (!validateSuspenseListNestedChild(step.value, i)) { - return; - } - i++; - } - } - } else { - console.error( - 'A single row was passed to a . ' + - 'This is not useful since it needs multiple rows. ' + - 'Did you mean to pass multiple children or an array?', - revealOrder, - ); - } - } - } - } -} - -function initSuspenseListRenderState( - workInProgress: Fiber, - isBackwards: boolean, - tail: null | Fiber, - lastContentRow: null | Fiber, - tailMode: SuspenseListTailMode, -): void { - const renderState: null | SuspenseListRenderState = - workInProgress.memoizedState; - if (renderState === null) { - workInProgress.memoizedState = ({ - isBackwards: isBackwards, - rendering: null, - renderingStartTime: 0, - last: lastContentRow, - tail: tail, - tailMode: tailMode, - }: SuspenseListRenderState); - } else { - // We can reuse the existing object from previous renders. - renderState.isBackwards = isBackwards; - renderState.rendering = null; - renderState.renderingStartTime = 0; - renderState.last = lastContentRow; - renderState.tail = tail; - renderState.tailMode = tailMode; - } -} - -// This can end up rendering this component multiple passes. -// The first pass splits the children fibers into two sets. A head and tail. -// We first render the head. If anything is in fallback state, we do another -// pass through beginWork to rerender all children (including the tail) with -// the force suspend context. If the first render didn't have anything in -// in fallback state. Then we render each row in the tail one-by-one. -// That happens in the completeWork phase without going back to beginWork. -function updateSuspenseListComponent( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - const nextProps = workInProgress.pendingProps; - const revealOrder: SuspenseListRevealOrder = nextProps.revealOrder; - const tailMode: SuspenseListTailMode = nextProps.tail; - const newChildren = nextProps.children; - - validateRevealOrder(revealOrder); - validateTailOptions(tailMode, revealOrder); - validateSuspenseListChildren(newChildren, revealOrder); - - reconcileChildren(current, workInProgress, newChildren, renderLanes); - - let suspenseContext: SuspenseContext = suspenseStackCursor.current; - - const shouldForceFallback = hasSuspenseListContext( - suspenseContext, - (ForceSuspenseFallback: SuspenseContext), - ); - if (shouldForceFallback) { - suspenseContext = setShallowSuspenseListContext( - suspenseContext, - ForceSuspenseFallback, - ); - workInProgress.flags |= DidCapture; - } else { - const didSuspendBefore = - current !== null && (current.flags & DidCapture) !== NoFlags; - if (didSuspendBefore) { - // If we previously forced a fallback, we need to schedule work - // on any nested boundaries to let them know to try to render - // again. This is the same as context updating. - propagateSuspenseContextChange( - workInProgress, - workInProgress.child, - renderLanes, - ); - } - suspenseContext = setDefaultShallowSuspenseListContext(suspenseContext); - } - pushSuspenseListContext(workInProgress, suspenseContext); - - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - // In legacy mode, SuspenseList doesn't work so we just - // use make it a noop by treating it as the default revealOrder. - workInProgress.memoizedState = null; - } else { - switch (revealOrder) { - case 'forwards': { - const lastContentRow = findLastContentRow(workInProgress.child); - let tail; - if (lastContentRow === null) { - // The whole list is part of the tail. - // TODO: We could fast path by just rendering the tail now. - tail = workInProgress.child; - workInProgress.child = null; - } else { - // Disconnect the tail rows after the content row. - // We're going to render them separately later. - tail = lastContentRow.sibling; - lastContentRow.sibling = null; - } - initSuspenseListRenderState( - workInProgress, - false, // isBackwards - tail, - lastContentRow, - tailMode, - ); - break; - } - case 'backwards': { - // We're going to find the first row that has existing content. - // At the same time we're going to reverse the list of everything - // we pass in the meantime. That's going to be our tail in reverse - // order. - let tail = null; - let row = workInProgress.child; - workInProgress.child = null; - while (row !== null) { - const currentRow = row.alternate; - // New rows can't be content rows. - if (currentRow !== null && findFirstSuspended(currentRow) === null) { - // This is the beginning of the main content. - workInProgress.child = row; - break; - } - const nextRow = row.sibling; - row.sibling = tail; - tail = row; - row = nextRow; - } - // TODO: If workInProgress.child is null, we can continue on the tail immediately. - initSuspenseListRenderState( - workInProgress, - true, // isBackwards - tail, - null, // last - tailMode, - ); - break; - } - case 'together': { - initSuspenseListRenderState( - workInProgress, - false, // isBackwards - null, // tail - null, // last - undefined, - ); - break; - } - default: { - // The default reveal order is the same as not having - // a boundary. - workInProgress.memoizedState = null; - } - } - } - return workInProgress.child; -} - -function updatePortalComponent( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - const nextChildren = workInProgress.pendingProps; - if (current === null) { - // Portals are special because we don't append the children during mount - // but at commit. Therefore we need to track insertions which the normal - // flow doesn't do during mount. This doesn't happen at the root because - // the root always starts with a "current" with a null child. - // TODO: Consider unifying this with how the root works. - workInProgress.child = reconcileChildFibers( - workInProgress, - null, - nextChildren, - renderLanes, - ); - } else { - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - } - return workInProgress.child; -} - -let hasWarnedAboutUsingNoValuePropOnContextProvider = false; - -function updateContextProvider( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - const providerType: ReactProviderType = workInProgress.type; - const context: ReactContext = providerType._context; - - const newProps = workInProgress.pendingProps; - const oldProps = workInProgress.memoizedProps; - - const newValue = newProps.value; - - if (__DEV__) { - if (!('value' in newProps)) { - if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { - hasWarnedAboutUsingNoValuePropOnContextProvider = true; - console.error( - 'The `value` prop is required for the ``. Did you misspell it or forget to pass it?', - ); - } - } - const providerPropTypes = workInProgress.type.propTypes; - - if (providerPropTypes) { - checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); - } - } - - pushProvider(workInProgress, context, newValue); - - if (enableLazyContextPropagation) { - // In the lazy propagation implementation, we don't scan for matching - // consumers until something bails out, because until something bails out - // we're going to visit those nodes, anyway. The trade-off is that it shifts - // responsibility to the consumer to track whether something has changed. - } else { - if (oldProps !== null) { - const oldValue = oldProps.value; - if (is(oldValue, newValue)) { - // No change. Bailout early if children are the same. - if ( - oldProps.children === newProps.children && - !hasLegacyContextChanged() - ) { - return bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes, - ); - } - } else { - // The context value changed. Search for matching consumers and schedule - // them to update. - propagateContextChange(workInProgress, context, renderLanes); - } - } - } - - const newChildren = newProps.children; - reconcileChildren(current, workInProgress, newChildren, renderLanes); - return workInProgress.child; -} - -let hasWarnedAboutUsingContextAsConsumer = false; - -function updateContextConsumer( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -) { - let context: ReactContext = workInProgress.type; - // The logic below for Context differs depending on PROD or DEV mode. In - // DEV mode, we create a separate object for Context.Consumer that acts - // like a proxy to Context. This proxy object adds unnecessary code in PROD - // so we use the old behaviour (Context.Consumer references Context) to - // reduce size and overhead. The separate object references context via - // a property called "_context", which also gives us the ability to check - // in DEV mode if this property exists or not and warn if it does not. - if (__DEV__) { - if ((context: any)._context === undefined) { - // This may be because it's a Context (rather than a Consumer). - // Or it may be because it's older React where they're the same thing. - // We only want to warn if we're sure it's a new React. - if (context !== context.Consumer) { - if (!hasWarnedAboutUsingContextAsConsumer) { - hasWarnedAboutUsingContextAsConsumer = true; - console.error( - 'Rendering directly is not supported and will be removed in ' + - 'a future major release. Did you mean to render instead?', - ); - } - } - } else { - context = (context: any)._context; - } - } - const newProps = workInProgress.pendingProps; - const render = newProps.children; - - if (__DEV__) { - if (typeof render !== 'function') { - console.error( - 'A context consumer was rendered with multiple children, or a child ' + - "that isn't a function. A context consumer expects a single child " + - 'that is a function. If you did pass a function, make sure there ' + - 'is no trailing or leading whitespace around it.', - ); - } - } - - prepareToReadContext(workInProgress, renderLanes); - const newValue = readContext(context); - if (enableSchedulingProfiler) { - markComponentRenderStarted(workInProgress); - } - let newChildren; - if (__DEV__) { - ReactCurrentOwner.current = workInProgress; - setIsRendering(true); - newChildren = render(newValue); - setIsRendering(false); - } else { - newChildren = render(newValue); - } - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - } - - // React DevTools reads this flag. - workInProgress.flags |= PerformedWork; - reconcileChildren(current, workInProgress, newChildren, renderLanes); - return workInProgress.child; -} - -function updateScopeComponent(current, workInProgress, renderLanes) { - const nextProps = workInProgress.pendingProps; - const nextChildren = nextProps.children; - - reconcileChildren(current, workInProgress, nextChildren, renderLanes); - return workInProgress.child; -} - -export function markWorkInProgressReceivedUpdate() { - didReceiveUpdate = true; -} - -export function checkIfWorkInProgressReceivedUpdate(): boolean { - return didReceiveUpdate; -} - -function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) { - if ((workInProgress.mode & ConcurrentMode) === NoMode) { - if (current !== null) { - // A lazy component only mounts if it suspended inside a non- - // concurrent tree, in an inconsistent state. We want to treat it like - // a new mount, even though an empty version of it already committed. - // Disconnect the alternate pointers. - current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect - workInProgress.flags |= Placement; - } - } -} - -function bailoutOnAlreadyFinishedWork( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -): Fiber | null { - if (current !== null) { - // Reuse previous dependencies - workInProgress.dependencies = current.dependencies; - } - - if (enableProfilerTimer) { - // Don't update "base" render times for bailouts. - stopProfilerTimerIfRunning(workInProgress); - } - - markSkippedUpdateLanes(workInProgress.lanes); - - // Check if the children have any pending work. - if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { - // The children don't have any work either. We can skip them. - // TODO: Once we add back resuming, we should check if the children are - // a work-in-progress set. If so, we need to transfer their effects. - - if (enableLazyContextPropagation && current !== null) { - // Before bailing out, check if there are any context changes in - // the children. - lazilyPropagateParentContextChanges(current, workInProgress, renderLanes); - if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { - return null; - } - } else { - return null; - } - } - - // This fiber doesn't have work, but its subtree does. Clone the child - // fibers and continue. - cloneChildFibers(current, workInProgress); - return workInProgress.child; -} - -function remountFiber( - current: Fiber, - oldWorkInProgress: Fiber, - newWorkInProgress: Fiber, -): Fiber | null { - if (__DEV__) { - const returnFiber = oldWorkInProgress.return; - if (returnFiber === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Cannot swap the root fiber.'); - } - - // Disconnect from the old current. - // It will get deleted. - current.alternate = null; - oldWorkInProgress.alternate = null; - - // Connect to the new tree. - newWorkInProgress.index = oldWorkInProgress.index; - newWorkInProgress.sibling = oldWorkInProgress.sibling; - newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; - - // Replace the child/sibling pointers above it. - if (oldWorkInProgress === returnFiber.child) { - returnFiber.child = newWorkInProgress; - } else { - let prevSibling = returnFiber.child; - if (prevSibling === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Expected parent to have a child.'); - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - while (prevSibling.sibling !== oldWorkInProgress) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - prevSibling = prevSibling.sibling; - if (prevSibling === null) { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('Expected to find the previous sibling.'); - } - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - prevSibling.sibling = newWorkInProgress; - } - - // Delete the old fiber and place the new one. - // Since the old fiber is disconnected, we have to schedule it manually. - const deletions = returnFiber.deletions; - if (deletions === null) { - returnFiber.deletions = [current]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(current); - } - - newWorkInProgress.flags |= Placement; - - // Restart work from the new fiber. - return newWorkInProgress; - } else { - throw new Error( - 'Did not expect this call in production. ' + - 'This is a bug in React. Please file an issue.', - ); - } -} - -function checkScheduledUpdateOrContext( - current: Fiber, - renderLanes: Lanes, -): boolean { - // Before performing an early bailout, we must check if there are pending - // updates or context. - const updateLanes = current.lanes; - if (includesSomeLane(updateLanes, renderLanes)) { - return true; - } - // No pending update, but because context is propagated lazily, we need - // to check for a context change before we bail out. - if (enableLazyContextPropagation) { - const dependencies = current.dependencies; - if (dependencies !== null && checkIfContextChanged(dependencies)) { - return true; - } - } - return false; -} - -function attemptEarlyBailoutIfNoScheduledUpdate( - current: Fiber, - workInProgress: Fiber, - renderLanes: Lanes, -) { - // This fiber does not have any pending work. Bailout without entering - // the begin phase. There's still some bookkeeping we that needs to be done - // in this optimized path, mostly pushing stuff onto the stack. - switch (workInProgress.tag) { - case HostRoot: - pushHostRootContext(workInProgress); - const root: FiberRoot = workInProgress.stateNode; - pushRootTransition(workInProgress, root, renderLanes); - - if (enableTransitionTracing) { - pushRootMarkerInstance(workInProgress); - } - - if (enableCache) { - const cache: Cache = current.memoizedState.cache; - pushCacheProvider(workInProgress, cache); - } - resetHydrationState(); - break; - case HostResource: - case HostSingleton: - case HostComponent: - pushHostContext(workInProgress); - break; - case ClassComponent: { - const Component = workInProgress.type; - if (isLegacyContextProvider(Component)) { - pushLegacyContextProvider(workInProgress); - } - break; - } - case HostPortal: - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - break; - case ContextProvider: { - const newValue = workInProgress.memoizedProps.value; - const context: ReactContext = workInProgress.type._context; - pushProvider(workInProgress, context, newValue); - break; - } - case Profiler: - if (enableProfilerTimer) { - // Profiler should only call onRender when one of its descendants actually rendered. - const hasChildWork = includesSomeLane( - renderLanes, - workInProgress.childLanes, - ); - if (hasChildWork) { - workInProgress.flags |= Update; - } - - if (enableProfilerCommitHooks) { - // Reset effect durations for the next eventual effect phase. - // These are reset during render to allow the DevTools commit hook a chance to read them, - const stateNode = workInProgress.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - } - break; - case SuspenseComponent: { - const state: SuspenseState | null = workInProgress.memoizedState; - if (state !== null) { - if (state.dehydrated !== null) { - // We're not going to render the children, so this is just to maintain - // push/pop symmetry - pushPrimaryTreeSuspenseHandler(workInProgress); - // We know that this component will suspend again because if it has - // been unsuspended it has committed as a resolved Suspense component. - // If it needs to be retried, it should have work scheduled on it. - workInProgress.flags |= DidCapture; - // We should never render the children of a dehydrated boundary until we - // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. - return null; - } - - // If this boundary is currently timed out, we need to decide - // whether to retry the primary children, or to skip over it and - // go straight to the fallback. Check the priority of the primary - // child fragment. - const primaryChildFragment: Fiber = (workInProgress.child: any); - const primaryChildLanes = primaryChildFragment.childLanes; - if (includesSomeLane(renderLanes, primaryChildLanes)) { - // The primary children have pending work. Use the normal path - // to attempt to render the primary children again. - return updateSuspenseComponent(current, workInProgress, renderLanes); - } else { - // The primary child fragment does not have pending work marked - // on it - pushPrimaryTreeSuspenseHandler(workInProgress); - // The primary children do not have pending work with sufficient - // priority. Bailout. - const child = bailoutOnAlreadyFinishedWork( - current, - workInProgress, - renderLanes, - ); - if (child !== null) { - // The fallback children have pending work. Skip over the - // primary children and work on the fallback. - return child.sibling; - } else { - // Note: We can return `null` here because we already checked - // whether there were nested context consumers, via the call to - // `bailoutOnAlreadyFinishedWork` above. - return null; - } - } - } else { - pushPrimaryTreeSuspenseHandler(workInProgress); - } - break; - } - case SuspenseListComponent: { - const didSuspendBefore = (current.flags & DidCapture) !== NoFlags; - - let hasChildWork = includesSomeLane( - renderLanes, - workInProgress.childLanes, - ); - - if (enableLazyContextPropagation && !hasChildWork) { - // Context changes may not have been propagated yet. We need to do - // that now, before we can decide whether to bail out. - // TODO: We use `childLanes` as a heuristic for whether there is - // remaining work in a few places, including - // `bailoutOnAlreadyFinishedWork` and - // `updateDehydratedSuspenseComponent`. We should maybe extract this - // into a dedicated function. - lazilyPropagateParentContextChanges( - current, - workInProgress, - renderLanes, - ); - hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); - } - - if (didSuspendBefore) { - if (hasChildWork) { - // If something was in fallback state last time, and we have all the - // same children then we're still in progressive loading state. - // Something might get unblocked by state updates or retries in the - // tree which will affect the tail. So we need to use the normal - // path to compute the correct tail. - return updateSuspenseListComponent( - current, - workInProgress, - renderLanes, - ); - } - // If none of the children had any work, that means that none of - // them got retried so they'll still be blocked in the same way - // as before. We can fast bail out. - workInProgress.flags |= DidCapture; - } - - // If nothing suspended before and we're rendering the same children, - // then the tail doesn't matter. Anything new that suspends will work - // in the "together" mode, so we can continue from the state we had. - const renderState = workInProgress.memoizedState; - if (renderState !== null) { - // Reset to the "together" mode in case we've started a different - // update in the past but didn't complete it. - renderState.rendering = null; - renderState.tail = null; - renderState.lastEffect = null; - } - pushSuspenseListContext(workInProgress, suspenseStackCursor.current); - - if (hasChildWork) { - break; - } else { - // If none of the children had any work, that means that none of - // them got retried so they'll still be blocked in the same way - // as before. We can fast bail out. - return null; - } - } - case OffscreenComponent: - case LegacyHiddenComponent: { - // Need to check if the tree still needs to be deferred. This is - // almost identical to the logic used in the normal update path, - // so we'll just enter that. The only difference is we'll bail out - // at the next level instead of this one, because the child props - // have not changed. Which is fine. - // TODO: Probably should refactor `beginWork` to split the bailout - // path from the normal path. I'm tempted to do a labeled break here - // but I won't :) - workInProgress.lanes = NoLanes; - return updateOffscreenComponent(current, workInProgress, renderLanes); - } - case CacheComponent: { - if (enableCache) { - const cache: Cache = current.memoizedState.cache; - pushCacheProvider(workInProgress, cache); - } - break; - } - case TracingMarkerComponent: { - if (enableTransitionTracing) { - const instance: TracingMarkerInstance | null = workInProgress.stateNode; - if (instance !== null) { - pushMarkerInstance(workInProgress, instance); - } - } - } - } - return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); -} - -function beginWork( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -): Fiber | null { - if (__DEV__) { - if (workInProgress._debugNeedsRemount && current !== null) { - // This will restart the begin phase with a new fiber. - return remountFiber( - current, - workInProgress, - createFiberFromTypeAndProps( - workInProgress.type, - workInProgress.key, - workInProgress.pendingProps, - workInProgress._debugOwner || null, - workInProgress.mode, - workInProgress.lanes, - ), - ); - } - } - - if (current !== null) { - const oldProps = current.memoizedProps; - const newProps = workInProgress.pendingProps; - - if ( - oldProps !== newProps || - hasLegacyContextChanged() || - // Force a re-render if the implementation changed due to hot reload: - (__DEV__ ? workInProgress.type !== current.type : false) - ) { - // If props or context changed, mark the fiber as having performed work. - // This may be unset if the props are determined to be equal later (memo). - didReceiveUpdate = true; - } else { - // Neither props nor legacy context changes. Check if there's a pending - // update or context change. - const hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( - current, - renderLanes, - ); - if ( - !hasScheduledUpdateOrContext && - // If this is the second pass of an error or suspense boundary, there - // may not be work scheduled on `current`, so we check for this flag. - (workInProgress.flags & DidCapture) === NoFlags - ) { - // No pending updates or context. Bail out now. - didReceiveUpdate = false; - return attemptEarlyBailoutIfNoScheduledUpdate( - current, - workInProgress, - renderLanes, - ); - } - if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { - // This is a special case that only exists for legacy mode. - // See https://github.com/facebook/react/pull/19216. - didReceiveUpdate = true; - } else { - // An update was scheduled on this fiber, but there are no new props - // nor legacy context. Set this to false. If an update queue or context - // consumer produces a changed value, it will set this to true. Otherwise, - // the component will assume the children have not changed and bail out. - didReceiveUpdate = false; - } - } - } else { - didReceiveUpdate = false; - - if (getIsHydrating() && isForkedChild(workInProgress)) { - // Check if this child belongs to a list of muliple children in - // its parent. - // - // In a true multi-threaded implementation, we would render children on - // parallel threads. This would represent the beginning of a new render - // thread for this subtree. - // - // We only use this for id generation during hydration, which is why the - // logic is located in this special branch. - const slotIndex = workInProgress.index; - const numberOfForks = getForksAtLevel(workInProgress); - pushTreeId(workInProgress, numberOfForks, slotIndex); - } - } - - // Before entering the begin phase, clear pending update priority. - // TODO: This assumes that we're about to evaluate the component and process - // the update queue. However, there's an exception: SimpleMemoComponent - // sometimes bails out later in the begin phase. This indicates that we should - // move this assignment out of the common path and into each branch. - workInProgress.lanes = NoLanes; - - switch (workInProgress.tag) { - case IndeterminateComponent: { - return mountIndeterminateComponent( - current, - workInProgress, - workInProgress.type, - renderLanes, - ); - } - case LazyComponent: { - const elementType = workInProgress.elementType; - return mountLazyComponent( - current, - workInProgress, - elementType, - renderLanes, - ); - } - case FunctionComponent: { - const Component = workInProgress.type; - const unresolvedProps = workInProgress.pendingProps; - const resolvedProps = - workInProgress.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - return updateFunctionComponent( - current, - workInProgress, - Component, - resolvedProps, - renderLanes, - ); - } - case ClassComponent: { - const Component = workInProgress.type; - const unresolvedProps = workInProgress.pendingProps; - const resolvedProps = - workInProgress.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - return updateClassComponent( - current, - workInProgress, - Component, - resolvedProps, - renderLanes, - ); - } - case HostRoot: - return updateHostRoot(current, workInProgress, renderLanes); - case HostResource: - if (enableFloat && supportsResources) { - return updateHostResource(current, workInProgress, renderLanes); - } - // eslint-disable-next-line no-fallthrough - case HostSingleton: - if (enableHostSingletons && supportsSingletons) { - return updateHostSingleton(current, workInProgress, renderLanes); - } - // eslint-disable-next-line no-fallthrough - case HostComponent: - return updateHostComponent(current, workInProgress, renderLanes); - case HostText: - return updateHostText(current, workInProgress); - case SuspenseComponent: - return updateSuspenseComponent(current, workInProgress, renderLanes); - case HostPortal: - return updatePortalComponent(current, workInProgress, renderLanes); - case ForwardRef: { - const type = workInProgress.type; - const unresolvedProps = workInProgress.pendingProps; - const resolvedProps = - workInProgress.elementType === type - ? unresolvedProps - : resolveDefaultProps(type, unresolvedProps); - return updateForwardRef( - current, - workInProgress, - type, - resolvedProps, - renderLanes, - ); - } - case Fragment: - return updateFragment(current, workInProgress, renderLanes); - case Mode: - return updateMode(current, workInProgress, renderLanes); - case Profiler: - return updateProfiler(current, workInProgress, renderLanes); - case ContextProvider: - return updateContextProvider(current, workInProgress, renderLanes); - case ContextConsumer: - return updateContextConsumer(current, workInProgress, renderLanes); - case MemoComponent: { - const type = workInProgress.type; - const unresolvedProps = workInProgress.pendingProps; - // Resolve outer props first, then resolve inner props. - let resolvedProps = resolveDefaultProps(type, unresolvedProps); - if (__DEV__) { - if (workInProgress.type !== workInProgress.elementType) { - const outerPropTypes = type.propTypes; - if (outerPropTypes) { - checkPropTypes( - outerPropTypes, - resolvedProps, // Resolved for outer only - 'prop', - getComponentNameFromType(type), - ); - } - } - } - resolvedProps = resolveDefaultProps(type.type, resolvedProps); - return updateMemoComponent( - current, - workInProgress, - type, - resolvedProps, - renderLanes, - ); - } - case SimpleMemoComponent: { - return updateSimpleMemoComponent( - current, - workInProgress, - workInProgress.type, - workInProgress.pendingProps, - renderLanes, - ); - } - case IncompleteClassComponent: { - const Component = workInProgress.type; - const unresolvedProps = workInProgress.pendingProps; - const resolvedProps = - workInProgress.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - return mountIncompleteClassComponent( - current, - workInProgress, - Component, - resolvedProps, - renderLanes, - ); - } - case SuspenseListComponent: { - return updateSuspenseListComponent(current, workInProgress, renderLanes); - } - case ScopeComponent: { - if (enableScopeAPI) { - return updateScopeComponent(current, workInProgress, renderLanes); - } - break; - } - case OffscreenComponent: { - return updateOffscreenComponent(current, workInProgress, renderLanes); - } - case LegacyHiddenComponent: { - if (enableLegacyHidden) { - return updateLegacyHiddenComponent( - current, - workInProgress, - renderLanes, - ); - } - break; - } - case CacheComponent: { - if (enableCache) { - return updateCacheComponent(current, workInProgress, renderLanes); - } - break; - } - case TracingMarkerComponent: { - if (enableTransitionTracing) { - return updateTracingMarkerComponent( - current, - workInProgress, - renderLanes, - ); - } - break; - } - } - - throw new Error( - `Unknown unit of work tag (${workInProgress.tag}). This error is likely caused by a bug in ` + - 'React. Please file an issue.', - ); -} - -export {beginWork}; diff --git a/packages/react-reconciler/src/ReactFiberBeginWork.old.js b/packages/react-reconciler/src/ReactFiberBeginWork.old.js index 1f22a6e18bcf5..6a017a83343a2 100644 --- a/packages/react-reconciler/src/ReactFiberBeginWork.old.js +++ b/packages/react-reconciler/src/ReactFiberBeginWork.old.js @@ -170,7 +170,7 @@ import { getResource, } from './ReactFiberHostConfig'; import type {SuspenseInstance} from './ReactFiberHostConfig'; -import {shouldError, shouldSuspend} from './ReactFiberReconciler'; +import {shouldError, shouldSuspend} from './ReactFiberReconciler.old'; import {pushHostContext, pushHostContainer} from './ReactFiberHostContext.old'; import { suspenseStackCursor, diff --git a/packages/react-reconciler/src/ReactFiberCache.new.js b/packages/react-reconciler/src/ReactFiberCache.new.js deleted file mode 100644 index 2d73d6a57d03c..0000000000000 --- a/packages/react-reconciler/src/ReactFiberCache.new.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {CacheDispatcher} from './ReactInternalTypes'; -import type {Cache} from './ReactFiberCacheComponent.new'; - -import {enableCache} from 'shared/ReactFeatureFlags'; -import {readContext} from './ReactFiberNewContext.new'; -import {CacheContext} from './ReactFiberCacheComponent.new'; - -function getCacheSignal(): AbortSignal { - if (!enableCache) { - throw new Error('Not implemented.'); - } - const cache: Cache = readContext(CacheContext); - return cache.controller.signal; -} - -function getCacheForType(resourceType: () => T): T { - if (!enableCache) { - throw new Error('Not implemented.'); - } - const cache: Cache = readContext(CacheContext); - let cacheForType: T | void = (cache.data.get(resourceType): any); - if (cacheForType === undefined) { - cacheForType = resourceType(); - cache.data.set(resourceType, cacheForType); - } - return cacheForType; -} - -export const DefaultCacheDispatcher: CacheDispatcher = { - getCacheSignal, - getCacheForType, -}; diff --git a/packages/react-reconciler/src/ReactFiberCacheComponent.new.js b/packages/react-reconciler/src/ReactFiberCacheComponent.new.js deleted file mode 100644 index 56b2025b46a41..0000000000000 --- a/packages/react-reconciler/src/ReactFiberCacheComponent.new.js +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {ReactContext} from 'shared/ReactTypes'; -import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; - -import {enableCache} from 'shared/ReactFeatureFlags'; -import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols'; - -import {pushProvider, popProvider} from './ReactFiberNewContext.new'; -import * as Scheduler from 'scheduler'; - -// In environments without AbortController (e.g. tests) -// replace it with a lightweight shim that only has the features we use. -const AbortControllerLocal: typeof AbortController = enableCache - ? typeof AbortController !== 'undefined' - ? AbortController - : (function AbortControllerShim() { - const listeners = []; - const signal = (this.signal = { - aborted: false, - addEventListener: (type, listener) => { - listeners.push(listener); - }, - }); - - this.abort = () => { - signal.aborted = true; - listeners.forEach(listener => listener()); - }; - }: AbortController) - : (null: any); - -export type Cache = { - controller: AbortControllerLocal, - data: Map<() => mixed, mixed>, - refCount: number, -}; - -export type CacheComponentState = { - +parent: Cache, - +cache: Cache, -}; - -export type SpawnedCachePool = { - +parent: Cache, - +pool: Cache, -}; - -// Intentionally not named imports because Rollup would -// use dynamic dispatch for CommonJS interop named imports. -const { - unstable_scheduleCallback: scheduleCallback, - unstable_NormalPriority: NormalPriority, -} = Scheduler; - -export const CacheContext: ReactContext = enableCache - ? { - $$typeof: REACT_CONTEXT_TYPE, - // We don't use Consumer/Provider for Cache components. So we'll cheat. - Consumer: (null: any), - Provider: (null: any), - // We'll initialize these at the root. - _currentValue: (null: any), - _currentValue2: (null: any), - _threadCount: 0, - _defaultValue: (null: any), - _globalName: (null: any), - } - : (null: any); - -if (__DEV__ && enableCache) { - CacheContext._currentRenderer = null; - CacheContext._currentRenderer2 = null; -} - -// Creates a new empty Cache instance with a ref-count of 0. The caller is responsible -// for retaining the cache once it is in use (retainCache), and releasing the cache -// once it is no longer needed (releaseCache). -export function createCache(): Cache { - if (!enableCache) { - return (null: any); - } - const cache: Cache = { - controller: new AbortControllerLocal(), - data: new Map(), - refCount: 0, - }; - - return cache; -} - -export function retainCache(cache: Cache) { - if (!enableCache) { - return; - } - if (__DEV__) { - if (cache.controller.signal.aborted) { - console.warn( - 'A cache instance was retained after it was already freed. ' + - 'This likely indicates a bug in React.', - ); - } - } - cache.refCount++; -} - -// Cleanup a cache instance, potentially freeing it if there are no more references -export function releaseCache(cache: Cache) { - if (!enableCache) { - return; - } - cache.refCount--; - if (__DEV__) { - if (cache.refCount < 0) { - console.warn( - 'A cache instance was released after it was already freed. ' + - 'This likely indicates a bug in React.', - ); - } - } - if (cache.refCount === 0) { - scheduleCallback(NormalPriority, () => { - cache.controller.abort(); - }); - } -} - -export function pushCacheProvider(workInProgress: Fiber, cache: Cache) { - if (!enableCache) { - return; - } - pushProvider(workInProgress, CacheContext, cache); -} - -export function popCacheProvider(workInProgress: Fiber, cache: Cache) { - if (!enableCache) { - return; - } - popProvider(CacheContext, workInProgress); -} diff --git a/packages/react-reconciler/src/ReactFiberClassComponent.new.js b/packages/react-reconciler/src/ReactFiberClassComponent.new.js deleted file mode 100644 index 14524865749d8..0000000000000 --- a/packages/react-reconciler/src/ReactFiberClassComponent.new.js +++ /dev/null @@ -1,1248 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; -import type {Lanes} from './ReactFiberLane.new'; -import type {UpdateQueue} from './ReactFiberClassUpdateQueue.new'; -import type {Flags} from './ReactFiberFlags'; - -import { - LayoutStatic, - Update, - Snapshot, - MountLayoutDev, -} from './ReactFiberFlags'; -import { - debugRenderPhaseSideEffectsForStrictMode, - disableLegacyContext, - enableDebugTracing, - enableSchedulingProfiler, - warnAboutDeprecatedLifecycles, - enableLazyContextPropagation, -} from 'shared/ReactFeatureFlags'; -import ReactStrictModeWarnings from './ReactStrictModeWarnings.new'; -import {isMounted} from './ReactFiberTreeReflection'; -import {get as getInstance, set as setInstance} from 'shared/ReactInstanceMap'; -import shallowEqual from 'shared/shallowEqual'; -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import getComponentNameFromType from 'shared/getComponentNameFromType'; -import assign from 'shared/assign'; -import isArray from 'shared/isArray'; -import {REACT_CONTEXT_TYPE, REACT_PROVIDER_TYPE} from 'shared/ReactSymbols'; - -import {resolveDefaultProps} from './ReactFiberLazyComponent.new'; -import { - DebugTracingMode, - NoMode, - StrictLegacyMode, - StrictEffectsMode, -} from './ReactTypeOfMode'; - -import { - enqueueUpdate, - entangleTransitions, - processUpdateQueue, - checkHasForceUpdateAfterProcessing, - resetHasForceUpdateBeforeProcessing, - createUpdate, - ReplaceState, - ForceUpdate, - initializeUpdateQueue, - cloneUpdateQueue, -} from './ReactFiberClassUpdateQueue.new'; -import {NoLanes} from './ReactFiberLane.new'; -import { - cacheContext, - getMaskedContext, - getUnmaskedContext, - hasContextChanged, - emptyContextObject, -} from './ReactFiberContext.new'; -import {readContext, checkIfContextChanged} from './ReactFiberNewContext.new'; -import { - requestEventTime, - requestUpdateLane, - scheduleUpdateOnFiber, -} from './ReactFiberWorkLoop.new'; -import {logForceUpdateScheduled, logStateUpdateScheduled} from './DebugTracing'; -import { - markForceUpdateScheduled, - markStateUpdateScheduled, - setIsStrictModeForDevtools, -} from './ReactFiberDevToolsHook.new'; - -const fakeInternalInstance = {}; - -let didWarnAboutStateAssignmentForComponent; -let didWarnAboutUninitializedState; -let didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; -let didWarnAboutLegacyLifecyclesAndDerivedState; -let didWarnAboutUndefinedDerivedState; -let warnOnUndefinedDerivedState; -let warnOnInvalidCallback; -let didWarnAboutDirectlyAssigningPropsToState; -let didWarnAboutContextTypeAndContextTypes; -let didWarnAboutInvalidateContextType; - -if (__DEV__) { - didWarnAboutStateAssignmentForComponent = new Set(); - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); - didWarnAboutInvalidateContextType = new Set(); - - const didWarnOnInvalidCallback = new Set(); - - warnOnInvalidCallback = function(callback: mixed, callerName: string) { - if (callback === null || typeof callback === 'function') { - return; - } - const key = callerName + '_' + (callback: any); - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); - console.error( - '%s(...): Expected the last optional `callback` argument to be a ' + - 'function. Instead received: %s.', - callerName, - callback, - ); - } - }; - - warnOnUndefinedDerivedState = function(type, partialState) { - if (partialState === undefined) { - const componentName = getComponentNameFromType(type) || 'Component'; - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); - console.error( - '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + - 'You have returned undefined.', - componentName, - ); - } - } - }; - - // This is so gross but it's at least non-critical and can be removed if - // it causes problems. This is meant to give a nicer error message for - // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, - // ...)) which otherwise throws a "_processChildContext is not a function" - // exception. - Object.defineProperty(fakeInternalInstance, '_processChildContext', { - enumerable: false, - value: function() { - throw new Error( - '_processChildContext is not available in React 16+. This likely ' + - 'means you have multiple copies of React and are attempting to nest ' + - 'a React 15 tree inside a React 16 tree using ' + - "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + - 'to make sure you have only one copy of React (and ideally, switch ' + - 'to ReactDOM.createPortal).', - ); - }, - }); - Object.freeze(fakeInternalInstance); -} - -function applyDerivedStateFromProps( - workInProgress: Fiber, - ctor: any, - getDerivedStateFromProps: (props: any, state: any) => any, - nextProps: any, -) { - const prevState = workInProgress.memoizedState; - let partialState = getDerivedStateFromProps(nextProps, prevState); - if (__DEV__) { - if ( - debugRenderPhaseSideEffectsForStrictMode && - workInProgress.mode & StrictLegacyMode - ) { - setIsStrictModeForDevtools(true); - try { - // Invoke the function an extra time to help detect side-effects. - partialState = getDerivedStateFromProps(nextProps, prevState); - } finally { - setIsStrictModeForDevtools(false); - } - } - warnOnUndefinedDerivedState(ctor, partialState); - } - // Merge the partial state and the previous state. - const memoizedState = - partialState === null || partialState === undefined - ? prevState - : assign({}, prevState, partialState); - workInProgress.memoizedState = memoizedState; - - // Once the update queue is empty, persist the derived state onto the - // base state. - if (workInProgress.lanes === NoLanes) { - // Queue is always non-null for classes - const updateQueue: UpdateQueue = (workInProgress.updateQueue: any); - updateQueue.baseState = memoizedState; - } -} - -const classComponentUpdater = { - isMounted, - enqueueSetState(inst, payload, callback) { - const fiber = getInstance(inst); - const eventTime = requestEventTime(); - const lane = requestUpdateLane(fiber); - - const update = createUpdate(eventTime, lane); - update.payload = payload; - if (callback !== undefined && callback !== null) { - if (__DEV__) { - warnOnInvalidCallback(callback, 'setState'); - } - update.callback = callback; - } - - const root = enqueueUpdate(fiber, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitions(root, fiber, lane); - } - - if (__DEV__) { - if (enableDebugTracing) { - if (fiber.mode & DebugTracingMode) { - const name = getComponentNameFromFiber(fiber) || 'Unknown'; - logStateUpdateScheduled(name, lane, payload); - } - } - } - - if (enableSchedulingProfiler) { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueReplaceState(inst, payload, callback) { - const fiber = getInstance(inst); - const eventTime = requestEventTime(); - const lane = requestUpdateLane(fiber); - - const update = createUpdate(eventTime, lane); - update.tag = ReplaceState; - update.payload = payload; - - if (callback !== undefined && callback !== null) { - if (__DEV__) { - warnOnInvalidCallback(callback, 'replaceState'); - } - update.callback = callback; - } - - const root = enqueueUpdate(fiber, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitions(root, fiber, lane); - } - - if (__DEV__) { - if (enableDebugTracing) { - if (fiber.mode & DebugTracingMode) { - const name = getComponentNameFromFiber(fiber) || 'Unknown'; - logStateUpdateScheduled(name, lane, payload); - } - } - } - - if (enableSchedulingProfiler) { - markStateUpdateScheduled(fiber, lane); - } - }, - enqueueForceUpdate(inst, callback) { - const fiber = getInstance(inst); - const eventTime = requestEventTime(); - const lane = requestUpdateLane(fiber); - - const update = createUpdate(eventTime, lane); - update.tag = ForceUpdate; - - if (callback !== undefined && callback !== null) { - if (__DEV__) { - warnOnInvalidCallback(callback, 'forceUpdate'); - } - update.callback = callback; - } - - const root = enqueueUpdate(fiber, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitions(root, fiber, lane); - } - - if (__DEV__) { - if (enableDebugTracing) { - if (fiber.mode & DebugTracingMode) { - const name = getComponentNameFromFiber(fiber) || 'Unknown'; - logForceUpdateScheduled(name, lane); - } - } - } - - if (enableSchedulingProfiler) { - markForceUpdateScheduled(fiber, lane); - } - }, -}; - -function checkShouldComponentUpdate( - workInProgress, - ctor, - oldProps, - newProps, - oldState, - newState, - nextContext, -) { - const instance = workInProgress.stateNode; - if (typeof instance.shouldComponentUpdate === 'function') { - let shouldUpdate = instance.shouldComponentUpdate( - newProps, - newState, - nextContext, - ); - if (__DEV__) { - if ( - debugRenderPhaseSideEffectsForStrictMode && - workInProgress.mode & StrictLegacyMode - ) { - setIsStrictModeForDevtools(true); - try { - // Invoke the function an extra time to help detect side-effects. - shouldUpdate = instance.shouldComponentUpdate( - newProps, - newState, - nextContext, - ); - } finally { - setIsStrictModeForDevtools(false); - } - } - if (shouldUpdate === undefined) { - console.error( - '%s.shouldComponentUpdate(): Returned undefined instead of a ' + - 'boolean value. Make sure to return true or false.', - getComponentNameFromType(ctor) || 'Component', - ); - } - } - - return shouldUpdate; - } - - if (ctor.prototype && ctor.prototype.isPureReactComponent) { - return ( - !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) - ); - } - - return true; -} - -function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) { - const instance = workInProgress.stateNode; - if (__DEV__) { - const name = getComponentNameFromType(ctor) || 'Component'; - const renderPresent = instance.render; - - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === 'function') { - console.error( - '%s(...): No `render` method found on the returned component ' + - 'instance: did you accidentally return an object from the constructor?', - name, - ); - } else { - console.error( - '%s(...): No `render` method found on the returned component ' + - 'instance: you may have forgotten to define `render`.', - name, - ); - } - } - - if ( - instance.getInitialState && - !instance.getInitialState.isReactClassApproved && - !instance.state - ) { - console.error( - 'getInitialState was defined on %s, a plain JavaScript class. ' + - 'This is only supported for classes created using React.createClass. ' + - 'Did you mean to define a state property instead?', - name, - ); - } - if ( - instance.getDefaultProps && - !instance.getDefaultProps.isReactClassApproved - ) { - console.error( - 'getDefaultProps was defined on %s, a plain JavaScript class. ' + - 'This is only supported for classes created using React.createClass. ' + - 'Use a static property to define defaultProps instead.', - name, - ); - } - if (instance.propTypes) { - console.error( - 'propTypes was defined as an instance property on %s. Use a static ' + - 'property to define propTypes instead.', - name, - ); - } - if (instance.contextType) { - console.error( - 'contextType was defined as an instance property on %s. Use a static ' + - 'property to define contextType instead.', - name, - ); - } - - if (disableLegacyContext) { - if (ctor.childContextTypes) { - console.error( - '%s uses the legacy childContextTypes API which is no longer supported. ' + - 'Use React.createContext() instead.', - name, - ); - } - if (ctor.contextTypes) { - console.error( - '%s uses the legacy contextTypes API which is no longer supported. ' + - 'Use React.createContext() with static contextType instead.', - name, - ); - } - } else { - if (instance.contextTypes) { - console.error( - 'contextTypes was defined as an instance property on %s. Use a static ' + - 'property to define contextTypes instead.', - name, - ); - } - - if ( - ctor.contextType && - ctor.contextTypes && - !didWarnAboutContextTypeAndContextTypes.has(ctor) - ) { - didWarnAboutContextTypeAndContextTypes.add(ctor); - console.error( - '%s declares both contextTypes and contextType static properties. ' + - 'The legacy contextTypes property will be ignored.', - name, - ); - } - } - - if (typeof instance.componentShouldUpdate === 'function') { - console.error( - '%s has a method called ' + - 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + - 'The name is phrased as a question because the function is ' + - 'expected to return a value.', - name, - ); - } - if ( - ctor.prototype && - ctor.prototype.isPureReactComponent && - typeof instance.shouldComponentUpdate !== 'undefined' - ) { - console.error( - '%s has a method called shouldComponentUpdate(). ' + - 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + - 'Please extend React.Component if shouldComponentUpdate is used.', - getComponentNameFromType(ctor) || 'A pure component', - ); - } - if (typeof instance.componentDidUnmount === 'function') { - console.error( - '%s has a method called ' + - 'componentDidUnmount(). But there is no such lifecycle method. ' + - 'Did you mean componentWillUnmount()?', - name, - ); - } - if (typeof instance.componentDidReceiveProps === 'function') { - console.error( - '%s has a method called ' + - 'componentDidReceiveProps(). But there is no such lifecycle method. ' + - 'If you meant to update the state in response to changing props, ' + - 'use componentWillReceiveProps(). If you meant to fetch data or ' + - 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', - name, - ); - } - if (typeof instance.componentWillRecieveProps === 'function') { - console.error( - '%s has a method called ' + - 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', - name, - ); - } - if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { - console.error( - '%s has a method called ' + - 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', - name, - ); - } - const hasMutatedProps = instance.props !== newProps; - if (instance.props !== undefined && hasMutatedProps) { - console.error( - '%s(...): When calling super() in `%s`, make sure to pass ' + - "up the same props that your component's constructor was passed.", - name, - name, - ); - } - if (instance.defaultProps) { - console.error( - 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + - ' Instead, define defaultProps as a static property on %s.', - name, - name, - ); - } - - if ( - typeof instance.getSnapshotBeforeUpdate === 'function' && - typeof instance.componentDidUpdate !== 'function' && - !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) - ) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - console.error( - '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + - 'This component defines getSnapshotBeforeUpdate() only.', - getComponentNameFromType(ctor), - ); - } - - if (typeof instance.getDerivedStateFromProps === 'function') { - console.error( - '%s: getDerivedStateFromProps() is defined as an instance method ' + - 'and will be ignored. Instead, declare it as a static method.', - name, - ); - } - if (typeof instance.getDerivedStateFromError === 'function') { - console.error( - '%s: getDerivedStateFromError() is defined as an instance method ' + - 'and will be ignored. Instead, declare it as a static method.', - name, - ); - } - if (typeof ctor.getSnapshotBeforeUpdate === 'function') { - console.error( - '%s: getSnapshotBeforeUpdate() is defined as a static method ' + - 'and will be ignored. Instead, declare it as an instance method.', - name, - ); - } - const state = instance.state; - if (state && (typeof state !== 'object' || isArray(state))) { - console.error('%s.state: must be set to an object or null', name); - } - if ( - typeof instance.getChildContext === 'function' && - typeof ctor.childContextTypes !== 'object' - ) { - console.error( - '%s.getChildContext(): childContextTypes must be defined in order to ' + - 'use getChildContext().', - name, - ); - } - } -} - -function adoptClassInstance(workInProgress: Fiber, instance: any): void { - instance.updater = classComponentUpdater; - workInProgress.stateNode = instance; - // The instance needs access to the fiber so that it can schedule updates - setInstance(instance, workInProgress); - if (__DEV__) { - instance._reactInternalInstance = fakeInternalInstance; - } -} - -function constructClassInstance( - workInProgress: Fiber, - ctor: any, - props: any, -): any { - let isLegacyContextConsumer = false; - let unmaskedContext = emptyContextObject; - let context = emptyContextObject; - const contextType = ctor.contextType; - - if (__DEV__) { - if ('contextType' in ctor) { - const isValid = - // Allow null for conditional declaration - contextType === null || - (contextType !== undefined && - contextType.$$typeof === REACT_CONTEXT_TYPE && - contextType._context === undefined); // Not a - - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - - let addendum = ''; - if (contextType === undefined) { - addendum = - ' However, it is set to undefined. ' + - 'This can be caused by a typo or by mixing up named and default imports. ' + - 'This can also happen due to a circular dependency, so ' + - 'try moving the createContext() call to a separate file.'; - } else if (typeof contextType !== 'object') { - addendum = ' However, it is set to a ' + typeof contextType + '.'; - } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { - addendum = ' Did you accidentally pass the Context.Provider instead?'; - } else if (contextType._context !== undefined) { - // - addendum = ' Did you accidentally pass the Context.Consumer instead?'; - } else { - addendum = - ' However, it is set to an object with keys {' + - Object.keys(contextType).join(', ') + - '}.'; - } - console.error( - '%s defines an invalid contextType. ' + - 'contextType should point to the Context object returned by React.createContext().%s', - getComponentNameFromType(ctor) || 'Component', - addendum, - ); - } - } - } - - if (typeof contextType === 'object' && contextType !== null) { - context = readContext((contextType: any)); - } else if (!disableLegacyContext) { - unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - const contextTypes = ctor.contextTypes; - isLegacyContextConsumer = - contextTypes !== null && contextTypes !== undefined; - context = isLegacyContextConsumer - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyContextObject; - } - - let instance = new ctor(props, context); - // Instantiate twice to help detect side-effects. - if (__DEV__) { - if ( - debugRenderPhaseSideEffectsForStrictMode && - workInProgress.mode & StrictLegacyMode - ) { - setIsStrictModeForDevtools(true); - try { - instance = new ctor(props, context); // eslint-disable-line no-new - } finally { - setIsStrictModeForDevtools(false); - } - } - } - - const state = (workInProgress.memoizedState = - instance.state !== null && instance.state !== undefined - ? instance.state - : null); - adoptClassInstance(workInProgress, instance); - - if (__DEV__) { - if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { - const componentName = getComponentNameFromType(ctor) || 'Component'; - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); - console.error( - '`%s` uses `getDerivedStateFromProps` but its initial state is ' + - '%s. This is not recommended. Instead, define the initial state by ' + - 'assigning an object to `this.state` in the constructor of `%s`. ' + - 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', - componentName, - instance.state === null ? 'null' : 'undefined', - componentName, - ); - } - } - - // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - if ( - typeof ctor.getDerivedStateFromProps === 'function' || - typeof instance.getSnapshotBeforeUpdate === 'function' - ) { - let foundWillMountName = null; - let foundWillReceivePropsName = null; - let foundWillUpdateName = null; - if ( - typeof instance.componentWillMount === 'function' && - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - foundWillMountName = 'componentWillMount'; - } else if (typeof instance.UNSAFE_componentWillMount === 'function') { - foundWillMountName = 'UNSAFE_componentWillMount'; - } - if ( - typeof instance.componentWillReceiveProps === 'function' && - instance.componentWillReceiveProps.__suppressDeprecationWarning !== true - ) { - foundWillReceivePropsName = 'componentWillReceiveProps'; - } else if ( - typeof instance.UNSAFE_componentWillReceiveProps === 'function' - ) { - foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; - } - if ( - typeof instance.componentWillUpdate === 'function' && - instance.componentWillUpdate.__suppressDeprecationWarning !== true - ) { - foundWillUpdateName = 'componentWillUpdate'; - } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - foundWillUpdateName = 'UNSAFE_componentWillUpdate'; - } - if ( - foundWillMountName !== null || - foundWillReceivePropsName !== null || - foundWillUpdateName !== null - ) { - const componentName = getComponentNameFromType(ctor) || 'Component'; - const newApiName = - typeof ctor.getDerivedStateFromProps === 'function' - ? 'getDerivedStateFromProps()' - : 'getSnapshotBeforeUpdate()'; - if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(componentName)) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(componentName); - console.error( - 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + - '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + - 'The above lifecycles should be removed. Learn more about this warning here:\n' + - 'https://reactjs.org/link/unsafe-component-lifecycles', - componentName, - newApiName, - foundWillMountName !== null ? `\n ${foundWillMountName}` : '', - foundWillReceivePropsName !== null - ? `\n ${foundWillReceivePropsName}` - : '', - foundWillUpdateName !== null ? `\n ${foundWillUpdateName}` : '', - ); - } - } - } - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. - // ReactFiberContext usually updates this cache but can't for newly-created instances. - if (isLegacyContextConsumer) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return instance; -} - -function callComponentWillMount(workInProgress, instance) { - const oldState = instance.state; - - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - - if (oldState !== instance.state) { - if (__DEV__) { - console.error( - '%s.componentWillMount(): Assigning directly to this.state is ' + - "deprecated (except inside a component's " + - 'constructor). Use setState instead.', - getComponentNameFromFiber(workInProgress) || 'Component', - ); - } - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } -} - -function callComponentWillReceiveProps( - workInProgress, - instance, - newProps, - nextContext, -) { - const oldState = instance.state; - if (typeof instance.componentWillReceiveProps === 'function') { - instance.componentWillReceiveProps(newProps, nextContext); - } - if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); - } - - if (instance.state !== oldState) { - if (__DEV__) { - const componentName = - getComponentNameFromFiber(workInProgress) || 'Component'; - if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { - didWarnAboutStateAssignmentForComponent.add(componentName); - console.error( - '%s.componentWillReceiveProps(): Assigning directly to ' + - "this.state is deprecated (except inside a component's " + - 'constructor). Use setState instead.', - componentName, - ); - } - } - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } -} - -// Invokes the mount life-cycles on a previously never rendered instance. -function mountClassInstance( - workInProgress: Fiber, - ctor: any, - newProps: any, - renderLanes: Lanes, -): void { - if (__DEV__) { - checkClassInstance(workInProgress, ctor, newProps); - } - - const instance = workInProgress.stateNode; - instance.props = newProps; - instance.state = workInProgress.memoizedState; - instance.refs = {}; - - initializeUpdateQueue(workInProgress); - - const contextType = ctor.contextType; - if (typeof contextType === 'object' && contextType !== null) { - instance.context = readContext(contextType); - } else if (disableLegacyContext) { - instance.context = emptyContextObject; - } else { - const unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - instance.context = getMaskedContext(workInProgress, unmaskedContext); - } - - if (__DEV__) { - if (instance.state === newProps) { - const componentName = getComponentNameFromType(ctor) || 'Component'; - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - console.error( - '%s: It is not recommended to assign props directly to state ' + - "because updates to props won't be reflected in state. " + - 'In most cases, it is better to use props directly.', - componentName, - ); - } - } - - if (workInProgress.mode & StrictLegacyMode) { - ReactStrictModeWarnings.recordLegacyContextWarning( - workInProgress, - instance, - ); - } - - if (warnAboutDeprecatedLifecycles) { - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings( - workInProgress, - instance, - ); - } - } - - instance.state = workInProgress.memoizedState; - - const getDerivedStateFromProps = ctor.getDerivedStateFromProps; - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps( - workInProgress, - ctor, - getDerivedStateFromProps, - newProps, - ); - instance.state = workInProgress.memoizedState; - } - - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - typeof ctor.getDerivedStateFromProps !== 'function' && - typeof instance.getSnapshotBeforeUpdate !== 'function' && - (typeof instance.UNSAFE_componentWillMount === 'function' || - typeof instance.componentWillMount === 'function') - ) { - callComponentWillMount(workInProgress, instance); - // If we had additional state updates during this life-cycle, let's - // process them now. - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - instance.state = workInProgress.memoizedState; - } - - if (typeof instance.componentDidMount === 'function') { - let fiberFlags: Flags = Update | LayoutStatic; - if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - workInProgress.flags |= fiberFlags; - } -} - -function resumeMountClassInstance( - workInProgress: Fiber, - ctor: any, - newProps: any, - renderLanes: Lanes, -): boolean { - const instance = workInProgress.stateNode; - - const oldProps = workInProgress.memoizedProps; - instance.props = oldProps; - - const oldContext = instance.context; - const contextType = ctor.contextType; - let nextContext = emptyContextObject; - if (typeof contextType === 'object' && contextType !== null) { - nextContext = readContext(contextType); - } else if (!disableLegacyContext) { - const nextLegacyUnmaskedContext = getUnmaskedContext( - workInProgress, - ctor, - true, - ); - nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); - } - - const getDerivedStateFromProps = ctor.getDerivedStateFromProps; - const hasNewLifecycles = - typeof getDerivedStateFromProps === 'function' || - typeof instance.getSnapshotBeforeUpdate === 'function'; - - // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - !hasNewLifecycles && - (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || - typeof instance.componentWillReceiveProps === 'function') - ) { - if (oldProps !== newProps || oldContext !== nextContext) { - callComponentWillReceiveProps( - workInProgress, - instance, - newProps, - nextContext, - ); - } - } - - resetHasForceUpdateBeforeProcessing(); - - const oldState = workInProgress.memoizedState; - let newState = (instance.state = oldState); - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - newState = workInProgress.memoizedState; - if ( - oldProps === newProps && - oldState === newState && - !hasContextChanged() && - !checkHasForceUpdateAfterProcessing() - ) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - let fiberFlags: Flags = Update | LayoutStatic; - if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - workInProgress.flags |= fiberFlags; - } - return false; - } - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps( - workInProgress, - ctor, - getDerivedStateFromProps, - newProps, - ); - newState = workInProgress.memoizedState; - } - - const shouldUpdate = - checkHasForceUpdateAfterProcessing() || - checkShouldComponentUpdate( - workInProgress, - ctor, - oldProps, - newProps, - oldState, - newState, - nextContext, - ); - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - !hasNewLifecycles && - (typeof instance.UNSAFE_componentWillMount === 'function' || - typeof instance.componentWillMount === 'function') - ) { - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - } - if (typeof instance.componentDidMount === 'function') { - let fiberFlags: Flags = Update | LayoutStatic; - if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - workInProgress.flags |= fiberFlags; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - let fiberFlags: Flags = Update | LayoutStatic; - if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { - fiberFlags |= MountLayoutDev; - } - workInProgress.flags |= fiberFlags; - } - - // If shouldComponentUpdate returned false, we should still update the - // memoized state to indicate that this work can be reused. - workInProgress.memoizedProps = newProps; - workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - - return shouldUpdate; -} - -// Invokes the update life-cycles and returns false if it shouldn't rerender. -function updateClassInstance( - current: Fiber, - workInProgress: Fiber, - ctor: any, - newProps: any, - renderLanes: Lanes, -): boolean { - const instance = workInProgress.stateNode; - - cloneUpdateQueue(current, workInProgress); - - const unresolvedOldProps = workInProgress.memoizedProps; - const oldProps = - workInProgress.type === workInProgress.elementType - ? unresolvedOldProps - : resolveDefaultProps(workInProgress.type, unresolvedOldProps); - instance.props = oldProps; - const unresolvedNewProps = workInProgress.pendingProps; - - const oldContext = instance.context; - const contextType = ctor.contextType; - let nextContext = emptyContextObject; - if (typeof contextType === 'object' && contextType !== null) { - nextContext = readContext(contextType); - } else if (!disableLegacyContext) { - const nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); - nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); - } - - const getDerivedStateFromProps = ctor.getDerivedStateFromProps; - const hasNewLifecycles = - typeof getDerivedStateFromProps === 'function' || - typeof instance.getSnapshotBeforeUpdate === 'function'; - - // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - !hasNewLifecycles && - (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || - typeof instance.componentWillReceiveProps === 'function') - ) { - if ( - unresolvedOldProps !== unresolvedNewProps || - oldContext !== nextContext - ) { - callComponentWillReceiveProps( - workInProgress, - instance, - newProps, - nextContext, - ); - } - } - - resetHasForceUpdateBeforeProcessing(); - - const oldState = workInProgress.memoizedState; - let newState = (instance.state = oldState); - processUpdateQueue(workInProgress, newProps, instance, renderLanes); - newState = workInProgress.memoizedState; - - if ( - unresolvedOldProps === unresolvedNewProps && - oldState === newState && - !hasContextChanged() && - !checkHasForceUpdateAfterProcessing() && - !( - enableLazyContextPropagation && - current !== null && - current.dependencies !== null && - checkIfContextChanged(current.dependencies) - ) - ) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if ( - unresolvedOldProps !== current.memoizedProps || - oldState !== current.memoizedState - ) { - workInProgress.flags |= Update; - } - } - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if ( - unresolvedOldProps !== current.memoizedProps || - oldState !== current.memoizedState - ) { - workInProgress.flags |= Snapshot; - } - } - return false; - } - - if (typeof getDerivedStateFromProps === 'function') { - applyDerivedStateFromProps( - workInProgress, - ctor, - getDerivedStateFromProps, - newProps, - ); - newState = workInProgress.memoizedState; - } - - const shouldUpdate = - checkHasForceUpdateAfterProcessing() || - checkShouldComponentUpdate( - workInProgress, - ctor, - oldProps, - newProps, - oldState, - newState, - nextContext, - ) || - // TODO: In some cases, we'll end up checking if context has changed twice, - // both before and after `shouldComponentUpdate` has been called. Not ideal, - // but I'm loath to refactor this function. This only happens for memoized - // components so it's not that common. - (enableLazyContextPropagation && - current !== null && - current.dependencies !== null && - checkIfContextChanged(current.dependencies)); - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if ( - !hasNewLifecycles && - (typeof instance.UNSAFE_componentWillUpdate === 'function' || - typeof instance.componentWillUpdate === 'function') - ) { - if (typeof instance.componentWillUpdate === 'function') { - instance.componentWillUpdate(newProps, newState, nextContext); - } - if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); - } - } - if (typeof instance.componentDidUpdate === 'function') { - workInProgress.flags |= Update; - } - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - workInProgress.flags |= Snapshot; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if ( - unresolvedOldProps !== current.memoizedProps || - oldState !== current.memoizedState - ) { - workInProgress.flags |= Update; - } - } - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if ( - unresolvedOldProps !== current.memoizedProps || - oldState !== current.memoizedState - ) { - workInProgress.flags |= Snapshot; - } - } - - // If shouldComponentUpdate returned false, we should still update the - // memoized props/state to indicate that this work can be reused. - workInProgress.memoizedProps = newProps; - workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - instance.props = newProps; - instance.state = newState; - instance.context = nextContext; - - return shouldUpdate; -} - -export { - adoptClassInstance, - constructClassInstance, - mountClassInstance, - resumeMountClassInstance, - updateClassInstance, -}; diff --git a/packages/react-reconciler/src/ReactFiberClassUpdateQueue.new.js b/packages/react-reconciler/src/ReactFiberClassUpdateQueue.new.js deleted file mode 100644 index 6ad50d8130571..0000000000000 --- a/packages/react-reconciler/src/ReactFiberClassUpdateQueue.new.js +++ /dev/null @@ -1,742 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -// UpdateQueue is a linked list of prioritized updates. -// -// Like fibers, update queues come in pairs: a current queue, which represents -// the visible state of the screen, and a work-in-progress queue, which can be -// mutated and processed asynchronously before it is committed — a form of -// double buffering. If a work-in-progress render is discarded before finishing, -// we create a new work-in-progress by cloning the current queue. -// -// Both queues share a persistent, singly-linked list structure. To schedule an -// update, we append it to the end of both queues. Each queue maintains a -// pointer to first update in the persistent list that hasn't been processed. -// The work-in-progress pointer always has a position equal to or greater than -// the current queue, since we always work on that one. The current queue's -// pointer is only updated during the commit phase, when we swap in the -// work-in-progress. -// -// For example: -// -// Current pointer: A - B - C - D - E - F -// Work-in-progress pointer: D - E - F -// ^ -// The work-in-progress queue has -// processed more updates than current. -// -// The reason we append to both queues is because otherwise we might drop -// updates without ever processing them. For example, if we only add updates to -// the work-in-progress queue, some updates could be lost whenever a work-in -// -progress render restarts by cloning from current. Similarly, if we only add -// updates to the current queue, the updates will be lost whenever an already -// in-progress queue commits and swaps with the current queue. However, by -// adding to both queues, we guarantee that the update will be part of the next -// work-in-progress. (And because the work-in-progress queue becomes the -// current queue once it commits, there's no danger of applying the same -// update twice.) -// -// Prioritization -// -------------- -// -// Updates are not sorted by priority, but by insertion; new updates are always -// appended to the end of the list. -// -// The priority is still important, though. When processing the update queue -// during the render phase, only the updates with sufficient priority are -// included in the result. If we skip an update because it has insufficient -// priority, it remains in the queue to be processed later, during a lower -// priority render. Crucially, all updates subsequent to a skipped update also -// remain in the queue *regardless of their priority*. That means high priority -// updates are sometimes processed twice, at two separate priorities. We also -// keep track of a base state, that represents the state before the first -// update in the queue is applied. -// -// For example: -// -// Given a base state of '', and the following queue of updates -// -// A1 - B2 - C1 - D2 -// -// where the number indicates the priority, and the update is applied to the -// previous state by appending a letter, React will process these updates as -// two separate renders, one per distinct priority level: -// -// First render, at priority 1: -// Base state: '' -// Updates: [A1, C1] -// Result state: 'AC' -// -// Second render, at priority 2: -// Base state: 'A' <- The base state does not include C1, -// because B2 was skipped. -// Updates: [B2, C1, D2] <- C1 was rebased on top of B2 -// Result state: 'ABCD' -// -// Because we process updates in insertion order, and rebase high priority -// updates when preceding updates are skipped, the final result is deterministic -// regardless of priority. Intermediate state may vary according to system -// resources, but the final state is always the same. - -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Lanes, Lane} from './ReactFiberLane.new'; - -import { - NoLane, - NoLanes, - OffscreenLane, - isSubsetOfLanes, - mergeLanes, - removeLanes, - isTransitionLane, - intersectLanes, - markRootEntangled, -} from './ReactFiberLane.new'; -import { - enterDisallowedContextReadInDEV, - exitDisallowedContextReadInDEV, -} from './ReactFiberNewContext.new'; -import { - Callback, - Visibility, - ShouldCapture, - DidCapture, -} from './ReactFiberFlags'; - -import {debugRenderPhaseSideEffectsForStrictMode} from 'shared/ReactFeatureFlags'; - -import {StrictLegacyMode} from './ReactTypeOfMode'; -import { - markSkippedUpdateLanes, - isUnsafeClassRenderPhaseUpdate, - getWorkInProgressRootRenderLanes, -} from './ReactFiberWorkLoop.new'; -import { - enqueueConcurrentClassUpdate, - unsafe_markUpdateLaneFromFiberToRoot, -} from './ReactFiberConcurrentUpdates.new'; -import {setIsStrictModeForDevtools} from './ReactFiberDevToolsHook.new'; - -import assign from 'shared/assign'; - -export type Update = { - // TODO: Temporary field. Will remove this by storing a map of - // transition -> event time on the root. - eventTime: number, - lane: Lane, - - tag: 0 | 1 | 2 | 3, - payload: any, - callback: (() => mixed) | null, - - next: Update | null, -}; - -export type SharedQueue = { - pending: Update | null, - lanes: Lanes, - hiddenCallbacks: Array<() => mixed> | null, -}; - -export type UpdateQueue = { - baseState: State, - firstBaseUpdate: Update | null, - lastBaseUpdate: Update | null, - shared: SharedQueue, - callbacks: Array<() => mixed> | null, -}; - -export const UpdateState = 0; -export const ReplaceState = 1; -export const ForceUpdate = 2; -export const CaptureUpdate = 3; - -// Global state that is reset at the beginning of calling `processUpdateQueue`. -// It should only be read right after calling `processUpdateQueue`, via -// `checkHasForceUpdateAfterProcessing`. -let hasForceUpdate = false; - -let didWarnUpdateInsideUpdate; -let currentlyProcessingQueue; -export let resetCurrentlyProcessingQueue: () => void; -if (__DEV__) { - didWarnUpdateInsideUpdate = false; - currentlyProcessingQueue = null; - resetCurrentlyProcessingQueue = () => { - currentlyProcessingQueue = null; - }; -} - -export function initializeUpdateQueue(fiber: Fiber): void { - const queue: UpdateQueue = { - baseState: fiber.memoizedState, - firstBaseUpdate: null, - lastBaseUpdate: null, - shared: { - pending: null, - lanes: NoLanes, - hiddenCallbacks: null, - }, - callbacks: null, - }; - fiber.updateQueue = queue; -} - -export function cloneUpdateQueue( - current: Fiber, - workInProgress: Fiber, -): void { - // Clone the update queue from current. Unless it's already a clone. - const queue: UpdateQueue = (workInProgress.updateQueue: any); - const currentQueue: UpdateQueue = (current.updateQueue: any); - if (queue === currentQueue) { - const clone: UpdateQueue = { - baseState: currentQueue.baseState, - firstBaseUpdate: currentQueue.firstBaseUpdate, - lastBaseUpdate: currentQueue.lastBaseUpdate, - shared: currentQueue.shared, - callbacks: null, - }; - workInProgress.updateQueue = clone; - } -} - -export function createUpdate(eventTime: number, lane: Lane): Update { - const update: Update = { - eventTime, - lane, - - tag: UpdateState, - payload: null, - callback: null, - - next: null, - }; - return update; -} - -export function enqueueUpdate( - fiber: Fiber, - update: Update, - lane: Lane, -): FiberRoot | null { - const updateQueue = fiber.updateQueue; - if (updateQueue === null) { - // Only occurs if the fiber has been unmounted. - return null; - } - - const sharedQueue: SharedQueue = (updateQueue: any).shared; - - if (__DEV__) { - if ( - currentlyProcessingQueue === sharedQueue && - !didWarnUpdateInsideUpdate - ) { - console.error( - 'An update (setState, replaceState, or forceUpdate) was scheduled ' + - 'from inside an update function. Update functions should be pure, ' + - 'with zero side-effects. Consider using componentDidUpdate or a ' + - 'callback.', - ); - didWarnUpdateInsideUpdate = true; - } - } - - if (isUnsafeClassRenderPhaseUpdate(fiber)) { - // This is an unsafe render phase update. Add directly to the update - // queue so we can process it immediately during the current render. - const pending = sharedQueue.pending; - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - sharedQueue.pending = update; - - // Update the childLanes even though we're most likely already rendering - // this fiber. This is for backwards compatibility in the case where you - // update a different component during render phase than the one that is - // currently renderings (a pattern that is accompanied by a warning). - return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane); - } else { - return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane); - } -} - -export function entangleTransitions(root: FiberRoot, fiber: Fiber, lane: Lane) { - const updateQueue = fiber.updateQueue; - if (updateQueue === null) { - // Only occurs if the fiber has been unmounted. - return; - } - - const sharedQueue: SharedQueue = (updateQueue: any).shared; - if (isTransitionLane(lane)) { - let queueLanes = sharedQueue.lanes; - - // If any entangled lanes are no longer pending on the root, then they must - // have finished. We can remove them from the shared queue, which represents - // a superset of the actually pending lanes. In some cases we may entangle - // more than we need to, but that's OK. In fact it's worse if we *don't* - // entangle when we should. - queueLanes = intersectLanes(queueLanes, root.pendingLanes); - - // Entangle the new transition lane with the other transition lanes. - const newQueueLanes = mergeLanes(queueLanes, lane); - sharedQueue.lanes = newQueueLanes; - // Even if queue.lanes already include lane, we don't know for certain if - // the lane finished since the last time we entangled it. So we need to - // entangle it again, just to be sure. - markRootEntangled(root, newQueueLanes); - } -} - -export function enqueueCapturedUpdate( - workInProgress: Fiber, - capturedUpdate: Update, -) { - // Captured updates are updates that are thrown by a child during the render - // phase. They should be discarded if the render is aborted. Therefore, - // we should only put them on the work-in-progress queue, not the current one. - let queue: UpdateQueue = (workInProgress.updateQueue: any); - - // Check if the work-in-progress queue is a clone. - const current = workInProgress.alternate; - if (current !== null) { - const currentQueue: UpdateQueue = (current.updateQueue: any); - if (queue === currentQueue) { - // The work-in-progress queue is the same as current. This happens when - // we bail out on a parent fiber that then captures an error thrown by - // a child. Since we want to append the update only to the work-in - // -progress queue, we need to clone the updates. We usually clone during - // processUpdateQueue, but that didn't happen in this case because we - // skipped over the parent when we bailed out. - let newFirst = null; - let newLast = null; - const firstBaseUpdate = queue.firstBaseUpdate; - if (firstBaseUpdate !== null) { - // Loop through the updates and clone them. - let update: Update = firstBaseUpdate; - do { - const clone: Update = { - eventTime: update.eventTime, - lane: update.lane, - - tag: update.tag, - payload: update.payload, - // When this update is rebased, we should not fire its - // callback again. - callback: null, - - next: null, - }; - if (newLast === null) { - newFirst = newLast = clone; - } else { - newLast.next = clone; - newLast = clone; - } - // $FlowFixMe[incompatible-type] we bail out when we get a null - update = update.next; - } while (update !== null); - - // Append the captured update the end of the cloned list. - if (newLast === null) { - newFirst = newLast = capturedUpdate; - } else { - newLast.next = capturedUpdate; - newLast = capturedUpdate; - } - } else { - // There are no base updates. - newFirst = newLast = capturedUpdate; - } - queue = { - baseState: currentQueue.baseState, - firstBaseUpdate: newFirst, - lastBaseUpdate: newLast, - shared: currentQueue.shared, - callbacks: currentQueue.callbacks, - }; - workInProgress.updateQueue = queue; - return; - } - } - - // Append the update to the end of the list. - const lastBaseUpdate = queue.lastBaseUpdate; - if (lastBaseUpdate === null) { - queue.firstBaseUpdate = capturedUpdate; - } else { - lastBaseUpdate.next = capturedUpdate; - } - queue.lastBaseUpdate = capturedUpdate; -} - -function getStateFromUpdate( - workInProgress: Fiber, - queue: UpdateQueue, - update: Update, - prevState: State, - nextProps: any, - instance: any, -): any { - switch (update.tag) { - case ReplaceState: { - const payload = update.payload; - if (typeof payload === 'function') { - // Updater function - if (__DEV__) { - enterDisallowedContextReadInDEV(); - } - const nextState = payload.call(instance, prevState, nextProps); - if (__DEV__) { - if ( - debugRenderPhaseSideEffectsForStrictMode && - workInProgress.mode & StrictLegacyMode - ) { - setIsStrictModeForDevtools(true); - try { - payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - exitDisallowedContextReadInDEV(); - } - return nextState; - } - // State object - return payload; - } - case CaptureUpdate: { - workInProgress.flags = - (workInProgress.flags & ~ShouldCapture) | DidCapture; - } - // Intentional fallthrough - case UpdateState: { - const payload = update.payload; - let partialState; - if (typeof payload === 'function') { - // Updater function - if (__DEV__) { - enterDisallowedContextReadInDEV(); - } - partialState = payload.call(instance, prevState, nextProps); - if (__DEV__) { - if ( - debugRenderPhaseSideEffectsForStrictMode && - workInProgress.mode & StrictLegacyMode - ) { - setIsStrictModeForDevtools(true); - try { - payload.call(instance, prevState, nextProps); - } finally { - setIsStrictModeForDevtools(false); - } - } - exitDisallowedContextReadInDEV(); - } - } else { - // Partial state object - partialState = payload; - } - if (partialState === null || partialState === undefined) { - // Null and undefined are treated as no-ops. - return prevState; - } - // Merge the partial state and the previous state. - return assign({}, prevState, partialState); - } - case ForceUpdate: { - hasForceUpdate = true; - return prevState; - } - } - return prevState; -} - -export function processUpdateQueue( - workInProgress: Fiber, - props: any, - instance: any, - renderLanes: Lanes, -): void { - // This is always non-null on a ClassComponent or HostRoot - const queue: UpdateQueue = (workInProgress.updateQueue: any); - - hasForceUpdate = false; - - if (__DEV__) { - // $FlowFixMe[escaped-generic] discovered when updating Flow - currentlyProcessingQueue = queue.shared; - } - - let firstBaseUpdate = queue.firstBaseUpdate; - let lastBaseUpdate = queue.lastBaseUpdate; - - // Check if there are pending updates. If so, transfer them to the base queue. - let pendingQueue = queue.shared.pending; - if (pendingQueue !== null) { - queue.shared.pending = null; - - // The pending queue is circular. Disconnect the pointer between first - // and last so that it's non-circular. - const lastPendingUpdate = pendingQueue; - const firstPendingUpdate = lastPendingUpdate.next; - lastPendingUpdate.next = null; - // Append pending updates to base queue - if (lastBaseUpdate === null) { - firstBaseUpdate = firstPendingUpdate; - } else { - lastBaseUpdate.next = firstPendingUpdate; - } - lastBaseUpdate = lastPendingUpdate; - - // If there's a current queue, and it's different from the base queue, then - // we need to transfer the updates to that queue, too. Because the base - // queue is a singly-linked list with no cycles, we can append to both - // lists and take advantage of structural sharing. - // TODO: Pass `current` as argument - const current = workInProgress.alternate; - if (current !== null) { - // This is always non-null on a ClassComponent or HostRoot - const currentQueue: UpdateQueue = (current.updateQueue: any); - const currentLastBaseUpdate = currentQueue.lastBaseUpdate; - if (currentLastBaseUpdate !== lastBaseUpdate) { - if (currentLastBaseUpdate === null) { - currentQueue.firstBaseUpdate = firstPendingUpdate; - } else { - currentLastBaseUpdate.next = firstPendingUpdate; - } - currentQueue.lastBaseUpdate = lastPendingUpdate; - } - } - } - - // These values may change as we process the queue. - if (firstBaseUpdate !== null) { - // Iterate through the list of updates to compute the result. - let newState = queue.baseState; - // TODO: Don't need to accumulate this. Instead, we can remove renderLanes - // from the original lanes. - let newLanes = NoLanes; - - let newBaseState = null; - let newFirstBaseUpdate = null; - let newLastBaseUpdate = null; - - let update: Update = firstBaseUpdate; - do { - // TODO: Don't need this field anymore - const updateEventTime = update.eventTime; - - // An extra OffscreenLane bit is added to updates that were made to - // a hidden tree, so that we can distinguish them from updates that were - // already there when the tree was hidden. - const updateLane = removeLanes(update.lane, OffscreenLane); - const isHiddenUpdate = updateLane !== update.lane; - - // Check if this update was made while the tree was hidden. If so, then - // it's not a "base" update and we should disregard the extra base lanes - // that were added to renderLanes when we entered the Offscreen tree. - const shouldSkipUpdate = isHiddenUpdate - ? !isSubsetOfLanes(getWorkInProgressRootRenderLanes(), updateLane) - : !isSubsetOfLanes(renderLanes, updateLane); - - if (shouldSkipUpdate) { - // Priority is insufficient. Skip this update. If this is the first - // skipped update, the previous update/state is the new base - // update/state. - const clone: Update = { - eventTime: updateEventTime, - lane: updateLane, - - tag: update.tag, - payload: update.payload, - callback: update.callback, - - next: null, - }; - if (newLastBaseUpdate === null) { - newFirstBaseUpdate = newLastBaseUpdate = clone; - newBaseState = newState; - } else { - newLastBaseUpdate = newLastBaseUpdate.next = clone; - } - // Update the remaining priority in the queue. - newLanes = mergeLanes(newLanes, updateLane); - } else { - // This update does have sufficient priority. - - if (newLastBaseUpdate !== null) { - const clone: Update = { - eventTime: updateEventTime, - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - - tag: update.tag, - payload: update.payload, - - // When this update is rebased, we should not fire its - // callback again. - callback: null, - - next: null, - }; - newLastBaseUpdate = newLastBaseUpdate.next = clone; - } - - // Process this update. - newState = getStateFromUpdate( - workInProgress, - queue, - update, - newState, - props, - instance, - ); - const callback = update.callback; - if (callback !== null) { - workInProgress.flags |= Callback; - if (isHiddenUpdate) { - workInProgress.flags |= Visibility; - } - const callbacks = queue.callbacks; - if (callbacks === null) { - queue.callbacks = [callback]; - } else { - callbacks.push(callback); - } - } - } - // $FlowFixMe[incompatible-type] we bail out when we get a null - update = update.next; - if (update === null) { - pendingQueue = queue.shared.pending; - if (pendingQueue === null) { - break; - } else { - // An update was scheduled from inside a reducer. Add the new - // pending updates to the end of the list and keep processing. - const lastPendingUpdate = pendingQueue; - // Intentionally unsound. Pending updates form a circular list, but we - // unravel them when transferring them to the base queue. - const firstPendingUpdate = ((lastPendingUpdate.next: any): Update); - lastPendingUpdate.next = null; - update = firstPendingUpdate; - queue.lastBaseUpdate = lastPendingUpdate; - queue.shared.pending = null; - } - } - } while (true); - - if (newLastBaseUpdate === null) { - newBaseState = newState; - } - - queue.baseState = ((newBaseState: any): State); - queue.firstBaseUpdate = newFirstBaseUpdate; - queue.lastBaseUpdate = newLastBaseUpdate; - - if (firstBaseUpdate === null) { - // `queue.lanes` is used for entangling transitions. We can set it back to - // zero once the queue is empty. - queue.shared.lanes = NoLanes; - } - - // Set the remaining expiration time to be whatever is remaining in the queue. - // This should be fine because the only two other things that contribute to - // expiration time are props and context. We're already in the middle of the - // begin phase by the time we start processing the queue, so we've already - // dealt with the props. Context in components that specify - // shouldComponentUpdate is tricky; but we'll have to account for - // that regardless. - markSkippedUpdateLanes(newLanes); - workInProgress.lanes = newLanes; - workInProgress.memoizedState = newState; - } - - if (__DEV__) { - currentlyProcessingQueue = null; - } -} - -function callCallback(callback, context) { - if (typeof callback !== 'function') { - throw new Error( - 'Invalid argument passed as callback. Expected a function. Instead ' + - `received: ${callback}`, - ); - } - - callback.call(context); -} - -export function resetHasForceUpdateBeforeProcessing() { - hasForceUpdate = false; -} - -export function checkHasForceUpdateAfterProcessing(): boolean { - return hasForceUpdate; -} - -export function deferHiddenCallbacks( - updateQueue: UpdateQueue, -): void { - // When an update finishes on a hidden component, its callback should not - // be fired until/unless the component is made visible again. Stash the - // callback on the shared queue object so it can be fired later. - const newHiddenCallbacks = updateQueue.callbacks; - if (newHiddenCallbacks !== null) { - const existingHiddenCallbacks = updateQueue.shared.hiddenCallbacks; - if (existingHiddenCallbacks === null) { - updateQueue.shared.hiddenCallbacks = newHiddenCallbacks; - } else { - updateQueue.shared.hiddenCallbacks = existingHiddenCallbacks.concat( - newHiddenCallbacks, - ); - } - } -} - -export function commitHiddenCallbacks( - updateQueue: UpdateQueue, - context: any, -): void { - // This component is switching from hidden -> visible. Commit any callbacks - // that were previously deferred. - const hiddenCallbacks = updateQueue.shared.hiddenCallbacks; - if (hiddenCallbacks !== null) { - updateQueue.shared.hiddenCallbacks = null; - for (let i = 0; i < hiddenCallbacks.length; i++) { - const callback = hiddenCallbacks[i]; - callCallback(callback, context); - } - } -} - -export function commitCallbacks( - updateQueue: UpdateQueue, - context: any, -): void { - const callbacks = updateQueue.callbacks; - if (callbacks !== null) { - updateQueue.callbacks = null; - for (let i = 0; i < callbacks.length; i++) { - const callback = callbacks[i]; - callCallback(callback, context); - } - } -} diff --git a/packages/react-reconciler/src/ReactFiberCommitWork.new.js b/packages/react-reconciler/src/ReactFiberCommitWork.new.js deleted file mode 100644 index ae9337a01647f..0000000000000 --- a/packages/react-reconciler/src/ReactFiberCommitWork.new.js +++ /dev/null @@ -1,4450 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type { - Instance, - TextInstance, - SuspenseInstance, - Container, - ChildSet, - UpdatePayload, -} from './ReactFiberHostConfig'; -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Lanes} from './ReactFiberLane.new'; -import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; -import type {UpdateQueue} from './ReactFiberClassUpdateQueue.new'; -import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new'; -import type {Wakeable} from 'shared/ReactTypes'; -import {isOffscreenManual} from './ReactFiberOffscreenComponent'; -import type { - OffscreenState, - OffscreenInstance, - OffscreenQueue, - OffscreenProps, -} from './ReactFiberOffscreenComponent'; -import type {HookFlags} from './ReactHookEffectTags'; -import type {Cache} from './ReactFiberCacheComponent.new'; -import type {RootState} from './ReactFiberRoot.new'; -import type { - Transition, - TracingMarkerInstance, - TransitionAbort, -} from './ReactFiberTracingMarkerComponent.new'; - -import { - enableCreateEventHandleAPI, - enableProfilerTimer, - enableProfilerCommitHooks, - enableProfilerNestedUpdatePhase, - enableSchedulingProfiler, - enableSuspenseCallback, - enableScopeAPI, - deletedTreeCleanUpLevel, - enableUpdaterTracking, - enableCache, - enableTransitionTracing, - enableUseEventHook, - enableFloat, - enableLegacyHidden, - enableHostSingletons, -} from 'shared/ReactFeatureFlags'; -import { - FunctionComponent, - ForwardRef, - ClassComponent, - HostRoot, - HostComponent, - HostResource, - HostSingleton, - HostText, - HostPortal, - Profiler, - SuspenseComponent, - DehydratedFragment, - IncompleteClassComponent, - MemoComponent, - SimpleMemoComponent, - SuspenseListComponent, - ScopeComponent, - OffscreenComponent, - LegacyHiddenComponent, - CacheComponent, - TracingMarkerComponent, -} from './ReactWorkTags'; -import { - NoFlags, - ContentReset, - Placement, - ChildDeletion, - Snapshot, - Update, - Callback, - Ref, - Hydrating, - Passive, - BeforeMutationMask, - MutationMask, - LayoutMask, - PassiveMask, - Visibility, -} from './ReactFiberFlags'; -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import { - resetCurrentFiber as resetCurrentDebugFiberInDEV, - setCurrentFiber as setCurrentDebugFiberInDEV, - getCurrentFiber as getCurrentDebugFiberInDEV, -} from './ReactCurrentFiber'; -import {resolveDefaultProps} from './ReactFiberLazyComponent.new'; -import { - isCurrentUpdateNested, - getCommitTime, - recordLayoutEffectDuration, - startLayoutEffectTimer, - recordPassiveEffectDuration, - startPassiveEffectTimer, -} from './ReactProfilerTimer.new'; -import {ConcurrentMode, NoMode, ProfileMode} from './ReactTypeOfMode'; -import { - deferHiddenCallbacks, - commitHiddenCallbacks, - commitCallbacks, -} from './ReactFiberClassUpdateQueue.new'; -import { - getPublicInstance, - supportsMutation, - supportsPersistence, - supportsHydration, - supportsResources, - supportsSingletons, - commitMount, - commitUpdate, - resetTextContent, - commitTextUpdate, - appendChild, - appendChildToContainer, - insertBefore, - insertInContainerBefore, - removeChild, - removeChildFromContainer, - clearSuspenseBoundary, - clearSuspenseBoundaryFromContainer, - replaceContainerChildren, - createContainerChildSet, - hideInstance, - hideTextInstance, - unhideInstance, - unhideTextInstance, - commitHydratedContainer, - commitHydratedSuspenseInstance, - clearContainer, - prepareScopeUpdate, - prepareForCommit, - beforeActiveInstanceBlur, - detachDeletedInstance, - acquireResource, - releaseResource, - clearSingleton, - acquireSingletonInstance, - releaseSingletonInstance, - scheduleMicrotask, -} from './ReactFiberHostConfig'; -import { - captureCommitPhaseError, - resolveRetryWakeable, - markCommitTimeOfFallback, - enqueuePendingPassiveProfilerEffect, - restorePendingUpdaters, - addTransitionStartCallbackToPendingTransition, - addTransitionProgressCallbackToPendingTransition, - addTransitionCompleteCallbackToPendingTransition, - addMarkerProgressCallbackToPendingTransition, - addMarkerIncompleteCallbackToPendingTransition, - addMarkerCompleteCallbackToPendingTransition, - setIsRunningInsertionEffect, - getExecutionContext, - CommitContext, - RenderContext, - NoContext, -} from './ReactFiberWorkLoop.new'; -import { - NoFlags as NoHookEffect, - HasEffect as HookHasEffect, - Layout as HookLayout, - Insertion as HookInsertion, - Passive as HookPassive, -} from './ReactHookEffectTags'; -import {didWarnAboutReassigningProps} from './ReactFiberBeginWork.new'; -import {doesFiberContain} from './ReactFiberTreeReflection'; -import {invokeGuardedCallback, clearCaughtError} from 'shared/ReactErrorUtils'; -import { - isDevToolsPresent, - markComponentPassiveEffectMountStarted, - markComponentPassiveEffectMountStopped, - markComponentPassiveEffectUnmountStarted, - markComponentPassiveEffectUnmountStopped, - markComponentLayoutEffectMountStarted, - markComponentLayoutEffectMountStopped, - markComponentLayoutEffectUnmountStarted, - markComponentLayoutEffectUnmountStopped, - onCommitUnmount, -} from './ReactFiberDevToolsHook.new'; -import {releaseCache, retainCache} from './ReactFiberCacheComponent.new'; -import {clearTransitionsForLanes} from './ReactFiberLane.new'; -import { - OffscreenVisible, - OffscreenDetached, - OffscreenPassiveEffectsConnected, -} from './ReactFiberOffscreenComponent'; -import { - TransitionRoot, - TransitionTracingMarker, -} from './ReactFiberTracingMarkerComponent.new'; - -let didWarnAboutUndefinedSnapshotBeforeUpdate: Set | null = null; -if (__DEV__) { - didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); -} - -// Used during the commit phase to track the state of the Offscreen component stack. -// Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. -let offscreenSubtreeIsHidden: boolean = false; -let offscreenSubtreeWasHidden: boolean = false; - -const PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; - -let nextEffect: Fiber | null = null; - -// Used for Profiling builds to track updaters. -let inProgressLanes: Lanes | null = null; -let inProgressRoot: FiberRoot | null = null; - -function shouldProfile(current: Fiber): boolean { - return ( - enableProfilerTimer && - enableProfilerCommitHooks && - (current.mode & ProfileMode) !== NoMode && - (getExecutionContext() & CommitContext) !== NoContext - ); -} - -export function reportUncaughtErrorInDEV(error: mixed) { - // Wrapping each small part of the commit phase into a guarded - // callback is a bit too slow (https://github.com/facebook/react/pull/21666). - // But we rely on it to surface errors to DEV tools like overlays - // (https://github.com/facebook/react/issues/21712). - // As a compromise, rethrow only caught errors in a guard. - if (__DEV__) { - invokeGuardedCallback(null, () => { - throw error; - }); - clearCaughtError(); - } -} - -const callComponentWillUnmountWithTimer = function(current, instance) { - instance.props = current.memoizedProps; - instance.state = current.memoizedState; - if (shouldProfile(current)) { - try { - startLayoutEffectTimer(); - instance.componentWillUnmount(); - } finally { - recordLayoutEffectDuration(current); - } - } else { - instance.componentWillUnmount(); - } -}; - -// Capture errors so they don't interrupt unmounting. -function safelyCallComponentWillUnmount( - current: Fiber, - nearestMountedAncestor: Fiber | null, - instance: any, -) { - try { - callComponentWillUnmountWithTimer(current, instance); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } -} - -// Capture errors so they don't interrupt mounting. -function safelyAttachRef(current: Fiber, nearestMountedAncestor: Fiber | null) { - try { - commitAttachRef(current); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } -} - -function safelyDetachRef(current: Fiber, nearestMountedAncestor: Fiber | null) { - const ref = current.ref; - const refCleanup = current.refCleanup; - - if (ref !== null) { - if (typeof refCleanup === 'function') { - try { - if (shouldProfile(current)) { - try { - startLayoutEffectTimer(); - refCleanup(); - } finally { - recordLayoutEffectDuration(current); - } - } else { - refCleanup(); - } - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } finally { - // `refCleanup` has been called. Nullify all references to it to prevent double invocation. - current.refCleanup = null; - const finishedWork = current.alternate; - if (finishedWork != null) { - finishedWork.refCleanup = null; - } - } - } else if (typeof ref === 'function') { - let retVal; - try { - if (shouldProfile(current)) { - try { - startLayoutEffectTimer(); - retVal = ref(null); - } finally { - recordLayoutEffectDuration(current); - } - } else { - retVal = ref(null); - } - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } - if (__DEV__) { - if (typeof retVal === 'function') { - console.error( - 'Unexpected return value from a callback ref in %s. ' + - 'A callback ref should not return a function.', - getComponentNameFromFiber(current), - ); - } - } - } else { - // $FlowFixMe unable to narrow type to RefObject - ref.current = null; - } - } -} - -function safelyCallDestroy( - current: Fiber, - nearestMountedAncestor: Fiber | null, - destroy: () => void, -) { - try { - destroy(); - } catch (error) { - captureCommitPhaseError(current, nearestMountedAncestor, error); - } -} - -let focusedInstanceHandle: null | Fiber = null; -let shouldFireAfterActiveInstanceBlur: boolean = false; - -export function commitBeforeMutationEffects( - root: FiberRoot, - firstChild: Fiber, -): boolean { - focusedInstanceHandle = prepareForCommit(root.containerInfo); - - nextEffect = firstChild; - commitBeforeMutationEffects_begin(); - - // We no longer need to track the active instance fiber - const shouldFire = shouldFireAfterActiveInstanceBlur; - shouldFireAfterActiveInstanceBlur = false; - focusedInstanceHandle = null; - - return shouldFire; -} - -function commitBeforeMutationEffects_begin() { - while (nextEffect !== null) { - const fiber = nextEffect; - - // This phase is only used for beforeActiveInstanceBlur. - // Let's skip the whole loop if it's off. - if (enableCreateEventHandleAPI) { - // TODO: Should wrap this in flags check, too, as optimization - const deletions = fiber.deletions; - if (deletions !== null) { - for (let i = 0; i < deletions.length; i++) { - const deletion = deletions[i]; - commitBeforeMutationEffectsDeletion(deletion); - } - } - } - - const child = fiber.child; - if ( - (fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && - child !== null - ) { - child.return = fiber; - nextEffect = child; - } else { - commitBeforeMutationEffects_complete(); - } - } -} - -function commitBeforeMutationEffects_complete() { - while (nextEffect !== null) { - const fiber = nextEffect; - setCurrentDebugFiberInDEV(fiber); - try { - commitBeforeMutationEffectsOnFiber(fiber); - } catch (error) { - captureCommitPhaseError(fiber, fiber.return, error); - } - resetCurrentDebugFiberInDEV(); - - const sibling = fiber.sibling; - if (sibling !== null) { - sibling.return = fiber.return; - nextEffect = sibling; - return; - } - - nextEffect = fiber.return; - } -} - -function commitBeforeMutationEffectsOnFiber(finishedWork: Fiber) { - const current = finishedWork.alternate; - const flags = finishedWork.flags; - - if (enableCreateEventHandleAPI) { - if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) { - // Check to see if the focused element was inside of a hidden (Suspense) subtree. - // TODO: Move this out of the hot path using a dedicated effect tag. - if ( - finishedWork.tag === SuspenseComponent && - isSuspenseBoundaryBeingHidden(current, finishedWork) && - // $FlowFixMe[incompatible-call] found when upgrading Flow - doesFiberContain(finishedWork, focusedInstanceHandle) - ) { - shouldFireAfterActiveInstanceBlur = true; - beforeActiveInstanceBlur(finishedWork); - } - } - } - - if ((flags & Snapshot) !== NoFlags) { - setCurrentDebugFiberInDEV(finishedWork); - } - - switch (finishedWork.tag) { - case FunctionComponent: { - if (enableUseEventHook) { - if ((flags & Update) !== NoFlags) { - commitUseEventMount(finishedWork); - } - } - break; - } - case ForwardRef: - case SimpleMemoComponent: { - break; - } - case ClassComponent: { - if ((flags & Snapshot) !== NoFlags) { - if (current !== null) { - const prevProps = current.memoizedProps; - const prevState = current.memoizedState; - const instance = finishedWork.stateNode; - // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - if (__DEV__) { - if ( - finishedWork.type === finishedWork.elementType && - !didWarnAboutReassigningProps - ) { - if (instance.props !== finishedWork.memoizedProps) { - console.error( - 'Expected %s props to match memoized props before ' + - 'getSnapshotBeforeUpdate. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.props`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - if (instance.state !== finishedWork.memoizedState) { - console.error( - 'Expected %s state to match memoized state before ' + - 'getSnapshotBeforeUpdate. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.state`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - } - } - const snapshot = instance.getSnapshotBeforeUpdate( - finishedWork.elementType === finishedWork.type - ? prevProps - : resolveDefaultProps(finishedWork.type, prevProps), - prevState, - ); - if (__DEV__) { - const didWarnSet = ((didWarnAboutUndefinedSnapshotBeforeUpdate: any): Set); - if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { - didWarnSet.add(finishedWork.type); - console.error( - '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + - 'must be returned. You have returned undefined.', - getComponentNameFromFiber(finishedWork), - ); - } - } - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - } - break; - } - case HostRoot: { - if ((flags & Snapshot) !== NoFlags) { - if (supportsMutation) { - const root = finishedWork.stateNode; - clearContainer(root.containerInfo); - } - } - break; - } - case HostComponent: - case HostResource: - case HostSingleton: - case HostText: - case HostPortal: - case IncompleteClassComponent: - // Nothing to do for these component types - break; - default: { - if ((flags & Snapshot) !== NoFlags) { - throw new Error( - 'This unit of work tag should not have side-effects. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - } - } - - if ((flags & Snapshot) !== NoFlags) { - resetCurrentDebugFiberInDEV(); - } -} - -function commitBeforeMutationEffectsDeletion(deletion: Fiber) { - if (enableCreateEventHandleAPI) { - // TODO (effects) It would be nice to avoid calling doesFiberContain() - // Maybe we can repurpose one of the subtreeFlags positions for this instead? - // Use it to store which part of the tree the focused instance is in? - // This assumes we can safely determine that instance during the "render" phase. - if (doesFiberContain(deletion, ((focusedInstanceHandle: any): Fiber))) { - shouldFireAfterActiveInstanceBlur = true; - beforeActiveInstanceBlur(deletion); - } - } -} - -function commitHookEffectListUnmount( - flags: HookFlags, - finishedWork: Fiber, - nearestMountedAncestor: Fiber | null, -) { - const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any); - const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - if (lastEffect !== null) { - const firstEffect = lastEffect.next; - let effect = firstEffect; - do { - if ((effect.tag & flags) === flags) { - // Unmount - const destroy = effect.destroy; - effect.destroy = undefined; - if (destroy !== undefined) { - if (enableSchedulingProfiler) { - if ((flags & HookPassive) !== NoHookEffect) { - markComponentPassiveEffectUnmountStarted(finishedWork); - } else if ((flags & HookLayout) !== NoHookEffect) { - markComponentLayoutEffectUnmountStarted(finishedWork); - } - } - - if (__DEV__) { - if ((flags & HookInsertion) !== NoHookEffect) { - setIsRunningInsertionEffect(true); - } - } - safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); - if (__DEV__) { - if ((flags & HookInsertion) !== NoHookEffect) { - setIsRunningInsertionEffect(false); - } - } - - if (enableSchedulingProfiler) { - if ((flags & HookPassive) !== NoHookEffect) { - markComponentPassiveEffectUnmountStopped(); - } else if ((flags & HookLayout) !== NoHookEffect) { - markComponentLayoutEffectUnmountStopped(); - } - } - } - } - effect = effect.next; - } while (effect !== firstEffect); - } -} - -function commitHookEffectListMount(flags: HookFlags, finishedWork: Fiber) { - const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any); - const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; - if (lastEffect !== null) { - const firstEffect = lastEffect.next; - let effect = firstEffect; - do { - if ((effect.tag & flags) === flags) { - if (enableSchedulingProfiler) { - if ((flags & HookPassive) !== NoHookEffect) { - markComponentPassiveEffectMountStarted(finishedWork); - } else if ((flags & HookLayout) !== NoHookEffect) { - markComponentLayoutEffectMountStarted(finishedWork); - } - } - - // Mount - const create = effect.create; - if (__DEV__) { - if ((flags & HookInsertion) !== NoHookEffect) { - setIsRunningInsertionEffect(true); - } - } - effect.destroy = create(); - if (__DEV__) { - if ((flags & HookInsertion) !== NoHookEffect) { - setIsRunningInsertionEffect(false); - } - } - - if (enableSchedulingProfiler) { - if ((flags & HookPassive) !== NoHookEffect) { - markComponentPassiveEffectMountStopped(); - } else if ((flags & HookLayout) !== NoHookEffect) { - markComponentLayoutEffectMountStopped(); - } - } - - if (__DEV__) { - const destroy = effect.destroy; - if (destroy !== undefined && typeof destroy !== 'function') { - let hookName; - if ((effect.tag & HookLayout) !== NoFlags) { - hookName = 'useLayoutEffect'; - } else if ((effect.tag & HookInsertion) !== NoFlags) { - hookName = 'useInsertionEffect'; - } else { - hookName = 'useEffect'; - } - let addendum; - if (destroy === null) { - addendum = - ' You returned null. If your effect does not require clean ' + - 'up, return undefined (or nothing).'; - } else if (typeof destroy.then === 'function') { - addendum = - '\n\nIt looks like you wrote ' + - hookName + - '(async () => ...) or returned a Promise. ' + - 'Instead, write the async function inside your effect ' + - 'and call it immediately:\n\n' + - hookName + - '(() => {\n' + - ' async function fetchData() {\n' + - ' // You can await here\n' + - ' const response = await MyAPI.getData(someId);\n' + - ' // ...\n' + - ' }\n' + - ' fetchData();\n' + - `}, [someId]); // Or [] if effect doesn't need props or state\n\n` + - 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; - } else { - addendum = ' You returned: ' + destroy; - } - console.error( - '%s must not return anything besides a function, ' + - 'which is used for clean-up.%s', - hookName, - addendum, - ); - } - } - } - effect = effect.next; - } while (effect !== firstEffect); - } -} - -function commitUseEventMount(finishedWork: Fiber) { - const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any); - const eventPayloads = updateQueue !== null ? updateQueue.events : null; - if (eventPayloads !== null) { - for (let ii = 0; ii < eventPayloads.length; ii++) { - const {ref, nextImpl} = eventPayloads[ii]; - ref.impl = nextImpl; - } - } -} - -export function commitPassiveEffectDurations( - finishedRoot: FiberRoot, - finishedWork: Fiber, -): void { - if ( - enableProfilerTimer && - enableProfilerCommitHooks && - getExecutionContext() & CommitContext - ) { - // Only Profilers with work in their subtree will have an Update effect scheduled. - if ((finishedWork.flags & Update) !== NoFlags) { - switch (finishedWork.tag) { - case Profiler: { - const {passiveEffectDuration} = finishedWork.stateNode; - const {id, onPostCommit} = finishedWork.memoizedProps; - - // This value will still reflect the previous commit phase. - // It does not get reset until the start of the next commit phase. - const commitTime = getCommitTime(); - - let phase = finishedWork.alternate === null ? 'mount' : 'update'; - if (enableProfilerNestedUpdatePhase) { - if (isCurrentUpdateNested()) { - phase = 'nested-update'; - } - } - - if (typeof onPostCommit === 'function') { - onPostCommit(id, phase, passiveEffectDuration, commitTime); - } - - // Bubble times to the next nearest ancestor Profiler. - // After we process that Profiler, we'll bubble further up. - let parentFiber = finishedWork.return; - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - const root = parentFiber.stateNode; - root.passiveEffectDuration += passiveEffectDuration; - break outer; - case Profiler: - const parentStateNode = parentFiber.stateNode; - parentStateNode.passiveEffectDuration += passiveEffectDuration; - break outer; - } - parentFiber = parentFiber.return; - } - break; - } - default: - break; - } - } - } -} - -function commitHookLayoutEffects(finishedWork: Fiber, hookFlags: HookFlags) { - // At this point layout effects have already been destroyed (during mutation phase). - // This is done to prevent sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(); - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else { - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } -} - -function commitClassLayoutLifecycles( - finishedWork: Fiber, - current: Fiber | null, -) { - const instance = finishedWork.stateNode; - if (current === null) { - // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - if (__DEV__) { - if ( - finishedWork.type === finishedWork.elementType && - !didWarnAboutReassigningProps - ) { - if (instance.props !== finishedWork.memoizedProps) { - console.error( - 'Expected %s props to match memoized props before ' + - 'componentDidMount. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.props`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - if (instance.state !== finishedWork.memoizedState) { - console.error( - 'Expected %s state to match memoized state before ' + - 'componentDidMount. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.state`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - } - } - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(); - instance.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else { - try { - instance.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } else { - const prevProps = - finishedWork.elementType === finishedWork.type - ? current.memoizedProps - : resolveDefaultProps(finishedWork.type, current.memoizedProps); - const prevState = current.memoizedState; - // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - if (__DEV__) { - if ( - finishedWork.type === finishedWork.elementType && - !didWarnAboutReassigningProps - ) { - if (instance.props !== finishedWork.memoizedProps) { - console.error( - 'Expected %s props to match memoized props before ' + - 'componentDidUpdate. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.props`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - if (instance.state !== finishedWork.memoizedState) { - console.error( - 'Expected %s state to match memoized state before ' + - 'componentDidUpdate. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.state`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - } - } - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(); - instance.componentDidUpdate( - prevProps, - prevState, - instance.__reactInternalSnapshotBeforeUpdate, - ); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else { - try { - instance.componentDidUpdate( - prevProps, - prevState, - instance.__reactInternalSnapshotBeforeUpdate, - ); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } -} - -function commitClassCallbacks(finishedWork: Fiber) { - // TODO: I think this is now always non-null by the time it reaches the - // commit phase. Consider removing the type check. - const updateQueue: UpdateQueue | null = (finishedWork.updateQueue: any); - if (updateQueue !== null) { - const instance = finishedWork.stateNode; - if (__DEV__) { - if ( - finishedWork.type === finishedWork.elementType && - !didWarnAboutReassigningProps - ) { - if (instance.props !== finishedWork.memoizedProps) { - console.error( - 'Expected %s props to match memoized props before ' + - 'processing the update queue. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.props`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - if (instance.state !== finishedWork.memoizedState) { - console.error( - 'Expected %s state to match memoized state before ' + - 'processing the update queue. ' + - 'This might either be because of a bug in React, or because ' + - 'a component reassigns its own `this.state`. ' + - 'Please file an issue.', - getComponentNameFromFiber(finishedWork) || 'instance', - ); - } - } - } - // We could update instance props and state here, - // but instead we rely on them being set during last render. - // TODO: revisit this when we implement resuming. - try { - commitCallbacks(updateQueue, instance); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } -} - -function commitHostComponentMount(finishedWork: Fiber) { - const type = finishedWork.type; - const props = finishedWork.memoizedProps; - const instance: Instance = finishedWork.stateNode; - try { - commitMount(instance, type, props, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } -} - -function commitProfilerUpdate(finishedWork: Fiber, current: Fiber | null) { - if (enableProfilerTimer && getExecutionContext() & CommitContext) { - try { - const {onCommit, onRender} = finishedWork.memoizedProps; - const {effectDuration} = finishedWork.stateNode; - - const commitTime = getCommitTime(); - - let phase = current === null ? 'mount' : 'update'; - if (enableProfilerNestedUpdatePhase) { - if (isCurrentUpdateNested()) { - phase = 'nested-update'; - } - } - - if (typeof onRender === 'function') { - onRender( - finishedWork.memoizedProps.id, - phase, - finishedWork.actualDuration, - finishedWork.treeBaseDuration, - finishedWork.actualStartTime, - commitTime, - ); - } - - if (enableProfilerCommitHooks) { - if (typeof onCommit === 'function') { - onCommit( - finishedWork.memoizedProps.id, - phase, - effectDuration, - commitTime, - ); - } - - // Schedule a passive effect for this Profiler to call onPostCommit hooks. - // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, - // because the effect is also where times bubble to parent Profilers. - enqueuePendingPassiveProfilerEffect(finishedWork); - - // Propagate layout effect durations to the next nearest Profiler ancestor. - // Do not reset these values until the next render so DevTools has a chance to read them first. - let parentFiber = finishedWork.return; - outer: while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - const root = parentFiber.stateNode; - root.effectDuration += effectDuration; - break outer; - case Profiler: - const parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += effectDuration; - break outer; - } - parentFiber = parentFiber.return; - } - } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } -} - -function commitLayoutEffectOnFiber( - finishedRoot: FiberRoot, - current: Fiber | null, - finishedWork: Fiber, - committedLanes: Lanes, -): void { - // When updating this function, also update reappearLayoutEffects, which does - // most of the same things when an offscreen tree goes from hidden -> visible. - const flags = finishedWork.flags; - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - if (flags & Update) { - commitHookLayoutEffects(finishedWork, HookLayout | HookHasEffect); - } - break; - } - case ClassComponent: { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - if (flags & Update) { - commitClassLayoutLifecycles(finishedWork, current); - } - - if (flags & Callback) { - commitClassCallbacks(finishedWork); - } - - if (flags & Ref) { - safelyAttachRef(finishedWork, finishedWork.return); - } - break; - } - case HostRoot: { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - if (flags & Callback) { - // TODO: I think this is now always non-null by the time it reaches the - // commit phase. Consider removing the type check. - const updateQueue: UpdateQueue | null = (finishedWork.updateQueue: any); - if (updateQueue !== null) { - let instance = null; - if (finishedWork.child !== null) { - switch (finishedWork.child.tag) { - case HostSingleton: - case HostComponent: - instance = getPublicInstance(finishedWork.child.stateNode); - break; - case ClassComponent: - instance = finishedWork.child.stateNode; - break; - } - } - try { - commitCallbacks(updateQueue, instance); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } - break; - } - case HostResource: { - if (enableFloat && supportsResources) { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - - if (flags & Ref) { - safelyAttachRef(finishedWork, finishedWork.return); - } - break; - } - } - // eslint-disable-next-line-no-fallthrough - case HostSingleton: - case HostComponent: { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - - // Renderers may schedule work to be done after host components are mounted - // (eg DOM renderer may schedule auto-focus for inputs and form controls). - // These effects should only be committed when components are first mounted, - // aka when there is no current/alternate. - if (current === null && flags & Update) { - commitHostComponentMount(finishedWork); - } - - if (flags & Ref) { - safelyAttachRef(finishedWork, finishedWork.return); - } - break; - } - case Profiler: { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - // TODO: Should this fire inside an offscreen tree? Or should it wait to - // fire when the tree becomes visible again. - if (flags & Update) { - commitProfilerUpdate(finishedWork, current); - } - break; - } - case SuspenseComponent: { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - if (flags & Update) { - commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); - } - break; - } - case OffscreenComponent: { - const isModernRoot = (finishedWork.mode & ConcurrentMode) !== NoMode; - if (isModernRoot) { - const isHidden = finishedWork.memoizedState !== null; - const newOffscreenSubtreeIsHidden = - isHidden || offscreenSubtreeIsHidden; - if (newOffscreenSubtreeIsHidden) { - // The Offscreen tree is hidden. Skip over its layout effects. - } else { - // The Offscreen tree is visible. - - const wasHidden = current !== null && current.memoizedState !== null; - const newOffscreenSubtreeWasHidden = - wasHidden || offscreenSubtreeWasHidden; - const prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; - const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; - - if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { - // This is the root of a reappearing boundary. As we continue - // traversing the layout effects, we must also re-mount layout - // effects that were unmounted when the Offscreen subtree was - // hidden. So this is a superset of the normal commitLayoutEffects. - const includeWorkInProgressEffects = - (finishedWork.subtreeFlags & LayoutMask) !== NoFlags; - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - } else { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - } - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - } - } else { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - } - if (flags & Ref) { - const props: OffscreenProps = finishedWork.memoizedProps; - if (props.mode === 'manual') { - safelyAttachRef(finishedWork, finishedWork.return); - } else { - safelyDetachRef(finishedWork, finishedWork.return); - } - } - break; - } - default: { - recursivelyTraverseLayoutEffects( - finishedRoot, - finishedWork, - committedLanes, - ); - break; - } - } -} - -function abortRootTransitions( - root: FiberRoot, - abort: TransitionAbort, - deletedTransitions: Set, - deletedOffscreenInstance: OffscreenInstance | null, - isInDeletedTree: boolean, -) { - if (enableTransitionTracing) { - const rootTransitions = root.incompleteTransitions; - deletedTransitions.forEach(transition => { - if (rootTransitions.has(transition)) { - const transitionInstance: TracingMarkerInstance = (rootTransitions.get( - transition, - ): any); - if (transitionInstance.aborts === null) { - transitionInstance.aborts = []; - } - transitionInstance.aborts.push(abort); - - if (deletedOffscreenInstance !== null) { - if ( - transitionInstance.pendingBoundaries !== null && - transitionInstance.pendingBoundaries.has(deletedOffscreenInstance) - ) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - transitionInstance.pendingBoundaries.delete( - deletedOffscreenInstance, - ); - } - } - } - }); - } -} - -function abortTracingMarkerTransitions( - abortedFiber: Fiber, - abort: TransitionAbort, - deletedTransitions: Set, - deletedOffscreenInstance: OffscreenInstance | null, - isInDeletedTree: boolean, -) { - if (enableTransitionTracing) { - const markerInstance: TracingMarkerInstance = abortedFiber.stateNode; - const markerTransitions = markerInstance.transitions; - const pendingBoundaries = markerInstance.pendingBoundaries; - if (markerTransitions !== null) { - // TODO: Refactor this code. Is there a way to move this code to - // the deletions phase instead of calculating it here while making sure - // complete is called appropriately? - deletedTransitions.forEach(transition => { - // If one of the transitions on the tracing marker is a transition - // that was in an aborted subtree, we will abort that tracing marker - if ( - abortedFiber !== null && - markerTransitions.has(transition) && - (markerInstance.aborts === null || - !markerInstance.aborts.includes(abort)) - ) { - if (markerInstance.transitions !== null) { - if (markerInstance.aborts === null) { - markerInstance.aborts = [abort]; - addMarkerIncompleteCallbackToPendingTransition( - abortedFiber.memoizedProps.name, - markerInstance.transitions, - markerInstance.aborts, - ); - } else { - markerInstance.aborts.push(abort); - } - - // We only want to call onTransitionProgress when the marker hasn't been - // deleted - if ( - deletedOffscreenInstance !== null && - !isInDeletedTree && - pendingBoundaries !== null && - pendingBoundaries.has(deletedOffscreenInstance) - ) { - pendingBoundaries.delete(deletedOffscreenInstance); - - addMarkerProgressCallbackToPendingTransition( - abortedFiber.memoizedProps.name, - deletedTransitions, - pendingBoundaries, - ); - } - } - } - }); - } - } -} - -function abortParentMarkerTransitionsForDeletedFiber( - abortedFiber: Fiber, - abort: TransitionAbort, - deletedTransitions: Set, - deletedOffscreenInstance: OffscreenInstance | null, - isInDeletedTree: boolean, -) { - if (enableTransitionTracing) { - // Find all pending markers that are waiting on child suspense boundaries in the - // aborted subtree and cancels them - let fiber: null | Fiber = abortedFiber; - while (fiber !== null) { - switch (fiber.tag) { - case TracingMarkerComponent: - abortTracingMarkerTransitions( - fiber, - abort, - deletedTransitions, - deletedOffscreenInstance, - isInDeletedTree, - ); - break; - case HostRoot: - const root = fiber.stateNode; - abortRootTransitions( - root, - abort, - deletedTransitions, - deletedOffscreenInstance, - isInDeletedTree, - ); - - break; - default: - break; - } - - fiber = fiber.return; - } - } -} - -function commitTransitionProgress(offscreenFiber: Fiber) { - if (enableTransitionTracing) { - // This function adds suspense boundaries to the root - // or tracing marker's pendingBoundaries map. - // When a suspense boundary goes from a resolved to a fallback - // state we add the boundary to the map, and when it goes from - // a fallback to a resolved state, we remove the boundary from - // the map. - - // We use stateNode on the Offscreen component as a stable object - // that doesnt change from render to render. This way we can - // distinguish between different Offscreen instances (vs. the same - // Offscreen instance with different fibers) - const offscreenInstance: OffscreenInstance = offscreenFiber.stateNode; - - let prevState: SuspenseState | null = null; - const previousFiber = offscreenFiber.alternate; - if (previousFiber !== null && previousFiber.memoizedState !== null) { - prevState = previousFiber.memoizedState; - } - const nextState: SuspenseState | null = offscreenFiber.memoizedState; - - const wasHidden = prevState !== null; - const isHidden = nextState !== null; - - const pendingMarkers = offscreenInstance._pendingMarkers; - // If there is a name on the suspense boundary, store that in - // the pending boundaries. - let name = null; - const parent = offscreenFiber.return; - if ( - parent !== null && - parent.tag === SuspenseComponent && - parent.memoizedProps.unstable_name - ) { - name = parent.memoizedProps.unstable_name; - } - - if (!wasHidden && isHidden) { - // The suspense boundaries was just hidden. Add the boundary - // to the pending boundary set if it's there - if (pendingMarkers !== null) { - pendingMarkers.forEach(markerInstance => { - const pendingBoundaries = markerInstance.pendingBoundaries; - const transitions = markerInstance.transitions; - const markerName = markerInstance.name; - if ( - pendingBoundaries !== null && - !pendingBoundaries.has(offscreenInstance) - ) { - pendingBoundaries.set(offscreenInstance, { - name, - }); - if (transitions !== null) { - if ( - markerInstance.tag === TransitionTracingMarker && - markerName !== null - ) { - addMarkerProgressCallbackToPendingTransition( - markerName, - transitions, - pendingBoundaries, - ); - } else if (markerInstance.tag === TransitionRoot) { - transitions.forEach(transition => { - addTransitionProgressCallbackToPendingTransition( - transition, - pendingBoundaries, - ); - }); - } - } - } - }); - } - } else if (wasHidden && !isHidden) { - // The suspense boundary went from hidden to visible. Remove - // the boundary from the pending suspense boundaries set - // if it's there - if (pendingMarkers !== null) { - pendingMarkers.forEach(markerInstance => { - const pendingBoundaries = markerInstance.pendingBoundaries; - const transitions = markerInstance.transitions; - const markerName = markerInstance.name; - if ( - pendingBoundaries !== null && - pendingBoundaries.has(offscreenInstance) - ) { - pendingBoundaries.delete(offscreenInstance); - if (transitions !== null) { - if ( - markerInstance.tag === TransitionTracingMarker && - markerName !== null - ) { - addMarkerProgressCallbackToPendingTransition( - markerName, - transitions, - pendingBoundaries, - ); - - // If there are no more unresolved suspense boundaries, the interaction - // is considered finished - if (pendingBoundaries.size === 0) { - if (markerInstance.aborts === null) { - addMarkerCompleteCallbackToPendingTransition( - markerName, - transitions, - ); - } - markerInstance.transitions = null; - markerInstance.pendingBoundaries = null; - markerInstance.aborts = null; - } - } else if (markerInstance.tag === TransitionRoot) { - transitions.forEach(transition => { - addTransitionProgressCallbackToPendingTransition( - transition, - pendingBoundaries, - ); - }); - } - } - } - }); - } - } - } -} - -function hideOrUnhideAllChildren(finishedWork, isHidden) { - // Only hide or unhide the top-most host nodes. - let hostSubtreeRoot = null; - - if (supportsMutation) { - // We only have the top Fiber that was inserted but we need to recurse down its - // children to find all the terminal nodes. - let node: Fiber = finishedWork; - while (true) { - if ( - node.tag === HostComponent || - (enableFloat && supportsResources - ? node.tag === HostResource - : false) || - (enableHostSingletons && supportsSingletons - ? node.tag === HostSingleton - : false) - ) { - if (hostSubtreeRoot === null) { - hostSubtreeRoot = node; - try { - const instance = node.stateNode; - if (isHidden) { - hideInstance(instance); - } else { - unhideInstance(node.stateNode, node.memoizedProps); - } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } else if (node.tag === HostText) { - if (hostSubtreeRoot === null) { - try { - const instance = node.stateNode; - if (isHidden) { - hideTextInstance(instance); - } else { - unhideTextInstance(instance, node.memoizedProps); - } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } else if ( - (node.tag === OffscreenComponent || - node.tag === LegacyHiddenComponent) && - (node.memoizedState: OffscreenState) !== null && - node !== finishedWork - ) { - // Found a nested Offscreen component that is hidden. - // Don't search any deeper. This tree should remain hidden. - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === finishedWork) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return; - } - - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - - node = node.return; - } - - if (hostSubtreeRoot === node) { - hostSubtreeRoot = null; - } - - node.sibling.return = node.return; - node = node.sibling; - } - } -} - -function commitAttachRef(finishedWork: Fiber) { - const ref = finishedWork.ref; - if (ref !== null) { - const instance = finishedWork.stateNode; - let instanceToUse; - switch (finishedWork.tag) { - case HostResource: - case HostSingleton: - case HostComponent: - instanceToUse = getPublicInstance(instance); - break; - default: - instanceToUse = instance; - } - // Moved outside to ensure DCE works with this flag - if (enableScopeAPI && finishedWork.tag === ScopeComponent) { - instanceToUse = instance; - } - if (typeof ref === 'function') { - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(); - finishedWork.refCleanup = ref(instanceToUse); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - finishedWork.refCleanup = ref(instanceToUse); - } - } else { - if (__DEV__) { - if (!ref.hasOwnProperty('current')) { - console.error( - 'Unexpected ref object provided for %s. ' + - 'Use either a ref-setter function or React.createRef().', - getComponentNameFromFiber(finishedWork), - ); - } - } - - // $FlowFixMe unable to narrow type to the non-function case - ref.current = instanceToUse; - } - } -} - -function detachFiberMutation(fiber: Fiber) { - // Cut off the return pointer to disconnect it from the tree. - // This enables us to detect and warn against state updates on an unmounted component. - // It also prevents events from bubbling from within disconnected components. - // - // Ideally, we should also clear the child pointer of the parent alternate to let this - // get GC:ed but we don't know which for sure which parent is the current - // one so we'll settle for GC:ing the subtree of this child. - // This child itself will be GC:ed when the parent updates the next time. - // - // Note that we can't clear child or sibling pointers yet. - // They're needed for passive effects and for findDOMNode. - // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). - // - // Don't reset the alternate yet, either. We need that so we can detach the - // alternate's fields in the passive phase. Clearing the return pointer is - // sufficient for findDOMNode semantics. - const alternate = fiber.alternate; - if (alternate !== null) { - alternate.return = null; - } - fiber.return = null; -} - -function detachFiberAfterEffects(fiber: Fiber) { - const alternate = fiber.alternate; - if (alternate !== null) { - fiber.alternate = null; - detachFiberAfterEffects(alternate); - } - - // Note: Defensively using negation instead of < in case - // `deletedTreeCleanUpLevel` is undefined. - if (!(deletedTreeCleanUpLevel >= 2)) { - // This is the default branch (level 0). - fiber.child = null; - fiber.deletions = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.sibling = null; - fiber.stateNode = null; - fiber.updateQueue = null; - - if (__DEV__) { - fiber._debugOwner = null; - } - } else { - // Clear cyclical Fiber fields. This level alone is designed to roughly - // approximate the planned Fiber refactor. In that world, `setState` will be - // bound to a special "instance" object instead of a Fiber. The Instance - // object will not have any of these fields. It will only be connected to - // the fiber tree via a single link at the root. So if this level alone is - // sufficient to fix memory issues, that bodes well for our plans. - fiber.child = null; - fiber.deletions = null; - fiber.sibling = null; - - // The `stateNode` is cyclical because on host nodes it points to the host - // tree, which has its own pointers to children, parents, and siblings. - // The other host nodes also point back to fibers, so we should detach that - // one, too. - if (fiber.tag === HostComponent) { - const hostInstance: Instance = fiber.stateNode; - if (hostInstance !== null) { - detachDeletedInstance(hostInstance); - } - } - fiber.stateNode = null; - - // I'm intentionally not clearing the `return` field in this level. We - // already disconnect the `return` pointer at the root of the deleted - // subtree (in `detachFiberMutation`). Besides, `return` by itself is not - // cyclical — it's only cyclical when combined with `child`, `sibling`, and - // `alternate`. But we'll clear it in the next level anyway, just in case. - - if (__DEV__) { - fiber._debugOwner = null; - } - - if (deletedTreeCleanUpLevel >= 3) { - // Theoretically, nothing in here should be necessary, because we already - // disconnected the fiber from the tree. So even if something leaks this - // particular fiber, it won't leak anything else - // - // The purpose of this branch is to be super aggressive so we can measure - // if there's any difference in memory impact. If there is, that could - // indicate a React leak we don't know about. - fiber.return = null; - fiber.dependencies = null; - fiber.memoizedProps = null; - fiber.memoizedState = null; - fiber.pendingProps = null; - fiber.stateNode = null; - // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. - fiber.updateQueue = null; - } - } -} - -function emptyPortalContainer(current: Fiber) { - if (!supportsPersistence) { - return; - } - - const portal: { - containerInfo: Container, - pendingChildren: ChildSet, - ... - } = current.stateNode; - const {containerInfo} = portal; - const emptyChildSet = createContainerChildSet(containerInfo); - replaceContainerChildren(containerInfo, emptyChildSet); -} - -function getHostParentFiber(fiber: Fiber): Fiber { - let parent = fiber.return; - while (parent !== null) { - if (isHostParent(parent)) { - return parent; - } - parent = parent.return; - } - - throw new Error( - 'Expected to find a host parent. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); -} - -function isHostParent(fiber: Fiber): boolean { - return ( - fiber.tag === HostComponent || - fiber.tag === HostRoot || - (enableFloat && supportsResources ? fiber.tag === HostResource : false) || - (enableHostSingletons && supportsSingletons - ? fiber.tag === HostSingleton - : false) || - fiber.tag === HostPortal - ); -} - -function getHostSibling(fiber: Fiber): ?Instance { - // We're going to search forward into the tree until we find a sibling host - // node. Unfortunately, if multiple insertions are done in a row we have to - // search past them. This leads to exponential search for the next sibling. - // TODO: Find a more efficient way to do this. - let node: Fiber = fiber; - siblings: while (true) { - // If we didn't find anything, let's try the next sibling. - while (node.sibling === null) { - if (node.return === null || isHostParent(node.return)) { - // If we pop out of the root or hit the parent the fiber we are the - // last sibling. - return null; - } - // $FlowFixMe[incompatible-type] found when upgrading Flow - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - while ( - node.tag !== HostComponent && - node.tag !== HostText && - (!(enableHostSingletons && supportsSingletons) - ? true - : node.tag !== HostSingleton) && - node.tag !== DehydratedFragment - ) { - // If it is not host node and, we might have a host node inside it. - // Try to search down until we find one. - if (node.flags & Placement) { - // If we don't have a child, try the siblings instead. - continue siblings; - } - // If we don't have a child, try the siblings instead. - // We also skip portals because they are not part of this host tree. - if (node.child === null || node.tag === HostPortal) { - continue siblings; - } else { - node.child.return = node; - node = node.child; - } - } - // Check if this host node is stable or about to be placed. - if (!(node.flags & Placement)) { - // Found it! - return node.stateNode; - } - } -} - -function commitPlacement(finishedWork: Fiber): void { - if (!supportsMutation) { - return; - } - - if (enableHostSingletons && supportsSingletons) { - if (finishedWork.tag === HostSingleton) { - // Singletons are already in the Host and don't need to be placed - // Since they operate somewhat like Portals though their children will - // have Placement and will get placed inside them - return; - } - } - // Recursively insert all host nodes into the parent. - const parentFiber = getHostParentFiber(finishedWork); - - switch (parentFiber.tag) { - case HostSingleton: { - if (enableHostSingletons && supportsSingletons) { - const parent: Instance = parentFiber.stateNode; - const before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need to recurse down its - // children to find all the terminal nodes. - insertOrAppendPlacementNode(finishedWork, before, parent); - break; - } - } - // eslint-disable-next-line no-fallthrough - case HostComponent: { - const parent: Instance = parentFiber.stateNode; - if (parentFiber.flags & ContentReset) { - // Reset the text content of the parent before doing any insertions - resetTextContent(parent); - // Clear ContentReset from the effect tag - parentFiber.flags &= ~ContentReset; - } - - const before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need to recurse down its - // children to find all the terminal nodes. - insertOrAppendPlacementNode(finishedWork, before, parent); - break; - } - case HostRoot: - case HostPortal: { - const parent: Container = parentFiber.stateNode.containerInfo; - const before = getHostSibling(finishedWork); - insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent); - break; - } - // eslint-disable-next-line-no-fallthrough - default: - throw new Error( - 'Invalid host parent fiber. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - } -} - -function insertOrAppendPlacementNodeIntoContainer( - node: Fiber, - before: ?Instance, - parent: Container, -): void { - const {tag} = node; - const isHost = tag === HostComponent || tag === HostText; - if (isHost) { - const stateNode = node.stateNode; - if (before) { - insertInContainerBefore(parent, stateNode, before); - } else { - appendChildToContainer(parent, stateNode); - } - } else if ( - tag === HostPortal || - (enableHostSingletons && supportsSingletons ? tag === HostSingleton : false) - ) { - // If the insertion itself is a portal, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - // If the insertion is a HostSingleton then it will be placed independently - } else { - const child = node.child; - if (child !== null) { - insertOrAppendPlacementNodeIntoContainer(child, before, parent); - let sibling = child.sibling; - while (sibling !== null) { - insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); - sibling = sibling.sibling; - } - } - } -} - -function insertOrAppendPlacementNode( - node: Fiber, - before: ?Instance, - parent: Instance, -): void { - const {tag} = node; - const isHost = tag === HostComponent || tag === HostText; - if (isHost) { - const stateNode = node.stateNode; - if (before) { - insertBefore(parent, stateNode, before); - } else { - appendChild(parent, stateNode); - } - } else if ( - tag === HostPortal || - (enableHostSingletons && supportsSingletons ? tag === HostSingleton : false) - ) { - // If the insertion itself is a portal, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - // If the insertion is a HostSingleton then it will be placed independently - } else { - const child = node.child; - if (child !== null) { - insertOrAppendPlacementNode(child, before, parent); - let sibling = child.sibling; - while (sibling !== null) { - insertOrAppendPlacementNode(sibling, before, parent); - sibling = sibling.sibling; - } - } - } -} - -// These are tracked on the stack as we recursively traverse a -// deleted subtree. -// TODO: Update these during the whole mutation phase, not just during -// a deletion. -let hostParent: Instance | Container | null = null; -let hostParentIsContainer: boolean = false; - -function commitDeletionEffects( - root: FiberRoot, - returnFiber: Fiber, - deletedFiber: Fiber, -) { - if (supportsMutation) { - // We only have the top Fiber that was deleted but we need to recurse down its - // children to find all the terminal nodes. - - // Recursively delete all host nodes from the parent, detach refs, clean - // up mounted layout effects, and call componentWillUnmount. - - // We only need to remove the topmost host child in each branch. But then we - // still need to keep traversing to unmount effects, refs, and cWU. TODO: We - // could split this into two separate traversals functions, where the second - // one doesn't include any removeChild logic. This is maybe the same - // function as "disappearLayoutEffects" (or whatever that turns into after - // the layout phase is refactored to use recursion). - - // Before starting, find the nearest host parent on the stack so we know - // which instance/container to remove the children from. - // TODO: Instead of searching up the fiber return path on every deletion, we - // can track the nearest host component on the JS stack as we traverse the - // tree during the commit phase. This would make insertions faster, too. - let parent: null | Fiber = returnFiber; - findParent: while (parent !== null) { - switch (parent.tag) { - case HostSingleton: - case HostComponent: { - hostParent = parent.stateNode; - hostParentIsContainer = false; - break findParent; - } - case HostRoot: { - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = true; - break findParent; - } - case HostPortal: { - hostParent = parent.stateNode.containerInfo; - hostParentIsContainer = true; - break findParent; - } - } - parent = parent.return; - } - if (hostParent === null) { - throw new Error( - 'Expected to find a host parent. This error is likely caused by ' + - 'a bug in React. Please file an issue.', - ); - } - - commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); - hostParent = null; - hostParentIsContainer = false; - } else { - // Detach refs and call componentWillUnmount() on the whole subtree. - commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); - } - - detachFiberMutation(deletedFiber); -} - -function recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - parent, -) { - // TODO: Use a static flag to skip trees that don't have unmount effects - let child = parent.child; - while (child !== null) { - commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child); - child = child.sibling; - } -} - -function commitDeletionEffectsOnFiber( - finishedRoot: FiberRoot, - nearestMountedAncestor: Fiber, - deletedFiber: Fiber, -) { - onCommitUnmount(deletedFiber); - - // The cases in this outer switch modify the stack before they traverse - // into their subtree. There are simpler cases in the inner switch - // that don't modify the stack. - switch (deletedFiber.tag) { - case HostResource: { - if (enableFloat && supportsResources) { - if (!offscreenSubtreeWasHidden) { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - if (deletedFiber.memoizedState) { - releaseResource(deletedFiber.memoizedState); - } - return; - } - } - // eslint-disable-next-line no-fallthrough - case HostSingleton: { - if (enableHostSingletons && supportsSingletons) { - if (!offscreenSubtreeWasHidden) { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - } - - const prevHostParent = hostParent; - const prevHostParentIsContainer = hostParentIsContainer; - hostParent = deletedFiber.stateNode; - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - - // Normally this is called in passive unmount effect phase however with - // HostSingleton we warn if you acquire one that is already associated to - // a different fiber. To increase our chances of avoiding this, specifically - // if you keyed a HostSingleton so there will be a delete followed by a Placement - // we treat detach eagerly here - releaseSingletonInstance(deletedFiber.stateNode); - - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - - return; - } - } - // eslint-disable-next-line no-fallthrough - case HostComponent: { - if (!offscreenSubtreeWasHidden) { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - } - // Intentional fallthrough to next branch - } - // eslint-disable-next-line-no-fallthrough - case HostText: { - // We only need to remove the nearest host child. Set the host parent - // to `null` on the stack to indicate that nested children don't - // need to be removed. - if (supportsMutation) { - const prevHostParent = hostParent; - const prevHostParentIsContainer = hostParentIsContainer; - hostParent = null; - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - - if (hostParent !== null) { - // Now that all the child effects have unmounted, we can remove the - // node from the tree. - if (hostParentIsContainer) { - removeChildFromContainer( - ((hostParent: any): Container), - (deletedFiber.stateNode: Instance | TextInstance), - ); - } else { - removeChild( - ((hostParent: any): Instance), - (deletedFiber.stateNode: Instance | TextInstance), - ); - } - } - } else { - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - } - return; - } - case DehydratedFragment: { - if (enableSuspenseCallback) { - const hydrationCallbacks = finishedRoot.hydrationCallbacks; - if (hydrationCallbacks !== null) { - const onDeleted = hydrationCallbacks.onDeleted; - if (onDeleted) { - onDeleted((deletedFiber.stateNode: SuspenseInstance)); - } - } - } - - // Dehydrated fragments don't have any children - - // Delete the dehydrated suspense boundary and all of its content. - if (supportsMutation) { - if (hostParent !== null) { - if (hostParentIsContainer) { - clearSuspenseBoundaryFromContainer( - ((hostParent: any): Container), - (deletedFiber.stateNode: SuspenseInstance), - ); - } else { - clearSuspenseBoundary( - ((hostParent: any): Instance), - (deletedFiber.stateNode: SuspenseInstance), - ); - } - } - } - return; - } - case HostPortal: { - if (supportsMutation) { - // When we go into a portal, it becomes the parent to remove from. - const prevHostParent = hostParent; - const prevHostParentIsContainer = hostParentIsContainer; - hostParent = deletedFiber.stateNode.containerInfo; - hostParentIsContainer = true; - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - hostParent = prevHostParent; - hostParentIsContainer = prevHostParentIsContainer; - } else { - emptyPortalContainer(deletedFiber); - - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - } - return; - } - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: { - if (!offscreenSubtreeWasHidden) { - const updateQueue: FunctionComponentUpdateQueue | null = (deletedFiber.updateQueue: any); - if (updateQueue !== null) { - const lastEffect = updateQueue.lastEffect; - if (lastEffect !== null) { - const firstEffect = lastEffect.next; - - let effect = firstEffect; - do { - const {destroy, tag} = effect; - if (destroy !== undefined) { - if ((tag & HookInsertion) !== NoHookEffect) { - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy, - ); - } else if ((tag & HookLayout) !== NoHookEffect) { - if (enableSchedulingProfiler) { - markComponentLayoutEffectUnmountStarted(deletedFiber); - } - - if (shouldProfile(deletedFiber)) { - startLayoutEffectTimer(); - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy, - ); - recordLayoutEffectDuration(deletedFiber); - } else { - safelyCallDestroy( - deletedFiber, - nearestMountedAncestor, - destroy, - ); - } - - if (enableSchedulingProfiler) { - markComponentLayoutEffectUnmountStopped(); - } - } - } - effect = effect.next; - } while (effect !== firstEffect); - } - } - } - - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - return; - } - case ClassComponent: { - if (!offscreenSubtreeWasHidden) { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - const instance = deletedFiber.stateNode; - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount( - deletedFiber, - nearestMountedAncestor, - instance, - ); - } - } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - return; - } - case ScopeComponent: { - if (enableScopeAPI) { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - } - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - return; - } - case OffscreenComponent: { - safelyDetachRef(deletedFiber, nearestMountedAncestor); - if (deletedFiber.mode & ConcurrentMode) { - // If this offscreen component is hidden, we already unmounted it. Before - // deleting the children, track that it's already unmounted so that we - // don't attempt to unmount the effects again. - // TODO: If the tree is hidden, in most cases we should be able to skip - // over the nested children entirely. An exception is we haven't yet found - // the topmost host node to delete, which we already track on the stack. - // But the other case is portals, which need to be detached no matter how - // deeply they are nested. We should use a subtree flag to track whether a - // subtree includes a nested portal. - const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeWasHidden = - prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null; - - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - } else { - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - } - break; - } - default: { - recursivelyTraverseDeletionEffects( - finishedRoot, - nearestMountedAncestor, - deletedFiber, - ); - return; - } - } -} -function commitSuspenseCallback(finishedWork: Fiber) { - // TODO: Move this to passive phase - const newState: SuspenseState | null = finishedWork.memoizedState; - if (enableSuspenseCallback && newState !== null) { - const suspenseCallback = finishedWork.memoizedProps.suspenseCallback; - if (typeof suspenseCallback === 'function') { - const wakeables: Set | null = (finishedWork.updateQueue: any); - if (wakeables !== null) { - suspenseCallback(new Set(wakeables)); - } - } else if (__DEV__) { - if (suspenseCallback !== undefined) { - console.error('Unexpected type for suspenseCallback.'); - } - } - } -} - -function commitSuspenseHydrationCallbacks( - finishedRoot: FiberRoot, - finishedWork: Fiber, -) { - if (!supportsHydration) { - return; - } - const newState: SuspenseState | null = finishedWork.memoizedState; - if (newState === null) { - const current = finishedWork.alternate; - if (current !== null) { - const prevState: SuspenseState | null = current.memoizedState; - if (prevState !== null) { - const suspenseInstance = prevState.dehydrated; - if (suspenseInstance !== null) { - try { - commitHydratedSuspenseInstance(suspenseInstance); - if (enableSuspenseCallback) { - const hydrationCallbacks = finishedRoot.hydrationCallbacks; - if (hydrationCallbacks !== null) { - const onHydrated = hydrationCallbacks.onHydrated; - if (onHydrated) { - onHydrated(suspenseInstance); - } - } - } - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } - } - } -} - -function getRetryCache(finishedWork) { - // TODO: Unify the interface for the retry cache so we don't have to switch - // on the tag like this. - switch (finishedWork.tag) { - case SuspenseComponent: - case SuspenseListComponent: { - let retryCache = finishedWork.stateNode; - if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet(); - } - return retryCache; - } - case OffscreenComponent: { - const instance: OffscreenInstance = finishedWork.stateNode; - // $FlowFixMe[incompatible-type-arg] found when upgrading Flow - let retryCache: null | Set | WeakSet = - // $FlowFixMe[incompatible-type] found when upgrading Flow - instance._retryCache; - if (retryCache === null) { - // $FlowFixMe[incompatible-type] - retryCache = instance._retryCache = new PossiblyWeakSet(); - } - return retryCache; - } - default: { - throw new Error( - `Unexpected Suspense handler tag (${finishedWork.tag}). This is a ` + - 'bug in React.', - ); - } - } -} - -export function detachOffscreenInstance(instance: OffscreenInstance): void { - const currentOffscreenFiber = instance._current; - if (currentOffscreenFiber === null) { - throw new Error( - 'Calling Offscreen.detach before instance handle has been set.', - ); - } - - const executionContext = getExecutionContext(); - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - scheduleMicrotask(() => { - instance._visibility |= OffscreenDetached; - disappearLayoutEffects(currentOffscreenFiber); - disconnectPassiveEffect(currentOffscreenFiber); - }); - } else { - instance._visibility |= OffscreenDetached; - disappearLayoutEffects(currentOffscreenFiber); - disconnectPassiveEffect(currentOffscreenFiber); - } -} - -function attachSuspenseRetryListeners( - finishedWork: Fiber, - wakeables: Set, -) { - // If this boundary just timed out, then it will have a set of wakeables. - // For each wakeable, attach a listener so that when it resolves, React - // attempts to re-render the boundary in the primary (pre-timeout) state. - const retryCache = getRetryCache(finishedWork); - wakeables.forEach(wakeable => { - // Memoize using the boundary fiber to prevent redundant listeners. - const retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); - if (!retryCache.has(wakeable)) { - retryCache.add(wakeable); - - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - if (inProgressLanes !== null && inProgressRoot !== null) { - // If we have pending work still, associate the original updaters with it. - restorePendingUpdaters(inProgressRoot, inProgressLanes); - } else { - throw Error( - 'Expected finished root and lanes to be set. This is a bug in React.', - ); - } - } - } - - wakeable.then(retry, retry); - } - }); -} - -// This function detects when a Suspense boundary goes from visible to hidden. -// It returns false if the boundary is already hidden. -// TODO: Use an effect tag. -export function isSuspenseBoundaryBeingHidden( - current: Fiber | null, - finishedWork: Fiber, -): boolean { - if (current !== null) { - const oldState: SuspenseState | null = current.memoizedState; - if (oldState === null || oldState.dehydrated !== null) { - const newState: SuspenseState | null = finishedWork.memoizedState; - return newState !== null && newState.dehydrated === null; - } - } - return false; -} - -export function commitMutationEffects( - root: FiberRoot, - finishedWork: Fiber, - committedLanes: Lanes, -) { - inProgressLanes = committedLanes; - inProgressRoot = root; - - setCurrentDebugFiberInDEV(finishedWork); - commitMutationEffectsOnFiber(finishedWork, root, committedLanes); - setCurrentDebugFiberInDEV(finishedWork); - - inProgressLanes = null; - inProgressRoot = null; -} - -function recursivelyTraverseMutationEffects( - root: FiberRoot, - parentFiber: Fiber, - lanes: Lanes, -) { - // Deletions effects can be scheduled on any fiber type. They need to happen - // before the children effects hae fired. - const deletions = parentFiber.deletions; - if (deletions !== null) { - for (let i = 0; i < deletions.length; i++) { - const childToDelete = deletions[i]; - try { - commitDeletionEffects(root, parentFiber, childToDelete); - } catch (error) { - captureCommitPhaseError(childToDelete, parentFiber, error); - } - } - } - - const prevDebugFiber = getCurrentDebugFiberInDEV(); - if (parentFiber.subtreeFlags & MutationMask) { - let child = parentFiber.child; - while (child !== null) { - setCurrentDebugFiberInDEV(child); - commitMutationEffectsOnFiber(child, root, lanes); - child = child.sibling; - } - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -function commitMutationEffectsOnFiber( - finishedWork: Fiber, - root: FiberRoot, - lanes: Lanes, -) { - const current = finishedWork.alternate; - const flags = finishedWork.flags; - - // The effect flag should be checked *after* we refine the type of fiber, - // because the fiber tag is more specific. An exception is any flag related - // to reconciliation, because those can be set on all fiber types. - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Update) { - try { - commitHookEffectListUnmount( - HookInsertion | HookHasEffect, - finishedWork, - finishedWork.return, - ); - commitHookEffectListMount( - HookInsertion | HookHasEffect, - finishedWork, - ); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - // Layout effects are destroyed during the mutation phase so that all - // destroy functions for all fibers are called before any create functions. - // This prevents sibling component effects from interfering with each other, - // e.g. a destroy function in one component should never override a ref set - // by a create function in another component during the same commit. - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount( - HookLayout | HookHasEffect, - finishedWork, - finishedWork.return, - ); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordLayoutEffectDuration(finishedWork); - } else { - try { - commitHookEffectListUnmount( - HookLayout | HookHasEffect, - finishedWork, - finishedWork.return, - ); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } - return; - } - case ClassComponent: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Ref) { - if (current !== null) { - safelyDetachRef(current, current.return); - } - } - - if (flags & Callback && offscreenSubtreeIsHidden) { - const updateQueue: UpdateQueue | null = (finishedWork.updateQueue: any); - if (updateQueue !== null) { - deferHiddenCallbacks(updateQueue); - } - } - return; - } - case HostResource: { - if (enableFloat && supportsResources) { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Ref) { - if (current !== null) { - safelyDetachRef(current, current.return); - } - } - - if (flags & Update) { - const newResource = finishedWork.memoizedState; - if (current !== null) { - const currentResource = current.memoizedState; - if (currentResource !== newResource) { - releaseResource(currentResource); - } - } - finishedWork.stateNode = newResource - ? acquireResource(newResource) - : null; - } - return; - } - } - // eslint-disable-next-line-no-fallthrough - case HostSingleton: { - if (enableHostSingletons && supportsSingletons) { - if (flags & Update) { - const previousWork = finishedWork.alternate; - if (previousWork === null) { - const singleton = finishedWork.stateNode; - const props = finishedWork.memoizedProps; - // This was a new mount, we need to clear and set initial properties - clearSingleton(singleton); - acquireSingletonInstance( - finishedWork.type, - props, - singleton, - finishedWork, - ); - } - } - } - } - // eslint-disable-next-line-no-fallthrough - case HostComponent: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Ref) { - if (current !== null) { - safelyDetachRef(current, current.return); - } - } - if (supportsMutation) { - // TODO: ContentReset gets cleared by the children during the commit - // phase. This is a refactor hazard because it means we must read - // flags the flags after `commitReconciliationEffects` has already run; - // the order matters. We should refactor so that ContentReset does not - // rely on mutating the flag during commit. Like by setting a flag - // during the render phase instead. - if (finishedWork.flags & ContentReset) { - const instance: Instance = finishedWork.stateNode; - try { - resetTextContent(instance); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - - if (flags & Update) { - const instance: Instance = finishedWork.stateNode; - if (instance != null) { - // Commit the work prepared earlier. - const newProps = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - const oldProps = - current !== null ? current.memoizedProps : newProps; - const type = finishedWork.type; - // TODO: Type the updateQueue to be specific to host components. - const updatePayload: null | UpdatePayload = (finishedWork.updateQueue: any); - finishedWork.updateQueue = null; - if (updatePayload !== null) { - try { - commitUpdate( - instance, - updatePayload, - type, - oldProps, - newProps, - finishedWork, - ); - } catch (error) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error, - ); - } - } - } - } - } - return; - } - case HostText: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Update) { - if (supportsMutation) { - if (finishedWork.stateNode === null) { - throw new Error( - 'This should have a text node initialized. This error is likely ' + - 'caused by a bug in React. Please file an issue.', - ); - } - - const textInstance: TextInstance = finishedWork.stateNode; - const newText: string = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - const oldText: string = - current !== null ? current.memoizedProps : newText; - - try { - commitTextUpdate(textInstance, oldText, newText); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } - return; - } - case HostRoot: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Update) { - if (supportsMutation && supportsHydration) { - if (current !== null) { - const prevRootState: RootState = current.memoizedState; - if (prevRootState.isDehydrated) { - try { - commitHydratedContainer(root.containerInfo); - } catch (error) { - captureCommitPhaseError( - finishedWork, - finishedWork.return, - error, - ); - } - } - } - } - if (supportsPersistence) { - const containerInfo = root.containerInfo; - const pendingChildren = root.pendingChildren; - try { - replaceContainerChildren(containerInfo, pendingChildren); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } - return; - } - case HostPortal: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Update) { - if (supportsPersistence) { - const portal = finishedWork.stateNode; - const containerInfo = portal.containerInfo; - const pendingChildren = portal.pendingChildren; - try { - replaceContainerChildren(containerInfo, pendingChildren); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - } - return; - } - case SuspenseComponent: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - const offscreenFiber: Fiber = (finishedWork.child: any); - - if (offscreenFiber.flags & Visibility) { - const newState: OffscreenState | null = offscreenFiber.memoizedState; - const isHidden = newState !== null; - if (isHidden) { - const wasHidden = - offscreenFiber.alternate !== null && - offscreenFiber.alternate.memoizedState !== null; - if (!wasHidden) { - // TODO: Move to passive phase - markCommitTimeOfFallback(); - } - } - } - - if (flags & Update) { - try { - commitSuspenseCallback(finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - const wakeables: Set | null = (finishedWork.updateQueue: any); - if (wakeables !== null) { - finishedWork.updateQueue = null; - attachSuspenseRetryListeners(finishedWork, wakeables); - } - } - return; - } - case OffscreenComponent: { - if (flags & Ref) { - if (current !== null) { - safelyDetachRef(current, current.return); - } - } - - const newState: OffscreenState | null = finishedWork.memoizedState; - const isHidden = newState !== null; - const wasHidden = current !== null && current.memoizedState !== null; - - if (finishedWork.mode & ConcurrentMode) { - // Before committing the children, track on the stack whether this - // offscreen subtree was already hidden, so that we don't unmount the - // effects again. - const prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; - const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || isHidden; - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden; - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; - offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; - } else { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - } - - commitReconciliationEffects(finishedWork); - // TODO: Add explicit effect flag to set _current. - finishedWork.stateNode._current = finishedWork; - - if (flags & Visibility) { - const offscreenInstance: OffscreenInstance = finishedWork.stateNode; - - // Track the current state on the Offscreen instance so we can - // read it during an event - if (isHidden) { - offscreenInstance._visibility &= ~OffscreenVisible; - } else { - offscreenInstance._visibility |= OffscreenVisible; - } - - if (isHidden) { - const isUpdate = current !== null; - const wasHiddenByAncestorOffscreen = - offscreenSubtreeIsHidden || offscreenSubtreeWasHidden; - // Only trigger disapper layout effects if: - // - This is an update, not first mount. - // - This Offscreen was not hidden before. - // - Ancestor Offscreen was not hidden in previous commit. - if (isUpdate && !wasHidden && !wasHiddenByAncestorOffscreen) { - if ((finishedWork.mode & ConcurrentMode) !== NoMode) { - // Disappear the layout effects of all the children - recursivelyTraverseDisappearLayoutEffects(finishedWork); - } - } - } else { - if (wasHidden) { - // TODO: Move re-appear call here for symmetry? - } - } - - // Offscreen with manual mode manages visibility manually. - if (supportsMutation && !isOffscreenManual(finishedWork)) { - // TODO: This needs to run whenever there's an insertion or update - // inside a hidden Offscreen tree. - hideOrUnhideAllChildren(finishedWork, isHidden); - } - } - - // TODO: Move to passive phase - if (flags & Update) { - const offscreenQueue: OffscreenQueue | null = (finishedWork.updateQueue: any); - if (offscreenQueue !== null) { - const wakeables = offscreenQueue.wakeables; - if (wakeables !== null) { - offscreenQueue.wakeables = null; - attachSuspenseRetryListeners(finishedWork, wakeables); - } - } - } - return; - } - case SuspenseListComponent: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - if (flags & Update) { - const wakeables: Set | null = (finishedWork.updateQueue: any); - if (wakeables !== null) { - finishedWork.updateQueue = null; - attachSuspenseRetryListeners(finishedWork, wakeables); - } - } - return; - } - case ScopeComponent: { - if (enableScopeAPI) { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - // TODO: This is a temporary solution that allowed us to transition away - // from React Flare on www. - if (flags & Ref) { - if (current !== null) { - safelyDetachRef(finishedWork, finishedWork.return); - } - safelyAttachRef(finishedWork, finishedWork.return); - } - if (flags & Update) { - const scopeInstance = finishedWork.stateNode; - prepareScopeUpdate(scopeInstance, finishedWork); - } - } - return; - } - default: { - recursivelyTraverseMutationEffects(root, finishedWork, lanes); - commitReconciliationEffects(finishedWork); - - return; - } - } -} -function commitReconciliationEffects(finishedWork: Fiber) { - // Placement effects (insertions, reorders) can be scheduled on any fiber - // type. They needs to happen after the children effects have fired, but - // before the effects on this fiber have fired. - const flags = finishedWork.flags; - if (flags & Placement) { - try { - commitPlacement(finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - // Clear the "placement" from effect tag so that we know that this is - // inserted, before any life-cycles like componentDidMount gets called. - // TODO: findDOMNode doesn't rely on this any more but isMounted does - // and isMounted is deprecated anyway so we should be able to kill this. - finishedWork.flags &= ~Placement; - } - if (flags & Hydrating) { - finishedWork.flags &= ~Hydrating; - } -} - -export function commitLayoutEffects( - finishedWork: Fiber, - root: FiberRoot, - committedLanes: Lanes, -): void { - inProgressLanes = committedLanes; - inProgressRoot = root; - - const current = finishedWork.alternate; - commitLayoutEffectOnFiber(root, current, finishedWork, committedLanes); - - inProgressLanes = null; - inProgressRoot = null; -} - -function recursivelyTraverseLayoutEffects( - root: FiberRoot, - parentFiber: Fiber, - lanes: Lanes, -) { - const prevDebugFiber = getCurrentDebugFiberInDEV(); - if (parentFiber.subtreeFlags & LayoutMask) { - let child = parentFiber.child; - while (child !== null) { - setCurrentDebugFiberInDEV(child); - const current = child.alternate; - commitLayoutEffectOnFiber(root, current, child, lanes); - child = child.sibling; - } - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -export function disappearLayoutEffects(finishedWork: Fiber) { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case MemoComponent: - case SimpleMemoComponent: { - // TODO (Offscreen) Check: flags & LayoutStatic - if (shouldProfile(finishedWork)) { - try { - startLayoutEffectTimer(); - commitHookEffectListUnmount( - HookLayout, - finishedWork, - finishedWork.return, - ); - } finally { - recordLayoutEffectDuration(finishedWork); - } - } else { - commitHookEffectListUnmount( - HookLayout, - finishedWork, - finishedWork.return, - ); - } - - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - } - case ClassComponent: { - // TODO (Offscreen) Check: flags & RefStatic - safelyDetachRef(finishedWork, finishedWork.return); - - const instance = finishedWork.stateNode; - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount( - finishedWork, - finishedWork.return, - instance, - ); - } - - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - } - case HostResource: - case HostSingleton: - case HostComponent: { - // TODO (Offscreen) Check: flags & RefStatic - safelyDetachRef(finishedWork, finishedWork.return); - - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - } - case OffscreenComponent: { - // TODO (Offscreen) Check: flags & RefStatic - safelyDetachRef(finishedWork, finishedWork.return); - - const isHidden = finishedWork.memoizedState !== null; - if (isHidden) { - // Nested Offscreen tree is already hidden. Don't disappear - // its effects. - } else { - recursivelyTraverseDisappearLayoutEffects(finishedWork); - } - break; - } - default: { - recursivelyTraverseDisappearLayoutEffects(finishedWork); - break; - } - } -} - -function recursivelyTraverseDisappearLayoutEffects(parentFiber: Fiber) { - // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) - let child = parentFiber.child; - while (child !== null) { - disappearLayoutEffects(child); - child = child.sibling; - } -} - -export function reappearLayoutEffects( - finishedRoot: FiberRoot, - current: Fiber | null, - finishedWork: Fiber, - // This function visits both newly finished work and nodes that were re-used - // from a previously committed tree. We cannot check non-static flags if the - // node was reused. - includeWorkInProgressEffects: boolean, -) { - // Turn on layout effects in a tree that previously disappeared. - const flags = finishedWork.flags; - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - // TODO: Check flags & LayoutStatic - commitHookLayoutEffects(finishedWork, HookLayout); - break; - } - case ClassComponent: { - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - - // TODO: Check for LayoutStatic flag - const instance = finishedWork.stateNode; - if (typeof instance.componentDidMount === 'function') { - try { - instance.componentDidMount(); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } - - // Commit any callbacks that would have fired while the component - // was hidden. - const updateQueue: UpdateQueue | null = (finishedWork.updateQueue: any); - if (updateQueue !== null) { - commitHiddenCallbacks(updateQueue, instance); - } - - // If this is newly finished work, check for setState callbacks - if (includeWorkInProgressEffects && flags & Callback) { - commitClassCallbacks(finishedWork); - } - - // TODO: Check flags & RefStatic - safelyAttachRef(finishedWork, finishedWork.return); - break; - } - // Unlike commitLayoutEffectsOnFiber, we don't need to handle HostRoot - // because this function only visits nodes that are inside an - // Offscreen fiber. - // case HostRoot: { - // ... - // } - case HostResource: - case HostSingleton: - case HostComponent: { - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - - // Renderers may schedule work to be done after host components are mounted - // (eg DOM renderer may schedule auto-focus for inputs and form controls). - // These effects should only be committed when components are first mounted, - // aka when there is no current/alternate. - if (includeWorkInProgressEffects && current === null && flags & Update) { - commitHostComponentMount(finishedWork); - } - - // TODO: Check flags & Ref - safelyAttachRef(finishedWork, finishedWork.return); - break; - } - case Profiler: { - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - // TODO: Figure out how Profiler updates should work with Offscreen - if (includeWorkInProgressEffects && flags & Update) { - commitProfilerUpdate(finishedWork, current); - } - break; - } - case SuspenseComponent: { - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - - // TODO: Figure out how Suspense hydration callbacks should work - // with Offscreen. - if (includeWorkInProgressEffects && flags & Update) { - commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); - } - break; - } - case OffscreenComponent: { - const offscreenState: OffscreenState = finishedWork.memoizedState; - const isHidden = offscreenState !== null; - if (isHidden) { - // Nested Offscreen tree is still hidden. Don't re-appear its effects. - } else { - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - } - // TODO: Check flags & Ref - safelyAttachRef(finishedWork, finishedWork.return); - break; - } - default: { - recursivelyTraverseReappearLayoutEffects( - finishedRoot, - finishedWork, - includeWorkInProgressEffects, - ); - break; - } - } -} - -function recursivelyTraverseReappearLayoutEffects( - finishedRoot: FiberRoot, - parentFiber: Fiber, - includeWorkInProgressEffects: boolean, -) { - // This function visits both newly finished work and nodes that were re-used - // from a previously committed tree. We cannot check non-static flags if the - // node was reused. - const childShouldIncludeWorkInProgressEffects = - includeWorkInProgressEffects && - (parentFiber.subtreeFlags & LayoutMask) !== NoFlags; - - // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) - const prevDebugFiber = getCurrentDebugFiberInDEV(); - let child = parentFiber.child; - while (child !== null) { - const current = child.alternate; - reappearLayoutEffects( - finishedRoot, - current, - child, - childShouldIncludeWorkInProgressEffects, - ); - child = child.sibling; - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -function commitHookPassiveMountEffects( - finishedWork: Fiber, - hookFlags: HookFlags, -) { - if (shouldProfile(finishedWork)) { - startPassiveEffectTimer(); - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - recordPassiveEffectDuration(finishedWork); - } else { - try { - commitHookEffectListMount(hookFlags, finishedWork); - } catch (error) { - captureCommitPhaseError(finishedWork, finishedWork.return, error); - } - } -} - -function commitOffscreenPassiveMountEffects( - current: Fiber | null, - finishedWork: Fiber, - instance: OffscreenInstance, -) { - if (enableCache) { - let previousCache: Cache | null = null; - if ( - current !== null && - current.memoizedState !== null && - current.memoizedState.cachePool !== null - ) { - previousCache = current.memoizedState.cachePool.pool; - } - let nextCache: Cache | null = null; - if ( - finishedWork.memoizedState !== null && - finishedWork.memoizedState.cachePool !== null - ) { - nextCache = finishedWork.memoizedState.cachePool.pool; - } - // Retain/release the cache used for pending (suspended) nodes. - // Note that this is only reached in the non-suspended/visible case: - // when the content is suspended/hidden, the retain/release occurs - // via the parent Suspense component (see case above). - if (nextCache !== previousCache) { - if (nextCache != null) { - retainCache(nextCache); - } - if (previousCache != null) { - releaseCache(previousCache); - } - } - } - - if (enableTransitionTracing) { - // TODO: Pre-rendering should not be counted as part of a transition. We - // may add separate logs for pre-rendering, but it's not part of the - // primary metrics. - const offscreenState: OffscreenState = finishedWork.memoizedState; - const queue: OffscreenQueue | null = (finishedWork.updateQueue: any); - - const isHidden = offscreenState !== null; - if (queue !== null) { - if (isHidden) { - const transitions = queue.transitions; - if (transitions !== null) { - transitions.forEach(transition => { - // Add all the transitions saved in the update queue during - // the render phase (ie the transitions associated with this boundary) - // into the transitions set. - if (instance._transitions === null) { - instance._transitions = new Set(); - } - instance._transitions.add(transition); - }); - } - - const markerInstances = queue.markerInstances; - if (markerInstances !== null) { - markerInstances.forEach(markerInstance => { - const markerTransitions = markerInstance.transitions; - // There should only be a few tracing marker transitions because - // they should be only associated with the transition that - // caused them - if (markerTransitions !== null) { - markerTransitions.forEach(transition => { - if (instance._transitions === null) { - instance._transitions = new Set(); - } else if (instance._transitions.has(transition)) { - if (markerInstance.pendingBoundaries === null) { - markerInstance.pendingBoundaries = new Map(); - } - if (instance._pendingMarkers === null) { - instance._pendingMarkers = new Set(); - } - - instance._pendingMarkers.add(markerInstance); - } - }); - } - }); - } - } - - finishedWork.updateQueue = null; - } - - commitTransitionProgress(finishedWork); - - // TODO: Refactor this into an if/else branch - if (!isHidden) { - instance._transitions = null; - instance._pendingMarkers = null; - } - } -} - -function commitCachePassiveMountEffect( - current: Fiber | null, - finishedWork: Fiber, -) { - if (enableCache) { - let previousCache: Cache | null = null; - if (finishedWork.alternate !== null) { - previousCache = finishedWork.alternate.memoizedState.cache; - } - const nextCache = finishedWork.memoizedState.cache; - // Retain/release the cache. In theory the cache component - // could be "borrowing" a cache instance owned by some parent, - // in which case we could avoid retaining/releasing. But it - // is non-trivial to determine when that is the case, so we - // always retain/release. - if (nextCache !== previousCache) { - retainCache(nextCache); - if (previousCache != null) { - releaseCache(previousCache); - } - } - } -} - -function commitTracingMarkerPassiveMountEffect(finishedWork: Fiber) { - // Get the transitions that were initiatized during the render - // and add a start transition callback for each of them - // We will only call this on initial mount of the tracing marker - // only if there are no suspense children - const instance = finishedWork.stateNode; - if (instance.transitions !== null && instance.pendingBoundaries === null) { - addMarkerCompleteCallbackToPendingTransition( - finishedWork.memoizedProps.name, - instance.transitions, - ); - instance.transitions = null; - instance.pendingBoundaries = null; - instance.aborts = null; - instance.name = null; - } -} - -export function commitPassiveMountEffects( - root: FiberRoot, - finishedWork: Fiber, - committedLanes: Lanes, - committedTransitions: Array | null, -): void { - setCurrentDebugFiberInDEV(finishedWork); - commitPassiveMountOnFiber( - root, - finishedWork, - committedLanes, - committedTransitions, - ); - resetCurrentDebugFiberInDEV(); -} - -function recursivelyTraversePassiveMountEffects( - root: FiberRoot, - parentFiber: Fiber, - committedLanes: Lanes, - committedTransitions: Array | null, -) { - const prevDebugFiber = getCurrentDebugFiberInDEV(); - if (parentFiber.subtreeFlags & PassiveMask) { - let child = parentFiber.child; - while (child !== null) { - setCurrentDebugFiberInDEV(child); - commitPassiveMountOnFiber( - root, - child, - committedLanes, - committedTransitions, - ); - child = child.sibling; - } - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -function commitPassiveMountOnFiber( - finishedRoot: FiberRoot, - finishedWork: Fiber, - committedLanes: Lanes, - committedTransitions: Array | null, -): void { - // When updating this function, also update reconnectPassiveEffects, which does - // most of the same things when an offscreen tree goes from hidden -> visible, - // or when toggling effects inside a hidden tree. - const flags = finishedWork.flags; - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - if (flags & Passive) { - commitHookPassiveMountEffects( - finishedWork, - HookPassive | HookHasEffect, - ); - } - break; - } - case HostRoot: { - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - if (flags & Passive) { - if (enableCache) { - let previousCache: Cache | null = null; - if (finishedWork.alternate !== null) { - previousCache = finishedWork.alternate.memoizedState.cache; - } - const nextCache = finishedWork.memoizedState.cache; - // Retain/release the root cache. - // Note that on initial mount, previousCache and nextCache will be the same - // and this retain won't occur. To counter this, we instead retain the HostRoot's - // initial cache when creating the root itself (see createFiberRoot() in - // ReactFiberRoot.js). Subsequent updates that change the cache are reflected - // here, such that previous/next caches are retained correctly. - if (nextCache !== previousCache) { - retainCache(nextCache); - if (previousCache != null) { - releaseCache(previousCache); - } - } - } - - if (enableTransitionTracing) { - // Get the transitions that were initiatized during the render - // and add a start transition callback for each of them - const root: FiberRoot = finishedWork.stateNode; - const incompleteTransitions = root.incompleteTransitions; - // Initial render - if (committedTransitions !== null) { - committedTransitions.forEach(transition => { - addTransitionStartCallbackToPendingTransition(transition); - }); - - clearTransitionsForLanes(finishedRoot, committedLanes); - } - - incompleteTransitions.forEach((markerInstance, transition) => { - const pendingBoundaries = markerInstance.pendingBoundaries; - if (pendingBoundaries === null || pendingBoundaries.size === 0) { - if (markerInstance.aborts === null) { - addTransitionCompleteCallbackToPendingTransition(transition); - } - incompleteTransitions.delete(transition); - } - }); - - clearTransitionsForLanes(finishedRoot, committedLanes); - } - } - break; - } - case LegacyHiddenComponent: { - if (enableLegacyHidden) { - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - - if (flags & Passive) { - const current = finishedWork.alternate; - const instance: OffscreenInstance = finishedWork.stateNode; - commitOffscreenPassiveMountEffects(current, finishedWork, instance); - } - } - break; - } - case OffscreenComponent: { - // TODO: Pass `current` as argument to this function - const instance: OffscreenInstance = finishedWork.stateNode; - const nextState: OffscreenState | null = finishedWork.memoizedState; - - const isHidden = nextState !== null; - - if (isHidden) { - if (instance._visibility & OffscreenPassiveEffectsConnected) { - // The effects are currently connected. Update them. - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - } else { - if (finishedWork.mode & ConcurrentMode) { - // The effects are currently disconnected. Since the tree is hidden, - // don't connect them. This also applies to the initial render. - if (enableCache || enableTransitionTracing) { - // "Atomic" effects are ones that need to fire on every commit, - // even during pre-rendering. An example is updating the reference - // count on cache instances. - recursivelyTraverseAtomicPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - } - } else { - // Legacy Mode: Fire the effects even if the tree is hidden. - instance._visibility |= OffscreenPassiveEffectsConnected; - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - } - } - } else { - // Tree is visible - if (instance._visibility & OffscreenPassiveEffectsConnected) { - // The effects are currently connected. Update them. - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - } else { - // The effects are currently disconnected. Reconnect them, while also - // firing effects inside newly mounted trees. This also applies to - // the initial render. - instance._visibility |= OffscreenPassiveEffectsConnected; - - const includeWorkInProgressEffects = - (finishedWork.subtreeFlags & PassiveMask) !== NoFlags; - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - } - } - - if (flags & Passive) { - const current = finishedWork.alternate; - commitOffscreenPassiveMountEffects(current, finishedWork, instance); - } - break; - } - case CacheComponent: { - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - if (flags & Passive) { - // TODO: Pass `current` as argument to this function - const current = finishedWork.alternate; - commitCachePassiveMountEffect(current, finishedWork); - } - break; - } - case TracingMarkerComponent: { - if (enableTransitionTracing) { - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - if (flags & Passive) { - commitTracingMarkerPassiveMountEffect(finishedWork); - } - break; - } - // Intentional fallthrough to next branch - } - // eslint-disable-next-line-no-fallthrough - default: { - recursivelyTraversePassiveMountEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - break; - } - } -} - -function recursivelyTraverseReconnectPassiveEffects( - finishedRoot: FiberRoot, - parentFiber: Fiber, - committedLanes: Lanes, - committedTransitions: Array | null, - includeWorkInProgressEffects: boolean, -) { - // This function visits both newly finished work and nodes that were re-used - // from a previously committed tree. We cannot check non-static flags if the - // node was reused. - const childShouldIncludeWorkInProgressEffects = - includeWorkInProgressEffects && - (parentFiber.subtreeFlags & PassiveMask) !== NoFlags; - - // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) - const prevDebugFiber = getCurrentDebugFiberInDEV(); - let child = parentFiber.child; - while (child !== null) { - reconnectPassiveEffects( - finishedRoot, - child, - committedLanes, - committedTransitions, - childShouldIncludeWorkInProgressEffects, - ); - child = child.sibling; - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -export function reconnectPassiveEffects( - finishedRoot: FiberRoot, - finishedWork: Fiber, - committedLanes: Lanes, - committedTransitions: Array | null, - // This function visits both newly finished work and nodes that were re-used - // from a previously committed tree. We cannot check non-static flags if the - // node was reused. - includeWorkInProgressEffects: boolean, -) { - const flags = finishedWork.flags; - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - // TODO: Check for PassiveStatic flag - commitHookPassiveMountEffects(finishedWork, HookPassive); - break; - } - // Unlike commitPassiveMountOnFiber, we don't need to handle HostRoot - // because this function only visits nodes that are inside an - // Offscreen fiber. - // case HostRoot: { - // ... - // } - case LegacyHiddenComponent: { - if (enableLegacyHidden) { - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - - if (includeWorkInProgressEffects && flags & Passive) { - // TODO: Pass `current` as argument to this function - const current: Fiber | null = finishedWork.alternate; - const instance: OffscreenInstance = finishedWork.stateNode; - commitOffscreenPassiveMountEffects(current, finishedWork, instance); - } - } - break; - } - case OffscreenComponent: { - const instance: OffscreenInstance = finishedWork.stateNode; - const nextState: OffscreenState | null = finishedWork.memoizedState; - - const isHidden = nextState !== null; - - if (isHidden) { - if (instance._visibility & OffscreenPassiveEffectsConnected) { - // The effects are currently connected. Update them. - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - } else { - if (finishedWork.mode & ConcurrentMode) { - // The effects are currently disconnected. Since the tree is hidden, - // don't connect them. This also applies to the initial render. - if (enableCache || enableTransitionTracing) { - // "Atomic" effects are ones that need to fire on every commit, - // even during pre-rendering. An example is updating the reference - // count on cache instances. - recursivelyTraverseAtomicPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - } - } else { - // Legacy Mode: Fire the effects even if the tree is hidden. - instance._visibility |= OffscreenPassiveEffectsConnected; - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - } - } - } else { - // Tree is visible - - // Since we're already inside a reconnecting tree, it doesn't matter - // whether the effects are currently connected. In either case, we'll - // continue traversing the tree and firing all the effects. - // - // We do need to set the "connected" flag on the instance, though. - instance._visibility |= OffscreenPassiveEffectsConnected; - - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - } - - if (includeWorkInProgressEffects && flags & Passive) { - // TODO: Pass `current` as argument to this function - const current: Fiber | null = finishedWork.alternate; - commitOffscreenPassiveMountEffects(current, finishedWork, instance); - } - break; - } - case CacheComponent: { - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - if (includeWorkInProgressEffects && flags & Passive) { - // TODO: Pass `current` as argument to this function - const current = finishedWork.alternate; - commitCachePassiveMountEffect(current, finishedWork); - } - break; - } - case TracingMarkerComponent: { - if (enableTransitionTracing) { - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - if (includeWorkInProgressEffects && flags & Passive) { - commitTracingMarkerPassiveMountEffect(finishedWork); - } - break; - } - // Intentional fallthrough to next branch - } - // eslint-disable-next-line-no-fallthrough - default: { - recursivelyTraverseReconnectPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - includeWorkInProgressEffects, - ); - break; - } - } -} - -function recursivelyTraverseAtomicPassiveEffects( - finishedRoot: FiberRoot, - parentFiber: Fiber, - committedLanes: Lanes, - committedTransitions: Array | null, -) { - // "Atomic" effects are ones that need to fire on every commit, even during - // pre-rendering. We call this function when traversing a hidden tree whose - // regular effects are currently disconnected. - const prevDebugFiber = getCurrentDebugFiberInDEV(); - // TODO: Add special flag for atomic effects - if (parentFiber.subtreeFlags & PassiveMask) { - let child = parentFiber.child; - while (child !== null) { - setCurrentDebugFiberInDEV(child); - commitAtomicPassiveEffects( - finishedRoot, - child, - committedLanes, - committedTransitions, - ); - child = child.sibling; - } - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -function commitAtomicPassiveEffects( - finishedRoot: FiberRoot, - finishedWork: Fiber, - committedLanes: Lanes, - committedTransitions: Array | null, -) { - // "Atomic" effects are ones that need to fire on every commit, even during - // pre-rendering. We call this function when traversing a hidden tree whose - // regular effects are currently disconnected. - const flags = finishedWork.flags; - switch (finishedWork.tag) { - case OffscreenComponent: { - recursivelyTraverseAtomicPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - if (flags & Passive) { - // TODO: Pass `current` as argument to this function - const current = finishedWork.alternate; - const instance: OffscreenInstance = finishedWork.stateNode; - commitOffscreenPassiveMountEffects(current, finishedWork, instance); - } - break; - } - case CacheComponent: { - recursivelyTraverseAtomicPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - if (flags & Passive) { - // TODO: Pass `current` as argument to this function - const current = finishedWork.alternate; - commitCachePassiveMountEffect(current, finishedWork); - } - break; - } - // eslint-disable-next-line-no-fallthrough - default: { - recursivelyTraverseAtomicPassiveEffects( - finishedRoot, - finishedWork, - committedLanes, - committedTransitions, - ); - break; - } - } -} - -export function commitPassiveUnmountEffects(finishedWork: Fiber): void { - setCurrentDebugFiberInDEV(finishedWork); - commitPassiveUnmountOnFiber(finishedWork); - resetCurrentDebugFiberInDEV(); -} - -function detachAlternateSiblings(parentFiber: Fiber) { - if (deletedTreeCleanUpLevel >= 1) { - // A fiber was deleted from this parent fiber, but it's still part of the - // previous (alternate) parent fiber's list of children. Because children - // are a linked list, an earlier sibling that's still alive will be - // connected to the deleted fiber via its `alternate`: - // - // live fiber --alternate--> previous live fiber --sibling--> deleted - // fiber - // - // We can't disconnect `alternate` on nodes that haven't been deleted yet, - // but we can disconnect the `sibling` and `child` pointers. - - const previousFiber = parentFiber.alternate; - if (previousFiber !== null) { - let detachedChild = previousFiber.child; - if (detachedChild !== null) { - previousFiber.child = null; - do { - // $FlowFixMe[incompatible-use] found when upgrading Flow - const detachedSibling = detachedChild.sibling; - // $FlowFixMe[incompatible-use] found when upgrading Flow - detachedChild.sibling = null; - detachedChild = detachedSibling; - } while (detachedChild !== null); - } - } - } -} - -function commitHookPassiveUnmountEffects( - finishedWork: Fiber, - nearestMountedAncestor, - hookFlags: HookFlags, -) { - if (shouldProfile(finishedWork)) { - startPassiveEffectTimer(); - commitHookEffectListUnmount( - hookFlags, - finishedWork, - nearestMountedAncestor, - ); - recordPassiveEffectDuration(finishedWork); - } else { - commitHookEffectListUnmount( - hookFlags, - finishedWork, - nearestMountedAncestor, - ); - } -} - -function recursivelyTraversePassiveUnmountEffects(parentFiber: Fiber): void { - // Deletions effects can be scheduled on any fiber type. They need to happen - // before the children effects have fired. - const deletions = parentFiber.deletions; - - if ((parentFiber.flags & ChildDeletion) !== NoFlags) { - if (deletions !== null) { - for (let i = 0; i < deletions.length; i++) { - const childToDelete = deletions[i]; - // TODO: Convert this to use recursion - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber, - ); - } - } - detachAlternateSiblings(parentFiber); - } - - const prevDebugFiber = getCurrentDebugFiberInDEV(); - // TODO: Split PassiveMask into separate masks for mount and unmount? - if (parentFiber.subtreeFlags & PassiveMask) { - let child = parentFiber.child; - while (child !== null) { - setCurrentDebugFiberInDEV(child); - commitPassiveUnmountOnFiber(child); - child = child.sibling; - } - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -function commitPassiveUnmountOnFiber(finishedWork: Fiber): void { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - recursivelyTraversePassiveUnmountEffects(finishedWork); - if (finishedWork.flags & Passive) { - commitHookPassiveUnmountEffects( - finishedWork, - finishedWork.return, - HookPassive | HookHasEffect, - ); - } - break; - } - case OffscreenComponent: { - const instance: OffscreenInstance = finishedWork.stateNode; - const nextState: OffscreenState | null = finishedWork.memoizedState; - - const isHidden = nextState !== null; - - if ( - isHidden && - instance._visibility & OffscreenPassiveEffectsConnected && - // For backwards compatibility, don't unmount when a tree suspends. In - // the future we may change this to unmount after a delay. - (finishedWork.return === null || - finishedWork.return.tag !== SuspenseComponent) - ) { - // The effects are currently connected. Disconnect them. - // TODO: Add option or heuristic to delay before disconnecting the - // effects. Then if the tree reappears before the delay has elapsed, we - // can skip toggling the effects entirely. - instance._visibility &= ~OffscreenPassiveEffectsConnected; - recursivelyTraverseDisconnectPassiveEffects(finishedWork); - } else { - recursivelyTraversePassiveUnmountEffects(finishedWork); - } - - break; - } - default: { - recursivelyTraversePassiveUnmountEffects(finishedWork); - break; - } - } -} - -function recursivelyTraverseDisconnectPassiveEffects(parentFiber: Fiber): void { - // Deletions effects can be scheduled on any fiber type. They need to happen - // before the children effects have fired. - const deletions = parentFiber.deletions; - - if ((parentFiber.flags & ChildDeletion) !== NoFlags) { - if (deletions !== null) { - for (let i = 0; i < deletions.length; i++) { - const childToDelete = deletions[i]; - // TODO: Convert this to use recursion - nextEffect = childToDelete; - commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - childToDelete, - parentFiber, - ); - } - } - detachAlternateSiblings(parentFiber); - } - - const prevDebugFiber = getCurrentDebugFiberInDEV(); - // TODO: Check PassiveStatic flag - let child = parentFiber.child; - while (child !== null) { - setCurrentDebugFiberInDEV(child); - disconnectPassiveEffect(child); - child = child.sibling; - } - setCurrentDebugFiberInDEV(prevDebugFiber); -} - -export function disconnectPassiveEffect(finishedWork: Fiber): void { - switch (finishedWork.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - // TODO: Check PassiveStatic flag - commitHookPassiveUnmountEffects( - finishedWork, - finishedWork.return, - HookPassive, - ); - // When disconnecting passive effects, we fire the effects in the same - // order as during a deletiong: parent before child - recursivelyTraverseDisconnectPassiveEffects(finishedWork); - break; - } - case OffscreenComponent: { - const instance: OffscreenInstance = finishedWork.stateNode; - if (instance._visibility & OffscreenPassiveEffectsConnected) { - instance._visibility &= ~OffscreenPassiveEffectsConnected; - recursivelyTraverseDisconnectPassiveEffects(finishedWork); - } else { - // The effects are already disconnected. - } - break; - } - default: { - recursivelyTraverseDisconnectPassiveEffects(finishedWork); - break; - } - } -} - -function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( - deletedSubtreeRoot: Fiber, - nearestMountedAncestor: Fiber | null, -) { - while (nextEffect !== null) { - const fiber = nextEffect; - - // Deletion effects fire in parent -> child order - // TODO: Check if fiber has a PassiveStatic flag - setCurrentDebugFiberInDEV(fiber); - commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); - resetCurrentDebugFiberInDEV(); - - const child = fiber.child; - // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we - // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) - if (child !== null) { - child.return = fiber; - nextEffect = child; - } else { - commitPassiveUnmountEffectsInsideOfDeletedTree_complete( - deletedSubtreeRoot, - ); - } - } -} - -function commitPassiveUnmountEffectsInsideOfDeletedTree_complete( - deletedSubtreeRoot: Fiber, -) { - while (nextEffect !== null) { - const fiber = nextEffect; - const sibling = fiber.sibling; - const returnFiber = fiber.return; - - if (deletedTreeCleanUpLevel >= 2) { - // Recursively traverse the entire deleted tree and clean up fiber fields. - // This is more aggressive than ideal, and the long term goal is to only - // have to detach the deleted tree at the root. - detachFiberAfterEffects(fiber); - if (fiber === deletedSubtreeRoot) { - nextEffect = null; - return; - } - } else { - // This is the default branch (level 0). We do not recursively clear all - // the fiber fields. Only the root of the deleted subtree. - if (fiber === deletedSubtreeRoot) { - detachFiberAfterEffects(fiber); - nextEffect = null; - return; - } - } - - if (sibling !== null) { - sibling.return = returnFiber; - nextEffect = sibling; - return; - } - - nextEffect = returnFiber; - } -} - -function commitPassiveUnmountInsideDeletedTreeOnFiber( - current: Fiber, - nearestMountedAncestor: Fiber | null, -): void { - switch (current.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - commitHookPassiveUnmountEffects( - current, - nearestMountedAncestor, - HookPassive, - ); - break; - } - // TODO: run passive unmount effects when unmounting a root. - // Because passive unmount effects are not currently run, - // the cache instance owned by the root will never be freed. - // When effects are run, the cache should be freed here: - // case HostRoot: { - // if (enableCache) { - // const cache = current.memoizedState.cache; - // releaseCache(cache); - // } - // break; - // } - case LegacyHiddenComponent: - case OffscreenComponent: { - if (enableCache) { - if ( - current.memoizedState !== null && - current.memoizedState.cachePool !== null - ) { - const cache: Cache = current.memoizedState.cachePool.pool; - // Retain/release the cache used for pending (suspended) nodes. - // Note that this is only reached in the non-suspended/visible case: - // when the content is suspended/hidden, the retain/release occurs - // via the parent Suspense component (see case above). - if (cache != null) { - retainCache(cache); - } - } - } - break; - } - case SuspenseComponent: { - if (enableTransitionTracing) { - // We need to mark this fiber's parents as deleted - const offscreenFiber: Fiber = (current.child: any); - const instance: OffscreenInstance = offscreenFiber.stateNode; - const transitions = instance._transitions; - if (transitions !== null) { - const abortReason = { - reason: 'suspense', - name: current.memoizedProps.unstable_name || null, - }; - if ( - current.memoizedState === null || - current.memoizedState.dehydrated === null - ) { - abortParentMarkerTransitionsForDeletedFiber( - offscreenFiber, - abortReason, - transitions, - instance, - true, - ); - - if (nearestMountedAncestor !== null) { - abortParentMarkerTransitionsForDeletedFiber( - nearestMountedAncestor, - abortReason, - transitions, - instance, - false, - ); - } - } - } - } - break; - } - case CacheComponent: { - if (enableCache) { - const cache = current.memoizedState.cache; - releaseCache(cache); - } - break; - } - case TracingMarkerComponent: { - if (enableTransitionTracing) { - // We need to mark this fiber's parents as deleted - const instance: TracingMarkerInstance = current.stateNode; - const transitions = instance.transitions; - if (transitions !== null) { - const abortReason = { - reason: 'marker', - name: current.memoizedProps.name, - }; - abortParentMarkerTransitionsForDeletedFiber( - current, - abortReason, - transitions, - null, - true, - ); - - if (nearestMountedAncestor !== null) { - abortParentMarkerTransitionsForDeletedFiber( - nearestMountedAncestor, - abortReason, - transitions, - null, - false, - ); - } - } - } - break; - } - } -} - -function invokeLayoutEffectMountInDEV(fiber: Fiber): void { - if (__DEV__) { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListMount(HookLayout | HookHasEffect, fiber); - } catch (error) { - captureCommitPhaseError(fiber, fiber.return, error); - } - break; - } - case ClassComponent: { - const instance = fiber.stateNode; - try { - instance.componentDidMount(); - } catch (error) { - captureCommitPhaseError(fiber, fiber.return, error); - } - break; - } - } - } -} - -function invokePassiveEffectMountInDEV(fiber: Fiber): void { - if (__DEV__) { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListMount(HookPassive | HookHasEffect, fiber); - } catch (error) { - captureCommitPhaseError(fiber, fiber.return, error); - } - break; - } - } - } -} - -function invokeLayoutEffectUnmountInDEV(fiber: Fiber): void { - if (__DEV__) { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListUnmount( - HookLayout | HookHasEffect, - fiber, - fiber.return, - ); - } catch (error) { - captureCommitPhaseError(fiber, fiber.return, error); - } - break; - } - case ClassComponent: { - const instance = fiber.stateNode; - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(fiber, fiber.return, instance); - } - break; - } - } - } -} - -function invokePassiveEffectUnmountInDEV(fiber: Fiber): void { - if (__DEV__) { - // We don't need to re-check StrictEffectsMode here. - // This function is only called if that check has already passed. - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - try { - commitHookEffectListUnmount( - HookPassive | HookHasEffect, - fiber, - fiber.return, - ); - } catch (error) { - captureCommitPhaseError(fiber, fiber.return, error); - } - } - } - } -} - -export { - commitPlacement, - commitAttachRef, - invokeLayoutEffectMountInDEV, - invokeLayoutEffectUnmountInDEV, - invokePassiveEffectMountInDEV, - invokePassiveEffectUnmountInDEV, -}; diff --git a/packages/react-reconciler/src/ReactFiberCompleteWork.new.js b/packages/react-reconciler/src/ReactFiberCompleteWork.new.js deleted file mode 100644 index e091bfbbb81d6..0000000000000 --- a/packages/react-reconciler/src/ReactFiberCompleteWork.new.js +++ /dev/null @@ -1,1686 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {RootState} from './ReactFiberRoot.new'; -import type {Lanes, Lane} from './ReactFiberLane.new'; -import type { - ReactScopeInstance, - ReactContext, - Wakeable, -} from 'shared/ReactTypes'; -import type { - Instance, - Type, - Props, - Container, - ChildSet, -} from './ReactFiberHostConfig'; -import type { - SuspenseState, - SuspenseListRenderState, -} from './ReactFiberSuspenseComponent.new'; -import {isOffscreenManual} from './ReactFiberOffscreenComponent'; -import type {OffscreenState} from './ReactFiberOffscreenComponent'; -import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new'; -import type {Cache} from './ReactFiberCacheComponent.new'; -import { - enableLegacyHidden, - enableHostSingletons, - enableSuspenseCallback, - enableScopeAPI, - enableProfilerTimer, - enableCache, - enableTransitionTracing, - enableFloat, -} from 'shared/ReactFeatureFlags'; - -import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.new'; - -import {now} from './Scheduler'; - -import { - IndeterminateComponent, - FunctionComponent, - ClassComponent, - HostRoot, - HostComponent, - HostResource, - HostSingleton, - HostText, - HostPortal, - ContextProvider, - ContextConsumer, - ForwardRef, - Fragment, - Mode, - Profiler, - SuspenseComponent, - SuspenseListComponent, - MemoComponent, - SimpleMemoComponent, - LazyComponent, - IncompleteClassComponent, - ScopeComponent, - OffscreenComponent, - LegacyHiddenComponent, - CacheComponent, - TracingMarkerComponent, -} from './ReactWorkTags'; -import {NoMode, ConcurrentMode, ProfileMode} from './ReactTypeOfMode'; -import { - Ref, - RefStatic, - Placement, - Update, - Visibility, - NoFlags, - DidCapture, - Snapshot, - ChildDeletion, - StaticMask, - MutationMask, - Passive, - Incomplete, - ShouldCapture, - ForceClientRender, -} from './ReactFiberFlags'; - -import { - createInstance, - createTextInstance, - resolveSingletonInstance, - appendInitialChild, - finalizeInitialChildren, - prepareUpdate, - supportsMutation, - supportsPersistence, - supportsResources, - supportsSingletons, - cloneInstance, - cloneHiddenInstance, - cloneHiddenTextInstance, - createContainerChildSet, - appendChildToContainerChildSet, - finalizeContainerChildren, - preparePortalMount, - prepareScopeUpdate, -} from './ReactFiberHostConfig'; -import { - getRootHostContainer, - popHostContext, - getHostContext, - popHostContainer, -} from './ReactFiberHostContext.new'; -import { - suspenseStackCursor, - popSuspenseListContext, - popSuspenseHandler, - pushSuspenseListContext, - setShallowSuspenseListContext, - ForceSuspenseFallback, - setDefaultShallowSuspenseListContext, - isBadSuspenseFallback, -} from './ReactFiberSuspenseContext.new'; -import {popHiddenContext} from './ReactFiberHiddenContext.new'; -import {findFirstSuspended} from './ReactFiberSuspenseComponent.new'; -import { - isContextProvider as isLegacyContextProvider, - popContext as popLegacyContext, - popTopLevelContextObject as popTopLevelLegacyContextObject, -} from './ReactFiberContext.new'; -import {popProvider} from './ReactFiberNewContext.new'; -import { - prepareToHydrateHostInstance, - prepareToHydrateHostTextInstance, - prepareToHydrateHostSuspenseInstance, - warnIfUnhydratedTailNodes, - popHydrationState, - resetHydrationState, - getIsHydrating, - hasUnhydratedTailNodes, - upgradeHydrationErrorsToRecoverable, -} from './ReactFiberHydrationContext.new'; -import { - renderDidSuspend, - renderDidSuspendDelayIfPossible, - renderHasNotSuspendedYet, - getRenderTargetTime, - getWorkInProgressTransitions, -} from './ReactFiberWorkLoop.new'; -import { - OffscreenLane, - SomeRetryLane, - NoLanes, - includesSomeLane, - mergeLanes, -} from './ReactFiberLane.new'; -import {resetChildFibers} from './ReactChildFiber.new'; -import {createScopeInstance} from './ReactFiberScope.new'; -import {transferActualDuration} from './ReactProfilerTimer.new'; -import {popCacheProvider} from './ReactFiberCacheComponent.new'; -import {popTreeContext} from './ReactFiberTreeContext.new'; -import {popRootTransition, popTransition} from './ReactFiberTransition.new'; -import { - popMarkerInstance, - popRootMarkerInstance, -} from './ReactFiberTracingMarkerComponent.new'; - -function markUpdate(workInProgress: Fiber) { - // Tag the fiber with an update effect. This turns a Placement into - // a PlacementAndUpdate. - workInProgress.flags |= Update; -} - -function markRef(workInProgress: Fiber) { - workInProgress.flags |= Ref | RefStatic; -} - -function hadNoMutationsEffects(current: null | Fiber, completedWork: Fiber) { - const didBailout = current !== null && current.child === completedWork.child; - if (didBailout) { - return true; - } - - if ((completedWork.flags & ChildDeletion) !== NoFlags) { - return false; - } - - // TODO: If we move the `hadNoMutationsEffects` call after `bubbleProperties` - // then we only have to check the `completedWork.subtreeFlags`. - let child = completedWork.child; - while (child !== null) { - if ( - (child.flags & MutationMask) !== NoFlags || - (child.subtreeFlags & MutationMask) !== NoFlags - ) { - return false; - } - child = child.sibling; - } - return true; -} - -let appendAllChildren; -let updateHostContainer; -let updateHostComponent; -let updateHostText; -if (supportsMutation) { - // Mutation mode - - appendAllChildren = function( - parent: Instance, - workInProgress: Fiber, - needsVisibilityToggle: boolean, - isHidden: boolean, - ) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - let node = workInProgress.child; - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText) { - appendInitialChild(parent, node.stateNode); - } else if ( - node.tag === HostPortal || - (enableHostSingletons && supportsSingletons - ? node.tag === HostSingleton - : false) - ) { - // If we have a portal child, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - // If we have a HostSingleton it will be placed independently - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === workInProgress) { - return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - while (node.sibling === null) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (node.return === null || node.return === workInProgress) { - return; - } - node = node.return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - node.sibling.return = node.return; - node = node.sibling; - } - }; - - updateHostContainer = function(current: null | Fiber, workInProgress: Fiber) { - // Noop - }; - updateHostComponent = function( - current: Fiber, - workInProgress: Fiber, - type: Type, - newProps: Props, - ) { - // If we have an alternate, that means this is an update and we need to - // schedule a side-effect to do the updates. - const oldProps = current.memoizedProps; - if (oldProps === newProps) { - // In mutation mode, this is sufficient for a bailout because - // we won't touch this node even if children changed. - return; - } - - // If we get updated because one of our children updated, we don't - // have newProps so we'll have to reuse them. - // TODO: Split the update API as separate for the props vs. children. - // Even better would be if children weren't special cased at all tho. - const instance: Instance = workInProgress.stateNode; - const currentHostContext = getHostContext(); - // TODO: Experiencing an error where oldProps is null. Suggests a host - // component is hitting the resume path. Figure out why. Possibly - // related to `hidden`. - const updatePayload = prepareUpdate( - instance, - type, - oldProps, - newProps, - currentHostContext, - ); - // TODO: Type this specific to this type of component. - workInProgress.updateQueue = (updatePayload: any); - // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. All the work is done in commitWork. - if (updatePayload) { - markUpdate(workInProgress); - } - }; - updateHostText = function( - current: Fiber, - workInProgress: Fiber, - oldText: string, - newText: string, - ) { - // If the text differs, mark it as an update. All the work in done in commitWork. - if (oldText !== newText) { - markUpdate(workInProgress); - } - }; -} else if (supportsPersistence) { - // Persistent host tree mode - - appendAllChildren = function( - parent: Instance, - workInProgress: Fiber, - needsVisibilityToggle: boolean, - isHidden: boolean, - ) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - let node = workInProgress.child; - while (node !== null) { - // eslint-disable-next-line no-labels - branches: if (node.tag === HostComponent) { - let instance = node.stateNode; - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - const props = node.memoizedProps; - const type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - appendInitialChild(parent, instance); - } else if (node.tag === HostText) { - let instance = node.stateNode; - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - const text = node.memoizedProps; - instance = cloneHiddenTextInstance(instance, text, node); - } - appendInitialChild(parent, instance); - } else if (node.tag === HostPortal) { - // If we have a portal child, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - } else if ( - node.tag === OffscreenComponent && - node.memoizedState !== null - ) { - // The children in this boundary are hidden. Toggle their visibility - // before appending. - const child = node.child; - if (child !== null) { - child.return = node; - } - appendAllChildren(parent, node, true, true); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - node = (node: Fiber); - if (node === workInProgress) { - return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - while (node.sibling === null) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (node.return === null || node.return === workInProgress) { - return; - } - node = node.return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - node.sibling.return = node.return; - node = node.sibling; - } - }; - - // An unfortunate fork of appendAllChildren because we have two different parent types. - const appendAllChildrenToContainer = function( - containerChildSet: ChildSet, - workInProgress: Fiber, - needsVisibilityToggle: boolean, - isHidden: boolean, - ) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - let node = workInProgress.child; - while (node !== null) { - // eslint-disable-next-line no-labels - branches: if (node.tag === HostComponent) { - let instance = node.stateNode; - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - const props = node.memoizedProps; - const type = node.type; - instance = cloneHiddenInstance(instance, type, props, node); - } - appendChildToContainerChildSet(containerChildSet, instance); - } else if (node.tag === HostText) { - let instance = node.stateNode; - if (needsVisibilityToggle && isHidden) { - // This child is inside a timed out tree. Hide it. - const text = node.memoizedProps; - instance = cloneHiddenTextInstance(instance, text, node); - } - appendChildToContainerChildSet(containerChildSet, instance); - } else if (node.tag === HostPortal) { - // If we have a portal child, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - } else if ( - node.tag === OffscreenComponent && - node.memoizedState !== null - ) { - // The children in this boundary are hidden. Toggle their visibility - // before appending. - const child = node.child; - if (child !== null) { - child.return = node; - } - // If Offscreen is not in manual mode, detached tree is hidden from user space. - const _needsVisibilityToggle = !isOffscreenManual(node); - appendAllChildrenToContainer( - containerChildSet, - node, - _needsVisibilityToggle, - true, - ); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - node = (node: Fiber); - if (node === workInProgress) { - return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - while (node.sibling === null) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (node.return === null || node.return === workInProgress) { - return; - } - node = node.return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - node.sibling.return = node.return; - node = node.sibling; - } - }; - updateHostContainer = function(current: null | Fiber, workInProgress: Fiber) { - const portalOrRoot: { - containerInfo: Container, - pendingChildren: ChildSet, - ... - } = workInProgress.stateNode; - const childrenUnchanged = hadNoMutationsEffects(current, workInProgress); - if (childrenUnchanged) { - // No changes, just reuse the existing instance. - } else { - const container = portalOrRoot.containerInfo; - const newChildSet = createContainerChildSet(container); - // If children might have changed, we have to add them all to the set. - appendAllChildrenToContainer(newChildSet, workInProgress, false, false); - portalOrRoot.pendingChildren = newChildSet; - // Schedule an update on the container to swap out the container. - markUpdate(workInProgress); - finalizeContainerChildren(container, newChildSet); - } - }; - updateHostComponent = function( - current: Fiber, - workInProgress: Fiber, - type: Type, - newProps: Props, - ) { - const currentInstance = current.stateNode; - const oldProps = current.memoizedProps; - // If there are no effects associated with this node, then none of our children had any updates. - // This guarantees that we can reuse all of them. - const childrenUnchanged = hadNoMutationsEffects(current, workInProgress); - if (childrenUnchanged && oldProps === newProps) { - // No changes, just reuse the existing instance. - // Note that this might release a previous clone. - workInProgress.stateNode = currentInstance; - return; - } - const recyclableInstance: Instance = workInProgress.stateNode; - const currentHostContext = getHostContext(); - let updatePayload = null; - if (oldProps !== newProps) { - updatePayload = prepareUpdate( - recyclableInstance, - type, - oldProps, - newProps, - currentHostContext, - ); - } - if (childrenUnchanged && updatePayload === null) { - // No changes, just reuse the existing instance. - // Note that this might release a previous clone. - workInProgress.stateNode = currentInstance; - return; - } - const newInstance = cloneInstance( - currentInstance, - updatePayload, - type, - oldProps, - newProps, - workInProgress, - childrenUnchanged, - recyclableInstance, - ); - if ( - finalizeInitialChildren(newInstance, type, newProps, currentHostContext) - ) { - markUpdate(workInProgress); - } - workInProgress.stateNode = newInstance; - if (childrenUnchanged) { - // If there are no other effects in this tree, we need to flag this node as having one. - // Even though we're not going to use it for anything. - // Otherwise parents won't know that there are new children to propagate upwards. - markUpdate(workInProgress); - } else { - // If children might have changed, we have to add them all to the set. - appendAllChildren(newInstance, workInProgress, false, false); - } - }; - updateHostText = function( - current: Fiber, - workInProgress: Fiber, - oldText: string, - newText: string, - ) { - if (oldText !== newText) { - // If the text content differs, we'll create a new text instance for it. - const rootContainerInstance = getRootHostContainer(); - const currentHostContext = getHostContext(); - workInProgress.stateNode = createTextInstance( - newText, - rootContainerInstance, - currentHostContext, - workInProgress, - ); - // We'll have to mark it as having an effect, even though we won't use the effect for anything. - // This lets the parents know that at least one of their children has changed. - markUpdate(workInProgress); - } else { - workInProgress.stateNode = current.stateNode; - } - }; -} else { - // No host operations - updateHostContainer = function(current: null | Fiber, workInProgress: Fiber) { - // Noop - }; - updateHostComponent = function( - current: Fiber, - workInProgress: Fiber, - type: Type, - newProps: Props, - ) { - // Noop - }; - updateHostText = function( - current: Fiber, - workInProgress: Fiber, - oldText: string, - newText: string, - ) { - // Noop - }; -} - -function cutOffTailIfNeeded( - renderState: SuspenseListRenderState, - hasRenderedATailFallback: boolean, -) { - if (getIsHydrating()) { - // If we're hydrating, we should consume as many items as we can - // so we don't leave any behind. - return; - } - switch (renderState.tailMode) { - case 'hidden': { - // Any insertions at the end of the tail list after this point - // should be invisible. If there are already mounted boundaries - // anything before them are not considered for collapsing. - // Therefore we need to go through the whole tail to find if - // there are any. - let tailNode = renderState.tail; - let lastTailNode = null; - while (tailNode !== null) { - if (tailNode.alternate !== null) { - lastTailNode = tailNode; - } - tailNode = tailNode.sibling; - } - // Next we're simply going to delete all insertions after the - // last rendered item. - if (lastTailNode === null) { - // All remaining items in the tail are insertions. - renderState.tail = null; - } else { - // Detach the insertion after the last node that was already - // inserted. - lastTailNode.sibling = null; - } - break; - } - case 'collapsed': { - // Any insertions at the end of the tail list after this point - // should be invisible. If there are already mounted boundaries - // anything before them are not considered for collapsing. - // Therefore we need to go through the whole tail to find if - // there are any. - let tailNode = renderState.tail; - let lastTailNode = null; - while (tailNode !== null) { - if (tailNode.alternate !== null) { - lastTailNode = tailNode; - } - tailNode = tailNode.sibling; - } - // Next we're simply going to delete all insertions after the - // last rendered item. - if (lastTailNode === null) { - // All remaining items in the tail are insertions. - if (!hasRenderedATailFallback && renderState.tail !== null) { - // We suspended during the head. We want to show at least one - // row at the tail. So we'll keep on and cut off the rest. - renderState.tail.sibling = null; - } else { - renderState.tail = null; - } - } else { - // Detach the insertion after the last node that was already - // inserted. - lastTailNode.sibling = null; - } - break; - } - } -} - -function bubbleProperties(completedWork: Fiber) { - const didBailout = - completedWork.alternate !== null && - completedWork.alternate.child === completedWork.child; - - let newChildLanes = NoLanes; - let subtreeFlags = NoFlags; - - if (!didBailout) { - // Bubble up the earliest expiration time. - if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) { - // In profiling mode, resetChildExpirationTime is also used to reset - // profiler durations. - let actualDuration = completedWork.actualDuration; - let treeBaseDuration = ((completedWork.selfBaseDuration: any): number); - - let child = completedWork.child; - while (child !== null) { - newChildLanes = mergeLanes( - newChildLanes, - mergeLanes(child.lanes, child.childLanes), - ); - - subtreeFlags |= child.subtreeFlags; - subtreeFlags |= child.flags; - - // When a fiber is cloned, its actualDuration is reset to 0. This value will - // only be updated if work is done on the fiber (i.e. it doesn't bailout). - // When work is done, it should bubble to the parent's actualDuration. If - // the fiber has not been cloned though, (meaning no work was done), then - // this value will reflect the amount of time spent working on a previous - // render. In that case it should not bubble. We determine whether it was - // cloned by comparing the child pointer. - // $FlowFixMe[unsafe-addition] addition with possible null/undefined value - actualDuration += child.actualDuration; - - // $FlowFixMe[unsafe-addition] addition with possible null/undefined value - treeBaseDuration += child.treeBaseDuration; - child = child.sibling; - } - - completedWork.actualDuration = actualDuration; - completedWork.treeBaseDuration = treeBaseDuration; - } else { - let child = completedWork.child; - while (child !== null) { - newChildLanes = mergeLanes( - newChildLanes, - mergeLanes(child.lanes, child.childLanes), - ); - - subtreeFlags |= child.subtreeFlags; - subtreeFlags |= child.flags; - - // Update the return pointer so the tree is consistent. This is a code - // smell because it assumes the commit phase is never concurrent with - // the render phase. Will address during refactor to alternate model. - child.return = completedWork; - - child = child.sibling; - } - } - - completedWork.subtreeFlags |= subtreeFlags; - } else { - // Bubble up the earliest expiration time. - if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) { - // In profiling mode, resetChildExpirationTime is also used to reset - // profiler durations. - let treeBaseDuration = ((completedWork.selfBaseDuration: any): number); - - let child = completedWork.child; - while (child !== null) { - newChildLanes = mergeLanes( - newChildLanes, - mergeLanes(child.lanes, child.childLanes), - ); - - // "Static" flags share the lifetime of the fiber/hook they belong to, - // so we should bubble those up even during a bailout. All the other - // flags have a lifetime only of a single render + commit, so we should - // ignore them. - subtreeFlags |= child.subtreeFlags & StaticMask; - subtreeFlags |= child.flags & StaticMask; - - // $FlowFixMe[unsafe-addition] addition with possible null/undefined value - treeBaseDuration += child.treeBaseDuration; - child = child.sibling; - } - - completedWork.treeBaseDuration = treeBaseDuration; - } else { - let child = completedWork.child; - while (child !== null) { - newChildLanes = mergeLanes( - newChildLanes, - mergeLanes(child.lanes, child.childLanes), - ); - - // "Static" flags share the lifetime of the fiber/hook they belong to, - // so we should bubble those up even during a bailout. All the other - // flags have a lifetime only of a single render + commit, so we should - // ignore them. - subtreeFlags |= child.subtreeFlags & StaticMask; - subtreeFlags |= child.flags & StaticMask; - - // Update the return pointer so the tree is consistent. This is a code - // smell because it assumes the commit phase is never concurrent with - // the render phase. Will address during refactor to alternate model. - child.return = completedWork; - - child = child.sibling; - } - } - - completedWork.subtreeFlags |= subtreeFlags; - } - - completedWork.childLanes = newChildLanes; - - return didBailout; -} - -function completeDehydratedSuspenseBoundary( - current: Fiber | null, - workInProgress: Fiber, - nextState: SuspenseState | null, -): boolean { - if ( - hasUnhydratedTailNodes() && - (workInProgress.mode & ConcurrentMode) !== NoMode && - (workInProgress.flags & DidCapture) === NoFlags - ) { - warnIfUnhydratedTailNodes(workInProgress); - resetHydrationState(); - workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture; - - return false; - } - - const wasHydrated = popHydrationState(workInProgress); - - if (nextState !== null && nextState.dehydrated !== null) { - // We might be inside a hydration state the first time we're picking up this - // Suspense boundary, and also after we've reentered it for further hydration. - if (current === null) { - if (!wasHydrated) { - throw new Error( - 'A dehydrated suspense component was completed without a hydrated node. ' + - 'This is probably a bug in React.', - ); - } - prepareToHydrateHostSuspenseInstance(workInProgress); - bubbleProperties(workInProgress); - if (enableProfilerTimer) { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - const isTimedOutSuspense = nextState !== null; - if (isTimedOutSuspense) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - const primaryChildFragment = workInProgress.child; - if (primaryChildFragment !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= ((primaryChildFragment.treeBaseDuration: any): number); - } - } - } - } - return false; - } else { - // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration - // state since we're now exiting out of it. popHydrationState doesn't do that for us. - resetHydrationState(); - if ((workInProgress.flags & DidCapture) === NoFlags) { - // This boundary did not suspend so it's now hydrated and unsuspended. - workInProgress.memoizedState = null; - } - // If nothing suspended, we need to schedule an effect to mark this boundary - // as having hydrated so events know that they're free to be invoked. - // It's also a signal to replay events and the suspense callback. - // If something suspended, schedule an effect to attach retry listeners. - // So we might as well always mark this. - workInProgress.flags |= Update; - bubbleProperties(workInProgress); - if (enableProfilerTimer) { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - const isTimedOutSuspense = nextState !== null; - if (isTimedOutSuspense) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - const primaryChildFragment = workInProgress.child; - if (primaryChildFragment !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= ((primaryChildFragment.treeBaseDuration: any): number); - } - } - } - } - return false; - } - } else { - // Successfully completed this tree. If this was a forced client render, - // there may have been recoverable errors during first hydration - // attempt. If so, add them to a queue so we can log them in the - // commit phase. - upgradeHydrationErrorsToRecoverable(); - - // Fall through to normal Suspense path - return true; - } -} - -function completeWork( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -): Fiber | null { - const newProps = workInProgress.pendingProps; - // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - popTreeContext(workInProgress); - switch (workInProgress.tag) { - case IndeterminateComponent: - case LazyComponent: - case SimpleMemoComponent: - case FunctionComponent: - case ForwardRef: - case Fragment: - case Mode: - case Profiler: - case ContextConsumer: - case MemoComponent: - bubbleProperties(workInProgress); - return null; - case ClassComponent: { - const Component = workInProgress.type; - if (isLegacyContextProvider(Component)) { - popLegacyContext(workInProgress); - } - bubbleProperties(workInProgress); - return null; - } - case HostRoot: { - const fiberRoot = (workInProgress.stateNode: FiberRoot); - - if (enableTransitionTracing) { - const transitions = getWorkInProgressTransitions(); - // We set the Passive flag here because if there are new transitions, - // we will need to schedule callbacks and process the transitions, - // which we do in the passive phase - if (transitions !== null) { - workInProgress.flags |= Passive; - } - } - - if (enableCache) { - let previousCache: Cache | null = null; - if (current !== null) { - previousCache = current.memoizedState.cache; - } - const cache: Cache = workInProgress.memoizedState.cache; - if (cache !== previousCache) { - // Run passive effects to retain/release the cache. - workInProgress.flags |= Passive; - } - popCacheProvider(workInProgress, cache); - } - - if (enableTransitionTracing) { - popRootMarkerInstance(workInProgress); - } - - popRootTransition(workInProgress, fiberRoot, renderLanes); - popHostContainer(workInProgress); - popTopLevelLegacyContextObject(workInProgress); - resetMutableSourceWorkInProgressVersions(); - if (fiberRoot.pendingContext) { - fiberRoot.context = fiberRoot.pendingContext; - fiberRoot.pendingContext = null; - } - if (current === null || current.child === null) { - // If we hydrated, pop so that we can delete any remaining children - // that weren't hydrated. - const wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { - // If we hydrated, then we'll need to schedule an update for - // the commit side-effects on the root. - markUpdate(workInProgress); - } else { - if (current !== null) { - const prevState: RootState = current.memoizedState; - if ( - // Check if this is a client root - !prevState.isDehydrated || - // Check if we reverted to client rendering (e.g. due to an error) - (workInProgress.flags & ForceClientRender) !== NoFlags - ) { - // Schedule an effect to clear this container at the start of the - // next commit. This handles the case of React rendering into a - // container with previous children. It's also safe to do for - // updates too, because current.child would only be null if the - // previous render was null (so the container would already - // be empty). - workInProgress.flags |= Snapshot; - - // If this was a forced client render, there may have been - // recoverable errors during first hydration attempt. If so, add - // them to a queue so we can log them in the commit phase. - upgradeHydrationErrorsToRecoverable(); - } - } - } - } - updateHostContainer(current, workInProgress); - bubbleProperties(workInProgress); - if (enableTransitionTracing) { - if ((workInProgress.subtreeFlags & Visibility) !== NoFlags) { - // If any of our suspense children toggle visibility, this means that - // the pending boundaries array needs to be updated, which we only - // do in the passive phase. - workInProgress.flags |= Passive; - } - } - return null; - } - case HostResource: { - if (enableFloat && supportsResources) { - popHostContext(workInProgress); - const currentRef = current ? current.ref : null; - if (currentRef !== workInProgress.ref) { - markRef(workInProgress); - } - if ( - current === null || - current.memoizedState !== workInProgress.memoizedState - ) { - // The workInProgress resource is different than the current one or the current - // one does not exist - markUpdate(workInProgress); - } - bubbleProperties(workInProgress); - return null; - } - } - // eslint-disable-next-line-no-fallthrough - case HostSingleton: { - if (enableHostSingletons && supportsSingletons) { - popHostContext(workInProgress); - const rootContainerInstance = getRootHostContainer(); - const type = workInProgress.type; - if (current !== null && workInProgress.stateNode != null) { - updateHostComponent(current, workInProgress, type, newProps); - - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } - } else { - if (!newProps) { - if (workInProgress.stateNode === null) { - throw new Error( - 'We must have new props for new mounts. This error is likely ' + - 'caused by a bug in React. Please file an issue.', - ); - } - - // This can happen when we abort work. - bubbleProperties(workInProgress); - return null; - } - - const currentHostContext = getHostContext(); - const wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { - // We ignore the boolean indicating there is an updateQueue because - // it is used only to set text children and HostSingletons do not - // use them. - prepareToHydrateHostInstance(workInProgress, currentHostContext); - } else { - workInProgress.stateNode = resolveSingletonInstance( - type, - newProps, - rootContainerInstance, - currentHostContext, - true, - ); - markUpdate(workInProgress); - } - - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } - } - bubbleProperties(workInProgress); - return null; - } - } - // eslint-disable-next-line-no-fallthrough - case HostComponent: { - popHostContext(workInProgress); - const type = workInProgress.type; - if (current !== null && workInProgress.stateNode != null) { - updateHostComponent(current, workInProgress, type, newProps); - - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } - } else { - if (!newProps) { - if (workInProgress.stateNode === null) { - throw new Error( - 'We must have new props for new mounts. This error is likely ' + - 'caused by a bug in React. Please file an issue.', - ); - } - - // This can happen when we abort work. - bubbleProperties(workInProgress); - return null; - } - - const currentHostContext = getHostContext(); - // TODO: Move createInstance to beginWork and keep it on a context - // "stack" as the parent. Then append children as we go in beginWork - // or completeWork depending on whether we want to add them top->down or - // bottom->up. Top->down is faster in IE11. - const wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { - // TODO: Move this and createInstance step into the beginPhase - // to consolidate. - if ( - prepareToHydrateHostInstance(workInProgress, currentHostContext) - ) { - // If changes to the hydrated node need to be applied at the - // commit-phase we mark this as such. - markUpdate(workInProgress); - } - } else { - const rootContainerInstance = getRootHostContainer(); - const instance = createInstance( - type, - newProps, - rootContainerInstance, - currentHostContext, - workInProgress, - ); - appendAllChildren(instance, workInProgress, false, false); - workInProgress.stateNode = instance; - - // Certain renderers require commit-time effects for initial mount. - // (eg DOM renderer supports auto-focus for certain elements). - // Make sure such renderers get scheduled for later work. - if ( - finalizeInitialChildren( - instance, - type, - newProps, - currentHostContext, - ) - ) { - markUpdate(workInProgress); - } - } - - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } - } - bubbleProperties(workInProgress); - return null; - } - case HostText: { - const newText = newProps; - if (current && workInProgress.stateNode != null) { - const oldText = current.memoizedProps; - // If we have an alternate, that means this is an update and we need - // to schedule a side-effect to do the updates. - updateHostText(current, workInProgress, oldText, newText); - } else { - if (typeof newText !== 'string') { - if (workInProgress.stateNode === null) { - throw new Error( - 'We must have new props for new mounts. This error is likely ' + - 'caused by a bug in React. Please file an issue.', - ); - } - // This can happen when we abort work. - } - const rootContainerInstance = getRootHostContainer(); - const currentHostContext = getHostContext(); - const wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { - if (prepareToHydrateHostTextInstance(workInProgress)) { - markUpdate(workInProgress); - } - } else { - workInProgress.stateNode = createTextInstance( - newText, - rootContainerInstance, - currentHostContext, - workInProgress, - ); - } - } - bubbleProperties(workInProgress); - return null; - } - case SuspenseComponent: { - popSuspenseHandler(workInProgress); - const nextState: null | SuspenseState = workInProgress.memoizedState; - - // Special path for dehydrated boundaries. We may eventually move this - // to its own fiber type so that we can add other kinds of hydration - // boundaries that aren't associated with a Suspense tree. In anticipation - // of such a refactor, all the hydration logic is contained in - // this branch. - if ( - current === null || - (current.memoizedState !== null && - current.memoizedState.dehydrated !== null) - ) { - const fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary( - current, - workInProgress, - nextState, - ); - if (!fallthroughToNormalSuspensePath) { - if (workInProgress.flags & ShouldCapture) { - // Special case. There were remaining unhydrated nodes. We treat - // this as a mismatch. Revert to client rendering. - return workInProgress; - } else { - // Did not finish hydrating, either because this is the initial - // render or because something suspended. - return null; - } - } - - // Continue with the normal Suspense path. - } - - if ((workInProgress.flags & DidCapture) !== NoFlags) { - // Something suspended. Re-render with the fallback children. - workInProgress.lanes = renderLanes; - // Do not reset the effect list. - if ( - enableProfilerTimer && - (workInProgress.mode & ProfileMode) !== NoMode - ) { - transferActualDuration(workInProgress); - } - // Don't bubble properties in this case. - return workInProgress; - } - - const nextDidTimeout = nextState !== null; - const prevDidTimeout = - current !== null && - (current.memoizedState: null | SuspenseState) !== null; - - if (enableCache && nextDidTimeout) { - const offscreenFiber: Fiber = (workInProgress.child: any); - let previousCache: Cache | null = null; - if ( - offscreenFiber.alternate !== null && - offscreenFiber.alternate.memoizedState !== null && - offscreenFiber.alternate.memoizedState.cachePool !== null - ) { - previousCache = offscreenFiber.alternate.memoizedState.cachePool.pool; - } - let cache: Cache | null = null; - if ( - offscreenFiber.memoizedState !== null && - offscreenFiber.memoizedState.cachePool !== null - ) { - cache = offscreenFiber.memoizedState.cachePool.pool; - } - if (cache !== previousCache) { - // Run passive effects to retain/release the cache. - offscreenFiber.flags |= Passive; - } - } - - // If the suspended state of the boundary changes, we need to schedule - // a passive effect, which is when we process the transitions - if (nextDidTimeout !== prevDidTimeout) { - if (enableTransitionTracing) { - const offscreenFiber: Fiber = (workInProgress.child: any); - offscreenFiber.flags |= Passive; - } - - // If the suspended state of the boundary changes, we need to schedule - // an effect to toggle the subtree's visibility. When we switch from - // fallback -> primary, the inner Offscreen fiber schedules this effect - // as part of its normal complete phase. But when we switch from - // primary -> fallback, the inner Offscreen fiber does not have a complete - // phase. So we need to schedule its effect here. - // - // We also use this flag to connect/disconnect the effects, but the same - // logic applies: when re-connecting, the Offscreen fiber's complete - // phase will handle scheduling the effect. It's only when the fallback - // is active that we have to do anything special. - if (nextDidTimeout) { - const offscreenFiber: Fiber = (workInProgress.child: any); - offscreenFiber.flags |= Visibility; - - // TODO: This will still suspend a synchronous tree if anything - // in the concurrent tree already suspended during this render. - // This is a known bug. - if ((workInProgress.mode & ConcurrentMode) !== NoMode) { - // TODO: Move this back to throwException because this is too late - // if this is a large tree which is common for initial loads. We - // don't know if we should restart a render or not until we get - // this marker, and this is too late. - // If this render already had a ping or lower pri updates, - // and this is the first time we know we're going to suspend we - // should be able to immediately restart from within throwException. - if (isBadSuspenseFallback(current, newProps)) { - renderDidSuspendDelayIfPossible(); - } else { - renderDidSuspend(); - } - } - } - } - - const wakeables: Set | null = (workInProgress.updateQueue: any); - if (wakeables !== null) { - // Schedule an effect to attach a retry listener to the promise. - // TODO: Move to passive phase - workInProgress.flags |= Update; - } - - if ( - enableSuspenseCallback && - workInProgress.updateQueue !== null && - workInProgress.memoizedProps.suspenseCallback != null - ) { - // Always notify the callback - // TODO: Move to passive phase - workInProgress.flags |= Update; - } - bubbleProperties(workInProgress); - if (enableProfilerTimer) { - if ((workInProgress.mode & ProfileMode) !== NoMode) { - if (nextDidTimeout) { - // Don't count time spent in a timed out Suspense subtree as part of the base duration. - const primaryChildFragment = workInProgress.child; - if (primaryChildFragment !== null) { - // $FlowFixMe Flow doesn't support type casting in combination with the -= operator - workInProgress.treeBaseDuration -= ((primaryChildFragment.treeBaseDuration: any): number); - } - } - } - } - return null; - } - case HostPortal: - popHostContainer(workInProgress); - updateHostContainer(current, workInProgress); - if (current === null) { - preparePortalMount(workInProgress.stateNode.containerInfo); - } - bubbleProperties(workInProgress); - return null; - case ContextProvider: - // Pop provider fiber - const context: ReactContext = workInProgress.type._context; - popProvider(context, workInProgress); - bubbleProperties(workInProgress); - return null; - case IncompleteClassComponent: { - // Same as class component case. I put it down here so that the tags are - // sequential to ensure this switch is compiled to a jump table. - const Component = workInProgress.type; - if (isLegacyContextProvider(Component)) { - popLegacyContext(workInProgress); - } - bubbleProperties(workInProgress); - return null; - } - case SuspenseListComponent: { - popSuspenseListContext(workInProgress); - - const renderState: null | SuspenseListRenderState = - workInProgress.memoizedState; - - if (renderState === null) { - // We're running in the default, "independent" mode. - // We don't do anything in this mode. - bubbleProperties(workInProgress); - return null; - } - - let didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags; - - const renderedTail = renderState.rendering; - if (renderedTail === null) { - // We just rendered the head. - if (!didSuspendAlready) { - // This is the first pass. We need to figure out if anything is still - // suspended in the rendered set. - - // If new content unsuspended, but there's still some content that - // didn't. Then we need to do a second pass that forces everything - // to keep showing their fallbacks. - - // We might be suspended if something in this render pass suspended, or - // something in the previous committed pass suspended. Otherwise, - // there's no chance so we can skip the expensive call to - // findFirstSuspended. - const cannotBeSuspended = - renderHasNotSuspendedYet() && - (current === null || (current.flags & DidCapture) === NoFlags); - if (!cannotBeSuspended) { - let row = workInProgress.child; - while (row !== null) { - const suspended = findFirstSuspended(row); - if (suspended !== null) { - didSuspendAlready = true; - workInProgress.flags |= DidCapture; - cutOffTailIfNeeded(renderState, false); - - // If this is a newly suspended tree, it might not get committed as - // part of the second pass. In that case nothing will subscribe to - // its thenables. Instead, we'll transfer its thenables to the - // SuspenseList so that it can retry if they resolve. - // There might be multiple of these in the list but since we're - // going to wait for all of them anyway, it doesn't really matter - // which ones gets to ping. In theory we could get clever and keep - // track of how many dependencies remain but it gets tricky because - // in the meantime, we can add/remove/change items and dependencies. - // We might bail out of the loop before finding any but that - // doesn't matter since that means that the other boundaries that - // we did find already has their listeners attached. - const newThenables = suspended.updateQueue; - if (newThenables !== null) { - workInProgress.updateQueue = newThenables; - workInProgress.flags |= Update; - } - - // Rerender the whole list, but this time, we'll force fallbacks - // to stay in place. - // Reset the effect flags before doing the second pass since that's now invalid. - // Reset the child fibers to their original state. - workInProgress.subtreeFlags = NoFlags; - resetChildFibers(workInProgress, renderLanes); - - // Set up the Suspense List Context to force suspense and - // immediately rerender the children. - pushSuspenseListContext( - workInProgress, - setShallowSuspenseListContext( - suspenseStackCursor.current, - ForceSuspenseFallback, - ), - ); - // Don't bubble properties in this case. - return workInProgress.child; - } - row = row.sibling; - } - } - - if (renderState.tail !== null && now() > getRenderTargetTime()) { - // We have already passed our CPU deadline but we still have rows - // left in the tail. We'll just give up further attempts to render - // the main content and only render fallbacks. - workInProgress.flags |= DidCapture; - didSuspendAlready = true; - - cutOffTailIfNeeded(renderState, false); - - // Since nothing actually suspended, there will nothing to ping this - // to get it started back up to attempt the next item. While in terms - // of priority this work has the same priority as this current render, - // it's not part of the same transition once the transition has - // committed. If it's sync, we still want to yield so that it can be - // painted. Conceptually, this is really the same as pinging. - // We can use any RetryLane even if it's the one currently rendering - // since we're leaving it behind on this node. - workInProgress.lanes = SomeRetryLane; - } - } else { - cutOffTailIfNeeded(renderState, false); - } - // Next we're going to render the tail. - } else { - // Append the rendered row to the child list. - if (!didSuspendAlready) { - const suspended = findFirstSuspended(renderedTail); - if (suspended !== null) { - workInProgress.flags |= DidCapture; - didSuspendAlready = true; - - // Ensure we transfer the update queue to the parent so that it doesn't - // get lost if this row ends up dropped during a second pass. - const newThenables = suspended.updateQueue; - if (newThenables !== null) { - workInProgress.updateQueue = newThenables; - workInProgress.flags |= Update; - } - - cutOffTailIfNeeded(renderState, true); - // This might have been modified. - if ( - renderState.tail === null && - renderState.tailMode === 'hidden' && - !renderedTail.alternate && - !getIsHydrating() // We don't cut it if we're hydrating. - ) { - // We're done. - bubbleProperties(workInProgress); - return null; - } - } else if ( - // The time it took to render last row is greater than the remaining - // time we have to render. So rendering one more row would likely - // exceed it. - now() * 2 - renderState.renderingStartTime > - getRenderTargetTime() && - renderLanes !== OffscreenLane - ) { - // We have now passed our CPU deadline and we'll just give up further - // attempts to render the main content and only render fallbacks. - // The assumption is that this is usually faster. - workInProgress.flags |= DidCapture; - didSuspendAlready = true; - - cutOffTailIfNeeded(renderState, false); - - // Since nothing actually suspended, there will nothing to ping this - // to get it started back up to attempt the next item. While in terms - // of priority this work has the same priority as this current render, - // it's not part of the same transition once the transition has - // committed. If it's sync, we still want to yield so that it can be - // painted. Conceptually, this is really the same as pinging. - // We can use any RetryLane even if it's the one currently rendering - // since we're leaving it behind on this node. - workInProgress.lanes = SomeRetryLane; - } - } - if (renderState.isBackwards) { - // The effect list of the backwards tail will have been added - // to the end. This breaks the guarantee that life-cycles fire in - // sibling order but that isn't a strong guarantee promised by React. - // Especially since these might also just pop in during future commits. - // Append to the beginning of the list. - renderedTail.sibling = workInProgress.child; - workInProgress.child = renderedTail; - } else { - const previousSibling = renderState.last; - if (previousSibling !== null) { - previousSibling.sibling = renderedTail; - } else { - workInProgress.child = renderedTail; - } - renderState.last = renderedTail; - } - } - - if (renderState.tail !== null) { - // We still have tail rows to render. - // Pop a row. - const next = renderState.tail; - renderState.rendering = next; - renderState.tail = next.sibling; - renderState.renderingStartTime = now(); - next.sibling = null; - - // Restore the context. - // TODO: We can probably just avoid popping it instead and only - // setting it the first time we go from not suspended to suspended. - let suspenseContext = suspenseStackCursor.current; - if (didSuspendAlready) { - suspenseContext = setShallowSuspenseListContext( - suspenseContext, - ForceSuspenseFallback, - ); - } else { - suspenseContext = setDefaultShallowSuspenseListContext( - suspenseContext, - ); - } - pushSuspenseListContext(workInProgress, suspenseContext); - // Do a pass over the next row. - // Don't bubble properties in this case. - return next; - } - bubbleProperties(workInProgress); - return null; - } - case ScopeComponent: { - if (enableScopeAPI) { - if (current === null) { - const scopeInstance: ReactScopeInstance = createScopeInstance(); - workInProgress.stateNode = scopeInstance; - prepareScopeUpdate(scopeInstance, workInProgress); - if (workInProgress.ref !== null) { - markRef(workInProgress); - markUpdate(workInProgress); - } - } else { - if (workInProgress.ref !== null) { - markUpdate(workInProgress); - } - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } - } - bubbleProperties(workInProgress); - return null; - } - break; - } - case OffscreenComponent: - case LegacyHiddenComponent: { - popSuspenseHandler(workInProgress); - popHiddenContext(workInProgress); - const nextState: OffscreenState | null = workInProgress.memoizedState; - const nextIsHidden = nextState !== null; - - // Schedule a Visibility effect if the visibility has changed - if (enableLegacyHidden && workInProgress.tag === LegacyHiddenComponent) { - // LegacyHidden doesn't do any hiding — it only pre-renders. - } else { - if (current !== null) { - const prevState: OffscreenState | null = current.memoizedState; - const prevIsHidden = prevState !== null; - if (prevIsHidden !== nextIsHidden) { - workInProgress.flags |= Visibility; - } - } else { - // On initial mount, we only need a Visibility effect if the tree - // is hidden. - if (nextIsHidden) { - workInProgress.flags |= Visibility; - } - } - } - - if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) { - bubbleProperties(workInProgress); - } else { - // Don't bubble properties for hidden children unless we're rendering - // at offscreen priority. - if ( - includesSomeLane(renderLanes, (OffscreenLane: Lane)) && - // Also don't bubble if the tree suspended - (workInProgress.flags & DidCapture) === NoLanes - ) { - bubbleProperties(workInProgress); - // Check if there was an insertion or update in the hidden subtree. - // If so, we need to hide those nodes in the commit phase, so - // schedule a visibility effect. - if ( - (!enableLegacyHidden || - workInProgress.tag !== LegacyHiddenComponent) && - workInProgress.subtreeFlags & (Placement | Update) - ) { - workInProgress.flags |= Visibility; - } - } - } - - if (workInProgress.updateQueue !== null) { - // Schedule an effect to attach Suspense retry listeners - // TODO: Move to passive phase - workInProgress.flags |= Update; - } - - if (enableCache) { - let previousCache: Cache | null = null; - if ( - current !== null && - current.memoizedState !== null && - current.memoizedState.cachePool !== null - ) { - previousCache = current.memoizedState.cachePool.pool; - } - let cache: Cache | null = null; - if ( - workInProgress.memoizedState !== null && - workInProgress.memoizedState.cachePool !== null - ) { - cache = workInProgress.memoizedState.cachePool.pool; - } - if (cache !== previousCache) { - // Run passive effects to retain/release the cache. - workInProgress.flags |= Passive; - } - } - - popTransition(workInProgress, current); - - return null; - } - case CacheComponent: { - if (enableCache) { - let previousCache: Cache | null = null; - if (current !== null) { - previousCache = current.memoizedState.cache; - } - const cache: Cache = workInProgress.memoizedState.cache; - if (cache !== previousCache) { - // Run passive effects to retain/release the cache. - workInProgress.flags |= Passive; - } - popCacheProvider(workInProgress, cache); - bubbleProperties(workInProgress); - } - return null; - } - case TracingMarkerComponent: { - if (enableTransitionTracing) { - const instance: TracingMarkerInstance | null = workInProgress.stateNode; - if (instance !== null) { - popMarkerInstance(workInProgress); - } - bubbleProperties(workInProgress); - } - return null; - } - } - - throw new Error( - `Unknown unit of work tag (${workInProgress.tag}). This error is likely caused by a bug in ` + - 'React. Please file an issue.', - ); -} - -export {completeWork}; diff --git a/packages/react-reconciler/src/ReactFiberConcurrentUpdates.new.js b/packages/react-reconciler/src/ReactFiberConcurrentUpdates.new.js deleted file mode 100644 index 261bc518fc052..0000000000000 --- a/packages/react-reconciler/src/ReactFiberConcurrentUpdates.new.js +++ /dev/null @@ -1,288 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type { - UpdateQueue as HookQueue, - Update as HookUpdate, -} from './ReactFiberHooks.new'; -import type { - SharedQueue as ClassQueue, - Update as ClassUpdate, -} from './ReactFiberClassUpdateQueue.new'; -import type {Lane, Lanes} from './ReactFiberLane.new'; -import type {OffscreenInstance} from './ReactFiberOffscreenComponent'; - -import { - warnAboutUpdateOnNotYetMountedFiberInDEV, - throwIfInfiniteUpdateLoopDetected, - getWorkInProgressRoot, -} from './ReactFiberWorkLoop.new'; -import { - NoLane, - NoLanes, - mergeLanes, - markHiddenUpdate, -} from './ReactFiberLane.new'; -import {NoFlags, Placement, Hydrating} from './ReactFiberFlags'; -import {HostRoot, OffscreenComponent} from './ReactWorkTags'; -import {OffscreenVisible} from './ReactFiberOffscreenComponent'; - -export type ConcurrentUpdate = { - next: ConcurrentUpdate, - lane: Lane, -}; - -type ConcurrentQueue = { - pending: ConcurrentUpdate | null, -}; - -// If a render is in progress, and we receive an update from a concurrent event, -// we wait until the current render is over (either finished or interrupted) -// before adding it to the fiber/hook queue. Push to this array so we can -// access the queue, fiber, update, et al later. -const concurrentQueues: Array = []; -let concurrentQueuesIndex = 0; - -let concurrentlyUpdatedLanes: Lanes = NoLanes; - -export function finishQueueingConcurrentUpdates(): void { - const endIndex = concurrentQueuesIndex; - concurrentQueuesIndex = 0; - - concurrentlyUpdatedLanes = NoLanes; - - let i = 0; - while (i < endIndex) { - const fiber: Fiber = concurrentQueues[i]; - concurrentQueues[i++] = null; - const queue: ConcurrentQueue = concurrentQueues[i]; - concurrentQueues[i++] = null; - const update: ConcurrentUpdate = concurrentQueues[i]; - concurrentQueues[i++] = null; - const lane: Lane = concurrentQueues[i]; - concurrentQueues[i++] = null; - - if (queue !== null && update !== null) { - const pending = queue.pending; - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - queue.pending = update; - } - - if (lane !== NoLane) { - markUpdateLaneFromFiberToRoot(fiber, update, lane); - } - } -} - -export function getConcurrentlyUpdatedLanes(): Lanes { - return concurrentlyUpdatedLanes; -} - -function enqueueUpdate( - fiber: Fiber, - queue: ConcurrentQueue | null, - update: ConcurrentUpdate | null, - lane: Lane, -) { - // Don't update the `childLanes` on the return path yet. If we already in - // the middle of rendering, wait until after it has completed. - concurrentQueues[concurrentQueuesIndex++] = fiber; - concurrentQueues[concurrentQueuesIndex++] = queue; - concurrentQueues[concurrentQueuesIndex++] = update; - concurrentQueues[concurrentQueuesIndex++] = lane; - - concurrentlyUpdatedLanes = mergeLanes(concurrentlyUpdatedLanes, lane); - - // The fiber's `lane` field is used in some places to check if any work is - // scheduled, to perform an eager bailout, so we need to update it immediately. - // TODO: We should probably move this to the "shared" queue instead. - fiber.lanes = mergeLanes(fiber.lanes, lane); - const alternate = fiber.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, lane); - } -} - -export function enqueueConcurrentHookUpdate( - fiber: Fiber, - queue: HookQueue, - update: HookUpdate, - lane: Lane, -): FiberRoot | null { - const concurrentQueue: ConcurrentQueue = (queue: any); - const concurrentUpdate: ConcurrentUpdate = (update: any); - enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane); - return getRootForUpdatedFiber(fiber); -} - -export function enqueueConcurrentHookUpdateAndEagerlyBailout( - fiber: Fiber, - queue: HookQueue, - update: HookUpdate, -): void { - // This function is used to queue an update that doesn't need a rerender. The - // only reason we queue it is in case there's a subsequent higher priority - // update that causes it to be rebased. - const lane = NoLane; - const concurrentQueue: ConcurrentQueue = (queue: any); - const concurrentUpdate: ConcurrentUpdate = (update: any); - enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane); - - // Usually we can rely on the upcoming render phase to process the concurrent - // queue. However, since this is a bail out, we're not scheduling any work - // here. So the update we just queued will leak until something else happens - // to schedule work (if ever). - // - // Check if we're currently in the middle of rendering a tree, and if not, - // process the queue immediately to prevent a leak. - const isConcurrentlyRendering = getWorkInProgressRoot() !== null; - if (!isConcurrentlyRendering) { - finishQueueingConcurrentUpdates(); - } -} - -export function enqueueConcurrentClassUpdate( - fiber: Fiber, - queue: ClassQueue, - update: ClassUpdate, - lane: Lane, -): FiberRoot | null { - const concurrentQueue: ConcurrentQueue = (queue: any); - const concurrentUpdate: ConcurrentUpdate = (update: any); - enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane); - return getRootForUpdatedFiber(fiber); -} - -export function enqueueConcurrentRenderForLane( - fiber: Fiber, - lane: Lane, -): FiberRoot | null { - enqueueUpdate(fiber, null, null, lane); - return getRootForUpdatedFiber(fiber); -} - -// Calling this function outside this module should only be done for backwards -// compatibility and should always be accompanied by a warning. -export function unsafe_markUpdateLaneFromFiberToRoot( - sourceFiber: Fiber, - lane: Lane, -): FiberRoot | null { - // NOTE: For Hyrum's Law reasons, if an infinite update loop is detected, it - // should throw before `markUpdateLaneFromFiberToRoot` is called. But this is - // undefined behavior and we can change it if we need to; it just so happens - // that, at the time of this writing, there's an internal product test that - // happens to rely on this. - const root = getRootForUpdatedFiber(sourceFiber); - markUpdateLaneFromFiberToRoot(sourceFiber, null, lane); - return root; -} - -function markUpdateLaneFromFiberToRoot( - sourceFiber: Fiber, - update: ConcurrentUpdate | null, - lane: Lane, -): void { - // Update the source fiber's lanes - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); - let alternate = sourceFiber.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, lane); - } - // Walk the parent path to the root and update the child lanes. - let isHidden = false; - let parent = sourceFiber.return; - let node = sourceFiber; - while (parent !== null) { - parent.childLanes = mergeLanes(parent.childLanes, lane); - alternate = parent.alternate; - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, lane); - } - - if (parent.tag === OffscreenComponent) { - // Check if this offscreen boundary is currently hidden. - // - // The instance may be null if the Offscreen parent was unmounted. Usually - // the parent wouldn't be reachable in that case because we disconnect - // fibers from the tree when they are deleted. However, there's a weird - // edge case where setState is called on a fiber that was interrupted - // before it ever mounted. Because it never mounts, it also never gets - // deleted. Because it never gets deleted, its return pointer never gets - // disconnected. Which means it may be attached to a deleted Offscreen - // parent node. (This discovery suggests it may be better for memory usage - // if we don't attach the `return` pointer until the commit phase, though - // in order to do that we'd need some other way to track the return - // pointer during the initial render, like on the stack.) - // - // This case is always accompanied by a warning, but we still need to - // account for it. (There may be other cases that we haven't discovered, - // too.) - const offscreenInstance: OffscreenInstance | null = parent.stateNode; - if ( - offscreenInstance !== null && - !(offscreenInstance._visibility & OffscreenVisible) - ) { - isHidden = true; - } - } - - node = parent; - parent = parent.return; - } - - if (isHidden && update !== null && node.tag === HostRoot) { - const root: FiberRoot = node.stateNode; - markHiddenUpdate(root, update, lane); - } -} - -function getRootForUpdatedFiber(sourceFiber: Fiber): FiberRoot | null { - // TODO: We will detect and infinite update loop and throw even if this fiber - // has already unmounted. This isn't really necessary but it happens to be the - // current behavior we've used for several release cycles. Consider not - // performing this check if the updated fiber already unmounted, since it's - // not possible for that to cause an infinite update loop. - throwIfInfiniteUpdateLoopDetected(); - - // When a setState happens, we must ensure the root is scheduled. Because - // update queues do not have a backpointer to the root, the only way to do - // this currently is to walk up the return path. This used to not be a big - // deal because we would have to walk up the return path to set - // the `childLanes`, anyway, but now those two traversals happen at - // different times. - // TODO: Consider adding a `root` backpointer on the update queue. - detectUpdateOnUnmountedFiber(sourceFiber, sourceFiber); - let node = sourceFiber; - let parent = node.return; - while (parent !== null) { - detectUpdateOnUnmountedFiber(sourceFiber, node); - node = parent; - parent = node.return; - } - return node.tag === HostRoot ? (node.stateNode: FiberRoot) : null; -} - -function detectUpdateOnUnmountedFiber(sourceFiber: Fiber, parent: Fiber) { - if (__DEV__) { - const alternate = parent.alternate; - if ( - alternate === null && - (parent.flags & (Placement | Hydrating)) !== NoFlags - ) { - warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); - } - } -} diff --git a/packages/react-reconciler/src/ReactFiberContext.new.js b/packages/react-reconciler/src/ReactFiberContext.new.js deleted file mode 100644 index 6baef778e6c3e..0000000000000 --- a/packages/react-reconciler/src/ReactFiberContext.new.js +++ /dev/null @@ -1,343 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; -import type {StackCursor} from './ReactFiberStack.new'; - -import {isFiberMounted} from './ReactFiberTreeReflection'; -import {disableLegacyContext} from 'shared/ReactFeatureFlags'; -import {ClassComponent, HostRoot} from './ReactWorkTags'; -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import checkPropTypes from 'shared/checkPropTypes'; - -import {createCursor, push, pop} from './ReactFiberStack.new'; - -let warnedAboutMissingGetChildContext; - -if (__DEV__) { - warnedAboutMissingGetChildContext = {}; -} - -// $FlowFixMe[incompatible-exact] -export const emptyContextObject: {} = {}; -if (__DEV__) { - Object.freeze(emptyContextObject); -} - -// A cursor to the current merged context object on the stack. -const contextStackCursor: StackCursor = createCursor( - emptyContextObject, -); -// A cursor to a boolean indicating whether the context has changed. -const didPerformWorkStackCursor: StackCursor = createCursor(false); -// Keep track of the previous context object that was on the stack. -// We use this to get access to the parent context after we have already -// pushed the next context provider, and now need to merge their contexts. -let previousContext: Object = emptyContextObject; - -function getUnmaskedContext( - workInProgress: Fiber, - Component: Function, - didPushOwnContextIfProvider: boolean, -): Object { - if (disableLegacyContext) { - return emptyContextObject; - } else { - if (didPushOwnContextIfProvider && isContextProvider(Component)) { - // If the fiber is a context provider itself, when we read its context - // we may have already pushed its own child context on the stack. A context - // provider should not "see" its own child context. Therefore we read the - // previous (parent) context instead for a context provider. - return previousContext; - } - return contextStackCursor.current; - } -} - -function cacheContext( - workInProgress: Fiber, - unmaskedContext: Object, - maskedContext: Object, -): void { - if (disableLegacyContext) { - return; - } else { - const instance = workInProgress.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; - } -} - -function getMaskedContext( - workInProgress: Fiber, - unmaskedContext: Object, -): Object { - if (disableLegacyContext) { - return emptyContextObject; - } else { - const type = workInProgress.type; - const contextTypes = type.contextTypes; - if (!contextTypes) { - return emptyContextObject; - } - - // Avoid recreating masked context unless unmasked context has changed. - // Failing to do this will result in unnecessary calls to componentWillReceiveProps. - // This may trigger infinite loops if componentWillReceiveProps calls setState. - const instance = workInProgress.stateNode; - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext - ) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - - const context = {}; - for (const key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - if (__DEV__) { - const name = getComponentNameFromFiber(workInProgress) || 'Unknown'; - checkPropTypes(contextTypes, context, 'context', name); - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. - // Context is created before the class component is instantiated so check for instance. - if (instance) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return context; - } -} - -function hasContextChanged(): boolean { - if (disableLegacyContext) { - return false; - } else { - return didPerformWorkStackCursor.current; - } -} - -function isContextProvider(type: Function): boolean { - if (disableLegacyContext) { - return false; - } else { - const childContextTypes = type.childContextTypes; - return childContextTypes !== null && childContextTypes !== undefined; - } -} - -function popContext(fiber: Fiber): void { - if (disableLegacyContext) { - return; - } else { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } -} - -function popTopLevelContextObject(fiber: Fiber): void { - if (disableLegacyContext) { - return; - } else { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } -} - -function pushTopLevelContextObject( - fiber: Fiber, - context: Object, - didChange: boolean, -): void { - if (disableLegacyContext) { - return; - } else { - if (contextStackCursor.current !== emptyContextObject) { - throw new Error( - 'Unexpected context found on stack. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - push(contextStackCursor, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); - } -} - -function processChildContext( - fiber: Fiber, - type: any, - parentContext: Object, -): Object { - if (disableLegacyContext) { - return parentContext; - } else { - const instance = fiber.stateNode; - const childContextTypes = type.childContextTypes; - - // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - if (typeof instance.getChildContext !== 'function') { - if (__DEV__) { - const componentName = getComponentNameFromFiber(fiber) || 'Unknown'; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - console.error( - '%s.childContextTypes is specified but there is no getChildContext() method ' + - 'on the instance. You can either define getChildContext() on %s or remove ' + - 'childContextTypes from it.', - componentName, - componentName, - ); - } - } - return parentContext; - } - - const childContext = instance.getChildContext(); - for (const contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error( - `${getComponentNameFromFiber(fiber) || - 'Unknown'}.getChildContext(): key "${contextKey}" is not defined in childContextTypes.`, - ); - } - } - if (__DEV__) { - const name = getComponentNameFromFiber(fiber) || 'Unknown'; - checkPropTypes(childContextTypes, childContext, 'child context', name); - } - - return {...parentContext, ...childContext}; - } -} - -function pushContextProvider(workInProgress: Fiber): boolean { - if (disableLegacyContext) { - return false; - } else { - const instance = workInProgress.stateNode; - // We push the context as early as possible to ensure stack integrity. - // If the instance does not exist yet, we will push null at first, - // and replace it on the stack later when invalidating the context. - const memoizedMergedChildContext = - (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - - // Remember the parent context so we can merge with it later. - // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. - previousContext = contextStackCursor.current; - push(contextStackCursor, memoizedMergedChildContext, workInProgress); - push( - didPerformWorkStackCursor, - didPerformWorkStackCursor.current, - workInProgress, - ); - - return true; - } -} - -function invalidateContextProvider( - workInProgress: Fiber, - type: any, - didChange: boolean, -): void { - if (disableLegacyContext) { - return; - } else { - const instance = workInProgress.stateNode; - - if (!instance) { - throw new Error( - 'Expected to have an instance by this point. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - if (didChange) { - // Merge parent and own context. - // Skip this if we're not updating due to sCU. - // This avoids unnecessarily recomputing memoized values. - const mergedContext = processChildContext( - workInProgress, - type, - previousContext, - ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - - // Replace the old (or empty) context with the new one. - // It is important to unwind the context in the reverse order. - pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); - // Now push the new context and mark that it has changed. - push(contextStackCursor, mergedContext, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } else { - pop(didPerformWorkStackCursor, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } - } -} - -function findCurrentUnmaskedContext(fiber: Fiber): Object { - if (disableLegacyContext) { - return emptyContextObject; - } else { - // Currently this is only used with renderSubtreeIntoContainer; not sure if it - // makes sense elsewhere - if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { - throw new Error( - 'Expected subtree parent to be a mounted class component. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - let node: Fiber = fiber; - do { - switch (node.tag) { - case HostRoot: - return node.stateNode.context; - case ClassComponent: { - const Component = node.type; - if (isContextProvider(Component)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - break; - } - } - // $FlowFixMe[incompatible-type] we bail out when we get a null - node = node.return; - } while (node !== null); - - throw new Error( - 'Found unexpected detached subtree parent. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } -} - -export { - getUnmaskedContext, - cacheContext, - getMaskedContext, - hasContextChanged, - popContext, - popTopLevelContextObject, - pushTopLevelContextObject, - processChildContext, - isContextProvider, - pushContextProvider, - invalidateContextProvider, - findCurrentUnmaskedContext, -}; diff --git a/packages/react-reconciler/src/ReactFiberDevToolsHook.new.js b/packages/react-reconciler/src/ReactFiberDevToolsHook.new.js deleted file mode 100644 index 323f4e090531c..0000000000000 --- a/packages/react-reconciler/src/ReactFiberDevToolsHook.new.js +++ /dev/null @@ -1,540 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Lane, Lanes} from './ReactFiberLane.new'; -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {ReactNodeList, Wakeable} from 'shared/ReactTypes'; -import type {EventPriority} from './ReactEventPriorities.new'; -// import type {DevToolsProfilingHooks} from 'react-devtools-shared/src/backend/types'; -// TODO: This import doesn't work because the DevTools depend on the DOM version of React -// and to properly type check against DOM React we can't also type check again non-DOM -// React which this hook might be in. -type DevToolsProfilingHooks = any; - -import { - getLabelForLane, - TotalLanes, -} from 'react-reconciler/src/ReactFiberLane.new'; -import {DidCapture} from './ReactFiberFlags'; -import { - consoleManagedByDevToolsDuringStrictMode, - enableProfilerTimer, - enableSchedulingProfiler, -} from 'shared/ReactFeatureFlags'; -import { - DiscreteEventPriority, - ContinuousEventPriority, - DefaultEventPriority, - IdleEventPriority, -} from './ReactEventPriorities.new'; -import { - ImmediatePriority as ImmediateSchedulerPriority, - UserBlockingPriority as UserBlockingSchedulerPriority, - NormalPriority as NormalSchedulerPriority, - IdlePriority as IdleSchedulerPriority, - unstable_yieldValue, - unstable_setDisableYieldValue, -} from './Scheduler'; -import {setSuppressWarning} from 'shared/consoleWithStackDev'; -import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev'; - -declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void; - -let rendererID = null; -let injectedHook = null; -let injectedProfilingHooks: DevToolsProfilingHooks | null = null; -let hasLoggedError = false; - -export const isDevToolsPresent = - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; - -export function injectInternals(internals: Object): boolean { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { - // No DevTools - return false; - } - const hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; - if (hook.isDisabled) { - // This isn't a real property on the hook, but it can be set to opt out - // of DevTools integration and associated warnings and logs. - // https://github.com/facebook/react/issues/3877 - return true; - } - if (!hook.supportsFiber) { - if (__DEV__) { - console.error( - 'The installed version of React DevTools is too old and will not work ' + - 'with the current version of React. Please update React DevTools. ' + - 'https://reactjs.org/link/react-devtools', - ); - } - // DevTools exists, even though it doesn't support Fiber. - return true; - } - try { - if (enableSchedulingProfiler) { - // Conditionally inject these hooks only if Timeline profiler is supported by this build. - // This gives DevTools a way to feature detect that isn't tied to version number - // (since profiling and timeline are controlled by different feature flags). - internals = { - ...internals, - getLaneLabelMap, - injectProfilingHooks, - }; - } - - rendererID = hook.inject(internals); - - // We have successfully injected, so now it is safe to set up hooks. - injectedHook = hook; - } catch (err) { - // Catch all errors because it is unsafe to throw during initialization. - if (__DEV__) { - console.error('React instrumentation encountered an error: %s.', err); - } - } - if (hook.checkDCE) { - // This is the real DevTools. - return true; - } else { - // This is likely a hook installed by Fast Refresh runtime. - return false; - } -} - -export function onScheduleRoot(root: FiberRoot, children: ReactNodeList) { - if (__DEV__) { - if ( - injectedHook && - typeof injectedHook.onScheduleFiberRoot === 'function' - ) { - try { - injectedHook.onScheduleFiberRoot(rendererID, root, children); - } catch (err) { - if (__DEV__ && !hasLoggedError) { - hasLoggedError = true; - console.error('React instrumentation encountered an error: %s', err); - } - } - } - } -} - -export function onCommitRoot(root: FiberRoot, eventPriority: EventPriority) { - if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { - try { - const didError = (root.current.flags & DidCapture) === DidCapture; - if (enableProfilerTimer) { - let schedulerPriority; - switch (eventPriority) { - case DiscreteEventPriority: - schedulerPriority = ImmediateSchedulerPriority; - break; - case ContinuousEventPriority: - schedulerPriority = UserBlockingSchedulerPriority; - break; - case DefaultEventPriority: - schedulerPriority = NormalSchedulerPriority; - break; - case IdleEventPriority: - schedulerPriority = IdleSchedulerPriority; - break; - default: - schedulerPriority = NormalSchedulerPriority; - break; - } - injectedHook.onCommitFiberRoot( - rendererID, - root, - schedulerPriority, - didError, - ); - } else { - injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError); - } - } catch (err) { - if (__DEV__) { - if (!hasLoggedError) { - hasLoggedError = true; - console.error('React instrumentation encountered an error: %s', err); - } - } - } - } -} - -export function onPostCommitRoot(root: FiberRoot) { - if ( - injectedHook && - typeof injectedHook.onPostCommitFiberRoot === 'function' - ) { - try { - injectedHook.onPostCommitFiberRoot(rendererID, root); - } catch (err) { - if (__DEV__) { - if (!hasLoggedError) { - hasLoggedError = true; - console.error('React instrumentation encountered an error: %s', err); - } - } - } - } -} - -export function onCommitUnmount(fiber: Fiber) { - if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { - try { - injectedHook.onCommitFiberUnmount(rendererID, fiber); - } catch (err) { - if (__DEV__) { - if (!hasLoggedError) { - hasLoggedError = true; - console.error('React instrumentation encountered an error: %s', err); - } - } - } - } -} - -export function setIsStrictModeForDevtools(newIsStrictMode: boolean) { - if (consoleManagedByDevToolsDuringStrictMode) { - if (typeof unstable_yieldValue === 'function') { - // We're in a test because Scheduler.unstable_yieldValue only exists - // in SchedulerMock. To reduce the noise in strict mode tests, - // suppress warnings and disable scheduler yielding during the double render - unstable_setDisableYieldValue(newIsStrictMode); - setSuppressWarning(newIsStrictMode); - } - - if (injectedHook && typeof injectedHook.setStrictMode === 'function') { - try { - injectedHook.setStrictMode(rendererID, newIsStrictMode); - } catch (err) { - if (__DEV__) { - if (!hasLoggedError) { - hasLoggedError = true; - console.error( - 'React instrumentation encountered an error: %s', - err, - ); - } - } - } - } - } else { - if (newIsStrictMode) { - disableLogs(); - } else { - reenableLogs(); - } - } -} - -// Profiler API hooks - -function injectProfilingHooks(profilingHooks: DevToolsProfilingHooks): void { - injectedProfilingHooks = profilingHooks; -} - -function getLaneLabelMap(): Map | null { - if (enableSchedulingProfiler) { - const map: Map = new Map(); - - let lane = 1; - for (let index = 0; index < TotalLanes; index++) { - const label = ((getLabelForLane(lane): any): string); - map.set(lane, label); - lane *= 2; - } - - return map; - } else { - return null; - } -} - -export function markCommitStarted(lanes: Lanes): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markCommitStarted === 'function' - ) { - injectedProfilingHooks.markCommitStarted(lanes); - } - } -} - -export function markCommitStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markCommitStopped === 'function' - ) { - injectedProfilingHooks.markCommitStopped(); - } - } -} - -export function markComponentRenderStarted(fiber: Fiber): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentRenderStarted === 'function' - ) { - injectedProfilingHooks.markComponentRenderStarted(fiber); - } - } -} - -export function markComponentRenderStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentRenderStopped === 'function' - ) { - injectedProfilingHooks.markComponentRenderStopped(); - } - } -} - -export function markComponentPassiveEffectMountStarted(fiber: Fiber): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === - 'function' - ) { - injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); - } - } -} - -export function markComponentPassiveEffectMountStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === - 'function' - ) { - injectedProfilingHooks.markComponentPassiveEffectMountStopped(); - } - } -} - -export function markComponentPassiveEffectUnmountStarted(fiber: Fiber): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === - 'function' - ) { - injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); - } - } -} - -export function markComponentPassiveEffectUnmountStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === - 'function' - ) { - injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); - } - } -} - -export function markComponentLayoutEffectMountStarted(fiber: Fiber): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === - 'function' - ) { - injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); - } - } -} - -export function markComponentLayoutEffectMountStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === - 'function' - ) { - injectedProfilingHooks.markComponentLayoutEffectMountStopped(); - } - } -} - -export function markComponentLayoutEffectUnmountStarted(fiber: Fiber): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === - 'function' - ) { - injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); - } - } -} - -export function markComponentLayoutEffectUnmountStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === - 'function' - ) { - injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); - } - } -} - -export function markComponentErrored( - fiber: Fiber, - thrownValue: mixed, - lanes: Lanes, -): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentErrored === 'function' - ) { - injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); - } - } -} - -export function markComponentSuspended( - fiber: Fiber, - wakeable: Wakeable, - lanes: Lanes, -): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markComponentSuspended === 'function' - ) { - injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); - } - } -} - -export function markLayoutEffectsStarted(lanes: Lanes): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function' - ) { - injectedProfilingHooks.markLayoutEffectsStarted(lanes); - } - } -} - -export function markLayoutEffectsStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function' - ) { - injectedProfilingHooks.markLayoutEffectsStopped(); - } - } -} - -export function markPassiveEffectsStarted(lanes: Lanes): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function' - ) { - injectedProfilingHooks.markPassiveEffectsStarted(lanes); - } - } -} - -export function markPassiveEffectsStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function' - ) { - injectedProfilingHooks.markPassiveEffectsStopped(); - } - } -} - -export function markRenderStarted(lanes: Lanes): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markRenderStarted === 'function' - ) { - injectedProfilingHooks.markRenderStarted(lanes); - } - } -} - -export function markRenderYielded(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markRenderYielded === 'function' - ) { - injectedProfilingHooks.markRenderYielded(); - } - } -} - -export function markRenderStopped(): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markRenderStopped === 'function' - ) { - injectedProfilingHooks.markRenderStopped(); - } - } -} - -export function markRenderScheduled(lane: Lane): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markRenderScheduled === 'function' - ) { - injectedProfilingHooks.markRenderScheduled(lane); - } - } -} - -export function markForceUpdateScheduled(fiber: Fiber, lane: Lane): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markForceUpdateScheduled === 'function' - ) { - injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); - } - } -} - -export function markStateUpdateScheduled(fiber: Fiber, lane: Lane): void { - if (enableSchedulingProfiler) { - if ( - injectedProfilingHooks !== null && - typeof injectedProfilingHooks.markStateUpdateScheduled === 'function' - ) { - injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); - } - } -} diff --git a/packages/react-reconciler/src/ReactFiberHiddenContext.new.js b/packages/react-reconciler/src/ReactFiberHiddenContext.new.js deleted file mode 100644 index f81aafbc5ad2e..0000000000000 --- a/packages/react-reconciler/src/ReactFiberHiddenContext.new.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; -import type {StackCursor} from './ReactFiberStack.new'; -import type {Lanes} from './ReactFiberLane.new'; - -import {createCursor, push, pop} from './ReactFiberStack.new'; - -import {getRenderLanes, setRenderLanes} from './ReactFiberWorkLoop.new'; -import {NoLanes, mergeLanes} from './ReactFiberLane.new'; - -// TODO: Remove `renderLanes` context in favor of hidden context -type HiddenContext = { - // Represents the lanes that must be included when processing updates in - // order to reveal the hidden content. - // TODO: Remove `subtreeLanes` context from work loop in favor of this one. - baseLanes: number, - ... -}; - -// TODO: This isn't being used yet, but it's intended to replace the -// InvisibleParentContext that is currently managed by SuspenseContext. -export const currentTreeHiddenStackCursor: StackCursor = createCursor( - null, -); -export const prevRenderLanesStackCursor: StackCursor = createCursor( - NoLanes, -); - -export function pushHiddenContext(fiber: Fiber, context: HiddenContext): void { - const prevRenderLanes = getRenderLanes(); - push(prevRenderLanesStackCursor, prevRenderLanes, fiber); - push(currentTreeHiddenStackCursor, context, fiber); - - // When rendering a subtree that's currently hidden, we must include all - // lanes that would have rendered if the hidden subtree hadn't been deferred. - // That is, in order to reveal content from hidden -> visible, we must commit - // all the updates that we skipped when we originally hid the tree. - setRenderLanes(mergeLanes(prevRenderLanes, context.baseLanes)); -} - -export function reuseHiddenContextOnStack(fiber: Fiber): void { - // This subtree is not currently hidden, so we don't need to add any lanes - // to the render lanes. But we still need to push something to avoid a - // context mismatch. Reuse the existing context on the stack. - push(prevRenderLanesStackCursor, getRenderLanes(), fiber); - push( - currentTreeHiddenStackCursor, - currentTreeHiddenStackCursor.current, - fiber, - ); -} - -export function popHiddenContext(fiber: Fiber): void { - // Restore the previous render lanes from the stack - setRenderLanes(prevRenderLanesStackCursor.current); - - pop(currentTreeHiddenStackCursor, fiber); - pop(prevRenderLanesStackCursor, fiber); -} - -export function isCurrentTreeHidden(): boolean { - return currentTreeHiddenStackCursor.current !== null; -} diff --git a/packages/react-reconciler/src/ReactFiberHooks.new.js b/packages/react-reconciler/src/ReactFiberHooks.new.js deleted file mode 100644 index a3c9eefb9cb37..0000000000000 --- a/packages/react-reconciler/src/ReactFiberHooks.new.js +++ /dev/null @@ -1,4099 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type { - MutableSource, - MutableSourceGetSnapshotFn, - MutableSourceSubscribeFn, - ReactContext, - StartTransitionOptions, - Usable, - Thenable, -} from 'shared/ReactTypes'; -import type { - Fiber, - FiberRoot, - Dispatcher, - HookType, - MemoCache, -} from './ReactInternalTypes'; -import type {Lanes, Lane} from './ReactFiberLane.new'; -import type {HookFlags} from './ReactHookEffectTags'; -import type {Flags} from './ReactFiberFlags'; - -import ReactSharedInternals from 'shared/ReactSharedInternals'; -import { - enableDebugTracing, - enableSchedulingProfiler, - enableNewReconciler, - enableCache, - enableUseRefAccessWarning, - enableLazyContextPropagation, - enableUseMutableSource, - enableTransitionTracing, - enableUseHook, - enableUseMemoCacheHook, - enableUseEventHook, - enableLegacyCache, - debugRenderPhaseSideEffectsForStrictMode, -} from 'shared/ReactFeatureFlags'; -import { - REACT_CONTEXT_TYPE, - REACT_SERVER_CONTEXT_TYPE, - REACT_MEMO_CACHE_SENTINEL, -} from 'shared/ReactSymbols'; - -import { - NoMode, - ConcurrentMode, - DebugTracingMode, - StrictEffectsMode, - StrictLegacyMode, -} from './ReactTypeOfMode'; -import { - NoLane, - SyncLane, - OffscreenLane, - NoLanes, - isSubsetOfLanes, - includesBlockingLane, - includesOnlyNonUrgentLanes, - claimNextTransitionLane, - mergeLanes, - removeLanes, - intersectLanes, - isTransitionLane, - markRootEntangled, - markRootMutableRead, - NoTimestamp, -} from './ReactFiberLane.new'; -import { - ContinuousEventPriority, - getCurrentUpdatePriority, - setCurrentUpdatePriority, - higherEventPriority, -} from './ReactEventPriorities.new'; -import {readContext, checkIfContextChanged} from './ReactFiberNewContext.new'; -import {HostRoot, CacheComponent} from './ReactWorkTags'; -import { - LayoutStatic as LayoutStaticEffect, - Passive as PassiveEffect, - PassiveStatic as PassiveStaticEffect, - StaticMask as StaticMaskEffect, - Update as UpdateEffect, - StoreConsistency, - MountLayoutDev as MountLayoutDevEffect, - MountPassiveDev as MountPassiveDevEffect, -} from './ReactFiberFlags'; -import { - HasEffect as HookHasEffect, - Layout as HookLayout, - Passive as HookPassive, - Insertion as HookInsertion, -} from './ReactHookEffectTags'; -import { - getWorkInProgressRoot, - getWorkInProgressRootRenderLanes, - scheduleUpdateOnFiber, - requestUpdateLane, - requestEventTime, - markSkippedUpdateLanes, - isInvalidExecutionContextForEventFunction, -} from './ReactFiberWorkLoop.new'; - -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import is from 'shared/objectIs'; -import isArray from 'shared/isArray'; -import { - markWorkInProgressReceivedUpdate, - checkIfWorkInProgressReceivedUpdate, -} from './ReactFiberBeginWork.new'; -import {getIsHydrating} from './ReactFiberHydrationContext.new'; -import { - getWorkInProgressVersion, - markSourceAsDirty, - setWorkInProgressVersion, - warnAboutMultipleRenderersDEV, -} from './ReactMutableSource.new'; -import {logStateUpdateScheduled} from './DebugTracing'; -import { - markStateUpdateScheduled, - setIsStrictModeForDevtools, -} from './ReactFiberDevToolsHook.new'; -import {createCache} from './ReactFiberCacheComponent.new'; -import { - createUpdate as createLegacyQueueUpdate, - enqueueUpdate as enqueueLegacyQueueUpdate, - entangleTransitions as entangleLegacyQueueTransitions, -} from './ReactFiberClassUpdateQueue.new'; -import { - enqueueConcurrentHookUpdate, - enqueueConcurrentHookUpdateAndEagerlyBailout, - enqueueConcurrentRenderForLane, -} from './ReactFiberConcurrentUpdates.new'; -import {getTreeId} from './ReactFiberTreeContext.new'; -import {now} from './Scheduler'; -import { - trackUsedThenable, - checkIfUseWrappedInTryCatch, - createThenableState, -} from './ReactFiberThenable.new'; -import type {ThenableState} from './ReactFiberThenable.new'; - -const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals; - -export type Update = { - lane: Lane, - action: A, - hasEagerState: boolean, - eagerState: S | null, - next: Update, -}; - -export type UpdateQueue = { - pending: Update | null, - lanes: Lanes, - dispatch: (A => mixed) | null, - lastRenderedReducer: ((S, A) => S) | null, - lastRenderedState: S | null, -}; - -let didWarnAboutMismatchedHooksForComponent; -let didWarnUncachedGetSnapshot; -let didWarnAboutUseWrappedInTryCatch; -if (__DEV__) { - didWarnAboutMismatchedHooksForComponent = new Set(); - didWarnAboutUseWrappedInTryCatch = new Set(); -} - -export type Hook = { - memoizedState: any, - baseState: any, - baseQueue: Update | null, - queue: any, - next: Hook | null, -}; - -export type Effect = { - tag: HookFlags, - create: () => (() => void) | void, - destroy: (() => void) | void, - deps: Array | void | null, - next: Effect, -}; - -type StoreInstance = { - value: T, - getSnapshot: () => T, -}; - -type StoreConsistencyCheck = { - value: T, - getSnapshot: () => T, -}; - -type EventFunctionPayload) => Return> = { - ref: { - eventFn: F, - impl: F, - }, - nextImpl: F, -}; - -export type FunctionComponentUpdateQueue = { - lastEffect: Effect | null, - events: Array> | null, - stores: Array> | null, - // NOTE: optional, only set when enableUseMemoCacheHook is enabled - memoCache?: MemoCache | null, -}; - -type BasicStateAction = (S => S) | S; - -type Dispatch = A => void; - -// These are set right before calling the component. -let renderLanes: Lanes = NoLanes; -// The work-in-progress fiber. I've named it differently to distinguish it from -// the work-in-progress hook. -let currentlyRenderingFiber: Fiber = (null: any); - -// Hooks are stored as a linked list on the fiber's memoizedState field. The -// current hook list is the list that belongs to the current fiber. The -// work-in-progress hook list is a new list that will be added to the -// work-in-progress fiber. -let currentHook: Hook | null = null; -let workInProgressHook: Hook | null = null; - -// Whether an update was scheduled at any point during the render phase. This -// does not get reset if we do another render pass; only when we're completely -// finished evaluating this component. This is an optimization so we know -// whether we need to clear render phase updates after a throw. -let didScheduleRenderPhaseUpdate: boolean = false; -// Where an update was scheduled only during the current render pass. This -// gets reset after each attempt. -// TODO: Maybe there's some way to consolidate this with -// `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. -let didScheduleRenderPhaseUpdateDuringThisPass: boolean = false; -let shouldDoubleInvokeUserFnsInHooksDEV: boolean = false; -// Counts the number of useId hooks in this component. -let localIdCounter: number = 0; -// Counts number of `use`-d thenables -let thenableIndexCounter: number = 0; -let thenableState: ThenableState | null = null; - -// Used for ids that are generated completely client-side (i.e. not during -// hydration). This counter is global, so client ids are not stable across -// render attempts. -let globalClientIdCounter: number = 0; - -const RE_RENDER_LIMIT = 25; - -// In DEV, this is the name of the currently executing primitive hook -let currentHookNameInDev: ?HookType = null; - -// In DEV, this list ensures that hooks are called in the same order between renders. -// The list stores the order of hooks used during the initial render (mount). -// Subsequent renders (updates) reference this list. -let hookTypesDev: Array | null = null; -let hookTypesUpdateIndexDev: number = -1; - -// In DEV, this tracks whether currently rendering component needs to ignore -// the dependencies for Hooks that need them (e.g. useEffect or useMemo). -// When true, such Hooks will always be "remounted". Only used during hot reload. -let ignorePreviousDependencies: boolean = false; - -function mountHookTypesDev() { - if (__DEV__) { - const hookName = ((currentHookNameInDev: any): HookType); - - if (hookTypesDev === null) { - hookTypesDev = [hookName]; - } else { - hookTypesDev.push(hookName); - } - } -} - -function updateHookTypesDev() { - if (__DEV__) { - const hookName = ((currentHookNameInDev: any): HookType); - - if (hookTypesDev !== null) { - hookTypesUpdateIndexDev++; - if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { - warnOnHookMismatchInDev(hookName); - } - } - } -} - -function checkDepsAreArrayDev(deps: mixed) { - if (__DEV__) { - if (deps !== undefined && deps !== null && !isArray(deps)) { - // Verify deps, but only on mount to avoid extra checks. - // It's unlikely their type would change as usually you define them inline. - console.error( - '%s received a final argument that is not an array (instead, received `%s`). When ' + - 'specified, the final argument must be an array.', - currentHookNameInDev, - typeof deps, - ); - } - } -} - -function warnOnHookMismatchInDev(currentHookName: HookType) { - if (__DEV__) { - const componentName = getComponentNameFromFiber(currentlyRenderingFiber); - if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { - didWarnAboutMismatchedHooksForComponent.add(componentName); - - if (hookTypesDev !== null) { - let table = ''; - - const secondColumnStart = 30; - - for (let i = 0; i <= ((hookTypesUpdateIndexDev: any): number); i++) { - const oldHookName = hookTypesDev[i]; - const newHookName = - i === ((hookTypesUpdateIndexDev: any): number) - ? currentHookName - : oldHookName; - - let row = `${i + 1}. ${oldHookName}`; - - // Extra space so second column lines up - // lol @ IE not supporting String#repeat - while (row.length < secondColumnStart) { - row += ' '; - } - - row += newHookName + '\n'; - - table += row; - } - - console.error( - 'React has detected a change in the order of Hooks called by %s. ' + - 'This will lead to bugs and errors if not fixed. ' + - 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + - ' Previous render Next render\n' + - ' ------------------------------------------------------\n' + - '%s' + - ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', - componentName, - table, - ); - } - } - } -} - -function throwInvalidHookError() { - throw new Error( - 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + - ' one of the following reasons:\n' + - '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + - '2. You might be breaking the Rules of Hooks\n' + - '3. You might have more than one copy of React in the same app\n' + - 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.', - ); -} - -function areHookInputsEqual( - nextDeps: Array, - prevDeps: Array | null, -) { - if (__DEV__) { - if (ignorePreviousDependencies) { - // Only true when this component is being hot reloaded. - return false; - } - } - - if (prevDeps === null) { - if (__DEV__) { - console.error( - '%s received a final argument during this render, but not during ' + - 'the previous render. Even though the final argument is optional, ' + - 'its type cannot change between renders.', - currentHookNameInDev, - ); - } - return false; - } - - if (__DEV__) { - // Don't bother comparing lengths in prod because these arrays should be - // passed inline. - if (nextDeps.length !== prevDeps.length) { - console.error( - 'The final argument passed to %s changed size between renders. The ' + - 'order and size of this array must remain constant.\n\n' + - 'Previous: %s\n' + - 'Incoming: %s', - currentHookNameInDev, - `[${prevDeps.join(', ')}]`, - `[${nextDeps.join(', ')}]`, - ); - } - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - if (is(nextDeps[i], prevDeps[i])) { - continue; - } - return false; - } - return true; -} - -export function renderWithHooks( - current: Fiber | null, - workInProgress: Fiber, - Component: (p: Props, arg: SecondArg) => any, - props: Props, - secondArg: SecondArg, - nextRenderLanes: Lanes, -): any { - renderLanes = nextRenderLanes; - currentlyRenderingFiber = workInProgress; - - if (__DEV__) { - hookTypesDev = - current !== null - ? ((current._debugHookTypes: any): Array) - : null; - hookTypesUpdateIndexDev = -1; - // Used for hot reloading: - ignorePreviousDependencies = - current !== null && current.type !== workInProgress.type; - } - - workInProgress.memoizedState = null; - workInProgress.updateQueue = null; - workInProgress.lanes = NoLanes; - - // The following should have already been reset - // currentHook = null; - // workInProgressHook = null; - - // didScheduleRenderPhaseUpdate = false; - // localIdCounter = 0; - // thenableIndexCounter = 0; - // thenableState = null; - - // TODO Warn if no hooks are used at all during mount, then some are used during update. - // Currently we will identify the update render as a mount because memoizedState === null. - // This is tricky because it's valid for certain types of components (e.g. React.lazy) - - // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. - // Non-stateful hooks (e.g. context) don't get added to memoizedState, - // so memoizedState would be null during updates and mounts. - if (__DEV__) { - if (current !== null && current.memoizedState !== null) { - ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV; - } else if (hookTypesDev !== null) { - // This dispatcher handles an edge case where a component is updating, - // but no stateful hooks have been used. - // We want to match the production code behavior (which will use HooksDispatcherOnMount), - // but with the extra DEV validation to ensure hooks ordering hasn't changed. - // This dispatcher does that. - ReactCurrentDispatcher.current = HooksDispatcherOnMountWithHookTypesInDEV; - } else { - ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV; - } - } else { - ReactCurrentDispatcher.current = - current === null || current.memoizedState === null - ? HooksDispatcherOnMount - : HooksDispatcherOnUpdate; - } - - // In Strict Mode, during development, user functions are double invoked to - // help detect side effects. The logic for how this is implemented for in - // hook components is a bit complex so let's break it down. - // - // We will invoke the entire component function twice. However, during the - // second invocation of the component, the hook state from the first - // invocation will be reused. That means things like `useMemo` functions won't - // run again, because the deps will match and the memoized result will - // be reused. - // - // We want memoized functions to run twice, too, so account for this, user - // functions are double invoked during the *first* invocation of the component - // function, and are *not* double invoked during the second incovation: - // - // - First execution of component function: user functions are double invoked - // - Second execution of component function (in Strict Mode, during - // development): user functions are not double invoked. - // - // This is intentional for a few reasons; most importantly, it's because of - // how `use` works when something suspends: it reuses the promise that was - // passed during the first attempt. This is itself a form of memoization. - // We need to be able to memoize the reactive inputs to the `use` call using - // a hook (i.e. `useMemo`), which means, the reactive inputs to `use` must - // come from the same component invocation as the output. - // - // There are plenty of tests to ensure this behavior is correct. - const shouldDoubleRenderDEV = - __DEV__ && - debugRenderPhaseSideEffectsForStrictMode && - (workInProgress.mode & StrictLegacyMode) !== NoMode; - - shouldDoubleInvokeUserFnsInHooksDEV = shouldDoubleRenderDEV; - let children = Component(props, secondArg); - shouldDoubleInvokeUserFnsInHooksDEV = false; - - // Check if there was a render phase update - if (didScheduleRenderPhaseUpdateDuringThisPass) { - // Keep rendering until the component stabilizes (there are no more render - // phase updates). - children = renderWithHooksAgain( - workInProgress, - Component, - props, - secondArg, - ); - } - - if (shouldDoubleRenderDEV) { - // In development, components are invoked twice to help detect side effects. - setIsStrictModeForDevtools(true); - try { - children = renderWithHooksAgain( - workInProgress, - Component, - props, - secondArg, - ); - } finally { - setIsStrictModeForDevtools(false); - } - } - - finishRenderingHooks(current, workInProgress); - - return children; -} - -function finishRenderingHooks(current: Fiber | null, workInProgress: Fiber) { - // We can assume the previous dispatcher is always this one, since we set it - // at the beginning of the render phase and there's no re-entrance. - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - - if (__DEV__) { - workInProgress._debugHookTypes = hookTypesDev; - } - - // This check uses currentHook so that it works the same in DEV and prod bundles. - // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. - const didRenderTooFewHooks = - currentHook !== null && currentHook.next !== null; - - renderLanes = NoLanes; - currentlyRenderingFiber = (null: any); - - currentHook = null; - workInProgressHook = null; - - if (__DEV__) { - currentHookNameInDev = null; - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; - - // Confirm that a static flag was not added or removed since the last - // render. If this fires, it suggests that we incorrectly reset the static - // flags in some other part of the codebase. This has happened before, for - // example, in the SuspenseList implementation. - if ( - current !== null && - (current.flags & StaticMaskEffect) !== - (workInProgress.flags & StaticMaskEffect) && - // Disable this warning in legacy mode, because legacy Suspense is weird - // and creates false positives. To make this work in legacy mode, we'd - // need to mark fibers that commit in an incomplete state, somehow. For - // now I'll disable the warning that most of the bugs that would trigger - // it are either exclusive to concurrent mode or exist in both. - (current.mode & ConcurrentMode) !== NoMode - ) { - console.error( - 'Internal React error: Expected static flag was missing. Please ' + - 'notify the React team.', - ); - } - } - - didScheduleRenderPhaseUpdate = false; - // This is reset by checkDidRenderIdHook - // localIdCounter = 0; - - thenableIndexCounter = 0; - thenableState = null; - - if (didRenderTooFewHooks) { - throw new Error( - 'Rendered fewer hooks than expected. This may be caused by an accidental ' + - 'early return statement.', - ); - } - - if (enableLazyContextPropagation) { - if (current !== null) { - if (!checkIfWorkInProgressReceivedUpdate()) { - // If there were no changes to props or state, we need to check if there - // was a context change. We didn't already do this because there's no - // 1:1 correspondence between dependencies and hooks. Although, because - // there almost always is in the common case (`readContext` is an - // internal API), we could compare in there. OTOH, we only hit this case - // if everything else bails out, so on the whole it might be better to - // keep the comparison out of the common path. - const currentDependencies = current.dependencies; - if ( - currentDependencies !== null && - checkIfContextChanged(currentDependencies) - ) { - markWorkInProgressReceivedUpdate(); - } - } - } - } - - if (__DEV__) { - if (checkIfUseWrappedInTryCatch()) { - const componentName = - getComponentNameFromFiber(workInProgress) || 'Unknown'; - if (!didWarnAboutUseWrappedInTryCatch.has(componentName)) { - didWarnAboutUseWrappedInTryCatch.add(componentName); - console.error( - '`use` was called from inside a try/catch block. This is not allowed ' + - 'and can lead to unexpected behavior. To handle errors triggered ' + - 'by `use`, wrap your component in a error boundary.', - ); - } - } - } -} - -export function replaySuspendedComponentWithHooks( - current: Fiber | null, - workInProgress: Fiber, - Component: (p: Props, arg: SecondArg) => any, - props: Props, - secondArg: SecondArg, -): any { - // This function is used to replay a component that previously suspended, - // after its data resolves. - // - // It's a simplified version of renderWithHooks, but it doesn't need to do - // most of the set up work because they weren't reset when we suspended; they - // only get reset when the component either completes (finishRenderingHooks) - // or unwinds (resetHooksOnUnwind). - if (__DEV__) { - hookTypesDev = - current !== null - ? ((current._debugHookTypes: any): Array) - : null; - hookTypesUpdateIndexDev = -1; - // Used for hot reloading: - ignorePreviousDependencies = - current !== null && current.type !== workInProgress.type; - } - const children = renderWithHooksAgain( - workInProgress, - Component, - props, - secondArg, - ); - finishRenderingHooks(current, workInProgress); - return children; -} - -function renderWithHooksAgain( - workInProgress: Fiber, - Component: (p: Props, arg: SecondArg) => any, - props: Props, - secondArg: SecondArg, -) { - // This is used to perform another render pass. It's used when setState is - // called during render, and for double invoking components in Strict Mode - // during development. - // - // The state from the previous pass is reused whenever possible. So, state - // updates that were already processed are not processed again, and memoized - // functions (`useMemo`) are not invoked again. - // - // Keep rendering in a loop for as long as render phase updates continue to - // be scheduled. Use a counter to prevent infinite loops. - let numberOfReRenders: number = 0; - let children; - do { - didScheduleRenderPhaseUpdateDuringThisPass = false; - thenableIndexCounter = 0; - - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error( - 'Too many re-renders. React limits the number of renders to prevent ' + - 'an infinite loop.', - ); - } - - numberOfReRenders += 1; - if (__DEV__) { - // Even when hot reloading, allow dependencies to stabilize - // after first render to prevent infinite render phase updates. - ignorePreviousDependencies = false; - } - - // Start over from the beginning of the list - currentHook = null; - workInProgressHook = null; - - workInProgress.updateQueue = null; - - if (__DEV__) { - // Also validate hook order for cascading updates. - hookTypesUpdateIndexDev = -1; - } - - ReactCurrentDispatcher.current = __DEV__ - ? HooksDispatcherOnRerenderInDEV - : HooksDispatcherOnRerender; - - children = Component(props, secondArg); - } while (didScheduleRenderPhaseUpdateDuringThisPass); - return children; -} - -export function checkDidRenderIdHook(): boolean { - // This should be called immediately after every renderWithHooks call. - // Conceptually, it's part of the return value of renderWithHooks; it's only a - // separate function to avoid using an array tuple. - const didRenderIdHook = localIdCounter !== 0; - localIdCounter = 0; - return didRenderIdHook; -} - -export function bailoutHooks( - current: Fiber, - workInProgress: Fiber, - lanes: Lanes, -) { - workInProgress.updateQueue = current.updateQueue; - // TODO: Don't need to reset the flags here, because they're reset in the - // complete phase (bubbleProperties). - if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { - workInProgress.flags &= ~( - MountPassiveDevEffect | - MountLayoutDevEffect | - PassiveEffect | - UpdateEffect - ); - } else { - workInProgress.flags &= ~(PassiveEffect | UpdateEffect); - } - current.lanes = removeLanes(current.lanes, lanes); -} - -export function resetHooksAfterThrow(): void { - // This is called immediaetly after a throw. It shouldn't reset the entire - // module state, because the work loop might decide to replay the component - // again without rewinding. - // - // It should only reset things like the current dispatcher, to prevent hooks - // from being called outside of a component. - - // We can assume the previous dispatcher is always this one, since we set it - // at the beginning of the render phase and there's no re-entrance. - ReactCurrentDispatcher.current = ContextOnlyDispatcher; -} - -export function resetHooksOnUnwind(): void { - if (didScheduleRenderPhaseUpdate) { - // There were render phase updates. These are only valid for this render - // phase, which we are now aborting. Remove the updates from the queues so - // they do not persist to the next render. Do not remove updates from hooks - // that weren't processed. - // - // Only reset the updates from the queue if it has a clone. If it does - // not have a clone, that means it wasn't processed, and the updates were - // scheduled before we entered the render phase. - let hook: Hook | null = currentlyRenderingFiber.memoizedState; - while (hook !== null) { - const queue = hook.queue; - if (queue !== null) { - queue.pending = null; - } - hook = hook.next; - } - didScheduleRenderPhaseUpdate = false; - } - - renderLanes = NoLanes; - currentlyRenderingFiber = (null: any); - - currentHook = null; - workInProgressHook = null; - - if (__DEV__) { - hookTypesDev = null; - hookTypesUpdateIndexDev = -1; - - currentHookNameInDev = null; - } - - didScheduleRenderPhaseUpdateDuringThisPass = false; - localIdCounter = 0; - thenableIndexCounter = 0; - thenableState = null; -} - -function mountWorkInProgressHook(): Hook { - const hook: Hook = { - memoizedState: null, - - baseState: null, - baseQueue: null, - queue: null, - - next: null, - }; - - if (workInProgressHook === null) { - // This is the first hook in the list - currentlyRenderingFiber.memoizedState = workInProgressHook = hook; - } else { - // Append to the end of the list - workInProgressHook = workInProgressHook.next = hook; - } - return workInProgressHook; -} - -function updateWorkInProgressHook(): Hook { - // This function is used both for updates and for re-renders triggered by a - // render phase update. It assumes there is either a current hook we can - // clone, or a work-in-progress hook from a previous render pass that we can - // use as a base. When we reach the end of the base list, we must switch to - // the dispatcher used for mounts. - let nextCurrentHook: null | Hook; - if (currentHook === null) { - const current = currentlyRenderingFiber.alternate; - if (current !== null) { - nextCurrentHook = current.memoizedState; - } else { - nextCurrentHook = null; - } - } else { - nextCurrentHook = currentHook.next; - } - - let nextWorkInProgressHook: null | Hook; - if (workInProgressHook === null) { - nextWorkInProgressHook = currentlyRenderingFiber.memoizedState; - } else { - nextWorkInProgressHook = workInProgressHook.next; - } - - if (nextWorkInProgressHook !== null) { - // There's already a work-in-progress. Reuse it. - workInProgressHook = nextWorkInProgressHook; - nextWorkInProgressHook = workInProgressHook.next; - - currentHook = nextCurrentHook; - } else { - // Clone from the current hook. - - if (nextCurrentHook === null) { - const currentFiber = currentlyRenderingFiber.alternate; - if (currentFiber === null) { - // This is the initial render. This branch is reached when the component - // suspends, resumes, then renders an additional hook. - const newHook: Hook = { - memoizedState: null, - - baseState: null, - baseQueue: null, - queue: null, - - next: null, - }; - nextCurrentHook = newHook; - } else { - // This is an update. We should always have a current hook. - throw new Error('Rendered more hooks than during the previous render.'); - } - } - - currentHook = nextCurrentHook; - - const newHook: Hook = { - memoizedState: currentHook.memoizedState, - - baseState: currentHook.baseState, - baseQueue: currentHook.baseQueue, - queue: currentHook.queue, - - next: null, - }; - - if (workInProgressHook === null) { - // This is the first hook in the list. - currentlyRenderingFiber.memoizedState = workInProgressHook = newHook; - } else { - // Append to the end of the list. - workInProgressHook = workInProgressHook.next = newHook; - } - } - return workInProgressHook; -} - -// NOTE: defining two versions of this function to avoid size impact when this feature is disabled. -// Previously this function was inlined, the additional `memoCache` property makes it not inlined. -let createFunctionComponentUpdateQueue: () => FunctionComponentUpdateQueue; -if (enableUseMemoCacheHook) { - createFunctionComponentUpdateQueue = () => { - return { - lastEffect: null, - events: null, - stores: null, - memoCache: null, - }; - }; -} else { - createFunctionComponentUpdateQueue = () => { - return { - lastEffect: null, - events: null, - stores: null, - }; - }; -} - -function use(usable: Usable): T { - if (usable !== null && typeof usable === 'object') { - // $FlowFixMe[method-unbinding] - if (typeof usable.then === 'function') { - // This is a thenable. - const thenable: Thenable = (usable: any); - - // Track the position of the thenable within this fiber. - const index = thenableIndexCounter; - thenableIndexCounter += 1; - - if (thenableState === null) { - thenableState = createThenableState(); - } - return trackUsedThenable(thenableState, thenable, index); - } else if ( - usable.$$typeof === REACT_CONTEXT_TYPE || - usable.$$typeof === REACT_SERVER_CONTEXT_TYPE - ) { - const context: ReactContext = (usable: any); - return readContext(context); - } - } - - // eslint-disable-next-line react-internal/safe-string-coercion - throw new Error('An unsupported type was passed to use(): ' + String(usable)); -} - -function useMemoCache(size: number): Array { - let memoCache = null; - // Fast-path, load memo cache from wip fiber if already prepared - let updateQueue: FunctionComponentUpdateQueue | null = (currentlyRenderingFiber.updateQueue: any); - if (updateQueue !== null) { - memoCache = updateQueue.memoCache; - } - // Otherwise clone from the current fiber - if (memoCache == null) { - const current: Fiber | null = currentlyRenderingFiber.alternate; - if (current !== null) { - const currentUpdateQueue: FunctionComponentUpdateQueue | null = (current.updateQueue: any); - if (currentUpdateQueue !== null) { - const currentMemoCache: ?MemoCache = currentUpdateQueue.memoCache; - if (currentMemoCache != null) { - memoCache = { - data: currentMemoCache.data.map(array => array.slice()), - index: 0, - }; - } - } - } - } - // Finally fall back to allocating a fresh instance of the cache - if (memoCache == null) { - memoCache = { - data: [], - index: 0, - }; - } - if (updateQueue === null) { - updateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber.updateQueue = updateQueue; - } - updateQueue.memoCache = memoCache; - - let data = memoCache.data[memoCache.index]; - if (data === undefined) { - data = memoCache.data[memoCache.index] = new Array(size); - for (let i = 0; i < size; i++) { - data[i] = REACT_MEMO_CACHE_SENTINEL; - } - } else if (data.length !== size) { - // TODO: consider warning or throwing here - if (__DEV__) { - console.error( - 'Expected a constant size argument for each invocation of useMemoCache. ' + - 'The previous cache was allocated with size %s but size %s was requested.', - data.length, - size, - ); - } - } - memoCache.index++; - return data; -} - -function basicStateReducer(state: S, action: BasicStateAction): S { - // $FlowFixMe: Flow doesn't like mixed types - return typeof action === 'function' ? action(state) : action; -} - -function mountReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, -): [S, Dispatch] { - const hook = mountWorkInProgressHook(); - let initialState; - if (init !== undefined) { - initialState = init(initialArg); - } else { - initialState = ((initialArg: any): S); - } - hook.memoizedState = hook.baseState = initialState; - const queue: UpdateQueue = { - pending: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: reducer, - lastRenderedState: (initialState: any), - }; - hook.queue = queue; - const dispatch: Dispatch = (queue.dispatch = (dispatchReducerAction.bind( - null, - currentlyRenderingFiber, - queue, - ): any)); - return [hook.memoizedState, dispatch]; -} - -function updateReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, -): [S, Dispatch] { - const hook = updateWorkInProgressHook(); - const queue = hook.queue; - - if (queue === null) { - throw new Error( - 'Should have a queue. This is likely a bug in React. Please file an issue.', - ); - } - - queue.lastRenderedReducer = reducer; - - const current: Hook = (currentHook: any); - - // The last rebase update that is NOT part of the base state. - let baseQueue = current.baseQueue; - - // The last pending update that hasn't been processed yet. - const pendingQueue = queue.pending; - if (pendingQueue !== null) { - // We have new updates that haven't been processed yet. - // We'll add them to the base queue. - if (baseQueue !== null) { - // Merge the pending queue and the base queue. - const baseFirst = baseQueue.next; - const pendingFirst = pendingQueue.next; - baseQueue.next = pendingFirst; - pendingQueue.next = baseFirst; - } - if (__DEV__) { - if (current.baseQueue !== baseQueue) { - // Internal invariant that should never happen, but feasibly could in - // the future if we implement resuming, or some form of that. - console.error( - 'Internal error: Expected work-in-progress queue to be a clone. ' + - 'This is a bug in React.', - ); - } - } - current.baseQueue = baseQueue = pendingQueue; - queue.pending = null; - } - - if (baseQueue !== null) { - // We have a queue to process. - const first = baseQueue.next; - let newState = current.baseState; - - let newBaseState = null; - let newBaseQueueFirst = null; - let newBaseQueueLast = null; - let update = first; - do { - // An extra OffscreenLane bit is added to updates that were made to - // a hidden tree, so that we can distinguish them from updates that were - // already there when the tree was hidden. - const updateLane = removeLanes(update.lane, OffscreenLane); - const isHiddenUpdate = updateLane !== update.lane; - - // Check if this update was made while the tree was hidden. If so, then - // it's not a "base" update and we should disregard the extra base lanes - // that were added to renderLanes when we entered the Offscreen tree. - const shouldSkipUpdate = isHiddenUpdate - ? !isSubsetOfLanes(getWorkInProgressRootRenderLanes(), updateLane) - : !isSubsetOfLanes(renderLanes, updateLane); - - if (shouldSkipUpdate) { - // Priority is insufficient. Skip this update. If this is the first - // skipped update, the previous update/state is the new base - // update/state. - const clone: Update = { - lane: updateLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: (null: any), - }; - if (newBaseQueueLast === null) { - newBaseQueueFirst = newBaseQueueLast = clone; - newBaseState = newState; - } else { - newBaseQueueLast = newBaseQueueLast.next = clone; - } - // Update the remaining priority in the queue. - // TODO: Don't need to accumulate this. Instead, we can remove - // renderLanes from the original lanes. - currentlyRenderingFiber.lanes = mergeLanes( - currentlyRenderingFiber.lanes, - updateLane, - ); - markSkippedUpdateLanes(updateLane); - } else { - // This update does have sufficient priority. - - if (newBaseQueueLast !== null) { - const clone: Update = { - // This update is going to be committed so we never want uncommit - // it. Using NoLane works because 0 is a subset of all bitmasks, so - // this will never be skipped by the check above. - lane: NoLane, - action: update.action, - hasEagerState: update.hasEagerState, - eagerState: update.eagerState, - next: (null: any), - }; - newBaseQueueLast = newBaseQueueLast.next = clone; - } - - // Process this update. - const action = update.action; - if (shouldDoubleInvokeUserFnsInHooksDEV) { - reducer(newState, action); - } - if (update.hasEagerState) { - // If this update is a state update (not a reducer) and was processed eagerly, - // we can use the eagerly computed state - newState = ((update.eagerState: any): S); - } else { - newState = reducer(newState, action); - } - } - update = update.next; - } while (update !== null && update !== first); - - if (newBaseQueueLast === null) { - newBaseState = newState; - } else { - newBaseQueueLast.next = (newBaseQueueFirst: any); - } - - // Mark that the fiber performed work, but only if the new state is - // different from the current state. - if (!is(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - - hook.memoizedState = newState; - hook.baseState = newBaseState; - hook.baseQueue = newBaseQueueLast; - - queue.lastRenderedState = newState; - } - - if (baseQueue === null) { - // `queue.lanes` is used for entangling transitions. We can set it back to - // zero once the queue is empty. - queue.lanes = NoLanes; - } - - const dispatch: Dispatch = (queue.dispatch: any); - return [hook.memoizedState, dispatch]; -} - -function rerenderReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, -): [S, Dispatch] { - const hook = updateWorkInProgressHook(); - const queue = hook.queue; - - if (queue === null) { - throw new Error( - 'Should have a queue. This is likely a bug in React. Please file an issue.', - ); - } - - queue.lastRenderedReducer = reducer; - - // This is a re-render. Apply the new render phase updates to the previous - // work-in-progress hook. - const dispatch: Dispatch = (queue.dispatch: any); - const lastRenderPhaseUpdate = queue.pending; - let newState = hook.memoizedState; - if (lastRenderPhaseUpdate !== null) { - // The queue doesn't persist past this render pass. - queue.pending = null; - - const firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; - let update = firstRenderPhaseUpdate; - do { - // Process this render phase update. We don't have to check the - // priority because it will always be the same as the current - // render's. - const action = update.action; - newState = reducer(newState, action); - update = update.next; - } while (update !== firstRenderPhaseUpdate); - - // Mark that the fiber performed work, but only if the new state is - // different from the current state. - if (!is(newState, hook.memoizedState)) { - markWorkInProgressReceivedUpdate(); - } - - hook.memoizedState = newState; - // Don't persist the state accumulated from the render phase updates to - // the base state unless the queue is empty. - // TODO: Not sure if this is the desired semantics, but it's what we - // do for gDSFP. I can't remember why. - if (hook.baseQueue === null) { - hook.baseState = newState; - } - - queue.lastRenderedState = newState; - } - return [newState, dispatch]; -} - -type MutableSourceMemoizedState = { - refs: { - getSnapshot: MutableSourceGetSnapshotFn, - setSnapshot: Snapshot => void, - }, - source: MutableSource, - subscribe: MutableSourceSubscribeFn, -}; - -function readFromUnsubscribedMutableSource( - root: FiberRoot, - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, -): Snapshot { - if (__DEV__) { - warnAboutMultipleRenderersDEV(source); - } - - const getVersion = source._getVersion; - const version = getVersion(source._source); - - // Is it safe for this component to read from this source during the current render? - let isSafeToReadFromSource = false; - - // Check the version first. - // If this render has already been started with a specific version, - // we can use it alone to determine if we can safely read from the source. - const currentRenderVersion = getWorkInProgressVersion(source); - if (currentRenderVersion !== null) { - // It's safe to read if the store hasn't been mutated since the last time - // we read something. - isSafeToReadFromSource = currentRenderVersion === version; - } else { - // If there's no version, then this is the first time we've read from the - // source during the current render pass, so we need to do a bit more work. - // What we need to determine is if there are any hooks that already - // subscribed to the source, and if so, whether there are any pending - // mutations that haven't been synchronized yet. - // - // If there are no pending mutations, then `root.mutableReadLanes` will be - // empty, and we know we can safely read. - // - // If there *are* pending mutations, we may still be able to safely read - // if the currently rendering lanes are inclusive of the pending mutation - // lanes, since that guarantees that the value we're about to read from - // the source is consistent with the values that we read during the most - // recent mutation. - isSafeToReadFromSource = isSubsetOfLanes( - renderLanes, - root.mutableReadLanes, - ); - - if (isSafeToReadFromSource) { - // If it's safe to read from this source during the current render, - // store the version in case other components read from it. - // A changed version number will let those components know to throw and restart the render. - setWorkInProgressVersion(source, version); - } - } - - if (isSafeToReadFromSource) { - const snapshot = getSnapshot(source._source); - if (__DEV__) { - if (typeof snapshot === 'function') { - console.error( - 'Mutable source should not return a function as the snapshot value. ' + - 'Functions may close over mutable values and cause tearing.', - ); - } - } - return snapshot; - } else { - // This handles the special case of a mutable source being shared between renderers. - // In that case, if the source is mutated between the first and second renderer, - // The second renderer don't know that it needs to reset the WIP version during unwind, - // (because the hook only marks sources as dirty if it's written to their WIP version). - // That would cause this tear check to throw again and eventually be visible to the user. - // We can avoid this infinite loop by explicitly marking the source as dirty. - // - // This can lead to tearing in the first renderer when it resumes, - // but there's nothing we can do about that (short of throwing here and refusing to continue the render). - markSourceAsDirty(source); - - // Intentioally throw an error to force React to retry synchronously. During - // the synchronous retry, it will block interleaved mutations, so we should - // get a consistent read. Therefore, the following error should never be - // visible to the user. - - // We expect this error not to be thrown during the synchronous retry, - // because we blocked interleaved mutations. - throw new Error( - 'Cannot read from mutable source during the current render without tearing. This may be a bug in React. Please file an issue.', - ); - } -} - -function useMutableSource( - hook: Hook, - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, -): Snapshot { - if (!enableUseMutableSource) { - return (undefined: any); - } - - const root = ((getWorkInProgressRoot(): any): FiberRoot); - - if (root === null) { - throw new Error( - 'Expected a work-in-progress root. This is a bug in React. Please file an issue.', - ); - } - - const getVersion = source._getVersion; - const version = getVersion(source._source); - - const dispatcher = ReactCurrentDispatcher.current; - - // eslint-disable-next-line prefer-const - let [currentSnapshot, setSnapshot] = dispatcher.useState(() => - readFromUnsubscribedMutableSource(root, source, getSnapshot), - ); - let snapshot = currentSnapshot; - - // Grab a handle to the state hook as well. - // We use it to clear the pending update queue if we have a new source. - const stateHook = ((workInProgressHook: any): Hook); - - const memoizedState = ((hook.memoizedState: any): MutableSourceMemoizedState< - Source, - Snapshot, - >); - const refs = memoizedState.refs; - const prevGetSnapshot = refs.getSnapshot; - const prevSource = memoizedState.source; - const prevSubscribe = memoizedState.subscribe; - - const fiber = currentlyRenderingFiber; - - hook.memoizedState = ({ - refs, - source, - subscribe, - }: MutableSourceMemoizedState); - - // Sync the values needed by our subscription handler after each commit. - dispatcher.useEffect(() => { - refs.getSnapshot = getSnapshot; - - // Normally the dispatch function for a state hook never changes, - // but this hook recreates the queue in certain cases to avoid updates from stale sources. - // handleChange() below needs to reference the dispatch function without re-subscribing, - // so we use a ref to ensure that it always has the latest version. - refs.setSnapshot = setSnapshot; - - // Check for a possible change between when we last rendered now. - const maybeNewVersion = getVersion(source._source); - if (!is(version, maybeNewVersion)) { - const maybeNewSnapshot = getSnapshot(source._source); - if (__DEV__) { - if (typeof maybeNewSnapshot === 'function') { - console.error( - 'Mutable source should not return a function as the snapshot value. ' + - 'Functions may close over mutable values and cause tearing.', - ); - } - } - - if (!is(snapshot, maybeNewSnapshot)) { - setSnapshot(maybeNewSnapshot); - - const lane = requestUpdateLane(fiber); - markRootMutableRead(root, lane); - } - // If the source mutated between render and now, - // there may be state updates already scheduled from the old source. - // Entangle the updates so that they render in the same batch. - markRootEntangled(root, root.mutableReadLanes); - } - }, [getSnapshot, source, subscribe]); - - // If we got a new source or subscribe function, re-subscribe in a passive effect. - dispatcher.useEffect(() => { - const handleChange = () => { - const latestGetSnapshot = refs.getSnapshot; - const latestSetSnapshot = refs.setSnapshot; - - try { - latestSetSnapshot(latestGetSnapshot(source._source)); - - // Record a pending mutable source update with the same expiration time. - const lane = requestUpdateLane(fiber); - - markRootMutableRead(root, lane); - } catch (error) { - // A selector might throw after a source mutation. - // e.g. it might try to read from a part of the store that no longer exists. - // In this case we should still schedule an update with React. - // Worst case the selector will throw again and then an error boundary will handle it. - latestSetSnapshot( - (() => { - throw error; - }: any), - ); - } - }; - - const unsubscribe = subscribe(source._source, handleChange); - if (__DEV__) { - if (typeof unsubscribe !== 'function') { - console.error( - 'Mutable source subscribe function must return an unsubscribe function.', - ); - } - } - - return unsubscribe; - }, [source, subscribe]); - - // If any of the inputs to useMutableSource change, reading is potentially unsafe. - // - // If either the source or the subscription have changed we can't can't trust the update queue. - // Maybe the source changed in a way that the old subscription ignored but the new one depends on. - // - // If the getSnapshot function changed, we also shouldn't rely on the update queue. - // It's possible that the underlying source was mutated between the when the last "change" event fired, - // and when the current render (with the new getSnapshot function) is processed. - // - // In both cases, we need to throw away pending updates (since they are no longer relevant) - // and treat reading from the source as we do in the mount case. - if ( - !is(prevGetSnapshot, getSnapshot) || - !is(prevSource, source) || - !is(prevSubscribe, subscribe) - ) { - // Create a new queue and setState method, - // So if there are interleaved updates, they get pushed to the older queue. - // When this becomes current, the previous queue and dispatch method will be discarded, - // including any interleaving updates that occur. - const newQueue: UpdateQueue> = { - pending: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: basicStateReducer, - lastRenderedState: snapshot, - }; - newQueue.dispatch = setSnapshot = (dispatchSetState.bind( - null, - currentlyRenderingFiber, - newQueue, - ): any); - stateHook.queue = newQueue; - stateHook.baseQueue = null; - snapshot = readFromUnsubscribedMutableSource(root, source, getSnapshot); - stateHook.memoizedState = stateHook.baseState = snapshot; - } - - return snapshot; -} - -function mountMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, -): Snapshot { - if (!enableUseMutableSource) { - return (undefined: any); - } - - const hook = mountWorkInProgressHook(); - hook.memoizedState = ({ - refs: { - getSnapshot, - setSnapshot: (null: any), - }, - source, - subscribe, - }: MutableSourceMemoizedState); - return useMutableSource(hook, source, getSnapshot, subscribe); -} - -function updateMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, -): Snapshot { - if (!enableUseMutableSource) { - return (undefined: any); - } - - const hook = updateWorkInProgressHook(); - return useMutableSource(hook, source, getSnapshot, subscribe); -} - -function mountSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, -): T { - const fiber = currentlyRenderingFiber; - const hook = mountWorkInProgressHook(); - - let nextSnapshot; - const isHydrating = getIsHydrating(); - if (isHydrating) { - if (getServerSnapshot === undefined) { - throw new Error( - 'Missing getServerSnapshot, which is required for ' + - 'server-rendered content. Will revert to client rendering.', - ); - } - nextSnapshot = getServerSnapshot(); - if (__DEV__) { - if (!didWarnUncachedGetSnapshot) { - if (nextSnapshot !== getServerSnapshot()) { - console.error( - 'The result of getServerSnapshot should be cached to avoid an infinite loop', - ); - didWarnUncachedGetSnapshot = true; - } - } - } - } else { - nextSnapshot = getSnapshot(); - if (__DEV__) { - if (!didWarnUncachedGetSnapshot) { - const cachedSnapshot = getSnapshot(); - if (!is(nextSnapshot, cachedSnapshot)) { - console.error( - 'The result of getSnapshot should be cached to avoid an infinite loop', - ); - didWarnUncachedGetSnapshot = true; - } - } - } - // Unless we're rendering a blocking lane, schedule a consistency check. - // Right before committing, we will walk the tree and check if any of the - // stores were mutated. - // - // We won't do this if we're hydrating server-rendered content, because if - // the content is stale, it's already visible anyway. Instead we'll patch - // it up in a passive effect. - const root: FiberRoot | null = getWorkInProgressRoot(); - - if (root === null) { - throw new Error( - 'Expected a work-in-progress root. This is a bug in React. Please file an issue.', - ); - } - - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } - - // Read the current snapshot from the store on every render. This breaks the - // normal rules of React, and only works because store updates are - // always synchronous. - hook.memoizedState = nextSnapshot; - const inst: StoreInstance = { - value: nextSnapshot, - getSnapshot, - }; - hook.queue = inst; - - // Schedule an effect to subscribe to the store. - mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); - - // Schedule an effect to update the mutable instance fields. We will update - // this whenever subscribe, getSnapshot, or value changes. Because there's no - // clean-up function, and we track the deps correctly, we can call pushEffect - // directly, without storing any additional state. For the same reason, we - // don't need to set a static flag, either. - // TODO: We can move this to the passive phase once we add a pre-commit - // consistency check. See the next comment. - fiber.flags |= PassiveEffect; - pushEffect( - HookHasEffect | HookPassive, - updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), - undefined, - null, - ); - - return nextSnapshot; -} - -function updateSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, -): T { - const fiber = currentlyRenderingFiber; - const hook = updateWorkInProgressHook(); - // Read the current snapshot from the store on every render. This breaks the - // normal rules of React, and only works because store updates are - // always synchronous. - const nextSnapshot = getSnapshot(); - if (__DEV__) { - if (!didWarnUncachedGetSnapshot) { - const cachedSnapshot = getSnapshot(); - if (!is(nextSnapshot, cachedSnapshot)) { - console.error( - 'The result of getSnapshot should be cached to avoid an infinite loop', - ); - didWarnUncachedGetSnapshot = true; - } - } - } - const prevSnapshot = (currentHook || hook).memoizedState; - const snapshotChanged = !is(prevSnapshot, nextSnapshot); - if (snapshotChanged) { - hook.memoizedState = nextSnapshot; - markWorkInProgressReceivedUpdate(); - } - const inst = hook.queue; - - updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [ - subscribe, - ]); - - // Whenever getSnapshot or subscribe changes, we need to check in the - // commit phase if there was an interleaved mutation. In concurrent mode - // this can happen all the time, but even in synchronous mode, an earlier - // effect may have mutated the store. - if ( - inst.getSnapshot !== getSnapshot || - snapshotChanged || - // Check if the susbcribe function changed. We can save some memory by - // checking whether we scheduled a subscription effect above. - (workInProgressHook !== null && - workInProgressHook.memoizedState.tag & HookHasEffect) - ) { - fiber.flags |= PassiveEffect; - pushEffect( - HookHasEffect | HookPassive, - updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), - undefined, - null, - ); - - // Unless we're rendering a blocking lane, schedule a consistency check. - // Right before committing, we will walk the tree and check if any of the - // stores were mutated. - const root: FiberRoot | null = getWorkInProgressRoot(); - - if (root === null) { - throw new Error( - 'Expected a work-in-progress root. This is a bug in React. Please file an issue.', - ); - } - - if (!includesBlockingLane(root, renderLanes)) { - pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); - } - } - - return nextSnapshot; -} - -function pushStoreConsistencyCheck( - fiber: Fiber, - getSnapshot: () => T, - renderedSnapshot: T, -) { - fiber.flags |= StoreConsistency; - const check: StoreConsistencyCheck = { - getSnapshot, - value: renderedSnapshot, - }; - let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any); - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any); - componentUpdateQueue.stores = [check]; - } else { - const stores = componentUpdateQueue.stores; - if (stores === null) { - componentUpdateQueue.stores = [check]; - } else { - stores.push(check); - } - } -} - -function updateStoreInstance( - fiber: Fiber, - inst: StoreInstance, - nextSnapshot: T, - getSnapshot: () => T, -) { - // These are updated in the passive phase - inst.value = nextSnapshot; - inst.getSnapshot = getSnapshot; - - // Something may have been mutated in between render and commit. This could - // have been in an event that fired before the passive effects, or it could - // have been in a layout effect. In that case, we would have used the old - // snapsho and getSnapshot values to bail out. We need to check one more time. - if (checkIfSnapshotChanged(inst)) { - // Force a re-render. - forceStoreRerender(fiber); - } -} - -function subscribeToStore(fiber, inst: StoreInstance, subscribe) { - const handleStoreChange = () => { - // The store changed. Check if the snapshot changed since the last time we - // read from the store. - if (checkIfSnapshotChanged(inst)) { - // Force a re-render. - forceStoreRerender(fiber); - } - }; - // Subscribe to the store and return a clean-up function. - return subscribe(handleStoreChange); -} - -function checkIfSnapshotChanged(inst: StoreInstance): boolean { - const latestGetSnapshot = inst.getSnapshot; - const prevValue = inst.value; - try { - const nextValue = latestGetSnapshot(); - return !is(prevValue, nextValue); - } catch (error) { - return true; - } -} - -function forceStoreRerender(fiber) { - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } -} - -function mountState( - initialState: (() => S) | S, -): [S, Dispatch>] { - const hook = mountWorkInProgressHook(); - if (typeof initialState === 'function') { - // $FlowFixMe: Flow doesn't like mixed types - initialState = initialState(); - } - hook.memoizedState = hook.baseState = initialState; - const queue: UpdateQueue> = { - pending: null, - lanes: NoLanes, - dispatch: null, - lastRenderedReducer: basicStateReducer, - lastRenderedState: (initialState: any), - }; - hook.queue = queue; - const dispatch: Dispatch< - BasicStateAction, - > = (queue.dispatch = (dispatchSetState.bind( - null, - currentlyRenderingFiber, - queue, - ): any)); - return [hook.memoizedState, dispatch]; -} - -function updateState( - initialState: (() => S) | S, -): [S, Dispatch>] { - return updateReducer(basicStateReducer, (initialState: any)); -} - -function rerenderState( - initialState: (() => S) | S, -): [S, Dispatch>] { - return rerenderReducer(basicStateReducer, (initialState: any)); -} - -function pushEffect(tag, create, destroy, deps: Array | void | null) { - const effect: Effect = { - tag, - create, - destroy, - deps, - // Circular - next: (null: any), - }; - let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any); - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any); - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - const lastEffect = componentUpdateQueue.lastEffect; - if (lastEffect === null) { - componentUpdateQueue.lastEffect = effect.next = effect; - } else { - const firstEffect = lastEffect.next; - lastEffect.next = effect; - effect.next = firstEffect; - componentUpdateQueue.lastEffect = effect; - } - } - return effect; -} - -let stackContainsErrorMessage: boolean | null = null; - -function getCallerStackFrame(): string { - // eslint-disable-next-line react-internal/prod-error-codes - const stackFrames = new Error('Error message').stack.split('\n'); - - // Some browsers (e.g. Chrome) include the error message in the stack - // but others (e.g. Firefox) do not. - if (stackContainsErrorMessage === null) { - stackContainsErrorMessage = stackFrames[0].includes('Error message'); - } - - return stackContainsErrorMessage - ? stackFrames.slice(3, 4).join('\n') - : stackFrames.slice(2, 3).join('\n'); -} - -function mountRef(initialValue: T): {current: T} { - const hook = mountWorkInProgressHook(); - if (enableUseRefAccessWarning) { - if (__DEV__) { - // Support lazy initialization pattern shown in docs. - // We need to store the caller stack frame so that we don't warn on subsequent renders. - let hasBeenInitialized = initialValue != null; - let lazyInitGetterStack = null; - let didCheckForLazyInit = false; - - // Only warn once per component+hook. - let didWarnAboutRead = false; - let didWarnAboutWrite = false; - - let current = initialValue; - const ref = { - get current() { - if (!hasBeenInitialized) { - didCheckForLazyInit = true; - lazyInitGetterStack = getCallerStackFrame(); - } else if (currentlyRenderingFiber !== null && !didWarnAboutRead) { - if ( - lazyInitGetterStack === null || - lazyInitGetterStack !== getCallerStackFrame() - ) { - didWarnAboutRead = true; - console.warn( - '%s: Unsafe read of a mutable value during render.\n\n' + - 'Reading from a ref during render is only safe if:\n' + - '1. The ref value has not been updated, or\n' + - '2. The ref holds a lazily-initialized value that is only set once.\n', - getComponentNameFromFiber(currentlyRenderingFiber) || 'Unknown', - ); - } - } - return current; - }, - set current(value) { - if (currentlyRenderingFiber !== null && !didWarnAboutWrite) { - if (hasBeenInitialized || !didCheckForLazyInit) { - didWarnAboutWrite = true; - console.warn( - '%s: Unsafe write of a mutable value during render.\n\n' + - 'Writing to a ref during render is only safe if the ref holds ' + - 'a lazily-initialized value that is only set once.\n', - getComponentNameFromFiber(currentlyRenderingFiber) || 'Unknown', - ); - } - } - - hasBeenInitialized = true; - current = value; - }, - }; - Object.seal(ref); - hook.memoizedState = ref; - return ref; - } else { - const ref = {current: initialValue}; - hook.memoizedState = ref; - return ref; - } - } else { - const ref = {current: initialValue}; - hook.memoizedState = ref; - return ref; - } -} - -function updateRef(initialValue: T): {current: T} { - const hook = updateWorkInProgressHook(); - return hook.memoizedState; -} - -function mountEffectImpl( - fiberFlags, - hookFlags, - create, - deps: Array | void | null, -): void { - const hook = mountWorkInProgressHook(); - const nextDeps = deps === undefined ? null : deps; - currentlyRenderingFiber.flags |= fiberFlags; - hook.memoizedState = pushEffect( - HookHasEffect | hookFlags, - create, - undefined, - nextDeps, - ); -} - -function updateEffectImpl( - fiberFlags, - hookFlags, - create, - deps: Array | void | null, -): void { - const hook = updateWorkInProgressHook(); - const nextDeps = deps === undefined ? null : deps; - let destroy = undefined; - - if (currentHook !== null) { - const prevEffect = currentHook.memoizedState; - destroy = prevEffect.destroy; - if (nextDeps !== null) { - const prevDeps = prevEffect.deps; - if (areHookInputsEqual(nextDeps, prevDeps)) { - hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); - return; - } - } - } - - currentlyRenderingFiber.flags |= fiberFlags; - - hook.memoizedState = pushEffect( - HookHasEffect | hookFlags, - create, - destroy, - nextDeps, - ); -} - -function mountEffect( - create: () => (() => void) | void, - deps: Array | void | null, -): void { - if ( - __DEV__ && - (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode - ) { - return mountEffectImpl( - MountPassiveDevEffect | PassiveEffect | PassiveStaticEffect, - HookPassive, - create, - deps, - ); - } else { - return mountEffectImpl( - PassiveEffect | PassiveStaticEffect, - HookPassive, - create, - deps, - ); - } -} - -function updateEffect( - create: () => (() => void) | void, - deps: Array | void | null, -): void { - return updateEffectImpl(PassiveEffect, HookPassive, create, deps); -} - -function useEventImpl) => Return>( - payload: EventFunctionPayload, -) { - currentlyRenderingFiber.flags |= UpdateEffect; - let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any); - if (componentUpdateQueue === null) { - componentUpdateQueue = createFunctionComponentUpdateQueue(); - currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any); - componentUpdateQueue.events = [payload]; - } else { - const events = componentUpdateQueue.events; - if (events === null) { - componentUpdateQueue.events = [payload]; - } else { - events.push(payload); - } - } -} - -function mountEvent) => Return>( - callback: F, -): F { - const hook = mountWorkInProgressHook(); - const ref = {impl: callback}; - hook.memoizedState = ref; - // $FlowIgnore[incompatible-return] - return function eventFn() { - if (isInvalidExecutionContextForEventFunction()) { - throw new Error( - "A function wrapped in useEvent can't be called during rendering.", - ); - } - return ref.impl.apply(undefined, arguments); - }; -} - -function updateEvent) => Return>( - callback: F, -): F { - const hook = updateWorkInProgressHook(); - const ref = hook.memoizedState; - useEventImpl({ref, nextImpl: callback}); - // $FlowIgnore[incompatible-return] - return function eventFn() { - if (isInvalidExecutionContextForEventFunction()) { - throw new Error( - "A function wrapped in useEvent can't be called during rendering.", - ); - } - return ref.impl.apply(undefined, arguments); - }; -} - -function mountInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, -): void { - return mountEffectImpl(UpdateEffect, HookInsertion, create, deps); -} - -function updateInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, -): void { - return updateEffectImpl(UpdateEffect, HookInsertion, create, deps); -} - -function mountLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, -): void { - let fiberFlags: Flags = UpdateEffect | LayoutStaticEffect; - if ( - __DEV__ && - (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode - ) { - fiberFlags |= MountLayoutDevEffect; - } - return mountEffectImpl(fiberFlags, HookLayout, create, deps); -} - -function updateLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, -): void { - return updateEffectImpl(UpdateEffect, HookLayout, create, deps); -} - -function imperativeHandleEffect( - create: () => T, - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, -) { - if (typeof ref === 'function') { - const refCallback = ref; - const inst = create(); - refCallback(inst); - return () => { - refCallback(null); - }; - } else if (ref !== null && ref !== undefined) { - const refObject = ref; - if (__DEV__) { - if (!refObject.hasOwnProperty('current')) { - console.error( - 'Expected useImperativeHandle() first argument to either be a ' + - 'ref callback or React.createRef() object. Instead received: %s.', - 'an object with keys {' + Object.keys(refObject).join(', ') + '}', - ); - } - } - const inst = create(); - refObject.current = inst; - return () => { - refObject.current = null; - }; - } -} - -function mountImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, -): void { - if (__DEV__) { - if (typeof create !== 'function') { - console.error( - 'Expected useImperativeHandle() second argument to be a function ' + - 'that creates a handle. Instead received: %s.', - create !== null ? typeof create : 'null', - ); - } - } - - // TODO: If deps are provided, should we skip comparing the ref itself? - const effectDeps = - deps !== null && deps !== undefined ? deps.concat([ref]) : null; - - let fiberFlags: Flags = UpdateEffect | LayoutStaticEffect; - if ( - __DEV__ && - (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode - ) { - fiberFlags |= MountLayoutDevEffect; - } - return mountEffectImpl( - fiberFlags, - HookLayout, - imperativeHandleEffect.bind(null, create, ref), - effectDeps, - ); -} - -function updateImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, -): void { - if (__DEV__) { - if (typeof create !== 'function') { - console.error( - 'Expected useImperativeHandle() second argument to be a function ' + - 'that creates a handle. Instead received: %s.', - create !== null ? typeof create : 'null', - ); - } - } - - // TODO: If deps are provided, should we skip comparing the ref itself? - const effectDeps = - deps !== null && deps !== undefined ? deps.concat([ref]) : null; - - return updateEffectImpl( - UpdateEffect, - HookLayout, - imperativeHandleEffect.bind(null, create, ref), - effectDeps, - ); -} - -function mountDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - // This hook is normally a no-op. - // The react-debug-hooks package injects its own implementation - // so that e.g. DevTools can display custom hook values. -} - -const updateDebugValue = mountDebugValue; - -function mountCallback(callback: T, deps: Array | void | null): T { - const hook = mountWorkInProgressHook(); - const nextDeps = deps === undefined ? null : deps; - hook.memoizedState = [callback, nextDeps]; - return callback; -} - -function updateCallback(callback: T, deps: Array | void | null): T { - const hook = updateWorkInProgressHook(); - const nextDeps = deps === undefined ? null : deps; - const prevState = hook.memoizedState; - if (prevState !== null) { - if (nextDeps !== null) { - const prevDeps: Array | null = prevState[1]; - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - hook.memoizedState = [callback, nextDeps]; - return callback; -} - -function mountMemo( - nextCreate: () => T, - deps: Array | void | null, -): T { - const hook = mountWorkInProgressHook(); - const nextDeps = deps === undefined ? null : deps; - if (shouldDoubleInvokeUserFnsInHooksDEV) { - nextCreate(); - } - const nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; -} - -function updateMemo( - nextCreate: () => T, - deps: Array | void | null, -): T { - const hook = updateWorkInProgressHook(); - const nextDeps = deps === undefined ? null : deps; - const prevState = hook.memoizedState; - if (prevState !== null) { - // Assume these are defined. If they're not, areHookInputsEqual will warn. - if (nextDeps !== null) { - const prevDeps: Array | null = prevState[1]; - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - if (shouldDoubleInvokeUserFnsInHooksDEV) { - nextCreate(); - } - const nextValue = nextCreate(); - hook.memoizedState = [nextValue, nextDeps]; - return nextValue; -} - -function mountDeferredValue(value: T): T { - const hook = mountWorkInProgressHook(); - hook.memoizedState = value; - return value; -} - -function updateDeferredValue(value: T): T { - const hook = updateWorkInProgressHook(); - const resolvedCurrentHook: Hook = (currentHook: any); - const prevValue: T = resolvedCurrentHook.memoizedState; - return updateDeferredValueImpl(hook, prevValue, value); -} - -function rerenderDeferredValue(value: T): T { - const hook = updateWorkInProgressHook(); - if (currentHook === null) { - // This is a rerender during a mount. - hook.memoizedState = value; - return value; - } else { - // This is a rerender during an update. - const prevValue: T = currentHook.memoizedState; - return updateDeferredValueImpl(hook, prevValue, value); - } -} - -function updateDeferredValueImpl(hook: Hook, prevValue: T, value: T): T { - const shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes); - if (shouldDeferValue) { - // This is an urgent update. If the value has changed, keep using the - // previous value and spawn a deferred render to update it later. - - if (!is(value, prevValue)) { - // Schedule a deferred render - const deferredLane = claimNextTransitionLane(); - currentlyRenderingFiber.lanes = mergeLanes( - currentlyRenderingFiber.lanes, - deferredLane, - ); - markSkippedUpdateLanes(deferredLane); - - // Set this to true to indicate that the rendered value is inconsistent - // from the latest value. The name "baseState" doesn't really match how we - // use it because we're reusing a state hook field instead of creating a - // new one. - hook.baseState = true; - } - - // Reuse the previous value - return prevValue; - } else { - // This is not an urgent update, so we can use the latest value regardless - // of what it is. No need to defer it. - - // However, if we're currently inside a spawned render, then we need to mark - // this as an update to prevent the fiber from bailing out. - // - // `baseState` is true when the current value is different from the rendered - // value. The name doesn't really match how we use it because we're reusing - // a state hook field instead of creating a new one. - if (hook.baseState) { - // Flip this back to false. - hook.baseState = false; - markWorkInProgressReceivedUpdate(); - } - - hook.memoizedState = value; - return value; - } -} - -function startTransition(setPending, callback, options) { - const previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority( - higherEventPriority(previousPriority, ContinuousEventPriority), - ); - - setPending(true); - - const prevTransition = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = {}; - const currentTransition = ReactCurrentBatchConfig.transition; - - if (enableTransitionTracing) { - if (options !== undefined && options.name !== undefined) { - ReactCurrentBatchConfig.transition.name = options.name; - ReactCurrentBatchConfig.transition.startTime = now(); - } - } - - if (__DEV__) { - ReactCurrentBatchConfig.transition._updatedFibers = new Set(); - } - - try { - setPending(false); - callback(); - } finally { - setCurrentUpdatePriority(previousPriority); - - ReactCurrentBatchConfig.transition = prevTransition; - - if (__DEV__) { - if (prevTransition === null && currentTransition._updatedFibers) { - const updatedFibersCount = currentTransition._updatedFibers.size; - if (updatedFibersCount > 10) { - console.warn( - 'Detected a large number of updates inside startTransition. ' + - 'If this is due to a subscription please re-write it to use React provided hooks. ' + - 'Otherwise concurrent mode guarantees are off the table.', - ); - } - currentTransition._updatedFibers.clear(); - } - } - } -} - -function mountTransition(): [ - boolean, - (callback: () => void, options?: StartTransitionOptions) => void, -] { - const [isPending, setPending] = mountState(false); - // The `start` method never changes. - const start = startTransition.bind(null, setPending); - const hook = mountWorkInProgressHook(); - hook.memoizedState = start; - return [isPending, start]; -} - -function updateTransition(): [ - boolean, - (callback: () => void, options?: StartTransitionOptions) => void, -] { - const [isPending] = updateState(false); - const hook = updateWorkInProgressHook(); - const start = hook.memoizedState; - return [isPending, start]; -} - -function rerenderTransition(): [ - boolean, - (callback: () => void, options?: StartTransitionOptions) => void, -] { - const [isPending] = rerenderState(false); - const hook = updateWorkInProgressHook(); - const start = hook.memoizedState; - return [isPending, start]; -} - -function mountId(): string { - const hook = mountWorkInProgressHook(); - - const root = ((getWorkInProgressRoot(): any): FiberRoot); - // TODO: In Fizz, id generation is specific to each server config. Maybe we - // should do this in Fiber, too? Deferring this decision for now because - // there's no other place to store the prefix except for an internal field on - // the public createRoot object, which the fiber tree does not currently have - // a reference to. - const identifierPrefix = root.identifierPrefix; - - let id; - if (getIsHydrating()) { - const treeId = getTreeId(); - - // Use a captial R prefix for server-generated ids. - id = ':' + identifierPrefix + 'R' + treeId; - - // Unless this is the first id at this level, append a number at the end - // that represents the position of this useId hook among all the useId - // hooks for this fiber. - const localId = localIdCounter++; - if (localId > 0) { - id += 'H' + localId.toString(32); - } - - id += ':'; - } else { - // Use a lowercase r prefix for client-generated ids. - const globalClientId = globalClientIdCounter++; - id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; - } - - hook.memoizedState = id; - return id; -} - -function updateId(): string { - const hook = updateWorkInProgressHook(); - const id: string = hook.memoizedState; - return id; -} - -function mountRefresh() { - const hook = mountWorkInProgressHook(); - const refresh = (hook.memoizedState = refreshCache.bind( - null, - currentlyRenderingFiber, - )); - return refresh; -} - -function updateRefresh() { - const hook = updateWorkInProgressHook(); - return hook.memoizedState; -} - -function refreshCache(fiber: Fiber, seedKey: ?() => T, seedValue: T) { - if (!enableCache) { - return; - } - // TODO: Does Cache work in legacy mode? Should decide and write a test. - // TODO: Consider warning if the refresh is at discrete priority, or if we - // otherwise suspect that it wasn't batched properly. - let provider = fiber.return; - while (provider !== null) { - switch (provider.tag) { - case CacheComponent: - case HostRoot: { - // Schedule an update on the cache boundary to trigger a refresh. - const lane = requestUpdateLane(provider); - const eventTime = requestEventTime(); - const refreshUpdate = createLegacyQueueUpdate(eventTime, lane); - const root = enqueueLegacyQueueUpdate(provider, refreshUpdate, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, provider, lane, eventTime); - entangleLegacyQueueTransitions(root, provider, lane); - } - - // TODO: If a refresh never commits, the new cache created here must be - // released. A simple case is start refreshing a cache boundary, but then - // unmount that boundary before the refresh completes. - const seededCache = createCache(); - if (seedKey !== null && seedKey !== undefined && root !== null) { - if (enableLegacyCache) { - // Seed the cache with the value passed by the caller. This could be - // from a server mutation, or it could be a streaming response. - seededCache.data.set(seedKey, seedValue); - } else { - if (__DEV__) { - console.error( - 'The seed argument is not enabled outside experimental channels.', - ); - } - } - } - - const payload = { - cache: seededCache, - }; - refreshUpdate.payload = payload; - return; - } - } - provider = provider.return; - } - // TODO: Warn if unmounted? -} - -function dispatchReducerAction( - fiber: Fiber, - queue: UpdateQueue, - action: A, -) { - if (__DEV__) { - if (typeof arguments[3] === 'function') { - console.error( - "State updates from the useState() and useReducer() Hooks don't support the " + - 'second callback argument. To execute a side effect after ' + - 'rendering, declare it in the component body with useEffect().', - ); - } - } - - const lane = requestUpdateLane(fiber); - - const update: Update = { - lane, - action, - hasEagerState: false, - eagerState: null, - next: (null: any), - }; - - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - const root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); - if (root !== null) { - const eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitionUpdate(root, queue, lane); - } - } - - markUpdateInDevTools(fiber, lane, action); -} - -function dispatchSetState( - fiber: Fiber, - queue: UpdateQueue, - action: A, -) { - if (__DEV__) { - if (typeof arguments[3] === 'function') { - console.error( - "State updates from the useState() and useReducer() Hooks don't support the " + - 'second callback argument. To execute a side effect after ' + - 'rendering, declare it in the component body with useEffect().', - ); - } - } - - const lane = requestUpdateLane(fiber); - - const update: Update = { - lane, - action, - hasEagerState: false, - eagerState: null, - next: (null: any), - }; - - if (isRenderPhaseUpdate(fiber)) { - enqueueRenderPhaseUpdate(queue, update); - } else { - const alternate = fiber.alternate; - if ( - fiber.lanes === NoLanes && - (alternate === null || alternate.lanes === NoLanes) - ) { - // The queue is currently empty, which means we can eagerly compute the - // next state before entering the render phase. If the new state is the - // same as the current state, we may be able to bail out entirely. - const lastRenderedReducer = queue.lastRenderedReducer; - if (lastRenderedReducer !== null) { - let prevDispatcher; - if (__DEV__) { - prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - } - try { - const currentState: S = (queue.lastRenderedState: any); - const eagerState = lastRenderedReducer(currentState, action); - // Stash the eagerly computed state, and the reducer used to compute - // it, on the update object. If the reducer hasn't changed by the - // time we enter the render phase, then the eager state can be used - // without calling the reducer again. - update.hasEagerState = true; - update.eagerState = eagerState; - if (is(eagerState, currentState)) { - // Fast path. We can bail out without scheduling React to re-render. - // It's still possible that we'll need to rebase this update later, - // if the component re-renders for a different reason and by that - // time the reducer has changed. - // TODO: Do we still need to entangle transitions in this case? - enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update); - return; - } - } catch (error) { - // Suppress the error. It will throw again in the render phase. - } finally { - if (__DEV__) { - ReactCurrentDispatcher.current = prevDispatcher; - } - } - } - } - - const root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); - if (root !== null) { - const eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - entangleTransitionUpdate(root, queue, lane); - } - } - - markUpdateInDevTools(fiber, lane, action); -} - -function isRenderPhaseUpdate(fiber: Fiber) { - const alternate = fiber.alternate; - return ( - fiber === currentlyRenderingFiber || - (alternate !== null && alternate === currentlyRenderingFiber) - ); -} - -function enqueueRenderPhaseUpdate( - queue: UpdateQueue, - update: Update, -) { - // This is a render phase update. Stash it in a lazily-created map of - // queue -> linked list of updates. After this render pass, we'll restart - // and apply the stashed updates on top of the work-in-progress hook. - didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; - const pending = queue.pending; - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - queue.pending = update; -} - -// TODO: Move to ReactFiberConcurrentUpdates? -function entangleTransitionUpdate( - root: FiberRoot, - queue: UpdateQueue, - lane: Lane, -) { - if (isTransitionLane(lane)) { - let queueLanes = queue.lanes; - - // If any entangled lanes are no longer pending on the root, then they - // must have finished. We can remove them from the shared queue, which - // represents a superset of the actually pending lanes. In some cases we - // may entangle more than we need to, but that's OK. In fact it's worse if - // we *don't* entangle when we should. - queueLanes = intersectLanes(queueLanes, root.pendingLanes); - - // Entangle the new transition lane with the other transition lanes. - const newQueueLanes = mergeLanes(queueLanes, lane); - queue.lanes = newQueueLanes; - // Even if queue.lanes already include lane, we don't know for certain if - // the lane finished since the last time we entangled it. So we need to - // entangle it again, just to be sure. - markRootEntangled(root, newQueueLanes); - } -} - -function markUpdateInDevTools(fiber, lane, action: A) { - if (__DEV__) { - if (enableDebugTracing) { - if (fiber.mode & DebugTracingMode) { - const name = getComponentNameFromFiber(fiber) || 'Unknown'; - logStateUpdateScheduled(name, lane, action); - } - } - } - - if (enableSchedulingProfiler) { - markStateUpdateScheduled(fiber, lane); - } -} - -export const ContextOnlyDispatcher: Dispatcher = { - readContext, - - useCallback: throwInvalidHookError, - useContext: throwInvalidHookError, - useEffect: throwInvalidHookError, - useImperativeHandle: throwInvalidHookError, - useInsertionEffect: throwInvalidHookError, - useLayoutEffect: throwInvalidHookError, - useMemo: throwInvalidHookError, - useReducer: throwInvalidHookError, - useRef: throwInvalidHookError, - useState: throwInvalidHookError, - useDebugValue: throwInvalidHookError, - useDeferredValue: throwInvalidHookError, - useTransition: throwInvalidHookError, - useMutableSource: throwInvalidHookError, - useSyncExternalStore: throwInvalidHookError, - useId: throwInvalidHookError, - - unstable_isNewReconciler: enableNewReconciler, -}; -if (enableCache) { - (ContextOnlyDispatcher: Dispatcher).useCacheRefresh = throwInvalidHookError; -} -if (enableUseHook) { - (ContextOnlyDispatcher: Dispatcher).use = throwInvalidHookError; -} -if (enableUseMemoCacheHook) { - (ContextOnlyDispatcher: Dispatcher).useMemoCache = throwInvalidHookError; -} -if (enableUseEventHook) { - (ContextOnlyDispatcher: Dispatcher).useEvent = throwInvalidHookError; -} - -const HooksDispatcherOnMount: Dispatcher = { - readContext, - - useCallback: mountCallback, - useContext: readContext, - useEffect: mountEffect, - useImperativeHandle: mountImperativeHandle, - useLayoutEffect: mountLayoutEffect, - useInsertionEffect: mountInsertionEffect, - useMemo: mountMemo, - useReducer: mountReducer, - useRef: mountRef, - useState: mountState, - useDebugValue: mountDebugValue, - useDeferredValue: mountDeferredValue, - useTransition: mountTransition, - useMutableSource: mountMutableSource, - useSyncExternalStore: mountSyncExternalStore, - useId: mountId, - - unstable_isNewReconciler: enableNewReconciler, -}; -if (enableCache) { - // $FlowFixMe[escaped-generic] discovered when updating Flow - (HooksDispatcherOnMount: Dispatcher).useCacheRefresh = mountRefresh; -} -if (enableUseHook) { - (HooksDispatcherOnMount: Dispatcher).use = use; -} -if (enableUseMemoCacheHook) { - (HooksDispatcherOnMount: Dispatcher).useMemoCache = useMemoCache; -} -if (enableUseEventHook) { - (HooksDispatcherOnMount: Dispatcher).useEvent = mountEvent; -} -const HooksDispatcherOnUpdate: Dispatcher = { - readContext, - - useCallback: updateCallback, - useContext: readContext, - useEffect: updateEffect, - useImperativeHandle: updateImperativeHandle, - useInsertionEffect: updateInsertionEffect, - useLayoutEffect: updateLayoutEffect, - useMemo: updateMemo, - useReducer: updateReducer, - useRef: updateRef, - useState: updateState, - useDebugValue: updateDebugValue, - useDeferredValue: updateDeferredValue, - useTransition: updateTransition, - useMutableSource: updateMutableSource, - useSyncExternalStore: updateSyncExternalStore, - useId: updateId, - - unstable_isNewReconciler: enableNewReconciler, -}; -if (enableCache) { - (HooksDispatcherOnUpdate: Dispatcher).useCacheRefresh = updateRefresh; -} -if (enableUseMemoCacheHook) { - (HooksDispatcherOnUpdate: Dispatcher).useMemoCache = useMemoCache; -} -if (enableUseHook) { - (HooksDispatcherOnUpdate: Dispatcher).use = use; -} -if (enableUseEventHook) { - (HooksDispatcherOnUpdate: Dispatcher).useEvent = updateEvent; -} - -const HooksDispatcherOnRerender: Dispatcher = { - readContext, - - useCallback: updateCallback, - useContext: readContext, - useEffect: updateEffect, - useImperativeHandle: updateImperativeHandle, - useInsertionEffect: updateInsertionEffect, - useLayoutEffect: updateLayoutEffect, - useMemo: updateMemo, - useReducer: rerenderReducer, - useRef: updateRef, - useState: rerenderState, - useDebugValue: updateDebugValue, - useDeferredValue: rerenderDeferredValue, - useTransition: rerenderTransition, - useMutableSource: updateMutableSource, - useSyncExternalStore: updateSyncExternalStore, - useId: updateId, - - unstable_isNewReconciler: enableNewReconciler, -}; -if (enableCache) { - (HooksDispatcherOnRerender: Dispatcher).useCacheRefresh = updateRefresh; -} -if (enableUseHook) { - (HooksDispatcherOnRerender: Dispatcher).use = use; -} -if (enableUseMemoCacheHook) { - (HooksDispatcherOnRerender: Dispatcher).useMemoCache = useMemoCache; -} -if (enableUseEventHook) { - (HooksDispatcherOnRerender: Dispatcher).useEvent = updateEvent; -} - -let HooksDispatcherOnMountInDEV: Dispatcher | null = null; -let HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher | null = null; -let HooksDispatcherOnUpdateInDEV: Dispatcher | null = null; -let HooksDispatcherOnRerenderInDEV: Dispatcher | null = null; -let InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher | null = null; -let InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher | null = null; -let InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher | null = null; - -if (__DEV__) { - const warnInvalidContextAccess = () => { - console.error( - 'Context can only be read while React is rendering. ' + - 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + - 'In function components, you can read it directly in the function body, but not ' + - 'inside Hooks like useReducer() or useMemo().', - ); - }; - - const warnInvalidHookAccess = () => { - console.error( - 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + - 'You can only call Hooks at the top level of your React function. ' + - 'For more information, see ' + - 'https://reactjs.org/link/rules-of-hooks', - ); - }; - - HooksDispatcherOnMountInDEV = { - readContext(context: ReactContext): T { - return readContext(context); - }, - useCallback(callback: T, deps: Array | void | null): T { - currentHookNameInDev = 'useCallback'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountCallback(callback, deps); - }, - useContext(context: ReactContext): T { - currentHookNameInDev = 'useContext'; - mountHookTypesDev(); - return readContext(context); - }, - useEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountEffect(create, deps); - }, - useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useImperativeHandle'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useInsertionEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useLayoutEffect'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - return mountLayoutEffect(create, deps); - }, - useMemo(create: () => T, deps: Array | void | null): T { - currentHookNameInDev = 'useMemo'; - mountHookTypesDev(); - checkDepsAreArrayDev(deps); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, - ): [S, Dispatch] { - currentHookNameInDev = 'useReducer'; - mountHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useRef(initialValue: T): {current: T} { - currentHookNameInDev = 'useRef'; - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState( - initialState: (() => S) | S, - ): [S, Dispatch>] { - currentHookNameInDev = 'useState'; - mountHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - currentHookNameInDev = 'useDebugValue'; - mountHookTypesDev(); - return mountDebugValue(value, formatterFn); - }, - useDeferredValue(value: T): T { - currentHookNameInDev = 'useDeferredValue'; - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition(): [boolean, (() => void) => void] { - currentHookNameInDev = 'useTransition'; - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, - ): Snapshot { - currentHookNameInDev = 'useMutableSource'; - mountHookTypesDev(); - return mountMutableSource(source, getSnapshot, subscribe); - }, - useSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, - ): T { - currentHookNameInDev = 'useSyncExternalStore'; - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId(): string { - currentHookNameInDev = 'useId'; - mountHookTypesDev(); - return mountId(); - }, - - unstable_isNewReconciler: enableNewReconciler, - }; - if (enableCache) { - (HooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { - currentHookNameInDev = 'useCacheRefresh'; - mountHookTypesDev(); - return mountRefresh(); - }; - } - if (enableUseHook) { - (HooksDispatcherOnMountInDEV: Dispatcher).use = use; - } - if (enableUseMemoCacheHook) { - (HooksDispatcherOnMountInDEV: Dispatcher).useMemoCache = useMemoCache; - } - if (enableUseEventHook) { - (HooksDispatcherOnMountInDEV: Dispatcher).useEvent = function useEvent< - Args, - Return, - F: (...Array) => Return, - >(callback: F): F { - currentHookNameInDev = 'useEvent'; - mountHookTypesDev(); - return mountEvent(callback); - }; - } - - HooksDispatcherOnMountWithHookTypesInDEV = { - readContext(context: ReactContext): T { - return readContext(context); - }, - useCallback(callback: T, deps: Array | void | null): T { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext(context: ReactContext): T { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo(create: () => T, deps: Array | void | null): T { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, - ): [S, Dispatch] { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useRef(initialValue: T): {current: T} { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return mountRef(initialValue); - }, - useState( - initialState: (() => S) | S, - ): [S, Dispatch>] { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return mountDebugValue(value, formatterFn); - }, - useDeferredValue(value: T): T { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition(): [boolean, (() => void) => void] { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return mountTransition(); - }, - useMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, - ): Snapshot { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return mountMutableSource(source, getSnapshot, subscribe); - }, - useSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, - ): T { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId(): string { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return mountId(); - }, - - unstable_isNewReconciler: enableNewReconciler, - }; - if (enableCache) { - (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { - currentHookNameInDev = 'useCacheRefresh'; - updateHookTypesDev(); - return mountRefresh(); - }; - } - if (enableUseHook) { - (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).use = use; - } - if (enableUseMemoCacheHook) { - (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useMemoCache = useMemoCache; - } - if (enableUseEventHook) { - (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useEvent = function useEvent< - Args, - Return, - F: (...Array) => Return, - >(callback: F): F { - currentHookNameInDev = 'useEvent'; - updateHookTypesDev(); - return mountEvent(callback); - }; - } - - HooksDispatcherOnUpdateInDEV = { - readContext(context: ReactContext): T { - return readContext(context); - }, - useCallback(callback: T, deps: Array | void | null): T { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext(context: ReactContext): T { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo(create: () => T, deps: Array | void | null): T { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, - ): [S, Dispatch] { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useRef(initialValue: T): {current: T} { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return updateRef(initialValue); - }, - useState( - initialState: (() => S) | S, - ): [S, Dispatch>] { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return updateDebugValue(value, formatterFn); - }, - useDeferredValue(value: T): T { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition(): [boolean, (() => void) => void] { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, - ): Snapshot { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return updateMutableSource(source, getSnapshot, subscribe); - }, - useSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, - ): T { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId(): string { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return updateId(); - }, - - unstable_isNewReconciler: enableNewReconciler, - }; - if (enableCache) { - (HooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { - currentHookNameInDev = 'useCacheRefresh'; - updateHookTypesDev(); - return updateRefresh(); - }; - } - if (enableUseHook) { - (HooksDispatcherOnUpdateInDEV: Dispatcher).use = use; - } - if (enableUseMemoCacheHook) { - (HooksDispatcherOnUpdateInDEV: Dispatcher).useMemoCache = useMemoCache; - } - if (enableUseEventHook) { - (HooksDispatcherOnUpdateInDEV: Dispatcher).useEvent = function useEvent< - Args, - Return, - F: (...Array) => Return, - >(callback: F): F { - currentHookNameInDev = 'useEvent'; - updateHookTypesDev(); - return updateEvent(callback); - }; - } - - HooksDispatcherOnRerenderInDEV = { - readContext(context: ReactContext): T { - return readContext(context); - }, - - useCallback(callback: T, deps: Array | void | null): T { - currentHookNameInDev = 'useCallback'; - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext(context: ReactContext): T { - currentHookNameInDev = 'useContext'; - updateHookTypesDev(); - return readContext(context); - }, - useEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useEffect'; - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useImperativeHandle'; - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useInsertionEffect'; - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useLayoutEffect'; - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo(create: () => T, deps: Array | void | null): T { - currentHookNameInDev = 'useMemo'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, - ): [S, Dispatch] { - currentHookNameInDev = 'useReducer'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useRef(initialValue: T): {current: T} { - currentHookNameInDev = 'useRef'; - updateHookTypesDev(); - return updateRef(initialValue); - }, - useState( - initialState: (() => S) | S, - ): [S, Dispatch>] { - currentHookNameInDev = 'useState'; - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV; - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - currentHookNameInDev = 'useDebugValue'; - updateHookTypesDev(); - return updateDebugValue(value, formatterFn); - }, - useDeferredValue(value: T): T { - currentHookNameInDev = 'useDeferredValue'; - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition(): [boolean, (() => void) => void] { - currentHookNameInDev = 'useTransition'; - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, - ): Snapshot { - currentHookNameInDev = 'useMutableSource'; - updateHookTypesDev(); - return updateMutableSource(source, getSnapshot, subscribe); - }, - useSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, - ): T { - currentHookNameInDev = 'useSyncExternalStore'; - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId(): string { - currentHookNameInDev = 'useId'; - updateHookTypesDev(); - return updateId(); - }, - - unstable_isNewReconciler: enableNewReconciler, - }; - if (enableCache) { - (HooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { - currentHookNameInDev = 'useCacheRefresh'; - updateHookTypesDev(); - return updateRefresh(); - }; - } - if (enableUseHook) { - (HooksDispatcherOnRerenderInDEV: Dispatcher).use = use; - } - if (enableUseMemoCacheHook) { - (HooksDispatcherOnRerenderInDEV: Dispatcher).useMemoCache = useMemoCache; - } - if (enableUseEventHook) { - (HooksDispatcherOnRerenderInDEV: Dispatcher).useEvent = function useEvent< - Args, - Return, - F: (...Array) => Return, - >(callback: F): F { - currentHookNameInDev = 'useEvent'; - updateHookTypesDev(); - return updateEvent(callback); - }; - } - - InvalidNestedHooksDispatcherOnMountInDEV = { - readContext(context: ReactContext): T { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback(callback: T, deps: Array | void | null): T { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountCallback(callback, deps); - }, - useContext(context: ReactContext): T { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return readContext(context); - }, - useEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountEffect(create, deps); - }, - useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountImperativeHandle(ref, create, deps); - }, - useInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountInsertionEffect(create, deps); - }, - useLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountLayoutEffect(create, deps); - }, - useMemo(create: () => T, deps: Array | void | null): T { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - mountHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountMemo(create, deps); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, - ): [S, Dispatch] { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - mountHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useRef(initialValue: T): {current: T} { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountRef(initialValue); - }, - useState( - initialState: (() => S) | S, - ): [S, Dispatch>] { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - mountHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV; - try { - return mountState(initialState); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDebugValue(value, formatterFn); - }, - useDeferredValue(value: T): T { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountDeferredValue(value); - }, - useTransition(): [boolean, (() => void) => void] { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountTransition(); - }, - useMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, - ): Snapshot { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountMutableSource(source, getSnapshot, subscribe); - }, - useSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, - ): T { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId(): string { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountId(); - }, - - unstable_isNewReconciler: enableNewReconciler, - }; - if (enableCache) { - (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { - currentHookNameInDev = 'useCacheRefresh'; - mountHookTypesDev(); - return mountRefresh(); - }; - } - if (enableUseHook) { - (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).use = function( - usable: Usable, - ): T { - warnInvalidHookAccess(); - return use(usable); - }; - } - if (enableUseMemoCacheHook) { - (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useMemoCache = function( - size: number, - ): Array { - warnInvalidHookAccess(); - return useMemoCache(size); - }; - } - if (enableUseEventHook) { - (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useEvent = function useEvent< - Args, - Return, - F: (...Array) => Return, - >(callback: F): F { - currentHookNameInDev = 'useEvent'; - warnInvalidHookAccess(); - mountHookTypesDev(); - return mountEvent(callback); - }; - } - - InvalidNestedHooksDispatcherOnUpdateInDEV = { - readContext(context: ReactContext): T { - warnInvalidContextAccess(); - return readContext(context); - }, - useCallback(callback: T, deps: Array | void | null): T { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext(context: ReactContext): T { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo(create: () => T, deps: Array | void | null): T { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, - ): [S, Dispatch] { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useRef(initialValue: T): {current: T} { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(initialValue); - }, - useState( - initialState: (() => S) | S, - ): [S, Dispatch>] { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateState(initialState); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(value, formatterFn); - }, - useDeferredValue(value: T): T { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDeferredValue(value); - }, - useTransition(): [boolean, (() => void) => void] { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateTransition(); - }, - useMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, - ): Snapshot { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(source, getSnapshot, subscribe); - }, - useSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, - ): T { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId(): string { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - - unstable_isNewReconciler: enableNewReconciler, - }; - if (enableCache) { - (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { - currentHookNameInDev = 'useCacheRefresh'; - updateHookTypesDev(); - return updateRefresh(); - }; - } - if (enableUseHook) { - (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).use = function( - usable: Usable, - ): T { - warnInvalidHookAccess(); - return use(usable); - }; - } - if (enableUseMemoCacheHook) { - (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useMemoCache = function( - size: number, - ): Array { - warnInvalidHookAccess(); - return useMemoCache(size); - }; - } - if (enableUseEventHook) { - (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useEvent = function useEvent< - Args, - Return, - F: (...Array) => Return, - >(callback: F): F { - currentHookNameInDev = 'useEvent'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEvent(callback); - }; - } - - InvalidNestedHooksDispatcherOnRerenderInDEV = { - readContext(context: ReactContext): T { - warnInvalidContextAccess(); - return readContext(context); - }, - - useCallback(callback: T, deps: Array | void | null): T { - currentHookNameInDev = 'useCallback'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateCallback(callback, deps); - }, - useContext(context: ReactContext): T { - currentHookNameInDev = 'useContext'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return readContext(context); - }, - useEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEffect(create, deps); - }, - useImperativeHandle( - ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, - create: () => T, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useImperativeHandle'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateImperativeHandle(ref, create, deps); - }, - useInsertionEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useInsertionEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateInsertionEffect(create, deps); - }, - useLayoutEffect( - create: () => (() => void) | void, - deps: Array | void | null, - ): void { - currentHookNameInDev = 'useLayoutEffect'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateLayoutEffect(create, deps); - }, - useMemo(create: () => T, deps: Array | void | null): T { - currentHookNameInDev = 'useMemo'; - warnInvalidHookAccess(); - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return updateMemo(create, deps); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useReducer( - reducer: (S, A) => S, - initialArg: I, - init?: I => S, - ): [S, Dispatch] { - currentHookNameInDev = 'useReducer'; - warnInvalidHookAccess(); - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return rerenderReducer(reducer, initialArg, init); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useRef(initialValue: T): {current: T} { - currentHookNameInDev = 'useRef'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateRef(initialValue); - }, - useState( - initialState: (() => S) | S, - ): [S, Dispatch>] { - currentHookNameInDev = 'useState'; - warnInvalidHookAccess(); - updateHookTypesDev(); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV; - try { - return rerenderState(initialState); - } finally { - ReactCurrentDispatcher.current = prevDispatcher; - } - }, - useDebugValue(value: T, formatterFn: ?(value: T) => mixed): void { - currentHookNameInDev = 'useDebugValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateDebugValue(value, formatterFn); - }, - useDeferredValue(value: T): T { - currentHookNameInDev = 'useDeferredValue'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderDeferredValue(value); - }, - useTransition(): [boolean, (() => void) => void] { - currentHookNameInDev = 'useTransition'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return rerenderTransition(); - }, - useMutableSource( - source: MutableSource, - getSnapshot: MutableSourceGetSnapshotFn, - subscribe: MutableSourceSubscribeFn, - ): Snapshot { - currentHookNameInDev = 'useMutableSource'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateMutableSource(source, getSnapshot, subscribe); - }, - useSyncExternalStore( - subscribe: (() => void) => () => void, - getSnapshot: () => T, - getServerSnapshot?: () => T, - ): T { - currentHookNameInDev = 'useSyncExternalStore'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - }, - useId(): string { - currentHookNameInDev = 'useId'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateId(); - }, - - unstable_isNewReconciler: enableNewReconciler, - }; - if (enableCache) { - (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { - currentHookNameInDev = 'useCacheRefresh'; - updateHookTypesDev(); - return updateRefresh(); - }; - } - if (enableUseHook) { - (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).use = function( - usable: Usable, - ): T { - warnInvalidHookAccess(); - return use(usable); - }; - } - if (enableUseMemoCacheHook) { - (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useMemoCache = function( - size: number, - ): Array { - warnInvalidHookAccess(); - return useMemoCache(size); - }; - } - if (enableUseEventHook) { - (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useEvent = function useEvent< - Args, - Return, - F: (...Array) => Return, - >(callback: F): F { - currentHookNameInDev = 'useEvent'; - warnInvalidHookAccess(); - updateHookTypesDev(); - return updateEvent(callback); - }; - } -} diff --git a/packages/react-reconciler/src/ReactFiberHooks.old.js b/packages/react-reconciler/src/ReactFiberHooks.old.js index 1917a76b09a29..3f3a617531aa1 100644 --- a/packages/react-reconciler/src/ReactFiberHooks.old.js +++ b/packages/react-reconciler/src/ReactFiberHooks.old.js @@ -31,7 +31,6 @@ import ReactSharedInternals from 'shared/ReactSharedInternals'; import { enableDebugTracing, enableSchedulingProfiler, - enableNewReconciler, enableCache, enableUseRefAccessWarning, enableLazyContextPropagation, @@ -2758,8 +2757,6 @@ export const ContextOnlyDispatcher: Dispatcher = { useMutableSource: throwInvalidHookError, useSyncExternalStore: throwInvalidHookError, useId: throwInvalidHookError, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (ContextOnlyDispatcher: Dispatcher).useCacheRefresh = throwInvalidHookError; @@ -2793,8 +2790,6 @@ const HooksDispatcherOnMount: Dispatcher = { useMutableSource: mountMutableSource, useSyncExternalStore: mountSyncExternalStore, useId: mountId, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { // $FlowFixMe[escaped-generic] discovered when updating Flow @@ -2828,8 +2823,6 @@ const HooksDispatcherOnUpdate: Dispatcher = { useMutableSource: updateMutableSource, useSyncExternalStore: updateSyncExternalStore, useId: updateId, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (HooksDispatcherOnUpdate: Dispatcher).useCacheRefresh = updateRefresh; @@ -2863,8 +2856,6 @@ const HooksDispatcherOnRerender: Dispatcher = { useMutableSource: updateMutableSource, useSyncExternalStore: updateSyncExternalStore, useId: updateId, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (HooksDispatcherOnRerender: Dispatcher).useCacheRefresh = updateRefresh; @@ -3041,8 +3032,6 @@ if (__DEV__) { mountHookTypesDev(); return mountId(); }, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (HooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { @@ -3198,8 +3187,6 @@ if (__DEV__) { updateHookTypesDev(); return mountId(); }, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { @@ -3355,8 +3342,6 @@ if (__DEV__) { updateHookTypesDev(); return updateId(); }, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (HooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { @@ -3513,8 +3498,6 @@ if (__DEV__) { updateHookTypesDev(); return updateId(); }, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (HooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { @@ -3687,8 +3670,6 @@ if (__DEV__) { mountHookTypesDev(); return mountId(); }, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { @@ -3872,8 +3853,6 @@ if (__DEV__) { updateHookTypesDev(); return updateId(); }, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { @@ -4058,8 +4037,6 @@ if (__DEV__) { updateHookTypesDev(); return updateId(); }, - - unstable_isNewReconciler: enableNewReconciler, }; if (enableCache) { (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).useCacheRefresh = function useCacheRefresh() { diff --git a/packages/react-reconciler/src/ReactFiberHostContext.js b/packages/react-reconciler/src/ReactFiberHostContext.js deleted file mode 100644 index bc6204cad184e..0000000000000 --- a/packages/react-reconciler/src/ReactFiberHostContext.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Container, HostContext} from './ReactFiberHostConfig'; -import {enableNewReconciler} from 'shared/ReactFeatureFlags'; - -import { - getCurrentRootHostContainer as getCurrentRootHostContainer_old, - getHostContext as getHostContext_old, -} from './ReactFiberHostContext.old'; - -import { - getCurrentRootHostContainer as getCurrentRootHostContainer_new, - getHostContext as getHostContext_new, -} from './ReactFiberHostContext.new'; - -export function getCurrentRootHostContainer(): null | Container { - return enableNewReconciler - ? getCurrentRootHostContainer_new() - : getCurrentRootHostContainer_old(); -} - -export function getHostContext(): HostContext { - return enableNewReconciler ? getHostContext_new() : getHostContext_old(); -} diff --git a/packages/react-reconciler/src/ReactFiberHostContext.new.js b/packages/react-reconciler/src/ReactFiberHostContext.new.js deleted file mode 100644 index 13d4df12b483c..0000000000000 --- a/packages/react-reconciler/src/ReactFiberHostContext.new.js +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; -import type {StackCursor} from './ReactFiberStack.new'; -import type {Container, HostContext} from './ReactFiberHostConfig'; - -import {getChildHostContext, getRootHostContext} from './ReactFiberHostConfig'; -import {createCursor, push, pop} from './ReactFiberStack.new'; - -const contextStackCursor: StackCursor = createCursor(null); -const contextFiberStackCursor: StackCursor = createCursor(null); -const rootInstanceStackCursor: StackCursor = createCursor( - null, -); - -function requiredContext(c: Value | null): Value { - if (__DEV__) { - if (c === null) { - console.error( - 'Expected host context to exist. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - } - } - return (c: any); -} - -function getCurrentRootHostContainer(): null | Container { - return rootInstanceStackCursor.current; -} - -function getRootHostContainer(): Container { - const rootInstance = requiredContext(rootInstanceStackCursor.current); - return rootInstance; -} - -function pushHostContainer(fiber: Fiber, nextRootInstance: Container) { - // Push current root instance onto the stack; - // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); - // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - - // Finally, we need to push the host context to the stack. - // However, we can't just call getRootHostContext() and push it because - // we'd have a different number of entries on the stack depending on - // whether getRootHostContext() throws somewhere in renderer code or not. - // So we push an empty value first. This lets us safely unwind on errors. - push(contextStackCursor, null, fiber); - const nextRootContext = getRootHostContext(nextRootInstance); - // Now that we know this function doesn't throw, replace it. - pop(contextStackCursor, fiber); - push(contextStackCursor, nextRootContext, fiber); -} - -function popHostContainer(fiber: Fiber) { - pop(contextStackCursor, fiber); - pop(contextFiberStackCursor, fiber); - pop(rootInstanceStackCursor, fiber); -} - -function getHostContext(): HostContext { - const context = requiredContext(contextStackCursor.current); - return context; -} - -function pushHostContext(fiber: Fiber): void { - const context: HostContext = requiredContext(contextStackCursor.current); - const nextContext = getChildHostContext(context, fiber.type); - - // Don't push this Fiber's context unless it's unique. - if (context === nextContext) { - return; - } - - // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor, nextContext, fiber); -} - -function popHostContext(fiber: Fiber): void { - // Do not pop unless this Fiber provided the current context. - // pushHostContext() only pushes Fibers that provide unique contexts. - if (contextFiberStackCursor.current !== fiber) { - return; - } - - pop(contextStackCursor, fiber); - pop(contextFiberStackCursor, fiber); -} - -export { - getHostContext, - getCurrentRootHostContainer, - getRootHostContainer, - popHostContainer, - popHostContext, - pushHostContainer, - pushHostContext, -}; diff --git a/packages/react-reconciler/src/ReactFiberHotReloading.js b/packages/react-reconciler/src/ReactFiberHotReloading.js deleted file mode 100644 index c602f6a41499a..0000000000000 --- a/packages/react-reconciler/src/ReactFiberHotReloading.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {ReactElement} from '../../shared/ReactElementType'; -import type {Instance} from './ReactFiberHostConfig'; -import type {ReactNodeList} from 'shared/ReactTypes'; - -import {enableNewReconciler} from 'shared/ReactFeatureFlags'; - -import { - setRefreshHandler as setRefreshHandler_old, - resolveFunctionForHotReloading as resolveFunctionForHotReloading_old, - resolveClassForHotReloading as resolveClassForHotReloading_old, - resolveForwardRefForHotReloading as resolveForwardRefForHotReloading_old, - isCompatibleFamilyForHotReloading as isCompatibleFamilyForHotReloading_old, - markFailedErrorBoundaryForHotReloading as markFailedErrorBoundaryForHotReloading_old, - scheduleRefresh as scheduleRefresh_old, - scheduleRoot as scheduleRoot_old, - findHostInstancesForRefresh as findHostInstancesForRefresh_old, -} from './ReactFiberHotReloading.old'; - -import { - setRefreshHandler as setRefreshHandler_new, - resolveFunctionForHotReloading as resolveFunctionForHotReloading_new, - resolveClassForHotReloading as resolveClassForHotReloading_new, - resolveForwardRefForHotReloading as resolveForwardRefForHotReloading_new, - isCompatibleFamilyForHotReloading as isCompatibleFamilyForHotReloading_new, - markFailedErrorBoundaryForHotReloading as markFailedErrorBoundaryForHotReloading_new, - scheduleRefresh as scheduleRefresh_new, - scheduleRoot as scheduleRoot_new, - findHostInstancesForRefresh as findHostInstancesForRefresh_new, -} from './ReactFiberHotReloading.new'; - -export type Family = { - current: any, -}; - -export type RefreshUpdate = { - staleFamilies: Set, - updatedFamilies: Set, -}; - -// Resolves type to a family. -export type RefreshHandler = any => Family | void; - -// Used by React Refresh runtime through DevTools Global Hook. -export type SetRefreshHandler = (handler: RefreshHandler | null) => void; -export type ScheduleRefresh = (root: FiberRoot, update: RefreshUpdate) => void; -export type ScheduleRoot = (root: FiberRoot, element: ReactNodeList) => void; -export type FindHostInstancesForRefresh = ( - root: FiberRoot, - families: Array, -) => Set; - -export const setRefreshHandler: ( - handler: RefreshHandler | null, -) => void = enableNewReconciler ? setRefreshHandler_new : setRefreshHandler_old; -export const resolveFunctionForHotReloading: typeof resolveFunctionForHotReloading_new = enableNewReconciler - ? resolveFunctionForHotReloading_new - : resolveFunctionForHotReloading_old; -export const resolveClassForHotReloading: typeof resolveClassForHotReloading_new = enableNewReconciler - ? resolveClassForHotReloading_new - : resolveClassForHotReloading_old; -export const resolveForwardRefForHotReloading: typeof resolveForwardRefForHotReloading_new = enableNewReconciler - ? resolveForwardRefForHotReloading_new - : resolveForwardRefForHotReloading_old; -export const isCompatibleFamilyForHotReloading: ( - fiber: Fiber, - element: ReactElement, -) => boolean = enableNewReconciler - ? isCompatibleFamilyForHotReloading_new - : isCompatibleFamilyForHotReloading_old; -export const markFailedErrorBoundaryForHotReloading: ( - fiber: Fiber, -) => void = enableNewReconciler - ? markFailedErrorBoundaryForHotReloading_new - : markFailedErrorBoundaryForHotReloading_old; -export const scheduleRefresh: ScheduleRefresh = enableNewReconciler - ? scheduleRefresh_new - : scheduleRefresh_old; -export const scheduleRoot: ScheduleRoot = enableNewReconciler - ? scheduleRoot_new - : scheduleRoot_old; -export const findHostInstancesForRefresh: FindHostInstancesForRefresh = enableNewReconciler - ? findHostInstancesForRefresh_new - : findHostInstancesForRefresh_old; diff --git a/packages/react-reconciler/src/ReactFiberHotReloading.new.js b/packages/react-reconciler/src/ReactFiberHotReloading.new.js deleted file mode 100644 index 8a3b695666f4b..0000000000000 --- a/packages/react-reconciler/src/ReactFiberHotReloading.new.js +++ /dev/null @@ -1,487 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -/* eslint-disable react-internal/prod-error-codes */ - -import type {ReactElement} from 'shared/ReactElementType'; -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Instance} from './ReactFiberHostConfig'; -import type {ReactNodeList} from 'shared/ReactTypes'; - -import type { - Family, - FindHostInstancesForRefresh, - RefreshHandler, - RefreshUpdate, - ScheduleRefresh, - ScheduleRoot, -} from './ReactFiberHotReloading'; - -import {enableHostSingletons, enableFloat} from 'shared/ReactFeatureFlags'; -import { - flushSync, - scheduleUpdateOnFiber, - flushPassiveEffects, -} from './ReactFiberWorkLoop.new'; -import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates.new'; -import {updateContainer} from './ReactFiberReconciler.new'; -import {emptyContextObject} from './ReactFiberContext.new'; -import {SyncLane, NoTimestamp} from './ReactFiberLane.new'; -import { - ClassComponent, - FunctionComponent, - ForwardRef, - HostComponent, - HostResource, - HostSingleton, - HostPortal, - HostRoot, - MemoComponent, - SimpleMemoComponent, -} from './ReactWorkTags'; -import { - REACT_FORWARD_REF_TYPE, - REACT_MEMO_TYPE, - REACT_LAZY_TYPE, -} from 'shared/ReactSymbols'; -import {supportsSingletons} from './ReactFiberHostConfig'; - -let resolveFamily: RefreshHandler | null = null; -let failedBoundaries: WeakSet | null = null; - -export const setRefreshHandler = (handler: RefreshHandler | null): void => { - if (__DEV__) { - resolveFamily = handler; - } -}; - -export function resolveFunctionForHotReloading(type: any): any { - if (__DEV__) { - if (resolveFamily === null) { - // Hot reloading is disabled. - return type; - } - const family = resolveFamily(type); - if (family === undefined) { - return type; - } - // Use the latest known implementation. - return family.current; - } else { - return type; - } -} - -export function resolveClassForHotReloading(type: any): any { - // No implementation differences. - return resolveFunctionForHotReloading(type); -} - -export function resolveForwardRefForHotReloading(type: any): any { - if (__DEV__) { - if (resolveFamily === null) { - // Hot reloading is disabled. - return type; - } - const family = resolveFamily(type); - if (family === undefined) { - // Check if we're dealing with a real forwardRef. Don't want to crash early. - if ( - type !== null && - type !== undefined && - typeof type.render === 'function' - ) { - // ForwardRef is special because its resolved .type is an object, - // but it's possible that we only have its inner render function in the map. - // If that inner render function is different, we'll build a new forwardRef type. - const currentRender = resolveFunctionForHotReloading(type.render); - if (type.render !== currentRender) { - const syntheticType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: currentRender, - }; - if (type.displayName !== undefined) { - (syntheticType: any).displayName = type.displayName; - } - return syntheticType; - } - } - return type; - } - // Use the latest known implementation. - return family.current; - } else { - return type; - } -} - -export function isCompatibleFamilyForHotReloading( - fiber: Fiber, - element: ReactElement, -): boolean { - if (__DEV__) { - if (resolveFamily === null) { - // Hot reloading is disabled. - return false; - } - - const prevType = fiber.elementType; - const nextType = element.type; - - // If we got here, we know types aren't === equal. - let needsCompareFamilies = false; - - const $$typeofNextType = - typeof nextType === 'object' && nextType !== null - ? nextType.$$typeof - : null; - - switch (fiber.tag) { - case ClassComponent: { - if (typeof nextType === 'function') { - needsCompareFamilies = true; - } - break; - } - case FunctionComponent: { - if (typeof nextType === 'function') { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - // We don't know the inner type yet. - // We're going to assume that the lazy inner type is stable, - // and so it is sufficient to avoid reconciling it away. - // We're not going to unwrap or actually use the new lazy type. - needsCompareFamilies = true; - } - break; - } - case ForwardRef: { - if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - break; - } - case MemoComponent: - case SimpleMemoComponent: { - if ($$typeofNextType === REACT_MEMO_TYPE) { - // TODO: if it was but can no longer be simple, - // we shouldn't set this. - needsCompareFamilies = true; - } else if ($$typeofNextType === REACT_LAZY_TYPE) { - needsCompareFamilies = true; - } - break; - } - default: - return false; - } - - // Check if both types have a family and it's the same one. - if (needsCompareFamilies) { - // Note: memo() and forwardRef() we'll compare outer rather than inner type. - // This means both of them need to be registered to preserve state. - // If we unwrapped and compared the inner types for wrappers instead, - // then we would risk falsely saying two separate memo(Foo) - // calls are equivalent because they wrap the same Foo function. - const prevFamily = resolveFamily(prevType); - // $FlowFixMe[not-a-function] found when upgrading Flow - if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { - return true; - } - } - return false; - } else { - return false; - } -} - -export function markFailedErrorBoundaryForHotReloading(fiber: Fiber) { - if (__DEV__) { - if (resolveFamily === null) { - // Hot reloading is disabled. - return; - } - if (typeof WeakSet !== 'function') { - return; - } - if (failedBoundaries === null) { - failedBoundaries = new WeakSet(); - } - failedBoundaries.add(fiber); - } -} - -export const scheduleRefresh: ScheduleRefresh = ( - root: FiberRoot, - update: RefreshUpdate, -): void => { - if (__DEV__) { - if (resolveFamily === null) { - // Hot reloading is disabled. - return; - } - const {staleFamilies, updatedFamilies} = update; - flushPassiveEffects(); - flushSync(() => { - scheduleFibersWithFamiliesRecursively( - root.current, - updatedFamilies, - staleFamilies, - ); - }); - } -}; - -export const scheduleRoot: ScheduleRoot = ( - root: FiberRoot, - element: ReactNodeList, -): void => { - if (__DEV__) { - if (root.context !== emptyContextObject) { - // Super edge case: root has a legacy _renderSubtree context - // but we don't know the parentComponent so we can't pass it. - // Just ignore. We'll delete this with _renderSubtree code path later. - return; - } - flushPassiveEffects(); - flushSync(() => { - updateContainer(element, root, null, null); - }); - } -}; - -function scheduleFibersWithFamiliesRecursively( - fiber: Fiber, - updatedFamilies: Set, - staleFamilies: Set, -) { - if (__DEV__) { - const {alternate, child, sibling, tag, type} = fiber; - - let candidateType = null; - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - case ForwardRef: - candidateType = type.render; - break; - default: - break; - } - - if (resolveFamily === null) { - throw new Error('Expected resolveFamily to be set during hot reload.'); - } - - let needsRender = false; - let needsRemount = false; - if (candidateType !== null) { - const family = resolveFamily(candidateType); - if (family !== undefined) { - if (staleFamilies.has(family)) { - needsRemount = true; - } else if (updatedFamilies.has(family)) { - if (tag === ClassComponent) { - needsRemount = true; - } else { - needsRender = true; - } - } - } - } - if (failedBoundaries !== null) { - if ( - failedBoundaries.has(fiber) || - // $FlowFixMe[incompatible-use] found when upgrading Flow - (alternate !== null && failedBoundaries.has(alternate)) - ) { - needsRemount = true; - } - } - - if (needsRemount) { - fiber._debugNeedsRemount = true; - } - if (needsRemount || needsRender) { - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - if (child !== null && !needsRemount) { - scheduleFibersWithFamiliesRecursively( - child, - updatedFamilies, - staleFamilies, - ); - } - if (sibling !== null) { - scheduleFibersWithFamiliesRecursively( - sibling, - updatedFamilies, - staleFamilies, - ); - } - } -} - -export const findHostInstancesForRefresh: FindHostInstancesForRefresh = ( - root: FiberRoot, - families: Array, -): Set => { - if (__DEV__) { - const hostInstances = new Set(); - const types = new Set(families.map(family => family.current)); - findHostInstancesForMatchingFibersRecursively( - root.current, - types, - hostInstances, - ); - return hostInstances; - } else { - throw new Error( - 'Did not expect findHostInstancesForRefresh to be called in production.', - ); - } -}; - -function findHostInstancesForMatchingFibersRecursively( - fiber: Fiber, - types: Set, - hostInstances: Set, -) { - if (__DEV__) { - const {child, sibling, tag, type} = fiber; - - let candidateType = null; - switch (tag) { - case FunctionComponent: - case SimpleMemoComponent: - case ClassComponent: - candidateType = type; - break; - case ForwardRef: - candidateType = type.render; - break; - default: - break; - } - - let didMatch = false; - if (candidateType !== null) { - if (types.has(candidateType)) { - didMatch = true; - } - } - - if (didMatch) { - // We have a match. This only drills down to the closest host components. - // There's no need to search deeper because for the purpose of giving - // visual feedback, "flashing" outermost parent rectangles is sufficient. - findHostInstancesForFiberShallowly(fiber, hostInstances); - } else { - // If there's no match, maybe there will be one further down in the child tree. - if (child !== null) { - findHostInstancesForMatchingFibersRecursively( - child, - types, - hostInstances, - ); - } - } - - if (sibling !== null) { - findHostInstancesForMatchingFibersRecursively( - sibling, - types, - hostInstances, - ); - } - } -} - -function findHostInstancesForFiberShallowly( - fiber: Fiber, - hostInstances: Set, -): void { - if (__DEV__) { - const foundHostInstances = findChildHostInstancesForFiberShallowly( - fiber, - hostInstances, - ); - if (foundHostInstances) { - return; - } - // If we didn't find any host children, fallback to closest host parent. - let node = fiber; - while (true) { - switch (node.tag) { - case HostSingleton: - case HostComponent: - hostInstances.add(node.stateNode); - return; - case HostPortal: - hostInstances.add(node.stateNode.containerInfo); - return; - case HostRoot: - hostInstances.add(node.stateNode.containerInfo); - return; - } - if (node.return === null) { - throw new Error('Expected to reach root first.'); - } - node = node.return; - } - } -} - -function findChildHostInstancesForFiberShallowly( - fiber: Fiber, - hostInstances: Set, -): boolean { - if (__DEV__) { - let node: Fiber = fiber; - let foundHostInstances = false; - while (true) { - if ( - node.tag === HostComponent || - (enableFloat ? node.tag === HostResource : false) || - (enableHostSingletons && supportsSingletons - ? node.tag === HostSingleton - : false) - ) { - // We got a match. - foundHostInstances = true; - hostInstances.add(node.stateNode); - // There may still be more, so keep searching. - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === fiber) { - return foundHostInstances; - } - while (node.sibling === null) { - if (node.return === null || node.return === fiber) { - return foundHostInstances; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - return false; -} diff --git a/packages/react-reconciler/src/ReactFiberHotReloading.old.js b/packages/react-reconciler/src/ReactFiberHotReloading.old.js index f0c76ea502ecf..1d282869d3fe9 100644 --- a/packages/react-reconciler/src/ReactFiberHotReloading.old.js +++ b/packages/react-reconciler/src/ReactFiberHotReloading.old.js @@ -14,15 +14,6 @@ import type {Fiber, FiberRoot} from './ReactInternalTypes'; import type {Instance} from './ReactFiberHostConfig'; import type {ReactNodeList} from 'shared/ReactTypes'; -import type { - Family, - FindHostInstancesForRefresh, - RefreshHandler, - RefreshUpdate, - ScheduleRefresh, - ScheduleRoot, -} from './ReactFiberHotReloading'; - import {enableHostSingletons, enableFloat} from 'shared/ReactFeatureFlags'; import { flushSync, @@ -52,6 +43,27 @@ import { } from 'shared/ReactSymbols'; import {supportsSingletons} from './ReactFiberHostConfig'; +export type Family = { + current: any, +}; + +export type RefreshUpdate = { + staleFamilies: Set, + updatedFamilies: Set, +}; + +// Resolves type to a family. +type RefreshHandler = any => Family | void; + +// Used by React Refresh runtime through DevTools Global Hook. +export type SetRefreshHandler = (handler: RefreshHandler | null) => void; +export type ScheduleRefresh = (root: FiberRoot, update: RefreshUpdate) => void; +export type ScheduleRoot = (root: FiberRoot, element: ReactNodeList) => void; +export type FindHostInstancesForRefresh = ( + root: FiberRoot, + families: Array, +) => Set; + let resolveFamily: RefreshHandler | null = null; let failedBoundaries: WeakSet | null = null; diff --git a/packages/react-reconciler/src/ReactFiberHydrationContext.new.js b/packages/react-reconciler/src/ReactFiberHydrationContext.new.js deleted file mode 100644 index caedaa7b20089..0000000000000 --- a/packages/react-reconciler/src/ReactFiberHydrationContext.new.js +++ /dev/null @@ -1,771 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; -import {NoMode, ConcurrentMode} from './ReactTypeOfMode'; -import type { - Instance, - TextInstance, - HydratableInstance, - SuspenseInstance, - Container, - HostContext, -} from './ReactFiberHostConfig'; -import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; -import type {TreeContext} from './ReactFiberTreeContext.new'; -import type {CapturedValue} from './ReactCapturedValue'; - -import { - HostComponent, - HostSingleton, - HostText, - HostRoot, - SuspenseComponent, -} from './ReactWorkTags'; -import { - ChildDeletion, - Placement, - Hydrating, - NoFlags, - DidCapture, -} from './ReactFiberFlags'; -import {enableHostSingletons, enableFloat} from 'shared/ReactFeatureFlags'; - -import { - createFiberFromHostInstanceForDeletion, - createFiberFromDehydratedFragment, -} from './ReactFiber.new'; -import { - shouldSetTextContent, - supportsHydration, - supportsSingletons, - isHydratable, - canHydrateInstance, - canHydrateTextInstance, - canHydrateSuspenseInstance, - getNextHydratableSibling, - getFirstHydratableChild, - getFirstHydratableChildWithinContainer, - getFirstHydratableChildWithinSuspenseInstance, - hydrateInstance, - hydrateTextInstance, - hydrateSuspenseInstance, - getNextHydratableInstanceAfterSuspenseInstance, - shouldDeleteUnhydratedTailInstances, - didNotMatchHydratedContainerTextInstance, - didNotMatchHydratedTextInstance, - didNotHydrateInstanceWithinContainer, - didNotHydrateInstanceWithinSuspenseInstance, - didNotHydrateInstance, - didNotFindHydratableInstanceWithinContainer, - didNotFindHydratableTextInstanceWithinContainer, - didNotFindHydratableSuspenseInstanceWithinContainer, - didNotFindHydratableInstanceWithinSuspenseInstance, - didNotFindHydratableTextInstanceWithinSuspenseInstance, - didNotFindHydratableSuspenseInstanceWithinSuspenseInstance, - didNotFindHydratableInstance, - didNotFindHydratableTextInstance, - didNotFindHydratableSuspenseInstance, - resolveSingletonInstance, -} from './ReactFiberHostConfig'; -import {OffscreenLane} from './ReactFiberLane.new'; -import { - getSuspendedTreeContext, - restoreSuspendedTreeContext, -} from './ReactFiberTreeContext.new'; -import {queueRecoverableErrors} from './ReactFiberWorkLoop.new'; -import { - getRootHostContainer, - getHostContext, -} from './ReactFiberHostContext.new'; - -// The deepest Fiber on the stack involved in a hydration context. -// This may have been an insertion or a hydration. -let hydrationParentFiber: null | Fiber = null; -let nextHydratableInstance: null | HydratableInstance = null; -let isHydrating: boolean = false; - -// This flag allows for warning supression when we expect there to be mismatches -// due to earlier mismatches or a suspended fiber. -let didSuspendOrErrorDEV: boolean = false; - -// Hydration errors that were thrown inside this boundary -let hydrationErrors: Array> | null = null; - -function warnIfHydrating() { - if (__DEV__) { - if (isHydrating) { - console.error( - 'We should not be hydrating here. This is a bug in React. Please file a bug.', - ); - } - } -} - -export function markDidThrowWhileHydratingDEV() { - if (__DEV__) { - didSuspendOrErrorDEV = true; - } -} - -export function didSuspendOrErrorWhileHydratingDEV(): boolean { - if (__DEV__) { - return didSuspendOrErrorDEV; - } - return false; -} - -function enterHydrationState(fiber: Fiber): boolean { - if (!supportsHydration) { - return false; - } - - const parentInstance: Container = fiber.stateNode.containerInfo; - nextHydratableInstance = getFirstHydratableChildWithinContainer( - parentInstance, - ); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspendOrErrorDEV = false; - return true; -} - -function reenterHydrationStateFromDehydratedSuspenseInstance( - fiber: Fiber, - suspenseInstance: SuspenseInstance, - treeContext: TreeContext | null, -): boolean { - if (!supportsHydration) { - return false; - } - nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance( - suspenseInstance, - ); - hydrationParentFiber = fiber; - isHydrating = true; - hydrationErrors = null; - didSuspendOrErrorDEV = false; - if (treeContext !== null) { - restoreSuspendedTreeContext(fiber, treeContext); - } - return true; -} - -function warnUnhydratedInstance( - returnFiber: Fiber, - instance: HydratableInstance, -) { - if (__DEV__) { - switch (returnFiber.tag) { - case HostRoot: { - didNotHydrateInstanceWithinContainer( - returnFiber.stateNode.containerInfo, - instance, - ); - break; - } - case HostSingleton: - case HostComponent: { - const isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotHydrateInstance( - returnFiber.type, - returnFiber.memoizedProps, - returnFiber.stateNode, - instance, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode, - ); - break; - } - case SuspenseComponent: { - const suspenseState: SuspenseState = returnFiber.memoizedState; - if (suspenseState.dehydrated !== null) - didNotHydrateInstanceWithinSuspenseInstance( - suspenseState.dehydrated, - instance, - ); - break; - } - } - } -} - -function deleteHydratableInstance( - returnFiber: Fiber, - instance: HydratableInstance, -) { - warnUnhydratedInstance(returnFiber, instance); - const childToDelete = createFiberFromHostInstanceForDeletion(); - childToDelete.stateNode = instance; - childToDelete.return = returnFiber; - - const deletions = returnFiber.deletions; - if (deletions === null) { - returnFiber.deletions = [childToDelete]; - returnFiber.flags |= ChildDeletion; - } else { - deletions.push(childToDelete); - } -} - -function warnNonhydratedInstance(returnFiber: Fiber, fiber: Fiber) { - if (__DEV__) { - if (didSuspendOrErrorDEV) { - // Inside a boundary that already suspended. We're currently rendering the - // siblings of a suspended node. The mismatch may be due to the missing - // data, so it's probably a false positive. - return; - } - - switch (returnFiber.tag) { - case HostRoot: { - const parentContainer = returnFiber.stateNode.containerInfo; - switch (fiber.tag) { - case HostSingleton: - case HostComponent: - const type = fiber.type; - const props = fiber.pendingProps; - didNotFindHydratableInstanceWithinContainer( - parentContainer, - type, - props, - ); - break; - case HostText: - const text = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinContainer( - parentContainer, - text, - ); - break; - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinContainer( - parentContainer, - ); - break; - } - break; - } - case HostSingleton: - case HostComponent: { - const parentType = returnFiber.type; - const parentProps = returnFiber.memoizedProps; - const parentInstance = returnFiber.stateNode; - switch (fiber.tag) { - case HostSingleton: - case HostComponent: { - const type = fiber.type; - const props = fiber.pendingProps; - const isConcurrentMode = - (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotFindHydratableInstance( - parentType, - parentProps, - parentInstance, - type, - props, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode, - ); - break; - } - case HostText: { - const text = fiber.pendingProps; - const isConcurrentMode = - (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotFindHydratableTextInstance( - parentType, - parentProps, - parentInstance, - text, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode, - ); - break; - } - case SuspenseComponent: { - didNotFindHydratableSuspenseInstance( - parentType, - parentProps, - parentInstance, - ); - break; - } - } - break; - } - case SuspenseComponent: { - const suspenseState: SuspenseState = returnFiber.memoizedState; - const parentInstance = suspenseState.dehydrated; - if (parentInstance !== null) - switch (fiber.tag) { - case HostSingleton: - case HostComponent: - const type = fiber.type; - const props = fiber.pendingProps; - didNotFindHydratableInstanceWithinSuspenseInstance( - parentInstance, - type, - props, - ); - break; - case HostText: - const text = fiber.pendingProps; - didNotFindHydratableTextInstanceWithinSuspenseInstance( - parentInstance, - text, - ); - break; - case SuspenseComponent: - didNotFindHydratableSuspenseInstanceWithinSuspenseInstance( - parentInstance, - ); - break; - } - break; - } - default: - return; - } - } -} -function insertNonHydratedInstance(returnFiber: Fiber, fiber: Fiber) { - fiber.flags = (fiber.flags & ~Hydrating) | Placement; - warnNonhydratedInstance(returnFiber, fiber); -} - -function tryHydrate(fiber, nextInstance) { - switch (fiber.tag) { - // HostSingleton is intentionally omitted. the hydration pathway for singletons is non-fallible - // you can find it inlined in claimHydratableSingleton - case HostComponent: { - const type = fiber.type; - const props = fiber.pendingProps; - const instance = canHydrateInstance(nextInstance, type, props); - if (instance !== null) { - fiber.stateNode = (instance: Instance); - hydrationParentFiber = fiber; - nextHydratableInstance = getFirstHydratableChild(instance); - return true; - } - return false; - } - case HostText: { - const text = fiber.pendingProps; - const textInstance = canHydrateTextInstance(nextInstance, text); - if (textInstance !== null) { - fiber.stateNode = (textInstance: TextInstance); - hydrationParentFiber = fiber; - // Text Instances don't have children so there's nothing to hydrate. - nextHydratableInstance = null; - return true; - } - return false; - } - case SuspenseComponent: { - const suspenseInstance: null | SuspenseInstance = canHydrateSuspenseInstance( - nextInstance, - ); - if (suspenseInstance !== null) { - const suspenseState: SuspenseState = { - dehydrated: suspenseInstance, - treeContext: getSuspendedTreeContext(), - retryLane: OffscreenLane, - }; - fiber.memoizedState = suspenseState; - // Store the dehydrated fragment as a child fiber. - // This simplifies the code for getHostSibling and deleting nodes, - // since it doesn't have to consider all Suspense boundaries and - // check if they're dehydrated ones or not. - const dehydratedFragment = createFiberFromDehydratedFragment( - suspenseInstance, - ); - dehydratedFragment.return = fiber; - fiber.child = dehydratedFragment; - hydrationParentFiber = fiber; - // While a Suspense Instance does have children, we won't step into - // it during the first pass. Instead, we'll reenter it later. - nextHydratableInstance = null; - return true; - } - return false; - } - default: - return false; - } -} - -function shouldClientRenderOnMismatch(fiber: Fiber) { - return ( - (fiber.mode & ConcurrentMode) !== NoMode && - (fiber.flags & DidCapture) === NoFlags - ); -} - -function throwOnHydrationMismatch(fiber: Fiber) { - throw new Error( - 'Hydration failed because the initial UI does not match what was ' + - 'rendered on the server.', - ); -} - -function claimHydratableSingleton(fiber: Fiber): void { - if (enableHostSingletons && supportsSingletons) { - if (!isHydrating) { - return; - } - const currentRootContainer = getRootHostContainer(); - const currentHostContext = getHostContext(); - const instance = (fiber.stateNode = resolveSingletonInstance( - fiber.type, - fiber.pendingProps, - currentRootContainer, - currentHostContext, - false, - )); - hydrationParentFiber = fiber; - nextHydratableInstance = getFirstHydratableChild(instance); - } -} - -function tryToClaimNextHydratableInstance(fiber: Fiber): void { - if (!isHydrating) { - return; - } - if (enableFloat && !isHydratable(fiber.type, fiber.pendingProps)) { - // This fiber never hydrates from the DOM and always does an insert - fiber.flags = (fiber.flags & ~Hydrating) | Placement; - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - let nextInstance = nextHydratableInstance; - if (!nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance((hydrationParentFiber: any), fiber); - throwOnHydrationMismatch(fiber); - } - // Nothing to hydrate. Make it an insertion. - insertNonHydratedInstance((hydrationParentFiber: any), fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - const firstAttemptedInstance = nextInstance; - if (!tryHydrate(fiber, nextInstance)) { - if (shouldClientRenderOnMismatch(fiber)) { - warnNonhydratedInstance((hydrationParentFiber: any), fiber); - throwOnHydrationMismatch(fiber); - } - // If we can't hydrate this instance let's try the next one. - // We use this as a heuristic. It's based on intuition and not data so it - // might be flawed or unnecessary. - nextInstance = getNextHydratableSibling(firstAttemptedInstance); - const prevHydrationParentFiber: Fiber = (hydrationParentFiber: any); - if (!nextInstance || !tryHydrate(fiber, nextInstance)) { - // Nothing to hydrate. Make it an insertion. - insertNonHydratedInstance((hydrationParentFiber: any), fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - // We matched the next one, we'll now assume that the first one was - // superfluous and we'll delete it. Since we can't eagerly delete it - // we'll have to schedule a deletion. To do that, this node needs a dummy - // fiber associated with it. - deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); - } -} - -function prepareToHydrateHostInstance( - fiber: Fiber, - hostContext: HostContext, -): boolean { - if (!supportsHydration) { - throw new Error( - 'Expected prepareToHydrateHostInstance() to never be called. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - const instance: Instance = fiber.stateNode; - const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; - const updatePayload = hydrateInstance( - instance, - fiber.type, - fiber.memoizedProps, - hostContext, - fiber, - shouldWarnIfMismatchDev, - ); - // TODO: Type this specific to this type of component. - fiber.updateQueue = (updatePayload: any); - // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. - if (updatePayload !== null) { - return true; - } - return false; -} - -function prepareToHydrateHostTextInstance(fiber: Fiber): boolean { - if (!supportsHydration) { - throw new Error( - 'Expected prepareToHydrateHostTextInstance() to never be called. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - const textInstance: TextInstance = fiber.stateNode; - const textContent: string = fiber.memoizedProps; - const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; - const shouldUpdate = hydrateTextInstance( - textInstance, - textContent, - fiber, - shouldWarnIfMismatchDev, - ); - if (shouldUpdate) { - // We assume that prepareToHydrateHostTextInstance is called in a context where the - // hydration parent is the parent host component of this host text. - const returnFiber = hydrationParentFiber; - if (returnFiber !== null) { - switch (returnFiber.tag) { - case HostRoot: { - const parentContainer = returnFiber.stateNode.containerInfo; - const isConcurrentMode = - (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotMatchHydratedContainerTextInstance( - parentContainer, - textInstance, - textContent, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode, - shouldWarnIfMismatchDev, - ); - break; - } - case HostSingleton: - case HostComponent: { - const parentType = returnFiber.type; - const parentProps = returnFiber.memoizedProps; - const parentInstance = returnFiber.stateNode; - const isConcurrentMode = - (returnFiber.mode & ConcurrentMode) !== NoMode; - didNotMatchHydratedTextInstance( - parentType, - parentProps, - parentInstance, - textInstance, - textContent, - // TODO: Delete this argument when we remove the legacy root API. - isConcurrentMode, - shouldWarnIfMismatchDev, - ); - break; - } - } - } - } - return shouldUpdate; -} - -function prepareToHydrateHostSuspenseInstance(fiber: Fiber): void { - if (!supportsHydration) { - throw new Error( - 'Expected prepareToHydrateHostSuspenseInstance() to never be called. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - const suspenseState: null | SuspenseState = fiber.memoizedState; - const suspenseInstance: null | SuspenseInstance = - suspenseState !== null ? suspenseState.dehydrated : null; - - if (!suspenseInstance) { - throw new Error( - 'Expected to have a hydrated suspense instance. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - hydrateSuspenseInstance(suspenseInstance, fiber); -} - -function skipPastDehydratedSuspenseInstance( - fiber: Fiber, -): null | HydratableInstance { - if (!supportsHydration) { - throw new Error( - 'Expected skipPastDehydratedSuspenseInstance() to never be called. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - const suspenseState: null | SuspenseState = fiber.memoizedState; - const suspenseInstance: null | SuspenseInstance = - suspenseState !== null ? suspenseState.dehydrated : null; - - if (!suspenseInstance) { - throw new Error( - 'Expected to have a hydrated suspense instance. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - - return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); -} - -function popToNextHostParent(fiber: Fiber): void { - let parent = fiber.return; - while ( - parent !== null && - parent.tag !== HostComponent && - parent.tag !== HostRoot && - parent.tag !== SuspenseComponent && - (!(enableHostSingletons && supportsSingletons) - ? true - : parent.tag !== HostSingleton) - ) { - parent = parent.return; - } - hydrationParentFiber = parent; -} - -function popHydrationState(fiber: Fiber): boolean { - if (!supportsHydration) { - return false; - } - if (fiber !== hydrationParentFiber) { - // We're deeper than the current hydration context, inside an inserted - // tree. - return false; - } - if (!isHydrating) { - // If we're not currently hydrating but we're in a hydration context, then - // we were an insertion and now need to pop up reenter hydration of our - // siblings. - popToNextHostParent(fiber); - isHydrating = true; - return false; - } - - let shouldClear = false; - if (enableHostSingletons && supportsSingletons) { - // With float we never clear the Root, or Singleton instances. We also do not clear Instances - // that have singleton text content - if ( - fiber.tag !== HostRoot && - fiber.tag !== HostSingleton && - !( - fiber.tag === HostComponent && - shouldSetTextContent(fiber.type, fiber.memoizedProps) - ) - ) { - shouldClear = true; - } - } else { - // If we have any remaining hydratable nodes, we need to delete them now. - // We only do this deeper than head and body since they tend to have random - // other nodes in them. We also ignore components with pure text content in - // side of them. We also don't delete anything inside the root container. - if ( - fiber.tag !== HostRoot && - (fiber.tag !== HostComponent || - (shouldDeleteUnhydratedTailInstances(fiber.type) && - !shouldSetTextContent(fiber.type, fiber.memoizedProps))) - ) { - shouldClear = true; - } - } - if (shouldClear) { - let nextInstance = nextHydratableInstance; - if (nextInstance) { - if (shouldClientRenderOnMismatch(fiber)) { - warnIfUnhydratedTailNodes(fiber); - throwOnHydrationMismatch(fiber); - } else { - while (nextInstance) { - deleteHydratableInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - } - } - popToNextHostParent(fiber); - if (fiber.tag === SuspenseComponent) { - nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); - } else { - nextHydratableInstance = hydrationParentFiber - ? getNextHydratableSibling(fiber.stateNode) - : null; - } - return true; -} - -function hasUnhydratedTailNodes(): boolean { - return isHydrating && nextHydratableInstance !== null; -} - -function warnIfUnhydratedTailNodes(fiber: Fiber) { - let nextInstance = nextHydratableInstance; - while (nextInstance) { - warnUnhydratedInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } -} - -function resetHydrationState(): void { - if (!supportsHydration) { - return; - } - - hydrationParentFiber = null; - nextHydratableInstance = null; - isHydrating = false; - didSuspendOrErrorDEV = false; -} - -export function upgradeHydrationErrorsToRecoverable(): void { - if (hydrationErrors !== null) { - // Successfully completed a forced client render. The errors that occurred - // during the hydration attempt are now recovered. We will log them in - // commit phase, once the entire tree has finished. - queueRecoverableErrors(hydrationErrors); - hydrationErrors = null; - } -} - -function getIsHydrating(): boolean { - return isHydrating; -} - -export function queueHydrationError(error: CapturedValue): void { - if (hydrationErrors === null) { - hydrationErrors = [error]; - } else { - hydrationErrors.push(error); - } -} - -export { - warnIfHydrating, - enterHydrationState, - getIsHydrating, - reenterHydrationStateFromDehydratedSuspenseInstance, - resetHydrationState, - claimHydratableSingleton, - tryToClaimNextHydratableInstance, - prepareToHydrateHostInstance, - prepareToHydrateHostTextInstance, - prepareToHydrateHostSuspenseInstance, - popHydrationState, - hasUnhydratedTailNodes, - warnIfUnhydratedTailNodes, -}; diff --git a/packages/react-reconciler/src/ReactFiberLane.new.js b/packages/react-reconciler/src/ReactFiberLane.new.js deleted file mode 100644 index cc3781bd7b3ed..0000000000000 --- a/packages/react-reconciler/src/ReactFiberLane.new.js +++ /dev/null @@ -1,924 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Transition} from './ReactFiberTracingMarkerComponent.new'; -import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates.new'; - -// TODO: Ideally these types would be opaque but that doesn't work well with -// our reconciler fork infra, since these leak into non-reconciler packages. - -export type Lanes = number; -export type Lane = number; -export type LaneMap = Array; - -import { - enableSchedulingProfiler, - enableUpdaterTracking, - allowConcurrentByDefault, - enableTransitionTracing, -} from 'shared/ReactFeatureFlags'; -import {isDevToolsPresent} from './ReactFiberDevToolsHook.new'; -import {ConcurrentUpdatesByDefaultMode, NoMode} from './ReactTypeOfMode'; -import {clz32} from './clz32'; - -// Lane values below should be kept in sync with getLabelForLane(), used by react-devtools-timeline. -// If those values are changed that package should be rebuilt and redeployed. - -export const TotalLanes = 31; - -export const NoLanes: Lanes = /* */ 0b0000000000000000000000000000000; -export const NoLane: Lane = /* */ 0b0000000000000000000000000000000; - -export const SyncHydrationLane: Lane = /* */ 0b0000000000000000000000000000001; -export const SyncLane: Lane = /* */ 0b0000000000000000000000000000010; - -export const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000000100; -export const InputContinuousLane: Lane = /* */ 0b0000000000000000000000000001000; - -export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000000010000; -export const DefaultLane: Lane = /* */ 0b0000000000000000000000000100000; - -const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000001000000; -const TransitionLanes: Lanes = /* */ 0b0000000011111111111111110000000; -const TransitionLane1: Lane = /* */ 0b0000000000000000000000010000000; -const TransitionLane2: Lane = /* */ 0b0000000000000000000000100000000; -const TransitionLane3: Lane = /* */ 0b0000000000000000000001000000000; -const TransitionLane4: Lane = /* */ 0b0000000000000000000010000000000; -const TransitionLane5: Lane = /* */ 0b0000000000000000000100000000000; -const TransitionLane6: Lane = /* */ 0b0000000000000000001000000000000; -const TransitionLane7: Lane = /* */ 0b0000000000000000010000000000000; -const TransitionLane8: Lane = /* */ 0b0000000000000000100000000000000; -const TransitionLane9: Lane = /* */ 0b0000000000000001000000000000000; -const TransitionLane10: Lane = /* */ 0b0000000000000010000000000000000; -const TransitionLane11: Lane = /* */ 0b0000000000000100000000000000000; -const TransitionLane12: Lane = /* */ 0b0000000000001000000000000000000; -const TransitionLane13: Lane = /* */ 0b0000000000010000000000000000000; -const TransitionLane14: Lane = /* */ 0b0000000000100000000000000000000; -const TransitionLane15: Lane = /* */ 0b0000000001000000000000000000000; -const TransitionLane16: Lane = /* */ 0b0000000010000000000000000000000; - -const RetryLanes: Lanes = /* */ 0b0000111100000000000000000000000; -const RetryLane1: Lane = /* */ 0b0000000100000000000000000000000; -const RetryLane2: Lane = /* */ 0b0000001000000000000000000000000; -const RetryLane3: Lane = /* */ 0b0000010000000000000000000000000; -const RetryLane4: Lane = /* */ 0b0000100000000000000000000000000; - -export const SomeRetryLane: Lane = RetryLane1; - -export const SelectiveHydrationLane: Lane = /* */ 0b0001000000000000000000000000000; - -const NonIdleLanes: Lanes = /* */ 0b0001111111111111111111111111111; - -export const IdleHydrationLane: Lane = /* */ 0b0010000000000000000000000000000; -export const IdleLane: Lane = /* */ 0b0100000000000000000000000000000; - -export const OffscreenLane: Lane = /* */ 0b1000000000000000000000000000000; - -// This function is used for the experimental timeline (react-devtools-timeline) -// It should be kept in sync with the Lanes values above. -export function getLabelForLane(lane: Lane): string | void { - if (enableSchedulingProfiler) { - if (lane & SyncHydrationLane) { - return 'SyncHydrationLane'; - } - if (lane & SyncLane) { - return 'Sync'; - } - if (lane & InputContinuousHydrationLane) { - return 'InputContinuousHydration'; - } - if (lane & InputContinuousLane) { - return 'InputContinuous'; - } - if (lane & DefaultHydrationLane) { - return 'DefaultHydration'; - } - if (lane & DefaultLane) { - return 'Default'; - } - if (lane & TransitionHydrationLane) { - return 'TransitionHydration'; - } - if (lane & TransitionLanes) { - return 'Transition'; - } - if (lane & RetryLanes) { - return 'Retry'; - } - if (lane & SelectiveHydrationLane) { - return 'SelectiveHydration'; - } - if (lane & IdleHydrationLane) { - return 'IdleHydration'; - } - if (lane & IdleLane) { - return 'Idle'; - } - if (lane & OffscreenLane) { - return 'Offscreen'; - } - } -} - -export const NoTimestamp = -1; - -let nextTransitionLane: Lane = TransitionLane1; -let nextRetryLane: Lane = RetryLane1; - -function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes { - switch (getHighestPriorityLane(lanes)) { - case SyncHydrationLane: - return SyncHydrationLane; - case SyncLane: - return SyncLane; - case InputContinuousHydrationLane: - return InputContinuousHydrationLane; - case InputContinuousLane: - return InputContinuousLane; - case DefaultHydrationLane: - return DefaultHydrationLane; - case DefaultLane: - return DefaultLane; - case TransitionHydrationLane: - return TransitionHydrationLane; - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return lanes & TransitionLanes; - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - return lanes & RetryLanes; - case SelectiveHydrationLane: - return SelectiveHydrationLane; - case IdleHydrationLane: - return IdleHydrationLane; - case IdleLane: - return IdleLane; - case OffscreenLane: - return OffscreenLane; - default: - if (__DEV__) { - console.error( - 'Should have found matching lanes. This is a bug in React.', - ); - } - // This shouldn't be reachable, but as a fallback, return the entire bitmask. - return lanes; - } -} - -export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes { - // Early bailout if there's no pending work left. - const pendingLanes = root.pendingLanes; - if (pendingLanes === NoLanes) { - return NoLanes; - } - - let nextLanes = NoLanes; - - const suspendedLanes = root.suspendedLanes; - const pingedLanes = root.pingedLanes; - - // Do not work on any idle work until all the non-idle work has finished, - // even if the work is suspended. - const nonIdlePendingLanes = pendingLanes & NonIdleLanes; - if (nonIdlePendingLanes !== NoLanes) { - const nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; - if (nonIdleUnblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); - } else { - const nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; - if (nonIdlePingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); - } - } - } else { - // The only remaining work is Idle. - const unblockedLanes = pendingLanes & ~suspendedLanes; - if (unblockedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(unblockedLanes); - } else { - if (pingedLanes !== NoLanes) { - nextLanes = getHighestPriorityLanes(pingedLanes); - } - } - } - - if (nextLanes === NoLanes) { - // This should only be reachable if we're suspended - // TODO: Consider warning in this path if a fallback timer is not scheduled. - return NoLanes; - } - - // If we're already in the middle of a render, switching lanes will interrupt - // it and we'll lose our progress. We should only do this if the new lanes are - // higher priority. - if ( - wipLanes !== NoLanes && - wipLanes !== nextLanes && - // If we already suspended with a delay, then interrupting is fine. Don't - // bother waiting until the root is complete. - (wipLanes & suspendedLanes) === NoLanes - ) { - const nextLane = getHighestPriorityLane(nextLanes); - const wipLane = getHighestPriorityLane(wipLanes); - if ( - // Tests whether the next lane is equal or lower priority than the wip - // one. This works because the bits decrease in priority as you go left. - nextLane >= wipLane || - // Default priority updates should not interrupt transition updates. The - // only difference between default updates and transition updates is that - // default updates do not support refresh transitions. - (nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) - ) { - // Keep working on the existing in-progress tree. Do not interrupt. - return wipLanes; - } - } - - if ( - allowConcurrentByDefault && - (root.current.mode & ConcurrentUpdatesByDefaultMode) !== NoMode - ) { - // Do nothing, use the lanes as they were assigned. - } else if ((nextLanes & InputContinuousLane) !== NoLanes) { - // When updates are sync by default, we entangle continuous priority updates - // and default updates, so they render in the same batch. The only reason - // they use separate lanes is because continuous updates should interrupt - // transitions, but default updates should not. - nextLanes |= pendingLanes & DefaultLane; - } - - // Check for entangled lanes and add them to the batch. - // - // A lane is said to be entangled with another when it's not allowed to render - // in a batch that does not also include the other lane. Typically we do this - // when multiple updates have the same source, and we only want to respond to - // the most recent event from that source. - // - // Note that we apply entanglements *after* checking for partial work above. - // This means that if a lane is entangled during an interleaved event while - // it's already rendering, we won't interrupt it. This is intentional, since - // entanglement is usually "best effort": we'll try our best to render the - // lanes in the same batch, but it's not worth throwing out partially - // completed work in order to do it. - // TODO: Reconsider this. The counter-argument is that the partial work - // represents an intermediate state, which we don't want to show to the user. - // And by spending extra time finishing it, we're increasing the amount of - // time it takes to show the final state, which is what they are actually - // waiting for. - // - // For those exceptions where entanglement is semantically important, like - // useMutableSource, we should ensure that there is no partial work at the - // time we apply the entanglement. - const entangledLanes = root.entangledLanes; - if (entangledLanes !== NoLanes) { - const entanglements = root.entanglements; - let lanes = nextLanes & entangledLanes; - while (lanes > 0) { - const index = pickArbitraryLaneIndex(lanes); - const lane = 1 << index; - - nextLanes |= entanglements[index]; - - lanes &= ~lane; - } - } - - return nextLanes; -} - -export function getMostRecentEventTime(root: FiberRoot, lanes: Lanes): number { - const eventTimes = root.eventTimes; - - let mostRecentEventTime = NoTimestamp; - while (lanes > 0) { - const index = pickArbitraryLaneIndex(lanes); - const lane = 1 << index; - - const eventTime = eventTimes[index]; - if (eventTime > mostRecentEventTime) { - mostRecentEventTime = eventTime; - } - - lanes &= ~lane; - } - - return mostRecentEventTime; -} - -function computeExpirationTime(lane: Lane, currentTime: number) { - switch (lane) { - case SyncHydrationLane: - case SyncLane: - case InputContinuousHydrationLane: - case InputContinuousLane: - // User interactions should expire slightly more quickly. - // - // NOTE: This is set to the corresponding constant as in Scheduler.js. - // When we made it larger, a product metric in www regressed, suggesting - // there's a user interaction that's being starved by a series of - // synchronous updates. If that theory is correct, the proper solution is - // to fix the starvation. However, this scenario supports the idea that - // expiration times are an important safeguard when starvation - // does happen. - return currentTime + 250; - case DefaultHydrationLane: - case DefaultLane: - case TransitionHydrationLane: - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - return currentTime + 5000; - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - // TODO: Retries should be allowed to expire if they are CPU bound for - // too long, but when I made this change it caused a spike in browser - // crashes. There must be some other underlying bug; not super urgent but - // ideally should figure out why and fix it. Unfortunately we don't have - // a repro for the crashes, only detected via production metrics. - return NoTimestamp; - case SelectiveHydrationLane: - case IdleHydrationLane: - case IdleLane: - case OffscreenLane: - // Anything idle priority or lower should never expire. - return NoTimestamp; - default: - if (__DEV__) { - console.error( - 'Should have found matching lanes. This is a bug in React.', - ); - } - return NoTimestamp; - } -} - -export function markStarvedLanesAsExpired( - root: FiberRoot, - currentTime: number, -): void { - // TODO: This gets called every time we yield. We can optimize by storing - // the earliest expiration time on the root. Then use that to quickly bail out - // of this function. - - const pendingLanes = root.pendingLanes; - const suspendedLanes = root.suspendedLanes; - const pingedLanes = root.pingedLanes; - const expirationTimes = root.expirationTimes; - - // Iterate through the pending lanes and check if we've reached their - // expiration time. If so, we'll assume the update is being starved and mark - // it as expired to force it to finish. - // - // We exclude retry lanes because those must always be time sliced, in order - // to unwrap uncached promises. - // TODO: Write a test for this - let lanes = pendingLanes & ~RetryLanes; - while (lanes > 0) { - const index = pickArbitraryLaneIndex(lanes); - const lane = 1 << index; - - const expirationTime = expirationTimes[index]; - if (expirationTime === NoTimestamp) { - // Found a pending lane with no expiration time. If it's not suspended, or - // if it's pinged, assume it's CPU-bound. Compute a new expiration time - // using the current time. - if ( - (lane & suspendedLanes) === NoLanes || - (lane & pingedLanes) !== NoLanes - ) { - // Assumes timestamps are monotonically increasing. - expirationTimes[index] = computeExpirationTime(lane, currentTime); - } - } else if (expirationTime <= currentTime) { - // This lane expired - root.expiredLanes |= lane; - } - - lanes &= ~lane; - } -} - -// This returns the highest priority pending lanes regardless of whether they -// are suspended. -export function getHighestPriorityPendingLanes(root: FiberRoot): Lanes { - return getHighestPriorityLanes(root.pendingLanes); -} - -export function getLanesToRetrySynchronouslyOnError( - root: FiberRoot, - originallyAttemptedLanes: Lanes, -): Lanes { - if (root.errorRecoveryDisabledLanes & originallyAttemptedLanes) { - // The error recovery mechanism is disabled until these lanes are cleared. - return NoLanes; - } - - const everythingButOffscreen = root.pendingLanes & ~OffscreenLane; - if (everythingButOffscreen !== NoLanes) { - return everythingButOffscreen; - } - if (everythingButOffscreen & OffscreenLane) { - return OffscreenLane; - } - return NoLanes; -} - -export function includesSyncLane(lanes: Lanes): boolean { - return (lanes & (SyncLane | SyncHydrationLane)) !== NoLanes; -} - -export function includesNonIdleWork(lanes: Lanes): boolean { - return (lanes & NonIdleLanes) !== NoLanes; -} -export function includesOnlyRetries(lanes: Lanes): boolean { - return (lanes & RetryLanes) === lanes; -} -export function includesOnlyNonUrgentLanes(lanes: Lanes): boolean { - // TODO: Should hydration lanes be included here? This function is only - // used in `updateDeferredValueImpl`. - const UrgentLanes = SyncLane | InputContinuousLane | DefaultLane; - return (lanes & UrgentLanes) === NoLanes; -} -export function includesOnlyTransitions(lanes: Lanes): boolean { - return (lanes & TransitionLanes) === lanes; -} - -export function includesBlockingLane(root: FiberRoot, lanes: Lanes): boolean { - if ( - allowConcurrentByDefault && - (root.current.mode & ConcurrentUpdatesByDefaultMode) !== NoMode - ) { - // Concurrent updates by default always use time slicing. - return false; - } - const SyncDefaultLanes = - InputContinuousHydrationLane | - InputContinuousLane | - DefaultHydrationLane | - DefaultLane; - return (lanes & SyncDefaultLanes) !== NoLanes; -} - -export function includesExpiredLane(root: FiberRoot, lanes: Lanes): boolean { - // This is a separate check from includesBlockingLane because a lane can - // expire after a render has already started. - return (lanes & root.expiredLanes) !== NoLanes; -} - -export function isTransitionLane(lane: Lane): boolean { - return (lane & TransitionLanes) !== NoLanes; -} - -export function claimNextTransitionLane(): Lane { - // Cycle through the lanes, assigning each new transition to the next lane. - // In most cases, this means every transition gets its own lane, until we - // run out of lanes and cycle back to the beginning. - const lane = nextTransitionLane; - nextTransitionLane <<= 1; - if ((nextTransitionLane & TransitionLanes) === NoLanes) { - nextTransitionLane = TransitionLane1; - } - return lane; -} - -export function claimNextRetryLane(): Lane { - const lane = nextRetryLane; - nextRetryLane <<= 1; - if ((nextRetryLane & RetryLanes) === NoLanes) { - nextRetryLane = RetryLane1; - } - return lane; -} - -export function getHighestPriorityLane(lanes: Lanes): Lane { - return lanes & -lanes; -} - -export function pickArbitraryLane(lanes: Lanes): Lane { - // This wrapper function gets inlined. Only exists so to communicate that it - // doesn't matter which bit is selected; you can pick any bit without - // affecting the algorithms where its used. Here I'm using - // getHighestPriorityLane because it requires the fewest operations. - return getHighestPriorityLane(lanes); -} - -function pickArbitraryLaneIndex(lanes: Lanes) { - return 31 - clz32(lanes); -} - -function laneToIndex(lane: Lane) { - return pickArbitraryLaneIndex(lane); -} - -export function includesSomeLane(a: Lanes | Lane, b: Lanes | Lane): boolean { - return (a & b) !== NoLanes; -} - -export function isSubsetOfLanes(set: Lanes, subset: Lanes | Lane): boolean { - return (set & subset) === subset; -} - -export function mergeLanes(a: Lanes | Lane, b: Lanes | Lane): Lanes { - return a | b; -} - -export function removeLanes(set: Lanes, subset: Lanes | Lane): Lanes { - return set & ~subset; -} - -export function intersectLanes(a: Lanes | Lane, b: Lanes | Lane): Lanes { - return a & b; -} - -// Seems redundant, but it changes the type from a single lane (used for -// updates) to a group of lanes (used for flushing work). -export function laneToLanes(lane: Lane): Lanes { - return lane; -} - -export function higherPriorityLane(a: Lane, b: Lane): Lane { - // This works because the bit ranges decrease in priority as you go left. - return a !== NoLane && a < b ? a : b; -} - -export function createLaneMap(initial: T): LaneMap { - // Intentionally pushing one by one. - // https://v8.dev/blog/elements-kinds#avoid-creating-holes - const laneMap = []; - for (let i = 0; i < TotalLanes; i++) { - laneMap.push(initial); - } - return laneMap; -} - -export function markRootUpdated( - root: FiberRoot, - updateLane: Lane, - eventTime: number, -) { - root.pendingLanes |= updateLane; - - // If there are any suspended transitions, it's possible this new update - // could unblock them. Clear the suspended lanes so that we can try rendering - // them again. - // - // TODO: We really only need to unsuspend only lanes that are in the - // `subtreeLanes` of the updated fiber, or the update lanes of the return - // path. This would exclude suspended updates in an unrelated sibling tree, - // since there's no way for this update to unblock it. - // - // We don't do this if the incoming update is idle, because we never process - // idle updates until after all the regular updates have finished; there's no - // way it could unblock a transition. - if (updateLane !== IdleLane) { - root.suspendedLanes = NoLanes; - root.pingedLanes = NoLanes; - } - - const eventTimes = root.eventTimes; - const index = laneToIndex(updateLane); - // We can always overwrite an existing timestamp because we prefer the most - // recent event, and we assume time is monotonically increasing. - eventTimes[index] = eventTime; -} - -export function markRootSuspended(root: FiberRoot, suspendedLanes: Lanes) { - root.suspendedLanes |= suspendedLanes; - root.pingedLanes &= ~suspendedLanes; - - // The suspended lanes are no longer CPU-bound. Clear their expiration times. - const expirationTimes = root.expirationTimes; - let lanes = suspendedLanes; - while (lanes > 0) { - const index = pickArbitraryLaneIndex(lanes); - const lane = 1 << index; - - expirationTimes[index] = NoTimestamp; - - lanes &= ~lane; - } -} - -export function markRootPinged( - root: FiberRoot, - pingedLanes: Lanes, - eventTime: number, -) { - root.pingedLanes |= root.suspendedLanes & pingedLanes; -} - -export function markRootMutableRead(root: FiberRoot, updateLane: Lane) { - root.mutableReadLanes |= updateLane & root.pendingLanes; -} - -export function markRootFinished(root: FiberRoot, remainingLanes: Lanes) { - const noLongerPendingLanes = root.pendingLanes & ~remainingLanes; - - root.pendingLanes = remainingLanes; - - // Let's try everything again - root.suspendedLanes = NoLanes; - root.pingedLanes = NoLanes; - - root.expiredLanes &= remainingLanes; - root.mutableReadLanes &= remainingLanes; - - root.entangledLanes &= remainingLanes; - - root.errorRecoveryDisabledLanes &= remainingLanes; - - const entanglements = root.entanglements; - const eventTimes = root.eventTimes; - const expirationTimes = root.expirationTimes; - const hiddenUpdates = root.hiddenUpdates; - - // Clear the lanes that no longer have pending work - let lanes = noLongerPendingLanes; - while (lanes > 0) { - const index = pickArbitraryLaneIndex(lanes); - const lane = 1 << index; - - entanglements[index] = NoLanes; - eventTimes[index] = NoTimestamp; - expirationTimes[index] = NoTimestamp; - - const hiddenUpdatesForLane = hiddenUpdates[index]; - if (hiddenUpdatesForLane !== null) { - hiddenUpdates[index] = null; - // "Hidden" updates are updates that were made to a hidden component. They - // have special logic associated with them because they may be entangled - // with updates that occur outside that tree. But once the outer tree - // commits, they behave like regular updates. - for (let i = 0; i < hiddenUpdatesForLane.length; i++) { - const update = hiddenUpdatesForLane[i]; - if (update !== null) { - update.lane &= ~OffscreenLane; - } - } - } - - lanes &= ~lane; - } -} - -export function markRootEntangled(root: FiberRoot, entangledLanes: Lanes) { - // In addition to entangling each of the given lanes with each other, we also - // have to consider _transitive_ entanglements. For each lane that is already - // entangled with *any* of the given lanes, that lane is now transitively - // entangled with *all* the given lanes. - // - // Translated: If C is entangled with A, then entangling A with B also - // entangles C with B. - // - // If this is hard to grasp, it might help to intentionally break this - // function and look at the tests that fail in ReactTransition-test.js. Try - // commenting out one of the conditions below. - - const rootEntangledLanes = (root.entangledLanes |= entangledLanes); - const entanglements = root.entanglements; - let lanes = rootEntangledLanes; - while (lanes) { - const index = pickArbitraryLaneIndex(lanes); - const lane = 1 << index; - if ( - // Is this one of the newly entangled lanes? - (lane & entangledLanes) | - // Is this lane transitively entangled with the newly entangled lanes? - (entanglements[index] & entangledLanes) - ) { - entanglements[index] |= entangledLanes; - } - lanes &= ~lane; - } -} - -export function markHiddenUpdate( - root: FiberRoot, - update: ConcurrentUpdate, - lane: Lane, -) { - const index = laneToIndex(lane); - const hiddenUpdates = root.hiddenUpdates; - const hiddenUpdatesForLane = hiddenUpdates[index]; - if (hiddenUpdatesForLane === null) { - hiddenUpdates[index] = [update]; - } else { - hiddenUpdatesForLane.push(update); - } - update.lane = lane | OffscreenLane; -} - -export function getBumpedLaneForHydration( - root: FiberRoot, - renderLanes: Lanes, -): Lane { - const renderLane = getHighestPriorityLane(renderLanes); - - let lane; - switch (renderLane) { - case SyncLane: - lane = SyncHydrationLane; - break; - case InputContinuousLane: - lane = InputContinuousHydrationLane; - break; - case DefaultLane: - lane = DefaultHydrationLane; - break; - case TransitionLane1: - case TransitionLane2: - case TransitionLane3: - case TransitionLane4: - case TransitionLane5: - case TransitionLane6: - case TransitionLane7: - case TransitionLane8: - case TransitionLane9: - case TransitionLane10: - case TransitionLane11: - case TransitionLane12: - case TransitionLane13: - case TransitionLane14: - case TransitionLane15: - case TransitionLane16: - case RetryLane1: - case RetryLane2: - case RetryLane3: - case RetryLane4: - lane = TransitionHydrationLane; - break; - case IdleLane: - lane = IdleHydrationLane; - break; - default: - // Everything else is already either a hydration lane, or shouldn't - // be retried at a hydration lane. - lane = NoLane; - break; - } - - // Check if the lane we chose is suspended. If so, that indicates that we - // already attempted and failed to hydrate at that level. Also check if we're - // already rendering that lane, which is rare but could happen. - if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { - // Give up trying to hydrate and fall back to client render. - return NoLane; - } - - return lane; -} - -export function addFiberToLanesMap( - root: FiberRoot, - fiber: Fiber, - lanes: Lanes | Lane, -) { - if (!enableUpdaterTracking) { - return; - } - if (!isDevToolsPresent) { - return; - } - const pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - while (lanes > 0) { - const index = laneToIndex(lanes); - const lane = 1 << index; - - const updaters = pendingUpdatersLaneMap[index]; - updaters.add(fiber); - - lanes &= ~lane; - } -} - -export function movePendingFibersToMemoized(root: FiberRoot, lanes: Lanes) { - if (!enableUpdaterTracking) { - return; - } - if (!isDevToolsPresent) { - return; - } - const pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; - const memoizedUpdaters = root.memoizedUpdaters; - while (lanes > 0) { - const index = laneToIndex(lanes); - const lane = 1 << index; - - const updaters = pendingUpdatersLaneMap[index]; - if (updaters.size > 0) { - updaters.forEach(fiber => { - const alternate = fiber.alternate; - if (alternate === null || !memoizedUpdaters.has(alternate)) { - memoizedUpdaters.add(fiber); - } - }); - updaters.clear(); - } - - lanes &= ~lane; - } -} - -export function addTransitionToLanesMap( - root: FiberRoot, - transition: Transition, - lane: Lane, -) { - if (enableTransitionTracing) { - const transitionLanesMap = root.transitionLanes; - const index = laneToIndex(lane); - let transitions = transitionLanesMap[index]; - if (transitions === null) { - transitions = new Set(); - } - transitions.add(transition); - - transitionLanesMap[index] = transitions; - } -} - -export function getTransitionsForLanes( - root: FiberRoot, - lanes: Lane | Lanes, -): Array | null { - if (!enableTransitionTracing) { - return null; - } - - const transitionsForLanes = []; - while (lanes > 0) { - const index = laneToIndex(lanes); - const lane = 1 << index; - const transitions = root.transitionLanes[index]; - if (transitions !== null) { - transitions.forEach(transition => { - transitionsForLanes.push(transition); - }); - } - - lanes &= ~lane; - } - - if (transitionsForLanes.length === 0) { - return null; - } - - return transitionsForLanes; -} - -export function clearTransitionsForLanes(root: FiberRoot, lanes: Lane | Lanes) { - if (!enableTransitionTracing) { - return; - } - - while (lanes > 0) { - const index = laneToIndex(lanes); - const lane = 1 << index; - - const transitions = root.transitionLanes[index]; - if (transitions !== null) { - root.transitionLanes[index] = null; - } - - lanes &= ~lane; - } -} diff --git a/packages/react-reconciler/src/ReactFiberLazyComponent.new.js b/packages/react-reconciler/src/ReactFiberLazyComponent.new.js deleted file mode 100644 index b66f8efe4ed1b..0000000000000 --- a/packages/react-reconciler/src/ReactFiberLazyComponent.new.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import assign from 'shared/assign'; - -export function resolveDefaultProps(Component: any, baseProps: Object): Object { - if (Component && Component.defaultProps) { - // Resolve default props. Taken from ReactElement - const props = assign({}, baseProps); - const defaultProps = Component.defaultProps; - for (const propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName]; - } - } - return props; - } - return baseProps; -} diff --git a/packages/react-reconciler/src/ReactFiberNewContext.new.js b/packages/react-reconciler/src/ReactFiberNewContext.new.js deleted file mode 100644 index f27abacb65951..0000000000000 --- a/packages/react-reconciler/src/ReactFiberNewContext.new.js +++ /dev/null @@ -1,706 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {ReactContext, ReactProviderType} from 'shared/ReactTypes'; -import type { - Fiber, - ContextDependency, - Dependencies, -} from './ReactInternalTypes'; -import type {StackCursor} from './ReactFiberStack.new'; -import type {Lanes} from './ReactFiberLane.new'; -import type {SharedQueue} from './ReactFiberClassUpdateQueue.new'; - -import {isPrimaryRenderer} from './ReactFiberHostConfig'; -import {createCursor, push, pop} from './ReactFiberStack.new'; -import { - ContextProvider, - ClassComponent, - DehydratedFragment, -} from './ReactWorkTags'; -import { - NoLanes, - NoTimestamp, - isSubsetOfLanes, - includesSomeLane, - mergeLanes, - pickArbitraryLane, -} from './ReactFiberLane.new'; -import { - NoFlags, - DidPropagateContext, - NeedsPropagation, -} from './ReactFiberFlags'; - -import is from 'shared/objectIs'; -import {createUpdate, ForceUpdate} from './ReactFiberClassUpdateQueue.new'; -import {markWorkInProgressReceivedUpdate} from './ReactFiberBeginWork.new'; -import { - enableLazyContextPropagation, - enableServerContext, -} from 'shared/ReactFeatureFlags'; -import {REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED} from 'shared/ReactSymbols'; - -const valueCursor: StackCursor = createCursor(null); - -let rendererSigil; -if (__DEV__) { - // Use this to detect multiple renderers using the same context - rendererSigil = {}; -} - -let currentlyRenderingFiber: Fiber | null = null; -let lastContextDependency: ContextDependency | null = null; -let lastFullyObservedContext: ReactContext | null = null; - -let isDisallowedContextReadInDEV: boolean = false; - -export function resetContextDependencies(): void { - // This is called right before React yields execution, to ensure `readContext` - // cannot be called outside the render phase. - currentlyRenderingFiber = null; - lastContextDependency = null; - lastFullyObservedContext = null; - if (__DEV__) { - isDisallowedContextReadInDEV = false; - } -} - -export function enterDisallowedContextReadInDEV(): void { - if (__DEV__) { - isDisallowedContextReadInDEV = true; - } -} - -export function exitDisallowedContextReadInDEV(): void { - if (__DEV__) { - isDisallowedContextReadInDEV = false; - } -} - -export function pushProvider( - providerFiber: Fiber, - context: ReactContext, - nextValue: T, -): void { - if (isPrimaryRenderer) { - push(valueCursor, context._currentValue, providerFiber); - - context._currentValue = nextValue; - if (__DEV__) { - if ( - context._currentRenderer !== undefined && - context._currentRenderer !== null && - context._currentRenderer !== rendererSigil - ) { - console.error( - 'Detected multiple renderers concurrently rendering the ' + - 'same context provider. This is currently unsupported.', - ); - } - context._currentRenderer = rendererSigil; - } - } else { - push(valueCursor, context._currentValue2, providerFiber); - - context._currentValue2 = nextValue; - if (__DEV__) { - if ( - context._currentRenderer2 !== undefined && - context._currentRenderer2 !== null && - context._currentRenderer2 !== rendererSigil - ) { - console.error( - 'Detected multiple renderers concurrently rendering the ' + - 'same context provider. This is currently unsupported.', - ); - } - context._currentRenderer2 = rendererSigil; - } - } -} - -export function popProvider( - context: ReactContext, - providerFiber: Fiber, -): void { - const currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - if (isPrimaryRenderer) { - if ( - enableServerContext && - currentValue === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED - ) { - context._currentValue = context._defaultValue; - } else { - context._currentValue = currentValue; - } - } else { - if ( - enableServerContext && - currentValue === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED - ) { - context._currentValue2 = context._defaultValue; - } else { - context._currentValue2 = currentValue; - } - } -} - -export function scheduleContextWorkOnParentPath( - parent: Fiber | null, - renderLanes: Lanes, - propagationRoot: Fiber, -) { - // Update the child lanes of all the ancestors, including the alternates. - let node = parent; - while (node !== null) { - const alternate = node.alternate; - if (!isSubsetOfLanes(node.childLanes, renderLanes)) { - node.childLanes = mergeLanes(node.childLanes, renderLanes); - if (alternate !== null) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); - } - } else if ( - alternate !== null && - !isSubsetOfLanes(alternate.childLanes, renderLanes) - ) { - alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); - } else { - // Neither alternate was updated. - // Normally, this would mean that the rest of the - // ancestor path already has sufficient priority. - // However, this is not necessarily true inside offscreen - // or fallback trees because childLanes may be inconsistent - // with the surroundings. This is why we continue the loop. - } - if (node === propagationRoot) { - break; - } - node = node.return; - } - if (__DEV__) { - if (node !== propagationRoot) { - console.error( - 'Expected to find the propagation root when scheduling context work. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - } - } -} - -export function propagateContextChange( - workInProgress: Fiber, - context: ReactContext, - renderLanes: Lanes, -): void { - if (enableLazyContextPropagation) { - // TODO: This path is only used by Cache components. Update - // lazilyPropagateParentContextChanges to look for Cache components so they - // can take advantage of lazy propagation. - const forcePropagateEntireTree = true; - propagateContextChanges( - workInProgress, - [context], - renderLanes, - forcePropagateEntireTree, - ); - } else { - propagateContextChange_eager(workInProgress, context, renderLanes); - } -} - -function propagateContextChange_eager( - workInProgress: Fiber, - context: ReactContext, - renderLanes: Lanes, -): void { - // Only used by eager implementation - if (enableLazyContextPropagation) { - return; - } - let fiber = workInProgress.child; - if (fiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - fiber.return = workInProgress; - } - while (fiber !== null) { - let nextFiber; - - // Visit this fiber. - const list = fiber.dependencies; - if (list !== null) { - nextFiber = fiber.child; - - let dependency = list.firstContext; - while (dependency !== null) { - // Check if the context matches. - if (dependency.context === context) { - // Match! Schedule an update on this fiber. - if (fiber.tag === ClassComponent) { - // Schedule a force update on the work-in-progress. - const lane = pickArbitraryLane(renderLanes); - const update = createUpdate(NoTimestamp, lane); - update.tag = ForceUpdate; - // TODO: Because we don't have a work-in-progress, this will add the - // update to the current fiber, too, which means it will persist even if - // this render is thrown away. Since it's a race condition, not sure it's - // worth fixing. - - // Inlined `enqueueUpdate` to remove interleaved update check - const updateQueue = fiber.updateQueue; - if (updateQueue === null) { - // Only occurs if the fiber has been unmounted. - } else { - const sharedQueue: SharedQueue = (updateQueue: any).shared; - const pending = sharedQueue.pending; - if (pending === null) { - // This is the first update. Create a circular list. - update.next = update; - } else { - update.next = pending.next; - pending.next = update; - } - sharedQueue.pending = update; - } - } - - fiber.lanes = mergeLanes(fiber.lanes, renderLanes); - const alternate = fiber.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - scheduleContextWorkOnParentPath( - fiber.return, - renderLanes, - workInProgress, - ); - - // Mark the updated lanes on the list, too. - list.lanes = mergeLanes(list.lanes, renderLanes); - - // Since we already found a match, we can stop traversing the - // dependency list. - break; - } - dependency = dependency.next; - } - } else if (fiber.tag === ContextProvider) { - // Don't scan deeper if this is a matching provider - nextFiber = fiber.type === workInProgress.type ? null : fiber.child; - } else if (fiber.tag === DehydratedFragment) { - // If a dehydrated suspense boundary is in this subtree, we don't know - // if it will have any context consumers in it. The best we can do is - // mark it as having updates. - const parentSuspense = fiber.return; - - if (parentSuspense === null) { - throw new Error( - 'We just came from a parent so we must have had a parent. This is a bug in React.', - ); - } - - parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); - const alternate = parentSuspense.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - // This is intentionally passing this fiber as the parent - // because we want to schedule this fiber as having work - // on its children. We'll use the childLanes on - // this fiber to indicate that a context has changed. - scheduleContextWorkOnParentPath( - parentSuspense, - renderLanes, - workInProgress, - ); - nextFiber = fiber.sibling; - } else { - // Traverse down. - nextFiber = fiber.child; - } - - if (nextFiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - nextFiber.return = fiber; - } else { - // No child. Traverse to next sibling. - nextFiber = fiber; - while (nextFiber !== null) { - if (nextFiber === workInProgress) { - // We're back to the root of this subtree. Exit. - nextFiber = null; - break; - } - const sibling = nextFiber.sibling; - if (sibling !== null) { - // Set the return pointer of the sibling to the work-in-progress fiber. - sibling.return = nextFiber.return; - nextFiber = sibling; - break; - } - // No more siblings. Traverse up. - nextFiber = nextFiber.return; - } - } - fiber = nextFiber; - } -} - -function propagateContextChanges( - workInProgress: Fiber, - contexts: Array, - renderLanes: Lanes, - forcePropagateEntireTree: boolean, -): void { - // Only used by lazy implementation - if (!enableLazyContextPropagation) { - return; - } - let fiber = workInProgress.child; - if (fiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - fiber.return = workInProgress; - } - while (fiber !== null) { - let nextFiber; - - // Visit this fiber. - const list = fiber.dependencies; - if (list !== null) { - nextFiber = fiber.child; - - let dep = list.firstContext; - findChangedDep: while (dep !== null) { - // Assigning these to constants to help Flow - const dependency = dep; - const consumer = fiber; - findContext: for (let i = 0; i < contexts.length; i++) { - const context: ReactContext = contexts[i]; - // Check if the context matches. - // TODO: Compare selected values to bail out early. - if (dependency.context === context) { - // Match! Schedule an update on this fiber. - - // In the lazy implementation, don't mark a dirty flag on the - // dependency itself. Not all changes are propagated, so we can't - // rely on the propagation function alone to determine whether - // something has changed; the consumer will check. In the future, we - // could add back a dirty flag as an optimization to avoid double - // checking, but until we have selectors it's not really worth - // the trouble. - consumer.lanes = mergeLanes(consumer.lanes, renderLanes); - const alternate = consumer.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - scheduleContextWorkOnParentPath( - consumer.return, - renderLanes, - workInProgress, - ); - - if (!forcePropagateEntireTree) { - // During lazy propagation, when we find a match, we can defer - // propagating changes to the children, because we're going to - // visit them during render. We should continue propagating the - // siblings, though - nextFiber = null; - } - - // Since we already found a match, we can stop traversing the - // dependency list. - break findChangedDep; - } - } - dep = dependency.next; - } - } else if (fiber.tag === DehydratedFragment) { - // If a dehydrated suspense boundary is in this subtree, we don't know - // if it will have any context consumers in it. The best we can do is - // mark it as having updates. - const parentSuspense = fiber.return; - - if (parentSuspense === null) { - throw new Error( - 'We just came from a parent so we must have had a parent. This is a bug in React.', - ); - } - - parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); - const alternate = parentSuspense.alternate; - if (alternate !== null) { - alternate.lanes = mergeLanes(alternate.lanes, renderLanes); - } - // This is intentionally passing this fiber as the parent - // because we want to schedule this fiber as having work - // on its children. We'll use the childLanes on - // this fiber to indicate that a context has changed. - scheduleContextWorkOnParentPath( - parentSuspense, - renderLanes, - workInProgress, - ); - nextFiber = null; - } else { - // Traverse down. - nextFiber = fiber.child; - } - - if (nextFiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - nextFiber.return = fiber; - } else { - // No child. Traverse to next sibling. - nextFiber = fiber; - while (nextFiber !== null) { - if (nextFiber === workInProgress) { - // We're back to the root of this subtree. Exit. - nextFiber = null; - break; - } - const sibling = nextFiber.sibling; - if (sibling !== null) { - // Set the return pointer of the sibling to the work-in-progress fiber. - sibling.return = nextFiber.return; - nextFiber = sibling; - break; - } - // No more siblings. Traverse up. - nextFiber = nextFiber.return; - } - } - fiber = nextFiber; - } -} - -export function lazilyPropagateParentContextChanges( - current: Fiber, - workInProgress: Fiber, - renderLanes: Lanes, -) { - const forcePropagateEntireTree = false; - propagateParentContextChanges( - current, - workInProgress, - renderLanes, - forcePropagateEntireTree, - ); -} - -// Used for propagating a deferred tree (Suspense, Offscreen). We must propagate -// to the entire subtree, because we won't revisit it until after the current -// render has completed, at which point we'll have lost track of which providers -// have changed. -export function propagateParentContextChangesToDeferredTree( - current: Fiber, - workInProgress: Fiber, - renderLanes: Lanes, -) { - const forcePropagateEntireTree = true; - propagateParentContextChanges( - current, - workInProgress, - renderLanes, - forcePropagateEntireTree, - ); -} - -function propagateParentContextChanges( - current: Fiber, - workInProgress: Fiber, - renderLanes: Lanes, - forcePropagateEntireTree: boolean, -) { - if (!enableLazyContextPropagation) { - return; - } - - // Collect all the parent providers that changed. Since this is usually small - // number, we use an Array instead of Set. - let contexts = null; - let parent: null | Fiber = workInProgress; - let isInsidePropagationBailout = false; - while (parent !== null) { - if (!isInsidePropagationBailout) { - if ((parent.flags & NeedsPropagation) !== NoFlags) { - isInsidePropagationBailout = true; - } else if ((parent.flags & DidPropagateContext) !== NoFlags) { - break; - } - } - - if (parent.tag === ContextProvider) { - const currentParent = parent.alternate; - - if (currentParent === null) { - throw new Error('Should have a current fiber. This is a bug in React.'); - } - - const oldProps = currentParent.memoizedProps; - if (oldProps !== null) { - const providerType: ReactProviderType = parent.type; - const context: ReactContext = providerType._context; - - const newProps = parent.pendingProps; - const newValue = newProps.value; - - const oldValue = oldProps.value; - - if (!is(newValue, oldValue)) { - if (contexts !== null) { - contexts.push(context); - } else { - contexts = [context]; - } - } - } - } - parent = parent.return; - } - - if (contexts !== null) { - // If there were any changed providers, search through the children and - // propagate their changes. - propagateContextChanges( - workInProgress, - contexts, - renderLanes, - forcePropagateEntireTree, - ); - } - - // This is an optimization so that we only propagate once per subtree. If a - // deeply nested child bails out, and it calls this propagation function, it - // uses this flag to know that the remaining ancestor providers have already - // been propagated. - // - // NOTE: This optimization is only necessary because we sometimes enter the - // begin phase of nodes that don't have any work scheduled on them — - // specifically, the siblings of a node that _does_ have scheduled work. The - // siblings will bail out and call this function again, even though we already - // propagated content changes to it and its subtree. So we use this flag to - // mark that the parent providers already propagated. - // - // Unfortunately, though, we need to ignore this flag when we're inside a - // tree whose context propagation was deferred — that's what the - // `NeedsPropagation` flag is for. - // - // If we could instead bail out before entering the siblings' begin phase, - // then we could remove both `DidPropagateContext` and `NeedsPropagation`. - // Consider this as part of the next refactor to the fiber tree structure. - workInProgress.flags |= DidPropagateContext; -} - -export function checkIfContextChanged( - currentDependencies: Dependencies, -): boolean { - if (!enableLazyContextPropagation) { - return false; - } - // Iterate over the current dependencies to see if something changed. This - // only gets called if props and state has already bailed out, so it's a - // relatively uncommon path, except at the root of a changed subtree. - // Alternatively, we could move these comparisons into `readContext`, but - // that's a much hotter path, so I think this is an appropriate trade off. - let dependency = currentDependencies.firstContext; - while (dependency !== null) { - const context = dependency.context; - const newValue = isPrimaryRenderer - ? context._currentValue - : context._currentValue2; - const oldValue = dependency.memoizedValue; - if (!is(newValue, oldValue)) { - return true; - } - dependency = dependency.next; - } - return false; -} - -export function prepareToReadContext( - workInProgress: Fiber, - renderLanes: Lanes, -): void { - currentlyRenderingFiber = workInProgress; - lastContextDependency = null; - lastFullyObservedContext = null; - - const dependencies = workInProgress.dependencies; - if (dependencies !== null) { - if (enableLazyContextPropagation) { - // Reset the work-in-progress list - dependencies.firstContext = null; - } else { - const firstContext = dependencies.firstContext; - if (firstContext !== null) { - if (includesSomeLane(dependencies.lanes, renderLanes)) { - // Context list has a pending update. Mark that this fiber performed work. - markWorkInProgressReceivedUpdate(); - } - // Reset the work-in-progress list - dependencies.firstContext = null; - } - } - } -} - -export function readContext(context: ReactContext): T { - if (__DEV__) { - // This warning would fire if you read context inside a Hook like useMemo. - // Unlike the class check below, it's not enforced in production for perf. - if (isDisallowedContextReadInDEV) { - console.error( - 'Context can only be read while React is rendering. ' + - 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + - 'In function components, you can read it directly in the function body, but not ' + - 'inside Hooks like useReducer() or useMemo().', - ); - } - } - - const value = isPrimaryRenderer - ? context._currentValue - : context._currentValue2; - - if (lastFullyObservedContext === context) { - // Nothing to do. We already observe everything in this context. - } else { - const contextItem = { - context: ((context: any): ReactContext), - memoizedValue: value, - next: null, - }; - - if (lastContextDependency === null) { - if (currentlyRenderingFiber === null) { - throw new Error( - 'Context can only be read while React is rendering. ' + - 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + - 'In function components, you can read it directly in the function body, but not ' + - 'inside Hooks like useReducer() or useMemo().', - ); - } - - // This is the first dependency for this component. Create a new list. - lastContextDependency = contextItem; - currentlyRenderingFiber.dependencies = { - lanes: NoLanes, - firstContext: contextItem, - }; - if (enableLazyContextPropagation) { - currentlyRenderingFiber.flags |= NeedsPropagation; - } - } else { - // Append a new context item. - lastContextDependency = lastContextDependency.next = contextItem; - } - } - return value; -} diff --git a/packages/react-reconciler/src/ReactFiberOffscreenComponent.js b/packages/react-reconciler/src/ReactFiberOffscreenComponent.js index 9d0030ea22b23..1a2038a43010f 100644 --- a/packages/react-reconciler/src/ReactFiberOffscreenComponent.js +++ b/packages/react-reconciler/src/ReactFiberOffscreenComponent.js @@ -9,12 +9,12 @@ import type {ReactNodeList, OffscreenMode, Wakeable} from 'shared/ReactTypes'; import type {Lanes} from './ReactFiberLane.old'; -import type {SpawnedCachePool} from './ReactFiberCacheComponent.new'; +import type {SpawnedCachePool} from './ReactFiberCacheComponent.old'; import type {Fiber} from './ReactInternalTypes'; import type { Transition, TracingMarkerInstance, -} from './ReactFiberTracingMarkerComponent.new'; +} from './ReactFiberTracingMarkerComponent.old'; export type OffscreenProps = { // TODO: Pick an API before exposing the Offscreen type. I've chosen an enum diff --git a/packages/react-reconciler/src/ReactFiberReconciler.js b/packages/react-reconciler/src/ReactFiberReconciler.js deleted file mode 100644 index 61d589936da7c..0000000000000 --- a/packages/react-reconciler/src/ReactFiberReconciler.js +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import {enableNewReconciler} from 'shared/ReactFeatureFlags'; - -// The entry file imports either the old or new version of the reconciler. -// During build and testing, this indirection is always shimmed with the actual -// modules, otherwise both reconcilers would be initialized. So this is really -// only here for Flow purposes. - -import { - createContainer as createContainer_old, - createHydrationContainer as createHydrationContainer_old, - updateContainer as updateContainer_old, - batchedUpdates as batchedUpdates_old, - deferredUpdates as deferredUpdates_old, - discreteUpdates as discreteUpdates_old, - flushControlled as flushControlled_old, - flushSync as flushSync_old, - isAlreadyRendering as isAlreadyRendering_old, - flushPassiveEffects as flushPassiveEffects_old, - getPublicRootInstance as getPublicRootInstance_old, - attemptSynchronousHydration as attemptSynchronousHydration_old, - attemptDiscreteHydration as attemptDiscreteHydration_old, - attemptContinuousHydration as attemptContinuousHydration_old, - attemptHydrationAtCurrentPriority as attemptHydrationAtCurrentPriority_old, - findHostInstance as findHostInstance_old, - findHostInstanceWithWarning as findHostInstanceWithWarning_old, - findHostInstanceWithNoPortals as findHostInstanceWithNoPortals_old, - shouldError as shouldError_old, - shouldSuspend as shouldSuspend_old, - injectIntoDevTools as injectIntoDevTools_old, - createPortal as createPortal_old, - createComponentSelector as createComponentSelector_old, - createHasPseudoClassSelector as createHasPseudoClassSelector_old, - createRoleSelector as createRoleSelector_old, - createTestNameSelector as createTestNameSelector_old, - createTextSelector as createTextSelector_old, - getFindAllNodesFailureDescription as getFindAllNodesFailureDescription_old, - findAllNodes as findAllNodes_old, - findBoundingRects as findBoundingRects_old, - focusWithin as focusWithin_old, - observeVisibleRects as observeVisibleRects_old, - registerMutableSourceForHydration as registerMutableSourceForHydration_old, - runWithPriority as runWithPriority_old, - getCurrentUpdatePriority as getCurrentUpdatePriority_old, -} from './ReactFiberReconciler.old'; - -import { - createContainer as createContainer_new, - createHydrationContainer as createHydrationContainer_new, - updateContainer as updateContainer_new, - batchedUpdates as batchedUpdates_new, - deferredUpdates as deferredUpdates_new, - discreteUpdates as discreteUpdates_new, - flushControlled as flushControlled_new, - flushSync as flushSync_new, - isAlreadyRendering as isAlreadyRendering_new, - flushPassiveEffects as flushPassiveEffects_new, - getPublicRootInstance as getPublicRootInstance_new, - attemptSynchronousHydration as attemptSynchronousHydration_new, - attemptDiscreteHydration as attemptDiscreteHydration_new, - attemptContinuousHydration as attemptContinuousHydration_new, - attemptHydrationAtCurrentPriority as attemptHydrationAtCurrentPriority_new, - findHostInstance as findHostInstance_new, - findHostInstanceWithWarning as findHostInstanceWithWarning_new, - findHostInstanceWithNoPortals as findHostInstanceWithNoPortals_new, - shouldError as shouldError_new, - shouldSuspend as shouldSuspend_new, - injectIntoDevTools as injectIntoDevTools_new, - createPortal as createPortal_new, - createComponentSelector as createComponentSelector_new, - createHasPseudoClassSelector as createHasPseudoClassSelector_new, - createRoleSelector as createRoleSelector_new, - createTestNameSelector as createTestNameSelector_new, - createTextSelector as createTextSelector_new, - getFindAllNodesFailureDescription as getFindAllNodesFailureDescription_new, - findAllNodes as findAllNodes_new, - findBoundingRects as findBoundingRects_new, - focusWithin as focusWithin_new, - observeVisibleRects as observeVisibleRects_new, - registerMutableSourceForHydration as registerMutableSourceForHydration_new, - runWithPriority as runWithPriority_new, - getCurrentUpdatePriority as getCurrentUpdatePriority_new, -} from './ReactFiberReconciler.new'; - -export const createContainer: typeof createContainer_new = enableNewReconciler - ? createContainer_new - : createContainer_old; -export const createHydrationContainer: typeof createHydrationContainer_new = enableNewReconciler - ? createHydrationContainer_new - : createHydrationContainer_old; -export const updateContainer: typeof updateContainer_new = enableNewReconciler - ? updateContainer_new - : updateContainer_old; -export const batchedUpdates: typeof batchedUpdates_new = enableNewReconciler - ? batchedUpdates_new - : batchedUpdates_old; -export const deferredUpdates: typeof deferredUpdates_new = enableNewReconciler - ? deferredUpdates_new - : deferredUpdates_old; -export const discreteUpdates: typeof discreteUpdates_new = enableNewReconciler - ? discreteUpdates_new - : discreteUpdates_old; -export const flushControlled: typeof flushControlled_new = enableNewReconciler - ? flushControlled_new - : flushControlled_old; -export const flushSync: typeof flushSync_new = enableNewReconciler - ? flushSync_new - : flushSync_old; -export const isAlreadyRendering: typeof isAlreadyRendering_new = enableNewReconciler - ? isAlreadyRendering_new - : isAlreadyRendering_old; -export const flushPassiveEffects: typeof flushPassiveEffects_new = enableNewReconciler - ? flushPassiveEffects_new - : flushPassiveEffects_old; -export const getPublicRootInstance: typeof getPublicRootInstance_new = enableNewReconciler - ? getPublicRootInstance_new - : getPublicRootInstance_old; -export const attemptSynchronousHydration: typeof attemptSynchronousHydration_new = enableNewReconciler - ? attemptSynchronousHydration_new - : attemptSynchronousHydration_old; -export const attemptDiscreteHydration: typeof attemptDiscreteHydration_new = enableNewReconciler - ? attemptDiscreteHydration_new - : attemptDiscreteHydration_old; -export const attemptContinuousHydration: typeof attemptContinuousHydration_new = enableNewReconciler - ? attemptContinuousHydration_new - : attemptContinuousHydration_old; -export const attemptHydrationAtCurrentPriority: typeof attemptHydrationAtCurrentPriority_new = enableNewReconciler - ? attemptHydrationAtCurrentPriority_new - : attemptHydrationAtCurrentPriority_old; -export const getCurrentUpdatePriority: typeof getCurrentUpdatePriority_new = enableNewReconciler - ? getCurrentUpdatePriority_new - : /* $FlowFixMe[incompatible-type] opaque types EventPriority from new and old - * are incompatible. */ - getCurrentUpdatePriority_old; -export const findHostInstance: typeof findHostInstance_new = enableNewReconciler - ? findHostInstance_new - : findHostInstance_old; -export const findHostInstanceWithWarning: typeof findHostInstanceWithWarning_new = enableNewReconciler - ? findHostInstanceWithWarning_new - : findHostInstanceWithWarning_old; -export const findHostInstanceWithNoPortals: typeof findHostInstanceWithNoPortals_new = enableNewReconciler - ? findHostInstanceWithNoPortals_new - : findHostInstanceWithNoPortals_old; -export const shouldError: typeof shouldError_new = enableNewReconciler - ? shouldError_new - : shouldError_old; -export const shouldSuspend: typeof shouldSuspend_new = enableNewReconciler - ? shouldSuspend_new - : shouldSuspend_old; -export const injectIntoDevTools: typeof injectIntoDevTools_new = enableNewReconciler - ? injectIntoDevTools_new - : injectIntoDevTools_old; -export const createPortal: typeof createPortal_new = enableNewReconciler - ? createPortal_new - : createPortal_old; -export const createComponentSelector: typeof createComponentSelector_new = enableNewReconciler - ? createComponentSelector_new - : createComponentSelector_old; - -export const createHasPseudoClassSelector: typeof createHasPseudoClassSelector_new = enableNewReconciler - ? createHasPseudoClassSelector_new - : createHasPseudoClassSelector_old; -export const createRoleSelector: typeof createRoleSelector_new = enableNewReconciler - ? createRoleSelector_new - : createRoleSelector_old; -export const createTextSelector: typeof createTextSelector_new = enableNewReconciler - ? createTextSelector_new - : createTextSelector_old; -export const createTestNameSelector: typeof createTestNameSelector_new = enableNewReconciler - ? createTestNameSelector_new - : createTestNameSelector_old; -export const getFindAllNodesFailureDescription: typeof getFindAllNodesFailureDescription_new = enableNewReconciler - ? getFindAllNodesFailureDescription_new - : getFindAllNodesFailureDescription_old; -export const findAllNodes: typeof findAllNodes_new = enableNewReconciler - ? findAllNodes_new - : findAllNodes_old; -export const findBoundingRects: typeof findBoundingRects_new = enableNewReconciler - ? findBoundingRects_new - : findBoundingRects_old; -export const focusWithin: typeof focusWithin_new = enableNewReconciler - ? focusWithin_new - : focusWithin_old; -export const observeVisibleRects: typeof observeVisibleRects_new = enableNewReconciler - ? observeVisibleRects_new - : observeVisibleRects_old; -export const registerMutableSourceForHydration: typeof registerMutableSourceForHydration_new = enableNewReconciler - ? registerMutableSourceForHydration_new - : registerMutableSourceForHydration_old; -/* $FlowFixMe[incompatible-type] opaque types EventPriority from new and old - * are incompatible. */ -export const runWithPriority: typeof runWithPriority_new = enableNewReconciler - ? runWithPriority_new - : runWithPriority_old; diff --git a/packages/react-reconciler/src/ReactFiberReconciler.new.js b/packages/react-reconciler/src/ReactFiberReconciler.new.js deleted file mode 100644 index 99f96c2eaa83e..0000000000000 --- a/packages/react-reconciler/src/ReactFiberReconciler.new.js +++ /dev/null @@ -1,845 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type { - Fiber, - FiberRoot, - SuspenseHydrationCallbacks, - TransitionTracingCallbacks, -} from './ReactInternalTypes'; -import type {RootTag} from './ReactRootTags'; -import type { - Instance, - TextInstance, - Container, - PublicInstance, - RendererInspectionConfig, -} from './ReactFiberHostConfig'; -import type {ReactNodeList} from 'shared/ReactTypes'; -import type {Lane} from './ReactFiberLane.new'; -import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; - -import { - findCurrentHostFiber, - findCurrentHostFiberWithNoPortals, -} from './ReactFiberTreeReflection'; -import {get as getInstance} from 'shared/ReactInstanceMap'; -import { - HostComponent, - HostSingleton, - ClassComponent, - HostRoot, - SuspenseComponent, -} from './ReactWorkTags'; -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import isArray from 'shared/isArray'; -import {enableSchedulingProfiler} from 'shared/ReactFeatureFlags'; -import ReactSharedInternals from 'shared/ReactSharedInternals'; -import {getPublicInstance} from './ReactFiberHostConfig'; -import { - findCurrentUnmaskedContext, - processChildContext, - emptyContextObject, - isContextProvider as isLegacyContextProvider, -} from './ReactFiberContext.new'; -import {createFiberRoot} from './ReactFiberRoot.new'; -import {isRootDehydrated} from './ReactFiberShellHydration'; -import { - injectInternals, - markRenderScheduled, - onScheduleRoot, -} from './ReactFiberDevToolsHook.new'; -import { - requestEventTime, - requestUpdateLane, - scheduleUpdateOnFiber, - scheduleInitialHydrationOnRoot, - flushRoot, - batchedUpdates, - flushSync, - isAlreadyRendering, - flushControlled, - deferredUpdates, - discreteUpdates, - flushPassiveEffects, -} from './ReactFiberWorkLoop.new'; -import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates.new'; -import { - createUpdate, - enqueueUpdate, - entangleTransitions, -} from './ReactFiberClassUpdateQueue.new'; -import { - isRendering as ReactCurrentFiberIsRendering, - current as ReactCurrentFiberCurrent, - resetCurrentFiber as resetCurrentDebugFiberInDEV, - setCurrentFiber as setCurrentDebugFiberInDEV, -} from './ReactCurrentFiber'; -import {StrictLegacyMode} from './ReactTypeOfMode'; -import { - SyncLane, - SelectiveHydrationLane, - NoTimestamp, - getHighestPriorityPendingLanes, - higherPriorityLane, -} from './ReactFiberLane.new'; -import { - getCurrentUpdatePriority, - runWithPriority, -} from './ReactEventPriorities.new'; -import { - scheduleRefresh, - scheduleRoot, - setRefreshHandler, - findHostInstancesForRefresh, -} from './ReactFiberHotReloading.new'; -import ReactVersion from 'shared/ReactVersion'; -export {registerMutableSourceForHydration} from './ReactMutableSource.new'; -export {createPortal} from './ReactPortal'; -export { - createComponentSelector, - createHasPseudoClassSelector, - createRoleSelector, - createTestNameSelector, - createTextSelector, - getFindAllNodesFailureDescription, - findAllNodes, - findBoundingRects, - focusWithin, - observeVisibleRects, -} from './ReactTestSelectors'; - -type OpaqueRoot = FiberRoot; - -// 0 is PROD, 1 is DEV. -// Might add PROFILE later. -type BundleType = 0 | 1; - -type DevToolsConfig = { - bundleType: BundleType, - version: string, - rendererPackageName: string, - // Note: this actually *does* depend on Fiber internal fields. - // Used by "inspect clicked DOM element" in React DevTools. - findFiberByHostInstance?: (instance: Instance | TextInstance) => Fiber | null, - rendererConfig?: RendererInspectionConfig, -}; - -let didWarnAboutNestedUpdates; -let didWarnAboutFindNodeInStrictMode; - -if (__DEV__) { - didWarnAboutNestedUpdates = false; - didWarnAboutFindNodeInStrictMode = {}; -} - -function getContextForSubtree( - parentComponent: ?React$Component, -): Object { - if (!parentComponent) { - return emptyContextObject; - } - - const fiber = getInstance(parentComponent); - const parentContext = findCurrentUnmaskedContext(fiber); - - if (fiber.tag === ClassComponent) { - const Component = fiber.type; - if (isLegacyContextProvider(Component)) { - return processChildContext(fiber, Component, parentContext); - } - } - - return parentContext; -} - -function findHostInstance(component: Object): PublicInstance | null { - const fiber = getInstance(component); - if (fiber === undefined) { - if (typeof component.render === 'function') { - throw new Error('Unable to find node on an unmounted component.'); - } else { - const keys = Object.keys(component).join(','); - throw new Error( - `Argument appears to not be a ReactComponent. Keys: ${keys}`, - ); - } - } - const hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; -} - -function findHostInstanceWithWarning( - component: Object, - methodName: string, -): PublicInstance | null { - if (__DEV__) { - const fiber = getInstance(component); - if (fiber === undefined) { - if (typeof component.render === 'function') { - throw new Error('Unable to find node on an unmounted component.'); - } else { - const keys = Object.keys(component).join(','); - throw new Error( - `Argument appears to not be a ReactComponent. Keys: ${keys}`, - ); - } - } - const hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - if (hostFiber.mode & StrictLegacyMode) { - const componentName = getComponentNameFromFiber(fiber) || 'Component'; - if (!didWarnAboutFindNodeInStrictMode[componentName]) { - didWarnAboutFindNodeInStrictMode[componentName] = true; - - const previousFiber = ReactCurrentFiberCurrent; - try { - setCurrentDebugFiberInDEV(hostFiber); - if (fiber.mode & StrictLegacyMode) { - console.error( - '%s is deprecated in StrictMode. ' + - '%s was passed an instance of %s which is inside StrictMode. ' + - 'Instead, add a ref directly to the element you want to reference. ' + - 'Learn more about using refs safely here: ' + - 'https://reactjs.org/link/strict-mode-find-node', - methodName, - methodName, - componentName, - ); - } else { - console.error( - '%s is deprecated in StrictMode. ' + - '%s was passed an instance of %s which renders StrictMode children. ' + - 'Instead, add a ref directly to the element you want to reference. ' + - 'Learn more about using refs safely here: ' + - 'https://reactjs.org/link/strict-mode-find-node', - methodName, - methodName, - componentName, - ); - } - } finally { - // Ideally this should reset to previous but this shouldn't be called in - // render and there's another warning for that anyway. - if (previousFiber) { - setCurrentDebugFiberInDEV(previousFiber); - } else { - resetCurrentDebugFiberInDEV(); - } - } - } - } - return hostFiber.stateNode; - } - return findHostInstance(component); -} - -export function createContainer( - containerInfo: Container, - tag: RootTag, - hydrationCallbacks: null | SuspenseHydrationCallbacks, - isStrictMode: boolean, - concurrentUpdatesByDefaultOverride: null | boolean, - identifierPrefix: string, - onRecoverableError: (error: mixed) => void, - transitionCallbacks: null | TransitionTracingCallbacks, -): OpaqueRoot { - const hydrate = false; - const initialChildren = null; - return createFiberRoot( - containerInfo, - tag, - hydrate, - initialChildren, - hydrationCallbacks, - isStrictMode, - concurrentUpdatesByDefaultOverride, - identifierPrefix, - onRecoverableError, - transitionCallbacks, - ); -} - -export function createHydrationContainer( - initialChildren: ReactNodeList, - // TODO: Remove `callback` when we delete legacy mode. - callback: ?Function, - containerInfo: Container, - tag: RootTag, - hydrationCallbacks: null | SuspenseHydrationCallbacks, - isStrictMode: boolean, - concurrentUpdatesByDefaultOverride: null | boolean, - identifierPrefix: string, - onRecoverableError: (error: mixed) => void, - transitionCallbacks: null | TransitionTracingCallbacks, -): OpaqueRoot { - const hydrate = true; - const root = createFiberRoot( - containerInfo, - tag, - hydrate, - initialChildren, - hydrationCallbacks, - isStrictMode, - concurrentUpdatesByDefaultOverride, - identifierPrefix, - onRecoverableError, - transitionCallbacks, - ); - - // TODO: Move this to FiberRoot constructor - root.context = getContextForSubtree(null); - - // Schedule the initial render. In a hydration root, this is different from - // a regular update because the initial render must match was was rendered - // on the server. - // NOTE: This update intentionally doesn't have a payload. We're only using - // the update to schedule work on the root fiber (and, for legacy roots, to - // enqueue the callback if one is provided). - const current = root.current; - const eventTime = requestEventTime(); - const lane = requestUpdateLane(current); - const update = createUpdate(eventTime, lane); - update.callback = - callback !== undefined && callback !== null ? callback : null; - enqueueUpdate(current, update, lane); - scheduleInitialHydrationOnRoot(root, lane, eventTime); - - return root; -} - -export function updateContainer( - element: ReactNodeList, - container: OpaqueRoot, - parentComponent: ?React$Component, - callback: ?Function, -): Lane { - if (__DEV__) { - onScheduleRoot(container, element); - } - const current = container.current; - const eventTime = requestEventTime(); - const lane = requestUpdateLane(current); - - if (enableSchedulingProfiler) { - markRenderScheduled(lane); - } - - const context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - if (__DEV__) { - if ( - ReactCurrentFiberIsRendering && - ReactCurrentFiberCurrent !== null && - !didWarnAboutNestedUpdates - ) { - didWarnAboutNestedUpdates = true; - console.error( - 'Render methods should be a pure function of props and state; ' + - 'triggering nested component updates from render is not allowed. ' + - 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + - 'Check the render method of %s.', - getComponentNameFromFiber(ReactCurrentFiberCurrent) || 'Unknown', - ); - } - } - - const update = createUpdate(eventTime, lane); - // Caution: React DevTools currently depends on this property - // being called "element". - update.payload = {element}; - - callback = callback === undefined ? null : callback; - if (callback !== null) { - if (__DEV__) { - if (typeof callback !== 'function') { - console.error( - 'render(...): Expected the last optional `callback` argument to be a ' + - 'function. Instead received: %s.', - callback, - ); - } - } - update.callback = callback; - } - - const root = enqueueUpdate(current, update, lane); - if (root !== null) { - scheduleUpdateOnFiber(root, current, lane, eventTime); - entangleTransitions(root, current, lane); - } - - return lane; -} - -export { - batchedUpdates, - deferredUpdates, - discreteUpdates, - flushControlled, - flushSync, - isAlreadyRendering, - flushPassiveEffects, -}; - -export function getPublicRootInstance( - container: OpaqueRoot, -): React$Component | PublicInstance | null { - const containerFiber = container.current; - if (!containerFiber.child) { - return null; - } - switch (containerFiber.child.tag) { - case HostSingleton: - case HostComponent: - return getPublicInstance(containerFiber.child.stateNode); - default: - return containerFiber.child.stateNode; - } -} - -export function attemptSynchronousHydration(fiber: Fiber): void { - switch (fiber.tag) { - case HostRoot: { - const root: FiberRoot = fiber.stateNode; - if (isRootDehydrated(root)) { - // Flush the first scheduled "update". - const lanes = getHighestPriorityPendingLanes(root); - flushRoot(root, lanes); - } - break; - } - case SuspenseComponent: { - flushSync(() => { - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - const eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime); - } - }); - // If we're still blocked after this, we need to increase - // the priority of any promises resolving within this - // boundary so that they next attempt also has higher pri. - const retryLane = SyncLane; - markRetryLaneIfNotHydrated(fiber, retryLane); - break; - } - } -} - -function markRetryLaneImpl(fiber: Fiber, retryLane: Lane) { - const suspenseState: null | SuspenseState = fiber.memoizedState; - if (suspenseState !== null && suspenseState.dehydrated !== null) { - suspenseState.retryLane = higherPriorityLane( - suspenseState.retryLane, - retryLane, - ); - } -} - -// Increases the priority of thenables when they resolve within this boundary. -function markRetryLaneIfNotHydrated(fiber: Fiber, retryLane: Lane) { - markRetryLaneImpl(fiber, retryLane); - const alternate = fiber.alternate; - if (alternate) { - markRetryLaneImpl(alternate, retryLane); - } -} - -export function attemptDiscreteHydration(fiber: Fiber): void { - if (fiber.tag !== SuspenseComponent) { - // We ignore HostRoots here because we can't increase - // their priority and they should not suspend on I/O, - // since you have to wrap anything that might suspend in - // Suspense. - return; - } - const lane = SyncLane; - const root = enqueueConcurrentRenderForLane(fiber, lane); - if (root !== null) { - const eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - } - markRetryLaneIfNotHydrated(fiber, lane); -} - -export function attemptContinuousHydration(fiber: Fiber): void { - if (fiber.tag !== SuspenseComponent) { - // We ignore HostRoots here because we can't increase - // their priority and they should not suspend on I/O, - // since you have to wrap anything that might suspend in - // Suspense. - return; - } - const lane = SelectiveHydrationLane; - const root = enqueueConcurrentRenderForLane(fiber, lane); - if (root !== null) { - const eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - } - markRetryLaneIfNotHydrated(fiber, lane); -} - -export function attemptHydrationAtCurrentPriority(fiber: Fiber): void { - if (fiber.tag !== SuspenseComponent) { - // We ignore HostRoots here because we can't increase - // their priority other than synchronously flush it. - return; - } - const lane = requestUpdateLane(fiber); - const root = enqueueConcurrentRenderForLane(fiber, lane); - if (root !== null) { - const eventTime = requestEventTime(); - scheduleUpdateOnFiber(root, fiber, lane, eventTime); - } - markRetryLaneIfNotHydrated(fiber, lane); -} - -export {getCurrentUpdatePriority, runWithPriority}; - -export {findHostInstance}; - -export {findHostInstanceWithWarning}; - -export function findHostInstanceWithNoPortals( - fiber: Fiber, -): PublicInstance | null { - const hostFiber = findCurrentHostFiberWithNoPortals(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; -} - -let shouldErrorImpl: Fiber => ?boolean = fiber => null; - -export function shouldError(fiber: Fiber): ?boolean { - return shouldErrorImpl(fiber); -} - -let shouldSuspendImpl = fiber => false; - -export function shouldSuspend(fiber: Fiber): boolean { - return shouldSuspendImpl(fiber); -} - -let overrideHookState = null; -let overrideHookStateDeletePath = null; -let overrideHookStateRenamePath = null; -let overrideProps = null; -let overridePropsDeletePath = null; -let overridePropsRenamePath = null; -let scheduleUpdate = null; -let setErrorHandler = null; -let setSuspenseHandler = null; - -if (__DEV__) { - const copyWithDeleteImpl = ( - obj: Object | Array, - path: Array, - index: number, - ) => { - const key = path[index]; - const updated = isArray(obj) ? obj.slice() : {...obj}; - if (index + 1 === path.length) { - if (isArray(updated)) { - updated.splice(((key: any): number), 1); - } else { - delete updated[key]; - } - return updated; - } - // $FlowFixMe number or string is fine here - updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); - return updated; - }; - - const copyWithDelete = ( - obj: Object | Array, - path: Array, - ): Object | Array => { - return copyWithDeleteImpl(obj, path, 0); - }; - - const copyWithRenameImpl = ( - obj: Object | Array, - oldPath: Array, - newPath: Array, - index: number, - ) => { - const oldKey = oldPath[index]; - const updated = isArray(obj) ? obj.slice() : {...obj}; - if (index + 1 === oldPath.length) { - const newKey = newPath[index]; - // $FlowFixMe number or string is fine here - updated[newKey] = updated[oldKey]; - if (isArray(updated)) { - updated.splice(((oldKey: any): number), 1); - } else { - delete updated[oldKey]; - } - } else { - // $FlowFixMe number or string is fine here - updated[oldKey] = copyWithRenameImpl( - // $FlowFixMe number or string is fine here - obj[oldKey], - oldPath, - newPath, - index + 1, - ); - } - return updated; - }; - - const copyWithRename = ( - obj: Object | Array, - oldPath: Array, - newPath: Array, - ): Object | Array => { - if (oldPath.length !== newPath.length) { - console.warn('copyWithRename() expects paths of the same length'); - return; - } else { - for (let i = 0; i < newPath.length - 1; i++) { - if (oldPath[i] !== newPath[i]) { - console.warn( - 'copyWithRename() expects paths to be the same except for the deepest key', - ); - return; - } - } - } - return copyWithRenameImpl(obj, oldPath, newPath, 0); - }; - - const copyWithSetImpl = ( - obj: Object | Array, - path: Array, - index: number, - value: any, - ) => { - if (index >= path.length) { - return value; - } - const key = path[index]; - const updated = isArray(obj) ? obj.slice() : {...obj}; - // $FlowFixMe number or string is fine here - updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); - return updated; - }; - - const copyWithSet = ( - obj: Object | Array, - path: Array, - value: any, - ): Object | Array => { - return copyWithSetImpl(obj, path, 0, value); - }; - - const findHook = (fiber: Fiber, id: number) => { - // For now, the "id" of stateful hooks is just the stateful hook index. - // This may change in the future with e.g. nested hooks. - let currentHook = fiber.memoizedState; - while (currentHook !== null && id > 0) { - currentHook = currentHook.next; - id--; - } - return currentHook; - }; - - // Support DevTools editable values for useState and useReducer. - overrideHookState = ( - fiber: Fiber, - id: number, - path: Array, - value: any, - ) => { - const hook = findHook(fiber, id); - if (hook !== null) { - const newState = copyWithSet(hook.memoizedState, path, value); - hook.memoizedState = newState; - hook.baseState = newState; - - // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - fiber.memoizedProps = {...fiber.memoizedProps}; - - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - }; - overrideHookStateDeletePath = ( - fiber: Fiber, - id: number, - path: Array, - ) => { - const hook = findHook(fiber, id); - if (hook !== null) { - const newState = copyWithDelete(hook.memoizedState, path); - hook.memoizedState = newState; - hook.baseState = newState; - - // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - fiber.memoizedProps = {...fiber.memoizedProps}; - - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - }; - overrideHookStateRenamePath = ( - fiber: Fiber, - id: number, - oldPath: Array, - newPath: Array, - ) => { - const hook = findHook(fiber, id); - if (hook !== null) { - const newState = copyWithRename(hook.memoizedState, oldPath, newPath); - hook.memoizedState = newState; - hook.baseState = newState; - - // We aren't actually adding an update to the queue, - // because there is no update we can add for useReducer hooks that won't trigger an error. - // (There's no appropriate action type for DevTools overrides.) - // As a result though, React will see the scheduled update as a noop and bailout. - // Shallow cloning props works as a workaround for now to bypass the bailout check. - fiber.memoizedProps = {...fiber.memoizedProps}; - - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - } - }; - - // Support DevTools props for function components, forwardRef, memo, host components, etc. - overrideProps = (fiber: Fiber, path: Array, value: any) => { - fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - overridePropsDeletePath = (fiber: Fiber, path: Array) => { - fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - overridePropsRenamePath = ( - fiber: Fiber, - oldPath: Array, - newPath: Array, - ) => { - fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); - if (fiber.alternate) { - fiber.alternate.pendingProps = fiber.pendingProps; - } - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - - scheduleUpdate = (fiber: Fiber) => { - const root = enqueueConcurrentRenderForLane(fiber, SyncLane); - if (root !== null) { - scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); - } - }; - - setErrorHandler = (newShouldErrorImpl: Fiber => ?boolean) => { - shouldErrorImpl = newShouldErrorImpl; - }; - - setSuspenseHandler = (newShouldSuspendImpl: Fiber => boolean) => { - shouldSuspendImpl = newShouldSuspendImpl; - }; -} - -function findHostInstanceByFiber(fiber: Fiber): Instance | TextInstance | null { - const hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; -} - -function emptyFindFiberByHostInstance( - instance: Instance | TextInstance, -): Fiber | null { - return null; -} - -function getCurrentFiberForDevTools() { - return ReactCurrentFiberCurrent; -} - -export function injectIntoDevTools(devToolsConfig: DevToolsConfig): boolean { - const {findFiberByHostInstance} = devToolsConfig; - const {ReactCurrentDispatcher} = ReactSharedInternals; - - return injectInternals({ - bundleType: devToolsConfig.bundleType, - version: devToolsConfig.version, - rendererPackageName: devToolsConfig.rendererPackageName, - rendererConfig: devToolsConfig.rendererConfig, - overrideHookState, - overrideHookStateDeletePath, - overrideHookStateRenamePath, - overrideProps, - overridePropsDeletePath, - overridePropsRenamePath, - setErrorHandler, - setSuspenseHandler, - scheduleUpdate, - currentDispatcherRef: ReactCurrentDispatcher, - findHostInstanceByFiber, - findFiberByHostInstance: - findFiberByHostInstance || emptyFindFiberByHostInstance, - // React Refresh - findHostInstancesForRefresh: __DEV__ ? findHostInstancesForRefresh : null, - scheduleRefresh: __DEV__ ? scheduleRefresh : null, - scheduleRoot: __DEV__ ? scheduleRoot : null, - setRefreshHandler: __DEV__ ? setRefreshHandler : null, - // Enables DevTools to append owner stacks to error messages in DEV mode. - getCurrentFiber: __DEV__ ? getCurrentFiberForDevTools : null, - // Enables DevTools to detect reconciler version rather than renderer version - // which may not match for third party renderers. - reconcilerVersion: ReactVersion, - }); -} diff --git a/packages/react-reconciler/src/ReactFiberRoot.new.js b/packages/react-reconciler/src/ReactFiberRoot.new.js deleted file mode 100644 index c613fa5dd31bf..0000000000000 --- a/packages/react-reconciler/src/ReactFiberRoot.new.js +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {ReactNodeList} from 'shared/ReactTypes'; -import type { - FiberRoot, - SuspenseHydrationCallbacks, - TransitionTracingCallbacks, -} from './ReactInternalTypes'; -import type {RootTag} from './ReactRootTags'; -import type {Cache} from './ReactFiberCacheComponent.new'; -import type {Container} from './ReactFiberHostConfig'; - -import {noTimeout, supportsHydration} from './ReactFiberHostConfig'; -import {createHostRootFiber} from './ReactFiber.new'; -import { - NoLane, - NoLanes, - NoTimestamp, - TotalLanes, - createLaneMap, -} from './ReactFiberLane.new'; -import { - enableSuspenseCallback, - enableCache, - enableProfilerCommitHooks, - enableProfilerTimer, - enableUpdaterTracking, - enableTransitionTracing, -} from 'shared/ReactFeatureFlags'; -import {initializeUpdateQueue} from './ReactFiberClassUpdateQueue.new'; -import {LegacyRoot, ConcurrentRoot} from './ReactRootTags'; -import {createCache, retainCache} from './ReactFiberCacheComponent.new'; - -export type RootState = { - element: any, - isDehydrated: boolean, - cache: Cache, -}; - -function FiberRootNode( - containerInfo, - tag, - hydrate, - identifierPrefix, - onRecoverableError, -) { - this.tag = tag; - this.containerInfo = containerInfo; - this.pendingChildren = null; - this.current = null; - this.pingCache = null; - this.finishedWork = null; - this.timeoutHandle = noTimeout; - this.context = null; - this.pendingContext = null; - this.callbackNode = null; - this.callbackPriority = NoLane; - this.eventTimes = createLaneMap(NoLanes); - this.expirationTimes = createLaneMap(NoTimestamp); - - this.pendingLanes = NoLanes; - this.suspendedLanes = NoLanes; - this.pingedLanes = NoLanes; - this.expiredLanes = NoLanes; - this.mutableReadLanes = NoLanes; - this.finishedLanes = NoLanes; - this.errorRecoveryDisabledLanes = NoLanes; - - this.entangledLanes = NoLanes; - this.entanglements = createLaneMap(NoLanes); - - this.hiddenUpdates = createLaneMap(null); - - this.identifierPrefix = identifierPrefix; - this.onRecoverableError = onRecoverableError; - - if (enableCache) { - this.pooledCache = null; - this.pooledCacheLanes = NoLanes; - } - - if (supportsHydration) { - this.mutableSourceEagerHydrationData = null; - } - - if (enableSuspenseCallback) { - this.hydrationCallbacks = null; - } - - this.incompleteTransitions = new Map(); - if (enableTransitionTracing) { - this.transitionCallbacks = null; - const transitionLanesMap = (this.transitionLanes = []); - for (let i = 0; i < TotalLanes; i++) { - transitionLanesMap.push(null); - } - } - - if (enableProfilerTimer && enableProfilerCommitHooks) { - this.effectDuration = 0; - this.passiveEffectDuration = 0; - } - - if (enableUpdaterTracking) { - this.memoizedUpdaters = new Set(); - const pendingUpdatersLaneMap = (this.pendingUpdatersLaneMap = []); - for (let i = 0; i < TotalLanes; i++) { - pendingUpdatersLaneMap.push(new Set()); - } - } - - if (__DEV__) { - switch (tag) { - case ConcurrentRoot: - this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; - break; - case LegacyRoot: - this._debugRootType = hydrate ? 'hydrate()' : 'render()'; - break; - } - } -} - -export function createFiberRoot( - containerInfo: Container, - tag: RootTag, - hydrate: boolean, - initialChildren: ReactNodeList, - hydrationCallbacks: null | SuspenseHydrationCallbacks, - isStrictMode: boolean, - concurrentUpdatesByDefaultOverride: null | boolean, - // TODO: We have several of these arguments that are conceptually part of the - // host config, but because they are passed in at runtime, we have to thread - // them through the root constructor. Perhaps we should put them all into a - // single type, like a DynamicHostConfig that is defined by the renderer. - identifierPrefix: string, - onRecoverableError: null | ((error: mixed) => void), - transitionCallbacks: null | TransitionTracingCallbacks, -): FiberRoot { - // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions - const root: FiberRoot = (new FiberRootNode( - containerInfo, - tag, - hydrate, - identifierPrefix, - onRecoverableError, - ): any); - if (enableSuspenseCallback) { - root.hydrationCallbacks = hydrationCallbacks; - } - - if (enableTransitionTracing) { - root.transitionCallbacks = transitionCallbacks; - } - - // Cyclic construction. This cheats the type system right now because - // stateNode is any. - const uninitializedFiber = createHostRootFiber( - tag, - isStrictMode, - concurrentUpdatesByDefaultOverride, - ); - root.current = uninitializedFiber; - uninitializedFiber.stateNode = root; - - if (enableCache) { - const initialCache = createCache(); - retainCache(initialCache); - - // The pooledCache is a fresh cache instance that is used temporarily - // for newly mounted boundaries during a render. In general, the - // pooledCache is always cleared from the root at the end of a render: - // it is either released when render commits, or moved to an Offscreen - // component if rendering suspends. Because the lifetime of the pooled - // cache is distinct from the main memoizedState.cache, it must be - // retained separately. - root.pooledCache = initialCache; - retainCache(initialCache); - const initialState: RootState = { - element: initialChildren, - isDehydrated: hydrate, - cache: initialCache, - }; - uninitializedFiber.memoizedState = initialState; - } else { - const initialState: RootState = { - element: initialChildren, - isDehydrated: hydrate, - cache: (null: any), // not enabled yet - }; - uninitializedFiber.memoizedState = initialState; - } - - initializeUpdateQueue(uninitializedFiber); - - return root; -} diff --git a/packages/react-reconciler/src/ReactFiberScope.new.js b/packages/react-reconciler/src/ReactFiberScope.new.js deleted file mode 100644 index 3ce4ac784ce5b..0000000000000 --- a/packages/react-reconciler/src/ReactFiberScope.new.js +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; -import type { - ReactScopeInstance, - ReactContext, - ReactScopeQuery, -} from 'shared/ReactTypes'; - -import { - getPublicInstance, - getInstanceFromNode, - getInstanceFromScope, -} from './ReactFiberHostConfig'; -import {isFiberSuspenseAndTimedOut} from './ReactFiberTreeReflection'; - -import {HostComponent, ScopeComponent, ContextProvider} from './ReactWorkTags'; -import {enableScopeAPI} from 'shared/ReactFeatureFlags'; - -function getSuspenseFallbackChild(fiber: Fiber): Fiber | null { - return ((((fiber.child: any): Fiber).sibling: any): Fiber).child; -} - -const emptyObject = {}; - -function collectScopedNodes( - node: Fiber, - fn: ReactScopeQuery, - scopedNodes: Array, -): void { - if (enableScopeAPI) { - if (node.tag === HostComponent) { - const {type, memoizedProps, stateNode} = node; - const instance = getPublicInstance(stateNode); - if ( - instance !== null && - fn(type, memoizedProps || emptyObject, instance) === true - ) { - scopedNodes.push(instance); - } - } - let child = node.child; - - if (isFiberSuspenseAndTimedOut(node)) { - child = getSuspenseFallbackChild(node); - } - if (child !== null) { - collectScopedNodesFromChildren(child, fn, scopedNodes); - } - } -} - -function collectFirstScopedNode( - node: Fiber, - fn: ReactScopeQuery, -): null | Object { - if (enableScopeAPI) { - if (node.tag === HostComponent) { - const {type, memoizedProps, stateNode} = node; - const instance = getPublicInstance(stateNode); - if (instance !== null && fn(type, memoizedProps, instance) === true) { - return instance; - } - } - let child = node.child; - - if (isFiberSuspenseAndTimedOut(node)) { - child = getSuspenseFallbackChild(node); - } - if (child !== null) { - return collectFirstScopedNodeFromChildren(child, fn); - } - } - return null; -} - -function collectScopedNodesFromChildren( - startingChild: Fiber, - fn: ReactScopeQuery, - scopedNodes: Array, -): void { - let child: null | Fiber = startingChild; - while (child !== null) { - collectScopedNodes(child, fn, scopedNodes); - child = child.sibling; - } -} - -function collectFirstScopedNodeFromChildren( - startingChild: Fiber, - fn: ReactScopeQuery, -): Object | null { - let child: null | Fiber = startingChild; - while (child !== null) { - const scopedNode = collectFirstScopedNode(child, fn); - if (scopedNode !== null) { - return scopedNode; - } - child = child.sibling; - } - return null; -} - -function collectNearestContextValues( - node: Fiber, - context: ReactContext, - childContextValues: Array, -): void { - if (node.tag === ContextProvider && node.type._context === context) { - const contextValue = node.memoizedProps.value; - childContextValues.push(contextValue); - } else { - let child = node.child; - - if (isFiberSuspenseAndTimedOut(node)) { - child = getSuspenseFallbackChild(node); - } - if (child !== null) { - collectNearestChildContextValues(child, context, childContextValues); - } - } -} - -function collectNearestChildContextValues( - startingChild: Fiber | null, - context: ReactContext, - childContextValues: Array, -): void { - let child = startingChild; - while (child !== null) { - collectNearestContextValues(child, context, childContextValues); - child = child.sibling; - } -} - -function DO_NOT_USE_queryAllNodes(fn: ReactScopeQuery): null | Array { - const currentFiber = getInstanceFromScope(this); - if (currentFiber === null) { - return null; - } - const child = currentFiber.child; - const scopedNodes = []; - if (child !== null) { - collectScopedNodesFromChildren(child, fn, scopedNodes); - } - return scopedNodes.length === 0 ? null : scopedNodes; -} - -function DO_NOT_USE_queryFirstNode(fn: ReactScopeQuery): null | Object { - const currentFiber = getInstanceFromScope(this); - if (currentFiber === null) { - return null; - } - const child = currentFiber.child; - if (child !== null) { - return collectFirstScopedNodeFromChildren(child, fn); - } - return null; -} - -function containsNode(node: Object): boolean { - let fiber = getInstanceFromNode(node); - while (fiber !== null) { - if (fiber.tag === ScopeComponent && fiber.stateNode === this) { - return true; - } - fiber = fiber.return; - } - return false; -} - -function getChildContextValues(context: ReactContext): Array { - const currentFiber = getInstanceFromScope(this); - if (currentFiber === null) { - return []; - } - const child = currentFiber.child; - const childContextValues = []; - if (child !== null) { - collectNearestChildContextValues(child, context, childContextValues); - } - return childContextValues; -} - -export function createScopeInstance(): ReactScopeInstance { - return { - DO_NOT_USE_queryAllNodes, - DO_NOT_USE_queryFirstNode, - containsNode, - getChildContextValues, - }; -} diff --git a/packages/react-reconciler/src/ReactFiberShellHydration.js b/packages/react-reconciler/src/ReactFiberShellHydration.js index 7488740cb89d0..8afe36cc2637e 100644 --- a/packages/react-reconciler/src/ReactFiberShellHydration.js +++ b/packages/react-reconciler/src/ReactFiberShellHydration.js @@ -8,7 +8,7 @@ */ import type {FiberRoot} from './ReactInternalTypes'; -import type {RootState} from './ReactFiberRoot.new'; +import type {RootState} from './ReactFiberRoot.old'; // This is imported by the event replaying implementation in React DOM. It's // in a separate file to break a circular dependency between the renderer and diff --git a/packages/react-reconciler/src/ReactFiberStack.new.js b/packages/react-reconciler/src/ReactFiberStack.new.js deleted file mode 100644 index 985fb421ebd0f..0000000000000 --- a/packages/react-reconciler/src/ReactFiberStack.new.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; - -export type StackCursor = {current: T}; - -const valueStack: Array = []; - -let fiberStack: Array; - -if (__DEV__) { - fiberStack = []; -} - -let index = -1; - -function createCursor(defaultValue: T): StackCursor { - return { - current: defaultValue, - }; -} - -function isEmpty(): boolean { - return index === -1; -} - -function pop(cursor: StackCursor, fiber: Fiber): void { - if (index < 0) { - if (__DEV__) { - console.error('Unexpected pop.'); - } - return; - } - - if (__DEV__) { - if (fiber !== fiberStack[index]) { - console.error('Unexpected Fiber popped.'); - } - } - - cursor.current = valueStack[index]; - - valueStack[index] = null; - - if (__DEV__) { - fiberStack[index] = null; - } - - index--; -} - -function push(cursor: StackCursor, value: T, fiber: Fiber): void { - index++; - - valueStack[index] = cursor.current; - - if (__DEV__) { - fiberStack[index] = fiber; - } - - cursor.current = value; -} - -function checkThatStackIsEmpty() { - if (__DEV__) { - if (index !== -1) { - console.error( - 'Expected an empty stack. Something was not reset properly.', - ); - } - } -} - -function resetStackAfterFatalErrorInDev() { - if (__DEV__) { - index = -1; - valueStack.length = 0; - fiberStack.length = 0; - } -} - -export { - createCursor, - isEmpty, - pop, - push, - // DEV only: - checkThatStackIsEmpty, - resetStackAfterFatalErrorInDev, -}; diff --git a/packages/react-reconciler/src/ReactFiberSuspenseComponent.new.js b/packages/react-reconciler/src/ReactFiberSuspenseComponent.new.js deleted file mode 100644 index a672e8b0ef568..0000000000000 --- a/packages/react-reconciler/src/ReactFiberSuspenseComponent.new.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {ReactNodeList, Wakeable} from 'shared/ReactTypes'; -import type {Fiber} from './ReactInternalTypes'; -import type {SuspenseInstance} from './ReactFiberHostConfig'; -import type {Lane} from './ReactFiberLane.new'; -import type {TreeContext} from './ReactFiberTreeContext.new'; - -import {SuspenseComponent, SuspenseListComponent} from './ReactWorkTags'; -import {NoFlags, DidCapture} from './ReactFiberFlags'; -import { - isSuspenseInstancePending, - isSuspenseInstanceFallback, -} from './ReactFiberHostConfig'; - -export type SuspenseProps = { - children?: ReactNodeList, - fallback?: ReactNodeList, - - // TODO: Add "unstable_" prefix? - suspenseCallback?: (Set | null) => mixed, - - unstable_avoidThisFallback?: boolean, - unstable_expectedLoadTime?: number, - unstable_name?: string, -}; - -// A null SuspenseState represents an unsuspended normal Suspense boundary. -// A non-null SuspenseState means that it is blocked for one reason or another. -// - A non-null dehydrated field means it's blocked pending hydration. -// - A non-null dehydrated field can use isSuspenseInstancePending or -// isSuspenseInstanceFallback to query the reason for being dehydrated. -// - A null dehydrated field means it's blocked by something suspending and -// we're currently showing a fallback instead. -export type SuspenseState = { - // If this boundary is still dehydrated, we store the SuspenseInstance - // here to indicate that it is dehydrated (flag) and for quick access - // to check things like isSuspenseInstancePending. - dehydrated: null | SuspenseInstance, - treeContext: null | TreeContext, - // Represents the lane we should attempt to hydrate a dehydrated boundary at. - // OffscreenLane is the default for dehydrated boundaries. - // NoLane is the default for normal boundaries, which turns into "normal" pri. - retryLane: Lane, -}; - -export type SuspenseListTailMode = 'collapsed' | 'hidden' | void; - -export type SuspenseListRenderState = { - isBackwards: boolean, - // The currently rendering tail row. - rendering: null | Fiber, - // The absolute time when we started rendering the most recent tail row. - renderingStartTime: number, - // The last of the already rendered children. - last: null | Fiber, - // Remaining rows on the tail of the list. - tail: null | Fiber, - // Tail insertions setting. - tailMode: SuspenseListTailMode, -}; - -export function findFirstSuspended(row: Fiber): null | Fiber { - let node = row; - while (node !== null) { - if (node.tag === SuspenseComponent) { - const state: SuspenseState | null = node.memoizedState; - if (state !== null) { - const dehydrated: null | SuspenseInstance = state.dehydrated; - if ( - dehydrated === null || - isSuspenseInstancePending(dehydrated) || - isSuspenseInstanceFallback(dehydrated) - ) { - return node; - } - } - } else if ( - node.tag === SuspenseListComponent && - // revealOrder undefined can't be trusted because it don't - // keep track of whether it suspended or not. - node.memoizedProps.revealOrder !== undefined - ) { - const didSuspend = (node.flags & DidCapture) !== NoFlags; - if (didSuspend) { - return node; - } - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === row) { - return null; - } - while (node.sibling === null) { - if (node.return === null || node.return === row) { - return null; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - return null; -} diff --git a/packages/react-reconciler/src/ReactFiberSuspenseContext.new.js b/packages/react-reconciler/src/ReactFiberSuspenseContext.new.js deleted file mode 100644 index 1bdd54ba83fb6..0000000000000 --- a/packages/react-reconciler/src/ReactFiberSuspenseContext.new.js +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; -import type {StackCursor} from './ReactFiberStack.new'; -import type { - SuspenseState, - SuspenseProps, -} from './ReactFiberSuspenseComponent.new'; - -import {enableSuspenseAvoidThisFallback} from 'shared/ReactFeatureFlags'; -import {createCursor, push, pop} from './ReactFiberStack.new'; -import {isCurrentTreeHidden} from './ReactFiberHiddenContext.new'; -import {SuspenseComponent, OffscreenComponent} from './ReactWorkTags'; - -// The Suspense handler is the boundary that should capture if something -// suspends, i.e. it's the nearest `catch` block on the stack. -const suspenseHandlerStackCursor: StackCursor = createCursor( - null, -); - -function shouldAvoidedBoundaryCapture( - workInProgress: Fiber, - handlerOnStack: Fiber, - props: any, -): boolean { - if (enableSuspenseAvoidThisFallback) { - // If the parent is already showing content, and we're not inside a hidden - // tree, then we should show the avoided fallback. - if (handlerOnStack.alternate !== null && !isCurrentTreeHidden()) { - return true; - } - - // If the handler on the stack is also an avoided boundary, then we should - // favor this inner one. - if ( - handlerOnStack.tag === SuspenseComponent && - handlerOnStack.memoizedProps.unstable_avoidThisFallback === true - ) { - return true; - } - - // If this avoided boundary is dehydrated, then it should capture. - const suspenseState: SuspenseState | null = workInProgress.memoizedState; - if (suspenseState !== null && suspenseState.dehydrated !== null) { - return true; - } - } - - // If none of those cases apply, then we should avoid this fallback and show - // the outer one instead. - return false; -} - -export function isBadSuspenseFallback( - current: Fiber | null, - nextProps: SuspenseProps, -): boolean { - // Check if this is a "bad" fallback state or a good one. A bad fallback state - // is one that we only show as a last resort; if this is a transition, we'll - // block it from displaying, and wait for more data to arrive. - if (current !== null) { - const prevState: SuspenseState = current.memoizedState; - const isShowingFallback = prevState !== null; - if (!isShowingFallback && !isCurrentTreeHidden()) { - // It's bad to switch to a fallback if content is already visible - return true; - } - } - - if ( - enableSuspenseAvoidThisFallback && - nextProps.unstable_avoidThisFallback === true - ) { - // Experimental: Some fallbacks are always bad - return true; - } - - return false; -} - -export function pushPrimaryTreeSuspenseHandler(handler: Fiber): void { - const props = handler.pendingProps; - const handlerOnStack = suspenseHandlerStackCursor.current; - if ( - enableSuspenseAvoidThisFallback && - props.unstable_avoidThisFallback === true && - handlerOnStack !== null && - !shouldAvoidedBoundaryCapture(handler, handlerOnStack, props) - ) { - // This boundary should not capture if something suspends. Reuse the - // existing handler on the stack. - push(suspenseHandlerStackCursor, handlerOnStack, handler); - } else { - // Push this handler onto the stack. - push(suspenseHandlerStackCursor, handler, handler); - } -} - -export function pushFallbackTreeSuspenseHandler(fiber: Fiber): void { - // We're about to render the fallback. If something in the fallback suspends, - // it's akin to throwing inside of a `catch` block. This boundary should not - // capture. Reuse the existing handler on the stack. - reuseSuspenseHandlerOnStack(fiber); -} - -export function pushOffscreenSuspenseHandler(fiber: Fiber): void { - if (fiber.tag === OffscreenComponent) { - push(suspenseHandlerStackCursor, fiber, fiber); - } else { - // This is a LegacyHidden component. - reuseSuspenseHandlerOnStack(fiber); - } -} - -export function reuseSuspenseHandlerOnStack(fiber: Fiber) { - push(suspenseHandlerStackCursor, getSuspenseHandler(), fiber); -} - -export function getSuspenseHandler(): Fiber | null { - return suspenseHandlerStackCursor.current; -} - -export function popSuspenseHandler(fiber: Fiber): void { - pop(suspenseHandlerStackCursor, fiber); -} - -// SuspenseList context -// TODO: Move to a separate module? We may change the SuspenseList -// implementation to hide/show in the commit phase, anyway. -export opaque type SuspenseContext = number; -export opaque type SubtreeSuspenseContext: SuspenseContext = number; -export opaque type ShallowSuspenseContext: SuspenseContext = number; - -const DefaultSuspenseContext: SuspenseContext = 0b00; - -const SubtreeSuspenseContextMask: SuspenseContext = 0b01; - -// ForceSuspenseFallback can be used by SuspenseList to force newly added -// items into their fallback state during one of the render passes. -export const ForceSuspenseFallback: ShallowSuspenseContext = 0b10; - -export const suspenseStackCursor: StackCursor = createCursor( - DefaultSuspenseContext, -); - -export function hasSuspenseListContext( - parentContext: SuspenseContext, - flag: SuspenseContext, -): boolean { - return (parentContext & flag) !== 0; -} - -export function setDefaultShallowSuspenseListContext( - parentContext: SuspenseContext, -): SuspenseContext { - return parentContext & SubtreeSuspenseContextMask; -} - -export function setShallowSuspenseListContext( - parentContext: SuspenseContext, - shallowContext: ShallowSuspenseContext, -): SuspenseContext { - return (parentContext & SubtreeSuspenseContextMask) | shallowContext; -} - -export function pushSuspenseListContext( - fiber: Fiber, - newContext: SuspenseContext, -): void { - push(suspenseStackCursor, newContext, fiber); -} - -export function popSuspenseListContext(fiber: Fiber): void { - pop(suspenseStackCursor, fiber); -} diff --git a/packages/react-reconciler/src/ReactFiberSyncTaskQueue.new.js b/packages/react-reconciler/src/ReactFiberSyncTaskQueue.new.js deleted file mode 100644 index 12bb0c1c14861..0000000000000 --- a/packages/react-reconciler/src/ReactFiberSyncTaskQueue.new.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {SchedulerCallback} from './Scheduler'; - -import { - DiscreteEventPriority, - getCurrentUpdatePriority, - setCurrentUpdatePriority, -} from './ReactEventPriorities.new'; -import {ImmediatePriority, scheduleCallback} from './Scheduler'; - -let syncQueue: Array | null = null; -let includesLegacySyncCallbacks: boolean = false; -let isFlushingSyncQueue: boolean = false; - -export function scheduleSyncCallback(callback: SchedulerCallback) { - // Push this callback into an internal queue. We'll flush these either in - // the next tick, or earlier if something calls `flushSyncCallbackQueue`. - if (syncQueue === null) { - syncQueue = [callback]; - } else { - // Push onto existing queue. Don't need to schedule a callback because - // we already scheduled one when we created the queue. - syncQueue.push(callback); - } -} - -export function scheduleLegacySyncCallback(callback: SchedulerCallback) { - includesLegacySyncCallbacks = true; - scheduleSyncCallback(callback); -} - -export function flushSyncCallbacksOnlyInLegacyMode() { - // Only flushes the queue if there's a legacy sync callback scheduled. - // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So - // it might make more sense for the queue to be a list of roots instead of a - // list of generic callbacks. Then we can have two: one for legacy roots, one - // for concurrent roots. And this method would only flush the legacy ones. - if (includesLegacySyncCallbacks) { - flushSyncCallbacks(); - } -} - -export function flushSyncCallbacks(): null { - if (!isFlushingSyncQueue && syncQueue !== null) { - // Prevent re-entrance. - isFlushingSyncQueue = true; - let i = 0; - const previousUpdatePriority = getCurrentUpdatePriority(); - try { - const isSync = true; - const queue = syncQueue; - // TODO: Is this necessary anymore? The only user code that runs in this - // queue is in the render or commit phases. - setCurrentUpdatePriority(DiscreteEventPriority); - // $FlowFixMe[incompatible-use] found when upgrading Flow - for (; i < queue.length; i++) { - // $FlowFixMe[incompatible-use] found when upgrading Flow - let callback: SchedulerCallback = queue[i]; - do { - // $FlowFixMe[incompatible-type] we bail out when we get a null - callback = callback(isSync); - } while (callback !== null); - } - syncQueue = null; - includesLegacySyncCallbacks = false; - } catch (error) { - // If something throws, leave the remaining callbacks on the queue. - if (syncQueue !== null) { - syncQueue = syncQueue.slice(i + 1); - } - // Resume flushing in the next tick - scheduleCallback(ImmediatePriority, flushSyncCallbacks); - throw error; - } finally { - setCurrentUpdatePriority(previousUpdatePriority); - isFlushingSyncQueue = false; - } - } - return null; -} diff --git a/packages/react-reconciler/src/ReactFiberThenable.new.js b/packages/react-reconciler/src/ReactFiberThenable.new.js deleted file mode 100644 index 53d1c7176d588..0000000000000 --- a/packages/react-reconciler/src/ReactFiberThenable.new.js +++ /dev/null @@ -1,175 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type { - Thenable, - PendingThenable, - FulfilledThenable, - RejectedThenable, -} from 'shared/ReactTypes'; - -import ReactSharedInternals from 'shared/ReactSharedInternals'; -const {ReactCurrentActQueue} = ReactSharedInternals; - -export opaque type ThenableState = Array>; - -// An error that is thrown (e.g. by `use`) to trigger Suspense. If we -// detect this is caught by userspace, we'll log a warning in development. -export const SuspenseException: mixed = new Error( - "Suspense Exception: This is not a real error! It's an implementation " + - 'detail of `use` to interrupt the current render. You must either ' + - 'rethrow it immediately, or move the `use` call outside of the ' + - '`try/catch` block. Capturing without rethrowing will lead to ' + - 'unexpected behavior.\n\n' + - 'To handle async errors, wrap your component in an error boundary, or ' + - "call the promise's `.catch` method and pass the result to `use`", -); - -export function createThenableState(): ThenableState { - // The ThenableState is created the first time a component suspends. If it - // suspends again, we'll reuse the same state. - return []; -} - -export function isThenableResolved(thenable: Thenable): boolean { - const status = thenable.status; - return status === 'fulfilled' || status === 'rejected'; -} - -function noop(): void {} - -export function trackUsedThenable( - thenableState: ThenableState, - thenable: Thenable, - index: number, -): T { - if (__DEV__ && ReactCurrentActQueue.current !== null) { - ReactCurrentActQueue.didUsePromise = true; - } - - const previous = thenableState[index]; - if (previous === undefined) { - thenableState.push(thenable); - } else { - if (previous !== thenable) { - // Reuse the previous thenable, and drop the new one. We can assume - // they represent the same value, because components are idempotent. - - // Avoid an unhandled rejection errors for the Promises that we'll - // intentionally ignore. - thenable.then(noop, noop); - thenable = previous; - } - } - - // We use an expando to track the status and result of a thenable so that we - // can synchronously unwrap the value. Think of this as an extension of the - // Promise API, or a custom interface that is a superset of Thenable. - // - // If the thenable doesn't have a status, set it to "pending" and attach - // a listener that will update its status and result when it resolves. - switch (thenable.status) { - case 'fulfilled': { - const fulfilledValue: T = thenable.value; - return fulfilledValue; - } - case 'rejected': { - const rejectedError = thenable.reason; - throw rejectedError; - } - default: { - if (typeof thenable.status === 'string') { - // Only instrument the thenable if the status if not defined. If - // it's defined, but an unknown value, assume it's been instrumented by - // some custom userspace implementation. We treat it as "pending". - } else { - const pendingThenable: PendingThenable = (thenable: any); - pendingThenable.status = 'pending'; - pendingThenable.then( - fulfilledValue => { - if (thenable.status === 'pending') { - const fulfilledThenable: FulfilledThenable = (thenable: any); - fulfilledThenable.status = 'fulfilled'; - fulfilledThenable.value = fulfilledValue; - } - }, - (error: mixed) => { - if (thenable.status === 'pending') { - const rejectedThenable: RejectedThenable = (thenable: any); - rejectedThenable.status = 'rejected'; - rejectedThenable.reason = error; - } - }, - ); - - // Check one more time in case the thenable resolved synchronously - switch (thenable.status) { - case 'fulfilled': { - const fulfilledThenable: FulfilledThenable = (thenable: any); - return fulfilledThenable.value; - } - case 'rejected': { - const rejectedThenable: RejectedThenable = (thenable: any); - throw rejectedThenable.reason; - } - } - } - - // Suspend. - // - // Throwing here is an implementation detail that allows us to unwind the - // call stack. But we shouldn't allow it to leak into userspace. Throw an - // opaque placeholder value instead of the actual thenable. If it doesn't - // get captured by the work loop, log a warning, because that means - // something in userspace must have caught it. - suspendedThenable = thenable; - if (__DEV__) { - needsToResetSuspendedThenableDEV = true; - } - throw SuspenseException; - } - } -} - -// This is used to track the actual thenable that suspended so it can be -// passed to the rest of the Suspense implementation — which, for historical -// reasons, expects to receive a thenable. -let suspendedThenable: Thenable | null = null; -let needsToResetSuspendedThenableDEV = false; -export function getSuspendedThenable(): Thenable { - // This is called right after `use` suspends by throwing an exception. `use` - // throws an opaque value instead of the thenable itself so that it can't be - // caught in userspace. Then the work loop accesses the actual thenable using - // this function. - if (suspendedThenable === null) { - throw new Error( - 'Expected a suspended thenable. This is a bug in React. Please file ' + - 'an issue.', - ); - } - const thenable = suspendedThenable; - suspendedThenable = null; - if (__DEV__) { - needsToResetSuspendedThenableDEV = false; - } - return thenable; -} - -export function checkIfUseWrappedInTryCatch(): boolean { - if (__DEV__) { - // This was set right before SuspenseException was thrown, and it should - // have been cleared when the exception was handled. If it wasn't, - // it must have been caught by userspace. - if (needsToResetSuspendedThenableDEV) { - needsToResetSuspendedThenableDEV = false; - return true; - } - } - return false; -} diff --git a/packages/react-reconciler/src/ReactFiberThrow.new.js b/packages/react-reconciler/src/ReactFiberThrow.new.js deleted file mode 100644 index 076ff63e5c174..0000000000000 --- a/packages/react-reconciler/src/ReactFiberThrow.new.js +++ /dev/null @@ -1,529 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Lane, Lanes} from './ReactFiberLane.new'; -import type {CapturedValue} from './ReactCapturedValue'; -import type {Update} from './ReactFiberClassUpdateQueue.new'; -import type {Wakeable} from 'shared/ReactTypes'; -import type {OffscreenQueue} from './ReactFiberOffscreenComponent'; - -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import { - ClassComponent, - HostRoot, - IncompleteClassComponent, - FunctionComponent, - ForwardRef, - SimpleMemoComponent, - SuspenseComponent, - OffscreenComponent, -} from './ReactWorkTags'; -import { - DidCapture, - Incomplete, - NoFlags, - ShouldCapture, - LifecycleEffectMask, - ForceUpdateForLegacySuspense, - ForceClientRender, -} from './ReactFiberFlags'; -import {NoMode, ConcurrentMode, DebugTracingMode} from './ReactTypeOfMode'; -import { - enableDebugTracing, - enableLazyContextPropagation, - enableUpdaterTracking, -} from 'shared/ReactFeatureFlags'; -import {createCapturedValueAtFiber} from './ReactCapturedValue'; -import { - enqueueCapturedUpdate, - createUpdate, - CaptureUpdate, - ForceUpdate, - enqueueUpdate, -} from './ReactFiberClassUpdateQueue.new'; -import {markFailedErrorBoundaryForHotReloading} from './ReactFiberHotReloading.new'; -import {getSuspenseHandler} from './ReactFiberSuspenseContext.new'; -import { - renderDidError, - renderDidSuspendDelayIfPossible, - onUncaughtError, - markLegacyErrorBoundaryAsFailed, - isAlreadyFailedLegacyErrorBoundary, - attachPingListener, - restorePendingUpdaters, -} from './ReactFiberWorkLoop.new'; -import {propagateParentContextChangesToDeferredTree} from './ReactFiberNewContext.new'; -import {logCapturedError} from './ReactFiberErrorLogger'; -import {logComponentSuspended} from './DebugTracing'; -import {isDevToolsPresent} from './ReactFiberDevToolsHook.new'; -import { - SyncLane, - NoTimestamp, - includesSomeLane, - mergeLanes, - pickArbitraryLane, -} from './ReactFiberLane.new'; -import { - getIsHydrating, - markDidThrowWhileHydratingDEV, - queueHydrationError, -} from './ReactFiberHydrationContext.new'; -import {ConcurrentRoot} from './ReactRootTags'; - -function createRootErrorUpdate( - fiber: Fiber, - errorInfo: CapturedValue, - lane: Lane, -): Update { - const update = createUpdate(NoTimestamp, lane); - // Unmount the root by rendering null. - update.tag = CaptureUpdate; - // Caution: React DevTools currently depends on this property - // being called "element". - update.payload = {element: null}; - const error = errorInfo.value; - update.callback = () => { - onUncaughtError(error); - logCapturedError(fiber, errorInfo); - }; - return update; -} - -function createClassErrorUpdate( - fiber: Fiber, - errorInfo: CapturedValue, - lane: Lane, -): Update { - const update = createUpdate(NoTimestamp, lane); - update.tag = CaptureUpdate; - const getDerivedStateFromError = fiber.type.getDerivedStateFromError; - if (typeof getDerivedStateFromError === 'function') { - const error = errorInfo.value; - update.payload = () => { - return getDerivedStateFromError(error); - }; - update.callback = () => { - if (__DEV__) { - markFailedErrorBoundaryForHotReloading(fiber); - } - logCapturedError(fiber, errorInfo); - }; - } - - const inst = fiber.stateNode; - if (inst !== null && typeof inst.componentDidCatch === 'function') { - update.callback = function callback() { - if (__DEV__) { - markFailedErrorBoundaryForHotReloading(fiber); - } - logCapturedError(fiber, errorInfo); - if (typeof getDerivedStateFromError !== 'function') { - // To preserve the preexisting retry behavior of error boundaries, - // we keep track of which ones already failed during this batch. - // This gets reset before we yield back to the browser. - // TODO: Warn in strict mode if getDerivedStateFromError is - // not defined. - markLegacyErrorBoundaryAsFailed(this); - } - const error = errorInfo.value; - const stack = errorInfo.stack; - this.componentDidCatch(error, { - componentStack: stack !== null ? stack : '', - }); - if (__DEV__) { - if (typeof getDerivedStateFromError !== 'function') { - // If componentDidCatch is the only error boundary method defined, - // then it needs to call setState to recover from errors. - // If no state update is scheduled then the boundary will swallow the error. - if (!includesSomeLane(fiber.lanes, (SyncLane: Lane))) { - console.error( - '%s: Error boundaries should implement getDerivedStateFromError(). ' + - 'In that method, return a state update to display an error message or fallback UI.', - getComponentNameFromFiber(fiber) || 'Unknown', - ); - } - } - } - }; - } - return update; -} - -function resetSuspendedComponent(sourceFiber: Fiber, rootRenderLanes: Lanes) { - if (enableLazyContextPropagation) { - const currentSourceFiber = sourceFiber.alternate; - if (currentSourceFiber !== null) { - // Since we never visited the children of the suspended component, we - // need to propagate the context change now, to ensure that we visit - // them during the retry. - // - // We don't have to do this for errors because we retry errors without - // committing in between. So this is specific to Suspense. - propagateParentContextChangesToDeferredTree( - currentSourceFiber, - sourceFiber, - rootRenderLanes, - ); - } - } - - // Reset the memoizedState to what it was before we attempted to render it. - // A legacy mode Suspense quirk, only relevant to hook components. - const tag = sourceFiber.tag; - if ( - (sourceFiber.mode & ConcurrentMode) === NoMode && - (tag === FunctionComponent || - tag === ForwardRef || - tag === SimpleMemoComponent) - ) { - const currentSource = sourceFiber.alternate; - if (currentSource) { - sourceFiber.updateQueue = currentSource.updateQueue; - sourceFiber.memoizedState = currentSource.memoizedState; - sourceFiber.lanes = currentSource.lanes; - } else { - sourceFiber.updateQueue = null; - sourceFiber.memoizedState = null; - } - } -} - -function markSuspenseBoundaryShouldCapture( - suspenseBoundary: Fiber, - returnFiber: Fiber, - sourceFiber: Fiber, - root: FiberRoot, - rootRenderLanes: Lanes, -): Fiber | null { - // This marks a Suspense boundary so that when we're unwinding the stack, - // it captures the suspended "exception" and does a second (fallback) pass. - if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { - // Legacy Mode Suspense - // - // If the boundary is in legacy mode, we should *not* - // suspend the commit. Pretend as if the suspended component rendered - // null and keep rendering. When the Suspense boundary completes, - // we'll do a second pass to render the fallback. - if (suspenseBoundary === returnFiber) { - // Special case where we suspended while reconciling the children of - // a Suspense boundary's inner Offscreen wrapper fiber. This happens - // when a React.lazy component is a direct child of a - // Suspense boundary. - // - // Suspense boundaries are implemented as multiple fibers, but they - // are a single conceptual unit. The legacy mode behavior where we - // pretend the suspended fiber committed as `null` won't work, - // because in this case the "suspended" fiber is the inner - // Offscreen wrapper. - // - // Because the contents of the boundary haven't started rendering - // yet (i.e. nothing in the tree has partially rendered) we can - // switch to the regular, concurrent mode behavior: mark the - // boundary with ShouldCapture and enter the unwind phase. - suspenseBoundary.flags |= ShouldCapture; - } else { - suspenseBoundary.flags |= DidCapture; - sourceFiber.flags |= ForceUpdateForLegacySuspense; - - // We're going to commit this fiber even though it didn't complete. - // But we shouldn't call any lifecycle methods or callbacks. Remove - // all lifecycle effect tags. - sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); - - if (sourceFiber.tag === ClassComponent) { - const currentSourceFiber = sourceFiber.alternate; - if (currentSourceFiber === null) { - // This is a new mount. Change the tag so it's not mistaken for a - // completed class component. For example, we should not call - // componentWillUnmount if it is deleted. - sourceFiber.tag = IncompleteClassComponent; - } else { - // When we try rendering again, we should not reuse the current fiber, - // since it's known to be in an inconsistent state. Use a force update to - // prevent a bail out. - const update = createUpdate(NoTimestamp, SyncLane); - update.tag = ForceUpdate; - enqueueUpdate(sourceFiber, update, SyncLane); - } - } - - // The source fiber did not complete. Mark it with Sync priority to - // indicate that it still has pending work. - sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); - } - return suspenseBoundary; - } - // Confirmed that the boundary is in a concurrent mode tree. Continue - // with the normal suspend path. - // - // After this we'll use a set of heuristics to determine whether this - // render pass will run to completion or restart or "suspend" the commit. - // The actual logic for this is spread out in different places. - // - // This first principle is that if we're going to suspend when we complete - // a root, then we should also restart if we get an update or ping that - // might unsuspend it, and vice versa. The only reason to suspend is - // because you think you might want to restart before committing. However, - // it doesn't make sense to restart only while in the period we're suspended. - // - // Restarting too aggressively is also not good because it starves out any - // intermediate loading state. So we use heuristics to determine when. - - // Suspense Heuristics - // - // If nothing threw a Promise or all the same fallbacks are already showing, - // then don't suspend/restart. - // - // If this is an initial render of a new tree of Suspense boundaries and - // those trigger a fallback, then don't suspend/restart. We want to ensure - // that we can show the initial loading state as quickly as possible. - // - // If we hit a "Delayed" case, such as when we'd switch from content back into - // a fallback, then we should always suspend/restart. Transitions apply - // to this case. If none is defined, JND is used instead. - // - // If we're already showing a fallback and it gets "retried", allowing us to show - // another level, but there's still an inner boundary that would show a fallback, - // then we suspend/restart for 500ms since the last time we showed a fallback - // anywhere in the tree. This effectively throttles progressive loading into a - // consistent train of commits. This also gives us an opportunity to restart to - // get to the completed state slightly earlier. - // - // If there's ambiguity due to batching it's resolved in preference of: - // 1) "delayed", 2) "initial render", 3) "retry". - // - // We want to ensure that a "busy" state doesn't get force committed. We want to - // ensure that new initial loading states can commit as soon as possible. - suspenseBoundary.flags |= ShouldCapture; - // TODO: I think we can remove this, since we now use `DidCapture` in - // the begin phase to prevent an early bailout. - suspenseBoundary.lanes = rootRenderLanes; - return suspenseBoundary; -} - -function throwException( - root: FiberRoot, - returnFiber: Fiber, - sourceFiber: Fiber, - value: mixed, - rootRenderLanes: Lanes, -): void { - // The source fiber did not complete. - sourceFiber.flags |= Incomplete; - - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - // If we have pending work still, restore the original updaters - restorePendingUpdaters(root, rootRenderLanes); - } - } - - if ( - value !== null && - typeof value === 'object' && - typeof value.then === 'function' - ) { - // This is a wakeable. The component suspended. - const wakeable: Wakeable = (value: any); - resetSuspendedComponent(sourceFiber, rootRenderLanes); - - if (__DEV__) { - if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { - markDidThrowWhileHydratingDEV(); - } - } - - if (__DEV__) { - if (enableDebugTracing) { - if (sourceFiber.mode & DebugTracingMode) { - const name = getComponentNameFromFiber(sourceFiber) || 'Unknown'; - logComponentSuspended(name, wakeable); - } - } - } - - // Schedule the nearest Suspense to re-render the timed out view. - const suspenseBoundary = getSuspenseHandler(); - if (suspenseBoundary !== null) { - switch (suspenseBoundary.tag) { - case SuspenseComponent: { - suspenseBoundary.flags &= ~ForceClientRender; - markSuspenseBoundaryShouldCapture( - suspenseBoundary, - returnFiber, - sourceFiber, - root, - rootRenderLanes, - ); - // Retry listener - // - // If the fallback does commit, we need to attach a different type of - // listener. This one schedules an update on the Suspense boundary to - // turn the fallback state off. - // - // Stash the wakeable on the boundary fiber so we can access it in the - // commit phase. - // - // When the wakeable resolves, we'll attempt to render the boundary - // again ("retry"). - const wakeables: Set | null = (suspenseBoundary.updateQueue: any); - if (wakeables === null) { - suspenseBoundary.updateQueue = new Set([wakeable]); - } else { - wakeables.add(wakeable); - } - break; - } - case OffscreenComponent: { - if (suspenseBoundary.mode & ConcurrentMode) { - suspenseBoundary.flags |= ShouldCapture; - const offscreenQueue: OffscreenQueue | null = (suspenseBoundary.updateQueue: any); - if (offscreenQueue === null) { - const newOffscreenQueue: OffscreenQueue = { - transitions: null, - markerInstances: null, - wakeables: new Set([wakeable]), - }; - suspenseBoundary.updateQueue = newOffscreenQueue; - } else { - const wakeables = offscreenQueue.wakeables; - if (wakeables === null) { - offscreenQueue.wakeables = new Set([wakeable]); - } else { - wakeables.add(wakeable); - } - } - break; - } - } - // eslint-disable-next-line no-fallthrough - default: { - throw new Error( - `Unexpected Suspense handler tag (${suspenseBoundary.tag}). This ` + - 'is a bug in React.', - ); - } - } - // We only attach ping listeners in concurrent mode. Legacy Suspense always - // commits fallbacks synchronously, so there are no pings. - if (suspenseBoundary.mode & ConcurrentMode) { - attachPingListener(root, wakeable, rootRenderLanes); - } - return; - } else { - // No boundary was found. Unless this is a sync update, this is OK. - // We can suspend and wait for more data to arrive. - - if (root.tag === ConcurrentRoot) { - // In a concurrent root, suspending without a Suspense boundary is - // allowed. It will suspend indefinitely without committing. - // - // TODO: Should we have different behavior for discrete updates? What - // about flushSync? Maybe it should put the tree into an inert state, - // and potentially log a warning. Revisit this for a future release. - attachPingListener(root, wakeable, rootRenderLanes); - renderDidSuspendDelayIfPossible(); - return; - } else { - // In a legacy root, suspending without a boundary is always an error. - const uncaughtSuspenseError = new Error( - 'A component suspended while responding to synchronous input. This ' + - 'will cause the UI to be replaced with a loading indicator. To ' + - 'fix, updates that suspend should be wrapped ' + - 'with startTransition.', - ); - value = uncaughtSuspenseError; - } - } - } else { - // This is a regular error, not a Suspense wakeable. - if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { - markDidThrowWhileHydratingDEV(); - const suspenseBoundary = getSuspenseHandler(); - // If the error was thrown during hydration, we may be able to recover by - // discarding the dehydrated content and switching to a client render. - // Instead of surfacing the error, find the nearest Suspense boundary - // and render it again without hydration. - if (suspenseBoundary !== null) { - if ((suspenseBoundary.flags & ShouldCapture) === NoFlags) { - // Set a flag to indicate that we should try rendering the normal - // children again, not the fallback. - suspenseBoundary.flags |= ForceClientRender; - } - markSuspenseBoundaryShouldCapture( - suspenseBoundary, - returnFiber, - sourceFiber, - root, - rootRenderLanes, - ); - - // Even though the user may not be affected by this error, we should - // still log it so it can be fixed. - queueHydrationError(createCapturedValueAtFiber(value, sourceFiber)); - return; - } - } else { - // Otherwise, fall through to the error path. - } - } - - value = createCapturedValueAtFiber(value, sourceFiber); - renderDidError(value); - - // We didn't find a boundary that could handle this type of exception. Start - // over and traverse parent path again, this time treating the exception - // as an error. - let workInProgress: Fiber = returnFiber; - do { - switch (workInProgress.tag) { - case HostRoot: { - const errorInfo = value; - workInProgress.flags |= ShouldCapture; - const lane = pickArbitraryLane(rootRenderLanes); - workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); - const update = createRootErrorUpdate(workInProgress, errorInfo, lane); - enqueueCapturedUpdate(workInProgress, update); - return; - } - case ClassComponent: - // Capture and retry - const errorInfo = value; - const ctor = workInProgress.type; - const instance = workInProgress.stateNode; - if ( - (workInProgress.flags & DidCapture) === NoFlags && - (typeof ctor.getDerivedStateFromError === 'function' || - (instance !== null && - typeof instance.componentDidCatch === 'function' && - !isAlreadyFailedLegacyErrorBoundary(instance))) - ) { - workInProgress.flags |= ShouldCapture; - const lane = pickArbitraryLane(rootRenderLanes); - workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); - // Schedule the error boundary to re-render using updated state - const update = createClassErrorUpdate( - workInProgress, - errorInfo, - lane, - ); - enqueueCapturedUpdate(workInProgress, update); - return; - } - break; - default: - break; - } - // $FlowFixMe[incompatible-type] we bail out when we get a null - workInProgress = workInProgress.return; - } while (workInProgress !== null); -} - -export {throwException, createRootErrorUpdate, createClassErrorUpdate}; diff --git a/packages/react-reconciler/src/ReactFiberTracingMarkerComponent.new.js b/packages/react-reconciler/src/ReactFiberTracingMarkerComponent.new.js deleted file mode 100644 index 04a584de0679a..0000000000000 --- a/packages/react-reconciler/src/ReactFiberTracingMarkerComponent.new.js +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type { - TransitionTracingCallbacks, - Fiber, - FiberRoot, -} from './ReactInternalTypes'; -import type {OffscreenInstance} from './ReactFiberOffscreenComponent'; -import type {StackCursor} from './ReactFiberStack.new'; - -import {enableTransitionTracing} from 'shared/ReactFeatureFlags'; -import {createCursor, push, pop} from './ReactFiberStack.new'; -import {getWorkInProgressTransitions} from './ReactFiberWorkLoop.new'; - -export type SuspenseInfo = {name: string | null}; - -export type PendingTransitionCallbacks = { - transitionStart: Array | null, - transitionProgress: Map | null, - transitionComplete: Array | null, - markerProgress: Map< - string, - {pendingBoundaries: PendingBoundaries, transitions: Set}, - > | null, - markerIncomplete: Map< - string, - {aborts: Array, transitions: Set}, - > | null, - markerComplete: Map> | null, -}; - -export type Transition = { - name: string, - startTime: number, -}; - -export type BatchConfigTransition = { - name?: string, - startTime?: number, - _updatedFibers?: Set, -}; - -// TODO: Is there a way to not include the tag or name here? -export type TracingMarkerInstance = { - tag?: TracingMarkerTag, - transitions: Set | null, - pendingBoundaries: PendingBoundaries | null, - aborts: Array | null, - name: string | null, -}; - -export type TransitionAbort = { - reason: 'error' | 'unknown' | 'marker' | 'suspense', - name?: string | null, -}; - -export const TransitionRoot = 0; -export const TransitionTracingMarker = 1; -export type TracingMarkerTag = 0 | 1; - -export type PendingBoundaries = Map; - -export function processTransitionCallbacks( - pendingTransitions: PendingTransitionCallbacks, - endTime: number, - callbacks: TransitionTracingCallbacks, -): void { - if (enableTransitionTracing) { - if (pendingTransitions !== null) { - const transitionStart = pendingTransitions.transitionStart; - const onTransitionStart = callbacks.onTransitionStart; - if (transitionStart !== null && onTransitionStart != null) { - transitionStart.forEach(transition => - onTransitionStart(transition.name, transition.startTime), - ); - } - - const markerProgress = pendingTransitions.markerProgress; - const onMarkerProgress = callbacks.onMarkerProgress; - if (onMarkerProgress != null && markerProgress !== null) { - markerProgress.forEach((markerInstance, markerName) => { - if (markerInstance.transitions !== null) { - // TODO: Clone the suspense object so users can't modify it - const pending = - markerInstance.pendingBoundaries !== null - ? Array.from(markerInstance.pendingBoundaries.values()) - : []; - markerInstance.transitions.forEach(transition => { - onMarkerProgress( - transition.name, - markerName, - transition.startTime, - endTime, - pending, - ); - }); - } - }); - } - - const markerComplete = pendingTransitions.markerComplete; - const onMarkerComplete = callbacks.onMarkerComplete; - if (markerComplete !== null && onMarkerComplete != null) { - markerComplete.forEach((transitions, markerName) => { - transitions.forEach(transition => { - onMarkerComplete( - transition.name, - markerName, - transition.startTime, - endTime, - ); - }); - }); - } - - const markerIncomplete = pendingTransitions.markerIncomplete; - const onMarkerIncomplete = callbacks.onMarkerIncomplete; - if (onMarkerIncomplete != null && markerIncomplete !== null) { - markerIncomplete.forEach(({transitions, aborts}, markerName) => { - transitions.forEach(transition => { - const filteredAborts = []; - aborts.forEach(abort => { - switch (abort.reason) { - case 'marker': { - filteredAborts.push({ - type: 'marker', - name: abort.name, - endTime, - }); - break; - } - case 'suspense': { - filteredAborts.push({ - type: 'suspense', - name: abort.name, - endTime, - }); - break; - } - default: { - break; - } - } - }); - - if (filteredAborts.length > 0) { - onMarkerIncomplete( - transition.name, - markerName, - transition.startTime, - filteredAborts, - ); - } - }); - }); - } - - const transitionProgress = pendingTransitions.transitionProgress; - const onTransitionProgress = callbacks.onTransitionProgress; - if (onTransitionProgress != null && transitionProgress !== null) { - transitionProgress.forEach((pending, transition) => { - onTransitionProgress( - transition.name, - transition.startTime, - endTime, - Array.from(pending.values()), - ); - }); - } - - const transitionComplete = pendingTransitions.transitionComplete; - const onTransitionComplete = callbacks.onTransitionComplete; - if (transitionComplete !== null && onTransitionComplete != null) { - transitionComplete.forEach(transition => - onTransitionComplete(transition.name, transition.startTime, endTime), - ); - } - } - } -} - -// For every tracing marker, store a pointer to it. We will later access it -// to get the set of suspense boundaries that need to resolve before the -// tracing marker can be logged as complete -// This code lives separate from the ReactFiberTransition code because -// we push and pop on the tracing marker, not the suspense boundary -const markerInstanceStack: StackCursor | null> = createCursor( - null, -); - -export function pushRootMarkerInstance(workInProgress: Fiber): void { - if (enableTransitionTracing) { - // On the root, every transition gets mapped to it's own map of - // suspense boundaries. The transition is marked as complete when - // the suspense boundaries map is empty. We do this because every - // transition completes at different times and depends on different - // suspense boundaries to complete. We store all the transitions - // along with its map of suspense boundaries in the root incomplete - // transitions map. Each entry in this map functions like a tracing - // marker does, so we can push it onto the marker instance stack - const transitions = getWorkInProgressTransitions(); - const root: FiberRoot = workInProgress.stateNode; - - if (transitions !== null) { - transitions.forEach(transition => { - if (!root.incompleteTransitions.has(transition)) { - const markerInstance: TracingMarkerInstance = { - tag: TransitionRoot, - transitions: new Set([transition]), - pendingBoundaries: null, - aborts: null, - name: null, - }; - root.incompleteTransitions.set(transition, markerInstance); - } - }); - } - - const markerInstances = []; - // For ever transition on the suspense boundary, we push the transition - // along with its map of pending suspense boundaries onto the marker - // instance stack. - root.incompleteTransitions.forEach(markerInstance => { - markerInstances.push(markerInstance); - }); - push(markerInstanceStack, markerInstances, workInProgress); - } -} - -export function popRootMarkerInstance(workInProgress: Fiber) { - if (enableTransitionTracing) { - pop(markerInstanceStack, workInProgress); - } -} - -export function pushMarkerInstance( - workInProgress: Fiber, - markerInstance: TracingMarkerInstance, -): void { - if (enableTransitionTracing) { - if (markerInstanceStack.current === null) { - push(markerInstanceStack, [markerInstance], workInProgress); - } else { - push( - markerInstanceStack, - markerInstanceStack.current.concat(markerInstance), - workInProgress, - ); - } - } -} - -export function popMarkerInstance(workInProgress: Fiber): void { - if (enableTransitionTracing) { - pop(markerInstanceStack, workInProgress); - } -} - -export function getMarkerInstances(): Array | null { - if (enableTransitionTracing) { - return markerInstanceStack.current; - } - return null; -} diff --git a/packages/react-reconciler/src/ReactFiberTransition.js b/packages/react-reconciler/src/ReactFiberTransition.js deleted file mode 100644 index 6fab816770e29..0000000000000 --- a/packages/react-reconciler/src/ReactFiberTransition.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import ReactSharedInternals from 'shared/ReactSharedInternals'; -import type {Transition} from './ReactFiberTracingMarkerComponent.new'; - -const {ReactCurrentBatchConfig} = ReactSharedInternals; - -export const NoTransition = null; - -export function requestCurrentTransition(): Transition | null { - return ReactCurrentBatchConfig.transition; -} diff --git a/packages/react-reconciler/src/ReactFiberTransition.new.js b/packages/react-reconciler/src/ReactFiberTransition.new.js deleted file mode 100644 index df677a53074d1..0000000000000 --- a/packages/react-reconciler/src/ReactFiberTransition.new.js +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Lanes} from './ReactFiberLane.new'; -import type {StackCursor} from './ReactFiberStack.new'; -import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent.new'; -import type {Transition} from './ReactFiberTracingMarkerComponent.new'; - -import {enableCache, enableTransitionTracing} from 'shared/ReactFeatureFlags'; -import {isPrimaryRenderer} from './ReactFiberHostConfig'; -import {createCursor, push, pop} from './ReactFiberStack.new'; -import { - getWorkInProgressRoot, - getWorkInProgressTransitions, -} from './ReactFiberWorkLoop.new'; -import { - createCache, - retainCache, - CacheContext, -} from './ReactFiberCacheComponent.new'; - -// When retrying a Suspense/Offscreen boundary, we restore the cache that was -// used during the previous render by placing it here, on the stack. -const resumedCache: StackCursor = createCursor(null); - -// During the render/synchronous commit phase, we don't actually process the -// transitions. Therefore, we want to lazily combine transitions. Instead of -// comparing the arrays of transitions when we combine them and storing them -// and filtering out the duplicates, we will instead store the unprocessed transitions -// in an array and actually filter them in the passive phase. -const transitionStack: StackCursor | null> = createCursor( - null, -); - -function peekCacheFromPool(): Cache | null { - if (!enableCache) { - return (null: any); - } - - // Check if the cache pool already has a cache we can use. - - // If we're rendering inside a Suspense boundary that is currently hidden, - // we should use the same cache that we used during the previous render, if - // one exists. - const cacheResumedFromPreviousRender = resumedCache.current; - if (cacheResumedFromPreviousRender !== null) { - return cacheResumedFromPreviousRender; - } - - // Otherwise, check the root's cache pool. - const root = (getWorkInProgressRoot(): any); - const cacheFromRootCachePool = root.pooledCache; - - return cacheFromRootCachePool; -} - -export function requestCacheFromPool(renderLanes: Lanes): Cache { - // Similar to previous function, except if there's not already a cache in the - // pool, we allocate a new one. - const cacheFromPool = peekCacheFromPool(); - if (cacheFromPool !== null) { - return cacheFromPool; - } - - // Create a fresh cache and add it to the root cache pool. A cache can have - // multiple owners: - // - A cache pool that lives on the FiberRoot. This is where all fresh caches - // are originally created (TODO: except during refreshes, until we implement - // this correctly). The root takes ownership immediately when the cache is - // created. Conceptually, root.pooledCache is an Option> (owned), - // and the return value of this function is a &Arc (borrowed). - // - One of several fiber types: host root, cache boundary, suspense - // component. These retain and release in the commit phase. - - const root = (getWorkInProgressRoot(): any); - const freshCache = createCache(); - root.pooledCache = freshCache; - retainCache(freshCache); - if (freshCache !== null) { - root.pooledCacheLanes |= renderLanes; - } - return freshCache; -} - -export function pushRootTransition( - workInProgress: Fiber, - root: FiberRoot, - renderLanes: Lanes, -) { - if (enableTransitionTracing) { - const rootTransitions = getWorkInProgressTransitions(); - push(transitionStack, rootTransitions, workInProgress); - } -} - -export function popRootTransition( - workInProgress: Fiber, - root: FiberRoot, - renderLanes: Lanes, -) { - if (enableTransitionTracing) { - pop(transitionStack, workInProgress); - } -} - -export function pushTransition( - offscreenWorkInProgress: Fiber, - prevCachePool: SpawnedCachePool | null, - newTransitions: Array | null, -): void { - if (enableCache) { - if (prevCachePool === null) { - push(resumedCache, resumedCache.current, offscreenWorkInProgress); - } else { - push(resumedCache, prevCachePool.pool, offscreenWorkInProgress); - } - } - - if (enableTransitionTracing) { - if (transitionStack.current === null) { - push(transitionStack, newTransitions, offscreenWorkInProgress); - } else if (newTransitions === null) { - push(transitionStack, transitionStack.current, offscreenWorkInProgress); - } else { - push( - transitionStack, - transitionStack.current.concat(newTransitions), - offscreenWorkInProgress, - ); - } - } -} - -export function popTransition(workInProgress: Fiber, current: Fiber | null) { - if (current !== null) { - if (enableTransitionTracing) { - pop(transitionStack, workInProgress); - } - - if (enableCache) { - pop(resumedCache, workInProgress); - } - } -} - -export function getPendingTransitions(): Array | null { - if (!enableTransitionTracing) { - return null; - } - - return transitionStack.current; -} - -export function getSuspendedCache(): SpawnedCachePool | null { - if (!enableCache) { - return null; - } - // This function is called when a Suspense boundary suspends. It returns the - // cache that would have been used to render fresh data during this render, - // if there was any, so that we can resume rendering with the same cache when - // we receive more data. - const cacheFromPool = peekCacheFromPool(); - if (cacheFromPool === null) { - return null; - } - - return { - // We must also save the parent, so that when we resume we can detect - // a refresh. - parent: isPrimaryRenderer - ? CacheContext._currentValue - : CacheContext._currentValue2, - pool: cacheFromPool, - }; -} - -export function getOffscreenDeferredCache(): SpawnedCachePool | null { - if (!enableCache) { - return null; - } - - const cacheFromPool = peekCacheFromPool(); - if (cacheFromPool === null) { - return null; - } - - return { - // We must also store the parent, so that when we resume we can detect - // a refresh. - parent: isPrimaryRenderer - ? CacheContext._currentValue - : CacheContext._currentValue2, - pool: cacheFromPool, - }; -} diff --git a/packages/react-reconciler/src/ReactFiberTransition.old.js b/packages/react-reconciler/src/ReactFiberTransition.old.js index 0d075f7a86582..7d8be86b6319b 100644 --- a/packages/react-reconciler/src/ReactFiberTransition.old.js +++ b/packages/react-reconciler/src/ReactFiberTransition.old.js @@ -25,6 +25,16 @@ import { CacheContext, } from './ReactFiberCacheComponent.old'; +import ReactSharedInternals from 'shared/ReactSharedInternals'; + +const {ReactCurrentBatchConfig} = ReactSharedInternals; + +export const NoTransition = null; + +export function requestCurrentTransition(): Transition | null { + return ReactCurrentBatchConfig.transition; +} + // When retrying a Suspense/Offscreen boundary, we restore the cache that was // used during the previous render by placing it here, on the stack. const resumedCache: StackCursor = createCursor(null); diff --git a/packages/react-reconciler/src/ReactFiberTransitionPool.old.js b/packages/react-reconciler/src/ReactFiberTransitionPool.old.js deleted file mode 100644 index 58c6201e0e2f6..0000000000000 --- a/packages/react-reconciler/src/ReactFiberTransitionPool.old.js +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Lanes} from './ReactFiberLane.old'; -import type {StackCursor} from './ReactFiberStack.old'; -import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent.old'; - -import {enableCache} from 'shared/ReactFeatureFlags'; -import {isPrimaryRenderer} from './ReactFiberHostConfig'; -import {createCursor, push, pop} from './ReactFiberStack.old'; -import {getWorkInProgressRoot} from './ReactFiberWorkLoop.old'; -import { - createCache, - retainCache, - CacheContext, -} from './ReactFiberCacheComponent.old'; - -// When retrying a Suspense/Offscreen boundary, we restore the cache that was -// used during the previous render by placing it here, on the stack. -const resumedCache: StackCursor = createCursor(null); - -function peekCacheFromPool(): Cache | null { - if (!enableCache) { - return (null: any); - } - - // Check if the cache pool already has a cache we can use. - - // If we're rendering inside a Suspense boundary that is currently hidden, - // we should use the same cache that we used during the previous render, if - // one exists. - const cacheResumedFromPreviousRender = resumedCache.current; - if (cacheResumedFromPreviousRender !== null) { - return cacheResumedFromPreviousRender; - } - - // Otherwise, check the root's cache pool. - const root = (getWorkInProgressRoot(): any); - const cacheFromRootCachePool = root.pooledCache; - - return cacheFromRootCachePool; -} - -export function requestCacheFromPool(renderLanes: Lanes): Cache { - // Similar to previous function, except if there's not already a cache in the - // pool, we allocate a new one. - const cacheFromPool = peekCacheFromPool(); - if (cacheFromPool !== null) { - return cacheFromPool; - } - - // Create a fresh cache and add it to the root cache pool. A cache can have - // multiple owners: - // - A cache pool that lives on the FiberRoot. This is where all fresh caches - // are originally created (TODO: except during refreshes, until we implement - // this correctly). The root takes ownership immediately when the cache is - // created. Conceptually, root.pooledCache is an Option> (owned), - // and the return value of this function is a &Arc (borrowed). - // - One of several fiber types: host root, cache boundary, suspense - // component. These retain and release in the commit phase. - - const root = (getWorkInProgressRoot(): any); - const freshCache = createCache(); - root.pooledCache = freshCache; - retainCache(freshCache); - if (freshCache !== null) { - root.pooledCacheLanes |= renderLanes; - } - return freshCache; -} - -export function pushRootTransitionPool(root: FiberRoot) { - if (enableCache) { - return; - } - // Note: This function currently does nothing but I'll leave it here for - // code organization purposes in case that changes. -} - -export function popRootTransitionPool(root: FiberRoot, renderLanes: Lanes) { - if (enableCache) { - return; - } - // Note: This function currently does nothing but I'll leave it here for - // code organization purposes in case that changes. -} - -export function pushTransitionPool( - offscreenWorkInProgress: Fiber, - prevCachePool: SpawnedCachePool | null, -): void { - if (enableCache) { - if (prevCachePool === null) { - push(resumedCache, resumedCache.current, offscreenWorkInProgress); - } else { - push(resumedCache, prevCachePool.pool, offscreenWorkInProgress); - } - } -} - -export function popTransitionPool(workInProgress: Fiber) { - if (enableCache) { - pop(resumedCache, workInProgress); - } -} - -export function getSuspendedCachePool(): SpawnedCachePool | null { - if (!enableCache) { - return null; - } - // This function is called when a Suspense boundary suspends. It returns the - // cache that would have been used to render fresh data during this render, - // if there was any, so that we can resume rendering with the same cache when - // we receive more data. - const cacheFromPool = peekCacheFromPool(); - if (cacheFromPool === null) { - return null; - } - - return { - // We must also save the parent, so that when we resume we can detect - // a refresh. - parent: isPrimaryRenderer - ? CacheContext._currentValue - : CacheContext._currentValue2, - pool: cacheFromPool, - }; -} - -export function getOffscreenDeferredCachePool(): SpawnedCachePool | null { - if (!enableCache) { - return null; - } - - const cacheFromPool = peekCacheFromPool(); - if (cacheFromPool === null) { - return null; - } - - return { - // We must also store the parent, so that when we resume we can detect - // a refresh. - parent: isPrimaryRenderer - ? CacheContext._currentValue - : CacheContext._currentValue2, - pool: cacheFromPool, - }; -} diff --git a/packages/react-reconciler/src/ReactFiberTreeContext.new.js b/packages/react-reconciler/src/ReactFiberTreeContext.new.js deleted file mode 100644 index cb894091f7418..0000000000000 --- a/packages/react-reconciler/src/ReactFiberTreeContext.new.js +++ /dev/null @@ -1,289 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -// Ids are base 32 strings whose binary representation corresponds to the -// position of a node in a tree. - -// Every time the tree forks into multiple children, we add additional bits to -// the left of the sequence that represent the position of the child within the -// current level of children. -// -// 00101 00010001011010101 -// ╰─┬─╯ ╰───────┬───────╯ -// Fork 5 of 20 Parent id -// -// The leading 0s are important. In the above example, you only need 3 bits to -// represent slot 5. However, you need 5 bits to represent all the forks at -// the current level, so we must account for the empty bits at the end. -// -// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise, -// the zeroth id at a level would be indistinguishable from its parent. -// -// If a node has only one child, and does not materialize an id (i.e. does not -// contain a useId hook), then we don't need to allocate any space in the -// sequence. It's treated as a transparent indirection. For example, these two -// trees produce the same ids: -// -// <> <> -// -// -// -// -// -// -// However, we cannot skip any node that materializes an id. Otherwise, a parent -// id that does not fork would be indistinguishable from its child id. For -// example, this tree does not fork, but the parent and child must have -// different ids. -// -// -// -// -// -// To handle this scenario, every time we materialize an id, we allocate a -// new level with a single slot. You can think of this as a fork with only one -// prong, or an array of children with length 1. -// -// It's possible for the size of the sequence to exceed 32 bits, the max -// size for bitwise operations. When this happens, we make more room by -// converting the right part of the id to a string and storing it in an overflow -// variable. We use a base 32 string representation, because 32 is the largest -// power of 2 that is supported by toString(). We want the base to be large so -// that the resulting ids are compact, and we want the base to be a power of 2 -// because every log2(base) bits corresponds to a single character, i.e. every -// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without -// affecting the final result. - -import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; - -import {getIsHydrating} from './ReactFiberHydrationContext.new'; -import {clz32} from './clz32'; -import {Forked, NoFlags} from './ReactFiberFlags'; - -export type TreeContext = { - id: number, - overflow: string, -}; - -// TODO: Use the unified fiber stack module instead of this local one? -// Intentionally not using it yet to derisk the initial implementation, because -// the way we push/pop these values is a bit unusual. If there's a mistake, I'd -// rather the ids be wrong than crash the whole reconciler. -const forkStack: Array = []; -let forkStackIndex: number = 0; -let treeForkProvider: Fiber | null = null; -let treeForkCount: number = 0; - -const idStack: Array = []; -let idStackIndex: number = 0; -let treeContextProvider: Fiber | null = null; -let treeContextId: number = 1; -let treeContextOverflow: string = ''; - -export function isForkedChild(workInProgress: Fiber): boolean { - warnIfNotHydrating(); - return (workInProgress.flags & Forked) !== NoFlags; -} - -export function getForksAtLevel(workInProgress: Fiber): number { - warnIfNotHydrating(); - return treeForkCount; -} - -export function getTreeId(): string { - const overflow = treeContextOverflow; - const idWithLeadingBit = treeContextId; - const id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; -} - -export function pushTreeFork( - workInProgress: Fiber, - totalChildren: number, -): void { - // This is called right after we reconcile an array (or iterator) of child - // fibers, because that's the only place where we know how many children in - // the whole set without doing extra work later, or storing addtional - // information on the fiber. - // - // That's why this function is separate from pushTreeId — it's called during - // the render phase of the fork parent, not the child, which is where we push - // the other context values. - // - // In the Fizz implementation this is much simpler because the child is - // rendered in the same callstack as the parent. - // - // It might be better to just add a `forks` field to the Fiber type. It would - // make this module simpler. - - warnIfNotHydrating(); - - forkStack[forkStackIndex++] = treeForkCount; - forkStack[forkStackIndex++] = treeForkProvider; - - treeForkProvider = workInProgress; - treeForkCount = totalChildren; -} - -export function pushTreeId( - workInProgress: Fiber, - totalChildren: number, - index: number, -) { - warnIfNotHydrating(); - - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - - treeContextProvider = workInProgress; - - const baseIdWithLeadingBit = treeContextId; - const baseOverflow = treeContextOverflow; - - // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part - // of the id; we use it to account for leading 0s. - const baseLength = getBitLength(baseIdWithLeadingBit) - 1; - const baseId = baseIdWithLeadingBit & ~(1 << baseLength); - - const slot = index + 1; - const length = getBitLength(totalChildren) + baseLength; - - // 30 is the max length we can store without overflowing, taking into - // consideration the leading 1 we use to mark the end of the sequence. - if (length > 30) { - // We overflowed the bitwise-safe range. Fall back to slower algorithm. - // This branch assumes the length of the base id is greater than 5; it won't - // work for smaller ids, because you need 5 bits per character. - // - // We encode the id in multiple steps: first the base id, then the - // remaining digits. - // - // Each 5 bit sequence corresponds to a single base 32 character. So for - // example, if the current id is 23 bits long, we can convert 20 of those - // bits into a string of 4 characters, with 3 bits left over. - // - // First calculate how many bits in the base id represent a complete - // sequence of characters. - const numberOfOverflowBits = baseLength - (baseLength % 5); - - // Then create a bitmask that selects only those bits. - const newOverflowBits = (1 << numberOfOverflowBits) - 1; - - // Select the bits, and convert them to a base 32 string. - const newOverflow = (baseId & newOverflowBits).toString(32); - - // Now we can remove those bits from the base id. - const restOfBaseId = baseId >> numberOfOverflowBits; - const restOfBaseLength = baseLength - numberOfOverflowBits; - - // Finally, encode the rest of the bits using the normal algorithm. Because - // we made more room, this time it won't overflow. - const restOfLength = getBitLength(totalChildren) + restOfBaseLength; - const restOfNewBits = slot << restOfBaseLength; - const id = restOfNewBits | restOfBaseId; - const overflow = newOverflow + baseOverflow; - - treeContextId = (1 << restOfLength) | id; - treeContextOverflow = overflow; - } else { - // Normal path - const newBits = slot << baseLength; - const id = newBits | baseId; - const overflow = baseOverflow; - - treeContextId = (1 << length) | id; - treeContextOverflow = overflow; - } -} - -export function pushMaterializedTreeId(workInProgress: Fiber) { - warnIfNotHydrating(); - - // This component materialized an id. This will affect any ids that appear - // in its children. - const returnFiber = workInProgress.return; - if (returnFiber !== null) { - const numberOfForks = 1; - const slotIndex = 0; - pushTreeFork(workInProgress, numberOfForks); - pushTreeId(workInProgress, numberOfForks, slotIndex); - } -} - -function getBitLength(number: number): number { - return 32 - clz32(number); -} - -function getLeadingBit(id: number) { - return 1 << (getBitLength(id) - 1); -} - -export function popTreeContext(workInProgress: Fiber) { - // Restore the previous values. - - // This is a bit more complicated than other context-like modules in Fiber - // because the same Fiber may appear on the stack multiple times and for - // different reasons. We have to keep popping until the work-in-progress is - // no longer at the top of the stack. - - while (workInProgress === treeForkProvider) { - treeForkProvider = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - treeForkCount = forkStack[--forkStackIndex]; - forkStack[forkStackIndex] = null; - } - - while (workInProgress === treeContextProvider) { - treeContextProvider = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextOverflow = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - treeContextId = idStack[--idStackIndex]; - idStack[idStackIndex] = null; - } -} - -export function getSuspendedTreeContext(): TreeContext | null { - warnIfNotHydrating(); - if (treeContextProvider !== null) { - return { - id: treeContextId, - overflow: treeContextOverflow, - }; - } else { - return null; - } -} - -export function restoreSuspendedTreeContext( - workInProgress: Fiber, - suspendedContext: TreeContext, -) { - warnIfNotHydrating(); - - idStack[idStackIndex++] = treeContextId; - idStack[idStackIndex++] = treeContextOverflow; - idStack[idStackIndex++] = treeContextProvider; - - treeContextId = suspendedContext.id; - treeContextOverflow = suspendedContext.overflow; - treeContextProvider = workInProgress; -} - -function warnIfNotHydrating() { - if (__DEV__) { - if (!getIsHydrating()) { - console.error( - 'Expected to be hydrating. This is a bug in React. Please file ' + - 'an issue.', - ); - } - } -} diff --git a/packages/react-reconciler/src/ReactFiberUnwindWork.new.js b/packages/react-reconciler/src/ReactFiberUnwindWork.new.js deleted file mode 100644 index 3e1923486dee7..0000000000000 --- a/packages/react-reconciler/src/ReactFiberUnwindWork.new.js +++ /dev/null @@ -1,285 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {ReactContext} from 'shared/ReactTypes'; -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Lanes} from './ReactFiberLane.new'; -import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; -import type {Cache} from './ReactFiberCacheComponent.new'; -import type {TracingMarkerInstance} from './ReactFiberTracingMarkerComponent.new'; - -import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.new'; -import { - ClassComponent, - HostRoot, - HostComponent, - HostResource, - HostSingleton, - HostPortal, - ContextProvider, - SuspenseComponent, - SuspenseListComponent, - OffscreenComponent, - LegacyHiddenComponent, - CacheComponent, - TracingMarkerComponent, -} from './ReactWorkTags'; -import {DidCapture, NoFlags, ShouldCapture} from './ReactFiberFlags'; -import {NoMode, ProfileMode} from './ReactTypeOfMode'; -import { - enableProfilerTimer, - enableCache, - enableTransitionTracing, -} from 'shared/ReactFeatureFlags'; - -import {popHostContainer, popHostContext} from './ReactFiberHostContext.new'; -import { - popSuspenseListContext, - popSuspenseHandler, -} from './ReactFiberSuspenseContext.new'; -import {popHiddenContext} from './ReactFiberHiddenContext.new'; -import {resetHydrationState} from './ReactFiberHydrationContext.new'; -import { - isContextProvider as isLegacyContextProvider, - popContext as popLegacyContext, - popTopLevelContextObject as popTopLevelLegacyContextObject, -} from './ReactFiberContext.new'; -import {popProvider} from './ReactFiberNewContext.new'; -import {popCacheProvider} from './ReactFiberCacheComponent.new'; -import {transferActualDuration} from './ReactProfilerTimer.new'; -import {popTreeContext} from './ReactFiberTreeContext.new'; -import {popRootTransition, popTransition} from './ReactFiberTransition.new'; -import { - popMarkerInstance, - popRootMarkerInstance, -} from './ReactFiberTracingMarkerComponent.new'; - -function unwindWork( - current: Fiber | null, - workInProgress: Fiber, - renderLanes: Lanes, -): Fiber | null { - // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - popTreeContext(workInProgress); - switch (workInProgress.tag) { - case ClassComponent: { - const Component = workInProgress.type; - if (isLegacyContextProvider(Component)) { - popLegacyContext(workInProgress); - } - const flags = workInProgress.flags; - if (flags & ShouldCapture) { - workInProgress.flags = (flags & ~ShouldCapture) | DidCapture; - if ( - enableProfilerTimer && - (workInProgress.mode & ProfileMode) !== NoMode - ) { - transferActualDuration(workInProgress); - } - return workInProgress; - } - return null; - } - case HostRoot: { - const root: FiberRoot = workInProgress.stateNode; - if (enableCache) { - const cache: Cache = workInProgress.memoizedState.cache; - popCacheProvider(workInProgress, cache); - } - - if (enableTransitionTracing) { - popRootMarkerInstance(workInProgress); - } - - popRootTransition(workInProgress, root, renderLanes); - popHostContainer(workInProgress); - popTopLevelLegacyContextObject(workInProgress); - resetMutableSourceWorkInProgressVersions(); - const flags = workInProgress.flags; - if ( - (flags & ShouldCapture) !== NoFlags && - (flags & DidCapture) === NoFlags - ) { - // There was an error during render that wasn't captured by a suspense - // boundary. Do a second pass on the root to unmount the children. - workInProgress.flags = (flags & ~ShouldCapture) | DidCapture; - return workInProgress; - } - // We unwound to the root without completing it. Exit. - return null; - } - case HostResource: - case HostSingleton: - case HostComponent: { - // TODO: popHydrationState - popHostContext(workInProgress); - return null; - } - case SuspenseComponent: { - popSuspenseHandler(workInProgress); - const suspenseState: null | SuspenseState = workInProgress.memoizedState; - if (suspenseState !== null && suspenseState.dehydrated !== null) { - if (workInProgress.alternate === null) { - throw new Error( - 'Threw in newly mounted dehydrated component. This is likely a bug in ' + - 'React. Please file an issue.', - ); - } - - resetHydrationState(); - } - - const flags = workInProgress.flags; - if (flags & ShouldCapture) { - workInProgress.flags = (flags & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - if ( - enableProfilerTimer && - (workInProgress.mode & ProfileMode) !== NoMode - ) { - transferActualDuration(workInProgress); - } - return workInProgress; - } - return null; - } - case SuspenseListComponent: { - popSuspenseListContext(workInProgress); - // SuspenseList doesn't actually catch anything. It should've been - // caught by a nested boundary. If not, it should bubble through. - return null; - } - case HostPortal: - popHostContainer(workInProgress); - return null; - case ContextProvider: - const context: ReactContext = workInProgress.type._context; - popProvider(context, workInProgress); - return null; - case OffscreenComponent: - case LegacyHiddenComponent: { - popSuspenseHandler(workInProgress); - popHiddenContext(workInProgress); - popTransition(workInProgress, current); - const flags = workInProgress.flags; - if (flags & ShouldCapture) { - workInProgress.flags = (flags & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - if ( - enableProfilerTimer && - (workInProgress.mode & ProfileMode) !== NoMode - ) { - transferActualDuration(workInProgress); - } - return workInProgress; - } - return null; - } - case CacheComponent: - if (enableCache) { - const cache: Cache = workInProgress.memoizedState.cache; - popCacheProvider(workInProgress, cache); - } - return null; - case TracingMarkerComponent: - if (enableTransitionTracing) { - if (workInProgress.stateNode !== null) { - popMarkerInstance(workInProgress); - } - } - return null; - default: - return null; - } -} - -function unwindInterruptedWork( - current: Fiber | null, - interruptedWork: Fiber, - renderLanes: Lanes, -) { - // Note: This intentionally doesn't check if we're hydrating because comparing - // to the current tree provider fiber is just as fast and less error-prone. - // Ideally we would have a special version of the work loop only - // for hydration. - popTreeContext(interruptedWork); - switch (interruptedWork.tag) { - case ClassComponent: { - const childContextTypes = interruptedWork.type.childContextTypes; - if (childContextTypes !== null && childContextTypes !== undefined) { - popLegacyContext(interruptedWork); - } - break; - } - case HostRoot: { - const root: FiberRoot = interruptedWork.stateNode; - if (enableCache) { - const cache: Cache = interruptedWork.memoizedState.cache; - popCacheProvider(interruptedWork, cache); - } - - if (enableTransitionTracing) { - popRootMarkerInstance(interruptedWork); - } - - popRootTransition(interruptedWork, root, renderLanes); - popHostContainer(interruptedWork); - popTopLevelLegacyContextObject(interruptedWork); - resetMutableSourceWorkInProgressVersions(); - break; - } - case HostResource: - case HostSingleton: - case HostComponent: { - popHostContext(interruptedWork); - break; - } - case HostPortal: - popHostContainer(interruptedWork); - break; - case SuspenseComponent: - popSuspenseHandler(interruptedWork); - break; - case SuspenseListComponent: - popSuspenseListContext(interruptedWork); - break; - case ContextProvider: - const context: ReactContext = interruptedWork.type._context; - popProvider(context, interruptedWork); - break; - case OffscreenComponent: - case LegacyHiddenComponent: - popSuspenseHandler(interruptedWork); - popHiddenContext(interruptedWork); - popTransition(interruptedWork, current); - break; - case CacheComponent: - if (enableCache) { - const cache: Cache = interruptedWork.memoizedState.cache; - popCacheProvider(interruptedWork, cache); - } - break; - case TracingMarkerComponent: - if (enableTransitionTracing) { - const instance: TracingMarkerInstance | null = - interruptedWork.stateNode; - if (instance !== null) { - popMarkerInstance(interruptedWork); - } - } - break; - default: - break; - } -} - -export {unwindWork, unwindInterruptedWork}; diff --git a/packages/react-reconciler/src/ReactFiberWorkLoop.new.js b/packages/react-reconciler/src/ReactFiberWorkLoop.new.js deleted file mode 100644 index fb5f1306a8715..0000000000000 --- a/packages/react-reconciler/src/ReactFiberWorkLoop.new.js +++ /dev/null @@ -1,4014 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import {REACT_STRICT_MODE_TYPE} from 'shared/ReactSymbols'; - -import type {Wakeable, Thenable} from 'shared/ReactTypes'; -import type {Fiber, FiberRoot} from './ReactInternalTypes'; -import type {Lanes, Lane} from './ReactFiberLane.new'; -import type { - SuspenseProps, - SuspenseState, -} from './ReactFiberSuspenseComponent.new'; -import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new'; -import type {EventPriority} from './ReactEventPriorities.new'; -import type { - PendingTransitionCallbacks, - PendingBoundaries, - Transition, - TransitionAbort, -} from './ReactFiberTracingMarkerComponent.new'; -import type {OffscreenInstance} from './ReactFiberOffscreenComponent'; - -import { - warnAboutDeprecatedLifecycles, - replayFailedUnitOfWorkWithInvokeGuardedCallback, - enableCreateEventHandleAPI, - enableProfilerTimer, - enableProfilerCommitHooks, - enableProfilerNestedUpdatePhase, - enableProfilerNestedUpdateScheduledHook, - deferRenderPhaseUpdateToNextBatch, - enableDebugTracing, - enableSchedulingProfiler, - disableSchedulerTimeoutInWorkLoop, - skipUnmountedBoundaries, - enableUpdaterTracking, - enableCache, - enableTransitionTracing, - useModernStrictMode, -} from 'shared/ReactFeatureFlags'; -import ReactSharedInternals from 'shared/ReactSharedInternals'; -import is from 'shared/objectIs'; - -import { - // Aliased because `act` will override and push to an internal queue - scheduleCallback as Scheduler_scheduleCallback, - cancelCallback as Scheduler_cancelCallback, - shouldYield, - requestPaint, - now, - ImmediatePriority as ImmediateSchedulerPriority, - UserBlockingPriority as UserBlockingSchedulerPriority, - NormalPriority as NormalSchedulerPriority, - IdlePriority as IdleSchedulerPriority, -} from './Scheduler'; -import { - flushSyncCallbacks, - flushSyncCallbacksOnlyInLegacyMode, - scheduleSyncCallback, - scheduleLegacySyncCallback, -} from './ReactFiberSyncTaskQueue.new'; -import { - logCommitStarted, - logCommitStopped, - logLayoutEffectsStarted, - logLayoutEffectsStopped, - logPassiveEffectsStarted, - logPassiveEffectsStopped, - logRenderStarted, - logRenderStopped, -} from './DebugTracing'; - -import { - resetAfterCommit, - scheduleTimeout, - cancelTimeout, - noTimeout, - afterActiveInstanceBlur, - getCurrentEventPriority, - supportsMicrotasks, - errorHydratingContainer, - scheduleMicrotask, - prepareRendererToRender, - resetRendererAfterRender, -} from './ReactFiberHostConfig'; - -import { - createWorkInProgress, - assignFiberPropertiesInDEV, - resetWorkInProgress, -} from './ReactFiber.new'; -import {isRootDehydrated} from './ReactFiberShellHydration'; -import {didSuspendOrErrorWhileHydratingDEV} from './ReactFiberHydrationContext.new'; -import { - NoMode, - ProfileMode, - ConcurrentMode, - StrictLegacyMode, - StrictEffectsMode, -} from './ReactTypeOfMode'; -import { - HostRoot, - IndeterminateComponent, - ClassComponent, - SuspenseComponent, - SuspenseListComponent, - OffscreenComponent, - FunctionComponent, - ForwardRef, - MemoComponent, - SimpleMemoComponent, - Profiler, -} from './ReactWorkTags'; -import {ConcurrentRoot, LegacyRoot} from './ReactRootTags'; -import type {Flags} from './ReactFiberFlags'; -import { - NoFlags, - Incomplete, - StoreConsistency, - HostEffectMask, - ForceClientRender, - BeforeMutationMask, - MutationMask, - LayoutMask, - PassiveMask, - PlacementDEV, - Visibility, - MountPassiveDev, - MountLayoutDev, -} from './ReactFiberFlags'; -import { - NoLanes, - NoLane, - SyncLane, - NoTimestamp, - claimNextTransitionLane, - claimNextRetryLane, - includesSyncLane, - isSubsetOfLanes, - mergeLanes, - removeLanes, - pickArbitraryLane, - includesNonIdleWork, - includesOnlyRetries, - includesOnlyTransitions, - includesBlockingLane, - includesExpiredLane, - getNextLanes, - markStarvedLanesAsExpired, - getLanesToRetrySynchronouslyOnError, - getMostRecentEventTime, - markRootUpdated, - markRootSuspended as markRootSuspended_dontCallThisOneDirectly, - markRootPinged, - markRootEntangled, - markRootFinished, - getHighestPriorityLane, - addFiberToLanesMap, - movePendingFibersToMemoized, - addTransitionToLanesMap, - getTransitionsForLanes, -} from './ReactFiberLane.new'; -import { - DiscreteEventPriority, - ContinuousEventPriority, - DefaultEventPriority, - IdleEventPriority, - getCurrentUpdatePriority, - setCurrentUpdatePriority, - lowerEventPriority, - lanesToEventPriority, -} from './ReactEventPriorities.new'; -import {requestCurrentTransition, NoTransition} from './ReactFiberTransition'; -import { - SelectiveHydrationException, - beginWork as originalBeginWork, - replayFunctionComponent, -} from './ReactFiberBeginWork.new'; -import {completeWork} from './ReactFiberCompleteWork.new'; -import {unwindWork, unwindInterruptedWork} from './ReactFiberUnwindWork.new'; -import { - throwException, - createRootErrorUpdate, - createClassErrorUpdate, -} from './ReactFiberThrow.new'; -import { - commitBeforeMutationEffects, - commitLayoutEffects, - commitMutationEffects, - commitPassiveEffectDurations, - commitPassiveMountEffects, - commitPassiveUnmountEffects, - disappearLayoutEffects, - reconnectPassiveEffects, - reappearLayoutEffects, - disconnectPassiveEffect, - reportUncaughtErrorInDEV, - invokeLayoutEffectMountInDEV, - invokePassiveEffectMountInDEV, - invokeLayoutEffectUnmountInDEV, - invokePassiveEffectUnmountInDEV, -} from './ReactFiberCommitWork.new'; -import {enqueueUpdate} from './ReactFiberClassUpdateQueue.new'; -import {resetContextDependencies} from './ReactFiberNewContext.new'; -import { - resetHooksAfterThrow, - resetHooksOnUnwind, - ContextOnlyDispatcher, -} from './ReactFiberHooks.new'; -import {DefaultCacheDispatcher} from './ReactFiberCache.new'; -import { - createCapturedValueAtFiber, - type CapturedValue, -} from './ReactCapturedValue'; -import { - enqueueConcurrentRenderForLane, - finishQueueingConcurrentUpdates, - getConcurrentlyUpdatedLanes, -} from './ReactFiberConcurrentUpdates.new'; - -import { - markNestedUpdateScheduled, - recordCommitTime, - resetNestedUpdateFlag, - startProfilerTimer, - stopProfilerTimerIfRunningAndRecordDelta, - syncNestedUpdateFlag, -} from './ReactProfilerTimer.new'; - -// DEV stuff -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import ReactStrictModeWarnings from './ReactStrictModeWarnings.new'; -import { - isRendering as ReactCurrentDebugFiberIsRenderingInDEV, - current as ReactCurrentFiberCurrent, - resetCurrentFiber as resetCurrentDebugFiberInDEV, - setCurrentFiber as setCurrentDebugFiberInDEV, -} from './ReactCurrentFiber'; -import { - invokeGuardedCallback, - hasCaughtError, - clearCaughtError, -} from 'shared/ReactErrorUtils'; -import { - isDevToolsPresent, - markCommitStarted, - markCommitStopped, - markComponentRenderStopped, - markComponentSuspended, - markComponentErrored, - markLayoutEffectsStarted, - markLayoutEffectsStopped, - markPassiveEffectsStarted, - markPassiveEffectsStopped, - markRenderStarted, - markRenderYielded, - markRenderStopped, - onCommitRoot as onCommitRootDevTools, - onPostCommitRoot as onPostCommitRootDevTools, -} from './ReactFiberDevToolsHook.new'; -import {onCommitRoot as onCommitRootTestSelector} from './ReactTestSelectors'; -import {releaseCache} from './ReactFiberCacheComponent.new'; -import { - isLegacyActEnvironment, - isConcurrentActEnvironment, -} from './ReactFiberAct.new'; -import {processTransitionCallbacks} from './ReactFiberTracingMarkerComponent.new'; -import { - SuspenseException, - getSuspendedThenable, - isThenableResolved, -} from './ReactFiberThenable.new'; -import {schedulePostPaintCallback} from './ReactPostPaintCallback'; -import { - getSuspenseHandler, - isBadSuspenseFallback, -} from './ReactFiberSuspenseContext.new'; -import {resolveDefaultProps} from './ReactFiberLazyComponent.new'; - -const ceil = Math.ceil; - -const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - -const { - ReactCurrentDispatcher, - ReactCurrentCache, - ReactCurrentOwner, - ReactCurrentBatchConfig, - ReactCurrentActQueue, -} = ReactSharedInternals; - -type ExecutionContext = number; - -export const NoContext = /* */ 0b000; -const BatchedContext = /* */ 0b001; -export const RenderContext = /* */ 0b010; -export const CommitContext = /* */ 0b100; - -type RootExitStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6; -const RootInProgress = 0; -const RootFatalErrored = 1; -const RootErrored = 2; -const RootSuspended = 3; -const RootSuspendedWithDelay = 4; -const RootCompleted = 5; -const RootDidNotComplete = 6; - -// Describes where we are in the React execution stack -let executionContext: ExecutionContext = NoContext; -// The root we're working on -let workInProgressRoot: FiberRoot | null = null; -// The fiber we're working on -let workInProgress: Fiber | null = null; -// The lanes we're rendering -let workInProgressRootRenderLanes: Lanes = NoLanes; - -opaque type SuspendedReason = 0 | 1 | 2 | 3 | 4 | 5 | 6; -const NotSuspended: SuspendedReason = 0; -const SuspendedOnError: SuspendedReason = 1; -const SuspendedOnData: SuspendedReason = 2; -const SuspendedOnImmediate: SuspendedReason = 3; -const SuspendedOnDeprecatedThrowPromise: SuspendedReason = 4; -const SuspendedAndReadyToUnwind: SuspendedReason = 5; -const SuspendedOnHydration: SuspendedReason = 6; - -// When this is true, the work-in-progress fiber just suspended (or errored) and -// we've yet to unwind the stack. In some cases, we may yield to the main thread -// after this happens. If the fiber is pinged before we resume, we can retry -// immediately instead of unwinding the stack. -let workInProgressSuspendedReason: SuspendedReason = NotSuspended; -let workInProgressThrownValue: mixed = null; - -// Whether a ping listener was attached during this render. This is slightly -// different that whether something suspended, because we don't add multiple -// listeners to a promise we've already seen (per root and lane). -let workInProgressRootDidAttachPingListener: boolean = false; - -// A contextual version of workInProgressRootRenderLanes. It is a superset of -// the lanes that we started working on at the root. When we enter a subtree -// that is currently hidden, we add the lanes that would have committed if -// the hidden tree hadn't been deferred. This is modified by the -// HiddenContext module. -// -// Most things in the work loop should deal with workInProgressRootRenderLanes. -// Most things in begin/complete phases should deal with renderLanes. -export let renderLanes: Lanes = NoLanes; - -// Whether to root completed, errored, suspended, etc. -let workInProgressRootExitStatus: RootExitStatus = RootInProgress; -// A fatal error, if one is thrown -let workInProgressRootFatalError: mixed = null; -// The work left over by components that were visited during this render. Only -// includes unprocessed updates, not work in bailed out children. -let workInProgressRootSkippedLanes: Lanes = NoLanes; -// Lanes that were updated (in an interleaved event) during this render. -let workInProgressRootInterleavedUpdatedLanes: Lanes = NoLanes; -// Lanes that were updated during the render phase (*not* an interleaved event). -let workInProgressRootRenderPhaseUpdatedLanes: Lanes = NoLanes; -// Lanes that were pinged (in an interleaved event) during this render. -let workInProgressRootPingedLanes: Lanes = NoLanes; -// Errors that are thrown during the render phase. -let workInProgressRootConcurrentErrors: Array< - CapturedValue, -> | null = null; -// These are errors that we recovered from without surfacing them to the UI. -// We will log them once the tree commits. -let workInProgressRootRecoverableErrors: Array< - CapturedValue, -> | null = null; - -// The most recent time we committed a fallback. This lets us ensure a train -// model where we don't commit new loading states in too quick succession. -let globalMostRecentFallbackTime: number = 0; -const FALLBACK_THROTTLE_MS: number = 500; - -// The absolute time for when we should start giving up on rendering -// more and prefer CPU suspense heuristics instead. -let workInProgressRootRenderTargetTime: number = Infinity; -// How long a render is supposed to take before we start following CPU -// suspense heuristics and opt out of rendering more content. -const RENDER_TIMEOUT_MS = 500; - -let workInProgressTransitions: Array | null = null; -export function getWorkInProgressTransitions(): null | Array { - return workInProgressTransitions; -} - -let currentPendingTransitionCallbacks: PendingTransitionCallbacks | null = null; -let currentEndTime: number | null = null; - -export function addTransitionStartCallbackToPendingTransition( - transition: Transition, -) { - if (enableTransitionTracing) { - if (currentPendingTransitionCallbacks === null) { - currentPendingTransitionCallbacks = { - transitionStart: [], - transitionProgress: null, - transitionComplete: null, - markerProgress: null, - markerIncomplete: null, - markerComplete: null, - }; - } - - if (currentPendingTransitionCallbacks.transitionStart === null) { - currentPendingTransitionCallbacks.transitionStart = []; - } - - currentPendingTransitionCallbacks.transitionStart.push(transition); - } -} - -export function addMarkerProgressCallbackToPendingTransition( - markerName: string, - transitions: Set, - pendingBoundaries: PendingBoundaries, -) { - if (enableTransitionTracing) { - if (currentPendingTransitionCallbacks === null) { - currentPendingTransitionCallbacks = ({ - transitionStart: null, - transitionProgress: null, - transitionComplete: null, - markerProgress: new Map(), - markerIncomplete: null, - markerComplete: null, - }: PendingTransitionCallbacks); - } - - if (currentPendingTransitionCallbacks.markerProgress === null) { - currentPendingTransitionCallbacks.markerProgress = new Map(); - } - - currentPendingTransitionCallbacks.markerProgress.set(markerName, { - pendingBoundaries, - transitions, - }); - } -} - -export function addMarkerIncompleteCallbackToPendingTransition( - markerName: string, - transitions: Set, - aborts: Array, -) { - if (enableTransitionTracing) { - if (currentPendingTransitionCallbacks === null) { - currentPendingTransitionCallbacks = { - transitionStart: null, - transitionProgress: null, - transitionComplete: null, - markerProgress: null, - markerIncomplete: new Map(), - markerComplete: null, - }; - } - - if (currentPendingTransitionCallbacks.markerIncomplete === null) { - currentPendingTransitionCallbacks.markerIncomplete = new Map(); - } - - currentPendingTransitionCallbacks.markerIncomplete.set(markerName, { - transitions, - aborts, - }); - } -} - -export function addMarkerCompleteCallbackToPendingTransition( - markerName: string, - transitions: Set, -) { - if (enableTransitionTracing) { - if (currentPendingTransitionCallbacks === null) { - currentPendingTransitionCallbacks = { - transitionStart: null, - transitionProgress: null, - transitionComplete: null, - markerProgress: null, - markerIncomplete: null, - markerComplete: new Map(), - }; - } - - if (currentPendingTransitionCallbacks.markerComplete === null) { - currentPendingTransitionCallbacks.markerComplete = new Map(); - } - - currentPendingTransitionCallbacks.markerComplete.set( - markerName, - transitions, - ); - } -} - -export function addTransitionProgressCallbackToPendingTransition( - transition: Transition, - boundaries: PendingBoundaries, -) { - if (enableTransitionTracing) { - if (currentPendingTransitionCallbacks === null) { - currentPendingTransitionCallbacks = { - transitionStart: null, - transitionProgress: new Map(), - transitionComplete: null, - markerProgress: null, - markerIncomplete: null, - markerComplete: null, - }; - } - - if (currentPendingTransitionCallbacks.transitionProgress === null) { - currentPendingTransitionCallbacks.transitionProgress = new Map(); - } - - currentPendingTransitionCallbacks.transitionProgress.set( - transition, - boundaries, - ); - } -} - -export function addTransitionCompleteCallbackToPendingTransition( - transition: Transition, -) { - if (enableTransitionTracing) { - if (currentPendingTransitionCallbacks === null) { - currentPendingTransitionCallbacks = { - transitionStart: null, - transitionProgress: null, - transitionComplete: [], - markerProgress: null, - markerIncomplete: null, - markerComplete: null, - }; - } - - if (currentPendingTransitionCallbacks.transitionComplete === null) { - currentPendingTransitionCallbacks.transitionComplete = []; - } - - currentPendingTransitionCallbacks.transitionComplete.push(transition); - } -} - -function resetRenderTimer() { - workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS; -} - -export function getRenderTargetTime(): number { - return workInProgressRootRenderTargetTime; -} - -let hasUncaughtError = false; -let firstUncaughtError = null; -let legacyErrorBoundariesThatAlreadyFailed: Set | null = null; - -// Only used when enableProfilerNestedUpdateScheduledHook is true; -// to track which root is currently committing layout effects. -let rootCommittingMutationOrLayoutEffects: FiberRoot | null = null; - -let rootDoesHavePassiveEffects: boolean = false; -let rootWithPendingPassiveEffects: FiberRoot | null = null; -let pendingPassiveEffectsLanes: Lanes = NoLanes; -let pendingPassiveProfilerEffects: Array = []; -let pendingPassiveEffectsRemainingLanes: Lanes = NoLanes; -let pendingPassiveTransitions: Array | null = null; - -// Use these to prevent an infinite loop of nested updates -const NESTED_UPDATE_LIMIT = 50; -let nestedUpdateCount: number = 0; -let rootWithNestedUpdates: FiberRoot | null = null; -let isFlushingPassiveEffects = false; -let didScheduleUpdateDuringPassiveEffects = false; - -const NESTED_PASSIVE_UPDATE_LIMIT = 50; -let nestedPassiveUpdateCount: number = 0; -let rootWithPassiveNestedUpdates: FiberRoot | null = null; - -// If two updates are scheduled within the same event, we should treat their -// event times as simultaneous, even if the actual clock time has advanced -// between the first and second call. -let currentEventTime: number = NoTimestamp; -let currentEventTransitionLane: Lanes = NoLanes; - -let isRunningInsertionEffect = false; - -export function getWorkInProgressRoot(): FiberRoot | null { - return workInProgressRoot; -} - -export function getWorkInProgressRootRenderLanes(): Lanes { - return workInProgressRootRenderLanes; -} - -export function requestEventTime(): number { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - // We're inside React, so it's fine to read the actual time. - return now(); - } - // We're not inside React, so we may be in the middle of a browser event. - if (currentEventTime !== NoTimestamp) { - // Use the same start time for all updates until we enter React again. - return currentEventTime; - } - // This is the first update since React yielded. Compute a new start time. - currentEventTime = now(); - return currentEventTime; -} - -export function getCurrentTime(): number { - return now(); -} - -export function requestUpdateLane(fiber: Fiber): Lane { - // Special cases - const mode = fiber.mode; - if ((mode & ConcurrentMode) === NoMode) { - return (SyncLane: Lane); - } else if ( - !deferRenderPhaseUpdateToNextBatch && - (executionContext & RenderContext) !== NoContext && - workInProgressRootRenderLanes !== NoLanes - ) { - // This is a render phase update. These are not officially supported. The - // old behavior is to give this the same "thread" (lanes) as - // whatever is currently rendering. So if you call `setState` on a component - // that happens later in the same render, it will flush. Ideally, we want to - // remove the special case and treat them as if they came from an - // interleaved event. Regardless, this pattern is not officially supported. - // This behavior is only a fallback. The flag only exists until we can roll - // out the setState warning, since existing code might accidentally rely on - // the current behavior. - return pickArbitraryLane(workInProgressRootRenderLanes); - } - - const isTransition = requestCurrentTransition() !== NoTransition; - if (isTransition) { - if (__DEV__ && ReactCurrentBatchConfig.transition !== null) { - const transition = ReactCurrentBatchConfig.transition; - if (!transition._updatedFibers) { - transition._updatedFibers = new Set(); - } - - transition._updatedFibers.add(fiber); - } - // The algorithm for assigning an update to a lane should be stable for all - // updates at the same priority within the same event. To do this, the - // inputs to the algorithm must be the same. - // - // The trick we use is to cache the first of each of these inputs within an - // event. Then reset the cached values once we can be sure the event is - // over. Our heuristic for that is whenever we enter a concurrent work loop. - if (currentEventTransitionLane === NoLane) { - // All transitions within the same event are assigned the same lane. - currentEventTransitionLane = claimNextTransitionLane(); - } - return currentEventTransitionLane; - } - - // Updates originating inside certain React methods, like flushSync, have - // their priority set by tracking it with a context variable. - // - // The opaque type returned by the host config is internally a lane, so we can - // use that directly. - // TODO: Move this type conversion to the event priority module. - const updateLane: Lane = (getCurrentUpdatePriority(): any); - if (updateLane !== NoLane) { - return updateLane; - } - - // This update originated outside React. Ask the host environment for an - // appropriate priority, based on the type of event. - // - // The opaque type returned by the host config is internally a lane, so we can - // use that directly. - // TODO: Move this type conversion to the event priority module. - const eventLane: Lane = (getCurrentEventPriority(): any); - return eventLane; -} - -function requestRetryLane(fiber: Fiber) { - // This is a fork of `requestUpdateLane` designed specifically for Suspense - // "retries" — a special update that attempts to flip a Suspense boundary - // from its placeholder state to its primary/resolved state. - - // Special cases - const mode = fiber.mode; - if ((mode & ConcurrentMode) === NoMode) { - return (SyncLane: Lane); - } - - return claimNextRetryLane(); -} - -export function scheduleUpdateOnFiber( - root: FiberRoot, - fiber: Fiber, - lane: Lane, - eventTime: number, -) { - if (__DEV__) { - if (isRunningInsertionEffect) { - console.error('useInsertionEffect must not schedule updates.'); - } - } - - if (__DEV__) { - if (isFlushingPassiveEffects) { - didScheduleUpdateDuringPassiveEffects = true; - } - } - - // Check if the work loop is currently suspended and waiting for data to - // finish loading. - if ( - workInProgressSuspendedReason === SuspendedOnData && - root === workInProgressRoot - ) { - // The incoming update might unblock the current render. Interrupt the - // current attempt and restart from the top. - prepareFreshStack(root, NoLanes); - markRootSuspended(root, workInProgressRootRenderLanes); - } - - // Mark that the root has a pending update. - markRootUpdated(root, lane, eventTime); - - if ( - (executionContext & RenderContext) !== NoLanes && - root === workInProgressRoot - ) { - // This update was dispatched during the render phase. This is a mistake - // if the update originates from user space (with the exception of local - // hook updates, which are handled differently and don't reach this - // function), but there are some internal React features that use this as - // an implementation detail, like selective hydration. - warnAboutRenderPhaseUpdatesInDEV(fiber); - - // Track lanes that were updated during the render phase - workInProgressRootRenderPhaseUpdatedLanes = mergeLanes( - workInProgressRootRenderPhaseUpdatedLanes, - lane, - ); - } else { - // This is a normal update, scheduled from outside the render phase. For - // example, during an input event. - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - addFiberToLanesMap(root, fiber, lane); - } - } - - warnIfUpdatesNotWrappedWithActDEV(fiber); - - if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) { - if ( - (executionContext & CommitContext) !== NoContext && - root === rootCommittingMutationOrLayoutEffects - ) { - if (fiber.mode & ProfileMode) { - let current: null | Fiber = fiber; - while (current !== null) { - if (current.tag === Profiler) { - const {id, onNestedUpdateScheduled} = current.memoizedProps; - if (typeof onNestedUpdateScheduled === 'function') { - onNestedUpdateScheduled(id); - } - } - current = current.return; - } - } - } - } - - if (enableTransitionTracing) { - const transition = ReactCurrentBatchConfig.transition; - if (transition !== null && transition.name != null) { - if (transition.startTime === -1) { - transition.startTime = now(); - } - - addTransitionToLanesMap(root, transition, lane); - } - } - - if (root === workInProgressRoot) { - // Received an update to a tree that's in the middle of rendering. Mark - // that there was an interleaved update work on this root. Unless the - // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render - // phase update. In that case, we don't treat render phase updates as if - // they were interleaved, for backwards compat reasons. - if ( - deferRenderPhaseUpdateToNextBatch || - (executionContext & RenderContext) === NoContext - ) { - workInProgressRootInterleavedUpdatedLanes = mergeLanes( - workInProgressRootInterleavedUpdatedLanes, - lane, - ); - } - if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - // The root already suspended with a delay, which means this render - // definitely won't finish. Since we have a new update, let's mark it as - // suspended now, right before marking the incoming update. This has the - // effect of interrupting the current render and switching to the update. - // TODO: Make sure this doesn't override pings that happen while we've - // already started rendering. - markRootSuspended(root, workInProgressRootRenderLanes); - } - } - - ensureRootIsScheduled(root, eventTime); - if ( - lane === SyncLane && - executionContext === NoContext && - (fiber.mode & ConcurrentMode) === NoMode && - // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !(__DEV__ && ReactCurrentActQueue.isBatchingLegacy) - ) { - // Flush the synchronous work now, unless we're already working or inside - // a batch. This is intentionally inside scheduleUpdateOnFiber instead of - // scheduleCallbackForFiber to preserve the ability to schedule a callback - // without immediately flushing it. We only do this for user-initiated - // updates, to preserve historical behavior of legacy mode. - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } -} - -export function scheduleInitialHydrationOnRoot( - root: FiberRoot, - lane: Lane, - eventTime: number, -) { - // This is a special fork of scheduleUpdateOnFiber that is only used to - // schedule the initial hydration of a root that has just been created. Most - // of the stuff in scheduleUpdateOnFiber can be skipped. - // - // The main reason for this separate path, though, is to distinguish the - // initial children from subsequent updates. In fully client-rendered roots - // (createRoot instead of hydrateRoot), all top-level renders are modeled as - // updates, but hydration roots are special because the initial render must - // match what was rendered on the server. - const current = root.current; - current.lanes = lane; - markRootUpdated(root, lane, eventTime); - ensureRootIsScheduled(root, eventTime); -} - -export function isUnsafeClassRenderPhaseUpdate(fiber: Fiber): boolean { - // Check if this is a render phase update. Only called by class components, - // which special (deprecated) behavior for UNSAFE_componentWillReceive props. - return ( - // TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We - // decided not to enable it. - (!deferRenderPhaseUpdateToNextBatch || - (fiber.mode & ConcurrentMode) === NoMode) && - (executionContext & RenderContext) !== NoContext - ); -} - -// Use this function to schedule a task for a root. There's only one task per -// root; if a task was already scheduled, we'll check to make sure the priority -// of the existing task is the same as the priority of the next level that the -// root has work on. This function is called on every update, and right before -// exiting a task. -function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { - const existingCallbackNode = root.callbackNode; - - // Check if any lanes are being starved by other work. If so, mark them as - // expired so we know to work on those next. - markStarvedLanesAsExpired(root, currentTime); - - // Determine the next lanes to work on, and their priority. - const nextLanes = getNextLanes( - root, - root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes, - ); - - if (nextLanes === NoLanes) { - // Special case: There's nothing to work on. - if (existingCallbackNode !== null) { - cancelCallback(existingCallbackNode); - } - root.callbackNode = null; - root.callbackPriority = NoLane; - return; - } - - // We use the highest priority lane to represent the priority of the callback. - const newCallbackPriority = getHighestPriorityLane(nextLanes); - - // Check if there's an existing task. We may be able to reuse it. - const existingCallbackPriority = root.callbackPriority; - if ( - existingCallbackPriority === newCallbackPriority && - // Special case related to `act`. If the currently scheduled task is a - // Scheduler task, rather than an `act` task, cancel it and re-scheduled - // on the `act` queue. - !( - __DEV__ && - ReactCurrentActQueue.current !== null && - existingCallbackNode !== fakeActCallbackNode - ) - ) { - if (__DEV__) { - // If we're going to re-use an existing task, it needs to exist. - // Assume that discrete update microtasks are non-cancellable and null. - // TODO: Temporary until we confirm this warning is not fired. - if ( - existingCallbackNode == null && - !includesSyncLane(existingCallbackPriority) - ) { - console.error( - 'Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.', - ); - } - } - // The priority hasn't changed. We can reuse the existing task. Exit. - return; - } - - if (existingCallbackNode != null) { - // Cancel the existing callback. We'll schedule a new one below. - cancelCallback(existingCallbackNode); - } - - // Schedule a new callback. - let newCallbackNode; - if (includesSyncLane(newCallbackPriority)) { - // Special case: Sync React callbacks are scheduled on a special - // internal queue - if (root.tag === LegacyRoot) { - if (__DEV__ && ReactCurrentActQueue.isBatchingLegacy !== null) { - ReactCurrentActQueue.didScheduleLegacyUpdate = true; - } - scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); - } else { - scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); - } - if (supportsMicrotasks) { - // Flush the queue in a microtask. - if (__DEV__ && ReactCurrentActQueue.current !== null) { - // Inside `act`, use our internal `act` queue so that these get flushed - // at the end of the current scope even when using the sync version - // of `act`. - ReactCurrentActQueue.current.push(flushSyncCallbacks); - } else { - scheduleMicrotask(() => { - // In Safari, appending an iframe forces microtasks to run. - // https://github.com/facebook/react/issues/22459 - // We don't support running callbacks in the middle of render - // or commit so we need to check against that. - if ( - (executionContext & (RenderContext | CommitContext)) === - NoContext - ) { - // Note that this would still prematurely flush the callbacks - // if this happens outside render or commit phase (e.g. in an event). - flushSyncCallbacks(); - } - }); - } - } else { - // Flush the queue in an Immediate task. - scheduleCallback(ImmediateSchedulerPriority, flushSyncCallbacks); - } - newCallbackNode = null; - } else { - let schedulerPriorityLevel; - switch (lanesToEventPriority(nextLanes)) { - case DiscreteEventPriority: - schedulerPriorityLevel = ImmediateSchedulerPriority; - break; - case ContinuousEventPriority: - schedulerPriorityLevel = UserBlockingSchedulerPriority; - break; - case DefaultEventPriority: - schedulerPriorityLevel = NormalSchedulerPriority; - break; - case IdleEventPriority: - schedulerPriorityLevel = IdleSchedulerPriority; - break; - default: - schedulerPriorityLevel = NormalSchedulerPriority; - break; - } - newCallbackNode = scheduleCallback( - schedulerPriorityLevel, - performConcurrentWorkOnRoot.bind(null, root), - ); - } - - root.callbackPriority = newCallbackPriority; - root.callbackNode = newCallbackNode; -} - -// This is the entry point for every concurrent task, i.e. anything that -// goes through Scheduler. -function performConcurrentWorkOnRoot(root, didTimeout) { - if (enableProfilerTimer && enableProfilerNestedUpdatePhase) { - resetNestedUpdateFlag(); - } - - // Since we know we're in a React event, we can clear the current - // event time. The next update will compute a new event time. - currentEventTime = NoTimestamp; - currentEventTransitionLane = NoLanes; - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } - - // Flush any pending passive effects before deciding which lanes to work on, - // in case they schedule additional work. - const originalCallbackNode = root.callbackNode; - const didFlushPassiveEffects = flushPassiveEffects(); - if (didFlushPassiveEffects) { - // Something in the passive effect phase may have canceled the current task. - // Check if the task node for this root was changed. - if (root.callbackNode !== originalCallbackNode) { - // The current task was canceled. Exit. We don't need to call - // `ensureRootIsScheduled` because the check above implies either that - // there's a new task, or that there's no remaining work on this root. - return null; - } else { - // Current task was not canceled. Continue. - } - } - - // Determine the next lanes to work on, using the fields stored - // on the root. - let lanes = getNextLanes( - root, - root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes, - ); - if (lanes === NoLanes) { - // Defensive coding. This is never expected to happen. - return null; - } - - // We disable time-slicing in some cases: if the work has been CPU-bound - // for too long ("expired" work, to prevent starvation), or we're in - // sync-updates-by-default mode. - // TODO: We only check `didTimeout` defensively, to account for a Scheduler - // bug we're still investigating. Once the bug in Scheduler is fixed, - // we can remove this, since we track expiration ourselves. - const shouldTimeSlice = - !includesBlockingLane(root, lanes) && - !includesExpiredLane(root, lanes) && - (disableSchedulerTimeoutInWorkLoop || !didTimeout); - let exitStatus = shouldTimeSlice - ? renderRootConcurrent(root, lanes) - : renderRootSync(root, lanes); - if (exitStatus !== RootInProgress) { - if (exitStatus === RootErrored) { - // If something threw an error, try rendering one more time. We'll - // render synchronously to block concurrent data mutations, and we'll - // includes all pending updates are included. If it still fails after - // the second attempt, we'll give up and commit the resulting tree. - const originallyAttemptedLanes = lanes; - const errorRetryLanes = getLanesToRetrySynchronouslyOnError( - root, - originallyAttemptedLanes, - ); - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes, - ); - } - } - if (exitStatus === RootFatalErrored) { - const fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended(root, lanes); - ensureRootIsScheduled(root, now()); - throw fatalError; - } - - if (exitStatus === RootDidNotComplete) { - // The render unwound without completing the tree. This happens in special - // cases where need to exit the current render without producing a - // consistent tree or committing. - markRootSuspended(root, lanes); - } else { - // The render completed. - - // Check if this render may have yielded to a concurrent event, and if so, - // confirm that any newly rendered stores are consistent. - // TODO: It's possible that even a concurrent render may never have yielded - // to the main thread, if it was fast enough, or if it expired. We could - // skip the consistency check in that case, too. - const renderWasConcurrent = !includesBlockingLane(root, lanes); - const finishedWork: Fiber = (root.current.alternate: any); - if ( - renderWasConcurrent && - !isRenderConsistentWithExternalStores(finishedWork) - ) { - // A store was mutated in an interleaved event. Render again, - // synchronously, to block further mutations. - exitStatus = renderRootSync(root, lanes); - - // We need to check again if something threw - if (exitStatus === RootErrored) { - const originallyAttemptedLanes = lanes; - const errorRetryLanes = getLanesToRetrySynchronouslyOnError( - root, - originallyAttemptedLanes, - ); - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes, - ); - // We assume the tree is now consistent because we didn't yield to any - // concurrent events. - } - } - if (exitStatus === RootFatalErrored) { - const fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended(root, lanes); - ensureRootIsScheduled(root, now()); - throw fatalError; - } - - // FIXME: Need to check for RootDidNotComplete again. The factoring here - // isn't ideal. - } - - // We now have a consistent tree. The next step is either to commit it, - // or, if something suspended, wait to commit it after a timeout. - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - finishConcurrentRender(root, exitStatus, lanes); - } - } - - ensureRootIsScheduled(root, now()); - if (root.callbackNode === originalCallbackNode) { - // The task node scheduled for this root is the same one that's - // currently executed. Need to return a continuation. - if ( - workInProgressSuspendedReason === SuspendedOnData && - workInProgressRoot === root - ) { - // Special case: The work loop is currently suspended and waiting for - // data to resolve. Unschedule the current task. - // - // TODO: The factoring is a little weird. Arguably this should be checked - // in ensureRootIsScheduled instead. I went back and forth, not totally - // sure yet. - root.callbackPriority = NoLane; - root.callbackNode = null; - return null; - } - return performConcurrentWorkOnRoot.bind(null, root); - } - return null; -} - -function recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes, -) { - // If an error occurred during hydration, discard server response and fall - // back to client side render. - - // Before rendering again, save the errors from the previous attempt. - const errorsFromFirstAttempt = workInProgressRootConcurrentErrors; - - const wasRootDehydrated = isRootDehydrated(root); - if (wasRootDehydrated) { - // The shell failed to hydrate. Set a flag to force a client rendering - // during the next attempt. To do this, we call prepareFreshStack now - // to create the root work-in-progress fiber. This is a bit weird in terms - // of factoring, because it relies on renderRootSync not calling - // prepareFreshStack again in the call below, which happens because the - // root and lanes haven't changed. - // - // TODO: I think what we should do is set ForceClientRender inside - // throwException, like we do for nested Suspense boundaries. The reason - // it's here instead is so we can switch to the synchronous work loop, too. - // Something to consider for a future refactor. - const rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); - rootWorkInProgress.flags |= ForceClientRender; - if (__DEV__) { - errorHydratingContainer(root.containerInfo); - } - } - - const exitStatus = renderRootSync(root, errorRetryLanes); - if (exitStatus !== RootErrored) { - // Successfully finished rendering on retry - - if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) { - // During the synchronous render, we attached additional ping listeners. - // This is highly suggestive of an uncached promise (though it's not the - // only reason this would happen). If it was an uncached promise, then - // it may have masked a downstream error from ocurring without actually - // fixing it. Example: - // - // use(Promise.resolve('uncached')) - // throw new Error('Oops!') - // - // When this happens, there's a conflict between blocking potential - // concurrent data races and unwrapping uncached promise values. We - // have to choose one or the other. Because the data race recovery is - // a last ditch effort, we'll disable it. - root.errorRecoveryDisabledLanes = mergeLanes( - root.errorRecoveryDisabledLanes, - originallyAttemptedLanes, - ); - - // Mark the current render as suspended and force it to restart. Once - // these lanes finish successfully, we'll re-enable the error recovery - // mechanism for subsequent updates. - workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes; - return RootSuspendedWithDelay; - } - - // The errors from the failed first attempt have been recovered. Add - // them to the collection of recoverable errors. We'll log them in the - // commit phase. - const errorsFromSecondAttempt = workInProgressRootRecoverableErrors; - workInProgressRootRecoverableErrors = errorsFromFirstAttempt; - // The errors from the second attempt should be queued after the errors - // from the first attempt, to preserve the causal sequence. - if (errorsFromSecondAttempt !== null) { - queueRecoverableErrors(errorsFromSecondAttempt); - } - } else { - // The UI failed to recover. - } - return exitStatus; -} - -export function queueRecoverableErrors(errors: Array>) { - if (workInProgressRootRecoverableErrors === null) { - workInProgressRootRecoverableErrors = errors; - } else { - // $FlowFixMe[method-unbinding] - workInProgressRootRecoverableErrors.push.apply( - workInProgressRootRecoverableErrors, - errors, - ); - } -} - -function finishConcurrentRender(root, exitStatus, lanes) { - switch (exitStatus) { - case RootInProgress: - case RootFatalErrored: { - throw new Error('Root did not complete. This is a bug in React.'); - } - // Flow knows about invariant, so it complains if I add a break - // statement, but eslint doesn't know about invariant, so it complains - // if I do. eslint-disable-next-line no-fallthrough - case RootErrored: { - // We should have already attempted to retry this tree. If we reached - // this point, it errored again. Commit it. - commitRoot( - root, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - ); - break; - } - case RootSuspended: { - markRootSuspended(root, lanes); - - // We have an acceptable loading state. We need to figure out if we - // should immediately commit it or wait a bit. - - if ( - includesOnlyRetries(lanes) && - // do not delay if we're inside an act() scope - !shouldForceFlushFallbacksInDEV() - ) { - // This render only included retries, no updates. Throttle committing - // retries so that we don't show too many loading states too quickly. - const msUntilTimeout = - globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); - // Don't bother with a very short suspense time. - if (msUntilTimeout > 10) { - const nextLanes = getNextLanes(root, NoLanes); - if (nextLanes !== NoLanes) { - // There's additional work on this root. - break; - } - const suspendedLanes = root.suspendedLanes; - if (!isSubsetOfLanes(suspendedLanes, lanes)) { - // We should prefer to render the fallback of at the last - // suspended level. Ping the last suspended level to try - // rendering it again. - // FIXME: What if the suspended lanes are Idle? Should not restart. - const eventTime = requestEventTime(); - markRootPinged(root, suspendedLanes, eventTime); - break; - } - - // The render is suspended, it hasn't timed out, and there's no - // lower priority work to do. Instead of committing the fallback - // immediately, wait for more data to arrive. - root.timeoutHandle = scheduleTimeout( - commitRoot.bind( - null, - root, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - ), - msUntilTimeout, - ); - break; - } - } - // The work expired. Commit immediately. - commitRoot( - root, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - ); - break; - } - case RootSuspendedWithDelay: { - markRootSuspended(root, lanes); - - if (includesOnlyTransitions(lanes)) { - // This is a transition, so we should exit without committing a - // placeholder and without scheduling a timeout. Delay indefinitely - // until we receive more data. - break; - } - - if (!shouldForceFlushFallbacksInDEV()) { - // This is not a transition, but we did trigger an avoided state. - // Schedule a placeholder to display after a short delay, using the Just - // Noticeable Difference. - // TODO: Is the JND optimization worth the added complexity? If this is - // the only reason we track the event time, then probably not. - // Consider removing. - - const mostRecentEventTime = getMostRecentEventTime(root, lanes); - const eventTimeMs = mostRecentEventTime; - const timeElapsedMs = now() - eventTimeMs; - const msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; - - // Don't bother with a very short suspense time. - if (msUntilTimeout > 10) { - // Instead of committing the fallback immediately, wait for more data - // to arrive. - root.timeoutHandle = scheduleTimeout( - commitRoot.bind( - null, - root, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - ), - msUntilTimeout, - ); - break; - } - } - - // Commit the placeholder. - commitRoot( - root, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - ); - break; - } - case RootCompleted: { - // The work completed. Ready to commit. - commitRoot( - root, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - ); - break; - } - default: { - throw new Error('Unknown root exit status.'); - } - } -} - -function isRenderConsistentWithExternalStores(finishedWork: Fiber): boolean { - // Search the rendered tree for external store reads, and check whether the - // stores were mutated in a concurrent event. Intentionally using an iterative - // loop instead of recursion so we can exit early. - let node: Fiber = finishedWork; - while (true) { - if (node.flags & StoreConsistency) { - const updateQueue: FunctionComponentUpdateQueue | null = (node.updateQueue: any); - if (updateQueue !== null) { - const checks = updateQueue.stores; - if (checks !== null) { - for (let i = 0; i < checks.length; i++) { - const check = checks[i]; - const getSnapshot = check.getSnapshot; - const renderedValue = check.value; - try { - if (!is(getSnapshot(), renderedValue)) { - // Found an inconsistent store. - return false; - } - } catch (error) { - // If `getSnapshot` throws, return `false`. This will schedule - // a re-render, and the error will be rethrown during render. - return false; - } - } - } - } - } - const child = node.child; - if (node.subtreeFlags & StoreConsistency && child !== null) { - child.return = node; - node = child; - continue; - } - if (node === finishedWork) { - return true; - } - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return true; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - // Flow doesn't know this is unreachable, but eslint does - // eslint-disable-next-line no-unreachable - return true; -} - -function markRootSuspended(root, suspendedLanes) { - // When suspending, we should always exclude lanes that were pinged or (more - // rarely, since we try to avoid it) updated during the render phase. - // TODO: Lol maybe there's a better way to factor this besides this - // obnoxiously named function :) - suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); - suspendedLanes = removeLanes( - suspendedLanes, - workInProgressRootInterleavedUpdatedLanes, - ); - // $FlowFixMe[incompatible-call] found when upgrading Flow - markRootSuspended_dontCallThisOneDirectly(root, suspendedLanes); -} - -// This is the entry point for synchronous tasks that don't go -// through Scheduler -function performSyncWorkOnRoot(root) { - if (enableProfilerTimer && enableProfilerNestedUpdatePhase) { - syncNestedUpdateFlag(); - } - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } - - flushPassiveEffects(); - - let lanes = getNextLanes(root, NoLanes); - if (!includesSyncLane(lanes)) { - // There's no remaining sync work left. - ensureRootIsScheduled(root, now()); - return null; - } - - let exitStatus = renderRootSync(root, lanes); - if (root.tag !== LegacyRoot && exitStatus === RootErrored) { - // If something threw an error, try rendering one more time. We'll render - // synchronously to block concurrent data mutations, and we'll includes - // all pending updates are included. If it still fails after the second - // attempt, we'll give up and commit the resulting tree. - const originallyAttemptedLanes = lanes; - const errorRetryLanes = getLanesToRetrySynchronouslyOnError( - root, - originallyAttemptedLanes, - ); - if (errorRetryLanes !== NoLanes) { - lanes = errorRetryLanes; - exitStatus = recoverFromConcurrentError( - root, - originallyAttemptedLanes, - errorRetryLanes, - ); - } - } - - if (exitStatus === RootFatalErrored) { - const fatalError = workInProgressRootFatalError; - prepareFreshStack(root, NoLanes); - markRootSuspended(root, lanes); - ensureRootIsScheduled(root, now()); - throw fatalError; - } - - if (exitStatus === RootDidNotComplete) { - // The render unwound without completing the tree. This happens in special - // cases where need to exit the current render without producing a - // consistent tree or committing. - markRootSuspended(root, lanes); - ensureRootIsScheduled(root, now()); - return null; - } - - // We now have a consistent tree. Because this is a sync render, we - // will commit it even if something suspended. - const finishedWork: Fiber = (root.current.alternate: any); - root.finishedWork = finishedWork; - root.finishedLanes = lanes; - commitRoot( - root, - workInProgressRootRecoverableErrors, - workInProgressTransitions, - ); - - // Before exiting, make sure there's a callback scheduled for the next - // pending level. - ensureRootIsScheduled(root, now()); - - return null; -} - -export function flushRoot(root: FiberRoot, lanes: Lanes) { - if (lanes !== NoLanes) { - markRootEntangled(root, mergeLanes(lanes, SyncLane)); - ensureRootIsScheduled(root, now()); - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - resetRenderTimer(); - flushSyncCallbacks(); - } - } -} - -export function getExecutionContext(): ExecutionContext { - return executionContext; -} - -export function deferredUpdates(fn: () => A): A { - const previousPriority = getCurrentUpdatePriority(); - const prevTransition = ReactCurrentBatchConfig.transition; - - try { - ReactCurrentBatchConfig.transition = null; - setCurrentUpdatePriority(DefaultEventPriority); - return fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig.transition = prevTransition; - } -} - -export function batchedUpdates(fn: A => R, a: A): R { - const prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - // If there were legacy sync updates, flush them at the end of the outer - // most batchedUpdates-like method. - if ( - executionContext === NoContext && - // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. - !(__DEV__ && ReactCurrentActQueue.isBatchingLegacy) - ) { - resetRenderTimer(); - flushSyncCallbacksOnlyInLegacyMode(); - } - } -} - -export function discreteUpdates( - fn: (A, B, C, D) => R, - a: A, - b: B, - c: C, - d: D, -): R { - const previousPriority = getCurrentUpdatePriority(); - const prevTransition = ReactCurrentBatchConfig.transition; - try { - ReactCurrentBatchConfig.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - return fn(a, b, c, d); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig.transition = prevTransition; - if (executionContext === NoContext) { - resetRenderTimer(); - } - } -} - -// Overload the definition to the two valid signatures. -// Warning, this opts-out of checking the function body. -declare function flushSync(fn: () => R): R; -// eslint-disable-next-line no-redeclare -declare function flushSync(void): void; -// eslint-disable-next-line no-redeclare -export function flushSync(fn: (() => R) | void): R | void { - // In legacy mode, we flush pending passive effects at the beginning of the - // next event, not at the end of the previous one. - if ( - rootWithPendingPassiveEffects !== null && - rootWithPendingPassiveEffects.tag === LegacyRoot && - (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - flushPassiveEffects(); - } - - const prevExecutionContext = executionContext; - executionContext |= BatchedContext; - - const prevTransition = ReactCurrentBatchConfig.transition; - const previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - if (fn) { - return fn(); - } else { - return undefined; - } - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig.transition = prevTransition; - - executionContext = prevExecutionContext; - // Flush the immediate callbacks that were scheduled during this batch. - // Note that this will happen even if batchedUpdates is higher up - // the stack. - if ((executionContext & (RenderContext | CommitContext)) === NoContext) { - flushSyncCallbacks(); - } - } -} - -export function isAlreadyRendering(): boolean { - // Used by the renderer to print a warning if certain APIs are called from - // the wrong context. - return ( - __DEV__ && - (executionContext & (RenderContext | CommitContext)) !== NoContext - ); -} - -export function isInvalidExecutionContextForEventFunction(): boolean { - // Used to throw if certain APIs are called from the wrong context. - return (executionContext & RenderContext) !== NoContext; -} - -export function flushControlled(fn: () => mixed): void { - const prevExecutionContext = executionContext; - executionContext |= BatchedContext; - const prevTransition = ReactCurrentBatchConfig.transition; - const previousPriority = getCurrentUpdatePriority(); - try { - ReactCurrentBatchConfig.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - fn(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig.transition = prevTransition; - - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - resetRenderTimer(); - flushSyncCallbacks(); - } - } -} - -// This is called by the HiddenContext module when we enter or leave a -// hidden subtree. The stack logic is managed there because that's the only -// place that ever modifies it. Which module it lives in doesn't matter for -// performance because this function will get inlined regardless -export function setRenderLanes(subtreeRenderLanes: Lanes) { - renderLanes = subtreeRenderLanes; -} - -export function getRenderLanes(): Lanes { - return renderLanes; -} - -function prepareFreshStack(root: FiberRoot, lanes: Lanes): Fiber { - root.finishedWork = null; - root.finishedLanes = NoLanes; - - const timeoutHandle = root.timeoutHandle; - if (timeoutHandle !== noTimeout) { - // The root previous suspended and scheduled a timeout to commit a fallback - // state. Now that we have additional work, cancel the timeout. - root.timeoutHandle = noTimeout; - // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - cancelTimeout(timeoutHandle); - } - - if (workInProgress !== null) { - let interruptedWork; - if (workInProgressSuspendedReason === NotSuspended) { - // Normal case. Work-in-progress hasn't started yet. Unwind all - // its parents. - interruptedWork = workInProgress.return; - } else { - // Work-in-progress is in suspended state. Reset the work loop and unwind - // both the suspended fiber and all its parents. - resetSuspendedWorkLoopOnUnwind(); - interruptedWork = workInProgress; - } - while (interruptedWork !== null) { - const current = interruptedWork.alternate; - unwindInterruptedWork( - current, - interruptedWork, - workInProgressRootRenderLanes, - ); - interruptedWork = interruptedWork.return; - } - } - workInProgressRoot = root; - const rootWorkInProgress = createWorkInProgress(root.current, null); - workInProgress = rootWorkInProgress; - workInProgressRootRenderLanes = renderLanes = lanes; - workInProgressSuspendedReason = NotSuspended; - workInProgressThrownValue = null; - workInProgressRootDidAttachPingListener = false; - workInProgressRootExitStatus = RootInProgress; - workInProgressRootFatalError = null; - workInProgressRootSkippedLanes = NoLanes; - workInProgressRootInterleavedUpdatedLanes = NoLanes; - workInProgressRootRenderPhaseUpdatedLanes = NoLanes; - workInProgressRootPingedLanes = NoLanes; - workInProgressRootConcurrentErrors = null; - workInProgressRootRecoverableErrors = null; - - finishQueueingConcurrentUpdates(); - - if (__DEV__) { - ReactStrictModeWarnings.discardPendingWarnings(); - } - - return rootWorkInProgress; -} - -function resetSuspendedWorkLoopOnUnwind() { - // Reset module-level state that was set during the render phase. - resetContextDependencies(); - resetHooksOnUnwind(); -} - -function handleThrow(root, thrownValue): void { - // A component threw an exception. Usually this is because it suspended, but - // it also includes regular program errors. - // - // We're either going to unwind the stack to show a Suspense or error - // boundary, or we're going to replay the component again. Like after a - // promise resolves. - // - // Until we decide whether we're going to unwind or replay, we should preserve - // the current state of the work loop without resetting anything. - // - // If we do decide to unwind the stack, module-level variables will be reset - // in resetSuspendedWorkLoopOnUnwind. - - // These should be reset immediately because they're only supposed to be set - // when React is executing user code. - resetHooksAfterThrow(); - resetCurrentDebugFiberInDEV(); - ReactCurrentOwner.current = null; - - if (thrownValue === SuspenseException) { - // This is a special type of exception used for Suspense. For historical - // reasons, the rest of the Suspense implementation expects the thrown value - // to be a thenable, because before `use` existed that was the (unstable) - // API for suspending. This implementation detail can change later, once we - // deprecate the old API in favor of `use`. - thrownValue = getSuspendedThenable(); - workInProgressSuspendedReason = shouldAttemptToSuspendUntilDataResolves() - ? SuspendedOnData - : SuspendedOnImmediate; - } else if (thrownValue === SelectiveHydrationException) { - // An update flowed into a dehydrated boundary. Before we can apply the - // update, we need to finish hydrating. Interrupt the work-in-progress - // render so we can restart at the hydration lane. - // - // The ideal implementation would be able to switch contexts without - // unwinding the current stack. - // - // We could name this something more general but as of now it's the only - // case where we think this should happen. - workInProgressSuspendedReason = SuspendedOnHydration; - } else { - // This is a regular error. - const isWakeable = - thrownValue !== null && - typeof thrownValue === 'object' && - // $FlowFixMe[method-unbinding] - typeof thrownValue.then === 'function'; - - workInProgressSuspendedReason = isWakeable - ? // A wakeable object was thrown by a legacy Suspense implementation. - // This has slightly different behavior than suspending with `use`. - SuspendedOnDeprecatedThrowPromise - : // This is a regular error. If something earlier in the component already - // suspended, we must clear the thenable state to unblock the work loop. - SuspendedOnError; - } - - workInProgressThrownValue = thrownValue; - - const erroredWork = workInProgress; - if (erroredWork === null) { - // This is a fatal error - workInProgressRootExitStatus = RootFatalErrored; - workInProgressRootFatalError = thrownValue; - return; - } - - if (enableProfilerTimer && erroredWork.mode & ProfileMode) { - // Record the time spent rendering before an error was thrown. This - // avoids inaccurate Profiler durations in the case of a - // suspended render. - stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); - } - - if (enableSchedulingProfiler) { - markComponentRenderStopped(); - if (workInProgressSuspendedReason !== SuspendedOnError) { - const wakeable: Wakeable = (thrownValue: any); - markComponentSuspended( - erroredWork, - wakeable, - workInProgressRootRenderLanes, - ); - } else { - markComponentErrored( - erroredWork, - thrownValue, - workInProgressRootRenderLanes, - ); - } - } -} - -function shouldAttemptToSuspendUntilDataResolves() { - // TODO: We should be able to move the - // renderDidSuspend/renderDidSuspendDelayIfPossible logic into this function, - // instead of repeating it in the complete phase. Or something to that effect. - - if (includesOnlyRetries(workInProgressRootRenderLanes)) { - // We can always wait during a retry. - return true; - } - - // Check if there are other pending updates that might possibly unblock this - // component from suspending. This mirrors the check in - // renderDidSuspendDelayIfPossible. We should attempt to unify them somehow. - if ( - includesNonIdleWork(workInProgressRootSkippedLanes) || - includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes) - ) { - // Suspend normally. renderDidSuspendDelayIfPossible will handle - // interrupting the work loop. - return false; - } - - // TODO: We should be able to remove the equivalent check in - // finishConcurrentRender, and rely just on this one. - if (includesOnlyTransitions(workInProgressRootRenderLanes)) { - const suspenseHandler = getSuspenseHandler(); - if (suspenseHandler !== null && suspenseHandler.tag === SuspenseComponent) { - const currentSuspenseHandler = suspenseHandler.alternate; - const nextProps: SuspenseProps = suspenseHandler.memoizedProps; - if (isBadSuspenseFallback(currentSuspenseHandler, nextProps)) { - // The nearest Suspense boundary is already showing content. We should - // avoid replacing it with a fallback, and instead wait until the - // data finishes loading. - return true; - } else { - // This is not a bad fallback condition. We should show a fallback - // immediately instead of waiting for the data to resolve. This includes - // when suspending inside new trees. - return false; - } - } - - // During a transition, if there is no Suspense boundary (i.e. suspending in - // the "shell" of an application), or if we're inside a hidden tree, then - // we should wait until the data finishes loading. - return true; - } - - // For all other Lanes besides Transitions and Retries, we should not wait - // for the data to load. - // TODO: We should wait during Offscreen prerendering, too. - return false; -} - -function pushDispatcher(container) { - prepareRendererToRender(container); - const prevDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - if (prevDispatcher === null) { - // The React isomorphic package does not include a default dispatcher. - // Instead the first renderer will lazily attach one, in order to give - // nicer error messages. - return ContextOnlyDispatcher; - } else { - return prevDispatcher; - } -} - -function popDispatcher(prevDispatcher) { - resetRendererAfterRender(); - ReactCurrentDispatcher.current = prevDispatcher; -} - -function pushCacheDispatcher() { - if (enableCache) { - const prevCacheDispatcher = ReactCurrentCache.current; - ReactCurrentCache.current = DefaultCacheDispatcher; - return prevCacheDispatcher; - } else { - return null; - } -} - -function popCacheDispatcher(prevCacheDispatcher) { - if (enableCache) { - ReactCurrentCache.current = prevCacheDispatcher; - } -} - -export function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now(); -} - -export function markSkippedUpdateLanes(lane: Lane | Lanes): void { - workInProgressRootSkippedLanes = mergeLanes( - lane, - workInProgressRootSkippedLanes, - ); -} - -export function renderDidSuspend(): void { - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootSuspended; - } -} - -export function renderDidSuspendDelayIfPossible(): void { - workInProgressRootExitStatus = RootSuspendedWithDelay; - - // Check if there are updates that we skipped tree that might have unblocked - // this render. - if ( - workInProgressRoot !== null && - (includesNonIdleWork(workInProgressRootSkippedLanes) || - includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes)) - ) { - // Mark the current render as suspended so that we switch to working on - // the updates that were skipped. Usually we only suspend at the end of - // the render phase. - // TODO: We should probably always mark the root as suspended immediately - // (inside this function), since by suspending at the end of the render - // phase introduces a potential mistake where we suspend lanes that were - // pinged or updated while we were rendering. - markRootSuspended(workInProgressRoot, workInProgressRootRenderLanes); - } -} - -export function renderDidError(error: CapturedValue) { - if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { - workInProgressRootExitStatus = RootErrored; - } - if (workInProgressRootConcurrentErrors === null) { - workInProgressRootConcurrentErrors = [error]; - } else { - workInProgressRootConcurrentErrors.push(error); - } -} - -// Called during render to determine if anything has suspended. -// Returns false if we're not sure. -export function renderHasNotSuspendedYet(): boolean { - // If something errored or completed, we can't really be sure, - // so those are false. - return workInProgressRootExitStatus === RootInProgress; -} - -// TODO: Over time, this function and renderRootConcurrent have become more -// and more similar. Not sure it makes sense to maintain forked paths. Consider -// unifying them again. -function renderRootSync(root: FiberRoot, lanes: Lanes) { - const prevExecutionContext = executionContext; - executionContext |= RenderContext; - const prevDispatcher = pushDispatcher(root.containerInfo); - const prevCacheDispatcher = pushCacheDispatcher(); - - // If the root or lanes have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - const memoizedUpdaters = root.memoizedUpdaters; - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } - - // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. - // If we bailout on this work, we'll move them back (like above). - // It's important to move them now in case the work spawns more work at the same priority with different updaters. - // That way we can keep the current update and future updates separate. - movePendingFibersToMemoized(root, lanes); - } - } - - workInProgressTransitions = getTransitionsForLanes(root, lanes); - prepareFreshStack(root, lanes); - } - - if (__DEV__) { - if (enableDebugTracing) { - logRenderStarted(lanes); - } - } - - if (enableSchedulingProfiler) { - markRenderStarted(lanes); - } - - outer: do { - try { - if ( - workInProgressSuspendedReason !== NotSuspended && - workInProgress !== null - ) { - // The work loop is suspended. During a synchronous render, we don't - // yield to the main thread. Immediately unwind the stack. This will - // trigger either a fallback or an error boundary. - // TODO: For discrete and "default" updates (anything that's not - // flushSync), we want to wait for the microtasks the flush before - // unwinding. Will probably implement this using renderRootConcurrent, - // or merge renderRootSync and renderRootConcurrent into the same - // function and fork the behavior some other way. - const unitOfWork = workInProgress; - const thrownValue = workInProgressThrownValue; - switch (workInProgressSuspendedReason) { - case SuspendedOnHydration: { - // Selective hydration. An update flowed into a dehydrated tree. - // Interrupt the current render so the work loop can switch to the - // hydration lane. - workInProgress = null; - workInProgressRootExitStatus = RootDidNotComplete; - break outer; - } - default: { - // Continue with the normal work loop. - workInProgressSuspendedReason = NotSuspended; - workInProgressThrownValue = null; - unwindSuspendedUnitOfWork(unitOfWork, thrownValue); - break; - } - } - } - workLoopSync(); - break; - } catch (thrownValue) { - handleThrow(root, thrownValue); - } - } while (true); - resetContextDependencies(); - - executionContext = prevExecutionContext; - popDispatcher(prevDispatcher); - popCacheDispatcher(prevCacheDispatcher); - - if (workInProgress !== null) { - // This is a sync render, so we should have finished the whole tree. - throw new Error( - 'Cannot commit an incomplete root. This error is likely caused by a ' + - 'bug in React. Please file an issue.', - ); - } - - if (__DEV__) { - if (enableDebugTracing) { - logRenderStopped(); - } - } - - if (enableSchedulingProfiler) { - markRenderStopped(); - } - - // Set this to null to indicate there's no in-progress render. - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; - - // It's safe to process the queue now that the render phase is complete. - finishQueueingConcurrentUpdates(); - - return workInProgressRootExitStatus; -} - -// The work loop is an extremely hot path. Tell Closure not to inline it. -/** @noinline */ -function workLoopSync() { - // Perform work without checking if we need to yield between fiber. - while (workInProgress !== null) { - performUnitOfWork(workInProgress); - } -} - -function renderRootConcurrent(root: FiberRoot, lanes: Lanes) { - const prevExecutionContext = executionContext; - executionContext |= RenderContext; - const prevDispatcher = pushDispatcher(root.containerInfo); - const prevCacheDispatcher = pushCacheDispatcher(); - - // If the root or lanes have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - const memoizedUpdaters = root.memoizedUpdaters; - if (memoizedUpdaters.size > 0) { - restorePendingUpdaters(root, workInProgressRootRenderLanes); - memoizedUpdaters.clear(); - } - - // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. - // If we bailout on this work, we'll move them back (like above). - // It's important to move them now in case the work spawns more work at the same priority with different updaters. - // That way we can keep the current update and future updates separate. - movePendingFibersToMemoized(root, lanes); - } - } - - workInProgressTransitions = getTransitionsForLanes(root, lanes); - resetRenderTimer(); - prepareFreshStack(root, lanes); - } - - if (__DEV__) { - if (enableDebugTracing) { - logRenderStarted(lanes); - } - } - - if (enableSchedulingProfiler) { - markRenderStarted(lanes); - } - - outer: do { - try { - if ( - workInProgressSuspendedReason !== NotSuspended && - workInProgress !== null - ) { - // The work loop is suspended. We need to either unwind the stack or - // replay the suspended component. - const unitOfWork = workInProgress; - const thrownValue = workInProgressThrownValue; - switch (workInProgressSuspendedReason) { - case SuspendedOnError: { - // Unwind then continue with the normal work loop. - workInProgressSuspendedReason = NotSuspended; - workInProgressThrownValue = null; - unwindSuspendedUnitOfWork(unitOfWork, thrownValue); - break; - } - case SuspendedOnData: { - const thenable: Thenable = (thrownValue: any); - if (isThenableResolved(thenable)) { - // The data resolved. Try rendering the component again. - workInProgressSuspendedReason = NotSuspended; - workInProgressThrownValue = null; - replaySuspendedUnitOfWork(unitOfWork); - break; - } - // The work loop is suspended on data. We should wait for it to - // resolve before continuing to render. - const onResolution = () => { - ensureRootIsScheduled(root, now()); - }; - thenable.then(onResolution, onResolution); - break outer; - } - case SuspendedOnImmediate: { - // If this fiber just suspended, it's possible the data is already - // cached. Yield to the main thread to give it a chance to ping. If - // it does, we can retry immediately without unwinding the stack. - workInProgressSuspendedReason = SuspendedAndReadyToUnwind; - break outer; - } - case SuspendedAndReadyToUnwind: { - const thenable: Thenable = (thrownValue: any); - if (isThenableResolved(thenable)) { - // The data resolved. Try rendering the component again. - workInProgressSuspendedReason = NotSuspended; - workInProgressThrownValue = null; - replaySuspendedUnitOfWork(unitOfWork); - } else { - // Otherwise, unwind then continue with the normal work loop. - workInProgressSuspendedReason = NotSuspended; - workInProgressThrownValue = null; - unwindSuspendedUnitOfWork(unitOfWork, thrownValue); - } - break; - } - case SuspendedOnDeprecatedThrowPromise: { - // Suspended by an old implementation that uses the `throw promise` - // pattern. The newer replaying behavior can cause subtle issues - // like infinite ping loops. So we maintain the old behavior and - // always unwind. - workInProgressSuspendedReason = NotSuspended; - workInProgressThrownValue = null; - unwindSuspendedUnitOfWork(unitOfWork, thrownValue); - break; - } - case SuspendedOnHydration: { - // Selective hydration. An update flowed into a dehydrated tree. - // Interrupt the current render so the work loop can switch to the - // hydration lane. - workInProgress = null; - workInProgressRootExitStatus = RootDidNotComplete; - break outer; - } - default: { - throw new Error( - 'Unexpected SuspendedReason. This is a bug in React.', - ); - } - } - } - workLoopConcurrent(); - break; - } catch (thrownValue) { - handleThrow(root, thrownValue); - } - } while (true); - resetContextDependencies(); - - popDispatcher(prevDispatcher); - popCacheDispatcher(prevCacheDispatcher); - executionContext = prevExecutionContext; - - if (__DEV__) { - if (enableDebugTracing) { - logRenderStopped(); - } - } - - // Check if the tree has completed. - if (workInProgress !== null) { - // Still work remaining. - if (enableSchedulingProfiler) { - markRenderYielded(); - } - return RootInProgress; - } else { - // Completed the tree. - if (enableSchedulingProfiler) { - markRenderStopped(); - } - - // Set this to null to indicate there's no in-progress render. - workInProgressRoot = null; - workInProgressRootRenderLanes = NoLanes; - - // It's safe to process the queue now that the render phase is complete. - finishQueueingConcurrentUpdates(); - - // Return the final exit status. - return workInProgressRootExitStatus; - } -} - -/** @noinline */ -function workLoopConcurrent() { - // Perform work until Scheduler asks us to yield - while (workInProgress !== null && !shouldYield()) { - // $FlowFixMe[incompatible-call] found when upgrading Flow - performUnitOfWork(workInProgress); - } -} - -function performUnitOfWork(unitOfWork: Fiber): void { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - const current = unitOfWork.alternate; - setCurrentDebugFiberInDEV(unitOfWork); - - let next; - if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) { - startProfilerTimer(unitOfWork); - next = beginWork(current, unitOfWork, renderLanes); - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); - } else { - next = beginWork(current, unitOfWork, renderLanes); - } - - resetCurrentDebugFiberInDEV(); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - if (next === null) { - // If this doesn't spawn new work, complete the current work. - completeUnitOfWork(unitOfWork); - } else { - workInProgress = next; - } - - ReactCurrentOwner.current = null; -} - -function replaySuspendedUnitOfWork(unitOfWork: Fiber): void { - // This is a fork of performUnitOfWork specifcally for replaying a fiber that - // just suspended. - // - const current = unitOfWork.alternate; - setCurrentDebugFiberInDEV(unitOfWork); - - let next; - setCurrentDebugFiberInDEV(unitOfWork); - const isProfilingMode = - enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode; - if (isProfilingMode) { - startProfilerTimer(unitOfWork); - } - switch (unitOfWork.tag) { - case IndeterminateComponent: { - // Because it suspended with `use`, we can assume it's a - // function component. - unitOfWork.tag = FunctionComponent; - // Fallthrough to the next branch. - } - // eslint-disable-next-line no-fallthrough - case FunctionComponent: - case ForwardRef: { - // Resolve `defaultProps`. This logic is copied from `beginWork`. - // TODO: Consider moving this switch statement into that module. Also, - // could maybe use this as an opportunity to say `use` doesn't work with - // `defaultProps` :) - const Component = unitOfWork.type; - const unresolvedProps = unitOfWork.pendingProps; - const resolvedProps = - unitOfWork.elementType === Component - ? unresolvedProps - : resolveDefaultProps(Component, unresolvedProps); - next = replayFunctionComponent( - current, - unitOfWork, - resolvedProps, - Component, - workInProgressRootRenderLanes, - ); - break; - } - case SimpleMemoComponent: { - const Component = unitOfWork.type; - const nextProps = unitOfWork.pendingProps; - next = replayFunctionComponent( - current, - unitOfWork, - nextProps, - Component, - workInProgressRootRenderLanes, - ); - break; - } - default: { - if (__DEV__) { - console.error( - 'Unexpected type of work: %s, Currently only function ' + - 'components are replayed after suspending. This is a bug in React.', - unitOfWork.tag, - ); - } - resetSuspendedWorkLoopOnUnwind(); - unwindInterruptedWork(current, unitOfWork, workInProgressRootRenderLanes); - unitOfWork = workInProgress = resetWorkInProgress( - unitOfWork, - renderLanes, - ); - next = beginWork(current, unitOfWork, renderLanes); - break; - } - } - if (isProfilingMode) { - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); - } - - // The begin phase finished successfully without suspending. Return to the - // normal work loop. - - resetCurrentDebugFiberInDEV(); - unitOfWork.memoizedProps = unitOfWork.pendingProps; - if (next === null) { - // If this doesn't spawn new work, complete the current work. - completeUnitOfWork(unitOfWork); - } else { - workInProgress = next; - } - - ReactCurrentOwner.current = null; -} - -function unwindSuspendedUnitOfWork(unitOfWork: Fiber, thrownValue: mixed) { - // This is a fork of performUnitOfWork specifcally for unwinding a fiber - // that threw an exception. - // - // Return to the normal work loop. This will unwind the stack, and potentially - // result in showing a fallback. - resetSuspendedWorkLoopOnUnwind(); - - const returnFiber = unitOfWork.return; - if (returnFiber === null || workInProgressRoot === null) { - // Expected to be working on a non-root fiber. This is a fatal error - // because there's no ancestor that can handle it; the root is - // supposed to capture all errors that weren't caught by an error - // boundary. - workInProgressRootExitStatus = RootFatalErrored; - workInProgressRootFatalError = thrownValue; - // Set `workInProgress` to null. This represents advancing to the next - // sibling, or the parent if there are no siblings. But since the root - // has no siblings nor a parent, we set it to null. Usually this is - // handled by `completeUnitOfWork` or `unwindWork`, but since we're - // intentionally not calling those, we need set it here. - // TODO: Consider calling `unwindWork` to pop the contexts. - workInProgress = null; - return; - } - - try { - // Find and mark the nearest Suspense or error boundary that can handle - // this "exception". - throwException( - workInProgressRoot, - returnFiber, - unitOfWork, - thrownValue, - workInProgressRootRenderLanes, - ); - } catch (error) { - // We had trouble processing the error. An example of this happening is - // when accessing the `componentDidCatch` property of an error boundary - // throws an error. A weird edge case. There's a regression test for this. - // To prevent an infinite loop, bubble the error up to the next parent. - workInProgress = returnFiber; - throw error; - } - - // Return to the normal work loop. - completeUnitOfWork(unitOfWork); -} - -function completeUnitOfWork(unitOfWork: Fiber): void { - // Attempt to complete the current unit of work, then move to the next - // sibling. If there are no more siblings, return to the parent fiber. - let completedWork: Fiber = unitOfWork; - do { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - const current = completedWork.alternate; - const returnFiber = completedWork.return; - - // Check if the work completed or if something threw. - if ((completedWork.flags & Incomplete) === NoFlags) { - setCurrentDebugFiberInDEV(completedWork); - let next; - if ( - !enableProfilerTimer || - (completedWork.mode & ProfileMode) === NoMode - ) { - next = completeWork(current, completedWork, renderLanes); - } else { - startProfilerTimer(completedWork); - next = completeWork(current, completedWork, renderLanes); - // Update render duration assuming we didn't error. - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); - } - resetCurrentDebugFiberInDEV(); - - if (next !== null) { - // Completing this fiber spawned new work. Work on that next. - workInProgress = next; - return; - } - } else { - // This fiber did not complete because something threw. Pop values off - // the stack without entering the complete phase. If this is a boundary, - // capture values if possible. - const next = unwindWork(current, completedWork, renderLanes); - - // Because this fiber did not complete, don't reset its lanes. - - if (next !== null) { - // If completing this work spawned new work, do that next. We'll come - // back here again. - // Since we're restarting, remove anything that is not a host effect - // from the effect tag. - next.flags &= HostEffectMask; - workInProgress = next; - return; - } - - if ( - enableProfilerTimer && - (completedWork.mode & ProfileMode) !== NoMode - ) { - // Record the render duration for the fiber that errored. - stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); - - // Include the time spent working on failed children before continuing. - let actualDuration = completedWork.actualDuration; - let child = completedWork.child; - while (child !== null) { - // $FlowFixMe[unsafe-addition] addition with possible null/undefined value - actualDuration += child.actualDuration; - child = child.sibling; - } - completedWork.actualDuration = actualDuration; - } - - if (returnFiber !== null) { - // Mark the parent fiber as incomplete and clear its subtree flags. - returnFiber.flags |= Incomplete; - returnFiber.subtreeFlags = NoFlags; - returnFiber.deletions = null; - } else { - // We've unwound all the way to the root. - workInProgressRootExitStatus = RootDidNotComplete; - workInProgress = null; - return; - } - } - - const siblingFiber = completedWork.sibling; - if (siblingFiber !== null) { - // If there is more work to do in this returnFiber, do that next. - workInProgress = siblingFiber; - return; - } - // Otherwise, return to the parent - // $FlowFixMe[incompatible-type] we bail out when we get a null - completedWork = returnFiber; - // Update the next thing we're working on in case something throws. - workInProgress = completedWork; - } while (completedWork !== null); - - // We've reached the root. - if (workInProgressRootExitStatus === RootInProgress) { - workInProgressRootExitStatus = RootCompleted; - } -} - -function commitRoot( - root: FiberRoot, - recoverableErrors: null | Array>, - transitions: Array | null, -) { - // TODO: This no longer makes any sense. We already wrap the mutation and - // layout phases. Should be able to remove. - const previousUpdateLanePriority = getCurrentUpdatePriority(); - const prevTransition = ReactCurrentBatchConfig.transition; - - try { - ReactCurrentBatchConfig.transition = null; - setCurrentUpdatePriority(DiscreteEventPriority); - commitRootImpl( - root, - recoverableErrors, - transitions, - previousUpdateLanePriority, - ); - } finally { - ReactCurrentBatchConfig.transition = prevTransition; - setCurrentUpdatePriority(previousUpdateLanePriority); - } - - return null; -} - -function commitRootImpl( - root: FiberRoot, - recoverableErrors: null | Array>, - transitions: Array | null, - renderPriorityLevel: EventPriority, -) { - do { - // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which - // means `flushPassiveEffects` will sometimes result in additional - // passive effects. So we need to keep flushing in a loop until there are - // no more pending effects. - // TODO: Might be better if `flushPassiveEffects` did not automatically - // flush synchronous work at the end, to avoid factoring hazards like this. - flushPassiveEffects(); - } while (rootWithPendingPassiveEffects !== null); - flushRenderPhaseStrictModeWarningsInDEV(); - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Should not already be working.'); - } - - const finishedWork = root.finishedWork; - const lanes = root.finishedLanes; - - if (__DEV__) { - if (enableDebugTracing) { - logCommitStarted(lanes); - } - } - - if (enableSchedulingProfiler) { - markCommitStarted(lanes); - } - - if (finishedWork === null) { - if (__DEV__) { - if (enableDebugTracing) { - logCommitStopped(); - } - } - - if (enableSchedulingProfiler) { - markCommitStopped(); - } - - return null; - } else { - if (__DEV__) { - if (lanes === NoLanes) { - console.error( - 'root.finishedLanes should not be empty during a commit. This is a ' + - 'bug in React.', - ); - } - } - } - root.finishedWork = null; - root.finishedLanes = NoLanes; - - if (finishedWork === root.current) { - throw new Error( - 'Cannot commit the same tree as before. This error is likely caused by ' + - 'a bug in React. Please file an issue.', - ); - } - - // commitRoot never returns a continuation; it always finishes synchronously. - // So we can clear these now to allow a new callback to be scheduled. - root.callbackNode = null; - root.callbackPriority = NoLane; - - // Check which lanes no longer have any work scheduled on them, and mark - // those as finished. - let remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); - - // Make sure to account for lanes that were updated by a concurrent event - // during the render phase; don't mark them as finished. - const concurrentlyUpdatedLanes = getConcurrentlyUpdatedLanes(); - remainingLanes = mergeLanes(remainingLanes, concurrentlyUpdatedLanes); - - markRootFinished(root, remainingLanes); - - if (root === workInProgressRoot) { - // We can reset these now that they are finished. - workInProgressRoot = null; - workInProgress = null; - workInProgressRootRenderLanes = NoLanes; - } else { - // This indicates that the last root we worked on is not the same one that - // we're committing now. This most commonly happens when a suspended root - // times out. - } - - // If there are pending passive effects, schedule a callback to process them. - // Do this as early as possible, so it is queued before anything else that - // might get scheduled in the commit phase. (See #16714.) - // TODO: Delete all other places that schedule the passive effect callback - // They're redundant. - if ( - (finishedWork.subtreeFlags & PassiveMask) !== NoFlags || - (finishedWork.flags & PassiveMask) !== NoFlags - ) { - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - pendingPassiveEffectsRemainingLanes = remainingLanes; - // workInProgressTransitions might be overwritten, so we want - // to store it in pendingPassiveTransitions until they get processed - // We need to pass this through as an argument to commitRoot - // because workInProgressTransitions might have changed between - // the previous render and commit if we throttle the commit - // with setTimeout - pendingPassiveTransitions = transitions; - scheduleCallback(NormalSchedulerPriority, () => { - flushPassiveEffects(); - // This render triggered passive effects: release the root cache pool - // *after* passive effects fire to avoid freeing a cache pool that may - // be referenced by a node in the tree (HostRoot, Cache boundary etc) - return null; - }); - } - } - - // Check if there are any effects in the whole tree. - // TODO: This is left over from the effect list implementation, where we had - // to check for the existence of `firstEffect` to satisfy Flow. I think the - // only other reason this optimization exists is because it affects profiling. - // Reconsider whether this is necessary. - const subtreeHasEffects = - (finishedWork.subtreeFlags & - (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== - NoFlags; - const rootHasEffect = - (finishedWork.flags & - (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== - NoFlags; - - if (subtreeHasEffects || rootHasEffect) { - const prevTransition = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = null; - const previousPriority = getCurrentUpdatePriority(); - setCurrentUpdatePriority(DiscreteEventPriority); - - const prevExecutionContext = executionContext; - executionContext |= CommitContext; - - // Reset this to null before calling lifecycles - ReactCurrentOwner.current = null; - - // The commit phase is broken into several sub-phases. We do a separate pass - // of the effect list for each phase: all mutation effects come before all - // layout effects, and so on. - - // The first phase a "before mutation" phase. We use this phase to read the - // state of the host tree right before we mutate it. This is where - // getSnapshotBeforeUpdate is called. - const shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects( - root, - finishedWork, - ); - - if (enableProfilerTimer) { - // Mark the current commit time to be shared by all Profilers in this - // batch. This enables them to be grouped later. - recordCommitTime(); - } - - if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) { - // Track the root here, rather than in commitLayoutEffects(), because of ref setters. - // Updates scheduled during ref detachment should also be flagged. - rootCommittingMutationOrLayoutEffects = root; - } - - // The next phase is the mutation phase, where we mutate the host tree. - commitMutationEffects(root, finishedWork, lanes); - - if (enableCreateEventHandleAPI) { - if (shouldFireAfterActiveInstanceBlur) { - afterActiveInstanceBlur(); - } - } - resetAfterCommit(root.containerInfo); - - // The work-in-progress tree is now the current tree. This must come after - // the mutation phase, so that the previous tree is still current during - // componentWillUnmount, but before the layout phase, so that the finished - // work is current during componentDidMount/Update. - root.current = finishedWork; - - // The next phase is the layout phase, where we call effects that read - // the host tree after it's been mutated. The idiomatic use case for this is - // layout, but class component lifecycles also fire here for legacy reasons. - if (__DEV__) { - if (enableDebugTracing) { - logLayoutEffectsStarted(lanes); - } - } - if (enableSchedulingProfiler) { - markLayoutEffectsStarted(lanes); - } - commitLayoutEffects(finishedWork, root, lanes); - if (__DEV__) { - if (enableDebugTracing) { - logLayoutEffectsStopped(); - } - } - - if (enableSchedulingProfiler) { - markLayoutEffectsStopped(); - } - - if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) { - rootCommittingMutationOrLayoutEffects = null; - } - - // Tell Scheduler to yield at the end of the frame, so the browser has an - // opportunity to paint. - requestPaint(); - - executionContext = prevExecutionContext; - - // Reset the priority to the previous non-sync value. - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig.transition = prevTransition; - } else { - // No effects. - root.current = finishedWork; - // Measure these anyway so the flamegraph explicitly shows that there were - // no effects. - // TODO: Maybe there's a better way to report this. - if (enableProfilerTimer) { - recordCommitTime(); - } - } - - const rootDidHavePassiveEffects = rootDoesHavePassiveEffects; - - if (rootDoesHavePassiveEffects) { - // This commit has passive effects. Stash a reference to them. But don't - // schedule a callback until after flushing layout work. - rootDoesHavePassiveEffects = false; - rootWithPendingPassiveEffects = root; - pendingPassiveEffectsLanes = lanes; - } else { - // There were no passive effects, so we can immediately release the cache - // pool for this render. - releaseRootPooledCache(root, remainingLanes); - if (__DEV__) { - nestedPassiveUpdateCount = 0; - rootWithPassiveNestedUpdates = null; - } - } - - // Read this again, since an effect might have updated it - remainingLanes = root.pendingLanes; - - // Check if there's remaining work on this root - // TODO: This is part of the `componentDidCatch` implementation. Its purpose - // is to detect whether something might have called setState inside - // `componentDidCatch`. The mechanism is known to be flawed because `setState` - // inside `componentDidCatch` is itself flawed — that's why we recommend - // `getDerivedStateFromError` instead. However, it could be improved by - // checking if remainingLanes includes Sync work, instead of whether there's - // any work remaining at all (which would also include stuff like Suspense - // retries or transitions). It's been like this for a while, though, so fixing - // it probably isn't that urgent. - if (remainingLanes === NoLanes) { - // If there's no remaining work, we can clear the set of already failed - // error boundaries. - legacyErrorBoundariesThatAlreadyFailed = null; - } - - if (__DEV__) { - if (!rootDidHavePassiveEffects) { - commitDoubleInvokeEffectsInDEV(root, false); - } - } - - onCommitRootDevTools(finishedWork.stateNode, renderPriorityLevel); - - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - root.memoizedUpdaters.clear(); - } - } - - if (__DEV__) { - onCommitRootTestSelector(); - } - - // Always call this before exiting `commitRoot`, to ensure that any - // additional work on this root is scheduled. - ensureRootIsScheduled(root, now()); - - if (recoverableErrors !== null) { - // There were errors during this render, but recovered from them without - // needing to surface it to the UI. We log them here. - const onRecoverableError = root.onRecoverableError; - for (let i = 0; i < recoverableErrors.length; i++) { - const recoverableError = recoverableErrors[i]; - const errorInfo = makeErrorInfo( - recoverableError.digest, - recoverableError.stack, - ); - onRecoverableError(recoverableError.value, errorInfo); - } - } - - if (hasUncaughtError) { - hasUncaughtError = false; - const error = firstUncaughtError; - firstUncaughtError = null; - throw error; - } - - // If the passive effects are the result of a discrete render, flush them - // synchronously at the end of the current task so that the result is - // immediately observable. Otherwise, we assume that they are not - // order-dependent and do not need to be observed by external systems, so we - // can wait until after paint. - // TODO: We can optimize this by not scheduling the callback earlier. Since we - // currently schedule the callback in multiple places, will wait until those - // are consolidated. - if (includesSyncLane(pendingPassiveEffectsLanes) && root.tag !== LegacyRoot) { - flushPassiveEffects(); - } - - // Read this again, since a passive effect might have updated it - remainingLanes = root.pendingLanes; - if (includesSyncLane(remainingLanes)) { - if (enableProfilerTimer && enableProfilerNestedUpdatePhase) { - markNestedUpdateScheduled(); - } - - // Count the number of times the root synchronously re-renders without - // finishing. If there are too many, it indicates an infinite update loop. - if (root === rootWithNestedUpdates) { - nestedUpdateCount++; - } else { - nestedUpdateCount = 0; - rootWithNestedUpdates = root; - } - } else { - nestedUpdateCount = 0; - } - - // If layout work was scheduled, flush it now. - flushSyncCallbacks(); - - if (__DEV__) { - if (enableDebugTracing) { - logCommitStopped(); - } - } - - if (enableSchedulingProfiler) { - markCommitStopped(); - } - - if (enableTransitionTracing) { - // We process transitions during passive effects. However, passive effects can be - // processed synchronously during the commit phase as well as asynchronously after - // paint. At the end of the commit phase, we schedule a callback that will be called - // after the next paint. If the transitions have already been processed (passive - // effect phase happened synchronously), we will schedule a callback to process - // the transitions. However, if we don't have any pending transition callbacks, this - // means that the transitions have yet to be processed (passive effects processed after paint) - // so we will store the end time of paint so that we can process the transitions - // and then call the callback via the correct end time. - const prevRootTransitionCallbacks = root.transitionCallbacks; - if (prevRootTransitionCallbacks !== null) { - schedulePostPaintCallback(endTime => { - const prevPendingTransitionCallbacks = currentPendingTransitionCallbacks; - if (prevPendingTransitionCallbacks !== null) { - currentPendingTransitionCallbacks = null; - scheduleCallback(IdleSchedulerPriority, () => { - processTransitionCallbacks( - prevPendingTransitionCallbacks, - endTime, - prevRootTransitionCallbacks, - ); - }); - } else { - currentEndTime = endTime; - } - }); - } - } - - return null; -} - -function makeErrorInfo(digest: ?string, componentStack: ?string) { - if (__DEV__) { - const errorInfo = { - componentStack, - digest, - }; - Object.defineProperty(errorInfo, 'digest', { - configurable: false, - enumerable: true, - get() { - console.error( - 'You are accessing "digest" from the errorInfo object passed to onRecoverableError.' + - ' This property is deprecated and will be removed in a future version of React.' + - ' To access the digest of an Error look for this property on the Error instance itself.', - ); - return digest; - }, - }); - return errorInfo; - } else { - return { - digest, - componentStack, - }; - } -} - -function releaseRootPooledCache(root: FiberRoot, remainingLanes: Lanes) { - if (enableCache) { - const pooledCacheLanes = (root.pooledCacheLanes &= remainingLanes); - if (pooledCacheLanes === NoLanes) { - // None of the remaining work relies on the cache pool. Clear it so - // subsequent requests get a new cache - const pooledCache = root.pooledCache; - if (pooledCache != null) { - root.pooledCache = null; - releaseCache(pooledCache); - } - } - } -} - -export function flushPassiveEffects(): boolean { - // Returns whether passive effects were flushed. - // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should - // probably just combine the two functions. I believe they were only separate - // in the first place because we used to wrap it with - // `Scheduler.runWithPriority`, which accepts a function. But now we track the - // priority within React itself, so we can mutate the variable directly. - if (rootWithPendingPassiveEffects !== null) { - // Cache the root since rootWithPendingPassiveEffects is cleared in - // flushPassiveEffectsImpl - const root = rootWithPendingPassiveEffects; - // Cache and clear the remaining lanes flag; it must be reset since this - // method can be called from various places, not always from commitRoot - // where the remaining lanes are known - const remainingLanes = pendingPassiveEffectsRemainingLanes; - pendingPassiveEffectsRemainingLanes = NoLanes; - - const renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); - const priority = lowerEventPriority(DefaultEventPriority, renderPriority); - const prevTransition = ReactCurrentBatchConfig.transition; - const previousPriority = getCurrentUpdatePriority(); - - try { - ReactCurrentBatchConfig.transition = null; - setCurrentUpdatePriority(priority); - return flushPassiveEffectsImpl(); - } finally { - setCurrentUpdatePriority(previousPriority); - ReactCurrentBatchConfig.transition = prevTransition; - - // Once passive effects have run for the tree - giving components a - // chance to retain cache instances they use - release the pooled - // cache at the root (if there is one) - releaseRootPooledCache(root, remainingLanes); - } - } - return false; -} - -export function enqueuePendingPassiveProfilerEffect(fiber: Fiber): void { - if (enableProfilerTimer && enableProfilerCommitHooks) { - pendingPassiveProfilerEffects.push(fiber); - if (!rootDoesHavePassiveEffects) { - rootDoesHavePassiveEffects = true; - scheduleCallback(NormalSchedulerPriority, () => { - flushPassiveEffects(); - return null; - }); - } - } -} - -function flushPassiveEffectsImpl() { - if (rootWithPendingPassiveEffects === null) { - return false; - } - - // Cache and clear the transitions flag - const transitions = pendingPassiveTransitions; - pendingPassiveTransitions = null; - - const root = rootWithPendingPassiveEffects; - const lanes = pendingPassiveEffectsLanes; - rootWithPendingPassiveEffects = null; - // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. - // Figure out why and fix it. It's not causing any known issues (probably - // because it's only used for profiling), but it's a refactor hazard. - pendingPassiveEffectsLanes = NoLanes; - - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - throw new Error('Cannot flush passive effects while already rendering.'); - } - - if (__DEV__) { - isFlushingPassiveEffects = true; - didScheduleUpdateDuringPassiveEffects = false; - - if (enableDebugTracing) { - logPassiveEffectsStarted(lanes); - } - } - - if (enableSchedulingProfiler) { - markPassiveEffectsStarted(lanes); - } - - const prevExecutionContext = executionContext; - executionContext |= CommitContext; - - commitPassiveUnmountEffects(root.current); - commitPassiveMountEffects(root, root.current, lanes, transitions); - - // TODO: Move to commitPassiveMountEffects - if (enableProfilerTimer && enableProfilerCommitHooks) { - const profilerEffects = pendingPassiveProfilerEffects; - pendingPassiveProfilerEffects = []; - for (let i = 0; i < profilerEffects.length; i++) { - const fiber = ((profilerEffects[i]: any): Fiber); - commitPassiveEffectDurations(root, fiber); - } - } - - if (__DEV__) { - if (enableDebugTracing) { - logPassiveEffectsStopped(); - } - } - - if (enableSchedulingProfiler) { - markPassiveEffectsStopped(); - } - - if (__DEV__) { - commitDoubleInvokeEffectsInDEV(root, true); - } - - executionContext = prevExecutionContext; - - flushSyncCallbacks(); - - if (enableTransitionTracing) { - const prevPendingTransitionCallbacks = currentPendingTransitionCallbacks; - const prevRootTransitionCallbacks = root.transitionCallbacks; - const prevEndTime = currentEndTime; - if ( - prevPendingTransitionCallbacks !== null && - prevRootTransitionCallbacks !== null && - prevEndTime !== null - ) { - currentPendingTransitionCallbacks = null; - currentEndTime = null; - scheduleCallback(IdleSchedulerPriority, () => { - processTransitionCallbacks( - prevPendingTransitionCallbacks, - prevEndTime, - prevRootTransitionCallbacks, - ); - }); - } - } - - if (__DEV__) { - // If additional passive effects were scheduled, increment a counter. If this - // exceeds the limit, we'll fire a warning. - if (didScheduleUpdateDuringPassiveEffects) { - if (root === rootWithPassiveNestedUpdates) { - nestedPassiveUpdateCount++; - } else { - nestedPassiveUpdateCount = 0; - rootWithPassiveNestedUpdates = root; - } - } else { - nestedPassiveUpdateCount = 0; - } - isFlushingPassiveEffects = false; - didScheduleUpdateDuringPassiveEffects = false; - } - - // TODO: Move to commitPassiveMountEffects - onPostCommitRootDevTools(root); - if (enableProfilerTimer && enableProfilerCommitHooks) { - const stateNode = root.current.stateNode; - stateNode.effectDuration = 0; - stateNode.passiveEffectDuration = 0; - } - - return true; -} - -export function isAlreadyFailedLegacyErrorBoundary(instance: mixed): boolean { - return ( - legacyErrorBoundariesThatAlreadyFailed !== null && - legacyErrorBoundariesThatAlreadyFailed.has(instance) - ); -} - -export function markLegacyErrorBoundaryAsFailed(instance: mixed) { - if (legacyErrorBoundariesThatAlreadyFailed === null) { - legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); - } else { - legacyErrorBoundariesThatAlreadyFailed.add(instance); - } -} - -function prepareToThrowUncaughtError(error: mixed) { - if (!hasUncaughtError) { - hasUncaughtError = true; - firstUncaughtError = error; - } -} -export const onUncaughtError = prepareToThrowUncaughtError; - -function captureCommitPhaseErrorOnRoot( - rootFiber: Fiber, - sourceFiber: Fiber, - error: mixed, -) { - const errorInfo = createCapturedValueAtFiber(error, sourceFiber); - const update = createRootErrorUpdate(rootFiber, errorInfo, (SyncLane: Lane)); - const root = enqueueUpdate(rootFiber, update, (SyncLane: Lane)); - const eventTime = requestEventTime(); - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } -} - -export function captureCommitPhaseError( - sourceFiber: Fiber, - nearestMountedAncestor: Fiber | null, - error: mixed, -) { - if (__DEV__) { - reportUncaughtErrorInDEV(error); - setIsRunningInsertionEffect(false); - } - if (sourceFiber.tag === HostRoot) { - // Error was thrown at the root. There is no parent, so the root - // itself should capture it. - captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); - return; - } - - let fiber = null; - if (skipUnmountedBoundaries) { - fiber = nearestMountedAncestor; - } else { - fiber = sourceFiber.return; - } - - while (fiber !== null) { - if (fiber.tag === HostRoot) { - captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error); - return; - } else if (fiber.tag === ClassComponent) { - const ctor = fiber.type; - const instance = fiber.stateNode; - if ( - typeof ctor.getDerivedStateFromError === 'function' || - (typeof instance.componentDidCatch === 'function' && - !isAlreadyFailedLegacyErrorBoundary(instance)) - ) { - const errorInfo = createCapturedValueAtFiber(error, sourceFiber); - const update = createClassErrorUpdate( - fiber, - errorInfo, - (SyncLane: Lane), - ); - const root = enqueueUpdate(fiber, update, (SyncLane: Lane)); - const eventTime = requestEventTime(); - if (root !== null) { - markRootUpdated(root, SyncLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } - return; - } - } - fiber = fiber.return; - } - - if (__DEV__) { - // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning - // will fire for errors that are thrown by destroy functions inside deleted - // trees. What it should instead do is propagate the error to the parent of - // the deleted tree. In the meantime, do not add this warning to the - // allowlist; this is only for our internal use. - console.error( - 'Internal React error: Attempted to capture a commit phase error ' + - 'inside a detached tree. This indicates a bug in React. Likely ' + - 'causes include deleting the same fiber more than once, committing an ' + - 'already-finished tree, or an inconsistent return pointer.\n\n' + - 'Error message:\n\n%s', - error, - ); - } -} - -export function attachPingListener( - root: FiberRoot, - wakeable: Wakeable, - lanes: Lanes, -) { - // Attach a ping listener - // - // The data might resolve before we have a chance to commit the fallback. Or, - // in the case of a refresh, we'll never commit a fallback. So we need to - // attach a listener now. When it resolves ("pings"), we can decide whether to - // try rendering the tree again. - // - // Only attach a listener if one does not already exist for the lanes - // we're currently rendering (which acts like a "thread ID" here). - // - // We only need to do this in concurrent mode. Legacy Suspense always - // commits fallbacks synchronously, so there are no pings. - let pingCache = root.pingCache; - let threadIDs; - if (pingCache === null) { - pingCache = root.pingCache = new PossiblyWeakMap(); - threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } else { - threadIDs = pingCache.get(wakeable); - if (threadIDs === undefined) { - threadIDs = new Set(); - pingCache.set(wakeable, threadIDs); - } - } - if (!threadIDs.has(lanes)) { - workInProgressRootDidAttachPingListener = true; - - // Memoize using the thread ID to prevent redundant listeners. - threadIDs.add(lanes); - const ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - // If we have pending work still, restore the original updaters - restorePendingUpdaters(root, lanes); - } - } - wakeable.then(ping, ping); - } -} - -function pingSuspendedRoot( - root: FiberRoot, - wakeable: Wakeable, - pingedLanes: Lanes, -) { - const pingCache = root.pingCache; - if (pingCache !== null) { - // The wakeable resolved, so we no longer need to memoize, because it will - // never be thrown again. - pingCache.delete(wakeable); - } - - const eventTime = requestEventTime(); - markRootPinged(root, pingedLanes, eventTime); - - warnIfSuspenseResolutionNotWrappedWithActDEV(root); - - if ( - workInProgressRoot === root && - isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes) - ) { - // Received a ping at the same priority level at which we're currently - // rendering. We might want to restart this render. This should mirror - // the logic of whether or not a root suspends once it completes. - // TODO: If we're rendering sync either due to Sync, Batched or expired, - // we should probably never restart. - - // If we're suspended with delay, or if it's a retry, we'll always suspend - // so we can always restart. - if ( - workInProgressRootExitStatus === RootSuspendedWithDelay || - (workInProgressRootExitStatus === RootSuspended && - includesOnlyRetries(workInProgressRootRenderLanes) && - now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) - ) { - // Restart from the root. - prepareFreshStack(root, NoLanes); - } else { - // Even though we can't restart right now, we might get an - // opportunity later. So we mark this render as having a ping. - workInProgressRootPingedLanes = mergeLanes( - workInProgressRootPingedLanes, - pingedLanes, - ); - } - } - - ensureRootIsScheduled(root, eventTime); -} - -function retryTimedOutBoundary(boundaryFiber: Fiber, retryLane: Lane) { - // The boundary fiber (a Suspense component or SuspenseList component) - // previously was rendered in its fallback state. One of the promises that - // suspended it has resolved, which means at least part of the tree was - // likely unblocked. Try rendering again, at a new lanes. - if (retryLane === NoLane) { - // TODO: Assign this to `suspenseState.retryLane`? to avoid - // unnecessary entanglement? - retryLane = requestRetryLane(boundaryFiber); - } - // TODO: Special case idle priority? - const eventTime = requestEventTime(); - const root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); - if (root !== null) { - markRootUpdated(root, retryLane, eventTime); - ensureRootIsScheduled(root, eventTime); - } -} - -export function retryDehydratedSuspenseBoundary(boundaryFiber: Fiber) { - const suspenseState: null | SuspenseState = boundaryFiber.memoizedState; - let retryLane = NoLane; - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - retryTimedOutBoundary(boundaryFiber, retryLane); -} - -export function resolveRetryWakeable(boundaryFiber: Fiber, wakeable: Wakeable) { - let retryLane = NoLane; // Default - let retryCache: WeakSet | Set | null; - switch (boundaryFiber.tag) { - case SuspenseComponent: - retryCache = boundaryFiber.stateNode; - const suspenseState: null | SuspenseState = boundaryFiber.memoizedState; - if (suspenseState !== null) { - retryLane = suspenseState.retryLane; - } - break; - case SuspenseListComponent: - retryCache = boundaryFiber.stateNode; - break; - case OffscreenComponent: { - const instance: OffscreenInstance = boundaryFiber.stateNode; - // $FlowFixMe[incompatible-type] found when upgrading Flow - retryCache = instance._retryCache; - break; - } - default: - throw new Error( - 'Pinged unknown suspense boundary type. ' + - 'This is probably a bug in React.', - ); - } - - if (retryCache !== null) { - // The wakeable resolved, so we no longer need to memoize, because it will - // never be thrown again. - retryCache.delete(wakeable); - } - - retryTimedOutBoundary(boundaryFiber, retryLane); -} - -// Computes the next Just Noticeable Difference (JND) boundary. -// The theory is that a person can't tell the difference between small differences in time. -// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable -// difference in the experience. However, waiting for longer might mean that we can avoid -// showing an intermediate loading state. The longer we have already waited, the harder it -// is to tell small differences in time. Therefore, the longer we've already waited, -// the longer we can wait additionally. At some point we have to give up though. -// We pick a train model where the next boundary commits at a consistent schedule. -// These particular numbers are vague estimates. We expect to adjust them based on research. -function jnd(timeElapsed: number) { - return timeElapsed < 120 - ? 120 - : timeElapsed < 480 - ? 480 - : timeElapsed < 1080 - ? 1080 - : timeElapsed < 1920 - ? 1920 - : timeElapsed < 3000 - ? 3000 - : timeElapsed < 4320 - ? 4320 - : ceil(timeElapsed / 1960) * 1960; -} - -export function throwIfInfiniteUpdateLoopDetected() { - if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { - nestedUpdateCount = 0; - nestedPassiveUpdateCount = 0; - rootWithNestedUpdates = null; - rootWithPassiveNestedUpdates = null; - - throw new Error( - 'Maximum update depth exceeded. This can happen when a component ' + - 'repeatedly calls setState inside componentWillUpdate or ' + - 'componentDidUpdate. React limits the number of nested updates to ' + - 'prevent infinite loops.', - ); - } - - if (__DEV__) { - if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { - nestedPassiveUpdateCount = 0; - rootWithPassiveNestedUpdates = null; - - console.error( - 'Maximum update depth exceeded. This can happen when a component ' + - "calls setState inside useEffect, but useEffect either doesn't " + - 'have a dependency array, or one of the dependencies changes on ' + - 'every render.', - ); - } - } -} - -function flushRenderPhaseStrictModeWarningsInDEV() { - if (__DEV__) { - ReactStrictModeWarnings.flushLegacyContextWarning(); - - if (warnAboutDeprecatedLifecycles) { - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); - } - } -} - -function recursivelyTraverseAndDoubleInvokeEffectsInDEV( - root: FiberRoot, - parentFiber: Fiber, - isInStrictMode: boolean, -) { - if ((parentFiber.subtreeFlags & (PlacementDEV | Visibility)) === NoFlags) { - // Parent's descendants have already had effects double invoked. - // Early exit to avoid unnecessary tree traversal. - return; - } - let child = parentFiber.child; - while (child !== null) { - doubleInvokeEffectsInDEVIfNecessary(root, child, isInStrictMode); - child = child.sibling; - } -} - -// Unconditionally disconnects and connects passive and layout effects. -function doubleInvokeEffectsOnFiber(root: FiberRoot, fiber: Fiber) { - disappearLayoutEffects(fiber); - disconnectPassiveEffect(fiber); - reappearLayoutEffects(root, fiber.alternate, fiber, false); - reconnectPassiveEffects(root, fiber, NoLanes, null, false); -} - -function doubleInvokeEffectsInDEVIfNecessary( - root: FiberRoot, - fiber: Fiber, - parentIsInStrictMode: boolean, -) { - const isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE; - const isInStrictMode = parentIsInStrictMode || isStrictModeFiber; - - // First case: the fiber **is not** of type OffscreenComponent. No - // special rules apply to double invoking effects. - if (fiber.tag !== OffscreenComponent) { - if (fiber.flags & PlacementDEV) { - setCurrentDebugFiberInDEV(fiber); - if (isInStrictMode) { - doubleInvokeEffectsOnFiber(root, fiber); - } - resetCurrentDebugFiberInDEV(); - } else { - recursivelyTraverseAndDoubleInvokeEffectsInDEV( - root, - fiber, - isInStrictMode, - ); - } - return; - } - - // Second case: the fiber **is** of type OffscreenComponent. - // This branch contains cases specific to Offscreen. - if (fiber.memoizedState === null) { - // Only consider Offscreen that is visible. - // TODO (Offscreen) Handle manual mode. - setCurrentDebugFiberInDEV(fiber); - if (isInStrictMode && fiber.flags & Visibility) { - // Double invoke effects on Offscreen's subtree only - // if it is visible and its visibility has changed. - doubleInvokeEffectsOnFiber(root, fiber); - } else if (fiber.subtreeFlags & PlacementDEV) { - // Something in the subtree could have been suspended. - // We need to continue traversal and find newly inserted fibers. - recursivelyTraverseAndDoubleInvokeEffectsInDEV( - root, - fiber, - isInStrictMode, - ); - } - resetCurrentDebugFiberInDEV(); - } -} - -function commitDoubleInvokeEffectsInDEV( - root: FiberRoot, - hasPassiveEffects: boolean, -) { - if (__DEV__) { - if (useModernStrictMode) { - let doubleInvokeEffects = true; - - if (root.tag === LegacyRoot && !(root.current.mode & StrictLegacyMode)) { - doubleInvokeEffects = false; - } - if ( - root.tag === ConcurrentRoot && - !(root.current.mode & (StrictLegacyMode | StrictEffectsMode)) - ) { - doubleInvokeEffects = false; - } - recursivelyTraverseAndDoubleInvokeEffectsInDEV( - root, - root.current, - doubleInvokeEffects, - ); - } else { - legacyCommitDoubleInvokeEffectsInDEV(root.current, hasPassiveEffects); - } - } -} - -function legacyCommitDoubleInvokeEffectsInDEV( - fiber: Fiber, - hasPassiveEffects: boolean, -) { - // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects - // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. - // Maybe not a big deal since this is DEV only behavior. - - setCurrentDebugFiberInDEV(fiber); - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); - } - - invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); - if (hasPassiveEffects) { - invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); - } - resetCurrentDebugFiberInDEV(); -} - -function invokeEffectsInDev( - firstChild: Fiber, - fiberFlags: Flags, - invokeEffectFn: (fiber: Fiber) => void, -) { - let current: null | Fiber = firstChild; - let subtreeRoot = null; - while (current != null) { - const primarySubtreeFlag = current.subtreeFlags & fiberFlags; - if ( - current !== subtreeRoot && - current.child != null && - primarySubtreeFlag !== NoFlags - ) { - current = current.child; - } else { - if ((current.flags & fiberFlags) !== NoFlags) { - invokeEffectFn(current); - } - - if (current.sibling !== null) { - current = current.sibling; - } else { - current = subtreeRoot = current.return; - } - } - } -} - -let didWarnStateUpdateForNotYetMountedComponent: Set | null = null; -export function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber: Fiber) { - if (__DEV__) { - if ((executionContext & RenderContext) !== NoContext) { - // We let the other warning about render phase updates deal with this one. - return; - } - - if (!(fiber.mode & ConcurrentMode)) { - return; - } - - const tag = fiber.tag; - if ( - tag !== IndeterminateComponent && - tag !== HostRoot && - tag !== ClassComponent && - tag !== FunctionComponent && - tag !== ForwardRef && - tag !== MemoComponent && - tag !== SimpleMemoComponent - ) { - // Only warn for user-defined components, not internal ones like Suspense. - return; - } - - // We show the whole stack but dedupe on the top component's name because - // the problematic code almost always lies inside that component. - const componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; - if (didWarnStateUpdateForNotYetMountedComponent !== null) { - if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { - return; - } - // $FlowFixMe[incompatible-use] found when upgrading Flow - didWarnStateUpdateForNotYetMountedComponent.add(componentName); - } else { - didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); - } - - const previousFiber = ReactCurrentFiberCurrent; - try { - setCurrentDebugFiberInDEV(fiber); - console.error( - "Can't perform a React state update on a component that hasn't mounted yet. " + - 'This indicates that you have a side-effect in your render function that ' + - 'asynchronously later calls tries to update the component. Move this work to ' + - 'useEffect instead.', - ); - } finally { - if (previousFiber) { - setCurrentDebugFiberInDEV(fiber); - } else { - resetCurrentDebugFiberInDEV(); - } - } - } -} - -let beginWork; -if (__DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback) { - const dummyFiber = null; - beginWork = (current, unitOfWork, lanes) => { - // If a component throws an error, we replay it again in a synchronously - // dispatched event, so that the debugger will treat it as an uncaught - // error See ReactErrorUtils for more information. - - // Before entering the begin phase, copy the work-in-progress onto a dummy - // fiber. If beginWork throws, we'll use this to reset the state. - const originalWorkInProgressCopy = assignFiberPropertiesInDEV( - dummyFiber, - unitOfWork, - ); - try { - return originalBeginWork(current, unitOfWork, lanes); - } catch (originalError) { - if ( - didSuspendOrErrorWhileHydratingDEV() || - originalError === SuspenseException || - (originalError !== null && - typeof originalError === 'object' && - typeof originalError.then === 'function') - ) { - // Don't replay promises. - // Don't replay errors if we are hydrating and have already suspended or handled an error - throw originalError; - } - - // Don't reset current debug fiber, since we're about to work on the - // same fiber again. - - // Unwind the failed stack frame - resetSuspendedWorkLoopOnUnwind(); - unwindInterruptedWork(current, unitOfWork, workInProgressRootRenderLanes); - - // Restore the original properties of the fiber. - assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); - - if (enableProfilerTimer && unitOfWork.mode & ProfileMode) { - // Reset the profiler timer. - startProfilerTimer(unitOfWork); - } - - // Run beginWork again. - invokeGuardedCallback( - null, - originalBeginWork, - null, - current, - unitOfWork, - lanes, - ); - - if (hasCaughtError()) { - const replayError = clearCaughtError(); - if ( - typeof replayError === 'object' && - replayError !== null && - replayError._suppressLogging && - typeof originalError === 'object' && - originalError !== null && - !originalError._suppressLogging - ) { - // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. - originalError._suppressLogging = true; - } - } - // We always throw the original error in case the second render pass is not idempotent. - // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. - throw originalError; - } - }; -} else { - beginWork = originalBeginWork; -} - -let didWarnAboutUpdateInRender = false; -let didWarnAboutUpdateInRenderForAnotherComponent; -if (__DEV__) { - didWarnAboutUpdateInRenderForAnotherComponent = new Set(); -} - -function warnAboutRenderPhaseUpdatesInDEV(fiber) { - if (__DEV__) { - if (ReactCurrentDebugFiberIsRenderingInDEV) { - switch (fiber.tag) { - case FunctionComponent: - case ForwardRef: - case SimpleMemoComponent: { - const renderingComponentName = - (workInProgress && getComponentNameFromFiber(workInProgress)) || - 'Unknown'; - // Dedupe by the rendering component because it's the one that needs to be fixed. - const dedupeKey = renderingComponentName; - if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { - didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); - const setStateComponentName = - getComponentNameFromFiber(fiber) || 'Unknown'; - console.error( - 'Cannot update a component (`%s`) while rendering a ' + - 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + - 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', - setStateComponentName, - renderingComponentName, - renderingComponentName, - ); - } - break; - } - case ClassComponent: { - if (!didWarnAboutUpdateInRender) { - console.error( - 'Cannot update during an existing state transition (such as ' + - 'within `render`). Render methods should be a pure ' + - 'function of props and state.', - ); - didWarnAboutUpdateInRender = true; - } - break; - } - } - } - } -} - -export function restorePendingUpdaters(root: FiberRoot, lanes: Lanes): void { - if (enableUpdaterTracking) { - if (isDevToolsPresent) { - const memoizedUpdaters = root.memoizedUpdaters; - memoizedUpdaters.forEach(schedulingFiber => { - addFiberToLanesMap(root, schedulingFiber, lanes); - }); - - // This function intentionally does not clear memoized updaters. - // Those may still be relevant to the current commit - // and a future one (e.g. Suspense). - } - } -} - -const fakeActCallbackNode = {}; -function scheduleCallback(priorityLevel, callback) { - if (__DEV__) { - // If we're currently inside an `act` scope, bypass Scheduler and push to - // the `act` queue instead. - const actQueue = ReactCurrentActQueue.current; - if (actQueue !== null) { - actQueue.push(callback); - return fakeActCallbackNode; - } else { - return Scheduler_scheduleCallback(priorityLevel, callback); - } - } else { - // In production, always call Scheduler. This function will be stripped out. - return Scheduler_scheduleCallback(priorityLevel, callback); - } -} - -function cancelCallback(callbackNode) { - if (__DEV__ && callbackNode === fakeActCallbackNode) { - return; - } - // In production, always call Scheduler. This function will be stripped out. - return Scheduler_cancelCallback(callbackNode); -} - -function shouldForceFlushFallbacksInDEV() { - // Never force flush in production. This function should get stripped out. - return __DEV__ && ReactCurrentActQueue.current !== null; -} - -function warnIfUpdatesNotWrappedWithActDEV(fiber: Fiber): void { - if (__DEV__) { - if (fiber.mode & ConcurrentMode) { - if (!isConcurrentActEnvironment()) { - // Not in an act environment. No need to warn. - return; - } - } else { - // Legacy mode has additional cases where we suppress a warning. - if (!isLegacyActEnvironment(fiber)) { - // Not in an act environment. No need to warn. - return; - } - if (executionContext !== NoContext) { - // Legacy mode doesn't warn if the update is batched, i.e. - // batchedUpdates or flushSync. - return; - } - if ( - fiber.tag !== FunctionComponent && - fiber.tag !== ForwardRef && - fiber.tag !== SimpleMemoComponent - ) { - // For backwards compatibility with pre-hooks code, legacy mode only - // warns for updates that originate from a hook. - return; - } - } - - if (ReactCurrentActQueue.current === null) { - const previousFiber = ReactCurrentFiberCurrent; - try { - setCurrentDebugFiberInDEV(fiber); - console.error( - 'An update to %s inside a test was not wrapped in act(...).\n\n' + - 'When testing, code that causes React state updates should be ' + - 'wrapped into act(...):\n\n' + - 'act(() => {\n' + - ' /* fire events that update state */\n' + - '});\n' + - '/* assert on the output */\n\n' + - "This ensures that you're testing the behavior the user would see " + - 'in the browser.' + - ' Learn more at https://reactjs.org/link/wrap-tests-with-act', - getComponentNameFromFiber(fiber), - ); - } finally { - if (previousFiber) { - setCurrentDebugFiberInDEV(fiber); - } else { - resetCurrentDebugFiberInDEV(); - } - } - } - } -} - -function warnIfSuspenseResolutionNotWrappedWithActDEV(root: FiberRoot): void { - if (__DEV__) { - if ( - root.tag !== LegacyRoot && - isConcurrentActEnvironment() && - ReactCurrentActQueue.current === null - ) { - console.error( - 'A suspended resource finished loading inside a test, but the event ' + - 'was not wrapped in act(...).\n\n' + - 'When testing, code that resolves suspended data should be wrapped ' + - 'into act(...):\n\n' + - 'act(() => {\n' + - ' /* finish loading suspended data */\n' + - '});\n' + - '/* assert on the output */\n\n' + - "This ensures that you're testing the behavior the user would see " + - 'in the browser.' + - ' Learn more at https://reactjs.org/link/wrap-tests-with-act', - ); - } - } -} - -export function setIsRunningInsertionEffect(isRunning: boolean): void { - if (__DEV__) { - isRunningInsertionEffect = isRunning; - } -} diff --git a/packages/react-reconciler/src/ReactFiberWorkLoop.old.js b/packages/react-reconciler/src/ReactFiberWorkLoop.old.js index 069db86d4c05c..01753af76c871 100644 --- a/packages/react-reconciler/src/ReactFiberWorkLoop.old.js +++ b/packages/react-reconciler/src/ReactFiberWorkLoop.old.js @@ -176,7 +176,10 @@ import { lowerEventPriority, lanesToEventPriority, } from './ReactEventPriorities.old'; -import {requestCurrentTransition, NoTransition} from './ReactFiberTransition'; +import { + requestCurrentTransition, + NoTransition, +} from './ReactFiberTransition.old'; import { SelectiveHydrationException, beginWork as originalBeginWork, diff --git a/packages/react-reconciler/src/ReactInternalTypes.js b/packages/react-reconciler/src/ReactInternalTypes.js index 0b7a0c4f9ef1f..478a77d6f1fac 100644 --- a/packages/react-reconciler/src/ReactInternalTypes.js +++ b/packages/react-reconciler/src/ReactInternalTypes.js @@ -31,13 +31,11 @@ import type { SuspenseInstance, } from './ReactFiberHostConfig'; import type {Cache} from './ReactFiberCacheComponent.old'; -// Doing this because there's a merge conflict because of the way sync-reconciler-fork -// is implemented import type { TracingMarkerInstance, Transition, -} from './ReactFiberTracingMarkerComponent.new'; -import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates.new'; +} from './ReactFiberTracingMarkerComponent.old'; +import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates.old'; // Unwind Circular: moved from ReactFiberHooks.old export type HookType = @@ -416,8 +414,6 @@ export type Dispatcher = { useId(): string, useCacheRefresh?: () => (?() => T, ?T) => void, useMemoCache?: (size: number) => Array, - - unstable_isNewReconciler?: boolean, }; export type CacheDispatcher = { diff --git a/packages/react-reconciler/src/ReactMutableSource.new.js b/packages/react-reconciler/src/ReactMutableSource.new.js deleted file mode 100644 index 218e2171a9c15..0000000000000 --- a/packages/react-reconciler/src/ReactMutableSource.new.js +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {MutableSource, MutableSourceVersion} from 'shared/ReactTypes'; -import type {FiberRoot} from './ReactInternalTypes'; - -import {isPrimaryRenderer} from './ReactFiberHostConfig'; - -// Work in progress version numbers only apply to a single render, -// and should be reset before starting a new render. -// This tracks which mutable sources need to be reset after a render. -const workInProgressSources: Array> = []; - -let rendererSigil; -if (__DEV__) { - // Used to detect multiple renderers using the same mutable source. - rendererSigil = {}; -} - -export function markSourceAsDirty(mutableSource: MutableSource): void { - workInProgressSources.push(mutableSource); -} - -export function resetWorkInProgressVersions(): void { - for (let i = 0; i < workInProgressSources.length; i++) { - const mutableSource = workInProgressSources[i]; - if (isPrimaryRenderer) { - mutableSource._workInProgressVersionPrimary = null; - } else { - mutableSource._workInProgressVersionSecondary = null; - } - } - workInProgressSources.length = 0; -} - -export function getWorkInProgressVersion( - mutableSource: MutableSource, -): null | MutableSourceVersion { - if (isPrimaryRenderer) { - return mutableSource._workInProgressVersionPrimary; - } else { - return mutableSource._workInProgressVersionSecondary; - } -} - -export function setWorkInProgressVersion( - mutableSource: MutableSource, - version: MutableSourceVersion, -): void { - if (isPrimaryRenderer) { - mutableSource._workInProgressVersionPrimary = version; - } else { - mutableSource._workInProgressVersionSecondary = version; - } - workInProgressSources.push(mutableSource); -} - -export function warnAboutMultipleRenderersDEV( - mutableSource: MutableSource, -): void { - if (__DEV__) { - if (isPrimaryRenderer) { - if (mutableSource._currentPrimaryRenderer == null) { - mutableSource._currentPrimaryRenderer = rendererSigil; - } else if (mutableSource._currentPrimaryRenderer !== rendererSigil) { - console.error( - 'Detected multiple renderers concurrently rendering the ' + - 'same mutable source. This is currently unsupported.', - ); - } - } else { - if (mutableSource._currentSecondaryRenderer == null) { - mutableSource._currentSecondaryRenderer = rendererSigil; - } else if (mutableSource._currentSecondaryRenderer !== rendererSigil) { - console.error( - 'Detected multiple renderers concurrently rendering the ' + - 'same mutable source. This is currently unsupported.', - ); - } - } - } -} - -// Eager reads the version of a mutable source and stores it on the root. -// This ensures that the version used for server rendering matches the one -// that is eventually read during hydration. -// If they don't match there's a potential tear and a full deopt render is required. -export function registerMutableSourceForHydration( - root: FiberRoot, - mutableSource: MutableSource, -): void { - const getVersion = mutableSource._getVersion; - const version = getVersion(mutableSource._source); - - // TODO Clear this data once all pending hydration work is finished. - // Retaining it forever may interfere with GC. - if (root.mutableSourceEagerHydrationData == null) { - root.mutableSourceEagerHydrationData = [mutableSource, version]; - } else { - root.mutableSourceEagerHydrationData.push(mutableSource, version); - } -} diff --git a/packages/react-reconciler/src/ReactProfilerTimer.new.js b/packages/react-reconciler/src/ReactProfilerTimer.new.js deleted file mode 100644 index 016e7c1e0dc03..0000000000000 --- a/packages/react-reconciler/src/ReactProfilerTimer.new.js +++ /dev/null @@ -1,240 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; - -import { - enableProfilerCommitHooks, - enableProfilerNestedUpdatePhase, - enableProfilerTimer, -} from 'shared/ReactFeatureFlags'; -import {HostRoot, Profiler} from './ReactWorkTags'; - -// Intentionally not named imports because Rollup would use dynamic dispatch for -// CommonJS interop named imports. -import * as Scheduler from 'scheduler'; - -const {unstable_now: now} = Scheduler; - -export type ProfilerTimer = { - getCommitTime(): number, - isCurrentUpdateNested(): boolean, - markNestedUpdateScheduled(): void, - recordCommitTime(): void, - startProfilerTimer(fiber: Fiber): void, - stopProfilerTimerIfRunning(fiber: Fiber): void, - stopProfilerTimerIfRunningAndRecordDelta(fiber: Fiber): void, - syncNestedUpdateFlag(): void, - ... -}; - -let commitTime: number = 0; -let layoutEffectStartTime: number = -1; -let profilerStartTime: number = -1; -let passiveEffectStartTime: number = -1; - -/** - * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). - * - * The overall sequence is: - * 1. render - * 2. commit (and call `onRender`, `onCommit`) - * 3. check for nested updates - * 4. flush passive effects (and call `onPostCommit`) - * - * Nested updates are identified in step 3 above, - * but step 4 still applies to the work that was just committed. - * We use two flags to track nested updates then: - * one tracks whether the upcoming update is a nested update, - * and the other tracks whether the current update was a nested update. - * The first value gets synced to the second at the start of the render phase. - */ -let currentUpdateIsNested: boolean = false; -let nestedUpdateScheduled: boolean = false; - -function isCurrentUpdateNested(): boolean { - return currentUpdateIsNested; -} - -function markNestedUpdateScheduled(): void { - if (enableProfilerNestedUpdatePhase) { - nestedUpdateScheduled = true; - } -} - -function resetNestedUpdateFlag(): void { - if (enableProfilerNestedUpdatePhase) { - currentUpdateIsNested = false; - nestedUpdateScheduled = false; - } -} - -function syncNestedUpdateFlag(): void { - if (enableProfilerNestedUpdatePhase) { - currentUpdateIsNested = nestedUpdateScheduled; - nestedUpdateScheduled = false; - } -} - -function getCommitTime(): number { - return commitTime; -} - -function recordCommitTime(): void { - if (!enableProfilerTimer) { - return; - } - commitTime = now(); -} - -function startProfilerTimer(fiber: Fiber): void { - if (!enableProfilerTimer) { - return; - } - - profilerStartTime = now(); - - if (((fiber.actualStartTime: any): number) < 0) { - fiber.actualStartTime = now(); - } -} - -function stopProfilerTimerIfRunning(fiber: Fiber): void { - if (!enableProfilerTimer) { - return; - } - profilerStartTime = -1; -} - -function stopProfilerTimerIfRunningAndRecordDelta( - fiber: Fiber, - overrideBaseTime: boolean, -): void { - if (!enableProfilerTimer) { - return; - } - - if (profilerStartTime >= 0) { - const elapsedTime = now() - profilerStartTime; - // $FlowFixMe[unsafe-addition] addition with possible null/undefined value - fiber.actualDuration += elapsedTime; - if (overrideBaseTime) { - fiber.selfBaseDuration = elapsedTime; - } - profilerStartTime = -1; - } -} - -function recordLayoutEffectDuration(fiber: Fiber): void { - if (!enableProfilerTimer || !enableProfilerCommitHooks) { - return; - } - - if (layoutEffectStartTime >= 0) { - const elapsedTime = now() - layoutEffectStartTime; - - layoutEffectStartTime = -1; - - // Store duration on the next nearest Profiler ancestor - // Or the root (for the DevTools Profiler to read) - let parentFiber = fiber.return; - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - const root = parentFiber.stateNode; - root.effectDuration += elapsedTime; - return; - case Profiler: - const parentStateNode = parentFiber.stateNode; - parentStateNode.effectDuration += elapsedTime; - return; - } - parentFiber = parentFiber.return; - } - } -} - -function recordPassiveEffectDuration(fiber: Fiber): void { - if (!enableProfilerTimer || !enableProfilerCommitHooks) { - return; - } - - if (passiveEffectStartTime >= 0) { - const elapsedTime = now() - passiveEffectStartTime; - - passiveEffectStartTime = -1; - - // Store duration on the next nearest Profiler ancestor - // Or the root (for the DevTools Profiler to read) - let parentFiber = fiber.return; - while (parentFiber !== null) { - switch (parentFiber.tag) { - case HostRoot: - const root = parentFiber.stateNode; - if (root !== null) { - root.passiveEffectDuration += elapsedTime; - } - return; - case Profiler: - const parentStateNode = parentFiber.stateNode; - if (parentStateNode !== null) { - // Detached fibers have their state node cleared out. - // In this case, the return pointer is also cleared out, - // so we won't be able to report the time spent in this Profiler's subtree. - parentStateNode.passiveEffectDuration += elapsedTime; - } - return; - } - parentFiber = parentFiber.return; - } - } -} - -function startLayoutEffectTimer(): void { - if (!enableProfilerTimer || !enableProfilerCommitHooks) { - return; - } - layoutEffectStartTime = now(); -} - -function startPassiveEffectTimer(): void { - if (!enableProfilerTimer || !enableProfilerCommitHooks) { - return; - } - passiveEffectStartTime = now(); -} - -function transferActualDuration(fiber: Fiber): void { - // Transfer time spent rendering these children so we don't lose it - // after we rerender. This is used as a helper in special cases - // where we should count the work of multiple passes. - let child = fiber.child; - while (child) { - // $FlowFixMe[unsafe-addition] addition with possible null/undefined value - fiber.actualDuration += child.actualDuration; - child = child.sibling; - } -} - -export { - getCommitTime, - isCurrentUpdateNested, - markNestedUpdateScheduled, - recordCommitTime, - recordLayoutEffectDuration, - recordPassiveEffectDuration, - resetNestedUpdateFlag, - startLayoutEffectTimer, - startPassiveEffectTimer, - startProfilerTimer, - stopProfilerTimerIfRunning, - stopProfilerTimerIfRunningAndRecordDelta, - syncNestedUpdateFlag, - transferActualDuration, -}; diff --git a/packages/react-reconciler/src/ReactReconcilerConstants.js b/packages/react-reconciler/src/ReactReconcilerConstants.js index 3e9b1c7009da9..5a905e4aa3f18 100644 --- a/packages/react-reconciler/src/ReactReconcilerConstants.js +++ b/packages/react-reconciler/src/ReactReconcilerConstants.js @@ -15,5 +15,5 @@ export { ContinuousEventPriority, DefaultEventPriority, IdleEventPriority, -} from './ReactEventPriorities'; +} from './ReactEventPriorities.old'; export {ConcurrentRoot, LegacyRoot} from './ReactRootTags'; diff --git a/packages/react-reconciler/src/ReactStrictModeWarnings.new.js b/packages/react-reconciler/src/ReactStrictModeWarnings.new.js deleted file mode 100644 index a4a36a7aa3091..0000000000000 --- a/packages/react-reconciler/src/ReactStrictModeWarnings.new.js +++ /dev/null @@ -1,370 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - */ - -import type {Fiber} from './ReactInternalTypes'; - -import { - resetCurrentFiber as resetCurrentDebugFiberInDEV, - setCurrentFiber as setCurrentDebugFiberInDEV, -} from './ReactCurrentFiber'; -import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; -import {StrictLegacyMode} from './ReactTypeOfMode'; - -type FiberArray = Array; -type FiberToFiberComponentsMap = Map; - -const ReactStrictModeWarnings = { - recordUnsafeLifecycleWarnings: (fiber: Fiber, instance: any): void => {}, - flushPendingUnsafeLifecycleWarnings: (): void => {}, - recordLegacyContextWarning: (fiber: Fiber, instance: any): void => {}, - flushLegacyContextWarning: (): void => {}, - discardPendingWarnings: (): void => {}, -}; - -if (__DEV__) { - const findStrictRoot = (fiber: Fiber): Fiber | null => { - let maybeStrictRoot = null; - - let node: null | Fiber = fiber; - while (node !== null) { - if (node.mode & StrictLegacyMode) { - maybeStrictRoot = node; - } - node = node.return; - } - - return maybeStrictRoot; - }; - - const setToSortedString = set => { - const array = []; - set.forEach(value => { - array.push(value); - }); - return array.sort().join(', '); - }; - - let pendingComponentWillMountWarnings: Array = []; - let pendingUNSAFE_ComponentWillMountWarnings: Array = []; - let pendingComponentWillReceivePropsWarnings: Array = []; - let pendingUNSAFE_ComponentWillReceivePropsWarnings: Array = []; - let pendingComponentWillUpdateWarnings: Array = []; - let pendingUNSAFE_ComponentWillUpdateWarnings: Array = []; - - // Tracks components we have already warned about. - const didWarnAboutUnsafeLifecycles = new Set(); - - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = ( - fiber: Fiber, - instance: any, - ) => { - // Dedupe strategy: Warn once per component. - if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { - return; - } - - if ( - typeof instance.componentWillMount === 'function' && - // Don't warn about react-lifecycles-compat polyfilled components. - instance.componentWillMount.__suppressDeprecationWarning !== true - ) { - pendingComponentWillMountWarnings.push(fiber); - } - - if ( - fiber.mode & StrictLegacyMode && - typeof instance.UNSAFE_componentWillMount === 'function' - ) { - pendingUNSAFE_ComponentWillMountWarnings.push(fiber); - } - - if ( - typeof instance.componentWillReceiveProps === 'function' && - instance.componentWillReceiveProps.__suppressDeprecationWarning !== true - ) { - pendingComponentWillReceivePropsWarnings.push(fiber); - } - - if ( - fiber.mode & StrictLegacyMode && - typeof instance.UNSAFE_componentWillReceiveProps === 'function' - ) { - pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); - } - - if ( - typeof instance.componentWillUpdate === 'function' && - instance.componentWillUpdate.__suppressDeprecationWarning !== true - ) { - pendingComponentWillUpdateWarnings.push(fiber); - } - - if ( - fiber.mode & StrictLegacyMode && - typeof instance.UNSAFE_componentWillUpdate === 'function' - ) { - pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); - } - }; - - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = () => { - // We do an initial pass to gather component names - const componentWillMountUniqueNames = new Set(); - if (pendingComponentWillMountWarnings.length > 0) { - pendingComponentWillMountWarnings.forEach(fiber => { - componentWillMountUniqueNames.add( - getComponentNameFromFiber(fiber) || 'Component', - ); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingComponentWillMountWarnings = []; - } - - const UNSAFE_componentWillMountUniqueNames = new Set(); - if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { - pendingUNSAFE_ComponentWillMountWarnings.forEach(fiber => { - UNSAFE_componentWillMountUniqueNames.add( - getComponentNameFromFiber(fiber) || 'Component', - ); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - pendingUNSAFE_ComponentWillMountWarnings = []; - } - - const componentWillReceivePropsUniqueNames = new Set(); - if (pendingComponentWillReceivePropsWarnings.length > 0) { - pendingComponentWillReceivePropsWarnings.forEach(fiber => { - componentWillReceivePropsUniqueNames.add( - getComponentNameFromFiber(fiber) || 'Component', - ); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - - pendingComponentWillReceivePropsWarnings = []; - } - - const UNSAFE_componentWillReceivePropsUniqueNames = new Set(); - if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { - pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(fiber => { - UNSAFE_componentWillReceivePropsUniqueNames.add( - getComponentNameFromFiber(fiber) || 'Component', - ); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - } - - const componentWillUpdateUniqueNames = new Set(); - if (pendingComponentWillUpdateWarnings.length > 0) { - pendingComponentWillUpdateWarnings.forEach(fiber => { - componentWillUpdateUniqueNames.add( - getComponentNameFromFiber(fiber) || 'Component', - ); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - - pendingComponentWillUpdateWarnings = []; - } - - const UNSAFE_componentWillUpdateUniqueNames = new Set(); - if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { - pendingUNSAFE_ComponentWillUpdateWarnings.forEach(fiber => { - UNSAFE_componentWillUpdateUniqueNames.add( - getComponentNameFromFiber(fiber) || 'Component', - ); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } - - // Finally, we flush all the warnings - // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' - if (UNSAFE_componentWillMountUniqueNames.size > 0) { - const sortedNames = setToSortedString( - UNSAFE_componentWillMountUniqueNames, - ); - console.error( - 'Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + - 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + - '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + - '\nPlease update the following components: %s', - sortedNames, - ); - } - - if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { - const sortedNames = setToSortedString( - UNSAFE_componentWillReceivePropsUniqueNames, - ); - console.error( - 'Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + - 'and may indicate bugs in your code. ' + - 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + - '* Move data fetching code or side effects to componentDidUpdate.\n' + - "* If you're updating state whenever props change, " + - 'refactor your code to use memoization techniques or move it to ' + - 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + - '\nPlease update the following components: %s', - sortedNames, - ); - } - - if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { - const sortedNames = setToSortedString( - UNSAFE_componentWillUpdateUniqueNames, - ); - console.error( - 'Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + - 'and may indicate bugs in your code. ' + - 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + - '* Move data fetching code or side effects to componentDidUpdate.\n' + - '\nPlease update the following components: %s', - sortedNames, - ); - } - - if (componentWillMountUniqueNames.size > 0) { - const sortedNames = setToSortedString(componentWillMountUniqueNames); - - console.warn( - 'componentWillMount has been renamed, and is not recommended for use. ' + - 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + - '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + - '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + - 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + - 'To rename all deprecated lifecycles to their new names, you can run ' + - '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + - '\nPlease update the following components: %s', - sortedNames, - ); - } - - if (componentWillReceivePropsUniqueNames.size > 0) { - const sortedNames = setToSortedString( - componentWillReceivePropsUniqueNames, - ); - - console.warn( - 'componentWillReceiveProps has been renamed, and is not recommended for use. ' + - 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + - '* Move data fetching code or side effects to componentDidUpdate.\n' + - "* If you're updating state whenever props change, refactor your " + - 'code to use memoization techniques or move it to ' + - 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + - '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + - 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + - 'To rename all deprecated lifecycles to their new names, you can run ' + - '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + - '\nPlease update the following components: %s', - sortedNames, - ); - } - - if (componentWillUpdateUniqueNames.size > 0) { - const sortedNames = setToSortedString(componentWillUpdateUniqueNames); - - console.warn( - 'componentWillUpdate has been renamed, and is not recommended for use. ' + - 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + - '* Move data fetching code or side effects to componentDidUpdate.\n' + - '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + - 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + - 'To rename all deprecated lifecycles to their new names, you can run ' + - '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + - '\nPlease update the following components: %s', - sortedNames, - ); - } - }; - - let pendingLegacyContextWarning: FiberToFiberComponentsMap = new Map(); - - // Tracks components we have already warned about. - const didWarnAboutLegacyContext = new Set(); - - ReactStrictModeWarnings.recordLegacyContextWarning = ( - fiber: Fiber, - instance: any, - ) => { - const strictRoot = findStrictRoot(fiber); - if (strictRoot === null) { - console.error( - 'Expected to find a StrictMode component in a strict mode tree. ' + - 'This error is likely caused by a bug in React. Please file an issue.', - ); - return; - } - - // Dedup strategy: Warn once per component. - if (didWarnAboutLegacyContext.has(fiber.type)) { - return; - } - - let warningsForRoot = pendingLegacyContextWarning.get(strictRoot); - - if ( - fiber.type.contextTypes != null || - fiber.type.childContextTypes != null || - (instance !== null && typeof instance.getChildContext === 'function') - ) { - if (warningsForRoot === undefined) { - warningsForRoot = []; - pendingLegacyContextWarning.set(strictRoot, warningsForRoot); - } - warningsForRoot.push(fiber); - } - }; - - ReactStrictModeWarnings.flushLegacyContextWarning = () => { - ((pendingLegacyContextWarning: any): FiberToFiberComponentsMap).forEach( - (fiberArray: FiberArray, strictRoot) => { - if (fiberArray.length === 0) { - return; - } - const firstFiber = fiberArray[0]; - - const uniqueNames = new Set(); - fiberArray.forEach(fiber => { - uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); - didWarnAboutLegacyContext.add(fiber.type); - }); - - const sortedNames = setToSortedString(uniqueNames); - - try { - setCurrentDebugFiberInDEV(firstFiber); - console.error( - 'Legacy context API has been detected within a strict-mode tree.' + - '\n\nThe old API will be supported in all 16.x releases, but applications ' + - 'using it should migrate to the new version.' + - '\n\nPlease update the following components: %s' + - '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', - sortedNames, - ); - } finally { - resetCurrentDebugFiberInDEV(); - } - }, - ); - }; - - ReactStrictModeWarnings.discardPendingWarnings = () => { - pendingComponentWillMountWarnings = []; - pendingUNSAFE_ComponentWillMountWarnings = []; - pendingComponentWillReceivePropsWarnings = []; - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; - pendingComponentWillUpdateWarnings = []; - pendingUNSAFE_ComponentWillUpdateWarnings = []; - pendingLegacyContextWarning = new Map(); - }; -} - -export default ReactStrictModeWarnings; diff --git a/packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js b/packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js index 07fc29552b4f0..59510939e99e7 100644 --- a/packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js +++ b/packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.internal.js @@ -24,7 +24,7 @@ describe('ReactFiberHostContext', () => { ReactFiberReconciler = require('react-reconciler'); ConcurrentRoot = require('react-reconciler/src/ReactRootTags') .ConcurrentRoot; - DefaultEventPriority = require('react-reconciler/src/ReactEventPriorities') + DefaultEventPriority = require('react-reconciler/src/ReactEventPriorities.old') .DefaultEventPriority; }); diff --git a/packages/react-reconciler/src/__tests__/ReactIncrementalErrorReplay-test.internal.js b/packages/react-reconciler/src/__tests__/ReactIncrementalErrorReplay-test.internal.js index d77712bf544f8..78b8c68f05aae 100644 --- a/packages/react-reconciler/src/__tests__/ReactIncrementalErrorReplay-test.internal.js +++ b/packages/react-reconciler/src/__tests__/ReactIncrementalErrorReplay-test.internal.js @@ -21,10 +21,7 @@ describe('ReactIncrementalErrorReplay-test', () => { // This is the method we're going to test. // If this is no longer used, you can delete this test file.; - - const assignFiberPropertiesInDEV = gate(flags => flags.new) - ? require('../ReactFiber.new').assignFiberPropertiesInDEV - : require('../ReactFiber.old').assignFiberPropertiesInDEV; + const {assignFiberPropertiesInDEV} = require('../ReactFiber.old'); // Get a real fiber. const realFiber = ReactTestRenderer.create(
).root._currentFiber(); diff --git a/packages/react-reconciler/src/__tests__/ReactUpdaters-test.internal.js b/packages/react-reconciler/src/__tests__/ReactUpdaters-test.internal.js index b683a0e4905f7..35e33a7e4441f 100644 --- a/packages/react-reconciler/src/__tests__/ReactUpdaters-test.internal.js +++ b/packages/react-reconciler/src/__tests__/ReactUpdaters-test.internal.js @@ -84,10 +84,6 @@ describe('updaters', () => { 'react-reconciler/src/ReactFiberDevToolsHook.old', () => mockDevToolsHook, ); - jest.mock( - 'react-reconciler/src/ReactFiberDevToolsHook.new', - () => mockDevToolsHook, - ); React = require('react'); ReactDOM = require('react-dom'); diff --git a/packages/react-refresh/src/ReactFreshRuntime.js b/packages/react-refresh/src/ReactFreshRuntime.js index 6a936513a1e12..68a615044f90a 100644 --- a/packages/react-refresh/src/ReactFreshRuntime.js +++ b/packages/react-refresh/src/ReactFreshRuntime.js @@ -16,7 +16,7 @@ import type { ScheduleRoot, FindHostInstancesForRefresh, SetRefreshHandler, -} from 'react-reconciler/src/ReactFiberHotReloading'; +} from 'react-reconciler/src/ReactFiberHotReloading.old'; import type {ReactNodeList} from 'shared/ReactTypes'; import {REACT_MEMO_TYPE, REACT_FORWARD_REF_TYPE} from 'shared/ReactSymbols'; diff --git a/packages/react-test-renderer/src/ReactTestHostConfig.js b/packages/react-test-renderer/src/ReactTestHostConfig.js index a3230a541aa36..e2adfb201d037 100644 --- a/packages/react-test-renderer/src/ReactTestHostConfig.js +++ b/packages/react-test-renderer/src/ReactTestHostConfig.js @@ -8,7 +8,7 @@ */ import isArray from 'shared/isArray'; -import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities'; +import {DefaultEventPriority} from 'react-reconciler/src/ReactEventPriorities.old'; export type Type = string; export type Props = Object; diff --git a/packages/react-test-renderer/src/ReactTestRenderer.js b/packages/react-test-renderer/src/ReactTestRenderer.js index 4645047977113..ae6834d0b6dc4 100644 --- a/packages/react-test-renderer/src/ReactTestRenderer.js +++ b/packages/react-test-renderer/src/ReactTestRenderer.js @@ -23,7 +23,7 @@ import { flushSync, injectIntoDevTools, batchedUpdates, -} from 'react-reconciler/src/ReactFiberReconciler'; +} from 'react-reconciler/src/ReactFiberReconciler.old'; import {findCurrentFiberUsingSlowPath} from 'react-reconciler/src/ReactFiberTreeReflection'; import { Fragment, diff --git a/packages/react/src/ReactCurrentBatchConfig.js b/packages/react/src/ReactCurrentBatchConfig.js index f627087618764..88068338f82b2 100644 --- a/packages/react/src/ReactCurrentBatchConfig.js +++ b/packages/react/src/ReactCurrentBatchConfig.js @@ -7,7 +7,7 @@ * @flow */ -import type {BatchConfigTransition} from 'react-reconciler/src/ReactFiberTracingMarkerComponent.new'; +import type {BatchConfigTransition} from 'react-reconciler/src/ReactFiberTracingMarkerComponent.old'; type BatchConfig = { transition: BatchConfigTransition | null, diff --git a/packages/shared/ReactFeatureFlags.js b/packages/shared/ReactFeatureFlags.js index 23e74d128cca8..d3c128ae77bbe 100644 --- a/packages/shared/ReactFeatureFlags.js +++ b/packages/shared/ReactFeatureFlags.js @@ -68,10 +68,6 @@ export const enableScopeAPI = false; // Experimental Create Event Handle API. export const enableCreateEventHandleAPI = false; -// This controls whether you get the `.old` modules or the `.new` modules in -// the react-reconciler package. -export const enableNewReconciler = false; - // Support legacy Primer support on internal FB www export const enableLegacyFBSupport = false; diff --git a/packages/shared/forks/ReactFeatureFlags.native-fb.js b/packages/shared/forks/ReactFeatureFlags.native-fb.js index ac5f8de086201..8a6f0dc811f90 100644 --- a/packages/shared/forks/ReactFeatureFlags.native-fb.js +++ b/packages/shared/forks/ReactFeatureFlags.native-fb.js @@ -64,7 +64,6 @@ export const disableNativeComponentFrames = false; export const skipUnmountedBoundaries = false; export const deletedTreeCleanUpLevel = 3; export const enableGetInspectorDataForInstanceInProduction = true; -export const enableNewReconciler = false; export const deferRenderPhaseUpdateToNextBatch = false; export const createRootStrictEffectsByDefault = false; diff --git a/packages/shared/forks/ReactFeatureFlags.native-oss.js b/packages/shared/forks/ReactFeatureFlags.native-oss.js index 994fab5272e2c..d2e8863e9128a 100644 --- a/packages/shared/forks/ReactFeatureFlags.native-oss.js +++ b/packages/shared/forks/ReactFeatureFlags.native-oss.js @@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false; export const skipUnmountedBoundaries = false; export const deletedTreeCleanUpLevel = 3; export const enableGetInspectorDataForInstanceInProduction = false; -export const enableNewReconciler = false; export const deferRenderPhaseUpdateToNextBatch = false; export const createRootStrictEffectsByDefault = false; diff --git a/packages/shared/forks/ReactFeatureFlags.test-renderer.js b/packages/shared/forks/ReactFeatureFlags.test-renderer.js index 2105a3e303ad2..c3a096acef8c1 100644 --- a/packages/shared/forks/ReactFeatureFlags.test-renderer.js +++ b/packages/shared/forks/ReactFeatureFlags.test-renderer.js @@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false; export const skipUnmountedBoundaries = false; export const deletedTreeCleanUpLevel = 3; export const enableGetInspectorDataForInstanceInProduction = false; -export const enableNewReconciler = false; export const deferRenderPhaseUpdateToNextBatch = false; export const createRootStrictEffectsByDefault = false; diff --git a/packages/shared/forks/ReactFeatureFlags.test-renderer.native.js b/packages/shared/forks/ReactFeatureFlags.test-renderer.native.js index a9574a110aa24..2f88033de445c 100644 --- a/packages/shared/forks/ReactFeatureFlags.test-renderer.native.js +++ b/packages/shared/forks/ReactFeatureFlags.test-renderer.native.js @@ -46,7 +46,6 @@ export const disableNativeComponentFrames = false; export const skipUnmountedBoundaries = false; export const deletedTreeCleanUpLevel = 3; export const enableGetInspectorDataForInstanceInProduction = false; -export const enableNewReconciler = false; export const deferRenderPhaseUpdateToNextBatch = false; export const enableSuspenseAvoidThisFallback = false; export const enableSuspenseAvoidThisFallbackFizz = false; diff --git a/packages/shared/forks/ReactFeatureFlags.test-renderer.www.js b/packages/shared/forks/ReactFeatureFlags.test-renderer.www.js index 3c0de034a7bf7..de05d1a8c1d9b 100644 --- a/packages/shared/forks/ReactFeatureFlags.test-renderer.www.js +++ b/packages/shared/forks/ReactFeatureFlags.test-renderer.www.js @@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false; export const skipUnmountedBoundaries = false; export const deletedTreeCleanUpLevel = 3; export const enableGetInspectorDataForInstanceInProduction = false; -export const enableNewReconciler = false; export const deferRenderPhaseUpdateToNextBatch = false; export const createRootStrictEffectsByDefault = false; diff --git a/packages/shared/forks/ReactFeatureFlags.testing.js b/packages/shared/forks/ReactFeatureFlags.testing.js index 3e7ec4d238c2e..a239d108dc00f 100644 --- a/packages/shared/forks/ReactFeatureFlags.testing.js +++ b/packages/shared/forks/ReactFeatureFlags.testing.js @@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false; export const skipUnmountedBoundaries = false; export const deletedTreeCleanUpLevel = 3; export const enableGetInspectorDataForInstanceInProduction = false; -export const enableNewReconciler = false; export const deferRenderPhaseUpdateToNextBatch = false; export const createRootStrictEffectsByDefault = false; diff --git a/packages/shared/forks/ReactFeatureFlags.testing.www.js b/packages/shared/forks/ReactFeatureFlags.testing.www.js index 56fee4169077d..441b7647bd4d8 100644 --- a/packages/shared/forks/ReactFeatureFlags.testing.www.js +++ b/packages/shared/forks/ReactFeatureFlags.testing.www.js @@ -54,7 +54,6 @@ export const disableNativeComponentFrames = false; export const skipUnmountedBoundaries = true; export const deletedTreeCleanUpLevel = 3; export const enableGetInspectorDataForInstanceInProduction = false; -export const enableNewReconciler = false; export const deferRenderPhaseUpdateToNextBatch = false; export const createRootStrictEffectsByDefault = false; diff --git a/packages/shared/forks/ReactFeatureFlags.www.js b/packages/shared/forks/ReactFeatureFlags.www.js index 513c7562c7f36..1a06367d129ef 100644 --- a/packages/shared/forks/ReactFeatureFlags.www.js +++ b/packages/shared/forks/ReactFeatureFlags.www.js @@ -95,11 +95,6 @@ export const enableComponentStackLocations = true; export const disableTextareaChildren = __EXPERIMENTAL__; -// Enable forked reconciler. Piggy-backing on the "variant" global so that we -// don't have to add another test dimension. The build system will compile this -// to the correct value. -export const enableNewReconciler = __VARIANT__; - export const allowConcurrentByDefault = true; export const deletedTreeCleanUpLevel = 3; diff --git a/scripts/eslint-rules/__tests__/no-cross-fork-imports-test.internal.js b/scripts/eslint-rules/__tests__/no-cross-fork-imports-test.internal.js deleted file mode 100644 index e2fc5e2ce61ee..0000000000000 --- a/scripts/eslint-rules/__tests__/no-cross-fork-imports-test.internal.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @emails react-core - */ - -'use strict'; - -const rule = require('../no-cross-fork-imports'); -const {RuleTester} = require('eslint'); -const ruleTester = new RuleTester({ - parserOptions: { - ecmaVersion: 8, - sourceType: 'module', - }, -}); - -ruleTester.run('eslint-rules/no-cross-fork-imports', rule, { - valid: [ - { - code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop';", - filename: 'ReactFiberWorkLoop.js', - }, - { - code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';", - filename: 'ReactFiberWorkLoop.new.js', - }, - { - code: - "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new.js';", - filename: 'ReactFiberWorkLoop.new.js', - }, - { - code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';", - filename: 'ReactFiberWorkLoop.old.js', - }, - { - code: - "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old.js';", - filename: 'ReactFiberWorkLoop.old.js', - }, - ], - invalid: [ - { - code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';", - filename: 'ReactFiberWorkLoop.old.js', - errors: [ - { - message: - 'A module that belongs to the old fork cannot import a module ' + - 'from the new fork.', - }, - ], - output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';", - }, - { - code: - "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new.js';", - filename: 'ReactFiberWorkLoop.old.js', - errors: [ - { - message: - 'A module that belongs to the old fork cannot import a module ' + - 'from the new fork.', - }, - ], - output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';", - }, - { - code: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old';", - filename: 'ReactFiberWorkLoop.new.js', - errors: [ - { - message: - 'A module that belongs to the new fork cannot import a module ' + - 'from the old fork.', - }, - ], - output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';", - }, - { - code: - "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.old.js';", - filename: 'ReactFiberWorkLoop.new.js', - errors: [ - { - message: - 'A module that belongs to the new fork cannot import a module ' + - 'from the old fork.', - }, - ], - output: "import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop.new';", - }, - { - code: "export {DiscreteEventPriority} from './ReactFiberLane.old.js';", - filename: 'ReactFiberReconciler.new.js', - errors: [ - { - message: - 'A module that belongs to the new fork cannot import a module ' + - 'from the old fork.', - }, - ], - output: "export {DiscreteEventPriority} from './ReactFiberLane.new';", - }, - { - code: "export {DiscreteEventPriority} from './ReactFiberLane.new.js';", - filename: 'ReactFiberReconciler.old.js', - errors: [ - { - message: - 'A module that belongs to the old fork cannot import a module ' + - 'from the new fork.', - }, - ], - output: "export {DiscreteEventPriority} from './ReactFiberLane.old';", - }, - ], -}); diff --git a/scripts/eslint-rules/__tests__/no-cross-fork-types-test.internal.js b/scripts/eslint-rules/__tests__/no-cross-fork-types-test.internal.js deleted file mode 100644 index 8e3d477bcbc0a..0000000000000 --- a/scripts/eslint-rules/__tests__/no-cross-fork-types-test.internal.js +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @emails react-core - */ - -'use strict'; - -const rule = require('../no-cross-fork-types'); -const {RuleTester} = require('eslint'); -const ruleTester = new RuleTester({ - parserOptions: { - ecmaVersion: 8, - sourceType: 'module', - }, -}); - -const newAccessWarning = - 'Field cannot be accessed inside the old reconciler fork, only the ' + - 'new fork.'; - -const oldAccessWarning = - 'Field cannot be accessed inside the new reconciler fork, only the ' + - 'old fork.'; - -ruleTester.run('eslint-rules/no-cross-fork-types', rule, { - valid: [ - { - code: ` -const a = obj.key_old; -const b = obj.key_new; -const {key_old, key_new} = obj; -`, - filename: 'ReactFiberWorkLoop.js', - }, - { - code: ` -const a = obj.key_old; -const {key_old} = obj; -`, - filename: 'ReactFiberWorkLoop.old.js', - }, - { - code: ` -const a = obj.key_new; -const {key_new} = obj; -`, - filename: 'ReactFiberWorkLoop.new.js', - }, - ], - invalid: [ - { - code: 'const a = obj.key_new;', - filename: 'ReactFiberWorkLoop.old.js', - errors: [{message: newAccessWarning}], - }, - { - code: 'const a = obj.key_old;', - filename: 'ReactFiberWorkLoop.new.js', - errors: [{message: oldAccessWarning}], - }, - - { - code: 'const {key_new} = obj;', - filename: 'ReactFiberWorkLoop.old.js', - errors: [{message: newAccessWarning}], - }, - { - code: 'const {key_old} = obj;', - filename: 'ReactFiberWorkLoop.new.js', - errors: [{message: oldAccessWarning}], - }, - { - code: 'const subtreeFlags = obj.subtreeFlags;', - filename: 'ReactFiberWorkLoop.old.js', - options: [{new: ['subtreeFlags']}], - errors: [{message: newAccessWarning}], - }, - { - code: 'const firstEffect = obj.firstEffect;', - filename: 'ReactFiberWorkLoop.new.js', - options: [{old: ['firstEffect']}], - errors: [{message: oldAccessWarning}], - }, - ], -}); diff --git a/scripts/eslint-rules/index.js b/scripts/eslint-rules/index.js index 3bf0fb61521da..f66c49a80e40c 100644 --- a/scripts/eslint-rules/index.js +++ b/scripts/eslint-rules/index.js @@ -7,8 +7,6 @@ module.exports = { 'warning-args': require('./warning-args'), 'prod-error-codes': require('./prod-error-codes'), 'no-production-logging': require('./no-production-logging'), - 'no-cross-fork-imports': require('./no-cross-fork-imports'), - 'no-cross-fork-types': require('./no-cross-fork-types'), 'safe-string-coercion': require('./safe-string-coercion'), }, }; diff --git a/scripts/eslint-rules/no-cross-fork-imports.js b/scripts/eslint-rules/no-cross-fork-imports.js deleted file mode 100644 index c9b5b5c74ac14..0000000000000 --- a/scripts/eslint-rules/no-cross-fork-imports.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @emails react-core - */ - -'use strict'; - -function isOldFork(filename) { - return filename.endsWith('.old.js') || filename.endsWith('.old'); -} - -function isNewFork(filename) { - return filename.endsWith('.new.js') || filename.endsWith('.new'); -} - -module.exports = { - meta: { - type: 'problem', - fixable: 'code', - }, - create(context) { - const sourceFilename = context.getFilename(); - - if (isOldFork(sourceFilename)) { - const visitor = node => { - const sourceNode = node.source; - if (sourceNode === null) { - return; - } - const filename = sourceNode.value; - if (isNewFork(filename)) { - context.report({ - node: sourceNode, - message: - 'A module that belongs to the old fork cannot import a module ' + - 'from the new fork.', - fix(fixer) { - return fixer.replaceText( - sourceNode, - `'${filename.replace(/\.new(\.js)?$/, '.old')}'` - ); - }, - }); - } - }; - return { - ImportDeclaration: visitor, - ExportNamedDeclaration: visitor, - }; - } - - if (isNewFork(sourceFilename)) { - const visitor = node => { - const sourceNode = node.source; - if (sourceNode === null) { - return; - } - const filename = sourceNode.value; - if (isOldFork(filename)) { - context.report({ - node: sourceNode, - message: - 'A module that belongs to the new fork cannot import a module ' + - 'from the old fork.', - fix(fixer) { - return fixer.replaceText( - sourceNode, - `'${filename.replace(/\.old(\.js)?$/, '.new')}'` - ); - }, - }); - } - }; - - return { - ImportDeclaration: visitor, - ExportNamedDeclaration: visitor, - }; - } - - return {}; - }, -}; diff --git a/scripts/eslint-rules/no-cross-fork-types.js b/scripts/eslint-rules/no-cross-fork-types.js deleted file mode 100644 index 2745137db50fa..0000000000000 --- a/scripts/eslint-rules/no-cross-fork-types.js +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @emails react-core - */ - -/* eslint-disable no-for-of-loops/no-for-of-loops */ - -'use strict'; - -function isOldFork(filename) { - return filename.endsWith('.old.js') || filename.endsWith('.old'); -} - -function isNewFork(filename) { - return filename.endsWith('.new.js') || filename.endsWith('.new'); -} - -function warnIfNewField(context, newFields, identifier) { - const name = identifier.name; - if (name.endsWith('_new') || (newFields !== null && newFields.has(name))) { - context.report({ - node: identifier, - message: - 'Field cannot be accessed inside the old reconciler fork, only the ' + - 'new fork.', - }); - } -} - -function warnIfOldField(context, oldFields, identifier) { - const name = identifier.name; - if (name.endsWith('_old') || (oldFields !== null && oldFields.has(name))) { - context.report({ - node: identifier, - message: - 'Field cannot be accessed inside the new reconciler fork, only the ' + - 'old fork.', - }); - } -} - -module.exports = { - meta: { - type: 'problem', - }, - create(context) { - const sourceFilename = context.getFilename(); - - if (isOldFork(sourceFilename)) { - const options = context.options; - let newFields = null; - if (options !== null) { - for (const option of options) { - if (option.new !== undefined) { - if (newFields === null) { - newFields = new Set(option.new); - } else { - for (const field of option.new) { - newFields.add(field); - } - } - } - } - } - return { - MemberExpression(node) { - const property = node.property; - if (property.type === 'Identifier') { - warnIfNewField(context, newFields, property); - } - }, - - ObjectPattern(node) { - for (const property of node.properties) { - const key = property.key; - if (key.type === 'Identifier') { - warnIfNewField(context, newFields, key); - } - } - }, - }; - } - - if (isNewFork(sourceFilename)) { - const options = context.options; - let oldFields = null; - if (options !== null) { - for (const option of options) { - if (option.old !== undefined) { - if (oldFields === null) { - oldFields = new Set(option.old); - } else { - for (const field of option.new) { - oldFields.add(field); - } - } - } - } - } - return { - MemberExpression(node) { - const property = node.property; - if (property.type === 'Identifier') { - warnIfOldField(context, oldFields, property); - } - }, - - ObjectPattern(node) { - for (const property of node.properties) { - const key = property.key; - if (key.type === 'Identifier') { - warnIfOldField(context, oldFields, key); - } - } - }, - }; - } - - return {}; - }, -}; diff --git a/scripts/jest/TestFlags.js b/scripts/jest/TestFlags.js index ed792b948f23e..e919aec5ffc9f 100644 --- a/scripts/jest/TestFlags.js +++ b/scripts/jest/TestFlags.js @@ -75,10 +75,6 @@ function getTestFlags() { // doesn't exist. return new Proxy( { - // Feature flag aliases - old: featureFlags.enableNewReconciler === false, - new: featureFlags.enableNewReconciler === true, - channel: releaseChannel, modern: releaseChannel === 'modern', classic: releaseChannel === 'classic', diff --git a/scripts/jest/setupHostConfigs.js b/scripts/jest/setupHostConfigs.js index 9f25e04bcf8f5..cd763c57ff6f2 100644 --- a/scripts/jest/setupHostConfigs.js +++ b/scripts/jest/setupHostConfigs.js @@ -58,14 +58,6 @@ jest.mock('react/react.shared-subset', () => { return jest.requireActual(resolvedEntryPoint); }); -jest.mock('react-reconciler/src/ReactFiberReconciler', () => { - return jest.requireActual( - __VARIANT__ - ? 'react-reconciler/src/ReactFiberReconciler.new' - : 'react-reconciler/src/ReactFiberReconciler.old' - ); -}); - // When testing the custom renderer code path through `react-reconciler`, // turn the export into a function, and use the argument as host config. const shimHostConfigPath = 'react-reconciler/src/ReactFiberHostConfig'; diff --git a/scripts/merge-fork/README.md b/scripts/merge-fork/README.md deleted file mode 100644 index 2b01bfe156bdd..0000000000000 --- a/scripts/merge-fork/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# merge-fork - -Script for syncing changes between forked modules. - -## Basic example - -```sh -yarn merge-fork --base-dir=packages/react-reconciler/src ReactFiberWorkLoop -``` - -This will take all the changes in `ReactFiberWorkLoop.new.js` and apply them to `ReactFiberWorkLoop.old.js`. - -## Syncing multiple modules at once - -You can merge multiple modules at a time: - -```sh -yarn merge-fork \ - --base-dir=packages/react-reconciler/src \ - ReactFiberWorkLoop \ - ReactFiberBeginWork \ - ReactFiberCompleteWork \ - ReactFiberCommitWork -``` - -## Syncing modules with different names - -You can provide explicit "old" and "new" file names. This only works for one module at a time: - -```sh -yarn merge-fork \ - --base-dir=packages/react-reconciler/src \ - --old=ReactFiberExpirationTime.js \ - --new=ReactFiberLane.js -``` - -## Syncing modules in the opposite direction (old -> new) - -The default is to merge changes from the new module to the old one. To merge changes in the opposite direction, use `--reverse`. - -```sh -yarn merge-fork \ - --reverse \ - --base-dir=packages/react-reconciler/src \ - ReactFiberWorkLoop -``` - -## Comparing changes to an older base rev - -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: - -```sh -yarn merge-fork \ - --base-ref=$(git merge-base HEAD origin/main) - --base-dir=packages/react-reconciler/src \ - ReactFiberWorkLoop -``` - diff --git a/scripts/merge-fork/forked-revisions b/scripts/merge-fork/forked-revisions deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/scripts/merge-fork/merge-fork.js b/scripts/merge-fork/merge-fork.js deleted file mode 100644 index 1b054dd395cad..0000000000000 --- a/scripts/merge-fork/merge-fork.js +++ /dev/null @@ -1,109 +0,0 @@ -'use strict'; - -/* eslint-disable no-for-of-loops/no-for-of-loops */ - -const {writeFileSync} = require('fs'); -const path = require('path'); -const {spawnSync} = require('child_process'); -const minimist = require('minimist'); -const tmp = require('tmp'); - -const argv = minimist(process.argv.slice(2), { - boolean: ['reverse'], - default: { - 'base-ref': 'HEAD', - }, -}); - -const baseRef = argv['base-ref']; -const baseDir = argv['base-dir']; - -function resolvePath(file) { - return baseDir !== undefined ? path.join(baseDir, file) : file; -} - -function getTransforms() { - const old = argv.old; - const base = argv.base; - const _new = argv.new; - if (old !== undefined) { - if (_new === undefined) { - throw Error('Cannot provide --old without also providing --new'); - } - const oldPath = resolvePath(old); - const newPath = resolvePath(_new); - - let basePath; - let fromPath; - let toPath; - if (argv.reverse) { - fromPath = oldPath; - toPath = newPath; - basePath = base !== undefined ? resolvePath(basePath) : oldPath; - } else { - fromPath = newPath; - toPath = oldPath; - basePath = base !== undefined ? resolvePath(basePath) : newPath; - } - - return [ - { - base: basePath, - from: fromPath, - to: toPath, - }, - ]; - } else if (_new !== undefined) { - throw Error('Cannot provide --new without also providing --old'); - } - return argv._.map(filename => { - const oldPath = resolvePath(filename + '.old.js'); - const newPath = resolvePath(filename + '.new.js'); - - let basePath; - let fromPath; - let toPath; - if (argv.reverse) { - fromPath = oldPath; - toPath = newPath; - basePath = base !== undefined ? resolvePath(basePath) : oldPath; - } else { - fromPath = newPath; - toPath = oldPath; - basePath = base !== undefined ? resolvePath(basePath) : newPath; - } - return { - base: basePath, - from: fromPath, - to: toPath, - }; - }); -} - -for (const {base: baseFilename, from, to} of getTransforms()) { - // Write the base file contents to a temporary file - const gitShowResult = spawnSync( - 'git', - ['show', `${baseRef}:${baseFilename}`], - { - stdio: 'pipe', - } - ); - if (gitShowResult.status !== 0) { - console.error(String(gitShowResult.stderr)); - continue; - } - - const baseFileContents = gitShowResult.stdout; - const base = tmp.fileSync().name; - writeFileSync(base, baseFileContents); - - // Run the merge with `git merge-file` - const mergeFileResult = spawnSync('git', ['merge-file', to, base, from], { - stdio: 'pipe', - }); - - if (mergeFileResult.status !== 0) { - console.error(String(mergeFileResult.stderr)); - } -} diff --git a/scripts/merge-fork/replace-fork.js b/scripts/merge-fork/replace-fork.js deleted file mode 100644 index 8369d271bb2b3..0000000000000 --- a/scripts/merge-fork/replace-fork.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -/* eslint-disable no-for-of-loops/no-for-of-loops */ - -// Copies the contents of the new fork into the old fork - -const chalk = require('chalk'); -const {promisify} = require('util'); -const glob = promisify(require('glob')); -const {execSync, spawnSync} = require('child_process'); -const fs = require('fs'); -const minimist = require('minimist'); - -const stat = promisify(fs.stat); -const copyFile = promisify(fs.copyFile); - -const argv = minimist(process.argv.slice(2), { - boolean: ['reverse'], -}); - -async function main() { - const status = execSync('git status').toString(); - const hadUnstagedChanges = status.includes('Changes not staged for commit'); - if (hadUnstagedChanges) { - const readline = require('readline'); - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }); - - await new Promise(resolve => { - rl.question( - `\n${chalk.yellow.bold( - 'Unstaged changes were found in repository.' - )} Do you want to continue? (Y/n) `, - input => { - switch (input.trim().toLowerCase()) { - case '': - case 'y': - case 'yes': - resolve(); - break; - default: - console.log('No modifications were made.'); - process.exit(0); - break; - } - } - ); - }); - } - - const oldFilenames = await glob('packages/react-reconciler/**/*.old.js'); - await Promise.all(oldFilenames.map(unforkFile)); - - // Use ESLint to autofix imports - const command = spawnSync('yarn', ['linc', '--fix'], { - stdio: ['inherit', 'inherit', 'pipe'], - }); - if (command.status === 1) { - console.log( - chalk.bold.red('\nreplace-fork script failed with the following error:') - ); - console.error(Error(command.stderr)); - - // If eslint crashes, it may not have successfully fixed all the imports, - // which would leave the reconciler files in an inconsistent stat. - // It would be nice to clean up the working directory in this case, - // but it's only safe to do that if we aren't going to override any previous changes. - if (!hadUnstagedChanges) { - spawnSync('git', ['checkout', '.']); - } else { - console.log( - `\n${chalk.yellow.bold( - 'Unstaged changes were present when `replace-fork` was run.' - )} ` + - `To cleanup the repository run:\n ${chalk.bold( - 'git checkout packages/react-reconciler' - )}` - ); - } - - process.exit(1); - } else { - process.exit(0); - } -} - -async function unforkFile(oldFilename) { - let oldStats; - try { - oldStats = await stat(oldFilename); - } catch { - return; - } - if (!oldStats.isFile()) { - return; - } - - const newFilename = oldFilename.replace(/\.old.js$/, '.new.js'); - let newStats; - try { - newStats = await stat(newFilename); - } catch { - return; - } - if (!newStats.isFile()) { - return; - } - - if (argv.reverse) { - await copyFile(oldFilename, newFilename); - } else { - await copyFile(newFilename, oldFilename); - } -} - -main(); diff --git a/scripts/rollup/build.js b/scripts/rollup/build.js index daec05ff1b650..9bd7072872035 100644 --- a/scripts/rollup/build.js +++ b/scripts/rollup/build.js @@ -361,9 +361,6 @@ function getPlugins( __UMD__: isUMDBundle ? 'true' : 'false', 'process.env.NODE_ENV': isProduction ? "'production'" : "'development'", __EXPERIMENTAL__, - // Enable forked reconciler. - // NOTE: I did not put much thought into how to configure this. - __VARIANT__: bundle.enableNewReconciler === true, }), // The CommonJS plugin *only* exists to pull "art" into "react-art". // I'm going to port "art" to ES modules to avoid this problem. diff --git a/scripts/rollup/bundles.js b/scripts/rollup/bundles.js index 23a2089a7351a..271e5770b87e3 100644 --- a/scripts/rollup/bundles.js +++ b/scripts/rollup/bundles.js @@ -169,7 +169,6 @@ const bundles = [ bundleTypes: [FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING], entry: 'react-dom', global: 'ReactDOMForked', - enableNewReconciler: true, minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: true, externals: ['react'], diff --git a/scripts/rollup/forks.js b/scripts/rollup/forks.js index d1f9fbd71ce70..93833be1467b4 100644 --- a/scripts/rollup/forks.js +++ b/scripts/rollup/forks.js @@ -224,66 +224,6 @@ const forks = Object.freeze({ } }, - './packages/react-reconciler/src/ReactFiberReconciler.js': ( - bundleType, - entry, - dependencies, - moduleType, - bundle - ) => { - if (bundle.enableNewReconciler) { - switch (bundleType) { - case FB_WWW_DEV: - case FB_WWW_PROD: - case FB_WWW_PROFILING: - // Use the forked version of the reconciler - return './packages/react-reconciler/src/ReactFiberReconciler.new.js'; - } - } - // Otherwise, use the non-forked version. - return './packages/react-reconciler/src/ReactFiberReconciler.old.js'; - }, - - './packages/react-reconciler/src/ReactEventPriorities.js': ( - bundleType, - entry, - dependencies, - moduleType, - bundle - ) => { - if (bundle.enableNewReconciler) { - switch (bundleType) { - case FB_WWW_DEV: - case FB_WWW_PROD: - case FB_WWW_PROFILING: - // Use the forked version of the reconciler - return './packages/react-reconciler/src/ReactEventPriorities.new.js'; - } - } - // Otherwise, use the non-forked version. - return './packages/react-reconciler/src/ReactEventPriorities.old.js'; - }, - - './packages/react-reconciler/src/ReactFiberHotReloading.js': ( - bundleType, - entry, - dependencies, - moduleType, - bundle - ) => { - if (bundle.enableNewReconciler) { - switch (bundleType) { - case FB_WWW_DEV: - case FB_WWW_PROD: - case FB_WWW_PROFILING: - // Use the forked version of the reconciler - return './packages/react-reconciler/src/ReactFiberHotReloading.new.js'; - } - } - // Otherwise, use the non-forked version. - return './packages/react-reconciler/src/ReactFiberHotReloading.old.js'; - }, - // Different dialogs for caught errors. './packages/react-reconciler/src/ReactFiberErrorDialog.js': ( bundleType,