An open source design system that's fully customizable and agent ready
TypeScript
refactor(motion): core's shared theme-timing reader (#10068)
Christopher Chedeau1dce3182988b
diff --git a/.changeset/theme-timing-shared-curve.md b/.changeset/theme-timing-shared-curve.mdnew file mode 100644index 0000000000..c60fb17964--- /dev/null+++ b/.changeset/theme-timing-shared-curve.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: one shared reader times motion from the theme's duration and easing, as a computed transition resolves them. SegmentedControl's selection slide now reads its timing with it; its timing is unchanged, `calc()` tokens included.++@vjeuxdiff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.tsindex 87fda01795..b71ea0db95 100644--- a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts@@ -1058,80 +1058,7 @@ test('with a mouse a click slides the selection from the old segment to the new'transition-property','color, background-color, box-shadow',);- // 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.- await group.evaluate(element => {- const w = window as unknown as {- __slide: {from: number; to: number; durationMs: number} | null;- };- w.__slide = null;- const read = () => {- for (const animation of element.getAnimations({subtree: true})) {- const effect = animation.effect as KeyframeEffect | null;- if (- effect?.target !== element ||- effect.pseudoElement !== '::before'- ) {- continue;- }- const frames = effect- .getKeyframes()- .filter(frame => typeof frame.translate === 'string');- if (frames.length < 2) {- continue;- }- // The animator holds the last value after the curve ends: the- // curve's own length runs to the first frame at the end value.- const values = frames.map(frame =>- parseFloat(String(frame.translate)),- );- const to = values[values.length - 1];- const firstAtEnd = frames.find(- (frame, i) => Math.abs(values[i] - to) < 0.01,- );- w.__slide = {- from: values[0],- to,- durationMs:- (firstAtEnd?.computedOffset ?? 1) *- Number(effect.getComputedTiming().duration ?? 0),- };- return;- }- requestAnimationFrame(read);- };- element.addEventListener('click', () => requestAnimationFrame(read), {- capture: true,- once: true,- });- });- const themeMs = await group- .locator('[data-value="table"]')- .evaluate(- segment =>- parseFloat(getComputedStyle(segment).transitionDuration) * 1000,- );- await group.locator('[data-value="table"]').click();- await expect(group.locator('[data-value="table"]')).toHaveAttribute(- '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;- };+ const {from, to, durationMs, themeMs} = await clickSlide(group, 'table');// Where the segments sit. A title's weight change moves them by a pixel// or so, so the start is checked to within 3 px.const centers = await group.evaluate(element => {@@ -1159,6 +1086,24 @@ test('with a mouse a click slides the selection from the old segment to the new}});+test('a hand-written calc() duration token times a click’s slide as the segments’ own transition resolves it', async ({+ browser,+}) => {+ const {context, group} = await openWithMouse(browser);+ try {+ await group.evaluate(element => {+ element.style.setProperty('--duration-fast', 'calc(0.1s * 2)');+ });+ const {durationMs, themeMs} = await clickSlide(group, 'table');+ // The segments' transition resolves the token to 200 ms, and the slide+ // plays that length.+ expect(themeMs).toBe(200);+ expect(Math.abs(durationMs - themeMs), String(durationMs)).toBeLessThan(25);+ } finally {+ await context.close();+ }+});+test('the slide plays UISegmentedControl’s measured spring, an internal motion role: no theme setting retunes it', async ({page,}) => {@@ -2396,6 +2341,87 @@ test('a drag commits through the destination item’s click too: its onClick runawait expectLensHidden(control);});+/**+ * 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.+ */+async function clickSlide(+ group: Locator,+ value: string,+): Promise<{from: number; to: number; durationMs: number; 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.+ await group.evaluate(element => {+ const w = window as unknown as {+ __slide: {from: number; to: number; durationMs: number} | null;+ };+ w.__slide = null;+ const read = () => {+ for (const animation of element.getAnimations({subtree: true})) {+ const effect = animation.effect as KeyframeEffect | null;+ if (effect?.target !== element || effect.pseudoElement !== '::before') {+ continue;+ }+ const frames = effect+ .getKeyframes()+ .filter(frame => typeof frame.translate === 'string');+ if (frames.length < 2) {+ continue;+ }+ // The animator holds the last value after the curve ends: the+ // curve's own length runs to the first frame at the end value.+ const values = frames.map(frame => parseFloat(String(frame.translate)));+ const to = values[values.length - 1];+ const firstAtEnd = frames.find(+ (frame, i) => Math.abs(values[i] - to) < 0.01,+ );+ w.__slide = {+ from: values[0],+ to,+ durationMs:+ (firstAtEnd?.computedOffset ?? 1) *+ Number(effect.getComputedTiming().duration ?? 0),+ };+ return;+ }+ requestAnimationFrame(read);+ };+ element.addEventListener('click', () => requestAnimationFrame(read), {+ capture: true,+ once: true,+ });+ });+ const themeMs = await group+ .locator(`[data-value="${value}"]`)+ .evaluate(+ segment =>+ parseFloat(getComputedStyle(segment).transitionDuration) * 1000,+ );+ await group.locator(`[data-value="${value}"]`).click();+ await expect(group.locator(`[data-value="${value}"]`)).toHaveAttribute(+ '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};+}+/** A desktop context: a mouse, no touch, a fine primary pointer. */async function openWithMouse(browser: Browser): Promise<{context: BrowserContext;diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.tsindex 3fdf9c0af3..f048ae81ae 100644--- a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts+++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts@@ -28,7 +28,6 @@ import {createMotionEngine,type AnimateOptions,type Animator,- type MotionCurve,type MotionHandle,type MotionValues,type SpringTransition,@@ -41,8 +40,8 @@ import {registerSpringsTable, springs} from '../motion/uikit/springs';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {observeResize} from '../utils/sharedResizeObserver';import {titleOfSegment} from '../privateAttributes/segmentTitle.stylex';-import {cubicBezier} from '../motion/bezier';-import {parseCssEasing, parseMotionRoleValue} from '../motion/roles';+import {mapProgress, mapRange} from '../motion/progress';+import {easedProgress, readThemeTiming} from '../motion/themeTiming';import {useSegmentedTouchTracking} from './useSegmentedTouchTracking';/** The segments, in DOM order. */@@ -351,59 +350,8 @@ function isEnabledSegment(segment: HTMLElement): boolean {const titleOf = titleOfSegment;-/** The theme's timing: a duration in seconds and its easing. */-interface ThemeTiming {- readonly seconds: number;- readonly ease: (progress: number) => number;-}--/**- * The timing of `segment`'s own transition, which reads the theme's duration- * and easing tokens. The values stay readable while a carry turns the- * transition's property off. Null when the theme gives no duration.- */-function themeTimingOf(segment: HTMLElement): ThemeTiming | null {- const view = segment.ownerDocument.defaultView;- if (view == null) {- return null;- }- const style = view.getComputedStyle(segment);- const ms = parseMotionRoleValue(- 'duration',- style.transitionDuration.split(',')[0] ?? '',- );- const points = parseCssEasing(- style.transitionTimingFunction.split(/,(?![^(]*\))/)[0] ?? '',- );- if (ms == null || ms <= 0 || points == null) {- return null;- }- return {seconds: ms / 1000, ease: cubicBezier(points)};-}-/** A theme that gives the segments no transition: the lens lands at once. */-const INSTANT: ThemeTiming = {seconds: 0.001, ease: progress => progress};--/** A curve from `from` to `to` on `timing`. */-function timedCurve(- from: number,- to: number,- timing: ThemeTiming,-): MotionCurve {- const {seconds, ease} = timing;- const at = (t: number) =>- from + (to - from) * ease(Math.min(1, Math.max(0, t / seconds)));- const step = Math.min(seconds / 100, 0.001);- return {- duration: seconds,- at,- velocity: t => {- const before = Math.max(0, t - step);- const after = Math.min(seconds, t + step);- return (at(after) - at(before)) / (after - before);- },- };-}+const INSTANT = easedProgress(0.001, progress => progress);/** What the control reads of its selection motion. */export interface SegmentedSelection {@@ -1277,14 +1225,19 @@ export class SegmentedSelectionMotion {return;}this.velocity = {};- const timing = themeTimingOf(segment) ?? INSTANT;+ // The segment's own transition carries the theme's duration and easing.+ // They stay readable while a carry turns its property off.+ const progress = readThemeTiming(segment) ?? INSTANT;const at = options.at;+ // Unclamped, so an easing that overshoots carries the lens with it.+ const toward = (from: number, to: number) =>+ mapProgress(progress, mapRange([0, 1], [from, to], {clamp: false}));this.trackHandle(this.animator.play({- x: timedCurve(this.animator.get('x', at), 0, timing),- scaleX: timedCurve(this.animator.get('scaleX', at), 1, timing),- scaleY: timedCurve(this.animator.get('scaleY', at), 1, timing),+ x: toward(this.animator.get('x', at), 0),+ scaleX: toward(this.animator.get('scaleX', at), 1),+ scaleY: toward(this.animator.get('scaleY', at), 1),},options,),diff --git a/packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.tsnew file mode 100644index 0000000000..f329416aaa--- /dev/null+++ b/packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.ts@@ -0,0 +1,234 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file themeTiming.interaction.browser.spec.ts+ * @input themeTiming.ts bundled with esbuild onto a blank fixture page;+ * Chromium and WebKit on the phone profile+ * @output Proof that readThemeTiming resolves a motion's timing as the+ * browser resolves a transition. A hand-written `calc()` token, a nested+ * theme scope and a tempo-scaled value give one length in both of its+ * 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+ * @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 type * as ThemeTimingModule from '../themeTiming';++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))],+ plugins: [stylexDeclarations],+ bundle: true,+ write: false,+ format: 'iife',+ globalName: 'ThemeTiming',+ target: 'es2022',+ });+ script = result.outputFiles[0].text;+});++// A real navigation (not setContent): the page keeps its own window.+async function open(page: Page) {+ const html = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">+<style>+ :root { --duration-fast: 175ms; --ease-standard: cubic-bezier(0.24, 1, 0.4, 1); }+ .carrier {+ transition-property: color;+ transition-duration: var(--duration-fast);+ transition-timing-function: var(--ease-standard);+ }+</style>+<div id="theme">+ <div class="carrier" id="own"></div><div id="plain"></div>+ <div id="nested"><div class="carrier" id="own-nested"></div><div id="plain-nested"></div></div>+</div>+<script>${script}</script>`;+ await page.route('http://theme-timing.test/', async route =>+ route.fulfill({contentType: 'text/html', body: html}),+ );+ await page.goto('http://theme-timing.test/');+}++interface Reading {+ /** The carrier's computed transition-duration, in ms. */+ computed: number;+ /** readThemeTiming on the carrier's own transition, in ms. */+ own: number | null;+ /** readThemeTiming on the tokens, read on a plain sibling, in ms. */+ tokens: number | null;+ /** Both curves at a quarter and three quarters of their length. */+ ownAt: number[];+ tokensAt: number[];+}++/**+ * Sets the custom properties on the scopes and reads both patterns in the+ * outer scope and in the nested one.+ */+async function readBoth(+ page: Page,+ scopes: Record<string, Record<string, string>>,+): Promise<{outer: Reading; nested: Reading; probesLeft: number}> {+ return page.evaluate(scopes => {+ const byId = (id: string) => {+ const found = document.getElementById(id);+ if (found == null) {+ throw new Error(`the fixture has no #${id}`);+ }+ return found;+ };+ for (const [id, properties] of Object.entries(scopes)) {+ for (const [name, value] of Object.entries(properties)) {+ byId(id).style.setProperty(name, value);+ }+ }+ const {readThemeTiming} = (+ window as unknown as {ThemeTiming: typeof ThemeTimingModule}+ ).ThemeTiming;+ const ms = (seconds: number | undefined) =>+ seconds == null ? null : Math.round(seconds * 1e6) / 1e3;+ const samples = (curve: ReturnType<typeof readThemeTiming>) =>+ curve == null+ ? []+ : [0.25, 0.75].map(share => curve.at(share * curve.duration));+ const read = (ownId: string, plainId: string) => {+ const carrier = byId(ownId);+ const own = readThemeTiming(carrier);+ const tokens = readThemeTiming(byId(plainId), {+ duration: '--duration-fast',+ easing: '--ease-standard',+ });+ return {+ computed:+ Math.round(+ parseFloat(getComputedStyle(carrier).transitionDuration) * 1e6,+ ) / 1e3,+ own: ms(own?.duration),+ tokens: ms(tokens?.duration),+ ownAt: samples(own),+ tokensAt: samples(tokens),+ };+ };+ return {+ outer: read('own', 'plain'),+ nested: read('own-nested', 'plain-nested'),+ probesLeft: document.querySelectorAll('span').length,+ };+ }, scopes);+}++test('a hand-written calc() token times the motion as the transition resolves it, in both patterns', async ({+ page,+}) => {+ await open(page);+ const {outer, nested, probesLeft} = await readBoth(page, {+ theme: {'--duration-fast': 'calc(0.1s * 2)'},+ });+ for (const reading of [outer, nested]) {+ expect(reading.computed).toBe(200);+ expect(reading.own).toBe(200);+ expect(reading.tokens).toBe(200);+ }+ expect(probesLeft).toBe(0);+});++test('a nested theme scope and a tempo-scaled value resolve where the element is', async ({+ page,+}) => {+ await open(page);+ const {outer, nested} = await readBoth(page, {+ nested: {'--duration-fast': 'calc(175ms * 1.2)'},+ });+ expect([outer.computed, outer.own, outer.tokens]).toEqual([175, 175, 175]);+ expect([nested.computed, nested.own, nested.tokens]).toEqual([210, 210, 210]);+});++test('both patterns play the same easing, a calc() argument included', async ({+ page,+}) => {+ await open(page);+ const {outer} = await readBoth(page, {+ theme: {'--ease-standard': 'cubic-bezier(calc(0.25 * 2), 0, 0.5, 1)'},+ });+ expect(outer.ownAt).toHaveLength(2);+ expect(outer.tokensAt).toEqual(outer.ownAt);+});++test('a duration that is not a positive length gives no curve in either pattern', async ({+ page,+}) => {+ await open(page);+ for (const value of ['0s', 'fast']) {+ const {outer} = await readBoth(page, {theme: {'--duration-fast': value}});+ expect([outer.own, outer.tokens]).toEqual([null, null]);+ }+});++/** The page's bundle. */+type Bundle = typeof ThemeTimingModule;++test('resolveTiming resolves calc() values for a caller that needs them', async ({+ page,+}) => {+ await open(page);+ const resolved = await page.evaluate(() => {+ const {resolveTiming} = (window as unknown as {ThemeTiming: Bundle})+ .ThemeTiming;+ return resolveTiming(document.body, {+ duration: 'calc(0.15s * 2)',+ easing: 'cubic-bezier(calc(0.25 * 2), 0, 0.5, 1)',+ });+ });+ expect(resolved).toEqual({ms: 300, points: [0.5, 0, 0.5, 1]});+});++test('with no stylesheet, --duration-exit reads its declared default where the element is', async ({+ page,+}) => {+ await open(page);+ const read = await page.evaluate(() => {+ const {readThemeTiming, readThemeTokens} = (+ window as unknown as {ThemeTiming: Bundle}+ ).ThemeTiming;+ document.querySelector('style')?.remove();+ const plain = document.querySelector<HTMLElement>('#plain');+ if (plain == null) {+ throw new Error('the fixture has no #plain');+ }+ const unset = readThemeTiming(plain, {+ duration: '--duration-exit',+ easing: '--ease-exit',+ });+ plain.style.setProperty('--duration-fast', '250ms');+ return {+ unsetMs: unset == null ? null : Math.round(unset.duration * 1000),+ fastMs: readThemeTokens(plain, {duration: '--duration-exit'}).ms,+ };+ });+ expect(read).toEqual({unsetMs: 175, fastMs: 250});+});diff --git a/packages/core/src/motion/themeTiming.test.ts b/packages/core/src/motion/themeTiming.test.tsnew file mode 100644index 0000000000..a64971583e--- /dev/null+++ b/packages/core/src/motion/themeTiming.test.ts@@ -0,0 +1,163 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file themeTiming.test.ts+ * @input vitest (jsdom), themeTiming's readers and easedProgress, the+ * theme's duration and easing defaults+ * @output Checks how a motion reads its timing: from the element's own+ * 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.+ * @position Testing; validates themeTiming.ts+ */++import {afterEach, describe, expect, it} from 'vitest';+import {cubicBezier} from './bezier';+import {parseCssEasing} from './roles';+import {+ easedProgress,+ readThemeTiming,+ readThemeTokens,+ resolveTiming,+ type ThemeTimingTokens,+} from './themeTiming';+import {easeDefaults} from '../theme/tokens.stylex';++const FAST: ThemeTimingTokens = {+ duration: '--duration-fast',+ easing: '--ease-standard',+};++const standardEase = cubicBezier(+ parseCssEasing(easeDefaults['--ease-standard'])!,+);++function element(styles: Record<string, string> = {}): HTMLElement {+ const node = document.createElement('div');+ for (const [name, value] of Object.entries(styles)) {+ node.style.setProperty(name, value);+ }+ document.body.appendChild(node);+ return node;+}++describe('readThemeTiming', () => {+ afterEach(() => {+ document.body.replaceChildren();+ });++ it('reads the element\u2019s own transition with no tokens', () => {+ const timing = readThemeTiming(+ element({+ 'transition-duration': '0.3s, 1s',+ 'transition-timing-function': 'linear, ease-in',+ }),+ )!;+ expect(timing.duration).toBeCloseTo(0.3, 6);+ expect(timing.at(0.15)).toBeCloseTo(0.5, 6);+ expect(readThemeTiming(element())).toBe(null);+ });++ it('reads tokens set where the element is, in ms or s', () => {+ const seconds = readThemeTiming(+ element({'--duration-fast': '0.3s', '--ease-standard': 'linear'}),+ FAST,+ )!;+ expect(seconds.duration).toBeCloseTo(0.3, 6);+ expect(seconds.at(0.15)).toBeCloseTo(0.5, 6);+ const ms = readThemeTiming(element({'--duration-fast': '250ms'}), FAST)!;+ expect(ms.duration).toBeCloseTo(0.25, 6);+ expect(document.body.children).toHaveLength(2);+ });++ it('reads a token with no value on the element at the default core declares', () => {+ const timing = readThemeTiming(element(), FAST)!;+ expect(timing.duration).toBeCloseTo(0.175, 6);+ expect(timing.at(0.0875)).toBeCloseTo(standardEase(0.5), 6);+ expect(timing.at(0.175)).toBe(1);+ });++ it('reads --duration-exit with no value at its declared default, var(--duration-fast), resolved where the element is', () => {+ const exit: ThemeTimingTokens = {+ duration: '--duration-exit',+ easing: '--ease-exit',+ };+ expect(readThemeTiming(element(), exit)?.duration).toBeCloseTo(0.175, 6);+ expect(+ readThemeTokens(element({'--duration-fast': '250ms'}), {+ duration: '--duration-exit',+ }),+ ).toEqual({ms: 250, points: null});+ expect(readThemeTokens(element({'--duration-exit': '90ms'}), exit).ms).toBe(+ 90,+ );+ });++ it('gives the progress velocity per second, and none once the motion ends', () => {+ const timing = readThemeTiming(+ element({'--duration-fast': '0.3s', '--ease-standard': 'linear'}),+ FAST,+ )!;+ expect(timing.velocity(0)).toBeCloseTo(1 / 0.3, 4);+ expect(timing.velocity(0.15)).toBeCloseTo(1 / 0.3, 4);+ expect(timing.velocity(0.3)).toBe(0);+ const eased = readThemeTiming(element(), {+ duration: '--duration-fast',+ easing: '--ease-exit',+ })!;+ const t = 0.05;+ const h = 1e-6;+ expect(eased.velocity(t)).toBeCloseTo(+ (eased.at(t + h) - eased.at(t - h)) / (2 * h),+ 3,+ );+ });++ 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,+ );+ expect(readThemeTiming(element({'--duration-fast': 'fast'}), FAST)).toBe(+ null,+ );+ expect(+ readThemeTiming(element({'--ease-standard': 'steps(4)'}), FAST),+ ).toBe(null);+ expect(readThemeTiming(element({'transition-duration': '0s'}))).toBe(null);+ });+});++describe('resolveTiming', () => {+ afterEach(() => {+ document.body.replaceChildren();+ });++ it('resolves a time of zero or more and a cubic Bézier, and null for anything else or a text left out', () => {+ const node = element();+ expect(+ resolveTiming(node, {duration: '0.3s', easing: 'ease-in-out'}),+ ).toEqual({ms: 300, points: [0.42, 0, 0.58, 1]});+ expect(resolveTiming(node, {duration: '0ms'}).ms).toBe(0);+ expect(resolveTiming(node, {duration: 'fast'}).ms).toBe(null);+ expect(resolveTiming(node, {duration: '-1ms'}).ms).toBe(null);+ expect(resolveTiming(node, {easing: 'steps(4)'}).points).toBe(null);+ expect(resolveTiming(node, {})).toEqual({ms: null, points: null});+ expect(document.body.children).toHaveLength(1);+ });+});++describe('easedProgress', () => {+ it('eases from 0 to 1 over its length, and a curve of no length is at its end', () => {+ const curve = easedProgress(0.2, x => x * x);+ expect(curve.duration).toBe(0.2);+ expect(curve.at(0)).toBe(0);+ expect(curve.at(0.1)).toBeCloseTo(0.25, 6);+ expect(curve.at(0.2)).toBe(1);+ expect(curve.velocity(0.1)).toBeCloseTo(5, 3);+ expect(curve.velocity(0.2)).toBe(0);+ const none = easedProgress(0, x => x);+ expect(none.at(0)).toBe(1);+ expect(none.velocity(0)).toBe(0);+ });+});diff --git a/packages/core/src/motion/themeTiming.ts b/packages/core/src/motion/themeTiming.tsnew file mode 100644index 0000000000..ffc581d280--- /dev/null+++ b/packages/core/src/motion/themeTiming.ts@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file themeTiming.ts+ * @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.+ * @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.+ *+ * SYNC: When modified, update /packages/core/src/motion/themeTiming.test.ts+ * and /packages/core/src/motion/__tests__/themeTiming.interaction.browser.spec.ts+ */++import type {MotionCurve} from './animator';+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';++/** The theme tokens that time one motion. */+export interface ThemeTimingTokens {+ readonly duration: DurationVarName;+ readonly easing: EaseVarName;+}++/** A duration and an easing that time a motion, each null when unresolved. */+export interface ResolvedTiming {+ /** The duration in ms, zero or more. */+ readonly ms: number | null;+ readonly points: MotionCurvePoints | null;+}++/**+ * 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.+ */+export function easedProgress(+ seconds: number,+ ease: (x: number) => number,+): MotionCurve {+ const at = (t: number) =>+ seconds <= 0 || t >= seconds ? 1 : ease(Math.max(0, t) / seconds);+ // A central difference, one step inside the curve at either end.+ const step = Math.min(1e-3, seconds / 100);+ return {+ duration: seconds,+ at,+ velocity: t => {+ if (seconds <= 0 || t >= seconds) {+ return 0;+ }+ const before = Math.max(0, t - step);+ const after = Math.min(seconds, t + step);+ return (at(after) - at(before)) / (after - before);+ },+ };+}++/** The first transition's duration in a computed style, in ms. */+function firstDurationMs(style: CSSStyleDeclaration): number | null {+ return parseMotionRoleValue(+ 'duration',+ style.transitionDuration.split(',')[0] ?? '',+ );+}++/** The first transition's easing in a computed style. */+function firstEasing(style: CSSStyleDeclaration): MotionCurvePoints | null {+ return parseCssEasing(+ style.transitionTimingFunction.split(/,(?![^(]*\))/)[0] ?? '',+ );+}++/** 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) {+ return null;+ }+ return easedProgress(ms / 1000, cubicBezier(points));+}++/**+ * A duration and an easing written in CSS, resolved as a transition resolves+ * them where `element` is. A plain time or easing parses as written. Other+ * text, such as `calc()`, resolves on a hidden probe's transition. The+ * duration is null when it is not a time of zero or more. The easing is null+ * when it is not a cubic Bézier, and a text left out gives null.+ */+export function resolveTiming(+ element: Element,+ {duration, easing}: {readonly duration?: string; readonly easing?: string},+): ResolvedTiming {+ const plainMs =+ duration == null ? null : parseMotionRoleValue('duration', duration);+ const plainPoints = easing == null ? null : parseCssEasing(easing);+ const doc = element.ownerDocument;+ const view = doc.defaultView;+ const needsMs = duration != null && plainMs == null;+ const needsPoints = easing != null && plainPoints == null;+ if (view == null || (!needsMs && !needsPoints)) {+ return {ms: plainMs, points: plainPoints};+ }+ const probe = doc.createElement('span');+ // A computed value needs no layout, so the probe never renders.+ probe.style.setProperty('display', 'none', 'important');+ // The browser refuses a value it cannot read, and the property stays unset.+ const takes = (property: string, value: string) => {+ probe.style.setProperty(property, value, 'important');+ return probe.style.getPropertyValue(property) !== '';+ };+ const hasMs = needsMs && takes('transition-duration', duration);+ const hasPoints = needsPoints && takes('transition-timing-function', easing);+ (doc.body ?? doc.documentElement).append(probe);+ try {+ const style = view.getComputedStyle(probe);+ return {+ ms: hasMs ? firstDurationMs(style) : plainMs,+ points: hasPoints ? firstEasing(style) : plainPoints,+ };+ } finally {+ probe.remove();+ }+}++/**+ * The value of `token` in `style`. With none, it is the default core declares,+ * and the references in that default read their own tokens in `style` too.+ */+function tokenValue(+ style: CSSStyleDeclaration,+ token: DurationVarName | EaseVarName,+): string {+ const own = style.getPropertyValue(token).trim();+ if (own !== '') {+ return own;+ }+ const declared: Record<string, string> = {};+ for (const [name, value] of Object.entries({+ ...durationDefaults,+ ...easeDefaults,+ })) {+ declared[name] = style.getPropertyValue(name).trim() || value;+ }+ return resolveTokenReferences(declared)[token] ?? '';+}++/**+ * The duration and easing of theme tokens where `element` is, resolved as a+ * transition resolves them. A token with no value there reads the default+ * core declares. A token left out gives null.+ */+export function readThemeTokens(+ element: Element,+ {+ duration,+ easing,+ }: {readonly duration?: DurationVarName; readonly easing?: EaseVarName},+): ResolvedTiming {+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ if (style == null) {+ return {ms: null, points: null};+ }+ return resolveTiming(element, {+ duration: duration == null ? undefined : tokenValue(style, duration),+ easing: easing == null ? undefined : tokenValue(style, easing),+ });+}++/**+ * 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.+ */+export function readThemeTiming(+ element: Element,+ tokens?: ThemeTimingTokens,+): MotionCurve | null {+ if (tokens != null) {+ return progressOf(readThemeTokens(element, tokens));+ }+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ return style == null+ ? null+ : progressOf({ms: firstDurationMs(style), points: firstEasing(style)});+}