An open source design system that's fully customizable and agent ready
TypeScript
chore(core): the animator plans Reduce Motion in its own module, shares a track per element and starts at the commit (#8056)
Christopher Chedeau2c4f1728b433
diff --git a/.changeset/uikit-motion-animator-reduced-motion.md b/.changeset/uikit-motion-animator-reduced-motion.mdnew file mode 100644index 0000000000..4dc42ecde1--- /dev/null+++ b/.changeset/uikit-motion-animator-reduced-motion.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the touch presentations' animator follows design:reduced-motion (under Reduce Motion, an opacity-only cross-fade of 200 ms on a coarse pointer or after a touch release and an immediate change on any other pointer, with no option or theme value that keeps travel or lengthens the fade; an entrance or exit role orients a slide that changes no opacity), decided by its own planner module, and starts a call from rest when the browser commits it, as Core Animation does. Not exported from the package entry point.++@vjeuxdiff --git a/.changeset/uikit-motion-animator.md b/.changeset/uikit-motion-animator.mdindex 83e8f2b68c..d489e3022e 100644--- a/.changeset/uikit-motion-animator.md+++ b/.changeset/uikit-motion-animator.md@@ -2,6 +2,6 @@'@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.+[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 momentum, and sends a spring back from past an edge through the Reduce Motion policy: a cross-fade on a coarse pointer or after a touch release, at once elsewhere) 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.@vjeuxdiff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.mdindex 96b5578d38..e22ced5450 100644--- a/packages/core/src/motion/MEASUREMENTS.md+++ b/packages/core/src/motion/MEASUREMENTS.md@@ -37,27 +37,27 @@ installed); rows marked † also on iOS 18 for the pre-glass delta. iPhone## Shared (foundation)-| ID | What | App and gesture | Extract | Method | Feeds |-| ----- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------- |-| M-S1 | Deceleration rates | none | `UIScrollView.DecelerationRate.normal.rawValue`, `.fast.rawValue` | D | `scroll.decelerationRate` |-| M-S2 | Momentum coast | A long list (Contacts, or a probe table of 500 rows): flicks released at 1000, 2500, 5000 pt/s | contentOffset(t) from release to rest; decay constant; per-millisecond vs per-frame model; the speed at which it stops | C | `scroll.decelerationRate` |-| M-S3 | Bounce-back spring | Same list: drag 120 pt past the top, hold still, release; a flick into the top edge at 3000 pt/s | contentOffset(t) after release and after edge contact; spring response and damping ratio; velocity hand-off | C | `scroll.bounce` |-| M-S5 | Rubber band | Same list on an 852 pt view: drag 100, 300, 600 pt past the top; a horizontal pager | displayed overflow against finger overflow; confirm c = 0.55 and d = the view's size on the axis | C | `scroll.rubberBand` |-| M-PG1 | Paging | Photos full-screen swipes; a probe paging scroll view | page chosen per release position × velocity (thresholds; at most one page?); contentOffset(t) onto the page | B, C | `scroll.paging` |-| M-ST1 | Scroll to top | Settings scrolled down 500, 2000, 8000 pt; tap the status bar | contentOffset(t); duration against distance; curve or spring fit | B, C | `scroll.scrollToTopRate` |-| M-N1 | Navigation push | Settings: tap General | incoming leading edge x(t), outgoing x(t) (parallax fraction), dimming alpha(t); animation parameters | A, B | `springs.navigationPush` |-| M-N2 | Navigation pop | General: back button | same as M-N1 | A, B | `springs.navigationPop` |-| M-N3 | Interactive pop | Settings ▸ General: edge swipe released at 40 % of the width at 600 pt/s (finishes) and at 30 % at rest (cancels) | x(t) after release; spring parameters; the finish / cancel rule (position, velocity) | A, B | `springs.navigationInteractivePopFinish` |-| M-A1 | Alert | Probe app: `UIAlertController(.alert)` presented and dismissed | scale(t), alpha(t) of the alert and the dimming view; animation parameters | A | `springs.alertPresent`, `.alertDismiss` |-| M-AS1 | Action sheet and menu | Probe app: `.actionSheet`; a button with a `UIMenu` as its primary action; Files: the … menu | scale, alpha, position (t) on open and close; animation parameters | A, B | `springs.actionSheet*`, `.menu*` |-| M-CM1 | Context menu | Files: long-press an item; dismiss by tapping outside | preview scale(t) on lift, backdrop blur and dim (t), menu scale(t); the preview's return on dismiss | A, B | `springs.contextMenu*` |-| M-K1 | UIKit legacy spring | Probe app: `UIView.animate(withDuration:usingSpringWithDamping:initialSpringVelocity:)`, durations 0.3, 0.5, 1 × ratios 0.5, 0.8, 1 × velocities 0, 2 | the `CASpringAnimation` UIKit attaches: mass, stiffness, damping, initialVelocity, duration, settlingDuration | A | `springs.ts` (UIKit's legacy springs) |-| M-K2 | Default spring, keyboard | Probe app: an animator with `UISpringTimingParameters()`; focus and blur a text field | both springs' parameters and allowsOverdamping; the keyboard notification's duration and curve | A, D | `springs.viewChange`, `.keyboard`, `timing.keyboard*` |-| M-CA1 | Settling duration | none: `CASpringAnimation` mass 1, stiffness 100, damping 5, 10, 15, 20, 40 × initialVelocity 0, 5, −5 × allowsOverdamping on, off | `settlingDuration` of each (checks the critically damped and overdamped branches) | D | `springs.ts` (settling) |-| M-T1 | Banner | A notification pushed to the simulator while an app is in the foreground | banner y(t) in and out; time on screen | B | `springs.banner` |-| M-RM1 | Reduced Motion | Reduce Motion on, Prefer Cross-Fade Transitions on and off: Settings push and pop, an alert (sheets: M-SH13; controls: M-SW11, M-SL12, M-SG15) | which transitions become cross-fades; alpha(t), duration and curve; what still moves | B | `timing.reducedMotionCrossFadeMs` (a reference reading, not played: `spec:AST-094` FR8) |-| M-PR1 | Press release curve | Settings and Contacts: a row tapped and released (the deselect cross-fade) | the timing function Core Animation attaches to the deselect fade (control points) | A | `timing.press.highlightOutCurve` |-| M-NB1 | Navigation bar hide / show | none | `UINavigationController.hideShowBarDuration` | D | `timing.navigationBarHideShowMs` |+| ID | What | App and gesture | Extract | Method | Feeds |+| ----- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |+| M-S1 | Deceleration rates | none | `UIScrollView.DecelerationRate.normal.rawValue`, `.fast.rawValue` | D | `scroll.decelerationRate` |+| M-S2 | Momentum coast | A long list (Contacts, or a probe table of 500 rows): flicks released at 1000, 2500, 5000 pt/s | contentOffset(t) from release to rest; decay constant; per-millisecond vs per-frame model; the speed at which it stops | C | `scroll.decelerationRate` |+| M-S3 | Bounce-back spring | Same list: drag 120 pt past the top, hold still, release; a flick into the top edge at 3000 pt/s | contentOffset(t) after release and after edge contact; spring response and damping ratio; velocity hand-off | C | `scroll.bounce` |+| M-S5 | Rubber band | Same list on an 852 pt view: drag 100, 300, 600 pt past the top; a horizontal pager | displayed overflow against finger overflow; confirm c = 0.55 and d = the view's size on the axis | C | `scroll.rubberBand` |+| M-PG1 | Paging | Photos full-screen swipes; a probe paging scroll view | page chosen per release position × velocity (thresholds; at most one page?); contentOffset(t) onto the page | B, C | `scroll.paging` |+| M-ST1 | Scroll to top | Settings scrolled down 500, 2000, 8000 pt; tap the status bar | contentOffset(t); duration against distance; curve or spring fit | B, C | `scroll.scrollToTopRate` |+| M-N1 | Navigation push | Settings: tap General | incoming leading edge x(t), outgoing x(t) (parallax fraction), dimming alpha(t); animation parameters | A, B | `springs.navigationPush` |+| M-N2 | Navigation pop | General: back button | same as M-N1 | A, B | `springs.navigationPop` |+| M-N3 | Interactive pop | Settings ▸ General: edge swipe released at 40 % of the width at 600 pt/s (finishes) and at 30 % at rest (cancels) | x(t) after release; spring parameters; the finish / cancel rule (position, velocity) | A, B | `springs.navigationInteractivePopFinish` |+| M-A1 | Alert | Probe app: `UIAlertController(.alert)` presented and dismissed | scale(t), alpha(t) of the alert and the dimming view; animation parameters | A | `springs.alertPresent`, `.alertDismiss` |+| M-AS1 | Action sheet and menu | Probe app: `.actionSheet`; a button with a `UIMenu` as its primary action; Files: the … menu | scale, alpha, position (t) on open and close; animation parameters | A, B | `springs.actionSheet*`, `.menu*` |+| M-CM1 | Context menu | Files: long-press an item; dismiss by tapping outside | preview scale(t) on lift, backdrop blur and dim (t), menu scale(t); the preview's return on dismiss | A, B | `springs.contextMenu*` |+| M-K1 | UIKit legacy spring | Probe app: `UIView.animate(withDuration:usingSpringWithDamping:initialSpringVelocity:)`, durations 0.3, 0.5, 1 × ratios 0.5, 0.8, 1 × velocities 0, 2 | the `CASpringAnimation` UIKit attaches: mass, stiffness, damping, initialVelocity, duration, settlingDuration | A | `springs.ts` (UIKit's legacy springs) |+| M-K2 | Default spring, keyboard | Probe app: an animator with `UISpringTimingParameters()`; focus and blur a text field | both springs' parameters and allowsOverdamping; the keyboard notification's duration and curve | A, D | `springs.viewChange`, `.keyboard`, `timing.keyboard*` |+| M-CA1 | Settling duration | none: `CASpringAnimation` mass 1, stiffness 100, damping 5, 10, 15, 20, 40 × initialVelocity 0, 5, −5 × allowsOverdamping on, off | `settlingDuration` of each (checks the critically damped and overdamped branches) | D | `springs.ts` (settling) |+| M-T1 | Banner | A notification pushed to the simulator while an app is in the foreground | banner y(t) in and out; time on screen | B | `springs.banner` |+| M-RM1 | Reduced Motion | Reduce Motion on, Prefer Cross-Fade Transitions on and off: Settings push and pop, an alert (sheets: M-SH13; controls: M-SW11, M-SL12, M-SG15) | which transitions become cross-fades; alpha(t), duration and curve; what still moves | B | `timing.reducedMotionCrossFadeMs` (played at 200 ms: `design:reduced-motion` DR2 caps it, DEC-1 of 2026-10-24, departing from the measured 0.5 s) |+| M-PR1 | Press release curve | Settings and Contacts: a row tapped and released (the deselect cross-fade) | the timing function Core Animation attaches to the deselect fade (control points) | A | `timing.press.highlightOutCurve` |+| M-NB1 | Navigation bar hide / show | none | `UINavigationController.hideShowBarDuration` | D | `timing.navigationBarHideShowMs` |Done (UIKit lab, iOS 26.2 simulator, Oct 23 2026; values in `uikit/` tagged`measured:`): M-S1, M-NB1, M-K2, M-CA1 (underdamped grid matched to the lastdiff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex 8b8fa725a5..e25d5c6346 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -11,22 +11,23 @@ so each keeps its measured value; no shipped component reads the roles yet.## Files-| File | What it is |-| --------------------- | ----------------------------------------------------------------------------------------------------------------------- |-| `uikit/` | THE constants table: every spring, duration, deceleration rate, rubber-band constant and curve, with its source. |-| `uikit/springs.ts` | Interaction springs (navigation, sheets, alerts, menus, controls, keyboard, banners) and the SwiftUI / UIKit presets. |-| `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, paging, `delaysContentTouches`, scroll to top. |-| `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. |-| `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. |-| `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). |-| `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. |+| File | What it is |+| ---------------------- | -------------------------------------------------------------------------------------------------------------------------- |+| `uikit/` | THE constants table: every spring, duration, deceleration rate, rubber-band constant and curve, with its source. |+| `uikit/springs.ts` | Interaction springs (navigation, sheets, alerts, menus, controls, keyboard, banners) and the SwiftUI / UIKit presets. |+| `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, paging, `delaysContentTouches`, scroll to top. |+| `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. |+| `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. |+| `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). |+| `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 coasts compiled to Web Animations, read back analytically. |+| `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. |Component-specific values (a sheet's detents, a switch's geometry, a contextmenu's timeline) live in a domain file per component, `uikit/<component>.ts`,@@ -36,6 +37,7 @@ under the same rules.```import {createAnimator} from '../motion/animator';+import {coast} from '../motion/coast';import {springs} from '../motion/uikit';const animator = createAnimator(sheet);@@ -61,25 +63,52 @@ await handle.finished; // true if it ran to the end, false if interrupted`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.+- Promotion: every animation the animator creates, and every `set`, gives its+ channels a compositing layer in the same task (inline `will-change`, merged+ with the element's own), cleared 500 ms after the last motion. Mobile Safari+ needs it to run a curve through a blocked main thread.+- `atRest(properties)` resolves once none of them is moving, after the last+ curve ends, whoever started it.+- `rebase({y: -shift})` moves properties at once, as a layout shift does; a+ property moving on a spring keeps its spring, velocity and target.- `animate` always starts from the presentation value with the presentationvelocity 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.+- A call from rest gets no start time, so the browser starts it when it+ commits it, as Core Animation does: in Chromium a block before that frame+ delays the motion instead of skipping into it (WebKit starts it at the+ frame before the block). Everything the call starts shares that start+ (`handle.started`); a retarget keeps an explicit one, and `{at}` puts+ several animators on one clock.+- Reduced Motion (`prefers-reduced-motion: reduce`, design:reduced-motion):+ every `animate` is replaced and nothing moves, scales or+ springs. On a coarse primary pointer, or for a call started by a touch+ drag's release (`{touchRelease: true}`), it is an opacity-only cross-fade+ of `timing.reducedMotionCrossFadeMs` (200 ms): an entrance from 0 lands and+ fades in, an exit to 0 fades out then lands, an opacity change fades, any+ other move dips (fade out, land, fade in). Travel lands with a plain style write while+ the element is transparent, never as an animated transform. On any other+ pointer it completes at once.+ `{crossfadeAs: 'entrance'}` or `'exit'` gives a slide that changes no+ opacity its direction. No option or theme value lengthens the fade or keeps+ travel. For motion the animator does not drive, `reducedMotionFade()`+ answers the same policy, and `reducedMotion.stylex.ts` holds its CSS+ constants and the two media queries a StyleX transition spells.+ A decay's momentum keeps its motion under Reduce Motion: momentum that+ continues a throw is direct movement (DR2, DEC-2). A curve marked+ `isTransition` (a coast's spring back from past an edge), like a spring a+ component starts on release toward a target it picks, plays through the+ Reduce Motion policy: a cross-fade on a coarse pointer or after a touch+ release (`decay(curves, {touchRelease: true})`), at once elsewhere.+- `animatorFor(element)` returns the one animator for an element, so code+ that animates it from several places (a swipe on x, a removal on y)+ composes in one `translate` track.### How it stays on the compositorEach 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,+interpolation is within 0.05 px, and played with `easing: linear` on one+start time. 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 theframe an animation ends needs no main thread and shows no flicker, even whendiff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex eaf35560ee..5b71a32d7c 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -9,15 +9,22 @@* 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)+ * @position Testing; what the compositor plays (frames advancing through a+ * blocked main thread) needs a real browser, which these tests do not+ * cover*/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 {+ animatorFor,+ createAnimator,+ END_HOLD_MS,+ PROMOTION_LINGER_MS,+ type AnimatorOptions,+} from './animator';import {cubicBezier} from './bezier';import {coast} from './coast';import {solveDecay} from './decay';@@ -31,15 +38,29 @@ interface Recorded {keyframes: Keyframe[];options: KeyframeAnimationOptions;startTime: number | null;+ /** The fake clock when it was created (a pending start reads from it). */+ createdAt: number;cancelled: boolean;/** A sampler holding it (the interaction harness pauses to seek). */paused: boolean;- readonly playState: 'idle' | 'paused' | 'running';+ /** Frames a resumed (play()) animation still waits for its start. */+ startDelayFrames: number;+ /** Finished from outside (a sampler's `finish()`), keeping its start. */+ finished: boolean;+ readonly playState: 'idle' | 'paused' | 'running' | 'finished';+ ready: Promise<Recorded>;+ commit(at: number): void;+ finish(): void;cancel(): void;}let clock = 1000;let recorded: Recorded[] = [];+/** Callbacks waiting for the next animation frame (`requestFrame`). */+let frameQueue: (() => void)[] = [];+const requestFrame = (callback: () => void) => {+ frameQueue.push(callback);+};/*** What the page's stylesheet sets, by property. Computed style reads it* under the inline value (jsdom keeps stale computed values for these@@ -50,6 +71,7 @@ let stylesheet: Record<string, string> = {};beforeEach(() => {clock = 1000;recorded = [];+ frameQueue = [];stylesheet = {};vi.spyOn(window, 'getComputedStyle').mockImplementation(element =>@@ -61,18 +83,57 @@ beforeEach(() => {);vi.useFakeTimers();HTMLElement.prototype.animate = function (keyframes, options) {+ let resolveReady: (a: Recorded) => void = () => {};+ let rejectReady: (e: Error) => void = () => {};+ const ready = new Promise<Recorded>((resolve, reject) => {+ resolveReady = resolve;+ rejectReady = reject;+ });+ // Like a browser: a pending animation (no start time) starts at the next+ // committed frame; setting a start time, or a cancel, settles `ready`.+ let start: number | null = null;const animation: Recorded = {element: this,keyframes: keyframes as Keyframe[],options: options as KeyframeAnimationOptions,- startTime: null,+ get startTime() {+ return start;+ },+ set startTime(value) {+ start = value;+ resolveReady(animation);+ },+ createdAt: clock,cancelled: false,paused: false,+ finished: false,get playState() {- return this.cancelled ? 'idle' : this.paused ? 'paused' : 'running';+ return this.cancelled+ ? 'idle'+ : this.finished+ ? 'finished'+ : this.paused+ ? 'paused'+ : 'running';+ },+ ready,+ commit(at) {+ // A paused animation's pending pause completes without a start; one+ // resumed with play() gets its start a frame later.+ if (this.startDelayFrames > 0) {+ this.startDelayFrames -= 1;+ } else if (!this.cancelled && start == null && !this.paused) {+ start = at;+ }+ resolveReady(this);+ },+ startDelayFrames: 0,+ finish() {+ this.finished = true;},cancel() {this.cancelled = true;+ rejectReady(new Error('AbortError'));},};recorded.push(animation);@@ -81,23 +142,70 @@ beforeEach(() => {});afterEach(() => {+ vi.unstubAllGlobals();Reflect.deleteProperty(HTMLElement.prototype, 'animate');vi.useRealTimers();vi.restoreAllMocks();});-function setup(options: AnimatorOptions = {}) {+/**+ * The person's settings, through `matchMedia` as the animator reads them: no+ * option overrides them.+ */+function stubMedia(reduced: boolean, coarse: boolean) {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query.includes('prefers-reduced-motion')+ ? reduced+ : query.includes('pointer: coarse')+ ? coarse+ : false,+ media: query,+ onchange: null,+ addEventListener: () => {},+ removeEventListener: () => {},+ addListener: () => {},+ removeListener: () => {},+ dispatchEvent: () => false,+ }));+}++function setup({+ reduced = false,+ coarse = false,+ ...options+}: AnimatorOptions & {reduced?: boolean; coarse?: boolean} = {}) {+ stubMedia(reduced, coarse);const element = document.createElement('div');const animator = createAnimator(element, {now: () => clock,- prefersReducedMotion: () => false,+ requestFrame,...options,});return {element, animator};}-/** Advances the injected clock and the timers together. */+/** The browser commits a frame at `at`: pending animations start there. */+async function commitFrame(at: number) {+ for (const animation of recorded) {+ if (animation.startTime == null && !animation.cancelled) {+ animation.commit(at);+ }+ }+ const frames = frameQueue;+ frameQueue = [];+ for (const callback of frames) {+ callback();+ }+ await Promise.resolve();+ await Promise.resolve();+}++/**+ * Advances the injected clock and the timers together. The browser commits+ * pending animations at the next frame, here at once.+ */async function advance(ms: number) {+ await commitFrame(clock);clock += ms;await vi.advanceTimersByTimeAsync(ms);}@@ -123,7 +231,10 @@ function sampleAt(const duration = Number(animation.options.duration);const offset = Math.min(1,- Math.max(0, (time - (animation.startTime ?? 0)) / duration),+ Math.max(+ 0,+ (time - (animation.startTime ?? animation.createdAt)) / duration,+ ),);const frames = animation.keyframes;for (let i = 0; i + 1 < frames.length; i++) {@@ -150,7 +261,7 @@ function sampleAt(}describe('animate: keyframes on the compositor', () => {- it('bakes the spring into keyframes within a twentieth of a pixel of the curve', () => {+ it('bakes the spring into keyframes within a twentieth of a pixel of the curve', async () => {const {animator} = setup();animator.animate({x: 300}, {spring: springs.settle});const [animation] = live('translate');@@ -159,6 +270,9 @@ describe('animate: keyframes on the compositor', () => {fill: 'both',easing: 'linear',});+ // From rest, the browser sets the start when it commits the first frame.+ expect(animation.startTime).toBeNull();+ await commitFrame(1000);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).@@ -275,6 +389,7 @@ describe('animate: keyframes on the compositor', () => {const {animator} = setup();animator.animate({x: 120}, {spring: springs.quickChange});const [animation] = live('translate');+ await commitFrame(1000);const duration = Number(animation.options.duration) - END_HOLD_MS;animation.paused = true;await advance(duration + 500);@@ -285,18 +400,20 @@ describe('animate: keyframes on the compositor', () => {expect(animation.cancelled).toBe(true);});- it('puts everything one call starts on one clock', () => {+ it('puts everything one call starts on one clock', async () => {const {animator} = setup();animator.animate({x: 100, opacity: 0.5}, {spring: springs.settle});+ await commitFrame(1000);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', () => {+ it('expands scale onto both axes and reads it back', async () => {const {animator} = setup();animator.animate({scale: 0.5}, {spring: springs.settle});+ await commitFrame(clock); // the browser starts itclock += 5000;expect(animator.get('scale')).toBe(0.5);expect(animator.get('scaleY')).toBe(0.5);@@ -310,7 +427,500 @@ describe('animate: keyframes on the compositor', () => {});});-describe('presentation values, retargeting, velocity (M2, M3)', () => {+describe('a call from rest starts at the commit, as Core Animation does', () => {+ const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});++ it('a block before the first frame delays the motion instead of skipping into it', async () => {+ const {animator} = setup();+ const handle = animator.animate({x: 300}, {spring: springs.settle});+ const [animation] = live('translate');+ expect(animation.startTime).toBeNull();+ // Until the commit the curve reads from the call time.+ expect(animator.get('x', 1000)).toBe(0);+ // The main thread was blocked for 300 ms: the first frame commits at 1300.+ clock = 1300;+ await commitFrame(1300);+ await expect(handle.started).resolves.toBe(1300);+ expect(animator.get('x', 1300)).toBeCloseTo(0, 9);+ expect(animator.get('x', 1400)).toBeCloseTo(curve.value(0.1), 9);+ expect(handle.value('x', 1400)).toBeCloseTo(curve.value(0.1), 9);+ expect(sampleAt(animation, 'translate', 1400)[0]).toBeCloseTo(+ curve.value(0.1),+ 1,+ );+ });++ it('holds its start until the browser starts it', async () => {+ const {animator} = setup();+ animator.animate({x: 300}, {spring: springs.settle});+ // Nothing has moved on screen yet, whatever the clock says; a time ahead+ // reads the curve from the call's time, and the model is moving: a+ // retarget carries this velocity.+ expect(animator.get('x')).toBe(0);+ expect(animator.get('x', 1100)).toBeCloseTo(curve.value(0.1), 9);+ clock = 1100;+ expect(animator.get('x')).toBe(0);+ expect(animator.getVelocity('x', 1100)).toBeCloseTo(curve.velocity(0.1), 9);+ clock = 1250;+ await commitFrame(1250);+ expect(animator.get('x', 1350)).toBeCloseTo(curve.value(0.1), 9);+ expect(live('translate')[0].startTime).toBe(1250);+ });++ it('a companion sampling a waiting curve ahead follows its shape', async () => {+ // A tab bar's counter-moving copy, sampled from the body's curve.+ const {animator} = setup();+ animator.animate({x: 300}, {spring: springs.settle});+ const at = clock;+ const samples = [0, 50, 100, 200].map(t => animator.get('x', at + t));+ expect(samples[0]).toBe(0);+ expect(samples.slice(1).map((v, i) => v > samples[i])).toEqual([+ true,+ true,+ true,+ ]);+ expect(samples[2]).toBeCloseTo(curve.value(0.1), 9);+ });++ it('finishes and drops the animation on the committed clock', async () => {+ const {animator} = setup();+ const handle = animator.animate({x: 300}, {spring: springs.settle});+ const [animation] = live('translate');+ const duration = Number(animation.options.duration) - END_HOLD_MS;+ clock = 1300;+ await commitFrame(1300);+ let done = false;+ void handle.finished.then(() => {+ done = true;+ });+ await advance(duration - 1);+ expect(done).toBe(false);+ expect(animation.cancelled).toBe(false);+ await advance(2);+ expect(done).toBe(true);+ expect(animation.cancelled).toBe(true);+ });++ it('a retarget mid-flight keeps an explicit start', async () => {+ const {animator} = setup();+ const first = animator.animate({x: 300}, {spring: springs.settle});+ await advance(100);+ await expect(first.started).resolves.toBe(1000);+ const second = animator.animate({x: 0}, {spring: springs.settle});+ expect(live('translate')[0].startTime).toBe(1100);+ await expect(second.started).resolves.toBe(1100);+ });++ it('a call stopped before its first frame resolves at its own time', async () => {+ const {animator} = setup();+ const handle = animator.animate({x: 300}, {spring: springs.settle});+ animator.stop();+ clock = 1300;+ await commitFrame(1300);+ await expect(handle.started).resolves.toBe(1000);+ await expect(handle.finished).resolves.toBe(false);+ });++ it('a second call before the first frame starts with the same commit', async () => {+ const {animator} = setup();+ animator.animate({x: 300}, {spring: springs.settle});+ animator.animate({y: 300}, {spring: springs.settle});+ const [animation] = live('translate');+ expect(animation.startTime).toBeNull();+ clock = 1300;+ await commitFrame(1300);+ expect(animator.get('x', 1400)).toBeCloseTo(curve.value(0.1), 9);+ expect(animator.get('y', 1400)).toBeCloseTo(curve.value(0.1), 9);+ });+ it('an explicit clock after a waiting call was finished from outside keeps that clock, with no lead-in', async () => {+ // A sampler holds a call from rest before the browser starts it, then+ // finishes it (the interaction harness's release with finish): the call+ // never gets a start time. A call on an explicit clock that follows plays+ // from that clock instead of waiting on the finished call's start.+ const {animator} = setup();+ animator.animate({opacity: 0}, {spring: springs.settle});+ const [held] = live('opacity');+ expect(held.startTime).toBeNull();+ held.paused = true;+ held.finish();+ clock += 9;+ const at = clock - 4;+ animator.animate({opacity: 1}, {spring: springs.settle}, {at});+ const fade = recorded.filter(a => !a.cancelled && a !== held).at(-1);+ expect(fade?.startTime).toBe(at);+ // The curve moves from its first keyframe: no hold before it.+ expect(fade?.keyframes[1].opacity).not.toBe(fade?.keyframes[0].opacity);+ });+});++describe('review fixes', () => {+ it('a retarget before the first frame starts from what is on screen', async () => {+ const {animator} = setup();+ animator.animate({x: 300}, {spring: springs.settle});+ // A 150 ms block, then a second call on the same channel, all before the+ // browser started the first.+ clock = 1150;+ animator.animate({x: 100}, {spring: springs.settle});+ expect(animator.get('x')).toBe(0);+ await commitFrame(1150);+ // From where it is drawn, with the velocity the first curve had reached.+ const first = solveSpring(toSpring(springs.settle), {from: 0, to: 300});+ const from0 = solveSpring(toSpring(springs.settle), {+ from: 0,+ to: 100,+ velocity: first.velocity(0.15),+ });+ expect(animator.get('x', 1250)).toBeCloseTo(from0.value(0.1), 9);+ });++ it('retargets the browser has not started keep a flick\u2019s velocity', async () => {+ const {animator} = setup();+ const tracking = {response: 0.08, dampingRatio: 1};+ // Ten moves at 120 Hz retarget the tracking spring, and the browser starts+ // none of them before the finger lifts.+ for (let i = 1; i <= 10; i++) {+ clock = 1000 + (i * 1000) / 120;+ animator.animate({x: -12 * i}, {spring: tracking});+ }+ // Nothing has moved on screen, but the model is moving with the finger.+ expect(animator.get('x')).toBe(0);+ const velocity = animator.getVelocity('x');+ expect(velocity).toBeLessThan(-100);+ // The release springs with that velocity.+ animator.animate({x: -200}, {spring: springs.settle});+ await commitFrame(clock);+ const release = solveSpring(toSpring(springs.settle), {+ from: 0,+ to: -200,+ velocity,+ });+ expect(animator.get('x', clock + 50)).toBeCloseTo(release.value(0.05), 6);+ });++ it('a pager settle after drags the browser has not started is already moving', async () => {+ const {animator} = setup();+ const tracking = {response: 0.08, dampingRatio: 1};+ // A page drag toward the next page, its moves all held.+ for (let i = 1; i <= 6; i++) {+ clock = 1000 + (i * 1000) / 60;+ animator.animate({x: -20 * i}, {spring: tracking});+ }+ const velocity = animator.getVelocity('x');+ expect(velocity).toBeLessThan(0);+ // The settle to the next page starts with the drag's velocity.+ animator.animate({x: -400}, {spring: springs.settle});+ expect(animator.getVelocity('x')).toBeCloseTo(velocity, 6);+ await commitFrame(clock);+ const first = animator.get('x', clock + 16);+ const settle = solveSpring(toSpring(springs.settle), {+ from: 0,+ to: -400,+ velocity,+ });+ expect(first).toBeCloseTo(settle.value(0.016), 6);+ expect(first).toBeLessThan(+ solveSpring(toSpring(springs.settle), {from: 0, to: -400}).value(0.016),+ );+ });++ it('a call adopted by a later same-task call starts with it', async () => {+ const {animator} = setup();+ const a = animator.animate({x: 300}, {spring: springs.settle});+ const b = animator.animate({y: 300}, {spring: springs.settle});+ clock = 1300;+ await commitFrame(1300);+ await expect(b.started).resolves.toBe(1300);+ await expect(a.started).resolves.toBe(1300);+ });++ it('dispose settles every atRest() wait', async () => {+ const {animator} = setup();+ animator.animate({x: 300}, {spring: springs.settle});+ await commitFrame(1000);+ let rested = false;+ void animator.atRest().then(() => {+ rested = true;+ });+ animator.dispose();+ for (let i = 0; i < 5; i++) {+ await Promise.resolve();+ }+ expect(rested).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('a rebase and a retarget in the task of a drop from rest start on the browser\u2019s clock', async () => {+ // A list row's drop: it springs home from where the finger left it.+ const {animator} = setup();+ animator.set({y: 30});+ animator.animate({y: 0}, {spring: springs.settle, velocity: {y: 0}});+ // The reorder commits in the same task, on the call's clock: the layout+ // moved the row by 56 px, and the row springs home from there.+ animator.rebase({y: 56}, {at: 1000});+ const home = animator.animate({y: 0}, {spring: springs.settle}, {at: 1000});+ clock = 1004;+ await commitFrame(1004);+ await expect(home.started).resolves.toBe(1004);+ const curve = solveSpring(toSpring(springs.settle), {from: 86, to: 0});+ for (const t of [0, 16, 50, 100, 200]) {+ expect(animator.get('y', 1004 + t)).toBeCloseTo(curve.value(t / 1000), 6);+ }+ });++ it('writing another axis before the first frame keeps the channel on the call\u2019s start', async () => {+ const {animator} = setup();+ animator.animate({opacity: 0.5, x: 100}, {spring: springs.settle});+ animator.set({y: 10});+ const [translate] = live('translate');+ expect(translate.startTime).toBeNull();+ clock = 1300;+ await commitFrame(1300);+ const x = solveSpring(toSpring(springs.settle), {from: 0, to: 100});+ expect(animator.get('x', 1400)).toBeCloseTo(x.value(0.1), 6);+ expect(sampleAt(live('translate')[0], 'translate', 1400)[0]).toBeCloseTo(+ x.value(0.1),+ 1,+ );+ });++ it('a same-task write that cancels the call\u2019s first animation still leaves the call on the browser\u2019s start', async () => {+ const {animator} = setup();+ const handle = animator.animate({x: 100}, {spring: springs.settle});+ animator.set({y: 10});+ // The cancelled animation's rejection runs before the first frame, as in+ // a browser's task order.+ await Promise.resolve();+ await Promise.resolve();+ clock = 1300;+ await commitFrame(1300);+ await expect(handle.started).resolves.toBe(1300);+ const x = solveSpring(toSpring(springs.settle), {from: 0, to: 100});+ expect(animator.get('x', 1316)).toBeCloseTo(x.value(0.016), 6);+ expect(sampleAt(live('translate')[0], 'translate', 1316)[0]).toBeCloseTo(+ x.value(0.016),+ 1,+ );+ });++ it('a write later in the task samples the waiting call\u2019s curve from its start, so the screen and get() share one clock', async () => {+ const {animator} = setup();+ animator.animate({opacity: 0.5, x: 100}, {spring: springs.settle});+ // 100 ms of work in the same task before another axis is written.+ clock = 1100;+ animator.set({y: 10});+ clock = 1300;+ await commitFrame(1300);+ const x = solveSpring(toSpring(springs.settle), {from: 0, to: 100});+ expect(animator.get('x', 1400)).toBeCloseTo(x.value(0.1), 6);+ expect(sampleAt(live('translate')[0], 'translate', 1400)[0]).toBeCloseTo(+ x.value(0.1),+ 1,+ );+ });++ it('an earlier {at} on a channel whose other axis waits joins that call, so the screen and get() share its clock', async () => {+ const {animator} = setup();+ clock = 1020;+ animator.animate({x: 100}, {spring: springs.settle});+ // An event timestamp 20 ms before the waiting call's time.+ animator.animate({y: 50}, {spring: springs.settle}, {at: 1000});+ clock = 1300;+ await commitFrame(1300);+ const y = animator.get('y', 1316);+ expect(sampleAt(live('translate')[0], 'translate', 1316)[1]).toBeCloseTo(+ y,+ 1,+ );+ });++ it('a later {at} than a call from rest still waiting keeps its own clock, with no hold', async () => {+ const {animator} = setup();+ animator.animate({opacity: 0}, {spring: springs.settle});+ // A frame later the browser has still not started it (a busy compositor),+ // and a tap's call names its own, later clock.+ clock = 1011;+ animator.animate({opacity: 1}, {spring: springs.settle}, {at: 1011});+ const fade = recorded.filter(a => !a.cancelled).at(-1);+ expect(fade?.startTime).toBe(1011);+ // The curve moves from its first keyframe on.+ expect(fade?.keyframes[1].opacity).not.toBe(fade?.keyframes[0].opacity);+ });++ it('a call adopted by a later same-task call starts at the commit, after the work between them', async () => {+ const {animator} = setup();+ const first = animator.animate({x: 100}, {spring: springs.settle});+ // 300 ms of work in the same task, then another axis from rest.+ clock = 1300;+ animator.animate({y: 50}, {spring: springs.settle});+ clock = 1310;+ await commitFrame(1310);+ await expect(first.started).resolves.toBe(1310);+ expect(animator.get('x', 1310)).toBeCloseTo(0, 6);+ expect(sampleAt(live('translate')[0], 'translate', 1310)[0]).toBeCloseTo(+ 0,+ 1,+ );+ });++ it('under Reduced Motion on a fine pointer, a move leaves a running fade alone', async () => {+ const {animator} = setup({+ reduced: true,+ coarse: false,+ });+ animator.set({opacity: 0});+ animator.animate({opacity: 1}, {spring: springs.settle});+ await advance(10_000);+ animator.animate({x: 40}, {spring: springs.settle});+ expect(animator.get('opacity')).toBe(1);+ expect(animator.get('x')).toBe(40);+ });+});++describe('animatorFor: one animator per element', () => {+ it('gives every caller the same animator for an element', () => {+ const a = document.createElement('div');+ const b = document.createElement('div');+ expect(animatorFor(a)).toBe(animatorFor(a));+ expect(animatorFor(a)).not.toBe(animatorFor(b));+ });++ it('composes two callers’ axes in one translate track', async () => {+ const row = document.createElement('div');+ const options = {+ now: () => clock,+ requestFrame,+ };+ const swipe = animatorFor(row, options);+ swipe.animate({x: -120}, {spring: springs.settle});+ await advance(50);+ const x = solveSpring(toSpring(springs.settle), {from: 0, to: -120});+ const removal = animatorFor(row, options);+ removal.animate({y: -44}, {spring: springs.settle});+ const tracks = live('translate');+ expect(tracks).toHaveLength(1);+ // x stays on its curve; y starts its own.+ expect(removal.get('x', clock + 30)).toBeCloseTo(x.value(0.08), 9);+ const y = solveSpring(toSpring(springs.settle), {from: 0, to: -44});+ expect(swipe.get('y', clock + 30)).toBeCloseTo(y.value(0.03), 9);+ const [tx, ty] = sampleAt(tracks[0], 'translate', clock + 30);+ expect(tx).toBeCloseTo(x.value(0.08), 1);+ expect(ty).toBeCloseTo(y.value(0.03), 1);+ });+});++describe('rebase: a layout shift under a moving element', () => {+ it('keeps a spring’s spring, velocity and target', async () => {+ const {animator} = setup();+ const handle = animator.animate({y: 100}, {spring: springs.settle});+ await advance(60);+ const value = animator.get('y');+ const velocity = animator.getVelocity('y');+ animator.rebase({y: -40});+ expect(animator.get('y', clock)).toBeCloseTo(value - 40, 9);+ expect(animator.getVelocity('y', clock)).toBeCloseTo(velocity, 6);+ const curve = solveSpring(toSpring(springs.settle), {+ from: value - 40,+ to: 100,+ velocity,+ });+ expect(animator.get('y', clock + 30)).toBeCloseTo(curve.value(0.03), 9);+ expect(live('translate')).toHaveLength(1);+ await advance(5000);+ expect(animator.get('y')).toBe(100);+ await expect(handle.finished).resolves.toBe(true);+ });++ it('offsets a resting value and starts nothing', () => {+ const {animator, element} = setup();+ animator.set({y: 10});+ animator.rebase({y: -20});+ expect(animator.get('y')).toBe(-10);+ expect(live('translate')).toHaveLength(0);+ expect(parse(element.style.translate)[1]).toBe(-10);+ });+});++describe('promotion: a compositing layer while it moves', () => {+ it('promotes the animated channels in the task that starts the motion, and ends it after rest', async () => {+ const {animator, element} = setup();+ animator.animate({x: 120, opacity: 0.5}, {spring: springs.settle});+ expect(element.style.willChange).toBe('translate, opacity');+ const end = Math.max(+ ...live('translate').map(a => Number(a.options.duration) - END_HOLD_MS),+ ...live('opacity').map(a => Number(a.options.duration) - END_HOLD_MS),+ );+ await advance(end + PROMOTION_LINGER_MS - 5);+ expect(element.style.willChange).toBe('translate, opacity');+ await advance(10);+ expect(element.style.willChange).toBe('');+ });++ it('keeps the element’s own will-change', async () => {+ const {animator, element} = setup();+ element.style.willChange = 'contents';+ animator.animate({y: 40}, {spring: springs.quickChange});+ expect(element.style.willChange).toBe('contents, translate');+ await advance(5000 + PROMOTION_LINGER_MS);+ expect(element.style.willChange).toBe('contents');+ });++ it("keeps the stylesheet's will-change reasons while it promotes, and hands them back", async () => {+ const {animator, element} = setup();+ stylesheet = {'will-change': 'transform, opacity'};+ animator.animate({y: 40, opacity: 0.5}, {spring: springs.quickChange});+ expect(element.style.willChange).toBe('transform, translate, opacity');+ await advance(5000 + PROMOTION_LINGER_MS);+ expect(element.style.willChange).toBe('');+ });++ it('promotes during direct manipulation, until the writes stop', async () => {+ const {animator, element} = setup();+ animator.set({y: 10});+ expect(element.style.willChange).toBe('translate');+ await advance(PROMOTION_LINGER_MS - 10);+ animator.set({y: 20});+ await advance(PROMOTION_LINGER_MS - 10);+ expect(element.style.willChange).toBe('translate');+ await advance(20);+ expect(element.style.willChange).toBe('');+ });++ it('ends promotion on the element it leaves', () => {+ const {animator, element} = setup();+ animator.animate({x: 50}, {spring: springs.settle});+ expect(element.style.willChange).toBe('translate');+ animator.attach(document.createElement('div'));+ expect(element.style.willChange).toBe('');+ });+});++describe('atRest: waiting out every curve', () => {+ it('resolves when the last curve ends, retargets included', async () => {+ const {animator} = setup();+ animator.animate({y: 100}, {spring: springs.settle});+ let rested = false;+ void animator.atRest(['y']).then(() => {+ rested = true;+ });+ await advance(100);+ // Someone else retargets the row: the wait follows the new curve.+ const second = animator.animate({y: 0}, {spring: springs.settle});+ const [track] = live('translate');+ const end = Number(track.options.duration) - END_HOLD_MS;+ await advance(end - 1);+ expect(rested).toBe(false);+ await advance(2);+ expect(rested).toBe(true);+ await expect(second.finished).resolves.toBe(true);+ });++ it('resolves at once at rest', async () => {+ const {animator} = setup();+ await expect(animator.atRest()).resolves.toBeUndefined();+ });+});++describe('presentation values, retargeting, velocity (spec:AST-094 FR6)', () => {it('hands a release velocity to the spring', () => {const {animator} = setup();animator.set({y: 200});@@ -410,7 +1020,20 @@ describe('presentation values, retargeting, velocity (M2, M3)', () => {});});-describe('set: direct manipulation (M4)', () => {+describe('set: direct manipulation', () => {+ it('a commit that leaves several channels at identity reads the stylesheet once', () => {+ // Each read after a write forces a style recalculation (a lifted menu+ // that grows back to identity on translate, scale and opacity paid one+ // per channel in its opening commit).+ const {animator} = setup();+ animator.set({x: 10, scale: 2, opacity: 0.5});+ const reads = vi.mocked(window.getComputedStyle).mock.calls.length;+ animator.set({x: 0, scale: 1, opacity: 1});+ expect(vi.mocked(window.getComputedStyle).mock.calls.length - reads).toBe(+ 1,+ );+ });+it('writes one inline style per move and starts no animation', () => {const {animator, element} = setup();for (let x = 0; x < 30; x += 3) {@@ -471,47 +1094,115 @@ describe('finished', () => {});});-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);+describe('Reduced Motion (design:reduced-motion)', () => {+ // A coarse primary pointer, or a touch drag's release on any pointer,+ // cross-fades (DR2); any other call completes at once (DR3).+ const reduced = (coarse = true) => setup({reduced: true, coarse});+ const fade = timing.reducedMotionCrossFadeMs;const ease = cubicBezier(timing.curves.move);+ /** Every animation the browser was handed changes opacity only. */+ const opacityOnly = () =>+ recorded.every(animation =>+ animation.keyframes.every(keyframe =>+ Object.keys(keyframe).every(key =>+ ['opacity', 'offset', 'easing', 'composite'].includes(key),+ ),+ ),+ );- it('a move during a running fade keeps that fade\u2019s target', async () => {+ it('an entrance after an outside finish starts from what is on screen', 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);+ animator.animate(+ {opacity: 0},+ {spring: springs.settle},+ {crossfadeAs: 'exit'},+ );+ await commitFrame(clock);+ await advance(16);+ // A test utility finishes the fade out: opacity 0 on screen, while the+ // curve would still read about 0.93.+ const [exit] = live('opacity');+ exit.finish();+ animator.animate(+ {opacity: 1},+ {spring: springs.settle},+ {crossfadeAs: 'entrance'},+ );+ const fade = live('opacity').at(-1);+ expect(fade?.keyframes[0].opacity).toBe('0');+ });- 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('fades for 200 ms at most', () => {+ expect(fade).toBeGreaterThan(0);+ expect(fade).toBeLessThanOrEqual(200);});- it("a move dips from and back to the stylesheet's opacity, then hands it back", async () => {+ it('never animates a transform, on either pointer', async () => {+ for (const coarse of [true, false]) {+ const {animator} = reduced(coarse);+ animator.animate({x: 100}, {spring: springs.navigationPush});+ animator.animate({y: 400, opacity: 0}, {spring: springs.sheetDismiss});+ animator.animate(+ {scale: 0.9},+ {spring: springs.quickChange},+ {crossfadeAs: 'exit'},+ );+ await advance(1000);+ }+ expect(recorded.length).toBeGreaterThan(0);+ expect(opacityOnly()).toBe(true);+ });++ it("a move with no opacity of its own 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});+ await commitFrame(clock); // the browser starts itexpect(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);+ const [out] = live('opacity');+ expect(out.keyframes[0].opacity).toBe('0.6');+ await advance(fade / 2);+ // Landed while transparent, fading back in to the stylesheet's value.+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity', clock + fade / 2)).toBeCloseTo(0.6, 9);+ await advance(fade / 2 + 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('overlapping dips on the stylesheet opacity never leave it pinned inline', async () => {+ for (const at of ['fading out', 'fading back in'] as const) {+ const {animator, element} = reduced();+ stylesheet = {opacity: '0.6'};+ animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(at === 'fading out' ? fade / 4 : fade / 2 + 20);+ animator.animate({x: 200}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(fade * 2 + END_HOLD_MS + 1);+ expect(animator.get('x')).toBe(200);+ // The stylesheet owns opacity again.+ expect(element.style.opacity).toBe('');+ expect(animator.get('opacity')).toBe(1);+ }+ });++ it('detaching and attaching a new node during a dip lands the move on it (React replacement)', async () => {+ const {animator} = reduced();+ const handle = animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(50);+ animator.attach(null);+ const replacement = document.createElement('div');+ animator.attach(replacement);+ // The dip goes on on the new node: the move lands at its bottom.+ await advance(fade);+ expect(animator.get('x')).toBe(100);+ expect(replacement.style.translate).toBe('100px 0px');+ await expect(handle.finished).resolves.toBe(true);+ });+it('a move that overlaps a running fade lands only once the element is invisible', async () => {const {animator} = reduced();animator.set({opacity: 0});@@ -521,10 +1212,14 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or leexpect(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);+ await advance(fade / 2 - 2);+ expect(clock - start).toBe(fade / 2 - 2);+ expect(animator.get('x')).toBe(0);+ await advance(4);+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBeLessThan(0.1);+ await advance(fade);+ expect(animator.get('opacity')).toBeCloseTo(1, 9);});it("a second call's fade re-times the first call's pending jump to its own invisible moment", async () => {@@ -534,14 +1229,16 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or leconst 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);+ // Neither moves while the element shows: both land at the new dip's+ // bottom.+ await advance(fade / 2 - 2);+ expect(clock - start).toBe(fade / 2 - 2);+ expect(animator.get('x')).toBe(0);+ expect(animator.get('y')).toBe(0);+ await advance(4);+ expect(animator.get('x')).toBe(100);+ expect(animator.get('y')).toBe(50);+ expect(animator.get('opacity')).toBeLessThan(0.1);});it('a stop during a dip finishes the fade instead of freezing it', async () => {@@ -574,14 +1271,10 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or leexpect(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,- });+ const changed = setup({reduced: true, coarse: true});changed.animator.animate({x: 100}, {spring: springs.navigationPush});await advance(fade / 4);- reduce = false;+ stubMedia(false, true);changed.animator.animate({y: 20}, {spring: springs.navigationPush});await advance(2000);expect(changed.element.style.opacity).toBe('');@@ -651,13 +1344,15 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or le});it('a running dip survives any re-attach, so the move never passes in view', async () => {- const halfway = (+ const halfway = async (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);+ ): Promise<number> => {+ // The plan lands by timer: step the clock to the landing.+ while (clock <= start + fade) {+ await advance(2);+ if (animator.get('x') !== 0) {+ return animator.get('opacity');}}return Number.NaN;@@ -669,7 +1364,7 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or leawait advance(25);same.animator.attach(null);same.animator.attach(same.element);- expect(halfway(same.animator, start)).toBeCloseTo(0, 6);+ expect(await 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});@@ -678,7 +1373,7 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or leconst next = document.createElement('div');document.body.append(next);other.animator.attach(next);- expect(halfway(other.animator, start2)).toBeCloseTo(0, 6);+ expect(await halfway(other.animator, start2)).toBeCloseTo(0, 6);await advance(fade + END_HOLD_MS + 1);expect(next.style.opacity).toBe('');next.remove();@@ -721,7 +1416,7 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or leexpect(animator.get('opacity')).toBe(1);});- it('a release past an edge springs back as a cross-fade, not momentum (DR2)', () => {+ it('a release past an edge springs back as a cross-fade, not momentum (DR2)', async () => {const {animator} = reduced();animator.set({x: -80});const start = clock;@@ -729,13 +1424,39 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or lecoast(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;+ // The plan lands by timer: step the clock; it moves only while invisible.+ let moved = false;+ while (clock <= start + fade) {+ await advance(2);+ if (!moved && animator.get('x') !== -80) {+ moved = true;+ expect(animator.get('opacity')).toBeLessThan(0.1);+ }+ }+ expect(moved).toBe(true);+ expect(animator.get('x')).toBe(0);+ });++ it('a spring back a touch release starts cross-fades on a fine pointer too (DR2)', async () => {+ const {animator} = reduced(false);+ animator.set({x: -80});+ const start = clock;+ animator.decay(+ coast(animator, {x: 0}, {bounds: {x: {min: 0, max: 100}}, at: start}),+ {at: start, touchRelease: true},+ );+ // Not at once: it moves only while invisible.+ expect(animator.get('x')).toBe(-80);+ let moved = false;+ while (clock <= start + fade) {+ await advance(2);+ if (!moved && animator.get('x') !== -80) {+ moved = true;+ expect(animator.get('opacity')).toBeLessThan(0.1);}}- expect(animator.get('x', start + fade)).toBe(0);+ expect(moved).toBe(true);+ expect(animator.get('x')).toBe(0);});it('a release with one axis past an edge is one handle: stop() stops the cross-fade too', async () => {@@ -753,64 +1474,580 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or leexpect(handle.properties).toEqual(expect.arrayContaining(['x', 'y']));await advance(fade / 4);handle.stop();+ // A catch freezes the release where it is on screen (AST-094 FR6): x+ // never lands at its edge, and the fade it was waiting in finishes.+ const stopped = {x: animator.get('x'), y: animator.get('y')};+ expect(stopped.x).toBe(-80);+ expect(animator.get('opacity')).toBe(1);await advance(fade + END_HOLD_MS + 1);- // x never lands at its edge after the stop.expect(animator.get('x')).toBe(-80);+ expect(animator.get('y')).toBe(stopped.y);});- it('a second move during a borrowed dip copies no stylesheet opacity inline', async () => {+ it('a carried move keeps its own call: stopping or setting it settles that call, not the one carrying it', async () => {+ for (const interrupt of ['set', 'stop'] as const) {+ const {animator} = reduced();+ const a = animator.animate({x: 100}, {spring: springs.navigationPush});+ await advance(fade / 4);+ const b = animator.animate({y: 50}, {spring: springs.navigationPush});+ if (interrupt === 'set') {+ animator.set({x: 40});+ } else {+ a.stop();+ }+ await advance(fade * 2 + END_HOLD_MS + 1);+ await expect(a.finished).resolves.toBe(false);+ await expect(b.finished).resolves.toBe(true);+ expect(animator.get('x')).toBe(interrupt === 'set' ? 40 : 0);+ expect(animator.get('y')).toBe(50);+ }+ });++ it("an earlier handle's stop leaves a later call's move on the same property alone", async () => {+ const {animator} = reduced();+ const a = animator.animate({x: 100}, {spring: springs.navigationPush});+ await advance(fade / 4);+ const b = animator.animate({x: 200}, {spring: springs.navigationPush});+ a.stop();+ await advance(fade * 2 + END_HOLD_MS + 1);+ expect(animator.get('x')).toBe(200);+ await expect(a.finished).resolves.toBe(false);+ await expect(b.finished).resolves.toBe(true);+ });++ it('a retargeted call settles interrupted; its retarget lands', async () => {+ const {animator} = reduced();+ const a = animator.animate({x: 100}, {spring: springs.navigationPush});+ await advance(fade / 4);+ const b = a.retarget({x: 150});+ await advance(fade * 2 + END_HOLD_MS + 1);+ expect(animator.get('x')).toBe(150);+ await expect(a.finished).resolves.toBe(false);+ await expect(b.finished).resolves.toBe(true);+ });++ it('a move whose animations are paused before their first frame still lands once released', async () => {+ for (const release of ['resume', 'finish'] as const) {+ const {animator} = reduced();+ const handle = animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ );+ // Something pauses the call's animations in its own task.+ for (const animation of recorded) {+ animation.paused = true;+ }+ await commitFrame(clock);+ clock += 30;+ await commitFrame(clock);+ for (const animation of recorded) {+ if (release === 'resume') {+ // play(): pending, so the start comes a frame later, after the+ // frame's callbacks.+ animation.paused = false;+ animation.startDelayFrames = 1;+ } else {+ animation.finish();+ }+ }+ // Frames keep coming: step the clock through the landing.+ for (let step = 0; step < 16; step++) {+ await advance(fade / 4);+ }+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBe(1);+ await expect(handle.finished).resolves.toBe(true);+ }+ });++ it('a waiting call whose own opacity a later call retargets settles interrupted', async () => {+ const {animator} = reduced();+ const dismiss = animator.animate(+ {y: 800, opacity: 0},+ {spring: springs.sheetDismiss},+ );+ await advance(fade / 4);+ const show = animator.animate({opacity: 1}, {spring: springs.settle});+ // The plan lands by timer: step the clock through the dip.+ for (let step = 0; step < 12; step++) {+ await advance(fade / 8);+ }+ expect(animator.get('opacity')).toBe(1);+ await expect(dismiss.finished).resolves.toBe(false);+ await expect(show.finished).resolves.toBe(true);+ });++ it('a move taken back mid-dip fades straight back up instead of finishing the dip', async () => {+ const {animator} = reduced();+ const move = animator.animate({x: 100}, {spring: springs.navigationPush});+ await advance(fade / 4);+ const shown = animator.get('opacity');+ expect(shown).toBeLessThan(1);+ const back = animator.animate({x: 0}, {spring: springs.navigationPush});+ let lowest = shown;+ for (let step = 0; step < 12; step++) {+ await advance(fade / 8);+ lowest = Math.min(lowest, animator.get('opacity'));+ }+ expect(lowest).toBeGreaterThanOrEqual(shown - 1e-6);+ expect(animator.get('x')).toBe(0);+ expect(animator.get('opacity')).toBe(1);+ await expect(move.finished).resolves.toBe(false);+ await expect(back.finished).resolves.toBe(true);+ });++ it('an entrance by role caught mid-exit fades in from where the exit has it', async () => {+ const {animator} = reduced();+ animator.animate(+ {y: 40},+ {spring: springs.navigationPush},+ {crossfadeAs: 'exit'},+ );+ await advance(fade / 4);+ const shown = animator.get('opacity');+ expect(shown).toBeLessThan(1);+ animator.animate(+ {y: 0},+ {spring: springs.navigationPush},+ {crossfadeAs: 'entrance'},+ );+ let lowest = shown;+ for (let step = 0; step < 12; step++) {+ await advance(fade / 8);+ lowest = Math.min(lowest, animator.get('opacity'));+ }+ expect(lowest).toBeGreaterThanOrEqual(shown - 1e-6);+ expect(animator.get('y')).toBe(0);+ expect(animator.get('opacity')).toBe(1);+ });++ it('a caught dismissal fades straight back up: a call that sets every waiting value takes it over', async () => {+ const {animator} = reduced();+ const dismiss = animator.animate(+ {y: 800, opacity: 0},+ {spring: springs.sheetDismiss},+ );+ await advance(fade / 4);+ const shown = animator.get('opacity');+ const present = animator.animate(+ {y: 0, opacity: 1},+ {spring: springs.sheetPresent},+ );+ await commitFrame(clock);+ // No dip: the opacity only rises from where it was.+ let lowest = shown;+ const start = clock;+ while (clock <= start + fade * 2) {+ await advance(2);+ lowest = Math.min(lowest, animator.get('opacity'));+ }+ expect(lowest).toBeGreaterThanOrEqual(shown - 1e-6);+ expect(animator.get('y')).toBe(0);+ expect(animator.get('opacity')).toBe(1);+ await expect(dismiss.finished).resolves.toBe(false);+ await expect(present.finished).resolves.toBe(true);+ });++ it("a handle's stop mid-dip freezes its waiting travel where it is, as animator.stop() does (AST-094 FR6)", async () => {+ const {animator} = reduced();+ const handle = animator.animate({x: 100}, {spring: springs.navigationPush});+ await advance(fade / 4);+ handle.stop();+ expect(animator.get('x')).toBe(0);+ expect(animator.get('opacity')).toBe(1);+ await advance(fade + END_HOLD_MS + 1);+ expect(animator.get('x')).toBe(0);+ await expect(handle.finished).resolves.toBe(false);+ });++ 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 / 2);+ // Landed, and fading back in to the stylesheet's value.+ expect(animator.get('opacity', clock + fade / 2)).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', () => {+ it('a stop during a dip whose opacity a call owns ends where the fade was heading', async () => {+ const {animator} = reduced();+ animator.set({opacity: 0.8});+ animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(50);+ animator.stop();+ expect(animator.get('opacity')).toBeCloseTo(0.8, 9);+ });++ it('an opacity change mid-dip lands the waiting move only once the element is invisible', async () => {+ const {animator} = reduced();+ animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(20);+ animator.animate({opacity: 0}, {spring: springs.navigationPush});+ // Still where it was while it shows.+ expect(animator.get('x')).toBe(0);+ await advance(fade - 2);+ expect(animator.get('x')).toBe(0);+ await advance(4);+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBeCloseTo(0, 9);+ });++ it('a second borrowed dip opens at the opacity on screen', async () => {+ const {animator} = reduced();+ stylesheet = {opacity: '0.6'};+ animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(fade / 4);+ const before = animator.get('opacity');+ expect(before).toBeLessThan(0.6);+ animator.animate({x: 200}, {spring: springs.navigationPush});+ expect(animator.get('opacity')).toBeCloseTo(before, 6);+ });++ it("a fade by role on a stylesheet's opacity ends on it and hands it back", async () => {+ for (const role of ['entrance', 'exit'] as const) {+ const {animator, element} = reduced();+ stylesheet = {opacity: '0.6'};+ animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ {crossfadeAs: role},+ );+ await commitFrame(clock);+ const [layer] = live('opacity');+ const keyframes = layer.keyframes.map(k => Number(k.opacity));+ expect(Math.max(...keyframes)).toBeCloseTo(0.6, 9);+ await advance(fade * 2 + END_HOLD_MS + 1);+ expect(animator.get('x')).toBe(100);+ expect(element.style.opacity).toBe('');+ }+ });++ it('a move set before its dip lands does not report finished', async () => {+ const {animator} = reduced();+ const handle = animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(20);+ animator.set({x: 40});+ await expect(handle.finished).resolves.toBe(false);+ await advance(fade + END_HOLD_MS + 1);+ expect(animator.get('x')).toBe(40);+ });++ it('dispose settles a move still waiting to land, and the calls it carries, as interrupted', async () => {+ const {animator} = reduced();+ const first = animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(10);+ const second = animator.animate({y: 50}, {spring: springs.navigationPush});+ await advance(10);+ animator.dispose();+ await expect(first.finished).resolves.toBe(false);+ await expect(second.finished).resolves.toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("a caught or replaced exit by role hands the stylesheet's opacity back", async () => {+ // Caught: stop() 50 ms into the exit.+ const caught = reduced();+ stylesheet = {opacity: '0.6'};+ caught.animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ {crossfadeAs: 'exit'},+ );+ await commitFrame(clock);+ await advance(50);+ caught.animator.stop();+ expect(caught.element.style.opacity).toBe('');+ // Replaced: React swaps the node 50 ms into the exit.+ const replaced = reduced();+ stylesheet = {opacity: '0.6'};+ replaced.animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ {crossfadeAs: 'exit'},+ );+ await commitFrame(clock);+ await advance(50);+ replaced.animator.attach(null);+ const node = document.createElement('div');+ replaced.animator.attach(node);+ expect(replaced.element.style.opacity).toBe('');+ // The exit goes on on the new node, then hands the opacity back.+ await advance(fade + END_HOLD_MS + 1);+ expect(node.style.opacity).toBe('');+ expect(replaced.animator.get('x')).toBe(100);+ });++ it('dispose mid-dip or mid-exit leaves the element visible where it was going', async () => {+ // A dip on an owned opacity.+ const dip = reduced();+ dip.animator.set({opacity: 0.8});+ dip.animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(50);+ dip.animator.dispose();+ expect(dip.element.style.opacity).toBe('0.8');+ expect(dip.element.style.translate).toBe('100px 0px');+ // An exit by role.+ const exit = reduced();+ exit.animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ {crossfadeAs: 'exit'},+ );+ await commitFrame(clock);+ await advance(50);+ exit.animator.dispose();+ expect(['', '1']).toContain(exit.element.style.opacity);+ expect(exit.element.style.translate).toBe('100px 0px');+ });++ it('an unmount mid-dip leaves no compositing promotion on the element it leaves', async () => {const {animator, element} = reduced();+ animator.decay(coast(animator, {y: 1500}));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);+ await commitFrame(clock);+ await advance(20);+ animator.attach(null);+ expect(element.style.willChange).toBe('');+ });++ it("a new element taking over an exit by role leaves the stylesheet's opacity on the outgoing one", async () => {+ const {animator, element} = reduced();+ stylesheet = {opacity: '0.6'};+ animator.animate(+ {x: 100},+ {spring: springs.navigationPush},+ {crossfadeAs: 'exit'},+ );+ await commitFrame(clock);+ await advance(50);+ animator.attach(document.createElement('div'));+ expect(element.style.opacity).toBe('');+ });++ it('an unmount mid-dip lands the move where it was going, so a later attach shows it visible there', async () => {+ const {animator, element} = reduced();+ animator.set({opacity: 0.8});+ const handle = animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ await advance(50);+ animator.attach(null);+ await Promise.resolve(); // the end of the task: an unmount+ await expect(handle.finished).resolves.toBe(false);+ await advance(fade);+ animator.attach(element);+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBeCloseTo(0.8, 9);+ expect(element.style.opacity).toBe('0.8');+ expect(element.style.translate).toBe('100px 0px');+ });++ it('a move dips: fades out, lands while transparent, fades back in', async () => {+ const {animator, element} = reduced();+ animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock); // the browser starts it+ // Fading out in place.+ expect(animator.get('x')).toBe(0);expect(animator.get('opacity', 1000 + fade / 4)).toBeCloseTo(1 - ease(0.5),9,);- expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(0, 9);+ expect(live('translate')).toHaveLength(0);+ await advance(fade / 2);+ // Landed with a plain write at the bottom, and fading back in from there.+ expect(animator.get('x')).toBe(100);+ expect(element.style.translate).toBe('100px 0px');+ expect(animator.get('opacity')).toBeCloseTo(0, 9);+ expect(animator.get('opacity', clock + fade / 4)).toBeCloseTo(ease(0.5), 9);+ expect(live('translate')).toHaveLength(0);+ expect(opacityOnly()).toBe(true);+ });++ it('a landing a busy main thread runs late still ends the dip on time', async () => {+ const {animator} = reduced();+ animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(1000);+ // The task that lands it runs 80 ms late (the page's clock is ahead+ // of the timer when it fires).+ clock += fade / 2 + 80;+ await vi.advanceTimersByTimeAsync(fade / 2);+ // Landed while transparent, never shown in the wrong place.+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBeCloseTo(0, 9);+ // The fade back in takes what is left: the dip ends when it was due.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(opacityOnly()).toBe(true);+ });++ it('a busy main thread keeps the element transparent longer, never in the wrong place', async () => {+ const {animator} = reduced();+ const handle = animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(1000);+ // The task that would land it runs 300 ms late.+ clock += fade / 2 + 300;+ expect(animator.get('x')).toBe(0);+ expect(animator.get('opacity')).toBe(0);+ await vi.advanceTimersByTimeAsync(fade / 2 + 300);+ expect(animator.get('x')).toBe(100);+ let finished: boolean | null = null;+ void handle.finished.then(value => {+ finished = value;});- expect(sampleAt(translate, 'translate', 1000 + fade / 2 - 2)[0]).toBe(0);- expect(element.style.translate).toBe('100px 0px');- expect(element.style.opacity).toBe('');+ await advance(fade);+ expect(animator.get('opacity')).toBe(1);+ expect(finished).toBe(true);});- it('an entrance lands in place and fades in', () => {+ it('two calls in one frame both land', async () => {+ // A drag cancel: the position on one spring, the scale on another.const {animator, element} = reduced();+ animator.set({x: 6.3, y: 84, scale: 0.969});+ const position = animator.animate(+ {x: 0, y: 0},+ {spring: springs.sheetPresent},+ {touchRelease: true},+ );+ const scale = animator.animate(+ {scale: 1},+ {spring: springs.quickChange},+ {touchRelease: true},+ );+ const settled: boolean[] = [];+ void position.finished.then(value => settled.push(value));+ void scale.finished.then(value => settled.push(value));+ await commitFrame(clock);+ // Both land at the bottom of one dip, then fade back in together.+ await advance(fade / 2);+ expect(animator.get('x')).toBe(0);+ expect(animator.get('scaleX')).toBe(1);+ expect(animator.get('opacity')).toBeCloseTo(0, 9);+ await advance(fade);+ expect(animator.get('x')).toBe(0);+ expect(animator.get('y')).toBe(0);+ expect(animator.get('scaleX')).toBe(1);+ expect(animator.get('opacity')).toBe(1);+ // Back at identity with nothing running: the inline value is gone.+ expect(element.style.translate).toBe('');+ expect(settled).toEqual([true, true]);+ expect(opacityOnly()).toBe(true);+ });++ it('a move during a dip\u2019s fade out dips once more and ends visible', async () => {+ const {animator} = reduced();+ animator.animate({y: 100}, {spring: springs.sheetPresent});+ await commitFrame(clock);+ // Half-way down the first dip's fade out, a frame or more later.+ await advance(fade / 4);+ animator.animate({y: 120}, {spring: springs.sheetPresent});+ await commitFrame(clock);+ await advance(fade / 2);+ await advance(fade);+ expect(animator.get('y')).toBe(120);+ expect(animator.get('opacity')).toBe(1);+ });++ it('a drop, its reorder\u2019s rebase and the move to the new slot in one task dip once', async () => {+ // A list row's drop under Reduce Motion: the drop from where the finger+ // left it, then the reorder's commit (the layout moved the row by 56 px)+ // and the move to its new slot, in one task on one clock.+ const {animator} = reduced();+ animator.set({y: 30});+ const at = clock;+ animator.animate(+ {y: 0},+ {spring: springs.settle, velocity: {y: 0}},+ {at, touchRelease: true},+ );+ // The commit comes a few ms later, once the first fade has begun.+ clock += 8;+ const at2 = clock;+ animator.rebase({y: 56}, {at: at2});+ animator.animate(+ {y: 0},+ {spring: springs.settle},+ {at: at2, touchRelease: true},+ );+ await commitFrame(clock);+ // It never moves while visible, and fades all the way out once.+ let lowest = 1;+ for (let t = 0; t <= fade / 2; t += 10) {+ const opacity = animator.get('opacity', at2 + t);+ lowest = Math.min(lowest, opacity);+ if (opacity > 0.01) {+ expect(animator.get('y', at2 + t)).toBe(86);+ }+ }+ expect(lowest).toBeLessThanOrEqual(0.1);+ await advance(fade / 2);+ expect(animator.get('y')).toBe(0);+ await advance(fade);+ expect(animator.get('y')).toBe(0);+ expect(animator.get('opacity')).toBe(1);+ });++ it('a later opacity change carries a waiting move to its own invisible moment instead of dropping it', async () => {+ const {animator} = reduced();+ const move = animator.animate({x: 100}, {spring: springs.navigationPush});+ await commitFrame(clock);+ animator.animate({opacity: 0.5}, {spring: springs.settle});+ // Not while the element shows: at the bottom of the new call's dip.+ expect(animator.get('x')).toBe(0);+ const start = clock;+ let landedAt: number | null = null;+ while (clock <= start + fade * 2) {+ await advance(2);+ if (landedAt == null && animator.get('x') !== 0) {+ landedAt = animator.get('opacity');+ }+ }+ expect(landedAt).not.toBeNull();+ expect(landedAt as number).toBeLessThan(0.05);+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBeCloseTo(0.5, 9);+ await expect(move.finished).resolves.toBe(true);+ });++ it('a move whose opacity rises from or falls to a visible value lands only while transparent (DR1, DR2)', async () => {+ for (const [from, to] of [+ [0.5, 1],+ [1, 0.5],+ ] as const) {+ const {animator} = reduced();+ animator.set({opacity: from});+ animator.animate({x: 100, opacity: to}, {spring: springs.navigationPush});+ expect(animator.get('x')).toBe(0);+ const start = clock;+ let landedAt: number | null = null;+ while (clock <= start + fade * 2) {+ await advance(2);+ if (landedAt == null && animator.get('x') !== 0) {+ landedAt = animator.get('opacity');+ }+ }+ expect(landedAt).not.toBeNull();+ expect(landedAt as number).toBeLessThan(0.05);+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBeCloseTo(to, 9);+ }+ });++ it('an entrance lands in place and fades in', async () => {+ const {animator} = reduced();animator.set({y: 400, opacity: 0});animator.animate({y: 0, opacity: 1}, {spring: springs.sheetPresent});+ await commitFrame(clock); // the browser starts itexpect(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,@@ -818,74 +2055,139 @@ describe('Reduced Motion on a coarse pointer (DR2): a cross-fade of 200 ms or le);});- it('an exit fades out in place, then moves', () => {+ it('an exit fades out in place, then lands', async () => {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',+ await commitFrame(clock); // the browser starts it+ expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(+ 1 - ease(0.5),+ 9,);+ await advance(fade - 1);+ expect(animator.get('y')).toBe(0);+ await advance(1);+ expect(animator.get('y')).toBe(400);+ expect(animator.get('opacity')).toBe(0);+ expect(opacityOnly()).toBe(true);});- it('an opacity-only change fades within 200 ms, with no spring', () => {+ it('an opacity change on a spring becomes the timed fade, never the spring', async () => {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,+ animator.animate({opacity: 0}, {spring: springs.alertDismiss});+ await commitFrame(clock); // the browser starts it+ expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(+ 1 - ease(0.5),+ 9,+ );+ expect(animator.get('opacity', 1000 + fade)).toBe(0);+ expect(Number(live('opacity')[0].options.duration)).toBeCloseTo(+ fade + END_HOLD_MS,+ 6,);- 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);+ it('a slide without opacity takes its direction from crossfadeAs', async () => {+ const entrance = reduced().animator;+ entrance.set({x: 300});+ entrance.animate(+ {x: 0},+ {spring: springs.navigationPush},+ {crossfadeAs: 'entrance'},+ );+ await commitFrame(clock); // the browser starts it+ expect(entrance.get('x', 1000)).toBe(0);+ expect(entrance.get('opacity', 1000)).toBe(0);+ expect(entrance.get('opacity', 1000 + fade / 2)).toBeCloseTo(ease(0.5), 9);+ expect(entrance.get('opacity', 1000 + fade)).toBe(1);++ const exit = reduced().animator;+ exit.animate(+ {y: 800},+ {spring: springs.sheetDismiss},+ {crossfadeAs: 'exit'},+ );+ await commitFrame(clock); // the browser starts it+ expect(exit.get('opacity', clock + fade / 2)).toBeCloseTo(1 - ease(0.5), 9);+ await advance(fade);+ // Lands, and the opacity returns to its value, in one plain write.+ expect(exit.get('y')).toBe(800);+ expect(exit.get('opacity')).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', () => {+ it('a later call before the landing takes the property over', async () => {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);+ await advance(fade / 4);+ animator.set({x: 40});+ await advance(fade);+ expect(animator.get('x')).toBe(40);+ });++ it('completes at once on a fine pointer, opacity included', () => {+ const {animator} = reduced(false);+ animator.animate({x: 100, opacity: 0.5}, {spring: springs.navigationPush});expect(recorded).toHaveLength(0);+ expect(animator.get('x')).toBe(100);+ expect(animator.get('opacity')).toBe(0.5);});- 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,- });+ it('fades on a fine pointer when a touch release started the call', async () => {+ const {animator} = reduced(false);+ animator.animate(+ {y: 400, opacity: 0},+ {spring: springs.sheetDismiss},+ {touchRelease: true},+ );+ await commitFrame(clock); // the browser starts it+ expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(+ 1 - ease(0.5),+ 9,+ );+ await advance(fade);+ expect(animator.get('y')).toBe(400);+ });++ it('no theme lengthens the fade', async () => {+ const {animator, element} = reduced();+ element.style.setProperty(+ '--motion-timing-reduced-motion-cross-fade-ms',+ '900ms',+ );+ document.documentElement.append(element);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);+ await commitFrame(clock); // the browser starts it+ expect(animator.get('opacity', 1000 + fade)).toBe(0);+ element.remove();+ });++ it('says what it makes of a call, for feedback with no fade of its own', () => {+ expect(setup().animator.reducedMotion()).toBe('off');+ expect(reduced().animator.reducedMotion()).toBe('crossfade');+ expect(reduced(false).animator.reducedMotion()).toBe('instant');+ expect(reduced(false).animator.reducedMotion({touchRelease: true})).toBe(+ 'crossfade',+ );+ });++ it('crossfadeAs changes nothing without Reduced Motion', async () => {+ const {animator} = setup();+ animator.set({y: 800});+ animator.animate(+ {y: 0},+ {spring: springs.sheetPresent},+ {crossfadeAs: 'entrance'},+ );+ await commitFrame(clock); // the browser starts it+ expect(live('opacity')).toHaveLength(0);+ expect(animator.getVelocity('y', 1010)).toBeLessThan(0);});});describe('decay: momentum curves (a coast)', () => {- it('plays a coast and comes to rest where it projects', () => {+ it('plays a coast and comes to rest where it projects', async () => {const {animator} = setup();animator.decay(coast(animator, {y: -2400}));+ await commitFrame(clock); // the browser starts itconst 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);@@ -901,12 +2203,13 @@ describe('decay: momentum curves (a coast)', () => {expect(animator.get('y', 1e7)).toBeCloseTo(glide.rest, 9);});- it('a coast that reaches an edge hands its velocity to the edge spring', () => {+ it('a coast that reaches an edge hands its velocity to the edge spring', async () => {const {animator} = setup();animator.set({y: -100});animator.decay(coast(animator, {y: 3000}, {bounds: {y: {min: -2000, max: 0}}}),);+ await commitFrame(clock); // the browser starts itconst glide = solveDecay({from: -100, velocity: 3000});const contact = 1000 + (glide.timeToReach(0) as number) * 1000;expect(animator.get('y', contact)).toBeCloseTo(0, 6);@@ -919,12 +2222,13 @@ describe('decay: momentum curves (a coast)', () => {expect(animator.get('y', 1e7)).toBe(0);});- it('a release past an edge springs straight back with the release velocity', () => {+ it('a release past an edge springs straight back with the release velocity', async () => {const {animator} = setup();animator.set({x: 60});animator.decay(coast(animator, {x: 400}, {bounds: {x: {min: -500, max: 0}}}),);+ await commitFrame(clock); // the browser starts itexpect(animator.getVelocity('x')).toBeCloseTo(400, 6);const curve = solveSpring(toSpring(scroll.bounce), {from: 60,@@ -934,18 +2238,21 @@ describe('decay: momentum curves (a coast)', () => {expect(animator.get('x', 1100)).toBeCloseTo(curve.value(0.1), 9);});- it('a coast continues a running spring from its presentation value', () => {+ it('a coast continues a running spring from its presentation value', async () => {const {animator} = setup();animator.animate({x: 300}, {spring: springs.settle});+ await commitFrame(clock); // the browser starts itclock += 80;const from = animator.get('x');+ expect(from).toBeGreaterThan(0);animator.decay(coast(animator, {x: 900}));+ await commitFrame(clock);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();+ it('plays any curve as given, and a zero-length one rests at its value', async () => {+ const {animator} = setup();const linear = {duration: 0.5,at: (t: number) => 200 * t,@@ -953,17 +2260,18 @@ describe('decay: momentum curves (a coast)', () => {};animator.decay({x: linear,- opacity: {duration: 0, at: () => 0.5, velocity: () => 0},+ y: {duration: 0, at: () => 5, velocity: () => 0},});+ await commitFrame(clock); // the browser starts itexpect(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');+ expect(animator.get('y')).toBe(5);});- it('keeps moving under Reduced Motion: a throw is the finger’s', () => {- const {animator, element} = setup({prefersReducedMotion: () => true});+ it('keeps moving under Reduced Motion: momentum continues the throw (DEC-2)', async () => {+ const {animator, element} = setup({reduced: true});animator.decay(coast(animator, {x: 1000}));+ await commitFrame(clock); // the browser starts itexpect(animator.getVelocity('x', 1016)).toBeGreaterThan(900);// No cross-fade: the coast moves the element and leaves opacity alone.expect(live('translate')).toHaveLength(1);@@ -972,16 +2280,18 @@ describe('decay: momentum curves (a coast)', () => {});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).+ // Bundled for a page, the animator and reducedMotionFade() read 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'))}],`,+ ` entryPoints: ${JSON.stringify(['animator.ts', 'reducedMotion.ts'].map(file => path.resolve(__dirname, file)))},`,+ ' outdir: "out",'," bundle: true, write: false, format: 'esm', logLevel: 'silent',",'});',- 'process.stdout.write(result.outputFiles[0].text);',+ 'process.stdout.write(result.outputFiles.map(file => file.text).join("\\n"));',].join('\n');const bundle = execFileSync(process.execPath,@@ -1013,7 +2323,6 @@ 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);@@ -1030,18 +2339,71 @@ describe('attach', () => {expect(element.style.translate).toBe('300px 0px');});+ it('unmounting settles a pending atRest() wait and leaves no poll timer', async () => {+ const {animator} = setup();+ animator.animate({x: 300}, {spring: springs.settle});+ const rest = animator.atRest();+ animator.attach(null);+ // Resolves without any timer running (none is advanced here).+ await rest;+ expect(vi.getTimerCount()).toBe(0);+ });+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);+ // At the end of the task, once no node has replaced it.+ await Promise.resolve();expect(vi.getTimerCount()).toBe(0);await expect(handle.finished).resolves.toBe(false);});- it('detaching cancels the running animations', () => {+ it('a node replacement keeps every handle and atRest() wait: the motion goes on on the new node', async () => {+ const {animator} = setup();+ const handle = animator.animate({x: 300}, {spring: springs.settle});+ let rested = false;+ void animator.atRest().then(() => {+ rested = true;+ });+ let finished: boolean | null = null;+ void handle.finished.then(value => {+ finished = value;+ });+ // React's replacement order: the old node detaches, the new one attaches.+ animator.attach(null);+ animator.attach(document.createElement('div'));+ for (let tick = 0; tick < 5; tick++) {+ await Promise.resolve();+ }+ expect(finished).toBeNull();+ expect(rested).toBe(false);+ await advance(5000);+ expect(finished).toBe(true);+ expect(rested).toBe(true);+ });++ it('unmounting settles every atRest() wait, as dispose() does', async () => {+ const {animator} = setup();+ animator.animate({x: 300}, {spring: springs.settle});+ let rested = false;+ void animator.atRest().then(() => {+ rested = true;+ });+ animator.attach(null);+ // Without advancing time: the curve has not ended.+ for (let tick = 0; tick < 5; tick++) {+ await Promise.resolve();+ }+ expect(rested).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('detaching cancels the running animations', async () => {const {animator} = setup();animator.animate({x: 300}, {spring: springs.settle});+ await commitFrame(clock); // the browser starts itanimator.attach(null);expect(recorded.every(a => a.cancelled)).toBe(true);expect(animator.get('x', 1050)).toBeGreaterThan(0);diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 9726911c15..7114cbaddf 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -2,7 +2,8 @@/*** @file animator.ts- * @input An element, target values, and a spring or momentum curves+ * @input An element, target values, and a spring, momentum curves (coast.ts)+ * or any closed-form curve* @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@@ -16,12 +17,11 @@* 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`,+ * 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).+ * keep advancing every frame while JavaScript is busy (`spec:AST-094` FR5).** Why keyframes and not one `linear()` easing: measured in Chromium, both* forms are composited and equally precise for the same samples, but WebKit's@@ -37,8 +37,8 @@* 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+ * mid-flight from the value on screen, and a new target starts from the+ * current value with the current velocity (`spec:AST-094` FR6). A gesture's release velocity* can be handed in explicitly instead.** End state without a flicker frame: the element's inline style always holds@@ -50,48 +50,107 @@* 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.+ * Start time: a call that starts from rest (nothing on its channels moving,+ * no `options.at`) gets no start time, so the browser starts it when it+ * commits it, as Core Animation starts an animation at its transaction's+ * commit: a main-thread block before that frame delays the motion instead of+ * skipping into it. Everything the call starts, and every+ * call from rest in the same task, starts at that one time, which+ * `handle.started` reports. A call that continues motion on+ * screen (a retarget, a catch) keeps an explicit start at the call time, or+ * `options.at` to line several animators up, so the new curve continues+ * from the frame on screen. Keyframes are sampled from the call's start, 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).+ * WebKit starts an animation created just before a block at its last frame+ * time before the block, so there the motion still skips into its curve;+ * Chromium starts it after the block.+ *+ * Promotion: Mobile Safari runs an animation whose start time is set from+ * script on its compositor at its first commit only if the element already+ * has a compositing layer; without one, a block right after that commit+ * freezes it (iOS 26.2 simulator: 2 of 7 runs kept moving). Every animation+ * the animator creates, and every `set`, therefore promotes its channels in+ * the same task: inline `will-change` on the element, merged with the+ * element's own. That is enough (5 of 5, and 4 of 4 through the animator);+ * promotion ends PROMOTION_LINGER_MS after the last motion.+ *+ * Known limits, iOS Safari (measured on the iOS 26.2 simulator):+ * - a block in the task that starts a motion delays it: it starts when the+ * browser commits it, after the block;+ * - an animation created in the task that first displays a dialog stays on+ * the main thread: start it in the next animation frame;+ * - after a long block, an animation frame's timestamp is when the frame was+ * due, so passing it as `at` starts the curve in the past: keep the default+ * clock;+ * - WebKit does not promote the siblings a moving layer will cross, so a+ * moving layer below content can paint over it: give it `z-index: -1`+ * inside a parent with `isolation: isolate`;+ * - a tap-driven start can show its first moving frame two to four frames+ * into the curve (simulator, not yet confirmed on a device).+ *+ * Reduced Motion (design:reduced-motion): with `prefers-reduced-motion:+ * reduce`, every `animate` (travel or opacity) is replaced, and nothing moves, scales or springs. The planner+ * (reducedMotionPlan.ts) decides what each call becomes; the animator+ * applies the plan and runs its landings:+ * - on a coarse primary pointer, or for a call started by a touch drag's+ * release on any pointer (`touchRelease`), it becomes (DR2) an+ * opacity-only cross-fade of `timing.reducedMotionCrossFadeMs` (200 ms)+ * on `timing.curves.move`:+ * - entering (opacity rises from 0 in the same call, or `crossfadeAs:+ * 'entrance'`): lands in its new place at once and fades in;+ * - leaving (opacity falls to 0, or `crossfadeAs: 'exit'`): fades out in+ * place, then lands;+ * - an opacity change alone: fades to its value;+ * - otherwise: dips (fades out, lands, fades back in);+ * travel lands with a plain style write while the element is transparent,+ * never as an animated transform; a busy main thread only keeps it+ * transparent longer, and a dip fades back in from the landing; a later+ * call that lands too carries a landing still waiting (two calls in one+ * frame land together), and a later opacity change lands it at once;+ * - on any other primary pointer (DR3) it completes at once.+ * No call option and no theme value lengthens the fade or keeps travel (DR4):+ * the fade's length is not a theme role.+ *+ * Momentum under Reduce Motion (`design:reduced-motion` DR2, DEC-2): a+ * decay's momentum continues the velocity a finger handed it on release+ * (UIScrollView's coast after a flick, with its bounce at an edge), so it+ * keeps its motion, as native momentum does: it is direct movement, not a+ * transition. A curve marked `isTransition` (coast()'s spring back from past+ * an edge), like a spring a component starts on release toward a target it+ * picks (a detent, a page), is a transition: it plays through the Reduce+ * Motion policy above, a cross-fade on a coarse pointer or after a touch+ * release (`touchRelease`) and at once elsewhere (DR2, DR3).** 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/reducedMotionPlan.ts (the Reduce Motion plan)* - /packages/core/src/motion/README.md*/import {cubicBezier} from './bezier';import {solveSpring, toSpring, type SpringDescription} from './spring';import {reducedMotionCrossFade} from './uikit/timing';+import {planReducedMotion, type ReducedMotionView} from './reducedMotionPlan';-/** A value the animator can drive. */+/**+ * A value the animator can drive.+ */export type MotionProperty ='x' | 'y' | 'rotate' | 'scaleX' | 'scaleY' | 'opacity';-/** Values by property; `scale` sets `scaleX` and `scaleY` together. */+/**+ * Values by property; `scale` sets `scaleX` and `scaleY` together.+ */export type MotionValues = Partial<Record<MotionProperty | 'scale', number>>;+/**+ * A spring and the velocity it starts with.+ */export interface SpringTransition {/** The spring, in any vocabulary of the constants table. */spring: SpringDescription;@@ -104,13 +163,41 @@ export interface SpringTransition {}/**- * 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.+ * Options of `animate`: the spring, a release velocity, the Reduced+ * Motion handling.+ */+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;+ /**+ * The call starts from the release of a touch drag (a sheet let go, a swipe+ * back released). Under Reduced Motion it then cross-fades whatever the+ * primary pointer (design:reduced-motion DR2), where another call on a+ * fine primary pointer completes at once (DR3). The gesture host knows;+ * nothing is inferred from the last pointer.+ */+ touchRelease?: boolean;+ /**+ * Which way the substituted cross-fade goes when the call's own opacity+ * does not say (a sheet slides in or out without fading): `'entrance'`+ * lands the travel at once and fades the opacity in from 0; `'exit'` fades+ * it out in place, then lands the travel and returns the opacity to its+ * value. The call's targets stay the end state; without Reduced Motion this+ * changes nothing.+ */+ crossfadeAs?: 'entrance' | 'exit';+}++/**+ * A closed-form curve a release starts, to play on the compositor through+ * `Animator.decay`: a released scroll view's coast and its edge bounce+ * (coast.ts). 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. */@@ -127,27 +214,24 @@ export interface MotionCurve {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;-}-+/**+ * Options of `createAnimator`.+ */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;+ /**+ * Runs a callback in the next animation frame; `requestAnimationFrame` by+ * default. A call from rest reads the start the browser gave it there.+ */+ requestFrame?: (callback: () => void) => void;}-/** One `animate` / `decay` call's animations. */+/**+ * One `animate` / `decay` call's animations.+ */export interface MotionHandle {/** The properties this call drives. */readonly properties: ReadonlyArray<MotionProperty>;@@ -156,6 +240,12 @@ export interface MotionHandle {* as soon as any of them is retargeted, stopped or set before that.*/readonly finished: Promise<boolean>;+ /**+ * When the motion started on the document timeline (ms): for a call from+ * rest, the time the browser committed it (a block before the first frame+ * moves it later); otherwise the call time, or `at`.+ */+ readonly started: Promise<number>;/** Presentation value of a property at `time` (default now). */value(property: MotionProperty, time?: number): number;/** Presentation velocity of a property at `time`, units/s. */@@ -170,7 +260,20 @@ export interface MotionHandle {stop(): void;}+/**+ * A compositor animator bound to one element (see the file header).+ */export interface Animator {+ /**+ * What Reduced Motion makes of a call on this element right now:+ * `'off'` (motion plays), `'crossfade'` (an opacity-only fade: a coarse+ * pointer, or `touchRelease`) or `'instant'` (any other pointer). For+ * feedback that has no fade of its own (a press lift, a lens chasing the+ * finger): skip it unless `'off'`.+ */+ reducedMotion(options?: {+ touchRelease?: boolean;+ }): 'off' | 'crossfade' | 'instant';/** The element the animator writes to, if attached. */readonly element: HTMLElement | null;/**@@ -195,18 +298,37 @@ export interface Animator {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.+ * Plays momentum curves as given, on the translate axes only: a released+ * scroll view's coast and edge bounce, which `coast()` (coast.ts) builds+ * from a finger's release velocity. Under Reduce Motion momentum keeps+ * its motion: it continues a throw, direct movement (design:reduced-motion+ * DR2, DEC-2). A curve marked `isTransition` (coast()'s spring back from+ * past an edge) is a transition and plays through the Reduce Motion+ * policy, as `animate` does. Anything else (a fade, a slide a tap starts)+ * is a transition too: play it with `animate`. Pass `touchRelease` when a+ * touch drag's release starts it, so a spring back cross-fades on any+ * pointer (DR2). Only a surface that coasts imports the coast math and the+ * scroll table.*/decay(- curves: Partial<Record<MotionProperty, MotionCurve>>,- options?: Pick<AnimateOptions, 'at'>,+ curves: Partial<Record<'x' | 'y', MotionCurve>>,+ options?: Pick<AnimateOptions, 'at' | 'touchRelease'>,): MotionHandle;+ /**+ * Moves properties by the given amounts at once, as when a layout shift+ * moves the element under them: a property moving on a spring keeps its+ * spring, velocity and target (the curve restarts from the shifted value);+ * any other moving curve shifts whole, its end included; a resting+ * property takes the offset and stays.+ */+ rebase(deltas: MotionValues, options?: Pick<AnimateOptions, 'at'>): void;/** Freezes properties (all by default) at their presentation values. */stop(properties?: ReadonlyArray<MotionProperty | 'scale'>): void;+ /**+ * Resolves once none of `properties` (every property by default) is moving:+ * after the last curve ends, whoever started it, retargets included.+ */+ atRest(properties?: ReadonlyArray<MotionProperty | 'scale'>): Promise<void>;/** Cancels everything and detaches. */dispose(): void;}@@ -216,8 +338,11 @@ export interface Animator {// ---------------------------------------------------------------------------interface Segment {- /** Start on the document timeline, ms. */- readonly start: number;+ /**+ * Start on the document timeline, ms. A call started from rest moves it to+ * the time the browser committed the animation (StartGroup).+ */+ start: number;/** Length in ms (finite). */readonly duration: number;/** Value from the end on. */@@ -228,11 +353,38 @@ interface Segment {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;+ /** The call's start group while its start waits for the commit. */+ group?: StartGroup;+ /** The spring driving it, when one does (`rebase` keeps it). */+ spring?: SpringDescription;+}++/**+ * A call started from rest. Its animations are created without a start time,+ * so the browser starts them when it commits them, as Core Animation starts+ * an animation at its transaction's commit: a main-thread block before that+ * frame delays the motion instead of skipping into it. Until then the curves+ * read from the call time; once the browser's start is known they move to it.+ */+interface StartGroup {+ readonly provisional: number;+ readonly segments: Segment[];+ readonly animations: Animation[];+ readonly channels: Set<Channel>;+ resolved: boolean;+ /** A later call in the same task that took over its curves. */+ adoptedBy?: StartGroup;+ readonly resolve: (start: number) => void;+ readonly started: Promise<number>;+}++/** An atRest() call waiting for its curves to end. */+interface RestWait {+ timer: ReturnType<typeof setTimeout> | null;+ settle: () => void;}interface HandleState {@@ -241,6 +393,54 @@ interface HandleState {timer: ReturnType<typeof setTimeout> | null;}+/**+ * Reduced Motion travel that lands with a plain style write while the+ * element is fully transparent (never an animated transform), then, in a+ * dip, the fade back in.+ */+interface Landing {+ readonly owner: HandleState;+ /** ms after the call's start. */+ readonly at: number;+ readonly values: Map<MotionProperty, number>;+ /**+ * The fade back in that follows the landing (a dip); `isBorrowed` when it+ * returns to the stylesheet's opacity, which owns it again once it ends.+ */+ fadeIn: {+ readonly to: number;+ readonly ms: number;+ readonly isBorrowed?: boolean;+ } | null;+ /** The opacity written with the landing (an exit by role). */+ restore: number | null;+ /**+ * The restore returns to the stylesheet's opacity (an exit by role on a+ * surface no call owns opacity on): the stylesheet owns it again.+ */+ restoreIsBorrowed?: boolean;+ /** Earlier calls whose landings this one carries: they land with it. */+ readonly carried: HandleState[];+ /** Whose move each value is: a carried value keeps its own call. */+ readonly owners: Map<MotionProperty, HandleState>;+ timer: ReturnType<typeof setTimeout> | null;+ /** When it is due on the document timeline, once the call has started. */+ due: number | null;+}++/** What Reduced Motion makes of a call: its segments, and any landing. */+interface ReducedPlan {+ readonly next: Partial<Record<MotionProperty, Segment | null>>;+ /** Values that stay where they are until the landing writes them. */+ readonly holds: Partial<Record<MotionProperty, number>>;+ readonly landing: Omit<+ Landing,+ 'owner' | 'timer' | 'carried' | 'owners' | 'due'+ > | null;+ /** The stylesheet opacity a dip borrowed (no call owns opacity). */+ readonly borrowed?: number | null;+}+const PROPERTIES: ReadonlyArray<MotionProperty> = ['x','y',@@ -250,6 +450,9 @@ const PROPERTIES: ReadonlyArray<MotionProperty> = ['opacity',];+/** The axes momentum moves: `decay` takes only these (DR2, DEC-2). */+const DECAY_PROPERTIES: ReadonlyArray<'x' | 'y'> = ['x', 'y'];+const IDENTITY: Record<MotionProperty, number> = {x: 0,y: 0,@@ -259,7 +462,11 @@ const IDENTITY: Record<MotionProperty, number> = {opacity: 1,};-/** Within this of its target a curve is over (in the property's own unit). */+/**+ * Within this of its target a curve is over (in the property's own unit). A+ * curve built outside the animator (a progress curve) settles where a call+ * would with this as its epsilon.+ */export const SETTLE_THRESHOLD: Record<MotionProperty, number> = {x: 0.05,y: 0.05,@@ -295,13 +502,8 @@ 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',-];+/** How long an element stays promoted after its last motion, ms. */+export const PROMOTION_LINGER_MS = 500;type Channel = 'translate' | 'rotate' | 'scale' | 'opacity';@@ -341,6 +543,29 @@ function format(}}+const shared = new WeakMap<HTMLElement, Animator>();++/**+ * The one animator for `element`, created on+ * first use. Code that animates one element from several places (a swipe on+ * x, a removal on y) shares it, so their curves compose in one `translate`+ * track and retargeting one axis leaves the other on its curve; two+ * animators on one element would overwrite each other. `options` apply+ * when it is created; later calls get the same animator. Never `attach` it+ * elsewhere or `dispose` it: it lives as long as the element.+ */+export function animatorFor(+ element: HTMLElement,+ options: AnimatorOptions = {},+): Animator {+ let animator = shared.get(element);+ if (animator == null) {+ animator = createAnimator(element, options);+ shared.set(element, animator);+ }+ return animator;+}+/*** The inline text for a channel: `format`, except that an identity transform* is written `none`. Any other value, `translate: 0px 0px` included, makes@@ -412,25 +637,32 @@ function defaultNow(): number {return typeof performance === 'undefined' ? Date.now() : performance.now();}-function matchesMedia(query: string): boolean {+/**+ * Whether the user asked for reduced motion (`prefers-reduced-motion:+ * reduce`), read at the moment of the call: the preference the animator uses+ * by default for its Reduce Motion substitution. A component never reads it+ * to pick a curve of its own: its motion settings do not override the+ * policy (design:reduced-motion DR4); `animator.reducedMotion()` or+ * `reducedMotionFade()` gives the policy's answer. False without a window+ * (server rendering).+ */+export function defaultPrefersReducedMotion(): boolean {return (typeof window !== 'undefined' &&typeof window.matchMedia === 'function' &&- window.matchMedia(query).matches+ window.matchMedia('(prefers-reduced-motion: reduce)').matches);}-function defaultPrefersReducedMotion(): boolean {- return matchesMedia('(prefers-reduced-motion: reduce)');-}--function defaultIsCoarsePointer(): boolean {- return matchesMedia('(pointer: coarse)');+/** Whether the primary pointer is coarse: `(pointer: coarse)`. */+export function defaultIsCoarsePointer(): boolean {+ return (+ typeof window !== 'undefined' &&+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(pointer: coarse)').matches+ );}-/** 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@@ -458,9 +690,17 @@ export function createAnimator(options: AnimatorOptions = {},): Animator {const now = options.now ?? defaultNow;- const prefersReducedMotion =- options.prefersReducedMotion ?? defaultPrefersReducedMotion;- const isCoarsePointer = options.isCoarsePointer ?? defaultIsCoarsePointer;+ const requestFrame =+ options.requestFrame ??+ (typeof requestAnimationFrame === 'function'+ ? (callback: () => void) => {+ requestAnimationFrame(() => callback());+ }+ : null);+ // Reduced Motion reads the person's settings and nothing else: no option+ // overrides them (design:reduced-motion DR4).+ const prefersReducedMotion = defaultPrefersReducedMotion;+ const isCoarsePointer = defaultIsCoarsePointer;const resting: Record<MotionProperty, number> = {...IDENTITY,...expand(options.initial ?? {}),@@ -476,6 +716,21 @@ export function createAnimator(*/let borrowedOpacity: number | null = null;let target: HTMLElement | null = null;+ /** Calls from rest whose start still waits for the browser's commit. */+ const pendingGroups = new Set<StartGroup>();+ /** atRest() calls still waiting; dispose settles them. */+ const restWaits = new Set<RestWait>();+ /** A detach that settles as an unmount at the end of the task, unless an attach follows. */+ let unmountQueued = false;+ /** The call being committed, when it starts from rest. */+ let callGroup: StartGroup | null = null;+ /** Channels promoted to the element's compositing layer (will-change). */+ const promoted = new Set<Channel>();+ /** The element's own inline will-change, restored when promotion ends. */+ let ownWillChange: string | null = null;+ /** The stylesheet's will-change when there is no inline value. */+ let sheetWillChange = '';+ let demoteTimer: ReturnType<typeof setTimeout> | null = null;/** Channels whose identity the last node held inline (see `attach`). */let heldIdentity = new Set<Channel>();@@ -495,7 +750,15 @@ export function createAnimator(return segment;};- const valueAt = (property: MotionProperty, time: number): number => {+ /**+ * A curve whose call the browser has not started yet: still at its start+ * on screen (valueAt), already moving in the model (velocityAt).+ */+ const isHeld = (segment: Segment) =>+ segment.group != null && !segment.group.resolved;++ /** The curve itself at `time`: what the keyframes play. */+ const curveAt = (property: MotionProperty, time: number): number => {const segment = segments.get(property);if (segment == null) {return resting[property];@@ -506,7 +769,29 @@ export function createAnimator(return segment.at(Math.max(0, time - segment.start));};+ /**+ * The value on screen at `time`. A curve the browser has not started is at+ * its start up to now; a later time reads the curve from its provisional+ * start, the model's best guess until the browser's start moves it (a+ * companion that samples a curve ahead follows its shape).+ */+ const valueAt = (property: MotionProperty, time: number): number => {+ const segment = segments.get(property);+ if (segment != null && isHeld(segment) && time <= now()) {+ // Nothing has moved on screen until the browser starts the call.+ return segment.at(0);+ }+ return curveAt(property, time);+ };+const velocityAt = (property: MotionProperty, time: number): number => {+ const held = segments.get(property);+ if (held != null && isHeld(held)) {+ // Still at its start on screen, but moving in the model: a retarget+ // carries the velocity the curve has reached by now, so a flick whose+ // moves all land before the browser starts any keeps its speed.+ return held.speed(Math.max(0, time - held.start));+ }const segment = segmentAt(property, time);if (segment == null || time < segment.start) {return 0;@@ -514,9 +799,9 @@ export function createAnimator(return segment.speed(time - segment.start);};- // A value just before a jump at absolute time `time`.+ // The curve just before a jump at absolute time `time`.const valueBefore = (property: MotionProperty, time: number): number =>- valueAt(property, time - 1e-6);+ curveAt(property, time - 1e-6);// -- writing --------------------------------------------------------------@@ -557,13 +842,10 @@ export function createAnimator(return [];}const times: number[] = [begin];- const value = (t: number) => valueAt(property, t);+ const value = (t: number) => curveAt(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];@@ -596,10 +878,13 @@ export function createAnimator(};const rebuild = (channel: Channel, time: number) => {- running.get(channel)?.cancel();+ const previous = running.get(channel);running.delete(channel);clearTimeout(retireTimers.get(channel));retireTimers.delete(channel);+ // The element's inline style holds the end state, so its old animation+ // can go first.+ previous?.cancel();const properties = CHANNELS[channel];// Settled curves become resting values.for (const property of properties) {@@ -611,15 +896,28 @@ export function createAnimator(}writeInline(channel, finalValue);const moving = properties.filter(p => segments.has(p));- if (- target == null ||- moving.length === 0 ||- typeof target.animate !== 'function'- ) {+ if (target == null || typeof target.animate !== 'function') {+ previous?.cancel();+ return;+ }+ if (moving.length === 0) {return;}+ // A channel rebuilt by an explicit call (set, rebase, a retarget of+ // another axis) while one of its curves still waits for the browser's+ // start keeps that start: no explicit start for this animation.+ const waiting =+ callGroup ??+ moving+ .map(p => (segments.get(p) as Segment).group)+ .find(group => group != null && !group.resolved) ??+ null;+ // The keyframes start where the animation will: at the waiting call's+ // own time, which its start moves to the browser's (resolveGroup), so a+ // write later in the task keeps the screen on the model's clock.+ const from = waiting?.provisional ?? time;const end = Math.min(- time + MAX_DURATION_MS,+ from + MAX_DURATION_MS,Math.max(...moving.map(p =>@@ -628,15 +926,35 @@ export function createAnimator(),),);- if (end <= time) {+ if (end <= from) {return;}+ if (callGroup != null) {+ // A curve of an earlier call still waiting for its first frame is+ // rebaked here: it starts with this call's commit.+ for (const property of moving) {+ const segment = segments.get(property) as Segment;+ const group = segment.group;+ if (group != null && group !== callGroup && !group.resolved) {+ const index = group.segments.indexOf(segment);+ if (index >= 0) {+ group.segments.splice(index, 1);+ }+ group.adoptedBy = callGroup;+ segment.group = callGroup;+ // Re-dated to this call's time: it starts at the commit too, not+ // the work between the two calls into its curve.+ segment.start += callGroup.provisional - group.provisional;+ callGroup.segments.push(segment);+ }+ }+ }const collect = (scale: number) => {- const times = new Set<number>([time, end]);+ const times = new Set<number>([from, end]);for (const property of moving) {for (const t of sampleTimes(property,- time,+ from,end,SAMPLE_TOLERANCE[property] * scale,)) {@@ -658,17 +976,17 @@ export function createAnimator(const segment = segments.get(property) as Segment;for (const j of segment.jumps) {const t = segment.start + j;- if (t > time && t <= end) {+ if (t > from && t <= end) {jumpTimes.add(t);all.add(t);}}}const times = [...all].sort((a, b) => a - b);- const span = end - time + END_HOLD_MS;+ const span = end - from + END_HOLD_MS;const keyframes: Keyframe[] = [];for (const t of times) {- const offset = (t - time) / span;+ const offset = (t - from) / span;if (jumpTimes.has(t)) {keyframes.push({offset,@@ -678,11 +996,12 @@ export function createAnimator(keyframes.push({offset,[channel]: format(channel, p =>- t >= end ? finalValue(p) : valueAt(p, t),+ t >= end ? finalValue(p) : curveAt(p, t),),});}keyframes.push({offset: 1, [channel]: format(channel, finalValue)});+ promote(channel);const animation = target.animate(keyframes, {duration: span,// The last keyframes hold the end state (END_HOLD_MS); filling both@@ -692,9 +1011,33 @@ export function createAnimator(fill: 'both',easing: 'linear',});- // One clock: the keyframes were sampled from `time`.- animation.startTime = time;+ if (waiting != null) {+ // From rest: no start time, so the browser starts the animation when+ // it commits it (StartGroup); the keyframes are sampled from `from`,+ // the call's own start.+ waiting.animations.push(animation);+ waiting.channels.add(channel);+ // A cancel before the first frame rejects its ready promise.+ (animation as Partial<Animation>).ready?.catch(() => {});+ } else {+ // One clock: the keyframes were sampled from `time`.+ animation.startTime = time;+ }running.set(channel, animation);+ previous?.cancel();+ scheduleRetire(channel, animation, end);+ };++ /**+ * Once the main thread runs after the curve's end, the animation leaves the+ * running state: the element's inline style already shows the end values.+ */+ const scheduleRetire = (+ channel: Channel,+ animation: Animation,+ end: number,+ ) => {+ clearTimeout(retireTimers.get(channel));const retire = () => {retireTimers.delete(channel);if (running.get(channel) !== animation) {@@ -713,19 +1056,14 @@ export function createAnimator();return;}- animation.cancel();running.delete(channel);+ animation.cancel();releaseIdentity(channel);+ flushReleases();};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;@@ -738,6 +1076,65 @@ export function createAnimator(return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 1;};+ /**+ * Whether the animator holds an opacity of its own on the element: an inline+ * value it wrote (a `set` over a stylesheet that hides or dims it). A dip+ * returns to that value.+ */+ const writesOwnOpacity = (): boolean =>+ (target?.style.getPropertyValue('opacity') ?? '') !== '';++ /** Gives the element's opacity back to its stylesheet: its inline value goes. */+ const releaseOwnOpacity = () => {+ target?.style.removeProperty('opacity');+ };++ /**+ * Lands every Reduce Motion move still waiting, at once, on the current+ * element: its travel, and the opacity its fade was heading to (the+ * stylesheet's again for a borrowed one). Its calls settle `finished`.+ */+ const landPending = (finished: boolean) => {+ if (landings.size === 0) {+ return;+ }+ const changed = new Set<MotionProperty>();+ let handedBack = false;+ for (const landing of [...landings]) {+ endLanding(landing);+ for (const [property, value] of landing.values) {+ segments.delete(property);+ resting[property] = value;+ changed.add(property);+ }+ if (landing.fadeIn != null || landing.restore != null) {+ const borrowed =+ landing.fadeIn?.isBorrowed === true ||+ landing.restoreIsBorrowed === true;+ segments.delete('opacity');+ resting.opacity = borrowed+ ? IDENTITY.opacity+ : (landing.fadeIn?.to ?? landing.restore ?? IDENTITY.opacity);+ changed.add('opacity');+ if (borrowed) {+ borrowedOpacity = null;+ handedBack = true;+ }+ }+ for (const owner of [landing.owner, ...landing.carried]) {+ carriedOwners.delete(owner);+ if (!owner.settled) {+ settle(owner, finished);+ }+ }+ }+ commit(changed, now());+ if (handedBack) {+ // The stylesheet owns its opacity again: no value stays inline.+ releaseOwnOpacity();+ }+ };+/*** 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).@@ -749,35 +1146,74 @@ export function createAnimator(borrowedOpacity = null;segments.delete('opacity');resting.opacity = IDENTITY.opacity;- target?.style.removeProperty('opacity');+ releaseOwnOpacity();};+ /**+ * 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.+ */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).+ if ([...landings].some(landing => landing.fadeIn?.isBorrowed === true)) {+ // At the bottom of the dip, before it lands and fades back in.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');+ releaseOwnOpacity();return;}- const text = target.style.getPropertyValue(channel);- if (text !== IDENTITY_TEXT[channel]) {+ if (target.style.getPropertyValue(channel) !== 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);+ // Read with every other channel the same commit leaves at identity: one+ // style read for the element, not one per channel (flushReleases).+ releasing.add(channel);+ if (!releaseQueued) {+ releaseQueued = true;+ queueMicrotask(flushReleases);+ }+ };++ /** Channels left at identity whose stylesheet value is still to be read. */+ const releasing = new Set<Channel>();+ let releaseQueued = false;++ /**+ * Removes the identity values written since the last flush, reads the+ * stylesheet once for all of them, and puts back the ones it would move:+ * a single forced style read per element and commit, where a read per+ * channel used to force one each.+ */+ const flushReleases = () => {+ releaseQueued = false;+ const element = target;+ const channels = [...releasing].filter(+ channel =>+ !running.has(channel) &&+ element?.style.getPropertyValue(channel) === IDENTITY_TEXT[channel],+ );+ releasing.clear();+ if (element == null || channels.length === 0) {+ return;+ }+ for (const channel of channels) {+ element.style.removeProperty(channel);+ }+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ for (const channel of channels) {+ const underneath = style?.getPropertyValue(channel);+ if (underneath != null && !isIdentityText(channel, underneath)) {+ element.style.setProperty(channel, IDENTITY_TEXT[channel]);+ }}};@@ -796,90 +1232,486 @@ export function createAnimator(return animation.playState === 'paused' ? Math.max(left, 1) : left;};- // -- handles ---------------------------------------------------------------- const lastSpring = new WeakMap<HandleState, SpringDescription>();+ // -- promotion -------------------------------------------------------------- const interrupt = (property: MotionProperty, time: number) => {- const segment = segments.get(property);- if (segment == null) {+ /** Writes the promoted channels as will-change. */+ const writePromotion = (element: HTMLElement) => {+ const list = [...promoted].join(', ');+ if (list === '') {+ element.style.willChange = ownWillChange ?? '';+ ownWillChange = null;return;}- if (time < segment.start + segment.duration) {- settle(segment.owner, false);+ if (ownWillChange == null) {+ ownWillChange = element.style.willChange;+ // Without an inline value, the stylesheet's reasons stay alongside the+ // promotion's (read once, as the promotion starts).+ sheetWillChange =+ ownWillChange === ''+ ? (element.ownerDocument.defaultView+ ?.getComputedStyle(element)+ .getPropertyValue('will-change') ?? '')+ : '';}+ const base = ownWillChange !== '' ? ownWillChange : sheetWillChange;+ const own = base === 'auto' ? '' : base;+ const reasons = own+ .split(',')+ .map(reason => reason.trim())+ .filter(reason => reason !== '' && !promoted.has(reason as Channel));+ element.style.willChange = [...reasons, ...promoted].join(', ');};- const settle = (owner: HandleState, finished: boolean) => {- if (owner.settled) {+ /**+ * Gives the element a compositing layer for+ * `channel` from the task that starts the motion: Mobile Safari runs an+ * animation whose start time is set from script on its compositor at its+ * first commit only if the element already has a layer.+ */+ const promote = (channel: Channel) => {+ if (target == null) {return;}- owner.settled = true;- if (owner.timer != null) {- clearTimeout(owner.timer);- owner.timer = null;+ if (!promoted.has(channel)) {+ promoted.add(channel);+ writePromotion(target);}- owner.resolve(finished);+ scheduleDemote();};- 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()),- );+ /** Ends promotion PROMOTION_LINGER_MS after the last motion ends. */+ const scheduleDemote = () => {+ if (demoteTimer != null) {+ clearTimeout(demoteTimer);}- 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');+ let end = now();+ for (const segment of segments.values()) {+ end = Math.max(end, segment.start + segment.duration);+ }+ demoteTimer = setTimeout(+ () => {+ demoteTimer = null;+ const time = now();+ const moving = [...segments.values()].some(+ segment => time < segment.start + segment.duration,+ );+ if (moving || pendingGroups.size > 0) {+ scheduleDemote();+ return;}- return animator.animate(to, {...transition, spring}, retargetOptions);+ demote();},- stop: () =>- animator.stop(properties.filter(p => segments.get(p)?.owner === owner)),- };- return handle;+ Math.max(0, end - now()) + PROMOTION_LINGER_MS,+ );};- 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};+ const demote = () => {+ if (demoteTimer != null) {+ clearTimeout(demoteTimer);+ demoteTimer = null;+ }+ if (promoted.size === 0) {+ return;+ }+ promoted.clear();+ if (target != null) {+ writePromotion(target);+ }};- // -- segment factories ------------------------------------------------------+ // -- starting from rest ---------------------------------------------------- const springSegment = (- owner: HandleState,- property: MotionProperty,- start: number,+ /**+ * A call starts from rest when nothing on the channels it drives is moving+ * (a curve still waiting for its first frame counts as rest) and nothing+ * pins its clock (`at`). Returns its start group, or null for an explicit+ * start.+ */+ const beginGroup = (+ time: number,+ properties: Iterable<MotionProperty>,+ at: number | undefined,+ ): StartGroup | null => {+ if (target == null || typeof target.animate !== 'function') {+ return null;+ }+ const channels = new Set<Channel>();+ for (const property of properties) {+ channels.add(CHANNEL_OF[property]);+ }+ if (at != null) {+ // An explicit clock is the caller's, except a clock no later than a+ // call from rest on these channels still waiting for the browser's+ // start (an event timestamp, such as a drop's, for the reorder that+ // rebases it): the new call joins that call, and the browser's start+ // moves both. A later clock is a later call, often a frame or more+ // later while the browser has not started the first: it keeps its own+ // clock, since joining would sample its curve from the earlier call's+ // time and hold its first value for the gap.+ for (const channel of channels) {+ for (const property of CHANNELS[channel]) {+ const group = segments.get(property)?.group;+ if (group != null && !group.resolved && at <= group.provisional) {+ return group;+ }+ }+ }+ return null;+ }+ for (const channel of channels) {+ for (const property of CHANNELS[channel]) {+ const segment = segments.get(property);+ if (+ segment != null &&+ time < segment.start + segment.duration &&+ (segment.group == null || segment.group.resolved)+ ) {+ return null;+ }+ }+ }+ let resolve: (start: number) => void = () => {};+ const started = new Promise<number>(r => {+ resolve = r;+ });+ return {+ provisional: time,+ segments: [],+ animations: [],+ channels: new Set(),+ resolved: false,+ resolve,+ started,+ };+ };++ /** Commits a call's changes, from rest when it has a start group. */+ const commitCall = (+ group: StartGroup | null,+ owner: HandleState,+ changed: MotionProperty[],+ time: number,+ ) => {+ if (group != null) {+ for (const property of changed) {+ const segment = segments.get(property);+ if (segment != null && segment.owner === owner) {+ segment.group = group;+ group.segments.push(segment);+ }+ }+ }+ callGroup = group;+ try {+ commit(changed, time);+ } finally {+ callGroup = null;+ }+ if (group == null) {+ return;+ }+ if (group.animations.length === 0) {+ resolveGroup(group, group.provisional); // nothing to start+ return;+ }+ pendingGroups.add(group);+ for (const animation of group.animations) {+ // A cancel before the first frame rejects each one's ready promise.+ (animation as Partial<Animation>).ready?.catch(() => {});+ }+ const ready = (group.animations[0] as Partial<Animation>).ready;+ if (ready == null || typeof ready.then !== 'function') {+ resolveGroup(group, group.provisional); // no pending start to wait for+ return;+ }+ // The browser sets the start: at the frame that commits the animations,+ // or when its compositor starts them (Chromium). Read it in that first+ // frame, ahead of anything that might pause or seek the animations, and+ // when `ready` settles.+ requestFrame?.(() => syncGroup(group));+ ready.then(+ () => syncGroup(group),+ () => settleCancelled(group),+ );+ };++ /**+ * A call whose first animation was cancelled before its first frame: if a+ * later call in the same task took over its curves, it starts with that+ * call; otherwise it never started.+ */+ const settleCancelled = (group: StartGroup) => {+ if (group.resolved) {+ return;+ }+ let adopter = group.adoptedBy;+ while (adopter?.adoptedBy != null) {+ adopter = adopter.adoptedBy;+ }+ if (adopter != null && adopter !== group) {+ void adopter.started.then(start => resolveGroup(group, start));+ return;+ }+ // A same-task write replaced the animation the call waited on: the call+ // still starts with the browser's start of the ones that remain.+ if (awaitStart(group)) {+ return;+ }+ resolveGroup(group, group.provisional);+ };++ /**+ * Waits for the browser's start of a call through one of its animations+ * still playing; false when none is left to wait on.+ */+ const awaitStart = (group: StartGroup): boolean => {+ const live = group.animations.find(+ animation => animation.playState !== 'idle',+ );+ const ready = (live as Partial<Animation> | undefined)?.ready;+ if (ready == null || typeof ready.then !== 'function') {+ return false;+ }+ ready.then(+ () => syncGroup(group),+ () => settleCancelled(group),+ );+ return true;+ };++ const syncGroup = (group: StartGroup) => {+ if (group.resolved) {+ return;+ }+ for (const animation of group.animations) {+ if (animation.startTime != null) {+ resolveGroup(group, Number(animation.startTime));+ return;+ }+ }+ // Finished from outside before the browser started it (a sampler's+ // finish() on a held animation): nothing is left to wait on, so the call+ // keeps its own clock, and a later call on an explicit clock does not+ // join it and wait for a start that never comes.+ if (+ group.animations.length > 0 &&+ group.animations.every(+ animation =>+ animation.playState === 'finished' || animation.playState === 'idle',+ ) &&+ group.animations.some(animation => animation.playState === 'finished')+ ) {+ resolveGroup(group, group.provisional);+ return;+ }+ // No start yet (paused before its first frame by a harness or a page,+ // or resumed with play() and still pending): neither `ready` nor the+ // first frame will look again, so keep looking each frame until the call+ // has a start, or its animations finish (its own clock) or are cancelled.+ if (+ group.animations.some(+ animation =>+ animation.startTime == null && animation.playState !== 'idle',+ )+ ) {+ requestFrame?.(() => syncGroup(group));+ }+ };++ /** Reads the start of every call whose first frame has been committed. */+ const syncPending = () => {+ for (const group of pendingGroups) {+ syncGroup(group);+ }+ syncFinished();+ };++ /**+ * An animation finished from outside (a test utility's or devtools'+ * `finish()`) shows its end state while the model still reads its curve:+ * the curve ends now in the model too, so the next call starts from what+ * is on screen.+ */+ const syncFinished = () => {+ for (const [channel, animation] of running) {+ if (animation.playState !== 'finished') {+ continue;+ }+ const time = now();+ for (const property of CHANNELS[channel]) {+ const segment = segments.get(property);+ if (segment == null || time >= segment.start + segment.duration) {+ continue;+ }+ segments.delete(property);+ resting[property] = segment.target;+ }+ }+ };++ /** Moves a call from rest onto the time the browser started it. */+ const resolveGroup = (group: StartGroup, start: number) => {+ if (group.resolved) {+ return;+ }+ group.resolved = true;+ pendingGroups.delete(group);+ for (const animation of group.animations) {+ // One clock for the whole call; a cancelled one stays cancelled (a+ // start time would play it again).+ if (animation.startTime == null && animation.playState !== 'idle') {+ animation.startTime = start;+ }+ }+ const delta = start - group.provisional;+ if (delta !== 0) {+ for (const segment of group.segments) {+ segment.start += delta;+ }+ for (const channel of group.channels) {+ const animation = running.get(channel);+ if (animation == null || !group.animations.includes(animation)) {+ continue;+ }+ const ends = CHANNELS[channel].flatMap(p => {+ const segment = segments.get(p);+ return segment == null ? [] : [segment.start + segment.duration];+ });+ if (ends.length > 0) {+ scheduleRetire(channel, animation, Math.max(...ends));+ }+ }+ for (const owner of new Set(group.segments.map(s => s.owner))) {+ if (owner.settled || owner.timer == null) {+ continue;+ }+ clearTimeout(owner.timer);+ const ends = group.segments+ .filter(segment => segment.owner === owner)+ .map(segment => segment.start + segment.duration);+ owner.timer = setTimeout(+ () => {+ owner.timer = null;+ settle(owner, true);+ },+ Math.max(0, Math.max(start, ...ends) - now()),+ );+ }+ }+ group.resolve(start);+ };++ // -- handles --------------------------------------------------------------++ const lastSpring = new WeakMap<HandleState, SpringDescription>();++ const interrupt = (property: MotionProperty, time: number) => {+ cancelLanding(property);+ const segment = segments.get(property);+ if (segment == null) {+ return;+ }+ if (+ time < segment.start + segment.duration &&+ !carriedOwners.has(segment.owner)+ ) {+ 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,+ group: StartGroup | null = null,+ ): 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,+ started: group?.started ?? Promise.resolve(time),+ value: (property, at = now()) => {+ syncPending();+ return valueAt(property, at);+ },+ velocity: (property, at = now()) => {+ syncPending();+ return 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);+ },+ // The call's own curves, and its travel still waiting to land under+ // Reduce Motion: a catch freezes both where they are on screen+ // (AST-094 FR6), travel first so the fade's landing no longer carries+ // it, as `animator.stop()` does.+ stop: () =>+ animator.stop(+ PROPERTIES.filter(+ p =>+ properties.includes(p) &&+ (segments.get(p)?.owner === owner ||+ [...landings].some(+ landing =>+ landing.values.has(p) &&+ (landing.owners.get(p) ?? landing.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,@@ -901,6 +1733,7 @@ export function createAnimator(speed: t => curve.velocity(t / 1000),jumps: [],owner,+ spring,};};@@ -940,23 +1773,6 @@ export function createAnimator(};};- 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) => {@@ -970,6 +1786,342 @@ export function createAnimator(for (const channel of channels) {rebuild(channel, time);}+ flushReleases();+ };++ /** Reduced Motion landings still waiting for the element to be transparent. */+ const landings = new Set<Landing>();+ /** Calls a later call's landing carries: an interrupt does not settle them. */+ const carriedOwners = new Set<HandleState>();++ /**+ * A later write to `property` takes it from any landing. A write to opacity+ * decides what shows, so a landing still waiting writes its travel at once+ * rather than never, and its calls settle as interrupted.+ */+ const cancelLanding = (property: MotionProperty) => {+ for (const landing of [...landings]) {+ if (property === 'opacity') {+ endLanding(landing);+ landNow(landing);+ } else if (landing.values.delete(property)) {+ // Set or stopped before it landed: the call whose move it was did+ // not finish (a carried value is an earlier call's).+ const moved = landing.owners.get(property) ?? landing.owner;+ landing.owners.delete(property);+ if (!moved.settled) {+ settle(moved, false);+ }+ }+ }+ };++ const landNow = (landing: Landing) => {+ const changed: MotionProperty[] = [];+ for (const [property, value] of landing.values) {+ segments.delete(property);+ resting[property] = value;+ changed.push(property);+ }+ if (changed.length > 0) {+ commit(changed, now());+ }+ for (const owner of [landing.owner, ...landing.carried]) {+ carriedOwners.delete(owner);+ if (!owner.settled) {+ settle(owner, false);+ }+ }+ };++ /**+ * A later Reduced Motion call that lands too carries the landings still+ * waiting: their travel lands with its own, which wins where both move a+ * property, and their calls settle when it lands. So two calls in one+ * frame (a drag cancel's position and scale) both land.+ */+ const adoptLandings = (+ plan: NonNullable<ReducedPlan['landing']>,+ properties: ReadonlyArray<MotionProperty>,+ ): {carried: HandleState[]; owners: Map<MotionProperty, HandleState>} => {+ const carried: HandleState[] = [];+ const owners = new Map<MotionProperty, HandleState>();+ for (const landing of [...landings]) {+ for (const [property, value] of landing.values) {+ const moved = landing.owners.get(property) ?? landing.owner;+ if (!properties.includes(property) && !plan.values.has(property)) {+ plan.values.set(property, value);+ owners.set(property, moved);+ } else if (!moved.settled) {+ // This call takes the property over: the earlier move never lands.+ settle(moved, false);+ }+ }+ carried.push(landing.owner, ...landing.carried);+ endLanding(landing);+ }+ for (const owner of carried) {+ carriedOwners.add(owner);+ }+ return {carried, owners};+ };++ /** Where opacity is heading: past a waiting landing's fade back in. */+ const opacityHeading = (): number => {+ let to = finalValue('opacity');+ for (const landing of landings) {+ if (landing.fadeIn != null) {+ to = landing.fadeIn.to;+ } else if (landing.restore != null) {+ to = landing.restore;+ }+ }+ return to;+ };++ const endLanding = (landing: Landing) => {+ if (landing.timer != null) {+ clearTimeout(landing.timer);+ }+ landings.delete(landing);+ };++ /** Arms a landing from the call's start (the browser's, for a call from rest). */+ const scheduleLanding = (+ owner: HandleState,+ started: Promise<number>,+ plan: NonNullable<ReducedPlan['landing']>,+ adopted: ReturnType<typeof adoptLandings> | null,+ ) => {+ const owners = new Map<MotionProperty, HandleState>();+ for (const property of plan.values.keys()) {+ owners.set(property, adopted?.owners.get(property) ?? owner);+ }+ const landing: Landing = {+ ...plan,+ owner,+ carried: adopted?.carried ?? [],+ owners,+ timer: null,+ due: null,+ };+ landings.add(landing);+ // The handle settles when the landing (and its fade back in) is done.+ if (owner.timer != null) {+ clearTimeout(owner.timer);+ owner.timer = null;+ }+ void started.then(start => {+ if (!landings.has(landing)) {+ return;+ }+ landing.due = start + landing.at;+ landing.timer = setTimeout(+ () => land(landing),+ Math.max(0, landing.due - now()),+ );+ });+ };++ /**+ * Writes the travel while the element is transparent: a plain style write,+ * never an animation (DR2: opacity only), so it is never shown in the wrong+ * place. In a dip the fade back in starts from here and takes what is left+ * of the cross-fade, so the dip ends when it was due even when a busy main+ * thread runs this timer late; past the whole fade back in (over 100 ms+ * late) the element appears at once where it landed.+ */+ const land = (landing: Landing) => {+ landings.delete(landing);+ landing.timer = null;+ const time = now();+ const changed: MotionProperty[] = [];+ for (const [property, value] of landing.values) {+ segments.delete(property);+ resting[property] = value;+ changed.push(property);+ }+ let end = time;+ if (landing.fadeIn != null) {+ // The fade back in takes what is left of the cross-fade: a timer that+ // a busy main thread runs late shortens it, so the dip still ends+ // when it was due (design:reduced-motion DR2, 200 ms or less), and the+ // element is never shown before it lands.+ const late = landing.due == null ? 0 : Math.max(0, time - landing.due);+ const ms = Math.max(1, landing.fadeIn.ms - late);+ segments.set(+ 'opacity',+ fadeSegment(landing.owner, time, [+ {at: 0, value: valueAt('opacity', time)},+ {at: ms, value: landing.fadeIn.to},+ ]),+ );+ changed.push('opacity');+ end = time + ms;+ } else if (landing.restore != null) {+ segments.delete('opacity');+ resting.opacity =+ landing.restoreIsBorrowed === true ? IDENTITY.opacity : landing.restore;+ changed.push('opacity');+ }+ commit(changed, time);+ if (landing.restoreIsBorrowed === true) {+ // The stylesheet owns its opacity again.+ releaseOwnOpacity();+ }+ if (landing.fadeIn?.isBorrowed === true) {+ // The fade back in returns to the stylesheet's opacity: it owns it+ // again once the fade ends (releaseIdentity).+ borrowedOpacity = landing.fadeIn.to;+ }+ // The calls it carries are done: their travel has landed.+ for (const carried of landing.carried) {+ carriedOwners.delete(carried);+ if (!carried.settled) {+ settle(carried, true);+ }+ }+ const {owner} = landing;+ if (owner.settled) {+ return;+ }+ if (end <= time) {+ settle(owner, true);+ } else {+ owner.timer = setTimeout(+ () => {+ owner.timer = null;+ settle(owner, true);+ },+ Math.max(0, end - now()),+ );+ }+ };++ /**+ * A call that sets a value still waiting to land takes it over: the earlier+ * move never lands, and its call settles interrupted. Once nothing waiting+ * is left, a call that names its own opacity replaces an earlier fade back+ * in or restore too, so a caught dismissal fades straight back up instead+ * of dipping. Whatever still waits is carried by the new plan.+ */+ const takeOverLandings = (+ properties: ReadonlyArray<MotionProperty>,+ namesOpacity: boolean,+ ) => {+ for (const property of properties) {+ if (property !== 'opacity') {+ cancelLanding(property);+ }+ }+ if (!namesOpacity) {+ // A dip left with nothing to land (a move taken back) fades straight+ // back in from where it is, rather than finishing its dip.+ for (const landing of [...landings]) {+ if (landing.values.size === 0 && landing.fadeIn != null) {+ endLanding(landing);+ land(landing);+ }+ }+ return;+ }+ for (const landing of [...landings]) {+ // A waiting call that named its own opacity loses it to this call: it+ // never reaches that opacity, so it settles interrupted even though its+ // travel still lands.+ for (const owner of [landing.owner, ...landing.carried]) {+ if (namedOpacity.has(owner) && !owner.settled) {+ settle(owner, false);+ }+ }+ if (landing.values.size > 0) {+ continue;+ }+ endLanding(landing);+ if (+ landing.fadeIn?.isBorrowed === true ||+ landing.restoreIsBorrowed === true+ ) {+ // The call's own opacity owns it now, not the stylesheet's.+ borrowedOpacity = null;+ }+ for (const owner of [landing.owner, ...landing.carried]) {+ carriedOwners.delete(owner);+ if (!owner.settled) {+ settle(owner, false);+ }+ }+ }+ };++ /** Reduce Motion calls that named their own opacity. */+ const namedOpacity = new WeakSet<HandleState>();++ /**+ * Where opacity was heading before a call took the waiting landings over:+ * an entrance by role that catches an exit fades back to what the exit+ * would have restored.+ */+ let headingBeforeTakeOver: number | null = null;++ /** What the Reduce Motion planner reads of this animator. */+ const planView: ReducedMotionView = {+ valueAt,+ opacityHeading: () => headingBeforeTakeOver ?? opacityHeading(),+ ownOpacity: () => ownOpacity(),+ writesOwnOpacity: () => writesOwnOpacity(),+ get borrowedOpacity() {+ return borrowedOpacity;+ },+ get hasOpacityCurve() {+ return segments.has('opacity');+ },+ get restingOpacity() {+ return resting.opacity;+ },+ get hasPendingLanding() {+ return landings.size > 0;+ },+ };++ /**+ * Reduced Motion (see the file header): the planner's plan+ * (reducedMotionPlan.ts) as this call's segments.+ */+ const reducedMotion = (+ owner: HandleState,+ time: number,+ targets: Partial<Record<MotionProperty, number>>,+ properties: MotionProperty[],+ fade: boolean,+ role?: 'entrance' | 'exit',+ ): ReducedPlan => {+ const heading = opacityHeading();+ // An entrance or an exit by role drives the opacity as a named one does.+ takeOverLandings(properties, targets.opacity != null || role != null);+ if (targets.opacity != null) {+ namedOpacity.add(owner);+ }+ headingBeforeTakeOver = heading;+ let plan: ReturnType<typeof planReducedMotion>;+ try {+ plan = planReducedMotion(planView, time, targets, properties, fade, role);+ } finally {+ headingBeforeTakeOver = null;+ }+ const next: Partial<Record<MotionProperty, Segment | null>> = {};+ for (const property of plan.atOnce) {+ next[property] = null;+ }+ if (plan.opacityFade != null) {+ next.opacity = fadeSegment(owner, time, plan.opacityFade);+ }+ return {+ next,+ holds: plan.holds,+ landing: plan.landing,+ borrowed: plan.borrowed,+ };};const animator: Animator = {@@ -977,19 +2129,56 @@ export function createAnimator(return target;},+ reducedMotion(reducedOptions = {}) {+ if (!prefersReducedMotion()) {+ return 'off';+ }+ return isCoarsePointer() || reducedOptions.touchRelease === true+ ? 'crossfade'+ : 'instant';+ },+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);+ // Unmount, unless a node replaces this one in the same task (React's+ // replacement order: attach(null), then the new node): nothing is+ // left to animate, so at the end of the task every other handle+ // settles as interrupted, every atRest() wait settles and no+ // completion timer outlives the element, as in dispose()+ // (architecture:react-component-runtime INV5). A replacement keeps+ // them all: the motion goes on on the new node.+ if (!unmountQueued) {+ unmountQueued = true;+ queueMicrotask(() => {+ if (!unmountQueued) {+ return;+ }+ unmountQueued = false;+ // A Reduce Motion move still waiting lands in the model where it+ // was going, as in dispose(), so a later attach shows the element+ // there and visible; its calls settle as interrupted.+ landPending(false);+ const time = now();+ for (const property of PROPERTIES) {+ interrupt(property, time);+ }+ for (const wait of [...restWaits]) {+ wait.settle();+ }+ });}+ } else {+ // A node in place of the one just detached: no unmount.+ unmountQueued = false;}+ // After the landing's commit, which can promote the element again.+ demote();+ const isOpacityBorrowed =+ borrowedOpacity != null ||+ [...landings].some(landing => landing.restoreIsBorrowed === true);for (const animation of running.values()) {animation.cancel();}@@ -998,11 +2187,12 @@ export function createAnimator(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+ if (isOpacityBorrowed) {+ // A running borrowed dip (or an exit by role returning to the+ // stylesheet) 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');+ releaseOwnOpacity();}// Identities the outgoing node holds inline over a stylesheet that// differs, kept through a detach for the node that comes next.@@ -1048,17 +2238,21 @@ export function createAnimator(writeInline(channel, property => resting[property]);}}+ flushReleases();},get(property, time = now()) {+ syncPending();return valueAt(property === 'scale' ? 'scaleX' : property, time);},getVelocity(property, time = now()) {+ syncPending();return velocityAt(property === 'scale' ? 'scaleX' : property, time);},set(values) {+ syncPending();const time = now();const next = expand(values);for (const [property, value] of Object.entries(next) as [@@ -1069,121 +2263,34 @@ export function createAnimator(segments.delete(property);resting[property] = value;}+ // Direct manipulation: the layer makes each write a composite only.+ for (const property of Object.keys(next) as MotionProperty[]) {+ promote(CHANNEL_OF[property]);+ }commit(Object.keys(next) as MotionProperty[], time);},animate(to, transition, animateOptions = {}) {+ syncPending();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,+ let plan: ReducedPlan | null = null;++ if (prefersReducedMotion()) {+ plan = reducedMotion(+ owner,+ time,+ targets,+ properties,+ isCoarsePointer() || animateOptions.touchRelease === true,+ animateOptions.crossfadeAs,);- 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,- );- }- }+ Object.assign(next, plan.next);} else {for (const property of properties) {const velocity = velocities[property] ?? velocityAt(property, time);@@ -1198,50 +2305,54 @@ export function createAnimator(}}+ const group = beginGroup(+ time,+ Object.keys(next) as MotionProperty[],+ animateOptions.at,+ );+ const adopted =+ plan?.landing != null+ ? adoptLandings(plan.landing, Object.keys(next) as MotionProperty[])+ : null;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);- }+ interrupt(property, time);changed.push(property);if (segment == null) {+ // Read before the segment goes: valueAt falls back to resting.+ const value =+ plan?.holds[property] ??+ targets[property] ??+ valueAt(property, time);segments.delete(property);- resting[property] =- property === 'opacity'- ? opacityTo- : (targets[property] ?? valueAt(property, time));+ resting[property] = value;} 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);+ commitCall(group, owner, changed, time);+ if (plan?.borrowed != null) {+ // The dip's own commit cleared it; the borrow lasts the dip.+ borrowedOpacity = plan.borrowed;+ }+ const handle = makeHandle(owner, changed, finished, time, group);+ if (plan?.landing != null) {+ scheduleLanding(owner, handle.started, plan.landing, adopted);+ }+ return handle;},decay(curves, decayOptions = {}) {+ syncPending();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) {+ for (const property of DECAY_PROPERTIES) {const curve = curves[property];if (reduce && curve?.isTransition === true) {transitions[property] = curve.at(curve.duration);@@ -1249,16 +2360,21 @@ export function createAnimator(}const transitioned =Object.keys(transitions).length > 0- ? animator.animate(transitions, REDUCED_TRANSITION, {at: time})+ ? animator.animate(transitions, REDUCED_TRANSITION, {+ at: time,+ touchRelease: decayOptions.touchRelease,+ }): null;const {owner, finished} = newOwner();- const properties = PROPERTIES.filter(+ // Momentum moves the translate axes only (DR2's throw exception).+ const properties = DECAY_PROPERTIES.filter(property =>curves[property] != null && transitions[property] === undefined,);if (transitioned != null && properties.length === 0) {return transitioned;}+ const group = beginGroup(time, properties, decayOptions.at);for (const property of properties) {const curve = curves[property] as MotionCurve;interrupt(property, time);@@ -1277,8 +2393,8 @@ export function createAnimator(owner,});}- commit(properties, time);- const handle = makeHandle(owner, properties, finished, time);+ commitCall(group, owner, properties, time);+ const handle = makeHandle(owner, properties, finished, time, group);if (transitioned == null) {return handle;}@@ -1289,6 +2405,9 @@ export function createAnimator(return {...handle,properties: [...handle.properties, ...faded.properties],+ started: Promise.all([handle.started, faded.started]).then(+ ([coasting]) => coasting,+ ),finished: Promise.all([handle.finished, faded.finished]).then(([coasted, done]) => coasted && done,),@@ -1308,11 +2427,18 @@ export function createAnimator(},stop(properties) {+ syncPending();const time = now();const list = properties == null ? PROPERTIES : expandList(properties);const changed: MotionProperty[] = [];- const wasBorrowed = borrowedOpacity != null;+ // A borrowed dip, or an exit by role that returns to the stylesheet.+ const wasBorrowed =+ borrowedOpacity != null ||+ [...landings].some(landing => landing.restoreIsBorrowed === true);+ // Read before the landings go: a dip's fade back in, an exit's restore.+ const heading = opacityHeading();for (const property of list) {+ cancelLanding(property);const segment = segments.get(property);if (segment == null) {continue;@@ -1323,37 +2449,155 @@ export function createAnimator(? valueAt(property, time): wasBorrowed? IDENTITY.opacity- : segment.target;+ : heading;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);+ commit(changed, time);+ if (wasBorrowed && changed.includes('opacity')) {+ releaseOwnOpacity();+ }+ },++ rebase(deltas, rebaseOptions = {}) {+ syncPending();+ const time = rebaseOptions.at ?? now();+ const changed: MotionProperty[] = [];+ const owners = new Set<HandleState>();+ for (const [property, delta] of Object.entries(expand(deltas)) as [+ MotionProperty,+ number,+ ][]) {+ if (delta === 0) {+ continue;+ }+ changed.push(property);+ const segment = segmentAt(property, time);+ if (segment == null) {+ resting[property] = valueAt(property, time) + delta;segments.delete(property);- resting[property] = segment.target;- changed.push(property);+ continue;+ }+ owners.add(segment.owner);+ // A curve still waiting for the browser's start stays in its call:+ // it starts with that call's commit.+ const group =+ segment.group != null && !segment.group.resolved+ ? segment.group+ : undefined;+ const replace = (next: Segment) => {+ if (group != null) {+ const index = group.segments.indexOf(segment);+ if (index >= 0) {+ group.segments[index] = next;+ } else {+ group.segments.push(next);+ }+ }+ segments.set(property, next);+ };+ if (segment.spring != null) {+ const from = valueAt(property, time) + delta;+ const velocity = velocityAt(property, time);+ const curve = solveSpring(toSpring(segment.spring), {+ from,+ to: segment.target,+ velocity,+ });+ replace({+ start: group?.provisional ?? time,+ ...(group != null ? {group} : {}),+ duration: Math.min(+ MAX_DURATION_MS,+ curve.settleTime(SETTLE_THRESHOLD[property]) * 1000,+ ),+ target: segment.target,+ at: t => curve.value(t / 1000),+ speed: t => curve.velocity(t / 1000),+ jumps: [],+ owner: segment.owner,+ spring: segment.spring,+ });+ } else {+ replace({+ ...segment,+ target: segment.target + delta,+ at: t => segment.at(t) + delta,+ });}}commit(changed, time);- if (wasBorrowed && changed.includes('opacity')) {- target?.style.removeProperty('opacity');+ // The handles that own the rebased curves finish at their new ends.+ for (const owner of owners) {+ if (owner.settled || owner.timer == null) {+ continue;+ }+ clearTimeout(owner.timer);+ let end = time;+ for (const segment of segments.values()) {+ if (segment.owner === owner) {+ end = Math.max(end, segment.start + segment.duration);+ }+ }+ owner.timer = setTimeout(+ () => {+ owner.timer = null;+ settle(owner, true);+ },+ Math.max(0, end - now()),+ );}},+ async atRest(properties) {+ const list = properties == null ? PROPERTIES : expandList(properties);+ return new Promise<void>(resolve => {+ const wait: RestWait = {timer: null, settle: () => {}};+ const done = () => {+ if (wait.timer != null) {+ clearTimeout(wait.timer);+ }+ restWaits.delete(wait);+ resolve();+ };+ wait.settle = done;+ restWaits.add(wait);+ const check = () => {+ wait.timer = null;+ syncPending();+ const time = now();+ let end = time;+ for (const property of list) {+ const segment = segments.get(property);+ if (segment != null) {+ end = Math.max(end, segment.start + segment.duration);+ }+ }+ if (landings.size > 0) {+ // A Reduced Motion landing is still to come.+ wait.timer = setTimeout(check, 16);+ } else if (end <= time) {+ done();+ } else {+ // A retarget or a later start moves the end: look again then.+ wait.timer = setTimeout(check, end - time);+ }+ };+ check();+ });+ },+dispose() {+ // A Reduce Motion move still waiting to land is written at its end+ // state, so the element is left visible where it was going; its call+ // and the calls it carries settle as interrupted.+ landPending(false);+ // Nothing moves any more: every atRest() wait settles.+ for (const wait of [...restWaits]) {+ wait.settle();+ }const time = now();for (const property of PROPERTIES) {interrupt(property, time);@@ -1367,6 +2611,7 @@ export function createAnimator(}retireTimers.clear();handBackBorrow();+ demote();target = null;},};diff --git a/packages/core/src/motion/coast.test.ts b/packages/core/src/motion/coast.test.tsindex 9c314d0251..58b17186ce 100644--- a/packages/core/src/motion/coast.test.ts+++ b/packages/core/src/motion/coast.test.ts@@ -73,12 +73,12 @@ describe('coast', () => {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);+ it('reads the presentation value at the release time, on the translate axes only', () => {+ const {animator, reads} = at({x: 0, y: 0});+ const curves = coast(animator, {x: 500, y: 200}, {at: 1234});+ expect(Object.keys(curves).sort()).toEqual(['x', 'y']);+ expect(curves.x!.velocity(0)).toBeCloseTo(500, 9);+ expect(curves.y!.velocity(0)).toBeCloseTo(200, 9);expect(reads).toEqual([1234, 1234]);});diff --git a/packages/core/src/motion/coast.ts b/packages/core/src/motion/coast.tsindex 8f5d85101e..7e0eff5fd7 100644--- a/packages/core/src/motion/coast.ts+++ b/packages/core/src/motion/coast.ts@@ -19,20 +19,15 @@* 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);+ * plays it as `animate` does, a cross-fade on a coarse pointer or after a+ * touch release (`touchRelease`) 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 {SETTLE_THRESHOLD, type Animator, type MotionCurve} from './animator';import {solveDecay} from './decay';import {solveSpring, toSpring, type SpringDescription} from './spring';import {scroll} from './uikit/scroll';@@ -41,7 +36,7 @@ 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}>>;+ bounds?: Partial<Record<'x' | 'y', {min: number; max: number}>>;/** The edge spring; `scroll.bounce` by default. */bounce?: SpringDescription;/**@@ -66,8 +61,9 @@ function settling(}/**- * The momentum curves of a release with `velocity` (units per second for- * each property; `scale` sets both scales), for `animator.decay`.+ * The momentum curves of a release with `velocity` (px per second on each+ * translate axis), for `animator.decay`, which moves only `x` and `y`:+ * momentum continues a finger's throw (design:reduced-motion DR2).** @example* ```@@ -78,29 +74,20 @@ function settling(*/export function coast(animator: Animator,- velocity: MotionValues,+ velocity: {readonly x?: number; readonly y?: number},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;+): Partial<Record<'x' | 'y', MotionCurve>> {+ const velocities: Partial<Record<'x' | 'y', number>> = {};+ for (const key of ['x', 'y'] as const) {+ const value = velocity[key];+ if (value != null && Number.isFinite(value)) {+ velocities[key] = 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 curves: Partial<Record<'x' | 'y', MotionCurve>> = {};+ for (const [key, v0] of Object.entries(velocities) as ['x' | 'y', number][]) {const from = animator.get(key, options.at);const bounds = options.bounds?.[key];const threshold = SETTLE_THRESHOLD[key];diff --git a/packages/core/src/motion/reducedMotion.stylex.ts b/packages/core/src/motion/reducedMotion.stylex.tsnew file mode 100644index 0000000000..337af66f4a--- /dev/null+++ b/packages/core/src/motion/reducedMotion.stylex.ts@@ -0,0 +1,41 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reducedMotion.stylex.ts+ * @input StyleX constant definitions+ * @output reducedMotionFadeConsts (the Reduced Motion cross-fade's duration+ * and easing) for StyleX transitions, and reducedMotionKeys (its two media+ * keys, which a transition spells literally)+ * @position The CSS side of the Reduced Motion policy (reducedMotion.ts):+ * values a transition takes under its two Reduce Motion media keys+ *+ * Constants, not theme variables: no theme lengthens the fade+ * (design:reduced-motion DR4). They equal `timing.reducedMotionCrossFadeMs`+ * and `timing.curves.move`, which reducedMotion.test.ts checks.+ *+ * SYNC: When modified, update /packages/core/src/motion/uikit/timing.ts and+ * /packages/core/src/motion/reducedMotion.test.ts.+ */++import * as stylex from '@stylexjs/stylex';++export const reducedMotionFadeConsts = stylex.defineConsts({+ /** The cross-fade under Reduce Motion on a coarse pointer. */+ duration: '200ms',+ /** Core Animation's easeInOut. */+ easing: 'cubic-bezier(0.42, 0, 0.58, 1)',+});++/**+ * The two Reduce Motion media keys, spelled once: under Reduce Motion a coarse+ * primary pointer fades (DR2) and any other completes at once (DR3). A+ * component spells the key literally rather than as a computed key: StyleX+ * puts a constant key in a later priority layer than the literal media key,+ * where it would outrank the element's state styles. reducedMotion.test.ts+ * holds every literal in core to these, exactly.+ */+export const reducedMotionKeys = stylex.defineConsts({+ fade: '@media (prefers-reduced-motion: reduce) and (pointer: coarse)',+ instant:+ '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))',+});diff --git a/packages/core/src/motion/reducedMotion.test.ts b/packages/core/src/motion/reducedMotion.test.tsnew file mode 100644index 0000000000..465b8b9f41--- /dev/null+++ b/packages/core/src/motion/reducedMotion.test.ts@@ -0,0 +1,129 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reducedMotion.test.ts+ * @input reducedMotion.ts, reducedMotion.stylex.ts, the timing table, and+ * every StyleX source file in core+ * @output Proof that the Reduced Motion policy for code beside the animator+ * fades 200 ms at most on a coarse pointer or a touch release and completes+ * at once elsewhere, that its CSS constants match the table, and that every+ * StyleX key splitting Reduce Motion by pointer spells the two queries+ * @position Testing for /packages/core/src/motion/reducedMotion.ts+ */++import {readdirSync, readFileSync} from 'node:fs';+import {join, resolve} from 'node:path';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {+ REDUCED_MOTION_FADE_QUERY,+ REDUCED_MOTION_INSTANT_QUERY,+ reducedMotionFade,+} from './reducedMotion';+import {+ reducedMotionFadeConsts,+ reducedMotionKeys,+} from './reducedMotion.stylex';+import {timing} from './uikit/timing';++/** The person's settings, through `matchMedia`: no option overrides them. */+function settings(reduced: boolean, coarse: boolean) {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query.includes('prefers-reduced-motion')+ ? reduced+ : query.includes('pointer: coarse')+ ? coarse+ : false,+ media: query,+ }));+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('reducedMotionFade', () => {+ it('is null when motion is not reduced', () => {+ settings(false, true);+ expect(reducedMotionFade(null)).toBeNull();+ });++ it('fades 200 ms at most on easeInOut on a coarse pointer', () => {+ settings(true, true);+ const fade = reducedMotionFade(null);+ expect(fade).toEqual({+ duration: timing.reducedMotionCrossFadeMs,+ easing: 'cubic-bezier(0.42, 0, 0.58, 1)',+ });+ expect(fade?.duration).toBeGreaterThan(0);+ expect(fade?.duration).toBeLessThanOrEqual(200);+ });++ it('completes at once on any other pointer, unless a touch release started it', () => {+ settings(true, false);+ expect(reducedMotionFade(null)).toEqual({duration: 0, easing: 'linear'});+ expect(reducedMotionFade(null, {touchRelease: true})?.duration).toBe(+ timing.reducedMotionCrossFadeMs,+ );+ });+});++describe('the CSS side of the policy', () => {+ it('holds the same fade as the table', () => {+ expect(reducedMotionFadeConsts.duration).toBe(+ `${timing.reducedMotionCrossFadeMs}ms`,+ );+ expect(reducedMotionFadeConsts.easing).toBe(+ `cubic-bezier(${timing.curves.move.join(', ')})`,+ );+ });++ it('spells the two media keys from the queries', () => {+ expect(reducedMotionKeys.fade).toBe(`@media ${REDUCED_MOTION_FADE_QUERY}`);+ expect(reducedMotionKeys.instant).toBe(+ `@media ${REDUCED_MOTION_INSTANT_QUERY}`,+ );+ });++ it('every key that splits Reduce Motion by pointer is one of the two constants, spelled exactly', () => {+ const allowed = new Set<string>([+ reducedMotionKeys.fade,+ reducedMotionKeys.instant,+ ]);+ const root = resolve(__dirname, '..');+ const offenders: string[] = [];+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, {withFileTypes: true})) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name !== 'node_modules' && entry.name !== '__tests__') {+ walk(path);+ }+ } else if (+ /\.tsx?$/.test(entry.name) &&+ !/\.(test|spec|stories)\.tsx?$/.test(entry.name)+ ) {+ for (const match of readFileSync(path, 'utf8').matchAll(+ /'(@media[^']*prefers-reduced-motion: reduce[^']*pointer[^']*)'/g,+ )) {+ if (!allowed.has(match[1])) {+ offenders.push(`${path.slice(root.length)}: ${match[1]}`);+ }+ }+ // A constant as a computed key lands in a later priority layer.+ if (+ !/[/\\]motion[/\\]reducedMotion\.ts$/.test(path) &&+ /\[reducedMotionKeys\.(fade|instant)\]/.test(+ readFileSync(path, 'utf8'),+ )+ ) {+ offenders.push(+ `${path.slice(root.length)}: a computed reducedMotionKeys key`,+ );+ }+ }+ }+ };+ walk(root);+ expect(offenders).toEqual([]);+ });+});diff --git a/packages/core/src/motion/reducedMotion.ts b/packages/core/src/motion/reducedMotion.tsnew file mode 100644index 0000000000..f59d3c423c--- /dev/null+++ b/packages/core/src/motion/reducedMotion.ts@@ -0,0 +1,94 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reducedMotion.ts+ * @input The Reduced Motion preference, the primary pointer, the motion tables+ * @output reducedMotionFade (the fade the animator would play, for motion it+ * does not drive) and the two media queries a StyleX transition spells+ * @position The one Reduced Motion policy (design:reduced-motion) for code+ * beside the animator: a raw Web Animations fade, a CSS transition+ *+ * Under Reduce Motion nothing moves, scales or springs. On a coarse primary+ * pointer, or for a change started by a touch drag's release on any pointer+ * (DR2), a change becomes an opacity-only cross-fade of+ * `timing.reducedMotionCrossFadeMs` (200 ms) on `timing.curves.move`; on+ * any other primary pointer it completes at once (DR3). No theme value or+ * call site lengthens the fade (DR4). The animator follows the same policy on+ * its own (animator.ts).+ *+ * In StyleX, a transition spells the two keys literally and takes its values+ * from reducedMotion.stylex.ts. A constant used as a computed key compiles to+ * a later priority layer than the literal media key, which would outrank the+ * element's state styles, so the keys stay literal:+ *+ * ```+ * transitionProperty: {+ * default: 'opacity, translate',+ * '@media (prefers-reduced-motion: reduce) and (pointer: coarse)': 'opacity',+ * '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))': 'none',+ * },+ * transitionDuration: {+ * default: '300ms',+ * '@media (prefers-reduced-motion: reduce) and (pointer: coarse)':+ * reducedMotionFadeConsts.duration,+ * '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))': '0s',+ * },+ * ```+ *+ * reducedMotion.test.ts requires every such key in core to equal one of+ * `reducedMotionKeys`, exactly.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/motion/reducedMotion.stylex.ts+ * - /packages/core/src/motion/reducedMotion.test.ts+ * - /packages/core/src/motion/animator.ts (its Reduced Motion path)+ */++import {defaultIsCoarsePointer, defaultPrefersReducedMotion} from './animator';+import {reducedMotionCrossFade} from './uikit/timing';++/** Reduce Motion on a coarse primary pointer: an opacity-only cross-fade. */+export const REDUCED_MOTION_FADE_QUERY =+ '(prefers-reduced-motion: reduce) and (pointer: coarse)';++/** Reduce Motion on any other primary pointer: the change completes at once. */+export const REDUCED_MOTION_INSTANT_QUERY =+ '(prefers-reduced-motion: reduce) and (not (pointer: coarse))';++/**+ * The fade to play under Reduce Motion. `duration` 0 means the change+ * completes at once; `easing` is a CSS timing function.+ */+export interface ReducedMotionFade {+ readonly duration: number;+ readonly easing: string;+}++/**+ * The Reduced Motion fade for a change to `element` now, for motion the+ * animator does not drive (two titles cross-fading with Web Animations):+ * null when motion is not reduced (play the normal motion), else an+ * opacity-only fade of 200 ms on a coarse pointer or for a touch release, or+ * duration 0 (at once) on any other pointer, on Core Animation's easeInOut;+ * the length is fixed.+ */+export function reducedMotionFade(+ element?: Element | null,+ options: {+ /** The change starts from the release of a touch drag (DR2). */+ touchRelease?: boolean;+ } = {},+): ReducedMotionFade | null {+ if (!defaultPrefersReducedMotion()) {+ return null;+ }+ const fades = options.touchRelease === true || defaultIsCoarsePointer();+ if (!fades) {+ return {duration: 0, easing: 'linear'};+ }+ const curve = reducedMotionCrossFade.curve;+ return {+ duration: reducedMotionCrossFade.durationMs,+ easing: `cubic-bezier(${curve.join(', ')})`,+ };+}diff --git a/packages/core/src/motion/reducedMotionPlan.test.ts b/packages/core/src/motion/reducedMotionPlan.test.tsnew file mode 100644index 0000000000..ddd81b8997--- /dev/null+++ b/packages/core/src/motion/reducedMotionPlan.test.ts@@ -0,0 +1,182 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reducedMotionPlan.test.ts+ * @input planReducedMotion and a stand-in view of the animator+ * @output Tests of the Reduce Motion planner on its own (the animator's+ * behavior under the plan is in animator.test.ts)+ * @position Testing for /packages/core/src/motion/reducedMotionPlan.ts+ */++import {describe, expect, it} from 'vitest';+import type {MotionProperty} from './animator';+import {planReducedMotion, type ReducedMotionView} from './reducedMotionPlan';+import {reducedMotionCrossFade} from './uikit/timing';++const MS = reducedMotionCrossFade.durationMs;++function view(overrides: Partial<ReducedMotionView> = {}): ReducedMotionView {+ const values: Partial<Record<MotionProperty, number>> = {opacity: 1};+ return {+ valueAt: property => values[property] ?? 0,+ opacityHeading: () => 1,+ ownOpacity: () => 1,+ writesOwnOpacity: () => false,+ borrowedOpacity: null,+ hasOpacityCurve: false,+ restingOpacity: 1,+ hasPendingLanding: false,+ ...overrides,+ };+}++describe('planReducedMotion', () => {+ it('without a fade (a fine primary pointer), writes everything at once (DR3)', () => {+ const plan = planReducedMotion(+ view(),+ 0,+ {x: 100, opacity: 0},+ ['x', 'opacity'],+ false,+ );+ expect(plan.atOnce).toEqual(['x', 'opacity']);+ expect(plan.opacityFade).toBeNull();+ expect(plan.landing).toBeNull();+ });++ it('an entrance lands at once and fades in over the cross-fade (DR2)', () => {+ const plan = planReducedMotion(+ view({valueAt: p => (p === 'opacity' ? 0 : 0)}),+ 0,+ {x: 100, opacity: 1},+ ['x', 'opacity'],+ true,+ );+ expect(plan.atOnce).toEqual(['x']);+ expect(plan.opacityFade).toEqual([+ {at: 0, value: 0},+ {at: MS, value: 1},+ ]);+ expect(plan.landing).toBeNull();+ });++ it('an exit fades out in place, then lands its travel', () => {+ const plan = planReducedMotion(+ view(),+ 0,+ {x: 100, opacity: 0},+ ['x', 'opacity'],+ true,+ );+ expect(plan.opacityFade).toEqual([+ {at: 0, value: 1},+ {at: MS, value: 0},+ ]);+ expect(plan.landing?.at).toBe(MS);+ expect([...(plan.landing?.values ?? [])]).toEqual([['x', 100]]);+ expect(plan.holds).toEqual({x: 0});+ });++ it('a move whose opacity rises from a visible value dips rather than landing in view', () => {+ const plan = planReducedMotion(+ view({valueAt: p => (p === 'opacity' ? 0.5 : 0)}),+ 0,+ {x: 100, opacity: 1},+ ['x', 'opacity'],+ true,+ );+ expect(plan.opacityFade).toEqual([+ {at: 0, value: 0.5},+ {at: MS / 2, value: 0},+ ]);+ expect(plan.landing?.at).toBe(MS / 2);+ expect(plan.landing?.fadeIn).toEqual({+ to: 1,+ ms: MS / 2,+ isBorrowed: false,+ });+ });++ it('a move whose opacity falls to a visible value dips rather than landing in view', () => {+ const plan = planReducedMotion(+ view(),+ 0,+ {x: 100, opacity: 0.5},+ ['x', 'opacity'],+ true,+ );+ expect(plan.landing?.at).toBe(MS / 2);+ expect(plan.landing?.fadeIn).toEqual({+ to: 0.5,+ ms: MS / 2,+ isBorrowed: false,+ });+ });++ it('a move alone dips on the stylesheet opacity it borrows, and lands at the bottom', () => {+ const plan = planReducedMotion(+ view({ownOpacity: () => 0.6}),+ 0,+ {x: 100},+ ['x'],+ true,+ );+ expect(plan.borrowed).toBe(0.6);+ expect(plan.opacityFade).toEqual([+ {at: 0, value: 0.6},+ {at: MS / 2, value: 0},+ ]);+ expect(plan.landing?.at).toBe(MS / 2);+ expect(plan.landing?.fadeIn).toEqual({+ to: 0.6,+ ms: MS / 2,+ isBorrowed: true,+ });+ });++ it('a stylesheet that hides the element lends nothing: the move lands at once, with no dip', () => {+ const plan = planReducedMotion(+ view({ownOpacity: () => 0}),+ 0,+ {x: 100},+ ['x'],+ true,+ );+ expect(plan.atOnce).toEqual(['x']);+ expect(plan.opacityFade).toBeNull();+ expect(plan.landing).toBeNull();+ });++ it('an opacity the animator writes is owned: a dip returns to it, borrowing nothing', () => {+ const plan = planReducedMotion(+ view({ownOpacity: () => 0, writesOwnOpacity: () => true}),+ 0,+ {x: 100},+ ['x'],+ true,+ );+ expect(plan.borrowed).toBeNull();+ expect(plan.landing?.fadeIn).toEqual({+ to: 1,+ ms: MS / 2,+ isBorrowed: false,+ });+ });++ it('an exit by role on a surface no call owns opacity on restores the stylesheet opacity', () => {+ const plan = planReducedMotion(+ view({ownOpacity: () => 0.6}),+ 0,+ {y: 40},+ ['y'],+ true,+ 'exit',+ );+ expect(plan.opacityFade).toEqual([+ {at: 0, value: 0.6},+ {at: MS, value: 0},+ ]);+ expect(plan.landing?.restore).toBe(0.6);+ expect(plan.landing?.restoreIsBorrowed).toBe(true);+ });+});diff --git a/packages/core/src/motion/reducedMotionPlan.ts b/packages/core/src/motion/reducedMotionPlan.tsnew file mode 100644index 0000000000..fd070b62e9--- /dev/null+++ b/packages/core/src/motion/reducedMotionPlan.ts@@ -0,0 +1,263 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reducedMotionPlan.ts+ * @input A call's targets and a read-only view of the animator's opacity+ * state+ * @output planReducedMotion, TRAVEL_PROPERTIES and the plan's types+ * @position The animator's Reduce Motion planner (packages/core/src/motion):+ * what one call becomes under Reduce Motion. animator.ts applies the plan;+ * the policy itself is described in its header (design:reduced-motion+ * DR1–DR4).+ *+ * With `fade` (a coarse primary pointer, or a touch drag's release), a call+ * becomes an opacity-only cross-fade whose travel lands while the element is+ * transparent: an entrance from 0 lands at once and fades in, an exit to 0+ * fades out in place and then lands, and any other call that moves dips+ * (fades out, lands, fades back in). Without `fade`, everything lands at once. When no call owns+ * the opacity, a dip or a fade by role starts from and returns to the+ * element's own (stylesheet) opacity, which the plan reports as `borrowed`.+ * The planner is pure: it reads the animator only through+ * `ReducedMotionView` and returns what to write.+ *+ * SYNC: When modified, update animator.ts (its header's Reduce Motion+ * section, and `reducedMotion`, which applies the plan) and animator.test.ts.+ */++import type {MotionProperty} from './animator';+import {reducedMotionCrossFade} from './uikit/timing';++/** The properties that move an element rather than fade it. */+export const TRAVEL_PROPERTIES: ReadonlyArray<MotionProperty> = [+ 'x',+ 'y',+ 'rotate',+ 'scaleX',+ 'scaleY',+];++/** A point of the opacity fade: ms after the call's start, and the value. */+export interface FadePoint {+ readonly at: number;+ readonly value: number;+}++/** The travel a plan writes later, while the element is transparent. */+export interface PlannedLanding {+ /** ms after the call's start. */+ readonly at: number;+ readonly values: Map<MotionProperty, number>;+ /**+ * The fade back in that follows the landing (a dip); `isBorrowed` when it+ * returns to the stylesheet's opacity, which owns it again once it ends.+ */+ fadeIn: {+ readonly to: number;+ readonly ms: number;+ readonly isBorrowed?: boolean;+ } | null;+ /** The opacity written with the landing (an exit by role). */+ restore: number | null;+ /**+ * The restore returns to the stylesheet's opacity (an exit by role on a+ * surface no call owns opacity on): the stylesheet owns it again.+ */+ restoreIsBorrowed?: boolean;+}++/** What the planner reads of the animator, at the call's time. */+export interface ReducedMotionView {+ valueAt(property: MotionProperty, time: number): number;+ /** Where the opacity is heading (a running fade's end, else its value). */+ opacityHeading(): number;+ /** The element's own (stylesheet) opacity. */+ ownOpacity(): number;+ /** Whether the animator writes the element's opacity itself. */+ writesOwnOpacity(): boolean;+ /** The stylesheet opacity a running dip borrowed, if any. */+ readonly borrowedOpacity: number | null;+ readonly hasOpacityCurve: boolean;+ readonly restingOpacity: number;+ /** Whether a move of an earlier call still waits to land. */+ readonly hasPendingLanding: boolean;+}++/** What Reduce Motion makes of a call. */+export interface ReducedMotionPlan {+ /** Properties written at once, with no curve. */+ readonly atOnce: MotionProperty[];+ /** The opacity fade, when the call fades. */+ readonly opacityFade: FadePoint[] | null;+ /** Values that stay where they are until the landing writes them. */+ readonly holds: Partial<Record<MotionProperty, number>>;+ readonly landing: PlannedLanding | null;+ /** The stylesheet opacity a dip borrowed (no call owns opacity). */+ readonly borrowed?: number | null;+}++/** The opacity no call has changed. */+const IDENTITY_OPACITY = 1;++/**+ * Plans one call under Reduce Motion: with `fade`, an opacity-only+ * cross-fade whose travel lands while the element is transparent; without,+ * everything at once. `role` gives a call that names no opacity its+ * direction (`crossfadeAs`).+ */+export function planReducedMotion(+ view: ReducedMotionView,+ time: number,+ targets: Partial<Record<MotionProperty, number>>,+ properties: ReadonlyArray<MotionProperty>,+ fade: boolean,+ role?: 'entrance' | 'exit',+): ReducedMotionPlan {+ const holds: Partial<Record<MotionProperty, number>> = {};+ if (!fade) {+ return {atOnce: [...properties], opacityFade: null, holds, landing: null};+ }+ const atOnce = properties.filter(property =>+ TRAVEL_PROPERTIES.includes(property),+ );+ const opacityNow = view.valueAt('opacity', time);+ // A fade the call does not name keeps going where it was heading.+ const opacityTo = targets.opacity ?? view.opacityHeading();+ const travel = properties.filter(+ property =>+ TRAVEL_PROPERTIES.includes(property) &&+ Math.abs((targets[property] as number) - view.valueAt(property, time)) >+ 1e-9,+ );+ // Only the call's own opacity (or its role) makes it an entrance or an+ // exit: a fade it does not name, such as a dip still running, does not.+ const named = targets.opacity != null;+ let entering = named && opacityTo > opacityNow + 1e-6;+ let leaving = named && opacityTo < opacityNow - 1e-6;+ let fadeFrom = opacityNow;+ let fadeTo = opacityTo;+ let restore: number | null = null;+ // A fade by role on a surface no call owns opacity on starts from, or+ // returns to, the element's own (stylesheet) opacity, as a dip does.+ const roleBorrow =+ role != null &&+ !named &&+ view.borrowedOpacity == null &&+ !view.hasOpacityCurve &&+ view.restingOpacity === IDENTITY_OPACITY &&+ !view.writesOwnOpacity()+ ? view.ownOpacity()+ : null;+ if (!entering && !leaving && role === 'entrance') {+ entering = true;+ // From transparent, or from where a running fade (an exit caught+ // midway) has it.+ fadeFrom = view.hasOpacityCurve ? opacityNow : 0;+ fadeTo = roleBorrow ?? opacityTo;+ } else if (!entering && !leaving && role === 'exit') {+ leaving = true;+ fadeFrom = roleBorrow ?? opacityNow;+ fadeTo = 0;+ restore = roleBorrow ?? opacityTo;+ }+ // A move still waiting to land (an earlier dip's) lands at this call's+ // invisible moment, never while the element shows.+ const pending = view.hasPendingLanding;+ // Not a theme role: no theme lengthens it (design:reduced-motion DR4).+ const ms = reducedMotionCrossFade.durationMs;+ const landsLater = (+ at: number,+ fadeIn: PlannedLanding['fadeIn'],+ ): PlannedLanding => {+ const values = new Map<MotionProperty, number>();+ for (const property of travel) {+ holds[property] = view.valueAt(property, time);+ values.set(property, targets[property] as number);+ }+ return {+ at,+ values,+ fadeIn,+ restore,+ ...(roleBorrow != null && restore != null+ ? {restoreIsBorrowed: true}+ : {}),+ };+ };+ // Travel lands only while the element is transparent (DR1, DR2): an+ // entrance that starts visible, or an exit that ends visible, dips instead+ // when it has travel or a waiting landing to carry.+ const carries = travel.length > 0 || pending;+ if (entering && !pending && (!carries || fadeFrom <= 1e-6)) {+ // Lands at once (the travel is written at once) and fades in.+ return {+ atOnce,+ opacityFade: [+ {at: 0, value: fadeFrom},+ {at: ms, value: fadeTo},+ ],+ holds,+ landing: null,+ borrowed: roleBorrow,+ };+ }+ if (leaving && (!carries || fadeTo <= 1e-6)) {+ // Fades out in place, then lands.+ const opacityFade = [+ {at: 0, value: fadeFrom},+ {at: ms, value: fadeTo},+ ];+ return {+ atOnce,+ opacityFade,+ holds,+ landing:+ travel.length > 0 || restore != null || pending+ ? landsLater(ms, null)+ : null,+ };+ }+ if (carries) {+ // A dip: fades out, lands while transparent, fades back in. When no+ // call owns opacity it starts from and returns to the element's own+ // (stylesheet) opacity, not the model's 1.+ // A dip still running on borrowed opacity (its fade out or back in)+ // lends the same borrow to the next one: overlapping dips never pin+ // the stylesheet's value inline.+ const priorBorrow = view.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 =+ named ||+ (priorBorrow == null &&+ (view.hasOpacityCurve ||+ view.restingOpacity !== IDENTITY_OPACITY ||+ view.writesOwnOpacity()));+ const borrowed = ownsOpacity ? null : (priorBorrow ?? view.ownOpacity());+ if (borrowed != null && borrowed <= 1e-6) {+ // A stylesheet that hides the element lends nothing: invisible, the+ // move lands at once, with no dip.+ return {atOnce, opacityFade: null, holds, landing: null};+ }+ // It opens at the opacity on screen: an earlier dip's, when one is+ // still running, else the borrowed stylesheet value.+ const opacityFade = [+ {+ at: 0,+ value: view.hasOpacityCurve ? opacityNow : (borrowed ?? opacityNow),+ },+ {at: ms / 2, value: 0},+ ];+ const landing = landsLater(ms / 2, {+ to: borrowed ?? opacityTo,+ ms: ms / 2,+ isBorrowed: borrowed != null,+ });+ return {atOnce, opacityFade, holds, landing, borrowed};+ }+ return {+ atOnce: 'opacity' in targets ? [...atOnce, 'opacity'] : atOnce,+ opacityFade: null,+ holds,+ landing: null,+ };+}diff --git a/packages/core/src/motion/uikit/timing.ts b/packages/core/src/motion/uikit/timing.tsindex 7402302c9a..b4edbf7fad 100644--- a/packages/core/src/motion/uikit/timing.ts+++ b/packages/core/src/motion/uikit/timing.ts@@ -91,13 +91,12 @@ export const press = {*/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).+ * The Reduced Motion cross-fade, in ms, on `curves.move`: under+ * Reduce Motion an entrance, exit, presentation switch or state change+ * becomes an opacity-only cross-fade of this length on a coarse pointer+ * (design:reduced-motion DR2 caps it at 200 ms, by owner decision DEC-1+ * of 2026-10-24, departing from UIKit's own navigation cross-fade,+ * measured below at 0.5 s). Not a theme role: no theme lengthens it (DR4).* @source apple-docs https://developer.apple.com/documentation/uikit/uiaccessibility/preferscrossfadetransitions* (the setting)* @source measured: UIKit lab (injected host app), iOS 26.2 simulator,@@ -105,7 +104,7 @@ export const reducedMotionCrossFade = {* Cross-Fade Transitions on (opacity CABasicAnimation 0.5 s,* (0.42, 0, 0.58, 1)), Oct 23 2026*/- durationMs: 500,+ durationMs: 200,/*** `easeInEaseOut`; UIKit's default curve (`UIView.AnimationCurve* .easeInOut`, "the default curve for most animations").