Skip to content

Commit 540efeb

Browse files
authored
View Transition Events (#32041)
This adds five events to `<ViewTransition>` that triggers when React wants to animate it. - `onEnter`: The `<ViewTransition>` or its parent Component is mounted and there's no other `<ViewTransition>` with the same name being deleted. - `onExit`: The `<ViewTransition>` or its parent Component is unmounted and there's no other `<ViewTransition>` with the same name being deleted. - `onLayout`: There are no updates to the content inside this `<ViewTransition>` boundary itself but the boundary has resized or moved due to other changes to siblings. - `onShare`: This `<ViewTransition>` is being mounted and another `<ViewTransition>` instance with the same name is being unmounted elsewhere. - `onUpdate`: The content of `<ViewTransition>` has changed either due to DOM mutations or because an inner child `<ViewTransition>` has resized. Only one of these events is fired per Transition. If you want to cover all updates you have to listen to `onLayout`, `onShare` and `onUpdate`. We could potentially do something like fire `onUpdate` if `onLayout` or `onShare` isn't specified but it's a little sketchy to have behavior based on if someone is listening since it limits adding wrappers that may or may not need it. Each takes a `ViewTransitionInstance` as an argument so you don't need a ref to animate it. ```js <ViewTransition onEnter={inst => inst.new.animate(keyframes, options)}> ``` The timing of this event is after the View Transition's `ready` state which means that's too late to do any changes to the View Transition's snapshots but now both the new and old pseudo-elements are ready to animate. The order of `onExit` is parent first, where as the others are child first. This mimics effect mount/unmount. I implement this by adding to a queue in the commit phase and then call it while we're finishing up the commit. This is after layout effects but before passive effects since passive effects fire after the animation is `finished`.
1 parent 0bf1f39 commit 540efeb

File tree

4 files changed

+93
-19
lines changed

4 files changed

+93
-19
lines changed

fixtures/view-transition/src/components/Page.js

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import React, {
22
unstable_ViewTransition as ViewTransition,
33
unstable_Activity as Activity,
4-
useRef,
5-
useLayoutEffect,
64
} from 'react';
75

86
import './Page.css';
@@ -37,21 +35,17 @@ function Component() {
3735
}
3836

3937
export default function Page({url, navigate}) {
40-
const ref = useRef();
4138
const show = url === '/?b';
42-
useLayoutEffect(() => {
43-
const viewTransition = ref.current;
44-
requestAnimationFrame(() => {
45-
const keyframes = [
46-
{rotate: '0deg', transformOrigin: '30px 8px'},
47-
{rotate: '360deg', transformOrigin: '30px 8px'},
48-
];
49-
viewTransition.old.animate(keyframes, 300);
50-
viewTransition.new.animate(keyframes, 300);
51-
});
52-
}, [show]);
39+
function onTransition(viewTransition) {
40+
const keyframes = [
41+
{rotate: '0deg', transformOrigin: '30px 8px'},
42+
{rotate: '360deg', transformOrigin: '30px 8px'},
43+
];
44+
viewTransition.old.animate(keyframes, 250);
45+
viewTransition.new.animate(keyframes, 250);
46+
}
5347
const exclamation = (
54-
<ViewTransition name="exclamation">
48+
<ViewTransition name="exclamation" onShare={onTransition}>
5549
<span>!</span>
5650
</ViewTransition>
5751
);
@@ -76,7 +70,7 @@ export default function Page({url, navigate}) {
7670
{a}
7771
</div>
7872
)}
79-
<ViewTransition ref={ref}>
73+
<ViewTransition>
8074
{show ? <div>hello{exclamation}</div> : <section>Loading</section>}
8175
</ViewTransition>
8276
<p>scroll me</p>

packages/react-reconciler/src/ReactFiberCommitWork.js

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ import {
186186
addMarkerIncompleteCallbackToPendingTransition,
187187
addMarkerCompleteCallbackToPendingTransition,
188188
retryDehydratedSuspenseBoundary,
189+
scheduleViewTransitionEvent,
189190
} from './ReactFiberWorkLoop';
190191
import {
191192
HasEffect as HookHasEffect,
@@ -649,6 +650,7 @@ function commitAppearingPairViewTransitions(placement: Fiber): void {
649650
if (child.tag === OffscreenComponent && child.memoizedState === null) {
650651
// This tree was already hidden so we skip it.
651652
} else {
653+
commitAppearingPairViewTransitions(child);
652654
if (
653655
child.tag === ViewTransitionComponent &&
654656
(child.flags & ViewTransitionNamedStatic) !== NoFlags
@@ -682,7 +684,6 @@ function commitAppearingPairViewTransitions(placement: Fiber): void {
682684
}
683685
}
684686
}
685-
commitAppearingPairViewTransitions(child);
686687
}
687688
child = child.sibling;
688689
}
@@ -701,12 +702,18 @@ function commitEnterViewTransitions(placement: Fiber): void {
701702
false,
702703
);
703704
if (!inViewport) {
705+
// TODO: If this was part of a pair we will still run the onShare callback.
704706
// Revert the transition names. This boundary is not in the viewport
705707
// so we won't bother animating it.
706708
restoreViewTransitionOnHostInstances(placement.child, false);
707709
// TODO: Should we still visit the children in case a named one was in the viewport?
708710
} else {
709711
commitAppearingPairViewTransitions(placement);
712+
713+
const state: ViewTransitionState = placement.stateNode;
714+
if (!state.paired) {
715+
scheduleViewTransitionEvent(placement, props.onEnter);
716+
}
710717
}
711718
} else if ((placement.subtreeFlags & ViewTransitionStatic) !== NoFlags) {
712719
let child = placement.child;
@@ -764,6 +771,9 @@ function commitDeletedPairViewTransitions(
764771
const oldinstance: ViewTransitionState = child.stateNode;
765772
const newInstance: ViewTransitionState = pair;
766773
newInstance.paired = oldinstance;
774+
// Note: If the other side ends up outside the viewport, we'll still run this.
775+
// Therefore it's possible for onShare to be called with only an old snapshot.
776+
scheduleViewTransitionEvent(child, props.onShare);
767777
}
768778
// Delete the entry so that we know when we've found all of them
769779
// and can stop searching (size reaches zero).
@@ -811,9 +821,16 @@ function commitExitViewTransitions(
811821
// Delete the entry so that we know when we've found all of them
812822
// and can stop searching (size reaches zero).
813823
appearingViewTransitions.delete(name);
824+
// Note: If the other side ends up outside the viewport, we'll still run this.
825+
// Therefore it's possible for onShare to be called with only an old snapshot.
826+
scheduleViewTransitionEvent(deletion, props.onShare);
827+
} else {
828+
scheduleViewTransitionEvent(deletion, props.onExit);
814829
}
815830
// Look for more pairs deeper in the tree.
816831
commitDeletedPairViewTransitions(deletion, appearingViewTransitions);
832+
} else {
833+
scheduleViewTransitionEvent(deletion, props.onExit);
817834
}
818835
} else if ((deletion.subtreeFlags & ViewTransitionStatic) !== NoFlags) {
819836
let child = deletion.child;
@@ -1118,6 +1135,8 @@ function measureNestedViewTransitions(changedParent: Fiber): void {
11181135
child.memoizedState,
11191136
false,
11201137
);
1138+
const props: ViewTransitionProps = child.memoizedProps;
1139+
scheduleViewTransitionEvent(child, props.onLayout);
11211140
}
11221141
} else if ((child.subtreeFlags & ViewTransitionStatic) !== NoFlags) {
11231142
measureNestedViewTransitions(child);
@@ -3075,6 +3094,8 @@ function commitAfterMutationEffectsOnFiber(
30753094
(Placement | Update | ChildDeletion | ContentReset | Visibility)) !==
30763095
NoFlags
30773096
) {
3097+
const wasMutated = (finishedWork.flags & Update) !== NoFlags;
3098+
30783099
const prevContextChanged = viewTransitionContextChanged;
30793100
const prevCancelableChildren = viewTransitionCancelableChildren;
30803101
viewTransitionContextChanged = false;
@@ -3103,7 +3124,17 @@ function commitAfterMutationEffectsOnFiber(
31033124
);
31043125
viewTransitionCancelableChildren = prevCancelableChildren;
31053126
}
3127+
// TODO: If this doesn't end up canceled, because a parent animates,
3128+
// then we should probably issue an event since this instance is part of it.
31063129
} else {
3130+
const props: ViewTransitionProps = finishedWork.memoizedProps;
3131+
scheduleViewTransitionEvent(
3132+
finishedWork,
3133+
wasMutated || viewTransitionContextChanged
3134+
? props.onUpdate
3135+
: props.onLayout,
3136+
);
3137+
31073138
// If this boundary did update, we cannot cancel its children so those are dropped.
31083139
viewTransitionCancelableChildren = prevCancelableChildren;
31093140
}

