diff --git a/.changeset/selectable-card-mark-touch-one-frame.md b/.changeset/selectable-card-mark-touch-one-frame.md new file mode 100644 index 0000000000000..5c54b5dd69a77 --- /dev/null +++ b/.changeset/selectable-card-mark-touch-one-frame.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] Under a finger (a coarse primary pointer), a SelectableCard's selection mark now changes in one frame, as UIKit's selection marks do. Before, the inset ring appeared or vanished at once while the border faded over the theme's fast duration, so the mark changed in two steps. With a mouse the card keeps the theme's fade, and under Reduce Motion a mouse's change is now immediate. + +@vjeux diff --git a/.changeset/selection-marks-touch-one-frame.md b/.changeset/selection-marks-touch-one-frame.md new file mode 100644 index 0000000000000..e7f1a98638ced --- /dev/null +++ b/.changeset/selection-marks-touch-one-frame.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] Under a finger (a coarse primary pointer), a checkbox or radio mark now changes in the frame the selection lands, the way UIKit shows a selection mark. The box or circle used to fade between its two colors over the theme duration, so a tap first showed half-filled frames. With a mouse the marks keep the theme duration and easing, and under Reduce Motion they still change at once. + +@vjeux diff --git a/packages/core/src/Indicator/CheckboxIndicator.tsx b/packages/core/src/Indicator/CheckboxIndicator.tsx index ca8594e71c04c..d79e8f764d4de 100644 --- a/packages/core/src/Indicator/CheckboxIndicator.tsx +++ b/packages/core/src/Indicator/CheckboxIndicator.tsx @@ -2,7 +2,8 @@ /** * @file CheckboxIndicator.tsx - * @input Indicator state props + * @input Indicator state props; the mark-change clock of a touch presentation + * (selectionMotion.stylex.ts, mirroring motion/uikit/selection.ts) * @output Exports CheckboxIndicator — the default checkbox selection visual * @position Decorative checkbox visual shared by CheckboxInput, CheckboxList, * and decorative menu markers @@ -20,8 +21,12 @@ import {isRenderable} from '../utils/isRenderable'; import {mergeProps} from '../utils/mergeProps'; import {themeProps} from '../utils/themeProps'; import {indicatorScope} from './indicator.markers.stylex'; +import {selectionMotionConsts} from './selectionMotion.stylex'; import type {IndicatorProps} from './types'; +/** How long the mark takes to change under a finger: one frame. */ +const MARK_CHANGE = `${selectionMotionConsts.markChangeMs}ms`; + const styles = stylex.create({ box: { boxSizing: 'border-box', @@ -35,7 +40,14 @@ const styles = stylex.create({ transitionProperty: 'background-color, border-color', transitionDuration: { default: durationVars['--duration-fast'], - '@media (prefers-reduced-motion: reduce)': '0s', + // Under a finger the mark changes in the frame the selection lands, as + // UIKit's marks do (motion/uikit/selection.ts). Under Reduce Motion a + // mouse's change is immediate too. + // The keys are spelled out: an imported at-rule key lands in another + // StyleX priority layer than a literal one. + '@media (pointer: coarse)': MARK_CHANGE, + '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))': + '0s', }, transitionTimingFunction: easeVars['--ease-standard'], }, diff --git a/packages/core/src/Indicator/Indicator.doc.mjs b/packages/core/src/Indicator/Indicator.doc.mjs index baeea1c083f94..d97b833588be9 100644 --- a/packages/core/src/Indicator/Indicator.doc.mjs +++ b/packages/core/src/Indicator/Indicator.doc.mjs @@ -26,7 +26,7 @@ export const docs = { name: 'CheckboxIndicator', displayName: 'Checkbox Indicator', description: - 'The checkbox visual: a square box with a checkmark or an indeterminate bar. Decorative (aria-hidden); the owning control keeps the input, role, accessible name, focus, and keyboard behavior.', + 'The checkbox visual: a square box with a checkmark or an indeterminate bar. Decorative (aria-hidden); the owning control keeps the input, role, accessible name, focus, and keyboard behavior. Under a finger (a coarse primary pointer) the box changes in one frame, as UIKit selection marks do; with a mouse its colors fade over the theme duration.', props: [ { name: 'state', @@ -97,7 +97,7 @@ export const docs = { name: 'RadioIndicator', displayName: 'Radio Indicator', description: - 'The radio visual: a circle with a filled inner dot when selected. Draws in both states; an unselected radio is an empty circle, which is what lets it stand in for a checkmark in a selection slot.', + 'The radio visual: a circle with a filled inner dot when selected. Draws in both states; an unselected radio is an empty circle, which is what lets it stand in for a checkmark in a selection slot. Under a finger (a coarse primary pointer) the circle changes in one frame, as UIKit selection marks do; with a mouse its colors fade over the theme duration.', props: [ { name: 'state', diff --git a/packages/core/src/Indicator/RadioIndicator.tsx b/packages/core/src/Indicator/RadioIndicator.tsx index 860f77fd16f36..9a7178ae10f60 100644 --- a/packages/core/src/Indicator/RadioIndicator.tsx +++ b/packages/core/src/Indicator/RadioIndicator.tsx @@ -2,7 +2,8 @@ /** * @file RadioIndicator.tsx - * @input Indicator state props + * @input Indicator state props; the mark-change clock of a touch presentation + * (selectionMotion.stylex.ts, mirroring motion/uikit/selection.ts) * @output Exports RadioIndicator — the default radio selection visual * @position Decorative radio visual shared by RadioList, decorative menu * markers, and any selection slot themed to use a radio @@ -20,8 +21,12 @@ import {isRenderable} from '../utils/isRenderable'; import {mergeProps} from '../utils/mergeProps'; import {themeProps} from '../utils/themeProps'; import {indicatorScope} from './indicator.markers.stylex'; +import {selectionMotionConsts} from './selectionMotion.stylex'; import type {IndicatorProps} from './types'; +/** How long the mark takes to change under a finger: one frame. */ +const MARK_CHANGE = `${selectionMotionConsts.markChangeMs}ms`; + const styles = stylex.create({ circle: { boxSizing: 'border-box', @@ -39,7 +44,14 @@ const styles = stylex.create({ transitionProperty: 'background-color, border-color', transitionDuration: { default: durationVars['--duration-fast'], - '@media (prefers-reduced-motion: reduce)': '0s', + // Under a finger the mark changes in the frame the selection lands, as + // UIKit's marks do (motion/uikit/selection.ts). Under Reduce Motion a + // mouse's change is immediate too. + // The keys are spelled out: an imported at-rule key lands in another + // StyleX priority layer than a literal one. + '@media (pointer: coarse)': MARK_CHANGE, + '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))': + '0s', }, transitionTimingFunction: easeVars['--ease-standard'], }, diff --git a/packages/core/src/Indicator/__tests__/SelectionMarks.interaction.browser.spec.ts b/packages/core/src/Indicator/__tests__/SelectionMarks.interaction.browser.spec.ts new file mode 100644 index 0000000000000..c0af7912890ea --- /dev/null +++ b/packages/core/src/Indicator/__tests__/SelectionMarks.interaction.browser.spec.ts @@ -0,0 +1,779 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file SelectionMarks.interaction.browser.spec.ts + * @input The built CheckboxList and RadioList Default stories, real touch + * input (Chromium CDP, WebKit's tap) and the interaction harness + * @output Proofs that under a finger a mark changes in the frame the + * selection lands, for a checkbox, both radios and under Reduce Motion. + * A mouse keeps the theme's fade (the negative control). A tap's frames + * show only the two states (storyboard). A main thread blocked after the + * change keeps showing the whole mark. + * @position Real-engine layer of the touch mark change; the stylesheet layer + * is Indicator/selectionMotion.test.ts. + */ + +import {expect, test, type Page} from '@playwright/test'; +// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned. +import {PNG} from 'pngjs'; +import { + blockMainThread, + castStoryboard, + frames, + openStory, + startScreencast, + touchDriver, + withStorybook, + writeEvidence, + type CastFrame, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +type RGB = [number, number, number]; + +/** What the page saw in the microtask after the mark's class changed. */ +interface MarkRead { + /** The first background colour computed after the change. */ + first: string; + /** Animations on the mark right after that computation. */ + animations: {property: string; duration: number}[]; +} + +const MARK = { + checkbox: '.astryx-checkbox-indicator', + radio: '.astryx-radio-indicator', +} as const; + +/** + * Watches the mark of the option named `name`. When React writes its new + * state, the observer runs as a microtask, before any frame. It computes the + * mark's style once and records the colour and any transition it started. + * With `hold`, it also pauses those animations where they begin, so nothing + * presents them until a test moves them (seekMark). + */ +async function watchMark( + page: Page, + role: 'checkbox' | 'radio', + name: string, + {hold = false}: {hold?: boolean} = {}, +): Promise { + await page.getByRole(role, {name}).evaluate( + (input, {selector, key, hold}) => { + // The option's row: a CheckboxList `li`, a RadioList item. + const row = input.closest('.astryx-item, li'); + const mark = row?.querySelector(selector); + if (mark == null) { + throw new Error(`no mark for ${key}`); + } + const reads = (( + window as unknown as Record + ).__selectionMarkReads ??= {}) as Record; + const observer = new MutationObserver(() => { + if (reads[key] != null) { + return; + } + const first = getComputedStyle(mark).backgroundColor; + reads[key] = { + first, + animations: mark.getAnimations().map(animation => ({ + property: + (animation as CSSTransition).transitionProperty ?? + animation.constructor.name, + duration: Number(animation.effect?.getTiming().duration ?? 0), + })), + }; + if (hold) { + for (const animation of mark.getAnimations()) { + animation.pause(); + } + } + observer.disconnect(); + }); + observer.observe(mark, {attributes: true, attributeFilter: ['class']}); + }, + {selector: MARK[role], key: `${role}:${name}`, hold}, + ); +} + +async function readMark( + page: Page, + role: 'checkbox' | 'radio', + name: string, +): Promise { + const key = `${role}:${name}`; + await page.waitForFunction( + k => + ((window as unknown as Record>) + .__selectionMarkReads ?? {})[k] != null, + key, + ); + return page.evaluate( + k => + (window as unknown as Record>) + .__selectionMarkReads[k], + key, + ); +} + +/** The mark's colour, and how many animations it and its parts run. */ +async function readMarkNow( + page: Page, + role: 'checkbox' | 'radio', + name: string, +): Promise<{colour: string; running: number}> { + return page.getByRole(role, {name}).evaluate((input, selector) => { + const mark = input.closest('.astryx-item, li')?.querySelector(selector); + if (mark == null) { + throw new Error('no mark'); + } + return { + colour: getComputedStyle(mark).backgroundColor, + running: mark.getAnimations({subtree: true}).length, + }; + }, MARK[role]); +} + +/** + * Waits until the mark runs no animation. The two frames first let the + * last input's transition start. + */ +async function untilMarkStill( + page: Page, + role: 'checkbox' | 'radio', + name: string, +): Promise { + await frames(page, 2); + await expect + .poll(async () => (await readMarkNow(page, role, name)).running) + .toBe(0); +} + +/** The mark's colour once it is still, held for two more frames. */ +async function settledColour( + page: Page, + role: 'checkbox' | 'radio', + name: string, +): Promise { + await untilMarkStill(page, role, name); + const {colour} = await readMarkNow(page, role, name); + await frames(page, 2); + expect((await readMarkNow(page, role, name)).colour, 'two frames later').toBe( + colour, + ); + return colour; +} + +/** How many animations the list and its rows run. */ +async function listRunning(page: Page): Promise { + return page + .getByRole('group') + .first() + .evaluate(list => list.getAnimations({subtree: true}).length); +} + +/** Waits until nothing in the list runs an animation, the press release included. */ +async function untilListStill(page: Page): Promise { + await frames(page, 2); + await expect.poll(async () => listRunning(page)).toBe(0); + await frames(page, 2); +} + +/** + * Moves the animations on the option's mark to `t` ms, or finishes them. + * With 'midway' it steps through the duration and parks them where the colour + * is furthest from both ends. That point is a blend whatever the theme's + * easing. + */ +async function seekMark( + page: Page, + role: 'checkbox' | 'radio', + name: string, + t: number | 'finish' | 'midway', +): Promise { + await page.getByRole(role, {name}).evaluate( + (input, {selector, t}) => { + const mark = input.closest('.astryx-item, li')?.querySelector(selector); + const animations = mark?.getAnimations() ?? []; + if (animations.length === 0) { + throw new Error('no animation on the mark'); + } + if (t === 'midway') { + const end = Math.max( + ...animations.map(animation => + Number(animation.effect?.getComputedTiming().endTime ?? 0), + ), + ); + const colourAt = (time: number) => { + for (const animation of animations) { + animation.currentTime = time; + } + return ( + getComputedStyle(mark as Element).backgroundColor.match( + /[\d.]+/g, + ) ?? [] + ) + .slice(0, 3) + .map(Number); + }; + const start = colourAt(0); + const finish = colourAt(end); + const apart = (a: number[], b: number[]) => + Math.max(...a.map((v, i) => Math.abs(v - b[i]))); + let best = 0; + let bestApart = -1; + for (let step = 1; step < 50; step++) { + const time = (end * step) / 50; + const colour = colourAt(time); + const fromEnds = Math.min( + apart(colour, start), + apart(colour, finish), + ); + if (fromEnds > bestApart) { + best = time; + bestApart = fromEnds; + } + } + colourAt(best); + return; + } + for (const animation of animations) { + if (t === 'finish') { + animation.finish(); + } else { + animation.currentTime = t; + } + } + }, + {selector: MARK[role], t}, + ); +} + +/** Waits until no animation in the page is running: a state, not a time. */ +async function idle(page: Page): Promise { + await expect + .poll( + async () => + page.evaluate( + () => + document + .getAnimations() + .filter(animation => animation.playState === 'running').length, + ), + {timeout: 30_000}, + ) + .toBe(0); +} + +/** + * The colour at a CSS px point in the first frame a new screencast sends: the + * screen as it is now. Only a frame's arrival is waited for, never a time. + */ +async function castColour( + page: Page, + at: {x: number; y: number}, +): Promise { + await frames(page, 2); + const cast = await startScreencast(page); + await expect + .poll(() => cast.frameCount(), {timeout: 30_000}) + .toBeGreaterThan(0); + const shot = await cast.stop(); + const [first] = await decodeFrames(page, shot.slice(0, 1), at); + return first.colour; +} + +/** + * The press overlay the theme paints over a pressed control, as the page + * resolves `--color-overlay-pressed`: its colour and its opacity. + */ +async function pressOverlay(page: Page): Promise<{rgb: RGB; alpha: number}> { + const value = await page + .locator('#storybook-root > *') + .first() + .evaluate(host => { + const probe = document.createElement('div'); + probe.style.backgroundColor = 'var(--color-overlay-pressed)'; + host.append(probe); + const colour = getComputedStyle(probe).backgroundColor; + probe.remove(); + return colour; + }); + const match = /^rgba?\(([^)]+)\)$/.exec(value); + if (match == null) { + throw new Error(`the press overlay is not an rgb colour: ${value}`); + } + const [r, g, b, a = '1'] = match[1].split(/[\s,/]+/).filter(Boolean); + return {rgb: [Number(r), Number(g), Number(b)], alpha: Number(a)}; +} + +/** Within `tolerance` of a colour between `a` and `b` (a blend of the two). */ +function nearSegment(c: RGB, a: RGB, b: RGB, tolerance: number): boolean { + const ab = b.map((v, i) => v - a[i]); + const length = ab.reduce((sum, v) => sum + v * v, 0); + const along = + length === 0 + ? 0 + : Math.min( + 1, + Math.max( + 0, + c.reduce((sum, v, i) => sum + (v - a[i]) * ab[i], 0) / length, + ), + ); + return c.every((v, i) => Math.abs(v - (a[i] + along * ab[i])) <= tolerance); +} + +async function centreOf(page: Page, name: string, role: 'checkbox' | 'radio') { + const box = await page.getByRole(role, {name}).evaluate((input, selector) => { + const mark = input.closest('.astryx-item, li')?.querySelector(selector); + if (mark == null) { + throw new Error('no mark'); + } + const r = mark.getBoundingClientRect(); + return {x: r.x + r.width / 2, y: r.y + r.height / 2, w: r.width}; + }, MARK[role]); + return box; +} + +/** The colour at a CSS px point of the page as presented now. */ +async function pagePixel(page: Page, at: {x: number; y: number}): Promise { + const png = PNG.sync.read( + await page.screenshot({ + clip: {x: Math.round(at.x), y: Math.round(at.y), width: 1, height: 1}, + scale: 'css', + animations: 'allow', + }), + ); + return [png.data[0], png.data[1], png.data[2]]; +} + +interface DecodedFrame { + /** Mean colour of a 3 × 3 CSS px patch around the sample point. */ + readonly colour: RGB; + /** The frame cut down to `crop`, as a PNG frame (for a storyboard cell). */ + readonly cropped: CastFrame | null; +} + +/** + * Decodes screencast frames in a scratch page: Chromium sends PNG, WebKit + * JPEG. It returns the colour at a CSS px point of each frame, and with + * `crop`, the frame cut down to that box. + */ +async function decodeFrames( + page: Page, + shot: ReadonlyArray, + at: {x: number; y: number}, + crop?: {x: number; y: number; width: number; height: number}, +): Promise { + const scratch = await page.context().newPage(); + try { + const decoded = await scratch.evaluate( + async ({cast, point, box}) => { + const out: {colour: number[]; png: string | null}[] = []; + for (const frame of cast) { + const bitmap = await createImageBitmap( + await ( + await fetch(`data:image/${frame.format};base64,${frame.data}`) + ).blob(), + ); + const scale = bitmap.width / frame.viewportWidth; + const canvas = document.createElement('canvas'); + canvas.width = bitmap.width; + canvas.height = bitmap.height; + const context = canvas.getContext('2d'); + if (context == null) { + throw new Error('no 2d context'); + } + context.drawImage(bitmap, 0, 0); + const patch = context.getImageData( + Math.round((point.x - 1) * scale), + Math.round((point.y - 1) * scale), + Math.max(1, Math.round(3 * scale)), + Math.max(1, Math.round(3 * scale)), + ).data; + const sum = [0, 0, 0]; + for (let i = 0; i < patch.length; i += 4) { + sum[0] += patch[i]; + sum[1] += patch[i + 1]; + sum[2] += patch[i + 2]; + } + const count = patch.length / 4; + let png: string | null = null; + if (box != null) { + const cut = document.createElement('canvas'); + cut.width = Math.round(box.width * scale); + cut.height = Math.round(box.height * scale); + cut + .getContext('2d') + ?.drawImage( + canvas, + Math.round(box.x * scale), + Math.round(box.y * scale), + cut.width, + cut.height, + 0, + 0, + cut.width, + cut.height, + ); + const url = cut.toDataURL('image/png'); + png = url.slice(url.indexOf(',') + 1); + } + out.push({colour: sum.map(v => Math.round(v / count)), png}); + } + return out; + }, + {cast: shot, point: at, box: crop ?? null}, + ); + return decoded.map(({colour, png}, i) => ({ + colour: colour as RGB, + cropped: + png == null ? null : {...shot[i], format: 'png' as const, data: png}, + })); + } finally { + await scratch.close(); + } +} + +/** + * Within `tolerance` levels per channel. The press overlay over the box + * fades out after the lift, and darkens a mark by a few levels on the way. + * That is the press, not the mark changing. WebKit's frames are JPEG, which + * moves a flat colour by a few levels more. + */ +const near = (a: RGB, b: RGB, tolerance: number) => + a.every((v, i) => Math.abs(v - b[i]) <= tolerance); +const same = (a: RGB, b: RGB) => near(a, b, 2); +/** Further than this from both ends is a blend between the two states. */ +const PRESS_TOLERANCE = 20; + +interface BusyProbe { + /** The colour at the rest state's sample point before the tap. */ + readonly restColour: RGB; + /** The colour there once the block is over and the page has settled. */ + readonly settledColour: RGB; + /** Each frame on screen during the block once the change showed, oldest first. */ + readonly colours: RGB[]; + readonly trace: Record; +} + +/** + * One busy-window probe: a tap checks "Push notification". Once the page has + * committed the change, the main thread blocks for 500 ms. + * + * It returns what the screen showed during the block, from the change's + * presentation on. That is the last frame before the block if it shows the + * change, plus every frame inside the block from the change on. Chromium's + * screencast sends nothing for an unchanged screen, so the block can hold no + * frame. The last frame before it stays on screen; earlier frames were never + * on screen during it. The capture starts before the tap, so it holds the + * frame that presents the change. + * + * Both compositors can present a change committed before the block a few + * milliseconds into it. That is presentation latency, not the blocked thread. + * A change committed before the block and first presented after it fails, + * with its frames. + */ +async function probeBusyAfterChange(page: Page): Promise { + await openStory(page, storybook(), 'core-checkboxlist--default'); + const driver = await touchDriver(page); + const at = await centreOf(page, 'Push notification', 'checkbox'); + const sample = {x: at.x - at.w / 2 + 3, y: at.y}; + const restColour = await pagePixel(page, sample); + const cast = await startScreencast(page); + await driver.tap(at); + await expect( + page.getByRole('checkbox', {name: 'Push notification'}), + ).toBeChecked(); + // The change committed: the second frame's callbacks run only after the + // first frame, which renders the change, has been committed. Now the app + // does 500 ms of work. + await frames(page, 2); + const busy = await blockMainThread(page, 500); + await frames(page, 2); + const shot = await cast.stop(); + // The mark once the block is over: the checked colour, whole. + const settledColour = await pagePixel(page, sample); + const decoded = await decodeFrames(page, shot, sample); + const read = shot.map((frame, i) => ({ + t: frame.t, + colour: decoded[i].colour, + })); + const change = read.find( + frame => !near(frame.colour, restColour, PRESS_TOLERANCE), + ); + if (change == null || change.t > busy.to) { + throw new Error( + 'the change, committed before the block, showed only after it: ' + + JSON.stringify({busy, frames: read}), + ); + } + const before = read + .filter(frame => frame.t >= change.t && frame.t < busy.from) + .at(-1); + const inside = read.filter( + frame => frame.t >= busy.from && frame.t <= busy.to && frame.t >= change.t, + ); + const onScreen = before == null ? inside : [before, ...inside]; + return { + restColour, + settledColour, + colours: onScreen.map(frame => frame.colour), + trace: { + busy, + frames: shot.length, + changePresented: change.t, + inBlock: inside.length, + settledColour, + judged: onScreen.map(frame => ({t: frame.t, colour: frame.colour})), + }, + }; +} + +test.describe('selection marks under a finger', () => { + // One touch model on every touch device: a coarse primary pointer. The + // touch page here is the engine's own touch emulation; real iOS Safari and + // Android Chrome are the simulator and emulator recordings. + + test('a tap changes a checkbox mark in the frame the selection lands', async ({ + page, + }) => { + await openStory(page, storybook(), 'core-checkboxlist--default'); + const driver = await touchDriver(page); + await watchMark(page, 'checkbox', 'SMS'); + const at = await centreOf(page, 'SMS', 'checkbox'); + await driver.tap(at); + const read = await readMark(page, 'checkbox', 'SMS'); + await expect(page.getByRole('checkbox', {name: 'SMS'})).toBeChecked(); + // No transition was started, and the first colour the page computed is + // the one the mark keeps. + expect(read.animations).toEqual([]); + expect(read.first).toBe(await settledColour(page, 'checkbox', 'SMS')); + }); + + test('a tap moves a radio choice in one frame, on both circles', async ({ + page, + }) => { + await openStory(page, storybook(), 'core-radiolist--default'); + const driver = await touchDriver(page); + await driver.tap(await centreOf(page, 'Email', 'radio')); + await expect(page.getByRole('radio', {name: 'Email'})).toBeChecked(); + await frames(page, 2); + await watchMark(page, 'radio', 'Email'); + await watchMark(page, 'radio', 'SMS'); + await driver.tap(await centreOf(page, 'SMS', 'radio')); + const selected = await readMark(page, 'radio', 'SMS'); + const deselected = await readMark(page, 'radio', 'Email'); + await expect(page.getByRole('radio', {name: 'SMS'})).toBeChecked(); + expect(selected.animations).toEqual([]); + expect(deselected.animations).toEqual([]); + expect(selected.first).toBe(await settledColour(page, 'radio', 'SMS')); + expect(deselected.first).toBe(await settledColour(page, 'radio', 'Email')); + }); + + test('Reduce Motion keeps the one-frame change', async ({page}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + await openStory(page, storybook(), 'core-checkboxlist--default'); + const driver = await touchDriver(page); + await watchMark(page, 'checkbox', 'Email'); + await driver.tap(await centreOf(page, 'Email', 'checkbox')); + const read = await readMark(page, 'checkbox', 'Email'); + expect(read.animations).toEqual([]); + expect(read.first).toBe(await settledColour(page, 'checkbox', 'Email')); + }); + + test('a mouse keeps the theme’s transition (negative control)', async ({ + browser, + }) => { + const context = await browser.newContext({ + viewport: {width: 1024, height: 768}, + hasTouch: false, + isMobile: false, + }); + const page = await context.newPage(); + try { + await openStory(page, storybook(), 'core-checkboxlist--default'); + // A fine-pointer case proves nothing under a coarse primary pointer. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + // The fade is frozen where it begins, in the task that starts it. The + // frames below then read it at set points, however busy the page is: a + // busy main thread can present none of a fade. + await watchMark(page, 'checkbox', 'SMS', {hold: true}); + const at = await centreOf(page, 'SMS', 'checkbox'); + const sample = {x: at.x - at.w / 2 + 3, y: at.y}; + // Hover first, so the colours below differ by the click alone. + await page.mouse.move(at.x, at.y); + await idle(page); + const before = await castColour(page, sample); + await page.mouse.click(at.x, at.y); + const read = await readMark(page, 'checkbox', 'SMS'); + const themeMs = await page.evaluate(() => { + const value = getComputedStyle(document.documentElement) + .getPropertyValue('--duration-fast') + .trim(); + return value.endsWith('ms') + ? parseFloat(value) + : parseFloat(value) * 1000; + }); + expect(themeMs).toBeGreaterThan(0); + expect(read.animations).toContainEqual({ + property: 'background-color', + duration: themeMs, + }); + // The fade midway (where its colour is furthest from both ends), then + // finished. Screencast frames show each once the hover and the press are + // at rest. + await seekMark(page, 'checkbox', 'SMS', 'midway'); + await idle(page); + const midway = await castColour(page, sample); + await seekMark(page, 'checkbox', 'SMS', 'finish'); + await idle(page); + const after = await castColour(page, sample); + expect(read.first).not.toBe(await settledColour(page, 'checkbox', 'SMS')); + // The instrument sees a blend when the screen shows one. + const summary = JSON.stringify({before, midway, after}); + expect(near(before, after, PRESS_TOLERANCE), summary).toBe(false); + expect(near(midway, before, PRESS_TOLERANCE), summary).toBe(false); + expect(near(midway, after, PRESS_TOLERANCE), summary).toBe(false); + } finally { + await context.close(); + } + }); + + test('the frames of a tap show no colour between the two states @storyboard', async ({ + page, + }, testInfo) => { + await openStory(page, storybook(), 'core-checkboxlist--default'); + const driver = await touchDriver(page); + const at = await centreOf(page, 'SMS', 'checkbox'); + // Sample inside the box, clear of the check glyph. + const sample = {x: at.x - at.w / 2 + 3, y: at.y}; + const list = await page.getByRole('group').first().boundingBox(); + if (list == null) { + throw new Error('no list'); + } + const cast = await startScreencast(page); + await frames(page, 4); + const tapAt = Date.now(); + await driver.tap(at); + await expect(page.getByRole('checkbox', {name: 'SMS'})).toBeChecked(); + // The capture ends once the press overlay's release has finished. + await untilListStill(page); + const shot = await cast.stop(); + // Two frames at least, or the capture shows nothing between. Capped at + // 3 CPUs with 16 workers, WebKit's screencast can hold a single frame for + // the whole capture, which this reports: the engine's limit there. + expect(shot.length).toBeGreaterThan(1); + const clip = { + x: Math.max(0, Math.floor(list.x) - 8), + y: Math.max(0, Math.floor(list.y) - 8), + width: Math.ceil(list.width) + 16, + height: Math.ceil(list.height) + 16, + }; + const decoded = await decodeFrames(page, shot, sample, clip); + const colours = decoded.map(frame => frame.colour); + const before = colours[0]; + const after = colours[colours.length - 1]; + // The box shows two states, unchecked and checked, each at rest or under + // the press overlay. A finger paints the overlay at touch-down, before the + // lift changes the mark, and it fades after. Until the mark first shows + // checked, a frame is the unchecked box; from then on, the checked one. + // Any other colour is a blend of the two marks. + const overlay = await pressOverlay(page); + const pressed = (c: RGB): RGB => [ + c[0] * (1 - overlay.alpha) + overlay.rgb[0] * overlay.alpha, + c[1] * (1 - overlay.alpha) + overlay.rgb[1] * overlay.alpha, + c[2] * (1 - overlay.alpha) + overlay.rgb[2] * overlay.alpha, + ]; + const unchecked = (c: RGB) => + nearSegment(c, before, pressed(before), PRESS_TOLERANCE); + const checked = (c: RGB) => + nearSegment(c, after, pressed(after), PRESS_TOLERANCE); + const changed = colours.findIndex(checked); + const between = colours.filter((c, i) => + i < changed ? !unchecked(c) : !checked(c), + ); + // The evidence is written first, so a failing run shows its blend. + const storyboard = await castStoryboard( + page, + decoded.map((frame, i) => frame.cropped ?? shot[i]), + { + name: 'checkbox-mark-tap', + zero: tapAt, + cellScale: 1, + columns: 4, + data: t => { + const i = shot.findIndex(f => f.t === t); + return {box: i < 0 ? '' : `rgb(${colours[i].join(',')})`}; + }, + }, + ); + await storyboard.write(testInfo, { + claim: + 'under a finger the mark changes in one frame (motion/uikit/selection.ts)', + sample, + before, + after, + blendFrames: between.length, + }); + expect(same(before, after)).toBe(false); + // Every presented frame shows one state or the other, at rest or pressed, + // never a blend. + expect(between).toEqual([]); + }); + + test('a main thread blocked right after the change shows the whole mark', async ({ + page, + }, testInfo) => { + const probe = await probeBusyAfterChange(page); + const {colours, restColour, settledColour} = probe; + expect(near(settledColour, restColour, PRESS_TOLERANCE)).toBe(false); + // Whatever the screen showed during the block, once the change showed, + // is the checked mark, whole: the settled colour, never a frozen blend. + for (const colour of colours) { + expect(near(colour, restColour, PRESS_TOLERANCE)).toBe(false); + expect(near(colour, colours[0], 8)).toBe(true); + expect(near(colour, settledColour, 8)).toBe(true); + } + await writeEvidence( + 'selection-marks/busy-after-change', + {'trace.json': JSON.stringify(probe.trace, null, 2)}, + testInfo, + ); + }); +}); + +test.describe('selection marks with a mouse under Reduce Motion', () => { + test('the change is immediate (design:reduced-motion DR3)', async ({ + browser, + }) => { + const context = await browser.newContext({ + viewport: {width: 1024, height: 768}, + hasTouch: false, + isMobile: false, + reducedMotion: 'reduce', + }); + const page = await context.newPage(); + try { + await openStory(page, storybook(), 'core-checkboxlist--default'); + // A fine-pointer case proves nothing under a coarse primary pointer. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await watchMark(page, 'checkbox', 'SMS'); + const at = await centreOf(page, 'SMS', 'checkbox'); + await page.mouse.move(at.x, at.y); + await untilMarkStill(page, 'checkbox', 'SMS'); + await page.mouse.click(at.x, at.y); + const read = await readMark(page, 'checkbox', 'SMS'); + await expect(page.getByRole('checkbox', {name: 'SMS'})).toBeChecked(); + expect(read.animations).toEqual([]); + expect(read.first).toBe(await settledColour(page, 'checkbox', 'SMS')); + } finally { + await context.close(); + } + }); +}); diff --git a/packages/core/src/Indicator/selectionMotion.stylex.ts b/packages/core/src/Indicator/selectionMotion.stylex.ts new file mode 100644 index 0000000000000..9564fba7e2df6 --- /dev/null +++ b/packages/core/src/Indicator/selectionMotion.stylex.ts @@ -0,0 +1,24 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file selectionMotion.stylex.ts + * @input Uses StyleX + * @output Exports `selectionMotionConsts`: the build-time mirror of + * `selection.mark` in motion/uikit/selection.ts + * @position Internal styling constants; CheckboxIndicator and RadioIndicator + * read them for their touch presentation + * + * StyleX evaluates a style at build time and cannot read the constants + * table, so this mirrors its value. selectionMotion.test.ts fails if they + * drift. + * + * SYNC: When modified, update /packages/core/src/motion/uikit/selection.ts + * and selectionMotion.test.ts. + */ + +import * as stylex from '@stylexjs/stylex'; + +export const selectionMotionConsts = stylex.defineConsts({ + /** `selection.mark.changeMs`, in ms. */ + markChangeMs: 0, +}); diff --git a/packages/core/src/Indicator/selectionMotion.test.ts b/packages/core/src/Indicator/selectionMotion.test.ts new file mode 100644 index 0000000000000..a5848b1184bd8 --- /dev/null +++ b/packages/core/src/Indicator/selectionMotion.test.ts @@ -0,0 +1,136 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file selectionMotion.test.ts + * @input vitest, the UIKit constants table (motion/uikit/selection.ts), the + * build-time mirror and the checkbox and radio indicators + * @output Holds the mirror to the table, and asserts what each mark ships. + * Under a finger (a coarse primary pointer) its colour change takes the + * table's one frame. With a mouse it keeps the theme's duration token, and + * under Reduce Motion it is immediate. + * @position Unit test beside Indicator/selectionMotion.stylex.ts; the + * real-engine proof (a tap's first frame, storyboard, busy main thread) is + * Indicator/__tests__/SelectionMarks.interaction.browser.spec.ts + */ + +import {createElement} from 'react'; +import {render} from '@testing-library/react'; +import {describe, expect, it} from 'vitest'; +import {selection} from '../motion/uikit/selection'; +import {CheckboxIndicator} from './CheckboxIndicator'; +import {RadioIndicator} from './RadioIndicator'; +import {selectionMotionConsts} from './selectionMotion.stylex'; + +interface Declared { + /** The enclosing at-rule conditions, outermost first, joined by " | ". */ + media: string | null; + text: string; +} + +/** + * Every injected rule that names one of the element's classes, with the + * media and supports conditions it sits in (null at the top level). + */ +function declaredFor(el: Element): Declared[] { + const classes = el.className + .split(/\s+/) + .filter(Boolean) + .map(name => `.${name}`); + const out: Declared[] = []; + const walk = (list: CSSRuleList, conditions: string[]) => { + for (const rule of Array.from(list)) { + if (rule instanceof CSSMediaRule) { + walk(rule.cssRules, [...conditions, rule.media.mediaText]); + } else if (rule instanceof CSSSupportsRule) { + walk(rule.cssRules, [...conditions, rule.conditionText]); + } else if (rule instanceof CSSStyleRule) { + if (classes.some(cls => rule.selectorText.startsWith(cls))) { + out.push({ + media: conditions.length === 0 ? null : conditions.join(' | '), + text: rule.style.cssText, + }); + } + } + } + }; + for (const sheet of Array.from(document.styleSheets)) { + walk(sheet.cssRules, []); + } + return out; +} + +/** The `transition-duration` each media condition declares on `el`. */ +function durationsOf(el: Element): Map { + const durations = new Map(); + for (const {media, text} of declaredFor(el)) { + const match = /transition-duration:\s*([^;]+)/.exec(text); + if (match) { + durations.set(media, match[1].trim()); + } + } + return durations; +} + +describe('selection mark clock', () => { + it('is the constants table’s mark change, mirrored for the stylesheet', () => { + expect(selectionMotionConsts.markChangeMs).toBe(selection.mark.changeMs); + }); + + it('is one frame: UIKit never animates a selection mark', () => { + expect(selection.mark.changeMs).toBe(0); + }); +}); + +type MarkState = 'checked' | 'unchecked'; + +/** The instant key of the Reduce Motion policy (motion/reducedMotion.ts). */ +const REDUCED_MOTION_INSTANT = + '(prefers-reduced-motion: reduce) and (not (pointer: coarse))'; + +describe.each<[string, (state: MarkState) => ReturnType]>( + [ + [ + 'CheckboxIndicator', + state => createElement(CheckboxIndicator, {state, size: 'md'}), + ], + [ + 'RadioIndicator', + state => createElement(RadioIndicator, {state, size: 'md'}), + ], + ], +)('%s', (_name, element) => { + function mark(state: MarkState): Element { + const {container} = render(element(state)); + const root = container.firstElementChild; + if (root == null) { + throw new Error('the indicator rendered nothing'); + } + return root; + } + + it('changes its colour in one frame under a finger, on every touch device', () => { + const durations = [...durationsOf(mark('checked'))]; + // TOUCH_QUERY with no platform gate. StyleX keeps the earlier media key + // exclusive of the later reduced-motion one, which still leaves every + // coarse pointer. + const touch = durations.filter( + ([media]) => + media != null && + media !== REDUCED_MOTION_INSTANT && + media.includes('(pointer: coarse)'), + ); + expect(touch.map(([, value]) => value)).toEqual([ + `${selection.mark.changeMs}ms`, + ]); + expect( + durations.filter(([media]) => media?.includes('-webkit-touch-callout')), + ).toEqual([]); + }); + + it('keeps the theme’s duration token with a mouse, and changes at once with a mouse under Reduce Motion', () => { + const durations = durationsOf(mark('unchecked')); + expect(durations.get(null)).toMatch(/^var\(--duration-fast/); + // design:reduced-motion DR3, in the reduced-motion policy's instant key. + expect(durations.get(REDUCED_MOTION_INSTANT)).toBe('0s'); + }); +}); diff --git a/packages/core/src/SelectableCard/SelectableCard.doc.mjs b/packages/core/src/SelectableCard/SelectableCard.doc.mjs index 45ce06ae6dfac..846e88504f733 100644 --- a/packages/core/src/SelectableCard/SelectableCard.doc.mjs +++ b/packages/core/src/SelectableCard/SelectableCard.doc.mjs @@ -23,7 +23,7 @@ export const docs = { }, props: [ {name: 'label', type: 'string', description: 'Accessibility label.', required: true}, - {name: 'isSelected', type: 'boolean', description: 'Controlled selection state.', required: true}, + {name: 'isSelected', type: 'boolean', description: 'Controlled selection state. Under a finger (a coarse primary pointer) the selection ring and border change in one frame. With a mouse the ring changes at once and the border fades over the theme’s fast duration; under Reduce Motion both change at once.', required: true}, {name: 'onChange', type: '(isSelected: boolean) => void', description: 'Called when toggled.', required: true}, {name: 'isDisabled', type: 'boolean', description: 'Disables the card.', default: 'false'}, {name: 'children', type: 'ReactNode', description: 'Card content.'}, diff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsx index 4b68921405df2..3ace56b235c81 100644 --- a/packages/core/src/SelectableCard/SelectableCard.tsx +++ b/packages/core/src/SelectableCard/SelectableCard.tsx @@ -4,7 +4,8 @@ /** * @file SelectableCard.tsx - * @input Uses Card, useClickableContainer, StyleX + * @input Uses Card, useClickableContainer, StyleX, the selection mark's + * touch timing (Indicator/selectionMotion.stylex.ts) * @output Exports SelectableCard component and SelectableCardProps * @position Interactive card for toggle selection * @@ -43,6 +44,7 @@ import type {Elevation, SizeValue, SpacingStep} from '../utils/types'; import {mergeProps} from '../utils'; import {Card} from '../Card/Card'; import type {CardVariant} from '../Card/Card'; +import {selectionMotionConsts} from '../Indicator/selectionMotion.stylex'; import {useClickableContainer} from '../hooks/useClickableContainer'; import {closestLayerRoot} from '../privateAttributes/layerRoot.stylex'; import type {BaseProps} from '../BaseProps'; @@ -66,6 +68,9 @@ const PRESSED_ON = '[data-astryx-press="on"]'; /** Written by the press controller for the press's release. */ const PRESSED_FADING = '[data-astryx-press="fading"]'; +/** How long the selection mark takes to change under a finger: one frame. */ +const MARK_CHANGE = `${selectionMotionConsts.markChangeMs}ms`; + const styles = stylex.create({ interactive: { // Declared here, on the element that carries the `astryx-selectable-card` @@ -78,7 +83,19 @@ const styles = stylex.create({ ':is(:disabled,[aria-disabled="true"])': 'default', }, transitionProperty: 'box-shadow, border-color', - transitionDuration: durationVars['--duration-fast'], + transitionDuration: { + default: durationVars['--duration-fast'], + // Under a finger the ring and the border change in the frame the + // selection lands, as UIKit's marks do (motion/uikit/selection.ts). The + // ring cannot interpolate with the card's resting shadow, so a fade would + // split it from the border. Under Reduce Motion a mouse's change is + // immediate too. + // The keys are spelled out: an imported at-rule key lands in another + // StyleX priority layer than a literal one. + '@media (pointer: coarse)': MARK_CHANGE, + '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))': + '0s', + }, transitionTimingFunction: easeVars['--ease-standard'], }, // Hover and pressed overlay. Hover is guarded by @media (hover: hover) so diff --git a/packages/core/src/SelectableCard/SelectableCardMark.test.tsx b/packages/core/src/SelectableCard/SelectableCardMark.test.tsx new file mode 100644 index 0000000000000..59aa7d339feee --- /dev/null +++ b/packages/core/src/SelectableCard/SelectableCardMark.test.tsx @@ -0,0 +1,92 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file SelectableCardMark.test.tsx + * @input vitest, Testing Library, SelectableCard and the UIKit constants + * table (motion/uikit/selection.ts) + * @output Asserts the card's selection mark, its inset ring and its border. + * Under a finger (a coarse primary pointer) it changes on the table's one + * frame. With a mouse it keeps the theme's duration token, and under Reduce + * Motion it is immediate. + * @position Unit test of SelectableCard's touch mark timing; the real-engine + * proof is __tests__/SelectableCardMark.interaction.browser.spec.ts + */ + +import {describe, expect, it} from 'vitest'; +import {render} from '@testing-library/react'; +import {selection} from '../motion/uikit/selection'; +import {SelectableCard} from './SelectableCard'; + +/** + * The `transition-duration` each condition declares on `el`, keyed by its + * enclosing media and supports conditions (outermost first, " | "-joined). + */ +function durationsOf(el: Element): Map { + const classes = el.className + .split(/\s+/) + .filter(Boolean) + .map(name => `.${name}`); + const durations = new Map(); + const walk = (rules: CSSRuleList, conditions: string[]) => { + for (const rule of Array.from(rules)) { + if (rule instanceof CSSMediaRule) { + walk(rule.cssRules, [...conditions, rule.media.mediaText]); + } else if (rule instanceof CSSSupportsRule) { + walk(rule.cssRules, [...conditions, rule.conditionText]); + } else if ( + rule instanceof CSSStyleRule && + // The card itself, not its press layer (`::after`). + !rule.selectorText.includes('::') && + classes.some(cls => rule.selectorText.startsWith(cls)) + ) { + const match = /transition-duration:\s*([^;]+)/.exec(rule.style.cssText); + if (match) { + durations.set( + conditions.length === 0 ? null : conditions.join(' | '), + match[1].trim(), + ); + } + } + } + }; + for (const sheet of Array.from(document.styleSheets)) { + walk(sheet.cssRules, []); + } + return durations; +} + +/** The instant key of the Reduce Motion policy (motion/reducedMotion.ts). */ +const REDUCED_MOTION_INSTANT = + '(prefers-reduced-motion: reduce) and (not (pointer: coarse))'; + +describe('SelectableCard selection mark', () => { + it('changes its ring and border in one frame under a finger, keeps the theme’s duration with a mouse, and changes at once with a mouse under Reduce Motion', () => { + const {container} = render( + {}}> + Pro + , + ); + const card = container.querySelector('.astryx-selectable-card'); + if (card == null) { + throw new Error('the card rendered no root'); + } + const durations = [...durationsOf(card)]; + // TOUCH_QUERY with no platform gate (StyleX keeps it exclusive of the + // later reduced-motion key, which still leaves every coarse pointer). + const touch = durations.filter( + ([media]) => + media != null && + media !== REDUCED_MOTION_INSTANT && + media.includes('(pointer: coarse)'), + ); + expect(touch.map(([, value]) => value)).toEqual([ + `${selection.mark.changeMs}ms`, + ]); + expect( + durations.filter(([media]) => media?.includes('-webkit-touch-callout')), + ).toEqual([]); + expect(new Map(durations).get(null)).toMatch(/^var\(--duration-fast/); + // design:reduced-motion DR3, in the instant key the policy spells. + expect(new Map(durations).get(REDUCED_MOTION_INSTANT)).toBe('0s'); + }); +}); diff --git a/packages/core/src/SelectableCard/__tests__/SelectableCardMark.interaction.browser.spec.ts b/packages/core/src/SelectableCard/__tests__/SelectableCardMark.interaction.browser.spec.ts new file mode 100644 index 0000000000000..7fd3712340f50 --- /dev/null +++ b/packages/core/src/SelectableCard/__tests__/SelectableCardMark.interaction.browser.spec.ts @@ -0,0 +1,350 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file SelectableCardMark.interaction.browser.spec.ts + * @input The built SelectableCard Single Select story, real touch input + * (Chromium CDP / WebKit's tap) and the interaction harness + * @output Proofs that under a finger a card's ring and border change in the + * frame the selection lands. This holds on the card that gains the + * selection and on the one that loses it. No transition is created. Every + * animation frame of a tap shows each card wholly selected or wholly not + * (storyboard). A mouse keeps the theme's transition (the negative + * control). + * @position Real-engine layer of SelectableCard's touch mark timing; the + * stylesheet layer is SelectableCard/SelectableCardMark.test.tsx + */ + +import {expect, test, type Page} from '@playwright/test'; +import { + castStoryboard, + frames, + openStory, + startScreencast, + touchDriver, + withStorybook, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +const STORY = 'core-selectablecard--single-select'; + +/** A card's mark: its border colour and its shadow (which carries the ring). */ +interface Mark { + border: string; + shadow: string; +} + +/** What the page saw in the microtask after the card's class changed. */ +interface CardRead extends Mark { + /** Transitions on the card right after that computation. */ + transitions: {property: string; duration: number}[]; +} + +/** + * Watches the card labelled `name`. When React writes its new state, the + * observer runs as a microtask, before any frame. It computes the card's + * style once and records the mark and any transition it started. + */ +async function watchCard(page: Page, name: string): Promise { + await page.getByRole('checkbox', {name}).evaluate((input, key) => { + const card = input.closest('.astryx-selectable-card'); + if (card == null) { + throw new Error(`no card for ${key}`); + } + const reads = ((window as unknown as Record).__c06cards ??= + {}) as Record; + const observer = new MutationObserver(() => { + if (reads[key] != null) { + return; + } + const style = getComputedStyle(card); + reads[key] = { + border: style.borderTopColor, + shadow: style.boxShadow, + transitions: card + .getAnimations() + .filter(animation => 'transitionProperty' in animation) + .map(animation => ({ + property: (animation as CSSTransition).transitionProperty, + duration: Number(animation.effect?.getTiming().duration ?? 0), + })), + }; + observer.disconnect(); + }); + observer.observe(card, {attributes: true, attributeFilter: ['class']}); + }, name); +} + +async function readCard(page: Page, name: string): Promise { + await page.waitForFunction( + key => + ((window as unknown as Record>) + .__c06cards ?? {})[key] != null, + name, + ); + return page.evaluate( + key => + (window as unknown as Record>) + .__c06cards[key], + name, + ); +} + +/** The card's mark, and how many animations it and its layers run. */ +async function readCardNow( + page: Page, + name: string, +): Promise<{mark: Mark; running: number}> { + return page.getByRole('checkbox', {name}).evaluate(input => { + const card = input.closest('.astryx-selectable-card'); + if (card == null) { + throw new Error('no card'); + } + const style = getComputedStyle(card); + return { + mark: {border: style.borderTopColor, shadow: style.boxShadow}, + running: card.getAnimations({subtree: true}).length, + }; + }); +} + +/** + * Waits until the card runs no animation. The two frames first let the + * last input's transition start. + */ +async function untilCardStill(page: Page, name: string): Promise { + await frames(page, 2); + await expect + .poll(async () => (await readCardNow(page, name)).running) + .toBe(0); +} + +/** The card's mark once it is still, held for two more frames. */ +async function settledMark(page: Page, name: string): Promise { + await untilCardStill(page, name); + const {mark} = await readCardNow(page, name); + await frames(page, 2); + expect((await readCardNow(page, name)).mark, 'two frames later').toEqual( + mark, + ); + return mark; +} + +/** + * Samples both cards' marks on every animation frame for `ms`, stamped with + * the epoch time the screencast uses. + */ +async function traceMarks( + page: Page, + names: ReadonlyArray, + ms: number, +): Promise<{t: number; marks: Record}[]> { + return page.evaluate( + async ({names, ms}) => + new Promise(resolve => { + const cards = names.map(name => { + const input = [ + ...document.querySelectorAll( + 'input[type=checkbox]', + ), + ].find(el => el.getAttribute('aria-label') === name); + const card = input?.closest('.astryx-selectable-card'); + if (card == null) { + throw new Error(`no card for ${name}`); + } + return [name, card] as const; + }); + const samples: {t: number; marks: Record}[] = []; + const end = performance.now() + ms; + const tick = () => { + const marks: Record = {}; + for (const [name, card] of cards) { + const style = getComputedStyle(card); + marks[name] = { + border: style.borderTopColor, + shadow: style.boxShadow, + }; + } + samples.push({t: Date.now(), marks}); + if (performance.now() < end) { + requestAnimationFrame(tick); + } else { + resolve(samples); + } + }; + requestAnimationFrame(tick); + }), + {names, ms}, + ); +} + +async function centreOf(page: Page, name: string) { + const box = await page.getByRole('checkbox', {name}).evaluate(input => { + const card = input.closest('.astryx-selectable-card'); + if (card == null) { + throw new Error('no card'); + } + const r = card.getBoundingClientRect(); + return {x: r.x + r.width / 2, y: r.y + r.height / 2}; + }); + return {x: Math.round(box.x), y: Math.round(box.y)}; +} + +test.describe('SelectableCard selection mark under a finger', () => { + // One touch model on every touch device: a coarse primary pointer. The + // touch page here is the engine's own touch emulation; real iOS Safari and + // Android Chrome are the simulator and emulator recordings. + + test('a tap changes the ring and the border in the frame the selection lands, on both cards', async ({ + page, + }) => { + await openStory(page, storybook(), STORY); + await watchCard(page, 'Pro'); + await watchCard(page, 'Basic'); + const driver = await touchDriver(page); + await driver.tap(await centreOf(page, 'Pro')); + for (const name of ['Pro', 'Basic']) { + const read = await readCard(page, name); + expect(read.transitions, name).toEqual([]); + const settled = await settledMark(page, name); + expect(read.border, name).toBe(settled.border); + expect(read.shadow, name).toBe(settled.shadow); + } + await expect(page.getByRole('checkbox', {name: 'Pro'})).toBeChecked(); + }); + + test('every frame of a tap shows each card wholly selected or wholly not @storyboard', async ({ + page, + }, testInfo) => { + await openStory(page, storybook(), STORY); + const driver = await touchDriver(page); + const at = await centreOf(page, 'Pro'); + const before = (await traceMarks(page, ['Pro', 'Basic'], 50)).at(-1); + if (before == null) { + throw new Error('no resting sample'); + } + const cast = await startScreencast(page); + await frames(page, 4); + const tapAt = Date.now(); + const [trace] = await Promise.all([ + traceMarks(page, ['Pro', 'Basic'], 500), + driver.tap(at), + ]); + const shot = await cast.stop(); + const after = trace.at(-1); + if (after == null) { + throw new Error('no samples'); + } + const nearest = (t: number) => + trace.reduce((best, sample) => + Math.abs(sample.t - t) < Math.abs(best.t - t) ? sample : best, + ); + // The evidence is written first, so a failing run shows its blend. + const storyboard = await castStoryboard(page, shot, { + name: 'selectable-card-mark-tap', + zero: tapAt, + cellScale: 0.5, + columns: 4, + data: t => ({ + pro: nearest(t).marks.Pro.border, + basic: nearest(t).marks.Basic.border, + }), + }); + await storyboard.write(testInfo, { + claim: + 'under a finger a card’s ring and border change in one frame (motion/uikit/selection.ts)', + before: before.marks, + after: after.marks, + }); + expect(after.marks.Pro.border).not.toBe(before.marks.Pro.border); + for (const name of ['Pro', 'Basic']) { + for (const sample of trace) { + const mark = sample.marks[name]; + const whole = + (mark.border === before.marks[name].border && + mark.shadow === before.marks[name].shadow) || + (mark.border === after.marks[name].border && + mark.shadow === after.marks[name].shadow); + expect(whole, `${name} at ${sample.t - tapAt} ms`).toBe(true); + } + } + }); + + test('a mouse keeps the theme’s transition (negative control)', async ({ + browser, + }) => { + const context = await browser.newContext({ + viewport: {width: 1024, height: 768}, + hasTouch: false, + isMobile: false, + }); + const page = await context.newPage(); + try { + await openStory(page, storybook(), STORY); + // A fine-pointer case proves nothing under a coarse primary pointer. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await watchCard(page, 'Pro'); + const at = await centreOf(page, 'Pro'); + await page.mouse.move(at.x, at.y); + await untilCardStill(page, 'Pro'); + await page.mouse.click(at.x, at.y); + const read = await readCard(page, 'Pro'); + expect( + read.transitions.some( + ({property, duration}) => property === 'border-color' && duration > 0, + ) || + read.transitions.some( + ({property, duration}) => + property.startsWith('border-') && duration > 0, + ), + ).toBe(true); + expect(read.border).not.toBe((await settledMark(page, 'Pro')).border); + } finally { + await context.close(); + } + }); +}); + +// design:reduced-motion: under Reduce Motion the mark changes at once with a +// mouse (DR3); under a finger it already changes in one frame, within DR2. +test.describe('SelectableCard selection mark under Reduce Motion', () => { + test('a finger gets an instant change', async ({page}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + await openStory(page, storybook(), STORY); + await watchCard(page, 'Pro'); + const driver = await touchDriver(page); + await driver.tap(await centreOf(page, 'Pro')); + const read = await readCard(page, 'Pro'); + expect(read.transitions.filter(({duration}) => duration > 0)).toEqual([]); + expect(read.border).toBe((await settledMark(page, 'Pro')).border); + }); + + test('a mouse gets an instant change', async ({browser}) => { + const context = await browser.newContext({ + viewport: {width: 1024, height: 768}, + hasTouch: false, + isMobile: false, + reducedMotion: 'reduce', + }); + const page = await context.newPage(); + try { + await openStory(page, storybook(), STORY); + // A fine-pointer case proves nothing under a coarse primary pointer. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await watchCard(page, 'Pro'); + const at = await centreOf(page, 'Pro'); + await page.mouse.move(at.x, at.y); + await untilCardStill(page, 'Pro'); + await page.mouse.click(at.x, at.y); + const read = await readCard(page, 'Pro'); + expect(read.transitions.filter(({duration}) => duration > 0)).toEqual([]); + expect(read.border).toBe((await settledMark(page, 'Pro')).border); + } finally { + await context.close(); + } + }); +}); diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index 2f255c73a024e..29a9415dd376e 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -23,6 +23,7 @@ roles through `resolveMotion`. | `uikit/progressBar.ts` | UIProgressView's fill: the whole-track duration and curve, its minimum length and empty alpha; the reduced-motion pulse (three roles). | | `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). | | `uikit/segmented.ts` | UISegmentedControl: the selection indicator's spring; under Reduce Motion the animator's cross-fade replaces it. | +| `uikit/selection.ts` | Selection marks (checkmark accessory, multiselect circle, completion circle): they change in one frame. | | `uikit/switch.ts` | UISwitch on iOS 26.2: geometry, the lift, settle, travel and tracking springs, the flip distance, the track colour. | | `roles.ts` | The internal motion roles: the springs, durations and curves `spec:AST-094` FR4 names, registered by the shared tables, and a role's CSS form read back. | | `roleValue.ts` | A role's CSS form, written: a spring's duration and bounce, a duration in ms, a curve's `cubic-bezier()`. | diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts index ab92f5038e486..5839cafe4fc66 100644 --- a/packages/core/src/motion/uikit/index.ts +++ b/packages/core/src/motion/uikit/index.ts @@ -4,10 +4,10 @@ * @file index.ts * @input The domain files of the UIKit constants table * @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`, - * …), `scroll`, `timing`, `navigation`, `progressBar`, `segmentedControl`, - * the `slider` and switch (`switchControl`) domains, and the gesture - * thresholds (one `UIKIT_*` group per recognizer, their union - * `UIKIT_GESTURES`, and the haptic tables) + * …), and the `scroll`, `timing`, `navigation`, `progressBar`, + * `segmentedControl`, `selection`, `slider` and switch (`switchControl`) + * domains. It also re-exports the gesture thresholds: one `UIKIT_*` group + * per recognizer, their union `UIKIT_GESTURES`, and the haptic tables. * @position Entry of the UIKit constants table (motion/uikit). Internal to * core: not exported from the package entry point * @@ -43,6 +43,7 @@ export {navigation, registerNavigationTable} from './navigation'; export {progressBar, registerProgressBarTable} from './progressBar'; export {registerScrollTable, scroll} from './scroll'; export {segmentedControl} from './segmented'; +export {selection} from './selection'; export {slider} from './slider'; export { ACTION_SHEET_DISMISS_SPRING, diff --git a/packages/core/src/motion/uikit/selection.ts b/packages/core/src/motion/uikit/selection.ts new file mode 100644 index 0000000000000..f68ef77a86726 --- /dev/null +++ b/packages/core/src/motion/uikit/selection.ts @@ -0,0 +1,41 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file selection.ts + * @input Nothing; data only + * @output Exports `selection`: how iOS shows a selection mark changing, such + * as a list's checkmark accessory or multiselect circle + * @position The selection domain of the UIKit constants table + * (motion/uikit); Indicator/selectionMotion.stylex.ts mirrors it + * + * iOS marks a choice on its row. On iOS 26.2 the mark changes in the frame + * the selection lands, in every built-in case measured. The edit-mode circle + * of a UITableView cross-fades for 0.15 s; list rows in edit mode own it. + * + * SYNC: When modified, update /packages/core/src/Indicator/selectionMotion.stylex.ts. + */ + +/** + * How iOS shows a selection mark changing: in one frame, with no animation. + */ +export const selection = { + mark: { + /** + * A selection mark appears and leaves in one frame. Reduce Motion keeps + * it: there is nothing to substitute. + * @source measured: Settings › Camera › Record Video (built-in app), iOS + * 26.2 simulator, iPhone 17 Pro, cell hooks and CAAnimation read: the + * checkmark accessory moves between rows in one frame about 87 ms after + * the lift, with no animation on it, Oct 24 2026 + * @source measured: Reminders (built-in app), iOS 26.2 simulator, iPhone + * 17 Pro, UIImageView symbol read: the completion circle's symbol is + * replaced in one frame about 17 ms after the lift, with no symbol + * effect, Oct 24 2026 + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CAAnimation read: a UICollectionView list's + * multiselect accessory changes at the lift with no animation added, + * with and without Reduce Motion, Oct 23 2026 + */ + changeMs: 0, + }, +} as const;