diff --git a/.github/workflows/compiler_playground.yml b/.github/workflows/compiler_playground.yml index d3d2420ee2..e53158bf60 100644 --- a/.github/workflows/compiler_playground.yml +++ b/.github/workflows/compiler_playground.yml @@ -36,8 +36,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: compiler-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} + path: | + **/node_modules + key: compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} - run: yarn install --frozen-lockfile - run: npx playwright install --with-deps chromium - run: CI=true yarn test diff --git a/.github/workflows/compiler_prereleases.yml b/.github/workflows/compiler_prereleases.yml index 4f4954dd95..8baede7ac2 100644 --- a/.github/workflows/compiler_prereleases.yml +++ b/.github/workflows/compiler_prereleases.yml @@ -46,8 +46,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: compiler-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} + path: | + **/node_modules + key: compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} - run: yarn install --frozen-lockfile - name: Publish packages to npm run: | diff --git a/.github/workflows/compiler_typescript.yml b/.github/workflows/compiler_typescript.yml index d3b9517c8e..dbde1b9962 100644 --- a/.github/workflows/compiler_typescript.yml +++ b/.github/workflows/compiler_typescript.yml @@ -46,8 +46,9 @@ jobs: - name: Restore cached node_modules uses: actions/cache@v4 with: - path: "**/node_modules" - key: compiler-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} + path: | + **/node_modules + key: compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} - run: yarn install --frozen-lockfile - run: yarn workspace babel-plugin-react-compiler lint @@ -66,8 +67,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: compiler-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} + path: | + **/node_modules + key: compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} - run: yarn install --frozen-lockfile - run: yarn workspace babel-plugin-react-compiler jest @@ -90,8 +92,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: compiler-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} + path: | + **/node_modules + key: compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/**/yarn.lock') }} - run: yarn install --frozen-lockfile - run: xvfb-run -a yarn workspace ${{ matrix.workspace_name }} test if: runner.os == 'Linux' && matrix.workspace_name == 'react-forgive' diff --git a/.github/workflows/devtools_regression_tests.yml b/.github/workflows/devtools_regression_tests.yml index 4babfeefb0..9399b80f0e 100644 --- a/.github/workflows/devtools_regression_tests.yml +++ b/.github/workflows/devtools_regression_tests.yml @@ -29,8 +29,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-release-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} + path: | + **/node_modules + key: runtime-release-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -63,8 +64,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -120,8 +122,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - run: yarn install --frozen-lockfile - name: Restore all archived build artifacts uses: actions/download-artifact@v4 @@ -154,8 +157,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - run: yarn install --frozen-lockfile - name: Restore all archived build artifacts uses: actions/download-artifact@v4 diff --git a/.github/workflows/runtime_build_and_test.yml b/.github/workflows/runtime_build_and_test.yml index d53e352fbb..1cb04920e8 100644 --- a/.github/workflows/runtime_build_and_test.yml +++ b/.github/workflows/runtime_build_and_test.yml @@ -55,8 +55,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -79,8 +80,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -105,8 +107,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -153,16 +156,21 @@ jobs: with: node-version-file: '.nvmrc' cache: yarn - cache-dependency-path: yarn.lock + cache-dependency-path: | + yarn.lock + compiler/yarn.lock - name: Restore cached node_modules uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-and-compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile + - run: yarn install --frozen-lockfile + working-directory: compiler - run: yarn test ${{ matrix.params }} --ci --shard=${{ matrix.shard }} # ----- BUILD ----- @@ -183,7 +191,9 @@ jobs: with: node-version-file: '.nvmrc' cache: yarn - cache-dependency-path: yarn.lock + cache-dependency-path: | + yarn.lock + compiler/yarn.lock - uses: actions/setup-java@v4 with: distribution: temurin @@ -192,11 +202,14 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-and-compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile + - run: yarn install --frozen-lockfile + working-directory: compiler - run: yarn build --index=${{ matrix.worker_id }} --total=20 --r=${{ matrix.release_channel }} --ci env: CI: github @@ -261,16 +274,21 @@ jobs: with: node-version-file: '.nvmrc' cache: yarn - cache-dependency-path: yarn.lock + cache-dependency-path: | + yarn.lock + compiler/yarn.lock - name: Restore cached node_modules uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-and-compiler-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile + - run: yarn install --frozen-lockfile + working-directory: compiler - name: Restore archived build uses: actions/download-artifact@v4 with: @@ -298,8 +316,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -345,8 +364,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -380,8 +400,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -412,8 +433,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: fixtures_dom-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: fixtures_dom-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -455,8 +477,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: fixtures_flight-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: fixtures_flight-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -517,8 +540,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -568,8 +592,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -605,8 +630,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile diff --git a/.github/workflows/runtime_commit_artifacts.yml b/.github/workflows/runtime_commit_artifacts.yml index b136c60bb7..9e60606210 100644 --- a/.github/workflows/runtime_commit_artifacts.yml +++ b/.github/workflows/runtime_commit_artifacts.yml @@ -73,8 +73,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-release-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} + path: | + **/node_modules + key: runtime-release-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile diff --git a/.github/workflows/runtime_eslint_plugin_e2e.yml b/.github/workflows/runtime_eslint_plugin_e2e.yml index f8878548c0..8b8222721c 100644 --- a/.github/workflows/runtime_eslint_plugin_e2e.yml +++ b/.github/workflows/runtime_eslint_plugin_e2e.yml @@ -35,16 +35,21 @@ jobs: with: node-version-file: '.nvmrc' cache: yarn - cache-dependency-path: yarn.lock + cache-dependency-path: | + yarn.lock + compiler/yarn.lock - name: Restore cached node_modules uses: actions/cache@v4 id: node_modules with: - path: "node_modules" - key: runtime-eslint_e2e-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + path: | + **/node_modules + key: runtime-and-compiler-eslint_e2e-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile + - run: yarn install --frozen-lockfile + working-directory: compiler - name: Build plugin working-directory: fixtures/eslint-v${{ matrix.eslint_major }} run: node build.mjs diff --git a/.github/workflows/runtime_prereleases.yml b/.github/workflows/runtime_prereleases.yml index e52bed6bb1..293e5f2ce9 100644 --- a/.github/workflows/runtime_prereleases.yml +++ b/.github/workflows/runtime_prereleases.yml @@ -39,8 +39,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-release-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} + path: | + **/node_modules + key: runtime-release-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile diff --git a/.github/workflows/runtime_releases_from_npm_manual.yml b/.github/workflows/runtime_releases_from_npm_manual.yml index c0b3867e03..c4675bfb7f 100644 --- a/.github/workflows/runtime_releases_from_npm_manual.yml +++ b/.github/workflows/runtime_releases_from_npm_manual.yml @@ -71,8 +71,9 @@ jobs: uses: actions/cache@v4 id: node_modules with: - path: "**/node_modules" - key: runtime-release-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} + path: | + **/node_modules + key: runtime-release-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile diff --git a/.github/workflows/shared_lint.yml b/.github/workflows/shared_lint.yml index 4b077eff65..08ade6cb7f 100644 --- a/.github/workflows/shared_lint.yml +++ b/.github/workflows/shared_lint.yml @@ -28,8 +28,9 @@ jobs: - name: Restore cached node_modules uses: actions/cache@v4 with: - path: "**/node_modules" - key: shared-lint-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} + path: | + **/node_modules + key: shared-lint-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -48,8 +49,9 @@ jobs: - name: Restore cached node_modules uses: actions/cache@v4 with: - path: "**/node_modules" - key: shared-lint-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} + path: | + **/node_modules + key: shared-lint-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -68,8 +70,9 @@ jobs: - name: Restore cached node_modules uses: actions/cache@v4 with: - path: "**/node_modules" - key: shared-lint-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} + path: | + **/node_modules + key: shared-lint-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile @@ -88,8 +91,9 @@ jobs: - name: Restore cached node_modules uses: actions/cache@v4 with: - path: "**/node_modules" - key: shared-lint-node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} + path: | + **/node_modules + key: shared-lint-node_modules-v5-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('**/yarn.lock') }} - name: Ensure clean build directory run: rm -rf build - run: yarn install --frozen-lockfile diff --git a/compiler/packages/babel-plugin-react-compiler/src/HIR/CollectHoistablePropertyLoads.ts b/compiler/packages/babel-plugin-react-compiler/src/HIR/CollectHoistablePropertyLoads.ts index 7b35269686..b8e4760cc9 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/HIR/CollectHoistablePropertyLoads.ts +++ b/compiler/packages/babel-plugin-react-compiler/src/HIR/CollectHoistablePropertyLoads.ts @@ -7,21 +7,27 @@ import { Set_intersect, Set_union, getOrInsertDefault, + getOrInsertWith, } from '../Utils/utils'; import { BasicBlock, BlockId, DependencyPathEntry, GeneratedSource, + getHookKind, HIRFunction, Identifier, IdentifierId, InstructionId, InstructionValue, + LoweredFunction, + Place, PropertyLiteral, ReactiveScopeDependency, ScopeId, + ValidatedIdentifier, } from './HIR'; +import {eachInstructionOperand, eachInstructionValueOperand} from './visitors'; const DEBUG_PRINT = false; @@ -112,6 +118,9 @@ export function collectHoistablePropertyLoads( hoistableFromOptionals, registry, nestedFnImmutableContext: null, + fnUsages: fn.env.config.enableTreatFunctionDepsAsConditional + ? new Map() + : mapFunctionExpressionsToEscapingBlocks(fn), }); } @@ -127,6 +136,11 @@ type CollectHoistablePropertyLoadsContext = { * but are currently kept separate for readability. */ nestedFnImmutableContext: ReadonlySet | null; + /** + * Mapping of functions declared within a traversal context to their + * (valid) usage sites, which will have hoistable property loads added + */ + fnUsages: ReadonlyMap>; }; function collectHoistablePropertyLoadsImpl( fn: HIRFunction, @@ -338,7 +352,13 @@ function collectNonNullsInBlocks( context.registry.getOrCreateIdentifier(identifier), ); } - const nodes = new Map(); + const nodes = new Map< + BlockId, + { + block: BasicBlock; + assumedNonNullObjects: Set; + } + >(); for (const [_, block] of fn.body.blocks) { const assumedNonNullObjects = new Set( knownNonNullIdentifiers, @@ -358,40 +378,68 @@ function collectNonNullsInBlocks( ) { assumedNonNullObjects.add(maybeNonNull); } - if ( - (instr.value.kind === 'FunctionExpression' || - instr.value.kind === 'ObjectMethod') && - !fn.env.config.enableTreatFunctionDepsAsConditional - ) { + if (instr.value.kind === 'FunctionExpression') { + /** + * What are reasonable semantics here? + * Risky + * - only treat named fns as unconditionally hoistable + * + * Conservative + */ const innerFn = instr.value.loweredFunc; - const innerHoistableMap = collectHoistablePropertyLoadsImpl( - innerFn.func, - { - ...context, - nestedFnImmutableContext: - context.nestedFnImmutableContext ?? - new Set( - innerFn.func.context - .filter(place => - isImmutableAtInstr(place.identifier, instr.id, context), - ) - .map(place => place.identifier.id), - ), - }, - ); - const innerHoistables = assertNonNull( - innerHoistableMap.get(innerFn.func.body.entry), - ); - for (const entry of innerHoistables.assumedNonNullObjects) { - assumedNonNullObjects.add(entry); + const resultBlocks = context.fnUsages.get(innerFn); + if (resultBlocks != null) { + const innerHoistableMap = collectHoistablePropertyLoadsImpl( + innerFn.func, + { + ...context, + nestedFnImmutableContext: + context.nestedFnImmutableContext ?? + new Set( + innerFn.func.context + .filter(place => + isImmutableAtInstr(place.identifier, instr.id, context), + ) + .map(place => place.identifier.id), + ), + fnUsages: fn.env.config.enableTreatFunctionDepsAsConditional + ? new Map() + : mapFunctionExpressionsToEscapingBlocks(innerFn.func), + }, + ); + const innerHoistables = assertNonNull( + innerHoistableMap.get(innerFn.func.body.entry), + ); + for (const innerBlock of resultBlocks) { + let innerNonNulls; + if (innerBlock === block.id) { + innerNonNulls = assumedNonNullObjects; + } else { + innerNonNulls = getOrInsertWith(nodes, innerBlock, () => ({ + block: assertNonNull(fn.body.blocks.get(innerBlock)), + assumedNonNullObjects: new Set(), + })).assumedNonNullObjects; + } + for (const entry of innerHoistables.assumedNonNullObjects) { + innerNonNulls.add(entry); + } + } } } } - nodes.set(block.id, { - block, - assumedNonNullObjects, - }); + const maybeNode = nodes.get(block.id); + if (maybeNode != null) { + // merge + for (const entry of assumedNonNullObjects) { + maybeNode.assumedNonNullObjects.add(entry); + } + } else { + nodes.set(block.id, { + block, + assumedNonNullObjects, + }); + } } return nodes; } @@ -591,3 +639,123 @@ function reduceMaybeOptionalChains( } } while (changed); } + +/** + * + * const foo = function() { ... } // this matches + * arr.map(function() { ... }) // this does not match + * + * What about function expressions that just escape to other functions? + * + * For both below examples, cb1 should be hoistable only to if-cond block + * ```js + * function useFoo(...) { + * const cb1 = function() { ... }; + * const cb2 = function() { if (cond) cb1() }; + * return cb2; + * } + * ``` + * ```js + * function useFoo(...) { + * const cb1 = function() { ... }; + * const cb2 = function() { if (cond) return cb1; }; + * return cb2; + * } + * ``` + */ +function mapFunctionExpressionsToEscapingBlocks( + fn: HIRFunction, +): ReadonlyMap> { + /** + * Step 1: gather all function expressions and known ssa'd aliases + */ + const temporaries = new Map< + IdentifierId, + {fn: LoweredFunction; usage: Set} + >(); + const validUsages = new Set(); + + for (const block of fn.body.blocks.values()) { + for (const {lvalue, value} of block.instructions) { + /** + * Only match function expressions which can have guaranteed ssa. + */ + if (value.kind === 'FunctionExpression') { + temporaries.set(lvalue.identifier.id, { + fn: value.loweredFunc, + usage: new Set(), + }); + } else if (value.kind === 'StoreLocal') { + const lvalue = value.lvalue.place.identifier; + const maybeLoweredFunc = temporaries.get(value.value.identifier.id); + if ( + lvalue.name != null && + lvalue.name.kind === 'named' && + maybeLoweredFunc != null + ) { + temporaries.set(lvalue.id, maybeLoweredFunc); + validUsages.add(value.value); + } + } else if (value.kind === 'LoadLocal') { + const maybeLoweredFunc = temporaries.get(value.place.identifier.id); + if (maybeLoweredFunc != null) { + temporaries.set(lvalue.identifier.id, maybeLoweredFunc); + validUsages.add(value.place); + } + } + } + } + /** + * Step 2: Forward pass to do best-effort "escape analysis" + */ + for (const block of fn.body.blocks.values()) { + for (const {value} of block.instructions) { + if (value.kind === 'CallExpression') { + const callee = value.callee; + const maybeHook = getHookKind(fn.env, callee.identifier); + const maybeLoweredFunc = temporaries.get(callee.identifier.id); + if (maybeLoweredFunc != null) { + // Direct calls + maybeLoweredFunc.usage.add(block.id); + } else if (maybeHook != null) { + // Arguments to hooks + for (const arg of value.args.filter( + arg => arg.kind === 'Identifier', + ) as Array) { + const maybeLoweredFunc = temporaries.get(arg.identifier.id); + if (maybeLoweredFunc != null) { + maybeLoweredFunc.usage.add(block.id); + } + } + } + } else if (value.kind === 'JsxExpression') { + /* Match jsx attributes */ + for (const attr of value.props) { + if (attr.kind === 'JsxSpreadAttribute') { + continue; + } + const maybeLoweredFunc = temporaries.get(attr.place.identifier.id); + if (maybeLoweredFunc != null) { + maybeLoweredFunc.usage.add(block.id); + } + } + } + if (block.terminal.kind === 'return') { + const maybeLoweredFunc = temporaries.get( + block.terminal.value.identifier.id, + ); + if (maybeLoweredFunc != null) { + maybeLoweredFunc.usage.add(block.id); + } + } + } + } + + const map = new Map>(); + for (const {fn, usage} of temporaries.values()) { + if (!map.has(fn)) { + map.set(fn, usage); + } + } + return map; +} diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-operand-conditionally-invoked.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-operand-conditionally-invoked.expect.md new file mode 100644 index 0000000000..8df552c108 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-operand-conditionally-invoked.expect.md @@ -0,0 +1,53 @@ + +## Input + +```javascript +function useFoo({arr}) { + return arr.map(e => arr[0].value + e.value); +} + +export const FIXTURE_ENTRYPOINT = { + fn: useFoo, + params: [{arr: []}], + sequentialRenders: [{arr: []}, {arr: [{value: 1}, {value: 2}]}], +}; + +``` + +## Code + +```javascript +import { c as _c } from "react/compiler-runtime"; +function useFoo(t0) { + const $ = _c(4); + const { arr } = t0; + let t1; + if ($[0] !== arr) { + let t2; + if ($[2] !== arr[0]) { + t2 = (e) => arr[0].value + e.value; + $[2] = arr[0]; + $[3] = t2; + } else { + t2 = $[3]; + } + t1 = arr.map(t2); + $[0] = arr; + $[1] = t1; + } else { + t1 = $[1]; + } + return t1; +} + +export const FIXTURE_ENTRYPOINT = { + fn: useFoo, + params: [{ arr: [] }], + sequentialRenders: [{ arr: [] }, { arr: [{ value: 1 }, { value: 2 }] }], +}; + +``` + +### Eval output +(kind: ok) [] +[2,3] \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-operand-conditionally-invoked.js b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-operand-conditionally-invoked.js new file mode 100644 index 0000000000..e7d5f59046 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-operand-conditionally-invoked.js @@ -0,0 +1,9 @@ +function useFoo({arr}) { + return arr.map(e => arr[0].value + e.value); +} + +export const FIXTURE_ENTRYPOINT = { + fn: useFoo, + params: [{arr: []}], + sequentialRenders: [{arr: []}, {arr: [{value: 1}, {value: 2}]}], +}; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-aliased-capture-mutate.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-aliased-capture-mutate.expect.md index c35efe6a16..ae60114253 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-aliased-capture-mutate.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-aliased-capture-mutate.expect.md @@ -56,9 +56,9 @@ function useFoo(t0) { setPropertyByKey(obj, "arr", arr); const obj_alias = obj; let t2; - if ($[2] !== obj_alias.arr.length) { + if ($[2] !== obj_alias) { t2 = () => obj_alias.arr.length; - $[2] = obj_alias.arr.length; + $[2] = obj_alias; $[3] = t2; } else { t2 = $[3]; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call.expect.md index 5666876f00..2df5b90890 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call.expect.md @@ -23,11 +23,11 @@ import { c as _c } from "react/compiler-runtime"; function Component(props) { const $ = _c(4); let t0; - if ($[0] !== props.name) { + if ($[0] !== props) { t0 = function () { return
{props.name}
; }; - $[0] = props.name; + $[0] = props; $[1] = t0; } else { t0 = $[1]; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useMemo-read-maybeRef.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useMemo-read-maybeRef.expect.md deleted file mode 100644 index ce0b751851..0000000000 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useMemo-read-maybeRef.expect.md +++ /dev/null @@ -1,32 +0,0 @@ - -## Input - -```javascript -// @validatePreserveExistingMemoizationGuarantees -import {useMemo} from 'react'; - -function useHook(maybeRef, shouldRead) { - return useMemo(() => { - return () => [maybeRef.current]; - }, [shouldRead, maybeRef]); -} - -``` - - -## Error - -``` - 3 | - 4 | function useHook(maybeRef, shouldRead) { -> 5 | return useMemo(() => { - | ^^^^^^^ -> 6 | return () => [maybeRef.current]; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -> 7 | }, [shouldRead, maybeRef]); - | ^^^^ CannotPreserveMemoization: React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected (5:7) - 8 | } - 9 | -``` - - \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/maybe-invalid-useMemo-read-maybeRef.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/maybe-invalid-useMemo-read-maybeRef.expect.md new file mode 100644 index 0000000000..b65fb89782 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/maybe-invalid-useMemo-read-maybeRef.expect.md @@ -0,0 +1,40 @@ + +## Input + +```javascript +// @validatePreserveExistingMemoizationGuarantees +import {useMemo} from 'react'; + +function useHook(maybeRef, shouldRead) { + return useMemo(() => { + return () => [maybeRef.current]; + }, [shouldRead, maybeRef]); +} + +``` + +## Code + +```javascript +import { c as _c } from "react/compiler-runtime"; // @validatePreserveExistingMemoizationGuarantees +import { useMemo } from "react"; + +function useHook(maybeRef, shouldRead) { + const $ = _c(2); + let t0; + let t1; + if ($[0] !== maybeRef) { + t1 = () => [maybeRef.current]; + $[0] = maybeRef; + $[1] = t1; + } else { + t1 = $[1]; + } + t0 = t1; + return t0; +} + +``` + +### Eval output +(kind: exception) Fixture not implemented \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useMemo-read-maybeRef.ts b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/maybe-invalid-useMemo-read-maybeRef.ts similarity index 100% rename from compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useMemo-read-maybeRef.ts rename to compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/maybe-invalid-useMemo-read-maybeRef.ts diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-nested-function-uncond-access-local-var.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-nested-function-uncond-access-local-var.expect.md index ca65ce72bc..53d3d04531 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-nested-function-uncond-access-local-var.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-nested-function-uncond-access-local-var.expect.md @@ -41,9 +41,9 @@ function useFoo(t0) { local = $[1]; } let t1; - if ($[2] !== local.b.c) { + if ($[2] !== local) { t1 = () => [() => local.b.c]; - $[2] = local.b.c; + $[2] = local; $[3] = t1; } else { t1 = $[3]; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-object-method-uncond-access.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-object-method-uncond-access.expect.md index 7d75470550..f8a8af1fd4 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-object-method-uncond-access.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/infer-object-method-uncond-access.expect.md @@ -34,13 +34,13 @@ function useFoo(t0) { const $ = _c(4); const { a } = t0; let t1; - if ($[0] !== a.b.c) { + if ($[0] !== a) { t1 = { fn() { return identity(a.b.c); }, }; - $[0] = a.b.c; + $[0] = a; $[1] = t1; } else { t1 = $[1]; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-on-context-variable.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-on-context-variable.expect.md index ceaa350012..963024e887 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-on-context-variable.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-on-context-variable.expect.md @@ -51,7 +51,7 @@ import { identity } from "shared-runtime"; function Component(props) { const $ = _c(4); let x; - if ($[0] !== props.cond) { + if ($[0] !== props) { const f = () => { if (props.cond) { x = 1; @@ -62,7 +62,7 @@ function Component(props) { const f2 = identity(f); f2(); - $[0] = props.cond; + $[0] = props; $[1] = x; } else { x = $[1]; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/context-var-granular-dep.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/context-var-granular-dep.expect.md index d72f34b4fd..f887870197 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/context-var-granular-dep.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/context-var-granular-dep.expect.md @@ -82,9 +82,9 @@ function Component(t0) { contextVar = $[2]; } let t1; - if ($[3] !== contextVar.val) { + if ($[3] !== contextVar) { t1 = { cb: () => contextVar.val * 4 }; - $[3] = contextVar.val; + $[3] = contextVar; $[4] = t1; } else { t1 = $[4]; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-object-method.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-object-method.expect.md index d0f3d5dcfe..e406f3a7d7 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-object-method.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-object-method.expect.md @@ -43,7 +43,7 @@ const t0 = "module_t0"; const c_0 = "module_c_0"; function useFoo(props) { const $0 = _c(2); - const c_00 = $0[0] !== props.value; + const c_00 = $0[0] !== props; let t1; if (c_00) { const a = { @@ -61,7 +61,7 @@ function useFoo(props) { }; t1 = a.foo().bar(); - $0[0] = props.value; + $0[0] = props; $0[1] = t1; } else { t1 = $0[1]; diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-nested-lambdas.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-nested-lambdas.expect.md index c3e115fa0d..0cce42e97a 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-nested-lambdas.expect.md +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-nested-lambdas.expect.md @@ -35,7 +35,7 @@ function Component(props) { import { c as _c } from "react/compiler-runtime"; // @enableTransitivelyFreezeFunctionExpressions:false function Component(props) { - const $ = _c(9); + const $ = _c(7); const item = useMutable(props.itemId); const dispatch = useDispatch(); useFreeze(dispatch); @@ -51,7 +51,8 @@ function Component(props) { } const exit = t0; let t1; - if ($[2] !== exit || $[3] !== item.value) { + let t2; + if ($[2] !== exit || $[3] !== item) { t1 = () => { const cleanup = GlobalEventEmitter.addListener("onInput", () => { if (item.value) { @@ -60,30 +61,24 @@ function Component(props) { }); return () => cleanup.remove(); }; + t2 = [exit, item]; $[2] = exit; - $[3] = item.value; + $[3] = item; $[4] = t1; + $[5] = t2; } else { t1 = $[4]; - } - let t2; - if ($[5] !== exit || $[6] !== item) { - t2 = [exit, item]; - $[5] = exit; - $[6] = item; - $[7] = t2; - } else { - t2 = $[7]; + t2 = $[5]; } useEffect(t1, t2); maybeMutate(item); let t3; - if ($[8] === Symbol.for("react.memo_cache_sentinel")) { + if ($[6] === Symbol.for("react.memo_cache_sentinel")) { t3 =
; - $[8] = t3; + $[6] = t3; } else { - t3 = $[8]; + t3 = $[6]; } return t3; } diff --git a/package.json b/package.json index 2c7041f0fb..ca0b62e846 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "testRegex": "/scripts/jest/dont-run-jest-directly\\.js$" }, "scripts": { - "prebuild": "yarn --cwd compiler install --frozen-lockfile && ./scripts/react-compiler/link-compiler.sh", + "prebuild": "./scripts/react-compiler/link-compiler.sh", "build": "node ./scripts/rollup/build-all-release-channels.js", "build-for-devtools": "cross-env RELEASE_CHANNEL=experimental yarn build react/index,react/jsx,react/compiler-runtime,react-dom/index,react-dom/client,react-dom/unstable_testing,react-dom/test-utils,react-is,react-debug-tools,scheduler,react-test-renderer,react-refresh,react-art --type=NODE", "build-for-devtools-dev": "yarn build-for-devtools --type=NODE_DEV", diff --git a/packages/react-reconciler/src/ReactFiber.js b/packages/react-reconciler/src/ReactFiber.js index 70cb3ed9de..f6011a3ba1 100644 --- a/packages/react-reconciler/src/ReactFiber.js +++ b/packages/react-reconciler/src/ReactFiber.js @@ -878,6 +878,7 @@ export function createFiberFromViewTransition( const instance: ViewTransitionState = { autoName: null, paired: null, + clones: null, ref: null, }; fiber.stateNode = instance; diff --git a/packages/react-reconciler/src/ReactFiberApplyGesture.js b/packages/react-reconciler/src/ReactFiberApplyGesture.js index 6847a2426c..a83c52c57c 100644 --- a/packages/react-reconciler/src/ReactFiberApplyGesture.js +++ b/packages/react-reconciler/src/ReactFiberApplyGesture.js @@ -13,6 +13,11 @@ import type {Instance, TextInstance} from './ReactFiberConfig'; import type {OffscreenState} from './ReactFiberActivityComponent'; +import type { + ViewTransitionState, + ViewTransitionProps, +} from './ReactFiberViewTransitionComponent'; + import { cloneMutableInstance, cloneMutableTextInstance, @@ -40,6 +45,8 @@ import { ContentReset, NoFlags, Visibility, + ViewTransitionNamedStatic, + ViewTransitionStatic, } from './ReactFiberFlags'; import { HostComponent, @@ -50,6 +57,10 @@ import { OffscreenComponent, ViewTransitionComponent, } from './ReactWorkTags'; +import { + restoreEnterOrExitViewTransitions, + restoreNestedViewTransitions, +} from './ReactFiberCommitViewTransitions'; let didWarnForRootClone = false; @@ -57,26 +68,284 @@ function detectMutationOrInsertClones(finishedWork: Fiber): boolean { return true; } -let unhideHostChildren = false; +const CLONE_UPDATE = 0; // Mutations in this subtree or potentially affected by layout. +const CLONE_EXIT = 1; // Inside a reappearing offscreen before the next ViewTransition or HostComponent. +const CLONE_UNHIDE = 2; // Inside a reappearing offscreen before the next HostComponent. +const CLONE_APPEARING_PAIR = 3; // Like UNHIDE but we're already inside the first Host Component only finding pairs. +const CLONE_UNCHANGED = 4; // Nothing in this tree was changed but we're still walking to clone it. +const INSERT_EXIT = 5; // Inside a newly mounted tree before the next ViewTransition or HostComponent. +const INSERT_APPEND = 6; // Inside a newly mounted tree before the next HostComponent. +const INSERT_APPEARING_PAIR = 7; // Inside a newly mounted tree only finding pairs. +type VisitPhase = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7; + +function trackDeletedPairViewTransitions(deletion: Fiber): void { + if ((deletion.subtreeFlags & ViewTransitionNamedStatic) === NoFlags) { + // This has no named view transitions in its subtree. + return; + } + let child = deletion.child; + while (child !== null) { + if (child.tag === OffscreenComponent && child.memoizedState === null) { + // This tree was already hidden so we skip it. + } else { + if ( + child.tag === ViewTransitionComponent && + (child.flags & ViewTransitionNamedStatic) !== NoFlags + ) { + const props: ViewTransitionProps = child.memoizedProps; + const name = props.name; + if (name != null && name !== 'auto') { + // TODO: Find a pair + } + } + trackDeletedPairViewTransitions(child); + } + child = child.sibling; + } +} + +function trackEnterViewTransitions(deletion: Fiber): void { + if (deletion.tag === ViewTransitionComponent) { + const props: ViewTransitionProps = deletion.memoizedProps; + const name = props.name; + if (name != null && name !== 'auto') { + // TODO: Find a pair + } + // Look for more pairs deeper in the tree. + trackDeletedPairViewTransitions(deletion); + } else if ((deletion.subtreeFlags & ViewTransitionStatic) !== NoFlags) { + let child = deletion.child; + while (child !== null) { + trackEnterViewTransitions(child); + child = child.sibling; + } + } else { + trackDeletedPairViewTransitions(deletion); + } +} + +function recursivelyInsertNew( + parentFiber: Fiber, + hostParentClone: Instance, + parentViewTransition: null | ViewTransitionState, + visitPhase: VisitPhase, +): void { + if ( + visitPhase === INSERT_APPEARING_PAIR && + parentViewTransition === null && + (parentFiber.subtreeFlags & ViewTransitionNamedStatic) === NoFlags + ) { + // We're just searching for pairs but we have reached the end. + return; + } + let child = parentFiber.child; + while (child !== null) { + recursivelyInsertNewFiber( + child, + hostParentClone, + parentViewTransition, + visitPhase, + ); + child = child.sibling; + } +} + +function recursivelyInsertNewFiber( + finishedWork: Fiber, + hostParentClone: Instance, + parentViewTransition: null | ViewTransitionState, + visitPhase: VisitPhase, +): void { + switch (finishedWork.tag) { + case HostHoistable: { + if (supportsResources) { + // TODO: Hoistables should get optimistically inserted and then removed. + recursivelyInsertNew( + finishedWork, + hostParentClone, + parentViewTransition, + visitPhase, + ); + break; + } + // Fall through + } + case HostSingleton: { + if (supportsSingletons) { + recursivelyInsertNew( + finishedWork, + hostParentClone, + parentViewTransition, + visitPhase, + ); + + if (__DEV__) { + // We cannot apply mutations to Host Singletons since by definition + // they cannot be cloned. Therefore we warn in DEV if this commit + // had any effect. + if (finishedWork.flags & Update) { + console.error( + 'useSwipeTransition() caused something to render a new <%s>. ' + + 'This is not possible in the current implementation. ' + + "Make sure that the swipe doesn't mount any new <%s> elements.", + finishedWork.type, + finishedWork.type, + ); + } + } + break; + } + // Fall through + } + case HostComponent: { + const instance: Instance = finishedWork.stateNode; + // For insertions we don't need to clone. It's already new state node. + if (visitPhase !== INSERT_APPEARING_PAIR) { + appendChild(hostParentClone, instance); + recursivelyInsertNew( + finishedWork, + instance, + null, + INSERT_APPEARING_PAIR, + ); + } else { + recursivelyInsertNew(finishedWork, instance, null, visitPhase); + } + if (parentViewTransition !== null) { + if (parentViewTransition.clones === null) { + parentViewTransition.clones = [instance]; + } else { + parentViewTransition.clones.push(instance); + } + } + break; + } + case HostText: { + const textInstance: TextInstance = finishedWork.stateNode; + if (textInstance === 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.', + ); + } + // For insertions we don't need to clone. It's already new state node. + if (visitPhase !== INSERT_APPEARING_PAIR) { + appendChild(hostParentClone, textInstance); + } + break; + } + case HostPortal: { + // TODO: Consider what should happen to Portals. For now we exclude them. + break; + } + case OffscreenComponent: { + const newState: OffscreenState | null = finishedWork.memoizedState; + const isHidden = newState !== null; + if (!isHidden) { + // Only insert nodes if this tree is going to be visible. No need to + // insert invisible content. + // Since there was no mutation to this node, it couldn't have changed + // visibility so we don't need to update visitPhase here. + recursivelyInsertNew( + finishedWork, + hostParentClone, + parentViewTransition, + visitPhase, + ); + } + break; + } + case ViewTransitionComponent: + const prevMutationContext = pushMutationContext(); + const viewTransitionState: ViewTransitionState = finishedWork.stateNode; + // TODO: If this was already cloned by a previous pass we can reuse those clones. + viewTransitionState.clones = null; + let nextPhase; + if (visitPhase === INSERT_EXIT) { + // This was an Enter of a ViewTransition. We now move onto inserting the inner + // HostComponents and finding inner pairs. + nextPhase = INSERT_APPEND; + // TODO: Mark the name and find a pair. + } else { + nextPhase = visitPhase; + } + recursivelyInsertNew( + finishedWork, + hostParentClone, + viewTransitionState, + nextPhase, + ); + popMutationContext(prevMutationContext); + break; + default: { + recursivelyInsertNew( + finishedWork, + hostParentClone, + parentViewTransition, + visitPhase, + ); + break; + } + } +} function recursivelyInsertClonesFromExistingTree( parentFiber: Fiber, hostParentClone: Instance, + parentViewTransition: null | ViewTransitionState, + visitPhase: VisitPhase, ): void { let child = parentFiber.child; while (child !== null) { switch (child.tag) { case HostComponent: { const instance: Instance = child.stateNode; - // If we have no mutations in this subtree, we just need to make a deep clone. - const clone: Instance = cloneMutableInstance(instance, true); + let nextPhase: VisitPhase; + switch (visitPhase) { + case CLONE_EXIT: + case CLONE_UNHIDE: + case CLONE_APPEARING_PAIR: + // If this was an unhide, we need to keep going if there are any named + // pairs in this subtree, since they might need to be marked. + nextPhase = + (child.subtreeFlags & ViewTransitionNamedStatic) !== NoFlags + ? CLONE_APPEARING_PAIR + : CLONE_UNCHANGED; + break; + default: + // We've found any "layout" View Transitions at this point so we can bail. + nextPhase = CLONE_UNCHANGED; + } + let clone: Instance; + if (nextPhase !== CLONE_UNCHANGED) { + // We might need a handle on these clones, so we need to do a shallow clone + // and keep going. + clone = cloneMutableInstance(instance, false); + recursivelyInsertClonesFromExistingTree( + child, + clone, + null, + nextPhase, + ); + } else { + // If we have no mutations in this subtree, and we don't need a handle on the + // clones, then we can do a deep clone instead and bailout. + clone = cloneMutableInstance(instance, true); + // TODO: We may need to transfer some DOM state such as scroll position + // for the deep clones. + // TODO: If there's a manual view-transition-name inside the clone we + // should ideally remove it from the original and then restore it in mutation + // phase. Otherwise it leads to duplicate names. + } appendChild(hostParentClone, clone); - // TODO: We may need to transfer some DOM state such as scroll position - // for the deep clones. - // TODO: If there's a manual view-transition-name inside the clone we - // should ideally remove it from the original and then restore it in mutation - // phase. Otherwise it leads to duplicate names. - if (unhideHostChildren) { + if (parentViewTransition !== null) { + if (parentViewTransition.clones === null) { + parentViewTransition.clones = [clone]; + } else { + parentViewTransition.clones.push(clone); + } + } + if (visitPhase === CLONE_EXIT || visitPhase === CLONE_UNHIDE) { unhideInstance(clone, child.memoizedProps); } break; @@ -91,7 +360,7 @@ function recursivelyInsertClonesFromExistingTree( } const clone = cloneMutableTextInstance(textInstance); appendChild(hostParentClone, clone); - if (unhideHostChildren) { + if (visitPhase === CLONE_EXIT || visitPhase === CLONE_UNHIDE) { unhideTextInstance(clone, child.memoizedProps); } break; @@ -108,21 +377,52 @@ function recursivelyInsertClonesFromExistingTree( // clone invisible content. // TODO: If this is visible but detached it should still be cloned. // Since there was no mutation to this node, it couldn't have changed - // visibility so we don't need to update unhideHostChildren here. - recursivelyInsertClonesFromExistingTree(child, hostParentClone); + // visibility so we don't need to update visitPhase here. + recursivelyInsertClonesFromExistingTree( + child, + hostParentClone, + parentViewTransition, + visitPhase, + ); } break; } case ViewTransitionComponent: const prevMutationContext = pushMutationContext(); + const viewTransitionState: ViewTransitionState = child.stateNode; // TODO: If this was already cloned by a previous pass we can reuse those clones. - recursivelyInsertClonesFromExistingTree(child, hostParentClone); - // TODO: Do we need to track whether this should have a name applied? + viewTransitionState.clones = null; + let nextPhase; + if (visitPhase === CLONE_EXIT) { + // This was an Enter of a ViewTransition. We now move onto unhiding the inner + // HostComponents and finding inner pairs. + nextPhase = CLONE_UNHIDE; + // TODO: Mark the name and find a pair. + } else if (visitPhase === CLONE_UPDATE) { + // If the tree had no mutations and we've found the top most ViewTransition + // then this is the one we might apply the "layout" state too if it has changed + // position. After we've found its HostComponents we can bail out. + nextPhase = CLONE_UNCHANGED; + } else { + nextPhase = visitPhase; + } + recursivelyInsertClonesFromExistingTree( + child, + hostParentClone, + viewTransitionState, + nextPhase, + ); + // TODO: Only the first level should track if this was s // child.flags |= Update; popMutationContext(prevMutationContext); break; default: { - recursivelyInsertClonesFromExistingTree(child, hostParentClone); + recursivelyInsertClonesFromExistingTree( + child, + hostParentClone, + parentViewTransition, + visitPhase, + ); break; } } @@ -133,12 +433,14 @@ function recursivelyInsertClonesFromExistingTree( function recursivelyInsertClones( parentFiber: Fiber, hostParentClone: Instance, + parentViewTransition: null | ViewTransitionState, + visitPhase: VisitPhase, ) { const deletions = parentFiber.deletions; if (deletions !== null) { for (let i = 0; i < deletions.length; i++) { - // const childToDelete = deletions[i]; - // TODO + const childToDelete = deletions[i]; + trackEnterViewTransitions(childToDelete); } } @@ -149,21 +451,45 @@ function recursivelyInsertClones( // If we have mutations or if this is a newly inserted tree, clone as we go. let child = parentFiber.child; while (child !== null) { - insertDestinationClonesOfFiber(child, hostParentClone); + insertDestinationClonesOfFiber( + child, + hostParentClone, + parentViewTransition, + visitPhase, + ); child = child.sibling; } } else { // Once we reach a subtree with no more mutations we can bail out. // However, we must still insert deep clones of the HostComponents. - recursivelyInsertClonesFromExistingTree(parentFiber, hostParentClone); + recursivelyInsertClonesFromExistingTree( + parentFiber, + hostParentClone, + parentViewTransition, + visitPhase, + ); } } function insertDestinationClonesOfFiber( finishedWork: Fiber, hostParentClone: Instance, + parentViewTransition: null | ViewTransitionState, + visitPhase: VisitPhase, ) { const current = finishedWork.alternate; + if (current === null) { + // This is a newly mounted subtree. Insert any HostComponents and trigger + // Enter transitions. + recursivelyInsertNewFiber( + finishedWork, + hostParentClone, + parentViewTransition, + INSERT_EXIT, + ); + return; + } + 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 @@ -172,55 +498,55 @@ function insertDestinationClonesOfFiber( case HostHoistable: { if (supportsResources) { // TODO: Hoistables should get optimistically inserted and then removed. - recursivelyInsertClones(finishedWork, hostParentClone); + recursivelyInsertClones( + finishedWork, + hostParentClone, + parentViewTransition, + visitPhase, + ); break; } // Fall through } case HostSingleton: { if (supportsSingletons) { - recursivelyInsertClones(finishedWork, hostParentClone); + recursivelyInsertClones( + finishedWork, + hostParentClone, + parentViewTransition, + visitPhase, + ); if (__DEV__) { // We cannot apply mutations to Host Singletons since by definition // they cannot be cloned. Therefore we warn in DEV if this commit // had any effect. if (flags & Update) { - if (current === null) { - console.error( - 'useSwipeTransition() caused something to render a new <%s>. ' + - 'This is not possible in the current implementation. ' + - "Make sure that the swipe doesn't mount any new <%s> elements.", - finishedWork.type, - finishedWork.type, - ); - } else { - const newProps = finishedWork.memoizedProps; - const oldProps = current.memoizedProps; - const instance = finishedWork.stateNode; - const type = finishedWork.type; - const prev = pushMutationContext(); + const newProps = finishedWork.memoizedProps; + const oldProps = current.memoizedProps; + const instance = finishedWork.stateNode; + const type = finishedWork.type; + const prev = pushMutationContext(); - try { - // Since we currently don't have a separate diffing algorithm for - // individual properties, the Update flag can be a false positive. - // We have to apply the new props first o detect any mutations and - // then revert them. - commitUpdate(instance, type, oldProps, newProps, finishedWork); - if (viewTransitionMutationContext) { - console.error( - 'useSwipeTransition() caused something to mutate <%s>. ' + - 'This is not possible in the current implementation. ' + - "Make sure that the swipe doesn't update any state which " + - 'causes <%s> to change.', - finishedWork.type, - finishedWork.type, - ); - } - // Revert - commitUpdate(instance, type, newProps, oldProps, finishedWork); - } finally { - popMutationContext(prev); + try { + // Since we currently don't have a separate diffing algorithm for + // individual properties, the Update flag can be a false positive. + // We have to apply the new props first o detect any mutations and + // then revert them. + commitUpdate(instance, type, oldProps, newProps, finishedWork); + if (viewTransitionMutationContext) { + console.error( + 'useSwipeTransition() caused something to mutate <%s>. ' + + 'This is not possible in the current implementation. ' + + "Make sure that the swipe doesn't update any state which " + + 'causes <%s> to change.', + finishedWork.type, + finishedWork.type, + ); } + // Revert + commitUpdate(instance, type, newProps, oldProps, finishedWork); + } finally { + popMutationContext(prev); } } } @@ -230,42 +556,46 @@ function insertDestinationClonesOfFiber( } case HostComponent: { const instance: Instance = finishedWork.stateNode; - if (current === null) { - // For insertions we don't need to clone. It's already new state node. - // TODO: Do we need to visit it for ViewTransitions though? - appendChild(hostParentClone, instance); + let clone: Instance; + if (finishedWork.child === null) { + // This node is terminal. We still do a deep clone in case this has user + // inserted content, text content or dangerouslySetInnerHTML. + clone = cloneMutableInstance(instance, true); + if (finishedWork.flags & ContentReset) { + resetTextContent(clone); + } } else { - let clone: Instance; - if (finishedWork.child === null) { - // This node is terminal. We still do a deep clone in case this has user - // inserted content, text content or dangerouslySetInnerHTML. - clone = cloneMutableInstance(instance, true); - if (finishedWork.flags & ContentReset) { - resetTextContent(clone); - } - } else { - // If we have children we'll clone them as we walk the tree so we just - // do a shallow clone here. - clone = cloneMutableInstance(instance, false); - } + // If we have children we'll clone them as we walk the tree so we just + // do a shallow clone here. + clone = cloneMutableInstance(instance, false); + } - if (flags & Update) { - const newProps = finishedWork.memoizedProps; - const oldProps = current.memoizedProps; - const type = finishedWork.type; - // Apply the delta to the clone. - commitUpdate(clone, type, oldProps, newProps, finishedWork); - } + if (flags & Update) { + const newProps = finishedWork.memoizedProps; + const oldProps = current.memoizedProps; + const type = finishedWork.type; + // Apply the delta to the clone. + commitUpdate(clone, type, oldProps, newProps, finishedWork); + } - if (unhideHostChildren) { - unhideHostChildren = false; - recursivelyInsertClones(finishedWork, clone); - appendChild(hostParentClone, clone); - unhideHostChildren = true; - unhideInstance(clone, finishedWork.memoizedProps); + if (visitPhase === CLONE_EXIT || visitPhase === CLONE_UNHIDE) { + recursivelyInsertClones( + finishedWork, + clone, + null, + CLONE_APPEARING_PAIR, + ); + appendChild(hostParentClone, clone); + unhideInstance(clone, finishedWork.memoizedProps); + } else { + recursivelyInsertClones(finishedWork, clone, null, visitPhase); + appendChild(hostParentClone, clone); + } + if (parentViewTransition !== null) { + if (parentViewTransition.clones === null) { + parentViewTransition.clones = [clone]; } else { - recursivelyInsertClones(finishedWork, clone); - appendChild(hostParentClone, clone); + parentViewTransition.clones.push(clone); } } break; @@ -278,20 +608,15 @@ function insertDestinationClonesOfFiber( 'caused by a bug in React. Please file an issue.', ); } - if (current === null) { - // For insertions we don't need to clone. It's already new state node. - appendChild(hostParentClone, textInstance); - } else { - const clone = cloneMutableTextInstance(textInstance); - if (flags & Update) { - const newText: string = finishedWork.memoizedProps; - const oldText: string = current.memoizedProps; - commitTextUpdate(clone, newText, oldText); - } - appendChild(hostParentClone, clone); - if (unhideHostChildren) { - unhideTextInstance(clone, finishedWork.memoizedProps); - } + const clone = cloneMutableTextInstance(textInstance); + if (flags & Update) { + const newText: string = finishedWork.memoizedProps; + const oldText: string = current.memoizedProps; + commitTextUpdate(clone, newText, oldText); + } + appendChild(hostParentClone, clone); + if (visitPhase === CLONE_EXIT || visitPhase === CLONE_UNHIDE) { + unhideTextInstance(clone, finishedWork.memoizedProps); } break; } @@ -306,17 +631,45 @@ function insertDestinationClonesOfFiber( // Only insert clones if this tree is going to be visible. No need to // clone invisible content. // TODO: If this is visible but detached it should still be cloned. - const prevUnhide = unhideHostChildren; - unhideHostChildren = prevUnhide || (flags & Visibility) !== NoFlags; - recursivelyInsertClones(finishedWork, hostParentClone); - unhideHostChildren = prevUnhide; + let nextPhase; + if (visitPhase === CLONE_UPDATE && (flags & Visibility) !== NoFlags) { + // This is the root of an appear. We need to trigger Enter transitions. + nextPhase = CLONE_EXIT; + } else { + nextPhase = visitPhase; + } + recursivelyInsertClones( + finishedWork, + hostParentClone, + parentViewTransition, + nextPhase, + ); + } else if (current !== null && current.memoizedState === null) { + // Was previously mounted as visible but is now hidden. + trackEnterViewTransitions(current); } break; } case ViewTransitionComponent: const prevMutationContext = pushMutationContext(); + const viewTransitionState: ViewTransitionState = finishedWork.stateNode; // TODO: If this was already cloned by a previous pass we can reuse those clones. - recursivelyInsertClones(finishedWork, hostParentClone); + viewTransitionState.clones = null; + let nextPhase; + if (visitPhase === CLONE_EXIT) { + // This was an Enter of a ViewTransition. We now move onto unhiding the inner + // HostComponents and finding inner pairs. + nextPhase = CLONE_UNHIDE; + // TODO: Mark the name and find a pair. + } else { + nextPhase = visitPhase; + } + recursivelyInsertClones( + finishedWork, + hostParentClone, + viewTransitionState, + nextPhase, + ); if (viewTransitionMutationContext) { // Track that this boundary had a mutation and therefore needs to animate // whether it resized or not. @@ -325,7 +678,12 @@ function insertDestinationClonesOfFiber( popMutationContext(prevMutationContext); break; default: { - recursivelyInsertClones(finishedWork, hostParentClone); + recursivelyInsertClones( + finishedWork, + hostParentClone, + parentViewTransition, + visitPhase, + ); break; } } @@ -337,7 +695,6 @@ export function insertDestinationClones( root: FiberRoot, finishedWork: Fiber, ): void { - unhideHostChildren = false; // We'll either not transition the root, or we'll transition the clone. Regardless // we cancel the root view transition name. const needsClone = detectMutationOrInsertClones(finishedWork); @@ -356,24 +713,274 @@ export function insertDestinationClones( // Clone the whole root const rootClone = cloneRootViewTransitionContainer(root.containerInfo); root.gestureClone = rootClone; - recursivelyInsertClones(finishedWork, rootClone); + recursivelyInsertClones(finishedWork, rootClone, null, CLONE_UPDATE); } else { root.gestureClone = null; cancelRootViewTransitionName(root.containerInfo); } } +function applyDeletedPairViewTransitions(deletion: Fiber): void { + if ((deletion.subtreeFlags & ViewTransitionNamedStatic) === NoFlags) { + // This has no named view transitions in its subtree. + return; + } + let child = deletion.child; + while (child !== null) { + if (child.tag === OffscreenComponent && child.memoizedState === null) { + // This tree was already hidden so we skip it. + } else { + if ( + child.tag === ViewTransitionComponent && + (child.flags & ViewTransitionNamedStatic) !== NoFlags + ) { + const props: ViewTransitionProps = child.memoizedProps; + const name = props.name; + if (name != null && name !== 'auto') { + // TODO: Find a pair + } + } + applyDeletedPairViewTransitions(child); + } + child = child.sibling; + } +} + +function applyEnterViewTransitions(deletion: Fiber): void { + if (deletion.tag === ViewTransitionComponent) { + const props: ViewTransitionProps = deletion.memoizedProps; + const name = props.name; + if (name != null && name !== 'auto') { + // TODO: Find a pair + } + // Look for more pairs deeper in the tree. + applyDeletedPairViewTransitions(deletion); + } else if ((deletion.subtreeFlags & ViewTransitionStatic) !== NoFlags) { + // TODO: Check if this is a hidden Offscreen or a Portal. + let child = deletion.child; + while (child !== null) { + applyEnterViewTransitions(child); + child = child.sibling; + } + } else { + applyDeletedPairViewTransitions(deletion); + } +} + +function measureExitViewTransitions(placement: Fiber): void { + if (placement.tag === ViewTransitionComponent) { + // const state: ViewTransitionState = placement.stateNode; + const props: ViewTransitionProps = placement.memoizedProps; + const name = props.name; + if (name != null && name !== 'auto') { + // TODO: Find a pair + } + } else if ((placement.subtreeFlags & ViewTransitionStatic) !== NoFlags) { + // TODO: Check if this is a hidden Offscreen or a Portal. + let child = placement.child; + while (child !== null) { + measureExitViewTransitions(child); + child = child.sibling; + } + } else { + // We don't need to find pairs here because we would've already found and + // measured the pairs inside the deletion phase. + } +} + +function measureNestedViewTransitions(changedParent: Fiber): void { + let child = changedParent.child; + while (child !== null) { + if (child.tag === ViewTransitionComponent) { + const current = child.alternate; + if (current !== null) { + // const props: ViewTransitionProps = child.memoizedProps; + // const name = getViewTransitionName(props, child.stateNode); + // TODO: Measure both the old and new state and see if they're different. + } + } else if ((child.subtreeFlags & ViewTransitionStatic) !== NoFlags) { + // TODO: Check if this is a hidden Offscreen or a Portal. + measureNestedViewTransitions(child); + } + child = child.sibling; + } +} + +function measureUpdateViewTransition( + current: Fiber, + finishedWork: Fiber, +): void { + // TODO +} + +function recursivelyApplyViewTransitions(parentFiber: Fiber) { + const deletions = parentFiber.deletions; + if (deletions !== null) { + for (let i = 0; i < deletions.length; i++) { + const childToDelete = deletions[i]; + applyEnterViewTransitions(childToDelete); + } + } + + if ( + parentFiber.alternate === null || + (parentFiber.subtreeFlags & MutationMask) !== NoFlags + ) { + // If we have mutations or if this is a newly inserted tree, clone as we go. + let child = parentFiber.child; + while (child !== null) { + applyViewTransitionsOnFiber(child); + child = child.sibling; + } + } else { + // Nothing has changed in this subtree, but the parent may have still affected + // its size and position. We need to measure the old and new state to see if + // we should animate its size and position. + measureNestedViewTransitions(parentFiber); + } +} + +function applyViewTransitionsOnFiber(finishedWork: Fiber) { + const current = finishedWork.alternate; + if (current === null) { + measureExitViewTransitions(finishedWork); + return; + } + + 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 HostComponent: { + // const instance: Instance = finishedWork.stateNode; + // TODO: Apply name and measure. + recursivelyApplyViewTransitions(finishedWork); + break; + } + case HostText: { + break; + } + case HostPortal: { + // TODO: Consider what should happen to Portals. For now we exclude them. + break; + } + case OffscreenComponent: { + if (flags & Visibility) { + const newState: OffscreenState | null = finishedWork.memoizedState; + const isHidden = newState !== null; + if (!isHidden) { + measureExitViewTransitions(finishedWork); + } else if (current !== null && current.memoizedState === null) { + // Was previously mounted as visible but is now hidden. + applyEnterViewTransitions(current); + } + } + break; + } + case ViewTransitionComponent: + measureUpdateViewTransition(current, finishedWork); + const viewTransitionState: ViewTransitionState = finishedWork.stateNode; + viewTransitionState.clones = null; // Reset + recursivelyApplyViewTransitions(finishedWork); + break; + default: { + recursivelyApplyViewTransitions(finishedWork); + break; + } + } +} + // Revert insertions and apply view transition names to the "new" (current) state. export function applyDepartureTransitions( root: FiberRoot, finishedWork: Fiber, ): void { + // First measure and apply view-transition-names to the "new" states. + recursivelyApplyViewTransitions(finishedWork); + // Then remove the clones. const rootClone = root.gestureClone; if (rootClone !== null) { root.gestureClone = null; removeRootViewTransitionClone(root.containerInfo, rootClone); } - // TODO +} + +function recursivelyRestoreViewTransitions(parentFiber: Fiber) { + const deletions = parentFiber.deletions; + if (deletions !== null) { + for (let i = 0; i < deletions.length; i++) { + const childToDelete = deletions[i]; + restoreEnterOrExitViewTransitions(childToDelete); + } + } + + if ( + parentFiber.alternate === null || + (parentFiber.subtreeFlags & MutationMask) !== NoFlags + ) { + // If we have mutations or if this is a newly inserted tree, clone as we go. + let child = parentFiber.child; + while (child !== null) { + restoreViewTransitionsOnFiber(child); + child = child.sibling; + } + } else { + // Nothing has changed in this subtree, but the parent may have still affected + // its size and position. We need to measure the old and new state to see if + // we should animate its size and position. + restoreNestedViewTransitions(parentFiber); + } +} + +function restoreViewTransitionsOnFiber(finishedWork: Fiber) { + const current = finishedWork.alternate; + if (current === null) { + restoreEnterOrExitViewTransitions(finishedWork); + return; + } + + 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 HostComponent: { + // const instance: Instance = finishedWork.stateNode; + // TODO: Restore the name. + recursivelyRestoreViewTransitions(finishedWork); + break; + } + case HostText: { + break; + } + case HostPortal: { + // TODO: Consider what should happen to Portals. For now we exclude them. + break; + } + case OffscreenComponent: { + if (flags & Visibility) { + const newState: OffscreenState | null = finishedWork.memoizedState; + const isHidden = newState !== null; + if (!isHidden) { + restoreEnterOrExitViewTransitions(finishedWork); + } else if (current !== null && current.memoizedState === null) { + // Was previously mounted as visible but is now hidden. + restoreEnterOrExitViewTransitions(current); + } + } + break; + } + case ViewTransitionComponent: + const viewTransitionState: ViewTransitionState = finishedWork.stateNode; + viewTransitionState.clones = null; // Reset + recursivelyRestoreViewTransitions(finishedWork); + break; + default: { + recursivelyRestoreViewTransitions(finishedWork); + break; + } + } } // Revert transition names and start/adjust animations on the started View Transition. @@ -381,6 +988,6 @@ export function startGestureAnimations( root: FiberRoot, finishedWork: Fiber, ): void { - // TODO + restoreViewTransitionsOnFiber(finishedWork); restoreRootViewTransitionName(root.containerInfo); } diff --git a/packages/react-reconciler/src/ReactFiberCommitViewTransitions.js b/packages/react-reconciler/src/ReactFiberCommitViewTransitions.js index 22b9d11ac6..09f749bd22 100644 --- a/packages/react-reconciler/src/ReactFiberCommitViewTransitions.js +++ b/packages/react-reconciler/src/ReactFiberCommitViewTransitions.js @@ -71,15 +71,40 @@ export let viewTransitionCancelableChildren: null | Array< Instance | string | Props, > = null; // tupled array where each entry is [instance: Instance, oldName: string, props: Props] -export function setViewTransitionCancelableChildren( - children: null | Array, +export function pushViewTransitionCancelableScope(): null | Array< + Instance | string | Props, +> { + const prevChildren = viewTransitionCancelableChildren; + viewTransitionCancelableChildren = null; + return prevChildren; +} + +export function popViewTransitionCancelableScope( + prevChildren: null | Array, ): void { - viewTransitionCancelableChildren = children; + viewTransitionCancelableChildren = prevChildren; } let viewTransitionHostInstanceIdx = 0; -function applyViewTransitionToHostInstances( +export function applyViewTransitionToHostInstances( + child: null | Fiber, + name: string, + className: ?string, + collectMeasurements: null | Array, + stopAtNestedViewTransitions: boolean, +): boolean { + viewTransitionHostInstanceIdx = 0; + return applyViewTransitionToHostInstancesRecursive( + child, + name, + className, + collectMeasurements, + stopAtNestedViewTransitions, + ); +} + +function applyViewTransitionToHostInstancesRecursive( child: null | Fiber, name: string, className: ?string, @@ -128,7 +153,7 @@ function applyViewTransitionToHostInstances( // inner most one is the one that handles the update. } else { if ( - applyViewTransitionToHostInstances( + applyViewTransitionToHostInstancesRecursive( child.child, name, className, @@ -207,7 +232,6 @@ function commitAppearingPairViewTransitions(placement: Fiber): void { if (className !== 'none') { // We found a new appearing view transition with the same name as this deletion. // We'll transition between them. - viewTransitionHostInstanceIdx = 0; const inViewport = applyViewTransitionToHostInstances( child.child, name, @@ -242,7 +266,6 @@ export function commitEnterViewTransitions(placement: Fiber): void { state.paired ? props.share : props.enter, ); if (className !== 'none') { - viewTransitionHostInstanceIdx = 0; const inViewport = applyViewTransitionToHostInstances( placement.child, name, @@ -310,7 +333,6 @@ function commitDeletedPairViewTransitions(deletion: Fiber): void { ); if (className !== 'none') { // We found a new appearing view transition with the same name as this deletion. - viewTransitionHostInstanceIdx = 0; const inViewport = applyViewTransitionToHostInstances( child.child, name, @@ -361,7 +383,6 @@ export function commitExitViewTransitions(deletion: Fiber): void { pair !== undefined ? props.share : props.exit, ); if (className !== 'none') { - viewTransitionHostInstanceIdx = 0; const inViewport = applyViewTransitionToHostInstances( deletion.child, name, @@ -449,7 +470,6 @@ export function commitBeforeUpdateViewTransition( return; } } - viewTransitionHostInstanceIdx = 0; applyViewTransitionToHostInstances( current.child, oldName, @@ -472,7 +492,6 @@ export function commitNestedViewTransitions(changedParent: Fiber): void { props.layout, ); if (className !== 'none') { - viewTransitionHostInstanceIdx = 0; applyViewTransitionToHostInstances( child.child, name, @@ -514,37 +533,20 @@ function restorePairedViewTransitions(parent: Fiber): void { } } -export function restoreEnterViewTransitions(placement: Fiber): void { - if (placement.tag === ViewTransitionComponent) { - const instance: ViewTransitionState = placement.stateNode; +export function restoreEnterOrExitViewTransitions(fiber: Fiber): void { + if (fiber.tag === ViewTransitionComponent) { + const instance: ViewTransitionState = fiber.stateNode; instance.paired = null; - restoreViewTransitionOnHostInstances(placement.child, false); - restorePairedViewTransitions(placement); - } else if ((placement.subtreeFlags & ViewTransitionStatic) !== NoFlags) { - let child = placement.child; + restoreViewTransitionOnHostInstances(fiber.child, false); + restorePairedViewTransitions(fiber); + } else if ((fiber.subtreeFlags & ViewTransitionStatic) !== NoFlags) { + let child = fiber.child; while (child !== null) { - restoreEnterViewTransitions(child); + restoreEnterOrExitViewTransitions(child); child = child.sibling; } } else { - restorePairedViewTransitions(placement); - } -} - -export function restoreExitViewTransitions(deletion: Fiber): void { - if (deletion.tag === ViewTransitionComponent) { - const instance: ViewTransitionState = deletion.stateNode; - instance.paired = null; - restoreViewTransitionOnHostInstances(deletion.child, false); - restorePairedViewTransitions(deletion); - } else if ((deletion.subtreeFlags & ViewTransitionStatic) !== NoFlags) { - let child = deletion.child; - while (child !== null) { - restoreExitViewTransitions(child); - child = child.sibling; - } - } else { - restorePairedViewTransitions(deletion); + restorePairedViewTransitions(fiber); } } @@ -570,9 +572,22 @@ export function restoreNestedViewTransitions(changedParent: Fiber): void { } } -function cancelViewTransitionHostInstances( - currentViewTransition: Fiber, +export function cancelViewTransitionHostInstances( child: null | Fiber, + oldName: string, + stopAtNestedViewTransitions: boolean, +): void { + viewTransitionHostInstanceIdx = 0; + cancelViewTransitionHostInstancesRecursive( + child, + oldName, + stopAtNestedViewTransitions, + ); +} + +function cancelViewTransitionHostInstancesRecursive( + child: null | Fiber, + oldName: string, stopAtNestedViewTransitions: boolean, ): void { if (!supportsMutation) { @@ -581,10 +596,6 @@ function cancelViewTransitionHostInstances( while (child !== null) { if (child.tag === HostComponent) { const instance: Instance = child.stateNode; - const oldName = getViewTransitionName( - currentViewTransition.memoizedProps, - currentViewTransition.stateNode, - ); if (viewTransitionCancelableChildren === null) { viewTransitionCancelableChildren = []; } @@ -606,9 +617,9 @@ function cancelViewTransitionHostInstances( // Skip any nested view transitions for updates since in that case the // inner most one is the one that handles the update. } else { - cancelViewTransitionHostInstances( - currentViewTransition, + cancelViewTransitionHostInstancesRecursive( child.child, + oldName, stopAtNestedViewTransitions, ); } @@ -616,11 +627,32 @@ function cancelViewTransitionHostInstances( } } -function measureViewTransitionHostInstances( - currentViewTransition: Fiber, +export function measureViewTransitionHostInstances( parentViewTransition: Fiber, child: null | Fiber, - name: string, + newName: string, + oldName: string, + className: ?string, + previousMeasurements: null | Array, + stopAtNestedViewTransitions: boolean, +): boolean { + viewTransitionHostInstanceIdx = 0; + return measureViewTransitionHostInstancesRecursive( + parentViewTransition, + child, + newName, + oldName, + className, + previousMeasurements, + stopAtNestedViewTransitions, + ); +} + +function measureViewTransitionHostInstancesRecursive( + parentViewTransition: Fiber, + child: null | Fiber, + newName: string, + oldName: string, className: ?string, previousMeasurements: null | Array, stopAtNestedViewTransitions: boolean, @@ -671,10 +703,10 @@ function measureViewTransitionHostInstances( applyViewTransitionName( instance, viewTransitionHostInstanceIdx === 0 - ? name + ? newName : // If we have multiple Host Instances below, we add a suffix to the name to give // each one a unique name. - name + '_' + viewTransitionHostInstanceIdx, + newName + '_' + viewTransitionHostInstanceIdx, className, ); } @@ -684,10 +716,6 @@ function measureViewTransitionHostInstances( // animating it. However, in the current model this only works if the parent also // doesn't animate. So we have to queue these and wait until we complete the parent // to cancel them. - const oldName = getViewTransitionName( - currentViewTransition.memoizedProps, - currentViewTransition.stateNode, - ); if (viewTransitionCancelableChildren === null) { viewTransitionCancelableChildren = []; } @@ -713,11 +741,11 @@ function measureViewTransitionHostInstances( parentViewTransition.flags |= child.flags & AffectedParentLayout; } else { if ( - measureViewTransitionHostInstances( - currentViewTransition, + measureViewTransitionHostInstancesRecursive( parentViewTransition, child.child, - name, + newName, + oldName, className, previousMeasurements, stopAtNestedViewTransitions, @@ -736,6 +764,11 @@ export function measureUpdateViewTransition( finishedWork: Fiber, ): boolean { const props: ViewTransitionProps = finishedWork.memoizedProps; + const newName = getViewTransitionName(props, finishedWork.stateNode); + const oldName = getViewTransitionName( + current.memoizedProps, + current.stateNode, + ); const updateClassName: ?string = getViewTransitionClassName( props.className, props.update, @@ -762,24 +795,21 @@ export function measureUpdateViewTransition( if (layoutClassName === 'none') { // If we did not update, then all changes are considered a layout. We'll // attempt to cancel. - viewTransitionHostInstanceIdx = 0; - cancelViewTransitionHostInstances(current, finishedWork.child, true); + cancelViewTransitionHostInstances(finishedWork.child, oldName, true); return false; } // We didn't update but we might still apply layout so we measure each // instance to see if it moved or resized. className = layoutClassName; } - const name = getViewTransitionName(props, finishedWork.stateNode); // If nothing changed due to a mutation, or children changing size // and the measurements end up unchanged, we should restore it to not animate. - viewTransitionHostInstanceIdx = 0; const previousMeasurements = current.memoizedState; const inViewport = measureViewTransitionHostInstances( - current, finishedWork, finishedWork.child, - name, + newName, + oldName, className, previousMeasurements, true, @@ -799,29 +829,25 @@ export function measureNestedViewTransitions(changedParent: Fiber): void { let child = changedParent.child; while (child !== null) { if (child.tag === ViewTransitionComponent) { - const current = child.alternate; - if (current !== null) { - const props: ViewTransitionProps = child.memoizedProps; - const name = getViewTransitionName(props, child.stateNode); - const className: ?string = getViewTransitionClassName( - props.className, - props.layout, - ); - viewTransitionHostInstanceIdx = 0; - const inViewport = measureViewTransitionHostInstances( - current, - child, - child.child, - name, - className, - child.memoizedState, - false, - ); - if ((child.flags & Update) === NoFlags || !inViewport) { - // Nothing changed. - } else { - scheduleViewTransitionEvent(child, props.onLayout); - } + const props: ViewTransitionProps = child.memoizedProps; + const name = getViewTransitionName(props, child.stateNode); + const className: ?string = getViewTransitionClassName( + props.className, + props.layout, + ); + const inViewport = measureViewTransitionHostInstances( + child, + child.child, + name, + name, // Since this is unchanged, new and old name is the same. + className, + child.memoizedState, + false, + ); + if ((child.flags & Update) === NoFlags || !inViewport) { + // Nothing changed. + } else { + scheduleViewTransitionEvent(child, props.onLayout); } } else if ((child.subtreeFlags & ViewTransitionStatic) !== NoFlags) { measureNestedViewTransitions(child); diff --git a/packages/react-reconciler/src/ReactFiberCommitWork.js b/packages/react-reconciler/src/ReactFiberCommitWork.js index 8b82e6a7e7..2663c1e087 100644 --- a/packages/react-reconciler/src/ReactFiberCommitWork.js +++ b/packages/react-reconciler/src/ReactFiberCommitWork.js @@ -246,8 +246,7 @@ import { commitExitViewTransitions, commitBeforeUpdateViewTransition, commitNestedViewTransitions, - restoreEnterViewTransitions, - restoreExitViewTransitions, + restoreEnterOrExitViewTransitions, restoreUpdateViewTransition, restoreNestedViewTransitions, measureUpdateViewTransition, @@ -255,7 +254,8 @@ import { resetAppearingViewTransitions, trackAppearingViewTransition, viewTransitionCancelableChildren, - setViewTransitionCancelableChildren, + pushViewTransitionCancelableScope, + popViewTransitionCancelableScope, } from './ReactFiberCommitViewTransitions'; import { viewTransitionMutationContext, @@ -2475,14 +2475,14 @@ function commitAfterMutationEffectsOnFiber( switch (finishedWork.tag) { case HostRoot: { viewTransitionContextChanged = false; - setViewTransitionCancelableChildren(null); + pushViewTransitionCancelableScope(); recursivelyTraverseAfterMutationEffects(root, finishedWork, lanes); if (!viewTransitionContextChanged) { // If we didn't leak any resizing out to the root, we don't have to transition // the root itself. This means that we can now safely cancel any cancellations // that bubbled all the way up. const cancelableChildren = viewTransitionCancelableChildren; - setViewTransitionCancelableChildren(null); + popViewTransitionCancelableScope(null); if (cancelableChildren !== null) { for (let i = 0; i < cancelableChildren.length; i += 3) { cancelViewTransitionName( @@ -2533,9 +2533,8 @@ function commitAfterMutationEffectsOnFiber( const wasMutated = (finishedWork.flags & Update) !== NoFlags; const prevContextChanged = viewTransitionContextChanged; - const prevCancelableChildren = viewTransitionCancelableChildren; + const prevCancelableChildren = pushViewTransitionCancelableScope(); viewTransitionContextChanged = false; - setViewTransitionCancelableChildren(null); recursivelyTraverseAfterMutationEffects(root, finishedWork, lanes); if (viewTransitionContextChanged) { @@ -2558,7 +2557,7 @@ function commitAfterMutationEffectsOnFiber( prevCancelableChildren, viewTransitionCancelableChildren, ); - setViewTransitionCancelableChildren(prevCancelableChildren); + popViewTransitionCancelableScope(prevCancelableChildren); } // TODO: If this doesn't end up canceled, because a parent animates, // then we should probably issue an event since this instance is part of it. @@ -2572,7 +2571,7 @@ function commitAfterMutationEffectsOnFiber( ); // If this boundary did update, we cannot cancel its children so those are dropped. - setViewTransitionCancelableChildren(prevCancelableChildren); + popViewTransitionCancelableScope(prevCancelableChildren); } if ((finishedWork.flags & AffectedParentLayout) !== NoFlags) { @@ -3228,7 +3227,7 @@ function commitPassiveMountOnFiber( // This was a new mount. This means we could've triggered an enter animation on // the content. Restore the view transitions if there were any assigned in the // snapshot phase. - restoreEnterViewTransitions(finishedWork); + restoreEnterOrExitViewTransitions(finishedWork); } // When updating this function, also update reconnectPassiveEffects, which does @@ -3529,7 +3528,7 @@ function commitPassiveMountOnFiber( // Content is now hidden but wasn't before. This means we could've // triggered an exit animation on the content. Restore the view // transitions if there were any assigned in the snapshot phase. - restoreExitViewTransitions(current); + restoreEnterOrExitViewTransitions(current); } if (instance._visibility & OffscreenPassiveEffectsConnected) { // The effects are currently connected. Update them. @@ -3576,7 +3575,7 @@ function commitPassiveMountOnFiber( // Content is now visible but wasn't before. This means we could've // triggered an enter animation on the content. Restore the view // transitions if there were any assigned in the snapshot phase. - restoreEnterViewTransitions(finishedWork); + restoreEnterOrExitViewTransitions(finishedWork); } if (instance._visibility & OffscreenPassiveEffectsConnected) { // The effects are currently connected. Update them. diff --git a/packages/react-reconciler/src/ReactFiberViewTransitionComponent.js b/packages/react-reconciler/src/ReactFiberViewTransitionComponent.js index 16b5ef3049..ecacf2a439 100644 --- a/packages/react-reconciler/src/ReactFiberViewTransitionComponent.js +++ b/packages/react-reconciler/src/ReactFiberViewTransitionComponent.js @@ -9,7 +9,7 @@ import type {ReactNodeList} from 'shared/ReactTypes'; import type {FiberRoot} from './ReactInternalTypes'; -import type {ViewTransitionInstance} from './ReactFiberConfig'; +import type {ViewTransitionInstance, Instance} from './ReactFiberConfig'; import { getWorkInProgressRoot, @@ -45,6 +45,7 @@ export type ViewTransitionProps = { export type ViewTransitionState = { autoName: null | string, // the view-transition-name to use when an explicit one is not specified paired: null | ViewTransitionState, // a temporary state during the commit phase if we have paired this with another instance + clones: null | Array, // a temporary state during the apply gesture phase if we cloned this boundary ref: null | ViewTransitionInstance, // the current ref instance. This can change through the lifetime of the instance. }; diff --git a/packages/react-reconciler/src/ReactFiberWorkLoop.js b/packages/react-reconciler/src/ReactFiberWorkLoop.js index d7fe089363..380fa20c3d 100644 --- a/packages/react-reconciler/src/ReactFiberWorkLoop.js +++ b/packages/react-reconciler/src/ReactFiberWorkLoop.js @@ -3927,6 +3927,9 @@ function commitGestureOnRoot( } function flushGestureMutations(): void { + if (!enableSwipeTransition) { + return; + } if (pendingEffectsStatus !== PENDING_GESTURE_MUTATION_PHASE) { return; } @@ -3953,6 +3956,9 @@ function flushGestureMutations(): void { } function flushGestureAnimations(): void { + if (!enableSwipeTransition) { + return; + } // If we get canceled before we start we might not have applied // mutations yet. We need to apply them first. flushGestureMutations(); diff --git a/scripts/react-compiler/build-compiler.sh b/scripts/react-compiler/build-compiler.sh index 1c65fdcaa6..f732586462 100755 --- a/scripts/react-compiler/build-compiler.sh +++ b/scripts/react-compiler/build-compiler.sh @@ -11,5 +11,4 @@ if [[ "$REACT_CLASS_EQUIVALENCE_TEST" == "true" ]]; then fi echo "Building babel-plugin-react-compiler..." -yarn --cwd compiler install --frozen-lockfile yarn --cwd compiler workspace babel-plugin-react-compiler build --dts