packages/react-reconciler/src/ReactFiberViewTransitionComponent.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ export type ViewTransitionProps = {
2121
name?: string,
2222
className?: string,
2323
children?: ReactNodeList,
24+
onEnter?: (instance: ViewTransitionInstance) => void,
25+
onExit?: (instance: ViewTransitionInstance) => void,
26+
onLayout?: (instance: ViewTransitionInstance) => void,
27+
onShare?: (instance: ViewTransitionInstance) => void,
28+
onUpdate?: (instance: ViewTransitionInstance) => void,
2429
};
2530

2631
export type ViewTransitionState = {

packages/react-reconciler/src/ReactFiberWorkLoop.js

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,12 @@ import type {
2121
TransitionAbort,
2222
} from './ReactFiberTracingMarkerComponent';
2323
import type {OffscreenInstance} from './ReactFiberActivityComponent';
24-
import type {Resource} from './ReactFiberConfig';
24+
import type {Resource, ViewTransitionInstance} from './ReactFiberConfig';
2525
import type {RootState} from './ReactFiberRoot';
26-
import type {ViewTransitionState} from './ReactFiberViewTransitionComponent';
26+
import {
27+
getViewTransitionName,
28+
type ViewTransitionState,
29+
} from './ReactFiberViewTransitionComponent';
2730

2831
import {
2932
enableCreateEventHandleAPI,
@@ -95,6 +98,7 @@ import {
9598
resolveUpdatePriority,
9699
trackSchedulerEvent,
97100
startViewTransition,
101+
createViewTransitionInstance,
98102
} from './ReactFiberConfig';
99103

100104
import {createWorkInProgress, resetWorkInProgress} from './ReactFiber';
@@ -649,6 +653,7 @@ let pendingEffectsRemainingLanes: Lanes = NoLanes;
649653
let pendingEffectsRenderEndTime: number = -0; // Profiling-only
650654
let pendingPassiveTransitions: Array<Transition> | null = null;
651655
let pendingRecoverableErrors: null | Array<CapturedValue<mixed>> = null;
656+
let pendingViewTransitionEvents: Array<() => void> | null = null;
652657
let pendingDidIncludeRenderPhaseUpdate: boolean = false;
653658
let pendingSuspendedCommitReason: SuspendedCommitReason = IMMEDIATE_COMMIT; // Profiling-only
654659

@@ -797,6 +802,27 @@ export function requestDeferredLane(): Lane {
797802
return workInProgressDeferredLane;
798803
}
799804

805+
export function scheduleViewTransitionEvent(
806+
fiber: Fiber,
807+
callback: ?(instance: ViewTransitionInstance) => void,
808+
): void {
809+
if (enableViewTransition) {
810+
if (callback != null) {
811+
const state: ViewTransitionState = fiber.stateNode;
812+
let instance = state.ref;
813+
if (instance === null) {
814+
instance = state.ref = createViewTransitionInstance(
815+
getViewTransitionName(fiber.memoizedProps, state),
816+
);
817+
}
818+
if (pendingViewTransitionEvents === null) {
819+
pendingViewTransitionEvents = [];
820+
}
821+
pendingViewTransitionEvents.push(callback.bind(null, instance));
822+
}
823+
}
824+
}
825+
800826
export function peekDeferredLane(): Lane {
801827
return workInProgressDeferredLane;
802828
}
@@ -3322,6 +3348,9 @@ function commitRoot(
33223348
pendingEffectsRemainingLanes = remainingLanes;
33233349
pendingPassiveTransitions = transitions;
33243350
pendingRecoverableErrors = recoverableErrors;
3351+
if (enableViewTransition) {
3352+
pendingViewTransitionEvents = null;
3353+
}
33253354
pendingDidIncludeRenderPhaseUpdate = didIncludeRenderPhaseUpdate;
33263355
if (enableProfilerTimer) {
33273356
pendingEffectsRenderEndTime = completedRenderEndTime;
@@ -3673,6 +3702,21 @@ function flushSpawnedWork(): void {
36733702
}
36743703
}
36753704

3705+
if (enableViewTransition) {
3706+
// We should now be after the startViewTransition's .ready call which is late enough
3707+
// to start animating any pseudo-elements. We do this before flushing any passive
3708+
// effects or spawned sync work since this is still part of the previous commit.
3709+
// Even though conceptually it's like its own task between layout effets and passive.
3710+
const pendingEvents = pendingViewTransitionEvents;
3711+
if (pendingEvents !== null) {
3712+
pendingViewTransitionEvents = null;
3713+
for (let i = 0; i < pendingEvents.length; i++) {
3714+
const viewTransitionEvent = pendingEvents[i];
3715+
viewTransitionEvent();
3716+
}
3717+
}
3718+
}
3719+
36763720
// If the passive effects are the result of a discrete render, flush them
36773721
// synchronously at the end of the current task so that the result is
36783722
// immediately observable. Otherwise, we assume that they are not

0 commit comments

Comments
 (0)