An open source design system that's fully customizable and agent ready
TypeScript
feat(core): one progress module for the motion foundation (#9755)
Cindy Zhang7585c6e42cb8
diff --git a/.changeset/motion-progress.md b/.changeset/motion-progress.mdnew file mode 100644index 0000000000..d7d9d896ba--- /dev/null+++ b/.changeset/motion-progress.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: one progress module for the motion foundation. `progressCurve` gives a spring's progress from 0 to 1 as a closed-form curve, `mapProgress` maps any curve from another (a companion's dim following a sheet, a clamped range), `mapRange` is the clamped linear map they share, and `presentedProgressVelocity` reads the velocity an interrupted motion continues from. One velocity unit throughout: progress per second. Nothing public changes; no component imports it yet.++@vjeuxdiff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex 05e5a15d62..19ef169b0e 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -38,6 +38,7 @@ roles through `resolveMotion`.| `resolveSnapPoint.ts` | Release policy: the snap point a release lands on (flick, back-out cancel, step limit), on `selectSnapPoint`. Internal. || `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). || `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. |+| `progress.ts` | A spring's progress, one curve mapped from another (companions, clamped ranges), the velocity that continues a motion. || `presentation.ts` | Where each moving element is drawn relative to where the engine hit-tests it, reported by the animator while translate runs; read by the gesture host at touch-down. || `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. || `__tests__/animator.interaction.browser.spec.ts` | Browser proofs on the interaction harness (Chromium and WebKit): busy main thread, end state through a block, no Layout / Paint, seeked curves, a dialog's backdrop. |diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex 9d744f917f..43c5ba9b34 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -89,7 +89,8 @@ import {wrapText,} from './transientCopy';import {isSpring} from './roleValue';-import {solveSpring, toSpring, type SpringDescription} from './spring';+import {progressCurve} from './progress';+import type {SpringDescription} from './spring';import {registerSpringsTable, SETTLE_SPRING} from './uikit/springs';import {reducedMotionCrossFade} from './uikit/timing';@@ -142,11 +143,11 @@ function settleSpring(): SpringDescription {}function springProgress(description: SpringDescription): SpringProgress {- const curve = solveSpring(toSpring(description), {from: 1, to: 0});- const durationMs = Math.max(1, curve.settleTime(0.001) * 1000);+ const curve = progressCurve(description, {epsilon: 0.001});+ const durationMs = Math.max(1, curve.duration * 1000);return {durationMs,- remaining: t => (t >= durationMs ? 0 : curve.value(t / 1000)),+ remaining: t => (t >= durationMs ? 0 : 1 - curve.at(t / 1000)),};}diff --git a/packages/core/src/motion/progress.test.ts b/packages/core/src/motion/progress.test.tsnew file mode 100644index 0000000000..4de3fa57df--- /dev/null+++ b/packages/core/src/motion/progress.test.ts@@ -0,0 +1,172 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import type {MotionProperty} from './animator';+import {+ mapProgress,+ mapRange,+ presentedProgressVelocity,+ progressCurve,+ type ProgressChannel,+} from './progress';+import {solveSpring, toSpring} from './spring';++const SPRING = {response: 0.4, dampingRatio: 0.85};++/** An animator stand-in that presents fixed velocities. */+const presenting = (velocities: Partial<Record<MotionProperty, number>>) => ({+ getVelocity: (property: MotionProperty) => velocities[property] ?? 0,+});++describe('progressCurve', () => {+ it('follows the spring from 0 to 1 and lands exactly on 1 once settled', () => {+ const curve = progressCurve(SPRING, {velocity: 2});+ const spring = solveSpring(toSpring(SPRING), {from: 0, to: 1, velocity: 2});+ expect(curve.at(0)).toBe(0);+ expect(curve.velocity(0)).toBeCloseTo(2, 9);+ for (const t of [0.05, 0.1, 0.2, 0.3]) {+ expect(curve.at(t)).toBeCloseTo(spring.value(t), 12);+ expect(curve.velocity(t)).toBeCloseTo(spring.velocity(t), 12);+ }+ expect(curve.duration).toBeGreaterThan(0.3);+ expect(curve.at(curve.duration)).toBe(1);+ expect(curve.velocity(curve.duration)).toBe(0);+ });+});++describe('mapProgress', () => {+ it('maps the value through f and the velocity by the chain rule', () => {+ const progress = progressCurve(SPRING);+ const f = (p: number) => 100 + 300 * p * p;+ const mapped = mapProgress(progress, f);+ expect(mapped.duration).toBe(progress.duration);+ for (const t of [0.02, 0.1, 0.25]) {+ const p = progress.at(t);+ expect(mapped.at(t)).toBeCloseTo(f(p), 9);+ expect(mapped.velocity(t)).toBeCloseTo(600 * p * progress.velocity(t), 4);+ }+ expect(mapped.at(progress.duration)).toBe(400);+ });+});++describe('mapRange', () => {+ it('maps linearly inside the input range, exactly at its ends', () => {+ const dim = mapRange([600, 200], [0, 0.4]);+ expect(dim(600)).toBe(0);+ expect(dim(200)).toBe(0.4);+ expect(dim(400)).toBeCloseTo(0.2, 12);+ expect(dim(500)).toBeCloseTo(0.1, 12);+ });++ it('holds the output’s ends outside the input range, or runs on when not clamped', () => {+ const dim = mapRange([600, 200], [0, 0.4]);+ expect(dim(800)).toBe(0);+ expect(dim(0)).toBe(0.4);+ const open = mapRange([600, 200], [0, 0.4], {clamp: false});+ expect(open(800)).toBeCloseTo(-0.2, 12);+ expect(open(0)).toBeCloseTo(0.6, 12);+ });++ it('steps at the input when its range is empty', () => {+ const step = mapRange([10, 10], [0, 1]);+ expect(step(9)).toBe(0);+ expect(step(10)).toBe(1);+ expect(step(11)).toBe(1);+ });+});++describe('mapProgress with a driving channel', () => {+ // A sheet's y falling from 700 px to 100 px at a steady 1000 px/s.+ const sheetY = {+ duration: 0.6,+ at: (t: number) => 700 - 1000 * t,+ velocity: () => -1000,+ };++ it('follows any curve, not only a progress: the scrim’s dim along the sheet’s travel', () => {+ const dim = mapProgress(sheetY, mapRange([600, 200], [0, 0.4]));+ expect(dim.duration).toBe(0.6);+ expect(dim.at(0.3)).toBeCloseTo(0.4 * (200 / 400), 12);+ // Inside the range: 0.4 per 400 px at 1000 px/s, rising.+ expect(dim.velocity(0.3)).toBeCloseTo(1, 4);+ });++ it('is still, velocity 0, outside the range on both sides', () => {+ const dim = mapProgress(sheetY, mapRange([600, 200], [0, 0.4]));+ // y = 650 (not yet in range) and y = 150 (past it).+ for (const t of [0.05, 0.55]) {+ expect(Math.abs(dim.velocity(t))).toBe(0);+ }+ expect(dim.at(0.05)).toBe(0);+ expect(dim.at(0.55)).toBe(0.4);+ });+});++describe('presentedProgressVelocity', () => {+ const line = (+ from: Partial<Record<MotionProperty, number>>,+ to: Partial<Record<MotionProperty, number>>,+ weights: Partial<Record<MotionProperty, number>> = {},+ ): ProgressChannel[] =>+ (Object.keys(to) as MotionProperty[]).map(property => ({+ property,+ at: p => from[property]! + (to[property]! - from[property]!) * p,+ weight: weights[property],+ }));++ it('is the presented velocity over the path\u2019s tangent when they are parallel', () => {+ // A path of 200 px on x and 100 px on y, presented at 400 and 200 px/s:+ // two progress units per second.+ const channels = line({x: 0, y: 0}, {x: 200, y: 100});+ expect(+ presentedProgressVelocity(presenting({x: 400, y: 200}), channels),+ ).toBeCloseTo(2, 6);+ });++ it('keeps only the part along the path (v\u00b7t / t\u00b7t)', () => {+ // Moving across the path counts for nothing; against it, negatively.+ const channels = line({x: 0, y: 0}, {x: 100, y: 0});+ expect(+ presentedProgressVelocity(presenting({x: 0, y: 500}), channels),+ ).toBeCloseTo(0, 9);+ expect(+ presentedProgressVelocity(presenting({x: -50, y: 500}), channels),+ ).toBeCloseTo(-0.5, 6);+ });++ it('weighs each channel into one unit, so a scale counts in px', () => {+ // A 300 px wide box growing from scale 0.5 to 1 while moving 50 px: in px+ // the scale moves 150 px against 50 px of travel.+ const channels = line(+ {x: 0, scaleX: 0.5},+ {x: 50, scaleX: 1},+ {scaleX: 300},+ );+ // Presented: 100 px/s on x and 1 scale/s (300 px/s): (100·50 + 300·150) /+ // (50² + 150²) = 2 progress units per second.+ expect(+ presentedProgressVelocity(presenting({x: 100, scaleX: 1}), channels),+ ).toBeCloseTo(2, 6);+ });++ it('is 0 on a path that moves none of its channels, or from rest', () => {+ expect(+ presentedProgressVelocity(presenting({x: 100}), line({x: 10}, {x: 10})),+ ).toBe(0);+ expect(+ presentedProgressVelocity(presenting({}), line({x: 0}, {x: 10})),+ ).toBe(0);+ });++ it('reads every channel at the one time it is given', () => {+ const times: (number | undefined)[] = [];+ const animator = {+ getVelocity: (_property: MotionProperty, time?: number) => {+ times.push(time);+ return 0;+ },+ };+ presentedProgressVelocity(animator, line({x: 0, y: 0}, {x: 1, y: 1}), 1234);+ expect(times).toEqual([1234, 1234]);+ });+});diff --git a/packages/core/src/motion/progress.ts b/packages/core/src/motion/progress.tsnew file mode 100644index 0000000000..8b97de255d--- /dev/null+++ b/packages/core/src/motion/progress.ts@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file progress.ts+ * @input A spring, a normalized progress, an animator's presented velocities+ * @output Exports `progressCurve` (a spring's progress from 0 to 1 as a+ * MotionCurve), `mapProgress` (one curve as a function of another),+ * `mapRange` (the clamped linear map most companions use) and+ * `presentedProgressVelocity` (the progress velocity that continues what+ * an animator shows)+ * @position Shared by the motion building blocks that move several channels+ * along one path and by companion motion (a+ * scrim's dim following a sheet): one velocity unit, one curve mapping and+ * one way to continue an interrupted motion+ *+ * A path is described by a normalized progress: 0 where it starts, 1 where+ * it rests, beyond either end on a spring's overshoot. Its velocity is in+ * progress per second; each channel's own velocity stays in the channel's+ * units per second.+ *+ * An interrupted motion continues from what is on screen: the+ * block reads the presented values and velocities from the animator at one+ * `now` (`get`, `getVelocity`), restarts a path from those values, and starts+ * its progress with the presented velocity projected on the path's tangent+ * at its start, v·t / (t·t), where t = d(values)/dp. Channels are weighted+ * into one unit first (px per unit of scale, say), so a scale and a+ * translation count alike.+ *+ * A companion follows a driving curve through `mapProgress`, most often+ * with `mapRange`: `mapProgress(sheetY, mapRange([closedY, openY], [0, dim]))`+ * dims a scrim as a sheet rises. Played on another animator, it stays in+ * lockstep only when it starts with its driver: pass the driver's start,+ * `scrim.play({opacity}, {at: start})` with `start = await handle.started`+ * (or one shared `at` for both calls); two calls from rest otherwise each+ * start at their own commit.+ *+ * SYNC: When modified, update /packages/core/src/motion/progress.test.ts and+ * /packages/core/src/motion/README.md.+ */++import type {Animator, MotionCurve, MotionProperty} from './animator';+import {+ SETTLING_EPSILON,+ solveSpring,+ toSpring,+ type SpringDescription,+} from './spring';++/** The step of the finite differences taken on a progress. */+const STEP = 1e-4;++/**+ * The progress of `spring` from 0 to 1, starting with `velocity` (progress+ * per second): exactly 1 once it settles within `epsilon`.+ */+export function progressCurve(+ spring: SpringDescription,+ {+ velocity = 0,+ epsilon = SETTLING_EPSILON,+ }: {velocity?: number; epsilon?: number} = {},+): MotionCurve {+ const curve = solveSpring(toSpring(spring), {from: 0, to: 1, velocity});+ const duration = curve.settleTime(epsilon);+ return {+ duration,+ at: t => (t >= duration ? 1 : curve.value(t)),+ velocity: t => (t >= duration ? 0 : curve.velocity(t)),+ };+}++/**+ * The curve of `f(driver(t))`, its velocity by the chain rule: a channel+ * following a path as its progress moves, or a companion following any+ * driving curve (a sheet's `y` mapped onto its scrim's opacity). The driver+ * is any MotionCurve, not only a progress from 0 to 1. A companion played on+ * another animator starts with its driver (`{at: start}`; see the file+ * header).+ */+export function mapProgress(+ driver: MotionCurve,+ f: (value: number) => number,+): MotionCurve {+ return {+ duration: driver.duration,+ at: t => f(driver.at(t)),+ velocity: t => {+ const value = driver.at(t);+ return (+ ((f(value + STEP) - f(value - STEP)) / (2 * STEP)) * driver.velocity(t)+ );+ },+ };+}++/**+ * The linear map from `input` to `output`, held at `output`'s ends outside+ * `input` unless `clamp` is false: what most companions are (a scrim's dim+ * along a sheet's travel, a parallax, a dismissal's fade). Either range may+ * run backward (`[openY, closedY]`).+ */+export function mapRange(+ input: readonly [number, number],+ output: readonly [number, number],+ {clamp = true}: {clamp?: boolean} = {},+): (x: number) => number {+ const [a, b] = input;+ const [c, d] = output;+ return x => {+ let t = a === b ? (x < a ? 0 : 1) : (x - a) / (b - a);+ if (clamp) {+ t = Math.min(1, Math.max(0, t));+ }+ // Exact at both ends.+ return t === 0 ? c : t === 1 ? d : c + (d - c) * t;+ };+}++/**+ * One channel of a path: an animator property and its value at each+ * progress.+ */+export interface ProgressChannel {+ readonly property: MotionProperty;+ /** The property's value at progress `p`. */+ at(p: number): number;+ /**+ * What one unit of the property weighs in the projection, in a unit the+ * channels share (px per unit of scale for a box `weight` px wide). 1 by+ * default.+ */+ readonly weight?: number;+}++/**+ * The progress velocity, per second, that continues what `animator`+ * presents at `now` along a path that starts there: the presented velocity+ * projected on the path's tangent at progress 0, v·t / (t·t). 0 when the+ * path does not move any of its channels.+ */+export function presentedProgressVelocity(+ animator: Pick<Animator, 'getVelocity'>,+ channels: ReadonlyArray<ProgressChannel>,+ now?: number,+): number {+ let along = 0;+ let squared = 0;+ for (const channel of channels) {+ const weight = channel.weight ?? 1;+ const tangent = ((channel.at(STEP) - channel.at(0)) / STEP) * weight;+ along += animator.getVelocity(channel.property, now) * weight * tangent;+ squared += tangent * tangent;+ }+ return squared > 1e-12 ? along / squared : 0;+}