} />
+ ) : (
+
+ );
+}
+
+describe('useGestureRecognizer follows the element behind its ref', () => {
+ it('attaches to a node rendered after mount, and to a node swapped behind the same ref', () => {
+ const states: string[] = [];
+ const onPan = (r: PanGestureRecognizer) => states.push(r.state);
+ const {getByTestId, rerender} = render(
+
,
+ );
+ rerender(
);
+ const first = getByTestId('node');
+ touch('touchstart', first, {id: 1, x: 0, y: 0}, 0);
+ touch('touchmove', first, {id: 1, x: 30, y: 0}, 16);
+ touch('touchend', first, {id: 1, x: 30, y: 0}, 32, true);
+ expect(states).toContain('began');
+ states.length = 0;
+ rerender(
);
+ const second = getByTestId('node');
+ expect(second).not.toBe(first);
+ touch('touchstart', second, {id: 2, x: 0, y: 0}, 100);
+ touch('touchmove', second, {id: 2, x: 30, y: 0}, 116);
+ touch('touchend', second, {id: 2, x: 30, y: 0}, 132, true);
+ expect(states).toContain('began');
+ // The detached node no longer drives it.
+ states.length = 0;
+ touch('touchstart', first, {id: 3, x: 0, y: 0}, 200);
+ touch('touchmove', first, {id: 3, x: 30, y: 0}, 216);
+ touch('touchend', first, {id: 3, x: 30, y: 0}, 232, true);
+ expect(states).toEqual([]);
+ });
+
+ it('reports nothing from cleanup when it unmounts mid-gesture', () => {
+ const states: string[] = [];
+ const {getByTestId, unmount} = render(
+
states.push(r.state)} />,
+ );
+ const surface = getByTestId('surface');
+ touch('touchstart', surface, {id: 5, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 5, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ unmount();
+ expect(states).toEqual(['began']);
+ });
+});
+
+function LaterButton({
+ isShown,
+ onEvent,
+ onHighlight,
+ isBraking,
+ highlightDelay,
+}: {
+ isShown: boolean;
+ onEvent?: (event: ControlEvent) => void;
+ onHighlight?: (isOn: boolean) => void;
+ isBraking?: () => boolean;
+ highlightDelay?: 'inScrollers' | 'always' | 'never';
+}) {
+ const ref = useRef(null);
+ usePressTracker(ref, {
+ onControlEvent: event => onEvent?.(event),
+ onHighlightChange: isOn => onHighlight?.(isOn),
+ isBraking,
+ highlightDelay,
+ });
+ return isShown ? (
+
+ ) : null;
+}
+
+describe('usePressTracker follows its element and its options', () => {
+ it('tracks a node rendered after mount', () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId, rerender} = render(
+ events.push(event)} />,
+ );
+ rerender( events.push(event)} />);
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ touch('touchend', stepper, {id: 1, x: 2, y: 2}, 60, true);
+ expect(events).toContain('touchUpInside');
+ });
+
+ it("uses the caller's brake", () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId} = render(
+ true}
+ onEvent={event => events.push(event)}
+ />,
+ );
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ touch('touchend', stepper, {id: 1, x: 2, y: 2}, 60, true);
+ expect(events).not.toContain('touchDown');
+ expect(events).not.toContain('touchUpInside');
+ });
+
+ it('takes a highlight delay changed after mount from the next touch', () => {
+ vi.useFakeTimers();
+ const highlights: boolean[] = [];
+ const {getByTestId, rerender} = render(
+ highlights.push(isOn)}
+ />,
+ );
+ rerender(
+ highlights.push(isOn)}
+ />,
+ );
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ // 'always' waits the content-touch delay before highlighting.
+ expect(highlights).toEqual([]);
+ touch('touchend', stepper, {id: 1, x: 2, y: 2}, 400, true);
+ vi.useRealTimers();
+ });
+
+ it('calls no callback from cleanup when it unmounts while highlighted', () => {
+ const highlights: boolean[] = [];
+ const {getByTestId, unmount} = render(
+ highlights.push(isOn)}
+ />,
+ );
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ expect(highlights).toEqual([true]);
+ unmount();
+ expect(highlights).toEqual([true]);
+ });
+});
+
+function boundsOf(element: HTMLElement, width: number, height: number): void {
+ Object.defineProperty(element, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => ({
+ left: 0,
+ top: 0,
+ right: width,
+ bottom: height,
+ width,
+ height,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }),
+ });
+}
+
+function SwappedColumn({
+ which,
+ freshRef,
+ onEvent,
+}: {
+ which: 'a' | 'b';
+ freshRef: boolean;
+ onEvent: (event: ControlEvent) => void;
+}) {
+ const stableRef = useRef(null);
+ const fresh = {current: null as HTMLButtonElement | null};
+ const ref = freshRef ? fresh : stableRef;
+ usePressTracker(ref, {onControlEvent: event => onEvent(event)});
+ return which === 'a' ? (
+
+ ) : (
+
+ );
+}
+
+describe('usePressTracker hit-tests the element behind its ref now', () => {
+ for (const freshRef of [false, true]) {
+ it(`judges a lift against the swapped node's bounds (${freshRef ? 'a new ref object' : 'the same ref'})`, () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId, rerender} = render(
+ events.push(event)}
+ />,
+ );
+ rerender(
+ events.push(event)}
+ />,
+ );
+ const b = getByTestId('b');
+ boundsOf(b, 100, 40);
+ touch('touchstart', b, {id: 1, x: 10, y: 10}, 0);
+ // Far outside B, past the tracking expansion.
+ touch('touchmove', b, {id: 1, x: 400, y: 400}, 16);
+ touch('touchend', b, {id: 1, x: 400, y: 400}, 32, true);
+ expect(events).toContain('touchDown');
+ expect(events).toContain('touchUpOutside');
+ expect(events).not.toContain('touchUpInside');
+ });
+ }
+});
+
+function SwappedSurface({
+ which,
+ onPan,
+}: {
+ which: 'a' | 'b';
+ onPan: (recognizer: PanGestureRecognizer) => void;
+}) {
+ const ref = useRef(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ onPan,
+ );
+ return which === 'a' ? (
+
+ ) : (
+
+ );
+}
+
+describe('useGestureRecognizer follows a replaced node', () => {
+ for (const strict of [false, true]) {
+ it(`cancels a gesture in flight without calling the listener from the effect${strict ? ' (StrictMode)' : ''}`, () => {
+ const states: string[] = [];
+ const wrap = (node: React.ReactElement) =>
+ strict ? {node} : node;
+ const {getByTestId, rerender} = render(
+ wrap( states.push(r.state)} />),
+ );
+ const a = getByTestId('a');
+ touch('touchstart', a, {id: 3, x: 0, y: 0}, 0);
+ touch('touchmove', a, {id: 3, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ rerender(
+ wrap( states.push(r.state)} />),
+ );
+ // The replaced node's cancel comes from a layout effect: no callback.
+ expect(states).toEqual(['began']);
+ // The new node drives the same recognizer.
+ const b = getByTestId('b');
+ touch('touchstart', b, {id: 4, x: 0, y: 0}, 100);
+ touch('touchmove', b, {id: 4, x: 30, y: 0}, 116);
+ expect(states).toEqual(['began', 'began']);
+ touch('touchend', b, {id: 4, x: 30, y: 0}, 132, true);
+ });
+ }
+});
+
+describe('usePressTracker keeps its press through an option change', () => {
+ for (const strict of [false, true]) {
+ it(`a press in progress survives a rerender with new options${strict ? ' (StrictMode)' : ''}`, () => {
+ const events: ControlEvent[] = [];
+ const highlights: boolean[] = [];
+ function Held({cancelTravel}: {cancelTravel?: number}) {
+ const ref = useRef(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ onHighlightChange: isHighlighted => highlights.push(isHighlighted),
+ cancelTravel,
+ });
+ return (
+
+ );
+ }
+ const wrap = (node: React.ReactElement) =>
+ strict ? {node} : node;
+ const {getByTestId, rerender} = render(wrap());
+ const button = getByTestId('held');
+ touch('touchstart', button, {id: 6, x: 1, y: 1}, 0);
+ expect(highlights).toEqual([true]);
+ rerender(wrap());
+ // Still pressed: the tracker was not rebuilt or disposed.
+ expect(highlights).toEqual([true]);
+ touch('touchend', button, {id: 6, x: 1, y: 1}, 50, true);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ });
+ }
+});
+
+describe('the hooks let go of an element removed while they stay mounted', () => {
+ it('useGestureRecognizer cancels its gesture without calling back, and works on a new element', () => {
+ const states: string[] = [];
+ function Maybe({shown}: {shown: boolean}) {
+ const ref = useRef(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ r => states.push(r.state),
+ );
+ return shown ? : null;
+ }
+ const {getByTestId, rerender} = render();
+ const first = getByTestId('maybe');
+ touch('touchstart', first, {id: 11, x: 0, y: 0}, 0);
+ touch('touchmove', first, {id: 11, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ rerender();
+ expect(states).toEqual(['began']);
+ rerender();
+ const second = getByTestId('maybe');
+ touch('touchstart', second, {id: 12, x: 0, y: 0}, 100);
+ touch('touchmove', second, {id: 12, x: 30, y: 0}, 116);
+ expect(states).toEqual(['began', 'began']);
+ touch('touchend', second, {id: 12, x: 30, y: 0}, 132, true);
+ });
+
+ it('usePressTracker ends its press without calling back, and presses a new element', () => {
+ const events: ControlEvent[] = [];
+ const highlights: boolean[] = [];
+ function Maybe({shown}: {shown: boolean}) {
+ const ref = useRef(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ onHighlightChange: isHighlighted => highlights.push(isHighlighted),
+ });
+ return shown ? (
+
+ ) : null;
+ }
+ const {getByTestId, rerender} = render();
+ touch('touchstart', getByTestId('maybe'), {id: 13, x: 1, y: 1}, 0);
+ expect(highlights).toEqual([true]);
+ rerender();
+ expect(highlights).toEqual([true]);
+ expect(events).toEqual(['touchDown']);
+ rerender();
+ const button = getByTestId('maybe');
+ touch('touchstart', button, {id: 14, x: 1, y: 1}, 100);
+ touch('touchend', button, {id: 14, x: 1, y: 1}, 150, true);
+ expect(events).toEqual(['touchDown', 'touchDown', 'touchUpInside']);
+ });
+});
+
+describe('usePressTracker reads trackingExpansion as it is now', () => {
+ it('a smaller expansion takes effect without rebuilding the tracker', () => {
+ const events: ControlEvent[] = [];
+ function Tracked({expansion}: {expansion: number}) {
+ const ref = useRef(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ trackingExpansion: expansion,
+ });
+ return (
+
+ );
+ }
+ const {getByTestId, rerender} = render();
+ const button = getByTestId('tracked');
+ boundsOf(button, 100, 40);
+ touch('touchstart', button, {id: 15, x: 10, y: 10}, 0);
+ // 30 px below the bottom edge: inside a 70 px expansion.
+ touch('touchmove', button, {id: 15, x: 10, y: 70}, 16);
+ expect(events).not.toContain('touchDragExit');
+ rerender();
+ // The same point is outside a 10 px expansion, mid-press.
+ touch('touchmove', button, {id: 15, x: 10, y: 71}, 32);
+ expect(events).toContain('touchDragExit');
+ touch('touchend', button, {id: 15, x: 10, y: 71}, 48, true);
+ expect(events).toContain('touchUpOutside');
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/watcherRecognizer.test.ts b/packages/core/src/gestures/__tests__/watcherRecognizer.test.ts
new file mode 100644
index 0000000000000..06cf3b523ad9b
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/watcherRecognizer.test.ts
@@ -0,0 +1,244 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file watcherRecognizer.test.ts
+ * @input Uses vitest, the arena harness, GestureHost and the pan recognizer
+ * @output Checks the `claimsTouches: false` watcher: it never claims or
+ * blocks a scroll, prevents nothing and is prevented by nothing, and
+ * follows a touch the browser takes for a scroll to the lift
+ * @position Test for GestureRecognizerOptions.claimsTouches
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {GestureHost} from '../GestureHost';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {createHarness, ManualClock, RecordingConsumer} from './harness';
+import {coarsePrimaryPointer} from './pointerQuery';
+
+describe('a recognizer that never claims (a watcher)', () => {
+ let detach: (() => void)[] = [];
+ // A phone: the host attaches only where the primary pointer is coarse.
+ let restorePointer: () => void;
+ beforeEach(() => {
+ restorePointer = coarsePrimaryPointer();
+ });
+ afterEach(() => {
+ detach.forEach(release => release());
+ detach = [];
+ document.body.innerHTML = '';
+ restorePointer();
+ });
+
+ it('runs alongside a claiming pan on the same touch, and claims nothing', () => {
+ const h = createHarness();
+ const watcher = new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ });
+ const sheet = new PanGestureRecognizer({
+ name: 'sheet',
+ direction: 'vertical',
+ });
+ const finger = h
+ .finger(1)
+ .down(0, 100, 0, {recognizers: [sheet, watcher]})
+ .move(0, 115, 16);
+ expect(watcher.state).toBe('began');
+ expect(sheet.state).toBe('began');
+ expect(h.claims).toEqual([1]);
+ finger.up(32);
+ });
+
+ it('cancels no press under it when it begins: a held control keeps its touch (spec:AST-094 FR15, FR19)', () => {
+ const h = createHarness();
+ const watcher = new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ });
+ const press = new RecordingConsumer();
+ const finger = h
+ .finger(1)
+ .down(0, 100, 0, {recognizers: [watcher], consumer: press})
+ .move(0, 130, 16);
+ expect(watcher.state).toBe('began');
+ expect(press.events).not.toContain('cancelled:1');
+ finger.up(32);
+ expect(press.events).toContain('ended:1');
+ });
+
+ it('follows a touch the browser took for a scroll until the lift', () => {
+ const h = createHarness();
+ const watcher = new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ });
+ const finger = h
+ .finger(1)
+ .down(0, 100, 0, {recognizers: [watcher]})
+ .move(0, 115, 16);
+ expect(watcher.state).toBe('began');
+ finger.takenByBrowser(20);
+ finger.move(0, 160, 32);
+ expect(watcher.state).toBe('changed');
+ finger.up(48);
+ expect(h.log).toContain('watcher:ended@48');
+ });
+
+ it('gets only passive touchmove listeners from the host', () => {
+ document.body.innerHTML = '';
+ const page = document.getElementById('page') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const added = vi.spyOn(page, 'addEventListener');
+ detach.push(
+ host.attach(
+ page,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ {manageStyle: false},
+ ),
+ );
+ const event = new Event('touchstart', {bubbles: true, cancelable: true});
+ const entry = {identifier: 1, clientX: 10, clientY: 10, target: page};
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: [entry]});
+ page.dispatchEvent(event);
+ const blocking = added.mock.calls.filter(
+ ([type, , options]) =>
+ type === 'touchmove' &&
+ (options as AddEventListenerOptions | undefined)?.passive === false,
+ );
+ expect(blocking).toHaveLength(0);
+ });
+
+ it('gets only passive target listeners for its touch, touchend included, while a tap on the same kind of touch gets a cancelable touchend (spec:AST-094 FR20)', () => {
+ document.body.innerHTML = '';
+ const page = document.getElementById('page') as HTMLElement;
+ const button = document.getElementById('button') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const onPage = vi.spyOn(page, 'addEventListener');
+ const onButton = vi.spyOn(button, 'addEventListener');
+ detach.push(
+ host.attach(
+ page,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ {manageStyle: false},
+ ),
+ host.attach(button, new TapGestureRecognizer({name: 'tap'})),
+ );
+ const touchDown = (target: HTMLElement, identifier: number) => {
+ const event = new Event('touchstart', {bubbles: true, cancelable: true});
+ const entry = {identifier, clientX: 10, clientY: 10, target};
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: [entry]});
+ target.dispatchEvent(event);
+ };
+ const passivity = (spy: typeof onPage, type: string) =>
+ spy.mock.calls
+ .filter(([listened]) => listened === type)
+ .map(
+ ([, , options]) =>
+ (options as AddEventListenerOptions | undefined)?.passive,
+ );
+ touchDown(page, 1);
+ expect(passivity(onPage, 'touchmove')).toEqual([true]);
+ expect(passivity(onPage, 'touchend')).toEqual([true]);
+ expect(passivity(onPage, 'touchcancel')).toEqual([true]);
+ touchDown(button, 2);
+ expect(passivity(onButton, 'touchend')).toEqual([false]);
+ });
+
+ it('alone, leaves the host only passive document and window listeners; a claiming recognizer brings the cancelable touchend, contextmenu and click (spec:AST-094 FR20)', () => {
+ document.body.innerHTML = '';
+ const page = document.getElementById('page') as HTMLElement;
+ const strip = document.getElementById('strip') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const active = () => {
+ const listed: string[] = [];
+ for (const [target, spy] of [
+ ['document', onDocument],
+ ['window', onWindow],
+ ] as const) {
+ for (const [type, , options] of spy.mock.calls) {
+ if (typeof options === 'object' && options.passive === false) {
+ listed.push(`${target} ${type}`);
+ }
+ }
+ }
+ return listed;
+ };
+ const onDocument = vi.spyOn(document, 'addEventListener');
+ const onWindow = vi.spyOn(window, 'addEventListener');
+ detach.push(
+ host.attach(
+ page,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ {manageStyle: false},
+ ),
+ );
+ expect(active()).toEqual([]);
+ detach.push(
+ host.attach(
+ strip,
+ new PanGestureRecognizer({name: 'claimer', direction: 'horizontal'}),
+ ),
+ );
+ // At this layer every host listener comes through the shared input
+ // stream (utils/inputStream.ts), on the window's capture phase; clicks
+ // are the click guard's, whose listener comes only once a gesture acts.
+ expect(active().sort()).toEqual(['window contextmenu', 'window touchend']);
+ });
+
+ it('leaves the browser every touch behavior: its direction writes no touch-action', () => {
+ document.body.innerHTML = '';
+ const list = document.getElementById('list') as HTMLElement;
+ const row = document.getElementById('row') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const listStyle = vi.spyOn(list.style, 'setProperty');
+ detach.push(
+ host.attach(
+ list,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ ),
+ host.attach(
+ row,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ ),
+ // A claiming pan beside it on the same element keeps its own.
+ host.attach(
+ row,
+ new PanGestureRecognizer({name: 'swipe', direction: 'horizontal'}),
+ ),
+ );
+ expect(list.hasAttribute('data-astryx-touch-action')).toBe(false);
+ expect(row.getAttribute('data-astryx-touch-action')).toBe(
+ 'pan-y pinch-zoom',
+ );
+ expect(listStyle).not.toHaveBeenCalledWith(
+ 'touch-action',
+ expect.anything(),
+ );
+ });
+});
diff --git a/packages/core/src/gestures/fingerScroll.ts b/packages/core/src/gestures/fingerScroll.ts
new file mode 100644
index 0000000000000..1e429e2a220da
--- /dev/null
+++ b/packages/core/src/gestures/fingerScroll.ts
@@ -0,0 +1,208 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file fingerScroll.ts
+ * @input A scroller (an element, or the document for the page's own scroll),
+ * its document's scroll and scrollend events, and the gesture host's
+ * finger record
+ * @output Exports watchFingerScrolls and isFingerScroll
+ * @position Finger-scroll watch of packages/core/src/gestures (useFingerScroll
+ * reads it), in its own module so a page that never asks never ships it;
+ * internal to the touch module, not in the gestures barrel
+ *
+ * A watched scroller's scroll is a finger's from a scroll event while a
+ * finger that landed inside it is down, until the scroller's own `scrollend`
+ * (the momentum after the lift is still the finger's). A scroll that ends
+ * while its finger still rests there stays the finger's until the lift. A
+ * scroll the program starts while no finger is down there (`scrollTo`, a
+ * status-bar tap) is not. Where the browser sends no `scrollend`, a quiet
+ * spell of `SCROLL_END_FALLBACK_MS` after its last scroll event ends a
+ * finger's scroll instead. The host keeps the one finger record; this module
+ * adds only passive scroll listeners, and only while something is watched.
+ */
+
+import {subscribeInput} from '../utils/inputStream';
+import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer';
+import type {GestureHost} from './GestureHost';
+
+/**
+ * Where the browser sends no `scrollend`, how long a finger-driven scroller
+ * stays quiet (no scroll event) before its scroll counts as ended, in ms:
+ * longer than the gap between a momentum scroll's events, short enough that
+ * a program's scroll right after it is not read as the finger's.
+ */
+const SCROLL_END_FALLBACK_MS = 150;
+
+interface Watch {
+ /** Watched scrollers, and how many watchers each has. */
+ readonly scrollers: Map;
+ /** Watched scrollers whose current scroll is a finger's. */
+ readonly fingerScrollers: Set