An open source design system that's fully customizable and agent ready
TypeScript
feat(core): tap and long-press recognizers with UIKit's measured thresholds (#8059)
Christopher Chedeau19a7a463cce0
diff --git a/.changeset/gesture-tap-long-press.md b/.changeset/gesture-tap-long-press.mdnew file mode 100644index 0000000000..9ef786da65--- /dev/null+++ b/.changeset/gesture-tap-long-press.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: tap and long-press gesture recognizers with UIKit's measured thresholds. Not exported from the package entry point; no component uses them yet.++@vjeuxdiff --git a/packages/core/src/gestures/LongPressGestureRecognizer.ts b/packages/core/src/gestures/LongPressGestureRecognizer.tsnew file mode 100644index 0000000000..b552928573--- /dev/null+++ b/packages/core/src/gestures/LongPressGestureRecognizer.ts@@ -0,0 +1,186 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LongPressGestureRecognizer.ts+ * @input Touches from a GestureArena+ * @output Exports LongPressGestureRecognizer (UILongPressGestureRecognizer)+ * and its options+ * @position Continuous recognizer of packages/core/src/gestures+ *+ * Begins once `numberOfTouchesRequired` fingers have stayed down for+ * `minimumPressDuration` without any of them travelling further than+ * `allowableMovement` (after `numberOfTapsRequired` quick taps, when set).+ * After it begins, movement is unlimited and reports `changed`; lifting a+ * finger ends it. Lifting or travelling before the duration fails it. With a+ * duration of zero it begins on the touch itself, in the same event, as+ * UIKit's does: the selection tracker of an alert's, a menu's or an action+ * sheet's actions (highlight under the finger, act on the lift).+ *+ * The begin time is exact: the duration is a deadline on the event clock, so+ * a blocked main thread delays the callback, not the moment it reports.+ */++import {UIKIT_LONG_PRESS, UIKIT_TAP} from '../motion/uikit/gestures';+import {travel} from './geometry';+import {+ GestureRecognizer,+ isActive,+ MANIPULATION,+ type GestureRecognizerOptions,+ type NativeTouchBehavior,+} from './GestureRecognizer';+import type {GestureEventContext, GestureTouch} from './types';++export interface LongPressGestureRecognizerOptions extends GestureRecognizerOptions<LongPressGestureRecognizer> {+ minimumPressDuration?: number;+ allowableMovement?: number;+ /** Quick taps before the press. @default 0 */+ numberOfTapsRequired?: number;+ /** @default 1 */+ numberOfTouchesRequired?: number;+}++export class LongPressGestureRecognizer extends GestureRecognizer {+ minimumPressDuration: number;+ allowableMovement: number;+ numberOfTapsRequired: number;+ numberOfTouchesRequired: number;++ private tapsDone = 0;+ /** The taps phase's current tap: when it landed and its most fingers. */+ private tapStartedAt: number | null = null;+ private tapMostTouches = 0;+ private isPressTimerArmed = false;+ /** When the gesture began, on the event clock. */+ beganAt: number | null = null;++ constructor(options: LongPressGestureRecognizerOptions = {}) {+ super(options);+ this.minimumPressDuration =+ options.minimumPressDuration ??+ UIKIT_LONG_PRESS.minimumPressDuration.value;+ this.allowableMovement =+ options.allowableMovement ?? UIKIT_LONG_PRESS.allowableMovement.value;+ this.numberOfTapsRequired = options.numberOfTapsRequired ?? 0;+ this.numberOfTouchesRequired = options.numberOfTouchesRequired ?? 1;+ }++ override isInvolved(): boolean {+ return super.isInvolved() || this.tapsDone > 0;+ }++ override get nativeTouchBehavior(): NativeTouchBehavior {+ return MANIPULATION;+ }++ protected override acceptsTouch(touch: GestureTouch): boolean {+ // Extra fingers after the press began do not end or move it.+ if (isActive(this.state)) {+ return false;+ }+ return super.acceptsTouch(touch);+ }++ protected override touchesBegan(+ _touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (this.numberOfTouches > this.numberOfTouchesRequired) {+ this.setState('failed');+ return;+ }+ if (this.tapsDone > 0) {+ // The next tap (or the press) landed in time.+ this.clearTimer();+ }+ if (this.tapsDone < this.numberOfTapsRequired) {+ this.tapStartedAt ??= event.time;+ this.tapMostTouches = Math.max(this.tapMostTouches, this.numberOfTouches);+ }+ if (+ this.numberOfTouches === this.numberOfTouchesRequired &&+ this.tapsDone >= this.numberOfTapsRequired+ ) {+ if (this.minimumPressDuration <= 0) {+ // UIKit's zero-duration press begins on the touch itself, in the+ // same event (a selection tracker over a group of actions).+ this.beganAt = event.time;+ this.setState('began');+ return;+ }+ this.isPressTimerArmed = true;+ this.setTimer(event.time + this.minimumPressDuration, () => {+ this.isPressTimerArmed = false;+ if (+ this.state === 'possible' &&+ this.numberOfTouches === this.numberOfTouchesRequired+ ) {+ this.beganAt = this.now();+ this.setState('began');+ }+ });+ }+ }++ protected override touchesMoved(touches: ReadonlyArray<GestureTouch>): void {+ if (this.state === 'possible') {+ if (touches.some(touch => travel(touch) > this.allowableMovement)) {+ this.setState('failed');+ }+ return;+ }+ if (isActive(this.state)) {+ this.setState('changed');+ }+ }++ protected override touchesEnded(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (isActive(this.state)) {+ this.setState('ended');+ return;+ }+ if (this.isPressTimerArmed || this.tapsDone >= this.numberOfTapsRequired) {+ // Lifted before the duration: not a long press.+ this.setState('failed');+ return;+ }+ if (this.numberOfTouches - touches.length > 0) {+ return;+ }+ // A completed tap of the taps phase: quick, and with the press's finger+ // count, as a tap recognizer's would be. GUESS: its hold limit and+ // interval are the tap recognizer's (UIKit's measured+ // `maximumTapDuration` and `maximumIntervalBetweenTaps`), until+ // measurement M-G20 (motion/MEASUREMENTS.md) reads+ // UILongPressGestureRecognizer's own.+ const heldFor = event.time - (this.tapStartedAt ?? event.time);+ const fingers = this.tapMostTouches;+ this.tapStartedAt = null;+ this.tapMostTouches = 0;+ if (+ heldFor > UIKIT_TAP.maximumTapDuration.value ||+ fingers !== this.numberOfTouchesRequired+ ) {+ this.setState('failed');+ return;+ }+ this.tapsDone += 1;+ this.setTimer(+ event.time + UIKIT_TAP.maximumIntervalBetweenTaps.value,+ () => {+ this.setState('failed');+ },+ );+ }++ protected override reset(): void {+ this.tapsDone = 0;+ this.tapStartedAt = null;+ this.tapMostTouches = 0;+ this.isPressTimerArmed = false;+ this.beganAt = null;+ }+}diff --git a/packages/core/src/gestures/TapGestureRecognizer.ts b/packages/core/src/gestures/TapGestureRecognizer.tsnew file mode 100644index 0000000000..1d27e57912--- /dev/null+++ b/packages/core/src/gestures/TapGestureRecognizer.ts@@ -0,0 +1,192 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TapGestureRecognizer.ts+ * @input Touches from a GestureArena+ * @output Exports TapGestureRecognizer (UITapGestureRecognizer) and its options+ * @position Discrete recognizer of packages/core/src/gestures+ *+ * Recognizes when `numberOfTapsRequired` taps of `numberOfTouchesRequired`+ * fingers each have lifted. A tap fails when a finger travels further than+ * `allowableMovement`, when more fingers land than required, when the next+ * tap does not land within `maximumIntervalBetweenTaps` of the previous lift+ * or lands further than `allowableSeparation` from the first, or when a+ * finger stays down longer than `maximumTapDuration`. With several fingers a+ * tap is placed at their centroid: the first tap where its fingers lifted,+ * the next where its fingers landed, once all of them have.+ *+ * Between taps the recognizer stays `possible` with no touches, so a single+ * tap that requires a double tap to fail waits the interval out, as in UIKit.+ */++import {UIKIT_TAP} from '../motion/uikit/gestures';+import {distance, travel} from './geometry';+import {+ GestureRecognizer,+ MANIPULATION,+ type GestureRecognizerOptions,+ type NativeTouchBehavior,+} from './GestureRecognizer';+import type {GestureEventContext, GestureTouch, Point} from './types';++export interface TapGestureRecognizerOptions extends GestureRecognizerOptions<TapGestureRecognizer> {+ /** @default 1 */+ numberOfTapsRequired?: number;+ /** @default 1 */+ numberOfTouchesRequired?: number;+ allowableMovement?: number;+ maximumIntervalBetweenTaps?: number;+ allowableSeparation?: number;+ maximumTapDuration?: number;+}++const TAP = UIKIT_TAP;++export class TapGestureRecognizer extends GestureRecognizer {+ numberOfTapsRequired: number;+ numberOfTouchesRequired: number;+ allowableMovement: number;+ maximumIntervalBetweenTaps: number;+ allowableSeparation: number;+ maximumTapDuration: number;++ private tapCount = 0;+ private isTapInProgress = false;+ private maxTouchesThisTap = 0;+ /** Where the first tap's fingers lifted: their centroid. */+ private firstTapLocation: Point | null = null;+ /** The current tap's fingers: where each landed and where each lifted. */+ private tapStarts = new Map<number, Point>();+ private tapLifts = new Map<number, Point>();++ constructor(options: TapGestureRecognizerOptions = {}) {+ super(options);+ this.numberOfTapsRequired = options.numberOfTapsRequired ?? 1;+ this.numberOfTouchesRequired = options.numberOfTouchesRequired ?? 1;+ this.allowableMovement =+ options.allowableMovement ?? TAP.allowableMovement.value;+ this.maximumIntervalBetweenTaps =+ options.maximumIntervalBetweenTaps ??+ TAP.maximumIntervalBetweenTaps.value;+ this.allowableSeparation =+ options.allowableSeparation ?? TAP.allowableSeparation.value;+ this.maximumTapDuration =+ options.maximumTapDuration ?? TAP.maximumTapDuration.value;+ }++ override get isDiscrete(): boolean {+ return true;+ }++ override get nativeTouchBehavior(): NativeTouchBehavior {+ return MANIPULATION;+ }++ /** Taps completed so far in the current sequence. */+ get completedTaps(): number {+ return this.tapCount;+ }++ override isInvolved(): boolean {+ return super.isInvolved() || this.tapCount > 0;+ }++ protected override touchesBegan(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (!this.isTapInProgress) {+ this.isTapInProgress = true;+ this.tapStarts.clear();+ this.tapLifts.clear();+ this.maxTouchesThisTap = 0;+ this.clearTimer();+ if (Number.isFinite(this.maximumTapDuration)) {+ this.setTimer(event.time + this.maximumTapDuration, () => {+ this.setState('failed');+ });+ }+ }+ for (const touch of touches) {+ this.tapStarts.set(touch.id, {x: touch.startX, y: touch.startY});+ }+ this.maxTouchesThisTap = Math.max(+ this.maxTouchesThisTap,+ this.numberOfTouches,+ );+ if (this.numberOfTouches > this.numberOfTouchesRequired) {+ this.setState('failed');+ return;+ }+ // A later tap must land near the first: compared once all of its+ // fingers have landed, centroid to centroid.+ if (+ this.firstTapLocation != null &&+ this.tapStarts.size === this.numberOfTouchesRequired &&+ distance(centerOf(this.tapStarts.values()), this.firstTapLocation) >+ this.allowableSeparation+ ) {+ this.setState('failed');+ }+ }++ protected override touchesMoved(touches: ReadonlyArray<GestureTouch>): void {+ if (touches.some(touch => travel(touch) > this.allowableMovement)) {+ this.setState('failed');+ }+ }++ protected override touchesEnded(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (touches.some(touch => travel(touch) > this.allowableMovement)) {+ this.setState('failed');+ return;+ }+ for (const touch of touches) {+ this.tapLifts.set(touch.id, {x: touch.x, y: touch.y});+ }+ if (this.numberOfTouches - touches.length > 0) {+ // Wait for every finger of this tap to lift.+ return;+ }+ this.isTapInProgress = false;+ this.clearTimer();+ if (this.maxTouchesThisTap !== this.numberOfTouchesRequired) {+ this.setState('failed');+ return;+ }+ this.tapCount += 1;+ this.firstTapLocation ??= centerOf(this.tapLifts.values());+ if (this.tapCount >= this.numberOfTapsRequired) {+ this.setState('ended');+ return;+ }+ this.setTimer(event.time + this.maximumIntervalBetweenTaps, () => {+ this.setState('failed');+ });+ }++ protected override reset(): void {+ this.tapCount = 0;+ this.isTapInProgress = false;+ this.maxTouchesThisTap = 0;+ this.firstTapLocation = null;+ this.tapStarts.clear();+ this.tapLifts.clear();+ }+}++/** The centroid of some points. */+function centerOf(points: Iterable<Point>): Point {+ let x = 0;+ let y = 0;+ let count = 0;+ for (const point of points) {+ x += point.x;+ y += point.y;+ count += 1;+ }+ return count === 0 ? {x: 0, y: 0} : {x: x / count, y: y / count};+}diff --git a/packages/core/src/gestures/__tests__/LongPressGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/LongPressGestureRecognizer.test.tsnew file mode 100644index 0000000000..d1c83b9466--- /dev/null+++ b/packages/core/src/gestures/__tests__/LongPressGestureRecognizer.test.ts@@ -0,0 +1,141 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LongPressGestureRecognizer.test.ts+ * @input Synthetic touches with explicit timestamps through a GestureArena+ * @output LongPressGestureRecognizer's state machine: the press duration on the event clock, the movement tolerance as a distance, a lift before the duration, taps before the press, and a zero duration beginning on the touch+ * @position Unit tests of packages/core/src/gestures/LongPressGestureRecognizer.ts+ */++import {describe, expect, it} from 'vitest';+import {UIKIT_GESTURES} from '../../motion/uikit/gestures';+import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';+import {createHarness} from './harness';++describe('LongPressGestureRecognizer', () => {+ it('begins at exactly touch-down + 500 ms even when the next input is late', () => {+ const h = createHarness();+ const press = new LongPressGestureRecognizer({name: 'press'});+ h.finger(1).down(50, 50, 1000, {recognizers: [press]});+ // The main thread was blocked: the next thing processed is a move at+ // t = 1900. The press began at 1500, before that move.+ h.finger(1).move(80, 50, 1900);+ expect(press.beganAt).toBe(1500);+ expect(h.log).toEqual(['press:began@1500', 'press:changed@1900']);+ h.finger(1).up(2000);+ expect(h.log.slice(2)).toEqual(['press:ended@2000', 'press:possible@2000']);+ });++ it('uses UIKit defaults and allows unlimited movement after it began', () => {+ const press = new LongPressGestureRecognizer();+ expect(press.minimumPressDuration).toBe(500);+ expect(press.allowableMovement).toBe(10);+ const h = createHarness();+ h.finger(1).down(0, 0, 0, {recognizers: [press]});+ h.advance(500);+ expect(press.state).toBe('began');+ h.finger(1).move(300, 300, 600);+ expect(press.state).toBe('changed');+ expect(press.location()).toEqual({x: 300, y: 300});+ });++ it('measures the movement tolerance as a distance, not per axis', () => {+ const inside = createHarness();+ const a = new LongPressGestureRecognizer({name: 'a'});+ inside+ .finger(1)+ .down(0, 0, 0, {recognizers: [a]})+ .move(7, 7, 100);+ expect(a.state).toBe('possible');+ const outside = createHarness();+ const b = new LongPressGestureRecognizer({name: 'b'});+ outside+ .finger(1)+ .down(0, 0, 0, {recognizers: [b]})+ .move(7.2, 7.2, 100);+ expect(b.state).toBe('failed');+ });++ it('fails on a lift before the duration', () => {+ const h = createHarness();+ const press = new LongPressGestureRecognizer({name: 'press'});+ h.finger(1).down(0, 0, 0, {recognizers: [press]});+ h.finger(1).up(499);+ expect(h.log).toEqual(['press:failed@499', 'press:possible@499']);+ h.advance(600);+ expect(h.log).toHaveLength(2);+ });++ it('begins on the touch itself with a zero duration, and claims it', () => {+ const h = createHarness();+ const press = new LongPressGestureRecognizer({+ name: 'press',+ minimumPressDuration: 0,+ allowableMovement: Number.POSITIVE_INFINITY,+ });+ // Synchronously, in the touch-down delivery: no timer to wait for.+ h.finger(1).down(10, 10, 40, {recognizers: [press]});+ expect(press.state).toBe('began');+ expect(press.beganAt).toBe(40);+ expect(h.log).toEqual(['press:began@40']);+ expect(h.claims).toEqual([1]);+ // The finger slides across the group: changed, then ended at the lift.+ h.finger(1).move(10, 120, 80);+ expect(press.location()).toEqual({x: 10, y: 120});+ h.finger(1).up(120);+ expect(h.log.slice(1)).toEqual([+ 'press:changed@80',+ 'press:ended@120',+ 'press:possible@120',+ ]);+ });++ it('supports a tap before the press (numberOfTapsRequired)', () => {+ const h = createHarness();+ const press = new LongPressGestureRecognizer({+ name: 'press',+ numberOfTapsRequired: 1,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [press]});+ h.finger(1).up(80);+ h.finger(2).down(2, 0, 200, {recognizers: [press]});+ h.advance(700);+ expect(press.state).toBe('began');+ });++ it('counts only quick taps with the required fingers in the taps phase', () => {+ const tapLimit = UIKIT_GESTURES.tap.maximumTapDuration.value;+ // A first touch held past a tap's limit is no tap.+ const held = createHarness();+ const slow = new LongPressGestureRecognizer({+ name: 'slow',+ numberOfTapsRequired: 1,+ });+ held.finger(1).down(0, 0, 0, {recognizers: [slow]});+ held.finger(1).up(tapLimit + 100);+ expect(held.log).toContain(`slow:failed@${tapLimit + 100}`);+ // With two fingers required, a one-finger tap is no tap.+ const fingers = createHarness();+ const two = new LongPressGestureRecognizer({+ name: 'two',+ numberOfTapsRequired: 1,+ numberOfTouchesRequired: 2,+ });+ fingers.finger(1).down(0, 0, 0, {recognizers: [two]});+ fingers.finger(1).up(80);+ expect(fingers.log).toContain('two:failed@80');+ });++ it('keeps a begun press through a second finger, and ends it at the first finger’s lift (FR10)', () => {+ const h = createHarness();+ const press = new LongPressGestureRecognizer({name: 'press'});+ h.finger(1).down(0, 0, 0, {recognizers: [press]});+ h.advance(600);+ expect(press.state).toBe('began');+ h.finger(2).down(80, 0, 700, {recognizers: [press]});+ expect(press.state).toBe('began');+ expect(press.numberOfTouches).toBe(1);+ h.finger(1).up(800);+ expect(h.log).toContain('press:ended@800');+ });+});diff --git a/packages/core/src/gestures/__tests__/TapGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/TapGestureRecognizer.test.tsnew file mode 100644index 0000000000..3d1c8fffce--- /dev/null+++ b/packages/core/src/gestures/__tests__/TapGestureRecognizer.test.ts@@ -0,0 +1,154 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TapGestureRecognizer.test.ts+ * @input Synthetic touches with explicit timestamps through a GestureArena+ * @output TapGestureRecognizer's state machine: single and multiple taps with one or more fingers: recognition at the lift, the movement, interval, separation and hold limits+ * @position Unit tests of packages/core/src/gestures/TapGestureRecognizer.ts+ */++import {describe, expect, it} from 'vitest';+import {UIKIT_GESTURES} from '../../motion/uikit/gestures';+import {TapGestureRecognizer} from '../TapGestureRecognizer';+import {createHarness} from './harness';++describe('TapGestureRecognizer', () => {+ it('recognizes a single tap at the lift', () => {+ const h = createHarness();+ const tap = new TapGestureRecognizer({name: 'tap'});+ const actions: string[] = [];+ tap.addListener(r => actions.push(`${r.state}@${h.arena.now()}`));+ h.finger(1)+ .down(100, 100, 0, {recognizers: [tap]})+ .move(103, 101, 40);+ expect(tap.state).toBe('possible');+ h.finger(1).up(80, 103, 101);+ expect(actions).toEqual(['ended@80']);+ expect(h.log).toEqual(['tap:ended@80', 'tap:possible@80']);+ expect(tap.location()).toEqual({x: 103, y: 101});+ });++ it('fails once a finger travels past the allowable movement', () => {+ const h = createHarness();+ const tap = new TapGestureRecognizer({name: 'tap'});+ const allowed = UIKIT_GESTURES.tap.allowableMovement.value;+ h.finger(1)+ .down(0, 0, 0, {recognizers: [tap]})+ .move(allowed, 0, 16);+ expect(tap.state).toBe('possible');+ h.finger(1).move(allowed + 0.5, 0, 32);+ expect(tap.state).toBe('failed');+ h.finger(1).up(48);+ expect(h.log).toEqual(['tap:failed@32', 'tap:possible@48']);+ });++ it('fails when more fingers land than required, and taps with two', () => {+ const h = createHarness();+ const one = new TapGestureRecognizer({name: 'one'});+ const two = new TapGestureRecognizer({+ name: 'two',+ numberOfTouchesRequired: 2,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [one, two]});+ h.finger(2).down(40, 0, 20, {recognizers: [one, two]});+ expect(one.state).toBe('failed');+ h.finger(1).up(60);+ expect(two.state).toBe('possible');+ h.finger(2).up(70);+ expect(h.log).toEqual([+ 'one:failed@20',+ 'two:ended@70',+ 'one:possible@70',+ 'two:possible@70',+ ]);+ });++ it('recognizes a double tap inside the interval and fails outside it', () => {+ const interval = UIKIT_GESTURES.tap.maximumIntervalBetweenTaps.value;+ const h = createHarness();+ const double = new TapGestureRecognizer({+ name: 'double',+ numberOfTapsRequired: 2,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [double]});+ h.finger(1).up(60);+ expect(double.state).toBe('possible');+ expect(double.completedTaps).toBe(1);+ h.finger(2).down(4, 2, 60 + interval - 1, {recognizers: [double]});+ h.finger(2).up(60 + interval + 50);+ expect(h.log).toEqual([+ `double:ended@${60 + interval + 50}`,+ `double:possible@${60 + interval + 50}`,+ ]);++ const late = createHarness();+ const slow = new TapGestureRecognizer({+ name: 'slow',+ numberOfTapsRequired: 2,+ });+ late.finger(1).down(0, 0, 0, {recognizers: [slow]});+ late.finger(1).up(60);+ late.finger(2).down(0, 0, 60 + interval + 1, {recognizers: [slow]});+ // The interval timer fired at its own deadline, before the late touch.+ expect(late.log[0]).toBe(`slow:failed@${60 + interval}`);+ });++ it('fails a second tap that lands too far from the first', () => {+ const h = createHarness();+ const double = new TapGestureRecognizer({+ name: 'double',+ numberOfTapsRequired: 2,+ });+ const separation = UIKIT_GESTURES.tap.allowableSeparation.value;+ h.finger(1).down(0, 0, 0, {recognizers: [double]});+ h.finger(1).up(50);+ h.finger(2).down(separation + 1, 0, 100, {recognizers: [double]});+ expect(double.state).toBe('failed');+ });++ it('recognizes a two-finger double tap, placing each tap at its fingers’ centroid', () => {+ const separation = UIKIT_GESTURES.tap.allowableSeparation.value;+ const make = () => {+ const h = createHarness();+ const tap = new TapGestureRecognizer({+ name: 'two',+ numberOfTapsRequired: 2,+ numberOfTouchesRequired: 2,+ });+ // First tap: fingers 80 px apart, the right one lifting last.+ h.finger(1).down(0, 0, 0, {recognizers: [tap]});+ h.finger(2).down(80, 0, 10, {recognizers: [tap]});+ h.finger(1).up(50);+ h.finger(2).up(60);+ expect(tap.completedTaps).toBe(1);+ return {h, tap};+ };+ // The same two fingers again, a few px off: one double tap, though the+ // first finger lands 78 px from where the last one lifted.+ const near = make();+ near.h.finger(3).down(2, 1, 150, {recognizers: [near.tap]});+ near.h.finger(4).down(82, 1, 160, {recognizers: [near.tap]});+ near.h.finger(3).up(200);+ near.h.finger(4).up(210);+ expect(near.h.log).toEqual(['two:ended@210', 'two:possible@210']);+ // A second tap whose centroid lands too far from the first's fails.+ const far = make();+ far.h.finger(3).down(separation + 1, 0, 150, {recognizers: [far.tap]});+ expect(far.tap.state).toBe('possible');+ far.h.finger(4).down(separation + 81, 0, 160, {recognizers: [far.tap]});+ expect(far.tap.state).toBe('failed');+ });++ it('fails a hold past a finite maximum tap duration', () => {+ const h = createHarness();+ const tap = new TapGestureRecognizer({+ name: 'tap',+ maximumTapDuration: 400,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [tap]});+ h.advance(399);+ expect(tap.state).toBe('possible');+ h.advance(400);+ expect(tap.state).toBe('failed');+ });+});diff --git a/packages/core/src/gestures/__tests__/arenaTapLongPress.test.ts b/packages/core/src/gestures/__tests__/arenaTapLongPress.test.tsnew file mode 100644index 0000000000..91bd0b5403--- /dev/null+++ b/packages/core/src/gestures/__tests__/arenaTapLongPress.test.ts@@ -0,0 +1,211 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file arenaTapLongPress.test.ts+ * @input GestureArena with taps, long presses and consumers, driven by+ * synthetic touches with explicit timestamps+ * @output The arena with real discrete and press recognizers: tap vs double+ * tap with and without require-to-fail, delegate requirements, delivery and+ * deferred clicks, cancellation before and after a long press began+ * @position Unit tests of packages/core/src/gestures/GestureArena.ts; the+ * arena's own rules, with scripted recognizers, are in arena.test.ts+ */++import {describe, expect, it} from 'vitest';+import {LongPressGestureRecognizer} from '../LongPressGestureRecognizer';+import {TapGestureRecognizer} from '../TapGestureRecognizer';+import {UIKIT_GESTURES} from '../../motion/uikit/gestures';+import {createHarness, RecordingConsumer} from './harness';++const INTERVAL = UIKIT_GESTURES.tap.maximumIntervalBetweenTaps.value;++describe('conflict matrix', () => {+ it('tap vs double tap, single requires double to fail: the single waits out the interval', () => {+ 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);+ expect(single.state).toBe('possible');+ expect(single.pending).toBe('ended');+ h.advance(80 + INTERVAL);+ expect(h.log).toEqual([+ `double:failed@${80 + INTERVAL}`,+ `single:ended@${80 + INTERVAL}`,+ `single:possible@${80 + INTERVAL}`,+ `double:possible@${80 + INTERVAL}`,+ ]);+ });++ 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'});+ 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);+ h.finger(2).down(2, 2, 200, {recognizers: [single, double]});+ h.finger(2).up(260);+ expect(h.log).toEqual([+ 'double:ended@260',+ 'single:failed@260',+ 'single:possible@260',+ 'double:possible@260',+ ]);+ });++ it('tap vs double tap with no requirement: the single wins at once and fails the double', () => {+ const h = createHarness();+ const single = new TapGestureRecognizer({name: 'single'});+ const double = new TapGestureRecognizer({+ name: 'double',+ numberOfTapsRequired: 2,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [single, double]});+ h.finger(1).up(80);+ expect(h.log.slice(0, 2)).toEqual(['single:ended@80', 'double:failed@80']);+ });++ it('a recognizer that is not involved holds nothing up', () => {+ const h = createHarness();+ const idle = new TapGestureRecognizer({name: 'idle'});+ const tap = new TapGestureRecognizer({name: 'tap'});+ tap.requireToFail(idle);+ h.finger(1).down(0, 0, 0, {recognizers: [tap]});+ h.finger(1).up(50);+ expect(h.log[0]).toBe('tap:ended@50');+ });++ it('honors delegate failure requirements', () => {+ const h = createHarness();+ const double = new TapGestureRecognizer({+ name: 'double',+ numberOfTapsRequired: 2,+ });+ const single = new TapGestureRecognizer({+ name: 'single',+ shouldRequireFailureOf: (_self, other) => other === double,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [single, double]});+ h.finger(1).up(50);+ expect(single.pending).toBe('ended');+ });+});++describe('delivery to the view', () => {+ it('delivers an unclaimed touch to the consumer and allows its click', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const press = new LongPressGestureRecognizer({name: 'press'});+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [press], consumer});+ finger.move(3, 0, 16);+ expect(finger.up(60)).toBe('allow');+ expect(consumer.events).toEqual(['began:1', 'moved:1', 'ended:1']);+ });++ it('cancels the view and swallows the click when a recognizer takes the touch', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const press = new LongPressGestureRecognizer({name: 'press'});+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [press], consumer});+ h.advance(500);+ expect(consumer.events).toEqual(['began:1', 'cancelled:1']);+ expect(h.claims).toEqual([1]);+ expect(finger.up(600)).toBe('suppress');+ });++ it('keeps the view and the click with cancelsTouchesInView off', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const press = new LongPressGestureRecognizer({+ name: 'press',+ cancelsTouchesInView: false,+ });+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [press], consumer});+ h.advance(500);+ expect(finger.up(600)).toBe('allow');+ expect(consumer.events).toEqual(['began:1', 'ended:1']);+ });++ it('defers the click of a tap a double tap may still claim, then replays it', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const double = new TapGestureRecognizer({+ name: 'double',+ numberOfTapsRequired: 2,+ });+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [double], consumer});+ expect(finger.up(70)).toBe('defer');+ expect(consumer.events).toEqual(['began:1']);+ h.advance(70 + INTERVAL);+ expect(consumer.events).toEqual(['began:1', 'ended:1']);+ expect(h.deferredClicks).toEqual([+ {id: 1, allowed: true, time: 70 + INTERVAL},+ ]);+ });++ it('drops the deferred click when the double tap is recognized', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const double = new TapGestureRecognizer({+ name: 'double',+ numberOfTapsRequired: 2,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [double], consumer});+ h.finger(1).up(70);+ h.finger(2).down(1, 1, 150, {recognizers: [double], consumer});+ expect(h.finger(2).up(210)).toBe('suppress');+ expect(h.deferredClicks).toEqual([{id: 1, allowed: false, time: 210}]);+ expect(consumer.events).toEqual([+ 'began:1',+ 'began:2',+ 'cancelled:1',+ 'cancelled:2',+ ]);+ });++ it('cancels the view when the browser takes the touch', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const tap = new TapGestureRecognizer({name: 'tap'});+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [tap], consumer});+ finger.takenByBrowser(30);+ expect(consumer.events).toEqual(['began:1', 'cancelled:1']);+ expect(h.log).toEqual(['tap:failed@30', 'tap:possible@30']);+ });+});++describe('cancellation', () => {+ it('a system cancel cancels an active gesture and fails a possible one', () => {+ const h = createHarness();+ const press = new LongPressGestureRecognizer({name: 'press'});+ const tap = new TapGestureRecognizer({name: 'tap'});+ h.finger(1).down(0, 0, 0, {recognizers: [press]});+ h.advance(500);+ h.finger(2).down(100, 0, 600, {recognizers: [tap]});+ h.arena.cancelled([1, 2], 650);+ expect(h.log).toEqual([+ 'press:began@500',+ 'press:cancelled@650',+ 'tap:failed@650',+ 'press:possible@650',+ 'tap:possible@650',+ ]);+ });++ it('a long press cancelled before its duration never begins', () => {+ const h = createHarness();+ const press = new LongPressGestureRecognizer({name: 'press'});+ h.finger(1).down(0, 0, 0, {recognizers: [press]});+ h.finger(1).cancel(200);+ h.advance(1000);+ expect(h.log).toEqual(['press:failed@200', 'press:possible@200']);+ });+});diff --git a/packages/core/src/gestures/geometry.ts b/packages/core/src/gestures/geometry.tsnew file mode 100644index 0000000000..b4f81062ce--- /dev/null+++ b/packages/core/src/gestures/geometry.ts@@ -0,0 +1,55 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file geometry.ts+ * @input Touches+ * @output Exports the small geometry helpers recognizers share: centroid,+ * distance, span and angle of two touches, angle unwrapping+ * @position Pure helpers under packages/core/src/gestures+ */++import type {GestureTouch, Point} from './types';++export function centroid(+ touches: Iterable<GestureTouch>,+ excluding?: ReadonlySet<number>,+): Point {+ let x = 0;+ let y = 0;+ let count = 0;+ for (const touch of touches) {+ if (excluding?.has(touch.id)) {+ continue;+ }+ x += touch.x;+ y += touch.y;+ count += 1;+ }+ return count === 0 ? {x: 0, y: 0} : {x: x / count, y: y / count};+}++export function distance(a: Point, b: Point): number {+ return Math.hypot(a.x - b.x, a.y - b.y);+}++/** How far a touch is from where it landed. */+export function travel(touch: GestureTouch): number {+ return Math.hypot(touch.x - touch.startX, touch.y - touch.startY);+}++/** The angle of the vector from the first touch to the second, radians. */+export function angleBetween(a: Point, b: Point): number {+ return Math.atan2(b.y - a.y, b.x - a.x);+}++/** `angle` shifted by whole turns to be within half a turn of `reference`. */+export function unwrapAngle(angle: number, reference: number): number {+ let result = angle;+ while (result - reference > Math.PI) {+ result -= 2 * Math.PI;+ }+ while (result - reference < -Math.PI) {+ result += 2 * Math.PI;+ }+ return result;+}diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.mdindex 7fb90666fc..3030484136 100644--- a/packages/core/src/motion/MEASUREMENTS.md+++ b/packages/core/src/motion/MEASUREMENTS.md@@ -95,6 +95,7 @@ of a page scroll, so many of these can be read off Safari itself.| 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-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 |Done (UIKit lab, iOS 26.2 simulator, Oct 23 2026: the recognizers' ivars readin process, each confirmed with HID touches and the state log; values in