Skip to content

Commit a53da6a

Browse files
authored
Add useSwipeTransition Hook Behind Experimental Flag (#32373)
This Hook will be used to drive a View Transition based on a gesture. ```js const [value, startGesture] = useSwipeTransition(prev, current, next); ``` The `enableSwipeTransition` flag will depend on `enableViewTransition` flag but we may decide to ship them independently. This PR doesn't do anything interesting yet. There will be a lot more PRs to build out the actual functionality. This is just wiring up the plumbing for the new Hook. This first PR is mainly concerned with how the whole starts (and stops). The core API is the `startGesture` function (although there will be other conveniences added in the future). You can call this to start a gesture with a source provider. You can call this multiple times in one event to batch multiple Hooks listening to the same provider. However, each render can only handle one source provider at a time and so it does one render per scheduled gesture provider. This uses a separate `GestureLane` to drive gesture renders by marking the Hook as having an update on that lane. Then schedule a render. These renders should be blocking and in the same microtask as the `startGesture` to ensure it can block the paint. So it's similar to sync. It may not be possible to finish it synchronously e.g. if something suspends. If so, it just tries again later when it can like any other render. This can also happen because it also may not be possible to drive more than one gesture at a time like if we're limited to one View Transition per document. So right now you can only run one gesture at a time in practice. These renders never commit. This means that we can't clear the `GestureLane` the normal way. Instead, we have to clear only the root's `pendingLanes` if we don't have any new renders scheduled. Then wait until something else updates the Fiber after all gestures on it have stopped before it really clears.
1 parent 32b0cad commit a53da6a

26 files changed

+647
-68
lines changed

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,14 @@
66
font-variation-settings:
77
"wdth" 100;
88
}
9+
10+
.swipe-recognizer {
11+
width: 200px;
12+
overflow-x: scroll;
13+
border: 1px solid #333333;
14+
border-radius: 10px;
15+
}
16+
17+
.swipe-overscroll {
18+
width: 200%;
19+
}

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

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import React, {
22
unstable_ViewTransition as ViewTransition,
33
unstable_Activity as Activity,
4+
unstable_useSwipeTransition as useSwipeTransition,
5+
useRef,
6+
useLayoutEffect,
47
} from 'react';
58

69
import './Page.css';
@@ -35,7 +38,8 @@ function Component() {
3538
}
3639

