An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): PageControl, UIPageControl's indicators: a tap steps a page, a finger scrubs, every pointer pages (#9684)
Christopher Chedeau0cc54070077c
diff --git a/.changeset/cli-discover-page-control.md b/.changeset/cli-discover-page-control.mdnew file mode 100644index 0000000000..6807ce1396--- /dev/null+++ b/.changeset/cli-discover-page-control.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx discover` lists the experimental PageControl component from `@astryxdesign/lab`.++@vjeuxdiff --git a/apps/storybook/stories/PageControl.stories.tsx b/apps/storybook/stories/PageControl.stories.tsxnew file mode 100644index 0000000000..a8e6ab662c--- /dev/null+++ b/apps/storybook/stories/PageControl.stories.tsx@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import * as stylex from '@stylexjs/stylex';+import {PageControl} from '@astryxdesign/lab';+import {+ colorVars,+ radiusVars,+ spacingVars,+ typographyVars,+} from '@astryxdesign/core/theme/tokens.stylex';++const styles = stylex.create({+ stack: {+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: spacingVars['--spacing-3'],+ padding: spacingVars['--spacing-6'],+ fontFamily: typographyVars['--font-family-body'],+ },+ page: {+ width: 280,+ height: 160,+ display: 'grid',+ placeItems: 'center',+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-background-muted'],+ color: colorVars['--color-text-primary'],+ fontSize: 20,+ fontWeight: 600,+ },+});++const meta: Meta<typeof PageControl> = {+ title: 'Lab/PageControl',+ component: PageControl,+ parameters: {layout: 'centered'},+};++export default meta;+type Story = StoryObj<typeof PageControl>;++function Paged({totalPages, start = 1}: {totalPages: number; start?: number}) {+ const [page, setPage] = useState(start);+ return (+ <div {...stylex.props(styles.stack)}>+ <div {...stylex.props(styles.page)} data-testid="page">+ Page {page}+ </div>+ <PageControl totalPages={totalPages} page={page} onChange={setPage} />+ </div>+ );+}++export const Default: Story = {+ render: () => <Paged totalPages={5} start={3} />,+};++export const ManyPages: Story = {+ name: 'Many Pages (50)',+ render: () => <Paged totalPages={50} start={26} />,+};++export const SinglePageHidden: Story = {+ name: 'Single Page (hidesForSinglePage)',+ render: () => (+ <PageControl+ totalPages={1}+ page={1}+ onChange={() => {}}+ hidesForSinglePage+ />+ ),+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 897cd88208..8a7022a404 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -632,6 +632,11 @@"path": "components/lab/navigation-stack","aliases": []},+ {+ "name": "component-lab-page-control",+ "path": "components/lab/page-control",+ "aliases": []+ },{"name": "component-lab-radial-chart","path": "components/lab/radial-chart",diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.jsonindex c409650e1d..9351ed525a 100644--- a/packages/cli/assets/discover/official-packages.json+++ b/packages/cli/assets/discover/official-packages.json@@ -152,6 +152,10 @@"kind": "component","name": "NavigationStack"},+ {+ "kind": "component",+ "name": "PageControl"+ },{"kind": "component","name": "RadialChart"diff --git a/packages/lab/src/PageControl/PageControl.doc.mjs b/packages/lab/src/PageControl/PageControl.doc.mjsnew file mode 100644index 0000000000..632148f6b5--- /dev/null+++ b/packages/lab/src/PageControl/PageControl.doc.mjs@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'PageControl',+ displayName: 'Page Control',+ category: 'Navigation',+ keywords: [+ 'page control',+ 'page indicator',+ 'pager dots',+ 'dots',+ 'carousel dots',+ 'onboarding',+ 'paging',+ ],+ description:+ 'A row of page indicators under a paging view, as on iOS: one dot per page, the current one highlighted. A tap or a click to either side of the current dot moves one page that way, and sliding a finger or dragging the mouse across the dots scrubs straight to the page under it. Under a finger (any touch device, iOS and Android alike), with more than ten pages the row is a window whose edge dots shrink to show there is more, and a held finger shows a platter behind the dots; with a mouse a long row is cropped to the control. Experimental: lands in lab first.',+ props: [+ {+ name: 'totalPages',+ type: 'number',+ description: 'Number of pages.',+ required: true,+ },+ {+ name: 'page',+ type: 'number',+ description: 'Current page number (1-based). Page 1 is the first page.',+ required: true,+ },+ {+ name: 'onChange',+ type: '(page: number) => void',+ description:+ 'Called with the page, 1-based, that a tap, a click, a scrub, an arrow key, Home, End or an assistive technology asks for; a scrub calls it each time the page under the pointer changes, so a quick sweep can skip a page. Update the paging view and page together.',+ required: true,+ },+ {+ name: 'label',+ type: 'string',+ description:+ 'Names the control for assistive technology. Defaults to "Page indicators", localized.',+ },+ {+ name: 'hidesForSinglePage',+ type: 'boolean',+ description: 'Render nothing when there is only one page.',+ default: 'false',+ },+ ],+ usage: {+ description:+ 'Use PageControl below a paging view, such as a Carousel with `hasSnap` or onboarding screens, to show how many pages there are and which one is showing. Keep its page in step with the view in both directions.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Pair it with a view that pages by swipe: the control is a secondary way to move and the main way to see where you are.',+ },+ {+ guidance: true,+ description:+ 'Keep pages few enough to count at a glance; past ten the row stays a fixed width, shows a window of them and scrolls as the page changes.',+ },+ {+ guidance: false,+ description:+ "Don't use it for long lists of results (use Pagination) or for choosing between views (use SegmentedControl or TabList).",+ },+ ],+ },+};diff --git a/packages/lab/src/PageControl/PageControl.test.tsx b/packages/lab/src/PageControl/PageControl.test.tsxnew file mode 100644index 0000000000..29450338ef--- /dev/null+++ b/packages/lab/src/PageControl/PageControl.test.tsx@@ -0,0 +1,727 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PageControl.test.tsx+ * @input vitest (jsdom), Testing Library, PageControl+ * @output Proves the semantics, the keyboard, the measured geometry and+ * alphas, the width cap, the window it renders and hidesForSinglePage+ * @position Testing; the real-touch proofs are+ * __tests__/PageControl.interaction.browser.spec.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {createRef, useState} from 'react';+import {renderToString} from 'react-dom/server';+import {act, fireEvent, render, screen} from '@testing-library/react';+import {PageControl} from './PageControl';+import {SWITCH} from './pageControlModel';++/**+ * The pointer and the Reduce Motion setting a case runs under, read live by+ * every media query list the stub below returns. Core's gesture host asks for+ * its `(pointer: coarse)` list once, when the document's host is created. It+ * keeps that list for the whole file. A list that froze its answer would+ * carry the first case's pointer into every later case.+ */+const media: {pointer: 'default' | 'coarse' | 'fine'; reduced: boolean} = {+ pointer: 'default',+ reduced: false,+};++function matchesNow(query: string): boolean {+ if (media.pointer === 'default') {+ // As the shared test setup's polyfill answers: a mouse-driven desktop+ // that hovers.+ return /\(\s*hover\s*:\s*hover\s*\)/.test(query);+ }+ return (+ (media.pointer === 'coarse' && query.includes('pointer: coarse')) ||+ (media.pointer === 'fine' && query.includes('pointer: fine')) ||+ (media.reduced && query.includes('prefers-reduced-motion: reduce'))+ );+}++beforeEach(() => {+ media.pointer = 'default';+ media.reduced = false;+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ get matches() {+ return matchesNow(query);+ },+ media: query,+ onchange: null,+ addListener: vi.fn(),+ removeListener: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+});++/**+ * A finger: a coarse primary pointer, on any engine (one touch model; nothing+ * asks for iOS); `reduced` turns Reduce Motion on.+ */+function asTouch({reduced = false}: {reduced?: boolean} = {}) {+ media.pointer = 'coarse';+ media.reduced = reduced;+}++/** A mouse: a fine primary pointer, on any engine. */+function asMouse() {+ media.pointer = 'fine';+ media.reduced = false;+ // The case's pointer, as the control will read it.+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);+}++afterEach(() => {+ vi.unstubAllGlobals();+});++function renderControl(+ props: Partial<React.ComponentProps<typeof PageControl>> = {},+) {+ const onChange = vi.fn();+ const result = render(+ <PageControl totalPages={5} page={3} onChange={onChange} {...props} />,+ );+ return {onChange, ...result};+}++/**+ * A tap at `x` on `target`, through the gesture host's touch path. In jsdom,+ * boxes are 0 px wide, so any x > 0 is the trailing side of the current dot.+ */+function tap(target: Element, x: number) {+ for (const type of ['touchstart', 'touchend'] as const) {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const contact = {identifier: 1, clientX: x, clientY: 10, target};+ Object.defineProperty(event, 'changedTouches', {value: [contact]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [contact],+ });+ target.dispatchEvent(event);+ }+}++/**+ * A finger's swipe on `target` from `from` to `to` through the gesture host's+ * touch path, in `steps` moves. Returns whether any move was cancelled: a+ * cancelled move is one the page cannot scroll with.+ */+function swipe(+ target: Element,+ from: {x: number; y: number},+ to: {x: number; y: number},+ steps = 10,+): boolean {+ let cancelled = false;+ const send = (+ type: 'touchstart' | 'touchmove' | 'touchend',+ point: {x: number; y: number},+ ) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const contact = {identifier: 1, clientX: point.x, clientY: point.y, target};+ Object.defineProperty(event, 'changedTouches', {value: [contact]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [contact],+ });+ target.dispatchEvent(event);+ if (type === 'touchmove' && event.defaultPrevented) {+ cancelled = true;+ }+ };+ send('touchstart', from);+ for (let i = 1; i <= steps; i++) {+ send('touchmove', {+ x: from.x + ((to.x - from.x) * i) / steps,+ y: from.y + ((to.y - from.y) * i) / steps,+ });+ }+ send('touchend', to);+ return cancelled;+}++/** A mouse pointer event at `x` for the gesture host (jsdom has no PointerEvent). */+function mouse(+ target: Element,+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ x: number,+ pointerType: 'mouse' | 'pen' = 'mouse',+) {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const fields: Record<string, unknown> = {+ pointerType,+ pointerId: 1,+ isPrimary: true,+ button: 0,+ buttons: type === 'pointerup' ? 0 : 1,+ clientX: x,+ clientY: 10,+ };+ for (const [key, value] of Object.entries(fields)) {+ Object.defineProperty(event, key, {value});+ }+ target.dispatchEvent(event);+}++/**+ * A mouse's click at `x`, pressed at `fromX`. The press and release reach the+ * gesture host, which listens to every pointer. The browser sends its click+ * after them.+ */+function click(target: Element, x: number, fromX = x) {+ mouse(target, 'pointerdown', fromX);+ if (x !== fromX) {+ mouse(target, 'pointermove', x);+ }+ mouse(target, 'pointerup', x);+ fireEvent.click(target, {clientX: x, clientY: 10});+}++/**+ * Lays the row out for jsdom: page `i`'s dot 10 px wide at 100 + 16·i, the+ * control from 80 to 280.+ */+function layOutRow() {+ return vi+ .spyOn(Element.prototype, 'getBoundingClientRect')+ .mockImplementation(function (this: Element) {+ const page = this.getAttribute('data-page');+ if (page != null) {+ return new DOMRect(100 + 16 * Number(page), 0, 10, 10);+ }+ if (this.getAttribute('role') === 'slider') {+ return new DOMRect(80, 0, 200, 30);+ }+ return new DOMRect(0, 0, 0, 0);+ });+}++/** WCAG contrast of `fg` at `alpha` over `bg` against `bg`. */+function contrastOver(fg: number[], bg: number[], alpha: number): number {+ const luminance = (rgb: number[]) => {+ const [r, g, b] = rgb.map(value => {+ const v = value / 255;+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;+ });+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;+ };+ const mixed = fg.map((c, i) => c * alpha + bg[i] * (1 - alpha));+ return (luminance(bg) + 0.05) / (luminance(mixed) + 0.05);+}++describe('PageControl', () => {+ it('is one slider named "Page indicators" that reads "Page 3 of 5"', () => {+ renderControl();+ const slider = screen.getByRole('slider', {name: 'Page indicators'});+ expect(slider).toHaveAttribute('aria-valuemin', '1');+ expect(slider).toHaveAttribute('aria-valuemax', '5');+ expect(slider).toHaveAttribute('aria-valuenow', '3');+ expect(slider).toHaveAttribute('aria-valuetext', 'Page 3 of 5');+ expect(slider).toHaveAttribute('tabindex', '0');+ });++ it('takes a custom label', () => {+ renderControl({label: 'Onboarding'});+ expect(+ screen.getByRole('slider', {name: 'Onboarding'}),+ ).toBeInTheDocument();+ });++ it('arrow keys, Home and End ask for a page', () => {+ const {onChange} = renderControl();+ const slider = screen.getByRole('slider');+ fireEvent.keyDown(slider, {key: 'ArrowRight'});+ expect(onChange).toHaveBeenLastCalledWith(4);+ fireEvent.keyDown(slider, {key: 'ArrowLeft'});+ expect(onChange).toHaveBeenLastCalledWith(2);+ fireEvent.keyDown(slider, {key: 'ArrowUp'});+ expect(onChange).toHaveBeenLastCalledWith(4);+ fireEvent.keyDown(slider, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(2);+ fireEvent.keyDown(slider, {key: 'Home'});+ expect(onChange).toHaveBeenLastCalledWith(1);+ fireEvent.keyDown(slider, {key: 'End'});+ expect(onChange).toHaveBeenLastCalledWith(5);+ });++ it('mirrors the horizontal arrows in RTL', () => {+ const onChange = vi.fn();+ // jsdom does not inherit `direction`: set it on the control itself.+ render(+ <PageControl+ totalPages={5}+ page={3}+ onChange={onChange}+ style={{direction: 'rtl'}}+ />,+ );+ const slider = screen.getByRole('slider');+ fireEvent.keyDown(slider, {key: 'ArrowRight'});+ expect(onChange).toHaveBeenLastCalledWith(2);+ fireEvent.keyDown(slider, {key: 'ArrowLeft'});+ expect(onChange).toHaveBeenLastCalledWith(4);+ });++ it('asks for nothing past the first or last page', () => {+ const {onChange} = renderControl({page: 5});+ fireEvent.keyDown(screen.getByRole('slider'), {key: 'ArrowRight'});+ expect(onChange).not.toHaveBeenCalled();+ });++ it("draws UIPageControl's geometry: 9.67 px indicators, the current one opaque, the others at 48 % (UIKit's 45 % raised to 3:1)", () => {+ renderControl();+ const slider = screen.getByRole('slider');+ expect(slider.style.height).toBe('25.67px');+ expect(slider.style.width).toBe('108.35px');+ const indicators = Array.from(+ slider.querySelectorAll<HTMLElement>('[data-page]'),+ );+ expect(indicators).toHaveLength(5);+ // A 10 px box scaled to 9.67 px: round wherever it falls (see the browser+ // proof "every indicator paints round").+ expect(indicators[0].style.width).toBe('10px');+ // The animator writes `scale` as "x y".+ expect(Number.parseFloat(indicators[0].style.scale) * 10).toBeCloseTo(+ 9.67,+ 3,+ );+ expect(indicators.map(i => i.style.opacity)).toEqual([+ '0.48',+ '0.48',+ '1',+ '0.48',+ '0.48',+ ]);+ });++ it('never grows wider than 161.3 px; under a finger, with more than ten pages it renders the window around the current page', () => {+ asTouch();+ renderControl({totalPages: 50, page: 26});+ const slider = screen.getByRole('slider');+ expect(slider.style.width).toBe('161.3px');+ // `data-page` counts from 0. From page 1, page 26 (dot 25) sits in the+ // window's last full slot. The window starts at dot 18, with dots 20–25+ // full. Three slots on each side render for the slide.+ const dots = Array.from(+ slider.querySelectorAll<HTMLElement>('[data-page]'),+ i => Number(i.dataset.page),+ );+ expect(dots[0]).toBe(15);+ expect(dots[dots.length - 1]).toBe(30);+ });++ it('an Android finger (no -webkit-touch-callout) gets the window too: one touch model, no platform idiom', () => {+ asTouch();+ vi.stubGlobal('CSS', {supports: () => false});+ render(<PageControl totalPages={50} page={26} onChange={() => {}} />);+ const dots = screen+ .getByRole('slider')+ .querySelectorAll<HTMLElement>('[data-page]');+ // The window and its render margin, not the full row of 50.+ expect(dots.length).toBeLessThan(50);+ });++ it('with a mouse, a long control is the full row of pages, cropped', () => {+ asMouse();+ renderControl({totalPages: 50, page: 26});+ const slider = screen.getByRole('slider');+ expect(slider.style.width).toBe('161.3px');+ const dots = Array.from(+ slider.querySelectorAll<HTMLElement>('[data-page]'),+ );+ expect(dots).toHaveLength(50);+ // No fades and no shrinking slots with a mouse.+ expect(dots.every(dot => dot.style.transition === 'none')).toBe(true);+ });++ // Touch motion stays internal: no theme role, so no variable retunes it.+ it("under a finger, the old indicator fades on the table's measured 250 ms and curve, and a --motion-page-control-… variable changes nothing", () => {+ asTouch();+ const onChange = vi.fn();+ const themed = (value: number) => (+ <div+ data-astryx-theme="page-control-test"+ style={+ {+ '--motion-page-control-fade-out-ms': '500ms',+ '--motion-page-control-fade-out-curve': 'cubic-bezier(0, 0, 1, 1)',+ } as React.CSSProperties+ }>+ <PageControl totalPages={5} page={value} onChange={onChange} />+ </div>+ );+ const {rerender} = render(themed(3));+ const old = screen+ .getByRole('slider')+ .querySelector<HTMLElement>('[data-page="2"]') as HTMLElement;+ // Every transition written to the old indicator, in order.+ const observer = new MutationObserver(() => {});+ observer.observe(old, {+ attributes: true,+ attributeFilter: ['style'],+ attributeOldValue: true,+ });+ rerender(themed(4));+ const written = [+ ...observer.takeRecords().map(record => record.oldValue ?? ''),+ old.getAttribute('style') ?? '',+ ].map(style => /transition:\s*([^;]+)/.exec(style)?.[1].trim());+ observer.disconnect();+ expect(written).toContain('opacity 0.25s cubic-bezier(0, 0, 0.58, 1)');+ // Once the fade starts, the dot's next change is a switch again.+ expect(old.style.transition).toBe(SWITCH);+ });++ it('under a finger and Reduce Motion, the current indicator changes at once, with no fade, whatever the theme (design:reduced-motion DR2)', () => {+ asTouch({reduced: true});+ const onChange = vi.fn();+ const themed = (value: number) => (+ <div+ style={+ {+ '--motion-page-control-fade-out-ms': '500ms',+ } as React.CSSProperties+ }>+ <PageControl totalPages={5} page={value} onChange={onChange} />+ </div>+ );+ const {rerender} = render(themed(3));+ rerender(themed(4));+ const dots = Array.from(+ screen.getByRole('slider').querySelectorAll<HTMLElement>('[data-page]'),+ );+ expect(dots.length).toBe(5);+ for (const dot of dots) {+ expect(dot.style.transition).toBe('none');+ }+ });++ it('under a finger and Reduce Motion, a held finger’s platter and the dots’ dimming show at once and hide on the policy’s fade (design:reduced-motion DR2)', () => {+ vi.useFakeTimers();+ try {+ asTouch({reduced: true});+ renderControl();+ const slider = screen.getByRole('slider');+ const reduced = 'opacity 0.2s cubic-bezier(0.42, 0, 0.58, 1)';+ const fadeOfLook = () => ({+ platter: slider.style.getPropertyValue(+ '--_page-control-platter-transition',+ ),+ dots: Array.from(+ slider.querySelectorAll<HTMLElement>('[data-page]'),+ dot => dot.style.transition,+ ),+ });+ const touch = (type: 'touchstart' | 'touchend') => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const contact = {+ identifier: 1,+ clientX: 1,+ clientY: 10,+ target: slider,+ };+ Object.defineProperty(event, 'changedTouches', {value: [contact]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [contact],+ });+ slider.dispatchEvent(event);+ };+ touch('touchstart');+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(slider.hasAttribute('data-interacting')).toBe(true);+ expect(fadeOfLook()).toEqual({+ platter: 'none',+ dots: Array.from({length: 5}, () => 'none'),+ });+ act(() => {+ touch('touchend');+ });+ expect(slider.hasAttribute('data-interacting')).toBe(false);+ expect(fadeOfLook()).toEqual({+ platter: reduced,+ dots: Array.from({length: 5}, () => reduced),+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it('with a mouse, a click on the trailing side of the current dot asks for the next page, on the leading side for the previous', () => {+ asMouse();+ const {onChange} = renderControl();+ click(screen.getByRole('slider'), 50);+ expect(onChange).toHaveBeenLastCalledWith(4);+ click(screen.getByRole('slider'), -50);+ expect(onChange).toHaveBeenLastCalledWith(2);+ });++ // Input takes every pointer. The touch presentation (the window, the+ // platter, the fades) stays on a coarse pointer.+ it('with a mouse, a press and release on the trailing side ask for the next page through the tap recognizer, before any click', () => {+ asMouse();+ const {onChange} = renderControl();+ const slider = screen.getByRole('slider');+ mouse(slider, 'pointerdown', 50);+ mouse(slider, 'pointerup', 50);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(4);+ });++ it('with a mouse, a tap pages once: the click the browser sends after it does not page again', () => {+ asMouse();+ const {onChange} = renderControl();+ click(screen.getByRole('slider'), 50);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(4);+ });++ it('with a mouse, a drag scrubs: the page follows the pointer to the dot under it (spec:AST-094 FR43)', () => {+ asMouse();+ const rects = layOutRow();+ try {+ const {onChange} = renderControl();+ const slider = screen.getByRole('slider');+ // Pressed on page 3's dot (centre 137), dragged to page 5's (169).+ mouse(slider, 'pointerdown', 137);+ for (let i = 1; i <= 8; i++) {+ mouse(slider, 'pointermove', 137 + 4 * i);+ }+ mouse(slider, 'pointerup', 169);+ expect(onChange).toHaveBeenCalledWith(4);+ expect(onChange).toHaveBeenLastCalledWith(5);+ } finally {+ rects.mockRestore();+ }+ });++ it('with a mouse, a scrub on a cropped long row holds the row still until the lift, so the page stays the dot under the pointer', () => {+ asMouse();+ const rects = layOutRow();+ try {+ function Owner() {+ const [page, setPage] = useState(6);+ return <PageControl totalPages={50} page={page} onChange={setPage} />;+ }+ render(<Owner />);+ const slider = screen.getByRole('slider');+ const strip = slider.children[0] as HTMLElement;+ const rest = strip.style.translate;+ // Pressed on page 6's dot (centre 185), dragged three dots on. Each+ // event commits its render, as a browser's would.+ act(() => mouse(slider, 'pointerdown', 185));+ for (let i = 1; i <= 12; i++) {+ act(() => mouse(slider, 'pointermove', 185 + 4 * i));+ expect(strip.style.translate).toBe(rest);+ }+ expect(Number(slider.getAttribute('aria-valuenow'))).toBe(9);+ act(() => mouse(slider, 'pointerup', 233));+ expect(strip.style.translate).not.toBe(rest);+ } finally {+ rects.mockRestore();+ }+ });++ it('with a pen, a press and release on the trailing side ask for the next page', () => {+ asMouse();+ const {onChange} = renderControl();+ const slider = screen.getByRole('slider');+ mouse(slider, 'pointerdown', 50, 'pen');+ mouse(slider, 'pointerup', 50, 'pen');+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(4);+ });++ it('with a pen, a drag scrubs: the page follows the pen to the dot under it', () => {+ asMouse();+ const rects = layOutRow();+ try {+ const {onChange} = renderControl();+ const slider = screen.getByRole('slider');+ // Pressed on page 3's dot (centre 137), dragged to page 5's (169).+ mouse(slider, 'pointerdown', 137, 'pen');+ for (let i = 1; i <= 8; i++) {+ mouse(slider, 'pointermove', 137 + 4 * i, 'pen');+ }+ mouse(slider, 'pointerup', 169, 'pen');+ expect(onChange).toHaveBeenCalledWith(4);+ expect(onChange).toHaveBeenLastCalledWith(5);+ } finally {+ rects.mockRestore();+ }+ });++ it('under a coarse pointer, an invisible hit area grows the 25.67 px tall control toward 44 px', () => {+ asTouch();+ let reveal: ((entries: IntersectionObserverEntry[]) => void) | null = null;+ const frames: Array<() => void> = [];+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ constructor(callback: (entries: IntersectionObserverEntry[]) => void) {+ reveal = callback;+ }+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ vi.stubGlobal('requestAnimationFrame', (run: () => void) => {+ frames.push(run);+ return frames.length;+ });+ vi.stubGlobal('cancelAnimationFrame', () => {});+ renderControl();+ const slider = screen.getByRole('slider');+ slider.getBoundingClientRect = () => new DOMRect(100, 100, 108.33, 25.67);+ act(() => {+ reveal?.([+ {+ target: slider,+ isIntersecting: true,+ } as unknown as IntersectionObserverEntry,+ ]);+ for (const run of frames.splice(0)) {+ run();+ }+ });+ const inset = (side: string) =>+ Number.parseFloat(+ slider.style.getPropertyValue(`--astryx-hit-inset-${side}`),+ );+ expect(inset('top')).toBeCloseTo((44 - 25.67) / 2, 1);+ expect(inset('bottom')).toBeCloseTo((44 - 25.67) / 2, 1);+ expect(inset('left')).toBe(0);+ expect(inset('right')).toBe(0);+ });++ it('with a mouse, a press held past 155 ms shows no platter and dims nothing: the held look is the touch presentation', () => {+ vi.useFakeTimers();+ try {+ asMouse();+ renderControl();+ const slider = screen.getByRole('slider');+ const dot = slider.querySelector('[data-page="0"]') as HTMLElement;+ const restOpacity = dot.style.opacity;+ mouse(slider, 'pointerdown', 50);+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(slider.hasAttribute('data-interacting')).toBe(false);+ expect(dot.style.opacity).toBe(restOpacity);+ mouse(slider, 'pointerup', 50);+ } finally {+ vi.useRealTimers();+ }+ });++ // A recognizer that competes with the page's scroll decides within 10 px.+ // So a swipe that starts vertical is the page's.+ it("under a finger, a vertical swipe that starts on the dots pages nothing and leaves every move to the page's scroll", () => {+ asTouch();+ const {onChange} = renderControl();+ const slider = screen.getByRole('slider');+ const cancelled = swipe(slider, {x: 50, y: 10}, {x: 52, y: -290}, 30);+ expect(cancelled).toBe(false);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('under a finger, the click the browser sends after a tap does not page again', () => {+ asTouch();+ const {onChange} = renderControl();+ const slider = screen.getByRole('slider');+ tap(slider, 50);+ fireEvent.click(slider, {clientX: 50, clientY: 10});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(4);+ });++ it('clicks work when the control first renders with no pages and the pages arrive later', () => {+ const onChange = vi.fn();+ const view = render(+ <PageControl totalPages={0} page={1} onChange={onChange} />,+ );+ view.rerender(<PageControl totalPages={5} page={3} onChange={onChange} />);+ click(screen.getByRole('slider'), 50);+ expect(onChange).toHaveBeenCalledWith(4);+ });++ it('a page the app declines can be asked for again', async () => {+ // The app keeps its value: no render follows onChange.+ const {onChange} = renderControl();+ click(screen.getByRole('slider'), 50);+ await new Promise(resolve => setTimeout(resolve, 0));+ click(screen.getByRole('slider'), 50);+ expect(onChange).toHaveBeenCalledTimes(2);+ fireEvent.keyDown(screen.getByRole('slider'), {key: 'ArrowRight'});+ expect(onChange).toHaveBeenCalledTimes(2);+ await new Promise(resolve => setTimeout(resolve, 0));+ fireEvent.keyDown(screen.getByRole('slider'), {key: 'ArrowRight'});+ expect(onChange).toHaveBeenCalledTimes(3);+ });++ it("a caller's onKeyDown runs first and can keep the page with preventDefault", () => {+ const onKeyDown = vi.fn((event: React.KeyboardEvent) => {+ if (event.key === 'End') {+ event.preventDefault();+ }+ });+ const {onChange} = renderControl({onKeyDown});+ const slider = screen.getByRole('slider');+ fireEvent.keyDown(slider, {key: 'ArrowRight'});+ expect(onKeyDown).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(4);+ fireEvent.keyDown(slider, {key: 'End'});+ expect(onKeyDown).toHaveBeenCalledTimes(2);+ expect(onChange).toHaveBeenCalledTimes(1);+ });++ it('forwards ref to the slider, and clicks still page with a ref passed', () => {+ const ref = createRef<HTMLDivElement>();+ const onChange = vi.fn();+ render(+ <PageControl ref={ref} totalPages={5} page={3} onChange={onChange} />,+ );+ expect(ref.current).toBe(screen.getByRole('slider'));+ click(screen.getByRole('slider'), 50);+ expect(onChange).toHaveBeenCalledWith(4);+ });++ it("inactive dots reach 3:1 on Core's default page background (WCAG 1.4.11)", () => {+ renderControl();+ const dot = screen+ .getByRole('slider')+ .querySelector('[data-page="0"]') as HTMLElement;+ // Core's light defaults: --color-text-primary #0A1317 on+ // --color-background-body #F1F4F7.+ expect(+ contrastOver(+ [0x0a, 0x13, 0x17],+ [0xf1, 0xf4, 0xf7],+ Number(dot.style.opacity),+ ),+ ).toBeGreaterThanOrEqual(3);+ });++ it('server-rendered, a long control already carries its resting offset and sizes', () => {+ const html = renderToString(+ <PageControl totalPages={50} page={27} onChange={() => {}} />,+ );+ const rest = /--_page-control-rest:\s*([\d.]+)px/.exec(html);+ expect(rest).not.toBeNull();+ expect(Number(rest?.[1])).toBeGreaterThan(0);+ expect(html).toMatch(/--_page-control-scale:\s*0\.967/);+ });++ it('with hidesForSinglePage, renders nothing for one page', () => {+ renderControl({totalPages: 1, page: 1, hidesForSinglePage: true});+ expect(screen.queryByRole('slider')).toBeNull();+ });+});diff --git a/packages/lab/src/PageControl/PageControl.tsx b/packages/lab/src/PageControl/PageControl.tsxnew file mode 100644index 0000000000..b1753f4f2f--- /dev/null+++ b/packages/lab/src/PageControl/PageControl.tsx@@ -0,0 +1,449 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file PageControl.tsx+ * @input React, StyleX, Core's theme tokens and translator, Core's internal+ * touch entry, pageControlTable.ts, pageControlModel.ts, PageControlTouch.ts+ * @output Exports PageControl: a row of page indicators that pages one step+ * per tap and follows a scrubbing finger, like UIPageControl+ * @position Lab component: the phone's "which page am I on" under a paging+ * view, UIPageControl's counterpart+ *+ * SYNC: When modified, update PageControl.doc.mjs, PageControl.test.tsx,+ * PageControlTouch.ts, pageControlModel.ts and the interaction spec.+ */++import {+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type CSSProperties,+ type KeyboardEvent,+ type Ref,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '@astryxdesign/core';+import {useTranslator} from '@astryxdesign/core/i18n';+import {+ composeEventHandlers,+ mergeProps,+ mergeRefs,+} from '@astryxdesign/core/utils';+import {colorVars, focusVars} from '@astryxdesign/core/theme/tokens.stylex';+import {+ animatorFor,+ isRtlElement,+ touchHitAreaStyles,+ useTouchHitArea,+ useTouchPresentation,+} from '@astryxdesign/core/internal/touch';+import {pageControl} from './pageControlTable';+import {usePageControlTouch} from './PageControlTouch';+import {+ BOX,+ PITCH,+ SWITCH,+ clampPage,+ croppedRowOffset,+ indicatorSize,+ pageControlLayout,+ renderedPages,+ windowFor,+ type ChangeKind,+ type Latest,+} from './pageControlModel';++const PC = pageControl;+/** A 10 px box scaled to the 9.67 px indicator (see BOX). */+const DOT_SCALE = PC.indicatorSize / BOX;+// UIKit draws the other indicators at 45 %. At that alpha, Core's primary+// text colour on its page background measures 2.97:1. That is under the 3:1+// that WCAG 1.4.11 asks of the only page-count cue. 48 % gives 3.25:1.+const INACTIVE_ALPHA = Math.max(PC.otherIndicatorAlpha, 0.48);++export interface PageControlProps extends Omit<+ BaseProps<HTMLDivElement>,+ 'onChange'+> {+ /** Number of pages. */+ totalPages: number;+ /** Current page number (1-based). Page 1 is the first page. */+ page: number;+ /**+ * Called with the page, 1-based, that a tap, a scrub, a key or an assistive+ * technology asks for.+ */+ onChange: (page: number) => void;+ /**+ * Accessible name of the control.+ * @default 'Page indicators' (localized)+ */+ label?: string;+ /**+ * Render nothing when there is only one page.+ * @default false+ */+ hidesForSinglePage?: boolean;+ 'data-testid'?: string;+ /** The slider element. */+ ref?: Ref<HTMLDivElement>;+}++const styles = stylex.create({+ root: {+ position: 'relative',+ display: 'inline-block',+ boxSizing: 'border-box',+ flexShrink: 0,+ verticalAlign: 'middle',+ cursor: 'default',+ userSelect: 'none',+ WebkitUserSelect: 'none',+ WebkitTapHighlightColor: 'transparent',+ outlineStyle: {+ default: 'none',+ ':focus-visible': focusVars['--focus-outline-style'],+ },+ outlineWidth: focusVars['--focus-outline-width'],+ outlineColor: focusVars['--focus-outline-color'],+ outlineOffset: focusVars['--focus-outline-offset'],+ },+ cropped: {+ overflow: 'hidden',+ },+ // The held look has no element of its own. The root's `::before` paints it.+ platter: {+ '::before': {+ content: '""',+ position: 'absolute',+ inset: 0,+ borderRadius: 9999,+ backgroundColor: colorVars['--color-overlay-pressed'],+ pointerEvents: 'none',+ opacity: 0,+ transition: 'var(--_page-control-platter-transition, none)',+ },+ },+ platterShown: {+ '::before': {+ opacity: 1,+ },+ },+ strip: {+ position: 'absolute',+ insetBlock: 0,+ width: 0,+ pointerEvents: 'none',+ },+ indicator: {+ position: 'absolute',+ borderRadius: '50%',+ backgroundColor: colorVars['--color-text-primary'],+ },+ // The resting offset and sizes the markup carries (custom properties the+ // render sets); the animator's inline translate and scale override them.+ restingStrip: {+ translate: {+ default: 'calc(-1 * var(--_page-control-rest, 0px)) 0',+ ':is([dir="rtl"] *)': 'var(--_page-control-rest, 0px) 0',+ },+ },+ restingDot: {+ scale: 'var(--_page-control-scale, 1)',+ },+});++/** The page count: 0 for a total that is not a finite number. */+function pageCountOf(totalPages: number): number {+ return Number.isFinite(totalPages) ? Math.max(0, Math.floor(totalPages)) : 0;+}++/**+ * A row of page indicators that pages one step per tap and follows a+ * scrubbing finger, like UIPageControl.+ *+ * It draws UIPageControl's measured geometry: 9.67 px indicators 8 px apart,+ * 14 px of padding at each end and 25.67 px tall. At most ten indicator+ * slots show. With more pages, the row is a window. Where pages continue past+ * it, the last two slots on that side shrink. The window moves only when the+ * current page would land in a shrunk slot, on UIKit's spring.+ *+ * The app owns the page (`page` and `onChange`). A tap on the trailing side+ * of the current indicator asks for the next page, and on the leading side+ * for the previous one. A finger that travels 16 px scrubs instead. Past the+ * content's edge, the page keeps stepping on its own. A held or scrubbing+ * finger shows a platter behind the indicators and dims the others.+ *+ * Assistive technology gets one adjustable element: a slider named "Page+ * indicators" whose value reads "Page 3 of 5". The arrow keys, Home and End+ * change the page. Every pointer taps and scrubs. With a fine pointer, the+ * row is cropped to the control and opacity changes are instant.+ *+ * @example+ * ```+ * const [page, setPage] = useState(1);+ * <PageControl totalPages={5} page={page} onChange={setPage} />+ * ```+ */+export function PageControl(props: PageControlProps) {+ const pages = pageCountOf(props.totalPages);+ if (pages === 0 || (props.hidesForSinglePage === true && pages === 1)) {+ // Nothing to show. The row mounts with its element when pages arrive, so+ // its recognizers attach then.+ return null;+ }+ return <PageControlRow {...props} />;+}++function PageControlRow({+ totalPages,+ page: pageProp,+ onChange,+ label,+ hidesForSinglePage: _hidesForSinglePage,+ xstyle,+ className,+ style,+ 'data-testid': testId,+ ref,+ onKeyDown: onKeyDownProp,+ ...htmlProps+}: PageControlProps) {+ const t = useTranslator();+ const rootRef = useRef<HTMLDivElement>(null);+ const stripRef = useRef<HTMLSpanElement>(null);+ const pages = pageCountOf(totalPages);+ // Pages count from 1 outside and from 0 inside.+ const current =+ pages === 0 || !Number.isFinite(pageProp)+ ? 0+ : clampPage(pageProp - 1, pages);+ const layout = pageControlLayout(pages);+ // The held platter, shrinking window and fades are the touch presentation,+ // under a finger on any touch device. With a mouse, the control shows the+ // full row, cropped, and takes the same taps and scrubs over it.+ const {isTouch} = useTouchPresentation();++ // The window moves only when the current page would land in a shrunk+ // slot, so it depends on where it was: state, adjusted during render.+ const [windowStart, setWindowStart] = useState(() =>+ windowFor(pages, 0, current),+ );+ const nextWindowStart = isTouch+ ? windowFor(pages, windowStart, current)+ : windowStart;+ if (nextWindowStart !== windowStart) {+ setWindowStart(nextWindowStart);+ }++ const [isInteracting, setInteracting] = useState(false);+ const [isScrubbing, setScrubbing] = useState(false);++ // Read by the gesture and its timers, which outlive a render.+ const latestRef = useRef<Latest>({+ current,+ pages,+ windowStart,+ onChange,+ });+ // Syncs latestRef with the committed render. It is written at commit: a+ // render that React discards, as a suspended transition does, must not+ // leave its values behind.+ useLayoutEffect(() => {+ latestRef.current = {current, pages, windowStart, onChange};+ });++ // What asked for the page the control shows next: a tap fades the old+ // indicator faster than anything else.+ const requestRef = useRef<{page: number; kind: ChangeKind} | null>(null);+ const request = (page: number, kind: ChangeKind) => {+ const latest = latestRef.current;+ if (page === latest.current || page === requestRef.current?.page) {+ return;+ }+ const pending = {page, kind};+ requestRef.current = pending;+ latest.onChange(page + 1);+ // An app that keeps its value never renders the page. Once it has had its+ // chance to, in the next task, the request lapses. Then asking again+ // calls onChange again.+ const view = rootRef.current?.ownerDocument.defaultView ?? globalThis;+ view.setTimeout(() => {+ if (requestRef.current === pending) {+ requestRef.current = null;+ }+ }, 0);+ };++ usePageControlTouch({+ isTouch,+ rootRef,+ stripRef,+ latestRef,+ requestRef,+ request,+ setInteracting,+ setScrubbing,+ pages,+ current,+ windowStart,+ });++ // With a mouse: the cropped row, every page at full size, shifted at once to+ // keep the current indicator in view. A scrub maps the pointer onto the dots+ // as they lie, so the row holds still until the lift.+ useLayoutEffect(() => {+ const strip = stripRef.current;+ const root = rootRef.current;+ if (isTouch || isScrubbing || strip == null || root == null) {+ return;+ }+ const isRtl = isRtlElement(root);+ animatorFor(strip).set({+ x: (isRtl ? 1 : -1) * croppedRowOffset(pages, current),+ });+ for (const dot of Array.from(strip.children) as HTMLElement[]) {+ animatorFor(dot).set({scale: DOT_SCALE});+ }+ }, [isTouch, isScrubbing, pages, current]);++ // A finger needs a 44 px target: the touch hit area grows the control toward+ // it, as far as its neighbours allow. It pauses while a scrub runs, so+ // nothing reads layout as the finger moves.+ const hitAreaRef = useTouchHitArea(!isScrubbing);+ const mergedRef = useMemo(+ () => mergeRefs(ref, rootRef, hitAreaRef),+ [ref, hitAreaRef],+ );++ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ const isRtl = isRtlElement(event.currentTarget);+ let next: number;+ switch (event.key) {+ case 'ArrowRight':+ next = current + (isRtl ? -1 : 1);+ break;+ case 'ArrowLeft':+ next = current + (isRtl ? 1 : -1);+ break;+ case 'ArrowUp':+ next = current + 1;+ break;+ case 'ArrowDown':+ next = current - 1;+ break;+ case 'Home':+ next = 0;+ break;+ case 'End':+ next = pages - 1;+ break;+ default:+ return;+ }+ event.preventDefault();+ request(clampPage(next, pages), 'other');+ };++ const isWindow = isTouch && layout.isWindowed;+ const [first, last] = isWindow+ ? renderedPages(pages, windowStart)+ : [0, pages];+ // The cropped row starts inside the padding.+ const fullRow = pages * PITCH - PC.indicatorSpacing;+ const stripStart = isTouch+ ? (layout.width - layout.rowWidth) / 2+ : (layout.width -+ Math.min(fullRow, layout.width - 2 * PC.horizontalPadding)) /+ 2;+ const transition = isTouch ? SWITCH : 'none';+ const otherAlpha = isInteracting+ ? PC.interactingOtherIndicatorAlpha+ : INACTIVE_ALPHA;+ // The resting window is in the markup too. So a server-rendered control+ // shows its current indicator before the animator takes the strip and the+ // dots. Then the animator's inline values win.+ const restOffset = isTouch+ ? windowStart * PITCH+ : croppedRowOffset(pages, current);+ const stripStyle: CSSProperties & Record<`--${string}`, string> = {+ insetInlineStart: stripStart,+ '--_page-control-rest': `${restOffset}px`,+ };+ const top = (PC.height - BOX) / 2;++ return (+ <div+ data-testid={testId}+ data-interacting={isInteracting || undefined}+ {...htmlProps}+ ref={mergedRef}+ {...mergeProps(+ stylex.props(+ styles.root,+ !isTouch && styles.cropped,+ isTouch && styles.platter,+ isTouch && touchHitAreaStyles.layer,+ isTouch && isInteracting && styles.platterShown,+ xstyle,+ ),+ className,+ {+ ...style,+ width: layout.width,+ height: PC.height,+ ['--_page-control-platter-transition' as string]: transition,+ },+ )}+ role="slider"+ tabIndex={0}+ aria-label={label ?? t('@astryx.pagination.pageIndicators')}+ aria-orientation="horizontal"+ aria-valuemin={1}+ aria-valuemax={pages}+ aria-valuenow={current + 1}+ aria-valuetext={t('@astryx.pagination.pageOfTotal', {+ current: current + 1,+ total: pages,+ })}+ // The caller's handler first: its preventDefault keeps the page.+ onKeyDown={composeEventHandlers(onKeyDownProp, onKeyDown)}>+ <span+ ref={stripRef}+ aria-hidden="true"+ {...stylex.props(styles.strip, styles.restingStrip)}+ style={stripStyle}>+ {Array.from({length: last - first}, (_, i) => {+ const page = first + i;+ return (+ <span+ key={page}+ data-page={page}+ {...stylex.props(styles.indicator, styles.restingDot)}+ style={{+ // The box overhangs its drawn indicator by half a pixel.+ insetInlineStart: page * PITCH - (BOX - PC.indicatorSize) / 2,+ top,+ width: BOX,+ height: BOX,+ ['--_page-control-scale' as string]: String(+ isTouch+ ? indicatorSize(pages, windowStart, page) / BOX+ : DOT_SCALE,+ ),+ opacity:+ page === current ? PC.currentIndicatorAlpha : otherAlpha,+ transition,+ }}+ />+ );+ })}+ </span>+ </div>+ );+}++PageControl.displayName = 'PageControl';diff --git a/packages/lab/src/PageControl/PageControlTouch.ts b/packages/lab/src/PageControl/PageControlTouch.tsnew file mode 100644index 0000000000..e1d909cbe8--- /dev/null+++ b/packages/lab/src/PageControl/PageControlTouch.ts@@ -0,0 +1,593 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file PageControlTouch.ts+ * @input The control's elements, page state and request function; the+ * gesture system, the animator, the Reduce Motion policy and `flushSync`+ * @output usePageControlTouch: the scrub and its jog, the held platter, the+ * window's slide and the fades+ * @position Internal to PageControl: its one touch module, imported once+ *+ * SYNC: When modified, update PageControl.tsx, PageControl.test.tsx and+ * __tests__/PageControl.interaction.browser.spec.ts.+ */++import {useEffect, useLayoutEffect, useRef, type RefObject} from 'react';+import {flushSync} from 'react-dom';+import {+ animatorFor,+ isRtlElement,+ LongPressGestureRecognizer,+ PanGestureRecognizer,+ reducedMotionFade,+ TapGestureRecognizer,+ useGestureRecognizer,+} from '@astryxdesign/core/internal/touch';+import {pageControl} from './pageControlTable';+import {+ BOX,+ PITCH,+ SWITCH,+ clampPage,+ fadeOf,+ indicatorSize,+ jogInterval,+ pageControlLayout,+ renderedPages,+ scrubTarget,+ tapTarget,+ type ChangeKind,+ type Latest,+} from './pageControlModel';++const PC = pageControl;++/**+ * Under Reduce Motion, the held look's release takes the one policy's fade:+ * 200 ms on a coarse pointer, and none on any other. It is null when motion+ * is not reduced.+ */+function reducedFadeOf(root: Element): string | null {+ const fade = reducedMotionFade(root);+ if (fade == null) {+ return null;+ }+ return fade.duration === 0+ ? 'none'+ : `opacity ${fade.duration / 1000}s ${fade.easing}`;+}++/** What the touch layer reads from the control and writes back. */+export interface PageControlTouch {+ /** The touch presentation is on (a coarse primary pointer). */+ readonly isTouch: boolean;+ readonly rootRef: RefObject<HTMLDivElement | null>;+ readonly stripRef: RefObject<HTMLSpanElement | null>;+ /** The control's state after each render, for gestures and timers. */+ readonly latestRef: RefObject<Latest>;+ /** The page last asked for and what asked (a tap fades faster). */+ readonly requestRef: RefObject<{page: number; kind: ChangeKind} | null>;+ /** Asks the app for a page. */+ readonly request: (page: number, kind: ChangeKind) => void;+ /** Shows or hides the platter and dims the other indicators. */+ readonly setInteracting: (isInteracting: boolean) => void;+ /** Whether a scrub runs: a mouse's cropped row holds still meanwhile. */+ readonly setScrubbing: (isScrubbing: boolean) => void;+ readonly pages: number;+ readonly current: number;+ readonly windowStart: number;+}++/**+ * PageControl's input and its touch presentation. The recognizers take every+ * pointer: a mouse taps and scrubs as a finger does, over the row it sees.+ * The platter, the window's slide and the fades are the touch presentation,+ * on only while `isTouch`.+ */+export function usePageControlTouch({+ isTouch,+ rootRef,+ stripRef,+ latestRef,+ requestRef,+ request,+ setInteracting,+ setScrubbing,+ pages,+ current,+ windowStart,+}: PageControlTouch): void {+ // Timers run on the control's own window, as an iframe or another window+ // throttles its own.+ const view = (): Window =>+ rootRef.current?.ownerDocument.defaultView ?? window;+ const geometry = () => {+ const root = rootRef.current;+ if (root == null) {+ return null;+ }+ const rect = root.getBoundingClientRect();+ const isRtl = isRtlElement(root);+ const rowStart =+ (rect.width - pageControlLayout(latestRef.current.pages).rowWidth) / 2;+ const firstCenter = rowStart + PC.indicatorSize / 2;+ /** Px along the row (mirrored in RTL) from the window's first slot's centre. */+ const along = (x: number) =>+ isRtl ? rect.right - firstCenter - x : x - rect.left - firstCenter;+ /** Px past the edge of the content: positive past the end, negative past the start. */+ const past = (x: number) => {+ const start = rect.left + PC.horizontalPadding;+ const end = rect.right - PC.horizontalPadding;+ const beyond = x > end ? x - end : x < start ? x - start : 0;+ return isRtl ? -beyond : beyond;+ };+ return {along, past};+ };++ /**+ * With a mouse, the full row: each page's dot centre on screen, read when a+ * scrub begins (the geometry above is the touch presentation's window).+ */+ const rowCentres = (): ReadonlyArray<{page: number; x: number}> => {+ const strip = stripRef.current;+ if (strip == null) {+ return [];+ }+ return Array.from(strip.querySelectorAll<HTMLElement>('[data-page]')).map(+ dot => {+ const box = dot.getBoundingClientRect();+ return {page: Number(dot.dataset.page), x: box.left + box.width / 2};+ },+ );+ };++ const gestureRef = useRef({+ startX: 0,+ lastX: 0,+ isScrubbing: false,+ /**+ * The control's geometry, read once when the scrub begins: nothing reads+ * layout while the finger moves.+ */+ geo: null as ReturnType<typeof geometry>,+ /** With a mouse, the row's dot centres, read once when the scrub begins. */+ centres: [] as ReadonlyArray<{page: number; x: number}>,+ interactTimer: 0,+ jogTimer: 0,+ /** When the finger crossed the edge or the last jog step was due, ms. */+ jogFrom: null as number | null,+ /** When the pending jog step runs, ms. */+ jogDue: 0,+ });++ const stopJog = () => {+ const g = gestureRef.current;+ if (g.jogTimer !== 0) {+ view().clearTimeout(g.jogTimer);+ g.jogTimer = 0;+ }+ g.jogFrom = null;+ };++ // Past the content's edge of a windowed control, the page steps on its own.+ // Each step comes 1 / rate after the previous one was due, or after the+ // finger crossed the edge. The rate follows how far past the finger is now,+ // so moving further brings the next step closer. Steps count from when one+ // was due, so a late timer does not slow the run. After a stall longer than+ // a step, the next one counts from the late step, with no burst.+ const jog = () => {+ const g = gestureRef.current;+ const geo = g.geo;+ const latest = latestRef.current;+ if (+ geo == null ||+ !g.isScrubbing ||+ !pageControlLayout(latest.pages).isWindowed+ ) {+ stopJog();+ return;+ }+ const beyond = geo.past(g.lastX);+ const direction = Math.sign(beyond);+ const interval =+ direction === 0 ? Infinity : jogInterval(Math.abs(beyond), direction);+ if (!Number.isFinite(interval)) {+ stopJog();+ return;+ }+ const now = performance.now();+ g.jogFrom ??= now;+ const due = g.jogFrom + interval * 1000;+ if (g.jogTimer !== 0) {+ if (Math.abs(due - g.jogDue) < 1) {+ return;+ }+ view().clearTimeout(g.jogTimer);+ }+ g.jogDue = due;+ g.jogTimer = view().setTimeout(+ () => {+ g.jogTimer = 0;+ const ranAt = performance.now();+ g.jogFrom = ranAt - due > interval * 1000 ? ranAt : due;+ const step = Math.sign(geo.past(g.lastX));+ if (step !== 0) {+ const current = latestRef.current;+ const from = requestRef.current?.page ?? current.current;+ // The step commits in this task. A render scheduled after it can+ // wait behind a busy page's other tasks past the next step. Then+ // two steps would show as one.+ flushSync(() => {+ request(clampPage(from + step, current.pages), 'other');+ });+ }+ jog();+ },+ Math.max(0, due - now),+ );+ };++ const scrubTo = (x: number) => {+ const geo = gestureRef.current.geo;+ const latest = latestRef.current;+ if (!isTouch) {+ // With a mouse: the page whose dot is nearest the pointer, on the full+ // row; nothing jogs past its ends.+ let nearest: {page: number; x: number} | null = null;+ for (const centre of gestureRef.current.centres) {+ if (+ nearest == null ||+ Math.abs(centre.x - x) < Math.abs(nearest.x - x)+ ) {+ nearest = centre;+ }+ }+ if (nearest != null) {+ request(clampPage(nearest.page, latest.pages), 'other');+ }+ return;+ }+ if (geo == null) {+ return;+ }+ if (geo.past(x) === 0 || !pageControlLayout(latest.pages).isWindowed) {+ stopJog();+ request(+ scrubTarget(geo.along(x), latest.pages, latest.windowStart),+ 'other',+ );+ }+ jog();+ };++ // Under Reduce Motion the held look, the platter and the dots' dimming,+ // shows at once and takes the policy's fade on the release. It is written+ // before the look changes.+ const writeHeldFade = (isRelease: boolean) => {+ const root = rootRef.current;+ if (!isTouch || root == null) {+ return;+ }+ const reduced = reducedFadeOf(root);+ if (reduced == null) {+ return;+ }+ const transition = isRelease ? reduced : 'none';+ // The platter is the root's ::before: its fade is a custom property.+ root.style.setProperty('--_page-control-platter-transition', transition);+ for (const dot of Array.from(+ stripRef.current?.children ?? [],+ ) as HTMLElement[]) {+ dot.style.transition = transition;+ }+ };++ const finish = () => {+ const g = gestureRef.current;+ if (g.interactTimer !== 0) {+ view().clearTimeout(g.interactTimer);+ g.interactTimer = 0;+ }+ stopJog();+ g.isScrubbing = false;+ g.geo = null;+ g.centres = [];+ writeHeldFade(true);+ setInteracting(false);+ setScrubbing(false);+ };+ // The platter and the dimmed indicators are the touch presentation.+ const showHeld = () => {+ if (isTouch) {+ writeHeldFade(false);+ setInteracting(true);+ }+ };++ // A pointer on the control, a finger or a mouse, is decided within 10 px.+ // So a swipe that starts vertical stays the page's scroll:+ // - a horizontal pan, from 10 px, scrubs once the pointer is 16 px from+ // where it landed; a drag that starts vertical fails it;+ // - a pointer held still for 155 ms (UIPageControl's interaction delay)+ // scrubs the same way from there, under a finger on the platter;+ // - a tap steps one page.+ // Whichever begins first holds the press and fails the others. The scrub's+ // 16 px count from where the pointer landed, as UIKit counts them.+ const landingX = (+ recognizer: {trackedTouches: ReadonlyArray<{startX: number}>},+ fallback: number,+ ) => recognizer.trackedTouches[0]?.startX ?? fallback;+ const begin = (startX: number) => {+ const g = gestureRef.current;+ g.startX = startX;+ g.lastX = startX;+ g.isScrubbing = false;+ };+ const track = (x: number) => {+ const g = gestureRef.current;+ g.lastX = x;+ if (+ !g.isScrubbing &&+ Math.abs(x - g.startX) >= PC.scrubStartDistance &&+ latestRef.current.pages > 1+ ) {+ g.isScrubbing = true;+ g.geo = geometry();+ g.centres = isTouch ? [] : rowCentres();+ setScrubbing(true);+ showHeld();+ }+ if (g.isScrubbing) {+ scrubTo(x);+ }+ };+ // A tap, or a pan or hold that lifts before it scrubs: one page toward the+ // finger's side of the current indicator.+ const step = (x: number) => {+ const latest = latestRef.current;+ if (!isTouch) {+ // With a mouse: toward the pointer's side of the current dot, on the+ // row as drawn.+ const root = rootRef.current;+ const dot = stripRef.current?.querySelector(+ `[data-page="${latest.current}"]`,+ );+ if (root == null || dot == null || latest.pages < 2) {+ return;+ }+ const box = dot.getBoundingClientRect();+ request(+ tapTarget(+ x,+ box.left + box.width / 2,+ latest.current,+ latest.pages,+ isRtlElement(root),+ ),+ 'tap',+ );+ return;+ }+ const geo = geometry();+ if (geo == null || latest.pages < 2) {+ return;+ }+ const slot =+ latest.current -+ (pageControlLayout(latest.pages).isWindowed ? latest.windowStart : 0);+ request(+ tapTarget(+ geo.along(x),+ slot * PITCH,+ latest.current,+ latest.pages,+ false,+ ),+ 'tap',+ );+ };+ const lift = (x: number) => {+ if (!gestureRef.current.isScrubbing) {+ step(x);+ }+ finish();+ };++ useGestureRecognizer(+ rootRef,+ () => new PanGestureRecognizer({direction: 'horizontal'}),+ pan => {+ const {x} = pan.location();+ switch (pan.state) {+ case 'began': {+ begin(landingX(pan, x - pan.travelAtBegan.x));+ const g = gestureRef.current;+ g.interactTimer = view().setTimeout(() => {+ g.interactTimer = 0;+ showHeld();+ }, PC.interactionDelayMs);+ track(x);+ break;+ }+ case 'changed':+ track(x);+ break;+ case 'ended':+ lift(x);+ break;+ case 'cancelled':+ finish();+ break;+ default:+ break;+ }+ },+ );++ useGestureRecognizer(+ rootRef,+ () =>+ new LongPressGestureRecognizer({+ minimumPressDuration: PC.interactionDelayMs,+ }),+ hold => {+ const {x} = hold.location();+ switch (hold.state) {+ case 'began':+ begin(landingX(hold, x));+ showHeld();+ break;+ case 'changed':+ track(x);+ break;+ case 'ended':+ lift(x);+ break;+ case 'cancelled':+ finish();+ break;+ default:+ break;+ }+ },+ );++ useGestureRecognizer(+ rootRef,+ () => new TapGestureRecognizer(),+ tap => {+ if (tap.state === 'ended') {+ step(tap.location().x);+ }+ },+ );++ // Timers end with the control. Its window is read at mount: at unmount+ // the ref is already detached.+ useEffect(() => {+ const owner = view();+ return () => {+ const g = gestureRef.current;+ owner.clearTimeout(g.interactTimer);+ owner.clearTimeout(g.jogTimer);+ };+ }, []);++ const shownPageRef = useRef(current);+ // Syncs the indicators' opacity transitions with the page. The old current+ // indicator fades, faster after a tap; every other opacity change is a+ // switch. Under Reduce Motion the highlight is a selection colour, so it+ // changes at once. This runs before the window effect: its style reads+ // would start the transitions on the previous values.+ useLayoutEffect(() => {+ const old = shownPageRef.current;+ shownPageRef.current = current;+ if (old === current) {+ return;+ }+ const kind =+ requestRef.current?.page === current ? requestRef.current.kind : 'other';+ // Clear it. A later change from the app then fades as other.+ requestRef.current = null;+ const root = rootRef.current;+ if (!isTouch || root == null) {+ return;+ }+ const isReduced = reducedMotionFade(root) != null;+ const fade = fadeOf(+ kind === 'tap' ? PC.tapFadeOutMs : PC.fadeOutMs,+ PC.fadeOutCurve,+ );+ const other = isReduced ? 'none' : SWITCH;+ let fading: HTMLElement | null = null;+ for (const dot of Array.from(+ stripRef.current?.children ?? [],+ ) as HTMLElement[]) {+ const isFading = !isReduced && Number(dot.dataset.page) === old;+ dot.style.transition = isFading ? fade : other;+ if (isFading) {+ fading = dot;+ }+ }+ if (fading != null) {+ // The style read starts the fade with the duration written above. A+ // running transition keeps its duration, so the dot's next change is a+ // switch again at once. A hidden control starts no fade.+ void getComputedStyle(fading).opacity;+ fading.style.transition = SWITCH;+ }+ }, [current, isTouch]);++ const shownRef = useRef<{windowStart: number; pages: number} | null>(null);+ // Syncs each element's animator with the window: the strip's offset and+ // every indicator's size.+ useLayoutEffect(() => {+ const strip = stripRef.current;+ const root = rootRef.current;+ if (strip == null || root == null) {+ return undefined;+ }+ const isRtl = isRtlElement(root);+ const offsetFor = (start: number) => (isRtl ? 1 : -1) * start * PITCH;+ const dots = Array.from(strip.children) as HTMLElement[];+ const pageOf = (dot: HTMLElement) => Number(dot.dataset.page);+ const scaleFor = (start: number, page: number) =>+ indicatorSize(pages, start, page) / BOX;+ if (!isTouch) {+ shownRef.current = null;+ return undefined;+ }+ const before = shownRef.current;+ shownRef.current = {windowStart, pages};+ if (+ before == null ||+ before.pages !== pages ||+ before.windowStart === windowStart+ ) {+ animatorFor(strip).set({x: offsetFor(windowStart)});+ for (const dot of dots) {+ animatorFor(dot).set({scale: scaleFor(windowStart, pageOf(dot))});+ }+ return undefined;+ }+ // Dots that just mounted start at their size in the old window.+ const [wasFirst, wasLast] = renderedPages(pages, before.windowStart);+ for (const dot of dots) {+ const page = pageOf(dot);+ if (page < wasFirst || page >= wasLast) {+ animatorFor(dot).set({scale: scaleFor(before.windowStart, page)});+ }+ }+ // The move starts windowSlideDelay after the change. The strip and every+ // dot share one start time on the document timeline. A busy main thread+ // cannot push that back, as it would a timer.+ const at = performance.now() + PC.windowSlideDelayMs;+ const transition = {spring: PC.windowSlide};+ const stripAnimator = animatorFor(strip);+ stripAnimator.animate({x: offsetFor(windowStart)}, transition, {at});+ if (stripAnimator.reducedMotion() === 'off') {+ for (const dot of dots) {+ animatorFor(dot).animate(+ {scale: scaleFor(windowStart, pageOf(dot))},+ transition,+ {at},+ );+ }+ return undefined;+ }+ // Under Reduce Motion, the strip's cross-fade carries the whole change.+ // The dots take their new sizes at its middle, while it is transparent.+ // Fades of their own would fight their page opacity.+ const half = (reducedMotionFade(root)?.duration ?? 0) / 2;+ const resizeTimer = view().setTimeout(() => {+ for (const dot of dots) {+ animatorFor(dot).set({scale: scaleFor(windowStart, pageOf(dot))});+ }+ }, PC.windowSlideDelayMs + half);+ return () => {+ view().clearTimeout(resizeTimer);+ };+ }, [windowStart, pages, isTouch]);+}diff --git a/packages/lab/src/PageControl/__tests__/PageControl.interaction.browser.spec.ts b/packages/lab/src/PageControl/__tests__/PageControl.interaction.browser.spec.tsnew file mode 100644index 0000000000..cb1a41f651--- /dev/null+++ b/packages/lab/src/PageControl/__tests__/PageControl.interaction.browser.spec.ts@@ -0,0 +1,1368 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PageControl.interaction.browser.spec.ts+ * @input The built "Default" and "Many Pages" PageControl stories, real touch+ * input (Chromium CDP / WebKit's tap path) and the interaction harness+ * @output Proof against UIPageControl's measurements: taps, the scrub, the+ * jog, the held platter, the fades, the window's slide and the page scroll+ * @position Browser proof for the lab PageControl, run by+ * `pnpm test:interaction`+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ animationStoryboard,+ armHold,+ drag,+ releaseAnimations,+ openStory,+ touchDriver,+ touchStoryboard,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++/** Indicator pitch, px (the pageControl table: 9.67 + 8). */+const PITCH = 17.67;+/** A full-size dot's scale: the 9.67 px indicator on its 10 px box. */+const DOT_SCALE = 0.967;++/**+ * Opens a PageControl story. The phone projects have a coarse primary+ * pointer: the touch presentation, on any engine (one touch model; nothing+ * asks for iOS). A block that sets `hasTouch: false` gets a mouse.+ */+async function open(+ page: Page,+ story = 'lab-pagecontrol--default',+ {rtl = false}: {rtl?: boolean} = {},+) {+ if (rtl) {+ await page.goto(+ `${storybook()}/iframe.html?id=${story}&viewMode=story&globals=direction:rtl`,+ );+ await page.getByRole('slider').waitFor();+ } else {+ await openStory(page, storybook(), story);+ }+ const slider = page.getByRole('slider');+ const driver = await touchDriver(page);+ return {slider, driver};+}++/** The centre of page `index`'s indicator, page coordinates. */+async function indicatorCenter(slider: Locator, index: number) {+ return slider.evaluate((el, i) => {+ const dot = el.querySelector(`[data-page="${i}"]`) as HTMLElement;+ const box = dot.getBoundingClientRect();+ return {x: box.left + box.width / 2, y: box.top + box.height / 2};+ }, index);+}++const valueNow = async (slider: Locator) =>+ Number(await slider.getAttribute('aria-valuenow'));++/** Logs every page change with its time (performance.now()) from now on. */+async function logPages(slider: Locator) {+ await slider.evaluate(el => {+ const log: Array<{t: number; page: number}> = [];+ (window as unknown as {pageLog: typeof log}).pageLog = log;+ new MutationObserver(() => {+ log.push({+ t: performance.now(),+ page: Number(el.getAttribute('aria-valuenow')),+ });+ }).observe(el, {attributes: true, attributeFilter: ['aria-valuenow']});+ });+ return () =>+ slider.evaluate(+ () =>+ (window as unknown as {pageLog: Array<{t: number; page: number}>})+ .pageLog,+ );+}++test('a tap on the trailing side of the current indicator moves one page forward, the leading side one back', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ expect(await valueNow(slider)).toBe(3);+ const current = await indicatorCenter(slider, 2);+ await driver.tap({x: current.x + 12, y: current.y});+ await expect.poll(async () => valueNow(slider)).toBe(4);+ await expect(page.getByTestId('page')).toHaveText('Page 4');+ const next = await indicatorCenter(slider, 3);+ await driver.tap({x: next.x - 12, y: next.y});+ await expect.poll(async () => valueNow(slider)).toBe(3);+});++test('a tap just above the control, inside its 44 px hit area, steps a page', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ expect(await valueNow(slider)).toBe(3);+ // The 25.67 px tall control grows about 9 px past each edge.+ await expect+ .poll(() =>+ slider.evaluate(+ el =>+ Number.parseFloat(+ el.style.getPropertyValue('--astryx-hit-inset-top'),+ ) || 0,+ ),+ )+ .toBeGreaterThan(8);+ const box = await slider.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const current = await indicatorCenter(slider, 2);+ await driver.tap({x: current.x + 12, y: box.y - 6});+ await expect.poll(async () => valueNow(slider)).toBe(4);+});++test('the page changes when the finger lifts, not when it lands', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ const current = await indicatorCenter(slider, 2);+ const at = {x: current.x + 12, y: current.y};+ let whileDown = NaN;+ // A finger held 200 ms (a 0.4 px creep, so moves are reported) then lifted.+ await driver.play(+ drag(at, {x: at.x + 0.4, y: at.y}, {durationMs: 200, hz: 10}),+ {+ onEvent: async step => {+ if (step.type === 'touchMove' && Number.isNaN(whileDown)) {+ whileDown = await valueNow(slider);+ }+ },+ },+ );+ expect(whileDown).toBe(3);+ await expect.poll(async () => valueNow(slider)).toBe(4);+});++test('rapid taps are not coalesced: five taps 150 ms apart step five pages (UIKit: each tap steps once)', async ({+ page,+}) => {+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages');+ expect(await valueNow(slider)).toBe(26);+ for (let i = 0; i < 5; i++) {+ const current = await indicatorCenter(slider, 25 + i);+ await driver.tap({x: current.x + 12, y: current.y});+ await page.waitForTimeout(100);+ }+ await expect.poll(async () => valueNow(slider)).toBe(31);+});++test('a finger that travels 16 px scrubs: the page is the indicator under it, switching at the midpoints, with no layout read after the scrub begins', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ const centers = await Promise.all(+ [0, 1, 2, 3, 4].map(i => indicatorCenter(slider, i)),+ );+ const from = centers[2];+ const to = {x: centers[4].x + 4, y: from.y};+ // Every layout read the page makes from here on.+ await page.evaluate(() => {+ const counter = window as unknown as {layoutReads: number};+ const read = Element.prototype.getBoundingClientRect;+ counter.layoutReads = 0;+ Element.prototype.getBoundingClientRect = function (this: Element) {+ counter.layoutReads++;+ return read.call(this);+ };+ });+ const seen: Array<{x: number; reads: number}> = [];+ await driver.play(drag(from, to, {durationMs: 900, hz: 30, restMs: 120}), {+ onEvent: async step => {+ if (step.type === 'touchMove') {+ const x = step.fingers[0].x;+ const travel = x - from.x;+ const expected =+ travel < 16+ ? 2+ : Math.max(0, Math.min(4, Math.round((x - centers[0].x) / PITCH)));+ // One sample of slack at a switch point (the page follows the finger+ // within the move that crossed it). Each other sample waits for the+ // page it expects: where the page lands, not how fast.+ if (+ Math.abs(((x - centers[0].x) / PITCH) % 1) - 0.5 > 0.06 ||+ travel < 15+ ) {+ await expect+ .poll(async () => (await valueNow(slider)) - 1, {+ message: `finger at ${x.toFixed(1)}`,+ })+ .toBe(expected);+ }+ seen.push({+ x,+ reads: await page.evaluate(+ () => (window as unknown as {layoutReads: number}).layoutReads,+ ),+ });+ }+ },+ });+ // The scrub reads the control's layout once, as it begins, and never while+ // the finger moves.+ const scrubbing = seen.filter(({x}) => x - from.x >= 16);+ expect(scrubbing.length).toBeGreaterThan(5);+ expect(scrubbing[0].reads).toBeGreaterThan(0);+ expect(scrubbing[scrubbing.length - 1].reads).toBe(scrubbing[0].reads);+ await expect.poll(async () => valueNow(slider)).toBe(5);+ // Scrubbing back to page 0.+ await driver.play(+ drag(to, {x: centers[0].x - 6, y: from.y}, {durationMs: 900, restMs: 120}),+ );+ await expect.poll(async () => valueNow(slider)).toBe(1);+});++test('past the edge of a windowed control the page keeps stepping, faster the further past (jog)', async ({+ page,+}) => {+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages');+ const box = await slider.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const contentEnd = box.x + box.width - 14;+ const current = await indicatorCenter(slider, 25);+ const pages = await logPages(slider);+ // Scrub 40 px past the content's edge and hold there for 1.2 s:+ // 0.173 pages/s per px → about 7 pages a second.+ await driver.play(+ drag(+ current,+ {x: contentEnd + 40, y: current.y},+ {durationMs: 300, hz: 60, restMs: 1200},+ ),+ );+ const log = await pages();+ const held = log.filter(e => e.t >= log[0].t + 400);+ const intervals = held.slice(1).map((e, i) => e.t - held[i].t);+ const median = intervals.sort((a, b) => a - b)[+ Math.floor(intervals.length / 2)+ ];+ expect(median).toBeGreaterThan(110);+ expect(median).toBeLessThan(190);+ expect(log[log.length - 1].page).toBeGreaterThan(30);+ // Far past (100 px): 15 pages a second.+ const far = await logPages(slider);+ const now = await indicatorCenter(slider, (await valueNow(slider)) - 1);+ await driver.play(+ drag(+ now,+ {x: contentEnd + 100, y: now.y},+ {durationMs: 200, hz: 60, restMs: 900},+ ),+ );+ const fast = (await far()).filter((e, i, all) => e.t >= all[0].t + 300);+ const fastIntervals = fast.slice(1).map((e, i) => e.t - fast[i].t);+ const fastMedian = fastIntervals.sort((a, b) => a - b)[+ Math.floor(fastIntervals.length / 2)+ ];+ expect(fastMedian).toBeGreaterThan(50);+ expect(fastMedian).toBeLessThan(85);+});++test('a held finger shows the platter, the pressed overlay, and dims the other indicators after 155 ms; the touched indicator does not transform', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ const target = await indicatorCenter(slider, 3);+ const restingScale = await slider.evaluate(+ el =>+ getComputedStyle(el.querySelector('[data-page="3"]') as HTMLElement)+ .scale,+ );+ const states: Array<{+ t: number;+ interacting: boolean;+ platter: number;+ other: number;+ touchedScale: string;+ }> = [];+ // Each read is dated on the page's clock from the moment the finger landed.+ // The 155 ms runs on that clock. On a loaded runner, the driver plays the+ // moves later than scripted, so a scripted time would date a late read+ // early.+ await slider.evaluate(el => {+ el.addEventListener(+ 'touchstart',+ () => {+ (window as unknown as {landedAt: number}).landedAt = performance.now();+ },+ {capture: true, once: true},+ );+ });+ const read = async () => {+ const state = await slider.evaluate(el => {+ // The platter is the root's ::before (no element of its own).+ const platter = getComputedStyle(el, '::before');+ const other = el.querySelector('[data-page="0"]') as HTMLElement;+ const touched = el.querySelector('[data-page="3"]') as HTMLElement;+ return {+ t:+ performance.now() -+ (window as unknown as {landedAt: number}).landedAt,+ interacting: el.hasAttribute('data-interacting'),+ platter: Number(platter.opacity),+ other: Number(other.style.opacity),+ touchedScale: getComputedStyle(touched).scale,+ };+ });+ states.push(state);+ };+ await driver.play(+ drag(target, {x: target.x + 0.4, y: target.y}, {durationMs: 400, hz: 20}),+ {+ onEvent: async step => {+ if (step.type === 'touchStart' || step.type === 'touchMove') {+ await read();+ }+ },+ },+ );+ const early = states.filter(s => s.t < 100);+ const late = states.filter(s => s.t > 260);+ expect(early.length).toBeGreaterThan(0);+ expect(early.every(s => !s.interacting && s.other === 0.48)).toBe(true);+ expect(late.length).toBeGreaterThan(0);+ expect(late.every(s => s.interacting && s.other === 0.25)).toBe(true);+ expect(late.every(s => s.platter > 0.9)).toBe(true);+ // The platter is the held look: the system pressed overlay, resolved as any+ // element resolves it here.+ const colors = await slider.evaluate(el => {+ const probe = document.createElement('span');+ probe.style.backgroundColor = 'var(--color-overlay-pressed)';+ el.append(probe);+ const expected = getComputedStyle(probe).backgroundColor;+ probe.remove();+ return {+ platter: getComputedStyle(el, '::before').backgroundColor,+ expected,+ };+ });+ expect(colors.expected).not.toBe('rgba(0, 0, 0, 0)');+ expect(colors.platter).toBe(colors.expected);+ // The touched indicator keeps its resting size throughout.+ expect(states.every(s => s.touchedScale === restingScale)).toBe(true);+ // At the lift both return.+ await expect+ .poll(async () =>+ slider.evaluate(el => el.hasAttribute('data-interacting')),+ )+ .toBe(false);+ expect(+ await slider.evaluate(+ el => (el.querySelector('[data-page="0"]') as HTMLElement).style.opacity,+ ),+ ).toBe('0.48');+});++test('the old current indicator fades over 0.125 s after a tap and 0.25 s after any other change, on (0, 0, 0.58, 1)', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ // Each opacity transition as it runs, read from the transition itself: the+ // dot goes back to the switch once its fade starts. And each one that ran+ // to its end, with how long it ran.+ await slider.evaluate(el => {+ const runs: Array<{page: number; duration: number; easing: string}> = [];+ const ends: Array<{page: number; duration: number}> = [];+ Object.assign(window, {runs, ends});+ el.addEventListener('transitionrun', event => {+ const dot = event.target as HTMLElement;+ for (const animation of dot.getAnimations()) {+ if (+ animation instanceof CSSTransition &&+ animation.transitionProperty === 'opacity'+ ) {+ const timing = animation.effect?.getTiming();+ // WebKit names this curve by its keyword.+ const easing =+ timing?.easing === 'ease-out'+ ? 'cubic-bezier(0, 0, 0.58, 1)'+ : (timing?.easing ?? '');+ runs.push({+ page: Number(dot.dataset.page),+ duration: Number(timing?.duration),+ easing,+ });+ }+ }+ });+ el.addEventListener('transitionend', event => {+ const {propertyName, elapsedTime, target} = event as TransitionEvent;+ if (propertyName === 'opacity') {+ ends.push({+ page: Number((target as HTMLElement).dataset.page),+ duration: elapsedTime,+ });+ }+ });+ });+ const runsOf = async (index: number) =>+ page.evaluate(+ i =>+ (+ window as unknown as {+ runs: Array<{page: number; duration: number; easing: string}>;+ }+ ).runs+ .filter(run => run.page === i)+ .map(({duration, easing}) => ({duration, easing})),+ index,+ );+ const endsOf = async (index: number) =>+ page.evaluate(+ i =>+ (+ window as unknown as {ends: Array<{page: number; duration: number}>}+ ).ends+ .filter(end => end.page === i)+ .map(end => end.duration),+ index,+ );+ const current = await indicatorCenter(slider, 2);+ await driver.tap({x: current.x + 12, y: current.y});+ await expect.poll(async () => valueNow(slider)).toBe(4);+ await expect+ .poll(async () => runsOf(2))+ .toEqual([{duration: 125, easing: 'cubic-bezier(0, 0, 0.58, 1)'}]);+ await expect.poll(async () => endsOf(2)).toEqual([0.125]);+ await expect.poll(async () => endsOf(3)).toEqual([0.015625]);+ await slider.focus();+ await page.keyboard.press('ArrowRight');+ await expect.poll(async () => valueNow(slider)).toBe(5);+ await expect+ .poll(async () => (await runsOf(3)).at(-1))+ .toEqual({duration: 250, easing: 'cubic-bezier(0, 0, 0.58, 1)'});+ await expect.poll(async () => (await endsOf(3)).at(-1)).toBe(0.25);+});++test('after a page change, a held finger dims every other indicator on the switch, the previous current one included, and the lift restores them on it', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ // Each opacity transition that ran to its end, with how long it ran.+ await slider.evaluate(el => {+ const fades: Array<{page: number; duration: number}> = [];+ (window as unknown as {fades: typeof fades}).fades = fades;+ el.addEventListener('transitionend', event => {+ const {propertyName, elapsedTime, target} = event as TransitionEvent;+ if (propertyName === 'opacity') {+ fades.push({+ page: Number((target as HTMLElement).dataset.page),+ duration: elapsedTime,+ });+ }+ });+ });+ const fadesOf = async (index: number) =>+ page.evaluate(+ i =>+ (+ window as unknown as {fades: Array<{page: number; duration: number}>}+ ).fades+ .filter(fade => fade.page === i)+ .map(fade => fade.duration),+ index,+ );+ // End: page 3's indicator fades out over 0.25 s.+ await slider.focus();+ await page.keyboard.press('End');+ await expect.poll(async () => valueNow(slider)).toBe(5);+ await expect.poll(async () => fadesOf(2)).toEqual([0.25]);+ await page.evaluate(() => {+ (window as unknown as {fades: unknown[]}).fades.length = 0;+ });+ // A finger held on the current indicator dims the others, then lifts. Its+ // step past the last page keeps the page.+ const target = await indicatorCenter(slider, 4);+ await driver.play(+ drag(target, {x: target.x + 0.4, y: target.y}, {durationMs: 400, hz: 20}),+ );+ await expect+ .poll(async () =>+ slider.evaluate(el => el.hasAttribute('data-interacting')),+ )+ .toBe(false);+ expect(await valueNow(slider)).toBe(5);+ for (const index of [0, 1, 2, 3]) {+ await expect.poll(async () => fadesOf(index)).toEqual([0.015625, 0.015625]);+ }+});++test('after a page change made while the control is hidden, a held finger dims the previous current indicator on the switch', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ await slider.evaluate(el => {+ const fades: Array<{page: number; duration: number}> = [];+ (window as unknown as {fades: typeof fades}).fades = fades;+ el.addEventListener('transitionend', event => {+ const {propertyName, elapsedTime, target} = event as TransitionEvent;+ if (propertyName === 'opacity') {+ fades.push({+ page: Number((target as HTMLElement).dataset.page),+ duration: elapsedTime,+ });+ }+ });+ });+ const fadesOf = async (index: number) =>+ page.evaluate(+ i =>+ (+ window as unknown as {fades: Array<{page: number; duration: number}>}+ ).fades+ .filter(fade => fade.page === i)+ .map(fade => fade.duration),+ index,+ );+ // End while the control is hidden: no fade can run.+ await slider.evaluate(el => {+ el.style.display = 'none';+ el.dispatchEvent(+ new KeyboardEvent('keydown', {+ key: 'End',+ bubbles: true,+ cancelable: true,+ }),+ );+ });+ // A role locator skips a hidden element; read the attribute directly.+ const hidden = page.locator('[role="slider"]');+ await expect(hidden).toHaveAttribute('aria-valuenow', '5');+ await hidden.evaluate(el => {+ el.style.display = '';+ });+ // A finger held on the current indicator dims the others, then lifts.+ const target = await indicatorCenter(slider, 4);+ await driver.play(+ drag(target, {x: target.x + 0.4, y: target.y}, {durationMs: 400, hz: 20}),+ );+ await expect+ .poll(async () =>+ slider.evaluate(el => el.hasAttribute('data-interacting')),+ )+ .toBe(false);+ await expect.poll(async () => fadesOf(2)).toEqual([0.015625, 0.015625]);+});++test('when a tap or a key slides the window, the old indicator fades for 0.125 s or 0.25 s, not the switch', async ({+ page,+}) => {+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages');+ // Each opacity transition that ran, with how long it ran: a finished+ // transition's transitionend reports its duration.+ await slider.evaluate(el => {+ const fades: Array<{page: number; duration: number}> = [];+ (window as unknown as {fades: typeof fades}).fades = fades;+ el.addEventListener('transitionend', event => {+ const {propertyName, elapsedTime, target} = event as TransitionEvent;+ if (propertyName === 'opacity') {+ fades.push({+ page: Number((target as HTMLElement).dataset.page),+ duration: elapsedTime,+ });+ }+ });+ });+ const fadesOf = async (index: number) =>+ page.evaluate(+ i =>+ (+ window as unknown as {fades: Array<{page: number; duration: number}>}+ ).fades+ .filter(fade => fade.page === i)+ .map(fade => fade.duration),+ index,+ );+ const translateX = async () =>+ slider.evaluate(el => {+ const strip = el.children[0] as HTMLElement;+ return Number.parseFloat(getComputedStyle(strip).translate) || 0;+ });+ // Page 26 of 50 (index 25) sits in the window's last full slot, so the next+ // page slides the window.+ const before = await translateX();+ const current = await indicatorCenter(slider, 25);+ await driver.tap({x: current.x + 12, y: current.y});+ await expect.poll(async () => valueNow(slider)).toBe(27);+ await expect.poll(async () => translateX()).not.toBeCloseTo(before, 0);+ await expect.poll(async () => fadesOf(25)).toEqual([0.125]);+ // A key slides it again: the old indicator fades for 0.25 s. Page 27 also+ // switched on when it became current, so read only the fades after the key.+ await page.evaluate(() => {+ (window as unknown as {fades: unknown[]}).fades.length = 0;+ });+ await slider.focus();+ await page.keyboard.press('ArrowRight');+ await expect.poll(async () => valueNow(slider)).toBe(28);+ await expect.poll(async () => fadesOf(26)).toEqual([0.25]);+});++test('when the window jumps, a dot that mounts starts at its size in the old window and grows on the slide', async ({+ page,+}) => {+ const {slider} = await open(page, 'lab-pagecontrol--many-pages');+ const scaleOf = async (index: number) =>+ slider.evaluate((el, i) => {+ const dot = el.querySelector(`[data-page="${i}"]`) as HTMLElement | null;+ return dot == null+ ? null+ : Number.parseFloat(getComputedStyle(dot).scale);+ }, index);+ // Page 46 (index 45) is outside the window, so it is not rendered yet.+ expect(await scaleOf(45)).toBeNull();+ // The first frame after the change: before the slide starts.+ await slider.evaluate(el => {+ el.addEventListener(+ 'keydown',+ () => {+ requestAnimationFrame(() => {+ const dot = el.querySelector<HTMLElement>('[data-page="45"]');+ (window as unknown as {mounted?: number | null}).mounted =+ dot == null ? null : Number.parseFloat(getComputedStyle(dot).scale);+ });+ },+ {capture: true, once: true},+ );+ });+ await slider.focus();+ await page.keyboard.press('End');+ await expect.poll(async () => valueNow(slider)).toBe(50);+ // It mounted at its old-window size, 0, and grows to full size.+ await expect+ .poll(async () =>+ page.evaluate(+ () => (window as unknown as {mounted?: number | null}).mounted,+ ),+ )+ .toBe(0);+ await expect.poll(async () => scaleOf(45)).toBeCloseTo(DOT_SCALE, 3);+});++test('a windowed control slides one slot 50 ms after the change, on a critically damped spring', async ({+ page,+}) => {+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages');+ // Page 26 of 50 from page 1: the window starts at page 18; page 26 (index+ // 25) is in its last full slot.+ const translateX = () =>+ slider.evaluate(el => {+ const strip = el.children[0] as HTMLElement;+ return Number.parseFloat(getComputedStyle(strip).translate) || 0;+ });+ expect(await translateX()).toBeCloseTo(-18 * PITCH, 0);+ const current = await indicatorCenter(slider, 25);+ await slider.evaluate(el => {+ const strip = el.children[0] as HTMLElement;+ const trace: Array<{t: number; x: number; page: number}> = [];+ const w = window as unknown as {slide: typeof trace; changedAt?: number};+ w.slide = trace;+ const start = performance.now();+ // The change is dated when the lift that makes it begins, at its first+ // event: the pointer's, then the touch's. The page commits the change in+ // that task. The first frame that shows it and the end of the task both+ // come late on a loaded runner, so neither dates it.+ for (const type of ['pointerup', 'touchend']) {+ addEventListener(+ type,+ () => {+ w.changedAt ??= performance.now() - start;+ },+ {capture: true, once: true},+ );+ }+ const sample = () => {+ trace.push({+ t: performance.now() - start,+ x: Number.parseFloat(getComputedStyle(strip).translate) || 0,+ page: Number(el.getAttribute('aria-valuenow')),+ });+ if (performance.now() - start < 1500) {+ requestAnimationFrame(sample);+ }+ };+ requestAnimationFrame(sample);+ });+ await driver.tap({x: current.x + 12, y: current.y});+ await expect.poll(async () => valueNow(slider)).toBe(27);+ // The trace holds the slide once a sample sits on the next slot.+ await expect+ .poll(() =>+ slider.evaluate(+ (_, pitch) =>+ (window as unknown as {slide: Array<{x: number}>}).slide.some(+ s => Math.abs(s.x + 19 * pitch) < 0.3,+ ),+ PITCH,+ ),+ )+ .toBe(true);+ const {trace, changedAt} = await slider.evaluate(() => {+ const w = window as unknown as {+ slide: Array<{t: number; x: number; page: number}>;+ changedAt?: number;+ };+ return {trace: w.slide, changedAt: w.changedAt ?? NaN};+ });+ const moving = trace.filter(s => Math.abs(s.x + 18 * PITCH) > 0.2);+ const startedAt = moving[0]?.t ?? NaN;+ expect(startedAt - changedAt).toBeGreaterThan(30);+ expect(startedAt - changedAt).toBeLessThan(120);+ // Monotonic to the next slot, settled within ~0.35 s of starting.+ const xs = trace.filter(s => s.t >= startedAt).map(s => s.x);+ for (let i = 1; i < xs.length; i++) {+ expect(xs[i]).toBeLessThanOrEqual(xs[i - 1] + 0.01);+ }+ const settled = trace.find(s => Math.abs(s.x + 19 * PITCH) < 0.3);+ expect(settled).toBeDefined();+ expect((settled?.t ?? Infinity) - startedAt).toBeLessThan(350);+ // Page 27 (index 26) grows from its 7.33 px edge size to full: 9.67 px, a+ // 10 px box at scale 0.967.+ expect(+ Number.parseFloat(+ await slider.evaluate(+ el =>+ getComputedStyle(el.querySelector('[data-page="26"]') as HTMLElement)+ .scale,+ ),+ ),+ ).toBeCloseTo(0.967, 3);+});++test('RTL: a scrub toward the left goes forward and the window slides the other way', async ({+ page,+}) => {+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages', {+ rtl: true,+ });+ expect(await slider.evaluate(el => getComputedStyle(el).direction)).toBe(+ 'rtl',+ );+ const stripX = () =>+ slider.evaluate(el =>+ Number.parseFloat(+ getComputedStyle(el.children[0] as HTMLElement).translate,+ ),+ );+ // Page 26: the window starts at page 18, shifted toward the right in RTL.+ expect(await stripX()).toBeCloseTo(18 * PITCH, 0);+ const current = await indicatorCenter(slider, 25);+ const box = await slider.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ // The next pages sit to the left in RTL. Page 26 is the window's last full+ // slot. So a scrub past it toward the left runs into the content's edge and+ // jogs forward, as it does toward the right in LTR. Held 6 px past the edge,+ // about one page a second, the jog steps once about 1 s after the finger+ // crosses it. It steps again about 1 s later, after the lift.+ await driver.play(+ drag(+ current,+ {x: box.x + 14 - 6, y: current.y},+ {durationMs: 300, restMs: 1400},+ ),+ );+ await expect.poll(async () => valueNow(slider)).toBe(27);+ // The window followed one slot, toward the right.+ await expect.poll(stripX, {timeout: 2000}).toBeCloseTo(19 * PITCH, 0);+});++/**+ * 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.+ */+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 nothing slides or scales, the current indicator and a held finger’s platter change at once, and no fade runs over 200 ms on a coarse pointer (design:reduced-motion DR1, DR2)', async ({+ page,+}) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages');+ // The phone projects have a coarse pointer, where the cross-fade applies.+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(true);+ const stripX = () =>+ slider.evaluate(el =>+ Number.parseFloat(+ getComputedStyle(el.children[0] as HTMLElement).translate,+ ),+ );+ const longestFade = () =>+ slider.evaluate(el =>+ Math.max(+ 0,+ ...Array.from(el.querySelectorAll<HTMLElement>('[data-page]')).flatMap(+ dot =>+ getComputedStyle(dot)+ .transitionDuration.split(',')+ .map(d =>+ d.trim().endsWith('ms') ? parseFloat(d) : parseFloat(d) * 1000,+ ),+ ),+ ),+ );+ // A tap that moves the window: page 26 to 27. Armed before the tap, the page+ // holds every animation under the control once one has run 60 ms, past the+ // window's 50 ms delay.+ const current = await indicatorCenter(slider, 25);+ const hold = await armHold(page, slider, {minProgressMs: 60});+ await driver.tap({x: current.x + 12, y: current.y});+ await expect.poll(async () => valueNow(slider)).toBe(27);+ // Every animation is an opacity fade of at most 200 ms. No translate or+ // scale travels.+ const held = await hold.held();+ // The window's own cross-fade is among them: the animator's, not a CSS+ // transition.+ expect(held.some(a => a.kind === 'Animation')).toBe(true);+ for (const a of held) {+ // Nothing travels: the strip and the dots hold, then jump.+ for (const property of ['translate', 'scale', 'transform']) {+ expect(holdsOrJumps(a.keyframes, property)).toBe(true);+ }+ expect(a.curveEndMs).toBeLessThanOrEqual(200);+ }+ await releaseAnimations(page);+ // The window still keeps the page in view.+ await expect.poll(stripX, {timeout: 2000}).toBeCloseTo(-19 * PITCH, 0);+ expect(await longestFade()).toBeLessThanOrEqual(200);+ // A change that is not a tap (a key) changes the current indicator at once.+ await slider.focus();+ await page.keyboard.press('ArrowRight');+ await expect.poll(async () => valueNow(slider)).toBe(28);+ expect(await longestFade()).toBe(0);+ // A held finger's platter shows at once, and fades out on the lift.+ const finger = await indicatorCenter(slider, 27);+ const frames = slider.evaluate(+ el =>+ new Promise<{held: boolean; opacity: number}[]>(resolve => {+ const seen: {held: boolean; opacity: number}[] = [];+ const tick = () => {+ seen.push({+ held: el.hasAttribute('data-interacting'),+ opacity: Number(getComputedStyle(el, '::before').opacity),+ });+ const held = seen.map(frame => frame.held);+ const lifted = held.lastIndexOf(true);+ if (lifted !== -1 && seen.length - lifted > 15) {+ resolve(seen);+ } else if (seen.length < 180) {+ requestAnimationFrame(tick);+ } else {+ resolve(seen);+ }+ };+ requestAnimationFrame(tick);+ }),+ );+ await driver.play(+ drag(finger, {x: finger.x + 1, y: finger.y}, {durationMs: 400, restMs: 0}),+ );+ const seen = await frames;+ const shown = seen.findIndex(frame => frame.held);+ const lifted = seen.map(frame => frame.held).lastIndexOf(true) + 1;+ expect(shown).toBeGreaterThan(-1);+ expect(seen[shown].opacity).toBe(1);+ expect(lifted).toBeLessThan(seen.length);+ expect(seen[lifted].opacity).toBeGreaterThan(0.5);+ const platterFade = await slider.evaluate(el =>+ Math.max(+ ...getComputedStyle(el, '::before')+ .transitionDuration.split(',')+ .map(d =>+ d.trim().endsWith('ms') ? parseFloat(d) : parseFloat(d) * 1000,+ ),+ ),+ );+ expect(platterFade).toBeGreaterThan(0);+ expect(platterFade).toBeLessThanOrEqual(200);+});++test('busy main thread: a window slide finishes on time through a 600 ms block', async ({+ page,+ browserName,+}) => {+ test.skip(+ browserName === 'webkit',+ "WebKit's screencast clock is not the page's (harness README); the simulator clip covers it",+ );+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages');+ const current = await indicatorCenter(slider, 25);+ await driver.tap({x: current.x + 12, y: current.y});+ await expect+ .poll(async () =>+ slider.evaluate(+ el => (el.children[0] as HTMLElement).getAnimations().length,+ ),+ )+ .toBeGreaterThan(0);+ // Block the main thread once the slide is on the timeline (it starts 50 ms+ // after the change), for longer than the slide lasts.+ const afterBlock = await slider.evaluate(el => {+ const strip = el.children[0] as HTMLElement;+ const end = performance.now() + 600;+ while (performance.now() < end) {+ // busy+ }+ return {+ x: Number.parseFloat(getComputedStyle(strip).translate),+ running: strip+ .getAnimations()+ .filter(+ a => a.playState === 'running' && Number(a.currentTime ?? 0) < 400,+ ).length,+ };+ });+ // The compositor carried the slide to the next slot during the block.+ expect(afterBlock.x).toBeCloseTo(-19 * PITCH, 0);+ expect(afterBlock.running).toBe(0);+});++test('on an Android phone (no -webkit-touch-callout) a finger scrubs: one touch model, no platform idiom', async ({+ page,+}) => {+ const {slider, driver} = await open(page);+ expect(+ await page.evaluate(() => ({+ coarse: matchMedia('(pointer: coarse)').matches,+ ios: CSS.supports('(-webkit-touch-callout: none)'),+ })),+ ).toEqual({coarse: true, ios: false});+ const from = await indicatorCenter(slider, 2);+ const to = await indicatorCenter(slider, 4);+ await driver.play(drag(from, to, {durationMs: 600, restMs: 150}));+ await expect.poll(async () => valueNow(slider)).toBe(5);+});++test.describe('with a mouse', () => {+ test.use({hasTouch: false, isMobile: false});++ test('a long control is the full row of pages, cropped, every dot at full size', async ({+ page,+ }) => {+ const {slider} = await open(page, 'lab-pagecontrol--many-pages');+ // A mouse: the context's pointer must not still match coarse.+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const facts = await slider.evaluate(el => {+ const dots = Array.from(el.querySelectorAll<HTMLElement>('[data-page]'));+ return {+ count: dots.length,+ scales: new Set(dots.map(d => getComputedStyle(d).scale)).size,+ overflow: getComputedStyle(el).overflow,+ width: el.getBoundingClientRect().width,+ };+ });+ expect(facts).toMatchObject({count: 50, scales: 1, overflow: 'hidden'});+ expect(facts.width).toBeCloseTo(161.3, 0);+ });++ // The tap and the scrub take every pointer. The touch presentation (the+ // platter, the window, the fades) stays on a coarse one.+ test('a click on the trailing side of the current indicator moves one page forward, the leading side one back, once each (spec:AST-094 FR43)', async ({+ page,+ }) => {+ const {slider} = await open(page);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ // aria-valuenow counts from 1; the dots from 0.+ const start = (await valueNow(slider)) - 1;+ const last = Number(await slider.getAttribute('aria-valuemax')) - 1;+ const forward = start < last;+ const from = await indicatorCenter(slider, start);+ await page.mouse.click(from.x + (forward ? 12 : -12), from.y);+ const next = start + (forward ? 1 : -1);+ await expect.poll(() => valueNow(slider)).toBe(next + 1);+ // The click the browser sends after the press pages nothing more.+ await page.waitForTimeout(150);+ expect(await valueNow(slider)).toBe(next + 1);+ const back = await indicatorCenter(slider, next);+ await page.mouse.click(back.x + (forward ? -12 : 12), back.y);+ await expect.poll(() => valueNow(slider)).toBe(start + 1);+ });++ test('a drag across the dots scrubs: the page is the dot under the pointer (spec:AST-094 FR43)', async ({+ page,+ }) => {+ const {slider} = await open(page);+ // aria-valuenow counts from 1; the dots from 0.+ const last = Number(await slider.getAttribute('aria-valuemax')) - 1;+ expect(last).toBeGreaterThanOrEqual(2);+ const mid = Math.floor(last / 2);+ const first = await indicatorCenter(slider, 0);+ const end = await indicatorCenter(slider, last);+ const middle = await indicatorCenter(slider, mid);+ await page.mouse.move(first.x, first.y);+ await page.mouse.down();+ await page.mouse.move(end.x, end.y, {steps: 12});+ await expect.poll(() => valueNow(slider)).toBe(last + 1);+ await page.mouse.move(middle.x, middle.y, {steps: 8});+ await expect.poll(() => valueNow(slider)).toBe(mid + 1);+ await page.mouse.up();+ expect(+ await slider.evaluate(el => el.hasAttribute('data-interacting')),+ ).toBe(false);+ });++ test('on a cropped long row, a drag holds the row still, and the page is the dot under the pointer until the lift', async ({+ page,+ }) => {+ const {slider} = await open(page, 'lab-pagecontrol--many-pages');+ const stripX = () =>+ slider.evaluate(+ el =>+ Number.parseFloat(+ getComputedStyle(el.children[0] as HTMLElement).translate,+ ) || 0,+ );+ // aria-valuenow counts from 1; the dots from 0.+ const start = (await valueNow(slider)) - 1;+ const rest = await stripX();+ const from = await indicatorCenter(slider, start);+ await page.mouse.move(from.x, from.y);+ await page.mouse.down();+ for (let i = 1; i <= 5; i++) {+ const x = from.x + i * PITCH;+ await page.mouse.move(x, from.y, {steps: 3});+ const under = await slider.evaluate((el, at) => {+ let nearest = -1;+ let distance = Infinity;+ for (const dot of el.querySelectorAll<HTMLElement>('[data-page]')) {+ const box = dot.getBoundingClientRect();+ const d = Math.abs(box.left + box.width / 2 - at);+ if (d < distance) {+ distance = d;+ nearest = Number(dot.dataset.page);+ }+ }+ return nearest;+ }, x);+ await expect.poll(() => valueNow(slider)).toBe(under + 1);+ expect(await stripX()).toBe(rest);+ }+ await page.mouse.up();+ // At the lift the row re-centres on the page.+ await expect.poll(stripX).not.toBe(rest);+ });++ test('a held press shows no platter and dims nothing: the held look is the touch presentation', async ({+ page,+ }) => {+ const {slider} = await open(page);+ const look = () =>+ slider.evaluate(el => ({+ interacting: el.hasAttribute('data-interacting'),+ background: getComputedStyle(el).backgroundColor,+ opacities: Array.from(+ el.querySelectorAll<HTMLElement>('[data-page]'),+ ).map(dot => getComputedStyle(dot).opacity),+ }));+ const before = await look();+ const at = await indicatorCenter(slider, await valueNow(slider));+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ // Past UIPageControl's 155 ms interaction delay.+ await page.waitForTimeout(400);+ const held = await look();+ await page.mouse.up();+ expect(held).toEqual({...before, interacting: false});+ });++ for (const [story, count] of [+ ['lab-pagecontrol--default', 5],+ ['lab-pagecontrol--many-pages', 9],+ ] as const) {+ test(`every indicator paints round, as wide as it is tall (${story}, a mouse)`, async ({+ page,+ }) => {+ const {slider} = await open(page, story);+ // A mouse: the context's pointer must not still match coarse.+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const dots = await paintedDots(page, slider);+ expect(dots.length).toBeGreaterThanOrEqual(count);+ for (const dot of dots) {+ expect(+ Math.abs(dot.width - dot.height),+ JSON.stringify(dots),+ ).toBeLessThanOrEqual(1);+ }+ });+ }+});++test('the page can scroll under the control (touch-action)', async ({page}) => {+ const {slider} = await open(page);+ // The scrub's horizontal pan keeps the vertical axis for the page.+ expect(await slider.evaluate(el => getComputedStyle(el).touchAction)).toBe(+ 'pan-y pinch-zoom',+ );+});++// A recognizer that competes with the page's scroll decides within 10 px. So+// a swipe that starts vertical on the dots is the page's: it scrolls, and the+// page indicator does not change.+test("a vertical swipe that starts on the dots pages nothing and leaves every move to the page's scroll", async ({+ page,+ browserName,+}) => {+ const {slider, driver} = await open(page);+ // Room to scroll, the control well inside the viewport, and whether each+ // move reached the page cancelled (read after every listener).+ await page.evaluate(() => {+ const above = document.createElement('div');+ above.style.height = '420px';+ document.body.insertBefore(above, document.body.firstChild);+ const below = document.createElement('div');+ below.style.height = '3000px';+ document.body.appendChild(below);+ window.scrollTo(0, 0);+ const log = window as unknown as {cancelledMoves: boolean[]};+ log.cancelledMoves = [];+ addEventListener(+ 'touchmove',+ event => log.cancelledMoves.push(event.defaultPrevented),+ {passive: true},+ );+ });+ const pageBefore = await slider.getAttribute('aria-valuenow');+ const from = await indicatorCenter(slider, 3);+ await driver.play(+ drag(from, {x: from.x + 2, y: from.y - 300}, {durationMs: 500, hz: 60}),+ );+ await page.waitForTimeout(400);+ expect(await slider.getAttribute('aria-valuenow')).toBe(pageBefore);+ const cancelled = await page.evaluate(+ () => (window as unknown as {cancelledMoves: boolean[]}).cancelledMoves,+ );+ expect(cancelled.length).toBeGreaterThan(5);+ expect(cancelled.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 painted size of every indicator, in device pixels. The page decodes the+ * control's screenshot and reads each dark run across its middle row. It also+ * reads the dark run down through that run's centre. Runs cut by the+ * screenshot's edge are left out.+ */+async function paintedDots(page: Page, slider: Locator) {+ const png = await slider.screenshot();+ return page.evaluate(async b64 => {+ const img = new Image();+ img.src = `data:image/png;base64,${b64}`;+ await img.decode();+ const canvas = document.createElement('canvas');+ canvas.width = img.width;+ canvas.height = img.height;+ const g = canvas.getContext('2d');+ if (g == null) {+ throw new Error('no 2d context');+ }+ g.drawImage(img, 0, 0);+ const {data, width, height} = g.getImageData(0, 0, img.width, img.height);+ const dark = (x: number, y: number) => data[(y * width + x) * 4] < 200;+ const cy = Math.floor(height / 2);+ const dots: Array<{width: number; height: number}> = [];+ for (let x = 0; x < width;) {+ if (!dark(x, cy)) {+ x++;+ continue;+ }+ let x1 = x;+ while (x1 < width && dark(x1, cy)) {+ x1++;+ }+ const mid = (x + x1) >> 1;+ let y0 = cy;+ while (y0 > 0 && dark(mid, y0 - 1)) {+ y0--;+ }+ let y1 = cy;+ while (y1 < height - 1 && dark(mid, y1 + 1)) {+ y1++;+ }+ if (x > 0 && x1 < width) {+ dots.push({width: x1 - x, height: y1 - y0 + 1});+ }+ x = x1;+ }+ return dots;+ }, png.toString('base64'));+}++for (const [story, count] of [+ ['lab-pagecontrol--default', 5],+ // The window's two outermost dots overhang the control's box by a pixel or+ // two, so the screenshot cuts them.+ ['lab-pagecontrol--many-pages', 8],+] as const) {+ test(`every indicator paints round, as wide as it is tall (${story}, a finger)`, async ({+ page,+ }) => {+ const {slider} = await open(page, story);+ const dots = await paintedDots(page, slider);+ expect(dots.length).toBeGreaterThanOrEqual(count);+ for (const dot of dots) {+ expect(+ Math.abs(dot.width - dot.height),+ JSON.stringify(dots),+ ).toBeLessThanOrEqual(1);+ }+ });+}++test('storyboard: a tap on the trailing side @storyboard', async ({page}) => {+ const {slider, driver} = await open(page);+ const current = await indicatorCenter(slider, 2);+ const at = {x: current.x + 12, y: current.y};+ const box = await slider.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const storyboard = await touchStoryboard(+ page,+ driver,+ drag(at, {x: at.x + 0.4, y: at.y}, {durationMs: 100, hz: 20}),+ {+ name: 'page-control-tap',+ clip: {+ x: box.x - 8,+ y: box.y - 8,+ width: box.width + 16,+ height: box.height + 16,+ },+ measure: async () => ({page: await valueNow(slider)}),+ },+ );+ await storyboard.write(test.info());+ const pages = storyboard.frames.map(f => (f.data as {page: number}).page);+ // Page 3 until the lift, page 4 after it.+ expect(pages[0]).toBe(3);+ expect(pages.slice(0, -1).every(p => p === 3)).toBe(true);+ expect(pages[pages.length - 1]).toBe(4);+});++test('storyboard: a scrub across the control @storyboard', async ({page}) => {+ const {slider, driver} = await open(page);+ const from = await indicatorCenter(slider, 2);+ const end = await indicatorCenter(slider, 4);+ const box = await slider.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const storyboard = await touchStoryboard(+ page,+ driver,+ drag(from, {x: end.x + 4, y: from.y}, {durationMs: 600, hz: 10}),+ {+ name: 'page-control-scrub',+ clip: {+ x: box.x - 8,+ y: box.y - 8,+ width: box.width + 16,+ height: box.height + 16,+ },+ measure: async () => ({+ page: await valueNow(slider),+ interacting: await slider.evaluate(el =>+ el.hasAttribute('data-interacting'),+ ),+ }),+ },+ );+ await storyboard.write(test.info());+ const pages = storyboard.frames.map(f => (f.data as {page: number}).page);+ // Pages only move forward, one indicator at a time, and end on page 5.+ for (let i = 1; i < pages.length; i++) {+ expect(pages[i] - pages[i - 1]).toBeGreaterThanOrEqual(0);+ expect(pages[i] - pages[i - 1]).toBeLessThanOrEqual(1);+ }+ expect(pages[pages.length - 1]).toBe(5);+});++test('storyboard: the window slides one slot @storyboard', async ({page}) => {+ const {slider, driver} = await open(page, 'lab-pagecontrol--many-pages');+ const current = await indicatorCenter(slider, 25);+ const box = await slider.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ // Armed before the tap, the page holds the change's motion as it starts,+ // however late the test reads it. That motion is the old indicator's fade+ // and the slide, which starts 50 ms after the change.+ const hold = await armHold(page, slider);+ await driver.tap({x: current.x + 12, y: current.y});+ const held = await hold.held();+ const {storyboard} = await animationStoryboard(page, {+ name: 'page-control-window-slide',+ held,+ clip: {+ x: box.x - 24,+ y: box.y - 8,+ width: box.width + 48,+ height: box.height + 16,+ },+ measure: async () =>+ slider.evaluate(el => ({+ x: Number.parseFloat(+ getComputedStyle(el.children[0] as HTMLElement).translate,+ ),+ grow: Number.parseFloat(+ getComputedStyle(el.querySelector('[data-page="26"]') as HTMLElement)+ .scale,+ ),+ })),+ });+ await storyboard.write(test.info());+ const frames = storyboard.frames.map(+ f => f.data as {x: number; grow: number},+ );+ // The strip moves one slot left without overshoot while the new current+ // indicator grows from its edge size (0.7588) to full.+ for (let i = 1; i < frames.length; i++) {+ expect(frames[i].x).toBeLessThanOrEqual(frames[i - 1].x + 0.01);+ expect(frames[i].grow).toBeGreaterThanOrEqual(frames[i - 1].grow - 0.001);+ }+ expect(frames[frames.length - 1].x).toBeCloseTo(-19 * PITCH, 0);+ expect(frames[0].grow).toBeLessThan(0.9);+ // Full size: 9.67 px, a 10 px box at scale 0.967.+ expect(frames[frames.length - 1].grow).toBeCloseTo(0.967, 2);+});diff --git a/packages/lab/src/PageControl/index.ts b/packages/lab/src/PageControl/index.tsnew file mode 100644index 0000000000..0adb867a4f--- /dev/null+++ b/packages/lab/src/PageControl/index.ts@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file index.ts+ * @input Imports from PageControl.tsx+ * @output Re-exports PageControl and its props type+ * @position Barrel export; consumed by packages/lab/src/index.ts+ */++export {PageControl} from './PageControl';+export type {PageControlProps} from './PageControl';diff --git a/packages/lab/src/PageControl/pageControlModel.test.ts b/packages/lab/src/PageControl/pageControlModel.test.tsnew file mode 100644index 0000000000..1ca4448eb7--- /dev/null+++ b/packages/lab/src/PageControl/pageControlModel.test.ts@@ -0,0 +1,161 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pageControlModel.test.ts+ * @input vitest, pageControlModel.ts, the UIKit page-control table+ * @output Proves the page-control math against UIPageControl's measurements:+ * sizes, the 50-page window, the tap rule, the scrub and the jog's cadence+ * @position Testing+ */++import {describe, expect, it} from 'vitest';+import {+ fullPages,+ indicatorSize,+ jogInterval,+ pageControlLayout,+ PITCH,+ scrubTarget,+ tapTarget,+ windowFor,+} from './pageControlModel';++describe('pageControlLayout', () => {+ it("matches UIPageControl's measured width for 5 pages", () => {+ const layout = pageControlLayout(5);+ expect(layout.rowWidth).toBeCloseTo(80.35, 1);+ expect(layout.width).toBeCloseTo(108.3, 0);+ expect(layout.slots).toBe(5);+ expect(layout.isWindowed).toBe(false);+ });++ it('caps the width at 161.3 for 50 pages and shows ten slots', () => {+ const layout = pageControlLayout(50);+ expect(layout.width).toBe(161.3);+ expect(layout.slots).toBe(10);+ expect(layout.isWindowed).toBe(true);+ });++ it('is empty without pages', () => {+ expect(pageControlLayout(0)).toEqual({+ width: 28,+ slots: 0,+ rowWidth: 0,+ isWindowed: false,+ });+ });+});++/** The sizes of the ten shown slots, rounded to 0.01 pt. */+function shown(count: number, windowStart: number): number[] {+ return Array.from(+ {length: 10},+ (_, i) =>+ Math.round(indicatorSize(count, windowStart, windowStart + i) * 100) /+ 100,+ );+}++describe('the window of a 50-page control (as measured at pages 0, 10, 25, 49)', () => {+ it('page 0: pages 0–7 full, then 7.33 and 4.31', () => {+ const start = windowFor(50, 0, 0);+ expect(start).toBe(0);+ expect(shown(50, start)).toEqual([+ 9.67, 9.67, 9.67, 9.67, 9.67, 9.67, 9.67, 9.67, 7.33, 4.31,+ ]);+ expect(indicatorSize(50, start, 10)).toBe(0);+ });++ it('page 10 from page 0: the current page in the last full slot, edges shrunk on both sides', () => {+ const start = windowFor(50, 0, 10);+ expect(start).toBe(3);+ expect(shown(50, start)).toEqual([+ 4.31, 7.33, 9.67, 9.67, 9.67, 9.67, 9.67, 9.67, 7.33, 4.31,+ ]);+ expect(fullPages(50, start)).toEqual([5, 10]);+ });++ it('page 25 from page 10: the same shape, the current page last', () => {+ const start = windowFor(50, 3, 25);+ expect(fullPages(50, start)[1]).toBe(25);+ });++ it('page 49: eight full slots ending at the current page, 7.33 and 4.31 on the left', () => {+ const start = windowFor(50, 18, 49);+ expect(start).toBe(40);+ expect(shown(50, start)).toEqual([+ 4.31, 7.33, 9.67, 9.67, 9.67, 9.67, 9.67, 9.67, 9.67, 9.67,+ ]);+ });++ it('moves only when the current page would land in a shrunk slot', () => {+ expect(windowFor(50, 3, 7)).toBe(3);+ expect(windowFor(50, 3, 11)).toBe(4);+ expect(windowFor(50, 3, 4)).toBe(2);+ });++ it('a control with ten pages or fewer never windows', () => {+ expect(windowFor(10, 0, 9)).toBe(0);+ expect(shown(10, 0)).toEqual(Array.from({length: 10}, () => 9.67));+ });+});++describe('tapTarget', () => {+ it('a tap on the trailing side moves forward one page, the leading side back', () => {+ expect(tapTarget(60, 50, 2, 5, false)).toBe(3);+ expect(tapTarget(40, 50, 2, 5, false)).toBe(1);+ });++ it('mirrors in RTL', () => {+ expect(tapTarget(40, 50, 2, 5, true)).toBe(3);+ expect(tapTarget(60, 50, 2, 5, true)).toBe(1);+ });++ it('stops at the first and last pages', () => {+ expect(tapTarget(60, 50, 4, 5, false)).toBe(4);+ expect(tapTarget(40, 50, 0, 5, false)).toBe(0);+ });+});++describe('scrubTarget', () => {+ it('switches at the midpoint between indicator centres (measured 192.3 / 210.3 / 229.0 on a 5-page control whose first centre is at 166)', () => {+ // The measured switch points, relative to the first indicator's centre.+ expect(scrubTarget(192.3 - 166 - 0.5, 5, 0)).toBe(1);+ expect(scrubTarget(192.3 - 166 + 0.5, 5, 0)).toBe(2);+ expect(scrubTarget(210.3 - 166 - 0.5, 5, 0)).toBe(2);+ expect(scrubTarget(210.3 - 166 + 0.5, 5, 0)).toBe(3);+ expect(scrubTarget(1.5 * PITCH + 2.5 * PITCH, 5, 0)).toBe(4);+ });++ it('stays within the pages', () => {+ expect(scrubTarget(-40, 5, 0)).toBe(0);+ expect(scrubTarget(400, 5, 0)).toBe(4);+ });++ it('in a window, stays within the pages shown at full size', () => {+ // Window at 3 (page 10 current): full pages 5–10.+ expect(scrubTarget(0, 50, 3)).toBe(5);+ expect(scrubTarget(5 * PITCH, 50, 3)).toBe(8);+ expect(scrubTarget(9 * PITCH, 50, 3)).toBe(10);+ });+});++describe('jogInterval', () => {+ it('does not step inside the content', () => {+ expect(jogInterval(0)).toBe(Infinity);+ expect(jogInterval(-5)).toBe(Infinity);+ });++ it('steps faster the further past the edge, at most 15 pages a second (the least-squares fit of the measured run: 266 ms at 19 pt, 66 ms at 76 pt)', () => {+ expect(jogInterval(19)).toBeCloseTo(0.304, 2);+ expect(jogInterval(45.7)).toBeCloseTo(0.126, 2);+ expect(jogInterval(76)).toBeCloseTo(0.076, 2);+ expect(jogInterval(110)).toBeCloseTo(1 / 15, 5);+ });++ it('a run toward the first page steps at the measured 10 pages a second 77 pt past the edge, where the run toward the last steps at 13.3 (spec:AST-094 FR1)', () => {+ expect(1 / jogInterval(77, -1)).toBeCloseTo(10, 0);+ expect(1 / jogInterval(77, 1)).toBeCloseTo(13.3, 1);+ expect(jogInterval(150, -1)).toBeCloseTo(1 / 15, 5);+ });+});diff --git a/packages/lab/src/PageControl/pageControlModel.ts b/packages/lab/src/PageControl/pageControlModel.tsnew file mode 100644index 0000000000..b57f84a375--- /dev/null+++ b/packages/lab/src/PageControl/pageControlModel.ts@@ -0,0 +1,244 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pageControlModel.ts+ * @input The page-control table (`pageControl`, pageControlTable.ts)+ * @output Pure page-control math: the control's size, the window of+ * indicators, a tap's step, a scrub's page and the jog past the edge+ * @position Model of the lab PageControl; no DOM+ *+ * Coordinates are along the row, in px, from the centre of the window's+ * first slot. RTL callers mirror them before the call.+ *+ * SYNC: When modified, update pageControlModel.test.ts and PageControl.tsx.+ */++import {pageControl} from './pageControlTable';++const PC = pageControl;++/**+ * Each indicator is a whole-pixel box scaled to its size (9.67 px, or the+ * window's shrunk edge sizes). Chromium paints a box's edges on whole CSS+ * pixels. So a 9.67 px box paints 9 or 10 px wide, and every few indicators+ * one is an oval. A 10 px box keeps its shape wherever it falls, and `scale`+ * brings it to size around its centre.+ */+export const BOX = Math.ceil(PC.indicatorSize);++/** An opacity transition of `ms` on the curve's control points. */+export const fadeOf = (ms: number, curve: ReadonlyArray<number>): string =>+ `opacity ${ms / 1000}s cubic-bezier(${curve.join(', ')})`;++/** The opacity switch every indicator change makes under a finger. */+export const SWITCH = fadeOf(PC.switchMs, PC.switchCurve);++/** `page` rounded into 0 to `count - 1`. */+export function clampPage(page: number, count: number): number {+ return Math.max(0, Math.min(count - 1, Math.round(page)));+}++/** What asked for a page: a tap fades the old indicator faster. */+export type ChangeKind = 'tap' | 'other';++/** The control's state as its gestures and timers read it, after renders. */+export interface Latest {+ current: number;+ pages: number;+ windowStart: number;+ onChange: (page: number) => void;+}++/** Distance between neighbouring indicators' centres, px. */+export const PITCH = PC.indicatorSize + PC.indicatorSpacing;++export interface PageControlLayout {+ /** The control's width, px. */+ width: number;+ /** How many indicator slots show. */+ slots: number;+ /** Width of the row of shown slots, px; may exceed `width`. */+ rowWidth: number;+ /** Whether there are more pages than slots, so the row is a window. */+ isWindowed: boolean;+}++/** The control's size for `count` pages (UIPageControl's, as measured). */+export function pageControlLayout(count: number): PageControlLayout {+ const n = Math.max(0, Math.floor(count));+ const slots = Math.min(n, PC.visibleSlots);+ const rowWidth = slots === 0 ? 0 : slots * PITCH - PC.indicatorSpacing;+ const natural =+ (n === 0 ? 0 : n * PITCH - PC.indicatorSpacing) + 2 * PC.horizontalPadding;+ const hundredths = (value: number) => Math.round(value * 100) / 100;+ return {+ width: hundredths(Math.min(natural, PC.maxWidth)),+ slots,+ rowWidth: hundredths(rowWidth),+ isWindowed: n > PC.visibleSlots,+ };+}++/** Slots rendered on each side of the window, so a slide has its dots. */+export const RENDER_MARGIN = 3;++/**+ * The pages a windowed row renders, as `[first, last)`: the window's slots+ * and RENDER_MARGIN slots on each side.+ */+export function renderedPages(+ count: number,+ windowStart: number,+): [first: number, last: number] {+ const {slots} = pageControlLayout(count);+ return [+ Math.max(0, windowStart - RENDER_MARGIN),+ Math.min(count, windowStart + slots + RENDER_MARGIN),+ ];+}++/**+ * With a fine pointer, the row shows every page at full size, cropped by the+ * control when it is wider. This is how far the row shifts toward its start,+ * in px. The current indicator stays in view: centred where it can be,+ * pinned at either end.+ */+export function croppedRowOffset(count: number, current: number): number {+ const n = Math.max(0, Math.floor(count));+ const row = n === 0 ? 0 : n * PITCH - PC.indicatorSpacing;+ const visible = pageControlLayout(n).width - 2 * PC.horizontalPadding;+ if (row <= visible) {+ return 0;+ }+ const center = current * PITCH + PC.indicatorSize / 2;+ return Math.max(0, Math.min(row - visible, center - visible / 2));+}++/**+ * Diameter of page `page`'s indicator while the window starts at+ * `windowStart`. It is full inside the window and 0 outside it. Where pages+ * continue, the last two slots on that side take the two edge sizes.+ */+export function indicatorSize(+ count: number,+ windowStart: number,+ page: number,+): number {+ if (count <= PC.visibleSlots) {+ return page >= 0 && page < count ? PC.indicatorSize : 0;+ }+ const slot = page - windowStart;+ if (slot < 0 || slot >= PC.visibleSlots) {+ return 0;+ }+ const [near, far] = PC.edgeIndicatorSizes;+ if (windowStart > 0) {+ if (slot === 0) {+ return far;+ }+ if (slot === 1) {+ return near;+ }+ }+ if (windowStart + PC.visibleSlots < count) {+ if (slot === PC.visibleSlots - 1) {+ return far;+ }+ if (slot === PC.visibleSlots - 2) {+ return near;+ }+ }+ return PC.indicatorSize;+}++/** First and last pages shown at full size. */+export function fullPages(+ count: number,+ windowStart: number,+): [first: number, last: number] {+ if (count <= PC.visibleSlots) {+ return [0, count - 1];+ }+ const first = windowStart + (windowStart > 0 ? 2 : 0);+ const last =+ windowStart ++ PC.visibleSlots -+ 1 -+ (windowStart + PC.visibleSlots < count ? 2 : 0);+ return [first, last];+}++/**+ * The window after the current page changes: unchanged while the current+ * page is at full size, otherwise moved the least that makes it so.+ */+export function windowFor(+ count: number,+ windowStart: number,+ current: number,+): number {+ if (count <= PC.visibleSlots) {+ return 0;+ }+ const maxStart = count - PC.visibleSlots;+ let start = Math.max(0, Math.min(maxStart, windowStart));+ for (let guard = 0; guard <= count; guard++) {+ const [first, last] = fullPages(count, start);+ if (current > last && start < maxStart) {+ start += 1;+ } else if (current < first && start > 0) {+ start -= 1;+ } else {+ break;+ }+ }+ return start;+}++/**+ * The page a tap moves to: one page toward the side of the current+ * indicator the tap landed on (trailing = forward), clamped to the pages.+ * `x` and `currentCenter` are in the same horizontal coordinates.+ */+export function tapTarget(+ x: number,+ currentCenter: number,+ current: number,+ count: number,+ isRtl: boolean,+): number {+ const trailing = isRtl ? x < currentCenter : x > currentCenter;+ const next = current + (trailing ? PC.tapStep : -PC.tapStep);+ return Math.max(0, Math.min(count - 1, next));+}++/**+ * The page under a scrubbing finger, `x` px along the row from the centre of+ * the window's first slot. It switches at the midpoint between indicators.+ * It stays within the pages shown at full size.+ */+export function scrubTarget(+ x: number,+ count: number,+ windowStart: number,+): number {+ const slot = Math.floor(x / PITCH + PC.scrubSwitchPoint);+ const start = count <= PC.visibleSlots ? 0 : windowStart;+ const [first, last] = fullPages(count, start);+ return Math.max(first, Math.min(last, start + slot));+}++/**+ * Seconds until the next page while a scrubbing finger is `distance` px past+ * the edge of the control's content. It is Infinity when it is not past it.+ * `direction` is 1 toward the last page and -1 toward the first. UIKit's run+ * toward the first page is slower.+ */+export function jogInterval(distance: number, direction = 1): number {+ if (!(distance > 0)) {+ return Infinity;+ }+ const perPoint =+ direction < 0 ? PC.jogRatePerPointBackward : PC.jogRatePerPoint;+ return 1 / Math.min(PC.jogMaxRate, perPoint * distance);+}diff --git a/packages/lab/src/PageControl/pageControlTable.ts b/packages/lab/src/PageControl/pageControlTable.tsnew file mode 100644index 0000000000..b990c59ef8--- /dev/null+++ b/packages/lab/src/PageControl/pageControlTable.ts@@ -0,0 +1,200 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pageControlTable.ts+ * @input Nothing; data only+ * @output Exports `pageControl`: UIPageControl's measured geometry, alphas,+ * tap and scrub rules, indicator window, fades and jog past the edge+ * @position PageControl's own measured table; only PageControl reads it+ *+ * The values come from a stock UIPageControl on the iOS 26.2 simulator.+ * Geometry is in points. Touch motion stays internal, with no theme role.+ *+ * SYNC: When modified, update pageControlModel.ts.+ */++/** UIPageControl on iOS 26. */+export const pageControl = {+ /**+ * Diameter of one page indicator.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026. A+ * 5-page control: indicator dots 9.67 pt.+ */+ indicatorSize: 9.67,+ /**+ * Space between neighbouring indicators.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026. A+ * 5-page control: the indicator strip is 80.3 pt wide, 5 × 9.67 + 4 × 8.+ */+ indicatorSpacing: 8,+ /**+ * Space between the strip and the control's leading and trailing edges.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026. A+ * 5-page control 108.3 pt wide around an 80.3 pt strip.+ */+ horizontalPadding: 14,+ /**+ * The control's height.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026.+ * intrinsicContentSize 108.3 × 25.67 at 5 pages and 161.3 × 25.67 at 50.+ */+ height: 25.67,+ /**+ * The control is never wider than this, however many pages: past it the+ * indicators scroll in a window (size(forNumberOfPages: 50) is 903.3 pt).+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026.+ * intrinsicContentSize capped at 161.3 pt wide at 50 pages.+ */+ maxWidth: 161.3,+ /**+ * Opacity of the current page's indicator, of the indicator colour.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026. The+ * default tint renders the current indicator white α 1 in light and dark+ * (#FFFFFF over black).+ */+ currentIndicatorAlpha: 1,+ /**+ * Opacity of every other page's indicator, of the indicator colour.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026. The+ * default tint renders the other indicators white α 0.45 in light and dark+ * (#737373 over black).+ */+ otherIndicatorAlpha: 0.45,+ /**+ * A tap on the trailing side of the current page's indicator moves one+ * page forward. A tap on the leading side moves one back. The control+ * reports the change when the finger lifts.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 23 2026. HID+ * taps on a 5-page control: valueChanged at the lift, about 70–90 ms after+ * the touch, one page per tap.+ */+ tapStep: 1,+ /**+ * How far a finger travels from where it landed before the control+ * scrubs: from then on the page is the indicator under the finger.+ * Movement alone starts it; holding first changes nothing.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. HID+ * drags across 5- and 50-page controls, from a still touch and after an+ * 800 ms hold. The first page change comes at 16.3 and 16.7 pt.+ */+ scrubStartDistance: 16,+ /**+ * While scrubbing, the page switches at the midpoint between two+ * indicators' centres: one page per indicator pitch (9.67 + 8 pt), the+ * same going back.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 5-page control: changes at x 192.3, 210.3, 229.0 against midpoints 192.3,+ * 210.2, 227.8 between indicator centres.+ */+ scrubSwitchPoint: 0.5,+ /**+ * A finger held on the control turns it interactive after this many+ * milliseconds, moving or not. Then the platter shows, and the other+ * indicators dim to `interactingOtherIndicatorAlpha`.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. The+ * indicators' contentsMultiplyColor animations start 153–160 ms after+ * touch-down, interactionState 2.+ */+ interactionDelayMs: 155,+ /**+ * Opacity of the indicators other than the current one while a finger is+ * on the control.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. Held+ * control: the other indicators' tint alpha 0.25.+ */+ interactingOtherIndicatorAlpha: 0.25,+ /**+ * At most this many indicator slots show. Past it the row is a window+ * that moves only when the current page would land in a shrunk slot.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 50-page control at pages 0, 10, 25 and 49: ten slots on the 17.67 pt+ * pitch, centred on the control.+ */+ visibleSlots: 10,+ /**+ * Where pages continue past the window, its last two slots on that side+ * shrink to these diameters, outermost last; the slots beyond show+ * nothing.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 50-page control: edge indicators 7.33 and 4.31 pt (scale 0.7588 and+ * 0.4461).+ */+ edgeIndicatorSizes: [7.33, 4.31],+ /**+ * When the window moves, every indicator slides to its new slot and+ * takes its new size on this spring.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 50-page control at page 10 tapped to 11: UIView spring dampingRatio 1,+ * response 0.15 (tracking), the strip sliding 17.67 pt in about 0.2 s.+ */+ windowSlide: {response: 0.15, dampingRatio: 1},+ /**+ * The window starts to move this many milliseconds after the page changes;+ * the new current indicator lights first, in its shrunk slot.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 50-page control at page 10 tapped to 11: the strip starts to slide about+ * 50 ms after valueChanged.+ */+ windowSlideDelayMs: 50,+ /**+ * After a tap, the indicator that stops being current fades to the+ * other indicators' opacity over this many milliseconds, on `fadeOutCurve`.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. Taps:+ * contentsMultiplyColor CABasicAnimation 0.125 s.+ */+ tapFadeOutMs: 125,+ /**+ * After any other page change (scrubbing, or the app setting the page),+ * the indicator that stops being current fades over this many+ * milliseconds.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026.+ * Programmatic currentPage changes and scrubs: contentsMultiplyColor+ * CABasicAnimation 0.25 s.+ */+ fadeOutMs: 250,+ /**+ * The curve of both fades out.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. The+ * fade's timing function control points (0, 0, 0.58, 1).+ */+ fadeOutCurve: [0, 0, 0.58, 1],+ /**+ * Any other opacity change takes this many milliseconds: a switch. Such+ * changes are the new current indicator lighting, the platter showing, and+ * the others dimming under a finger and recovering at the lift.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026.+ * contentsMultiplyColor and opacity CABasicAnimations 0.015625 s.+ */+ switchMs: 15.625,+ /**+ * The curve of those switches.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. The+ * switch's timing function control points (0.42, 0, 0.58, 1).+ */+ switchCurve: [0.42, 0, 0.58, 1],+ /**+ * Past the window's edge, while scrubbing toward the last page, the+ * control steps pages on its own. The rate is this many pages per second+ * for each point the finger is past the content's edge.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 50-page control scrubbed right at 40 pt/s. Intervals ran from 266 ms at+ * 19 pt past the content edge to 66 ms at 76 pt. A least-squares fit gives+ * 0.173 pages/s per pt.+ */+ jogRatePerPoint: 0.173,+ /**+ * The same toward the first page, where the run is slower.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 50-page control scrubbed left: the steps settled at 10 pages/s 77 pt past+ * the content edge, where the rightward rate gives 13.3.+ */+ jogRatePerPointBackward: 0.13,+ /**+ * The fastest the control steps pages past the window's edge, pages per+ * second.+ * @source measured: UIKit lab, iPhone 17 Pro simulator, Oct 24 2026. A+ * 50-page control held 108 pt past the content edge: one page every 61–71+ * ms.+ */+ jogMaxRate: 15,+} as const;diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 27dc575c75..ca6adeb0db 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -339,6 +339,9 @@ export {type NavigationStackProps,} from './NavigationStack';+// PageControl: UIPageControl's row of page indicators.+export {PageControl, type PageControlProps} from './PageControl';+// RichTextEditor (RFC meta/astryx#3899) moved out of @astryxdesign/lab into// its own package, @astryxdesign/richtext. Import it from there:// import {RichTextEditor, RichTextView} from '@astryxdesign/richtext';