Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

chore(core): a compositor animator for touch presentations (#8055)

Christopher Chedeau30a4a2b356c0
diff --git a/.changeset/uikit-motion-animator.md b/.changeset/uikit-motion-animator.md
new file mode 100644
index 0000000000..83e8f2b68c
--- /dev/null
+++ b/.changeset/uikit-motion-animator.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a compositor animator for touch presentations. It plays UIKit's springs, and scroll coasts (built by a separate coast module, so a surface that never coasts does not carry them; `decay` plays a release's momentum, and under Reduce Motion cross-fades a spring back from past an edge) as Web Animations on translate, rotate, scale and opacity, so they keep running while JavaScript is busy, and reads values and velocities back from the curves for interruption, retargeting and Reduce Motion cross-fades. Not exported from the package entry point; no component uses it yet.
+
+@vjeux
diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md
index 03e0e801d0..8b8fa725a5 100644
--- a/packages/core/src/motion/README.md
+++ b/packages/core/src/motion/README.md
@@ -3,11 +3,11 @@
Internal motion foundation for the touch presentations of core components: the
UIKit constants table (every spring, duration, deceleration rate, rubber-band
constant, curve and gesture threshold a touch presentation uses, each with its
-source) and the spring, decay, rubber-band and projection math UIKit uses.
-Nothing here is exported from the package entry point. Core's motion and
-gesture modules read the table by path; components read touch motion through
-its internal motion roles (`roles.ts`), so each keeps its measured value; no
-shipped component reads the roles yet.
+source), the spring, decay, rubber-band and projection math UIKit uses, and a
+compositor animator that plays it. Nothing here is exported from the package
+entry point. Core's motion and gesture modules read the table by path;
+components read touch motion through its internal motion roles (`roles.ts`),
+so each keeps its measured value; no shipped component reads the roles yet.
## Files
@@ -22,13 +22,78 @@ shipped component reads the roles yet.
| `MEASUREMENTS.md` | The UIKit reference captures each unconfirmed value still needs. |
| `spring.ts` | Closed-form damped spring, every Apple parameterization, settling duration, a spring chasing a moving target. |
| `decay.ts` | UIScrollView's momentum coast. |
+| `coast.ts` | A release's momentum curves for `animator.decay`: the coast, the edge spring, a release past an edge. |
| `rubberBand.ts` | UIScrollView's resistance past an edge, and its inverse. |
| `projection.ts` | Release targets: the rest point nearest the projected coast; paging. |
+| `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). |
+| `animator.ts` | Compositor animator: springs and momentum curves compiled to Web Animations, read back analytically. |
Component-specific values (a sheet's detents, a switch's geometry, a context
menu's timeline) live in a domain file per component, `uikit/<component>.ts`,
under the same rules.
+## Animator
+
+```
+import {createAnimator} from '../motion/animator';
+import {springs} from '../motion/uikit';
+
+const animator = createAnimator(sheet);
+
+// A drag writes one style per frame and never renders:
+animator.set({y: offset});
+
+// The finger lifts: spring to the detent with the release velocity (px/s).
+const handle = animator.animate({y: detent}, {spring: springs.sheetDetent, velocity: {y: 1200}});
+
+// A finger lands mid-flight: where is the sheet right now, how fast?
+const y = animator.get('y', event.timeStamp);
+const v = animator.getVelocity('y', event.timeStamp);
+animator.stop(['y']); // freezes at the value on screen
+
+// A throw on a scroll-like surface, with an edge (coast.ts builds the curves):
+animator.decay(coast(animator, {x: velocityX}, {bounds: {x: {min: -maxScroll, max: 0}}}));
+
+await handle.finished; // true if it ran to the end, false if interrupted
+```
+
+- Drives `x`, `y`, `rotate`, `scaleX`, `scaleY` (`scale` sets both) and
+ `opacity`, through the individual CSS properties `translate`, `rotate`,
+ `scale` and `opacity`. The element's `transform` stays the component's.
+- `get` / `getVelocity` evaluate the curves; the DOM is never read.
+- `animate` always starts from the presentation value with the presentation
+ velocity unless a velocity is handed in, so retargeting is continuous
+ (`handle.retarget(to)` keeps the call's spring).
+- Everything one call starts shares one start time; `{at}` puts several
+ animators on one clock.
+- Reduced Motion (`prefers-reduced-motion: reduce`, `design:reduced-motion`
+ DR2–DR4): on a coarse primary pointer every `animate` cross-fades within
+ 200 ms. An entrance lands and fades in, an exit fades out then moves, any
+ other move dips (fade out, move, fade in), and an opacity change fades, over
+ `timing.reducedMotionCrossFadeMs` capped at 200 ms. On any other pointer every
+ change completes at once. No call keeps travel or a spring or skips the
+ touch cross-fade. A `decay` keeps moving: momentum after a throw is
+ direct movement.
+
+### How it stays on the compositor
+
+Each curve is baked into keyframes, sampled adaptively until linear
+interpolation is within 0.05 px, and played with `easing: linear` and an
+explicit `startTime`. The element's inline style already holds the end values,
+and the keyframes hold the end state for a few seconds past the curve's end;
+the main thread drops the animation as soon as it runs after that end. So the
+frame an animation ends needs no main thread and shows no flicker, even when
+the main thread is blocked as the curve ends (WebKit's compositor otherwise
+falls back to the last value its main thread committed, mid-flight).
+
+Keyframes rather than one `linear()` easing: measured in Chromium, both are
+composited and, for the same samples, equally precise; but WebKit's Core
+Animation path does not accelerate an effect whose easing is `linear()` with
+points (`KeyframeEffect::canBeAccelerated`) unless its newer threaded
+animations are on, so on older iOS Safari a `linear()` spring would run on the
+main thread. Linear segments between keyframes map directly onto Core
+Animation keyframe animations.
+
## Math
`spring.ts` solves m·x″ + c·x′ + k·x = 0 in closed form in all three regimes:
diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.ts
new file mode 100644
index 0000000000..eaf35560ee
--- /dev/null
+++ b/packages/core/src/motion/animator.test.ts
@@ -0,0 +1,1055 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file animator.test.ts
+ * @input vitest (jsdom), the animator, a recording stand-in for
+ * Element.animate (jsdom runs no animations)
+ * @output Checks what the animator hands the browser: keyframes that follow
+ * the analytic curves, the clock, the inline end state; and what it reads
+ * back: presentation values and velocities, retarget continuity, stop,
+ * completion, Reduced Motion substitutions, momentum curves (a coast with
+ * edges), late attach
+ * @position Testing for /packages/core/src/motion/animator.ts (jsdom: the
+ * compositor itself is proven in the browser)
+ */
+
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {createAnimator, END_HOLD_MS, type AnimatorOptions} from './animator';
+import {cubicBezier} from './bezier';
+import {coast} from './coast';
+import {solveDecay} from './decay';
+import {solveSpring, toSpring} from './spring';
+import {scroll} from './uikit/scroll';
+import {springs} from './uikit/springs';
+import {timing} from './uikit/timing';
+
+interface Recorded {
+ element: Element;
+ keyframes: Keyframe[];
+ options: KeyframeAnimationOptions;
+ startTime: number | null;
+ cancelled: boolean;
+ /** A sampler holding it (the interaction harness pauses to seek). */
+ paused: boolean;
+ readonly playState: 'idle' | 'paused' | 'running';
+ cancel(): void;
+}
+
+let clock = 1000;
+let recorded: Recorded[] = [];
+/**
+ * What the page's stylesheet sets, by property. Computed style reads it
+ * under the inline value (jsdom keeps stale computed values for these
+ * properties, so the page is modeled here).
+ */
+let stylesheet: Record<string, string> = {};
+
+beforeEach(() => {
+ clock = 1000;
+ recorded = [];
+ stylesheet = {};
+ vi.spyOn(window, 'getComputedStyle').mockImplementation(
+ element =>
+ ({
+ getPropertyValue: (property: string) =>
+ (element as HTMLElement).style.getPropertyValue(property) ||
+ (stylesheet[property] ?? ''),
+ }) as unknown as CSSStyleDeclaration,
+ );
+ vi.useFakeTimers();
+ HTMLElement.prototype.animate = function (keyframes, options) {
+ const animation: Recorded = {
+ element: this,
+ keyframes: keyframes as Keyframe[],
+ options: options as KeyframeAnimationOptions,
+ startTime: null,
+ cancelled: false,
+ paused: false,
+ get playState() {
+ return this.cancelled ? 'idle' : this.paused ? 'paused' : 'running';
+ },
+ cancel() {
+ this.cancelled = true;
+ },
+ };
+ recorded.push(animation);
+ return animation as unknown as Animation;
+ };
+});
+
+afterEach(() => {
+ Reflect.deleteProperty(HTMLElement.prototype, 'animate');
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+function setup(options: AnimatorOptions = {}) {
+ const element = document.createElement('div');
+ const animator = createAnimator(element, {
+ now: () => clock,
+ prefersReducedMotion: () => false,
+ ...options,
+ });
+ return {element, animator};
+}
+
+/** Advances the injected clock and the timers together. */
+async function advance(ms: number) {
+ clock += ms;
+ await vi.advanceTimersByTimeAsync(ms);
+}
+
+function live(channel: string): Recorded[] {
+ return recorded.filter(
+ a => !a.cancelled && channel in (a.keyframes[0] ?? {}),
+ );
+}
+
+function parse(value: string | number | null | undefined): number[] {
+ return String(value)
+ .split(/\s+/)
+ .map(part => Number.parseFloat(part));
+}
+
+/** What the browser would show: the keyframes interpolated linearly at `time`. */
+function sampleAt(
+ animation: Recorded,
+ channel: string,
+ time: number,
+): number[] {
+ const duration = Number(animation.options.duration);
+ const offset = Math.min(
+ 1,
+ Math.max(0, (time - (animation.startTime ?? 0)) / duration),
+ );
+ const frames = animation.keyframes;
+ for (let i = 0; i + 1 < frames.length; i++) {
+ const a = frames[i];
+ const b = frames[i + 1];
+ const oa = Number(a.offset);
+ const ob = Number(b.offset);
+ if (
+ offset >= oa &&
+ offset <= ob &&
+ !(
+ offset === ob &&
+ i + 2 < frames.length &&
+ Number(frames[i + 2].offset) === ob
+ )
+ ) {
+ const va = parse(a[channel]);
+ const vb = parse(b[channel]);
+ const f = ob === oa ? 1 : (offset - oa) / (ob - oa);
+ return va.map((v, k) => v + (vb[k] - v) * f);
+ }
+ }
+ return parse(frames[frames.length - 1][channel]);
+}
+
+describe('animate: keyframes on the compositor', () => {
+ it('bakes the spring into keyframes within a twentieth of a pixel of the curve', () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ expect(animation).toBeDefined();
+ expect(animation.options).toMatchObject({
+ fill: 'both',
+ easing: 'linear',
+ });
+ expect(animation.startTime).toBe(1000);
+ const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
+ // The curve, then the end state held (END_HOLD_MS).
+ const duration = Number(animation.options.duration) - END_HOLD_MS;
+ expect(duration).toBeCloseTo(curve.settleTime(0.05) * 1000, 6);
+ for (let t = 0; t <= duration; t += 0.5) {
+ const [x, y] = sampleAt(animation, 'translate', 1000 + t);
+ expect(Math.abs(x - curve.value(t / 1000))).toBeLessThan(0.06);
+ expect(y).toBe(0);
+ expect(animator.get('x', 1000 + t)).toBeCloseTo(curve.value(t / 1000), 9);
+ }
+ // Then the end state, held through a main-thread block.
+ expect(
+ sampleAt(animation, 'translate', 1000 + duration + END_HOLD_MS / 2),
+ ).toEqual([300, 0]);
+ });
+
+ it('keeps the keyframe count modest (adaptive sampling)', () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ expect(live('translate')[0].keyframes.length).toBeLessThan(200);
+ });
+
+ it('clears an identity transform at rest, so a fixed child stays fixed', async () => {
+ const {animator, element} = setup();
+ animator.animate(
+ {x: 100, scale: 0.9, rotate: 10},
+ {spring: springs.quickChange},
+ );
+ expect(element.style.translate).toBe('100px 0px');
+ await advance(100);
+ animator.animate(
+ {x: 0, scale: 1, rotate: 0},
+ {spring: springs.quickChange},
+ );
+ // While the motion back runs, the end is never written 0px 0px: none, or
+ // nothing where the stylesheet agrees.
+ expect(live('translate')).toHaveLength(1);
+ for (const channel of ['translate', 'scale', 'rotate'] as const) {
+ expect(['', 'none']).toContain(element.style[channel]);
+ }
+ await advance(5000);
+ // At rest the identity leaves the element: translate 0px 0px would make
+ // the element a fixed child's containing block, and scale 1 stops a
+ // finger scrolling inside it on Mobile Safari.
+ expect(element.style.translate).toBe('');
+ expect(element.style.scale).toBe('');
+ expect(element.style.rotate).toBe('');
+ // The keyframes stay numeric, so the curve still interpolates.
+ animator.animate({x: 50}, {spring: springs.quickChange});
+ expect(live('translate')[0].keyframes[0].translate).toBe('0px 0px');
+ });
+
+ it('clears opacity back at 1, and an identity set at rest, and keeps any other value', async () => {
+ const {animator, element} = setup();
+ animator.set({opacity: 0});
+ animator.animate({opacity: 1}, {spring: springs.quickChange});
+ await advance(5000);
+ expect(element.style.opacity).toBe('');
+ animator.set({x: 12});
+ animator.set({x: 0});
+ expect(element.style.translate).toBe('');
+ animator.animate({opacity: 0.5, x: 20}, {spring: springs.quickChange});
+ await advance(5000);
+ expect(element.style.opacity).toBe('0.5');
+ expect(element.style.translate).toBe('20px 0px');
+ });
+
+ it('keeps an identity inline where the stylesheet would move the element', async () => {
+ const {animator, element} = setup();
+ stylesheet.scale = '0.5';
+ animator.animate({scale: 0.9}, {spring: springs.quickChange});
+ animator.animate({scale: 1}, {spring: springs.quickChange});
+ await advance(5000);
+ expect(element.style.scale).toBe('none');
+ });
+
+ it('writes the end values inline up front, so the last frame needs no main thread', () => {
+ const {animator, element} = setup();
+ animator.animate(
+ {x: 120, y: -40, scale: 1.1, rotate: 12, opacity: 0.25},
+ {spring: springs.quickChange},
+ );
+ expect(element.style.translate).toBe('120px -40px');
+ expect(element.style.scale).toBe('1.1 1.1');
+ expect(element.style.rotate).toBe('12deg');
+ expect(element.style.opacity).toBe('0.25');
+ for (const channel of ['translate', 'scale', 'rotate', 'opacity']) {
+ const [animation] = live(channel);
+ expect(animation.keyframes[animation.keyframes.length - 1][channel]).toBe(
+ (element.style as unknown as Record<string, string>)[channel],
+ );
+ }
+ });
+
+ it('keeps the end state in effect until the main thread drops the finished animation', async () => {
+ const {animator, element} = setup();
+ animator.animate({x: 120}, {spring: springs.quickChange});
+ const [animation] = live('translate');
+ expect(animation.options.fill).toBe('both');
+ // The animation outlasts its curve by END_HOLD_MS; the main thread drops
+ // it as soon as it runs after the curve's end.
+ const duration = Number(animation.options.duration) - END_HOLD_MS;
+ await advance(duration - 1);
+ expect(animation.cancelled).toBe(false);
+ await advance(2);
+ expect(animation.cancelled).toBe(true);
+ expect(element.style.translate).toBe(
+ animation.keyframes[animation.keyframes.length - 1].translate,
+ );
+ });
+
+ it('never retires an animation a sampler has paused', async () => {
+ const {animator} = setup();
+ animator.animate({x: 120}, {spring: springs.quickChange});
+ const [animation] = live('translate');
+ const duration = Number(animation.options.duration) - END_HOLD_MS;
+ animation.paused = true;
+ await advance(duration + 500);
+ expect(animation.cancelled).toBe(false);
+ // Resumed: it leaves once the main thread looks again.
+ animation.paused = false;
+ await advance(150);
+ expect(animation.cancelled).toBe(true);
+ });
+
+ it('puts everything one call starts on one clock', () => {
+ const {animator} = setup();
+ animator.animate({x: 100, opacity: 0.5}, {spring: springs.settle});
+ const starts = recorded.map(a => a.startTime);
+ expect(starts).toEqual([1000, 1000]);
+ animator.animate({rotate: 90}, {spring: springs.settle}, {at: 1234.5});
+ expect(live('rotate')[0].startTime).toBe(1234.5);
+ });
+
+ it('expands scale onto both axes and reads it back', () => {
+ const {animator} = setup();
+ animator.animate({scale: 0.5}, {spring: springs.settle});
+ clock += 5000;
+ expect(animator.get('scale')).toBe(0.5);
+ expect(animator.get('scaleY')).toBe(0.5);
+ });
+
+ it('does nothing for a value already at its target and at rest', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({x: 0}, {spring: springs.settle});
+ expect(live('translate')).toHaveLength(0);
+ await expect(handle.finished).resolves.toBe(true);
+ });
+});
+
+describe('presentation values, retargeting, velocity (M2, M3)', () => {
+ it('hands a release velocity to the spring', () => {
+ const {animator} = setup();
+ animator.set({y: 200});
+ animator.animate(
+ {y: 0},
+ {spring: springs.sheetDetent, velocity: {y: 1500}},
+ );
+ expect(animator.get('y')).toBe(200);
+ expect(animator.getVelocity('y')).toBeCloseTo(1500, 6);
+ });
+
+ it('a retarget starts from the value and the velocity on screen', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.emphasis, velocity: {x: 800}});
+ const first = live('translate')[0];
+ await advance(120);
+ const value = animator.get('x');
+ const velocity = animator.getVelocity('x');
+ animator.animate({x: -100}, {spring: springs.emphasis});
+ expect(first.cancelled).toBe(true);
+ const second = live('translate')[0];
+ expect(second.startTime).toBe(clock);
+ expect(animator.get('x', clock)).toBeCloseTo(value, 9);
+ expect(animator.getVelocity('x', clock)).toBeCloseTo(velocity, 6);
+ expect(sampleAt(second, 'translate', clock)[0]).toBeCloseTo(value, 2);
+ // And it really goes to the new target with that start.
+ const curve = solveSpring(toSpring(springs.emphasis), {
+ from: value,
+ to: -100,
+ velocity,
+ });
+ expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 9);
+ });
+
+ it('velocity is continuous across a retarget (property sweep)', async () => {
+ for (const spring of [
+ springs.settle,
+ springs.quickChange,
+ springs.switchThumbMove,
+ springs.navigationPush,
+ ]) {
+ const {animator} = setup();
+ animator.animate({x: 200}, {spring});
+ for (const step of [16, 50, 120]) {
+ await advance(step);
+ const before = animator.getVelocity('x', clock);
+ const value = animator.get('x', clock);
+ animator.animate({x: value > 100 ? 0 : 200}, {spring});
+ expect(animator.getVelocity('x', clock)).toBeCloseTo(before, 6);
+ expect(animator.get('x', clock)).toBeCloseTo(value, 9);
+ }
+ }
+ });
+
+ it('a value that keeps moving through a rebuild stays on its curve', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300, y: 200}, {spring: springs.settle});
+ const yCurve = solveSpring(toSpring(springs.settle), {from: 0, to: 200});
+ await advance(100);
+ animator.animate({x: 0}, {spring: springs.settle});
+ const [animation] = live('translate');
+ for (let t = clock; t < clock + 400; t += 7) {
+ expect(sampleAt(animation, 'translate', t)[1]).toBeCloseTo(
+ yCurve.value((t - 1000) / 1000),
+ 1,
+ );
+ expect(animator.get('y', t)).toBeCloseTo(
+ yCurve.value((t - 1000) / 1000),
+ 9,
+ );
+ }
+ });
+
+ it('stop() freezes at the presentation value', async () => {
+ const {animator, element} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ await advance(80);
+ const value = animator.get('x');
+ animator.stop();
+ expect(live('translate')).toHaveLength(0);
+ expect(Number.parseFloat(element.style.translate)).toBeCloseTo(value, 3);
+ await advance(500);
+ expect(animator.get('x')).toBe(value);
+ expect(animator.getVelocity('x')).toBe(0);
+ });
+
+ it('a handle reads, retargets and stops its own properties', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({x: 100}, {spring: springs.settle});
+ await advance(50);
+ expect(handle.value('x')).toBe(animator.get('x'));
+ expect(handle.velocity('x')).toBe(animator.getVelocity('x'));
+ const next = handle.retarget({x: 50});
+ await expect(handle.finished).resolves.toBe(false);
+ next.stop();
+ await expect(next.finished).resolves.toBe(false);
+ });
+});
+
+describe('set: direct manipulation (M4)', () => {
+ it('writes one inline style per move and starts no animation', () => {
+ const {animator, element} = setup();
+ for (let x = 0; x < 30; x += 3) {
+ animator.set({x});
+ expect(element.style.translate).toBe(x === 0 ? '' : `${x}px 0px`);
+ }
+ expect(recorded).toHaveLength(0);
+ });
+
+ it('a drag on translate leaves a running scale alone', () => {
+ const {animator} = setup();
+ animator.animate({scale: 0.95}, {spring: springs.settle});
+ const scaleAnimation = live('scale')[0];
+ animator.set({x: 12});
+ animator.set({x: 20});
+ expect(scaleAnimation.cancelled).toBe(false);
+ expect(live('translate')).toHaveLength(0);
+ });
+});
+
+describe('finished', () => {
+ it('resolves true when the curve ends untouched', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({x: 40}, {spring: springs.quickChange});
+ let result: boolean | undefined;
+ void handle.finished.then(value => {
+ result = value;
+ });
+ await advance(100);
+ expect(result).toBeUndefined();
+ await advance(5000);
+ expect(result).toBe(true);
+ });
+
+ it('resolves false as soon as a property is retargeted, set or stopped', async () => {
+ const {animator} = setup();
+ const a = animator.animate({x: 40}, {spring: springs.quickChange});
+ animator.animate({x: 80}, {spring: springs.quickChange});
+ await expect(a.finished).resolves.toBe(false);
+ const b = animator.animate({y: 40}, {spring: springs.quickChange});
+ animator.set({y: 3});
+ await expect(b.finished).resolves.toBe(false);
+ const c = animator.animate({rotate: 40}, {spring: springs.quickChange});
+ animator.stop(['rotate']);
+ await expect(c.finished).resolves.toBe(false);
+ });
+
+ it('dispose cancels and settles everything', async () => {
+ const {animator} = setup();
+ const handle = animator.animate(
+ {x: 40, opacity: 0},
+ {spring: springs.quickChange},
+ );
+ animator.dispose();
+ await expect(handle.finished).resolves.toBe(false);
+ expect(recorded.every(a => a.cancelled)).toBe(true);
+ expect(animator.element).toBeNull();
+ });
+});
+
+describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or less', () => {
+ const reduced = () =>
+ setup({prefersReducedMotion: () => true, isCoarsePointer: () => true});
+ const fade = Math.min(timing.reducedMotionCrossFadeMs, 200);
+ const ease = cubicBezier(timing.curves.move);
+
+ it('a move during a running fade keeps that fade\u2019s target', async () => {
+ const {animator} = reduced();
+ animator.animate({opacity: 0}, {spring: springs.settle});
+ await advance(fade / 2);
+ expect(animator.get('opacity')).toBeGreaterThan(0.1);
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade + 100);
+ expect(animator.get('opacity')).toBeCloseTo(0, 6);
+ expect(animator.get('x')).toBe(100);
+
+ const entrance = reduced().animator;
+ entrance.set({opacity: 0});
+ entrance.animate({opacity: 1}, {spring: springs.settle});
+ await advance(fade / 2);
+ entrance.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade + 100);
+ expect(entrance.get('opacity')).toBeCloseTo(1, 6);
+ });
+
+ it("a move dips from and back to the stylesheet's opacity, then hands it back", async () => {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0.6'};
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ expect(animator.get('opacity', 1000)).toBeCloseTo(0.6, 9);
+ expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(0, 9);
+ expect(animator.get('opacity', 1000 + fade)).toBeCloseTo(0.6, 9);
+ const [opacity] = live('opacity');
+ expect(opacity.keyframes[0].opacity).toBe('0.6');
+ expect(opacity.keyframes[opacity.keyframes.length - 1].opacity).toBe('0.6');
+ await advance(fade + END_HOLD_MS + 1);
+ // No inline opacity is left behind: the stylesheet owns it again.
+ expect(element.style.opacity).toBe('');
+ expect(animator.get('opacity')).toBe(1);
+ });
+
+ it('a move that overlaps a running fade lands only once the element is invisible', async () => {
+ const {animator} = reduced();
+ animator.set({opacity: 0});
+ animator.animate({opacity: 1}, {spring: springs.navigationPush});
+ await advance(fade / 3);
+ const start = clock;
+ expect(animator.get('opacity')).toBeGreaterThan(0.1);
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ // Still where it was while it shows; it moves at the bottom of the dip.
+ expect(animator.get('x', start + fade / 2 - 1)).toBe(0);
+ expect(animator.get('opacity', start + fade / 2)).toBeCloseTo(0, 9);
+ expect(animator.get('x', start + fade / 2)).toBe(100);
+ expect(animator.get('opacity', start + fade)).toBeCloseTo(1, 9);
+ });
+
+ it("a second call's fade re-times the first call's pending jump to its own invisible moment", async () => {
+ const {animator} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade / 4);
+ const start = clock;
+ // x still waits for the first dip's bottom; y starts a new dip now.
+ animator.animate({y: 50}, {spring: springs.navigationPush});
+ for (let t = start; t <= start + fade; t += 5) {
+ if (animator.get('x', t) !== 0) {
+ expect(animator.get('opacity', t)).toBeCloseTo(0, 6);
+ break;
+ }
+ }
+ expect(animator.get('x', start + fade / 2)).toBe(100);
+ expect(animator.get('y', start + fade / 2)).toBe(50);
+ });
+
+ it('a stop during a dip finishes the fade instead of freezing it', async () => {
+ const {animator} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade / 2 - 5);
+ expect(animator.get('opacity')).toBeLessThan(0.1);
+ animator.stop();
+ expect(animator.get('opacity')).toBe(1);
+ });
+
+ it("a stop during a dip on the stylesheet's opacity hands it back", async () => {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0.6'};
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade / 4);
+ animator.stop();
+ expect(element.style.opacity).toBe('');
+ expect(animator.get('opacity')).toBe(1);
+ });
+
+ it('a call that does not own opacity keeps a running borrowed dip handing it back', async () => {
+ // One that moves nothing.
+ const still = reduced();
+ stylesheet = {opacity: '0.6'};
+ still.animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade / 4);
+ still.animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade + END_HOLD_MS + 1);
+ expect(still.element.style.opacity).toBe('');
+
+ // One that springs after Reduce Motion turned off mid-dip.
+ let reduce = true;
+ const changed = setup({
+ prefersReducedMotion: () => reduce,
+ isCoarsePointer: () => true,
+ });
+ changed.animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade / 4);
+ reduce = false;
+ changed.animator.animate({y: 20}, {spring: springs.navigationPush});
+ await advance(2000);
+ expect(changed.element.style.opacity).toBe('');
+ });
+
+ it('a borrowed dip that ends while detached hands the opacity back on the next attach', async () => {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0.6'};
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(25);
+ animator.attach(null);
+ await advance(fade + END_HOLD_MS + 1);
+ animator.attach(element);
+ expect(element.style.opacity).toBe('');
+ expect(animator.get('opacity')).toBe(1);
+ });
+
+ it('an unmount or dispose during a borrowed dip hands the opacity back to that element', async () => {
+ for (const end of ['detach', 'dispose'] as const) {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0.6'};
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(25);
+ if (end === 'detach') {
+ animator.attach(null);
+ } else {
+ animator.dispose();
+ }
+ expect(element.style.opacity).toBe('');
+ }
+ });
+
+ it('a new element taking over mid-dip keeps the dip, so the move lands while invisible', async () => {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0.6'};
+ animator.animate({x: 240}, {spring: springs.navigationPush});
+ await advance(25);
+ const next = document.createElement('div');
+ document.body.append(next);
+ animator.attach(next);
+ // The outgoing element follows its stylesheet again.
+ expect(element.style.opacity).toBe('');
+ const start = clock - 25;
+ for (let t = start; t <= start + fade; t += 2) {
+ if (animator.get('x', t) !== 0) {
+ expect(animator.get('opacity', t)).toBeCloseTo(0, 6);
+ break;
+ }
+ }
+ await advance(fade + END_HOLD_MS + 1);
+ expect(next.style.opacity).toBe('');
+ next.remove();
+ });
+
+ it('an identity held over a differing stylesheet follows a node replacement', () => {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0'};
+ animator.set({opacity: 1});
+ expect(element.style.opacity).toBe('1');
+ animator.attach(null);
+ const next = document.createElement('div');
+ document.body.append(next);
+ animator.attach(next);
+ expect(next.style.opacity).toBe('1');
+ expect(animator.get('opacity')).toBe(1);
+ next.remove();
+ });
+
+ it('a running dip survives any re-attach, so the move never passes in view', async () => {
+ const halfway = (
+ animator: ReturnType<typeof createAnimator>,
+ start: number,
+ ) => {
+ for (let t = start; t <= start + fade; t += 2) {
+ if (animator.get('x', t) !== 0) {
+ return animator.get('opacity', t);
+ }
+ }
+ return Number.NaN;
+ };
+ // Detached and re-attached to the same element, no stylesheet opacity.
+ const same = reduced();
+ same.animator.animate({x: 240}, {spring: springs.navigationPush});
+ const start = clock;
+ await advance(25);
+ same.animator.attach(null);
+ same.animator.attach(same.element);
+ expect(halfway(same.animator, start)).toBeCloseTo(0, 6);
+ // Handed to another element, no stylesheet opacity.
+ const other = reduced();
+ other.animator.animate({x: 240}, {spring: springs.navigationPush});
+ const start2 = clock;
+ await advance(25);
+ const next = document.createElement('div');
+ document.body.append(next);
+ other.animator.attach(next);
+ expect(halfway(other.animator, start2)).toBeCloseTo(0, 6);
+ await advance(fade + END_HOLD_MS + 1);
+ expect(next.style.opacity).toBe('');
+ next.remove();
+ });
+
+ it('an opacity the animator wrote is owned: a dip returns to it, never to a hiding stylesheet', async () => {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0'};
+ animator.set({opacity: 1});
+ expect(element.style.opacity).toBe('1');
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade + END_HOLD_MS + 1);
+ expect(element.style.opacity).toBe('1');
+ });
+
+ it('borrows nothing from a hidden element, so a later move still dips once it shows', async () => {
+ const {animator} = reduced();
+ stylesheet = {opacity: '0'};
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ // Invisible: the move lands at once, with no dip.
+ expect(animator.get('x')).toBe(100);
+ await advance(fade + END_HOLD_MS + 1);
+ stylesheet = {opacity: '1'};
+ animator.animate({x: 200}, {spring: springs.navigationPush});
+ const start = clock;
+ for (let t = start; t <= start + fade; t += 2) {
+ if (animator.get('x', t) !== 100) {
+ expect(animator.get('opacity', t)).toBeCloseTo(0, 6);
+ break;
+ }
+ }
+ });
+
+ it("a stop that finishes a dip's fade lands the move with it, never later in view", async () => {
+ const {animator} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade / 4);
+ animator.stop(['opacity']);
+ expect(animator.get('x')).toBe(100);
+ expect(animator.get('opacity')).toBe(1);
+ });
+
+ it('a release past an edge springs back as a cross-fade, not momentum (DR2)', () => {
+ const {animator} = reduced();
+ animator.set({x: -80});
+ const start = clock;
+ animator.decay(
+ coast(animator, {x: 0}, {bounds: {x: {min: 0, max: 100}}, at: start}),
+ {at: start},
+ );
+ for (let t = start; t <= start + fade; t += 2) {
+ if (animator.get('x', t) !== -80) {
+ expect(animator.get('opacity', t)).toBeCloseTo(0, 6);
+ break;
+ }
+ }
+ expect(animator.get('x', start + fade)).toBe(0);
+ });
+
+ it('a release with one axis past an edge is one handle: stop() stops the cross-fade too', async () => {
+ const {animator} = reduced();
+ animator.set({x: -80, y: 0});
+ const start = clock;
+ const handle = animator.decay(
+ coast(
+ animator,
+ {x: 0, y: 500},
+ {bounds: {x: {min: 0, max: 100}}, at: start},
+ ),
+ {at: start},
+ );
+ expect(handle.properties).toEqual(expect.arrayContaining(['x', 'y']));
+ await advance(fade / 4);
+ handle.stop();
+ await advance(fade + END_HOLD_MS + 1);
+ // x never lands at its edge after the stop.
+ expect(animator.get('x')).toBe(-80);
+ });
+
+ it('a second move during a borrowed dip copies no stylesheet opacity inline', async () => {
+ const {animator, element} = reduced();
+ stylesheet = {opacity: '0.6'};
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ await advance(fade / 4);
+ animator.animate({y: 50}, {spring: springs.navigationPush});
+ expect(animator.get('opacity', clock + fade)).toBeCloseTo(0.6, 9);
+ await advance(fade + END_HOLD_MS + 1);
+ expect(element.style.opacity).toBe('');
+ expect(animator.get('opacity')).toBe(1);
+ });
+
+ it('a move dips: fades out, jumps at the midpoint, fades back in', () => {
+ const {animator, element} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ expect(animator.get('x', 1000 + fade / 2 - 1)).toBe(0);
+ expect(animator.get('x', 1000 + fade / 2)).toBe(100);
+ expect(animator.get('opacity', 1000 + fade / 4)).toBeCloseTo(
+ 1 - ease(0.5),
+ 9,
+ );
+ expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(0, 9);
+ expect(animator.get('opacity', 1000 + fade)).toBe(1);
+ // The move is a hold that ends in a jump: two keyframes at its last
+ // offset, the value before and after. The fade runs on the same clock.
+ const [translate] = live('translate');
+ const [opacity] = live('opacity');
+ expect(translate.startTime).toBe(opacity.startTime);
+ expect(Number(translate.options.duration)).toBeCloseTo(
+ fade / 2 + END_HOLD_MS,
+ 6,
+ );
+ const jump = fade / 2 / (fade / 2 + END_HOLD_MS);
+ const atJump = translate.keyframes.filter(
+ k => Math.abs(Number(k.offset) - jump) < 1e-12,
+ );
+ expect(atJump.map(k => k.translate)).toEqual(['0px 0px', '100px 0px']);
+ expect(translate.keyframes[translate.keyframes.length - 1]).toMatchObject({
+ offset: 1,
+ translate: '100px 0px',
+ });
+ expect(sampleAt(translate, 'translate', 1000 + fade / 2 - 2)[0]).toBe(0);
+ expect(element.style.translate).toBe('100px 0px');
+ expect(element.style.opacity).toBe('');
+ });
+
+ it('an entrance lands in place and fades in', () => {
+ const {animator, element} = reduced();
+ animator.set({y: 400, opacity: 0});
+ animator.animate({y: 0, opacity: 1}, {spring: springs.sheetPresent});
+ expect(animator.get('y')).toBe(0);
+ expect(live('translate')).toHaveLength(0);
+ expect(element.style.translate).toBe('');
+ expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(ease(0.5), 9);
+ expect(Number(live('opacity')[0].options.duration)).toBeCloseTo(
+ fade + END_HOLD_MS,
+ 6,
+ );
+ });
+
+ it('an exit fades out in place, then moves', () => {
+ const {animator} = reduced();
+ animator.animate({y: 400, opacity: 0}, {spring: springs.sheetDismiss});
+ expect(animator.get('y', 1000 + fade - 1)).toBe(0);
+ expect(animator.get('y', 1000 + fade)).toBe(400);
+ const [translate] = live('translate');
+ expect(sampleAt(translate, 'translate', 1000 + fade - 1)[1]).toBe(0);
+ expect(translate.keyframes[translate.keyframes.length - 1].translate).toBe(
+ '0px 400px',
+ );
+ });
+
+ it('an opacity-only change fades within 200 ms, with no spring', () => {
+ const {animator} = reduced();
+ animator.set({opacity: 0});
+ animator.animate({opacity: 1}, {spring: springs.settle});
+ const [opacity] = live('opacity');
+ expect(Number(opacity.options.duration)).toBeLessThanOrEqual(
+ 200 + END_HOLD_MS,
+ );
+ expect(animator.get('opacity', 1000 + 200)).toBe(1);
+ });
+
+ it('a move finishes within 200 ms', () => {
+ const {animator} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ expect(animator.get('x', 1000 + 200)).toBe(100);
+ expect(animator.get('opacity', 1000 + 200)).toBe(1);
+ });
+});
+
+describe('Reduced Motion on a fine pointer (DR3): every change at once', () => {
+ const reduced = () =>
+ setup({prefersReducedMotion: () => true, isCoarsePointer: () => false});
+
+ it('a move and an opacity change complete in the call, with nothing animated', () => {
+ const {animator} = reduced();
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ animator.animate({opacity: 0}, {spring: springs.settle});
+ expect(animator.get('x')).toBe(100);
+ expect(animator.get('opacity')).toBe(0);
+ expect(recorded).toHaveLength(0);
+ });
+
+ it('a move leaves an opacity it does not name to finish what it was doing', async () => {
+ let isCoarse = true;
+ const {animator} = setup({
+ prefersReducedMotion: () => true,
+ isCoarsePointer: () => isCoarse,
+ });
+ animator.animate({opacity: 0}, {spring: springs.settle});
+ await advance(60);
+ const midFade = animator.get('opacity');
+ expect(midFade).toBeGreaterThan(0);
+ isCoarse = false;
+ animator.animate({x: 100}, {spring: springs.navigationPush});
+ expect(animator.get('x')).toBe(100);
+ // The fade is neither overwritten nor restored: it runs to its target.
+ expect(animator.get('opacity')).toBeCloseTo(midFade, 6);
+ await advance(300);
+ expect(animator.get('opacity')).toBeCloseTo(0, 6);
+ });
+});
+
+describe('decay: momentum curves (a coast)', () => {
+ it('plays a coast and comes to rest where it projects', () => {
+ const {animator} = setup();
+ animator.decay(coast(animator, {y: -2400}));
+ const glide = solveDecay({from: 0, velocity: -2400});
+ for (const t of [0, 16, 100, 400, 1200]) {
+ expect(animator.get('y', 1000 + t)).toBeCloseTo(glide.value(t / 1000), 9);
+ }
+ const [animation] = live('translate');
+ for (let t = 0; t < 1500; t += 3) {
+ expect(
+ Math.abs(
+ sampleAt(animation, 'translate', 1000 + t)[1] - glide.value(t / 1000),
+ ),
+ ).toBeLessThan(0.11);
+ }
+ expect(animator.get('y', 1e7)).toBeCloseTo(glide.rest, 9);
+ });
+
+ it('a coast that reaches an edge hands its velocity to the edge spring', () => {
+ const {animator} = setup();
+ animator.set({y: -100});
+ animator.decay(
+ coast(animator, {y: 3000}, {bounds: {y: {min: -2000, max: 0}}}),
+ );
+ const glide = solveDecay({from: -100, velocity: 3000});
+ const contact = 1000 + (glide.timeToReach(0) as number) * 1000;
+ expect(animator.get('y', contact)).toBeCloseTo(0, 6);
+ expect(animator.getVelocity('y', contact - 1e-6)).toBeCloseTo(
+ animator.getVelocity('y', contact + 1e-6),
+ 2,
+ );
+ // It overshoots past the edge, then comes back to it.
+ expect(animator.get('y', contact + 60)).toBeGreaterThan(0);
+ expect(animator.get('y', 1e7)).toBe(0);
+ });
+
+ it('a release past an edge springs straight back with the release velocity', () => {
+ const {animator} = setup();
+ animator.set({x: 60});
+ animator.decay(
+ coast(animator, {x: 400}, {bounds: {x: {min: -500, max: 0}}}),
+ );
+ expect(animator.getVelocity('x')).toBeCloseTo(400, 6);
+ const curve = solveSpring(toSpring(scroll.bounce), {
+ from: 60,
+ to: 0,
+ velocity: 400,
+ });
+ expect(animator.get('x', 1100)).toBeCloseTo(curve.value(0.1), 9);
+ });
+
+ it('a coast continues a running spring from its presentation value', () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ clock += 80;
+ const from = animator.get('x');
+ animator.decay(coast(animator, {x: 900}));
+ expect(animator.get('x', clock)).toBeCloseTo(from, 9);
+ expect(animator.getVelocity('x', clock)).toBeCloseTo(900, 6);
+ });
+
+ it('plays any curve as given, and a zero-length one rests at its value', () => {
+ const {animator, element} = setup();
+ const linear = {
+ duration: 0.5,
+ at: (t: number) => 200 * t,
+ velocity: () => 200,
+ };
+ animator.decay({
+ x: linear,
+ opacity: {duration: 0, at: () => 0.5, velocity: () => 0},
+ });
+ expect(animator.get('x', 1250)).toBeCloseTo(50, 9);
+ expect(animator.get('x', 1e7)).toBeCloseTo(100, 9);
+ expect(animator.get('opacity')).toBe(0.5);
+ expect(element.style.opacity).toBe('0.5');
+ });
+
+ it('keeps moving under Reduced Motion: a throw is the finger’s', () => {
+ const {animator, element} = setup({prefersReducedMotion: () => true});
+ animator.decay(coast(animator, {x: 1000}));
+ expect(animator.getVelocity('x', 1016)).toBeGreaterThan(900);
+ // No cross-fade: the coast moves the element and leaves opacity alone.
+ expect(live('translate')).toHaveLength(1);
+ expect(live('opacity')).toHaveLength(0);
+ expect(element.style.opacity).toBe('');
+ });
+
+ it('ships the Reduce Motion fade, not the rest of the timing table', () => {
+ // Bundled for a page, the animator reads two timing values; the table's
+ // other rows stay out (architecture:component-style-authoring INV6).
+ // esbuild runs in its own process: it needs a native TextEncoder.
+ const script = [
+ "import {build} from 'esbuild';",
+ 'const result = await build({',
+ ` entryPoints: [${JSON.stringify(path.resolve(__dirname, 'animator.ts'))}],`,
+ " bundle: true, write: false, format: 'esm', logLevel: 'silent',",
+ '});',
+ 'process.stdout.write(result.outputFiles[0].text);',
+ ].join('\n');
+ const bundle = execFileSync(
+ process.execPath,
+ ['--input-type=module', '-e', script],
+ {cwd: path.resolve(__dirname, '../../../..'), encoding: 'utf8'},
+ );
+ expect(bundle).toContain('durationMs');
+ for (const row of [
+ 'stateChangeMs',
+ 'highlightOutMs',
+ 'navigationBarHideShowMs',
+ ]) {
+ expect(bundle).not.toContain(row);
+ }
+ });
+
+ it('imports neither the coast math nor the scroll table', () => {
+ // Only a surface that coasts pays for them (coast.ts).
+ const source = fs.readFileSync(
+ path.resolve(__dirname, 'animator.ts'),
+ 'utf8',
+ );
+ expect(source).not.toMatch(/from '\.\/decay'/);
+ expect(source).not.toMatch(/from '\.\/uikit\/scroll'/);
+ });
+});
+
+describe('attach', () => {
+ it('keeps state without an element and resumes the curve on attach', () => {
+ const animator = createAnimator(null, {
+ now: () => clock,
+ prefersReducedMotion: () => false,
+ });
+ animator.animate({x: 300}, {spring: springs.settle});
+ expect(recorded).toHaveLength(0);
+ clock += 100;
+ const element = document.createElement('div');
+ animator.attach(element);
+ const [animation] = live('translate');
+ expect(animation.startTime).toBe(1100);
+ const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
+ expect(sampleAt(animation, 'translate', 1100)[0]).toBeCloseTo(
+ curve.value(0.1),
+ 1,
+ );
+ expect(element.style.translate).toBe('300px 0px');
+ });
+
+ it('unmounting settles every handle as interrupted and leaves no timer', async () => {
+ const {animator} = setup();
+ const handle = animator.animate({x: 300}, {spring: springs.settle});
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+ animator.attach(null);
+ expect(vi.getTimerCount()).toBe(0);
+ await expect(handle.finished).resolves.toBe(false);
+ });
+
+ it('detaching cancels the running animations', () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ animator.attach(null);
+ expect(recorded.every(a => a.cancelled)).toBe(true);
+ expect(animator.get('x', 1050)).toBeGreaterThan(0);
+ });
+
+ it('writes nothing for channels at identity', () => {
+ const element = document.createElement('div');
+ createAnimator(element);
+ expect(element.getAttribute('style')).toBeNull();
+ });
+});
diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.ts
new file mode 100644
index 0000000000..9726911c15
--- /dev/null
+++ b/packages/core/src/motion/animator.ts
@@ -0,0 +1,1391 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file animator.ts
+ * @input An element, target values, and a spring or momentum curves
+ * @output Exports `createAnimator`: a compositor animator for translate,
+ * rotate, scale and opacity, with presentation values and velocities read
+ * from the analytic curves, velocity-preserving retargeting, freeze-in-place
+ * `stop`, completion promises, a shared clock, and UIKit's Reduced Motion
+ * substitution; plus its option, handle and transition types
+ * @position Motion foundation (DOM). Internal to core: components use it for
+ * every touch-presentation animation; not exported from the package entry
+ *
+ * HOW IT RUNS
+ *
+ * Each animated value (x, y, rotate, scaleX, scaleY, opacity) follows a
+ * closed-form curve: a spring (spring.ts), momentum curves its caller built (a
+ * UIScrollView coast with an edge bounce, coast.ts), or a Reduced Motion
+ * cross-fade. The curves are baked into
+ * Web Animations keyframes on the individual transform properties (`translate`,
+ * `rotate`, `scale`) and `opacity`, sampled adaptively until linear
+ * interpolation between keyframes is within a fraction of a pixel, and played
+ * with `easing: linear`. The browser then runs them on its compositor: they
+ * keep advancing every frame while JavaScript is busy (law M1).
+ *
+ * Why keyframes and not one `linear()` easing: measured in Chromium, both
+ * forms are composited and equally precise for the same samples, but WebKit's
+ * Core Animation path refuses to accelerate an effect whose easing is
+ * `linear()` with points (KeyframeEffect::canBeAccelerated) unless its newer
+ * threaded animations are on, so on older iOS Safari a `linear()` spring would
+ * run on the main thread. Linear segments between keyframes map directly onto
+ * a Core Animation keyframe animation. Why the individual properties and not
+ * `transform`: each can be animated, retargeted or driven by a finger on its
+ * own (a drag writes `translate` while `scale` keeps springing), with no
+ * additive composition, which neither engine composites.
+ *
+ * The page never reads the DOM to know where something is: `get` and
+ * `getVelocity` evaluate the curves at a time on the document timeline's
+ * clock (`performance.now()` by default), so a finger can grab anything
+ * mid-flight from the value on screen (M2), and a new target starts from the
+ * current value with the current velocity (M3). A gesture's release velocity
+ * can be handed in explicitly instead.
+ *
+ * End state without a flicker frame: the element's inline style always holds
+ * the values the animations END on, and the keyframes hold that end state for
+ * a while after the curve ends (END_HOLD_MS). The main thread drops a finished
+ * animation as soon as it runs after the curve's end; the inline style already
+ * shows the same values, so nothing moves. The hold matters when the curve
+ * ends during a main-thread block: WebKit's compositor ends an animation by
+ * falling back to the value its main thread last committed, which is
+ * mid-flight.
+ *
+ * Shared clock: every animation an `animate` / `decay` call starts gets the
+ * same explicit `startTime` (the call time, or `options.at` to line several
+ * animators up). Keyframes are sampled from that time, so a value that keeps
+ * moving through a rebuild stays on its curve to the frame.
+ *
+ * Reduced Motion (`design:reduced-motion` DR2–DR4). With
+ * `prefers-reduced-motion: reduce`, every `animate` call is a transition:
+ * - on a coarse primary pointer (DR2) it changes opacity only and finishes
+ * within 200 ms. A move that enters (opacity rises in the same call) jumps
+ * to the new place and fades in; one that leaves (opacity falls) fades out
+ * in place, then jumps; any other move dips (fades out, jumps at the
+ * midpoint, fades back in). An opacity-only change fades. The fade runs
+ * `timing.reducedMotionCrossFadeMs`, capped at 200 ms, on
+ * `timing.curves.move`;
+ * - on any other pointer (DR3) it completes at once; an opacity the call does
+ * not name keeps what it was doing.
+ * No call changes this: nothing keeps travel or a spring, and nothing skips
+ * the touch cross-fade (DR4). On a coarse pointer, a fade the call does not
+ * name ends where it was heading. Decays keep their
+ * motion: momentum that continues a throw is direct movement, as scrolling
+ * keeps decelerating under iOS Reduce Motion (`design:reduced-motion` DR2,
+ * DEC-2).
+ *
+ * SSR-safe: nothing touches `window` or `document` at module scope, and an
+ * animator created without an element only keeps state until one is attached.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/motion/animator.test.ts
+ * - /packages/core/src/motion/README.md
+ */
+
+import {cubicBezier} from './bezier';
+import {solveSpring, toSpring, type SpringDescription} from './spring';
+import {reducedMotionCrossFade} from './uikit/timing';
+
+/** A value the animator can drive. */
+export type MotionProperty =
+ 'x' | 'y' | 'rotate' | 'scaleX' | 'scaleY' | 'opacity';
+
+/** Values by property; `scale` sets `scaleX` and `scaleY` together. */
+export type MotionValues = Partial<Record<MotionProperty | 'scale', number>>;
+
+export interface SpringTransition {
+ /** The spring, in any vocabulary of the constants table. */
+ spring: SpringDescription;
+ /**
+ * Initial velocities in units per second (px/s, deg/s, 1/s), for example a
+ * gesture's release velocity. A property without one keeps the velocity it
+ * has on screen.
+ */
+ velocity?: MotionValues;
+}
+
+/**
+ * A curve a release starts, to play on the compositor: a released scroll
+ * view's coast and its edge bounce (`coast.ts`). Momentum keeps moving under
+ * Reduce Motion (design:reduced-motion DR2, DEC-2); a curve marked
+ * `isTransition` (a spring back from past an edge) cross-fades as `animate`
+ * does. Every other motion goes through `animate`. Times are seconds from
+ * the curve's start; the value at `duration` is the end state. Start it at
+ * the property's presentation value (`get`) to continue without a jump.
+ */
+export interface MotionCurve {
+ /** Length, s. */
+ readonly duration: number;
+ /** Value `t` seconds after the start (0 ≤ t ≤ duration). */
+ at(t: number): number;
+ /** Velocity `t` seconds after the start, units/s. */
+ velocity(t: number): number;
+ /**
+ * A transition started on release rather than a throw's momentum (a
+ * spring back from past an edge): under Reduce Motion it is no coast and
+ * cross-fades like `animate` (`design:reduced-motion` DR2).
+ */
+ readonly isTransition?: boolean;
+}
+
+export interface AnimateOptions {
+ /**
+ * Start time on the document timeline (ms, `performance.now()` clock).
+ * Defaults to now. Pass one value to several animators to put their
+ * animations on one clock.
+ */
+ at?: number;
+}
+
+export interface AnimatorOptions {
+ /** Starting values; identity by default. Never read from the DOM. */
+ initial?: MotionValues;
+ /** Clock in ms on the document timeline's time base. */
+ now?: () => number;
+ /** The Reduced Motion preference; `prefers-reduced-motion` by default. */
+ prefersReducedMotion?: () => boolean;
+ /** Whether the primary pointer is coarse; `(pointer: coarse)` by default. */
+ isCoarsePointer?: () => boolean;
+}
+
+/** One `animate` / `decay` call's animations. */
+export interface MotionHandle {
+ /** The properties this call drives. */
+ readonly properties: ReadonlyArray<MotionProperty>;
+ /**
+ * True when every property reached the end of this call's curve, false
+ * as soon as any of them is retargeted, stopped or set before that.
+ */
+ readonly finished: Promise<boolean>;
+ /** Presentation value of a property at `time` (default now). */
+ value(property: MotionProperty, time?: number): number;
+ /** Presentation velocity of a property at `time`, units/s. */
+ velocity(property: MotionProperty, time?: number): number;
+ /** New targets for this call's properties, keeping their velocity. */
+ retarget(
+ to: MotionValues,
+ transition?: SpringTransition,
+ options?: AnimateOptions,
+ ): MotionHandle;
+ /** Freezes this call's properties at their presentation values. */
+ stop(): void;
+}
+
+export interface Animator {
+ /** The element the animator writes to, if attached. */
+ readonly element: HTMLElement | null;
+ /**
+ * Attaches (or detaches, with null) the element. Attaching writes the
+ * current state and resumes running curves from now.
+ */
+ attach(element: HTMLElement | null): void;
+ /** Presentation value at `time` (default now), from the curve. */
+ get(property: MotionProperty | 'scale', time?: number): number;
+ /** Presentation velocity at `time` (default now), units/s. */
+ getVelocity(property: MotionProperty | 'scale', time?: number): number;
+ /**
+ * Puts values in place now, ending their animations: the per-frame write
+ * of a drag (one style write per channel, no animation when nothing else
+ * on the channel is moving).
+ */
+ set(values: MotionValues): void;
+ /** Springs to `to` from the presentation values. */
+ animate(
+ to: MotionValues,
+ transition: SpringTransition,
+ options?: AnimateOptions,
+ ): MotionHandle;
+ /**
+ * Plays the curves a release starts, one per property: a released scroll
+ * view's coast and edge bounce, which `coast()` (coast.ts) builds. Under
+ * Reduced Motion momentum still plays (a throw continues the finger), and
+ * a curve marked `isTransition` cross-fades as `animate` does. Only a
+ * surface that coasts imports the coast math and the scroll table.
+ */
+ decay(
+ curves: Partial<Record<MotionProperty, MotionCurve>>,
+ options?: Pick<AnimateOptions, 'at'>,
+ ): MotionHandle;
+ /** Freezes properties (all by default) at their presentation values. */
+ stop(properties?: ReadonlyArray<MotionProperty | 'scale'>): void;
+ /** Cancels everything and detaches. */
+ dispose(): void;
+}
+
+// ---------------------------------------------------------------------------
+// Curves
+// ---------------------------------------------------------------------------
+
+interface Segment {
+ /** Start on the document timeline, ms. */
+ readonly start: number;
+ /** Length in ms (finite). */
+ readonly duration: number;
+ /** Value from the end on. */
+ readonly target: number;
+ /** Value `t` ms after the start (0 ≤ t ≤ duration). */
+ at(t: number): number;
+ /** Velocity `t` ms after the start, units/s. */
+ speed(t: number): number;
+ /** Times (ms after the start) where the value jumps; `at` is right-continuous. */
+ readonly jumps: ReadonlyArray<number>;
+ /** Constant between jumps: sampled at its jumps only. */
+ readonly steps?: true;
+ /** A Reduce Motion fade: an interruption finishes it instead of freezing it. */
+ readonly isFade?: true;
+ readonly owner: HandleState;
+}
+
+interface HandleState {
+ resolve: (finished: boolean) => void;
+ settled: boolean;
+ timer: ReturnType<typeof setTimeout> | null;
+}
+
+const PROPERTIES: ReadonlyArray<MotionProperty> = [
+ 'x',
+ 'y',
+ 'rotate',
+ 'scaleX',
+ 'scaleY',
+ 'opacity',
+];
+
+const IDENTITY: Record<MotionProperty, number> = {
+ x: 0,
+ y: 0,
+ rotate: 0,
+ scaleX: 1,
+ scaleY: 1,
+ opacity: 1,
+};
+
+/** Within this of its target a curve is over (in the property's own unit). */
+export const SETTLE_THRESHOLD: Record<MotionProperty, number> = {
+ x: 0.05,
+ y: 0.05,
+ rotate: 0.01,
+ scaleX: 0.0001,
+ scaleY: 0.0001,
+ opacity: 0.001,
+};
+
+/** Keyframes are added until linear interpolation is within this. */
+const SAMPLE_TOLERANCE: Record<MotionProperty, number> = {
+ x: 0.05,
+ y: 0.05,
+ rotate: 0.02,
+ scaleX: 0.0002,
+ scaleY: 0.0002,
+ opacity: 0.002,
+};
+
+/** A curve that has not settled by then (an undamped spring) snaps. */
+const MAX_DURATION_MS = 30_000;
+/** Above this many keyframes the tolerance is relaxed. */
+const MAX_KEYFRAMES = 1200;
+/**
+ * The keyframes hold the end state this long after a curve ends. An engine
+ * whose compositor ends an animation while the main thread is blocked falls
+ * back to the value its main thread last committed, mid-flight (WebKit); the
+ * hold keeps the end state on screen through such a block. The main thread
+ * drops the animation as soon as it runs after the curve's end.
+ */
+export const END_HOLD_MS = 5000;
+
+/** How often a paused animation is looked at again for retiring, ms. */
+const RETIRE_RECHECK_MS = 100;
+
+const TRAVEL: ReadonlyArray<MotionProperty> = [
+ 'x',
+ 'y',
+ 'rotate',
+ 'scaleX',
+ 'scaleY',
+];
+
+type Channel = 'translate' | 'rotate' | 'scale' | 'opacity';
+
+const CHANNELS: Record<Channel, ReadonlyArray<MotionProperty>> = {
+ translate: ['x', 'y'],
+ rotate: ['rotate'],
+ scale: ['scaleX', 'scaleY'],
+ opacity: ['opacity'],
+};
+
+const CHANNEL_OF: Record<MotionProperty, Channel> = {
+ x: 'translate',
+ y: 'translate',
+ rotate: 'rotate',
+ scaleX: 'scale',
+ scaleY: 'scale',
+ opacity: 'opacity',
+};
+
+function round(value: number, digits: number): number {
+ return Number(value.toFixed(digits));
+}
+
+function format(
+ channel: Channel,
+ value: (property: MotionProperty) => number,
+): string {
+ switch (channel) {
+ case 'translate':
+ return `${round(value('x'), 3)}px ${round(value('y'), 3)}px`;
+ case 'rotate':
+ return `${round(value('rotate'), 4)}deg`;
+ case 'scale':
+ return `${round(value('scaleX'), 5)} ${round(value('scaleY'), 5)}`;
+ case 'opacity':
+ return `${round(Math.min(1, Math.max(0, value('opacity'))), 4)}`;
+ }
+}
+
+/**
+ * The inline text for a channel: `format`, except that an identity transform
+ * is written `none`. Any other value, `translate: 0px 0px` included, makes
+ * the element the containing block of its `position: fixed` descendants and
+ * a stacking context, so a motion back to identity would leave a fixed child
+ * moved with its parent; Mobile Safari also lets no finger scroll a list
+ * inside an element left at `scale: 1`. At rest the identity leaves the
+ * element entirely when its stylesheet agrees (`releaseIdentity`).
+ */
+function inlineText(
+ channel: Channel,
+ value: (property: MotionProperty) => number,
+): string {
+ const at = (property: MotionProperty, identity: number, digits: number) =>
+ round(value(property), digits) === identity;
+ switch (channel) {
+ case 'translate':
+ return at('x', 0, 3) && at('y', 0, 3) ? 'none' : format(channel, value);
+ case 'rotate':
+ return at('rotate', 0, 4) ? 'none' : format(channel, value);
+ case 'scale':
+ return at('scaleX', 1, 5) && at('scaleY', 1, 5)
+ ? 'none'
+ : format(channel, value);
+ case 'opacity':
+ return format(channel, value);
+ }
+}
+
+/** What `inlineText` writes for each channel at identity. */
+const IDENTITY_TEXT: Record<Channel, string> = {
+ translate: 'none',
+ rotate: 'none',
+ scale: 'none',
+ opacity: '1',
+};
+
+/** Whether a computed value (or an unset one) is the channel's identity. */
+function isIdentityText(channel: Channel, text: string): boolean {
+ const value = text.trim();
+ if (value === '' || value === 'none') {
+ return true;
+ }
+ const numbers = value.split(/\s+/).map(part => Number.parseFloat(part));
+ if (numbers.some(number => !Number.isFinite(number))) {
+ return false;
+ }
+ const identity = channel === 'scale' || channel === 'opacity' ? 1 : 0;
+ return numbers.every(number => Math.abs(number - identity) < 1e-6);
+}
+
+function expand(values: MotionValues): Partial<Record<MotionProperty, number>> {
+ const out: Partial<Record<MotionProperty, number>> = {};
+ for (const [key, value] of Object.entries(values)) {
+ if (value == null || !Number.isFinite(value)) {
+ continue;
+ }
+ if (key === 'scale') {
+ out.scaleX ??= value;
+ out.scaleY ??= value;
+ } else if ((PROPERTIES as ReadonlyArray<string>).includes(key)) {
+ out[key as MotionProperty] = value;
+ }
+ }
+ return out;
+}
+
+function defaultNow(): number {
+ return typeof performance === 'undefined' ? Date.now() : performance.now();
+}
+
+function matchesMedia(query: string): boolean {
+ return (
+ typeof window !== 'undefined' &&
+ typeof window.matchMedia === 'function' &&
+ window.matchMedia(query).matches
+ );
+}
+
+function defaultPrefersReducedMotion(): boolean {
+ return matchesMedia('(prefers-reduced-motion: reduce)');
+}
+
+function defaultIsCoarsePointer(): boolean {
+ return matchesMedia('(pointer: coarse)');
+}
+
+/** The longest a Reduced Motion cross-fade may run (`design:reduced-motion` DR2). */
+const REDUCED_MOTION_MAX_FADE_MS = 200;
+
+/**
+ * The transition `decay` hands a Reduce Motion transition curve to: under
+ * Reduce Motion `animate` plays no spring (a cross-fade, or at once), so the
+ * spring itself is never solved.
+ */
+const REDUCED_TRANSITION: SpringTransition = {
+ spring: {duration: 0.5, bounce: 0},
+};
+
+/**
+ * Creates an animator for `element` (or for an element attached later).
+ *
+ * @example
+ * ```
+ * const animator = createAnimator(sheet);
+ * // finger lifts at 1200 px/s heading for the detent at 0:
+ * animator.animate({y: 0}, {spring: springs.sheetDetent, velocity: {y: 1200}});
+ * // the finger lands again: where is it right now?
+ * const y = animator.get('y', event.timeStamp);
+ * animator.stop(['y']);
+ * ```
+ */
+export function createAnimator(
+ element: HTMLElement | null,
+ options: AnimatorOptions = {},
+): Animator {
+ const now = options.now ?? defaultNow;
+ const prefersReducedMotion =
+ options.prefersReducedMotion ?? defaultPrefersReducedMotion;
+ const isCoarsePointer = options.isCoarsePointer ?? defaultIsCoarsePointer;
+ const resting: Record<MotionProperty, number> = {
+ ...IDENTITY,
+ ...expand(options.initial ?? {}),
+ };
+ const segments = new Map<MotionProperty, Segment>();
+ const running = new Map<Channel, Animation>();
+ /** Drops a finished, still-filling animation once the main thread runs. */
+ const retireTimers = new Map<Channel, ReturnType<typeof setTimeout>>();
+ const touched = new Set<Channel>();
+ /**
+ * The stylesheet's opacity a Reduce Motion dip borrowed because no call
+ * owned opacity; the dip runs from and back to it, then hands it back.
+ */
+ let borrowedOpacity: number | null = null;
+ let target: HTMLElement | null = null;
+ /** Channels whose identity the last node held inline (see `attach`). */
+ let heldIdentity = new Set<Channel>();
+
+ // -- reading the curves ---------------------------------------------------
+
+ const segmentAt = (
+ property: MotionProperty,
+ time: number,
+ ): Segment | null => {
+ const segment = segments.get(property);
+ if (segment == null) {
+ return null;
+ }
+ if (time >= segment.start + segment.duration) {
+ return null;
+ }
+ return segment;
+ };
+
+ const valueAt = (property: MotionProperty, time: number): number => {
+ const segment = segments.get(property);
+ if (segment == null) {
+ return resting[property];
+ }
+ if (time >= segment.start + segment.duration) {
+ return segment.target;
+ }
+ return segment.at(Math.max(0, time - segment.start));
+ };
+
+ const velocityAt = (property: MotionProperty, time: number): number => {
+ const segment = segmentAt(property, time);
+ if (segment == null || time < segment.start) {
+ return 0;
+ }
+ return segment.speed(time - segment.start);
+ };
+
+ // A value just before a jump at absolute time `time`.
+ const valueBefore = (property: MotionProperty, time: number): number =>
+ valueAt(property, time - 1e-6);
+
+ // -- writing --------------------------------------------------------------
+
+ const finalValue = (property: MotionProperty): number =>
+ segments.get(property)?.target ?? resting[property];
+
+ const writeInline = (
+ channel: Channel,
+ value: (property: MotionProperty) => number,
+ ) => {
+ if (target == null) {
+ return;
+ }
+ touched.add(channel);
+ const text = inlineText(channel, value);
+ if (text === IDENTITY_TEXT[channel]) {
+ // Identity leaves the element when nothing else would move it.
+ target.style.setProperty(channel, text);
+ releaseIdentity(channel);
+ } else {
+ target.style.setProperty(channel, text);
+ }
+ };
+
+ const sampleTimes = (
+ property: MotionProperty,
+ from: number,
+ to: number,
+ tolerance: number,
+ ): number[] => {
+ const segment = segments.get(property);
+ if (segment == null) {
+ return [];
+ }
+ const begin = Math.max(from, segment.start);
+ const end = Math.min(to, segment.start + segment.duration);
+ if (end <= begin) {
+ return [];
+ }
+ const times: number[] = [begin];
+ const value = (t: number) => valueAt(property, t);
+ const breaks = segment.jumps
+ .map(j => segment.start + j)
+ .filter(t => t > begin && t < end);
+ if (segment.steps) {
+ return [begin, ...breaks, end];
+ }
+ const edges = [begin, ...breaks, end];
+ for (let e = 0; e + 1 < edges.length; e++) {
+ const a = edges[e];
+ const b = edges[e + 1];
+ // A 120 Hz grid, each interval split until the chord is within the
+ // tolerance at its quarter points.
+ const steps = Math.max(1, Math.ceil((b - a) / (1000 / 120)));
+ const split = (t0: number, t1: number, depth: number) => {
+ const v0 = value(t0);
+ const v1 =
+ t1 === b && breaks.includes(b) ? valueBefore(property, b) : value(t1);
+ let worst = 0;
+ for (const f of [0.25, 0.5, 0.75]) {
+ const t = t0 + (t1 - t0) * f;
+ worst = Math.max(worst, Math.abs(value(t) - (v0 + (v1 - v0) * f)));
+ }
+ if (worst > tolerance && depth < 10 && t1 - t0 > 0.25) {
+ const mid = (t0 + t1) / 2;
+ split(t0, mid, depth + 1);
+ split(mid, t1, depth + 1);
+ } else {
+ times.push(t1);
+ }
+ };
+ for (let i = 0; i < steps; i++) {
+ split(a + ((b - a) * i) / steps, a + ((b - a) * (i + 1)) / steps, 0);
+ }
+ }
+ return times;
+ };
+
+ const rebuild = (channel: Channel, time: number) => {
+ running.get(channel)?.cancel();
+ running.delete(channel);
+ clearTimeout(retireTimers.get(channel));
+ retireTimers.delete(channel);
+ const properties = CHANNELS[channel];
+ // Settled curves become resting values.
+ for (const property of properties) {
+ const segment = segments.get(property);
+ if (segment != null && time >= segment.start + segment.duration) {
+ resting[property] = segment.target;
+ segments.delete(property);
+ }
+ }
+ writeInline(channel, finalValue);
+ const moving = properties.filter(p => segments.has(p));
+ if (
+ target == null ||
+ moving.length === 0 ||
+ typeof target.animate !== 'function'
+ ) {
+ return;
+ }
+ const end = Math.min(
+ time + MAX_DURATION_MS,
+ Math.max(
+ ...moving.map(
+ p =>
+ (segments.get(p) as Segment).start +
+ (segments.get(p) as Segment).duration,
+ ),
+ ),
+ );
+ if (end <= time) {
+ return;
+ }
+ const collect = (scale: number) => {
+ const times = new Set<number>([time, end]);
+ for (const property of moving) {
+ for (const t of sampleTimes(
+ property,
+ time,
+ end,
+ SAMPLE_TOLERANCE[property] * scale,
+ )) {
+ times.add(t);
+ }
+ }
+ return times;
+ };
+ let scale = 1;
+ let all = collect(scale);
+ while (all.size > MAX_KEYFRAMES && scale < 64) {
+ scale *= 2;
+ all = collect(scale);
+ }
+ // Jumps become two keyframes at one offset: the value just before, then
+ // the value after. A jump on the last frame (fade out, then move) too.
+ const jumpTimes = new Set<number>();
+ for (const property of moving) {
+ const segment = segments.get(property) as Segment;
+ for (const j of segment.jumps) {
+ const t = segment.start + j;
+ if (t > time && t <= end) {
+ jumpTimes.add(t);
+ all.add(t);
+ }
+ }
+ }
+ const times = [...all].sort((a, b) => a - b);
+ const span = end - time + END_HOLD_MS;
+ const keyframes: Keyframe[] = [];
+ for (const t of times) {
+ const offset = (t - time) / span;
+ if (jumpTimes.has(t)) {
+ keyframes.push({
+ offset,
+ [channel]: format(channel, p => valueBefore(p, t)),
+ });
+ }
+ keyframes.push({
+ offset,
+ [channel]: format(channel, p =>
+ t >= end ? finalValue(p) : valueAt(p, t),
+ ),
+ });
+ }
+ keyframes.push({offset: 1, [channel]: format(channel, finalValue)});
+ const animation = target.animate(keyframes, {
+ duration: span,
+ // The last keyframes hold the end state (END_HOLD_MS); filling both
+ // ways also keeps it where an engine honors the fill on its compositor.
+ // The main thread drops the animation once it runs after the end; the
+ // inline style already holds the same values, so that changes no pixel.
+ fill: 'both',
+ easing: 'linear',
+ });
+ // One clock: the keyframes were sampled from `time`.
+ animation.startTime = time;
+ running.set(channel, animation);
+ const retire = () => {
+ retireTimers.delete(channel);
+ if (running.get(channel) !== animation) {
+ return;
+ }
+ // Paused or sought (a sampler holding it): retire when its own time
+ // reaches the curve's end, never from the wall clock.
+ const remaining = remainingCurve(animation);
+ if (remaining != null && remaining > 0) {
+ retireTimers.set(
+ channel,
+ setTimeout(
+ retire,
+ animation.playState === 'paused' ? RETIRE_RECHECK_MS : remaining,
+ ),
+ );
+ return;
+ }
+ animation.cancel();
+ running.delete(channel);
+ releaseIdentity(channel);
+ };
+ retireTimers.set(channel, setTimeout(retire, Math.max(0, end - now())));
+ };
+
+ /**
+ * A channel at identity with no animation of its own leaves the element:
+ * its inline value is removed, unless the stylesheet would then move the
+ * element, in which case the identity stays inline. Runs when such a value
+ * is written and again when a motion ends.
+ */
+ /** The element's own (stylesheet) opacity, read once when a dip starts. */
+ const ownOpacity = (): number => {
+ const view = target?.ownerDocument.defaultView;
+ const value =
+ target == null
+ ? NaN
+ : Number.parseFloat(
+ view?.getComputedStyle(target).getPropertyValue('opacity') ?? '',
+ );
+ return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 1;
+ };
+
+ /**
+ * Ends a borrowed dip on the element it ran on: the stylesheet owns its
+ * opacity again (an unmount or a new element never keeps the borrow).
+ */
+ const handBackBorrow = () => {
+ if (borrowedOpacity == null) {
+ return;
+ }
+ borrowedOpacity = null;
+ segments.delete('opacity');
+ resting.opacity = IDENTITY.opacity;
+ target?.style.removeProperty('opacity');
+ };
+
+ const releaseIdentity = (channel: Channel) => {
+ if (target == null || running.has(channel)) {
+ return;
+ }
+ if (channel === 'opacity' && borrowedOpacity != null) {
+ const dip = segments.get('opacity');
+ if (dip != null && now() < dip.start + dip.duration) {
+ // The dip is still running (a rebuild wrote its end value first).
+ return;
+ }
+ // A dip on the stylesheet's opacity ended: the stylesheet owns it again.
+ borrowedOpacity = null;
+ segments.delete('opacity');
+ resting.opacity = IDENTITY.opacity;
+ target.style.removeProperty('opacity');
+ return;
+ }
+ const text = target.style.getPropertyValue(channel);
+ if (text !== IDENTITY_TEXT[channel]) {
+ return;
+ }
+ target.style.removeProperty(channel);
+ const view = target.ownerDocument.defaultView;
+ const underneath = view?.getComputedStyle(target).getPropertyValue(channel);
+ if (underneath != null && !isIdentityText(channel, underneath)) {
+ target.style.setProperty(channel, text);
+ }
+ };
+
+ /**
+ * Curve time an animation still has to play on its own clock (its keyframes
+ * hold the end for END_HOLD_MS after the curve), or null where the engine
+ * does not report it; a paused animation always has some left.
+ */
+ const remainingCurve = (animation: Animation): number | null => {
+ const timing = animation.effect?.getTiming?.();
+ const current = animation.currentTime;
+ if (timing == null || current == null) {
+ return animation.playState === 'paused' ? Infinity : null;
+ }
+ const left = Number(timing.duration) - END_HOLD_MS - Number(current);
+ return animation.playState === 'paused' ? Math.max(left, 1) : left;
+ };
+
+ // -- handles --------------------------------------------------------------
+
+ const lastSpring = new WeakMap<HandleState, SpringDescription>();
+
+ const interrupt = (property: MotionProperty, time: number) => {
+ const segment = segments.get(property);
+ if (segment == null) {
+ return;
+ }
+ if (time < segment.start + segment.duration) {
+ settle(segment.owner, false);
+ }
+ };
+
+ const settle = (owner: HandleState, finished: boolean) => {
+ if (owner.settled) {
+ return;
+ }
+ owner.settled = true;
+ if (owner.timer != null) {
+ clearTimeout(owner.timer);
+ owner.timer = null;
+ }
+ owner.resolve(finished);
+ };
+
+ const makeHandle = (
+ owner: HandleState,
+ properties: MotionProperty[],
+ finished: Promise<boolean>,
+ time: number,
+ ): MotionHandle => {
+ const ends = properties.map(p => {
+ const segment = segments.get(p);
+ return segment != null && segment.owner === owner
+ ? segment.start + segment.duration
+ : time;
+ });
+ const end = Math.max(time, ...ends);
+ if (properties.length === 0 || end <= time) {
+ settle(owner, true);
+ } else {
+ // Interruptions settle false as they happen (interrupt); reaching the
+ // end untouched is completion.
+ owner.timer = setTimeout(
+ () => {
+ owner.timer = null;
+ settle(owner, true);
+ },
+ Math.max(0, end - now()),
+ );
+ }
+ const handle: MotionHandle = {
+ properties,
+ finished,
+ value: (property, at = now()) => valueAt(property, at),
+ velocity: (property, at = now()) => velocityAt(property, at),
+ retarget: (to, transition, retargetOptions) => {
+ const spring = transition?.spring ?? lastSpring.get(owner);
+ if (spring == null) {
+ throw new Error('animator: retarget needs a spring');
+ }
+ return animator.animate(to, {...transition, spring}, retargetOptions);
+ },
+ stop: () =>
+ animator.stop(properties.filter(p => segments.get(p)?.owner === owner)),
+ };
+ return handle;
+ };
+
+ const newOwner = (): {owner: HandleState; finished: Promise<boolean>} => {
+ let resolve: (finished: boolean) => void = () => {};
+ const finished = new Promise<boolean>(r => {
+ resolve = r;
+ });
+ return {owner: {resolve, settled: false, timer: null}, finished};
+ };
+
+ // -- segment factories ------------------------------------------------------
+
+ const springSegment = (
+ owner: HandleState,
+ property: MotionProperty,
+ start: number,
+ to: number,
+ spring: SpringDescription,
+ velocity: number,
+ ): Segment | null => {
+ const from = valueAt(property, start);
+ if (from === to && velocity === 0) {
+ return null;
+ }
+ const curve = solveSpring(toSpring(spring), {from, to, velocity});
+ const duration = Math.min(
+ MAX_DURATION_MS,
+ curve.settleTime(SETTLE_THRESHOLD[property]) * 1000,
+ );
+ return {
+ start,
+ duration,
+ target: to,
+ at: t => curve.value(t / 1000),
+ speed: t => curve.velocity(t / 1000),
+ jumps: [],
+ owner,
+ };
+ };
+
+ const fadeSegment = (
+ owner: HandleState,
+ start: number,
+ stops: ReadonlyArray<{at: number; value: number}>,
+ jumps: ReadonlyArray<number> = [],
+ ): Segment => {
+ const ease = cubicBezier(reducedMotionCrossFade.curve);
+ const duration = stops[stops.length - 1].at;
+ const at = (t: number) => {
+ for (let i = 0; i + 1 < stops.length; i++) {
+ const a = stops[i];
+ const b = stops[i + 1];
+ if (t < b.at || i + 2 === stops.length) {
+ if (b.at === a.at) {
+ return b.value;
+ }
+ const p = Math.min(1, Math.max(0, (t - a.at) / (b.at - a.at)));
+ return a.value + (b.value - a.value) * ease(p);
+ }
+ }
+ return stops[stops.length - 1].value;
+ };
+ return {
+ start,
+ duration,
+ target: stops[stops.length - 1].value,
+ at,
+ speed: t =>
+ ((at(t + 0.5) - at(Math.max(0, t - 0.5))) / (t >= 0.5 ? 1 : 0.5 + t)) *
+ 1000,
+ jumps,
+ owner,
+ isFade: true,
+ };
+ };
+
+ const jumpSegment = (
+ owner: HandleState,
+ start: number,
+ from: number,
+ to: number,
+ after: number,
+ ): Segment => ({
+ start,
+ duration: after,
+ target: to,
+ at: t => (t < after ? from : to),
+ speed: () => 0,
+ jumps: [after],
+ steps: true,
+ owner,
+ });
+
+ // -- the animator -----------------------------------------------------------
+
+ const commit = (changed: Iterable<MotionProperty>, time: number) => {
+ const channels = new Set<Channel>();
+ for (const property of changed) {
+ channels.add(CHANNEL_OF[property]);
+ }
+ if (channels.has('opacity')) {
+ borrowedOpacity = null;
+ }
+ for (const channel of channels) {
+ rebuild(channel, time);
+ }
+ };
+
+ const animator: Animator = {
+ get element() {
+ return target;
+ },
+
+ attach(next) {
+ if (next === target) {
+ return;
+ }
+ if (next == null) {
+ // Unmount: nothing is left to animate, so every handle settles as
+ // interrupted and no completion timer outlives the element, as in
+ // dispose() (architecture:react-component-runtime INV5).
+ const time = now();
+ for (const property of PROPERTIES) {
+ interrupt(property, time);
+ }
+ }
+ for (const animation of running.values()) {
+ animation.cancel();
+ }
+ running.clear();
+ for (const timer of retireTimers.values()) {
+ clearTimeout(timer);
+ }
+ retireTimers.clear();
+ if (borrowedOpacity != null) {
+ // A running borrowed dip stays in the model through any attach, so a
+ // pending move still lands while the element is invisible; only the
+ // outgoing element gets its stylesheet's opacity back.
+ target?.style.removeProperty('opacity');
+ }
+ // Identities the outgoing node holds inline over a stylesheet that
+ // differs, kept through a detach for the node that comes next.
+ if (target != null) {
+ const outgoing = target;
+ heldIdentity = new Set(
+ (Object.keys(CHANNELS) as Channel[]).filter(
+ channel =>
+ outgoing.style.getPropertyValue(channel) ===
+ IDENTITY_TEXT[channel],
+ ),
+ );
+ }
+ const held = heldIdentity;
+ target = next;
+ if (target == null) {
+ return;
+ }
+ heldIdentity = new Set();
+ const time = now();
+ // A borrowed dip that ended while detached hands the opacity back
+ // instead of writing the borrowed value inline.
+ const dip = segments.get('opacity');
+ if (
+ borrowedOpacity != null &&
+ (dip == null || time >= dip.start + dip.duration)
+ ) {
+ borrowedOpacity = null;
+ segments.delete('opacity');
+ resting.opacity = IDENTITY.opacity;
+ }
+ for (const channel of Object.keys(CHANNELS) as Channel[]) {
+ const properties = CHANNELS[channel];
+ const isDefault = properties.every(
+ p => !segments.has(p) && resting[p] === IDENTITY[p],
+ );
+ if (!isDefault) {
+ rebuild(channel, time);
+ } else if (held.has(channel)) {
+ // An identity the animator held inline over a stylesheet that
+ // differs goes onto the new node too (writeInline keeps it only
+ // where the new node's stylesheet still differs).
+ writeInline(channel, property => resting[property]);
+ }
+ }
+ },
+
+ get(property, time = now()) {
+ return valueAt(property === 'scale' ? 'scaleX' : property, time);
+ },
+
+ getVelocity(property, time = now()) {
+ return velocityAt(property === 'scale' ? 'scaleX' : property, time);
+ },
+
+ set(values) {
+ const time = now();
+ const next = expand(values);
+ for (const [property, value] of Object.entries(next) as [
+ MotionProperty,
+ number,
+ ][]) {
+ interrupt(property, time);
+ segments.delete(property);
+ resting[property] = value;
+ }
+ commit(Object.keys(next) as MotionProperty[], time);
+ },
+
+ animate(to, transition, animateOptions = {}) {
+ const time = animateOptions.at ?? now();
+ const targets = expand(to);
+ const velocities = expand(transition.velocity ?? {});
+ const {owner, finished} = newOwner();
+ lastSpring.set(owner, transition.spring);
+ const properties = Object.keys(targets) as MotionProperty[];
+ const reduce = prefersReducedMotion();
+ const instant = reduce && !isCoarsePointer();
+ const travels = properties.some(
+ p =>
+ TRAVEL.includes(p) &&
+ Math.abs((targets[p] as number) - valueAt(p, time)) > 1e-9,
+ );
+ const next: Partial<Record<MotionProperty, Segment | null>> = {};
+ const retimed = new Set<MotionProperty>();
+ // A fade the call does not name ends where it was heading.
+ const opacityTo = targets.opacity ?? finalValue('opacity');
+
+ // A dip on a touch screen when no call owns opacity starts from and
+ // returns to the element's own opacity, not the model's 1.
+ // A dip already borrowing it does not make the call own it.
+ const previousBorrow = borrowedOpacity;
+ // An opacity the animator left inline (a `set` over a stylesheet that
+ // hides or dims the element) is owned too: a dip returns to it.
+ const ownsOpacity =
+ targets.opacity != null ||
+ (borrowedOpacity == null &&
+ (segments.has('opacity') ||
+ resting.opacity !== IDENTITY.opacity ||
+ (target?.style.getPropertyValue('opacity') ?? '') !== ''));
+ const borrowed =
+ reduce && !instant && travels && !ownsOpacity
+ ? (borrowedOpacity ?? ownOpacity())
+ : null;
+ if (reduce) {
+ const fade = Math.min(
+ reducedMotionCrossFade.durationMs,
+ REDUCED_MOTION_MAX_FADE_MS,
+ );
+ const opacityNow = segments.has('opacity')
+ ? valueAt('opacity', time)
+ : (borrowed ?? valueAt('opacity', time));
+ const fadeTo = borrowed ?? opacityTo;
+ const entering = fadeTo > opacityNow + 1e-6;
+ const leaving = fadeTo < opacityNow - 1e-6;
+ // Travel lands only while the element is invisible: at once when it
+ // already is, at the end of a fade out to 0, and otherwise at the
+ // bottom of a dip (DR2), so an overlapping call never moves it while
+ // it shows.
+ const isInvisible = opacityNow <= 1e-6;
+ const fadesOut = fadeTo <= 1e-6;
+ // An earlier call's travel still waiting for its dip: this call's
+ // fade replaces that dip, so the travel lands at this fade's own
+ // invisible moment instead of while the element shows.
+ const pendingJumps = TRAVEL.filter(property => {
+ if (properties.includes(property)) {
+ return false;
+ }
+ const segment = segments.get(property);
+ return (
+ segment?.steps === true && time < segment.start + segment.duration
+ );
+ });
+ const dips =
+ (travels || pendingJumps.length > 0) && !isInvisible && !fadesOut;
+ for (const property of properties) {
+ if (!TRAVEL.includes(property)) {
+ continue;
+ }
+ const from = valueAt(property, time);
+ const toValue = targets[property] as number;
+ if (instant || isInvisible || from === toValue) {
+ next[property] = null; // in place at once (and fade in)
+ } else if (fadesOut) {
+ next[property] = jumpSegment(owner, time, from, toValue, fade); // fade out, then move
+ } else {
+ next[property] = jumpSegment(owner, time, from, toValue, fade / 2); // dip
+ }
+ }
+ if (instant) {
+ if (targets.opacity != null) {
+ next.opacity = null;
+ }
+ } else if (!dips && (entering || leaving)) {
+ next.opacity = fadeSegment(owner, time, [
+ {at: 0, value: opacityNow},
+ {at: fade, value: opacityTo},
+ ]);
+ } else if (dips) {
+ next.opacity = fadeSegment(owner, time, [
+ {at: 0, value: opacityNow},
+ {at: fade / 2, value: 0},
+ {at: fade, value: borrowed ?? opacityTo},
+ ]);
+ } else if (targets.opacity != null) {
+ next.opacity = null; // already there
+ }
+ if (!instant) {
+ const landAt = isInvisible ? 0 : fadesOut ? fade : fade / 2;
+ for (const property of pendingJumps) {
+ retimed.add(property);
+ const segment = segments.get(property) as Segment;
+ next[property] = jumpSegment(
+ segment.owner,
+ time,
+ valueAt(property, time),
+ segment.target,
+ landAt,
+ );
+ }
+ }
+ } else {
+ for (const property of properties) {
+ const velocity = velocities[property] ?? velocityAt(property, time);
+ next[property] = springSegment(
+ owner,
+ property,
+ time,
+ targets[property] as number,
+ transition.spring,
+ velocity,
+ );
+ }
+ }
+
+ const changed: MotionProperty[] = [];
+ for (const [property, segment] of Object.entries(next) as [
+ MotionProperty,
+ Segment | null,
+ ][]) {
+ // A re-timed jump keeps its own call's handle running.
+ if (!retimed.has(property)) {
+ interrupt(property, time);
+ }
+ changed.push(property);
+ if (segment == null) {
+ segments.delete(property);
+ resting[property] =
+ property === 'opacity'
+ ? opacityTo
+ : (targets[property] ?? valueAt(property, time));
+ } else {
+ segments.set(property, segment);
+ }
+ }
+ commit(changed, time);
+ // A call that does not own opacity keeps a running borrowed dip's
+ // borrow, whatever it does itself (moves nothing, springs after a
+ // preference or pointer change), so the dip still hands the
+ // stylesheet's opacity back when it ends.
+ // A borrow exists only while its dip runs: a call that found the
+ // element already invisible (a stylesheet opacity of 0) dips nothing
+ // and borrows nothing.
+ borrowedOpacity =
+ borrowed != null && next.opacity != null
+ ? borrowed
+ : targets.opacity == null
+ ? previousBorrow
+ : null;
+ return makeHandle(owner, changed, finished, time);
+ },
+
+ decay(curves, decayOptions = {}) {
+ const time = decayOptions.at ?? now();
+ // Under Reduce Motion only momentum keeps moving (DR2, DEC-2): a curve
+ // that is a transition plays as `animate` does, a cross-fade or at once.
+ const reduce = prefersReducedMotion();
+ const transitions: MotionValues = {};
+ for (const property of PROPERTIES) {
+ const curve = curves[property];
+ if (reduce && curve?.isTransition === true) {
+ transitions[property] = curve.at(curve.duration);
+ }
+ }
+ const transitioned =
+ Object.keys(transitions).length > 0
+ ? animator.animate(transitions, REDUCED_TRANSITION, {at: time})
+ : null;
+ const {owner, finished} = newOwner();
+ const properties = PROPERTIES.filter(
+ property =>
+ curves[property] != null && transitions[property] === undefined,
+ );
+ if (transitioned != null && properties.length === 0) {
+ return transitioned;
+ }
+ for (const property of properties) {
+ const curve = curves[property] as MotionCurve;
+ interrupt(property, time);
+ if (!(curve.duration > 0)) {
+ segments.delete(property);
+ resting[property] = curve.at(0);
+ continue;
+ }
+ segments.set(property, {
+ start: time,
+ duration: Math.min(MAX_DURATION_MS, curve.duration * 1000),
+ target: curve.at(curve.duration),
+ at: t => curve.at(t / 1000),
+ speed: t => curve.velocity(t / 1000),
+ jumps: [],
+ owner,
+ });
+ }
+ commit(properties, time);
+ const handle = makeHandle(owner, properties, finished, time);
+ if (transitioned == null) {
+ return handle;
+ }
+ // One handle for the whole release: the cross-faded axes too.
+ const faded = transitioned;
+ const owns = (property: MotionProperty) =>
+ faded.properties.includes(property);
+ return {
+ ...handle,
+ properties: [...handle.properties, ...faded.properties],
+ finished: Promise.all([handle.finished, faded.finished]).then(
+ ([coasted, done]) => coasted && done,
+ ),
+ value: (property, at) =>
+ owns(property)
+ ? faded.value(property, at)
+ : handle.value(property, at),
+ velocity: (property, at) =>
+ owns(property)
+ ? faded.velocity(property, at)
+ : handle.velocity(property, at),
+ stop: () => {
+ handle.stop();
+ faded.stop();
+ },
+ };
+ },
+
+ stop(properties) {
+ const time = now();
+ const list = properties == null ? PROPERTIES : expandList(properties);
+ const changed: MotionProperty[] = [];
+ const wasBorrowed = borrowedOpacity != null;
+ for (const property of list) {
+ const segment = segments.get(property);
+ if (segment == null) {
+ continue;
+ }
+ // A Reduce Motion fade is never left half done: it finishes, and a
+ // dip on the stylesheet's opacity hands that opacity back.
+ const value = !segment.isFade
+ ? valueAt(property, time)
+ : wasBorrowed
+ ? IDENTITY.opacity
+ : segment.target;
+ interrupt(property, time);
+ segments.delete(property);
+ resting[property] = value;
+ changed.push(property);
+ }
+ // A finished fade takes the travel waiting for it along, at the same
+ // instant: a pending jump never lands later, in view.
+ if (changed.includes('opacity')) {
+ for (const property of TRAVEL) {
+ const segment = segments.get(property);
+ if (
+ list.includes(property) ||
+ segment?.steps !== true ||
+ time >= segment.start + segment.duration
+ ) {
+ continue;
+ }
+ interrupt(property, time);
+ segments.delete(property);
+ resting[property] = segment.target;
+ changed.push(property);
+ }
+ }
+ commit(changed, time);
+ if (wasBorrowed && changed.includes('opacity')) {
+ target?.style.removeProperty('opacity');
+ }
+ },
+
+ dispose() {
+ const time = now();
+ for (const property of PROPERTIES) {
+ interrupt(property, time);
+ }
+ for (const animation of running.values()) {
+ animation.cancel();
+ }
+ running.clear();
+ for (const timer of retireTimers.values()) {
+ clearTimeout(timer);
+ }
+ retireTimers.clear();
+ handBackBorrow();
+ target = null;
+ },
+ };
+
+ animator.attach(element);
+ return animator;
+}
+
+function expandList(
+ properties: ReadonlyArray<MotionProperty | 'scale'>,
+): MotionProperty[] {
+ const out = new Set<MotionProperty>();
+ for (const property of properties) {
+ if (property === 'scale') {
+ out.add('scaleX');
+ out.add('scaleY');
+ } else {
+ out.add(property);
+ }
+ }
+ return [...out];
+}
diff --git a/packages/core/src/motion/bezier.test.ts b/packages/core/src/motion/bezier.test.ts
new file mode 100644
index 0000000000..db93170d09
--- /dev/null
+++ b/packages/core/src/motion/bezier.test.ts
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file bezier.test.ts
+ * @input vitest, the cubic-bézier timing function
+ * @output Checks the solver against the curve's own parametric form and the
+ * properties every CSS / Core Animation timing curve has
+ * @position Testing; validates bezier.ts without a browser
+ */
+
+import {describe, expect, it} from 'vitest';
+import {cubicBezier, type BezierPoints} from './bezier';
+import {timing} from './uikit/timing';
+
+const CURVES: BezierPoints[] = [
+ timing.curves.viewChange,
+ timing.curves.move,
+ timing.curves.exit,
+ timing.curves.entrance,
+ [0.24, 1, 0.4, 1],
+ [0.3, 0, 0.6, 0.6],
+];
+
+describe('cubicBezier', () => {
+ it.each(CURVES)('matches the parametric curve (%s)', (...points) => {
+ const [x1, y1, x2, y2] = points;
+ const ease = cubicBezier(points);
+ const axis = (a: number, b: number, t: number) =>
+ 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3;
+ for (let t = 0; t <= 1; t += 1 / 256) {
+ expect(ease(axis(x1, x2, t))).toBeCloseTo(axis(y1, y2, t), 5);
+ }
+ });
+
+ it('runs from 0 to 1 and clamps outside', () => {
+ for (const points of CURVES) {
+ const ease = cubicBezier(points);
+ expect(ease(0)).toBe(0);
+ expect(ease(1)).toBe(1);
+ expect(ease(-0.5)).toBe(0);
+ expect(ease(1.5)).toBe(1);
+ }
+ });
+
+ it('ease-in-out is symmetric about its midpoint', () => {
+ const ease = cubicBezier(timing.curves.move);
+ expect(ease(0.5)).toBeCloseTo(0.5, 9);
+ for (let x = 0; x <= 0.5; x += 0.05) {
+ expect(ease(x) + ease(1 - x)).toBeCloseTo(1, 6);
+ }
+ });
+});
diff --git a/packages/core/src/motion/bezier.ts b/packages/core/src/motion/bezier.ts
new file mode 100644
index 0000000000..8f1613635d
--- /dev/null
+++ b/packages/core/src/motion/bezier.ts
@@ -0,0 +1,64 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file bezier.ts
+ * @input Cubic-bézier control points [x1, y1, x2, y2]
+ * @output Exports `cubicBezier`, the timing function CSS and Core Animation
+ * define by those points (progress → eased progress)
+ * @position Pure math under the animator (the Reduced Motion cross-fade runs
+ * on Core Animation's named curves); no DOM, no React
+ *
+ * The curve runs from (0, 0) to (1, 1) with the two given control points;
+ * x is time, y is progress. Solved for x by Newton's method with a bisection
+ * fallback, the approach browser engines use for CSS `cubic-bezier()`.
+ *
+ * SYNC: When modified, update /packages/core/src/motion/bezier.test.ts
+ */
+
+export type BezierPoints = readonly [number, number, number, number];
+
+/** The timing function for `points`: maps time progress to eased progress. */
+export function cubicBezier([x1, y1, x2, y2]: BezierPoints): (
+ x: number,
+) => number {
+ const cx = 3 * x1;
+ const bx = 3 * (x2 - x1) - cx;
+ const ax = 1 - cx - bx;
+ const cy = 3 * y1;
+ const by = 3 * (y2 - y1) - cy;
+ const ay = 1 - cy - by;
+ const sampleX = (t: number) => ((ax * t + bx) * t + cx) * t;
+ const sampleY = (t: number) => ((ay * t + by) * t + cy) * t;
+ const slopeX = (t: number) => (3 * ax * t + 2 * bx) * t + cx;
+ const solveT = (x: number) => {
+ let t = x;
+ for (let i = 0; i < 8; i++) {
+ const error = sampleX(t) - x;
+ if (Math.abs(error) < 1e-7) {
+ return t;
+ }
+ const slope = slopeX(t);
+ if (Math.abs(slope) < 1e-6) {
+ break;
+ }
+ t -= error / slope;
+ }
+ let lo = 0;
+ let hi = 1;
+ t = x;
+ for (let i = 0; i < 60; i++) {
+ const value = sampleX(t);
+ if (Math.abs(value - x) < 1e-7) {
+ break;
+ }
+ if (value < x) {
+ lo = t;
+ } else {
+ hi = t;
+ }
+ t = (lo + hi) / 2;
+ }
+ return t;
+ };
+ return x => (x <= 0 ? 0 : x >= 1 ? 1 : sampleY(solveT(x)));
+}
diff --git a/packages/core/src/motion/coast.test.ts b/packages/core/src/motion/coast.test.ts
new file mode 100644
index 0000000000..9c314d0251
--- /dev/null
+++ b/packages/core/src/motion/coast.test.ts
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file coast.test.ts
+ * @input vitest, coast.ts, and the decay and spring math it composes
+ * @output Checks each momentum curve `coast` builds against the closed-form
+ * coast and edge spring: inside the bounds, through an edge, released past
+ * an edge, at rest, from the presentation value at the release time
+ * @position Testing; pure, with a stand-in for the animator's `get`
+ */
+
+import {describe, expect, it} from 'vitest';
+import type {Animator, MotionProperty} from './animator';
+import {coast} from './coast';
+import {solveDecay} from './decay';
+import {solveSpring, toSpring} from './spring';
+import {scroll} from './uikit/scroll';
+
+/** An animator whose presentation values are fixed, recording `get` times. */
+function at(values: Partial<Record<MotionProperty, number>>) {
+ const reads: (number | undefined)[] = [];
+ const animator = {
+ get(property: MotionProperty, time?: number) {
+ reads.push(time);
+ return values[property] ?? 0;
+ },
+ } as unknown as Animator;
+ return {animator, reads};
+}
+
+describe('coast', () => {
+ it('follows the coast from the presentation value and ends where it projects', () => {
+ const {animator} = at({y: 40});
+ const {y} = coast(animator, {y: -2400});
+ const glide = solveDecay({from: 40, velocity: -2400});
+ expect(y).toBeDefined();
+ for (const t of [0, 0.016, 0.1, 0.4, 1.2]) {
+ expect(y!.at(t)).toBeCloseTo(glide.value(t), 9);
+ expect(y!.velocity(t)).toBeCloseTo(glide.velocity(t), 9);
+ }
+ expect(y!.at(y!.duration)).toBe(glide.rest);
+ });
+
+ it('hands the coast\u2019s velocity to the edge spring where it reaches an edge', () => {
+ const {animator} = at({y: -100});
+ const {y} = coast(animator, {y: 3000}, {bounds: {y: {min: -2000, max: 0}}});
+ const glide = solveDecay({from: -100, velocity: 3000});
+ const hit = glide.timeToReach(0) as number;
+ expect(y!.at(hit)).toBeCloseTo(0, 6);
+ expect(y!.velocity(hit - 1e-9)).toBeCloseTo(y!.velocity(hit + 1e-9), 2);
+ // It overshoots past the edge, then comes back to it.
+ expect(y!.at(hit + 0.06)).toBeGreaterThan(0);
+ expect(y!.at(y!.duration)).toBe(0);
+ });
+
+ it('springs straight back with the release velocity when released past an edge', () => {
+ const {animator} = at({x: 60});
+ const {x} = coast(animator, {x: 400}, {bounds: {x: {min: -500, max: 0}}});
+ const back = solveSpring(toSpring(scroll.bounce), {
+ from: 60,
+ to: 0,
+ velocity: 400,
+ });
+ expect(x!.velocity(0)).toBeCloseTo(400, 6);
+ expect(x!.at(0.1)).toBeCloseTo(back.value(0.1), 9);
+ expect(x!.at(x!.duration)).toBe(0);
+ });
+
+ it('rests where it is at zero velocity inside its bounds', () => {
+ const {animator} = at({x: -30});
+ const {x} = coast(animator, {x: 0}, {bounds: {x: {min: -100, max: 0}}});
+ expect(x!.duration).toBe(0);
+ expect(x!.at(0)).toBe(-30);
+ });
+
+ it('reads the presentation value at the release time, and scale sets both scales', () => {
+ const {animator, reads} = at({scaleX: 1, scaleY: 1});
+ const curves = coast(animator, {scale: 0.5, scaleY: 0.2}, {at: 1234});
+ expect(Object.keys(curves).sort()).toEqual(['scaleX', 'scaleY']);
+ expect(curves.scaleX!.velocity(0)).toBeCloseTo(0.5, 9);
+ expect(curves.scaleY!.velocity(0)).toBeCloseTo(0.2, 9);
+ expect(reads).toEqual([1234, 1234]);
+ });
+
+ it('coasts at the given rate', () => {
+ const {animator} = at({x: 0});
+ const {x} = coast(
+ animator,
+ {x: 1000},
+ {rate: scroll.decelerationRate.fast},
+ );
+ const glide = solveDecay({
+ from: 0,
+ velocity: 1000,
+ rate: scroll.decelerationRate.fast,
+ });
+ expect(x!.at(x!.duration)).toBe(glide.rest);
+ });
+});
diff --git a/packages/core/src/motion/coast.ts b/packages/core/src/motion/coast.ts
new file mode 100644
index 0000000000..8f5d85101e
--- /dev/null
+++ b/packages/core/src/motion/coast.ts
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file coast.ts
+ * @input An animator, release velocities, and optional edges, deceleration
+ * rate and edge spring
+ * @output Exports `coast`: the momentum curves of a released scroll view
+ * (UIScrollView's coast, handing its velocity to an edge spring at a bound)
+ * for `Animator.decay` to play; and its `CoastOptions`
+ * @position Motion foundation, pure math over an animator's presentation
+ * values. Only a surface that coasts imports it, so the coast math and the
+ * scroll table stay out of every other caller of the animator.
+ *
+ * Each property starts at its presentation value (`animator.get`), so a coast
+ * continues whatever was running without a jump:
+ * - inside its bounds, it coasts at `rate` (decay.ts) and comes to rest where
+ * it projects;
+ * - a coast that reaches an edge hands its velocity at the contact to the
+ * edge spring, which settles on the edge;
+ * - released past an edge, it springs straight back with the release
+ * velocity: a transition, not momentum, so under Reduce Motion `decay`
+ * plays it as `animate` does, a cross-fade on a coarse pointer and at once
+ * on any other (`design:reduced-motion` DR2, DR3);
+ * - at zero velocity inside its bounds, it rests where it is.
+ *
+ * SYNC: When modified, update coast.test.ts.
+ */
+
+import {
+ SETTLE_THRESHOLD,
+ type Animator,
+ type MotionCurve,
+ type MotionProperty,
+ type MotionValues,
+} from './animator';
+import {solveDecay} from './decay';
+import {solveSpring, toSpring, type SpringDescription} from './spring';
+import {scroll} from './uikit/scroll';
+
+export interface CoastOptions {
+ /** Per-millisecond velocity factor; UIScrollView's normal rate by default. */
+ rate?: number;
+ /** Edges: a coast crossing one hands its velocity to `bounce`. */
+ bounds?: Partial<Record<MotionProperty, {min: number; max: number}>>;
+ /** The edge spring; `scroll.bounce` by default. */
+ bounce?: SpringDescription;
+ /**
+ * The release time on the document timeline (ms, `performance.now()`
+ * clock); now by default. Pass the same `at` to `decay`.
+ */
+ at?: number;
+}
+
+/** A curve that holds `end` from `duration` on. */
+function settling(
+ duration: number,
+ end: number,
+ at: (t: number) => number,
+ velocity: (t: number) => number,
+): MotionCurve {
+ return {
+ duration,
+ at: t => (t >= duration ? end : at(t)),
+ velocity: t => (t >= duration ? 0 : velocity(t)),
+ };
+}
+
+/**
+ * The momentum curves of a release with `velocity` (units per second for
+ * each property; `scale` sets both scales), for `animator.decay`.
+ *
+ * @example
+ * ```
+ * animator.decay(
+ * coast(animator, {x: velocityX}, {bounds: {x: {min: -maxScroll, max: 0}}}),
+ * );
+ * ```
+ */
+export function coast(
+ animator: Animator,
+ velocity: MotionValues,
+ options: CoastOptions = {},
+): Partial<Record<MotionProperty, MotionCurve>> {
+ const known = Object.keys(SETTLE_THRESHOLD) as MotionProperty[];
+ const velocities: Partial<Record<MotionProperty, number>> = {};
+ for (const [key, value] of Object.entries(velocity)) {
+ if (value == null || !Number.isFinite(value)) {
+ continue;
+ }
+ if (key === 'scale') {
+ velocities.scaleX ??= value;
+ velocities.scaleY ??= value;
+ } else if ((known as ReadonlyArray<string>).includes(key)) {
+ velocities[key as MotionProperty] = value;
+ }
+ }
+ const rate = options.rate ?? scroll.decelerationRate.normal;
+ const bounce = toSpring(options.bounce ?? scroll.bounce);
+ const curves: Partial<Record<MotionProperty, MotionCurve>> = {};
+ for (const [key, v0] of Object.entries(velocities) as [
+ MotionProperty,
+ number,
+ ][]) {
+ const from = animator.get(key, options.at);
+ const bounds = options.bounds?.[key];
+ const threshold = SETTLE_THRESHOLD[key];
+ if (bounds != null && (from < bounds.min || from > bounds.max)) {
+ // Released past an edge: straight back with the release velocity.
+ const edge = from < bounds.min ? bounds.min : bounds.max;
+ const back = solveSpring(bounce, {from, to: edge, velocity: v0});
+ curves[key] = {
+ ...settling(
+ back.settleTime(threshold),
+ edge,
+ t => back.value(t),
+ t => back.velocity(t),
+ ),
+ // A spring the release starts, not momentum (Reduce Motion: DR2).
+ isTransition: true,
+ };
+ continue;
+ }
+ const glide = solveDecay({from, velocity: v0, rate});
+ const edge =
+ bounds == null
+ ? null
+ : glide.rest < bounds.min
+ ? bounds.min
+ : glide.rest > bounds.max
+ ? bounds.max
+ : null;
+ const hit = edge == null ? null : glide.timeToReach(edge);
+ if (edge != null && hit != null) {
+ // The coast reaches the edge: the edge spring takes its velocity.
+ const spring = solveSpring(bounce, {
+ from: edge,
+ to: edge,
+ velocity: glide.velocity(hit),
+ });
+ curves[key] = settling(
+ hit + spring.settleTime(threshold),
+ edge,
+ t => (t < hit ? glide.value(t) : spring.value(t - hit)),
+ t => (t < hit ? glide.velocity(t) : spring.velocity(t - hit)),
+ );
+ } else if (v0 === 0) {
+ curves[key] = settling(
+ 0,
+ from,
+ () => from,
+ () => 0,
+ );
+ } else {
+ curves[key] = settling(
+ glide.settleTime(threshold * 2),
+ edge ?? glide.rest,
+ t => glide.value(t),
+ t => glide.velocity(t),
+ );
+ }
+ }
+ return curves;
+}
diff --git a/packages/core/src/motion/uikit/timing.ts b/packages/core/src/motion/uikit/timing.ts
index e67f5a02dc..7402302c9a 100644
--- a/packages/core/src/motion/uikit/timing.ts
+++ b/packages/core/src/motion/uikit/timing.ts
@@ -83,6 +83,45 @@ export const press = {
buttonReleaseMs: 250,
} as const;
+/**
+ * The Reduce Motion fade, its own export so the animator reads it without
+ * the rest of the table (`architecture:component-style-authoring` INV6).
+ * `timing` composes it under its table paths, `reducedMotionCrossFadeMs` and
+ * `curves.move`, so their roles are unchanged.
+ */
+export const reducedMotionCrossFade = {
+ /**
+ * Reduce Motion with Prefer Cross-Fade Transitions: a navigation push or pop
+ * becomes a cross-fade of this length on `curves.move` (the new view
+ * fades in while the old one fades out, with no travel), in ms. Sheets,
+ * full-screen modals and alerts fade on their own presentation spring
+ * instead. A reference reading only: under reduced motion a touch
+ * presentation follows `design:reduced-motion` DR2 and DR4, not this clock
+ * (`spec:AST-094` FR8).
+ * @source apple-docs https://developer.apple.com/documentation/uikit/uiaccessibility/preferscrossfadetransitions
+ * (the setting)
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, CAAnimation dump with Reduce Motion and Prefer
+ * Cross-Fade Transitions on (opacity CABasicAnimation 0.5 s,
+ * (0.42, 0, 0.58, 1)), Oct 23 2026
+ */
+ durationMs: 500,
+ /**
+ * `easeInEaseOut`; UIKit's default curve (`UIView.AnimationCurve
+ * .easeInOut`, "the default curve for most animations").
+ * @source apple-docs https://developer.apple.com/documentation/quartzcore/camediatimingfunctionname/easeineaseout
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, CAMediaTimingFunction read from UIView.animate,
+ * Oct 23 2026
+ */
+ curve: [0.42, 0, 0.58, 1],
+} as const;
+
+// `timing` composes the fade from bindings, not property reads, so a bundle
+// that reads only the fade drops the rest of the table.
+const {durationMs: reducedMotionCrossFadeMs, curve: move} =
+ reducedMotionCrossFade;
+
export const timing = {
press,
curves: {
@@ -95,15 +134,8 @@ export const timing = {
* Oct 23 2026
*/
viewChange: [0.25, 0.1, 0.25, 1],
- /**
- * `easeInEaseOut`; UIKit's default curve (`UIView.AnimationCurve
- * .easeInOut`, "the default curve for most animations").
- * @source apple-docs https://developer.apple.com/documentation/quartzcore/camediatimingfunctionname/easeineaseout
- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
- * iPhone 17 Pro, CAMediaTimingFunction read from UIView.animate,
- * Oct 23 2026
- */
- move: [0.42, 0, 0.58, 1],
+ // The Reduce Motion fade's curve, sourced on `reducedMotionCrossFade`.
+ move,
/**
* `easeIn`.
* @source apple-docs https://developer.apple.com/documentation/quartzcore/camediatimingfunctionname/easein
@@ -145,22 +177,8 @@ export const timing = {
* iPhone 17 Pro, read, Oct 23 2026
*/
stateChangeMs: 250,
- /**
- * Reduce Motion with Prefer Cross-Fade Transitions: a navigation push or pop
- * becomes a cross-fade of this length on `curves.move` (the new view
- * fades in while the old one fades out, with no travel), in ms. Sheets,
- * full-screen modals and alerts fade on their own presentation spring
- * instead. A reference reading only: under reduced motion a touch
- * presentation follows `design:reduced-motion` DR2 and DR4, not this clock
- * (`spec:AST-094` FR8).
- * @source apple-docs https://developer.apple.com/documentation/uikit/uiaccessibility/preferscrossfadetransitions
- * (the setting)
- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
- * iPhone 17 Pro, CAAnimation dump with Reduce Motion and Prefer
- * Cross-Fade Transitions on (opacity CABasicAnimation 0.5 s,
- * (0.42, 0, 0.58, 1)), Oct 23 2026
- */
- reducedMotionCrossFadeMs: 500,
+ // The Reduce Motion fade's length, sourced on `reducedMotionCrossFade`.
+ reducedMotionCrossFadeMs,
} as const;
/**
diff --git a/packages/core/src/motion/uikit/uikit.test.ts b/packages/core/src/motion/uikit/uikit.test.ts
index 7783bdd8d3..9b97ab9b79 100644
--- a/packages/core/src/motion/uikit/uikit.test.ts
+++ b/packages/core/src/motion/uikit/uikit.test.ts
@@ -82,6 +82,16 @@ function leavesOf(file: string): Leaf[] {
starts.push(index);
}
});
+ // Values bound from one of those groups (`const {curve: move} = group;`)
+ // are checked where the group declares them too.
+ const bindings = /^const \{([^}]+)\} =\s*(?:\n\s*)?(\w+);/gm;
+ for (const [, names, group] of text.matchAll(bindings)) {
+ if (exported.has(group)) {
+ for (const name of names.split(',')) {
+ exported.add(name.split(':').pop()!.trim());
+ }
+ }
+ }
expect(starts.length).toBeGreaterThan(0);
return [
...starts.flatMap(start => leavesFrom(file, lines, start, exported)),