3740
export default function Page({url, navigate}) {
38-
const show = url === '/?b';
41+
const [renderedUrl, startGesture] = useSwipeTransition('/?a', url, '/?b');
42+
const show = renderedUrl === '/?b';
3943
function onTransition(viewTransition, types) {
4044
const keyframes = [
4145
{rotate: '0deg', transformOrigin: '30px 8px'},
@@ -44,6 +48,32 @@ export default function Page({url, navigate}) {
4448
viewTransition.old.animate(keyframes, 250);
4549
viewTransition.new.animate(keyframes, 250);
4650
}
51+
52+
const swipeRecognizer = useRef(null);
53+
const activeGesture = useRef(null);
54+
function onScroll() {
55+
if (activeGesture.current !== null) {
56+
return;
57+
}
58+
// eslint-disable-next-line no-undef
59+
const scrollTimeline = new ScrollTimeline({
60+
source: swipeRecognizer.current,
61+
axis: 'x',
62+
});
63+
activeGesture.current = startGesture(scrollTimeline);
64+
}
65+
function onScrollEnd() {
66+
if (activeGesture.current !== null) {
67+
const cancelGesture = activeGesture.current;
68+
activeGesture.current = null;
69+
cancelGesture();
70+
}
71+
}
72+
73+
useLayoutEffect(() => {
74+
swipeRecognizer.current.scrollLeft = show ? 0 : 10000;
75+
}, [show]);
76+
4777
const exclamation = (
4878
<ViewTransition name="exclamation" onShare={onTransition}>
4979
<span>!</span>
@@ -90,6 +120,13 @@ export default function Page({url, navigate}) {
90120
<p></p>
91121
<p></p>
92122
<p></p>
123+
<div
124+
className="swipe-recognizer"
125+
onScroll={onScroll}
126+
onScrollEnd={onScrollEnd}
127+
ref={swipeRecognizer}>
128+
<div className="swipe-overscroll">Swipe me</div>
129+
</div>
93130
<p></p>
94131
<p></p>
95132
{show ? null : (

packages/react-debug-tools/src/ReactDebugHooks.js

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type {
1414
Usable,
1515
Thenable,
1616
ReactDebugInfo,
17+
StartGesture,
1718
} from 'shared/ReactTypes';
1819
import type {
1920
ContextDependency,
@@ -131,6 +132,9 @@ function getPrimitiveStackCache(): Map<string, Array<any>> {
131132
if (typeof Dispatcher.useEffectEvent === 'function') {
132133
Dispatcher.useEffectEvent((args: empty) => {});
133134
}
135+
if (typeof Dispatcher.useSwipeTransition === 'function') {
136+
Dispatcher.useSwipeTransition(null, null, null);
137+
}
134138
} finally {
135139
readHookLog = hookLog;
136140
hookLog = [];
@@ -752,31 +756,50 @@ function useEffectEvent<Args, F: (...Array<Args>) => mixed>(callback: F): F {
752756
return callback;
753757
}
754758

759+
function useSwipeTransition<T>(
760+
previous: T,
761+
current: T,
762+
next: T,
763+
): [T, StartGesture] {
764+
nextHook();
765+
hookLog.push({
766+
displayName: null,
767+
primitive: 'SwipeTransition',
768+
stackError: new Error(),
769+
value: current,
770+
debugInfo: null,
771+
dispatcherHookName: 'SwipeTransition',
772+
});
773+
return [current, () => () => {}];
774+
}
775+
755776
const Dispatcher: DispatcherType = {
756-
use,
757777
readContext,
758-
useCacheRefresh,
778+
779+
use,
759780
useCallback,
760781
useContext,
761782
useEffect,
762783
useImperativeHandle,
763-
useDebugValue,
764784
useLayoutEffect,
765785
useInsertionEffect,
766786
useMemo,
767-
useMemoCache,
768-
useOptimistic,
769787
useReducer,
770788
useRef,
771789
useState,
790+
useDebugValue,
791+
useDeferredValue,
772792
useTransition,
773793
useSyncExternalStore,
774-
useDeferredValue,
775794
useId,
795+
useHostTransitionStatus,
776796
useFormState,
777797
useActionState,
778-
useHostTransitionStatus,
798+
useOptimistic,
799+
useMemoCache,
800+
useCacheRefresh,
779801
useEffectEvent,
802+
useSwipeTransition,
780803
};
781804

782805
// create a proxy to throw a custom error

packages/react-reconciler/src/ReactFiberConcurrentUpdates.js

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,14 @@ import {
2424
throwIfInfiniteUpdateLoopDetected,
2525
getWorkInProgressRoot,
2626
} from './ReactFiberWorkLoop';
27-
import {NoLane, NoLanes, mergeLanes, markHiddenUpdate} from './ReactFiberLane';
27+
import {
28+
NoLane,
29+
NoLanes,
30+
mergeLanes,
31+
markHiddenUpdate,
32+
markRootUpdated,
33+
GestureLane,
34+
} from './ReactFiberLane';
2835
import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
2936
import {HostRoot, OffscreenComponent} from './ReactWorkTags';
3037
import {OffscreenVisible} from './ReactFiberActivityComponent';
@@ -169,6 +176,25 @@ export function enqueueConcurrentRenderForLane(
169176
return getRootForUpdatedFiber(fiber);
170177
}
171178

179+
export function enqueueGestureRender(fiber: Fiber): FiberRoot | null {
180+
// We can't use the concurrent queuing for these so this is basically just a
181+
// short cut for marking the lane on the parent path. It is possible for a
182+
// gesture render to suspend and then in the gap get another gesture starting.
183+
// However, marking the lane doesn't make much different in this case because
184+
// it would have to call startGesture with the same exact provider as was
185+
// already rendering. Because otherwise it has no effect on the Hook itself.
186+
// TODO: We could potentially solve this case by popping a ScheduledGesture
187+
// off the root's queue while we're rendering it so that it can't dedupe
188+
// and so new startGesture with the same provider would create a new
189+
// ScheduledGesture which goes into a separate render pass anyway.
190+
// This is such an edge case it probably doesn't matter much.
191+
const root = markUpdateLaneFromFiberToRoot(fiber, null, GestureLane);
192+
if (root !== null) {
193+
markRootUpdated(root, GestureLane);
194+
}
195+
return root;
196+
}
197+
172198
// Calling this function outside this module should only be done for backwards
173199
// compatibility and should always be accompanied by a warning.
174200
export function unsafe_markUpdateLaneFromFiberToRoot(
@@ -189,7 +215,7 @@ function markUpdateLaneFromFiberToRoot(
189215
sourceFiber: Fiber,
190216
update: ConcurrentUpdate | null,
191217
lane: Lane,
192-
): void {
218+
): null | FiberRoot {
193219
// Update the source fiber's lanes
194220
sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
195221
let alternate = sourceFiber.alternate;
@@ -238,10 +264,14 @@ function markUpdateLaneFromFiberToRoot(
238264
parent = parent.return;
239265
}
240266

241-
if (isHidden && update !== null && node.tag === HostRoot) {
267+
if (node.tag === HostRoot) {
242268
const root: FiberRoot = node.stateNode;
243-
markHiddenUpdate(root, update, lane);
269+
if (isHidden && update !== null) {
270+
markHiddenUpdate(root, update, lane);
271+
}
272+
return root;
244273
}
274+
return null;
245275
}
246276

247277
function getRootForUpdatedFiber(sourceFiber: Fiber): FiberRoot | null {
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow
8+
*/
9+
10+
import type {FiberRoot} from './ReactInternalTypes';
11+
import type {GestureProvider} from 'shared/ReactTypes';
12+
13+
import {GestureLane} from './ReactFiberLane';
14+
import {ensureRootIsScheduled} from './ReactFiberRootScheduler';
15+
16+
// This type keeps track of any scheduled or active gestures.
17+
export type ScheduledGesture = {
18+
provider: GestureProvider,
19+
count: number, // The number of times this same provider has been started.
20+
prev: null | ScheduledGesture, // The previous scheduled gesture in the queue for this root.
21+
next: null | ScheduledGesture, // The next scheduled gesture in the queue for this root.
22+
};
23+
24+
export function scheduleGesture(
25+
root: FiberRoot,
26+
provider: GestureProvider,
27+
): ScheduledGesture {
28+
let prev = root.gestures;
29+
while (prev !== null) {
30+
if (prev.provider === provider) {
31+
// Existing instance found.
32+
prev.count++;
33+
return prev;
34+
}
35+
const next = prev.next;
36+
if (next === null) {
37+
break;
38+
}
39+
prev = next;
40+
}
41+
// Add new instance to the end of the queue.
42+
const gesture: ScheduledGesture = {
43+
provider: provider,
44+
count: 1,
45+
prev: prev,
46+
next: null,
47+
};
48+
if (prev === null) {
49+
root.gestures = gesture;
50+
} else {
51+
prev.next = gesture;
52+
}
53+
ensureRootIsScheduled(root);
54+
return gesture;
55+
}
56+
57+
export function cancelScheduledGesture(
58+
root: FiberRoot,
59+
gesture: ScheduledGesture,
60+
): void {
61+
gesture.count--;
62+
if (gesture.count === 0) {
63+
// Delete the scheduled gesture from the queue.
64+
deleteScheduledGesture(root, gesture);
65+
}
66+
}
67+
68+
export function deleteScheduledGesture(
69+
root: FiberRoot,
70+
gesture: ScheduledGesture,
71+
): void {
72+
if (gesture.prev === null) {
73+
if (root.gestures === gesture) {
74+
root.gestures = gesture.next;
75+
if (root.gestures === null) {
76+
// Gestures don't clear their lanes while the gesture is still active but it
77+
// might not be scheduled to do any more renders and so we shouldn't schedule
78+
// any more gesture lane work until a new gesture is scheduled.
79+
root.pendingLanes &= ~GestureLane;
80+
}
81+
}
82+
} else {
83+
gesture.prev.next = gesture.next;
84+
if (gesture.next !== null) {
85+
gesture.next.prev = gesture.prev;
86+
}
87+
gesture.prev = null;
88+
gesture.next = null;
89+
}
90+
}

0 commit comments

Comments
 (0)