Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): a pan follows a trackpad where its owner allows it, never a mouse wheel; a pinch takes a ctrl-wheel (spec:AST-094 FR43) (#8676)

Christopher Chedeau5a455f5fdd55
diff --git a/.changeset/gestures-wheel.md b/.changeset/gestures-wheel.md
new file mode 100644
index 0000000000..755a703248
--- /dev/null
+++ b/.changeset/gestures-wheel.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a pan follows a trackpad's two-finger scroll where its owner allows it (`allowedScrollTypes: ['continuous']`, UIKit's `allowedScrollTypesMask`; none by default), along its own axis and after the scrollers under the pointer, and never a mouse wheel's notches, which scroll what is under the pointer; the screen-edge pan takes none; and a pinch takes a ctrl-wheel from a trackpad or a mouse (AST-094 FR43, DEC-24). A watcher pan never takes the wheel, and a wheel another handler already prevented stays the page's. Input the deltas cannot place, Shift+wheel included, reads as a mouse wheel; a trackpad scroll a pan follows keeps moving at the fingers' speed until their lift is read, ends there still moving, and the momentum never moves it. Not exported from the package entry point.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 73a2faf4b4..830b769fac 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -575,7 +575,9 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
deltas; a lift then continues without a stop, and fingers that keep moving
take up the difference. A pan released at the lift releases with the
fingers' last velocity (FR36); a pan whose stream stops releases still. A
- pinch takes a ctrl-wheel and ends 100 ms after its last event. A BottomSheet's pull
+ window blur or a hidden page cancels a trackpad pan, as the browser taking a
+ touch cancels a finger's. A pinch takes a ctrl-wheel and ends 100 ms after
+ its last event. A BottomSheet's pull
follows a trackpad as it follows a finger: a sheet a swipe cannot close
(`purpose` `form` or `required`) stretches past its resting place on FR3's
rubber band for a finger and a trackpad alike, the same travel giving the
@@ -733,7 +735,7 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
| FR41 | Browser tests with real touch input (`spec:AST-013` FR10) | a tap; a long press on a ContextMenu trigger, a DropdownMenu trigger the caller renders, a row with a context menu, and a slider thumb; a long press on a checkbox row's label and on plain text; a cancelled press; mouse and keyboard selection; a pen long press; a mouse long press, which makes no context request | a tap that selects, a hold with an action that starts a selection or callout, a label or plain text whose long press does not select natively, a suppression that outlives the press, or a change to native selection elsewhere or to mouse, keyboard, or assistive-technology selection fails |
| FR42 | Default-theme geometry tests under a coarse and a fine pointer, and hit-testing between adjacent targets | every component at phone width with a finger and with a mouse; a dense toolbar; a chip and its remove button; a Switch beside a label link | a default-theme box that grows under touch or at phone width other than with its text, or, where no component or module record sets the hit area, a touch target under 44 px where neighbors allow it or a hit area that overlaps a neighbor's target, fails |
| FR43 | Browser tests with a mouse, a trackpad, a pen, a finger, and the keyboard, and resource counts | a pan by drag and by wheel; a slider's thumb under a wheel and a trackpad scroll; a ctrl-wheel pinch; a long press, a right click, and Shift+F10; a mouse press; a handle drag; a row swipe with a mouse and a trackpad; a component with no gesture | a gesture missing under a mouse or pen, a mouse-drag swipe action, a pen pinch, an edge pan under a mouse, a trackpad, or a pen, a press delay under a fine pointer, a wheel or trackpad scroll that changes a thumb's value or does not reach the scroll under it, an idle listener in a component with no gesture, or added stylesheet bytes, fails |
-| FR43 trackpad | Unit tests on timed wheel streams; WebKit browser tests with trackpad streams (Chromium's driver wheels read as a mouse wheel) | a form and a required sheet pulled 30 to 240 px by a finger and by a trackpad; mouse lines, notches, ticks and accelerated deltas over a sheet, a pager and a row; ten swipes each starting mid-momentum, ten whose momentum ends, and a slow drag with 150 ms pauses; a trackpad flick and a slow stopped drag on an info sheet; a fling, a slow 60 px swipe, a 42 px spike and back-to-back swipes on a pager; a row opened and swiped back within one gesture, and a long fast swipe; a pinch ending | a trackpad stretch that differs from a finger's for the same travel (120 px gives 54 px on the reference sheet), a mouse wheel that moves a sheet, a pager or a row, splitter counts other than ten, ten and one, momentum that moves a surface, a flick released with no velocity, a pager that travels past one page or pages on a spike, an info sheet a flick leaves open or a slow stopped drag closes, an open row that reveals its other side within one gesture, or a pinch that ends after 100 ms fails |
+| FR43 trackpad | Unit tests on timed wheel streams; WebKit browser tests with trackpad streams (Chromium's driver wheels read as a mouse wheel) | a form and a required sheet pulled 30 to 240 px by a finger and by a trackpad; mouse lines, notches, ticks and accelerated deltas over a sheet, a pager and a row; ten swipes each starting mid-momentum, ten whose momentum ends, and a slow drag with 150 ms pauses; a trackpad flick and a slow stopped drag on an info sheet; a fling, a slow 60 px swipe, a 42 px spike and back-to-back swipes on a pager; a row opened and swiped back within one gesture, and a long fast swipe; a pinch ending; a trackpad pan through a window blur and through a hidden page | a trackpad stretch that differs from a finger's for the same travel (120 px gives 54 px on the reference sheet), a mouse wheel that moves a sheet, a pager or a row, splitter counts other than ten, ten and one, momentum that moves a surface, a flick released with no velocity, a pager that travels past one page or pages on a spike, an info sheet a flick leaves open or a slow stopped drag closes, an open row that reveals its other side within one gesture, a trackpad pan a window blur or a hidden page leaves mid-gesture, or a pinch that ends after 100 ms fails |
| all | iOS simulator: the UIKit reference capture and the same gesture in Safari; real iOS Safari and Android Chrome devices | per component | an unmatched curve or timing is a parity defect |
## Decision log
diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
index fe144e838c..1f74c6d75a 100644
--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
@@ -1609,7 +1609,6 @@
"FR20",
"FR20",
"FR20",
- "FR20",
"FR21",
"FR21",
"FR21",
@@ -1718,7 +1717,6 @@
"spec:AST-094",
"spec:AST-094",
"spec:AST-094",
- "spec:AST-094",
"spec:AST-094"
],
"packages/core/src/gestures/GestureRecognizer.ts": [
@@ -1801,14 +1799,12 @@
"FR19",
"FR24",
"FR43",
- "FR43",
"design:bidirectionality",
"spec quote",
"spec:AST-094",
"spec:AST-094",
"spec:AST-094",
"spec:AST-094",
- "spec:AST-094",
"spec:AST-094"
],
"packages/core/src/gestures/SwipeGestureRecognizer.ts": [
diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts
index 1d11b2df6a..a3731a5d1b 100644
--- a/packages/core/src/gestures/GestureArena.ts
+++ b/packages/core/src/gestures/GestureArena.ts
@@ -228,6 +228,7 @@ export class GestureArena {
target: input.target,
scroll: input.scroll ?? null,
takenByBrowser: false,
+ ...(input.scrollType == null ? {} : {scrollType: input.scrollType}),
};
const participants: GestureRecognizer[] = [];
for (const [depth, recognizer] of input.recognizers.entries()) {
diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts
index b90fd81a8c..0b7f937278 100644
--- a/packages/core/src/gestures/GestureHost.ts
+++ b/packages/core/src/gestures/GestureHost.ts
@@ -140,9 +140,14 @@ import {
import type {GestureRecognizer, SelectionLock} from './GestureRecognizer';
import type {PressBounds} from './PressTracker';
import type {PanGestureRecognizer} from './PanGestureRecognizer';
-import {createNativeScrollProbe, parentAcrossShadow} from './nativeScroll';
+import {
+ canElementScroll,
+ createNativeScrollProbe,
+ parentAcrossShadow,
+} from './nativeScroll';
import {containsAlongFlatTree} from '../utils/flatTree';
import {isIosWebKit} from '../utils/touchQueries';
+import {type WheelSegment, WheelSegmenter} from './wheelSegmenter';
import {
gestureHostStyle,
type GestureHostStyle,
@@ -158,6 +163,7 @@ import type {
GestureEnvironment,
GestureTouch,
PointerKind,
+ ScrollType,
TouchBeganInput,
TouchConsumer,
TouchInput,
@@ -186,6 +192,8 @@ interface Registration {
hasTouchEndListener: boolean;
/** Whether the element carries the host's shared blocking touchmove handler. */
hasTouchMoveListener: boolean;
+ /** Whether the element carries the host's wheel handler. */
+ hasWheelListener: boolean;
/** Inline values the host replaced, to restore on detach. */
readonly savedStyle: Map<string, string>;
/**
@@ -305,6 +313,16 @@ function claimsWhileMoving(recognizer: GestureRecognizer): boolean {
);
}
+/**
+ * Whether a recognizer takes a contact that comes with Touch Events and a
+ * long press's contextmenu: a finger's or a pen's. A scroll-only recognizer
+ * (`allowedPointerTypes: []`) and a mouse-only one take neither.
+ */
+function takesTouchContacts(recognizer: GestureRecognizer): boolean {
+ const types = recognizer.allowedPointerTypes;
+ return types == null || types.has('touch') || types.has('pen');
+}
+
/**
* A pan (or a pan subclass), told apart by its family rather than its class,
* so a page that constructs no pan never ships PanGestureRecognizer.
@@ -381,6 +399,207 @@ function landedOn(
return event.composedPath()[0] ?? retargeted;
}
+/**
+ * How long after its last event a pinch or a mouse wheel's notches end, ms.
+ * The web reports no wheel phases, so a quiet wheel is a lifted one.
+ */
+const WHEEL_END_MS = 100;
+/**
+ * How long after its last event a vertical trackpad scroll ends, ms (a
+ * sheet's pull), whoever keeps it. A slow drag's stream pauses longer than
+ * WHEEL_END_MS between events.
+ */
+const WHEEL_FOLLOW_END_V_MS = 180;
+/**
+ * The same horizontally, ms (a pager's or a row's swipe), whose slow
+ * swipes pause longer still.
+ */
+const WHEEL_FOLLOW_END_MS = 220;
+/** A line-mode wheel's line, px, as the platforms scroll it. */
+const WHEEL_LINE_PX = 40;
+/** The span a ctrl-wheel pinch's two contacts start at, px. */
+const WHEEL_PINCH_SPAN = 100;
+
+/** A wheel gesture: the contacts it drives in the arena, or none where the page keeps it. */
+interface WheelGesture {
+ readonly kind: 'pan' | 'pinch';
+ /** A mouse wheel's notches, or a trackpad's continuous scroll. */
+ readonly scrollType: ScrollType;
+ readonly ids: ReadonlyArray<number>;
+ /** A pan's contact, or a pinch's center. */
+ x: number;
+ y: number;
+ /** A pinch's span between its two contacts. */
+ span: number;
+ /** The latest wheel's time. */
+ last: number;
+ /**
+ * How long after its last wheel it ends, ms. A trackpad pan stream waits
+ * out its axis's pause bound, whoever keeps it. A pinch or a mouse wheel's
+ * notches wait 100 ms.
+ */
+ readonly endMs: number;
+ timer: unknown;
+ /** The recognizers that took it; none where the page keeps it. */
+ readonly takers: ReadonlyArray<GestureRecognizer>;
+ /** A trackpad scroll a pan follows, until its fingers lift. */
+ follow?: WheelFollow;
+}
+
+/** A trackpad scroll a pan follows: where its fingers lift, and what waits until then. */
+interface WheelFollow {
+ /** The fingers lifted: the momentum after them never moves the pan. */
+ lifted: boolean;
+ /**
+ * Shrinking deltas held until the splitter decides. They are the fingers'
+ * when larger ones follow, and the start of momentum when it reads the
+ * lift.
+ */
+ heldX: number;
+ heldY: number;
+ /** The time of the fingers' last move the pan took. */
+ lastMove: number;
+ /** The fingers' travel as of that move: the contact without any held delta. */
+ trueX: number;
+ trueY: number;
+ /** Where the pan was shown at that move, which the undecided stretch moves on from. */
+ baseX: number;
+ baseY: number;
+ /** The fingers' speed at that move, content px per ms. */
+ speedX: number;
+ speedY: number;
+}
+
+/**
+ * How long after its last wheel a wheel gesture ends, ms. A trackpad's
+ * two-finger scroll waits out a slow drag's pauses for its axis, whoever
+ * keeps the stream. A pinch and a mouse wheel's notches end 100 ms after
+ * their last wheel.
+ */
+function wheelEndMs(
+ kind: 'pan' | 'pinch',
+ scrollType: ScrollType,
+ isHorizontal: boolean,
+): number {
+ if (kind === 'pinch' || scrollType !== 'continuous') {
+ return WHEEL_END_MS;
+ }
+ return isHorizontal ? WHEEL_FOLLOW_END_MS : WHEEL_FOLLOW_END_V_MS;
+}
+
+/**
+ * A provisional lead `debt` after a move of `moved`. The debt is what a
+ * followed pan shows past the fingers' travel, or short of it. Half the move
+ * is absorbed, so the pan keeps moving the way the fingers do.
+ */
+function absorbedDebt(debt: number, moved: number): number {
+ return Math.sign(debt) * Math.max(0, Math.abs(debt) - Math.abs(moved) / 2);
+}
+
+/**
+ * `target` where it is ahead of `shown` in the direction of `speed`, else
+ * `shown`: a reconcile that never steps back.
+ */
+function ahead(shown: number, target: number, speed: number): number {
+ return speed === 0 || (target - shown) * Math.sign(speed) > 0
+ ? target
+ : shown;
+}
+
+/**
+ * A wheel's deltas in CSS px: a line is `WHEEL_LINE_PX`, a page the
+ * viewport.
+ */
+function wheelPixels(
+ wheel: WheelEvent,
+ view: Window | null,
+): {dx: number; dy: number} {
+ if (wheel.deltaMode === 1) {
+ return {dx: wheel.deltaX * WHEEL_LINE_PX, dy: wheel.deltaY * WHEEL_LINE_PX};
+ }
+ if (wheel.deltaMode === 2) {
+ return {
+ dx: wheel.deltaX * (view?.innerWidth ?? 0),
+ dy: wheel.deltaY * (view?.innerHeight ?? 0),
+ };
+ }
+ return {dx: wheel.deltaX, dy: wheel.deltaY};
+}
+
+/**
+ * The web's best reading of what scrolled: a mouse wheel's notches
+ * (`discrete`) or a trackpad's scroll (`continuous`). Input it cannot tell
+ * apart counts as a mouse wheel's, which a pan that takes only a trackpad's
+ * scroll leaves to the page. These read as a mouse wheel's:
+ * - a line- or page-mode delta;
+ * - a scroll with Shift held (Shift+wheel);
+ * - a pixel delta a hair off a whole pixel (a mouse wheel on Windows);
+ * - a scroll with no legacy `wheelDelta` (an engine that sends none);
+ * - a delta that is not a third of its legacy `wheelDelta`;
+ * - a 120 tick over a 40 px delta.
+ * A trackpad's precise deltas, a third of their legacy `wheelDelta` in
+ * Chromium and WebKit, read as a trackpad's.
+ */
+function scrollTypeOf(wheel: WheelEvent): ScrollType {
+ if (wheel.deltaMode !== 0 || wheel.shiftKey) {
+ return 'discrete';
+ }
+ const remainder = (value: number) => {
+ const fraction = Math.abs(value - Math.round(value));
+ return fraction > 0 && fraction < 0.01;
+ };
+ if (remainder(wheel.deltaX) || remainder(wheel.deltaY)) {
+ return 'discrete';
+ }
+ const legacy = wheel as WheelEvent & {
+ wheelDeltaX?: number;
+ wheelDeltaY?: number;
+ };
+ if (
+ typeof legacy.wheelDeltaY !== 'number' ||
+ typeof legacy.wheelDeltaX !== 'number'
+ ) {
+ return 'discrete';
+ }
+ const precise = (delta: number, legacyDelta: number) =>
+ delta === 0
+ ? legacyDelta === 0
+ : Math.abs(Math.abs(legacyDelta) - 3 * Math.abs(delta)) <=
+ Math.max(1.5, 0.05 * Math.abs(delta) * 3);
+ if (
+ !precise(wheel.deltaY, legacy.wheelDeltaY) ||
+ !precise(wheel.deltaX, legacy.wheelDeltaX)
+ ) {
+ return 'discrete';
+ }
+ const tick = (delta: number, legacyDelta: number) =>
+ legacyDelta !== 0 && legacyDelta % 120 === 0 && delta % 40 === 0;
+ return tick(wheel.deltaY, legacy.wheelDeltaY) ||
+ tick(wheel.deltaX, legacy.wheelDeltaX)
+ ? 'discrete'
+ : 'continuous';
+}
+
+/** Read without the pan class, which a page with no pan never ships. */
+function isScrollEdgePan(recognizer: GestureRecognizer): boolean {
+ return (recognizer as {scrollEdge?: boolean}).scrollEdge === true;
+}
+
+/**
+ * Whether a pan takes a contact moving by (cx, cy), by its own direction
+ * rule, `axisRatio` included. A move its rule leaves undecided stays the
+ * page's.
+ */
+function panTakesMove(
+ recognizer: GestureRecognizer,
+ cx: number,
+ cy: number,
+): boolean {
+ return (
+ (internals(recognizer).classify?.({x: cx, y: cy}) ?? 'begin') === 'begin'
+ );
+}
+
/**
* An event's time on the arena's clock (`performance.now()`). Some engines
* and DOM emulators stamp events in epoch milliseconds instead.
@@ -530,6 +749,16 @@ export class GestureHost {
*/
private fingerTargets: ReadonlyArray<Node> = [];
private nextId = 1;
+ /** The wheel gesture in progress. */
+ private wheel: WheelGesture | null = null;
+ /** The wheel latch's input-stream subscription, while a gesture is latched. */
+ private stopWheelLatch: (() => void) | null = null;
+ /** Splits the wheel stream into gestures and reads a trackpad's lift. */
+ private readonly segmenter = new WheelSegmenter();
+ /** The latest wheel's segment. */
+ private wheelSegment: WheelSegment | null = null;
+ /** Wheels already taken: each element on the path with a listener hears one. */
+ private readonly wheelsSeen = new WeakSet<Event>();
private isInstalled = false;
/**
* Whether the primary pointer is coarse (`spec:AST-094` FR19), read when
@@ -648,6 +877,16 @@ export class GestureHost {
if (recognizer.state !== 'possible' || recognizer.isInvolved()) {
recognizer.cancel();
}
+ const wheel = this.wheel;
+ if (
+ wheel != null &&
+ wheel.takers.includes(recognizer) &&
+ !this.wheelHasTaker(wheel)
+ ) {
+ // At its last wheel: a later stamp would move the arena's clock past
+ // the next input's own time.
+ this.endWheel(wheel.last);
+ }
this.refresh(element, registration);
// Even when the element keeps other attachments: one left disabled
// keeps no listener or observer (FR24).
@@ -1055,6 +1294,7 @@ export class GestureHost {
consumer: null,
hasTouchEndListener: false,
hasTouchMoveListener: false,
+ hasWheelListener: false,
savedStyle: new Map(),
authorTouchAction: null,
manageStyle: true,
@@ -1135,6 +1375,26 @@ export class GestureHost {
element.removeEventListener('touchmove', this.onBlockingTouchMove);
registration.hasTouchMoveListener = false;
}
+ // Wheel and trackpad input, only where an enabled recognizer takes it. A
+ // non-passive wheel listener makes the browser's scrolling over the
+ // element wait for the main thread.
+ const needsWheel = registration.recognizers.some(
+ recognizer =>
+ recognizer.isEnabled &&
+ // A watcher never takes the wheel: the page keeps it.
+ recognizer.claimsTouches &&
+ recognizer.allowedScrollTypes.size > 0 &&
+ // A wheel drives a pan or a pinch only.
+ (internals(recognizer).family === 'pan' ||
+ internals(recognizer).family === 'pinch'),
+ );
+ if (needsWheel && !registration.hasWheelListener) {
+ element.addEventListener('wheel', this.onWheel, {passive: false});
+ registration.hasWheelListener = true;
+ } else if (!needsWheel && registration.hasWheelListener) {
+ element.removeEventListener('wheel', this.onWheel);
+ registration.hasWheelListener = false;
+ }
}
private applyStyle(element: HTMLElement, registration: Registration): void {
@@ -1290,6 +1550,9 @@ export class GestureHost {
if (registration.hasTouchMoveListener) {
element.removeEventListener('touchmove', this.onBlockingTouchMove);
}
+ if (registration.hasWheelListener) {
+ element.removeEventListener('wheel', this.onWheel);
+ }
this.registry.delete(element);
this.uninstallIfIdle();
}
@@ -1394,7 +1657,13 @@ export class GestureHost {
for (const [element, registration] of this.registry) {
const consumer = registration.consumer;
if (
- registration.recognizers.some(recognizer => recognizer.isEnabled) ||
+ registration.recognizers.some(
+ recognizer =>
+ recognizer.isEnabled &&
+ // One that takes only scroll input has no press to arm.
+ (recognizer.allowedPointerTypes == null ||
+ recognizer.allowedPointerTypes.size > 0),
+ ) ||
(consumer != null && consumer.isEnabled?.() !== false)
) {
wanted.add(element);
@@ -1545,8 +1814,9 @@ export class GestureHost {
/**
* Whether an enabled participant could claim a touch or cancel a lift: a
- * consumer, or a recognizer that claims touches. With only watchers
- * attached, the host's listeners are all passive (`spec:AST-094` FR20).
+ * consumer, or a recognizer that claims touches and takes a finger or a
+ * pen. With only watchers, or only scroll-only recognizers
+ * (`allowedPointerTypes: []`), the host's listeners are all passive.
*/
private hasClaimer(): boolean {
for (const registration of this.registry.values()) {
@@ -1554,7 +1824,10 @@ export class GestureHost {
if (
(consumer != null && consumer.isEnabled?.() !== false) ||
registration.recognizers.some(
- recognizer => recognizer.isEnabled && recognizer.claimsTouches,
+ recognizer =>
+ recognizer.isEnabled &&
+ recognizer.claimsTouches &&
+ takesTouchContacts(recognizer),
)
) {
return true;
@@ -1827,6 +2100,489 @@ export class GestureHost {
}
}
+ /**
+ * Wheel and trackpad input. A wheel gesture drives the recognizers that
+ * allow its scroll type, as a contact that moves with the content. A pan
+ * takes it along its own axis, once no scroller between the pointer and
+ * the pan's element can scroll that way. The gesture's first wheel decides
+ * this. A pinch takes a ctrl-wheel, as a trackpad pinches, as two contacts
+ * whose span follows exp(-deltaY / 100). A wheel the page keeps is never
+ * prevented, and a wheel a recognizer takes always is. A gesture ends its
+ * end window after its last wheel (wheelEndMs), at that wheel's time, so
+ * its release keeps its velocity. A gesture a recognizer took is latched
+ * to it, as a browser latches a scroller. While the gesture lasts, the
+ * shared input stream hands this every wheel first, wherever it lands. So
+ * a pan whose element moves from under a still pointer keeps the gesture.
+ * The page listener exists only during a gesture.
+ */
+ private readonly onWheel = (event: Event): void => {
+ const wheel = event as WheelEvent;
+ if (this.wheelsSeen.has(wheel)) {
+ return;
+ }
+ this.wheelsSeen.add(wheel);
+ const time = eventTime(wheel);
+ const kind = wheel.ctrlKey ? 'pinch' : 'pan';
+ let gesture = this.wheel;
+ if (
+ gesture != null &&
+ (gesture.kind !== kind || time - gesture.last >= gesture.endMs)
+ ) {
+ this.endWheel(time);
+ gesture = null;
+ }
+ if (
+ gesture != null &&
+ gesture.ids.length > 0 &&
+ gesture.follow?.lifted !== true &&
+ !this.wheelHasTaker(gesture)
+ ) {
+ // Every recognizer that took it has left (detached, disabled or
+ // cancelled), so the rest of the gesture is the page's. A followed
+ // pan's own lift does not count. Its momentum stays latched and
+ // prevented until the splitter's next gesture or the end timer, and
+ // moves nothing. The release is stamped at its last wheel.
+ this.endWheel(gesture.last);
+ const left = wheelPixels(wheel, this.doc.defaultView);
+ gesture = {
+ kind,
+ scrollType: scrollTypeOf(wheel),
+ ids: [],
+ x: wheel.clientX,
+ y: wheel.clientY,
+ span: WHEEL_PINCH_SPAN,
+ last: time,
+ endMs: wheelEndMs(
+ kind,
+ scrollTypeOf(wheel),
+ Math.abs(left.dx) > Math.abs(left.dy),
+ ),
+ timer: null,
+ takers: [],
+ };
+ this.wheel = gesture;
+ }
+ const {dx, dy} = wheelPixels(wheel, this.doc.defaultView);
+ const horizontal = Math.abs(dx) > Math.abs(dy);
+ // The splitter reads a pan's stream only. A ctrl-wheel pinch has no
+ // fingers' phase or momentum to tell apart, and ends 100 ms after its
+ // last wheel.
+ let seg: WheelSegment | null = null;
+ if (kind === 'pan') {
+ seg = this.segmenter.push(
+ time,
+ horizontal ? dx : dy,
+ horizontal ? WHEEL_FOLLOW_END_MS : WHEEL_FOLLOW_END_V_MS,
+ );
+ } else {
+ this.segmenter.end();
+ }
+ this.wheelSegment = seg;
+ if (seg?.boundary != null) {
+ if (gesture != null) {
+ this.endWheel(time);
+ gesture = null;
+ }
+ }
+ if (gesture == null) {
+ gesture = this.beginWheel(wheel, kind, dx, dy, time);
+ this.wheel = gesture;
+ if (gesture.ids.length > 0) {
+ this.latchWheel();
+ }
+ }
+ gesture.last = time;
+ if (gesture.timer != null) {
+ this.clock.clearTimeout(gesture.timer);
+ }
+ // A trackpad scroll waits out a slow drag's pauses, whoever
+ // keeps it; a pinch or a mouse wheel's notches 100 ms.
+ gesture.timer = this.clock.setTimeout(() => {
+ this.segmenter.end();
+ this.endWheel();
+ }, gesture.endMs);
+ if (gesture.ids.length === 0) {
+ return;
+ }
+ wheel.preventDefault();
+ if (gesture.kind === 'pan' && gesture.follow) {
+ const f = gesture.follow;
+ if (f.lifted) {
+ return;
+ }
+ if (this.wheelSegment?.liftNow === true) {
+ // Momentum began: the fingers lifted before the held deltas. The pan
+ // keeps the travel it showed through the undecided stretch. It lets
+ // go here, still moving at the fingers' speed, so its release carries
+ // on from it. The rest of the momentum never moves the pan.
+ this.followProvisionally(gesture, f, time);
+ f.lifted = true;
+ this.arena.ended([
+ {id: gesture.ids[0], x: gesture.x, y: gesture.y, time},
+ ]);
+ return;
+ }
+ if (this.wheelSegment?.decaying === true) {
+ // Undecided: the real deltas wait for the splitter while the
+ // fingers' last speed carries the pan on.
+ f.heldX += dx;
+ f.heldY += dy;
+ this.followProvisionally(gesture, f, time);
+ return;
+ }
+ // The fingers' own delta; the held ones were theirs too. Their moves
+ // absorb what the pan shows ahead of their travel, or behind it, half a
+ // move at a time. So the pan never steps back, and ends on their travel.
+ const beforeX = f.trueX - f.heldX;
+ const beforeY = f.trueY - f.heldY;
+ const debtX = absorbedDebt(gesture.x - beforeX, dx);
+ const debtY = absorbedDebt(gesture.y - beforeY, dy);
+ const trueX = beforeX - dx;
+ const trueY = beforeY - dy;
+ const elapsed = time - f.lastMove;
+ if (elapsed > 0) {
+ f.speedX = (trueX - f.trueX) / elapsed;
+ f.speedY = (trueY - f.trueY) / elapsed;
+ }
+ f.trueX = trueX;
+ f.trueY = trueY;
+ f.heldX = 0;
+ f.heldY = 0;
+ f.lastMove = time;
+ gesture.x = trueX + debtX;
+ gesture.y = trueY + debtY;
+ f.baseX = gesture.x;
+ f.baseY = gesture.y;
+ this.arena.moved([
+ {id: gesture.ids[0], x: gesture.x, y: gesture.y, time},
+ ]);
+ return;
+ }
+ if (gesture.kind === 'pan') {
+ gesture.x -= dx;
+ gesture.y -= dy;
+ this.arena.moved([
+ {id: gesture.ids[0], x: gesture.x, y: gesture.y, time},
+ ]);
+ } else {
+ gesture.span *= Math.exp(-dy / 100);
+ this.arena.moved(this.pinchContacts(gesture, time));
+ }
+ };
+
+ /**
+ * Move a followed pan through the splitter's undecided stretch. It moves on
+ * from where it was shown at the fingers' last move, at their last speed.
+ * It never passes what that speed projects for the time since.
+ */
+ private followProvisionally(
+ gesture: WheelGesture,
+ f: WheelFollow,
+ time: number,
+ ): void {
+ const elapsed = Math.max(0, time - f.lastMove);
+ const x = f.baseX + f.speedX * elapsed;
+ const y = f.baseY + f.speedY * elapsed;
+ if (x === gesture.x && y === gesture.y) {
+ return;
+ }
+ gesture.x = x;
+ gesture.y = y;
+ this.arena.moved([{id: gesture.ids[0], x, y, time}]);
+ }
+
+ /** Start a wheel gesture: who takes it, decided once, or nobody. */
+ private beginWheel(
+ wheel: WheelEvent,
+ kind: 'pan' | 'pinch',
+ dx: number,
+ dy: number,
+ time: number,
+ ): WheelGesture {
+ const type = scrollTypeOf(wheel);
+ const isHorizontal = Math.abs(dx) > Math.abs(dy);
+ const kept: WheelGesture = {
+ kind,
+ scrollType: type,
+ ids: [],
+ x: wheel.clientX,
+ y: wheel.clientY,
+ span: WHEEL_PINCH_SPAN,
+ last: time,
+ endMs: wheelEndMs(kind, type, isHorizontal),
+ timer: null,
+ takers: [],
+ };
+ // A contact already down keeps its gesture; the wheel stays the page's.
+ // So does a first wheel another handler already prevented, or one that
+ // cannot be cancelled: no recognizer could take it from the page.
+ if (
+ this.arena.touches.length > 0 ||
+ (dx === 0 && dy === 0) ||
+ wheel.defaultPrevented ||
+ !wheel.cancelable
+ ) {
+ return kept;
+ }
+ // Every scroller under the pointer, the page included, as a finger's
+ // probe reads them, without touch-action, which a wheel ignores.
+ // What the wheel landed on: at a shadow host's listener the event's
+ // target is the host, and a scroller inside its tree must count.
+ const target = landedOn(wheel);
+ const scroll = createNativeScrollProbe(target, {
+ readsTouchAction: false,
+ });
+ const takers: GestureRecognizer[] = [];
+ for (
+ let node: Node | null = target instanceof Node ? target : null;
+ node != null;
+ node = parentAcrossShadow(node)
+ ) {
+ if (!(node instanceof Element)) {
+ continue;
+ }
+ for (const recognizer of this.registry.get(node)?.recognizers ?? []) {
+ // A pan follows a trackpad, never a mouse wheel's notches, which
+ // scroll what is under the pointer.
+ if (
+ !recognizer.isEnabled ||
+ !recognizer.claimsTouches ||
+ !recognizer.allowedScrollTypes.has(type) ||
+ internals(recognizer).family !== kind ||
+ (kind === 'pan' && type !== 'continuous')
+ ) {
+ continue;
+ }
+ if (
+ kind === 'pan' &&
+ (!panTakesMove(recognizer, -dx, -dy) ||
+ this.scrollerTakes(target, node, dx, dy, isHorizontal) ||
+ // A scroll-edge pan only past every scroller's edge.
+ (isScrollEdgePan(recognizer) && scroll.canScroll(-dx, -dy)))
+ ) {
+ continue;
+ }
+ takers.push(recognizer);
+ }
+ }
+ if (takers.length === 0) {
+ return kept;
+ }
+ const base = {
+ pointerType: 'mouse' as const,
+ target,
+ scroll,
+ scrollType: type,
+ recognizers: takers,
+ consumer: null,
+ };
+ const ids =
+ kind === 'pan' ? [this.nextId++] : [this.nextId++, this.nextId++];
+ const gesture: WheelGesture = {...kept, ids, takers};
+ if (kind === 'pan' && type === 'continuous') {
+ gesture.follow = {
+ lifted: false,
+ heldX: 0,
+ heldY: 0,
+ lastMove: time,
+ trueX: kept.x,
+ trueY: kept.y,
+ baseX: kept.x,
+ baseY: kept.y,
+ speedX: 0,
+ speedY: 0,
+ };
+ }
+ this.arena.began(
+ kind === 'pan'
+ ? [{...base, id: ids[0], x: wheel.clientX, y: wheel.clientY, time}]
+ : this.pinchContacts(gesture, time).map(input => ({
+ ...base,
+ ...input,
+ })),
+ );
+ // Every recognizer it was offered to may decline it (its own
+ // shouldReceiveTouch). Then nobody took the wheel, and it scrolls the
+ // page from its first step, as with no gesture system.
+ if (ids.every(id => this.arena.participantsOf(id).length === 0)) {
+ this.arena.cancelled(ids, time);
+ return kept;
+ }
+ return gesture;
+ }
+
+ /**
+ * Whether a scroller between `target` and `boundary` (both included)
+ * scrolls this wheel now, along the wheel's major axis. It uses the edge
+ * test a finger's probe uses (canElementScroll).
+ */
+ private scrollerTakes(
+ target: unknown,
+ boundary: Element,
+ dx: number,
+ dy: number,
+ isHorizontal: boolean,
+ ): boolean {
+ for (
+ let node: Node | null = target instanceof Node ? target : null;
+ node != null;
+ node = parentAcrossShadow(node)
+ ) {
+ if (
+ node instanceof Element &&
+ canElementScroll(node, isHorizontal ? -dx : 0, isHorizontal ? 0 : -dy)
+ ) {
+ return true;
+ }
+ if (node === boundary) {
+ break;
+ }
+ }
+ return false;
+ }
+
+ /** A ctrl-wheel pinch's two contacts, `span` apart around its center. */
+ private pinchContacts(
+ gesture: WheelGesture,
+ time: number,
+ ): {id: number; x: number; y: number; time: number}[] {
+ return [
+ {id: gesture.ids[0], x: gesture.x - gesture.span / 2, y: gesture.y, time},
+ {id: gesture.ids[1], x: gesture.x + gesture.span / 2, y: gesture.y, time},
+ ];
+ }
+
+ /** Whether a recognizer that took this wheel gesture still takes part in it. */
+ private wheelHasTaker(gesture: WheelGesture): boolean {
+ // A cancelled or failed recognizer keeps that state until its contacts
+ // end, which a wheel gesture's do only here.
+ return gesture.takers.some(recognizer => {
+ const {state} = recognizer;
+ return (
+ recognizer.isEnabled &&
+ (state === 'began' ||
+ state === 'changed' ||
+ (state === 'possible' && recognizer.isInvolved()))
+ );
+ });
+ }
+
+ /**
+ * Route every wheel on the page to the live wheel gesture, from its claim.
+ * The route is the shared input stream's capture listener on the window,
+ * which runs before any document listener. It is non-passive only while it
+ * is subscribed.
+ */
+ private latchWheel(): void {
+ const view = this.doc.defaultView;
+ if (this.stopWheelLatch == null && view != null) {
+ const cancelWheel = () => {
+ const ids = this.dropDrivenWheel();
+ if (ids.length > 0) {
+ this.arena.cancelled(ids, this.arena.now());
+ }
+ };
+ const stops = [
+ subscribeInput(view, 'wheel', this.onWheel, {cancels: true}),
+ // A page that loses focus or hides ends a trackpad pan, as it ends
+ // every touch. An element's blur reaches the window's capture phase
+ // too and means nothing here.
+ subscribeInput(view, 'blur', event => {
+ if (!(event.target instanceof view.Node)) {
+ cancelWheel();
+ }
+ }),
+ subscribeInput(view, 'visibilitychange', () => {
+ if (this.doc.visibilityState === 'hidden') {
+ cancelWheel();
+ }
+ }),
+ ];
+ this.stopWheelLatch = () => {
+ for (const stop of stops) {
+ stop();
+ }
+ };
+ }
+ }
+
+ /**
+ * End the trackpad pan a recognizer still drives, when the page loses focus
+ * or hides, and return its contacts to cancel. The rest of its stream is
+ * the page's until the stream ends, as a touch the browser takes is. A
+ * ctrl-wheel pinch keeps its stream, so the page never zooms for it. A
+ * gesture the page keeps stays as it is. So does a pan its lift released:
+ * its momentum stays latched and prevented until the stream ends.
+ */
+ private dropDrivenWheel(): ReadonlyArray<number> {
+ const gesture = this.wheel;
+ if (
+ gesture == null ||
+ gesture.kind !== 'pan' ||
+ gesture.ids.length === 0 ||
+ gesture.follow?.lifted === true
+ ) {
+ return [];
+ }
+ const kept: WheelGesture = {...gesture, ids: [], takers: []};
+ delete kept.follow;
+ this.wheel = kept;
+ this.stopWheelLatch?.();
+ this.stopWheelLatch = null;
+ return gesture.ids;
+ }
+
+ /**
+ * End the wheel gesture in progress. On its own timer, it ends its end
+ * window after its last wheel. A taker that leaves (a detach, a disable)
+ * passes that last wheel's time. An input that ends it sooner (a press,
+ * the next gesture's first wheel) passes its own time. Both times are on
+ * the wheels' time base (eventTime), never the host's clock, which need
+ * not share it.
+ */
+ private endWheel(endTime?: number): void {
+ const gesture = this.wheel;
+ this.stopWheelLatch?.();
+ this.stopWheelLatch = null;
+ if (gesture == null) {
+ return;
+ }
+ this.wheel = null;
+ if (gesture.timer != null) {
+ this.clock.clearTimeout(gesture.timer);
+ }
+ if (gesture.ids.length === 0 || gesture.follow?.lifted) {
+ return;
+ }
+ // Fingers that stop without a lift end on their travel, where it runs
+ // ahead of what the pan shows. What the undecided stretch showed past it
+ // stays, as a step back would show.
+ if (gesture.follow != null) {
+ const f = gesture.follow;
+ const x = ahead(gesture.x, f.trueX - f.heldX, f.speedX);
+ const y = ahead(gesture.y, f.trueY - f.heldY, f.speedY);
+ if (x !== gesture.x || y !== gesture.y) {
+ gesture.x = x;
+ gesture.y = y;
+ this.arena.moved([{id: gesture.ids[0], x, y, time: gesture.last}]);
+ }
+ }
+ // A trackpad scroll whose fingers stop releases still, past the
+ // velocity's stillness interval. A pinch releases 100 ms after its last
+ // wheel, and a lift released the pan already. The release is never later
+ // than the input that ends it (a press, the next gesture's first wheel).
+ // The arena's clock only moves forward, so a later stamp would move that
+ // input's times too.
+ const end = gesture.last + gesture.endMs;
+ const time =
+ endTime == null ? end : Math.max(gesture.last, Math.min(end, endTime));
+ this.arena.ended(
+ gesture.kind === 'pan'
+ ? [{id: gesture.ids[0], x: gesture.x, y: gesture.y, time}]
+ : this.pinchContacts(gesture, time),
+ );
+ }
+
/** Undo `lockSelection` for a contact that ended; idempotent. */
private unlockSelection(id: number): void {
this.lockedBy.get(id)?.();
@@ -1869,6 +2625,7 @@ export class GestureHost {
}
private readonly onTouchStart = (event: TouchEvent): void => {
+ this.endWheel(eventTime(event));
this.noteFingersDown(event);
// Where the host reads a finger from its pointer events (no ontouchstart,
// as after touch emulation turns on), its Touch Events would track it twice.
@@ -2554,6 +3311,7 @@ export class GestureHost {
// --- Pointer events --------------------------------------------------------
private readonly onPointerDown = (event: PointerEvent): void => {
+ this.endWheel(eventTime(event));
// A new press: whatever click is still owed to the last one is not this.
disarmClickGuard(this.doc);
if (!isPointerKind(event.pointerType)) {
@@ -3024,6 +3782,8 @@ export class GestureHost {
this.unpairedTouches.clear();
this.lastFed.clear();
this.pointerFed.clear();
+ // A trackpad pan a recognizer still drives is cancelled with them.
+ ids.push(...this.dropDrivenWheel());
if (ids.length > 0) {
this.arena.cancelled(ids, time);
}
diff --git a/packages/core/src/gestures/GestureRecognizer.ts b/packages/core/src/gestures/GestureRecognizer.ts
index e68007b6b7..76223c75c7 100644
--- a/packages/core/src/gestures/GestureRecognizer.ts
+++ b/packages/core/src/gestures/GestureRecognizer.ts
@@ -36,6 +36,7 @@ import type {
GestureTouch,
Point,
PointerKind,
+ ScrollType,
} from './types';
import {DEFAULT_ENVIRONMENT} from './types';
@@ -81,6 +82,16 @@ export interface GestureRecognizerOptions<R = GestureRecognizer> {
delaysTouchesEnded?: boolean;
/** Pointer kinds this recognizer listens to (UIKit's `allowedTouchTypes`). @default all */
allowedPointerTypes?: ReadonlyArray<PointerKind>;
+ /**
+ * Scroll input this recognizer takes, as UIKit's `allowedScrollTypesMask`.
+ * A pan follows a trackpad's two-finger scroll (`continuous`), never a
+ * mouse wheel's notches. It moves as a contact with the content, along its
+ * own axis, after the scrollers under the pointer. A pinch takes a
+ * ctrl-wheel of either, as a trackpad pinches.
+ * @default none; a pinch takes both, the screen-edge pan none whatever a
+ * caller passes
+ */
+ allowedScrollTypes?: ReadonlyArray<ScrollType>;
/** Ignore a touch of a different kind than the ones already tracked. @default true */
requiresExclusiveTouchType?: boolean;
/**
@@ -202,6 +213,8 @@ export abstract class GestureRecognizer {
delaysTouchesBegan: boolean;
delaysTouchesEnded: boolean;
allowedPointerTypes: ReadonlySet<PointerKind> | null;
+ /** See GestureRecognizerOptions.allowedScrollTypes. */
+ readonly allowedScrollTypes: ReadonlySet<ScrollType>;
requiresExclusiveTouchType: boolean;
/**
* The element (or any object) the recognizer is attached to. The DOM host
@@ -247,6 +260,9 @@ export abstract class GestureRecognizer {
options.allowedPointerTypes == null
? null
: new Set(options.allowedPointerTypes);
+ this.allowedScrollTypes = new Set(
+ options.allowedScrollTypes ?? this.defaultScrollTypes,
+ );
this.requiresExclusiveTouchType =
options.requiresExclusiveTouchType ?? true;
}
@@ -479,6 +495,11 @@ export abstract class GestureRecognizer {
/** Clear per-gesture state before the next attempt. */
protected reset(): void {}
+ /** The scroll types taken when the options name none (UIKit's: none). */
+ protected get defaultScrollTypes(): ReadonlyArray<ScrollType> {
+ return [];
+ }
+
/**
* Whether a touch may join. The base checks enabled, pointer kind and
* exclusivity of kind; subclasses narrow it (a one-finger pan ignores a
@@ -488,6 +509,13 @@ export abstract class GestureRecognizer {
if (!this.isEnabled) {
return false;
}
+ if (touch.scrollType != null) {
+ // Scroll input is no pointer: only the scroll types allowed count.
+ return (
+ this.allowedScrollTypes.has(touch.scrollType) &&
+ (this.options.shouldReceiveTouch?.(this, touch) ?? true)
+ );
+ }
if (
this.allowedPointerTypes != null &&
!this.allowedPointerTypes.has(touch.pointerType)
diff --git a/packages/core/src/gestures/PanGestureRecognizer.ts b/packages/core/src/gestures/PanGestureRecognizer.ts
index ac21d5637a..2f65f77b71 100644
--- a/packages/core/src/gestures/PanGestureRecognizer.ts
+++ b/packages/core/src/gestures/PanGestureRecognizer.ts
@@ -73,6 +73,14 @@ export interface PanGestureRecognizerOptions extends GestureRecognizerOptions<Pa
* at the start only (UIScrollView's directional lock).
*/
lockAxis?: boolean;
+ /**
+ * A trackpad's two-finger scroll (`continuous`) drives the pan where its
+ * owner allows it. It moves as a contact with the content, along its own
+ * axis, after the scrollers under the pointer. A mouse wheel's notches
+ * never drive a pan; they scroll what is under the pointer.
+ * @default [] (none)
+ */
+ allowedScrollTypes?: ReadonlyArray<'continuous'>;
/** Begin only when the native scrollers under the touch are at the edge. */
scrollEdge?: boolean;
}
diff --git a/packages/core/src/gestures/PinchGestureRecognizer.ts b/packages/core/src/gestures/PinchGestureRecognizer.ts
index 6ca75bb627..900c348dc9 100644
--- a/packages/core/src/gestures/PinchGestureRecognizer.ts
+++ b/packages/core/src/gestures/PinchGestureRecognizer.ts
@@ -27,7 +27,12 @@ import {
type GestureRecognizerOptions,
type NativeTouchBehavior,
} from './GestureRecognizer';
-import type {GestureEventContext, GestureTouch, Point} from './types';
+import type {
+ GestureEventContext,
+ GestureTouch,
+ Point,
+ ScrollType,
+} from './types';
import {VelocityTracker} from './VelocityTracker';
export interface PinchGestureRecognizerOptions extends GestureRecognizerOptions<PinchGestureRecognizer> {
@@ -51,6 +56,16 @@ export class PinchGestureRecognizer extends GestureRecognizer {
this.hysteresis = options.hysteresis ?? UIKIT_PINCH.hysteresis.value;
}
+ /** @internal The host's brand: a ctrl-wheel drives a pinch (recognizerInternals). */
+ protected get family(): 'pinch' {
+ return 'pinch';
+ }
+
+ /** A ctrl-wheel drives a pinch, from a trackpad or a mouse. */
+ protected override get defaultScrollTypes(): ReadonlyArray<ScrollType> {
+ return ['continuous', 'discrete'];
+ }
+
/** Current span over the span the fingers started at. */
get scale(): number {
return this.scaleValue;
diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md
index 57b3bbf7a7..a2429c0c93 100644
--- a/packages/core/src/gestures/README.md
+++ b/packages/core/src/gestures/README.md
@@ -452,6 +452,69 @@ anywhere (often on a plain row no recognizer is on) fails a pan limited to
one finger, so the two fingers zoom the page (WCAG 1.4.4) instead of the pan
claiming them midway.
+## Wheel and trackpad
+
+A recognizer takes scroll input only where it allows that scroll type
+(`allowedScrollTypes`, UIKit's `allowedScrollTypesMask`): `continuous`
+for a trackpad's two-finger scroll or pinch, `discrete` for a mouse wheel's
+notches. A pan follows a trackpad, never a mouse wheel (`spec:AST-094` FR43,
+DEC-24): it allows only `continuous`, and none by default, so it takes a
+trackpad's scroll only where its owner allows it, its element then getting
+the one wheel listener, and a mouse wheel's notches always scroll what is
+under the pointer. A pinch allows both, for a ctrl-wheel from a trackpad or
+a mouse. The screen-edge pan takes none, as it takes no mouse, trackpad or
+pen (FR43). A control's thumb, a slider's or a switch's, tracks as a control,
+not a pan, and takes no wheel, so a page scroll over it never changes its
+value (DEC-23). The web reports no wheel phases or device, so the deltas
+tell, and what they cannot tell apart reads as a mouse wheel: a line- or
+page-mode delta; a scroll with Shift held (Shift+wheel); a pixel delta a hair
+off a whole pixel (a mouse wheel on Windows); a scroll with no legacy `wheelDelta` (an engine that
+sends none); a delta that is not a third of its legacy `wheelDelta`; or a 120
+tick over a 40 px delta. A trackpad's precise deltas, a third of their legacy
+`wheelDelta` (Chromium and WebKit), read as a trackpad.
+
+A wheel gesture drives a pan as a contact moving with the content, along the
+pan's own axis, and only once every scroller between the pointer and the
+pan's element is at its edge that way, decided at the gesture's first wheel:
+a wheel the pan does not take is never prevented. A watcher
+(`claimsTouches: false`) never takes one, and a gesture whose first wheel
+another handler already prevented, or that cannot be cancelled, stays the
+page's. A scroll-edge pan (a pull to
+refresh) takes one only if no scroller under the pointer could scroll for it,
+its own scroll owner and the page included, as its finger's rule reads them
+(`spec:AST-094` FR19); `touch-action` narrows only a finger's pan, so a wheel
+reads every scroller past it. A ctrl-wheel (a trackpad
+pinch, or Control and a mouse wheel) drives a pinch, whose scale follows
+`exp(-deltaY / 100)`; a pinch takes it by default and ends 100 ms after its
+last wheel. While the fingers move, a trackpad scroll ends 180 ms after its
+last wheel vertically and 220 ms horizontally, whoever keeps it (a pan, a
+scroller under the pointer, or the page), as a slow drag pauses between
+wheels (DEC-24). A gesture's release is never stamped
+later than an input that ends it sooner (FR16).
+
+The web reports no trackpad contact or phase either, so one splitter reads
+every trackpad stream (`wheelSegmenter.ts`, DEC-24): at the fourth or later
+delta of a shrinking run, once the run has lost a fifth of its size, the
+fingers lifted and momentum began. Until it decides,
+the shrinking deltas wait, and a pan it follows moves on at the fingers' last
+speed, never past what that speed projects. At the lift the pan keeps that
+travel and lets go there, still moving at that speed, and the momentum after
+it never moves it; when the fingers carry on instead, their moves absorb
+what the pan showed past their travel, or short of it, so it never steps
+back and ends on their travel. Fingers that stop release still, once the end
+time passes. In momentum, a reversal, a delta that grows
+against the decay, or a 50 ms pause starts a new gesture. A finger, mouse or
+pen that comes down ends it, and a wheel claim keeps the page's text
+selection. A gesture a
+recognizer took is latched to it, as a browser latches a scroller: while it
+lasts, the host hears every step first, through the shared input stream's
+window-capture listener, wherever it lands, so a pan whose element moves from
+under a still pointer keeps the gesture. A page that loses focus or hides
+cancels a trackpad pan a recognizer still drives, as it cancels every touch;
+the rest of that stream is the page's. A ctrl-wheel pinch keeps its stream,
+so the page never zooms for it, and a pan its lift released keeps its
+momentum latched until the stream ends.
+
## Time
Every input carries its own timestamp (`event.timeStamp`), and timers are
diff --git a/packages/core/src/gestures/ScreenEdgePanGestureRecognizer.ts b/packages/core/src/gestures/ScreenEdgePanGestureRecognizer.ts
index d9ca6f5c4d..85653cd918 100644
--- a/packages/core/src/gestures/ScreenEdgePanGestureRecognizer.ts
+++ b/packages/core/src/gestures/ScreenEdgePanGestureRecognizer.ts
@@ -71,12 +71,12 @@ interface EdgeLayout {
}
/**
- * A screen-edge pan is a finger's: it takes no `allowedPointerTypes`
- * (`spec:AST-094` FR43).
+ * A screen-edge pan is a finger's: it takes no `allowedPointerTypes` and no
+ * `allowedScrollTypes`, so neither a mouse, a trackpad nor a pen drives it.
*/
export interface ScreenEdgePanGestureRecognizerOptions extends Omit<
PanGestureRecognizerOptions,
- 'direction' | 'allowedPointerTypes'
+ 'direction' | 'allowedPointerTypes' | 'allowedScrollTypes'
> {
/** The edges a touch may start from. @default ['leading'] */
edges?: ReadonlyArray<ScreenEdge>;
@@ -109,9 +109,11 @@ export class ScreenEdgePanGestureRecognizer extends PanGestureRecognizer {
maximumNumberOfTouches: 1,
hysteresis: UIKIT_SCREEN_EDGE_PAN.hysteresis.value,
...options,
- // A finger's only: under a mouse, a trackpad or a pen the screen-edge
- // pan stays off (`spec:AST-094` FR43), whatever a caller passes.
+ // A finger's only (`spec:AST-094` FR43). Under a mouse, a trackpad or
+ // a pen, the screen-edge pan stays off, whatever a caller passes. It
+ // takes no wheel or trackpad scrolling.
allowedPointerTypes: ['touch'],
+ allowedScrollTypes: [],
});
this.edges = options.edges ?? ['leading'];
this.edgeRegion =
diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts
index 590ff8a26e..d4c8265481 100644
--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts
+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts
@@ -566,7 +566,9 @@ describe('GestureHost', () => {
.filter(t => /^(touch|pointer)/.test(t));
// A fine primary pointer: nothing on the page while idle, and on the
// element the one listener its press needs, plus the claiming pan's
- // blocking touchmove, which FR24 counts outside that budget (FR19).
+ // blocking touchmove, which FR24 counts outside that budget (FR19). A pan
+ // takes no scroll unless its owner allows a trackpad's, so no wheel
+ // listener (FR43, DEC-24).
const fine = new GestureHost(document, {
clock,
isPrimaryPointerCoarse: () => false,
diff --git a/packages/core/src/gestures/__tests__/browser/bareFixture.ts b/packages/core/src/gestures/__tests__/browser/bareFixture.ts
index ed73146690..eabd17f666 100644
--- a/packages/core/src/gestures/__tests__/browser/bareFixture.ts
+++ b/packages/core/src/gestures/__tests__/browser/bareFixture.ts
@@ -15,6 +15,7 @@
import {getGestureHost} from '../../GestureHost';
import {LongPressGestureRecognizer} from '../../LongPressGestureRecognizer';
import {PanGestureRecognizer} from '../../PanGestureRecognizer';
+import {PinchGestureRecognizer} from '../../PinchGestureRecognizer';
import {ScreenEdgePanGestureRecognizer} from '../../ScreenEdgePanGestureRecognizer';
import {lockSelection} from '../../../utils/selectionLock';
import {TapGestureRecognizer} from '../../TapGestureRecognizer';
@@ -22,10 +23,12 @@ import {TapGestureRecognizer} from '../../TapGestureRecognizer';
declare global {
interface Window {
__pageTouch: number;
+ __wheelLog: string[];
__api: {
host: ReturnType<typeof getGestureHost>;
LongPressGestureRecognizer: typeof LongPressGestureRecognizer;
PanGestureRecognizer: typeof PanGestureRecognizer;
+ PinchGestureRecognizer: typeof PinchGestureRecognizer;
ScreenEdgePanGestureRecognizer: typeof ScreenEdgePanGestureRecognizer;
TapGestureRecognizer: typeof TapGestureRecognizer;
lockSelection: typeof lockSelection;
@@ -36,6 +39,7 @@ declare global {
// The touch listeners on the window and the document, as the engine sees
// them: what makes the page pay for touches.
window.__pageTouch = 0;
+window.__wheelLog = [];
const live = new Set<string>();
const listenerIds = new WeakMap<object, number>();
let nextListenerId = 1;
@@ -92,6 +96,7 @@ window.__api = {
host: getGestureHost(document),
LongPressGestureRecognizer,
PanGestureRecognizer,
+ PinchGestureRecognizer,
ScreenEdgePanGestureRecognizer,
TapGestureRecognizer,
lockSelection,
diff --git a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
index 85340e6ebc..49b2338836 100644
--- a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
+++ b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
@@ -25,6 +25,16 @@
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {build} from 'esbuild';
+import {webInputDriver, WHEEL_SKIP} from '@astryxdesign/interaction-harness';
+
+/**
+ * Chromium's driver sends each wheel as one notch, `wheelDeltaY` -120
+ * whatever its delta, which the host reads as a mouse wheel's (FR43);
+ * WebKit's sends a trackpad's precise deltas (`wheelDeltaY` three times the
+ * delta), so it carries the trackpad-only cases.
+ */
+const TRACKPAD_SKIP =
+ "Chromium's driver sends each wheel as a mouse wheel's notch (wheelDeltaY -120 whatever its delta); WebKit's driver sends a trackpad's precise deltas";
import {expect, test, type Page} from '@playwright/test';
interface Entry {
@@ -1710,6 +1720,284 @@ test.describe('under a fine primary pointer (spec:AST-094 FR43, FR24)', () => {
test.describe('where the primary pointer is fine', () => {
test.use({hasTouch: false, isMobile: false});
+ test('a scroll-edge pan takes a trackpad scroll only at the top of the page that scrolls it, pulling the content down; mid-page the page scrolls (spec:AST-094 FR43, FR19)', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName === 'chromium', TRACKPAD_SKIP);
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body style="margin: 0"></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<div id="content" style="height: 3000px; width: 300px">content</div>';
+ const pull = new PanGestureRecognizer({
+ direction: 'vertical',
+ scrollEdge: true,
+ allowedPointerTypes: [],
+ allowedScrollTypes: ['continuous'],
+ });
+ pull.addTransitionListener((_recognizer, _from, to) =>
+ window.__wheelLog.push(`pull:${to}`),
+ );
+ host.attach(document.getElementById('content') as HTMLElement, pull);
+ });
+ const driver = await webInputDriver(page);
+ test.skip(!driver.wheels, WHEEL_SKIP);
+ const at = {x: 100, y: 200};
+ // Mid-page, a scroll up is the page's.
+ await page.evaluate(() => window.scrollTo(0, 400));
+ await page.waitForTimeout(100);
+ for (let step = 0; step < 4; step += 1) {
+ await driver.wheel({...at, dy: -16});
+ }
+ await page.waitForTimeout(250);
+ expect(await page.evaluate(() => window.scrollY)).toBeLessThan(400);
+ expect(await page.evaluate(() => window.__wheelLog)).toEqual([]);
+ // At the top, scrolling down is the page's too.
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await page.waitForTimeout(100);
+ await driver.wheel({...at, dy: 16});
+ await page.waitForTimeout(250);
+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0);
+ expect(await page.evaluate(() => window.__wheelLog)).toEqual([]);
+ // At the top, pulling the content down: the pan's, and the page holds.
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await page.waitForTimeout(100);
+ for (let step = 0; step < 4; step += 1) {
+ await driver.wheel({...at, dy: -16});
+ }
+ await page.waitForTimeout(250);
+ const pull = await page.evaluate(() => window.__wheelLog);
+ expect(pull[0]).toBe('pull:began');
+ expect(pull).toContain('pull:ended');
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ });
+
+ test('a wheel gesture stays with the pan that took it when the pan moves its element from under a still cursor, as a browser latches a scroller (spec:AST-094 FR43)', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName === 'chromium', TRACKPAD_SKIP);
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<div id="wrapper" style="height: 120px; width: 400px"><div id="card" style="height: 120px; width: 60px; background: #ccc">card</div></div><div style="height: 10px; width: 3000px"></div>';
+ const card = document.getElementById('card') as HTMLElement;
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ // The card follows the pan, as a swipe would move it.
+ pan.addTransitionListener((_recognizer, _from, to) => {
+ card.style.transform = `translateX(${pan.translation().x}px)`;
+ window.__wheelLog.push(`pan:${to}:${Math.round(pan.translation().x)}`);
+ });
+ host.attach(card, pan);
+ });
+ const driver = await webInputDriver(page);
+ test.skip(!driver.wheels, WHEEL_SKIP);
+ const card = await center(page, 'card');
+ // Six 16 px steps at a still cursor: the card leaves it after two.
+ for (let step = 0; step < 6; step += 1) {
+ await driver.wheel({...card, dx: 16});
+ }
+ await page.waitForTimeout(250);
+ const pan = await page.evaluate(() =>
+ window.__wheelLog.filter(entry => entry.startsWith('pan:')),
+ );
+ const moved = pan.filter(entry => entry.startsWith('pan:changed:'));
+ // Every step after the first moved the card, and none scrolled the page.
+ expect(moved).toHaveLength(5);
+ expect(pan.slice(-2).map(entry => entry.split(':')[1])).toEqual([
+ 'ended',
+ 'possible',
+ ]);
+ expect(await page.evaluate(() => window.scrollX)).toBe(0);
+ });
+
+ /** A page with a horizontal pan that takes only a trackpad's scroll; its moves land on `window.__wheelLog`. */
+ async function trackpadPanPage(page: Page) {
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<div id="card" style="height: 120px; width: 300px; background: #ccc">card</div>';
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedPointerTypes: [],
+ allowedScrollTypes: ['continuous'],
+ });
+ pan.addTransitionListener((_recognizer, _from, to) => {
+ window.__wheelLog.push(
+ `pan:${to}:${pan.translation().x.toFixed(2)}:${Math.round(pan.velocity().x)}`,
+ );
+ });
+ host.attach(document.getElementById('card') as HTMLElement, pan);
+ // After every listener of the host's: whether each wheel reached the
+ // page (not prevented) or was the pan's.
+ window.addEventListener('wheel', event => {
+ window.__wheelLog.push(`wheel:${String(event.defaultPrevented)}`);
+ });
+ });
+ }
+
+ /** The pan's log entries after `deltas`, one wheel each, and a quiet 300 ms. */
+ async function trackpadRun(page: Page, deltas: number[]) {
+ const driver = await webInputDriver(page);
+ test.skip(!driver.wheels, WHEEL_SKIP);
+ const at = await center(page, 'card');
+ for (const dx of deltas) {
+ await driver.wheel({...at, dx});
+ }
+ await page.waitForTimeout(300);
+ const log = await page.evaluate(() =>
+ window.__wheelLog.filter(entry => entry.startsWith('pan:')),
+ );
+ const moves = log
+ .filter(entry => /^pan:(changed|ended):/.test(entry))
+ .map(entry => Number(entry.split(':')[2]));
+ return {log, moves};
+ }
+
+ test("keeps a trackpad pan moving at the fingers' speed through the splitter's undecided stretch and lets it go at the lift still moving: no stall (spec:AST-094 FR43)", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName === 'chromium', TRACKPAD_SKIP);
+ await trackpadPanPage(page);
+ // Four steady wheels, four shrinking ones (the lift is read at the
+ // fourth), then momentum.
+ const {log, moves} = await trackpadRun(
+ page,
+ [12, 12, 12, 12, 11, 10, 9, 8, 7, 6, 5, 4],
+ );
+ const ended = log.filter(entry => entry.startsWith('pan:ended:'));
+ expect(ended).toHaveLength(1);
+ // The fingers' travel at their last steady wheel is -38 (48 px past the
+ // 10 px hysteresis); the pan moved on past it through the shrinking
+ // wheels, at least a wheel and a half's worth, never stepping back.
+ for (const [i, x] of moves.entries()) {
+ if (i > 0) {
+ expect(x).toBeLessThanOrEqual(moves[i - 1]);
+ }
+ }
+ expect(moves.at(-1)).toBeLessThan(-38 - 18);
+ // Let go still moving, and the momentum after it moved nothing.
+ expect(Math.abs(Number(ended[0].split(':')[3]))).toBeGreaterThan(100);
+ expect(
+ log.slice(log.indexOf(ended[0]) + 1).map(entry => entry.split(':')[1]),
+ ).toEqual(['possible']);
+ // No wheel reached the page, the momentum after the lift included
+ // (spec:AST-094 FR43).
+ const wheels = await page.evaluate(() =>
+ window.__wheelLog.filter(entry => entry.startsWith('wheel:')),
+ );
+ expect(wheels).toEqual(Array.from({length: 12}, () => 'wheel:true'));
+ });
+
+ test('absorbs what the undecided stretch showed when the fingers carry on: never a step back, and the pan ends on their travel (spec:AST-094 FR43)', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName === 'chromium', TRACKPAD_SKIP);
+ await trackpadPanPage(page);
+ const deltas = [12, 12, 12, 12, 11, 10, 12, 12, 12, 12, 12, 12];
+ const {moves} = await trackpadRun(page, deltas);
+ for (const [i, x] of moves.entries()) {
+ if (i > 0) {
+ expect(x).toBeLessThanOrEqual(moves[i - 1]);
+ }
+ }
+ const travel = deltas.reduce((sum, delta) => sum + delta, 0) - 10;
+ expect(moves.at(-1)).toBeCloseTo(-travel, 1);
+ });
+
+ test("a pan that takes a trackpad's scroll follows a real trackpad scroll along its axis and keeps the page still, never a mouse wheel's notches, which scroll the page; a wheel across it scrolls the page, and a pinch follows a ctrl-wheel (spec:AST-094 FR43, DEC-24)", async ({
+ page,
+ browserName,
+ }) => {
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer, PinchGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<div id="strip" style="height: 120px; width: 300px">strip</div><div id="photo" style="height: 120px; width: 300px">photo</div><div style="height: 3000px; width: 3000px"></div>';
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ pan.addTransitionListener((_recognizer, _from, to) =>
+ window.__wheelLog.push(`pan:${to}:${Math.round(pan.translation().x)}`),
+ );
+ host.attach(document.getElementById('strip') as HTMLElement, pan);
+ const pinch = new PinchGestureRecognizer();
+ pinch.addTransitionListener((_recognizer, _from, to) =>
+ window.__wheelLog.push(`pinch:${to}:${pinch.scale.toFixed(2)}`),
+ );
+ host.attach(document.getElementById('photo') as HTMLElement, pinch);
+ });
+ const driver = await webInputDriver(page);
+ test.skip(!driver.wheels, WHEEL_SKIP);
+ const strip = await center(page, 'strip');
+ for (let step = 0; step < 6; step += 1) {
+ await driver.wheel({...strip, dx: 8});
+ }
+ await page.waitForTimeout(250);
+ const pan = await page.evaluate(() =>
+ window.__wheelLog.filter(entry => entry.startsWith('pan:')),
+ );
+ if (browserName === 'chromium') {
+ // Chromium's driver sends a mouse wheel's notches (wheelDeltaX -120
+ // whatever the delta): a pan never takes them, and they scroll the page.
+ expect(pan).toEqual([]);
+ expect(await page.evaluate(() => window.scrollX)).toBeGreaterThan(0);
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await page.waitForTimeout(250);
+ } else {
+ // WebKit's sends a trackpad's precise deltas, which the pan follows.
+ expect(pan[0]).toMatch(/^pan:began:/);
+ expect(pan.some(entry => entry.startsWith('pan:ended:'))).toBe(true);
+ // The content moves the way the fingers do: a scroll right drags it left.
+ const moved = pan.filter(entry => entry.startsWith('pan:changed:'));
+ expect(Number(moved.at(-1)?.split(':')[2])).toBeLessThan(0);
+ expect(await page.evaluate(() => window.scrollX)).toBe(0);
+ }
+ // Across the pan's axis the wheel is the page's.
+ await driver.wheel({...strip, dy: 60});
+ await page.waitForTimeout(250);
+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0);
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await page.waitForTimeout(250);
+ const photo = await center(page, 'photo');
+ for (let step = 0; step < 5; step += 1) {
+ await driver.wheel({...photo, dy: -10, ctrl: true});
+ }
+ await page.waitForTimeout(250);
+ const pinch = await page.evaluate(() =>
+ window.__wheelLog.filter(entry => entry.startsWith('pinch:')),
+ );
+ expect(pinch[0]).toMatch(/^pinch:began:/);
+ expect(pinch.some(entry => entry.startsWith('pinch:ended:'))).toBe(true);
+ expect(
+ Math.max(...pinch.map(entry => Number(entry.split(':')[2]))),
+ ).toBeGreaterThan(1);
+ });
test("the host registers no page touch listener while idle and warns for nothing, though the page attaches recognizers: an element keeps only a claiming recognizer's blocking touchmove; a mouse drag pans (spec:AST-094 FR43, FR24, FR19)", async ({
page,
diff --git a/packages/core/src/gestures/__tests__/harness.ts b/packages/core/src/gestures/__tests__/harness.ts
index cf68c863b8..37f8796de6 100644
--- a/packages/core/src/gestures/__tests__/harness.ts
+++ b/packages/core/src/gestures/__tests__/harness.ts
@@ -20,16 +20,49 @@ import type {
TouchConsumer,
} from '../types';
-/** A clock that only moves when the test says so. */
+/**
+ * A clock that only moves when the test says so. Its timers run only when a
+ * test calls `runDue`.
+ */
export class ManualClock implements GestureClock {
time = 0;
+ private readonly pending = new Map<
+ number,
+ {deadline: number; callback: () => void}
+ >();
+ private nextHandle = 1;
now(): number {
return this.time;
}
- setTimeout(): number {
- return 0;
+ setTimeout(callback: () => void, ms: number): number {
+ const handle = this.nextHandle++;
+ this.pending.set(handle, {deadline: this.time + ms, callback});
+ return handle;
+ }
+ clearTimeout(handle: unknown): void {
+ this.pending.delete(handle as number);
+ }
+ /** Move to `time`, running every timer due by then, earliest first. */
+ runDue(time: number): void {
+ for (;;) {
+ let due: [number, {deadline: number; callback: () => void}] | null = null;
+ for (const entry of this.pending) {
+ if (
+ entry[1].deadline <= time &&
+ (due == null || entry[1].deadline < due[1].deadline)
+ ) {
+ due = entry;
+ }
+ }
+ if (due == null) {
+ break;
+ }
+ this.pending.delete(due[0]);
+ this.time = Math.max(this.time, due[1].deadline);
+ due[1].callback();
+ }
+ this.time = time;
}
- clearTimeout(): void {}
}
export interface Harness {
diff --git a/packages/core/src/gestures/__tests__/wheel.test.ts b/packages/core/src/gestures/__tests__/wheel.test.ts
new file mode 100644
index 0000000000..45582eb4d5
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/wheel.test.ts
@@ -0,0 +1,1538 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file wheel.test.ts
+ * @input A GestureHost on a manual clock, with pans and pinches that allow
+ * scroll input, driven by synthetic WheelEvents
+ * @output Tests for spec:AST-094 FR43's wheel and trackpad input: a pan
+ * takes scrolling only where it allows that scroll type (UIKit's
+ * allowedScrollTypesMask, none by default), along its own axis, after the
+ * scrollers under the pointer; a pinch takes a ctrl-wheel; a wheel gesture
+ * ends 100 ms after its last event
+ * @position Unit tests of the host's wheel input (GestureHost.ts)
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {GestureHost} from '../GestureHost';
+import {createNativeScrollProbe} from '../nativeScroll';
+import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {PinchGestureRecognizer} from '../PinchGestureRecognizer';
+import {ScreenEdgePanGestureRecognizer} from '../ScreenEdgePanGestureRecognizer';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {ManualClock} from './harness';
+
+let clock: ManualClock;
+let host: GestureHost;
+let detachers: (() => void)[];
+
+function mount(html: string): Record<string, HTMLElement> {
+ document.body.innerHTML = html;
+ const elements: Record<string, HTMLElement> = {};
+ for (const element of document.querySelectorAll<HTMLElement>('[id]')) {
+ elements[element.id] = element;
+ }
+ return elements;
+}
+
+function wheel(
+ target: EventTarget,
+ init: {
+ x?: number;
+ y?: number;
+ dx?: number;
+ dy?: number;
+ mode?: number;
+ ctrl?: boolean;
+ /** The legacy `wheelDeltaX`/`wheelDeltaY` Chromium and WebKit send. */
+ legacy?: {x: number; y: number};
+ /** A trackpad's wheel: its legacy delta three times its delta. */
+ trackpad?: boolean;
+ /** Shift held, as Shift+wheel sends. */
+ shift?: boolean;
+ time: number;
+ },
+): WheelEvent {
+ clock.time = init.time;
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ clientX: init.x ?? 20,
+ clientY: init.y ?? 20,
+ deltaX: init.dx ?? 0,
+ deltaY: init.dy ?? 0,
+ deltaMode: init.mode ?? 0,
+ ctrlKey: init.ctrl ?? false,
+ shiftKey: init.shift ?? false,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: init.time});
+ const legacy =
+ init.legacy ??
+ (init.trackpad === true
+ ? {x: -3 * (init.dx ?? 0), y: -3 * (init.dy ?? 0)}
+ : null);
+ if (legacy != null) {
+ Object.defineProperty(event, 'wheelDeltaX', {value: legacy.x});
+ Object.defineProperty(event, 'wheelDeltaY', {value: legacy.y});
+ }
+ target.dispatchEvent(event);
+ return event;
+}
+
+function statesOf(recognizer: PanGestureRecognizer | PinchGestureRecognizer) {
+ const states: string[] = [];
+ recognizer.addTransitionListener((_recognizer, _from, to) => states.push(to));
+ return states;
+}
+
+/** jsdom has no layout: give a scroller its horizontal metrics. */
+function scrollableX(
+ element: HTMLElement,
+ metrics: {scrollLeft: number; scrollWidth: number; clientWidth: number},
+): void {
+ element.style.overflowX = 'auto';
+ for (const [key, value] of Object.entries(metrics)) {
+ Object.defineProperty(element, key, {configurable: true, value});
+ }
+}
+
+/** jsdom has no layout: give a scroller its vertical metrics. */
+function scrollableY(
+ element: HTMLElement,
+ metrics: {scrollTop: number; scrollHeight: number; clientHeight: number},
+): void {
+ element.style.overflowY = 'auto';
+ for (const [key, value] of Object.entries(metrics)) {
+ Object.defineProperty(element, key, {configurable: true, value});
+ }
+}
+
+beforeEach(() => {
+ clock = new ManualClock();
+ host = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ detachers = [];
+});
+
+afterEach(() => {
+ for (const detach of detachers.splice(0)) {
+ detach();
+ }
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+});
+
+describe('wheel and trackpad input (spec:AST-094 FR43)', () => {
+ it.each([
+ [
+ 'a 50° swipe is the pan’s when its axisRatio is 0.5, as a finger’s is',
+ 0.5,
+ 6.4,
+ 7.7,
+ true,
+ ],
+ [
+ 'a 35° swipe is the page’s when its axisRatio of 2 leaves it undecided',
+ 2,
+ 8.2,
+ 5.7,
+ false,
+ ],
+ ] as const)(
+ 'reads a trackpad’s direction by the pan’s own rule: %s',
+ (_name, axisRatio, dx, dy, takes) => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ axisRatio,
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ expect(
+ wheel(box, {trackpad: true, dx, dy, time: 0}).defaultPrevented,
+ ).toBe(takes);
+ for (const time of [16, 32, 48]) {
+ wheel(box, {trackpad: true, dx, dy, time});
+ }
+ expect(states.includes('began')).toBe(takes);
+ },
+ );
+
+ it.each([
+ ['a blur', 'blur', false],
+ ['a hidden page', 'hidden', false],
+ ['a blur, under a coarse primary pointer', 'blur', true],
+ ] as const)(
+ 'cancels a trackpad pan mid-swipe at %s: it reads cancelled, never ended, the rest of that stream is the page’s, and the next stream is decided afresh',
+ (_name, how, isCoarse) => {
+ const {box, outside} = mount(
+ '<div id="box"></div><div id="outside"></div>',
+ );
+ const subject = isCoarse
+ ? new GestureHost(document, {clock, isPrimaryPointerCoarse: () => true})
+ : host;
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(subject.attach(box, pan));
+ for (const time of [0, 16, 32]) {
+ clock.runDue(time);
+ expect(
+ wheel(box, {trackpad: true, dx: 10, time}).defaultPrevented,
+ ).toBe(true);
+ }
+ expect(states.at(-1)).toBe('changed');
+ clock.runDue(40);
+ if (how === 'blur') {
+ window.dispatchEvent(new Event('blur'));
+ } else {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'hidden',
+ });
+ detachers.push(() => {
+ delete (document as {visibilityState?: unknown}).visibilityState;
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ }
+ expect(states.slice(-2)).toEqual(['cancelled', 'possible']);
+ // The rest of the stream is the page's: the fingers' wheels, then the
+ // momentum after their lift.
+ const rest = [10, 10, 10, 10, 12, 11.4, 10.8, 10.3, 9.8, 9.3, 8.8, 8.4];
+ rest.forEach((dx, i) => {
+ expect(
+ wheel(box, {trackpad: true, dx, time: 48 + i * 16}).defaultPrevented,
+ ).toBe(false);
+ });
+ expect(states.filter(state => state === 'began')).toHaveLength(1);
+ expect(states).not.toContain('ended');
+ // The latch is gone: a wheel outside the pan is the page's.
+ expect(
+ wheel(outside, {trackpad: true, dx: 8, time: 48 + 12 * 16})
+ .defaultPrevented,
+ ).toBe(false);
+ // After the stream's pause, a new stream is decided afresh.
+ clock.runDue(48 + 12 * 16 + 400);
+ expect(
+ wheel(box, {trackpad: true, dx: 10, time: 700}).defaultPrevented,
+ ).toBe(true);
+ },
+ );
+
+ it('reads a right-to-left scroller under the pointer by its own range: at its start a scroll toward it is the pan’s, a scroll away from it the scroller’s', () => {
+ const {strip, scroller, item} = mount(
+ '<div id="strip"><div id="scroller" dir="rtl"><div id="item"></div></div></div>',
+ );
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(strip, pan));
+ // Right to left, scrollLeft runs from 0 at the start to minus the
+ // overflow: at 0 the scroller cannot scroll right any further.
+ scrollableX(scroller, {scrollLeft: 0, scrollWidth: 300, clientWidth: 200});
+ expect(
+ wheel(item, {trackpad: true, dx: -20, time: 0}).defaultPrevented,
+ ).toBe(false);
+ expect(states).toEqual([]);
+ // The scroller's stream ends 220 ms after its last wheel (FR43); the
+ // next one is decided afresh.
+ expect(
+ wheel(item, {trackpad: true, dx: 20, time: 400}).defaultPrevented,
+ ).toBe(true);
+ expect(
+ wheel(item, {trackpad: true, dx: 20, time: 416}).defaultPrevented,
+ ).toBe(true);
+ expect(states).toEqual(['began', 'changed']);
+ });
+
+ it("reads a right-to-left scroller by a finger's edge test: one WebKit leaves a pixel past its reported range is at its end, and a scroll on toward it is the pan’s", () => {
+ const {strip, scroller, item} = mount(
+ '<div id="strip"><div id="scroller" dir="rtl"><div id="item"></div></div></div>',
+ );
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(strip, pan));
+ // A fractional width rounds the reported overflow down to 99, while
+ // WebKit scrolls to -100 (measured): past the reported end, so at it.
+ scrollableX(scroller, {
+ scrollLeft: -100,
+ scrollWidth: 299,
+ clientWidth: 200,
+ });
+ expect(
+ wheel(item, {trackpad: true, dx: -20, time: 0}).defaultPrevented,
+ ).toBe(true);
+ expect(
+ wheel(item, {trackpad: true, dx: -20, time: 16}).defaultPrevented,
+ ).toBe(true);
+ expect(states).toEqual(['began', 'changed']);
+ });
+
+ it("reads a scroller's ends as a finger's probe does: 0.75 px short of its end it can still scroll, so the stream is the scroller's; within half a pixel, the pan's (spec:AST-094 FR43, FR19)", () => {
+ const {sheet, list, row} = mount(
+ '<div id="sheet"><div id="list"><div id="row"></div></div></div>',
+ );
+ const pan = new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(sheet, pan));
+ scrollableY(list, {
+ scrollTop: 299.25,
+ scrollHeight: 400,
+ clientHeight: 100,
+ });
+ expect(
+ createNativeScrollProbe(row, {readsTouchAction: false}).canScroll(0, -8),
+ ).toBe(true);
+ expect(wheel(row, {trackpad: true, dy: 8, time: 0}).defaultPrevented).toBe(
+ false,
+ );
+ expect(states).toEqual([]);
+ Object.defineProperty(list, 'scrollTop', {
+ configurable: true,
+ value: 299.6,
+ });
+ expect(
+ createNativeScrollProbe(row, {readsTouchAction: false}).canScroll(0, -8),
+ ).toBe(false);
+ expect(
+ wheel(row, {trackpad: true, dy: 8, time: 400}).defaultPrevented,
+ ).toBe(true);
+ expect(
+ wheel(row, {trackpad: true, dy: 8, time: 416}).defaultPrevented,
+ ).toBe(true);
+ expect(states[0]).toBe('began');
+ });
+
+ it('finds a scroller inside a shadow tree between the pointer and the pan, from what the wheel landed on', () => {
+ const {outer} = mount('<div id="outer"></div>');
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<div id="scroller"><div id="item"></div></div>';
+ const scroller = shadow.getElementById('scroller') as HTMLElement;
+ const item = shadow.getElementById('item') as HTMLElement;
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(outer, pan));
+ scrollableX(scroller, {scrollLeft: 50, scrollWidth: 300, clientWidth: 200});
+ expect(wheel(item, {dx: 20, time: 0}).defaultPrevented).toBe(false);
+ expect(wheel(item, {dx: 20, time: 16}).defaultPrevented).toBe(false);
+ expect(states).toEqual([]);
+ });
+
+ it("takes a wheel on a scroll-edge pan only while no scroller under the pointer could scroll for it, its own scroll owner above it included, as a finger's (FR19)", () => {
+ const {owner, content} = mount(
+ '<div id="owner"><div id="content"></div></div>',
+ );
+ const pull = new PanGestureRecognizer({
+ direction: 'vertical',
+ scrollEdge: true,
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pull);
+ detachers.push(host.attach(content, pull));
+ // Mid-scroll: a scroll up is the owner's.
+ scrollableY(owner, {scrollTop: 50, scrollHeight: 300, clientHeight: 200});
+ expect(
+ wheel(content, {trackpad: true, dy: -20, time: 0}).defaultPrevented,
+ ).toBe(false);
+ expect(
+ wheel(content, {trackpad: true, dy: -20, time: 16}).defaultPrevented,
+ ).toBe(false);
+ // At the top, a scroll down is the owner's too.
+ scrollableY(owner, {scrollTop: 0, scrollHeight: 300, clientHeight: 200});
+ expect(
+ wheel(content, {trackpad: true, dy: 20, time: 200}).defaultPrevented,
+ ).toBe(false);
+ expect(states).toEqual([]);
+ // At the top, pulling the content down: the pan's.
+ expect(
+ wheel(content, {trackpad: true, dy: -20, time: 400}).defaultPrevented,
+ ).toBe(true);
+ expect(
+ wheel(content, {trackpad: true, dy: -20, time: 416}).defaultPrevented,
+ ).toBe(true);
+ expect(states).toEqual(['began', 'changed']);
+ });
+
+ it("reads a wheel's scrollers past touch-action, which only narrows a finger's pan: content with touch-action none still leaves a mid-scroll wheel to its owner", () => {
+ const {owner, content} = mount(
+ '<div id="owner"><div id="content" style="touch-action: none"></div></div>',
+ );
+ const pull = new PanGestureRecognizer({
+ direction: 'vertical',
+ scrollEdge: true,
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pull);
+ detachers.push(host.attach(content, pull));
+ scrollableY(owner, {scrollTop: 50, scrollHeight: 300, clientHeight: 200});
+ expect(wheel(content, {dy: -20, time: 0}).defaultPrevented).toBe(false);
+ expect(wheel(content, {dy: -20, time: 16}).defaultPrevented).toBe(false);
+ expect(states).toEqual([]);
+ });
+
+ it('latches a wheel gesture to the pan that took it, as a browser latches a scroller: a step that lands outside the moved element still drives the pan and is prevented, until the gesture ends', () => {
+ const {wrapper, card} = mount(
+ '<div id="wrapper"><div id="card"></div></div>',
+ );
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(card, pan));
+ const added = vi.spyOn(window, 'addEventListener');
+ expect(
+ wheel(card, {trackpad: true, dx: 16, time: 0}).defaultPrevented,
+ ).toBe(true);
+ expect(
+ wheel(card, {trackpad: true, dx: 16, time: 16}).defaultPrevented,
+ ).toBe(true);
+ expect(states).toEqual(['began', 'changed']);
+ const afterTwo = pan.translation().x;
+ // The card has moved out from under a still cursor: the next steps land
+ // on the wrapper.
+ for (const time of [32, 48, 64, 80]) {
+ expect(
+ wheel(wrapper, {trackpad: true, dx: 16, time}).defaultPrevented,
+ ).toBe(true);
+ }
+ expect(pan.translation().x).toBe(afterTwo - 64);
+ expect(states.at(-1)).toBe('changed');
+ // One capturing, non-passive wheel listener on the window: the shared
+ // input stream's (architecture:react-component-runtime INV13).
+ expect(
+ (added.mock.calls as unknown[][]).filter(
+ call =>
+ call[0] === 'wheel' &&
+ (call[2] as AddEventListenerOptions | undefined)?.capture === true &&
+ (call[2] as AddEventListenerOptions | undefined)?.passive === false,
+ ),
+ ).toHaveLength(1);
+ const removed = vi.spyOn(window, 'removeEventListener');
+ // A followed trackpad swipe ends 220 ms after its last wheel.
+ clock.runDue(80 + 220);
+ expect(states.slice(-2)).toEqual(['ended', 'possible']);
+ expect(
+ (removed.mock.calls as unknown[][]).filter(call => call[0] === 'wheel'),
+ ).toHaveLength(1);
+ // Over: a wheel on the wrapper is the page's again.
+ expect(
+ wheel(wrapper, {trackpad: true, dx: 16, time: 400}).defaultPrevented,
+ ).toBe(false);
+ });
+
+ it("hears a latched wheel through the shared input stream, so an app's window-capture stopPropagation of a wheel outside the moved element cannot hand it to the page (architecture:react-component-runtime INV13)", () => {
+ const {card, outside} = mount(
+ '<div id="card"></div><div id="outside"></div>',
+ );
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ detachers.push(host.attach(card, pan));
+ // The app stops every wheel that does not land on the card, on the
+ // window's capture phase.
+ const stop = (event: Event) => {
+ if (event.target !== card) {
+ event.stopPropagation();
+ }
+ };
+ window.addEventListener('wheel', stop, {capture: true});
+ try {
+ wheel(card, {trackpad: true, dx: 16, time: 0});
+ wheel(card, {trackpad: true, dx: 16, time: 16});
+ expect(pan.state).toBe('changed');
+ // The card moved from under the cursor: the next step lands outside.
+ const step = wheel(outside, {trackpad: true, dx: 16, time: 32});
+ expect(step.defaultPrevented).toBe(true);
+ expect(pan.translation().x).toBeLessThan(-16);
+ } finally {
+ window.removeEventListener('wheel', stop, {capture: true});
+ }
+ });
+
+ it("ends a wheel gesture whose pan is detached mid-gesture at once, and takes the window's wheel listener with it (FR24)", () => {
+ const {card} = mount('<div id="card"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const detach = host.attach(card, pan);
+ wheel(card, {trackpad: true, dx: 16, time: 0});
+ wheel(card, {trackpad: true, dx: 16, time: 16});
+ expect(pan.state).toBe('changed');
+ const removed = vi.spyOn(window, 'removeEventListener');
+ detach();
+ // The latch leaves the shared stream, and its window listener goes with
+ // its last subscriber.
+ expect(
+ (removed.mock.calls as unknown[][]).filter(call => call[0] === 'wheel'),
+ ).toHaveLength(1);
+ expect(
+ wheel(document.body, {trackpad: true, dx: 16, time: 32}).defaultPrevented,
+ ).toBe(false);
+ });
+
+ it('arms nothing else for a recognizer that takes only scroll input (no pointer types): where the primary pointer is fine its element gets the wheel listener alone, and no finger, mouse or pen starts it', () => {
+ const {content} = mount('<div id="content"></div>');
+ const added = vi.spyOn(content, 'addEventListener');
+ const pan = new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedPointerTypes: [],
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(content, pan));
+ expect(
+ (added.mock.calls as unknown[][]).map(call => String(call[0])),
+ ).toEqual(['wheel']);
+ for (const pointerType of ['mouse', 'pen', 'touch']) {
+ for (const [type, y] of [
+ ['pointerdown', 10],
+ ['pointermove', 40],
+ ['pointermove', 80],
+ ['pointerup', 80],
+ ] as const) {
+ content.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 7,
+ pointerType,
+ clientX: 10,
+ clientY: y,
+ buttons: type === 'pointerup' ? 0 : 1,
+ }),
+ );
+ }
+ }
+ expect(states).toEqual([]);
+ });
+
+ it('makes no touch listener cancelling for a scroll-only claimer: with it beside a watcher, the touchend stays passive and the contextmenu off (spec:AST-094 FR20, FR24)', () => {
+ const {watched, pull} = mount(
+ '<div id="watched"></div><div id="pull"></div>',
+ );
+ const added = vi.spyOn(window, 'addEventListener');
+ detachers.push(() => added.mockRestore());
+ const coarse = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ // A watcher installs the host's touch listeners, all passive (FR20).
+ detachers.push(
+ coarse.attach(
+ watched,
+ new PanGestureRecognizer({claimsTouches: false, direction: 'vertical'}),
+ ),
+ );
+ added.mockClear();
+ // A pull that takes only the wheel claims no touch.
+ detachers.push(
+ coarse.attach(
+ pull,
+ new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedPointerTypes: [],
+ allowedScrollTypes: ['continuous'],
+ }),
+ ),
+ );
+ const calls = added.mock.calls as unknown as [
+ string,
+ unknown,
+ AddEventListenerOptions | undefined,
+ ][];
+ expect(
+ calls.filter(
+ ([type, , options]) =>
+ type === 'touchend' && options?.passive === false,
+ ),
+ ).toEqual([]);
+ expect(calls.filter(([type]) => type === 'contextmenu')).toEqual([]);
+ });
+
+ it('listens for the wheel only where a recognizer a wheel can drive allows it: a tap that allows scroll input adds no wheel listener', () => {
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(box, 'addEventListener');
+ const tap = new TapGestureRecognizer({allowedScrollTypes: ['continuous']});
+ detachers.push(host.attach(box, tap));
+ expect(
+ (added.mock.calls as unknown[][]).filter(call => call[0] === 'wheel'),
+ ).toEqual([]);
+ });
+
+ it("takes no scroll on a pan by default: a pan follows a trackpad's scroll only where its owner allows it, so its element gets no wheel listener (spec:AST-094 FR43, DEC-24)", () => {
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(box, 'addEventListener');
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ expect(pan.allowedScrollTypes.size).toBe(0);
+ expect(
+ (added.mock.calls as unknown[][]).filter(call => call[0] === 'wheel'),
+ ).toEqual([]);
+ expect(wheel(box, {trackpad: true, dx: 30, time: 0}).defaultPrevented).toBe(
+ false,
+ );
+ expect(states).toEqual([]);
+ });
+
+ it("never takes a mouse wheel's notches on a pan, even one a caller passes 'discrete': they scroll what is under the pointer (spec:AST-094 FR43, DEC-24)", () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ // @ts-expect-error a pan takes only a trackpad's scroll
+ allowedScrollTypes: ['continuous', 'discrete'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ // A notch in lines (Firefox's), a whole 100 px notch, and a 120 tick over
+ // 40 px (Chromium's).
+ expect(wheel(box, {dx: 1, mode: 1, time: 0}).defaultPrevented).toBe(false);
+ clock.runDue(300);
+ expect(wheel(box, {dx: 100, time: 400}).defaultPrevented).toBe(false);
+ clock.runDue(700);
+ expect(
+ wheel(box, {dx: 40, legacy: {x: -120, y: 0}, time: 800}).defaultPrevented,
+ ).toBe(false);
+ expect(states).toEqual([]);
+ });
+
+ it('leaves a wheel every taker declined to the page from its first step, as with no gesture system: a pan whose shouldReceiveTouch refuses it prevents nothing (spec:AST-094 FR43, FR19)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ // A Toast declines a wheel a scroller under it can still take.
+ shouldReceiveTouch: () => false,
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ const prevented = [0, 16, 32, 48, 64, 80].map(
+ time => wheel(box, {trackpad: true, dx: 16, time}).defaultPrevented,
+ );
+ expect(prevented).toEqual([false, false, false, false, false, false]);
+ expect(states).toEqual([]);
+ clock.runDue(300);
+ // A notch, too.
+ expect(wheel(box, {dx: 1, mode: 1, time: 400}).defaultPrevented).toBe(
+ false,
+ );
+ });
+
+ it('takes no wheel for a pan whose caller allows no scroll type: its element gets no wheel listener, and the page scrolls', () => {
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(box, 'addEventListener');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: [],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ expect(added.mock.calls.map(call => call[0])).not.toContain('wheel');
+ expect(wheel(box, {dx: 30, time: 0}).defaultPrevented).toBe(false);
+ expect(states).toEqual([]);
+ });
+
+ it('takes no wheel on a screen-edge pan, which FR43 keeps off under a mouse and a trackpad: a widened allowedScrollTypes is refused (spec:AST-094 FR43)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(box, 'addEventListener');
+ const edge = new ScreenEdgePanGestureRecognizer({
+ edges: ['leading'],
+ // @ts-expect-error the screen-edge pan takes no allowedScrollTypes
+ allowedScrollTypes: ['continuous', 'discrete'],
+ });
+ expect(edge.allowedScrollTypes.size).toBe(0);
+ detachers.push(host.attach(box, edge));
+ expect(added.mock.calls.map(call => call[0])).not.toContain('wheel');
+ expect(wheel(box, {dx: 30, time: 0}).defaultPrevented).toBe(false);
+ });
+
+ it('takes a trackpad scroll along its axis on a pan that allows continuous scrolling: it begins past 10 px, follows the content, and ends 220 ms after the last wheel, a slow swipe pausing between its wheels', () => {
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(box, 'addEventListener');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ expect(
+ (added.mock.calls as unknown[][]).filter(call => call[0] === 'wheel'),
+ ).toEqual([['wheel', expect.any(Function), {passive: false}]]);
+ const events = [0, 16, 32, 48].map(time =>
+ wheel(box, {trackpad: true, dx: 6.5, dy: 0.5, time}),
+ );
+ expect(events.every(event => event.defaultPrevented)).toBe(true);
+ expect(states[0]).toBe('began');
+ // The content moves the way the fingers do: a scroll right drags it left.
+ expect(pan.translation().x).toBeLessThan(0);
+ expect(states).not.toContain('ended');
+ clock.runDue(48 + 219);
+ expect(states).not.toContain('ended');
+ clock.runDue(48 + 220);
+ expect(states).toContain('ended');
+ });
+
+ it("releases a trackpad's scroll with the fingers' speed where they lift into momentum, and still where they stop (spec:AST-094 FR43, DEC-24)", () => {
+ const {smooth, stopped} = mount(
+ '<div id="smooth"></div><div id="stopped"></div>',
+ );
+ const released: Record<string, {velocity: number; scroll: number}> = {};
+ for (const [key, element] of [
+ ['smooth', smooth],
+ ['stopped', stopped],
+ ] as const) {
+ const pan = new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedScrollTypes: ['continuous'],
+ });
+ pan.addTransitionListener((current, _from, to) => {
+ if (to === 'ended') {
+ released[key] = {
+ velocity: current.velocity().y,
+ scroll: current.scrollVelocity().y,
+ };
+ }
+ });
+ detachers.push(host.attach(element, pan));
+ }
+ // A trackpad's fling: steady deltas, then shrinking ones as the fingers
+ // lift into momentum. It releases at the lift with the fingers' speed.
+ let time = 500;
+ for (const dy of [8, 8, 8, 8, 7.6, 7.2, 6.8, 6.4, 6, 5.6]) {
+ wheel(smooth, {trackpad: true, dy, time});
+ time += 16;
+ }
+ clock.runDue(time + 200);
+ expect(Math.abs(released.smooth.velocity)).toBeGreaterThan(0);
+ expect(Math.abs(released.smooth.scroll)).toBeGreaterThan(0);
+ // Fingers that stop: the scroll ends 180 ms after its last wheel, still.
+ for (const at of [1500, 1516, 1532, 1548]) {
+ wheel(stopped, {trackpad: true, dy: 8, time: at});
+ }
+ clock.runDue(1548 + 180);
+ expect(Math.abs(released.stopped.velocity)).toBe(0);
+ expect(Math.abs(released.stopped.scroll)).toBe(0);
+ });
+
+ it("releases a trackpad scroll whose fingers stop still whatever the host's clock reads: the release is stamped on the wheels' own times", () => {
+ // The host schedules a gesture's end on its clock, while the arena reads
+ // the wheels' own timestamps, which need not share the clock's base: a
+ // page whose clock a test fakes, as a sheet's tests do.
+ const {pad} = mount('<div id="pad"></div>');
+ const released: number[] = [];
+ const pan = new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedScrollTypes: ['continuous'],
+ });
+ pan.addTransitionListener((current, _from, to) => {
+ if (to === 'ended') {
+ released.push(current.velocity().y);
+ }
+ });
+ detachers.push(host.attach(pad, pan));
+ clock.time = 0;
+ for (const time of [1_000_000, 1_000_016, 1_000_032, 1_000_048]) {
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ clientX: 20,
+ clientY: 20,
+ deltaY: 8,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ // A trackpad's signature: a legacy delta three times the delta.
+ Object.defineProperty(event, 'wheelDeltaX', {value: 0});
+ Object.defineProperty(event, 'wheelDeltaY', {value: -24});
+ pad.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(true);
+ }
+ clock.runDue(200);
+ expect(released.map(Math.abs)).toEqual([0]);
+ });
+
+ it('starts a new wheel gesture after a quiet gap even when the end timer has not run yet (a blocked main thread)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ for (const time of [0, 16, 32]) {
+ wheel(box, {trackpad: true, dx: 8, time});
+ }
+ // The timer that would end it has not run: the next wheel, 250 ms later
+ // (past a swipe's 220 ms), ends it and begins another.
+ for (const time of [282, 298, 314]) {
+ wheel(box, {trackpad: true, dx: 8, time});
+ }
+ expect(states.filter(state => state === 'began')).toHaveLength(2);
+ expect(states).toContain('ended');
+ });
+
+ it('leaves a wheel across its axis to the page', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ const events = [0, 16, 32].map(time =>
+ wheel(box, {trackpad: true, dy: 12, time}),
+ );
+ expect(events.some(event => event.defaultPrevented)).toBe(false);
+ expect(states).toEqual([]);
+ });
+
+ it('leaves a wheel to a scroller under the pointer that can still scroll that way, for the whole wheel gesture, and takes the next one once it is at its edge', () => {
+ const {box, list} = mount(
+ '<div id="box"><div id="list"><div id="row">row</div></div></div>',
+ );
+ scrollableX(list, {scrollLeft: 0, scrollWidth: 600, clientWidth: 200});
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ const native = [0, 16, 32].map(time =>
+ wheel(document.getElementById('row') as HTMLElement, {
+ trackpad: true,
+ dx: 8,
+ time,
+ }),
+ );
+ // Decided once, at the gesture's first wheel: the list scrolls.
+ Object.defineProperty(list, 'scrollLeft', {configurable: true, value: 400});
+ native.push(
+ wheel(document.getElementById('row') as HTMLElement, {
+ trackpad: true,
+ dx: 8,
+ time: 48,
+ }),
+ );
+ expect(native.some(event => event.defaultPrevented)).toBe(false);
+ expect(states).toEqual([]);
+ clock.runDue(48 + 100);
+ const taken = [500, 516, 532].map(time =>
+ wheel(document.getElementById('row') as HTMLElement, {
+ trackpad: true,
+ dx: 8,
+ time,
+ }),
+ );
+ expect(taken.every(event => event.defaultPrevented)).toBe(true);
+ expect(states[0]).toBe('began');
+ });
+
+ it("tells a mouse wheel's notches from a trackpad: a pan leaves lines and whole notches to the page and takes a trackpad's scroll (spec:AST-094 FR43, DEC-24)", () => {
+ const {smooth} = mount('<div id="smooth"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(smooth, pan));
+ // Lines (Firefox's mouse wheel), and a whole notch in pixels (Chromium's).
+ expect(wheel(smooth, {dy: 3, mode: 1, time: 0}).defaultPrevented).toBe(
+ false,
+ );
+ clock.runDue(200);
+ expect(wheel(smooth, {dy: 100, time: 300}).defaultPrevented).toBe(false);
+ clock.runDue(500);
+ expect(states).toEqual([]);
+ expect(
+ wheel(smooth, {trackpad: true, dy: 12, time: 600}).defaultPrevented,
+ ).toBe(true);
+ expect(states[0]).toBe('began');
+ });
+
+ it('takes a ctrl-wheel on a pinch, a trackpad pinch or ctrl and a mouse wheel: the scale follows exp(-deltaY / 100), the page does not zoom, and it ends 100 ms after the last wheel', () => {
+ const {photo} = mount('<div id="photo"></div>');
+ const pinch = new PinchGestureRecognizer();
+ const states = statesOf(pinch);
+ detachers.push(host.attach(photo, pinch));
+ const events = [0, 16, 32, 48, 64].map(time =>
+ wheel(photo, {dy: -10, ctrl: true, time}),
+ );
+ expect(events.every(event => event.defaultPrevented)).toBe(true);
+ expect(states[0]).toBe('began');
+ expect(pinch.scale).toBeGreaterThan(1);
+ expect(pinch.scale).toBeLessThanOrEqual(Math.exp(0.5) + 1e-6);
+ clock.runDue(64 + 100);
+ expect(states).toContain('ended');
+ });
+
+ it("keeps a trackpad stream a scroller took for FR43's pause bound, not 100 ms: a slow drag that rests 130 ms at the list's end stays the list's, and the pan takes only the next stream (spec:AST-094 FR43)", () => {
+ const {sheet, list, row} = mount(
+ '<div id="sheet"><div id="list"><div id="row"></div></div></div>',
+ );
+ const pan = new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(sheet, pan));
+ scrollableY(list, {scrollTop: 0, scrollHeight: 400, clientHeight: 100});
+ const at = (time: number) => {
+ clock.runDue(time);
+ return wheel(row, {trackpad: true, dy: 8, time});
+ };
+ // Three wheels the list scrolls.
+ expect([0, 16, 32].map(at).some(event => event.defaultPrevented)).toBe(
+ false,
+ );
+ // The list reaches its end; the fingers rest 130 ms and carry on: still
+ // the list's stream, so the pan never takes it midway.
+ Object.defineProperty(list, 'scrollTop', {configurable: true, value: 300});
+ expect([162, 178, 194].map(at).some(event => event.defaultPrevented)).toBe(
+ false,
+ );
+ expect(states).toEqual([]);
+ // Past the 180 ms bound the stream has ended; the next one is the pan's.
+ expect([600, 616].map(at).every(event => event.defaultPrevented)).toBe(
+ true,
+ );
+ expect(states[0]).toBe('began');
+ });
+
+ it('keeps a ctrl-wheel pinch out of the trackpad splitter: a pinch that slows and reverses, or rests 60 ms, stays one gesture, and ends 100 ms after its last wheel (spec:AST-094 FR43)', () => {
+ const {photo} = mount('<div id="photo"></div>');
+ const pinch = new PinchGestureRecognizer();
+ const states = statesOf(pinch);
+ detachers.push(host.attach(photo, pinch));
+ const at = (time: number, dy: number) => {
+ clock.runDue(time);
+ return wheel(photo, {dy, ctrl: true, time});
+ };
+ const deltas = [-3, -4, -5, -4, -3, -2.5, -2, -1.5, 1, 2, 3, 4];
+ for (const [i, dy] of deltas.entries()) {
+ expect(at(i * 16, dy).defaultPrevented).toBe(true);
+ }
+ expect(states.filter(state => state === 'began')).toHaveLength(1);
+ expect(states).not.toContain('ended');
+ // One pinch throughout: still magnified after the reversal, where a
+ // second pinch starting from 1 would read below it.
+ expect(pinch.scale).toBeGreaterThan(1);
+ clock.runDue(11 * 16 + 99);
+ expect(states).not.toContain('ended');
+ clock.runDue(11 * 16 + 100);
+ expect(states.filter(state => state === 'ended')).toHaveLength(1);
+ // Slowing, then resting 60 ms, is still one pinch.
+ states.length = 0;
+ for (const [i, dy] of [-5, -4, -3, -2.5, -2].entries()) {
+ at(1000 + i * 16, dy);
+ }
+ at(1000 + 4 * 16 + 60, -2);
+ expect(states.filter(state => state === 'began')).toHaveLength(1);
+ expect(states).not.toContain('ended');
+ });
+
+ it("keeps the page's text selection when a wheel pan claims, as a scroll does", () => {
+ const {box} = mount('<div id="box">Some selected text</div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ detachers.push(host.attach(box, pan));
+ const selection = window.getSelection() as Selection;
+ selection.removeAllRanges();
+ const range = document.createRange();
+ range.selectNodeContents(box);
+ selection.addRange(range);
+ for (const time of [0, 16, 32, 48]) {
+ wheel(box, {trackpad: true, dx: 8, time});
+ }
+ expect(pan.state).not.toBe('possible');
+ expect(selection.rangeCount).toBe(1);
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ });
+
+ it('keeps a watcher pan off the wheel: its element gets no wheel listener, and the page keeps the wheel (spec:AST-094 FR20, DEC-7)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(box, 'addEventListener');
+ const watcher = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ claimsTouches: false,
+ });
+ const states = statesOf(watcher);
+ detachers.push(host.attach(box, watcher));
+ expect(
+ (added.mock.calls as unknown[][]).filter(call => call[0] === 'wheel'),
+ ).toEqual([]);
+ expect(wheel(box, {trackpad: true, dx: 30, time: 0}).defaultPrevented).toBe(
+ false,
+ );
+ expect(states).toEqual([]);
+ });
+
+ it('leaves a first wheel already prevented, or one that cannot be cancelled, to the page for its whole gesture', () => {
+ const {box, inner} = mount('<div id="box"><div id="inner"></div></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ // An app's own handler below the pan prevented the first wheel.
+ inner.addEventListener('wheel', event => event.preventDefault(), {
+ once: true,
+ });
+ wheel(inner, {trackpad: true, dx: 30, time: 0});
+ expect(
+ wheel(inner, {trackpad: true, dx: 30, time: 16}).defaultPrevented,
+ ).toBe(false);
+ expect(states).toEqual([]);
+ clock.runDue(400);
+ // A wheel the browser lets no one cancel.
+ const uncancelable = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: false,
+ composed: true,
+ clientX: 20,
+ clientY: 20,
+ deltaX: 30,
+ });
+ Object.defineProperty(uncancelable, 'timeStamp', {value: 500});
+ Object.defineProperty(uncancelable, 'wheelDeltaX', {value: -90});
+ Object.defineProperty(uncancelable, 'wheelDeltaY', {value: 0});
+ clock.time = 500;
+ inner.dispatchEvent(uncancelable);
+ expect(
+ wheel(inner, {trackpad: true, dx: 30, time: 516}).defaultPrevented,
+ ).toBe(false);
+ expect(states).toEqual([]);
+ });
+
+ it("stamps a trackpad gesture's release no later than the press that ends it: a long press right after keeps its own clock (spec:AST-094 FR16)", () => {
+ const {box, other} = mount('<div id="box"></div><div id="other"></div>');
+ detachers.push(
+ host.attach(
+ box,
+ new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedScrollTypes: ['continuous'],
+ }),
+ ),
+ );
+ const press = new LongPressGestureRecognizer({name: 'press'});
+ const began: number[] = [];
+ press.addListener(recognizer => {
+ if (recognizer.state === 'began') {
+ began.push(clock.time);
+ }
+ });
+ detachers.push(host.attach(other, press));
+ // A trackpad's scroll past the pan's 10 px start.
+ expect(wheel(box, {trackpad: true, dy: 12, time: 0}).defaultPrevented).toBe(
+ true,
+ );
+ // A pen comes down 20 ms later, ending the wheel gesture.
+ clock.time = 20;
+ const down = new PointerEvent('pointerdown', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 5,
+ pointerType: 'pen',
+ clientX: 5,
+ clientY: 5,
+ buttons: 1,
+ });
+ Object.defineProperty(down, 'timeStamp', {value: 20});
+ other.dispatchEvent(down);
+ clock.runDue(519);
+ expect(began).toEqual([]);
+ clock.runDue(521);
+ // 500 ms after the pen landed, not after the scroll's release time.
+ expect(began).toHaveLength(1);
+ });
+
+ it.each(['detached', 'disabled'] as const)(
+ 'stamps the release of a trackpad pan %s mid-swipe at its last wheel: a long press right after keeps its own clock (spec:AST-094 FR16)',
+ how => {
+ const {box, other} = mount('<div id="box"></div><div id="other"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'vertical',
+ allowedScrollTypes: ['continuous'],
+ });
+ const detach = host.attach(box, pan);
+ const press = new LongPressGestureRecognizer({name: 'press'});
+ const began: number[] = [];
+ press.addListener(recognizer => {
+ if (recognizer.state === 'began') {
+ began.push(clock.time);
+ }
+ });
+ detachers.push(host.attach(other, press));
+ expect(
+ wheel(box, {trackpad: true, dy: 12, time: 0}).defaultPrevented,
+ ).toBe(true);
+ // 10 ms later the pan leaves mid-swipe, and the fingers' next wheel
+ // lands at 16 ms, the page's now.
+ clock.runDue(10);
+ if (how === 'detached') {
+ detach();
+ } else {
+ pan.setEnabled(false);
+ detachers.push(detach);
+ }
+ clock.runDue(16);
+ expect(
+ wheel(box, {trackpad: true, dy: 12, time: 16}).defaultPrevented,
+ ).toBe(false);
+ // A pen comes down at 20 ms.
+ clock.runDue(20);
+ const down = new PointerEvent('pointerdown', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 6,
+ pointerType: 'pen',
+ clientX: 5,
+ clientY: 5,
+ buttons: 1,
+ });
+ Object.defineProperty(down, 'timeStamp', {value: 20});
+ other.dispatchEvent(down);
+ clock.runDue(519);
+ expect(began).toEqual([]);
+ clock.runDue(521);
+ // 500 ms after the pen landed, not after the scroll's end window.
+ expect(began).toHaveLength(1);
+ },
+ );
+
+ it('removes the wheel listener when the pan is disabled or detached', () => {
+ const {box} = mount('<div id="box"></div>');
+ const removed = vi.spyOn(box, 'removeEventListener');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const detach = host.attach(box, pan);
+ pan.isEnabled = false;
+ host.update(box);
+ expect(removed.mock.calls.map(call => call[0])).toContain('wheel');
+ expect(wheel(box, {dx: 30, time: 0}).defaultPrevented).toBe(false);
+ detach();
+ });
+});
+
+describe("a mouse's wheel and a trackpad's lift (spec:AST-094 FR43)", () => {
+ /** A pan that takes only a trackpad's scroll, horizontally. */
+ function trackpadPan(box: HTMLElement): PanGestureRecognizer {
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedPointerTypes: [],
+ allowedScrollTypes: ['continuous'],
+ });
+ detachers.push(host.attach(box, pan));
+ return pan;
+ }
+
+ for (const [name, init] of [
+ [
+ 'deltas a hair off whole pixels, as a mouse wheel on Windows sends',
+ {dx: 100.0000015},
+ ],
+ [
+ 'a legacy wheelDelta that is not three times the delta',
+ {dx: 10, legacy: {x: -120, y: 0}},
+ ],
+ [
+ 'a 120 legacy tick over a 40 px delta, a notch',
+ {dx: 40, legacy: {x: -120, y: 0}},
+ ],
+ ] as const) {
+ it(`counts ${name} as a mouse's wheel: a pan that takes only a trackpad's scroll leaves it to the page`, () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = trackpadPan(box);
+ const states = statesOf(pan);
+ for (let step = 0; step < 3; step++) {
+ const event = wheel(box, {...init, time: step * 16});
+ expect(event.defaultPrevented).toBe(false);
+ }
+ expect(states).toEqual([]);
+ });
+ }
+
+ it("counts a pixel scroll that carries no legacy wheelDelta, as Firefox sends, as a mouse's wheel: a pan that takes only a trackpad's scroll leaves it to the page", () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = trackpadPan(box);
+ const states = statesOf(pan);
+ for (let step = 0; step < 3; step++) {
+ const event = wheel(box, {dx: 7, time: step * 16});
+ expect(event.defaultPrevented).toBe(false);
+ }
+ expect(states).toEqual([]);
+ });
+
+ it("counts a scroll with Shift held, as Shift+wheel sends, as a mouse's wheel even with a trackpad's deltas: a pan that takes only a trackpad's scroll leaves it to the page (spec:AST-094 FR43)", () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = trackpadPan(box);
+ const states = statesOf(pan);
+ for (let step = 0; step < 3; step++) {
+ const event = wheel(box, {
+ trackpad: true,
+ shift: true,
+ dx: 7,
+ time: step * 16,
+ });
+ expect(event.defaultPrevented).toBe(false);
+ }
+ expect(states).toEqual([]);
+ });
+
+ it("takes a trackpad's precise deltas, whose legacy wheelDelta is three times each", () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = trackpadPan(box);
+ const states = statesOf(pan);
+ for (let step = 0; step < 3; step++) {
+ wheel(box, {dx: 7, legacy: {x: -21, y: 0}, time: step * 16});
+ }
+ expect(states[0]).toBe('began');
+ });
+});
+
+describe("a trackpad scroll through the splitter's undecided stretch (spec:AST-094 FR43)", () => {
+ /** A horizontal pan that takes only a trackpad's scroll, and what it did. */
+ function followed() {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedPointerTypes: [],
+ allowedScrollTypes: ['continuous'],
+ });
+ const seen: {state: string; x: number; velocity: number}[] = [];
+ pan.addTransitionListener((recognizer, _from, to) => {
+ seen.push({
+ state: to,
+ x: recognizer.translation().x,
+ velocity: recognizer.velocity().x,
+ });
+ });
+ detachers.push(host.attach(box, pan));
+ return {box, seen};
+ }
+
+ /** Each wheel 16 ms apart from 0; returns the time after the last. */
+ function stream(box: HTMLElement, deltas: number[]): number {
+ let time = 0;
+ for (const dx of deltas) {
+ wheel(box, {trackpad: true, dx, time});
+ time += 16;
+ }
+ return time;
+ }
+
+ it("keeps a trackpad pan moving at the fingers' speed while the splitter is undecided, and lets go at the lift still moving at that speed: no stall", () => {
+ const {box, seen} = followed();
+ // Four steady deltas, then four shrinking ones (the lift is read at the
+ // fourth), then momentum.
+ const end = stream(box, [10, 10, 10, 10, 9.5, 9, 8.5, 8, 7.5, 7, 6.5, 6]);
+ clock.runDue(end + 500);
+ const changed = seen.filter(entry => entry.state === 'changed');
+ // The fingers' travel at their last move is -30 (40 px past the 10 px
+ // hysteresis); through the shrinking deltas the pan moves on 10 px a
+ // wheel at their speed.
+ expect(changed.map(entry => entry.x).slice(-4)).toEqual([
+ -40, -50, -60, -70,
+ ]);
+ const ended = seen.filter(entry => entry.state === 'ended');
+ expect(ended).toHaveLength(1);
+ expect(ended[0].x).toBeCloseTo(-70, 6);
+ // Released at the fingers' speed, 10 px a 16 ms wheel.
+ expect(ended[0].velocity).toBeCloseTo(-625, -1);
+ // The momentum after the lift moves nothing.
+ expect(
+ seen.slice(seen.indexOf(ended[0]) + 1).map(entry => entry.state),
+ ).toEqual(['possible']);
+ });
+
+ it.each([
+ ['a blur', 'blur', false],
+ ['a hidden page', 'hidden', false],
+ ['a blur, under a coarse primary pointer', 'blur', true],
+ ] as const)(
+ 'keeps a ctrl-wheel pinch through %s: the pinch keeps its stream, and the page never zooms',
+ (_name, how, isCoarse) => {
+ const {photo} = mount('<div id="photo"></div>');
+ const subject = isCoarse
+ ? new GestureHost(document, {clock, isPrimaryPointerCoarse: () => true})
+ : host;
+ const pinch = new PinchGestureRecognizer();
+ const states = statesOf(pinch);
+ detachers.push(subject.attach(photo, pinch));
+ for (const time of [0, 16, 32]) {
+ expect(wheel(photo, {dy: -10, ctrl: true, time}).defaultPrevented).toBe(
+ true,
+ );
+ }
+ expect(states[0]).toBe('began');
+ clock.runDue(40);
+ if (how === 'blur') {
+ window.dispatchEvent(new Event('blur'));
+ } else {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'hidden',
+ });
+ detachers.push(() => {
+ delete (document as {visibilityState?: unknown}).visibilityState;
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ }
+ expect(states).not.toContain('cancelled');
+ const scale = pinch.scale;
+ for (const time of [48, 64, 80]) {
+ expect(wheel(photo, {dy: -10, ctrl: true, time}).defaultPrevented).toBe(
+ true,
+ );
+ }
+ expect(pinch.scale).toBeGreaterThan(scale);
+ clock.runDue(80 + 100);
+ expect(states).toContain('ended');
+ expect(states).not.toContain('cancelled');
+ },
+ );
+
+ it('cancels nothing when focus moves between elements mid-swipe: only the window’s own blur ends a trackpad pan', () => {
+ const {box, field} = mount(
+ '<div id="box"></div><input id="field" type="text" />',
+ );
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ for (const time of [0, 16, 32]) {
+ wheel(box, {trackpad: true, dx: 10, time});
+ }
+ expect(states.at(-1)).toBe('changed');
+ field.dispatchEvent(new FocusEvent('focus'));
+ field.dispatchEvent(new FocusEvent('blur'));
+ expect(states).not.toContain('cancelled');
+ expect(
+ wheel(box, {trackpad: true, dx: 10, time: 48}).defaultPrevented,
+ ).toBe(true);
+ expect(states.at(-1)).toBe('changed');
+ });
+
+ it('keeps the momentum of a pan its lift released latched through a blur: the blur cancels nothing, and the momentum still moves no surface (spec:AST-094 FR43)', () => {
+ const {box, seen} = followed();
+ const deltas = [10, 10, 10, 10, 9.5, 9, 8.5, 8, 7.5, 7, 6.5, 6];
+ deltas.forEach((dx, i) => wheel(box, {trackpad: true, dx, time: i * 16}));
+ expect(seen.some(entry => entry.state === 'ended')).toBe(true);
+ window.dispatchEvent(new Event('blur'));
+ expect(seen.map(entry => entry.state)).not.toContain('cancelled');
+ expect(
+ wheel(box, {trackpad: true, dx: 5.5, time: 12 * 16}).defaultPrevented,
+ ).toBe(true);
+ });
+
+ it('keeps the momentum after the lift prevented, latched to the pan it released: momentum never moves a surface or continues a gesture (spec:AST-094 FR43)', () => {
+ const {box, seen} = followed();
+ // Four steady wheels, then sixteen shrinking ones 16 ms apart: the lift
+ // is read at the fourth shrinking wheel (112 ms), and twelve momentum
+ // wheels follow it.
+ const deltas = [
+ 10, 10, 10, 10, 9.5, 9, 8.5, 8, 7.5, 7, 6.5, 6, 5.5, 5, 4.5, 4, 3.5, 3,
+ 2.5, 2,
+ ];
+ const events = deltas.map((dx, i) =>
+ wheel(box, {trackpad: true, dx, time: i * 16}),
+ );
+ const lift = seen.findIndex(entry => entry.state === 'ended');
+ expect(lift).toBeGreaterThan(-1);
+ // Every wheel was the pan's: none after the lift reached the page.
+ expect(events.slice(8).map(event => event.defaultPrevented)).toEqual(
+ Array.from({length: 12}, () => true),
+ );
+ expect(events.every(event => event.defaultPrevented)).toBe(true);
+ // The momentum moved nothing and began nothing.
+ expect(seen.slice(lift + 1).map(entry => entry.state)).toEqual([
+ 'possible',
+ ]);
+ // The fingers' next swipe, past the momentum's 50 ms pause, is a new
+ // gesture the pan takes.
+ const next = [0, 16, 32].map(t =>
+ wheel(box, {trackpad: true, dx: 10, time: 20 * 16 + 60 + t}),
+ );
+ expect(next.every(event => event.defaultPrevented)).toBe(true);
+ expect(seen.filter(entry => entry.state === 'began')).toHaveLength(2);
+ });
+
+ it("lets the momentum's latch go with the stream's end window: a wheel after it is decided afresh (spec:AST-094 FR43)", () => {
+ const {box, seen} = followed();
+ const deltas = [10, 10, 10, 10, 9.5, 9, 8.5, 8, 7.5, 7, 6.5, 6];
+ for (const [i, dx] of deltas.entries()) {
+ expect(
+ wheel(box, {trackpad: true, dx, time: i * 16}).defaultPrevented,
+ ).toBe(true);
+ }
+ expect(seen.some(entry => entry.state === 'ended')).toBe(true);
+ const outside = document.createElement('div');
+ document.body.append(outside);
+ try {
+ // Within the window the momentum is still the pan's.
+ clock.runDue(11 * 16 + 219);
+ expect(
+ wheel(outside, {trackpad: true, dx: 5.5, time: 11 * 16 + 30})
+ .defaultPrevented,
+ ).toBe(true);
+ // 220 ms after its last wheel the stream has ended: the next wheel
+ // there is the page's.
+ clock.runDue(11 * 16 + 30 + 220);
+ expect(
+ wheel(outside, {trackpad: true, dx: 5, time: 11 * 16 + 260})
+ .defaultPrevented,
+ ).toBe(false);
+ } finally {
+ outside.remove();
+ }
+ });
+
+ it('lets the momentum’s latch go when the pan it released is detached: the next wheels are the page’s (spec:AST-094 FR43, FR24)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ allowedScrollTypes: ['continuous'],
+ });
+ const detach = host.attach(box, pan);
+ const deltas = [10, 10, 10, 10, 9.5, 9, 8.5, 8, 7.5, 7, 6.5, 6];
+ const events = deltas.map((dx, i) =>
+ wheel(box, {trackpad: true, dx, time: i * 16}),
+ );
+ expect(events.every(event => event.defaultPrevented)).toBe(true);
+ detach();
+ const outside = document.createElement('div');
+ document.body.append(outside);
+ try {
+ expect(
+ wheel(outside, {trackpad: true, dx: 5.5, time: 12 * 16})
+ .defaultPrevented,
+ ).toBe(false);
+ } finally {
+ outside.remove();
+ }
+ });
+
+ it('absorbs what the undecided stretch showed when the fingers carry on: never a step back, and no extra travel', () => {
+ const {box, seen} = followed();
+ const deltas = [10, 10, 10, 10, 9.5, 9, 10, 10, 10, 10, 10, 10];
+ const end = stream(box, deltas);
+ clock.runDue(end + 500);
+ const moves = seen.filter(
+ entry => entry.state === 'changed' || entry.state === 'ended',
+ );
+ for (const [i, entry] of moves.entries()) {
+ if (i > 0) {
+ expect(entry.x).toBeLessThanOrEqual(moves[i - 1].x);
+ }
+ }
+ // The fingers' whole travel, past the 10 px hysteresis.
+ const travel = deltas.reduce((sum, delta) => sum + delta, 0) - 10;
+ expect(moves.at(-1)?.x).toBeCloseTo(-travel, 6);
+ });
+
+ it("never moves the pan past what the fingers' last speed projects through a long undecided stretch", () => {
+ const {box, seen} = followed();
+ // Deltas that shrink too slowly to read a lift for a while.
+ const shrinking = [9.9, 9.8, 9.7, 9.6, 9.5, 9.4];
+ stream(box, [10, 10, 10, 10, ...shrinking]);
+ const changed = seen.filter(entry => entry.state === 'changed');
+ expect(changed.map(entry => entry.x).slice(-shrinking.length)).toEqual(
+ shrinking.map((_, i) => -30 - 10 * (i + 1)),
+ );
+ });
+});
+
+describe("the splitter's gestures on timed trackpad streams (spec:AST-094 FR43, DEC-24)", () => {
+ /** A pan that takes a trackpad's scroll, and how many gestures it began. */
+ function counted(direction: 'horizontal' | 'vertical') {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({
+ direction,
+ allowedPointerTypes: [],
+ allowedScrollTypes: ['continuous'],
+ });
+ const states = statesOf(pan);
+ detachers.push(host.attach(box, pan));
+ return {box, began: () => states.filter(state => state === 'began').length};
+ }
+
+ /** Fingers, then a shrinking run whose fourth delta reads the lift. */
+ const SWIPE = [12, 12, 12, 12, 11, 10, 9, 8];
+
+ it("counts ten swipes that each start in the last one's momentum as ten gestures", () => {
+ const {box, began} = counted('horizontal');
+ let time = 0;
+ for (let swipe = 0; swipe < 10; swipe++) {
+ // The next swipe's first delta rises against the decay.
+ for (const dx of [...SWIPE, 7, 6, 5]) {
+ clock.runDue(time);
+ wheel(box, {trackpad: true, dx, time});
+ time += 16;
+ }
+ }
+ clock.runDue(time + 500);
+ expect(began()).toBe(10);
+ });
+
+ it('counts ten swipes whose momentum runs out as ten gestures', () => {
+ const {box, began} = counted('horizontal');
+ let time = 0;
+ for (let swipe = 0; swipe < 10; swipe++) {
+ for (const dx of [...SWIPE, 7, 6, 5, 4, 3, 2, 1]) {
+ clock.runDue(time);
+ wheel(box, {trackpad: true, dx, time});
+ time += 16;
+ }
+ time += 400;
+ }
+ clock.runDue(time + 500);
+ expect(began()).toBe(10);
+ });
+
+ it('counts a slow drag with 150 ms pauses as one gesture', () => {
+ const {box, began} = counted('vertical');
+ let time = 0;
+ for (let stretch = 0; stretch < 6; stretch++) {
+ for (let step = 0; step < 5; step++) {
+ clock.runDue(time);
+ wheel(box, {trackpad: true, dy: 4, time});
+ time += 16;
+ }
+ // A 150 ms pause from the stretch's last wheel to the next one's first.
+ time += 150 - 16;
+ }
+ clock.runDue(time + 500);
+ expect(began()).toBe(1);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/wheelSegmenter.test.ts b/packages/core/src/gestures/__tests__/wheelSegmenter.test.ts
new file mode 100644
index 0000000000..340381ec32
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/wheelSegmenter.test.ts
@@ -0,0 +1,89 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file wheelSegmenter.test.ts
+ * @input A WheelSegmenter fed deltas along one axis with their times
+ * @output Tests for how a wheel stream splits into gestures and where a
+ * trackpad's fingers lift (spec:AST-094 FR43)
+ * @position Unit tests of wheelSegmenter.ts
+ */
+
+import {describe, expect, it} from 'vitest';
+import {WheelSegmenter} from '../wheelSegmenter';
+
+/** Push `deltas` 16 ms apart from `from`, with a 180 ms finger pause. */
+function feed(segmenter: WheelSegmenter, deltas: number[], from = 0) {
+ return deltas.map((delta, i) => segmenter.push(from + i * 16, delta, 180));
+}
+
+describe('WheelSegmenter (spec:AST-094 FR43)', () => {
+ it('starts a gesture at the first wheel, and again after a finger pause of idleMs', () => {
+ const segmenter = new WheelSegmenter();
+ expect(segmenter.push(0, 10, 180).boundary).toBe('first');
+ expect(segmenter.push(16, 10, 180).boundary).toBeNull();
+ expect(segmenter.push(195, 10, 180).boundary).toBeNull();
+ const after = segmenter.push(375, 10, 180);
+ expect(after.boundary).toBe('idle');
+ expect(after.gesture).toBe(2);
+ });
+
+ it('reads the lift where a run of shrinking deltas has lost a fifth of its size, and marks the shrinking ones before it as held', () => {
+ const seen = feed(
+ new WheelSegmenter(),
+ [10, 10, 10, 10, 9.5, 9, 8.5, 8, 7.5],
+ );
+ expect(seen.map(segment => segment.liftNow)).toEqual([
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ ]);
+ expect(seen.map(segment => segment.decaying)).toEqual([
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false,
+ ]);
+ expect(seen[7].phase).toBe('momentum');
+ expect(seen[8].boundary).toBeNull();
+ });
+
+ it('keeps a slow finger, whose deltas shrink and grow again, in its finger phase', () => {
+ const seen = feed(new WheelSegmenter(), [10, 10, 10, 9, 8, 9, 10, 9, 8, 9]);
+ expect(seen.some(segment => segment.liftNow)).toBe(false);
+ expect(seen.every(segment => segment.phase === 'finger')).toBe(true);
+ });
+
+ for (const [name, next, at] of [
+ ['reversal', -5, 16],
+ ['gap', 7, 50],
+ ['jump', 20, 16],
+ ] as const) {
+ it(`starts a new gesture in momentum at a ${name}: momentum never ${name === 'gap' ? 'pauses' : name === 'jump' ? 'grows' : 'reverses'}`, () => {
+ const segmenter = new WheelSegmenter();
+ const seen = feed(segmenter, [10, 10, 10, 10, 9.5, 9, 8.5, 8]);
+ expect(seen[7].liftNow).toBe(true);
+ const segment = segmenter.push(7 * 16 + at, next, 180);
+ expect(segment.boundary).toBe(name);
+ expect(segment.phase).toBe('finger');
+ expect(segment.gesture).toBe(2);
+ });
+ }
+
+ it('starts a gesture at the next wheel once the last one ended on its own', () => {
+ const segmenter = new WheelSegmenter();
+ feed(segmenter, [10, 10]);
+ segmenter.end();
+ expect(segmenter.push(40, 10, 180).boundary).toBe('idle');
+ });
+});
diff --git a/packages/core/src/gestures/nativeScroll.ts b/packages/core/src/gestures/nativeScroll.ts
index 0ff1c5440b..bea018ef49 100644
--- a/packages/core/src/gestures/nativeScroll.ts
+++ b/packages/core/src/gestures/nativeScroll.ts
@@ -4,7 +4,8 @@
* @file nativeScroll.ts
* @input An element a touch landed on
* @output Exports createNativeScrollProbe (the NativeScrollProbe a host gives
- * each touch) and parseTouchAction
+ * each touch, and each wheel gesture without the touch-action narrowing)
+ * and parseTouchAction
* @position DOM half of the scroll coordination in packages/core/src/gestures
*
* Answers one question for a recognizer without letting it touch the DOM:
@@ -82,7 +83,7 @@ interface Chain {
readonly allowsPan: boolean;
}
-function buildChain(target: Element): Chain {
+function buildChain(target: Element, readsTouchAction: boolean): Chain {
const doc = target.ownerDocument;
const view = doc.defaultView;
if (view == null) {
@@ -103,9 +104,11 @@ function buildChain(target: Element): Chain {
continue;
}
const style = view.getComputedStyle(node);
- const pans = parseTouchAction(style.touchAction || 'auto');
- allowX &&= pans.x;
- allowY &&= pans.y;
+ if (readsTouchAction) {
+ const pans = parseTouchAction(style.touchAction || 'auto');
+ allowX &&= pans.x;
+ allowY &&= pans.y;
+ }
const isRoot = node === root || node === doc.documentElement;
if (isRoot) {
reachedRoot = true;
@@ -196,7 +199,10 @@ function canMoveY(element: Element, dy: number): boolean {
element.scrollHeight - element.clientHeight - EDGE_TOLERANCE + 0.5;
}
-function canMoveX(entry: ChainEntry, dx: number): boolean {
+function canMoveX(
+ entry: Pick<ChainEntry, 'element' | 'isRtl'>,
+ dx: number,
+): boolean {
const {element} = entry;
const overflow = element.scrollWidth - element.clientWidth;
if (overflow <= EDGE_TOLERANCE) {
@@ -210,13 +216,47 @@ function canMoveX(entry: ChainEntry, dx: number): boolean {
: element.scrollLeft < max - EDGE_TOLERANCE + 0.5;
}
-/** A probe of the native scrollers under `target`. */
-export function createNativeScrollProbe(target: unknown): NativeScrollProbe {
+/**
+ * Whether `element` itself scrolls natively now for a finger moving by
+ * (dx, dy). It uses the probe's own test of each scroller: overflow that
+ * scrolls on that axis, and room past the edge tolerance. The position must
+ * also be short of the end it moves toward, a right-to-left range included.
+ * A wheel moves the content the other way, so pass its deltas negated.
+ */
+export function canElementScroll(
+ element: Element,
+ dx: number,
+ dy: number,
+): boolean {
+ const view = element.ownerDocument.defaultView;
+ if (view == null) {
+ return false;
+ }
+ const style = view.getComputedStyle(element);
+ if (dy !== 0 && SCROLLABLE.has(style.overflowY) && canMoveY(element, dy)) {
+ return true;
+ }
+ return (
+ dx !== 0 &&
+ SCROLLABLE.has(style.overflowX) &&
+ canMoveX({element, isRtl: isRtlElement(element as HTMLElement)}, dx)
+ );
+}
+
+/**
+ * A probe of the native scrollers under `target`. A wheel scrolls whatever
+ * `touch-action` says, which narrows only a finger's pan: a wheel's probe
+ * passes `readsTouchAction: false`.
+ */
+export function createNativeScrollProbe(
+ target: unknown,
+ {readsTouchAction = true}: {readsTouchAction?: boolean} = {},
+): NativeScrollProbe {
let chain: Chain | null = null;
const getChain = (): ChainEntry[] => {
chain ??=
target instanceof Element
- ? buildChain(target)
+ ? buildChain(target, readsTouchAction)
: {entries: [], allowsPan: false};
return chain.entries;
};
diff --git a/packages/core/src/gestures/recognizerInternals.ts b/packages/core/src/gestures/recognizerInternals.ts
index dd9a20547c..faa91898e0 100644
--- a/packages/core/src/gestures/recognizerInternals.ts
+++ b/packages/core/src/gestures/recognizerInternals.ts
@@ -20,7 +20,12 @@
import type {GestureArena} from './GestureArena';
import type {GestureRecognizer} from './GestureRecognizer';
-import type {GestureEventContext, GestureState, GestureTouch} from './types';
+import type {
+ GestureEventContext,
+ GestureState,
+ GestureTouch,
+ Point,
+} from './types';
/**
* The kinds of recognizer the host and touch-action treat specially. Each of
@@ -28,12 +33,14 @@ import type {GestureEventContext, GestureState, GestureTouch} from './types';
* never imports a recognizer class: a page ships only the recognizers it
* constructs.
*/
-export type RecognizerFamily = 'tap' | 'longPress' | 'pan';
+export type RecognizerFamily = 'tap' | 'longPress' | 'pan' | 'pinch';
/** The members of a recognizer only the gesture system calls. */
export interface RecognizerInternals {
/** The recognizer's family, when the host treats it specially. */
readonly family?: RecognizerFamily;
+ /** A pan's direction rule for a translation, `axisRatio` included. */
+ classify?(translation: Point): 'begin' | 'fail' | 'wait';
arena: GestureArena | null;
pending: 'began' | 'ended' | null;
readonly seenTouchIds: Set<number>;
diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.ts
index d50f5c1391..936707dd59 100644
--- a/packages/core/src/gestures/types.ts
+++ b/packages/core/src/gestures/types.ts
@@ -21,6 +21,14 @@ export type GestureState =
/** What made the contact. A pen on an iPad is `pen`, not `touch`. */
export type PointerKind = 'touch' | 'mouse' | 'pen';
+/**
+ * Scroll input a recognizer can take, as UIKit's `UIScrollTypeMask`: a
+ * trackpad's two-finger scroll or pinch (`continuous`), or a mouse wheel's
+ * notches (`discrete`). A pan takes only a trackpad's; a pinch takes a
+ * ctrl-wheel of either.
+ */
+export type ScrollType = 'continuous' | 'discrete';
+
export interface Point {
readonly x: number;
readonly y: number;
@@ -85,6 +93,8 @@ export interface GestureTouch {
readonly target: unknown;
/** The native scrollers under the contact, when the host knows them. */
readonly scroll: NativeScrollProbe | null;
+ /** Set for a wheel's or a trackpad's scroll input, which is no contact. */
+ readonly scrollType?: ScrollType;
/** The browser took this contact for its own pan or zoom. */
takenByBrowser: boolean;
}
@@ -104,6 +114,8 @@ export interface TouchBeganInput extends TouchInput {
readonly pointerType: PointerKind;
readonly target: unknown;
readonly scroll?: NativeScrollProbe | null;
+ /** Set for a wheel's or a trackpad's scroll input. */
+ readonly scrollType?: ScrollType;
}
/** What a recognizer is told alongside the touches that changed. */
diff --git a/packages/core/src/gestures/wheelSegmenter.ts b/packages/core/src/gestures/wheelSegmenter.ts
new file mode 100644
index 0000000000..1fec9701d0
--- /dev/null
+++ b/packages/core/src/gestures/wheelSegmenter.ts
@@ -0,0 +1,114 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file wheelSegmenter.ts
+ * @input A wheel stream's deltas along one axis, with their event times
+ * @output Exports WheelSegmenter: splits the stream into gestures and reads
+ * a trackpad's lift (the onset of momentum)
+ * @position Read by GestureHost.ts's wheel input: the web reports no
+ * trackpad contact or phase, so both are inferred.
+ */
+
+export type WheelBoundary = 'first' | 'idle' | 'reversal' | 'jump' | 'gap';
+export type WheelPhase = 'finger' | 'momentum';
+
+export interface WheelSegment {
+ /** Why this event starts a new gesture, or null when it continues one. */
+ readonly boundary: WheelBoundary | null;
+ readonly phase: WheelPhase;
+ /** The gesture's number, counting from 1. */
+ readonly gesture: number;
+ /** This event is where the fingers lifted (momentum begins with it). */
+ readonly liftNow: boolean;
+ /** This event shrank, so it may be momentum: hold it until known. */
+ readonly decaying: boolean;
+}
+
+/** Momentum arrives at frame rate: a pause this long ends it. */
+const MOMENTUM_GAP_MS = 50;
+/** Shrinking deltas in a row before the lift is read. */
+const LIFT_RUN = 4;
+/** And how much of its size the run has lost by then. */
+const LIFT_DECAY = 0.8;
+
+/**
+ * A trackpad gesture has a finger phase and, after a fling, a momentum phase.
+ * In the finger phase, deltas come while the fingers move, with pauses when
+ * they move slowly. In the momentum phase, deltas come at frame rate and
+ * shrink smoothly. The lift is the start of a run of shrinking deltas that
+ * has lost a fifth of its size. In the finger phase, a pause of `idleMs`
+ * ends the gesture. In the momentum phase, a reversal, a jump up against the
+ * decay, or a pause of 50 ms starts a new gesture. Momentum never pauses,
+ * reverses or grows.
+ */
+export class WheelSegmenter {
+ gesture = 0;
+ phase: WheelPhase = 'finger';
+ private last = -Infinity;
+ private previous = 0;
+ private sign = 0;
+ private count = 0;
+ private run = 0;
+ private runStart = 0;
+
+ push(time: number, delta: number, idleMs: number): WheelSegment {
+ const size = Math.abs(delta);
+ const sign = Math.sign(delta);
+ const gap = time - this.last;
+ let boundary: WheelBoundary | null = null;
+ if (this.count === 0) {
+ boundary = this.gesture === 0 ? 'first' : 'idle';
+ } else if (this.phase === 'finger' && gap >= idleMs) {
+ boundary = 'idle';
+ } else if (this.phase === 'momentum') {
+ if (sign !== 0 && this.sign !== 0 && sign !== this.sign) {
+ boundary = 'reversal';
+ } else if (gap >= MOMENTUM_GAP_MS) {
+ boundary = 'gap';
+ } else if (size >= 2 && size > this.previous * 1.3 + 0.5) {
+ boundary = 'jump';
+ }
+ }
+ if (boundary != null) {
+ this.gesture += 1;
+ this.phase = 'finger';
+ this.count = 0;
+ this.run = 0;
+ }
+ let liftNow = false;
+ let decaying = false;
+ if (this.phase === 'finger' && this.count >= 3 && size > 0) {
+ decaying = size <= this.previous * 0.995 && size >= this.previous * 0.5;
+ if (decaying) {
+ if (this.run === 0) {
+ this.runStart = this.previous;
+ }
+ this.run += 1;
+ } else {
+ this.run = 0;
+ }
+ if (this.run >= LIFT_RUN && size <= this.runStart * LIFT_DECAY) {
+ this.phase = 'momentum';
+ liftNow = true;
+ }
+ }
+ this.count += 1;
+ this.previous = size;
+ if (sign !== 0) {
+ this.sign = sign;
+ }
+ this.last = time;
+ return {
+ boundary,
+ phase: this.phase,
+ gesture: this.gesture,
+ liftNow,
+ decaying: decaying && !liftNow,
+ };
+ }
+
+ /** The gesture ended on its own (its timer): the next event starts one. */
+ end(): void {
+ this.count = 0;
+ }
+}