Skip to content

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

TypeScript

feat(core): the internal touch foundation: press tracking and the animator (#8076)

Christopher Chedeau5dd4d2691441
diff --git a/.changeset/gesture-arena-moving-cancel.md b/.changeset/gesture-arena-moving-cancel.md
new file mode 100644
index 0000000000..5b7e52cad1
--- /dev/null
+++ b/.changeset/gesture-arena-moving-cancel.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a gesture that cancels itself on a finger's move (a long press dragged past its tolerance) keeps that finger claimed until it lifts, so the page never takes the drag over midway; a resting finger is still given back when its gesture is cancelled. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-press-tracking.md b/.changeset/gesture-press-tracking.md
new file mode 100644
index 0000000000..e964301a57
--- /dev/null
+++ b/.changeset/gesture-press-tracking.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: UIControl press tracking with control and cell profiles and the gesture hooks. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-readme.md b/.changeset/gesture-readme.md
new file mode 100644
index 0000000000..9a6293b811
--- /dev/null
+++ b/.changeset/gesture-readme.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture system's README for component authors, with its browser proof in Chromium and WebKit.
+
+@vjeux
diff --git a/.changeset/reduced-motion-record.md b/.changeset/reduced-motion-record.md
new file mode 100644
index 0000000000..bd4884f719
--- /dev/null
+++ b/.changeset/reduced-motion-record.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: under Reduce Motion, a call that names the opacity a waiting dip returns to, with no travel, joins that dip instead of fading the element out a second time, and `reducedMotionFade()` resolves the cross-fade's curve as a registered motion role where it plays. Not exported from the package entry point.
+
+@vjeux
diff --git a/packages/core/src/__tests__/internalModulesNotExperimental.test.ts b/packages/core/src/__tests__/internalModulesNotExperimental.test.ts
new file mode 100644
index 0000000000..85fe3a821d
--- /dev/null
+++ b/packages/core/src/__tests__/internalModulesNotExperimental.test.ts
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file internalModulesNotExperimental.test.ts
+ * @input vitest, the source of core's internal motion, gesture and keyboard
+ * modules, and of the package-private utility module (touchPresentation)
+ * @output Fails when one of them declares `@experimental`: those modules are
+ * internal and never exported (spec:AST-017 FR21, DEC-27), and the tag
+ * belongs only to a deliberately experimental public API
+ * @position Testing; a repository guard over src/motion, src/gestures,
+ * src/keyboard and src/utils/touchPresentation.ts. The rest of src/utils
+ * backs the public `@astryxdesign/core/utils` entry, where an experimental
+ * API may carry the tag
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+const SRC = path.resolve(__dirname, '..');
+const INTERNAL_DIRS = ['motion', 'gestures', 'keyboard'];
+/** Package-private files in a directory that also backs a public entry. */
+const INTERNAL_FILES = ['utils/touchPresentation.ts'];
+
+/** Every source file under `dir`, tests and declarations left out. */
+function sourcesUnder(dir: string): string[] {
+ const files: string[] = [];
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name !== '__tests__') {
+ files.push(...sourcesUnder(full));
+ }
+ } else if (
+ /\.(ts|tsx|mjs|js)$/.test(entry.name) &&
+ !/\.(test|spec)\.[cm]?[jt]sx?$/.test(entry.name) &&
+ !entry.name.endsWith('.d.ts')
+ ) {
+ files.push(full);
+ }
+ }
+ return files;
+}
+
+/** The internal files the guard reads, relative to src. */
+function checkedFiles(): string[] {
+ const files: string[] = [];
+ for (const dir of INTERNAL_DIRS) {
+ const root = path.join(SRC, dir);
+ if (fs.existsSync(root)) {
+ files.push(...sourcesUnder(root));
+ }
+ }
+ files.push(...INTERNAL_FILES.map(file => path.join(SRC, file)));
+ return files.map(file => path.relative(SRC, file));
+}
+
+describe('internal modules', () => {
+ it('declare no @experimental: only an experimental public API carries it', () => {
+ const offenders: string[] = [];
+ for (const file of checkedFiles()) {
+ fs.readFileSync(path.join(SRC, file), 'utf8')
+ .split('\n')
+ .forEach((line, index) => {
+ if (/@experimental\b/.test(line)) {
+ offenders.push(`${file}:${index + 1}`);
+ }
+ });
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ it('checks the directories and files it names', () => {
+ expect(fs.existsSync(path.join(SRC, 'motion'))).toBe(true);
+ expect(fs.existsSync(path.join(SRC, 'gestures'))).toBe(true);
+ expect(sourcesUnder(path.join(SRC, 'motion')).length).toBeGreaterThan(5);
+ for (const file of INTERNAL_FILES) {
+ expect(fs.existsSync(path.join(SRC, file)), file).toBe(true);
+ }
+ });
+
+ it('leaves the public utils entry alone: of src/utils, only its package-private files are checked', () => {
+ const utils = checkedFiles().filter(file =>
+ file.startsWith('utils' + path.sep),
+ );
+ expect(utils).toEqual([path.join('utils', 'touchPresentation.ts')]);
+ });
+});
diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts
index 409589f3c5..5691eab56a 100644
--- a/packages/core/src/gestures/GestureArena.ts
+++ b/packages/core/src/gestures/GestureArena.ts
@@ -119,10 +119,15 @@ interface Timer {
callback: () => void;
}
+/**
+ * The arena that decides which recognizer gets a touch.
+ */
export class GestureArena {
readonly environment: GestureEnvironment;
private readonly clock: GestureClock;
private readonly options: GestureArenaOptions;
+ /** The touches whose move the arena is delivering right now. */
+ private movingIds: ReadonlySet<number> = new Set();
private readonly records = new Map<number, TouchRecord>();
/** Recognizers involved in the current interaction, in resolution order. */
private active: GestureRecognizer[] = [];
@@ -134,6 +139,10 @@ export class GestureArena {
/** The latest time processed: input never moves the clock backwards. */
private latestTime = Number.NEGATIVE_INFINITY;
private depth = 0;
+ /** Open `deferResolution` calls: what their stops unblock waits. */
+ private deferDepth = 0;
+ /** A deferred stop left recognitions, held touches or resets to settle. */
+ private owesResolution = false;
constructor(options: GestureArenaOptions = {}) {
this.options = options;
@@ -308,8 +317,14 @@ export class GestureArena {
return;
}
const context = this.context();
- for (const recognizer of [...this.active]) {
- recognizer.deliverMoved(changed, context);
+ const previous = this.movingIds;
+ this.movingIds = new Set(changed.map(touch => touch.id));
+ try {
+ for (const recognizer of [...this.active]) {
+ recognizer.deliverMoved(changed, context);
+ }
+ } finally {
+ this.movingIds = previous;
}
for (const touch of changed) {
const record = this.records.get(touch.id);
@@ -457,12 +472,42 @@ export class GestureArena {
}
/** Cancel an active recognizer, or fail a possible one. */
+ /**
+ * Runs `body`, code outside input that stops recognizers (an Effect that
+ * turns one off or detaches it), without resolving what those stops
+ * unblock: the recognitions waiting on them, the touches they held from a
+ * view, the resets. A pass a microtask later resolves all of it, at the
+ * last event's time, so the listeners and consumers it reaches hear it
+ * outside the caller's frame and read the recognized state
+ * (react-component-runtime INV2).
+ */
+ deferResolution(body: () => void): void {
+ this.deferDepth += 1;
+ try {
+ body();
+ } finally {
+ this.deferDepth -= 1;
+ }
+ if (this.deferDepth === 0 && this.owesResolution) {
+ queueMicrotask(() => {
+ if (this.owesResolution && this.deferDepth === 0) {
+ this.run(this.lastEventTime(), () => {});
+ }
+ });
+ }
+ }
+
+ /** The last event's time, or now before any event. */
+ private lastEventTime(): number {
+ return Number.isFinite(this.latestTime)
+ ? this.latestTime
+ : this.clock.now();
+ }
+
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());
+ const time = this.currentTime ?? this.lastEventTime();
this.run(time, () => {
if (isActive(recognizer.state)) {
this.apply(recognizer, 'cancelled');
@@ -569,6 +614,11 @@ export class GestureArena {
}
recognizer.pending = null;
this.apply(recognizer, 'failed');
+ if (this.deferDepth > 0) {
+ // Inside `deferResolution`, the next pass settles.
+ this.owesResolution = true;
+ return;
+ }
this.reviewPending();
}
@@ -576,12 +626,19 @@ export class GestureArena {
* 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.
+ * them, so a finger still resting there can pinch-zoom the page. A gesture
+ * that cancels itself on a finger's move (a long press past its tolerance)
+ * keeps that finger until it lifts: the drag goes on, and the page never
+ * takes it over midway (`spec:AST-094` FR14), as UIKit's scroll view never
+ * takes a touch another recognizer had.
*/
- private releaseClaim(recognizer: GestureRecognizer): void {
+ private releaseClaim(
+ recognizer: GestureRecognizer,
+ keep: ReadonlySet<number> = new Set(),
+ ): void {
for (const touch of recognizer.trackedTouches) {
const record = this.records.get(touch.id);
- if (record == null || !record.isClaimed) {
+ if (record == null || !record.isClaimed || keep.has(touch.id)) {
continue;
}
// A recognized discrete gesture (`ended`, a swipe) still owns its
@@ -612,7 +669,9 @@ export class GestureArena {
if (isTerminal(next)) {
this.clearTimer(recognizer);
}
- if (next === 'cancelled' || next === 'failed') {
+ if (next === 'cancelled') {
+ this.releaseClaim(recognizer, this.movingIds);
+ } else if (next === 'failed') {
this.releaseClaim(recognizer);
}
}
@@ -870,9 +929,15 @@ export class GestureArena {
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.
+ // would reset recognizers that have not heard the event yet. Inside
+ // `deferResolution`, the next pass settles.
if (this.depth === 1) {
- this.settle();
+ if (this.deferDepth > 0) {
+ this.owesResolution = true;
+ } else {
+ this.owesResolution = false;
+ this.settle();
+ }
}
} finally {
this.depth -= 1;
diff --git a/packages/core/src/gestures/GestureRecognizer.ts b/packages/core/src/gestures/GestureRecognizer.ts
index 80f8651133..af9b0a617b 100644
--- a/packages/core/src/gestures/GestureRecognizer.ts
+++ b/packages/core/src/gestures/GestureRecognizer.ts
@@ -118,7 +118,9 @@ export function isActive(state: GestureState): boolean {
return state === 'began' || state === 'changed';
}
-/** The browser behaviors `touch-action` can keep or remove. */
+/**
+ * The browser behaviors `touch-action` can keep or remove.
+ */
export interface NativeTouchBehavior {
readonly panX: boolean;
readonly panY: boolean;
diff --git a/packages/core/src/gestures/PressTracker.ts b/packages/core/src/gestures/PressTracker.ts
new file mode 100644
index 0000000000..350aaa1f55
--- /dev/null
+++ b/packages/core/src/gestures/PressTracker.ts
@@ -0,0 +1,386 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file PressTracker.ts
+ * @input Touches the arena delivers to a pressable view (TouchConsumer)
+ * @output Exports createPressTracker and its PressTracker interface
+ * (UIControl's touch tracking, built by a factory per
+ * architecture:react-component-runtime INV13), its options, the
+ * control event type, and PRESS_PROFILES (a control's and a table cell's
+ * tracking and release clock)
+ * @position View-level consumer of packages/core/src/gestures: what a
+ * UIControl does with the touches no gesture recognizer took
+ *
+ * UIControl semantics, event for event:
+ *
+ * - `touchDown` when the finger lands; the highlight comes on in the same
+ * frame, unless the control sits in a scroller, where it waits
+ * `contentTouchDelay` (UIScrollView.delaysContentTouches) so a flick
+ * paints nothing.
+ * - `touchDragInside` / `touchDragOutside` on every move, `touchDragExit` /
+ * `touchDragEnter` when the finger crosses the control's bounds EXPANDED
+ * by `trackingExpansion` (a fingertip dragged a little off a button is
+ * still on it). The highlight follows inside / outside.
+ * - `touchUpInside` / `touchUpOutside` at the lift. A tap quicker than the
+ * scroller delay shows the highlight at the lift for `quickTapFlash`.
+ * - `touchCancel` when a recognizer took the touch (`cancelsTouchesInView`)
+ * or the browser took it to scroll: the highlight goes at once, with no
+ * release, one frame before the content moves.
+ *
+ * Two profiles (PRESS_PROFILES) cover what UIKit does:
+ *
+ * - `control` (a button, a switch): as above.
+ * - `cell` (a table or collection row): the highlight waits the
+ * content-touch delay inside a scroll view and comes on at once outside one
+ * (`spec:AST-094` FR11), travel past the pan hysteresis cancels the press
+ * for good (the scroll view took the touch), and a quicker tap highlights
+ * at the lift straight into the release, with no flash.
+ *
+ * And UIControl's iOS 6 rule: a single-finger single tap recognizer on an
+ * ANCESTOR does not beat the control's own action for a touch on it (the
+ * default veto; `vetoesAncestorRecognizer` replaces it, as a slider vetoes a
+ * pan along its track).
+ *
+ * The bounds are read once, when the finger lands; nothing reads layout
+ * during the press. Activation stays the browser's click, which the arena
+ * swallows for a touch a recognizer took.
+ */
+
+import {UIKIT_GESTURES} from '../motion/uikit/gestures';
+import {timing} from '../motion/uikit/timing';
+import {travel} from './geometry';
+import type {GestureRecognizer} from './GestureRecognizer';
+import type {TapGestureRecognizer} from './TapGestureRecognizer';
+import type {GestureTouch, TouchConsumer} from './types';
+
+export type ControlEvent =
+ | 'touchDown'
+ | 'touchDragInside'
+ | 'touchDragOutside'
+ | 'touchDragEnter'
+ | 'touchDragExit'
+ | 'touchUpInside'
+ | 'touchUpOutside'
+ | 'touchCancel';
+
+export interface PressBounds {
+ readonly left: number;
+ readonly top: number;
+ readonly right: number;
+ readonly bottom: number;
+}
+
+export interface PressTrackerOptions {
+ /** The control's bounds in client px, read when a finger lands. */
+ getBounds: () => PressBounds | null;
+ /** The view the tracker belongs to; recognizers on it are not ancestors. */
+ view?: unknown;
+ onControlEvent?: (event: ControlEvent, touch: GestureTouch) => void;
+ onHighlightChange?: (isHighlighted: boolean) => void;
+ trackingExpansion?: number;
+ /**
+ * When the highlight waits `contentTouchDelay`: inside a scroller (a
+ * control or a cell), always, or never. @default 'inScrollers'
+ */
+ highlightDelay?: PressHighlightDelay;
+ /**
+ * Travel (px) past which the press is cancelled for good, with no
+ * re-highlight on the way back (a cell whose scroll view took the touch).
+ * Unset, the finger is tracked in and out of the expanded bounds.
+ */
+ cancelTravel?: number;
+ /**
+ * How long a tap quicker than the delay shows the highlight at the lift,
+ * ms; 0 highlights and releases at once. @default the quick-tap flash
+ */
+ quickTapFlash?: number;
+ /** Which ancestor recognizers the control's own action beats. */
+ vetoesAncestorRecognizer?: (recognizer: GestureRecognizer) => boolean;
+ /** @default () => true */
+ isEnabled?: () => boolean;
+ /**
+ * Whether this finger is braking a scroll it set moving (see
+ * GestureHost.isScrollBraking): a native list highlights nothing for one,
+ * and the control does not track it at all. Asked only for a finger: a
+ * mouse or a pen never brakes (`spec:AST-094` FR11).
+ */
+ isBraking?: (touch: GestureTouch) => boolean;
+}
+
+const PRESS = UIKIT_GESTURES.press;
+
+export type PressHighlightDelay = 'inScrollers' | 'always' | 'never';
+
+/**
+ * How a kind of pressable tracks a finger and how long its release takes.
+ */
+export interface PressProfile {
+ readonly highlightDelay: PressHighlightDelay;
+ readonly cancelTravel?: number;
+ readonly quickTapFlash: number;
+ /** The release (`fading`) clock a painter uses, ms. */
+ readonly releaseMs: number;
+}
+
+export const PRESS_PROFILES = {
+ /** UIControl: same-frame highlight outside scrollers, 70 pt tracking. */
+ control: {
+ highlightDelay: 'inScrollers',
+ quickTapFlash: PRESS.quickTapFlash.value,
+ // The shared press styles release every surface on the deselect clock
+ // until a control runs its own release (UIButton's 250 ms), so a
+ // painter's `fading` never outlasts the fade it shows.
+ releaseMs: timing.press.highlightOutMs,
+ },
+ /**
+ * A table or collection cell: inside a scroll view it highlights after the
+ * content-touch delay, outside one at once (AST-094 FR11: the delay applies
+ * only inside scroll views); cancelled by the scroll.
+ */
+ cell: {
+ highlightDelay: 'inScrollers',
+ cancelTravel: UIKIT_GESTURES.pan.hysteresis.value,
+ quickTapFlash: 0,
+ releaseMs: timing.press.highlightOutMs,
+ },
+} as const satisfies Record<string, PressProfile>;
+
+export type PressProfileName = keyof typeof PRESS_PROFILES;
+
+/**
+ * UIButton's rule, the tracker's default ancestor veto: an ancestor's
+ * single-finger single tap. A tap is told apart by its `kind`
+ * (`architecture:react-component-runtime` INV13).
+ */
+export function vetoesSingleTap(recognizer: GestureRecognizer): boolean {
+ if (recognizer.kind !== 'tap') {
+ return false;
+ }
+ const tap = recognizer as TapGestureRecognizer;
+ return tap.numberOfTapsRequired === 1 && tap.numberOfTouchesRequired === 1;
+}
+
+/**
+ * A control's touch tracking, the gesture host's consumer for one element
+ * (UIControl's `beginTracking` / `continueTracking` / `endTracking`): it
+ * reports control events and the highlight. Built by
+ * {@link createPressTracker}.
+ */
+export interface PressTracker extends TouchConsumer {
+ /** Whether the control paints its pressed highlight now. */
+ readonly isHighlighted: boolean;
+ /** Whether a touch is being tracked. */
+ readonly isTracking: boolean;
+ /** Whether the tracked touch is inside the bounds plus the expansion. */
+ readonly isTouchInside: boolean;
+ /**
+ * How far past its bounds a tracked touch still counts as inside, px; its
+ * hook keeps it in step with the option.
+ */
+ trackingExpansion: number;
+ /**
+ * Whether the control takes touches now: a disabled one gives the host no
+ * reason to listen (`spec:AST-094` FR24).
+ */
+ isEnabled(): boolean;
+ allowsAncestorRecognizer(recognizer: unknown): boolean;
+ /** Drop any highlight and timers (the control unmounted or was disabled). */
+ dispose(): void;
+}
+
+/** Track a control's touches (see {@link PressTracker}). */
+export function createPressTracker(options: PressTrackerOptions): PressTracker {
+ let touchId: number | null = null;
+ let bounds: PressBounds | null = null;
+ let highlightTimer: ReturnType<typeof setTimeout> | null = null;
+ let flashTimer: ReturnType<typeof setTimeout> | null = null;
+ /** A pending highlight whose finger travelled: it will never paint. */
+ let isPendingDead = false;
+
+ const state = {
+ isHighlighted: false,
+ isTracking: false,
+ isTouchInside: false,
+ };
+ const contains = (touch: GestureTouch): boolean => {
+ if (bounds == null) {
+ return true;
+ }
+ const margin = tracker.trackingExpansion;
+ return (
+ touch.x >= bounds.left - margin &&
+ touch.x <= bounds.right + margin &&
+ touch.y >= bounds.top - margin &&
+ touch.y <= bounds.bottom + margin
+ );
+ };
+
+ const emit = (event: ControlEvent, touch: GestureTouch): void => {
+ options.onControlEvent?.(event, touch);
+ };
+
+ const setHighlighted = (value: boolean): void => {
+ if (state.isHighlighted === value) {
+ return;
+ }
+ state.isHighlighted = value;
+ options.onHighlightChange?.(value);
+ };
+
+ const clearHighlightTimer = (): void => {
+ if (highlightTimer != null) {
+ clearTimeout(highlightTimer);
+ highlightTimer = null;
+ }
+ };
+
+ const clearFlash = (): void => {
+ if (flashTimer != null) {
+ clearTimeout(flashTimer);
+ flashTimer = null;
+ }
+ };
+
+ const finish = (): void => {
+ touchId = null;
+ state.isTracking = false;
+ state.isTouchInside = false;
+ bounds = null;
+ };
+
+ const touchCancelled = (touch: GestureTouch): void => {
+ if (touch.id !== touchId) {
+ return;
+ }
+ clearHighlightTimer();
+ emit('touchCancel', touch);
+ setHighlighted(false);
+ finish();
+ };
+
+ const tracker: PressTracker = {
+ get isHighlighted() {
+ return state.isHighlighted;
+ },
+ get isTracking() {
+ return state.isTracking;
+ },
+ get isTouchInside() {
+ return state.isTouchInside;
+ },
+ trackingExpansion:
+ options.trackingExpansion ??
+ UIKIT_GESTURES.control.trackingExpansion.value,
+
+ isEnabled(): boolean {
+ return options.isEnabled?.() !== false;
+ },
+
+ touchBegan(touch: GestureTouch): void {
+ if (
+ touchId != null ||
+ options.isEnabled?.() === false ||
+ // The scroll brake is a finger's (`spec:AST-094` FR11, DEC-21).
+ (touch.pointerType === 'touch' && options.isBraking?.(touch) === true)
+ ) {
+ return;
+ }
+ clearFlash();
+ touchId = touch.id;
+ bounds = options.getBounds();
+ state.isTracking = true;
+ state.isTouchInside = true;
+ isPendingDead = false;
+ emit('touchDown', touch);
+ const delay = options.highlightDelay ?? 'inScrollers';
+ const delays =
+ touch.pointerType === 'touch' &&
+ (delay === 'always' ||
+ (delay === 'inScrollers' && touch.scroll?.isInsideScroller === true));
+ if (delays) {
+ highlightTimer = setTimeout(() => {
+ highlightTimer = null;
+ if (state.isTouchInside) {
+ setHighlighted(true);
+ }
+ }, PRESS.contentTouchDelay.value);
+ } else {
+ setHighlighted(true);
+ }
+ },
+
+ touchMoved(touch: GestureTouch): void {
+ if (touch.id !== touchId) {
+ return;
+ }
+ const cancelTravel = options.cancelTravel;
+ if (cancelTravel != null && travel(touch) > cancelTravel) {
+ // A cell's scroll view took the touch: the press is over.
+ touchCancelled(touch);
+ return;
+ }
+ if (highlightTimer != null && travel(touch) > PRESS.slop.value) {
+ // A finger travelling before the delay ran out is scrolling: the
+ // press it began never paints, as a flick on a list paints nothing.
+ clearTimeout(highlightTimer);
+ highlightTimer = null;
+ isPendingDead = true;
+ }
+ const inside = contains(touch);
+ if (inside !== state.isTouchInside) {
+ state.isTouchInside = inside;
+ emit(inside ? 'touchDragEnter' : 'touchDragExit', touch);
+ if (highlightTimer == null && !isPendingDead) {
+ setHighlighted(inside);
+ }
+ }
+ emit(inside ? 'touchDragInside' : 'touchDragOutside', touch);
+ },
+
+ touchEnded(touch: GestureTouch): void {
+ if (touch.id !== touchId) {
+ return;
+ }
+ const inside = contains(touch);
+ const wasPending = highlightTimer != null;
+ clearHighlightTimer();
+ emit(inside ? 'touchUpInside' : 'touchUpOutside', touch);
+ const flash = options.quickTapFlash ?? PRESS.quickTapFlash.value;
+ if (wasPending && inside) {
+ // Quicker than the delay: the highlight shows at the lift, for the
+ // flash, or (a cell) straight into the release.
+ setHighlighted(true);
+ if (flash > 0) {
+ flashTimer = setTimeout(() => {
+ flashTimer = null;
+ setHighlighted(false);
+ }, flash);
+ } else {
+ setHighlighted(false);
+ }
+ } else {
+ setHighlighted(false);
+ }
+ finish();
+ },
+
+ touchCancelled,
+
+ allowsAncestorRecognizer(recognizer: unknown): boolean {
+ const candidate = recognizer as GestureRecognizer;
+ if (candidate.view != null && candidate.view === options.view) {
+ return true;
+ }
+ const vetoes = options.vetoesAncestorRecognizer ?? vetoesSingleTap;
+ return !vetoes(candidate);
+ },
+
+ dispose(): void {
+ clearHighlightTimer();
+ clearFlash();
+ setHighlighted(false);
+ finish();
+ },
+ };
+ return tracker;
+}
diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md
new file mode 100644
index 0000000000..f2da11247f
--- /dev/null
+++ b/packages/core/src/gestures/README.md
@@ -0,0 +1,420 @@
+# Gestures
+
+A gesture recognizer system with UIKit's semantics, for the touch
+presentations of Astryx core components. Components import it from
+`../gestures`; nothing here is exported from the package.
+
+UIKit is the reference throughout: the same recognizer states, the same
+conflict rules, the same thresholds (from `../motion/uikit/gestures.ts`, each
+one sourced or marked as a guess awaiting measurement), and touch handling
+that behaves like `UIControl` and `UIScrollView`. The rest of this page says
+where the web forces a difference.
+
+## Using it from a component
+
+```tsx
+import {useRef} from 'react';
+import {PanGestureRecognizer, useGestureRecognizer} from '../gestures';
+
+function Sheet() {
+ const ref = useRef<HTMLDivElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'down'}),
+ pan => {
+ // Runs inside the input event: write the transform, render nothing.
+ const element = ref.current;
+ if (element == null) return;
+ if (pan.state === 'ended') {
+ settle(element, pan.translation().y, pan.velocity().y);
+ } else {
+ element.style.transform = `translateY(${pan.translation().y}px)`;
+ }
+ },
+ );
+ return <div ref={ref}>…</div>;
+}
+```
+
+- The recognizer is created once per component and keeps its identity, so
+ relationships set up when it is created (`requireToFail`,
+ `recognizeSimultaneouslyWith`) keep working.
+- The listener is read through a ref. Passing a new function on each render
+ attaches nothing new, and a gesture never causes a React render.
+- The recognizer attaches in a layout effect, so the element's `touch-action`
+ is set before the browser can see a finger.
+- The `isEnabled` option follows the prop. Turning it off mid-gesture ends
+ the gesture without calling the listener, since the handler that turned
+ it off owns that end (no consumer callback from an Effect). A recognizer
+ that required it to fail recognizes a microtask later, outside the Effect,
+ and its listener reports as usual. A handler that wants UIKit's
+ `.cancelled` calls `recognizer.setEnabled(false)` itself, which reports it
+ at once.
+- `usePressTracker` rebuilds its tracker when `trackingExpansion`,
+ `highlightDelay`, `cancelTravel` or `quickTapFlash` change, from the next
+ touch, and reads its callbacks (`isBraking` included) on every touch.
+- `usePressTracker(ref, options)` gives an element `UIControl` touch tracking
+ (see below).
+
+Outside React, `getGestureHost(document).attach(element, recognizer)` does
+the same and returns a detach function.
+
+## Recognizers
+
+| Recognizer | UIKit | Kind | Notes |
+| -------------------------------- | ---------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `TapGestureRecognizer` | `UITapGestureRecognizer` | discrete | `numberOfTapsRequired`, `numberOfTouchesRequired`; fails past 45 px of travel, on extra fingers, a hold over 1.5 s, a late or far next tap |
+| `LongPressGestureRecognizer` | `UILongPressGestureRecognizer` | continuous | `minimumPressDuration` 500 ms, `allowableMovement` 10 px (a distance, not per axis), `numberOfTapsRequired`; a zero duration begins on the touch itself (a selection tracker over a group of actions) |
+| `PanGestureRecognizer` | `UIPanGestureRecognizer` | continuous | min/max touches, `direction` (axis or one-way) with `axisRatio`, `lockAxis`, `scrollEdge`; `translation()`, `totalTranslation()`, `velocity()` |
+| `SwipeGestureRecognizer` | `UISwipeGestureRecognizer` | discrete | recognized during the motion; one or more directions, `numberOfTouchesRequired`; 50 px along, at most 50 px across, 500 ms |
+| `PinchGestureRecognizer` | `UIPinchGestureRecognizer` | continuous | `scale` (settable, to re-base it), `velocity` in scale per second, `focalPoint()` |
+| `ScreenEdgePanGestureRecognizer` | `UIScreenEdgePanGestureRecognizer` | continuous | `edges`: `leading` / `trailing`, resolved against the view's writing direction; attached to an edge zone the view lies within; fails as soon as the touch lands outside every requested edge band; a finger's only |
+
+Every recognizer also has UIKit's switches: `isEnabled` (use `setEnabled`;
+turning it off mid-gesture cancels), `cancelsTouchesInView` (default true),
+`delaysTouchesBegan` (default false), `delaysTouchesEnded` (default true),
+`allowedPointerTypes`, and `requiresExclusiveTouchType`.
+
+### What the pan reports
+
+The pan reads its numbers the way `UIPanGestureRecognizer` does, as measured
+in the UIKit lab:
+
+- It begins once the centroid has moved `hysteresis` (10 px) along either
+ axis, not as a distance.
+- `translation()` leaves out the travel the threshold took: a slow drag reads
+ zero when the pan begins, and a step that overshoots keeps only the
+ overshoot. A dragged surface does not jump. `totalTranslation()` is the
+ movement since the fingers landed, for a surface that wants it.
+- `axisRatio` (for a pan limited to an axis): the movement along the axis
+ must exceed `axisRatio` times the movement across it to begin; movement
+ across that exceeds the movement along it fails the pan; in between it
+ waits.
+- `velocity()` is UIKit's own filter (see Velocity). The lift updates
+ neither number; a finger that rested past the stillness interval releases
+ at 0.
+
+### States
+
+```
+possible ─► began ─► changed* ─► ended | cancelled continuous
+possible ─► ended discrete ("recognized")
+possible ─► failed
+```
+
+Listeners (UIKit's target-action) run for `began`, `changed`, `ended` and
+`cancelled`. `addTransitionListener` also reports `failed` and the return to
+`possible`. A recognizer in a terminal state ignores the touches it still
+holds and returns to `possible` when all of them have ended.
+
+## Conflicts: the arena
+
+A new touch goes to every recognizer on its hit path, innermost first, and
+each one that accepts it tracks it until it ends. Then:
+
+- **Exclusivity.** Two recognizers that share a touch are never active
+ together unless one allows it (`recognizeSimultaneouslyWith`, or the
+ `shouldRecognizeSimultaneously` delegate). The first to recognize fails
+ the other possible ones. A recognizer that tries to begin while a
+ conflicting one is active fails instead. When two qualify on the same
+ input, the innermost one wins.
+- **Failure requirements.** `a.requireToFail(b)` keeps `a` in `possible`
+ until `b` fails, then lets `a` recognize. If `b` recognizes, `a` fails. A
+ recognizer that is not involved in the current touches holds nothing up.
+ The delegates `shouldRequireFailureOf` and `shouldBeRequiredToFailBy`
+ express the same thing dynamically.
+- **Delegates.** `shouldBegin`, `shouldReceiveTouch`, and `canPrevent` /
+ `canBePrevented` on subclasses.
+
+```ts
+// Single tap waits for the double tap to fail, as in UIKit.
+single.requireToFail(double);
+
+// Inner horizontal scroller yields to the back-swipe in the edge band only:
+// the edge pan fails at touch-down anywhere else, so nothing waits.
+innerPan.requireToFail(edgePan);
+```
+
+## Touches in the view: `createPressTracker`
+
+A pressable control's view-level touch handling, with `UIControl`
+semantics:
+
+- `touchDown`, `touchDragInside` / `touchDragOutside`, `touchDragEnter` /
+ `touchDragExit`, `touchUpInside` / `touchUpOutside`, `touchCancel`.
+- "Inside" is the control's bounds expanded by `trackingExpansion`, so a
+ fingertip that slides a little off a button is still on it.
+- The highlight comes on in the same frame. Inside a scroller it waits
+ `contentTouchDelay` (`UIScrollView.delaysContentTouches`), so a flick
+ paints nothing. A tap quicker than that delay shows the highlight at the
+ lift for `quickTapFlash`.
+- A recognizer that takes the touch (`cancelsTouchesInView`), or the browser
+ taking it to scroll, cancels the press with no release.
+- `UIControl`'s iOS 6 rule applies: an ancestor's single-finger single tap
+ does not beat the control's own action for a touch on it.
+ `vetoesAncestorRecognizer` replaces that rule (a slider vetoes a pan along
+ its track).
+
+The browser's click stays the control's activation, so keyboard and
+assistive-technology activation keep working.
+
+### Press profiles
+
+`PRESS_PROFILES` holds the two ways UIKit tracks a press:
+
+- `control` (a button, a switch): the highlight comes on in the same frame
+ outside a scroller, the finger is tracked 70 pt beyond the bounds, and
+ the release takes the list's deselect clock, as every surface's does
+ until a control runs its own (UIButton's 0.25 s);
+- `cell` (a table or collection row): the highlight waits the content-touch
+ delay inside a scroll view and comes on at once outside one
+ (`spec:AST-094` FR11), travel past the pan hysteresis cancels the press for
+ good, a quicker tap highlights at the lift straight into the release, and
+ the release takes the list's deselect clock.
+
+The document press controller (`utils/pressFeedback.ts`) writes
+`data-astryx-press` for the presses it tracks, and the action-group tracker
+(`hooks/actionGroupTracker.ts`) writes its groups' presses itself.
+
+### Rows and cards
+
+A list of a thousand rows cannot pay for a hook and four listeners per row.
+The document press controller (`utils/pressFeedback.ts`) presses the
+innermost enabled `[data-astryx-pressable]` under each touch and paints it,
+with no listener per row; a touch that brakes a scroll the finger set moving
+presses nothing.
+
+## What the browser is told
+
+- **Every pointer.** Gestures attach for a mouse, a pen and a finger
+ (`spec:AST-094` FR43). Under a fine primary pointer an element whose
+ gesture or press consumer is enabled listens with one passive
+ `pointerdown`; a press (the primary button, a pen's contact or a finger)
+ adds the page's listeners for that press alone, and they go once none of
+ its contacts is down, except the `click` listener, which stays up to 1 s
+ when a claimed lift owes a swallowed click (FR24). An element whose
+ recognizer claims a moving finger also keeps its blocking `touchmove`
+ (FR19). A right click, a pen's barrel button or a ctrl-click on macOS
+ starts no press.
+- **`touch-action`.** Each element gets the intersection of what its
+ recognizers leave the browser, never wider than the element's own
+ `touch-action` (`spec:AST-094` FR18). Over an inline value the host writes
+ what both allow, inline. Otherwise it marks the element
+ (`data-astryx-touch-action`) under a rule in the first cascade layer, which
+ any author rule outranks, and in the next frame writes inline what both
+ allow where that is narrower than the author's rule. Detaching gives the
+ element its own value back (opt out with `manageStyle: false`):
+
+ | Recognizers on the element | `touch-action` |
+ | -------------------------------------------- | ------------------- |
+ | tap, long press | `manipulation` |
+ | horizontal pan or swipe, horizontal edge pan | `pan-y pinch-zoom` |
+ | vertical pan or swipe | `pan-x pinch-zoom` |
+ | one-way pan, pan with `scrollEdge` | left as is (`auto`) |
+ | free pan | `pinch-zoom` |
+ | pinch | `pan-x pan-y` |
+ | pinch together with a free pan | `none` |
+
+ A one-way pan leaves the browser its own axis too: a toast dragged away
+ from its edge scrolls the page. It claims its direction by cancelling
+ `touchmove` when it begins.
+
+ `pinch-zoom` stays in the value unless a pinch recognizer is
+ attached, so the page stays zoomable (WCAG 1.4.4). A long press also turns
+ off the iOS callout and text selection on its element.
+
+- **Claiming.** When a recognizer recognizes, it owns its touches. Each
+ element with a recognizer that can claim a moving touch (a pan, a swipe, a
+ long press that then drags, a pinch) has a non-passive
+ `touchmove` listener that cancels the event only while one of its touches
+ is owned. A touch nobody owns scrolls exactly as it would without the
+ system. Taps claim only at the lift, so an element with only taps, or only
+ a press consumer, gets no such listener (see the known limit below).
+- **Claim at the begin.** A pan claims its touch only as it begins, at
+ UIKit's 10 pt (`spec:AST-094` FR19), before WebKit commits a slow drag to
+ a scroll at 10–11 px; a drag the browser took first stays the browser's
+ (FR14).
+- **The browser's claim.** `pointercancel` on a finger, or a scroll above
+ the touch, means the browser took the finger; so does its first `touchmove`
+ that can no longer be cancelled, when the browser could pan along the
+ finger's main axis. (Chromium also stops asking after one unconsumed
+ `touchmove` when `touch-action` keeps it from panning that way, as for a
+ horizontal drag under `pan-y`; that is not a claim.) Possible recognizers that share it fail, active ones are
+ cancelled, and the view's press is cancelled.
+- **Clicks.** When a touch's gesture cancelled the view's touches, its
+ `touchend` is cancelled (no click and no compatibility mouse events) and a
+ one-shot guard swallows the next trusted click. A click held back for a
+ recognizer that may still recognize (a double tap between taps) is
+ swallowed at once and replayed on the original target if the recognizer
+ fails. Clicks with `detail === 0` (keyboard, assistive technology, code)
+ always pass.
+- **Context menus.** A `contextmenu` while a recognizer owns a touch is
+ cancelled, so a long press never also opens the browser's menu.
+- **Focus.** Losing window focus or hiding the page cancels every touch in
+ flight, as UIKit does when the app resigns active.
+
+### Native scrolling
+
+`scrollEdge` makes a pan share its axis with the native scrollers under the
+finger. This is the sheet over its own list: the pan begins only if nothing
+under the touch could scroll for that movement, the finger landed at the
+edge and pulls away from it. The browser has not committed yet, so beginning
+claims the touch and the content never moves.
+
+Who gets a drag is decided once, when it begins, as in UIKit: a drag that
+began as a scroll stays the scroll view's for its whole length (it scrolls
+to the top, then rubber-bands), and never changes hands midway
+(`spec:AST-094` FR14).
+
+"Could scroll" follows the browser's own rules: `touch-action` between the
+touch and each scroller, scroll chaining stopped by `overscroll-behavior`,
+and RTL `scrollLeft` ranges.
+
+### Multiple fingers
+
+A second finger never breaks a one-finger pan that is already moving: the
+pan ignores it, and the claim keeps the browser from zooming with it. A
+second finger that lands before any recognizer has claimed fails the
+one-finger recognizers, so the two fingers zoom the page.
+
+## Time
+
+Every input carries its own timestamp (`event.timeStamp`), and timers are
+deadlines on that same clock. Before an input is processed, every timer due
+by 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 ran late. Tests drive the whole system with explicit
+timestamps and no real time.
+
+## Velocity
+
+`VelocityTracker` reports px per second, UIKit's unit, and is the one
+velocity tracker every continuous recognizer uses
+(`architecture:interaction-modality` INV10, `spec:AST-100` FR1, FR2; no
+alternative estimators). One filter, iOS's measured blend, updated on each
+moved sample (a sample at the newest position is not motion):
+
+- A pan's velocity is 0.2 times the newest interval's velocity plus 0.8 times
+ the previous interval's (an interval runs from one moved sample to the
+ next; the touch-down counts as the first). With one interval so far it is
+ that interval, as UIKit reports it. It reproduces every value UIKit
+ reported on six recorded touch streams, and like UIKit's it reacts a frame
+ late to an acceleration.
+- A scrolling surface's release (paging, a wheel) is 0.25 times the newest
+ pan value plus 0.75 times the previous one: a pan's `scrollVelocity()`.
+ Everything else reads `velocity()`.
+
+A release reads 0 when the finger stayed still for longer than the stillness
+interval (`UIKIT_GESTURES.velocity.stillness`) before lifting, the one
+difference from iOS, whose filter never decays and so flings after a rest;
+and 0 with fewer than two moved samples. The pan passes its lift's event time
+to the tracker.
+
+## Haptics
+
+`playHaptic(kind)` vibrates where `navigator.vibrate` exists, with one
+pattern per UIKit feedback kind. iOS Safari has no vibration API. It plays a
+light impact only when a real tap toggles an `<input type="checkbox"
+switch>`, and WebKit requires a trusted event for it. `attachTapHaptic(label)`
+puts a hidden switch inside a label the control renders as its tap target,
+so every real tap on it plays that impact. Nothing can play a haptic later
+from script, so mid-drag haptics (detent snaps, picker ticks) are not
+possible in iOS Safari.
+
+## Thresholds
+
+All numbers live in `../motion/uikit/gestures.ts`. Each one carries either
+its source (Apple documentation, or a measurement: the recognizers' own
+values read in a UIKit app on the iOS 26.2 simulator and confirmed with
+touches, or Mobile Safari measured on the same simulator) or a guess
+together with the measurement that will replace it. A unit test fails if an
+entry has neither.
+
+## Touch presentation
+
+Whether a component presents itself the touch (UIKit) way is answered once,
+in `../utils/touchPresentation.ts`:
+
+- touch behaviours (UIKit springs and timings, the press model's touch
+ profiles) key on a coarse PRIMARY pointer (`TOUCH_QUERY`);
+- layout behaviours key on a compact viewport, below the theme's `md`
+ width point (`spec:AST-012` FR9): `COMPACT_QUERY` spells the default
+ points for a style, and behaviour reads the active theme's definition, so
+ a theme that moves `md` moves compact with it;
+- a presentation that needs both, a sheet in place of a popover, asks for
+ both (`COMPACT_TOUCH_QUERY`).
+
+Styles switch on the same conditions by writing the same query as a StyleX
+media key (`'@media (pointer: coarse)'`, and the compact-touch query spelled
+exactly as `COMPACT_TOUCH_QUERY`, which a test enforces), so the first paint
+is right. Behaviour reads
+`useTouchPresentation()` (SSR-safe), a component with no interaction to
+infer from included (UIKit timings under a finger, its own motion under a
+mouse), and a decision taken once reads `readTouchPresentation()`.
+
+## Known limits
+
+- **A scroll that begins on a recognizer waits for a busy main thread.** In
+ Mobile Safari (iOS 26.2, measured), a vertical scroll that starts on an
+ element with a non-passive `touchmove` listener waits until the current
+ JavaScript task ends; on a plain row, a pressable row or a tap-only
+ element it starts at once (within 50 ms) even during a 500 ms task.
+ Chromium documents the same rule for non-passive listeners. The listener
+ stays because nothing else keeps UIKit's arbitration: with a passive
+ listener, or one added during `touchstart` (which Safari ignores for that
+ touch), Safari hands every diagonal drag on a swipe row to the list's
+ scroll, 3:1 included. It is never worse than UIKit, where a busy main
+ thread stalls every scroll.
+- **Lists where every row has a horizontal recognizer** (swipe actions on
+ every row of a mail list): every scroll start waits on the current task in
+ Safari. Keep list screens' tasks short. A native horizontal `scroll-snap`
+ reveal inside the row would never wait, but it tracks with scroll physics
+ rather than UIKit's measured tracking spring; it is a possible opt-in, not
+ the default.
+- **Follow-up:** Chromium keeps 3:1 to 1.5:1 drags as swipes even with a
+ passive listener (its `touch-action` filter drops a `pan-y` scroll that
+ starts sideways), so a passive listener there would cost no parity. It
+ waits on a measured run on Android before any engine-specific choice.
+
+## Where the web differs from UIKit
+
+- Once a recognizer owns a touch, the browser cannot take the scroll back
+ later in the same gesture. UIKit does not either: it decides between a
+ sheet and its list when the drag begins.
+- In Chromium a finger's first `touchmove` arrives only after about 16 px.
+ Movement below that comes from the finger's pointer events, but the
+ browser's own decision to scroll happens at that first `touchmove`.
+ Mobile Safari delivers `touchmove` from the first pixel.
+- A tap that holds a plain `<button>` for a second or more gets no click in
+ Mobile Safari, while UIKit's tap allows 1.5 s. A tap recognizer on the
+ element follows UIKit.
+- iOS Safari's own back swipe from the screen edge cannot be cancelled by
+ the page. A leading-edge pan works where that swipe has no history to go
+ back to.
+- `translation()` is in client CSS px. It is not converted into a rotated or
+ scaled ancestor's coordinate space.
+- A replayed click is untrusted. Anything that needs real user activation
+ inside the replay window (opening a file picker, for example) should not
+ sit under a multi-tap recognizer.
+
+## Tests
+
+- `__tests__/<Recognizer>.test.ts`: each recognizer's state machine on
+ synthetic touches with explicit timestamps.
+- `__tests__/arena*.test.ts`: the conflict matrix, delivery to the view,
+ click dispositions, cancellation, and multiple fingers.
+- `__tests__/GestureHost.test.ts`: the DOM integration through real
+ listeners in jsdom.
+- `__tests__/VelocityTracker.test.ts`: UIKit's filter against the velocities
+ UIKit reported on recorded touch streams, a steady speed and a hard
+ acceleration.
+- `__tests__/haptics.test.ts`: vibration patterns and the hidden switch.
+- `__tests__/browser/`: the browser proof on a phone-sized touch screen, in
+ Chromium (CDP touches with timestamps) and WebKit (its own touch input),
+ with mouse and pen input in a fine-pointer context, run by
+ `pnpm test:interaction gestures.interaction.browser.spec.ts` and in CI's
+ interaction proofs; where WebKit cannot launch on the host,
+ `internal/interaction-harness/scripts/webkit-container.mjs` runs its
+ project in the official Playwright image. The same fixture passed in
+ Mobile Safari on the iOS 26.2 simulator: claims, click suppression, the
+ scroll edge, pinch, and a long press at exactly 500 ms.
diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts
index cae31eb550..e90bcec389 100644
--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts
+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts
@@ -86,7 +86,14 @@ let detachers: (() => void)[];
/** jsdom computes no layout: give a scroller its metrics. */
function scrollable(
element: HTMLElement,
- metrics: {scrollTop?: number; scrollHeight?: number; clientHeight?: number},
+ metrics: {
+ scrollTop?: number;
+ scrollHeight?: number;
+ clientHeight?: number;
+ scrollLeft?: number;
+ scrollWidth?: number;
+ clientWidth?: number;
+ },
): void {
for (const [key, value] of Object.entries(metrics)) {
Object.defineProperty(element, key, {configurable: true, value});
@@ -1184,6 +1191,48 @@ describe('GestureHost', () => {
}
});
+ it('keeps a vertical drag under pan-x when Chromium stops asking after one unconsumed move', () => {
+ // The case above turned 90°: a row of a sideways list, dragged down.
+ const restore = touchActionFromData();
+ try {
+ const {list, row} = mount(
+ '<div id="list" style="overflow-x: auto"><div id="row" data-touch-action="pan-x pinch-zoom"></div></div>',
+ );
+ scrollable(list, {scrollLeft: 0, scrollWidth: 1000, clientWidth: 400});
+ const consumer = new RecordingConsumer();
+ detachers.push(host.attachConsumer(row, consumer));
+ const finger = {id: 1, x: 30, y: 100};
+ touch('touchstart', row, [finger], [finger], 0);
+ // The first move goes unconsumed; Chromium sends the rest uncancelable
+ // although pan-x keeps it from panning vertically.
+ touch('touchmove', row, [{...finger, y: 120}], [{...finger, y: 120}], 16);
+ touch(
+ 'touchmove',
+ row,
+ [{...finger, x: 33, y: 140}],
+ [{...finger, x: 33, y: 140}],
+ 32,
+ false,
+ );
+ touch(
+ 'touchmove',
+ row,
+ [{...finger, x: 35, y: 160}],
+ [{...finger, x: 35, y: 160}],
+ 48,
+ false,
+ );
+ expect(consumer.events).toEqual([
+ 'began:1',
+ 'moved:1',
+ 'moved:1',
+ 'moved:1',
+ ]);
+ } finally {
+ restore();
+ }
+ });
+
it("judges only the first uncancelable move: a sideways drag that turns vertical stays the page's", () => {
const restore = touchActionFromData();
try {
diff --git a/packages/core/src/gestures/__tests__/PressTracker.test.ts b/packages/core/src/gestures/__tests__/PressTracker.test.ts
new file mode 100644
index 0000000000..9a0a558f00
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/PressTracker.test.ts
@@ -0,0 +1,275 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file PressTracker.test.ts
+ * @input A PressTracker fed through a GestureArena by synthetic touches
+ * @output UIControl semantics: events, the expanded tracking bounds, the
+ * highlight timing inside and outside scrollers, cancellation
+ * @position Unit tests of packages/core/src/gestures/PressTracker.ts
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {UIKIT_GESTURES} from '../../motion/uikit/gestures';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {
+ PRESS_PROFILES,
+ createPressTracker,
+ type ControlEvent,
+} from '../PressTracker';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {createHarness, scrollProbe} from './harness';
+
+const BOUNDS = {left: 100, top: 100, right: 200, bottom: 140};
+const EXPANSION = UIKIT_GESTURES.control.trackingExpansion.value;
+const DELAY = UIKIT_GESTURES.press.contentTouchDelay.value;
+const FLASH = UIKIT_GESTURES.press.quickTapFlash.value;
+
+function setup() {
+ const events: ControlEvent[] = [];
+ const highlights: boolean[] = [];
+ const tracker = createPressTracker({
+ getBounds: () => BOUNDS,
+ onControlEvent: event => events.push(event),
+ onHighlightChange: value => highlights.push(value),
+ });
+ return {events, highlights, tracker, h: createHarness()};
+}
+
+describe('PressTracker', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('highlights in the same frame outside a scroller and acts on touch up inside', () => {
+ const {events, highlights, tracker, h} = setup();
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ expect(highlights).toEqual([true]);
+ h.finger(1).move(152, 121, 16);
+ h.finger(1).up(80);
+ expect(events).toEqual(['touchDown', 'touchDragInside', 'touchUpInside']);
+ expect(highlights).toEqual([true, false]);
+ });
+
+ it('brakes only a finger: a mouse or pen press right after a finger-driven scroll still presses (spec:AST-094 FR11)', () => {
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ const events: ControlEvent[] = [];
+ const tracker = createPressTracker({
+ getBounds: () => BOUNDS,
+ onControlEvent: event => events.push(event),
+ // A finger set a scroll moving a moment ago.
+ isBraking: () => true,
+ });
+ const h = createHarness();
+ h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: tracker,
+ pointerType,
+ });
+ h.finger(1).up(80);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ }
+ // A finger that brakes the scroll presses nothing.
+ const events: ControlEvent[] = [];
+ const tracker = createPressTracker({
+ getBounds: () => BOUNDS,
+ onControlEvent: event => events.push(event),
+ isBraking: () => true,
+ });
+ const h = createHarness();
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ h.finger(1).up(80);
+ expect(events).toEqual([]);
+ });
+
+ it('keeps tracking inside the expanded bounds and exits past them', () => {
+ const {events, highlights, tracker, h} = setup();
+ const finger = h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: tracker,
+ });
+ finger.move(200 + EXPANSION, 120, 16);
+ expect(tracker.isTouchInside).toBe(true);
+ finger.move(200 + EXPANSION + 1, 120, 32);
+ expect(tracker.isTouchInside).toBe(false);
+ finger.move(150, 120, 48);
+ finger.up(64, 200 + EXPANSION + 10, 120);
+ expect(events).toEqual([
+ 'touchDown',
+ 'touchDragInside',
+ 'touchDragExit',
+ 'touchDragOutside',
+ 'touchDragEnter',
+ 'touchDragInside',
+ 'touchUpOutside',
+ ]);
+ expect(highlights).toEqual([true, false, true, false]);
+ });
+
+ it('waits the content-touch delay inside a scroller, and flashes a quicker tap', () => {
+ const {highlights, tracker, h} = setup();
+ const probe = scrollProbe(() => true, true);
+ h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: tracker,
+ scroll: probe,
+ });
+ expect(highlights).toEqual([]);
+ vi.advanceTimersByTime(DELAY - 1);
+ expect(highlights).toEqual([]);
+ vi.advanceTimersByTime(1);
+ expect(highlights).toEqual([true]);
+ h.finger(1).up(400);
+ expect(highlights).toEqual([true, false]);
+
+ const quick = setup();
+ quick.h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: quick.tracker,
+ scroll: probe,
+ });
+ quick.h.finger(1).up(60);
+ expect(quick.highlights).toEqual([true]);
+ vi.advanceTimersByTime(FLASH);
+ expect(quick.highlights).toEqual([true, false]);
+ });
+
+ it('never paints a pending press whose finger travelled (a flick)', () => {
+ const {highlights, tracker, h} = setup();
+ const probe = scrollProbe(() => true, true);
+ h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: tracker,
+ scroll: probe,
+ });
+ h.finger(1).move(150, 140, 20);
+ vi.advanceTimersByTime(DELAY * 2);
+ expect(highlights).toEqual([]);
+ });
+
+ it('is cancelled, with no release, when a recognizer takes the touch', () => {
+ const {events, highlights, tracker, h} = setup();
+ const pan = new PanGestureRecognizer({name: 'pan'});
+ h.finger(1).down(150, 120, 0, {recognizers: [pan], consumer: tracker});
+ h.finger(1).move(175, 120, 16);
+ expect(events).toEqual(['touchDown', 'touchCancel']);
+ expect(highlights).toEqual([true, false]);
+ });
+
+ it('is cancelled when the browser takes the touch to scroll', () => {
+ const {events, tracker, h} = setup();
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ h.finger(1).takenByBrowser(30);
+ expect(events).toEqual(['touchDown', 'touchCancel']);
+ expect(tracker.isTracking).toBe(false);
+ });
+
+ it('tracks one finger at a time', () => {
+ const {events, tracker, h} = setup();
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ h.finger(2).down(160, 120, 10, {recognizers: [], consumer: tracker});
+ h.finger(2).up(20);
+ h.finger(1).up(30);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ });
+});
+
+describe('PressTracker cell profile', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function cell() {
+ const events: ControlEvent[] = [];
+ const highlights: boolean[] = [];
+ const tracker = createPressTracker({
+ getBounds: () => BOUNDS,
+ ...PRESS_PROFILES.cell,
+ onControlEvent: event => events.push(event),
+ onHighlightChange: value => highlights.push(value),
+ });
+ return {events, highlights, tracker, h: createHarness()};
+ }
+
+ it('highlights at once outside a scroller: the delay applies only inside one (AST-094 FR11)', () => {
+ const {highlights, tracker, h} = cell();
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ expect(highlights).toEqual([true]);
+ vi.advanceTimersByTime(DELAY);
+ expect(highlights).toEqual([true]);
+ h.finger(1).up(DELAY + 40);
+ expect(highlights).toEqual([true, false]);
+ });
+
+ it('waits the content-touch delay inside a scroller', () => {
+ const {highlights, tracker, h} = cell();
+ h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: tracker,
+ scroll: scrollProbe(() => true, true),
+ });
+ expect(highlights).toEqual([]);
+ vi.advanceTimersByTime(DELAY);
+ expect(highlights).toEqual([true]);
+ h.finger(1).up(DELAY + 40);
+ expect(highlights).toEqual([true, false]);
+ });
+
+ it('is cancelled for good once the finger travels past the pan hysteresis', () => {
+ const {events, highlights, tracker, h} = cell();
+ const finger = h.finger(1).down(150, 120, 0, {
+ recognizers: [],
+ consumer: tracker,
+ });
+ vi.advanceTimersByTime(DELAY);
+ const limit = UIKIT_GESTURES.pan.hysteresis.value;
+ finger.move(150, 120 + limit, DELAY + 16);
+ expect(tracker.isTracking).toBe(true);
+ finger.move(150, 120 + limit + 1, DELAY + 32);
+ expect(tracker.isTracking).toBe(false);
+ // Back inside: no re-highlight, and the lift does nothing.
+ finger.move(150, 120, DELAY + 48);
+ finger.up(DELAY + 64);
+ expect(events).toEqual(['touchDown', 'touchDragInside', 'touchCancel']);
+ expect(highlights).toEqual([true, false]);
+ });
+
+ it('shows a quicker tap at the lift straight into the release, with no flash', () => {
+ const {events, highlights, tracker, h} = cell();
+ h.finger(1).down(150, 120, 0, {recognizers: [], consumer: tracker});
+ h.finger(1).up(60);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ expect(highlights).toEqual([true, false]);
+ });
+
+ it('keeps the control profile on today defaults, with the button release clock', () => {
+ expect(PRESS_PROFILES.control.highlightDelay).toBe('inScrollers');
+ expect(PRESS_PROFILES.control.quickTapFlash).toBe(FLASH);
+ expect(PRESS_PROFILES.cell.cancelTravel).toBe(
+ UIKIT_GESTURES.pan.hysteresis.value,
+ );
+ });
+});
+
+describe('PressTracker in the arena', () => {
+ it("lets a control veto an ancestor's single tap (UIControl's rule)", () => {
+ const h = createHarness();
+ const button = createPressTracker({getBounds: () => null, view: 'button'});
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ tap.view = 'row';
+ const double = new TapGestureRecognizer({
+ name: 'double',
+ numberOfTapsRequired: 2,
+ });
+ double.view = 'row';
+ h.finger(1).down(0, 0, 0, {recognizers: [tap, double], consumer: button});
+ expect(h.finger(1).up(50)).toBe('defer');
+ expect(h.log[0]).toBe('tap:failed@50');
+ expect(double.state).toBe('possible');
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/arena.test.ts b/packages/core/src/gestures/__tests__/arena.test.ts
index 741e64e72c..8f3ca4f3c4 100644
--- a/packages/core/src/gestures/__tests__/arena.test.ts
+++ b/packages/core/src/gestures/__tests__/arena.test.ts
@@ -80,6 +80,11 @@ class Scripted extends GestureRecognizer {
this.setState('failed');
}
+ /** Cancel itself, as a recognizer that gives up mid-gesture does. */
+ cancelSelf(): void {
+ this.setState('cancelled');
+ }
+
/** Recognize at `deadline` on the event clock, unless the touch lifts. */
recognizeAt(deadline: number): void {
this.setTimer(deadline, () => this.recognize());
@@ -522,6 +527,36 @@ describe('arena: claims', () => {
first.up(80);
second.up(80);
});
+
+ it('keeps a moving finger claimed until it lifts when its gesture cancels itself on that move, so the drag never turns into the page scroll midway (FR14)', () => {
+ const h = createHarness();
+ // A long press's shape: it begins while the finger rests, then cancels
+ // itself on the first move past its tolerance.
+ 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.y - touch.startY) > 10 &&
+ isActive(self.state)
+ ) {
+ self.cancelSelf();
+ }
+ },
+ });
+ const finger = h.finger(1).down(0, 0, 0, {recognizers: [press]});
+ h.advance(600);
+ expect(press.state).toBe('began');
+ expect(h.arena.isClaimed(1)).toBe(true);
+ finger.move(0, -11, 616);
+ expect(press.state).toBe('cancelled');
+ expect(h.arena.isClaimed(1)).toBe(true);
+ finger.move(0, -60, 632);
+ expect(h.arena.isClaimed(1)).toBe(true);
+ finger.up(700);
+ expect(h.arena.isClaimed(1)).toBe(false);
+ });
});
/** Records the touches that began off its hit path. */
diff --git a/packages/core/src/gestures/__tests__/harness.ts b/packages/core/src/gestures/__tests__/harness.ts
index bf339255cd..cf68c863b8 100644
--- a/packages/core/src/gestures/__tests__/harness.ts
+++ b/packages/core/src/gestures/__tests__/harness.ts
@@ -4,8 +4,9 @@
* @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
+ * manual clock, an arena wired to a transition log, fingers that land,
+ * move and lift at explicit timestamps, and a coarse primary pointer for
+ * tests that go through the document's host
* @position Test-only helper of packages/core/src/gestures (excluded from the
* build with the rest of __tests__)
*/
@@ -221,3 +222,31 @@ export function scrollProbe(
): NativeScrollProbe {
return {canScroll, isInsideScroller, allowsNativePan: true};
}
+
+/**
+ * Declare a phone's primary pointer for a test that goes through the
+ * document's host (`getGestureHost`): these tests exercise the host's
+ * coarse-pointer path, which needs `(pointer: coarse)` to match, and jsdom
+ * has no `matchMedia`. Returns the undo.
+ */
+export function coarsePrimaryPointer(): () => void {
+ const hadOwn = Object.prototype.hasOwnProperty.call(window, 'matchMedia');
+ const original = window.matchMedia;
+ window.matchMedia = (query: string) => ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ });
+ return () => {
+ if (hadOwn) {
+ window.matchMedia = original;
+ } else {
+ delete (window as {matchMedia?: unknown}).matchMedia;
+ }
+ };
+}
diff --git a/packages/core/src/gestures/__tests__/pressTrackerFactory.test.ts b/packages/core/src/gestures/__tests__/pressTrackerFactory.test.ts
new file mode 100644
index 0000000000..17efacdcef
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/pressTrackerFactory.test.ts
@@ -0,0 +1,59 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file pressTrackerFactory.test.ts
+ * @input The sources of Core and Lab
+ * @output Press tracking is built by a `create…` factory, not a class: no
+ * `class PressTracker`, and no press tracker constructed with `new`, anywhere
+ * (architecture:react-component-runtime INV13: the recognizer family is
+ * the one place the touch modules use classes)
+ * @position Source boundary test of packages/core/src/gestures/PressTracker.ts
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+const ROOT = path.resolve(__dirname, '../../../../..');
+
+function sourcesUnder(directory: string): string[] {
+ const files: string[] = [];
+ const visit = (current: string) => {
+ for (const entry of fs.readdirSync(current, {withFileTypes: true})) {
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) {
+ continue;
+ }
+ const full = path.join(current, entry.name);
+ if (entry.isDirectory()) {
+ visit(full);
+ } else if (/\.(m?[jt]sx?)$/.test(entry.name)) {
+ files.push(full);
+ }
+ }
+ };
+ if (fs.existsSync(directory)) {
+ visit(directory);
+ }
+ return files;
+}
+
+describe('press tracking', () => {
+ it('is built by createPressTracker: no class PressTracker, and no new PressTracker in Core or Lab (architecture:react-component-runtime INV13)', () => {
+ const source = fs.readFileSync(
+ path.join(ROOT, 'packages/core/src/gestures/PressTracker.ts'),
+ 'utf8',
+ );
+ expect(source).not.toMatch(/\bclass PressTracker\b/);
+ // Built from parts, so this file does not match itself.
+ const construction = new RegExp(
+ ['\\bnew ', 'PressTracker', '\\('].join(''),
+ );
+ const offenders = [
+ ...sourcesUnder(path.join(ROOT, 'packages/core/src')),
+ ...sourcesUnder(path.join(ROOT, 'packages/lab/src')),
+ ]
+ .filter(file => construction.test(fs.readFileSync(file, 'utf8')))
+ .map(file => path.relative(ROOT, file));
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/packages/core/src/gestures/__tests__/useGestureRecognizer.test.tsx b/packages/core/src/gestures/__tests__/useGestureRecognizer.test.tsx
new file mode 100644
index 0000000000..ba2e937236
--- /dev/null
+++ b/packages/core/src/gestures/__tests__/useGestureRecognizer.test.tsx
@@ -0,0 +1,570 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useGestureRecognizer.test.tsx
+ * @input React components using useGestureRecognizer / usePressTracker, and
+ * touch events dispatched on their elements
+ * @output The hooks keep one recognizer per component, attach before the
+ * first touch, run the latest listener without rendering per move, and
+ * detach on unmount
+ * @position jsdom tests of packages/core/src/gestures/useGestureRecognizer.ts
+ */
+
+import {act, render} from '@testing-library/react';
+import {useRef} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {getGestureHost} from '../GestureHost';
+import {PanGestureRecognizer} from '../PanGestureRecognizer';
+import {TapGestureRecognizer} from '../TapGestureRecognizer';
+import {TOUCH_ACTION_ATTRIBUTE} from '../touchActionRule';
+import type {ControlEvent} from '../PressTracker';
+import {useGestureRecognizer, usePressTracker} from '../useGestureRecognizer';
+import {coarsePrimaryPointer} from './harness';
+
+function touch(
+ type: string,
+ target: EventTarget,
+ contact: {id: number; x: number; y: number},
+ time: number,
+ isLift = false,
+): void {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const entry = {
+ identifier: contact.id,
+ clientX: contact.x,
+ clientY: contact.y,
+ target,
+ };
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {value: isLift ? [] : [entry]});
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+}
+
+let renders = 0;
+
+function Draggable({
+ onPan,
+ onRecognizer,
+ isEnabled = true,
+}: {
+ onPan: (recognizer: PanGestureRecognizer) => void;
+ onRecognizer?: (recognizer: PanGestureRecognizer) => void;
+ isEnabled?: boolean;
+}) {
+ renders += 1;
+ const ref = useRef<HTMLDivElement>(null);
+ const pan = useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ onPan,
+ {isEnabled},
+ );
+ onRecognizer?.(pan);
+ return <div data-testid="surface" ref={ref} />;
+}
+
+// A phone: the document's host listens only where the pointer is coarse.
+let restorePointer: () => void = () => {};
+beforeEach(() => {
+ restorePointer = coarsePrimaryPointer();
+});
+afterEach(() => {
+ restorePointer();
+});
+
+describe('useGestureRecognizer', () => {
+ afterEach(() => {
+ renders = 0;
+ });
+
+ it('drives the latest listener with no render per move', () => {
+ const seen: string[] = [];
+ const {getByTestId} = render(
+ <Draggable
+ onPan={recognizer => {
+ seen.push(`${recognizer.state}:${recognizer.translation().x}`);
+ }}
+ />,
+ );
+ const surface = getByTestId('surface');
+ expect(renders).toBe(1);
+ touch('touchstart', surface, {id: 1, x: 0, y: 0}, 0);
+ for (let x = 6; x <= 36; x += 6) {
+ touch('touchmove', surface, {id: 1, x, y: 0}, x * 2);
+ }
+ touch('touchend', surface, {id: 1, x: 36, y: 0}, 80, true);
+ // The 10 px hysteresis is left out of the translation, as in UIKit.
+ expect(seen).toEqual([
+ 'began:2',
+ 'changed:8',
+ 'changed:14',
+ 'changed:20',
+ 'changed:26',
+ 'ended:26',
+ ]);
+ expect(renders).toBe(1);
+ });
+
+ it('keeps one recognizer across renders and reads the newest listener', () => {
+ const identities = new Set<PanGestureRecognizer>();
+ const first = vi.fn();
+ const second = vi.fn();
+ const {getByTestId, rerender} = render(
+ <Draggable onPan={first} onRecognizer={r => identities.add(r)} />,
+ );
+ rerender(
+ <Draggable onPan={second} onRecognizer={r => identities.add(r)} />,
+ );
+ expect(identities.size).toBe(1);
+ const surface = getByTestId('surface');
+ touch('touchstart', surface, {id: 2, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 2, x: 30, y: 0}, 16);
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ touch('touchend', surface, {id: 2, x: 30, y: 0}, 32, true);
+ });
+
+ it('cancels a gesture in flight when it is disabled, without calling the listener from the effect', () => {
+ const states: string[] = [];
+ // A listener of the recognizer's own, outside the hook, hears the cancel.
+ const heard: string[] = [];
+ let pan: PanGestureRecognizer | null = null;
+ const {getByTestId, rerender} = render(
+ <Draggable
+ onPan={r => states.push(r.state)}
+ onRecognizer={r => {
+ if (pan == null) {
+ pan = r;
+ r.addListener(current => heard.push(current.state));
+ }
+ }}
+ />,
+ );
+ const surface = getByTestId('surface');
+ touch('touchstart', surface, {id: 3, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 3, x: 30, y: 0}, 16);
+ act(() => {
+ rerender(
+ <Draggable onPan={r => states.push(r.state)} isEnabled={false} />,
+ );
+ });
+ // Disabling cancels the gesture; its attachment then goes (FR24), which
+ // leaves the recognizer at rest. The hook reports nothing from the effect.
+ expect(heard).toContain('cancelled');
+ expect(pan!.state).not.toBe('changed');
+ expect(states).toEqual(['began']);
+ touch('touchend', surface, {id: 3, x: 30, y: 0}, 32, true);
+ expect(states).toEqual(['began']);
+ });
+
+ it('follows the element when the node behind the ref is replaced', () => {
+ const onPan = vi.fn();
+ function Swappable({tag}: {tag: 'div' | 'section'}) {
+ const ref = useRef<HTMLElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ onPan,
+ );
+ const Tag = tag;
+ return <Tag data-testid="surface" ref={ref as never} />;
+ }
+ const {getByTestId, rerender} = render(<Swappable tag="div" />);
+ const first = getByTestId('surface');
+ rerender(<Swappable tag="section" />);
+ const second = getByTestId('surface');
+ expect(second).not.toBe(first);
+ touch('touchstart', first, {id: 6, x: 0, y: 0}, 0);
+ touch('touchmove', first, {id: 6, x: 30, y: 0}, 16);
+ touch('touchend', first, {id: 6, x: 30, y: 0}, 32, true);
+ expect(onPan).not.toHaveBeenCalled();
+ touch('touchstart', second, {id: 7, x: 0, y: 0}, 100);
+ touch('touchmove', second, {id: 7, x: 30, y: 0}, 116);
+ expect(onPan).toHaveBeenCalled();
+ touch('touchend', second, {id: 7, x: 30, y: 0}, 132, true);
+ });
+
+ it('reports cancelled to a handler that disables the recognizer itself, from that handler', () => {
+ const states: string[] = [];
+ let pan: PanGestureRecognizer | null = null;
+ const {getByTestId} = render(
+ <Draggable
+ onPan={r => states.push(r.state)}
+ onRecognizer={r => {
+ pan = r;
+ }}
+ />,
+ );
+ const surface = getByTestId('surface');
+ touch('touchstart', surface, {id: 6, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 6, x: 30, y: 0}, 16);
+ // A handler (here, the test) turns it off: UIKit's .cancelled, at once.
+ (pan as PanGestureRecognizer | null)?.setEnabled(false);
+ expect(states).toEqual(['began', 'cancelled']);
+ touch('touchend', surface, {id: 6, x: 30, y: 0}, 32, true);
+ });
+
+ it('attaches nothing while disabled: no touch-action, no gesture (FR24)', () => {
+ const states: string[] = [];
+ const {getByTestId, rerender} = render(
+ <Draggable onPan={r => states.push(r.state)} />,
+ );
+ const surface = getByTestId('surface');
+ expect(surface.hasAttribute(TOUCH_ACTION_ATTRIBUTE)).toBe(true);
+ act(() => {
+ rerender(
+ <Draggable onPan={r => states.push(r.state)} isEnabled={false} />,
+ );
+ });
+ // Disabling detaches: the host takes its touch-action off the element.
+ expect(surface.hasAttribute(TOUCH_ACTION_ATTRIBUTE)).toBe(false);
+ touch('touchstart', surface, {id: 6, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 6, x: 30, y: 0}, 16);
+ touch('touchend', surface, {id: 6, x: 30, y: 0}, 32, true);
+ expect(states).toEqual([]);
+ act(() => {
+ rerender(<Draggable onPan={r => states.push(r.state)} />);
+ });
+ touch('touchstart', surface, {id: 8, x: 0, y: 0}, 100);
+ touch('touchmove', surface, {id: 8, x: 30, y: 0}, 116);
+ expect(states).toContain('began');
+ touch('touchend', surface, {id: 8, x: 30, y: 0}, 132, true);
+ });
+
+ it('follows the element behind the ref when it is replaced (INV6)', () => {
+ const states: string[] = [];
+ function Swapped({id}: {id: string}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ r => states.push(r.state),
+ );
+ return <div key={id} data-testid={id} ref={ref} />;
+ }
+ const {getByTestId, rerender} = render(<Swapped id="first" />);
+ act(() => {
+ rerender(<Swapped id="second" />);
+ });
+ const second = getByTestId('second');
+ touch('touchstart', second, {id: 9, x: 0, y: 0}, 0);
+ touch('touchmove', second, {id: 9, x: 30, y: 0}, 16);
+ expect(states).toContain('began');
+ touch('touchend', second, {id: 9, x: 30, y: 0}, 32, true);
+ });
+
+ it('ends a gesture in flight on unmount without calling the listener from the cleanup (INV2)', () => {
+ const states: string[] = [];
+ // A listener of the recognizer's own, outside the hook, hears the cancel.
+ const heard: string[] = [];
+ let pan: PanGestureRecognizer | null = null;
+ const {getByTestId, unmount} = render(
+ <Draggable
+ onPan={r => states.push(r.state)}
+ onRecognizer={r => {
+ if (pan == null) {
+ pan = r;
+ r.addListener(current => heard.push(current.state));
+ }
+ }}
+ />,
+ );
+ const surface = getByTestId('surface');
+ touch('touchstart', surface, {id: 5, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 5, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ unmount();
+ expect(heard).toContain('cancelled');
+ expect(states).toEqual(['began']);
+ });
+
+ it('ends a gesture in flight when the node is replaced without calling the listener from the effect (INV2)', () => {
+ const states: string[] = [];
+ function Swapped({id}: {id: string}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useGestureRecognizer(
+ ref,
+ () => new PanGestureRecognizer({direction: 'horizontal'}),
+ r => states.push(r.state),
+ );
+ return <div key={id} data-testid={id} ref={ref} />;
+ }
+ const {getByTestId, rerender} = render(<Swapped id="first" />);
+ const first = getByTestId('first');
+ touch('touchstart', first, {id: 10, x: 0, y: 0}, 0);
+ touch('touchmove', first, {id: 10, x: 30, y: 0}, 16);
+ expect(states).toEqual(['began']);
+ act(() => {
+ rerender(<Swapped id="second" />);
+ });
+ expect(states).toEqual(['began']);
+ });
+
+ it('keeps a recognizer that waits on one being disabled from calling its listener from the effect, and reports it after (INV2)', async () => {
+ const heard: string[] = [];
+ let inCommit = false;
+ function Pair({isDoubleTapEnabled}: {isDoubleTapEnabled: boolean}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const doubleTap = useGestureRecognizer(
+ ref,
+ () => new TapGestureRecognizer({numberOfTapsRequired: 2}),
+ () => {},
+ {isEnabled: isDoubleTapEnabled},
+ );
+ useGestureRecognizer(
+ ref,
+ () => new TapGestureRecognizer().requireToFail(doubleTap),
+ tap => heard.push(`${inCommit ? 'effect' : 'handler'}:${tap.state}`),
+ );
+ return <div data-testid="surface" ref={ref} />;
+ }
+ const {getByTestId, rerender} = render(<Pair isDoubleTapEnabled />);
+ const surface = getByTestId('surface');
+ touch('touchstart', surface, {id: 5, x: 10, y: 10}, 0);
+ touch('touchend', surface, {id: 5, x: 10, y: 10}, 40, true);
+ // The single tap waits for the double tap to fail.
+ expect(heard).toEqual([]);
+ inCommit = true;
+ act(() => {
+ rerender(<Pair isDoubleTapEnabled={false} />);
+ });
+ inCommit = false;
+ // Disabling the double tap fails it inside that Effect, and nothing
+ // reports there: the single tap it held back is not lost, it recognizes
+ // after React's update, where its listener reports as usual.
+ expect(heard.filter(entry => entry.startsWith('effect:'))).toEqual([]);
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(heard).toEqual(['handler:ended']);
+ });
+
+ it('detaches on unmount', () => {
+ const onPan = vi.fn();
+ const {getByTestId, unmount} = render(<Draggable onPan={onPan} />);
+ const surface = getByTestId('surface');
+ expect(surface.hasAttribute(TOUCH_ACTION_ATTRIBUTE)).toBe(true);
+ unmount();
+ expect(surface.hasAttribute(TOUCH_ACTION_ATTRIBUTE)).toBe(false);
+ touch('touchstart', surface, {id: 4, x: 0, y: 0}, 0);
+ touch('touchmove', surface, {id: 4, x: 30, y: 0}, 16);
+ expect(onPan).not.toHaveBeenCalled();
+ });
+});
+
+function Button({
+ onEvent,
+ cancelTravel,
+ isBraking,
+ isDisabled = false,
+}: {
+ onEvent: (event: ControlEvent) => void;
+ cancelTravel?: number;
+ isBraking?: () => boolean;
+ isDisabled?: boolean;
+}) {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => onEvent(event),
+ cancelTravel,
+ isBraking,
+ isEnabled: () => !isDisabled,
+ });
+ return (
+ <button data-testid="button" ref={ref} type="button">
+ Go
+ </button>
+ );
+}
+
+describe('usePressTracker', () => {
+ it('gives the host no listener while the control is disabled (FR24)', () => {
+ const add = vi.spyOn(document, 'addEventListener');
+ const remove = vi.spyOn(document, 'removeEventListener');
+ const {rerender, unmount} = render(
+ <Button onEvent={() => {}} isDisabled />,
+ );
+ const added = () =>
+ add.mock.calls.filter(([type]) => type === 'touchstart').length;
+ expect(added()).toBe(0);
+ rerender(<Button onEvent={() => {}} />);
+ expect(added()).toBe(1);
+ rerender(<Button onEvent={() => {}} isDisabled />);
+ expect(
+ remove.mock.calls.filter(([type]) => type === 'touchstart').length,
+ ).toBe(1);
+ unmount();
+ add.mockRestore();
+ remove.mockRestore();
+ });
+
+ it("keeps the tracker's own ancestor veto when the caller gives none: a single tap by its kind, nothing else with the same counts (architecture:react-component-runtime INV13)", () => {
+ let tracker: ReturnType<typeof usePressTracker> | null = null;
+ function Tracked() {
+ const ref = useRef<HTMLButtonElement>(null);
+ tracker = usePressTracker(ref);
+ return (
+ <button ref={ref} type="button">
+ Go
+ </button>
+ );
+ }
+ render(<Tracked />);
+ const tap = new TapGestureRecognizer({});
+ expect(tracker!.allowsAncestorRecognizer(tap)).toBe(false);
+ // A discrete recognizer that is not a tap, carrying the same counts.
+ const notATap = {
+ kind: 'swipe',
+ isDiscrete: true,
+ numberOfTapsRequired: 1,
+ numberOfTouchesRequired: 1,
+ view: null,
+ };
+ expect(tracker!.allowsAncestorRecognizer(notATap)).toBe(true);
+ });
+
+ it('rebuilds its tracker when trackingExpansion, highlightDelay, cancelTravel or quickTapFlash change', () => {
+ const trackers: unknown[] = [];
+ function Tracked(props: {
+ trackingExpansion?: number;
+ highlightDelay?: 'inScrollers' | 'always' | 'never';
+ cancelTravel?: number;
+ quickTapFlash?: number;
+ label?: string;
+ }) {
+ const ref = useRef<HTMLButtonElement>(null);
+ trackers.push(usePressTracker(ref, props));
+ return (
+ <button ref={ref} type="button">
+ {props.label ?? 'Go'}
+ </button>
+ );
+ }
+ const {rerender} = render(<Tracked cancelTravel={70} />);
+ rerender(<Tracked cancelTravel={70} label="Same options" />);
+ expect(trackers[1]).toBe(trackers[0]);
+ rerender(<Tracked cancelTravel={20} />);
+ expect(trackers[2]).not.toBe(trackers[1]);
+ rerender(<Tracked cancelTravel={20} trackingExpansion={30} />);
+ expect(trackers[3]).not.toBe(trackers[2]);
+ rerender(
+ <Tracked
+ cancelTravel={20}
+ trackingExpansion={30}
+ highlightDelay="never"
+ />,
+ );
+ expect(trackers[4]).not.toBe(trackers[3]);
+ rerender(
+ <Tracked
+ cancelTravel={20}
+ trackingExpansion={30}
+ highlightDelay="never"
+ quickTapFlash={0}
+ />,
+ );
+ expect(trackers[5]).not.toBe(trackers[4]);
+ });
+
+ it('reports UIControl events for a tap', () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId} = render(
+ <Button onEvent={event => events.push(event)} />,
+ );
+ const button = getByTestId('button');
+ touch('touchstart', button, {id: 5, x: 1, y: 1}, 0);
+ touch('touchend', button, {id: 5, x: 1, y: 1}, 50, true);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ });
+
+ it('ends a held press on unmount without calling back from the effect', () => {
+ const highlights: boolean[] = [];
+ const events: ControlEvent[] = [];
+ function HeldButton() {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ onHighlightChange: isHighlighted => highlights.push(isHighlighted),
+ });
+ return (
+ <button data-testid="held" ref={ref} type="button">
+ Go
+ </button>
+ );
+ }
+ const {getByTestId, unmount} = render(<HeldButton />);
+ touch('touchstart', getByTestId('held'), {id: 9, x: 1, y: 1}, 0);
+ const seenHighlights = [...highlights];
+ const seenEvents = [...events];
+ unmount();
+ expect(highlights).toEqual(seenHighlights);
+ expect(events).toEqual(seenEvents);
+ });
+
+ it('passes isBraking through to the tracker', () => {
+ const events: ControlEvent[] = [];
+ const isBraking = vi.fn(() => true);
+ function BrakingButton() {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {
+ onControlEvent: event => events.push(event),
+ isBraking,
+ });
+ return (
+ <button data-testid="braking" ref={ref} type="button">
+ Go
+ </button>
+ );
+ }
+ const {getByTestId} = render(<BrakingButton />);
+ const button = getByTestId('braking');
+ touch('touchstart', button, {id: 8, x: 1, y: 1}, 0);
+ touch('touchend', button, {id: 8, x: 1, y: 1}, 50, true);
+ expect(isBraking).toHaveBeenCalled();
+ expect(events).not.toContain('touchDown');
+ });
+
+ it("uses the caller's scroll brake", () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId} = render(
+ <Button onEvent={event => events.push(event)} isBraking={() => true} />,
+ );
+ const button = getByTestId('button');
+ touch('touchstart', button, {id: 8, x: 1, y: 1}, 0);
+ touch('touchend', button, {id: 8, x: 1, y: 1}, 50, true);
+ expect(events).toEqual([]);
+ });
+
+ it('tracks the element behind the ref when it is replaced (INV6)', () => {
+ const events: ControlEvent[] = [];
+ function Swapped({id}: {id: string}) {
+ const ref = useRef<HTMLButtonElement>(null);
+ usePressTracker(ref, {onControlEvent: event => events.push(event)});
+ return <button key={id} data-testid={id} ref={ref} type="button" />;
+ }
+ const {getByTestId, rerender} = render(<Swapped id="first" />);
+ act(() => {
+ rerender(<Swapped id="second" />);
+ });
+ const second = getByTestId('second');
+ touch('touchstart', second, {id: 10, x: 1, y: 1}, 0);
+ touch('touchend', second, {id: 10, x: 1, y: 1}, 50, true);
+ expect(events).toEqual(['touchDown', 'touchUpInside']);
+ });
+
+ it('presses nothing for a touch that brakes a scroll', () => {
+ const events: ControlEvent[] = [];
+ const {getByTestId} = render(
+ <Button onEvent={event => events.push(event)} />,
+ );
+ const button = getByTestId('button');
+ const brake = vi
+ .spyOn(getGestureHost(document), 'isScrollBraking')
+ .mockReturnValue(true);
+ touch('touchstart', button, {id: 7, x: 1, y: 1}, 0);
+ touch('touchend', button, {id: 7, x: 1, y: 1}, 50, true);
+ expect(events).toEqual([]);
+ brake.mockRestore();
+ });
+});
diff --git a/packages/core/src/gestures/index.ts b/packages/core/src/gestures/index.ts
new file mode 100644
index 0000000000..9cd69efafd
--- /dev/null
+++ b/packages/core/src/gestures/index.ts
@@ -0,0 +1,79 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file index.ts
+ * @input The modules of packages/core/src/gestures
+ * @output Re-exports the gesture system for core's own components
+ * @position Core's own barrel. Not exported from the package.
+ */
+
+export {GestureArena, browserClock} from './GestureArena';
+export type {
+ ArenaBeganInput,
+ ClickDisposition,
+ GestureArenaOptions,
+ GestureClock,
+} from './GestureArena';
+export {GestureHost, getGestureHost} from './GestureHost';
+export type {AttachOptions, GestureHostOptions} from './GestureHost';
+export {
+ GestureRecognizer,
+ isActive,
+ isTerminal,
+ isTransitionAllowed,
+} from './GestureRecognizer';
+export type {
+ GestureListener,
+ GestureRecognizerOptions,
+ GestureTransitionListener,
+ NativeTouchBehavior,
+} from './GestureRecognizer';
+export {
+ attachTapHaptic,
+ canVibrate,
+ playHaptic,
+ supportsSwitchControl,
+} from './haptics';
+export {LongPressGestureRecognizer} from './LongPressGestureRecognizer';
+export type {LongPressGestureRecognizerOptions} from './LongPressGestureRecognizer';
+export {createNativeScrollProbe, parseTouchAction} from './nativeScroll';
+export {PanGestureRecognizer} from './PanGestureRecognizer';
+export type {
+ PanDirection,
+ PanGestureRecognizerOptions,
+} from './PanGestureRecognizer';
+export {PinchGestureRecognizer} from './PinchGestureRecognizer';
+export type {PinchGestureRecognizerOptions} from './PinchGestureRecognizer';
+export {PRESS_PROFILES, createPressTracker} from './PressTracker';
+export type {
+ ControlEvent,
+ PressBounds,
+ PressHighlightDelay,
+ PressProfile,
+ PressProfileName,
+ PressTracker,
+ PressTrackerOptions,
+} from './PressTracker';
+export {ScreenEdgePanGestureRecognizer} from './ScreenEdgePanGestureRecognizer';
+export type {
+ ScreenEdge,
+ ScreenEdgePanGestureRecognizerOptions,
+} from './ScreenEdgePanGestureRecognizer';
+export {SwipeGestureRecognizer} from './SwipeGestureRecognizer';
+export type {
+ SwipeDirection,
+ SwipeGestureRecognizerOptions,
+} from './SwipeGestureRecognizer';
+export {TapGestureRecognizer} from './TapGestureRecognizer';
+export type {TapGestureRecognizerOptions} from './TapGestureRecognizer';
+export {deriveTouchAction, gestureHostStyle} from './touchAction';
+export type {GestureHostStyle} from './touchAction';
+export type * from './types';
+export {DEFAULT_ENVIRONMENT} from './types';
+export {useGestureRecognizer, usePressTracker} from './useGestureRecognizer';
+export type {
+ UseGestureRecognizerOptions,
+ UsePressTrackerOptions,
+} from './useGestureRecognizer';
+export {VelocityTracker} from './VelocityTracker';
+export type {VelocityTrackerOptions} from './VelocityTracker';
diff --git a/packages/core/src/gestures/useGestureRecognizer.ts b/packages/core/src/gestures/useGestureRecognizer.ts
new file mode 100644
index 0000000000..8dcb3080d9
--- /dev/null
+++ b/packages/core/src/gestures/useGestureRecognizer.ts
@@ -0,0 +1,305 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useGestureRecognizer.ts
+ * @input An element ref, a recognizer factory and a gesture listener; or an
+ * element ref and press tracker options
+ * @output Exports useGestureRecognizer and usePressTracker
+ * @position React face of packages/core/src/gestures
+ *
+ * The recognizer is created once and keeps its identity for the life of the
+ * component, so relationships set up at creation (`requireToFail`,
+ * `recognizeSimultaneouslyWith`) hold. The listener is read through a ref:
+ * passing a new function each render re-attaches nothing, and a gesture
+ * costs no React render at all — the listener runs inside the input event
+ * and writes to the DOM itself. The recognizer attaches in a layout effect,
+ * so its `touch-action` is in place before the browser can see a finger.
+ *
+ * SYNC: When modified, update useGestureRecognizer.test.tsx and README.md.
+ */
+
+import {useEffect, useMemo, useRef, useState, type RefObject} from 'react';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {getGestureHost} from './GestureHost';
+import type {GestureRecognizer} from './GestureRecognizer';
+import {
+ createPressTracker,
+ vetoesSingleTap,
+ type PressTracker,
+ type PressTrackerOptions,
+} from './PressTracker';
+
+export interface UseGestureRecognizerOptions {
+ /**
+ * Live toggle; turning it off mid-gesture cancels the gesture. That cancel
+ * does not call `onGesture`: it comes from the render that turned the
+ * recognizer off, and the code that turned it off already knows.
+ * @default true
+ */
+ isEnabled?: boolean;
+ /** Let the host set touch-action (and long-press callout) styles. @default true */
+ manageStyle?: boolean;
+}
+
+/**
+ * How many Effects are driving the gesture system right now (an `isEnabled`
+ * sync, a detach, a press tracker's release or host update). While one runs
+ * no hook calls its caller back (react-component-runtime INV2, INV3): the
+ * recognizer it stops is cancelled silently, and what that stop unblocks (a
+ * recognizer that required it to fail) resolves in the arena's next pass, a
+ * microtask later, where its listener reports as usual
+ * (`deferringResolution`).
+ */
+let effectDepth = 0;
+
+/** Runs `drive` as an Effect's work on the gesture system (see effectDepth). */
+function driveFromEffect(drive: () => void): void {
+ effectDepth += 1;
+ try {
+ drive();
+ } finally {
+ effectDepth -= 1;
+ }
+}
+
+/**
+ * Runs `body`, which stops `recognizer` from an Effect, with its arena leaving
+ * what the stop unblocks to a pass a microtask later
+ * (GestureArena.deferResolution): a recognizer that required the stopped one
+ * to fail recognizes there, outside the Effect, and its listener reports as
+ * usual. A recognizer that has met no touch has no arena, and nothing waits on
+ * it.
+ */
+function deferringResolution(
+ recognizer: GestureRecognizer,
+ body: () => void,
+): void {
+ const arena = recognizer.arena;
+ if (arena == null) {
+ body();
+ return;
+ }
+ arena.deferResolution(body);
+}
+
+/**
+ * Attach a recognizer to the element behind `ref`.
+ *
+ * @example
+ * ```
+ * const pan = useGestureRecognizer(
+ * ref,
+ * () => new PanGestureRecognizer({direction: 'vertical'}),
+ * recognizer => {
+ * ref.current.style.transform = `translateY(${recognizer.translation().y}px)`;
+ * },
+ * );
+ * ```
+ */
+export function useGestureRecognizer<R extends GestureRecognizer>(
+ ref: RefObject<Element | null>,
+ create: () => R,
+ onGesture?: (recognizer: R) => void,
+ options: UseGestureRecognizerOptions = {},
+): R {
+ const [recognizer] = useState(create);
+ const onGestureRef = useRef(onGesture);
+ useIsomorphicLayoutEffect(() => {
+ onGestureRef.current = onGesture;
+ });
+ const {isEnabled = true, manageStyle = true} = options;
+
+ // Syncs the recognizer's target-action listeners with the caller's
+ // callback (read through a ref, so a new function re-subscribes nothing).
+ useEffect(
+ () =>
+ recognizer.addListener(current => {
+ if (effectDepth === 0) {
+ onGestureRef.current?.(current);
+ }
+ }),
+ [recognizer],
+ );
+
+ // Syncs the recognizer's `isEnabled` (UIKit's). It runs first, so disabling
+ // cancels a gesture in flight before its attachment goes, and that cancel,
+ // with whatever it settles in the arena, reaches no caller callback.
+ useIsomorphicLayoutEffect(() => {
+ driveFromEffect(() =>
+ deferringResolution(recognizer, () => recognizer.setEnabled(isEnabled)),
+ );
+ }, [recognizer, isEnabled]);
+
+ // Syncs the document's gesture host with the element behind `ref`: attached
+ // while enabled, re-attached when the node is replaced. A disabled gesture
+ // is not attached at all: no listener and no `touch-action` of its own on
+ // the element (spec:AST-094 FR24). Detaching (an unmount, a replaced node)
+ // cancels a gesture in flight, and that cancel, run in an Effect, reaches
+ // no caller callback (react-component-runtime INV2).
+ useNodeAttachment(
+ ref,
+ element => {
+ if (!isEnabled) {
+ return null;
+ }
+ const detach = getGestureHost(element.ownerDocument).attach(
+ element,
+ recognizer,
+ {manageStyle},
+ );
+ return () =>
+ driveFromEffect(() => deferringResolution(recognizer, detach));
+ },
+ [recognizer, manageStyle, isEnabled],
+ );
+
+ return recognizer;
+}
+
+export type UsePressTrackerOptions = Omit<
+ PressTrackerOptions,
+ 'getBounds' | 'view'
+>;
+
+/**
+ * Track presses on the element behind `ref` with UIControl semantics. The
+ * callbacks are read through a ref, like a recognizer's listener. Releasing
+ * the element (unmount, or a replaced node) ends any press without calling
+ * them: that release runs in an Effect, which never calls a caller's
+ * callback (react-component-runtime INV2, INV3).
+ */
+export function usePressTracker(
+ ref: RefObject<Element | null>,
+ options: UsePressTrackerOptions = {},
+): PressTracker {
+ const optionsRef = useRef(options);
+ useIsomorphicLayoutEffect(() => {
+ optionsRef.current = options;
+ });
+ const {trackingExpansion, highlightDelay, cancelTravel, quickTapFlash} =
+ options;
+ // The tracker reads these four when it is built: a change rebuilds it (the
+ // attachment below moves to the new one and disposes the old), and the new
+ // values apply from the next touch. The callbacks, the brake included, are
+ // read through the ref on every touch.
+ const tracker = useMemo(
+ () =>
+ createPressTracker({
+ getBounds: () => ref.current?.getBoundingClientRect() ?? null,
+ get view() {
+ return ref.current;
+ },
+ onControlEvent: (event, touch) => {
+ if (effectDepth === 0) {
+ optionsRef.current.onControlEvent?.(event, touch);
+ }
+ },
+ onHighlightChange: isHighlighted => {
+ if (effectDepth === 0) {
+ optionsRef.current.onHighlightChange?.(isHighlighted);
+ }
+ },
+ trackingExpansion,
+ highlightDelay,
+ cancelTravel,
+ quickTapFlash,
+ // The caller's veto, read on every touch, else the tracker's own.
+ vetoesAncestorRecognizer: recognizer =>
+ (optionsRef.current.vetoesAncestorRecognizer ?? vetoesSingleTap)(
+ recognizer,
+ ),
+ isEnabled: () => optionsRef.current.isEnabled?.() ?? true,
+ // A finger that brakes a scroll it set moving presses nothing
+ // (GestureHost.isScrollBraking), unless the caller decides; the tracker
+ // asks only for a finger (spec:AST-094 FR11).
+ isBraking: touch => {
+ const element = ref.current;
+ return (
+ optionsRef.current.isBraking?.(touch) ??
+ (element != null &&
+ getGestureHost(element.ownerDocument).isScrollBraking(element))
+ );
+ },
+ }),
+ [ref, trackingExpansion, highlightDelay, cancelTravel, quickTapFlash],
+ );
+
+ // Syncs the document's gesture host with the element behind `ref`: the
+ // tracker is its press consumer, moved when the node is replaced, and a
+ // press in progress ends with it.
+ useNodeAttachment(
+ ref,
+ element => {
+ const detach = getGestureHost(element.ownerDocument).attachConsumer(
+ element,
+ tracker,
+ );
+ return () =>
+ driveFromEffect(() => {
+ detach();
+ tracker.dispose();
+ });
+ },
+ [tracker],
+ );
+
+ // Syncs the host's listeners with the tracker's enabled state, which can
+ // change with any render: the host listens only while an enabled control
+ // is attached (spec:AST-094 FR24).
+ useIsomorphicLayoutEffect(() => {
+ const element = ref.current;
+ if (element != null) {
+ driveFromEffect(() =>
+ getGestureHost(element.ownerDocument).update(element),
+ );
+ }
+ });
+
+ return tracker;
+}
+
+/**
+ * Keeps `attach` applied to the element behind `ref`: checked after every
+ * render, so a replaced node (a re-keyed or swapped element) is detached and
+ * the new one attached, a removed one detached, and a change in `deps`
+ * re-attaches (`architecture:react-component-runtime` INV6). Costs no render.
+ * `attach` returns its detach, or null for nothing attached.
+ */
+function useNodeAttachment<T extends Element>(
+ ref: RefObject<T | null>,
+ attach: (element: T) => (() => void) | null,
+ deps: ReadonlyArray<unknown>,
+): void {
+ const attachedRef = useRef<{
+ element: T;
+ deps: ReadonlyArray<unknown>;
+ detach: (() => void) | null;
+ } | null>(null);
+ // Syncs the attachment with the DOM node the caller's ref holds after
+ // this commit.
+ useIsomorphicLayoutEffect(() => {
+ const element = ref.current;
+ const current = attachedRef.current;
+ if (
+ current != null &&
+ current.element === element &&
+ current.deps.length === deps.length &&
+ current.deps.every((dep, index) => Object.is(dep, deps[index]))
+ ) {
+ return;
+ }
+ current?.detach?.();
+ attachedRef.current =
+ element == null ? null : {element, deps, detach: attach(element)};
+ });
+ // Detaches at unmount.
+ useIsomorphicLayoutEffect(
+ () => () => {
+ attachedRef.current?.detach?.();
+ attachedRef.current = null;
+ },
+ [],
+ );
+}
diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md
index e22ced5450..f21c9669b8 100644
--- a/packages/core/src/motion/MEASUREMENTS.md
+++ b/packages/core/src/motion/MEASUREMENTS.md
@@ -110,7 +110,8 @@ during the motion; `velocity(in:)` is 0.2 × the newest event's
instantaneous velocity + 0.8 × the previous one's (it reproduces every value
UIKit reported on six recorded streams), does not decay through a rest and
ignores the lift: the table keeps that one filter and no least-squares
-estimator (`spec:AST-100` FR2); a sheet over a scrolled list leaves the whole
+estimator (`spec:AST-100` FR2; M-G14 is the scroll-view release blend still to
+confirm, and M-G16 is Astryx’s stillness reset, not a UIKit value); a sheet over a scrolled list leaves the whole
drag to the list (no mid-gesture handoff), so the table carries no handoff
slop (`spec:AST-094` FR14).
diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md
index b14dc91c5d..b052a57755 100644
--- a/packages/core/src/motion/README.md
+++ b/packages/core/src/motion/README.md
@@ -11,45 +11,72 @@ so each keeps its measured value; no shipped component reads the roles yet.
## Files
-| File | What it is |
-| ---------------------- | -------------------------------------------------------------------------------------------------------------------------- |
-| `uikit/` | THE constants table: every spring, duration, deceleration rate, rubber-band constant and curve, with its source. |
-| `uikit/springs.ts` | Interaction springs (navigation, sheets, alerts, menus, controls, keyboard, banners) and the SwiftUI / UIKit presets. |
-| `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, paging, `delaysContentTouches`, scroll to top. |
-| `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. |
-| `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. |
-| `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). |
-| `MEASUREMENTS.md` | The UIKit reference captures each unconfirmed value still needs. |
-| `spring.ts` | Closed-form damped spring, every Apple parameterization, settling duration, a spring chasing a moving target. |
-| `decay.ts` | UIScrollView's momentum coast. |
-| `coast.ts` | A release's momentum curves for `animator.decay`: the coast, the edge spring, a release past an edge. |
-| `rubberBand.ts` | UIScrollView's resistance past an edge, and its inverse. |
-| `projection.ts` | Release targets: the rest point nearest the projected coast. |
-| `resolveSnapPoint.ts` | Release policy: the snap point a release lands on (flick, back-out cancel, step limit), on `selectSnapPoint`. Internal. |
-| `selectPage.ts` | Paging: at most one page per release, on `resolveSnapPoint`. |
-| `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). |
-| `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. |
-| `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. |
+| File | What it is |
+| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `uikit/` | THE constants table: every spring, duration, deceleration rate, rubber-band constant and curve, with its source. |
+| `uikit/springs.ts` | Interaction springs (navigation, sheets, alerts, menus, controls, keyboard, banners) and the SwiftUI / UIKit presets. |
+| `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, paging, `delaysContentTouches`, scroll to top. |
+| `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. |
+| `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. |
+| `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). |
+| `roles.ts` | Motion roles: each spring, duration and curve of a registered table, named by its path, and its CSS variable. |
+| `resolveMotion.ts` | A role's value: its table value, as the per-role tables stay internal (`spec:AST-094` DEC-15). |
+| `MEASUREMENTS.md` | The UIKit reference captures each unconfirmed value still needs. |
+| `spring.ts` | Closed-form damped spring, every Apple parameterization, settling duration, a spring chasing a moving target. |
+| `decay.ts` | UIScrollView's momentum coast. |
+| `coast.ts` | A release's momentum curves for `animator.decay`: the coast, the edge spring, a release past an edge. |
+| `rubberBand.ts` | UIScrollView's resistance past an edge, and its inverse. |
+| `projection.ts` | Release targets: the rest point nearest the projected coast. |
+| `resolveSnapPoint.ts` | Release policy: the snap point a release lands on (flick, back-out cancel, step limit), on `selectSnapPoint`. Internal. |
+| `selectPage.ts` | Paging: at most one page per release, on `resolveSnapPoint`. |
+| `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). |
+| `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. |
+| `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. |
+| `__tests__/animator.interaction.browser.spec.ts` | Browser proofs on the interaction harness (Chromium and WebKit): busy main thread, end state through a block, no Layout / Paint, seeked curves, a dialog's backdrop. |
Component-specific values (a sheet's detents, a switch's geometry, a context
menu's timeline) live in a domain file per component, `uikit/<component>.ts`,
under the same rules.
+## Motion roles
+
+The motion roles are the springs, durations and curves `spec:AST-094` FR4
+names for their use (`springs.settle`, `timing.stateChangeMs`,
+`timing.curves.move`, …): a shared table lists them when it registers
+(`roles`), and every other value, a component's measured spring included, is
+a plain constant. The per-role tables stay internal (`spec:AST-094` DEC-15): a
+role plays its table value, and nothing reads its CSS variable
+(`--motion-springs-settle`), so no page or theme style sets a role. A table's
+roles exist once its `register<Name>Table()` has run: the animator registers
+the Reduce Motion fade's curve, and code that plays the shared springs calls
+`registerSpringsTable()` before its first motion. The animator resolves each
+role it is handed when the motion starts; code that times something itself
+calls `resolveMotion(element, timing, 'stateChangeMs')`. Gesture thresholds and
+the timings that decide who gets a touch are not roles.
+
## Animator
```
import {createAnimator} from '../motion/animator';
import {coast} from '../motion/coast';
import {solveSpringTowardRamp, toSpring} from '../motion/spring';
-import {springs} from '../motion/uikit';
+import {resolveMotion} from '../motion/resolveMotion';
+import {registerSpringsTable, springs} from '../motion/uikit';
+
+// Once, so the springs are registered as their roles:
+registerSpringsTable();
const animator = createAnimator(sheet);
+// The animator plays a motion role (spec:AST-094 FR4), its table value, as the
+// per-role tables stay internal (DEC-15); math on a spring reads the role with
+// resolveMotion.
+const spring = springs.settle;
// A drag writes one style per frame and never renders:
animator.set({y: offset});
// The finger lifts: spring to the detent with the release velocity (px/s).
-const handle = animator.animate({y: detent}, {spring: springs.sheetDetent, velocity: {y: 1200}});
+const handle = animator.animate({y: detent}, {spring, velocity: {y: 1200}});
// A finger lands mid-flight: where is the sheet right now, how fast?
const y = animator.get('y', event.timeStamp);
@@ -63,7 +90,7 @@ animator.decay(coast(animator, {x: velocityX}, {bounds: {x: {min: -maxScroll, ma
// scale falls at 0.16/s and the platter follows it on a spring. Press
// feedback has no fade of its own, so it is skipped under Reduce Motion.
if (animator.reducedMotion() === 'off') {
- const ramp = solveSpringTowardRamp(toSpring(springs.contextMenuLift), {
+ const ramp = solveSpringTowardRamp(toSpring(resolveMotion(sheet, springs.quickChange)), {
from: 1,
target: 1,
slope: -0.16,
@@ -80,7 +107,9 @@ await handle.finished; // true if it ran to the end, false if interrupted
- `get` / `getVelocity` evaluate the curves; the DOM is never read.
- Promotion: every animation the animator creates, and every `set`, gives its
channels a compositing layer in the same task (inline `will-change`, merged
- with the element's own), cleared 500 ms after the last motion. Mobile Safari
+ with the element's own), cleared 500 ms after the last motion.
+ `set(values, {promote: false})` writes without one, for a one-off switch
+ that must not give its element a layer. Mobile Safari
needs it to run a curve through a blocked main thread. A pseudo-element is
promoted through `--astryx-motion-will-change-<pseudo>` on its host; its
style opts in with
@@ -96,11 +125,19 @@ await handle.finished; // true if it ran to the end, false if interrupted
velocity unless a velocity is handed in, so retargeting is continuous
(`handle.retarget(to)` keeps the call's spring).
- A call from rest gets no start time, so the browser starts it when it
- commits it, as Core Animation does: in Chromium a block before that frame
- delays the motion instead of skipping into it (WebKit starts it at the
- frame before the block). Everything the call starts shares that start
+ commits it, as Core Animation does: a block before that frame delays the
+ motion instead of skipping into it. WebKit dates the start at the frame
+ before the block, so when the task that created the animations (a
+ presented call's second frame) runs on over two frames, the start moves to
+ the call's first read after it, with every call of that task. Everything
+ the call starts shares that start
(`handle.started`); a retarget keeps an explicit one, and `{at}` puts
- several animators on one clock.
+ several animators on one clock. `{start: 'commit'}` lets the browser date
+ a retarget too; `{start: 'presented'}` waits two frames, until the
+ element at rest has been presented. `handle.curve(property)` is the curve
+ a call plays, for a companion to follow. `{additive: true}` retargets the
+ way UIKit does: the old curve keeps going and the change is added on top,
+ in one animation.
- Reduced Motion (`prefers-reduced-motion: reduce`, design:reduced-motion):
every `animate` and `play` is replaced and nothing moves, scales or
springs. On a coarse primary pointer, or for a call started by a touch
@@ -134,11 +171,14 @@ await handle.finished; // true if it ran to the end, false if interrupted
### How it stays on the compositor
-Each curve is baked into keyframes, sampled adaptively until linear
-interpolation is within 0.05 px, and played with `easing: linear` on one
-start time. The element's inline style already holds the end values,
-and the keyframes hold the end state for a few seconds past the curve's end;
-the main thread drops the animation as soon as it runs after that end. So the
+Each curve is baked into keyframes on a 30 Hz grid, refined until linear
+interpolation is within each channel's tolerance (`SAMPLE_TOLERANCE`, a
+quarter pixel for a move), and played with `easing: linear` on one start
+time. The element's inline style holds the
+value the curve starts from, where the element is, never where it is going;
+the keyframes hold the end state for a minute past the curve's end
+(`END_HOLD_MS`), and the main thread retires a finished animation as soon as
+it runs after that end, writing the end values inline in the same task. So the
frame an animation ends needs no main thread and shows no flicker, even when
the main thread is blocked as the curve ends (WebKit's compositor otherwise
falls back to the last value its main thread committed, mid-flight).
@@ -171,6 +211,35 @@ simulation of the deceleration rate and to WWDC18's projection function;
`rubberBand.ts` to UIScrollView's overscroll measured on the simulator.
`uikit/values.test.ts` plays the table's values through this math.
+## Browser proofs
+
+`__tests__/animator.interaction.browser.spec.ts` runs on the interaction
+harness: the real animator, bundled from source onto a blank fixture page, in
+Chromium and WebKit on the phone profile.
+
+- A slow spring keeps advancing on every screencast frame while the main
+ thread is blocked for 1 s, and every frame sits on the analytic curve with
+ one consistent time offset.
+- A spring that ends inside the block keeps showing its end state. Without the
+ animator's end-state hold, WebKit falls back to a mid-flight value.
+- No Layout or Paint runs while it animates (Chromium trace).
+- Seeked to fixed times, the engine plays the analytic curve within the
+ sampling tolerance, with every channel on one start time.
+- A finished animation leaves the element within a frame or two of the curve's
+ end.
+- A dialog's `::backdrop` follows the curve when seeked and holds its end
+ state.
+- A scope that sets `springs.settle`'s variable changes nothing: the per-role
+ tables stay internal (DEC-15), so the engine plays the table's spring there
+ too.
+
+```
+pnpm test:interaction packages/core/src/motion
+```
+
+Where WebKit cannot launch on the host, the harness's container script runs
+it. The iOS Safari check is the same proof on the iOS simulator.
+
## Sources
Every value in `uikit/` carries its source next to it, as a JSDoc tag on the
diff --git a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts
new file mode 100644
index 0000000000..d7da114d90
--- /dev/null
+++ b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts
@@ -0,0 +1,843 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file animator.interaction.browser.spec.ts
+ * @input The motion source (animator, springs, spring math) bundled with
+ * esbuild onto a blank fixture page; the interaction harness's screencast,
+ * busy-main-thread and trace instruments; Chromium and WebKit on the phone
+ * profile
+ * @output Proof that the animator's motion runs on the compositor
+ * (`spec:AST-094` FR5): a spring keeps advancing every frame through a 1 s
+ * main-thread block, on its analytic curve; a spring that ends inside the
+ * block keeps its end state; no Layout or Paint runs while it animates
+ * (Chromium trace); the engine plays the analytic curve when seeked; a
+ * finished animation leaves within a frame or two of the curve's end; a
+ * fade-in on an element its stylesheet hides stays visible once it retires;
+ * a dialog's ::backdrop follows the curve and holds its end state; a frame
+ * painted before the compositor has a curve shows the element where it is;
+ * a role variable set on a scope changes nothing, as the per-role tables
+ * stay internal (DEC-15)
+ * @position Browser proof for animator.ts, run by `pnpm test:interaction`;
+ * jsdom runs no animations
+ */
+
+import {fileURLToPath} from 'node:url';
+import {
+ blockMainThread,
+ busyWindowProof,
+ countBetween,
+ markElement,
+ startScreencast,
+ traceRendering,
+ trackMarker,
+} from '@astryxdesign/interaction-harness';
+import {expect, test, type Page} from '@playwright/test';
+import {build} from 'esbuild';
+import type {Animator, MotionHandle} from '../animator';
+import type * as MotionBundle from './motionBundle';
+
+let script = '';
+
+test.beforeAll(async () => {
+ const result = await build({
+ entryPoints: [fileURLToPath(new URL('./motionBundle.ts', import.meta.url))],
+ bundle: true,
+ write: false,
+ format: 'iife',
+ globalName: 'Motion',
+ target: 'es2022',
+ });
+ script = result.outputFiles[0].text;
+});
+
+/**
+ * A slow, critically damped spring: over 1 px per frame through the whole
+ * block, so every frame inside it has to move.
+ */
+const SLOW = {response: 2, dampingRatio: 1};
+/** Settles about 450 ms into the block. */
+const FAST = {response: 0.25, dampingRatio: 1};
+const TRAVEL = 300;
+/** One frame at 60 Hz, in ms. */
+const FRAME_MS = 1000 / 60;
+/** The marker chip sits this far inside the box\u2019s top-left corner. */
+const MARKER_INSET = 8;
+
+/**
+ * Waits for the held-dip call to end: on the call's own `finished`, then on
+ * the browser's own animations still running or waiting for their first
+ * frame, never on a count of frames. The dip lands on a timer due on the
+ * call's clock, which a loaded page runs whenever it can, so a frame window
+ * can close before the landing. Reads no animator value: a call would look
+ * for the start again.
+ */
+async function dipDone(page: Page) {
+ await page.evaluate(async () => {
+ await (window as unknown as {dip: MotionHandle}).dip.finished;
+ const box = document.getElementById('box') as HTMLElement;
+ await Promise.all(
+ box
+ .getAnimations()
+ .filter(
+ animation => animation.pending || animation.playState === 'running',
+ )
+ .map(async animation =>
+ animation.finished.catch((error: unknown) => {
+ // A retired animation's cancel rejects its finished with an
+ // AbortError; any other rejection is a real failure.
+ if (!(
+ error instanceof DOMException && error.name === 'AbortError'
+ )) {
+ throw error;
+ }
+ }),
+ ),
+ );
+ });
+}
+
+// A real navigation (not setContent): the page keeps its own window.
+async function open(page: Page) {
+ const html = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">
+<style>
+ html, body { margin: 0; background: #fff; }
+ #box { position: absolute; top: 40px; left: 0; width: 48px; height: 48px; background: #36c; }
+</style>
+<div id="box"></div>
+<script>${script}</script>
+<script>window.animator = Motion.createAnimator(document.getElementById('box'));</script>`;
+ await page.route('http://motion.test/', async route =>
+ route.fulfill({contentType: 'text/html', body: html}),
+ );
+ await page.goto('http://motion.test/');
+}
+
+/**
+ * Starts a spring of TRAVEL px on x, blocks the main thread for 1 s mid-flight
+ * and returns the screencast frames with the run\u2019s clock (epoch ms).
+ */
+async function blockedRun(
+ page: Page,
+ spring: {response: number; dampingRatio: number},
+) {
+ await open(page);
+ const box = page.locator('#box');
+ await markElement(box, {inset: MARKER_INSET});
+ const cast = await startScreencast(page);
+ // The curve starts when the browser commits it (handle.started).
+ const start = await page.evaluate(
+ async ({spring: s, travel}) => {
+ const handle = window.animator.animate({x: travel}, {spring: s});
+ return performance.timeOrigin + (await handle.started);
+ },
+ {spring, travel: TRAVEL},
+ );
+ // The page blocks itself in the frame that sees the curve 40 ms in, however
+ // loaded the machine is.
+ const busy = await blockMainThread(page, 1000, {
+ during: box,
+ minProgressMs: 40,
+ });
+ await page.waitForTimeout(200);
+ const tracked = await trackMarker(page, await cast.stop());
+ return {start, busy, tracked};
+}
+
+test('a spring keeps advancing every frame through a 1 s main-thread block, on its curve', async ({
+ page,
+ browserName,
+}) => {
+ const {start, busy, tracked} = await blockedRun(page, SLOW);
+ const proof = busyWindowProof(tracked, busy, {axis: 'x', settledWithin: 2});
+ test
+ .info()
+ .annotations.push({type: 'busy window', description: proof.summary});
+ expect(busy.to - busy.from).toBeGreaterThanOrEqual(1000);
+ // The harness's verdict: no stall over two dropped frames, and nearly
+ // every expected frame moved (what a loaded runner still meets and a
+ // main-thread animation never does). It sets no display-rate bound.
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+ expect(proof.monotonic).toBe(true);
+ // And it is the spring: placing each frame inside the block on the
+ // analytic curve (inverting it at the frame's position) gives the same time
+ // offset for every frame. Chromium stamps frames on the page's clock, so its
+ // offset is also near zero; WebKit's screencast clock is rebased, so only
+ // the spread is judged there.
+ const inside = tracked.filter(
+ f => f.box != null && f.t > busy.from + 20 && f.t < busy.to - 20,
+ );
+ expect(inside.length).toBeGreaterThan(30);
+ const offsets = await page.evaluate(
+ ({spring, travel, frames}) => {
+ const solved = Motion.solveSpring(Motion.toSpring(spring), {
+ from: 0,
+ to: travel,
+ });
+ return frames.map(({t, x}) => {
+ let lo = 0;
+ let hi = 3;
+ for (let i = 0; i < 60; i++) {
+ const mid = (lo + hi) / 2;
+ if (solved.value(mid) < x) {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+ return t - lo * 1000;
+ });
+ },
+ {
+ spring: SLOW,
+ travel: TRAVEL,
+ frames: inside.map(f => ({
+ t: f.t - start,
+ x: (f.box?.x ?? NaN) - MARKER_INSET,
+ })),
+ },
+ );
+ const sorted = [...offsets].sort((x, y) => x - y);
+ const median = sorted[Math.floor(sorted.length / 2)];
+ const spread =
+ sorted[Math.floor(sorted.length * 0.9)] -
+ sorted[Math.floor(sorted.length * 0.1)];
+ test.info().annotations.push({
+ type: 'time offset of the frames on the curve',
+ description: JSON.stringify({median, spread}),
+ });
+ expect(spread).toBeLessThan(25);
+ if (browserName === 'chromium') {
+ expect(Math.abs(median)).toBeLessThan(20);
+ }
+});
+
+test('a spring that ends inside the block keeps showing its end state', async ({
+ page,
+}) => {
+ const {busy, tracked} = await blockedRun(page, FAST);
+ // Frames from the block's start on, through the frames after it: a screen
+ // that holds still sends no frames, so a fallback to an older value would
+ // show up as a new frame.
+ const after = tracked.filter(f => f.box != null && f.t > busy.from + 20);
+ const xs = after.map(f => (f.box?.x ?? NaN) - MARKER_INSET);
+ test.info().annotations.push({
+ type: 'positions from the block on',
+ description: xs.map(x => Math.round(x)).join(' '),
+ });
+ const landed = xs.findIndex(x => x >= TRAVEL - 1);
+ expect(landed).toBeGreaterThanOrEqual(0);
+ // WebKit's compositor falls back to the main thread's last committed value
+ // when an animation ends during a block; the keyframes' hold of the end
+ // state past the curve keeps the end on screen until script runs again.
+ for (const x of xs.slice(landed)) {
+ expect(x).toBeGreaterThanOrEqual(TRAVEL - 1);
+ }
+});
+
+test('a frame painted before the compositor has the curve shows the element where it is', async ({
+ page,
+}) => {
+ await open(page);
+ // What a frame shows without the curve is the element's own style: drop the
+ // curves right after they are created and read it. A present from rest,
+ // then a retarget mid-flight.
+ const result = await page.evaluate(
+ async ({travel}) => {
+ const fresh = (now?: () => number) => {
+ const element = document.createElement('div');
+ element.style.cssText =
+ 'position:absolute;top:120px;left:0;width:48px;height:48px;background:#c63';
+ document.body.append(element);
+ return {
+ element,
+ animator: Motion.createAnimator(element, now ? {now} : {}),
+ };
+ };
+ const x = (element: HTMLElement) =>
+ Number.parseFloat(getComputedStyle(element).translate.split(' ')[0]) ||
+ 0;
+ const present = fresh();
+ present.animator.animate({x: travel}, {spring: Motion.springs.settle});
+ for (const animation of present.element.getAnimations()) {
+ animation.cancel();
+ }
+ const presentX = x(present.element);
+
+ // One instant for the read and the retarget: 150 ms into the settle the
+ // curve moves about a pixel a millisecond, so two clock reads would
+ // differ by however long a busy page took between them.
+ let frozen: number | null = null;
+ const retarget = fresh(() => frozen ?? performance.now());
+ await retarget.animator.animate(
+ {x: travel},
+ {spring: Motion.springs.settle},
+ ).started;
+ await new Promise(resolve => setTimeout(resolve, 150));
+ frozen = performance.now();
+ const onScreen = retarget.animator.get('x');
+ retarget.animator.animate({x: 0}, {spring: Motion.springs.settle});
+ frozen = null;
+ for (const animation of retarget.element.getAnimations()) {
+ animation.cancel();
+ }
+ return {presentX, onScreen, retargetX: x(retarget.element)};
+ },
+ {travel: TRAVEL},
+ );
+ test.info().annotations.push({
+ type: 'without the curve',
+ description: JSON.stringify(result),
+ });
+ expect(result.presentX).toBeCloseTo(0, 1);
+ expect(result.onScreen).toBeGreaterThan(20);
+ // The inline value is written to a thousandth of a pixel.
+ expect(result.retargetX).toBeCloseTo(result.onScreen, 2);
+});
+
+test('under Reduce Motion, a dip a busy main thread lands late still ends within its 200 ms cross-fade', async ({
+ page,
+}) => {
+ // design:reduced-motion DR2 on a touch screen: the move dips (fades out,
+ // lands while transparent, fades back in) in 200 ms or less, opacity only.
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await open(page);
+ const read = await page.evaluate(async travel => {
+ const box = document.getElementById('box') as HTMLElement;
+ const handle = window.animator.animate(
+ {x: travel},
+ {spring: Motion.springs.navigationPush},
+ );
+ const start = await handle.started;
+ // What the dip animates, read while it runs.
+ const animated = box
+ .getAnimations()
+ .flatMap(animation =>
+ (animation.effect as KeyframeEffect)
+ .getKeyframes()
+ .flatMap(frame =>
+ Object.keys(frame).filter(
+ key =>
+ !['offset', 'easing', 'composite', 'computedOffset'].includes(
+ key,
+ ),
+ ),
+ ),
+ );
+ // The main thread is busy from 60 to 180 ms into the dip, so the task
+ // that lands it (due at 100 ms) runs 80 ms late.
+ await new Promise(resolve =>
+ setTimeout(resolve, Math.max(0, start + 60 - performance.now())),
+ );
+ while (performance.now() < start + 180) {
+ // the main thread is busy
+ }
+ await new Promise(resolve =>
+ setTimeout(resolve, Math.max(0, start + 230 - performance.now())),
+ );
+ const style = getComputedStyle(box);
+ return {
+ at: performance.now() - start,
+ opacity: Number(style.opacity),
+ translate: style.translate,
+ animated,
+ };
+ }, TRAVEL);
+ test.info().annotations.push({
+ type: '30 ms after the cross-fade was due to end',
+ description: JSON.stringify(read),
+ });
+ // Landed, and fully back in by then: the late landing did not stretch it.
+ expect(read.translate).toBe(`${TRAVEL}px`);
+ expect(read.opacity).toBeCloseTo(1, 2);
+ // Opacity only, read while the dip ran: the travel is never animated.
+ expect(read.animated).toContain('opacity');
+ expect(read.animated.every(key => key === 'opacity')).toBe(true);
+});
+
+test('under Reduce Motion, a dip held before its first frame lands once the hold is finished', async ({
+ page,
+}) => {
+ // A sampler can pause a call's animations before the browser starts them
+ // (the interaction harness's hold landing ahead of the call's first frame
+ // under load, or a page pausing every animation). Its release with finish
+ // ends the held fade out; with no animator call after it, the dip still
+ // lands and fades back in.
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await open(page);
+ await page.evaluate(travel => {
+ (window as unknown as {dip: MotionHandle}).dip = window.animator.animate(
+ {x: travel},
+ {spring: Motion.springs.navigationPush},
+ );
+ // In the call's own task, ahead of its first frame.
+ const held = document.getAnimations();
+ for (const animation of held) {
+ animation.pause();
+ }
+ (window as unknown as {held: Animation[]}).held = held;
+ }, TRAVEL);
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve =>
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => setTimeout(resolve, 40)),
+ ),
+ ),
+ );
+ await page.evaluate(() => {
+ for (const animation of (window as unknown as {held: Animation[]}).held) {
+ animation.finish();
+ }
+ });
+ // Read from the page only: an animator call would look for the start again.
+ const read = async () =>
+ page.evaluate(() => {
+ const box = document.getElementById('box') as HTMLElement;
+ const style = getComputedStyle(box);
+ return {opacity: Number(style.opacity), translate: style.translate};
+ });
+ await dipDone(page);
+ expect(await read()).toEqual({opacity: 1, translate: `${TRAVEL}px`});
+});
+
+test('under Reduce Motion, a dip held before its first frame lands once the hold is resumed', async ({
+ page,
+}) => {
+ // The hold's release without finish plays the held fade out again: the
+ // browser starts it then, and the dip lands and fades back in on the clock
+ // it resumed on, with no animator call after the release.
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await open(page);
+ await page.evaluate(travel => {
+ (window as unknown as {dip: MotionHandle}).dip = window.animator.animate(
+ {x: travel},
+ {spring: Motion.springs.navigationPush},
+ );
+ const held = document.getAnimations();
+ for (const animation of held) {
+ animation.pause();
+ }
+ (window as unknown as {held: Animation[]}).held = held;
+ }, TRAVEL);
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve =>
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => setTimeout(resolve, 40)),
+ ),
+ ),
+ );
+ await page.evaluate(() => {
+ for (const animation of (window as unknown as {held: Animation[]}).held) {
+ animation.play();
+ }
+ });
+ const read = async () =>
+ page.evaluate(() => {
+ const box = document.getElementById('box') as HTMLElement;
+ const style = getComputedStyle(box);
+ return {opacity: Number(style.opacity), translate: style.translate};
+ });
+ await dipDone(page);
+ expect(await read()).toEqual({opacity: 1, translate: `${TRAVEL}px`});
+});
+
+test('a spring started right before a block plays in full after it', async ({
+ page,
+}) => {
+ await open(page);
+ const box = page.locator('#box');
+ await markElement(box, {inset: MARKER_INSET});
+ const cast = await startScreencast(page);
+ // Started and blocked in one task: the browser has not committed it yet.
+ // It starts when the first frame after the block commits it, as Core
+ // Animation starts an animation at its transaction's commit, instead of
+ // landing 400 ms into its curve.
+ const busy = await page.evaluate(
+ ({spring, travel}) => {
+ (window as unknown as {blocked: MotionHandle}).blocked =
+ window.animator.animate({x: travel}, {spring});
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 400;
+ while (performance.now() < end) {
+ // the main thread is busy
+ }
+ return {from, to: performance.timeOrigin + performance.now()};
+ },
+ {spring: SLOW, travel: TRAVEL},
+ );
+ // Wait for the motion, not a wall clock: on a loaded machine the frames
+ // after the block reach the screencast later than any fixed wait. The page
+ // shows the box a quarter of the way along, then three more frames arrive.
+ await page.waitForFunction(
+ min =>
+ (document.getElementById('box')?.getBoundingClientRect().left ?? 0) > min,
+ TRAVEL / 4,
+ {polling: 'raf', timeout: 0},
+ );
+ const seen = cast.frameCount();
+ await expect
+ .poll(() => cast.frameCount(), {timeout: 0})
+ .toBeGreaterThan(seen + 2);
+ const startedAt = await page.evaluate(
+ async () =>
+ performance.timeOrigin +
+ (await (window as unknown as {blocked: MotionHandle}).blocked.started),
+ );
+ const tracked = await trackMarker(page, await cast.stop());
+ const xs = tracked
+ .filter(f => f.box != null)
+ .map(f => ({t: f.t, x: (f.box?.x ?? NaN) - MARKER_INSET}));
+ // Judged on the first frame after the block, whatever the frames before
+ // it showed: it is at the start of the curve, and the frames after it
+ // move on from there.
+ const first = xs.find(f => f.t >= busy.to);
+ const later = xs.filter(f => f.t >= busy.to + 100);
+ test.info().annotations.push({
+ type: 'first frame after the block',
+ description: JSON.stringify({
+ x: first?.x,
+ after: first == null ? null : first.t - busy.to,
+ }),
+ });
+ expect(first).toBeDefined();
+ // The curve starts after the block, as Core Animation commits it.
+ expect(startedAt).toBeGreaterThan(busy.to - FRAME_MS);
+ // The first frame after the block shows that curve: no further along than
+ // one that started a frame before the block ended, at that frame's own
+ // time, however sparse the frames a loaded machine sends. A curve dated at
+ // the call is 107 px in by then.
+ const atMost = await page.evaluate(
+ ({spring, travel, ms}) =>
+ Motion.solveSpring(Motion.toSpring(spring), {from: 0, to: travel}).value(
+ Math.max(0, ms) / 1000,
+ ),
+ {
+ spring: SLOW,
+ travel: TRAVEL,
+ ms: (first?.t ?? Infinity) - (busy.to - FRAME_MS),
+ },
+ );
+ expect(first?.x ?? Infinity).toBeLessThanOrEqual(atMost + 1);
+ expect(later.length).toBeGreaterThan(0);
+ expect(Math.max(...later.map(f => f.x))).toBeGreaterThan((first?.x ?? 0) + 1);
+});
+
+test('no Layout or Paint runs while it animates', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(browserName !== 'chromium', 'tracing is a Chromium protocol');
+ await open(page);
+ let start = 0;
+ const trace = await traceRendering(page, async () => {
+ start = await page.evaluate(
+ ({spring, travel}) => {
+ window.animator.animate({x: travel, opacity: 0.5}, {spring});
+ return performance.timeOrigin + performance.now();
+ },
+ {spring: SLOW, travel: TRAVEL},
+ );
+ await page.waitForTimeout(1900);
+ });
+ // After the frame that starts the animation.
+ const counts = countBetween(trace, start + 50, trace.window.to);
+ test.info().annotations.push({
+ type: 'rendering work while animating',
+ description: JSON.stringify(counts),
+ });
+ expect(counts.Layout ?? 0).toBe(0);
+ expect(counts.Paint ?? 0).toBe(0);
+});
+
+test('the engine plays the analytic curve, all channels on one clock', async ({
+ page,
+}) => {
+ await open(page);
+ const result = await page.evaluate(async () => {
+ const spring = Motion.springs.quickChange;
+ const handle = window.animator.animate({x: 300, opacity: 0.4}, {spring});
+ // From rest, the animations start in the frame after the call.
+ await handle.started;
+ const animations = document.getAnimations();
+ const starts = animations.map(a => Number(a.startTime));
+ const start = starts[0];
+ const box = document.getElementById('box') as HTMLElement;
+ let worstX = 0;
+ let worstOpacity = 0;
+ const duration = Math.max(
+ ...animations.map(a => Number(a.effect?.getComputedTiming().endTime)),
+ );
+ for (const a of animations) {
+ a.pause();
+ }
+ for (let t = 0; t <= duration; t += 4) {
+ for (const a of animations) {
+ a.currentTime = t;
+ }
+ const style = getComputedStyle(box);
+ const x = Number.parseFloat(style.translate || '0');
+ const opacity = Number.parseFloat(style.opacity);
+ worstX = Math.max(
+ worstX,
+ Math.abs(x - window.animator.get('x', start + t)),
+ );
+ worstOpacity = Math.max(
+ worstOpacity,
+ Math.abs(opacity - window.animator.get('opacity', start + t)),
+ );
+ }
+ return {count: animations.length, starts, worstX, worstOpacity};
+ });
+ test.info().annotations.push({
+ type: 'seeked curve',
+ description: JSON.stringify(result),
+ });
+ expect(result.count).toBe(2);
+ expect(new Set(result.starts).size).toBe(1);
+ expect(result.worstX).toBeLessThan(0.26);
+ expect(result.worstOpacity).toBeLessThan(0.0045);
+});
+
+test('a role variable set on a scope changes nothing while touch motion stays internal', async ({
+ page,
+}) => {
+ // A page's own style sets the role's variable on a scope; the per-role
+ // tables stay internal (spec:AST-094 DEC-15), so both boxes play the
+ // table's spring.
+ const html = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">
+<style>
+ html, body { margin: 0; background: #fff; }
+ .box { position: absolute; top: 40px; width: 48px; height: 48px; background: #36c; }
+ @scope ([data-astryx-theme="soft"]) { :scope { --motion-springs-settle: 0.8s 0.3; } }
+</style>
+<div class="box" id="plain" style="left: 0"></div>
+<div data-astryx-theme="soft"><div class="box" id="themed" style="left: 80px"></div></div>
+<script>${script}</script>`;
+ await page.route('http://motion.test/', async route =>
+ route.fulfill({contentType: 'text/html', body: html}),
+ );
+ await page.goto('http://motion.test/');
+ const result = await page.evaluate(async () => {
+ // Only a registered table's roles resolve: register it as a touch
+ // module would, and fail loudly if the role is not there.
+ Motion.registerSpringsTable();
+ if (Motion.motionRoleOf(Motion.springs.settle)?.id !== 'springs.settle') {
+ throw new Error(
+ 'springs.settle is not a registered role: call registerSpringsTable() first',
+ );
+ }
+ const curves = {
+ plain: Motion.solveSpring(Motion.toSpring(Motion.springs.settle), {
+ from: 300,
+ to: 0,
+ }),
+ themed: Motion.solveSpring(Motion.toSpring(Motion.springs.settle), {
+ from: 300,
+ to: 0,
+ }),
+ };
+ const report: Record<string, {worst: number; lowest: number}> = {};
+ for (const id of ['plain', 'themed'] as const) {
+ const element = document.getElementById(id) as HTMLElement;
+ const animator = Motion.createAnimator(element);
+ animator.set({y: 300});
+ const handle = animator.animate({y: 0}, {spring: Motion.springs.settle});
+ await handle.started;
+ const animations = element.getAnimations();
+ for (const a of animations) {
+ a.pause();
+ }
+ let worst = 0;
+ let lowest = Infinity;
+ for (let t = 0; t <= 1200; t += 8) {
+ for (const a of animations) {
+ a.currentTime = t;
+ }
+ const [, y = '0'] = getComputedStyle(element).translate.split(' ');
+ const value = Number.parseFloat(y) || 0;
+ lowest = Math.min(lowest, value);
+ worst = Math.max(worst, Math.abs(value - curves[id].value(t / 1000)));
+ }
+ report[id] = {worst, lowest};
+ }
+ return report;
+ });
+ test.info().annotations.push({
+ type: 'themed spring',
+ description: JSON.stringify(result),
+ });
+ // Both boxes play the table's (critically damped) spring: neither
+ // overshoots.
+ expect(result.plain.worst).toBeLessThan(0.26);
+ expect(result.themed.worst).toBeLessThan(0.26);
+ expect(result.plain.lowest).toBeGreaterThan(-0.5);
+ expect(result.themed.lowest).toBeGreaterThan(-0.5);
+});
+
+test('a finished animation leaves the element once the curve ends', async ({
+ page,
+}) => {
+ await open(page);
+ const result = await page.evaluate(
+ async spring =>
+ new Promise<{curveEnd: number; leftAt: number}>(resolve => {
+ const start = performance.now();
+ window.animator.animate({x: 120}, {spring});
+ const box = document.getElementById('box') as HTMLElement;
+ const solved = Motion.solveSpring(Motion.toSpring(spring), {
+ from: 0,
+ to: 120,
+ });
+ const curveEnd = solved.settleTime(0.05) * 1000;
+ const tick = () => {
+ if (box.getAnimations().length === 0) {
+ resolve({curveEnd, leftAt: performance.now() - start});
+ } else {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ }),
+ {response: 0.3, dampingRatio: 1},
+ );
+ test.info().annotations.push({
+ type: 'animation lifetime',
+ description: JSON.stringify(result),
+ });
+ // Gone within a couple of frames of the curve's end, not after the hold.
+ expect(result.leftAt).toBeGreaterThanOrEqual(result.curveEnd - 1);
+ expect(result.leftAt).toBeLessThan(result.curveEnd + 100);
+});
+
+test('a fade-in on an element its stylesheet hides stays visible once it retires', async ({
+ page,
+}) => {
+ await open(page);
+ const result = await page.evaluate(
+ async spring => {
+ const sheet = document.createElement('style');
+ sheet.textContent = '.hidden { opacity: 0; }';
+ document.head.append(sheet);
+ const element = document.createElement('div');
+ element.className = 'hidden';
+ element.style.cssText =
+ 'position:absolute;top:120px;left:0;width:48px;height:48px;background:#c63';
+ document.body.append(element);
+ const animator = Motion.createAnimator(element);
+ animator.set({opacity: 0});
+ animator.animate({opacity: 1}, {spring});
+ await new Promise<void>(resolve => {
+ const tick = () => {
+ if (element.getAnimations().length === 0) {
+ resolve();
+ } else {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ });
+ // A frame after the retire.
+ await new Promise(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve)),
+ );
+ return {
+ inline: element.style.opacity,
+ computed: getComputedStyle(element).opacity,
+ };
+ },
+ {response: 0.3, dampingRatio: 1},
+ );
+ test.info().annotations.push({
+ type: 'after retire',
+ description: JSON.stringify(result),
+ });
+ // The end stays inline over the stylesheet's opacity 0.
+ expect(result.computed).toBe('1');
+ expect(result.inline).toBe('1');
+});
+
+test('a fixed child stays fixed after a motion back to identity', async ({
+ page,
+}) => {
+ await open(page);
+ const result = await page.evaluate(async () => {
+ const box = document.getElementById('box') as HTMLElement;
+ const child = document.createElement('div');
+ child.style.cssText =
+ 'position: fixed; top: 10px; left: 10px; width: 4px; height: 4px;';
+ box.appendChild(child);
+ const quick = {response: 0.1, dampingRatio: 1};
+ await window.animator.animate({x: 120}, {spring: quick}).finished;
+ await window.animator.animate({x: 0}, {spring: quick}).finished;
+ // At rest: the animation retired and the layer promotion lingered out.
+ await new Promise<void>(resolve => {
+ const tick = () =>
+ box.getAnimations().length === 0 && box.style.willChange === ''
+ ? resolve()
+ : requestAnimationFrame(tick);
+ requestAnimationFrame(tick);
+ });
+ const rect = child.getBoundingClientRect();
+ return {top: rect.top, left: rect.left, translate: box.style.translate};
+ });
+ // The identity left the element: any translate but none would keep the box
+ // (40 px down) its containing block for good.
+ expect(result.translate).toBe('');
+ expect(result.top).toBe(10);
+ expect(result.left).toBe(10);
+});
+
+test('a dialog\u2019s ::backdrop plays the curve and holds its end state', async ({
+ page,
+}) => {
+ await open(page);
+ const result = await page.evaluate(async () => {
+ const dialog = document.createElement('dialog');
+ document.body.append(dialog);
+ dialog.showModal();
+ const backdrop = Motion.createAnimator(dialog, {
+ pseudoElement: '::backdrop',
+ });
+ backdrop.set({opacity: 0});
+ await backdrop.animate({opacity: 1}, {spring: Motion.springs.alertPresent})
+ .started;
+ const animations = document
+ .getAnimations()
+ .filter(a => (a.effect as KeyframeEffect).target === dialog);
+ const start = Number(animations[0].startTime);
+ let worst = 0;
+ const read = () =>
+ Number.parseFloat(getComputedStyle(dialog, '::backdrop').opacity);
+ for (const a of animations) {
+ a.pause();
+ }
+ for (let t = 0; t <= 400; t += 5) {
+ for (const a of animations) {
+ a.currentTime = t;
+ }
+ worst = Math.max(
+ worst,
+ Math.abs(read() - backdrop.get('opacity', start + t)),
+ );
+ }
+ for (const a of animations) {
+ a.currentTime = 20_000; // long after the curve and the hold
+ }
+ return {count: animations.length, worst, held: read()};
+ });
+ test.info().annotations.push({
+ type: 'backdrop curve',
+ description: JSON.stringify(result),
+ });
+ expect(result.count).toBe(1);
+ expect(result.worst).toBeLessThan(0.0045);
+ expect(result.held).toBeCloseTo(1, 6);
+});
+
+declare global {
+ interface Window {
+ animator: Animator;
+ }
+ const Motion: typeof MotionBundle;
+}
diff --git a/packages/core/src/motion/__tests__/motionBundle.ts b/packages/core/src/motion/__tests__/motionBundle.ts
new file mode 100644
index 0000000000..0c5447b6f5
--- /dev/null
+++ b/packages/core/src/motion/__tests__/motionBundle.ts
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file motionBundle.ts
+ * @input The motion modules the browser proofs drive
+ * @output Re-exports them as one entry point
+ * @position The esbuild entry the compositor proofs bundle into their page
+ * (global `Motion`), and the type of that global
+ */
+
+export {createAnimator} from '../animator';
+export {solveSpring, toSpring} from '../spring';
+export {registerSpringsTable, springs} from '../uikit/springs';
+export {motionRoleOf} from '../roles';
diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.ts
index 66254c7ce9..546ef04b51 100644
--- a/packages/core/src/motion/animator.test.ts
+++ b/packages/core/src/motion/animator.test.ts
@@ -9,9 +9,8 @@
* back: presentation values and velocities, retarget continuity, stop,
* completion, Reduced Motion substitutions, momentum curves (a coast with
* edges), late attach
- * @position Testing; what the compositor plays (frames advancing through a
- * blocked main thread) needs a real browser, which these tests do not
- * cover
+ * @position Testing; the compositor itself is proven in
+ * __tests__/animator.interaction.browser.spec.ts
*/
import {execFileSync} from 'node:child_process';
@@ -79,11 +78,31 @@ beforeEach(() => {
vi.spyOn(window, 'getComputedStyle').mockImplementation(
(element, pseudo) =>
({
- getPropertyValue: (property: string) =>
- pseudo != null
- ? (pseudoStylesheet[property] ?? '')
- : (element as HTMLElement).style.getPropertyValue(property) ||
- (stylesheet[property] ?? ''),
+ getPropertyValue: (property: string) => {
+ if (pseudo != null) {
+ return pseudoStylesheet[property] ?? '';
+ }
+ // A live animation wins over the inline value, holding its last
+ // keyframe (the end-state tail) until it is cancelled.
+ const held = recorded
+ .filter(
+ animation =>
+ animation.element === element &&
+ !animation.cancelled &&
+ animation.keyframes.some(frame => property in frame),
+ )
+ .at(-1);
+ const last = held?.keyframes
+ .filter(frame => property in frame)
+ .at(-1) as Record<string, unknown> | undefined;
+ if (last != null) {
+ return String(last[property]);
+ }
+ return (
+ (element as HTMLElement).style.getPropertyValue(property) ||
+ (stylesheet[property] ?? '')
+ );
+ },
}) as unknown as CSSStyleDeclaration,
);
vi.useFakeTimers();
@@ -266,7 +285,7 @@ function sampleAt(
}
describe('animate: keyframes on the compositor', () => {
- it('bakes the spring into keyframes within a twentieth of a pixel of the curve', async () => {
+ it('bakes the spring into keyframes within a quarter of a pixel of the curve', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
@@ -285,7 +304,7 @@ describe('animate: keyframes on the compositor', () => {
expect(duration).toBeCloseTo(curve.settleTime(0.05) * 1000, 6);
for (let t = 0; t <= duration; t += 0.5) {
const [x, y] = sampleAt(animation, 'translate', 1000 + t);
- expect(Math.abs(x - curve.value(t / 1000))).toBeLessThan(0.06);
+ expect(Math.abs(x - curve.value(t / 1000))).toBeLessThan(0.26);
expect(y).toBe(0);
expect(animator.get('x', 1000 + t)).toBeCloseTo(curve.value(t / 1000), 9);
}
@@ -295,10 +314,41 @@ describe('animate: keyframes on the compositor', () => {
).toEqual([300, 0]);
});
+ it('on a 3x screen, bakes the spring within a quarter of a device pixel', async () => {
+ vi.stubGlobal('devicePixelRatio', 3);
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ await commitFrame(1000);
+ const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
+ const duration = Number(animation.options.duration) - END_HOLD_MS;
+ let worst = 0;
+ for (let t = 0; t <= duration; t += 0.5) {
+ const [x] = sampleAt(animation, 'translate', 1000 + t);
+ worst = Math.max(worst, Math.abs(x - curve.value(t / 1000)));
+ }
+ // In device pixels, as the curve's chords are checked at their quarters.
+ expect(worst * 3).toBeLessThan(0.26);
+ });
+
+ it('on a 1x screen, bakes no more keyframes than a quarter of a CSS pixel needs', () => {
+ const count = (ratio: number) => {
+ vi.stubGlobal('devicePixelRatio', ratio);
+ recorded = [];
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ return live('translate')[0].keyframes.length;
+ };
+ const desktop = count(1);
+ expect(desktop).toBeLessThan(count(3));
+ // A ratio below 1 (a zoomed-out page) bakes as 1, never coarser.
+ expect(count(0.5)).toBe(desktop);
+ });
+
it('keeps the keyframe count modest (adaptive sampling)', () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
- expect(live('translate')[0].keyframes.length).toBeLessThan(200);
+ expect(live('translate')[0].keyframes.length).toBeLessThan(60);
});
it('clears an identity transform at rest, so a fixed child stays fixed', async () => {
@@ -307,18 +357,16 @@ describe('animate: keyframes on the compositor', () => {
{x: 100, scale: 0.9, rotate: 10},
{spring: springs.quickChange},
);
- expect(element.style.translate).toBe('100px 0px');
+ // While the curve runs, the inline value is where it starts.
+ expect(['', 'none']).toContain(element.style.translate);
await advance(100);
animator.animate(
{x: 0, scale: 1, rotate: 0},
{spring: springs.quickChange},
);
- // While the motion back runs, the end is never written 0px 0px: none, or
- // nothing where the stylesheet agrees.
+ // While the motion back runs, the inline value is where it starts.
expect(live('translate')).toHaveLength(1);
- for (const channel of ['translate', 'scale', 'rotate'] as const) {
- expect(['', 'none']).toContain(element.style[channel]);
- }
+ expect(parse(element.style.translate)[0]).toBeCloseTo(animator.get('x'), 2);
await advance(5000);
// At rest the identity leaves the element: translate 0px 0px would make
// the element a fixed child's containing block, and scale 1 stops a
@@ -355,21 +403,41 @@ describe('animate: keyframes on the compositor', () => {
expect(element.style.scale).toBe('none');
});
- it('writes the end values inline up front, so the last frame needs no main thread', () => {
+ it('keeps a fade to 1 inline where the stylesheet rests at 0', async () => {
+ const {animator, element} = setup();
+ // A scroll edge layer: transparent in its stylesheet, faded in on a
+ // spring. At retire the end-state tail still holds 1, so the end can only
+ // be judged against the stylesheet once the animation is gone.
+ stylesheet.opacity = '0';
+ animator.set({opacity: 0});
+ animator.animate({opacity: 1}, {spring: springs.quickChange});
+ await advance(5000);
+ expect(live('opacity')).toHaveLength(0);
+ expect(element.style.opacity).toBe('1');
+ });
+
+ it('holds the value on screen inline while a curve runs, and the end once it retires', async () => {
const {animator, element} = setup();
+ animator.set({x: 10, opacity: 0.5});
animator.animate(
{x: 120, y: -40, scale: 1.1, rotate: 12, opacity: 0.25},
{spring: springs.quickChange},
);
+ // A frame painted before the compositor has the curve shows where the
+ // element is, never where it is going.
+ expect(element.style.translate).toBe('10px 0px');
+ expect(element.style.opacity).toBe('0.5');
+ const animations = ['translate', 'scale', 'rotate', 'opacity'].map(
+ channel => live(channel)[0],
+ );
+ await commitFrame(clock);
+ await advance(5000);
expect(element.style.translate).toBe('120px -40px');
expect(element.style.scale).toBe('1.1 1.1');
expect(element.style.rotate).toBe('12deg');
expect(element.style.opacity).toBe('0.25');
- for (const channel of ['translate', 'scale', 'rotate', 'opacity']) {
- const [animation] = live(channel);
- expect(animation.keyframes[animation.keyframes.length - 1][channel]).toBe(
- (element.style as unknown as Record<string, string>)[channel],
- );
+ for (const animation of animations) {
+ expect(animation.cancelled).toBe(true);
}
});
@@ -390,6 +458,47 @@ describe('animate: keyframes on the compositor', () => {
);
});
+ it('looks for its end again on the next frame when the engine dates animations per frame (WebKit), not in a spin', async () => {
+ // WebKit moves an animation's currentTime once per frame. A retire that
+ // looks within a frame reads the frame's time, a fraction of a ms short of
+ // the end, and a timer set to that fraction fires again before anything
+ // moved: dozens of timers on the main thread after every motion.
+ const {animator} = setup();
+ const handle = animator.animate({x: 100}, {spring: springs.settle});
+ const [animation] = live('translate');
+ await commitFrame(clock);
+ const start = animation.startTime as number;
+ const curve = Number(animation.options.duration) - END_HOLD_MS;
+ let frameTime = start;
+ Object.defineProperty(animation, 'currentTime', {
+ configurable: true,
+ get: () => frameTime - start,
+ });
+ Object.defineProperty(animation, 'effect', {
+ configurable: true,
+ value: {getTiming: () => ({duration: animation.options.duration})},
+ });
+ // The last frame before the end dates the animation 0.5 ms short of it.
+ frameTime = start + curve - 0.5;
+ // Up to just before the retire is due (the injected clock and the timers
+ // move together).
+ clock += curve - 1;
+ await vi.advanceTimersByTimeAsync(curve - 1);
+ const timers = vi.spyOn(globalThis, 'setTimeout');
+ // A frame's worth of main-thread time with no frame in between.
+ for (let ms = 0; ms < 16; ms++) {
+ clock += 1;
+ await vi.advanceTimersByTimeAsync(1);
+ }
+ expect(timers.mock.calls.length).toBeLessThanOrEqual(2);
+ // The next frame: the engine's time passes the end, and it retires.
+ frameTime = start + curve + 16;
+ clock += 1;
+ await vi.advanceTimersByTimeAsync(17);
+ expect(animation.cancelled).toBe(true);
+ await expect(handle.finished).resolves.toBe(true);
+ });
+
it('never retires an animation a sampler has paused', async () => {
const {animator} = setup();
animator.animate({x: 120}, {spring: springs.quickChange});
@@ -455,6 +564,157 @@ describe('a call from rest starts at the commit, as Core Animation does', () =>
);
});
+ it('a start the browser dates before the block (WebKit) moves to after it', async () => {
+ // WebKit dates a pending animation at its last frame time before the
+ // task that made it, so after a block its first frame would show the
+ // motion that far in; the call's first read of that start moves it to
+ // the read. Chromium's commit start (the case above) stays.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ const handle = animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ // The task blocks for 300 ms; the browser dates the animation at 1000.
+ clock = 1300;
+ animation.startTime = 1000;
+ await commitFrame(1300);
+ await expect(handle.started).resolves.toBe(1300);
+ expect(animation.startTime).toBe(1300);
+ expect(animator.get('x', 1300)).toBeCloseTo(0, 9);
+ expect(animator.get('x', 1400)).toBeCloseTo(curve.value(0.1), 9);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('a start the browser dates at the frame before the call stays when the call\u2019s task runs on a few ms', async () => {
+ // Browser start times are frame times and a task's end is a live clock:
+ // on every call they differ by up to a frame plus the task's own length.
+ // A task that runs on 5 ms after the call (a component's effect after a
+ // tap) blocks nothing, so the start stays the browser's and a sequence
+ // chained on it keeps its clock.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ clock = 1005;
+ const handle = animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ clock = 1010;
+ animation.startTime = 1000;
+ await commitFrame(1016);
+ await expect(handle.started).resolves.toBe(1000);
+ expect(animation.startTime).toBe(1000);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('calls made in one task start together, whichever of them a block follows', async () => {
+ // One motion's parts are often separate calls in one task (a
+ // component's effect): a block measured per call would move the
+ // earlier calls past it and leave a later one on the browser's start,
+ // splitting the parts by a frame.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ const first = animator.animate({x: 300}, {spring: springs.settle});
+ clock = 1030;
+ const second = animator.animate({opacity: 0.5}, {spring: springs.settle});
+ clock = 1040;
+ for (const animation of recorded) {
+ animation.startTime = 1000;
+ }
+ await commitFrame(1040);
+ const [a, b] = await Promise.all([first.started, second.started]);
+ expect(a).toBe(b);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('a block within two frames of the call keeps the browser\u2019s start', async () => {
+ // Browser start times are frame times and the task's end a live clock: a
+ // 20 ms block cannot be told apart from that quantization, so the start
+ // stays where the browser put it.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ const handle = animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ // The task blocks for 20 ms; the browser dates the animation at 1000.
+ clock = 1020;
+ animation.startTime = 1000;
+ await commitFrame(1020);
+ await expect(handle.started).resolves.toBe(1000);
+ expect(animation.startTime).toBe(1000);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('a start the browser dates by the call stays when its own task ended at once, however late the first read', async () => {
+ // WebKit under load from other tasks: the call's task ends at once, and
+ // another task holds the main thread before the first frame. Nothing in
+ // the call's task delayed it, so its start stays the browser's and the
+ // calls a sequence chains on it keep their clock (design:reduced-motion
+ // DR2's 200 ms cross-fade, a cancel fading on the previous fade's end).
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ const handle = animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ // The call's task ends; then another task runs for 100 ms, and the
+ // browser commits the animation after it, dated at the call.
+ await Promise.resolve();
+ clock = 1100;
+ animation.startTime = 1000;
+ await commitFrame(1100);
+ await expect(handle.started).resolves.toBe(1000);
+ expect(animation.startTime).toBe(1000);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('a start read after the first frame stays the browser\u2019s', async () => {
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ const handle = animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ // Paused before its first frame (a harness), then started late: the
+ // first frame passed with no start to read.
+ animation.paused = true;
+ await commitFrame(1016);
+ clock = 1600;
+ animation.paused = false;
+ animation.startTime = 1000;
+ await commitFrame(1600);
+ await expect(handle.started).resolves.toBe(1000);
+ expect(animation.startTime).toBe(1000);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
it('holds its start until the browser starts it', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
@@ -798,6 +1058,361 @@ describe('review fixes', () => {
});
});
+describe('additive: a retarget adds to the curve on screen', () => {
+ const old = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
+ const oldEnd = old.settleTime(0.05);
+ const oldAt = (t: number) => (t >= oldEnd ? 300 : old.value(t));
+
+ it('starts from the old curve\u2019s value and velocity, and reads as their sum', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ await commitFrame(1000);
+ clock = 1150;
+ const x = animator.get('x');
+ const v = animator.getVelocity('x');
+ animator.animate({x: 100}, {spring: springs.settle}, {additive: true});
+ expect(animator.get('x')).toBeCloseTo(x, 9);
+ expect(animator.getVelocity('x')).toBeCloseTo(v, 6);
+ const delta = solveSpring(toSpring(springs.settle), {from: 0, to: -200});
+ for (const t of [0.02, 0.1, 0.4]) {
+ expect(animator.get('x', 1150 + t * 1000)).toBeCloseTo(
+ oldAt(0.15 + t) + delta.value(t),
+ 6,
+ );
+ }
+ await advance(10_000);
+ expect(animator.get('x')).toBe(100);
+ });
+
+ it('a played reversal keeps the old velocity: a late first frame shows only the reversal\u2019s own start', async () => {
+ // An ease-in-out reversal starts at rest; replacing a curve that moves
+ // at v puts the old curve v·d ahead of it by a first frame d ms late.
+ const ease = cubicBezier(timing.curves.move);
+ const reversal = (from: number, to: number) => ({
+ duration: 0.35,
+ at: (t: number) => from + (to - from) * ease(Math.min(1, t / 0.35)),
+ velocity: (t: number) =>
+ ((to - from) / 0.35) *
+ ((ease(Math.min(1, t / 0.35 + 1e-4)) -
+ ease(Math.max(0, t / 0.35 - 1e-4))) /
+ 2e-4),
+ });
+ const steps = async (additive: boolean) => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle}, {at: 1000});
+ clock = 1120;
+ const from = animator.get('x');
+ animator.play({x: reversal(from, 0)}, {at: 1120, additive});
+ return [30, 60, 100].map(d =>
+ Math.abs(animator.get('x', 1120 + d) - oldAt((120 + d) / 1000)),
+ );
+ };
+ const replaced = await steps(false);
+ const added = await steps(true);
+ for (let i = 0; i < added.length; i++) {
+ expect(added[i]).toBeLessThan(replaced[i] / 2);
+ }
+ // What remains is the reversal's own first d ms, scaled to the targets.
+ expect(added[0]).toBeCloseTo(300 * ease(30 / 350), 6);
+ });
+
+ it('nests: a second retarget adds to the first', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ await commitFrame(1000);
+ clock = 1100;
+ animator.animate({x: 100}, {spring: springs.settle}, {additive: true});
+ clock = 1200;
+ const x = animator.get('x');
+ const v = animator.getVelocity('x');
+ animator.animate({x: 250}, {spring: springs.settle}, {additive: true});
+ expect(animator.get('x')).toBeCloseTo(x, 9);
+ expect(animator.getVelocity('x')).toBeCloseTo(v, 6);
+ const first = solveSpring(toSpring(springs.settle), {from: 0, to: -200});
+ const second = solveSpring(toSpring(springs.settle), {from: 0, to: 150});
+ expect(animator.get('x', 1300)).toBeCloseTo(
+ oldAt(0.3) + first.value(0.2) + second.value(0.1),
+ 6,
+ );
+ await advance(10_000);
+ expect(animator.get('x')).toBe(250);
+ });
+
+ it('replaces as before for a property at rest or given a velocity', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle}, {additive: true});
+ await commitFrame(1000);
+ const fromRest = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
+ expect(animator.get('x', 1100)).toBeCloseTo(fromRest.value(0.1), 9);
+ clock = 1100;
+ const x = animator.get('x');
+ animator.animate(
+ {x: 0},
+ {spring: springs.settle, velocity: {x: 0}},
+ {additive: true},
+ );
+ const back = solveSpring(toSpring(springs.settle), {from: x, to: 0});
+ expect(animator.get('x', 1200)).toBeCloseTo(back.value(0.1), 9);
+ });
+});
+
+describe('start: when a call\u2019s animations start', () => {
+ it('presented: leaves the element at rest, and creates the animations two frames later', async () => {
+ const {animator, element} = setup();
+ animator.set({x: 20});
+ // The set's own promotion ends first.
+ await vi.advanceTimersByTimeAsync(PROMOTION_LINGER_MS + 1);
+ expect(element.style.willChange).toBe('');
+ const handle = animator.animate(
+ {x: 100},
+ {spring: springs.settle},
+ {start: 'presented'},
+ );
+ // At rest, with no layer yet: the next frame commits it where it is.
+ // (A layer at rest for two frames left a stale paint in WebKit on iOS.)
+ expect(live('translate')).toHaveLength(0);
+ expect(element.style.translate).toBe('20px 0px');
+ expect(element.style.willChange).toBe('');
+ expect(animator.get('x')).toBe(20);
+ clock = 1016;
+ await commitFrame(1016);
+ expect(live('translate')).toHaveLength(0);
+ // The frame after it creates them; the browser starts them at its commit.
+ clock = 1033;
+ await commitFrame(1033);
+ expect(live('translate')).toHaveLength(1);
+ expect(element.style.willChange).toContain('translate');
+ clock = 1050;
+ await commitFrame(1050);
+ await expect(handle.started).resolves.toBe(1050);
+ const curve = solveSpring(toSpring(springs.settle), {from: 20, to: 100});
+ expect(animator.get('x', 1150)).toBeCloseTo(curve.value(0.1), 9);
+ expect(sampleAt(live('translate')[0], 'translate', 1150)[0]).toBeCloseTo(
+ curve.value(0.1),
+ 0,
+ );
+ });
+
+ it('presented: a start WebKit dates at the frame that creates the animations keeps it, wherever in its frame the call was made', async () => {
+ // A presented call's animations are created in its second frame's
+ // callback, so its task is that callback's, not the call's: measured
+ // from the call, a call made early in its frame looked like a block
+ // longer than two frames, and a late first read moved the start.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ const handle = animator.animate(
+ {x: 100},
+ {spring: springs.settle},
+ {start: 'presented'},
+ );
+ clock = 1016;
+ await commitFrame(1016);
+ // The frame that creates the animations; the callback's task runs on
+ // 3 ms.
+ requestFrame(() => {
+ clock = 1036;
+ });
+ clock = 1033;
+ await commitFrame(1033);
+ expect(live('translate')).toHaveLength(1);
+ // Other tasks hold the main thread until the next frame, where WebKit's
+ // start for them, that frame's time, is first read.
+ clock = 1090;
+ live('translate')[0].startTime = 1033;
+ await commitFrame(1090);
+ await expect(handle.started).resolves.toBe(1033);
+ expect(live('translate')[0].startTime).toBe(1033);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('presented: a block in the frame that creates the animations moves their start past it', async () => {
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ get: () => ({currentTime: clock}),
+ });
+ try {
+ const {animator} = setup();
+ const handle = animator.animate(
+ {x: 100},
+ {spring: springs.settle},
+ {start: 'presented'},
+ );
+ clock = 1016;
+ await commitFrame(1016);
+ // The frame that creates the animations blocks for 300 ms; WebKit's
+ // start for them, that frame's time, is read at the next frame.
+ requestFrame(() => {
+ clock = 1333;
+ });
+ clock = 1033;
+ await commitFrame(1033);
+ clock = 1340;
+ live('translate')[0].startTime = 1033;
+ await commitFrame(1340);
+ await expect(handle.started).resolves.toBe(1340);
+ expect(live('translate')[0].startTime).toBe(1340);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('presented: a call queued after another change flushed the queue still waits its own two frames', async () => {
+ const {animator} = setup();
+ animator.animate({x: 100}, {spring: springs.settle}, {start: 'presented'});
+ // Another change creates the waiting call's animations first.
+ animator.animate({y: 50}, {spring: springs.settle});
+ clock = 1016;
+ await commitFrame(1016);
+ animator.animate(
+ {opacity: 0.5},
+ {spring: springs.settle},
+ {start: 'presented'},
+ );
+ expect(live('opacity')).toHaveLength(0);
+ // The first call's second frame is this call's first: it still waits.
+ clock = 1033;
+ await commitFrame(1033);
+ expect(live('opacity')).toHaveLength(0);
+ clock = 1050;
+ await commitFrame(1050);
+ expect(live('opacity')).toHaveLength(1);
+ });
+
+ it('presented: a second presented call on the same property a frame later keeps its own two frames', async () => {
+ const {animator} = setup();
+ animator.animate({x: 100}, {spring: springs.settle}, {start: 'presented'});
+ clock = 1016;
+ await commitFrame(1016);
+ animator.animate({x: 200}, {spring: springs.settle}, {start: 'presented'});
+ // The first call's second frame: its property is now the second call's,
+ // so nothing starts yet.
+ clock = 1033;
+ await commitFrame(1033);
+ expect(live('translate')).toHaveLength(0);
+ // The second call's own second frame.
+ clock = 1050;
+ await commitFrame(1050);
+ expect(live('translate')).toHaveLength(1);
+ await commitFrame(1066);
+ expect(animator.get('x', 1066 + 5000)).toBeCloseTo(200, 3);
+ });
+
+ it('presented: a later presented call that takes part of a waiting call\u2019s channel starts the rest of it, from its own start', async () => {
+ const {animator} = setup();
+ const first = animator.animate(
+ {x: 100, y: 100},
+ {spring: springs.settle},
+ {start: 'presented'},
+ );
+ clock = 1016;
+ await commitFrame(1016);
+ animator.animate({x: 200}, {spring: springs.settle}, {start: 'presented'});
+ // The first call's second frame: its channel now holds the second call's
+ // curve, so nothing starts yet.
+ clock = 1033;
+ await commitFrame(1033);
+ expect(live('translate')).toHaveLength(0);
+ // The second call's second frame creates the channel, with the first
+ // call's y in it; the browser starts it at the next commit.
+ clock = 1050;
+ await commitFrame(1050);
+ expect(live('translate')).toHaveLength(1);
+ clock = 1066;
+ await commitFrame(1066);
+ await expect(first.started).resolves.toBe(1066);
+ // y was at rest on screen until then: its curve starts there, and the
+ // model reads what the screen shows.
+ const y = solveSpring(toSpring(springs.settle), {from: 0, to: 100});
+ expect(animator.get('y', 1166)).toBeCloseTo(y.value(0.1), 6);
+ expect(sampleAt(live('translate')[0], 'translate', 1166)[1]).toBeCloseTo(
+ y.value(0.1),
+ 0,
+ );
+ });
+
+ it('presented: another change before then creates the animations first', async () => {
+ const {animator} = setup();
+ animator.animate({x: 100}, {spring: springs.settle}, {start: 'presented'});
+ animator.animate({y: 50}, {spring: springs.settle});
+ expect(live('translate').length).toBeGreaterThan(0);
+ await commitFrame(clock);
+ const x = solveSpring(toSpring(springs.settle), {from: 0, to: 100});
+ expect(animator.get('x', clock + 100)).toBeCloseTo(x.value(0.1), 9);
+ });
+
+ it('presented: a retarget of a moving property starts now, from the value and velocity on screen (FR6)', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ await commitFrame(1000);
+ clock = 1100;
+ const from = animator.get('x');
+ const velocity = animator.getVelocity('x');
+ animator.animate({x: 0}, {spring: springs.settle}, {start: 'presented'});
+ // The element is moving, not at rest: no two frames on the old curve and
+ // no restart at the commit from the call's value. The new curve starts at
+ // the call, from what is on screen, as a retarget does.
+ const [animation] = live('translate');
+ expect(animation.startTime).toBe(1100);
+ expect(animator.get('x', 1100)).toBeCloseTo(from, 6);
+ expect(animator.getVelocity('x', 1100)).toBeCloseTo(velocity, 3);
+ const back = solveSpring(toSpring(springs.settle), {
+ from,
+ to: 0,
+ velocity,
+ });
+ expect(animator.get('x', 1200)).toBeCloseTo(back.value(0.1), 6);
+ });
+
+ it('commit: a retarget is dated by the browser\u2019s commit, from the value on screen', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ await commitFrame(1000);
+ clock = 1100;
+ const from = animator.get('x');
+ const velocity = animator.getVelocity('x');
+ const handle = animator.animate(
+ {x: 0},
+ {spring: springs.settle},
+ {start: 'commit'},
+ );
+ const [animation] = live('translate');
+ expect(animation.startTime).toBeNull();
+ // Held where it is until the browser starts it.
+ expect(animator.get('x')).toBeCloseTo(from, 9);
+ clock = 1130;
+ await commitFrame(1130);
+ await expect(handle.started).resolves.toBe(1130);
+ const back = solveSpring(toSpring(springs.settle), {
+ from,
+ to: 0,
+ velocity,
+ });
+ expect(animator.get('x', 1230)).toBeCloseTo(back.value(0.1), 6);
+ });
+
+ it('a handle hands out the curve it plays, for a companion on the same clock', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({y: 400}, {spring: springs.sheetPresent});
+ const curve = handle.curve('y');
+ expect(curve).not.toBeNull();
+ expect(handle.curve('x')).toBeNull();
+ await commitFrame(1000);
+ const y = solveSpring(toSpring(springs.sheetPresent), {from: 0, to: 400});
+ for (const t of [0, 0.05, 0.2]) {
+ expect(curve?.at(t)).toBeCloseTo(y.value(t), 9);
+ expect(curve?.velocity(t)).toBeCloseTo(y.velocity(t), 6);
+ expect(animator.get('y', 1000 + t * 1000)).toBeCloseTo(y.value(t), 9);
+ }
+ expect(curve?.at(curve.duration)).toBe(400);
+ });
+});
+
describe('animatorFor: one animator per element', () => {
it('gives every caller the same animator for an element', () => {
const a = document.createElement('div');
@@ -831,8 +1446,8 @@ describe('animatorFor: one animator per element', () => {
const y = solveSpring(toSpring(springs.settle), {from: 0, to: -44});
expect(swipe.get('y', clock + 30)).toBeCloseTo(y.value(0.03), 9);
const [tx, ty] = sampleAt(tracks[0], 'translate', clock + 30);
- expect(tx).toBeCloseTo(x.value(0.08), 1);
- expect(ty).toBeCloseTo(y.value(0.03), 1);
+ expect(Math.abs(tx - x.value(0.08))).toBeLessThan(0.26);
+ expect(Math.abs(ty - y.value(0.03))).toBeLessThan(0.26);
});
});
@@ -901,6 +1516,74 @@ describe('promotion: a compositing layer while it moves', () => {
expect(element.style.willChange).toBe('');
});
+ it("reads the stylesheet's will-change in a task of its own, so a promotion reads no style in its own task", async () => {
+ // A drag's first move promotes: reading the stylesheet's reasons then
+ // would force a style recalculation in the input handler.
+ stylesheet['will-change'] = 'transform, opacity';
+ const {animator, element} = setup();
+ // In the document, where the read happens.
+ document.body.append(element);
+ await commitFrame(clock);
+ await vi.advanceTimersByTimeAsync(0);
+ const readsOf = () =>
+ vi
+ .mocked(window.getComputedStyle)
+ .mock.calls.filter(([read]) => read === element).length;
+ const before = readsOf();
+ animator.set({y: 10});
+ expect(readsOf()).toBe(before);
+ expect(element.style.willChange).toBe('transform, opacity, translate');
+ await advance(PROMOTION_LINGER_MS + 10);
+ expect(element.style.willChange).toBe('');
+ element.remove();
+ });
+
+ it('reads no style for a node out of the document: a node removed before its read is never read', async () => {
+ // A shared animator (animatorFor) is never detached: its node can leave
+ // the document with the read still waiting. A node out of the document
+ // has no style to read, and reading one costs a style pass for nothing.
+ stubMedia(false, false);
+ const readsOf = (node: Element) =>
+ vi
+ .mocked(window.getComputedStyle)
+ .mock.calls.filter(([read]) => read === node).length;
+ const removed = document.createElement('div');
+ document.body.append(removed);
+ createAnimator(removed, {now: () => clock, requestFrame});
+ removed.remove();
+ const kept = document.createElement('div');
+ document.body.append(kept);
+ createAnimator(kept, {now: () => clock, requestFrame});
+ await vi.advanceTimersByTimeAsync(0);
+ expect(readsOf(removed)).toBe(0);
+ // A node still in the document is read, once, in that task.
+ expect(readsOf(kept)).toBe(1);
+ kept.remove();
+ });
+
+ it("keeps the stylesheet's will-change when a node read nothing before it moves", () => {
+ // Put back after its read was skipped, a node reads its stylesheet's
+ // reasons when a promotion needs them.
+ stylesheet['will-change'] = 'transform, opacity';
+ stubMedia(false, false);
+ const element = document.createElement('div');
+ const animator = createAnimator(element, {
+ now: () => clock,
+ requestFrame,
+ });
+ document.body.append(element);
+ animator.set({y: 10});
+ expect(element.style.willChange).toBe('transform, opacity, translate');
+ element.remove();
+ });
+
+ it("keeps the stylesheet's will-change when an element attached in this task moves at once", () => {
+ stylesheet['will-change'] = 'transform, opacity';
+ const {animator, element} = setup();
+ animator.animate({y: 100}, {spring: springs.settle});
+ expect(element.style.willChange).toBe('transform, opacity, translate');
+ });
+
it('promotes during direct manipulation, until the writes stop', async () => {
const {animator, element} = setup();
animator.set({y: 10});
@@ -913,6 +1596,34 @@ describe('promotion: a compositing layer while it moves', () => {
expect(element.style.willChange).toBe('');
});
+ it('set with promote: false writes the values without a layer, and leaves other promotion alone', async () => {
+ // A one-off switch (a veil under a sticky header during a programmatic
+ // scroll) must not give its element a layer.
+ const {animator, element} = setup();
+ animator.set({opacity: 0.5}, {promote: false});
+ expect(element.style.opacity).toBe('0.5');
+ expect(element.style.willChange).toBe('');
+ await advance(PROMOTION_LINGER_MS + 10);
+ expect(element.style.willChange).toBe('');
+
+ // A channel a running motion promoted stays promoted, on its own clock.
+ const moving = setup();
+ moving.animator.animate({x: 120}, {spring: springs.settle});
+ expect(moving.element.style.willChange).toBe('translate');
+ moving.animator.set({opacity: 0.25}, {promote: false});
+ expect(moving.element.style.opacity).toBe('0.25');
+ expect(moving.element.style.willChange).toBe('translate');
+ await advance(5000 + PROMOTION_LINGER_MS);
+ expect(moving.element.style.willChange).toBe('');
+
+ // A channel with other motion still running gets its animation's layer.
+ const shared = setup();
+ shared.animator.animate({y: 80}, {spring: springs.settle});
+ shared.animator.set({x: 10}, {promote: false});
+ expect(live('translate').length).toBeGreaterThan(0);
+ expect(shared.element.style.willChange).toBe('translate');
+ });
+
it('promotes a pseudo-element through a custom property on its host', async () => {
const {animator, element} = setup({pseudoElement: '::backdrop'});
animator.set({opacity: 0});
@@ -1029,10 +1740,12 @@ describe('presentation values, retargeting, velocity (spec:AST-094 FR6)', () =>
animator.animate({x: 0}, {spring: springs.settle});
const [animation] = live('translate');
for (let t = clock; t < clock + 400; t += 7) {
- expect(sampleAt(animation, 'translate', t)[1]).toBeCloseTo(
- yCurve.value((t - 1000) / 1000),
- 1,
- );
+ expect(
+ Math.abs(
+ sampleAt(animation, 'translate', t)[1] -
+ yCurve.value((t - 1000) / 1000),
+ ),
+ ).toBeLessThan(0.26);
expect(animator.get('y', t)).toBeCloseTo(
yCurve.value((t - 1000) / 1000),
9,
@@ -1127,6 +1840,52 @@ describe('finished', () => {
await expect(c.finished).resolves.toBe(false);
});
+ it('waits while a sampler holds the animation past the curve\u2019s end', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({x: 40}, {spring: springs.quickChange});
+ let result: boolean | undefined;
+ void handle.finished.then(value => {
+ result = value;
+ });
+ await advance(16);
+ // A harness pauses it (holdAnimations) and keeps it held well past the
+ // end of the curve on the wall clock: the motion has not ended.
+ const [animation] = live('translate');
+ animation.paused = true;
+ await advance(5000);
+ expect(result).toBeUndefined();
+ });
+
+ it('resolves true once a held animation resumes and reaches its end', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({x: 40}, {spring: springs.quickChange});
+ let result: boolean | undefined;
+ void handle.finished.then(value => {
+ result = value;
+ });
+ await advance(16);
+ const [animation] = live('translate');
+ animation.paused = true;
+ await advance(5000);
+ animation.paused = false;
+ await advance(1000);
+ expect(result).toBe(true);
+ });
+
+ it('resolves on time for an animation nobody holds', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({x: 40}, {spring: springs.quickChange});
+ let result: boolean | undefined;
+ void handle.finished.then(value => {
+ result = value;
+ });
+ const end = (handle.curve('x')?.duration ?? NaN) * 1000;
+ await advance(end - 50);
+ expect(result).toBeUndefined();
+ await advance(100);
+ expect(result).toBe(true);
+ });
+
it('dispose cancels and settles everything', async () => {
const {animator} = setup();
const handle = animator.animate(
@@ -1156,6 +1915,64 @@ describe('Reduced Motion (design:reduced-motion)', () => {
),
);
+ it('a call naming the opacity a running dip heads to keeps the dip', async () => {
+ const {animator} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await commitFrame(clock);
+ const start = clock;
+ await advance(fade / 4);
+ // Mid fade out: a call names the opacity the dip returns to.
+ const handle = animator.animate({opacity: 1}, {spring: springs.settle});
+ // The dip goes on as it was: at its bottom when it was due, not opening
+ // a second dip from where it had got to.
+ expect(animator.get('opacity', start + fade / 2)).toBeCloseTo(0, 6);
+ await advance(fade / 4 + 1);
+ // Landed at the bottom; the fade back in ends when the dip was due to.
+ expect(animator.get('x')).toBe(100);
+ expect(animator.get('opacity', start + fade)).toBeCloseTo(1, 6);
+ await advance(fade + END_HOLD_MS + 1);
+ expect(animator.get('x')).toBe(100);
+ expect(animator.get('opacity')).toBe(1);
+ expect(await handle.finished).toBe(true);
+ });
+
+ it('a call naming the opacity a dip heads to, in the same task as the dip, hands the browser no second fade', async () => {
+ const {animator} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ animator.animate({opacity: 1}, {spring: springs.settle});
+ await commitFrame(clock);
+ const fades = recorded.filter(animation =>
+ animation.keyframes.some(keyframe => 'opacity' in keyframe),
+ );
+ expect(fades).toHaveLength(1);
+ expect(fades[0].cancelled).toBe(false);
+ });
+
+ it('a release played as a dip, then its state layer naming the opacity the dip returns to, fades once', async () => {
+ // A swipe row's release: the move's layer plays the travel, then the
+ // state layer lands its opacity on the same element in the same task.
+ const {animator} = reduced();
+ const move = animator.play(
+ {x: {duration: 0.3, at: t => (100 * t) / 0.3, velocity: () => 100 / 0.3}},
+ {touchRelease: true},
+ );
+ const state = animator.animate(
+ {opacity: 1},
+ {spring: springs.settle},
+ {touchRelease: true},
+ );
+ await commitFrame(clock);
+ const fades = recorded.filter(animation =>
+ animation.keyframes.some(keyframe => 'opacity' in keyframe),
+ );
+ expect(fades).toHaveLength(1);
+ await advance(fade + END_HOLD_MS + 1);
+ expect(animator.get('x')).toBe(100);
+ expect(animator.get('opacity')).toBe(1);
+ expect(await move.finished).toBe(true);
+ expect(await state.finished).toBe(true);
+ });
+
it('an entrance after an outside finish starts from what is on screen', async () => {
const {animator} = reduced();
animator.animate(
@@ -1178,6 +1995,24 @@ describe('Reduced Motion (design:reduced-motion)', () => {
expect(fade?.keyframes[0].opacity).toBe('0');
});
+ it('presented: a call that moves and fades in from transparent lands its travel', async () => {
+ // A control part at its rest offset, transparent, presented in one task
+ // with its own animator (SearchField's close button).
+ const {animator, element} = reduced();
+ animator.set({x: 44, opacity: 0});
+ animator.animate(
+ {x: 0, opacity: 1},
+ {spring: springs.settle},
+ {start: 'presented'},
+ );
+ await commitFrame(clock);
+ await commitFrame(clock);
+ await advance(fade + 16);
+ expect(animator.get('x')).toBe(0);
+ expect(parse(element.style.translate)[0] || 0).toBe(0);
+ expect(animator.get('opacity', clock)).toBeCloseTo(1, 9);
+ });
+
it('fades for 200 ms at most', () => {
expect(fade).toBeGreaterThan(0);
expect(fade).toBeLessThanOrEqual(200);
@@ -1380,10 +2215,13 @@ describe('Reduced Motion (design:reduced-motion)', () => {
it('a node detached mid-dip and attached again in a later task shows the move landed and visible', async () => {
const {animator, element} = reduced();
- // The call owns its opacity: its dip writes the low opacity inline.
+ // The call owns its opacity: its dip writes opacity inline, the value on
+ // screen as the fade starts (its end is written when the fade retires),
+ // while the model is already partway down.
animator.animate({x: 240, opacity: 1}, {spring: springs.navigationPush});
await advance(25);
- expect(Number(element.style.opacity)).toBeLessThan(1);
+ expect(element.style.opacity).not.toBe('');
+ expect(animator.get('opacity')).toBeLessThan(1);
animator.attach(null);
await advance(100);
animator.attach(element);
@@ -1393,6 +2231,24 @@ describe('Reduced Motion (design:reduced-motion)', () => {
expect(Number(element.style.opacity || '1')).toBe(1);
});
+ it('a node detached mid-dip from a dimmed opacity shows the move landed and visible when attached again', async () => {
+ // With the presented start, a curve writes its starting value inline: a
+ // dip from a dimmed opacity leaves that low value on the node while the
+ // move still waits to land.
+ const {animator, element} = reduced();
+ animator.set({opacity: 0.3});
+ animator.animate({x: 240, opacity: 1}, {spring: springs.navigationPush});
+ await advance(25);
+ expect(Number(element.style.opacity)).toBeLessThan(1);
+ expect(animator.get('x')).toBe(0);
+ animator.attach(null);
+ await advance(100);
+ animator.attach(element);
+ expect(animator.get('x')).toBe(240);
+ expect(animator.get('opacity')).toBe(1);
+ expect(Number(element.style.opacity || '1')).toBe(1);
+ });
+
it('a node detached mid-dip while another axis moves is left with no animation or promotion', async () => {
const {animator, element} = reduced();
animator.set({x: 0, y: 0});
@@ -1671,6 +2527,92 @@ describe('Reduced Motion (design:reduced-motion)', () => {
}
});
+ it('a landing later than the whole fade back in shows the element at once and settles then', async () => {
+ // A hold released long after the dip was due: the landing\u2019s timer runs
+ // more than the whole fade back in late, so the element appears at once
+ // where it landed. No fade is left for the browser to start a frame
+ // later, so the call\u2019s finished never reports an element still at 0.
+ for (const sheet of ['own', 'stylesheet'] as const) {
+ const {animator, element} = reduced();
+ stylesheet = sheet === 'stylesheet' ? {opacity: '0.6'} : {};
+ const handle = animator.animate(
+ {x: 100},
+ {spring: springs.navigationPush},
+ );
+ for (const animation of recorded) {
+ animation.paused = true;
+ }
+ await commitFrame(clock);
+ clock += fade * 2;
+ for (const animation of recorded) {
+ animation.finish();
+ }
+ const before = recorded.length;
+ let settled: boolean | undefined;
+ void handle.finished.then(value => {
+ settled = value;
+ });
+ // The next frame finds the hold finished: the landing is long due.
+ await commitFrame(clock);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(animator.get('x')).toBe(100);
+ expect(
+ recorded
+ .slice(before)
+ .filter(
+ animation =>
+ !animation.cancelled &&
+ 'opacity' in (animation.keyframes[0] ?? {}),
+ ),
+ ).toHaveLength(0);
+ expect(settled).toBe(true);
+ if (sheet === 'stylesheet') {
+ // Handed back to the stylesheet at once.
+ expect(element.style.opacity).toBe('');
+ } else {
+ expect(animator.get('opacity')).toBe(1);
+ }
+ animator.dispose();
+ recorded = [];
+ }
+ });
+
+ it('a move held before its first frame and finished from outside still lands when its retire runs before the next frame', async () => {
+ // A sampler pauses the call's animations in its own task and finishes
+ // them later. A loaded page can run the retire timer, which cancels the
+ // finished fade, before the frame that would read the call's start: the
+ // call must not be left waiting for a start that no animation can give.
+ const {animator} = reduced();
+ const handle = animator.animate({x: 100}, {spring: springs.navigationPush});
+ for (const animation of recorded) {
+ animation.paused = true;
+ }
+ await commitFrame(clock);
+ clock += 30;
+ await commitFrame(clock);
+ for (const animation of recorded) {
+ animation.finish();
+ }
+ let settled: boolean | undefined;
+ void handle.finished.then(value => {
+ settled = value;
+ });
+ // The retire timer first, with no frame in between: it cancels the
+ // finished fade out.
+ clock += fade * 2;
+ await vi.advanceTimersByTimeAsync(fade * 2);
+ expect(
+ recorded.filter(animation => animation.finished && !animation.cancelled),
+ ).toEqual([]);
+ // Frames keep coming: step the clock through the landing.
+ for (let step = 0; step < 16; step++) {
+ await advance(fade / 4);
+ }
+ expect(animator.get('x')).toBe(100);
+ expect(animator.get('opacity')).toBe(1);
+ expect(settled).toBe(true);
+ });
+
it('a waiting call whose own opacity a later call retargets settles interrupted', async () => {
const {animator} = reduced();
const dismiss = animator.animate(
@@ -2426,6 +3368,8 @@ describe('play: any closed-form curve', () => {
const end = press.value(0.266);
expect(animator.get('scale', 1266)).toBeCloseTo(end, 12);
expect(animator.getVelocity('scale', 1266)).toBe(0);
+ // Retired, the end is inline.
+ await advance(400);
for (const axis of parse(element.style.scale)) {
expect(axis).toBeCloseTo(end, 4);
}
@@ -2532,7 +3476,7 @@ describe('decay: momentum curves (a coast)', () => {
Math.abs(
sampleAt(animation, 'translate', 1000 + t)[1] - glide.value(t / 1000),
),
- ).toBeLessThan(0.11);
+ ).toBeLessThan(0.26);
}
expect(animator.get('y', 1e7)).toBeCloseTo(glide.rest, 9);
});
@@ -2720,7 +3664,8 @@ describe('attach', () => {
curve.value(0.1),
1,
);
- expect(element.style.translate).toBe('300px 0px');
+ // The value on screen, not the end.
+ expect(parse(element.style.translate)[0]).toBeCloseTo(curve.value(0.1), 2);
});
it('unmounting settles a pending atRest() wait and leaves no poll timer', async () => {
diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.ts
index cb539e0d87..a02bca5b55 100644
--- a/packages/core/src/motion/animator.ts
+++ b/packages/core/src/motion/animator.ts
@@ -42,14 +42,16 @@
* current value with the current velocity (`spec:AST-094` FR6). A gesture's release velocity
* can be handed in explicitly instead.
*
- * End state without a flicker frame: the element's inline style always holds
- * the values the animations END on, and the keyframes hold that end state for
- * a while after the curve ends (END_HOLD_MS). The main thread drops a finished
- * animation as soon as it runs after the curve's end; the inline style already
- * shows the same values, so nothing moves. The hold matters when the curve
- * ends during a main-thread block: WebKit's compositor ends an animation by
- * falling back to the value its main thread last committed, which is
- * mid-flight.
+ * No frame shows a value the element is not at. While a curve runs, the
+ * element's inline style holds the value the curve starts from (the value on
+ * screen when it was built), so a frame painted before the compositor has the
+ * curve (WebKit can receive a new curve a few updates late) shows the element
+ * where it is, never where it is going. The keyframes hold the end state for a
+ * while after the curve ends (END_HOLD_MS); the main thread retires a finished
+ * animation as soon as it runs after the curve's end, writing the end values
+ * inline in the same task that cancels it, so nothing moves. The hold matters
+ * when the curve ends during a main-thread block: WebKit's compositor ends an
+ * animation by falling back to the value its main thread last committed.
*
* Start time: a call that starts from rest (nothing on its channels moving,
* no `options.at`) gets no start time, so the browser starts it when it
@@ -62,18 +64,34 @@
* `options.at` to line several animators up, so the new curve continues
* from the frame on screen. Keyframes are sampled from the call's start, so
* a value that keeps moving through a rebuild stays on its curve to the
- * frame.
+ * frame. `options.start` changes that per call: `'commit'` dates a retarget
+ * by the browser's commit as well, and `'presented'` creates the animations
+ * of a call from rest two frames later, once its element at rest has been
+ * presented (a UI process that applies commits late); a retarget still starts
+ * now, from the value and velocity on screen.
+ * `handle.curve(property)` hands out the curve a call plays, so a
+ * companion can follow it on the same clock.
+ * `options.additive` retargets as UIKit does: the old curve keeps going and a
+ * curve of the change between the targets is added on top, baked into one
+ * animation (two animations on one property leave the compositor in both
+ * engines), so the retarget keeps the velocity on screen.
*
- * WebKit starts an animation created just before a block at its last frame
- * time before the block, so there the motion still skips into its curve;
- * Chromium starts it after the block.
+ * WebKit dates an animation created just before a block at its last frame
+ * time before the block, where the first frame after it would show the
+ * motion skipped into its curve; when the call's own task ran on more than
+ * two frames, the call's first read of that start moves it to that read, so
+ * WebKit delays the motion as Chromium's commit does (startAfterBlock). Every
+ * call of that task moves together, and a shorter task or a read that other
+ * tasks delay keeps the browser's start, so a sequence chained on a call's
+ * end (a Reduce Motion cross-fade's second half) keeps its clock.
*
* Promotion: Mobile Safari runs an animation whose start time is set from
* script on its compositor at its first commit only if the element (or the
* pseudo-element) already has a compositing layer; without one, a block
* right after that commit freezes it (iOS 26.2 simulator: 2 of 7 runs kept
* moving, 0 of 5 on a ::before). Every animation the animator creates, and
- * every `set`, therefore promotes its channels in the same task: inline
+ * every `set` (unless it passes `{promote: false}`), therefore promotes its
+ * channels in the same task: inline
* `will-change` on the element, merged with the element's own, or the custom
* property `--astryx-motion-will-change-<pseudo>` on the host for a
* pseudo-element, whose style opts in with
@@ -116,8 +134,8 @@
* call that lands too carries a landing still waiting (two calls in one
* frame land together), and a later opacity change lands it at once;
* - on any other primary pointer (DR3) it completes at once.
- * No call option and no theme value lengthens the fade or keeps travel (DR4):
- * the fade's length is not a theme role.
+ * No call option and no role value lengthens the fade or keeps travel (DR4):
+ * the fade's length is not a role.
*
* Momentum under Reduce Motion (`design:reduced-motion` DR2, DEC-2): a
* decay's momentum continues the velocity a finger handed it on release
@@ -129,6 +147,15 @@
* Motion policy above, a cross-fade on a coarse pointer or after a touch
* release (`touchRelease`) and at once elsewhere (DR2, DR3).
*
+ * Roles: every spring and curve the animator plays passes through
+ * resolveMotion.ts, which names the motion role it plays (`springs.settle`
+ * once `registerSpringsTable()` has run, the Reduce Motion fade's curve,
+ * which the animator registers alone). The per-role tables stay internal
+ * (`spec:AST-094` DEC-15), so a role plays its table value: nothing reads a
+ * CSS variable or the element's style for it. A spring written inline at the call
+ * site, and a table never registered, play as given; the fade's length is not
+ * a role.
+ *
* A pseudo-element (`options.pseudoElement`, a dialog's `::backdrop`) has no
* inline style: its end value is held by a static filling animation (after a
* curve ends, and after `set`) until the next animation replaces it, and for
@@ -143,12 +170,18 @@
* SYNC: When modified, update:
* - /packages/core/src/motion/animator.test.ts
* - /packages/core/src/motion/reducedMotionPlan.ts (the Reduce Motion plan)
+ * - /packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts
+ * - /packages/core/src/motion/resolveMotion.ts (the roles it resolves)
* - /packages/core/src/motion/README.md
*/
import {cubicBezier} from './bezier';
import {solveSpring, toSpring, type SpringDescription} from './spring';
-import {reducedMotionCrossFade} from './uikit/timing';
+import {resolveMotion} from './resolveMotion';
+import {
+ reducedMotionCrossFade,
+ registerReducedMotionCrossFade,
+} from './uikit/timing';
import {planReducedMotion, type ReducedMotionView} from './reducedMotionPlan';
/**
@@ -204,6 +237,36 @@ export interface AnimateOptions {
* changes nothing.
*/
crossfadeAs?: 'entrance' | 'exit';
+ /**
+ * When the call's animations start. By default a call from rest starts
+ * when the browser commits it, and a call that continues motion on screen
+ * (a retarget) starts now, from the value on screen. Ignored with `at`.
+ * - `'commit'`: a call that continues motion also starts when the browser
+ * commits it, dated by the browser rather than by the main thread, as a
+ * call from rest is.
+ * - `'presented'`: a call from rest leaves its element at rest and creates
+ * its animations two frames later, once the frame that carries the
+ * element at rest has been presented; they then start at their commit. A
+ * busy UI process delays the motion instead of skipping into it, for two
+ * frames more before an idle start. Any other change to the animator
+ * before then creates the animations first, in call order. A call that
+ * continues motion on screen (a retarget) starts now, as by default.
+ */
+ start?: 'commit' | 'presented';
+ /**
+ * A call that retargets a curve on screen adds to it instead of replacing
+ * it, as UIKit's animations do: the old curve keeps going (past its end, at
+ * its target) and a spring of the difference between the two targets runs
+ * from 0 on top, in the same animation. Its value and velocity at the call
+ * are the old curve's, so whichever frame first shows it (WebKit can apply
+ * a new curve tens of ms late), nothing steps back. Ignored for a property
+ * at rest or still waiting for the browser's start, for a property given a
+ * velocity, and under Reduced Motion. Use it for a played curve that starts
+ * at rest (an eased reversal) while the property moves; a spring retarget
+ * on the same spring moves the same either way, and a curve that already
+ * continues the velocity on screen must not add to it.
+ */
+ additive?: boolean;
}
/**
@@ -231,6 +294,21 @@ export interface MotionCurve {
/**
* Options of `createAnimator`.
*/
+/** How `set` puts values in place. */
+export interface SetOptions {
+ /**
+ * Whether the write promotes its channels to a compositing layer, as a
+ * drag's per-frame writes need so each is a composite only (default
+ * true). `false` writes the values and nothing else: a one-off switch that
+ * must not give its element a layer, such as a veil under a sticky header
+ * switched during a programmatic scroll (on iOS 26.2, a layer there blanks
+ * the header's painted items for about two frames). A channel another
+ * motion keeps promoted stays promoted, and a channel with other motion
+ * still running gets its animation's layer as usual.
+ */
+ promote?: boolean;
+}
+
export interface AnimatorOptions {
/**
* Animates a pseudo-element of the element instead (`'::backdrop'` of a
@@ -270,6 +348,14 @@ export interface MotionHandle {
value(property: MotionProperty, time?: number): number;
/** Presentation velocity of a property at `time`, units/s. */
velocity(property: MotionProperty, time?: number): number;
+ /**
+ * The curve this call started on `property` (`scale` reads `scaleX`),
+ * in seconds from the call's start: what the keyframes play. Null for a
+ * property the call does not move, or moves without travel (Reduced
+ * Motion). Map it onto a companion property with `mapProgress`, and play
+ * that on the same clock.
+ */
+ curve(property: MotionProperty | 'scale'): MotionCurve | null;
/** New targets for this call's properties, keeping their velocity. */
retarget(
to: MotionValues,
@@ -310,7 +396,7 @@ export interface Animator {
* of a drag (one style write per channel, no animation when nothing else
* on the channel is moving).
*/
- set(values: MotionValues): void;
+ set(values: MotionValues, options?: SetOptions): void;
/** Springs to `to` from the presentation values. */
animate(
to: MotionValues,
@@ -404,10 +490,22 @@ interface Segment {
*/
interface StartGroup {
readonly provisional: number;
+ /**
+ * Its animations were created in the running task: the browser cannot have
+ * started them yet, so nothing reads their start time until it ends.
+ */
+ fresh: boolean;
readonly segments: Segment[];
readonly animations: Animation[];
readonly channels: Set<Channel>;
resolved: boolean;
+ /**
+ * The first frame after the call has run: a start read later is the
+ * browser's, whatever it says (startAfterBlock).
+ */
+ framed?: boolean;
+ /** The task it was made in, with every call made in that task. */
+ task?: TaskMark;
/** A later call in the same task that took over its curves. */
adoptedBy?: StartGroup;
readonly resolve: (start: number) => void;
@@ -432,7 +530,12 @@ interface HandleState {
* dip, the fade back in.
*/
interface Landing {
- readonly owner: HandleState;
+ /**
+ * The call that settles when the landing (and its fade back in) ends; a
+ * call that joins the dip takes it over, and the call it replaces is
+ * carried.
+ */
+ owner: HandleState;
/** ms after the call's start. */
readonly at: number;
readonly values: Map<MotionProperty, number>;
@@ -472,6 +575,8 @@ interface ReducedPlan {
> | null;
/** The stylesheet opacity a dip borrowed (no call owns opacity). */
readonly borrowed?: number | null;
+ /** The call joins the waiting dip (see the planner's `joins`). */
+ readonly joins?: boolean;
}
const PROPERTIES: ReadonlyArray<MotionProperty> = [
@@ -509,32 +614,106 @@ export const SETTLE_THRESHOLD: Record<MotionProperty, number> = {
opacity: 0.001,
};
-/** Keyframes are added until linear interpolation is within this. */
+/**
+ * Keyframes are added until linear interpolation is within this: a quarter of
+ * a device pixel (this quarter of a CSS pixel, divided by the device pixel
+ * ratio where it is above 1), a twentieth of a degree, a 2000th of the size,
+ * about one step of an 8-bit alpha. Every one is below what a moving element
+ * can show.
+ */
const SAMPLE_TOLERANCE: Record<MotionProperty, number> = {
- x: 0.05,
- y: 0.05,
- rotate: 0.02,
- scaleX: 0.0002,
- scaleY: 0.0002,
- opacity: 0.002,
+ x: 0.25,
+ y: 0.25,
+ rotate: 0.05,
+ scaleX: 0.0005,
+ scaleY: 0.0005,
+ opacity: 0.004,
};
+/** Keyframes start on this grid (ms) and are split where the curve needs it. */
+const SAMPLE_GRID_MS = 1000 / 30;
+
/** A curve that has not settled by then (an undamped spring) snaps. */
const MAX_DURATION_MS = 30_000;
+
+/**
+ * How long a task must run on past its first call from rest before that
+ * counts as a block (WebKit; startAfterBlock): two frames at 60 Hz.
+ */
+// Browser start times are frame times and a task's end a live clock, so only a block longer than a frame plus the task's own length can be told apart from that quantization.
+const LATE_START_MS = 34;
+
+/**
+ * The task calls from rest are made in, shared by every call made in it
+ * (every animator's), so one motion's parts that are separate calls start
+ * together (startAfterBlock).
+ */
+interface TaskMark {
+ /**
+ * When its first call from rest created animations: the call itself, or a
+ * presented call's second frame.
+ */
+ readonly first: number;
+ /** When the task ended, at its first microtask. */
+ ended?: number;
+ /** The start every call of a blocked task moves to, set by its first read. */
+ at?: number;
+}
+
+/** The task the current calls from rest are made in, until it ends. */
+let openTask: TaskMark | null = null;
+
+/** The mark of the running task, opened by its first call from rest. */
+function markTask(time: number, clock: () => number): TaskMark {
+ if (openTask == null) {
+ const task: TaskMark = {first: time};
+ openTask = task;
+ queueMicrotask(() => {
+ task.ended = clock();
+ openTask = null;
+ });
+ }
+ return openTask;
+}
+
/** Above this many keyframes the tolerance is relaxed. */
const MAX_KEYFRAMES = 1200;
/**
* The keyframes hold the end state this long after a curve ends. An engine
* whose compositor ends an animation while the main thread is blocked falls
- * back to the value its main thread last committed, mid-flight (WebKit); the
- * hold keeps the end state on screen through such a block. The main thread
- * drops the animation as soon as it runs after the curve's end.
+ * back to the value its main thread last committed, the curve's start
+ * (WebKit on Linux); the hold keeps the end state on screen through any such
+ * block. It only stretches the last keyframe. The main thread retires the
+ * animation as soon as it runs after the curve's end.
+ *
+ * Why a tail inside the curve's own animation, with a bound (measured Oct 24
+ * 2026; do not replace it without these proofs):
+ * - WebKit on Linux (WebKitGTK and WPE) ignores `fill` on its compositor:
+ * a 400 ms move that ends during a 1 s main-thread block snaps back to the
+ * block-start position 13 ms after its end, with `fill: forwards` or with
+ * no fill, and holds with this tail. iOS 26.2 Mobile Safari holds the end
+ * in all three forms, so there the tail is unneeded but harmless (measured
+ * Oct 25 2026). The browser proof "a spring that ends inside the block
+ * keeps showing its end state" catches it.
+ * - A separate static animation of the end state under the curve would hold
+ * it without a bound, but two animations on one property push Chromium to
+ * run the curve on the main thread: the 1 s block proof moved in 0 of 57
+ * frames, the start-before-a-block proof failed, and seeking the curve
+ * broke.
*/
-export const END_HOLD_MS = 5000;
+export const END_HOLD_MS = 60_000;
/** How often a paused animation is looked at again for retiring, ms. */
const RETIRE_RECHECK_MS = 100;
+/**
+ * The soonest a running animation's end is looked for again, ms: a frame at
+ * 60 Hz. WebKit moves an animation's currentTime once per frame, so a look
+ * within a frame reads the frame's time, a fraction of a ms short of the end,
+ * and a timer for that fraction would fire again before anything moved.
+ */
+const END_RECHECK_MS = 1000 / 60;
+
/** How long an element stays promoted after its last motion, ms. */
export const PROMOTION_LINGER_MS = 500;
@@ -717,8 +896,9 @@ const REDUCED_TRANSITION: SpringTransition = {
* @example
* ```
* const animator = createAnimator(sheet);
- * // finger lifts at 1200 px/s heading for the detent at 0:
- * animator.animate({y: 0}, {spring: springs.sheetDetent, velocity: {y: 1200}});
+ * // finger lifts at 1200 px/s heading for the detent at 0 (a component
+ * // passes the spring of its motion role):
+ * animator.animate({y: 0}, {spring: {response: 0.45, dampingRatio: 0.9}, velocity: {y: 1200}});
* // the finger lands again: where is it right now?
* const y = animator.get('y', event.timeStamp);
* animator.stop(['y']);
@@ -786,6 +966,15 @@ export function createAnimator(
let ownWillChange: string | null = null;
/** The stylesheet's will-change when there is no inline value. */
let sheetWillChange = '';
+ /**
+ * Whether sheetWillChange holds a read of the element's current style: it
+ * is read in the task after the element is attached, and again after each
+ * demotion, so a promotion (a drag's first move) reads no style in its
+ * own task.
+ */
+ let sheetWillChangeRead = false;
+ /** The pending read of sheetWillChange, cancelled with its element. */
+ let sheetReadTimer: ReturnType<typeof setTimeout> | null = null;
let demoteTimer: ReturnType<typeof setTimeout> | null = null;
/** A pseudo-element is promoted through a custom property on its host. */
const promotionProperty =
@@ -872,18 +1061,22 @@ export function createAnimator(
const writeInline = (
channel: Channel,
value: (property: MotionProperty) => number,
+ release = true,
) => {
if (target == null || pseudoElement != null) {
return;
}
touched.add(channel);
const text = inlineText(channel, value);
- if (text === IDENTITY_TEXT[channel]) {
- // Identity leaves the element when nothing else would move it.
+ // An unchanged value is not written: a style write invalidates the
+ // element, and WebKit can repaint sticky content stale when that lands in
+ // the frame a scroll commits.
+ if (target.style.getPropertyValue(channel) !== text) {
target.style.setProperty(channel, text);
+ }
+ if (release && text === IDENTITY_TEXT[channel]) {
+ // Identity leaves the element when nothing else would move it.
releaseIdentity(channel);
- } else {
- target.style.setProperty(channel, text);
}
};
@@ -911,9 +1104,9 @@ export function createAnimator(
for (let e = 0; e + 1 < edges.length; e++) {
const a = edges[e];
const b = edges[e + 1];
- // A 120 Hz grid, each interval split until the chord is within the
+ // A 30 Hz grid, each interval split until the chord is within the
// tolerance at its quarter points.
- const steps = Math.max(1, Math.ceil((b - a) / (1000 / 120)));
+ const steps = Math.max(1, Math.ceil((b - a) / SAMPLE_GRID_MS));
const split = (t0: number, t1: number, depth: number) => {
const v0 = value(t0);
const v1 =
@@ -958,9 +1151,10 @@ export function createAnimator(
running.delete(channel);
clearTimeout(retireTimers.get(channel));
retireTimers.delete(channel);
- // An element's inline style holds the end state, so its old animation can
- // go first. A pseudo-element has none: its old animation keeps holding the
- // value until the new one exists (same task, no frame in between).
+ // An element's inline style takes the value on screen below, so its old
+ // animation can go first. A pseudo-element has none: its old animation
+ // keeps holding the value until the new one exists (same task, no frame in
+ // between).
if (pseudoElement == null) {
previous?.cancel();
}
@@ -973,8 +1167,18 @@ export function createAnimator(
segments.delete(property);
}
}
- writeInline(channel, finalValue);
const moving = properties.filter(p => segments.has(p));
+ if (
+ moving.length === 0 ||
+ target == null ||
+ typeof target.animate !== 'function'
+ ) {
+ writeInline(channel, finalValue);
+ } else {
+ // The value on screen as the curve starts: what a frame painted before
+ // the compositor has the curve shows. The end is written at retire.
+ writeInline(channel, p => valueAt(p, time));
+ }
if (target == null || typeof target.animate !== 'function') {
previous?.cancel();
return;
@@ -1036,15 +1240,17 @@ export function createAnimator(
}
}
}
+ // Read where the keyframes are baked: a page moved to another screen
+ // bakes its next motion for that screen.
+ const devicePixel = 1 / Math.max(1, globalThis.devicePixelRatio || 1);
const collect = (scale: number) => {
const times = new Set<number>([from, end]);
for (const property of moving) {
- for (const t of sampleTimes(
- property,
- from,
- end,
- SAMPLE_TOLERANCE[property] * scale,
- )) {
+ const tolerance =
+ SAMPLE_TOLERANCE[property] *
+ scale *
+ (property === 'x' || property === 'y' ? devicePixel : 1);
+ for (const t of sampleTimes(property, from, end, tolerance)) {
times.add(t);
}
}
@@ -1093,8 +1299,8 @@ export function createAnimator(
duration: span,
// The last keyframes hold the end state (END_HOLD_MS); filling both
// ways also keeps it where an engine honors the fill on its compositor.
- // The main thread drops the animation once it runs after the end; the
- // inline style already holds the same values, so that changes no pixel.
+ // The main thread retires the animation once it runs after the end,
+ // writing the end inline in that task, so that changes no pixel.
fill: 'both',
easing: 'linear',
...(pseudoElement != null ? {pseudoElement} : {}),
@@ -1118,9 +1324,16 @@ export function createAnimator(
/**
* Once the main thread runs after the curve's end, the animation leaves the
- * running state: an element's inline style already shows the end values; a
- * pseudo-element's end value moves to a static holding animation, created
- * before the long one goes.
+ * running state: an element's end values are written inline in the task
+ * that cancels it; a pseudo-element's end value moves to a static holding
+ * animation, created before the long one goes.
+ *
+ * Why a timer at the curve's end: no browser event reports that an
+ * animation's time has reached a point inside its effect, and its
+ * `finished` comes only after the END_HOLD_MS tail, which would keep the
+ * element promoted and the animation alive for a minute. The timer is set
+ * on the curve's own clock and re-armed while a sampler pauses or seeks the
+ * animation, so it never retires a held one.
*/
const scheduleRetire = (
channel: Channel,
@@ -1141,7 +1354,9 @@ export function createAnimator(
channel,
setTimeout(
retire,
- animation.playState === 'paused' ? RETIRE_RECHECK_MS : remaining,
+ animation.playState === 'paused'
+ ? RETIRE_RECHECK_MS
+ : Math.max(remaining, END_RECHECK_MS),
),
);
return;
@@ -1155,8 +1370,27 @@ export function createAnimator(
![...landings].some(landing => landing.fadeIn?.isBorrowed === true);
if (pseudoElement != null && !handsBack) {
hold(channel, now());
+ } else {
+ // The end goes inline in the task that cancels the animation. Whether
+ // an identity end may leave the element is judged after the cancel:
+ // until then the end-state tail still holds the end, so the computed
+ // style would hide a stylesheet value (an opacity 0) under it.
+ writeInline(channel, finalValue, false);
+ }
+ // A call from rest the browser never started (finished from outside
+ // before its first frame, a sampler's finish()): read its start from the
+ // animation before the cancel takes it, and with nothing left to wait
+ // on the call keeps its own clock, so its landing is still armed.
+ const waiting = [...pendingGroups].filter(group =>
+ group.animations.includes(animation),
+ );
+ for (const group of waiting) {
+ syncGroup(group);
}
animation.cancel();
+ for (const group of waiting) {
+ resolveGroup(group, group.provisional);
+ }
releaseIdentity(channel);
flushReleases();
};
@@ -1369,13 +1603,12 @@ export function createAnimator(
if (ownWillChange == null) {
ownWillChange = element.style.willChange;
// Without an inline value, the stylesheet's reasons stay alongside the
- // promotion's (read once, as the promotion starts).
- sheetWillChange =
- ownWillChange === ''
- ? (element.ownerDocument.defaultView
- ?.getComputedStyle(element)
- .getPropertyValue('will-change') ?? '')
- : '';
+ // promotion's. They were read in the task after the element was
+ // attached; a promotion that comes first (an element attached in this
+ // task that moves at once) reads them now.
+ if (ownWillChange === '' && !sheetWillChangeRead) {
+ readSheetWillChange(element);
+ }
}
const base = ownWillChange !== '' ? ownWillChange : sheetWillChange;
const own = base === 'auto' ? '' : base;
@@ -1386,6 +1619,48 @@ export function createAnimator(
element.style.willChange = [...reasons, ...promoted].join(', ');
};
+ /** Reads the element's own will-change while no promotion of ours is written. */
+ const readSheetWillChange = (element: HTMLElement) => {
+ sheetWillChange =
+ element.ownerDocument.defaultView
+ ?.getComputedStyle(element)
+ .getPropertyValue('will-change') ?? '';
+ sheetWillChangeRead = true;
+ };
+
+ /**
+ * Reads sheetWillChange in a task of its own, so a later promotion reads no
+ * style in its own task. Skipped while a promotion of ours is written,
+ * which the read would see (demote asks again), and for a node out of the
+ * document. A pseudo-element's promotion is its own property, with
+ * nothing to read.
+ */
+ const readSheetWillChangeLater = () => {
+ cancelSheetWillChangeRead();
+ sheetWillChangeRead = false;
+ if (target == null || promotionProperty != null) {
+ return;
+ }
+ const element = target;
+ sheetReadTimer = setTimeout(() => {
+ sheetReadTimer = null;
+ // A node out of the document has no style to read, and reading one
+ // still costs a style pass: a shared animator (animatorFor) is never
+ // detached, so its node can leave with this read waiting. Skipped, the
+ // read waits for a promotion that needs it.
+ if (target === element && promoted.size === 0 && element.isConnected) {
+ readSheetWillChange(element);
+ }
+ }, 0);
+ };
+
+ const cancelSheetWillChangeRead = () => {
+ if (sheetReadTimer != null) {
+ clearTimeout(sheetReadTimer);
+ sheetReadTimer = null;
+ }
+ };
+
/**
* Gives the element (or its pseudo-element) a compositing layer for
* `channel` from the task that starts the motion: Mobile Safari runs an
@@ -1440,6 +1715,8 @@ export function createAnimator(
promoted.clear();
if (target != null) {
writePromotion(target);
+ // Its stylesheet may have changed its will-change since.
+ readSheetWillChangeLater();
}
};
@@ -1455,6 +1732,7 @@ export function createAnimator(
time: number,
properties: Iterable<MotionProperty>,
at: number | undefined,
+ start?: AnimateOptions['start'],
): StartGroup | null => {
if (target == null || typeof target.animate !== 'function') {
return null;
@@ -1482,7 +1760,11 @@ export function createAnimator(
}
return null;
}
- for (const channel of channels) {
+ // A call that continues motion starts now unless it asks for the
+ // browser's start (`commit`). `presented` asks only for a call from rest:
+ // an element still moving is not at rest, so a retarget starts now, from
+ // the value and velocity on screen (spec:AST-094 FR6).
+ for (const channel of start === 'commit' ? [] : channels) {
for (const property of CHANNELS[channel]) {
const segment = segments.get(property);
if (
@@ -1500,6 +1782,7 @@ export function createAnimator(
});
return {
provisional: time,
+ fresh: false,
segments: [],
animations: [],
channels: new Set(),
@@ -1515,6 +1798,7 @@ export function createAnimator(
owner: HandleState,
changed: MotionProperty[],
time: number,
+ presented = false,
) => {
if (group != null) {
for (const property of changed) {
@@ -1525,6 +1809,99 @@ export function createAnimator(
}
}
}
+ if (presented && group != null && requestFrame != null) {
+ // At rest until then: the animations, and the layer they promote, come
+ // two frames later. Promoting now, a layer at rest for two frames, left
+ // a stale paint of the element's rest in WebKit on iOS 26.2 (a title in
+ // a scroller inside a clipped card) after the motion ended.
+ // Each call waits its own two frames: one queued after another change
+ // flushed the queue, or after an earlier call's first frame, still
+ // waits its two.
+ const call = {group, changed};
+ deferredCalls.push(call);
+ requestFrame(() => requestFrame(() => flushDeferredThrough(call)));
+ return;
+ }
+ startCall(group, changed, time);
+ };
+
+ /** Calls with `start: 'presented'` waiting for their second frame. */
+ const deferredCalls: {group: StartGroup; changed: MotionProperty[]}[] = [];
+
+ /** Creates the animations of the given waiting calls, in call order. */
+ const startDeferred = (
+ calls: {group: StartGroup; changed: MotionProperty[]}[],
+ ) => {
+ for (const {group, changed} of calls) {
+ // Not a channel that holds the curve of a later call still waiting: a
+ // later presented call that took a property over starts that channel
+ // with its own two frames. Every other property starts here, whatever
+ // its segment's group: a value Reduce Motion writes at once, or lands
+ // under a dip, has no curve of this call's.
+ const own: MotionProperty[] = [];
+ let handedTo: StartGroup | null = null;
+ for (const property of changed) {
+ const holder = CHANNELS[CHANNEL_OF[property]]
+ .map(other => segments.get(other)?.group)
+ .find(
+ waiting =>
+ waiting != null &&
+ waiting !== group &&
+ deferredCalls.some(call => call.group === waiting),
+ );
+ if (holder == null) {
+ own.push(property);
+ continue;
+ }
+ // A curve of this call's in that channel never ran: the element held
+ // it at its start. It starts with the later call, which creates the
+ // channel, dated from that call's start, so the model reads what the
+ // screen shows.
+ const segment = segments.get(property);
+ if (segment != null && segment.group === group) {
+ segment.start += holder.provisional - group.provisional;
+ segment.group = holder;
+ holder.segments.push(segment);
+ group.segments.splice(group.segments.indexOf(segment), 1);
+ handedTo = holder;
+ }
+ }
+ if (own.length === 0 && handedTo != null) {
+ // Everything this call still plays starts with the later call.
+ const adopter = handedTo;
+ group.adoptedBy = adopter;
+ void adopter.started.then(start => resolveGroup(group, start));
+ continue;
+ }
+ // From the call's own time: the curve starts at the browser's commit.
+ startCall(group, own, group.provisional);
+ }
+ };
+
+ /** Creates the animations of every waiting call, in call order. */
+ const flushDeferred = () => {
+ startDeferred(deferredCalls.splice(0));
+ };
+
+ /**
+ * A call's second frame: it starts, with every call queued before it (in
+ * call order), unless another change created it already.
+ */
+ const flushDeferredThrough = (call: {
+ group: StartGroup;
+ changed: MotionProperty[];
+ }) => {
+ const index = deferredCalls.indexOf(call);
+ if (index >= 0) {
+ startDeferred(deferredCalls.splice(0, index + 1));
+ }
+ };
+
+ const startCall = (
+ group: StartGroup | null,
+ changed: MotionProperty[],
+ time: number,
+ ) => {
callGroup = group;
try {
commit(changed, time);
@@ -1539,6 +1916,14 @@ export function createAnimator(
return;
}
pendingGroups.add(group);
+ group.fresh = true;
+ // The task that creates the animations, not the call's: a presented
+ // call's is its second frame's callback, wherever in its frame the call
+ // was made.
+ group.task = markTask(now(), now);
+ queueMicrotask(() => {
+ group.fresh = false;
+ });
for (const animation of group.animations) {
// A cancel before the first frame rejects each one's ready promise.
(animation as Partial<Animation>).ready?.catch(() => {});
@@ -1552,7 +1937,10 @@ export function createAnimator(
// or when its compositor starts them (Chromium). Read it in that first
// frame, ahead of anything that might pause or seek the animations, and
// when `ready` settles.
- requestFrame?.(() => syncGroup(group));
+ requestFrame?.(() => {
+ syncGroup(group);
+ group.framed = true;
+ });
ready.then(
() => syncGroup(group),
() => settleCancelled(group),
@@ -1609,7 +1997,10 @@ export function createAnimator(
}
for (const animation of group.animations) {
if (animation.startTime != null) {
- resolveGroup(group, Number(animation.startTime));
+ resolveGroup(
+ group,
+ startAfterBlock(group, Number(animation.startTime)),
+ );
return;
}
}
@@ -1642,10 +2033,16 @@ export function createAnimator(
}
};
- /** Reads the start of every call whose first frame has been committed. */
+ /**
+ * Reads the start of every call whose first frame may have been committed:
+ * not those created in the running task, whose start the browser cannot
+ * have set (reading it there can cost a style update per call).
+ */
const syncPending = () => {
for (const group of pendingGroups) {
- syncGroup(group);
+ if (!group.fresh) {
+ syncGroup(group);
+ }
}
syncFinished();
};
@@ -1673,6 +2070,55 @@ export function createAnimator(
}
};
+ /**
+ * The start of a call from rest, on the frame that commits it. Chromium,
+ * like Core Animation, starts a pending animation when it commits it, so a
+ * main-thread block later in the call's task delays the motion; WebKit
+ * dates it at its last frame time before that task, so the first frame
+ * after the block would show it skipped into its curve. When the task ran
+ * on more than LATE_START_MS past its first call, a start the browser put
+ * by the task's first animations (a presented call's second frame, not the
+ * call) and more than LATE_START_MS before the call's first read (its
+ * `ready`, once the task has ended, or the first frame after it) moves to
+ * that read, with every animation of the call, and every call of the task
+ * moves to the same read. A shorter task, or a read other tasks delay,
+ * keeps the browser's start.
+ */
+ const startAfterBlock = (group: StartGroup, start: number): number => {
+ const timeline =
+ typeof document === 'undefined'
+ ? null
+ : (document.timeline?.currentTime as number | null | undefined);
+ // A start well after the animations were created is the browser's
+ // commit of them.
+ if (
+ timeline == null ||
+ group.framed === true ||
+ start > (group.task?.first ?? group.provisional) + LATE_START_MS
+ ) {
+ return start;
+ }
+ const {task} = group;
+ // A read in the task's first microtasks comes after its end too.
+ const ended = task?.ended ?? now();
+ if (task == null || ended - task.first <= LATE_START_MS) {
+ return start;
+ }
+ // Read once the task has ended (its `ready`) or in the first frame after
+ // it, both after the block; the task's other calls take the same read.
+ const at = task.at ?? Math.max(now(), timeline);
+ if (at - start <= LATE_START_MS) {
+ return start;
+ }
+ task.at = at;
+ for (const animation of group.animations) {
+ if (animation.playState !== 'idle') {
+ animation.startTime = at;
+ }
+ }
+ return at;
+ };
+
/** Moves a call from rest onto the time the browser started it. */
const resolveGroup = (group: StartGroup, start: number) => {
if (group.resolved) {
@@ -1714,10 +2160,7 @@ export function createAnimator(
.filter(segment => segment.owner === owner)
.map(segment => segment.start + segment.duration);
owner.timer = setTimeout(
- () => {
- owner.timer = null;
- settle(owner, true);
- },
+ () => settleAtEnd(owner),
Math.max(0, Math.max(start, ...ends) - now()),
);
}
@@ -1755,12 +2198,48 @@ export function createAnimator(
owner.resolve(finished);
};
+ /**
+ * A handle whose curves have reached their end on the wall clock finishes,
+ * unless a sampler holds one of its animations (paused, or sought back):
+ * then it waits on that animation's own time, as retiring does
+ * (scheduleRetire), so `finished` never resolves under motion still on
+ * screen.
+ */
+ const settleAtEnd = (owner: HandleState) => {
+ owner.timer = null;
+ let wait = 0;
+ for (const [channel, animation] of running) {
+ if (
+ !CHANNELS[channel].some(
+ property => segments.get(property)?.owner === owner,
+ )
+ ) {
+ continue;
+ }
+ const remaining = remainingCurve(animation);
+ if (remaining != null && remaining > 0) {
+ wait = Math.max(
+ wait,
+ animation.playState === 'paused'
+ ? RETIRE_RECHECK_MS
+ : Math.max(remaining, END_RECHECK_MS),
+ );
+ }
+ }
+ if (wait > 0) {
+ owner.timer = setTimeout(() => settleAtEnd(owner), wait);
+ return;
+ }
+ settle(owner, true);
+ };
+
const makeHandle = (
owner: HandleState,
properties: MotionProperty[],
finished: Promise<boolean>,
time: number,
group: StartGroup | null = null,
+ settlesWithLanding = false,
): MotionHandle => {
const ends = properties.map(p => {
const segment = segments.get(p);
@@ -1769,23 +2248,45 @@ export function createAnimator(
: time;
});
const end = Math.max(time, ...ends);
- if (properties.length === 0 || end <= time) {
+ if (settlesWithLanding) {
+ // The landing it joined settles it.
+ } else if (properties.length === 0 || end <= time) {
settle(owner, true);
} else {
// Interruptions settle false as they happen (interrupt); reaching the
// end untouched is completion.
owner.timer = setTimeout(
- () => {
- owner.timer = null;
- settle(owner, true);
- },
+ () => settleAtEnd(owner),
Math.max(0, end - now()),
);
}
+ // The call's own curves, as it started them.
+ const curves = new Map<MotionProperty, Segment>();
+ for (const property of properties) {
+ const segment = segments.get(property);
+ if (segment != null && segment.owner === owner) {
+ curves.set(property, segment);
+ }
+ }
const handle: MotionHandle = {
properties,
finished,
started: group?.started ?? Promise.resolve(time),
+ curve: property => {
+ const segment = curves.get(property === 'scale' ? 'scaleX' : property);
+ if (segment == null) {
+ return null;
+ }
+ return {
+ duration: segment.duration / 1000,
+ at: t =>
+ t * 1000 >= segment.duration
+ ? segment.target
+ : segment.at(Math.max(0, t * 1000)),
+ velocity: t =>
+ t * 1000 >= segment.duration ? 0 : segment.speed(t * 1000),
+ };
+ },
value: (property, at = now()) => {
syncPending();
return valueAt(property, at);
@@ -1844,7 +2345,9 @@ export function createAnimator(
if (from === to && velocity === 0) {
return null;
}
- const curve = solveSpring(toSpring(spring), {from, to, velocity});
+ // The motion role it plays: its table value (DEC-15).
+ const resolved = resolveMotion(target, spring);
+ const curve = solveSpring(toSpring(resolved), {from, to, velocity});
const duration = Math.min(
MAX_DURATION_MS,
curve.settleTime(SETTLE_THRESHOLD[property]) * 1000,
@@ -1857,7 +2360,81 @@ export function createAnimator(
speed: t => curve.velocity(t / 1000),
jumps: [],
owner,
- spring,
+ spring: resolved,
+ };
+ };
+
+ /** The retarget of `additive`: the old curve plus a spring of the difference. */
+ const additiveSegment = (
+ owner: HandleState,
+ property: MotionProperty,
+ start: number,
+ to: number,
+ spring: SpringDescription,
+ old: Segment,
+ ): Segment => {
+ const oldEnd = old.start + old.duration;
+ const resolved = resolveMotion(target, spring);
+ const delta = solveSpring(toSpring(resolved), {
+ from: 0,
+ to: to - old.target,
+ velocity: 0,
+ });
+ const deltaMs = Math.min(
+ MAX_DURATION_MS,
+ delta.settleTime(SETTLE_THRESHOLD[property]) * 1000,
+ );
+ const ownAt = (t: number) =>
+ t >= deltaMs ? to - old.target : delta.value(t / 1000);
+ const oldAt = (time: number) =>
+ time >= oldEnd ? old.target : old.at(Math.max(0, time - old.start));
+ return {
+ start,
+ duration: Math.min(MAX_DURATION_MS, Math.max(oldEnd - start, deltaMs)),
+ target: to,
+ at: t => oldAt(start + t) + ownAt(t),
+ speed: t =>
+ (start + t >= oldEnd ? 0 : old.speed(start + t - old.start)) +
+ (t >= deltaMs ? 0 : delta.velocity(t / 1000)),
+ jumps: old.jumps
+ .map(jump => old.start + jump - start)
+ .filter(jump => jump > 0),
+ owner,
+ spring: resolved,
+ };
+ };
+
+ /**
+ * `additive` for a played curve: the old curve plus the new curve's shape,
+ * scaled to the difference between the two targets.
+ */
+ const additiveCurveSegment = (
+ owner: HandleState,
+ start: number,
+ curve: MotionCurve,
+ old: Segment,
+ ): Segment => {
+ const from = curve.at(0);
+ const to = curve.at(curve.duration);
+ const scale = (to - old.target) / (to - from);
+ const ms = Math.min(MAX_DURATION_MS, curve.duration * 1000);
+ const oldEnd = old.start + old.duration;
+ const oldAt = (time: number) =>
+ time >= oldEnd ? old.target : old.at(Math.max(0, time - old.start));
+ return {
+ start,
+ duration: Math.min(MAX_DURATION_MS, Math.max(oldEnd - start, ms)),
+ target: to,
+ at: t =>
+ oldAt(start + t) +
+ (t >= ms ? to - old.target : (curve.at(t / 1000) - from) * scale),
+ speed: t =>
+ (start + t >= oldEnd ? 0 : old.speed(start + t - old.start)) +
+ (t >= ms ? 0 : curve.velocity(t / 1000) * scale),
+ jumps: old.jumps
+ .map(jump => old.start + jump - start)
+ .filter(jump => jump > 0),
+ owner,
};
};
@@ -1867,7 +2444,10 @@ export function createAnimator(
stops: ReadonlyArray<{at: number; value: number}>,
jumps: ReadonlyArray<number> = [],
): Segment => {
- const ease = cubicBezier(reducedMotionCrossFade.curve);
+ registerReducedMotionCrossFade();
+ const ease = cubicBezier(
+ resolveMotion(target, reducedMotionCrossFade.curve),
+ );
const duration = stops[stops.length - 1].at;
const at = (t: number) => {
for (let i = 0; i + 1 < stops.length; i++) {
@@ -1990,6 +2570,27 @@ export function createAnimator(
return {carried, owners};
};
+ /**
+ * A call joins the newest waiting dip: it takes the landing over and
+ * settles when the dip ends, and the call it replaces lands with it. Each
+ * value keeps the call whose move it is.
+ */
+ const joinWaitingDip = (owner: HandleState) => {
+ const dip = [...landings].reverse().find(landing => landing.fadeIn != null);
+ if (dip == null) {
+ settle(owner, true);
+ return;
+ }
+ for (const property of dip.values.keys()) {
+ if (!dip.owners.has(property)) {
+ dip.owners.set(property, dip.owner);
+ }
+ }
+ dip.carried.push(dip.owner);
+ carriedOwners.add(dip.owner);
+ dip.owner = owner;
+ };
+
/** Where opacity is heading: past a waiting landing's fade back in. */
const opacityHeading = (): number => {
let to = finalValue('opacity');
@@ -2052,8 +2653,9 @@ export function createAnimator(
* never an animation (DR2: opacity only), so it is never shown in the wrong
* place. In a dip the fade back in starts from here and takes what is left
* of the cross-fade, so the dip ends when it was due even when a busy main
- * thread runs this timer late; past the whole fade back in (over 100 ms
- * late) the element appears at once where it landed.
+ * thread runs this timer late; past the whole fade back in (100 ms late or
+ * more) the element appears at once where it landed, with no animation,
+ * and the call settles then.
*/
const land = (landing: Landing) => {
landings.delete(landing);
@@ -2066,13 +2668,16 @@ export function createAnimator(
changed.push(property);
}
let end = time;
- if (landing.fadeIn != null) {
- // The fade back in takes what is left of the cross-fade: a timer that
- // a busy main thread runs late shortens it, so the dip still ends
- // when it was due (design:reduced-motion DR2, 200 ms or less), and the
- // element is never shown before it lands.
- const late = landing.due == null ? 0 : Math.max(0, time - landing.due);
- const ms = Math.max(1, landing.fadeIn.ms - late);
+ // The fade back in takes what is left of the cross-fade: a timer that a
+ // busy main thread runs late shortens it, so the dip still ends when it
+ // was due (design:reduced-motion DR2, 200 ms or less), and the element is
+ // never shown before it lands. Past the whole fade back in nothing is
+ // left: the element appears at once, a plain write with no fade for the
+ // browser to start a frame later, so the call settles showing it.
+ const late = landing.due == null ? 0 : Math.max(0, time - landing.due);
+ const appears = landing.fadeIn != null && late >= landing.fadeIn.ms;
+ if (landing.fadeIn != null && !appears) {
+ const ms = landing.fadeIn.ms - late;
segments.set(
'opacity',
fadeSegment(landing.owner, time, [
@@ -2082,6 +2687,13 @@ export function createAnimator(
);
changed.push('opacity');
end = time + ms;
+ } else if (landing.fadeIn != null) {
+ segments.delete('opacity');
+ resting.opacity =
+ landing.fadeIn.isBorrowed === true
+ ? IDENTITY.opacity
+ : landing.fadeIn.to;
+ changed.push('opacity');
} else if (landing.restore != null) {
segments.delete('opacity');
resting.opacity =
@@ -2089,11 +2701,13 @@ export function createAnimator(
changed.push('opacity');
}
commit(changed, time);
- if (landing.restoreIsBorrowed === true) {
+ if (
+ landing.restoreIsBorrowed === true ||
+ (appears && landing.fadeIn?.isBorrowed === true)
+ ) {
// The stylesheet owns its opacity again.
releaseOwnOpacity();
- }
- if (landing.fadeIn?.isBorrowed === true) {
+ } else if (landing.fadeIn?.isBorrowed === true) {
// The fade back in returns to the stylesheet's opacity: it owns it
// again once the fade ends (releaseIdentity).
borrowedOpacity = landing.fadeIn.to;
@@ -2113,10 +2727,7 @@ export function createAnimator(
settle(owner, true);
} else {
owner.timer = setTimeout(
- () => {
- owner.timer = null;
- settle(owner, true);
- },
+ () => settleAtEnd(owner),
Math.max(0, end - now()),
);
}
@@ -2206,6 +2817,9 @@ export function createAnimator(
get hasPendingLanding() {
return landings.size > 0;
},
+ get hasWaitingDip() {
+ return [...landings].some(landing => landing.fadeIn != null);
+ },
};
/**
@@ -2245,6 +2859,7 @@ export function createAnimator(
holds: plan.holds,
landing: plan.landing,
borrowed: plan.borrowed,
+ joins: plan.joins,
};
};
@@ -2266,6 +2881,7 @@ export function createAnimator(
if (next === target) {
return;
}
+ flushDeferred();
if (next == null) {
// Unmount, unless a node replaces this one in the same task (React's
// replacement order: attach(null), then the new node): nothing is
@@ -2301,6 +2917,9 @@ export function createAnimator(
}
retireTimers.clear();
demote();
+ // demote() asks for a fresh will-change read of the node it
+ // demotes; a detached node gets none.
+ cancelSheetWillChangeRead();
});
lastDetached = null;
const time = now();
@@ -2369,6 +2988,9 @@ export function createAnimator(
}
const held = heldIdentity;
target = next;
+ // A new node: its own will-change is read again.
+ cancelSheetWillChangeRead();
+ sheetWillChangeRead = false;
if (target == null) {
return;
}
@@ -2405,6 +3027,7 @@ export function createAnimator(
}
}
flushReleases();
+ readSheetWillChangeLater();
},
get(property, time = now()) {
@@ -2417,8 +3040,9 @@ export function createAnimator(
return velocityAt(property === 'scale' ? 'scaleX' : property, time);
},
- set(values) {
+ set(values, setOptions = {}) {
syncPending();
+ flushDeferred();
const time = now();
const next = expand(values);
for (const [property, value] of Object.entries(next) as [
@@ -2430,14 +3054,19 @@ export function createAnimator(
resting[property] = value;
}
// Direct manipulation: the layer makes each write a composite only.
- for (const property of Object.keys(next) as MotionProperty[]) {
- promote(CHANNEL_OF[property]);
+ if (setOptions.promote !== false) {
+ for (const property of Object.keys(next) as MotionProperty[]) {
+ promote(CHANNEL_OF[property]);
+ }
}
commit(Object.keys(next) as MotionProperty[], time);
},
animate(to, transition, animateOptions = {}) {
syncPending();
+ if (animateOptions.start !== 'presented') {
+ flushDeferred();
+ }
const time = animateOptions.at ?? now();
const targets = expand(to);
const velocities = expand(transition.velocity ?? {});
@@ -2459,6 +3088,21 @@ export function createAnimator(
Object.assign(next, plan.next);
} else {
for (const property of properties) {
+ const running =
+ animateOptions.additive === true && velocities[property] == null
+ ? segmentAt(property, time)
+ : null;
+ if (running != null && !isHeld(running)) {
+ next[property] = additiveSegment(
+ owner,
+ property,
+ time,
+ targets[property] as number,
+ transition.spring,
+ running,
+ );
+ continue;
+ }
const velocity = velocities[property] ?? velocityAt(property, time);
next[property] = springSegment(
owner,
@@ -2475,6 +3119,7 @@ export function createAnimator(
time,
Object.keys(next) as MotionProperty[],
animateOptions.at,
+ animateOptions.start,
);
const adopted =
plan?.landing != null
@@ -2499,12 +3144,24 @@ export function createAnimator(
segments.set(property, segment);
}
}
- commitCall(group, owner, changed, time);
+ commitCall(
+ group,
+ owner,
+ changed,
+ time,
+ animateOptions.start === 'presented' && animateOptions.at == null,
+ );
if (plan?.borrowed != null) {
// The dip's own commit cleared it; the borrow lasts the dip.
borrowedOpacity = plan.borrowed;
}
- const handle = makeHandle(owner, changed, finished, time, group);
+ if (plan?.joins === true) {
+ joinWaitingDip(owner);
+ }
+ const handle =
+ plan?.joins === true
+ ? makeHandle(owner, ['opacity'], finished, time, group, true)
+ : makeHandle(owner, changed, finished, time, group);
if (plan?.landing != null) {
scheduleLanding(owner, handle.started, plan.landing, adopted);
}
@@ -2513,6 +3170,9 @@ export function createAnimator(
play(curves, playOptions = {}) {
syncPending();
+ if (playOptions.start !== 'presented') {
+ flushDeferred();
+ }
const time = playOptions.at ?? now();
const {owner, finished} = newOwner();
const byProperty: Partial<Record<MotionProperty, MotionCurve>> = {};
@@ -2560,6 +3220,17 @@ export function createAnimator(
continue;
}
const curve = byProperty[property] as MotionCurve;
+ const running =
+ playOptions.additive === true ? segmentAt(property, time) : null;
+ if (
+ running != null &&
+ !isHeld(running) &&
+ curve.duration > 0 &&
+ Math.abs(curve.at(curve.duration) - curve.at(0)) > 1e-9
+ ) {
+ next[property] = additiveCurveSegment(owner, time, curve, running);
+ continue;
+ }
next[property] =
curve.duration === 0
? null
@@ -2577,6 +3248,7 @@ export function createAnimator(
time,
Object.keys(next) as MotionProperty[],
playOptions.at,
+ playOptions.start,
);
const adopted =
plan?.landing != null
@@ -2601,12 +3273,24 @@ export function createAnimator(
segments.set(property, segment);
}
}
- commitCall(group, owner, changed, time);
+ commitCall(
+ group,
+ owner,
+ changed,
+ time,
+ playOptions.start === 'presented' && playOptions.at == null,
+ );
if (plan?.borrowed != null) {
// The dip's own commit cleared it; the borrow lasts the dip.
borrowedOpacity = plan.borrowed;
}
- const handle = makeHandle(owner, changed, finished, time, group);
+ if (plan?.joins === true) {
+ joinWaitingDip(owner);
+ }
+ const handle =
+ plan?.joins === true
+ ? makeHandle(owner, ['opacity'], finished, time, group, true)
+ : makeHandle(owner, changed, finished, time, group);
if (plan?.landing != null) {
scheduleLanding(owner, handle.started, plan.landing, adopted);
}
@@ -2615,6 +3299,7 @@ export function createAnimator(
decay(curves, decayOptions = {}) {
syncPending();
+ flushDeferred();
const time = decayOptions.at ?? now();
// Under Reduce Motion only momentum keeps moving (DR2, DEC-2): a curve
// that is a transition plays as `animate` does, a cross-fade or at once.
@@ -2696,6 +3381,7 @@ export function createAnimator(
stop(properties) {
syncPending();
+ flushDeferred();
const time = now();
const list = properties == null ? PROPERTIES : expandList(properties);
const changed: MotionProperty[] = [];
@@ -2731,6 +3417,7 @@ export function createAnimator(
rebase(deltas, rebaseOptions = {}) {
syncPending();
+ flushDeferred();
const time = rebaseOptions.at ?? now();
const changed: MotionProperty[] = [];
const owners = new Set<HandleState>();
@@ -2810,10 +3497,7 @@ export function createAnimator(
}
}
owner.timer = setTimeout(
- () => {
- owner.timer = null;
- settle(owner, true);
- },
+ () => settleAtEnd(owner),
Math.max(0, end - now()),
);
}
@@ -2858,6 +3542,7 @@ export function createAnimator(
},
dispose() {
+ flushDeferred();
// A Reduce Motion move still waiting to land is written at its end
// state, so the element is left visible where it was going (the node
// just detached, when an unmount is pending); its call and the calls
@@ -2886,6 +3571,7 @@ export function createAnimator(
retireTimers.clear();
handBackBorrow();
demote();
+ cancelSheetWillChangeRead();
target = null;
},
};
diff --git a/packages/core/src/motion/coast.ts b/packages/core/src/motion/coast.ts
index 7e0eff5fd7..3e33d2f07d 100644
--- a/packages/core/src/motion/coast.ts
+++ b/packages/core/src/motion/coast.ts
@@ -29,15 +29,19 @@
import {SETTLE_THRESHOLD, type Animator, type MotionCurve} from './animator';
import {solveDecay} from './decay';
+import {resolveMotion} from './resolveMotion';
import {solveSpring, toSpring, type SpringDescription} from './spring';
-import {scroll} from './uikit/scroll';
+import {registerScrollTable, scroll} from './uikit/scroll';
export interface CoastOptions {
/** Per-millisecond velocity factor; UIScrollView's normal rate by default. */
rate?: number;
/** Edges: a coast crossing one hands its velocity to `bounce`. */
bounds?: Partial<Record<'x' | 'y', {min: number; max: number}>>;
- /** The edge spring; `scroll.bounce` by default. */
+ /**
+ * The edge spring; `scroll.bounce` by default, which plays its table value
+ * (it is not a motion role: `spec:AST-094` FR4 lists no scroll spring).
+ */
bounce?: SpringDescription;
/**
* The release time on the document timeline (ms, `performance.now()`
@@ -85,7 +89,10 @@ export function coast(
}
}
const rate = options.rate ?? scroll.decelerationRate.normal;
- const bounce = toSpring(options.bounce ?? scroll.bounce);
+ registerScrollTable();
+ const bounce = toSpring(
+ resolveMotion(animator.element, options.bounce ?? scroll.bounce),
+ );
const curves: Partial<Record<'x' | 'y', MotionCurve>> = {};
for (const [key, v0] of Object.entries(velocities) as ['x' | 'y', number][]) {
const from = animator.get(key, options.at);
diff --git a/packages/core/src/motion/reducedMotion.ts b/packages/core/src/motion/reducedMotion.ts
index f59d3c423c..5c6dbdee90 100644
--- a/packages/core/src/motion/reducedMotion.ts
+++ b/packages/core/src/motion/reducedMotion.ts
@@ -45,7 +45,11 @@
*/
import {defaultIsCoarsePointer, defaultPrefersReducedMotion} from './animator';
-import {reducedMotionCrossFade} from './uikit/timing';
+import {resolveMotion} from './resolveMotion';
+import {
+ reducedMotionCrossFade,
+ registerReducedMotionCrossFade,
+} from './uikit/timing';
/** Reduce Motion on a coarse primary pointer: an opacity-only cross-fade. */
export const REDUCED_MOTION_FADE_QUERY =
@@ -86,7 +90,13 @@ export function reducedMotionFade(
if (!fades) {
return {duration: 0, easing: 'linear'};
}
- const curve = reducedMotionCrossFade.curve;
+ if (element != null) {
+ registerReducedMotionCrossFade();
+ }
+ const curve =
+ element != null
+ ? resolveMotion(element, reducedMotionCrossFade.curve)
+ : reducedMotionCrossFade.curve;
return {
duration: reducedMotionCrossFade.durationMs,
easing: `cubic-bezier(${curve.join(', ')})`,
diff --git a/packages/core/src/motion/reducedMotionPlan.test.ts b/packages/core/src/motion/reducedMotionPlan.test.ts
index ddd81b8997..d2d8be795b 100644
--- a/packages/core/src/motion/reducedMotionPlan.test.ts
+++ b/packages/core/src/motion/reducedMotionPlan.test.ts
@@ -26,11 +26,37 @@ function view(overrides: Partial<ReducedMotionView> = {}): ReducedMotionView {
hasOpacityCurve: false,
restingOpacity: 1,
hasPendingLanding: false,
+ hasWaitingDip: false,
...overrides,
};
}
describe('planReducedMotion', () => {
+ it('a call naming the opacity a waiting dip returns to, with no travel, joins that dip', () => {
+ const plan = planReducedMotion(
+ view({hasPendingLanding: true, hasWaitingDip: true}),
+ 0,
+ {opacity: 1},
+ ['opacity'],
+ true,
+ );
+ expect(plan.joins).toBe(true);
+ expect(plan.atOnce).toEqual([]);
+ expect(plan.opacityFade).toBeNull();
+ expect(plan.landing).toBeNull();
+ });
+
+ it('a call naming travel, or another opacity, while a dip waits does not join it', () => {
+ const waiting = view({hasPendingLanding: true, hasWaitingDip: true});
+ expect(
+ planReducedMotion(waiting, 0, {opacity: 1, x: 0}, ['opacity', 'x'], true)
+ .joins,
+ ).toBeUndefined();
+ expect(
+ planReducedMotion(waiting, 0, {opacity: 0.5}, ['opacity'], true).joins,
+ ).toBeUndefined();
+ });
+
it('without a fade (a fine primary pointer), writes everything at once (DR3)', () => {
const plan = planReducedMotion(
view(),
diff --git a/packages/core/src/motion/reducedMotionPlan.ts b/packages/core/src/motion/reducedMotionPlan.ts
index fd070b62e9..35bfa3bb44 100644
--- a/packages/core/src/motion/reducedMotionPlan.ts
+++ b/packages/core/src/motion/reducedMotionPlan.ts
@@ -80,6 +80,8 @@ export interface ReducedMotionView {
readonly restingOpacity: number;
/** Whether a move of an earlier call still waits to land. */
readonly hasPendingLanding: boolean;
+ /** Whether an earlier dip's fade back in still waits on its landing. */
+ readonly hasWaitingDip: boolean;
}
/** What Reduce Motion makes of a call. */
@@ -93,6 +95,11 @@ export interface ReducedMotionPlan {
readonly landing: PlannedLanding | null;
/** The stylesheet opacity a dip borrowed (no call owns opacity). */
readonly borrowed?: number | null;
+ /**
+ * The call joins the waiting dip: it names the opacity the dip returns to
+ * and moves nothing, so the fade goes on as it was.
+ */
+ readonly joins?: boolean;
}
/** The opacity no call has changed. */
@@ -162,7 +169,7 @@ export function planReducedMotion(
// A move still waiting to land (an earlier dip's) lands at this call's
// invisible moment, never while the element shows.
const pending = view.hasPendingLanding;
- // Not a theme role: no theme lengthens it (design:reduced-motion DR4).
+ // Not a role: nothing lengthens it (design:reduced-motion DR4).
const ms = reducedMotionCrossFade.durationMs;
const landsLater = (
at: number,
@@ -183,6 +190,18 @@ export function planReducedMotion(
: {}),
};
};
+ // A call that names the opacity a waiting dip returns to, and names no
+ // travel, joins that dip: the fade goes on as it was and the call settles
+ // when the dip ends. A second dip, opened from where the first had got
+ // to, would fade the element out twice.
+ if (
+ named &&
+ view.hasWaitingDip &&
+ !properties.some(property => TRAVEL_PROPERTIES.includes(property)) &&
+ Math.abs(opacityTo - view.opacityHeading()) < 1e-6
+ ) {
+ return {atOnce: [], opacityFade: null, holds, landing: null, joins: true};
+ }
// Travel lands only while the element is transparent (DR1, DR2): an
// entrance that starts visible, or an exit that ends visible, dips instead
// when it has travel or a waiting landing to carry.
diff --git a/packages/core/src/motion/resolveMotion.test.ts b/packages/core/src/motion/resolveMotion.test.ts
new file mode 100644
index 0000000000..b2a1502081
--- /dev/null
+++ b/packages/core/src/motion/resolveMotion.test.ts
@@ -0,0 +1,123 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file resolveMotion.test.ts
+ * @input resolveMotion.ts, the shared UIKit tables, a stubbed computed style
+ * @output Proof that, with the per-role tables internal (spec:AST-094
+ * DEC-15), a role plays its table value whatever a scope's CSS variable
+ * says, reads no style, and leaves values that are not roles alone; and
+ * that the animator plays the table's spring
+ * @position Testing for /packages/core/src/motion/resolveMotion.ts (the
+ * browser proof: animator.interaction.browser.spec.ts)
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {createAnimator} from './animator';
+import {coast} from './coast';
+import {resolveMotion} from './resolveMotion';
+import {solveSpring, toSpring} from './spring';
+import {
+ registerSpringsTable,
+ registerTimingTable,
+ scroll,
+ springs,
+ timing,
+} from './uikit';
+
+// Like a touch module: register the tables these motions resolve from.
+registerSpringsTable();
+registerTimingTable();
+
+let reads: number;
+
+beforeEach(() => {
+ reads = 0;
+ vi.spyOn(window, 'getComputedStyle').mockImplementation(
+ () =>
+ ({
+ getPropertyValue: () => {
+ reads += 1;
+ return '';
+ },
+ }) as unknown as CSSStyleDeclaration,
+ );
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+});
+
+/** A scope that sets role variables, as a page's own style could. */
+function scoped(values: Record<string, string>) {
+ const scope = document.createElement('div');
+ scope.setAttribute('data-astryx-theme', 'soft');
+ for (const [name, value] of Object.entries(values)) {
+ scope.style.setProperty(name, value);
+ }
+ const child = document.createElement('div');
+ scope.append(child);
+ document.body.append(scope);
+ return child;
+}
+
+describe('resolveMotion while the per-role tables stay internal (DEC-15)', () => {
+ it('plays the table value for a spring, a curve and a duration, whatever a scope sets', () => {
+ const child = scoped({
+ '--motion-springs-settle': '0.8s 0.3',
+ '--motion-timing-curves-move': 'cubic-bezier(0.4, 0, 0.2, 1)',
+ '--motion-timing-state-change-ms': '300ms',
+ });
+ expect(resolveMotion(child, springs.settle)).toBe(springs.settle);
+ expect(resolveMotion(child, timing.curves.move)).toBe(timing.curves.move);
+ expect(resolveMotion(child, timing, 'stateChangeMs')).toBe(
+ timing.stateChangeMs,
+ );
+ expect(resolveMotion(null, springs.settle)).toBe(springs.settle);
+ // No style is read to resolve a role.
+ expect(reads).toBe(0);
+ });
+
+ it('leaves values that are not roles alone', () => {
+ const inline = {response: 0.4, dampingRatio: 0.9};
+ expect(resolveMotion(document.body, inline)).toBe(inline);
+ expect(resolveMotion(document.body, springs.sheetPresent)).toBe(
+ springs.sheetPresent,
+ );
+ expect(resolveMotion(document.body, timing.press, 'scrollBrakeMs')).toBe(
+ timing.press.scrollBrakeMs,
+ );
+ });
+});
+
+describe('the animator', () => {
+ it("plays the table's spring even where a scope sets the role's variable", () => {
+ const child = scoped({'--motion-springs-settle': '0.8s 0.3'});
+ const animator = createAnimator(child, {now: () => 0});
+ animator.set({y: 300});
+ animator.animate({y: 0}, {spring: springs.settle}, {at: 0});
+ const table = solveSpring(toSpring(springs.settle), {from: 300, to: 0});
+ for (const ms of [50, 150, 400]) {
+ expect(animator.get('y', ms)).toBeCloseTo(table.value(ms / 1000), 3);
+ }
+ animator.dispose();
+ });
+ it('a coast plays the table edge spring whatever a scope sets: scroll.bounce is no role', () => {
+ const child = scoped({'--motion-scroll-bounce': '0.8s 0.3'});
+ const animator = createAnimator(child, {now: () => 0});
+ animator.set({x: 60});
+ // Released past the edge: straight back on the edge spring.
+ animator.decay(
+ coast(animator, {x: 0}, {bounds: {x: {min: -500, max: 0}}, at: 0}),
+ {at: 0},
+ );
+ const expected = solveSpring(toSpring(scroll.bounce), {
+ from: 60,
+ to: 0,
+ });
+ for (const ms of [50, 150, 400]) {
+ expect(animator.get('x', ms)).toBeCloseTo(expected.value(ms / 1000), 3);
+ }
+ animator.dispose();
+ });
+});
diff --git a/packages/core/src/motion/resolveMotion.ts b/packages/core/src/motion/resolveMotion.ts
new file mode 100644
index 0000000000..e14d509d64
--- /dev/null
+++ b/packages/core/src/motion/resolveMotion.ts
@@ -0,0 +1,68 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file resolveMotion.ts
+ * @input A motion role: a spring or curve of a registered motion table, or a
+ * table group and the key of one of its values
+ * @output resolveMotion: the role's value
+ * @position Motion foundation; the animator resolves every spring and curve
+ * it is handed with it, and components resolve the durations they time
+ * with it
+ *
+ * Every touch motion passes through here, so the role a value plays is named
+ * in one place. A role plays its table value: the per-role tables stay
+ * internal (`spec:AST-094` DEC-15), so nothing reads a role's CSS variable
+ * and no page or theme style sets a role. Nothing here reads style or
+ * layout, listens or observes, imports a table, or runs on import or on the
+ * server.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/motion/resolveMotion.test.ts
+ * - /packages/core/src/motion/animator.ts (resolves each role it plays)
+ */
+
+import type {MotionCurvePoints} from './roles';
+import type {SpringDescription} from './spring';
+
+/**
+ * A motion role's value: its table value, as the per-role tables stay
+ * internal (`spec:AST-094` DEC-15). Hand it a spring or curve of a motion
+ * table, or a table group and a key (the way to name a duration, which is a
+ * bare number):
+ *
+ * @example
+ * ```
+ * const spring = resolveMotion(sheet, springs.settle);
+ * const fadeMs = resolveMotion(row, timing, 'stateChangeMs');
+ * ```
+ *
+ * The element names where the motion plays; anything that is not a role
+ * comes back unchanged too, so a spring
+ * written inline at a call site keeps working.
+ */
+export function resolveMotion<T extends SpringDescription>(
+ element: Element | null | undefined,
+ spring: T,
+): T | SpringDescription;
+export function resolveMotion(
+ element: Element | null | undefined,
+ curve: MotionCurvePoints,
+): MotionCurvePoints;
+export function resolveMotion<G extends object, K extends keyof G & string>(
+ element: Element | null | undefined,
+ group: G,
+ key: K,
+): G[K] extends number
+ ? number
+ : G[K] extends MotionCurvePoints
+ ? MotionCurvePoints
+ : G[K] | SpringDescription;
+export function resolveMotion(
+ _element: Element | null | undefined,
+ leafOrGroup: object,
+ key?: string,
+): unknown {
+ return key === undefined
+ ? leafOrGroup
+ : (leafOrGroup as Record<string, unknown>)[key];
+}
diff --git a/packages/core/src/motion/roleValue.ts b/packages/core/src/motion/roleValue.ts
index 2ca32e922b..40b12aaece 100644
--- a/packages/core/src/motion/roleValue.ts
+++ b/packages/core/src/motion/roleValue.ts
@@ -69,7 +69,8 @@ export function short(n: number): string {
* spring: mass folds into the duration, overdamping into a negative bounce);
* - duration: `250ms`;
* - curve: `cubic-bezier(0.42, 0, 0.58, 1)`, usable as is in CSS.
- * Throws on a value that is not a valid value of its kind.
+ * Throws on a value that is not a valid value of its kind, a spring that
+ * never settles included.
*/
export function formatMotionRoleValue(
kind: MotionRoleKind,
diff --git a/packages/core/src/motion/roles.test.ts b/packages/core/src/motion/roles.test.ts
index d3f8b1003c..c64145e4ac 100644
--- a/packages/core/src/motion/roles.test.ts
+++ b/packages/core/src/motion/roles.test.ts
@@ -175,6 +175,10 @@ describe('motion roles', () => {
// thresholds and the arbitration timings are not motion roles either.
expect(motionRoleIn(timing, 'reducedMotionCrossFadeMs')).toBeUndefined();
expect(motionRoleOf(springs.menuReducedMotion)).toBeUndefined();
+ // Nor is the keyboard's motion: it rides the keyboard's own spring and
+ // notification duration, not a role (spec:AST-094 FR4).
+ expect(motionRoleIn(springs, 'keyboard')).toBeUndefined();
+ expect(motionRoleIn(timing, 'keyboardNotificationMs')).toBeUndefined();
expect(motionRoleIn(timing.press, 'scrollBrakeMs')).toBeUndefined();
expect(motionRoleIn(scroll, 'delaysContentTouchesMs')).toBeUndefined();
expect(motionRoleIn(navigation, 'parallax')).toBeUndefined();
@@ -244,6 +248,18 @@ describe('motion roles', () => {
expect(() => formatMotionRoleValue('spring', {response: 0.5})).toThrow(
/spring is/,
);
+ // A spring with no damping never settles.
+ for (const never of [
+ {duration: 0.5, bounce: 1},
+ {duration: 0.5, bounce: 1.5},
+ {response: 0.5, dampingRatio: 0},
+ {mass: 1, stiffness: 100, damping: 0},
+ ]) {
+ expect(() => formatMotionRoleValue('spring', never)).toThrow(
+ /must settle/,
+ );
+ }
+ expect(parseMotionRoleValue('spring', '0.5s 1')).toBeNull();
expect(parseMotionRoleValue('spring', '')).toBeNull();
expect(parseMotionRoleValue('spring', 'fast')).toBeNull();
expect(parseMotionRoleValue('spring', '0.4s 0.2')).toEqual({
diff --git a/packages/core/src/motion/uikit/tableImports.test.ts b/packages/core/src/motion/uikit/tableImports.test.ts
new file mode 100644
index 0000000000..c1bf495809
--- /dev/null
+++ b/packages/core/src/motion/uikit/tableImports.test.ts
@@ -0,0 +1,293 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tableImports.test.ts
+ * @input Core's source files and their relative runtime imports
+ * @output Fails when a component's import graph reaches a motion table it
+ * only reaches through a barrel or a namespace object, when anything imports
+ * a table as a namespace object, or when a shared module imports a table
+ * that belongs to one component
+ * @position Keeps a page to the motion tables it animates with: a namespace
+ * object (`export * as uikit`) keeps every table, every register function
+ * and the role registry in the bundle of anything that reads one table.
+ */
+
+import {existsSync, readdirSync, readFileSync, statSync} from 'node:fs';
+import {dirname, join, relative, resolve} from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+/** The tables every touch module may share: the animator and gestures read them. */
+const SHARED_TABLES = new Set([
+ 'motion/uikit/gestures.ts',
+ 'motion/uikit/navigation.ts',
+ 'motion/uikit/scroll.ts',
+ 'motion/uikit/springs.ts',
+ 'motion/uikit/timing.ts',
+]);
+
+const BARREL = 'motion/uikit/index.ts';
+
+/** A source file of the package, not a test, story or fixture. */
+function isSource(path: string): boolean {
+ return (
+ /\.(ts|tsx)$/.test(path) &&
+ !path.endsWith('.d.ts') &&
+ !/(\.test|\.spec|\.stories|\.test-violations)\.tsx?$/.test(path) &&
+ !/(^|\/)__tests__\//.test(path)
+ );
+}
+
+/** A table: a data module directly under motion/uikit, not the barrel. */
+function isTable(path: string): boolean {
+ return (
+ /^motion\/uikit\/[^/]+\.ts$/.test(path) &&
+ path !== BARREL &&
+ isSource(path) &&
+ !path.endsWith('.generated.ts')
+ );
+}
+
+/** The component a file belongs to (a PascalCase top-level directory), or null. */
+function componentOf(path: string): string | null {
+ const top = path.split('/')[0] ?? '';
+ return path.includes('/') && /^[A-Z]/.test(top) ? top : null;
+}
+
+interface Edge {
+ readonly to: string;
+ readonly namespace: boolean;
+}
+
+const IMPORT =
+ /(?:^|[\s;])(import|export)\s+(type\s+)?([^'";]*?)\s*from\s*['"](\.{1,2}\/[^'"]+)['"]/g;
+const DYNAMIC = /import\(\s*['"](\.{1,2}\/[^'"]+)['"]\s*\)/g;
+const BARE = /(?:^|[\s;])import\s*['"](\.{1,2}\/[^'"]+)['"]/g;
+
+/** The runtime edges of one file; type-only imports load nothing. */
+function edgesOf(
+ path: string,
+ source: string,
+ resolveSpecifier: (from: string, specifier: string) => string | null,
+): Edge[] {
+ const edges: Edge[] = [];
+ const text = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
+ for (const match of text.matchAll(IMPORT)) {
+ const [, , typeOnly, clause = '', specifier = ''] = match;
+ if (typeOnly != null) {
+ continue;
+ }
+ const named = /^\{([\s\S]*)\}$/.exec(clause.trim());
+ if (
+ named != null &&
+ (named[1] ?? '')
+ .split(',')
+ .map(part => part.trim())
+ .filter(Boolean)
+ .every(part => part.startsWith('type '))
+ ) {
+ continue;
+ }
+ const to = resolveSpecifier(path, specifier);
+ if (to != null) {
+ edges.push({to, namespace: /\*\s+as\s+\w+/.test(clause)});
+ }
+ }
+ for (const pattern of [DYNAMIC, BARE]) {
+ for (const match of text.matchAll(pattern)) {
+ const to = resolveSpecifier(path, match[1] ?? '');
+ if (to != null) {
+ edges.push({to, namespace: false});
+ }
+ }
+ }
+ return edges;
+}
+
+/**
+ * Every leak in a package, given its source files by path (relative to the
+ * package's src directory). Pure, so the rule can be checked on a made-up
+ * package too.
+ */
+function findTableLeaks(files: ReadonlyMap<string, string>): string[] {
+ const resolveSpecifier = (from: string, specifier: string): string | null => {
+ const base = join(dirname(from), specifier).replace(/\\/g, '/');
+ const stem = base.replace(/\.js$/, '');
+ for (const candidate of [
+ base,
+ `${stem}.ts`,
+ `${stem}.tsx`,
+ `${stem}/index.ts`,
+ `${stem}/index.tsx`,
+ ]) {
+ if (files.has(candidate)) {
+ return candidate;
+ }
+ }
+ return null;
+ };
+ const graph = new Map<string, Edge[]>();
+ for (const [path, source] of files) {
+ if (isSource(path)) {
+ graph.set(path, edgesOf(path, source, resolveSpecifier));
+ }
+ }
+
+ const leaks: string[] = [];
+ for (const [path, edges] of graph) {
+ for (const edge of edges) {
+ if (edge.namespace && (isTable(edge.to) || edge.to === BARREL)) {
+ leaks.push(
+ `${path} imports ${edge.to} as a namespace object, which keeps every table it reaches; import the tables by name`,
+ );
+ }
+ if (
+ isTable(edge.to) &&
+ !SHARED_TABLES.has(edge.to) &&
+ componentOf(path) == null &&
+ path !== BARREL
+ ) {
+ leaks.push(
+ `${path} (shared code) imports ${edge.to}, a component's table; import it in that component's touch module`,
+ );
+ }
+ }
+ }
+
+ const entries = [...graph.keys()].filter(path =>
+ /^[A-Z][^/]*\/index\.tsx?$/.test(path),
+ );
+ for (const entry of entries) {
+ const reached = new Set<string>([entry]);
+ const queue = [entry];
+ while (queue.length > 0) {
+ const file = queue.pop() as string;
+ for (const edge of graph.get(file) ?? []) {
+ if (!reached.has(edge.to)) {
+ reached.add(edge.to);
+ queue.push(edge.to);
+ }
+ }
+ }
+ for (const table of reached) {
+ if (!isTable(table) || SHARED_TABLES.has(table)) {
+ continue;
+ }
+ // Reached the way a page needs it: some component file this entry
+ // loads imports the table itself.
+ const direct = [...reached].some(
+ file =>
+ componentOf(file) != null &&
+ (graph.get(file) ?? []).some(edge => edge.to === table),
+ );
+ if (!direct) {
+ leaks.push(
+ `${entry} reaches ${table} only through a barrel or shared module; a component's table must be imported by the component that animates with it`,
+ );
+ }
+ }
+ }
+ return leaks;
+}
+
+function readPackage(root: string): Map<string, string> {
+ const files = new Map<string, string>();
+ const walk = (dir: string) => {
+ for (const name of readdirSync(dir)) {
+ if (name === 'node_modules' || name.startsWith('.')) {
+ continue;
+ }
+ const full = join(dir, name);
+ if (statSync(full).isDirectory()) {
+ walk(full);
+ } else if (/\.(ts|tsx)$/.test(name)) {
+ files.set(
+ relative(root, full).replace(/\\/g, '/'),
+ readFileSync(full, 'utf8'),
+ );
+ }
+ }
+ };
+ walk(root);
+ return files;
+}
+
+describe('motion table imports', () => {
+ const src = resolve(__dirname, '../..');
+
+ it('core imports each motion table by name, from the component that animates with it', () => {
+ expect(existsSync(join(src, BARREL))).toBe(true);
+ expect(findTableLeaks(readPackage(src))).toEqual([]);
+ });
+
+ it('catches a table reached through the barrel, a namespace object or shared code', () => {
+ const files = new Map([
+ [
+ 'motion/uikit/index.ts',
+ "export {springs} from './springs';\nexport {refresh} from './refresh';\n",
+ ],
+ ['motion/uikit/springs.ts', 'export const springs = {};\n'],
+ ['motion/uikit/refresh.ts', 'export const refresh = {};\n'],
+ ['motion/uikit/wheel.ts', 'export const wheel = {};\n'],
+ [
+ 'Refresh/index.ts',
+ "import {refresh} from '../motion/uikit/refresh';\nexport {refresh};\n",
+ ],
+ [
+ 'Button/index.ts',
+ "import {springs} from '../motion/uikit';\nexport {springs};\n",
+ ],
+ [
+ 'Picker/index.ts',
+ "import * as uikit from '../motion/uikit';\nimport type {Wheel} from '../motion/uikit/wheel';\nexport const p = uikit;\n",
+ ],
+ [
+ 'motion/animator.ts',
+ "import {wheel} from './uikit/wheel';\nexport {wheel};\n",
+ ],
+ [
+ 'Sheet/index.ts',
+ "import {wheel} from '../motion/animator';\nexport {wheel};\n",
+ ],
+ ]);
+ const leaks = findTableLeaks(files);
+ // The barrel re-exports a component's table, so Button reaches it.
+ expect(
+ leaks.some(leak =>
+ leak.startsWith('Button/index.ts reaches motion/uikit/refresh.ts'),
+ ),
+ ).toBe(true);
+ // A namespace object, and everything it keeps.
+ expect(
+ leaks.some(leak =>
+ leak.startsWith(
+ 'Picker/index.ts imports motion/uikit/index.ts as a namespace object',
+ ),
+ ),
+ ).toBe(true);
+ expect(
+ leaks.some(leak =>
+ leak.startsWith('Picker/index.ts reaches motion/uikit/refresh.ts'),
+ ),
+ ).toBe(true);
+ // Shared code importing one component's table, and what that leaks.
+ expect(
+ leaks.some(leak =>
+ leak.startsWith(
+ 'motion/animator.ts (shared code) imports motion/uikit/wheel.ts',
+ ),
+ ),
+ ).toBe(true);
+ expect(
+ leaks.some(leak =>
+ leak.startsWith('Sheet/index.ts reaches motion/uikit/wheel.ts'),
+ ),
+ ).toBe(true);
+ // The owner reaching its own table directly is fine; a type import loads nothing.
+ expect(leaks.some(leak => leak.startsWith('Refresh/index.ts'))).toBe(false);
+ expect(
+ leaks.some(leak =>
+ leak.includes('Picker/index.ts reaches motion/uikit/wheel.ts'),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/packages/core/src/motion/uikit/timing.ts b/packages/core/src/motion/uikit/timing.ts
index b4edbf7fad..a0d4ea8d02 100644
--- a/packages/core/src/motion/uikit/timing.ts
+++ b/packages/core/src/motion/uikit/timing.ts
@@ -96,7 +96,7 @@ export const reducedMotionCrossFade = {
* becomes an opacity-only cross-fade of this length on a coarse pointer
* (design:reduced-motion DR2 caps it at 200 ms, by owner decision DEC-1
* of 2026-10-24, departing from UIKit's own navigation cross-fade,
- * measured below at 0.5 s). Not a theme role: no theme lengthens it (DR4).
+ * measured below at 0.5 s). Not a role: nothing lengthens it (DR4).
* @source apple-docs https://developer.apple.com/documentation/uikit/uiaccessibility/preferscrossfadetransitions
* (the setting)
* @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
@@ -208,3 +208,17 @@ export function registerTimingTable(): void {
],
});
}
+
+// The fade's curve under its table path, for registerReducedMotionCrossFade.
+const reducedMotionCrossFadeRoles = {curves: {move}};
+
+/**
+ * Registers only the Reduce Motion fade's curve as its role,
+ * `timing.curves.move`, for code that reads the fade without the rest of the
+ * table (the animator, reducedMotionFade()). The fade's length is not a role.
+ */
+export function registerReducedMotionCrossFade(): void {
+ registerMotionTable('timing', reducedMotionCrossFadeRoles, {
+ roles: ['curves.move'],
+ });
+}
diff --git a/packages/core/src/motion/uikit/values.test.ts b/packages/core/src/motion/uikit/values.test.ts
index e64e09d3c9..467ffb6d40 100644
--- a/packages/core/src/motion/uikit/values.test.ts
+++ b/packages/core/src/motion/uikit/values.test.ts
@@ -2,7 +2,8 @@
/**
* @file values.test.ts
- * @input vitest, the UIKit constants table and the motion math
+ * @input vitest, the UIKit constants table, the motion math, and the press
+ * overlay's release rule as StyleX's dev runtime injects it
* @output Checks the table's values through the math that plays them: every
* spring is valid and settles; the alert spring is UIKit's legacy
* derivation; a sheet's detent and presentation springs render alike;
@@ -11,9 +12,10 @@
* @position Testing; the source rules are uikit.test.ts
*/
-import {readFileSync} from 'node:fs';
-import {join} from 'node:path';
+import * as stylex from '@stylexjs/stylex';
import {describe, expect, it} from 'vitest';
+import {rulesDeclaredFor} from '../../__tests__/pressState';
+import {interactionOverlayStyles} from '../../utils/interactionOverlay.stylex';
import {solveDecay} from '../decay';
import {rubberBand} from '../rubberBand';
import {
@@ -97,14 +99,23 @@ describe('UIKit constants table through the motion math', () => {
it('the press release curve is the press model\u2019s RELEASE_EASE', () => {
// The table records the curve the touch press model ships with; this pins
- // the two together so neither drifts alone.
- const source = readFileSync(
- join(__dirname, '../../utils/interactionOverlay.stylex.ts'),
- 'utf8',
- );
- const match = /const RELEASE_EASE = 'cubic-bezier\(([^)]*)\)'/.exec(source);
- expect(match?.[1].split(',').map(Number)).toEqual([
- ...press.highlightOutCurve,
- ]);
+ // the two together so neither drifts alone. It reads the curve the
+ // overlay's fading arm ships (the rule StyleX injects), so it holds
+ // however the stylesheet spells the value.
+ const element = document.createElement('div');
+ element.className =
+ stylex.props(interactionOverlayStyles.backgroundColor).className ?? '';
+ const curves = rulesDeclaredFor(element)
+ .filter(rule =>
+ rule
+ .slice(0, rule.indexOf('{'))
+ .includes('[data-astryx-press="fading"]'),
+ )
+ .flatMap(rule => {
+ const match =
+ /animation-timing-function:\s*cubic-bezier\(([^)]*)\)/.exec(rule);
+ return match == null ? [] : [match[1].split(',').map(Number)];
+ });
+ expect(curves).toEqual([[...press.highlightOutCurve]]);
});
});
diff --git a/packages/core/src/utils/pressGesture.test.ts b/packages/core/src/utils/pressGesture.test.ts
index 5bf49e0ee9..f292cd81a2 100644
--- a/packages/core/src/utils/pressGesture.test.ts
+++ b/packages/core/src/utils/pressGesture.test.ts
@@ -14,6 +14,7 @@
*/
import {describe, expect, it} from 'vitest';
+import {UIKIT_GESTURES} from '../motion/uikit/gestures';
import type {PressEvent, PressGesture, PressPaint} from './pressGesture';
import {
idlePressGesture,
@@ -54,6 +55,14 @@ describe('the clocks are the native ones', () => {
expect(PRESS_FADE_MS).toBe(200);
expect(PRESS_FLASH_MS).toBe(100);
});
+
+ it("are the UIKit table's measured values, one definition each", () => {
+ // The machine keeps its own constants, so a pressable page loads no
+ // motion table; the table's entries stay the one definition.
+ expect(PRESS_ONSET_MS).toBe(UIKIT_GESTURES.press.contentTouchDelay.value);
+ expect(PRESS_FLASH_MS).toBe(UIKIT_GESTURES.press.quickTapFlash.value);
+ expect(PRESS_SLOP_PX).toBe(UIKIT_GESTURES.press.slop.value);
+ });
});
describe('nothing paints until the press is believed', () => {
diff --git a/packages/core/src/utils/touchPresentation.ts b/packages/core/src/utils/touchPresentation.ts
index 9cf79f845a..5b889ba4d3 100644
--- a/packages/core/src/utils/touchPresentation.ts
+++ b/packages/core/src/utils/touchPresentation.ts
@@ -4,7 +4,8 @@
/**
* @file touchPresentation.ts
- * @input Uses the SSR-safe useMediaQuery hook and window.matchMedia
+ * @input Uses the SSR-safe useMediaQuery hook, window.matchMedia, and
+ * TOUCH_QUERY from touchQueries.ts (which loads without React or the theme)
* @output The one definition of when a component presents itself the touch
* way: TOUCH_QUERY, COMPACT_QUERY, COMPACT_TOUCH_QUERY, the iOS style gate
* (IOS_SUPPORTS_QUERY and its StyleX keys); the hook useTouchPresentation;
@@ -28,8 +29,8 @@
* drilled-in sub-menu in place of a flyout) asks for both.
*
* Touch behaviour is one model on every touch device, iOS and Android alike;
- * nothing here chooses a platform. Touch motion reads the theme's motion
- * roles, whose defaults are the measured table.
+ * nothing here chooses a platform. Touch motion plays the measured table,
+ * through the internal motion roles where a value is one.
*
* CSS first: a style that changes with these conditions writes the same
* query as a StyleX media key, spelled exactly as here (`@media` followed by
@@ -67,9 +68,11 @@ import {
type CompactDefinition,
} from '../theme/themeAdaptations';
import {useThemeDefinition} from '../theme/useTheme';
+import {TOUCH_QUERY} from './touchQueries';
-/** The primary pointer is coarse: touch behaviours. */
-export const TOUCH_QUERY = '(pointer: coarse)';
+// The primary pointer is coarse: touch behaviours. Defined in touchQueries.ts,
+// which loads without React or the theme.
+export {TOUCH_QUERY};
/**
* The viewport is compact at the default width points: layout behaviours
diff --git a/packages/core/src/utils/touchQueries.ts b/packages/core/src/utils/touchQueries.ts
new file mode 100644
index 0000000000..f90777ff7d
--- /dev/null
+++ b/packages/core/src/utils/touchQueries.ts
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file touchQueries.ts
+ * @input Nothing: plain strings
+ * @output TOUCH_QUERY, the media query for a coarse primary pointer
+ * @position The dependency-free half of touchPresentation.ts, for code that
+ * must load without React or the theme: the motion foundation, which
+ * Node-side specs and browser proofs load without a StyleX compile.
+ * touchPresentation.ts re-exports it beside the hook and the parts that
+ * read the theme.
+ */
+
+/** The primary pointer is coarse: touch behaviours. */
+export const TOUCH_QUERY = '(pointer: coarse)';
diff --git a/scripts/motion-node-load.test.mjs b/scripts/motion-node-load.test.mjs
new file mode 100644
index 0000000000..d6b9b15aac
--- /dev/null
+++ b/scripts/motion-node-load.test.mjs
@@ -0,0 +1,122 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file motion-node-load.test.mjs
+ *
+ * The touch motion foundation loads in plain Node, without React, the theme or
+ * a StyleX compile: Node-side specs and browser proofs bundle it with esbuild
+ * and import it as is. A module in its graph that calls StyleX at load (a
+ * theme's `defineVars`) throws there, so the foundation must reach no StyleX
+ * module. This bundles it the way such a spec does, with every package left as
+ * a real Node import, checks the graph, and imports it in a child Node process
+ * (no Vite transform).
+ */
+
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {build} from 'esbuild';
+import {describe, expect, it} from 'vitest';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const coreSrc = path.join(root, 'packages/core/src');
+
+/**
+ * What a Node-side spec imports from the foundation: the motion modules, and
+ * each gesture recognizer by its own module (the gestures barrel also carries
+ * the press paint's styles).
+ */
+const ENTRY = `
+export {createAnimator, animatorFor, SETTLE_THRESHOLD} from './motion/animator';
+export {reducedMotionFade} from './motion/reducedMotion';
+export {resolveMotion} from './motion/resolveMotion';
+export {solveSpring, toSpring} from './motion/spring';
+export {registerSpringsTable, springs} from './motion/uikit/springs';
+export {registerTimingTable, timing} from './motion/uikit/timing';
+export {registerScrollTable, scroll} from './motion/uikit/scroll';
+export {GestureRecognizer} from './gestures/GestureRecognizer';
+export {TapGestureRecognizer} from './gestures/TapGestureRecognizer';
+export {LongPressGestureRecognizer} from './gestures/LongPressGestureRecognizer';
+export {PanGestureRecognizer} from './gestures/PanGestureRecognizer';
+export {ScreenEdgePanGestureRecognizer} from './gestures/ScreenEdgePanGestureRecognizer';
+export {SwipeGestureRecognizer} from './gestures/SwipeGestureRecognizer';
+export {PinchGestureRecognizer} from './gestures/PinchGestureRecognizer';
+`;
+
+async function bundleFoundation() {
+ return build({
+ stdin: {contents: ENTRY, resolveDir: coreSrc, loader: 'ts'},
+ bundle: true,
+ write: false,
+ format: 'esm',
+ platform: 'node',
+ // A package stays a real Node import, as in a spec: @stylexjs/stylex
+ // would run its runtime, which throws on an uncompiled call.
+ packages: 'external',
+ // Every module runs as it would loaded one by one (a spec runner does
+ // not tree-shake), so a call at load in an unused module still runs.
+ treeShaking: false,
+ metafile: true,
+ logLevel: 'silent',
+ });
+}
+
+describe('the touch motion foundation in plain Node', () => {
+ it('reaches no StyleX module and no theme module', async () => {
+ const {metafile} = await bundleFoundation();
+ const inputs = Object.keys(metafile.inputs);
+ const stylex = inputs.filter(file => /\.stylex\.[cm]?[jt]sx?$/.test(file));
+ const theme = inputs.filter(file => file.includes('/src/theme/'));
+ const stylexImports = inputs.flatMap(file =>
+ metafile.inputs[file].imports
+ .filter(entry => entry.path.startsWith('@stylexjs/'))
+ .map(entry => `${file} -> ${entry.path}`),
+ );
+ expect({stylex, theme, stylexImports}).toEqual({
+ stylex: [],
+ theme: [],
+ stylexImports: [],
+ });
+ });
+
+ it('loads in a child Node process and creates an animator', async () => {
+ const result = await bundleFoundation();
+ // Beside core, so its packages resolve from core's node_modules.
+ const dir = path.join(
+ root,
+ 'packages/core/node_modules/.cache/motion-node-load',
+ );
+ fs.mkdirSync(dir, {recursive: true});
+ const file = path.join(dir, `foundation-${process.pid}.mjs`);
+ fs.writeFileSync(file, result.outputFiles[0].text);
+ try {
+ const out = execFileSync(
+ process.execPath,
+ [
+ '--input-type=module',
+ '-e',
+ `const m = await import(${JSON.stringify(pathToFileURL(file).href)});
+ m.registerSpringsTable();
+ const animator = m.createAnimator(null);
+ const pan = new m.PanGestureRecognizer({});
+ console.log(JSON.stringify({
+ createAnimator: typeof m.createAnimator,
+ set: typeof animator.set,
+ sheet: m.springs.sheetPresent != null,
+ pan: typeof pan.state,
+ }));`,
+ ],
+ {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']},
+ );
+ expect(JSON.parse(out.trim().split('\n').at(-1))).toEqual({
+ createAnimator: 'function',
+ set: 'function',
+ sheet: true,
+ pan: 'string',
+ });
+ } finally {
+ fs.rmSync(file, {force: true});
+ }
+ });
+});
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index ee5316c791..e42eb6a13e 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -43,7 +43,7 @@ const UTILITY_DIRS = new Set(['hooks', 'theme', 'utils']);
* publicly exported. These are shared implementation details
* consumed by other components via relative imports.
*/
-const INTERNAL_DIRS = new Set(['NavItem']);
+const INTERNAL_DIRS = new Set(['NavItem', 'gestures']);
/**
* Additional exports that can't be auto-discovered from directory structure.