Skip to content

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

TypeScript

fix(core): one click guard for the menu press model and the gesture host (#8360)

Christopher Chedeau134afc4b322a
diff --git a/.changeset/click-guard.md b/.changeset/click-guard.md
new file mode 100644
index 0000000000..7376b26fef
--- /dev/null
+++ b/.changeset/click-guard.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture recognizers and the menu press model share one guard for the browser's click after a gesture that already acted, swallowing it for 400ms or until the next press. Keyboard and assistive-technology clicks (`detail` 0) always pass.
+
+@vjeux
diff --git a/.changeset/gesture-hook-fixes.md b/.changeset/gesture-hook-fixes.md
new file mode 100644
index 0000000000..87f08a0948
--- /dev/null
+++ b/.changeset/gesture-hook-fixes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture hooks call nothing back after unmount; `usePressTracker` brakes with the host by default and keeps one tracker, so an option change or a new ref never drops a press in progress; the recognizer's arena plumbing is `protected`. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-host-fixes.md b/.changeset/gesture-host-fixes.md
new file mode 100644
index 0000000000..3609238c3d
--- /dev/null
+++ b/.changeset/gesture-host-fixes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: gesture host fixes from review. A claimed pen holds only its own stylus touches, and a finger is matched to its scroller, its target and a moving element along the flat tree, through slots and shadow roots. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-host-owner.md b/.changeset/gesture-host-owner.md
new file mode 100644
index 0000000000..c4e1adeb8b
--- /dev/null
+++ b/.changeset/gesture-host-owner.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture host becomes the one document-level touch owner: the finger count, touch gates, and a kept press for continuous-tracking controls, whose element gets `touch-action: manipulation`. A scroll lock's page hold and the finger-scroll watch keep their own listeners and ask the host only about the touches it owns. A second finger fails a one-finger pan that has not claimed, so the page can pinch. A scroll-edge pan holds a lone finger from the first move that pulls away from an edge every scroller under it is at, so those moves are cancelled before it begins; with a second finger anywhere on the screen the page keeps its pinch. A press tracker whose hold acts (a stepper's hold-repeat) can bring a selection lock for its presses, as a recognizer can. Internal, for the touch components that adopt them; not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-recognizer-fixes.md b/.changeset/gesture-recognizer-fixes.md
new file mode 100644
index 0000000000..9e6754a78d
--- /dev/null
+++ b/.changeset/gesture-recognizer-fixes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: gesture recognizer and arena fixes from review; a pan claims nothing before it begins at 10 pt; one velocity tracker for every gesture (`spec:AST-100`: UIKit's measured blend, a scrolling surface's release through the pan's `scrollVelocity()`, and FR2's release rules). Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-watcher.md b/.changeset/gesture-watcher.md
new file mode 100644
index 0000000000..bec7cd286e
--- /dev/null
+++ b/.changeset/gesture-watcher.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a recognizer created with `claimsTouches: false` is a watcher: passive listeners only, simultaneous with every recognizer, and it follows a touch the browser takes for a scroll to the lift. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gestures-every-pointer.md b/.changeset/gestures-every-pointer.md
new file mode 100644
index 0000000000..bd76644fd6
--- /dev/null
+++ b/.changeset/gestures-every-pointer.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: with the gesture host serving every pointer, a press tracker takes a mouse press as a press, painting at once with no scroll brake (AST-094 FR11); a finger's or a pen's hold that does something keeps text unselected under any primary pointer, a touchscreen laptop's included, while a mouse keeps its released behavior (FR41); a finger is read once where the browser sends Touch Events without exposing `ontouchstart`; and `perEventPointer`, from before FR43, is accepted and does nothing. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/input-stream-recognizers.md b/.changeset/input-stream-recognizers.md
new file mode 100644
index 0000000000..f836fbddad
--- /dev/null
+++ b/.changeset/input-stream-recognizers.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture recognizers hear page-wide input through the same shared stream on the window's capture phase, so an app's window-capture `stopPropagation`, or a document-capture `stopImmediatePropagation` registered before Core, no longer hides a touch from them; a recognizer that must claim a touch mid-gesture still needs the touch to reach its element. Each event type's listener is passive unless a subscriber cancels it (the gesture host's `touchend` and `contextmenu` while a claiming recognizer or press tracker is attached, the page hold's `touchmove` while it holds, and the click guard's `click` while it is armed, and from the menu press model's first arm on), so a page of pressables registers no listener that can hold a scroll.
+
+@vjeux
diff --git a/.changeset/input-stream.md b/.changeset/input-stream.md
new file mode 100644
index 0000000000..a55f98ee0c
--- /dev/null
+++ b/.changeset/input-stream.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Touch press feedback now hears scrolls and page hides on the window's capture phase, where its pointer listeners already were. Under an app's window-capture `stopPropagation`, or a document-capture `stopImmediatePropagation` registered before Core, a finger's pressed look now ends when the content under it scrolls, and every pressed look ends when the page is hidden.
+
+@vjeux
diff --git a/.changeset/long-press-one-source.md b/.changeset/long-press-one-source.md
new file mode 100644
index 0000000000..c32640d83c
--- /dev/null
+++ b/.changeset/long-press-one-source.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: `useLongPress` takes its default duration and tolerance, 500ms and 10px on either axis, from the same source as the long-press gesture recognizer, so ContextMenu's long press behaves as before. A finger held on a DropdownMenu trigger passes its own 13px allowance instead (see the trigger drift fix).
+
+@vjeux
diff --git a/.changeset/menu-trigger-drift.md b/.changeset/menu-trigger-drift.md
new file mode 100644
index 0000000000..98ca1acc90
--- /dev/null
+++ b/.changeset/menu-trigger-drift.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A finger held on a DropdownMenu trigger may drift up to 13px on each axis and still open the menu under every primary pointer, a phone's, a tablet's and a touchscreen laptop's alike, as AST-094 FR29 allows; it cancelled past 10px. No menu, row or trigger reads the pointer query.
+
+@vjeux
diff --git a/.changeset/presented-hit-testing.md b/.changeset/presented-hit-testing.md
new file mode 100644
index 0000000000..e27c857277
--- /dev/null
+++ b/.changeset/presented-hit-testing.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] On iOS, a touch on an element the compositor animator is moving reaches what is drawn: the animator reports each moving element's offset from its layout box, and the gesture host sends the touch, press bounds and the tap's click there instead of to the layout position iOS WebKit hit-tests.
+
+@vjeux
diff --git a/.changeset/touch-selection-lock-gestures.md b/.changeset/touch-selection-lock-gestures.md
new file mode 100644
index 0000000000..d1f3ab7c2b
--- /dev/null
+++ b/.changeset/touch-selection-lock-gestures.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture host applies a recognizer's own `selectionLock` to that recognizer's contact and imports no lock itself; a long press brings one only when it has a hold (a `minimumPressDuration` above 0), and `selectionLock: null` opts out. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/touch-selection-lock.md b/.changeset/touch-selection-lock.md
new file mode 100644
index 0000000000..e5285afc1f
--- /dev/null
+++ b/.changeset/touch-selection-lock.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Where the primary pointer is fine (a mouse, a trackpad, a touchscreen laptop, a desktop pen tablet), the press feedback controller no longer registers a touch listener: it reads the primary pointer at the first finger or pen press and keeps its `touchcancel` listener only while that pointer is coarse.
+
+@vjeux
diff --git a/.changeset/use-finger-scroll.md b/.changeset/use-finger-scroll.md
new file mode 100644
index 0000000000..e48f0b171d
--- /dev/null
+++ b/.changeset/use-finger-scroll.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: `useFingerScroll(scroller)` tells a finger's scroll from the program's, and the gestures README gains a guide to migrating a raw-touch drag onto the recognizers. Internal to the touch components: not exported from the package entry point or the gestures barrel.
+
+@vjeux
diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md
index daa06c4bff..048fd73bcc 100644
--- a/docs/architecture/react-component-runtime.md
+++ b/docs/architecture/react-component-runtime.md
@@ -272,7 +272,7 @@ those contracts.
the modules through an internal hook only. A component's own touch logic is
small glue in its own build over these modules. The gesture host attaches for
every pointer, with no touch-only query; under a fine pointer only a component that
- uses a gesture listens (`spec:AST-094` FR19, FR24, FR43). The modules are not public exports and are not
+ uses a gesture listens (`spec:AST-094` FR19, FR24, FR43). The gesture host, press feedback, page hold, finger-scroll watch and click guard hear document-wide input through one capture-phase listener per event type on the window, present while a subscriber needs it. They run in subscription order, before any document or element listener; it is passive unless a subscriber cancels the event. The modules are not public exports and are not
documented for consumers; Core and Lab components reach them through
`@astryxdesign/core/internal/touch`, a subpath reserved for Astryx's own
packages: undocumented, outside the compatibility promise, versioned in
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index ea94298319..84ca1eea22 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -197,7 +197,7 @@ a measured, sourced difference exists.
activation stays the browser's click, except that an action a
`family:action-groups` member tracks activates at the lift (FR26), and a toggle
under `spec:AST-020` FR9's slide-off exception (Switch, Checkbox,
- CheckboxListItem) may also complete on a lift after the finger slid off.
+ CheckboxListItem) may also complete on a lift after the finger slid off. Where the engine hit-tests an element a compositor animation moves at the motion's start (iOS WebKit), a touch on moving content goes to what was drawn under the finger at touch-down, and a tap there (no recognizer claimed it, the browser did not take it, and it stayed within 45 pt) MUST activate it: the browser's own click for that touch is cancelled or swallowed, and that element receives one click, an editable focused first.
Under a fine pointer a control uses a third profile with no delay: its
press paint starts at once on `pointerdown`, through the same press
controller and release fade as a finger's, in place of CSS `:active`; the
@@ -312,7 +312,7 @@ a measured, sourced difference exists.
recognizer that must claim mid-gesture registers that blocking listener; an
element whose recognizers decide only at the lift keeps its `touchmove`
listener passive, and its `touchend` listener stays cancelable so the
- gesture can cancel the click (FR21). Known limit: a native scroll that starts on an element with a
+ gesture can cancel the click (FR21). While an element that holds, or sits inside, an element with a recognizer that claims moving touches moves on the compositor (iOS WebKit), the document MAY carry a non-passive `touchmove` listener; it cancels only the moves of a touch a recognizer owns under this rule and comes off when the motion ends. While it is on, a native scroll that starts anywhere on the page waits for a free main thread. Known limit: a native scroll that starts on an element with a
blocking listener waits for a free main thread in iOS Safari and Chromium.
That is never worse than UIKit, whose scrolling stops on a busy main thread,
and a passive listener, or one added at `touchstart`, would hand diagonal
@@ -617,6 +617,10 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
recordings for every claim about the reference values, and real-device
evidence for every claim about iOS Safari and Android Chrome behavior
(`spec:AST-013` FR10).
+- Presented hit testing (FR11's and FR19's iOS WebKit sentences): unit tests
+ that mimic iOS WebKit's hit testing at the motion's start, the WebKit tap and
+ drag proof with the correction off as its control, and the iOS Simulator
+ gate a merge; real-device evidence for it follows merge.
## Current-state impact
diff --git a/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json b/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
index 871fa48cb0..1aab6be4c1 100644
--- a/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
+++ b/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
@@ -119,7 +119,6 @@
"data-astryx-press",
"data-astryx-press"
],
- "packages/core/src/gestures/haptics.ts": ["data-astryx-haptic-switch"],
"packages/core/src/gestures/touchActionRule.ts": ["data-astryx-touch-action"],
"packages/core/src/hooks/useAnnounce.ts": [
"data-astryx-live-region",
diff --git a/internal/test-utils/src/setup.ts b/internal/test-utils/src/setup.ts
index 440b32ff22..991bb056f0 100644
--- a/internal/test-utils/src/setup.ts
+++ b/internal/test-utils/src/setup.ts
@@ -12,6 +12,8 @@
/// <reference types="@testing-library/jest-dom" />
import '@testing-library/jest-dom/vitest';
import {configure} from '@testing-library/react';
+import {afterEach} from 'vitest';
+import {__resetClickGuardForTest} from '../../../packages/core/src/utils/clickGuard';
// Text queries (getByText/findByText/…) target VISIBLE text. Astryx's
// `useAnnounce` renders a visually-hidden aria-live region
@@ -25,6 +27,15 @@ import {configure} from '@testing-library/react';
// Keeps the jsdom defaults (script, style).
configure({defaultIgnore: 'script, style, [data-astryx-live-region]'});
+// The click guard (packages/core/src/utils/clickGuard.ts) is armed per
+// document by a gesture that already acted and disarms itself 400 ms later.
+// A test that ends inside that window would leave the timer to fire after
+// the environment tears its window down, during a later file. Disarm every
+// guard as each test ends.
+afterEach(() => {
+ __resetClickGuardForTest();
+});
+
// Polyfill for matchMedia (not supported in jsdom).
//
// `(hover: hover)` reports TRUE: jsdom models a desktop browser driven by a
diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts
index 25f81a79c7..1d11b2df6a 100644
--- a/packages/core/src/gestures/GestureArena.ts
+++ b/packages/core/src/gestures/GestureArena.ts
@@ -58,6 +58,7 @@ import type {
TouchSample,
} from './types';
import {DEFAULT_ENVIRONMENT} from './types';
+import {internals} from './recognizerInternals';
export interface GestureClock {
now(): number;
@@ -93,6 +94,12 @@ export interface GestureArenaOptions {
onClaim?: (touchIds: ReadonlyArray<number>) => void;
/** A click deferred at touch end resolved: replay it, or drop it. */
onDeferredClick?: (touch: GestureTouch, allowed: boolean) => void;
+ /**
+ * The arena dropped its last touch, as after a lifted touch's decision
+ * waited on a timer (a tap waiting on a double tap): its host may stop
+ * listening now (`spec:AST-094` FR24).
+ */
+ onIdle?: () => void;
/** Every recognizer transition, for debugging and tests. */
onTransition?: (
recognizer: GestureRecognizer,
@@ -141,7 +148,7 @@ export class GestureArena {
private depth = 0;
/** Open `deferResolution` calls: what their stops unblock waits. */
private deferDepth = 0;
- /** A deferred stop left recognitions, held touches or resets to settle. */
+ /** A deferred stop left a resolution for the next pass. */
private owesResolution = false;
constructor(options: GestureArenaOptions = {}) {
@@ -162,11 +169,25 @@ export class GestureArena {
return this.records.get(id)?.isClaimed === true;
}
+ /** @internal The view-level consumer of this touch, if any. */
+ consumerOf(id: number): TouchConsumer | null {
+ return this.records.get(id)?.consumer ?? null;
+ }
+
/** The live touch with this id. */
getTouch(id: number): GestureTouch | undefined {
return this.records.get(id)?.touch;
}
+ /**
+ * The recognizers that took touch `id` when it began: each was enabled,
+ * accepted its pointer, and its `shouldReceiveTouch` agreed. Empty for a
+ * touch the arena does not track.
+ */
+ participantsOf(id: number): ReadonlyArray<GestureRecognizer> {
+ return this.records.get(id)?.participants ?? [];
+ }
+
/** Every touch the arena tracks, lifted ones awaiting a decision included. */
get touches(): ReadonlyArray<GestureTouch> {
return [...this.records.values()].map(record => record.touch);
@@ -210,11 +231,11 @@ export class GestureArena {
};
const participants: GestureRecognizer[] = [];
for (const [depth, recognizer] of input.recognizers.entries()) {
- if (!recognizer.wantsTouch(touch)) {
+ if (!internals(recognizer).wantsTouch(touch)) {
continue;
}
participants.push(recognizer);
- recognizer.arena = this;
+ internals(recognizer).arena = this;
if (!this.active.includes(recognizer)) {
// Resolution follows `active`, so a recognizer joins ahead of any
// that sits further out on this touch's path: when two recognize
@@ -250,7 +271,7 @@ export class GestureArena {
for (const recognizer of [...this.active]) {
const touches = newTouches.get(recognizer);
if (touches != null) {
- recognizer.deliverBegan(touches, context);
+ internals(recognizer).deliverBegan(touches, context);
}
}
// A recognizer already tracking a gesture hears of a touch that began
@@ -262,7 +283,7 @@ export class GestureArena {
.map(record => record.touch)
.filter(touch => own == null || !own.includes(touch));
if (elsewhere.length > 0 && recognizer.numberOfTouches > 0) {
- recognizer.deliverBeganElsewhere(elsewhere, context);
+ internals(recognizer).deliverBeganElsewhere(elsewhere, context);
}
}
for (const record of created) {
@@ -300,7 +321,7 @@ export class GestureArena {
const context = this.context();
for (const recognizer of [...this.active]) {
if (recognizer.numberOfTouches > 0) {
- recognizer.deliverBeganElsewhere([touch], context);
+ internals(recognizer).deliverBeganElsewhere([touch], context);
}
}
});
@@ -321,7 +342,7 @@ export class GestureArena {
this.movingIds = new Set(changed.map(touch => touch.id));
try {
for (const recognizer of [...this.active]) {
- recognizer.deliverMoved(changed, context);
+ internals(recognizer).deliverMoved(changed, context);
}
} finally {
this.movingIds = previous;
@@ -348,7 +369,7 @@ export class GestureArena {
const changed = this.update(inputs, 'ended');
const context = this.context();
for (const recognizer of [...this.active]) {
- recognizer.deliverEnded(changed, context);
+ internals(recognizer).deliverEnded(changed, context);
}
// A lift can decide a waiting recognition (its requirement lifted
// undecided and failed): settle those first, so each click's answer is
@@ -375,7 +396,7 @@ export class GestureArena {
}
const context = this.context();
for (const recognizer of [...this.active]) {
- recognizer.deliverCancelled(touches, context);
+ internals(recognizer).deliverCancelled(touches, context);
}
for (const touch of touches) {
const record = this.records.get(touch.id);
@@ -410,7 +431,7 @@ export class GestureArena {
}
const context = this.context();
for (const recognizer of [...this.active]) {
- recognizer.deliverTakenByBrowser(touches, context);
+ internals(recognizer).deliverTakenByBrowser(touches, context);
}
for (const touch of touches) {
const record = this.records.get(touch.id);
@@ -437,7 +458,10 @@ export class GestureArena {
this.fail(recognizer);
return;
}
- if (recognizer.pending != null && (next === 'began' || next === 'ended')) {
+ if (
+ internals(recognizer).pending != null &&
+ (next === 'began' || next === 'ended')
+ ) {
// Already waiting on a requirement; the recognition stands as asked.
return;
}
@@ -474,8 +498,8 @@ export class GestureArena {
/**
* Runs `body`, code outside input that stops recognizers (an Effect that
* turns one off or detaches it), without resolving what those stops
- * unblock: the recognitions waiting on them, the touches they held from a
- * view, the resets. A pass a microtask later resolves all of it, at the
+ * unblock: the recognitions waiting on them, the touches they held from
+ * a view, the resets. A pass a microtask later resolves all of it, at the
* last event's time, so the listeners and consumers it reaches hear it
* outside the caller's frame and read the recognized state
* (react-component-runtime INV2).
@@ -507,7 +531,9 @@ export class GestureArena {
stop(recognizer: GestureRecognizer): void {
// A cancel from code between events happens at the last event's time:
// wall time would run deadlines ahead of input still queued (FR16).
- const time = this.currentTime ?? this.lastEventTime();
+ const time =
+ this.currentTime ??
+ (Number.isFinite(this.latestTime) ? this.latestTime : this.clock.now());
this.run(time, () => {
if (isActive(recognizer.state)) {
this.apply(recognizer, 'cancelled');
@@ -524,13 +550,19 @@ export class GestureArena {
recognizer: GestureRecognizer,
next: 'began' | 'ended',
): void {
- if (!recognizer.shouldBegin() || this.isVetoedByConsumer(recognizer)) {
+ if (
+ !internals(recognizer).shouldBegin() ||
+ this.isVetoedByConsumer(recognizer)
+ ) {
this.fail(recognizer);
return;
}
let isWaiting = false;
for (const other of this.active) {
- if (other === recognizer || !recognizer.requiresFailureOf(other)) {
+ if (
+ other === recognizer ||
+ !internals(recognizer).requiresFailureOf(other)
+ ) {
continue;
}
if (other.state === 'failed') {
@@ -546,7 +578,7 @@ export class GestureArena {
}
}
if (isWaiting) {
- recognizer.pending = next;
+ internals(recognizer).pending = next;
this.claim(recognizer);
return;
}
@@ -570,14 +602,16 @@ export class GestureArena {
continue;
}
if (
- other.requiresFailureOf(recognizer) ||
+ internals(other).requiresFailureOf(recognizer) ||
this.conflicts(recognizer, other)
) {
this.fail(other);
}
}
this.claim(recognizer);
- if (recognizer.cancelsTouchesInView) {
+ // A watcher takes nothing from the view either: the press and the click
+ // under it stay (spec:AST-094 FR11, FR19; FR15 exempts watchers).
+ if (recognizer.claimsTouches && recognizer.cancelsTouchesInView) {
this.cancelViewTouchesOf(recognizer);
}
}
@@ -587,7 +621,14 @@ export class GestureArena {
winner: GestureRecognizer,
other: GestureRecognizer,
): boolean {
- if (!sharesTouches(winner, other) || winner.allowsSimultaneous(other)) {
+ if (
+ !sharesTouches(winner, other) ||
+ internals(winner).allowsSimultaneous(other) ||
+ // A watcher (claimsTouches false) prevents nothing and nothing
+ // prevents it.
+ !winner.claimsTouches ||
+ !other.claimsTouches
+ ) {
return false;
}
return winner.canPrevent(other) && other.canBePrevented(winner);
@@ -595,7 +636,7 @@ export class GestureArena {
/** UIControl's rule: a control may veto an overlapping ancestor recognizer. */
private isVetoedByConsumer(recognizer: GestureRecognizer): boolean {
- for (const id of recognizer.seenTouchIds) {
+ for (const id of internals(recognizer).seenTouchIds) {
const consumer = this.records.get(id)?.consumer;
if (consumer?.allowsAncestorRecognizer?.(recognizer) === false) {
return true;
@@ -612,13 +653,9 @@ export class GestureArena {
this.apply(recognizer, 'cancelled');
return;
}
- recognizer.pending = null;
+ internals(recognizer).pending = null;
+ // apply() gives back any claim it held (releaseClaim), waiting or not.
this.apply(recognizer, 'failed');
- if (this.deferDepth > 0) {
- // Inside `deferResolution`, the next pass settles.
- this.owesResolution = true;
- return;
- }
this.reviewPending();
}
@@ -649,7 +686,7 @@ export class GestureArena {
other.claimsTouches &&
(isActive(other.state) ||
other.state === 'ended' ||
- other.pending != null) &&
+ internals(other).pending != null) &&
other.trackedTouches.some(tracked => tracked.id === touch.id),
);
if (!isOwned) {
@@ -660,7 +697,7 @@ export class GestureArena {
private apply(recognizer: GestureRecognizer, next: GestureState): void {
const from = recognizer.state;
- recognizer.applyState(next);
+ internals(recognizer).applyState(next);
if (recognizer.state === next && from !== next) {
this.options.onTransition?.(recognizer, from, next);
} else if (next === 'changed' && from === 'changed') {
@@ -682,25 +719,29 @@ export class GestureArena {
* settle in one pass.
*/
private reviewPending(): void {
+ if (this.deferDepth > 0) {
+ this.owesResolution = true;
+ return;
+ }
let changed = true;
while (changed) {
changed = false;
for (const recognizer of [...this.active]) {
- const next = recognizer.pending;
+ const next = internals(recognizer).pending;
if (next == null || recognizer.state !== 'possible') {
continue;
}
const blocked = this.active.some(
other =>
other !== recognizer &&
- recognizer.requiresFailureOf(other) &&
+ internals(recognizer).requiresFailureOf(other) &&
other.state === 'possible' &&
other.isInvolved(),
);
if (blocked) {
continue;
}
- recognizer.pending = null;
+ internals(recognizer).pending = null;
this.attemptRecognition(recognizer, next);
changed = true;
}
@@ -829,7 +870,7 @@ export class GestureArena {
recognizer.delaysTouchesBegan &&
recognizer.state === 'possible' &&
recognizer.isInvolved() &&
- recognizer.seenTouchIds.has(record.touch.id),
+ internals(recognizer).seenTouchIds.has(record.touch.id),
);
}
@@ -839,12 +880,12 @@ export class GestureArena {
recognizer.delaysTouchesEnded &&
recognizer.state === 'possible' &&
recognizer.isInvolved() &&
- recognizer.seenTouchIds.has(record.touch.id),
+ internals(recognizer).seenTouchIds.has(record.touch.id),
);
}
private cancelViewTouchesOf(recognizer: GestureRecognizer): void {
- for (const id of recognizer.seenTouchIds) {
+ for (const id of internals(recognizer).seenTouchIds) {
const record = this.records.get(id);
if (record == null) {
continue;
@@ -925,6 +966,13 @@ export class GestureArena {
private run(time: number, body: () => void): void {
this.depth += 1;
try {
+ if (this.depth === 1 && this.deferDepth === 0 && this.owesResolution) {
+ // A deferred stop resolves before anything newer: input that comes
+ // ahead of its microtask (a nested dispatch) sees settled state.
+ this.owesResolution = false;
+ this.currentTime = this.clampTime(this.lastEventTime());
+ this.settle();
+ }
this.flushTimers(time);
this.currentTime = this.clampTime(time);
body();
@@ -997,7 +1045,7 @@ export class GestureArena {
}
this.active = this.active.filter(other => other !== recognizer);
const from = recognizer.state;
- recognizer.resetToPossible();
+ internals(recognizer).resetToPossible();
didReset = true;
if (from !== 'possible') {
this.options.onTransition?.(recognizer, from, 'possible');
@@ -1008,6 +1056,7 @@ export class GestureArena {
// touch from its view; release it now, not at the next input.
this.reviewHeld();
}
+ let dropped = false;
for (const [id, record] of this.records) {
if (
record.isLifted &&
@@ -1016,8 +1065,12 @@ export class GestureArena {
!record.deferredClick
) {
this.records.delete(id);
+ dropped = true;
}
}
+ if (dropped && this.records.size === 0) {
+ this.options.onIdle?.();
+ }
}
private scheduleRealTimer(): void {
@@ -1057,8 +1110,8 @@ export class GestureArena {
}
function sharesTouches(a: GestureRecognizer, b: GestureRecognizer): boolean {
- for (const id of a.seenTouchIds) {
- if (b.seenTouchIds.has(id)) {
+ for (const id of internals(a).seenTouchIds) {
+ if (internals(b).seenTouchIds.has(id)) {
return true;
}
}
diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts
index 71cf291dd5..b90fd81a8c 100644
--- a/packages/core/src/gestures/GestureHost.ts
+++ b/packages/core/src/gestures/GestureHost.ts
@@ -3,10 +3,9 @@
/**
* @file GestureHost.ts
* @input DOM touch, pointer, click, contextmenu, scroll and focus events of
- * one document; elements with recognizers and consumers attached, and
- * consumer types found by attribute
- * @output Exports GestureHost (the DOM side of the gesture system),
- * getGestureHost (one host per document) and the delegated consumer type
+ * one document; elements with recognizers and consumers attached
+ * @output Exports GestureHost (the DOM side of the gesture system) and
+ * getGestureHost (one host per document)
* @position Browser adapter of packages/core/src/gestures: turns real events
* into GestureArena input, and carries out what the arena decides
*
@@ -14,36 +13,36 @@
*
* - Recognizers and press consumers attach for a mouse, a pen and a finger
* alike (`spec:AST-094` FR43, FR19). Where the primary pointer is coarse
- * the host listens on the page while something enabled could take a
- * touch. Where it is fine, each element with an enabled recognizer or
- * consumer keeps one passive `pointerdown` listener and the page has none:
- * a press on it (a mouse's primary button, a pen, or a finger, whose
- * `pointerdown` comes before its `touchstart`) installs the host's page
- * listeners, which go once that press's contacts end; the click listener
- * alone stays through the swallower's window, for the click a claimed lift
- * owes (FR21, FR24). An element whose recognizer claims a moving finger
- * keeps its blocking `touchmove` under every pointer, a listener FR24
- * counts apart.
- * - A right click, a pen's barrel button and a ctrl-click on macOS start no
- * press (primaryClick.ts).
- * - The host follows the primary pointer (a tablet docking a mouse): turning
- * fine with no press held removes the page listeners and cancels every
- * touch in flight.
- * - A delegated consumer type has no element to listen on: where the
- * primary pointer is fine, the document keeps one passive `pointerdown`
- * listener for every type, counted once per page (FR24).
+ * the host listens while something enabled could take a touch. Where it
+ * is fine, each element with an enabled recognizer or consumer keeps one
+ * passive `pointerdown` listener and the page has none; a press on it (a
+ * mouse's primary button, a pen, or a finger, whose `pointerdown` comes
+ * before its `touchstart`) installs the host's page listeners, which go
+ * once that press's contacts end and the arena has decided them, a tap
+ * that waits on a double tap included (FR24). After the last detach the
+ * host holds nothing: no listener, note, frame or timer (releaseWhenIdle).
+ * Under every pointer, an element whose recognizer claims a moving finger
+ * also keeps its blocking `touchmove`, a listener FR24 counts apart from
+ * the press's one.
+ * - A press consumer takes a mouse press as a press (DEC-21): PressTracker's
+ * fine-pointer profile paints at once and brakes no scroll (FR11).
+ * - The host follows the query (a tablet docking or undocking a mouse):
+ * turning fine cancels every touch in flight.
+ * - `perEventPointer` (AttachOptions), from before FR43, changes nothing.
*
* INPUT CHANNELS
*
* - Fingers begin and end with Touch Events: they are the only cancelable
* channel (a pointer event's preventDefault cannot stop a scroll or a
- * click), they keep arriving after the browser takes a pan (which a scroll
- * handoff needs), and every event lists all the fingers at once. A
- * finger's movement comes from BOTH its `touchmove`s and its
- * `pointermove`s (paired at touchstart by target and position), the echo
- * of one in the other dropped: Chromium sends no `touchmove` until a
- * finger has travelled about 16 px, while a tap fails and a pan begins at
- * 10.
+ * click), they keep arriving after the browser takes a pan (which a
+ * watcher following the scroll to the lift needs, `spec:AST-094` FR20,
+ * DEC-7), and every event lists all the fingers at once. A
+ * finger's movement is sampled from ONE channel: its `pointermove`s, once
+ * its pointerdown has paired with its touchstart (by target and
+ * position), since Chromium sends no `touchmove` until a finger has
+ * travelled about 16 px while a tap fails and a pan begins at 10; touch
+ * events sample only a finger no pointer event reported. The other
+ * channel keeps its control duties but feeds no sample.
* - A finger's events go to the element it landed on even after that
* element leaves the document, and then never reach the document. Each
* tracked finger's target therefore gets its own listeners, and a finger
@@ -51,17 +50,43 @@
* removed target never strands a gesture.
* - Mice and pens come from Pointer Events, with coalesced samples for
* velocity. A pen on an iPad also produces `stylus` touches; those are left
- * to the pointer path.
+ * to the pointer path, except that a claimed pen's stylus moves are
+ * cancelled as a finger's.
* - `pointercancel` on a finger is the browser saying it took that finger
* for its own pan or zoom; so is a `touchmove` that can no longer be
* cancelled where `touch-action` let the browser pan, and a scroll above
* the touch.
*
+ * FINGERS
+ *
+ * - The host keeps one record of where each finger on the screen landed
+ * (`fingersDown()`). Finger scrolls (fingerScroll.ts) read it, and a
+ * scroll lock's page hold (pageHold.ts) asks which touches a recognizer
+ * owns; both live in their own modules, so a page that needs neither
+ * never ships them.
+ *
+ * TOUCHES ON MOVING ELEMENTS
+ *
+ * - iOS WebKit hit-tests an element a compositor animation moves where the
+ * animation started. There, at touch-down, the host resolves the moving
+ * elements (motion/presentation.ts: one style write each) and asks the
+ * engine again, so a contact goes to what is drawn under it; press
+ * trackers read `presentedRect`, and a retargeted tap clicks what it
+ * touched once, with the engine's own click cancelled or swallowed.
+ *
* WHAT THE BROWSER IS TOLD
*
* - Each element gets the `touch-action` its recognizers leave the browser
- * (touchAction.ts), set inline when they attach and restored when they
- * detach.
+ * (touchAction.ts), never wider than the element's own value (a caller's
+ * explicit `touch-action` stays in force), set inline when they attach and
+ * restored when they detach.
+ * - While a finger or a pen is down, text selection and the touch callout
+ * are off only where the hold does something (`spec:AST-094` FR41): on the
+ * elements of recognizers that bring a `selectionLock`, and on a non-text
+ * input under the finger inside them (WebKit's own style makes every
+ * input selectable); restored when the contact ends. A finger or a pen
+ * takes it under any primary pointer; a mouse never does (`spec:AST-017`
+ * FR59).
* - Each element with a recognizer that can claim a touch while it moves (a
* pan, a swipe, a long press that then drags, a pinch) gets a
* NON-passive `touchmove` listener that cancels the event only while a
@@ -71,27 +96,39 @@
* known cost: a scroll that BEGINS on such an element waits for a busy main
* thread (measured in iOS Safari; a passive listener would hand every
* diagonal to the scroll instead). Elements whose recognizers only claim
- * at the lift (taps) and press consumers get no blocking listener, so a
- * scroll starting on them never waits.
+ * at the lift (taps), recognizers that never claim (`claimsTouches` false)
+ * and press consumers get no blocking listener, and the listener a
+ * finger's target gets at touch-down is passive for them too, so a scroll
+ * starting on them never waits.
+ * - The browser took a finger on `pointercancel`, on its first uncancelable
+ * `touchmove` where it could pan, or on a scroll above it once the finger
+ * has travelled the slop; a scroll under a finger that has not moved is
+ * the page's own and leaves the touch alone.
* - A lift whose click must not happen cancels its `touchend` (no click, no
- * compatibility mouse events) and arms a one-shot swallower for the next
- * trusted click; a click held for a recognizer that may still recognize is
+ * compatibility mouse events) and arms the shared click guard
+ * (utils/clickGuard.ts, the menu press model's too) for the browser's next
+ * click; a click held for a recognizer that may still recognize is
* replayed if they all fail. Keyboard and assistive-technology clicks
* (`detail === 0`) always pass.
* - A `contextmenu` while a recognizer owns a touch is cancelled, so a long
* press never also opens the browser's menu.
- *
- * DELEGATED CONSUMERS. A consumer type registered with an attribute (a
- * pressable row) is found at touch-down by walking up from the touch target,
- * and an instance is created for that one touch: a list of a thousand rows
- * costs nothing until a finger lands on one.
+ * - When the app loses focus (a window blur, a hidden page), every touch in
+ * flight is cancelled, as in UIKit; a finger the browser keeps alive lifts
+ * on nothing: its `touchend` is cancelled (`spec:AST-094` FR28).
*
* SSR-safe: nothing touches `window` or `document` until something attaches.
*
* SYNC: When modified, update GestureHost.test.ts and README.md.
*/
-import {UIKIT_GESTURES} from '../motion/uikit/gestures';
+import {isRtlElement} from '../hooks/isRtlElement';
+import {
+ presentedElements,
+ presentedOffsetOf,
+ resolvePresented,
+ watchPresentedElements,
+} from '../motion/presentation';
+import {UIKIT_PRESS, UIKIT_TAP} from '../motion/uikit/gestures';
import {
browserClock,
GestureArena,
@@ -100,14 +137,15 @@ import {
type GestureArenaOptions,
type GestureClock,
} from './GestureArena';
-import type {GestureRecognizer} from './GestureRecognizer';
-import {HAPTIC_SWITCH_ATTRIBUTE} from './haptics';
-import {isPrimaryClick} from '../utils/primaryClick';
+import type {GestureRecognizer, SelectionLock} from './GestureRecognizer';
+import type {PressBounds} from './PressTracker';
+import type {PanGestureRecognizer} from './PanGestureRecognizer';
import {createNativeScrollProbe, parentAcrossShadow} from './nativeScroll';
+import {containsAlongFlatTree} from '../utils/flatTree';
+import {isIosWebKit} from '../utils/touchQueries';
import {
gestureHostStyle,
type GestureHostStyle,
- holdSelectionStyle,
intersectTouchAction,
} from './touchAction';
import {
@@ -125,16 +163,29 @@ import type {
TouchInput,
TouchSample,
} from './types';
+import {internals} from './recognizerInternals';
+import {
+ armClickGuard,
+ disarmClickGuard,
+ withoutClickGuard,
+} from '../utils/clickGuard';
+import {subscribeInput} from '../utils/inputStream';
+import {isPrimaryClick} from '../utils/primaryClick';
+import {locksSelectionFor} from '../utils/selectionLock';
+import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer';
+import {gestureHosts} from './hostRegistry';
interface Registration {
readonly recognizers: GestureRecognizer[];
consumer: TouchConsumer | null;
- touchMoveListener: EventListener | null;
/**
- * Under `inputMode: 'pointer-events'`, the element's blocking `touchend`
- * listener: it cancels a claimed finger's lift (`spec:AST-094` FR21).
+ * Where fingers come from their pointer events, whether the element
+ * carries the host's blocking `touchend` handler, which cancels a claimed
+ * finger's lift (`spec:AST-094` FR21).
*/
- touchEndListener: EventListener | null;
+ hasTouchEndListener: boolean;
+ /** Whether the element carries the host's shared blocking touchmove handler. */
+ hasTouchMoveListener: boolean;
/** Inline values the host replaced, to restore on detach. */
readonly savedStyle: Map<string, string>;
/**
@@ -147,6 +198,8 @@ interface Registration {
manageStyle: boolean;
/** An action group (`family:action-groups` FR5). */
actionGroup: boolean;
+ /** The attachments that asked for the action group; it lasts while one does. */
+ actionGroupAsks: number;
}
export interface GestureHostOptions {
@@ -159,6 +212,13 @@ export interface GestureHostOptions {
inputMode?: 'auto' | 'pointer-events';
/** Every recognizer transition, for debugging and tests. */
onTransition?: GestureArenaOptions['onTransition'];
+ /**
+ * Send a contact to what is drawn while a compositor animation moves an
+ * element (motion/presentation.ts): `auto` where the engine hit-tests such
+ * an element where its animation started (iOS WebKit); `always` or
+ * `never` for tests. @default 'auto'
+ */
+ presentedHitTesting?: 'auto' | 'always' | 'never';
/**
* Whether the primary pointer is coarse (a phone, a tablet). Gestures
* attach for every pointer (`spec:AST-094` FR43); where it is fine, an
@@ -178,6 +238,12 @@ export interface AttachOptions {
* @default true
*/
manageStyle?: boolean;
+ /**
+ * Accepted and ignored: every attachment reads each event's pointer
+ * (`spec:AST-094` FR43). Kept so callers written before FR43 compile.
+ * @deprecated
+ */
+ perEventPointer?: boolean;
/**
* The element is an action group, sibling actions a held pointer slides
* across (`family:action-groups` FR5). It is served like every
@@ -186,21 +252,6 @@ export interface AttachOptions {
actionGroup?: boolean;
}
-/**
- * A kind of view-level consumer found by attribute instead of attached to
- * each element.
- */
-export interface DelegatedConsumerType {
- /** Marks an element as this kind of consumer. */
- readonly attribute: string;
- /**
- * The consumer for one contact on `element`, or null for none (a disabled
- * control). The innermost marked element decides, even with null: a press
- * on a disabled button does not light the row around it.
- */
- create(element: Element, pointerType: PointerKind): TouchConsumer | null;
-}
-
const STYLE_PROPERTIES: Record<keyof GestureHostStyle, string> = {
touchAction: 'touch-action',
WebkitTouchCallout: '-webkit-touch-callout',
@@ -208,15 +259,6 @@ const STYLE_PROPERTIES: Record<keyof GestureHostStyle, string> = {
userSelect: 'user-select',
};
-/**
- * Whether a recognizer can take a touch while it moves, and so needs the
- * blocking `touchmove` listener that stops the browser's pan. A tap claims
- * only at the lift (it fails once the finger travels), so it needs none.
- */
-function claimsWhileMoving(recognizer: GestureRecognizer): boolean {
- return recognizer.acceptsTouchInput && recognizer.kind !== 'tap';
-}
-
/**
* A CSS-wide keyword, which names no touch-action of its own: the value in
* force resolves it (`initial` and `unset` to `auto`, `inherit` to the
@@ -238,16 +280,41 @@ const CSS_WIDE_KEYWORDS: ReadonlySet<string> = new Set([
* Run `task` in the next frame, before it paints: a read there styles what
* the frame must style anyway, and its writes are what the frame shows.
*/
-function inNextFrame(view: Window | null, task: () => void): void {
+function inNextFrame(view: Window | null, task: () => void): () => void {
if (view != null && typeof view.requestAnimationFrame === 'function') {
- view.requestAnimationFrame(task);
- } else {
- setTimeout(task, 0);
+ const frame = view.requestAnimationFrame(task);
+ return () => view.cancelAnimationFrame(frame);
}
+ const timeout = setTimeout(task, 0);
+ return () => clearTimeout(timeout);
}
+/** An armed press tracker's own element listeners: they never cancel. */
const PASSIVE_CAPTURE = {capture: true, passive: true} as const;
+/**
+ * Whether a recognizer can take a touch while it moves, and so needs the
+ * blocking `touchmove` listener that stops the browser's pan. A tap claims
+ * only at the lift (it fails once the finger travels), so it needs none.
+ */
+function claimsWhileMoving(recognizer: GestureRecognizer): boolean {
+ return (
+ recognizer.claimsTouches &&
+ internals(recognizer).acceptsTouchInput &&
+ internals(recognizer).family !== 'tap'
+ );
+}
+
+/**
+ * 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.
+ */
+function isPanRecognizer(
+ recognizer: GestureRecognizer,
+): recognizer is PanGestureRecognizer {
+ return internals(recognizer).family === 'pan';
+}
+
/**
* A screen-edge pan, told apart by its kind (architecture:react-component-runtime
* INV13), so the host can report its layout changes without importing it.
@@ -260,31 +327,30 @@ function asScreenEdgePan(
: null;
}
-/** The inline properties a held press sets to none (holdSelectionStyle). */
-const HOLD_SELECTION_PROPERTIES = [
- '-webkit-touch-callout',
- '-webkit-user-select',
- 'user-select',
-] as const;
-
-/** Elements a held press turned selection off on, and what to restore. */
-const heldSelection = new WeakMap<
- HTMLElement,
- {
- count: number;
- saved: ReadonlyArray<{name: string; value: string; priority: string}>;
- }
->();
-const ACTIVE_CAPTURE = {capture: true, passive: false} as const;
-
type StylusTouch = Touch & {touchType?: string};
+function hasStylusTouch(event: TouchEvent): boolean {
+ return touchesOf(event.changedTouches).some(
+ touch => (touch as StylusTouch).touchType === 'stylus',
+ );
+}
+
interface PlacedContact {
readonly x: number;
readonly y: number;
readonly target: unknown;
}
+/**
+ * How long a claimed finger's lift waits for its `touchend`, ms. The touchend
+ * follows its pointerup in the same frame; a browser that sends pointer events
+ * alone for a finger never sends it, and the record goes.
+ */
+const CLAIMED_LIFT_MS = 500;
+
+/** At most this many claimed lifts wait for their `touchend` at once (FR24). */
+const CLAIMED_LIFT_LIMIT = 8;
+
/** A touchstart and a pointerdown describe one finger: same target, same spot. */
function isSamePlace(a: PlacedContact, b: PlacedContact): boolean {
return (
@@ -298,6 +364,23 @@ function isPointerKind(type: string): type is PointerKind {
return type === 'touch' || type === 'mouse' || type === 'pen';
}
+/**
+ * What an event, or one of its touches, landed on. Inside an open shadow root
+ * the document's listeners see the shadow host, in `event.target` and in a
+ * touch's `target` alike, while the composed path starts at the element
+ * itself. A touch whose target is not the event's (another finger) keeps its
+ * own.
+ */
+function landedOn(
+ event: Event,
+ retargeted: EventTarget | null = event.target,
+): EventTarget | null {
+ if (retargeted !== event.target) {
+ return retargeted;
+ }
+ return event.composedPath()[0] ?? retargeted;
+}
+
/**
* An event's time on the arena's clock (`performance.now()`). Some engines
* and DOM emulators stamp events in epoch milliseconds instead.
@@ -323,9 +406,34 @@ export class GestureHost {
readonly arena: GestureArena;
private readonly doc: Document;
private readonly registry = new Map<Element, Registration>();
- private readonly delegated = new Set<DelegatedConsumerType>();
+ /** Stops following the animator's moving elements (iOS WebKit only). */
+ private stopWatchingMovers: (() => void) | null = null;
+ /** Whether the document carries the blocking touchmove for a mover. */
+ private stopBlockingForMovers: (() => void) | null = null;
+ /** Elements whose caller touch-action waits for a read after paint. */
+ private readonly pendingCallerReads = new Set<HTMLElement>();
+ private isCallerReadScheduled = false;
+ /** Cancels the scheduled next-frame read (readCallerTouchActionInNextFrame). */
+ private cancelCallerRead: (() => void) | null = null;
+ /** The selection lock each contact holds, by host contact id. */
+ private readonly lockedBy = new Map<number, () => void>();
+ private readonly presentedHitTesting: 'auto' | 'always' | 'never';
+ /**
+ * Contacts sent to what is drawn instead of what the engine hit, by host
+ * contact id, with where they landed (for their click).
+ */
+ private readonly retargeted = new Map<
+ number,
+ {x: number; y: number; target: EventTarget}
+ >();
/** Touch.identifier → arena id, for live fingers. */
private readonly touchIds = new Map<number, number>();
+ /**
+ * Fingers cancelled because the app lost focus, kept until the browser
+ * ends them: a browser that keeps such a touch alive must not let its
+ * lift click (`spec:AST-094` FR28: nothing acts).
+ */
+ private readonly cancelledFingers = new Set<number>();
/** Touch.identifier → the element the finger landed on. */
private readonly touchTargets = new Map<number, EventTarget>();
/**
@@ -335,17 +443,21 @@ export class GestureHost {
*/
private readonly watched = new Map<
EventTarget,
- {count: number; blocking: number}
+ {count: number; blocking: number; claiming: number}
>();
/** Fingers whose target listener is the blocking one. */
private readonly blockingFingers = new Set<number>();
+ /**
+ * Fingers a participant could claim (a recognizer that claims touches, or
+ * a press consumer): only their target's `touchend` may need cancelling,
+ * so a touch only watchers follow gets a passive one (`spec:AST-094`
+ * FR20).
+ */
+ private readonly claimingFingers = new Set<number>();
/** Touch events already handled (the document's and the target's listeners both see one). */
private readonly processed = new WeakSet<Event>();
/** pointerId → arena id, for live mouse and pen contacts. */
private readonly pointerIds = new Map<number, number>();
- /** Elements whose caller touch-action waits for a read after paint. */
- private readonly pendingCallerReads = new Set<HTMLElement>();
- private isCallerReadScheduled = false;
/**
* The boxes the host watches for screen-edge pans (syncLayoutWatch): each
* element with an enabled one, and the root for one whose band moves with
@@ -359,63 +471,103 @@ export class GestureHost {
/**
* A finger's pointerId → its arena id, once its pointerdown and its
* touchstart are paired. Chromium sends no `touchmove` until a finger has
- * travelled its slop (about 16 px), but sends every `pointermove`, so the
- * finger's movement comes from both channels; and its `pointercancel` is
- * the browser's claim of exactly that finger.
+ * travelled its slop (about 16 px), but sends every `pointermove`, so a
+ * paired finger is sampled from its pointer events (`pointerFed`); and its
+ * `pointercancel` is the browser's claim of exactly that finger.
*/
private readonly fingerPointers = new Map<number, number>();
/** Finger pointerdowns still waiting for their touchstart. */
private readonly pendingPointers = new Map<number, PlacedContact>();
/**
- * Under `inputMode: 'pointer-events'`, where claimed fingers lifted: the
- * `touchend` that follows their `pointerup` is cancelled (FR21).
+ * Where fingers come from their pointer events, where claimed fingers
+ * lifted and when: the `touchend` that follows each `pointerup` is
+ * cancelled (FR21). A record no `touchend` consumed expires
+ * (CLAIMED_LIFT_MS).
*/
- private readonly claimedLifts: PlacedContact[] = [];
+ private readonly claimedLifts: (PlacedContact & {time: number})[] = [];
+ /** The one timer that drops claimed lifts whose `touchend` never came. */
+ private claimedLiftTimer: unknown = null;
+ /** The arena's clock, which the claimed lifts' timer runs on too. */
+ private readonly clock: GestureClock;
/** Fingers still waiting for their pointerdown, by arena id. */
private readonly unpairedTouches = new Map<number, PlacedContact>();
- /** The elements each held contact turned selection off on. */
- private readonly heldSelectionBy = new Map<number, HTMLElement[]>();
private readonly isPrimaryPointerCoarse: () => boolean;
- private readonly coarseQuery: MediaQueryList | null;
- private isWatchingPointer = false;
- private readonly onPointerKindChange = (): void => this.refreshAll();
- /** The last position fed per contact, so one channel's echo is dropped. */
+ /** Whether the host follows `(pointer: coarse)` (no read was passed). */
+ private readonly followsPointer: boolean;
+ /** The last sample fed per contact: a contact's time never runs back. */
private readonly lastFed = new Map<number, TouchSample>();
+ /**
+ * Fingers whose samples come from their pointer events. A finger the
+ * browser reports on both channels is sampled from ONE: the pointer
+ * channel, where its pointerdown paired with its touchstart; touch events
+ * sample only a finger no pointer event reported (no Pointer Events). The
+ * other channel keeps its control duties (cancelling, claiming, the
+ * browser's takeover) but never feeds a sample, so the two copies of one
+ * move cannot both reach a velocity, however far apart they arrive.
+ */
+ private readonly pointerFed = new Set<number>();
/** When a finger was last down or lifted, and where it landed. */
private lastTouch: {readonly target: Node; readonly time: number} | null =
null;
/** Scrollers a recognizer is scrolling itself this frame (ownScroll). */
- private readonly ownedScrolls = new Set<Node>();
+ private readonly ownedScrolls = new Map<Node, number>();
+ /** Numbers each ownScroll call: only the newest one's timer clears it. */
+ private ownScrollCalls = 0;
+ /** Cancels each scroller's pending ownScroll frames. */
+ private readonly ownScrollFrames = new Map<Node, () => void>();
/** The last scroll a finger drove, and when. */
private lastScroll: {readonly scroller: Node; readonly time: number} | null =
null;
+ /** Predicates that hold a touch's target away from every participant. */
+ private readonly touchGates = new Set<(target: Node) => boolean>();
+ /** Who keeps the listeners installed without a registration (retain). */
+ private retainers = 0;
+ /** Told after every touch event that changed the fingers on the screen. */
+ private readonly fingerListeners = new Set<() => void>();
+ /**
+ * Where each finger now on the screen landed, from the last touch event's
+ * `touches` (every finger, whether or not a recognizer tracks it).
+ */
+ private fingerTargets: ReadonlyArray<Node> = [];
private nextId = 1;
private isInstalled = false;
- private readonly inputMode: 'auto' | 'pointer-events';
- private usesTouchEvents = true;
- private swallowDeadline = Number.NEGATIVE_INFINITY;
/**
- * Where the primary pointer is fine: what listens for a press itself (the
- * elements that use a gesture, and the document for delegated consumers),
- * with its removal; whether a press one armed is held, the page's
- * listeners lasting that long; and the pending removal of the click
- * listener a released press kept (FR21, FR24).
+ * Whether the primary pointer is coarse (`spec:AST-094` FR19), read when
+ * something first attaches and kept current while anything is attached.
+ */
+ private isCoarse = false;
+ private stopWatchingPointer: (() => void) | null = null;
+ /** The input stream subscriptions while installed. */
+ private unsubscribers: (() => void)[] = [];
+ /**
+ * Where the primary pointer is fine, each element that uses a gesture
+ * listens for a press itself; the page's listeners last that press (FR24).
*/
- private readonly armed = new Map<EventTarget, () => void>();
+ private readonly armedElements = new Map<Element, () => void>();
private isArmedPress = false;
- private clickRemoval: ReturnType<typeof setTimeout> | null = null;
+ /**
+ * Whether the installed listeners include the cancelable ones (the
+ * document's touchend, contextmenu and the window's click): only while a
+ * participant that can claim is attached (`spec:AST-094` FR20).
+ */
+ private isClaimingInstalled = false;
+ /** The input stream subscriptions syncClaimingListeners keeps. */
+ private claimingUnsubscribers: (() => void)[] = [];
+ private readonly inputMode: 'auto' | 'pointer-events';
+ private usesTouchEvents = true;
constructor(doc: Document, options: GestureHostOptions = {}) {
this.doc = doc;
this.inputMode = options.inputMode ?? 'auto';
+ this.presentedHitTesting = options.presentedHitTesting ?? 'auto';
const environment: GestureEnvironment = {
viewportSize: () => ({
width: doc.defaultView?.innerWidth ?? 0,
height: doc.defaultView?.innerHeight ?? 0,
}),
+ // The writing direction through core's one helper.
isRtl: view =>
- view instanceof Element &&
- doc.defaultView?.getComputedStyle(view).direction === 'rtl',
+ view instanceof Element && isRtlElement(view as HTMLElement),
// A screen-edge pan tells a view within its edge band from any other
// by its box (spec:AST-094 FR18).
viewRect: view => {
@@ -426,29 +578,22 @@ export class GestureHost {
return {left, top, width, height};
},
};
+ this.clock = options.clock ?? browserClock;
this.arena = new GestureArena({
- clock: options.clock ?? browserClock,
+ clock: this.clock,
environment,
onDeferredClick: (touch, allowed) => this.replayClick(touch, allowed),
+ // A press whose decision waited on a timer (a tap waiting on a double
+ // tap) ends here: an armed press stops listening (FR24).
+ onIdle: () => this.releaseArmedPress(),
onTransition: options.onTransition,
});
const view = doc.defaultView;
- const coarseQuery =
- options.isPrimaryPointerCoarse == null &&
- typeof view?.matchMedia === 'function'
- ? view.matchMedia('(pointer: coarse)')
- : null;
+ // A test may pass its own read; otherwise the one coarse-pointer gate,
+ // followed as it changes.
+ this.followsPointer = options.isPrimaryPointerCoarse == null;
this.isPrimaryPointerCoarse =
- options.isPrimaryPointerCoarse ?? (() => coarseQuery?.matches ?? false);
- this.coarseQuery = coarseQuery;
- }
-
- /** Re-derive every element's styles and the host's listeners. */
- private refreshAll(): void {
- for (const [element, registration] of this.registry) {
- this.refresh(element, registration);
- }
- this.syncListeners();
+ options.isPrimaryPointerCoarse ?? (() => isCoarsePointer(view));
}
// --- Attachment ------------------------------------------------------------
@@ -461,7 +606,12 @@ export class GestureHost {
): () => void {
const registration = this.registrationFor(element);
registration.manageStyle = options.manageStyle ?? registration.manageStyle;
- registration.actionGroup = options.actionGroup ?? registration.actionGroup;
+ // An action group while any attachment asks, whatever their order.
+ const asksForGroup = options.actionGroup === true;
+ if (asksForGroup) {
+ registration.actionGroupAsks += 1;
+ registration.actionGroup = true;
+ }
recognizer.view = element;
registration.recognizers.push(recognizer);
recognizer.onEnabledChange = () => {
@@ -482,6 +632,10 @@ export class GestureHost {
this.syncListeners();
return () => {
recognizer.onEnabledChange = null;
+ if (asksForGroup) {
+ registration.actionGroupAsks -= 1;
+ registration.actionGroup = registration.actionGroupAsks > 0;
+ }
if (edgePan != null) {
edgePan.onTouchBehaviorChange = null;
}
@@ -570,14 +724,22 @@ export class GestureHost {
};
/** Attach the view-level touch consumer of an element (a pressable control). */
- attachConsumer(element: Element, consumer: TouchConsumer): () => void {
+ attachConsumer(
+ element: Element,
+ consumer: TouchConsumer,
+ _options: Pick<AttachOptions, 'perEventPointer'> = {},
+ ): () => void {
const registration = this.registrationFor(element);
registration.consumer = consumer;
+ this.refresh(element, registration);
this.syncListeners();
return () => {
if (registration.consumer === consumer) {
registration.consumer = null;
}
+ // A keepsTouch consumer's blocking touchmove goes with it, even while
+ // the element keeps its recognizers.
+ this.refresh(element, registration);
// Even when the element keeps a recognizer: one left disabled keeps
// no listener or observer (FR24).
this.syncListeners();
@@ -586,23 +748,217 @@ export class GestureHost {
}
/**
- * Find consumers of a kind by attribute, one instance per contact. Returns
- * the function that stops it.
+ * @internal The document this host serves.
*/
- addDelegatedConsumer(type: DelegatedConsumerType): () => void {
- this.delegated.add(type);
- this.syncListeners();
- return () => {
- this.delegated.delete(type);
- this.syncListeners();
+ get document(): Document {
+ return this.doc;
+ }
+
+ /**
+ * @internal Whether a recognizer owns the touch with this Touch Events
+ * `identifier`, so the browser must not pan it (pageHold.ts asks).
+ */
+ isTouchClaimed(identifier: number): boolean {
+ const id = this.touchIds.get(identifier);
+ return id != null && this.arena.isClaimed(id);
+ }
+
+ /**
+ * An element's box where it is drawn: the box the engine reports, moved
+ * by the compositor animations of it and its ancestors on engines that
+ * report and hit-test those where they started (iOS WebKit). Elsewhere
+ * `getBoundingClientRect` already reports the drawn box. Press trackers
+ * read their bounds through it.
+ */
+ presentedRect(element: Element): PressBounds {
+ const box = element.getBoundingClientRect();
+ if (!this.hitTestsLayout()) {
+ return box;
+ }
+ const {x, y} = presentedOffsetOf(element);
+ if (x === 0 && y === 0) {
+ return box;
+ }
+ return {
+ left: box.left + x,
+ top: box.top + y,
+ right: box.right + x,
+ bottom: box.bottom + y,
};
}
+ /** Whether this engine hit-tests a compositor-moved element at layout. */
+ private hitTestsLayout(): boolean {
+ return (
+ this.presentedHitTesting === 'always' ||
+ (this.presentedHitTesting === 'auto' && isIosWebKit(this.doc.defaultView))
+ );
+ }
+
+ /**
+ * Where a contact lands among what is drawn. iOS WebKit hit-tests an
+ * element that a compositor animation moves where the animation started:
+ * a finger on a settling sheet lands on whatever sat under the sheet's
+ * start (the scrim, which closes it), and a finger where the sheet was
+ * lands on the sheet. UIKit keeps an interruptible animation hit-testable
+ * where it is drawn (UIViewPropertyAnimator). The touch goes to what was
+ * drawn under the finger when it landed (`time`, its event's timestamp),
+ * even when a busy main thread hands it over later, and content that slid
+ * under the finger since takes nothing (`spec:AST-094` FR11).
+ */
+ private presentedTarget(
+ native: EventTarget | null,
+ x: number,
+ y: number,
+ time: number,
+ ): EventTarget | null {
+ if (!this.hitTestsLayout()) {
+ return native;
+ }
+ const movers = presentedElements().filter(element => {
+ if (!element.isConnected || element.ownerDocument !== this.doc) {
+ return false;
+ }
+ const {x: dx, y: dy} = presentedOffsetOf(element);
+ return Math.abs(dx) >= 0.5 || Math.abs(dy) >= 0.5;
+ });
+ if (movers.length === 0) {
+ return native;
+ }
+ // One style write per mover makes the engine hit-test it where it is
+ // drawn now; the hit test below flushes them. The engine then gets
+ // z-order, pointer-events and clipping right, which no box math would.
+ resolvePresented(movers);
+ let hit = this.drawnAt(x, y);
+ // A mover kept going while the touch waited for the main thread: what
+ // was under the finger when it landed is now that far along. A timestamp
+ // on another clock, or older than a second, is not corrected.
+ const age = (this.doc.defaultView?.performance.now() ?? time) - time;
+ if (age > 0 && age < 1000) {
+ const movedSince = (mover: Element) => {
+ const then = presentedOffsetOf(mover, time);
+ return Math.abs(then.x) >= 0.5 || Math.abs(then.y) >= 0.5 ? then : null;
+ };
+ const now = hit;
+ const under =
+ now == null
+ ? undefined
+ : movers.find(mover => containsAlongFlatTree(mover, now));
+ let landedOnMover = false;
+ for (const mover of movers) {
+ const then = movedSince(mover);
+ if (then == null) {
+ continue;
+ }
+ const landed = this.drawnAt(x - then.x, y - then.y);
+ if (landed != null && containsAlongFlatTree(mover, landed)) {
+ hit = landed;
+ landedOnMover = true;
+ break;
+ }
+ }
+ // Content that slid under the finger after it landed takes nothing:
+ // the touch goes to what was there, beneath it.
+ if (!landedOnMover && under != null && movedSince(under) != null) {
+ hit = this.drawnBeneath(x, y, movers);
+ }
+ }
+ if (hit == null || hit === native) {
+ return native;
+ }
+ const found = hit;
+ const node = native instanceof Node ? native : null;
+ const isAboutMover = movers.some(
+ mover =>
+ containsAlongFlatTree(mover, found) ||
+ (node != null && containsAlongFlatTree(mover, node)),
+ );
+ return isAboutMover ? found : native;
+ }
+
+ /** What is drawn at a point beneath every mover. */
+ private drawnBeneath(
+ x: number,
+ y: number,
+ movers: ReadonlyArray<Element>,
+ ): Element | null {
+ if (typeof this.doc.elementsFromPoint !== 'function') {
+ return null;
+ }
+ return (
+ this.doc
+ .elementsFromPoint(x, y)
+ .find(
+ element =>
+ !movers.some(mover => containsAlongFlatTree(mover, element)),
+ ) ?? null
+ );
+ }
+
+ /** What is drawn at a point, inside open shadow roots too. */
+ private drawnAt(x: number, y: number): Element | null {
+ let hit = this.doc.elementFromPoint(x, y);
+ // The document answers a shadow host for anything inside its open root:
+ // descend to what is drawn there.
+ while (hit?.shadowRoot != null) {
+ const inner = hit.shadowRoot.elementFromPoint(x, y);
+ if (inner == null || inner === hit) {
+ break;
+ }
+ hit = inner;
+ }
+ return hit;
+ }
+
+ /** The browser took these touches (a scroll): no click of ours for them. */
+ private browserTook(ids: ReadonlyArray<number>, time: number): void {
+ for (const id of ids) {
+ this.retargeted.delete(id);
+ }
+ this.arena.browserTookOver(ids, time);
+ }
+
+ /**
+ * The click a retargeted tap earned, on what was drawn under the finger.
+ * The engine's own click would hit the start position, so the caller
+ * cancels it (or the click guard drops it, a late one included) and this one
+ * is the tap's single activation.
+ */
+ private clickRetargeted(target: EventTarget, x: number, y: number): void {
+ const view = this.doc.defaultView;
+ if (!(target instanceof Element) || !target.isConnected || view == null) {
+ return;
+ }
+ armClickGuard(this.doc);
+ if (
+ target instanceof view.HTMLElement &&
+ target.matches('input, textarea, select, [contenteditable]')
+ ) {
+ target.focus();
+ }
+ withoutClickGuard(() =>
+ target.dispatchEvent(
+ new view.MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ detail: 1,
+ clientX: x,
+ clientY: y,
+ }),
+ ),
+ );
+ }
+
/**
* Re-derive an element's styles and the host's listeners after its
* recognizers' options or its consumer's enabled state changed.
*/
update(element: Element): void {
+ if (!this.followsPointer) {
+ // A read passed in (a test's) is not followed: an update reads it again.
+ this.isCoarse = this.isPrimaryPointerCoarse();
+ }
const registration = this.registry.get(element);
if (registration != null) {
this.refresh(element, registration);
@@ -639,77 +995,165 @@ export class GestureHost {
*/
isScrollBraking(
node: Node,
- window: number = UIKIT_GESTURES.press.scrollBrake.value,
+ window: number = UIKIT_PRESS.scrollBrake.value,
): boolean {
const last = this.lastScroll;
return (
last != null &&
this.arena.now() - last.time < window &&
- last.scroller.contains(node)
+ containsAlongFlatTree(last.scroller, node)
+ );
+ }
+
+ /**
+ * @internal Keep the host's listeners installed until the returned
+ * function runs, with no recognizer attached (fingerScroll.ts reads the
+ * finger record meanwhile).
+ */
+ retain(): () => void {
+ this.retainers += 1;
+ // A watch is not an attach: no warning where the pointer is fine.
+ this.watchPointer();
+ this.syncListeners();
+ let isRetained = true;
+ return () => {
+ if (!isRetained) {
+ return;
+ }
+ isRetained = false;
+ this.retainers -= 1;
+ this.uninstallIfIdle();
+ };
+ }
+
+ /**
+ * @internal Call `listener` after each touch event the host hears, once
+ * the finger record is up to date. Returns the unsubscribe.
+ */
+ onFingersChange(listener: () => void): () => void {
+ this.fingerListeners.add(listener);
+ return () => {
+ this.fingerListeners.delete(listener);
+ };
+ }
+
+ /** @internal Whether a finger that landed inside `node` is down now. */
+ isFingerDownIn(node: Node): boolean {
+ // Along the flat tree: a finger on content inside an open shadow root is
+ // in the scroller around that root.
+ return this.fingerTargets.some(target =>
+ containsAlongFlatTree(node, target),
);
}
private registrationFor(element: Element): Registration {
+ this.watchPointer();
let registration = this.registry.get(element);
if (registration == null) {
registration = {
recognizers: [],
consumer: null,
- touchMoveListener: null,
- touchEndListener: null,
+ hasTouchEndListener: false,
+ hasTouchMoveListener: false,
savedStyle: new Map(),
authorTouchAction: null,
manageStyle: true,
actionGroup: false,
+ actionGroupAsks: 0,
};
this.registry.set(element, registration);
}
return registration;
}
+ /** Whether anything attached could take input. */
+ private needsInput(): boolean {
+ return this.registry.size > 0 || this.retainers > 0;
+ }
+
private refresh(element: Element, registration: Registration): void {
if (registration.manageStyle && element instanceof HTMLElement) {
this.applyStyle(element, registration);
}
- // For every pointer (FR43): a finger's claim cancels its moves here
- // (FR19), a listener FR24 counts apart from the one an element keeps for
- // its press.
- const needsListener = registration.recognizers.some(
- r => r.isEnabled && claimsWhileMoving(r),
- );
- if (needsListener && registration.touchMoveListener == null) {
- const listener: EventListener = event =>
- this.cancelIfClaimed(event as TouchEvent);
- registration.touchMoveListener = listener;
- element.addEventListener('touchmove', listener, {passive: false});
- } else if (!needsListener && registration.touchMoveListener != null) {
- element.removeEventListener('touchmove', registration.touchMoveListener);
- registration.touchMoveListener = null;
- }
- // Pointer Events only: a claimed finger's touchend is not the host's
- // own document listener's to cancel, so the element cancels it.
+ this.syncTouchMoveListener(element, registration);
+ }
+
+ /**
+ * The element's blocking `touchmove`. For every pointer a claiming
+ * recognizer keeps it: a finger's claim cancels its moves here (FR19), a
+ * listener FR24 counts outside the one-listener budget a fine pointer's
+ * element keeps for its press (syncArmed). A kept press needs it only
+ * while a press is held: a phone's before every touch (Safari honours a
+ * blocking listener only when registered before the touch began), a fine
+ * pointer's only during an armed press, whose `pointerdown` comes before
+ * the touch it brings (FR24).
+ */
+ private syncTouchMoveListener(
+ element: Element,
+ registration: Registration,
+ ): void {
+ // Where fingers come from their pointer events (Pointer Events input, or
+ // a window with no ontouchstart), a claimed finger's touchend is not the
+ // host's own document listener's to cancel, so the element cancels it
+ // (FR21). Under a coarse pointer always: touch emulation turned on after
+ // load hides ontouchstart yet sends touches. Under a fine one wherever
+ // the browser sends Touch Events, as a touchscreen laptop does (FR43);
+ // elsewhere no touchend ever comes, and the element keeps no listener
+ // (FR24).
const needsEndListener =
- this.inputMode === 'pointer-events' &&
- registration.recognizers.some(r => r.isEnabled && r.acceptsTouchInput);
- if (needsEndListener && registration.touchEndListener == null) {
- const listener: EventListener = event =>
- this.cancelClaimedLift(event as TouchEvent);
- registration.touchEndListener = listener;
- element.addEventListener('touchend', listener, {passive: false});
- } else if (!needsEndListener && registration.touchEndListener != null) {
- element.removeEventListener('touchend', registration.touchEndListener);
- registration.touchEndListener = null;
+ this.readsFingersFromPointerEvents() &&
+ (this.isCoarse || this.sendsTouchEvents()) &&
+ registration.recognizers.some(
+ recognizer =>
+ recognizer.isEnabled && internals(recognizer).acceptsTouchInput,
+ );
+ if (needsEndListener && !registration.hasTouchEndListener) {
+ element.addEventListener('touchend', this.onClaimedTouchEnd, {
+ passive: false,
+ });
+ registration.hasTouchEndListener = true;
+ } else if (!needsEndListener && registration.hasTouchEndListener) {
+ element.removeEventListener('touchend', this.onClaimedTouchEnd);
+ registration.hasTouchEndListener = false;
+ }
+ const needsListener =
+ registration.recognizers.some(
+ recognizer => recognizer.isEnabled && claimsWhileMoving(recognizer),
+ ) ||
+ (registration.consumer?.keepsTouch != null &&
+ registration.consumer.isEnabled?.() !== false &&
+ (this.isCoarse || this.isArmedPress));
+ // The blocking listener sits on the element itself (FR19: a scroll that
+ // starts elsewhere never waits on it), but every element shares the
+ // host's one handler, which routes through the arena.
+ if (needsListener && !registration.hasTouchMoveListener) {
+ element.addEventListener('touchmove', this.onBlockingTouchMove, {
+ passive: false,
+ });
+ registration.hasTouchMoveListener = true;
+ } else if (!needsListener && registration.hasTouchMoveListener) {
+ element.removeEventListener('touchmove', this.onBlockingTouchMove);
+ registration.hasTouchMoveListener = false;
}
}
private applyStyle(element: HTMLElement, registration: Registration): void {
- // Where no attached recognizer is enabled the host manages no style: the
- // element keeps its own touch-action, and any value set before is
- // restored (FR24). Every pointer gets it: a touchscreen laptop's finger
- // as a phone's (spec:AST-094 FR43).
- const enabled = registration.recognizers.filter(r => r.isEnabled);
- const style: GestureHostStyle =
- enabled.length > 0 ? gestureHostStyle(enabled) : {};
+ // A disabled recognizer leaves the browser everything (FR24).
+ // Every pointer gets it: a touchscreen laptop's finger as a phone's (FR43).
+ const active = registration.recognizers.filter(
+ recognizer => recognizer.isEnabled,
+ );
+ let style: GestureHostStyle =
+ active.length > 0 ? gestureHostStyle(active) : {};
+ // A control that keeps its touch (a stepper's hold-repeat) takes taps in
+ // quick succession: the browser's double-tap zoom goes, as for a tap
+ // recognizer (`spec:AST-094` FR18), for every pointer (FR43).
+ if (
+ style.touchAction == null &&
+ registration.consumer?.keepsTouch != null
+ ) {
+ style = {...style, touchAction: 'manipulation'};
+ }
for (const key of Object.keys(
STYLE_PROPERTIES,
) as (keyof GestureHostStyle)[]) {
@@ -804,8 +1248,9 @@ export class GestureHost {
return;
}
this.isCallerReadScheduled = true;
- inNextFrame(this.doc.defaultView, () => {
+ this.cancelCallerRead = inNextFrame(this.doc.defaultView, () => {
this.isCallerReadScheduled = false;
+ this.cancelCallerRead = null;
const pending: [HTMLElement, Registration][] = [];
for (const candidate of this.pendingCallerReads) {
const registration = this.registry.get(candidate);
@@ -834,60 +1279,99 @@ export class GestureHost {
private cleanup(element: Element, registration: Registration): void {
if (registration.recognizers.length > 0 || registration.consumer != null) {
+ // What stays may take nothing (only disabled recognizers): FR24.
+ this.syncListeners();
return;
}
- if (registration.touchMoveListener != null) {
- element.removeEventListener('touchmove', registration.touchMoveListener);
+ if (registration.hasTouchEndListener) {
+ element.removeEventListener('touchend', this.onClaimedTouchEnd);
+ registration.hasTouchEndListener = false;
}
- if (registration.touchEndListener != null) {
- element.removeEventListener('touchend', registration.touchEndListener);
- registration.touchEndListener = null;
+ if (registration.hasTouchMoveListener) {
+ element.removeEventListener('touchmove', this.onBlockingTouchMove);
}
this.registry.delete(element);
- this.syncListeners();
+ this.uninstallIfIdle();
}
/**
* Listen only while something could take a touch now (`spec:AST-094`
- * FR24, FR43): where the primary pointer is coarse, while an enabled
- * recognizer or consumer, or a delegated consumer, is attached; where it is
- * fine, only during a press something armed (syncArmed). Otherwise no page
- * listener is registered, so an idle page and a disabled control pay
- * nothing.
+ * FR24, FR43): where the primary pointer is coarse, an enabled recognizer
+ * or consumer, or a finger-scroll watch; where it is fine, only during a
+ * press an element armed (syncArmed). Otherwise no document listener is
+ * registered, so an idle page and a disabled control pay nothing.
*/
private syncListeners(): void {
this.syncLayoutWatch();
- // The primary pointer can change (a tablet's keyboard attached or
- // removed): while anything is attached, styles and listeners follow it.
- // Nothing touch-related stays once the last attachment goes (FR24).
- const hasAttachments = this.registry.size > 0 || this.delegated.size > 0;
- if (hasAttachments && !this.isWatchingPointer) {
- this.coarseQuery?.addEventListener?.('change', this.onPointerKindChange);
- this.isWatchingPointer = true;
- } else if (!hasAttachments && this.isWatchingPointer) {
- this.coarseQuery?.removeEventListener?.(
- 'change',
- this.onPointerKindChange,
- );
- this.isWatchingPointer = false;
- }
this.syncArmed();
if (this.shouldListen()) {
this.install();
- } else if (this.isInstalled) {
+ this.syncClaimingListeners();
+ } else {
this.uninstall();
}
+ this.syncMoverBlocking();
}
- private shouldListen(): boolean {
- if (!this.isPrimaryPointerCoarse()) {
- return this.isArmedPress;
+ /**
+ * Safari honours a blocking `touchmove` only where it was registered before
+ * the touch began, on the engine's own target, and on iOS WebKit a finger
+ * on an element a compositor animation moves lands, for the engine, on
+ * whatever sits under the motion's start (see presentedTarget). So while an
+ * element a recognizer that claims moving touches lives in (or around) is
+ * moving, the blocking listener subscribes to the window's capturing
+ * `touchmove` through the shared input stream with `{cancels: true}`,
+ * which sees every touch on the page whatever the engine targets and makes
+ * that one listener non-passive (`spec:AST-094` FR19;
+ * architecture:react-component-runtime INV13). It leaves when the motion
+ * ends: only while it is subscribed does a scroll starting anywhere wait on
+ * the main thread.
+ */
+ private syncMoverBlocking(): void {
+ const isWatching = this.isInstalled && this.hitTestsLayout();
+ if (isWatching && this.stopWatchingMovers == null) {
+ this.stopWatchingMovers = watchPresentedElements(() =>
+ this.syncMoverBlocking(),
+ );
+ } else if (!isWatching && this.stopWatchingMovers != null) {
+ this.stopWatchingMovers();
+ this.stopWatchingMovers = null;
+ }
+ const needed =
+ isWatching &&
+ presentedElements().some(mover =>
+ this.hasClaimingRecognizerAround(mover),
+ );
+ if (needed === (this.stopBlockingForMovers != null)) {
+ return;
}
- if (this.delegated.size > 0) {
- return true;
+ const view = this.doc.defaultView;
+ if (needed && view != null) {
+ this.stopBlockingForMovers = subscribeInput(
+ view,
+ 'touchmove',
+ this.onBlockingTouchMove,
+ {cancels: true},
+ );
+ } else if (!needed) {
+ this.stopBlockingForMovers?.();
+ this.stopBlockingForMovers = null;
}
- for (const registration of this.registry.values()) {
- if (isServed(registration)) {
+ }
+
+ /** Whether a recognizer that claims moving touches lives in or around `mover`. */
+ private hasClaimingRecognizerAround(mover: Element): boolean {
+ if (!mover.isConnected || mover.ownerDocument !== this.doc) {
+ return false;
+ }
+ for (const [element, registration] of this.registry) {
+ if (
+ (containsAlongFlatTree(mover, element) ||
+ containsAlongFlatTree(element, mover)) &&
+ registration.recognizers.some(
+ recognizer => recognizer.isEnabled && claimsWhileMoving(recognizer),
+ )
+ ) {
return true;
}
}
@@ -897,56 +1381,56 @@ export class GestureHost {
/**
* Where the primary pointer is fine, each element with an enabled
* recognizer or press consumer listens for a press itself: one passive
- * `pointerdown` listener, in the capture phase, so the outermost one hears
- * a press first and serves every recognizer on its path. Delegated
- * consumer types, which have no element, arm the document once. A press
- * installs the host's page listeners for as long as its contacts last
- * (`spec:AST-094` FR24, FR43). Where the primary pointer is coarse the
- * page's listeners serve every press, and nothing is armed.
+ * `pointerdown` listener on the element. The host's page listeners come at
+ * that press and go once its contacts end and the arena drops their last
+ * record (onIdle: a decision that waited on a timer), so an idle page has none
+ * (`spec:AST-094` FR24, FR43). A finger on a touchscreen whose primary
+ * pointer is fine sends its `pointerdown` before its `touchstart`, so the
+ * host hears both.
*/
private syncArmed(): void {
- const wanted = new Set<EventTarget>();
- if (!this.isPrimaryPointerCoarse()) {
+ const wanted = new Set<Element>();
+ if (!this.isCoarse) {
for (const [element, registration] of this.registry) {
- if (isServed(registration)) {
+ const consumer = registration.consumer;
+ if (
+ registration.recognizers.some(recognizer => recognizer.isEnabled) ||
+ (consumer != null && consumer.isEnabled?.() !== false)
+ ) {
wanted.add(element);
}
}
- if (this.delegated.size > 0) {
- wanted.add(this.doc);
- }
}
- for (const [target, disarm] of [...this.armed]) {
- if (!wanted.has(target)) {
- disarm();
- this.armed.delete(target);
+ for (const [element, release] of this.armedElements) {
+ if (!wanted.has(element)) {
+ release();
+ this.armedElements.delete(element);
}
}
- for (const target of wanted) {
- if (this.armed.has(target)) {
+ for (const element of wanted) {
+ if (this.armedElements.has(element)) {
continue;
}
- target.addEventListener(
+ element.addEventListener(
'pointerdown',
this.onArmedPress,
PASSIVE_CAPTURE,
);
- this.armed.set(target, () => {
- target.removeEventListener(
+ this.armedElements.set(element, () => {
+ element.removeEventListener(
'pointerdown',
this.onArmedPress,
PASSIVE_CAPTURE,
);
});
}
+ if (wanted.size === 0 && this.isArmedPress) {
+ this.isArmedPress = false;
+ this.syncKeptPresses();
+ }
}
- /**
- * A press on something armed, where the primary pointer is fine: a
- * mouse's primary button, a pen, or a finger. The page's listeners come
- * for this press, and the press goes on to them, its capture phase on the
- * page being over.
- */
+ /** A press on an armed element, a mouse's primary button, a pen or a finger: listen for this press. */
private readonly onArmedPress = (event: Event): void => {
const press = event as PointerEvent;
if (
@@ -957,95 +1441,250 @@ export class GestureHost {
return;
}
this.isArmedPress = true;
+ this.syncKeptPresses();
this.install();
+ // A finger's or a pen's press brings the cancelable touchend and the
+ // contextmenu canceller, as wherever the host installs, so a claimed
+ // lift clicks nothing and a claimed hold opens no browser menu (FR21). A
+ // mouse's press needs neither.
+ if (press.pointerType !== 'mouse') {
+ this.syncClaimingListeners();
+ }
+ // The window's capture phase is over for this event: hand it on.
this.onPointerDown(press);
- // A mouse's or a pen's press that nothing took has nothing to wait for;
- // a finger's contact begins at its touchstart, which comes next.
- if (press.pointerType !== 'touch') {
- this.releaseArmedPress();
- }
};
- /**
- * After a contact ends: once no contact of the press that armed the page's
- * listeners is down, they go (FR24). A recognizer still deciding after the
- * lift needs no input; the click it may owe keeps its listener
- * (releaseClickListener).
- */
+ /** A kept press's blocking `touchmove` follows the armed press (syncTouchMoveListener). */
+ private syncKeptPresses(): void {
+ for (const [element, registration] of this.registry) {
+ if (registration.consumer?.keepsTouch != null) {
+ this.syncTouchMoveListener(element, registration);
+ }
+ }
+ }
+
+ /** After a contact ends: an armed press that is over stops listening. */
private releaseArmedPress(): void {
- if (
- this.isArmedPress &&
- !this.arena.touches.some(
- touch => touch.phase !== 'ended' && touch.phase !== 'cancelled',
- )
- ) {
- this.isArmedPress = false;
- this.syncListeners();
+ if (!this.isArmedPress) {
+ return;
+ }
+ queueMicrotask(() => {
+ if (this.isArmedPress && this.arena.touches.length === 0) {
+ this.isArmedPress = false;
+ this.syncKeptPresses();
+ this.syncListeners();
+ }
+ });
+ }
+
+ /** With nothing attached, stop listening and stop following the pointer. */
+ private uninstallIfIdle(): void {
+ this.syncListeners();
+ if (this.registry.size === 0 && this.retainers === 0) {
+ this.uninstall();
+ this.stopWatchingPointer?.();
+ this.stopWatchingPointer = null;
+ this.releaseWhenIdle();
}
}
/**
- * The click listener outlives the page's others while the swallower is
- * armed: a claimed lift's click comes after its pointerup or touchend
- * (`spec:AST-094` FR21; FR24 counts it as press work). It goes when that
- * window closes, unless the host listens again by then.
+ * In the microtask after the last detach, unless something attached again
+ * in the same task (a component that remounts mid-press keeps its notes):
+ * nothing the host holds outlives it, no note and no pending frame or
+ * timer (`spec:AST-094` FR24).
*/
- private releaseClickListener(): void {
+ private releaseWhenIdle(): void {
+ queueMicrotask(() => {
+ if (this.registry.size > 0 || this.retainers > 0) {
+ return;
+ }
+ this.cancelledFingers.clear();
+ this.clearClaimedLifts();
+ this.cancelCallerRead?.();
+ this.cancelCallerRead = null;
+ this.isCallerReadScheduled = false;
+ this.pendingCallerReads.clear();
+ for (const cancel of this.ownScrollFrames.values()) {
+ cancel();
+ }
+ this.ownScrollFrames.clear();
+ this.ownedScrolls.clear();
+ });
+ }
+
+ /** Read the primary pointer, and follow it while anything is attached. */
+ private watchPointer(): void {
+ if (this.stopWatchingPointer != null) {
+ return;
+ }
const view = this.doc.defaultView;
- if (this.clickRemoval != null) {
- clearTimeout(this.clickRemoval);
- this.clickRemoval = null;
+ this.isCoarse = this.isPrimaryPointerCoarse();
+ this.stopWatchingPointer = this.followsPointer
+ ? watchCoarsePointer(view, isCoarse => this.pointerChanged(isCoarse))
+ : () => {};
+ }
+
+ /**
+ * The primary pointer turned coarse or fine (a tablet docking a mouse):
+ * install or remove everything, as if each attach happened now.
+ */
+ private pointerChanged(isCoarse: boolean): void {
+ if (isCoarse === this.isCoarse) {
+ return;
}
- const remaining = this.swallowDeadline - browserClock.now();
- if (view == null || remaining < 0) {
- view?.removeEventListener('click', this.onClick, ACTIVE_CAPTURE);
+ this.isCoarse = isCoarse;
+ if (!isCoarse) {
+ this.cancelEverything(this.arena.now());
+ }
+ for (const [element, registration] of this.registry) {
+ this.refresh(element, registration);
+ }
+ this.syncListeners();
+ }
+
+ /**
+ * 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).
+ */
+ private hasClaimer(): boolean {
+ for (const registration of this.registry.values()) {
+ const consumer = registration.consumer;
+ if (
+ (consumer != null && consumer.isEnabled?.() !== false) ||
+ registration.recognizers.some(
+ recognizer => recognizer.isEnabled && recognizer.claimsTouches,
+ )
+ ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Keeps the touchend cancelable, and the contextmenu subscription on,
+ * only while a claimer is attached; with only watchers the touchend is
+ * passive and the contextmenu is off. Clicks are the click guard's
+ * (utils/clickGuard.ts), whose one listener a window gets only once a
+ * gesture first arms it.
+ */
+ private syncClaimingListeners(): void {
+ if (!this.isInstalled) {
+ return;
+ }
+ const isClaiming = this.hasClaimer();
+ if (isClaiming === this.isClaimingInstalled) {
return;
}
- this.clickRemoval = setTimeout(() => {
- this.clickRemoval = null;
- if (!this.isInstalled) {
- view.removeEventListener('click', this.onClick, ACTIVE_CAPTURE);
+ const view = this.doc.defaultView;
+ for (const unsubscribe of this.claimingUnsubscribers.splice(0)) {
+ unsubscribe();
+ }
+ if (view != null) {
+ if (this.inputMode === 'auto') {
+ this.claimingUnsubscribers.push(
+ subscribeInput(view, 'touchend', this.onTouchEnd, {
+ cancels: isClaiming,
+ }),
+ );
+ }
+ if (isClaiming) {
+ this.claimingUnsubscribers.push(
+ subscribeInput(view, 'contextmenu', this.onContextMenu, {
+ cancels: true,
+ }),
+ );
+ }
+ }
+ this.isClaimingInstalled = isClaiming;
+ }
+
+ private shouldListen(): boolean {
+ if (!this.needsInput()) {
+ return false;
+ }
+ // A retainer (a finger-scroll watch) listens only where the pointer is
+ // coarse: it follows a finger's scroll, which a fine pointer's page
+ // leaves to the browser (FR24).
+ if (this.isCoarse && this.retainers > 0) {
+ return true;
+ }
+ let isUsed = false;
+ for (const registration of this.registry.values()) {
+ const consumer = registration.consumer;
+ if (
+ (consumer != null && consumer.isEnabled?.() !== false) ||
+ registration.recognizers.some(recognizer => recognizer.isEnabled)
+ ) {
+ isUsed = true;
+ break;
}
- }, remaining + 1);
+ }
+ // Where the primary pointer is fine, only while a press an element armed
+ // is held (syncArmed, FR24, FR43).
+ return isUsed && (this.isCoarse || this.isArmedPress);
}
// --- Listeners -------------------------------------------------------------
private install(): void {
- if (this.isInstalled) {
+ this.watchPointer();
+ if (!this.needsInput()) {
return;
}
- if (this.clickRemoval != null) {
- clearTimeout(this.clickRemoval);
- this.clickRemoval = null;
+ if (this.isInstalled) {
+ return;
}
const view = this.doc.defaultView;
this.isInstalled = true;
this.usesTouchEvents =
this.inputMode === 'auto' && view != null && 'ontouchstart' in view;
- const doc = this.doc;
- // Pointer Events only: a finger comes from its pointer events alone. A
- // browser that has Touch Events still sends them for the same finger, and
- // reading both would track it twice (a long press needs one touch).
- if (this.inputMode === 'auto') {
- doc.addEventListener('touchstart', this.onTouchStart, PASSIVE_CAPTURE);
- doc.addEventListener('touchmove', this.onTouchMove, PASSIVE_CAPTURE);
- doc.addEventListener('touchend', this.onTouchEnd, ACTIVE_CAPTURE);
- doc.addEventListener('touchcancel', this.onTouchCancel, PASSIVE_CAPTURE);
- }
- doc.addEventListener('pointerdown', this.onPointerDown, PASSIVE_CAPTURE);
- doc.addEventListener('pointermove', this.onPointerMove, PASSIVE_CAPTURE);
- doc.addEventListener('pointerup', this.onPointerUp, PASSIVE_CAPTURE);
- doc.addEventListener(
- 'pointercancel',
- this.onPointerCancel,
- PASSIVE_CAPTURE,
- );
- doc.addEventListener('contextmenu', this.onContextMenu, ACTIVE_CAPTURE);
- doc.addEventListener('scroll', this.onScroll, PASSIVE_CAPTURE);
- doc.addEventListener('visibilitychange', this.onVisibilityChange);
- view?.addEventListener('click', this.onClick, ACTIVE_CAPTURE);
- view?.addEventListener('blur', this.onBlur);
+ if (view == null) {
+ // A document without a window receives no input.
+ return;
+ }
+ // The window's capture phase, through the shared input stream
+ // (utils/inputStream.ts): ahead of any document listener, so an app's
+ // window-capture stopPropagation, or a document-capture
+ // stopImmediatePropagation registered first, no longer hides a touch
+ // from the recognizers. A recognizer that must claim mid-gesture still
+ // needs the touch to reach its element, where its blocking touchmove
+ // sits. Only the listeners that cancel are non-passive, and only while a
+ // claimer is attached (syncClaimingListeners); none of them is a
+ // touchstart or touchmove, so none of them holds a scroll.
+ this.unsubscribers = [
+ // Pointer Events only: a finger comes from its pointer events alone. A
+ // browser that has Touch Events still sends them for the same finger,
+ // and reading both would track it twice (a long press needs one touch).
+ ...(this.inputMode === 'auto'
+ ? [
+ subscribeInput(view, 'touchstart', this.onTouchStart),
+ subscribeInput(view, 'touchmove', this.onTouchMove),
+ subscribeInput(view, 'touchcancel', this.onTouchCancel),
+ ]
+ : []),
+ subscribeInput(view, 'pointerdown', this.onPointerDown),
+ subscribeInput(view, 'pointermove', this.onPointerMove),
+ subscribeInput(view, 'pointerup', this.onPointerUp),
+ subscribeInput(view, 'pointercancel', this.onPointerCancel),
+ subscribeInput(view, 'scroll', this.onScroll),
+ subscribeInput(view, 'visibilitychange', this.onVisibilityChange),
+ // The window's own blur; an element's blur (a Node's) reaches the
+ // window's capture phase too and means nothing here.
+ subscribeInput(view, 'blur', event => {
+ if (!(event.target instanceof view.Node)) {
+ this.onBlur();
+ }
+ }),
+ ];
+ // Passive until a claimer is attached (syncClaimingListeners).
+ this.isClaimingInstalled = false;
+ this.claimingUnsubscribers =
+ this.inputMode === 'auto'
+ ? [subscribeInput(view, 'touchend', this.onTouchEnd)]
+ : [];
}
private uninstall(): void {
@@ -1053,26 +1692,20 @@ export class GestureHost {
return;
}
this.isInstalled = false;
- const doc = this.doc;
- const view = doc.defaultView;
- doc.removeEventListener('touchstart', this.onTouchStart, PASSIVE_CAPTURE);
- doc.removeEventListener('touchmove', this.onTouchMove, PASSIVE_CAPTURE);
- doc.removeEventListener('touchend', this.onTouchEnd, ACTIVE_CAPTURE);
- doc.removeEventListener('touchcancel', this.onTouchCancel, PASSIVE_CAPTURE);
- doc.removeEventListener('pointerdown', this.onPointerDown, PASSIVE_CAPTURE);
- doc.removeEventListener('pointermove', this.onPointerMove, PASSIVE_CAPTURE);
- doc.removeEventListener('pointerup', this.onPointerUp, PASSIVE_CAPTURE);
- doc.removeEventListener(
- 'pointercancel',
- this.onPointerCancel,
- PASSIVE_CAPTURE,
- );
- doc.removeEventListener('contextmenu', this.onContextMenu, ACTIVE_CAPTURE);
- doc.removeEventListener('scroll', this.onScroll, PASSIVE_CAPTURE);
- doc.removeEventListener('visibilitychange', this.onVisibilityChange);
- this.releaseClickListener();
- view?.removeEventListener('blur', this.onBlur);
+ // Unheard from here on: no fingers to keep.
+ this.fingerTargets = [];
+ this.isClaimingInstalled = false;
+ for (const unsubscribe of [
+ ...this.unsubscribers.splice(0),
+ ...this.claimingUnsubscribers.splice(0),
+ ]) {
+ unsubscribe();
+ }
this.cancelEverything(this.arena.now());
+ // A claimed lift's note stays: an armed press's listeners go in the
+ // microtask after its pointerup, the touchend comes after that microtask
+ // in the same task (iOS and WebKit), and the element's own listener still
+ // takes it (noteClaimedLift).
this.lastTouch = null;
this.lastScroll = null;
}
@@ -1082,7 +1715,7 @@ export class GestureHost {
/**
* The recognizers on the path from `target` to the document, innermost
* first, and (for a contact) its consumer: the innermost element with an
- * attached consumer or a delegated consumer type's attribute.
+ * attached consumer.
*/
private participantsAt(
target: unknown,
@@ -1090,9 +1723,17 @@ export class GestureHost {
): {
recognizers: GestureRecognizer[];
consumer: TouchConsumer | null;
+ consumerElement: Element | null;
} {
const recognizers: GestureRecognizer[] = [];
let consumer: TouchConsumer | null = null;
+ let consumerElement: Element | null = null;
+ if (
+ target instanceof Node &&
+ [...this.touchGates].some(gate => gate(target))
+ ) {
+ return {recognizers, consumer, consumerElement};
+ }
let hasConsumerOwner = pointerType == null;
for (
let node: Node | null = target instanceof Node ? target : null;
@@ -1104,29 +1745,120 @@ export class GestureHost {
}
const registration = this.registry.get(node);
if (registration != null) {
+ // Every pointer (`spec:AST-094` FR43), hover included.
recognizers.push(...registration.recognizers);
}
if (hasConsumerOwner || pointerType == null) {
continue;
}
+ // A press consumer takes every pointer's press, a mouse's too
+ // (`spec:AST-094` FR43, DEC-21).
if (registration?.consumer != null) {
consumer = registration.consumer;
+ consumerElement = node;
hasConsumerOwner = true;
continue;
}
- for (const type of this.delegated) {
- if (node.hasAttribute(type.attribute)) {
- consumer = type.create(node, pointerType);
- hasConsumerOwner = true;
- break;
- }
+ }
+ return {recognizers, consumer, consumerElement};
+ }
+
+ /**
+ * Turn text selection and the touch callout off, for as long as this
+ * finger or pen is down, only on the elements whose hold does something:
+ * a long press's (a menu, a hold-repeat), those of recognizers created
+ * with a `selectionLock` (a slider's thumb, a switch's drag, a tab bar's
+ * zero-delay lens) and that of a press tracker created with one (a
+ * stepper's hold-repeat). Anything whose hold does nothing, a plain
+ * press-tracked control or row included, keeps the browser's long-press
+ * selection (`spec:AST-094` FR41). Restored when the contact ends. Callers
+ * lock for a finger or a pen under any primary pointer, never for a mouse
+ * (locksSelectionFor), and only once the arena has admitted the contact:
+ * `recognizers` and `consumer` are the ones that took it.
+ */
+ private lockSelection(
+ id: number,
+ recognizers: ReadonlyArray<GestureRecognizer>,
+ target: EventTarget | null,
+ consumer: TouchConsumer | null,
+ consumerElement: Element | null,
+ ): void {
+ // Each recognizer whose hold does something brings its lock; the host
+ // never imports one (a component without such a hold does not bundle
+ // it). Only one that took this contact locks for it: a recognizer that
+ // declined it (its pointer, or its own shouldReceiveTouch) has no hold
+ // here.
+ // An element attached with manageStyle: false keeps its own styles, the
+ // lock included (AttachOptions.manageStyle).
+ const managed = (element: Element) =>
+ this.registry.get(element)?.manageStyle !== false;
+ const byLock = new Map<SelectionLock, Set<Element>>();
+ for (const recognizer of recognizers) {
+ const lock = recognizer.selectionLock;
+ if (
+ lock != null &&
+ recognizer.view instanceof Element &&
+ managed(recognizer.view)
+ ) {
+ const elements = byLock.get(lock) ?? new Set<Element>();
+ elements.add(recognizer.view);
+ byLock.set(lock, elements);
}
}
- return {recognizers, consumer};
+ const consumerLock = consumer?.selectionLock;
+ if (
+ consumerLock != null &&
+ consumerElement != null &&
+ managed(consumerElement)
+ ) {
+ const elements = byLock.get(consumerLock) ?? new Set<Element>();
+ elements.add(consumerElement);
+ byLock.set(consumerLock, elements);
+ }
+ if (byLock.size > 0) {
+ const undo = [...byLock].map(([lock, elements]) =>
+ lock(elements, target),
+ );
+ this.lockedBy.set(id, () => {
+ for (const release of undo) {
+ release();
+ }
+ });
+ }
+ }
+
+ /** Undo `lockSelection` for a contact that ended; idempotent. */
+ private unlockSelection(id: number): void {
+ this.lockedBy.get(id)?.();
+ this.lockedBy.delete(id);
}
// --- Touch events ----------------------------------------------------------
+ /**
+ * Hold touches away from every participant while `gate(target)` answers
+ * true (a presentation running in a layer: its content takes no touch
+ * until it settles). Returns the release.
+ */
+ addTouchGate(gate: (target: Node) => boolean): () => void {
+ this.touchGates.add(gate);
+ return () => {
+ this.touchGates.delete(gate);
+ };
+ }
+
+ /**
+ * How many fingers are on the screen: the length of `touches` in the last
+ * touch event the host's listeners heard (`touchstart`, `touchmove`,
+ * `touchend`, `touchcancel`), whatever its target, so a finger on an
+ * element with no recognizer counts too. 0 before any, and while no
+ * listener is installed. A recognizer that must not begin under a second
+ * finger reads it in `shouldBegin`.
+ */
+ fingersDown(): number {
+ return this.fingerTargets.length;
+ }
+
/** Whether this event is new to the host (and mark it handled). */
private takeEvent(event: Event): boolean {
if (this.processed.has(event)) {
@@ -1137,25 +1869,50 @@ export class GestureHost {
}
private readonly onTouchStart = (event: TouchEvent): void => {
- if (!this.takeEvent(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.
+ if (!this.usesTouchEvents || !this.takeEvent(event)) {
return;
}
+ if (this.fingerTargets.length > 1) {
+ this.failUnclaimedLoneFingerPans();
+ }
const time = eventTime(event);
const inputs: ArenaBeganInput[] = [];
const untracked: TouchBeganInput[] = [];
const stale: number[] = [];
+ // Locked once the arena knows which recognizers took each finger.
+ const toLock: {
+ id: number;
+ target: EventTarget | null;
+ consumerElement: Element | null;
+ }[] = [];
for (const touch of touchesOf(event.changedTouches)) {
if ((touch as StylusTouch).touchType === 'stylus') {
continue;
}
// A finger number still tracked here began again: the touch it named
// ended where no listener of ours could hear it.
+ this.cancelledFingers.delete(touch.identifier);
const previous = this.forgetFinger(touch.identifier);
if (previous != null) {
stale.push(previous);
}
- const target = touch.target instanceof Node ? touch.target : event.target;
- const {recognizers, consumer} = this.participantsAt(target, 'touch');
+ const native =
+ touch.target instanceof Node
+ ? landedOn(event, touch.target)
+ : landedOn(event);
+ const target = this.presentedTarget(
+ native,
+ touch.clientX,
+ touch.clientY,
+ event.timeStamp,
+ );
+ const {recognizers, consumer, consumerElement} = this.participantsAt(
+ target,
+ 'touch',
+ );
if (recognizers.length === 0 && consumer == null) {
// Nothing here takes part: the touch stays the page's, but a
// recognizer tracking another finger hears it began (a second
@@ -1172,14 +1929,22 @@ export class GestureHost {
}
const id = this.nextId++;
this.touchIds.set(touch.identifier, id);
- this.holdSelection(id, recognizers);
+ if (locksSelectionFor('touch')) {
+ toLock.push({id, target, consumerElement});
+ }
+ // The finger's events keep going to what the engine hit.
this.watchTarget(
touch.identifier,
- target,
- recognizers.some(claimsWhileMoving),
+ native,
+ recognizers.some(claimsWhileMoving) || consumer?.keepsTouch != null,
+ consumer != null ||
+ recognizers.some(recognizer => recognizer.claimsTouches),
);
this.lastFed.set(id, {x: touch.clientX, y: touch.clientY, time});
- this.pairTouch(id, {x: touch.clientX, y: touch.clientY, target});
+ this.pairTouch(id, {x: touch.clientX, y: touch.clientY, target: native});
+ if (target !== native && target != null) {
+ this.retargeted.set(id, {x: touch.clientX, y: touch.clientY, target});
+ }
inputs.push({
id,
x: touch.clientX,
@@ -1196,18 +1961,31 @@ export class GestureHost {
this.arena.cancelled(stale, time);
}
this.arena.began(inputs);
+ for (const {id, target, consumerElement} of toLock) {
+ this.lockSelection(
+ id,
+ this.arena.participantsOf(id),
+ target,
+ this.arena.consumerOf(id) ?? null,
+ consumerElement,
+ );
+ }
for (const input of untracked) {
this.arena.untrackedBegan(input);
}
// Stamped after the consumers judged the touch: the brake asks whether
// an EARLIER finger is still driving a scroll.
- if (event.target instanceof Node) {
- this.lastTouch = {target: event.target, time};
+ const landed = landedOn(event);
+ if (landed instanceof Node) {
+ this.lastTouch = {target: landed, time};
}
};
private readonly onTouchMove = (event: TouchEvent): void => {
- if (!this.takeEvent(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.
+ if (!this.usesTouchEvents || !this.takeEvent(event)) {
return;
}
this.dropFingersNotDown(event);
@@ -1258,12 +2036,25 @@ export class GestureHost {
: touch.scroll.canScroll(0, dy);
});
if (taken.length > 0) {
- this.arena.browserTookOver(taken, time);
+ this.browserTook(taken, time);
}
}
- this.feedMoves(inputs);
+ // A finger its pointer events sample is fed from there, never from here.
+ this.feedMoves(inputs.filter(input => !this.pointerFed.has(input.id)));
};
+ /** The one blocking `touchmove` handler every claiming element shares. */
+ private readonly onBlockingTouchMove = (event: Event): void => {
+ this.cancelIfClaimed(event as TouchEvent);
+ };
+
+ /**
+ * Cancel a `touchmove` while a recognizer owns one of its fingers. A touch
+ * no recognizer owns keeps its moves (`spec:AST-094` FR19): nothing is
+ * cancelled before a recognizer begins, or for a touch it does not track,
+ * unless a recognizer holds that finger already (a scroll-edge pan pulling
+ * away from an edge every scroller under it is at; FR19, DEC-18).
+ */
/**
* Under `inputMode: 'pointer-events'` a finger comes from its pointer
* events, so its touches carry no id of ours: the live finger it is, the
@@ -1280,10 +2071,11 @@ export class GestureHost {
finger.phase === 'cancelled' ||
!(finger.target instanceof Node) ||
!(touch.target instanceof Node) ||
+ // Along the flat tree, both ways: the finger's target can be inside
+ // an open shadow root while its touches reach the host retargeted.
!(
- finger.target === touch.target ||
- finger.target.contains(touch.target) ||
- touch.target.contains(finger.target)
+ containsAlongFlatTree(finger.target, touch.target) ||
+ containsAlongFlatTree(touch.target, finger.target)
)
) {
continue;
@@ -1300,33 +2092,41 @@ export class GestureHost {
/**
* Cancel the `touchend` of a finger a recognizer owned when it lifted
* (`inputMode: 'pointer-events'`): its `pointerup` came first, at the same
- * place on the same target (`spec:AST-094` FR21).
+ * place on the same target (`spec:AST-094` FR21). Records older than
+ * CLAIMED_LIFT_MS are dropped first: their touchend never came.
*/
- private cancelClaimedLift(event: TouchEvent): void {
- if (!event.cancelable || event.defaultPrevented) {
+ private readonly onClaimedTouchEnd = (event: Event): void => {
+ const end = event as TouchEvent;
+ const time = eventTime(end);
+ for (let i = this.claimedLifts.length - 1; i >= 0; i--) {
+ if (time - this.claimedLifts[i].time > CLAIMED_LIFT_MS) {
+ this.claimedLifts.splice(i, 1);
+ }
+ }
+ if (!end.cancelable || end.defaultPrevented) {
return;
}
- for (const touch of touchesOf(event.changedTouches)) {
+ for (const touch of touchesOf(end.changedTouches)) {
+ // As its pointer landed: inside an open shadow root this listener
+ // sees the touch retargeted to the host.
const index = this.claimedLifts.findIndex(lift =>
isSamePlace(lift, {
x: touch.clientX,
y: touch.clientY,
- target: touch.target,
+ target: landedOn(end, touch.target),
}),
);
if (index >= 0) {
this.claimedLifts.splice(index, 1);
- event.preventDefault();
+ if (this.claimedLifts.length === 0) {
+ this.clearClaimedLifts();
+ }
+ end.preventDefault();
return;
}
}
- }
+ };
- /**
- * Cancel a `touchmove` while a recognizer owns one of its fingers. A touch
- * no recognizer owns keeps its moves (`spec:AST-094` FR19): nothing is
- * cancelled before a recognizer begins, or for a touch it does not track.
- */
private cancelIfClaimed(event: TouchEvent): void {
if (!event.cancelable || event.defaultPrevented) {
return;
@@ -1337,15 +2137,29 @@ export class GestureHost {
for (const touch of moved) {
const id =
this.touchIds.get(touch.identifier) ??
- (this.inputMode === 'pointer-events'
- ? this.pointerFingerAt(touch)
- : undefined);
- if (id != null && this.arena.isClaimed(id)) {
+ // Where fingers come from pointer events (inputMode 'pointer-events',
+ // or 'auto' with no ontouchstart), the touch is matched to its pointer.
+ (this.usesTouchEvents ? undefined : this.pointerFingerAt(touch));
+ if (
+ id != null &&
+ (this.arena.isClaimed(id) ||
+ // A kept press keeps its finger under any pointer (FR11, DEC-21).
+ this.arena.consumerOf(id)?.keepsTouch?.(id) === true ||
+ // A recognizer that holds the finger before it begins: a
+ // scroll-edge pan pulling away from an edge (FR19, DEC-18), only
+ // while this is the one finger on the screen: with a second one
+ // down anywhere, even off the recognizer's element, the moves stay
+ // the browser's, for its pinch (FR10).
+ (event.touches.length === 1 &&
+ this.arena
+ .participantsOf(id)
+ .some(recognizer => internals(recognizer).keepsTouch(id))))
+ ) {
event.preventDefault();
return;
}
}
- if (moved.some(touch => (touch as StylusTouch).touchType === 'stylus')) {
+ if (hasStylusTouch(event)) {
for (const id of this.pointerIds.values()) {
if (this.arena.isClaimed(id)) {
// A pen whose pointer a recognizer owns: its stylus touches too,
@@ -1358,39 +2172,92 @@ export class GestureHost {
}
private readonly onTouchEnd = (event: TouchEvent): void => {
- if (!this.takeEvent(event)) {
+ this.releaseArmedPress();
+ 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.
+ if (!this.usesTouchEvents || !this.takeEvent(event)) {
return;
}
this.dropFingersNotDown(event);
const time = eventTime(event);
const inputs: TouchInput[] = [];
+ const retargetedEnds: {
+ id: number;
+ landed: {x: number; y: number; target: EventTarget};
+ x: number;
+ y: number;
+ }[] = [];
+ let isRefused = false;
for (const touch of touchesOf(event.changedTouches)) {
+ if (this.cancelledFingers.delete(touch.identifier)) {
+ isRefused = true;
+ continue;
+ }
+ const tracked = this.touchIds.get(touch.identifier);
+ const landed = tracked == null ? undefined : this.retargeted.get(tracked);
const id = this.forgetFinger(touch.identifier);
if (id == null) {
continue;
}
inputs.push({id, x: touch.clientX, y: touch.clientY, time});
+ if (landed != null) {
+ retargetedEnds.push({id, landed, x: touch.clientX, y: touch.clientY});
+ }
}
// The lift is when momentum starts: the clock the brake wants most.
- if (event.target instanceof Node) {
- this.lastTouch = {target: event.target, time};
- }
- if (inputs.length === 0) {
- this.releaseArmedPress();
- return;
+ const landed = landedOn(event);
+ if (landed instanceof Node) {
+ this.lastTouch = {target: landed, time};
+ }
+ const dispositions =
+ inputs.length > 0
+ ? this.arena.ended(inputs)
+ : new Map<number, ClickDisposition>();
+ let cancelsClick = isRefused || needsSuppression(dispositions);
+ // A tap sent to what is drawn: the engine's click would hit the layout
+ // position, so it is cancelled and the tap clicks what it touched.
+ for (const end of retargetedEnds) {
+ if (this.clickRetargetedTap(end.landed, end, dispositions.get(end.id))) {
+ cancelsClick = true;
+ }
}
- const dispositions = this.arena.ended(inputs);
- if (needsSuppression(dispositions)) {
+ if (cancelsClick) {
if (event.cancelable) {
event.preventDefault();
}
- this.armSwallower();
+ armClickGuard(this.doc);
}
- this.releaseArmedPress();
};
+ /**
+ * Clicks what a retargeted contact touched if it ended as a tap the
+ * engine would click: nothing claimed it, the browser did not take it
+ * (a taken contact is no longer retargeted), and the finger stayed within
+ * a tap's movement. Returns whether it clicked.
+ */
+ private clickRetargetedTap(
+ landed: {x: number; y: number; target: EventTarget} | undefined,
+ end: {x: number; y: number},
+ disposition: ClickDisposition | undefined,
+ ): boolean {
+ if (landed == null || disposition !== 'allow') {
+ return false;
+ }
+ const moved = Math.hypot(end.x - landed.x, end.y - landed.y);
+ if (moved > UIKIT_TAP.allowableMovement.value) {
+ return false;
+ }
+ this.clickRetargeted(landed.target, end.x, end.y);
+ return true;
+ }
+
private readonly onTouchCancel = (event: TouchEvent): void => {
- if (!this.takeEvent(event)) {
+ this.releaseArmedPress();
+ 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.
+ if (!this.usesTouchEvents || !this.takeEvent(event)) {
return;
}
const listed = touchesOf(event.changedTouches);
@@ -1399,6 +2266,12 @@ export class GestureHost {
listed.length > 0
? listed.map(touch => touch.identifier)
: [...this.touchIds.keys()];
+ if (listed.length === 0) {
+ this.cancelledFingers.clear();
+ }
+ for (const identifier of identifiers) {
+ this.cancelledFingers.delete(identifier);
+ }
const ids: number[] = [];
for (const identifier of identifiers) {
const id = this.forgetFinger(identifier);
@@ -1409,7 +2282,6 @@ export class GestureHost {
if (ids.length > 0) {
this.arena.cancelled(ids, eventTime(event));
}
- this.releaseArmedPress();
};
/** The target's own listeners, for a target that left the document. */
@@ -1427,6 +2299,11 @@ export class GestureHost {
this.onTouchEnd(event as TouchEvent);
};
+ /** The same, registered passively for a touch only watchers follow. */
+ private readonly onTargetTouchEndPassive = (event: Event): void => {
+ this.onTouchEnd(event as TouchEvent);
+ };
+
private readonly onTargetTouchCancel = (event: Event): void => {
this.onTouchCancel(event as TouchEvent);
};
@@ -1437,7 +2314,10 @@ export class GestureHost {
* in this very event) ended where we could not see it.
*/
private dropFingersNotDown(event: TouchEvent): void {
- if (event.touches == null || this.touchIds.size === 0) {
+ if (
+ event.touches == null ||
+ (this.touchIds.size === 0 && this.cancelledFingers.size === 0)
+ ) {
return;
}
const down = new Set<number>();
@@ -1447,6 +2327,11 @@ export class GestureHost {
for (const touch of touchesOf(event.changedTouches)) {
down.add(touch.identifier);
}
+ for (const identifier of [...this.cancelledFingers]) {
+ if (!down.has(identifier)) {
+ this.cancelledFingers.delete(identifier);
+ }
+ }
const gone = [...this.touchIds.keys()].filter(
identifier => !down.has(identifier),
);
@@ -1466,6 +2351,7 @@ export class GestureHost {
identifier: number,
target: EventTarget | null,
isBlocking: boolean,
+ isClaiming: boolean,
): void {
if (target == null || typeof target.addEventListener !== 'function') {
return;
@@ -1473,30 +2359,45 @@ export class GestureHost {
this.touchTargets.set(identifier, target);
const state = this.watched.get(target);
if (state == null) {
- this.watched.set(target, {count: 1, blocking: isBlocking ? 1 : 0});
+ this.watched.set(target, {
+ count: 1,
+ blocking: isBlocking ? 1 : 0,
+ claiming: isClaiming ? 1 : 0,
+ });
if (isBlocking) {
this.blockingFingers.add(identifier);
}
+ if (isClaiming) {
+ this.claimingFingers.add(identifier);
+ }
target.addEventListener(
'touchmove',
isBlocking ? this.onTargetTouchMove : this.onTargetTouchMovePassive,
{passive: !isBlocking},
);
- target.addEventListener('touchend', this.onTargetTouchEnd, {
- passive: false,
- });
+ target.addEventListener(
+ 'touchend',
+ isClaiming ? this.onTargetTouchEnd : this.onTargetTouchEndPassive,
+ {passive: !isClaiming},
+ );
target.addEventListener('touchcancel', this.onTargetTouchCancel, {
passive: true,
});
return;
}
const wasBlocking = state.blocking > 0;
+ const wasClaiming = state.claiming > 0;
state.count += 1;
if (isBlocking) {
state.blocking += 1;
this.blockingFingers.add(identifier);
}
+ if (isClaiming) {
+ state.claiming += 1;
+ this.claimingFingers.add(identifier);
+ }
this.swapTargetTouchMove(target, wasBlocking, state.blocking > 0);
+ this.swapTargetTouchEnd(target, wasClaiming, state.claiming > 0);
}
private unwatchTarget(identifier: number): void {
@@ -1510,12 +2411,17 @@ export class GestureHost {
return;
}
const wasBlocking = state.blocking > 0;
+ const wasClaiming = state.claiming > 0;
state.count -= 1;
if (this.blockingFingers.delete(identifier)) {
state.blocking -= 1;
}
+ if (this.claimingFingers.delete(identifier)) {
+ state.claiming -= 1;
+ }
if (state.count > 0) {
this.swapTargetTouchMove(target, wasBlocking, state.blocking > 0);
+ this.swapTargetTouchEnd(target, wasClaiming, state.claiming > 0);
return;
}
this.watched.delete(target);
@@ -1523,7 +2429,10 @@ export class GestureHost {
'touchmove',
wasBlocking ? this.onTargetTouchMove : this.onTargetTouchMovePassive,
);
- target.removeEventListener('touchend', this.onTargetTouchEnd);
+ target.removeEventListener(
+ 'touchend',
+ wasClaiming ? this.onTargetTouchEnd : this.onTargetTouchEndPassive,
+ );
target.removeEventListener('touchcancel', this.onTargetTouchCancel);
}
@@ -1552,6 +2461,31 @@ export class GestureHost {
);
}
+ /**
+ * Keeps one `touchend` listener on a watched target: the cancelable one
+ * while a finger on it has a participant that could claim (a lift whose
+ * click must not happen cancels its `touchend`), a passive one while only
+ * watchers follow its fingers (`spec:AST-094` FR20).
+ */
+ private swapTargetTouchEnd(
+ target: EventTarget,
+ wasClaiming: boolean,
+ isClaiming: boolean,
+ ): void {
+ if (wasClaiming === isClaiming) {
+ return;
+ }
+ target.removeEventListener(
+ 'touchend',
+ wasClaiming ? this.onTargetTouchEnd : this.onTargetTouchEndPassive,
+ );
+ target.addEventListener(
+ 'touchend',
+ isClaiming ? this.onTargetTouchEnd : this.onTargetTouchEndPassive,
+ {passive: !isClaiming},
+ );
+ }
+
/** Stop tracking a finger by its Touch.identifier; returns its arena id. */
private forgetFinger(identifier: number): number | undefined {
const id = this.touchIds.get(identifier);
@@ -1568,6 +2502,7 @@ export class GestureHost {
if (isSamePlace(pending, place)) {
this.pendingPointers.delete(pointerId);
this.fingerPointers.set(pointerId, id);
+ this.pointerFed.add(id);
return;
}
}
@@ -1579,23 +2514,18 @@ export class GestureHost {
if (isSamePlace(unpaired, place)) {
this.unpairedTouches.delete(id);
this.fingerPointers.set(pointerId, id);
+ this.pointerFed.add(id);
return;
}
}
this.pendingPointers.set(pointerId, place);
}
- /** Feed moves, dropping the echo of a move the other channel delivered. */
+ /** Feed moves from a contact's sampling channel, in time order. */
private feedMoves(inputs: ReadonlyArray<TouchInput>): void {
const fresh = inputs.filter(input => {
const last = this.lastFed.get(input.id);
- if (
- last != null &&
- (input.time < last.time ||
- (input.time === last.time &&
- input.x === last.x &&
- input.y === last.y))
- ) {
+ if (last != null && input.time < last.time) {
return false;
}
this.lastFed.set(input.id, {x: input.x, y: input.y, time: input.time});
@@ -1606,83 +2536,12 @@ export class GestureHost {
}
}
- /**
- * For one held press by a finger or a pen: text selection and the touch
- * callout off on the elements whose hold does something (a long press),
- * as `holdSelectionStyle` decides (`spec:AST-094` FR41, DEC-9).
- * Everything else keeps the browser's long-press selection. Restored when
- * the contact ends; refcounted across contacts on one element.
- */
- private holdSelection(
- id: number,
- recognizers: ReadonlyArray<GestureRecognizer>,
- ): void {
- const elements = new Set<HTMLElement>();
- for (const recognizer of recognizers) {
- if (
- recognizer.view instanceof HTMLElement &&
- recognizer.isEnabled &&
- // An element attached with manageStyle: false keeps its own styles.
- this.registry.get(recognizer.view)?.manageStyle !== false &&
- holdSelectionStyle([recognizer]) != null
- ) {
- elements.add(recognizer.view);
- }
- }
- if (elements.size === 0) {
- return;
- }
- const held = [...elements];
- for (const element of held) {
- const entry = heldSelection.get(element);
- if (entry != null) {
- entry.count += 1;
- continue;
- }
- const saved = HOLD_SELECTION_PROPERTIES.map(name => ({
- name,
- value: element.style.getPropertyValue(name),
- priority: element.style.getPropertyPriority(name),
- }));
- for (const name of HOLD_SELECTION_PROPERTIES) {
- element.style.setProperty(name, 'none');
- }
- heldSelection.set(element, {count: 1, saved});
- }
- this.heldSelectionBy.set(id, held);
- }
-
- /** Undo `holdSelection` for a contact that ended; idempotent. */
- private releaseSelection(id: number): void {
- const held = this.heldSelectionBy.get(id);
- if (held == null) {
- return;
- }
- this.heldSelectionBy.delete(id);
- for (const element of held) {
- const entry = heldSelection.get(element);
- if (entry == null) {
- continue;
- }
- entry.count -= 1;
- if (entry.count > 0) {
- continue;
- }
- heldSelection.delete(element);
- for (const {name, value, priority} of entry.saved) {
- if (value === '') {
- element.style.removeProperty(name);
- } else {
- element.style.setProperty(name, value, priority);
- }
- }
- }
- }
-
/** Forget a contact's pairing and echo state. */
private forgetContact(id: number): void {
- this.releaseSelection(id);
+ this.unlockSelection(id);
+ this.retargeted.delete(id);
this.lastFed.delete(id);
+ this.pointerFed.delete(id);
this.judgedUncancelable.delete(id);
this.unpairedTouches.delete(id);
for (const [pointerId, paired] of this.fingerPointers) {
@@ -1696,7 +2555,7 @@ export class GestureHost {
private readonly onPointerDown = (event: PointerEvent): void => {
// A new press: whatever click is still owed to the last one is not this.
- this.disarmSwallower();
+ disarmClickGuard(this.doc);
if (!isPointerKind(event.pointerType)) {
return;
}
@@ -1704,17 +2563,24 @@ export class GestureHost {
this.pairPointer(event.pointerId, {
x: event.clientX,
y: event.clientY,
- target: event.target,
+ target: landedOn(event),
});
return;
}
- // A right click, a pen's barrel button and a ctrl-click on macOS start
- // no press (FR43).
+ // A right click, a pen's barrel button, or a ctrl-click on macOS (its
+ // context click) starts no press (FR43).
if (event.pointerType !== 'touch' && !isPrimaryClick(event)) {
return;
}
- const {recognizers, consumer} = this.participantsAt(
- event.target,
+ const landed = landedOn(event);
+ const target = this.presentedTarget(
+ landed,
+ event.clientX,
+ event.clientY,
+ event.timeStamp,
+ );
+ const {recognizers, consumer, consumerElement} = this.participantsAt(
+ target,
event.pointerType,
);
if (recognizers.length === 0 && consumer == null) {
@@ -1722,8 +2588,8 @@ export class GestureHost {
}
const id = this.nextId++;
this.pointerIds.set(event.pointerId, id);
- if (event.pointerType !== 'mouse') {
- this.holdSelection(id, recognizers);
+ if (target !== landed && target != null) {
+ this.retargeted.set(id, {x: event.clientX, y: event.clientY, target});
}
this.arena.began([
{
@@ -1732,12 +2598,23 @@ export class GestureHost {
y: event.clientY,
time: eventTime(event),
pointerType: event.pointerType,
- target: event.target,
- scroll: createNativeScrollProbe(event.target),
+ target,
+ scroll: createNativeScrollProbe(target),
recognizers,
consumer,
},
]);
+ if (locksSelectionFor(event.pointerType)) {
+ // The presented target: what the pen is on, where the engine's own
+ // hit test may still see the motion's start.
+ this.lockSelection(
+ id,
+ this.arena.participantsOf(id),
+ target,
+ this.arena.consumerOf(id) ?? null,
+ consumerElement,
+ );
+ }
};
private readonly onPointerMove = (event: PointerEvent): void => {
@@ -1772,6 +2649,7 @@ export class GestureHost {
};
private readonly onPointerUp = (event: PointerEvent): void => {
+ this.releaseArmedPress();
if (event.pointerType === 'touch' && this.usesTouchEvents) {
// The lift itself is the touchend's: it alone can cancel the click.
this.fingerPointers.delete(event.pointerId);
@@ -1780,31 +2658,96 @@ export class GestureHost {
}
const id = this.pointerIds.get(event.pointerId);
if (id == null) {
- this.releaseArmedPress();
return;
}
this.pointerIds.delete(event.pointerId);
- this.releaseSelection(id);
- if (event.pointerType === 'touch' && this.arena.isClaimed(id)) {
- this.claimedLifts.push({
- x: event.clientX,
- y: event.clientY,
- target: event.target,
- });
- if (this.claimedLifts.length > 8) {
- this.claimedLifts.shift();
- }
- }
+ this.unlockSelection(id);
const dispositions = this.arena.ended([
{id, x: event.clientX, y: event.clientY, time: eventTime(event)},
]);
- if (needsSuppression(dispositions)) {
- this.armSwallower();
+ // A retargeted tap's own click arms the click guard for the engine's.
+ const landed = this.retargeted.get(id);
+ this.retargeted.delete(id);
+ const clicked = this.clickRetargetedTap(
+ landed,
+ {x: event.clientX, y: event.clientY},
+ dispositions.get(id),
+ );
+ if (!clicked && needsSuppression(dispositions)) {
+ armClickGuard(this.doc);
+ }
+ // A finger read from its pointer events: the touchend that follows the
+ // lift is cancelled when a gesture took it, which the lift itself may
+ // decide (a hold whose time came with it), or when its tap was retargeted
+ // (FR21).
+ if (
+ event.pointerType === 'touch' &&
+ (clicked || needsSuppression(dispositions))
+ ) {
+ this.noteClaimedLift(event);
}
- this.releaseArmedPress();
};
+ /**
+ * Note a claimed finger's lift, so the `touchend` that follows its
+ * `pointerup` is cancelled (FR21). Only where an element's listener can take
+ * that touchend: elsewhere none comes, and the note would hold its node for
+ * nothing. At most CLAIMED_LIFT_LIMIT wait, the oldest going first, and one
+ * timer drops each once CLAIMED_LIFT_MS has passed (FR24); the host's
+ * uninstall keeps them, as it can run in the microtask after the pointerup,
+ * before the touchend that comes later in the same task.
+ */
+ private noteClaimedLift(event: PointerEvent): void {
+ if (
+ !this.readsFingersFromPointerEvents() ||
+ !(this.isCoarse || this.sendsTouchEvents())
+ ) {
+ return;
+ }
+ this.claimedLifts.push({
+ x: event.clientX,
+ y: event.clientY,
+ target: landedOn(event),
+ time: eventTime(event),
+ });
+ if (this.claimedLifts.length > CLAIMED_LIFT_LIMIT) {
+ this.claimedLifts.shift();
+ }
+ this.armClaimedLiftTimer();
+ }
+
+ /** Arm the one timer for the oldest claimed lift still waiting. */
+ private armClaimedLiftTimer(): void {
+ if (this.claimedLiftTimer != null || this.claimedLifts.length === 0) {
+ return;
+ }
+ const due = this.claimedLifts[0].time + CLAIMED_LIFT_MS;
+ this.claimedLiftTimer = this.clock.setTimeout(
+ () => {
+ this.claimedLiftTimer = null;
+ const now = this.clock.now();
+ for (let i = this.claimedLifts.length - 1; i >= 0; i--) {
+ if (now - this.claimedLifts[i].time >= CLAIMED_LIFT_MS) {
+ this.claimedLifts.splice(i, 1);
+ }
+ }
+ this.armClaimedLiftTimer();
+ },
+ Math.max(0, due - this.clock.now()),
+ );
+ }
+
+ /** Drop every claimed lift and its timer, once the last one is taken. */
+ private clearClaimedLifts(): void {
+ this.claimedLifts.length = 0;
+ if (this.claimedLiftTimer != null) {
+ this.clock.clearTimeout(this.claimedLiftTimer);
+ this.claimedLiftTimer = null;
+ }
+ }
+
private readonly onPointerCancel = (event: PointerEvent): void => {
+ this.releaseArmedPress();
if (event.pointerType === 'touch' && this.usesTouchEvents) {
const id =
this.fingerPointers.get(event.pointerId) ??
@@ -1812,17 +2755,21 @@ export class GestureHost {
this.fingerPointers.delete(event.pointerId);
this.pendingPointers.delete(event.pointerId);
if (id != null) {
- this.arena.browserTookOver([id], eventTime(event));
+ // The pointer channel ends here while the finger keeps moving (the
+ // browser scrolls with it): its touch events, now the only channel,
+ // sample it, as a watcher following the scroll to the lift needs.
+ this.pointerFed.delete(id);
+ this.browserTook([id], eventTime(event));
}
return;
}
const id = this.pointerIds.get(event.pointerId);
if (id != null) {
this.pointerIds.delete(event.pointerId);
- this.releaseSelection(id);
+ this.unlockSelection(id);
+ this.retargeted.delete(id);
this.arena.cancelled([id], eventTime(event));
}
- this.releaseArmedPress();
};
/**
@@ -1839,7 +2786,7 @@ export class GestureHost {
touch.pointerType !== 'touch' ||
touch.phase === 'ended' ||
touch.phase === 'cancelled' ||
- touch.target !== event.target
+ touch.target !== landedOn(event)
) {
continue;
}
@@ -1857,54 +2804,29 @@ export class GestureHost {
// --- Clicks, menus, scrolls, focus -----------------------------------------
- private armSwallower(): void {
- this.swallowDeadline =
- browserClock.now() + UIKIT_GESTURES.click.strayClickWindow.value;
- }
-
- private disarmSwallower(): void {
- this.swallowDeadline = Number.NEGATIVE_INFINITY;
- }
-
- private readonly onClick = (event: MouseEvent): void => {
- if (browserClock.now() > this.swallowDeadline) {
- return;
- }
- if (!event.isTrusted || event.detail === 0) {
- return;
- }
- if (
- event.target instanceof Element &&
- event.target.hasAttribute(HAPTIC_SWITCH_ATTRIBUTE)
- ) {
- return;
- }
- this.disarmSwallower();
- event.preventDefault();
- event.stopImmediatePropagation();
- };
-
private replayClick(touch: GestureTouch, allowed: boolean): void {
if (!allowed) {
return;
}
// The browser's own click was swallowed while recognizers decided; they
// all failed, so the click the touch earned is delivered now.
- this.disarmSwallower();
+ disarmClickGuard(this.doc);
const target = touch.target;
const view = this.doc.defaultView;
if (!(target instanceof Element) || !target.isConnected || view == null) {
return;
}
- target.dispatchEvent(
- new view.MouseEvent('click', {
- bubbles: true,
- cancelable: true,
- composed: true,
- detail: 1,
- clientX: touch.x,
- clientY: touch.y,
- }),
+ withoutClickGuard(() =>
+ target.dispatchEvent(
+ new view.MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ detail: 1,
+ clientX: touch.x,
+ clientY: touch.y,
+ }),
+ ),
);
}
@@ -1925,16 +2847,38 @@ export class GestureHost {
* reports itself through pointercancel or touchcancel.
*/
ownScroll(scroller: Node): void {
- this.ownedScrolls.add(scroller);
+ const call = ++this.ownScrollCalls;
+ this.ownedScrolls.set(scroller, call);
const view = this.doc.defaultView;
if (view == null) {
return;
}
- view.requestAnimationFrame(() => {
- view.requestAnimationFrame(() => {
- this.ownedScrolls.delete(scroller);
+ // A newer call keeps it until its own frame has passed: its frames
+ // replace the older call's.
+ this.ownScrollFrames.get(scroller)?.();
+ let inner = 0;
+ const outer = view.requestAnimationFrame(() => {
+ inner = view.requestAnimationFrame(() => {
+ this.ownScrollFrames.delete(scroller);
+ if (this.ownedScrolls.get(scroller) === call) {
+ this.ownedScrolls.delete(scroller);
+ }
});
});
+ this.ownScrollFrames.set(scroller, () => {
+ view.cancelAnimationFrame(outer);
+ if (inner !== 0) {
+ view.cancelAnimationFrame(inner);
+ }
+ });
+ }
+
+ /**
+ * @internal Whether a recognizer is scrolling `scroller` itself now
+ * (ownScroll): that scroll is not a finger's (fingerScroll.ts reads it).
+ */
+ isOwnScroll(scroller: Node): boolean {
+ return this.ownedScrolls.has(scroller);
}
private readonly onScroll = (event: Event): void => {
@@ -1948,8 +2892,8 @@ export class GestureHost {
const last = this.lastTouch;
if (
last != null &&
- time - last.time < UIKIT_GESTURES.press.momentumMemory.value &&
- scroller.contains(last.target)
+ time - last.time < UIKIT_PRESS.momentumMemory.value &&
+ containsAlongFlatTree(scroller, last.target)
) {
this.lastScroll = {scroller, time};
}
@@ -1966,7 +2910,7 @@ export class GestureHost {
}
if (
touch.target instanceof Node &&
- scroller.contains(touch.target) &&
+ containsAlongFlatTree(scroller, touch.target) &&
// Only a pan this finger drove takes the touch: the browser starts
// one only once the finger has travelled the take distance
// (spec:AST-094 FR20). A scroll under a finger that has not
@@ -1974,60 +2918,118 @@ export class GestureHost {
// anchoring) is the page's own: the touch, and the click it earns,
// stay where they are.
Math.hypot(touch.x - touch.startX, touch.y - touch.startY) >=
- UIKIT_GESTURES.press.slop.value
+ UIKIT_PRESS.slop.value
) {
taken.push(touch.id);
}
}
if (taken.length > 0) {
- this.arena.browserTookOver(taken, time);
+ this.browserTook(taken, time);
}
};
+ private noteFingersDown(event: TouchEvent): void {
+ const fingers: Node[] = [];
+ for (const touch of touchesOf(event.touches)) {
+ if ((touch as StylusTouch).touchType !== 'stylus') {
+ if (touch.target instanceof Node) {
+ fingers.push(touch.target);
+ }
+ }
+ }
+ this.fingerTargets = fingers;
+ for (const listener of [...this.fingerListeners]) {
+ listener();
+ }
+ }
+
+ /**
+ * A second finger landed somewhere (wherever: often on a plain row): a
+ * pan that takes one finger only and has not claimed its touch fails, so
+ * the two fingers stay the browser's pinch (WCAG 1.4.4) instead of the
+ * pan claiming them midway. A drag a recognizer has claimed keeps its
+ * finger: a second finger never cancels or redirects it (`spec:AST-094`
+ * FR10), and no claim is released here.
+ */
+ private failUnclaimedLoneFingerPans(): void {
+ for (const recognizer of [...this.arena.involvedRecognizers]) {
+ if (
+ isPanRecognizer(recognizer) &&
+ recognizer.state === 'possible' &&
+ recognizer.maximumNumberOfTouches === 1 &&
+ recognizer.trackedTouches.length > 0 &&
+ recognizer.trackedTouches.every(
+ touch =>
+ touch.pointerType === 'touch' && !this.arena.isClaimed(touch.id),
+ )
+ ) {
+ recognizer.cancel();
+ }
+ }
+ }
+
private readonly onVisibilityChange = (): void => {
if (this.doc.visibilityState === 'hidden') {
this.cancelEverything(this.arena.now());
+ // As at a blur: the press sends no further pointer event, so an armed
+ // press's page listeners go now (FR24).
this.releaseArmedPress();
}
};
private readonly onBlur = (): void => {
this.cancelEverything(this.arena.now());
+ // The press a blur ends sends no further pointer event: an armed press's
+ // page listeners go now, as at its lift (FR24).
this.releaseArmedPress();
};
+ /** Whether the browser sends Touch Events at all (`ontouchstart`). */
+ private sendsTouchEvents(): boolean {
+ const view = this.doc.defaultView;
+ return view != null && 'ontouchstart' in view;
+ }
+
+ /**
+ * Whether the host reads fingers from their pointer events: Pointer Events
+ * input, or a window with no `ontouchstart` (touch emulation turned on
+ * after load), as the move path does.
+ */
+ private readsFingersFromPointerEvents(): boolean {
+ const view = this.doc.defaultView;
+ return (
+ this.inputMode === 'pointer-events' ||
+ (view != null && !('ontouchstart' in view))
+ );
+ }
+
/** The app lost focus: UIKit cancels every touch in flight. */
private cancelEverything(time: number): void {
const ids = [...this.pointerIds.values()];
for (const id of ids) {
- this.releaseSelection(id);
+ this.unlockSelection(id);
}
for (const identifier of [...this.touchIds.keys()]) {
+ // The browser may keep the touch alive: its lift must not click.
+ this.cancelledFingers.add(identifier);
const id = this.forgetFinger(identifier);
if (id != null) {
ids.push(id);
}
}
this.pointerIds.clear();
+ this.retargeted.clear();
this.fingerPointers.clear();
this.pendingPointers.clear();
this.unpairedTouches.clear();
this.lastFed.clear();
+ this.pointerFed.clear();
if (ids.length > 0) {
this.arena.cancelled(ids, time);
}
}
}
-/** Whether an attachment could take a press now: something on it is enabled. */
-function isServed(registration: Registration): boolean {
- return (
- registration.recognizers.some(r => r.isEnabled) ||
- (registration.consumer != null &&
- registration.consumer.isEnabled?.() !== false)
- );
-}
-
function needsSuppression(
dispositions: Map<number, ClickDisposition>,
): boolean {
@@ -2051,14 +3053,12 @@ function coalescedHistory(event: PointerEvent): TouchSample[] {
}));
}
-const hosts = new WeakMap<Document, GestureHost>();
-
/** The gesture host of a document, created on first use. */
export function getGestureHost(doc: Document): GestureHost {
- let host = hosts.get(doc);
+ let host = gestureHosts.get(doc);
if (host == null) {
host = new GestureHost(doc);
- hosts.set(doc, host);
+ gestureHosts.set(doc, host);
}
return host;
}
diff --git a/packages/core/src/gestures/GestureRecognizer.ts b/packages/core/src/gestures/GestureRecognizer.ts
index af9b0a617b..e68007b6b7 100644
--- a/packages/core/src/gestures/GestureRecognizer.ts
+++ b/packages/core/src/gestures/GestureRecognizer.ts
@@ -24,7 +24,8 @@
* event, so a listener that writes a transform writes it in the same frame
* as the input, with no React render in between.
*
- * SYNC: When modified, update GestureArena.ts.
+ * SYNC: When modified, update GestureArena.ts, recognizerInternals.ts and
+ * README.md.
*/
import type {GestureArena} from './GestureArena';
@@ -38,6 +39,16 @@ import type {
} from './types';
import {DEFAULT_ENVIRONMENT} from './types';
+/**
+ * Turns text selection and the touch callout off on `elements` (and on a
+ * non-text input `target` inside one) for one held press; returns the undo.
+ * utils/selectionLock.ts's `lockSelection` is the one implementation.
+ */
+export type SelectionLock = (
+ elements: Iterable<Element>,
+ target: EventTarget | null,
+) => () => void;
+
export interface GestureRecognizerOptions<R = GestureRecognizer> {
/** A name for debugging and test output. */
name?: string;
@@ -51,6 +62,18 @@ export interface GestureRecognizerOptions<R = GestureRecognizer> {
cancelsTouchesInView?: boolean;
/** Hold the view's touch-began until this recognizer fails. @default false */
delaysTouchesBegan?: boolean;
+ /**
+ * For a hold that does something (a slider's thumb, a switch's or a
+ * segmented control's drag): the lock that turns text selection and the
+ * touch callout off on this recognizer's element for each held press
+ * (`spec:AST-094` FR41). Pass `lockSelection` from utils/selectionLock.ts;
+ * the host calls it and never imports it, so a component without such a
+ * hold does not bundle it. Content under a sheet's or a pager's pan stays
+ * selectable, so there is none by default; a mouse keeps desktop selection
+ * either way. A long press brings its own when it has a hold (a
+ * `minimumPressDuration` above 0); `null` brings none.
+ */
+ selectionLock?: SelectionLock | null;
/**
* Hold the view's touch-ended (and the browser's click) while this
* recognizer may still recognize. @default true
@@ -60,6 +83,17 @@ export interface GestureRecognizerOptions<R = GestureRecognizer> {
allowedPointerTypes?: ReadonlyArray<PointerKind>;
/** Ignore a touch of a different kind than the ones already tracked. @default true */
requiresExclusiveTouchType?: boolean;
+ /**
+ * Whether this recognizer takes its touches from the browser when it
+ * recognizes. `false` makes a watcher (a tab bar that minimizes while the
+ * page scrolls): it never claims, so it gets only passive listeners and
+ * never delays a scroll; it prevents no other recognizer and none prevents
+ * it (`spec:AST-094` FR15); it cancels no press or click under it; and it
+ * keeps tracking a touch the browser takes for a scroll,
+ * reporting through the native scroll and ending at the lift.
+ * @default true
+ */
+ claimsTouches?: boolean;
/** gestureRecognizerShouldBegin: return false to fail instead of beginning. */
shouldBegin?: (recognizer: R) => boolean;
/** gestureRecognizer(_:shouldReceive:): return false to never see this touch. */
@@ -163,6 +197,8 @@ export abstract class GestureRecognizer {
name: string;
isEnabled: boolean;
cancelsTouchesInView: boolean;
+ /** See GestureRecognizerOptions.selectionLock. */
+ readonly selectionLock: SelectionLock | null;
delaysTouchesBegan: boolean;
delaysTouchesEnded: boolean;
allowedPointerTypes: ReadonlySet<PointerKind> | null;
@@ -174,9 +210,9 @@ export abstract class GestureRecognizer {
view: unknown = null;
/** @internal The arena delivering touches to this recognizer, if any. */
- arena: GestureArena | null = null;
+ protected arena: GestureArena | null = null;
/** @internal A recognition waiting for a failure requirement. */
- pending: 'began' | 'ended' | null = null;
+ protected pending: 'began' | 'ended' | null = null;
/**
* The delegate functions. Typed against the base so a subclass stays
@@ -195,7 +231,7 @@ export abstract class GestureRecognizer {
/** Touches currently tracked, by id. */
protected readonly touches = new Map<number, GestureTouch>();
/** @internal Every touch id received since the last reset. */
- readonly seenTouchIds = new Set<number>();
+ protected readonly seenTouchIds = new Set<number>();
private lastLocation: Point = {x: 0, y: 0};
constructor(options: GestureRecognizerOptions<never> = {}) {
@@ -204,6 +240,7 @@ export abstract class GestureRecognizer {
this.name = options.name ?? this.constructor.name;
this.isEnabled = options.isEnabled ?? true;
this.cancelsTouchesInView = options.cancelsTouchesInView ?? true;
+ this.selectionLock = options.selectionLock ?? null;
this.delaysTouchesBegan = options.delaysTouchesBegan ?? false;
this.delaysTouchesEnded = options.delaysTouchesEnded ?? true;
this.allowedPointerTypes =
@@ -225,7 +262,7 @@ export abstract class GestureRecognizer {
* it. Every touch recognizer claims; hover has no touches to claim.
*/
get claimsTouches(): boolean {
- return true;
+ return this.options.claimsTouches ?? true;
}
get state(): GestureState {
@@ -242,7 +279,7 @@ export abstract class GestureRecognizer {
}
/** @internal Whether this recognizer listens to touch at all. */
- get acceptsTouchInput(): boolean {
+ protected get acceptsTouchInput(): boolean {
return (
this.allowedPointerTypes == null || this.allowedPointerTypes.has('touch')
);
@@ -299,7 +336,7 @@ export abstract class GestureRecognizer {
}
/** @internal Whether this recognizer must wait for `other` to fail. */
- requiresFailureOf(other: GestureRecognizer): boolean {
+ protected requiresFailureOf(other: GestureRecognizer): boolean {
return (
this.failureRequirements.has(other) ||
this.options.shouldRequireFailureOf?.(this, other) === true ||
@@ -312,7 +349,7 @@ export abstract class GestureRecognizer {
* (`recognizeSimultaneouslyWith` sets both sides; each delegate answers for
* its own recognizer), so one delegate alone keeps them exclusive (FR15).
*/
- allowsSimultaneous(other: GestureRecognizer): boolean {
+ protected allowsSimultaneous(other: GestureRecognizer): boolean {
return (
this.simultaneousWith.has(other) ||
(this.options.shouldRecognizeSimultaneously?.(this, other) === true &&
@@ -321,10 +358,20 @@ export abstract class GestureRecognizer {
}
/** @internal The delegate's should-begin answer. */
- shouldBegin(): boolean {
+ protected shouldBegin(): boolean {
return this.options.shouldBegin?.(this) ?? true;
}
+ /**
+ * @internal Whether this recognizer holds `touchId` before it begins: the
+ * host then cancels that finger's moves as for a touch a recognizer owns.
+ * None does by default (`spec:AST-094` FR19); a scroll-edge pan holds a
+ * finger pulling away from an edge every scroller under it is at.
+ */
+ protected keepsTouch(_touchId: number): boolean {
+ return false;
+ }
+
/** UIKit's `canPrevent(_:)`: whether recognizing fails `other`. */
canPrevent(_other: GestureRecognizer): boolean {
return true;
@@ -409,6 +456,10 @@ export abstract class GestureRecognizer {
touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): boolean {
+ if (!this.claimsTouches) {
+ // A watcher follows the browser's scroll to the lift.
+ return true;
+ }
this.touchesCancelled(touches, event);
return false;
}
@@ -482,7 +533,7 @@ export abstract class GestureRecognizer {
// --- Arena hooks (internal) ----------------------------------------------
/** @internal Whether this recognizer takes `touch` right now. */
- wantsTouch(touch: GestureTouch): boolean {
+ protected wantsTouch(touch: GestureTouch): boolean {
if (this.state !== 'possible' && !isActive(this.state)) {
return false;
}
@@ -493,7 +544,7 @@ export abstract class GestureRecognizer {
}
/** @internal */
- deliverBegan(
+ protected deliverBegan(
touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): void {
@@ -506,7 +557,7 @@ export abstract class GestureRecognizer {
}
/** @internal */
- deliverBeganElsewhere(
+ protected deliverBeganElsewhere(
touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): void {
@@ -517,7 +568,7 @@ export abstract class GestureRecognizer {
}
/** @internal */
- deliverMoved(
+ protected deliverMoved(
touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): void {
@@ -530,7 +581,7 @@ export abstract class GestureRecognizer {
}
/** @internal */
- deliverEnded(
+ protected deliverEnded(
touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): void {
@@ -548,7 +599,7 @@ export abstract class GestureRecognizer {
}
/** @internal */
- deliverCancelled(
+ protected deliverCancelled(
touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): void {
@@ -565,7 +616,7 @@ export abstract class GestureRecognizer {
}
/** @internal */
- deliverTakenByBrowser(
+ protected deliverTakenByBrowser(
touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): void {
@@ -612,7 +663,7 @@ export abstract class GestureRecognizer {
}
/** @internal Apply a transition the arena has approved. */
- applyState(next: GestureState): void {
+ protected applyState(next: GestureState): void {
const from = this.stateValue;
if (from === next && next !== 'changed') {
return;
@@ -635,7 +686,7 @@ export abstract class GestureRecognizer {
}
/** @internal Return to `possible` for the next attempt. */
- resetToPossible(): void {
+ protected resetToPossible(): void {
this.clearTimer();
this.pending = null;
this.touches.clear();
diff --git a/packages/core/src/gestures/LongPressGestureRecognizer.ts b/packages/core/src/gestures/LongPressGestureRecognizer.ts
index 839fede44a..4b7e4718b8 100644
--- a/packages/core/src/gestures/LongPressGestureRecognizer.ts
+++ b/packages/core/src/gestures/LongPressGestureRecognizer.ts
@@ -21,6 +21,7 @@
*/
import {UIKIT_LONG_PRESS, UIKIT_TAP} from '../motion/uikit/gestures';
+import {lockSelection} from '../utils/selectionLock';
import {travel} from './geometry';
import {
GestureRecognizer,
@@ -45,6 +46,11 @@ export class LongPressGestureRecognizer extends GestureRecognizer {
return 'longPress';
}
+ /** @internal The host's brand: a long press keeps the callout and selection off (recognizerInternals). */
+ protected get family(): 'longPress' {
+ return 'longPress';
+ }
+
minimumPressDuration: number;
allowableMovement: number;
numberOfTapsRequired: number;
@@ -59,7 +65,20 @@ export class LongPressGestureRecognizer extends GestureRecognizer {
beganAt: number | null = null;
constructor(options: LongPressGestureRecognizerOptions = {}) {
- super(options);
+ // A long press's hold does something (a menu, a hold-repeat): it locks
+ // selection for its press (spec:AST-094 FR41). One at 0 ms recognizes at
+ // touch-down and has no hold, so it brings none, nor does one told null:
+ // there the browser keeps its native long press.
+ super({
+ ...options,
+ selectionLock:
+ options.selectionLock !== undefined
+ ? options.selectionLock
+ : (options.minimumPressDuration ??
+ UIKIT_LONG_PRESS.minimumPressDuration.value) > 0
+ ? lockSelection
+ : null,
+ });
this.minimumPressDuration =
options.minimumPressDuration ??
UIKIT_LONG_PRESS.minimumPressDuration.value;
diff --git a/packages/core/src/gestures/PanGestureRecognizer.ts b/packages/core/src/gestures/PanGestureRecognizer.ts
index 18ae9bb1ef..ac21d5637a 100644
--- a/packages/core/src/gestures/PanGestureRecognizer.ts
+++ b/packages/core/src/gestures/PanGestureRecognizer.ts
@@ -91,6 +91,11 @@ export class PanGestureRecognizer extends GestureRecognizer {
return 'pan';
}
+ /** @internal The host's brand: a pan follows the one-finger rule (recognizerInternals). */
+ protected get family(): 'pan' {
+ return 'pan';
+ }
+
minimumNumberOfTouches: number;
maximumNumberOfTouches: number;
hysteresis: number;
@@ -368,6 +373,36 @@ export class PanGestureRecognizer extends GestureRecognizer {
this.offset = {x: -swallowed.x, y: -swallowed.y};
}
+ /**
+ * A scroll-edge pan holds its finger from the first move while every
+ * scroller under it is at its edge and the finger pulls away from that
+ * edge, the pan's own way (`spec:AST-094` FR19, DEC-18):
+ * the browser would only rubber-band there. It still begins at its
+ * hysteresis; a move the content can still scroll stays the browser's,
+ * and so does every move while a second finger is down (a pinch).
+ */
+ protected override keepsTouch(touchId: number): boolean {
+ const touch = this.touches.get(touchId);
+ if (
+ !this.scrollEdge ||
+ this.state !== 'possible' ||
+ // A lone finger only: two fingers before a claim are the page's pinch
+ // (spec:AST-094 FR10).
+ this.touches.size !== 1 ||
+ touch == null ||
+ touch.pointerType !== 'touch' ||
+ touch.takenByBrowser
+ ) {
+ return false;
+ }
+ const moved = this.raw;
+ return (
+ (moved.x !== 0 || moved.y !== 0) &&
+ this.classify(moved) === 'begin' &&
+ !this.nativeCanScroll(moved.x, moved.y)
+ );
+ }
+
private nativeCanScroll(dx: number, dy: number): boolean {
for (const touch of this.touches.values()) {
if (touch.scroll?.canScroll(dx, dy) === true) {
diff --git a/packages/core/src/gestures/PinchGestureRecognizer.ts b/packages/core/src/gestures/PinchGestureRecognizer.ts
index 07b3a6c3c1..6ca75bb627 100644
--- a/packages/core/src/gestures/PinchGestureRecognizer.ts
+++ b/packages/core/src/gestures/PinchGestureRecognizer.ts
@@ -43,7 +43,8 @@ export class PinchGestureRecognizer extends GestureRecognizer {
private initialSpan = 0;
private scaleValue = 1;
private readonly tracker = new VelocityTracker();
- private lastTime = 0;
+ /** The lift's event time, for the stillness reset. */
+ private liftTime: number | undefined;
constructor(options: PinchGestureRecognizerOptions = {}) {
super(options);
@@ -59,17 +60,18 @@ export class PinchGestureRecognizer extends GestureRecognizer {
set scale(value: number) {
const span = this.span();
if (span > 0 && value > 0) {
+ const factor = this.scaleValue > 0 ? value / this.scaleValue : 1;
this.initialSpan = span / value;
this.scaleValue = value;
- // The velocity continues from the re-based value, without a jump.
- this.tracker.reset();
- this.tracker.add(value, 0, this.lastTime);
+ // The velocity continues from the re-based value, without a jump: the
+ // samples scale with it, keeping the release.
+ this.tracker.scaleBy(factor);
}
}
/** Scale per second (UIKit's filter; measured for pans, assumed here). */
get velocity(): number {
- return this.tracker.velocity().x;
+ return this.tracker.velocity(this.liftTime).x;
}
/** The midpoint between the two fingers. */
@@ -90,7 +92,6 @@ export class PinchGestureRecognizer extends GestureRecognizer {
_touches: ReadonlyArray<GestureTouch>,
event: GestureEventContext,
): void {
- this.lastTime = event.time;
if (this.numberOfTouches === 2) {
this.initialSpan = this.span();
this.scaleValue = 1;
@@ -106,7 +107,6 @@ export class PinchGestureRecognizer extends GestureRecognizer {
if (this.numberOfTouches < 2 || this.initialSpan <= 0) {
return;
}
- this.lastTime = event.time;
const span = this.span();
// Once recognized, a pinch waiting on a recognizer it requires to fail
// keeps its re-based start: its moves only follow the fingers.
@@ -131,11 +131,16 @@ export class PinchGestureRecognizer extends GestureRecognizer {
}
}
- protected override touchesEnded(): void {
+ protected override touchesEnded(
+ _touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void {
+ this.liftTime = event.time;
this.setState(isActive(this.state) ? 'ended' : 'failed');
}
protected override reset(): void {
+ this.liftTime = undefined;
this.initialSpan = 0;
this.scaleValue = 1;
this.tracker.reset();
diff --git a/packages/core/src/gestures/PressTracker.ts b/packages/core/src/gestures/PressTracker.ts
index 350aaa1f55..3fd29986ed 100644
--- a/packages/core/src/gestures/PressTracker.ts
+++ b/packages/core/src/gestures/PressTracker.ts
@@ -46,10 +46,10 @@
* swallows for a touch a recognizer took.
*/
-import {UIKIT_GESTURES} from '../motion/uikit/gestures';
+import {UIKIT_CONTROL, UIKIT_PAN, UIKIT_PRESS} from '../motion/uikit/gestures';
import {timing} from '../motion/uikit/timing';
import {travel} from './geometry';
-import type {GestureRecognizer} from './GestureRecognizer';
+import type {GestureRecognizer, SelectionLock} from './GestureRecognizer';
import type {TapGestureRecognizer} from './TapGestureRecognizer';
import type {GestureTouch, TouchConsumer} from './types';
@@ -77,6 +77,24 @@ export interface PressTrackerOptions {
view?: unknown;
onControlEvent?: (event: ControlEvent, touch: GestureTouch) => void;
onHighlightChange?: (isHighlighted: boolean) => void;
+ /**
+ * A continuous-tracking control (a held stepper) keeps its touch once its
+ * press is delivered: the host cancels the browser's pan for that finger,
+ * as UIKit's `touchesShouldCancel(in:)` is false for a tracking control.
+ * Its element then gets a blocking `touchmove` listener, so a scroll that
+ * starts on it waits on the main thread: never set it on plain buttons,
+ * links, cards or list cells.
+ * @default false
+ */
+ keepsTouch?: boolean;
+ /**
+ * For a control whose own record defines a hold action (a stepper's
+ * hold-repeat): pass `lockSelection` (utils/selectionLock.ts) to turn
+ * text selection and the callout off for each press by a finger or a pen,
+ * under any primary pointer (`spec:AST-094` FR41). A control whose hold
+ * does nothing passes none. @default undefined
+ */
+ selectionLock?: SelectionLock;
trackingExpansion?: number;
/**
* When the highlight waits `contentTouchDelay`: inside a scroller (a
@@ -107,7 +125,7 @@ export interface PressTrackerOptions {
isBraking?: (touch: GestureTouch) => boolean;
}
-const PRESS = UIKIT_GESTURES.press;
+const PRESS = UIKIT_PRESS;
export type PressHighlightDelay = 'inScrollers' | 'always' | 'never';
@@ -139,7 +157,7 @@ export const PRESS_PROFILES = {
*/
cell: {
highlightDelay: 'inScrollers',
- cancelTravel: UIKIT_GESTURES.pan.hysteresis.value,
+ cancelTravel: UIKIT_PAN.hysteresis.value,
quickTapFlash: 0,
releaseMs: timing.press.highlightOutMs,
},
@@ -163,8 +181,8 @@ export function vetoesSingleTap(recognizer: GestureRecognizer): boolean {
/**
* A control's touch tracking, the gesture host's consumer for one element
* (UIControl's `beginTracking` / `continueTracking` / `endTracking`): it
- * reports control events and the highlight. Built by
- * {@link createPressTracker}.
+ * reports control events and the highlight, and keeps a continuous-tracking
+ * control's touch. Built by {@link createPressTracker}.
*/
export interface PressTracker extends TouchConsumer {
/** Whether the control paints its pressed highlight now. */
@@ -186,10 +204,21 @@ export interface PressTracker extends TouchConsumer {
allowsAncestorRecognizer(recognizer: unknown): boolean;
/** Drop any highlight and timers (the control unmounted or was disabled). */
dispose(): void;
+ /**
+ * Present only for a continuous-tracking control created with
+ * `keepsTouch: true` (a held stepper): once its press is delivered, the
+ * browser's pan must not take the touch. A plain pressable leaves it
+ * undefined and keeps passive listeners, so a scroll starting on it never
+ * waits on the main thread.
+ */
+ readonly keepsTouch?: (touchId: number) => boolean;
+ /** The selection lock of a control whose hold acts (FR41); see the option. */
+ readonly selectionLock: SelectionLock | undefined;
}
/** Track a control's touches (see {@link PressTracker}). */
export function createPressTracker(options: PressTrackerOptions): PressTracker {
+ let isKept = false;
let touchId: number | null = null;
let bounds: PressBounds | null = null;
let highlightTimer: ReturnType<typeof setTimeout> | null = null;
@@ -220,6 +249,11 @@ export function createPressTracker(options: PressTrackerOptions): PressTracker {
};
const setHighlighted = (value: boolean): void => {
+ if (value && touchId != null) {
+ // Delivered: the control keeps this touch until it ends (also when a
+ // quick tap's flash is still showing as the press arrives).
+ isKept = true;
+ }
if (state.isHighlighted === value) {
return;
}
@@ -242,6 +276,8 @@ export function createPressTracker(options: PressTrackerOptions): PressTracker {
};
const finish = (): void => {
+ // A highlight shown at the lift (a quick tap's flash) keeps nothing.
+ isKept = false;
touchId = null;
state.isTracking = false;
state.isTouchInside = false;
@@ -252,6 +288,7 @@ export function createPressTracker(options: PressTrackerOptions): PressTracker {
if (touch.id !== touchId) {
return;
}
+ isKept = false;
clearHighlightTimer();
emit('touchCancel', touch);
setHighlighted(false);
@@ -269,8 +306,7 @@ export function createPressTracker(options: PressTrackerOptions): PressTracker {
return state.isTouchInside;
},
trackingExpansion:
- options.trackingExpansion ??
- UIKIT_GESTURES.control.trackingExpansion.value,
+ options.trackingExpansion ?? UIKIT_CONTROL.trackingExpansion.value,
isEnabled(): boolean {
return options.isEnabled?.() !== false;
@@ -341,6 +377,7 @@ export function createPressTracker(options: PressTrackerOptions): PressTracker {
if (touch.id !== touchId) {
return;
}
+ isKept = false;
const inside = contains(touch);
const wasPending = highlightTimer != null;
clearHighlightTimer();
@@ -381,6 +418,16 @@ export function createPressTracker(options: PressTrackerOptions): PressTracker {
setHighlighted(false);
finish();
},
+
+ get selectionLock() {
+ return options.selectionLock;
+ },
};
+ if (options.keepsTouch === true) {
+ // Only the tracked touch whose press was delivered is kept.
+ return Object.assign(tracker, {
+ keepsTouch: (id: number) => isKept && touchId === id,
+ });
+ }
return tracker;
}
diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md
index f2da11247f..57b3bbf7a7 100644
--- a/packages/core/src/gestures/README.md
+++ b/packages/core/src/gestures/README.md
@@ -42,22 +42,48 @@ function Sheet() {
- The listener is read through a ref. Passing a new function on each render
attaches nothing new, and a gesture never causes a React render.
- The recognizer attaches in a layout effect, so the element's `touch-action`
- is set before the browser can see a finger.
-- The `isEnabled` option follows the prop. Turning it off mid-gesture ends
- the gesture without calling the listener, since the handler that turned
- it off owns that end (no consumer callback from an Effect). A recognizer
- that required it to fail recognizes a microtask later, outside the Effect,
- and its listener reports as usual. A handler that wants UIKit's
- `.cancelled` calls `recognizer.setEnabled(false)` itself, which reports it
- at once.
-- `usePressTracker` rebuilds its tracker when `trackingExpansion`,
- `highlightDelay`, `cancelTravel` or `quickTapFlash` change, from the next
- touch, and reads its callbacks (`isBraking` included) on every touch.
+ is set before the browser can see a finger. It follows the element behind
+ the ref: a node rendered after mount, or swapped behind the same ref (a
+ trigger rendered `as` another element), is attached at that commit.
+- `isEnabled: false` mid-gesture ends the gesture without calling the
+ listener, since the handler that turned it off owns that end (no consumer
+ callback from an Effect). A handler that wants UIKit's `.cancelled` calls
+ `recognizer.setEnabled(false)` itself, which reports it at once. A
+ recognizer that required it to fail (a single tap waiting on a double
+ tap) resolves just after that render, and its listener reports as usual;
+ so does one waiting on a recognizer whose node a render replaced. After
+ unmount the listener hears nothing, not even the cancellation of a
+ gesture the unmount ended.
+- `actionGroup: true` attaches the element as an action group, sibling
+ actions a held pointer slides across (`family:action-groups` FR5), served
+ like every attachment, for every pointer. Changing it attaches the
+ element again.
- `usePressTracker(ref, options)` gives an element `UIControl` touch tracking
- (see below).
+ (see below). It follows its element the same way, takes `isBraking` (by
+ default the host's: a touch that stops a flick presses nothing), and keeps
+ one tracker for the component's life: it reads `trackingExpansion`,
+ `highlightDelay`, `cancelTravel` and `quickTapFlash` (and the ref itself)
+ as they are now, so a change, even mid-press, never drops the press in
+ progress. Unmounting or losing its element calls neither
+ `onHighlightChange` nor `onControlEvent`, and neither does disabling the
+ control under a finger: the press ends, so the handler that disables it
+ clears its own highlight.
+- `useFingerScroll(scroller)`, an internal piece of the touch module with
+ no public API (not in the gestures barrel; a scroll-driven component
+ imports its module, so it ships only where used), returns a reader, `true` while the scroller's scroll is a finger's: from a scroll
+ while a finger that landed inside it is down, until its `scrollend` (the
+ momentum is still the finger's), or, where the browser fires none (mobile
+ Safari before 26), until its scroll events go quiet. Pass a ref, or the
+ document for the page. Outside React, `watchFingerScrolls(host, scroller)` and
+ `isFingerScroll(host, scroller)` from `fingerScroll.ts` do the same; that
+ module adds passive scroll listeners only while something is watched.
Outside React, `getGestureHost(document).attach(element, recognizer)` does
-the same and returns a detach function.
+the same and returns a detach function. `getGestureHost(document).fingersDown()`
+is how many fingers are on the screen (the last touch event's `touches`,
+wherever they landed): a recognizer that must not begin under a second
+finger checks it in `shouldBegin`, so two fingers stay the browser's pinch.
+Once a drag has claimed its finger, a second finger never breaks it.
## Recognizers
@@ -65,11 +91,18 @@ the same and returns a detach function.
| -------------------------------- | ---------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `TapGestureRecognizer` | `UITapGestureRecognizer` | discrete | `numberOfTapsRequired`, `numberOfTouchesRequired`; fails past 45 px of travel, on extra fingers, a hold over 1.5 s, a late or far next tap |
| `LongPressGestureRecognizer` | `UILongPressGestureRecognizer` | continuous | `minimumPressDuration` 500 ms, `allowableMovement` 10 px (a distance, not per axis), `numberOfTapsRequired`; a zero duration begins on the touch itself (a selection tracker over a group of actions) |
-| `PanGestureRecognizer` | `UIPanGestureRecognizer` | continuous | min/max touches, `direction` (axis or one-way) with `axisRatio`, `lockAxis`, `scrollEdge`; `translation()`, `totalTranslation()`, `velocity()` |
+| `PanGestureRecognizer` | `UIPanGestureRecognizer` | continuous | min/max touches, `direction` (axis or one-way) with `axisRatio`, `lockAxis`, `scrollEdge`; `translation()`, `totalTranslation()`, `velocity()`, `scrollVelocity()` |
| `SwipeGestureRecognizer` | `UISwipeGestureRecognizer` | discrete | recognized during the motion; one or more directions, `numberOfTouchesRequired`; 50 px along, at most 50 px across, 500 ms |
| `PinchGestureRecognizer` | `UIPinchGestureRecognizer` | continuous | `scale` (settable, to re-base it), `velocity` in scale per second, `focalPoint()` |
| `ScreenEdgePanGestureRecognizer` | `UIScreenEdgePanGestureRecognizer` | continuous | `edges`: `leading` / `trailing`, resolved against the view's writing direction; attached to an edge zone the view lies within; fails as soon as the touch lands outside every requested edge band; a finger's only |
+A recognizer created with `claimsTouches: false` is a watcher (a tab bar
+that minimizes while the page scrolls): it never claims, so its element gets
+only passive listeners and a scroll never waits for it; it prevents no other
+recognizer and none prevents it; and it follows a touch the browser takes
+for a scroll to the lift. It adds nothing to the element's derived
+`touch-action`.
+
Every recognizer also has UIKit's switches: `isEnabled` (use `setEnabled`;
turning it off mid-gesture cancels), `cancelsTouchesInView` (default true),
`delaysTouchesBegan` (default false), `delaysTouchesEnded` (default true),
@@ -124,7 +157,10 @@ each one that accepts it tracks it until it ends. Then:
The delegates `shouldRequireFailureOf` and `shouldBeRequiredToFailBy`
express the same thing dynamically.
- **Delegates.** `shouldBegin`, `shouldReceiveTouch`, and `canPrevent` /
- `canBePrevented` on subclasses.
+ `canBePrevented` on subclasses. The arena's plumbing (touch delivery,
+ approved transitions, a pending recognition) is `protected`: a subclass
+ overrides the `touches*` handlers and sets `state`, and only the gesture
+ system drives the rest.
```ts
// Single tap waits for the double tap to fail, as in UIKit.
@@ -186,16 +222,42 @@ presses nothing.
## What the browser is told
-- **Every pointer.** Gestures attach for a mouse, a pen and a finger
- (`spec:AST-094` FR43). Under a fine primary pointer an element whose
- gesture or press consumer is enabled listens with one passive
- `pointerdown`; a press (the primary button, a pen's contact or a finger)
- adds the page's listeners for that press alone, and they go once none of
- its contacts is down, except the `click` listener, which stays up to 1 s
- when a claimed lift owes a swallowed click (FR24). An element whose
- recognizer claims a moving finger also keeps its blocking `touchmove`
- (FR19). A right click, a pen's barrel button or a ctrl-click on macOS
- starts no press.
+- **Pens.** A pen drives every recognizer and press tracker as a finger
+ does: it pans, taps and long-presses; its hold, where the hold does
+ something, keeps text unselected as a finger's does (FR41); its barrel button is a
+ context click and starts no press; a pinch never mixes a pen with a
+ finger; and the screen-edge pan, a finger's only, ignores it (FR43).
+- **For every pointer.** Recognizers and press trackers attach for a mouse,
+ a pen and a finger alike (`spec:AST-094` FR43, FR19). Where the primary
+ pointer is coarse (`TOUCH_QUERY`, `../utils/coarsePointer.ts`), the host
+ listens while something enabled could take a touch. Where it is fine, each
+ element that uses a gesture keeps one passive `pointerdown` listener (and
+ a recognizer that claims a moving finger its blocking `touchmove`, which
+ FR24 counts outside that budget, FR19) and the page has none: a press on the element (a mouse's primary button, a
+ pen, or a finger, whose `pointerdown` comes before its `touchstart`)
+ adds the host's document and window listeners, and they go once that
+ press's contacts end and the arena has decided them (a tap that waits on
+ a double tap goes when that wait ends), or when the window blurs during it
+ (FR24). After the last detach the host holds nothing: no listener, note,
+ frame or timer. A press
+ tracker created with `keepsTouch` gets its blocking `touchmove` only
+ during such a press; where the pointer is coarse it keeps it, since
+ Safari honours a blocking listener only when it was registered before
+ the touch. A component that uses no gesture, and a
+ disabled recognizer or consumer, registers nothing; after a consumer's
+ `isEnabled()` changes, `host.update(element)` re-syncs. The screen-edge
+ pan stays off under a mouse, a trackpad and a pen (its recognizer allows
+ touches only; it takes no `allowedPointerTypes`), and a pinch
+ never mixes a pen with a finger (a recognizer takes one kind of pointer
+ at a time) (FR43). A press tracker takes a mouse press as a press, with
+ the fine-pointer profile: it paints at once, inside a scroller too, and
+ the scroll brake is a finger's only (FR11, DEC-21). A right click, a pen's
+ barrel button and a ctrl-click on macOS (its context click) start no press
+ (`isPrimaryClick`, `../utils/primaryClick.ts`). The host follows the
+ query (a tablet docking or undocking a mouse): turning fine cancels every
+ touch in flight. `perEventPointer`, an option of `attach`,
+ `attachConsumer`, `useGestureRecognizer` and `usePressTracker` from
+ before FR43, is accepted and does nothing.
- **`touch-action`.** Each element gets the intersection of what its
recognizers leave the browser, never wider than the element's own
`touch-action` (`spec:AST-094` FR18). Over an inline value the host writes
@@ -205,45 +267,104 @@ presses nothing.
allow where that is narrower than the author's rule. Detaching gives the
element its own value back (opt out with `manageStyle: false`):
- | Recognizers on the element | `touch-action` |
- | -------------------------------------------- | ------------------- |
- | tap, long press | `manipulation` |
- | horizontal pan or swipe, horizontal edge pan | `pan-y pinch-zoom` |
- | vertical pan or swipe | `pan-x pinch-zoom` |
- | one-way pan, pan with `scrollEdge` | left as is (`auto`) |
- | free pan | `pinch-zoom` |
- | pinch | `pan-x pan-y` |
- | pinch together with a free pan | `none` |
+ | Recognizers on the element | `touch-action` |
+ | ------------------------------------------------- | ------------------- |
+ | tap, long press | `manipulation` |
+ | horizontal pan or swipe | `pan-y pinch-zoom` |
+ | horizontal edge pan on a strip within its band | `pan-y pinch-zoom` |
+ | vertical pan or swipe | `pan-x pinch-zoom` |
+ | one-way pan, pan with `scrollEdge` | left as is (`auto`) |
+ | edge pan on a view wider than its band | left as is (`auto`) |
+ | free pan | `pinch-zoom` |
+ | pinch | `pan-x pan-y` |
+ | pinch together with a free pan | `none` |
+ | a watcher (`claimsTouches: false`), any direction | left as is (`auto`) |
A one-way pan leaves the browser its own axis too: a toast dragged away
from its edge scrolls the page. It claims its direction by cancelling
`touchmove` when it begins.
`pinch-zoom` stays in the value unless a pinch recognizer is
- attached, so the page stays zoomable (WCAG 1.4.4). A long press also turns
- off the iOS callout and text selection on its element.
+ attached, so the page stays zoomable (WCAG 1.4.4). A long press with a
+ hold also turns off the iOS callout and text selection on its element for
+ its press; one at 0 ms (a touch-down detector) or given
+ `selectionLock: null` leaves them to the browser.
+
+ While a finger or a pen is down, the host turns them off too only where
+ the hold does something (`spec:AST-094` FR41): on the element of a
+ recognizer created with a `selectionLock` (pass `lockSelection`; a
+ slider's thumb, a segmented
+ control's or a switch's drag) that would take the touch (enabled, and
+ accepting its pointer), restored when the contact ends. The host calls
+ the recognizer's lock and never imports one, so a component with no such
+ hold does not bundle it. A press tracker created with a `selectionLock`
+ (a control whose own record defines a hold action, such as a stepper's
+ hold-repeat) gets the same for each press. A press-tracked
+ control or row whose hold does nothing, and the document press
+ controller's surfaces (`usePressFeedback` rows), keep the browser's
+ long-press selection; a tap never selects. A non-text input under the finger inside such an element (a checkbox, a radio, a switch's input) is locked too: WebKit's own stylesheet makes every input selectable, which no ancestor's lock reaches. A text field keeps its selection, since a held finger places its caret. A
+ finger or a pen takes the lock under any primary pointer, a touchscreen
+ laptop and a desktop pen tablet included; a mouse never does, so mouse
+ selection is unchanged (`spec:AST-017` FR59); content under a sheet's or a
+ pager's pan stays selectable.
- **Claiming.** When a recognizer recognizes, it owns its touches. Each
element with a recognizer that can claim a moving touch (a pan, a swipe, a
long press that then drags, a pinch) has a non-passive
`touchmove` listener that cancels the event only while one of its touches
is owned. A touch nobody owns scrolls exactly as it would without the
- system. Taps claim only at the lift, so an element with only taps, or only
- a press consumer, gets no such listener (see the known limit below).
+ system. Taps claim only at the lift, and a recognizer that never claims
+ (`claimsTouches` false, such as a pull that only watches the scroll) never
+ owns a touch, so an element with only those, or only a press consumer,
+ gets no such listener (see the known limit below). A press tracker created
+ with `keepsTouch: true` (opt-in, for a continuous-tracking control such
+ as a held stepper; never plain buttons, links, cards or list cells) gets
+ one: once its press is delivered its finger's moves are cancelled, so the
+ browser's pan never takes the held control (UIKit's
+ `touchesShouldCancel(in:)` is false for a tracking control). Its element
+ also gets `touch-action: manipulation`, for every pointer, as a tap
+ recognizer's does (`spec:AST-094` FR18), so taps in quick succession
+ never zoom. Where the primary pointer is fine the blocking listener comes
+ only with a press: the element keeps its one `pointerdown` listener
+ (FR24), the press adds the `touchmove` before its `touchstart`, and the
+ kept finger's moves are cancelled from then on, as on a phone (FR11,
+ DEC-21). A scroll that starts on such a control waits on the main
+ thread; a move before the press is delivered still scrolls. The listener the host
+ adds to a finger's target at touch-down, for a target that leaves the
+ document mid-gesture, is passive too unless a recognizer on that touch can
+ claim while it moves.
- **Claim at the begin.** A pan claims its touch only as it begins, at
UIKit's 10 pt (`spec:AST-094` FR19), before WebKit commits a slow drag to
a scroll at 10–11 px; a drag the browser took first stays the browser's
- (FR14).
+ (FR14). One exception: a `scrollEdge` pan cancels its finger's moves from
+ the first one while every scroller under the finger is at its edge and
+ the finger pulls away from it, the pan's own way (the browser could only
+ rubber-band there); it still begins at 10 pt. It holds only while that is
+ the one finger on the screen: with a second down anywhere, the moves stay
+ the browser's, for its pinch (FR10).
+ Measured in Mobile Safari (iOS 26.2): `touchmove` arrives from the first
+ pixel; on a scrollable element WebKit commits to scrolling at 10 to 11 px
+ (the last cancelable `touchmove` at 10 px), and cancelling every
+ `touchmove` from 8 px keeps the page still for the whole gesture. Under
+ `pan-y` it scrolls only drags steeper than about 2:1 to 3:1, once the
+ vertical travel reaches about 10 px. A pan that competes with native
+ scrolling therefore decides at 10 px or less.
- **The browser's claim.** `pointercancel` on a finger, or a scroll above
- the touch, means the browser took the finger; so does its first `touchmove`
+ the touch once the finger has travelled the slop (the browser starts a pan
+ no earlier), means the browser took the finger; a scroll under a finger
+ that has not moved (scrollIntoView, a transcript pinned to its end, scroll
+ anchoring) is the page's own and leaves the press and its click alone. So
+ does its first `touchmove`
that can no longer be cancelled, when the browser could pan along the
finger's main axis. (Chromium also stops asking after one unconsumed
`touchmove` when `touch-action` keeps it from panning that way, as for a
horizontal drag under `pan-y`; that is not a claim.) Possible recognizers that share it fail, active ones are
cancelled, and the view's press is cancelled.
- **Clicks.** When a touch's gesture cancelled the view's touches, its
- `touchend` is cancelled (no click and no compatibility mouse events) and a
- one-shot guard swallows the next trusted click. A click held back for a
+ `touchend` is cancelled (no click and no compatibility mouse events) and
+ the shared click guard (`utils/clickGuard.ts`, the menu press model's
+ too) swallows the browser's next click, until the next `pointerdown` or
+ 400 ms. A click held back for a
recognizer that may still recognize (a double tap between taps) is
swallowed at once and replayed on the original target if the recognizer
fails. Clicks with `detail === 0` (keyboard, assistive technology, code)
@@ -259,7 +380,9 @@ presses nothing.
finger. This is the sheet over its own list: the pan begins only if nothing
under the touch could scroll for that movement, the finger landed at the
edge and pulls away from it. The browser has not committed yet, so beginning
-claims the touch and the content never moves.
+claims the touch and the content never moves. From the first move that
+pulls away from such an edge the pan already holds the finger, so its moves
+are cancelled before it begins and the page does not rubber-band either.
Who gets a drag is decided once, when it begins, as in UIKit: a drag that
began as a scroll stays the scroll view's for its whole length (it scrolls
@@ -268,14 +391,66 @@ to the top, then rubber-bands), and never changes hands midway
"Could scroll" follows the browser's own rules: `touch-action` between the
touch and each scroller, scroll chaining stopped by `overscroll-behavior`,
-and RTL `scrollLeft` ranges.
+and RTL `scrollLeft` ranges, along the flat tree (content slotted into a
+shadow-tree scroller scrolls with it, as the hit path does).
+
+### The input stream
+
+The host listens through `utils/inputStream.ts`, which it shares with the
+press feedback controller: one native listener per event type, on the
+window's capture phase, fanned out to every subscriber in order. It runs
+ahead of any document listener, so an app's window-capture
+`stopPropagation`, or a document-capture `stopImmediatePropagation`
+registered before core, no longer hides a touch from either, as UIKit's
+recognizers see touches before views do. A recognizer that must claim
+mid-gesture still needs the touch to reach its element, where its blocking
+`touchmove` sits, below such a stop. The stream stays ahead of an app's own
+window-capture listener only until a type's listener is re-added (a
+passivity switch, or a subscription after its last subscriber left), which
+appends it after the app's. A type's listener is passive unless a
+subscriber cancels it: the host cancels `touchend` and `contextmenu` there
+while a claiming participant is attached, never a `touchstart` or a
+`touchmove`, and the click guard (`../utils/clickGuard.ts`) keeps a
+cancelling `click` while it is armed, and from the menu press model's first
+arm on. A blocking `touchmove` sits on a claiming
+element and on a claimed touch's target, on the document while an element a
+claiming recognizer lives in is moving (Touches on moving elements), or on
+the window only while a page hold is held, so a page of pressables blocks
+no scroll.
+
+### Holding the page still
+
+A scroll lock may hold the page with `holdPageScroll(document, decide)` from
+`pageHold.ts`, which returns the release (none does yet: `useScrollLock`
+does not call it). It lives in its own module, so a page without a scroll
+lock never ships it, and it imports nothing of the gesture host: it asks the
+document's host whether a recognizer owns a touch only if a host exists, and
+a document without one has no recognizer to own it. A hold reads the
+primary pointer as it starts. Where it is coarse it listens at once, since
+Safari honours a blocking listener only when it was registered before the
+touch, and the first drag after an overlay opens is the one a hold is for;
+where it is fine it registers no touch listener until the input stream's
+`pointerdown` sees a touch or pen contact. Either way the hold follows the
+pointer from then on. While any hold is active, and only
+where the primary pointer is coarse, the input stream listens with a
+non-passive `touchmove`; where the contact's `touchstart` came before its
+`pointerdown`, the finger is named at its first move. Once per one-finger touch that no
+recognizer owns, after the
+finger clears a 5 px slop (under WebKit's 10–11 px scroll claim), it asks
+`decide(origin, dx, dy)` whether that pan would scroll the page, `origin`
+being the innermost node under the finger (the composed path's first node),
+and cancels the touch's moves for its whole length if so. A second finger is
+never cancelled, so pinch-zoom keeps working. With no hold, the listener is
+gone and every touch scrolls as without the system.
### Multiple fingers
-A second finger never breaks a one-finger pan that is already moving: the
-pan ignores it, and the claim keeps the browser from zooming with it. A
-second finger that lands before any recognizer has claimed fails the
-one-finger recognizers, so the two fingers zoom the page.
+A drag a recognizer has claimed keeps its finger: a second finger never
+cancels or redirects it (`spec:AST-094` FR10), as in UIKit, where a pan
+ignores touches beyond its maximum. Before any claim, a second finger landing
+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.
## Time
@@ -310,6 +485,11 @@ difference from iOS, whose filter never decays and so flings after a rest;
and 0 with fewer than two moved samples. The pan passes its lift's event time
to the tracker.
+Times are the events' own. A finger the browser reports on both pointer and
+touch events is sampled from its pointer events alone (from its touch events
+once the browser cancels its pointer), so the two copies of one move never
+both count.
+
## Haptics
`playHaptic(kind)` vibrates where `navigator.vibrate` exists, with one
@@ -317,7 +497,10 @@ pattern per UIKit feedback kind. iOS Safari has no vibration API. It plays a
light impact only when a real tap toggles an `<input type="checkbox"
switch>`, and WebKit requires a trusted event for it. `attachTapHaptic(label)`
puts a hidden switch inside a label the control renders as its tap target,
-so every real tap on it plays that impact. Nothing can play a haptic later
+so every real tap on it plays that impact; focus the activation gives the
+switch goes straight back. A label tied to its control by `for`, or whose
+control is itself a switch, gets no switch; a label wrapping its own control
+gets one, which hands each tap on to that control. Nothing can play a haptic later
from script, so mid-drag haptics (detent snaps, picker ticks) are not
possible in iOS Safari.
@@ -336,7 +519,8 @@ Whether a component presents itself the touch (UIKit) way is answered once,
in `../utils/touchPresentation.ts`:
- touch behaviours (UIKit springs and timings, the press model's touch
- profiles) key on a coarse PRIMARY pointer (`TOUCH_QUERY`);
+ profiles) key on a coarse PRIMARY pointer (`TOUCH_QUERY`); gestures
+ themselves attach for every pointer (What the browser is told);
- layout behaviours key on a compact viewport, below the theme's `md`
width point (`spec:AST-012` FR9): `COMPACT_QUERY` spells the default
points for a style, and behaviour reads the active theme's definition, so
@@ -352,6 +536,40 @@ is right. Behaviour reads
infer from included (UIKit timings under a finger, its own motion under a
mouse), and a decision taken once reads `readTouchPresentation()`.
+## Migrating a raw-touch drag
+
+A component that listens to touches itself moves onto the recognizers this
+way:
+
+1. No window or document touch listeners: attach a recognizer with
+ `useGestureRecognizer` and read `translation()` and `velocity()` per
+ state. The host owns the page-wide listeners.
+2. Pick the reading: a drag that coasts like a scroll view (a wheel, a
+ picker, a pager, a carousel) releases with the pan's `scrollVelocity()`;
+ anything else with `velocity()`. A one-way drag sets `direction`. The host derives
+ `touch-action`, so delete a hand-written one.
+3. Native scrolling: a sheet over its own list uses `scrollEdge`, not
+ `scrollTop` checks; who gets a drag is decided once, when it begins
+ (`spec:AST-094` FR14).
+4. A behavior that only watches the person's scrolling uses a watcher
+ (`claimsTouches: false`) and `useFingerScroll`.
+5. A scroll lock holds the page with `holdPageScroll`; no `preventDefault`
+ of its own.
+6. A drag limited to one finger sets `maximumNumberOfTouches: 1`. Before
+ it claims, a second finger fails it; once claimed, it keeps its finger
+ (`spec:AST-094` FR10). Delete a local pinch yield.
+7. The release hands `velocity()` (px/s, event time) to the animator.
+ Delete local estimators, sample buffers and time windows; a flick, fling
+ or commit threshold stays in the component, compared against it.
+8. A control whose hold acts (a slider's thumb, a stepper's hold-repeat)
+ passes `selectionLock: lockSelection` to its recognizer or press tracker
+ (`spec:AST-094` FR41); content drags keep selection.
+9. Presses use `usePressTracker`; `keepsTouch: true` only for a control that
+ tracks a held finger across its own area.
+10. Unit tests drive the gesture harness (`__tests__/harness.ts`) with
+ timestamped touches; interaction specs use real touch input, never
+ synthetic DOM events.
+
## Known limits
- **A scroll that begins on a recognizer waits for a busy main thread.** In
@@ -376,6 +594,44 @@ mouse), and a decision taken once reads `readTouchPresentation()`.
starts sideways), so a passive listener there would cost no parity. It
waits on a measured run on Android before any engine-specific choice.
+## Touches on moving elements
+
+iOS WebKit hit-tests an element that a compositor animation moves where
+the animation started: it keeps the transform it resolved when the
+animation went to the compositor, so event targets, `elementFromPoint` and
+`getBoundingClientRect` stay there for the whole curve, though the inline
+style holds the value the curve starts from and the computed style is live
+(iOS 26.2, measured; Chromium and Linux WebKit hit what is drawn). A finger on a settling sheet
+lands on whatever sat under the sheet's start (an upward release can hit
+the scrim and close the sheet). UIKit keeps an interruptible animation
+hit-testable where it is drawn (UIViewPropertyAnimator).
+
+A style write on the element makes WebKit resolve the transform again, to
+the value drawn at that moment, where it stays. So on iOS WebKit, at
+touch-down, the host has every element the animator reports as moving
+(`motion/presentation.ts`) resolved with one custom-property write, then
+asks the engine what is under the finger: the touch goes to what is drawn
+there, with z-order and `pointer-events` as the engine sees them. A touch
+that a busy main thread hands the host late goes to what was drawn under the
+finger when it landed (its timestamp): the host asks at the point that
+content has moved to since. Press
+trackers take their bounds from `presentedRect`, the reported box moved by
+the motion since. A retargeted tap cancels the engine's click,
+which would hit the start position, and clicks what it touched; the
+click guard drops a late engine click, so the tap acts once. Safari honours a
+blocking `touchmove` only where it was registered before the touch began,
+on the engine's own target, which for a moving element is whatever sits
+under its start: so while an element a claiming recognizer lives in is
+moving, the document carries the blocking listener, and a scroll starting
+anywhere waits on the main thread only for that long. Not covered:
+scale and rotate (a zoom transition, a lifted preview is hit at its
+unscaled box) and CSS transitions or animations the animator did not start.
+
+This is an engine workaround (`spec:AST-013` FR6). Its review condition:
+re-measure on each iOS release, and remove the correction once iOS WebKit
+hit-tests a compositor-moved element where it is drawn. Its regression
+fixture is `__tests__/presentedHitTesting.test.ts`.
+
## Where the web differs from UIKit
- Once a recognizer owns a touch, the browser cannot take the scroll back
@@ -405,10 +661,16 @@ mouse), and a decision taken once reads `readTouchPresentation()`.
click dispositions, cancellation, and multiple fingers.
- `__tests__/GestureHost.test.ts`: the DOM integration through real
listeners in jsdom.
-- `__tests__/VelocityTracker.test.ts`: UIKit's filter against the velocities
+- `__tests__/VelocityTracker.test.ts`: the filter against the velocities
UIKit reported on recorded touch streams, a steady speed and a hard
acceleration.
- `__tests__/haptics.test.ts`: vibration patterns and the hidden switch.
+- `__tests__/importGraph.test.ts`: a gesture-only component's static
+ imports (`useGestureRecognizer`, the pan recognizers, the host) reach
+ neither the press tracker nor haptics, which live behind
+ `usePressTracker` and `attachTapHaptic` / `playHaptic`.
+- `__tests__/useFingerScroll.test.tsx`: a finger's scroll until its
+ `scrollend`, the page through the document, and the ref's node followed.
- `__tests__/browser/`: the browser proof on a phone-sized touch screen, in
Chromium (CDP touches with timestamps) and WebKit (its own touch input),
with mouse and pen input in a fine-pointer context, run by
diff --git a/packages/core/src/gestures/TapGestureRecognizer.ts b/packages/core/src/gestures/TapGestureRecognizer.ts
index a8acc09ab6..209af5cb57 100644
--- a/packages/core/src/gestures/TapGestureRecognizer.ts
+++ b/packages/core/src/gestures/TapGestureRecognizer.ts
@@ -47,6 +47,11 @@ export class TapGestureRecognizer extends GestureRecognizer {
return 'tap';
}
+ /** @internal The host's brand: a tap decides at the lift, so it never claims mid-move (recognizerInternals). */
+ protected get family(): 'tap' {
+ return 'tap';
+ }
+
numberOfTapsRequired: number;
numberOfTouchesRequired: number;
allowableMovement: number;
diff --git a/packages/core/src/gestures/VelocityTracker.ts b/packages/core/src/gestures/VelocityTracker.ts
index c3838427a2..6c86de4285 100644
--- a/packages/core/src/gestures/VelocityTracker.ts
+++ b/packages/core/src/gestures/VelocityTracker.ts
@@ -121,6 +121,41 @@ export class VelocityTracker {
this.pan = panVelocity(this.moved);
}
+ /**
+ * Re-base the samples by an offset (a recognizer whose value was set
+ * mid-gesture): every interval, the moved-sample count and the velocity
+ * carry on unchanged.
+ */
+ offsetBy(dx: number, dy: number): void {
+ const shift = (sample: TouchSample): TouchSample => ({
+ ...sample,
+ x: sample.x + dx,
+ y: sample.y + dy,
+ });
+ this.newest = this.newest == null ? null : shift(this.newest);
+ this.moved = this.moved.map(shift);
+ }
+
+ /**
+ * Re-base the samples by a factor (a pinch whose scale was set
+ * mid-gesture): positions and velocities scale with it, and the
+ * moved-sample count carries on.
+ */
+ scaleBy(factor: number): void {
+ const scale = (sample: TouchSample): TouchSample => ({
+ ...sample,
+ x: sample.x * factor,
+ y: sample.y * factor,
+ });
+ this.newest = this.newest == null ? null : scale(this.newest);
+ this.moved = this.moved.map(scale);
+ this.pan = {x: this.pan.x * factor, y: this.pan.y * factor};
+ this.previousPan = {
+ x: this.previousPan.x * factor,
+ y: this.previousPan.y * factor,
+ };
+ }
+
/** Record every sample in order. */
addSamples(samples: ReadonlyArray<TouchSample>): void {
for (const sample of samples) {
diff --git a/packages/core/src/gestures/__tests__/GestureHost.bundle.test.ts b/packages/core/src/gestures/__tests__/GestureHost.bundle.test.ts
new file mode 100644
index 0000000000..d69b2b6275
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/GestureHost.bundle.test.ts
@@ -0,0 +1,105 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file GestureHost.bundle.test.ts
+ * @input GestureHost.ts, PressTracker.ts and usePressTracker.ts, bundled and
+ * minified by esbuild
+ * @output The gesture host, the press tracker and its hook carry only the
+ * UIKit gesture groups they read, never the whole table
+ * (architecture:component-style-authoring INV6)
+ * @position Bundle evidence for packages/core/src/gestures: every recognizer
+ * and press tracker attaches through the host, so what it imports ships
+ * with every touch component
+ */
+
+import {execFileSync} from 'node:child_process';
+import {mkdtempSync, rmSync, writeFileSync} from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {afterAll, describe, expect, it} from 'vitest';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const gestures = path.resolve(here, '..');
+const repoRoot = path.resolve(here, '../../../../..');
+// Inside the repo so the script resolves `esbuild` by bare specifier, and
+// under node_modules so it is ignored and swept with the install.
+const workspace = mkdtempSync(
+ path.join(repoRoot, 'node_modules', '.astryx-gesture-host-bundle-'),
+);
+afterAll(() => {
+ rmSync(workspace, {recursive: true, force: true});
+});
+
+const script = path.join(workspace, 'bundle.mjs');
+writeFileSync(
+ script,
+ [
+ "import {build} from 'esbuild';",
+ 'const [dir, module, name] = process.argv.slice(2);',
+ 'const out = await build({',
+ " stdin: {contents: `import {${name}} from './${module}'; console.log(${name});`, resolveDir: dir, loader: 'ts'},",
+ " bundle: true, minify: true, format: 'esm', write: false, logLevel: 'silent',",
+ '});',
+ 'console.log(JSON.stringify(out.outputFiles[0].text));',
+ ].join('\n'),
+);
+
+/** The minified bundle of one gestures module's named export. */
+function bundle(module: string, name = module): string {
+ return JSON.parse(
+ execFileSync(process.execPath, [script, gestures, module, name], {
+ encoding: 'utf8',
+ timeout: 120_000,
+ })
+ .trim()
+ .split('\n')
+ .pop() ?? '""',
+ ) as string;
+}
+
+describe('the gesture host bundle', () => {
+ const text = bundle('GestureHost');
+
+ it('carries the press group it reads', () => {
+ expect(text).toContain('scrollBrake:');
+ });
+
+ it('never carries the whole UIKit gesture table', () => {
+ // The table's own keys: only the union of every group has them.
+ expect(text).not.toContain('screenEdgePan:');
+ expect(text).not.toContain('longPress:');
+ // Groups the host never reads.
+ for (const key of [
+ 'edgeRegion:',
+ 'minimumMovementDecay:',
+ 'scrollReleaseWeight:',
+ ]) {
+ expect(text).not.toContain(key);
+ }
+ });
+});
+
+describe.each([
+ ['PressTracker', 'createPressTracker'],
+ ['usePressTracker', 'usePressTracker'],
+])('the %s bundle', (module, name) => {
+ // NumberInput's stepper and every control reach the press tracker.
+ const text = bundle(module, name);
+
+ it('carries the press, pan and control groups it reads', () => {
+ expect(text).toContain('scrollBrake:');
+ expect(text).toContain('trackingExpansion:');
+ });
+
+ it('never carries the whole UIKit gesture table', () => {
+ expect(text).not.toContain('screenEdgePan:');
+ expect(text).not.toContain('longPress:');
+ for (const key of [
+ 'edgeRegion:',
+ 'minimumMovementDecay:',
+ 'scrollReleaseWeight:',
+ ]) {
+ expect(text).not.toContain(key);
+ }
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts
index e90bcec389..590ff8a26e 100644
--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts
+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts
@@ -8,18 +8,31 @@
* @output The DOM integration: hit-path collection (shadow DOM included),
* touch-action negotiation, cancelling touchmove only while claimed,
* click suppression and replay, browser takeover, the mouse path,
- * context menus, focus loss
+ * context menus, focus loss, and telling a finger's scroll (until the
+ * scroller's scrollend) from the program's
* @position jsdom integration tests of packages/core/src/gestures
*/
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {UIKIT_GESTURES} from '../../motion/uikit/gestures';
+import {isFingerScroll, watchFingerScrolls} from '../fingerScroll';
import {GestureHost} from '../GestureHost';
import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';
import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {createPressTracker} from '../PressTracker';
+import type {SelectionLock} from '../GestureRecognizer';
+import {VelocityTracker} from '../VelocityTracker';
import {ScreenEdgePanGestureRecognizer} from '../ScreenEdgePanGestureRecognizer';
+import {lockSelection} from '../../utils/selectionLock';
import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {createNativeScrollProbe} from '../nativeScroll';
+import {gestureHosts} from '../hostRegistry';
+import {holdPageScroll, type PageScrollDecision} from '../pageHold';
import {ManualClock, RecordingConsumer} from './harness';
+import {TOUCH_QUERY} from '../../utils/touchQueries';
+import {registerPresentedOffset} from '../../motion/presentation';
+import {__resetClickGuardForTest} from '../../utils/clickGuard';
+import {coarsePrimaryPointer, pointerQuery} from './pointerQuery';
import type {GestureTouch} from '../types';
interface Contact {
@@ -59,7 +72,9 @@ function pointer(
pointerType: string;
x: number;
y: number;
+ button?: number;
buttons?: number;
+ ctrlKey?: boolean;
time: number;
},
): Event {
@@ -71,8 +86,9 @@ function pointer(
pointerType: init.pointerType,
clientX: init.x,
clientY: init.y,
- button: 0,
+ button: init.button ?? 0,
buttons: init.buttons ?? 0,
+ ctrlKey: init.ctrlKey ?? false,
});
Object.defineProperty(event, 'timeStamp', {value: init.time});
target.dispatchEvent(event);
@@ -82,6 +98,8 @@ function pointer(
let host: GestureHost;
let clock: ManualClock;
let detachers: (() => void)[];
+/** A phone: the host attaches only where the primary pointer is coarse. */
+let restorePointer: () => void;
/** jsdom computes no layout: give a scroller its metrics. */
function scrollable(
@@ -149,6 +167,28 @@ function hostRules(root: Document | ShadowRoot): string {
return [...adopted, ...styles].join('\n');
}
+/**
+ * Make `CSS.supports` answer as iOS WebKit does for its touch callout: there
+ * the selection lock is an inline style (`spec:AST-094` FR41), which these
+ * cases read.
+ */
+function asIosWebKit(): () => void {
+ const original = globalThis.CSS;
+ Object.defineProperty(globalThis, 'CSS', {
+ configurable: true,
+ value: {
+ ...original,
+ supports: (query: string) => query === '(-webkit-touch-callout: none)',
+ },
+ });
+ return () => {
+ Object.defineProperty(globalThis, 'CSS', {
+ configurable: true,
+ value: original,
+ });
+ };
+}
+
function mount(html: string): Record<string, HTMLElement> {
document.body.innerHTML = html;
const elements: Record<string, HTMLElement> = {};
@@ -160,8 +200,11 @@ function mount(html: string): Record<string, HTMLElement> {
beforeEach(() => {
clock = new ManualClock();
- host = new GestureHost(document, {clock, isPrimaryPointerCoarse: () => true});
+ // A phone by default: the shared host follows (pointer: coarse), which a
+ // test can turn fine with pointerQuery.
+ host = new GestureHost(document, {clock});
detachers = [];
+ restorePointer = coarsePrimaryPointer();
});
afterEach(() => {
@@ -169,8 +212,19 @@ afterEach(() => {
detach();
}
document.body.innerHTML = '';
+ restorePointer();
+ // A guard a case armed would keep its pointerdown subscription into the
+ // next case.
+ __resetClickGuardForTest();
});
+/** A press tracker whose hold acts, as a stepper's hold-repeat (FR41). */
+class LockingConsumer extends RecordingConsumer {
+ constructor(readonly selectionLock: SelectionLock = lockSelection) {
+ super();
+ }
+}
+
describe('GestureHost', () => {
it("measures a screen-edge pan's view, so an edge-zone strip takes the axis at UIKit's 15 px, not 10 (spec:AST-094 FR18)", () => {
const {strip} = mount('<div id="strip"></div>');
@@ -360,6 +414,31 @@ describe('GestureHost', () => {
expect(press.numberOfTouches).toBe(0);
});
+ it("keeps a recognizer's own-scroll exemption until the newest call's frame has passed, so an autoscroll every frame keeps its finger (spec:AST-094 FR30)", async () => {
+ const {list} = mount('<div id="list"><div id="row"></div></div>');
+ scrollable(list, {scrollHeight: 1000, clientHeight: 200});
+ const row = document.getElementById('row')!;
+ const press = new LongPressGestureRecognizer({
+ name: 'press',
+ allowableMovement: 100,
+ });
+ detachers.push(host.attach(row, press));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ const moved = {...finger, y: 40};
+ touch('touchmove', row, [moved], [moved], 16);
+ const frame = async () =>
+ new Promise(resolve => requestAnimationFrame(resolve));
+ // An edge autoscroll writes every frame, announcing each write.
+ host.ownScroll(list);
+ await frame();
+ host.ownScroll(list);
+ await frame();
+ // The first call's frame has passed, the newest one's has not.
+ list.dispatchEvent(new Event('scroll'));
+ expect(press.numberOfTouches).toBe(1);
+ });
+
it('watches the pointer kind only while something is attached (spec:AST-094 FR24)', () => {
const {box} = mount('<div id="box"></div>');
const add = vi.fn();
@@ -383,7 +462,7 @@ describe('GestureHost', () => {
}
});
- it('sets touch-action for every pointer while a recognizer is enabled (spec:AST-094 FR18, FR43)', () => {
+ it('sets touch-action while a recognizer is enabled, for every pointer (spec:AST-094 FR18, FR43)', () => {
const {box} = mount('<div id="box"></div>');
const mark = () => box.getAttribute('data-astryx-touch-action');
let coarse = false;
@@ -393,7 +472,7 @@ describe('GestureHost', () => {
});
const pan = new PanGestureRecognizer({direction: 'horizontal'});
const detach = host2.attach(box, pan);
- // A touchscreen laptop's finger gets it as a phone's does.
+ // A touchscreen laptop's finger needs it as much as a phone's.
expect(mark()).toBe('pan-y pinch-zoom');
pan.setEnabled(false);
expect(mark()).toBeNull();
@@ -408,11 +487,17 @@ describe('GestureHost', () => {
it('registers no document listener for a disabled consumer until it is enabled (spec:AST-094 FR24)', () => {
const {box} = mount('<div id="box"></div>');
- const added = vi.spyOn(document, 'addEventListener');
- const removed = vi.spyOn(document, 'removeEventListener');
- added.mockClear();
- removed.mockClear();
- const types = (spy: typeof added) =>
+ // The host listens through the window's input stream (utils/inputStream).
+ const addSpy = vi.spyOn(window, 'addEventListener');
+ const removeSpy = vi.spyOn(window, 'removeEventListener');
+ // The window is shared: give its methods back after this test.
+ detachers.push(() => {
+ addSpy.mockRestore();
+ removeSpy.mockRestore();
+ });
+ const added = addSpy;
+ const removed = removeSpy;
+ const types = (spy: typeof addSpy) =>
spy.mock.calls
.map(call => call[0])
.filter(t => /^(touch|pointer)/.test(t));
@@ -434,19 +519,54 @@ describe('GestureHost', () => {
detach();
});
- it('registers no page listener while idle where the primary pointer is fine, or while nothing enabled is attached (spec:AST-094 FR24, FR43)', () => {
+ it('stops listening when a detach leaves an element only disabled recognizers, or a consumer leaves only them (spec:AST-094 FR24)', () => {
const {box} = mount('<div id="box"></div>');
- const added = vi.spyOn(document, 'addEventListener');
- const removed = vi.spyOn(document, 'removeEventListener');
- added.mockClear();
+ // The host listens through the window's input stream (utils/inputStream).
+ const removed = vi.spyOn(window, 'removeEventListener');
+ // The window is shared: give its method back after this test.
+ detachers.push(() => removed.mockRestore());
+ const types = () =>
+ removed.mock.calls
+ .map(call => call[0])
+ .filter(t => /^(touch|pointer)/.test(t));
+ const coarse = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detachOff = coarse.attach(
+ box,
+ new PanGestureRecognizer({isEnabled: false}),
+ );
+ const detachOn = coarse.attach(box, new TapGestureRecognizer());
removed.mockClear();
- const types = (spy: typeof added) =>
+ detachOn();
+ expect(types()).toContain('touchstart');
+ const detachConsumer = coarse.attachConsumer(box, new RecordingConsumer());
+ removed.mockClear();
+ detachConsumer();
+ expect(types()).toContain('touchstart');
+ detachOff();
+ });
+
+ it('registers no page listener while idle where the primary pointer is fine, or while nothing enabled is attached (spec:AST-094 FR24, FR43)', () => {
+ const {box} = mount('<div id="box"></div>');
+ // The host listens through the window's input stream (utils/inputStream).
+ const addSpy = vi.spyOn(window, 'addEventListener');
+ const removeSpy = vi.spyOn(window, 'removeEventListener');
+ // The window is shared: give its methods back after this test.
+ detachers.push(() => {
+ addSpy.mockRestore();
+ removeSpy.mockRestore();
+ });
+ const added = addSpy;
+ const removed = removeSpy;
+ const types = (spy: typeof addSpy) =>
spy.mock.calls
.map(call => call[0])
.filter(t => /^(touch|pointer)/.test(t));
- // A fine primary pointer: the page has no listener; the element keeps
- // one passive pointerdown for its press and, as a claimer, its blocking
- // touchmove (FR19, a listener FR24 counts apart).
+ // 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).
const fine = new GestureHost(document, {
clock,
isPrimaryPointerCoarse: () => false,
@@ -454,13 +574,13 @@ describe('GestureHost', () => {
const boxAdded = vi.spyOn(box, 'addEventListener');
const detachFine = fine.attach(box, new PanGestureRecognizer());
expect(types(added)).toEqual([]);
- expect(boxAdded.mock.calls.map(call => [call[0], call[2]])).toEqual([
- ['touchmove', {passive: false}],
- ['pointerdown', {capture: true, passive: true}],
+ expect(boxAdded.mock.calls.map(call => call[0]).sort()).toEqual([
+ 'pointerdown',
+ 'touchmove',
]);
detachFine();
boxAdded.mockClear();
- // A coarse one, with only a disabled recognizer: nothing at all.
+ // A coarse one, with only a disabled recognizer: still nothing.
const coarse = new GestureHost(document, {
clock,
isPrimaryPointerCoarse: () => true,
@@ -770,44 +890,6 @@ describe('GestureHost', () => {
}
});
- it('turns selection and the callout off for one held press, only where the hold does something (spec:AST-094 FR41)', () => {
- const {hold, plain} = mount(
- '<div><div id="hold"></div><div id="plain"></div></div>',
- );
- detachers.push(host.attach(hold, new LongPressGestureRecognizer()));
- detachers.push(host.attach(plain, new TapGestureRecognizer()));
- // jsdom drops the prefixed properties, so the writes are observed.
- const set = vi.spyOn(hold.style, 'setProperty');
- const remove = vi.spyOn(hold.style, 'removeProperty');
- const plainSet = vi.spyOn(plain.style, 'setProperty');
- const finger = {id: 1, x: 10, y: 10};
- touch('touchstart', hold, [finger], [finger], 0);
- expect(set).toHaveBeenCalledWith('-webkit-touch-callout', 'none');
- expect(set).toHaveBeenCalledWith('user-select', 'none');
- expect(remove).not.toHaveBeenCalledWith('user-select');
- touch('touchend', hold, [finger], [], 100);
- expect(remove).toHaveBeenCalledWith('-webkit-touch-callout');
- expect(remove).toHaveBeenCalledWith('user-select');
- const other = {id: 2, x: 10, y: 40};
- touch('touchstart', plain, [other], [other], 200);
- expect(plainSet).not.toHaveBeenCalledWith('user-select', 'none');
- touch('touchend', plain, [other], [], 260);
- });
-
- it('leaves selection and the callout alone on an element attached with manageStyle: false, whose styles the caller keeps', () => {
- const {hold} = mount('<div id="hold"></div>');
- detachers.push(
- host.attach(hold, new LongPressGestureRecognizer(), {manageStyle: false}),
- );
- const set = vi.spyOn(hold.style, 'setProperty');
- const remove = vi.spyOn(hold.style, 'removeProperty');
- const finger = {id: 1, x: 10, y: 10};
- touch('touchstart', hold, [finger], [finger], 0);
- touch('touchend', hold, [finger], [], 100);
- expect(set).not.toHaveBeenCalled();
- expect(remove).not.toHaveBeenCalled();
- });
-
it('cancels touchmove only once a recognizer owns the touch, and swallows the click', () => {
const {box, child} = mount('<div id="box"><span id="child">x</span></div>');
const pan = new PanGestureRecognizer({name: 'pan'});
@@ -850,6 +932,26 @@ describe('GestureHost', () => {
expect(end.defaultPrevented).toBe(false);
});
+ it('keeps a claimed one-finger drag when a second finger lands on it (AST-094 FR10)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({maximumNumberOfTouches: 1});
+ detachers.push(host.attach(box, pan));
+ const first = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [first], [first], 0);
+ const moved = {...first, x: 40};
+ touch('touchmove', box, [moved], [moved], 16);
+ expect(pan.state).toBe('began');
+ const before = pan.translation().x;
+ const second = {id: 2, x: 200, y: 200};
+ touch('touchstart', box, [second], [moved, second], 20);
+ // The first finger keeps driving it, and its moves stay the pan's.
+ const next = {...first, x: 70};
+ const drag = touch('touchmove', box, [next], [next, second], 32);
+ expect(pan.state).toBe('changed');
+ expect(pan.translation().x).toBe(before + 30);
+ expect(drag.defaultPrevented).toBe(true);
+ });
+
it('leaves a second finger no recognizer owns to the page while the claimed one is held (spec:AST-094 FR19)', () => {
const {box} = mount('<div id="box"></div>');
const pan = new PanGestureRecognizer({maximumNumberOfTouches: 1});
@@ -858,6 +960,8 @@ describe('GestureHost', () => {
touch('touchstart', box, [first], [first], 0);
const moved = {...first, x: 40};
touch('touchmove', box, [moved], [moved], 16);
+ expect(pan.state).toBe('began');
+ const before = pan.translation().x;
const second = {id: 2, x: 200, y: 200};
touch('touchstart', box, [second], [moved, second], 20);
const pinchLike = touch(
@@ -870,6 +974,8 @@ describe('GestureHost', () => {
expect(pinchLike.defaultPrevented).toBe(false);
expect(pan.state).toBe('began');
expect(pan.numberOfTouches).toBe(1);
+ // The second finger's move never moves the pan.
+ expect(pan.translation().x).toBe(before);
// The claimed finger's own moves stay cancelled.
const own = touch(
'touchmove',
@@ -974,6 +1080,153 @@ describe('GestureHost', () => {
expect(host.arena.getTouch(1)?.takenByBrowser).toBe(true);
});
+ it.each([
+ ['WebKit, the touch copy 1 ms later', 1],
+ ['Chromium, both copies at one time', 0],
+ ])('samples a finger from its pointer events alone: %s', (_, offset) => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ let released = Number.NaN;
+ pan.addListener(r => {
+ if (r.state === 'ended') {
+ released = pan.velocity().x;
+ }
+ });
+ detachers.push(host.attach(box, pan));
+ pointer('pointerdown', box, {
+ id: 21,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 0, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ let x = 10;
+ for (let step = 1; step <= 10; step++) {
+ x += 10;
+ const time = step * 16;
+ pointer('pointermove', box, {
+ id: 21,
+ pointerType: 'touch',
+ x,
+ y: 10,
+ buttons: 1,
+ time,
+ });
+ touch(
+ 'touchmove',
+ box,
+ [{...finger, x}],
+ [{...finger, x}],
+ time + offset,
+ );
+ }
+ pointer('pointerup', box, {
+ id: 21,
+ pointerType: 'touch',
+ x,
+ y: 10,
+ time: 168,
+ });
+ touch('touchend', box, [{...finger, x}], [], 168);
+ // 10 px every 16 ms: 625 px/s, the steady drag's own speed.
+ expect(released).toBeCloseTo(625, 6);
+ });
+
+ it('samples a finger from its touch events once the browser cancels its pointer', () => {
+ const {box} = mount('<div id="box"></div>');
+ // A watcher follows the touch the browser takes (AST-094 FR20, DEC-7).
+ const pan = new PanGestureRecognizer({
+ name: 'pan',
+ claimsTouches: false,
+ direction: 'vertical',
+ });
+ detachers.push(host.attach(box, pan));
+ pointer('pointerdown', box, {
+ id: 21,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 0, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ pointer('pointermove', box, {
+ id: 21,
+ pointerType: 'touch',
+ x: 10,
+ y: 14,
+ buttons: 1,
+ time: 16,
+ });
+ expect(host.arena.getTouch(1)?.y).toBe(14);
+ // The browser takes the touch to scroll: the pointer channel ends, the
+ // finger keeps moving, and only touch events report it now.
+ pointer('pointercancel', box, {
+ id: 21,
+ pointerType: 'touch',
+ x: 10,
+ y: 14,
+ time: 20,
+ });
+ touch('touchmove', box, [{...finger, y: 60}], [{...finger, y: 60}], 32);
+ expect(host.arena.getTouch(1)?.y).toBe(60);
+ });
+
+ it('keeps every report of a 120 Hz finger', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ let released = Number.NaN;
+ pan.addListener(r => {
+ if (r.state === 'ended') {
+ released = pan.velocity().x;
+ }
+ });
+ detachers.push(host.attach(box, pan));
+ pointer('pointerdown', box, {
+ id: 21,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 0, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ // An accelerating drag reported every 8 ms on both channels.
+ const expected = new VelocityTracker();
+ expected.add(10, 10, 0);
+ let last = {x: 10, time: 0};
+ for (let step = 1; step <= 12; step++) {
+ const x = 10 + 3 * step * step;
+ const time = step * 8;
+ pointer('pointermove', box, {
+ id: 21,
+ pointerType: 'touch',
+ x,
+ y: 10,
+ buttons: 1,
+ time,
+ });
+ touch('touchmove', box, [{...finger, x}], [{...finger, x}], time);
+ expected.add(x, 10, time);
+ last = {x, time};
+ }
+ pointer('pointerup', box, {
+ id: 21,
+ pointerType: 'touch',
+ x: last.x,
+ y: 10,
+ time: last.time,
+ });
+ touch('touchend', box, [{...finger, x: last.x}], [], last.time);
+ // Every report counted once: the blend of the last two intervals.
+ expect(released).toBeCloseTo(expected.velocity().x, 6);
+ });
+
it("gives a finger's target a passive touchmove listener unless a recognizer on that touch can claim while it moves (spec:AST-094 FR19)", () => {
const {taps, pan} = mount(
'<div id="taps"><span id="tapChild">t</span></div><div id="pan"><span id="panChild">p</span></div>',
@@ -1070,22 +1323,127 @@ describe('GestureHost', () => {
touch('touchend', card, [{...finger, y: 88}], [], 64);
});
- it('leaves a scroll-edge pan to claim at its begin', () => {
- const {sheet} = mount('<div id="sheet"></div>');
- const pan = new PanGestureRecognizer({
- name: 'sheet',
- direction: 'down',
- scrollEdge: true,
+ describe("a scroll-edge pan's first moves (spec:AST-094 FR19, DEC-18)", () => {
+ /** A sheet whose own list sits under the finger, scrolled to `scrollTop`. */
+ function sheetOverList(scrollTop: number, options = {scrollEdge: true}) {
+ const {list, row} = mount(
+ '<div id="list" style="overflow-y: auto"><div id="row"></div></div>',
+ );
+ scrollable(list, {scrollTop, scrollHeight: 1000, clientHeight: 400});
+ const pan = new PanGestureRecognizer({
+ name: 'sheet',
+ direction: 'down',
+ ...options,
+ });
+ detachers.push(host.attach(row, pan));
+ const finger = {id: 1, x: 50, y: 100};
+ touch('touchstart', row, [finger], [finger], 0);
+ const at = (y: number, time: number, cancelable = true) =>
+ touch(
+ 'touchmove',
+ row,
+ [{...finger, y}],
+ [{...finger, y}],
+ time,
+ cancelable,
+ );
+ const lift = (y: number, time: number) =>
+ touch('touchend', row, [{...finger, y}], [], time);
+ return {list, pan, at, lift};
+ }
+
+ it('cancels the moves from the first one while every scroller under the finger is at its edge and the finger pulls away from it; the pan still begins at 10 px', () => {
+ const {pan, at, lift} = sheetOverList(0);
+ expect(at(102, 16).defaultPrevented).toBe(true);
+ expect(pan.state).toBe('possible');
+ expect(at(107, 32).defaultPrevented).toBe(true);
+ expect(pan.state).toBe('possible');
+ expect(at(112, 48).defaultPrevented).toBe(true);
+ expect(pan.state).toBe('began');
+ lift(112, 64);
+ });
+
+ it('leaves the moves to the browser while a scroller under the finger can still scroll that way', () => {
+ const {pan, at, lift} = sheetOverList(50);
+ expect(at(102, 16).defaultPrevented).toBe(false);
+ expect(at(107, 32).defaultPrevented).toBe(false);
+ expect(at(112, 48).defaultPrevented).toBe(false);
+ expect(pan.state).toBe('failed');
+ lift(112, 64);
+ });
+
+ it('leaves a first move toward the content to the browser', () => {
+ const {at, lift} = sheetOverList(0);
+ expect(at(98, 16).defaultPrevented).toBe(false);
+ lift(98, 32);
+ });
+
+ it('cancels nothing before a pan without scrollEdge begins', () => {
+ const {pan, at, lift} = sheetOverList(0, {scrollEdge: false});
+ expect(at(102, 16).defaultPrevented).toBe(false);
+ expect(at(107, 32).defaultPrevented).toBe(false);
+ expect(at(112, 48).defaultPrevented).toBe(true);
+ expect(pan.state).toBe('began');
+ lift(112, 64);
+ });
+
+ it('holds nothing while two fingers are down: a pinch at the edge stays the page\u2019s (spec:AST-094 FR10)', () => {
+ const {list, row} = mount(
+ '<div id="list" style="overflow-y: auto"><div id="row"></div></div>',
+ );
+ scrollable(list, {scrollTop: 0, scrollHeight: 1000, clientHeight: 400});
+ const pan = new PanGestureRecognizer({
+ name: 'sheet',
+ direction: 'down',
+ scrollEdge: true,
+ });
+ detachers.push(host.attach(row, pan));
+ const a = {id: 1, x: 50, y: 100};
+ const b = {id: 2, x: 150, y: 100};
+ touch('touchstart', row, [a], [a], 0);
+ touch('touchstart', row, [b], [a, b], 8);
+ // Both fingers move apart and down: a pinch, never cancelled.
+ const moved = [
+ {...a, x: 40, y: 104},
+ {...b, x: 160, y: 104},
+ ];
+ expect(touch('touchmove', row, moved, moved, 16).defaultPrevented).toBe(
+ false,
+ );
+ touch('touchend', row, moved, [], 32);
+ });
+
+ it('holds nothing while a second finger is down off the sheet: a pinch across the edge stays the page\u2019s (spec:AST-094 FR10)', () => {
+ const {pan} = sheetOverList(0);
+ const row = document.getElementById('row') as HTMLElement;
+ const page = document.createElement('div');
+ document.body.append(page);
+ const first = {id: 1, x: 50, y: 100};
+ const second = {id: 2, x: 150, y: 20};
+ touch('touchstart', page, [second], [first, second], 8);
+ // The sheet's finger pulls away from the list's top edge while the
+ // other finger, on plain page content, moves up: a pinch.
+ const moved = [
+ {...first, y: 108},
+ {...second, y: 12},
+ ];
+ expect(
+ touch('touchmove', row, [moved[0]], moved, 16).defaultPrevented,
+ ).toBe(false);
+ expect(pan.state).not.toBe('began');
+ touch('touchend', row, moved, [], 32);
+ page.remove();
+ });
+
+ it('cancels nothing once the browser has taken the touch for a scroll', () => {
+ const {list, at, lift} = sheetOverList(50);
+ // The browser scrolls the list: its moves can no longer be cancelled.
+ at(102, 16, false);
+ // The list reaches its edge under the same finger: still the browser's.
+ scrollable(list, {scrollTop: 0});
+ expect(at(107, 32).defaultPrevented).toBe(false);
+ lift(107, 48);
});
- detachers.push(host.attach(sheet, pan));
- const finger = {id: 1, x: 50, y: 100};
- touch('touchstart', sheet, [finger], [finger], 0);
- const at = (y: number, time: number) =>
- touch('touchmove', sheet, [{...finger, y}], [{...finger, y}], time);
- expect(at(107, 16).defaultPrevented).toBe(false);
- expect(at(112, 32).defaultPrevented).toBe(true);
- expect(pan.state).toBe('began');
- touch('touchend', sheet, [{...finger, y: 112}], [], 48);
});
it('names the pointer a finger, a pen or a mouse is driven by', () => {
@@ -1272,17 +1630,16 @@ describe('GestureHost', () => {
}
});
- it('reads a scroll above an unclaimed touch that has travelled as the browser taking it (spec:AST-094 FR20)', () => {
+ it('reads a scroll above an unclaimed touch that travelled its slop as the browser taking it', () => {
const {list, row} = mount('<div id="list"><div id="row"></div></div>');
- const tap = new TapGestureRecognizer({name: 'tap'});
- detachers.push(host.attach(row, tap));
+ const consumer = new RecordingConsumer();
+ detachers.push(host.attachConsumer(row, consumer));
const finger = {id: 1, x: 10, y: 10};
touch('touchstart', row, [finger], [finger], 0);
- const moved = {...finger, y: 20};
- touch('touchmove', row, [moved], [moved], 16);
+ const moved = {...finger, y: 10 + UIKIT_GESTURES.press.slop.value};
+ touch('touchmove', row, [moved], [moved], 16, false);
list.dispatchEvent(new Event('scroll'));
- expect(tap.state).toBe('possible');
- expect(tap.numberOfTouches).toBe(0);
+ expect(consumer.events.at(-1)).toMatch(/^cancelled/);
});
it('lets a scroll take an unclaimed touch from 10 px of travel, straight or diagonal, and not before (spec:AST-094 FR20)', () => {
@@ -1302,8 +1659,6 @@ describe('GestureHost', () => {
detach();
return taken;
};
- // A still finger: the scroll is the page's own (anchoring, a carousel).
- expect(takenAfter(0, 0)).toBe(false);
expect(takenAfter(0, 9)).toBe(false);
expect(takenAfter(0, 10)).toBe(true);
// 9.9 px and 11.3 px from where it landed.
@@ -1311,220 +1666,3447 @@ describe('GestureHost', () => {
expect(takenAfter(8, 8)).toBe(true);
});
- it('drives mouse input through Pointer Events', () => {
- const {box} = mount('<div id="box"></div>');
- const pan = new PanGestureRecognizer({name: 'pan'});
- let released = {x: 0, y: 0};
- pan.addListener(r => {
- if (r.state === 'ended') {
- released = r.velocity();
- }
- });
- detachers.push(host.attach(box, pan));
- pointer('pointerdown', box, {
- pointerType: 'mouse',
- x: 0,
- y: 0,
- buttons: 1,
- time: 0,
- });
- for (let t = 8; t <= 96; t += 8) {
- pointer('pointermove', box, {
- pointerType: 'mouse',
- x: t * 2,
+ it('lets a scroll take a finger inside an open shadow root too, comparing it with the scroller along the flat tree (spec:AST-094 FR20)', () => {
+ const {list, outer} = mount('<div id="list"><div id="outer"></div></div>');
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<div id="row">x</div>';
+ const row = shadow.getElementById('row') as HTMLElement;
+ const consumer = new RecordingConsumer();
+ detachers.push(host.attachConsumer(row, consumer));
+ // At the document, a touch's target is the shadow host.
+ const finger = {id: 1, x: 10, y: 10, target: outer};
+ touch('touchstart', row, [finger], [finger], 0);
+ const moved = {...finger, y: 22};
+ touch('touchmove', row, [moved], [moved], 16);
+ list.dispatchEvent(new Event('scroll'));
+ expect(consumer.events.some(event => event.startsWith('cancelled'))).toBe(
+ true,
+ );
+ touch('touchend', row, [moved], [], 32);
+ });
+
+ it("leaves a still finger's press and click alone when the page scrolls under it", () => {
+ const {list, button} = mount(
+ '<div id="list"><button id="button">Go</button></div>',
+ );
+ const consumer = new RecordingConsumer();
+ detachers.push(host.attachConsumer(button, consumer));
+ const clicks: number[] = [];
+ button.addEventListener('click', () => clicks.push(1));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', button, [finger], [finger], 0);
+ // The program scrolls (a transcript pinned to its end, scrollIntoView).
+ scrollable(list, {scrollTop: 50, scrollHeight: 2000, clientHeight: 300});
+ list.dispatchEvent(new Event('scroll'));
+ expect(consumer.events.some(event => event.startsWith('cancelled'))).toBe(
+ false,
+ );
+ const end = touch('touchend', button, [finger], [], 120);
+ expect(end.defaultPrevented).toBe(false);
+ expect(consumer.events.at(-1)).toMatch(/^ended/);
+ });
+
+ it("cancels a finger's moves only when a claimed pen's own stylus touch moves, never a finger nobody owns", () => {
+ const {pad, list} = mount('<div id="pad"></div><div id="list"></div>');
+ const drawing = new PanGestureRecognizer({name: 'draw'});
+ detachers.push(
+ host.attach(pad, drawing),
+ host.attach(
+ list,
+ new PanGestureRecognizer({name: 'other', direction: 'horizontal'}),
+ ),
+ );
+ for (const [x, time] of [
+ [0, 0],
+ [5, 16],
+ [30, 32],
+ ] as const) {
+ pointer(time === 0 ? 'pointerdown' : 'pointermove', pad, {
+ id: 9,
+ pointerType: 'pen',
+ x,
y: 0,
buttons: 1,
- time: t,
+ time,
});
}
- pointer('pointerup', box, {pointerType: 'mouse', x: 192, y: 0, time: 104});
- expect(pan.state).toBe('possible');
- expect(released.x).toBeCloseTo(2000, 0);
+ expect(drawing.state).toBe('began');
+ // A finger on the list, which no recognizer owns: its moves scroll.
+ const finger = {id: 4, x: 10, y: 10};
+ touch('touchstart', list, [finger], [finger], 40);
+ const move = touch(
+ 'touchmove',
+ list,
+ [{...finger, y: 40}],
+ [{...finger, y: 40}],
+ 56,
+ );
+ expect(move.defaultPrevented).toBe(false);
+ // The pen's own stylus touch is held: the browser must not pan with it.
+ const stylus = new Event('touchmove', {bubbles: true, cancelable: true});
+ const pen = {
+ identifier: 77,
+ clientX: 31,
+ clientY: 0,
+ target: pad,
+ touchType: 'stylus',
+ };
+ Object.defineProperty(stylus, 'changedTouches', {value: [pen]});
+ Object.defineProperty(stylus, 'touches', {value: [pen]});
+ Object.defineProperty(stylus, 'timeStamp', {value: 60});
+ pad.dispatchEvent(stylus);
+ expect(stylus.defaultPrevented).toBe(true);
+ pointer('pointerup', pad, {
+ id: 9,
+ pointerType: 'pen',
+ x: 31,
+ y: 0,
+ time: 80,
+ });
+ });
+
+ it('keeps every touchmove listener passive on a finger nothing can claim as it moves', () => {
+ const {taps, quiet} = mount('<div id="taps"></div><div id="quiet"></div>');
+ class Watcher extends PanGestureRecognizer {
+ override get claimsTouches(): boolean {
+ return false;
+ }
+ }
+ detachers.push(
+ host.attach(taps, new TapGestureRecognizer({name: 'tap'})),
+ host.attachConsumer(taps, new RecordingConsumer()),
+ host.attach(quiet, new Watcher({name: 'watcher'})),
+ );
+ for (const element of [taps, quiet]) {
+ const added = vi.spyOn(element, 'addEventListener');
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', element, [finger], [finger], 0);
+ const blocking = added.mock.calls.filter(
+ ([type, , options]) =>
+ type === 'touchmove' &&
+ (options as AddEventListenerOptions | undefined)?.passive === false,
+ );
+ expect(blocking).toHaveLength(0);
+ touch('touchend', element, [finger], [], 50);
+ }
+ });
+
+ it('follows the flat tree: content slotted into a shadow scroller scrolls with it', () => {
+ const {host: shell, item} = mount(
+ '<div id="host"><div id="item">row</div></div>',
+ );
+ const shadow = shell.attachShadow({mode: 'open'});
+ shadow.innerHTML =
+ '<div id="scroller" style="overflow-y: auto; height: 300px"><slot></slot></div>';
+ const scroller = shadow.getElementById('scroller') as HTMLElement;
+ scrollable(scroller, {
+ scrollTop: 200,
+ scrollHeight: 2000,
+ clientHeight: 300,
+ });
+ const probe = createNativeScrollProbe(item);
+ expect(probe.canScroll(0, 10)).toBe(true);
+ expect(probe.isInsideScroller).toBe(true);
+ });
+
+ it("writes a touch-action no wider than the caller's own", () => {
+ vi.useFakeTimers({toFake: ['setTimeout', 'requestAnimationFrame']});
+ const restore = touchActionFromData();
+ try {
+ const {trigger, strip} = mount(
+ '<div id="trigger" data-touch-action="none"></div><div id="strip" data-touch-action="pan-y"></div>',
+ );
+ const set = vi.spyOn(trigger.style, 'setProperty');
+ const setStrip = vi.spyOn(strip.style, 'setProperty');
+ detachers.push(
+ host.attach(trigger, new LongPressGestureRecognizer({name: 'hold'})),
+ host.attach(
+ strip,
+ new PanGestureRecognizer({name: 'h', direction: 'horizontal'}),
+ ),
+ );
+ vi.advanceTimersByTime(16);
+ // manipulation (the hold's) with none, and pan-y pinch-zoom (the
+ // pan's) with pan-y, allow the caller's own: its rule stays in force.
+ expect(window.getComputedStyle(trigger).touchAction).toBe('none');
+ expect(window.getComputedStyle(strip).touchAction).toBe('pan-y');
+ expect(set).not.toHaveBeenCalledWith('touch-action', expect.anything());
+ expect(setStrip).not.toHaveBeenCalledWith(
+ 'touch-action',
+ expect.anything(),
+ );
+ } finally {
+ restore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('marks an element with its derived touch-action as it attaches, under a rule any author rule outranks, with no inline write and no style read (spec:AST-094 FR18, DEC-8)', () => {
+ const restore = touchActionFromData();
+ try {
+ const {box} = mount('<div id="box"></div>');
+ const set = vi.spyOn(box.style, 'setProperty');
+ const read = vi.mocked(window.getComputedStyle);
+ read.mockClear();
+ detachers.push(
+ host.attach(box, new PanGestureRecognizer({direction: 'horizontal'})),
+ );
+ expect(box.getAttribute('data-astryx-touch-action')).toBe(
+ 'pan-y pinch-zoom',
+ );
+ expect(hostRules(document)).toContain(
+ ':where([data-astryx-touch-action="pan-y pinch-zoom"])',
+ );
+ expect(set).not.toHaveBeenCalledWith('touch-action', expect.anything());
+ expect(read).not.toHaveBeenCalled();
+ } finally {
+ restore();
+ }
+ });
+
+ it('leaves no touch-action rule in a document or shadow root once its last marked element lets go (spec:AST-094 FR24)', () => {
+ const restore = touchActionFromData();
+ try {
+ const {box, other, outer} = mount(
+ '<div id="box"></div><div id="other"></div><div id="outer"></div>',
+ );
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<div id="inner"></div>';
+ const inner = shadow.getElementById('inner') as HTMLElement;
+ const releaseBox = host.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
+ const releaseOther = host.attach(
+ other,
+ new PanGestureRecognizer({direction: 'vertical'}),
+ );
+ const releaseInner = host.attach(
+ inner,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
+ expect(hostRules(document)).toContain('data-astryx-touch-action');
+ expect(hostRules(shadow)).toContain('data-astryx-touch-action');
+ // One element still marked keeps its root's rules.
+ releaseBox();
+ expect(hostRules(document)).toContain('data-astryx-touch-action');
+ releaseOther();
+ expect(hostRules(document)).not.toContain('data-astryx-touch-action');
+ releaseInner();
+ expect(hostRules(shadow)).not.toContain('data-astryx-touch-action');
+ // A later attach brings its rule back.
+ detachers.push(
+ host.attach(box, new PanGestureRecognizer({direction: 'horizontal'})),
+ );
+ expect(hostRules(document)).toContain(
+ ':where([data-astryx-touch-action="pan-y pinch-zoom"])',
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ it("keeps an author rule in force from the first frame, and writes the intersection inline only where it is narrower than the author's (spec:AST-094 FR18)", () => {
+ vi.useFakeTimers({toFake: ['setTimeout', 'requestAnimationFrame']});
+ const restore = touchActionFromData();
+ try {
+ const {both, strip} = mount(
+ '<div id="both" data-touch-action="pan-x pan-y"></div><div id="strip" data-touch-action="pan-y"></div>',
+ );
+ const setBoth = vi.spyOn(both.style, 'setProperty');
+ const setStrip = vi.spyOn(strip.style, 'setProperty');
+ detachers.push(
+ host.attach(both, new PanGestureRecognizer({direction: 'horizontal'})),
+ host.attach(strip, new PanGestureRecognizer({direction: 'horizontal'})),
+ );
+ // Before the host reads anything, the author's value stands.
+ expect(both.getAttribute('data-astryx-touch-action')).toBe(
+ 'pan-y pinch-zoom',
+ );
+ expect(window.getComputedStyle(both).touchAction).toBe('pan-x pan-y');
+ expect(setBoth).not.toHaveBeenCalledWith(
+ 'touch-action',
+ expect.anything(),
+ );
+ vi.advanceTimersByTime(16);
+ // pan-y pinch-zoom with pan-x pan-y allows pan-y: narrower than the
+ // author's, so it is written.
+ expect(setBoth).toHaveBeenLastCalledWith('touch-action', 'pan-y');
+ // With pan-y it is the author's own value: nothing to write.
+ expect(setStrip).not.toHaveBeenCalledWith(
+ 'touch-action',
+ expect.anything(),
+ );
+ } finally {
+ restore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('removes the mark when the last recognizer detaches', () => {
+ const {box} = mount('<div id="box"></div>');
+ const detach = host.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
+ expect(box.hasAttribute('data-astryx-touch-action')).toBe(true);
+ detach();
+ expect(box.hasAttribute('data-astryx-touch-action')).toBe(false);
+ });
+
+ it('adds the rule to the shadow root an element is in', () => {
+ const {box} = mount('<div id="box"></div>');
+ const shadow = box.attachShadow({mode: 'open'});
+ const inner = document.createElement('div');
+ shadow.append(inner);
+ detachers.push(host.attach(inner, new LongPressGestureRecognizer()));
+ expect(inner.getAttribute('data-astryx-touch-action')).toBe('manipulation');
+ expect(hostRules(shadow)).toContain(
+ ':where([data-astryx-touch-action="manipulation"])',
+ );
+ });
+
+ it("is never wider than the author's touch-action, at any frame (spec:AST-094 FR18, DEC-8)", () => {
+ vi.useFakeTimers({toFake: ['setTimeout', 'requestAnimationFrame']});
+ const restore = touchActionFromData();
+ try {
+ const {trigger} = mount(
+ '<div id="trigger" data-touch-action="none"></div>',
+ );
+ const set = vi.spyOn(trigger.style, 'setProperty');
+ detachers.push(
+ host.attach(trigger, new LongPressGestureRecognizer({name: 'hold'})),
+ );
+ // The author's none outranks the host's manipulation from the attach
+ // on, and the read finds nothing to narrow.
+ expect(window.getComputedStyle(trigger).touchAction).toBe('none');
+ vi.advanceTimersByTime(16);
+ expect(window.getComputedStyle(trigger).touchAction).toBe('none');
+ expect(set).not.toHaveBeenCalledWith('touch-action', expect.anything());
+ } finally {
+ restore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('gives an element attached while on screen its touch-action in the attach itself', () => {
+ const restore = touchActionFromData();
+ try {
+ const {box} = mount('<div id="box"></div>');
+ detachers.push(host.attach(box, new TapGestureRecognizer({name: 'tap'})));
+ expect(window.getComputedStyle(box).touchAction).toBe('manipulation');
+ } finally {
+ restore();
+ }
+ });
+
+ it("reads no computed style while attaching: a caller's inline touch-action applies at once, a stylesheet's is read in the next frame", () => {
+ vi.useFakeTimers({toFake: ['setTimeout', 'requestAnimationFrame']});
+ const restore = touchActionFromData();
+ try {
+ const {trigger, strip} = mount(
+ '<div id="trigger" data-touch-action="none"></div><div id="strip"></div>',
+ );
+ // jsdom keeps no touch-action in a style: this stands in for the
+ // caller's inline `touch-action: pan-y`.
+ vi.spyOn(strip.style, 'getPropertyValue').mockImplementation(name =>
+ name === 'touch-action' ? 'pan-y' : '',
+ );
+ const set = vi.spyOn(trigger.style, 'setProperty');
+ const setStrip = vi.spyOn(strip.style, 'setProperty');
+ const read = vi.mocked(window.getComputedStyle);
+ read.mockClear();
+ detachers.push(
+ host.attach(trigger, new LongPressGestureRecognizer({name: 'hold'})),
+ host.attach(
+ strip,
+ new PanGestureRecognizer({name: 'h', direction: 'horizontal'}),
+ ),
+ );
+ // Attaching forces no style recalc over whatever just mounted.
+ expect(read).not.toHaveBeenCalled();
+ // The caller's inline value: pan-y pinch-zoom ∩ pan-y, at once.
+ expect(setStrip).toHaveBeenLastCalledWith('touch-action', 'pan-y');
+ // A stylesheet's value: read once in the next frame, where none is
+ // already no wider than both allow.
+ vi.advanceTimersByTime(16);
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(set).not.toHaveBeenCalledWith('touch-action', expect.anything());
+ } finally {
+ restore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('releases the same velocity for one stroke from a finger, a pen and a mouse (spec:AST-100 FR1, FR4)', () => {
+ const velocities: number[] = [];
+ for (const kind of ['touch', 'pen', 'mouse'] as const) {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: kind});
+ let released = 0;
+ pan.addListener(r => {
+ if (r.state === 'ended') {
+ released = r.velocity().x;
+ }
+ });
+ const detach = host.attach(box, pan);
+ const at = (x: number, time: number, type: 'down' | 'move' | 'up') => {
+ if (kind === 'touch') {
+ const finger = {id: 1, x, y: 0};
+ touch(
+ type === 'down'
+ ? 'touchstart'
+ : type === 'move'
+ ? 'touchmove'
+ : 'touchend',
+ box,
+ [finger],
+ type === 'up' ? [] : [finger],
+ time,
+ );
+ } else {
+ pointer(
+ type === 'down'
+ ? 'pointerdown'
+ : type === 'move'
+ ? 'pointermove'
+ : 'pointerup',
+ box,
+ {
+ id: 5,
+ pointerType: kind,
+ x,
+ y: 0,
+ buttons: type === 'up' ? 0 : 1,
+ time,
+ },
+ );
+ }
+ };
+ // Each stroke later than the last: the arena's clock never goes back.
+ const start = 1000 * (velocities.length + 1);
+ at(0, start, 'down');
+ for (let step = 1; step <= 10; step++) {
+ at(step * 12, start + step * 8, 'move');
+ }
+ at(120, start + 80, 'up');
+ velocities.push(released);
+ detach();
+ }
+ expect(velocities[0]).toBeGreaterThan(0);
+ expect(velocities[1]).toBeCloseTo(velocities[0], 6);
+ expect(velocities[2]).toBeCloseTo(velocities[0], 6);
+ });
+
+ describe('finger scrolls', () => {
+ it('reads a scroll while a finger that landed inside is down as the finger’s, until the scroller’s scrollend', () => {
+ const {list, row} = mount('<div id="list"><div id="row"></div></div>');
+ detachers.push(watchFingerScrolls(host, list));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(true);
+ // The lift starts the momentum: still the finger's scroll.
+ touch('touchend', row, [finger], [], 120);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(true);
+ list.dispatchEvent(new Event('scrollend'));
+ expect(isFingerScroll(host, list)).toBe(false);
+ });
+
+ it('forgets a finger scroll in progress when the watch stops listening, so a later program scroll is not the finger’s', () => {
+ const pointer = pointerQuery(true);
+ detachers.push(pointer.restore);
+ const {list, row} = mount('<div id="list"><div id="row"></div></div>');
+ detachers.push(watchFingerScrolls(host, list));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(true);
+ // The pointer turns fine mid-scroll: the watch stops listening, and its
+ // scrollend never comes.
+ pointer.set(false);
+ pointer.set(true);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(false);
+ });
+
+ it('reads a scroll under a finger inside an open shadow root as the finger’s, comparing them along the flat tree', () => {
+ const {list, outer} = mount(
+ '<div id="list"><div id="outer"></div></div>',
+ );
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<div id="row">x</div>';
+ const row = shadow.getElementById('row') as HTMLElement;
+ detachers.push(watchFingerScrolls(host, list));
+ const finger = {id: 1, x: 10, y: 10, target: outer};
+ touch('touchstart', row, [finger], [finger], 0);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(true);
+ });
+
+ it('counts a finger on a recognizer inside an open shadow root as down in a light-DOM scroller around it, whichever listener saw it last (spec:AST-094 FR20)', () => {
+ const {list, outer} = mount(
+ '<div id="list"><div id="outer"></div></div>',
+ );
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<div id="row">x</div>';
+ const row = shadow.getElementById('row') as HTMLElement;
+ // A recognizer on the inner node: the host also listens there, where
+ // the browser hands the touch's target as that node.
+ detachers.push(
+ host.attach(row, new PanGestureRecognizer({direction: 'vertical'})),
+ );
+ const finger = {id: 1, x: 10, y: 10, target: row};
+ touch('touchstart', row, [finger], [finger], 0);
+ const moved = {...finger, y: 12};
+ touch('touchmove', row, [moved], [moved], 16);
+ expect(host.isFingerDownIn(list)).toBe(true);
+ expect(host.isFingerDownIn(outer)).toBe(true);
+ });
+
+ it('arms the scroll brake for a flick by a finger inside an open shadow root, and brakes a touch there, comparing along the flat tree', () => {
+ const {list, outer} = mount(
+ '<div id="list"><div id="outer"></div></div>',
+ );
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<div id="row">x</div>';
+ const row = shadow.getElementById('row') as HTMLElement;
+ const consumer = new RecordingConsumer();
+ detachers.push(host.attachConsumer(row, consumer));
+ const finger = {id: 1, x: 10, y: 10, target: outer};
+ touch('touchstart', row, [finger], [finger], 0);
+ const moved = {...finger, y: 40};
+ touch('touchmove', row, [moved], [moved], 16);
+ // Each scroll at its own time, on the touches' clock.
+ const scroll = (time: number) => {
+ const event = new Event('scroll');
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ list.dispatchEvent(event);
+ };
+ scroll(24);
+ touch('touchend', row, [moved], [], 32);
+ scroll(48);
+ expect(host.isScrollBraking(row)).toBe(true);
+ });
+
+ it('reads a scroll with no finger down as the program’s, even right after a tap', () => {
+ const {list, row} = mount('<div id="list"><div id="row"></div></div>');
+ detachers.push(watchFingerScrolls(host, list));
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(false);
+ // A tap whose click scrolls the list (a scrollTo after the lift).
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ touch('touchend', row, [finger], [], 80);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(false);
+ });
+
+ it('reads the page’s own scroll on the document', () => {
+ const {row} = mount('<div id="row"></div>');
+ detachers.push(watchFingerScrolls(host, document));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ document.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, document)).toBe(true);
+ touch('touchend', row, [finger], [], 120);
+ document.dispatchEvent(new Event('scrollend'));
+ expect(isFingerScroll(host, document)).toBe(false);
+ });
+
+ it('does not count a finger down outside the scroller', () => {
+ const {list, other} = mount(
+ '<div id="list"><div id="row"></div></div><div id="other"></div>',
+ );
+ detachers.push(watchFingerScrolls(host, list));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', other, [finger], [finger], 0);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(false);
+ });
+
+ it('keeps a scroll that ends while the finger still rests the finger’s until the lift', () => {
+ const {list, row} = mount('<div id="list"><div id="row"></div></div>');
+ detachers.push(watchFingerScrolls(host, list));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ list.dispatchEvent(new Event('scroll'));
+ list.dispatchEvent(new Event('scrollend'));
+ expect(isFingerScroll(host, list)).toBe(true);
+ // Lifting without moving the list again ends it.
+ touch('touchend', row, [finger], [], 300);
+ expect(isFingerScroll(host, list)).toBe(false);
+ });
+
+ it('ends a finger’s scroll after a quiet spell where the browser sends no scrollend', () => {
+ vi.useFakeTimers();
+ const own = Object.getOwnPropertyDescriptor(window, 'onscrollend');
+ const proto = Object.getPrototypeOf(window) as object;
+ const inherited = Object.getOwnPropertyDescriptor(proto, 'onscrollend');
+ Reflect.deleteProperty(window, 'onscrollend');
+ Reflect.deleteProperty(proto, 'onscrollend');
+ try {
+ expect('onscrollend' in window).toBe(false);
+ const {list, row} = mount('<div id="list"><div id="row"></div></div>');
+ detachers.push(watchFingerScrolls(host, list));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ list.dispatchEvent(new Event('scroll'));
+ touch('touchend', row, [finger], [], 120);
+ // The momentum keeps scrolling: still the finger's.
+ vi.advanceTimersByTime(100);
+ list.dispatchEvent(new Event('scroll'));
+ vi.advanceTimersByTime(100);
+ expect(isFingerScroll(host, list)).toBe(true);
+ // Quiet for the fallback spell: the scroll has ended.
+ vi.advanceTimersByTime(60);
+ expect(isFingerScroll(host, list)).toBe(false);
+ // A program's scroll afterwards is not the finger's.
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(false);
+ } finally {
+ if (inherited != null) {
+ Object.defineProperty(proto, 'onscrollend', inherited);
+ }
+ if (own != null) {
+ Object.defineProperty(window, 'onscrollend', own);
+ }
+ vi.useRealTimers();
+ }
+ });
+
+ it('forgets a scroller once nobody watches it', () => {
+ const {list, row} = mount('<div id="list"><div id="row"></div></div>');
+ const stop = watchFingerScrolls(host, list);
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(true);
+ stop();
+ expect(isFingerScroll(host, list)).toBe(false);
+ list.dispatchEvent(new Event('scroll'));
+ expect(isFingerScroll(host, list)).toBe(false);
+ });
+ });
+
+ it('drives mouse input through Pointer Events', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ let released = {x: 0, y: 0};
+ pan.addListener(r => {
+ if (r.state === 'ended') {
+ released = r.velocity();
+ }
+ });
+ detachers.push(host.attach(box, pan));
+ pointer('pointerdown', box, {
+ pointerType: 'mouse',
+ x: 0,
+ y: 0,
+ buttons: 1,
+ time: 0,
+ });
+ for (let t = 8; t <= 96; t += 8) {
+ pointer('pointermove', box, {
+ pointerType: 'mouse',
+ x: t * 2,
+ y: 0,
+ buttons: 1,
+ time: t,
+ });
+ }
+ pointer('pointerup', box, {pointerType: 'mouse', x: 192, y: 0, time: 104});
+ expect(pan.state).toBe('possible');
+ expect(released.x).toBeCloseTo(2000, 0);
});
it('cancels the context menu while a long press owns the touch', () => {
const {box} = mount('<div id="box"></div>');
- const press = new LongPressGestureRecognizer({name: 'press'});
- detachers.push(host.attach(box, press));
- const finger = {id: 1, x: 10, y: 10};
- touch('touchstart', box, [finger], [finger], 0);
- const before = new MouseEvent('contextmenu', {
+ const press = new LongPressGestureRecognizer({name: 'press'});
+ detachers.push(host.attach(box, press));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ const before = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ });
+ box.dispatchEvent(before);
+ expect(before.defaultPrevented).toBe(false);
+ host.arena.advanceTime(500);
+ expect(press.state).toBe('began');
+ const during = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ });
+ box.dispatchEvent(during);
+ expect(during.defaultPrevented).toBe(true);
+ });
+
+ it('holds the click of a tap a double tap may claim, and replays it when the double tap fails', () => {
+ const {row, button} = mount(
+ '<div id="row"><button id="button">Go</button></div>',
+ );
+ const double = new TapGestureRecognizer({
+ name: 'double',
+ numberOfTapsRequired: 2,
+ });
+ detachers.push(host.attach(row, double));
+ const clicks: {target: EventTarget | null; detail: number}[] = [];
+ button.addEventListener('click', event =>
+ clicks.push({target: event.target, detail: event.detail}),
+ );
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', button, [finger], [finger], 0);
+ const end = touch('touchend', button, [finger], [], 60);
+ expect(end.defaultPrevented).toBe(true);
+ expect(clicks).toEqual([]);
+ const interval = UIKIT_GESTURES.tap.maximumIntervalBetweenTaps.value;
+ host.arena.advanceTime(60 + interval);
+ expect(clicks).toEqual([{target: button, detail: 1}]);
+ });
+
+ it('collects recognizers across shadow roots', () => {
+ const {outer} = mount('<div id="outer"></div>');
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<span id="inner">x</span>';
+ const inner = shadow.getElementById('inner') as HTMLElement;
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const actions: string[] = [];
+ tap.addListener(r => actions.push(r.state));
+ detachers.push(host.attach(outer, tap));
+ const finger = {id: 1, x: 5, y: 5, target: inner};
+ touch('touchstart', inner, [finger], [finger], 0);
+ touch('touchend', inner, [finger], [], 50);
+ expect(actions).toEqual(['ended']);
+ });
+
+ it('gives a recognizer inside a shadow root its finger: a touch reaches the page retargeted to the shadow host, and the composed path names what it landed on', () => {
+ const {outer} = mount('<div id="outer"></div>');
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<span id="inner">x</span>';
+ const inner = shadow.getElementById('inner') as HTMLElement;
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const actions: string[] = [];
+ tap.addListener(r => actions.push(r.state));
+ detachers.push(host.attach(inner, tap));
+ // At the document, a touch's target is the shadow host, as the event's.
+ const finger = {id: 1, x: 5, y: 5, target: outer};
+ touch('touchstart', inner, [finger], [finger], 0);
+ touch('touchend', inner, [finger], [], 50);
+ expect(actions).toEqual(['ended']);
+ });
+
+ it('gives a recognizer inside a shadow root a mouse press too, the pointer event retargeted to the shadow host at the document', () => {
+ const {outer} = mount('<div id="outer"></div>');
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<span id="inner">x</span>';
+ const inner = shadow.getElementById('inner') as HTMLElement;
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const actions: string[] = [];
+ tap.addListener(r => actions.push(r.state));
+ detachers.push(host.attach(inner, tap));
+ pointer('pointerdown', inner, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ pointer('pointerup', inner, {pointerType: 'mouse', x: 5, y: 5, time: 50});
+ expect(actions).toEqual(['ended']);
+ });
+
+ it.each([
+ ['stopPropagation on the window', window, 'stopPropagation'],
+ [
+ 'stopImmediatePropagation on the document',
+ document,
+ 'stopImmediatePropagation',
+ ],
+ ] as const)(
+ "recognizes a touch an app's capture-phase listener, registered first, stops (%s)",
+ (_name, node, stop) => {
+ const {box} = mount('<div id="box"></div>');
+ const listener = (event: Event) => event[stop]();
+ const types = ['touchstart', 'touchmove', 'touchend'] as const;
+ // The app listens before any recognizer exists (the host installs on
+ // its first attach), as an app shell does.
+ for (const type of types) {
+ node.addEventListener(type, listener, {capture: true});
+ }
+ try {
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(host.attach(box, pan));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ touch('touchmove', box, [{...finger, x: 40}], [{...finger, x: 40}], 16);
+ touch('touchend', box, [{...finger, x: 40}], [], 32);
+ // The host hears the window's capture phase: a listener on the same
+ // node still runs after stopPropagation, and the window comes before
+ // the document.
+ expect(states).toEqual(['began', 'ended']);
+ } finally {
+ for (const type of types) {
+ node.removeEventListener(type, listener, {capture: true});
+ }
+ }
+ },
+ );
+
+ it('cancels every touch in flight when the window loses focus', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(host.attach(box, pan));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ touch('touchmove', box, [{...finger, x: 40}], [{...finger, x: 40}], 16);
+ window.dispatchEvent(new Event('blur'));
+ expect(states).toEqual(['began', 'cancelled']);
+ });
+
+ it('remembers a finger the window blur cancelled until it lifts, and refuses that lift its click: nothing acts (spec:AST-094 FR28)', () => {
+ const {box, page} = mount('<div id="box"></div><p id="page">text</p>');
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const states: string[] = [];
+ tap.addTransitionListener((_r, _from, to) => states.push(to));
+ detachers.push(host.attach(box, tap));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ window.dispatchEvent(new Event('blur'));
+ // The browser kept the touch alive: its lift would click the box.
+ const lift = touch('touchend', box, [finger], [], 80);
+ expect(lift.defaultPrevented).toBe(true);
+ expect(states).not.toContain('ended');
+ // Only that lift: a later finger with the same identifier keeps its
+ // click.
+ touch('touchstart', page, [finger], [finger], 200);
+ expect(touch('touchend', page, [finger], [], 260).defaultPrevented).toBe(
+ false,
+ );
+ // A cancelled finger whose lift never came: the next touch with its
+ // identifier is a new finger, and its lift keeps its click too.
+ touch('touchstart', box, [finger], [finger], 300);
+ window.dispatchEvent(new Event('blur'));
+ touch('touchstart', page, [finger], [finger], 400);
+ expect(touch('touchend', page, [finger], [], 460).defaultPrevented).toBe(
+ false,
+ );
+ });
+
+ it('finishes a gesture whose target left the document mid-gesture', () => {
+ const {box, child} = mount('<div id="box"><span id="child">x</span></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(host.attach(box, pan));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', child, [finger], [finger], 0);
+ touch('touchmove', child, [{...finger, x: 40}], [{...finger, x: 40}], 16);
+ // A re-render replaces the span: its events no longer reach the document.
+ child.remove();
+ const move = touch(
+ 'touchmove',
+ child,
+ [{...finger, x: 60}],
+ [{...finger, x: 60}],
+ 32,
+ );
+ expect(move.defaultPrevented).toBe(true);
+ touch('touchend', child, [{...finger, x: 60}], [], 48);
+ // The move and the lift after the removal still reached the pan.
+ expect(states).toEqual(['began', 'changed', 'ended']);
+ expect(host.arena.touches).toEqual([]);
+ });
+
+ it('cancels a finger the events say is no longer down', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(host.attach(box, pan));
+ const first = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [first], [first], 0);
+ touch('touchmove', box, [{...first, x: 40}], [{...first, x: 40}], 16);
+ // Its touchend went to a node outside the document; the next event for
+ // another finger no longer lists it.
+ const other = {id: 2, x: 300, y: 300};
+ touch('touchmove', document.body, [other], [other], 32);
+ expect(states).toEqual(['began', 'cancelled']);
+ });
+
+ it('treats a reused finger number as a new touch', () => {
+ const {box} = mount('<div id="box"></div>');
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const states: string[] = [];
+ tap.addListener(r => states.push(r.state));
+ detachers.push(host.attach(box, tap));
+ const finger = {id: 4, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ // No touchend reached us; the same identifier lands again.
+ touch('touchstart', box, [finger], [finger], 500);
+ touch('touchend', box, [finger], [], 560);
+ expect(states).toEqual(['ended']);
+ });
+
+ it('cancels every finger on a touchcancel that names none', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(host.attach(box, pan));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ touch('touchmove', box, [{...finger, x: 40}], [{...finger, x: 40}], 16);
+ box.dispatchEvent(new Event('touchcancel', {bubbles: true}));
+ expect(states).toEqual(['began', 'cancelled']);
+ });
+
+ it('reads epoch-stamped events on the arena clock', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ let released = {x: 0, y: 0};
+ pan.addListener(r => {
+ if (r.state === 'ended') {
+ released = r.velocity();
+ }
+ });
+ detachers.push(host.attach(box, pan));
+ const epoch = performance.timeOrigin + 5000;
+ const finger = {id: 1, x: 0, y: 10};
+ touch('touchstart', box, [finger], [finger], epoch);
+ for (let t = 8; t <= 96; t += 8) {
+ const at = {...finger, x: t};
+ touch('touchmove', box, [at], [at], epoch + t);
+ }
+ touch('touchend', box, [{...finger, x: 96}], [], epoch + 100);
+ expect(released.x).toBeCloseTo(1000, 0);
+ expect(host.arena.now()).toBeLessThan(1e9);
+ });
+
+ it('locks only for a recognizer that would take the contact: enabled, and accepting its pointer kind', () => {
+ detachers.push(coarsePrimaryPointer());
+ const {slider, stylus} = mount(
+ '<div><div id="slider"></div><div id="stylus"></div></div>',
+ );
+ const release = vi.fn();
+ const lock = vi.fn(() => release);
+ const drag = new PanGestureRecognizer({
+ name: 'drag',
+ direction: 'horizontal',
+ selectionLock: lock,
+ });
+ detachers.push(host.attach(slider, drag));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', slider, [finger], [finger], 0);
+ expect(lock).toHaveBeenCalledTimes(1);
+ touch('touchend', slider, [finger], [], 40);
+ expect(release).toHaveBeenCalledTimes(1);
+ drag.setEnabled(false);
+ touch('touchstart', slider, [finger], [finger], 100);
+ touch('touchend', slider, [finger], [], 140);
+ expect(lock).toHaveBeenCalledTimes(1);
+ // A pen-only drag locks for a pen: pen acceptance decides, not touch.
+ const penLock = vi.fn(() => () => {});
+ detachers.push(
+ host.attach(
+ stylus,
+ new PanGestureRecognizer({
+ name: 'pen',
+ direction: 'horizontal',
+ allowedPointerTypes: ['pen'],
+ selectionLock: penLock,
+ }),
+ ),
+ );
+ pointer('pointerdown', stylus, {
+ id: 7,
+ pointerType: 'pen',
+ x: 10,
+ y: 10,
+ time: 200,
+ });
+ expect(penLock).toHaveBeenCalledTimes(1);
+ pointer('pointerup', stylus, {
+ id: 7,
+ pointerType: 'pen',
+ x: 10,
+ y: 10,
+ time: 240,
+ });
+ });
+
+ it('shares one blocking touchmove handler among the elements that claim while moving: 200 pans, one handler, none for a tap (spec:AST-094 FR19)', () => {
+ const added = vi.spyOn(Element.prototype, 'addEventListener');
+ try {
+ const pans = Array.from({length: 200}, () => {
+ const element = document.createElement('div');
+ document.body.appendChild(element);
+ detachers.push(
+ host.attach(
+ element,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ ),
+ () => element.remove(),
+ );
+ return element;
+ });
+ const tapTarget = document.createElement('div');
+ document.body.appendChild(tapTarget);
+ detachers.push(host.attach(tapTarget, new TapGestureRecognizer()), () =>
+ tapTarget.remove(),
+ );
+ const blocking = added.mock.calls
+ .map((call, index) => ({
+ call,
+ element: added.mock.contexts[index] as Element,
+ }))
+ .filter(
+ ({call: [type, , options]}) =>
+ type === 'touchmove' &&
+ typeof options === 'object' &&
+ options.passive === false,
+ );
+ // Each claiming element carries the listener itself, so a scroll that
+ // starts outside the rows never waits on it...
+ expect(blocking.map(({element}) => element)).toEqual(pans);
+ // ...and all of them share the host's one handler.
+ expect(new Set(blocking.map(({call}) => call[1])).size).toBe(1);
+ } finally {
+ added.mockRestore();
+ }
+ });
+
+ it('keeps native long-press selection on a press-tracked element whose hold does nothing (spec:AST-094 FR41)', () => {
+ detachers.push(coarsePrimaryPointer());
+ const {row, text} = mount(
+ '<div id="row" style="user-select: text"><span id="text">Row</span></div>',
+ );
+ detachers.push(host.attachConsumer(row, new RecordingConsumer()));
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', text, [finger], [finger], 0);
+ expect(row.style.getPropertyValue('user-select')).toBe('text');
+ touch('touchend', text, [finger], [], 600);
+ expect(row.style.getPropertyValue('user-select')).toBe('text');
+ });
+
+ it('turns text selection and the callout off while a finger holds an element whose hold opens a menu (spec:AST-094 FR41)', () => {
+ detachers.push(coarsePrimaryPointer());
+ const {trigger} = mount(
+ '<div id="trigger" style="user-select: text">Hold for the menu</div>',
+ );
+ const release = vi.fn();
+ const lock = vi.fn(() => release);
+ detachers.push(
+ host.attach(
+ trigger,
+ new LongPressGestureRecognizer({name: 'menu', selectionLock: lock}),
+ ),
+ );
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', trigger, [finger], [finger], 0);
+ // The host calls the long press's lock for this contact alone.
+ expect(lock).toHaveBeenCalledTimes(1);
+ expect([
+ ...(lock.mock.calls[0] as unknown as [Iterable<Element>])[0],
+ ]).toEqual([trigger]);
+ expect(release).not.toHaveBeenCalled();
+ touch('touchend', trigger, [finger], [], 600);
+ expect(release).toHaveBeenCalledTimes(1);
+ });
+
+ it('brings no selection lock to an element attached with manageStyle: false, whose styles the caller keeps (spec:AST-094 FR41)', () => {
+ detachers.push(coarsePrimaryPointer());
+ const {trigger} = mount('<div id="trigger">Hold for the menu</div>');
+ const lock = vi.fn(() => () => {});
+ detachers.push(
+ host.attach(
+ trigger,
+ new LongPressGestureRecognizer({name: 'menu', selectionLock: lock}),
+ {manageStyle: false},
+ ),
+ );
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', trigger, [finger], [finger], 0);
+ touch('touchend', trigger, [finger], [], 600);
+ expect(lock).not.toHaveBeenCalled();
+ });
+
+ it('a long press brings lockSelection by default', () => {
+ expect(new LongPressGestureRecognizer().selectionLock).toBe(lockSelection);
+ expect(new TapGestureRecognizer().selectionLock).toBeNull();
+ });
+
+ it('keeps native long-press selection under a 0 ms long press, a touch-down detector whose hold does nothing (spec:AST-094 FR41)', () => {
+ detachers.push(coarsePrimaryPointer());
+ const {photo} = mount(
+ '<div id="photo" style="user-select: text">Photo</div>',
+ );
+ detachers.push(
+ host.attach(
+ photo,
+ new LongPressGestureRecognizer({minimumPressDuration: 0}),
+ ),
+ );
+ const set = vi.spyOn(photo.style, 'setProperty');
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', photo, [finger], [finger], 0);
+ expect(set).not.toHaveBeenCalledWith('user-select', 'none');
+ expect(set).not.toHaveBeenCalledWith('-webkit-touch-callout', 'none');
+ expect(photo.style.getPropertyValue('user-select')).toBe('text');
+ touch('touchend', photo, [finger], [], 1200);
+ });
+
+ it('keeps only the finger a kept-press control tracks: a second finger on the held control still scrolls (spec:AST-094 FR19)', () => {
+ detachers.push(coarsePrimaryPointer());
+ const {stepper} = mount('<div id="stepper">+</div>');
+ detachers.push(
+ host.attachConsumer(
+ stepper,
+ createPressTracker({getBounds: () => null, keepsTouch: true}),
+ ),
+ );
+ const held = {id: 1, x: 5, y: 5};
+ const heldMoved = {id: 1, x: 5, y: 40};
+ const second = {id: 2, x: 8, y: 8};
+ const secondMoved = {id: 2, x: 8, y: 60};
+ touch('touchstart', stepper, [held], [held], 0);
+ // The held finger's press is delivered: its moves are kept.
+ expect(
+ touch('touchmove', stepper, [heldMoved], [heldMoved], 16)
+ .defaultPrevented,
+ ).toBe(true);
+ // A second finger the tracker is not tracking keeps its own moves.
+ touch('touchstart', stepper, [second], [heldMoved, second], 32);
+ expect(
+ touch('touchmove', stepper, [secondMoved], [heldMoved, secondMoved], 48)
+ .defaultPrevented,
+ ).toBe(false);
+ touch('touchend', stepper, [heldMoved, secondMoved], [], 64);
+ });
+
+ it('writes touch-action: manipulation for a kept-press control, so rapid taps never zoom, for every pointer (spec:AST-094 FR18, FR43)', () => {
+ const pointer = pointerQuery(true);
+ detachers.push(pointer.restore);
+ const {stepper, row} = mount(
+ '<div><div id="stepper">+</div><div id="row">Row</div></div>',
+ );
+ detachers.push(
+ host.attachConsumer(
+ stepper,
+ createPressTracker({getBounds: () => null, keepsTouch: true}),
+ ),
+ );
+ detachers.push(
+ host.attachConsumer(row, createPressTracker({getBounds: () => null})),
+ );
+ expect(stepper.getAttribute('data-astryx-touch-action')).toBe(
+ 'manipulation',
+ );
+ // A press tracker that keeps no touch gets no mark.
+ expect(row.hasAttribute('data-astryx-touch-action')).toBe(false);
+ // Where the pointer turns fine, a touchscreen laptop's finger keeps it.
+ pointer.set(false);
+ expect(stepper.getAttribute('data-astryx-touch-action')).toBe(
+ 'manipulation',
+ );
+ });
+
+ it("calls a press tracker's own selection lock for each finger's press, a stepper's hold-repeat, and nowhere else (spec:AST-094 FR41)", () => {
+ detachers.push(coarsePrimaryPointer());
+ const {stepper, row} = mount(
+ '<div id="stepper">+</div><div id="row">Row</div>',
+ );
+ const release = vi.fn();
+ const lock = vi.fn(
+ (_elements: Iterable<Element>, _target: EventTarget | null) => release,
+ );
+ detachers.push(
+ host.attachConsumer(stepper, new LockingConsumer(lock)),
+ host.attachConsumer(row, new RecordingConsumer()),
+ );
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', stepper, [finger], [finger], 0);
+ expect(lock).toHaveBeenCalledTimes(1);
+ expect([...lock.mock.calls[0][0]]).toEqual([stepper]);
+ expect(release).not.toHaveBeenCalled();
+ touch('touchend', stepper, [finger], [], 600);
+ expect(release).toHaveBeenCalledTimes(1);
+ // A mouse press keeps desktop selection.
+ pointer('pointerdown', stepper, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 700,
+ });
+ pointer('pointerup', stepper, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ time: 750,
+ });
+ // A tracker whose hold does nothing brings no lock.
+ touch('touchstart', row, [finger], [finger], 800);
+ touch('touchend', row, [finger], [], 900);
+ expect(lock).toHaveBeenCalledTimes(1);
+ });
+ it('locks for a hold that takes the touch, and nothing where it declines one: a zero-delay hold opts in with its own lock (spec:AST-094 FR41)', () => {
+ detachers.push(asIosWebKit());
+ detachers.push(coarsePrimaryPointer());
+ const {bar, lens, search} = mount(
+ '<div id="bar"><div id="lens">Lens</div><button id="search">Search</button></div>',
+ );
+ // A tab bar's lens: a hold at 0 ms that brings the lock itself, and
+ // takes only touches on the lens, not on the search tab beside it.
+ detachers.push(
+ host.attach(
+ bar,
+ new LongPressGestureRecognizer({
+ minimumPressDuration: 0,
+ selectionLock: lockSelection,
+ shouldReceiveTouch: (_recognizer, contact) =>
+ contact.target instanceof Node && lens.contains(contact.target),
+ }),
+ ),
+ );
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', search, [finger], [finger], 0);
+ expect(bar.style.getPropertyValue('user-select')).toBe('');
+ touch('touchend', search, [finger], [], 100);
+ touch('touchstart', lens, [finger], [finger], 200);
+ expect(bar.style.getPropertyValue('user-select')).toBe('none');
+ touch('touchend', lens, [finger], [], 300);
+ expect(bar.style.getPropertyValue('user-select')).toBe('');
+ });
+
+ it('on a coarse primary pointer, keeps selection for a mouse, a press-tracked row and a pan that does not ask, and locks a pan that asks', () => {
+ detachers.push(asIosWebKit());
+ detachers.push(coarsePrimaryPointer());
+ const {row, sheet, slider} = mount(
+ '<div id="row"></div><div id="sheet"></div><div id="slider"></div>',
+ );
+ detachers.push(
+ host.attachConsumer(row, new RecordingConsumer()),
+ host.attach(sheet, new PanGestureRecognizer()),
+ host.attach(
+ slider,
+ new PanGestureRecognizer({
+ direction: 'horizontal',
+ selectionLock: lockSelection,
+ }),
+ ),
+ );
+ const at = {x: 5, y: 5};
+ pointer('pointerdown', row, {
+ pointerType: 'mouse',
+ ...at,
+ buttons: 1,
+ time: 0,
+ });
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ pointer('pointerup', row, {pointerType: 'mouse', ...at, time: 50});
+ // A pen on a touch device (an iPad's pencil) on a row whose hold does
+ // nothing keeps native selection too (spec:AST-094 FR41).
+ pointer('pointerdown', row, {
+ pointerType: 'pen',
+ ...at,
+ buttons: 1,
+ time: 100,
+ });
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ pointer('pointerup', row, {pointerType: 'pen', ...at, time: 150});
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+
+ const finger = {id: 1, ...at};
+ touch('touchstart', sheet, [finger], [finger], 200);
+ expect(sheet.style.getPropertyValue('user-select')).toBe('');
+ touch('touchend', sheet, [finger], [], 250);
+ touch('touchstart', slider, [finger], [finger], 300);
+ expect(slider.style.getPropertyValue('user-select')).toBe('none');
+ touch('touchcancel', slider, [finger], [], 350);
+ expect(slider.style.getPropertyValue('user-select')).toBe('');
+ });
+
+ it("locks for a finger and a pen where the primary pointer is fine, a touchscreen laptop's finger and a desktop pen, and never for a mouse (spec:AST-094 FR41, FR43; spec:AST-017 FR59)", () => {
+ detachers.push(asIosWebKit());
+ detachers.push(pointerQuery(false).restore);
+ const {slider} = mount('<div id="slider"></div>');
+ const laptop = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ detachers.push(
+ laptop.attach(
+ slider,
+ new PanGestureRecognizer({
+ direction: 'horizontal',
+ selectionLock: lockSelection,
+ }),
+ ),
+ );
+ const at = {x: 5, y: 5};
+ // A mouse keeps its released behavior: no lock.
+ pointer('pointerdown', slider, {
+ pointerType: 'mouse',
+ ...at,
+ buttons: 1,
+ time: 0,
+ });
+ expect(slider.style.getPropertyValue('user-select')).toBe('');
+ pointer('pointerup', slider, {pointerType: 'mouse', ...at, time: 50});
+ // A pen's hold acts as a finger's.
+ pointer('pointerdown', slider, {
+ pointerType: 'pen',
+ ...at,
+ buttons: 1,
+ time: 100,
+ });
+ expect(slider.style.getPropertyValue('user-select')).toBe('none');
+ pointer('pointerup', slider, {pointerType: 'pen', ...at, time: 150});
+ expect(slider.style.getPropertyValue('user-select')).toBe('');
+ // A touchscreen laptop's finger: its pointerdown arms the press, then
+ // its touchstart takes the lock.
+ pointer('pointerdown', slider, {
+ id: 7,
+ pointerType: 'touch',
+ ...at,
+ buttons: 1,
+ time: 200,
+ });
+ const finger = {id: 1, ...at};
+ touch('touchstart', slider, [finger], [finger], 200);
+ expect(slider.style.getPropertyValue('user-select')).toBe('none');
+ pointer('pointerup', slider, {
+ id: 7,
+ pointerType: 'touch',
+ ...at,
+ time: 250,
+ });
+ touch('touchend', slider, [finger], [], 250);
+ expect(slider.style.getPropertyValue('user-select')).toBe('');
+ });
+
+ it('locks a checkbox under the finger inside a locked element, which WebKit makes selectable, but never a text field', () => {
+ detachers.push(asIosWebKit());
+ detachers.push(coarsePrimaryPointer());
+ const {row, check, field} = mount(
+ '<div id="row"><input id="check" type="checkbox"><input id="field"></div>',
+ );
+ // A switch's drag: a hold that does something.
+ detachers.push(
+ host.attach(
+ row,
+ new PanGestureRecognizer({
+ direction: 'horizontal',
+ selectionLock: lockSelection,
+ }),
+ ),
+ );
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', check, [finger], [finger], 0);
+ expect(check.style.getPropertyValue('user-select')).toBe('none');
+ touch('touchend', check, [finger], [], 100);
+ expect(check.style.getPropertyValue('user-select')).toBe('');
+ touch('touchstart', field, [finger], [finger], 200);
+ expect(row.style.getPropertyValue('user-select')).toBe('none');
+ expect(field.style.getPropertyValue('user-select')).toBe('');
+ touch('touchend', field, [finger], [], 300);
+ // An input outside every locked element is not ours to lock.
+ const {alone} = mount('<input id="alone" type="checkbox">');
+ detachers.push(host.attach(alone, new TapGestureRecognizer()));
+ touch('touchstart', alone, [finger], [finger], 400);
+ expect(alone.style.getPropertyValue('user-select')).toBe('');
+ touch('touchend', alone, [finger], [], 450);
+ });
+
+ it('ignores touches that land outside every attached element', () => {
+ const {box, elsewhere} = mount(
+ '<div id="box"></div><div id="elsewhere"></div>',
+ );
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ detachers.push(host.attach(box, pan));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', elsewhere, [finger], [finger], 0);
+ const move = touch(
+ 'touchmove',
+ elsewhere,
+ [{...finger, x: 60}],
+ [{...finger, x: 60}],
+ 16,
+ );
+ expect(move.defaultPrevented).toBe(false);
+ expect(host.arena.touches).toEqual([]);
+ });
+});
+
+describe('holdPageScroll', () => {
+ const at = (id: number, x: number, y: number) => [{id, x, y}];
+ /** A contact's pointerdown, which reads the primary pointer for a hold. */
+ const contact = (pointerType = 'touch', x = 100, y = 300) =>
+ pointer('pointerdown', document.body, {pointerType, x, y, time: 0});
+ /** Hold the page, then touch it once, as a finger does. */
+ const hold = (decide: PageScrollDecision) => {
+ const release = holdPageScroll(document, decide);
+ contact();
+ return release;
+ };
+
+ /** The touch listeners a spy on the window saw added, with their options. */
+ const touchListenersAdded = (added: {mock: {calls: unknown[][]}}) =>
+ added.mock.calls.filter(([type]) => String(type).startsWith('touch')) as [
+ string,
+ unknown,
+ AddEventListenerOptions | boolean | undefined,
+ ][];
+
+ it('registers its blocking touchmove as it starts where the primary pointer is coarse, before any contact, as Safari honours a blocking listener only when it was registered before the touch (spec:AST-094 FR19)', () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ const ask = vi.spyOn(window, 'matchMedia');
+ detachers.push(() => ask.mockRestore());
+ const added = vi.spyOn(window, 'addEventListener');
+ detachers.push(() => added.mockRestore());
+ detachers.push(holdPageScroll(document, () => true));
+ expect(ask).toHaveBeenCalledWith(TOUCH_QUERY);
+ expect(
+ touchListenersAdded(added).some(
+ ([type, , options]) =>
+ type === 'touchmove' &&
+ typeof options === 'object' &&
+ options.passive === false,
+ ),
+ ).toBe(true);
+ // The first drag after the hold starts is held even where its
+ // pointerdown has not been heard.
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), 0);
+ expect(
+ touch('touchmove', scrim, at(1, 100, 250), at(1, 100, 250), 16)
+ .defaultPrevented,
+ ).toBe(true);
+ });
+
+ it('registers no touch listener as it starts where the primary pointer is fine: a mouse contact adds none, and a touch or pen contact follows the pointer from then on (spec:AST-094 FR24, FR43)', () => {
+ const primary = pointerQuery(false);
+ detachers.push(primary.restore);
+ const added = vi.spyOn(window, 'addEventListener');
+ detachers.push(() => added.mockRestore());
+ detachers.push(holdPageScroll(document, () => true));
+ expect(touchListenersAdded(added)).toEqual([]);
+ contact('mouse');
+ expect(touchListenersAdded(added)).toEqual([]);
+ contact('touch');
+ expect(touchListenersAdded(added)).toEqual([]);
+ // A tablet undocking its mouse: the hold now listens.
+ primary.set(true);
+ expect(touchListenersAdded(added).length).toBeGreaterThan(0);
+ });
+
+ it('holds a touch whose pointerdown comes after its touchstart: the finger is named at its first move', () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ detachers.push(holdPageScroll(document, () => true));
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), 0);
+ contact('touch', 100, 300);
+ expect(
+ touch('touchmove', scrim, at(1, 100, 250), at(1, 100, 250), 16)
+ .defaultPrevented,
+ ).toBe(true);
+ });
+
+ it('cancels a one-finger pan the decision says would scroll the page, for the rest of its touch', () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ const decide = vi.fn(() => true);
+ detachers.push(hold(decide));
+
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), 0);
+ const first = touch(
+ 'touchmove',
+ scrim,
+ at(1, 100, 250),
+ at(1, 100, 250),
+ 16,
+ );
+ const second = touch(
+ 'touchmove',
+ scrim,
+ at(1, 100, 200),
+ at(1, 100, 200),
+ 32,
+ );
+
+ expect(first.defaultPrevented).toBe(true);
+ expect(second.defaultPrevented).toBe(true);
+ expect(decide).toHaveBeenCalledTimes(1);
+ expect(decide).toHaveBeenCalledWith(scrim, 0, -50);
+ });
+
+ it("judges a new touch afresh when it reuses the last touch's identifier", () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ // The backdrop pan would scroll the page; the list pan scrolls the list.
+ const decide = vi.fn(
+ (_origin: EventTarget | null, _dx: number, dy: number) => dy < 0,
+ );
+ detachers.push(hold(decide));
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), 0);
+ expect(
+ touch('touchmove', scrim, at(1, 100, 250), at(1, 100, 250), 16)
+ .defaultPrevented,
+ ).toBe(true);
+ touch('touchend', scrim, at(1, 100, 250), [], 32);
+ // The next touch reuses identifier 1 and pans the other way.
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), 48);
+ expect(
+ touch('touchmove', scrim, at(1, 100, 350), at(1, 100, 350), 64)
+ .defaultPrevented,
+ ).toBe(false);
+ expect(decide).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps holding the first finger after a second finger touches and lifts', () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ detachers.push(hold(() => true));
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), 0);
+ expect(
+ touch('touchmove', scrim, at(1, 100, 250), at(1, 100, 250), 16)
+ .defaultPrevented,
+ ).toBe(true);
+ // A second finger lands and lifts: while two are down, nothing is
+ // cancelled, so the page can zoom.
+ const both = [...at(1, 100, 250), ...at(2, 200, 300)];
+ touch('touchstart', scrim, at(2, 200, 300), both, 32);
+ expect(
+ touch('touchmove', scrim, at(2, 200, 260), both, 48).defaultPrevented,
+ ).toBe(false);
+ touch('touchend', scrim, at(2, 200, 260), at(1, 100, 250), 64);
+ // Alone again, the first finger is held for the rest of its touch.
+ expect(
+ touch('touchmove', scrim, at(1, 100, 200), at(1, 100, 200), 80)
+ .defaultPrevented,
+ ).toBe(true);
+ });
+
+ it('judges a pan once it clears the slop, so a first wobble does not fix its axis', () => {
+ const {strip} = mount('<div id="strip"></div>');
+ const decide = vi.fn((_origin: EventTarget | null, dx: number) => dx === 0);
+ detachers.push(hold(decide));
+
+ touch('touchstart', strip, at(1, 100, 300), at(1, 100, 300), 0);
+ const wobble = touch(
+ 'touchmove',
+ strip,
+ at(1, 102, 302),
+ at(1, 102, 302),
+ 16,
+ );
+ const swipe = touch(
+ 'touchmove',
+ strip,
+ at(1, 110, 303),
+ at(1, 110, 303),
+ 32,
+ );
+
+ expect(wobble.defaultPrevented).toBe(false);
+ expect(decide).toHaveBeenCalledTimes(1);
+ expect(decide).toHaveBeenCalledWith(strip, 10, 3);
+ expect(swipe.defaultPrevented).toBe(false);
+ });
+
+ it('lets a pan through when the decision says something under the finger takes it', () => {
+ const {list} = mount('<div id="list"></div>');
+ detachers.push(hold(() => false));
+
+ touch('touchstart', list, at(1, 100, 300), at(1, 100, 300), 0);
+ expect(
+ touch('touchmove', list, at(1, 100, 250), at(1, 100, 250), 16)
+ .defaultPrevented,
+ ).toBe(false);
+ });
+
+ it('never cancels a two-finger gesture, so pinch-zoom keeps working', () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ const decide = vi.fn(() => true);
+ detachers.push(hold(decide));
+ const both = [
+ {id: 1, x: 100, y: 300},
+ {id: 2, x: 200, y: 300},
+ ];
+
+ touch('touchstart', scrim, both, both, 0);
+ const moved = [
+ {id: 1, x: 90, y: 300},
+ {id: 2, x: 210, y: 300},
+ ];
+ expect(touch('touchmove', scrim, moved, moved, 16).defaultPrevented).toBe(
+ false,
+ );
+ expect(decide).not.toHaveBeenCalled();
+ });
+
+ it('hands the decision the innermost node of a touch inside a shadow root', () => {
+ const {outer} = mount('<div id="outer"></div>');
+ const inner = document.createElement('div');
+ outer.attachShadow({mode: 'open'}).append(inner);
+ const decide = vi.fn(() => false);
+ detachers.push(hold(decide));
+
+ touch('touchstart', inner, at(1, 100, 300), at(1, 100, 300), 0);
+ touch('touchmove', inner, at(1, 100, 250), at(1, 100, 250), 16);
+
+ expect(decide).toHaveBeenCalledWith(inner, 0, -50);
+ });
+
+ it('holds the page of a document that has no gesture host, and creates none', () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ gestureHosts.delete(document);
+ detachers.push(hold(() => true));
+
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), 0);
+ expect(
+ touch('touchmove', scrim, at(1, 100, 250), at(1, 100, 250), 16)
+ .defaultPrevented,
+ ).toBe(true);
+ expect(gestureHosts.get(document)).toBeUndefined();
+ });
+
+ it("leaves a touch that a recognizer of the document's host owns to that recognizer", () => {
+ const {box} = mount('<div id="box"></div>');
+ gestureHosts.set(document, host);
+ detachers.push(() => gestureHosts.delete(document));
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ detachers.push(host.attach(box, pan));
+ const decide = vi.fn(() => true);
+ detachers.push(hold(decide));
+
+ touch('touchstart', box, at(1, 100, 300), at(1, 100, 300), 0);
+ touch('touchmove', box, at(1, 100, 250), at(1, 100, 250), 16);
+
+ expect(pan.state).toBe('began');
+ expect(decide).not.toHaveBeenCalled();
+ });
+
+ it('stacks holds and stops judging pans once the last one is released', () => {
+ const {scrim} = mount('<div id="scrim"></div>');
+ const releaseFirst = hold(() => true);
+ const releaseSecond = holdPageScroll(document, () => true);
+ const pan = (time: number) => {
+ touch('touchstart', scrim, at(1, 100, 300), at(1, 100, 300), time);
+ return touch(
+ 'touchmove',
+ scrim,
+ at(1, 100, 250),
+ at(1, 100, 250),
+ time + 16,
+ ).defaultPrevented;
+ };
+
+ releaseFirst();
+ expect(pan(0)).toBe(true);
+ releaseSecond();
+ releaseSecond();
+ expect(pan(100)).toBe(false);
+ });
+});
+
+describe('touch gates and a second finger', () => {
+ it('holds a gated target away from every participant until the gate is released', () => {
+ const {layer, button} = mount(
+ '<div id="layer"><div id="button"></div></div>',
+ );
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ detachers.push(host.attach(button, tap));
+ const release = host.addTouchGate(target => layer.contains(target));
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', button, [finger], [finger], 0);
+ expect(tap.numberOfTouches).toBe(0);
+ touch('touchend', button, [finger], [], 40);
+ release();
+ touch('touchstart', button, [finger], [finger], 100);
+ expect(tap.numberOfTouches).toBe(1);
+ touch('touchend', button, [finger], [], 140);
+ });
+
+ it('fails a one-finger pan that has not claimed when a second finger lands anywhere, so the browser can pinch', () => {
+ const {row, text} = mount('<div id="row"></div><p id="text">plain</p>');
+ const swipe = new PanGestureRecognizer({
+ name: 'swipe',
+ direction: 'horizontal',
+ maximumNumberOfTouches: 1,
+ });
+ const states: string[] = [];
+ swipe.addListener(r => states.push(r.state));
+ detachers.push(host.attach(row, swipe));
+ const first = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [first], [first], 0);
+ // Under the hysteresis: still possible, nothing claimed.
+ touch('touchmove', row, [{...first, x: 15}], [{...first, x: 15}], 16);
+ const second = {id: 2, x: 200, y: 300};
+ touch('touchstart', text, [second], [{...first, x: 15}, second], 32);
+ // The pan can no longer claim the pair midway: the pinch is the browser's.
+ const pinch = touch(
+ 'touchmove',
+ row,
+ [{...first, x: 60}],
+ [{...first, x: 60}, second],
+ 48,
+ );
+ expect(pinch.defaultPrevented).toBe(false);
+ expect(states).toEqual([]);
+ });
+
+ it('keeps a claimed one-finger drag when a second finger lands anywhere (AST-094 FR10)', () => {
+ const {row, text} = mount('<div id="row"></div><p id="text">plain</p>');
+ const swipe = new PanGestureRecognizer({
+ name: 'swipe',
+ direction: 'horizontal',
+ maximumNumberOfTouches: 1,
+ });
+ detachers.push(host.attach(row, swipe));
+ const first = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [first], [first], 0);
+ touch('touchmove', row, [{...first, x: 40}], [{...first, x: 40}], 16);
+ expect(swipe.state).toBe('began');
+ const second = {id: 2, x: 200, y: 300};
+ touch('touchstart', text, [second], [{...first, x: 40}, second], 32);
+ const drag = touch(
+ 'touchmove',
+ row,
+ [{...first, x: 80}],
+ [{...first, x: 80}, second],
+ 48,
+ );
+ expect(swipe.state).toBe('changed');
+ expect(drag.defaultPrevented).toBe(true);
+ });
+});
+
+describe('a delivered press keeps its touch', () => {
+ it('cancels the browser pan once the consumer keeps the touch, and not before', () => {
+ const {row} = mount('<div id="row"></div>');
+ class Keeper extends RecordingConsumer {
+ kept = false;
+ keepsTouch(): boolean {
+ return this.kept;
+ }
+ }
+ const control = new Keeper();
+ detachers.push(host.attachConsumer(row, control));
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', row, [finger], [finger], 0);
+ // Before the press is delivered, a move still scrolls.
+ const early = touch(
+ 'touchmove',
+ row,
+ [{...finger, y: 14}],
+ [{...finger, y: 14}],
+ 40,
+ );
+ expect(early.defaultPrevented).toBe(false);
+ // Delivered (highlighted past the content delay): the touch is the control's.
+ control.kept = true;
+ const late = touch(
+ 'touchmove',
+ row,
+ [{...finger, y: 54}],
+ [{...finger, y: 54}],
+ 200,
+ );
+ expect(late.defaultPrevented).toBe(true);
+ expect(control.events.some(event => event.startsWith('cancelled'))).toBe(
+ false,
+ );
+ touch('touchend', row, [{...finger, y: 54}], [], 260);
+ });
+});
+
+describe('detaching a keepsTouch press tracker', () => {
+ it('removes its blocking touchmove listener while the element keeps its recognizers', () => {
+ const {row} = mount('<div id="row"></div>');
+ const active = new Set<EventListenerOrEventListenerObject>();
+ const add = row.addEventListener.bind(row);
+ const remove = row.removeEventListener.bind(row);
+ vi.spyOn(row, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ if (
+ type === 'touchmove' &&
+ listener != null &&
+ typeof options === 'object' &&
+ options.passive === false
+ ) {
+ active.add(listener);
+ }
+ add(type, listener, options);
+ },
+ );
+ vi.spyOn(row, 'removeEventListener').mockImplementation(
+ (type, listener, options) => {
+ if (type === 'touchmove' && listener != null) {
+ active.delete(listener);
+ }
+ remove(type, listener, options);
+ },
+ );
+ // A tap decides at the lift: on its own it needs no blocking listener.
+ detachers.push(host.attach(row, new TapGestureRecognizer({name: 'tap'})));
+ expect(active.size).toBe(0);
+ class Keeper extends RecordingConsumer {
+ keepsTouch(): boolean {
+ return true;
+ }
+ }
+ const detach = host.attachConsumer(row, new Keeper());
+ expect(active.size).toBe(1);
+ detach();
+ expect(active.size).toBe(0);
+ });
+});
+
+describe('GestureHost.fingersDown', () => {
+ it('counts every finger on the screen, one on a plain element too', () => {
+ const {handle, row} = mount(
+ '<div id="handle"></div><div id="row">plain</div>',
+ );
+ expect(host.fingersDown()).toBe(0);
+ detachers.push(
+ host.attach(handle, new LongPressGestureRecognizer({name: 'hold'})),
+ );
+ const first = {id: 1, x: 10, y: 10, target: handle};
+ const second = {id: 2, x: 200, y: 10, target: row};
+ touch('touchstart', handle, [first], [first], 0);
+ expect(host.fingersDown()).toBe(1);
+ // The second finger lands on an element no recognizer is attached to.
+ touch('touchstart', row, [second], [first, second], 16);
+ expect(host.fingersDown()).toBe(2);
+ // A lift lowers it.
+ touch('touchend', row, [second], [first], 32);
+ expect(host.fingersDown()).toBe(1);
+ touch('touchend', handle, [first], [], 48);
+ expect(host.fingersDown()).toBe(0);
+ });
+
+ it('drops to what a touchcancel lists', () => {
+ const {handle, row} = mount(
+ '<div id="handle"></div><div id="row">plain</div>',
+ );
+ detachers.push(
+ host.attach(handle, new LongPressGestureRecognizer({name: 'hold'})),
+ );
+ const first = {id: 1, x: 10, y: 10, target: handle};
+ const second = {id: 2, x: 200, y: 10, target: row};
+ touch('touchstart', handle, [first], [first], 0);
+ touch('touchstart', row, [second], [first, second], 16);
+ expect(host.fingersDown()).toBe(2);
+ // The system takes every finger.
+ touch('touchcancel', handle, [first, second], [], 32);
+ expect(host.fingersDown()).toBe(0);
+ });
+
+ it('reads 0 once the host stops listening', () => {
+ const {handle} = mount('<div id="handle"></div>');
+ const detach = host.attach(
+ handle,
+ new LongPressGestureRecognizer({name: 'hold'}),
+ );
+ const finger = {id: 1, x: 10, y: 10, target: handle};
+ touch('touchstart', handle, [finger], [finger], 0);
+ expect(host.fingersDown()).toBe(1);
+ detach();
+ expect(host.fingersDown()).toBe(0);
+ });
+});
+
+describe('where the primary pointer is fine (spec:AST-094 FR43, FR24)', () => {
+ /** Quiets the development warning, and returns its spy. */
+ function quietWarning() {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ detachers.push(() => warn.mockRestore());
+ return warn;
+ }
+
+ it('follows the pointer: turning coarse installs it, turning fine cancels the touch in flight and keeps only what a press needs', () => {
+ const pointer = pointerQuery(false);
+ detachers.push(pointer.restore);
+ const {box} = mount('<div id="box"></div>');
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ const states: string[] = [];
+ pan.addTransitionListener((_current, _from, to) => states.push(to));
+ detachers.push(
+ host.attach(box, pan),
+ host.attach(box, new LongPressGestureRecognizer({name: 'press'})),
+ );
+ // Its touch-action is there for every pointer (FR43).
+ expect(box.hasAttribute('data-astryx-touch-action')).toBe(true);
+ // A tablet undocks its mouse.
+ pointer.set(true);
+ expect(box.hasAttribute('data-astryx-touch-action')).toBe(true);
+ const finger = {id: 1, x: 5, y: 5};
+ const moved = {id: 1, x: 40, y: 5};
+ touch('touchstart', box, [finger], [finger], 0);
+ touch('touchmove', box, [moved], [moved], 16);
+ expect(pan.state).toBe('began');
+ // It docks one again mid-drag: the drag ends without acting.
+ pointer.set(false);
+ expect(states).toContain('cancelled');
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ const count = states.length;
+ const later = {id: 1, x: 80, y: 5};
+ touch('touchmove', box, [later], [later], 32);
+ touch('touchend', box, [later], [], 48);
+ expect(states).toHaveLength(count);
+ });
+
+ it('an idle press tracker leaves no document or window listener: they last only a press (spec:AST-094 FR24, FR43)', async () => {
+ const primary = pointerQuery(false);
+ detachers.push(primary.restore);
+ const {stepper} = mount('<div id="stepper"></div>');
+ const listening = new Set<string>();
+ const watch = (scope: Document | Window, name: string) => {
+ const addOriginal = scope.addEventListener.bind(scope);
+ const removeOriginal = scope.removeEventListener.bind(scope);
+ const add = vi
+ .spyOn(scope, 'addEventListener')
+ .mockImplementation(
+ (
+ type: string,
+ listener: EventListenerOrEventListenerObject,
+ options?: boolean | AddEventListenerOptions,
+ ) => {
+ listening.add(`${name}:${type}`);
+ addOriginal(type, listener, options);
+ },
+ );
+ const remove = vi
+ .spyOn(scope, 'removeEventListener')
+ .mockImplementation(
+ (
+ type: string,
+ listener: EventListenerOrEventListenerObject,
+ options?: boolean | EventListenerOptions,
+ ) => {
+ listening.delete(`${name}:${type}`);
+ removeOriginal(type, listener, options);
+ },
+ );
+ detachers.push(() => {
+ add.mockRestore();
+ remove.mockRestore();
+ });
+ };
+ watch(document, 'document');
+ watch(window, 'window');
+ const highlights: boolean[] = [];
+ detachers.push(
+ host.attachConsumer(
+ stepper,
+ createPressTracker({
+ getBounds: () => ({left: 0, top: 0, right: 100, bottom: 100}),
+ onHighlightChange: value => highlights.push(value),
+ }),
+ ),
+ );
+ const pageListeners = () =>
+ [...listening].filter(key => /:(touch|pointer|click)/.test(key));
+ // Attached and idle: nothing on the document or the window, even beside
+ // a finger-scroll watch.
+ expect(pageListeners()).toEqual([]);
+ detachers.push(watchFingerScrolls(host, document));
+ expect(pageListeners()).toEqual([]);
+ const finger = {id: 1, x: 5, y: 5};
+ // A finger's pointerdown comes before its touchstart.
+ pointer('pointerdown', stepper, {
+ id: 7,
+ pointerType: 'touch',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ touch('touchstart', stepper, [finger], [finger], 0);
+ // The press is painted, and the host listens for this press only.
+ expect(highlights).toContain(true);
+ expect(pageListeners().length).toBeGreaterThan(0);
+ touch('touchend', stepper, [finger], [], 40);
+ await Promise.resolve();
+ expect(pageListeners()).toEqual([]);
+ });
+
+ it('keeps everything working when the pointer turns fine (spec:AST-094 FR43)', () => {
+ const primary = pointerQuery(true);
+ detachers.push(primary.restore);
+ const {box, row} = mount('<div id="box"></div><div id="row"></div>');
+ const swipe = new PanGestureRecognizer({
+ name: 'swipe',
+ direction: 'horizontal',
+ });
+ const states: string[] = [];
+ swipe.addTransitionListener((_current, _from, to) => states.push(to));
+ detachers.push(
+ host.attach(box, swipe),
+ host.attach(row, new LongPressGestureRecognizer({name: 'press'})),
+ );
+ expect(row.getAttribute('data-astryx-touch-action')).toBe('manipulation');
+ primary.set(false);
+ // Every touch-action stays.
+ expect(row.getAttribute('data-astryx-touch-action')).toBe('manipulation');
+ expect(box.getAttribute('data-astryx-touch-action')).toBe(
+ 'pan-y pinch-zoom',
+ );
+ const finger = {id: 3, x: 5, y: 5};
+ const moved = {id: 3, x: 60, y: 5};
+ // A finger's pointerdown comes before its touchstart.
+ pointer('pointerdown', box, {
+ id: 9,
+ pointerType: 'touch',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ touch('touchstart', box, [finger], [finger], 0);
+ // Its moves come from its pointer once paired, as in a browser.
+ pointer('pointermove', box, {
+ id: 9,
+ pointerType: 'touch',
+ x: 60,
+ y: 5,
+ buttons: 1,
+ time: 16,
+ });
+ touch('touchmove', box, [moved], [moved], 16);
+ pointer('pointerup', box, {
+ id: 9,
+ pointerType: 'touch',
+ x: 60,
+ y: 5,
+ time: 32,
+ });
+ touch('touchend', box, [moved], [], 32);
+ expect(states).toEqual(expect.arrayContaining(['began', 'ended']));
+ });
+
+ it('a page hold and a finger-scroll watch register no touch or scroll listener where it is fine, and follow it while they run', () => {
+ quietWarning();
+ const pointer = pointerQuery(false);
+ detachers.push(pointer.restore);
+ // On the document or the window, as each listens (jsdom's window carries
+ // its own listener methods).
+ const added = [
+ vi.spyOn(EventTarget.prototype, 'addEventListener'),
+ vi.spyOn(window, 'addEventListener'),
+ ];
+ const removed = [
+ vi.spyOn(EventTarget.prototype, 'removeEventListener'),
+ vi.spyOn(window, 'removeEventListener'),
+ ];
+ detachers.push(() => {
+ for (const spy of [...added, ...removed]) {
+ spy.mockRestore();
+ }
+ });
+ const {list} = mount('<div id="list"></div>');
+ detachers.push(
+ holdPageScroll(document, () => true),
+ watchFingerScrolls(host, list),
+ );
+ const types = (spies: typeof added) =>
+ spies
+ .flatMap(spy => spy.mock.calls.map(([type]) => type))
+ .filter(type => /^(touch|scroll)/.test(type));
+ expect(types(added)).toEqual([]);
+ // The hold reads the pointer at its first touch contact: still fine.
+ document.body.dispatchEvent(
+ new PointerEvent('pointerdown', {
+ bubbles: true,
+ composed: true,
+ pointerType: 'touch',
+ }),
+ );
+ expect(types(added)).toEqual([]);
+ pointer.set(true);
+ expect(types(added)).toEqual(
+ expect.arrayContaining([
+ 'touchstart',
+ 'touchmove',
+ 'scroll',
+ 'scrollend',
+ ]),
+ );
+ pointer.set(false);
+ expect(types(removed)).toEqual(
+ expect.arrayContaining([
+ 'touchstart',
+ 'touchmove',
+ 'scroll',
+ 'scrollend',
+ ]),
+ );
+ expect(isFingerScroll(host, list)).toBe(false);
+ });
+});
+
+describe('an action group under a fine pointer (family:action-groups FR5; spec:AST-094 FR19, FR24)', () => {
+ const listenerTypes = (spy: ReturnType<typeof vi.spyOn>) =>
+ (spy.mock.calls as unknown[][])
+ .map(call => call[0] as string)
+ .filter(t => /^(touch|pointer|click|blur|scroll|contextmenu)/.test(t));
+
+ it('keeps one passive pointerdown listener on the group while idle, as on any element that uses a gesture (spec:AST-094 FR43)', () => {
+ const {group, other} = mount(
+ '<div id="group"><button id="one"></button></div><div id="other"></div>',
+ );
+ const added = vi.spyOn(document, 'addEventListener');
+ const viewAdded = vi.spyOn(window, 'addEventListener');
+ const groupAdded = vi.spyOn(group, 'addEventListener');
+ const otherAdded = vi.spyOn(other, 'addEventListener');
+ added.mockClear();
+ viewAdded.mockClear();
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ detachers.push(
+ fine.attach(group, new TapGestureRecognizer(), {actionGroup: true}),
+ fine.attach(other, new TapGestureRecognizer()),
+ );
+ expect(listenerTypes(added)).toEqual([]);
+ expect(listenerTypes(viewAdded)).toEqual([]);
+ expect(groupAdded.mock.calls).toEqual([
+ ['pointerdown', expect.any(Function), {capture: true, passive: true}],
+ ]);
+ expect(otherAdded.mock.calls).toEqual([
+ ['pointerdown', expect.any(Function), {capture: true, passive: true}],
+ ]);
+ });
+
+ it('adds page listeners only during a press, removes them at the release, and serves the press to the group', async () => {
+ const {group, one} = mount(
+ '<div id="group"><button id="one"></button></div>',
+ );
+ // The press's listeners come through the shared input stream, on the
+ // window's capture phase.
+ const added = vi.spyOn(window, 'addEventListener');
+ const removed = vi.spyOn(window, 'removeEventListener');
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const tap = new TapGestureRecognizer();
+ const states: string[] = [];
+ tap.addListener(r => states.push(r.state));
+ detachers.push(fine.attach(group, tap, {actionGroup: true}));
+ added.mockClear();
+ removed.mockClear();
+ pointer('pointerdown', one, {
+ pointerType: 'mouse',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ expect(listenerTypes(added)).toEqual(
+ expect.arrayContaining(['pointermove', 'pointerup', 'pointercancel']),
+ );
+ expect(listenerTypes(removed)).toEqual([]);
+ pointer('pointerup', one, {pointerType: 'mouse', x: 10, y: 10, time: 80});
+ expect(states).toContain('ended');
+ // The press's contacts end; its listeners go after this task's events.
+ await Promise.resolve();
+ for (const type of ['pointermove', 'pointerup', 'pointercancel']) {
+ expect(listenerTypes(removed)).toContain(type);
+ }
+ });
+
+ it("adds no click listener of its own for a group press: only the click guard's, while it is armed, hears a claimed press's click, before and after the host installs", () => {
+ // A document of its own: no other host or guard has touched its window.
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ const frameDocument = frame.contentDocument as Document;
+ const frameWindow = frameDocument.defaultView as Window & typeof globalThis;
+ frameDocument.body.innerHTML =
+ '<div id="group"><button id="one"></button></div><div id="row"></div>';
+ const group = frameDocument.getElementById('group') as HTMLElement;
+ const one = frameDocument.getElementById('one') as HTMLElement;
+ const row = frameDocument.getElementById('row') as HTMLElement;
+ const added = vi.spyOn(frameWindow, 'addEventListener');
+ const clickListeners = () =>
+ added.mock.calls.filter(call => call[0] === 'click').length;
+ try {
+ const send = (type: 'pointerdown' | 'pointerup', time: number) => {
+ const event = new frameWindow.PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 1,
+ pointerType: 'mouse',
+ clientX: 10,
+ clientY: 10,
+ button: 0,
+ buttons: type === 'pointerdown' ? 1 : 0,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ one.dispatchEvent(event);
+ };
+ const fine = new GestureHost(frameDocument, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const detachGroup = fine.attach(group, new TapGestureRecognizer(), {
+ actionGroup: true,
+ });
+ send('pointerdown', 0);
+ send('pointerup', 80);
+ // At most the click guard's own listener, while it is armed.
+ const afterFirst = clickListeners();
+ expect(afterFirst).toBeLessThanOrEqual(1);
+ // A per-event recognizer installs the host mid-press: still no click
+ // listener of the press's own.
+ send('pointerdown', 1000);
+ const detachRow = fine.attach(row, new PanGestureRecognizer(), {
+ perEventPointer: true,
+ });
+ send('pointerup', 1080);
+ expect(clickListeners()).toBe(afterFirst);
+ detachRow();
+ detachGroup();
+ } finally {
+ added.mockRestore();
+ frame.remove();
+ }
+ });
+
+ it('serves only the group: a recognizer that is not a group, on the press path, takes no part', () => {
+ const {outer, group, one} = mount(
+ '<div id="outer"><div id="group"><button id="one"></button></div></div>',
+ );
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const groupTap = new TapGestureRecognizer();
+ const outerTap = new TapGestureRecognizer();
+ const outerStates: string[] = [];
+ outerTap.addListener(r => outerStates.push(r.state));
+ detachers.push(
+ fine.attach(group, groupTap, {actionGroup: true}),
+ fine.attach(outer, outerTap),
+ );
+ pointer('pointerdown', one, {
+ pointerType: 'mouse',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ pointer('pointerup', one, {pointerType: 'mouse', x: 10, y: 10, time: 80});
+ expect(outerStates).toEqual([]);
+ });
+
+ it('serves a finger on the group too, and still answers a mouse afterwards', async () => {
+ const {group, one} = mount(
+ '<div id="group"><button id="one"></button></div>',
+ );
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const tap = new TapGestureRecognizer();
+ const states: string[] = [];
+ tap.addListener(r => states.push(r.state));
+ detachers.push(fine.attach(group, tap, {actionGroup: true}));
+ // A finger: its pointer events and, after them, its touch events.
+ pointer('pointerdown', one, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', one, [finger], [finger], 0);
+ const moved = {id: 1, x: 11, y: 10};
+ pointer('pointermove', one, {
+ pointerType: 'touch',
+ x: 11,
+ y: 10,
+ buttons: 1,
+ time: 16,
+ });
+ touch('touchmove', one, [moved], [moved], 16);
+ pointer('pointerup', one, {pointerType: 'touch', x: 11, y: 10, time: 60});
+ touch('touchend', one, [moved], [], 60);
+ expect(states).toEqual(['ended']);
+ await Promise.resolve();
+ pointer('pointerdown', one, {
+ pointerType: 'mouse',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 400,
+ });
+ pointer('pointerup', one, {pointerType: 'mouse', x: 10, y: 10, time: 460});
+ expect(states).toEqual(['ended', 'ended']);
+ });
+
+ it('removes the group listener on detach, and a coarse pointer keeps the usual page listeners instead', () => {
+ const {group} = mount('<div id="group"></div>');
+ const groupRemoved = vi.spyOn(group, 'removeEventListener');
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const detach = fine.attach(group, new TapGestureRecognizer(), {
+ actionGroup: true,
+ });
+ detach();
+ expect(groupRemoved).toHaveBeenCalledWith(
+ 'pointerdown',
+ expect.any(Function),
+ {capture: true, passive: true},
+ );
+ const groupAdded = vi.spyOn(group, 'addEventListener');
+ const added = vi.spyOn(window, 'addEventListener');
+ added.mockClear();
+ const coarse = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ detachers.push(
+ coarse.attach(group, new TapGestureRecognizer(), {actionGroup: true}),
+ );
+ expect(listenerTypes(added)).toContain('pointerdown');
+ expect(
+ groupAdded.mock.calls.filter(call => call[0] === 'pointerdown'),
+ ).toEqual([]);
+ });
+
+ it("keeps an element's passive pointerdown while any of its gestures stays attached, whichever goes first, and drops it with the last (family:action-groups; spec:AST-094 FR24)", () => {
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ for (const order of ['group first', 'plain first'] as const) {
+ document.body.innerHTML = '<div id="group"></div>';
+ const element = document.getElementById('group') as HTMLElement;
+ let pointerDowns = 0;
+ const add = element.addEventListener.bind(element);
+ const remove = element.removeEventListener.bind(element);
+ element.addEventListener = ((type: string, ...rest: [never, never?]) => {
+ if (type === 'pointerdown') {
+ pointerDowns += 1;
+ }
+ add(type, ...rest);
+ }) as typeof element.addEventListener;
+ element.removeEventListener = ((
+ type: string,
+ ...rest: [never, never?]
+ ) => {
+ if (type === 'pointerdown') {
+ pointerDowns -= 1;
+ }
+ remove(type, ...rest);
+ }) as typeof element.removeEventListener;
+ const detachGroup = fine.attach(
+ element,
+ new TapGestureRecognizer({name: 'group'}),
+ {actionGroup: true},
+ );
+ const detachPlain = fine.attach(
+ element,
+ new TapGestureRecognizer({name: 'plain'}),
+ {actionGroup: false},
+ );
+ expect(pointerDowns).toBe(1);
+ const [first, last] =
+ order === 'group first'
+ ? [detachGroup, detachPlain]
+ : [detachPlain, detachGroup];
+ // One gesture left: the element is still a group.
+ first();
+ expect(pointerDowns).toBe(1);
+ // The last one gone: nothing stays on it.
+ last();
+ expect(pointerDowns).toBe(0);
+ }
+ });
+});
+
+describe("inputMode 'pointer-events'", () => {
+ /** A clock whose timers the test fires. */
+ class TimerClock {
+ time = 0;
+ private readonly timers = new Map<number, () => void>();
+ private next = 1;
+ now(): number {
+ return this.time;
+ }
+ setTimeout(callback: () => void): number {
+ const id = this.next++;
+ this.timers.set(id, callback);
+ return id;
+ }
+ clearTimeout(id: number): void {
+ this.timers.delete(id);
+ }
+ /** Runs every timer, and the ones they set, at `time`. */
+ fireAll(time: number): void {
+ this.time = time;
+ while (this.timers.size > 0) {
+ const due = [...this.timers.values()];
+ this.timers.clear();
+ for (const callback of due) {
+ callback();
+ }
+ }
+ }
+ }
+
+ it("tracks a finger once, from its pointer events, so a still finger's long press begins", () => {
+ const {box} = mount('<div id="box"></div>');
+ const timers = new TimerClock();
+ const pointerHost = new GestureHost(document, {
+ clock: timers,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ const press = new LongPressGestureRecognizer();
+ const states: string[] = [];
+ press.addListener(r => states.push(r.state));
+ detachers.push(pointerHost.attach(box, press));
+ // A browser with Touch Events sends both for one finger.
+ pointer('pointerdown', box, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 7, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ expect(press.numberOfTouches).toBe(1);
+ timers.fireAll(800);
+ expect(states).toContain('began');
+ pointer('pointerup', box, {pointerType: 'touch', x: 10, y: 10, time: 820});
+ touch('touchend', box, [finger], [], 820);
+ expect(states).toContain('ended');
+ });
+
+ it("cancels a claimed finger's touchmove, matching its touches to its pointer", () => {
+ const {box} = mount('<div id="box"></div>');
+ const pointerHost = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(pointerHost.attach(box, pan));
+ pointer('pointerdown', box, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 7, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ // Before the pan claims, the browser keeps the move.
+ const early = {...finger, x: 14};
+ pointer('pointermove', box, {
+ pointerType: 'touch',
+ x: 14,
+ y: 10,
+ buttons: 1,
+ time: 8,
+ });
+ expect(touch('touchmove', box, [early], [early], 8).defaultPrevented).toBe(
+ false,
+ );
+ // Past its hysteresis the pan owns the finger: its touchmoves are cancelled.
+ const claimed = {...finger, x: 40};
+ pointer('pointermove', box, {
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 32,
+ });
+ expect(pan.state).toBe('began');
+ expect(
+ touch('touchmove', box, [claimed], [claimed], 32).defaultPrevented,
+ ).toBe(true);
+ });
+
+ it("cancels a claimed finger's touchmove over content inside an open shadow root, matching its touches to its pointer along the flat tree (spec:AST-094 FR19)", () => {
+ const {outer} = mount('<div id="outer"></div>');
+ const shadow = outer.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<div id="row">x</div>';
+ const row = shadow.getElementById('row') as HTMLElement;
+ const pointerHost = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(pointerHost.attach(outer, pan));
+ // The finger lands on the inner node; the claiming host's listener sees
+ // its touches retargeted to the shadow host.
+ pointer('pointerdown', row, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 7, x: 10, y: 10, target: outer};
+ touch('touchstart', row, [finger], [finger], 0);
+ pointer('pointermove', row, {
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 32,
+ });
+ expect(pan.state).toBe('began');
+ const claimed = {...finger, x: 40};
+ expect(
+ touch('touchmove', row, [claimed], [claimed], 32).defaultPrevented,
+ ).toBe(true);
+ });
+});
+
+describe('gestures attach for every pointer (spec:AST-094 FR43, FR19, FR24)', () => {
+ const gestureListeners = (spy: ReturnType<typeof vi.spyOn>) =>
+ (spy.mock.calls as unknown[][])
+ .map(call => call[0] as string)
+ .filter(t => /^(touch|pointer|click|blur|scroll|contextmenu)/.test(t));
+
+ function fineHost(): GestureHost {
+ return new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ }
+
+ function mouse(type: string, target: EventTarget, x: number, time: number) {
+ return pointer(type, target, {
+ pointerType: 'mouse',
+ x,
+ y: 10,
+ buttons: type === 'pointerup' ? 0 : 1,
+ time,
+ });
+ }
+
+ it('keeps one passive pointerdown listener on each element that uses a gesture while idle, and no page listener', () => {
+ const {box, row} = mount('<div id="box"></div><div id="row"></div>');
+ const added = vi.spyOn(document, 'addEventListener');
+ const viewAdded = vi.spyOn(window, 'addEventListener');
+ const boxAdded = vi.spyOn(box, 'addEventListener');
+ const rowAdded = vi.spyOn(row, 'addEventListener');
+ // A spy an earlier case left keeps its calls.
+ for (const spy of [added, viewAdded, boxAdded, rowAdded]) {
+ spy.mockClear();
+ }
+ const fine = fineHost();
+ detachers.push(
+ fine.attach(box, new PanGestureRecognizer({direction: 'horizontal'})),
+ fine.attachConsumer(row, new RecordingConsumer()),
+ );
+ expect(gestureListeners(added)).toEqual([]);
+ expect(gestureListeners(viewAdded)).toEqual([]);
+ // The pan's blocking touchmove for a finger's claim counts outside the
+ // one-listener budget (FR24, FR19).
+ expect(gestureListeners(boxAdded).sort()).toEqual([
+ 'pointerdown',
+ 'touchmove',
+ ]);
+ expect(gestureListeners(rowAdded)).toEqual(['pointerdown']);
+ });
+
+ it('pans with a mouse, its page listeners lasting only the press', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(window, 'addEventListener');
+ const removed = vi.spyOn(window, 'removeEventListener');
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(fine.attach(box, pan));
+ added.mockClear();
+ mouse('pointerdown', box, 10, 0);
+ expect(gestureListeners(added)).toEqual(
+ expect.arrayContaining(['pointermove', 'pointerup']),
+ );
+ mouse('pointermove', box, 25, 16);
+ mouse('pointermove', box, 40, 32);
+ mouse('pointerup', box, 40, 48);
+ expect(states[0]).toBe('began');
+ expect(states.at(-1)).toBe('ended');
+ removed.mockClear();
+ await Promise.resolve();
+ expect(gestureListeners(removed)).toEqual(
+ expect.arrayContaining(['pointermove', 'pointerup']),
+ );
+ });
+
+ it('pans with a pen', () => {
+ const {box} = mount('<div id="box"></div>');
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(fine.attach(box, pan));
+ for (const [type, x, time] of [
+ ['pointerdown', 10, 0],
+ ['pointermove', 25, 16],
+ ['pointermove', 40, 32],
+ ['pointerup', 40, 48],
+ ] as const) {
+ pointer(type, box, {
+ pointerType: 'pen',
+ x,
+ y: 10,
+ buttons: type === 'pointerup' ? 0 : 1,
+ time,
+ });
+ }
+ expect(states[0]).toBe('began');
+ expect(states.at(-1)).toBe('ended');
+ });
+
+ it('gives a press consumer a mouse press, with no feedback-only mode (DEC-21)', () => {
+ const {row} = mount('<div id="row"></div>');
+ const fine = fineHost();
+ const consumer = new RecordingConsumer();
+ detachers.push(fine.attachConsumer(row, consumer));
+ mouse('pointerdown', row, 10, 0);
+ mouse('pointerup', row, 10, 80);
+ expect(consumer.events.map(event => event.split(':')[0])).toEqual([
+ 'began',
+ 'ended',
+ ]);
+ });
+
+ it('starts nothing for a secondary button', () => {
+ const {box} = mount('<div id="box"></div>');
+ const viewAdded = vi.spyOn(window, 'addEventListener');
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ pan.addListener(r => states.push(r.state));
+ detachers.push(fine.attach(box, pan));
+ viewAdded.mockClear();
+ const down = new PointerEvent('pointerdown', {
bubbles: true,
cancelable: true,
+ composed: true,
+ pointerId: 1,
+ pointerType: 'mouse',
+ clientX: 10,
+ clientY: 10,
+ button: 2,
+ buttons: 2,
});
- box.dispatchEvent(before);
- expect(before.defaultPrevented).toBe(false);
- host.arena.advanceTime(500);
- expect(press.state).toBe('began');
- const during = new MouseEvent('contextmenu', {
- bubbles: true,
- cancelable: true,
+ box.dispatchEvent(down);
+ mouse('pointermove', box, 40, 32);
+ expect(gestureListeners(viewAdded)).toEqual([]);
+ expect(states).toEqual([]);
+ });
+
+ it("writes a pan's touch-action under a fine pointer too, for a touchscreen laptop's finger (FR18)", () => {
+ const {box} = mount('<div id="box"></div>');
+ const fine = fineHost();
+ detachers.push(
+ fine.attach(box, new PanGestureRecognizer({direction: 'horizontal'})),
+ );
+ expect(box.getAttribute('data-astryx-touch-action')).toBe(
+ 'pan-y pinch-zoom',
+ );
+ });
+
+ it("keeps a claiming recognizer's blocking touchmove listener on its element under a fine pointer, outside FR24's one-listener budget, so a touchscreen laptop's finger claims as on a phone (FR19)", () => {
+ const {box, tapper} = mount('<div id="box"></div><div id="tapper"></div>');
+ const boxAdded = vi.spyOn(box, 'addEventListener');
+ const tapperAdded = vi.spyOn(tapper, 'addEventListener');
+ for (const spy of [boxAdded, tapperAdded]) {
+ spy.mockClear();
+ }
+ const fine = fineHost();
+ detachers.push(
+ fine.attach(box, new PanGestureRecognizer({direction: 'horizontal'})),
+ fine.attach(tapper, new TapGestureRecognizer()),
+ );
+ expect(
+ (boxAdded.mock.calls as unknown[][]).filter(
+ call => call[0] === 'touchmove',
+ ),
+ ).toEqual([['touchmove', expect.any(Function), {passive: false}]]);
+ // A tap claims only at its lift: still only its one listener.
+ expect(gestureListeners(tapperAdded)).toEqual(['pointerdown']);
+ });
+
+ it('claims a finger for a one-way pan under a fine pointer through its blocking touchmove, as the pan leaves the browser every direction (FR24, FR19)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const boxAdded = vi.spyOn(box, 'addEventListener');
+ boxAdded.mockClear();
+ const fine = fineHost();
+ // A one-way pan (a toast's swipe) leaves all four directions native, so
+ // no touch-action stops the browser's pan: only cancelling moves does,
+ // through a listener the element carries before the finger lands (the
+ // browser decides at touchstart whether a move can be cancelled).
+ const swipe = new PanGestureRecognizer({name: 'swipe', direction: 'right'});
+ detachers.push(fine.attach(box, swipe));
+ expect(box.getAttribute('data-astryx-touch-action')).toBeNull();
+ expect(
+ (boxAdded.mock.calls as unknown[][]).filter(
+ call => call[0] === 'touchmove',
+ ),
+ ).toEqual([['touchmove', expect.any(Function), {passive: false}]]);
+ const finger = {id: 3, x: 5, y: 5};
+ pointer('pointerdown', box, {
+ id: 9,
+ pointerType: 'touch',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
});
- box.dispatchEvent(during);
- expect(during.defaultPrevented).toBe(true);
+ touch('touchstart', box, [finger], [finger], 0);
+ let last: Event | null = null;
+ for (const [x, time] of [
+ [20, 16],
+ [40, 32],
+ [60, 48],
+ ] as const) {
+ pointer('pointermove', box, {
+ id: 9,
+ pointerType: 'touch',
+ x,
+ y: 5,
+ buttons: 1,
+ time,
+ });
+ const moved = {id: 3, x, y: 5};
+ last = touch('touchmove', box, [moved], [moved], time);
+ }
+ expect(['began', 'changed']).toContain(swipe.state);
+ expect(last?.defaultPrevented).toBe(true);
});
- it('holds the click of a tap a double tap may claim, and replays it when the double tap fails', () => {
- const {row, button} = mount(
- '<div id="row"><button id="button">Go</button></div>',
+ it("starts no press for a right click or a ctrl-click on macOS, that platform's context click, and starts one for a ctrl-click elsewhere (FR43)", () => {
+ const {row} = mount('<div id="row"></div>');
+ const fine = fineHost();
+ const consumer = new RecordingConsumer();
+ detachers.push(fine.attachConsumer(row, consumer));
+ const platform = vi.spyOn(navigator, 'platform', 'get');
+ platform.mockReturnValue('MacIntel');
+ pointer('pointerdown', row, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ button: 2,
+ buttons: 2,
+ time: 0,
+ });
+ pointer('pointerup', row, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ button: 2,
+ time: 80,
+ });
+ pointer('pointerdown', row, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ ctrlKey: true,
+ time: 500,
+ });
+ pointer('pointerup', row, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ ctrlKey: true,
+ time: 580,
+ });
+ expect(consumer.events).toEqual([]);
+ platform.mockReturnValue('Win32');
+ pointer('pointerdown', row, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ ctrlKey: true,
+ time: 1000,
+ });
+ pointer('pointerup', row, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ ctrlKey: true,
+ time: 1080,
+ });
+ expect(consumer.events.length).toBeGreaterThan(0);
+ });
+
+ it("starts no press for a pen's barrel button, as the README says, under a fine or a coarse pointer (FR43)", () => {
+ for (const target of [fineHost(), host]) {
+ document.body.innerHTML = '';
+ const {row} = mount('<div id="row"></div>');
+ const consumer = new RecordingConsumer();
+ detachers.push(target.attachConsumer(row, consumer));
+ pointer('pointerdown', row, {
+ pointerType: 'pen',
+ x: 5,
+ y: 5,
+ button: 2,
+ buttons: 2,
+ time: 0,
+ });
+ pointer('pointerup', row, {
+ pointerType: 'pen',
+ x: 5,
+ y: 5,
+ button: 2,
+ time: 80,
+ });
+ expect(consumer.events).toEqual([]);
+ }
+ });
+
+ it("ends a fine-pointer finger's press on an action group at its lift, and the group's next press begins and ends as well (FR43, FR19)", () => {
+ vi.useFakeTimers();
+ try {
+ const {group, a} = mount(
+ '<div id="group"><button id="a">A</button><button id="b">B</button></div>',
+ );
+ const laptop = new GestureHost(document, {
+ isPrimaryPointerCoarse: () => false,
+ });
+ // The action-group adapter's recognizer: a long press with no minimum
+ // duration and no movement limit, attached as an action group.
+ const press = new LongPressGestureRecognizer({
+ minimumPressDuration: 0,
+ allowableMovement: Number.POSITIVE_INFINITY,
+ });
+ const states: string[] = [];
+ press.addTransitionListener((_recognizer, _from, to) => states.push(to));
+ detachers.push(laptop.attach(group, press, {actionGroup: true}));
+ // Chromium on a touchscreen laptop: pointerdown, then touchstart; at
+ // the lift, pointerup, then touchend.
+ const fingerPress = (
+ pointerId: number,
+ touchId: number,
+ time: number,
+ ) => {
+ const finger = {id: touchId, x: 10, y: 10};
+ pointer('pointerdown', a, {
+ id: pointerId,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time,
+ });
+ touch('touchstart', a, [finger], [finger], time);
+ vi.advanceTimersByTime(20);
+ pointer('pointerup', a, {
+ id: pointerId,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ time: time + 50,
+ });
+ touch('touchend', a, [finger], [], time + 50);
+ vi.advanceTimersByTime(20);
+ };
+ fingerPress(31, 0, 0);
+ const first = states.splice(0);
+ fingerPress(32, 1, 1000);
+ expect(first).toEqual(expect.arrayContaining(['began', 'ended']));
+ expect(states).toEqual(expect.arrayContaining(['began', 'ended']));
+ expect(press.state).toBe('possible');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('takes perEventPointer as it takes any attach, and warns for nothing', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ detachers.push(() => warn.mockRestore());
+ const {box, row} = mount('<div id="box"></div><div id="row"></div>');
+ const boxAdded = vi.spyOn(box, 'addEventListener');
+ const rowAdded = vi.spyOn(row, 'addEventListener');
+ const fine = fineHost();
+ detachers.push(
+ fine.attach(box, new PanGestureRecognizer({direction: 'horizontal'}), {
+ perEventPointer: true,
+ }),
+ fine.attach(row, new PanGestureRecognizer({direction: 'horizontal'})),
+ );
+ expect(gestureListeners(boxAdded)).toEqual(gestureListeners(rowAdded));
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("cancels a claimed finger's touchend, a recognized tap's too, and leaves an unclaimed one's alone (spec:AST-094 FR21)", () => {
+ const {box, other, tapper} = mount(
+ '<div id="box"></div><div id="other"></div><div id="tapper"></div>',
);
+ const pointerHost = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(
+ pointerHost.attach(box, pan),
+ // A hold a short tap never reaches: the touch is tracked, unclaimed.
+ pointerHost.attach(other, new LongPressGestureRecognizer()),
+ pointerHost.attach(tapper, new TapGestureRecognizer()),
+ );
+ // A pan that claims, then lifts: its touchend is cancelled (FR21).
+ pointer('pointerdown', box, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 7, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ pointer('pointermove', box, {
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 32,
+ });
+ expect(pan.state).toBe('began');
+ pointer('pointerup', box, {pointerType: 'touch', x: 40, y: 10, time: 48});
+ const lifted = {...finger, x: 40};
+ expect(touch('touchend', box, [lifted], [], 48).defaultPrevented).toBe(
+ true,
+ );
+ // A tap nobody claims keeps its touchend.
+ pointer('pointerdown', other, {
+ id: 2,
+ pointerType: 'touch',
+ x: 10,
+ y: 80,
+ buttons: 1,
+ time: 400,
+ });
+ const second = {id: 8, x: 10, y: 80};
+ touch('touchstart', other, [second], [second], 400);
+ pointer('pointerup', other, {
+ id: 2,
+ pointerType: 'touch',
+ x: 10,
+ y: 80,
+ time: 460,
+ });
+ expect(touch('touchend', other, [second], [], 460).defaultPrevented).toBe(
+ false,
+ );
+ // A tap recognizer replaces the click, as under Touch Events: its lift's
+ // touchend is cancelled, so no compatibility mouse event follows.
+ pointer('pointerdown', tapper, {
+ id: 3,
+ pointerType: 'touch',
+ x: 10,
+ y: 160,
+ buttons: 1,
+ time: 800,
+ });
+ const third = {id: 9, x: 10, y: 160};
+ touch('touchstart', tapper, [third], [third], 800);
+ pointer('pointerup', tapper, {
+ id: 3,
+ pointerType: 'touch',
+ x: 10,
+ y: 160,
+ time: 860,
+ });
+ expect(touch('touchend', tapper, [third], [], 860).defaultPrevented).toBe(
+ true,
+ );
+ });
+
+ it("cancels a claimed finger's touchend under a fine primary pointer too, after the microtask that follows its pointerup has taken the armed press's listeners: a touchscreen laptop whose fingers come from pointer events (spec:AST-094 FR21, FR24, FR43)", async () => {
+ const {box} = mount('<div id="box"></div>');
+ const pointerHost = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => false,
+ });
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(pointerHost.attach(box, pan));
+ pointer('pointerdown', box, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ const finger = {id: 7, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ pointer('pointermove', box, {
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 32,
+ });
+ expect(pan.state).toBe('began');
+ pointer('pointerup', box, {pointerType: 'touch', x: 40, y: 10, time: 48});
+ // iOS and WebKit send the touchend in the pointerup's own task, after its
+ // microtasks. The armed press's page listeners go in that microtask
+ // (FR24); the lift's note stays.
+ await Promise.resolve();
+ expect((pointerHost as unknown as {isInstalled: boolean}).isInstalled).toBe(
+ false,
+ );
+ const lifted = {...finger, x: 40};
+ expect(touch('touchend', box, [lifted], [], 48).defaultPrevented).toBe(
+ true,
+ );
+ });
+
+ it('lets a mouse press go once the tap that waited on a double tap is decided, under a fine primary pointer: its page listeners go then (spec:AST-094 FR24)', async () => {
+ const timers: (() => void)[] = [];
+ const timerClock = {
+ now: () => clock.time,
+ setTimeout: (run: () => void) => timers.push(run),
+ clearTimeout: () => {},
+ };
+ const {box} = mount('<div id="box"></div>');
+ const fine = new GestureHost(document, {
+ clock: timerClock,
+ isPrimaryPointerCoarse: () => false,
+ });
const double = new TapGestureRecognizer({
name: 'double',
numberOfTapsRequired: 2,
});
- detachers.push(host.attach(row, double));
- const clicks: {target: EventTarget | null; detail: number}[] = [];
- button.addEventListener('click', event =>
- clicks.push({target: event.target, detail: event.detail}),
+ const single = new TapGestureRecognizer({name: 'single'}).requireToFail(
+ double,
);
- const finger = {id: 1, x: 10, y: 10};
- touch('touchstart', button, [finger], [finger], 0);
- const end = touch('touchend', button, [finger], [], 60);
- expect(end.defaultPrevented).toBe(true);
- expect(clicks).toEqual([]);
- const interval = UIKIT_GESTURES.tap.maximumIntervalBetweenTaps.value;
- host.arena.advanceTime(60 + interval);
- expect(clicks).toEqual([{target: button, detail: 1}]);
+ const states: string[] = [];
+ single.addTransitionListener((_r, _from, to) => states.push(to));
+ detachers.push(fine.attach(box, double), fine.attach(box, single));
+ const isInstalled = () =>
+ (fine as unknown as {isInstalled: boolean}).isInstalled;
+ pointer('pointerdown', box, {
+ pointerType: 'mouse',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ pointer('pointerup', box, {pointerType: 'mouse', x: 10, y: 10, time: 40});
+ await Promise.resolve();
+ // The single tap waits on the double tap: the press is not over yet.
+ expect(isInstalled()).toBe(true);
+ clock.time = 2000;
+ while (timers.length > 0) {
+ timers.shift()?.();
+ }
+ expect(states).toContain('ended');
+ await Promise.resolve();
+ expect(isInstalled()).toBe(false);
+ });
+
+ it('keeps no touchend listener under a fine primary pointer where the browser sends no Touch Events: no touchend ever comes (spec:AST-094 FR24)', () => {
+ let owner: object | null = window;
+ while (
+ owner != null &&
+ !Object.prototype.hasOwnProperty.call(owner, 'ontouchstart')
+ ) {
+ owner = Object.getPrototypeOf(owner) as object | null;
+ }
+ if (owner == null) {
+ throw new Error('no ontouchstart to take away');
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(owner, 'ontouchstart');
+ Reflect.deleteProperty(owner, 'ontouchstart');
+ try {
+ expect('ontouchstart' in window).toBe(false);
+ const {box} = mount('<div id="box"></div>');
+ const added = vi.spyOn(box, 'addEventListener');
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ detachers.push(
+ fine.attach(box, new PanGestureRecognizer({direction: 'horizontal'})),
+ );
+ expect(added.mock.calls.map(call => call[0])).not.toContain('touchend');
+ } finally {
+ if (descriptor != null) {
+ Object.defineProperty(owner, 'ontouchstart', descriptor);
+ }
+ }
});
- it('collects recognizers across shadow roots', () => {
+ it("cancels a claimed finger's touchend inside an open shadow root below the element, comparing the place its pointer landed with its touch's (spec:AST-094 FR21)", () => {
const {outer} = mount('<div id="outer"></div>');
const shadow = outer.attachShadow({mode: 'open'});
- shadow.innerHTML = '<span id="inner">x</span>';
- const inner = shadow.getElementById('inner') as HTMLElement;
- const tap = new TapGestureRecognizer({name: 'tap'});
- const actions: string[] = [];
- tap.addListener(r => actions.push(r.state));
- detachers.push(host.attach(outer, tap));
- const finger = {id: 1, x: 5, y: 5, target: inner};
- touch('touchstart', inner, [finger], [finger], 0);
- touch('touchend', inner, [finger], [], 50);
- expect(actions).toEqual(['ended']);
+ shadow.innerHTML = '<div id="row">x</div>';
+ const row = shadow.getElementById('row') as HTMLElement;
+ const pointerHost = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(pointerHost.attach(outer, pan));
+ pointer('pointerdown', row, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ // The element's own listener sees the finger's touch retargeted to the
+ // shadow host; its pointer landed on the inner node.
+ const finger = {id: 7, x: 10, y: 10, target: outer};
+ touch('touchstart', row, [finger], [finger], 0);
+ pointer('pointermove', row, {
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 32,
+ });
+ expect(pan.state).toBe('began');
+ pointer('pointerup', row, {pointerType: 'touch', x: 40, y: 10, time: 48});
+ const lifted = {...finger, x: 40};
+ expect(touch('touchend', row, [lifted], [], 48).defaultPrevented).toBe(
+ true,
+ );
});
- it('cancels every touch in flight when the window loses focus', () => {
+ it('forgets a claimed lift whose touchend never came: a later tap at that place keeps its touchend (spec:AST-094 FR21)', () => {
const {box} = mount('<div id="box"></div>');
- const pan = new PanGestureRecognizer({name: 'pan'});
- const states: string[] = [];
- pan.addListener(r => states.push(r.state));
- detachers.push(host.attach(box, pan));
- const finger = {id: 1, x: 10, y: 10};
- touch('touchstart', box, [finger], [finger], 0);
- touch('touchmove', box, [{...finger, x: 40}], [{...finger, x: 40}], 16);
- window.dispatchEvent(new Event('blur'));
- expect(states).toEqual(['began', 'cancelled']);
+ const pointerHost = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(pointerHost.attach(box, pan));
+ pointer('pointerdown', box, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ pointer('pointermove', box, {
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 32,
+ });
+ expect(pan.state).toBe('began');
+ // The claimed finger lifts, and no touchend follows (a browser that
+ // sends pointer events alone for it).
+ pointer('pointerup', box, {pointerType: 'touch', x: 40, y: 10, time: 48});
+ // Two seconds later, an unclaimed tap at the same place.
+ pointer('pointerdown', box, {
+ id: 2,
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 2048,
+ });
+ const tap = {id: 9, x: 40, y: 10};
+ touch('touchstart', box, [tap], [tap], 2048);
+ pointer('pointerup', box, {
+ id: 2,
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ time: 2100,
+ });
+ expect(touch('touchend', box, [tap], [], 2100).defaultPrevented).toBe(
+ false,
+ );
});
- it('finishes a gesture whose target left the document mid-gesture', () => {
- const {box, child} = mount('<div id="box"><span id="child">x</span></div>');
- const pan = new PanGestureRecognizer({name: 'pan'});
- const states: string[] = [];
- pan.addListener(r => states.push(r.state));
- detachers.push(host.attach(box, pan));
- const finger = {id: 1, x: 10, y: 10};
- touch('touchstart', child, [finger], [finger], 0);
- touch('touchmove', child, [{...finger, x: 40}], [{...finger, x: 40}], 16);
- // A re-render replaces the span: its events no longer reach the document.
- child.remove();
- const move = touch(
- 'touchmove',
- child,
- [{...finger, x: 60}],
- [{...finger, x: 60}],
- 32,
+ /** The claimed lifts a host holds, each with the node its finger lifted on. */
+ const claimedLiftsOf = (host: GestureHost) =>
+ (host as unknown as {claimedLifts: ReadonlyArray<unknown>}).claimedLifts;
+
+ /** A horizontal pan claims a finger from its pointer events, then it lifts. */
+ const claimAndLift = (
+ box: HTMLElement,
+ id: number,
+ y: number,
+ time: number,
+ ) => {
+ pointer('pointerdown', box, {
+ id,
+ pointerType: 'touch',
+ x: 10,
+ y,
+ buttons: 1,
+ time,
+ });
+ pointer('pointermove', box, {
+ id,
+ pointerType: 'touch',
+ x: 40,
+ y,
+ buttons: 1,
+ time: time + 4,
+ });
+ pointer('pointerup', box, {
+ id,
+ pointerType: 'touch',
+ x: 40,
+ y,
+ time: time + 8,
+ });
+ };
+
+ it('keeps at most 8 claimed lifts waiting for their touchend, dropping the oldest first (spec:AST-094 FR24)', () => {
+ const {box} = mount('<div id="box"></div>');
+ const pointerHost = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ detachers.push(
+ pointerHost.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ ),
);
- expect(move.defaultPrevented).toBe(true);
- touch('touchend', child, [{...finger, x: 60}], [], 48);
- // The move and the lift after the removal still reached the pan.
- expect(states).toEqual(['began', 'changed', 'ended']);
- expect(host.arena.touches).toEqual([]);
+ // Nine claimed lifts at nine places within 90 ms, no touchend after any.
+ for (let i = 0; i < 9; i++) {
+ claimAndLift(box, i + 1, 10 + i * 10, i * 10);
+ }
+ expect(claimedLiftsOf(pointerHost)).toHaveLength(8);
+ // The oldest went: its late touchend is the page's; the newest still waits.
+ const first = {id: 1, x: 40, y: 10};
+ expect(touch('touchend', box, [first], [], 100).defaultPrevented).toBe(
+ false,
+ );
+ const last = {id: 9, x: 40, y: 90};
+ expect(touch('touchend', box, [last], [], 100).defaultPrevented).toBe(true);
});
- it('cancels a finger the events say is no longer down', () => {
+ it('holds no claimed lift once its time passes with no touchend, and none where no touchend can come (spec:AST-094 FR24)', () => {
+ const timers: (() => void)[] = [];
+ const timerClock = {
+ now: () => clock.time,
+ setTimeout: (run: () => void) => timers.push(run),
+ clearTimeout: () => {},
+ };
const {box} = mount('<div id="box"></div>');
- const pan = new PanGestureRecognizer({name: 'pan'});
- const states: string[] = [];
- pan.addListener(r => states.push(r.state));
- detachers.push(host.attach(box, pan));
- const first = {id: 1, x: 10, y: 10};
- touch('touchstart', box, [first], [first], 0);
- touch('touchmove', box, [{...first, x: 40}], [{...first, x: 40}], 16);
- // Its touchend went to a node outside the document; the next event for
- // another finger no longer lists it.
- const other = {id: 2, x: 300, y: 300};
- touch('touchmove', document.body, [other], [other], 32);
- expect(states).toEqual(['began', 'cancelled']);
+ const pointerHost = new GestureHost(document, {
+ clock: timerClock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ detachers.push(
+ pointerHost.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ ),
+ );
+ claimAndLift(box, 1, 10, 0);
+ expect(claimedLiftsOf(pointerHost)).toHaveLength(1);
+ // No touchend comes: once its time has passed, nothing holds the node.
+ clock.time = 600;
+ for (const run of timers.splice(0)) {
+ run();
+ }
+ expect(claimedLiftsOf(pointerHost)).toEqual([]);
+
+ // Where no touchend can come at all (a fine primary pointer, no Touch
+ // Events), a claimed lift is never held.
+ let owner: object | null = window;
+ while (
+ owner != null &&
+ !Object.prototype.hasOwnProperty.call(owner, 'ontouchstart')
+ ) {
+ owner = Object.getPrototypeOf(owner) as object | null;
+ }
+ if (owner == null) {
+ throw new Error('no ontouchstart to take away');
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(owner, 'ontouchstart');
+ Reflect.deleteProperty(owner, 'ontouchstart');
+ try {
+ const {other} = mount('<div id="other"></div>');
+ const fine = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ detachers.push(
+ fine.attach(other, new PanGestureRecognizer({direction: 'horizontal'})),
+ );
+ for (let i = 0; i < 3; i++) {
+ claimAndLift(other, 20 + i, 10 + i * 10, 1000 + i * 10);
+ }
+ expect(claimedLiftsOf(fine)).toEqual([]);
+ } finally {
+ if (descriptor != null) {
+ Object.defineProperty(owner, 'ontouchstart', descriptor);
+ }
+ }
});
+});
- it('treats a reused finger number as a new touch', () => {
+describe('Touch Events from a browser that exposes no ontouchstart', () => {
+ it('takes a finger once, from its pointer events, so a one-finger long press recognizes (touch emulation turned on after load)', () => {
+ // Chromium fixes `ontouchstart` when the page is created; turning touch
+ // emulation on later sends Touch Events without it.
+ let owner: object | null = window;
+ let descriptor: PropertyDescriptor | undefined;
+ while (owner != null) {
+ descriptor = Object.getOwnPropertyDescriptor(owner, 'ontouchstart');
+ if (descriptor != null) {
+ break;
+ }
+ owner = Object.getPrototypeOf(owner) as object | null;
+ }
+ if (owner != null && descriptor != null) {
+ const from = owner;
+ const saved = descriptor;
+ delete (from as {ontouchstart?: unknown}).ontouchstart;
+ detachers.push(() => Object.defineProperty(from, 'ontouchstart', saved));
+ }
+ expect('ontouchstart' in window).toBe(false);
const {box} = mount('<div id="box"></div>');
- const tap = new TapGestureRecognizer({name: 'tap'});
- const states: string[] = [];
- tap.addListener(r => states.push(r.state));
- detachers.push(host.attach(box, tap));
- const finger = {id: 4, x: 10, y: 10};
+ const press = new LongPressGestureRecognizer({name: 'press'});
+ detachers.push(host.attach(box, press));
+ const finger = {id: 1, x: 10, y: 10};
+ pointer('pointerdown', box, {
+ id: 7,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
touch('touchstart', box, [finger], [finger], 0);
- // No touchend reached us; the same identifier lands again.
- touch('touchstart', box, [finger], [finger], 500);
- touch('touchend', box, [finger], [], 560);
- expect(states).toEqual(['ended']);
+ host.arena.advanceTime(600);
+ expect(press.state).toBe('began');
});
- it('cancels every finger on a touchcancel that names none', () => {
+ it("cancels a claimed pan's touchmove there too: the finger read from its pointer events is the one the move reports", () => {
+ let owner: object | null = window;
+ let descriptor: PropertyDescriptor | undefined;
+ while (owner != null) {
+ descriptor = Object.getOwnPropertyDescriptor(owner, 'ontouchstart');
+ if (descriptor != null) {
+ break;
+ }
+ owner = Object.getPrototypeOf(owner) as object | null;
+ }
+ if (owner != null && descriptor != null) {
+ const from = owner;
+ const saved = descriptor;
+ delete (from as {ontouchstart?: unknown}).ontouchstart;
+ detachers.push(() => Object.defineProperty(from, 'ontouchstart', saved));
+ }
+ expect('ontouchstart' in window).toBe(false);
const {box} = mount('<div id="box"></div>');
- const pan = new PanGestureRecognizer({name: 'pan'});
- const states: string[] = [];
- pan.addListener(r => states.push(r.state));
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
detachers.push(host.attach(box, pan));
const finger = {id: 1, x: 10, y: 10};
+ pointer('pointerdown', box, {
+ id: 7,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
touch('touchstart', box, [finger], [finger], 0);
- touch('touchmove', box, [{...finger, x: 40}], [{...finger, x: 40}], 16);
- box.dispatchEvent(new Event('touchcancel', {bubbles: true}));
- expect(states).toEqual(['began', 'cancelled']);
+ for (const [x, time] of [
+ [30, 16],
+ [50, 32],
+ ] as const) {
+ pointer('pointermove', box, {
+ id: 7,
+ pointerType: 'touch',
+ x,
+ y: 10,
+ buttons: 1,
+ time,
+ });
+ }
+ expect(['began', 'changed']).toContain(pan.state);
+ const moved = {...finger, x: 50};
+ const move = touch('touchmove', box, [moved], [moved], 32);
+ expect(move.defaultPrevented).toBe(true);
});
- it('reads epoch-stamped events on the arena clock', () => {
- const {box} = mount('<div id="box"></div>');
- const pan = new PanGestureRecognizer({name: 'pan'});
- let released = {x: 0, y: 0};
- pan.addListener(r => {
- if (r.state === 'ended') {
- released = r.velocity();
+ it("cancels a claimed finger's touchend there too: the lift of a pan that claimed from the finger's pointer events (spec:AST-094 FR21)", () => {
+ let owner: object | null = window;
+ let descriptor: PropertyDescriptor | undefined;
+ while (owner != null) {
+ descriptor = Object.getOwnPropertyDescriptor(owner, 'ontouchstart');
+ if (descriptor != null) {
+ break;
}
- });
- detachers.push(host.attach(box, pan));
- const epoch = performance.timeOrigin + 5000;
- const finger = {id: 1, x: 0, y: 10};
- touch('touchstart', box, [finger], [finger], epoch);
- for (let t = 8; t <= 96; t += 8) {
- const at = {...finger, x: t};
- touch('touchmove', box, [at], [at], epoch + t);
+ owner = Object.getPrototypeOf(owner) as object | null;
}
- touch('touchend', box, [{...finger, x: 96}], [], epoch + 100);
- expect(released.x).toBeCloseTo(1000, 0);
- expect(host.arena.now()).toBeLessThan(1e9);
- });
-
- it('ignores touches that land outside every attached element', () => {
- const {box, elsewhere} = mount(
- '<div id="box"></div><div id="elsewhere"></div>',
- );
- const pan = new PanGestureRecognizer({name: 'pan'});
- detachers.push(host.attach(box, pan));
+ if (owner != null && descriptor != null) {
+ const from = owner;
+ const saved = descriptor;
+ delete (from as {ontouchstart?: unknown}).ontouchstart;
+ detachers.push(() => Object.defineProperty(from, 'ontouchstart', saved));
+ }
+ expect('ontouchstart' in window).toBe(false);
+ const {box} = mount('<div id="box"></div>');
+ const auto = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(auto.attach(box, pan));
const finger = {id: 1, x: 10, y: 10};
- touch('touchstart', elsewhere, [finger], [finger], 0);
- const move = touch(
- 'touchmove',
- elsewhere,
- [{...finger, x: 60}],
- [{...finger, x: 60}],
- 16,
+ pointer('pointerdown', box, {
+ id: 7,
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ touch('touchstart', box, [finger], [finger], 0);
+ pointer('pointermove', box, {
+ id: 7,
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ buttons: 1,
+ time: 32,
+ });
+ expect(pan.state).toBe('began');
+ pointer('pointerup', box, {
+ id: 7,
+ pointerType: 'touch',
+ x: 40,
+ y: 10,
+ time: 48,
+ });
+ const lifted = {...finger, x: 40};
+ expect(touch('touchend', box, [lifted], [], 48).defaultPrevented).toBe(
+ true,
);
- expect(move.defaultPrevented).toBe(false);
- expect(host.arena.touches).toEqual([]);
});
});
-
describe('every pointer where the primary pointer is fine (spec:AST-094 FR19, FR24, FR43)', () => {
/** The page listeners live now, by type: what was added and not removed. */
function pageListeners(): () => string[] {
@@ -1617,74 +5199,6 @@ describe('every pointer where the primary pointer is fine (spec:AST-094 FR19, FR
expect(offAdded).not.toHaveBeenCalled();
});
- it("installs the page listeners for a mouse's primary-button press, serves it to every recognizer on its path, and removes them as the press ends", () => {
- vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']});
- const {outer, box} = mount('<div id="outer"><div id="box"></div></div>');
- const live = pageListeners();
- const fine = fineHost();
- const pan = new PanGestureRecognizer({
- name: 'pan',
- direction: 'horizontal',
- });
- const outerTap = new TapGestureRecognizer({name: 'outer'});
- const states: string[] = [];
- const outerTransitions: string[] = [];
- pan.addListener(r => states.push(r.state));
- outerTap.addTransitionListener((_current, _from, to) =>
- outerTransitions.push(to),
- );
- detachers.push(fine.attach(box, pan), fine.attach(outer, outerTap));
- pointer('pointerdown', box, {
- pointerType: 'mouse',
- x: 10,
- y: 10,
- buttons: 1,
- time: 0,
- });
- expect(live()).toEqual(
- expect.arrayContaining(['click', 'pointermove', 'pointerup']),
- );
- pointer('pointermove', box, {
- pointerType: 'mouse',
- x: 40,
- y: 10,
- buttons: 1,
- time: 16,
- });
- pointer('pointerup', box, {pointerType: 'mouse', x: 40, y: 10, time: 32});
- expect(states[0]).toBe('began');
- expect(states[states.length - 1]).toBe('ended');
- expect(outerTransitions).toContain('failed');
- // The click the claimed lift owes is still swallowed (FR21): its
- // listener alone stays, for the swallower's window.
- expect(live()).toEqual(['click']);
- vi.advanceTimersByTime(1001);
- expect(live()).toEqual([]);
- });
-
- it('removes every page listener at once after a press nothing claimed', () => {
- const {box} = mount('<div id="box"></div>');
- const live = pageListeners();
- const fine = fineHost();
- detachers.push(fine.attach(box, new PanGestureRecognizer()));
- pointer('pointerdown', box, {
- pointerType: 'mouse',
- x: 10,
- y: 10,
- buttons: 1,
- time: 0,
- });
- pointer('pointermove', box, {
- pointerType: 'mouse',
- x: 13,
- y: 10,
- buttons: 1,
- time: 16,
- });
- pointer('pointerup', box, {pointerType: 'mouse', x: 13, y: 10, time: 40});
- expect(live()).toEqual([]);
- });
-
it("starts no press for a right click, a pen's barrel button or a ctrl-click on macOS (spec:AST-094 FR43)", () => {
const {box} = mount('<div id="box"></div>');
const live = pageListeners();
@@ -1702,78 +5216,6 @@ describe('every pointer where the primary pointer is fine (spec:AST-094 FR19, FR
expect(host.arena.touches).toEqual([]);
});
- it('serves a pen press, and keeps no pointer listener after it', () => {
- const {box} = mount('<div id="box"></div>');
- const live = pageListeners();
- const fine = fineHost();
- const pan = new PanGestureRecognizer({direction: 'horizontal'});
- const states: string[] = [];
- pan.addListener(r => states.push(r.state));
- detachers.push(fine.attach(box, pan));
- pointer('pointerdown', box, {
- id: 3,
- pointerType: 'pen',
- x: 10,
- y: 10,
- buttons: 1,
- time: 0,
- });
- pointer('pointermove', box, {
- id: 3,
- pointerType: 'pen',
- x: 40,
- y: 10,
- buttons: 1,
- time: 16,
- });
- pointer('pointerup', box, {
- id: 3,
- pointerType: 'pen',
- x: 40,
- y: 10,
- time: 32,
- });
- expect(states[0]).toBe('began');
- expect(states[states.length - 1]).toBe('ended');
- expect(live().filter(type => type !== 'click')).toEqual([]);
- });
-
- it("serves a touchscreen laptop's finger: its pointerdown brings the page listeners, its touches are read, and a claim cancels its touchmove and its lift", () => {
- const {box} = mount('<div id="box"></div>');
- const live = pageListeners();
- const fine = fineHost();
- const pan = new PanGestureRecognizer({direction: 'horizontal'});
- const states: string[] = [];
- pan.addListener(r => states.push(r.state));
- detachers.push(fine.attach(box, pan));
- const finger = {id: 1, x: 10, y: 10};
- const moved = {id: 1, x: 40, y: 10};
- pointer('pointerdown', box, {
- id: 5,
- pointerType: 'touch',
- x: 10,
- y: 10,
- buttons: 1,
- time: 0,
- });
- expect(live()).toEqual(expect.arrayContaining(['touchstart', 'touchend']));
- touch('touchstart', box, [finger], [finger], 0);
- const move = touch('touchmove', box, [moved], [moved], 16);
- expect(states).toContain('began');
- expect(move.defaultPrevented).toBe(true);
- pointer('pointerup', box, {
- id: 5,
- pointerType: 'touch',
- x: 40,
- y: 10,
- time: 32,
- });
- const lift = touch('touchend', box, [moved], [], 32);
- expect(lift.defaultPrevented).toBe(true);
- expect(states[states.length - 1]).toBe('ended');
- expect(live().filter(type => type !== 'click')).toEqual([]);
- });
-
it('serves an action group like every attachment: its press reaches every recognizer on its path (family:action-groups FR5)', () => {
const {outer, group, one} = mount(
'<div id="outer"><div id="group"><button id="one"></button></div></div>',
@@ -1938,108 +5380,443 @@ describe('every pointer where the primary pointer is fine (spec:AST-094 FR19, FR
}
});
- it('removes the element listener on detach and leaves nothing on the page', () => {
+ it('removes the element listener on detach and leaves nothing on the page', () => {
+ const {box} = mount('<div id="box"></div>');
+ const live = pageListeners();
+ const boxRemoved = vi.spyOn(box, 'removeEventListener');
+ const fine = fineHost();
+ const detach = fine.attach(box, new TapGestureRecognizer());
+ detach();
+ expect(boxRemoved).toHaveBeenCalledWith(
+ 'pointerdown',
+ expect.any(Function),
+ {capture: true, passive: true},
+ );
+ expect(live()).toEqual([]);
+ });
+
+ it('gives a coarse primary pointer its page listeners and no element pointerdown', () => {
+ const {box} = mount('<div id="box"></div>');
+ const live = pageListeners();
+ const boxAdded = vi.spyOn(box, 'addEventListener');
+ const coarse = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ detachers.push(coarse.attach(box, new TapGestureRecognizer()));
+ expect(live()).toEqual(
+ expect.arrayContaining(['pointerdown', 'touchstart']),
+ );
+ expect(
+ boxAdded.mock.calls.filter(call => call[0] === 'pointerdown'),
+ ).toEqual([]);
+ });
+});
+
+describe('nothing left after the last detach (spec:AST-094 FR21, FR24)', () => {
+ /** Listeners added and not removed since the case began: target and type. */
+ let open: Map<string, string>;
+ /** Frames and timeouts scheduled, neither run nor cancelled. */
+ let pendingFrames: Set<number>;
+ let pendingTimeouts: Set<number>;
+ let restore: (() => void)[];
+
+ beforeEach(() => {
+ open = new Map();
+ pendingFrames = new Set();
+ pendingTimeouts = new Set();
+ restore = [];
+ const ids = new WeakMap<object, number>();
+ let next = 0;
+ const idOf = (value: object) => {
+ let id = ids.get(value);
+ if (id == null) {
+ next += 1;
+ id = next;
+ ids.set(value, id);
+ }
+ return id;
+ };
+ const nameOf = (target: EventTarget) =>
+ target === window
+ ? 'window'
+ : target === document
+ ? 'document'
+ : target instanceof Element
+ ? `#${target.id || target.tagName}`
+ : 'other';
+ const keyOf = (
+ target: EventTarget,
+ type: string,
+ listener: object,
+ options: unknown,
+ ) => {
+ const capture =
+ typeof options === 'boolean'
+ ? options
+ : Boolean((options as AddEventListenerOptions | undefined)?.capture);
+ return `${idOf(target)}|${type}|${capture}|${idOf(listener)}`;
+ };
+ const add = EventTarget.prototype.addEventListener;
+ const remove = EventTarget.prototype.removeEventListener;
+ EventTarget.prototype.addEventListener = function (
+ this: EventTarget,
+ type: string,
+ listener: EventListenerOrEventListenerObject | null,
+ options?: boolean | AddEventListenerOptions,
+ ) {
+ if (listener != null) {
+ open.set(
+ keyOf(this, type, listener, options),
+ `${nameOf(this)} ${type}`,
+ );
+ }
+ add.call(this, type, listener, options);
+ };
+ EventTarget.prototype.removeEventListener = function (
+ this: EventTarget,
+ type: string,
+ listener: EventListenerOrEventListenerObject | null,
+ options?: boolean | EventListenerOptions,
+ ) {
+ if (listener != null) {
+ open.delete(keyOf(this, type, listener, options));
+ }
+ remove.call(this, type, listener, options);
+ };
+ restore.push(() => {
+ EventTarget.prototype.addEventListener = add;
+ EventTarget.prototype.removeEventListener = remove;
+ });
+ const raf = window.requestAnimationFrame;
+ const caf = window.cancelAnimationFrame;
+ window.requestAnimationFrame = callback => {
+ const id: number = raf.call(window, time => {
+ pendingFrames.delete(id);
+ callback(time);
+ });
+ pendingFrames.add(id);
+ return id;
+ };
+ window.cancelAnimationFrame = id => {
+ pendingFrames.delete(id);
+ caf.call(window, id);
+ };
+ const timeout = window.setTimeout;
+ const clear = window.clearTimeout;
+ (window as {setTimeout: unknown}).setTimeout = (
+ handler: () => void,
+ ms?: number,
+ ): number => {
+ const handle = Number(
+ timeout.call(
+ window,
+ () => {
+ pendingTimeouts.delete(handle);
+ handler();
+ },
+ ms,
+ ),
+ );
+ pendingTimeouts.add(handle);
+ return handle;
+ };
+ (window as {clearTimeout: unknown}).clearTimeout = (handle: number) => {
+ pendingTimeouts.delete(handle);
+ clear.call(window, handle);
+ };
+ restore.push(() => {
+ window.requestAnimationFrame = raf;
+ window.cancelAnimationFrame = caf;
+ window.setTimeout = timeout;
+ window.clearTimeout = clear;
+ });
+ });
+
+ afterEach(() => {
+ for (const undo of restore.reverse()) {
+ undo();
+ }
+ });
+
+ const COLLECTIONS = [
+ 'registry',
+ 'pendingCallerReads',
+ 'lockedBy',
+ 'retargeted',
+ 'touchIds',
+ 'cancelledFingers',
+ 'touchTargets',
+ 'watched',
+ 'blockingFingers',
+ 'claimingFingers',
+ 'pointerIds',
+ 'layoutWatched',
+ 'judgedUncancelable',
+ 'fingerPointers',
+ 'pendingPointers',
+ 'claimedLifts',
+ 'unpairedTouches',
+ 'lastFed',
+ 'pointerFed',
+ 'ownedScrolls',
+ 'touchGates',
+ 'fingerListeners',
+ 'armedElements',
+ 'fingerTargets',
+ 'unsubscribers',
+ 'claimingUnsubscribers',
+ 'ownScrollFrames',
+ ];
+ const EMPTY_FIELDS = [
+ 'layoutObserver',
+ 'claimedLiftTimer',
+ 'stopWatchingMovers',
+ 'stopWatchingPointer',
+ 'lastTouch',
+ 'lastScroll',
+ 'cancelCallerRead',
+ ];
+ const FLAGS = [
+ 'isInstalled',
+ 'isArmedPress',
+ 'isClaimingInstalled',
+ 'isBlockingForMovers',
+ 'isCallerReadScheduled',
+ ];
+
+ /** The page holds no host listener, the host no note, and nothing waits. */
+ function expectNothingLeft(subject: GestureHost) {
+ const state = subject as unknown as Record<string, unknown>;
+ const left: Record<string, unknown> = {};
+ for (const name of COLLECTIONS) {
+ const value = state[name] as {size?: number; length?: number};
+ const size = value.size ?? value.length;
+ if (size !== 0) {
+ left[name] = size;
+ }
+ }
+ for (const name of EMPTY_FIELDS) {
+ if (state[name] != null) {
+ left[name] = 'set';
+ }
+ }
+ for (const name of FLAGS) {
+ if (state[name] !== false) {
+ left[name] = state[name];
+ }
+ }
+ if (state.retainers !== 0) {
+ left.retainers = state.retainers;
+ }
+ const arena = subject.arena as unknown as {
+ timers: Map<unknown, unknown>;
+ realTimerDeadline: number;
+ records: Map<unknown, unknown>;
+ active: unknown[];
+ };
+ if (arena.timers.size > 0) {
+ left.arenaTimers = arena.timers.size;
+ }
+ if (arena.realTimerDeadline !== Number.POSITIVE_INFINITY) {
+ left.arenaDeadline = arena.realTimerDeadline;
+ }
+ if (arena.records.size > 0) {
+ left.arenaRecords = arena.records.size;
+ }
+ if (arena.active.length > 0) {
+ left.arenaActive = arena.active.length;
+ }
+ if (open.size > 0) {
+ left.listeners = [...open.values()];
+ }
+ if (pendingFrames.size > 0) {
+ left.frames = pendingFrames.size;
+ }
+ if (pendingTimeouts.size > 0) {
+ left.timeouts = pendingTimeouts.size;
+ }
+ expect(left).toEqual({});
+ }
+
+ const settle = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ };
+
+ /** A finger lands, then moves `dx` to the right, from Touch Events. */
+ const fingerDrag = (box: HTMLElement, dx: number, lift: boolean) => {
+ const finger = {id: 1, x: 10, y: 10};
+ pointer('pointerdown', box, {
+ pointerType: 'touch',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ touch('touchstart', box, [finger], [finger], 0);
+ for (let step = 1; step <= 3 && dx > 0; step++) {
+ const moved = {...finger, x: 10 + (dx * step) / 3};
+ pointer('pointermove', box, {
+ pointerType: 'touch',
+ x: moved.x,
+ y: 10,
+ buttons: 1,
+ time: step * 16,
+ });
+ touch('touchmove', box, [moved], [moved], step * 16);
+ }
+ if (lift) {
+ const lifted = {...finger, x: 10 + dx};
+ pointer('pointerup', box, {
+ pointerType: 'touch',
+ x: lifted.x,
+ y: 10,
+ time: 80,
+ });
+ touch('touchend', box, [lifted], [], 80);
+ }
+ };
+
+ it('after a tap from Touch Events under a coarse pointer', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detach = subject.attach(box, new TapGestureRecognizer({name: 'tap'}));
+ fingerDrag(box, 0, true);
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after a claimed pan from Touch Events under a coarse pointer', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
+ fingerDrag(box, 60, true);
+ detach();
+ await settle();
+ // The click guard outlives the host by design: its window still swallows
+ // the click a lift may send (FR21); its own tests cover it.
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after a detach while a claimed finger is still down', async () => {
const {box} = mount('<div id="box"></div>');
- const live = pageListeners();
- const boxRemoved = vi.spyOn(box, 'removeEventListener');
- const fine = fineHost();
- const detach = fine.attach(box, new TapGestureRecognizer());
- detach();
- expect(boxRemoved).toHaveBeenCalledWith(
- 'pointerdown',
- expect.any(Function),
- {capture: true, passive: true},
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
);
- expect(live()).toEqual([]);
+ fingerDrag(box, 60, false);
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
});
- it('gives a coarse primary pointer its page listeners and no element pointerdown', () => {
+ it('after a window blur during a press, under a coarse pointer', async () => {
const {box} = mount('<div id="box"></div>');
- const live = pageListeners();
- const boxAdded = vi.spyOn(box, 'addEventListener');
- const coarse = new GestureHost(document, {
+ const subject = new GestureHost(document, {
clock,
isPrimaryPointerCoarse: () => true,
});
- detachers.push(coarse.attach(box, new TapGestureRecognizer()));
- expect(live()).toEqual(
- expect.arrayContaining(['pointerdown', 'touchstart']),
- );
- expect(
- boxAdded.mock.calls.filter(call => call[0] === 'pointerdown'),
- ).toEqual([]);
+ const detach = subject.attach(box, new TapGestureRecognizer({name: 'tap'}));
+ fingerDrag(box, 0, false);
+ window.dispatchEvent(new Event('blur'));
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
});
-});
-describe("inputMode 'pointer-events'", () => {
- /** A clock whose timers the test fires. */
- class TimerClock {
- time = 0;
- private readonly timers = new Map<number, () => void>();
- private next = 1;
- now(): number {
- return this.time;
- }
- setTimeout(callback: () => void): number {
- const id = this.next++;
- this.timers.set(id, callback);
- return id;
- }
- clearTimeout(id: number): void {
- this.timers.delete(id);
- }
- /** Runs every timer, and the ones they set, at `time`. */
- fireAll(time: number): void {
- this.time = time;
- while (this.timers.size > 0) {
- const due = [...this.timers.values()];
- this.timers.clear();
- for (const callback of due) {
- callback();
- }
- }
+ it('after a mouse drag on a pan under a fine pointer', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
+ pointer('pointerdown', box, {
+ pointerType: 'mouse',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ for (let step = 1; step <= 3; step++) {
+ pointer('pointermove', box, {
+ pointerType: 'mouse',
+ x: 10 + step * 20,
+ y: 10,
+ buttons: 1,
+ time: step * 16,
+ });
}
- }
+ pointer('pointerup', box, {pointerType: 'mouse', x: 70, y: 10, time: 80});
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
- it("tracks a finger once, from its pointer events, so a still finger's long press begins", () => {
+ it('after a mouse tap whose single tap waits on a double tap, detached during the wait', async () => {
const {box} = mount('<div id="box"></div>');
- const timers = new TimerClock();
- const pointerHost = new GestureHost(document, {
- clock: timers,
- inputMode: 'pointer-events',
- isPrimaryPointerCoarse: () => true,
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
});
- const press = new LongPressGestureRecognizer();
- const states: string[] = [];
- press.addListener(r => states.push(r.state));
- detachers.push(pointerHost.attach(box, press));
- // A browser with Touch Events sends both for one finger.
+ const double = new TapGestureRecognizer({
+ name: 'double',
+ numberOfTapsRequired: 2,
+ });
+ const single = new TapGestureRecognizer({name: 'single'}).requireToFail(
+ double,
+ );
+ const detachDouble = subject.attach(box, double);
+ const detachSingle = subject.attach(box, single);
pointer('pointerdown', box, {
- pointerType: 'touch',
+ pointerType: 'mouse',
x: 10,
y: 10,
buttons: 1,
time: 0,
});
- const finger = {id: 7, x: 10, y: 10};
- touch('touchstart', box, [finger], [finger], 0);
- expect(press.numberOfTouches).toBe(1);
- timers.fireAll(800);
- expect(states).toContain('began');
- pointer('pointerup', box, {pointerType: 'touch', x: 10, y: 10, time: 820});
- touch('touchend', box, [finger], [], 820);
- expect(states).toContain('ended');
+ pointer('pointerup', box, {pointerType: 'mouse', x: 10, y: 10, time: 40});
+ detachSingle();
+ detachDouble();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
});
- it("cancels a claimed finger's touchmove, matching its touches to its pointer", () => {
+ it('after a claimed lift from pointer events, detached before its touchend', async () => {
const {box} = mount('<div id="box"></div>');
- const pointerHost = new GestureHost(document, {
+ const subject = new GestureHost(document, {
clock,
inputMode: 'pointer-events',
isPrimaryPointerCoarse: () => true,
});
- const pan = new PanGestureRecognizer({direction: 'horizontal'});
- detachers.push(pointerHost.attach(box, pan));
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
pointer('pointerdown', box, {
pointerType: 'touch',
x: 10,
@@ -2047,22 +5824,6 @@ describe("inputMode 'pointer-events'", () => {
buttons: 1,
time: 0,
});
- const finger = {id: 7, x: 10, y: 10};
- touch('touchstart', box, [finger], [finger], 0);
- // Before the pan claims, the browser keeps the move.
- const early = {...finger, x: 14};
- pointer('pointermove', box, {
- pointerType: 'touch',
- x: 14,
- y: 10,
- buttons: 1,
- time: 8,
- });
- expect(touch('touchmove', box, [early], [early], 8).defaultPrevented).toBe(
- false,
- );
- // Past its hysteresis the pan owns the finger: its touchmoves are cancelled.
- const claimed = {...finger, x: 40};
pointer('pointermove', box, {
pointerType: 'touch',
x: 40,
@@ -2070,25 +5831,123 @@ describe("inputMode 'pointer-events'", () => {
buttons: 1,
time: 32,
});
- expect(pan.state).toBe('began');
- expect(
- touch('touchmove', box, [claimed], [claimed], 32).defaultPrevented,
- ).toBe(true);
+ pointer('pointerup', box, {pointerType: 'touch', x: 40, y: 10, time: 48});
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
});
- it("cancels a claimed finger's touchend, and leaves an unclaimed one's alone", () => {
- const {box, other} = mount('<div id="box"></div><div id="other"></div>');
- const pointerHost = new GestureHost(document, {
+ it('after a long press detached before its time', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
clock,
- inputMode: 'pointer-events',
isPrimaryPointerCoarse: () => true,
});
- const pan = new PanGestureRecognizer({direction: 'horizontal'});
- detachers.push(
- pointerHost.attach(box, pan),
- pointerHost.attach(other, new TapGestureRecognizer()),
+ const detach = subject.attach(
+ box,
+ new LongPressGestureRecognizer({name: 'press'}),
);
- // A pan that claims, then lifts: its touchend is cancelled (FR21).
+ fingerDrag(box, 0, false);
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after a screen-edge pan comes and goes', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detach = subject.attach(
+ box,
+ new ScreenEdgePanGestureRecognizer({name: 'edge', edges: ['leading']}),
+ );
+ detach();
+ await settle();
+ expectNothingLeft(subject);
+ });
+
+ it("after a recognizer detached before its element's author touch-action is read in the next frame", async () => {
+ const {box} = mount('<div id="box" class="author"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
+ detach();
+ await settle();
+ expectNothingLeft(subject);
+ });
+
+ it('after a press tracker that keeps its touch, under a coarse pointer', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detach = subject.attachConsumer(
+ box,
+ createPressTracker({
+ getBounds: () => ({left: 0, top: 0, right: 100, bottom: 100}),
+ keepsTouch: true,
+ onHighlightChange: () => {},
+ }),
+ );
+ fingerDrag(box, 0, true);
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after a window blur during a press, under a fine pointer', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const detach = subject.attach(box, new TapGestureRecognizer({name: 'tap'}));
+ fingerDrag(box, 0, false);
+ window.dispatchEvent(new Event('blur'));
+ await settle();
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after a finger lifts on a touchscreen under a fine pointer', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
+ );
+ fingerDrag(box, 60, true);
+ await settle();
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after a recognized tap from pointer events, detached before its touchend', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ inputMode: 'pointer-events',
+ isPrimaryPointerCoarse: () => true,
+ });
+ const detach = subject.attach(box, new TapGestureRecognizer({name: 'tap'}));
pointer('pointerdown', box, {
pointerType: 'touch',
x: 10,
@@ -2096,41 +5955,65 @@ describe("inputMode 'pointer-events'", () => {
buttons: 1,
time: 0,
});
- const finger = {id: 7, x: 10, y: 10};
- touch('touchstart', box, [finger], [finger], 0);
- pointer('pointermove', box, {
- pointerType: 'touch',
- x: 40,
- y: 10,
- buttons: 1,
- time: 32,
+ pointer('pointerup', box, {pointerType: 'touch', x: 10, y: 10, time: 40});
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after a finger-scroll watch is released', async () => {
+ const {box, list} = mount(
+ '<div id="list" style="overflow-y: auto"><div id="box"></div></div>',
+ );
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
});
- expect(pan.state).toBe('began');
- pointer('pointerup', box, {pointerType: 'touch', x: 40, y: 10, time: 48});
- const lifted = {...finger, x: 40};
- expect(touch('touchend', box, [lifted], [], 48).defaultPrevented).toBe(
- true,
+ const detach = subject.attach(box, new TapGestureRecognizer({name: 'tap'}));
+ const stopWatching = watchFingerScrolls(subject, list);
+ fingerDrag(box, 0, true);
+ stopWatching();
+ detach();
+ await settle();
+ __resetClickGuardForTest();
+ expectNothingLeft(subject);
+ });
+
+ it('after moving content a claiming recognizer lives in stops moving and detaches', async () => {
+ const {sheet, box} = mount('<div id="sheet"><div id="box"></div></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
+ presentedHitTesting: 'always',
+ });
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
);
- // A tap nobody claimed before its lift keeps its touchend.
- pointer('pointerdown', other, {
- id: 2,
- pointerType: 'touch',
- x: 10,
- y: 80,
- buttons: 1,
- time: 400,
+ const stopMoving = registerPresentedOffset(sheet, {
+ offset: () => ({x: 0, y: 100}),
+ resolve: () => {},
});
- const second = {id: 8, x: 10, y: 80};
- touch('touchstart', other, [second], [second], 400);
- pointer('pointerup', other, {
- id: 2,
- pointerType: 'touch',
- x: 10,
- y: 80,
- time: 460,
+ stopMoving();
+ detach();
+ await settle();
+ expectNothingLeft(subject);
+ });
+
+ it('after a scroller a recognizer scrolled itself, detached within its frames', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const subject = new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => true,
});
- expect(touch('touchend', other, [second], [], 460).defaultPrevented).toBe(
- false,
+ const detach = subject.attach(
+ box,
+ new PanGestureRecognizer({direction: 'horizontal'}),
);
+ subject.ownScroll(box);
+ detach();
+ await settle();
+ expectNothingLeft(subject);
});
});
diff --git a/packages/core/src/gestures/__tests__/LongPressGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/LongPressGestureRecognizer.test.ts
index d1c83b9466..e298686d0f 100644
--- a/packages/core/src/gestures/__tests__/LongPressGestureRecognizer.test.ts
+++ b/packages/core/src/gestures/__tests__/LongPressGestureRecognizer.test.ts
@@ -9,7 +9,9 @@
import {describe, expect, it} from 'vitest';
import {UIKIT_GESTURES} from '../../motion/uikit/gestures';
+import type {SelectionLock} from '../GestureRecognizer';
import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';
+import {lockSelection} from '../../utils/selectionLock';
import {createHarness} from './harness';
describe('LongPressGestureRecognizer', () => {
@@ -139,3 +141,27 @@ describe('LongPressGestureRecognizer', () => {
expect(h.log).toContain('press:ended@800');
});
});
+
+describe('LongPressGestureRecognizer selection lock (spec:AST-094 FR41)', () => {
+ it('brings the lock for a hold, none for a touch-down detector at 0 ms, and none when told null', () => {
+ expect(new LongPressGestureRecognizer().selectionLock).toBe(lockSelection);
+ expect(
+ new LongPressGestureRecognizer({minimumPressDuration: 300}).selectionLock,
+ ).toBe(lockSelection);
+ // A 0 ms long press recognizes at touch-down: it has no hold to act on,
+ // so the browser keeps its native long press.
+ expect(
+ new LongPressGestureRecognizer({minimumPressDuration: 0}).selectionLock,
+ ).toBeNull();
+ expect(
+ new LongPressGestureRecognizer({selectionLock: null}).selectionLock,
+ ).toBeNull();
+ const own: SelectionLock = () => () => {};
+ expect(
+ new LongPressGestureRecognizer({
+ minimumPressDuration: 0,
+ selectionLock: own,
+ }).selectionLock,
+ ).toBe(own);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.ts
index 04049b935b..c160b33fa1 100644
--- a/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.ts
+++ b/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.ts
@@ -12,6 +12,58 @@ import {UIKIT_PAN, UIKIT_VELOCITY} from '../../motion/uikit/gestures';
import {PanGestureRecognizer} from '../PanGestureRecognizer';
import {createHarness} from './harness';
+/**
+ * Swipes on a UIPickerView column (iOS 26.2 simulator, HID touches): [ms
+ * since touch-down, y in pt] per event, and the velocity UIKit handed
+ * scrollViewWillEndDragging, in offset px/s (the content moves against the
+ * finger).
+ */
+const PICKER_RELEASES = {
+ '200 pt in 50 ms': {
+ stream: [
+ [0, 368],
+ [46.48, 334.67],
+ [72.92, 201.33],
+ ],
+ release: 933.4,
+ },
+ '200 pt in 100 ms': {
+ stream: [
+ [0, 368],
+ [49.2, 351.33],
+ [65.27, 301.33],
+ [88.47, 251.33],
+ [104.68, 218],
+ [129.4, 168],
+ ],
+ release: 2114,
+ },
+ '200 pt in 200 ms': {
+ stream: [
+ [0, 368],
+ [46.01, 359.67],
+ [63.5, 334.67],
+ [81.36, 318],
+ [97.69, 301.33],
+ [120.12, 276.33],
+ [137.2, 259.67],
+ [171.83, 226.33],
+ [196.13, 201.33],
+ [212.66, 184.67],
+ [230.83, 168],
+ ],
+ release: 1016.2,
+ },
+ 'a 90 pt flick': {
+ stream: [
+ [0, 353],
+ [41.5, 335],
+ [62.02, 281],
+ ],
+ release: 543.6,
+ },
+} as const;
+
describe('PanGestureRecognizer', () => {
it('begins past the hysteresis and leaves the threshold out of the translation', () => {
const h = createHarness();
@@ -97,6 +149,56 @@ describe('PanGestureRecognizer', () => {
expect(release(100 + stillness + 60)).toEqual({x: 0, y: 0});
});
+ it.each(Object.entries(PICKER_RELEASES))(
+ 'releases a scrolling surface as UIScrollView does: %s',
+ (_, {stream, release}) => {
+ const h = createHarness();
+ const pan = new PanGestureRecognizer({
+ name: 'pan',
+ direction: 'vertical',
+ });
+ let scroll = Number.NaN;
+ pan.addListener(r => {
+ if (r.state === 'ended') {
+ scroll = -r.scrollVelocity().y;
+ }
+ });
+ const [first, ...rest] = stream;
+ const finger = h.finger(1).down(100, first[1], first[0], {
+ recognizers: [pan],
+ });
+ for (const [time, y] of rest) {
+ finger.move(100, y, time);
+ }
+ finger.up(rest[rest.length - 1][0]);
+ expect(Math.abs(scroll - release)).toBeLessThan(0.5);
+ },
+ );
+
+ it("reads a dragged surface's release as velocity(in:), not the scroll-view blend", () => {
+ const h = createHarness();
+ const pan = new PanGestureRecognizer({name: 'pan', direction: 'vertical'});
+ let drag = Number.NaN;
+ let scroll = Number.NaN;
+ pan.addListener(r => {
+ if (r.state === 'ended') {
+ drag = -r.velocity().y;
+ scroll = -r.scrollVelocity().y;
+ }
+ });
+ const [first, ...rest] = PICKER_RELEASES['200 pt in 50 ms'].stream;
+ const finger = h.finger(1).down(100, first[1], first[0], {
+ recognizers: [pan],
+ });
+ for (const [time, y] of rest) {
+ finger.move(100, y, time);
+ }
+ finger.up(rest[rest.length - 1][0]);
+ // UIPanGestureRecognizer's velocity(in:) on the same stream.
+ expect(Math.abs(drag - 1582.3)).toBeLessThan(0.5);
+ expect(Math.abs(scroll - 933.4)).toBeLessThan(0.5);
+ });
+
it('fails a drag against its direction', () => {
const vertical = createHarness();
const horizontal = new PanGestureRecognizer({
diff --git a/packages/core/src/gestures/__tests__/PinchGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/PinchGestureRecognizer.test.ts
index bccdf40aca..fe7c334be6 100644
--- a/packages/core/src/gestures/__tests__/PinchGestureRecognizer.test.ts
+++ b/packages/core/src/gestures/__tests__/PinchGestureRecognizer.test.ts
@@ -45,6 +45,32 @@ describe('PinchGestureRecognizer', () => {
expect(pinch.scale).toBeCloseTo(2, 5);
});
+ it('keeps its release velocity when a listener re-bases on every change', () => {
+ const h = createHarness();
+ const pinch = new PinchGestureRecognizer({name: 'pinch'});
+ pinch.addListener(r => {
+ if (r.state === 'changed') {
+ r.scale = 1;
+ }
+ });
+ let released = Number.NaN;
+ pinch.addListener(r => {
+ if (r.state === 'ended') {
+ released = r.velocity;
+ }
+ });
+ h.finger(1).down(100, 100, 0, {recognizers: [pinch]});
+ h.finger(2).down(200, 100, 0, {recognizers: [pinch]});
+ let t = 0;
+ for (let i = 0; i < 10; i++) {
+ t += 16;
+ h.finger(2).move(200 + t * 0.5, 100, t);
+ }
+ // Lift 8 ms after the last move: still spreading, so not 0.
+ h.finger(1).up(t + 8);
+ expect(released).toBeGreaterThan(1);
+ });
+
it('lets the velocity settle when the span holds while the fingers move', () => {
const h = createHarness();
const pinch = new PinchGestureRecognizer({name: 'pinch'});
diff --git a/packages/core/src/gestures/__tests__/PressTracker.test.ts b/packages/core/src/gestures/__tests__/PressTracker.test.ts
index 9a0a558f00..9b09d6276c 100644
--- a/packages/core/src/gestures/__tests__/PressTracker.test.ts
+++ b/packages/core/src/gestures/__tests__/PressTracker.test.ts
@@ -43,6 +43,28 @@ describe('PressTracker', () => {
vi.useRealTimers();
});
+ it('a keepsTouch tracker keeps only the touch whose press it delivered: a quick tap leaves the next touch free until its own press (spec:AST-094 FR19)', () => {
+ const tracker = createPressTracker({
+ getBounds: () => BOUNDS,
+ keepsTouch: true,
+ highlightDelay: 'always',
+ });
+ const h = createHarness();
+ // A tap quicker than the delay: the press shows at the lift, for a flash.
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ expect(tracker.keepsTouch?.(1)).toBe(false);
+ h.finger(1).up(DELAY / 2);
+ expect(tracker.keepsTouch?.(1)).toBe(false);
+ // The next touch is not kept from its first move: its press waits for
+ // the delay, so a scroll that starts on the control is the browser's.
+ h.finger(2).down(150, 120, DELAY, {recognizers: [], consumer: tracker});
+ expect(tracker.keepsTouch?.(2)).toBe(false);
+ vi.advanceTimersByTime(DELAY);
+ expect(tracker.keepsTouch?.(2)).toBe(true);
+ h.finger(2).up(DELAY * 3);
+ expect(tracker.keepsTouch?.(2)).toBe(false);
+ });
+
it('highlights in the same frame outside a scroller and acts on touch up inside', () => {
const {events, highlights, tracker, h} = setup();
h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
@@ -273,3 +295,50 @@ describe('PressTracker in the arena', () => {
expect(double.state).toBe('possible');
});
});
+
+describe('PressTracker under a fine pointer (spec:AST-094 FR11, DEC-21)', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('paints a mouse or a pen press at once, inside a scroller too: the fine profile has no delay', () => {
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ const {events, highlights, tracker, h} = setup();
+ h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: tracker,
+ pointerType,
+ scroll: scrollProbe(() => true),
+ });
+ expect(highlights).toEqual([true]);
+ h.finger(1).up(80);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ }
+ });
+
+ it('brakes only a finger: a mouse press on a scroller a flick set moving still presses', () => {
+ const events: ControlEvent[] = [];
+ const highlights: boolean[] = [];
+ const tracker = createPressTracker({
+ getBounds: () => BOUNDS,
+ onControlEvent: event => events.push(event),
+ onHighlightChange: value => highlights.push(value),
+ isBraking: () => true,
+ });
+ const h = createHarness();
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ h.finger(1).up(80);
+ expect(events).toEqual([]);
+ h.finger(2).down(150, 120, 400, {
+ recognizers: [],
+ consumer: tracker,
+ pointerType: 'mouse',
+ });
+ expect(highlights).toEqual([true]);
+ h.finger(2).up(480);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/SwipeGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/SwipeGestureRecognizer.test.ts
index d195d7d2e2..3cb8572b94 100644
--- a/packages/core/src/gestures/__tests__/SwipeGestureRecognizer.test.ts
+++ b/packages/core/src/gestures/__tests__/SwipeGestureRecognizer.test.ts
@@ -33,6 +33,8 @@ describe('SwipeGestureRecognizer', () => {
slow.advance(500);
expect(a.state).toBe('failed');
+ // Off-axis: still possible while the swipe could be reached (45 along,
+ // 40 across), failed once the drift passes the 50 px across limit.
const diagonal = createHarness();
const b = new SwipeGestureRecognizer({name: 'b'});
diagonal
@@ -65,6 +67,31 @@ describe('SwipeGestureRecognizer', () => {
expect(swipe.recognizedDirection).toBe('up');
});
+ it('gives a 20 degree drag the same answer in small and large steps', () => {
+ for (const step of [4, 9]) {
+ const h = createHarness();
+ const swipe = new SwipeGestureRecognizer({
+ name: 'swipe',
+ direction: 'right',
+ });
+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [swipe]});
+ const angle = (20 * Math.PI) / 180;
+ let travelled = 0;
+ let time = 0;
+ while (swipe.state === 'possible' && travelled < 80) {
+ travelled += step;
+ time += 8;
+ finger.move(
+ travelled * Math.cos(angle),
+ travelled * Math.sin(angle),
+ time,
+ );
+ }
+ expect(swipe.state).toBe('ended');
+ finger.up(time + 8);
+ }
+ });
+
it('gives the same verdict for the same path however its events are spaced', () => {
// A straight drag to (55, 40): along 55 past the 50 px distance, 40 px
// across within the 50 px allowance.
diff --git a/packages/core/src/gestures/__tests__/TapGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/TapGestureRecognizer.test.ts
index 3d1c8fffce..5b731aa83e 100644
--- a/packages/core/src/gestures/__tests__/TapGestureRecognizer.test.ts
+++ b/packages/core/src/gestures/__tests__/TapGestureRecognizer.test.ts
@@ -151,4 +151,25 @@ describe('TapGestureRecognizer', () => {
h.advance(400);
expect(tap.state).toBe('failed');
});
+
+ it('recognizes a two-finger double tap at the same two points', () => {
+ const h = createHarness();
+ const tap = new TapGestureRecognizer({
+ name: 'double2',
+ numberOfTapsRequired: 2,
+ numberOfTouchesRequired: 2,
+ });
+ for (const start of [0, 200]) {
+ const left = h
+ .finger(start + 1)
+ .down(100, 100, start, {recognizers: [tap]});
+ const right = h
+ .finger(start + 2)
+ .down(200, 100, start + 10, {recognizers: [tap]});
+ // The fingers lift one after the other, the right one last.
+ left.up(start + 60);
+ right.up(start + 80);
+ }
+ expect(h.log).toContain('double2:ended@280');
+ });
});
diff --git a/packages/core/src/gestures/__tests__/arena.test.ts b/packages/core/src/gestures/__tests__/arena.test.ts
index 8f3ca4f3c4..d5a724e208 100644
--- a/packages/core/src/gestures/__tests__/arena.test.ts
+++ b/packages/core/src/gestures/__tests__/arena.test.ts
@@ -24,6 +24,7 @@ import {
import type {GestureEventContext, GestureTouch} from '../types';
import {GestureArena, type GestureClock} from '../GestureArena';
import {createHarness, RecordingConsumer} from './harness';
+import {internals} from '../recognizerInternals';
type Step = (recognizer: Scripted, event: GestureEventContext) => void;
@@ -181,7 +182,7 @@ describe('arena: who wins', () => {
h.finger(1).down(0, 0, 0, {recognizers: [single, double]});
h.finger(1).up(50);
expect(single.state).toBe('possible');
- expect(single.pending).toBe('ended');
+ expect(internals(single).pending).toBe('ended');
h.advance(400);
expect(h.log).toEqual([
'double:failed@400',
@@ -220,7 +221,7 @@ describe('arena: who wins', () => {
});
h.finger(1).down(0, 0, 0, {recognizers: [single, double]});
h.finger(1).up(50);
- expect(single.pending).toBe('ended');
+ expect(internals(single).pending).toBe('ended');
});
it('honors shouldBegin and shouldReceiveTouch', () => {
diff --git a/packages/core/src/gestures/__tests__/arenaTapLongPress.test.ts b/packages/core/src/gestures/__tests__/arenaTapLongPress.test.ts
index 91bd0b5403..24267edb00 100644
--- a/packages/core/src/gestures/__tests__/arenaTapLongPress.test.ts
+++ b/packages/core/src/gestures/__tests__/arenaTapLongPress.test.ts
@@ -16,6 +16,7 @@ import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';
import {TapGestureRecognizer} from '../TapGestureRecognizer';
import {UIKIT_GESTURES} from '../../motion/uikit/gestures';
import {createHarness, RecordingConsumer} from './harness';
+import {internals} from '../recognizerInternals';
const INTERVAL = UIKIT_GESTURES.tap.maximumIntervalBetweenTaps.value;
@@ -31,7 +32,7 @@ describe('conflict matrix', () => {
h.finger(1).down(0, 0, 0, {recognizers: [single, double]});
h.finger(1).up(80);
expect(single.state).toBe('possible');
- expect(single.pending).toBe('ended');
+ expect(internals(single).pending).toBe('ended');
h.advance(80 + INTERVAL);
expect(h.log).toEqual([
`double:failed@${80 + INTERVAL}`,
@@ -41,6 +42,31 @@ describe('conflict matrix', () => {
]);
});
+ it('a requirement stopped inside deferResolution leaves the recognition waiting on it to a pass a microtask later', async () => {
+ const h = createHarness();
+ const single = new TapGestureRecognizer({name: 'single'});
+ const double = new TapGestureRecognizer({
+ name: 'double',
+ numberOfTapsRequired: 2,
+ });
+ single.requireToFail(double);
+ h.finger(1).down(0, 0, 0, {recognizers: [single, double]});
+ h.finger(1).up(80);
+ // Code outside input (a React Effect) turns the double tap off: it fails
+ // at once, at the last event's time, and the single tap waiting on it
+ // resolves only in the next pass.
+ h.arena.deferResolution(() => double.setEnabled(false));
+ expect(h.log).toEqual(['double:failed@80']);
+ expect(internals(single).pending).toBe('ended');
+ await Promise.resolve();
+ expect(h.log).toEqual([
+ 'double:failed@80',
+ 'single:ended@80',
+ 'single:possible@80',
+ 'double:possible@80',
+ ]);
+ });
+
it('tap vs double tap, single requires double to fail: a double tap fails the single', () => {
const h = createHarness();
const single = new TapGestureRecognizer({name: 'single'});
@@ -95,7 +121,7 @@ describe('conflict matrix', () => {
});
h.finger(1).down(0, 0, 0, {recognizers: [single, double]});
h.finger(1).up(50);
- expect(single.pending).toBe('ended');
+ expect(internals(single).pending).toBe('ended');
});
});
diff --git a/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts
new file mode 100644
index 0000000000..e2aaeaa925
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts
@@ -0,0 +1,146 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file arenaTimersAndClaims.test.ts
+ * @input Uses vitest, GestureArena, the tap, long-press and pan recognizers
+ * @output Checks a late timer against queued input, cancelling an idle
+ * recognizer, and the claim a waiting recognition takes
+ * @position Test for packages/core/src/gestures/GestureArena.ts
+ */
+
+import {describe, expect, it} from 'vitest';
+import {GestureArena, type GestureClock} from '../GestureArena';
+import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {createHarness} from './harness';
+
+/** A clock whose timers run one task at a time, as an event loop does. */
+class TaskClock implements GestureClock {
+ time = 0;
+ private nextId = 1;
+ private readonly tasks = new Map<number, {at: number; run: () => void}>();
+ now(): number {
+ return this.time;
+ }
+ setTimeout(run: () => void, delay: number): number {
+ const id = this.nextId++;
+ this.tasks.set(id, {at: this.time + delay, run});
+ return id;
+ }
+ clearTimeout(id: number): void {
+ this.tasks.delete(id);
+ }
+ /** Run the earliest task due by `time`, if any. */
+ runTask(time: number): void {
+ this.time = time;
+ const due = [...this.tasks.entries()]
+ .filter(([, task]) => task.at <= time)
+ .sort((a, b) => a[1].at - b[1].at)[0];
+ if (due != null) {
+ this.tasks.delete(due[0]);
+ due[1].run();
+ }
+ }
+}
+
+function pressArena(): {
+ clock: TaskClock;
+ arena: GestureArena;
+ press: LongPressGestureRecognizer;
+ log: string[];
+} {
+ const clock = new TaskClock();
+ const log: string[] = [];
+ const arena: GestureArena = new GestureArena({
+ clock,
+ onTransition: (recognizer, _from, to) =>
+ log.push(`${recognizer.name}:${to}@${arena.now()}`),
+ });
+ const press = new LongPressGestureRecognizer({name: 'press'});
+ arena.began([
+ {
+ id: 1,
+ x: 0,
+ y: 0,
+ time: 0,
+ pointerType: 'touch',
+ target: null,
+ scroll: null,
+ recognizers: [press],
+ consumer: null,
+ },
+ ]);
+ return {clock, arena, press, log};
+}
+
+describe('a timer that fires late', () => {
+ it('lets a lift queued before its deadline run first', () => {
+ const {clock, arena, log} = pressArena();
+ // A long task held the main thread from 100 to 800 ms; the finger
+ // lifted at 300. The timer task runs first, then the queued lift.
+ clock.runTask(800);
+ arena.ended([{id: 1, x: 0, y: 0, time: 300}]);
+ clock.runTask(800);
+ expect(log.some(entry => entry.startsWith('press:began'))).toBe(false);
+ });
+
+ it('keeps the timestamps of queued moves', () => {
+ const {clock, arena, log} = pressArena();
+ clock.runTask(800);
+ // The finger travelled 40 px at 300 ms: past the allowable movement.
+ arena.moved([{id: 1, x: 40, y: 0, time: 300}]);
+ clock.runTask(800);
+ expect(log.some(entry => entry.startsWith('press:began'))).toBe(false);
+ expect(log).toContain('press:failed@300');
+ arena.ended([{id: 1, x: 40, y: 0, time: 820}]);
+ });
+
+ it('still fires on its deadline when nothing was queued', () => {
+ const {clock, arena, log} = pressArena();
+ clock.runTask(800);
+ clock.runTask(800);
+ expect(log).toContain('press:began@500');
+ arena.ended([{id: 1, x: 0, y: 0, time: 820}]);
+ });
+});
+
+describe('cancelling an idle recognizer', () => {
+ it('leaves it possible, so its next touch counts', () => {
+ const h = createHarness();
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ // Never touched.
+ tap.cancel();
+ expect(tap.state).toBe('possible');
+ h.finger(1)
+ .down(10, 10, 0, {recognizers: [tap]})
+ .up(50);
+ expect(h.log).toContain('tap:ended@50');
+ // Touched before, idle now.
+ tap.cancel();
+ expect(tap.state).toBe('possible');
+ h.finger(2)
+ .down(10, 10, 1000, {recognizers: [tap]})
+ .up(1050);
+ expect(h.log).toContain('tap:ended@1050');
+ });
+});
+
+describe('a waiting recognition that fails', () => {
+ it('gives its claimed touches back', () => {
+ const h = createHarness();
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ pan.requireToFail(tap);
+ const finger = h
+ .finger(1)
+ .down(0, 0, 0, {recognizers: [pan, tap]})
+ .move(20, 0, 16);
+ // The pan recognized but waits for the tap to fail, holding the touch.
+ expect(h.arena.isClaimed(1)).toBe(true);
+ pan.setEnabled(false);
+ expect(pan.state).toBe('failed');
+ expect(h.arena.isClaimed(1)).toBe(false);
+ finger.up(40);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/browser/bareFixture.ts b/packages/core/src/gestures/__tests__/browser/bareFixture.ts
new file mode 100644
index 0000000000..ed73146690
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/browser/bareFixture.ts
@@ -0,0 +1,98 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file bareFixture.ts
+ * @input Nothing: bundled by esbuild and injected into a blank page
+ * @output A page with nothing attached: the document's gesture host and the
+ * recognizers (pan, screen-edge pan, tap, long press) on `window.__api`, for a test to attach what it needs, and
+ * `window.__pageTouch`, the count of touch listeners on the window and the
+ * document right now
+ * @position Browser fixture of gestures.interaction.browser.spec.ts for the
+ * checks that need a page with no other gesture on it (FR19, FR24);
+ * test-only
+ */
+
+import {getGestureHost} from '../../GestureHost';
+import {LongPressGestureRecognizer} from '../../LongPressGestureRecognizer';
+import {PanGestureRecognizer} from '../../PanGestureRecognizer';
+import {ScreenEdgePanGestureRecognizer} from '../../ScreenEdgePanGestureRecognizer';
+import {lockSelection} from '../../../utils/selectionLock';
+import {TapGestureRecognizer} from '../../TapGestureRecognizer';
+
+declare global {
+ interface Window {
+ __pageTouch: number;
+ __api: {
+ host: ReturnType<typeof getGestureHost>;
+ LongPressGestureRecognizer: typeof LongPressGestureRecognizer;
+ PanGestureRecognizer: typeof PanGestureRecognizer;
+ ScreenEdgePanGestureRecognizer: typeof ScreenEdgePanGestureRecognizer;
+ TapGestureRecognizer: typeof TapGestureRecognizer;
+ lockSelection: typeof lockSelection;
+ };
+ }
+}
+
+// The touch listeners on the window and the document, as the engine sees
+// them: what makes the page pay for touches.
+window.__pageTouch = 0;
+const live = new Set<string>();
+const listenerIds = new WeakMap<object, number>();
+let nextListenerId = 1;
+function keyOf(
+ target: EventTarget,
+ type: string,
+ listener: EventListenerOrEventListenerObject,
+ options?: boolean | EventListenerOptions,
+): string {
+ let id = listenerIds.get(listener);
+ if (id == null) {
+ id = nextListenerId++;
+ listenerIds.set(listener, id);
+ }
+ const capture =
+ typeof options === 'boolean' ? options : (options?.capture ?? false);
+ return [target === window ? 'window' : 'document', type, capture, id].join();
+}
+// Playwright's own hit-target interceptors listen on the window too; they
+// are the harness's, not the page's.
+const isPageTouch = (target: EventTarget, type: string) =>
+ (target === window || target === document) &&
+ type.startsWith('touch') &&
+ !(new Error().stack ?? '').includes('InjectedScript');
+const addListener = EventTarget.prototype.addEventListener;
+const removeListener = EventTarget.prototype.removeEventListener;
+EventTarget.prototype.addEventListener = function (
+ this: EventTarget,
+ type: string,
+ listener: EventListenerOrEventListenerObject | null,
+ options?: boolean | AddEventListenerOptions,
+) {
+ if (listener != null && isPageTouch(this, type)) {
+ live.add(keyOf(this, type, listener, options));
+ window.__pageTouch = live.size;
+ }
+ addListener.call(this, type, listener, options);
+};
+EventTarget.prototype.removeEventListener = function (
+ this: EventTarget,
+ type: string,
+ listener: EventListenerOrEventListenerObject | null,
+ options?: boolean | EventListenerOptions,
+) {
+ if (listener != null && isPageTouch(this, type)) {
+ live.delete(keyOf(this, type, listener, options));
+ window.__pageTouch = live.size;
+ }
+ removeListener.call(this, type, listener, options);
+};
+
+document.body.style.margin = '0';
+window.__api = {
+ host: getGestureHost(document),
+ LongPressGestureRecognizer,
+ PanGestureRecognizer,
+ ScreenEdgePanGestureRecognizer,
+ TapGestureRecognizer,
+ lockSelection,
+};
diff --git a/packages/core/src/gestures/__tests__/browser/fixture.ts b/packages/core/src/gestures/__tests__/browser/fixture.ts
index 9cd162bc56..b10c5beddd 100644
--- a/packages/core/src/gestures/__tests__/browser/fixture.ts
+++ b/packages/core/src/gestures/__tests__/browser/fixture.ts
@@ -18,9 +18,13 @@ import {getGestureHost} from '../../GestureHost';
import type {GestureRecognizer} from '../../GestureRecognizer';
import {LongPressGestureRecognizer} from '../../LongPressGestureRecognizer';
import {PanGestureRecognizer} from '../../PanGestureRecognizer';
+import {lockSelection} from '../../../utils/selectionLock';
import {PinchGestureRecognizer} from '../../PinchGestureRecognizer';
import {ScreenEdgePanGestureRecognizer} from '../../ScreenEdgePanGestureRecognizer';
+import {createPressTracker} from '../../PressTracker';
+import {holdPageScroll} from '../../pageHold';
import {TapGestureRecognizer} from '../../TapGestureRecognizer';
+import {internals} from '../../recognizerInternals';
interface Entry {
name: string;
@@ -47,6 +51,13 @@ declare global {
__pageListeners: Map<string, number>;
/** The page-level listener types the attachments below added. */
__attachListeners: string[];
+ /** Every touch listener added to the document or the window, by type. */
+ __pageTouchListeners: string[];
+ /**
+ * The same, as the page left them once loaded: the test driver adds its
+ * own window listeners when it first runs a script.
+ */
+ __pageTouchListenersAtLoad: string[];
}
}
@@ -60,6 +71,7 @@ window.__listeners = [];
window.__pageListeners = new Map();
const isPage = (target: EventTarget) =>
target === document || target === window;
+window.__pageTouchListeners = [];
const addListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (
this: EventTarget,
@@ -67,6 +79,9 @@ EventTarget.prototype.addEventListener = function (
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions,
) {
+ if ((this === document || this === window) && type.startsWith('touch')) {
+ window.__pageTouchListeners.push(type);
+ }
if (this instanceof Element && this.id !== '' && type.startsWith('touch')) {
window.__listeners.push({
id: this.id,
@@ -116,6 +131,9 @@ document.body.innerHTML = `
<div style="height: 1200px">sheet content</div>
</div>
<div id="passive" style="height: 60px; background: #dfd; touch-action: pan-y pinch-zoom">passive control</div>
+ <div id="slider" style="height: 60px; background: #fdf">slider: a pan that turns selection off</div>
+ <div id="checkRow" style="height: 60px; background: #eef">checkbox row <input id="check" type="checkbox" style="width: 40px; height: 40px"></div>
+ <div id="switchRow" style="height: 60px; background: #efe">switch: a drag that turns selection off <input id="switchInput" type="checkbox" style="width: 40px; height: 40px"></div>
<div id="card" style="height: 80px; background: #def">card (swipe up)</div>
<style>
.author-none { touch-action: none; }
@@ -138,6 +156,13 @@ document.body.innerHTML = `
<div style="width: 800px; height: 100px">wider than the band</div>
</div>
</div>
+ <div id="onePan" style="height: 160px; background: #dde">one-finger pan</div>
+ <div id="kept" style="height: 80px; background: #ede">kept press (a stepper's hold)</div>
+ <div id="plainArea" style="height: 160px; background: #eed">plain area</div>
+ <div id="feed" style="height: 240px; overflow-y: auto; overscroll-behavior: contain; background: #efe">
+ <div id="feedRow" style="height: 80px; background: #cfc">feed row (tap)</div>
+ <div style="height: 1200px">feed content</div>
+ </div>
<div style="height: 1600px">page</div>
<div id="passiveEnd" style="height: 60px; background: #dfd; touch-action: pan-y pinch-zoom">passive control at the page's end</div>
</div>`;
@@ -150,6 +175,24 @@ function element(id: string): HTMLElement {
return found;
}
+// Which browser signal arrives, in order with the presses it ends: on the
+// window's capture phase, added before the host exists so it runs ahead of
+// the host's own page-wide listeners there.
+addListener.call(
+ window,
+ 'pointercancel',
+ event => {
+ if ((event as PointerEvent).pointerType === 'touch') {
+ window.__gestures.push({
+ name: 'dom:pointercancel',
+ state: 'dom',
+ time: performance.now(),
+ });
+ }
+ },
+ true,
+);
+
const beforeAttach = new Map(window.__pageListeners);
const host = getGestureHost(document);
@@ -158,7 +201,7 @@ function record(recognizer: GestureRecognizer, extra: () => Partial<Entry>) {
window.__gestures.push({
name: current.name,
state: to,
- time: current.arena?.now() ?? performance.now(),
+ time: internals(current).arena?.now() ?? performance.now(),
...(to === 'possible' || to === 'failed' ? {} : extra()),
});
});
@@ -172,6 +215,12 @@ const tap = new TapGestureRecognizer({name: 'tap'});
record(tap, () => ({}));
host.attach(element('tapper'), tap);
+// A row in a scroller: a scroll the page makes under a still finger keeps
+// its tap; a drag that scrolls the feed takes it.
+const feedTap = new TapGestureRecognizer({name: 'feedTap'});
+record(feedTap, () => ({}));
+host.attach(element('feedRow'), feedTap);
+
const press = new LongPressGestureRecognizer({name: 'press'});
record(press, () => ({
beganAt: press.beganAt,
@@ -236,6 +285,31 @@ for (const id of ['edgeZone', 'edgeWide', 'edgeZoneRtl', 'edgeWideRtl']) {
// press consumer, under pan-y, as a passive switch is.
const passiveEvent = (state: string) =>
window.__gestures.push({name: 'passive', state, time: performance.now()});
+host.attach(
+ element('slider'),
+ new PanGestureRecognizer({
+ name: 'slider',
+ direction: 'horizontal',
+ selectionLock: lockSelection,
+ }),
+);
+
+host.attach(
+ element('switchRow'),
+ new PanGestureRecognizer({
+ name: 'switchRow',
+ direction: 'horizontal',
+ selectionLock: lockSelection,
+ }),
+);
+
+host.attachConsumer(element('checkRow'), {
+ touchBegan: () => {},
+ touchMoved: () => {},
+ touchEnded: () => {},
+ touchCancelled: () => {},
+});
+
host.attachConsumer(element('passive'), {
touchBegan: () => passiveEvent('began'),
touchMoved: () => passiveEvent('moved'),
@@ -254,23 +328,37 @@ host.attachConsumer(element('passiveEnd'), {
touchEnded: () => passiveEndEvent('ended'),
touchCancelled: () => passiveEndEvent('cancelled'),
});
-// Which browser signal arrives, in order with the presses it ends: on the
-// window, whose capture listeners run before the host's on the document.
-addListener.call(
- window,
- 'pointercancel',
- event => {
- if ((event as PointerEvent).pointerType === 'touch') {
- window.__gestures.push({
- name: 'dom:pointercancel',
- state: 'dom',
- time: performance.now(),
- });
- }
- },
- true,
+
+// A one-finger pan: a second finger before any claim fails it.
+const onePan = new PanGestureRecognizer({
+ name: 'onePan',
+ maximumNumberOfTouches: 1,
+});
+record(onePan, () => ({
+ x: onePan.translation().x,
+ y: onePan.translation().y,
+}));
+host.attach(element('onePan'), onePan);
+
+// A control that keeps its press through a drag, as a stepper's hold does.
+const keptEvent = (state: string) =>
+ window.__gestures.push({name: 'kept', state, time: performance.now()});
+host.attachConsumer(
+ element('kept'),
+ createPressTracker({
+ getBounds: () => element('kept').getBoundingClientRect(),
+ keepsTouch: true,
+ onControlEvent: event => keptEvent(event),
+ onHighlightChange: isHighlighted =>
+ keptEvent(isHighlighted ? 'highlight' : 'unhighlight'),
+ }),
);
+// A scroll lock's page hold, held on demand: every one-finger pan would
+// scroll the page.
+(window as unknown as {__holdPage: () => () => void}).__holdPage = () =>
+ holdPageScroll(document, () => true);
+
// The fixture's own loggers go around the count of page listeners.
// A press consumer inside the scroller, as a list row is: a scroll of the
// scroller takes its press only once the finger has moved the take distance
@@ -305,3 +393,4 @@ window.__attachListeners = [...window.__pageListeners]
.filter(([type, count]) => count > (beforeAttach.get(type) ?? 0))
.map(([type]) => type)
.sort();
+window.__pageTouchListenersAtLoad = [...window.__pageTouchListeners];
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 3828f751f8..85340e6ebc 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
@@ -9,8 +9,11 @@
* touch-action per element, touchmove cancelled exactly while a recognizer
* owns the finger, native scrolling untouched otherwise, click suppression
* with no ghost click, a drag that began as a scroll staying the browser's, pinch-zoom
- * left to the browser, a second finger that never breaks the first, and
- * timing taken from event timestamps under a blocked main thread
+ * left to the browser, a second finger that never breaks the first,
+ * timing taken from event timestamps under a blocked main thread, gestures
+ * for every pointer with nothing listening while idle where the primary
+ * pointer is fine, nothing for a disabled recognizer,
+ * and a held finger's selection lock only where the hold takes the touch
* @position Browser tests of packages/core/src/gestures, run by
* `pnpm test:interaction` (playwright.interaction.config.ts, a phone in
* Chromium and WebKit) and in CI's interaction proofs. WebKit's Linux build
@@ -36,19 +39,26 @@ interface Entry {
}
let bundle = '';
+let bareBundle = '';
test.beforeAll(async () => {
- const result = await build({
- entryPoints: [
- path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixture.ts'),
- ],
- bundle: true,
- write: false,
- format: 'iife',
- platform: 'browser',
- target: 'es2022',
- });
- bundle = result.outputFiles[0].text;
+ const bundleOf = async (file: string) => {
+ const result = await build({
+ entryPoints: [
+ path.join(path.dirname(fileURLToPath(import.meta.url)), file),
+ ],
+ bundle: true,
+ write: false,
+ format: 'iife',
+ platform: 'browser',
+ target: 'es2022',
+ // A development build, as an app's bundler would make one.
+ define: {'process.env.NODE_ENV': '"development"'},
+ });
+ return result.outputFiles[0].text;
+ };
+ bundle = await bundleOf('fixture.ts');
+ bareBundle = await bundleOf('bareFixture.ts');
});
type Point = {x: number; y: number};
@@ -238,6 +248,51 @@ async function open(page: Page, engine: string): Promise<Driver> {
return engine === 'webkit' ? webkitDriver(page) : chromiumDriver(page);
}
+/** A page with nothing attached: the test attaches through `window.__api`. */
+async function openBare(page: Page, engine: string): Promise<Driver> {
+ 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});
+ return engine === 'webkit' ? webkitDriver(page) : chromiumDriver(page);
+}
+
+/**
+ * The touch-action the host gives an element (its mark, or an inline value
+ * it wrote) and the page's touch listeners, read after the next frame: the
+ * host reads an author's value there (FR18), so an absent value is absent
+ * for good, not merely not yet written.
+ */
+async function footprint(page: Page, id: string) {
+ return page.evaluate(async target => {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ });
+ const element = document.getElementById(target);
+ return {
+ touchAction:
+ element?.getAttribute('data-astryx-touch-action') ??
+ element?.style.getPropertyValue('touch-action') ??
+ null,
+ pageTouchListeners: window.__pageTouch,
+ };
+ }, id);
+}
+
+/**
+ * Whether a selection starting on an element now is refused: where iOS
+ * WebKit does not run, the selection lock cancels `selectstart` and writes
+ * no style (`spec:AST-094` FR41).
+ */
+async function refusesSelection(page: Page, id: string): Promise<boolean> {
+ return page.evaluate(target => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ (document.getElementById(target) ?? document.body).dispatchEvent(event);
+ return event.defaultPrevented;
+ }, id);
+}
+
async function center(page: Page, id: string): Promise<Point> {
const box = await page.locator(`#${id}`).boundingBox();
if (box == null) {
@@ -294,6 +349,14 @@ test('derives touch-action per element from its recognizers', async ({
browserName,
}) => {
await open(page, browserName);
+ // The host reads each author's value and writes its own in the frame
+ // after the attach (FR18).
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ }),
+ );
const actions = await page.evaluate(() =>
Object.fromEntries(
['hpan', 'tapper', 'presser', 'pinchable', 'sheetBody'].map(id => [
@@ -322,16 +385,21 @@ test('only elements whose recognizers claim a moving touch carry a blocking touc
.filter(entry => entry.type === 'touchmove' && entry.passive === false)
.map(entry => entry.id),
);
- // Pans (the cards' and the screen-edge pans' too), long presses, a pinch
- // and the sheet's pan can take a moving touch; a tap-only element and a
- // press consumer never wait.
+ // Pans (the cards', the screen-edge pans', the switch's drag and a
+ // one-finger pan too), a long press, a pinch, the sheet's pan and a press
+ // that keeps its touch can take a moving touch; a tap-only element and a
+ // plain press consumer never wait.
expect(new Set(blocking)).toEqual(
new Set([
'hpan',
'presser',
'pinchable',
'sheetBody',
+ 'slider',
+ 'switchRow',
'card',
+ 'onePan',
+ 'kept',
'authorNone',
'authorPanY',
'authorPinchZoom',
@@ -496,6 +564,464 @@ test('a one-way overlay pan keeps its direction from the page, and leaves the ot
expect(states(await log(page), 'card')).toEqual(['failed', 'possible']);
});
+test('a held finger turns text selection off only where the hold does something (a pan that asks), until it lifts; a press-tracked control, a mouse and other pans keep native selection (spec:AST-094 FR41)', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ const held: Record<string, boolean[]> = {};
+ for (const id of ['passive', 'slider', 'hpan']) {
+ await page.locator(`#${id}`).scrollIntoViewIfNeeded();
+ const at = await center(page, id);
+ const before = await refusesSelection(page, id);
+ await driver.play([{t: 0, down: [{id: 1, ...at}]}]);
+ const during = await refusesSelection(page, id);
+ await driver.play([{t: 0, down: []}]);
+ held[id] = [before, during, await refusesSelection(page, id)];
+ }
+ // A control whose hold does nothing keeps the browser's long-press
+ // selection.
+ expect(held.passive).toEqual([false, false, false]);
+ expect(held.slider).toEqual([false, true, false]);
+ expect(held.hpan).toEqual([false, false, false]);
+
+ const at = await center(page, 'passive');
+ await page.mouse.move(at.x, at.y);
+ await page.mouse.down();
+ const withMouse = await refusesSelection(page, 'passive');
+ await page.mouse.up();
+ expect(withMouse).toBe(false);
+});
+
+test('a held finger on a checkbox inside an element whose hold does something turns its selection off too, as WebKit makes every input selectable; inside a press-tracked row it stays native (spec:AST-094 FR41)', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ const heldSelection = async (id: string) => {
+ await page.locator(`#${id}`).scrollIntoViewIfNeeded();
+ const at = await center(page, id);
+ const before = await refusesSelection(page, id);
+ await driver.play([{t: 0, down: [{id: 1, ...at}]}]);
+ const during = await refusesSelection(page, id);
+ await driver.play([{t: 0, down: []}]);
+ return [before, during, await refusesSelection(page, id)];
+ };
+ expect(await heldSelection('switchInput')).toEqual([false, true, false]);
+ expect(await heldSelection('check')).toEqual([false, false, false]);
+});
+
+test('a scroll the page makes under a still finger keeps the touch and its tap', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ await page.locator('#feed').scrollIntoViewIfNeeded();
+ const at = await center(page, 'feedRow');
+ await clearLog(page);
+ await driver.play([{t: 0, down: [{id: 1, ...at}]}]);
+ // The page scrolls the feed under the resting finger (scrollIntoView, a
+ // pinned transcript): the finger never travelled, so the touch stays.
+ await page.evaluate(() => {
+ const feed = document.getElementById('feed');
+ if (feed != null) {
+ feed.scrollTop += 6;
+ }
+ });
+ await page.evaluate(async () => {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ });
+ });
+ await driver.play([{t: 0, down: []}]);
+ expect(states(await log(page), 'feedTap')).toEqual(['ended', 'possible']);
+});
+
+test('a drag that scrolls the feed natively is the browser’s: no tap', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName === 'webkit',
+ 'needs native scrolling from injected touches (Mobile Safari on the simulator)',
+ );
+ const driver = await open(page, browserName);
+ await page.locator('#feed').scrollIntoViewIfNeeded();
+ await page.evaluate(() => {
+ const feed = document.getElementById('feed');
+ if (feed != null) {
+ feed.scrollTop = 0;
+ }
+ });
+ const start = await center(page, 'feedRow');
+ await clearLog(page);
+ await driver.play(drag(start, {x: start.x, y: start.y - 60}, 30));
+ const scrolled = await page.evaluate(
+ () => document.getElementById('feed')?.scrollTop ?? 0,
+ );
+ expect(scrolled).toBeGreaterThan(20);
+ expect(states(await log(page), 'feedTap')).not.toContain('ended');
+});
+
+test('a second finger before any claim fails a one-finger pan and leaves the pinch to the page', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ await page.locator('#onePan').scrollIntoViewIfNeeded();
+ const at = await center(page, 'onePan');
+ await clearLog(page);
+ await logTouchMoves(page);
+ const pair = (spread: number) => [
+ {id: 1, x: at.x - spread, y: at.y},
+ {id: 2, x: at.x + spread, y: at.y},
+ ];
+ await driver.play([
+ {t: 0, down: [{id: 1, x: at.x - 10, y: at.y}]},
+ {t: 30, down: pair(10)},
+ {t: 60, down: pair(30)},
+ {t: 90, down: pair(50)},
+ {t: 120, down: pair(70)},
+ {t: 150, down: []},
+ ]);
+ const pan = states(await log(page), 'onePan');
+ expect(pan).toContain('failed');
+ expect(pan).not.toContain('began');
+ // No move of the pinch is cancelled: the page may zoom.
+ const moves = await readTouchMoves(page);
+ expect(moves.length).toBeGreaterThan(0);
+ expect(moves.some(Boolean)).toBe(false);
+});
+
+test('a page hold keeps the page still under a one-finger pan, and leaves a pinch alone', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ await page.locator('#plainArea').scrollIntoViewIfNeeded();
+ await page.evaluate(() => {
+ const own = window as unknown as {
+ __holdPage: () => () => void;
+ __releaseHold: () => void;
+ };
+ own.__releaseHold = own.__holdPage();
+ });
+ await logTouchMoves(page);
+ const start = await center(page, 'plainArea');
+ const before = await page.evaluate(() => window.scrollY);
+ await driver.play(drag(start, {x: start.x, y: start.y - 80}, 30));
+ expect((await readTouchMoves(page)).some(Boolean)).toBe(true);
+ expect(await page.evaluate(() => window.scrollY)).toBe(before);
+ // A second finger is a pinch: never cancelled.
+ await logTouchMoves(page);
+ await driver.play([
+ {
+ t: 0,
+ down: [
+ {id: 1, x: start.x - 10, y: start.y},
+ {id: 2, x: start.x + 10, y: start.y},
+ ],
+ },
+ {
+ t: 30,
+ down: [
+ {id: 1, x: start.x - 40, y: start.y},
+ {id: 2, x: start.x + 40, y: start.y},
+ ],
+ },
+ {t: 60, down: []},
+ ]);
+ expect((await readTouchMoves(page)).some(Boolean)).toBe(false);
+ await page.evaluate(() =>
+ (window as unknown as {__releaseHold: () => void}).__releaseHold(),
+ );
+});
+
+test('a control that keeps its press through a drag holds the page still and stays pressed', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ await page.locator('#kept').scrollIntoViewIfNeeded();
+ await clearLog(page);
+ const start = await center(page, 'kept');
+ const before = await page.evaluate(() => window.scrollY);
+ // The finger rests until the press is delivered: a control in a scroller
+ // waits before it highlights, and a drag that starts sooner is a scroll.
+ await driver.play([{t: 0, down: [{id: 1, ...start}]}]);
+ await page.waitForFunction(() =>
+ window.__gestures.some(
+ entry => entry.name === 'kept' && entry.state === 'highlight',
+ ),
+ );
+ await logTouchMoves(page);
+ await driver.play(drag(start, {x: start.x, y: start.y - 40}, 20, false));
+ let kept = states(await log(page), 'kept');
+ expect(kept).toContain('touchDown');
+ expect(kept).not.toContain('touchCancel');
+ expect(kept).not.toContain('unhighlight');
+ // Its press was delivered, so every move is cancelled: the page stays.
+ const moves = await readTouchMoves(page);
+ expect(moves.length).toBeGreaterThan(0);
+ expect(moves.every(Boolean)).toBe(true);
+ expect(await page.evaluate(() => window.scrollY)).toBe(before);
+ await driver.play([{t: 0, down: []}]);
+ kept = states(await log(page), 'kept');
+ expect(kept).toContain('touchUpInside');
+ expect(kept).not.toContain('touchCancel');
+});
+
+test('where the primary pointer is fine, the host still writes touch-action, leaves the page no listener while idle, and pans with a mouse (spec:AST-094 FR43, FR24)', async ({
+ browser,
+}) => {
+ // A desktop: a mouse is the primary pointer.
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 800},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ await page.goto('about:blank');
+ await page.setContent('<!doctype html><body></body>');
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, LongPressGestureRecognizer, PanGestureRecognizer} =
+ window.__api;
+ document.body.innerHTML =
+ '<div id="drag" style="height: 80px">drag</div><div id="hold" style="height: 80px">hold</div>';
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ (window as unknown as {__panStates: string[]}).__panStates = states;
+ pan.addTransitionListener((_current, _from, to) => states.push(to));
+ host.attach(document.getElementById('drag') as HTMLElement, pan);
+ host.attach(
+ document.getElementById('hold') as HTMLElement,
+ new LongPressGestureRecognizer(),
+ );
+ });
+ // A touchscreen laptop's finger needs the same touch-action as a phone's.
+ expect(await footprint(page, 'drag')).toEqual({
+ touchAction: 'pan-y pinch-zoom',
+ pageTouchListeners: 0,
+ });
+ expect((await footprint(page, 'hold')).touchAction).toBe('manipulation');
+ // A real mouse drag pans; the page's listeners last only the press.
+ const box = await page.locator('#drag').boundingBox();
+ if (box == null) {
+ throw new Error('no box for #drag');
+ }
+ const y = box.y + box.height / 2;
+ await page.mouse.move(box.x + 20, y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 100, y, {steps: 8});
+ await page.mouse.up();
+ const states = await page.evaluate(
+ () => (window as unknown as {__panStates: string[]}).__panStates,
+ );
+ expect(states[0]).toBe('began');
+ expect(states).toContain('ended');
+ expect((await footprint(page, 'drag')).pageTouchListeners).toBe(0);
+ } finally {
+ await context.close();
+ }
+});
+
+test("the host's touch-action applies from the attach itself, an author rule outranks it from the first frame, and a shadow root gets it too (spec:AST-094 FR18, DEC-8)", async ({
+ page,
+ browserName,
+}) => {
+ await openBare(page, browserName);
+ const actions = await page.evaluate(() => {
+ const {host, PanGestureRecognizer, LongPressGestureRecognizer} =
+ window.__api;
+ const author = document.createElement('style');
+ author.textContent = '#authored { touch-action: none; }';
+ document.head.append(author);
+ document.body.innerHTML =
+ '<div id="plain" style="height: 60px"></div><div id="authored" style="height: 60px"></div><div id="shadowed" style="height: 60px"></div>';
+ const plain = document.getElementById('plain') as HTMLElement;
+ const authored = document.getElementById('authored') as HTMLElement;
+ const inner = document.createElement('div');
+ inner.style.height = '60px';
+ (document.getElementById('shadowed') as HTMLElement)
+ .attachShadow({mode: 'open'})
+ .append(inner);
+ host.attach(plain, new PanGestureRecognizer({direction: 'horizontal'}));
+ host.attach(authored, new LongPressGestureRecognizer());
+ host.attach(inner, new LongPressGestureRecognizer());
+ // Read in the attach's own task, before any frame.
+ return {
+ plain: getComputedStyle(plain).touchAction,
+ authored: getComputedStyle(authored).touchAction,
+ inner: getComputedStyle(inner).touchAction,
+ };
+ });
+ expect(actions).toEqual({
+ plain: 'pan-y pinch-zoom',
+ authored: 'none',
+ inner: 'manipulation',
+ });
+});
+
+test("an author rule in any cascade layer outranks the host's touch-action (spec:AST-094 FR18, DEC-8)", async ({
+ page,
+ browserName,
+}) => {
+ await openBare(page, browserName);
+ const actions = await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ // The layer order a package stylesheet declares (spec:AST-080 FR3), and
+ // author rules in Astryx's base layer and in the product's layer.
+ const author = document.createElement('style');
+ author.textContent = `@layer reset, astryx-base, astryx-theme, product;
+ @layer astryx-base { #base { touch-action: none; } }
+ @layer product { #product { touch-action: pan-x; } }`;
+ document.head.append(author);
+ document.body.innerHTML =
+ '<div id="base" style="height: 60px"></div><div id="product" style="height: 60px"></div>';
+ const base = document.getElementById('base') as HTMLElement;
+ const product = document.getElementById('product') as HTMLElement;
+ host.attach(base, new PanGestureRecognizer({direction: 'horizontal'}));
+ host.attach(product, new PanGestureRecognizer({direction: 'horizontal'}));
+ return {
+ base: getComputedStyle(base).touchAction,
+ product: getComputedStyle(product).touchAction,
+ };
+ });
+ expect(actions).toEqual({base: 'none', product: 'pan-x'});
+});
+
+test('a subtree that mounts with a recognizer is styled once: the host adds no second recalc of it (spec:AST-094 FR18)', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'counts style recalcs in a Chromium trace',
+ );
+ await openBare(page, browserName);
+ const cdp = await page.context().newCDPSession(page);
+ const events: {name: string; args?: {elementCount?: number}}[] = [];
+ cdp.on('Tracing.dataCollected', ({value}) => {
+ events.push(...(value as unknown as typeof events));
+ });
+ const complete = new Promise(resolve => {
+ cdp.once('Tracing.tracingComplete', resolve);
+ });
+ await cdp.send('Tracing.start', {
+ transferMode: 'ReportEvents',
+ traceConfig: {
+ includedCategories: [
+ 'devtools.timeline',
+ 'disabled-by-default-devtools.timeline',
+ ],
+ excludedCategories: ['*'],
+ },
+ });
+ await page.evaluate(async () => {
+ const {host, PanGestureRecognizer} = window.__api;
+ const wheel = document.createElement('div');
+ for (let i = 0; i < 300; i += 1) {
+ const row = document.createElement('div');
+ row.textContent = `Row ${i}`;
+ wheel.append(row);
+ }
+ document.body.append(wheel);
+ host.attach(wheel, new PanGestureRecognizer({direction: 'vertical'}));
+ for (let i = 0; i < 4; i += 1) {
+ await new Promise(resolve => {
+ requestAnimationFrame(resolve);
+ });
+ }
+ });
+ await cdp.send('Tracing.end');
+ await complete;
+ // The subtree's first styling, and no recalc of it after: a touch-action
+ // written later would restyle every row (each one's effective value).
+ const subtreeRecalcs = events.filter(
+ event =>
+ event.name === 'UpdateLayoutTree' &&
+ (event.args?.elementCount ?? 0) >= 300,
+ );
+ expect(subtreeRecalcs).toHaveLength(1);
+});
+
+test('a recognizer registers no touch listener and writes no touch-action while it is disabled, and does once it is enabled (spec:AST-094 FR24)', async ({
+ page,
+ browserName,
+}) => {
+ await openBare(page, browserName);
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML = '<div id="solo" style="height: 120px">solo</div>';
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ isEnabled: false,
+ });
+ (window as unknown as {__solo: typeof pan}).__solo = pan;
+ host.attach(document.getElementById('solo') as HTMLElement, pan);
+ });
+ expect(await footprint(page, 'solo')).toEqual({
+ touchAction: '',
+ pageTouchListeners: 0,
+ });
+ const setEnabled = async (isEnabled: boolean) =>
+ page.evaluate(next => {
+ const solo = (
+ window as unknown as {
+ __solo: {setEnabled(value: boolean): void};
+ }
+ ).__solo;
+ solo.setEnabled(next);
+ window.__api.host.update(document.getElementById('solo') as HTMLElement);
+ }, isEnabled);
+ await setEnabled(true);
+ const enabled = await footprint(page, 'solo');
+ expect(enabled.touchAction).toBe('pan-y pinch-zoom');
+ expect(enabled.pageTouchListeners).toBeGreaterThan(0);
+ await setEnabled(false);
+ expect(await footprint(page, 'solo')).toEqual({
+ touchAction: '',
+ pageTouchListeners: 0,
+ });
+});
+
+test('a zero-delay hold that brings its own lock turns selection off only for a touch it takes: a touch it declines keeps native selection (spec:AST-094 FR41)', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await openBare(page, browserName);
+ await page.evaluate(() => {
+ const {host, LongPressGestureRecognizer, lockSelection} = window.__api;
+ // A tab bar: its lens is a hold at 0 ms, and the search tab beside it
+ // is a button the lens's recognizer declines.
+ document.body.innerHTML =
+ '<div id="bar" style="display: flex; height: 80px"><div id="lens" style="flex: 1">lens</div><button id="search" style="width: 120px">search</button></div>';
+ const lens = document.getElementById('lens') as HTMLElement;
+ host.attach(
+ document.getElementById('bar') as HTMLElement,
+ new LongPressGestureRecognizer({
+ minimumPressDuration: 0,
+ selectionLock: lockSelection,
+ shouldReceiveTouch: (_recognizer, touch) =>
+ touch.target instanceof Node && lens.contains(touch.target),
+ }),
+ );
+ });
+ expect(await refusesSelection(page, 'lens')).toBe(false);
+ const held: Record<string, boolean[]> = {};
+ for (const id of ['search', 'lens']) {
+ const at = await center(page, id);
+ await driver.play([{t: 0, down: [{id: 1, ...at}]}]);
+ const during = await refusesSelection(page, 'lens');
+ await driver.play([{t: 0, down: []}]);
+ held[id] = [during, await refusesSelection(page, 'lens')];
+ }
+ expect(held.search).toEqual([false, false]);
+ expect(held.lens).toEqual([true, false]);
+});
+
test('a tap recognizer replaces the click: no ghost click, no compatibility mouse events', async ({
page,
browserName,
@@ -535,6 +1061,25 @@ test('a keyboard activation inside the click window after a claimed drag still c
);
});
+test('a finger the window blur cancelled lifts on nothing: its lift gets no click, and a later tap there keeps its own (spec:AST-094 FR28)', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ const at = await center(page, 'hbutton');
+ await clearLog(page);
+ await driver.play([{t: 0, down: [{id: 1, ...at}]}]);
+ // A headless page keeps its focus, so the blur is dispatched to the window.
+ await page.evaluate(() => window.dispatchEvent(new FocusEvent('blur')));
+ await driver.play([{t: 0, down: []}]);
+ await page.waitForTimeout(100);
+ const clicks = async () =>
+ (await log(page)).filter(entry => entry.name === 'click:hbutton');
+ expect(await clicks()).toEqual([]);
+ await driver.tap(at);
+ expect(await clicks()).toHaveLength(1);
+});
+
test('scroll edge: at the top the pull is the sheet’s at once', async ({
page,
browserName,
@@ -551,6 +1096,25 @@ test('scroll edge: at the top the pull is the sheet’s at once', async ({
expect(await scrollTop(page, 'sheetBody')).toBe(0);
});
+test("scroll edge: at the top the sheet cancels the pull's moves from the first one, before it begins (spec:AST-094 FR19, DEC-18)", async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ await logTouchMoves(page);
+ const start = await center(page, 'sheetBody');
+ await driver.play(drag(start, {x: start.x, y: start.y + 24}));
+ const moves = await readTouchMoves(page);
+ // WebKit sends the first move at 2 px, well before the sheet's 10 px begin;
+ // Chromium sends none inside its own 15 px slop. Every move the page sees
+ // is cancelled, the first one included.
+ expect(moves.length).toBeGreaterThan(0);
+ expect(moves).toEqual(moves.map(() => true));
+ const sheet = (await log(page)).filter(entry => entry.name === 'sheet');
+ expect(sheet[0]?.state).toBe('began');
+ expect(await scrollTop(page, 'sheetBody')).toBe(0);
+});
+
test('a drag that began as a scroll stays the browser’s (AST-094 FR14): the content scrolls to its top and the sheet never begins', async ({
page,
browserName,
@@ -1081,14 +1645,22 @@ test.describe('under a fine primary pointer (spec:AST-094 FR43, FR24)', () => {
// A right click adds none.
await page.mouse.click(start.x, start.y, {button: 'right'});
expect(await addedPageListeners(page, idle)).toEqual([]);
- // After a claimed drag only the click swallower stays, for 1 s.
- await page.mouse.down();
- await page.mouse.move(start.x + 40, start.y, {steps: 4});
- await page.mouse.up();
- await page.waitForTimeout(50);
- expect(await addedPageListeners(page, idle)).toEqual(['click']);
- await page.waitForTimeout(1100);
- expect(await addedPageListeners(page, idle)).toEqual([]);
+ // After a claimed drag at most the click guard's listener stays, until
+ // the click it swallows or the end of its window, then nothing: a
+ // release-armed swallower is press work (FR24). A second drag leaves
+ // nothing either.
+ for (let drag = 0; drag < 2; drag++) {
+ await page.mouse.move(start.x, start.y);
+ await page.mouse.down();
+ await page.mouse.move(start.x + 40, start.y, {steps: 4});
+ await page.mouse.up();
+ await page.waitForTimeout(50);
+ expect(
+ (await addedPageListeners(page, idle)).filter(type => type !== 'click'),
+ ).toEqual([]);
+ await page.waitForTimeout(1100);
+ expect(await addedPageListeners(page, idle)).toEqual([]);
+ }
});
test('a pen drag begins a pan at 10 px like a mouse; the pen’s barrel button starts nothing', async ({
@@ -1135,3 +1707,371 @@ 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("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,
+ }) => {
+ const warnings: string[] = [];
+ page.on('console', message => {
+ if (message.type() === 'warning') {
+ warnings.push(message.text());
+ }
+ });
+ 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: bundle});
+ const seen = await page.evaluate(() => ({
+ isCoarse: matchMedia('(pointer: coarse)').matches,
+ page: window.__pageTouchListenersAtLoad,
+ elements: window.__listeners.map(
+ entry => `${entry.id}:${entry.type}:${String(entry.passive)}`,
+ ),
+ // What the host would write: none of it, in any engine's spelling.
+ styles: ['hpan', 'presser', 'slider', 'card'].map(id => {
+ const style = document.getElementById(id)?.style;
+ return ['touch-action', '-webkit-user-select', '-webkit-touch-callout']
+ .map(property => style?.getPropertyValue(property) ?? 'missing')
+ .join('|');
+ }),
+ }));
+ expect(seen.isCoarse).toBe(false);
+ expect(seen.page).toEqual([]);
+ // Only the elements whose recognizer claims a moving finger carry a
+ // touch listener: the blocking touchmove, which FR24 counts outside the
+ // one-listener budget, so a touchscreen laptop's finger claims as on a
+ // phone (FR19). A kept press gets its own only during a press.
+ expect(seen.elements).toEqual(
+ [
+ 'hpan',
+ 'presser',
+ 'pinchable',
+ 'sheetBody',
+ 'card',
+ 'authorNone',
+ 'authorPanY',
+ 'authorPinchZoom',
+ 'authorPanXY',
+ 'inlinePanXY',
+ 'edgeZone',
+ 'edgeWide',
+ 'edgeZoneRtl',
+ 'edgeWideRtl',
+ 'slider',
+ 'switchRow',
+ 'onePan',
+ ].map(id => `${id}:touchmove:false`),
+ );
+ expect(seen.styles).toEqual(['||', '||', '||', '||']);
+ // Gestures attach for every pointer: nothing to warn about.
+ expect(
+ warnings.filter(text => text.includes('primary pointer is fine')),
+ ).toEqual([]);
+ // A real mouse drag pans the horizontal pan.
+ const box = await page.locator('#hpan').boundingBox();
+ if (box == null) {
+ throw new Error('no box for #hpan');
+ }
+ const y = box.y + box.height / 2;
+ await page.mouse.move(box.x + 20, y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 120, y, {steps: 8});
+ await page.mouse.up();
+ const hpan = await page.evaluate(() =>
+ window.__gestures
+ .filter(entry => entry.name === 'hpan')
+ .map(entry => entry.state),
+ );
+ expect(hpan[0]).toBe('began');
+ expect(hpan).toContain('ended');
+ });
+});
+
+/**
+ * A page with a scroller of rows and a tap recognizer on one row; every
+ * transition of the tap goes to `window.__taps`.
+ */
+async function openTapInScroller(page: Page, engine: string): Promise<Driver> {
+ const driver = await openBare(page, engine);
+ await page.evaluate(() => {
+ const {host, TapGestureRecognizer} = window.__api;
+ document.body.innerHTML = `
+ <div id="list" style="height: 300px; overflow-y: auto; overscroll-behavior: contain">
+ <div id="row" style="height: 80px; background: #cfc">row</div>
+ <div style="height: 1200px">more rows</div>
+ </div>`;
+ const taps: string[] = [];
+ (window as unknown as {__taps: string[]}).__taps = taps;
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ tap.addTransitionListener((_current, _from, to) => taps.push(to));
+ host.attach(document.getElementById('row') as HTMLElement, tap);
+ });
+ return driver;
+}
+
+test('a still finger with sub-pixel jitter over a scroll view keeps its tap and scrolls nothing (spec:AST-094 FR18–FR22)', async ({
+ page,
+ browserName,
+}) => {
+ const driver = await openTapInScroller(page, browserName);
+ const at = await center(page, 'row');
+ // A resting fingertip: a few tenths of a pixel back and forth.
+ const jitter = [
+ [0.3, 0.2],
+ [-0.2, 0.4],
+ [0.4, -0.3],
+ [-0.3, -0.2],
+ [0.2, 0.3],
+ [0, 0],
+ ];
+ const steps: Step[] = [{t: 0, down: [{...at, id: 1}]}];
+ jitter.forEach(([dx, dy], i) =>
+ steps.push({
+ t: (i + 1) * 16,
+ down: [{x: at.x + dx, y: at.y + dy, id: 1}],
+ }),
+ );
+ steps.push({t: (jitter.length + 1) * 16, down: []});
+ await driver.play(steps);
+ await page.waitForTimeout(100);
+ const taps = await page.evaluate(
+ () => (window as unknown as {__taps: string[]}).__taps,
+ );
+ expect(taps).toContain('ended');
+ expect(await scrollTop(page, 'list')).toBe(0);
+});
+
+for (const stop of [
+ {
+ label: "an app's window-capture stopPropagation",
+ install: 'window' as const,
+ },
+ {
+ label:
+ "a document-capture stopImmediatePropagation registered before core's",
+ install: 'document' as const,
+ },
+]) {
+ test(`a tap is still recognized under ${stop.label}, since the recognizers hear touches on the window's capture phase`, async ({
+ page,
+ browserName,
+ }) => {
+ const driver = await openBare(page, browserName);
+ await page.evaluate(install => {
+ // The app's stop comes first, before any recognizer attaches.
+ for (const type of ['touchstart', 'touchmove', 'touchend']) {
+ if (install === 'window') {
+ window.addEventListener(type, event => event.stopPropagation(), {
+ capture: true,
+ });
+ } else {
+ document.addEventListener(
+ type,
+ event => event.stopImmediatePropagation(),
+ {capture: true},
+ );
+ }
+ }
+ const {host, TapGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<div id="row" style="height: 80px; background: #cfc">row</div>';
+ const taps: string[] = [];
+ (window as unknown as {__taps: string[]}).__taps = taps;
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ tap.addTransitionListener((_current, _from, to) => taps.push(to));
+ host.attach(document.getElementById('row') as HTMLElement, tap);
+ }, stop.install);
+ const at = await center(page, 'row');
+ await driver.play([
+ {t: 0, down: [{...at, id: 1}]},
+ {t: 60, down: []},
+ ]);
+ await page.waitForTimeout(100);
+ const taps = await page.evaluate(
+ () => (window as unknown as {__taps: string[]}).__taps,
+ );
+ expect(taps).toContain('ended');
+ });
+}
+
+for (const travel of [
+ {dx: 0, dy: 9, label: '9 px straight', keeps: true},
+ {dx: 0, dy: 10, label: '10 px straight', keeps: false},
+ {dx: 7, dy: 7, label: '(7, 7), 9.9 px diagonally', keeps: true},
+ {dx: 8, dy: 8, label: '(8, 8), 11.3 px diagonally', keeps: false},
+]) {
+ test(`a finger moved ${travel.label} over a scroll view ${travel.keeps ? 'keeps its tap and scrolls nothing' : 'is a tap or a scroll, never both'} (spec:AST-094 FR18–FR22)`, async ({
+ page,
+ browserName,
+ }) => {
+ const driver = await openTapInScroller(page, browserName);
+ await logTouchMoves(page);
+ const at = await center(page, 'row');
+ await driver.play(drag(at, {x: at.x + travel.dx, y: at.y + travel.dy}, 6));
+ await page.waitForTimeout(100);
+ const taps = await page.evaluate(
+ () => (window as unknown as {__taps: string[]}).__taps,
+ );
+ const scrolled = (await scrollTop(page, 'list')) > 0;
+ if (travel.keeps) {
+ // Under 10 px of travel: a tap, and no scroll took the touch.
+ expect(taps).toContain('ended');
+ expect(scrolled).toBe(false);
+ } else {
+ // From 10 px the browser may scroll (WebKit on a phone starts at 10;
+ // Chromium waits longer): if it does, the scroll takes the touch and
+ // there is no tap; if it does not, the tap stands.
+ expect(scrolled && taps.includes('ended')).toBe(false);
+ }
+ // A tap never claims a moving touch: no touchmove is cancelled, so the
+ // browser's scroll is never blocked.
+ expect((await readTouchMoves(page)).some(Boolean)).toBe(false);
+ });
+}
+
+/**
+ * A screen-edge pan on a strip along the left edge as wide as its band
+ * (40.2 px, which lays out at 40.203), over a horizontal scroller that
+ * fills the page; every
+ * transition of the pan goes to `window.__edge`.
+ */
+async function openEdgePan(page: Page, engine: string): Promise<Driver> {
+ const driver = await openBare(page, engine);
+ await page.evaluate(() => {
+ const {host, ScreenEdgePanGestureRecognizer} = window.__api;
+ document.body.innerHTML = `
+ <div id="hscroll" style="height: 300px; overflow-x: auto; overscroll-behavior: contain">
+ <div style="width: 3000px; height: 300px; background: linear-gradient(90deg, #eef, #cce)">wide</div>
+ </div>
+ <div id="edge" style="position: fixed; left: 0; top: 0; width: 40.2px; height: 300px"></div>`;
+ const edges: string[] = [];
+ (window as unknown as {__edge: string[]}).__edge = edges;
+ const pan = new ScreenEdgePanGestureRecognizer({
+ name: 'edge',
+ edges: ['leading'],
+ });
+ pan.addTransitionListener((_current, _from, to) => edges.push(to));
+ host.attach(document.getElementById('edge') as HTMLElement, pan);
+ });
+ return driver;
+}
+
+for (const run of [
+ {travel: 14, begins: false},
+ {travel: 15, begins: true},
+]) {
+ test(`a screen-edge pan landing 40 px from the edge ${run.begins ? 'claims at' : 'has not claimed at'} ${run.travel} px of travel (spec:AST-094 FR18–FR22)`, async ({
+ page,
+ browserName,
+ }) => {
+ const driver = await openEdgePan(page, browserName);
+ await logTouchMoves(page);
+ await driver.play(
+ drag({x: 40, y: 150}, {x: 40 + run.travel, y: 150}, 7, false),
+ );
+ await page.waitForTimeout(100);
+ const edges = await page.evaluate(
+ () => (window as unknown as {__edge: string[]}).__edge,
+ );
+ expect(edges.includes('began')).toBe(run.begins);
+ await driver.play([{t: 0, down: []}]);
+ });
+}
+
+test('a touch landing 41 px from the edge is outside the band: the edge pan never begins, and the horizontal scroll it starts is not blocked (spec:AST-094 FR18–FR22)', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName === 'webkit',
+ 'needs native scrolling from injected touches (Mobile Safari on the simulator)',
+ );
+ const driver = await openEdgePan(page, browserName);
+ await page.evaluate(() => {
+ (document.getElementById('hscroll') as HTMLElement).scrollLeft = 600;
+ });
+ await logTouchMoves(page);
+ await driver.play(drag({x: 41, y: 150}, {x: 201, y: 150}, 12));
+ await page.waitForTimeout(300);
+ const edges = await page.evaluate(
+ () => (window as unknown as {__edge: string[]}).__edge,
+ );
+ expect(edges).not.toContain('began');
+ expect((await readTouchMoves(page)).some(Boolean)).toBe(false);
+ expect(
+ await page.evaluate(
+ () => (document.getElementById('hscroll') as HTMLElement).scrollLeft,
+ ),
+ ).toBeLessThan(600);
+});
+
+/** A watcher's transition, with how far the list had scrolled then. */
+interface WatchTransition {
+ to: string;
+ scrollTop: number;
+}
+
+test('a watcher follows a touch the browser scrolls with to the lift, and cancels none of its moves (spec:AST-094 FR20)', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName === 'webkit',
+ 'needs native scrolling from injected touches (Mobile Safari on the simulator)',
+ );
+ const driver = await openBare(page, browserName);
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML = `
+ <div id="list" style="height: 300px; overflow-y: auto">
+ <div id="row" style="height: 80px; background: #cfc">row</div>
+ <div style="height: 1200px">more rows</div>
+ </div>`;
+ const list = document.getElementById('list') as HTMLElement;
+ const states: WatchTransition[] = [];
+ (window as unknown as {__watch: WatchTransition[]}).__watch = states;
+ const watcher = new PanGestureRecognizer({
+ name: 'watch',
+ direction: 'vertical',
+ claimsTouches: false,
+ });
+ // Each transition with how far the list had scrolled then.
+ watcher.addTransitionListener((_current, _from, to) =>
+ states.push({to, scrollTop: list.scrollTop}),
+ );
+ host.attach(document.getElementById('list') as HTMLElement, watcher, {
+ manageStyle: false,
+ });
+ });
+ await logTouchMoves(page);
+ const at = await center(page, 'row');
+ await driver.play(drag(at, {x: at.x, y: at.y - 120}, 30));
+ await page.waitForTimeout(100);
+ const states = await page.evaluate(
+ () =>
+ (
+ window as unknown as {
+ __watch: WatchTransition[];
+ }
+ ).__watch,
+ );
+ // The browser scrolled the list: the watcher took nothing from it.
+ expect(await scrollTop(page, 'list')).toBeGreaterThan(20);
+ expect((await readTouchMoves(page)).some(Boolean)).toBe(false);
+ // And it followed the scroll from its start to the lift: it still
+ // reported moves once the browser had taken the touch and was scrolling.
+ expect(states.map(entry => entry.to)).toContain('began');
+ expect(
+ states.some(entry => entry.to === 'changed' && entry.scrollTop > 0),
+ ).toBe(true);
+ // It ended there, then the arena reset it to possible, as UIKit resets a
+ // recognizer after it ends.
+ expect(states.slice(-2).map(entry => entry.to)).toEqual([
+ 'ended',
+ 'possible',
+ ]);
+});
diff --git a/packages/core/src/gestures/__tests__/browser/presentedFixture.ts b/packages/core/src/gestures/__tests__/browser/presentedFixture.ts
new file mode 100644
index 0000000000..84e24830d4
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/browser/presentedFixture.ts
@@ -0,0 +1,315 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file presentedFixture.ts
+ * @input Nothing: bundled by esbuild and injected into a blank page
+ * @output A scrim and a sheet with a Done button. `window.__move('up')`
+ * springs the sheet up into place from below the screen and
+ * `__move('down')` springs it down off it, with Core's animator and a
+ * critically damped spring (the sheet's shape, slowed to a 6 s response so
+ * a test can act while it moves, even on a loaded machine).
+ * `__springSpeeds()` reads the spring's speed 0.3, 1.5 and 4.5 s into the
+ * motion from the animator's own curve. `__mimicIos()` makes hit tests answer where the engine
+ * last resolved the sheet (where the motion started, until a style write),
+ * as iOS WebKit does mid-animation. `__act('tap')` taps the drawn Done and
+ * `__act('drag')` drags the drawn sheet 120 px down, in the first frame
+ * where that target is drawn on screen and still moving (restarting the
+ * motion, up to four times, when a busy machine shows no such frame before
+ * it settles), with synthetic touches whose target is what such a hit test
+ * returns. A drag that
+ * begins the sheet's pan stops the spring where the sheet is drawn, and
+ * the sheet then follows the finger. Transitions and clicks go to `__log`.
+ * @position Browser fixture of presentedHitTesting.interaction.browser.spec.ts; test-only
+ */
+
+import {createAnimator} from '../../../motion/animator';
+import {presentedOffsetOf} from '../../../motion/presentation';
+import {GestureHost} from '../../GestureHost';
+import {PanGestureRecognizer} from '../../PanGestureRecognizer';
+import {TapGestureRecognizer} from '../../TapGestureRecognizer';
+
+/** What a tap or a drag found and did, for the test to check. */
+interface Act {
+ /** The presented offset (px) and the velocity (px/s) at touch-down. */
+ readonly offset: number;
+ readonly velocity: number;
+ /** Motions it took to find a frame that drew the target while moving. */
+ readonly attempts: number;
+ /** What the hit test under the finger returned at touch-down. */
+ readonly engineTarget: string;
+ /** Drag only: each `touchmove`'s `defaultPrevented`, in order. */
+ readonly movesPrevented: ReadonlyArray<boolean>;
+ /** Drag only: the sheet's drawn top when its pan began, or null. */
+ readonly caughtTop: number | null;
+ /** Drag only: the sheet's drawn top and the pan's translation at the lift. */
+ readonly topAtLift: number;
+ readonly translationAtLift: number;
+}
+
+declare global {
+ interface Window {
+ __log: string[];
+ __move: (direction: 'up' | 'down') => void;
+ __springSpeeds: () => number[];
+ __mimicIos: () => void;
+ __act: (kind: 'tap' | 'drag') => Promise<Act>;
+ }
+}
+
+window.__log = [];
+document.body.style.cssText = 'margin:0;font:15px system-ui,sans-serif';
+document.body.innerHTML = `
+ <div id="scrim" style="position:fixed;inset:0;background:rgba(0,0,0,.3)"></div>
+ <div id="sheet" style="position:fixed;left:0;right:0;top:400px;height:444px;background:#fff;border-radius:14px 14px 0 0">
+ <button id="done" style="position:absolute;right:16px;top:12px;width:80px;height:40px">Done</button>
+ </div>`;
+
+const element = (id: string): HTMLElement => {
+ const found = document.getElementById(id);
+ if (found == null) {
+ throw new Error(`missing #${id}`);
+ }
+ return found;
+};
+const scrim = element('scrim');
+const sheet = element('sheet');
+const done = element('done');
+
+const host = new GestureHost(document, {presentedHitTesting: 'always'});
+const scrimTap = new TapGestureRecognizer({name: 'scrim'});
+const sheetDrag = new PanGestureRecognizer({name: 'sheet', direction: 'down'});
+for (const recognizer of [scrimTap, sheetDrag]) {
+ recognizer.addTransitionListener((current, _from, to) => {
+ window.__log.push(`${current.name}:${to}`);
+ });
+}
+host.attach(scrim, scrimTap);
+host.attach(sheet, sheetDrag);
+for (const [name, target] of [
+ ['scrim', scrim],
+ ['done', done],
+] as const) {
+ target.addEventListener('click', () => window.__log.push(`click:${name}`));
+}
+
+/** How far the sheet travels: from its rest to below the screen. */
+const TRAVEL = 444;
+
+/**
+ * The sheet's spring shape (critically damped, as UIKit's sheet spring
+ * renders), slowed so the motion lasts long enough to act on mid-flight.
+ */
+const SPRING = {response: 6, dampingRatio: 1} as const;
+
+const animator = createAnimator(sheet);
+const drawn = (target: Element): DOMRect =>
+ Element.prototype.getBoundingClientRect.call(target);
+
+/** The current motion's direction and the translate it started from. */
+let direction: 'up' | 'down' = 'down';
+let startY = 0;
+/** Where the engine last resolved the sheet's top; reset by each motion. */
+let resolved: {top: number; key: string} | null = null;
+
+window.__move = towards => {
+ direction = towards;
+ startY = towards === 'up' ? TRAVEL : 0;
+ resolved = null;
+ animator.set({y: startY});
+ animator.animate({y: TRAVEL - startY}, {spring: SPRING});
+};
+
+/** Where `target`'s top is with the sheet at the translate it started from. */
+const startTop = (target: HTMLElement): number => {
+ let top = 0;
+ for (
+ let node: HTMLElement | null = target;
+ node != null;
+ node = node.offsetParent as HTMLElement | null
+ ) {
+ top += node.offsetTop;
+ }
+ return top + startY;
+};
+
+window.__springSpeeds = () =>
+ [0.3, 1.5, 4.5].map(seconds =>
+ animator.getVelocity('y', performance.now() + seconds * 1000),
+ );
+
+/**
+ * Where the compositor draws the sheet's top now: its layout top plus the
+ * spring's value at this moment. On a starved machine the page's own box can
+ * trail the motion or, after a style write, jump ahead of it.
+ */
+const drawnTopNow = (time = performance.now()): number =>
+ startTop(sheet) - startY + animator.get('y', time);
+
+window.__mimicIos = () => {
+ // iOS keeps the transform it resolved when the motion started, until a
+ // style write on the element resolves it again to the value drawn at that
+ // moment (the animator's resolve writes a custom property for it).
+ const write = sheet.style.setProperty.bind(sheet.style);
+ sheet.style.setProperty = (name, value, priority) => {
+ write(name, value, priority);
+ if (name === '--astryx-presented') {
+ resolved = {top: drawnTopNow(), key: value ?? ''};
+ }
+ };
+ const resolvedTop = (): number => {
+ const key = sheet.style.getPropertyValue('--astryx-presented');
+ if (resolved == null) {
+ resolved = {top: startTop(sheet), key};
+ } else if (key !== resolved.key) {
+ resolved = {top: drawnTopNow(), key};
+ }
+ return resolved.top;
+ };
+ for (const target of [sheet, done]) {
+ const fromSheetTop = startTop(target) - startTop(sheet);
+ const box = () => {
+ const now = drawn(target);
+ return new DOMRect(
+ now.left,
+ resolvedTop() + fromSheetTop,
+ now.width,
+ now.height,
+ );
+ };
+ Object.defineProperty(target, 'getBoundingClientRect', {value: box});
+ }
+ const stack = (x: number, y: number): Element[] => {
+ const inside = (target: HTMLElement) => {
+ const box = target.getBoundingClientRect();
+ return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
+ };
+ return [
+ ...(inside(done) ? [done] : []),
+ ...(inside(sheet) ? [sheet] : []),
+ scrim,
+ document.body,
+ document.documentElement,
+ ];
+ };
+ Object.defineProperty(document, 'elementsFromPoint', {
+ configurable: true,
+ value: stack,
+ });
+ Object.defineProperty(document, 'elementFromPoint', {
+ configurable: true,
+ value: (x: number, y: number) => stack(x, y)[0],
+ });
+};
+
+/** The drawn top when the sheet's pan began, and the translate it froze at. */
+let caught: {top: number; y: number} | null = null;
+sheetDrag.addListener(recognizer => {
+ if (recognizer.state === 'began') {
+ const y = animator.get('y');
+ animator.set({y});
+ caught = {top: drawn(sheet).top, y};
+ } else if (recognizer.state === 'changed' && caught != null) {
+ animator.set({y: caught.y + recognizer.translation().y});
+ }
+});
+
+const touch = (
+ type: 'touchstart' | 'touchmove' | 'touchend',
+ target: Element,
+ x: number,
+ y: number,
+ time = performance.now(),
+): boolean => {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ // When the finger landed or moved, whenever the main thread gets to it.
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ const contact = {identifier: 1, clientX: x, clientY: y, target};
+ Object.defineProperty(event, 'changedTouches', {value: [contact]});
+ Object.defineProperty(event, 'touches', {
+ value: type === 'touchend' ? [] : [contact],
+ });
+ target.dispatchEvent(event);
+ if (type !== 'touchmove') {
+ window.__log.push(
+ `${type}:${event.defaultPrevented ? 'prevented' : 'open'}`,
+ );
+ }
+ return event.defaultPrevented;
+};
+
+const nextFrame = async (): Promise<void> => {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ });
+};
+
+/** The catch the sheet's pan listener recorded, read past the awaits. */
+const currentCatch = (): {top: number; y: number} | null => caught;
+
+/** Acts in the first frame that draws the target on screen while it moves. */
+const tryAct = async (
+ kind: 'tap' | 'drag',
+ attempts: number,
+): Promise<Act | null> => {
+ for (;;) {
+ await nextFrame();
+ // Aim where the compositor draws the target now, as a finger does; the
+ // touch carries this moment as its timestamp. Reading the offset first
+ // brings in the browser's start for the curve, which a busy page learns
+ // late, so the aim and the host read the same curve.
+ const landedAt = performance.now();
+ const offset = presentedOffsetOf(sheet, landedAt).y;
+ const velocity = animator.getVelocity('y', landedAt);
+ const target = kind === 'tap' ? done : sheet;
+ const box = drawn(target);
+ const top = drawnTopNow(landedAt) + startTop(target) - startTop(sheet);
+ const x = kind === 'tap' ? box.left + box.width / 2 : box.left + 60;
+ const y = kind === 'tap' ? top + box.height / 2 : top + 24;
+ if (
+ y > 8 &&
+ y < window.innerHeight - 8 &&
+ Math.abs(offset) > 30 &&
+ Math.abs(velocity) > 20
+ ) {
+ const landed = document.elementFromPoint(x, y) ?? document.body;
+ const found = {offset, velocity, attempts, engineTarget: landed.id};
+ caught = null;
+ touch('touchstart', landed, x, y, landedAt);
+ const movesPrevented: boolean[] = [];
+ if (kind === 'drag') {
+ for (let step = 1; step <= 10; step++) {
+ await nextFrame();
+ movesPrevented.push(touch('touchmove', landed, x, y + 12 * step));
+ }
+ }
+ const translationAtLift = sheetDrag.translation().y;
+ touch('touchend', landed, x, kind === 'drag' ? y + 120 : y);
+ return {
+ ...found,
+ movesPrevented,
+ caughtTop: currentCatch()?.top ?? null,
+ topAtLift: drawn(sheet).top,
+ translationAtLift,
+ };
+ }
+ // Settled, slowed past use, or (springing down) gone below the screen
+ // without a usable frame: the caller starts the motion again.
+ const settled = animator.get('y') === TRAVEL - startY;
+ const slowed = Math.abs(velocity) <= 20 && Math.abs(offset) > 30;
+ const gone = direction === 'down' && y >= window.innerHeight - 8;
+ if (settled || slowed || gone) {
+ return null;
+ }
+ }
+};
+
+window.__act = async kind => {
+ for (let attempts = 1; attempts <= 4; attempts++) {
+ const act = await tryAct(kind, attempts);
+ if (act != null) {
+ return act;
+ }
+ window.__move(direction);
+ }
+ throw new Error(`no frame drew the ${kind} target on screen while moving`);
+};
diff --git a/packages/core/src/gestures/__tests__/browser/presentedHitTesting.interaction.browser.spec.ts b/packages/core/src/gestures/__tests__/browser/presentedHitTesting.interaction.browser.spec.ts
new file mode 100644
index 0000000000..5ce18f740c
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/browser/presentedHitTesting.interaction.browser.spec.ts
@@ -0,0 +1,108 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file presentedHitTesting.interaction.browser.spec.ts
+ * @input presentedFixture.ts bundled with esbuild: a sheet that Core's
+ * animator springs up into place or down off the screen, over a scrim
+ * @output Browser proof that, with the sheet on a spring and hit testing
+ * answering where its motion started, as iOS WebKit does mid-animation, in
+ * both directions: a tap on the drawn Done button clicks
+ * Done once, never the sheet's body or the scrim; and a drag on the drawn
+ * sheet begins the sheet's pan and catches the sheet where it is drawn,
+ * with no scrim gesture
+ * @position Browser tests of the presented hit testing in GestureHost.ts and
+ * motion/presentation.ts, run by `pnpm test:interaction`
+ * (playwright.interaction.config.ts) and in CI's interaction proofs; the
+ * real iOS behaviour is proven on the simulator
+ */
+
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {build} from 'esbuild';
+import {expect, test, type Page} from '@playwright/test';
+
+let bundle = '';
+
+test.beforeAll(async () => {
+ const result = await build({
+ entryPoints: [
+ path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ 'presentedFixture.ts',
+ ),
+ ],
+ bundle: true,
+ write: false,
+ format: 'iife',
+ platform: 'browser',
+ target: 'es2022',
+ });
+ bundle = result.outputFiles[0].text;
+});
+
+const load = async (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: bundle});
+};
+
+for (const direction of ['up', 'down'] as const) {
+ // Where the motion started, the drawn target sits over the scrim (the sheet
+ // springing up from below the screen) or over the sheet's body (the sheet
+ // springing down from its rest).
+ const engineTarget = direction === 'up' ? 'scrim' : 'sheet';
+
+ test(`the sheet moves ${direction} on a spring, not at a constant speed`, async ({
+ page,
+ }) => {
+ await load(page);
+ await page.evaluate(d => window.__move(d), direction);
+ const speeds = await page.evaluate(async () => {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ });
+ return window.__springSpeeds().map(Math.abs);
+ });
+ // Read off the animator's own curve: its speed changes on the way.
+ expect(Math.max(...speeds) / Math.min(...speeds)).toBeGreaterThan(2);
+ });
+
+ test(`a tap on the drawn Done while the spring moves the sheet ${direction} clicks Done once`, async ({
+ page,
+ }) => {
+ await load(page);
+ await page.evaluate(() => window.__mimicIos());
+ await page.evaluate(d => window.__move(d), direction);
+ const act = await page.evaluate(async () => window.__act('tap'));
+ expect(act.engineTarget).toBe(engineTarget);
+ const log = await page.evaluate(() => window.__log);
+ expect(log.filter(entry => entry === 'click:done')).toHaveLength(1);
+ expect(log).not.toContain('click:scrim');
+ expect(log.some(entry => entry.startsWith('scrim:'))).toBe(false);
+ expect(log).toContain('touchend:prevented');
+ });
+
+ test(`a drag on the drawn sheet while the spring moves it ${direction} catches it where it is drawn`, async ({
+ page,
+ }) => {
+ await load(page);
+ await page.evaluate(() => window.__mimicIos());
+ await page.evaluate(d => window.__move(d), direction);
+ const act = await page.evaluate(async () => window.__act('drag'));
+ expect(act.engineTarget).toBe(engineTarget);
+ const log = await page.evaluate(() => window.__log);
+ expect(log).toContain('sheet:began');
+ expect(log).toContain('sheet:ended');
+ expect(log.some(entry => entry.startsWith('scrim:'))).toBe(false);
+ // Caught where it was drawn, then it followed the finger.
+ expect(act.caughtTop).not.toBeNull();
+ expect(act.translationAtLift).toBeGreaterThan(90);
+ expect(
+ Math.abs(act.topAtLift - ((act.caughtTop ?? 0) + act.translationAtLift)),
+ ).toBeLessThan(2);
+ // The pan claimed the touch: its moves after the first are cancelled.
+ expect(act.movesPrevented.slice(1).every(Boolean)).toBe(true);
+ });
+}
diff --git a/packages/core/src/gestures/__tests__/browserNegotiation.test.ts b/packages/core/src/gestures/__tests__/browserNegotiation.test.ts
index 93660caee9..dd32c20c23 100644
--- a/packages/core/src/gestures/__tests__/browserNegotiation.test.ts
+++ b/packages/core/src/gestures/__tests__/browserNegotiation.test.ts
@@ -18,11 +18,7 @@ import {PinchGestureRecognizer} from '../PinchGestureRecognizer';
import {ScreenEdgePanGestureRecognizer} from '../ScreenEdgePanGestureRecognizer';
import {SwipeGestureRecognizer} from '../SwipeGestureRecognizer';
import {TapGestureRecognizer} from '../TapGestureRecognizer';
-import {
- deriveTouchAction,
- gestureHostStyle,
- holdSelectionStyle,
-} from '../touchAction';
+import {deriveTouchAction, gestureHostStyle} from '../touchAction';
describe('deriveTouchAction', () => {
it('needs nothing without touch recognizers', () => {
@@ -102,20 +98,12 @@ describe('deriveTouchAction', () => {
).toBe('pan-y pinch-zoom');
});
- it('locks selection only for a held press, never on the element (spec:AST-094 FR41)', () => {
- // The attached style is the touch-action alone: a mouse and a keyboard
- // keep selecting (spec:AST-017 FR59).
+ it('attaches the touch-action alone, never a selection lock (spec:AST-094 FR41)', () => {
+ // A mouse and a keyboard keep selecting (spec:AST-017 FR59); the lock
+ // for one held press is the long press's own selectionLock.
expect(gestureHostStyle([new LongPressGestureRecognizer()])).toEqual({
touchAction: 'manipulation',
});
- // The host applies this for one press, from touch-down to the lift.
- expect(holdSelectionStyle([new LongPressGestureRecognizer()])).toEqual({
- WebkitTouchCallout: 'none',
- WebkitUserSelect: 'none',
- userSelect: 'none',
- });
- // A hold that does nothing selects natively.
- expect(holdSelectionStyle([new TapGestureRecognizer()])).toBeNull();
});
});
diff --git a/packages/core/src/gestures/__tests__/finePointerListeners.test.ts b/packages/core/src/gestures/__tests__/finePointerListeners.test.ts
new file mode 100644
index 0000000000..aa3ba566b7
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/finePointerListeners.test.ts
@@ -0,0 +1,284 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file finePointerListeners.test.ts
+ * @input GestureHost under a fine primary pointer, with the shared input
+ * stream counted and synthetic pointer and touch events
+ * @output What the host listens with where the primary pointer is fine
+ * (`spec:AST-094` FR24, FR43): its page listeners go when the window blurs
+ * during a press; a kept press has its blocking touchmove only during a
+ * press
+ * @position Unit tests of packages/core/src/gestures/GestureHost.ts
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {GestureHost} from '../GestureHost';
+import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {createPressTracker} from '../PressTracker';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import type * as InputStreamModule from '../../utils/inputStream';
+import {ManualClock} from './harness';
+
+/** Live subscriptions to the shared input stream, by event type. */
+const subscriptions = new Map<string, number>();
+
+vi.mock('../../utils/inputStream', async importOriginal => {
+ const real = await importOriginal<typeof InputStreamModule>();
+ return {
+ ...real,
+ subscribeInput: ((...args: Parameters<typeof real.subscribeInput>) => {
+ const type = args[1];
+ subscriptions.set(type, (subscriptions.get(type) ?? 0) + 1);
+ const unsubscribe = real.subscribeInput(...args);
+ let isDone = false;
+ return () => {
+ if (!isDone) {
+ isDone = true;
+ subscriptions.set(type, (subscriptions.get(type) ?? 0) - 1);
+ }
+ unsubscribe();
+ };
+ }) as typeof real.subscribeInput,
+ };
+});
+
+function pageListeners(): string[] {
+ return [...subscriptions]
+ .filter(([, count]) => count > 0)
+ .map(([type]) => type)
+ .sort();
+}
+
+function pointer(
+ type: string,
+ target: EventTarget,
+ init: {
+ pointerType: string;
+ x: number;
+ y: number;
+ buttons?: number;
+ time: number;
+ relatedTarget?: EventTarget | null;
+ },
+): void {
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: init.pointerType === 'mouse' ? 1 : 2,
+ pointerType: init.pointerType,
+ clientX: init.x,
+ clientY: init.y,
+ buttons: init.buttons ?? 0,
+ relatedTarget: init.relatedTarget ?? null,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: init.time});
+ target.dispatchEvent(event);
+}
+
+function touch(
+ type: string,
+ target: EventTarget,
+ contact: {id: number; x: number; y: number},
+ time: number,
+ isLift = false,
+): void {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const entry = {
+ identifier: contact.id,
+ clientX: contact.x,
+ clientY: contact.y,
+ target,
+ };
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: isLift ? [] : [entry]});
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+}
+
+let detachers: (() => void)[];
+let host: GestureHost;
+
+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;
+}
+
+/** The element's live `touchmove` listeners, counted as they come and go. */
+function countTouchMoves(element: Element): () => number {
+ let count = 0;
+ const add = element.addEventListener.bind(element);
+ const remove = element.removeEventListener.bind(element);
+ element.addEventListener = ((type: string, ...rest: [never, never?]) => {
+ if (type === 'touchmove') {
+ count += 1;
+ }
+ add(type, ...rest);
+ }) as typeof element.addEventListener;
+ element.removeEventListener = ((type: string, ...rest: [never, never?]) => {
+ if (type === 'touchmove') {
+ count -= 1;
+ }
+ remove(type, ...rest);
+ }) as typeof element.removeEventListener;
+ return () => count;
+}
+
+beforeEach(() => {
+ subscriptions.clear();
+ detachers = [];
+ host = new GestureHost(document, {
+ clock: new ManualClock(),
+ isPrimaryPointerCoarse: () => false,
+ });
+});
+
+afterEach(() => {
+ for (const detach of detachers.splice(0)) {
+ detach();
+ }
+ document.body.innerHTML = '';
+});
+
+describe('a fine primary pointer', () => {
+ it('takes down the page listeners when the window blurs during a press', async () => {
+ const {box} = mount('<div id="box"></div>');
+ detachers.push(host.attach(box, new TapGestureRecognizer()));
+ expect(pageListeners()).toEqual([]);
+ pointer('pointerdown', box, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ expect(pageListeners()).toContain('pointermove');
+ window.dispatchEvent(new Event('blur'));
+ await Promise.resolve();
+ expect(pageListeners()).toEqual([]);
+ });
+
+ it("gives a kept press its blocking touchmove only during a press, as a phone's needs it only for a finger", async () => {
+ const {stepper} = mount('<div id="stepper"></div>');
+ const touchMoves = countTouchMoves(stepper);
+ detachers.push(
+ host.attachConsumer(
+ stepper,
+ createPressTracker({getBounds: () => null, keepsTouch: true}),
+ ),
+ );
+ expect(touchMoves()).toBe(0);
+ // A touchscreen laptop's finger: its pointerdown comes before its
+ // touchstart, so the listener is in place before the first touchmove.
+ pointer('pointerdown', stepper, {
+ pointerType: 'touch',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ expect(touchMoves()).toBeGreaterThan(0);
+ touch('touchstart', stepper, {id: 1, x: 5, y: 5}, 0);
+ pointer('pointerup', stepper, {pointerType: 'touch', x: 5, y: 5, time: 50});
+ touch('touchend', stepper, {id: 1, x: 5, y: 5}, 50, true);
+ await Promise.resolve();
+ expect(touchMoves()).toBe(0);
+ });
+
+ it("cancels a claimed finger's lift and the browser's menu during an armed press, as where the primary pointer is coarse (spec:AST-094 FR21)", () => {
+ const {sheet} = mount('<div id="sheet"></div>');
+ detachers.push(
+ host.attach(sheet, new PanGestureRecognizer({direction: 'horizontal'})),
+ host.attach(sheet, new LongPressGestureRecognizer({name: 'press'})),
+ );
+ // A touchscreen laptop's finger: its pointerdown arms the press.
+ pointer('pointerdown', sheet, {
+ pointerType: 'touch',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ touch('touchstart', sheet, {id: 1, x: 5, y: 5}, 0);
+ // The finger's pointer events sample it; its touchmove follows each.
+ pointer('pointermove', sheet, {
+ pointerType: 'touch',
+ x: 40,
+ y: 5,
+ buttons: 1,
+ time: 32,
+ });
+ touch('touchmove', sheet, {id: 1, x: 40, y: 5}, 32);
+ // The browser's own menu for that finger stays off.
+ const menu = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ });
+ sheet.dispatchEvent(menu);
+ expect(menu.defaultPrevented).toBe(true);
+ // The claimed finger's lift clicks nothing.
+ pointer('pointerup', sheet, {pointerType: 'touch', x: 40, y: 5, time: 48});
+ const lift = new Event('touchend', {bubbles: true, cancelable: true});
+ const entry = {identifier: 1, clientX: 40, clientY: 5, target: sheet};
+ Object.defineProperty(lift, 'changedTouches', {value: [entry]});
+ Object.defineProperty(lift, 'touches', {value: []});
+ Object.defineProperty(lift, 'timeStamp', {value: 48});
+ sheet.dispatchEvent(lift);
+ expect(lift.defaultPrevented).toBe(true);
+ });
+
+ it("keeps a kept press's finger during an armed press: its moves are cancelled, as on a phone (spec:AST-094 FR11, DEC-21)", () => {
+ const {stepper} = mount('<div id="stepper"></div>');
+ detachers.push(
+ host.attachConsumer(
+ stepper,
+ createPressTracker({getBounds: () => null, keepsTouch: true}),
+ ),
+ );
+ pointer('pointerdown', stepper, {
+ pointerType: 'touch',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ touch('touchstart', stepper, {id: 1, x: 5, y: 5}, 0);
+ const move = new Event('touchmove', {bubbles: true, cancelable: true});
+ const entry = {identifier: 1, clientX: 9, clientY: 5, target: stepper};
+ Object.defineProperty(move, 'changedTouches', {value: [entry]});
+ Object.defineProperty(move, 'touches', {value: [entry]});
+ Object.defineProperty(move, 'timeStamp', {value: 16});
+ stepper.dispatchEvent(move);
+ expect(move.defaultPrevented).toBe(true);
+ touch('touchend', stepper, {id: 1, x: 9, y: 5}, 50, true);
+ });
+
+ it('takes down the page listeners when the page is hidden during a press (spec:AST-094 FR24)', async () => {
+ const {box} = mount('<div id="box"></div>');
+ detachers.push(host.attach(box, new TapGestureRecognizer()));
+ pointer('pointerdown', box, {
+ pointerType: 'mouse',
+ x: 5,
+ y: 5,
+ buttons: 1,
+ time: 0,
+ });
+ expect(pageListeners()).toContain('pointermove');
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'hidden',
+ });
+ try {
+ document.dispatchEvent(new Event('visibilitychange'));
+ await Promise.resolve();
+ expect(pageListeners()).toEqual([]);
+ } finally {
+ Reflect.deleteProperty(document, 'visibilityState');
+ }
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/haptics.test.ts b/packages/core/src/gestures/__tests__/haptics.test.ts
index c52c387696..6492c68668 100644
--- a/packages/core/src/gestures/__tests__/haptics.test.ts
+++ b/packages/core/src/gestures/__tests__/haptics.test.ts
@@ -19,10 +19,14 @@ import {
import {
attachTapHaptic,
canVibrate,
- HAPTIC_SWITCH_ATTRIBUTE,
playHaptic,
supportsSwitchControl,
} from '../haptics';
+import {isHapticSwitch} from '../../privateAttributes/hapticSwitch.stylex';
+
+/** The hidden switch attachTapHaptic added inside `label`, if any. */
+const hapticSwitchIn = (label: Element): HTMLInputElement | null =>
+ [...label.querySelectorAll('input')].find(isHapticSwitch) ?? null;
const original = Object.getOwnPropertyDescriptor(navigator, 'vibrate');
@@ -82,7 +86,7 @@ describe('attachTapHaptic', () => {
label.addEventListener('change', onChange);
const release = attachTapHaptic(label);
- const input = label.querySelector(`[${HAPTIC_SWITCH_ATTRIBUTE}]`);
+ const input = hapticSwitchIn(label);
expect(input).toBeInstanceOf(HTMLInputElement);
const sw = input as HTMLInputElement;
expect(sw.type).toBe('checkbox');
@@ -101,7 +105,7 @@ describe('attachTapHaptic', () => {
expect(onChange).not.toHaveBeenCalled();
release();
- expect(label.querySelector(`[${HAPTIC_SWITCH_ATTRIBUTE}]`)).toBeNull();
+ expect(hapticSwitchIn(label)).toBeNull();
});
it('never leaves the focus on its hidden switch', () => {
@@ -110,9 +114,7 @@ describe('attachTapHaptic', () => {
const before = document.getElementById('before') as HTMLButtonElement;
const label = document.getElementById('tap') as HTMLLabelElement;
const release = attachTapHaptic(label);
- const sw = label.querySelector<HTMLInputElement>(
- `[${HAPTIC_SWITCH_ATTRIBUTE}]`,
- )!;
+ const sw = hapticSwitchIn(label)!;
before.focus();
// Chromium focuses a label's control on its activation.
sw.focus();
@@ -129,9 +131,7 @@ describe('attachTapHaptic', () => {
const onOwnClick = vi.fn();
own.addEventListener('click', onOwnClick);
const release = attachTapHaptic(label);
- const sw = label.querySelector<HTMLInputElement>(
- `[${HAPTIC_SWITCH_ATTRIBUTE}]`,
- )!;
+ const sw = hapticSwitchIn(label)!;
// The switch takes the label's activation, so a tap plays.
expect(label.control).toBe(sw);
// The checkbox keeps its name: the label's text, through aria-labelledby.
@@ -153,9 +153,7 @@ describe('attachTapHaptic', () => {
const label = document.getElementById('tap') as HTMLLabelElement;
const own = document.getElementById('own') as HTMLInputElement;
const release = attachTapHaptic(label);
- const sw = label.querySelector<HTMLInputElement>(
- `[${HAPTIC_SWITCH_ATTRIBUTE}]`,
- )!;
+ const sw = hapticSwitchIn(label)!;
before.focus();
sw.focus();
sw.click();
@@ -174,7 +172,7 @@ describe('attachTapHaptic', () => {
for (const id of ['a', 'b']) {
const label = document.getElementById(id) as HTMLLabelElement;
const release = attachTapHaptic(label);
- expect(label.querySelector(`[${HAPTIC_SWITCH_ATTRIBUTE}]`)).toBeNull();
+ expect(hapticSwitchIn(label)).toBeNull();
release();
}
});
diff --git a/packages/core/src/gestures/__tests__/importGraph.test.ts b/packages/core/src/gestures/__tests__/importGraph.test.ts
new file mode 100644
index 0000000000..ddd4a23722
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/importGraph.test.ts
@@ -0,0 +1,125 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file importGraph.test.ts
+ * @input Uses vitest and node:fs over the gestures sources
+ * @output A gesture-only component's imports (useGestureRecognizer, the pan
+ * recognizers, the gesture host) reach neither the press tracker nor
+ * haptics, nor the page hold or the finger-scroll watch; each of those stays reachable from the entry that uses it; the
+ * host and touch-action reach no recognizer class
+ * @position Unit test of packages/core/src/gestures' module graph
+ *
+ * Static imports only: a type-only import is erased and costs nothing, and
+ * nothing here loads lazily. Run from the source, the graph is what a bundler
+ * that keeps every reachable module would ship.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+const GESTURES = path.resolve(__dirname, '..');
+
+/** The relative modules `file` imports for their values. */
+function valueImports(file: string): string[] {
+ const source = fs.readFileSync(file, 'utf8');
+ const specifiers: string[] = [];
+ const statement =
+ /^\s*(import|export)\s+(type\s+)?([^'";]*?\s+from\s+)?'([^']+)';/gms;
+ for (const match of source.matchAll(statement)) {
+ const [, , isTypeOnly, , specifier] = match;
+ if (isTypeOnly == null && specifier.startsWith('.')) {
+ specifiers.push(specifier);
+ }
+ }
+ return specifiers.map(specifier => resolveModule(file, specifier));
+}
+
+function resolveModule(from: string, specifier: string): string {
+ const base = path.resolve(path.dirname(from), specifier);
+ for (const candidate of [
+ `${base}.ts`,
+ `${base}.tsx`,
+ path.join(base, 'index.ts'),
+ ]) {
+ if (fs.existsSync(candidate)) {
+ return candidate;
+ }
+ }
+ throw new Error(
+ `${path.relative(GESTURES, from)}: cannot resolve ${specifier}`,
+ );
+}
+
+/** Every module `entry` reaches through value imports, as names relative to gestures/. */
+function reachable(entry: string): Set<string> {
+ const seen = new Set<string>();
+ const queue = [path.join(GESTURES, entry)];
+ while (queue.length > 0) {
+ const file = queue.pop() as string;
+ if (seen.has(file)) {
+ continue;
+ }
+ seen.add(file);
+ queue.push(...valueImports(file));
+ }
+ return new Set([...seen].map(file => path.relative(GESTURES, file)));
+}
+
+describe('the gestures module graph', () => {
+ it.each([
+ 'useGestureRecognizer.ts',
+ 'PanGestureRecognizer.ts',
+ 'GestureHost.ts',
+ 'useFingerScroll.ts',
+ ])('%s reaches neither the press tracker nor haptics', entry => {
+ const modules = reachable(entry);
+ expect(modules.has(entry)).toBe(true);
+ expect(modules).not.toContain('PressTracker.ts');
+ expect(modules).not.toContain('usePressTracker.ts');
+ expect(modules).not.toContain('haptics.ts');
+ });
+
+ it('reaches the press tracker from usePressTracker, and haptics from its own entry', () => {
+ expect(reachable('usePressTracker.ts')).toContain('PressTracker.ts');
+ // The host shares only the switch's attribute with haptics, through its
+ // owner module, where the click guard reads it too.
+ expect(reachable('haptics.ts')).toContain(
+ '../privateAttributes/hapticSwitch.stylex.ts',
+ );
+ expect(reachable('GestureHost.ts')).toContain(
+ '../privateAttributes/hapticSwitch.stylex.ts',
+ );
+ });
+
+ it.each([
+ 'useGestureRecognizer.ts',
+ 'PanGestureRecognizer.ts',
+ 'GestureHost.ts',
+ ])('%s reaches neither the page hold nor the finger-scroll watch', entry => {
+ const modules = reachable(entry);
+ expect(modules).not.toContain('pageHold.ts');
+ expect(modules).not.toContain('fingerScroll.ts');
+ });
+
+ it('reaches the finger-scroll watch from useFingerScroll, and the page hold from its own entry', () => {
+ expect(reachable('useFingerScroll.ts')).toContain('fingerScroll.ts');
+ // The page hold takes the host it holds for: it imports none of it.
+ expect(reachable('pageHold.ts')).not.toContain('GestureHost.ts');
+ });
+
+ it.each(['GestureHost.ts', 'touchAction.ts', 'PressTracker.ts'])(
+ '%s reaches no recognizer class: each brands its family',
+ entry => {
+ const modules = reachable(entry);
+ expect(modules).not.toContain('TapGestureRecognizer.ts');
+ expect(modules).not.toContain('LongPressGestureRecognizer.ts');
+ expect(modules).not.toContain('PanGestureRecognizer.ts');
+ },
+ );
+
+ it('reads type-only imports as free', () => {
+ // GestureRecognizer imports GestureArena for its types alone.
+ expect(reachable('GestureRecognizer.ts')).not.toContain('GestureArena.ts');
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/passiveByDefault.test.tsx b/packages/core/src/gestures/__tests__/passiveByDefault.test.tsx
new file mode 100644
index 0000000000..751f6af816
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/passiveByDefault.test.tsx
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file passiveByDefault.test.tsx
+ * @input Uses vitest, Testing Library, Button, Item, GestureHost and
+ * PressTracker
+ * @output Checks that plain pressables never get a blocking touchmove
+ * listener, and that only a press tracker created with `keepsTouch: true`
+ * does
+ * @position Guards the 60 fps scroll goal: a scroll that starts on a plain
+ * button or a list cell never waits on the main thread
+ */
+
+import {render} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {Button} from '../../Button/Button';
+import {Item} from '../../Item/Item';
+import {GestureHost} from '../GestureHost';
+import {createPressTracker} from '../PressTracker';
+import {ManualClock} from './harness';
+import {coarsePrimaryPointer} from './pointerQuery';
+
+function touchStart(target: Element): void {
+ const event = new Event('touchstart', {bubbles: true, cancelable: true});
+ const entry = {identifier: 1, clientX: 5, clientY: 5, target};
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: [entry]});
+ target.dispatchEvent(event);
+}
+
+function blockingTouchMoves(spy: {mock: {calls: unknown[][]}}): number {
+ return spy.mock.calls.filter(
+ ([type, , options]) =>
+ type === 'touchmove' &&
+ (options as AddEventListenerOptions | undefined)?.passive === false,
+ ).length;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+});
+
+// A phone: the host attaches only where the primary pointer is coarse.
+let restorePointer: () => void;
+beforeEach(() => {
+ restorePointer = coarsePrimaryPointer();
+});
+afterEach(() => {
+ restorePointer();
+});
+
+describe('blocking touchmove listeners', () => {
+ it('never come with a plain Button or an Item cell', () => {
+ const spy = vi.spyOn(EventTarget.prototype, 'addEventListener');
+ const {getByRole, getByText} = render(
+ <div>
+ <Button label="Save" />
+ <Item label="Row" onClick={() => {}} />
+ </div>,
+ );
+ touchStart(getByRole('button', {name: 'Save'}));
+ touchStart(getByText('Row'));
+ expect(blockingTouchMoves(spy)).toBe(0);
+ });
+
+ it('come only with a press tracker that keeps its touch', () => {
+ document.body.innerHTML = '<div id="plain"></div><div id="stepper"></div>';
+ const plain = document.getElementById('plain') as HTMLElement;
+ const stepper = document.getElementById('stepper') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const onPlain = vi.spyOn(plain, 'addEventListener');
+ const onStepper = vi.spyOn(stepper, 'addEventListener');
+ const detachPlain = host.attachConsumer(
+ plain,
+ createPressTracker({getBounds: () => null}),
+ );
+ const detachStepper = host.attachConsumer(
+ stepper,
+ createPressTracker({getBounds: () => null, keepsTouch: true}),
+ );
+ touchStart(plain);
+ expect(blockingTouchMoves(onPlain)).toBe(0);
+ expect(blockingTouchMoves(onStepper)).toBe(1);
+ detachPlain();
+ detachStepper();
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/pointerQuery.ts b/packages/core/src/gestures/__tests__/pointerQuery.ts
new file mode 100644
index 0000000000..688d4ac04c
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/pointerQuery.ts
@@ -0,0 +1,75 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file pointerQuery.ts
+ * @input jsdom's window.matchMedia
+ * @output coarsePrimaryPointer() and pointerQuery(): the primary pointer a
+ * test needs, until restored
+ * @position Test helper of packages/core/src/gestures
+ *
+ * jsdom's matchMedia models a desktop, whose primary pointer is fine, and
+ * the gesture host attaches nothing there (`spec:AST-094` FR19). A test of
+ * touch behaviour models a phone with coarsePrimaryPointer(); a test of the
+ * gate itself drives pointerQuery() and fires its change.
+ */
+
+import {TOUCH_QUERY} from '../../utils/touchQueries';
+
+/** The primary pointer as a test sets it. */
+export interface PointerQuery {
+ /** Turn the primary pointer coarse or fine, firing `change`. */
+ set(isCoarse: boolean): void;
+ /** Put jsdom's matchMedia back. */
+ readonly restore: () => void;
+}
+
+/**
+ * The primary pointer is coarse (`isCoarse`) or fine until `restore` runs;
+ * `set` changes it as a tablet docking a mouse would.
+ */
+export function pointerQuery(isCoarse: boolean): PointerQuery {
+ const matchMedia = window.matchMedia;
+ const listeners = new Set<() => void>();
+ let coarse = isCoarse;
+ const query = {
+ get matches() {
+ return coarse;
+ },
+ media: TOUCH_QUERY,
+ onchange: null,
+ addEventListener: (_type: string, listener: () => void) => {
+ listeners.add(listener);
+ },
+ removeEventListener: (_type: string, listener: () => void) => {
+ listeners.delete(listener);
+ },
+ addListener: (listener: () => void) => {
+ listeners.add(listener);
+ },
+ removeListener: (listener: () => void) => {
+ listeners.delete(listener);
+ },
+ dispatchEvent: () => false,
+ } as unknown as MediaQueryList;
+ window.matchMedia = (media: string) =>
+ media.trim() === TOUCH_QUERY ? query : matchMedia(media);
+ return {
+ set(next) {
+ if (next === coarse) {
+ return;
+ }
+ coarse = next;
+ for (const listener of [...listeners]) {
+ listener();
+ }
+ },
+ restore: () => {
+ window.matchMedia = matchMedia;
+ },
+ };
+}
+
+/** The primary pointer is coarse (a phone, a tablet) until the restore runs. */
+export function coarsePrimaryPointer(): () => void {
+ return pointerQuery(true).restore;
+}
diff --git a/packages/core/src/gestures/__tests__/presentedHitTesting.test.ts b/packages/core/src/gestures/__tests__/presentedHitTesting.test.ts
new file mode 100644
index 0000000000..8669603aa3
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/presentedHitTesting.test.ts
@@ -0,0 +1,517 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file presentedHitTesting.test.ts
+ * @input GestureHost on jsdom with WebKit's iOS hit testing mimicked:
+ * `elementFromPoint`, `elementsFromPoint` and `getBoundingClientRect`
+ * answer where a compositor animation started while a registered offset
+ * draws the sheet elsewhere (motion/presentation.ts)
+ * @output A finger on the drawn sheet reaches the sheet, not the scrim under
+ * its start, and its tap clicks the drawn button once (the engine's click
+ * cancelled, a late one swallowed); a finger where the sheet was but is no
+ * longer drawn reaches what is drawn there; press bounds follow the drawn
+ * box, a control slotted into a moving shadow-tree panel's included; a
+ * claiming recognizer across a shadow boundary from the moving element
+ * keeps the window's touchmove blocking, through the shared input stream;
+ * nothing changes with the gate
+ * off or nothing moving
+ * @position Unit tests of the presented hit testing in
+ * packages/core/src/gestures/GestureHost.ts
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {registerPresentedOffset} from '../../motion/presentation';
+import {GestureHost} from '../GestureHost';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {ManualClock} from './harness';
+import {coarsePrimaryPointer} from './pointerQuery';
+
+interface Box {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+const rect = ({left, top, right, bottom}: Box): DOMRect => ({
+ left,
+ top,
+ right,
+ bottom,
+ x: left,
+ y: top,
+ width: right - left,
+ height: bottom - top,
+ toJSON: () => ({}),
+});
+
+function touch(
+ type: 'touchstart' | 'touchend',
+ target: EventTarget,
+ at: {x: number; y: number},
+ time: number,
+): Event {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const contact = {identifier: 1, clientX: at.x, clientY: at.y, target};
+ Object.defineProperty(event, 'changedTouches', {value: [contact]});
+ Object.defineProperty(event, 'touches', {
+ value: type === 'touchend' ? [] : [contact],
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+ return event;
+}
+
+let clock: ManualClock;
+let cleanups: (() => void)[];
+let scrim: HTMLElement;
+let sheet: HTMLElement;
+let done: HTMLElement;
+let clicks: string[];
+/** Where the engine hit-tests the sheet, relative to its start, px. */
+let resolvedY: number;
+
+/**
+ * A sheet whose animation started at `sheetBox` and is drawn `drawnY` px
+ * from it (or `drawnY(time)` px, `time` on the `performance.now()` clock,
+ * for a sheet still moving), with a Done button at its top right, over a
+ * full-page scrim. Hit tests answer where the engine last resolved the sheet,
+ * as iOS WebKit does mid-animation: at the start until a style write (the
+ * registry's `resolve`) moves it to where the sheet is drawn.
+ */
+function mount(
+ sheetBox: Box,
+ drawnY: number | ((time: number) => number),
+): void {
+ const drawnAt = (time: number) =>
+ typeof drawnY === 'number' ? drawnY : drawnY(time);
+ document.body.innerHTML =
+ '<div id="scrim"></div><div id="sheet"><button id="done">Done</button></div>';
+ scrim = document.getElementById('scrim') as HTMLElement;
+ sheet = document.getElementById('sheet') as HTMLElement;
+ done = document.getElementById('done') as HTMLElement;
+ resolvedY = 0;
+ const moved = (box: Box): Box => ({
+ ...box,
+ top: box.top + resolvedY,
+ bottom: box.bottom + resolvedY,
+ });
+ const doneBox: Box = {
+ left: 300,
+ top: sheetBox.top + 10,
+ right: 380,
+ bottom: sheetBox.top + 50,
+ };
+ const inside = (box: Box, x: number, y: number) =>
+ x >= box.left && x < box.right && y >= box.top && y < box.bottom;
+ vi.spyOn(sheet, 'getBoundingClientRect').mockImplementation(() =>
+ rect(moved(sheetBox)),
+ );
+ vi.spyOn(done, 'getBoundingClientRect').mockImplementation(() =>
+ rect(moved(doneBox)),
+ );
+ const stack = (x: number, y: number): Element[] => [
+ ...(inside(moved(doneBox), x, y) ? [done] : []),
+ ...(inside(moved(sheetBox), x, y) ? [sheet] : []),
+ scrim,
+ document.body,
+ document.documentElement,
+ ];
+ Object.defineProperty(document, 'elementsFromPoint', {
+ configurable: true,
+ value: stack,
+ });
+ Object.defineProperty(document, 'elementFromPoint', {
+ configurable: true,
+ value: (x: number, y: number) => stack(x, y)[0],
+ });
+ for (const [name, element] of [
+ ['scrim', scrim],
+ ['done', done],
+ ] as const) {
+ element.addEventListener('click', () => clicks.push(name));
+ }
+ cleanups.push(
+ registerPresentedOffset(sheet, {
+ offset: (time = window.performance.now()) => ({
+ x: 0,
+ y: drawnAt(time) - resolvedY,
+ }),
+ resolve: () => {
+ resolvedY = drawnAt(window.performance.now());
+ },
+ }),
+ );
+}
+
+// A phone: the host attaches only where the primary pointer is coarse.
+let restorePointer: () => void;
+beforeEach(() => {
+ restorePointer = coarsePrimaryPointer();
+});
+afterEach(() => {
+ restorePointer();
+});
+
+beforeEach(() => {
+ clock = new ManualClock();
+ cleanups = [];
+ clicks = [];
+});
+
+afterEach(() => {
+ for (const cleanup of cleanups) {
+ cleanup();
+ }
+ vi.restoreAllMocks();
+ Reflect.deleteProperty(document, 'elementsFromPoint');
+ Reflect.deleteProperty(document, 'elementFromPoint');
+ document.body.innerHTML = '';
+});
+
+function host(presentedHitTesting: 'always' | 'never' = 'always') {
+ const gestures = new GestureHost(document, {clock, presentedHitTesting});
+ const scrimTap = new TapGestureRecognizer({name: 'scrim'});
+ const sheetDrag = new PanGestureRecognizer({
+ name: 'sheet',
+ direction: 'down',
+ });
+ cleanups.push(
+ gestures.attach(scrim, scrimTap),
+ gestures.attach(sheet, sheetDrag),
+ );
+ return {gestures, scrimTap, sheetDrag};
+}
+
+describe('presented hit testing (iOS WebKit hit-tests compositor motion at layout)', () => {
+ it('sends a finger on the drawn sheet to the sheet, and clicks the drawn button once', () => {
+ // Presenting: the sheet started below the screen, where iOS still
+ // hit-tests it, and is drawn 544 px higher.
+ mount({left: 0, top: 844, right: 390, bottom: 1244}, -544);
+ const {scrimTap, sheetDrag} = host();
+ const onDone = {x: 340, y: 330};
+ // The engine hit the scrim, under the drawn button at the sheet's start.
+ touch('touchstart', scrim, onDone, 0);
+ expect(sheetDrag.numberOfTouches).toBe(1);
+ expect(scrimTap.numberOfTouches).toBe(0);
+ const end = touch('touchend', scrim, onDone, 80);
+ expect(end.defaultPrevented).toBe(true);
+ expect(clicks).toEqual(['done']);
+ // The engine's own click, however late, is swallowed by the shared
+ // click guard: one activation.
+ const late = () => {
+ const event = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ detail: 1,
+ });
+ scrim.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ expect(late()).toBe(true);
+ expect(clicks).toEqual(['done']);
+ // One click only: the guard is spent.
+ expect(late()).toBe(false);
+ });
+
+ it('sends a touch the host handles late to what was drawn under the finger when it landed (spec:AST-094 FR11)', () => {
+ // Presenting, still moving up at 160 px/s: at 1,000 ms the finger lands
+ // on the drawn Done; a busy main thread hands the host the touch 150 ms
+ // later, when Done is drawn 24 px higher and the finger's point is over
+ // the sheet's body.
+ mount({left: 0, top: 844, right: 390, bottom: 1244}, time => {
+ return -544 - 0.16 * (time - 1000);
+ });
+ const now = vi.spyOn(window.performance, 'now').mockReturnValue(1150);
+ host();
+ const onDone = {x: 340, y: 330};
+ touch('touchstart', scrim, onDone, 1000);
+ touch('touchend', scrim, onDone, 1080);
+ expect(clicks).toEqual(['done']);
+ now.mockRestore();
+ });
+
+ it('keeps a touch the host handles late with what was under the finger when it landed, not content that slid under it since (spec:AST-094 FR11)', () => {
+ // Presenting, still moving up at 160 px/s: at 1,000 ms the finger lands
+ // on the scrim just above the sheet's drawn top (300); a busy main thread
+ // hands the host the touch 150 ms later, when the sheet has slid 24 px
+ // higher and its Done button is drawn under the finger's point.
+ mount({left: 0, top: 844, right: 390, bottom: 1244}, time => {
+ return -544 - 0.16 * (time - 1000);
+ });
+ const now = vi.spyOn(window.performance, 'now').mockReturnValue(1150);
+ const {scrimTap, sheetDrag} = host();
+ const aboveSheet = {x: 340, y: 290};
+ touch('touchstart', scrim, aboveSheet, 1000);
+ expect(scrimTap.numberOfTouches).toBe(1);
+ expect(sheetDrag.numberOfTouches).toBe(0);
+ touch('touchend', scrim, aboveSheet, 1080);
+ expect(clicks).toEqual([]);
+ now.mockRestore();
+ });
+
+ it("clicks the drawn button once with only watchers attached: the shared click guard swallows the engine's own click", () => {
+ mount({left: 0, top: 844, right: 390, bottom: 1244}, -544);
+ // Nothing that claims: the host's touchend listener is passive, so the
+ // tap's single activation rests on the click guard alone.
+ const gestures = new GestureHost(document, {
+ clock,
+ presentedHitTesting: 'always',
+ });
+ cleanups.push(
+ gestures.attach(
+ scrim,
+ new TapGestureRecognizer({name: 'scrim', claimsTouches: false}),
+ ),
+ gestures.attach(
+ sheet,
+ new PanGestureRecognizer({
+ name: 'sheet',
+ direction: 'down',
+ claimsTouches: false,
+ }),
+ ),
+ );
+ const onDone = {x: 340, y: 330};
+ touch('touchstart', scrim, onDone, 0);
+ touch('touchend', scrim, onDone, 80);
+ expect(clicks).toEqual(['done']);
+ const late = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ detail: 1,
+ });
+ scrim.dispatchEvent(late);
+ expect(late.defaultPrevented).toBe(true);
+ expect(clicks).toEqual(['done']);
+ });
+
+ it('descends into an open shadow root on the drawn sheet: the tap reaches and clicks the control inside it', () => {
+ // A sheet whose content lives in an open shadow root: the document's hit
+ // test answers its host, the root's answers the control.
+ document.body.innerHTML = '<div id="scrim"></div><div id="sheet"></div>';
+ scrim = document.getElementById('scrim') as HTMLElement;
+ sheet = document.getElementById('sheet') as HTMLElement;
+ const shadow = sheet.attachShadow({mode: 'open'});
+ shadow.innerHTML = '<button id="done">Done</button>';
+ const inner = shadow.getElementById('done') as HTMLElement;
+ let drawnOffset = -544;
+ let isResolved = false;
+ const isOnSheet = (y: number) => (isResolved ? y >= 300 : y >= 844);
+ Object.defineProperty(document, 'elementFromPoint', {
+ configurable: true,
+ value: (_x: number, y: number) => (isOnSheet(y) ? sheet : scrim),
+ });
+ Object.defineProperty(shadow, 'elementFromPoint', {
+ configurable: true,
+ value: () => inner,
+ });
+ inner.addEventListener('click', () => clicks.push('inner'));
+ sheet.addEventListener('click', () => clicks.push('sheet'));
+ scrim.addEventListener('click', () => clicks.push('scrim'));
+ cleanups.push(
+ registerPresentedOffset(sheet, {
+ offset: () => ({x: 0, y: drawnOffset}),
+ resolve: () => {
+ isResolved = true;
+ drawnOffset = 0;
+ },
+ }),
+ );
+ const gestures = new GestureHost(document, {
+ clock,
+ presentedHitTesting: 'always',
+ });
+ // A recognizer inside the root that watches without claiming, so the tap
+ // still earns its click.
+ const innerWatch = new PanGestureRecognizer({
+ name: 'inner',
+ direction: 'down',
+ claimsTouches: false,
+ });
+ cleanups.push(
+ gestures.attach(scrim, new TapGestureRecognizer({name: 'scrim'})),
+ gestures.attach(inner, innerWatch),
+ );
+ const onDone = {x: 340, y: 330};
+ touch('touchstart', scrim, onDone, 0);
+ expect(innerWatch.numberOfTouches).toBe(1);
+ touch('touchend', scrim, onDone, 80);
+ expect(clicks).toEqual(['inner', 'sheet']);
+ });
+
+ it('sends a finger where the sheet is going, but not yet drawn, to what is drawn there', () => {
+ // Dismissing: the sheet started on screen, where iOS still hit-tests it,
+ // and is drawn 544 px lower.
+ mount({left: 0, top: 300, right: 390, bottom: 700}, 544);
+ const {scrimTap, sheetDrag} = host();
+ const point = {x: 340, y: 330};
+ // The engine hit the button where it started.
+ touch('touchstart', done, point, 0);
+ expect(scrimTap.numberOfTouches).toBe(1);
+ expect(sheetDrag.numberOfTouches).toBe(0);
+ touch('touchend', done, point, 80);
+ expect(clicks).not.toContain('done');
+ });
+
+ it('gives press trackers the drawn box, before and after a touch resolves the sheet', () => {
+ mount({left: 0, top: 844, right: 390, bottom: 1244}, -544);
+ const {gestures} = host();
+ const drawn = {left: 300, top: 310, right: 380, bottom: 350};
+ expect(gestures.presentedRect(done)).toMatchObject(drawn);
+ touch('touchstart', scrim, {x: 340, y: 330}, 0);
+ expect(resolvedY).toBe(-544);
+ expect(gestures.presentedRect(done)).toMatchObject(drawn);
+ touch('touchend', scrim, {x: 340, y: 330}, 80);
+ expect(
+ new GestureHost(document, {presentedHitTesting: 'never'}).presentedRect(
+ done,
+ ),
+ ).toMatchObject({top: 310, bottom: 350});
+ });
+
+ it("keeps the window's touchmove blocking, through the shared input stream, only while an element a claiming recognizer lives in is moving: Safari honours a blocking one only when registered before the touch, and the window's capture phase sees every touch whatever the engine targets (spec:AST-094 FR19)", () => {
+ document.body.innerHTML =
+ '<div id="moving"><div id="body"></div></div><div id="still"></div>';
+ const moving = document.getElementById('moving') as HTMLElement;
+ const body = document.getElementById('body') as HTMLElement;
+ const still = document.getElementById('still') as HTMLElement;
+ const onWindow = vi.spyOn(window, 'addEventListener');
+ const onDocument = vi.spyOn(document, 'addEventListener');
+ const touchmoves = () =>
+ onWindow.mock.calls
+ .filter(([type]) => type === 'touchmove')
+ .map(([, , options]) => options as AddEventListenerOptions);
+ const blocking = () =>
+ touchmoves().filter(
+ options => options.capture === true && options.passive === false,
+ ).length;
+ const gestures = new GestureHost(document, {
+ clock,
+ presentedHitTesting: 'always',
+ });
+ cleanups.push(
+ gestures.attach(body, new PanGestureRecognizer({direction: 'down'})),
+ gestures.attach(still, new TapGestureRecognizer()),
+ );
+ expect(blocking()).toBe(0);
+ // A tap target moving claims nothing while the finger moves: no listener.
+ const stopStill = registerPresentedOffset(still, {
+ offset: () => ({x: 0, y: 30}),
+ resolve: () => {},
+ });
+ expect(blocking()).toBe(0);
+ stopStill();
+ // The sheet the pan lives in moves: the window's capturing touchmove
+ // turns non-passive until it stops, then passive again.
+ const stop = registerPresentedOffset(moving, {
+ offset: () => ({x: 0, y: 40}),
+ resolve: () => {},
+ });
+ expect(blocking()).toBe(1);
+ stop();
+ expect(blocking()).toBe(1);
+ expect(touchmoves().at(-1)?.passive).toBe(true);
+ // The one input stream carries it: the document gets no touchmove
+ // listener of its own (architecture:react-component-runtime INV13).
+ expect(
+ onDocument.mock.calls.filter(([type]) => type === 'touchmove'),
+ ).toEqual([]);
+ });
+
+ it("gives a control slotted into a moving shadow-tree panel the panel's drawn press bounds: the walk follows the flat tree through the slot", () => {
+ document.body.innerHTML =
+ '<div id="card"><button id="slotted">Done</button></div>';
+ const card = document.getElementById('card') as HTMLElement;
+ const slotted = document.getElementById('slotted') as HTMLElement;
+ const panel = document.createElement('div');
+ panel.append(document.createElement('slot'));
+ card.attachShadow({mode: 'open'}).append(panel);
+ // The button's light-DOM parent is the card; on the flat tree it sits in
+ // the panel, through the slot.
+ expect(slotted.assignedSlot?.parentNode).toBe(panel);
+ const gestures = new GestureHost(document, {
+ clock,
+ presentedHitTesting: 'always',
+ });
+ const stop = registerPresentedOffset(panel, {
+ offset: () => ({x: 0, y: 40}),
+ resolve: () => {},
+ });
+ try {
+ expect(gestures.presentedRect(slotted)).toMatchObject({
+ top: slotted.getBoundingClientRect().top + 40,
+ bottom: slotted.getBoundingClientRect().bottom + 40,
+ });
+ } finally {
+ stop();
+ }
+ });
+
+ it("keeps the window's touchmove blocking for a claiming recognizer across a shadow boundary from the moving element, inside its shadow tree or around it", () => {
+ document.body.innerHTML =
+ '<div id="sheet"><div id="sheet-host"></div></div><div id="pager"></div>';
+ const sheet = document.getElementById('sheet') as HTMLElement;
+ const sheetHost = document.getElementById('sheet-host') as HTMLElement;
+ const pager = document.getElementById('pager') as HTMLElement;
+ // A pan inside an open shadow root of the moving sheet.
+ const handle = document.createElement('div');
+ sheetHost.attachShadow({mode: 'open'}).append(handle);
+ // A moving page inside an open shadow root of the pan's element.
+ const page = document.createElement('div');
+ pager.attachShadow({mode: 'open'}).append(page);
+ const onWindow = vi.spyOn(window, 'addEventListener');
+ const onDocument = vi.spyOn(document, 'addEventListener');
+ const blocking = () =>
+ onWindow.mock.calls.filter(
+ ([type, , options]) =>
+ type === 'touchmove' &&
+ typeof options === 'object' &&
+ options.capture === true &&
+ options.passive === false,
+ ).length;
+ const gestures = new GestureHost(document, {
+ clock,
+ presentedHitTesting: 'always',
+ });
+ cleanups.push(
+ gestures.attach(handle, new PanGestureRecognizer({direction: 'down'})),
+ gestures.attach(pager, new PanGestureRecognizer({direction: 'left'})),
+ );
+ expect(blocking()).toBe(0);
+ const stopSheet = registerPresentedOffset(sheet, {
+ offset: () => ({x: 0, y: 40}),
+ resolve: () => {},
+ });
+ expect(blocking()).toBe(1);
+ stopSheet();
+ const stopPage = registerPresentedOffset(page, {
+ offset: () => ({x: -60, y: 0}),
+ resolve: () => {},
+ });
+ expect(blocking()).toBe(2);
+ stopPage();
+ expect(
+ onDocument.mock.calls.filter(([type]) => type === 'touchmove'),
+ ).toEqual([]);
+ });
+
+ it('changes nothing with the gate off or nothing moving', () => {
+ mount({left: 0, top: 844, right: 390, bottom: 1244}, -544);
+ const off = host('never');
+ touch('touchstart', scrim, {x: 340, y: 330}, 0);
+ expect(off.scrimTap.numberOfTouches).toBe(1);
+ expect(off.sheetDrag.numberOfTouches).toBe(0);
+ expect(resolvedY).toBe(0);
+ touch('touchend', scrim, {x: 340, y: 330}, 80);
+ for (const cleanup of cleanups.splice(0)) {
+ cleanup();
+ }
+ const still = host('always');
+ touch('touchstart', scrim, {x: 340, y: 330}, 200);
+ expect(still.scrimTap.numberOfTouches).toBe(1);
+ expect(still.sheetDrag.numberOfTouches).toBe(0);
+ touch('touchend', scrim, {x: 340, y: 330}, 280);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/recognizerBundle.test.ts b/packages/core/src/gestures/__tests__/recognizerBundle.test.ts
new file mode 100644
index 0000000000..9c0164e5d6
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/recognizerBundle.test.ts
@@ -0,0 +1,114 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file recognizerBundle.test.ts
+ * @input Uses vitest, node:child_process and esbuild over the gestures
+ * sources
+ * @output A production bundle of a page that constructs only a pan ships the
+ * gesture host and the pan, and none of the tap or long-press recognizers;
+ * press tracking ships no recognizer
+ * @position Unit test of packages/core/src/gestures' bundled size
+ *
+ * The host and touch-action tell recognizers apart by an internal family
+ * brand, never `instanceof`, so a bundler drops every recognizer a page does
+ * not construct. Read from esbuild's metafile: the modules with bytes in the
+ * minified, tree-shaken output. esbuild cannot run in this suite's jsdom
+ * environment (it asserts on a native `TextEncoder`), so it runs in a child
+ * process.
+ */
+
+import {execFileSync} from 'node:child_process';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+const GESTURES = path.resolve(__dirname, '..');
+
+const BUNDLE_SCRIPT = `
+import {build} from 'esbuild';
+import path from 'node:path';
+const [contents, resolveDir] = process.argv.slice(1);
+const result = await build({
+ stdin: {contents, resolveDir, loader: 'ts'},
+ bundle: true,
+ write: false,
+ minify: true,
+ treeShaking: true,
+ format: 'esm',
+ platform: 'browser',
+ packages: 'external',
+ metafile: true,
+ logLevel: 'silent',
+ define: {'process.env.NODE_ENV': '"production"'},
+});
+const [output] = Object.values(result.metafile.outputs);
+const modules = Object.entries(output.inputs)
+ .filter(([, input]) => input.bytesInOutput > 0)
+ .map(([file]) => path.basename(file));
+process.stdout.write(JSON.stringify(modules));
+`;
+
+/** The gestures modules with bytes in a production bundle of `entry`. */
+function bundledModules(entry: string): string[] {
+ const stdout = execFileSync(
+ process.execPath,
+ ['--input-type=module', '-e', BUNDLE_SCRIPT, entry, GESTURES],
+ {cwd: GESTURES, encoding: 'utf8', timeout: 120_000},
+ );
+ return JSON.parse(stdout) as string[];
+}
+
+describe('a gesture bundle', () => {
+ it('ships only the recognizers a page constructs: a pan-only page has no tap or long press', () => {
+ const modules = bundledModules(`
+ import {getGestureHost} from './GestureHost';
+ import {PanGestureRecognizer} from './PanGestureRecognizer';
+ export function mount(element: Element): () => void {
+ return getGestureHost(element.ownerDocument).attach(
+ element,
+ new PanGestureRecognizer(),
+ );
+ }
+ `);
+ expect(modules).toContain('GestureHost.ts');
+ expect(modules).toContain('PanGestureRecognizer.ts');
+ expect(modules).not.toContain('TapGestureRecognizer.ts');
+ expect(modules).not.toContain('LongPressGestureRecognizer.ts');
+ });
+
+ it('ships the pan only when a page constructs one', () => {
+ const modules = bundledModules(`
+ import {getGestureHost} from './GestureHost';
+ import {TapGestureRecognizer} from './TapGestureRecognizer';
+ export function mount(element: Element): () => void {
+ return getGestureHost(element.ownerDocument).attach(
+ element,
+ new TapGestureRecognizer(),
+ );
+ }
+ `);
+ expect(modules).toContain('TapGestureRecognizer.ts');
+ expect(modules).not.toContain('PanGestureRecognizer.ts');
+ expect(modules).not.toContain('LongPressGestureRecognizer.ts');
+ });
+
+ it('ships press tracking without the tap recognizer, which it only reads', () => {
+ const modules = bundledModules(`
+ import {getGestureHost} from './GestureHost';
+ import {createPressTracker} from './PressTracker';
+ export function mount(element: Element): () => void {
+ const tracker = createPressTracker({
+ getBounds: () => element.getBoundingClientRect(),
+ view: element,
+ });
+ return getGestureHost(element.ownerDocument).attachConsumer(
+ element,
+ tracker,
+ );
+ }
+ `);
+ expect(modules).toContain('PressTracker.ts');
+ expect(modules).not.toContain('TapGestureRecognizer.ts');
+ expect(modules).not.toContain('PanGestureRecognizer.ts');
+ expect(modules).not.toContain('LongPressGestureRecognizer.ts');
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/recognizerInternals.test.ts b/packages/core/src/gestures/__tests__/recognizerInternals.test.ts
new file mode 100644
index 0000000000..84fb080627
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/recognizerInternals.test.ts
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file recognizerInternals.test.ts
+ * @input Uses vitest, TapGestureRecognizer and recognizerInternals
+ * @output Checks that a recognizer's arena plumbing is off its public type
+ * and reachable through internals()
+ * @position Test for packages/core/src/gestures/recognizerInternals.ts
+ *
+ * The `@ts-expect-error` lines are the assertion: `tsc` fails if any of
+ * these members is public again.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {internals} from '../recognizerInternals';
+
+describe('recognizer internals', () => {
+ it('keeps the arena plumbing protected on the published class', () => {
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ function reachesPlumbing(): void {
+ // @ts-expect-error protected: the arena assigns it
+ tap.arena = null;
+ // @ts-expect-error protected
+ void tap.pending;
+ // @ts-expect-error protected
+ void tap.seenTouchIds;
+ // @ts-expect-error protected
+ void tap.acceptsTouchInput;
+ // @ts-expect-error protected
+ tap.requiresFailureOf(tap);
+ // @ts-expect-error protected
+ tap.allowsSimultaneous(tap);
+ // @ts-expect-error protected
+ tap.shouldBegin();
+ // @ts-expect-error protected
+ tap.applyState('began');
+ // @ts-expect-error protected
+ tap.resetToPossible();
+ // @ts-expect-error protected
+ tap.deliverCancelled([], {time: 0, allTouches: []});
+ }
+ expect(typeof reachesPlumbing).toBe('function');
+ });
+
+ it('lets the gesture system reach them', () => {
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ expect(internals(tap).arena).toBeNull();
+ expect(internals(tap).acceptsTouchInput).toBe(true);
+ expect(internals(tap).shouldBegin()).toBe(true);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/selectionLockReexport.test.ts b/packages/core/src/gestures/__tests__/selectionLockReexport.test.ts
new file mode 100644
index 0000000000..03affb7643
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/selectionLockReexport.test.ts
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file selectionLockReexport.test.ts
+ * @input The selection lock's old gestures path and its utils module
+ * @output The transition re-export at gestures/selectionLock.ts hands out the
+ * same functions as utils/selectionLock.ts
+ * @position Unit test of packages/core/src/gestures/selectionLock.ts
+ */
+
+import {describe, expect, it} from 'vitest';
+import * as atUtils from '../../utils/selectionLock';
+import * as atGestures from '../selectionLock';
+
+describe('gestures/selectionLock, a transition re-export', () => {
+ it('hands out the lock from utils, so a caller importing the old path keeps working', () => {
+ expect(atGestures.lockSelection).toBe(atUtils.lockSelection);
+ expect(atGestures.locksSelectionFor).toBe(atUtils.locksSelectionFor);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx
new file mode 100644
index 0000000000..deff82ea60
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx
@@ -0,0 +1,122 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useFingerScroll.test.tsx
+ * @input Uses vitest, Testing Library and touch-shaped events through the
+ * document's gesture host
+ * @output A finger's scroll reads true until the scroller's scrollend; a
+ * scroll with no finger down reads false; the page's own scroll through
+ * the document; the watch follows the ref's node and ends on unmount
+ * @position Unit tests of packages/core/src/gestures/useFingerScroll.ts
+ */
+
+import {render} from '@testing-library/react';
+import {useRef} from 'react';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {getGestureHost} from '../GestureHost';
+import {useFingerScroll} from '../useFingerScroll';
+import {coarsePrimaryPointer} from './pointerQuery';
+
+function touch(type: string, target: Element, down: boolean): void {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const entry = {identifier: 1, clientX: 5, clientY: 5, target};
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: down ? [entry] : []});
+ target.dispatchEvent(event);
+}
+
+let read: () => boolean = () => false;
+
+function List({other = false}: {other?: boolean}) {
+ const ref = useRef<HTMLDivElement>(null);
+ read = useFingerScroll(ref);
+ return other ? (
+ <section ref={ref} data-testid="list">
+ <p data-testid="row">row</p>
+ </section>
+ ) : (
+ <div ref={ref} data-testid="list">
+ <p data-testid="row">row</p>
+ </div>
+ );
+}
+
+function Page() {
+ read = useFingerScroll(document);
+ return <p data-testid="row">row</p>;
+}
+
+// A phone: the finger-scroll watch listens only where the primary pointer is
+// coarse.
+let restorePointer: () => void;
+beforeEach(() => {
+ restorePointer = coarsePrimaryPointer();
+});
+afterEach(() => {
+ restorePointer();
+});
+
+afterEach(() => {
+ read = () => false;
+});
+
+describe('useFingerScroll', () => {
+ it('is internal: the gestures barrel exports neither the hook nor the watch', async () => {
+ const gestures: Record<string, unknown> = await import('../index');
+ expect(gestures).not.toHaveProperty('useFingerScroll');
+ expect(gestures).not.toHaveProperty('isFingerScroll');
+ expect(gestures).not.toHaveProperty('watchFingerScrolls');
+ });
+
+ it("reads a finger's scroll until the scroller's scrollend, and the program's as false", () => {
+ const {getByTestId} = render(<List />);
+ const list = getByTestId('list');
+ list.dispatchEvent(new Event('scroll'));
+ expect(read()).toBe(false);
+ touch('touchstart', getByTestId('row'), true);
+ list.dispatchEvent(new Event('scroll'));
+ expect(read()).toBe(true);
+ // The lift starts the momentum: still the finger's.
+ touch('touchend', getByTestId('row'), false);
+ list.dispatchEvent(new Event('scroll'));
+ expect(read()).toBe(true);
+ list.dispatchEvent(new Event('scrollend'));
+ expect(read()).toBe(false);
+ });
+
+ it("reads a recognizer's own scroll as the program's, even with a finger resting inside", () => {
+ const {getByTestId} = render(<List />);
+ const list = getByTestId('list');
+ touch('touchstart', getByTestId('row'), true);
+ // A menu's edge autoscroll under the resting finger.
+ getGestureHost(document).ownScroll(list);
+ list.dispatchEvent(new Event('scroll'));
+ expect(read()).toBe(false);
+ touch('touchend', getByTestId('row'), false);
+ });
+
+ it('reads the page’s own scroll through the document', () => {
+ const {getByTestId} = render(<Page />);
+ touch('touchstart', getByTestId('row'), true);
+ document.dispatchEvent(new Event('scroll'));
+ expect(read()).toBe(true);
+ touch('touchend', getByTestId('row'), false);
+ document.dispatchEvent(new Event('scrollend'));
+ expect(read()).toBe(false);
+ });
+
+ it("follows the ref's node, and stops watching on unmount", () => {
+ const {getByTestId, rerender, unmount} = render(<List />);
+ rerender(<List other />);
+ const list = getByTestId('list');
+ expect(list.tagName).toBe('SECTION');
+ touch('touchstart', getByTestId('row'), true);
+ list.dispatchEvent(new Event('scroll'));
+ expect(read()).toBe(true);
+ touch('touchend', getByTestId('row'), false);
+ list.dispatchEvent(new Event('scrollend'));
+ const reader = read;
+ unmount();
+ expect(reader()).toBe(false);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/useGestureRecognizer.test.tsx b/packages/core/src/gestures/__tests__/useGestureRecognizer.test.tsx
index ba2e937236..8cbac9790d 100644
--- a/packages/core/src/gestures/__tests__/useGestureRecognizer.test.tsx
+++ b/packages/core/src/gestures/__tests__/useGestureRecognizer.test.tsx
@@ -11,15 +11,18 @@
*/
import {act, render} from '@testing-library/react';
-import {useRef} from 'react';
+import {StrictMode, useEffect, useRef} from 'react';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import type {SelectionLock} from '../GestureRecognizer';
import {getGestureHost} from '../GestureHost';
import {PanGestureRecognizer} from '../PanGestureRecognizer';
-import {TapGestureRecognizer} from '../TapGestureRecognizer';
import {TOUCH_ACTION_ATTRIBUTE} from '../touchActionRule';
import type {ControlEvent} from '../PressTracker';
-import {useGestureRecognizer, usePressTracker} from '../useGestureRecognizer';
-import {coarsePrimaryPointer} from './harness';
+import {lockSelection} from '../../utils/selectionLock';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {useGestureRecognizer} from '../useGestureRecognizer';
+import {usePressTracker} from '../usePressTracker';
+import {coarsePrimaryPointer, pointerQuery} from './pointerQuery';
function touch(
type: string,
@@ -64,7 +67,7 @@ function Draggable({
return <div data-testid="surface" ref={ref} />;
}
-// A phone: the document's host listens only where the pointer is coarse.
+// A phone: the host attaches only where the primary pointer is coarse.
let restorePointer: () => void = () => {};
beforeEach(() => {
restorePointer = coarsePrimaryPointer();
@@ -73,6 +76,7 @@ afterEach(() => {
restorePointer();
});
+/** Wait for the next animation frame, where the host writes touch-action. */
describe('useGestureRecognizer', () => {
afterEach(() => {
renders = 0;
@@ -205,7 +209,190 @@ describe('useGestureRecognizer', () => {
touch('touchend', surface, {id: 6, x: 30, y: 0}, 32, true);
});
- it('attaches nothing while disabled: no touch-action, no gesture (FR24)', () => {
+ it('attaches a recognizer for every pointer: a mouse drag pans where the primary pointer is fine (spec:AST-094 FR43)', () => {
+ const pointer = pointerQuery(false);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const onPan = vi.fn();
+ function Swipe() {
+ const ref = useRef<HTMLDivElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ onPan,
+ );
+ return <div data-testid="surface" ref={ref} />;
+ }
+ const {getByTestId, unmount} = render(<Swipe />);
+ const surface = getByTestId('surface');
+ const mouse = (type: string, x: number, time: number) => {
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 9,
+ pointerType: 'mouse',
+ clientX: x,
+ clientY: 0,
+ button: 0,
+ buttons: type === 'pointerup' ? 0 : 1,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ surface.dispatchEvent(event);
+ };
+ mouse('pointerdown', 0, 0);
+ mouse('pointermove', 30, 16);
+ expect(onPan).toHaveBeenCalled();
+ mouse('pointerup', 30, 32);
+ unmount();
+ expect(warn).not.toHaveBeenCalled();
+ } finally {
+ warn.mockRestore();
+ pointer.restore();
+ }
+ });
+
+ it('reports a recognizer that required the disabled one to fail after the isEnabled Effect, not inside it, in its recognized state (react-component-runtime INV2)', async () => {
+ const states: string[] = [];
+ const onSingle = vi.fn((recognizer: TapGestureRecognizer) => {
+ states.push(recognizer.state);
+ });
+ function Taps({isDoubleEnabled}: {isDoubleEnabled: boolean}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const double = useGestureRecognizer(
+ ref,
+ () => new TapGestureRecognizer({numberOfTapsRequired: 2}),
+ undefined,
+ {isEnabled: isDoubleEnabled},
+ );
+ const single = useGestureRecognizer(
+ ref,
+ () => new TapGestureRecognizer(),
+ onSingle,
+ );
+ useEffect(() => {
+ single.requireToFail(double);
+ }, [single, double]);
+ return <div data-testid="taps" ref={ref} />;
+ }
+ const {getByTestId, rerender} = render(<Taps isDoubleEnabled />);
+ const surface = getByTestId('taps');
+ touch('touchstart', surface, {id: 1, x: 5, y: 5}, 0);
+ touch('touchend', surface, {id: 1, x: 5, y: 5}, 40, true);
+ // The single tap waits for the double tap to fail.
+ expect(onSingle).not.toHaveBeenCalled();
+ // Turning the double tap off fails it in the Effect; the single tap
+ // waiting on it recognizes in a pass just after, so its caller hears it
+ // outside the Effect, reading the recognized state.
+ rerender(<Taps isDoubleEnabled={false} />);
+ expect(onSingle).not.toHaveBeenCalled();
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(states).toEqual(['ended']);
+ });
+
+ it('reports a recognizer that required one a replaced node cancelled after that layout Effect, not inside it (react-component-runtime INV2)', async () => {
+ const states: string[] = [];
+ function Nested({innerKey}: {innerKey: string}) {
+ const outerRef = useRef<HTMLDivElement>(null);
+ const innerRef = useRef<HTMLDivElement>(null);
+ const double = useGestureRecognizer(
+ innerRef,
+ () => new TapGestureRecognizer({numberOfTapsRequired: 2}),
+ );
+ const single = useGestureRecognizer(
+ outerRef,
+ () => new TapGestureRecognizer(),
+ recognizer => {
+ states.push(recognizer.state);
+ },
+ );
+ useEffect(() => {
+ single.requireToFail(double);
+ }, [single, double]);
+ return (
+ <div ref={outerRef}>
+ <div key={innerKey} data-testid="inner" ref={innerRef} />
+ </div>
+ );
+ }
+ const {getByTestId, rerender} = render(<Nested innerKey="first" />);
+ const inner = getByTestId('inner');
+ touch('touchstart', inner, {id: 2, x: 5, y: 5}, 0);
+ touch('touchend', inner, {id: 2, x: 5, y: 5}, 40, true);
+ expect(states).toEqual([]);
+ // The double tap's node is replaced: detaching it cancels its wait in a
+ // layout Effect, and the outer single tap recognizes just after.
+ rerender(<Nested innerKey="second" />);
+ expect(states).toEqual([]);
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(states).toEqual(['ended']);
+ });
+
+ it('serves a mouse press under a fine pointer, on an action group or not (family:action-groups FR5; spec:AST-094 FR43)', () => {
+ const primary = pointerQuery(false);
+ const states: string[] = [];
+ function Group({actionGroup}: {actionGroup: boolean}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new TapGestureRecognizer(),
+ recognizer => {
+ states.push(recognizer.state);
+ },
+ {actionGroup},
+ );
+ return (
+ <div data-testid="group" ref={ref}>
+ <button data-testid="action" type="button">
+ OK
+ </button>
+ </div>
+ );
+ }
+ const press = (target: Element, pointerId: number, time: number) => {
+ for (const [type, buttons] of [
+ ['pointerdown', 1],
+ ['pointerup', 0],
+ ] as const) {
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId,
+ pointerType: 'mouse',
+ clientX: 5,
+ clientY: 5,
+ button: 0,
+ buttons,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+ }
+ };
+ try {
+ const {getByTestId, rerender, unmount} = render(
+ <Group actionGroup={false} />,
+ );
+ const action = getByTestId('action');
+ // Not a group: served too, as every attachment (FR43).
+ press(action, 1, 0);
+ expect(states).toEqual(['ended']);
+ act(() => {
+ rerender(<Group actionGroup />);
+ });
+ press(action, 2, 1000);
+ expect(states).toEqual(['ended', 'ended']);
+ unmount();
+ } finally {
+ primary.restore();
+ }
+ });
+
+ it('attaches nothing while disabled: no touch-action, no gesture (FR24)', async () => {
const states: string[] = [];
const {getByTestId, rerender} = render(
<Draggable onPan={r => states.push(r.state)} />,
@@ -301,7 +488,7 @@ describe('useGestureRecognizer', () => {
expect(states).toEqual(['began']);
});
- it('keeps a recognizer that waits on one being disabled from calling its listener from the effect, and reports it after (INV2)', async () => {
+ it('keeps a recognizer that waits on one being disabled from calling its listener from the effect, and delivers it right after (INV2)', async () => {
const heard: string[] = [];
let inCommit = false;
function Pair({isDoubleTapEnabled}: {isDoubleTapEnabled: boolean}) {
@@ -330,13 +517,11 @@ describe('useGestureRecognizer', () => {
rerender(<Pair isDoubleTapEnabled={false} />);
});
inCommit = false;
- // Disabling the double tap fails it inside that Effect, and nothing
- // reports there: the single tap it held back is not lost, it recognizes
- // after React's update, where its listener reports as usual.
+ // Disabling the double tap fails it, and the single tap it held back
+ // recognizes in the arena's next pass, a microtask after that Effect: no
+ // listener hears it from the Effect, and the tap is still delivered.
expect(heard.filter(entry => entry.startsWith('effect:'))).toEqual([]);
- await act(async () => {
- await Promise.resolve();
- });
+ await Promise.resolve();
expect(heard).toEqual(['handler:ended']);
});
@@ -357,11 +542,13 @@ function Button({
onEvent,
cancelTravel,
isBraking,
+ selectionLock,
isDisabled = false,
}: {
onEvent: (event: ControlEvent) => void;
cancelTravel?: number;
isBraking?: () => boolean;
+ selectionLock?: SelectionLock;
isDisabled?: boolean;
}) {
const ref = useRef<HTMLButtonElement>(null);
@@ -369,6 +556,7 @@ function Button({
onControlEvent: event => onEvent(event),
cancelTravel,
isBraking,
+ selectionLock,
isEnabled: () => !isDisabled,
});
return (
@@ -380,8 +568,9 @@ function Button({
describe('usePressTracker', () => {
it('gives the host no listener while the control is disabled (FR24)', () => {
- const add = vi.spyOn(document, 'addEventListener');
- const remove = vi.spyOn(document, 'removeEventListener');
+ // The host listens through the window's input stream (utils/inputStream).
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
const {rerender, unmount} = render(
<Button onEvent={() => {}} isDisabled />,
);
@@ -399,72 +588,53 @@ describe('usePressTracker', () => {
remove.mockRestore();
});
- it("keeps the tracker's own ancestor veto when the caller gives none: a single tap by its kind, nothing else with the same counts (architecture:react-component-runtime INV13)", () => {
- let tracker: ReturnType<typeof usePressTracker> | null = null;
- function Tracked() {
+ it('ends a press whose control, the only enabled one, is disabled under the finger: nothing reports from the commit or at the lift', () => {
+ const events: ControlEvent[] = [];
+ const onEvent = (event: ControlEvent) => events.push(event);
+ const {getByTestId, rerender} = render(<Button onEvent={onEvent} />);
+ const button = getByTestId('button');
+ touch('touchstart', button, {id: 11, x: 1, y: 1}, 0);
+ expect(events).toEqual(['touchDown']);
+ act(() => {
+ rerender(<Button onEvent={onEvent} isDisabled />);
+ });
+ // The commit that disables it ends the press and calls back nothing.
+ expect(events).toEqual(['touchDown']);
+ touch('touchend', button, {id: 11, x: 1, y: 1}, 50, true);
+ expect(events).toEqual(['touchDown']);
+ });
+
+ it('ends a press whose control is disabled under the finger while another control keeps the host listening: the lift reports nothing', () => {
+ const events: ControlEvent[] = [];
+ const onEvent = (event: ControlEvent) => events.push(event);
+ function Other() {
const ref = useRef<HTMLButtonElement>(null);
- tracker = usePressTracker(ref);
+ usePressTracker(ref);
return (
- <button ref={ref} type="button">
- Go
+ <button data-testid="other" ref={ref} type="button">
+ Other
</button>
);
}
- render(<Tracked />);
- const tap = new TapGestureRecognizer({});
- expect(tracker!.allowsAncestorRecognizer(tap)).toBe(false);
- // A discrete recognizer that is not a tap, carrying the same counts.
- const notATap = {
- kind: 'swipe',
- isDiscrete: true,
- numberOfTapsRequired: 1,
- numberOfTouchesRequired: 1,
- view: null,
- };
- expect(tracker!.allowsAncestorRecognizer(notATap)).toBe(true);
- });
-
- it('rebuilds its tracker when trackingExpansion, highlightDelay, cancelTravel or quickTapFlash change', () => {
- const trackers: unknown[] = [];
- function Tracked(props: {
- trackingExpansion?: number;
- highlightDelay?: 'inScrollers' | 'always' | 'never';
- cancelTravel?: number;
- quickTapFlash?: number;
- label?: string;
- }) {
- const ref = useRef<HTMLButtonElement>(null);
- trackers.push(usePressTracker(ref, props));
+ function Pair({isDisabled}: {isDisabled: boolean}) {
return (
- <button ref={ref} type="button">
- {props.label ?? 'Go'}
- </button>
+ <>
+ <Button onEvent={onEvent} isDisabled={isDisabled} />
+ <Other />
+ </>
);
}
- const {rerender} = render(<Tracked cancelTravel={70} />);
- rerender(<Tracked cancelTravel={70} label="Same options" />);
- expect(trackers[1]).toBe(trackers[0]);
- rerender(<Tracked cancelTravel={20} />);
- expect(trackers[2]).not.toBe(trackers[1]);
- rerender(<Tracked cancelTravel={20} trackingExpansion={30} />);
- expect(trackers[3]).not.toBe(trackers[2]);
- rerender(
- <Tracked
- cancelTravel={20}
- trackingExpansion={30}
- highlightDelay="never"
- />,
- );
- expect(trackers[4]).not.toBe(trackers[3]);
- rerender(
- <Tracked
- cancelTravel={20}
- trackingExpansion={30}
- highlightDelay="never"
- quickTapFlash={0}
- />,
- );
- expect(trackers[5]).not.toBe(trackers[4]);
+ const {getByTestId, rerender} = render(<Pair isDisabled={false} />);
+ const button = getByTestId('button');
+ touch('touchstart', button, {id: 12, x: 1, y: 1}, 0);
+ expect(events).toEqual(['touchDown']);
+ act(() => {
+ rerender(<Pair isDisabled />);
+ });
+ expect(events).toEqual(['touchDown']);
+ // A disabled control tracks no touch: the lift is no touchUpInside.
+ touch('touchend', button, {id: 12, x: 1, y: 1}, 50, true);
+ expect(events).toEqual(['touchDown']);
});
it('reports UIControl events for a tap', () => {
@@ -478,6 +648,37 @@ describe('usePressTracker', () => {
expect(events).toEqual(['touchDown', 'touchUpInside']);
});
+ it('locks selection and the callout for each press of a control whose hold acts, given the lock (spec:AST-094 FR41)', () => {
+ const {getByTestId} = render(
+ <Button onEvent={() => {}} selectionLock={lockSelection} />,
+ );
+ const button = getByTestId('button');
+ // Where iOS WebKit does not run, the lock refuses a selection by
+ // cancelling selectstart (jsdom has no touch callout).
+ const refuses = () => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ button.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ touch('touchstart', button, {id: 3, x: 1, y: 1}, 0);
+ expect(refuses()).toBe(true);
+ touch('touchend', button, {id: 3, x: 1, y: 1}, 50, true);
+ expect(refuses()).toBe(false);
+ });
+
+ it('takes an option changed after mount from the next touch', () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId, rerender} = render(
+ <Button onEvent={event => events.push(event)} />,
+ );
+ rerender(<Button onEvent={event => events.push(event)} cancelTravel={5} />);
+ const button = getByTestId('button');
+ touch('touchstart', button, {id: 7, x: 1, y: 1}, 0);
+ touch('touchmove', button, {id: 7, x: 1, y: 11}, 16);
+ expect(events).toEqual(['touchDown', 'touchCancel']);
+ touch('touchend', button, {id: 7, x: 1, y: 11}, 50, true);
+ });
+
it('ends a held press on unmount without calling back from the effect', () => {
const highlights: boolean[] = [];
const events: ControlEvent[] = [];
@@ -502,6 +703,69 @@ describe('usePressTracker', () => {
expect(events).toEqual(seenEvents);
});
+ it('gives a press tracker a mouse press where the primary pointer is fine, with or without perEventPointer (spec:AST-094 FR43, DEC-21)', () => {
+ const pointer = pointerQuery(false);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const held: ControlEvent[] = [];
+ const inactive: ControlEvent[] = [];
+ function Stepper({
+ events,
+ perEventPointer,
+ testId,
+ }: {
+ events: ControlEvent[];
+ perEventPointer: boolean;
+ testId: string;
+ }) {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ perEventPointer,
+ });
+ return (
+ <button data-testid={testId} ref={ref} type="button">
+ +
+ </button>
+ );
+ }
+ const {getByTestId} = render(
+ <>
+ <Stepper events={held} perEventPointer testId="held" />
+ <Stepper events={inactive} perEventPointer={false} testId="other" />
+ </>,
+ );
+ const mouse = (type: string, target: Element, id: number) => {
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: id,
+ pointerType: 'mouse',
+ clientX: 5,
+ clientY: 5,
+ button: 0,
+ buttons: type === 'pointerdown' ? 1 : 0,
+ });
+ target.dispatchEvent(event);
+ };
+ const stepper = getByTestId('held');
+ boundsOf(stepper, 44, 44);
+ mouse('pointerdown', stepper, 1);
+ mouse('pointerup', stepper, 1);
+ // A mouse press is a press (DEC-21).
+ expect(held).toEqual(['touchDown', 'touchUpInside']);
+ const other = getByTestId('other');
+ boundsOf(other, 44, 44);
+ mouse('pointerdown', other, 2);
+ mouse('pointerup', other, 2);
+ expect(inactive).toEqual(['touchDown', 'touchUpInside']);
+ } finally {
+ warn.mockRestore();
+ pointer.restore();
+ }
+ });
+
it('passes isBraking through to the tracker', () => {
const events: ControlEvent[] = [];
const isBraking = vi.fn(() => true);
@@ -536,6 +800,84 @@ describe('usePressTracker', () => {
expect(events).toEqual([]);
});
+ function PressInTaps({
+ isDoubleEnabled,
+ hasSingle,
+ onEvent,
+ }: {
+ isDoubleEnabled: boolean;
+ hasSingle: boolean;
+ onEvent: (event: ControlEvent | 'highlight' | 'unhighlight') => void;
+ }) {
+ const outerRef = useRef<HTMLDivElement>(null);
+ const innerRef = useRef<HTMLButtonElement>(null);
+ const double = useGestureRecognizer(
+ outerRef,
+ () => new TapGestureRecognizer({numberOfTapsRequired: 2}),
+ undefined,
+ {isEnabled: isDoubleEnabled},
+ );
+ const single = useGestureRecognizer(
+ outerRef,
+ () => new TapGestureRecognizer(),
+ undefined,
+ {isEnabled: hasSingle},
+ );
+ useEffect(() => {
+ single.requireToFail(double);
+ }, [single, double]);
+ usePressTracker(innerRef, {
+ onControlEvent: onEvent,
+ onHighlightChange: isHighlighted =>
+ onEvent(isHighlighted ? 'highlight' : 'unhighlight'),
+ });
+ return (
+ <div ref={outerRef}>
+ <button data-testid="press" ref={innerRef} type="button" />
+ </div>
+ );
+ }
+
+ it.each([
+ ['alone', false],
+ ['with a single tap waiting on it', true],
+ ])(
+ 'ends a press that waits on an ancestor double tap after, not inside, the isEnabled Effect that turns it off (%s; react-component-runtime INV2)',
+ async (_event, hasSingle) => {
+ const events: (ControlEvent | 'highlight' | 'unhighlight')[] = [];
+ const {getByTestId, rerender} = render(
+ <PressInTaps
+ isDoubleEnabled
+ hasSingle={hasSingle}
+ onEvent={event => events.push(event)}
+ />,
+ );
+ const button = getByTestId('press');
+ touch('touchstart', button, {id: 21, x: 1, y: 1}, 0);
+ touch('touchend', button, {id: 21, x: 1, y: 1}, 40, true);
+ const before = [...events];
+ // Turning the double tap off fails it in the Effect: whatever that
+ // arena pass resolves for the press reaches no caller callback.
+ rerender(
+ <PressInTaps
+ isDoubleEnabled={false}
+ hasSingle={hasSingle}
+ onEvent={event => events.push(event)}
+ />,
+ );
+ expect(events).toEqual(before);
+ // Just after it, the press ends and un-highlights: nothing is left
+ // highlighted.
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(events.slice(before.length)).toEqual([
+ 'touchUpInside',
+ 'unhighlight',
+ ]);
+ },
+ );
+
it('tracks the element behind the ref when it is replaced (INV6)', () => {
const events: ControlEvent[] = [];
function Swapped({id}: {id: string}) {
@@ -567,4 +909,433 @@ describe('usePressTracker', () => {
expect(events).toEqual([]);
brake.mockRestore();
});
+
+ it("keeps the tracker's own ancestor veto when the caller gives none: a single tap by its kind, nothing else with the same counts (architecture:react-component-runtime INV13)", () => {
+ let tracker: ReturnType<typeof usePressTracker> | null = null;
+ function Tracked() {
+ const ref = useRef<HTMLButtonElement>(null);
+ tracker = usePressTracker(ref);
+ return (
+ <button ref={ref} type="button">
+ Go
+ </button>
+ );
+ }
+ render(<Tracked />);
+ const tap = new TapGestureRecognizer({});
+ expect(tracker!.allowsAncestorRecognizer(tap)).toBe(false);
+ // A discrete recognizer that is not a tap, carrying the same counts.
+ const notATap = {
+ kind: 'swipe',
+ isDiscrete: true,
+ numberOfTapsRequired: 1,
+ numberOfTouchesRequired: 1,
+ view: null,
+ };
+ expect(tracker!.allowsAncestorRecognizer(notATap)).toBe(true);
+ });
+});
+
+function Swappable({
+ as,
+ onPan,
+}: {
+ as: 'none' | 'div' | 'span';
+ onPan: (recognizer: PanGestureRecognizer) => void;
+}) {
+ const ref = useRef<HTMLElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ onPan,
+ );
+ if (as === 'none') {
+ return null;
+ }
+ return as === 'div' ? (
+ <div data-testid="node" ref={ref as React.RefObject<HTMLDivElement>} />
+ ) : (
+ <span data-testid="node" ref={ref} />
+ );
+}
+
+describe('useGestureRecognizer follows the element behind its ref', () => {
+ it('attaches to a node rendered after mount, and to a node swapped behind the same ref', () => {
+ const states: string[] = [];
+ const onPan = (r: PanGestureRecognizer) => states.push(r.state);
+ const {getByTestId, rerender} = render(
+ <Swappable as="none" onPan={onPan} />,
+ );
+ rerender(<Swappable as="div" onPan={onPan} />);
+ const first = getByTestId('node');
+ touch('touchstart', first, {id: 1, x: 0, y: 0}, 0);
+ touch('touchmove', first, {id: 1, x: 30, y: 0}, 16);
+ touch('touchend', first, {id: 1, x: 30, y: 0}, 32, true);
+ expect(states).toContain('began');
+ states.length = 0;
+ rerender(<Swappable as="span" onPan={onPan} />);
+ const second = getByTestId('node');
+ expect(second).not.toBe(first);
+ touch('touchstart', second, {id: 2, x: 0, y: 0}, 100);
+ touch('touchmove', second, {id: 2, x: 30, y: 0}, 116);
+ touch('touchend', second, {id: 2, x: 30, y: 0}, 132, true);
+ expect(states).toContain('began');
+ // The detached node no longer drives it.
+ states.length = 0;
+ touch('touchstart', first, {id: 3, x: 0, y: 0}, 200);
+ touch('touchmove', first, {id: 3, x: 30, y: 0}, 216);
+ touch('touchend', first, {id: 3, x: 30, y: 0}, 232, true);
+ expect(states).toEqual([]);
+ });
+
+ it('reports nothing from cleanup when it unmounts mid-gesture', () => {
+ const states: string[] = [];
+ const {getByTestId, unmount} = render(
+ <Draggable onPan={r => states.push(r.state)} />,
+ );
+ const surface = getByTestId('surface');
+ touch('touchstart', surface, {id: 5, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 5, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ unmount();
+ expect(states).toEqual(['began']);
+ });
+});
+
+function LaterButton({
+ isShown,
+ onEvent,
+ onHighlight,
+ isBraking,
+ highlightDelay,
+}: {
+ isShown: boolean;
+ onEvent?: (event: ControlEvent) => void;
+ onHighlight?: (isOn: boolean) => void;
+ isBraking?: () => boolean;
+ highlightDelay?: 'inScrollers' | 'always' | 'never';
+}) {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => onEvent?.(event),
+ onHighlightChange: isOn => onHighlight?.(isOn),
+ isBraking,
+ highlightDelay,
+ });
+ return isShown ? (
+ <button data-testid="stepper" ref={ref} type="button">
+ +
+ </button>
+ ) : null;
+}
+
+describe('usePressTracker follows its element and its options', () => {
+ it('tracks a node rendered after mount', () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId, rerender} = render(
+ <LaterButton isShown={false} onEvent={event => events.push(event)} />,
+ );
+ rerender(<LaterButton isShown onEvent={event => events.push(event)} />);
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ touch('touchend', stepper, {id: 1, x: 2, y: 2}, 60, true);
+ expect(events).toContain('touchUpInside');
+ });
+
+ it("uses the caller's brake", () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId} = render(
+ <LaterButton
+ isShown
+ isBraking={() => true}
+ onEvent={event => events.push(event)}
+ />,
+ );
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ touch('touchend', stepper, {id: 1, x: 2, y: 2}, 60, true);
+ expect(events).not.toContain('touchDown');
+ expect(events).not.toContain('touchUpInside');
+ });
+
+ it('takes a highlight delay changed after mount from the next touch', () => {
+ vi.useFakeTimers();
+ const highlights: boolean[] = [];
+ const {getByTestId, rerender} = render(
+ <LaterButton
+ isShown
+ highlightDelay="never"
+ onHighlight={isOn => highlights.push(isOn)}
+ />,
+ );
+ rerender(
+ <LaterButton
+ isShown
+ highlightDelay="always"
+ onHighlight={isOn => highlights.push(isOn)}
+ />,
+ );
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ // 'always' waits the content-touch delay before highlighting.
+ expect(highlights).toEqual([]);
+ touch('touchend', stepper, {id: 1, x: 2, y: 2}, 400, true);
+ vi.useRealTimers();
+ });
+
+ it('calls no callback from cleanup when it unmounts while highlighted', () => {
+ const highlights: boolean[] = [];
+ const {getByTestId, unmount} = render(
+ <LaterButton
+ isShown
+ highlightDelay="never"
+ onHighlight={isOn => highlights.push(isOn)}
+ />,
+ );
+ const stepper = getByTestId('stepper');
+ touch('touchstart', stepper, {id: 1, x: 2, y: 2}, 0);
+ expect(highlights).toEqual([true]);
+ unmount();
+ expect(highlights).toEqual([true]);
+ });
+});
+
+function boundsOf(element: HTMLElement, width: number, height: number): void {
+ Object.defineProperty(element, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => ({
+ left: 0,
+ top: 0,
+ right: width,
+ bottom: height,
+ width,
+ height,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }),
+ });
+}
+
+function SwappedColumn({
+ which,
+ freshRef,
+ onEvent,
+}: {
+ which: 'a' | 'b';
+ freshRef: boolean;
+ onEvent: (event: ControlEvent) => void;
+}) {
+ const stableRef = useRef<HTMLButtonElement>(null);
+ const fresh = {current: null as HTMLButtonElement | null};
+ const ref = freshRef ? fresh : stableRef;
+ usePressTracker(ref, {onControlEvent: event => onEvent(event)});
+ return which === 'a' ? (
+ <button key="a" data-testid="a" ref={ref} type="button">
+ A
+ </button>
+ ) : (
+ <button key="b" data-testid="b" ref={ref} type="button">
+ B
+ </button>
+ );
+}
+
+describe('usePressTracker hit-tests the element behind its ref now', () => {
+ for (const freshRef of [false, true]) {
+ it(`judges a lift against the swapped node's bounds (${freshRef ? 'a new ref object' : 'the same ref'})`, () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId, rerender} = render(
+ <SwappedColumn
+ which="a"
+ freshRef={freshRef}
+ onEvent={event => events.push(event)}
+ />,
+ );
+ rerender(
+ <SwappedColumn
+ which="b"
+ freshRef={freshRef}
+ onEvent={event => events.push(event)}
+ />,
+ );
+ const b = getByTestId('b');
+ boundsOf(b, 100, 40);
+ touch('touchstart', b, {id: 1, x: 10, y: 10}, 0);
+ // Far outside B, past the tracking expansion.
+ touch('touchmove', b, {id: 1, x: 400, y: 400}, 16);
+ touch('touchend', b, {id: 1, x: 400, y: 400}, 32, true);
+ expect(events).toContain('touchDown');
+ expect(events).toContain('touchUpOutside');
+ expect(events).not.toContain('touchUpInside');
+ });
+ }
+});
+
+function SwappedSurface({
+ which,
+ onPan,
+}: {
+ which: 'a' | 'b';
+ onPan: (recognizer: PanGestureRecognizer) => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ onPan,
+ );
+ return which === 'a' ? (
+ <div key="a" data-testid="a" ref={ref} />
+ ) : (
+ <div key="b" data-testid="b" ref={ref} />
+ );
+}
+
+describe('useGestureRecognizer follows a replaced node', () => {
+ for (const strict of [false, true]) {
+ it(`cancels a gesture in flight without calling the listener from the effect${strict ? ' (StrictMode)' : ''}`, () => {
+ const states: string[] = [];
+ const wrap = (node: React.ReactElement) =>
+ strict ? <StrictMode>{node}</StrictMode> : node;
+ const {getByTestId, rerender} = render(
+ wrap(<SwappedSurface which="a" onPan={r => states.push(r.state)} />),
+ );
+ const a = getByTestId('a');
+ touch('touchstart', a, {id: 3, x: 0, y: 0}, 0);
+ touch('touchmove', a, {id: 3, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ rerender(
+ wrap(<SwappedSurface which="b" onPan={r => states.push(r.state)} />),
+ );
+ // The replaced node's cancel comes from a layout effect: no callback.
+ expect(states).toEqual(['began']);
+ // The new node drives the same recognizer.
+ const b = getByTestId('b');
+ touch('touchstart', b, {id: 4, x: 0, y: 0}, 100);
+ touch('touchmove', b, {id: 4, x: 30, y: 0}, 116);
+ expect(states).toEqual(['began', 'began']);
+ touch('touchend', b, {id: 4, x: 30, y: 0}, 132, true);
+ });
+ }
+});
+
+describe('usePressTracker keeps its press through an option change', () => {
+ for (const strict of [false, true]) {
+ it(`a press in progress survives a rerender with new options${strict ? ' (StrictMode)' : ''}`, () => {
+ const events: ControlEvent[] = [];
+ const highlights: boolean[] = [];
+ function Held({cancelTravel}: {cancelTravel?: number}) {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ onHighlightChange: isHighlighted => highlights.push(isHighlighted),
+ cancelTravel,
+ });
+ return (
+ <button data-testid="held" ref={ref} type="button">
+ Go
+ </button>
+ );
+ }
+ const wrap = (node: React.ReactElement) =>
+ strict ? <StrictMode>{node}</StrictMode> : node;
+ const {getByTestId, rerender} = render(wrap(<Held />));
+ const button = getByTestId('held');
+ touch('touchstart', button, {id: 6, x: 1, y: 1}, 0);
+ expect(highlights).toEqual([true]);
+ rerender(wrap(<Held cancelTravel={50} />));
+ // Still pressed: the tracker was not rebuilt or disposed.
+ expect(highlights).toEqual([true]);
+ touch('touchend', button, {id: 6, x: 1, y: 1}, 50, true);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ });
+ }
+});
+
+describe('the hooks let go of an element removed while they stay mounted', () => {
+ it('useGestureRecognizer cancels its gesture without calling back, and works on a new element', () => {
+ const states: string[] = [];
+ function Maybe({shown}: {shown: boolean}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ r => states.push(r.state),
+ );
+ return shown ? <div data-testid="maybe" ref={ref} /> : null;
+ }
+ const {getByTestId, rerender} = render(<Maybe shown />);
+ const first = getByTestId('maybe');
+ touch('touchstart', first, {id: 11, x: 0, y: 0}, 0);
+ touch('touchmove', first, {id: 11, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ rerender(<Maybe shown={false} />);
+ expect(states).toEqual(['began']);
+ rerender(<Maybe shown />);
+ const second = getByTestId('maybe');
+ touch('touchstart', second, {id: 12, x: 0, y: 0}, 100);
+ touch('touchmove', second, {id: 12, x: 30, y: 0}, 116);
+ expect(states).toEqual(['began', 'began']);
+ touch('touchend', second, {id: 12, x: 30, y: 0}, 132, true);
+ });
+
+ it('usePressTracker ends its press without calling back, and presses a new element', () => {
+ const events: ControlEvent[] = [];
+ const highlights: boolean[] = [];
+ function Maybe({shown}: {shown: boolean}) {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ onHighlightChange: isHighlighted => highlights.push(isHighlighted),
+ });
+ return shown ? (
+ <button data-testid="maybe" ref={ref} type="button">
+ Go
+ </button>
+ ) : null;
+ }
+ const {getByTestId, rerender} = render(<Maybe shown />);
+ touch('touchstart', getByTestId('maybe'), {id: 13, x: 1, y: 1}, 0);
+ expect(highlights).toEqual([true]);
+ rerender(<Maybe shown={false} />);
+ expect(highlights).toEqual([true]);
+ expect(events).toEqual(['touchDown']);
+ rerender(<Maybe shown />);
+ const button = getByTestId('maybe');
+ touch('touchstart', button, {id: 14, x: 1, y: 1}, 100);
+ touch('touchend', button, {id: 14, x: 1, y: 1}, 150, true);
+ expect(events).toEqual(['touchDown', 'touchDown', 'touchUpInside']);
+ });
+});
+
+describe('usePressTracker reads trackingExpansion as it is now', () => {
+ it('a smaller expansion takes effect without rebuilding the tracker', () => {
+ const events: ControlEvent[] = [];
+ function Tracked({expansion}: {expansion: number}) {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ trackingExpansion: expansion,
+ });
+ return (
+ <button data-testid="tracked" ref={ref} type="button">
+ Go
+ </button>
+ );
+ }
+ const {getByTestId, rerender} = render(<Tracked expansion={70} />);
+ const button = getByTestId('tracked');
+ boundsOf(button, 100, 40);
+ touch('touchstart', button, {id: 15, x: 10, y: 10}, 0);
+ // 30 px below the bottom edge: inside a 70 px expansion.
+ touch('touchmove', button, {id: 15, x: 10, y: 70}, 16);
+ expect(events).not.toContain('touchDragExit');
+ rerender(<Tracked expansion={10} />);
+ // The same point is outside a 10 px expansion, mid-press.
+ touch('touchmove', button, {id: 15, x: 10, y: 71}, 32);
+ expect(events).toContain('touchDragExit');
+ touch('touchend', button, {id: 15, x: 10, y: 71}, 48, true);
+ expect(events).toContain('touchUpOutside');
+ });
});
diff --git a/packages/core/src/gestures/__tests__/watcherRecognizer.test.ts b/packages/core/src/gestures/__tests__/watcherRecognizer.test.ts
new file mode 100644
index 0000000000..06cf3b523a
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/watcherRecognizer.test.ts
@@ -0,0 +1,244 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file watcherRecognizer.test.ts
+ * @input Uses vitest, the arena harness, GestureHost and the pan recognizer
+ * @output Checks the `claimsTouches: false` watcher: it never claims or
+ * blocks a scroll, prevents nothing and is prevented by nothing, and
+ * follows a touch the browser takes for a scroll to the lift
+ * @position Test for GestureRecognizerOptions.claimsTouches
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {GestureHost} from '../GestureHost';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {createHarness, ManualClock, RecordingConsumer} from './harness';
+import {coarsePrimaryPointer} from './pointerQuery';
+
+describe('a recognizer that never claims (a watcher)', () => {
+ let detach: (() => void)[] = [];
+ // A phone: the host attaches only where the primary pointer is coarse.
+ let restorePointer: () => void;
+ beforeEach(() => {
+ restorePointer = coarsePrimaryPointer();
+ });
+ afterEach(() => {
+ detach.forEach(release => release());
+ detach = [];
+ document.body.innerHTML = '';
+ restorePointer();
+ });
+
+ it('runs alongside a claiming pan on the same touch, and claims nothing', () => {
+ const h = createHarness();
+ const watcher = new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ });
+ const sheet = new PanGestureRecognizer({
+ name: 'sheet',
+ direction: 'vertical',
+ });
+ const finger = h
+ .finger(1)
+ .down(0, 100, 0, {recognizers: [sheet, watcher]})
+ .move(0, 115, 16);
+ expect(watcher.state).toBe('began');
+ expect(sheet.state).toBe('began');
+ expect(h.claims).toEqual([1]);
+ finger.up(32);
+ });
+
+ it('cancels no press under it when it begins: a held control keeps its touch (spec:AST-094 FR15, FR19)', () => {
+ const h = createHarness();
+ const watcher = new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ });
+ const press = new RecordingConsumer();
+ const finger = h
+ .finger(1)
+ .down(0, 100, 0, {recognizers: [watcher], consumer: press})
+ .move(0, 130, 16);
+ expect(watcher.state).toBe('began');
+ expect(press.events).not.toContain('cancelled:1');
+ finger.up(32);
+ expect(press.events).toContain('ended:1');
+ });
+
+ it('follows a touch the browser took for a scroll until the lift', () => {
+ const h = createHarness();
+ const watcher = new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ });
+ const finger = h
+ .finger(1)
+ .down(0, 100, 0, {recognizers: [watcher]})
+ .move(0, 115, 16);
+ expect(watcher.state).toBe('began');
+ finger.takenByBrowser(20);
+ finger.move(0, 160, 32);
+ expect(watcher.state).toBe('changed');
+ finger.up(48);
+ expect(h.log).toContain('watcher:ended@48');
+ });
+
+ it('gets only passive touchmove listeners from the host', () => {
+ document.body.innerHTML = '<div id="page"></div>';
+ const page = document.getElementById('page') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const added = vi.spyOn(page, 'addEventListener');
+ detach.push(
+ host.attach(
+ page,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ {manageStyle: false},
+ ),
+ );
+ const event = new Event('touchstart', {bubbles: true, cancelable: true});
+ const entry = {identifier: 1, clientX: 10, clientY: 10, target: page};
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: [entry]});
+ page.dispatchEvent(event);
+ const blocking = added.mock.calls.filter(
+ ([type, , options]) =>
+ type === 'touchmove' &&
+ (options as AddEventListenerOptions | undefined)?.passive === false,
+ );
+ expect(blocking).toHaveLength(0);
+ });
+
+ it('gets only passive target listeners for its touch, touchend included, while a tap on the same kind of touch gets a cancelable touchend (spec:AST-094 FR20)', () => {
+ document.body.innerHTML = '<div id="page"></div><div id="button"></div>';
+ const page = document.getElementById('page') as HTMLElement;
+ const button = document.getElementById('button') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const onPage = vi.spyOn(page, 'addEventListener');
+ const onButton = vi.spyOn(button, 'addEventListener');
+ detach.push(
+ host.attach(
+ page,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ {manageStyle: false},
+ ),
+ host.attach(button, new TapGestureRecognizer({name: 'tap'})),
+ );
+ const touchDown = (target: HTMLElement, identifier: number) => {
+ const event = new Event('touchstart', {bubbles: true, cancelable: true});
+ const entry = {identifier, clientX: 10, clientY: 10, target};
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: [entry]});
+ target.dispatchEvent(event);
+ };
+ const passivity = (spy: typeof onPage, type: string) =>
+ spy.mock.calls
+ .filter(([listened]) => listened === type)
+ .map(
+ ([, , options]) =>
+ (options as AddEventListenerOptions | undefined)?.passive,
+ );
+ touchDown(page, 1);
+ expect(passivity(onPage, 'touchmove')).toEqual([true]);
+ expect(passivity(onPage, 'touchend')).toEqual([true]);
+ expect(passivity(onPage, 'touchcancel')).toEqual([true]);
+ touchDown(button, 2);
+ expect(passivity(onButton, 'touchend')).toEqual([false]);
+ });
+
+ it('alone, leaves the host only passive document and window listeners; a claiming recognizer brings the cancelable touchend, contextmenu and click (spec:AST-094 FR20)', () => {
+ document.body.innerHTML = '<div id="page"></div><div id="strip"></div>';
+ const page = document.getElementById('page') as HTMLElement;
+ const strip = document.getElementById('strip') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const active = () => {
+ const listed: string[] = [];
+ for (const [target, spy] of [
+ ['document', onDocument],
+ ['window', onWindow],
+ ] as const) {
+ for (const [type, , options] of spy.mock.calls) {
+ if (typeof options === 'object' && options.passive === false) {
+ listed.push(`${target} ${type}`);
+ }
+ }
+ }
+ return listed;
+ };
+ const onDocument = vi.spyOn(document, 'addEventListener');
+ const onWindow = vi.spyOn(window, 'addEventListener');
+ detach.push(
+ host.attach(
+ page,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ {manageStyle: false},
+ ),
+ );
+ expect(active()).toEqual([]);
+ detach.push(
+ host.attach(
+ strip,
+ new PanGestureRecognizer({name: 'claimer', direction: 'horizontal'}),
+ ),
+ );
+ // At this layer every host listener comes through the shared input
+ // stream (utils/inputStream.ts), on the window's capture phase; clicks
+ // are the click guard's, whose listener comes only once a gesture acts.
+ expect(active().sort()).toEqual(['window contextmenu', 'window touchend']);
+ });
+
+ it('leaves the browser every touch behavior: its direction writes no touch-action', () => {
+ document.body.innerHTML = '<div id="list"></div><div id="row"></div>';
+ const list = document.getElementById('list') as HTMLElement;
+ const row = document.getElementById('row') as HTMLElement;
+ const host = new GestureHost(document, {clock: new ManualClock()});
+ const listStyle = vi.spyOn(list.style, 'setProperty');
+ detach.push(
+ host.attach(
+ list,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ ),
+ host.attach(
+ row,
+ new PanGestureRecognizer({
+ name: 'watcher',
+ direction: 'vertical',
+ claimsTouches: false,
+ }),
+ ),
+ // A claiming pan beside it on the same element keeps its own.
+ host.attach(
+ row,
+ new PanGestureRecognizer({name: 'swipe', direction: 'horizontal'}),
+ ),
+ );
+ expect(list.hasAttribute('data-astryx-touch-action')).toBe(false);
+ expect(row.getAttribute('data-astryx-touch-action')).toBe(
+ 'pan-y pinch-zoom',
+ );
+ expect(listStyle).not.toHaveBeenCalledWith(
+ 'touch-action',
+ expect.anything(),
+ );
+ });
+});
diff --git a/packages/core/src/gestures/fingerScroll.ts b/packages/core/src/gestures/fingerScroll.ts
new file mode 100644
index 0000000000..1e429e2a22
--- /dev/null
+++ b/packages/core/src/gestures/fingerScroll.ts
@@ -0,0 +1,208 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file fingerScroll.ts
+ * @input A scroller (an element, or the document for the page's own scroll),
+ * its document's scroll and scrollend events, and the gesture host's
+ * finger record
+ * @output Exports watchFingerScrolls and isFingerScroll
+ * @position Finger-scroll watch of packages/core/src/gestures (useFingerScroll
+ * reads it), in its own module so a page that never asks never ships it;
+ * internal to the touch module, not in the gestures barrel
+ *
+ * A watched scroller's scroll is a finger's from a scroll event while a
+ * finger that landed inside it is down, until the scroller's own `scrollend`
+ * (the momentum after the lift is still the finger's). A scroll that ends
+ * while its finger still rests there stays the finger's until the lift. A
+ * scroll the program starts while no finger is down there (`scrollTo`, a
+ * status-bar tap) is not. Where the browser sends no `scrollend`, a quiet
+ * spell of `SCROLL_END_FALLBACK_MS` after its last scroll event ends a
+ * finger's scroll instead. The host keeps the one finger record; this module
+ * adds only passive scroll listeners, and only while something is watched.
+ */
+
+import {subscribeInput} from '../utils/inputStream';
+import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer';
+import type {GestureHost} from './GestureHost';
+
+/**
+ * Where the browser sends no `scrollend`, how long a finger-driven scroller
+ * stays quiet (no scroll event) before its scroll counts as ended, in ms:
+ * longer than the gap between a momentum scroll's events, short enough that
+ * a program's scroll right after it is not read as the finger's.
+ */
+const SCROLL_END_FALLBACK_MS = 150;
+
+interface Watch {
+ /** Watched scrollers, and how many watchers each has. */
+ readonly scrollers: Map<Node, number>;
+ /** Watched scrollers whose current scroll is a finger's. */
+ readonly fingerScrollers: Set<Node>;
+ /** Finger scrolls whose `scrollend` came while the finger still rested. */
+ readonly endedWhileDown: Set<Node>;
+ stop: (() => void) | null;
+}
+
+const watches = new WeakMap<GestureHost, Watch>();
+
+function start(host: GestureHost, watch: Watch): () => void {
+ const doc = host.document;
+ const scrollerOf = (event: Event): Node | null => {
+ const target = event.target === doc ? doc : event.target;
+ return target instanceof Node ? target : null;
+ };
+ // A finger's scroll ends at the scroller's scrollend, or, where the
+ // browser sends none, after a quiet spell.
+ const endScroll = (scroller: Node): void => {
+ if (!watch.fingerScrollers.has(scroller)) {
+ return;
+ }
+ if (host.isFingerDownIn(scroller)) {
+ // The finger still rests there: the scroll is its until the lift.
+ watch.endedWhileDown.add(scroller);
+ } else {
+ watch.fingerScrollers.delete(scroller);
+ }
+ };
+ const scrollEndFallbacks = new Map<Node, ReturnType<typeof setTimeout>>();
+ const clearScrollEndFallback = (scroller: Node): void => {
+ const timer = scrollEndFallbacks.get(scroller);
+ if (timer != null) {
+ clearTimeout(timer);
+ scrollEndFallbacks.delete(scroller);
+ }
+ };
+ const hasScrollEnd = (): boolean => {
+ const view = doc.defaultView;
+ return view != null && 'onscrollend' in view;
+ };
+ const onScroll = (event: Event): void => {
+ const scroller = scrollerOf(event);
+ // A recognizer's own scroll (a menu's edge autoscroll) is never the
+ // finger's, even with a finger resting inside.
+ if (
+ scroller == null ||
+ !watch.scrollers.has(scroller) ||
+ host.isOwnScroll(scroller)
+ ) {
+ return;
+ }
+ watch.endedWhileDown.delete(scroller);
+ if (host.isFingerDownIn(scroller)) {
+ watch.fingerScrollers.add(scroller);
+ }
+ if (watch.fingerScrollers.has(scroller) && !hasScrollEnd()) {
+ clearScrollEndFallback(scroller);
+ scrollEndFallbacks.set(
+ scroller,
+ setTimeout(() => {
+ scrollEndFallbacks.delete(scroller);
+ endScroll(scroller);
+ }, SCROLL_END_FALLBACK_MS),
+ );
+ }
+ };
+ const onScrollEnd = (event: Event): void => {
+ const scroller = scrollerOf(event);
+ if (scroller != null) {
+ endScroll(scroller);
+ }
+ };
+ // A scroll that ended while its finger rested ends with the lift.
+ const onFingers = (): void => {
+ for (const scroller of watch.endedWhileDown) {
+ if (!host.isFingerDownIn(scroller)) {
+ watch.endedWhileDown.delete(scroller);
+ watch.fingerScrollers.delete(scroller);
+ }
+ }
+ };
+ // Its listeners are on only while the primary pointer is coarse
+ // (`spec:AST-094` FR19, FR24): elsewhere no finger scrolls, as far as the
+ // touch presentation is concerned. Passive, on the window's capture phase
+ // through the shared input stream.
+ const view = doc.defaultView;
+ let unsubscribers: (() => void)[] = [];
+ const listen = (on: boolean): void => {
+ if (view == null || on === unsubscribers.length > 0) {
+ return;
+ }
+ if (on) {
+ unsubscribers = [
+ subscribeInput(view, 'scroll', onScroll),
+ subscribeInput(view, 'scrollend', onScrollEnd),
+ ];
+ } else {
+ for (const stop of unsubscribers.splice(0)) {
+ stop();
+ }
+ for (const scroller of [...scrollEndFallbacks.keys()]) {
+ clearScrollEndFallback(scroller);
+ }
+ watch.fingerScrollers.clear();
+ watch.endedWhileDown.clear();
+ }
+ };
+ const stopWatchingPointer = watchCoarsePointer(view, listen);
+ listen(isCoarsePointer(view));
+ const unsubscribe = host.onFingersChange(onFingers);
+ const release = host.retain();
+ return () => {
+ stopWatchingPointer();
+ listen(false);
+ unsubscribe();
+ release();
+ };
+}
+
+/**
+ * Keep track of whether the scrolls of `scroller` (an element in `host`'s
+ * document, or the document itself) are a finger's, for isFingerScroll,
+ * until the returned function runs.
+ * Internal: not exported from the package.
+ */
+export function watchFingerScrolls(
+ host: GestureHost,
+ scroller: Node,
+): () => void {
+ let watch = watches.get(host);
+ if (watch == null) {
+ watch = {
+ scrollers: new Map(),
+ fingerScrollers: new Set(),
+ endedWhileDown: new Set(),
+ stop: null,
+ };
+ watches.set(host, watch);
+ }
+ const owned = watch;
+ owned.scrollers.set(scroller, (owned.scrollers.get(scroller) ?? 0) + 1);
+ owned.stop ??= start(host, owned);
+ let isWatching = true;
+ return () => {
+ if (!isWatching) {
+ return;
+ }
+ isWatching = false;
+ const count = (owned.scrollers.get(scroller) ?? 1) - 1;
+ if (count > 0) {
+ owned.scrollers.set(scroller, count);
+ return;
+ }
+ owned.scrollers.delete(scroller);
+ owned.fingerScrollers.delete(scroller);
+ owned.endedWhileDown.delete(scroller);
+ if (owned.scrollers.size === 0) {
+ owned.stop?.();
+ owned.stop = null;
+ }
+ };
+}
+
+/**
+ * Whether the scroll now moving a watched `scroller` is a finger's.
+ * Internal: not exported from the package.
+ */
+export function isFingerScroll(host: GestureHost, scroller: Node): boolean {
+ return watches.get(host)?.fingerScrollers.has(scroller) === true;
+}
diff --git a/packages/core/src/gestures/haptics.ts b/packages/core/src/gestures/haptics.ts
index da9e4e2109..7604c355cb 100644
--- a/packages/core/src/gestures/haptics.ts
+++ b/packages/core/src/gestures/haptics.ts
@@ -26,7 +26,12 @@
* light impact at the moment of the tap. The switch itself never takes the
* touch (`pointer-events: none`; WebKit marks a switch's `touchstart`
* handled, which would stop a pan starting on it from scrolling the page),
- * and its own events never reach the page.
+ * its own events never bubble to the page (capture-phase listeners still
+ * see its click; the gesture host's click swallower skips it by
+ * attribute), and focus the label's activation gives it goes straight
+ * back, so a later Space never toggles it. A label tied to its control
+ * by `for`, or whose control is itself a switch, gets no switch; a label
+ * wrapping its own control gets one, which hands each tap on to it.
* - `playHaptic(kind)` vibrates where `navigator.vibrate` exists (Android
* browsers) with the kind's pattern, and does nothing elsewhere.
*
@@ -39,9 +44,7 @@ import {
type HapticFeedbackKind,
} from '../motion/uikit/gestures';
import {isDisabledControl} from '../utils/pressDisabled';
-
-/** Marks the hidden switch, so click handlers can recognize and ignore it. */
-export const HAPTIC_SWITCH_ATTRIBUTE = 'data-astryx-haptic-switch';
+import {markHapticSwitch} from '../privateAttributes/hapticSwitch.stylex';
/** Whether this browser vibrates at all. */
export function canVibrate(): boolean {
@@ -118,7 +121,7 @@ export function attachTapHaptic(label: HTMLLabelElement): () => void {
const input = doc.createElement('input');
input.type = 'checkbox';
input.setAttribute('switch', '');
- input.setAttribute(HAPTIC_SWITCH_ATTRIBUTE, '');
+ markHapticSwitch(input);
input.setAttribute('aria-hidden', 'true');
input.tabIndex = -1;
input.style.cssText = VISUALLY_HIDDEN;
diff --git a/packages/core/src/gestures/hostRegistry.ts b/packages/core/src/gestures/hostRegistry.ts
new file mode 100644
index 0000000000..3c30fa9584
--- /dev/null
+++ b/packages/core/src/gestures/hostRegistry.ts
@@ -0,0 +1,18 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file hostRegistry.ts
+ * @input Documents, and the gesture host created for each
+ * @output Exports gestureHosts: each document's gesture host, once something
+ * has asked getGestureHost for it
+ * @position Shared by GestureHost.ts, which creates and records the hosts, and
+ * code that only asks a host that already exists (pageHold.ts), which then
+ * imports nothing of the host itself.
+ *
+ * SYNC: When modified, update GestureHost.ts (getGestureHost) and pageHold.ts.
+ */
+
+import type {GestureHost} from './GestureHost';
+
+/** Each document's gesture host, recorded when getGestureHost creates it. */
+export const gestureHosts = new WeakMap<Document, GestureHost>();
diff --git a/packages/core/src/gestures/index.ts b/packages/core/src/gestures/index.ts
index 9cd69efafd..7d03f78da7 100644
--- a/packages/core/src/gestures/index.ts
+++ b/packages/core/src/gestures/index.ts
@@ -15,6 +15,8 @@ export type {
GestureClock,
} from './GestureArena';
export {GestureHost, getGestureHost} from './GestureHost';
+export {holdPageScroll} from './pageHold';
+export type {PageScrollDecision} from './pageHold';
export type {AttachOptions, GestureHostOptions} from './GestureHost';
export {
GestureRecognizer,
@@ -70,10 +72,9 @@ export {deriveTouchAction, gestureHostStyle} from './touchAction';
export type {GestureHostStyle} from './touchAction';
export type * from './types';
export {DEFAULT_ENVIRONMENT} from './types';
-export {useGestureRecognizer, usePressTracker} from './useGestureRecognizer';
-export type {
- UseGestureRecognizerOptions,
- UsePressTrackerOptions,
-} from './useGestureRecognizer';
+export {useGestureRecognizer} from './useGestureRecognizer';
+export type {UseGestureRecognizerOptions} from './useGestureRecognizer';
+export {usePressTracker} from './usePressTracker';
+export type {UsePressTrackerOptions} from './usePressTracker';
export {VelocityTracker} from './VelocityTracker';
export type {VelocityTrackerOptions} from './VelocityTracker';
diff --git a/packages/core/src/gestures/nativeScroll.ts b/packages/core/src/gestures/nativeScroll.ts
index 1b0de8835d..0ff1c5440b 100644
--- a/packages/core/src/gestures/nativeScroll.ts
+++ b/packages/core/src/gestures/nativeScroll.ts
@@ -27,7 +27,11 @@
* read fresh on every question, since a native scroll moves them.
*/
+import {isRtlElement} from '../hooks/isRtlElement';
import type {NativeScrollProbe} from './types';
+import {parentAcrossShadow} from '../utils/flatTree';
+
+export {parentAcrossShadow};
export interface AllowedPans {
readonly x: boolean;
@@ -72,25 +76,6 @@ interface ChainEntry {
const SCROLLABLE = new Set(['auto', 'scroll', 'overlay']);
const EDGE_TOLERANCE = 1;
-/**
- * The node's parent in the flat tree: a slotted node's slot, then out of
- * shadow roots to their hosts, so a scroller inside a shadow tree around the
- * slot is found.
- */
-export function parentAcrossShadow(node: Node): Node | null {
- const slot =
- node instanceof Element || node instanceof Text ? node.assignedSlot : null;
- if (slot != null) {
- return slot;
- }
- if (node.parentNode != null) {
- return node.parentNode instanceof ShadowRoot
- ? node.parentNode.host
- : node.parentNode;
- }
- return null;
-}
-
interface Chain {
readonly entries: ChainEntry[];
/** touch-action allows some pan all the way up. */
@@ -136,7 +121,8 @@ function buildChain(target: Element): Chain {
element,
x: scrollsX && allowX,
y: scrollsY && allowY,
- isRtl: style.direction === 'rtl',
+ // The writing direction through core's one helper.
+ isRtl: isRtlElement(element as HTMLElement),
stopsX: behaviorX !== 'auto',
stopsY: behaviorY !== 'auto',
isBeyondFixed,
diff --git a/packages/core/src/gestures/pageHold.ts b/packages/core/src/gestures/pageHold.ts
new file mode 100644
index 0000000000..c477b18f4e
--- /dev/null
+++ b/packages/core/src/gestures/pageHold.ts
@@ -0,0 +1,265 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file pageHold.ts
+ * @input A document, its gesture host if it has one (which touches a
+ * recognizer owns), and a scroll lock's decision
+ * @output Exports holdPageScroll and PageScrollDecision
+ * @position Scroll-lock support of packages/core/src/gestures, in its own
+ * module so a page without a scroll lock never ships it. It imports nothing
+ * of the gesture host: it asks the document's host only if one exists, so a
+ * scroll lock does not bring the host, its arena and its recognizers into
+ * every overlay.
+ *
+ * While a hold is held, a one-finger pan that `decide` says would scroll the
+ * page, and that no recognizer owns, is cancelled for the rest of its touch;
+ * a second finger (pinch-zoom) never is. A document with no gesture host has
+ * no recognizer, so no touch there is owned. Holds stack per document. Only
+ * while one is held is there a non-passive `touchmove` listener, so a scroll
+ * lock costs nothing once it is released, and a touch scrolls as without
+ * the system. The primary pointer is read as a hold starts: where it is
+ * coarse the hold listens then, since Safari honours a blocking listener only
+ * when it was registered before the touch; where it is fine it registers no
+ * touch listener until a touch or pen contact. Either way it follows the
+ * pointer from then on.
+ *
+ * SYNC: When modified, update the gestures README ("Holding the page still").
+ */
+
+import {subscribeInput} from '../utils/inputStream';
+import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer';
+import {gestureHosts} from './hostRegistry';
+
+/**
+ * Decides, once per one-finger touch, whether its pan would scroll the page:
+ * `origin` is the innermost node under the finger (the composed path's first
+ * node, so a scroller inside a shadow root is seen), `dx` and `dy` the touch's
+ * movement once it clears a small slop. True cancels the touch's moves for as
+ * long as it lasts.
+ */
+export type PageScrollDecision = (
+ origin: EventTarget | null,
+ dx: number,
+ dy: number,
+) => boolean;
+
+/**
+ * How far a finger travels before a page-scroll hold judges its pan, in CSS
+ * px: enough that a swipe's first sample (a 2 px by 2 px wobble) does not fix
+ * the wrong axis, and still under WebKit's 10–11 px scroll claim, so the
+ * verdict comes before the browser commits to a scroll.
+ */
+const PAGE_HOLD_SLOP = 5;
+
+interface PageHolds {
+ readonly decisions: Set<{readonly decide: PageScrollDecision}>;
+ /** The one finger of the gesture the holds are judging. */
+ touch: {
+ /** Null until the finger's first move names it (see onPointerDown). */
+ readonly id: number | null;
+ readonly x: number;
+ readonly y: number;
+ verdict: boolean | null;
+ } | null;
+ readonly onPointerDown: (event: PointerEvent) => void;
+ readonly onTouchStart: (event: TouchEvent) => void;
+ readonly onTouchMove: (event: TouchEvent) => void;
+ /** The input stream subscriptions while held and the pointer is coarse. */
+ unsubscribers: (() => void)[];
+ /** The pointerdown subscription until the hold's first touch or pen contact. */
+ stopPointerDown: (() => void) | null;
+ stopWatchingPointer: (() => void) | null;
+}
+
+const holdsByDocument = new WeakMap<Document, PageHolds>();
+
+function fingersOf(event: TouchEvent): Touch[] {
+ return event.touches == null ? [] : Array.from(event.touches);
+}
+
+function createHolds(doc: Document): PageHolds {
+ const holds: PageHolds = {
+ decisions: new Set(),
+ touch: null,
+ unsubscribers: [],
+ stopPointerDown: null,
+ stopWatchingPointer: null,
+ onPointerDown: event => {
+ if (event.pointerType !== 'touch' && event.pointerType !== 'pen') {
+ return;
+ }
+ // The hold's first touch or pen contact reads the primary pointer and
+ // follows it from then on.
+ holds.stopPointerDown?.();
+ holds.stopPointerDown = null;
+ const view = doc.defaultView;
+ followPointer(doc, holds);
+ if (!isCoarsePointer(view)) {
+ return;
+ }
+ listen(doc, holds, true);
+ // An engine that sends this contact's touchstart first has passed it:
+ // the contact starts here, and its first move names its finger.
+ holds.touch = {
+ id: null,
+ x: event.clientX,
+ y: event.clientY,
+ verdict: null,
+ };
+ },
+ onTouchStart: event => {
+ const fingers = fingersOf(event);
+ const current = holds.touch;
+ // Only a finger already down keeps its record: a new touch that reuses
+ // the identifier starts afresh.
+ if (
+ current?.id != null &&
+ fingers.some(finger => finger.identifier === current.id) &&
+ !Array.from(event.changedTouches).some(
+ finger => finger.identifier === current.id,
+ )
+ ) {
+ // A second finger joins the held one: nothing is cancelled while two
+ // are down (a pinch), and the first keeps its verdict for the rest
+ // of its touch once it is alone again.
+ return;
+ }
+ const finger = fingers[0];
+ holds.touch =
+ fingers.length === 1 && finger != null
+ ? {
+ id: finger.identifier,
+ x: finger.clientX,
+ y: finger.clientY,
+ verdict: null,
+ }
+ : null;
+ },
+ onTouchMove: event => {
+ const fingers = fingersOf(event);
+ const finger = fingers[0];
+ if (holds.touch?.id === null && fingers.length === 1 && finger != null) {
+ holds.touch = {...holds.touch, id: finger.identifier};
+ }
+ const current = holds.touch;
+ // A second finger is a pinch: zooming the page stays available.
+ if (
+ fingers.length !== 1 ||
+ finger == null ||
+ current == null ||
+ finger.identifier !== current.id
+ ) {
+ return;
+ }
+ // A recognizer that owns the touch decides about its moves itself. The
+ // host is read on every move: one may be created after the hold began.
+ if (gestureHosts.get(doc)?.isTouchClaimed(current.id) === true) {
+ return;
+ }
+ if (current.verdict == null) {
+ const dx = finger.clientX - current.x;
+ const dy = finger.clientY - current.y;
+ if (Math.max(Math.abs(dx), Math.abs(dy)) < PAGE_HOLD_SLOP) {
+ return;
+ }
+ // The browser picks the scroller once per gesture; so do the holds.
+ const origin = event.composedPath()[0] ?? event.target;
+ current.verdict = [...holds.decisions].some(hold =>
+ hold.decide(origin, dx, dy),
+ );
+ }
+ if (current.verdict && event.cancelable) {
+ event.preventDefault();
+ }
+ },
+ };
+ return holds;
+}
+
+/**
+ * Follow the primary pointer while held, once: the holds listen while it is
+ * coarse and not while it is fine (`spec:AST-094` FR24).
+ */
+function followPointer(doc: Document, holds: PageHolds): void {
+ if (holds.stopWatchingPointer == null) {
+ holds.stopWatchingPointer = watchCoarsePointer(doc.defaultView, isCoarse =>
+ listen(doc, holds, isCoarse),
+ );
+ }
+}
+
+/**
+ * Turn the holds' listeners on or off: on only while one is held and the
+ * primary pointer is coarse (`spec:AST-094` FR19, FR24).
+ */
+function listen(doc: Document, holds: PageHolds, on: boolean): void {
+ const view = doc.defaultView;
+ if (view == null || on === holds.unsubscribers.length > 0) {
+ return;
+ }
+ if (on) {
+ // The window's capture phase, through the shared input stream, as the
+ // host listens; only the touchmove that cancels is non-passive.
+ holds.unsubscribers = [
+ subscribeInput(view, 'touchstart', holds.onTouchStart),
+ subscribeInput(view, 'touchmove', holds.onTouchMove, {cancels: true}),
+ ];
+ } else {
+ for (const unsubscribe of holds.unsubscribers.splice(0)) {
+ unsubscribe();
+ }
+ holds.touch = null;
+ }
+}
+
+/**
+ * Hold the page of `doc` still under a finger until the returned release runs
+ * (a scroll lock under a modal presentation): `holdPageScroll(document,
+ * decide)`. Never creates a gesture host. Where the primary pointer is
+ * coarse it listens as it starts, since Safari honours a blocking listener
+ * only when it was registered before the touch, and the first drag after an
+ * overlay opens is the one a hold is for; where it is fine it subscribes
+ * only to `pointerdown` and registers no touch listener until a touch or pen
+ * contact. Either way it follows the pointer while held.
+ * Proposed; pending owner review.
+ */
+export function holdPageScroll(
+ doc: Document,
+ decide: PageScrollDecision,
+): () => void {
+ let holds = holdsByDocument.get(doc);
+ if (holds == null) {
+ holds = createHolds(doc);
+ holdsByDocument.set(doc, holds);
+ }
+ const owned = holds;
+ const hold = {decide};
+ owned.decisions.add(hold);
+ const view = doc.defaultView;
+ if (owned.decisions.size === 1 && view != null) {
+ owned.stopPointerDown = subscribeInput(
+ view,
+ 'pointerdown',
+ owned.onPointerDown,
+ );
+ if (isCoarsePointer(view)) {
+ followPointer(doc, owned);
+ listen(doc, owned, true);
+ }
+ }
+ let isHeld = true;
+ return () => {
+ if (!isHeld) {
+ return;
+ }
+ isHeld = false;
+ owned.decisions.delete(hold);
+ if (owned.decisions.size === 0) {
+ owned.stopPointerDown?.();
+ owned.stopPointerDown = null;
+ owned.stopWatchingPointer?.();
+ owned.stopWatchingPointer = null;
+ listen(doc, owned, false);
+ }
+ };
+}
diff --git a/packages/core/src/gestures/recognizerInternals.ts b/packages/core/src/gestures/recognizerInternals.ts
new file mode 100644
index 0000000000..dd9a20547c
--- /dev/null
+++ b/packages/core/src/gestures/recognizerInternals.ts
@@ -0,0 +1,77 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file recognizerInternals.ts
+ * @input GestureRecognizer
+ * @output internals(recognizer): the members the arena, the host and the
+ * React hooks drive, and RecognizerFamily, the brand the host reads instead
+ * of `instanceof`
+ * @position Internal to packages/core/src/gestures; never exported from the
+ * package
+ *
+ * A recognizer's arena plumbing (its arena, a pending recognition, touch
+ * delivery, approved transitions) is `protected` on the class, so the
+ * published type offers it to subclasses only. The arena and the host reach
+ * it through this view, and so do the React hooks, for the arena an Effect's
+ * stop defers its resolution to.
+ *
+ * SYNC: When modified, update the `protected` members of GestureRecognizer.ts.
+ */
+
+import type {GestureArena} from './GestureArena';
+import type {GestureRecognizer} from './GestureRecognizer';
+import type {GestureEventContext, GestureState, GestureTouch} from './types';
+
+/**
+ * The kinds of recognizer the host and touch-action treat specially. Each of
+ * those classes brands itself (a subclass inherits the brand), so the host
+ * never imports a recognizer class: a page ships only the recognizers it
+ * constructs.
+ */
+export type RecognizerFamily = 'tap' | 'longPress' | 'pan';
+
+/** 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;
+ arena: GestureArena | null;
+ pending: 'began' | 'ended' | null;
+ readonly seenTouchIds: Set<number>;
+ readonly acceptsTouchInput: boolean;
+ requiresFailureOf(other: GestureRecognizer): boolean;
+ allowsSimultaneous(other: GestureRecognizer): boolean;
+ shouldBegin(): boolean;
+ keepsTouch(touchId: number): boolean;
+ wantsTouch(touch: GestureTouch): boolean;
+ deliverBegan(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void;
+ deliverBeganElsewhere(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void;
+ deliverMoved(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void;
+ deliverEnded(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void;
+ deliverCancelled(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void;
+ deliverTakenByBrowser(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void;
+ applyState(next: GestureState): void;
+ resetToPossible(): void;
+}
+
+/** The gesture system's view of `recognizer`. */
+export function internals(recognizer: GestureRecognizer): RecognizerInternals {
+ return recognizer as unknown as RecognizerInternals;
+}
diff --git a/packages/core/src/gestures/selectionLock.ts b/packages/core/src/gestures/selectionLock.ts
new file mode 100644
index 0000000000..b101b5afdf
--- /dev/null
+++ b/packages/core/src/gestures/selectionLock.ts
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file selectionLock.ts
+ * @input The selection lock in utils/selectionLock.ts
+ * @output Re-exports lockSelection and locksSelectionFor
+ * @position A transition re-export: the selection lock moved to utils with
+ * the shared input stream (utils/inputStream.ts), and stacks based below
+ * that move still import it from here. Remove it once they have moved up.
+ */
+
+export {lockSelection, locksSelectionFor} from '../utils/selectionLock';
diff --git a/packages/core/src/gestures/touchAction.ts b/packages/core/src/gestures/touchAction.ts
index 5400b97c90..1839a41e90 100644
--- a/packages/core/src/gestures/touchAction.ts
+++ b/packages/core/src/gestures/touchAction.ts
@@ -4,9 +4,10 @@
* @file touchAction.ts
* @input The recognizers attached to one element
* @output Exports deriveTouchAction (the element's `touch-action`),
- * gestureHostStyle (the inline style a host sets for its recognizers),
- * intersectTouchAction (what both a derived and a caller's value allow) and
- * holdSelectionStyle (the selection and callout lock for one held press)
+ * gestureHostStyle (the inline style a host sets for its recognizers) and
+ * intersectTouchAction (what both a derived and a caller's value allow).
+ * The selection and callout lock for one held press is the recognizer's
+ * own `selectionLock` (gestures/selectionLock.ts), which the host calls
* @position Browser negotiation of packages/core/src/gestures, pure so a
* server render can emit the same style the client would set
*
@@ -30,8 +31,14 @@
*/
import type {GestureRecognizer, NativeTouchBehavior} from './GestureRecognizer';
+import {internals} from './recognizerInternals';
-/** The intersection of what each touch recognizer leaves the browser. */
+/**
+ * The intersection of what each touch recognizer leaves the browser. A
+ * watcher (`claimsTouches: false`) never takes a touch, so it leaves the
+ * browser everything: its direction restricts no scroll (`spec:AST-094`
+ * FR20, DEC-7).
+ */
export function combinedNativeBehavior(
recognizers: ReadonlyArray<GestureRecognizer>,
): NativeTouchBehavior {
@@ -40,7 +47,7 @@ export function combinedNativeBehavior(
let pinchZoom = true;
let doubleTapZoom = true;
for (const recognizer of recognizers) {
- if (!recognizer.acceptsTouchInput) {
+ if (!internals(recognizer).acceptsTouchInput || !recognizer.claimsTouches) {
continue;
}
const behavior = recognizer.nativeTouchBehavior;
@@ -170,22 +177,3 @@ export function intersectTouchAction(derived: string, caller: string): string {
}
return parts.length === 0 ? 'none' : parts.join(' ');
}
-
-/**
- * The lock a host applies for one press only, from touch-down to the lift or
- * a cancel, on an element whose hold does something (a long press): no iOS
- * callout and no text-selection start under the held finger, as a
- * long-pressed row in UIKit selects no text (spec:AST-094 FR41). Null where
- * the hold does nothing, so a long press there selects natively.
- */
-export function holdSelectionStyle(
- recognizers: ReadonlyArray<GestureRecognizer>,
-): GestureHostStyle | null {
- const holds = recognizers.some(
- recognizer =>
- recognizer.kind === 'longPress' && recognizer.acceptsTouchInput,
- );
- return holds
- ? {WebkitTouchCallout: 'none', WebkitUserSelect: 'none', userSelect: 'none'}
- : null;
-}
diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.ts
index 064d028f18..d50f5c1391 100644
--- a/packages/core/src/gestures/types.ts
+++ b/packages/core/src/gestures/types.ts
@@ -9,6 +9,8 @@
* @position Shared vocabulary of packages/core/src/gestures; no runtime code
*/
+import type {SelectionLock} from './GestureRecognizer';
+
/**
* UIGestureRecognizer.State. A discrete recognizer goes straight from
* `possible` to `ended` (UIKit's `.recognized` is the same value).
@@ -172,6 +174,22 @@ export interface TouchConsumer {
* (attached above this consumer) from beginning for a touch on it.
*/
allowsAncestorRecognizer?(recognizer: unknown): boolean;
+ /**
+ * Whether the consumer holds this touch now (a control whose press was
+ * delivered for that touch): the host cancels the browser's pan for that
+ * finger only, as UIKit's `touchesShouldCancel(in:)` is false for a
+ * tracking control. A move before the press is delivered, and another
+ * finger the consumer is not tracking, still scroll.
+ */
+ keepsTouch?(touchId: number): boolean;
+ /**
+ * A control whose own record defines a hold action (a stepper's
+ * hold-repeat) brings the lock that turns text selection and the callout
+ * off for that press only, as a recognizer created with one does
+ * (`spec:AST-094` FR41). A control whose hold does nothing leaves it
+ * undefined and keeps the browser's long-press selection.
+ */
+ readonly selectionLock?: SelectionLock;
/**
* Whether the consumer takes touches now (a disabled control does not).
* The host listens only while something enabled is attached
diff --git a/packages/core/src/gestures/useAttachment.ts b/packages/core/src/gestures/useAttachment.ts
new file mode 100644
index 0000000000..d467687efc
--- /dev/null
+++ b/packages/core/src/gestures/useAttachment.ts
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useAttachment.ts
+ * @input An element ref, an attach function and a key
+ * @output Exports useAttachment, useIsUnmountedRef, and the gesture-sync
+ * depth (syncingGestures, isSyncingGestures) both hooks read
+ * @position Internal React helpers shared by useGestureRecognizer and
+ * usePressTracker, so each hook imports only what it uses
+ *
+ * SYNC: When modified, update useGestureRecognizer.test.tsx.
+ */
+
+import {useRef, type RefObject} from 'react';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+
+/**
+ * How many hooks are driving a recognizer from an Effect right now: an
+ * `isEnabled` sync, or the detach of a replaced node that cancels a gesture
+ * in flight. While one runs no hook's listener calls its caller's callback
+ * (react-component-runtime INV2, INV3): the recognizer it stops is cancelled
+ * silently, and what that stop unblocks (a recognizer that required it to
+ * fail) resolves in the arena's next pass, a microtask later, where its
+ * listener reports as usual (`deferringResolution` in useGestureRecognizer).
+ * A press tracker's callbacks wait for a microtask after it (usePressTracker).
+ */
+let syncingDepth = 0;
+
+/** Runs `body` as a gesture sync (see `syncingDepth`). */
+export function syncingGestures<T>(body: () => T): T {
+ syncingDepth += 1;
+ try {
+ return body();
+ } finally {
+ syncingDepth -= 1;
+ }
+}
+
+/** True while any gesture hook's sync runs. */
+export function isSyncingGestures(): boolean {
+ return syncingDepth > 0;
+}
+
+/**
+ * A flag that turns true when the component unmounts, before the cleanups of
+ * the effects declared after it run, so nothing reports from those cleanups.
+ */
+export function useIsUnmountedRef(): {readonly current: boolean} {
+ const isUnmountedRef = useRef(false);
+ // Syncs the flag with the component's mount.
+ useIsomorphicLayoutEffect(() => {
+ isUnmountedRef.current = false;
+ return () => {
+ isUnmountedRef.current = true;
+ };
+ }, []);
+ return isUnmountedRef;
+}
+
+/**
+ * Keep `attach` bound to the element `ref` holds after each commit. A
+ * replaced node is released and the new one attached, a changed `key`
+ * re-attaches, and the last attachment is released on unmount; a commit that
+ * changes neither does nothing (react-component-runtime INV3).
+ */
+export function useAttachment(
+ ref: RefObject<Element | null>,
+ attach: (element: Element) => () => void,
+ key: unknown,
+): void {
+ const attachmentRef = useRef<{
+ element: Element;
+ key: unknown;
+ release: () => void;
+ } | null>(null);
+
+ // Syncs the attachment with the DOM node `ref` holds after this commit.
+ useIsomorphicLayoutEffect(() => {
+ const element = ref.current;
+ const current = attachmentRef.current;
+ if (current?.element === element && current?.key === key) {
+ return;
+ }
+ current?.release();
+ attachmentRef.current =
+ element == null ? null : {element, key, release: attach(element)};
+ });
+
+ // Releases the attachment at unmount.
+ useIsomorphicLayoutEffect(
+ () => () => {
+ attachmentRef.current?.release();
+ attachmentRef.current = null;
+ },
+ [],
+ );
+}
diff --git a/packages/core/src/gestures/useFingerScroll.ts b/packages/core/src/gestures/useFingerScroll.ts
new file mode 100644
index 0000000000..2ce09e2aa8
--- /dev/null
+++ b/packages/core/src/gestures/useFingerScroll.ts
@@ -0,0 +1,85 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useFingerScroll.ts
+ * @input A scroller (a ref to an element, or the document for the page) and
+ * the document's gesture host
+ * @output useFingerScroll: whether the scroller's current scroll is a
+ * finger's, read at any moment
+ * @position Gesture hook of packages/core/src/gestures, over the
+ * finger-scroll watch (fingerScroll.ts). An internal piece of the touch
+ * module with no public API, not in the gestures barrel: a scroll-driven
+ * component (a tab bar that minimizes, a header that collapses, a picker
+ * that commits at rest) imports it from here, so it ships only where used
+ *
+ * A scroll is a finger's from a scroll event while a finger that landed
+ * inside the scroller is down, until the scroller's `scrollend` (the lift
+ * starts the momentum, which is still the finger's), or, where the browser
+ * sends no `scrollend`, until a 150 ms fallback after the last scroll event.
+ * A scroll with no finger down, or a recognizer's own scroll, is the
+ * program's, even right after a tap. A
+ * component that reacts to the person's scrolling only (a tab bar that
+ * minimizes as the page scrolls down) reads this instead of listening to
+ * touches itself.
+ *
+ * SYNC: When modified, update __tests__/useFingerScroll.test.tsx.
+ */
+
+import {useCallback, useRef, type RefObject} from 'react';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {isFingerScroll, watchFingerScrolls} from './fingerScroll';
+import {getGestureHost} from './GestureHost';
+
+function isDocument(value: unknown): value is Document {
+ return typeof Document !== 'undefined' && value instanceof Document;
+}
+
+/**
+ * Watch a scroller's finger scrolls. Pass a ref to a scrolling element, or
+ * the document for the page's own scroll. Returns a reader, stable across
+ * renders: `true` while the scroller's scroll is a finger's.
+ * Internal: not exported from the package.
+ */
+export function useFingerScroll(
+ scroller: RefObject<Element | null> | Document,
+): () => boolean {
+ const attachedRef = useRef<{node: Node; detach: () => void} | null>(null);
+ // Follows the node on every commit: a ref that now points at another
+ // element moves the watch to it.
+ useIsomorphicLayoutEffect(() => {
+ const node = isDocument(scroller) ? scroller : scroller.current;
+ if (attachedRef.current?.node === node) {
+ return;
+ }
+ attachedRef.current?.detach();
+ attachedRef.current =
+ node == null
+ ? null
+ : {
+ node,
+ detach: watchFingerScrolls(
+ getGestureHost(isDocument(node) ? node : node.ownerDocument),
+ node,
+ ),
+ };
+ });
+ // Synchronizes with the gesture host's finger-scroll watch: unmounting
+ // releases the watch this hook attached.
+ useIsomorphicLayoutEffect(
+ () => () => {
+ attachedRef.current?.detach();
+ attachedRef.current = null;
+ },
+ [],
+ );
+ return useCallback(() => {
+ const node = attachedRef.current?.node;
+ if (node == null) {
+ return false;
+ }
+ const doc = isDocument(node) ? node : node.ownerDocument;
+ return doc != null && isFingerScroll(getGestureHost(doc), node);
+ }, []);
+}
diff --git a/packages/core/src/gestures/useGestureRecognizer.ts b/packages/core/src/gestures/useGestureRecognizer.ts
index 8dcb3080d9..046fc7af1b 100644
--- a/packages/core/src/gestures/useGestureRecognizer.ts
+++ b/packages/core/src/gestures/useGestureRecognizer.ts
@@ -4,9 +4,10 @@
/**
* @file useGestureRecognizer.ts
- * @input An element ref, a recognizer factory and a gesture listener; or an
- * element ref and press tracker options
- * @output Exports useGestureRecognizer and usePressTracker
+ * @input An element ref, a recognizer factory and a gesture listener
+ * @output Exports useGestureRecognizer (usePressTracker lives in
+ * usePressTracker.ts, so a gesture-only component never imports the press
+ * tracker)
* @position React face of packages/core/src/gestures
*
* The recognizer is created once and keeps its identity for the life of the
@@ -15,68 +16,62 @@
* passing a new function each render re-attaches nothing, and a gesture
* costs no React render at all — the listener runs inside the input event
* and writes to the DOM itself. The recognizer attaches in a layout effect,
- * so its `touch-action` is in place before the browser can see a finger.
+ * so its `touch-action` is in place before the browser can see a finger, and
+ * re-attaches on any commit that finds another element behind the ref. After
+ * unmount neither hook calls the consumer back.
*
* SYNC: When modified, update useGestureRecognizer.test.tsx and README.md.
*/
-import {useEffect, useMemo, useRef, useState, type RefObject} from 'react';
+import {useEffect, useRef, useState, type RefObject} from 'react';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {getGestureHost} from './GestureHost';
import type {GestureRecognizer} from './GestureRecognizer';
import {
- createPressTracker,
- vetoesSingleTap,
- type PressTracker,
- type PressTrackerOptions,
-} from './PressTracker';
+ isSyncingGestures,
+ syncingGestures,
+ useAttachment,
+ useIsUnmountedRef,
+} from './useAttachment';
+import {internals} from './recognizerInternals';
export interface UseGestureRecognizerOptions {
/**
* Live toggle; turning it off mid-gesture cancels the gesture. That cancel
* does not call `onGesture`: it comes from the render that turned the
- * recognizer off, and the code that turned it off already knows.
+ * recognizer off, and the code that turned it off already knows. A
+ * recognizer that required this one to fail resolves just after that
+ * render and reports as usual.
* @default true
*/
isEnabled?: boolean;
/** Let the host set touch-action (and long-press callout) styles. @default true */
manageStyle?: boolean;
+ /**
+ * Accepted and ignored: every attachment reads each event's pointer
+ * (`spec:AST-094` FR43). Kept so callers written before FR43 compile.
+ * @deprecated
+ */
+ perEventPointer?: boolean;
+ /**
+ * The element is an action group, sibling actions a held pointer slides
+ * across (`family:action-groups` FR5): the host serves it where the
+ * primary pointer is fine too (`AttachOptions.actionGroup`).
+ * @default false
+ */
+ actionGroup?: boolean;
}
/**
- * How many Effects are driving the gesture system right now (an `isEnabled`
- * sync, a detach, a press tracker's release or host update). While one runs
- * no hook calls its caller back (react-component-runtime INV2, INV3): the
- * recognizer it stops is cancelled silently, and what that stop unblocks (a
- * recognizer that required it to fail) resolves in the arena's next pass, a
- * microtask later, where its listener reports as usual
- * (`deferringResolution`).
- */
-let effectDepth = 0;
-
-/** Runs `drive` as an Effect's work on the gesture system (see effectDepth). */
-function driveFromEffect(drive: () => void): void {
- effectDepth += 1;
- try {
- drive();
- } finally {
- effectDepth -= 1;
- }
-}
-
-/**
- * Runs `body`, which stops `recognizer` from an Effect, with its arena leaving
- * what the stop unblocks to a pass a microtask later
- * (GestureArena.deferResolution): a recognizer that required the stopped one
- * to fail recognizes there, outside the Effect, and its listener reports as
- * usual. A recognizer that has met no touch has no arena, and nothing waits on
- * it.
+ * Runs `body` with the recognizer's arena leaving what it unblocks to the
+ * next pass, outside the Effect (GestureArena.deferResolution). A recognizer
+ * that has met no touch has no arena, and nothing waits on it.
*/
function deferringResolution(
recognizer: GestureRecognizer,
body: () => void,
): void {
- const arena = recognizer.arena;
+ const {arena} = internals(recognizer);
if (arena == null) {
body();
return;
@@ -98,6 +93,7 @@ function deferringResolution(
* );
* ```
*/
+
export function useGestureRecognizer<R extends GestureRecognizer>(
ref: RefObject<Element | null>,
create: () => R,
@@ -106,200 +102,65 @@ export function useGestureRecognizer<R extends GestureRecognizer>(
): R {
const [recognizer] = useState(create);
const onGestureRef = useRef(onGesture);
+ // Syncs the listener's ref with the caller's newest callback.
useIsomorphicLayoutEffect(() => {
onGestureRef.current = onGesture;
});
- const {isEnabled = true, manageStyle = true} = options;
-
- // Syncs the recognizer's target-action listeners with the caller's
- // callback (read through a ref, so a new function re-subscribes nothing).
+ const {
+ isEnabled = true,
+ manageStyle = true,
+ perEventPointer = false,
+ actionGroup = false,
+ } = options;
+ const isUnmountedRef = useIsUnmountedRef();
+
+ // Syncs the recognizer's target-action listener with this component. The
+ // listener runs inside input events, never during a render or an Effect,
+ // and goes quiet once the component unmounts.
useEffect(
() =>
recognizer.addListener(current => {
- if (effectDepth === 0) {
+ if (!isUnmountedRef.current && !isSyncingGestures()) {
onGestureRef.current?.(current);
}
}),
- [recognizer],
+ [recognizer, isUnmountedRef],
);
- // Syncs the recognizer's `isEnabled` (UIKit's). It runs first, so disabling
- // cancels a gesture in flight before its attachment goes, and that cancel,
- // with whatever it settles in the arena, reaches no caller callback.
+ // Syncs the recognizer's `isEnabled` with the option. It runs first,
+ // under the guard, so disabling cancels a gesture in flight before its
+ // attachment goes.
useIsomorphicLayoutEffect(() => {
- driveFromEffect(() =>
- deferringResolution(recognizer, () => recognizer.setEnabled(isEnabled)),
- );
+ syncingGestures(() => {
+ deferringResolution(recognizer, () => {
+ recognizer.setEnabled(isEnabled);
+ });
+ });
}, [recognizer, isEnabled]);
- // Syncs the document's gesture host with the element behind `ref`: attached
- // while enabled, re-attached when the node is replaced. A disabled gesture
- // is not attached at all: no listener and no `touch-action` of its own on
- // the element (spec:AST-094 FR24). Detaching (an unmount, a replaced node)
- // cancels a gesture in flight, and that cancel, run in an Effect, reaches
- // no caller callback (react-component-runtime INV2).
- useNodeAttachment(
+ // Syncs the document's gesture host with the element behind `ref`. A
+ // disabled gesture is not attached at all: no listener and no
+ // `touch-action` of its own on the element (spec:AST-094 FR24). A replaced
+ // node is released and the new one attached; detaching cancels a gesture in
+ // progress from a layout effect, and that cancel reaches no caller callback
+ // (react-component-runtime INV2, INV3).
+ useAttachment(
ref,
element => {
if (!isEnabled) {
- return null;
+ return () => {};
}
const detach = getGestureHost(element.ownerDocument).attach(
element,
recognizer,
- {manageStyle},
+ {manageStyle, perEventPointer, actionGroup},
);
- return () =>
- driveFromEffect(() => deferringResolution(recognizer, detach));
+ return () => {
+ syncingGestures(() => deferringResolution(recognizer, detach));
+ };
},
- [recognizer, manageStyle, isEnabled],
+ `${manageStyle}:${perEventPointer}:${isEnabled}:${actionGroup}`,
);
return recognizer;
}
-
-export type UsePressTrackerOptions = Omit<
- PressTrackerOptions,
- 'getBounds' | 'view'
->;
-
-/**
- * Track presses on the element behind `ref` with UIControl semantics. The
- * callbacks are read through a ref, like a recognizer's listener. Releasing
- * the element (unmount, or a replaced node) ends any press without calling
- * them: that release runs in an Effect, which never calls a caller's
- * callback (react-component-runtime INV2, INV3).
- */
-export function usePressTracker(
- ref: RefObject<Element | null>,
- options: UsePressTrackerOptions = {},
-): PressTracker {
- const optionsRef = useRef(options);
- useIsomorphicLayoutEffect(() => {
- optionsRef.current = options;
- });
- const {trackingExpansion, highlightDelay, cancelTravel, quickTapFlash} =
- options;
- // The tracker reads these four when it is built: a change rebuilds it (the
- // attachment below moves to the new one and disposes the old), and the new
- // values apply from the next touch. The callbacks, the brake included, are
- // read through the ref on every touch.
- const tracker = useMemo(
- () =>
- createPressTracker({
- getBounds: () => ref.current?.getBoundingClientRect() ?? null,
- get view() {
- return ref.current;
- },
- onControlEvent: (event, touch) => {
- if (effectDepth === 0) {
- optionsRef.current.onControlEvent?.(event, touch);
- }
- },
- onHighlightChange: isHighlighted => {
- if (effectDepth === 0) {
- optionsRef.current.onHighlightChange?.(isHighlighted);
- }
- },
- trackingExpansion,
- highlightDelay,
- cancelTravel,
- quickTapFlash,
- // The caller's veto, read on every touch, else the tracker's own.
- vetoesAncestorRecognizer: recognizer =>
- (optionsRef.current.vetoesAncestorRecognizer ?? vetoesSingleTap)(
- recognizer,
- ),
- isEnabled: () => optionsRef.current.isEnabled?.() ?? true,
- // A finger that brakes a scroll it set moving presses nothing
- // (GestureHost.isScrollBraking), unless the caller decides; the tracker
- // asks only for a finger (spec:AST-094 FR11).
- isBraking: touch => {
- const element = ref.current;
- return (
- optionsRef.current.isBraking?.(touch) ??
- (element != null &&
- getGestureHost(element.ownerDocument).isScrollBraking(element))
- );
- },
- }),
- [ref, trackingExpansion, highlightDelay, cancelTravel, quickTapFlash],
- );
-
- // Syncs the document's gesture host with the element behind `ref`: the
- // tracker is its press consumer, moved when the node is replaced, and a
- // press in progress ends with it.
- useNodeAttachment(
- ref,
- element => {
- const detach = getGestureHost(element.ownerDocument).attachConsumer(
- element,
- tracker,
- );
- return () =>
- driveFromEffect(() => {
- detach();
- tracker.dispose();
- });
- },
- [tracker],
- );
-
- // Syncs the host's listeners with the tracker's enabled state, which can
- // change with any render: the host listens only while an enabled control
- // is attached (spec:AST-094 FR24).
- useIsomorphicLayoutEffect(() => {
- const element = ref.current;
- if (element != null) {
- driveFromEffect(() =>
- getGestureHost(element.ownerDocument).update(element),
- );
- }
- });
-
- return tracker;
-}
-
-/**
- * Keeps `attach` applied to the element behind `ref`: checked after every
- * render, so a replaced node (a re-keyed or swapped element) is detached and
- * the new one attached, a removed one detached, and a change in `deps`
- * re-attaches (`architecture:react-component-runtime` INV6). Costs no render.
- * `attach` returns its detach, or null for nothing attached.
- */
-function useNodeAttachment<T extends Element>(
- ref: RefObject<T | null>,
- attach: (element: T) => (() => void) | null,
- deps: ReadonlyArray<unknown>,
-): void {
- const attachedRef = useRef<{
- element: T;
- deps: ReadonlyArray<unknown>;
- detach: (() => void) | null;
- } | null>(null);
- // Syncs the attachment with the DOM node the caller's ref holds after
- // this commit.
- useIsomorphicLayoutEffect(() => {
- const element = ref.current;
- const current = attachedRef.current;
- if (
- current != null &&
- current.element === element &&
- current.deps.length === deps.length &&
- current.deps.every((dep, index) => Object.is(dep, deps[index]))
- ) {
- return;
- }
- current?.detach?.();
- attachedRef.current =
- element == null ? null : {element, deps, detach: attach(element)};
- });
- // Detaches at unmount.
- useIsomorphicLayoutEffect(
- () => () => {
- attachedRef.current?.detach?.();
- attachedRef.current = null;
- },
- [],
- );
-}
diff --git a/packages/core/src/gestures/usePressTracker.ts b/packages/core/src/gestures/usePressTracker.ts
new file mode 100644
index 0000000000..05bbdbdb29
--- /dev/null
+++ b/packages/core/src/gestures/usePressTracker.ts
@@ -0,0 +1,212 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file usePressTracker.ts
+ * @input An element ref and press tracker options
+ * @output Exports usePressTracker
+ * @position React face of packages/core/src/gestures' PressTracker, in its
+ * own module so a component that only recognizes gestures never imports
+ * the press tracker
+ *
+ * The callbacks and the profile are read through refs: one tracker serves
+ * the component's life, so a profile change applies from the tracker's next
+ * read and never ends a press in progress. After unmount the tracker calls
+ * nothing back.
+ *
+ * SYNC: When modified, update useGestureRecognizer.test.tsx and README.md.
+ */
+
+import {useMemo, useRef, useState, type RefObject} from 'react';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {UIKIT_CONTROL} from '../motion/uikit/gestures';
+import {getGestureHost} from './GestureHost';
+import {
+ createPressTracker,
+ vetoesSingleTap,
+ type PressTracker,
+ type PressTrackerOptions,
+} from './PressTracker';
+import {
+ isSyncingGestures,
+ syncingGestures,
+ useAttachment,
+ useIsUnmountedRef,
+} from './useAttachment';
+
+export type UsePressTrackerOptions = Omit<
+ PressTrackerOptions,
+ 'getBounds' | 'view'
+> & {
+ /**
+ * Accepted and ignored: every attachment reads each event's pointer
+ * (`spec:AST-094` FR43). Kept so callers written before FR43 compile.
+ * @deprecated
+ */
+ perEventPointer?: boolean;
+};
+
+/**
+ * Track presses on the element behind `ref` with UIControl semantics. The
+ * callbacks are read through a ref, like a recognizer's listener. Releasing
+ * the element (unmount, or a replaced node) ends any press without calling
+ * them: that release runs in an Effect, which never calls a caller's
+ * callback (react-component-runtime INV2, INV3).
+ */
+export function usePressTracker(
+ ref: RefObject<Element | null>,
+ options: UsePressTrackerOptions = {},
+): PressTracker {
+ const optionsRef = useRef(options);
+ // True while an Effect releases the tracker, so the press it ends reaches
+ // no caller callback.
+ const isReleasingRef = useRef(false);
+ // The ref is read through a ref too: a caller may pass a new ref object
+ // on a render, and the one tracker must follow it.
+ const refRef = useRef(ref);
+ // Syncs the options and ref refs with the newest render.
+ useIsomorphicLayoutEffect(() => {
+ optionsRef.current = options;
+ refRef.current = ref;
+ });
+ const isUnmountedRef = useIsUnmountedRef();
+ const {perEventPointer = false} = options;
+ // Calls a caller callback: never while an Effect releases the tracker or
+ // after unmount. While any gesture hook's isEnabled sync runs (turning off
+ // a recognizer the press waits on resolves the press in that arena pass,
+ // inside the Effect), the call waits for a microtask after it, in order,
+ // so the press still ends, un-highlighted, outside the Effect
+ // (react-component-runtime INV2).
+ const [deliver] = useState(() => (call: () => void) => {
+ if (isReleasingRef.current || isUnmountedRef.current) {
+ return;
+ }
+ if (!isSyncingGestures()) {
+ call();
+ return;
+ }
+ queueMicrotask(() => {
+ if (!isUnmountedRef.current) {
+ call();
+ }
+ });
+ });
+ // One tracker for the component's life, reading its profile through the
+ // options ref: a profile change never rebuilds it, so a press in progress
+ // survives it (the change applies from the tracker's next read).
+ // `keepsTouch` is the exception, fixed when the tracker is created: it
+ // decides whether the host gives the element a blocking touchmove.
+ const [tracker] = useState(() =>
+ createPressTracker({
+ getBounds: () => {
+ const element = refRef.current.current;
+ return element == null
+ ? null
+ : getGestureHost(element.ownerDocument).presentedRect(element);
+ },
+ get view() {
+ return refRef.current.current;
+ },
+ onControlEvent: (event, touch) =>
+ deliver(() => optionsRef.current.onControlEvent?.(event, touch)),
+ onHighlightChange: isHighlighted =>
+ deliver(() => optionsRef.current.onHighlightChange?.(isHighlighted)),
+ trackingExpansion: options.trackingExpansion,
+ get highlightDelay() {
+ return optionsRef.current.highlightDelay;
+ },
+ get cancelTravel() {
+ return optionsRef.current.cancelTravel;
+ },
+ get quickTapFlash() {
+ return optionsRef.current.quickTapFlash;
+ },
+ keepsTouch: options.keepsTouch,
+ get selectionLock() {
+ return optionsRef.current.selectionLock;
+ },
+ // The caller's veto, read on every touch, else the tracker's own.
+ vetoesAncestorRecognizer: recognizer =>
+ (optionsRef.current.vetoesAncestorRecognizer ?? vetoesSingleTap)(
+ recognizer,
+ ),
+ isEnabled: () => optionsRef.current.isEnabled?.() ?? true,
+ // The caller's brake, or the host's: a touch that stops a flick
+ // presses nothing, as a UIKit control in a decelerating scroll view.
+ isBraking: touch => {
+ const own = optionsRef.current.isBraking;
+ if (own != null) {
+ return own(touch);
+ }
+ const element = refRef.current.current;
+ return (
+ element != null &&
+ getGestureHost(element.ownerDocument).isScrollBraking(element)
+ );
+ },
+ }),
+ );
+ const {trackingExpansion} = options;
+ // Syncs the tracker's tracking expansion with the option.
+ useIsomorphicLayoutEffect(() => {
+ tracker.trackingExpansion =
+ trackingExpansion ?? UIKIT_CONTROL.trackingExpansion.value;
+ }, [tracker, trackingExpansion]);
+
+ // Syncs the host's press consumer with the element behind `ref`.
+ // Releasing the element (a replaced node, unmount) disposes the press,
+ // which un-highlights a control it was holding.
+ const attachment = useMemo(
+ () => ({tracker, perEventPointer}),
+ [tracker, perEventPointer],
+ );
+ useAttachment(
+ ref,
+ element => {
+ const detach = getGestureHost(element.ownerDocument).attachConsumer(
+ element,
+ attachment.tracker,
+ {perEventPointer: attachment.perEventPointer},
+ );
+ return () => {
+ isReleasingRef.current = true;
+ try {
+ detach();
+ tracker.dispose();
+ } finally {
+ isReleasingRef.current = false;
+ }
+ };
+ },
+ attachment,
+ );
+
+ // Syncs the host's listeners with the tracker's enabled state, which can
+ // change with any render: the host listens only while an enabled control
+ // is attached (spec:AST-094 FR24). A control disabled under a finger ends
+ // that press here, inside the release guard: a disabled control tracks no
+ // touch, and this Effect calls back no caller, whether the host stops
+ // listening or another control keeps it listening.
+ useIsomorphicLayoutEffect(() => {
+ const element = refRef.current.current;
+ isReleasingRef.current = true;
+ try {
+ if (tracker.isTracking && !(optionsRef.current.isEnabled?.() ?? true)) {
+ tracker.dispose();
+ }
+ if (element != null) {
+ // The update's arena pass can settle other recognizers and trackers
+ // too: it runs as a gesture sync, so none calls its caller back from
+ // this Effect.
+ syncingGestures(() =>
+ getGestureHost(element.ownerDocument).update(element),
+ );
+ }
+ } finally {
+ isReleasingRef.current = false;
+ }
+ });
+
+ return tracker;
+}
diff --git a/packages/core/src/hooks/useLongPress.test.tsx b/packages/core/src/hooks/useLongPress.test.tsx
index ed70a69dca..175b53235f 100644
--- a/packages/core/src/hooks/useLongPress.test.tsx
+++ b/packages/core/src/hooks/useLongPress.test.tsx
@@ -124,6 +124,26 @@ describe('useLongPress', () => {
expect(onLongPress).toHaveBeenCalledTimes(1);
});
+ it('measures the travel on each axis, as its documentation says: a (9, 9) drift keeps the press, 11 px on one axis ends it', () => {
+ const kept = vi.fn();
+ const {result: keeps} = renderHook(() => useLongPress({onLongPress: kept}));
+ act(() => {
+ keeps.current.onTouchStart(touchEvent([{clientX: 100, clientY: 100}]));
+ keeps.current.onTouchMove(touchEvent([{clientX: 109, clientY: 109}]));
+ vi.advanceTimersByTime(500);
+ });
+ expect(kept).toHaveBeenCalledTimes(1);
+
+ const ended = vi.fn();
+ const {result: ends} = renderHook(() => useLongPress({onLongPress: ended}));
+ act(() => {
+ ends.current.onTouchStart(touchEvent([{clientX: 100, clientY: 100}]));
+ ends.current.onTouchMove(touchEvent([{clientX: 100, clientY: 111}]));
+ vi.advanceTimersByTime(500);
+ });
+ expect(ended).not.toHaveBeenCalled();
+ });
+
it('cancels on touch end', () => {
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
@@ -149,4 +169,22 @@ describe('useLongPress', () => {
});
expect(onLongPress).not.toHaveBeenCalled();
});
+ it('takes only the point in its public start: a second argument changes no tolerance (architecture:public-component-api INV12)', () => {
+ const onLongPress = vi.fn();
+ const {result} = renderHook(() =>
+ useLongPress({onLongPress, moveCancelPx: 10}),
+ );
+ // A caller passing a tolerance anyway, which the handlers do not declare.
+ const start: (
+ point: {x: number; y: number},
+ tolerance?: {moveCancelPx?: number},
+ ) => void = result.current.start;
+ act(() => {
+ start({x: 0, y: 0}, {moveCancelPx: 100});
+ result.current.moveTo({x: 20, y: 0});
+ vi.advanceTimersByTime(600);
+ });
+ // The public moveCancelPx (10 px) stands: the press was cancelled.
+ expect(onLongPress).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.ts
index 021a2c9801..0e69fa2ea3 100644
--- a/packages/core/src/hooks/useLongPress.ts
+++ b/packages/core/src/hooks/useLongPress.ts
@@ -14,8 +14,14 @@
*
* Detects a single-finger long-press: fires `onLongPress` with the press
* start point after `delayMs`. Cancels if the finger moves past
- * `moveCancelPx` (treated as a scroll/drag), lifts, or the touch is
- * cancelled. The pending timer is also cleared on unmount.
+ * `moveCancelPx` on either axis (treated as a scroll/drag), lifts, or the
+ * touch is cancelled. The pending timer is also cleared on unmount. The
+ * default duration and tolerance are the long-press recognizer's
+ * (motion/uikit/longPress.ts); the recognizer measures its tolerance as a
+ * distance, as UIKit does, and this hook on each axis: the released rule
+ * that ContextMenu's hold and the menu trigger keep. GUESS (`spec:AST-094`
+ * FR2): the context menu's own movement allowance and press thresholds are
+ * not measured yet (motion/MEASUREMENTS.md M-CM3, M-CM6).
*
* Two ways in, one detector. Spread the touch handlers onto an element, or —
* when the caller already runs its own pointer-event machine, as
@@ -30,10 +36,15 @@
*/
import {useCallback, useEffect, useRef} from 'react';
+import {
+ LONG_PRESS_ALLOWABLE_MOVEMENT_PX,
+ LONG_PRESS_DURATION_MS,
+} from '../motion/uikit/longPress';
-// Default long-press tuning.
-const DEFAULT_DELAY_MS = 500;
-const DEFAULT_MOVE_CANCEL_PX = 10;
+// The long-press numbers have one source, shared with the gesture
+// recognizers (motion/uikit/longPress.ts).
+const DEFAULT_DELAY_MS = LONG_PRESS_DURATION_MS;
+const DEFAULT_MOVE_CANCEL_PX = LONG_PRESS_ALLOWABLE_MOVEMENT_PX;
export interface UseLongPressOptions {
/** Fired with the touch start point once the press is held for `delayMs`. */
@@ -46,6 +57,14 @@ export interface UseLongPressOptions {
moveCancelPx?: number;
}
+/**
+ * @internal A press's own movement tolerance, for a core caller that decides
+ * it as the press starts (useMenuPress's trigger). Not in the hooks entry.
+ */
+export interface LongPressTolerance {
+ moveCancelPx?: number;
+}
+
export interface UseLongPressHandlers {
onTouchStart: (e: React.TouchEvent) => void;
onTouchMove: (e: React.TouchEvent) => void;
@@ -66,9 +85,39 @@ export interface UseLongPressHandlers {
cancel: () => void;
}
+/**
+ * @internal The handlers with a per-press tolerance on `start`, for a core
+ * caller that decides it as the press starts (useMenuPress's trigger). Not in
+ * the hooks entry: the public `useLongPress` takes its tolerance from
+ * `moveCancelPx`.
+ */
+export interface LongPressDetectorHandlers extends Omit<
+ UseLongPressHandlers,
+ 'start'
+> {
+ start: (
+ point: {x: number; y: number},
+ tolerance?: LongPressTolerance,
+ ) => void;
+}
+
export function useLongPress(
options: UseLongPressOptions,
): UseLongPressHandlers {
+ const {start, ...handlers} = useLongPressDetector(options);
+ // The public start takes the point only: a per-press tolerance stays
+ // internal to its core caller (architecture:public-component-api INV12).
+ const startAt = useCallback(
+ (point: {x: number; y: number}) => start(point),
+ [start],
+ );
+ return {...handlers, start: startAt};
+}
+
+/** @internal useLongPress with a per-press tolerance (LongPressDetectorHandlers). */
+export function useLongPressDetector(
+ options: UseLongPressOptions,
+): LongPressDetectorHandlers {
const {
onLongPress,
disabled = false,
@@ -78,6 +127,8 @@ export function useLongPress(
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const startRef = useRef<{x: number; y: number} | null>(null);
+ // The press in progress's tolerance, when its caller chose one at start.
+ const pressToleranceRef = useRef<LongPressTolerance | null>(null);
// Keep the latest callback without re-creating handlers on every render.
const onLongPressRef = useRef(onLongPress);
onLongPressRef.current = onLongPress;
@@ -91,7 +142,7 @@ export function useLongPress(
}, []);
const start = useCallback(
- (point: {x: number; y: number}) => {
+ (point: {x: number; y: number}, tolerance?: LongPressTolerance) => {
if (disabled) {
return;
}
@@ -99,6 +150,7 @@ export function useLongPress(
// also nulls startRef, so order matters.
clear();
startRef.current = {x: point.x, y: point.y};
+ pressToleranceRef.current = tolerance ?? null;
timerRef.current = setTimeout(() => {
const from = startRef.current;
if (from == null) {
@@ -116,9 +168,11 @@ export function useLongPress(
if (from == null) {
return false;
}
+ // This press's own tolerance when its caller chose one, on either axis.
+ const limit = pressToleranceRef.current?.moveCancelPx ?? moveCancelPx;
if (
- Math.abs(point.x - from.x) > moveCancelPx ||
- Math.abs(point.y - from.y) > moveCancelPx
+ Math.abs(point.x - from.x) > limit ||
+ Math.abs(point.y - from.y) > limit
) {
// Treat as a scroll/drag, not a long-press.
clear();
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
index d686fa0a5b..2fddd8e788 100644
--- a/packages/core/src/hooks/useMenuPress.test.tsx
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -484,6 +484,140 @@ describe('useMenuPress — the trigger', () => {
expect(onOpenChange).not.toHaveBeenCalled();
});
+ it("a finger held on the trigger may drift 12 pt and still opens under every primary pointer; past FR29's 13 pt drift allowance it is a scroll (spec:AST-094 FR29, FR43; useMenuPress FR9)", () => {
+ vi.useFakeTimers();
+ const original = window.matchMedia;
+ const pointerIs = (coarse: boolean) => {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ writable: true,
+ value: (query: string) =>
+ ({
+ matches: coarse && query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ }) as MediaQueryList,
+ });
+ };
+ const hold = (drift: number) => {
+ const onOpenChange = vi.fn();
+ const {unmount} = render(<Harness onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ fireEvent.pointerMove(trigger, {...touch(), clientX: 0, clientY: drift});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ const opened = onOpenChange.mock.calls.some(([open]) => open === true);
+ fireEvent.pointerUp(trigger, touch());
+ unmount();
+ return opened;
+ };
+ try {
+ for (const coarse of [true, false]) {
+ pointerIs(coarse);
+ expect(hold(12)).toBe(true);
+ expect(hold(14)).toBe(false);
+ }
+ } finally {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ writable: true,
+ value: original,
+ });
+ }
+ });
+
+ it("measures FR29's drift allowance on each axis where the primary pointer is fine, as on a phone: a finger's (12, 12) settle on the trigger still opens, a 14 px drift does not (useMenuPress FR9)", () => {
+ vi.useFakeTimers();
+ const original = window.matchMedia;
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ writable: true,
+ value: (query: string) =>
+ ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ }) as MediaQueryList,
+ });
+ const hold = (dx: number, dy: number) => {
+ const onOpenChange = vi.fn();
+ const {unmount} = render(<Harness onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ fireEvent.pointerMove(trigger, {...touch(), clientX: dx, clientY: dy});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ const opened = onOpenChange.mock.calls.some(([open]) => open === true);
+ fireEvent.pointerUp(trigger, touch());
+ unmount();
+ return opened;
+ };
+ try {
+ expect(hold(12, 12)).toBe(true);
+ expect(hold(0, 14)).toBe(false);
+ } finally {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ writable: true,
+ value: original,
+ });
+ }
+ });
+
+ it('reads no pointer query from a menu, its rows or its trigger, a press on the trigger included: its drift allowance is the same under every primary pointer (spec:AST-094 FR24, FR43)', () => {
+ vi.useFakeTimers();
+ const original = window.matchMedia;
+ const listening: string[] = [];
+ const read: string[] = [];
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ writable: true,
+ value: (query: string) =>
+ read.push(query) &&
+ ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addEventListener: () => listening.push(query),
+ removeEventListener: () => {},
+ addListener: () => listening.push(query),
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ } as MediaQueryList),
+ });
+ try {
+ const {unmount} = render(<Harness />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ fireEvent.pointerUp(trigger, touch());
+ expect(listening.filter(query => query.includes('pointer'))).toEqual([]);
+ expect(read.filter(query => query.includes('pointer'))).toEqual([]);
+ unmount();
+ } finally {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ writable: true,
+ value: original,
+ });
+ }
+ });
+
it('marks the menu root as carrying the press model', () => {
render(<Harness />);
expect(screen.getByRole('menu')).toHaveAttribute('data-astryx-menu-press');
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index aad8315001..da19dc5342 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -67,10 +67,21 @@ import {
type MenuPressPointerType,
} from './menuPressGesture';
import {MENU_PRESS_MARKER} from './menuPressMarker';
-import {useLongPress, type UseLongPressHandlers} from './useLongPress';
+import {
+ useLongPressDetector,
+ type LongPressDetectorHandlers,
+ type LongPressTolerance,
+} from './useLongPress';
import {edgeAutoscroll} from '../utils/edgeAutoscroll';
import {focusForLastInput} from '../utils/focusReturn';
import {useInteractionModalityTrackingFor} from '../utils/interactionModality';
+import {LONG_PRESS_DURATION_MS} from '../motion/uikit/longPress';
+import {
+ __resetClickGuardForTest,
+ armClickGuard,
+ CLICK_GUARD_WINDOW_MS,
+ withoutClickGuard,
+} from '../utils/clickGuard';
export {MENU_PRESS_MARKER};
const MENU_PRESS_ROOT_SELECTOR = `[${MENU_PRESS_MARKER}]`;
@@ -83,10 +94,25 @@ const MENU_PRESS_ROOT_SELECTOR = `[${MENU_PRESS_MARKER}]`;
*/
export const MENU_PRESS_SURFACE_ATTR = 'data-astryx-menu-press-surface';
-/** How long after a tracked release the browser's click is still swallowed. */
-export const MENU_PRESS_STRAY_CLICK_MS = 400;
+/**
+ * How long after a tracked release the browser's click is still swallowed:
+ * the shared click guard's window (utils/clickGuard.ts).
+ */
+export const MENU_PRESS_STRAY_CLICK_MS = CLICK_GUARD_WINDOW_MS;
/** How long a finger must rest on the trigger before the menu opens under it. */
-export const MENU_PRESS_LONG_PRESS_MS = 500;
+export const MENU_PRESS_LONG_PRESS_MS = LONG_PRESS_DURATION_MS;
+/**
+ * How far a finger held on a DropdownMenu trigger may move before the open,
+ * in CSS px, under every primary pointer: `spec:AST-094` FR29's drift
+ * allowance (FR2's table: unmeasured, a 12 pt move still opened; useMenuPress
+ * FR9, FR43). ContextMenu keeps the long press's own allowable movement.
+ */
+export const MENU_PRESS_TRIGGER_DRIFT_PX = 13;
+
+/** A finger held on the trigger: FR29's drift allowance, the same under every primary pointer. */
+const TRIGGER_TOLERANCE: LongPressTolerance = {
+ moveCancelPx: MENU_PRESS_TRIGGER_DRIFT_PX,
+};
/** Distance from a scrolling menu's edge within which a resting pointer scrolls. */
export const MENU_PRESS_AUTOSCROLL_ZONE_PX = 24;
const AUTOSCROLL_STEP_PX = 6;
@@ -97,7 +123,8 @@ const FOCUSABLE_ROW_SELECTOR =
const INNER_CONTROL_SELECTOR = 'a[href], button, [tabindex]';
// =============================================================================
-// Module state: the activation mark and the stray-click swallower
+// Module state: the activation mark (the stray-click swallower is the
+// shared click guard, utils/clickGuard.ts)
// =============================================================================
let isModelActivation = false;
@@ -112,68 +139,9 @@ export function isMenuPressActivation(): boolean {
return isModelActivation;
}
-interface StrayClickSwallower {
- doc: Document;
- isArmed: boolean;
- timer: ReturnType<typeof setTimeout> | null;
-}
-
-let swallower: StrayClickSwallower | null = null;
-
-function disarmStrayClick(): void {
- if (swallower == null) {
- return;
- }
- swallower.isArmed = false;
- if (swallower.timer != null) {
- clearTimeout(swallower.timer);
- swallower.timer = null;
- }
-}
-
-function onWindowClickCapture(event: MouseEvent): void {
- if (swallower == null || !swallower.isArmed) {
- return;
- }
- // A keyboard's or a screen reader's activation reports detail 0, as does the
- // model's own dispatch. Those are never the browser's stray click.
- if (event.detail === 0 || isModelActivation) {
- return;
- }
- event.preventDefault();
- event.stopImmediatePropagation();
- disarmStrayClick();
-}
-
-function armStrayClick(doc: Document): void {
- const view = doc.defaultView;
- if (view == null) {
- return;
- }
- if (swallower == null || swallower.doc !== doc) {
- if (swallower != null) {
- swallower.doc.defaultView?.removeEventListener(
- 'click',
- onWindowClickCapture,
- true,
- );
- swallower.doc.removeEventListener('pointerdown', disarmStrayClick, true);
- }
- // The window, capture phase: ahead of React's root listener and of any
- // document listener, so no framework sees the click.
- view.addEventListener('click', onWindowClickCapture, true);
- // The next press is a new gesture; its click must never be eaten.
- doc.addEventListener('pointerdown', disarmStrayClick, true);
- swallower = {doc, isArmed: false, timer: null};
- }
- disarmStrayClick();
- swallower.isArmed = true;
- swallower.timer = setTimeout(disarmStrayClick, MENU_PRESS_STRAY_CLICK_MS);
-}
-
-/** Test-only: forget an armed swallower between cases. */
+/** Test-only: forget an armed click guard between cases. */
export function __resetMenuPressForTest(): void {
- disarmStrayClick();
+ __resetClickGuardForTest();
}
// =============================================================================
@@ -351,7 +319,7 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
// handle is held in a ref because the pointer handlers below are stable
// callbacks and the hook is created further down, once `fireLongPress`
// exists.
- const longPressApiRef = useRef<UseLongPressHandlers | null>(null);
+ const longPressApiRef = useRef<LongPressDetectorHandlers | null>(null);
const touchMovePreventerRef = useRef<(() => void) | null>(null);
// The edge autoscroll running now: its scroller, its direction, and the
// re-read of the row under the resting pointer after each step.
@@ -480,36 +448,39 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
);
const activate = useCallback((row: HTMLElement, release: PointerEvent) => {
- const {onActivate} = optionsRef.current;
- isModelActivation = true;
- try {
- if (onActivate != null) {
- onActivate(row, release);
- return;
+ // Every click this dispatches passes the shared click guard.
+ withoutClickGuard(() => {
+ const {onActivate} = optionsRef.current;
+ isModelActivation = true;
+ try {
+ if (onActivate != null) {
+ onActivate(row, release);
+ return;
+ }
+ // The row acts as its own click would. `detail: 0` marks a dispatched
+ // activation, as a keyboard's does, so the click guard lets
+ // it through; the button and modifiers are the release's.
+ row.dispatchEvent(
+ new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ detail: 0,
+ button: release.button,
+ clientX: release.clientX,
+ clientY: release.clientY,
+ screenX: release.screenX,
+ screenY: release.screenY,
+ ctrlKey: release.ctrlKey,
+ shiftKey: release.shiftKey,
+ altKey: release.altKey,
+ metaKey: release.metaKey,
+ }),
+ );
+ } finally {
+ isModelActivation = false;
}
- // The row acts as its own click would. `detail: 0` marks a dispatched
- // activation, as a keyboard's does, so the stray-click swallower lets
- // it through; the button and modifiers are the release's.
- row.dispatchEvent(
- new MouseEvent('click', {
- bubbles: true,
- cancelable: true,
- composed: true,
- detail: 0,
- button: release.button,
- clientX: release.clientX,
- clientY: release.clientY,
- screenX: release.screenX,
- screenY: release.screenY,
- ctrlKey: release.ctrlKey,
- shiftKey: release.shiftKey,
- altKey: release.altKey,
- metaKey: release.metaKey,
- }),
- );
- } finally {
- isModelActivation = false;
- }
+ });
}, []);
// Declared before `step` so the mutual recursion through refs type-checks.
@@ -547,7 +518,8 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
case 'act': {
// Detach before acting: the activation usually closes the menu.
endGesture();
- armStrayClick(doc);
+ // The one swallower stays installed once armed (PR2).
+ armClickGuard(doc, {staysInstalled: true});
if (native != null) {
activate(effect.row, native);
}
@@ -556,7 +528,7 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
case 'settle': {
endGesture();
if (effect.stray) {
- armStrayClick(doc);
+ armClickGuard(doc, {staysInstalled: true});
}
if (effect.dismiss) {
optionsRef.current.onDismiss?.();
@@ -663,8 +635,8 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
lastPointerEventRef.current = event;
const gesture = gestureRef.current;
if (gesture.phase === 'triggerPress') {
- // A finger that travels is scrolling, not holding. The tolerance is
- // the shared hook's, so it cannot drift from ContextMenu's.
+ // A finger that travels past FR29's drift allowance is scrolling,
+ // not holding.
const isPending = longPressApiRef.current?.moveTo({
x: event.clientX,
y: event.clientY,
@@ -769,7 +741,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
// onto its trigger, driven here from the pointer stream this model already
// observes. Its touch handlers go unused; the hold duration, the movement
// tolerance and the timer are what matter, and they now have one home.
- longPressApiRef.current = useLongPress({
+ // The trigger's press takes FR29's drift allowance under every primary
+ // pointer, so no menu, row or trigger reads the pointer query (spec:AST-094
+ // FR24, FR43).
+ longPressApiRef.current = useLongPressDetector({
onLongPress: fireLongPress,
delayMs: options.longPressDelayMs ?? MENU_PRESS_LONG_PRESS_MS,
});
@@ -852,7 +827,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
attach(native.pointerId);
lastPointerEventRef.current = native;
if (pointerType !== 'mouse') {
- longPressApiRef.current?.start({x: native.clientX, y: native.clientY});
+ longPressApiRef.current?.start(
+ {x: native.clientX, y: native.clientY},
+ TRIGGER_TOLERANCE,
+ );
}
step(
{
diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md
index f21c9669b8..fe236bf310 100644
--- a/packages/core/src/motion/MEASUREMENTS.md
+++ b/packages/core/src/motion/MEASUREMENTS.md
@@ -94,7 +94,7 @@ of a page scroll, so many of these can be read off Safari itself.
| M-G12 | `UIKIT_GESTURES.control.trackingExpansion` | Calculator (UIButton): HID press, drag away at 20 px/s filmed at 60 fps; distance from the frame at which the highlight turns off, then back on. | B, C |
| M-G14 | `UIKIT_GESTURES.velocity.scrollReleaseWeight` | Safari page scroll (UIScrollView): HID flings with known speed profiles; back out the release velocity from the coast distance (0.998/ms decay) and compare with this blend on the same samples. | C |
| M-G16 | `UIKIT_GESTURES.velocity.stillness` | Safari page scroll: HID drag, pause P ms, lift; smallest P after which the page does not coast. | C |
-| M-G17 | `UIKIT_GESTURES.click.strayClickWindow` | Not a parity value: confirm in Safari and Chromium that the click follows touchend within one frame. | C |
+| M-G17 | `CLICK_GUARD_WINDOW_MS` (utils/clickGuard.ts) | Not a parity value: confirm in Safari and Chromium that the click follows touchend within one frame. | C |
| M-G18 | `HAPTIC_VIBRATION_PATTERNS` (every kind) | On an Android device, compare against the platform HapticFeedbackConstants for the same moments. | C |
| M-G19 | `UIKIT_GESTURES.press.momentumMemory` | Safari page, hardest HID flick: time from the lift to the last scroll event. | C |
| M-G20 | `LongPressGestureRecognizer` taps phase | Probe app: a UILongPressGestureRecognizer with numberOfTapsRequired 1: HID taps held 0.2, 0.5, 1, 2 s, then the press after gaps of 100 to 600 ms; record which recognize. | C |
diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md
index 4315e523a3..6a0f6b68ac 100644
--- a/packages/core/src/motion/README.md
+++ b/packages/core/src/motion/README.md
@@ -32,6 +32,7 @@ so each keeps its measured value; no shipped component reads the roles yet.
| `selectPage.ts` | Paging: at most one page per release, on `resolveSnapPoint`. |
| `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). |
| `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. |
+| `presentation.ts` | Where each moving element is drawn relative to where the engine hit-tests it, reported by the animator while translate runs; read by the gesture host at touch-down. |
| `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. |
| `__tests__/animator.interaction.browser.spec.ts` | Browser proofs on the interaction harness (Chromium and WebKit): busy main thread, end state through a block, no Layout / Paint, seeked curves, a dialog's backdrop. |
@@ -184,6 +185,16 @@ frame an animation ends needs no main thread and shows no flicker, even when
the main thread is blocked as the curve ends (WebKit's compositor otherwise
falls back to the last value its main thread committed, mid-flight).
+While translate runs, the animator reports the element to `presentation.ts`:
+its offset (the curve's value now minus the value the engine last resolved,
+read live) and a `resolve` that makes the engine hit-test it where it is
+drawn now (one custom-property write). iOS WebKit keeps the transform it
+resolved when an animation went to the compositor, so it reports and
+hit-tests the element at that start for the whole curve, until a style
+write resolves it again. The gesture host resolves the moving elements at
+touch-down, so a touch reaches what is drawn (`gestures/README.md`,
+"Touches on moving elements"). Translation only.
+
Keyframes rather than one `linear()` easing: measured in Chromium, both are
composited and, for the same samples, equally precise; but WebKit's Core
Animation path does not accelerate an effect whose easing is `linear()` with
diff --git a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts
index 282204ee2b..fba9741b82 100644
--- a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts
+++ b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts
@@ -24,9 +24,12 @@
import {fileURLToPath} from 'node:url';
import {
blockMainThread,
+ type BusyWindow,
busyWindowProof,
+ CONTROL_RGB,
countBetween,
markElement,
+ startBusyControl,
startScreencast,
traceRendering,
trackMarker,
@@ -35,6 +38,7 @@ import {expect, test, type Page} from '@playwright/test';
import {build} from 'esbuild';
import type {Animator, MotionHandle} from '../animator';
import type * as MotionBundle from './motionBundle';
+import {controlClock} from './controlClock';
let script = '';
@@ -114,7 +118,10 @@ async function open(page: Page) {
/**
* Starts a spring of TRAVEL px on x, blocks the main thread for 1 s mid-flight
- * and returns the screencast frames with the run\u2019s clock (epoch ms).
+ * and returns the screencast frames with the run\u2019s clock (epoch ms), and
+ * the harness's compositor-only control box tracked from the same frames:
+ * what this machine's compositor presented in that window, which a loaded
+ * runner thins for every animation alike.
*/
async function blockedRun(
page: Page,
@@ -123,6 +130,9 @@ async function blockedRun(
await open(page);
const box = page.locator('#box');
await markElement(box, {inset: MARKER_INSET});
+ // Before the animation, so it is on the compositor first; in the top
+ // strip, clear of the box (top 40 px) and its marker.
+ await startBusyControl(page);
const cast = await startScreencast(page);
// The curve starts when the browser commits it (handle.started).
const start = await page.evaluate(
@@ -139,78 +149,191 @@ async function blockedRun(
minProgressMs: 40,
});
await page.waitForTimeout(200);
- const tracked = await trackMarker(page, await cast.stop());
- return {start, busy, tracked};
+ const frames = await cast.stop();
+ const tracked = await trackMarker(page, frames);
+ const control = await trackMarker(page, frames, {rgb: CONTROL_RGB});
+ return {start, busy, tracked, control};
}
test('a spring keeps advancing every frame through a 1 s main-thread block, on its curve', async ({
page,
browserName,
}) => {
- const {start, busy, tracked} = await blockedRun(page, SLOW);
- const proof = busyWindowProof(tracked, busy, {axis: 'x', settledWithin: 2});
- test
- .info()
- .annotations.push({type: 'busy window', description: proof.summary});
+ const {start, busy, tracked, control} = await blockedRun(page, SLOW);
+ // Judged against what the compositor presented in the same window, not a
+ // display-rate bound: a loaded runner's compositor skips frames for every
+ // animation alike, and the harness reads a slow tail inside the block at
+ // its own pace. The bound's own verdict is recorded beside it.
+ const proof = busyWindowProof(tracked, busy, {
+ axis: 'x',
+ settledWithin: 2,
+ control,
+ });
+ const alone = busyWindowProof(tracked, busy, {axis: 'x', settledWithin: 2});
+ test.info().annotations.push({
+ type: 'busy window',
+ description: `${proof.summary} | without the control: ${alone.verdict.failures.join('; ') || 'pass'}`,
+ });
expect(busy.to - busy.from).toBeGreaterThanOrEqual(1000);
- // The harness's verdict: no stall over two dropped frames, and nearly
- // every expected frame moved (what a loaded runner still meets and a
- // main-thread animation never does). It sets no display-rate bound.
+ // The harness's verdict against the control: the spring moved on every
+ // frame the control moved, and stalled no longer than it (what a
+ // main-thread animation never does; see the next test).
expect(proof.verdict.failures, proof.summary).toEqual([]);
expect(proof.monotonic).toBe(true);
- // And it is the spring: placing each frame inside the block on the
- // analytic curve (inverting it at the frame's position) gives the same time
- // offset for every frame. Chromium stamps frames on the page's clock, so its
- // offset is also near zero; WebKit's screencast clock is rebased, so only
- // the spread is judged there.
+ // And it is the spring. The control moves 240 px out and back every 800
+ // ms, linearly, on the compositor: between two frames where it kept one
+ // direction it advanced |dx| / 0.6 ms of its own curve, whatever the
+ // screencast's timestamps say (a loaded runner stamps some frames late).
+ // Placing the box's position on the analytic curve (inverting it), the
+ // spring must have advanced the same time over each such run of frames.
+ // Chromium also stamps frames on the page's clock, so there the median
+ // offset from the curve is near zero too.
const inside = tracked.filter(
f => f.box != null && f.t > busy.from + 20 && f.t < busy.to - 20,
);
expect(inside.length).toBeGreaterThan(30);
- const offsets = await page.evaluate(
- ({spring, travel, frames}) => {
- const solved = Motion.solveSpring(Motion.toSpring(spring), {
- from: 0,
- to: travel,
- });
- return frames.map(({t, x}) => {
- let lo = 0;
- let hi = 3;
- for (let i = 0; i < 60; i++) {
- const mid = (lo + hi) / 2;
- if (solved.value(mid) < x) {
- lo = mid;
- } else {
- hi = mid;
+ const curveMs = await page.evaluate(
+ ({springs, travel, xs}) =>
+ springs.map(spring => {
+ const solved = Motion.solveSpring(Motion.toSpring(spring), {
+ from: 0,
+ to: travel,
+ });
+ return xs.map(x => {
+ let lo = 0;
+ let hi = 3;
+ for (let i = 0; i < 60; i++) {
+ const mid = (lo + hi) / 2;
+ if (solved.value(mid) < x) {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
}
- }
- return t - lo * 1000;
- });
- },
+ return lo * 1000;
+ });
+ }),
{
- spring: SLOW,
+ // The spring, and one 10% faster: the check must tell them apart.
+ springs: [SLOW, {...SLOW, response: SLOW.response * 0.9}],
travel: TRAVEL,
- frames: inside.map(f => ({
- t: f.t - start,
- x: (f.box?.x ?? NaN) - MARKER_INSET,
- })),
+ xs: inside.map(f => (f.box?.x ?? NaN) - MARKER_INSET),
},
);
+ const [curve, faster] = curveMs;
+ const controlAt = new Map(
+ control.flatMap(f => (f.box == null ? [] : [[f.t, f.box.x] as const])),
+ );
+ // The control's own time at each frame (controlClock): 240 px out in
+ // 400 ms, back in 400 ms, read from its position on the origin most frames
+ // agree with, so no one frame's stamp or direction sets it.
+ const clock = controlClock(
+ inside.map(f => ({t: f.t, x: controlAt.get(f.t) ?? null})),
+ );
+ /** How far the box's curve time drifts from the control's, ms. */
+ const drift = (times: number[]) => {
+ const gaps = clock.map(({i, ms}) => times[i] - ms).sort((x, y) => x - y);
+ return (
+ gaps[Math.floor(gaps.length * 0.9)] - gaps[Math.floor(gaps.length * 0.1)]
+ );
+ };
+ const offsets = inside.map((f, i) => f.t - start - curve[i]);
const sorted = [...offsets].sort((x, y) => x - y);
const median = sorted[Math.floor(sorted.length / 2)];
+ // The offsets' spread reads the screencast's timestamps, which a loaded
+ // runner stamps late on some frames: recorded, judged by the drift instead.
const spread =
sorted[Math.floor(sorted.length * 0.9)] -
sorted[Math.floor(sorted.length * 0.1)];
+ const read = {
+ frames: clock.length,
+ drift: drift(curve),
+ faster: drift(faster),
+ median,
+ spread,
+ };
test.info().annotations.push({
- type: 'time offset of the frames on the curve',
- description: JSON.stringify({median, spread}),
+ type: 'the spring against the control (ms)',
+ description: JSON.stringify(read),
});
- expect(spread).toBeLessThan(25);
+ // Placed on its curve and on the control's, every frame is the same time
+ // apart, to within the 1 px steps of both; a spring 10% off drifts.
+ expect(clock.length, JSON.stringify(read)).toBeGreaterThan(20);
+ expect(read.drift, JSON.stringify(read)).toBeLessThan(12);
+ expect(read.faster, JSON.stringify(read)).toBeGreaterThan(24);
if (browserName === 'chromium') {
expect(Math.abs(median)).toBeLessThan(20);
}
});
+test('a move driven from the main thread freezes through the same block, and the judgment against the control fails it', async ({
+ page,
+}) => {
+ // The proof's negative: the same box and block, with the travel written
+ // each frame from requestAnimationFrame instead of the animator.
+ await open(page);
+ const box = page.locator('#box');
+ await markElement(box, {inset: MARKER_INSET});
+ await startBusyControl(page);
+ const cast = await startScreencast(page);
+ // The travel is written each frame, and the page blocks itself from a task
+ // queued in its eighth frame, as `blockMainThread`'s `during` does for an
+ // animation: the frame's write is on screen as the block starts, so the
+ // block is judged from its start however loaded the machine is (a round
+ // trip from the test could find the box at rest for a while first).
+ await box.evaluate((el, travel) => {
+ const start = performance.now();
+ let frames = 0;
+ const step = (now: number) => {
+ const p = Math.min(1, (now - start) / 2000);
+ el.style.translate = `${travel * p}px 0px`;
+ frames += 1;
+ if (frames === 8) {
+ setTimeout(() => {
+ const from = performance.timeOrigin + performance.now();
+ const until = performance.now() + 1000;
+ while (performance.now() < until) {
+ // Busy: nothing else runs.
+ }
+ (window as unknown as {busy: BusyWindow}).busy = {
+ from,
+ to: performance.timeOrigin + performance.now(),
+ };
+ }, 0);
+ }
+ if (p < 1) {
+ requestAnimationFrame(step);
+ }
+ };
+ requestAnimationFrame(step);
+ }, TRAVEL);
+ const signal = await page.waitForFunction(
+ () => (window as unknown as {busy?: BusyWindow}).busy,
+ undefined,
+ {polling: 50, timeout: 0},
+ );
+ const busy = (await signal.jsonValue()) as BusyWindow;
+ expect(busy.to - busy.from).toBeGreaterThanOrEqual(1000);
+ await page.waitForTimeout(200);
+ const frames = await cast.stop();
+ const tracked = await trackMarker(page, frames);
+ const control = await trackMarker(page, frames, {rgb: CONTROL_RGB});
+ const proof = busyWindowProof(tracked, busy, {
+ axis: 'x',
+ settledWithin: 2,
+ control,
+ });
+ test
+ .info()
+ .annotations.push({type: 'main-thread mutant', description: proof.summary});
+ // It moves on at most a frame or two as the block starts and ends, while
+ // the control keeps moving, and it stalls longer than the control.
+ const moved = proof.control?.moved ?? 0;
+ expect(moved).toBeGreaterThan(10);
+ expect(proof.control?.movedWith ?? 0).toBeLessThan(moved / 4);
+ expect(proof.verdict.failures, proof.summary).not.toEqual([]);
+});
+
test('a spring that ends inside the block keeps showing its end state', async ({
page,
}) => {
diff --git a/packages/core/src/motion/__tests__/controlClock.test.ts b/packages/core/src/motion/__tests__/controlClock.test.ts
new file mode 100644
index 0000000000..ce26cbb48d
--- /dev/null
+++ b/packages/core/src/motion/__tests__/controlClock.test.ts
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {controlClock} from './controlClock';
+
+/** The control's x at its own time `ms`: 240 px out in 400 ms, back in 400. */
+function controlX(ms: number): number {
+ const phase = ((ms % 800) + 800) % 800;
+ return phase < 400 ? phase * 0.6 : 240 - (phase - 400) * 0.6;
+}
+
+/**
+ * Frames 16 ms apart from the control's time `from`, stamped on a clock
+ * `offset` ms ahead of it; `late` adds lateness to chosen frames' stamps.
+ */
+function frames(
+ from: number,
+ count: number,
+ offset: number,
+ late: ReadonlyMap<number, number> = new Map(),
+) {
+ return Array.from({length: count}, (_, i) => {
+ const ms = from + i * 16;
+ return {t: ms + offset + (late.get(i) ?? 0), x: controlX(ms), ms};
+ });
+}
+
+/** How far each reading strays from the control's true time, past a constant. */
+function strays(
+ run: ReadonlyArray<{ms: number}>,
+ clock: ReadonlyArray<{i: number; ms: number}>,
+): number {
+ const gaps = clock.map(({i, ms}) => ms - run[i].ms).sort((a, b) => a - b);
+ return gaps[gaps.length - 1] - gaps[0];
+}
+
+describe('controlClock', () => {
+ it('reads every frame on the control’s own time on an even run', () => {
+ const run = frames(100, 60, 5_000);
+ const clock = controlClock(run);
+ expect(clock.length).toBeGreaterThan(40);
+ expect(strays(run, clock)).toBeLessThan(1e-6);
+ });
+
+ it('reads every frame right when the first usable frame sits just inside the band on its way out and the next usable one comes after the turn', () => {
+ // x 214 on the way out (356.7 ms); the frames until 452.7 ms sit above
+ // the band, and the next usable one, at 208.4, is on the way back.
+ const run = frames(356 + 2 / 3, 60, 5_000);
+ const clock = controlClock(run);
+ expect(strays(run, clock)).toBeLessThan(1e-6);
+ });
+
+ it('reads every other frame right when the first usable frame is stamped 50 ms late', () => {
+ const run = frames(100, 60, 5_000, new Map([[0, 50]]));
+ const clock = controlClock(run).filter(({i}) => i !== 0);
+ expect(strays(run, clock)).toBeLessThan(1e-6);
+ });
+});
diff --git a/packages/core/src/motion/__tests__/controlClock.ts b/packages/core/src/motion/__tests__/controlClock.ts
new file mode 100644
index 0000000000..641dd7e479
--- /dev/null
+++ b/packages/core/src/motion/__tests__/controlClock.ts
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file controlClock.ts
+ * @input Screencast frames: each one's timestamp and the harness's control
+ * box's x on it (240 px out in 400 ms, back in 400 ms, repeating)
+ * @output Exports controlClock: the control's own time at each usable frame
+ * @position Test support for animator.interaction.browser.spec.ts, whose
+ * busy-window proof reads the spring against the control's clock
+ */
+
+/** The control's speed, px per ms: 240 px in 400 ms. */
+const SPEED = 0.6;
+/** One out-and-back, ms. */
+const CYCLE = 800;
+/**
+ * Frames this near a turn are left out: there the two times a position
+ * gives are under 80 ms apart.
+ */
+const EDGE = 24;
+
+export interface ClockFrame {
+ readonly t: number;
+ readonly x: number | null;
+}
+
+/** How far a frame's stamp may run late and still agree with the others, ms. */
+const AGREE = 20;
+
+/** The distance between two times on the cycle, ms. */
+function onCycle(a: number, b: number): number {
+ const d = Math.abs(a - b) % CYCLE;
+ return Math.min(d, CYCLE - d);
+}
+
+/**
+ * The control's time at each usable frame, by index into `frames`. Its
+ * position gives two times a cycle, on the way out and on the way back. The
+ * cycle's origin is the one the most frames agree with, each within AGREE ms
+ * of one of its two times, so no single frame sets it: a frame whose stamp
+ * runs late, or one whose direction its neighbors cannot tell (the next
+ * usable frame past a turn), moves only its own reading. Each frame's
+ * timestamp, measured from that origin, then picks its time.
+ */
+export function controlClock(
+ frames: ReadonlyArray<ClockFrame>,
+): {i: number; ms: number}[] {
+ const usable = frames.flatMap((f, i) =>
+ f.x == null || f.x < EDGE || f.x > 240 - EDGE
+ ? []
+ : [{i, t: f.t, out: f.x / SPEED, back: CYCLE - f.x / SPEED}],
+ );
+ if (usable.length === 0) {
+ return [];
+ }
+ let origin = 0;
+ let agreeing = -1;
+ let spread = Number.POSITIVE_INFINITY;
+ for (let candidate = 0; candidate < CYCLE; candidate++) {
+ let count = 0;
+ let sum = 0;
+ for (const u of usable) {
+ const phase = u.t - candidate;
+ const d = Math.min(onCycle(phase, u.out), onCycle(phase, u.back));
+ if (d <= AGREE) {
+ count += 1;
+ sum += d;
+ }
+ }
+ if (count > agreeing || (count === agreeing && sum < spread)) {
+ origin = candidate;
+ agreeing = count;
+ spread = sum;
+ }
+ }
+ // The same origin a whole number of cycles before the first frame, so the
+ // control's times count up from it.
+ const first = usable[0].t;
+ const anchored = origin + Math.floor((first - origin) / CYCLE) * CYCLE;
+ return usable.map(u => {
+ const expected = u.t - anchored;
+ const cycle = Math.round((expected - u.out) / CYCLE);
+ const candidates = [u.out, u.back, u.out + CYCLE, u.back - CYCLE].map(
+ ms => ms + cycle * CYCLE,
+ );
+ const ms = candidates.reduce((best, c) =>
+ Math.abs(c - expected) < Math.abs(best - expected) ? c : best,
+ );
+ return {i: u.i, ms};
+ });
+}
diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.ts
index 4db132b502..126d7e32c0 100644
--- a/packages/core/src/motion/animator.test.ts
+++ b/packages/core/src/motion/animator.test.ts
@@ -26,6 +26,11 @@ import {
} from './animator';
import {cubicBezier} from './bezier';
import {coast} from './coast';
+import {
+ presentedElements,
+ presentedOffsetOf,
+ resolvePresented,
+} from './presentation';
import {solveDecay} from './decay';
import {solveSpring, solveSpringTowardRamp, toSpring} from './spring';
import {scroll} from './uikit/scroll';
@@ -3901,3 +3906,91 @@ describe('attach', () => {
expect(element.getAttribute('style')).toBeNull();
});
});
+
+describe('the presented offset iOS hit testing reads', () => {
+ it('reports translate while it moves: drawn minus where its animation started, zero before the browser starts it', async () => {
+ const {element, animator} = setup();
+ animator.animate({y: 300}, {spring: springs.sheetPresent});
+ // A call from rest starts at the browser's commit: nothing has moved yet.
+ expect(presentedOffsetOf(element)).toEqual({x: 0, y: 0});
+ await commitFrame(clock);
+ expect(presentedElements()).toContain(element);
+ expect(presentedOffsetOf(element)).toEqual({x: 0, y: 0});
+ clock += 120;
+ await vi.advanceTimersByTimeAsync(120);
+ const offset = presentedOffsetOf(element);
+ expect(offset.x).toBe(0);
+ expect(offset.y).toBeCloseTo(animator.get('y'), 9);
+ expect(offset.y).toBeGreaterThan(0);
+ expect(offset.y).toBeLessThan(300);
+ // The curve ends and its animation retires: nothing left to report.
+ clock += 5000;
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(presentedElements()).not.toContain(element);
+ });
+
+ it('stops reporting on stop, set, dispose and detach, and never for a pseudo-element or opacity alone', async () => {
+ const {element, animator} = setup();
+ const play = async () => {
+ animator.animate({x: 200}, {spring: springs.sheetPresent});
+ await advance(16);
+ expect(presentedElements()).toContain(element);
+ };
+ await play();
+ animator.stop();
+ expect(presentedElements()).not.toContain(element);
+ await play();
+ animator.set({x: 10});
+ expect(presentedElements()).not.toContain(element);
+ await play();
+ const other = document.createElement('div');
+ animator.attach(other);
+ expect(presentedElements()).not.toContain(element);
+ expect(presentedElements()).toContain(other);
+ animator.dispose();
+ expect(presentedElements()).not.toContain(other);
+
+ const fade = setup();
+ fade.animator.animate({opacity: 0}, {spring: springs.sheetPresent});
+ await advance(16);
+ expect(presentedElements()).not.toContain(fade.element);
+
+ const backdrop = setup({pseudoElement: '::backdrop'});
+ backdrop.animator.animate({y: 100}, {spring: springs.sheetPresent});
+ await advance(16);
+ expect(presentedElements()).not.toContain(backdrop.element);
+ backdrop.animator.dispose();
+ fade.animator.dispose();
+ });
+
+ it('resolves where it is drawn on request: one custom-property write, the offset restarting there', async () => {
+ const {element, animator} = setup();
+ animator.play({y: {duration: 1, at: t => 300 * t, velocity: () => 300}});
+ await advance(400);
+ expect(presentedOffsetOf(element).y).toBeCloseTo(120, 6);
+ resolvePresented([element]);
+ expect(element.style.getPropertyValue('--astryx-presented')).toBe('1');
+ expect(presentedOffsetOf(element).y).toBeCloseTo(0, 6);
+ await advance(100);
+ expect(presentedOffsetOf(element).y).toBeCloseTo(30, 6);
+ // Unreported once at rest, the property goes too.
+ animator.stop();
+ expect(element.style.getPropertyValue('--astryx-presented')).toBe('');
+ animator.dispose();
+ });
+
+ it('starts over from the current value when a rebase or a retarget builds a new animation', async () => {
+ const {element, animator} = setup();
+ animator.play({y: {duration: 1, at: t => 300 * t, velocity: () => 300}});
+ await advance(500);
+ expect(presentedOffsetOf(element).y).toBeCloseTo(150, 6);
+ animator.rebase({y: 40});
+ // The new animation starts where the element is drawn now.
+ expect(presentedOffsetOf(element).y).toBeCloseTo(0, 6);
+ await advance(100);
+ expect(presentedOffsetOf(element).y).toBeCloseTo(30, 6);
+ animator.animate({y: 0}, {spring: springs.sheetPresent});
+ expect(presentedOffsetOf(element).y).toBeCloseTo(0, 6);
+ animator.dispose();
+ });
+});
diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.ts
index dcd5676655..eafb3a7b42 100644
--- a/packages/core/src/motion/animator.ts
+++ b/packages/core/src/motion/animator.ts
@@ -181,6 +181,7 @@
import {cubicBezier} from './bezier';
import {solveSpring, toSpring, type SpringDescription} from './spring';
+import {registerPresentedOffset, type PresentedSource} from './presentation';
import {resolveMotion} from './resolveMotion';
import {
reducedMotionCrossFade,
@@ -732,6 +733,9 @@ export const PROMOTION_LINGER_MS = 500;
type Channel = 'translate' | 'rotate' | 'scale' | 'opacity';
+/** The custom property whose writes make WebKit resolve a moving element. */
+const RESOLVE_PROPERTY = '--astryx-presented';
+
const CHANNELS: Record<Channel, ReadonlyArray<MotionProperty>> = {
translate: ['x', 'y'],
rotate: ['rotate'],
@@ -992,6 +996,16 @@ export function createAnimator(
};
/** The call being committed, when it starts from rest. */
let callGroup: StartGroup | null = null;
+ /** The element reported to presentation.ts while translate moves. */
+ let presented: Element | null = null;
+ /**
+ * The translate the engine hit-tests the element at while the compositor
+ * moves it: where the animation started, or where a `resolve` left it.
+ */
+ let hitTested = {x: 0, y: 0};
+ /** Counts the style writes that make WebKit resolve the element again. */
+ let resolutions = 0;
+ let unpresent: (() => void) | null = null;
/** Channels promoted to the element's compositing layer (will-change). */
const promoted = new Set<Channel>();
/** The element's own inline will-change, restored when promotion ends. */
@@ -1090,6 +1104,62 @@ export function createAnimator(
const finalValue = (property: MotionProperty): number =>
segments.get(property)?.target ?? resting[property];
+ /**
+ * Where translate is drawn relative to where the translate animation
+ * started, read live when a touch lands. iOS WebKit keeps the transform it
+ * resolved when the animation went to the compositor (iOS 26.2: the
+ * element's rect and its hit tests stay at the start for the whole curve,
+ * while the computed style is live), until the animation is retired. A
+ * segment whose start still waits for the browser's commit has painted
+ * nothing of its curve yet.
+ */
+ const drawnTranslate = (property: MotionProperty, time: number) => {
+ const segment = segments.get(property);
+ return segment?.group != null && !segment.group.resolved
+ ? segment.at(0)
+ : valueAt(property, time);
+ };
+
+ const presentedSource: PresentedSource = {
+ offset: (time = now()) => {
+ syncPending();
+ return {
+ x: drawnTranslate('x', time) - hitTested.x,
+ y: drawnTranslate('y', time) - hitTested.y,
+ };
+ },
+ resolve: () => {
+ if (target == null) {
+ return;
+ }
+ syncPending();
+ const time = now();
+ // Any style write makes WebKit resolve the element's transform again,
+ // to the value drawn now, where it then stays (iOS 26.2: in the same
+ // task); a custom property changes nothing else.
+ resolutions += 1;
+ target.style.setProperty(RESOLVE_PROPERTY, String(resolutions));
+ hitTested = {x: drawnTranslate('x', time), y: drawnTranslate('y', time)};
+ },
+ };
+
+ /** Reports the element while its translate moves (not a pseudo-element's). */
+ const present = (isMoving: boolean) => {
+ const element = isMoving && pseudoElement == null ? target : null;
+ if (element === presented) {
+ return;
+ }
+ unpresent?.();
+ unpresent = null;
+ if (presented instanceof HTMLElement) {
+ presented.style.removeProperty(RESOLVE_PROPERTY);
+ }
+ presented = element;
+ if (element != null) {
+ unpresent = registerPresentedOffset(element, presentedSource);
+ }
+ };
+
const writeInline = (
channel: Channel,
value: (property: MotionProperty) => number,
@@ -1202,6 +1272,16 @@ export function createAnimator(
}
}
const moving = properties.filter(p => segments.has(p));
+ if (channel === 'translate') {
+ // The animation built below starts from the value at `time` (its first
+ // keyframe); a rebase or a retarget builds a new one, so a new start.
+ hitTested = {x: valueAt('x', time), y: valueAt('y', time)};
+ present(
+ moving.length > 0 &&
+ target != null &&
+ typeof target.animate === 'function',
+ );
+ }
if (
moving.length === 0 ||
target == null ||
@@ -1431,6 +1511,9 @@ export function createAnimator(
clearTimeout(retireTimers.get(channel));
retireTimers.delete(channel);
running.delete(channel);
+ if (channel === 'translate') {
+ present(false);
+ }
// A pseudo-element holds its resting value, unless the stylesheet
// takes it back now (a borrowed dip that has ended).
const handsBack =
@@ -2990,6 +3073,7 @@ export function createAnimator(
return;
}
flushDeferred();
+ present(false);
if (next == null) {
// Unmount, unless a node replaces this one in the same task (React's
// replacement order: attach(null), then the new node): nothing is
@@ -3687,6 +3771,7 @@ export function createAnimator(
clearTimeout(timer);
}
retireTimers.clear();
+ present(false);
for (const timer of retireLooks.values()) {
clearTimeout(timer);
}
diff --git a/packages/core/src/motion/presentation.ts b/packages/core/src/motion/presentation.ts
new file mode 100644
index 0000000000..580ef91d3e
--- /dev/null
+++ b/packages/core/src/motion/presentation.ts
@@ -0,0 +1,149 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file presentation.ts
+ * @input Animators reporting, while a translate runs on the compositor, how
+ * far their element is drawn from where the engine hit-tests it, and how
+ * to make the engine hit-test it where it is drawn
+ * @output Exports registerPresentedOffset, presentedElements,
+ * presentedOffsetOf, resolvePresented and watchPresentedElements: the
+ * registry the gesture host reads at touch-down to send a touch to what is
+ * drawn, and follows to keep a drag on a moving element blocking
+ * @position Motion foundation (DOM, no React). Written by animator.ts, read
+ * by gestures/GestureHost.ts; internal to core
+ *
+ * iOS WebKit hit-tests an element that a Web Animations transform moves on
+ * the compositor where the animation STARTED: it keeps the transform it
+ * resolved when the animation went to the compositor, so event targets,
+ * `elementFromPoint` and `getBoundingClientRect` stay there for the whole
+ * curve, while the inline style holds the value the curve starts from (the
+ * animator writes it there while the curve runs) and the computed style is
+ * live (iOS 26.2, measured). A style write on the element makes it
+ * resolve the transform again, to the value drawn at that moment, and it
+ * stays there. UIKit keeps an interruptible animation hit-testable where it
+ * is drawn (UIViewPropertyAnimator), so the host corrects for it from this
+ * registry.
+ *
+ * Translation only: a scale or a rotation (a zoom transition, a lifted
+ * preview) is still hit at its untransformed box.
+ *
+ * An engine workaround (`spec:AST-013` FR6). Review condition: re-measure on
+ * each iOS release, and remove this registry and the host's correction once
+ * iOS WebKit hit-tests a compositor-moved element where it is drawn.
+ * Regression fixture: gestures/__tests__/presentedHitTesting.test.ts.
+ */
+
+import {parentAcrossShadow} from '../utils/flatTree';
+
+/** How far an element is drawn from where the engine hit-tests it, CSS px. */
+export interface PresentedOffset {
+ readonly x: number;
+ readonly y: number;
+}
+
+/** What an animator reports for an element it is moving. */
+export interface PresentedSource {
+ /**
+ * The element's offset at `time` (ms on the `performance.now()` clock,
+ * now by default), read live (the motion keeps going): a past time says
+ * where it was drawn then, against where the engine hit-tests it now.
+ */
+ offset(time?: number): PresentedOffset;
+ /**
+ * Makes the engine hit-test the element where it is drawn now (one style
+ * write); the offset restarts from there.
+ */
+ resolve(): void;
+}
+
+const ZERO: PresentedOffset = {x: 0, y: 0};
+
+const sources = new Map<Element, PresentedSource>();
+const watchers = new Set<() => void>();
+
+/** Tell every watcher the reported elements changed; one's throw stops none. */
+function notifyWatchers(): void {
+ for (const watcher of [...watchers]) {
+ try {
+ watcher();
+ } catch (error) {
+ queueMicrotask(() => {
+ throw error;
+ });
+ }
+ }
+}
+
+/**
+ * Call `listener` each time an element starts or stops being reported.
+ * Returns the function that stops it.
+ */
+export function watchPresentedElements(listener: () => void): () => void {
+ watchers.add(listener);
+ return () => {
+ watchers.delete(listener);
+ };
+}
+
+/**
+ * Report an element drawn away from where the engine hit-tests it. Returns
+ * the function that removes the report.
+ */
+export function registerPresentedOffset(
+ element: Element,
+ source: PresentedSource,
+): () => void {
+ sources.set(element, source);
+ notifyWatchers();
+ return () => {
+ if (sources.get(element) === source) {
+ sources.delete(element);
+ notifyWatchers();
+ }
+ };
+}
+
+/** The elements reported now. */
+export function presentedElements(): ReadonlyArray<Element> {
+ return sources.size === 0 ? [] : [...sources.keys()];
+}
+
+/**
+ * How far `element` is drawn from where the engine hit-tests it: its own
+ * offset plus those of its moving ancestors along the flat tree (through a
+ * slot to the panel it is drawn in, and across shadow roots), now or at
+ * `time` (ms on the `performance.now()` clock).
+ */
+export function presentedOffsetOf(
+ element: Element,
+ time?: number,
+): PresentedOffset {
+ if (sources.size === 0) {
+ return ZERO;
+ }
+ let x = 0;
+ let y = 0;
+ for (
+ let node: Node | null = element;
+ node != null;
+ node = parentAcrossShadow(node)
+ ) {
+ const source = node instanceof Element ? sources.get(node) : undefined;
+ if (source != null) {
+ const offset = source.offset(time);
+ x += offset.x;
+ y += offset.y;
+ }
+ }
+ return {x, y};
+}
+
+/**
+ * Makes the engine hit-test each of `elements` where it is drawn now; the
+ * next hit test (an `elementFromPoint`) flushes the writes.
+ */
+export function resolvePresented(elements: Iterable<Element>): void {
+ for (const element of elements) {
+ sources.get(element)?.resolve();
+ }
+}
diff --git a/packages/core/src/motion/uikit/gestures.test.ts b/packages/core/src/motion/uikit/gestures.test.ts
index bdeb7dbd5a..0eb8b5edbb 100644
--- a/packages/core/src/motion/uikit/gestures.test.ts
+++ b/packages/core/src/motion/uikit/gestures.test.ts
@@ -57,6 +57,7 @@ describe('UIKIT_GESTURES', () => {
expect(UIKIT_GESTURES.pinch.hysteresis.value).toBe(8);
expect(UIKIT_GESTURES.control.trackingExpansion.value).toBe(70);
expect(UIKIT_GESTURES.velocity.currentWeight.value).toBe(0.2);
+ expect(UIKIT_GESTURES.velocity.scrollReleaseWeight.value).toBe(0.25);
});
it('holds the press entries to the press model, one value per use', () => {
diff --git a/packages/core/src/motion/uikit/gestures.ts b/packages/core/src/motion/uikit/gestures.ts
index 0a3900a2e2..eb250257d0 100644
--- a/packages/core/src/motion/uikit/gestures.ts
+++ b/packages/core/src/motion/uikit/gestures.ts
@@ -41,6 +41,10 @@
*/
import {DELAYS_CONTENT_TOUCHES_MS} from './scroll';
+import {
+ LONG_PRESS_ALLOWABLE_MOVEMENT_PX,
+ LONG_PRESS_DURATION_MS,
+} from './longPress';
export type GestureConstantUnit =
'px' | 'ms' | 'px/s' | 'rad' | 'ratio' | 'count';
@@ -96,7 +100,7 @@ export const UIKIT_LONG_PRESS = {
* @source measured: UIKit lab, iOS 26.2 simulator, ivar reads confirmed
* with HID touches, Oct 23 2026: _minimumPressDuration 0.5
*/
- minimumPressDuration: {value: 500, unit: 'ms'},
+ minimumPressDuration: {value: LONG_PRESS_DURATION_MS, unit: 'ms'},
/**
* UILongPressGestureRecognizer.allowableMovement default, a distance.
* @source apple-docs
@@ -104,7 +108,7 @@ export const UIKIT_LONG_PRESS = {
* @source measured: UIKit lab, iOS 26.2 simulator, ivar reads confirmed
* with HID touches, Oct 23 2026: a (7, 7) drift begins, (7.2, 7.2) fails
*/
- allowableMovement: {value: 10, unit: 'px'},
+ allowableMovement: {value: LONG_PRESS_ALLOWABLE_MOVEMENT_PX, unit: 'px'},
} as const satisfies Record<string, GestureConstant>;
export const UIKIT_PAN = {
@@ -283,15 +287,19 @@ export const UIKIT_VELOCITY = {
stillness: {value: 40, unit: 'ms'},
} as const satisfies Record<string, GestureConstant>;
+/**
+ * The stray-click window, kept for importers written before the click guard
+ * owned it: `CLICK_GUARD_WINDOW_MS` (utils/clickGuard.ts) bounds the stray
+ * click, and `UIKIT_GESTURES` leaves this out.
+ * @deprecated Read `CLICK_GUARD_WINDOW_MS`.
+ */
export const UIKIT_CLICK = {
/**
- * Longest the system waits for the browser's click after a touch it
- * swallows. iOS and Chromium deliver it right after `touchend`; this only
- * bounds a click that never comes.
- * @source GUESS — A safety bound, not a UIKit number.
+ * Longest a guard waits for the browser's click after a touch it swallowed.
+ * @source GUESS — A safety bound, not a UIKit number; the click guard's own.
* @measure M-G17
*/
- strayClickWindow: {value: 1000, unit: 'ms'},
+ strayClickWindow: {value: 400, unit: 'ms'},
} as const satisfies Record<string, GestureConstant>;
/**
@@ -311,7 +319,6 @@ export const UIKIT_GESTURES = {
control: UIKIT_CONTROL,
press: UIKIT_PRESS,
velocity: UIKIT_VELOCITY,
- click: UIKIT_CLICK,
} as const;
/**
diff --git a/packages/core/src/motion/uikit/longPress.test.ts b/packages/core/src/motion/uikit/longPress.test.ts
new file mode 100644
index 0000000000..68edb9f655
--- /dev/null
+++ b/packages/core/src/motion/uikit/longPress.test.ts
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file longPress.test.ts
+ * @input Uses vitest, React Testing Library and node:fs over the core sources
+ * @output The long-press numbers have one source: the constants table's
+ * entries, the long-press recognizer's defaults, useLongPress's hold and
+ * useMenuPress's trigger hold all read longPress.ts
+ * @position Unit tests of packages/core/src/motion/uikit/longPress.ts
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {act, renderHook} from '@testing-library/react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+import {LongPressGestureRecognizer} from '../../gestures/LongPressGestureRecognizer';
+import {useLongPress} from '../../hooks/useLongPress';
+import {MENU_PRESS_LONG_PRESS_MS} from '../../hooks/useMenuPress';
+import {UIKIT_GESTURES} from './gestures';
+import {
+ LONG_PRESS_ALLOWABLE_MOVEMENT_PX,
+ LONG_PRESS_DURATION_MS,
+} from './longPress';
+
+const CORE = path.resolve(__dirname, '../..');
+
+/** Every core module `entry` reaches through value imports. */
+function reachable(entry: string): string[] {
+ const statement =
+ /^\s*(import|export)\s+(type\s+)?([^'";]*?\s+from\s+)?'([^']+)';/gms;
+ const seen = new Set<string>();
+ const queue = [path.join(CORE, entry)];
+ while (queue.length > 0) {
+ const file = queue.pop() as string;
+ if (seen.has(file)) {
+ continue;
+ }
+ seen.add(file);
+ for (const match of fs.readFileSync(file, 'utf8').matchAll(statement)) {
+ const [, , isTypeOnly, , specifier] = match;
+ if (isTypeOnly != null || !specifier.startsWith('.')) {
+ continue;
+ }
+ const base = path.resolve(path.dirname(file), specifier);
+ const resolved = [
+ `${base}.ts`,
+ `${base}.tsx`,
+ path.join(base, 'index.ts'),
+ path.join(base, 'index.tsx'),
+ ].find(candidate => fs.existsSync(candidate));
+ if (resolved != null) {
+ queue.push(resolved);
+ }
+ }
+ }
+ return [...seen].map(file => path.relative(CORE, file));
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('the long-press numbers', () => {
+ it('have one source: the table, the recognizer, useLongPress and useMenuPress read it', () => {
+ expect(UIKIT_GESTURES.longPress.minimumPressDuration.value).toBe(
+ LONG_PRESS_DURATION_MS,
+ );
+ expect(UIKIT_GESTURES.longPress.allowableMovement.value).toBe(
+ LONG_PRESS_ALLOWABLE_MOVEMENT_PX,
+ );
+ const recognizer = new LongPressGestureRecognizer();
+ expect(recognizer.minimumPressDuration).toBe(LONG_PRESS_DURATION_MS);
+ expect(recognizer.allowableMovement).toBe(LONG_PRESS_ALLOWABLE_MOVEMENT_PX);
+ expect(MENU_PRESS_LONG_PRESS_MS).toBe(LONG_PRESS_DURATION_MS);
+
+ vi.useFakeTimers();
+ const onLongPress = vi.fn();
+ const {result} = renderHook(() => useLongPress({onLongPress}));
+ act(() => {
+ result.current.start({x: 0, y: 0});
+ vi.advanceTimersByTime(LONG_PRESS_DURATION_MS - 1);
+ });
+ expect(onLongPress).not.toHaveBeenCalled();
+ act(() => {
+ expect(
+ result.current.moveTo({x: LONG_PRESS_ALLOWABLE_MOVEMENT_PX, y: 0}),
+ ).toBe(true);
+ vi.advanceTimersByTime(1);
+ });
+ expect(onLongPress).toHaveBeenCalledTimes(1);
+ });
+
+ it('reach the hooks through longPress.ts alone', () => {
+ expect(reachable('hooks/useLongPress.ts')).toContain(
+ path.join('motion', 'uikit', 'longPress.ts'),
+ );
+ });
+});
diff --git a/packages/core/src/motion/uikit/longPress.ts b/packages/core/src/motion/uikit/longPress.ts
new file mode 100644
index 0000000000..f996f2604a
--- /dev/null
+++ b/packages/core/src/motion/uikit/longPress.ts
@@ -0,0 +1,29 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file longPress.ts
+ * @input Nothing
+ * @output Exports LONG_PRESS_DURATION_MS and LONG_PRESS_ALLOWABLE_MOVEMENT_PX
+ * @position The one source of the long-press numbers. The constants table's
+ * `longPress` entries (gestures.ts, which carry the sources) take their
+ * values from here, and so do `useLongPress` and `useMenuPress`, which
+ * import only this module: a menu does not pay for the whole gestures
+ * table.
+ *
+ * SYNC: When modified, update longPress.test.ts.
+ */
+
+/**
+ * How long a finger rests before a long press begins, in ms:
+ * `UILongPressGestureRecognizer.minimumPressDuration` (see
+ * `UIKIT_GESTURES.longPress.minimumPressDuration` for the source).
+ */
+export const LONG_PRESS_DURATION_MS = 500;
+
+/**
+ * How far the finger may travel from where it landed before a pending long
+ * press fails, in px, as a distance:
+ * `UILongPressGestureRecognizer.allowableMovement` (see
+ * `UIKIT_GESTURES.longPress.allowableMovement` for the source).
+ */
+export const LONG_PRESS_ALLOWABLE_MOVEMENT_PX = 10;
diff --git a/packages/core/src/motion/uikit/tableImports.test.ts b/packages/core/src/motion/uikit/tableImports.test.ts
index c1bf495809..97715084ab 100644
--- a/packages/core/src/motion/uikit/tableImports.test.ts
+++ b/packages/core/src/motion/uikit/tableImports.test.ts
@@ -19,6 +19,8 @@ import {describe, expect, it} from 'vitest';
/** The tables every touch module may share: the animator and gestures read them. */
const SHARED_TABLES = new Set([
'motion/uikit/gestures.ts',
+ // The long-press values: useLongPress and the menus' press model read them.
+ 'motion/uikit/longPress.ts',
'motion/uikit/navigation.ts',
'motion/uikit/scroll.ts',
'motion/uikit/springs.ts',
diff --git a/packages/core/src/motion/uikit/uikit.test.ts b/packages/core/src/motion/uikit/uikit.test.ts
index 9b97ab9b79..df4c783cd9 100644
--- a/packages/core/src/motion/uikit/uikit.test.ts
+++ b/packages/core/src/motion/uikit/uikit.test.ts
@@ -20,10 +20,14 @@ import {
PRESS_ONSET_MS,
PRESS_SCROLL_BRAKE_MS,
} from '../../utils/pressGesture';
+import * as uikit from '.';
import {scroll, springs, timing} from '.';
+import {CLICK_GUARD_WINDOW_MS} from '../../utils/clickGuard';
+import {UIKIT_GESTURES} from './gestures';
-// Modules in this folder that hold no table of their own (none yet).
-const NON_TABLE_FILES: string[] = [];
+// Modules in this folder that hold no table of their own: longPress.ts holds
+// only the long-press numbers, whose sources gestures.ts's entries carry.
+const NON_TABLE_FILES: string[] = ['longPress.ts'];
// Every domain file carries its sources as JSDoc tags: a new one is enforced
// the moment it lands.
const TABLE_FILES = fs
@@ -274,6 +278,24 @@ function expectSourced(key: string, doc: string) {
}
describe('UIKit constants table: values', () => {
+ it('carries no stray-click guess: the click guard owns its window (M-G17)', () => {
+ // CLICK_GUARD_WINDOW_MS (utils/clickGuard.ts) bounds the stray click; the
+ // table's 1000 ms guess had no reader left once the guard replaced the
+ // host's swallower.
+ expect(Object.keys(UIKIT_GESTURES)).not.toContain('click');
+ expect(
+ Object.values(UIKIT_GESTURES).some(group => 'strayClickWindow' in group),
+ ).toBe(false);
+ });
+
+ it("keeps UIKIT_CLICK in the barrel for importers written before the click guard, with the guard's window", () => {
+ // internal/motion.ts and its importers read it from the barrel.
+ expect(uikit.UIKIT_CLICK.strayClickWindow.value).toBe(
+ CLICK_GUARD_WINDOW_MS,
+ );
+ expect(Object.values(UIKIT_GESTURES)).not.toContain(uikit.UIKIT_CLICK);
+ });
+
it('names each platform preset for its use, not its source', () => {
// spec AST-094 FR4: a role is named for its use; the source stays in the
// JSDoc (SwiftUI .smooth, UISpringTimingParameters(), Core Animation's
diff --git a/packages/core/src/privateAttributes/hapticSwitch.stylex.ts b/packages/core/src/privateAttributes/hapticSwitch.stylex.ts
new file mode 100644
index 0000000000..570d667dbe
--- /dev/null
+++ b/packages/core/src/privateAttributes/hapticSwitch.stylex.ts
@@ -0,0 +1,27 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file privateAttributes/hapticSwitch.stylex.ts
+ * @input The hidden switch a label's tap haptic plays through
+ * @output markHapticSwitch, which marks that switch, and isHapticSwitch,
+ * which reads the mark
+ * @position Owner module of the private haptic-switch attribute
+ * (`architecture:public-component-api` INV23): the only file that writes
+ * its name. gestures/haptics.ts marks its hidden switch; the click guard
+ * skips that switch without importing the haptics module, so a gesture
+ * that only guards clicks carries no haptics code
+ * (`architecture:react-component-runtime` INV13). No package entry
+ * exports it.
+ */
+
+const HAPTIC_SWITCH = 'data-astryx-haptic-switch';
+
+/** Marks the hidden switch a label's tap haptic plays through. */
+export function markHapticSwitch(element: Element): void {
+ element.setAttribute(HAPTIC_SWITCH, '');
+}
+
+/** Whether `target` is that hidden switch. */
+export function isHapticSwitch(target: EventTarget | null): boolean {
+ return target instanceof Element && target.hasAttribute(HAPTIC_SWITCH);
+}
diff --git a/packages/core/src/utils/clickGuard.test.ts b/packages/core/src/utils/clickGuard.test.ts
new file mode 100644
index 0000000000..6b4ae7cd3a
--- /dev/null
+++ b/packages/core/src/utils/clickGuard.test.ts
@@ -0,0 +1,176 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file clickGuard.test.ts
+ * @input Uses vitest and jsdom
+ * @output An armed guard swallows the browser's next click before any page
+ * listener and is spent; a click whose detail is 0, one dispatched inside
+ * withoutClickGuard and the haptic switch's click pass; the next
+ * pointerdown and the window disarm it; it hears pointerdown only while
+ * armed; the menu press model's click listener stays, one per document,
+ * ahead of later ones, while the gesture host's lasts only while armed;
+ * the menu press model and the gesture host arm this one guard
+ * @position Unit tests of packages/core/src/utils/clickGuard.ts
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+import {GestureHost} from '../gestures/GestureHost';
+import {coarsePrimaryPointer} from '../gestures/__tests__/pointerQuery';
+import {markHapticSwitch} from '../privateAttributes/hapticSwitch.stylex';
+import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';
+import {MENU_PRESS_STRAY_CLICK_MS} from '../hooks/useMenuPress';
+import {
+ __resetClickGuardForTest,
+ armClickGuard,
+ CLICK_GUARD_WINDOW_MS,
+ disarmClickGuard,
+ isClickGuardArmed,
+ withoutClickGuard,
+} from './clickGuard';
+
+afterEach(() => {
+ __resetClickGuardForTest();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+});
+
+function click(target: EventTarget, detail = 1): MouseEvent {
+ const event = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ detail,
+ });
+ target.dispatchEvent(event);
+ return event;
+}
+
+function button(): HTMLButtonElement {
+ const element = document.createElement('button');
+ document.body.append(element);
+ return element;
+}
+
+describe('clickGuard', () => {
+ it("swallows the browser's next click before any page listener, once", () => {
+ const target = button();
+ const heard = vi.fn();
+ document.addEventListener('click', heard, {capture: true});
+ armClickGuard(document);
+ expect(click(target).defaultPrevented).toBe(true);
+ expect(heard).not.toHaveBeenCalled();
+ expect(isClickGuardArmed(document)).toBe(false);
+ expect(click(target).defaultPrevented).toBe(false);
+ expect(heard).toHaveBeenCalledTimes(1);
+ document.removeEventListener('click', heard, {capture: true});
+ });
+
+ it("keeps its place ahead of a window listener the page adds after the menu press model's first gesture: installed once per document (module:DropdownMenu/useMenuPress PR2)", () => {
+ const target = button();
+ armClickGuard(document, {staysInstalled: true});
+ disarmClickGuard(document);
+ const heard = vi.fn();
+ window.addEventListener('click', heard, {capture: true});
+ try {
+ // A later arm, the gesture host's included, uses the staying listener.
+ armClickGuard(document);
+ expect(click(target).defaultPrevented).toBe(true);
+ expect(heard).not.toHaveBeenCalled();
+ // Disarmed, every click passes, the page's listener included.
+ expect(click(target).defaultPrevented).toBe(false);
+ expect(heard).toHaveBeenCalledTimes(1);
+ } finally {
+ window.removeEventListener('click', heard, {capture: true});
+ }
+ });
+
+ it('armed by the gesture host, keeps its click listener only while armed: it goes at the click, at the next pointerdown and after its window (spec:AST-094 FR24)', () => {
+ vi.useFakeTimers();
+ const target = button();
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ const clicks = (spy: typeof add) =>
+ spy.mock.calls.filter(call => call[0] === 'click').length;
+ armClickGuard(document);
+ expect(clicks(add)).toBe(1);
+ expect(click(target).defaultPrevented).toBe(true);
+ expect(clicks(remove)).toBe(1);
+ armClickGuard(document);
+ target.dispatchEvent(new Event('pointerdown', {bubbles: true}));
+ expect(clicks(remove)).toBe(2);
+ armClickGuard(document);
+ vi.advanceTimersByTime(CLICK_GUARD_WINDOW_MS);
+ expect(clicks(remove)).toBe(3);
+ expect(clicks(add)).toBe(3);
+ });
+
+ it("lets through a keyboard's or a screen reader's click, a click the caller dispatches, and the haptic switch's", () => {
+ const target = button();
+ armClickGuard(document);
+ expect(click(target, 0).defaultPrevented).toBe(false);
+ expect(withoutClickGuard(() => click(target)).defaultPrevented).toBe(false);
+ const haptic = document.createElement('input');
+ markHapticSwitch(haptic);
+ document.body.append(haptic);
+ expect(click(haptic).defaultPrevented).toBe(false);
+ // Still armed for the browser's own click.
+ expect(isClickGuardArmed(document)).toBe(true);
+ expect(click(target).defaultPrevented).toBe(true);
+ });
+
+ it('disarms at the next pointerdown, and after its window', () => {
+ vi.useFakeTimers();
+ const target = button();
+ armClickGuard(document);
+ target.dispatchEvent(new Event('pointerdown', {bubbles: true}));
+ expect(isClickGuardArmed(document)).toBe(false);
+ expect(click(target).defaultPrevented).toBe(false);
+
+ armClickGuard(document);
+ vi.advanceTimersByTime(CLICK_GUARD_WINDOW_MS - 1);
+ expect(isClickGuardArmed(document)).toBe(true);
+ vi.advanceTimersByTime(1);
+ expect(isClickGuardArmed(document)).toBe(false);
+ expect(click(target).defaultPrevented).toBe(false);
+ });
+
+ it("hears pointerdown only while armed, and keeps the menu press model's one click listener", () => {
+ armClickGuard(document, {staysInstalled: true});
+ disarmClickGuard(document);
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ armClickGuard(document);
+ expect(add.mock.calls.map(call => call[0])).toEqual(['pointerdown']);
+ disarmClickGuard(document);
+ expect(remove.mock.calls.map(call => call[0])).toEqual(['pointerdown']);
+ });
+
+ it('is the one guard the menu press model and the gesture host arm', () => {
+ // A phone: the host attaches only where the primary pointer is coarse.
+ const restorePointer = coarsePrimaryPointer();
+ try {
+ expect(MENU_PRESS_STRAY_CLICK_MS).toBe(CLICK_GUARD_WINDOW_MS);
+ // A tap the host's recognizer claims arms the shared guard for the
+ // browser's click.
+ const host = new GestureHost(document);
+ const target = button();
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const detach = host.attach(target, tap);
+ const contact = {identifier: 1, clientX: 5, clientY: 5, target};
+ for (const type of ['touchstart', 'touchend'] as const) {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ Object.defineProperty(event, 'changedTouches', {value: [contact]});
+ Object.defineProperty(event, 'touches', {
+ value: type === 'touchend' ? [] : [contact],
+ });
+ target.dispatchEvent(event);
+ }
+ expect(isClickGuardArmed(document)).toBe(true);
+ expect(click(target).defaultPrevented).toBe(true);
+ detach();
+ } finally {
+ restorePointer();
+ }
+ });
+});
diff --git a/packages/core/src/utils/clickGuard.ts b/packages/core/src/utils/clickGuard.ts
new file mode 100644
index 0000000000..d17ed35aee
--- /dev/null
+++ b/packages/core/src/utils/clickGuard.ts
@@ -0,0 +1,167 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file clickGuard.ts
+ * @input A document whose gesture already acted (a menu row's release, a
+ * touch a gesture recognizer claimed)
+ * @output Exports armClickGuard (and its ClickGuardOptions),
+ * disarmClickGuard, isClickGuardArmed, withoutClickGuard and
+ * CLICK_GUARD_WINDOW_MS
+ * @position The one guard for the browser's click after a gesture that
+ * already acted (useMenuPress FR5, `spec:AST-057` FR6), shared by the menu
+ * press model (hooks/useMenuPress.ts) and the gesture host
+ * (gestures/GestureHost.ts)
+ *
+ * Armed at a tracked release, it swallows the next click the browser
+ * reports, on the window's capture phase through the input stream
+ * (utils/inputStream.ts), so no framework sees it. It disarms on that click,
+ * at the next `pointerdown` (a new gesture, whose click must act), or after
+ * {@link CLICK_GUARD_WINDOW_MS}; disarmed, it lets every click pass. Its
+ * click listener comes with an arm. Once the menu press model arms it, it
+ * stays: installed once per document and armed per gesture, it keeps its
+ * place ahead of any window listener the page adds later
+ * (`module:DropdownMenu/useMenuPress` PR2, which `spec:AST-094` FR24 counts
+ * once per page). Armed only by the gesture host, it goes when the guard
+ * disarms: a release-armed swallower is press work (FR24).
+ *
+ * Some clicks always pass:
+ * - a click whose `detail` is 0: a keyboard's, a screen reader's, or an
+ * activation the page dispatches;
+ * - a click dispatched inside {@link withoutClickGuard}: a menu row's own
+ * activation, or a recognizer's replayed or retargeted click;
+ * - the hidden haptic switch's click (gestures/haptics.ts), the tap's own
+ * feedback.
+ *
+ * SYNC: When modified, update clickGuard.test.ts, hooks/useMenuPress.ts and
+ * gestures/GestureHost.ts.
+ */
+
+import {isHapticSwitch} from '../privateAttributes/hapticSwitch.stylex';
+import {subscribeInput} from './inputStream';
+
+/**
+ * How long after a release the browser's click is still swallowed, in ms.
+ * Browsers report it right after the release; the next `pointerdown`
+ * disarms the guard first, so this bounds only a click that never comes.
+ */
+export const CLICK_GUARD_WINDOW_MS = 400;
+
+/** Options for {@link armClickGuard}. */
+export interface ClickGuardOptions {
+ /**
+ * The menu press model's arm: the window's click listener stays from then
+ * on (`module:DropdownMenu/useMenuPress` PR2). Any other arm keeps it only
+ * while the guard is armed (`spec:AST-094` FR24).
+ * @default false
+ */
+ readonly staysInstalled?: boolean;
+}
+
+interface Guard {
+ readonly unsubscribers: (() => void)[];
+ timer: ReturnType<typeof setTimeout> | null;
+}
+
+const guards = new Map<Document, Guard>();
+/** The click listeners that stay, by window: the menu press model's (PR2). */
+const stayingClickListeners = new WeakMap<Window, () => void>();
+let unguardedDepth = 0;
+
+/** Listen for the next click on `view`'s capture phase; returns the stop. */
+function listenForClicks(view: Window): () => void {
+ return subscribeInput(
+ view,
+ 'click',
+ event => {
+ const doc = view.document;
+ if (!guards.has(doc) || isExempt(event)) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ disarmClickGuard(doc);
+ },
+ {cancels: true},
+ );
+}
+
+/** Swallow the browser's next click on `doc` (see the file header). */
+export function armClickGuard(
+ doc: Document,
+ {staysInstalled = false}: ClickGuardOptions = {},
+): void {
+ const view = doc.defaultView;
+ if (view == null) {
+ return;
+ }
+ disarmClickGuard(doc);
+ const guard: Guard = {unsubscribers: [], timer: null};
+ if (staysInstalled && !stayingClickListeners.has(view)) {
+ stayingClickListeners.set(view, listenForClicks(view));
+ }
+ if (!stayingClickListeners.has(view)) {
+ // The gesture host's arm: the click listener lasts while this guard does.
+ guard.unsubscribers.push(listenForClicks(view));
+ }
+ guards.set(doc, guard);
+ guard.unsubscribers.push(
+ // The next press is a new gesture: its click must never be eaten.
+ subscribeInput(view, 'pointerdown', () => disarmClickGuard(doc)),
+ );
+ guard.timer = setTimeout(() => disarmClickGuard(doc), CLICK_GUARD_WINDOW_MS);
+}
+
+/** Stop swallowing on `doc`; idempotent. */
+export function disarmClickGuard(doc: Document): void {
+ const guard = guards.get(doc);
+ if (guard == null) {
+ return;
+ }
+ guards.delete(doc);
+ if (guard.timer != null) {
+ clearTimeout(guard.timer);
+ }
+ for (const unsubscribe of guard.unsubscribers) {
+ unsubscribe();
+ }
+}
+
+/** Whether the guard on `doc` would swallow the next click. */
+export function isClickGuardArmed(doc: Document): boolean {
+ return guards.has(doc);
+}
+
+/**
+ * Run `dispatch`, letting through every click it dispatches: a click the
+ * caller reports itself after the gesture (a row's activation, a replayed or
+ * retargeted click).
+ */
+export function withoutClickGuard<T>(dispatch: () => T): T {
+ unguardedDepth++;
+ try {
+ return dispatch();
+ } finally {
+ unguardedDepth--;
+ }
+}
+
+/**
+ * Test-only: disarm every guard between cases, and drop the current window's
+ * staying click listener, as on a fresh page.
+ */
+export function __resetClickGuardForTest(): void {
+ for (const doc of [...guards.keys()]) {
+ disarmClickGuard(doc);
+ }
+ if (typeof window !== 'undefined') {
+ stayingClickListeners.get(window)?.();
+ stayingClickListeners.delete(window);
+ }
+}
+
+function isExempt(event: MouseEvent): boolean {
+ if (event.detail === 0 || unguardedDepth > 0) {
+ return true;
+ }
+ return isHapticSwitch(event.target);
+}
diff --git a/packages/core/src/utils/clickGuardTeardown.test.ts b/packages/core/src/utils/clickGuardTeardown.test.ts
new file mode 100644
index 0000000000..5aa1a197aa
--- /dev/null
+++ b/packages/core/src/utils/clickGuardTeardown.test.ts
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file clickGuardTeardown.test.ts
+ * @input Two tests in order, the first ending with the click guard armed
+ * @output No guard outlives the test that armed it: the shared test setup
+ * disarms every guard as each test ends, so its 400 ms timer never fires
+ * after the environment tears its window down
+ * @position Test-isolation check for utils/clickGuard.ts; it has no
+ * afterEach of its own on purpose
+ */
+
+import {describe, expect, it} from 'vitest';
+import {armClickGuard, isClickGuardArmed} from './clickGuard';
+
+describe('the click guard between tests', () => {
+ it('is armed by a gesture that ends a test', () => {
+ armClickGuard(document);
+ expect(isClickGuardArmed(document)).toBe(true);
+ });
+
+ it('is disarmed when the next test starts: no timer outlives the test that armed it', () => {
+ expect(isClickGuardArmed(document)).toBe(false);
+ });
+});
diff --git a/packages/core/src/utils/coarsePointer.test.ts b/packages/core/src/utils/coarsePointer.test.ts
new file mode 100644
index 0000000000..3b33f30f55
--- /dev/null
+++ b/packages/core/src/utils/coarsePointer.test.ts
@@ -0,0 +1,36 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file coarsePointer.test.ts
+ * @input coarsePointer.ts and the gestures' pointer test helper
+ * @output The gate reads and follows the primary pointer
+ * @position Unit tests of packages/core/src/utils/coarsePointer.ts
+ */
+
+import {describe, expect, it} from 'vitest';
+import {isCoarsePointer, watchCoarsePointer} from './coarsePointer';
+import {pointerQuery} from '../gestures/__tests__/pointerQuery';
+
+describe('coarsePointer', () => {
+ it('reads the primary pointer, and follows it until stopped', () => {
+ const pointer = pointerQuery(false);
+ try {
+ expect(isCoarsePointer(window)).toBe(false);
+ const seen: boolean[] = [];
+ const stop = watchCoarsePointer(window, isCoarse => seen.push(isCoarse));
+ pointer.set(true);
+ expect(isCoarsePointer(window)).toBe(true);
+ pointer.set(false);
+ stop();
+ pointer.set(true);
+ expect(seen).toEqual([true, false]);
+ } finally {
+ pointer.restore();
+ }
+ });
+
+ it('answers fine without a window', () => {
+ expect(isCoarsePointer(null)).toBe(false);
+ expect(watchCoarsePointer(null, () => {})).toBeTypeOf('function');
+ });
+});
diff --git a/packages/core/src/utils/coarsePointer.ts b/packages/core/src/utils/coarsePointer.ts
new file mode 100644
index 0000000000..f279922c50
--- /dev/null
+++ b/packages/core/src/utils/coarsePointer.ts
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file coarsePointer.ts
+ * @input A window
+ * @output Exports isCoarsePointer and watchCoarsePointer: whether the
+ * primary pointer is coarse (TOUCH_QUERY), and when it changes
+ * @position The coarse-pointer gate of packages/core/src/gestures and of
+ * the press controller (pressFeedback.ts): touch-only work registers only
+ * while it holds
+ *
+ * Where the primary pointer is coarse, a phone's touch work stays
+ * registered: the gesture host's page listeners, the page hold and the
+ * finger scroll. Where it is fine, recognizers still attach for every
+ * pointer, and the host listens on the page only during a press
+ * (`spec:AST-094` FR19, FR24, FR43). The query is TOUCH_QUERY, from
+ * touchQueries.ts, which loads without React. The answer can change while
+ * the page is open (a tablet docking a mouse), so a holder watches it.
+ *
+ * SYNC: When modified, update coarsePointer.test.ts.
+ */
+
+import {TOUCH_QUERY} from './touchQueries';
+
+/** Whether the primary pointer of `view` is coarse now. */
+export function isCoarsePointer(view: Window | null | undefined): boolean {
+ return (
+ typeof view?.matchMedia === 'function' &&
+ view.matchMedia(TOUCH_QUERY).matches
+ );
+}
+
+/**
+ * Call `listener` with the new answer each time the primary pointer of
+ * `view` turns coarse or fine, until the returned function is called.
+ */
+export function watchCoarsePointer(
+ view: Window | null | undefined,
+ listener: (isCoarse: boolean) => void,
+): () => void {
+ if (typeof view?.matchMedia !== 'function') {
+ return () => {};
+ }
+ const query = view.matchMedia(TOUCH_QUERY);
+ const onChange = (): void => listener(query.matches);
+ if (typeof query.addEventListener === 'function') {
+ query.addEventListener('change', onChange);
+ return () => query.removeEventListener('change', onChange);
+ }
+ // Safari before 14 only has the older pair.
+ query.addListener(onChange);
+ return () => query.removeListener(onChange);
+}
diff --git a/packages/core/src/utils/flatTree.test.ts b/packages/core/src/utils/flatTree.test.ts
new file mode 100644
index 0000000000..7837af699d
--- /dev/null
+++ b/packages/core/src/utils/flatTree.test.ts
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, describe, expect, it} from 'vitest';
+import {containsAlongFlatTree} from './flatTree';
+
+afterEach(() => {
+ document.body.innerHTML = '';
+});
+
+describe('containsAlongFlatTree', () => {
+ it('holds for the node itself and for its descendants', () => {
+ document.body.innerHTML = '<div id="outer"><p id="inner">text</p></div>';
+ const outer = document.getElementById('outer')!;
+ const inner = document.getElementById('inner')!;
+ expect(containsAlongFlatTree(outer, outer)).toBe(true);
+ expect(containsAlongFlatTree(outer, inner)).toBe(true);
+ expect(containsAlongFlatTree(outer, inner.firstChild!)).toBe(true);
+ });
+
+ it('crosses an open shadow root to its host, which Node.contains does not', () => {
+ document.body.innerHTML =
+ '<section id="wrap"><div id="host"></div></section>';
+ const wrap = document.getElementById('wrap')!;
+ const host = document.getElementById('host')!;
+ const button = document.createElement('button');
+ host.attachShadow({mode: 'open'}).append(button);
+ expect(wrap.contains(button)).toBe(false);
+ expect(containsAlongFlatTree(wrap, button)).toBe(true);
+ expect(containsAlongFlatTree(host, button)).toBe(true);
+ });
+
+ it('does not hold for a sibling, an ancestor, or a detached node', () => {
+ document.body.innerHTML =
+ '<div id="a"><span id="child"></span></div><div id="b"></div>';
+ const a = document.getElementById('a')!;
+ const b = document.getElementById('b')!;
+ const child = document.getElementById('child')!;
+ expect(containsAlongFlatTree(b, child)).toBe(false);
+ expect(containsAlongFlatTree(child, a)).toBe(false);
+ expect(containsAlongFlatTree(a, document.createElement('i'))).toBe(false);
+ });
+});
diff --git a/packages/core/src/utils/flatTree.ts b/packages/core/src/utils/flatTree.ts
new file mode 100644
index 0000000000..f43ed609e9
--- /dev/null
+++ b/packages/core/src/utils/flatTree.ts
@@ -0,0 +1,40 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file flatTree.ts
+ * @input A DOM node
+ * @output Exports parentAcrossShadow, and containsAlongFlatTree, which walks it
+ * @position The flat-tree parent the browser scrolls and dispatches
+ * through, shared by the gesture host's native-scroll probe and the
+ * selection lock (which the press feedback controller uses without the
+ * gesture system)
+ */
+
+/** The node's parent, crossing out of shadow roots. */
+export function parentAcrossShadow(node: Node): Node | null {
+ // The flat tree the browser scrolls and dispatches through: a slotted node
+ // goes to its slot, a shadow root to its host.
+ const slot = (node as Partial<Slottable>).assignedSlot;
+ if (slot != null) {
+ return slot;
+ }
+ if (node.parentNode != null) {
+ return node.parentNode instanceof ShadowRoot
+ ? node.parentNode.host
+ : node.parentNode;
+ }
+ return null;
+}
+
+/**
+ * Whether `node` is `ancestor` or below it along the flat tree: across an open
+ * shadow root to its host, which `Node.contains` does not follow.
+ */
+export function containsAlongFlatTree(ancestor: Node, node: Node): boolean {
+ for (let at: Node | null = node; at != null; at = parentAcrossShadow(at)) {
+ if (at === ancestor) {
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/packages/core/src/utils/inputStream.test.ts b/packages/core/src/utils/inputStream.test.ts
new file mode 100644
index 0000000000..08201a7033
--- /dev/null
+++ b/packages/core/src/utils/inputStream.test.ts
@@ -0,0 +1,244 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file inputStream.test.ts
+ * @input Uses vitest and jsdom's window and document
+ * @output One native listener per event type however many subscribe, removed
+ * with the last; subscribers in order, each isolated from another's throw;
+ * passive unless a subscriber cancels, and passive again when it leaves;
+ * an app's capture-phase stop (stopPropagation on the document or on the
+ * window, stopImmediatePropagation on the document) starves no subscriber; events
+ * fired at the document reach the stream; a page of pressables registers
+ * no non-passive listener, and the gesture host none that holds a scroll;
+ * the press feedback controller imports nothing from gestures/
+ * @position Unit tests of packages/core/src/utils/inputStream.ts
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+import {getGestureHost} from '../gestures/GestureHost';
+import {subscribeInput} from './inputStream';
+import {installPressFeedback} from './pressFeedback';
+
+type Registration = {
+ type: string;
+ options: AddEventListenerOptions | boolean | undefined;
+};
+
+function spyRegistrations() {
+ const added: Registration[] = [];
+ const removed: Registration[] = [];
+ const originalAdd = window.addEventListener.bind(window);
+ const originalRemove = window.removeEventListener.bind(window);
+ vi.spyOn(window, 'addEventListener').mockImplementation((...args) => {
+ added.push({type: args[0], options: args[2]});
+ originalAdd(...args);
+ });
+ vi.spyOn(window, 'removeEventListener').mockImplementation((...args) => {
+ removed.push({type: args[0], options: args[2]});
+ originalRemove(...args);
+ });
+ return {added, removed};
+}
+
+const unsubscribers: (() => void)[] = [];
+
+afterEach(() => {
+ for (const unsubscribe of unsubscribers.splice(0)) {
+ unsubscribe();
+ }
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+});
+
+function subscribe(...args: Parameters<typeof subscribeInput>): () => void {
+ const unsubscribe = subscribeInput(...args);
+ unsubscribers.push(unsubscribe);
+ return unsubscribe;
+}
+
+function pointerDown(target: EventTarget): Event {
+ const event = new Event('pointerdown', {bubbles: true, cancelable: true});
+ target.dispatchEvent(event);
+ return event;
+}
+
+describe('inputStream', () => {
+ it('registers one capture listener per event type, however many subscribe, and removes it with the last', () => {
+ const {added, removed} = spyRegistrations();
+ const first = subscribe(window, 'pointerdown', () => {});
+ const second = subscribe(window, 'pointerdown', () => {});
+ subscribe(window, 'pointerup', () => {});
+ expect(added.map(r => r.type)).toEqual(['pointerdown', 'pointerup']);
+ expect(added[0].options).toEqual({capture: true, passive: true});
+ first();
+ expect(removed).toEqual([]);
+ second();
+ second(); // a second call does nothing
+ expect(removed.map(r => r.type)).toEqual(['pointerdown']);
+ });
+
+ it('delivers to every subscriber in subscription order, each isolated from another that throws', () => {
+ const reported = vi.fn();
+ vi.stubGlobal('reportError', reported);
+ const calls: string[] = [];
+ subscribe(window, 'pointerdown', () => calls.push('press feedback'));
+ subscribe(window, 'pointerdown', () => {
+ calls.push('throws');
+ throw new Error('a subscriber failed');
+ });
+ subscribe(window, 'pointerdown', () => calls.push('gesture host'));
+ pointerDown(document.body);
+ expect(calls).toEqual(['press feedback', 'throws', 'gesture host']);
+ expect(reported).toHaveBeenCalledTimes(1);
+ vi.unstubAllGlobals();
+ });
+
+ it('stays passive unless a subscriber cancels, and turns passive again when it leaves', () => {
+ const {added, removed} = spyRegistrations();
+ subscribe(window, 'touchmove', () => {});
+ const blocking = subscribe(window, 'touchmove', () => {}, {cancels: true});
+ expect(added.map(r => r.options)).toEqual([
+ {capture: true, passive: true},
+ {capture: true, passive: false},
+ ]);
+ blocking();
+ expect(removed).toHaveLength(2);
+ expect(added.at(-1)?.options).toEqual({capture: true, passive: true});
+ // A canceling subscriber's preventDefault takes effect.
+ subscribe(
+ window,
+ 'pointerdown',
+ event => {
+ event.preventDefault();
+ },
+ {cancels: true},
+ );
+ expect(pointerDown(document.body).defaultPrevented).toBe(true);
+ });
+
+ it.each([
+ ['stopPropagation on the document', document, 'stopPropagation'],
+ [
+ 'stopImmediatePropagation on the document',
+ document,
+ 'stopImmediatePropagation',
+ ],
+ [
+ 'stopPropagation on the window, registered first',
+ window,
+ 'stopPropagation',
+ ],
+ ] as const)(
+ "still reaches every subscriber under an app's capture-phase %s",
+ (_name, node, stop) => {
+ const button = document.createElement('button');
+ document.body.append(button);
+ const listener = (event: Event) => event[stop]();
+ // Registered before any subscriber, as an app shell's listener is.
+ node.addEventListener('pointerdown', listener, {capture: true});
+ const pressFeedback = vi.fn();
+ const gestureHost = vi.fn();
+ subscribe(window, 'pointerdown', pressFeedback);
+ subscribe(window, 'pointerdown', gestureHost);
+ pointerDown(button);
+ node.removeEventListener('pointerdown', listener, {capture: true});
+ expect(pressFeedback).toHaveBeenCalledTimes(1);
+ expect(gestureHost).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("reaches events fired at the document and an element's scroll", () => {
+ const visibility = vi.fn();
+ const scroll = vi.fn();
+ subscribe(window, 'visibilitychange', visibility);
+ subscribe(window, 'scroll', scroll);
+ document.dispatchEvent(new Event('visibilitychange', {bubbles: true}));
+ const scroller = document.createElement('div');
+ document.body.append(scroller);
+ scroller.dispatchEvent(new Event('scroll'));
+ expect(visibility).toHaveBeenCalledTimes(1);
+ expect(scroll).toHaveBeenCalledTimes(1);
+ expect(scroll.mock.calls[0][0].target).toBe(scroller);
+ });
+
+ it('delivers an event to the subscribers present when it arrived', () => {
+ const late = vi.fn();
+ let unsubscribeLate: (() => void) | null = null;
+ subscribe(window, 'pointerdown', () => {
+ unsubscribeLate?.();
+ });
+ unsubscribeLate = subscribe(window, 'pointerdown', late);
+ pointerDown(document.body);
+ expect(late).not.toHaveBeenCalled();
+ });
+
+ it('registers no non-passive listener for a page of pressables, and none that holds a scroll for the gesture host', () => {
+ const {added} = spyRegistrations();
+ const uninstall = installPressFeedback();
+ expect(added.length).toBeGreaterThan(0);
+ expect(
+ added.filter(
+ r => typeof r.options === 'object' && r.options.passive === false,
+ ),
+ ).toEqual([]);
+ uninstall();
+ added.length = 0;
+ const host = getGestureHost(document);
+ const box = document.createElement('div');
+ document.body.append(box);
+ const detach = host.attachConsumer(box, {
+ touchesBegan: () => {},
+ touchesMoved: () => {},
+ touchesEnded: () => {},
+ touchesCancelled: () => {},
+ } as never);
+ const blocking = added
+ .filter(r => typeof r.options === 'object' && r.options.passive === false)
+ .map(r => r.type);
+ expect(blocking).not.toContain('touchstart');
+ expect(blocking).not.toContain('touchmove');
+ expect(blocking).not.toContain('wheel');
+ detach();
+ });
+
+ it('keeps the press feedback controller free of the gesture system', () => {
+ const utils = path.resolve(__dirname);
+ const seen = new Set<string>();
+ const queue = [path.join(utils, 'pressFeedback.ts')];
+ const statement =
+ /^\s*(import|export)\s+(type\s+)?([^'";]*?\s+from\s+)?'([^']+)';/gms;
+ while (queue.length > 0) {
+ const file = queue.pop() as string;
+ if (seen.has(file)) {
+ continue;
+ }
+ seen.add(file);
+ for (const match of fs.readFileSync(file, 'utf8').matchAll(statement)) {
+ const [, , isTypeOnly, , specifier] = match;
+ if (isTypeOnly != null || !specifier.startsWith('.')) {
+ continue;
+ }
+ const base = path.resolve(path.dirname(file), specifier);
+ const resolved = [
+ `${base}.ts`,
+ `${base}.tsx`,
+ path.join(base, 'index.ts'),
+ ].find(candidate => fs.existsSync(candidate));
+ if (resolved == null) {
+ throw new Error(`cannot resolve ${specifier} from ${file}`);
+ }
+ queue.push(resolved);
+ }
+ }
+ const modules = [...seen].map(file =>
+ path.relative(path.resolve(utils, '..'), file),
+ );
+ expect(modules).toContain(path.join('utils', 'inputStream.ts'));
+ expect(
+ modules.filter(module => module.startsWith(`gestures${path.sep}`)),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/core/src/utils/inputStream.ts b/packages/core/src/utils/inputStream.ts
new file mode 100644
index 0000000000..beebb18543
--- /dev/null
+++ b/packages/core/src/utils/inputStream.ts
@@ -0,0 +1,168 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file inputStream.ts
+ * @input A window, and subscribers to its input events (the press feedback
+ * controller, the gesture host)
+ * @output Exports subscribeInput
+ * @position The one entry for document-wide input listeners in core: one
+ * native listener per event type on the window's capture phase, shared by
+ * every subscriber
+ *
+ * The window's capture phase runs before any document listener, so an app's
+ * window-capture `stopPropagation`, or a document-capture
+ * `stopImmediatePropagation` registered before core subscribed, no longer
+ * hides input from the press feedback or the gesture host, as UIKit's
+ * recognizers see touches before views do. A recognizer that claims a touch
+ * still needs the touch to reach its element: its blocking `touchmove` sits
+ * there, below such a stop. And the stream stays ahead of an app's own
+ * window-capture listener only until a type's listener is re-added: a
+ * passivity switch, or a subscription after the type's last subscriber left,
+ * appends it after every window-capture listener registered meanwhile, so an
+ * app listener added after core's first subscription runs before core from
+ * then on, and its `stopImmediatePropagation` hides the event from every
+ * subscriber. Events fired at the document (`visibilitychange`, the
+ * page's `scroll`) and every element's `scroll` reach the window's capture
+ * phase too. A non-bubbling event fired at an element (`blur`, `focus`)
+ * reaches it as well, so a subscriber that means the window's own event
+ * checks `event.target`.
+ *
+ * Subscribers run in subscription order, each isolated: one that throws is
+ * reported and the rest still run, as separate native listeners would.
+ *
+ * A type's native listener is passive, so a page that only paints presses
+ * blocks no scroll. It is registered non-passive only while a subscriber
+ * that cancels the event (`{cancels: true}`) is subscribed (the gesture
+ * host's `touchend` and `contextmenu` while a claiming participant is
+ * attached; the page hold's `touchmove` while it holds; the click guard's
+ * `click` while it is armed, and from the menu press model's first arm on),
+ * and passive again once that subscriber leaves. With no subscriber left,
+ * it is removed.
+ *
+ * SYNC: When modified, update inputStream.test.ts.
+ */
+
+type InputListener = (event: Event) => void;
+
+interface Subscriber {
+ readonly listener: InputListener;
+ readonly cancels: boolean;
+}
+
+interface Channel {
+ readonly subscribers: Subscriber[];
+ /** The registered native listener and whether it may cancel. */
+ native: {readonly listener: InputListener; readonly cancels: boolean} | null;
+}
+
+/** Options for {@link subscribeInput}. */
+export interface InputSubscriptionOptions {
+ /**
+ * The subscriber calls `preventDefault()` on this event type, so the
+ * native listener must not be passive while it is subscribed.
+ * @default false
+ */
+ readonly cancels?: boolean;
+}
+
+/** The events a window's capture phase sees: its own, and the document's. */
+export type InputEventMap = WindowEventMap & DocumentEventMap;
+
+const streams = new WeakMap<Window, Map<string, Channel>>();
+
+/**
+ * Listen to `type` on `view`'s capture phase through its shared native
+ * listener. Returns the unsubscribe; calling it again does nothing.
+ */
+export function subscribeInput<K extends keyof InputEventMap>(
+ view: Window,
+ type: K,
+ listener: (event: InputEventMap[K]) => void,
+ {cancels = false}: InputSubscriptionOptions = {},
+): () => void {
+ let channels = streams.get(view);
+ if (channels == null) {
+ channels = new Map();
+ streams.set(view, channels);
+ }
+ let channel = channels.get(type);
+ if (channel == null) {
+ channel = {subscribers: [], native: null};
+ channels.set(type, channel);
+ }
+ const subscriber: Subscriber = {
+ listener: listener as InputListener,
+ cancels,
+ };
+ channel.subscribers.push(subscriber);
+ register(view, type, channel);
+ let isSubscribed = true;
+ return () => {
+ if (!isSubscribed) {
+ return;
+ }
+ isSubscribed = false;
+ const current = streams.get(view)?.get(type);
+ if (current == null) {
+ return;
+ }
+ const index = current.subscribers.indexOf(subscriber);
+ if (index !== -1) {
+ current.subscribers.splice(index, 1);
+ }
+ register(view, type, current);
+ if (current.subscribers.length === 0) {
+ streams.get(view)?.delete(type);
+ }
+ };
+}
+
+/**
+ * Bring the channel's native listener in line with its subscribers: none
+ * without subscribers, non-passive while one of them cancels.
+ */
+function register(view: Window, type: string, channel: Channel): void {
+ const wanted =
+ channel.subscribers.length === 0
+ ? null
+ : channel.subscribers.some(subscriber => subscriber.cancels);
+ const native = channel.native;
+ if (native != null && native.cancels === wanted) {
+ return;
+ }
+ if (native != null) {
+ view.removeEventListener(type, native.listener, {capture: true});
+ channel.native = null;
+ }
+ if (wanted == null) {
+ return;
+ }
+ const listener: InputListener = event => dispatch(channel, event);
+ view.addEventListener(type, listener, {capture: true, passive: !wanted});
+ channel.native = {listener, cancels: wanted};
+}
+
+function dispatch(channel: Channel, event: Event): void {
+ // A subscriber may subscribe or unsubscribe while the event runs; the
+ // event goes to those subscribed when it arrived.
+ for (const subscriber of [...channel.subscribers]) {
+ if (!channel.subscribers.includes(subscriber)) {
+ continue;
+ }
+ try {
+ subscriber.listener(event);
+ } catch (error) {
+ report(error);
+ }
+ }
+}
+
+function report(error: unknown): void {
+ if (typeof globalThis.reportError === 'function') {
+ globalThis.reportError(error);
+ return;
+ }
+ queueMicrotask(() => {
+ throw error;
+ });
+}
diff --git a/packages/core/src/utils/pressFeedback.test.ts b/packages/core/src/utils/pressFeedback.test.ts
index 581d69649f..e34fca0be5 100644
--- a/packages/core/src/utils/pressFeedback.test.ts
+++ b/packages/core/src/utils/pressFeedback.test.ts
@@ -18,7 +18,6 @@ import {dirname, join} from 'node:path';
import {fileURLToPath} from 'node:url';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {
- durationToMs,
hasReleaseFade,
readsPressStrength,
declaresPressPaint,
@@ -41,6 +40,7 @@ import {
PRESS_SCROLL_BRAKE_MS,
PRESS_SLOP_PX,
} from './pressGesture';
+import {pointerQuery} from '../gestures/__tests__/pointerQuery';
let release: () => void = () => undefined;
let scroller: HTMLElement;
@@ -73,6 +73,27 @@ function pressable(tag = 'div'): HTMLElement {
return element;
}
+/**
+ * The primary pointer is coarse (a phone, a tablet) until the returned
+ * restore runs: jsdom's matchMedia models a desktop, where touch work stays
+ * off (`spec:AST-094` FR19).
+ */
+function coarsePrimaryPointer(): () => void {
+ const matchMedia = window.matchMedia;
+ window.matchMedia = (query: string) => ({
+ ...matchMedia(query),
+ matches: query.includes('(pointer: coarse)') || matchMedia(query).matches,
+ });
+ const restore = (): void => {
+ window.matchMedia = matchMedia;
+ };
+ matchMediaRestorers.push(restore);
+ return restore;
+}
+
+/** Restores every pointer stub a test left, so none leaks into the next. */
+const matchMediaRestorers: (() => void)[] = [];
+
beforeEach(() => {
vi.useFakeTimers();
document.body.innerHTML = '';
@@ -93,9 +114,96 @@ beforeEach(() => {
afterEach(() => {
release();
vi.useRealTimers();
+ for (const restore of matchMediaRestorers.splice(0).reverse()) {
+ restore();
+ }
});
describe('the press reaches the surface the finger landed on', () => {
+ it('keeps native long-press selection on the row and its switch input while a finger is held: the hold does nothing (spec:AST-094 FR41)', () => {
+ coarsePrimaryPointer();
+ const row = pressable('label');
+ const input = document.createElement('input');
+ input.type = 'checkbox';
+ input.setAttribute('role', 'switch');
+ row.appendChild(input);
+ document.body.appendChild(row);
+ press(input, 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(600);
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ expect(input.style.getPropertyValue('user-select')).toBe('');
+ press(input, 'pointerup', 10, 10);
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ expect(input.style.getPropertyValue('user-select')).toBe('');
+ // A mouse never locks anything.
+ press(input, 'pointerdown', 10, 10, 'mouse');
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ press(input, 'pointerup', 10, 10, 'mouse');
+ });
+
+ it('writes no selection or callout lock on any surface: a link keeps its native menu and a row its long-press selection (spec:AST-094 FR41)', () => {
+ coarsePrimaryPointer();
+ // jsdom drops -webkit-touch-callout, so every 'none' write is recorded.
+ const written: string[] = [];
+ const setProperty = CSSStyleDeclaration.prototype.setProperty;
+ const spy = vi
+ .spyOn(CSSStyleDeclaration.prototype, 'setProperty')
+ .mockImplementation(function (
+ this: CSSStyleDeclaration,
+ name: string,
+ value: string | null,
+ priority?: string,
+ ) {
+ if (value === 'none') {
+ written.push(name);
+ }
+ setProperty.call(this, name, value, priority);
+ });
+ const link = pressable('a');
+ link.setAttribute('href', '/next');
+ link.textContent = 'Next';
+ document.body.appendChild(link);
+ for (const surface of [link, rows[0]]) {
+ press(surface, 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(600);
+ press(surface, 'pointerup', 10, 10);
+ }
+ expect(written).toEqual([]);
+ spy.mockRestore();
+ });
+
+ it('keeps selection under a mouse, a pen and a finger where the primary pointer is fine, as on main (spec:AST-094 FR19, spec:AST-017 FR59)', () => {
+ const row = rows[2];
+ press(row, 'pointerdown', 10, 10, 'mouse');
+ vi.advanceTimersByTime(600);
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ press(row, 'pointerup', 10, 10, 'mouse');
+ // A desktop pen tablet: a fine primary pointer.
+ press(row, 'pointerdown', 10, 10, 'pen');
+ vi.advanceTimersByTime(600);
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ press(row, 'pointerup', 10, 10, 'pen');
+ vi.advanceTimersByTime(600);
+ // A finger on a touchscreen laptop: the primary pointer is still fine.
+ press(row, 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(600);
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ press(row, 'pointerup', 10, 10);
+ vi.advanceTimersByTime(600);
+ // On a touch device a pen keeps it too: a row's hold does nothing
+ // (spec:AST-094 FR41).
+ const restore = coarsePrimaryPointer();
+ try {
+ press(row, 'pointerdown', 10, 10, 'pen');
+ vi.advanceTimersByTime(600);
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ press(row, 'pointerup', 10, 10, 'pen');
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ } finally {
+ restore();
+ }
+ });
+
it('paints the row after the delay, not before', () => {
const label = rows[1].firstElementChild;
if (label == null) {
@@ -890,6 +998,60 @@ describe('what the list pays for it', () => {
expect(added).toEqual([]);
});
+ it('registers no touch listener on the window or the document where the primary pointer is fine (spec:AST-094 FR24)', () => {
+ release();
+ matchMediaRestorers.push(pointerQuery(false).restore);
+ const added = [
+ vi.spyOn(window, 'addEventListener'),
+ vi.spyOn(document, 'addEventListener'),
+ ];
+ try {
+ release = installPressFeedback();
+ // A finger lands, as on a touchscreen laptop: still none.
+ press(rows[0], 'pointerdown', 10, 10);
+ press(rows[0], 'pointerup', 10, 10);
+ const types = added.flatMap(spy => spy.mock.calls.map(([type]) => type));
+ expect(types.filter(type => type.startsWith('touch'))).toEqual([]);
+ expect(types).toContain('pointerdown');
+ } finally {
+ for (const spy of added) {
+ spy.mockRestore();
+ }
+ }
+ });
+
+ it('asks no media query when it installs: a page no one touches never reads the pointer', () => {
+ release();
+ const matchMedia = vi.spyOn(window, 'matchMedia');
+ try {
+ release = installPressFeedback();
+ expect(matchMedia).not.toHaveBeenCalled();
+ } finally {
+ matchMedia.mockRestore();
+ }
+ });
+
+ it('hears touchcancel only while the primary pointer is coarse, and follows it', () => {
+ release();
+ const pointer = pointerQuery(false);
+ matchMediaRestorers.push(pointer.restore);
+ release = installPressFeedback();
+ // A tablet undocks its mouse: the browser's touchcancel ends a press.
+ pointer.set(true);
+ press(rows[0], 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(pressedRow()).toBe(0);
+ window.dispatchEvent(new Event('touchcancel'));
+ expect(pressedRow()).toBe(-1);
+ // It docks one again: the touch listener comes down.
+ pointer.set(false);
+ press(rows[1], 'pointerdown', 10, 100);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(pressedRow()).toBe(1);
+ window.dispatchEvent(new Event('touchcancel'));
+ expect(pressedRow()).toBe(1);
+ });
+
it('installs once, however many times it is called, and stays while any holder remains', () => {
const second = installPressFeedback();
press(rows[0], 'pointerdown', 10, 10);
diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.ts
index e88c89fe4e..fd17a01d6d 100644
--- a/packages/core/src/utils/pressFeedback.ts
+++ b/packages/core/src/utils/pressFeedback.ts
@@ -40,6 +40,13 @@
* release, the way a finger's press leaves. The query is the stylesheet's
* own, so the two cannot disagree about which presses are the controller's.
*
+ * A surface's hold does nothing, so it keeps the browser's long-press text
+ * selection (`spec:AST-094` FR41); only an element whose hold does something
+ * suppresses it, through the gesture host (utils/selectionLock.ts).
+ *
+ * Its one touch-only listener, `touchcancel`, is on only while the primary
+ * pointer is coarse (coarsePointer.ts, `spec:AST-094` FR24).
+ *
* SYNC: When modified, update pressGesture.ts, hooks/usePressFeedback.ts,
* hooks/usePressFeedback.doc.mjs, utils/interactionOverlay.stylex.ts and
* pressFeedback.test.ts.
@@ -55,6 +62,8 @@ import {
PRESS_SCROLL_BRAKE_MS,
pressGestureStep,
} from './pressGesture';
+import {isCoarsePointer, watchCoarsePointer} from './coarsePointer';
+import {subscribeInput} from './inputStream';
import {TOUCH_QUERY} from './touchPresentation';
/**
@@ -419,6 +428,7 @@ function onPointerDown(event: PointerEvent): void {
}
return;
}
+ armTouchCancel();
if (finger.live != null) {
const fingerIsUp =
finger.live.gesture.phase === 'fading' ||
@@ -640,38 +650,79 @@ function onVisibilityChange(): void {
}
}
-const PASSIVE_CAPTURE = {capture: true, passive: true} as const;
-const PASSIVE = {passive: true} as const;
+/** The input stream subscriptions while installed. */
+let unsubscribers: (() => void)[] = [];
+
+/** The touch-only `touchcancel` subscription, while the pointer is coarse. */
+let stopTouchCancel: (() => void) | null = null;
+let stopWatchingPointer: (() => void) | null = null;
+/**
+ * The one touch-only listener is on only while the primary pointer is coarse
+ * (`spec:AST-094` FR24); where it is fine, a finger's press still ends
+ * through `pointercancel`.
+ */
+function hearTouchCancel(on: boolean): void {
+ if (on === (stopTouchCancel != null)) {
+ return;
+ }
+ if (on) {
+ stopTouchCancel = subscribeInput(window, 'touchcancel', onCancel);
+ } else {
+ stopTouchCancel?.();
+ stopTouchCancel = null;
+ }
+}
+
+/**
+ * Read the primary pointer when the first finger or pen lands, and follow it
+ * from then on: installing asks nothing, so a page no one touches never
+ * queries it.
+ */
+function armTouchCancel(): void {
+ if (stopWatchingPointer != null) {
+ return;
+ }
+ stopWatchingPointer = watchCoarsePointer(window, hearTouchCancel);
+ hearTouchCancel(isCoarsePointer(window));
+}
+
+// The pointer, drag, scroll and visibility listeners are passive and on the
+// window's capture phase, through the shared input stream
+// (utils/inputStream.ts): a page of pressables blocks no scroll, and an app's
+// capture-phase stopPropagation at the document cannot starve the controller.
function addListeners(): void {
- window.addEventListener('pointerdown', onPointerDown, PASSIVE_CAPTURE);
- window.addEventListener('pointermove', onPointerMove, PASSIVE_CAPTURE);
- window.addEventListener('pointerup', onPointerUp, PASSIVE_CAPTURE);
- window.addEventListener('pointercancel', onCancel, PASSIVE_CAPTURE);
- window.addEventListener('touchcancel', onCancel, PASSIVE_CAPTURE);
- window.addEventListener('dragstart', onDragStart, PASSIVE_CAPTURE);
- // `scroll` does not bubble, so the capture phase is the only way one
- // listener hears every scroller in the document.
- document.addEventListener('scroll', onScroll, PASSIVE_CAPTURE);
- document.addEventListener('visibilitychange', onVisibilityChange);
- // Only Space's press needs the key's release and focus loss, so those two
- // are attached while it is held (holdKey).
+ unsubscribers = [
+ subscribeInput(window, 'pointerdown', onPointerDown),
+ subscribeInput(window, 'pointermove', onPointerMove),
+ subscribeInput(window, 'pointerup', onPointerUp),
+ subscribeInput(window, 'pointercancel', onCancel),
+ subscribeInput(window, 'dragstart', onDragStart),
+ // `scroll` does not bubble; the capture phase hears every scroller.
+ subscribeInput(window, 'scroll', onScroll),
+ subscribeInput(window, 'visibilitychange', onVisibilityChange),
+ ];
+ // The key path listens after the page's own handlers, at the window's
+ // bubble phase: a Space press the page cancels (`defaultPrevented`) paints
+ // nothing. Only Space's press needs the key's release and focus loss, so
+ // those two are attached while it is held (holdKey).
window.addEventListener('keydown', onKeyDown, PASSIVE);
}
function removeListeners(): void {
- window.removeEventListener('pointerdown', onPointerDown, PASSIVE_CAPTURE);
- window.removeEventListener('pointermove', onPointerMove, PASSIVE_CAPTURE);
- window.removeEventListener('pointerup', onPointerUp, PASSIVE_CAPTURE);
- window.removeEventListener('pointercancel', onCancel, PASSIVE_CAPTURE);
- window.removeEventListener('touchcancel', onCancel, PASSIVE_CAPTURE);
- window.removeEventListener('dragstart', onDragStart, PASSIVE_CAPTURE);
- document.removeEventListener('scroll', onScroll, PASSIVE_CAPTURE);
- document.removeEventListener('visibilitychange', onVisibilityChange);
+ for (const unsubscribe of unsubscribers.splice(0)) {
+ unsubscribe();
+ }
+ stopWatchingPointer?.();
+ stopWatchingPointer = null;
+ hearTouchCancel(false);
window.removeEventListener('keydown', onKeyDown);
holdKey(false);
}
+const PASSIVE_CAPTURE = {capture: true, passive: true} as const;
+const PASSIVE = {passive: true} as const;
+
/** Whether the key-release listeners are attached. */
let keyHeld = false;
diff --git a/packages/core/src/utils/pressFeedbackImports.test.ts b/packages/core/src/utils/pressFeedbackImports.test.ts
new file mode 100644
index 0000000000..2a4348cd57
--- /dev/null
+++ b/packages/core/src/utils/pressFeedbackImports.test.ts
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file pressFeedbackImports.test.ts
+ * @input The source of utils/pressFeedback.ts and every module it imports
+ * @output The press feedback controller's import graph reaches no module
+ * under gestures/: a page whose only touch work is press feedback carries
+ * none of the gesture system (`spec:AST-094` FR24, FR43: pointer queries
+ * live with the environment queries)
+ * @position Source boundary test of packages/core/src/utils/pressFeedback.ts
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+describe('the press feedback controller', () => {
+ it('imports nothing from the gesture system', () => {
+ const utils = path.resolve(__dirname);
+ const seen = new Set<string>();
+ const queue = [path.join(utils, 'pressFeedback.ts')];
+ const statement =
+ /^\s*(import|export)\s+(type\s+)?([^'";]*?\s+from\s+)?'([^']+)';/gms;
+ while (queue.length > 0) {
+ const file = queue.pop() as string;
+ if (seen.has(file)) {
+ continue;
+ }
+ seen.add(file);
+ for (const match of fs.readFileSync(file, 'utf8').matchAll(statement)) {
+ const [, , isTypeOnly, , specifier] = match;
+ if (isTypeOnly != null || !specifier.startsWith('.')) {
+ continue;
+ }
+ const base = path.resolve(path.dirname(file), specifier);
+ const resolved = [
+ `${base}.ts`,
+ `${base}.tsx`,
+ path.join(base, 'index.ts'),
+ ].find(candidate => fs.existsSync(candidate));
+ if (resolved == null) {
+ throw new Error(`cannot resolve ${specifier} from ${file}`);
+ }
+ queue.push(resolved);
+ }
+ }
+ const modules = [...seen].map(file =>
+ path.relative(path.resolve(utils, '..'), file),
+ );
+ expect(modules).toContain(path.join('utils', 'pressFeedback.ts'));
+ expect(
+ modules.filter(module => module.startsWith(`gestures${path.sep}`)),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/core/src/utils/selectionLock.test.ts b/packages/core/src/utils/selectionLock.test.ts
new file mode 100644
index 0000000000..75e5b72928
--- /dev/null
+++ b/packages/core/src/utils/selectionLock.test.ts
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file selectionLock.test.ts
+ * @input lockSelection on the elements a hold acts on, in jsdom, with and
+ * without iOS WebKit's touch callout
+ * @output A hold that acts starts no selection and no callout, a link's
+ * callout included (`spec:AST-094` FR41, DEC-9). Where iOS WebKit runs the
+ * lock is a style; elsewhere `selectstart` is cancelled and no style is
+ * written
+ * @position Unit tests for utils/selectionLock.ts
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {lockSelection, locksSelectionFor} from './selectionLock';
+
+/** Make `CSS.supports` answer as iOS WebKit does for its touch callout. */
+function asIosWebKit(): () => void {
+ const original = globalThis.CSS;
+ Object.defineProperty(globalThis, 'CSS', {
+ configurable: true,
+ value: {
+ ...original,
+ supports: (query: string) => query === '(-webkit-touch-callout: none)',
+ },
+ });
+ return () => {
+ Object.defineProperty(globalThis, 'CSS', {
+ configurable: true,
+ value: original,
+ });
+ };
+}
+
+function mount(html: string): (id: string) => HTMLElement {
+ document.body.innerHTML = html;
+ return id => document.getElementById(id) as HTMLElement;
+}
+
+/** Whether a selection starting on `target` was refused. */
+function refuses(target: Element): boolean {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ target.dispatchEvent(event);
+ return event.defaultPrevented;
+}
+
+afterEach(() => {
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+});
+
+describe('lockSelection where iOS WebKit runs', () => {
+ it("suppresses a link's touch callout when its hold acts, under the link too (spec:AST-094 FR41, DEC-9)", () => {
+ const restore = asIosWebKit();
+ try {
+ const get = mount(
+ '<a id="row" href="/next"><span id="label">Next</span></a>',
+ );
+ const set = vi.spyOn(get('row').style, 'setProperty');
+ const release = lockSelection([get('row')], get('label'));
+ expect(set).toHaveBeenCalledWith('-webkit-touch-callout', 'none');
+ expect(set).toHaveBeenCalledWith('user-select', 'none');
+ release();
+ } finally {
+ restore();
+ }
+ });
+});
+
+describe('lockSelection elsewhere', () => {
+ it('refuses a selection by cancelling selectstart, with no style write, until the release (spec:AST-094 FR41)', () => {
+ const get = mount(
+ '<div id="row"><span id="label">Row</span><input id="field" type="text"></div>',
+ );
+ const set = vi.spyOn(get('row').style, 'setProperty');
+ const release = lockSelection([get('row')], get('label'));
+ expect(set).not.toHaveBeenCalled();
+ expect(refuses(get('label'))).toBe(true);
+ // A text field keeps its selection: a held finger places its caret.
+ expect(refuses(get('field'))).toBe(false);
+ release();
+ expect(refuses(get('label'))).toBe(false);
+ });
+
+ it('keeps refusing while any holder holds', () => {
+ const get = mount('<div id="row"><span id="label">Row</span></div>');
+ const first = lockSelection([get('row')], get('label'));
+ const second = lockSelection([get('row')], get('label'));
+ first();
+ expect(refuses(get('label'))).toBe(true);
+ second();
+ expect(refuses(get('label'))).toBe(false);
+ });
+});
+
+describe('locksSelectionFor', () => {
+ it('locks for a finger and a pen under any primary pointer, a touchscreen laptop’s included, and never for a mouse (spec:AST-094 FR41)', () => {
+ const matchMedia = vi.spyOn(window, 'matchMedia');
+ expect(locksSelectionFor('touch')).toBe(true);
+ expect(locksSelectionFor('pen')).toBe(true);
+ expect(locksSelectionFor('mouse')).toBe(false);
+ // No pointer query decides it.
+ expect(matchMedia).not.toHaveBeenCalled();
+ matchMedia.mockRestore();
+ });
+});
diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.ts
new file mode 100644
index 0000000000..e2ee0b8776
--- /dev/null
+++ b/packages/core/src/utils/selectionLock.ts
@@ -0,0 +1,193 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file selectionLock.ts
+ * @input The elements a held touch contact presses, and the touch's target
+ * @output Exports lockSelection: no text selection and no touch callout
+ * start under the held finger until the returned release runs; and
+ * locksSelectionFor: which contacts take it
+ * @position Brought by the recognizers whose hold does something (a long
+ * press, and a recognizer created with `selectionLock: lockSelection`); the
+ * gesture host calls it and never imports it (`spec:AST-094` FR41)
+ *
+ * A hold that does something never starts a selection or the callout under
+ * the finger, a link's menu and preview included (`spec:AST-094` FR41,
+ * DEC-9). A text field keeps its selection: a held finger places its caret.
+ * How it is refused differs by engine, because a style change repaints
+ * everything it covers:
+ * - Where iOS WebKit runs (its touch callout query), only `user-select` refuses
+ * a long-press selection: WebKit fires no `selectstart` for one. It covers
+ * every held element, inline and refcounted: on the element under the
+ * finger alone, a long press selected a word beside it (iOS 26.2
+ * simulator). WebKit's own stylesheet makes every input selectable
+ * (`-webkit-user-select: text`), out of reach of an ancestor's lock, so a
+ * checkbox, a radio or a switch's input under the finger is locked too.
+ * - Elsewhere a long press fires `selectstart`, and cancelling it refuses
+ * the selection with no style write, so nothing repaints (Chromium on
+ * Android re-rastered a held surface at the touch-down and the lift when
+ * the style toggled).
+ *
+ * SYNC: When modified, update GestureHost.ts and utils/pressFeedback.ts; the
+ * iOS query matches utils/touchPresentation.ts.
+ */
+
+import {containsAlongFlatTree} from './flatTree';
+import {isIosWebKit} from './touchQueries';
+
+/** What a held finger must not start on a control or a cell. */
+const SELECTION_LOCK = [
+ '-webkit-touch-callout',
+ '-webkit-user-select',
+ 'user-select',
+] as const;
+
+/** Inputs whose text a held finger edits: it places the caret there. */
+const TEXT_ENTRY_TYPES = new Set([
+ 'text',
+ 'search',
+ 'email',
+ 'url',
+ 'tel',
+ 'password',
+ 'number',
+]);
+
+/**
+ * Whether a contact of this pointer kind takes the lock: a finger or a pen,
+ * under any primary pointer, a laptop's touchscreen and a desktop pen tablet
+ * included, since a pen's hold acts as a finger's (`spec:AST-094` FR41). A
+ * mouse never does: it keeps its released behavior (`spec:AST-017` FR59).
+ */
+export function locksSelectionFor(pointerType: string): boolean {
+ return pointerType !== 'mouse';
+}
+
+/** Locked elements, how many contacts hold each, and what to restore. */
+const locks = new WeakMap<
+ Element,
+ {
+ count: number;
+ saved: ReadonlyArray<{name: string; value: string; priority: string}>;
+ }
+>();
+
+/**
+ * Refuse a selection and the touch callout on `elements` (and on a non-text
+ * input target inside one of them) until the returned function runs, while
+ * any holder holds. Idempotent release.
+ */
+export function lockSelection(
+ elements: Iterable<Element>,
+ target: EventTarget | null,
+): () => void {
+ const set = new Set(elements);
+ if (
+ isSelectableControl(target) &&
+ [...set].some(element => containsAlongFlatTree(element, target))
+ ) {
+ set.add(target);
+ }
+ if (!isIosWebKit()) {
+ const refuse = (event: Event) => {
+ if (!isTextEntry(event.target)) {
+ event.preventDefault();
+ }
+ };
+ for (const element of set) {
+ element.addEventListener('selectstart', refuse);
+ }
+ let isRefusing = true;
+ return () => {
+ if (isRefusing) {
+ isRefusing = false;
+ for (const element of set) {
+ element.removeEventListener('selectstart', refuse);
+ }
+ }
+ };
+ }
+ const locked: Element[] = [];
+ for (const element of set) {
+ const style = styleOf(element);
+ if (style == null) {
+ continue;
+ }
+ locked.push(element);
+ const lock = locks.get(element);
+ if (lock != null) {
+ lock.count += 1;
+ continue;
+ }
+ locks.set(element, {
+ count: 1,
+ saved: SELECTION_LOCK.map(name => ({
+ name,
+ value: style.getPropertyValue(name),
+ priority: style.getPropertyPriority(name),
+ })),
+ });
+ for (const name of SELECTION_LOCK) {
+ style.setProperty(name, 'none');
+ }
+ }
+ let isReleased = false;
+ return () => {
+ if (isReleased) {
+ return;
+ }
+ isReleased = true;
+ for (const element of locked) {
+ const lock = locks.get(element);
+ if (lock == null || --lock.count > 0) {
+ continue;
+ }
+ locks.delete(element);
+ const style = styleOf(element);
+ for (const {name, value, priority} of lock.saved) {
+ if (value === '') {
+ style?.removeProperty(name);
+ } else {
+ style?.setProperty(name, value, priority);
+ }
+ }
+ }
+ };
+}
+
+/**
+ * A form control WebKit's own stylesheet makes selectable, which no
+ * ancestor's lock reaches: every input that is not a text field.
+ */
+function isSelectableControl(node: unknown): node is HTMLInputElement {
+ return (
+ node instanceof Element &&
+ node.localName === 'input' &&
+ !TEXT_ENTRY_TYPES.has((node as HTMLInputElement).type)
+ );
+}
+
+/** Text a held finger edits: it places the caret there. */
+function isTextEntry(node: EventTarget | null): boolean {
+ const element =
+ node instanceof Element
+ ? node
+ : node instanceof Node
+ ? node.parentElement
+ : null;
+ if (element == null) {
+ return false;
+ }
+ if (element.localName === 'textarea') {
+ return true;
+ }
+ if (element.localName === 'input') {
+ return TEXT_ENTRY_TYPES.has((element as HTMLInputElement).type);
+ }
+ return (element as HTMLElement).isContentEditable;
+}
+
+/** An element's inline style, when it has one (HTML and SVG elements). */
+function styleOf(element: Element): CSSStyleDeclaration | null {
+ const style = (element as Partial<ElementCSSInlineStyle>).style;
+ return style instanceof Object ? style : null;
+}
diff --git a/packages/core/src/utils/touchPresentation.ts b/packages/core/src/utils/touchPresentation.ts
index 5b889ba4d3..94a32ae7f5 100644
--- a/packages/core/src/utils/touchPresentation.ts
+++ b/packages/core/src/utils/touchPresentation.ts
@@ -68,7 +68,7 @@ import {
type CompactDefinition,
} from '../theme/themeAdaptations';
import {useThemeDefinition} from '../theme/useTheme';
-import {TOUCH_QUERY} from './touchQueries';
+import {IOS_SUPPORTS_QUERY, TOUCH_QUERY} from './touchQueries';
// The primary pointer is coarse: touch behaviours. Defined in touchQueries.ts,
// which loads without React or the theme.
@@ -86,12 +86,9 @@ export const COMPACT_QUERY = DEFAULT_COMPACT_DEFINITION.query;
export const COMPACT_TOUCH_QUERY =
DEFAULT_COMPACT_DEFINITION.coarsePointerQuery;
-/**
- * The engine is WebKit on iOS or iPadOS: the only one that implements
- * `-webkit-touch-callout`. For a style iOS WebKit requires, never a
- * behaviour.
- */
-export const IOS_SUPPORTS_QUERY = '(-webkit-touch-callout: none)';
+// The engine is WebKit on iOS or iPadOS, for a style iOS WebKit requires.
+// Defined in touchQueries.ts, which loads without React or the theme.
+export {IOS_SUPPORTS_QUERY};
/**
* The iOS gate as StyleX keys, nested in this order: the media query
diff --git a/packages/core/src/utils/touchQueries.test.ts b/packages/core/src/utils/touchQueries.test.ts
new file mode 100644
index 0000000000..db0c5c8ade
--- /dev/null
+++ b/packages/core/src/utils/touchQueries.test.ts
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {IOS_SUPPORTS_QUERY as STYLE_GATE_QUERY} from './touchPresentation';
+import {IOS_SUPPORTS_QUERY, isIosWebKit} from './touchQueries';
+
+/** A view whose `CSS.supports` answers like an engine that knows `known`. */
+function viewSupporting(known: string): {CSS: Pick<typeof CSS, 'supports'>} {
+ return {
+ CSS: {
+ supports: (condition: string) => condition === known,
+ },
+ };
+}
+
+describe('the iOS WebKit engine check', () => {
+ it('is the touch callout query, the one the iOS style gate spells', () => {
+ expect(IOS_SUPPORTS_QUERY).toBe('(-webkit-touch-callout: none)');
+ expect(STYLE_GATE_QUERY).toBe(IOS_SUPPORTS_QUERY);
+ });
+
+ it('reads iOS WebKit from a view that supports the touch callout', () => {
+ expect(isIosWebKit(viewSupporting(IOS_SUPPORTS_QUERY))).toBe(true);
+ });
+
+ it('reads any other engine as not iOS WebKit', () => {
+ expect(isIosWebKit(viewSupporting('(display: grid)'))).toBe(false);
+ });
+
+ it('reads a view without CSS.supports, or no view, as not iOS WebKit', () => {
+ expect(isIosWebKit({CSS: {}})).toBe(false);
+ expect(isIosWebKit({})).toBe(false);
+ expect(isIosWebKit(null)).toBe(false);
+ });
+});
diff --git a/packages/core/src/utils/touchQueries.ts b/packages/core/src/utils/touchQueries.ts
index f90777ff7d..5396821e6b 100644
--- a/packages/core/src/utils/touchQueries.ts
+++ b/packages/core/src/utils/touchQueries.ts
@@ -3,7 +3,8 @@
/**
* @file touchQueries.ts
* @input Nothing: plain strings
- * @output TOUCH_QUERY, the media query for a coarse primary pointer
+ * @output TOUCH_QUERY, the media query for a coarse primary pointer; and
+ * IOS_SUPPORTS_QUERY with isIosWebKit, the iOS WebKit engine check
* @position The dependency-free half of touchPresentation.ts, for code that
* must load without React or the theme: the motion foundation, which
* Node-side specs and browser proofs load without a StyleX compile.
@@ -13,3 +14,25 @@
/** The primary pointer is coarse: touch behaviours. */
export const TOUCH_QUERY = '(pointer: coarse)';
+
+/**
+ * The engine is WebKit on iOS or iPadOS: the only one that implements
+ * `-webkit-touch-callout`. For a style iOS WebKit requires, never a
+ * behaviour; isIosWebKit reads it for an engine workaround a record names.
+ */
+export const IOS_SUPPORTS_QUERY = '(-webkit-touch-callout: none)';
+
+/**
+ * Whether `view`'s engine is iOS WebKit, by IOS_SUPPORTS_QUERY. Only for an
+ * engine workaround a record names (`spec:AST-013` FR6): the selection
+ * lock's inline style, and the gesture host's presented hit testing. False
+ * where `CSS.supports` is missing (jsdom has `CSS.escape` only).
+ */
+export function isIosWebKit(
+ view:
+ | {CSS?: Partial<Pick<typeof CSS, 'supports'>>}
+ | null
+ | undefined = globalThis,
+): boolean {
+ return view?.CSS?.supports?.(IOS_SUPPORTS_QUERY) === true;
+}
diff --git a/playwright.interaction.config.ts b/playwright.interaction.config.ts
index f0c61e2e6e..77f3d8b05f 100644
--- a/playwright.interaction.config.ts
+++ b/playwright.interaction.config.ts
@@ -59,6 +59,8 @@ export default defineConfig({
testMatch: [
'internal/interaction-harness/src/**/*.interaction.browser.spec.ts',
'packages/*/src/**/*.interaction.browser.spec.ts',
+ // The gesture system's own proofs (esbuild fixtures, no Storybook).
+ 'packages/core/src/gestures/__tests__/browser/*.browser.spec.ts',
],
// Playwright wipes its output directory per run; evidence (storyboards,
// curve traces) goes to test-results/interaction-evidence instead.
diff --git a/scripts/gesture-free-entries.test.mjs b/scripts/gesture-free-entries.test.mjs
new file mode 100644
index 0000000000..d148dfda5d
--- /dev/null
+++ b/scripts/gesture-free-entries.test.mjs
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file gesture-free-entries.test.mjs
+ * @input Core's utils entry, bundled with the PR size report's esbuild
+ * options (.github/scripts/lib/component-size.js)
+ * @output Pins architecture:react-component-runtime INV13's bundle claim for
+ * the utils entry: it carries no byte of `gestures/` (the haptic switch's
+ * attribute's owner module, privateAttributes/hapticSwitch.stylex.ts, serves that)
+ * @position Node test over source, so it needs no build. The root and hooks
+ * entries carry gesture code exactly as far as the components and hooks
+ * that use a gesture import it: scripts/touch-support-bundle.test.mjs pins
+ * that per import, against its list of gesture users
+ */
+
+import fs from 'node:fs';
+import {createRequire} from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import {afterAll, describe, expect, it} from 'vitest';
+
+const REPO = path.resolve(import.meta.dirname, '..');
+const CORE_SRC = path.join(REPO, 'packages/core/src');
+const require = createRequire(path.join(REPO, 'package.json'));
+const esbuild = require('esbuild');
+
+const GESTURES = /^packages\/core\/src\/gestures\//;
+
+const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-gesture-free-'));
+afterAll(() => {
+ fs.rmSync(scratch, {recursive: true, force: true});
+});
+
+/** The `gestures/` modules that put bytes in a bundle of `entry`. */
+function gestureBytesIn(entry) {
+ const result = esbuild.buildSync({
+ absWorkingDir: REPO,
+ entryPoints: [entry],
+ outdir: path.join(scratch, 'out'),
+ bundle: true,
+ splitting: true,
+ minify: true,
+ format: 'esm',
+ platform: 'browser',
+ define: {'process.env.NODE_ENV': '"production"'},
+ loader: {'.css': 'empty'},
+ external: [
+ 'react',
+ 'react/*',
+ 'react-dom',
+ 'react-dom/*',
+ '@stylexjs/stylex',
+ ],
+ metafile: true,
+ write: false,
+ logLevel: 'silent',
+ });
+ return Object.values(result.metafile.outputs).flatMap(output =>
+ Object.entries(output.inputs)
+ .filter(
+ ([input, {bytesInOutput}]) => GESTURES.test(input) && bytesInOutput > 0,
+ )
+ .map(([input, {bytesInOutput}]) => `${input} (${bytesInOutput} B)`),
+ );
+}
+
+describe("Core's utils entry carries no gesture code", () => {
+ it('bundles no byte of gestures/', () => {
+ expect(gestureBytesIn(path.join(CORE_SRC, 'utils/index.ts'))).toEqual([]);
+ });
+});