Skip to content

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

TypeScript

chore(core): a pager that pages like a UIKit paging scroll view (#8146)

Christopher Chedeauf883c083d0f1
diff --git a/.changeset/uikit-pager.md b/.changeset/uikit-pager.md
new file mode 100644
index 0000000000..1a077103ea
--- /dev/null
+++ b/.changeset/uikit-pager.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a pager for touch presentations that pages like a UIKit paging scroll view. A horizontal pan moves the pages one to one and rubber-bands at the ends. The release picks the page with UIKit's rule and settles on UIKit's paging curve on the compositor, and a finger can catch it mid-flight. It takes every pointer: a mouse drags it as a finger does, and its pan follows a trackpad's horizontal scroll, at most one page per swipe. A mouse wheel's scroll stays the page's. Its motion values are internal constants. Not exported from the package entry point.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 00e4957dd8..0732ea85d8 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -199,10 +199,8 @@ a measured, sourced difference exists.
starts its settle from rest, as UIKit's does; a faster release hands its
velocity to the settle. The floor is a guess inside the measured bracket
(UIKit zeroes steady releases at 175 and 200 pt/s and keeps 249 pt/s, iOS
- 26.2 simulator, 2026-10-23) until a measurement replaces it (FR2). A
- programmatic page change on a pager (a page control's tap, a keyboard step)
- starts from rest: this is a known gap against this requirement until the
- pager carries the current velocity into the page change (DEC-25).
+ 26.2 simulator, 2026-10-23) until a measurement replaces it (FR2). A page
+ change during a drag starts from rest (DEC-25).
- **FR7 — Exits animate as the native counterpart's do.** A touch
presentation MUST play the exit its UIKit counterpart plays, on every touch
platform. FR8 governs their reduced-motion form. Each overlay's own record states its
@@ -753,7 +751,7 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
| FR4 | Role unit tests over every touch motion | each role at its table value; a theme that writes `motion` | a literal played in place of a role, a value that differs from the table at `tempo` 1 and `'standard'`, or a theme that changes a role other than through its motion knobs fails |
| FR5 | Browser proof: an animation keeps advancing frame by frame through a 1 s main-thread block, with no layout or paint per frame | Chromium phone emulation; WebKit | a script-driven or layout-animating implementation freezes or lays out |
| FR6 | Unit and browser tests catching an animation mid-flight and retargeting it | catch at peak velocity; retarget with a new spring; a retarget before the browser reports the call's start | a layout read, a jump, or a lost velocity fails |
-| FR6 pager | Unit and browser tests of a pager's settle start | releases just under and over 225 pt/s; a catch mid-settle; a programmatic page change mid-settle | a release under the floor whose settle starts moving, a release over it whose settle starts from rest, or a catch that loses the on-screen velocity fails; a programmatic page change from rest is the recorded gap |
+| FR6 pager | Unit and browser tests of a pager's settle start | releases just under and over 225 pt/s; a catch mid-settle; a programmatic page change mid-settle | a release under the floor whose settle starts moving, a release over it whose settle starts from rest, a catch that loses the on-screen velocity, or a programmatic page change mid-settle that starts from rest fails; a page change during a drag starts from rest |
| FR7, FR8 | Component browser tests and storyboards with and without Reduce Motion | entrance, exit, move; a drag and its lift under Reduce Motion | a missing exit, any travel, scale or spring under Reduce Motion other than a coast after a throw and its settle at an edge (`design:reduced-motion` DR2), or an opacity fade over 200 ms fails |
| FR9, FR10 | Recognizer unit tests on synthetic streams and browser tests with real touch input | drag, second finger, pinch, page zoom, main-thread block | a second finger that breaks a drag, or a page pinch blocked other than by the author's `touch-action`, fails |
| FR11, FR12 | Press and long-press tests on synthetic streams with explicit timestamps | inside and outside a scroll view; a drag the browser takes; a lift inside; a menu row under a finger; a press on a row of a menu whose rows fit and of one that scrolls; a slide-off lift on a Switch and on a Radio | the wrong profile's timing, a press that survives the browser taking the touch, or a control outside an action group activated other than by the browser's click, outside `spec:AST-020` FR9's slide-off exception, a row of a menu whose rows fit that waits 150 ms, or one of a scrolling menu that does not, or a slide-off lift that completes a control outside `spec:AST-020` FR9's exception, fails |
@@ -1078,9 +1076,9 @@ of a page, not by a projection, and starts a slow release's settle from rest.
The owner tried this paging on the pager and the paging Carousel on
2026-11-01, with a trackpad and on a phone: "trackpad is good", "phone good".
This narrows FR3 and FR6 for paging only; every other release keeps them. A
-programmatic page change starts from rest until the pager carries velocity
-into it. A paging release decides by FR3's paging rule, and its settle starts
-as FR6's paging paragraph says; FR37 applies unchanged.
+page change during a drag starts from rest. A paging release decides by FR3's
+paging rule, and its settle starts as FR6's paging paragraph says; FR37
+applies unchanged.
Rejected: projecting a paging release with a deceleration rate; handing a
slow paging release's velocity to the settle.
diff --git a/packages/core/src/hooks/__tests__/pagerBundle.ts b/packages/core/src/hooks/__tests__/pagerBundle.ts
new file mode 100644
index 0000000000..4c1c93b778
--- /dev/null
+++ b/packages/core/src/hooks/__tests__/pagerBundle.ts
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file pagerBundle.ts
+ * @input The pager and the paging math
+ * @output The surface the pager's browser proofs bundle onto their fixture
+ * page (esbuild, IIFE global `Pager`)
+ * @position Test-only entry of usePager.interaction.browser.spec.ts
+ */
+
+export {createPager, pageForRelease} from '../usePager';
+export {
+ pagingSettleVelocity,
+ solveAnimatedPageScroll,
+ solvePaging,
+} from '../../motion/paging';
+export {rubberBand} from '../../motion/rubberBand';
+export {paging} from '../../motion/uikit/paging';
+export {VelocityTracker} from '../../gestures/VelocityTracker';
diff --git a/packages/core/src/hooks/__tests__/useAttachmentPair.test.tsx b/packages/core/src/hooks/__tests__/useAttachmentPair.test.tsx
new file mode 100644
index 0000000000..5293c3fde5
--- /dev/null
+++ b/packages/core/src/hooks/__tests__/useAttachmentPair.test.tsx
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useAttachmentPair.test.tsx
+ * @input useAttachmentPair
+ * @output Proof that an attachment of two nodes starts once both are there
+ * and follows either node and its key. A commit that changes neither does
+ * nothing, and the attachment is released when a node goes and at unmount
+ * @position Testing for /packages/core/src/hooks/useAttachment.ts
+ */
+
+import {render} from '@testing-library/react';
+import {createElement, useRef} from 'react';
+import {describe, expect, it} from 'vitest';
+import {useAttachmentPair} from '../useAttachment';
+
+interface PairProps {
+ log: string[];
+ first?: string | null;
+ second?: string | null;
+ attachKey?: unknown;
+}
+
+/** Two nodes, each shown under an id that names it (a new id is a new node). */
+function Pair({log, first = 'a', second = 'b', attachKey = 0}: PairProps) {
+ const firstRef = useRef<HTMLDivElement>(null);
+ const secondRef = useRef<HTMLSpanElement>(null);
+ useAttachmentPair(
+ firstRef,
+ secondRef,
+ (firstNode, secondNode) => {
+ const pair = `${firstNode.id}+${secondNode.id}`;
+ log.push(`attach ${pair}`);
+ return () => log.push(`release ${pair}`);
+ },
+ attachKey,
+ );
+ return createElement(
+ 'div',
+ null,
+ first == null
+ ? null
+ : createElement('div', {key: first, id: first, ref: firstRef}),
+ second == null
+ ? null
+ : createElement('span', {key: second, id: second, ref: secondRef}),
+ );
+}
+
+describe('useAttachmentPair', () => {
+ it('attaches once both nodes are there, and not before', () => {
+ const log: string[] = [];
+ const view = render(createElement(Pair, {log, second: null}));
+ expect(log).toEqual([]);
+ view.rerender(createElement(Pair, {log}));
+ expect(log).toEqual(['attach a+b']);
+ view.unmount();
+ });
+
+ it('does nothing on a commit that changes neither node nor the key', () => {
+ const log: string[] = [];
+ const view = render(createElement(Pair, {log}));
+ view.rerender(createElement(Pair, {log}));
+ view.rerender(createElement(Pair, {log}));
+ expect(log).toEqual(['attach a+b']);
+ view.unmount();
+ });
+
+ it('releases the pair and attaches the new one when either node is replaced', () => {
+ const log: string[] = [];
+ const view = render(createElement(Pair, {log}));
+ view.rerender(createElement(Pair, {log, first: 'c'}));
+ view.rerender(createElement(Pair, {log, first: 'c', second: 'd'}));
+ expect(log).toEqual([
+ 'attach a+b',
+ 'release a+b',
+ 'attach c+b',
+ 'release c+b',
+ 'attach c+d',
+ ]);
+ view.unmount();
+ });
+
+ it('attaches again when the key changes', () => {
+ const log: string[] = [];
+ const view = render(createElement(Pair, {log, attachKey: 'mouse'}));
+ view.rerender(createElement(Pair, {log, attachKey: 'touch'}));
+ expect(log).toEqual(['attach a+b', 'release a+b', 'attach a+b']);
+ view.unmount();
+ });
+
+ it('releases when a node goes, and the last attachment at unmount', () => {
+ const log: string[] = [];
+ const view = render(createElement(Pair, {log}));
+ view.rerender(createElement(Pair, {log, first: null}));
+ expect(log).toEqual(['attach a+b', 'release a+b']);
+ view.rerender(createElement(Pair, {log, first: 'e'}));
+ view.unmount();
+ expect(log).toEqual([
+ 'attach a+b',
+ 'release a+b',
+ 'attach e+b',
+ 'release e+b',
+ ]);
+ });
+});
diff --git a/packages/core/src/hooks/__tests__/usePager.interaction.browser.spec.ts b/packages/core/src/hooks/__tests__/usePager.interaction.browser.spec.ts
new file mode 100644
index 0000000000..9d507c6385
--- /dev/null
+++ b/packages/core/src/hooks/__tests__/usePager.interaction.browser.spec.ts
@@ -0,0 +1,1364 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file usePager.interaction.browser.spec.ts
+ * @input The pager on a fixture page (402 px over five pages), real touch and
+ * wheel input, and the interaction harness, in Chromium and WebKit
+ * @output Proof that the pager pages like a UIKit paging scroll view on the
+ * compositor. It covers drags, flicks, the rubber band, goTo, the catch, a
+ * busy main thread, a settle with no layout or paint, and storyboards
+ * @position Browser proof for hooks/usePager.ts, run by `pnpm test:interaction`
+ */
+
+import {fileURLToPath} from 'node:url';
+import {
+ animationStoryboard,
+ armHold,
+ busyWindowProof,
+ compareCurve,
+ countBetween,
+ curveOf,
+ drag,
+ flick,
+ markElement,
+ merge,
+ path,
+ releaseAnimations,
+ sampleCurve,
+ startScreencast,
+ timeline,
+ toTouchEvents,
+ touchDriver,
+ traceRendering,
+ trackMarker,
+ waitForRest,
+ webInputDriver,
+ withFinger,
+ writeEvidence,
+ type ArmedHold,
+ type HeldAnimation,
+ type TouchDriver,
+ type TouchScript,
+} from '@astryxdesign/interaction-harness';
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {build} from 'esbuild';
+import type * as PagerBundle from './pagerBundle';
+
+declare global {
+ interface Window {
+ Pager: typeof PagerBundle;
+ pager: ReturnType<typeof PagerBundle.createPager>;
+ motionStart?: number;
+ liftVelocities: number[];
+ liftPositions: number[];
+ frameTimes: number[];
+ settleTimes: number[];
+ armFrames: () => void;
+ touchTimes: [string, number][];
+ wheelTimes: number[];
+ pagerLog: string[];
+ cancelledMoves: boolean[];
+ cancelledWheels: boolean[];
+ minTrackX: number;
+ /** Each move's position, and where the touch started (CSS px). */
+ moves: [number, number][];
+ touchStart: [number, number];
+ }
+}
+
+let script = '';
+
+test.beforeAll(async () => {
+ const result = await build({
+ entryPoints: [fileURLToPath(new URL('./pagerBundle.ts', import.meta.url))],
+ bundle: true,
+ write: false,
+ format: 'iife',
+ globalName: 'Pager',
+ target: 'es2022',
+ });
+ script = result.outputFiles[0].text;
+});
+
+/** The phone profile's page width: one page. */
+const PAGE = 402;
+const COUNT = 5;
+const TOP = 80;
+const HEIGHT = 300;
+
+async function serve(
+ page: Page,
+ {rtl = false, startIndex = 1, tall = false} = {},
+): Promise<void> {
+ const pages = Array.from(
+ {length: COUNT},
+ (_, i) =>
+ `<div class="page" style="background: hsl(${i * 70} 60% 70%)"><span>${i}</span></div>`,
+ ).join('');
+ const html = `<!doctype html><html dir="${rtl ? 'rtl' : 'ltr'}"><meta name="viewport" content="width=device-width,initial-scale=1">
+<style>
+ html, body { margin: 0; background: #fff; font: 600 48px system-ui; }
+ #viewport { position: absolute; top: ${TOP}px; left: 0; width: ${PAGE}px; height: ${HEIGHT}px; overflow: hidden; }
+ #track { display: flex; height: 100%; }
+ .page { flex: 0 0 100%; height: 100%; display: grid; place-items: center; }
+ ${tall ? 'body { height: 3000px; }' : ''}
+</style>
+<div id="viewport"><div id="track">${pages}</div></div>
+<script>${script}</script>
+<script>
+ window.pagerLog = [];
+ // Whether each move reached the page cancelled (read after every listener).
+ window.cancelledMoves = [];
+ // Whether each wheel reached the page cancelled (read after every listener).
+ window.cancelledWheels = [];
+ addEventListener('wheel', e => { window.cancelledWheels.push(e.defaultPrevented); }, {passive: true});
+ window.moves = [];
+ // For a failure's load report. It records the frames the page draws from
+ // each touch, wheel or goTo, until 2 s after the last one. It also records
+ // when each settle ends, and the time of each touch and wheel event.
+ window.frameTimes = [];
+ window.settleTimes = [];
+ let framesUntil = 0;
+ let framing = false;
+ const frame = time => {
+ window.frameTimes.push(time);
+ if (performance.now() < framesUntil) {
+ requestAnimationFrame(frame);
+ } else {
+ framing = false;
+ }
+ };
+ window.armFrames = () => {
+ framesUntil = performance.now() + 2000;
+ if (!framing) {
+ framing = true;
+ requestAnimationFrame(frame);
+ }
+ };
+ addEventListener('touchstart', window.armFrames, {capture: true, passive: true});
+ addEventListener('wheel', window.armFrames, {capture: true, passive: true});
+ // Every touch and wheel event's own time, read first (window capture, before
+ // any listener can stop it).
+ window.touchTimes = [];
+ window.wheelTimes = [];
+ for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {
+ addEventListener(type, event => window.touchTimes.push([type, event.timeStamp]), {capture: true, passive: true});
+ }
+ addEventListener('wheel', event => window.wheelTimes.push(event.timeStamp), {capture: true, passive: true});
+ addEventListener('touchstart', e => { window.touchStart = [e.touches[0].clientX, e.touches[0].clientY]; }, {passive: true});
+ addEventListener('touchmove', e => { window.cancelledMoves.push(e.defaultPrevented); window.moves.push([e.touches[0].clientX, e.touches[0].clientY]); }, {passive: true});
+ // The lift velocity the pager's pan reads at each release, and where the
+ // track was then, for the model checks of the releases. The velocity is the
+ // tracker's scrollVelocity, from the class the bundle shares with the pager.
+ window.liftVelocities = [];
+ window.liftPositions = [];
+ const readScrollVelocity = Pager.VelocityTracker.prototype.scrollVelocity;
+ Pager.VelocityTracker.prototype.scrollVelocity = function (releaseTime) {
+ const velocity = readScrollVelocity.call(this, releaseTime);
+ window.liftVelocities.push(velocity.x);
+ const track = document.getElementById('track');
+ window.liftPositions.push(track ? parseFloat(getComputedStyle(track).translate) || 0 : 0);
+ return velocity;
+ };
+ window.pager = Pager.createPager({
+ count: ${COUNT},
+ defaultIndex: ${startIndex},
+ // Notes whether the settle was already running on its curve when the
+ // page was reported.
+ onIndexChange: (i, reason) => window.pagerLog.push('index:' + i + ':' + reason +
+ (document.getAnimations().some(a => a.playState === 'running' && a.startTime != null && a.currentTime > 20) ? ':moving' : '')),
+ onSettle: (i, previous) => {
+ window.settleTimes.push(performance.now());
+ window.pagerLog.push('settle:' + i + ':' + previous);
+ },
+ });
+ window.pager.attach(document.getElementById('viewport'), document.getElementById('track'));
+</script></html>`;
+ await page.route('http://pager.test/', async route =>
+ route.fulfill({contentType: 'text/html', body: html}),
+ );
+ await page.goto('http://pager.test/');
+}
+
+async function open(page: Page, options: Parameters<typeof serve>[1] = {}) {
+ await serve(page, options);
+ return {
+ track: page.locator('#track'),
+ driver: await recordingScripts(page, await touchDriver(page)),
+ };
+}
+
+/**
+ * The fixture under a fine primary pointer: a real mouse and real wheel
+ * input, no touch emulation (`spec:AST-094` FR43).
+ */
+async function openFine(page: Page, options: Parameters<typeof serve>[1] = {}) {
+ await serve(page, options);
+ return {track: page.locator('#track'), input: await webInputDriver(page)};
+}
+
+const log = async (page: Page) => page.evaluate(() => window.pagerLog);
+
+/**
+ * The touch script the case played last, and the page's clock when it began.
+ * The times (ms) are those of the steps that reach the page as events: a move
+ * where no finger moved sends none.
+ */
+let played: {steps: ReadonlyArray<number>; from: number} | null = null;
+test.beforeEach(() => {
+ played = null;
+});
+
+/** The touch driver, noting each script it plays for the load report. */
+async function recordingScripts(
+ page: Page,
+ driver: Awaited<ReturnType<typeof touchDriver>>,
+): Promise<Awaited<ReturnType<typeof touchDriver>>> {
+ return {
+ ...driver,
+ play: async (script, options) => {
+ const where = new Map<number, string>();
+ const steps: number[] = [];
+ for (const step of toTouchEvents(script)) {
+ const moved = step.changed.some(
+ finger => where.get(finger.id) !== `${finger.x},${finger.y}`,
+ );
+ for (const finger of step.changed) {
+ where.set(finger.id, `${finger.x},${finger.y}`);
+ }
+ if (step.type !== 'touchMove' || moved) {
+ steps.push(step.t);
+ }
+ }
+ played = {steps, from: await page.evaluate(() => performance.now())};
+ return driver.play(script, options);
+ },
+ };
+}
+
+/**
+ * What the page received and drew while a case ran. It goes before a failed
+ * case's own messages, so a failure under load names its cause with numbers:
+ * - touch input against the script it played, from the events' own
+ * timestamps (in WebKit, real dispatch times). Touches that took over 30 ms
+ * longer than the script are a stall. A closest gap under a quarter of the
+ * script's is a burst. An engine may not send a move, so the count can
+ * differ;
+ * - wheel input: a pause of 220 ms between steps ends a trackpad swipe;
+ * - the longest gap between the frames drawn from the input or goTo on: over
+ * 50 ms is frame starvation;
+ * - when each settle ended after the lift.
+ */
+async function loadReport(page: Page): Promise<string> {
+ const drawn = await page.evaluate(() => ({
+ frames: window.frameTimes,
+ settles: window.settleTimes,
+ touches: window.touchTimes,
+ wheels: window.wheelTimes,
+ origin: performance.timeOrigin,
+ }));
+ // Some engines stamp events in epoch milliseconds (GestureHost eventTime).
+ const at = (time: number) => (time > 1e12 ? time - drawn.origin : time);
+ const ms = (value: number) => `${value.toFixed(1)} ms`;
+ const causes: string[] = [];
+ const script = played;
+ const touches = drawn.touches
+ .map(([, time]) => at(time))
+ .filter(time => script == null || time >= script.from);
+ if (script != null && script.steps.length > 1 && touches.length > 1) {
+ const gaps = (times: ReadonlyArray<number>) =>
+ times.slice(1).map((time, i) => time - times[i]);
+ const arrived = gaps(touches);
+ const scripted = gaps(script.steps);
+ const longest = Math.max(...arrived);
+ const closest = Math.min(...arrived);
+ const scriptedClosest = Math.min(...scripted);
+ const took = touches[touches.length - 1] - touches[0];
+ const scriptedTook =
+ script.steps[script.steps.length - 1] - script.steps[0];
+ const named = [
+ took > scriptedTook + 30
+ ? `a stall (the touches took ${ms(took)}, scripted ${ms(scriptedTook)}; the longest gap ${ms(longest)})`
+ : null,
+ closest < scriptedClosest / 4
+ ? `a burst (touch events ${ms(closest)} apart, the script's closest ${ms(scriptedClosest)})`
+ : null,
+ ].filter(Boolean);
+ const span = `${touches.length} touch events over ${ms(took)}, scripted ${script.steps.length} over ${ms(scriptedTook)}, ${ms(closest)}–${ms(longest)} apart`;
+ causes.push(
+ named.length > 0
+ ? `real-time touch input with ${named.join(' and ')}: ${span}`
+ : `touch input on its script: ${span}`,
+ );
+ }
+ const wheels = drawn.wheels.map(at);
+ if (wheels.length > 1) {
+ const longest = Math.max(
+ ...wheels.slice(1).map((time, i) => time - wheels[i]),
+ );
+ causes.push(
+ longest >= 220
+ ? `real-time wheel input with a ${ms(longest)} pause between steps, which ends a trackpad swipe (220 ms)`
+ : `wheel steps at most ${ms(longest)} apart`,
+ );
+ }
+ if (drawn.frames.length > 1) {
+ const longest = Math.max(
+ ...drawn.frames.slice(1).map((time, i) => time - drawn.frames[i]),
+ );
+ causes.push(
+ longest > 50
+ ? `frame starvation: no frame drawn for ${ms(longest)}`
+ : `frames on pace (longest gap ${ms(longest)})`,
+ );
+ }
+ const lift = drawn.touches.filter(([type]) => type === 'touchend').at(-1);
+ for (const settle of drawn.settles) {
+ if (lift != null && settle > at(lift[1])) {
+ causes.push(`a settle ended ${ms(settle - at(lift[1]))} after the lift`);
+ }
+ }
+ return `Load report: ${causes.length > 0 ? causes.join('; ') : 'no input or frames recorded'}.`;
+}
+
+// A failed case's messages begin with its load report.
+test.afterEach(async ({page}, testInfo) => {
+ if (testInfo.status === testInfo.expectedStatus || page.isClosed()) {
+ return;
+ }
+ const report = await loadReport(page).catch(
+ (error: unknown) => `Load report unavailable: ${String(error)}.`,
+ );
+ for (const error of testInfo.errors) {
+ error.message = `${report}\n${error.message ?? ''}`;
+ if (error.stack != null) {
+ error.stack = `${report}\n${error.stack}`;
+ }
+ }
+});
+
+// A hold or a storyboard reads a motion a round trip after it starts. On
+// loaded cores, a round trip can outlast a 0.2–0.3 s motion. So these arm the
+// harness's hold before the input or goTo (armHold). The page then holds the
+// motion at its first frame, and the read finds it there however late it
+// comes.
+
+/**
+ * Plays `script` with the motion that its lift starts held (armHold), and
+ * gives that motion 5 s from the end of the input. The hold is armed before
+ * the input, so it holds the motion at its first frame. A long input can
+ * outlast the hold's own 5 s. The driver paces its events on the wall clock,
+ * and on a loaded runner they play much longer than scripted. Then the hold
+ * is armed again for what is left of 5 s from the input's end.
+ */
+async function playHeld(
+ page: Page,
+ track: Locator,
+ driver: TouchDriver,
+ script: TouchScript,
+): Promise<ArmedHold> {
+ const first = await armHold(page, track);
+ const caught = first.held().then(
+ held => ({held}),
+ () => null,
+ );
+ await driver.play(script);
+ const inputEnd = Date.now();
+ return {
+ held: async () => {
+ const outcome = await caught;
+ if (outcome != null) {
+ return outcome.held;
+ }
+ const again = await armHold(page, track, {
+ timeout: Math.max(0, inputEnd + 5_000 - Date.now()),
+ });
+ return again.held().catch(() => {
+ throw new Error(
+ 'no motion under the track started within 5 s of the input ending',
+ );
+ });
+ },
+ };
+}
+
+/** Calls `goTo(index)` with the motion it starts held at its first frame. */
+const goToHeld = async (page: Page, track: Locator, index: number) => {
+ const hold = await armHold(page, track);
+ await page.evaluate(next => {
+ window.armFrames();
+ window.pager.goTo(next);
+ }, index);
+ return hold.held();
+};
+
+/**
+ * Whether a selection that starts on the track's text is refused now. Where
+ * iOS WebKit does not run, the shared selection lock cancels `selectstart`
+ * and writes no style. Where it runs, the lock is `user-select: none`, which
+ * WebKit reports only prefixed. `spec:AST-094` FR41.
+ */
+const refusesSelection = (el: Element) => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ (el.firstElementChild ?? el).dispatchEvent(event);
+ const style = getComputedStyle(el) as CSSStyleDeclaration & {
+ webkitUserSelect?: string;
+ };
+ const userSelect = style.userSelect || (style.webkitUserSelect ?? '');
+ return event.defaultPrevented || userSelect === 'none';
+};
+
+/** The track's presented x (from the `translate` the pager drives). */
+const trackX = async (track: Locator) =>
+ track.evaluate(el => {
+ const value = getComputedStyle(el).translate;
+ return value === 'none' ? 0 : parseFloat(value);
+ });
+
+/**
+ * The pager's release velocity for a script: the shared tracker read as a
+ * scroll view reads it (a pan's `scrollVelocity()`), x only.
+ */
+async function releaseVelocities(
+ page: Page,
+ steps: ReturnType<typeof toTouchEvents>,
+) {
+ return page.evaluate(events => {
+ const tracker = new window.Pager.VelocityTracker();
+ let current = 0;
+ for (const event of events) {
+ if (event.type === 'touchEnd' || event.type === 'touchCancel') {
+ // Read at the lift's time, as the recognizer reads it (the
+ // stillness reset).
+ current = tracker.scrollVelocity(event.t).x;
+ break;
+ }
+ const finger = event.changed[0];
+ tracker.add(finger.x, finger.y, event.t);
+ if (event.type === 'touchMove') {
+ current = tracker.scrollVelocity(event.t).x;
+ }
+ }
+ return {current};
+ }, steps);
+}
+
+/**
+ * UIKit's paging settle for a release, from the lift velocity that the
+ * pager's pan read. The page records that velocity as the pan reads it; in
+ * WebKit, it comes from the touches' real dispatch times. The paging solver
+ * runs from where the settle starts onto the page the pager chose. Returns
+ * the content offset at each of `times` (ms into the settle).
+ */
+async function releaseModel(
+ page: Page,
+ {from, to, times}: {from: number; to: number; times: ReadonlyArray<number>},
+) {
+ return page.evaluate(
+ input => {
+ const lift = window.liftVelocities[window.liftVelocities.length - 1];
+ // The pan's x velocity is the finger's; the content moves the other way.
+ const curve = window.Pager.solvePaging({
+ from: input.from,
+ velocity: window.Pager.pagingSettleVelocity(-lift),
+ to: input.to,
+ });
+ return {lift, offsets: input.times.map(t => curve.at(t / 1000))};
+ },
+ {from, to, times},
+ );
+}
+
+/**
+ * A slow 300 px drag `degrees` up from leftward, at 300 px/s along it. At 35°
+ * and 45°, its horizontal part passes half a page, so the pager that takes it
+ * settles on the next page.
+ */
+function angled(degrees: number) {
+ const rad = (degrees * Math.PI) / 180;
+ const from = {x: 340, y: TOP + HEIGHT / 2};
+ return drag(
+ from,
+ {x: from.x - 300 * Math.cos(rad), y: from.y - 300 * Math.sin(rad)},
+ {durationMs: 1000},
+ );
+}
+
+for (const degrees of [35, 45]) {
+ test(`in a scrolling page, a ${degrees}° drag is the pager's: it pages, its moves are cancelled from the pan's start at 10 pt, and the page stays at scrollY 0`, async ({
+ page,
+ }) => {
+ const {track, driver} = await open(page, {tall: true});
+ await driver.play(angled(degrees));
+ await waitForRest(track);
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ const {cancelled, moves, start} = await page.evaluate(() => ({
+ cancelled: window.cancelledMoves,
+ moves: window.moves,
+ start: window.touchStart,
+ }));
+ expect(cancelled.length).toBeGreaterThan(3);
+ // Nothing is claimed before the pan begins at its 10 pt hysteresis, and
+ // every move from the first one past it is. Chromium holds back moves
+ // inside its own touch slop, so its first move may already be past 10 pt.
+ // Mobile Safari claims a slow drag for the page at about 10–11 px. So on
+ // the iOS 26.2 simulator, a drag steeper than about 27° scrolls the page:
+ // 25° pages, while 30° and 35° scroll. UIKit pages up to 45°.
+ const past = moves.findIndex(
+ ([x, y]) =>
+ Math.max(Math.abs(x - start[0]), Math.abs(y - start[1])) >= 10,
+ );
+ expect(past).toBeGreaterThanOrEqual(0);
+ expect(cancelled.slice(0, past).some(Boolean)).toBe(false);
+ expect(cancelled.slice(past).every(Boolean)).toBe(true);
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ });
+}
+
+test("in a scrolling page, a 50° drag is the page's: the page scrolls, the pager stays and no move is cancelled", async ({
+ page,
+ browserName,
+}) => {
+ const {track, driver} = await open(page, {tall: true});
+ await driver.play(angled(50));
+ await page.waitForTimeout(400);
+ expect(await page.evaluate(() => window.pager.index)).toBe(1);
+ expect(await trackX(track)).toBeCloseTo(-PAGE, 1);
+ expect((await page.evaluate(() => window.cancelledMoves)).some(Boolean)).toBe(
+ false,
+ );
+ if (browserName === 'chromium') {
+ // Injected touches scroll natively only in Chromium (harness README).
+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(100);
+ }
+});
+
+/**
+ * The track's settle as a curve of translateX samples (ms, px), from a motion
+ * held at its first frame (an armHold armed before the input).
+ */
+async function heldSettle(hold: ArmedHold, track: Locator) {
+ const held = await hold.held();
+ expect(held.length).toBeGreaterThan(0);
+ return curveOf(
+ await sampleCurve(
+ track,
+ timeline(Math.max(...held.map(a => a.curveEndMs))),
+ ),
+ 'translateX',
+ );
+}
+
+/** solvePaging from `start` at `velocity` onto page 2, at 60 Hz. */
+async function pagingOracle(page: Page, start: number, velocity: number) {
+ return page.evaluate(
+ ({from, v}) => {
+ const curve = window.Pager.solvePaging({from, velocity: v, to: 804});
+ return Array.from({length: 60}, (_, i) => curve.at(i / 60));
+ },
+ {from: start, v: velocity},
+ );
+}
+
+const at = (oracle: number[], t: number) =>
+ oracle[Math.min(oracle.length - 1, Math.round((t * 60) / 1000))];
+
+test("a slow drag past half a page, well under the 225 px/s floor, settles on the next page from rest on UIKit's paging curve", async ({
+ page,
+}) => {
+ const {track, driver} = await open(page);
+ // 60 % of a page at 100 px/s, lifted while moving: under the floor in
+ // either engine, so the settle starts at rest.
+ const script = drag(
+ {x: 320, y: 200},
+ {x: 320 - 0.6 * PAGE, y: 200},
+ {durationMs: 2400, restMs: 0},
+ );
+ const hold = await playHeld(page, track, driver, script);
+ const samples = await heldSettle(hold, track);
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ const oracle = await pagingOracle(page, -samples[0].value, 0);
+ const result = compareCurve(samples, t => -at(oracle, t), 1);
+ await writeEvidence(
+ 'pager/slow-drag-settle',
+ {'curve.json': JSON.stringify({samples, result}, null, 2)},
+ test.info(),
+ );
+ expect(result.maxError).toBeLessThan(1);
+ await releaseAnimations(page);
+ await waitForRest(track);
+ expect(await trackX(track)).toBeCloseTo(-2 * PAGE, 0);
+});
+
+// UIKit keeps the release velocity through a silent rest. Recorded on iOS
+// 26.2: 600 pt/s, then up to 397 ms with no touch event, kept 0.55 to
+// 0.61 pt/ms. The shared release filter reads 0 after 40 ms of silence
+// instead (spec:AST-100 FR2), and the pager reads the filter. A held finger
+// sends no events here either.
+test('a drag held still for 200 ms before the lift settles from rest: the release filter reads 0 after 40 ms of silence (spec:AST-100 FR2)', async ({
+ page,
+}) => {
+ const {track, driver} = await open(page);
+ // 60 % of a page at 600 px/s (far above the floor in either engine), then
+ // held still for 200 ms.
+ const script = drag(
+ {x: 320, y: 200},
+ {x: 320 - 0.6 * PAGE, y: 200},
+ {durationMs: 402, restMs: 200},
+ );
+ const velocities = await releaseVelocities(page, toTouchEvents(script));
+ expect(velocities.current).toBe(0);
+ const hold = await playHeld(page, track, driver, script);
+ const samples = await heldSettle(hold, track);
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ const rest = await pagingOracle(page, -samples[0].value, 0);
+ const result = compareCurve(samples, t => -at(rest, t), 1);
+ await writeEvidence(
+ 'pager/held-drag-settle',
+ {'curve.json': JSON.stringify({samples, result}, null, 2)},
+ test.info(),
+ );
+ expect(result.maxError).toBeLessThan(1);
+ await releaseAnimations(page);
+ await waitForRest(track);
+ expect(await trackX(track)).toBeCloseTo(-2 * PAGE, 0);
+});
+
+test('callbacks: the new page once the settle is moving, the settle when the track rests', async ({
+ page,
+}) => {
+ const {track, driver} = await open(page);
+ // 60 % of a page at 600 px/s, lifted while moving.
+ await driver.play(
+ drag(
+ {x: 320, y: 200},
+ {x: 320 - 0.6 * PAGE, y: 200},
+ {durationMs: 402, restMs: 0},
+ ),
+ );
+ // Reported a couple of frames into the settle, so the owner's render of
+ // the new page cannot hold up its hand-off to the compositor.
+ await expect
+ .poll(async () => (await log(page))[0])
+ .toBe('index:2:drag:moving');
+ await waitForRest(track);
+ await page.waitForTimeout(50);
+ expect(await log(page)).toEqual(['index:2:drag:moving', 'settle:2:1']);
+});
+
+test('a flick pages exactly one page, and the settle starts from the release velocity', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName === 'webkit',
+ 'WebKit sees real dispatch times, not the scripted ones the velocity oracle replays (harness README)',
+ );
+ const {track, driver} = await open(page);
+ const throwScript = flick(
+ {x: 320, y: 200},
+ {velocity: {x: -1500, y: 0}, durationMs: 80, hz: 120},
+ );
+ const velocities = await releaseVelocities(page, toTouchEvents(throwScript));
+ const hold = await playHeld(page, track, driver, throwScript);
+ const held = await hold.held();
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ const samples = curveOf(
+ await sampleCurve(
+ track,
+ timeline(Math.max(...held.map(a => a.curveEndMs))),
+ ),
+ 'translateX',
+ );
+ const from = -samples[0].value;
+ const oracle = await page.evaluate(
+ ({start, current}) => {
+ // The pan's x velocity is the finger's; the content moves the other way.
+ const settle = window.Pager.pagingSettleVelocity(-current);
+ const curve = window.Pager.solvePaging({
+ from: start,
+ velocity: settle,
+ to: 804,
+ });
+ return {
+ settle,
+ values: Array.from({length: 60}, (_, i) => curve.at(i / 60)),
+ };
+ },
+ {start: from, ...velocities},
+ );
+ expect(oracle.settle).toBeGreaterThan(900);
+ const result = compareCurve(
+ samples,
+ t => -oracle.values[Math.min(59, Math.round((t * 60) / 1000))],
+ 1.5,
+ );
+ await writeEvidence(
+ 'pager/flick-settle',
+ {
+ 'curve.json': JSON.stringify(
+ {samples, settle: oracle.settle, result},
+ null,
+ 2,
+ ),
+ },
+ test.info(),
+ );
+ expect(result.maxError).toBeLessThan(1.5);
+ await releaseAnimations(page);
+ await waitForRest(track);
+ // One page, however hard the throw.
+ expect(await trackX(track)).toBeCloseTo(-2 * PAGE, 0);
+});
+
+test('past the first page the track rubber-bands with d = the page width, then returns', async ({
+ page,
+}) => {
+ const {track, driver} = await open(page, {startIndex: 0});
+ const finger = 290;
+ let shown = NaN;
+ const moves = toTouchEvents(
+ drag(
+ {x: 60, y: 200},
+ {x: 60 + finger + 10, y: 200},
+ {durationMs: 600, restMs: 120},
+ ),
+ ).filter(e => e.type === 'touchMove').length;
+ let seen = 0;
+ await driver.play(
+ drag(
+ {x: 60, y: 200},
+ {x: 60 + finger + 10, y: 200},
+ {durationMs: 600, restMs: 120},
+ ),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove' && ++seen === moves) {
+ await page.evaluate(
+ async () =>
+ new Promise(r =>
+ requestAnimationFrame(() => requestAnimationFrame(r)),
+ ),
+ );
+ shown = await trackX(track);
+ }
+ },
+ },
+ );
+ const expected = await page.evaluate(
+ f => window.Pager.rubberBand(f, 402),
+ finger,
+ );
+ // 10 px of the finger went to the pan's threshold.
+ expect(shown).toBeGreaterThan(expected - 3);
+ expect(shown).toBeLessThan(expected + 3);
+ await waitForRest(track);
+ expect(await trackX(track)).toBeCloseTo(0, 0);
+ expect(await log(page)).toEqual(['settle:0:0']);
+});
+
+// spec:AST-094 FR37: a release whose velocity points back toward the start
+// cancels, whatever the travel (UIKit takes the nearest page).
+test('a drag 70 % of the way to the next page that turns back and lifts while moving back settles on its start page', async ({
+ page,
+}) => {
+ const {track, driver} = await open(page);
+ const x0 = 320;
+ // Forward 70 % of a page, then back 30 px in the last 180 ms, lifted
+ // while moving back.
+ await driver.play(
+ path(
+ p =>
+ p <= 0.85
+ ? {x: x0 - (0.7 * PAGE * p) / 0.85, y: 200}
+ : {x: x0 - 0.7 * PAGE + (30 * (p - 0.85)) / 0.15, y: 200},
+ {durationMs: 1200, restMs: 0},
+ ),
+ );
+ await releaseAnimations(page);
+ await waitForRest(track);
+ expect(await page.evaluate(() => window.pager.index)).toBe(1);
+ expect(await trackX(track)).toBeCloseTo(-PAGE, 0);
+ expect(await log(page)).toEqual(['settle:1:1']);
+});
+
+// spec:AST-094 FR6: a new target keeps the current velocity.
+test('a goTo that retargets a running goTo keeps its velocity: the new curve starts at the speed the old one had', async ({
+ page,
+}) => {
+ const {track} = await open(page, {startIndex: 0});
+ // The first goTo starts in the task that reads it: a round trip between the
+ // two can outlast its 0.3 s on two loaded cores.
+ const {before, after, firedAt} = await page.evaluate(async () => {
+ const el = document.getElementById('track') as HTMLElement;
+ window.armFrames();
+ window.pager.goTo(3);
+ // The keyframes' slope at `time` (ms into the animation), px/s: the
+ // animator plays a curve as linear segments between samples.
+ const slope = (animation: Animation, time: number) => {
+ const effect = animation.effect as KeyframeEffect;
+ const frames = effect.getKeyframes();
+ const duration = Number(effect.getComputedTiming().duration);
+ const at = Math.min(Math.max(time / duration, 0), 1);
+ for (let i = 1; i < frames.length; i++) {
+ const a = frames[i - 1];
+ const b = frames[i];
+ if (at <= b.computedOffset || i === frames.length - 1) {
+ const span = (b.computedOffset - a.computedOffset) * duration;
+ return span > 0
+ ? ((parseFloat(String(b.translate)) -
+ parseFloat(String(a.translate))) /
+ span) *
+ 1000
+ : 0;
+ }
+ }
+ return 0;
+ };
+ const running = el.getAnimations()[0];
+ // Once the curve has started (its start resolves in its first frame), the
+ // retarget comes 100 ms into it on the page's clock. This task waits for
+ // it, so no other task, such as a timer's queue or a slow frame, can hold
+ // it back. A loaded runner held a 100 ms timer past the curve's end. The
+ // old curve's slope is read at the time the retarget comes, on the clock
+ // that the animator's model runs on.
+ await running.ready;
+ const start = Number(running.startTime);
+ while (performance.now() < start + 100) {
+ // The curve runs on the compositor meanwhile.
+ }
+ const firedAt = performance.now() - start;
+ const speed = slope(running, firedAt);
+ window.pager.goTo(4);
+ const next = el.getAnimations().find(a => a !== running);
+ return {
+ before: speed,
+ after: next ? slope(next, 0) : Number.NaN,
+ firedAt,
+ };
+ });
+ expect(
+ Math.abs(before),
+ `the retarget came ${firedAt.toFixed(1)} ms into the 300 ms curve`,
+ ).toBeGreaterThan(1000);
+ expect(after / before).toBeGreaterThan(0.85);
+ expect(after / before).toBeLessThan(1.15);
+ await waitForRest(track);
+ expect(await trackX(track)).toBeCloseTo(-4 * PAGE, 0);
+});
+
+test('goTo plays setContentOffset(animated:): 0.3 s on a sinusoidal ease', async ({
+ page,
+}) => {
+ const {track} = await open(page, {startIndex: 0});
+ const held = await goToHeld(page, track, 3);
+ // Reported at the call; held, the motion cannot settle yet.
+ expect(await log(page)).toEqual(['index:3:goTo']);
+ const end = Math.max(...held.map(a => a.curveEndMs));
+ expect(end).toBeGreaterThan(290);
+ expect(end).toBeLessThan(310);
+ const samples = curveOf(
+ await sampleCurve(track, timeline(end)),
+ 'translateX',
+ );
+ const result = compareCurve(
+ samples,
+ t => (-3 * PAGE * (1 - Math.cos(Math.PI * Math.min(1, t / 300)))) / 2,
+ 0.5,
+ );
+ expect(result.maxError).toBeLessThan(0.5);
+ await releaseAnimations(page);
+});
+
+/**
+ * At most a jump: `property` holds its start value, then its end value, and
+ * never one in between. A cross-fade moves the track at the bottom of its dip
+ * (design:reduced-motion DR1).
+ */
+const holdsOrJumps = (
+ keyframes: ReadonlyArray<Record<string, unknown>>,
+ property: string,
+): boolean => {
+ const values = new Set<string>();
+ for (const k of keyframes) {
+ const v = k[property];
+ if (typeof v === 'string' || typeof v === 'number') {
+ values.add(String(v));
+ }
+ }
+ return values.size <= 2;
+};
+
+test('under Reduce Motion the settle and goTo do not travel: an opacity cross-fade of at most 200 ms on a coarse pointer (design:reduced-motion DR2)', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {track, driver} = await open(page);
+ expect(
+ await page.evaluate(() => ({
+ reduce: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ coarse: matchMedia('(pointer: coarse)').matches,
+ })),
+ ).toEqual({reduce: true, coarse: true});
+ const crossFadesOnly = (animations: ReadonlyArray<HeldAnimation>) => {
+ expect(animations.length).toBeGreaterThan(0);
+ for (const a of animations) {
+ // Nothing travels: the track holds, then jumps under the fade (DR1).
+ expect(holdsOrJumps(a.keyframes, 'translate')).toBe(true);
+ expect(holdsOrJumps(a.keyframes, 'transform')).toBe(true);
+ expect(a.curveEndMs).toBeLessThanOrEqual(200);
+ }
+ };
+ // The drag follows the finger; after the lift the settle cross-fades.
+ const throwScript = flick(
+ {x: 320, y: 200},
+ {velocity: {x: -1500, y: 0}, durationMs: 80},
+ );
+ const hold = await playHeld(page, track, driver, throwScript);
+ crossFadesOnly(await hold.held());
+ await releaseAnimations(page);
+ await expect
+ .poll(async () => page.evaluate(() => window.pager.isSettling))
+ .toBe(false);
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ // goTo cross-fades too.
+ crossFadesOnly(await goToHeld(page, track, 4));
+ await releaseAnimations(page);
+ await expect
+ .poll(async () => page.evaluate(() => window.pager.isSettling))
+ .toBe(false);
+ expect(await page.evaluate(() => window.pager.index)).toBe(4);
+});
+
+test(`a still finger catches a settle ${85} ms after it lands, selects no text, and the lift settles on the nearest page`, async ({
+ page,
+}) => {
+ const {track, driver} = await open(page, {startIndex: 0});
+ // One timeline the driver paces: a flick toward page 1. Then, 40 ms after
+ // its lift, a second finger lands on the settling track. It holds still for
+ // 600 ms, with a 0.6 px creep reported every 100 ms. The hold lands early in
+ // the settle, however busy the machine is. A settle that a separate goTo
+ // started raced the touch's dispatch, and under load the touch came later.
+ const throwScript = flick(
+ {x: 320, y: 200},
+ {velocity: {x: -1500, y: 0}, durationMs: 80, hz: 120},
+ );
+ const liftAt = throwScript[throwScript.length - 1].t;
+ const hold = withFinger(
+ drag({x: 200, y: 200}, {x: 200.6, y: 200}, {durationMs: 600, hz: 10}),
+ 1,
+ liftAt + 40,
+ );
+ const reads: {
+ x: number;
+ refused: boolean;
+ lift: {velocity: number; x: number; page: number};
+ }[] = [];
+ let holdMoves = 0;
+ await driver.play(merge(throwScript, hold), {
+ onEvent: async event => {
+ if (
+ event.type === 'touchMove' &&
+ event.changed.some(finger => finger.id === 1) &&
+ (++holdMoves === 3 || holdMoves === 6)
+ ) {
+ reads.push({
+ x: await track.evaluate(
+ el => parseFloat(getComputedStyle(el).translate) || 0,
+ ),
+ refused: await track.evaluate(refusesSelection),
+ // The flick's lift, as the pan read it, where the track was, and
+ // the page the release chose (the catch keeps it until the lift).
+ lift: await page.evaluate(() => ({
+ velocity: window.liftVelocities[window.liftVelocities.length - 1],
+ x: window.liftPositions[window.liftPositions.length - 1],
+ page: window.pager.index,
+ })),
+ });
+ }
+ },
+ });
+ // Held: the same place at 300 and 600 ms, no selection.
+ expect(reads).toHaveLength(2);
+ expect(reads[1].x).toBeCloseTo(reads[0].x, 1);
+ expect(reads[0].refused).toBe(true);
+ // Caught mid-settle, the track sits on UIKit's settle for the lift that the
+ // pan read. That settle runs from the track's place at the lift onto the
+ // page the release chose. The hold stops it wherever it is on that curve
+ // (within 1.5 px), never at rest. In WebKit, touches carry their real
+ // dispatch times. So a busy page can read the lift faster than scripted,
+ // and that curve passes page 1 before it lands. Or a stall reads it as
+ // still, and the settle returns to page 0.
+ const settle = await page.evaluate(
+ ({velocity, from, to}) => {
+ const curve = window.Pager.solvePaging({
+ from,
+ velocity: window.Pager.pagingSettleVelocity(-velocity),
+ to,
+ });
+ const values: number[] = [];
+ for (let ms = 0; ms <= curve.duration * 1000; ms += 1) {
+ values.push(curve.at(ms / 1000));
+ }
+ return {nearest: Math.min(...values), furthest: Math.max(...values)};
+ },
+ {
+ velocity: reads[0].lift.velocity,
+ from: -reads[0].lift.x,
+ to: reads[0].lift.page * PAGE,
+ },
+ );
+ const held = -reads[0].x;
+ expect(held, JSON.stringify({lift: reads[0].lift, settle})).toBeGreaterThan(
+ settle.nearest - 1.5,
+ );
+ expect(held, JSON.stringify({lift: reads[0].lift, settle})).toBeLessThan(
+ settle.furthest + 1.5,
+ );
+ expect(Math.abs(held - reads[0].lift.page * PAGE)).toBeGreaterThan(0.5);
+ // The lift settles on the page nearest to where it was held.
+ const nearest = Math.round(-reads[1].x / PAGE);
+ await waitForRest(track);
+ expect(await trackX(track)).toBeCloseTo(-nearest * PAGE, 0);
+ expect(await track.evaluate(refusesSelection)).toBe(false);
+});
+
+// spec:AST-094 FR41: a hold that does nothing keeps the browser's native
+// long-press selection. So a finger held on a resting pager's text can still
+// select it.
+test('a finger held on a resting track leaves its text selectable', async ({
+ page,
+}) => {
+ const {track, driver} = await open(page, {startIndex: 1});
+ const reads: boolean[] = [];
+ let step = 0;
+ await driver.play(
+ drag({x: 200, y: 200}, {x: 200.6, y: 200}, {durationMs: 600, hz: 10}),
+ {
+ onEvent: async event => {
+ if (event.type === 'touchMove' && step++ === 3) {
+ reads.push(await track.evaluate(refusesSelection));
+ }
+ },
+ },
+ );
+ expect(reads).toEqual([false]);
+ await waitForRest(track);
+ expect(await trackX(track)).toBeCloseTo(-PAGE, 0);
+});
+
+test('a settle keeps advancing every frame through an 800 ms main-thread block', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName === 'webkit',
+ "WebKit's screencast clock is not the page's (frames arrive ~100 ms off), so a 0.3 s motion cannot be placed inside the block; the animator's own WebKit proof covers compositor playback, and Mobile Safari on the iOS simulator is this proof's WebKit evidence",
+ );
+ await open(page, {startIndex: 0});
+ const marker = page.locator('.page').nth(1);
+ await markElement(marker, {inset: 8});
+ const cast = await startScreencast(page);
+ // Let the screencast deliver a few frames before anything moves.
+ await page.waitForTimeout(300);
+ // A goTo of one page (0.3 s at any distance), and an 800 ms block that the
+ // page schedules 90 ms in. WebKit hands a new animation to its compositor
+ // two or three rendering updates after it starts (animator.ts, known
+ // limits). A harness round trip would eat most of the motion.
+ const started = await page.evaluate(() => {
+ window.pager.goTo(1);
+ setTimeout(() => {
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 800;
+ let spins = 0;
+ while (performance.now() < end) {
+ spins += 1;
+ }
+ (window as unknown as {busy: unknown}).busy = {
+ from,
+ to: performance.timeOrigin + performance.now(),
+ spins,
+ };
+ }, 90);
+ return performance.timeOrigin + performance.now();
+ });
+ await page.waitForTimeout(1200);
+ const busy = await page.evaluate(
+ () =>
+ (window as unknown as {busy: {from: number; to: number; spins: number}})
+ .busy,
+ );
+ const tracked = await trackMarker(page, await cast.stop());
+ // Judge the part of the block that the motion spans. The motion ends about
+ // 0.3 s after the call, or a frame later when it starts at the next commit.
+ const spanned = {...busy, to: Math.min(busy.to, started + 300)};
+ test.info().annotations.push({
+ type: 'marker x per frame (ms from the call)',
+ description: JSON.stringify(
+ tracked.map(f => [Math.round(f.t - started), f.box?.x ?? null]),
+ ),
+ });
+ expect(spanned.to - spanned.from).toBeGreaterThan(150);
+ const proof = busyWindowProof(tracked, spanned, {
+ axis: 'x',
+ settledWithin: 1,
+ });
+ test.info().annotations.push({
+ type: 'busy window',
+ description: JSON.stringify({...proof, window: undefined}),
+ });
+ expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2);
+ expect(proof.changed).toBeGreaterThanOrEqual(proof.frames - 3);
+ // And it lands while the thread is still blocked. The last frame that the
+ // page presented before the block ended shows the end state. There, page
+ // 1's marker sits at its inset from the viewport's left edge. A page at rest
+ // presents no new frame, so the landing is that last frame, whenever the
+ // screencast delivered it.
+ const blocked = tracked.filter(f => f.box != null && f.t < busy.to);
+ const last = blocked[blocked.length - 1];
+ expect(last.t).toBeGreaterThan(spanned.from);
+ expect(Math.abs((last.box?.x ?? 0) - 8)).toBeLessThan(1.5);
+});
+
+test('no Layout or Paint while it settles', async ({page, browserName}) => {
+ test.skip(
+ browserName === 'webkit',
+ 'Playwright exposes no rendering trace for WebKit',
+ );
+ const {track} = await open(page, {startIndex: 0});
+ // Nothing reads the page while the motion runs: a read mid-motion draws a
+ // frame of its own, with paint. The motion notes when its curve starts, by
+ // the engine's clock, and that note is read afterwards. Under load, its
+ // first frame can come well after the call.
+ const trace = await traceRendering(page, async () => {
+ await page.evaluate(() => {
+ window.armFrames();
+ window.pager.goTo(2);
+ const track = document.getElementById('track') as HTMLElement;
+ for (const animation of track.getAnimations()) {
+ void animation.ready.then(running => {
+ if (running.startTime != null) {
+ const start = performance.timeOrigin + Number(running.startTime);
+ window.motionStart = Math.min(window.motionStart ?? start, start);
+ }
+ });
+ }
+ });
+ // The 0.3 s motion, with room for a late start under load.
+ await page.waitForTimeout(800);
+ });
+ const started = await page.evaluate(() => window.motionStart ?? NaN);
+ expect(Number.isFinite(started)).toBe(true);
+ // The trace holds the whole motion, and the motion moved the track to its
+ // page. So no layout or paint in it means the compositor moved it, not that
+ // the motion never ran. With nothing reading the page, the main thread draws
+ // no frame while it moves.
+ expect(trace.window.to).toBeGreaterThan(started + 300);
+ expect(await trackX(track)).toBeCloseTo(-2 * PAGE, 0);
+ // The steady part of the 0.3 s motion: its first and last frames may commit.
+ const during = countBetween(trace, started + 60, started + 240);
+ expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0);
+ expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0);
+ // And no long task while it settles. The task that starts the motion is the
+ // goTo call, which samples the curve into keyframes. It ends where the curve
+ // starts, and it is not part of the settle. On two loaded cores, it
+ // stretched to 51–85 ms, and ended 0.25–0.55 ms before the curve's start.
+ const whileSettling = trace.longTasks.filter(
+ task =>
+ task.start + task.durationMs > started && task.start < started + 300,
+ );
+ expect(
+ whileSettling,
+ JSON.stringify({started, longTasks: trace.longTasks}),
+ ).toEqual([]);
+});
+
+for (const [name, script] of [
+ [
+ 'release-at-rest',
+ drag(
+ {x: 320, y: 200},
+ {x: 320 - 0.6 * PAGE, y: 200},
+ {durationMs: 1000, restMs: 120},
+ ),
+ ],
+ [
+ 'flick',
+ flick(
+ {x: 320, y: 200},
+ {velocity: {x: -1500, y: 0}, durationMs: 80, hz: 120},
+ ),
+ ],
+ [
+ // The lift a busy WebKit page read for the flick above, its moves bunched:
+ // 144 px in 8 ms, about 18,000 px/s.
+ 'flick-bunched',
+ flick(
+ {x: 320, y: 200},
+ {velocity: {x: -18_000, y: 0}, durationMs: 8, hz: 1000},
+ ),
+ ],
+ [
+ 'return-to-page',
+ drag(
+ {x: 320, y: 200},
+ {x: 320 - 0.3 * PAGE, y: 200},
+ {durationMs: 1000, restMs: 120},
+ ),
+ ],
+ ['goto', null],
+] as const) {
+ test(`storyboard: ${name} @storyboard`, async ({page}) => {
+ const {track, driver} = await open(page);
+ let held: ReadonlyArray<HeldAnimation>;
+ if (script == null) {
+ held = await goToHeld(page, track, 3);
+ } else {
+ const hold = await playHeld(page, track, driver, script);
+ held = await hold.held();
+ }
+ const {storyboard} = await animationStoryboard(page, {
+ name: `pager-${name}`,
+ held,
+ clip: {x: 0, y: TOP, width: PAGE, height: HEIGHT},
+ measure: async () => ({x: await trackX(track)}),
+ });
+ await storyboard.write(test.info());
+ const xs = storyboard.frames.map(f => (f.data as {x: number}).x);
+ // It lands on the page the pager chose (the last frame is half a
+ // millisecond inside the curve's end, within the last step).
+ const index = await page.evaluate(() => window.pager.index);
+ expect(Math.abs(xs[xs.length - 1] + index * PAGE)).toBeLessThan(1.5);
+ if (name === 'goto') {
+ // setContentOffset's ease runs toward the page and never past it.
+ const toward = Math.sign(xs[xs.length - 1] - xs[0]);
+ for (let i = 1; i < xs.length; i++) {
+ expect(Math.sign(xs[i] - xs[i - 1]) * toward).toBeGreaterThanOrEqual(0);
+ }
+ } else {
+ // A release: every frame, the landing included, lies on UIKit's paging
+ // curve for the lift velocity the pan read, within 1.5 px. A fast lift
+ // carries the curve past the page and back; the frames follow it.
+ const model = await releaseModel(page, {
+ from: -xs[0],
+ to: index * PAGE,
+ times: storyboard.frames.map(f => f.t),
+ });
+ const off = xs.map((x, i) => Math.abs(x + model.offsets[i]));
+ expect(
+ Math.max(...off),
+ JSON.stringify({lift: model.lift, xs, model: model.offsets}),
+ ).toBeLessThan(1.5);
+ }
+ await releaseAnimations(page);
+ });
+}
+
+// spec:AST-094 FR43: gestures work on the web for every pointer. A desktop
+// context: a fine primary pointer, a real mouse and real wheel input.
+// Chromium's CDP input sends wheels without a trackpad's legacy `wheelDelta`
+// (three times each delta). So the gesture engine reads them as a mouse's
+// wheel, which a pan that takes only a trackpad's scroll leaves to the page.
+// The trackpad cases run in WebKit, whose injected wheels carry it.
+const TRACKPAD_IN_CHROMIUM =
+ "Chromium's CDP wheels read as a mouse's wheel; the trackpad cases run in WebKit";
+
+test.describe('under a fine primary pointer (spec:AST-094 FR43)', () => {
+ test.use({hasTouch: false, isMobile: false});
+
+ test('a mouse drag pages the pager like a finger', async ({page}) => {
+ const {track} = await openFine(page);
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const y = TOP + HEIGHT / 2;
+ await page.mouse.move(340, y);
+ await page.mouse.down();
+ // 250 px toward the start, past half a page whatever the release speed.
+ for (let i = 1; i <= 25; i++) {
+ await page.mouse.move(340 - 10 * i, y);
+ }
+ await page.mouse.up();
+ await waitForRest(track);
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ expect(await trackX(track)).toBeCloseTo(-2 * PAGE, 0);
+ });
+
+ test("a trackpad's horizontal scroll pages the pager, and the page keeps none of it", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName === 'chromium', TRACKPAD_IN_CHROMIUM);
+ const {track, input} = await openFine(page);
+ // 40 steps of 6.5 px (a trackpad's continuous scroll): 260 px toward the
+ // next page, past half of it whatever the release speed.
+ for (let i = 0; i < 40; i++) {
+ await input.wheel({x: 200, y: TOP + HEIGHT / 2, dx: 6.5});
+ }
+ // A trackpad scroll ends 220 ms after its last wheel.
+ await page.waitForTimeout(300);
+ await waitForRest(track);
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ expect(await trackX(track)).toBeCloseTo(-2 * PAGE, 0);
+ const cancelled = await page.evaluate(() => window.cancelledWheels);
+ expect(cancelled.length).toBeGreaterThan(0);
+ expect(cancelled.every(Boolean)).toBe(true);
+ });
+
+ test("a trackpad scroll of more than a page stays the pager's while the next page moves under the still cursor, stops at that page, and pages one page", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName === 'chromium', TRACKPAD_IN_CHROMIUM);
+ const {track, input} = await openFine(page);
+ // The furthest the track gets, sampled every frame.
+ await page.evaluate(() => {
+ window.minTrackX = 0;
+ const el = document.getElementById('track') as HTMLElement;
+ const sample = () => {
+ const value = getComputedStyle(el).translate;
+ const x = value === 'none' ? 0 : parseFloat(value);
+ window.minTrackX = Math.min(window.minTrackX, x);
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ });
+ // 30 steps of 17.5 px: 525 px, more than a page. The cursor stays put
+ // while the next page slides under it; the track stops there, one page
+ // from where the scroll began.
+ for (let i = 0; i < 30; i++) {
+ await input.wheel({x: 200, y: TOP + HEIGHT / 2, dx: 17.5});
+ }
+ // A trackpad scroll ends 220 ms after its last wheel.
+ await page.waitForTimeout(300);
+ await waitForRest(track);
+ const furthest = await page.evaluate(() => window.minTrackX);
+ expect(furthest).toBeGreaterThanOrEqual(-2 * PAGE - 0.5);
+ expect(furthest).toBeLessThanOrEqual(-2 * PAGE + 0.5);
+ const cancelled = await page.evaluate(() => window.cancelledWheels);
+ expect(cancelled.length).toBeGreaterThan(0);
+ expect(cancelled.every(Boolean)).toBe(true);
+ // One page per release, as UIKit pages.
+ expect(await page.evaluate(() => window.pager.index)).toBe(2);
+ expect(await trackX(track)).toBeCloseTo(-2 * PAGE, 0);
+ });
+
+ test("a vertical wheel over the pager is the page's: the pager stays and takes none of it", async ({
+ page,
+ browserName,
+ }) => {
+ const {track, input} = await openFine(page, {tall: true});
+ for (let i = 0; i < 10; i++) {
+ await input.wheel({x: 200, y: TOP + HEIGHT / 2, dy: 40.5});
+ }
+ await page.waitForTimeout(200);
+ expect(await page.evaluate(() => window.pager.index)).toBe(1);
+ expect(await trackX(track)).toBeCloseTo(-PAGE, 0);
+ const cancelled = await page.evaluate(() => window.cancelledWheels);
+ expect(cancelled.length).toBeGreaterThan(0);
+ expect(cancelled.some(Boolean)).toBe(false);
+ if (browserName === 'chromium') {
+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/packages/core/src/hooks/useAttachment.ts b/packages/core/src/hooks/useAttachment.ts
index 9bfe67fa64..77a1d8b4be 100644
--- a/packages/core/src/hooks/useAttachment.ts
+++ b/packages/core/src/hooks/useAttachment.ts
@@ -4,16 +4,16 @@
/**
* @file useAttachment.ts
- * @input A node ref (an element's, or the document's), an attach function
+ * @input Node refs (an element's, or the document's), an attach function
* and a key
- * @output Exports useAttachment: keeps the attach function bound to the node
- * the ref holds across commits
- * @position Internal React helper, not in hooks/index.ts: the one attach
- * and release lifecycle of the gesture hooks (useGestureRecognizer,
- * usePressTracker, useFingerScroll)
+ * @output Exports useAttachment and useAttachmentPair (two elements): they keep
+ * the attach function bound to the nodes the refs hold across commits
+ * @position Internal React helper, not in hooks/index.ts: the one attach and
+ * release lifecycle of the gesture hooks and the pager
*
- * SYNC: When modified, update gestures/__tests__/useGestureRecognizer.test.tsx
- * and gestures/__tests__/useFingerScroll.test.tsx.
+ * SYNC: When modified, update gestures/__tests__/useGestureRecognizer.test.tsx,
+ * gestures/__tests__/useFingerScroll.test.tsx and
+ * __tests__/useAttachmentPair.test.tsx.
*/
import {useRef, type RefObject} from 'react';
@@ -29,23 +29,65 @@ export function useAttachment<T extends Node = Element>(
ref: RefObject<T | null>,
attach: (element: T) => () => void,
key: unknown,
+): void {
+ useAttachedNodes([ref], ([node]) => attach(node as T), key);
+}
+
+/**
+ * `useAttachment` for two elements. It keeps `attach` bound to the pair the
+ * refs hold after each commit, once both are there. Replacing either element
+ * releases the attachment and attaches the new pair. A changed `key`
+ * re-attaches, and the last attachment is released on unmount. A commit that
+ * changes neither does nothing.
+ */
+export function useAttachmentPair<A extends Element, B extends Element>(
+ firstRef: RefObject<A | null>,
+ secondRef: RefObject<B | null>,
+ attach: (first: A, second: B) => () => void,
+ key: unknown,
+): void {
+ useAttachedNodes(
+ [firstRef, secondRef],
+ ([first, second]) => attach(first as A, second as B),
+ key,
+ );
+}
+
+/**
+ * The lifecycle both share: one attachment of the nodes the refs hold. It is
+ * made once every node is there, and released when a node or `key` changes
+ * and at unmount.
+ */
+function useAttachedNodes(
+ refs: ReadonlyArray<RefObject<Node | null>>,
+ attach: (nodes: ReadonlyArray<Node>) => () => void,
+ key: unknown,
): void {
const attachmentRef = useRef<{
- element: T;
+ nodes: ReadonlyArray<Node>;
key: unknown;
release: () => void;
} | null>(null);
- // Syncs the attachment with the DOM node `ref` holds after this commit.
+ // Syncs the attachment with the DOM nodes the refs hold after this commit.
useIsomorphicLayoutEffect(() => {
- const element = ref.current;
+ const nodes = refs.map(ref => ref.current);
const current = attachmentRef.current;
- if (current?.element === element && current?.key === key) {
+ if (
+ current != null &&
+ current.key === key &&
+ nodes.every((node, index) => node === current.nodes[index])
+ ) {
return;
}
current?.release();
- attachmentRef.current =
- element == null ? null : {element, key, release: attach(element)};
+ attachmentRef.current = nodes.every(node => node != null)
+ ? {
+ nodes: nodes,
+ key,
+ release: attach(nodes),
+ }
+ : null;
});
// Releases the attachment at unmount.
diff --git a/packages/core/src/hooks/usePager.test.ts b/packages/core/src/hooks/usePager.test.ts
new file mode 100644
index 0000000000..8b786a7c0b
--- /dev/null
+++ b/packages/core/src/hooks/usePager.test.ts
@@ -0,0 +1,3051 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file usePager.test.ts
+ * @input vitest (jsdom), the gesture host on a manual clock, the animator
+ * with a recording Web Animations stub, and synthetic touches
+ * @output Proves the pager's behavior: tracking, the rubber band, UIKit's page
+ * choice and settle, the catch, goTo, loops, RTL, the axis rules and the
+ * callbacks
+ * @position Testing; the browser proofs are
+ * __tests__/usePager.interaction.browser.spec.ts
+ */
+
+import {act, render} from '@testing-library/react';
+import {createElement, useRef, useState} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {GestureHost} from '../gestures/GestureHost';
+import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';
+import {ManualClock} from '../gestures/__tests__/harness';
+import {createAnimator, type Animator} from '../motion/animator';
+import {solveAnimatedPageScroll, solvePaging} from '../motion/paging';
+import type * as motionResolution from '../motion/resolveMotion';
+import {resolveMotion} from '../motion/resolveMotion';
+import {rubberBand} from '../motion/rubberBand';
+import {paging} from '../motion/uikit/paging';
+import {
+ createPager,
+ pageForRelease,
+ usePager,
+ type Pager,
+ type PagerOptions,
+} from './usePager';
+
+const WIDTH = 400;
+
+// resolveMotion as shipped, observable: a test can stand in other values for
+// the roles a motion reads (spec:AST-094 FR4).
+vi.mock('../motion/resolveMotion', async importOriginal => {
+ const actual = await importOriginal<typeof motionResolution>();
+ return {...actual, resolveMotion: vi.fn(actual.resolveMotion)};
+});
+
+// --- A recording Web Animations stub (pending until a frame commits). ------
+
+interface Recorded {
+ keyframes: Keyframe[];
+ options: KeyframeAnimationOptions;
+ startTime: number | null;
+ cancelled: boolean;
+ playState: string;
+ ready: Promise<unknown>;
+ cancel(): void;
+ commit(at: number): void;
+}
+
+let now = 1000;
+let recorded: Recorded[] = [];
+let frameQueue: (() => void)[] = [];
+
+beforeEach(() => {
+ now = 1000;
+ recorded = [];
+ frameQueue = [];
+ vi.useFakeTimers();
+ // A phone: a coarse primary pointer, which the gesture host reads when it
+ // first attaches. Gestures attach for every pointer (spec:AST-094 FR19,
+ // FR43). Under a fine pointer, an element keeps one passive `pointerdown`
+ // listener, and the page's listeners last only a press (FR24).
+ stubMedia(false, true);
+ HTMLElement.prototype.animate = function (keyframes, options) {
+ let resolveReady: (value: unknown) => void = () => {};
+ let rejectReady: (error: Error) => void = () => {};
+ const ready = new Promise((resolve, reject) => {
+ resolveReady = resolve;
+ rejectReady = reject;
+ });
+ ready.catch(() => {});
+ let start: number | null = null;
+ const animation: Recorded = {
+ keyframes: keyframes as Keyframe[],
+ options: options as KeyframeAnimationOptions,
+ get startTime() {
+ return start;
+ },
+ set startTime(value) {
+ start = value;
+ resolveReady(animation);
+ },
+ cancelled: false,
+ get playState() {
+ return this.cancelled ? 'idle' : 'running';
+ },
+ ready,
+ cancel() {
+ this.cancelled = true;
+ rejectReady(new Error('AbortError'));
+ },
+ commit(at) {
+ if (!this.cancelled && start == null) {
+ start = at;
+ }
+ resolveReady(this);
+ },
+ };
+ recorded.push(animation);
+ return animation as unknown as Animation;
+ };
+});
+
+afterEach(() => {
+ Reflect.deleteProperty(HTMLElement.prototype, 'animate');
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ document.body.innerHTML = '';
+});
+
+/**
+ * The person's settings, through `matchMedia` as the animator reads them: no
+ * option overrides them (design:reduced-motion DR4).
+ */
+function stubMedia(reduced: boolean, coarse: boolean) {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: query.includes('prefers-reduced-motion')
+ ? reduced
+ : query.includes('pointer: coarse')
+ ? coarse
+ : false,
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ }));
+}
+
+/** Commits a frame, then moves both clocks forward by `ms`. */
+async function advance(ms: number, clock?: ManualClock) {
+ for (const animation of recorded) {
+ if (animation.startTime == null && !animation.cancelled) {
+ animation.commit(now);
+ }
+ }
+ const frames = frameQueue;
+ frameQueue = [];
+ for (const callback of frames) {
+ callback();
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ now += ms;
+ if (clock != null) {
+ clock.time = now;
+ }
+ await vi.advanceTimersByTimeAsync(ms);
+}
+
+/**
+ * A frame in WebKit's order. The browser starts new animations and resolves
+ * their start inside the frame's rendering update. That comes before this
+ * frame's animation-frame callbacks, with no task (timer) in between.
+ * `advance` runs the callbacks first.
+ */
+async function advanceInWebKitOrder(ms: number, clock?: ManualClock) {
+ for (const animation of recorded) {
+ if (animation.startTime == null && !animation.cancelled) {
+ animation.commit(now);
+ }
+ }
+ for (let i = 0; i < 20; i++) {
+ await Promise.resolve();
+ }
+ const frames = frameQueue;
+ frameQueue = [];
+ for (const callback of frames) {
+ callback();
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ now += ms;
+ if (clock != null) {
+ clock.time = now;
+ }
+ await vi.advanceTimersByTimeAsync(ms);
+}
+
+// --- Touches ----------------------------------------------------------------
+
+function touch(
+ type: 'touchstart' | 'touchmove' | 'touchend',
+ target: EventTarget,
+ x: number,
+ y: number,
+ time: number,
+): Event {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const contact = {identifier: 1, clientX: x, clientY: y, target};
+ const list = type === 'touchend' ? [] : [contact];
+ Object.defineProperty(event, 'changedTouches', {value: [contact]});
+ Object.defineProperty(event, 'touches', {value: list});
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+ return event;
+}
+
+/** A mouse event for the gesture host (jsdom has no PointerEvent). */
+function mouse(
+ type: 'pointerdown' | 'pointermove' | 'pointerup',
+ target: EventTarget,
+ x: number,
+ y: number,
+ time: number,
+): Event {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const fields: Record<string, unknown> = {
+ pointerType: 'mouse',
+ pointerId: 1,
+ isPrimary: true,
+ button: 0,
+ buttons: type === 'pointerup' ? 0 : 1,
+ clientX: x,
+ clientY: y,
+ timeStamp: time,
+ };
+ for (const [key, value] of Object.entries(fields)) {
+ Object.defineProperty(event, key, {value});
+ }
+ target.dispatchEvent(event);
+ return event;
+}
+
+/**
+ * A wheel for the gesture host: `dx`/`dy` px (or lines with `mode` 1). With
+ * no legacy `wheelDeltaX`/`wheelDeltaY` it reads as a mouse's wheel.
+ */
+function wheel(
+ target: EventTarget,
+ init: {
+ dx?: number;
+ dy?: number;
+ mode?: number;
+ time: number;
+ legacy?: {x: number; y: number};
+ },
+): WheelEvent {
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 300,
+ clientY: 100,
+ deltaX: init.dx ?? 0,
+ deltaY: init.dy ?? 0,
+ deltaMode: init.mode ?? 0,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: init.time});
+ if (init.legacy != null) {
+ Object.defineProperty(event, 'wheelDeltaX', {value: init.legacy.x});
+ Object.defineProperty(event, 'wheelDeltaY', {value: init.legacy.y});
+ }
+ target.dispatchEvent(event);
+ return event;
+}
+
+/**
+ * A trackpad's scroll: precise deltas, whose legacy `wheelDelta` Chromium and
+ * WebKit report as three times each, against the content.
+ */
+function trackpad(
+ target: EventTarget,
+ init: {dx?: number; dy?: number; time: number},
+): WheelEvent {
+ const dx = init.dx ?? 0;
+ const dy = init.dy ?? 0;
+ return wheel(target, {...init, legacy: {x: -3 * dx, y: -3 * dy}});
+}
+
+interface Fixture {
+ pager: Pager;
+ viewport: HTMLElement;
+ track: HTMLElement;
+ page: HTMLElement;
+ animator: Animator;
+ clock: ManualClock;
+ host: GestureHost;
+ calls: string[];
+ /** The track's x on screen now, from the animator. */
+ x(): number;
+}
+
+function setup(options: Partial<PagerOptions> = {}, rtl = false): Fixture {
+ const clock = new ManualClock();
+ clock.time = now;
+ const host = new GestureHost(document, {clock});
+ const viewport = document.createElement('div');
+ const track = document.createElement('div');
+ const page = document.createElement('div');
+ if (rtl) {
+ viewport.style.direction = 'rtl';
+ }
+ track.appendChild(page);
+ viewport.appendChild(track);
+ document.body.appendChild(viewport);
+ Object.defineProperty(viewport, 'clientWidth', {
+ value: WIDTH,
+ configurable: true,
+ });
+ const animator = createAnimator(track, {
+ now: () => now,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ });
+ const calls: string[] = [];
+ const pager = createPager(
+ {
+ count: 5,
+ onIndexChange: (index, reason) => calls.push(`index:${index}:${reason}`),
+ onSettle: (index, previous) => calls.push(`settle:${index}:${previous}`),
+ ...options,
+ },
+ {
+ host,
+ animator,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ },
+ );
+ pager.attach(viewport, track);
+ return {
+ pager,
+ viewport,
+ track,
+ page,
+ animator,
+ clock,
+ host,
+ calls,
+ x: () => animator.get('x', now),
+ };
+}
+
+/**
+ * A horizontal drag on the page: lands at `from`, moves `dx` in steps of
+ * `step` px every `dt` ms, optionally holds still, then lifts. Returns the
+ * lift time.
+ */
+async function drag(
+ f: Fixture,
+ {
+ from = 200,
+ dx,
+ dy = 0,
+ step = 4,
+ dt = 8,
+ hold = 0,
+ still = 0,
+ }: {
+ from?: number;
+ dx: number;
+ dy?: number;
+ step?: number;
+ dt?: number;
+ /** A silent rest before the lift: no events, ms. */
+ hold?: number;
+ /** Move samples that stand still at the end, `dt` apart, before the lift. */
+ still?: number;
+ },
+): Promise<number> {
+ const y = 100;
+ touch('touchstart', f.page, from, y, now);
+ const steps = Math.max(1, Math.round(Math.abs(dx) / step));
+ for (let i = 1; i <= steps; i++) {
+ await advance(dt, f.clock);
+ touch(
+ 'touchmove',
+ f.page,
+ from + (dx * i) / steps,
+ y + (dy * i) / steps,
+ now,
+ );
+ }
+ for (let i = 0; i < still; i++) {
+ await advance(dt, f.clock);
+ touch('touchmove', f.page, from + dx, y + dy, now);
+ }
+ if (hold > 0) {
+ await advance(hold, f.clock);
+ }
+ await advance(dt, f.clock);
+ touch('touchend', f.page, from + dx, y + dy, now);
+ return now;
+}
+
+/** Three display frames: a release's report waits for its settle to run. */
+async function frames(f: Fixture, count = 3) {
+ for (let i = 0; i < count; i++) {
+ await advance(16, f.clock);
+ }
+}
+
+async function settle(f: Fixture) {
+ for (let i = 0; i < 80 && f.pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ await advance(16, f.clock);
+}
+
+/**
+ * A trackpad fling: `count` steady deltas of `px` every 8 ms, then four
+ * shrinking ones as the fingers lift into momentum. The gesture engine
+ * releases the pan at the lift, at the fingers' travel and speed; the
+ * shrinking deltas never move it.
+ */
+async function fling(f: Fixture, px: number, count: number) {
+ const events: WheelEvent[] = [];
+ for (const dx of [
+ ...Array.from({length: count}, () => px),
+ ...[0.95, 0.9, 0.85, 0.78].map(k => k * px),
+ ]) {
+ events.push(trackpad(f.page, {dx, time: now}));
+ await advance(8, f.clock);
+ }
+ return events;
+}
+
+describe('createPager', () => {
+ it('rests on the default page', () => {
+ const f = setup({defaultIndex: 2});
+ expect(f.pager.index).toBe(2);
+ expect(f.x()).toBe(-2 * WIDTH);
+ });
+
+ it('tracks the finger 1:1 without reading layout while it moves', async () => {
+ const f = setup({defaultIndex: 1});
+ const width = vi.spyOn(f.viewport, 'clientWidth', 'get');
+ touch('touchstart', f.page, 300, 100, now);
+ for (let i = 1; i <= 10; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 300 - 6 * i, 100, now);
+ }
+ // The pan began at 10 px and dropped the threshold's travel (UIKit).
+ expect(f.pager.isDragging).toBe(true);
+ const shown = -f.x() - WIDTH;
+ expect(shown).toBeGreaterThan(40);
+ expect(shown).toBeLessThanOrEqual(60);
+ const readsWhileMoving = width.mock.calls.length;
+ for (let i = 11; i <= 20; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 300 - 6 * i, 100, now);
+ }
+ expect(width.mock.calls.length).toBe(readsWhileMoving);
+ expect(-f.x() - WIDTH - shown).toBeCloseTo(60, 6);
+ });
+
+ // A lift within 40 ms of the last move keeps the release velocity: the
+ // settle carries it.
+ it('a lift within 40 ms of the last move keeps the release velocity: the settle carries it', async () => {
+ const f = setup({defaultIndex: 1});
+ // 250 px left in 8 ms steps of about 4 px (496 px/s), then 24 ms with no
+ // events. The lift comes 32 ms after the last move.
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 24});
+ expect(f.pager.index).toBe(2);
+ const position = -f.x();
+ const velocity = (250 / Math.round(250 / 4) / 8) * 1000;
+ const carried = solvePaging({from: position, velocity, to: 2 * WIDTH});
+ const rest = solvePaging({from: position, velocity: 0, to: 2 * WIDTH});
+ await advance(16, f.clock);
+ await advance(100, f.clock);
+ expect(carried.at(0.116) - rest.at(0.116)).toBeGreaterThan(5);
+ expect(-f.x()).toBeCloseTo(carried.at(0.116), 0);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ expect(f.calls).toEqual(['index:2:drag', 'settle:2:1']);
+ });
+
+ // UIKit keeps the release velocity through a silent rest. Recorded on
+ // iOS 26.2: 600 pt/s to 25 % of a page, then up to 397 ms with no touch
+ // event, kept 0.55 to 0.61 pt/ms. The shared release filter reads 0 after
+ // 40 ms of silence instead (spec:AST-100 FR2), and the pager reads the
+ // filter.
+ it('a silent hold of more than 40 ms before the lift starts the settle at rest (spec:AST-100 FR2), where UIKit keeps the speed', async () => {
+ const f = setup({defaultIndex: 1});
+ // The same drag, then 100 ms with no events.
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ expect(f.pager.index).toBe(2);
+ const position = -f.x();
+ const rest = solvePaging({from: position, velocity: 0, to: 2 * WIDTH});
+ await advance(16, f.clock);
+ await advance(100, f.clock);
+ expect(-f.x()).toBeCloseTo(rest.at(0.116), 0);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ expect(f.calls).toEqual(['index:2:drag', 'settle:2:1']);
+ });
+
+ // A sample at the finger's last place is not motion (spec:AST-100's one
+ // filter). A finger that keeps reporting while it stands still keeps its
+ // speed until the stillness interval runs out.
+ it('move samples that stand still are not motion: a lift 32 ms after the last move keeps the release velocity', async () => {
+ const f = setup({defaultIndex: 1});
+ // The same drag, then three samples at the same place, 8 ms apart; the
+ // lift comes 8 ms later, 32 ms after the last move.
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, still: 3});
+ expect(f.pager.index).toBe(2);
+ const position = -f.x();
+ const velocity = (250 / Math.round(250 / 4) / 8) * 1000;
+ const carried = solvePaging({from: position, velocity, to: 2 * WIDTH});
+ const rest = solvePaging({from: position, velocity: 0, to: 2 * WIDTH});
+ await advance(16, f.clock);
+ await advance(100, f.clock);
+ expect(carried.at(0.116) - rest.at(0.116)).toBeGreaterThan(5);
+ expect(-f.x()).toBeCloseTo(carried.at(0.116), 0);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ });
+
+ it('a finger that stands still, still reporting, for more than 40 ms before the lift starts the settle at rest (spec:AST-100 FR2)', async () => {
+ const f = setup({defaultIndex: 1});
+ // The same drag, then six samples at the same place, 8 ms apart; the
+ // lift comes 56 ms after the last move.
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, still: 6});
+ expect(f.pager.index).toBe(2);
+ const position = -f.x();
+ const rest = solvePaging({from: position, velocity: 0, to: 2 * WIDTH});
+ await advance(16, f.clock);
+ await advance(100, f.clock);
+ expect(-f.x()).toBeCloseTo(rest.at(0.116), 0);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ });
+
+ it('reports the new page once the settle runs on the compositor, two frames after its first', async () => {
+ const f = setup({defaultIndex: 1});
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ // Chosen at the lift (index), reported once the settle is moving.
+ expect(f.pager.index).toBe(2);
+ expect(f.calls).toEqual([]);
+ await advance(16, f.clock);
+ await advance(16, f.clock);
+ expect(f.calls).toEqual([]);
+ expect(recorded.some(a => a.startTime != null && !a.cancelled)).toBe(true);
+ await advance(16, f.clock);
+ expect(f.calls).toEqual(['index:2:drag']);
+ });
+
+ // WebKit resolves an animation's start in the frame's rendering update,
+ // before that same frame's animation-frame callbacks. A count that included
+ // that frame reported the page one frame into the settle.
+ it("in WebKit's frame order the settle's start frame does not count: the page is still reported two frames after it", async () => {
+ const f = setup({defaultIndex: 1});
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ expect(f.calls).toEqual([]);
+ // The frame that starts the settle, then one more: not yet.
+ await advanceInWebKitOrder(16, f.clock);
+ expect(recorded.some(a => a.startTime != null && !a.cancelled)).toBe(true);
+ await advanceInWebKitOrder(16, f.clock);
+ expect(f.calls).toEqual([]);
+ // The second frame after the start.
+ await advanceInWebKitOrder(16, f.clock);
+ expect(f.calls).toEqual(['index:2:drag']);
+ });
+
+ it('a drag that catches the settle before the report still reports the page', async () => {
+ const f = setup({defaultIndex: 1});
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ touch('touchstart', f.page, 300, 100, now);
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 288, 100, now);
+ expect(f.pager.isDragging).toBe(true);
+ expect(f.calls).toEqual(['index:2:drag']);
+ touch('touchend', f.page, 288, 100, now + 200);
+ });
+
+ it('a release whose report is still waiting reports nothing when the pager detaches: no callback from an unmount', async () => {
+ const f = setup({defaultIndex: 1});
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ expect(f.pager.index).toBe(2);
+ expect(f.calls).toEqual([]);
+ f.pager.dispose();
+ await frames(f, 4);
+ expect(f.calls).toEqual([]);
+ });
+
+ it("a controlled move during a release's waiting report drops it: the owner's own page wins, with no callback", async () => {
+ const f = setup({defaultIndex: 1});
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ expect(f.pager.index).toBe(2);
+ f.pager.goTo(3, {reason: 'controlled'});
+ expect(f.calls).toEqual([]);
+ await settle(f);
+ expect(f.pager.index).toBe(3);
+ expect(f.calls).toEqual(['settle:3:1']);
+ });
+
+ it('released slowly before half a page, returns to the page it started on', async () => {
+ const f = setup({defaultIndex: 1});
+ // 2 px every 16 ms (125 px/s), then still.
+ await drag(f, {from: 300, dx: -150, step: 2, dt: 16, hold: 100});
+ expect(f.calls).toEqual([]);
+ await settle(f);
+ expect(f.x()).toBe(-WIDTH);
+ expect(f.calls).toEqual(['settle:1:1']);
+ });
+
+ it('a flick at the advance speed pages from a few percent', async () => {
+ const f = setup({defaultIndex: 1});
+ // 40 px in 4 events of 10 px every 16 ms: 625 px/s, no hold.
+ await drag(f, {from: 300, dx: -50, step: 10, dt: 16});
+ await frames(f);
+ expect(f.calls).toEqual(['index:2:drag']);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ });
+
+ it('a flick lifted within 40 ms of its last move pages on its speed', async () => {
+ const f = setup({defaultIndex: 1});
+ // 625 px/s to 12.5 %, then 16 ms with no events: the lift comes 32 ms
+ // after the last move.
+ await drag(f, {from: 300, dx: -50, step: 10, dt: 16, hold: 16});
+ await frames(f);
+ expect(f.calls).toEqual(['index:2:drag']);
+ });
+
+ it('a hold of more than 40 ms before the lift cancels a flick (spec:AST-100 FR2): the page stays, where UIKit still pages', async () => {
+ const f = setup({defaultIndex: 1});
+ // 625 px/s to 12.5 %, then still for 400 ms.
+ await drag(f, {from: 300, dx: -50, step: 10, dt: 16, hold: 400});
+ expect(f.pager.index).toBe(1);
+ await settle(f);
+ expect(f.x()).toBe(-WIDTH);
+ expect(f.calls).toEqual(['settle:1:1']);
+ });
+
+ it('a slow drift does not page', async () => {
+ const f = setup({defaultIndex: 1});
+ // 2 px every 16 ms: 125 px/s, under the advance speed.
+ await drag(f, {from: 300, dx: -60, step: 2, dt: 16});
+ await frames(f);
+ expect(f.calls).toEqual([]);
+ });
+
+ it('never travels more than one page from the page the drag started on', async () => {
+ const f = setup({defaultIndex: 1});
+ // 1.5 pages in one fast drag: still only the next page.
+ await drag(f, {from: 390, dx: -380, step: 12, dt: 8});
+ expect(f.pager.index).toBe(2);
+ await frames(f);
+ expect(f.calls).toEqual(['index:2:drag']);
+ });
+
+ it('rubber-bands past the first page with d = the page width', async () => {
+ const f = setup({defaultIndex: 0});
+ touch('touchstart', f.page, 100, 100, now);
+ for (let i = 1; i <= 30; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 100 + 10 * i, 100, now);
+ }
+ // 300 px of finger, 10 px of it spent on the pan's threshold.
+ const finger = 300 - 10;
+ expect(f.x()).toBeCloseTo(rubberBand(finger, WIDTH), 1);
+ await advance(8, f.clock);
+ touch('touchend', f.page, 400, 100, now);
+ await settle(f);
+ expect(f.x()).toBe(0);
+ expect(f.calls).toEqual(['settle:0:0']);
+ });
+
+ it('a writing-direction flip re-places the track at the next measure, so a drag starts from under the finger', async () => {
+ const f = setup({defaultIndex: 2});
+ expect(f.x()).toBe(-2 * WIDTH);
+ f.viewport.style.direction = 'rtl';
+ // A drag's first move measures. The page shown stays page 2, mirrored.
+ touch('touchstart', f.page, 200, 100, now);
+ for (let i = 1; i <= 4; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 200 + 4 * i, 100, now);
+ }
+ expect(f.pager.isDragging).toBe(true);
+ expect(Math.abs(f.x() - 2 * WIDTH)).toBeLessThan(20);
+ // A still lift stays on page 2.
+ for (let i = 0; i < 6; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 216, 100, now);
+ }
+ await advance(8, f.clock);
+ touch('touchend', f.page, 216, 100, now);
+ await settle(f);
+ expect(f.x()).toBe(2 * WIDTH);
+ });
+
+ it('mirrors in RTL: a drag to the right goes forward', async () => {
+ const f = setup({defaultIndex: 0}, true);
+ expect(f.x()).toBe(0);
+ await drag(f, {from: 100, dx: 250, hold: 100});
+ expect(f.pager.index).toBe(1);
+ await settle(f);
+ expect(f.x()).toBe(WIDTH);
+ expect(f.calls).toEqual(['index:1:drag', 'settle:1:0']);
+ });
+
+ it('leaves a vertical drag to the page: the pan fails', async () => {
+ const f = setup({defaultIndex: 1});
+ await drag(f, {from: 300, dx: -20, dy: 60});
+ expect(f.pager.isDragging).toBe(false);
+ expect(f.calls).toEqual([]);
+ expect(f.x()).toBe(-WIDTH);
+ });
+
+ it('asks shouldBeginPan with the initial direction', async () => {
+ const directions: string[] = [];
+ const f = setup({
+ defaultIndex: 1,
+ shouldBeginPan: direction => {
+ directions.push(direction);
+ return direction === 'right';
+ },
+ });
+ await drag(f, {from: 300, dx: -200, hold: 50});
+ expect(directions).toEqual(['left']);
+ expect(f.x()).toBe(-WIDTH);
+ await drag(f, {from: 100, dx: 250, hold: 50});
+ expect(directions).toEqual(['left', 'right']);
+ await frames(f);
+ expect(f.calls).toContain('index:0:drag');
+ });
+
+ it("goTo animates setContentOffset's curve, and fires the callbacks", async () => {
+ const f = setup({defaultIndex: 0});
+ f.pager.goTo(3);
+ expect(f.calls).toEqual(['index:3:goTo']);
+ await advance(0, f.clock);
+ const curve = solveAnimatedPageScroll({from: 0, to: 3 * WIDTH});
+ await advance(150, f.clock);
+ expect(-f.x()).toBeCloseTo(curve.at(0.15), 0);
+ await settle(f);
+ expect(f.x()).toBe(-3 * WIDTH);
+ expect(f.calls).toEqual(['index:3:goTo', 'settle:3:0']);
+ });
+
+ it('goTo without animation lands at once', () => {
+ const f = setup({defaultIndex: 0});
+ f.pager.goTo(4, {animated: false});
+ expect(f.x()).toBe(-4 * WIDTH);
+ expect(f.calls).toEqual(['index:4:goTo', 'settle:4:0']);
+ });
+
+ // spec:AST-094 FR4: a component reads touch motion through resolveMotion and
+ // plays no literal. goTo reads setContentOffset's duration and curve there.
+ // What resolveMotion returns for them is what plays. Today those are the
+ // paging table's values, as no role names them.
+ it("goTo plays the duration and curve resolveMotion gives setContentOffset's", async () => {
+ const actual = await vi.importActual<typeof motionResolution>(
+ '../motion/resolveMotion',
+ );
+ const LINEAR = [0, 0, 1, 1] as const;
+ function standIn(
+ element: Element | null | undefined,
+ leafOrGroup: object,
+ key?: string,
+ ): number | object | undefined {
+ if (leafOrGroup === paging.animatedScroll && key === 'durationMs') {
+ return 600;
+ }
+ if (leafOrGroup === paging.animatedScroll.curve) {
+ return LINEAR;
+ }
+ return (
+ actual.resolveMotion as (
+ ...args: unknown[]
+ ) => number | object | undefined
+ )(element, leafOrGroup, key);
+ }
+ vi.mocked(resolveMotion).mockImplementation(
+ standIn as typeof resolveMotion,
+ );
+ try {
+ const f = setup({defaultIndex: 0});
+ f.pager.goTo(2);
+ await advance(0, f.clock);
+ // A quarter of the way along a linear 600 ms curve at 150 ms (the
+ // table's 300 ms sinusoid would be at 50 %)…
+ await advance(150, f.clock);
+ expect(-f.x()).toBeGreaterThan(0.4 * WIDTH);
+ expect(-f.x()).toBeLessThan(0.6 * WIDTH);
+ // …halfway at 300 ms, where the table's 300 ms has landed…
+ await advance(150, f.clock);
+ expect(-f.x()).toBeGreaterThan(0.9 * WIDTH);
+ expect(-f.x()).toBeLessThan(1.1 * WIDTH);
+ // …and on the page at 600 ms.
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ } finally {
+ vi.mocked(resolveMotion).mockImplementation(actual.resolveMotion);
+ }
+ });
+
+ it('goTo during a drag cancels the drag and starts from what is on screen', async () => {
+ const f = setup({defaultIndex: 1});
+ touch('touchstart', f.page, 300, 100, now);
+ for (let i = 1; i <= 10; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 300 - 8 * i, 100, now);
+ }
+ const onScreen = -f.x();
+ f.pager.goTo(3);
+ expect(f.pager.isDragging).toBe(false);
+ expect(f.pager.pan.state).not.toBe('changed');
+ await advance(0, f.clock);
+ expect(-f.x()).toBeCloseTo(onScreen, 0);
+ // The rest of the finger's travel no longer moves the track.
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 100, 100, now);
+ await settle(f);
+ touch('touchend', f.page, 100, 100, now);
+ expect(f.x()).toBe(-3 * WIDTH);
+ expect(f.calls).toEqual(['index:3:goTo', 'settle:3:1']);
+ });
+
+ it('a drag catches a settling track at the value on screen', async () => {
+ const f = setup({defaultIndex: 1});
+ f.pager.goTo(2);
+ await advance(0, f.clock);
+ await advance(100, f.clock);
+ const onScreen = -f.x();
+ expect(onScreen).toBeGreaterThan(WIDTH);
+ expect(onScreen).toBeLessThan(2 * WIDTH);
+ touch('touchstart', f.page, 300, 100, now);
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 289, 100, now);
+ expect(f.pager.isDragging).toBe(true);
+ expect(f.pager.isSettling).toBe(false);
+ // From the caught position, 1 px past the threshold.
+ expect(-f.x()).toBeCloseTo(-f.animator.get('x', now), 6);
+ touch('touchend', f.page, 289, 100, now + 40);
+ });
+
+ it(`a still finger catches a settle ${paging.catchStopMs} ms after it lands, and the lift settles on the nearest page`, async () => {
+ const f = setup({defaultIndex: 1});
+ f.pager.goTo(2);
+ await advance(0, f.clock);
+ await advance(60, f.clock);
+ touch('touchstart', f.page, 300, 100, now);
+ await advance(40, f.clock);
+ // Still moving 40 ms after the touch.
+ expect(f.pager.isSettling).toBe(true);
+ await advance(paging.catchStopMs, f.clock);
+ expect(f.pager.isSettling).toBe(false);
+ const held = -f.x();
+ await advance(100, f.clock);
+ expect(-f.x()).toBe(held);
+ touch('touchend', f.page, 300, 100, now);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ });
+
+ it('loops: past the last page goes forward to a virtual page, wrapped for callbacks', async () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ await drag(f, {from: 300, dx: -250, hold: 50});
+ expect(f.pager.virtualIndex).toBe(5);
+ expect(f.pager.index).toBe(0);
+ await frames(f);
+ expect(f.calls).toEqual(['index:0:drag']);
+ await settle(f);
+ expect(f.x()).toBe(-5 * WIDTH);
+ // goTo takes the nearest copy: from virtual 5 (page 0), page 4 is back one.
+ f.pager.goTo(4, {animated: false});
+ expect(f.pager.virtualIndex).toBe(4);
+ });
+
+ it("with two pages, a loop's step forward goes forward: of two copies equally near, the one asked for", () => {
+ const f = setup({count: 2, loop: true});
+ f.pager.goTo(f.pager.virtualIndex + 1, {animated: false});
+ expect(f.pager.virtualIndex).toBe(1);
+ f.pager.goTo(f.pager.virtualIndex + 1, {animated: false});
+ expect(f.pager.virtualIndex).toBe(2);
+ expect(f.x()).toBe(-2 * WIDTH);
+ f.pager.goTo(f.pager.virtualIndex - 1, {animated: false});
+ expect(f.pager.virtualIndex).toBe(1);
+ // A page index takes its nearest copy as before.
+ f.pager.goTo(0, {animated: false});
+ expect(f.pager.virtualIndex).toBe(0);
+ });
+
+ it('clamps goTo to the pages when not looping', () => {
+ const f = setup({defaultIndex: 0});
+ f.pager.goTo(9, {animated: false});
+ expect(f.pager.index).toBe(4);
+ f.pager.goTo(-3, {animated: false});
+ expect(f.pager.index).toBe(0);
+ });
+
+ it('a resize mid-settle lands on the target page at its new offset', async () => {
+ let onResize: ResizeObserverCallback | null = null;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ onResize = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const f = setup({defaultIndex: 0});
+ f.pager.goTo(2);
+ await advance(0, f.clock);
+ await advance(100, f.clock);
+ expect(f.pager.isSettling).toBe(true);
+ Object.defineProperty(f.viewport, 'clientWidth', {
+ value: 300,
+ configurable: true,
+ });
+ expect(onResize).not.toBeNull();
+ onResize!(
+ [{target: f.viewport} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ expect(f.pager.isSettling).toBe(false);
+ expect(f.x()).toBe(-600);
+ expect(f.calls).toEqual(['index:2:goTo', 'settle:2:0']);
+ vi.unstubAllGlobals();
+ });
+
+ // The shared resize observer is one per module. So this case loads a fresh
+ // pager module after it installs its ResizeObserver.
+ it('a resize while a finger holds a caught settle leaves the track under the finger, and the lift settles once', async () => {
+ let onResize: ResizeObserverCallback | null = null;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ onResize = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ vi.resetModules();
+ const fresh = await import('./usePager');
+ const f = setup({defaultIndex: 0});
+ f.pager.dispose();
+ const calls: string[] = [];
+ const pager = fresh.createPager(
+ {
+ count: 5,
+ defaultIndex: 1,
+ onIndexChange: (i, reason) => calls.push(`index:${i}:${reason}`),
+ onSettle: (i, previous) => calls.push(`settle:${i}:${previous}`),
+ },
+ {
+ host: f.host,
+ animator: f.animator,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ },
+ );
+ pager.attach(f.viewport, f.track);
+ try {
+ pager.goTo(2);
+ await advance(0, f.clock);
+ await advance(60, f.clock);
+ touch('touchstart', f.page, 300, 100, now);
+ await advance(paging.catchStopMs + 40, f.clock);
+ expect(pager.isSettling).toBe(false);
+ const held = f.x();
+ calls.length = 0;
+ Object.defineProperty(f.viewport, 'clientWidth', {
+ value: 300,
+ configurable: true,
+ });
+ expect(onResize).not.toBeNull();
+ onResize!(
+ [{target: f.viewport} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ await advance(16, f.clock);
+ // The track stays under the held finger.
+ expect(f.x()).toBe(held);
+ touch('touchend', f.page, 300, 100, now);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ await advance(16, f.clock);
+ expect(f.x()).toBe(-2 * 300);
+ expect(calls.filter(call => call.startsWith('settle:'))).toEqual([
+ 'settle:2:1',
+ ]);
+ } finally {
+ pager.dispose();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ // The shared resize observer is one per module. So this case loads a fresh
+ // pager module after it installs its ResizeObserver.
+ it('a resize after a forward wrap keeps the wrapped page: no jump and no callback', async () => {
+ let onResize: ResizeObserverCallback | null = null;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ onResize = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ vi.resetModules();
+ const fresh = await import('./usePager');
+ const f = setup({defaultIndex: 0});
+ f.pager.dispose();
+ const calls: string[] = [];
+ const pager = fresh.createPager(
+ {
+ count: 5,
+ defaultIndex: 4,
+ loop: true,
+ onIndexChange: (i, reason) => calls.push(`index:${i}:${reason}`),
+ onSettle: (i, previous) => calls.push(`settle:${i}:${previous}`),
+ },
+ {host: f.host, animator: f.animator},
+ );
+ pager.attach(f.viewport, f.track);
+ try {
+ // Forward past the last page: virtual page 5, which is page 0.
+ pager.goTo(5, {animated: false});
+ await frames(f);
+ expect(pager.virtualIndex).toBe(5);
+ expect(pager.index).toBe(0);
+ calls.length = 0;
+ Object.defineProperty(f.viewport, 'clientWidth', {
+ value: 300,
+ configurable: true,
+ });
+ expect(onResize).not.toBeNull();
+ onResize!(
+ [{target: f.viewport} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ await frames(f);
+ expect(pager.virtualIndex).toBe(5);
+ expect(f.x()).toBe(-5 * 300);
+ expect(calls).toEqual([]);
+ } finally {
+ pager.dispose();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ // The shared resize observer is one per module. So this case loads a fresh
+ // pager module after it installs its ResizeObserver, and another case's
+ // observer cannot stand in for it.
+ it("observes the track once pages becomes 'children' after attach, and stops when it goes back", async () => {
+ const observed: Element[] = [];
+ const unobserved: Element[] = [];
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe(element: Element) {
+ observed.push(element);
+ }
+ unobserve(element: Element) {
+ unobserved.push(element);
+ }
+ disconnect() {}
+ },
+ );
+ vi.resetModules();
+ const fresh = await import('./usePager');
+ const f = setup({defaultIndex: 0});
+ f.pager.dispose();
+ const pager = fresh.createPager(
+ {count: 3, defaultIndex: 0},
+ {host: f.host, animator: f.animator},
+ );
+ pager.attach(f.viewport, f.track);
+ expect(observed).toContain(f.viewport);
+ expect(observed).not.toContain(f.track);
+ pager.setOptions({pages: 'children'});
+ expect(observed).toContain(f.track);
+ pager.setOptions({pages: undefined});
+ expect(unobserved).toContain(f.track);
+ pager.dispose();
+ vi.unstubAllGlobals();
+ });
+
+ it("a loop's smaller count keeps the page shown where it can: page 4 of 5 becomes page 2 of 3, reported to no one", () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ f.calls.length = 0;
+ f.pager.setOptions({count: 3});
+ expect(f.pager.index).toBe(2);
+ expect(f.x()).toBe(-2 * WIDTH);
+ expect(f.calls.filter(call => call.startsWith('index:'))).toEqual([]);
+ });
+
+ it("a release whose report still waits when a looping pager's count changes is reported first", async () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ await drag(f, {from: 300, dx: -250, hold: 50});
+ expect(f.pager.virtualIndex).toBe(5);
+ // The release's report waits for its settle to run.
+ expect(f.calls).toEqual([]);
+ f.pager.setOptions({count: 6});
+ await frames(f);
+ expect(f.pager.index).toBe(0);
+ expect(f.calls[0]).toBe('index:0:drag');
+ });
+
+ it("turning loop off while a swipe's report waits reports that page first", async () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ await drag(f, {from: 300, dx: -250, hold: 50});
+ expect(f.pager.virtualIndex).toBe(5);
+ expect(f.calls).toEqual([]);
+ f.pager.setOptions({loop: false});
+ await frames(f);
+ expect(f.pager.index).toBe(0);
+ expect(f.calls[0]).toBe('index:0:drag');
+ });
+
+ it("a loop's smaller count drops a waiting report whose page is gone, and clamps unreported", async () => {
+ const f = setup({defaultIndex: 3, loop: true});
+ await drag(f, {from: 300, dx: -250, hold: 50});
+ expect(f.pager.virtualIndex).toBe(4);
+ expect(f.calls).toEqual([]);
+ f.pager.setOptions({count: 3});
+ await frames(f);
+ expect(f.pager.index).toBe(2);
+ expect(f.calls.filter(call => call.startsWith('index:'))).toEqual([]);
+ });
+
+ it('turning loop off with a smaller count keeps the page shown by the old count: virtual page 7 stays page 2', () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ for (let i = 0; i < 3; i++) {
+ f.pager.goTo(f.pager.virtualIndex + 1, {animated: false});
+ }
+ expect(f.pager.virtualIndex).toBe(7);
+ f.pager.setOptions({loop: false, count: 3});
+ expect(f.pager.index).toBe(2);
+ expect(f.x()).toBe(-2 * WIDTH);
+ });
+
+ it("a loop's smaller count at rest on a wrapped page settles nothing: the page did not move", async () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ f.pager.goTo(f.pager.virtualIndex + 1, {animated: false});
+ expect(f.pager.virtualIndex).toBe(5);
+ await frames(f);
+ f.calls.length = 0;
+ f.pager.setOptions({count: 3});
+ await frames(f);
+ expect(f.pager.index).toBe(0);
+ expect(f.x()).toBe(0);
+ expect(f.calls.filter(call => call.startsWith('settle:'))).toEqual([]);
+ });
+
+ it('turning loop off on a wrapped page names no virtual page in onSettle', async () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ for (let i = 0; i < 3; i++) {
+ f.pager.goTo(f.pager.virtualIndex + 1, {animated: false});
+ }
+ await frames(f);
+ f.calls.length = 0;
+ f.pager.setOptions({loop: false});
+ await frames(f);
+ expect(f.pager.index).toBe(2);
+ expect(f.calls).not.toContain('settle:2:7');
+ });
+
+ it("a loop's smaller count that clamps the page settles from the page shown, as a pager that does not loop", async () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ await frames(f);
+ f.calls.length = 0;
+ f.pager.setOptions({count: 3});
+ await frames(f);
+ expect(f.calls).toEqual(['settle:2:4']);
+ });
+
+ it('turning loop on with a smaller count clamps the page shown: page 4 of 5 becomes page 2 of 3', async () => {
+ const f = setup({defaultIndex: 4});
+ await frames(f);
+ f.calls.length = 0;
+ f.pager.setOptions({loop: true, count: 3});
+ expect(f.pager.index).toBe(2);
+ expect(f.x()).toBe(-2 * WIDTH);
+ await frames(f);
+ expect(f.calls).toEqual(['settle:2:4']);
+ });
+
+ it("a loop's count change after a forward wrap keeps the page shown: virtual page 7 (page 2) stays page 2", () => {
+ const f = setup({defaultIndex: 4, loop: true});
+ for (let i = 0; i < 3; i++) {
+ f.pager.goTo(f.pager.virtualIndex + 1, {animated: false});
+ }
+ expect(f.pager.virtualIndex).toBe(7);
+ f.calls.length = 0;
+ f.pager.setOptions({count: 3});
+ expect(f.pager.index).toBe(2);
+ expect(f.x()).toBe(-2 * WIDTH);
+ expect(f.calls.filter(call => call.startsWith('index:'))).toEqual([]);
+ });
+
+ it('a smaller count clamps the target page', () => {
+ const f = setup({defaultIndex: 4});
+ f.pager.setOptions({count: 2});
+ expect(f.pager.index).toBe(1);
+ });
+
+ // Touch motion stays internal: the paging values are constants, so no
+ // `--motion-paging-…` variable changes a settle or a goTo.
+ it('a --motion-paging-… variable changes neither the settle nor goTo', async () => {
+ const plain = setup({defaultIndex: 1});
+ await drag(plain, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ await advance(16, plain.clock);
+ await advance(150, plain.clock);
+ const integrator = plain.x();
+
+ const f = setup({defaultIndex: 1});
+ const scope = document.createElement('div');
+ scope.setAttribute('data-astryx-theme', 'paging-test');
+ scope.style.setProperty(
+ '--motion-paging-settle',
+ 'spring(response 1.2s, damping-ratio 1)',
+ );
+ scope.style.setProperty(
+ '--motion-paging-animated-scroll-duration-ms',
+ '600ms',
+ );
+ scope.style.setProperty(
+ '--motion-paging-animated-scroll-curve',
+ 'cubic-bezier(0, 0, 1, 1)',
+ );
+ document.body.appendChild(scope);
+ scope.appendChild(f.viewport);
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ await advance(16, f.clock);
+ await advance(150, f.clock);
+ expect(f.x()).toBe(integrator);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+
+ // goTo plays the table's 300 ms: landed at 300 ms, not halfway.
+ f.pager.goTo(3);
+ await advance(0, f.clock);
+ await advance(300, f.clock);
+ await advance(16, f.clock);
+ expect(f.x()).toBe(-3 * WIDTH);
+ scope.remove();
+ });
+
+ // design:reduced-motion: after the finger lifts, nothing travels. A
+ // finger's release settles with a cross-fade of at most 200 ms on any
+ // pointer (DR2). A mouse's, a trackpad's or a pen's release follows DR2 on a
+ // coarse primary pointer, and DR3 otherwise (spec:AST-094 FR43). A goTo
+ // cross-fades on a coarse pointer (DR2) and lands at once on any other
+ // (DR3). The drag itself follows the pointer.
+ function reducedPager(f: Fixture, defaultIndex: number, coarse: boolean) {
+ stubMedia(true, coarse);
+ const reduced = createAnimator(f.track, {
+ now: () => now,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ });
+ f.pager.dispose();
+ const pager = createPager(
+ {count: 3, defaultIndex},
+ {host: f.host, animator: reduced},
+ );
+ pager.attach(f.viewport, f.track);
+ return {pager, reduced};
+ }
+
+ /**
+ * Animations started after `from` that move the track through values in
+ * between (a cross-fade's jump holds the start, then the end: two values).
+ */
+ function travelsSince(from: number) {
+ return recorded.slice(from).filter(a => {
+ const xs = new Set<string>();
+ for (const k of a.keyframes as Record<string, unknown>[]) {
+ const v = k.translate ?? k.transform;
+ if (typeof v === 'string') {
+ xs.add(v);
+ }
+ }
+ return xs.size > 2;
+ });
+ }
+
+ /**
+ * How long `property` keeps changing. The animator compiles a long animation
+ * that holds its last value. So this is the offset of the first keyframe
+ * that stays at the end value, times the duration.
+ */
+ function activeMs(animation: Recorded, property: string): number {
+ const frames = animation.keyframes as Record<string, unknown>[];
+ const values = frames.map(k => {
+ const v = k[property];
+ return typeof v === 'string' || typeof v === 'number' ? String(v) : '';
+ });
+ const end = values[values.length - 1];
+ let i = values.length - 1;
+ while (i > 0 && values[i - 1] === end) {
+ i--;
+ }
+ const offset = Number(
+ frames[i]?.offset ?? i / Math.max(1, frames.length - 1),
+ );
+ return offset * Number(animation.options.duration ?? 0);
+ }
+
+ function fadesSince(from: number) {
+ return recorded
+ .slice(from)
+ .filter(a =>
+ a.keyframes.some(k => (k as Record<string, unknown>).opacity != null),
+ );
+ }
+
+ it('under Reduce Motion, a release settle does not travel: an opacity cross-fade of at most 200 ms on a coarse pointer (a touch release, DR2)', async () => {
+ const f = setup({defaultIndex: 1});
+ const {pager, reduced} = reducedPager(f, 1, true);
+ // The pointer this case claims, as the animator sees it.
+ expect(reduced.reducedMotion()).toBe('crossfade');
+ expect(reduced.reducedMotion({touchRelease: true})).toBe('crossfade');
+ const before = recorded.length;
+ await drag(
+ {...f, pager, animator: reduced, x: () => reduced.get('x', now)},
+ {from: 300, dx: -250, step: 4, dt: 8, hold: 100},
+ );
+ await frames(f, 40);
+ // The drag itself writes the track (no animation); every animation is
+ // the settle's.
+ expect(travelsSince(before)).toEqual([]);
+ const fades = fadesSince(before);
+ expect(fades.length).toBeGreaterThan(0);
+ for (const fade of fades) {
+ expect(activeMs(fade, 'opacity')).toBeLessThanOrEqual(200);
+ }
+ expect(-reduced.get('x', now)).toBeCloseTo(2 * WIDTH, 0);
+ });
+
+ // spec:AST-094 FR43: under reduced motion a release from a mouse, a
+ // trackpad, or a pen follows DR2 on a coarse primary pointer and DR3
+ // otherwise.
+ for (const coarse of [false, true]) {
+ it(`under Reduce Motion, a mouse drag's release follows the primary pointer (spec:AST-094 FR43): ${coarse ? 'coarse, an opacity cross-fade of at most 200 ms (DR2)' : 'fine, at once with no cross-fade (DR3)'}`, async () => {
+ const f = setup({defaultIndex: 1});
+ const {pager, reduced} = reducedPager(f, 1, coarse);
+ const before = recorded.length;
+ mouse('pointerdown', f.page, 300, 100, now);
+ for (let i = 1; i <= 62; i++) {
+ await advance(8, f.clock);
+ mouse('pointermove', f.page, 300 - 4 * i, 100, now);
+ }
+ await advance(8, f.clock);
+ mouse('pointerup', f.page, 52, 100, now);
+ await frames(f, 40);
+ expect(pager.index).toBe(2);
+ expect(travelsSince(before)).toEqual([]);
+ const fades = fadesSince(before);
+ if (coarse) {
+ expect(fades.length).toBeGreaterThan(0);
+ for (const fade of fades) {
+ expect(activeMs(fade, 'opacity')).toBeLessThanOrEqual(200);
+ }
+ } else {
+ expect(fades).toEqual([]);
+ }
+ expect(-reduced.get('x', now)).toBeCloseTo(2 * WIDTH, 0);
+ });
+ }
+
+ it("under Reduce Motion on a fine primary pointer, a trackpad scroll's release lands at once (spec:AST-094 FR43, DR3)", async () => {
+ const f = setup({defaultIndex: 1});
+ const {pager, reduced} = reducedPager(f, 1, false);
+ const before = recorded.length;
+ // A fling: the fingers' lift releases it with their speed.
+ await fling(f, 6.5, 12);
+ await frames(f, 40);
+ expect(pager.index).toBe(2);
+ expect(travelsSince(before)).toEqual([]);
+ expect(fadesSince(before)).toEqual([]);
+ expect(-reduced.get('x', now)).toBeCloseTo(2 * WIDTH, 0);
+ // The momentum's stream ends 220 ms after its last wheel.
+ await advance(240, f.clock);
+ f.clock.runDue(now);
+ });
+
+ for (const coarse of [true, false]) {
+ it(`under Reduce Motion, goTo does not travel (${coarse ? 'coarse pointer: an opacity cross-fade of at most 200 ms, DR2' : 'fine pointer: at once, DR3'})`, async () => {
+ const f = setup({defaultIndex: 0});
+ const {pager, reduced} = reducedPager(f, 0, coarse);
+ // The pointer this case claims, as the animator sees it.
+ expect(reduced.reducedMotion()).toBe(coarse ? 'crossfade' : 'instant');
+ const before = recorded.length;
+ pager.goTo(1);
+ await frames(f, 30);
+ expect(travelsSince(before)).toEqual([]);
+ const fades = fadesSince(before);
+ if (coarse) {
+ expect(fades.length).toBeGreaterThan(0);
+ for (const fade of fades) {
+ expect(activeMs(fade, 'opacity')).toBeLessThanOrEqual(200);
+ }
+ } else {
+ expect(fades).toEqual([]);
+ }
+ expect(-reduced.get('x', now)).toBeCloseTo(WIDTH, 0);
+ });
+ }
+
+ // spec:AST-094 FR43: gestures work for every pointer. A mouse drags the
+ // pager as a finger does.
+ it('on a fine primary pointer a mouse drag pages the pager like a finger (spec:AST-094 FR43)', async () => {
+ const f = setup({defaultIndex: 1});
+ stubMedia(false, false);
+ f.pager.dispose();
+ const pager = createPager(
+ {count: 3, defaultIndex: 1},
+ {host: f.host, animator: f.animator},
+ );
+ pager.attach(f.viewport, f.track);
+ mouse('pointerdown', f.page, 300, 100, now);
+ for (let i = 1; i <= 62; i++) {
+ await advance(8, f.clock);
+ mouse('pointermove', f.page, 300 - 4 * i, 100, now);
+ }
+ await advance(8, f.clock);
+ mouse('pointerup', f.page, 52, 100, now);
+ await frames(f, 2);
+ // 500 px/s at the lift, past the advance speed: the next page.
+ expect(pager.index).toBe(2);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ expect(f.x()).toBe(-2 * WIDTH);
+ pager.dispose();
+ });
+
+ // spec:AST-094 FR43: on the web a pan also takes wheel and trackpad
+ // scrolling, along its own axis.
+ async function wheelPager(
+ defaultIndex: number,
+ width = WIDTH,
+ options: Partial<PagerOptions> = {},
+ ) {
+ const f = setup({defaultIndex});
+ stubMedia(false, false);
+ f.pager.dispose();
+ Object.defineProperty(f.viewport, 'clientWidth', {
+ value: width,
+ configurable: true,
+ });
+ const pager = createPager(
+ {count: 3, defaultIndex, ...options},
+ {host: f.host, animator: f.animator},
+ );
+ pager.attach(f.viewport, f.track);
+ return {f, pager};
+ }
+
+ async function endWheel(f: Fixture) {
+ // A trackpad swipe ends 220 ms after its last wheel, a mouse wheel's
+ // notches 100 ms after theirs, both still: position alone decides.
+ await advance(240, f.clock);
+ f.clock.runDue(now);
+ await frames(f, 2);
+ }
+
+ // Each wheel case disposes its pager even when an assertion fails, so a
+ // wheel gesture it left live can never take the next case's wheels.
+ it("takes a trackpad's horizontal scroll as a drag (spec:AST-094 FR43): the content follows it, and a fling releases it where the fingers lift, at their speed", async () => {
+ const {f, pager} = await wheelPager(1);
+ try {
+ const events: WheelEvent[] = [];
+ // 6.5 px every 8 ms (about 810 px/s), a trackpad's continuous scroll.
+ for (let i = 0; i < 12; i++) {
+ events.push(trackpad(f.page, {dx: 6.5, time: now}));
+ await advance(8, f.clock);
+ }
+ expect(events.every(event => event.defaultPrevented)).toBe(true);
+ expect(pager.isDragging).toBe(true);
+ // A scroll toward later content drags the track toward its start.
+ expect(f.x()).toBeLessThan(-WIDTH);
+ // The fingers lift: 78 px at about 810 px/s, a flick to the next page.
+ const lift = await fling(f, 6.5, 0);
+ expect(lift.every(event => event.defaultPrevented)).toBe(true);
+ await frames(f, 2);
+ expect(pager.index).toBe(2);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ expect(f.x()).toBe(-2 * WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // spec:AST-094 FR43, DEC-24: a pan whose stream stops releases still.
+ it('a slow 60 px trackpad swipe that stops releases still and returns to its page', async () => {
+ const {f, pager} = await wheelPager(1);
+ try {
+ // 2 px every 20 ms, 60 px in all (50 past the pan's 10 px start),
+ // then the fingers rest.
+ let furthest = -WIDTH;
+ for (let i = 0; i < 30; i++) {
+ trackpad(f.page, {dx: 2, time: now});
+ await advance(20, f.clock);
+ furthest = Math.min(furthest, f.x());
+ }
+ expect(furthest).toBeCloseTo(-WIDTH - 50, 6);
+ await endWheel(f);
+ expect(pager.index).toBe(1);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ await advance(16, f.clock);
+ expect(f.x()).toBe(-WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // spec:AST-094 FR43, DEC-24: a pan follows a trackpad's scroll and never a
+ // mouse wheel's.
+ it("leaves a mouse wheel's notches to the page: the pager follows a trackpad's scroll only", async () => {
+ const {f, pager} = await wheelPager(1);
+ try {
+ // Whole 100 px notches on the horizontal axis (a tilt wheel, or Shift
+ // with a wheel): discrete scrolling, which the pager does not take.
+ const notches: WheelEvent[] = [];
+ for (let i = 0; i < 3; i++) {
+ notches.push(wheel(f.page, {dx: 100, time: now}));
+ await advance(30, f.clock);
+ }
+ await endWheel(f);
+ expect(notches.some(event => event.defaultPrevented)).toBe(false);
+ expect(pager.isDragging).toBe(false);
+ expect(pager.index).toBe(1);
+ expect(f.x()).toBe(-WIDTH);
+ // A trackpad's continuous scroll over the same pager still drags it.
+ const scroll: WheelEvent[] = [];
+ for (let i = 0; i < 6; i++) {
+ scroll.push(trackpad(f.page, {dx: 6.5, time: now}));
+ await advance(8, f.clock);
+ }
+ expect(scroll.every(event => event.defaultPrevented)).toBe(true);
+ expect(pager.isDragging).toBe(true);
+ expect(f.x()).toBeLessThan(-WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // A scroll without the trackpad's signature is a mouse wheel's (FR43):
+ // lines, a whole tick, and deltas with an accelerated mouse's remainder.
+ for (const [name, init] of [
+ ['lines', {dx: 3, mode: 1}],
+ ['ticks: 40 px under a 120 legacy tick', {dx: 40, legacy: {x: -120, y: 0}}],
+ [
+ "accelerated deltas: a hair off whole pixels, under a trackpad's legacy delta",
+ {dx: 12.004, legacy: {x: -36.012, y: 0}},
+ ],
+ ] as const) {
+ it(`leaves a mouse wheel's ${name} to the page`, async () => {
+ const {f, pager} = await wheelPager(1);
+ try {
+ const events: WheelEvent[] = [];
+ for (let i = 0; i < 3; i++) {
+ events.push(wheel(f.page, {...init, time: now}));
+ await advance(30, f.clock);
+ }
+ await endWheel(f);
+ expect(events.some(event => event.defaultPrevented)).toBe(false);
+ expect(pager.index).toBe(1);
+ expect(f.x()).toBe(-WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+ }
+
+ // A mouse drags as a finger does (FR43): a short fast drag pages, as a
+ // finger's flick does.
+ it("a mouse's short fast drag pages, as a finger's flick does", async () => {
+ const {f, pager} = await wheelPager(1);
+ try {
+ mouse('pointerdown', f.page, 300, 100, now);
+ // 10 px every 8 ms (1,250 px/s), 30 px in all.
+ for (let i = 1; i <= 3; i++) {
+ await advance(8, f.clock);
+ mouse('pointermove', f.page, 300 - 10 * i, 100, now);
+ }
+ await advance(8, f.clock);
+ mouse('pointerup', f.page, 270, 100, now);
+ await frames(f, 2);
+ expect(pager.index).toBe(2);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // spec:AST-094 FR43, DEC-24: a pager follows a trackpad swipe at most one
+ // page from where it began, rubber-banded at its first and last page. It
+ // commits past half a page or on a flick. A speed spike that moved it under
+ // a tenth of a page is not a flick. A swipe that lands during a settle
+ // starts from that settle's page.
+ it('a trackpad scroll never carries the track more than one page from the page it began on, and lands on that page', async () => {
+ const {f, pager} = await wheelPager(0);
+ try {
+ // 25 px every 8 ms, 1,000 px in all: two and a half pages.
+ let furthest = 0;
+ for (let i = 0; i < 40; i++) {
+ trackpad(f.page, {dx: 25, time: now});
+ await advance(8, f.clock);
+ furthest = Math.min(furthest, f.x());
+ }
+ // The track reaches the next page and stops there.
+ expect(furthest).toBeGreaterThanOrEqual(-WIDTH - 0.5);
+ expect(furthest).toBeLessThanOrEqual(-WIDTH + 0.5);
+ await endWheel(f);
+ expect(pager.index).toBe(1);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // A looping pager has no first or last page. The cap holds across the loop
+ // too, from the last page onto the copy of the first.
+ it('in a looping pager, a trackpad scroll never carries the track more than one page from the page it began on, and lands on that page', async () => {
+ const {f, pager} = await wheelPager(2, WIDTH, {loop: true});
+ try {
+ // 25 px every 8 ms, 1,000 px in all, from the last page forward.
+ let furthest = 0;
+ for (let i = 0; i < 40; i++) {
+ trackpad(f.page, {dx: 25, time: now});
+ await advance(8, f.clock);
+ furthest = Math.min(furthest, f.x());
+ }
+ // The track reaches the copy of page 0 past the last page, and stops.
+ expect(furthest).toBeGreaterThanOrEqual(-3 * WIDTH - 0.5);
+ expect(furthest).toBeLessThanOrEqual(-3 * WIDTH + 0.5);
+ await endWheel(f);
+ expect(pager.virtualIndex).toBe(3);
+ expect(pager.index).toBe(0);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // A trackpad swipe that moved the pager under a tenth of a page releases
+ // still, at any speed: a speed spike is not a flick. A finger's or a
+ // mouse's flick still pages from a few percent (above).
+ it('a 42 px trackpad spike on a 480 px page releases still, whatever its speed', async () => {
+ const width = 480;
+ const {f, pager} = await wheelPager(1, width);
+ try {
+ // 7.5 px every 8 ms, then the fingers lift. The pan moves at their
+ // speed, about 940 px/s (past the advance speed), until the lift is
+ // read. It releases there with that speed. It moved the track 42 px:
+ // more than a tenth of a 400 px page, less than a tenth of this one.
+ let moved = 0;
+ for (const dx of [7.5, 7.5, 7.5, 7.125, 6.75, 6.375, 6]) {
+ trackpad(f.page, {dx, time: now});
+ // Read before any frame runs: the last read is where it released.
+ moved = Math.max(moved, -width - f.x());
+ await advance(8, f.clock);
+ }
+ expect(moved).toBeGreaterThan(40);
+ expect(moved).toBeLessThan(48);
+ await frames(f, 2);
+ expect(pager.index).toBe(1);
+ // As settle() waits: the rest lands on the frame after the settle.
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ await advance(16, f.clock);
+ expect(f.x()).toBe(-width);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // The tenth is of the swipe's own pages. On 150 px children pages 10 px
+ // apart, a tenth of a page is 16 px, under a tenth of the 400 px viewport.
+ it('a trackpad swipe is measured in its own pages: a fast swipe past a tenth of a 150 px child pages on', async () => {
+ const f = setupChildren([150, 150, 150, 150, 150], 10);
+ stubMedia(false, false);
+ try {
+ // 6 px every 8 ms, then the fingers lift: about 750 px/s. It moved the
+ // track more than a tenth of a child's page, but less than a tenth of
+ // the viewport. So it keeps its speed and pages.
+ let moved = 0;
+ for (const dx of [6, 6, 6, 5.7, 5.4, 5.1, 4.8]) {
+ trackpad(f.page, {dx, time: now});
+ // Read before any frame runs: the last read is where it released.
+ moved = Math.max(moved, -f.x());
+ await advance(8, f.clock);
+ }
+ expect(moved).toBeGreaterThan(16);
+ expect(moved).toBeLessThan(40);
+ await frames(f, 2);
+ expect(f.pager.index).toBe(1);
+ // As settle() waits: the rest lands on the frame after the settle.
+ for (let i = 0; i < 80 && f.pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ await advance(16, f.clock);
+ expect(f.x()).toBe(-160);
+ } finally {
+ f.pager.dispose();
+ }
+ });
+
+ it("a trackpad swipe that lands while the last swipe's settle runs starts from that settle's page: back-to-back swipes page on", async () => {
+ const {f, pager} = await wheelPager(0);
+ try {
+ // The first swipe: 78 px at about 810 px/s, then the fingers lift: a
+ // flick to page 1, settling from the lift.
+ await fling(f, 6.5, 12);
+ await frames(f, 2);
+ expect(pager.index).toBe(1);
+ expect(pager.isSettling).toBe(true);
+ // At once, early in that settle and nearer page 0 than page 1, a
+ // second swipe of 600 px. Its first delta grows against the lift's
+ // decay, which momentum never does, so it is a new swipe. From page 1
+ // it may reach page 2, and lands there.
+ expect(f.x()).toBeGreaterThan(-WIDTH / 2);
+ for (let i = 0; i < 50; i++) {
+ trackpad(f.page, {dx: 12, time: now});
+ await advance(8, f.clock);
+ }
+ await endWheel(f);
+ expect(pager.index).toBe(2);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ expect(f.x()).toBe(-2 * WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // A swipe catches a moving track at the value on screen.
+ it('a trackpad swipe that lands during a goTo across pages catches the track where it is shown: no jump toward the target', async () => {
+ const {f, pager} = await wheelPager(0, WIDTH, {count: 5});
+ try {
+ pager.goTo(4);
+ // Part way through the animated scroll, between pages 1 and 2.
+ for (let i = 0; i < 40 && -f.x() < 1.3 * WIDTH; i++) {
+ await advance(8, f.clock);
+ }
+ const shown = -f.x();
+ expect(pager.isSettling).toBe(true);
+ expect(shown).toBeGreaterThan(WIDTH);
+ expect(shown).toBeLessThan(2 * WIDTH);
+ // 15 px of trackpad scroll. The track follows from where it is shown,
+ // not from within a page of the target (page 3 is at 1,200 px).
+ let farthest = shown;
+ for (const dx of [5, 5, 5]) {
+ trackpad(f.page, {dx, time: now});
+ farthest = Math.max(farthest, -f.x());
+ await advance(8, f.clock);
+ farthest = Math.max(farthest, -f.x());
+ }
+ expect(pager.isDragging).toBe(true);
+ expect(farthest).toBeLessThan(shown + 200);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ // A speed spike that moves the track less than a tenth of a page from the
+ // swipe's start does not change the page.
+ it('a backward trackpad spike late in a goTo settle releases still: it does not page back', async () => {
+ const {f, pager} = await wheelPager(0);
+ try {
+ pager.goTo(1);
+ for (let i = 0; i < 30 && -f.x() < 0.8 * WIDTH; i++) {
+ await advance(8, f.clock);
+ }
+ expect(pager.isSettling).toBe(true);
+ expect(-f.x()).toBeGreaterThan(0.5 * WIDTH);
+ // 6 px back every 8 ms, about 750 px/s, then the fingers lift: under a
+ // tenth of a page from where the swipe began.
+ const began = -f.x();
+ let moved = 0;
+ for (const dx of [-6, -6, -6, -5.7, -5.4, -5.1, -4.8]) {
+ trackpad(f.page, {dx, time: now});
+ // Read before any frame runs: the last read is where it released.
+ moved = Math.max(moved, began - -f.x());
+ await advance(8, f.clock);
+ }
+ expect(moved).toBeGreaterThan(10);
+ expect(moved).toBeLessThan(0.1 * WIDTH);
+ await frames(f, 2);
+ expect(pager.index).toBe(1);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ expect(f.x()).toBe(-WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ it('a backward trackpad swipe during a goTo across pages follows the fingers and lands from where it began', async () => {
+ const {f, pager} = await wheelPager(0, WIDTH, {count: 5});
+ try {
+ pager.goTo(4);
+ // Part way through the animated scroll, between pages 1 and 2.
+ for (let i = 0; i < 40 && -f.x() < 1.3 * WIDTH; i++) {
+ await advance(8, f.clock);
+ }
+ expect(pager.isSettling).toBe(true);
+ // A slow swipe of 150 px back. The track follows it toward page 1 from
+ // where the swipe caught it.
+ const positions: number[] = [];
+ for (let i = 0; i < 30; i++) {
+ trackpad(f.page, {dx: -5, time: now});
+ positions.push(-f.x());
+ await advance(16, f.clock);
+ }
+ const caught = Math.max(...positions);
+ expect(caught - positions[positions.length - 1]).toBeGreaterThan(100);
+ await endWheel(f);
+ expect(pager.index).toBe(1);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ expect(f.x()).toBe(-WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ it("a trackpad swipe during a mouse release's settle starts from the page on screen: it moves at most one page from there", async () => {
+ const {f, pager} = await wheelPager(0, WIDTH, {count: 5});
+ try {
+ // A mouse flick toward page 1.
+ mouse('pointerdown', f.page, 300, 100, now);
+ for (let i = 1; i <= 6; i++) {
+ await advance(8, f.clock);
+ mouse('pointermove', f.page, 300 - 12 * i, 100, now);
+ }
+ await advance(8, f.clock);
+ mouse('pointerup', f.page, 228, 100, now);
+ await advance(0, f.clock);
+ expect(pager.index).toBe(1);
+ expect(pager.isSettling).toBe(true);
+ // Early in that settle, a trackpad swipe of 600 px forward.
+ let farthest = -f.x();
+ for (let i = 0; i < 40; i++) {
+ trackpad(f.page, {dx: 15, time: now});
+ farthest = Math.max(farthest, -f.x());
+ await advance(8, f.clock);
+ }
+ // From page 0 on screen, the swipe reaches page 1 at most.
+ expect(farthest).toBeLessThanOrEqual(WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+
+ it('leaves a vertical wheel over the pager to the page (spec:AST-094 FR43)', async () => {
+ const {f, pager} = await wheelPager(1);
+ try {
+ const events: WheelEvent[] = [];
+ for (let i = 0; i < 6; i++) {
+ events.push(wheel(f.page, {dy: 12.5, time: now}));
+ await advance(8, f.clock);
+ }
+ await endWheel(f);
+ expect(events.some(event => event.defaultPrevented)).toBe(false);
+ expect(pager.isDragging).toBe(false);
+ expect(pager.index).toBe(1);
+ expect(f.x()).toBe(-WIDTH);
+ } finally {
+ pager.dispose();
+ }
+ });
+});
+
+/** A rect for jsdom, which lays nothing out. */
+function rectOf(left: number, width: number): DOMRect {
+ return new DOMRect(left, 0, width, 100);
+}
+
+/**
+ * A pager whose pages are the track's children (`pages: 'children'`). The
+ * children are `gap` px apart, laid out from the start edge of a WIDTH-wide
+ * viewport, the right edge in RTL.
+ */
+function setupChildren(
+ widths: number[],
+ gap: number,
+ options: Partial<PagerOptions> = {},
+ rtl = false,
+): Fixture {
+ const clock = new ManualClock();
+ clock.time = now;
+ const host = new GestureHost(document, {clock});
+ const viewport = document.createElement('div');
+ const track = document.createElement('div');
+ if (rtl) {
+ viewport.style.direction = 'rtl';
+ }
+ let start = 0;
+ for (const width of widths) {
+ const child = document.createElement('div');
+ const from = start;
+ child.getBoundingClientRect = () =>
+ rtl ? rectOf(WIDTH - from - width, width) : rectOf(from, width);
+ track.appendChild(child);
+ start += width + gap;
+ }
+ const extent = start - gap;
+ track.getBoundingClientRect = () =>
+ rtl ? rectOf(WIDTH - extent, extent) : rectOf(0, extent);
+ viewport.appendChild(track);
+ document.body.appendChild(viewport);
+ Object.defineProperty(viewport, 'clientWidth', {
+ value: WIDTH,
+ configurable: true,
+ });
+ const animator = createAnimator(track, {
+ now: () => now,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ });
+ const calls: string[] = [];
+ const pager = createPager(
+ {
+ count: widths.length,
+ pages: 'children',
+ onIndexChange: (index, reason) => calls.push(`index:${index}:${reason}`),
+ onSettle: (index, previous) => calls.push(`settle:${index}:${previous}`),
+ ...options,
+ },
+ {
+ host,
+ animator,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ },
+ );
+ pager.attach(viewport, track);
+ return {
+ pager,
+ viewport,
+ track,
+ page: track.children[0] as HTMLElement,
+ animator,
+ clock,
+ host,
+ calls,
+ x: () => animator.get('x', now),
+ };
+}
+
+describe("children pages: each child's start edge, as a snap container places it", () => {
+ // Five 150 px children 10 px apart in a 400 px viewport start at 0, 160,
+ // 320, 480 and 640. The track ends at 790, so its end meets the viewport's
+ // end at 390, where the last two children rest.
+ const CARDS = [150, 150, 150, 150, 150];
+
+ it("measures one page per child start, the last children sharing the page where the track's end meets the viewport's", () => {
+ const f = setupChildren(CARDS, 10);
+ expect(f.pager.pageCount).toBe(4);
+ f.pager.goTo(2, {animated: false});
+ expect(f.x()).toBe(-320);
+ f.pager.goTo(4, {animated: false});
+ expect(f.pager.index).toBe(3);
+ expect(f.x()).toBe(-390);
+ });
+
+ it('a flick moves one child, on the paging settle', async () => {
+ const f = setupChildren(CARDS, 10);
+ // 625 px/s, lifted 32 ms after the last move.
+ await drag(f, {from: 300, dx: -50, step: 10, dt: 16, hold: 16});
+ expect(f.pager.index).toBe(1);
+ await settle(f);
+ expect(f.x()).toBe(-160);
+ expect(f.calls).toEqual(['index:1:drag', 'settle:1:0']);
+ });
+
+ it('a slow drag past half the way to the next child settles there; short of half, back', async () => {
+ const f = setupChildren(CARDS, 10);
+ // The finger moves 100 px. Past the pan's 10 pt claim, the content
+ // travels 90 px, past half of the 160 px to the next child.
+ await drag(f, {from: 300, dx: -100, step: 2, dt: 16, hold: 100});
+ await settle(f);
+ expect(f.pager.index).toBe(1);
+ expect(f.x()).toBe(-160);
+ // 70 px of the 160 px back toward the first child: short of half.
+ await drag(f, {from: 100, dx: 70, step: 2, dt: 16, hold: 100});
+ await settle(f);
+ expect(f.pager.index).toBe(1);
+ expect(f.x()).toBe(-160);
+ });
+
+ it('past the last page the track rubber-bands and returns: children pages never loop', async () => {
+ const f = setupChildren(CARDS, 10, {loop: true});
+ f.pager.goTo(3, {animated: false});
+ await drag(f, {from: 300, dx: -100, step: 10, dt: 16, hold: 16});
+ expect(f.pager.index).toBe(3);
+ await settle(f);
+ expect(f.x()).toBe(-390);
+ f.pager.goTo(-1, {animated: false});
+ expect(f.pager.index).toBe(0);
+ });
+
+ it('content that fits is one page: nothing pages', async () => {
+ const f = setupChildren([150, 150], 10);
+ expect(f.pager.pageCount).toBe(1);
+ await drag(f, {from: 300, dx: -50, step: 10, dt: 16, hold: 16});
+ await settle(f);
+ expect(f.pager.index).toBe(0);
+ expect(f.x()).toBe(0);
+ });
+
+ it('reads where each page rests and the page nearest an offset', () => {
+ const f = setupChildren(CARDS, 10);
+ expect([0, 1, 2, 3].map(i => f.pager.pageOffset(i))).toEqual([
+ 0, 160, 320, 390,
+ ]);
+ expect(f.pager.nearestPage(70)).toBe(0);
+ expect(f.pager.nearestPage(90)).toBe(1);
+ expect(f.pager.nearestPage(370)).toBe(3);
+ expect(f.pager.nearestPage(5000)).toBe(3);
+ });
+
+ it('a child added to the track is measured on the next options change, and reported from the next frame', async () => {
+ const pages: number[] = [];
+ const f = setupChildren(CARDS, 10, {
+ onPagesChange: pageCount => pages.push(pageCount),
+ });
+ const child = document.createElement('div');
+ child.getBoundingClientRect = () => rectOf(800, 150);
+ f.track.appendChild(child);
+ f.track.getBoundingClientRect = () => rectOf(0, 950);
+ f.pager.setOptions({count: 6});
+ expect(f.pager.pageCount).toBe(5);
+ expect(pages).toEqual([]);
+ await advance(16, f.clock);
+ expect(pages).toEqual([5]);
+ });
+
+ it("under a CSS zoom the rects are scaled; the pages are measured in the track's own pixels", () => {
+ const f = setupChildren(CARDS, 10);
+ // Rects at twice the size, as an ancestor's \`zoom: 2\` reports them;
+ // the track's own width stays 790 CSS px.
+ const children = Array.from(f.track.children) as HTMLElement[];
+ children.forEach((child, i) => {
+ child.getBoundingClientRect = () => rectOf(2 * i * 160, 2 * 150);
+ });
+ f.track.getBoundingClientRect = () => rectOf(0, 2 * 790);
+ f.track.style.width = '790px';
+ f.pager.setOptions({count: 5});
+ expect([0, 1, 2, 3].map(i => f.pager.pageOffset(i))).toEqual([
+ 0, 160, 320, 390,
+ ]);
+ });
+
+ it('RTL: pages measure from the right edge, and a drag right goes forward', async () => {
+ const f = setupChildren(CARDS, 10, {}, true);
+ expect(f.pager.pageCount).toBe(4);
+ await drag(f, {from: 100, dx: 50, step: 10, dt: 16, hold: 16});
+ expect(f.pager.index).toBe(1);
+ await settle(f);
+ expect(f.x()).toBe(160);
+ });
+});
+
+describe("the drag's axis: UIKit's rule for a pager inside a scroll view", () => {
+ /**
+ * A drag `degrees` up from leftward, in 4 px steps every 8 ms, then a lift.
+ * Returns whether each move was cancelled (a cancelled move is Safari
+ * giving the page no scroll for the whole touch).
+ */
+ async function angledDrag(
+ f: Fixture,
+ degrees: number,
+ length = 150,
+ ): Promise<boolean[]> {
+ const rad = (degrees * Math.PI) / 180;
+ const x0 = 300;
+ const y0 = 200;
+ touch('touchstart', f.page, x0, y0, now);
+ const steps = Math.round(length / 4);
+ const cancelled: boolean[] = [];
+ for (let i = 1; i <= steps; i++) {
+ await advance(8, f.clock);
+ const d = (length * i) / steps;
+ const move = touch(
+ 'touchmove',
+ f.page,
+ x0 - d * Math.cos(rad),
+ y0 - d * Math.sin(rad),
+ now,
+ );
+ cancelled.push(move.defaultPrevented);
+ }
+ await advance(8, f.clock);
+ touch(
+ 'touchend',
+ f.page,
+ x0 - length * Math.cos(rad),
+ y0 - length * Math.sin(rad),
+ now,
+ );
+ return cancelled;
+ }
+
+ for (const degrees of [35, 45]) {
+ it(`a ${degrees}° drag is the pager's (|dx| ≥ |dy|, the tie included): it pages, and its moves are cancelled from the pan's start at 10 pt, not before`, async () => {
+ const f = setup();
+ const cancelled = await angledDrag(f, degrees);
+ // 4 px steps: the horizontal part reaches the pan's 10 pt hysteresis on
+ // the fourth move. Nothing claims the touch before the pan begins
+ // (no earlier committed claim); every move from then on is cancelled.
+ const start = 3;
+ expect(cancelled.slice(0, start).some(Boolean)).toBe(false);
+ expect(cancelled.slice(start).every(Boolean)).toBe(true);
+ await frames(f, 40);
+ expect(f.calls).toContain('index:1:drag');
+ });
+ }
+
+ it("a 50° drag is the page's: the pager stays and cancels nothing", async () => {
+ const f = setup();
+ const cancelled = await angledDrag(f, 50);
+ expect(cancelled.some(Boolean)).toBe(false);
+ await frames(f, 40);
+ expect(f.x()).toBe(0);
+ expect(f.calls).toEqual([]);
+ });
+
+ it('inside a sheet (an enclosing vertical pan takes part in the touch), a 35° drag moves neither, as UIKit does', async () => {
+ const f = setup();
+ const sheetPan = new PanGestureRecognizer({direction: 'vertical'});
+ const detach = f.host.attach(document.body, sheetPan);
+ try {
+ const cancelled = await angledDrag(f, 35);
+ expect(cancelled.some(Boolean)).toBe(false);
+ await frames(f, 40);
+ expect(f.x()).toBe(0);
+ expect(f.calls).toEqual([]);
+ expect(sheetPan.state === 'began' || sheetPan.state === 'changed').toBe(
+ false,
+ );
+ } finally {
+ detach();
+ }
+ });
+});
+
+describe('review fixes', () => {
+ // spec:AST-094 FR41: a hold that does nothing keeps the browser's native
+ // long-press selection; stopping a settle does something.
+ it('a finger on a resting track leaves its text selectable; one that catches a settle locks it until the lift', async () => {
+ const f = setup({defaultIndex: 0});
+ // Whether a selection that starts on the page's text is refused. Where
+ // iOS WebKit does not run (jsdom), the shared lock cancels `selectstart`
+ // and writes no style.
+ const refuses = () => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ f.page.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ touch('touchstart', f.page, 200, 100, now);
+ await advance(16, f.clock);
+ expect(refuses()).toBe(false);
+ touch('touchend', f.page, 200, 100, now);
+ await advance(16, f.clock);
+ f.pager.goTo(3);
+ await advance(16, f.clock);
+ await advance(16, f.clock);
+ expect(f.pager.isSettling).toBe(true);
+ touch('touchstart', f.page, 200, 100, now);
+ await advance(16, f.clock);
+ expect(refuses()).toBe(true);
+ await advance(120, f.clock);
+ touch('touchend', f.page, 200, 100, now);
+ await advance(16, f.clock);
+ expect(refuses()).toBe(false);
+ expect(f.track.style.getPropertyValue('user-select')).toBe('');
+ });
+
+ // spec:AST-017 FR59: a mouse keeps its released behavior. Its press stops a
+ // settle as a finger's does (spec:AST-094 FR43) and locks no selection.
+ it('a mouse that catches a settle stops it and leaves the text selectable', async () => {
+ const f = setup({defaultIndex: 0});
+ stubMedia(false, false);
+ const refuses = () => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ f.page.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ f.pager.goTo(3);
+ await advance(16, f.clock);
+ await advance(16, f.clock);
+ expect(f.pager.isSettling).toBe(true);
+ mouse('pointerdown', f.page, 200, 100, now);
+ await advance(16, f.clock);
+ expect(refuses()).toBe(false);
+ // The catch stops the settle after UIKit's catch delay, as a finger's.
+ await advance(120, f.clock);
+ expect(f.pager.isSettling).toBe(false);
+ expect(refuses()).toBe(false);
+ mouse('pointerup', f.page, 200, 100, now);
+ await advance(16, f.clock);
+ expect(refuses()).toBe(false);
+ expect(f.track.style.getPropertyValue('user-select')).toBe('');
+ });
+
+ // spec:AST-094 FR6.
+ it('a goTo that retargets a running move keeps its velocity, read from the curve', async () => {
+ const f = setup({defaultIndex: 0});
+ f.pager.goTo(2);
+ await advance(16, f.clock);
+ await advance(16, f.clock);
+ await advance(16, f.clock);
+ const before = f.animator.getVelocity('x', now);
+ expect(Math.abs(before)).toBeGreaterThan(1000);
+ f.pager.goTo(3);
+ expect(f.animator.getVelocity('x', now)).toBeCloseTo(before, -1);
+ await settle(f);
+ expect(f.x()).toBe(-3 * WIDTH);
+ });
+
+ // spec:AST-094 FR37.
+ it('a release moving back toward the start page settles there, whatever the travel', async () => {
+ const f = setup({defaultIndex: 1});
+ // One touch: 70 % of the way to page 2, then back 20 px at 125 px/s,
+ // lifted while moving back.
+ let x = 350;
+ touch('touchstart', f.page, x, 100, now);
+ for (let i = 0; i < 70; i++) {
+ await advance(8, f.clock);
+ x -= 4;
+ touch('touchmove', f.page, x, 100, now);
+ }
+ for (let i = 0; i < 10; i++) {
+ await advance(16, f.clock);
+ x += 2;
+ touch('touchmove', f.page, x, 100, now);
+ }
+ touch('touchend', f.page, x, 100, now);
+ await settle(f);
+ expect(f.pager.index).toBe(1);
+ expect(f.x()).toBe(-WIDTH);
+ });
+
+ // react-component-runtime INV2: setOptions and a controlled goTo run from
+ // the owner's Effect, so nothing they cause may call back from inside it.
+ it('a gap change before a release reports keeps the report and delivers it, and the settle, from a frame callback', async () => {
+ const f = setup({defaultIndex: 1});
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ expect(f.pager.index).toBe(2);
+ expect(f.calls).toEqual([]);
+ f.pager.setOptions({gap: 10});
+ // Nothing from inside the update.
+ expect(f.calls).toEqual([]);
+ expect(f.x()).toBe(-2 * (WIDTH + 10));
+ await advance(16, f.clock);
+ expect(f.calls).toEqual(['index:2:drag', 'settle:2:1']);
+ });
+
+ it('a controlled move calls nothing from inside the update: its settle comes on the next frame', async () => {
+ const f = setup({defaultIndex: 1});
+ f.pager.goTo(3, {animated: false, reason: 'controlled'});
+ expect(f.calls).toEqual([]);
+ await advance(16, f.clock);
+ expect(f.calls).toEqual(['settle:3:1']);
+ });
+
+ it('a count that clamps the page calls nothing from inside the update', async () => {
+ const f = setup({defaultIndex: 4});
+ f.pager.setOptions({count: 3});
+ expect(f.pager.index).toBe(2);
+ expect(f.calls).toEqual([]);
+ await advance(16, f.clock);
+ expect(f.calls).toEqual(['settle:2:4']);
+ });
+
+ it('callbacks an update left for the next frame are dropped when the pager detaches first', async () => {
+ const f = setup({defaultIndex: 1});
+ f.pager.goTo(3, {animated: false, reason: 'controlled'});
+ f.pager.dispose();
+ await advance(16, f.clock);
+ expect(f.calls).toEqual([]);
+ });
+
+ it('a vertical swipe that starts on a settling track still reaches the page: the catch never cancels its moves', async () => {
+ const f = setup();
+ await drag(f, {dx: -250, step: 10, dt: 8});
+ await frames(f, 2);
+ expect(f.pager.isSettling).toBe(true);
+ touch('touchstart', f.page, 200, 100, now);
+ const cancelled: boolean[] = [];
+ for (let i = 1; i <= 10; i++) {
+ await advance(8, f.clock);
+ cancelled.push(
+ touch('touchmove', f.page, 200, 100 - i * 6, now).defaultPrevented,
+ );
+ }
+ await advance(8, f.clock);
+ touch('touchend', f.page, 200, 40, now);
+ expect(cancelled.some(Boolean)).toBe(false);
+ });
+
+ it('a drag that catches an overscrolled track starts from under the finger, with no jump', async () => {
+ const f = setup();
+ // Pulled right past page 0 and released: the track springs back from x > 0.
+ await drag(f, {dx: 160, step: 10, dt: 8});
+ await frames(f, 2);
+ const caught = f.x();
+ expect(caught).toBeGreaterThan(10);
+ touch('touchstart', f.page, 200, 100, now);
+ const xs: number[] = [];
+ for (const dx of [4, 8, 12, 14, 15]) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 200 + dx, 100, now);
+ xs.push(f.x());
+ }
+ // Each move shifts the track by at most the finger's step (banding only
+ // shrinks it): no move jumps.
+ for (let i = 1; i < xs.length; i++) {
+ expect(Math.abs(xs[i] - xs[i - 1])).toBeLessThanOrEqual(4.01);
+ }
+ expect(Math.abs(xs[0] - caught)).toBeLessThan(30);
+ });
+
+ it('a gap change keeps the track on its page', () => {
+ const f = setup({gap: 0, defaultIndex: 3});
+ expect(f.x()).toBe(-3 * WIDTH);
+ f.pager.setOptions({gap: 40});
+ expect(f.x()).toBe(-3 * (WIDTH + 40));
+ });
+
+ it('turning loop off on a virtual page lands on the page shown', () => {
+ const f = setup({loop: true});
+ // Forward one page at a time, past the last page twice over: virtual 7.
+ for (const page of [1, 2, 3, 4, 0, 1, 2]) {
+ f.pager.goTo(page, {animated: false});
+ }
+ expect(f.pager.virtualIndex).toBe(7);
+ expect(f.pager.index).toBe(2);
+ f.pager.setOptions({loop: false});
+ expect(f.pager.index).toBe(2);
+ expect(f.x()).toBe(-2 * WIDTH);
+ });
+
+ it('one onSettle per settle when a finger lands as the settle ends and holds', async () => {
+ const f = setup();
+ f.pager.goTo(1);
+ // 50 ms before setContentOffset's 300 ms ends, a finger lands and holds.
+ await advance(250, f.clock);
+ touch('touchstart', f.page, 200, 100, now);
+ await advance(400, f.clock);
+ touch('touchend', f.page, 200, 100, now);
+ await frames(f, 40);
+ expect(f.calls.filter(c => c.startsWith('settle:'))).toEqual([
+ 'settle:1:0',
+ ]);
+ });
+});
+
+/** The owner replaces the viewport node: the track moves into a new one. */
+function replaceViewport(f: Fixture): HTMLElement {
+ const next = document.createElement('div');
+ Object.defineProperty(next, 'clientWidth', {
+ value: WIDTH,
+ configurable: true,
+ });
+ next.appendChild(f.track);
+ f.viewport.replaceWith(next);
+ f.pager.attach(next, f.track);
+ return next;
+}
+
+describe('pre-review fixes', () => {
+ it('replacing the viewport mid-drag ends the drag on its start page, with no silent page change', async () => {
+ const f = setup();
+ touch('touchstart', f.page, 300, 100, now);
+ for (let i = 1; i <= 30; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 300 - i * 8, 100, now);
+ }
+ expect(f.pager.isDragging).toBe(true);
+ replaceViewport(f);
+ await frames(f);
+ await settle(f);
+ expect(f.pager.index).toBe(0);
+ expect(f.x()).toBeCloseTo(0, 5);
+ expect(f.calls.filter(call => call.startsWith('index:'))).toEqual([]);
+ });
+
+ it('a release whose report still waits when the viewport is replaced is reported, and its settle ends', async () => {
+ const f = setup();
+ await drag(f, {dx: -240});
+ expect(f.calls).toEqual([]);
+ replaceViewport(f);
+ await frames(f);
+ expect(f.pager.index).toBe(1);
+ expect(f.x()).toBeCloseTo(-WIDTH, 5);
+ expect(f.calls).toEqual(['index:1:drag', 'settle:1:0']);
+ });
+
+ it('with the pan off, a touch on the track does not stop a goTo', async () => {
+ const f = setup();
+ f.pager.goTo(2);
+ await advance(16, f.clock);
+ expect(f.pager.isSettling).toBe(true);
+ f.pager.setPanEnabled(false);
+ touch('touchstart', f.page, 200, 100, now);
+ await advance(paging.catchStopMs + 30, f.clock);
+ expect(f.pager.isSettling).toBe(true);
+ touch('touchend', f.page, 200, 100, now);
+ await settle(f);
+ expect(f.pager.index).toBe(2);
+ expect(f.calls).toEqual(['index:2:goTo', 'settle:2:0']);
+ });
+
+ it('nearestPage before the first measure is the target page, never NaN', () => {
+ const pager = createPager({count: 5, defaultIndex: 2});
+ expect(pager.nearestPage(0)).toBe(2);
+ expect(pager.nearestPage(800)).toBe(2);
+ });
+
+ it("the pan's published name is neutral, and an owner can name it", () => {
+ expect(createPager({count: 3}).pan.name).toBe('pager');
+ expect(
+ createPager({count: 3, panOptions: {name: 'Gallery.pager'}}).pan.name,
+ ).toBe('Gallery.pager');
+ });
+
+ it("frames come from the viewport's own window, such as an iframe's", () => {
+ const frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ const view = frame.contentWindow as Window & typeof globalThis;
+ const doc = frame.contentDocument as Document;
+ const inner = vi.fn((_callback: FrameRequestCallback) => 1);
+ view.requestAnimationFrame = inner;
+ const outer = vi.fn((_callback: FrameRequestCallback) => 1);
+ vi.stubGlobal('requestAnimationFrame', outer);
+ const viewport = doc.createElement('div');
+ const track = doc.createElement('div');
+ viewport.appendChild(track);
+ doc.body.appendChild(viewport);
+ Object.defineProperty(viewport, 'clientWidth', {
+ value: WIDTH,
+ configurable: true,
+ });
+ const host = {attach: () => () => {}} as unknown as GestureHost;
+ const animator = createAnimator(track, {
+ now: () => now,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ });
+ const pager = createPager({count: 5}, {host, animator});
+ pager.attach(viewport, track);
+ // The owner's own move: its onSettle waits for a frame.
+ pager.goTo(2, {animated: false, reason: 'controlled'});
+ expect(inner).toHaveBeenCalledTimes(1);
+ expect(outer).not.toHaveBeenCalled();
+ });
+});
+
+describe('usePager (React)', () => {
+ function Paged(props: {
+ index?: number;
+ defaultIndex?: number;
+ viewportKey?: string;
+ isPanEnabled?: boolean;
+ onIndexChange?: (index: number) => void;
+ onSettle?: (index: number, previous: number) => void;
+ onPager?: (pager: Pager) => void;
+ }) {
+ const viewportRef = useRef<HTMLDivElement>(null);
+ const trackRef = useRef<HTMLDivElement>(null);
+ const pager = usePager({
+ viewportRef,
+ trackRef,
+ count: 5,
+ index: props.index,
+ defaultIndex: props.defaultIndex,
+ isPanEnabled: props.isPanEnabled,
+ onIndexChange: props.onIndexChange,
+ onSettle: props.onSettle,
+ });
+ props.onPager?.(pager);
+ return createElement(
+ 'div',
+ {
+ ref: viewportRef,
+ key: props.viewportKey ?? 'a',
+ 'data-testid': 'viewport',
+ },
+ createElement('div', {ref: trackRef}),
+ );
+ }
+
+ /**
+ * A finger's drag 40 px toward page 2 and back to where the pan began, 10 px
+ * from the landing. The pan has begun, and the track rests on the start
+ * page.
+ */
+ function restingDrag(target: Element) {
+ touch('touchstart', target, 300, 100, now);
+ for (let i = 1; i <= 10; i++) {
+ now += 8;
+ vi.advanceTimersByTime(8);
+ touch('touchmove', target, 300 - 4 * i, 100, now);
+ }
+ for (let i = 1; i <= 10; i++) {
+ now += 8;
+ vi.advanceTimersByTime(8);
+ touch('touchmove', target, 260 + 3 * i, 100, now);
+ }
+ }
+
+ /** Animation frames run by hand (the pager defers callbacks to a frame). */
+ function handFrames() {
+ const queued: FrameRequestCallback[] = [];
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ queued.push(callback);
+ return queued.length;
+ });
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+ return (count = 3) => {
+ for (let i = 0; i < count; i++) {
+ for (const callback of queued.splice(0)) {
+ callback(0);
+ }
+ }
+ };
+ }
+
+ // The pager's contract: no callback runs from an unmount.
+ it('an unmount that ends a drag resting on a page calls no onSettle, then or later', () => {
+ const runFrames = handFrames();
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(
+ WIDTH,
+ );
+ const onSettle = vi.fn();
+ const box: {pager: Pager | null} = {pager: null};
+ const view = render(
+ createElement(Paged, {
+ defaultIndex: 1,
+ onSettle,
+ onPager: p => {
+ box.pager = p;
+ },
+ }),
+ );
+ const track = view.getByTestId('viewport').firstElementChild as Element;
+ restingDrag(track);
+ expect(box.pager?.isDragging).toBe(true);
+ expect(box.pager?.presentation()).toBe(WIDTH);
+ view.unmount();
+ runFrames(5);
+ expect(onSettle).not.toHaveBeenCalled();
+ });
+
+ /** A drag 240 px toward page 1 on `track`, past half a page, still held. */
+ function heldDrag(track: Element) {
+ touch('touchstart', track, 300, 100, now);
+ for (let i = 1; i <= 30; i++) {
+ now += 8;
+ vi.advanceTimersByTime(8);
+ touch('touchmove', track, 300 - 8 * i, 100, now);
+ }
+ }
+
+ it('a viewport the hook replaces mid-drag ends the drag on its start page, with no silent page change', () => {
+ const runFrames = handFrames();
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(
+ WIDTH,
+ );
+ const onIndexChange = vi.fn();
+ const box: {pager: Pager | null} = {pager: null};
+ const capture = (p: Pager) => {
+ box.pager = p;
+ };
+ const view = render(
+ createElement(Paged, {viewportKey: 'a', onIndexChange, onPager: capture}),
+ );
+ heldDrag(view.getByTestId('viewport').firstElementChild as Element);
+ expect(box.pager?.isDragging).toBe(true);
+ act(() => {
+ view.rerender(
+ createElement(Paged, {
+ viewportKey: 'b',
+ onIndexChange,
+ onPager: capture,
+ }),
+ );
+ });
+ runFrames(5);
+ expect(box.pager?.index).toBe(0);
+ expect(box.pager?.presentation()).toBeCloseTo(0, 5);
+ expect(onIndexChange).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ it('a release whose report still waits when the hook replaces the viewport is reported, and its settle ends', () => {
+ const runFrames = handFrames();
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(
+ WIDTH,
+ );
+ const onIndexChange = vi.fn();
+ const onSettle = vi.fn();
+ const box: {pager: Pager | null} = {pager: null};
+ const capture = (p: Pager) => {
+ box.pager = p;
+ };
+ const props = {onIndexChange, onSettle, onPager: capture};
+ const view = render(createElement(Paged, {viewportKey: 'a', ...props}));
+ const track = view.getByTestId('viewport').firstElementChild as Element;
+ heldDrag(track);
+ now += 8;
+ vi.advanceTimersByTime(8);
+ touch('touchend', track, 60, 100, now);
+ expect(onIndexChange).not.toHaveBeenCalled();
+ act(() => {
+ view.rerender(createElement(Paged, {viewportKey: 'b', ...props}));
+ });
+ runFrames(5);
+ expect(box.pager?.index).toBe(1);
+ expect(box.pager?.presentation()).toBe(WIDTH);
+ expect(onIndexChange).toHaveBeenCalledWith(1, 'drag');
+ expect(onSettle).toHaveBeenCalledWith(1, 0);
+ view.unmount();
+ });
+
+ // ... and none from the owner's own update: the settle that turning the pan
+ // off causes is reported after the commit, not inside its Effect.
+ it('turning isPanEnabled off during a drag resting on a page calls onSettle after the commit, not inside its Effect', () => {
+ const runFrames = handFrames();
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(
+ WIDTH,
+ );
+ const onSettle = vi.fn();
+ const box: {pager: Pager | null} = {pager: null};
+ const capture = (p: Pager) => {
+ box.pager = p;
+ };
+ const view = render(
+ createElement(Paged, {
+ defaultIndex: 1,
+ onSettle,
+ isPanEnabled: true,
+ onPager: capture,
+ }),
+ );
+ const track = view.getByTestId('viewport').firstElementChild as Element;
+ restingDrag(track);
+ expect(box.pager?.isDragging).toBe(true);
+ expect(box.pager?.presentation()).toBe(WIDTH);
+ act(() => {
+ view.rerender(
+ createElement(Paged, {
+ defaultIndex: 1,
+ onSettle,
+ isPanEnabled: false,
+ onPager: capture,
+ }),
+ );
+ });
+ expect(onSettle).not.toHaveBeenCalled();
+ act(() => {
+ runFrames(3);
+ });
+ expect(onSettle).toHaveBeenCalledTimes(1);
+ expect(onSettle).toHaveBeenCalledWith(1, 1);
+ view.unmount();
+ });
+
+ it('a controlled index change does not echo onIndexChange: the owner caused it', () => {
+ const onIndexChange = vi.fn();
+ const view = render(createElement(Paged, {index: 0, onIndexChange}));
+ act(() => {
+ view.rerender(createElement(Paged, {index: 2, onIndexChange}));
+ });
+ expect(onIndexChange).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ // A controlled index wins, as a controlled input's value does. A page that
+ // the pager reports and the owner does not take returns the pager to the
+ // index, and is not reported again.
+ it('with a controlled index, a page the owner does not take returns the pager to the index', () => {
+ const frames: FrameRequestCallback[] = [];
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const runFrames = () => {
+ for (const callback of frames.splice(0)) {
+ callback(0);
+ }
+ };
+ const box: {pager: Pager | null} = {pager: null};
+ // The owner keeps page 2 whatever the pager reports.
+ const onIndexChange = vi.fn();
+ const view = render(
+ createElement(Paged, {
+ index: 2,
+ onIndexChange,
+ onPager: p => {
+ box.pager = p;
+ },
+ }),
+ );
+ act(() => {
+ box.pager?.goTo(3);
+ });
+ for (let i = 0; i < 4; i++) {
+ act(() => runFrames());
+ }
+ expect(onIndexChange).toHaveBeenCalledTimes(1);
+ expect(onIndexChange).toHaveBeenCalledWith(3, 'goTo');
+ expect(box.pager?.index).toBe(2);
+ view.unmount();
+ });
+
+ it('with a controlled index, a page the owner takes stays', () => {
+ const frames: FrameRequestCallback[] = [];
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const runFrames = () => {
+ for (const callback of frames.splice(0)) {
+ callback(0);
+ }
+ };
+ const box: {pager: Pager | null} = {pager: null};
+ function Owner() {
+ const [index, setIndex] = useState(2);
+ return createElement(Paged, {
+ index,
+ onIndexChange: setIndex,
+ onPager: p => {
+ box.pager = p;
+ },
+ });
+ }
+ const view = render(createElement(Owner));
+ act(() => {
+ box.pager?.goTo(3);
+ });
+ for (let i = 0; i < 4; i++) {
+ act(() => runFrames());
+ }
+ expect(box.pager?.index).toBe(3);
+ view.unmount();
+ });
+
+ // spec:AST-094 FR19 and FR43: recognizers attach for every pointer. Under a
+ // fine pointer, the host keeps its listener on the element and adds none to
+ // the document at rest (FR24). A goTo moves the pager on either pointer.
+ it('attaches the pan and the catch on a fine primary pointer as under a finger (spec:AST-094 FR19, FR43), adds no input listener to the document at rest (FR24), and goTo moves the pager', () => {
+ stubMedia(false, false);
+ const attach = vi.spyOn(GestureHost.prototype, 'attach');
+ const listen = vi.spyOn(document, 'addEventListener');
+ const inputListeners = () =>
+ listen.mock.calls.filter(([type]) =>
+ /^(touch|pointer|mouse|wheel)/.test(type),
+ );
+ const box: {pager: Pager | null} = {pager: null};
+ const view = render(
+ createElement(Paged, {
+ onPager: p => {
+ box.pager = p;
+ },
+ }),
+ );
+ expect(attach).toHaveBeenCalledTimes(2);
+ expect(inputListeners()).toEqual([]);
+ act(() => {
+ box.pager?.goTo(2);
+ });
+ expect(box.pager?.index).toBe(2);
+ view.unmount();
+ stubMedia(false, true);
+ const touchView = render(createElement(Paged, {}));
+ expect(attach).toHaveBeenCalledTimes(4);
+ touchView.unmount();
+ });
+
+ it('reads onPagesChange through the latest render, like the other callbacks', () => {
+ // The page change arrives on the next animation frame: run frames by hand.
+ const frames: FrameRequestCallback[] = [];
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const runFrames = () => {
+ for (const callback of frames.splice(0)) {
+ callback(0);
+ }
+ };
+ const clientWidth = vi
+ .spyOn(HTMLElement.prototype, 'clientWidth', 'get')
+ .mockReturnValue(WIDTH);
+ // Children 150 px wide, 10 px apart, from the track's start.
+ const rects = vi
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: HTMLElement) {
+ if (this.dataset.child != null) {
+ const i = Array.prototype.indexOf.call(
+ this.parentElement?.children ?? [],
+ this,
+ );
+ return new DOMRect(i * 160, 0, 150, 100);
+ }
+ if (this.dataset.track != null) {
+ const n = this.children.length;
+ return new DOMRect(0, 0, n * 160 - 10, 100);
+ }
+ return new DOMRect(0, 0, WIDTH, 100);
+ });
+ try {
+ function Cards({
+ count,
+ onPagesChange,
+ }: {
+ count: number;
+ onPagesChange: (pageCount: number) => void;
+ }) {
+ const viewportRef = useRef<HTMLDivElement>(null);
+ const trackRef = useRef<HTMLDivElement>(null);
+ usePager({
+ viewportRef,
+ trackRef,
+ count,
+ pages: 'children',
+ onPagesChange,
+ });
+ return createElement(
+ 'div',
+ {ref: viewportRef},
+ createElement(
+ 'div',
+ {ref: trackRef, 'data-track': ''},
+ Array.from({length: count}, (_, i) =>
+ createElement('div', {key: i, 'data-child': ''}),
+ ),
+ ),
+ );
+ }
+ const first = vi.fn();
+ const second = vi.fn();
+ const view = render(
+ createElement(Cards, {count: 5, onPagesChange: first}),
+ );
+ act(() => {
+ view.rerender(createElement(Cards, {count: 6, onPagesChange: second}));
+ });
+ expect(second).not.toHaveBeenCalled();
+ act(() => runFrames());
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledWith(5);
+ view.unmount();
+ } finally {
+ rects.mockRestore();
+ clientWidth.mockRestore();
+ }
+ });
+
+ it('attaches again when the viewport element is replaced', () => {
+ let pager: Pager | null = null;
+ const onPager = (p: Pager) => {
+ pager = p;
+ };
+ const view = render(createElement(Paged, {viewportKey: 'a', onPager}));
+ const first = view.getByTestId('viewport');
+ expect(pager!.pan.view).toBe(first);
+ act(() => {
+ view.rerender(createElement(Paged, {viewportKey: 'b', onPager}));
+ });
+ const second = view.getByTestId('viewport');
+ expect(second).not.toBe(first);
+ expect(pager!.pan.view).toBe(second);
+ view.unmount();
+ });
+});
+
+describe("pageForRelease: UIKit's measured page choices (402 pt pages)", () => {
+ const PAGE = 402;
+ const page = (fraction: number, velocity: number, startIndex = 1) =>
+ pageForRelease({
+ position: (startIndex + fraction) * PAGE,
+ velocity,
+ stride: PAGE,
+ count: 6,
+ startIndex,
+ });
+
+ it('released at rest, settles on the nearest page', () => {
+ expect(page(0.485, 0)).toBe(1);
+ expect(page(0.575, 0)).toBe(2);
+ expect(page(0.45, 0)).toBe(1);
+ expect(page(0.55, 0)).toBe(2);
+ expect(page(-0.485, 0)).toBe(1);
+ expect(page(-0.575, 0)).toBe(0);
+ });
+
+ it('pages with the velocity at the advance speed, from wherever the content is', () => {
+ // The pan's last velocity sample at the lift, measured at 10, 25 and
+ // 40 % of the page: the same flip everywhere.
+ for (const fraction of [0.1, 0.25, 0.4]) {
+ expect(page(fraction, 292.7)).toBe(1);
+ expect(page(fraction, 298.6)).toBe(1);
+ expect(page(fraction, 310.7)).toBe(2);
+ expect(page(fraction, 329.9)).toBe(2);
+ expect(page(-fraction, -298.6)).toBe(1);
+ expect(page(-fraction, -310.7)).toBe(0);
+ }
+ // 600 pt/s from 6 % advances; 150 pt/s at 46 % stays.
+ expect(page(0.06, 600)).toBe(2);
+ expect(page(0.46, 150)).toBe(1);
+ expect(page(-0.06, -600)).toBe(0);
+ });
+
+ it('a slow release past the midpoint still advances', () => {
+ expect(page(0.55, 150)).toBe(2);
+ });
+
+ it('never travels more than one page from the page the drag started on', () => {
+ // 1.5 pages from page 1 at 0, 600 and 3000 pt/s: page 2.
+ expect(page(1.5, 0)).toBe(2);
+ expect(page(1.5, 600)).toBe(2);
+ expect(page(1.5, 3000)).toBe(2);
+ // A flick of 1200 from 70 %: one page.
+ expect(page(0.7, 1200)).toBe(2);
+ });
+
+ it('a flick against the drag returns to the start page', () => {
+ expect(page(0.4, -600)).toBe(1);
+ expect(page(-0.4, 600)).toBe(1);
+ });
+
+ // spec:AST-094 FR37, where UIKit, slower than the advance speed, takes the
+ // nearest page.
+ it('a release whose velocity points back toward the start page cancels, whatever the travel', () => {
+ expect(page(0.7, -50)).toBe(1);
+ expect(page(0.95, -299)).toBe(1);
+ expect(page(-0.7, 50)).toBe(1);
+ expect(page(-0.95, 299)).toBe(1);
+ // At rest, or moving on, the travel decides as before.
+ expect(page(0.7, 0)).toBe(2);
+ expect(page(0.7, 50)).toBe(2);
+ expect(page(-0.7, -50)).toBe(0);
+ });
+
+ it('clamps to the pages, or leaves the range when looping', () => {
+ expect(page(0.3, 600, 5)).toBe(5);
+ expect(page(-0.3, -600, 0)).toBe(0);
+ expect(
+ pageForRelease({
+ position: 5.3 * PAGE,
+ velocity: 600,
+ stride: PAGE,
+ count: 6,
+ startIndex: 5,
+ loop: true,
+ }),
+ ).toBe(6);
+ expect(
+ pageForRelease({
+ position: -0.3 * PAGE,
+ velocity: -600,
+ stride: PAGE,
+ count: 6,
+ startIndex: 0,
+ loop: true,
+ }),
+ ).toBe(-1);
+ });
+
+ it('a stale start page past either end counts from the nearest real page, so a release still pages', () => {
+ // The count shrank under a drag that began on page 7 of 8.
+ expect(
+ pageForRelease({
+ position: 400,
+ velocity: -1000,
+ stride: 100,
+ count: 5,
+ startIndex: 7,
+ }),
+ ).toBe(3);
+ expect(
+ pageForRelease({
+ position: 0,
+ velocity: 1000,
+ stride: 100,
+ count: 5,
+ startIndex: -2,
+ }),
+ ).toBe(1);
+ // At rest it lands on a real page.
+ expect(
+ pageForRelease({
+ position: 400,
+ velocity: 0,
+ stride: 100,
+ count: 3,
+ startIndex: 4,
+ }),
+ ).toBe(2);
+ });
+
+ it('reads an exact page boundary as on it', () => {
+ expect(page(0, 600)).toBe(2);
+ expect(page(0, -600)).toBe(0);
+ expect(page(0, 0)).toBe(1);
+ });
+
+ it('handles degenerate geometry', () => {
+ expect(
+ pageForRelease({
+ position: 10,
+ velocity: 0,
+ stride: 0,
+ count: 3,
+ startIndex: 0,
+ }),
+ ).toBe(0);
+ expect(
+ pageForRelease({
+ position: 10,
+ velocity: 0,
+ stride: 100,
+ count: 1,
+ startIndex: 0,
+ }),
+ ).toBe(0);
+ });
+});
diff --git a/packages/core/src/hooks/usePager.ts b/packages/core/src/hooks/usePager.ts
new file mode 100644
index 0000000000..f3d360bb73
--- /dev/null
+++ b/packages/core/src/hooks/usePager.ts
@@ -0,0 +1,1446 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file usePager.ts
+ * @input A viewport and its track, a page count and gap (or the track's
+ * children), the gesture system and the animator
+ * @output Exports `createPager` (the framework-free pager), `usePager` (its
+ * React face) and their types
+ * @position Shared hook for core components that page like a UIKit paging
+ * scroll view, such as Carousel's paging presentation
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/usePager.test.ts
+ * - /packages/core/src/hooks/__tests__/usePager.interaction.browser.spec.ts
+ */
+
+import {useEffect, useRef, useState, type RefObject} from 'react';
+import {getGestureHost, type GestureHost} from '../gestures/GestureHost';
+import type {GestureRecognizer} from '../gestures/GestureRecognizer';
+import {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';
+import {useAttachmentPair} from './useAttachment';
+import {lockSelection, locksSelectionFor} from '../gestures/selectionLock';
+import {
+ PanGestureRecognizer,
+ type PanGestureRecognizerOptions,
+} from '../gestures/PanGestureRecognizer';
+import type {
+ GestureEventContext,
+ GestureTouch,
+ Point,
+ PointerKind,
+} from '../gestures/types';
+import {
+ animatorFor,
+ type Animator,
+ type MotionCurve,
+ type MotionHandle,
+} from '../motion/animator';
+import {
+ pagingSettleVelocity,
+ solveAnimatedPageScroll,
+ solvePaging,
+} from '../motion/paging';
+import {resolveMotion} from '../motion/resolveMotion';
+import {resolveSnapPoint} from '../motion/resolveSnapPoint';
+import {rubberBandClamp, rubberBandUnclamp} from '../motion/rubberBand';
+import {paging, registerPagingTable} from '../motion/uikit/paging';
+import {observeResize} from '../utils/sharedResizeObserver';
+import {isRtlElement} from './isRtlElement';
+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
+
+/** A release the pager settles: where the content is, how fast, and the page it left. */
+export interface PageRelease {
+ /** Content offset at the lift, px, or pages for children pages (may be past either end). */
+ position: number;
+ /** Content velocity at the release, px/s (the shared release velocity). */
+ velocity: number;
+ /** Distance between consecutive pages: page width plus the gap, px (1 for children pages). */
+ stride: number;
+ /** Number of pages (at least 1). */
+ count: number;
+ /** The page the drag started on (its rest position when the finger landed). */
+ startIndex: number;
+ /** Wraps around: the target may leave [0, count - 1] (the owner wraps it). */
+ loop?: boolean;
+}
+
+/**
+ * A pan or a screen-edge pan, told apart by its kind, never by its class.
+ */
+function isPanFamily(
+ recognizer: GestureRecognizer,
+): recognizer is PanGestureRecognizer {
+ return recognizer.kind === 'pan' || recognizer.kind === 'screenEdgePan';
+}
+
+/**
+ * The page a release settles on. It applies UIKit's measured paging rule
+ * (`release` in uikit/paging.ts) through the release policy of
+ * resolveSnapPoint.ts, with the pager's own pages and thresholds.
+ *
+ * - A release at `advanceSpeed` or faster is a flick: it goes to the next page
+ * in the direction of the velocity, from any content position.
+ * - A slower release goes to the page nearest the content. UIKit's measured
+ * `commitFraction` is half a page, the policy's nearest snap point.
+ * - A release whose velocity points back toward the start page settles there,
+ * at any travel, through the policy's `start`.
+ * - The page is never more than `maxPagesFromStart` from the start page
+ * (`maxSteps`). It is clamped to the pages unless the pager loops.
+ * - The policy sees only the pages within that reach of the start page. So a
+ * looping target may leave the range, and the owner wraps it.
+ *
+ * With children pages, positions are in pages, but the velocity stays px/s.
+ * The policy reads the velocity only against `advanceSpeed` and for its
+ * direction.
+ *
+ * @example
+ * ```
+ * // Released at rest 60 % of the way from page 1 to page 2: page 2.
+ * pageForRelease({position: 1.6 * 402, velocity: 0, stride: 402, count: 6, startIndex: 1});
+ * // Flicked forward at 600 px/s from 6 % past page 1: page 2.
+ * pageForRelease({position: 1.06 * 402, velocity: 600, stride: 402, count: 6, startIndex: 1});
+ * ```
+ */
+
+export function pageForRelease({
+ position,
+ velocity,
+ stride,
+ count,
+ startIndex,
+ loop = false,
+}: PageRelease): number {
+ if (!(stride > 0) || count < 1) {
+ return 0;
+ }
+ const reach = paging.release.maxPagesFromStart;
+ // A stale start page past either end (the count shrank, an overscrolled
+ // track) counts from the nearest real page.
+ const from = loop ? startIndex : Math.min(Math.max(startIndex, 0), count - 1);
+ const first = loop ? from - reach : Math.max(0, from - reach);
+ const last = loop ? from + reach : Math.min(count - 1, from + reach);
+ const points = Array.from(
+ {length: last - first + 1},
+ (_, i) => (first + i) * stride,
+ );
+ const {index} = resolveSnapPoint({
+ points,
+ position,
+ velocity,
+ flickThreshold: paging.release.advanceSpeed,
+ // A hair of tolerance so a release exactly on a page reads as on it.
+ tolerance: 1e-6 * stride,
+ start: from * stride,
+ fromIndex: from - first,
+ maxSteps: reach,
+ });
+ return first + index;
+}
+
+/** Why the target page changed. */
+export type PagerChangeReason = 'drag' | 'goTo' | 'controlled';
+
+export interface PagerOptions {
+ /** Number of pages (at least 1). */
+ count: number;
+ /** Space between pages, px; it shows only while a page moves. @default 0 */
+ gap?: number;
+ /** Pages wrap around; indexes become unbounded. @default false */
+ loop?: boolean;
+ /**
+ * What a page is. With `'viewport'`, every page is the viewport's width, at
+ * index × (width + `gap`). With `'children'`, each child of the track is a
+ * page at its own start edge, as `scroll-snap-align: start` places it.
+ *
+ * With children pages, the viewport's padding stays an inset. The travel
+ * ends where the track's end meets the end of the viewport's content box. A
+ * child whose start lies past that point rests there, so the last children
+ * can share one page. The count is then the number of distinct pages
+ * (`pageCount`). `count` and `gap` serve only before the first measure, and
+ * children pages do not loop. The pager measures the children on attach, on
+ * a resize, on an options change and when a drag begins. It never measures
+ * while a finger moves.
+ * @default 'viewport'
+ */
+ pages?: 'viewport' | 'children';
+ /** Starting page. @default 0 */
+ defaultIndex?: number;
+ /**
+ * The target page changed (index wrapped into [0, count)). A release
+ * reports once its settle is moving; `index` has the page from the lift.
+ * A controlled move (the `index` prop, or a `count` that clamps the page)
+ * is the owner's own and is not reported.
+ */
+ onIndexChange?: (index: number, reason: PagerChangeReason) => void;
+ /**
+ * The track came to rest on `index` after moving on its own (a settle, a
+ * `goTo`), having last rested on `previous` (equal when it returned).
+ */
+ onSettle?: (index: number, previous: number) => void;
+ /**
+ * With `pages: 'children'`: a measure found different pages (how many, or
+ * where they rest) after the viewport or the track resized or the options
+ * changed. Not called for the measure an attach makes: read `pageCount`
+ * after attaching.
+ */
+ onPagesChange?: (pageCount: number) => void;
+ /**
+ * Called when the pan would begin, with the drag's first physical direction
+ * on screen, the same in RTL. Return false to leave the touch to someone
+ * else, such as a zoomed photo that can still pan that way.
+ */
+ shouldBeginPan?: (direction: 'left' | 'right') => boolean;
+ /** Constructor options for the pan (e.g. `allowedPointerTypes`). */
+ panOptions?: Partial<PanGestureRecognizerOptions>;
+}
+
+export interface GoToOptions {
+ /** Animate with `setContentOffset(_:animated:)`'s curve. @default true */
+ animated?: boolean;
+ /** @default 'goTo' */
+ reason?: PagerChangeReason;
+}
+
+export interface Pager {
+ /** The page pan, for failure requirements and simultaneity. */
+ readonly pan: PanGestureRecognizer;
+ /** The target page, wrapped into [0, count). */
+ readonly index: number;
+ /** The target page, unbounded when looping. */
+ readonly virtualIndex: number;
+ /**
+ * How many pages there are: `count`, or with `pages: 'children'` the
+ * distinct pages last measured.
+ */
+ readonly pageCount: number;
+ /** Whether the track is moving on its own (a settle or a `goTo`). */
+ readonly isSettling: boolean;
+ /** Whether a finger is dragging the track. */
+ readonly isDragging: boolean;
+ /** The content offset on screen right now, from the curve (px). */
+ presentation(): number;
+ /** Where page `index` rests (px). */
+ pageOffset(index: number): number;
+ /** The page whose rest is nearest content offset `position` (px). */
+ nearestPage(position: number): number;
+ /** Move to a page (wrapped to the nearest copy when looping). */
+ goTo(index: number, options?: GoToOptions): void;
+ /** Update options; a smaller count clamps the target page. */
+ setOptions(options: Partial<PagerOptions>): void;
+ /**
+ * Turns the page pan on or off (the hook's `isPanEnabled`). While it is off,
+ * a touch does not stop a settle or a `goTo`. A drag that it ends settles as
+ * a cancelled drag does. The callbacks of that settle wait for the next
+ * frame, so no callback runs inside the caller's update.
+ */
+ setPanEnabled(enabled: boolean): void;
+ /** Attach to the elements; returns a detach function. */
+ attach(viewport: HTMLElement, track: HTMLElement): () => void;
+ /** Detach and stop everything (attaching again restarts it). */
+ dispose(): void;
+}
+
+/**
+ * The copy of page `index` nearest virtual page `from`, in a loop of `count`
+ * pages. Two copies can be equally near: with two pages, or half an even
+ * count away. Then it is `index` itself when that is one of them, so a step
+ * to `from + 1` always goes forward.
+ */
+export function nearestLoopCopy(
+ index: number,
+ from: number,
+ count: number,
+): number {
+ if (Math.abs(index - from) * 2 <= count) {
+ return index;
+ }
+ return Math.round(
+ from +
+ (((mod(index, count) - mod(from, count) + count + count / 2) % count) -
+ count / 2),
+ );
+}
+
+/** Whether two measured page lists are the same to within half a pixel. */
+function sameOffsets(
+ a: ReadonlyArray<number>,
+ b: ReadonlyArray<number> | null,
+): boolean {
+ return (
+ b != null &&
+ a.length === b.length &&
+ a.every((offset, i) => Math.abs(offset - b[i]) < 0.5)
+ );
+}
+
+function mod(value: number, count: number): number {
+ return ((value % count) + count) % count;
+}
+
+/** A position curve seen as the track's x (mirrored for LTR). */
+function toTrackCurve(curve: MotionCurve, sign: number): MotionCurve {
+ // `+ 0` turns a mirrored zero (−0) into 0.
+ return {
+ duration: curve.duration,
+ at: t => sign * curve.at(t) + 0,
+ velocity: t => sign * curve.velocity(t) + 0,
+ };
+}
+
+/** What a pager runs on; tests pass their own clocked host and animator. */
+export interface PagerEnvironment {
+ /** The gesture host; the document's shared host by default. */
+ host?: GestureHost;
+ /** The track's animator; `animatorFor(track)` by default. */
+ animator?: Animator;
+ /** Timers for the catch delay; the viewport's window's by default. */
+ setTimeout?: (callback: () => void, ms: number) => unknown;
+ clearTimeout?: (handle: unknown) => void;
+ /** The next animation frame; the viewport's window's by default. */
+ requestFrame?: (callback: () => void) => void;
+}
+
+/**
+ * The pager's pan. Its release velocity is the pan's `scrollVelocity()`, the
+ * one UIScrollView hands `scrollViewWillEndDragging`. Unlike UIKit's, it reads
+ * 0 after a still hold.
+ *
+ * Inside a scroll view, it takes UIKit's rule: a drag whose dominant axis is
+ * horizontal is the pager's (`paging.nestedPanAxisRatio`, the tie included).
+ * Any other drag is the page's. Like every pan, it cancels the touch's moves
+ * once it begins, at its 10 pt hysteresis. Nothing claims a touch earlier.
+ *
+ * Inside a sheet, it keeps the sheet's rule (`axisRatio`,
+ * `paging.panAxisRatio`). The arena shows the sheet as an enclosing vertical
+ * pan that takes part in the touch. Between atan(1 ÷ that ratio) and 45°,
+ * neither moves.
+ */
+class PagerPanGestureRecognizer extends PanGestureRecognizer {
+ /**
+ * The kind of pointer the pan follows. Under Reduce Motion a touch's
+ * release cross-fades; a mouse's or a pen's lands at once on a fine
+ * pointer.
+ */
+ pointerType: PointerKind | null = null;
+
+ protected override touchesBegan(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void {
+ if (this.state === 'possible' && touches.length > 0) {
+ this.pointerType = touches[0].pointerType;
+ }
+ super.touchesBegan(touches, event);
+ }
+
+ private hasEnclosingVerticalPan(): boolean {
+ for (const other of this.arena?.involvedRecognizers ?? []) {
+ if (
+ other !== this &&
+ isPanFamily(other) &&
+ (other.direction === 'vertical' ||
+ other.direction === 'up' ||
+ other.direction === 'down')
+ ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected override classify(translation: Point): 'begin' | 'fail' | 'wait' {
+ const decided = super.classify(translation);
+ if (decided !== 'wait' || this.hasEnclosingVerticalPan()) {
+ return decided;
+ }
+ const along = Math.abs(translation.x);
+ const across = Math.abs(translation.y);
+ if (along === 0 && across === 0) {
+ return 'wait';
+ }
+ return along >= paging.nestedPanAxisRatio * across ? 'begin' : 'fail';
+ }
+}
+
+/**
+ * The settle catcher: a zero-duration long press that only stops the settle.
+ * It never claims the touch. So a vertical swipe or a pinch that starts on a
+ * settling track still reaches the page. UIKit also hands the outer scroll
+ * view a vertical drag after the paging view's content stops.
+ */
+class SettleCatcher extends LongPressGestureRecognizer {
+ /** The kind of pointer that caught the settle (see the pager's pan). */
+ pointerType: PointerKind | null = null;
+
+ override get claimsTouches(): boolean {
+ return false;
+ }
+
+ protected override touchesBegan(
+ touches: ReadonlyArray<GestureTouch>,
+ event: GestureEventContext,
+ ): void {
+ if (this.state === 'possible' && touches.length > 0) {
+ this.pointerType = touches[0].pointerType;
+ }
+ super.touchesBegan(touches, event);
+ }
+}
+
+/**
+ * A trackpad swipe that moved under this fraction of a page (in the pages'
+ * own spacing, children pages included) releases still, whatever its
+ * speed.
+ */
+const STILL_RELEASE_FRACTION = 0.1;
+
+/** Whether a pan's contact is a scroll (a trackpad's), not a pointer. */
+function isScrollContact(recognizer: PanGestureRecognizer): boolean {
+ return recognizer.trackedTouches[0]?.scrollType != null;
+}
+
+/**
+ * Creates a pager: UIKit's paging scroll view, driven by the gesture system
+ * and played on the compositor. A native scroll-snap container does not run
+ * UIKit's paging integrator, and it cannot share a gesture with a pinch.
+ * Attach the pager to its viewport and track. It measures the page width on
+ * attach, on a resize and when a drag begins, never while a finger moves.
+ *
+ * - A horizontal pan moves the track 1:1, with one `translate` write per
+ * move, no layout read and no React render. Past the first or last page,
+ * the track follows UIKit's rubber band, with d = the page width.
+ * - At the lift, `pageForRelease` picks the page with UIKit's measured rule.
+ * The track then settles on UIKit's paging integrator (`solvePaging`),
+ * baked into keyframes.
+ * - A finger that lands on a settling pager catches it `paging.catchStopMs`
+ * after the touch, as in UIKit. A drag catches it at once, from the value
+ * on screen. While the pan is off, a touch does not stop the motion.
+ * - `goTo` runs the curve of `setContentOffset(_:animated:)` and cancels a
+ * drag in progress. It reads that duration and curve through
+ * `resolveMotion`.
+ * - Under Reduce Motion, the drag still follows the finger, but nothing
+ * travels after the lift. A touch's release cross-fades in 200 ms on any
+ * pointer. `goTo` and a mouse's or a pen's release cross-fade on a coarse
+ * pointer, and land at once on any other.
+ * - `onIndexChange` reports a release's page once its settle runs on the
+ * compositor, two frames after the frame it started in. It reports a
+ * `goTo` at once, and never a controlled change. A report still waiting at
+ * a detach or a controlled move is dropped. `onSettle` runs when the track
+ * rests.
+ * - A detach ends a drag on its start page, and an unmount calls nothing.
+ * When a replaced viewport or track attaches, a motion that the detach
+ * stopped ends on its page. Its report and `onSettle` go out from a frame.
+ * - A controlled `index` wins. A page that the pager reports and the owner
+ * does not take returns the pager to `index`, without a report.
+ * - The pan and the catch attach for every pointer. A mouse drags the track
+ * as a finger does. The pan follows a trackpad's scroll along its axis, but
+ * never a mouse wheel's.
+ * - A trackpad swipe moves the track at most one page from its start page.
+ * A swipe that moves under a tenth of a page releases still, at any speed.
+ * A swipe that lands during the last swipe's settle begins from that
+ * settle's page.
+ *
+ * Positions are content offsets in px, 0 at page 0 and growing toward later
+ * pages. The track is translated by −position, or by +position in a
+ * right-to-left viewport. The owner renders the pages: all of them, a window,
+ * or a wrapped copy for a loop. With `loop`, indexes are unbounded, and
+ * `index` wraps them into [0, count).
+ *
+ * Give the current page and its neighbors their own layers
+ * (`will-change: transform`). Through a busy main thread, Mobile Safari moves
+ * the track but cannot paint new content, so part of a page that slides in
+ * stays blank. A page on its own layer is painted whole before it moves.
+ */
+export function createPager(
+ initial: PagerOptions,
+ environment: PagerEnvironment = {},
+): Pager {
+ registerPagingTable();
+ // Frames and timers come from the viewport's own window, known from the
+ // attach. In a Picture-in-Picture window, the opener's frames stop while
+ // its tab is hidden.
+ let view: (Window & typeof globalThis) | null = null;
+ const realm = () => view ?? globalThis;
+ const setTimer =
+ environment.setTimeout ??
+ ((callback: () => void, ms: number) => realm().setTimeout(callback, ms));
+ const clearTimer =
+ environment.clearTimeout ??
+ ((handle: unknown) =>
+ realm().clearTimeout(handle as ReturnType<typeof setTimeout>));
+ const requestFrame =
+ environment.requestFrame ??
+ ((callback: () => void) => {
+ const frames = realm();
+ if (typeof frames.requestAnimationFrame === 'function') {
+ frames.requestAnimationFrame(() => callback());
+ } else {
+ setTimer(callback, 16);
+ }
+ });
+ let options: PagerOptions = {...initial};
+ let viewport: HTMLElement | null = null;
+ let trackElement: HTMLElement | null = null;
+ let animator: Animator | null = null;
+ let pageWidth = 0;
+ let isRtl = false;
+ // With `pages: 'children'`, each page's offset (px, ascending), once
+ // measured.
+ let childOffsets: ReadonlyArray<number> | null = null;
+
+ const isChildPages = () => options.pages === 'children';
+ const isLooping = () => options.loop === true && !isChildPages();
+ const count = () =>
+ isChildPages() && childOffsets != null
+ ? childOffsets.length
+ : Math.max(1, Math.floor(options.count));
+ const stride = () => pageWidth + (options.gap ?? 0);
+ const sign = () => (isRtl ? 1 : -1);
+ const clampIndex = (index: number) =>
+ isLooping() ? index : Math.max(0, Math.min(count() - 1, index));
+
+ /** Where page `index` rests (px). */
+ function offsetOf(index: number): number {
+ if (isChildPages() && childOffsets != null) {
+ return childOffsets[
+ Math.max(0, Math.min(childOffsets.length - 1, index))
+ ];
+ }
+ return index * stride();
+ }
+
+ /**
+ * Where `position` falls, in pages: an index plus the fraction of the way
+ * to the next page (past either end, in the end page's spacing).
+ */
+ function pageAt(position: number): number {
+ if (!(isChildPages() && childOffsets != null)) {
+ return position / stride();
+ }
+ const at = childOffsets;
+ const n = at.length;
+ if (n === 1) {
+ return (position - at[0]) / (pageWidth > 0 ? pageWidth : 1);
+ }
+ if (position < at[0]) {
+ return (position - at[0]) / (at[1] - at[0]);
+ }
+ for (let i = 0; i < n - 1; i++) {
+ if (position < at[i + 1]) {
+ return i + (position - at[i]) / (at[i + 1] - at[i]);
+ }
+ }
+ return n - 1 + (position - at[n - 1]) / (at[n - 1] - at[n - 2]);
+ }
+
+ /** The page nearest `position`, or the target before anything is measured. */
+ function nearestPage(position: number): number {
+ if (!isChildPages() && !(stride() > 0)) {
+ return target;
+ }
+ return Math.round(pageAt(position));
+ }
+
+ /**
+ * The page a release from `position` at `velocity` settles on (UIKit's
+ * rule, pageForRelease), in children pages' own spacing.
+ */
+ function releasePage(
+ position: number,
+ velocity: number,
+ startIndex: number,
+ ): number {
+ const pages = isChildPages() && childOffsets != null;
+ return pageForRelease({
+ position: pages ? pageAt(position) : position,
+ velocity,
+ stride: pages ? 1 : stride(),
+ count: count(),
+ startIndex,
+ loop: isLooping(),
+ });
+ }
+
+ /**
+ * Children pages: each child's start edge, from the track's start. The
+ * track's own translate moves both alike, so it cancels out. Each offset is
+ * clamped to the travel that keeps the track's end at or past the end of
+ * the viewport's content box. Children clamped onto one offset share its
+ * page.
+ *
+ * Rects are read in the track's own CSS pixels, which its `translate` moves
+ * in. An ancestor's `zoom` scales the rects, so the pager divides out that
+ * scale: the rect's width over the track's used width.
+ */
+ function measureChildOffsets(): ReadonlyArray<number> {
+ const track = trackElement;
+ if (viewport == null || track == null || track.children.length === 0) {
+ return [0];
+ }
+ const box = track.getBoundingClientRect();
+ const used = Number.parseFloat(getComputedStyle(track).width);
+ const scale = used > 0 && box.width > 0 ? box.width / used : 1;
+ const style = getComputedStyle(viewport);
+ const inner =
+ viewport.clientWidth -
+ (Number.parseFloat(style.paddingLeft) || 0) -
+ (Number.parseFloat(style.paddingRight) || 0);
+ const starts: number[] = [];
+ let extent = 0;
+ for (const child of Array.from(track.children)) {
+ const rect = child.getBoundingClientRect();
+ starts.push(
+ (isRtl ? box.right - rect.right : rect.left - box.left) / scale,
+ );
+ extent = Math.max(
+ extent,
+ (isRtl ? box.right - rect.left : rect.right - box.left) / scale,
+ );
+ }
+ const end = Math.max(0, extent - inner);
+ const offsets: number[] = [];
+ for (const start of starts) {
+ const offset = Math.min(Math.max(start, 0), end);
+ if (offsets.length === 0 || offset > offsets[offsets.length - 1] + 0.5) {
+ offsets.push(offset);
+ }
+ }
+ return offsets.length > 0 ? offsets : [0];
+ }
+
+ // The page the track rests on or is heading for (unbounded when looping),
+ // and the one it last rested on.
+ let target = clampIndex(Math.round(options.defaultIndex ?? 0));
+ let settled = target;
+ let settleHandle: MotionHandle | null = null;
+ let isSwipeSettle = false;
+ let settleToken = 0;
+ let isDragging = false;
+
+ let dragStart = 0;
+ let dragStartIndex = 0;
+ let dragPosition = 0;
+ let suppressCancelSettle = false;
+ let catchTimer: unknown = null;
+ // Whether the finger now holding the track stopped a settle (not one that
+ // ended on its own inside the catch window).
+ let caughtSettle = false;
+
+ const pan = new PagerPanGestureRecognizer({
+ ...options.panOptions,
+ // Published, so app code can relate its own recognizers to the paging
+ // pan (gesture delegates). Instances are told apart by their element.
+ name: options.panOptions?.name ?? 'pager',
+ direction: 'horizontal',
+ axisRatio: options.panOptions?.axisRatio ?? paging.panAxisRatio,
+ // On the web the pan follows a trackpad's scroll along its axis and never
+ // a mouse wheel's.
+ allowedScrollTypes: options.panOptions?.allowedScrollTypes ?? [
+ 'continuous',
+ ],
+ shouldBegin: recognizer => {
+ if (options.panOptions?.shouldBegin?.(recognizer) === false) {
+ return false;
+ }
+ const dx = recognizer.totalTranslation().x;
+ const direction = dx < 0 ? 'left' : 'right';
+ return options.shouldBeginPan?.(direction) ?? true;
+ },
+ });
+
+ // Catches a settling track when a finger lands on it. It begins on the
+ // touch itself, alongside the pan, only while the track moves on its own
+ // and the pan is on.
+ const catcher = new SettleCatcher({
+ minimumPressDuration: 0,
+ allowableMovement: Number.POSITIVE_INFINITY,
+ // Its own hold does nothing, so it brings no selection lock: a finger on
+ // a resting track keeps the browser's native long press. Stopping a
+ // settle does something; `holdSelection` locks then.
+ selectionLock: null,
+ shouldBegin: () => settleHandle != null && !isDragging && pan.isEnabled,
+ });
+ catcher.recognizeSimultaneouslyWith(pan);
+
+ function positionToX(position: number): number {
+ const x = sign() * position;
+ return x === 0 ? 0 : x;
+ }
+
+ function presentation(): number {
+ if (animator == null) {
+ return offsetOf(target);
+ }
+ return sign() * animator.get('x');
+ }
+
+ function clearCatchTimer(): void {
+ if (catchTimer != null) {
+ clearTimer(catchTimer);
+ catchTimer = null;
+ }
+ }
+
+ function stopSettle(): void {
+ clearCatchTimer();
+ flushReport();
+ isSwipeSettle = false;
+ if (settleHandle != null) {
+ settleToken += 1;
+ settleHandle = null;
+ animator?.stop(['x']);
+ }
+ }
+
+ function wrapped(index: number): number {
+ return isLooping() ? mod(index, count()) : index;
+ }
+
+ // The owner passes its own updates (setOptions, a controlled goTo) from an
+ // Effect. The callbacks they cause run from a frame callback, never inside
+ // that Effect. There, a callback that sets state would update the owner
+ // during its own commit. A detach drops the callbacks still waiting.
+ let deferDepth = 0;
+ let deferred: (() => void)[] = [];
+ let deferredToken = 0;
+
+ function deliver(callback: () => void): void {
+ if (deferDepth > 0) {
+ deferred.push(callback);
+ } else {
+ callback();
+ }
+ }
+
+ function deferringCallbacks(work: () => void): void {
+ deferDepth += 1;
+ try {
+ work();
+ } finally {
+ deferDepth -= 1;
+ if (deferDepth === 0 && deferred.length > 0) {
+ const calls = deferred;
+ deferred = [];
+ const token = deferredToken;
+ requestFrame(() => {
+ if (token === deferredToken) {
+ for (const call of calls) {
+ call();
+ }
+ }
+ });
+ }
+ }
+ }
+
+ function dropDeferred(): void {
+ deferred = [];
+ deferredToken += 1;
+ }
+
+ // A release's report waits for its settle to reach the compositor.
+ let reported = wrapped(target);
+ let pendingReport: PagerChangeReason | null = null;
+ let reportToken = 0;
+
+ function report(reason: PagerChangeReason): void {
+ pendingReport = null;
+ reportToken += 1;
+ const index = wrapped(target);
+ if (index !== reported) {
+ reported = index;
+ // A controlled move (the owner's `index`, or a `count` that clamps the
+ // page) is the owner's own change: it is not reported back.
+ if (reason !== 'controlled') {
+ deliver(() => options.onIndexChange?.(index, reason));
+ }
+ }
+ }
+
+ function flushReport(): void {
+ if (pendingReport != null) {
+ report(pendingReport);
+ }
+ }
+
+ /**
+ * Forgets a release's report still waiting: the pager is detaching, or the
+ * owner's own (controlled) move replaces the page it chose. The page last
+ * reported stays as it was.
+ */
+ function dropReport(): void {
+ pendingReport = null;
+ reportToken += 1;
+ }
+
+ /**
+ * A release reports its page once the settle reaches the compositor, two
+ * frames after the frame it started in. In Mobile Safari, a main-thread
+ * block that starts within about two frames of the touch freezes a motion
+ * that the touch's handler started. The owner's render of the new page is
+ * such a block. UIKit tells its delegate at the lift
+ * (`scrollViewWillEndDragging`), and the page is known then too (`index`).
+ */
+ function setTarget(
+ next: number,
+ reason: PagerChangeReason,
+ whenMoving = false,
+ ): void {
+ target = next;
+ if (whenMoving) {
+ pendingReport = reason;
+ } else {
+ report(reason);
+ }
+ }
+
+ /**
+ * Runs `callback` in the `frames`-th animation frame after the frame that a
+ * motion started in. Call it when the motion's start resolves.
+ *
+ * WebKit resolves an animation's start inside that frame's rendering
+ * update, before the frame's animation-frame callbacks. No task runs inside
+ * a rendering update. So a first frame that runs before a task queued at
+ * the resolution is the start's own frame, and it does not count.
+ * Timestamps cannot tell: WebKit stamps that frame's callbacks 0–4 ms after
+ * the animation's start time, as far apart as two frames at 240 Hz. Where
+ * the start resolves after its frame, as in Chromium, the task runs before
+ * the next frame. The report then comes a frame later, never earlier.
+ */
+ function afterFramesPastStart(frames: number, callback: () => void): void {
+ let isPastStartFrame = false;
+ setTimer(() => {
+ isPastStartFrame = true;
+ }, 0);
+ const onFrame = (left: number) => {
+ const remaining = isPastStartFrame ? left - 1 : left;
+ isPastStartFrame = true;
+ if (remaining <= 0) {
+ callback();
+ return;
+ }
+ requestFrame(() => onFrame(remaining));
+ };
+ requestFrame(() => onFrame(frames));
+ }
+
+ function rest(): void {
+ flushReport();
+ isSwipeSettle = false;
+ const previous = wrapped(settled);
+ settled = target;
+ const index = wrapped(settled);
+ deliver(() => options.onSettle?.(index, previous));
+ }
+
+ /**
+ * Plays `curve` on the track. Under Reduce Motion, the animator replaces the
+ * travel. A settle that a touch's release starts (`touchRelease`)
+ * cross-fades on any pointer. Any other motion, such as `goTo` or a mouse's
+ * or a pen's release, cross-fades on a coarse pointer. It lands at once on
+ * any other pointer.
+ */
+ function play(curve: MotionCurve, touchRelease = false): void {
+ isSwipeSettle = false;
+ if (animator == null) {
+ return;
+ }
+ follow(animator.play({x: toTrackCurve(curve, sign())}, {touchRelease}));
+ }
+
+ function follow(handle: MotionHandle): void {
+ const token = ++settleToken;
+ settleHandle = handle;
+ if (pendingReport != null) {
+ const reportAt = reportToken;
+ void handle.started.then(() =>
+ afterFramesPastStart(2, () => {
+ if (reportAt === reportToken) {
+ flushReport();
+ }
+ }),
+ );
+ }
+ void handle.finished.then(finished => {
+ if (token !== settleToken) {
+ return;
+ }
+ settleHandle = null;
+ if (finished) {
+ rest();
+ }
+ });
+ }
+
+ /**
+ * The settle after a pointer lifts (a release, or a hold let go);
+ * `touchRelease` when that pointer was a touch.
+ */
+ function settleFrom(
+ position: number,
+ velocity: number,
+ touchRelease: boolean,
+ ): void {
+ const to = offsetOf(target);
+ // UIKit's integrator, as a playable curve (touch motion stays internal).
+ const curve = solvePaging({from: position, velocity, to});
+ if (curve.steps === 0) {
+ animator?.set({x: positionToX(to)});
+ rest();
+ return;
+ }
+ play(curve, touchRelease);
+ }
+
+ function measure(): void {
+ if (viewport == null) {
+ return;
+ }
+ const width = viewport.clientWidth;
+ const rtl = isRtlElement(viewport);
+ // A new writing direction mirrors the track, so it re-places it too.
+ let changed = width !== pageWidth || rtl !== isRtl;
+ isRtl = rtl;
+ pageWidth = width;
+ if (isChildPages()) {
+ const offsets = measureChildOffsets();
+ if (!sameOffsets(offsets, childOffsets)) {
+ childOffsets = offsets;
+ changed = true;
+ const pageCount = offsets.length;
+ deliver(() => options.onPagesChange?.(pageCount));
+ }
+ }
+ if (!changed) {
+ return;
+ }
+ if (!isDragging && !isLooping() && target > count() - 1) {
+ // Fewer pages (children clamped onto one): the last one, as a smaller
+ // count clamps. A loop's target is unbounded, so it keeps it.
+ goTo(count() - 1, {animated: false, reason: 'controlled'});
+ return;
+ }
+ // A resize lands on the target page at its new offset (a settle in
+ // flight ends there), as a paging scroll view does on rotation. A finger
+ // that holds a caught track keeps it; its lift settles on the new offsets.
+ if (!isDragging && !caughtSettle) {
+ stopSettle();
+ animator?.set({x: positionToX(offsetOf(target))});
+ if (settled !== target) {
+ rest();
+ }
+ }
+ }
+
+ function onPan(recognizer: PanGestureRecognizer): void {
+ const state = recognizer.state;
+ if (state === 'began') {
+ // Read before measure(), which can stop the settle on a resize.
+ const wasSwipeSettle = settleHandle != null && isSwipeSettle;
+ measure();
+ clearCatchTimer();
+ const current = presentation();
+ stopSettle();
+ isDragging = true;
+ // A track caught past an end is shown rubber-banded: the drag starts
+ // from its unbanded position, so the first move keeps it under the
+ // finger.
+ dragStart = isLooping()
+ ? current
+ : rubberBandUnclamp(
+ current,
+ offsetOf(0),
+ offsetOf(count() - 1),
+ pageWidth > 0 ? pageWidth : 1,
+ );
+ dragPosition = current;
+ // A trackpad swipe that lands while the last swipe's settle runs
+ // begins from that settle's page, so back-to-back swipes page on. Any
+ // other motion, such as a goTo, hands over the page on screen.
+ dragStartIndex =
+ wasSwipeSettle && isScrollContact(recognizer)
+ ? target
+ : nearestPage(current);
+ return;
+ }
+ if (state === 'changed') {
+ const dx = recognizer.translation().x;
+ // Finger right (dx > 0) moves content toward earlier pages in LTR.
+ let raw = dragStart + sign() * dx;
+ if (isScrollContact(recognizer) && pageWidth > 0) {
+ // A trackpad swipe moves the track at most one page from its start
+ // page, across a loop too. The window also holds where the swipe
+ // began, so a swipe that catches a longer move starts from the
+ // screen. A pager that does not loop keeps the rubber band of its
+ // first and last pages below.
+ const looping = isLooping();
+ const before =
+ looping || dragStartIndex > 0
+ ? offsetOf(dragStartIndex - 1)
+ : -Infinity;
+ const after =
+ looping || dragStartIndex < count() - 1
+ ? offsetOf(dragStartIndex + 1)
+ : Infinity;
+ raw = Math.min(
+ Math.max(raw, Math.min(before, after, dragStart)),
+ Math.max(before, after, dragStart),
+ );
+ }
+ dragPosition = isLooping()
+ ? raw
+ : rubberBandClamp(
+ raw,
+ offsetOf(0),
+ offsetOf(count() - 1),
+ pageWidth > 0 ? pageWidth : 1,
+ );
+ animator?.set({x: positionToX(dragPosition)});
+ return;
+ }
+ if (state === 'ended' || state === 'cancelled') {
+ isDragging = false;
+ if (state === 'cancelled' && suppressCancelSettle) {
+ suppressCancelSettle = false;
+ return;
+ }
+ // A still finger releases at 0, where UIScrollView keeps the speed.
+ let velocity =
+ state === 'ended' ? sign() * recognizer.scrollVelocity().x : 0;
+ // A trackpad swipe that moved under a tenth of a page from where it
+ // began, in the pages' own spacing, releases still at any speed. Such a
+ // speed spike is not a flick. A finger's and a mouse's flick keep their
+ // speed.
+ if (
+ isScrollContact(recognizer) &&
+ Math.abs(pageAt(dragPosition) - pageAt(dragStart)) <
+ STILL_RELEASE_FRACTION
+ ) {
+ velocity = 0;
+ }
+ const next = releasePage(dragPosition, velocity, dragStartIndex);
+ setTarget(next, 'drag', true);
+ settleFrom(
+ dragPosition,
+ pagingSettleVelocity(velocity),
+ pan.pointerType === 'touch',
+ );
+ isSwipeSettle = settleHandle != null && isScrollContact(recognizer);
+ }
+ }
+
+ // While a finger holds a caught track, the browser's long-press text
+ // selection and callout stay off. In UIKit, the touch that stops a scroll
+ // view does not reach its content. The gesture system's shared lock is
+ // counted per element. So this lock and the gesture host's own lock for the
+ // same contact release in either order.
+ let releaseSelection: (() => void) | null = null;
+
+ function holdSelection(on: boolean): void {
+ if (on && releaseSelection == null && trackElement != null) {
+ if (locksSelectionFor(catcher.pointerType ?? 'touch')) {
+ releaseSelection = lockSelection([trackElement], null);
+ }
+ } else if (!on && releaseSelection != null) {
+ releaseSelection();
+ releaseSelection = null;
+ }
+ }
+
+ function onCatch(recognizer: LongPressGestureRecognizer): void {
+ if (recognizer.state === 'began') {
+ holdSelection(true);
+ clearCatchTimer();
+ caughtSettle = false;
+ catchTimer = setTimer(() => {
+ catchTimer = null;
+ if (settleHandle != null && !isDragging) {
+ stopSettle();
+ caughtSettle = true;
+ }
+ }, paging.catchStopMs);
+ return;
+ }
+ if (recognizer.state === 'ended' || recognizer.state === 'cancelled') {
+ holdSelection(false);
+ if (catchTimer != null) {
+ // Lifted before the catch took hold: the settle runs on.
+ clearCatchTimer();
+ return;
+ }
+ const wasCaught = caughtSettle;
+ caughtSettle = false;
+ if (
+ wasCaught &&
+ !isDragging &&
+ settleHandle == null &&
+ animator != null
+ ) {
+ // Held, then lifted without dragging: settle on the nearest page.
+ const position = presentation();
+ const next = releasePage(position, 0, nearestPage(position));
+ setTarget(next, 'drag', true);
+ settleFrom(position, 0, catcher.pointerType === 'touch');
+ }
+ }
+ }
+
+ function goTo(index: number, goToOptions: GoToOptions = {}): void {
+ if (goToOptions.reason === 'controlled' && deferDepth === 0) {
+ // The owner's own move: what it calls back waits for a frame.
+ deferringCallbacks(() => goTo(index, goToOptions));
+ return;
+ }
+ const {animated = true, reason = 'goTo'} = goToOptions;
+ let next = Math.round(index);
+ if (isLooping()) {
+ next = nearestLoopCopy(next, target, count());
+ } else {
+ next = clampIndex(next);
+ }
+ if (isDragging) {
+ suppressCancelSettle = true;
+ isDragging = false;
+ pan.cancel();
+ }
+ const from = presentation();
+ // A move this one retargets hands on its velocity, from its curve.
+ const velocity =
+ settleHandle != null && animator != null
+ ? sign() * animator.getVelocity('x')
+ : undefined;
+ if (reason === 'controlled') {
+ dropReport();
+ }
+ stopSettle();
+ setTarget(next, reason);
+ const to = offsetOf(next);
+ if (!animated || animator == null || from === to) {
+ animator?.set({x: positionToX(to)});
+ rest();
+ return;
+ }
+ play(
+ solveAnimatedPageScroll({
+ from,
+ to,
+ durationMs: resolveMotion(
+ trackElement,
+ paging.animatedScroll,
+ 'durationMs',
+ ),
+ curve: resolveMotion(trackElement, paging.animatedScroll.curve),
+ velocity,
+ }),
+ );
+ }
+
+ function setOptions(update: Partial<PagerOptions>): void {
+ deferringCallbacks(() => applyOptions(update));
+ }
+
+ function applyOptions(update: Partial<PagerOptions>): void {
+ const wasLooping = isLooping();
+ const wasChildPages = isChildPages();
+ const previousCount = count();
+ const previousOffset = offsetOf(target);
+ // A loop's indexes are unbounded. So the page shown and the page last at
+ // rest are read under the old count, before the options change.
+ const shownBefore = wasLooping ? mod(target, previousCount) : target;
+ const settledBefore = wasLooping ? mod(settled, previousCount) : settled;
+ options = {...options, ...update};
+ if (isChildPages() !== wasChildPages) {
+ syncTrackObserver();
+ }
+ if (isChildPages() && viewport != null && !isDragging) {
+ // The children may have changed with the options (a count, a gap).
+ const offsets = measureChildOffsets();
+ if (!sameOffsets(offsets, childOffsets)) {
+ childOffsets = offsets;
+ const pageCount = offsets.length;
+ deliver(() => options.onPagesChange?.(pageCount));
+ }
+ }
+ if (
+ (wasLooping || isLooping()) &&
+ (wasLooping !== isLooping() || count() !== previousCount)
+ ) {
+ if (target < 0 || target > Math.min(previousCount, count()) - 1) {
+ rewrap(shownBefore, settledBefore);
+ return;
+ }
+ // The target's slot shows the same page. Only the page last at rest
+ // can be a virtual index, so it is read under the old count.
+ settled = settledBefore;
+ }
+ if (!isLooping() && (target < 0 || target > count() - 1)) {
+ // A smaller `count` clamps.
+ goTo(clampIndex(target), {animated: false, reason: 'controlled'});
+ return;
+ }
+ if (offsetOf(target) !== previousOffset && !isDragging) {
+ // A new gap (or children): the target page at its new offset (a settle
+ // ends there).
+ const wasSettling = settleHandle != null;
+ stopSettle();
+ animator?.set({x: positionToX(offsetOf(target))});
+ if (wasSettling || settled !== target) {
+ rest();
+ }
+ }
+ }
+
+ /**
+ * Turning `loop` off, or a loop's new count, where the target's slot now
+ * shows another page. The page shown keeps its index, and a smaller count
+ * clamps it. A release's waiting report names its page under the old count.
+ * It reaches the owner only while that page exists.
+ */
+ function rewrap(shownBefore: number, settledBefore: number): void {
+ const next = Math.min(shownBefore, count() - 1);
+ const waiting = pendingReport;
+ pendingReport = null;
+ if (isDragging) {
+ suppressCancelSettle = true;
+ isDragging = false;
+ pan.cancel();
+ }
+ const wasSettling = settleHandle != null;
+ stopSettle();
+ if (waiting != null && shownBefore === next) {
+ target = next;
+ report(waiting);
+ }
+ setTarget(next, 'controlled');
+ animator?.set({x: positionToX(offsetOf(next))});
+ settled = next;
+ if (wasSettling || settledBefore !== next) {
+ deliver(() => options.onSettle?.(next, settledBefore));
+ }
+ }
+
+ let detachAll: (() => void) | null = null;
+ // What a detach carries to the next attach: a release's report that still
+ // waits, and whether the detach stopped a motion before the track rested.
+ let carriedReport: PagerChangeReason | null = null;
+ let carriedEnd = false;
+
+ // Children pages also move when the track's own size changes, as when a
+ // child is added, removed or resized. So the track is observed while the
+ // pages are its children, from the attach or the options change that makes
+ // them so.
+ let unobserveTrack: () => void = () => {};
+ function syncTrackObserver(): void {
+ unobserveTrack();
+ unobserveTrack =
+ isChildPages() && trackElement != null && detachAll != null
+ ? observeResize(trackElement, measure)
+ : () => {};
+ }
+
+ function attach(nextViewport: HTMLElement, nextTrack: HTMLElement) {
+ detachAll?.();
+ view = nextViewport.ownerDocument.defaultView;
+ viewport = nextViewport;
+ trackElement = nextTrack;
+ animator = environment.animator ?? animatorFor(nextTrack);
+ pageWidth = 0;
+ isRtl = isRtlElement(nextViewport);
+ pageWidth = nextViewport.clientWidth;
+ if (isChildPages()) {
+ childOffsets = measureChildOffsets();
+ target = clampIndex(target);
+ settled = target;
+ }
+ animator.set({x: positionToX(offsetOf(target))});
+ // No pointer check: a mouse and a trackpad page it too.
+ const removePanListener = pan.addListener(onPan);
+ const removeCatchListener = catcher.addListener(onCatch);
+ const host = environment.host ?? getGestureHost(nextViewport.ownerDocument);
+ const detachPan = host.attach(nextViewport, pan);
+ // The catcher sits on the track, so its long-press styles (no callout, no
+ // selection) stay off the pages' text. The viewport's touch-action
+ // already covers the touches that land on the track.
+ const detachCatch = host.attach(nextTrack, catcher, {
+ manageStyle: false,
+ });
+ const detachGestures = () => {
+ detachCatch();
+ detachPan();
+ removeCatchListener();
+ removePanListener();
+ };
+ const unobserve = observeResize(nextViewport, measure);
+ detachAll = () => {
+ unobserve();
+ unobserveTrack();
+ unobserveTrack = () => {};
+ // A drag that the detach ends stays on its start page. The report and
+ // the end of a motion that the detach stops wait for the next attach,
+ // so an unmount calls nothing.
+ if (isDragging) {
+ suppressCancelSettle = true;
+ }
+ deferringCallbacks(() => detachGestures());
+ suppressCancelSettle = false;
+ carriedReport = pendingReport;
+ carriedEnd = target !== settled;
+ dropReport();
+ stopSettle();
+ dropDeferred();
+ holdSelection(false);
+ isDragging = false;
+ detachAll = null;
+ };
+ syncTrackObserver();
+ // A motion that the last detach stopped ends here: its report, if it
+ // still waited, and its onSettle go out from a frame.
+ if (carriedEnd && target !== settled) {
+ const report = carriedReport;
+ deferringCallbacks(() => {
+ pendingReport = report;
+ rest();
+ });
+ }
+ carriedReport = null;
+ carriedEnd = false;
+ return () => detachAll?.();
+ }
+
+ return {
+ pan,
+ get index() {
+ return wrapped(target);
+ },
+ get virtualIndex() {
+ return target;
+ },
+ get pageCount() {
+ return count();
+ },
+ get isSettling() {
+ return settleHandle != null;
+ },
+ get isDragging() {
+ return isDragging;
+ },
+ presentation,
+ pageOffset: offsetOf,
+ nearestPage: (position: number) => clampIndex(nearestPage(position)),
+ goTo,
+ setOptions,
+ setPanEnabled(enabled: boolean) {
+ deferringCallbacks(() => pan.setEnabled(enabled));
+ },
+ attach,
+ dispose() {
+ detachAll?.();
+ },
+ };
+}
+
+export interface UsePagerOptions extends PagerOptions {
+ /** The gesture surface: the clipped box the pages show through. */
+ viewportRef: RefObject<HTMLElement | null>;
+ /** The row of pages the pager translates. */
+ trackRef: RefObject<HTMLElement | null>;
+ /**
+ * Controlled target page; a change animates to it (reason 'controlled'),
+ * and a page the pager reports that the owner does not take returns it
+ * here.
+ */
+ index?: number;
+ /** Live toggle for the pan; turning it off mid-drag cancels the drag. */
+ isPanEnabled?: boolean;
+}
+
+/**
+ * A pager on two elements. Callbacks are read through a ref, so passing new
+ * functions each render costs nothing; a gesture never renders.
+ *
+ * @example
+ * ```
+ * const pager = usePager({viewportRef, trackRef, count: photos.length, gap: 40,
+ * onIndexChange: setCounter});
+ * <div ref={viewportRef} style={{overflow: 'hidden'}}>
+ * <div ref={trackRef} style={{display: 'flex', gap: 40}}>…pages…</div>
+ * </div>
+ * ```
+ */
+export function usePager({
+ viewportRef,
+ trackRef,
+ index,
+ isPanEnabled = true,
+ ...options
+}: UsePagerOptions): Pager {
+ const latestRef = useRef(options);
+ // The controlled `index` of the last commit, read when the pager reports.
+ const indexRef = useRef(index);
+ // Syncs the callback and controlled-index refs with the newest render; the
+ // pager's callbacks read them.
+ useIsomorphicLayoutEffect(() => {
+ latestRef.current = options;
+ indexRef.current = index;
+ });
+ // Bumped when the pager reports a page while `index` is controlled. The
+ // render it causes is batched with the owner's own update. If the owner kept
+ // `index`, that render returns the pager to it (the controlled sync below).
+ const [reported, setReported] = useState(0);
+ const [pager] = useState(() =>
+ createPager({
+ ...options,
+ defaultIndex: index ?? options.defaultIndex,
+ onIndexChange: (i, reason) => {
+ latestRef.current.onIndexChange?.(i, reason);
+ if (indexRef.current != null) {
+ setReported(n => n + 1);
+ }
+ },
+ onSettle: (i, previous) => latestRef.current.onSettle?.(i, previous),
+ onPagesChange: pageCount => latestRef.current.onPagesChange?.(pageCount),
+ shouldBeginPan: direction =>
+ latestRef.current.shouldBeginPan?.(direction) ?? true,
+ }),
+ );
+
+ // Synchronizes the pager (the track's animation and the gesture host) with
+ // these props. A clamp it causes is not reported back (reason 'controlled').
+ const {count, gap, loop, pages} = options;
+ useIsomorphicLayoutEffect(() => {
+ pager.setOptions({count, gap, loop, pages});
+ }, [pager, count, gap, loop, pages]);
+
+ // Attaches the pager to the viewport and track nodes, and again whenever
+ // either node is replaced; detaches at unmount.
+ useAttachmentPair(
+ viewportRef,
+ trackRef,
+ (viewport, track) => pager.attach(viewport, track),
+ pager,
+ );
+
+ // Synchronizes the pan recognizer (the gesture host) with isPanEnabled; what
+ // a drag it ends calls back waits for the next frame, after this Effect.
+ useEffect(() => {
+ pager.setPanEnabled(isPanEnabled);
+ }, [pager, isPanEnabled]);
+
+ // Synchronizes the pager, an imperative system outside React (the track's
+ // animation and its gesture recognizers), with a controlled `index`. A new
+ // `index` moves the pager there. So does the render after a page that it
+ // reported and the owner did not take, such as a refused swipe. A
+ // controlled input returns to its value the same way. The move is the
+ // owner's own, so it is not reported back. It moves only while the two
+ // differ.
+ useEffect(() => {
+ if (index != null && index !== pager.index) {
+ pager.goTo(index, {reason: 'controlled'});
+ }
+ }, [pager, index, reported]);
+
+ return pager;
+}
diff --git a/packages/core/src/motion/paging.test.ts b/packages/core/src/motion/paging.test.ts
index bb0e585a17..6a8a1cba90 100644
--- a/packages/core/src/motion/paging.test.ts
+++ b/packages/core/src/motion/paging.test.ts
@@ -386,8 +386,44 @@ describe('solveAnimatedPageScroll: setContentOffset(_:animated:)', () => {
}
});
- it('peaks at π/2 times the average speed halfway', () => {
+ // spec:AST-094 FR6: a new target keeps the current velocity (UIKit's
+ // setContentOffset drops it).
+ it('a retarget starts at the velocity it was handed and still ends on the target, at rest, on time', () => {
+ for (const velocity of [900, -900, 0]) {
+ const curve = solveAnimatedPageScroll({from: 100, to: 804, velocity});
+ expect(curve.at(0)).toBe(100);
+ expect(curve.velocity(0)).toBe(velocity);
+ expect(curve.velocity(1e-4)).toBeCloseTo(velocity, -1);
+ expect(curve.at(0.3)).toBe(804);
+ expect(curve.velocity(0.3)).toBe(0);
+ expect(curve.velocity(0.2999)).toBeCloseTo(0, -1);
+ }
+ });
+
+ it('peaks at π/2 times the average speed halfway (the sinusoid, to 0.2 %)', () => {
+ const curve = solveAnimatedPageScroll({from: 0, to: 402});
+ expect(curve.velocity(0.15) / ((Math.PI / 2) * (402 / 0.3))).toBeCloseTo(
+ 1,
+ 2,
+ );
+ });
+
+ it('follows the sinusoid to 0.02 % of the distance', () => {
const curve = solveAnimatedPageScroll({from: 0, to: 402});
- expect(curve.velocity(0.15)).toBeCloseTo((Math.PI / 2) * (402 / 0.3), 6);
+ for (let t = 0; t <= 0.3; t += 0.01) {
+ const sine = (402 * (1 - Math.cos((Math.PI * t) / 0.3))) / 2;
+ expect(Math.abs(curve.at(t) - sine)).toBeLessThan(0.1);
+ }
+ });
+
+ it("takes a theme's duration and curve", () => {
+ const curve = solveAnimatedPageScroll({
+ from: 0,
+ to: 100,
+ durationMs: 500,
+ curve: [0, 0, 1, 1],
+ });
+ expect(curve.duration).toBe(0.5);
+ expect(curve.at(0.25)).toBeCloseTo(50, 1);
});
});
diff --git a/packages/core/src/motion/paging.ts b/packages/core/src/motion/paging.ts
index 77dce46938..2cd978c7c4 100644
--- a/packages/core/src/motion/paging.ts
+++ b/packages/core/src/motion/paging.ts
@@ -6,7 +6,7 @@
* paging constants
* @output Exports `pagingSettleVelocity`, `solvePaging` (UIKit's paging settle
* as a curve the animator plays) and `solveAnimatedPageScroll`
- * @position Pure math, with no DOM and no React
+ * @position Pure math, with no DOM and no React; hooks/usePager.ts reads it
*
* SYNC: When modified, update:
* - /packages/core/src/motion/paging.test.ts
@@ -14,6 +14,7 @@
*/
import type {MotionCurve} from './animator';
+import {cubicBezier, type BezierPoints} from './bezier';
import {paging} from './uikit/paging';
/**
@@ -106,33 +107,55 @@ export function solvePaging({
}
/**
- * `setContentOffset(_:animated:)`: `paging.animatedScroll.duration` on a
- * sinusoidal ease-in-out, whatever the distance. UIKit starts it from the
- * current offset and drops any velocity, as here.
+ * `setContentOffset(_:animated:)`: `paging.animatedScroll.durationMs` on its
+ * curve, from the current offset, at any distance. The pager passes the
+ * duration and curve that `resolveMotion` gives, which are the measured values
+ * of the table.
+ *
+ * `velocity` (px/s) is the velocity of a move that this one retargets. The new
+ * curve starts at it and still ends on `to`, at rest and on time. A new target
+ * keeps the current velocity, where UIKit drops it. The carry is a Hermite
+ * term, v × duration × u(1 − u)², less the curve's own starting slope. So a
+ * move from rest is the curve itself.
*/
export function solveAnimatedPageScroll({
from,
to,
+ durationMs = paging.animatedScroll.durationMs,
+ curve = paging.animatedScroll.curve,
+ velocity,
}: {
from: number;
to: number;
+ durationMs?: number;
+ curve?: BezierPoints;
+ velocity?: number;
}): MotionCurve {
- const {duration} = paging.animatedScroll;
+ const duration = durationMs / 1000;
const distance = to - from;
+ const ease = cubicBezier(curve);
+ const progress = (u: number) => ease(Math.min(1, Math.max(0, u)));
+ // The carry, in px: the retargeted velocity over the whole duration, less
+ // what the curve's own starting slope already gives.
+ const startSlope = progress(1e-4) / 1e-4;
+ const carry =
+ velocity == null ? 0 : velocity * duration - distance * startSlope;
+ const at = (t: number) => {
+ const u = Math.min(1, Math.max(0, t / duration));
+ return from + distance * progress(u) + carry * u * (1 - u) * (1 - u);
+ };
return {
duration,
- at: t => {
- const u = Math.min(1, Math.max(0, t / duration));
- return from + (distance * (1 - Math.cos(Math.PI * u))) / 2;
- },
+ at,
velocity: t => {
- if (t <= 0 || t >= duration) {
+ if (t <= 0) {
+ return velocity ?? 0;
+ }
+ if (t >= duration) {
return 0;
}
- return (
- ((distance * Math.PI) / (2 * duration)) *
- Math.sin((Math.PI * t) / duration)
- );
+ const h = Math.min(1e-4, t / 2, (duration - t) / 2);
+ return (at(t + h) - at(t - h)) / (2 * h);
},
};
}
diff --git a/packages/core/src/motion/uikit/paging.ts b/packages/core/src/motion/uikit/paging.ts
index 7448fec409..e4109c88f8 100644
--- a/packages/core/src/motion/uikit/paging.ts
+++ b/packages/core/src/motion/uikit/paging.ts
@@ -3,7 +3,8 @@
/**
* @file paging.ts
* @input Nothing; data only
- * @output Exports `paging`, the measured constants of a paging UIScrollView
+ * @output Exports `paging`, the measured constants of a paging UIScrollView,
+ * and `registerPagingTable`, which registers them with the motion registry
* @position The paging domain of the UIKit constants table (motion/uikit). Only
* core reads it, so the `uikit` namespace does not re-export it
*
@@ -12,6 +13,8 @@
* - /packages/core/src/motion/paging.ts and paging.test.ts
*/
+import {registerMotionTable} from '../roles';
+
export const paging = {
/**
* After the lift, one model moves the content: the settle onto the chosen
@@ -70,7 +73,8 @@ export const paging = {
release: {
/**
* Released slower than `advanceSpeed`, the scroll view settles on the page
- * nearest the content position: past half a page, the next one.
+ * nearest the content position: past half a page, the next one. The pager
+ * keeps the start page instead for a release that moves back toward it.
* @source measured: UIKit lab, iOS 26.2 simulator, Oct 23 2026. In releases
* at rest from page 1, content at 48.5 % of the page stays, and 57.5 %
* goes to the next page. On a second 402 pt pager, 45 % stays and 55 %
@@ -121,9 +125,9 @@ export const paging = {
*/
catchStopMs: 85,
/**
- * A horizontal pager's pan begins only for a drag within atan(1 ÷ this) of
- * horizontal (26.6° for 2). A steeper drag goes to the vertical scroll around
- * it. Between 26.6° and 45°, neither moves.
+ * In a sheet, a horizontal pager's pan begins only for a drag within atan(1 ÷
+ * this) of horizontal (26.6° for 2). A steeper drag goes to the sheet.
+ * Between 26.6° and 45°, neither moves.
* @source measured: UIKit lab, iOS 26.2 simulator, Oct 23 2026. A scroll
* view's directional lock holds the major axis up to 25° and frees it from
* 30°. An inline calendar pager in a sheet pages at 20° from horizontal. At
@@ -131,23 +135,36 @@ export const paging = {
* the sheet.
*/
panAxisRatio: 2,
+ /**
+ * Inside a vertical scroll view, exactly one of the pager and the scroll view
+ * takes a drag, decided once by its dominant axis. The pager takes it when
+ * |dx| ≥ this × |dy|, 45° and the tie included. The scroll view takes any
+ * other drag.
+ * @source measured: UIKit lab, iOS 26.2 simulator, Oct 24 2026. A 402 × 300
+ * paging view sits in a full-screen vertical scroll view, with 150 pt drags
+ * at 0–90°. The pager takes 0–45°, and the page takes 50–90°. At 35°, the
+ * outer view stays at 0 through 86 pt of vertical travel. The choice
+ * happens at 10–15 pt of travel.
+ */
+ nestedPanAxisRatio: 1,
animatedScroll: {
/**
- * `setContentOffset(_:animated:)` duration. It is the same for one page and
- * for five, as for a page control's tap.
+ * `setContentOffset(_:animated:)` duration in milliseconds. It is the same
+ * for one page and for five, as for a page control's tap.
* @source measured: UIKit lab, iOS 26.2 simulator, Oct 23 2026.
* `_contentOffsetAnimationDuration` reads 0.3, and five animated moves of
* 1 to 5 pages each last 0.30 s.
*/
- duration: 0.3,
+ durationMs: 300,
/**
* Its curve is a sinusoidal ease-in-out: x = from + (to − from) · (1 − cos
- * πu) ÷ 2, for u = t ÷ duration.
+ * πu) ÷ 2, for u = t ÷ duration. This cubic bézier matches it to 0.02 % of
+ * the distance (0.09 pt over a 402 pt page).
* @source measured: UIKit lab, iOS 26.2 simulator, Oct 23 2026. The five
* moves fit the sinusoid to 0.14–0.51 pt RMS, and a 2010 pt move fits to
* 0.20 pt. The curve easeInEaseOut (0.42, 0, 0.58, 1) misses by 7.7 pt.
*/
- curve: 'sineInOut',
+ curve: [0.364212, 0, 0.635788, 1],
},
/**
* Past the first or last page, the content follows the finger through the
@@ -160,3 +177,17 @@ export const paging = {
*/
rubberBandDimension: 'pageWidth',
} as const;
+
+/**
+ * Registers this table with the motion registry (motion/roles.ts). The pager
+ * then reads `setContentOffset(_:animated:)`'s duration and curve through
+ * `resolveMotion`, as it reads every touch motion. The table lists no role,
+ * because no motion role names any of its values, so each plays as measured.
+ * Nothing registers on import, and a second call does nothing.
+ */
+export function registerPagingTable(): void {
+ registerMotionTable('paging', paging, {
+ // Who gets the touch, not how anything moves.
+ exclude: ['catchStopMs'],
+ });
+}
diff --git a/packages/core/src/motion/uikit/tableImports.test.ts b/packages/core/src/motion/uikit/tableImports.test.ts
index 65b1986f52..4896356b06 100644
--- a/packages/core/src/motion/uikit/tableImports.test.ts
+++ b/packages/core/src/motion/uikit/tableImports.test.ts
@@ -17,8 +17,8 @@ import {dirname, join, relative, resolve} from 'node:path';
import {describe, expect, it} from 'vitest';
/**
- * The tables shared code may read. The animator and gestures read these, and
- * the paging math reads paging.
+ * The tables shared code may read. The animator and gestures read these. The
+ * paging math and the pager, one hook for every paging component, read paging.
*/
const SHARED_TABLES = new Set([
'motion/uikit/gestures.ts',