@samitouri / QOS-React-2 / commits / 8ce15b0f56

[Fizz] Apply View Transition Name and Class to SSR:ed View Transitions (#33332)

Stacked on #33330. This walks the element tree to activate the various classes under different scenarios. There are some edge case things that are a little different since we can't express every scenario without virtual nodes. The main thing that's still missing though is avoiding animating updates if it can be contained to a layout or enter/exit/share if they're out of the viewport. I.e. layout stuff.

Sebastian Markbåge committed May 22, 2025 at 10:40 UTC 8ce15b0f56a066ece465963ca1370e46113bb868
4 files changed +204 -19
fixtures/view-transition/server/render.js
-2
@@ -23,8 +23,6 @@ export default function render(url, res) {
23 const {pipe, abort} = renderToPipeableStream(
24 <App assets={assets} initialURL={url} />,
25 {
26 - // TODO: Temporary hack. Detect from attributes instead.
27 - bootstrapScriptContent: 'window._useVT = true;',
26 bootstrapScripts: [assets['main.js']],
27 onShellReady() {
28 // If something errored before we started streaming, we set the error code appropriately.
fixtures/view-transition/src/components/Page.js
+34 -14
@@ -200,21 +200,41 @@ export default function Page({url, navigate}) {
200 <div>!!</div>
201 </ViewTransition>
202 </Activity>
203 - <Suspense fallback="Loading">
203 + <Suspense
204 + fallback={
205 + <ViewTransition>
206 + <div>
207 + <ViewTransition name="shared-reveal">
208 + <h2>█████</h2>
209 + </ViewTransition>
210 + <p>████</p>
211 + <p>███████</p>
212 + <p>████</p>
213 + <p>██</p>
214 + <p>██████</p>
215 + <p>███</p>
216 + <p>████</p>
217 + </div>
218 + </ViewTransition>
219 + }>
220 <ViewTransition>
205 - <p>these</p>
206 - <p>rows</p>
207 - <p>exist</p>
208 - <p>to</p>
209 - <p>test</p>
210 - <p>scrolling</p>
211 - <p>content</p>
212 - <p>out</p>
213 - <p>of</p>
214 - {portal}
215 - <p>the</p>
216 - <p>viewport</p>
217 - <Suspend />
221 + <div>
222 + <p>these</p>
223 + <p>rows</p>
224 + <ViewTransition name="shared-reveal">
225 + <h2>exist</h2>
226 + </ViewTransition>
227 + <p>to</p>
228 + <p>test</p>
229 + <p>scrolling</p>
230 + <p>content</p>
231 + <p>out</p>
232 + <p>of</p>
233 + {portal}
234 + <p>the</p>
235 + <p>viewport</p>
236 + <Suspend />
237 + </div>
238 </ViewTransition>
239 </Suspense>
240 {show ? <Component /> : null}
packages/react-dom-bindings/src/server/fizz-instruction-set/ReactDOMFizzInstructionSetInlineCodeStrings.js
+1 -1
@@ -8,7 +8,7 @@ export const clientRenderBoundary =
8 export const completeBoundary =
9 '$RB=[];$RV=function(c){$RT=performance.now();for(var a=0;a<c.length;a+=2){var b=c[a],h=c[a+1],e=b.parentNode;if(e){var f=b.previousSibling,g=0;do{if(b&&8===b.nodeType){var d=b.data;if("/$"===d||"/&"===d)if(0===g)break;else g--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||g++}d=b.nextSibling;e.removeChild(b);b=d}while(b);for(;h.firstChild;)e.insertBefore(h.firstChild,b);f.data="$";f._reactRetry&&f._reactRetry()}}c.length=0};$RC=function(c,a){if(a=document.getElementById(a))if(a.parentNode.removeChild(a),c=document.getElementById(c))c.previousSibling.data="$~",$RB.push(c,a),2===$RB.length&&setTimeout($RV.bind(null,$RB),("number"!==typeof $RT?0:$RT)+300-performance.now())};';
10 export const completeBoundaryUpgradeToViewTransitions =
11 - '$RV=function(c,a){try{var d=document.__reactViewTransition;if(d){d.finished.finally($RV.bind(null,a));return}if(window._useVT){var b=document.__reactViewTransition=document.startViewTransition({update:c.bind(null,a),types:[]});b.ready.finally(function(){});b.finished.finally(function(){document.__reactViewTransition===b&&(document.__reactViewTransition=null)});$RB=[];return}}catch(e){}c(a)}.bind(null,$RV);';
11 + '$RV=function(w,f){function h(b,d){var k=b.getAttribute(d);k&&(d=b.style,l.push(b,d.viewTransitionName,d.viewTransitionClass),"auto"!==k&&(d.viewTransitionClass=k),(b=b.getAttribute("vt-name"))||(b="\\u00abT"+F++ +"\\u00bb"),d.viewTransitionName=b,x=!0)}var x=!1,F=0,l=[];try{var e=document.__reactViewTransition;if(e){e.finished.finally($RV.bind(null,f));return}var m=new Map;for(e=1;e<f.length;e+=2)for(var g=f[e].querySelectorAll("[vt-share]"),c=0;c<g.length;c++){var a=g[c];m.set(a.getAttribute("vt-name"),a)}for(g=0;g<f.length;g+=2){var y=f[g],t=y.parentNode;if(t){var r=t.getBoundingClientRect();if(r.left||r.top||r.width||r.height){a=y;for(e=0;a;){if(8===a.nodeType){var p=a.data;if("/$"===p)if(0===e)break;else e--;else"$"!==p&&"$?"!==p&&"$~"!==p&&"$!"!==p||e++}else if(1===a.nodeType){c=a;var z=c.getAttribute("vt-name"),u=m.get(z);h(c,u?"vt-share":"vt-exit");u&&(h(u,"vt-share"),m.set(z,null));var A=c.querySelectorAll("[vt-share]");for(c=0;c<A.length;c++){var B=A[c],C=B.getAttribute("vt-name"),D=m.get(C);\nD&&(h(B,"vt-share"),h(D,"vt-share"),m.set(C,null))}}a=a.nextSibling}for(var q=f[g+1].firstElementChild;q;)null!==m.get(q.getAttribute("vt-name"))&&h(q,"vt-enter"),q=q.nextElementSibling;a=t;do for(var n=a.firstElementChild;n;){var E=n.getAttribute("vt-update");E&&"none"!==E&&!l.includes(n)&&h(n,"vt-update");n=n.nextElementSibling}while((a=a.parentNode)&&1===a.nodeType&&"none"!==a.getAttribute("vt-update"))}}}if(x){var v=document.__reactViewTransition=document.startViewTransition({update:w.bind(null,\nf),types:[]});v.ready.finally(function(){for(var b=l.length-3;0<=b;b-=3){var d=l[b],k=d.style;k.viewTransitionName=l[b+1];k.viewTransitionClass=l[b+1];""===d.getAttribute("style")&&d.removeAttribute("style")}});v.finished.finally(function(){document.__reactViewTransition===v&&(document.__reactViewTransition=null)});$RB=[];return}}catch(b){}w(f)}.bind(null,$RV);';
12 export const completeBoundaryWithStyles =
13 '$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=\n"stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=\n"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};';
14 export const completeSegment =
packages/react-dom-bindings/src/server/fizz-instruction-set/ReactDOMFizzInstructionSetShared.js
+169 -2
@@ -3,6 +3,7 @@
3 // Shared implementation and constants between the inline script and external
4 // runtime instruction sets.
5
6 +const ELEMENT_NODE = 1;
7 const COMMENT_NODE = 8;
8 const ACTIVITY_START_DATA = '&';
9 const ACTIVITY_END_DATA = '/&';
@@ -84,6 +85,35 @@ export function revealCompletedBoundariesWithViewTransitions(
85 revealBoundaries,
86 batch,
87 ) {
88 + let shouldStartViewTransition = false;
89 + let autoNameIdx = 0;
90 + const restoreQueue = [];
91 + function applyViewTransitionName(element, classAttributeName) {
92 + const className = element.getAttribute(classAttributeName);
93 + if (!className) {
94 + return;
95 + }
96 + // Add any elements we apply a name to a queue to be reverted when we start.
97 + const elementStyle = element.style;
98 + restoreQueue.push(
99 + element,
100 + elementStyle['viewTransitionName'],
101 + elementStyle['viewTransitionClass'],
102 + );
103 + if (className !== 'auto') {
104 + elementStyle['viewTransitionClass'] = className;
105 + }
106 + let name = element.getAttribute('vt-name');
107 + if (!name) {
108 + // Auto-generate a name for this one.
109 + // TODO: We don't have a prefix to pick from here but maybe we don't need it
110 + // since it's only applicable temporarily during this specific animation.
111 + const idPrefix = '';
112 + name = '\u00AB' + idPrefix + 'T' + autoNameIdx++ + '\u00BB';
113 + }
114 + elementStyle['viewTransitionName'] = name;
115 + shouldStartViewTransition = true;
116 + }
117 try {
118 const existingTransition = document['__reactViewTransition'];
119 if (existingTransition) {
@@ -91,7 +121,132 @@ export function revealCompletedBoundariesWithViewTransitions(
121 existingTransition.finished.finally(window['$RV'].bind(null, batch));
122 return;
123 }
94 - const shouldStartViewTransition = window['_useVT']; // TODO: Detect.
124 + // First collect all entering names that might form pairs exiting names.
125 + const appearingViewTransitions = new Map();
126 + for (let i = 1; i < batch.length; i += 2) {
127 + const contentNode = batch[i];
128 + const appearingElements = contentNode.querySelectorAll('[vt-share]');
129 + for (let j = 0; j < appearingElements.length; j++) {
130 + const appearingElement = appearingElements[j];
131 + appearingViewTransitions.set(
132 + appearingElement.getAttribute('vt-name'),
133 + appearingElement,
134 + );
135 + }
136 + }
137 + // Next we'll find the nodes that we're going to animate and apply names to them..
138 + for (let i = 0; i < batch.length; i += 2) {
139 + const suspenseIdNode = batch[i];
140 + const parentInstance = suspenseIdNode.parentNode;
141 + if (!parentInstance) {
142 + // We may have client-rendered this boundary already. Skip it.
143 + continue;
144 + }
145 + const parentRect = parentInstance.getBoundingClientRect();
146 + if (
147 + !parentRect.left &&
148 + !parentRect.top &&
149 + !parentRect.width &&
150 + !parentRect.height
151 + ) {
152 + // If the parent instance is display: none then we don't animate this boundary.
153 + // This can happen when this boundary is actually a child of a different boundary that
154 + // isn't yet revealed or is about to be revealed, but in that case that boundary
155 + // should do the exit/enter and not this one. Conveniently this also lets us skip
156 + // this if it's just in a hidden tree in general.
157 + // TODO: Should we skip it if it's out of viewport? It's possible that it gets
158 + // brought into the viewport by changing size.
159 + // TODO: There's a another case where an inner boundary is inside a fallback that
160 + // is about to be deleted. In that case we should not run exit animations on the inner.
161 + continue;
162 + }
163 +
164 + // Apply exit animations to the immediate elements inside the fallback.
165 + let node = suspenseIdNode;
166 + let depth = 0;
167 + while (node) {
168 + if (node.nodeType === COMMENT_NODE) {
169 + const data = node.data;
170 + if (data === SUSPENSE_END_DATA) {
171 + if (depth === 0) {
172 + break;
173 + } else {
174 + depth--;
175 + }
176 + } else if (
177 + data === SUSPENSE_START_DATA ||
178 + data === SUSPENSE_PENDING_START_DATA ||
179 + data === SUSPENSE_QUEUED_START_DATA ||
180 + data === SUSPENSE_FALLBACK_START_DATA
181 + ) {
182 + depth++;
183 + }
184 + } else if (node.nodeType === ELEMENT_NODE) {
185 + const exitElement = node;
186 + const exitName = exitElement.getAttribute('vt-name');
187 + const pairedElement = appearingViewTransitions.get(exitName);
188 + applyViewTransitionName(
189 + exitElement,
190 + pairedElement ? 'vt-share' : 'vt-exit',
191 + );
192 + if (pairedElement) {
193 + // Activate the other side as well.
194 + applyViewTransitionName(pairedElement, 'vt-share');
195 + appearingViewTransitions.set(exitName, null); // mark claimed
196 + }
197 + // Next we'll look inside this element for pairs to trigger "share".
198 + const disappearingElements =
199 + exitElement.querySelectorAll('[vt-share]');
200 + for (let j = 0; j < disappearingElements.length; j++) {
201 + const disappearingElement = disappearingElements[j];
202 + const name = disappearingElement.getAttribute('vt-name');
203 + const appearingElement = appearingViewTransitions.get(name);
204 + if (appearingElement) {
205 + applyViewTransitionName(disappearingElement, 'vt-share');
206 + applyViewTransitionName(appearingElement, 'vt-share');
207 + appearingViewTransitions.set(name, null); // mark claimed
208 + }
209 + }
210 + }
211 + node = node.nextSibling;
212 + }
213 +
214 + // Apply enter animations to the new nodes about to be inserted.
215 + const contentNode = batch[i + 1];
216 + let enterElement = contentNode.firstElementChild;
217 + while (enterElement) {
218 + const paired =
219 + appearingViewTransitions.get(enterElement.getAttribute('vt-name')) ===
220 + null;
221 + if (!paired) {
222 + applyViewTransitionName(enterElement, 'vt-enter');
223 + }
224 + enterElement = enterElement.nextElementSibling;
225 + }
226 +
227 + // Apply update animations to any parents and siblings that might be affected.
228 + let ancestorElement = parentInstance;
229 + do {
230 + let childElement = ancestorElement.firstElementChild;
231 + while (childElement) {
232 + // TODO: Bail out if we can
233 + const updateClassName = childElement.getAttribute('vt-update');
234 + if (
235 + updateClassName &&
236 + updateClassName !== 'none' &&
237 + !restoreQueue.includes(childElement)
238 + ) {
239 + // If we have already handled this element as part of another exit/enter/share, don't override.
240 + applyViewTransitionName(childElement, 'vt-update');
241 + }
242 + childElement = childElement.nextElementSibling;
243 + }
244 + } while (
245 + (ancestorElement = ancestorElement.parentNode) &&
246 + ancestorElement.nodeType === ELEMENT_NODE &&
247 + ancestorElement.getAttribute('vt-update') !== 'none'
248 + );
249 + }
250 if (shouldStartViewTransition) {
251 const transition = (document['__reactViewTransition'] = document[
252 'startViewTransition'
@@ -100,7 +255,19 @@ export function revealCompletedBoundariesWithViewTransitions(
255 types: [], // TODO: Add a hard coded type for Suspense reveals.
256 }));
257 transition.ready.finally(() => {
103 - // TODO
258 + // Restore all the names/classes that we applied to what they were before.
259 + // We do it in reverse order in case there were duplicates so the first one wins.
260 + for (let i = restoreQueue.length - 3; i >= 0; i -= 3) {
261 + const element = restoreQueue[i];
262 + const elementStyle = element.style;
263 + const previousName = restoreQueue[i + 1];
264 + elementStyle['viewTransitionName'] = previousName;
265 + const previousClassName = restoreQueue[i + 1];
266 + elementStyle['viewTransitionClass'] = previousClassName;
267 + if (element.getAttribute('style') === '') {
268 + element.removeAttribute('style');
269 + }
270 + }
271 });
272 transition.finished.finally(() => {
273 if (document['__reactViewTransition'] === transition) {