An open source design system that's fully customizable and agent ready
TypeScript
feat(core): gesture recognizer core — UIKit's state machine and the arena (#8058)
Christopher Chedeaud8ffb8f09051
diff --git a/.changeset/gesture-recognizer-core.md b/.changeset/gesture-recognizer-core.mdnew file mode 100644index 0000000000..0b0bfc3892--- /dev/null+++ b/.changeset/gesture-recognizer-core.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the gesture recognizer core for touch presentations: UIKit's recognizer state machine and the arena that settles which recognizer owns a touch. Not exported from the package entry point; no component uses it yet.++@vjeuxdiff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.tsnew file mode 100644index 0000000000..3acc3edc83--- /dev/null+++ b/packages/core/src/gestures/GestureArena.ts@@ -0,0 +1,966 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file GestureArena.ts+ * @input Touch input (began / moved / ended / cancelled / taken by the+ * browser), each new touch with the recognizers on its hit path and the+ * view-level consumer under it+ * @output Exports GestureArena (UIKit's gesture environment), its clock+ * abstraction and the click disposition type+ * @position Pure coordinator of packages/core/src/gestures: no DOM. The DOM+ * host (GestureHost.ts) feeds it real events and carries out what it+ * decides; tests feed it synthetic streams with explicit timestamps.+ *+ * WHAT IT DECIDES, the way UIKit decides it:+ *+ * - Participation. A new touch is offered to every recognizer on its hit+ * path, innermost first; each one that accepts it tracks it until it ends.+ * - Exclusivity. Two recognizers that share a touch are not active at once+ * unless both allow it (`shouldRecognizeSimultaneously`, FR15). The first+ * to recognize fails the other possible ones; a recognizer that tries to+ * begin while a conflicting one is active fails instead.+ * - Failure requirements. A recognizer that requires another to fail waits+ * (still `possible`) until that one fails, then recognizes; if that one+ * recognizes, it fails. An idle recognizer holds nothing up.+ * - Delivery to the view. The touch's consumer (a pressable control) gets+ * began / moved / ended unless a recognizer delays them+ * (`delaysTouchesBegan`, `delaysTouchesEnded`) or recognizing cancels them+ * (`cancelsTouchesInView`).+ * - The browser. A touch owned by a recognized gesture is CLAIMED: the host+ * cancels the browser's pan and zoom for it. A touch whose gesture+ * cancelled the view's touches has its click swallowed; a click held for a+ * recognizer that may still recognize is DEFERRED, then replayed or dropped.+ *+ * TIME. Every input carries its timestamp, and timers are deadlines on that+ * same clock. Before an input is processed, every timer due at or before its+ * timestamp runs first, at its own deadline. A long press therefore begins at+ * exactly touch-down + 500 ms even when the main thread was blocked and the+ * timer callback came late, and a test drives the whole machine with explicit+ * timestamps and no real time at all.+ *+ * SYNC: When modified, update GestureRecognizer.ts and+ * __tests__/arena.test.ts.+ */++import {+ isActive,+ isTerminal,+ type GestureRecognizer,+} from './GestureRecognizer';+import type {+ GestureEnvironment,+ GestureEventContext,+ GestureState,+ GestureTouch,+ TouchBeganInput,+ TouchConsumer,+ TouchInput,+ TouchSample,+} from './types';+import {DEFAULT_ENVIRONMENT} from './types';++export interface GestureClock {+ now(): number;+ setTimeout(callback: () => void, ms: number): unknown;+ clearTimeout(handle: unknown): void;+}++/** The browser's clock: `performance.now()`, the base of `event.timeStamp`. */+export const browserClock: GestureClock = {+ now: () =>+ typeof performance === 'undefined' ? Date.now() : performance.now(),+ setTimeout: (callback, ms) => setTimeout(callback, ms),+ clearTimeout: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),+};++/**+ * What the browser's click after a touch should do: pass, be swallowed, or+ * be swallowed now and replayed if the recognizers holding it all fail.+ */+export type ClickDisposition = 'allow' | 'suppress' | 'defer';++export interface ArenaBeganInput extends TouchBeganInput {+ /** The recognizers on the touch's hit path, innermost first. */+ readonly recognizers: ReadonlyArray<GestureRecognizer>;+ /** The innermost view-level consumer under the touch, if any. */+ readonly consumer?: TouchConsumer | null;+}++export interface GestureArenaOptions {+ clock?: GestureClock;+ environment?: GestureEnvironment;+ /** Touches a recognizer now owns: cancel the browser's default for them. */+ onClaim?: (touchIds: ReadonlyArray<number>) => void;+ /** A click deferred at touch end resolved: replay it, or drop it. */+ onDeferredClick?: (touch: GestureTouch, allowed: boolean) => void;+ /** Every recognizer transition, for debugging and tests. */+ onTransition?: (+ recognizer: GestureRecognizer,+ from: GestureState,+ to: GestureState,+ ) => void;+}++type ViewDelivery = 'none' | 'held' | 'delivered' | 'endHeld' | 'done';++interface TouchRecord {+ readonly touch: GestureTouch;+ readonly participants: GestureRecognizer[];+ readonly consumer: TouchConsumer | null;+ view: ViewDelivery;+ isLifted: boolean;+ isClaimed: boolean;+ suppressClick: boolean;+ deferredClick: boolean;+}++interface Timer {+ deadline: number;+ callback: () => void;+}++export class GestureArena {+ readonly environment: GestureEnvironment;+ private readonly clock: GestureClock;+ private readonly options: GestureArenaOptions;+ private readonly records = new Map<number, TouchRecord>();+ /** Recognizers involved in the current interaction, in resolution order. */+ private active: GestureRecognizer[] = [];+ private readonly timers = new Map<GestureRecognizer, Timer>();+ private realTimer: unknown = null;+ private realTimerDeadline = Number.POSITIVE_INFINITY;+ /** The time of the event or timer being processed; null between them. */+ private currentTime: number | null = null;+ /** The latest time processed: input never moves the clock backwards. */+ private latestTime = Number.NEGATIVE_INFINITY;+ private depth = 0;++ constructor(options: GestureArenaOptions = {}) {+ this.options = options;+ this.clock = options.clock ?? browserClock;+ this.environment = options.environment ?? DEFAULT_ENVIRONMENT;+ }++ // --- Queries ---------------------------------------------------------------++ /** The current time on the event clock. */+ now(): number {+ return this.currentTime ?? Math.max(this.latestTime, this.clock.now());+ }++ /** Whether a recognizer owns this touch, so the browser must not pan or zoom it. */+ isClaimed(id: number): boolean {+ return this.records.get(id)?.isClaimed === true;+ }++ /** The live touch with this id. */+ getTouch(id: number): GestureTouch | undefined {+ return this.records.get(id)?.touch;+ }++ /** Every touch the arena tracks, lifted ones awaiting a decision included. */+ get touches(): ReadonlyArray<GestureTouch> {+ return [...this.records.values()].map(record => record.touch);+ }++ /** Recognizers taking part in the current interaction, in resolution order. */+ get involvedRecognizers(): ReadonlyArray<GestureRecognizer> {+ return this.active;+ }++ // --- Input -----------------------------------------------------------------++ /** New contacts, each with the recognizers on its hit path. */+ began(inputs: ReadonlyArray<ArenaBeganInput>): void {+ if (inputs.length === 0) {+ return;+ }+ this.run(inputs[0].time, () => {+ const newTouches = new Map<GestureRecognizer, GestureTouch[]>();+ const created: TouchRecord[] = [];+ for (const input of inputs) {+ if (this.records.has(input.id)) {+ continue;+ }+ const time = this.clampTime(input.time);+ const sample: TouchSample = {x: input.x, y: input.y, time};+ const touch: GestureTouch = {+ id: input.id,+ pointerType: input.pointerType,+ phase: 'began',+ x: input.x,+ y: input.y,+ time,+ startX: input.x,+ startY: input.y,+ startTime: time,+ samples: [...(input.history ?? []), sample],+ target: input.target,+ scroll: input.scroll ?? null,+ takenByBrowser: false,+ };+ const participants: GestureRecognizer[] = [];+ for (const [depth, recognizer] of input.recognizers.entries()) {+ if (!recognizer.wantsTouch(touch)) {+ continue;+ }+ participants.push(recognizer);+ 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+ // on the same event the innermost wins (FR15), whichever finger+ // brought the outer one in first.+ const outer = this.active.findIndex(+ other => input.recognizers.indexOf(other) > depth,+ );+ if (outer === -1) {+ this.active.push(recognizer);+ } else {+ this.active.splice(outer, 0, recognizer);+ }+ }+ const list = newTouches.get(recognizer) ?? [];+ list.push(touch);+ newTouches.set(recognizer, list);+ }+ const record: TouchRecord = {+ touch,+ participants,+ consumer: input.consumer ?? null,+ view: 'none',+ isLifted: false,+ isClaimed: false,+ suppressClick: false,+ deferredClick: false,+ };+ this.records.set(input.id, record);+ created.push(record);+ }+ const context = this.context();+ for (const recognizer of [...this.active]) {+ const touches = newTouches.get(recognizer);+ if (touches != null) {+ recognizer.deliverBegan(touches, context);+ }+ }+ // A recognizer already tracking a gesture hears of a touch that began+ // off its hit path (a second finger elsewhere on the page), which it+ // would otherwise never see.+ for (const recognizer of [...this.active]) {+ const own = newTouches.get(recognizer);+ const elsewhere = created+ .map(record => record.touch)+ .filter(touch => own == null || !own.includes(touch));+ if (elsewhere.length > 0 && recognizer.numberOfTouches > 0) {+ recognizer.deliverBeganElsewhere(elsewhere, context);+ }+ }+ for (const record of created) {+ this.deliverViewBegan(record);+ }+ });+ }++ /** Contacts moved. */+ moved(inputs: ReadonlyArray<TouchInput>): void {+ if (inputs.length === 0) {+ return;+ }+ this.run(inputs[0].time, () => {+ const changed = this.update(inputs, 'moved');+ if (changed.length === 0) {+ return;+ }+ const context = this.context();+ for (const recognizer of [...this.active]) {+ recognizer.deliverMoved(changed, context);+ }+ for (const touch of changed) {+ const record = this.records.get(touch.id);+ if (record?.view === 'delivered') {+ record.consumer?.touchMoved(touch);+ }+ }+ });+ }++ /**+ * Contacts lifted. Returns, per touch, what the browser's click for it+ * should do.+ */+ ended(inputs: ReadonlyArray<TouchInput>): Map<number, ClickDisposition> {+ const dispositions = new Map<number, ClickDisposition>();+ if (inputs.length === 0) {+ return dispositions;+ }+ this.run(inputs[0].time, () => {+ const changed = this.update(inputs, 'ended');+ const context = this.context();+ for (const recognizer of [...this.active]) {+ 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+ // the final one, never a `defer` for a click already replayed (FR21).+ this.reviewPending();+ for (const touch of changed) {+ const record = this.records.get(touch.id);+ if (record == null) {+ continue;+ }+ record.isLifted = true;+ dispositions.set(touch.id, this.resolveEnd(record));+ }+ });+ return dispositions;+ }++ /** The system took these contacts (`touchcancel`, a mouse `pointercancel`). */+ cancelled(ids: ReadonlyArray<number>, time: number): void {+ this.run(time, () => {+ const touches = this.liveTouches(ids);+ for (const touch of touches) {+ touch.phase = 'cancelled';+ }+ const context = this.context();+ for (const recognizer of [...this.active]) {+ recognizer.deliverCancelled(touches, context);+ }+ for (const touch of touches) {+ const record = this.records.get(touch.id);+ if (record == null) {+ continue;+ }+ record.isLifted = true;+ record.suppressClick = true;+ this.cancelView(record);+ }+ });+ }++ /**+ * The browser took these contacts for its own pan or zoom: their pointer+ * stream is gone (`pointercancel`) and no click will follow. Possible+ * recognizers sharing them fail and active ones are cancelled, as UIKit+ * fails everything a scroll view's pan beats, except a recognizer that+ * keeps observing the touch. Such a watcher never claims it: a drag the+ * browser took stays the browser's (FR14).+ */+ browserTookOver(ids: ReadonlyArray<number>, time: number): void {+ this.run(time, () => {+ const touches = this.liveTouches(ids).filter(+ touch => !touch.takenByBrowser,+ );+ if (touches.length === 0) {+ return;+ }+ for (const touch of touches) {+ touch.takenByBrowser = true;+ }+ const context = this.context();+ for (const recognizer of [...this.active]) {+ recognizer.deliverTakenByBrowser(touches, context);+ }+ for (const touch of touches) {+ const record = this.records.get(touch.id);+ if (record == null) {+ continue;+ }+ record.suppressClick = true;+ this.cancelView(record);+ }+ });+ }++ /** Run every timer due at or before `time` (the host's timer and tests). */+ advanceTime(time: number): void {+ this.run(time, () => {});+ }++ // --- Recognizer requests (internal) ----------------------------------------++ /** @internal A recognizer asked for a state change. */+ requestTransition(recognizer: GestureRecognizer, next: GestureState): void {+ const from = recognizer.state;+ if (next === 'failed') {+ this.fail(recognizer);+ return;+ }+ if (recognizer.pending != null && (next === 'began' || next === 'ended')) {+ // Already waiting on a requirement; the recognition stands as asked.+ return;+ }+ if (from === 'possible' && (next === 'began' || next === 'ended')) {+ this.attemptRecognition(recognizer, next);+ return;+ }+ if (isActive(from) && (next === 'changed' || next === 'ended')) {+ this.apply(recognizer, next);+ return;+ }+ if (isActive(from) && next === 'cancelled') {+ this.apply(recognizer, 'cancelled');+ }+ }++ /** @internal Arm a recognizer's one timer at an absolute deadline. */+ setTimer(+ recognizer: GestureRecognizer,+ deadline: number,+ callback: () => void,+ ): void {+ this.timers.set(recognizer, {deadline, callback});+ this.scheduleRealTimer();+ }++ /** @internal */+ clearTimer(recognizer: GestureRecognizer): void {+ if (this.timers.delete(recognizer)) {+ this.scheduleRealTimer();+ }+ }++ /** Cancel an active recognizer, or fail a possible one. */+ 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 ??+ (Number.isFinite(this.latestTime) ? this.latestTime : this.clock.now());+ this.run(time, () => {+ if (isActive(recognizer.state)) {+ this.apply(recognizer, 'cancelled');+ } else if (recognizer.state === 'possible' && recognizer.isInvolved()) {+ // An idle recognizer stays `possible`: nothing would ever reset it.+ this.fail(recognizer);+ }+ });+ }++ // --- Resolution ------------------------------------------------------------++ private attemptRecognition(+ recognizer: GestureRecognizer,+ next: 'began' | 'ended',+ ): void {+ if (!recognizer.shouldBegin() || this.isVetoedByConsumer(recognizer)) {+ this.fail(recognizer);+ return;+ }+ let isWaiting = false;+ for (const other of this.active) {+ if (other === recognizer || !recognizer.requiresFailureOf(other)) {+ continue;+ }+ if (other.state === 'failed') {+ continue;+ }+ if (other.state !== 'possible') {+ // The requirement recognized (or is mid-gesture): this one cannot.+ this.fail(recognizer);+ return;+ }+ if (other.isInvolved()) {+ isWaiting = true;+ }+ }+ if (isWaiting) {+ recognizer.pending = next;+ this.claim(recognizer);+ return;+ }+ for (const other of this.active) {+ if (+ other !== recognizer &&+ // A discrete winner (`ended`) still holding its touches blocks too.+ (isActive(other.state) ||+ (other.state === 'ended' && other.trackedTouches.length > 0)) &&+ this.conflicts(other, recognizer)+ ) {+ this.fail(recognizer);+ return;+ }+ }+ this.apply(recognizer, next);+ // Recognizing beats every possible recognizer it conflicts with, and+ // everything that required it to fail.+ for (const other of [...this.active]) {+ if (other === recognizer || other.state !== 'possible') {+ continue;+ }+ if (+ other.requiresFailureOf(recognizer) ||+ this.conflicts(recognizer, other)+ ) {+ this.fail(other);+ }+ }+ this.claim(recognizer);+ if (recognizer.cancelsTouchesInView) {+ this.cancelViewTouchesOf(recognizer);+ }+ }++ /** Whether `winner` being recognized prevents `other`. */+ private conflicts(+ winner: GestureRecognizer,+ other: GestureRecognizer,+ ): boolean {+ if (!sharesTouches(winner, other) || winner.allowsSimultaneous(other)) {+ return false;+ }+ return winner.canPrevent(other) && other.canBePrevented(winner);+ }++ /** UIControl's rule: a control may veto an overlapping ancestor recognizer. */+ private isVetoedByConsumer(recognizer: GestureRecognizer): boolean {+ for (const id of recognizer.seenTouchIds) {+ const consumer = this.records.get(id)?.consumer;+ if (consumer?.allowsAncestorRecognizer?.(recognizer) === false) {+ return true;+ }+ }+ return false;+ }++ private fail(recognizer: GestureRecognizer): void {+ if (isTerminal(recognizer.state)) {+ return;+ }+ if (isActive(recognizer.state)) {+ this.apply(recognizer, 'cancelled');+ return;+ }+ recognizer.pending = null;+ this.apply(recognizer, 'failed');+ this.reviewPending();+ }++ /**+ * A recognition that claimed its touches and then fails or is cancelled (a+ * waiting recognition that fails, a gesture a second finger or the app+ * cancels) gives them back to the browser unless another recognition owns+ * them, so a finger still resting there can pinch-zoom the page.+ */+ private releaseClaim(recognizer: GestureRecognizer): void {+ for (const touch of recognizer.trackedTouches) {+ const record = this.records.get(touch.id);+ if (record == null || !record.isClaimed) {+ continue;+ }+ // A recognized discrete gesture (`ended`, a swipe) still owns its+ // touches until they lift.+ const isOwned = this.active.some(+ other =>+ other !== recognizer &&+ other.claimsTouches &&+ (isActive(other.state) ||+ other.state === 'ended' ||+ other.pending != null) &&+ other.trackedTouches.some(tracked => tracked.id === touch.id),+ );+ if (!isOwned) {+ record.isClaimed = false;+ }+ }+ }++ private apply(recognizer: GestureRecognizer, next: GestureState): void {+ const from = recognizer.state;+ recognizer.applyState(next);+ if (recognizer.state === next && from !== next) {+ this.options.onTransition?.(recognizer, from, next);+ } else if (next === 'changed' && from === 'changed') {+ this.options.onTransition?.(recognizer, from, next);+ }+ if (isTerminal(next)) {+ this.clearTimer(recognizer);+ }+ if (next === 'cancelled' || next === 'failed') {+ this.releaseClaim(recognizer);+ }+ }++ /**+ * Re-run every waiting recognition whose requirements may have resolved.+ * Repeats until nothing changes, so chains (A waits on B waits on C)+ * settle in one pass.+ */+ private reviewPending(): void {+ let changed = true;+ while (changed) {+ changed = false;+ for (const recognizer of [...this.active]) {+ const next = recognizer.pending;+ if (next == null || recognizer.state !== 'possible') {+ continue;+ }+ const blocked = this.active.some(+ other =>+ other !== recognizer &&+ recognizer.requiresFailureOf(other) &&+ other.state === 'possible' &&+ other.isInvolved(),+ );+ if (blocked) {+ continue;+ }+ recognizer.pending = null;+ this.attemptRecognition(recognizer, next);+ changed = true;+ }+ }+ }++ private claim(recognizer: GestureRecognizer): void {+ if (!recognizer.claimsTouches) {+ return;+ }+ const claimed: number[] = [];+ for (const touch of recognizer.trackedTouches) {+ const record = this.records.get(touch.id);+ if (+ record != null &&+ !record.isLifted &&+ !record.isClaimed &&+ !record.touch.takenByBrowser+ ) {+ // A touch the browser took stays the browser's (FR14).+ record.isClaimed = true;+ claimed.push(touch.id);+ }+ }+ if (claimed.length > 0) {+ this.options.onClaim?.(claimed);+ }+ }++ // --- View delivery ---------------------------------------------------------++ private deliverViewBegan(record: TouchRecord): void {+ if (record.consumer == null || record.view !== 'none') {+ return;+ }+ if (record.suppressClick) {+ record.view = 'done';+ return;+ }+ if (this.beginDelayers(record)) {+ record.view = 'held';+ return;+ }+ record.view = 'delivered';+ record.consumer.touchBegan(record.touch);+ }++ /** What a lifted touch's view and click get, decided at the lift. */+ private resolveEnd(record: TouchRecord): ClickDisposition {+ if (record.suppressClick) {+ return 'suppress';+ }+ const isHeld = this.endDelayers(record);+ switch (record.view) {+ case 'delivered':+ if (isHeld) {+ record.view = 'endHeld';+ record.deferredClick = true;+ return 'defer';+ }+ record.view = 'done';+ record.consumer?.touchEnded(record.touch);+ return 'allow';+ case 'held':+ if (!this.beginDelayers(record)) {+ // The recognizer that held the view finished on this lift: the+ // view gets the whole touch now and the click goes with it, not a+ // `defer` for a click already released.+ record.view = 'delivered';+ record.consumer?.touchBegan(record.touch);+ return this.resolveEnd(record);+ }+ record.deferredClick = true;+ return 'defer';+ case 'none':+ case 'endHeld':+ case 'done':+ if (isHeld) {+ record.deferredClick = true;+ return 'defer';+ }+ return 'allow';+ }+ }++ /** Release whatever no recognizer is holding any more. */+ private reviewHeld(): void {+ for (const record of this.records.values()) {+ if (record.view === 'held' && !this.beginDelayers(record)) {+ if (record.suppressClick) {+ record.view = 'done';+ } else {+ record.view = 'delivered';+ record.consumer?.touchBegan(record.touch);+ if (record.isLifted && !this.endDelayers(record)) {+ record.view = 'done';+ record.consumer?.touchEnded(record.touch);+ } else if (record.isLifted) {+ record.view = 'endHeld';+ }+ }+ }+ if (record.view === 'endHeld' && !this.endDelayers(record)) {+ record.view = 'done';+ if (record.suppressClick) {+ record.consumer?.touchCancelled(record.touch);+ } else {+ record.consumer?.touchEnded(record.touch);+ }+ }+ if (+ record.deferredClick &&+ record.view !== 'held' &&+ record.view !== 'endHeld' &&+ !this.endDelayers(record)+ ) {+ record.deferredClick = false;+ this.options.onDeferredClick?.(record.touch, !record.suppressClick);+ }+ }+ }++ private beginDelayers(record: TouchRecord): boolean {+ return record.participants.some(+ recognizer =>+ recognizer.delaysTouchesBegan &&+ recognizer.state === 'possible' &&+ recognizer.isInvolved() &&+ recognizer.seenTouchIds.has(record.touch.id),+ );+ }++ private endDelayers(record: TouchRecord): boolean {+ return record.participants.some(+ recognizer =>+ recognizer.delaysTouchesEnded &&+ recognizer.state === 'possible' &&+ recognizer.isInvolved() &&+ recognizer.seenTouchIds.has(record.touch.id),+ );+ }++ private cancelViewTouchesOf(recognizer: GestureRecognizer): void {+ for (const id of recognizer.seenTouchIds) {+ const record = this.records.get(id);+ if (record == null) {+ continue;+ }+ record.suppressClick = true;+ this.cancelView(record);+ }+ }++ private cancelView(record: TouchRecord): void {+ if (record.view === 'delivered' || record.view === 'endHeld') {+ record.consumer?.touchCancelled(record.touch);+ }+ if (record.view !== 'none' || record.consumer != null) {+ record.view = 'done';+ }+ }++ // --- Plumbing --------------------------------------------------------------++ private context(): GestureEventContext {+ return {+ time: this.now(),+ allTouches: [...this.records.values()]+ .filter(record => !record.isLifted)+ .map(record => record.touch),+ };+ }++ private liveTouches(ids: ReadonlyArray<number>): GestureTouch[] {+ const touches: GestureTouch[] = [];+ for (const id of ids) {+ const record = this.records.get(id);+ if (record != null && !record.isLifted) {+ touches.push(record.touch);+ }+ }+ return touches;+ }++ private update(+ inputs: ReadonlyArray<TouchInput>,+ phase: 'moved' | 'ended',+ ): GestureTouch[] {+ const changed: GestureTouch[] = [];+ for (const input of inputs) {+ const record = this.records.get(input.id);+ if (record == null || record.isLifted) {+ continue;+ }+ const time = this.clampTime(input.time);+ const touch = record.touch;+ const history = (input.history ?? []).filter(+ sample => sample.time > touch.time && sample.time < time,+ );+ touch.samples = [...history, {x: input.x, y: input.y, time}];+ touch.x = input.x;+ touch.y = input.y;+ touch.time = time;+ touch.phase = phase;+ changed.push(touch);+ }+ return changed;+ }++ private clampTime(time: number): number {+ const clamped = Math.max(time, this.latestTime);+ this.latestTime = clamped;+ return clamped;+ }++ /**+ * One external entry: run the timers due by `time`, then `body`, then+ * settle (release held deliveries, reset finished recognizers, forget+ * finished touches). Re-entrant calls (a listener feeding input) run+ * inline and settle with the outermost one.+ */+ private run(time: number, body: () => void): void {+ this.depth += 1;+ try {+ this.flushTimers(time);+ this.currentTime = this.clampTime(time);+ body();+ // Re-entrant calls settle with the outermost one: settling mid-delivery+ // would reset recognizers that have not heard the event yet.+ if (this.depth === 1) {+ this.settle();+ }+ } finally {+ this.depth -= 1;+ if (this.depth === 0) {+ this.currentTime = null;+ }+ }+ }++ private flushTimers(upTo: number): void {+ for (;;) {+ let due: [GestureRecognizer, Timer] | null = null;+ for (const entry of this.timers) {+ if (+ entry[1].deadline <= upTo &&+ (due == null ||+ entry[1].deadline < due[1].deadline ||+ // Same instant: the innermost (earlier in `active`) goes first,+ // as FR15's innermost rule decides a tie on one event.+ (entry[1].deadline === due[1].deadline &&+ this.rank(entry[0]) < this.rank(due[0])))+ ) {+ due = entry;+ }+ }+ if (due == null) {+ break;+ }+ const [recognizer, timer] = due;+ this.timers.delete(recognizer);+ this.currentTime = this.clampTime(timer.deadline);+ timer.callback();+ // Inside a re-entrant entry the outermost call settles (see run()).+ if (this.depth <= 1) {+ this.settle();+ }+ }+ this.scheduleRealTimer();+ }++ /** A recognizer's place in resolution order: innermost first, idle last. */+ private rank(recognizer: GestureRecognizer): number {+ const index = this.active.indexOf(recognizer);+ return index === -1 ? Number.POSITIVE_INFINITY : index;+ }++ private settle(): void {+ this.reviewPending();+ this.reviewHeld();+ let didReset = false;+ for (const recognizer of [...this.active]) {+ const isFinished =+ (isTerminal(recognizer.state) && recognizer.numberOfTouches === 0) ||+ (recognizer.state === 'possible' && !recognizer.isInvolved());+ if (!isFinished) {+ continue;+ }+ this.active = this.active.filter(other => other !== recognizer);+ const from = recognizer.state;+ recognizer.resetToPossible();+ didReset = true;+ if (from !== 'possible') {+ this.options.onTransition?.(recognizer, from, 'possible');+ }+ }+ if (didReset) {+ // A recognizer that finished above may have been the one holding a+ // touch from its view; release it now, not at the next input.+ this.reviewHeld();+ }+ for (const [id, record] of this.records) {+ if (+ record.isLifted &&+ record.view !== 'held' &&+ record.view !== 'endHeld' &&+ !record.deferredClick+ ) {+ this.records.delete(id);+ }+ }+ }++ private scheduleRealTimer(): void {+ let earliest = Number.POSITIVE_INFINITY;+ for (const timer of this.timers.values()) {+ earliest = Math.min(earliest, timer.deadline);+ }+ if (earliest === this.realTimerDeadline) {+ return;+ }+ if (this.realTimer != null) {+ this.clock.clearTimeout(this.realTimer);+ this.realTimer = null;+ }+ this.realTimerDeadline = earliest;+ if (earliest === Number.POSITIVE_INFINITY) {+ return;+ }+ const delay = Math.max(0, earliest - this.clock.now());+ const fire = (mayYield: boolean): void => {+ this.realTimer = null;+ this.realTimerDeadline = Number.POSITIVE_INFINITY;+ if (mayYield && this.clock.now() > earliest) {+ // Late: a long task held the main thread past the deadline, and+ // input queued behind it may come before the deadline (a lift that+ // fails a long press). Let that input dispatch first, once.+ this.realTimerDeadline = earliest;+ this.realTimer = this.clock.setTimeout(() => fire(false), 0);+ return;+ }+ // The event clock moves to the deadline only, so input still queued+ // keeps its own timestamps.+ this.advanceTime(earliest);+ };+ this.realTimer = this.clock.setTimeout(() => fire(true), delay);+ }+}++function sharesTouches(a: GestureRecognizer, b: GestureRecognizer): boolean {+ for (const id of a.seenTouchIds) {+ if (b.seenTouchIds.has(id)) {+ return true;+ }+ }+ return false;+}diff --git a/packages/core/src/gestures/GestureRecognizer.ts b/packages/core/src/gestures/GestureRecognizer.tsnew file mode 100644index 0000000000..349ebbbda9--- /dev/null+++ b/packages/core/src/gestures/GestureRecognizer.ts@@ -0,0 +1,626 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file GestureRecognizer.ts+ * @input Touches delivered by a GestureArena+ * @output Exports GestureRecognizer, the base every recognizer extends+ * (UIGestureRecognizer), and its options and listener types+ * @position Core of packages/core/src/gestures: subclasses interpret touches+ * and request state changes; the arena decides whether a change is allowed+ * (require-to-fail, exclusivity, should-begin) and applies it+ *+ * The state machine is UIKit's:+ *+ * possible ─► began ─► changed* ─► ended | cancelled (continuous)+ * possible ─► ended (discrete: "recognized")+ * possible ─► failed+ *+ * A recognizer in a terminal state ignores the touches it still has and+ * returns to `possible` (its `reset()` runs) once all of them have ended,+ * exactly as UIKit resets a recognizer before the next touch sequence.+ *+ * Listeners (UIKit's target-action) fire for `began`, `changed`, `ended` and+ * `cancelled`, never for `failed`. They run synchronously inside the input+ * 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.+ */++import type {GestureArena} from './GestureArena';+import type {+ GestureEnvironment,+ GestureEventContext,+ GestureState,+ GestureTouch,+ Point,+ PointerKind,+} from './types';+import {DEFAULT_ENVIRONMENT} from './types';++export interface GestureRecognizerOptions<R = GestureRecognizer> {+ /** A name for debugging and test output. */+ name?: string;+ /** A disabled recognizer receives no touches; disabling one mid-gesture cancels it. @default true */+ isEnabled?: boolean;+ /**+ * When the gesture is recognized, cancel the view's touches: a pressed+ * control un-highlights without acting, and the browser's click for the+ * touch is swallowed. @default true+ */+ cancelsTouchesInView?: boolean;+ /** Hold the view's touch-began until this recognizer fails. @default false */+ delaysTouchesBegan?: boolean;+ /**+ * Hold the view's touch-ended (and the browser's click) while this+ * recognizer may still recognize. @default true+ */+ delaysTouchesEnded?: boolean;+ /** Pointer kinds this recognizer listens to (UIKit's `allowedTouchTypes`). @default all */+ allowedPointerTypes?: ReadonlyArray<PointerKind>;+ /** Ignore a touch of a different kind than the ones already tracked. @default true */+ requiresExclusiveTouchType?: boolean;+ /** gestureRecognizerShouldBegin: return false to fail instead of beginning. */+ shouldBegin?: (recognizer: R) => boolean;+ /** gestureRecognizer(_:shouldReceive:): return false to never see this touch. */+ shouldReceiveTouch?: (recognizer: R, touch: GestureTouch) => boolean;+ /** gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:). */+ shouldRecognizeSimultaneously?: (+ recognizer: R,+ other: GestureRecognizer,+ ) => boolean;+ /** gestureRecognizer(_:shouldRequireFailureOf:). */+ shouldRequireFailureOf?: (recognizer: R, other: GestureRecognizer) => boolean;+ /** gestureRecognizer(_:shouldBeRequiredToFailBy:). */+ shouldBeRequiredToFailBy?: (+ recognizer: R,+ other: GestureRecognizer,+ ) => boolean;+}++export type GestureListener<R> = (recognizer: R) => void;++export type GestureTransitionListener<R> = (+ recognizer: R,+ from: GestureState,+ to: GestureState,+) => void;++const ACTION_STATES: ReadonlySet<GestureState> = new Set([+ 'began',+ 'changed',+ 'ended',+ 'cancelled',+]);++/** Transitions UIKit allows; anything else is a recognizer bug. */+const ALLOWED: Record<GestureState, ReadonlyArray<GestureState>> = {+ possible: ['began', 'ended', 'failed'],+ began: ['changed', 'ended', 'cancelled'],+ changed: ['changed', 'ended', 'cancelled'],+ ended: ['possible'],+ cancelled: ['possible'],+ failed: ['possible'],+};++export function isTransitionAllowed(+ from: GestureState,+ to: GestureState,+): boolean {+ return ALLOWED[from].includes(to);+}++export function isTerminal(state: GestureState): boolean {+ return state === 'ended' || state === 'cancelled' || state === 'failed';+}++export function isActive(state: GestureState): boolean {+ return state === 'began' || state === 'changed';+}++/** The browser behaviors `touch-action` can keep or remove. */+export interface NativeTouchBehavior {+ readonly panX: boolean;+ readonly panY: boolean;+ readonly pinchZoom: boolean;+ /** Double-tap to zoom, the reason for the old 300 ms click delay. */+ readonly doubleTapZoom: boolean;+}++export const ALL_NATIVE_TOUCH: NativeTouchBehavior = {+ panX: true,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: true,+};++/** A tap-like recognizer only needs double-tap zoom gone (no click delay). */+export const MANIPULATION: NativeTouchBehavior = {+ panX: true,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: false,+};++let nextRecognizerId = 1;++export abstract class GestureRecognizer {+ /** Stable id, for ordering and debugging. */+ readonly id = nextRecognizerId++;+ name: string;+ isEnabled: boolean;+ cancelsTouchesInView: boolean;+ delaysTouchesBegan: boolean;+ delaysTouchesEnded: boolean;+ allowedPointerTypes: ReadonlySet<PointerKind> | null;+ requiresExclusiveTouchType: boolean;+ /**+ * The element (or any object) the recognizer is attached to. The DOM host+ * sets it; the arena treats it as opaque.+ */+ view: unknown = null;++ /** @internal The arena delivering touches to this recognizer, if any. */+ arena: GestureArena | null = null;+ /** @internal A recognition waiting for a failure requirement. */+ pending: 'began' | 'ended' | null = null;++ /**+ * The delegate functions. Typed against the base so a subclass stays+ * assignable to GestureRecognizer; each is only ever called with `this`.+ */+ private readonly options: GestureRecognizerOptions<GestureRecognizer>;+ private stateValue: GestureState = 'possible';+ // Typed against the base so a subclass stays assignable to+ // GestureRecognizer; every listener is only ever called with `this`.+ private readonly listeners = new Set<GestureListener<GestureRecognizer>>();+ private readonly transitionListeners = new Set<+ GestureTransitionListener<GestureRecognizer>+ >();+ private readonly failureRequirements = new Set<GestureRecognizer>();+ private readonly simultaneousWith = new Set<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>();+ private lastLocation: Point = {x: 0, y: 0};++ constructor(options: GestureRecognizerOptions<never> = {}) {+ this.options =+ options as unknown as GestureRecognizerOptions<GestureRecognizer>;+ this.name = options.name ?? this.constructor.name;+ this.isEnabled = options.isEnabled ?? true;+ this.cancelsTouchesInView = options.cancelsTouchesInView ?? true;+ this.delaysTouchesBegan = options.delaysTouchesBegan ?? false;+ this.delaysTouchesEnded = options.delaysTouchesEnded ?? true;+ this.allowedPointerTypes =+ options.allowedPointerTypes == null+ ? null+ : new Set(options.allowedPointerTypes);+ this.requiresExclusiveTouchType =+ options.requiresExclusiveTouchType ?? true;+ }++ /** Discrete recognizers go from `possible` straight to `ended`. */+ get isDiscrete(): boolean {+ return false;+ }++ /**+ * Whether recognizing takes the touches from the browser: while a claiming+ * recognizer owns a touch, the host cancels the browser's pan and zoom for+ * it. Every touch recognizer claims; hover has no touches to claim.+ */+ get claimsTouches(): boolean {+ return true;+ }++ get state(): GestureState {+ return this.stateValue;+ }++ /**+ * What the browser may still do natively on this recognizer's view: the+ * host intersects these across a view's recognizers into its+ * `touch-action`. A recognizer that takes no touches constrains nothing.+ */+ get nativeTouchBehavior(): NativeTouchBehavior {+ return ALL_NATIVE_TOUCH;+ }++ /** @internal Whether this recognizer listens to touch at all. */+ get acceptsTouchInput(): boolean {+ return (+ this.allowedPointerTypes == null || this.allowedPointerTypes.has('touch')+ );+ }++ /** How many touches the recognizer is tracking right now. */+ get numberOfTouches(): number {+ return this.touches.size;+ }++ /** The touches being tracked, in the order they began. */+ get trackedTouches(): ReadonlyArray<GestureTouch> {+ return [...this.touches.values()];+ }++ /**+ * The centroid of the tracked touches in client coordinates; after they+ * end, where they were last.+ */+ location(): Point {+ if (this.touches.size === 0) {+ return this.lastLocation;+ }+ let x = 0;+ let y = 0;+ for (const touch of this.touches.values()) {+ x += touch.x;+ y += touch.y;+ }+ this.lastLocation = {x: x / this.touches.size, y: y / this.touches.size};+ return this.lastLocation;+ }++ /** Facts about the page (viewport, writing direction). */+ protected get environment(): GestureEnvironment {+ return this.arena?.environment ?? DEFAULT_ENVIRONMENT;+ }++ // --- Relationships -------------------------------------------------------++ /** UIKit's `require(toFail:)`: recognize only once `other` has failed. */+ requireToFail(other: GestureRecognizer): this {+ this.failureRequirements.add(other);+ return this;+ }++ /** Let this and `others` be recognized at the same time (both directions). */+ recognizeSimultaneouslyWith(...others: GestureRecognizer[]): this {+ for (const other of others) {+ this.simultaneousWith.add(other);+ other.simultaneousWith.add(this);+ }+ return this;+ }++ /** @internal Whether this recognizer must wait for `other` to fail. */+ requiresFailureOf(other: GestureRecognizer): boolean {+ return (+ this.failureRequirements.has(other) ||+ this.options.shouldRequireFailureOf?.(this, other) === true ||+ other.options.shouldBeRequiredToFailBy?.(other, this) === true+ );+ }++ /**+ * @internal Whether this and `other` may be active together: both allow it+ * (`recognizeSimultaneouslyWith` sets both sides; each delegate answers for+ * its own recognizer), so one delegate alone keeps them exclusive (FR15).+ */+ allowsSimultaneous(other: GestureRecognizer): boolean {+ return (+ this.simultaneousWith.has(other) ||+ (this.options.shouldRecognizeSimultaneously?.(this, other) === true &&+ other.options.shouldRecognizeSimultaneously?.(other, this) === true)+ );+ }++ /** @internal The delegate's should-begin answer. */+ shouldBegin(): boolean {+ return this.options.shouldBegin?.(this) ?? true;+ }++ /** UIKit's `canPrevent(_:)`: whether recognizing fails `other`. */+ canPrevent(_other: GestureRecognizer): boolean {+ return true;+ }++ /** UIKit's `canBePrevented(by:)`. */+ canBePrevented(_other: GestureRecognizer): boolean {+ return true;+ }++ /**+ * Whether this recognizer is still part of the current interaction: it+ * tracks touches, is waiting on a requirement, or (a multi-tap between+ * taps) expects more input. An idle `possible` recognizer cannot recognize+ * and so does not hold up anything that requires it to fail.+ */+ isInvolved(): boolean {+ return this.touches.size > 0 || this.pending != null;+ }++ // --- Listeners -----------------------------------------------------------++ /** Called on began, changed, ended (recognized) and cancelled. */+ addListener(listener: GestureListener<this>): () => void {+ const stored = listener as GestureListener<GestureRecognizer>;+ this.listeners.add(stored);+ return () => {+ this.listeners.delete(stored);+ };+ }++ /** Called on every transition, including failed and the reset to possible. */+ addTransitionListener(listener: GestureTransitionListener<this>): () => void {+ const stored = listener as GestureTransitionListener<GestureRecognizer>;+ this.transitionListeners.add(stored);+ return () => {+ this.transitionListeners.delete(stored);+ };+ }++ // --- Subclass API --------------------------------------------------------++ /** New touches for this recognizer. */+ protected touchesBegan(+ _touches: ReadonlyArray<GestureTouch>,+ _event: GestureEventContext,+ ): void {}++ protected touchesMoved(+ _touches: ReadonlyArray<GestureTouch>,+ _event: GestureEventContext,+ ): void {}++ /** Touches lifted; they are removed from `touches` after this returns. */+ protected touchesEnded(+ _touches: ReadonlyArray<GestureTouch>,+ _event: GestureEventContext,+ ): void {}++ /**+ * The system or the browser took these touches. By default an active+ * gesture is cancelled and a possible one fails.+ */+ protected touchesCancelled(+ _touches: ReadonlyArray<GestureTouch>,+ _event: GestureEventContext,+ ): void {+ if (isActive(this.state)) {+ this.setState('cancelled');+ } else if (this.state === 'possible') {+ this.setState('failed');+ }+ }++ /**+ * The browser took these touches for its own pan or zoom (their pointer+ * stream is gone). Return true to keep observing them; by default they are+ * treated as cancelled. An observer never claims them: a drag the browser+ * took stays the browser's (FR14).+ */+ protected touchesTakenByBrowser(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): boolean {+ this.touchesCancelled(touches, event);+ return false;+ }++ /**+ * A touch began elsewhere (off this recognizer's hit path) while this+ * recognizer tracks touches of its own. It is not this recognizer's touch+ * and is never delivered as one; a recognizer that a foreign finger should+ * end (a menu's press slide) cancels itself here. By default nothing+ * happens.+ */+ protected touchBeganElsewhere(+ _touches: ReadonlyArray<GestureTouch>,+ _event: GestureEventContext,+ ): void {}++ /** Clear per-gesture state before the next attempt. */+ protected reset(): void {}++ /**+ * Whether a touch may join. The base checks enabled, pointer kind and+ * exclusivity of kind; subclasses narrow it (a one-finger pan ignores a+ * second finger once it is moving).+ */+ protected acceptsTouch(touch: GestureTouch): boolean {+ if (!this.isEnabled) {+ return false;+ }+ if (+ this.allowedPointerTypes != null &&+ !this.allowedPointerTypes.has(touch.pointerType)+ ) {+ return false;+ }+ if (this.requiresExclusiveTouchType) {+ for (const existing of this.touches.values()) {+ if (existing.pointerType !== touch.pointerType) {+ return false;+ }+ }+ }+ return this.options.shouldReceiveTouch?.(this, touch) ?? true;+ }++ /**+ * Ask for a state change. The arena may refuse (the recognizer fails+ * instead) or defer it until a failure requirement resolves.+ */+ protected setState(next: GestureState): void {+ if (this.arena != null) {+ this.arena.requestTransition(this, next);+ } else {+ this.applyState(next);+ }+ }++ /** Arm the recognizer's one timer at an absolute time on the event clock. */+ protected setTimer(deadline: number, callback: () => void): void {+ this.arena?.setTimer(this, deadline, callback);+ }++ protected clearTimer(): void {+ this.arena?.clearTimer(this);+ }++ /** The event clock's current time. */+ protected now(): number {+ return this.arena?.now() ?? 0;+ }++ // --- Arena hooks (internal) ----------------------------------------------++ /** @internal Whether this recognizer takes `touch` right now. */+ wantsTouch(touch: GestureTouch): boolean {+ if (this.state !== 'possible' && !isActive(this.state)) {+ return false;+ }+ if (this.pending != null) {+ return false;+ }+ return this.acceptsTouch(touch);+ }++ /** @internal */+ deliverBegan(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ for (const touch of touches) {+ this.touches.set(touch.id, touch);+ this.seenTouchIds.add(touch.id);+ }+ this.location();+ this.touchesBegan(touches, event);+ }++ /** @internal */+ deliverBeganElsewhere(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (isTerminal(this.state)) {+ return;+ }+ this.touchBeganElsewhere(touches, event);+ }++ /** @internal */+ deliverMoved(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ const own = touches.filter(touch => this.touches.has(touch.id));+ if (own.length === 0 || isTerminal(this.state)) {+ return;+ }+ this.location();+ this.touchesMoved(own, event);+ }++ /** @internal */+ deliverEnded(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ const own = touches.filter(touch => this.touches.has(touch.id));+ if (own.length === 0) {+ return;+ }+ this.location();+ if (!isTerminal(this.state)) {+ this.touchesEnded(own, event);+ }+ for (const touch of own) {+ this.touches.delete(touch.id);+ }+ }++ /** @internal */+ deliverCancelled(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ const own = touches.filter(touch => this.touches.has(touch.id));+ if (own.length === 0) {+ return;+ }+ if (!isTerminal(this.state)) {+ this.touchesCancelled(own, event);+ }+ for (const touch of own) {+ this.touches.delete(touch.id);+ }+ }++ /** @internal */+ deliverTakenByBrowser(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ const own = touches.filter(touch => this.touches.has(touch.id));+ if (own.length === 0) {+ return;+ }+ if (!isTerminal(this.state) && this.touchesTakenByBrowser(own, event)) {+ return;+ }+ for (const touch of own) {+ this.touches.delete(touch.id);+ }+ }++ /**+ * UIKit's `isEnabled` setter: turning a recognizer off mid-gesture cancels+ * the gesture (an active one) or fails it (a possible one).+ */+ setEnabled(value: boolean): void {+ this.isEnabled = value;+ if (!value && (this.state !== 'possible' || this.isInvolved())) {+ this.cancel();+ }+ }++ /** Cancel this recognizer if it is active, or fail it if it is possible. */+ cancel(): void {+ if (this.arena != null) {+ this.arena.stop(this);+ } else if (isActive(this.state)) {+ this.applyState('cancelled');+ } else if (this.state === 'possible' && this.isInvolved()) {+ // An idle recognizer stays `possible`: nothing would ever reset it.+ this.applyState('failed');+ }+ }++ /** @internal Apply a transition the arena has approved. */+ applyState(next: GestureState): void {+ const from = this.stateValue;+ if (from === next && next !== 'changed') {+ return;+ }+ if (!isTransitionAllowed(from, next)) {+ return;+ }+ this.stateValue = next;+ if (next !== 'possible') {+ this.pending = null;+ }+ for (const listener of [...this.transitionListeners]) {+ listener(this, from, next);+ }+ if (ACTION_STATES.has(next)) {+ for (const listener of [...this.listeners]) {+ listener(this);+ }+ }+ }++ /** @internal Return to `possible` for the next attempt. */+ resetToPossible(): void {+ this.clearTimer();+ this.pending = null;+ this.touches.clear();+ this.seenTouchIds.clear();+ this.reset();+ this.applyState('possible');+ }+}diff --git a/packages/core/src/gestures/__tests__/arena.test.ts b/packages/core/src/gestures/__tests__/arena.test.tsnew file mode 100644index 0000000000..8cc06fc5fe--- /dev/null+++ b/packages/core/src/gestures/__tests__/arena.test.ts@@ -0,0 +1,824 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file arena.test.ts+ * @input GestureArena with scripted recognizers (test doubles that begin,+ * change, end, fail or wait on command) and recording consumers, driven by+ * synthetic touches with explicit timestamps+ * @output The arena's own rules, independent of any real recognizer:+ * exclusivity, simultaneity, require-to-fail (waiting, failing, delegate+ * requirements, idle recognizers), shouldBegin and shouldReceiveTouch,+ * innermost resolution, independent touches, delivery to the view (claims,+ * cancelsTouchesInView, delaysTouchesBegan, deferred and replayed clicks,+ * the browser taking a touch), cancellation, and the event clock+ * @position Unit tests of packages/core/src/gestures/GestureArena.ts and the+ * state machine of GestureRecognizer.ts+ */++import {describe, expect, it} from 'vitest';+import {+ GestureRecognizer,+ isActive,+ type GestureRecognizerOptions,+} from '../GestureRecognizer';+import type {GestureEventContext, GestureTouch} from '../types';+import {GestureArena, type GestureClock} from '../GestureArena';+import {createHarness, RecordingConsumer} from './harness';++type Step = (recognizer: Scripted, event: GestureEventContext) => void;++interface Script {+ began?: Step;+ moved?: Step;+ ended?: Step;+}++/**+ * A recognizer that does what its script says on each touch event, and what+ * the test asks between them. Without a script for the lift, an active+ * gesture ends with its last touch and a possible one fails.+ */+class Scripted extends GestureRecognizer {+ /** Expects more input after its touches lifted (a multi-tap between taps). */+ isWaiting = false;+ private readonly discrete: boolean;+ private readonly script: Script;++ constructor(+ name: string,+ script: Script = {},+ options: GestureRecognizerOptions<Scripted> & {discrete?: boolean} = {},+ ) {+ super({...options, name});+ this.discrete = options.discrete ?? false;+ this.script = script;+ }++ override get isDiscrete(): boolean {+ return this.discrete;+ }++ override isInvolved(): boolean {+ return super.isInvolved() || this.isWaiting;+ }++ recognize(): void {+ this.setState(this.discrete ? 'ended' : 'began');+ }++ change(): void {+ this.setState('changed');+ }++ fail(): void {+ this.isWaiting = false;+ this.setState('failed');+ }++ /** Recognize at `deadline` on the event clock, unless the touch lifts. */+ recognizeAt(deadline: number): void {+ this.setTimer(deadline, () => this.recognize());+ }++ /** Wait for more input until `deadline` on the event clock, then fail. */+ waitUntil(deadline: number): void {+ this.isWaiting = true;+ this.setTimer(deadline, () => this.fail());+ }++ protected override touchesBegan(+ _touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ this.script.began?.(this, event);+ }++ protected override touchesMoved(+ _touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (this.script.moved != null) {+ this.script.moved(this, event);+ } else if (isActive(this.state)) {+ this.change();+ }+ }++ protected override touchesEnded(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (this.script.ended != null) {+ this.script.ended(this, event);+ return;+ }+ if (this.numberOfTouches - touches.length > 0) {+ return;+ }+ if (isActive(this.state)) {+ this.setState('ended');+ } else if (this.state === 'possible') {+ this.fail();+ }+ }++ protected override reset(): void {+ this.isWaiting = false;+ }+}++/** Recognizes on the first move. */+const onMove: Script = {+ moved: r => (r.state === 'possible' ? r.recognize() : r.change()),+};++/** A discrete recognizer that recognizes at the lift. */+const atLift = (name: string, options = {}) =>+ new Scripted(name, {ended: r => r.recognize()}, {discrete: true, ...options});++/** Waits after the lift until `deadline`, as a double tap between taps does. */+const waitsAfterLift = (name: string, deadline: number) =>+ new Scripted(name, {ended: r => r.waitUntil(deadline)}, {discrete: true});++describe('arena: who wins', () => {+ it('is exclusive by default: the first to recognize fails the others', () => {+ const h = createHarness();+ const a = new Scripted('a', onMove);+ const b = new Scripted('b');+ h.finger(1)+ .down(0, 0, 0, {recognizers: [a, b]})+ .move(5, 0, 16);+ expect(h.log).toEqual(['a:began@16', 'b:failed@16']);+ expect(h.claims).toEqual([1]);+ });++ it('lets two recognize together only when allowed', () => {+ const h = createHarness();+ const a = new Scripted('a', onMove);+ const b = new Scripted('b', onMove);+ a.recognizeSimultaneouslyWith(b);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [a, b]})+ .move(5, 0, 16);+ expect(h.log).toEqual(['a:began@16', 'b:began@16']);+ });++ it('holds a recognizer that requires another to fail until it fails', () => {+ const h = createHarness();+ const single = atLift('single');+ const double = waitsAfterLift('double', 400);+ single.requireToFail(double);+ 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');+ h.advance(400);+ expect(h.log).toEqual([+ 'double:failed@400',+ 'single:ended@400',+ 'single:possible@400',+ 'double:possible@400',+ ]);+ });++ it('fails the waiting recognizer when the required one recognizes', () => {+ const h = createHarness();+ const single = atLift('single');+ const double = new Scripted('double', {}, {discrete: true});+ single.requireToFail(double);+ h.finger(1).down(0, 0, 0, {recognizers: [single, double]});+ double.recognize();+ expect(h.log).toEqual(['double:ended@0', 'single:failed@0']);+ });++ it('is not held up by a required recognizer that is not involved', () => {+ const h = createHarness();+ const idle = new Scripted('idle');+ const tap = atLift('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 failure requirements from the delegate', () => {+ const h = createHarness();+ const double = waitsAfterLift('double', 400);+ const single = atLift('single', {+ shouldRequireFailureOf: (_self: Scripted, other: GestureRecognizer) =>+ other === double,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [single, double]});+ h.finger(1).up(50);+ expect(single.pending).toBe('ended');+ });++ it('honors shouldBegin and shouldReceiveTouch', () => {+ const h = createHarness();+ const refused = new Scripted('refused', onMove, {+ shouldBegin: () => false,+ });+ const blind = new Scripted('blind', {}, {shouldReceiveTouch: () => false});+ h.finger(1)+ .down(0, 0, 0, {recognizers: [refused, blind]})+ .move(5, 0, 16);+ expect(h.log).toEqual(['refused:failed@16']);+ expect(blind.numberOfTouches).toBe(0);+ });++ it('gives a tie on the same event to the innermost recognizer', () => {+ const h = createHarness();+ const inner = new Scripted('inner', onMove);+ const outer = new Scripted('outer', onMove);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [inner, outer]})+ .move(5, 0, 16);+ expect(h.log).toEqual(['inner:began@16', 'outer:failed@16']);+ });++ it('lets fingers on unrelated views drive their own recognizers', () => {+ const h = createHarness();+ const left = new Scripted('left', onMove);+ const right = new Scripted('right', onMove);+ h.finger(1).down(0, 0, 0, {recognizers: [left]});+ h.finger(2).down(300, 0, 0, {recognizers: [right]});+ h.finger(1).move(5, 0, 16);+ h.finger(2).move(305, 0, 16);+ expect(left.state).toBe('began');+ expect(right.state).toBe('began');+ });+});++describe('arena: delivery to the view', () => {+ it('delivers an unclaimed touch and allows its click', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const r = new Scripted('r');+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [r], 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 once a recognizer takes the touch', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const r = new Scripted('r', onMove);+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [r], consumer});+ finger.move(5, 0, 16);+ expect(consumer.events).toEqual(['began:1', 'cancelled:1']);+ expect(finger.up(60)).toBe('suppress');+ });++ it('keeps the view and the click with cancelsTouchesInView off', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const r = new Scripted('r', onMove, {cancelsTouchesInView: false});+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [r], consumer});+ finger.move(5, 0, 16);+ expect(finger.up(60)).toBe('allow');+ expect(consumer.events).toEqual(['began:1', 'moved:1', 'ended:1']);+ });++ it('holds the view until the recognizer fails with delaysTouchesBegan', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const r = new Scripted(+ 'r',+ {began: (self, event) => self.waitUntil(event.time + 100)},+ {delaysTouchesBegan: true},+ );+ h.finger(1).down(0, 0, 0, {recognizers: [r], consumer});+ expect(consumer.events).toEqual([]);+ h.advance(100);+ expect(consumer.events).toEqual(['began:1']);+ });++ it('defers the click a waiting recognizer may still claim, then replays it', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const double = waitsAfterLift('double', 400);+ 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(400);+ expect(consumer.events).toEqual(['began:1', 'ended:1']);+ expect(h.deferredClicks).toEqual([{id: 1, allowed: true, time: 400}]);+ });++ it('drops the deferred click when the waiting recognizer recognizes', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ let lifts = 0;+ // Waits after the first lift, recognizes at the second.+ const double = new Scripted(+ 'double',+ {ended: r => (lifts++ === 0 ? r.waitUntil(400) : r.recognize())},+ {discrete: true},+ );+ 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('fails a possible recognizer and cancels the view when the browser takes the touch', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const r = new Scripted('r');+ h.finger(1).down(0, 0, 0, {recognizers: [r], consumer});+ h.finger(1).takenByBrowser(30);+ expect(consumer.events).toEqual(['began:1', 'cancelled:1']);+ expect(h.log).toEqual(['r:failed@30', 'r:possible@30']);+ });+});++describe('arena: cancellation and time', () => {+ it('cancels an active gesture and fails a possible one on a system cancel', () => {+ const h = createHarness();+ const active = new Scripted('active', onMove);+ const waiting = new Scripted('waiting');+ h.finger(1)+ .down(0, 0, 0, {recognizers: [active]})+ .move(5, 0, 16);+ h.finger(2).down(100, 0, 20, {recognizers: [waiting]});+ h.arena.cancelled([1, 2], 50);+ expect(h.log).toEqual([+ 'active:began@16',+ 'active:cancelled@50',+ 'waiting:failed@50',+ 'active:possible@50',+ 'waiting:possible@50',+ ]);+ });++ it('cancels an active recognizer from code, which stays cancelled until the lift', () => {+ const h = createHarness();+ const r = new Scripted('r', onMove);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [r]})+ .move(5, 0, 16);+ r.cancel();+ expect(r.state).toBe('cancelled');+ h.finger(1).move(10, 0, 32);+ expect(r.state).toBe('cancelled');+ h.finger(1).up(48);+ expect(r.state).toBe('possible');+ });++ it('runs a deadline due before a late input first, at its own time', () => {+ const h = createHarness();+ const r = new Scripted('r', {+ began: (self, event) => self.waitUntil(event.time + 500),+ });+ h.finger(1).down(0, 0, 1000, {recognizers: [r]});+ // The main thread was blocked: the next input is processed at 1900.+ h.finger(1).move(5, 0, 1900);+ expect(h.log[0]).toBe('r:failed@1500');+ });++ it('never moves the event clock backwards', () => {+ const h = createHarness();+ const r = new Scripted('r', onMove);+ h.finger(1).down(0, 0, 100, {recognizers: [r]});+ h.finger(1).move(5, 0, 90);+ expect(h.log).toEqual(['r:began@100']);+ });+});++/** 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();+ }+ }+}++/** A long press: recognizes 500 ms after touch-down unless the touch lifts. */+function pressArena(): {clock: TaskClock; arena: GestureArena; 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 Scripted('press', {+ began: (self, event) => self.recognizeAt(event.time + 500),+ });+ arena.began([+ {+ id: 1,+ x: 0,+ y: 0,+ time: 0,+ pointerType: 'touch',+ target: null,+ scroll: null,+ recognizers: [press],+ consumer: null,+ },+ ]);+ return {clock, arena, log};+}++describe('arena: 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('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('arena: claims', () => {+ it('keeps an idle recognizer usable after cancel()', () => {+ const h = createHarness();+ const r = new Scripted('r', onMove);+ r.cancel();+ expect(r.state).toBe('possible');+ h.finger(1)+ .down(0, 0, 0, {recognizers: [r]})+ .move(5, 0, 16);+ expect(h.log).toContain('r:began@16');+ h.finger(1).up(32);+ });++ it('gives back the claim of a waiting recognition that fails', () => {+ const h = createHarness();+ const waiting = new Scripted('waiting', onMove);+ const blocker = new Scripted('blocker');+ waiting.requireToFail(blocker);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [waiting, blocker]})+ .move(5, 0, 16);+ expect(h.arena.isClaimed(1)).toBe(true);+ waiting.cancel();+ expect(waiting.state).toBe('failed');+ expect(h.arena.isClaimed(1)).toBe(false);+ h.finger(1).up(32);+ });++ it('gives a resting finger back when its gesture is cancelled, so a pinch can zoom the page', () => {+ const h = createHarness();+ const r = new Scripted('r', onMove);+ const first = h+ .finger(1)+ .down(0, 0, 0, {recognizers: [r]})+ .move(5, 0, 16);+ expect(h.arena.isClaimed(1)).toBe(true);+ r.cancel();+ expect(h.arena.isClaimed(1)).toBe(false);+ // A second finger lands with nothing on its path: the browser owns both.+ const second = h.finger(2).down(200, 200, 40, {recognizers: []});+ expect(h.arena.isClaimed(2)).toBe(false);+ first.move(0, 0, 56);+ second.move(220, 220, 56);+ expect(h.arena.isClaimed(1)).toBe(false);+ first.up(80);+ second.up(80);+ });+});++/** Records the touches that began off its hit path. */+class ElsewhereRecorder extends Scripted {+ readonly elsewhere: number[] = [];+ protected override touchBeganElsewhere(+ touches: ReadonlyArray<GestureTouch>,+ ): void {+ this.elsewhere.push(...touches.map(touch => touch.id));+ }+}++describe("arena: a touch that begins off an active recognizer's hit path", () => {+ it('is reported to the recognizer, not delivered as its own', () => {+ const h = createHarness();+ const recorder = new ElsewhereRecorder('recorder');+ const first = h.finger(1).down(0, 0, 0, {recognizers: [recorder]});+ expect(recorder.elsewhere).toEqual([]);+ const second = h.finger(2).down(300, 300, 16, {recognizers: []});+ expect(recorder.elsewhere).toEqual([2]);+ expect(recorder.numberOfTouches).toBe(1);+ first.up(40);+ second.up(40);+ });++ it('is not reported to a recognizer tracking nothing', () => {+ const h = createHarness();+ const recorder = new ElsewhereRecorder('recorder');+ h.finger(1)+ .down(0, 0, 0, {recognizers: [recorder]})+ .up(20);+ h.finger(2).down(300, 300, 100, {recognizers: []}).up(120);+ expect(recorder.elsewhere).toEqual([]);+ });+});++describe('arena: resolution order across fingers', () => {+ it('lets the inner recognizer win a tie even when another finger brought the outer one first', () => {+ const h = createHarness();+ const inner = new Scripted('inner', onMove);+ const outer = new Scripted('outer', onMove);+ // Finger 1 lands on the outer view only; finger 2 on the inner view,+ // inside it. Both recognize on the same move event.+ h.arena.began([+ {+ id: 1,+ x: 0,+ y: 0,+ time: 0,+ pointerType: 'touch',+ target: null,+ scroll: null,+ recognizers: [outer],+ consumer: null,+ },+ {+ id: 2,+ x: 50,+ y: 0,+ time: 0,+ pointerType: 'touch',+ target: null,+ scroll: null,+ recognizers: [inner, outer],+ consumer: null,+ },+ ]);+ h.arena.moved([+ {id: 1, x: 10, y: 0, time: 16},+ {id: 2, x: 60, y: 0, time: 16},+ ]);+ expect(inner.state).toBe('began');+ expect(outer.state).toBe('failed');+ h.arena.ended([+ {id: 1, x: 10, y: 0, time: 32},+ {id: 2, x: 60, y: 0, time: 32},+ ]);+ });+});++describe('arena: a held view', () => {+ it('is released in the same settle as the recognizer that held it finishes', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ // Delays the view's touch, then lifts without deciding: it finishes as+ // `possible` with nothing left to track.+ const r = new Scripted('r', {ended: () => {}}, {delaysTouchesBegan: true});+ h.finger(1).down(0, 0, 0, {recognizers: [r], consumer});+ expect(consumer.events).toEqual([]);+ h.finger(1).up(40);+ expect(consumer.events).toEqual(['began:1', 'ended:1']);+ });+});++describe('arena: review fixes', () => {+ it('runs a cancel from code at the last event time, not wall time', () => {+ const h = createHarness();+ const other = new Scripted('other');+ h.finger(9)+ .down(500, 500, 0, {recognizers: [other]})+ .up(10);+ const press = new Scripted('press', {+ began: (self, event) => self.recognizeAt(event.time + 500),+ moved: (self, event) => {+ const touch = event.allTouches[0];+ if (touch != null && Math.abs(touch.x - touch.startX) > 10) {+ self.fail();+ }+ },+ });+ h.finger(1).down(0, 0, 1000, {recognizers: [press]});+ // Wall time is 1800; a 40 px move stamped 1300 is still queued.+ h.clock.time = 1800;+ other.cancel();+ h.arena.moved([{id: 1, x: 40, y: 0, time: 1300}]);+ expect(h.log).toContain('press:failed@1300');+ expect(h.log.some(entry => entry.startsWith('press:began'))).toBe(false);+ h.finger(1).up(1900, 40, 0);+ });++ it('keeps two recognizers exclusive when only one delegate allows both', () => {+ const h = createHarness();+ const a = new Scripted('a', onMove, {+ shouldRecognizeSimultaneously: () => true,+ });+ const b = new Scripted('b', onMove);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [a, b]})+ .move(5, 0, 16);+ expect(h.log).toContain('a:began@16');+ expect(b.state).toBe('failed');+ h.finger(1).up(32);+ });++ it("gives the click with the touch when the view's hold ends on the lift", () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const r = new Scripted('r', {}, {delaysTouchesBegan: true});+ h.finger(1).down(0, 0, 0, {recognizers: [r], consumer});+ expect(consumer.events).toEqual([]);+ const click = h.finger(1).up(40);+ expect(click).toBe('allow');+ expect(consumer.events).toEqual(['began:1', 'ended:1']);+ expect(h.deferredClicks).toEqual([]);+ });++ it("keeps a recognized discrete gesture's claim when a partner is cancelled", () => {+ const h = createHarness();+ const swipe = new Scripted(+ 'swipe',+ {moved: r => (r.state === 'possible' ? r.recognize() : undefined)},+ {discrete: true},+ );+ const pan = new Scripted('pan', onMove);+ swipe.recognizeSimultaneouslyWith(pan);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [swipe, pan]})+ .move(5, 0, 16);+ expect(swipe.state).toBe('ended');+ expect(h.arena.isClaimed(1)).toBe(true);+ pan.cancel();+ expect(h.arena.isClaimed(1)).toBe(true);+ h.finger(1).up(32);+ });+});++describe('arena: a lift that decides a waiting recognition', () => {+ it('answers the click with the final outcome, not a defer it already resolved', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ // r recognizes at the lift but waits for q to fail; q lifts undecided.+ const q = new Scripted('q', {ended: () => {}});+ const r = atLift('r');+ r.requireToFail(q);+ h.finger(1).down(0, 0, 0, {recognizers: [r, q], consumer});+ const click = h.finger(1).up(40);+ expect(h.log).toContain('r:ended@40');+ expect(click).toBe('suppress');+ expect(h.deferredClicks).toEqual([]);+ });+});++/** Keeps observing a touch the browser took, as a scroll-edge watcher does. */+class Observer extends Scripted {+ protected override touchesTakenByBrowser(): boolean {+ return true;+ }+}++describe('arena: round-five review fixes', () => {+ it('never claims a touch the browser took, even for a watcher that begins later (FR14)', () => {+ const h = createHarness();+ const watcher = new Observer('watcher', onMove);+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [watcher]});+ finger.takenByBrowser(10);+ finger.move(0, 40, 20);+ expect(h.log).toContain('watcher:began@20');+ expect(h.claims).toEqual([]);+ expect(h.arena.isClaimed(1)).toBe(false);+ finger.up(40);+ });++ it('settles once, with the outermost call, when a listener cancels during a touch-down', () => {+ const h = createHarness();+ const elsewhere = new Scripted('elsewhere');+ h.finger(9).down(500, 500, 0, {recognizers: [elsewhere]});+ const consumer = new RecordingConsumer();+ const first = new Scripted('first', {began: () => elsewhere.cancel()});+ const holder = new Scripted('holder', {}, {delaysTouchesBegan: true});+ h.finger(1).down(0, 0, 10, {recognizers: [first, holder], consumer});+ // The holder heard the touch and fails at the lift: the click goes.+ expect(h.finger(1).up(40)).toBe('allow');+ expect(consumer.events).toEqual(['began:1', 'ended:1']);+ h.finger(9).up(50);+ });++ it('keeps a discrete winner exclusive against a waiter its win releases (FR15)', () => {+ const h = createHarness();+ const winner = new Scripted(+ 'R',+ {moved: (r, event) => (event.time >= 32 ? r.recognize() : undefined)},+ {discrete: true},+ );+ const blocker = new Scripted('O1', {moved: () => {}});+ const waiter = new Scripted('P', onMove);+ waiter.requireToFail(blocker);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [winner, blocker, waiter]})+ .move(5, 0, 16)+ .move(10, 0, 32);+ expect(h.log).toContain('R:ended@32');+ expect(h.log).not.toContain('P:began@32');+ expect(waiter.state).toBe('failed');+ h.finger(1).up(48);+ });++ it('lets the innermost deadline win a tie at the same instant (FR15)', () => {+ const h = createHarness();+ const inner = new Scripted('inner', {+ moved: (r, event) =>+ r.state === 'possible' && event.time === 10+ ? r.recognizeAt(500)+ : undefined,+ });+ const outer = new Scripted('outer', {+ began: r => r.recognizeAt(500),+ moved: () => {},+ });+ h.finger(1)+ .down(0, 0, 0, {recognizers: [inner, outer]})+ .move(1, 0, 10);+ h.arena.advanceTime(500);+ expect(h.log).toContain('inner:began@500');+ expect(outer.state).toBe('failed');+ h.finger(1).up(600);+ });+});++describe('arena: a waiting recognition that fails on its re-attempt', () => {+ it('gives its claim back when shouldBegin refuses once the requirement fails (FR19)', () => {+ const h = createHarness();+ let mayBegin = true;+ const blocker = new Scripted('q', {+ moved: (r, event) => (event.time >= 32 ? r.fail() : undefined),+ });+ const waiter = new Scripted('r', onMove, {shouldBegin: () => mayBegin});+ waiter.requireToFail(blocker);+ const finger = h+ .finger(1)+ .down(0, 0, 0, {recognizers: [waiter, blocker]})+ .move(20, 0, 16);+ // r waits for q and holds the touch meanwhile.+ expect(h.arena.isClaimed(1)).toBe(true);+ mayBegin = false;+ finger.move(40, 0, 32);+ expect(h.log).toContain('q:failed@32');+ expect(waiter.state).toBe('failed');+ expect(h.arena.isClaimed(1)).toBe(false);+ finger.up(48);+ });+});++describe('arena: a deadline inside a re-entrant entry', () => {+ it('settles with the outermost call, so a listener feeding input mid-delivery orphans nothing', () => {+ const h = createHarness();+ const timed = new Scripted('timed', {+ began: (r, event) => r.recognizeAt(event.time + 180),+ });+ h.finger(9).down(500, 500, 0, {recognizers: [timed]});+ const consumer = new RecordingConsumer();+ // A listener that feeds input while the touch-down is being delivered:+ // the nested entry runs `timed`'s deadline (180).+ const first = new Scripted('first', {+ began: () => {+ h.arena.moved([{id: 9, x: 500, y: 500, time: 200}]);+ },+ });+ const holder = new Scripted('holder', {}, {delaysTouchesBegan: true});+ h.finger(1).down(0, 0, 150, {recognizers: [first, holder], consumer});+ expect(h.log).toContain('timed:began@180');+ expect(h.finger(1).up(250)).toBe('allow');+ expect(consumer.events).toEqual(['began:1', 'ended:1']);+ h.finger(9).up(300);+ });+});diff --git a/packages/core/src/gestures/__tests__/harness.ts b/packages/core/src/gestures/__tests__/harness.tsnew file mode 100644index 0000000000..a54549412f--- /dev/null+++ b/packages/core/src/gestures/__tests__/harness.ts@@ -0,0 +1,204 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file harness.ts+ * @input Nothing+ * @output Exports the synthetic-input harness the gesture tests share: a+ * manual clock, an arena wired to a transition log, and fingers that land,+ * move and lift at explicit timestamps+ * @position Test-only helper of packages/core/src/gestures (excluded from the+ * build with the rest of __tests__)+ */++import {GestureArena, type GestureClock} from '../GestureArena';+import type {GestureRecognizer} from '../GestureRecognizer';+import type {+ GestureEnvironment,+ GestureTouch,+ NativeScrollProbe,+ TouchConsumer,+} from '../types';++/** A clock that only moves when the test says so. */+export class ManualClock implements GestureClock {+ time = 0;+ now(): number {+ return this.time;+ }+ setTimeout(): number {+ return 0;+ }+ clearTimeout(): void {}+}++export interface Harness {+ arena: GestureArena;+ clock: ManualClock;+ /** `name:state` for every transition, in order, with its time. */+ log: string[];+ /** Touch ids claimed from the browser, in order. */+ claims: number[];+ /** Deferred clicks as they resolved. */+ deferredClicks: {id: number; allowed: boolean; time: number}[];+ environment: {width: number; height: number; rtl: boolean};+ finger(id: number): Finger;+ /** Advance the clock and run every timer due by `time`. */+ advance(time: number): void;+}++export function createHarness(): Harness {+ const clock = new ManualClock();+ const log: string[] = [];+ const claims: number[] = [];+ const deferredClicks: Harness['deferredClicks'] = [];+ const environment = {width: 390, height: 844, rtl: false};+ const fingers = new Map<number, Finger>();+ const env: GestureEnvironment = {+ viewportSize: () => ({+ width: environment.width,+ height: environment.height,+ }),+ isRtl: () => environment.rtl,+ };+ const arena: GestureArena = new GestureArena({+ clock,+ environment: env,+ onTransition: (recognizer, _from, to) => {+ log.push(`${recognizer.name}:${to}@${round(arena.now())}`);+ },+ onClaim: ids => claims.push(...ids),+ onDeferredClick: (touch, allowed) =>+ deferredClicks.push({id: touch.id, allowed, time: arena.now()}),+ });+ const harness: Harness = {+ arena,+ clock,+ log,+ claims,+ deferredClicks,+ environment,+ finger: id => {+ let finger = fingers.get(id);+ if (finger == null) {+ finger = new Finger(harness, id);+ fingers.set(id, finger);+ }+ return finger;+ },+ advance: time => {+ clock.time = time;+ arena.advanceTime(time);+ },+ };+ return harness;+}++function round(value: number): number {+ return Math.round(value * 100) / 100;+}++export interface DownOptions {+ recognizers: ReadonlyArray<GestureRecognizer>;+ consumer?: TouchConsumer | null;+ scroll?: NativeScrollProbe | null;+ pointerType?: 'touch' | 'mouse' | 'pen';+ target?: unknown;+}++/** One contact, driven with explicit timestamps. */+export class Finger {+ x = 0;+ y = 0;+ time = 0;+ constructor(+ private readonly harness: Harness,+ readonly id: number,+ ) {}++ down(x: number, y: number, time: number, options: DownOptions): this {+ this.x = x;+ this.y = y;+ this.time = time;+ this.harness.clock.time = time;+ this.harness.arena.began([+ {+ id: this.id,+ x,+ y,+ time,+ pointerType: options.pointerType ?? 'touch',+ target: options.target ?? null,+ scroll: options.scroll ?? null,+ recognizers: options.recognizers,+ consumer: options.consumer ?? null,+ },+ ]);+ return this;+ }++ move(x: number, y: number, time: number): this {+ this.x = x;+ this.y = y;+ this.time = time;+ this.harness.clock.time = time;+ this.harness.arena.moved([{id: this.id, x, y, time}]);+ return this;+ }++ /** Move in `steps` equal steps over `duration` ms. */+ drag(dx: number, dy: number, duration: number, steps = 8): this {+ const x0 = this.x;+ const y0 = this.y;+ const t0 = this.time;+ for (let i = 1; i <= steps; i++) {+ const k = i / steps;+ this.move(x0 + dx * k, y0 + dy * k, t0 + duration * k);+ }+ return this;+ }++ up(time: number, x = this.x, y = this.y) {+ this.time = time;+ this.harness.clock.time = time;+ return this.harness.arena.ended([{id: this.id, x, y, time}]).get(this.id);+ }++ cancel(time: number): void {+ this.harness.clock.time = time;+ this.harness.arena.cancelled([this.id], time);+ }++ takenByBrowser(time: number): void {+ this.harness.clock.time = time;+ this.harness.arena.browserTookOver([this.id], time);+ }+}++/** A consumer that records what the arena delivered to it. */+export class RecordingConsumer implements TouchConsumer {+ events: string[] = [];+ veto: ((recognizer: unknown) => boolean) | null = null;+ touchBegan(touch: GestureTouch): void {+ this.events.push(`began:${touch.id}`);+ }+ touchMoved(touch: GestureTouch): void {+ this.events.push(`moved:${touch.id}`);+ }+ touchEnded(touch: GestureTouch): void {+ this.events.push(`ended:${touch.id}`);+ }+ touchCancelled(touch: GestureTouch): void {+ this.events.push(`cancelled:${touch.id}`);+ }+ allowsAncestorRecognizer(recognizer: unknown): boolean {+ return this.veto == null ? true : !this.veto(recognizer);+ }+}++/** A scroll probe with a scripted answer. */+export function scrollProbe(+ canScroll: (dx: number, dy: number) => boolean,+ isInsideScroller = true,+): NativeScrollProbe {+ return {canScroll, isInsideScroller, allowsNativePan: true};+}diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.tsnew file mode 100644index 0000000000..91fc86377a--- /dev/null+++ b/packages/core/src/gestures/types.ts@@ -0,0 +1,161 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file types.ts+ * @input Nothing+ * @output Exports the data the gesture system passes around: recognizer+ * states, pointer kinds, touches (UITouch), the per-event context, the+ * environment a host provides, and the view-level touch consumer contract+ * @position Shared vocabulary of packages/core/src/gestures; no runtime code+ */++/**+ * UIGestureRecognizer.State. A discrete recognizer goes straight from+ * `possible` to `ended` (UIKit's `.recognized` is the same value).+ */+export type GestureState =+ 'possible' | 'began' | 'changed' | 'ended' | 'cancelled' | 'failed';++/** What made the contact. A pen on an iPad is `pen`, not `touch`. */+export type PointerKind = 'touch' | 'mouse' | 'pen';++export interface Point {+ readonly x: number;+ readonly y: number;+}++/** One position of a contact at one instant, in client (viewport) CSS px. */+export interface TouchSample {+ readonly x: number;+ readonly y: number;+ /** Milliseconds on the `performance.now()` clock (an event's `timeStamp`). */+ readonly time: number;+}++export type TouchPhase = 'began' | 'moved' | 'ended' | 'cancelled';++/**+ * The scrollers between a touch and the page, as the host sees them: enough+ * for a recognizer to ask whether the browser would scroll something if the+ * finger moved one way, without the recognizer touching the DOM.+ */+export interface NativeScrollProbe {+ /**+ * Whether a finger moving by (dx, dy) would scroll some element under the+ * touch (one that has room left in that direction and whose `touch-action`+ * lets the browser pan that axis).+ */+ canScroll(dx: number, dy: number): boolean;+ /**+ * How much further (px) the scroller that would move for a finger moving+ * by (dx, dy) can scroll before it reaches its edge; 0 when none would.+ * Lets a scroll handoff place the point where the content ran out between+ * two samples instead of at the next one.+ */+ distanceToEdge?(dx: number, dy: number): number;+ /** Whether any element under the touch can scroll natively at all. */+ readonly isInsideScroller: boolean;+ /**+ * Whether `touch-action` from the touch target to the page lets the+ * browser pan at all: when it does not, the browser cannot have taken the+ * touch for a scroll, whatever its events say.+ */+ readonly allowsNativePan: boolean;+}++/**+ * One contact: UITouch. The arena owns it and updates it in place; a+ * recognizer keeps a reference to every touch it receives.+ */+export interface GestureTouch {+ /** Unique among the contacts the arena tracks at once. */+ readonly id: number;+ readonly pointerType: PointerKind;+ phase: TouchPhase;+ /** Latest position, client CSS px. */+ x: number;+ y: number;+ /** Timestamp of the latest position. */+ time: number;+ readonly startX: number;+ readonly startY: number;+ readonly startTime: number;+ /**+ * Positions since the previous event, oldest first, ending with the+ * current one (coalesced samples where the platform has them). Velocity+ * trackers read these; actions fire once per event.+ */+ samples: TouchSample[];+ /** The node the contact began on. Opaque to the arena. */+ readonly target: unknown;+ /** The native scrollers under the contact, when the host knows them. */+ readonly scroll: NativeScrollProbe | null;+ /** The browser took this contact for its own pan or zoom. */+ takenByBrowser: boolean;+}++/** The input a host hands the arena for one contact in one event. */+export interface TouchInput {+ readonly id: number;+ readonly x: number;+ readonly y: number;+ readonly time: number;+ /** Extra positions since the previous event, oldest first (coalesced). */+ readonly history?: ReadonlyArray<TouchSample>;+}++/** A new contact: where it is, what made it, and what it landed on. */+export interface TouchBeganInput extends TouchInput {+ readonly pointerType: PointerKind;+ readonly target: unknown;+ readonly scroll?: NativeScrollProbe | null;+}++/** What a recognizer is told alongside the touches that changed. */+export interface GestureEventContext {+ /** Timestamp of the event being processed. */+ readonly time: number;+ /** Every contact the arena currently tracks, not only this recognizer's. */+ readonly allTouches: ReadonlyArray<GestureTouch>;+}++/**+ * Facts about the page a recognizer may need and must not read from the DOM+ * itself: the viewport for screen-edge pans, and the writing direction of a+ * view for `leading` / `trailing`.+ */+export interface GestureEnvironment {+ viewportSize(): {readonly width: number; readonly height: number};+ isRtl(view: unknown): boolean;+}++export const DEFAULT_ENVIRONMENT: GestureEnvironment = {+ viewportSize() {+ if (typeof window === 'undefined') {+ return {width: 0, height: 0};+ }+ return {width: window.innerWidth, height: window.innerHeight};+ },+ isRtl() {+ return false;+ },+};++/**+ * A view-level touch consumer: what UIKit delivers `touchesBegan` /+ * `touchesEnded` to when no gesture recognizer takes the touch (a UIControl).+ * The arena delivers through it, honoring `delaysTouchesBegan`,+ * `delaysTouchesEnded` and `cancelsTouchesInView`.+ */+export interface TouchConsumer {+ touchBegan(touch: GestureTouch): void;+ touchMoved(touch: GestureTouch): void;+ touchEnded(touch: GestureTouch): void;+ touchCancelled(touch: GestureTouch): void;+ /**+ * UIControl's iOS 6 rule: a control's own action wins over an overlapping+ * single-tap recognizer on an ancestor. Return false to stop `recognizer`+ * (attached above this consumer) from beginning for a touch on it.+ */+ allowsAncestorRecognizer?(recognizer: unknown): boolean;+}