An open source design system that's fully customizable and agent ready
TypeScript
feat(core): swipe, pinch and screen-edge pan recognizers (#8061)
Christopher Chedeau5654357e1aa9
diff --git a/.changeset/gesture-swipe-pinch-edge.md b/.changeset/gesture-swipe-pinch-edge.mdnew file mode 100644index 0000000000..27c89e4323--- /dev/null+++ b/.changeset/gesture-swipe-pinch-edge.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: swipe, pinch and screen-edge pan gesture recognizers. Not exported from the package entry point; no component uses them yet.++@vjeuxdiff --git a/packages/core/src/gestures/PinchGestureRecognizer.ts b/packages/core/src/gestures/PinchGestureRecognizer.tsnew file mode 100644index 0000000000..2835237645--- /dev/null+++ b/packages/core/src/gestures/PinchGestureRecognizer.ts@@ -0,0 +1,144 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PinchGestureRecognizer.ts+ * @input Touches from a GestureArena+ * @output Exports PinchGestureRecognizer (UIPinchGestureRecognizer) and its+ * options+ * @position Continuous two-finger recognizer of packages/core/src/gestures+ *+ * Tracks the first two fingers; more are ignored. Begins once the distance+ * between them has changed by `hysteresis` px. As in UIKit, `scale` is then+ * the current distance over the starting distance moved by the hysteresis+ * toward the pinch, so it does not jump (settable to re-base it); `velocity`+ * is scale per second. Lifting either finger ends an+ * active pinch and fails a possible one.+ *+ * A host gives every element WITHOUT a pinch recognizer `pinch-zoom` in its+ * `touch-action`, so the page stays zoomable (WCAG 1.4.4); attaching one+ * takes the two-finger gesture for this element only.+ */++import {UIKIT_PINCH} from '../motion/uikit/gestures';+import {centroid, distance} from './geometry';+import {+ GestureRecognizer,+ isActive,+ type GestureRecognizerOptions,+ type NativeTouchBehavior,+} from './GestureRecognizer';+import type {GestureEventContext, GestureTouch, Point} from './types';+import {VelocityTracker} from './VelocityTracker';++export interface PinchGestureRecognizerOptions extends GestureRecognizerOptions<PinchGestureRecognizer> {+ hysteresis?: number;+}++export class PinchGestureRecognizer extends GestureRecognizer {+ hysteresis: number;+ private initialSpan = 0;+ private scaleValue = 1;+ private readonly tracker = new VelocityTracker();+ private lastTime = 0;++ constructor(options: PinchGestureRecognizerOptions = {}) {+ super(options);+ this.hysteresis = options.hysteresis ?? UIKIT_PINCH.hysteresis.value;+ }++ /** Current span over the span the fingers started at. */+ get scale(): number {+ return this.scaleValue;+ }++ /** Re-base: from now on the scale reads `value` at the current span. */+ set scale(value: number) {+ const span = this.span();+ if (span > 0 && value > 0) {+ this.initialSpan = span / value;+ this.scaleValue = value;+ // The velocity continues from the re-based value, without a jump.+ this.tracker.reset();+ this.tracker.add(value, 0, this.lastTime);+ }+ }++ /** Scale per second (UIKit's filter; measured for pans, assumed here). */+ get velocity(): number {+ return this.tracker.velocity().x;+ }++ /** The midpoint between the two fingers. */+ focalPoint(): Point {+ return centroid(this.touches.values());+ }++ /** Two fingers on this view are this recognizer's, not the browser's zoom. */+ override get nativeTouchBehavior(): NativeTouchBehavior {+ return {panX: true, panY: true, pinchZoom: false, doubleTapZoom: false};+ }++ protected override acceptsTouch(touch: GestureTouch): boolean {+ return this.numberOfTouches < 2 && super.acceptsTouch(touch);+ }++ protected override touchesBegan(+ _touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ this.lastTime = event.time;+ if (this.numberOfTouches === 2) {+ this.initialSpan = this.span();+ this.scaleValue = 1;+ this.tracker.reset();+ this.tracker.add(1, 0, event.time);+ }+ }++ protected override touchesMoved(+ _touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (this.numberOfTouches < 2 || this.initialSpan <= 0) {+ return;+ }+ this.lastTime = event.time;+ const span = this.span();+ // Once recognized, a pinch waiting on a recognizer it requires to fail+ // keeps its re-based start: its moves only follow the fingers.+ if (this.state === 'possible' && this.pending == null) {+ if (Math.abs(span - this.initialSpan) >= this.hysteresis) {+ // UIKit measures from the start moved by the hysteresis, and its+ // first velocity spans from the touch-down (scale 1) to here.+ this.initialSpan +=+ Math.sign(span - this.initialSpan) * this.hysteresis;+ this.scaleValue = span / this.initialSpan;+ this.tracker.add(this.scaleValue, 0, event.time);+ this.setState('began');+ }+ return;+ }+ this.scaleValue = span / this.initialSpan;+ // Every move of the fingers is a sample: a span that holds while they+ // move reads as no change, so the velocity never goes stale.+ this.tracker.add(this.scaleValue, 0, event.time, {isMotion: true});+ if (isActive(this.state)) {+ this.setState('changed');+ }+ }++ protected override touchesEnded(): void {+ this.setState(isActive(this.state) ? 'ended' : 'failed');+ }++ protected override reset(): void {+ this.initialSpan = 0;+ this.scaleValue = 1;+ this.tracker.reset();+ }++ private span(): number {+ const [a, b] = this.trackedTouches;+ return a == null || b == null ? 0 : distance(a, b);+ }+}diff --git a/packages/core/src/gestures/ScreenEdgePanGestureRecognizer.ts b/packages/core/src/gestures/ScreenEdgePanGestureRecognizer.tsnew file mode 100644index 0000000000..5f6dd1cedc--- /dev/null+++ b/packages/core/src/gestures/ScreenEdgePanGestureRecognizer.ts@@ -0,0 +1,252 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ScreenEdgePanGestureRecognizer.ts+ * @input Touches from a GestureArena; the viewport size and writing+ * direction from its environment+ * @output Exports ScreenEdgePanGestureRecognizer+ * (UIScreenEdgePanGestureRecognizer), its options and edge type+ * @position Continuous recognizer of packages/core/src/gestures, a pan that+ * only starts from a band at the edge of the viewport+ *+ * A touch that lands outside every requested band fails at once, so a+ * recognizer that requires this one to fail is not held up by a touch in the+ * middle of the screen. Inside a band, the pan begins on movement away from+ * that edge. `leading` and `trailing` resolve against the view's writing+ * direction: under RTL the leading edge is the right one, as the+ * interactive pop gesture's is.+ *+ * Attach it to the edge zone: an element that lies within the band at its+ * edge. There the pan takes the horizontal axis from the browser, which has+ * nothing to scroll in so thin a band, so a touch in the band decides at+ * UIKit's 15 px screen-edge hysteresis. On any other view, whose+ * `touch-action` cannot claim per touch, it leaves the browser every touch+ * behavior, so the author's scrolling there is untouched, and a touch in the+ * band decides at FR19's 10 px like every other claim (spec:AST-094 FR18,+ * DEC-22). The edges' physical sides and the edge zone are measured once,+ * together, and serve both the element's `touch-action` and the touch-down+ * decision; the host reports a layout change (layoutChanged), and a changed+ * answer is announced (onTouchBehaviorChange) so `touch-action` follows it+ * (FR19). The writing direction is read again at each touch-down: a view+ * switched to RTL in place, with no resize, is measured again there and the+ * change announced, so a `leading` back swipe follows the new leading edge+ * (`design:bidirectionality` DR13). That touch landed under the touch-action+ * from before, so it decides at FR19's 10 px unless that one claimed the+ * axis.+ */++import {UIKIT_PAN, UIKIT_SCREEN_EDGE_PAN} from '../motion/uikit/gestures';+import {ALL_NATIVE_TOUCH, type NativeTouchBehavior} from './GestureRecognizer';+import {+ PanGestureRecognizer,+ type PanGestureRecognizerOptions,+} from './PanGestureRecognizer';+import type {GestureEventContext, GestureTouch} from './types';++/**+ * How far past `edgeRegion` a view still counts as the edge zone, px: layout+ * snaps sizes to 1/64 px, so a strip authored at the region measures a hair+ * wider; half a pixel takes that and nothing a pixel wider.+ */+const EDGE_ZONE_TOLERANCE = 0.5;++/**+ * An edge by writing direction: under RTL the leading edge is the right one.+ * Top and bottom edges land with their first user.+ */+export type ScreenEdge = 'leading' | 'trailing';++/** A physical horizontal edge of the viewport. */+type PhysicalEdge = 'left' | 'right';++/**+ * What the pan measures of its view, once until a layout change: the+ * writing direction it read, the physical sides its edges resolve to under+ * that direction, and the sides whose band the view lies within.+ */+interface EdgeLayout {+ readonly isRtl: boolean;+ readonly watched: ReadonlyArray<PhysicalEdge>;+ readonly zone: ReadonlySet<PhysicalEdge>;+}++/**+ * A screen-edge pan is a finger's: it takes no `allowedPointerTypes`+ * (`spec:AST-094` FR43).+ */+export interface ScreenEdgePanGestureRecognizerOptions extends Omit<+ PanGestureRecognizerOptions,+ 'direction' | 'allowedPointerTypes'+> {+ /** The edges a touch may start from. @default ['leading'] */+ edges?: ReadonlyArray<ScreenEdge>;+ /** Width of the band at each edge, px. */+ edgeRegion?: number;+}++export class ScreenEdgePanGestureRecognizer extends PanGestureRecognizer {+ edges: ReadonlyArray<ScreenEdge>;+ edgeRegion: number;+ /** The physical edge the current gesture started from. */+ activeEdge: PhysicalEdge | null = null;+ /**+ * @internal Set by the host while attached: called when the edge-zone+ * answer changes, so the element's `touch-action` follows it+ * (spec:AST-094 FR19, DEC-22).+ */+ onTouchBehaviorChange: (() => void) | null = null;+ /** The hysteresis where the pan takes its axis (UIKit's 15 px). */+ private readonly edgeHysteresis: number;+ /** What the pan measured of its view (see EdgeLayout), until a layout change. */+ private layout: EdgeLayout | null = null;++ constructor(options: ScreenEdgePanGestureRecognizerOptions = {}) {+ super({+ maximumNumberOfTouches: 1,+ hysteresis: UIKIT_SCREEN_EDGE_PAN.hysteresis.value,+ ...options,+ // A finger's only: under a mouse, a trackpad or a pen the screen-edge+ // pan stays off (`spec:AST-094` FR43), whatever a caller passes.+ allowedPointerTypes: ['touch'],+ });+ this.edges = options.edges ?? ['leading'];+ this.edgeRegion =+ options.edgeRegion ?? UIKIT_SCREEN_EDGE_PAN.edgeRegion.value;+ this.edgeHysteresis = this.hysteresis;+ }++ /**+ * The pan takes the horizontal axis only in its edge zone, a view within+ * the band of an edge it watches; elsewhere it leaves the browser every+ * touch behavior, so the author's scrolling is untouched (spec:AST-094+ * FR18), never claiming across a whole wider element.+ */+ override get nativeTouchBehavior(): NativeTouchBehavior {+ const {watched, zone} = this.measured();+ if (!watched.some(edge => zone.has(edge))) {+ return ALL_NATIVE_TOUCH;+ }+ return {+ panX: false,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: false,+ };+ }++ /**+ * @internal Whether the edge zone depends on the viewport's width: the pan+ * watches the right side, whose band moves with the viewport, so the host+ * reports a viewport resize to it as well as its own box's (FR19, FR24).+ */+ get watchesViewport(): boolean {+ return this.measured().watched.includes('right');+ }++ /**+ * @internal The view's box may have changed (a resize): its edges' sides+ * and the edge zone are measured again, and a changed answer calls+ * onTouchBehaviorChange.+ */+ layoutChanged(): void {+ const before = this.layout;+ this.layout = null;+ const after = this.measured();+ if (+ before == null ||+ before.watched.join() !== after.watched.join() ||+ before.zone.size !== after.zone.size ||+ [...after.zone].some(edge => !before.zone.has(edge))+ ) {+ this.onTouchBehaviorChange?.();+ }+ }++ protected override touchesBegan(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (this.numberOfTouches === touches.length) {+ // The touch-action the browser applies to this touch was derived from+ // the layout in force as it landed: whether that claimed the axis.+ const inForce = this.measured();+ const claimedAxis = inForce.watched.some(side => inForce.zone.has(side));+ // A direction switched in place (no resize) moves the leading edge:+ // measure again, and announce it so touch-action follows for the next+ // touch (DR13).+ if (inForce.isRtl !== this.environment.isRtl(this.view)) {+ this.layoutChanged();+ }+ const edge = this.edgeAt(touches[0]);+ if (edge == null) {+ this.setState('failed');+ return;+ }+ this.activeEdge = edge;+ // On an element within the band, which takes the axis across the edge,+ // a touch decides at UIKit's 15 px; on any other, which leaves the+ // browser that axis, at FR19's 10 px, before the browser commits to a+ // scroll (spec:AST-094 FR18, DEC-22). The answer is the one this+ // touch's touch-action was derived from: a touch that measured again+ // decides at 10 px unless the layout in force claimed the axis.+ const offZone = !claimedAxis || !this.measured().zone.has(edge);+ this.hysteresis = offZone+ ? Math.min(this.edgeHysteresis, UIKIT_PAN.hysteresis.value)+ : this.edgeHysteresis;+ this.direction = edge === 'left' ? 'right' : 'left';+ }+ super.touchesBegan(touches, event);+ }++ /**+ * The physical sides the pan's edges resolve to under the view's writing+ * direction, and the sides whose band the view lies within, measured+ * together once until a layout change: the view starts at that side and+ * reaches no farther than `edgeRegion` from it, within layout's rounding+ * (a strip authored at the 40.2 px region lays out at 40.203 px, on+ * 1/64 px). A view that cannot be measured lies within none.+ */+ private measured(): EdgeLayout {+ if (this.layout != null) {+ return this.layout;+ }+ const isRtl = this.environment.isRtl(this.view);+ const watched = this.edges.map(edge =>+ (edge === 'leading') !== isRtl ? 'left' : 'right',+ );+ const zone = new Set<PhysicalEdge>();+ const rect = this.environment.viewRect?.(this.view);+ if (rect != null && rect.width > 0) {+ const {width} = this.environment.viewportSize();+ const right = rect.left + rect.width;+ const band = this.edgeRegion + EDGE_ZONE_TOLERANCE;+ if (rect.left >= -EDGE_ZONE_TOLERANCE && right <= band) {+ zone.add('left');+ }+ if (rect.left >= width - band && right <= width + EDGE_ZONE_TOLERANCE) {+ zone.add('right');+ }+ }+ this.layout = {isRtl, watched, zone};+ return this.layout;+ }++ protected override reset(): void {+ super.reset();+ this.activeEdge = null;+ }++ private edgeAt(touch: GestureTouch): PhysicalEdge | null {+ const {width} = this.environment.viewportSize();+ for (const physical of this.measured().watched) {+ const inBand =+ physical === 'left'+ ? touch.startX <= this.edgeRegion+ : touch.startX >= width - this.edgeRegion;+ if (inBand) {+ return physical;+ }+ }+ return null;+ }+}diff --git a/packages/core/src/gestures/SwipeGestureRecognizer.ts b/packages/core/src/gestures/SwipeGestureRecognizer.tsnew file mode 100644index 0000000000..d4b83bc072--- /dev/null+++ b/packages/core/src/gestures/SwipeGestureRecognizer.ts@@ -0,0 +1,193 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SwipeGestureRecognizer.ts+ * @input Touches from a GestureArena+ * @output Exports SwipeGestureRecognizer (UISwipeGestureRecognizer), its+ * options and direction type+ * @position Discrete recognizer of packages/core/src/gestures+ *+ * Recognized WHILE the fingers move, as UIKit's is: as soon as the centroid+ * has travelled `minimumDistance` along an allowed direction, within+ * `maximumDuration` of touch-down, with off-axis travel no more than+ * `maximumSecondaryMovement` px across it. Off-axis travel past that+ * allowance, or the distance travelled the wrong way, rules a direction out;+ * the swipe fails once every allowed direction is ruled out, as it does for+ * too many fingers, the duration running out, and a lift before it was+ * recognized.+ */++import {UIKIT_SWIPE} from '../motion/uikit/gestures';+import {centroid} from './geometry';+import {+ GestureRecognizer,+ type GestureRecognizerOptions,+ type NativeTouchBehavior,+} from './GestureRecognizer';+import type {GestureEventContext, GestureTouch, Point} from './types';++export type SwipeDirection = 'left' | 'right' | 'up' | 'down';++export interface SwipeGestureRecognizerOptions extends GestureRecognizerOptions<SwipeGestureRecognizer> {+ /** @default ['right'] */+ direction?: SwipeDirection | ReadonlyArray<SwipeDirection>;+ /** @default 1 */+ numberOfTouchesRequired?: number;+ minimumDistance?: number;+ maximumDuration?: number;+ maximumSecondaryMovement?: number;+}++const SWIPE = UIKIT_SWIPE;++export class SwipeGestureRecognizer extends GestureRecognizer {+ directions: ReadonlyArray<SwipeDirection>;+ numberOfTouchesRequired: number;+ minimumDistance: number;+ maximumDuration: number;+ maximumSecondaryMovement: number;+ /** The direction of the recognized swipe. */+ recognizedDirection: SwipeDirection | null = null;++ private origin: Point = {x: 0, y: 0};+ /** Directions this touch's path has ruled out. */+ private readonly ruledOut = new Set<SwipeDirection>();+ /** The centroid at the previous move. */+ private last: Point | null = null;++ constructor(options: SwipeGestureRecognizerOptions = {}) {+ super(options);+ const direction = options.direction ?? ['right'];+ this.directions = typeof direction === 'string' ? [direction] : direction;+ this.numberOfTouchesRequired = options.numberOfTouchesRequired ?? 1;+ this.minimumDistance =+ options.minimumDistance ?? SWIPE.minimumDistance.value;+ this.maximumDuration =+ options.maximumDuration ?? SWIPE.maximumDuration.value;+ this.maximumSecondaryMovement =+ options.maximumSecondaryMovement ?? SWIPE.maximumSecondaryMovement.value;+ }++ override get isDiscrete(): boolean {+ return true;+ }++ override get nativeTouchBehavior(): NativeTouchBehavior {+ const horizontal = this.directions.some(+ direction => direction === 'left' || direction === 'right',+ );+ const vertical = this.directions.some(+ direction => direction === 'up' || direction === 'down',+ );+ return {+ panX: !horizontal,+ panY: !vertical,+ pinchZoom: true,+ doubleTapZoom: false,+ };+ }++ protected override touchesBegan(+ touches: ReadonlyArray<GestureTouch>,+ event: GestureEventContext,+ ): void {+ if (this.numberOfTouches > this.numberOfTouchesRequired) {+ this.setState('failed');+ return;+ }+ if (this.numberOfTouches === touches.length) {+ this.setTimer(event.time + this.maximumDuration, () => {+ // A swipe already recognized, waiting on a recognizer it requires to+ // fail, holds its recognition (spec:AST-094 FR15).+ if (this.pending == null) {+ this.setState('failed');+ }+ });+ }+ // Measure from where every required finger is down.+ this.origin = centroid(this.touches.values());+ this.last = null;+ }++ protected override touchesMoved(): void {+ if (+ this.pending != null ||+ this.numberOfTouches !== this.numberOfTouchesRequired+ ) {+ return;+ }+ const current = centroid(this.touches.values());+ const from = this.last ?? this.origin;+ this.last = current;+ for (const direction of this.directions) {+ if (this.ruledOut.has(direction)) {+ continue;+ }+ // Along and across this direction at the start and the end of the+ // move. The path between two events is read as a straight segment, so+ // the verdict does not depend on how far apart the events were.+ const [along0, across0] = this.project(direction, from);+ const [along1, across1] = this.project(direction, current);+ const reaches = segmentCrossing(along0, along1, this.minimumDistance);+ const strays = Math.max(+ segmentCrossing(across0, across1, this.maximumSecondaryMovement),+ segmentCrossing(-across0, -across1, this.maximumSecondaryMovement),+ );+ const strayAt = strays < 0 ? Infinity : strays;+ if (reaches >= 0 && reaches <= strayAt) {+ this.recognizedDirection = direction;+ this.setState('ended');+ return;+ }+ // Off-axis travel past the allowance, or the distance the wrong way,+ // rules a direction out for good.+ if (strays >= 0 || along1 <= -this.minimumDistance) {+ this.ruledOut.add(direction);+ }+ }+ if (this.directions.every(direction => this.ruledOut.has(direction))) {+ this.setState('failed');+ }+ }++ /** Travel along and across `direction` from the origin to `point`. */+ private project(direction: SwipeDirection, point: Point): [number, number] {+ const dx = point.x - this.origin.x;+ const dy = point.y - this.origin.y;+ return direction === 'left'+ ? [-dx, dy]+ : direction === 'right'+ ? [dx, dy]+ : direction === 'up'+ ? [-dy, dx]+ : [dy, dx];+ }++ protected override touchesEnded(): void {+ // Recognized and waiting, it holds past the lift (FR15).+ if (this.pending == null) {+ this.setState('failed');+ }+ }++ protected override reset(): void {+ this.recognizedDirection = null;+ this.ruledOut.clear();+ this.last = null;+ this.origin = {x: 0, y: 0};+ }+}++/**+ * Where on the segment from `start` to `end` (0 to 1) the value first+ * reaches `limit`; 0 when it starts there, -1 when it never does.+ */+function segmentCrossing(start: number, end: number, limit: number): number {+ if (start >= limit) {+ return 0;+ }+ if (end < limit) {+ return -1;+ }+ return (limit - start) / (end - start);+}diff --git a/packages/core/src/gestures/VelocityTracker.ts b/packages/core/src/gestures/VelocityTracker.tsindex c627282c8c..c3838427a2 100644--- a/packages/core/src/gestures/VelocityTracker.ts+++ b/packages/core/src/gestures/VelocityTracker.ts@@ -88,15 +88,22 @@ export class VelocityTracker {* Record a position. Timestamps must not go backwards (an older sample is* ignored), and a moved sample at the newest moved sample's timestamp* replaces it. A sample at the newest position is not motion: it changes- * no velocity.+ * no velocity, unless `isMotion` says the contact moved anyway (a pinch's+ * value holding while both fingers move, which reads as zero velocity for+ * that interval).*/- add(x: number, y: number, time: number): void {+ add(+ x: number,+ y: number,+ time: number,+ {isMotion = false}: {isMotion?: boolean} = {},+ ): void {if (this.newest != null && time < this.newest.time) {return;}this.newest = {x, y, time};const last = this.moved[this.moved.length - 1];- if (last != null && x === last.x && y === last.y) {+ if (last != null && x === last.x && y === last.y && !isMotion) {return;}if (last != null && time === last.time) {diff --git a/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.tsindex 1cf18ec0b6..04049b935b 100644--- a/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.ts+++ b/packages/core/src/gestures/__tests__/PanGestureRecognizer.test.ts@@ -8,15 +8,15 @@*/import {describe, expect, it} from 'vitest';-import {UIKIT_GESTURES} from '../../motion/uikit/gestures';+import {UIKIT_PAN, UIKIT_VELOCITY} from '../../motion/uikit/gestures';import {PanGestureRecognizer} from '../PanGestureRecognizer';-import {createHarness, scrollProbe} from './harness';+import {createHarness} from './harness';describe('PanGestureRecognizer', () => {it('begins past the hysteresis and leaves the threshold out of the translation', () => {const h = createHarness();const pan = new PanGestureRecognizer({name: 'pan'});- const hysteresis = UIKIT_GESTURES.pan.hysteresis.value;+ const hysteresis = UIKIT_PAN.hysteresis.value;h.finger(1).down(100, 100, 0, {recognizers: [pan]});h.finger(1).move(100 + hysteresis - 0.1, 100, 16);expect(pan.state).toBe('possible');@@ -75,7 +75,7 @@ describe('PanGestureRecognizer', () => {});it('releases at 0 after a rest longer than the stillness interval (AST-100 FR2)', () => {- const stillness = UIKIT_GESTURES.velocity.stillness.value;+ const stillness = UIKIT_VELOCITY.stillness.value;const release = (liftAt: number) => {const h = createHarness();const pan = new PanGestureRecognizer({name: 'pan'});diff --git a/packages/core/src/gestures/__tests__/PinchGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/PinchGestureRecognizer.test.tsnew file mode 100644index 0000000000..bccdf40aca--- /dev/null+++ b/packages/core/src/gestures/__tests__/PinchGestureRecognizer.test.ts@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PinchGestureRecognizer.test.ts+ * @input Synthetic touches with explicit timestamps through a GestureArena+ * @output PinchGestureRecognizer's state machine: the hysteresis, the scale against the moved starting span, the velocity, extra fingers, re-basing+ * @position Unit tests of packages/core/src/gestures/PinchGestureRecognizer.ts+ */++import {describe, expect, it} from 'vitest';+import {PinchGestureRecognizer} from '../PinchGestureRecognizer';+import {createHarness} from './harness';++describe('PinchGestureRecognizer', () => {+ it('begins after the hysteresis and reports scale and velocity', () => {+ const h = createHarness();+ const pinch = new PinchGestureRecognizer({name: 'pinch'});+ h.finger(1).down(100, 100, 0, {recognizers: [pinch]});+ h.finger(2).down(200, 100, 0, {recognizers: [pinch]});+ h.finger(2).move(205, 100, 16);+ expect(pinch.state).toBe('possible');+ h.finger(2).move(210, 100, 32);+ expect(pinch.state).toBe('began');+ // UIKit: against the starting span moved by the hysteresis (100 + 8).+ expect(pinch.scale).toBeCloseTo(110 / 108, 5);+ for (let t = 48; t <= 160; t += 16) {+ h.finger(2).move(210 + (t - 32) * 0.1, 100, t);+ }+ // 0.1 px/ms over 108 px.+ expect(pinch.velocity).toBeCloseTo(100 / 108, 5);+ h.finger(1).up(170);+ expect(h.log).toContain('pinch:ended@170');+ });++ it('ignores a third finger and can be re-based', () => {+ const h = createHarness();+ const pinch = new PinchGestureRecognizer({name: 'pinch'});+ h.finger(1).down(0, 0, 0, {recognizers: [pinch]});+ h.finger(2).down(100, 0, 0, {recognizers: [pinch]});+ h.finger(3).down(50, 50, 5, {recognizers: [pinch]});+ expect(pinch.numberOfTouches).toBe(2);+ h.finger(2).move(150, 0, 16);+ pinch.scale = 1;+ h.finger(2).move(300, 0, 32);+ expect(pinch.scale).toBeCloseTo(2, 5);+ });++ it('lets the velocity settle when the span holds while the fingers move', () => {+ const h = createHarness();+ const pinch = new PinchGestureRecognizer({name: 'pinch'});+ h.finger(1).down(100, 100, 0, {recognizers: [pinch]});+ h.finger(2).down(200, 100, 0, {recognizers: [pinch]});+ let time = 0;+ for (let x = 210; x <= 260; x += 10) {+ time += 16;+ h.finger(2).move(x, 100, time);+ }+ const spreading = pinch.velocity;+ expect(spreading).toBeGreaterThan(0);+ // The second finger circles the first at exactly the same distance (160:+ // 3-4-5 triangles), so the span holds while it moves.+ for (const [dx, dy] of [+ [128, 96],+ [96, 128],+ [0, 160],+ [-96, 128],+ [-128, 96],+ ]) {+ time += 16;+ h.finger(2).move(100 + dx, 100 + dy, time);+ }+ expect(Math.abs(pinch.velocity)).toBeLessThan(spreading * 0.25);+ });+});diff --git a/packages/core/src/gestures/__tests__/ScreenEdgePanGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/ScreenEdgePanGestureRecognizer.test.tsnew file mode 100644index 0000000000..720786064a--- /dev/null+++ b/packages/core/src/gestures/__tests__/ScreenEdgePanGestureRecognizer.test.ts@@ -0,0 +1,498 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ScreenEdgePanGestureRecognizer.test.ts+ * @input Synthetic touches with explicit timestamps through a GestureArena+ * @output ScreenEdgePanGestureRecognizer's state machine (the edge band, RTL edges, inward movement) and its edge-zone touch-action+ * @position Unit tests of packages/core/src/gestures/ScreenEdgePanGestureRecognizer.ts+ */++import {describe, expect, it} from 'vitest';+import {UIKIT_SCREEN_EDGE_PAN} from '../../motion/uikit/gestures';+import {ALL_NATIVE_TOUCH} from '../GestureRecognizer';+import {ScreenEdgePanGestureRecognizer} from '../ScreenEdgePanGestureRecognizer';+import {createHarness} from './harness';++describe('ScreenEdgePanGestureRecognizer', () => {+ it('begins from the leading band and fails elsewhere at touch-down', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.finger(1)+ .down(10, 300, 0, {recognizers: [edge]})+ .drag(40, 4, 50);+ expect(h.log[0]).toMatch(/^edge:began@/);+ expect(edge.activeEdge).toBe('left');++ const middle = createHarness();+ const miss = new ScreenEdgePanGestureRecognizer({name: 'miss'});+ middle.finger(1).down(60, 300, 0, {recognizers: [miss]});+ expect(middle.log).toEqual(['miss:failed@0']);+ });++ it("is a finger's only: a mouse or a pen dragging from the band never begins it, even when the options list them (spec:AST-094 FR43)", () => {+ for (const pointerType of ['mouse', 'pen'] as const) {+ const h = createHarness();+ const options = {+ name: 'edge',+ allowedPointerTypes: ['touch', 'mouse', 'pen'],+ } as ConstructorParameters<typeof ScreenEdgePanGestureRecognizer>[0];+ const edge = new ScreenEdgePanGestureRecognizer(options);+ h.finger(1)+ .down(10, 300, 0, {recognizers: [edge], pointerType})+ .drag(40, 4, 50);+ expect(edge.state).toBe('possible');+ expect(h.log).toEqual([]);+ }+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.finger(1)+ .down(10, 300, 0, {recognizers: [edge], pointerType: 'touch'})+ .drag(40, 4, 50);+ expect(h.log[0]).toMatch(/^edge:began@/);+ });++ it('forgets the edge a gesture started from once it ends', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.finger(1)+ .down(10, 300, 0, {recognizers: [edge]})+ .drag(40, 4, 50);+ expect(edge.activeEdge).toBe('left');+ h.finger(1).up(80);+ expect(edge.activeEdge).toBeNull();+ });++ it('resolves the leading edge under RTL and requires inward movement', () => {+ const h = createHarness();+ h.environment.rtl = true;+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.finger(1)+ .down(385, 300, 0, {recognizers: [edge]})+ .drag(-40, 2, 50);+ expect(edge.activeEdge).toBe('right');+ expect(h.log[0]).toMatch(/^edge:began@/);++ const outward = createHarness();+ const back = new ScreenEdgePanGestureRecognizer({name: 'back'});+ outward+ .finger(1)+ .down(10, 300, 0, {recognizers: [back]})+ .drag(-8, 30, 50);+ expect(back.state).toBe('failed');+ });++ it('a drag 5 pt inward and then down the edge is the page\u2019s scroll: it fails and claims nothing (spec:AST-094 FR19)', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.finger(1)+ .down(10, 300, 0, {recognizers: [edge]})+ .drag(5, 0, 30)+ .drag(0, 20, 50);+ expect(edge.state).toBe('failed');+ expect(h.claims).toEqual([]);+ });++ it('leaves a view wider than the edge zone every touch behavior, so its scrolling is untouched (spec:AST-094 FR18)', () => {+ expect(new ScreenEdgePanGestureRecognizer().nativeTouchBehavior).toEqual(+ ALL_NATIVE_TOUCH,+ );+ const page = new ScreenEdgePanGestureRecognizer();+ page.view = viewOfSize(390, 844);+ expect(page.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ // A pan from several edges too, off their zones.+ expect(+ new ScreenEdgePanGestureRecognizer({edges: ['leading', 'trailing']})+ .nativeTouchBehavior,+ ).toEqual(ALL_NATIVE_TOUCH);+ });++ it('takes the axis across its edge in the edge zone, a view no wider than the edge region (spec:AST-094 FR18)', () => {+ const leading = new ScreenEdgePanGestureRecognizer();+ leading.view = viewOfSize(leading.edgeRegion, 844);+ expect(leading.nativeTouchBehavior).toEqual({+ panX: false,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: false,+ });+ // One pixel wider than the band is not the edge zone.+ const wide = new ScreenEdgePanGestureRecognizer();+ wide.view = viewOfSize(wide.edgeRegion + 1, 844);+ expect(wide.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ });++ it('takes a strip authored at the edge region as the edge zone though layout lays it out at 40.203 px', () => {+ const strip = new ScreenEdgePanGestureRecognizer();+ // 40.2 px snapped to layout's 1/64 px.+ strip.view = viewOfSize(Math.ceil(strip.edgeRegion * 64) / 64, 844);+ expect(strip.nativeTouchBehavior).toEqual({+ panX: false,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: false,+ });+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.environment.view = {width: 40.203, height: 844};+ const hysteresis = UIKIT_SCREEN_EDGE_PAN.hysteresis.value;+ h.finger(1)+ .down(10, 300, 0, {recognizers: [edge]})+ .drag(hysteresis - 1, 0, 30);+ expect(edge.state).toBe('possible');+ h.finger(1).drag(2, 0, 50);+ expect(h.log[0]).toMatch(/^edge:began@/);+ });++ it('in the edge zone, still decides at its hysteresis', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.environment.view = {width: edge.edgeRegion, height: 844};+ const hysteresis = UIKIT_SCREEN_EDGE_PAN.hysteresis.value;+ h.finger(1)+ .down(10, 300, 0, {recognizers: [edge]})+ .drag(hysteresis - 1, 0, 30);+ expect(edge.state).toBe('possible');+ h.finger(1).drag(2, 0, 50);+ expect(h.log[0]).toMatch(/^edge:began@/);+ });+});++describe('where an in-band touch decides (spec:AST-094 FR18, DEC-22)', () => {+ it('on an element that reaches beyond the band, at 10 px, before the browser commits to a scroll', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ // A stack container: as wide as the screen, the touch 4 px from its edge.+ h.environment.view = {width: 390, height: 844};+ h.finger(1)+ .down(4, 300, 0, {recognizers: [edge]})+ .drag(9, 0, 30, 9);+ expect(edge.state).toBe('possible');+ h.finger(1).drag(1, 0, 10, 1);+ expect(h.log[0]).toMatch(/^edge:began@/);+ });++ it('on an element within the band, at 15 px', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ h.environment.view = {width: edge.edgeRegion, height: 844};+ const hysteresis = UIKIT_SCREEN_EDGE_PAN.hysteresis.value;+ h.finger(1)+ .down(4, 300, 0, {recognizers: [edge]})+ .drag(hysteresis - 1, 0, 30, 14);+ expect(edge.state).toBe('possible');+ h.finger(1).drag(1, 0, 10, 1);+ expect(h.log[0]).toMatch(/^edge:began@/);+ });++ it('from several edges, at 10 px on an element beyond their bands', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({+ name: 'edge',+ edges: ['leading', 'trailing'],+ });+ h.environment.view = {width: 390, height: 844};+ h.finger(1)+ .down(4, 300, 0, {recognizers: [edge]})+ .drag(9, 0, 30, 9);+ expect(edge.state).toBe('possible');+ h.finger(1).drag(1, 0, 10, 1);+ expect(h.log[0]).toMatch(/^edge:began@/);+ });+});++describe('a pan from both edges (spec:AST-094 FR18)', () => {+ it('outside every edge zone leaves the browser every touch behavior', () => {+ const edge = new ScreenEdgePanGestureRecognizer({+ edges: ['leading', 'trailing'],+ });+ edge.view = viewOfSize(390, 844);+ expect(edge.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ });++ it('inside either edge zone claims pan-x only', () => {+ const leading = new ScreenEdgePanGestureRecognizer({+ edges: ['leading', 'trailing'],+ });+ leading.view = viewOfSize(leading.edgeRegion, 844);+ const trailing = new ScreenEdgePanGestureRecognizer({+ edges: ['leading', 'trailing'],+ });+ trailing.view = viewAt(window.innerWidth - 20, 20, 844);+ for (const edge of [leading, trailing]) {+ expect(edge.nativeTouchBehavior).toEqual({+ panX: false,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: false,+ });+ }+ });+});++describe('the edge zone (spec:AST-094 FR18, FR19, DEC-22)', () => {+ it('is a view that lies within the band at its edge, not merely a thin one', () => {+ const claim = {+ panX: false,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: false,+ };+ // Thin, but in the middle of the screen.+ const middle = new ScreenEdgePanGestureRecognizer();+ middle.view = viewAt(200, 20, 844);+ expect(middle.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ // Thin and at the leading edge.+ const atLeading = new ScreenEdgePanGestureRecognizer();+ atLeading.view = viewAt(0, 20, 844);+ expect(atLeading.nativeTouchBehavior).toEqual(claim);+ // At the trailing edge, for a trailing pan only.+ const trailing = new ScreenEdgePanGestureRecognizer({edges: ['trailing']});+ trailing.view = viewAt(window.innerWidth - 20, 20, 844);+ expect(trailing.nativeTouchBehavior).toEqual(claim);+ const wrongEdge = new ScreenEdgePanGestureRecognizer({edges: ['trailing']});+ wrongEdge.view = viewAt(0, 20, 844);+ expect(wrongEdge.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ });++ it('is measured once for both touch-action and the touch-down decision, and again on a layout change, which says so', () => {+ const h = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ let changes = 0;+ edge.onTouchBehaviorChange = () => {+ changes += 1;+ };+ const hysteresis = UIKIT_SCREEN_EDGE_PAN.hysteresis.value;+ h.environment.view = {left: 0, top: 0, width: edge.edgeRegion, height: 844};+ h.finger(1)+ .down(4, 300, 0, {recognizers: [edge]})+ .drag(hysteresis - 1, 0, 30, hysteresis - 1);+ expect(edge.state).toBe('possible');+ h.finger(1).up(40);+ expect(edge.nativeTouchBehavior.panX).toBe(false);+ // The view grows with no layout change reported: touch-action and the+ // next touch-down still share the answer in force.+ h.environment.view = {left: 0, top: 0, width: 390, height: 844};+ expect(edge.nativeTouchBehavior.panX).toBe(false);+ h.finger(2)+ .down(4, 300, 100, {recognizers: [edge]})+ .drag(hysteresis - 1, 0, 30, hysteresis - 1);+ expect(edge.state).toBe('possible');+ h.finger(2).up(140);+ expect(changes).toBe(0);+ // Reported: measured again, the change is announced, and both follow.+ edge.layoutChanged();+ expect(changes).toBe(1);+ expect(edge.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ h.finger(3)+ .down(4, 300, 200, {recognizers: [edge]})+ .drag(9, 0, 30, 9);+ expect(edge.state).toBe('possible');+ h.finger(3).drag(1, 0, 10, 1);+ expect(edge.state).toBe('began');+ // A layout change that leaves the answer as it was says nothing.+ edge.layoutChanged();+ expect(changes).toBe(1);+ });+});++describe('what the host watches for the edge zone (spec:AST-094 FR19, FR24)', () => {+ it('needs the viewport only for a pan that watches the right side, whose band moves with it', () => {+ const cases: [+ ReadonlyArray<'leading' | 'trailing'>,+ 'ltr' | 'rtl',+ boolean,+ ][] = [+ [['leading'], 'ltr', false],+ [['trailing'], 'ltr', true],+ [['leading'], 'rtl', true],+ [['trailing'], 'rtl', false],+ [['leading', 'trailing'], 'ltr', true],+ ];+ for (const [edges, direction, expected] of cases) {+ const pan = new ScreenEdgePanGestureRecognizer({edges});+ pan.view = viewAt(0, 20, 844, direction);+ expect([edges.join('+'), direction, pan.watchesViewport]).toEqual([+ edges.join('+'),+ direction,+ expected,+ ]);+ }+ });+});++describe('a writing direction switched in place (design:bidirectionality DR13)', () => {+ it('measures its edges again at touch-down when the view turns RTL with no resize, and announces the change', () => {+ const width = window.innerWidth;+ const h = createHarness();+ h.environment.width = width;+ h.environment.view = {left: 0, top: 0, width, height: 844};+ const pan = new ScreenEdgePanGestureRecognizer({+ name: 'edge',+ edges: ['leading'],+ });+ const view = viewAt(0, width, 844, 'ltr');+ pan.view = view;+ let announced = 0;+ pan.onTouchBehaviorChange = () => {+ announced += 1;+ };+ // Measured under LTR: the leading edge is the left one, so a touch in+ // the right band fails at once.+ expect(pan.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ h.finger(1)+ .down(width - 4, 300, 0, {recognizers: [pan]})+ .drag(-20, 0, 40);+ expect(h.log.some(line => line.startsWith('edge:began'))).toBe(false);+ h.finger(1).up(60);+ expect(announced).toBe(0);+ // The page turns RTL in place: no resize, so no layout report.+ view.style.direction = 'rtl';+ h.environment.rtl = true;+ const before = h.log.length;+ h.finger(2)+ .down(width - 4, 300, 200, {recognizers: [pan]})+ .drag(-20, 0, 40);+ expect(+ h.log.slice(before).some(line => line.startsWith('edge:began')),+ ).toBe(true);+ expect(pan.activeEdge).toBe('right');+ expect(announced).toBe(1);+ h.finger(2).up(260);+ });++ it("decides the touch that measures again at FR19's 10 px when the touch-action in force left the browser the axis, and the next at UIKit's 15 px (spec:AST-094 FR19)", () => {+ const width = window.innerWidth;+ const h = createHarness();+ h.environment.width = width;+ const pan = new ScreenEdgePanGestureRecognizer({+ name: 'edge',+ edges: ['leading'],+ });+ const region = pan.edgeRegion;+ // A strip at the right edge: under LTR the leading edge is the left one,+ // so the strip is out of the zone and its touch-action leaves the+ // browser pan-x.+ const view = viewAt(width - region, region, 844, 'ltr');+ pan.view = view;+ h.environment.view = {+ left: width - region,+ top: 0,+ width: region,+ height: 844,+ };+ expect(pan.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ // The page turns RTL in place: the strip is in the leading band now.+ view.style.direction = 'rtl';+ h.environment.rtl = true;+ // This touch landed under the touch-action from before the switch, with+ // pan-x the browser's: it decides at 10 px, before the browser commits.+ h.finger(1)+ .down(width - 4, 300, 0, {recognizers: [pan]})+ .drag(-9, 0, 30, 9);+ expect(pan.state).toBe('possible');+ h.finger(1).drag(-1, 0, 10, 1);+ expect(pan.state).toBe('began');+ h.finger(1).up(60);+ // The change was announced, so the next touch lands under pan-x+ // claimed: UIKit's 15 px.+ expect(pan.nativeTouchBehavior.panX).toBe(false);+ const hysteresis = UIKIT_SCREEN_EDGE_PAN.hysteresis.value;+ h.finger(2)+ .down(width - 4, 300, 200, {recognizers: [pan]})+ .drag(-(hysteresis - 1), 0, 30, hysteresis - 1);+ expect(pan.state).toBe('possible');+ h.finger(2).drag(-1, 0, 10, 1);+ expect(pan.state).toBe('began');+ h.finger(2).up(260);+ });+});++describe('each writing direction and edge, before a touch, at touch-down and after a resize (spec:AST-094 FR18, FR19, DEC-13, DEC-22)', () => {+ const claim = {+ panX: false,+ panY: true,+ pinchZoom: true,+ doubleTapZoom: false,+ };+ const hysteresis = UIKIT_SCREEN_EDGE_PAN.hysteresis.value;+ for (const rtl of [false, true]) {+ for (const edge of ['leading', 'trailing'] as const) {+ const physical = (edge === 'leading') !== rtl ? 'left' : 'right';+ it(`${rtl ? 'RTL' : 'LTR'} ${edge}, the ${physical} edge: touch-action and the touch-down decision agree`, () => {+ const width = window.innerWidth;+ const h = createHarness();+ h.environment.rtl = rtl;+ h.environment.width = width;+ const left = physical === 'left' ? 0 : width - 20;+ h.environment.view = {left, top: 0, width: 20, height: 844};+ const pan = new ScreenEdgePanGestureRecognizer({+ name: 'edge',+ edges: [edge],+ });+ // The element a host gives it, laid out with its own direction.+ pan.view = viewAt(left, 20, 844, rtl ? 'rtl' : 'ltr');+ // Before any touch, as the host derives touch-action: pan-x is taken.+ expect(pan.nativeTouchBehavior).toEqual(claim);+ // At touch-down, a touch in that band decides at 15 px, as the claim+ // allows.+ const x = physical === 'left' ? 4 : width - 4;+ const inward = physical === 'left' ? 1 : -1;+ h.finger(1)+ .down(x, 300, 0, {recognizers: [pan]})+ .drag(inward * (hysteresis - 1), 0, 30, hysteresis - 1);+ expect(pan.state).toBe('possible');+ h.finger(1).drag(inward * 2, 0, 20, 2);+ expect(['began', 'changed']).toContain(pan.state);+ h.finger(1).up(80);+ // After a resize past the band: no claim, and the next touch decides+ // at 10 px.+ h.environment.view = {left: 0, top: 0, width, height: 844};+ pan.view = viewAt(0, width, 844, rtl ? 'rtl' : 'ltr');+ pan.layoutChanged();+ expect(pan.nativeTouchBehavior).toEqual(ALL_NATIVE_TOUCH);+ h.finger(2)+ .down(x, 300, 200, {recognizers: [pan]})+ .drag(inward * 9, 0, 30, 9);+ expect(pan.state).toBe('possible');+ h.finger(2).drag(inward, 0, 10, 1);+ expect(['began', 'changed']).toContain(pan.state);+ h.finger(2).up(280);+ });+ }+ }+});++/** An element whose box has `width` × `height`, as layout would give it. */+function viewOfSize(width: number, height: number): HTMLElement {+ const view = document.createElement('div');+ view.getBoundingClientRect = () =>+ ({width, height, top: 0, left: 0, right: width, bottom: height}) as DOMRect;+ return view;+}++/**+ * An element whose box starts `left` px from the viewport's left edge, in+ * the document with the writing direction given.+ */+function viewAt(+ left: number,+ width: number,+ height: number,+ direction: 'ltr' | 'rtl' = 'ltr',+): HTMLElement {+ const view = document.createElement('div');+ view.style.direction = direction;+ document.body.append(view);+ view.getBoundingClientRect = () =>+ ({+ width,+ height,+ top: 0,+ left,+ right: left + width,+ bottom: height,+ x: left,+ y: 0,+ }) as DOMRect;+ return view;+}diff --git a/packages/core/src/gestures/__tests__/SwipeGestureRecognizer.test.ts b/packages/core/src/gestures/__tests__/SwipeGestureRecognizer.test.tsnew file mode 100644index 0000000000..d195d7d2e2--- /dev/null+++ b/packages/core/src/gestures/__tests__/SwipeGestureRecognizer.test.ts@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SwipeGestureRecognizer.test.ts+ * @input Synthetic touches with explicit timestamps through a GestureArena+ * @output SwipeGestureRecognizer's state machine: recognition during the motion, and failure when too slow, off-axis or the wrong way+ * @position Unit tests of packages/core/src/gestures/SwipeGestureRecognizer.ts+ */++import {describe, expect, it} from 'vitest';+import {SwipeGestureRecognizer} from '../SwipeGestureRecognizer';+import {createHarness} from './harness';++describe('SwipeGestureRecognizer', () => {+ it('is recognized during the motion, once the distance is covered', () => {+ const h = createHarness();+ const swipe = new SwipeGestureRecognizer({name: 'swipe'});+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [swipe]});+ finger.move(30, 2, 30);+ expect(swipe.state).toBe('possible');+ finger.move(50, 4, 50);+ expect(swipe.recognizedDirection).toBe('right');+ expect(h.log[0]).toBe('swipe:ended@50');+ });++ it('fails when too slow, off-axis, or the wrong way', () => {+ const slow = createHarness();+ const a = new SwipeGestureRecognizer({name: 'a'});+ slow+ .finger(1)+ .down(0, 0, 0, {recognizers: [a]})+ .move(30, 0, 400);+ slow.advance(500);+ expect(a.state).toBe('failed');++ const diagonal = createHarness();+ const b = new SwipeGestureRecognizer({name: 'b'});+ diagonal+ .finger(1)+ .down(0, 0, 0, {recognizers: [b]})+ .move(45, 55, 60);+ // 55 px across is past the 50 px secondary allowance.+ expect(b.state).toBe('failed');++ const wrong = createHarness();+ const c = new SwipeGestureRecognizer({name: 'c', direction: 'left'});+ wrong+ .finger(1)+ .down(100, 0, 0, {recognizers: [c]})+ .move(160, 0, 60);+ expect(c.state).toBe('failed');+ });++ it('takes several directions and fingers', () => {+ const h = createHarness();+ const swipe = new SwipeGestureRecognizer({+ name: 'swipe',+ direction: ['up', 'down'],+ numberOfTouchesRequired: 2,+ });+ h.finger(1).down(0, 200, 0, {recognizers: [swipe]});+ h.finger(2).down(40, 200, 5, {recognizers: [swipe]});+ h.finger(1).move(0, 140, 50);+ h.finger(2).move(40, 140, 50);+ expect(swipe.recognizedDirection).toBe('up');+ });++ it('gives the same verdict for the same path however its events are spaced', () => {+ // A straight drag to (55, 40): along 55 past the 50 px distance, 40 px+ // across within the 50 px allowance.+ const sparse = createHarness();+ const a = new SwipeGestureRecognizer({name: 'a'});+ sparse+ .finger(1)+ .down(0, 0, 0, {recognizers: [a]})+ .move(55, 40, 40);+ expect(a.state).toBe('ended');++ const dense = createHarness();+ const b = new SwipeGestureRecognizer({name: 'b'});+ const finger = dense.finger(1).down(0, 0, 0, {recognizers: [b]});+ for (let step = 1; step <= 10; step += 1) {+ finger.move(5.5 * step, 4 * step, 4 * step);+ }+ expect(b.state).toBe('ended');+ expect(b.recognizedDirection).toBe('right');+ });++ it('recognizes a 40\u00b0 swipe at 16 px per event as at small steps', () => {+ // At 40\u00b0 the travel along reaches 50 px with 42 px across, inside+ // the 50 px allowance; at 16 px per event the next event is already 51 px+ // across, so the verdict must come from the path between the events.+ const angle = (40 * Math.PI) / 180;+ for (const step of [2, 16]) {+ const h = createHarness();+ const swipe = new SwipeGestureRecognizer({name: 'swipe'});+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [swipe]});+ for (let d = step, t = 4; d <= 96; d += step, t += 4) {+ finger.move(d * Math.cos(angle), d * Math.sin(angle), t);+ if (swipe.state !== 'possible') {+ break;+ }+ }+ expect(swipe.state).toBe('ended');+ expect(swipe.recognizedDirection).toBe('right');+ }+ });+});diff --git a/packages/core/src/gestures/__tests__/arenaPinchSwipeEdge.test.ts b/packages/core/src/gestures/__tests__/arenaPinchSwipeEdge.test.tsnew file mode 100644index 0000000000..54829fb2ae--- /dev/null+++ b/packages/core/src/gestures/__tests__/arenaPinchSwipeEdge.test.ts@@ -0,0 +1,188 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file arenaPinchSwipeEdge.test.ts+ * @input GestureArena with pinches, swipes, edge pans and pans, driven by+ * synthetic touches with explicit timestamps+ * @output Simultaneous recognition (pinch + pan), the first to recognize+ * winning without permission, edge pan vs inner pan, swipe vs pan, and a+ * delayed touch delivery+ * @position Unit tests of packages/core/src/gestures/GestureArena.ts+ */++import {describe, expect, it} from 'vitest';+import {UIKIT_PINCH, UIKIT_SWIPE} from '../../motion/uikit/gestures';+import {GestureRecognizer} from '../GestureRecognizer';+import {PanGestureRecognizer} from '../PanGestureRecognizer';+import {PinchGestureRecognizer} from '../PinchGestureRecognizer';+import {ScreenEdgePanGestureRecognizer} from '../ScreenEdgePanGestureRecognizer';+import {SwipeGestureRecognizer} from '../SwipeGestureRecognizer';+import {createHarness, RecordingConsumer} from './harness';++/**+ * A recognizer that stays possible, even past its finger's lift, until the+ * test fails it: something another recognizer can wait on.+ */+class Held extends GestureRecognizer {+ private isWaiting = true;++ override isInvolved(): boolean {+ return super.isInvolved() || this.isWaiting;+ }++ fail(): void {+ this.isWaiting = false;+ this.setState('failed');+ }+}++describe('conflict matrix', () => {+ it('pinch + pan recognize simultaneously when allowed', () => {+ const h = createHarness();+ const pinch = new PinchGestureRecognizer({name: 'pinch'});+ const pan = new PanGestureRecognizer({name: 'pan'});+ pinch.recognizeSimultaneouslyWith(pan);+ h.finger(1).down(100, 100, 0, {recognizers: [pinch, pan]});+ h.finger(2).down(200, 100, 0, {recognizers: [pinch, pan]});+ h.finger(1).move(80, 120, 16);+ h.finger(2).move(240, 120, 16);+ expect(h.log.slice(0, 2)).toEqual(['pinch:began@16', 'pan:began@16']);+ // Span 100 -> 160, measured against 100 + 8.+ expect(pinch.scale).toBeCloseTo(160 / 108, 5);+ // The pan began at the first finger's move, centroid (-10, 10), which+ // the hysteresis swallows; the second finger's move brought it to (10, 20).+ expect(pan.translation()).toEqual({x: 20, y: 10});+ });++ it('pinch vs pan without permission: the first to recognize wins', () => {+ const h = createHarness();+ const pinch = new PinchGestureRecognizer({name: 'pinch'});+ const pan = new PanGestureRecognizer({name: 'pan'});+ h.finger(1).down(100, 100, 0, {recognizers: [pinch, pan]});+ h.finger(2).down(200, 100, 0, {recognizers: [pinch, pan]});+ h.finger(1).move(80, 120, 16);+ h.finger(2).move(240, 120, 16);+ expect(h.log.slice(0, 2)).toEqual(['pinch:began@16', 'pan:failed@16']);+ });++ it('edge pan vs inner pan: in the band the edge pan wins, elsewhere the inner pan runs undelayed', () => {+ const band = createHarness();+ const edge = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ const inner = new PanGestureRecognizer({+ name: 'inner',+ direction: 'horizontal',+ });+ inner.requireToFail(edge);+ // A thin edge view: the edge zone, where the pan takes its axis.+ band.environment.view = {width: edge.edgeRegion, height: 844};+ band.finger(1).down(8, 300, 0, {recognizers: [inner, edge]});+ band.finger(1).drag(60, 2, 60, 6);+ // The edge pan's own hysteresis is 15 px: the second 10 px step.+ expect(band.log.slice(0, 2)).toEqual(['edge:began@20', 'inner:failed@20']);++ const middle = createHarness();+ const edge2 = new ScreenEdgePanGestureRecognizer({name: 'edge'});+ const inner2 = new PanGestureRecognizer({+ name: 'inner',+ direction: 'horizontal',+ });+ inner2.requireToFail(edge2);+ middle.finger(1).down(150, 300, 0, {recognizers: [inner2, edge2]});+ // Failed at touch-down, before any movement: nothing waits on it.+ expect(middle.log).toEqual(['edge:failed@0']);+ middle.finger(1).drag(60, 2, 60, 6);+ expect(middle.log[1]).toBe('inner:began@10');+ });++ it('swipe vs pan: the pan wins by default, the swipe when the pan requires it to fail', () => {+ const plain = createHarness();+ const swipe = new SwipeGestureRecognizer({name: 'swipe'});+ const pan = new PanGestureRecognizer({name: 'pan'});+ plain+ .finger(1)+ .down(0, 0, 0, {recognizers: [swipe, pan]})+ .drag(80, 0, 60, 6);+ expect(plain.log.slice(0, 2)).toEqual(['pan:began@10', 'swipe:failed@10']);++ const ordered = createHarness();+ const swipe2 = new SwipeGestureRecognizer({name: 'swipe'});+ const pan2 = new PanGestureRecognizer({name: 'pan'});+ pan2.requireToFail(swipe2);+ ordered+ .finger(1)+ .down(0, 0, 0, {recognizers: [swipe2, pan2]})+ .drag(80, 0, 60, 8);+ expect(ordered.log.slice(0, 2)).toEqual([+ 'swipe:[email protected]',+ 'pan:[email protected]',+ ]);++ const slow = createHarness();+ const swipe3 = new SwipeGestureRecognizer({name: 'swipe'});+ const pan3 = new PanGestureRecognizer({name: 'pan'});+ pan3.requireToFail(swipe3);+ slow+ .finger(1)+ .down(0, 0, 0, {recognizers: [swipe3, pan3]})+ .drag(30, 0, 300, 3);+ expect(pan3.state).toBe('possible');+ slow.advance(500);+ // The swipe ran out of time; the waiting pan begins with what it has.+ expect(slow.log.slice(0, 2)).toEqual(['swipe:failed@500', 'pan:began@500']);+ });+});++describe('a recognizer waiting on another', () => {+ it('a swipe holds its recognition past its lift and its deadline (spec:AST-094 FR15)', () => {+ const h = createHarness();+ const held = new Held({name: 'held'});+ const swipe = new SwipeGestureRecognizer({name: 'swipe'});+ swipe.requireToFail(held);+ h.finger(1)+ .down(0, 0, 0, {recognizers: [swipe, held]})+ .drag(80, 0, 60, 8)+ .up(70);+ h.advance(UIKIT_SWIPE.maximumDuration.value + 100);+ expect(swipe.state).toBe('possible');+ expect(h.log.some(entry => entry.startsWith('swipe:failed'))).toBe(false);+ held.fail();+ expect(h.log).toContain(+ `swipe:ended@${UIKIT_SWIPE.maximumDuration.value + 100}`,+ );+ expect(swipe.recognizedDirection).toBe('right');+ });++ it('a pinch keeps its start once it passes the hysteresis, so it begins at the scale its fingers show (spec:AST-094 FR15)', () => {+ const h = createHarness();+ const held = new Held({name: 'held'});+ const pinch = new PinchGestureRecognizer({name: 'pinch'});+ pinch.requireToFail(held);+ h.finger(1).down(100, 100, 0, {recognizers: [pinch, held]});+ h.finger(2).down(200, 100, 0, {recognizers: [pinch, held]});+ // Span 100 -> 120 -> 140 -> 160 while the pinch waits.+ h.finger(2).move(220, 100, 16);+ h.finger(2).move(240, 100, 32);+ h.finger(2).move(260, 100, 48);+ expect(pinch.state).toBe('possible');+ held.fail();+ expect(h.log).toContain('pinch:began@48');+ // Measured against 100 + 8 once, not re-based on every move.+ const hysteresis = UIKIT_PINCH.hysteresis.value;+ expect(pinch.scale).toBeCloseTo(160 / (100 + hysteresis), 5);+ });+});++describe('delivery to the view', () => {+ it('holds the began with delaysTouchesBegan until the recognizer fails', () => {+ const h = createHarness();+ const consumer = new RecordingConsumer();+ const swipe = new SwipeGestureRecognizer({+ name: 'swipe',+ delaysTouchesBegan: true,+ });+ h.finger(1).down(0, 0, 0, {recognizers: [swipe], consumer});+ expect(consumer.events).toEqual([]);+ h.advance(UIKIT_SWIPE.maximumDuration.value);+ expect(consumer.events).toEqual(['began:1']);+ });+});diff --git a/packages/core/src/gestures/__tests__/harness.ts b/packages/core/src/gestures/__tests__/harness.tsindex a54549412f..bf339255cd 100644--- a/packages/core/src/gestures/__tests__/harness.ts+++ b/packages/core/src/gestures/__tests__/harness.ts@@ -40,7 +40,13 @@ export interface Harness {claims: number[];/** Deferred clicks as they resolved. */deferredClicks: {id: number; allowed: boolean; time: number}[];- environment: {width: number; height: number; rtl: boolean};+ environment: {+ width: number;+ height: number;+ rtl: boolean;+ /** The box every recognizer's view measures, when a test sets one. */+ view?: {left?: number; top?: number; width: number; height: number};+ };finger(id: number): Finger;/** Advance the clock and run every timer due by `time`. */advance(time: number): void;@@ -51,7 +57,11 @@ export function createHarness(): Harness {const log: string[] = [];const claims: number[] = [];const deferredClicks: Harness['deferredClicks'] = [];- const environment = {width: 390, height: 844, rtl: false};+ const environment: Harness['environment'] = {+ width: 390,+ height: 844,+ rtl: false,+ };const fingers = new Map<number, Finger>();const env: GestureEnvironment = {viewportSize: () => ({@@ -59,6 +69,15 @@ export function createHarness(): Harness {height: environment.height,}),isRtl: () => environment.rtl,+ viewRect: () =>+ environment.view == null+ ? null+ : {+ left: environment.view.left ?? 0,+ top: environment.view.top ?? 0,+ width: environment.view.width,+ height: environment.view.height,+ },};const arena: GestureArena = new GestureArena({clock,diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.tsindex 09d0dd0eca..975989d0a3 100644--- a/packages/core/src/gestures/types.ts+++ b/packages/core/src/gestures/types.ts@@ -46,13 +46,6 @@ export interface NativeScrollProbe {* 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 reader place the point where the content runs 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;/**@@ -127,6 +120,17 @@ export interface GestureEventContext {export interface GestureEnvironment {viewportSize(): {readonly width: number; readonly height: number};isRtl(view: unknown): boolean;+ /**+ * The box of a recognizer's view in viewport coordinates, or null when it+ * has none to measure. A screen-edge pan reads it to tell a view within+ * its edge band from any other.+ */+ viewRect?(view: unknown): {+ readonly left: number;+ readonly top: number;+ readonly width: number;+ readonly height: number;+ } | null;}export const DEFAULT_ENVIRONMENT: GestureEnvironment = {@@ -136,8 +140,18 @@ export const DEFAULT_ENVIRONMENT: GestureEnvironment = {}return {width: window.innerWidth, height: window.innerHeight};},- isRtl() {- return false;+ isRtl(view) {+ if (typeof window === 'undefined' || !(view instanceof Element)) {+ return false;+ }+ return window.getComputedStyle(view).direction === 'rtl';+ },+ viewRect(view) {+ if (typeof Element === 'undefined' || !(view instanceof Element)) {+ return null;+ }+ const {left, top, width, height} = view.getBoundingClientRect();+ return {left, top, width, height};},};