From a4d122f2d192fe0b6480e669cca43c8f953aaf85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Markb=C3=A5ge?= Date: Wed, 8 Jan 2025 12:11:18 -0500 Subject: [PATCH] Add Component (#31975) This will provide the opt-in for using [View Transitions](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API) in React. View Transitions only trigger for async updates like `startTransition`, `useDeferredValue`, Actions or `` revealing from fallback to content. Synchronous updates provide an opt-out but also guarantee that they commit immediately which View Transitions can't. There's no need to opt-in to View Transitions at the "cause" side like event handlers or actions. They don't know what UI will change and whether that has an animated transition described. Conceptually the `` component is like a DOM fragment that transitions its children in its own isolate/snapshot. The API works by wrapping a DOM node or inner component: ```js import {ViewTransition} from 'react'; ``` The default is `name="auto"` which will automatically assign a `view-transition-name` to the inner DOM node. That way you can add a View Transition to a Component without controlling its DOM nodes styling otherwise. A difference between this and the browser's built-in `view-transition-name: auto` is that switching the DOM nodes within the `` component preserves the same name so this example cross-fades between the DOM nodes instead of causing an exit and enter: ```js {condition ? : } ``` This becomes especially useful with `` as this example cross-fades between Skeleton and Content: ```js }> ``` Where as this example triggers an exit of the Skeleton and an enter of the Content: ```js }> ``` Managing instances and keys becomes extra important. You can also specify an explicit `name` property for example for animating the same conceptual item from one page onto another. However, best practices is to property namespace these since they can easily collide. It's also useful to add an `id` to it if available. ```js ``` The model in general is the same as plain `view-transition-name` except React manages a set of heuristics for when to apply it. A problem with the naive View Transitions model is that it overly opts in every boundary that *might* transition into transitioning. This is leads to unfortunate effects like things floating around when unrelated updates happen. This leads the whole document to animate which means that nothing is clickable in the meantime. It makes it not useful for smaller and more local transitions. Best practice is to add `view-transition-name` only right before you're about to need to animate the thing. This is tricky to manage globally on complex apps and is not compositional. Instead we let React manage when a `` "activates" and add/remove the `view-transition-name`. This is also when React calls `startViewTransition` behind the scenes while it mutates the DOM. I've come up with a number of heuristics that I think will make a lot easier to coordinate this. The principle is that only if something that updates that particular boundary do we activate it. I hope that one day maybe browsers will have something like these built-in and we can remove our implementation. A `` only activates if: - If a mounted Component renders a `` within it outside the first DOM node, and it is within the viewport, then that ViewTransition activates as an "enter" animation. This avoids inner "enter" animations trigger when the parent mounts. - If an unmounted Component had a `` within it outside the first DOM node, and it was within the viewport, then that ViewTransition activates as an "exit" animation. This avoids inner "exit" animations triggering when the parent unmounts. - If an explicitly named `` is deep within an unmounted tree and one with the same name appears in a mounted tree at the same time, then both are activated as a pair, but only if they're both in the viewport. This avoids these triggering "enter" or "exit" animations when going between parents that don't have a pair. - If an already mounted `` is visible and a DOM mutation, that might affect how it's painted, happens within its children but outside any nested ``. This allows it to "cross-fade" between its updates. - If an already mounted `` resizes or moves as the result of direct DOM nodes siblings changing or moving around. This allows insertion, deletion and reorders into a list to animate all children. It is only within one DOM node though, to avoid unrelated changes in the parent to trigger this. If an item is outside the viewport before and after, then it's skipped to avoid things flying across the screen. - If a `` boundary changes size, due to a DOM mutation within it, then the parent activates (or the root document if there are no more parents). This ensures that the container can cross-fade to avoid abrupt relayout. This can be avoided by using absolutely positioned children. When this can avoid bubbling to the root document, whatever is not animating is still responsive to clicks during the transition. Conceptually each DOM node has its own default that activates the parent `` or no transition if the parent is the root. That means that if you add a DOM node like `
` this won't trigger an "enter" animation since it was the div that was added, not the ViewTransition. Instead, it might cause a cross-fade of the parent ViewTransition or no transition if it had no parent. This ensures that only explicit boundaries perform coarse animations instead of every single node which is really the benefit of the View Transitions model. This ends up working out well for simple cases like switching between two pages immediately while transitioning one floating item that appears on both pages. Because only the floating item transitions by default. Note that it's possible to add manual `view-transition-name` with CSS or `style={{ viewTransitionName: 'auto' }}` that always transitions as long as something else has a `` that activates. For example a `` can wrap a whole page for a cross-fade but inside of it an explicit name can be added to something to ensure it animates as a move when something relates else changes its layout. Instead of just cross-fading it along with the Page which would be the default. There's more PRs coming with some optimizations, fixes and expanded APIs. This first PR explores the above core heuristic. --------- Co-authored-by: Sebastian "Sebbie" Silbermann --- fixtures/view-transition/README.md | 30 + fixtures/view-transition/package.json | 28 + fixtures/view-transition/public/favicon.ico | Bin 0 -> 24838 bytes fixtures/view-transition/public/index.html | 13 + fixtures/view-transition/server/index.js | 70 + fixtures/view-transition/server/render.js | 44 + .../view-transition/src/components/App.js | 12 + .../view-transition/src/components/Chrome.css | 5 + .../view-transition/src/components/Chrome.js | 33 + .../view-transition/src/components/Page.css | 0 .../view-transition/src/components/Page.js | 79 + fixtures/view-transition/src/index.js | 6 + fixtures/view-transition/yarn.lock | 7049 +++++++++++++++++ packages/react-art/src/ReactFiberConfigART.js | 45 + packages/react-devtools-shared/src/utils.js | 4 + .../src/client/CSSPropertyOperations.js | 3 + .../src/client/DOMPropertyOperations.js | 3 + .../src/client/ReactDOMComponent.js | 76 +- .../src/client/ReactFiberConfigDOM.js | 226 +- packages/react-is/src/ReactIs.js | 2 + .../src/ReactFiberConfigNative.js | 67 + .../src/createReactNoop.js | 47 + packages/react-reconciler/src/ReactFiber.js | 29 + .../src/ReactFiberBeginWork.js | 44 + .../src/ReactFiberCommitHostEffects.js | 11 +- .../src/ReactFiberCommitWork.js | 1096 ++- .../src/ReactFiberCompleteWork.js | 75 + .../src/ReactFiberConfigWithNoMutation.js | 11 + .../react-reconciler/src/ReactFiberFlags.js | 87 +- .../react-reconciler/src/ReactFiberLane.js | 4 + .../src/ReactFiberMutationTracking.js | 33 + .../src/ReactFiberViewTransitionComponent.js | 70 + .../src/ReactFiberWorkLoop.js | 107 +- .../react-reconciler/src/ReactWorkTags.js | 4 +- .../src/forks/ReactFiberConfig.custom.js | 13 + .../src/ReactFizzComponentStack.js | 10 +- packages/react-server/src/ReactFizzServer.js | 12 + .../src/ReactFiberConfigTestHost.js | 66 + .../react/index.experimental.development.js | 1 + packages/react/index.experimental.js | 1 + packages/react/index.js | 1 + packages/react/src/ReactClient.js | 3 + .../ReactServer.experimental.development.js | 6 +- .../react/src/ReactServer.experimental.js | 6 +- packages/shared/ReactComponentStackFrame.js | 7 + packages/shared/ReactFeatureFlags.js | 2 + packages/shared/ReactSerializationErrors.js | 7 + packages/shared/ReactSymbols.js | 4 + .../forks/ReactFeatureFlags.native-fb.js | 1 + .../forks/ReactFeatureFlags.native-oss.js | 1 + .../forks/ReactFeatureFlags.test-renderer.js | 1 + ...actFeatureFlags.test-renderer.native-fb.js | 1 + .../ReactFeatureFlags.test-renderer.www.js | 1 + .../shared/forks/ReactFeatureFlags.www.js | 1 + packages/shared/getComponentNameFromType.js | 7 + packages/shared/isValidElementType.js | 5 +- scripts/error-codes/codes.json | 3 +- 57 files changed, 9474 insertions(+), 99 deletions(-) create mode 100644 fixtures/view-transition/README.md create mode 100644 fixtures/view-transition/package.json create mode 100644 fixtures/view-transition/public/favicon.ico create mode 100644 fixtures/view-transition/public/index.html create mode 100644 fixtures/view-transition/server/index.js create mode 100644 fixtures/view-transition/server/render.js create mode 100644 fixtures/view-transition/src/components/App.js create mode 100644 fixtures/view-transition/src/components/Chrome.css create mode 100644 fixtures/view-transition/src/components/Chrome.js create mode 100644 fixtures/view-transition/src/components/Page.css create mode 100644 fixtures/view-transition/src/components/Page.js create mode 100644 fixtures/view-transition/src/index.js create mode 100644 fixtures/view-transition/yarn.lock create mode 100644 packages/react-reconciler/src/ReactFiberMutationTracking.js create mode 100644 packages/react-reconciler/src/ReactFiberViewTransitionComponent.js diff --git a/fixtures/view-transition/README.md b/fixtures/view-transition/README.md new file mode 100644 index 0000000000..7f5642ee9c --- /dev/null +++ b/fixtures/view-transition/README.md @@ -0,0 +1,30 @@ +# View Transition + +A test case for View Transitions. + +## Setup + +To reference a local build of React, first run `npm run build` at the root +of the React project. Then: + +``` +cd fixtures/view-transition +yarn +yarn start +``` + +The `start` command runs a webpack dev server and a server-side rendering server in development mode with hot reloading. + +**Note: whenever you make changes to React and rebuild it, you need to re-run `yarn` in this folder:** + +``` +yarn +``` + +If you want to try the production mode instead run: + +``` +yarn start:prod +``` + +This will pre-build all static resources and then start a server-side rendering HTTP server that hosts the React app and service the static resources (without hot reloading). diff --git a/fixtures/view-transition/package.json b/fixtures/view-transition/package.json new file mode 100644 index 0000000000..8d47a5b17d --- /dev/null +++ b/fixtures/view-transition/package.json @@ -0,0 +1,28 @@ +{ + "name": "react-fixtures-view-transition", + "version": "0.1.0", + "private": true, + "devDependencies": { + "concurrently": "3.1.0", + "http-proxy-middleware": "0.17.3", + "react-scripts": "0.9.5" + }, + "dependencies": { + "express": "^4.14.0", + "ignore-styles": "^5.0.1", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "scripts": { + "predev": "cp -r ../../build/oss-experimental/* ./node_modules/", + "prestart": "cp -r ../../build/oss-experimental/* ./node_modules/", + "prebuild": "cp -r ../../build/oss-experimental/* ./node_modules/", + "dev": "concurrently \"npm run dev:server\" \"npm run dev:client\"", + "dev:client": "PORT=3001 react-scripts start", + "dev:server": "NODE_ENV=development node server", + "start": "react-scripts build && NODE_ENV=production node server", + "build": "react-scripts build", + "test": "react-scripts test --env=jsdom", + "eject": "react-scripts eject" + } +} diff --git a/fixtures/view-transition/public/favicon.ico b/fixtures/view-transition/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..5c125de5d897c1ff5692a656485b3216123dcd89 GIT binary patch literal 24838 zcmeI4X^>UL6@VY56)S&I{`6Nu0RscWCdj@GJHx(%?6_-;yKy1n;EEf9f}pr1CW5HA zYt$%U#C=}?jWH&%G@BaHBxsWAoUb3}&6%Ei@4Ii_JRa1`RQ23*yU)_wJ$?H0>6gj0 z${d_I^w5kvTW3xYEc?FvyP3>p$!py@`@T`|dVepIsjbbvR}af%KKy7YuQ%SDC^zmNWPYR^7avI5P-@dKev}UZ^aDAOyci9Nn zwR4qEz~tSvrp|#ACvWzo9`3B;`}^{t18dxaH;?xT7#hmJiKAaI;|O=$yxzXNOHGw~ z^!5pE^SW`av%t_$22LFPsM^l%=PSp!3r`>9w%s+^ZQYnnTQ*Ggd9-1~kj_o$YdW@b ztCkJ(ZGYjusqV5L4{^)R9Gt@gzU1t|?xhE&c^q(|(R#oa*}Sj5c({A$mh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(* z!F&5X*?S&}YoDCyzwv1H+XI(+rL`;RN9}iLxlfr-r&vGG8OQa@=>+a)+Ij)sd_{wu z1Am(+3-RFr4&N8N6+hqo19S#;SA1-hG>07p3}&*j4CR+rqdV)^6n; z_vFr!(a%-=#=kb{pYmNL@6|DWkw~%E2V2jYl*e1}c{e$fib?(O+hs}eoBLRo&9(;J}YV}0Mi;LZAe{U$(s= zT<-IaV$Z+q-P!~3{HxN>Kbw30jXzM&I(S<6Ksx^}HvU2Vntb!etSsm0>)j}Me^+L5{2yz--)?W`Q?az z!WLG4UNP}+#C+NKH+ZG-Q=E>IPp%LuKLx$$8NAOGr(#~P>!EA zDYlpXDR=xM?Xv5(-qp74Cw3LzBeASHSBY`OezkbOyjP!G%WSymju_C$VBl--z + + + + + diff --git a/fixtures/view-transition/server/index.js b/fixtures/view-transition/server/index.js new file mode 100644 index 0000000000..dd8a783b50 --- /dev/null +++ b/fixtures/view-transition/server/index.js @@ -0,0 +1,70 @@ +require('ignore-styles'); +const babelRegister = require('babel-register'); +const proxy = require('http-proxy-middleware'); + +babelRegister({ + ignore: /\/(build|node_modules)\//, + presets: ['react-app'], +}); + +const express = require('express'); +const path = require('path'); + +const app = express(); + +// Application +if (process.env.NODE_ENV === 'development') { + app.get('/', function (req, res) { + // In development mode we clear the module cache between each request to + // get automatic hot reloading. + for (var key in require.cache) { + delete require.cache[key]; + } + const render = require('./render').default; + render(req.url, res); + }); +} else { + const render = require('./render').default; + app.get('/', function (req, res) { + render(req.url, res); + }); +} + +// Static resources +app.use(express.static(path.resolve(__dirname, '..', 'build'))); + +// Proxy everything else to create-react-app's webpack development server +if (process.env.NODE_ENV === 'development') { + app.use( + '/', + proxy({ + ws: true, + target: 'http://localhost:3001', + }) + ); +} + +app.listen(3000, () => { + console.log('Listening on port 3000...'); +}); + +app.on('error', function (error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; + + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +}); diff --git a/fixtures/view-transition/server/render.js b/fixtures/view-transition/server/render.js new file mode 100644 index 0000000000..1b37987edb --- /dev/null +++ b/fixtures/view-transition/server/render.js @@ -0,0 +1,44 @@ +import React from 'react'; +import {renderToPipeableStream} from 'react-dom/server'; + +import App from '../src/components/App'; + +let assets; +if (process.env.NODE_ENV === 'development') { + // Use the bundle from create-react-app's server in development mode. + assets = { + 'main.js': '/static/js/bundle.js', + // 'main.css': '', + }; +} else { + assets = require('../build/asset-manifest.json'); +} + +export default function render(url, res) { + res.socket.on('error', error => { + // Log fatal errors + console.error('Fatal', error); + }); + let didError = false; + const {pipe, abort} = renderToPipeableStream(, { + bootstrapScripts: [assets['main.js']], + onShellReady() { + // If something errored before we started streaming, we set the error code appropriately. + res.statusCode = didError ? 500 : 200; + res.setHeader('Content-type', 'text/html'); + pipe(res); + }, + onShellError(x) { + // Something errored before we could complete the shell so we emit an alternative shell. + res.statusCode = 500; + res.send('

Error

'); + }, + onError(x) { + didError = true; + console.error(x); + }, + }); + // Abandon and switch to client rendering after 5 seconds. + // Try lowering this to see the client recover. + setTimeout(abort, 5000); +} diff --git a/fixtures/view-transition/src/components/App.js b/fixtures/view-transition/src/components/App.js new file mode 100644 index 0000000000..6867b29d4c --- /dev/null +++ b/fixtures/view-transition/src/components/App.js @@ -0,0 +1,12 @@ +import React from 'react'; + +import Chrome from './Chrome'; +import Page from './Page'; + +export default function App({assets}) { + return ( + + + + ); +} diff --git a/fixtures/view-transition/src/components/Chrome.css b/fixtures/view-transition/src/components/Chrome.css new file mode 100644 index 0000000000..b019b57b1d --- /dev/null +++ b/fixtures/view-transition/src/components/Chrome.css @@ -0,0 +1,5 @@ +body { + margin: 10px; + padding: 0; + font-family: sans-serif; +} diff --git a/fixtures/view-transition/src/components/Chrome.js b/fixtures/view-transition/src/components/Chrome.js new file mode 100644 index 0000000000..0cae4a8dd1 --- /dev/null +++ b/fixtures/view-transition/src/components/Chrome.js @@ -0,0 +1,33 @@ +import React, {Component} from 'react'; + +import './Chrome.css'; + +export default class Chrome extends Component { + render() { + const assets = this.props.assets; + return ( + + + + + + + {this.props.title} + + +