An open source design system that's fully customizable and agent ready
TypeScript
fix(core): layout glides play the theme's move curve, not a spring (#10236)
Cindy Zhang8bd8c6146f9d
diff --git a/.changeset/animated-layout-curve-tokens.md b/.changeset/animated-layout-curve-tokens.mdnew file mode 100644index 0000000000..a199104b8d--- /dev/null+++ b/.changeset/animated-layout-curve-tokens.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Animated layout: the glide, the in-place swap and the edge reveal play the theme's move curve (`--ease-move`) over `--duration-medium-min` instead of a spring, so they follow the theme's `character` and `tempo` and land with the motion around them. Reduce Motion is unchanged: a cross-fade under a coarse pointer, an immediate change otherwise. The glides of AppShell's content area, Collapsible, Table's row expansion and TreeList change feel: 225 ms in the Neutral theme, 310 ms with no theme, instead of about 735 ms. A theme whose move easing is a `linear()` or `steps()` function glides on it, as the browser plays it. The segmented control's selection, which reads its timing the same way, now plays such an easing too instead of moving at once.++@vjeuxdiff --git a/.github/scripts/ci-interaction-webkit.test.mjs b/.github/scripts/ci-interaction-webkit.test.mjsindex 2157a32468..5b6ec9a33c 100644--- a/.github/scripts/ci-interaction-webkit.test.mjs+++ b/.github/scripts/ci-interaction-webkit.test.mjs@@ -425,6 +425,9 @@ describe('WebKit interaction proof routing', () => {// brings the outlet into the gesture fixtures and the pager bundle; the// scope covers it before that import lands.'packages/core/src/Layer/modalOutlet.ts',+ // The animated-layout glide reads its timing through the theme-timing+ // reader, which resolves token references, so its bundle carries them.+ 'packages/core/src/theme/tokenReferences.ts','packages/core/src/hooks/useMenuPress.ts','packages/core/src/hooks/menuPressGesture.ts','packages/core/src/hooks/useLongPress.ts',diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a739cdad98..30b462b1c2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2702,7 +2702,7 @@ jobs:id: scopeuses: ./.test-scope/.github/actions/test-scopewith:- paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver|scrollView|nodeType)|packages/core/src/privateAttributes/(hapticSwitch|reducedMotion)\.stylex\.ts$|packages/core/src/Layer/(inputHold|modalOutlet)\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/scripts/(playwright-legs|a11y-pr-contracts|lane-environment)\.mjs$|scripts/lib/duration-split\.mjs$|\.github/(playwright-leg-durations|lane-environments)\.json$|\.github/actions/test-scope/|.*\.interaction\.browser\.spec\.ts$)'+ paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver|scrollView|nodeType)|packages/core/src/privateAttributes/(hapticSwitch|reducedMotion)\.stylex\.ts$|packages/core/src/theme/tokenReferences\.ts$|packages/core/src/Layer/(inputHold|modalOutlet)\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/scripts/(playwright-legs|a11y-pr-contracts|lane-environment)\.mjs$|scripts/lib/duration-split\.mjs$|\.github/(playwright-leg-durations|lane-environments)\.json$|\.github/actions/test-scope/|.*\.interaction\.browser\.spec\.ts$)'outside-pull-request: skiprequires-head-file: playwright.interaction.config.ts# Lists the changed files, so the planner adds a changed spec.diff --git a/apps/storybook/stories/ThemeMotionTempo.stories.tsx b/apps/storybook/stories/ThemeMotionTempo.stories.tsxindex 1371301577..650161f045 100644--- a/apps/storybook/stories/ThemeMotionTempo.stories.tsx+++ b/apps/storybook/stories/ThemeMotionTempo.stories.tsx@@ -133,8 +133,8 @@ const durationScaleTheme = defineTheme({/*** A theme with only a duration scale, nested in a theme at tempo 1.5. Its- * glide keeps the pace of its own durations, as on a page with no tempo. The- * glide beside it, in the outer theme, takes 1.5 times as long.+ * glide plays its own scale's `--duration-medium-min`, which the outer tempo+ * does not reach.*/export const NestedDurationScale: Story = {name: 'A duration scale nested in a tempo',diff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.mdindex 25a05afe64..4ecfa07194 100644--- a/docs/specs/AST-105-animated-layout/spec.md+++ b/docs/specs/AST-105-animated-layout/spec.md@@ -216,10 +216,6 @@ Out of coverage, each taking its final place at once:- `architecture:react-component-runtime` INV12 produces the glide.- `architecture:react-component-runtime` INV12 also gains the in-place swap(FR8); no component swaps yet.-- The glide, the in-place swap and the edge reveal play `springs.settle`- today; FR4 moves them to `--ease-move` over `--duration-medium-min`. The- SideNav rail and AppShell's content area, which share that motion- (`component:SideNav` FR6, `component:AppShell` FR17), follow with them.- INV12 also produces the edge reveal (FR9). SideNav's rail clip and ride moveinto it from SideNav's own code, and a resizable LayoutPanel's collapse andopen, which today jump, adopt it; LayoutPanel's docs say a collapse slides.diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsxindex 6d7a8a040b..9e76277431 100644--- a/packages/core/src/AppShell/AppShell.tsx+++ b/packages/core/src/AppShell/AppShell.tsx@@ -987,10 +987,10 @@ export function AppShell({return;}const motion = layoutMotionFor(main);- // Only a spring glides the column; under Reduce Motion the two wraps+ // Only a glide moves the column; under Reduce Motion the two wraps// cross-fade over a steady surface (`design:reduced-motion` DR2).let change: LayoutChange | null = null;- if (motion.kind === 'spring') {+ if (motion.kind === 'glide') {change = reportLayoutChange(contentLayout, railRef);change.measureBefore();}@@ -1000,7 +1000,7 @@ export function AppShell({let held = 1;let entering = 0;const last = lastSwapRef.current;- if (last != null && motion.kind === 'spring') {+ if (last != null && motion.kind === 'glide') {// Read at the change's own start, where the glide it retargets// carries on. After a block, that is later than the frame the// timeline still reads.@@ -1047,7 +1047,7 @@ export function AppShell({const surface = backdropRef.current ?? main;const color = getComputedStyle(surface).backgroundColor;const isPainted = !/^rgba\(.*,\s*0\)$|^transparent$/.test(color);- const glides = layoutMotionFor(main).kind === 'spring';+ const glides = layoutMotionFor(main).kind === 'glide';if ((isRtl ? travel > 0 : travel < 0) && glides && isPainted) {cover.push({element: surface,diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.tsindex fbad9c1937..5dd904c43e 100644--- a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts@@ -1111,6 +1111,34 @@ test('a hand-written calc() duration token times a click’s slide as the segmen}});+test('with a mouse a click’s slide plays a theme’s linear() easing as the browser plays it, instead of landing at once', async ({+ browser,+}) => {+ const {context, group} = await openWithMouse(browser);+ try {+ // The motion scale's easing option writes such an easing.+ await group.evaluate(element => {+ element.style.setProperty('--ease-standard', 'linear(0, 0.8 50%, 1)');+ });+ const {from, to, durationMs, themeMs, frames} = await clickSlide(+ group,+ 'table',+ );+ expect(Math.abs(to - from), JSON.stringify({from, to})).toBeGreaterThan(10);+ expect(Math.abs(durationMs - themeMs), String(durationMs)).toBeLessThan(25);+ // Two straight runs: 80% of the way at half the time, then the rest.+ const linear = (x: number) => (x < 0.5 ? 1.6 * x : 0.8 + 0.4 * (x - 0.5));+ for (const {t, value} of frames.filter(frame => frame.t <= themeMs)) {+ expect(+ Math.abs((value - from) / (to - from) - linear(t / themeMs)),+ `${t} ms`,+ ).toBeLessThan(0.02);+ }+ } finally {+ await context.close();+ }+});+test('the slide plays UISegmentedControl’s measured spring, an internal motion role: no theme setting retunes it', async ({page,}) => {@@ -2353,22 +2381,28 @@ test('a drag commits through the destination item’s click too: its onClick runawait expectLensHidden(control);});+/** The lens's slide as the page reads it: its ends, its length, its frames. */+interface SlideRead {+ from: number;+ to: number;+ durationMs: number;+ frames: {t: number; value: number}[];+}+/*** Clicks the segment `value` and reads the lens's slide: where its first- * running translate starts and ends, and how long it runs. Also reads the- * duration that the segments' own transition resolves.+ * running translate starts and ends, how long it runs, and its frames. Also+ * reads the duration that the segments' own transition resolves.*/async function clickSlide(group: Locator,value: string,-): Promise<{from: number; to: number; durationMs: number; themeMs: number}> {+): Promise<SlideRead & {themeMs: number}> {// From the click on, the page reads the lens's first running translate// animation on each frame. It notes where the animation starts and ends,- // and how long it runs.+ // how long it runs, and each keyframe's time and value.await group.evaluate(element => {- const w = window as unknown as {- __slide: {from: number; to: number; durationMs: number} | null;- };+ const w = window as unknown as {__slide: SlideRead | null};w.__slide = null;const read = () => {for (const animation of element.getAnimations({subtree: true})) {@@ -2389,12 +2423,15 @@ async function clickSlide(const firstAtEnd = frames.find((frame, i) => Math.abs(values[i] - to) < 0.01,);+ const total = Number(effect.getComputedTiming().duration ?? 0);w.__slide = {from: values[0],to,- durationMs:- (firstAtEnd?.computedOffset ?? 1) *- Number(effect.getComputedTiming().duration ?? 0),+ durationMs: (firstAtEnd?.computedOffset ?? 1) * total,+ frames: frames.map((frame, i) => ({+ t: (frame.computedOffset ?? 0) * total,+ value: values[i],+ })),};return;}@@ -2416,22 +2453,15 @@ async function clickSlide('aria-checked','true',);- const slide = await group.page().waitForFunction(- () =>- (- window as unknown as {- __slide: {from: number; to: number; durationMs: number} | null;- }- ).__slide,- undefined,- {timeout: 3000},- );- const {from, to, durationMs} = (await slide.jsonValue()) as {- from: number;- to: number;- durationMs: number;- };- return {from, to, durationMs, themeMs};+ const slide = await group+ .page()+ .waitForFunction(+ () => (window as unknown as {__slide: SlideRead | null}).__slide,+ undefined,+ {timeout: 3000},+ );+ const {from, to, durationMs, frames} = (await slide.jsonValue()) as SlideRead;+ return {from, to, durationMs, themeMs, frames};}/** A desktop context: a mouse, no touch, a fine primary pointer. */diff --git a/packages/core/src/SideNav/SideNavRailMotion.test.tsx b/packages/core/src/SideNav/SideNavRailMotion.test.tsxindex 735f705889..1898fa00f6 100644--- a/packages/core/src/SideNav/SideNavRailMotion.test.tsx+++ b/packages/core/src/SideNav/SideNavRailMotion.test.tsx@@ -320,7 +320,7 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',it('starts a change made mid-motion from the width the rail shows', async () => {render(<Shell />);await toggle();- // About 150 ms into the collapse, on one of the glide's keyframes, the+ // About 30 ms into the collapse, on one of the glide's keyframes, the// clip shows part of the old rail. The column shows past its place by its// glide's offset then.const main = screen.getByRole('main');@@ -328,7 +328,7 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',entry => entry.element !== main && entry.element.contains(main),);const step = Number(slide.options.duration) / (slide.keyframes.length - 1);- const at = Math.round(150 / step) * step;+ const at = Math.round(30 / step) * step;const shift = translateAt(slide, at);Object.defineProperty(document, 'timeline', {configurable: true,@@ -367,10 +367,10 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',it('continues what the rail and the page show when a change reverses a running one', async () => {render(<Shell />);await toggle();- // 40 ms into the collapse: the old labels still show, fading.+ // 20 ms into the collapse: the old labels still show, fading.Object.defineProperty(document, 'timeline', {configurable: true,- value: {currentTime: 1040},+ value: {currentTime: 1020},});recorded = [];await toggle();@@ -403,11 +403,11 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',await toggle();settle();await toggle();- // 40 ms into the expand, collapse again.+ // 10 ms into the expand, collapse again.const at = (document.timeline as {currentTime: number}).currentTime;Object.defineProperty(document, 'timeline', {configurable: true,- value: {currentTime: at + 40},+ value: {currentTime: at + 10},});recorded = [];await toggle();diff --git a/packages/core/src/SideNav/railMotion.ts b/packages/core/src/SideNav/railMotion.tsindex be7f8d71c4..76fe547004 100644--- a/packages/core/src/SideNav/railMotion.ts+++ b/packages/core/src/SideNav/railMotion.ts@@ -12,9 +12,9 @@* @position Internal to SideNav (`component:SideNav` FR6, DEC-2); AppShell's* content area moves through the context (`component:AppShell` FR17)*- * Collapsing or expanding the rail plays one motion on one clock, the- * `springs.settle` role the animated-layout module reads (`spec:AST-105`- * FR4). The rail is FR9's edge reveal in its inline two-state form, which+ * Collapsing or expanding the rail plays one motion on one clock: the+ * theme's move curve, which the animated-layout module plays. The rail is+ * FR9's edge reveal in its inline two-state form, which* the module produces (`architecture:react-component-runtime` INV12): layout* snaps to the final rail width at once, nothing animates a width, and the* module clips the rail's inline-end edge from the width it shows to the newdiff --git a/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts b/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.tsindex ba593606d7..f387b95611 100644--- a/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts+++ b/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts@@ -329,15 +329,37 @@ test('the chevron turns on the glide; column lines and Reduce Motion change at o}) => {await mount(page, 'gliding-rows');await page.locator('[data-expansion-toggle]').first().click();+ // The values the rows glide on, as read where the area is.const timing = await page.locator('[data-expansion-toggle] > *').first()- .evaluate(glyph =>- (glyph as HTMLElement).style.getPropertyValue(+ .evaluate(glyph => {+ const row = document.querySelectorAll('tr[data-expansion-key]')[1];+ const glide = row+ ?.getAnimations()+ .find(animation =>+ (animation.effect as KeyframeEffect)+ .getKeyframes()+ .some(frame => frame.translate != null),+ );+ const style = (glyph as HTMLElement).style;+ // The theme's curve as an inline style serializes it (`.24` as `0.24`).+ const theme = document.createElement('i').style;+ theme.setProperty('transition-timing-function',- ),- );- expect(timing.startsWith('linear(')).toBe(true);+ getComputedStyle(glyph).getPropertyValue('--ease-move'),+ );+ return {+ easing: style.getPropertyValue('transition-timing-function'),+ duration: style.getPropertyValue('transition-duration'),+ theme: theme.getPropertyValue('transition-timing-function'),+ glideMs: Number(glide?.effect?.getComputedTiming().duration),+ };+ });+ expect(timing.glideMs).toBeGreaterThan(0);+ expect(parseFloat(timing.duration)).toBeCloseTo(timing.glideMs, 3);+ expect(timing.theme).toMatch(/^cubic-bezier\(/);+ expect(timing.easing).toBe(timing.theme);for (const dividers of ['columns', 'grid']) {await mount(page, 'gliding-rows', `&args=dividers:${dividers}`);diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.glide.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.glide.test.tsxindex 7fcd16875f..baf8c24a17 100644--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.glide.test.tsx+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.glide.test.tsx@@ -124,7 +124,7 @@ describe('useTableRowExpansion adopts animatedLayout (spec:AST-105 FR1, FR2)', (document.querySelector<HTMLElement>('[data-expansion-toggle] > *')?.style.getPropertyValue('transition-timing-function'),- ).toMatch(/^linear\(/);+ ).toBe('cubic-bezier(0.24, 1, 0.4, 1)');});it.each(['columns', 'grid'] as const)(@@ -146,7 +146,7 @@ describe('useTableRowExpansion adopts animatedLayout (spec:AST-105 FR1, FR2)', ();it.each(['columns', 'grid'] as const)(- 'takes the spring off a chevron when the table turns to %s dividers',+ 'takes the move curve off a chevron when the table turns to %s dividers',async dividers => {const user = userEvent.setup();const {rerender} = render(<ExpandableTable withHandle dividers="rows" />);@@ -156,9 +156,9 @@ describe('useTableRowExpansion adopts animatedLayout (spec:AST-105 FR1, FR2)', (const glyph = document.querySelector<HTMLElement>('[data-expansion-toggle] > *',);- expect(- glyph?.style.getPropertyValue('transition-timing-function'),- ).toMatch(/^linear\(/);+ expect(glyph?.style.getPropertyValue('transition-timing-function')).toBe(+ 'cubic-bezier(0.24, 1, 0.4, 1)',+ );rerender(<ExpandableTable withHandle dividers={dividers} />);expect(glyph?.style.getPropertyValue('transition-timing-function')).toBe('',@@ -255,9 +255,9 @@ describe('markGlidingRows', () => {expect(rows.map(row => row.hasAttribute('data-astryx-row-gliding')),).toEqual([false, false, true, true, false]);- expect(- rows[2].style.getPropertyValue('--_table-row-glide-width'),- ).toBe('0px');+ expect(rows[2].style.getPropertyValue('--_table-row-glide-width')).toBe(+ '0px',+ );// The first cell that scrolls draws the line; the pinned one draws its// own; the nested table's cell is not marked.expect(cellMarks(rows[2])).toEqual(['', 'line', '']);@@ -271,9 +271,7 @@ describe('markGlidingRows', () => {expect(rows.some(row => row.hasAttribute('data-astryx-row-gliding'))).toBe(false,);- expect(- rows[2].style.getPropertyValue('--_table-row-glide-width'),- ).toBe('');+ expect(rows[2].style.getPropertyValue('--_table-row-glide-width')).toBe('');expect(cellMarks(rows[2])).toEqual([null, null, null]);body.remove();});diff --git a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.tsindex 657c684dc6..3ee9d7a56a 100644--- a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts@@ -5,12 +5,14 @@* @input The animated-layout module bundled with esbuild onto fixture pages* written inline, real Chromium and WebKit (the interaction projects: a* phone with a coarse pointer) plus a fine-pointer describe- * @output One proof per `spec:AST-105` Coverage row, and FR2–FR4: which- * elements glide after a reported size change, by how much, on one shared- * start and spring, never past the area and never scrolling it; nothing- * without a handle; Reduce Motion by pointer; and FR9's edge reveal, a- * block-end and an inline-edge reveal and conceal and the two-state form,- * each element's moving edge on the content beside it on every frame, a+ * @output Proof of which elements glide after a reported size change, by how+ * much, and on one shared start and the theme's move curve. That curve may+ * be a `linear()` or `steps()` easing. A disclosure's indicator turns on the+ * timing read where the area is, through a nested theme scope. It checks that+ * the glide never passes the area or scrolls it, and that nothing moves+ * without a handle. It checks Reduce Motion by pointer, and the edge reveal:+ * a block-end and an inline-edge reveal and conceal, and the two-state form.+ * Each element's moving edge sits on the content beside it on every frame, a* reversal included* @position Real-browser verification of `spec:AST-105` and* `architecture:react-component-runtime` INV12@@ -19,7 +21,9 @@import {fileURLToPath} from 'node:url';import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';import {build} from 'esbuild';+import {cubicBezier} from '../bezier';import type * as Bundle from './animatedLayoutBundle';+import {stylexDeclarations} from './stylexDeclarationsPlugin';/** One animation on an element: its first frame and its timing. */interface MotionRead {@@ -42,6 +46,8 @@ declare global {}) => Promise<void>;/** Animations on an element: their first transform and timing. */motionOf: (selector: string) => MotionRead[];+ /** The first animation's keyframes: each one's time in ms and its y. */+ curveOf: (selector: string) => {t: number; y: number}[];/*** Pauses every animation `ms` into its motion: the page as it shows then,* however far apart the browser draws its frames.@@ -90,6 +96,7 @@ test.beforeAll(async () => {entryPoints: [fileURLToPath(new URL('./animatedLayoutBundle.ts', import.meta.url)),],+ plugins: [stylexDeclarations],bundle: true,write: false,format: 'iife',@@ -231,6 +238,21 @@ window.motionOf = selector => {};});};+window.curveOf = selector => {+ const [animation] = document+ .querySelector(selector)+ .getAnimations({subtree: false});+ const duration = Number(animation.effect.getTiming().duration);+ return animation.effect.getKeyframes().map(frame => {+ const match = /^(-?[\\d.e+-]+)px(?:\\s+(-?[\\d.e+-]+)px)?/.exec(+ frame.translate ?? '',+ );+ return {+ t: frame.computedOffset * duration,+ y: match == null || match[2] == null ? 0 : Number(match[2]),+ };+ });+};`;async function open(page: Page, body: string, style = '') {@@ -273,6 +295,34 @@ async function settle(page: Page) {.toBe(0);}+/** Every keyframe sits on `points` over `ms`, from the first one's offset. */+function expectOnCurve(+ curve: {t: number; y: number}[],+ points: readonly [number, number, number, number],+ ms: number,+) {+ expectOnEase(+ curve,+ cubicBezier([...points] as [number, number, number, number]),+ ms,+ );+}++/** Every keyframe sits on `ease` over `ms`, from the first one's offset. */+function expectOnEase(+ curve: {t: number; y: number}[],+ ease: (x: number) => number,+ ms: number,+) {+ const from = curve[0].y;+ // The glide moves the row: a curve read as all zeros proves nothing.+ expect(curve.length).toBeGreaterThan(2);+ expect(Math.abs(from)).toBeGreaterThan(10);+ for (const {t, y} of curve) {+ expect(y, `${t} ms`).toBeCloseTo(from * (1 - ease(Math.min(1, t / ms))), 2);+ }+}+/** The translate an animation starts from, in px. */function startOffset(first: string | null): {x: number; y: number} {// The browser shortens `-80px 0px` to `-80px`.@@ -632,8 +682,9 @@ test.describe('spec:AST-105 Coverage', () => {expect(motions).toHaveLength(1);expect(motions[0].composite).toBe('replace');expect(motions[0].startTime).not.toBe(first.startTime);- // No jump: the new glide starts where the old one is drawn.- expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);+ // No jump: the new glide starts where the old one is drawn, which is a+ // straight line between two of its keyframes.+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.01);// Still gliding down at least as fast: the new move adds to the motion.expect(run.before).toBeGreaterThan(0);expect(run.after).toBeGreaterThan(run.before * 0.9);@@ -656,7 +707,7 @@ test.describe('spec:AST-105 Coverage', () => {// started that many ms of motion ahead (0.3 px at 1 ms, about 3 px at// 9 ms).const {run} = await retarget(page, lateMs);- expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.01);expect(run.after).toBeGreaterThan(run.before * 0.9);});}@@ -744,7 +795,7 @@ test.describe('spec:AST-105 Coverage', () => {expect(run.cardGlidingAfter).toBe(true);expect(run.cardRetargeted).toBe(true);expect(run.rowGlidingAfter).toBe(true);- expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.01);});}@@ -766,7 +817,7 @@ test.describe('spec:AST-105 Coverage', () => {expect(run.cardGlidingAfter).toBe(true);expect(run.cardRetargeted).toBe(false);expect(run.rowGlidingAfter).toBe(true);- expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.01);});}@@ -824,10 +875,12 @@ test.describe('spec:AST-105 Coverage', () => {test('a change made after a block retargets a running glide from where the compositor has it, not from before the block', async ({page,}) => {+ // A glide long enough to still run when the 400 ms block ends.await open(page,`<div id="area" class="area"><div id="grow" class="grow"></div><div id="second" class="grow"></div><div id="after" class="row"></div></div>`,+ '#area { --duration-medium-min: 1000ms; }',);await change(page);await page.waitForTimeout(100);@@ -1895,7 +1948,7 @@ test.describe('spec:AST-105 FR2–FR4', () => {expect(withHandle).toEqual(without);});- test('the changed element and its followers start on one frame on springs.settle (FR4)', async ({+ test("the changed element and its followers start on one frame on the theme's move curve (FR4)", async ({page,}) => {await open(page, PAGE);@@ -1907,10 +1960,13 @@ test.describe('spec:AST-105 FR2–FR4', () => {expect(follower).toHaveLength(1);expect(grow[0].startTime).toBe(follower[0].startTime);expect(grow[0].duration).toBeCloseTo(follower[0].duration, 3);- // springs.settle is SwiftUI's smooth spring (duration 0.5 s, no bounce):- // it settles within a second.- expect(follower[0].duration).toBeGreaterThan(300);- expect(follower[0].duration).toBeLessThan(1200);+ // With no stylesheet, the tokens read core's declared values.+ expect(follower[0].duration).toBeCloseTo(310, 3);+ expectOnCurve(+ await page.evaluate(() => window.curveOf('#a')),+ [0.24, 1, 0.4, 1],+ 310,+ );});for (const layout of [@@ -2290,16 +2346,105 @@ test.describe('spec:AST-105 FR2–FR4', () => {);});- test("a scope's --motion-springs-settle changes nothing: the role is internal (FR4)", async ({+ for (const theme of [+ {+ name: 'at tempo 0.75',+ style: '--duration-medium-min: 232.5ms',+ ms: 232.5,+ points: [0.24, 1, 0.4, 1],+ },+ {+ name: 'at tempo 1.5',+ style: '--duration-medium-min: 465ms',+ ms: 465,+ points: [0.24, 1, 0.4, 1],+ },+ {+ name: "at character 'crisp'",+ style: '--ease-move: cubic-bezier(0, 0, 0.2, 1)',+ ms: 310,+ points: [0, 0, 0.2, 1],+ },+ {+ name: "at character 'expressive'",+ style: '--ease-move: cubic-bezier(0.3, 1.2, 0.5, 1)',+ ms: 310,+ points: [0.3, 1.2, 0.5, 1],+ },+ ] as const) {+ test(`a theme ${theme.name}: the glide plays its --ease-move over its --duration-medium-min (FR4)`, async ({+ page,+ }) => {+ // The tokens a theme with that knob writes on its scope.+ await open(page, PAGE, `#area { ${theme.style}; }`);+ await change(page);+ const [motion] = await page.evaluate(() => window.motionOf('#a'));+ expect(motion.duration).toBeCloseTo(theme.ms, 3);+ expectOnCurve(+ await page.evaluate(() => window.curveOf('#a')),+ theme.points,+ theme.ms,+ );+ });+ }++ for (const theme of [+ {+ easing: 'linear(0, 0.8 50%, 1)',+ // Two straight runs: to 0.8 at half the time, then on to 1.+ ease: (x: number) => (x < 0.5 ? 1.6 * x : 0.8 + 0.4 * (x - 0.5)),+ },+ {+ easing: 'steps(4, jump-end)',+ ease: (x: number) => Math.floor(4 * x) / 4,+ },+ ]) {+ test(`a theme whose --ease-move is ${theme.easing}: the glide plays it as the browser plays it (FR4)`, async ({+ page,+ }) => {+ // The motion scale's easing option writes such an easing.+ await open(page, PAGE, `#area { --ease-move: ${theme.easing}; }`);+ await change(page);+ const motions = await page.evaluate(() => window.motionOf('#a'));+ expect(motions, 'the content after the change glides').toHaveLength(1);+ expect(motions[0].duration).toBeCloseTo(310, 3);+ expectOnEase(+ await page.evaluate(() => window.curveOf('#a')),+ theme.ease,+ 310,+ );+ });+ }++ test("a disclosure's indicator turns on the timing read where the area is, whatever theme scope sits between them (FR4)", async ({page,}) => {- await open(page, PAGE);- await change(page);- const [shared] = await page.evaluate(() => window.motionOf('#a'));- await open(page, PAGE, '#area { --motion-springs-settle: 0.2s 0; }');+ // The area's tokens, and a nested scope with others around the indicator.+ await open(+ page,+ PAGE,+ `#area { --duration-medium-min: 310ms; --ease-move: cubic-bezier(0.24, 1, 0.4, 1); }+ #grow { --duration-medium-min: 620ms; --ease-move: cubic-bezier(0, 0, 0.2, 1); }`,+ );await change(page);- const [scoped] = await page.evaluate(() => window.motionOf('#a'));- expect(scoped.duration).toBeCloseTo(shared.duration, 3);+ const [motion] = await page.evaluate(() => window.motionOf('#a'));+ const indicator = await page.evaluate(() => {+ const area = document.getElementById('area') as HTMLElement;+ const chevron = document.createElement('span');+ document.getElementById('grow')?.append(chevron);+ window.AnimatedLayout.applyLayoutChangeTransition(+ window.AnimatedLayout.createAnimatedLayout(() => area),+ chevron,+ );+ const style = getComputedStyle(chevron);+ return {+ ms: parseFloat(style.transitionDuration) * 1000,+ easing: style.transitionTimingFunction,+ };+ });+ expect(motion.duration).toBeCloseTo(310, 3);+ expect(indicator.ms).toBeCloseTo(motion.duration, 3);+ expect(indicator.easing).toBe('cubic-bezier(0.24, 1, 0.4, 1)');});test('under Reduce Motion with a coarse pointer, both cross-fade with no travel (FR4)', async ({diff --git a/packages/core/src/motion/__tests__/animatedLayoutBundle.ts b/packages/core/src/motion/__tests__/animatedLayoutBundle.tsindex 4d55fc4290..790659f614 100644--- a/packages/core/src/motion/__tests__/animatedLayoutBundle.ts+++ b/packages/core/src/motion/__tests__/animatedLayoutBundle.ts@@ -9,6 +9,7 @@*/export {+ applyLayoutChangeTransition,createAnimatedLayout,holdLayoutEdge,holdLayoutExit,diff --git a/packages/core/src/motion/__tests__/stylexDeclarationsPlugin.ts b/packages/core/src/motion/__tests__/stylexDeclarationsPlugin.tsnew file mode 100644index 0000000000..8a469b7a9d--- /dev/null+++ b/packages/core/src/motion/__tests__/stylexDeclarationsPlugin.ts@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stylexDeclarationsPlugin.ts+ * @input esbuild's plugin interface+ * @output `stylexDeclarations`, an esbuild plugin that loads+ * `@stylexjs/stylex` as a stand-in whose `defineVars` returns its values+ * @position Shared by the motion browser specs that bundle a module which+ * imports the theme's token file+ *+ * The token file declares its variables through StyleX, which the build+ * compiles away. A page needs only the plain defaults beside them.+ */++import type {Plugin} from 'esbuild';++export const stylexDeclarations: Plugin = {+ name: 'stylex-declarations',+ setup(builder) {+ builder.onResolve({filter: /^@stylexjs\/stylex$/}, () => ({+ path: 'stylex',+ namespace: 'stylex-declarations',+ }));+ builder.onLoad({filter: /.*/, namespace: 'stylex-declarations'}, () => ({+ contents: 'export const defineVars = values => values;',+ loader: 'js',+ }));+ },+};diff --git a/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.tsindex 1d4ada6889..aaacc17980 100644--- a/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.ts@@ -13,7 +13,7 @@* too. Finger tracking draws the same in both. Under three real themes that set only `motion.tempo`, the* animated-layout glide lasts 0.75, 1 and 1.5 times as long, with a* finger or a mouse. A theme with only a duration scale, nested in one at- * tempo 1.5, glides at its own pace+ * tempo 1.5, glides on its own duration token* @position Browser proof for themeTempo.ts and resolveMotion.ts, run by* `pnpm test:interaction`; the unit proofs are resolveMotion.test.ts*/@@ -26,6 +26,7 @@ import {type StaticServer,} from '@astryxdesign/a11y-spec/storybook';import {build} from 'esbuild';+import {expandMotionScale} from '../../theme/expandMotionScale';import type * as MotionBundle from './motionBundle';declare const Motion: typeof MotionBundle;@@ -233,16 +234,32 @@ test.describe('with a mouse', () => {});});-test('a duration scale nested in a tempo theme glides at its own pace', async ({+test('a duration scale nested in a tempo theme glides on its own duration token', async ({page,}) => {await openStory(page, NESTED_STORY, 3);- const plain = await glideMs(page, 'section[data-row="plain"]');- expect(plain).toBeGreaterThan(300);- expect(- (await glideMs(page, 'section[data-row="outer"]')) / plain,- ).toBeCloseTo(1.5, 2);- expect(- (await glideMs(page, 'section[data-row="nested"]')) / plain,- ).toBeCloseTo(1, 2);+ // Each row's `--duration-medium-min`, in ms, as its theme writes it.+ const tokenMs = async (row: string) =>+ page.evaluate(+ selector =>+ Number.parseFloat(+ getComputedStyle(+ document.querySelector(selector) as Element,+ ).getPropertyValue('--duration-medium-min'),+ ),+ row,+ );+ // Each row glides on the `--duration-medium-min` of the theme it is in.+ for (const row of ['plain', 'outer', 'nested']) {+ const selector = `section[data-row="${row}"]`;+ expect(await glideMs(page, selector), row).toBeCloseTo(+ await tokenMs(selector),+ 1,+ );+ }+ // The nested scale's own value: the outer tempo is not on it.+ const own = expandMotionScale({fast: 130, medium: 310, ratio: 0.75});+ expect(await tokenMs('section[data-row="nested"]')).toBe(+ Number.parseFloat(own['--duration-medium-min']),+ );});diff --git a/packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.tsindex f329416aaa..0514a9ae97 100644--- a/packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.ts@@ -10,35 +10,22 @@* patterns. In one, the element's own transition carries the token. In the* other, the token is read where the element is. That length is the* element's computed transition. A `calc()` value resolves the same way- * for a caller that needs the values. With no stylesheet,- * `--duration-exit` reads its declared default where the element is+ * for a caller that needs the values. An easing that is not a cubic+ * Bézier, `linear()` or `steps()`, plays as the browser plays it in both+ * patterns. With no stylesheet, `--duration-exit` reads its declared+ * default where the element is* @position Browser proof for themeTiming.ts, run by `pnpm test:interaction`;* jsdom resolves no `calc()`*/import {fileURLToPath} from 'node:url';import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';-import {build, type Plugin} from 'esbuild';+import {build} from 'esbuild';import type * as ThemeTimingModule from '../themeTiming';+import {stylexDeclarations} from './stylexDeclarationsPlugin';let script = '';-// The token file declares its variables through StyleX, which the build-// compiles away; the page needs only the plain defaults beside them.-const stylexDeclarations: Plugin = {- name: 'stylex-declarations',- setup(builder) {- builder.onResolve({filter: /^@stylexjs\/stylex$/}, () => ({- path: 'stylex',- namespace: 'stylex-declarations',- }));- builder.onLoad({filter: /.*/, namespace: 'stylex-declarations'}, () => ({- contents: 'export const defineVars = values => values;',- loader: 'js',- }));- },-};-test.beforeAll(async () => {const result = await build({entryPoints: [fileURLToPath(new URL('../themeTiming.ts', import.meta.url))],@@ -179,6 +166,32 @@ test('both patterns play the same easing, a calc() argument included', async ({expect(outer.tokensAt).toEqual(outer.ownAt);});+test('an easing that is not a cubic Bézier plays as the browser plays it, in both patterns', async ({+ page,+}) => {+ await open(page);+ // The eased progress at a quarter and three quarters of the length.+ for (const [easing, expected] of [+ ['linear(0, 0.8 50%, 1)', [0.4, 0.9]],+ ['steps(3, jump-end)', [0, 2 / 3]],+ ] as const) {+ const {outer, nested} = await readBoth(page, {+ theme: {'--ease-standard': easing},+ });+ for (const at of [+ outer.ownAt,+ outer.tokensAt,+ nested.ownAt,+ nested.tokensAt,+ ]) {+ expect(at, easing).toHaveLength(2);+ at.forEach((value, i) =>+ expect(value, easing).toBeCloseTo(expected[i], 6),+ );+ }+ }+});+test('a duration that is not a positive length gives no curve in either pattern', async ({page,}) => {diff --git a/packages/core/src/motion/animatedLayout.edge.test.ts b/packages/core/src/motion/animatedLayout.edge.test.tsindex dbeb69644f..4228f791da 100644--- a/packages/core/src/motion/animatedLayout.edge.test.ts+++ b/packages/core/src/motion/animatedLayout.edge.test.ts@@ -734,9 +734,12 @@ describe('the edge reveal of a resized element, with no copy (spec:AST-105 FR9)'expect(pane.style.getPropertyValue('inline-size')).toBe('');expect(conceal.cancel).toHaveBeenCalled();const [reveal] = clipsOf(pane);- expect(String(reveal.keyframes[0].clipPath)).toBe(- `inset(0px ${260 - shown}px 0px 0px)`,+ const start = Number(+ /^inset\(0px ([\d.]+)px 0px 0px\)$/.exec(+ String(reveal.keyframes[0].clipPath),+ )?.[1],);+ expect(start).toBeCloseTo(260 - shown, 9);});it('cancel ends it at once and puts back what it held', () => {diff --git a/packages/core/src/motion/animatedLayout.test.ts b/packages/core/src/motion/animatedLayout.test.tsindex 4f2fc781c9..df4c4c063c 100644--- a/packages/core/src/motion/animatedLayout.test.ts+++ b/packages/core/src/motion/animatedLayout.test.ts@@ -4,15 +4,15 @@* @file animatedLayout.test.ts* @input vitest (jsdom), the animated-layout module, a recording stand-in for* Element.animate and stubbed layout rectangles (jsdom lays nothing out)- * @output Checks the handle (`spec:AST-105` FR1), that nothing runs without- * one (FR2), which elements the walk takes and how it moves them (FR3),- * the shared `springs.settle` motion and Reduce Motion by pointer (FR4),- * and the indicator's transition+ * @output Checks the handle, that nothing runs without one, and which+ * elements the walk takes and how it moves them. Checks the theme's move+ * curve, Reduce Motion by pointer, and the indicator's transition* @position Testing; the real geometry is proven in* __tests__/animatedLayout.interaction.browser.spec.ts*/import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {cubicBezier} from './bezier';import {applyLayoutChangeTransition,createAnimatedLayout,@@ -122,6 +122,23 @@ function translateOf(entry: Played): {x: number; y: number} {: {x: Number(match[1]), y: Number(match[2])};}+/** Each keyframe's time in ms and its vertical offset. */+function verticalCurveOf(entry: Played): {t: number; y: number}[] {+ return entry.keyframes.map(keyframe => ({+ t: Number(keyframe.offset) * Number(entry.options.duration),+ y: translateOf({...entry, keyframes: [keyframe]}).y,+ }));+}++/** The move curve core declares, as remaining distance at `t` of `ms`. */+function remainingOn(+ points: [number, number, number, number],+ ms: number,+): (t: number) => number {+ const ease = cubicBezier(points);+ return t => (t >= ms ? 0 : 1 - ease(t / ms));+}+async function runChange(layout: ReturnType<typeof createAnimatedLayout> | null,changed: Element,@@ -344,43 +361,48 @@ describe('one shared motion (spec:AST-105 FR4)', () => {);}- it('plays the changed element and its followers on springs.settle, with one duration', async () => {+ it("plays the changed element and its followers on the theme's move curve over --duration-medium-min, with one duration", async () => {+ // With no stylesheet, the tokens read core's declared values.await changeOnce();const follower = played.find(p => (p.element as HTMLElement).id === 'a');const own = played.find(p => (p.element as HTMLElement).id === 'changed');expect(follower).toBeDefined();expect(own).toBeDefined();expect(own?.options.duration).toBe(follower?.options.duration);- // SwiftUI's smooth spring (0.5 s, no bounce) settles in about 0.6 s.- expect(Number(follower?.options.duration)).toBeGreaterThan(400);- expect(Number(follower?.options.duration)).toBeLessThan(900);+ expect(Number(follower?.options.duration)).toBeCloseTo(310, 6);+ const remaining = remainingOn([0.24, 1, 0.4, 1], 310);+ for (const {t, y} of verticalCurveOf(follower as Played)) {+ expect(y).toBeCloseTo(-80 * remaining(t), 3);+ }});- it("ignores a scope's --motion-springs-settle: the role is internal", async () => {- await changeOnce();- const shared = played.find(p => (p.element as HTMLElement).id === 'a');- played = [];- document.body.innerHTML = '';- await changeOnce('--motion-springs-settle: 0.2s 0');- const scoped = played.find(p => (p.element as HTMLElement).id === 'a');- expect(scoped?.options.duration).toBe(shared?.options.duration);+ it('plays the --duration-medium-min and --ease-move of the theme the area is in', async () => {+ await changeOnce(+ '--duration-medium-min: 200ms; --ease-move: cubic-bezier(0, 0, 1, 1)',+ );+ const follower = played.find(p => (p.element as HTMLElement).id === 'a');+ expect(Number(follower?.options.duration)).toBeCloseTo(200, 6);+ for (const {t, y} of verticalCurveOf(follower as Played)) {+ expect(y).toBeCloseTo(-80 * (1 - t / 200), 3);+ }});- it("plays the shared spring at the tempo of the area's theme (spec:AST-108 FR3)", async () => {- await changeOnce();- const atOne = played.find(p => (p.element as HTMLElement).id === 'a');- played = [];- document.body.innerHTML = '';- // The private property a theme that sets `tempo` writes.- await changeOnce('--_astryx-motion-tempo: 1.5');+ it("follows the theme's tempo through its duration token, never scaled twice (spec:AST-108 FR2)", async () => {+ // A theme at tempo 1.5 writes the scaled token beside its tempo.+ await changeOnce(+ '--duration-medium-min: 465ms; --_astryx-motion-tempo: 1.5',+ );const follower = played.find(p => (p.element as HTMLElement).id === 'a');const own = played.find(p => (p.element as HTMLElement).id === 'changed');- const ratio =- Number(follower?.options.duration) / Number(atOne?.options.duration);- expect(Math.abs(ratio - 1.5)).toBeLessThan(0.01);+ expect(Number(follower?.options.duration)).toBeCloseTo(465, 6);expect(own?.options.duration).toBe(follower?.options.duration);});+ it('lands at once when the theme sets a zero duration', async () => {+ await changeOnce('--duration-medium-min: 0ms');+ expect(played).toEqual([]);+ });+it('cross-fades with no travel under Reduce Motion on a coarse pointer', async () => {media['(prefers-reduced-motion: reduce)'] = true;media['(pointer: coarse)'] = true;@@ -400,8 +422,9 @@ describe('one shared motion (spec:AST-105 FR4)', () => {});it('retargets an element already gliding: one glide, started from where it is on screen', async () => {+ // A long, even curve, so the first glide still moves fast 100 ms in.const {area, changed, phase} = setUp(- '<div id="area"><div id="changed"></div><div id="a"></div></div>',+ '<div id="area" style="--duration-medium-min: 1000ms; --ease-move: cubic-bezier(0, 0, 1, 1)"><div id="changed"></div><div id="a"></div></div>',);const a = document.getElementById('a') as HTMLElement;let top = 0;@@ -432,13 +455,20 @@ describe('one shared motion (spec:AST-105 FR4)', () => {expect(second).toHaveLength(1);// From 50 on screen to 120: it starts 70 px above its new place.expect(translateOf(second[0]).y).toBeCloseTo(-70);- // And it keeps the first glide's speed 100 ms in (about 6 px a frame);- // a new spring from rest moves about 1.4 px in its first frame.- const next = translateOf({- ...second[0],- keyframes: second[0].keyframes.slice(1),- });- expect(next.y - -70).toBeGreaterThan(3);+ // The rest of the first glide from 100 ms in, plus the new move on a+ // fresh curve.+ const remaining = remainingOn([0, 0, 1, 1], 1000);+ const held = -80 * remaining(100);+ const curve = verticalCurveOf(second[0]);+ for (const {t, y} of curve) {+ expect(y).toBeCloseTo(+ -80 * remaining(100 + t) + (-70 - held) * remaining(t),+ 3,+ );+ }+ // A glide started over from rest would sit more than 3 px from it.+ const restart = curve.map(({t, y}) => Math.abs(y - -70 * remaining(t)));+ expect(Math.max(...restart)).toBeGreaterThan(3);});it('drops a measurement no commit claims by the next frame', async () => {@@ -544,7 +574,7 @@ describe('the changed element exits (spec:AST-105 FR4)', () => {expect(content.style.getPropertyValue('margin-block-end')).toBe('');});- it('keeps the content where it is while it gives up its space, conceals it on the spring, then hands it back', () => {+ it('keeps the content where it is while it gives up its space, conceals it on the move curve, then hands it back', () => {const {content, layout} = exitSetUp();const done = vi.fn();const written = vi.spyOn(content.style, 'setProperty');@@ -716,7 +746,7 @@ describe('two changes in one frame (spec:AST-105 FR3)', () => {});describe('the indicator transition', () => {- it('takes the spring as a linear() easing with a handle, and clears without one', () => {+ it("takes the theme's move curve and duration with a handle, and clears without one", () => {document.body.innerHTML = '<div id="area"><svg id="chevron"></svg></div>';const area = document.getElementById('area') as HTMLElement;const chevron = document.getElementById(@@ -726,16 +756,31 @@ describe('the indicator transition', () => {createAnimatedLayout(() => area),chevron,);- expect(- chevron.style.getPropertyValue('transition-timing-function'),- ).toMatch(/^linear\(0 0%, .*1 100%\)$/);- expect(chevron.style.getPropertyValue('transition-duration')).toMatch(- /^\d+ms$/,+ expect(chevron.style.getPropertyValue('transition-timing-function')).toBe(+ 'cubic-bezier(0.24, 1, 0.4, 1)',);+ expect(chevron.style.getPropertyValue('transition-duration')).toBe('310ms');applyLayoutChangeTransition(null, chevron);expect(chevron.style.getPropertyValue('transition-duration')).toBe('');});+ it('takes the timing read where the area is, whatever scope sits between them', () => {+ document.body.innerHTML = `<div id="area" style="--duration-medium-min: 465ms; --ease-move: cubic-bezier(0, 0, 0.2, 1)">+ <div style="--duration-medium-min: 620ms; --ease-move: cubic-bezier(0.3, 1.2, 0.5, 1)"><svg id="chevron"></svg></div></div>`;+ const area = document.getElementById('area') as HTMLElement;+ const chevron = document.getElementById(+ 'chevron',+ ) as unknown as SVGSVGElement;+ applyLayoutChangeTransition(+ createAnimatedLayout(() => area),+ chevron,+ );+ expect(chevron.style.getPropertyValue('transition-duration')).toBe('465ms');+ expect(chevron.style.getPropertyValue('transition-timing-function')).toBe(+ 'cubic-bezier(0, 0, 0.2, 1)',+ );+ });+it('is immediate under Reduce Motion', () => {media['(prefers-reduced-motion: reduce)'] = true;document.body.innerHTML = '<div id="area"><svg id="chevron"></svg></div>';diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex faa4d7a75f..3364d7157e 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -3,9 +3,8 @@/*** @file animatedLayout.ts* @input The DOM (layout rectangles, computed style) and Web Animations. The- * internal `springs.settle` motion role at the area's tempo- * (resolveMotion.ts), the Reduce Motion cross-fade clock (uikit/timing.ts)- * and the block measure (frameBlock.ts)+ * theme's move curve and duration (themeTiming.ts), the Reduce Motion+ * cross-fade clock (uikit/timing.ts) and the block measure (frameBlock.ts)* @output Exports `createAnimatedLayout`, the opaque `AnimatedLayout` handle,* `reportLayoutChange`, `playLayoutChange` and `layoutStartFor`. It also* exports the exit hold (`holdLayoutExit`, `releaseLayoutExit`), the@@ -38,8 +37,8 @@* zero-size elements are skipped (an absolute child rides with its moving* parent); a stuck sticky element does not change rectangle, so it stays.* - The move is a compositor-only `translate` (replace composition) from the- * old place to the new one, sampled from `springs.settle` into linear- * keyframes and corrected for a scaled ancestor. An element already gliding+ * old place to the new one. Its linear keyframes sample the theme's move+ * curve, corrected for a scaled ancestor. An element already gliding* keeps that motion and adds the new move: the rest of its curve and the* new move are summed into one new glide, velocity included. Its place* before the change is read on the clock of every glide that carries it,@@ -50,8 +49,8 @@* glide the change leaves running cancels out of the move. Nothing* animates height, and nothing scrolls the area.* - A measurement no commit claims by the next frame is dropped.- * - The changed element plays its own entrance on the same spring, started in- * the same frame (`playLayoutChange`), or its exit: kept where it is while+ * - The changed element plays its own entrance on the same curve, started in+ * the same frame (`playLayoutChange`). Or it exits, kept where it is while* it gives up its space and conceals (`holdLayoutExit`). Both are FR9's* edge reveal: from its block-end edge by default, or from the block-start* or an inline edge it is given. Once the content on that edge's side@@ -82,8 +81,6 @@*/import {LATE_START_MS} from './frameBlock';-import {resolveMotion} from './resolveMotion';-import {motionRole} from './roles';import {inertCopy,isCopyable,@@ -92,20 +89,15 @@ import {visiblePartCopy,wrapText,} from './transientCopy';-import {isSpring} from './roleValue';-import {progressCurve} from './progress';-import type {SpringDescription} from './spring';-import {registerSpringsTable, SETTLE_SPRING} from './uikit/springs';+import {readThemeTiming, readThemeTokenText} from './themeTiming';import {themeReducesMotion} from '../privateAttributes/reducedMotion.stylex';import {reducedMotionCrossFade} from './uikit/timing';-/** The shared motion role (`spec:AST-105` FR4). */-const ROLE_ID = 'springs.settle';/** Below this many pixels a shift is not worth a move. */const MIN_SHIFT_PX = 0.5;/** The touch cross-fade's cap (`design:reduced-motion` DR2). */const CROSS_FADE_CAP_MS = 200;-/** Keyframes per second the spring is sampled at. */+/** Keyframes per second the motion is sampled at. */const SAMPLES_PER_SECOND = 60;// ---------------------------------------------------------------------------@@ -114,7 +106,7 @@ const SAMPLES_PER_SECOND = 60;/** How a change plays under the reader's settings. */type LayoutMotion =- | {readonly kind: 'spring'; readonly progress: SpringProgress}+ | {readonly kind: 'glide'; readonly progress: GlideProgress}| {readonly kind: 'fade';readonly durationMs: number;@@ -122,9 +114,11 @@ type LayoutMotion =}| {readonly kind: 'instant'};-/** The settle spring as remaining distance (1 → 0) over its duration. */-interface SpringProgress {+/** The move curve as remaining distance (1 → 0) over its duration. */+interface GlideProgress {readonly durationMs: number;+ /** The move curve's CSS text, as read where the area is. */+ readonly easing: string;/** Remaining fraction of the move at `t` ms. */remaining(t: number): number;}@@ -137,22 +131,24 @@ function matches(element: Element, query: string): boolean {}/**- * `springs.settle` from the internal role registry: one shared value for the- * glide, the changed element and the indicator. Motion roles are internal- * (`spec:AST-094` DEC-11): no page style sets the role. The glide plays it- * at the tempo of the theme that `area` is in.+ * The theme's move curve over its shortest medium duration where `area` is:+ * one value for the glide, the changed element and the indicator. The tokens+ * carry the theme's `character` and `tempo`. Null when the duration is zero+ * or the browser plays no such easing, and then the change lands at once.*/-function settleSpring(area: Element): SpringDescription {- registerSpringsTable();- const value = motionRole(ROLE_ID)?.value;- return resolveMotion(area, isSpring(value) ? value : SETTLE_SPRING);-}--function springProgress(description: SpringDescription): SpringProgress {- const curve = progressCurve(description, {epsilon: 0.001});- const durationMs = Math.max(1, curve.duration * 1000);+function glideProgress(area: Element): GlideProgress | null {+ const curve = readThemeTiming(area, {+ duration: '--duration-medium-min',+ easing: '--ease-move',+ });+ const easing = readThemeTokenText(area, '--ease-move');+ if (curve == null || easing == null) {+ return null;+ }+ const durationMs = curve.duration * 1000;return {durationMs,+ easing,remaining: t => (t >= durationMs ? 0 : 1 - curve.at(t / 1000)),};}@@ -176,7 +172,12 @@ function layoutMotion(area: Element): LayoutMotion {easing: `cubic-bezier(${x1}, ${y1}, ${x2}, ${y2})`,};}- return {kind: 'spring', progress: springProgress(settleSpring(area))};+ const progress = glideProgress(area);+ return progress == null ? {kind: 'instant'} : {kind: 'glide', progress};+}++function sampleCount(durationMs: number): number {+ return Math.max(2, Math.ceil((durationMs / 1000) * SAMPLES_PER_SECOND) + 1);}/** Linear keyframes over `durationMs`, one per frame, from `frame(t ms)`. */@@ -184,10 +185,7 @@ function sampleOver(durationMs: number,frame: (t: number) => Keyframe,): Keyframe[] {- const count = Math.max(- 2,- Math.ceil((durationMs / 1000) * SAMPLES_PER_SECOND) + 1,- );+ const count = sampleCount(durationMs);const keyframes: Keyframe[] = [];for (let i = 0; i < count; i++) {const offset = i / (count - 1);@@ -196,26 +194,14 @@ function sampleOver(return keyframes;}-/** Linear keyframes sampled from the spring, one per frame. */+/** Linear keyframes sampled from the move curve, one per frame. */function sampleKeyframes(- progress: SpringProgress,+ progress: GlideProgress,frame: (remaining: number) => Keyframe,): Keyframe[] {return sampleOver(progress.durationMs, t => frame(progress.remaining(t)));}-/** The spring as a CSS `linear()` easing, for a CSS transition. */-function linearEasing(progress: SpringProgress): string {- const stops: string[] = [];- const count = 24;- for (let i = 0; i <= count; i++) {- const fraction = i / count;- const value = 1 - progress.remaining(fraction * progress.durationMs);- stops.push(`${round(value)} ${round(fraction * 100)}%`);- }- return `linear(${stops.join(', ')})`;-}-function round(value: number): number {return Math.round(value * 1000) / 1000;}@@ -515,6 +501,25 @@ type OffsetCurve = (t: number) => {readonly x: number; readonly y: number};const AT_REST: OffsetCurve = () => ({x: 0, y: 0});+/**+ * `curve` as the browser draws it from `sampleOver`'s keyframes: a straight+ * line between each two. A new glide then starts where the old one shows.+ */+function drawnCurve(durationMs: number, curve: OffsetCurve): OffsetCurve {+ const count = sampleCount(durationMs);+ const points = Array.from({length: count}, (_, i) =>+ curve((i / (count - 1)) * durationMs),+ );+ return t => {+ const at = Math.min(Math.max(t / durationMs, 0), 1) * (count - 1);+ const i = Math.min(Math.floor(at), count - 2);+ const f = at - i;+ const a = points[i];+ const b = points[i + 1];+ return {x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f};+ };+}+/** A glide an element is playing, so a new change can retarget it. */interface Glide {readonly animation: Animation;@@ -1332,12 +1337,12 @@ function flush(batch: Batch): void {const moveX = dx / scale.x - held.x;const moveY = dy / scale.y - held.y;const {progress} = motion;- const offsetAt: OffsetCurve = t => {+ const durationMs = Math.max(progress.durationMs, carriedMs);+ const offsetAt = drawnCurve(durationMs, t => {const remaining = progress.remaining(t);const carry = carried(t);return {x: carry.x + moveX * remaining, y: carry.y + moveY * remaining};- };- const durationMs = Math.max(progress.durationMs, carriedMs);+ });// One replace-composited `translate`: the compositor runs it (INV12).const animation = safeAnimate(element,@@ -2334,10 +2339,10 @@ export function playLayoutSwap(};const {copyText, rideWith} = how;const fadedText =- copyText != null && motion.kind === 'spring' ? wrapText(copy) : [];+ copyText != null && motion.kind === 'glide' ? wrapText(copy) : [];// Each part as a function of time: its frame, or the copy's with its ride.const parts: [Element, (p: number, ride: LayoutRide) => Keyframe][] = [];- if (motion.kind === 'spring') {+ if (motion.kind === 'glide') {const moves = rideWith != null && rideWith.isCopyMoved !== false;parts.push([copy,@@ -2452,7 +2457,7 @@ export function playLayoutFrames(const animations: Animation[] = [];for (const {element, frames: shape} of parts) {const animation =- motion.kind === 'spring'+ motion.kind === 'glide'? safeAnimate(element,sampleKeyframes(motion.progress, remaining =>@@ -2628,9 +2633,9 @@ export function playLayoutEdge(const startedAt =changeStartIn(areaOf(handle, element), element.ownerDocument)?.at ?? 0;const durationMs =- motion.kind === 'spring' ? motion.progress.durationMs : motion.durationMs;+ motion.kind === 'glide' ? motion.progress.durationMs : motion.durationMs;const progressAt = (ms: number) =>- motion.kind === 'spring'+ motion.kind === 'glide'? 1 - motion.progress.remaining(Math.min(ms, durationMs)): 0;const shown = (): {extent: number; progress: number} | null => {@@ -3051,10 +3056,10 @@ export function reportLayoutEdge(/*** A disclosure's indicator (its chevron) turns on the same motion as the- * glide: its CSS transition takes the spring as a `linear()` easing, and an- * immediate change under Reduce Motion. Without a handle the inline values are- * cleared, so the component's own transition applies. An engine without- * `linear()` drops that value and keeps the component's easing.+ * glide. Its CSS transition takes the theme's move curve and duration as the+ * glide reads them where the area is, and is immediate under Reduce Motion.+ * Without a handle the inline values are cleared, so the component's own+ * transition applies.*/export function applyLayoutChangeTransition(handle: AnimatedLayout | null | undefined,@@ -3070,18 +3075,18 @@ export function applyLayoutChangeTransition(return;}const motion = layoutMotion(area);- if (motion.kind !== 'spring') {+ if (motion.kind !== 'glide') {element.style.setProperty('transition-duration', '0s');element.style.removeProperty('transition-timing-function');return;}- element.style.setProperty(- 'transition-duration',- `${Math.round(motion.progress.durationMs)}ms`,- );+ // Values, not the tokens: a theme scope between the area and the indicator+ // would retime a token that the indicator reads where it is.+ const ms = Math.round(motion.progress.durationMs * 1000) / 1000;+ element.style.setProperty('transition-duration', `${ms}ms`);element.style.setProperty('transition-timing-function',- linearEasing(motion.progress),+ motion.progress.easing,);}diff --git a/packages/core/src/motion/animatedLayoutAdopters.test.tsx b/packages/core/src/motion/animatedLayoutAdopters.test.tsxindex bb7847c40d..f4f6d4fb0b 100644--- a/packages/core/src/motion/animatedLayoutAdopters.test.tsx+++ b/packages/core/src/motion/animatedLayoutAdopters.test.tsx@@ -5,10 +5,10 @@* @input vitest (jsdom), React Testing Library, Collapsible, TreeList,* useAnimatedLayout, a recording stand-in for Element.animate and stubbed* rectangles for the content after the changed component- * @output Checks each adopting component with and without a handle- * (`spec:AST-105` FR1, FR2): with one, a toggle glides the content after it- * inside the container and the chevron takes the spring; without one,- * nothing animates and the chevron keeps its own transition+ * @output Checks each adopting component with and without a handle. With+ * one, a toggle glides the content after it inside the container, and the+ * chevron takes the move curve. Without one, nothing animates and the+ * chevron keeps its own transition* @position Testing; the walk and the motion are covered in* animatedLayout.test.ts and, in real browsers,* __tests__/animatedLayout.interaction.browser.spec.ts@@ -157,7 +157,7 @@ describe.each([expect(animated).toContain(after);expect(component.chevron()?.style.getPropertyValue('transition-timing-function'),- ).toMatch(/^linear\(/);+ ).toBe('cubic-bezier(0.24, 1, 0.4, 1)');});it('changes nothing without a handle', async () => {@@ -516,7 +516,7 @@ describe("a close plays the content's exit (spec:AST-105 FR4)", () => {expect(groupOf('photos')).toBeNull();});- it("drops the chevron's spring when the handle is removed", async () => {+ it("drops the chevron's move curve when the handle is removed", async () => {const user = userEvent.setup();const {rerender} = render(<Area withHandle>diff --git a/packages/core/src/motion/themeTiming.server.test.ts b/packages/core/src/motion/themeTiming.server.test.tsnew file mode 100644index 0000000000..8996658744--- /dev/null+++ b/packages/core/src/motion/themeTiming.server.test.ts@@ -0,0 +1,54 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file themeTiming.server.test.ts+ * @input vitest; esbuild and a plain Node process (no window, no document)+ * @output Checks that importing the theme-timing reader, or the animated-layout+ * module that reads it, does no DOM work and runs no StyleX at import+ * @position Testing; validates themeTiming.ts and animatedLayout.ts, which+ * server-safe factories import+ */++import {execFileSync} from 'node:child_process';+import path from 'node:path';+import {describe, expect, it} from 'vitest';++/** Bundles `entry` and imports it in a fresh Node process; prints its export names. */+function importOnServer(entry: string): string[] {+ const out = execFileSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ [+ "import {build} from 'esbuild';",+ `const result = await build({entryPoints: [${JSON.stringify(entry)}], bundle: true, write: false, format: 'esm', platform: 'node', logLevel: 'silent'});`,+ "const source = Buffer.from(result.outputFiles[0].text).toString('base64');",+ "if (typeof window !== 'undefined' || typeof document !== 'undefined') throw new Error('not a server');",+ "const mod = await import('data:text/javascript;base64,' + source);",+ 'process.stdout.write(JSON.stringify(Object.keys(mod).sort()));',+ ].join('\n'),+ ],+ {cwd: __dirname, encoding: 'utf8'},+ );+ return JSON.parse(out) as string[];+}++describe('the theme-timing reader on the server', () => {+ it('imports with no window or document', () => {+ expect(importOnServer(path.join(__dirname, 'themeTiming.ts'))).toEqual([+ 'declaredTimingTokens',+ 'easedProgress',+ 'readThemeTiming',+ 'readThemeTokenText',+ 'readThemeTokens',+ 'resolveTiming',+ ]);+ });++ it('keeps the animated-layout module safe to import there too', () => {+ expect(importOnServer(path.join(__dirname, 'animatedLayout.ts'))).toContain(+ 'createAnimatedLayout',+ );+ });+});diff --git a/packages/core/src/motion/themeTiming.test.ts b/packages/core/src/motion/themeTiming.test.tsindex a64971583e..e07eb74f91 100644--- a/packages/core/src/motion/themeTiming.test.ts+++ b/packages/core/src/motion/themeTiming.test.ts@@ -8,7 +8,9 @@* transition, and from tokens set where the element is or at their* defaults. A default that refers to a token reads it there. Also checks* the values that give no curve, the progress velocity and easedProgress's- * curve. jsdom resolves no `calc()`; the browser proof covers it.+ * curve, and that a jump in an easing carries no speed. jsdom resolves no+ * `calc()` and plays no `linear()` or `steps()`: a stand-in plays one, and+ * the browser proof covers both.* @position Testing; validates themeTiming.ts*/@@ -16,13 +18,14 @@ import {afterEach, describe, expect, it} from 'vitest';import {cubicBezier} from './bezier';import {parseCssEasing} from './roles';import {+ declaredTimingTokens,easedProgress,readThemeTiming,readThemeTokens,resolveTiming,type ThemeTimingTokens,} from './themeTiming';-import {easeDefaults} from '../theme/tokens.stylex';+import {durationDefaults, easeDefaults} from '../theme/tokens.stylex';const FAST: ThemeTimingTokens = {duration: '--duration-fast',@@ -42,6 +45,15 @@ function element(styles: Record<string, string> = {}): HTMLElement {return node;}+describe('declaredTimingTokens', () => {+ it('declares every timing token as the token file does', () => {+ expect(declaredTimingTokens).toEqual({+ ...durationDefaults,+ ...easeDefaults,+ });+ });+});+describe('readThemeTiming', () => {afterEach(() => {document.body.replaceChildren();@@ -114,6 +126,51 @@ describe('readThemeTiming', () => {);});+ it('plays an easing that is not a cubic Bézier as the browser does, and a jump in it hands on no speed', () => {+ // jsdom has no Web Animations, so a stand-in plays steps(4, jump-end).+ class StandInEffect {+ time = 0;+ constructor(_target: null, _frames: null, timing: {easing: string}) {+ if (timing.easing !== 'steps(4, jump-end)') {+ throw new TypeError(timing.easing);+ }+ }+ getComputedTiming() {+ return {progress: Math.floor((4 * this.time) / 1000) / 4};+ }+ }+ class StandInAnimation {+ constructor(readonly effect: StandInEffect) {}+ set currentTime(ms: number) {+ this.effect.time = ms;+ }+ }+ const view = window as unknown as Record<string, unknown>;+ const before = {+ Animation: view.Animation,+ KeyframeEffect: view.KeyframeEffect,+ };+ Object.assign(view, {+ Animation: StandInAnimation,+ KeyframeEffect: StandInEffect,+ });+ try {+ const curve = readThemeTiming(+ element({'--ease-standard': 'steps(4, jump-end)'}),+ FAST,+ );+ // 175 ms at the default, so the jumps fall at 43.75, 87.5 and 131.25 ms.+ expect(curve?.duration).toBeCloseTo(0.175, 6);+ expect(curve?.at(0.05)).toBe(0.25);+ // A retarget at a jump inherits this speed.+ for (const t of [0.04375, 0.0875, 0.13125, 0.1749]) {+ expect(curve?.velocity(t), `${t} s`).toBe(0);+ }+ } finally {+ Object.assign(view, before);+ }+ });+it('returns no curve for a duration that is not a positive length, or an easing it does not read', () => {expect(readThemeTiming(element({'--duration-fast': '0ms'}), FAST)).toBe(null,@@ -121,9 +178,9 @@ describe('readThemeTiming', () => {expect(readThemeTiming(element({'--duration-fast': 'fast'}), FAST)).toBe(null,);- expect(- readThemeTiming(element({'--ease-standard': 'steps(4)'}), FAST),- ).toBe(null);+ expect(readThemeTiming(element({'--ease-standard': 'bounce'}), FAST)).toBe(+ null,+ );expect(readThemeTiming(element({'transition-duration': '0s'}))).toBe(null);});});@@ -160,4 +217,17 @@ describe('easedProgress', () => {expect(none.at(0)).toBe(1);expect(none.velocity(0)).toBe(0);});++ it('with jumps, a jump carries no speed and a smooth stretch keeps its slope', () => {+ const steps = (x: number) => Math.floor(4 * x) / 4;+ // Without the option, the jump at a quarter of 300 ms reads as a spike.+ expect(easedProgress(0.3, steps).velocity(0.075)).toBeGreaterThan(100);+ const jumping = easedProgress(0.3, steps, {jumps: true});+ for (const t of [0, 0.0749, 0.075, 0.0751, 0.15, 0.225, 0.2995]) {+ expect(jumping.velocity(t), `${t} s`).toBe(0);+ }+ expect(+ easedProgress(0.2, x => x * x, {jumps: true}).velocity(0.1),+ ).toBeCloseTo(5, 1);+ });});diff --git a/packages/core/src/motion/themeTiming.ts b/packages/core/src/motion/themeTiming.tsindex ffc581d280..55154a4167 100644--- a/packages/core/src/motion/themeTiming.ts+++ b/packages/core/src/motion/themeTiming.ts@@ -5,9 +5,11 @@* @input An element, and the CSS or the theme tokens that time one motion* @output readThemeTiming: the eased progress from 0 to 1 that times a motion,* as one timed MotionCurve. It reads the element's own transition, or- * tokens where the element is. readThemeTokens and resolveTiming: that- * duration and easing as values. easedProgress: the curve for a length and- * an easing already read.+ * tokens where the element is. It plays an easing that is not a cubic+ * Bézier as the browser plays it. readThemeTokens and resolveTiming: that+ * duration and easing as values. readThemeTokenText: a token's text where+ * the element is. easedProgress: the curve for a length and an easing+ * already read.* @position Motion foundation, internal to core. Motion that a tap, a key or* the program starts reads its duration and easing from the theme with it.*@@ -20,12 +22,31 @@ import {cubicBezier} from './bezier';import {parseCssEasing, parseMotionRoleValue} from './roles';import type {MotionCurvePoints} from './roleValue';import {resolveTokenReferences} from '../theme/tokenReferences';-import {- durationDefaults,- easeDefaults,- type DurationVarName,- type EaseVarName,-} from '../theme/tokens.stylex';+import type {DurationVarName, EaseVarName} from '../theme/tokens.stylex';++/**+ * The value core declares for each timing token, as the token file declares+ * it. The token file declares its variables through StyleX, so importing its+ * values runs it; a reader that a server imports cannot do that.+ */+export const declaredTimingTokens: Readonly<+ Record<DurationVarName | EaseVarName, string>+> = {+ '--duration-fast-min': '130ms',+ '--duration-fast': '175ms',+ '--duration-fast-max': '230ms',+ '--duration-medium-min': '310ms',+ '--duration-medium': '410ms',+ '--duration-medium-max': '550ms',+ '--duration-slow-min': '730ms',+ '--duration-slow': '975ms',+ '--duration-slow-max': '1300ms',+ '--duration-exit': 'var(--duration-fast)',+ '--ease-standard': 'cubic-bezier(0.24, 1, 0.4, 1)',+ '--ease-entrance': 'cubic-bezier(0.24, 1, 0.4, 1)',+ '--ease-move': 'cubic-bezier(0.24, 1, 0.4, 1)',+ '--ease-exit': 'cubic-bezier(0.3, 0, 0.6, 0.6)',+};/** The theme tokens that time one motion. */export interface ThemeTimingTokens {@@ -43,10 +64,13 @@ export interface ResolvedTiming {/*** The eased progress from 0 to 1 over `seconds`, as a MotionCurve whose* velocity is in progress per second. A curve of no length is at its end.+ * With `jumps`, a jump in the easing, as in `steps()`, carries no speed. The+ * gentler of the slopes just before and just after counts.*/export function easedProgress(seconds: number,ease: (x: number) => number,+ {jumps = false}: {readonly jumps?: boolean} = {},): MotionCurve {const at = (t: number) =>seconds <= 0 || t >= seconds ? 1 : ease(Math.max(0, t) / seconds);@@ -61,7 +85,18 @@ export function easedProgress(}const before = Math.max(0, t - step);const after = Math.min(seconds, t + step);- return (at(after) - at(before)) / (after - before);+ if (!jumps) {+ return (at(after) - at(before)) / (after - before);+ }+ const here = at(t);+ const slopes: number[] = [];+ if (t > before) {+ slopes.push((here - at(before)) / (t - before));+ }+ if (after > t) {+ slopes.push((at(after) - here) / (after - t));+ }+ return slopes.reduce((a, b) => (Math.abs(b) < Math.abs(a) ? b : a));},};}@@ -74,19 +109,71 @@ function firstDurationMs(style: CSSStyleDeclaration): number | null {);}+/** The first transition's easing in a computed style, as the style writes it. */+function firstEasingText(style: CSSStyleDeclaration): string {+ return style.transitionTimingFunction.split(/,(?![^(]*\))/)[0] ?? '';+}+/** The first transition's easing in a computed style. */function firstEasing(style: CSSStyleDeclaration): MotionCurvePoints | null {- return parseCssEasing(- style.transitionTimingFunction.split(/,(?![^(]*\))/)[0] ?? '',- );+ return parseCssEasing(firstEasingText(style));+}++/**+ * The easing `text` as the browser plays it. A paused animation with that+ * easing gives its eased progress at each time it is set to. This reads an+ * easing that is not a cubic Bézier, such as `linear()` or `steps()`. Null+ * when the browser plays no such easing, or has no Web Animations.+ */+function browserEasing(+ doc: Document,+ text: string,+): ((x: number) => number) | null {+ const view = doc.defaultView;+ if (+ typeof view?.Animation !== 'function' ||+ typeof view.KeyframeEffect !== 'function'+ ) {+ return null;+ }+ let animation: Animation;+ try {+ animation = new view.Animation(+ new view.KeyframeEffect(null, null, {+ duration: 1000,+ easing: text,+ fill: 'both',+ }),+ null,+ );+ } catch {+ // The browser throws on an easing it cannot play.+ return null;+ }+ return x => {+ animation.currentTime = Math.min(1, Math.max(0, x)) * 1000;+ return animation.effect?.getComputedTiming().progress ?? 1;+ };}-/** The curve for a duration and an easing, or null if either cannot play. */-function progressOf({ms, points}: ResolvedTiming): MotionCurve | null {- if (ms == null || ms <= 0 || points == null) {+/**+ * The curve for a duration and an easing, or null if either cannot play. An+ * easing that is not a cubic Bézier plays as the browser plays `easing`, and+ * a jump in it carries no speed.+ */+function progressOf(+ doc: Document,+ {ms, points}: ResolvedTiming,+ easing: string,+): MotionCurve | null {+ if (ms == null || ms <= 0) {return null;}- return easedProgress(ms / 1000, cubicBezier(points));+ if (points != null) {+ return easedProgress(ms / 1000, cubicBezier(points));+ }+ const ease = browserEasing(doc, easing);+ return ease == null ? null : easedProgress(ms / 1000, ease, {jumps: true});}/**@@ -145,10 +232,7 @@ function tokenValue(return own;}const declared: Record<string, string> = {};- for (const [name, value] of Object.entries({- ...durationDefaults,- ...easeDefaults,- })) {+ for (const [name, value] of Object.entries(declaredTimingTokens)) {declared[name] = style.getPropertyValue(name).trim() || value;}return resolveTokenReferences(declared)[token] ?? '';@@ -176,23 +260,45 @@ export function readThemeTokens(});}+/**+ * The text of a timing token where `element` is: its value there, or the+ * default core declares, with that default's references read there too. It+ * holds no reference, so another element that takes it plays the same timing.+ */+export function readThemeTokenText(+ element: Element,+ token: DurationVarName | EaseVarName,+): string | null {+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ return style == null ? null : tokenValue(style, token);+}+/*** The eased progress from 0 to 1 that times a motion of `element`, as a* MotionCurve whose velocity is in progress per second. With no tokens, it* reads the element's own transition, where its stylesheet applies the* theme's tokens. With tokens, it reads them as readThemeTokens does. Null- * when the duration is not a positive length or the easing does not parse:- * the caller decides what that motion does.+ * when the duration is not a positive length or the browser plays no such+ * easing: the caller decides what that motion does.*/export function readThemeTiming(element: Element,tokens?: ThemeTimingTokens,): MotionCurve | null {+ const doc = element.ownerDocument;+ const style = doc.defaultView?.getComputedStyle(element);+ if (style == null) {+ return null;+ }if (tokens != null) {- return progressOf(readThemeTokens(element, tokens));+ const easing = tokenValue(style, tokens.easing);+ const duration = tokenValue(style, tokens.duration);+ return progressOf(doc, resolveTiming(element, {duration, easing}), easing);}- const style = element.ownerDocument.defaultView?.getComputedStyle(element);- return style == null- ? null- : progressOf({ms: firstDurationMs(style), points: firstEasing(style)});+ const easing = firstEasingText(style);+ return progressOf(+ doc,+ {ms: firstDurationMs(style), points: parseCssEasing(easing)},+ easing,+ );}