An open source design system that's fully customizable and agent ready
TypeScript
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
* @file animator.test.ts
* @input vitest (jsdom), the animator, a recording stand-in for
* Element.animate (jsdom runs no animations)
* @output Checks what the animator hands the browser: keyframes that follow
* the analytic curves, the clock, the inline end state; and what it reads
* back: presentation values and velocities, retarget continuity, stop,
* completion, Reduced Motion substitutions, momentum curves (a coast with
* edges), late attach
* @position Testing; the compositor itself is proven in
* __tests__/animator.interaction.browser.spec.ts
*/
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 {
animatorFor,
createMotionEngine,
END_HOLD_MS,
PROMOTION_LINGER_MS,
type Animator,
type AnimatorOptions,
} from './animator';
import {cubicBezier} from './bezier';
import {coast} from './coast';
import {
presentedElements,
presentedOffsetOf,
resolvePresented,
} from './presentation';
import {solveDecay} from './decay';
import {solveSpring, solveSpringTowardRamp, toSpring} from './spring';
import {scroll} from './uikit/scroll';
import {springs} from './uikit/springs';
import {timing} from './uikit/timing';
interface Recorded {
element: Element;
keyframes: Keyframe[];
options: KeyframeAnimationOptions;
startTime: number | null;
/** 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;
/** 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';
/** Its timing, as the browser reports it: the duration it was given. */
readonly effect: {getTiming(): {duration: number}};
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: ((frame?: number) => void)[] = [];
/** The last frame's timestamp: one of its own per frame, never reused. */
let frameStamp = 0;
const requestFrame = (callback: (frame?: number) => 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
* properties, so the page is modeled here).
*/
let stylesheet: Record<string, string> = {};
/** The stylesheet's values for a pseudo-element of the element. */
let pseudoStylesheet: Record<string, string> = {};
beforeEach(() => {
clock = 1000;
recorded = [];
frameQueue = [];
stylesheet = {};
pseudoStylesheet = {};
vi.spyOn(window, 'getComputedStyle').mockImplementation(
(element, pseudo) =>
({
getPropertyValue: (property: string) => {
if (pseudo != null) {
return pseudoStylesheet[property] ?? '';
}
// A live animation wins over the inline value, holding its last
// keyframe (the end-state tail) until it is cancelled.
const held = recorded
.filter(
animation =>
animation.element === element &&
!animation.cancelled &&
animation.keyframes.some(frame => property in frame),
)
.at(-1);
const last = held?.keyframes
.filter(frame => property in frame)
.at(-1) as Record<string, unknown> | undefined;
if (last != null) {
return String(last[property]);
}
return (
(element as HTMLElement).style.getPropertyValue(property) ||
(stylesheet[property] ?? '')
);
},
}) as unknown as CSSStyleDeclaration,
);
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,
get startTime() {
return start;
},
set startTime(value) {
start = value;
resolveReady(animation);
},
createdAt: clock,
cancelled: false,
paused: false,
finished: false,
effect: {
getTiming: () => ({
duration: Number((options as KeyframeAnimationOptions)?.duration),
}),
},
get playState() {
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);
return animation as unknown as Animation;
};
});
afterEach(() => {
vi.unstubAllGlobals();
Reflect.deleteProperty(HTMLElement.prototype, 'animate');
vi.useRealTimers();
vi.restoreAllMocks();
});
/**
* 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 = createMotionEngine(element, {
now: () => clock,
requestFrame,
...options,
});
return {element, animator};
}
/**
* The browser commits a frame at `at`: pending animations start there. With
* `startUnread`, the frame's callbacks run before the page can read those
* starts, as in Chromium, whose compositor starts a composited animation at
* the frame that commits it and tells the page that start a frame or more
* later.
*/
async function commitFrame(
at: number,
{startUnread = false}: {startUnread?: boolean} = {},
) {
if (!startUnread) {
for (const animation of recorded) {
if (animation.startTime == null && !animation.cancelled) {
animation.commit(at);
}
}
}
const frames = frameQueue;
frameQueue = [];
// A browser gives every callback of one frame the same timestamp, and no
// other frame that timestamp.
frameStamp += 1;
for (const callback of frames) {
callback(frameStamp);
}
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);
}
function live(channel: string): Recorded[] {
return recorded.filter(
a => !a.cancelled && channel in (a.keyframes[0] ?? {}),
);
}
function parse(value: string | number | null | undefined): number[] {
return String(value)
.split(/\s+/)
.map(part => Number.parseFloat(part));
}
/** The x of the element's inline translate; `none` is no translate. */
function inlineX(element: HTMLElement): number {
const value = element.style.translate;
return value === 'none' ? 0 : parse(value)[0];
}
/** What the browser would show: the keyframes interpolated linearly at `time`. */
function sampleAt(
animation: Recorded,
channel: string,
time: number,
): number[] {
const duration = Number(animation.options.duration);
const offset = Math.min(
1,
Math.max(
0,
(time - (animation.startTime ?? animation.createdAt)) / duration,
),
);
const frames = animation.keyframes;
for (let i = 0; i + 1 < frames.length; i++) {
const a = frames[i];
const b = frames[i + 1];
const oa = Number(a.offset);
const ob = Number(b.offset);
if (
offset >= oa &&
offset <= ob &&
!(
offset === ob &&
i + 2 < frames.length &&
Number(frames[i + 2].offset) === ob
)
) {
const va = parse(a[channel]);
const vb = parse(b[channel]);
const f = ob === oa ? 1 : (offset - oa) / (ob - oa);
return va.map((v, k) => v + (vb[k] - v) * f);
}
}
return parse(frames[frames.length - 1][channel]);
}
describe('animate: keyframes on the compositor', () => {
it('bakes the spring into keyframes within a quarter of a pixel of the curve', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
expect(animation).toBeDefined();
expect(animation.options).toMatchObject({
fill: 'both',
easing: 'linear',
});
// 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).
const duration = Number(animation.options.duration) - END_HOLD_MS;
expect(duration).toBeCloseTo(curve.settleTime(0.05) * 1000, 6);
for (let t = 0; t <= duration; t += 0.5) {
const [x, y] = sampleAt(animation, 'translate', 1000 + t);
expect(Math.abs(x - curve.value(t / 1000))).toBeLessThan(0.26);
expect(y).toBe(0);
expect(animator.get('x', 1000 + t)).toBeCloseTo(curve.value(t / 1000), 9);
}
// Then the end state, held through a main-thread block.
expect(
sampleAt(animation, 'translate', 1000 + duration + END_HOLD_MS / 2),
).toEqual([300, 0]);
});
it('on a 3x screen, bakes the spring within a quarter of a device pixel', async () => {
vi.stubGlobal('devicePixelRatio', 3);
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
await commitFrame(1000);
const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
const duration = Number(animation.options.duration) - END_HOLD_MS;
let worst = 0;
for (let t = 0; t <= duration; t += 0.5) {
const [x] = sampleAt(animation, 'translate', 1000 + t);
worst = Math.max(worst, Math.abs(x - curve.value(t / 1000)));
}
// In device pixels, as the curve's chords are checked at their quarters.
expect(worst * 3).toBeLessThan(0.26);
});
it('on a 1x screen, bakes no more keyframes than a quarter of a CSS pixel needs', () => {
const count = (ratio: number) => {
vi.stubGlobal('devicePixelRatio', ratio);
recorded = [];
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
return live('translate')[0].keyframes.length;
};
const desktop = count(1);
expect(desktop).toBeLessThan(count(3));
// A ratio below 1 (a zoomed-out page) bakes as 1, never coarser.
expect(count(0.5)).toBe(desktop);
});
it('keeps the keyframe count modest (adaptive sampling)', () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
expect(live('translate')[0].keyframes.length).toBeLessThan(60);
});
it('clears an identity transform at rest, so a fixed child stays fixed', async () => {
const {animator, element} = setup();
animator.animate(
{x: 100, scale: 0.9, rotate: 10},
{spring: springs.quickChange},
);
// While the curve runs, the inline value is where it starts.
expect(['', 'none']).toContain(element.style.translate);
await advance(100);
animator.animate(
{x: 0, scale: 1, rotate: 0},
{spring: springs.quickChange},
);
// The frame that commits the call builds its animations.
await commitFrame(clock);
// While the motion back runs, the inline value is where it starts.
expect(live('translate')).toHaveLength(1);
expect(parse(element.style.translate)[0]).toBeCloseTo(animator.get('x'), 2);
await advance(5000);
// At rest the identity leaves the element: translate 0px 0px would make
// the element a fixed child's containing block, and scale 1 stops a
// finger scrolling inside it on Mobile Safari.
expect(element.style.translate).toBe('');
expect(element.style.scale).toBe('');
expect(element.style.rotate).toBe('');
// The keyframes stay numeric, so the curve still interpolates.
animator.animate({x: 50}, {spring: springs.quickChange});
expect(live('translate')[0].keyframes[0].translate).toBe('0px 0px');
});
it('clears opacity back at 1, and an identity set at rest, and keeps any other value', async () => {
const {animator, element} = setup();
animator.set({opacity: 0});
animator.animate({opacity: 1}, {spring: springs.quickChange});
await advance(5000);
expect(element.style.opacity).toBe('');
animator.set({x: 12});
animator.set({x: 0});
expect(element.style.translate).toBe('');
animator.animate({opacity: 0.5, x: 20}, {spring: springs.quickChange});
await advance(5000);
expect(element.style.opacity).toBe('0.5');
expect(element.style.translate).toBe('20px 0px');
});
it('keeps an identity inline where the stylesheet would move the element', async () => {
const {animator, element} = setup();
stylesheet.scale = '0.5';
animator.animate({scale: 0.9}, {spring: springs.quickChange});
animator.animate({scale: 1}, {spring: springs.quickChange});
await advance(5000);
expect(element.style.scale).toBe('none');
});
it('keeps a fade to 1 inline where the stylesheet rests at 0', async () => {
const {animator, element} = setup();
// A scroll edge layer: transparent in its stylesheet, faded in on a
// spring. At retire the end-state tail still holds 1, so the end can only
// be judged against the stylesheet once the animation is gone.
stylesheet.opacity = '0';
animator.set({opacity: 0});
animator.animate({opacity: 1}, {spring: springs.quickChange});
await advance(5000);
expect(live('opacity')).toHaveLength(0);
expect(element.style.opacity).toBe('1');
});
it('holds the value on screen inline while a curve runs, and the end once it retires', async () => {
const {animator, element} = setup();
animator.set({x: 10, opacity: 0.5});
animator.animate(
{x: 120, y: -40, scale: 1.1, rotate: 12, opacity: 0.25},
{spring: springs.quickChange},
);
// A frame painted before the compositor has the curve shows where the
// element is, never where it is going.
expect(element.style.translate).toBe('10px 0px');
expect(element.style.opacity).toBe('0.5');
const animations = ['translate', 'scale', 'rotate', 'opacity'].map(
channel => live(channel)[0],
);
await commitFrame(clock);
await advance(5000);
expect(element.style.translate).toBe('120px -40px');
expect(element.style.scale).toBe('1.1 1.1');
expect(element.style.rotate).toBe('12deg');
expect(element.style.opacity).toBe('0.25');
for (const animation of animations) {
expect(animation.cancelled).toBe(true);
}
});
it('keeps the end state in effect until the main thread drops the finished animation', async () => {
const {animator, element} = setup();
animator.animate({x: 120}, {spring: springs.quickChange});
const [animation] = live('translate');
expect(animation.options.fill).toBe('both');
// The animation outlasts its curve by END_HOLD_MS; the main thread drops
// it as soon as it runs after the curve's end.
const duration = Number(animation.options.duration) - END_HOLD_MS;
await advance(duration - 1);
expect(animation.cancelled).toBe(false);
await advance(2);
expect(animation.cancelled).toBe(true);
expect(element.style.translate).toBe(
animation.keyframes[animation.keyframes.length - 1].translate,
);
});
it('looks for its end again on the next frame when the engine dates animations per frame, not in a spin, and retires in that frame', async () => {
// WebKit moves an animation's currentTime once per frame. A retire that
// looks within a frame reads the frame's time, a fraction of a ms short of
// the end, and a timer set to that fraction fires again before anything
// moved: dozens of timers on the main thread after every motion.
const {animator} = setup();
const handle = animator.animate({x: 100}, {spring: springs.settle});
const [animation] = live('translate');
await commitFrame(clock);
const start = animation.startTime as number;
const curve = Number(animation.options.duration) - END_HOLD_MS;
let frameTime = start;
Object.defineProperty(animation, 'currentTime', {
configurable: true,
get: () => frameTime - start,
});
Object.defineProperty(animation, 'effect', {
configurable: true,
value: {getTiming: () => ({duration: animation.options.duration})},
});
// The last frame before the end dates the animation 0.5 ms short of it.
frameTime = start + curve - 0.5;
// Up to just before the retire is due (the injected clock and the timers
// move together).
clock += curve - 1;
await vi.advanceTimersByTimeAsync(curve - 1);
const timers = vi.spyOn(globalThis, 'setTimeout');
// A frame's worth of main-thread time with no frame in between.
for (let ms = 0; ms < 16; ms++) {
clock += 1;
await vi.advanceTimersByTimeAsync(1);
}
expect(timers.mock.calls.length).toBeLessThanOrEqual(2);
// The next frame: the engine's time passes the end, and it retires in
// that frame, before it paints, with no timer run in between.
frameTime = start + curve + 16;
clock += 1;
await commitFrame(clock);
expect(animation.cancelled).toBe(true);
await vi.advanceTimersByTimeAsync(17);
await expect(handle.finished).resolves.toBe(true);
});
it('keeps looking while the frame it looked in was dated short of the end, and retires in the frame that reaches it, before a late end timer runs', async () => {
const {animator} = setup();
animator.animate({x: 100}, {spring: springs.settle});
const [animation] = live('translate');
await commitFrame(clock);
const start = animation.startTime as number;
const curve = Number(animation.options.duration) - END_HOLD_MS;
const end = start + curve;
// The engine dates each animation per frame, at `frameTime`.
let frameTime = start;
Object.defineProperty(animation, 'currentTime', {
configurable: true,
get: () => frameTime - start,
});
Object.defineProperty(animation, 'effect', {
configurable: true,
value: {getTiming: () => ({duration: animation.options.duration})},
});
// Inside the last frame before the end: the timer that starts the frame
// looks has run, the end timer has not.
const toLook = end - 16 - clock;
clock += toLook;
await vi.advanceTimersByTimeAsync(toLook);
// The frame the look runs in is dated 20 ms short of the end, before
// that timer was due.
frameTime = end - 20;
await commitFrame(clock);
expect(animation.cancelled).toBe(false);
// The next frame reaches the end while the end timer, late, has still
// not run: the frame retires it before it paints.
frameTime = end + 1;
await commitFrame(clock);
expect(animation.cancelled).toBe(true);
});
it('a retarget while a look at the old curve\u2019s end waits for its frame still looks at the new curve\u2019s end in a frame', async () => {
// Each animation's frame look is its own: one still waiting for its frame
// for a replaced animation does not stand in for the new animation's.
const {animator} = setup();
animator.animate({x: 100}, {spring: springs.settle});
const [first] = live('translate');
await commitFrame(clock);
// The engine dates each animation per frame, at `frameTime`.
let frameTime = clock;
const datedPerFrame = (animation: Recorded) => {
Object.defineProperty(animation, 'currentTime', {
configurable: true,
get: () => frameTime - (animation.startTime as number),
});
Object.defineProperty(animation, 'effect', {
configurable: true,
value: {getTiming: () => ({duration: animation.options.duration})},
});
};
datedPerFrame(first);
const firstCurve = Number(first.options.duration) - END_HOLD_MS;
// Inside the last frame before its end, with no frame drawn: its look
// waits for the next frame.
clock += firstCurve - 10;
await vi.advanceTimersByTimeAsync(firstCurve - 10);
expect(frameQueue.length).toBeGreaterThan(0);
// Retargeted before that frame comes. The first curve shows as at rest
// by now, so the call waits for the browser's start, as one from rest
// does. The frame the old look waits for starts it, and that look leaves
// it running. The page then draws no frame until the new curve is inside
// its own last frame.
animator.animate({x: 200}, {spring: springs.settle});
const second = live('translate').at(-1) as Recorded;
expect(second.startTime).toBeNull();
await commitFrame(clock);
expect(second.cancelled).toBe(false);
datedPerFrame(second);
const secondCurve = Number(second.options.duration) - END_HOLD_MS;
const secondEnd = (second.startTime as number) + secondCurve;
const wait = secondEnd - 10 - clock;
clock += wait;
await vi.advanceTimersByTimeAsync(wait);
expect(second.cancelled).toBe(false);
// The next frame reaches the new curve's end: it retires there, before
// that frame paints, with no timer run in between.
frameTime = secondEnd + 1;
await commitFrame(clock);
expect(second.cancelled).toBe(true);
});
it('never retires an animation a sampler has paused', async () => {
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);
expect(animation.cancelled).toBe(false);
// Resumed: it leaves once the main thread looks again.
animation.paused = false;
await advance(150);
expect(animation.cancelled).toBe(true);
});
it('puts everything one call starts on one clock', 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', async () => {
const {animator} = setup();
animator.animate({scale: 0.5}, {spring: springs.settle});
await commitFrame(clock); // the browser starts it
clock += 5000;
expect(animator.get('scale')).toBe(0.5);
expect(animator.get('scaleY')).toBe(0.5);
});
it('does nothing for a value already at its target and at rest', async () => {
const {animator} = setup();
const handle = animator.animate({x: 0}, {spring: springs.settle});
expect(live('translate')).toHaveLength(0);
await expect(handle.finished).resolves.toBe(true);
});
});
describe('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('a call on a settle tail starts at the commit too, so a late first frame skips none of its curve', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
const [first] = live('translate');
await commitFrame(1000);
// A time inside the first curve's tail: within half a pixel of its
// target and slower than a quarter pixel a frame, before its end.
let t = 0;
while (
(Math.abs(curve.value(t) - 300) > 0.5 ||
Math.abs(curve.velocity(t)) > 15) &&
t < 5
) {
t += 0.001;
}
expect(t).toBeLessThan(5);
const at = 1000 + Math.ceil(t * 1000);
expect(at - 1000).toBeLessThan(
Number(first.options.duration) - END_HOLD_MS,
);
clock = at;
const from = animator.get('x');
const handle = animator.animate({x: 0}, {spring: springs.settle});
const second = live('translate').at(-1) as Recorded;
expect(second.startTime).toBeNull();
// The main thread is blocked for 80 ms; the first frame shows the new
// curve's first value, not 80 ms into it.
clock = at + 80;
await commitFrame(clock);
await expect(handle.started).resolves.toBe(clock);
expect(animator.get('x', clock)).toBeCloseTo(from, 6);
});
it('a call while the curve still moves starts at the call, from the value and velocity on screen', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
await commitFrame(1000);
clock = 1100;
animator.animate({x: 0}, {spring: springs.settle});
await commitFrame(1100);
expect((live('translate').at(-1) as Recorded).startTime).toBe(1100);
});
it('a start the browser dates before the block (WebKit) moves to after it', async () => {
// WebKit dates a pending animation at its last frame time before the
// task that made it, so after a block its first frame would show the
// motion that far in; the call's first read of that start moves it to
// the read. Chromium's commit start (the case above) stays.
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
// The task blocks for 300 ms; the browser dates the animation at 1000.
clock = 1300;
animation.startTime = 1000;
await commitFrame(1300);
await expect(handle.started).resolves.toBe(1300);
expect(animation.startTime).toBe(1300);
expect(animator.get('x', 1300)).toBeCloseTo(0, 9);
expect(animator.get('x', 1400)).toBeCloseTo(curve.value(0.1), 9);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
it('a start the browser dates at the frame before the call stays when the call\u2019s task runs on a few ms', async () => {
// Browser start times are frame times and a task's end is a live clock:
// on every call they differ by up to a frame plus the task's own length.
// A task that runs on 5 ms after the call (a component's effect after a
// tap) blocks nothing, so the start stays the browser's and a sequence
// chained on it keeps its clock.
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
clock = 1005;
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
clock = 1010;
animation.startTime = 1000;
await commitFrame(1016);
await expect(handle.started).resolves.toBe(1000);
expect(animation.startTime).toBe(1000);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
it('calls made in one task start together, whichever of them a block follows', async () => {
// One motion's parts are often separate calls in one task (a
// component's effect): a block measured per call would move the
// earlier calls past it and leave a later one on the browser's start,
// splitting the parts by a frame.
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
const first = animator.animate({x: 300}, {spring: springs.settle});
clock = 1030;
const second = animator.animate({opacity: 0.5}, {spring: springs.settle});
clock = 1040;
for (const animation of recorded) {
animation.startTime = 1000;
}
await commitFrame(1040);
const [a, b] = await Promise.all([first.started, second.started]);
expect(a).toBe(b);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
it('a block within two frames of the call keeps the browser\u2019s start', async () => {
// Browser start times are frame times and the task's end a live clock: a
// 20 ms block cannot be told apart from that quantization, so the start
// stays where the browser put it.
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
// The task blocks for 20 ms; the browser dates the animation at 1000.
clock = 1020;
animation.startTime = 1000;
await commitFrame(1020);
await expect(handle.started).resolves.toBe(1000);
expect(animation.startTime).toBe(1000);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
it('a start the browser dates by the call stays when its own task ended at once, however late the first read', async () => {
// WebKit under load from other tasks: the call's task ends at once, and
// another task holds the main thread before the first frame. Nothing in
// the call's task delayed it, so its start stays the browser's and the
// calls a sequence chains on it keep their clock (design:reduced-motion
// DR2's 200 ms cross-fade, a cancel fading on the previous fade's end).
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
// The call's task ends; then another task runs for 100 ms, and the
// browser commits the animation after it, dated at the call.
await Promise.resolve();
clock = 1100;
animation.startTime = 1000;
await commitFrame(1100);
await expect(handle.started).resolves.toBe(1000);
expect(animation.startTime).toBe(1000);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
it('a start read after the first frame stays the browser\u2019s', async () => {
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
// Paused before its first frame (a harness), then started late: the
// first frame passed with no start to read.
animation.paused = true;
await commitFrame(1016);
clock = 1600;
animation.paused = false;
animation.startTime = 1000;
await commitFrame(1600);
await expect(handle.started).resolves.toBe(1000);
expect(animation.startTime).toBe(1000);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
describe('a start the page reads a frame or more after the compositor uses it (Chromium)', () => {
it('starts at the frame that commits it, on the page as on the compositor', async () => {
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
// The frame that commits it runs at 1016 while its start is unread.
clock = 1016;
await commitFrame(1016, {startUnread: true});
expect(animation.startTime).toBe(1016);
await expect(handle.started).resolves.toBe(1016);
clock = 1116;
expect(animator.get('x')).toBeCloseTo(curve.value(0.1), 9);
});
it('a retarget before the page reads the start starts where the screen shows it', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1016;
await commitFrame(1016, {startUnread: true});
// 100 ms into the curve on screen; the page still has no start to read.
clock = 1116;
animator.animate({x: 400}, {spring: springs.settle});
await commitFrame(1116, {startUnread: true});
const retarget = live('translate').at(-1) as Recorded;
expect(retarget.startTime).toBe(1116);
expect(sampleAt(retarget, 'translate', 1116)[0]).toBeCloseTo(
curve.value(0.1),
1,
);
});
it('a rebase before the page reads the start keeps the value on screen', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1016;
await commitFrame(1016, {startUnread: true});
clock = 1116;
animator.rebase({x: -16});
const rebased = live('translate').at(-1) as Recorded;
// On the curve's own clock, 100 ms in, shifted by the rebase.
expect(rebased.startTime).not.toBeNull();
expect(sampleAt(rebased, 'translate', 1116)[0]).toBeCloseTo(
curve.value(0.1) - 16,
1,
);
});
it('a call made in a frame callback keeps the start the browser gives it, however late its next frame', async () => {
// A presented call's animations are made in its second frame's
// callback, so that frame commits them: the frame after it, here late
// behind a busy task, is not the one that starts them.
const {animator} = setup();
const handle = animator.animate(
{x: 300},
{spring: springs.settle},
{start: 'presented'},
);
clock = 1016;
await commitFrame(1016);
clock = 1033;
await commitFrame(1033);
const [animation] = live('translate');
clock = 1180;
await commitFrame(1180, {startUnread: true});
expect(animation.startTime).toBeNull();
let started = false;
void handle.started.then(() => {
started = true;
});
await Promise.resolve();
expect(started).toBe(false);
});
it('the calls from rest that one frame commits start at one time, however long the frame callbacks between them run', async () => {
const first = setup();
const second = setup();
first.animator.animate({x: 300}, {spring: springs.settle});
// A page's own frame callback runs 3 ms between the two animators'.
frameQueue.push(() => {
clock += 3;
});
second.animator.animate({x: 300}, {spring: springs.settle});
const [a, b] = live('translate');
clock = 1016;
await commitFrame(1016, {startUnread: true});
expect(a.startTime).toBe(1016);
expect(b.startTime).toBe(1016);
});
it('calls made in two tasks before one frame start together at that frame', async () => {
const first = setup();
const second = setup();
first.animator.animate({x: 300}, {spring: springs.settle});
frameQueue.push(() => {
clock += 3;
});
// The first task ends; the second call comes in a later task.
await Promise.resolve();
clock = 1005;
second.animator.animate({x: 300}, {spring: springs.settle});
const [a, b] = live('translate');
clock = 1016;
await commitFrame(1016, {startUnread: true});
expect(a.startTime).toBe(1016);
expect(b.startTime).toBe(1016);
});
it('a frame source that repeats a timestamp still reads each frame anew', async () => {
// Each frame gives its callbacks timestamp 0, as some test doubles do.
let queue: ((frame?: number) => void)[] = [];
const repeating = {
requestFrame: (callback: (frame?: number) => void) => {
queue.push(callback);
},
};
const runFrame = () => {
const frames = queue;
queue = [];
for (const callback of frames) {
callback(0);
}
};
const first = setup(repeating);
const second = setup(repeating);
first.animator.animate({x: 300}, {spring: springs.settle});
clock = 1016;
runFrame();
await vi.advanceTimersByTimeAsync(0);
clock = 1020;
second.animator.animate({x: 300}, {spring: springs.settle});
clock = 1033;
runFrame();
const [a, b] = live('translate');
expect(a.startTime).toBe(1016);
expect(b.startTime).toBe(1033);
});
it('a call first framed in a later frame takes the time that frame runs', async () => {
const first = setup();
const second = setup();
first.animator.animate({x: 300}, {spring: springs.settle});
clock = 1016;
await commitFrame(1016, {startUnread: true});
clock = 1020;
second.animator.animate({x: 300}, {spring: springs.settle});
const [a, b] = live('translate');
clock = 1033;
await commitFrame(1033, {startUnread: true});
expect(a.startTime).toBe(1016);
expect(b.startTime).toBe(1033);
});
it('a call whose first frame comes after a block keeps the start the browser gives it', async () => {
// A block between the call and its first frame: that frame cannot tell
// a call made in a task from one a page's own frame callback made, so
// it sets no start of its own.
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
clock = 1150;
await commitFrame(1150, {startUnread: true});
expect(animation.startTime).toBeNull();
let started = false;
void handle.started.then(() => {
started = true;
});
await Promise.resolve();
expect(started).toBe(false);
});
it('a late first frame that leaves the start unread: a read and a retarget take the curve from that frame', async () => {
// The first frame comes 70 ms after the call, late behind other work.
// The page itself does not block. The page still has no start to read,
// but the compositor has the call moving by then.
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
clock = 1070;
await commitFrame(1070, {startUnread: true});
expect(animation.startTime).toBeNull();
clock = 1170;
expect(animator.get('x')).toBeCloseTo(curve.value(0.1), 9);
animator.animate({x: 400}, {spring: springs.settle});
const retarget = live('translate').at(-1) as Recorded;
expect(sampleAt(retarget, 'translate', 1170)[0]).toBeCloseTo(
curve.value(0.1),
1,
);
});
it('a late first frame that leaves the start unread: the browser\u2019s start, once read, still decides', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
clock = 1070;
await commitFrame(1070, {startUnread: true});
// The browser started it at 1060 and tells the page now.
animation.commit(1060);
await Promise.resolve();
await Promise.resolve();
clock = 1170;
expect(animator.get('x')).toBeCloseTo(curve.value(0.11), 9);
});
it('a rebase after a late first frame carries the channel on from that frame, with a start of its own', async () => {
const {element, animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
const shown = animator.get('x');
expect(shown).toBeCloseTo(curve.value(0.1), 1);
animator.rebase({x: -16});
const rebuilt = live('translate').at(-1) as Recorded;
// The compositor has x moving since that frame, so the rebuilt animation
// starts now, from the value on screen in the new coordinates.
expect(rebuilt.startTime).toBe(1170);
const first = parse(rebuilt.keyframes[0].translate)[0];
expect(first).toBeCloseTo(shown - 16, 1);
expect(animator.get('x')).toBeCloseTo(first, 1);
expect(inlineX(element)).toBeCloseTo(first, 1);
expect(presentedOffsetOf(element).x).toBeCloseTo(0, 1);
clock = 1186;
await commitFrame(1186, {startUnread: true});
clock = 1202;
const later = sampleAt(rebuilt, 'translate', 1202)[0];
expect(animator.get('x')).toBeCloseTo(later, 1);
animator.animate({x: 400}, {spring: springs.settle});
const retarget = live('translate').at(-1) as Recorded;
expect(sampleAt(retarget, 'translate', 1202)[0]).toBeCloseTo(later, 1);
});
it('a set of the other axis after a late first frame carries x on from that frame', async () => {
const {element, animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
const shown = animator.get('x');
const speed = animator.getVelocity('x');
animator.set({y: 10});
const rebuilt = live('translate').at(-1) as Recorded;
expect(rebuilt.startTime).toBe(1170);
const [x, y] = parse(rebuilt.keyframes[0].translate);
expect(x).toBeCloseTo(shown, 1);
expect(y).toBeCloseTo(10, 1);
expect(animator.get('x')).toBeCloseTo(shown, 1);
expect(animator.getVelocity('x')).toBeCloseTo(speed, 0);
expect(inlineX(element)).toBeCloseTo(shown, 1);
expect(presentedOffsetOf(element).x).toBeCloseTo(0, 1);
clock = 1186;
await commitFrame(1186, {startUnread: true});
clock = 1202;
expect(animator.get('x')).toBeCloseTo(
sampleAt(rebuilt, 'translate', 1202)[0],
1,
);
});
it('a retarget of the other axis without a clock after a late first frame carries x on from that frame', async () => {
const {element, animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
const shown = animator.get('x');
animator.animate({y: 50}, {spring: springs.settle});
const rebuilt = live('translate').at(-1) as Recorded;
// The element is moving on screen, so the call starts now: x carries
// on from the screen and y starts from rest.
expect(rebuilt.startTime).toBe(1170);
const [x, y] = parse(rebuilt.keyframes[0].translate);
expect(x).toBeCloseTo(shown, 1);
expect(y).toBeCloseTo(0, 1);
expect(animator.get('x')).toBeCloseTo(shown, 1);
expect(inlineX(element)).toBeCloseTo(shown, 1);
expect(presentedOffsetOf(element).x).toBeCloseTo(0, 1);
clock = 1186;
await commitFrame(1186, {startUnread: true});
clock = 1202;
const [laterX, laterY] = sampleAt(rebuilt, 'translate', 1202);
expect(animator.get('x')).toBeCloseTo(laterX, 1);
expect(animator.get('y')).toBeCloseTo(laterY, 1);
});
it('a retarget that joins a call by its clock after a late first frame reads the first value the rebuilt animation starts from', async () => {
const {element, animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
animator.animate({y: 50}, {spring: springs.settle}, {at: 1000});
const rebuilt = live('translate').at(-1) as Recorded;
expect(rebuilt.startTime).toBeNull();
const first = parse(rebuilt.keyframes[0].translate)[0];
expect(animator.get('x')).toBeCloseTo(first, 1);
expect(inlineX(element)).toBeCloseTo(first, 1);
expect(presentedOffsetOf(element).x).toBeCloseTo(0, 1);
// The frame that commits it starts the joined call: the call is that
// frame's own task's.
clock = 1186;
await commitFrame(1186, {startUnread: true});
clock = 1202;
expect(animator.get('x')).toBeCloseTo(
sampleAt(rebuilt, 'translate', 1202)[0],
1,
);
});
it('a curve that joins a call by an older clock reads, after a late first frame, where the compositor has it', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
animator.animate({y: 50}, {spring: springs.settle}, {at: 990});
const [joined] = live('translate').slice(-1);
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
// The compositor started the joined animation at that frame: 100 ms
// into its keyframes, which run from the call's own time.
const shown = sampleAt(joined, 'translate', joined.createdAt + 100);
expect(animator.get('x')).toBeCloseTo(shown[0], 1);
expect(animator.get('y')).toBeCloseTo(shown[1], 1);
});
it('a call whose only channel carries on after a late first frame reports that frame as its start', async () => {
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
animator.rebase({x: -16});
await expect(handle.started).resolves.toBe(1070);
});
it('a rebase of a coast after a late first frame keeps its course from that frame', async () => {
const {animator} = setup();
animator.decay(coast(animator, {x: 1000}));
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
const shown = animator.get('x');
animator.rebase({x: -16});
const rebuilt = live('translate').at(-1) as Recorded;
expect(rebuilt.startTime).toBe(1170);
expect(parse(rebuilt.keyframes[0].translate)[0]).toBeCloseTo(
shown - 16,
1,
);
clock = 1202;
expect(animator.get('x')).toBeCloseTo(
sampleAt(rebuilt, 'translate', 1202)[0],
1,
);
});
it('a channel whose call waits past its undated end after a late first frame still carries on from the screen', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1070;
await commitFrame(1070, {startUnread: true});
// Past the curve's end counted from the call's own time, and short of
// its end counted from that frame.
const duration =
Number(live('translate')[0].options.duration) - END_HOLD_MS;
clock = 1000 + duration + 30;
const shown = animator.get('x');
expect(shown).toBeLessThan(300);
animator.set({y: 10});
const rebuilt = live('translate').at(-1) as Recorded;
expect(parse(rebuilt.keyframes[0].translate)[0]).toBeCloseTo(shown, 1);
});
it('a late first frame that leaves the start unread: a read of a later time takes the curve from that frame, as the velocity does', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
// A companion samples a frame ahead of now.
expect(animator.get('x', 1186)).toBeCloseTo(curve.value(0.116), 9);
expect(animator.getVelocity('x', 1186)).toBeCloseTo(
curve.velocity(0.116),
9,
);
});
it("a rebase of one channel after a late first frame keeps the call's other channels reading from that frame", async () => {
const {animator} = setup();
animator.animate({x: 300, opacity: 0}, {spring: springs.settle});
const fade = live('opacity').at(-1) as Recorded;
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
animator.rebase({x: -16});
expect(live('opacity').at(-1)).toBe(fade);
expect(animator.get('opacity')).toBeCloseTo(
sampleAt(fade, 'opacity', fade.createdAt + 100)[0],
2,
);
clock = 1186;
await commitFrame(1186, {startUnread: true});
clock = 1202;
const shown = sampleAt(fade, 'opacity', fade.createdAt + 132)[0];
expect(animator.get('opacity')).toBeCloseTo(shown, 2);
animator.animate({opacity: 1}, {spring: springs.settle});
const retarget = live('opacity').at(-1) as Recorded;
expect(sampleAt(retarget, 'opacity', 1202)[0]).toBeCloseTo(shown, 2);
});
it("a set of the other axis after a late first frame keeps the call's other channels reading from that frame", async () => {
const {animator} = setup();
animator.animate({x: 300, opacity: 0}, {spring: springs.settle});
const fade = live('opacity').at(-1) as Recorded;
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
animator.set({y: 10});
expect(live('opacity').at(-1)).toBe(fade);
expect(animator.get('opacity')).toBeCloseTo(
sampleAt(fade, 'opacity', fade.createdAt + 100)[0],
2,
);
clock = 1186;
await commitFrame(1186, {startUnread: true});
clock = 1202;
const shown = sampleAt(fade, 'opacity', fade.createdAt + 132)[0];
expect(animator.get('opacity')).toBeCloseTo(shown, 2);
animator.animate({opacity: 1}, {spring: springs.settle});
const retarget = live('opacity').at(-1) as Recorded;
expect(sampleAt(retarget, 'opacity', 1202)[0]).toBeCloseTo(shown, 2);
});
it('a call the page pauses before its first frame waits for its start', async () => {
// A harness or a page that pauses the animation: nothing starts it at
// the commit, so nothing sets a start for it either.
const {animator} = setup();
const handle = animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
animation.paused = true;
clock = 1016;
await commitFrame(1016, {startUnread: true});
expect(animation.startTime).toBeNull();
let started = false;
void handle.started.then(() => {
started = true;
});
await Promise.resolve();
expect(started).toBe(false);
});
});
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});
await commitFrame(1100);
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});
// Each move is its own task.
await Promise.resolve();
}
// 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});
// Each move is its own task.
await Promise.resolve();
}
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('rebasing a curve that waits for its first frame keeps it in its call', async () => {
const {animator} = setup();
animator.play({
opacity: {duration: 0.3, at: t => 1 - t, velocity: () => -1},
x: {duration: 0.3, at: t => 100 * t, velocity: () => 100},
rotate: {duration: 0.3, at: t => 90 * t, velocity: () => 90},
});
animator.rebase({x: -20});
animator.animate({y: 50}, {spring: springs.settle});
clock = 1300;
await commitFrame(1300);
// Every curve starts with the browser's start.
// 100 ms in: 9° (not the 27° of a curve dated at the call), x 10 − 20.
expect(animator.get('rotate', 1400)).toBeCloseTo(9, 6);
expect(animator.get('x', 1400)).toBeCloseTo(-10, 6);
});
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('additive: a retarget adds to the curve on screen', () => {
const old = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
const oldEnd = old.settleTime(0.05);
const oldAt = (t: number) => (t >= oldEnd ? 300 : old.value(t));
it('starts from the old curve\u2019s value and velocity, and reads as their sum', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
await commitFrame(1000);
clock = 1150;
const x = animator.get('x');
const v = animator.getVelocity('x');
animator.animate({x: 100}, {spring: springs.settle}, {additive: true});
expect(animator.get('x')).toBeCloseTo(x, 9);
expect(animator.getVelocity('x')).toBeCloseTo(v, 6);
const delta = solveSpring(toSpring(springs.settle), {from: 0, to: -200});
for (const t of [0.02, 0.1, 0.4]) {
expect(animator.get('x', 1150 + t * 1000)).toBeCloseTo(
oldAt(0.15 + t) + delta.value(t),
6,
);
}
await advance(10_000);
expect(animator.get('x')).toBe(100);
});
it('a played reversal keeps the old velocity: a late first frame shows only the reversal\u2019s own start', async () => {
// An ease-in-out reversal starts at rest; replacing a curve that moves
// at v puts the old curve v·d ahead of it by a first frame d ms late.
const ease = cubicBezier(timing.curves.move);
const reversal = (from: number, to: number) => ({
duration: 0.35,
at: (t: number) => from + (to - from) * ease(Math.min(1, t / 0.35)),
velocity: (t: number) =>
((to - from) / 0.35) *
((ease(Math.min(1, t / 0.35 + 1e-4)) -
ease(Math.max(0, t / 0.35 - 1e-4))) /
2e-4),
});
const steps = async (additive: boolean) => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle}, {at: 1000});
clock = 1120;
const from = animator.get('x');
animator.play({x: reversal(from, 0)}, {at: 1120, additive});
return [30, 60, 100].map(d =>
Math.abs(animator.get('x', 1120 + d) - oldAt((120 + d) / 1000)),
);
};
const replaced = await steps(false);
const added = await steps(true);
for (let i = 0; i < added.length; i++) {
expect(added[i]).toBeLessThan(replaced[i] / 2);
}
// What remains is the reversal's own first d ms, scaled to the targets.
expect(added[0]).toBeCloseTo(300 * ease(30 / 350), 6);
});
it('nests: a second retarget adds to the first', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
await commitFrame(1000);
clock = 1100;
animator.animate({x: 100}, {spring: springs.settle}, {additive: true});
clock = 1200;
const x = animator.get('x');
const v = animator.getVelocity('x');
animator.animate({x: 250}, {spring: springs.settle}, {additive: true});
expect(animator.get('x')).toBeCloseTo(x, 9);
expect(animator.getVelocity('x')).toBeCloseTo(v, 6);
const first = solveSpring(toSpring(springs.settle), {from: 0, to: -200});
const second = solveSpring(toSpring(springs.settle), {from: 0, to: 150});
expect(animator.get('x', 1300)).toBeCloseTo(
oldAt(0.3) + first.value(0.2) + second.value(0.1),
6,
);
await advance(10_000);
expect(animator.get('x')).toBe(250);
});
it('replaces as before for a property at rest or given a velocity', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle}, {additive: true});
await commitFrame(1000);
const fromRest = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
expect(animator.get('x', 1100)).toBeCloseTo(fromRest.value(0.1), 9);
clock = 1100;
const x = animator.get('x');
animator.animate(
{x: 0},
{spring: springs.settle, velocity: {x: 0}},
{additive: true},
);
const back = solveSpring(toSpring(springs.settle), {from: x, to: 0});
expect(animator.get('x', 1200)).toBeCloseTo(back.value(0.1), 9);
});
});
describe('start: when a call\u2019s animations start', () => {
it('presented: leaves the element at rest, and creates the animations two frames later', async () => {
const {animator, element} = setup();
animator.set({x: 20});
// The set's own promotion ends first.
await vi.advanceTimersByTimeAsync(PROMOTION_LINGER_MS + 1);
expect(element.style.willChange).toBe('');
const handle = animator.animate(
{x: 100},
{spring: springs.settle},
{start: 'presented'},
);
// At rest, with no layer yet: the next frame commits it where it is.
// (A layer at rest for two frames left a stale paint in WebKit on iOS.)
expect(live('translate')).toHaveLength(0);
expect(element.style.translate).toBe('20px 0px');
expect(element.style.willChange).toBe('');
expect(animator.get('x')).toBe(20);
clock = 1016;
await commitFrame(1016);
expect(live('translate')).toHaveLength(0);
// The frame after it creates them; the browser starts them at its commit.
clock = 1033;
await commitFrame(1033);
expect(live('translate')).toHaveLength(1);
expect(element.style.willChange).toContain('translate');
clock = 1050;
await commitFrame(1050);
await expect(handle.started).resolves.toBe(1050);
const curve = solveSpring(toSpring(springs.settle), {from: 20, to: 100});
expect(animator.get('x', 1150)).toBeCloseTo(curve.value(0.1), 9);
expect(sampleAt(live('translate')[0], 'translate', 1150)[0]).toBeCloseTo(
curve.value(0.1),
0,
);
});
it('presented: a start WebKit dates at the frame that creates the animations keeps it, wherever in its frame the call was made', async () => {
// A presented call's animations are created in its second frame's
// callback, so its task is that callback's, not the call's: measured
// from the call, a call made early in its frame looked like a block
// longer than two frames, and a late first read moved the start.
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
const handle = animator.animate(
{x: 100},
{spring: springs.settle},
{start: 'presented'},
);
clock = 1016;
await commitFrame(1016);
// The frame that creates the animations; the callback's task runs on
// 3 ms.
requestFrame(() => {
clock = 1036;
});
clock = 1033;
await commitFrame(1033);
expect(live('translate')).toHaveLength(1);
// Other tasks hold the main thread until the next frame, where WebKit's
// start for them, that frame's time, is first read.
clock = 1090;
live('translate')[0].startTime = 1033;
await commitFrame(1090);
await expect(handle.started).resolves.toBe(1033);
expect(live('translate')[0].startTime).toBe(1033);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
it('presented: a block in the frame that creates the animations moves their start past it', async () => {
Object.defineProperty(document, 'timeline', {
configurable: true,
get: () => ({currentTime: clock}),
});
try {
const {animator} = setup();
const handle = animator.animate(
{x: 100},
{spring: springs.settle},
{start: 'presented'},
);
clock = 1016;
await commitFrame(1016);
// The frame that creates the animations blocks for 300 ms; WebKit's
// start for them, that frame's time, is read at the next frame.
requestFrame(() => {
clock = 1333;
});
clock = 1033;
await commitFrame(1033);
clock = 1340;
live('translate')[0].startTime = 1033;
await commitFrame(1340);
await expect(handle.started).resolves.toBe(1340);
expect(live('translate')[0].startTime).toBe(1340);
} finally {
Reflect.deleteProperty(document, 'timeline');
}
});
it('presented: a call queued after another change flushed the queue still waits its own two frames', async () => {
const {animator} = setup();
animator.animate({x: 100}, {spring: springs.settle}, {start: 'presented'});
// Another change creates the waiting call's animations first.
animator.animate({y: 50}, {spring: springs.settle});
clock = 1016;
await commitFrame(1016);
animator.animate(
{opacity: 0.5},
{spring: springs.settle},
{start: 'presented'},
);
expect(live('opacity')).toHaveLength(0);
// The first call's second frame is this call's first: it still waits.
clock = 1033;
await commitFrame(1033);
expect(live('opacity')).toHaveLength(0);
clock = 1050;
await commitFrame(1050);
expect(live('opacity')).toHaveLength(1);
});
it('presented: a second presented call on the same property a frame later keeps its own two frames', async () => {
const {animator} = setup();
animator.animate({x: 100}, {spring: springs.settle}, {start: 'presented'});
clock = 1016;
await commitFrame(1016);
animator.animate({x: 200}, {spring: springs.settle}, {start: 'presented'});
// The first call's second frame: its property is now the second call's,
// so nothing starts yet.
clock = 1033;
await commitFrame(1033);
expect(live('translate')).toHaveLength(0);
// The second call's own second frame.
clock = 1050;
await commitFrame(1050);
expect(live('translate')).toHaveLength(1);
await commitFrame(1066);
expect(animator.get('x', 1066 + 5000)).toBeCloseTo(200, 3);
});
it('presented: a later presented call that takes part of a waiting call\u2019s channel starts the rest of it, from its own start', async () => {
const {animator} = setup();
const first = animator.animate(
{x: 100, y: 100},
{spring: springs.settle},
{start: 'presented'},
);
clock = 1016;
await commitFrame(1016);
animator.animate({x: 200}, {spring: springs.settle}, {start: 'presented'});
// The first call's second frame: its channel now holds the second call's
// curve, so nothing starts yet.
clock = 1033;
await commitFrame(1033);
expect(live('translate')).toHaveLength(0);
// The second call's second frame creates the channel, with the first
// call's y in it; the browser starts it at the next commit.
clock = 1050;
await commitFrame(1050);
expect(live('translate')).toHaveLength(1);
clock = 1066;
await commitFrame(1066);
await expect(first.started).resolves.toBe(1066);
// y was at rest on screen until then: its curve starts there, and the
// model reads what the screen shows.
const y = solveSpring(toSpring(springs.settle), {from: 0, to: 100});
expect(animator.get('y', 1166)).toBeCloseTo(y.value(0.1), 6);
expect(sampleAt(live('translate')[0], 'translate', 1166)[1]).toBeCloseTo(
y.value(0.1),
0,
);
});
it('presented: another change before then creates the animations first', async () => {
const {animator} = setup();
animator.animate({x: 100}, {spring: springs.settle}, {start: 'presented'});
animator.animate({y: 50}, {spring: springs.settle});
expect(live('translate').length).toBeGreaterThan(0);
await commitFrame(clock);
const x = solveSpring(toSpring(springs.settle), {from: 0, to: 100});
expect(animator.get('x', clock + 100)).toBeCloseTo(x.value(0.1), 9);
});
it('presented: a retarget of a moving property starts now, from the value and velocity on screen (FR6)', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
await commitFrame(1000);
clock = 1100;
const from = animator.get('x');
const velocity = animator.getVelocity('x');
animator.animate({x: 0}, {spring: springs.settle}, {start: 'presented'});
// The element is moving, not at rest: no two frames on the old curve and
// no restart at the commit from the call's value. The new curve starts at
// the call, from what is on screen, as a retarget does.
await commitFrame(1100);
const [animation] = live('translate');
expect(animation.startTime).toBe(1100);
expect(animator.get('x', 1100)).toBeCloseTo(from, 6);
expect(animator.getVelocity('x', 1100)).toBeCloseTo(velocity, 3);
const back = solveSpring(toSpring(springs.settle), {
from,
to: 0,
velocity,
});
expect(animator.get('x', 1200)).toBeCloseTo(back.value(0.1), 6);
});
it('commit: a retarget is dated by the browser\u2019s commit, from the value on screen', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
await commitFrame(1000);
clock = 1100;
const from = animator.get('x');
const velocity = animator.getVelocity('x');
const handle = animator.animate(
{x: 0},
{spring: springs.settle},
{start: 'commit'},
);
const [animation] = live('translate');
expect(animation.startTime).toBeNull();
// Held where it is until the browser starts it.
expect(animator.get('x')).toBeCloseTo(from, 9);
clock = 1130;
await commitFrame(1130);
await expect(handle.started).resolves.toBe(1130);
const back = solveSpring(toSpring(springs.settle), {
from,
to: 0,
velocity,
});
expect(animator.get('x', 1230)).toBeCloseTo(back.value(0.1), 6);
});
it('a handle hands out the curve it plays, for a companion on the same clock', async () => {
const {animator} = setup();
const handle = animator.animate({y: 400}, {spring: springs.sheetPresent});
const curve = handle.curve('y');
expect(curve).not.toBeNull();
expect(handle.curve('x')).toBeNull();
await commitFrame(1000);
const y = solveSpring(toSpring(springs.sheetPresent), {from: 0, to: 400});
for (const t of [0, 0.05, 0.2]) {
expect(curve?.at(t)).toBeCloseTo(y.value(t), 9);
expect(curve?.velocity(t)).toBeCloseTo(y.velocity(t), 6);
expect(animator.get('y', 1000 + t * 1000)).toBeCloseTo(y.value(t), 9);
}
expect(curve?.at(curve.duration)).toBe(400);
});
});
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));
expect(animatorFor(a, {pseudoElement: '::backdrop'})).toBe(
animatorFor(a, {pseudoElement: '::backdrop'}),
);
expect(animatorFor(a, {pseudoElement: '::backdrop'})).not.toBe(
animatorFor(a),
);
});
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});
await commitFrame(clock);
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(Math.abs(tx - x.value(0.08))).toBeLessThan(0.26);
expect(Math.abs(ty - y.value(0.03))).toBeLessThan(0.26);
});
});
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});
// The stylesheet's reasons join once the callback's microtasks run.
await Promise.resolve();
expect(element.style.willChange).toBe('transform, translate, opacity');
await advance(5000 + PROMOTION_LINGER_MS);
expect(element.style.willChange).toBe('');
});
it("reads the stylesheet's will-change in a task of its own, so a promotion reads no style in its own task", async () => {
// A drag's first move promotes: reading the stylesheet's reasons then
// would force a style recalculation in the input handler.
stylesheet['will-change'] = 'transform, opacity';
const {animator, element} = setup();
// In the document, where the read happens.
document.body.append(element);
await commitFrame(clock);
await vi.advanceTimersByTimeAsync(0);
const readsOf = () =>
vi
.mocked(window.getComputedStyle)
.mock.calls.filter(([read]) => read === element).length;
const before = readsOf();
animator.set({y: 10});
expect(readsOf()).toBe(before);
expect(element.style.willChange).toBe('transform, opacity, translate');
await advance(PROMOTION_LINGER_MS + 10);
expect(element.style.willChange).toBe('');
element.remove();
});
it('reads no style for a node out of the document: a node removed before its read is never read', async () => {
// A shared animator (animatorFor) is never detached: its node can leave
// the document with the read still waiting. A node out of the document
// has no style to read, and reading one costs a style pass for nothing.
stubMedia(false, false);
const readsOf = (node: Element) =>
vi
.mocked(window.getComputedStyle)
.mock.calls.filter(([read]) => read === node).length;
const removed = document.createElement('div');
document.body.append(removed);
createMotionEngine(removed, {now: () => clock, requestFrame});
removed.remove();
const kept = document.createElement('div');
document.body.append(kept);
createMotionEngine(kept, {now: () => clock, requestFrame});
await vi.advanceTimersByTimeAsync(0);
expect(readsOf(removed)).toBe(0);
// A node still in the document is read, once, in that task.
expect(readsOf(kept)).toBe(1);
kept.remove();
});
it("keeps the stylesheet's will-change when a node read nothing before it moves", async () => {
// Put back after its read was skipped, a node reads its stylesheet's
// reasons when a promotion needs them.
stylesheet['will-change'] = 'transform, opacity';
stubMedia(false, false);
const element = document.createElement('div');
const animator = createMotionEngine(element, {
now: () => clock,
requestFrame,
});
document.body.append(element);
animator.set({y: 10});
await Promise.resolve();
expect(element.style.willChange).toBe('transform, opacity, translate');
element.remove();
});
it("keeps the stylesheet's will-change when an element attached in this task moves at once", async () => {
stylesheet['will-change'] = 'transform, opacity';
const {animator, element} = setup();
animator.animate({y: 100}, {spring: springs.settle});
await Promise.resolve();
expect(element.style.willChange).toBe('transform, opacity, translate');
});
it("reads the stylesheets of the motions one callback starts in one pass once it ends, not between one element's writes and the next's", async () => {
// A list's reorder glides every row at once, each row's animator new.
stylesheet['will-change'] = 'opacity';
const rows = [setup(), setup(), setup()];
// A bare spring, which reads no theme tempo.
const spring = {response: 0.3, dampingRatio: 1};
const readsOf = (node: Element) =>
vi
.mocked(window.getComputedStyle)
.mock.calls.filter(([read]) => read === node).length;
for (const {animator} of rows) {
animator.animate({y: 40}, {spring});
}
for (const {element} of rows) {
expect(readsOf(element)).toBe(0);
expect(element.style.willChange).toBe('translate');
}
await Promise.resolve();
for (const {element} of rows) {
expect(readsOf(element)).toBe(1);
expect(element.style.willChange).toBe('opacity, translate');
}
});
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('set with promote: false writes the values without a layer, and leaves other promotion alone', async () => {
// A one-off switch (a veil under a sticky header during a programmatic
// scroll) must not give its element a layer.
const {animator, element} = setup();
animator.set({opacity: 0.5}, {promote: false});
expect(element.style.opacity).toBe('0.5');
expect(element.style.willChange).toBe('');
await advance(PROMOTION_LINGER_MS + 10);
expect(element.style.willChange).toBe('');
// A channel a running motion promoted stays promoted, on its own clock.
const moving = setup();
moving.animator.animate({x: 120}, {spring: springs.settle});
expect(moving.element.style.willChange).toBe('translate');
moving.animator.set({opacity: 0.25}, {promote: false});
expect(moving.element.style.opacity).toBe('0.25');
expect(moving.element.style.willChange).toBe('translate');
await advance(5000 + PROMOTION_LINGER_MS);
expect(moving.element.style.willChange).toBe('');
// A channel with other motion still running gets its animation's layer.
const shared = setup();
shared.animator.animate({y: 80}, {spring: springs.settle});
shared.animator.set({x: 10}, {promote: false});
expect(live('translate').length).toBeGreaterThan(0);
expect(shared.element.style.willChange).toBe('translate');
});
it('promotes a pseudo-element through a custom property on its host', async () => {
const {animator, element} = setup({pseudoElement: '::backdrop'});
animator.set({opacity: 0});
// set() promotes a pseudo-element too.
expect(
element.style.getPropertyValue('--astryx-motion-will-change-backdrop'),
).toBe('opacity');
animator.animate({opacity: 1}, {spring: springs.alertPresent});
expect(
element.style.getPropertyValue('--astryx-motion-will-change-backdrop'),
).toBe('opacity');
expect(element.style.willChange).toBe('');
await advance(5000 + PROMOTION_LINGER_MS);
expect(
element.style.getPropertyValue('--astryx-motion-will-change-backdrop'),
).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});
await commitFrame(clock);
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});
animator.animate(
{y: 0},
{spring: springs.sheetDetent, velocity: {y: 1500}},
);
expect(animator.get('y')).toBe(200);
expect(animator.getVelocity('y')).toBeCloseTo(1500, 6);
});
it('a retarget starts from the value and the velocity on screen', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.emphasis, velocity: {x: 800}});
const first = live('translate')[0];
await advance(120);
const value = animator.get('x');
const velocity = animator.getVelocity('x');
animator.animate({x: -100}, {spring: springs.emphasis});
// The frame that commits the call replaces the animation.
expect(first.cancelled).toBe(false);
await commitFrame(clock);
expect(first.cancelled).toBe(true);
const second = live('translate')[0];
expect(second.startTime).toBe(clock);
expect(animator.get('x', clock)).toBeCloseTo(value, 9);
expect(animator.getVelocity('x', clock)).toBeCloseTo(velocity, 6);
expect(sampleAt(second, 'translate', clock)[0]).toBeCloseTo(value, 2);
// And it really goes to the new target with that start.
const curve = solveSpring(toSpring(springs.emphasis), {
from: value,
to: -100,
velocity,
});
expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 9);
});
describe('a spring retarget committed late starts at its frame', () => {
// The first curve, as the screen shows it from its start at 1000.
const old = solveSpring(toSpring(springs.emphasis), {
from: 0,
to: 300,
velocity: 800,
});
const shownAt = (time: number) => old.value((time - 1000) / 1000);
const shownVelocityAt = (time: number) =>
old.velocity((time - 1000) / 1000);
async function moving() {
const setUp = setup();
setUp.animator.animate(
{x: 300},
{spring: springs.emphasis, velocity: {x: 800}},
);
await advance(120);
return setUp;
}
it('a retarget whose frame comes late starts there, from the value and the velocity on screen', async () => {
const {animator} = await moving();
animator.animate({x: -100}, {spring: springs.emphasis});
// A main-thread block: the frame that commits the call comes 200 ms
// later, and the screen shows the first curve until then.
clock += 200;
await commitFrame(clock);
const [animation] = live('translate');
expect(animation.startTime).toBe(clock);
expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);
expect(animator.getVelocity('x', clock)).toBeCloseTo(
shownVelocityAt(clock),
4,
);
expect(sampleAt(animation, 'translate', clock)[0]).toBeCloseTo(
shownAt(clock),
2,
);
const curve = solveSpring(toSpring(springs.emphasis), {
from: shownAt(clock),
to: -100,
velocity: shownVelocityAt(clock),
});
expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 6);
});
it('a retarget whose frame comes on time keeps its own clock', async () => {
const {animator} = await moving();
const call = clock;
const [old] = live('translate');
animator.animate({x: -100}, {spring: springs.emphasis});
clock += 30;
await commitFrame(clock);
const [made] = live('translate');
expect(made).not.toBe(old);
expect(made.startTime).toBe(call);
const curve = solveSpring(toSpring(springs.emphasis), {
from: shownAt(call),
to: -100,
velocity: shownVelocityAt(call),
});
expect(animator.get('x', clock + 90)).toBeCloseTo(
curve.value((clock + 90 - call) / 1000),
6,
);
});
it('calls before a late frame start there from the curve that the screen still shows', async () => {
const {animator} = await moving();
animator.animate({x: -100}, {spring: springs.emphasis});
clock += 10;
animator.animate({x: 40}, {spring: springs.settle});
clock += 190;
await commitFrame(clock);
const curve = solveSpring(toSpring(springs.settle), {
from: shownAt(clock),
to: 40,
velocity: shownVelocityAt(clock),
});
expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 6);
});
it('a rebase before the late frame moves the place on screen with the element', async () => {
const {animator} = await moving();
animator.animate({x: -100}, {spring: springs.emphasis});
animator.rebase({x: -40});
clock += 200;
await commitFrame(clock);
expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock) - 40, 6);
expect(animator.getVelocity('x', clock)).toBeCloseTo(
shownVelocityAt(clock),
4,
);
});
it('an additive retarget whose frame comes late adds to the curve on screen from there', async () => {
const {animator} = await moving();
animator.animate({x: -100}, {spring: springs.settle}, {additive: true});
clock += 200;
await commitFrame(clock);
expect(live('translate')[0].startTime).toBe(clock);
expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);
const difference = solveSpring(toSpring(springs.settle), {
from: 0,
to: -400,
});
// The first curve keeps its own spring: one spring from the screen's
// value and velocity would be elsewhere.
const replaced = solveSpring(toSpring(springs.settle), {
from: shownAt(clock),
to: -100,
velocity: shownVelocityAt(clock),
});
let apart = 0;
for (let ms = 50; ms <= 600; ms += 50) {
const added = shownAt(clock + ms) + difference.value(ms / 1000);
expect(animator.get('x', clock + ms)).toBeCloseTo(added, 6);
apart = Math.max(apart, Math.abs(added - replaced.value(ms / 1000)));
}
expect(apart).toBeGreaterThan(1);
});
it('stop() before a late frame freezes where the screen shows', async () => {
const {animator, element} = await moving();
animator.animate({x: -100}, {spring: springs.emphasis});
clock += 200;
animator.stop();
expect(inlineX(element)).toBeCloseTo(shownAt(clock), 3);
expect(animator.get('x')).toBeCloseTo(shownAt(clock), 6);
});
it('a retarget that starts at its late frame finishes at the end of that curve', async () => {
const {animator} = await moving();
const handle = animator.animate({x: 250}, {spring: springs.quickChange});
let finished: boolean | null = null;
void handle.finished.then(value => {
finished = value;
});
// The block outlasts the call's own curve, so its timers come due in it.
const own = (handle.curve('x')?.duration ?? 0) * 1000;
clock += own + 50;
await vi.advanceTimersByTimeAsync(own + 50);
expect(finished).toBe(null);
await commitFrame(clock);
const left = Number(live('translate')[0].options.duration) - END_HOLD_MS;
await advance(left - 20);
expect(finished).toBe(null);
await advance(40);
expect(finished).toBe(true);
});
it('a played curve keeps its own clock when its frame comes late', async () => {
const {animator} = await moving();
const call = clock;
animator.play({
x: {duration: 0.3, at: t => 100 * t, velocity: () => 100},
});
clock += 200;
await commitFrame(clock);
expect(live('translate')[0].startTime).toBe(call);
});
it('a second property\u2019s retarget before the same late frame starts there too', async () => {
const {animator} = setup();
animator.animate(
{x: 300, y: 300},
{spring: springs.emphasis, velocity: {x: 800, y: 800}},
);
await advance(120);
animator.animate({x: -100}, {spring: springs.emphasis});
// Another task, 20 ms later, before the frame that commits both.
await Promise.resolve();
clock += 20;
animator.animate({y: -100}, {spring: springs.emphasis});
// That frame comes 45 ms after the first call it commits: late.
clock += 25;
await commitFrame(clock);
for (const property of ['x', 'y'] as const) {
expect(animator.get(property, clock)).toBeCloseTo(shownAt(clock), 6);
expect(animator.getVelocity(property, clock)).toBeCloseTo(
shownVelocityAt(clock),
4,
);
}
const curve = solveSpring(toSpring(springs.emphasis), {
from: shownAt(clock),
to: -100,
velocity: shownVelocityAt(clock),
});
expect(animator.get('y', clock + 90)).toBeCloseTo(curve.value(0.09), 6);
});
it('a late frame judges every animator from the first call it commits', async () => {
const now = () => clock;
const first = setup({now});
const second = setup({now});
for (const {animator} of [first, second]) {
animator.animate(
{x: 300},
{spring: springs.emphasis, velocity: {x: 800}},
);
}
await advance(120);
first.animator.animate({x: -100}, {spring: springs.emphasis});
await Promise.resolve();
clock += 20;
second.animator.animate({x: -100}, {spring: springs.emphasis});
clock += 25;
await commitFrame(clock);
expect(live('translate').map(animation => animation.startTime)).toEqual([
clock,
clock,
]);
for (const {animator} of [first, second]) {
expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);
expect(animator.getVelocity('x', clock)).toBeCloseTo(
shownVelocityAt(clock),
4,
);
}
});
it('retargets made in one callback on several animators share one clock', async () => {
const now = () => clock;
const first = setup({now});
const second = setup({now});
for (const {animator} of [first, second]) {
animator.animate(
{x: 300},
{spring: springs.emphasis, velocity: {x: 800}},
);
}
await advance(120);
const call = clock;
first.animator.animate({x: -100}, {spring: springs.emphasis});
// The callback goes on to a pager's next child.
clock += 3;
second.animator.animate({x: -100}, {spring: springs.emphasis});
clock += 13;
await commitFrame(clock);
expect(live('translate').map(animation => animation.startTime)).toEqual([
call,
call,
]);
for (const ms of [0, 50, 200]) {
expect(second.animator.get('x', clock + ms)).toBeCloseTo(
first.animator.get('x', clock + ms),
6,
);
}
});
it('a call in the next callback, after a microtask checkpoint, starts its own clock', async () => {
const now = () => clock;
const first = setup({now});
const second = setup({now});
for (const {animator} of [first, second]) {
animator.animate(
{x: 300},
{spring: springs.emphasis, velocity: {x: 800}},
);
}
await advance(120);
const call = clock;
first.animator.animate({x: -100}, {spring: springs.emphasis});
// The browser runs a microtask checkpoint after each callback.
await Promise.resolve();
clock += 3;
second.animator.animate({x: -100}, {spring: springs.emphasis});
clock += 13;
await commitFrame(clock);
expect(live('translate').map(animation => animation.startTime)).toEqual([
call,
call + 3,
]);
});
async function twoMoving() {
const now = () => clock;
const first = setup({now});
const second = setup({now});
for (const {animator} of [first, second]) {
animator.animate(
{x: 300},
{spring: springs.emphasis, velocity: {x: 800}},
);
}
await advance(120);
return [first, second] as const;
}
it('a call that a disposed animator left waiting does not make a later frame late', async () => {
const [first, second] = await twoMoving();
first.animator.animate({x: -100}, {spring: springs.emphasis});
first.animator.dispose();
await commitFrame(clock);
// A second later the other element moves again and retargets.
clock += 1000;
second.animator.animate(
{x: 300},
{spring: springs.emphasis, velocity: {x: 800}},
);
await advance(120);
const call = clock;
second.animator.animate({x: -100}, {spring: springs.emphasis});
clock += 10;
await commitFrame(clock);
const [made] = live('translate').filter(
animation => animation.element === second.element,
);
expect(made.startTime).toBe(call);
});
it('a call that a rebuild committed early does not make its frame late', async () => {
const [first, second] = await twoMoving();
first.animator.animate({x: -100}, {spring: springs.emphasis});
// A rebuild commits that call at once, before the frame.
first.animator.set({x: 0});
await Promise.resolve();
clock += 20;
const call = clock;
second.animator.animate({x: -100}, {spring: springs.emphasis});
clock += 25;
await commitFrame(clock);
const [made] = live('translate').filter(
animation => animation.element === second.element,
);
expect(made.startTime).toBe(call);
});
it('a retarget made in a frame callback of the page waits for the next frame, which starts it from the screen when it comes late', async () => {
const {animator} = await moving();
const [old] = live('translate');
// The page's own frame callback makes the call, in the frame it runs in.
frameQueue.push(() =>
animator.animate({x: -100}, {spring: springs.emphasis}),
);
await commitFrame(clock);
// That frame shows the old curve still.
expect(old.cancelled).toBe(false);
clock += 200;
await commitFrame(clock);
const [made] = live('translate');
expect(made.startTime).toBe(clock);
expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);
expect(animator.getVelocity('x', clock)).toBeCloseTo(
shownVelocityAt(clock),
4,
);
});
it('a retarget made in a frame callback of the page shows its new curve in the next frame, on its own clock', async () => {
const {animator} = await moving();
const [old] = live('translate');
const call = clock;
frameQueue.push(() =>
animator.animate({x: -100}, {spring: springs.emphasis}),
);
await commitFrame(clock);
// The frame that runs the callback still shows the old curve.
expect(live('translate')).toEqual([old]);
clock += 16;
await commitFrame(clock);
// The next frame shows the new curve, from the call's own time.
const [made] = live('translate');
expect(old.cancelled).toBe(true);
expect(made).not.toBe(old);
expect(made.startTime).toBe(call);
const curve = solveSpring(toSpring(springs.emphasis), {
from: shownAt(call),
to: -100,
velocity: shownVelocityAt(call),
});
// The keyframes hold the curve within a quarter of a pixel.
expect(
Math.abs(
sampleAt(made, 'translate', clock)[0] -
curve.value((clock - call) / 1000),
),
).toBeLessThan(0.26);
});
it('a late frame keeps a velocity that the call handed the spring, such as a release’s', async () => {
const {animator} = await moving();
animator.animate(
{x: -100},
{spring: springs.emphasis, velocity: {x: -900}},
);
clock += 200;
await commitFrame(clock);
expect(live('translate')[0].startTime).toBe(clock);
expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);
expect(animator.getVelocity('x', clock)).toBeCloseTo(-900, 4);
const curve = solveSpring(toSpring(springs.emphasis), {
from: shownAt(clock),
to: -100,
velocity: -900,
});
expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 6);
});
it('a late frame takes the velocity on screen when the call hands the curve’s own velocity', async () => {
const {animator} = await moving();
animator.animate(
{x: -100},
{spring: springs.emphasis, velocity: {x: animator.getVelocity('x')}},
);
clock += 200;
await commitFrame(clock);
expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);
expect(animator.getVelocity('x', clock)).toBeCloseTo(
shownVelocityAt(clock),
4,
);
});
it('a retarget whose frame source’s page is hidden while the element shows elsewhere keeps its own clock and finishes', async () => {
// The opener page's frames drive the animator; the element is in
// another visible document, as in a Picture-in-Picture window.
vi.stubGlobal('requestAnimationFrame', requestFrame);
const other = document.implementation.createHTMLDocument('elsewhere');
Object.defineProperty(other, 'visibilityState', {
configurable: true,
get: () => 'visible',
});
const element = other.createElement('div');
other.body.append(element);
stubMedia(false, false);
const animator = createMotionEngine(element, {now: () => clock});
animator.animate(
{x: 300},
{spring: springs.emphasis, velocity: {x: 800}},
);
await advance(120);
const showAgain = hidePage();
try {
const handle = animator.animate(
{x: 250},
{spring: springs.quickChange},
);
let finished: boolean | null = null;
void handle.finished.then(value => {
finished = value;
});
// No frame comes: the timers end the call.
const own = (handle.curve('x')?.duration ?? 0) * 1000;
clock += own + 50;
await vi.advanceTimersByTimeAsync(own + 50);
expect(finished).toBe(true);
expect(inlineX(element)).toBeCloseTo(250, 3);
} finally {
showAgain();
}
});
/** Hides the page, as a background tab is, until the call it returns. */
function hidePage() {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: () => 'hidden',
});
document.dispatchEvent(new Event('visibilitychange'));
return () => {
Reflect.deleteProperty(document, 'visibilityState');
document.dispatchEvent(new Event('visibilitychange'));
};
}
async function finishesOnItsClock(
animator: Animator,
element: HTMLElement,
hideFirst: boolean,
) {
const show = hideFirst ? hidePage() : null;
const handle = animator.animate({x: 250}, {spring: springs.quickChange});
const showAgain = show ?? hidePage();
try {
let finished: boolean | null = null;
void handle.finished.then(value => {
finished = value;
});
// No frame comes: the timers end the call.
const own = (handle.curve('x')?.duration ?? 0) * 1000;
clock += own + 50;
await vi.advanceTimersByTimeAsync(own + 50);
expect(finished).toBe(true);
expect(inlineX(element)).toBeCloseTo(250, 3);
} finally {
showAgain();
}
// The frame after the page shows again starts nothing. Animators of
// other tests hear the page change too, so only this one's count.
await commitFrame(clock);
expect(
live('translate').filter(animation => animation.element === element),
).toHaveLength(0);
}
it('on a hidden page, which draws no frames, a retarget keeps its own clock and finishes at its end', async () => {
const {animator, element} = await moving();
await finishesOnItsClock(animator, element, true);
});
it('a page that goes hidden before a retarget’s frame finishes it on its own clock', async () => {
const {animator, element} = await moving();
await finishesOnItsClock(animator, element, false);
});
});
it('velocity is continuous across a retarget (property sweep)', async () => {
for (const spring of [
springs.settle,
springs.quickChange,
springs.switchThumbMove,
springs.navigationPush,
]) {
const {animator} = setup();
animator.animate({x: 200}, {spring});
for (const step of [16, 50, 120]) {
await advance(step);
const before = animator.getVelocity('x', clock);
const value = animator.get('x', clock);
animator.animate({x: value > 100 ? 0 : 200}, {spring});
expect(animator.getVelocity('x', clock)).toBeCloseTo(before, 6);
expect(animator.get('x', clock)).toBeCloseTo(value, 9);
}
}
});
it('a value that keeps moving through a rebuild stays on its curve', async () => {
const {animator} = setup();
animator.animate({x: 300, y: 200}, {spring: springs.settle});
const yCurve = solveSpring(toSpring(springs.settle), {from: 0, to: 200});
await advance(100);
animator.animate({x: 0}, {spring: springs.settle});
const [animation] = live('translate');
for (let t = clock; t < clock + 400; t += 7) {
expect(
Math.abs(
sampleAt(animation, 'translate', t)[1] -
yCurve.value((t - 1000) / 1000),
),
).toBeLessThan(0.26);
expect(animator.get('y', t)).toBeCloseTo(
yCurve.value((t - 1000) / 1000),
9,
);
}
});
it('stop() freezes at the presentation value', async () => {
const {animator, element} = setup();
animator.animate({x: 300}, {spring: springs.settle});
await advance(80);
const value = animator.get('x');
animator.stop();
expect(live('translate')).toHaveLength(0);
expect(Number.parseFloat(element.style.translate)).toBeCloseTo(value, 3);
await advance(500);
expect(animator.get('x')).toBe(value);
expect(animator.getVelocity('x')).toBe(0);
});
it('a handle reads, retargets and stops its own properties', async () => {
const {animator} = setup();
const handle = animator.animate({x: 100}, {spring: springs.settle});
await advance(50);
expect(handle.value('x')).toBe(animator.get('x'));
expect(handle.velocity('x')).toBe(animator.getVelocity('x'));
const next = handle.retarget({x: 50});
await expect(handle.finished).resolves.toBe(false);
next.stop();
await expect(next.finished).resolves.toBe(false);
});
});
describe('set: direct manipulation', () => {
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) {
animator.set({x});
expect(element.style.translate).toBe(x === 0 ? '' : `${x}px 0px`);
}
expect(recorded).toHaveLength(0);
});
it('a drag on translate leaves a running scale alone', () => {
const {animator} = setup();
animator.animate({scale: 0.95}, {spring: springs.settle});
const scaleAnimation = live('scale')[0];
animator.set({x: 12});
animator.set({x: 20});
expect(scaleAnimation.cancelled).toBe(false);
expect(live('translate')).toHaveLength(0);
});
});
describe('finished', () => {
it('resolves true when the curve ends untouched', async () => {
const {animator} = setup();
const handle = animator.animate({x: 40}, {spring: springs.quickChange});
let result: boolean | undefined;
void handle.finished.then(value => {
result = value;
});
await advance(100);
expect(result).toBeUndefined();
await advance(5000);
expect(result).toBe(true);
});
it('resolves false as soon as a property is retargeted, set or stopped', async () => {
const {animator} = setup();
const a = animator.animate({x: 40}, {spring: springs.quickChange});
animator.animate({x: 80}, {spring: springs.quickChange});
await expect(a.finished).resolves.toBe(false);
const b = animator.animate({y: 40}, {spring: springs.quickChange});
animator.set({y: 3});
await expect(b.finished).resolves.toBe(false);
const c = animator.animate({rotate: 40}, {spring: springs.quickChange});
animator.stop(['rotate']);
await expect(c.finished).resolves.toBe(false);
});
it('waits while a sampler holds the animation past the curve\u2019s end', async () => {
const {animator} = setup();
const handle = animator.animate({x: 40}, {spring: springs.quickChange});
let result: boolean | undefined;
void handle.finished.then(value => {
result = value;
});
await advance(16);
// A harness pauses it (holdAnimations) and keeps it held well past the
// end of the curve on the wall clock: the motion has not ended.
const [animation] = live('translate');
animation.paused = true;
await advance(5000);
expect(result).toBeUndefined();
});
it('resolves true once a held animation resumes and reaches its end', async () => {
const {animator} = setup();
const handle = animator.animate({x: 40}, {spring: springs.quickChange});
let result: boolean | undefined;
void handle.finished.then(value => {
result = value;
});
await advance(16);
const [animation] = live('translate');
animation.paused = true;
await advance(5000);
animation.paused = false;
await advance(1000);
expect(result).toBe(true);
});
it('resolves on time for an animation nobody holds', async () => {
const {animator} = setup();
const handle = animator.animate({x: 40}, {spring: springs.quickChange});
let result: boolean | undefined;
void handle.finished.then(value => {
result = value;
});
const end = (handle.curve('x')?.duration ?? NaN) * 1000;
await advance(end - 50);
expect(result).toBeUndefined();
await advance(100);
expect(result).toBe(true);
});
it('dispose cancels and settles everything', async () => {
const {animator} = setup();
const handle = animator.animate(
{x: 40, opacity: 0},
{spring: springs.quickChange},
);
animator.dispose();
await expect(handle.finished).resolves.toBe(false);
expect(recorded.every(a => a.cancelled)).toBe(true);
expect(animator.element).toBeNull();
});
});
describe('Reduced Motion (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 call naming the opacity a running dip heads to keeps the dip', async () => {
const {animator} = reduced();
animator.animate({x: 100}, {spring: springs.navigationPush});
await commitFrame(clock);
const start = clock;
await advance(fade / 4);
// Mid fade out: a call names the opacity the dip returns to.
const handle = animator.animate({opacity: 1}, {spring: springs.settle});
// The dip goes on as it was: at its bottom when it was due, not opening
// a second dip from where it had got to.
expect(animator.get('opacity', start + fade / 2)).toBeCloseTo(0, 6);
await advance(fade / 4 + 1);
// Landed at the bottom; the fade back in ends when the dip was due to.
expect(animator.get('x')).toBe(100);
expect(animator.get('opacity', start + fade)).toBeCloseTo(1, 6);
await advance(fade + END_HOLD_MS + 1);
expect(animator.get('x')).toBe(100);
expect(animator.get('opacity')).toBe(1);
expect(await handle.finished).toBe(true);
});
it('a call naming the opacity a dip heads to, in the same task as the dip, hands the browser no second fade', async () => {
const {animator} = reduced();
animator.animate({x: 100}, {spring: springs.navigationPush});
animator.animate({opacity: 1}, {spring: springs.settle});
await commitFrame(clock);
const fades = recorded.filter(animation =>
animation.keyframes.some(keyframe => 'opacity' in keyframe),
);
expect(fades).toHaveLength(1);
expect(fades[0].cancelled).toBe(false);
});
it('a release played as a dip, then its state layer naming the opacity the dip returns to, fades once', async () => {
// A swipe row's release: the move's layer plays the travel, then the
// state layer lands its opacity on the same element in the same task.
const {animator} = reduced();
const move = animator.play(
{x: {duration: 0.3, at: t => (100 * t) / 0.3, velocity: () => 100 / 0.3}},
{touchRelease: true},
);
const state = animator.animate(
{opacity: 1},
{spring: springs.settle},
{touchRelease: true},
);
await commitFrame(clock);
const fades = recorded.filter(animation =>
animation.keyframes.some(keyframe => 'opacity' in keyframe),
);
expect(fades).toHaveLength(1);
await advance(fade + END_HOLD_MS + 1);
expect(animator.get('x')).toBe(100);
expect(animator.get('opacity')).toBe(1);
expect(await move.finished).toBe(true);
expect(await state.finished).toBe(true);
});
it('an entrance after an outside finish starts from what is on screen', async () => {
const {animator} = reduced();
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');
});
it('presented: a call that moves and fades in from transparent lands its travel', async () => {
// A control part at its rest offset, transparent, presented in one task
// with its own animator (SearchField's close button).
const {animator, element} = reduced();
animator.set({x: 44, opacity: 0});
animator.animate(
{x: 0, opacity: 1},
{spring: springs.settle},
{start: 'presented'},
);
await commitFrame(clock);
await commitFrame(clock);
await advance(fade + 16);
expect(animator.get('x')).toBe(0);
expect(parse(element.style.translate)[0] || 0).toBe(0);
expect(animator.get('opacity', clock)).toBeCloseTo(1, 9);
});
it('fades for 200 ms at most', () => {
expect(fade).toBeGreaterThan(0);
expect(fade).toBeLessThanOrEqual(200);
});
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'},
);
animator.play({
rotate: {duration: 0.3, at: t => 30 * t, velocity: () => 30},
});
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 it
expect(animator.get('opacity', 1000)).toBeCloseTo(0.6, 9);
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});
animator.animate({opacity: 1}, {spring: springs.navigationPush});
await advance(fade / 3);
const start = clock;
expect(animator.get('opacity')).toBeGreaterThan(0.1);
animator.animate({x: 100}, {spring: springs.navigationPush});
// Still where it was while it shows; it moves at the bottom of the dip.
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 () => {
const {animator} = reduced();
animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade / 4);
const start = clock;
// x still waits for the first dip's bottom; y starts a new dip now.
animator.animate({y: 50}, {spring: springs.navigationPush});
// 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 () => {
const {animator} = reduced();
animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade / 2 - 5);
expect(animator.get('opacity')).toBeLessThan(0.1);
animator.stop();
expect(animator.get('opacity')).toBe(1);
});
it("a stop during a dip on the stylesheet's opacity hands it back", async () => {
const {animator, element} = reduced();
stylesheet = {opacity: '0.6'};
animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade / 4);
animator.stop();
expect(element.style.opacity).toBe('');
expect(animator.get('opacity')).toBe(1);
});
it('a call that does not own opacity keeps a running borrowed dip handing it back', async () => {
// One that moves nothing.
const still = reduced();
stylesheet = {opacity: '0.6'};
still.animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade / 4);
still.animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade + END_HOLD_MS + 1);
expect(still.element.style.opacity).toBe('');
// One that springs after Reduce Motion turned off mid-dip.
const changed = setup({reduced: true, coarse: true});
changed.animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade / 4);
stubMedia(false, true);
changed.animator.animate({y: 20}, {spring: springs.navigationPush});
await advance(2000);
expect(changed.element.style.opacity).toBe('');
});
it('a borrowed dip that ends while detached hands the opacity back on the next attach', async () => {
const {animator, element} = reduced();
stylesheet = {opacity: '0.6'};
animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(25);
animator.attach(null);
await advance(fade + END_HOLD_MS + 1);
animator.attach(element);
expect(element.style.opacity).toBe('');
expect(animator.get('opacity')).toBe(1);
});
it('an unmount or dispose during a borrowed dip hands the opacity back to that element', async () => {
for (const end of ['detach', 'dispose'] as const) {
const {animator, element} = reduced();
stylesheet = {opacity: '0.6'};
animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(25);
if (end === 'detach') {
animator.attach(null);
} else {
animator.dispose();
}
expect(element.style.opacity).toBe('');
}
});
it('a new element taking over mid-dip keeps the dip, so the move lands while invisible', async () => {
const {animator, element} = reduced();
stylesheet = {opacity: '0.6'};
animator.animate({x: 240}, {spring: springs.navigationPush});
await advance(25);
const next = document.createElement('div');
document.body.append(next);
animator.attach(next);
// The outgoing element follows its stylesheet again.
expect(element.style.opacity).toBe('');
const start = clock - 25;
for (let t = start; t <= start + fade; t += 2) {
if (animator.get('x', t) !== 0) {
expect(animator.get('opacity', t)).toBeCloseTo(0, 6);
break;
}
}
await advance(fade + END_HOLD_MS + 1);
expect(next.style.opacity).toBe('');
next.remove();
});
it('a node detached mid-dip and attached again in a later task shows the move landed and visible', async () => {
const {animator, element} = reduced();
// The call owns its opacity: its dip writes opacity inline, the value on
// screen as the fade starts (its end is written when the fade retires),
// while the model is already partway down.
animator.animate({x: 240, opacity: 1}, {spring: springs.navigationPush});
await advance(25);
expect(element.style.opacity).not.toBe('');
expect(animator.get('opacity')).toBeLessThan(1);
animator.attach(null);
await advance(100);
animator.attach(element);
expect(animator.get('x')).toBe(240);
expect(animator.get('opacity')).toBe(1);
expect(element.style.opacity).not.toBe('0');
expect(Number(element.style.opacity || '1')).toBe(1);
});
it('a node detached mid-dip from a dimmed opacity shows the move landed and visible when attached again', async () => {
// With the presented start, a curve writes its starting value inline: a
// dip from a dimmed opacity leaves that low value on the node while the
// move still waits to land.
const {animator, element} = reduced();
animator.set({opacity: 0.3});
animator.animate({x: 240, opacity: 1}, {spring: springs.navigationPush});
await advance(25);
expect(Number(element.style.opacity)).toBeLessThan(1);
expect(animator.get('x')).toBe(0);
animator.attach(null);
await advance(100);
animator.attach(element);
expect(animator.get('x')).toBe(240);
expect(animator.get('opacity')).toBe(1);
expect(Number(element.style.opacity || '1')).toBe(1);
});
it('a node detached mid-dip while another axis moves is left with no animation or promotion', async () => {
const {animator, element} = reduced();
animator.set({x: 0, y: 0});
// y coasts (momentum keeps its motion) while x waits in a dip.
const start = clock;
animator.decay(coast(animator, {y: 800}, {at: start}), {at: start});
animator.animate({x: 240}, {spring: springs.navigationPush});
await advance(25);
animator.attach(null);
await advance(1);
expect(
recorded.filter(
animation =>
animation.element === element &&
!animation.cancelled &&
animation.playState !== 'finished',
),
).toEqual([]);
expect(element.style.willChange).toBe('');
});
it('lands a waiting move on the latest node detached in the task, after a replacement too', async () => {
const {animator} = reduced();
animator.animate({x: 240, opacity: 1}, {spring: springs.navigationPush});
await advance(25);
const next = document.createElement('div');
document.body.append(next);
animator.attach(null);
animator.attach(next);
animator.attach(null);
await advance(100);
// The node attached last, then detached, is the one left visible.
expect(Number(next.style.opacity || '1')).toBe(1);
next.remove();
});
it('a dispose right after a detach lands the waiting move on that node', async () => {
const {animator, element} = reduced();
animator.animate({x: 240, opacity: 1}, {spring: springs.navigationPush});
await advance(25);
animator.attach(null);
animator.dispose();
await advance(100);
expect(Number(element.style.opacity || '1')).toBe(1);
expect(element.style.willChange).toBe('');
});
it('an identity held over a differing stylesheet follows a node replacement', () => {
const {animator, element} = reduced();
stylesheet = {opacity: '0'};
animator.set({opacity: 1});
expect(element.style.opacity).toBe('1');
animator.attach(null);
const next = document.createElement('div');
document.body.append(next);
animator.attach(next);
expect(next.style.opacity).toBe('1');
expect(animator.get('opacity')).toBe(1);
next.remove();
});
it('a running dip survives any re-attach, so the move never passes in view', async () => {
const halfway = async (
animator: ReturnType<typeof createMotionEngine>,
start: number,
): 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;
};
// Detached and re-attached to the same element, no stylesheet opacity.
const same = reduced();
same.animator.animate({x: 240}, {spring: springs.navigationPush});
const start = clock;
await advance(25);
same.animator.attach(null);
same.animator.attach(same.element);
expect(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});
const start2 = clock;
await advance(25);
const next = document.createElement('div');
document.body.append(next);
other.animator.attach(next);
expect(await halfway(other.animator, start2)).toBeCloseTo(0, 6);
await advance(fade + END_HOLD_MS + 1);
expect(next.style.opacity).toBe('');
next.remove();
});
it('an opacity the animator wrote is owned: a dip returns to it, never to a hiding stylesheet', async () => {
const {animator, element} = reduced();
stylesheet = {opacity: '0'};
animator.set({opacity: 1});
expect(element.style.opacity).toBe('1');
animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade + END_HOLD_MS + 1);
expect(element.style.opacity).toBe('1');
});
it('borrows nothing from a hidden element, so a later move still dips once it shows', async () => {
const {animator} = reduced();
stylesheet = {opacity: '0'};
animator.animate({x: 100}, {spring: springs.navigationPush});
// Invisible: the move lands at once, with no dip.
expect(animator.get('x')).toBe(100);
await advance(fade + END_HOLD_MS + 1);
stylesheet = {opacity: '1'};
animator.animate({x: 200}, {spring: springs.navigationPush});
const start = clock;
for (let t = start; t <= start + fade; t += 2) {
if (animator.get('x', t) !== 100) {
expect(animator.get('opacity', t)).toBeCloseTo(0, 6);
break;
}
}
});
it("a stop that finishes a dip's fade lands the move with it, never later in view", async () => {
const {animator} = reduced();
animator.animate({x: 100}, {spring: springs.navigationPush});
await advance(fade / 4);
animator.stop(['opacity']);
expect(animator.get('x')).toBe(100);
expect(animator.get('opacity')).toBe(1);
});
it('a release past an edge springs back as a cross-fade, not momentum (DR2)', async () => {
const {animator} = reduced();
animator.set({x: -80});
const start = clock;
animator.decay(
coast(animator, {x: 0}, {bounds: {x: {min: 0, max: 100}}, at: start}),
{at: start},
);
// 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(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 () => {
const {animator} = reduced();
animator.set({x: -80, y: 0});
const start = clock;
const handle = animator.decay(
coast(
animator,
{x: 0, y: 500},
{bounds: {x: {min: 0, max: 100}}, at: start},
),
{at: start},
);
expect(handle.properties).toEqual(expect.arrayContaining(['x', 'y']));
await advance(fade / 4);
handle.stop();
// 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);
expect(animator.get('x')).toBe(-80);
expect(animator.get('y')).toBe(stopped.y);
});
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 landing waits while a sampler pauses its fade after the browser started it, and lands once the fade resumes', async () => {
const {animator} = reduced();
const handle = animator.animate({x: 100}, {spring: springs.navigationPush});
let settled: boolean | undefined;
void handle.finished.then(value => {
settled = value;
});
await commitFrame(clock);
await advance(fade / 4);
// A harness holds the fade mid-way, after the browser started it.
const [fadeOut] = live('opacity');
fadeOut.paused = true;
await advance(5000);
// The travel waits for the fade, which still shows the element.
expect(animator.get('x')).toBe(0);
expect(settled).toBeUndefined();
fadeOut.paused = false;
for (let step = 0; step < 16; step++) {
await advance(fade / 4);
}
expect(animator.get('x')).toBe(100);
expect(animator.get('opacity')).toBe(1);
expect(settled).toBe(true);
});
it('a landing waits while a resumed fade has no start yet, and lands once the fade plays to its end', async () => {
const {animator} = reduced();
const handle = animator.animate({x: 100}, {spring: springs.navigationPush});
let settled: boolean | undefined;
void handle.finished.then(value => {
settled = value;
});
await commitFrame(clock);
await advance(fade / 4);
const [fadeOut] = live('opacity');
fadeOut.paused = true;
// The fade shows the frame it was paused at, a quarter of the way in.
Object.defineProperty(fadeOut, 'currentTime', {
configurable: true,
get: () => fade / 4,
});
for (let step = 0; step < 300; step++) {
await advance(1);
}
// play(): the fade waits for the browser's next frame, with no start.
fadeOut.paused = false;
fadeOut.startTime = null;
fadeOut.startDelayFrames = 1_000;
for (let step = 0; step < 300; step++) {
await advance(1);
}
expect(animator.get('x')).toBe(0);
expect(settled).toBeUndefined();
// The browser starts it, and it plays to its end.
fadeOut.startDelayFrames = 0;
Reflect.deleteProperty(fadeOut, 'currentTime');
for (let step = 0; step < 16; step++) {
await advance(fade / 4);
}
expect(animator.get('x')).toBe(100);
expect(settled).toBe(true);
});
it('an exit whose fade a sampler pauses after its start settles only once the fade resumes', async () => {
const {animator} = reduced();
const handle = animator.animate(
{x: 100, opacity: 0},
{spring: springs.navigationPush},
);
let settled: boolean | undefined;
void handle.finished.then(value => {
settled = value;
});
await commitFrame(clock);
await advance(fade / 4);
const [fadeOut] = live('opacity');
fadeOut.paused = true;
await advance(5000);
// A component that removes the element when the call settles keeps it
// while the fade is held on screen.
expect(settled).toBeUndefined();
fadeOut.paused = false;
for (let step = 0; step < 16; step++) {
await advance(fade / 4);
}
expect(settled).toBe(true);
});
it('a landing later than the whole fade back in shows the element at once and settles then', async () => {
// A hold released long after the dip was due: the landing\u2019s timer runs
// more than the whole fade back in late, so the element appears at once
// where it landed. No fade is left for the browser to start a frame
// later, so the call\u2019s finished never reports an element still at 0.
for (const sheet of ['own', 'stylesheet'] as const) {
const {animator, element} = reduced();
stylesheet = sheet === 'stylesheet' ? {opacity: '0.6'} : {};
const handle = animator.animate(
{x: 100},
{spring: springs.navigationPush},
);
for (const animation of recorded) {
animation.paused = true;
}
await commitFrame(clock);
clock += fade * 2;
for (const animation of recorded) {
animation.finish();
}
const before = recorded.length;
let settled: boolean | undefined;
void handle.finished.then(value => {
settled = value;
});
// The next frame finds the hold finished: the landing is long due.
await commitFrame(clock);
await vi.advanceTimersByTimeAsync(0);
expect(animator.get('x')).toBe(100);
expect(
recorded
.slice(before)
.filter(
animation =>
!animation.cancelled &&
'opacity' in (animation.keyframes[0] ?? {}),
),
).toHaveLength(0);
expect(settled).toBe(true);
if (sheet === 'stylesheet') {
// Handed back to the stylesheet at once.
expect(element.style.opacity).toBe('');
} else {
expect(animator.get('opacity')).toBe(1);
}
animator.dispose();
recorded = [];
}
});
it('a move held before its first frame and finished from outside still lands when its retire runs before the next frame', async () => {
// A sampler pauses the call's animations in its own task and finishes
// them later. A loaded page can run the retire timer, which cancels the
// finished fade, before the frame that would read the call's start: the
// call must not be left waiting for a start that no animation can give.
const {animator} = reduced();
const handle = animator.animate({x: 100}, {spring: springs.navigationPush});
for (const animation of recorded) {
animation.paused = true;
}
await commitFrame(clock);
clock += 30;
await commitFrame(clock);
for (const animation of recorded) {
animation.finish();
}
let settled: boolean | undefined;
void handle.finished.then(value => {
settled = value;
});
// The retire timer first, with no frame in between: it cancels the
// finished fade out.
clock += fade * 2;
await vi.advanceTimersByTimeAsync(fade * 2);
expect(
recorded.filter(animation => animation.finished && !animation.cancelled),
).toEqual([]);
// 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);
expect(settled).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});
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 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});
await commitFrame(clock);
await advance(20);
animator.attach(null);
// The unmount is deferred to a microtask: read once it has run.
await Promise.resolve();
expect(element.style.willChange).toBe('');
expect(vi.getTimerCount()).toBe(0);
});
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 pseudo-element's dip borrows its own opacity and hands it back without touching the host", async () => {
for (const role of [undefined, 'exit'] as const) {
const {animator, element} = setup({
reduced: true,
coarse: true,
pseudoElement: '::before',
});
element.style.opacity = '0.5'; // the host's own, untouched
pseudoStylesheet = {opacity: '0.3'};
animator.animate(
{x: 100},
{spring: springs.navigationPush},
role == null ? {} : {crossfadeAs: role},
);
await commitFrame(clock);
const [fadeLayer] = live('opacity');
const values = fadeLayer.keyframes.map(k => Number(k.opacity));
expect(Math.max(...values)).toBeCloseTo(0.3, 9);
await advance(fade * 2 + END_HOLD_MS + 1);
expect(animator.get('x')).toBe(100);
// The pseudo-element's stylesheet owns its opacity again; the host
// keeps its own.
expect(live('opacity')).toEqual([]);
expect(element.style.opacity).toBe('0.5');
}
});
it("a pseudo-element's identity hold follows a node replacement", () => {
const {animator, element} = setup({pseudoElement: '::backdrop'});
pseudoStylesheet = {opacity: '0'};
animator.set({opacity: 1});
animator.attach(null);
const next = document.createElement('div');
document.body.append(next);
animator.attach(next);
const held = live('opacity').filter(
animation => animation.element === next,
);
expect(held).toHaveLength(1);
expect(Number(held[0].keyframes.at(-1)!.opacity)).toBe(1);
expect(live('opacity').some(a => a.element === element)).toBe(false);
next.remove();
});
it('a pseudo-element shown over a hiding stylesheet keeps its own opacity through a move', async () => {
for (const role of [undefined, 'entrance'] as const) {
const {animator} = setup({
reduced: true,
coarse: true,
pseudoElement: '::backdrop',
});
pseudoStylesheet = {opacity: '0'};
animator.set({opacity: 1});
animator.animate(
{x: 100},
{spring: springs.navigationPush},
role == null ? {} : {crossfadeAs: role},
);
await commitFrame(clock);
for (let step = 0; step < 8; step++) {
await advance(fade / 4);
}
expect(animator.get('x')).toBe(100);
expect(animator.get('opacity')).toBe(1);
const [held] = live('opacity');
expect(Number(held.keyframes.at(-1)?.opacity)).toBe(1);
}
});
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(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);
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;
});
await advance(fade);
expect(animator.get('opacity')).toBe(1);
expect(finished).toBe(true);
});
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 it
expect(animator.get('y')).toBe(0);
expect(live('translate')).toHaveLength(0);
expect(animator.get('opacity', 1000 + fade / 2)).toBeCloseTo(ease(0.5), 9);
expect(Number(live('opacity')[0].options.duration)).toBeCloseTo(
fade + END_HOLD_MS,
6,
);
});
it('an exit fades out in place, then lands', async () => {
const {animator} = reduced();
animator.animate({y: 400, opacity: 0}, {spring: springs.sheetDismiss});
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 change on a spring becomes the timed fade, never the spring', async () => {
const {animator} = reduced();
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,
);
});
it('a played curve, opacity alone included, becomes the timed fade', async () => {
const {animator} = reduced();
// A long dim that would follow a sheet's spring.
animator.play({
opacity: {duration: 0.6, at: t => 1 - t / 0.6, velocity: () => -1 / 0.6},
});
await commitFrame(clock); // the browser starts it
expect(animator.get('opacity', 1000 + fade)).toBe(0);
expect(Number(live('opacity')[0].options.duration)).toBeCloseTo(
fade + END_HOLD_MS,
6,
);
});
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);
});
it('a later call before the landing takes the property over', async () => {
const {animator} = reduced();
animator.animate({x: 100}, {spring: springs.navigationPush});
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});
animator.play({
y: {duration: 0.4, at: t => 100 * t, velocity: () => 100},
});
expect(recorded).toHaveLength(0);
expect(animator.get('x')).toBe(100);
expect(animator.get('opacity')).toBe(0.5);
expect(animator.get('y')).toBeCloseTo(40, 9);
});
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 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('play: any closed-form curve', () => {
// A press that keeps deepening: the scale's target falls at 0.16 per
// second and the presentation follows it on a spring.
const pressSpring = toSpring(springs.contextMenuLift);
const press = solveSpringTowardRamp(pressSpring, {
from: 1,
target: 1,
slope: -0.16,
});
const pressCurve = {
duration: 0.266,
at: (t: number) => press.value(t),
velocity: (t: number) => press.velocity(t),
};
it('bakes the curve into keyframes and reads it back', async () => {
const {animator, element} = setup();
animator.play({scale: pressCurve});
const [animation] = live('scale');
await commitFrame(1000);
expect(animation.startTime).toBe(1000);
expect(Number(animation.options.duration)).toBeCloseTo(
266 + END_HOLD_MS,
6,
);
// Up to the end: from then on the value rests where the curve ended.
for (let t = 0; t < 266; t += 0.5) {
const [sx, sy] = sampleAt(animation, 'scale', 1000 + t);
expect(Math.abs(sx - press.value(t / 1000))).toBeLessThan(0.001);
expect(sy).toBe(sx);
expect(animator.get('scale', 1000 + t)).toBeCloseTo(
press.value(t / 1000),
12,
);
expect(animator.getVelocity('scaleY', 1000 + t)).toBeCloseTo(
press.velocity(t / 1000),
12,
);
}
const end = press.value(0.266);
expect(animator.get('scale', 1266)).toBeCloseTo(end, 12);
expect(animator.getVelocity('scale', 1266)).toBe(0);
// Retired, the end is inline.
await advance(400);
for (const axis of parse(element.style.scale)) {
expect(axis).toBeCloseTo(end, 4);
}
});
it('calls in one task that play the same curve share one bake', async () => {
stubMedia(false, false);
let reads = 0;
const curve = {
duration: 0.4,
at: (t: number) => {
reads += 1;
return 300 * t * t;
},
velocity: (t: number) => 600 * t,
};
const animators = [0, 1, 2].map(() =>
createMotionEngine(document.createElement('div'), {
now: () => clock,
requestFrame,
}),
);
animators[0].play({x: curve});
const firstReads = reads;
animators[1].play({x: curve});
animators[2].play({x: curve});
const [first, second, third] = live('translate');
// The later calls play the first call's keyframes: the curve is sampled
// once. Each later call reads it only for its own start and end.
expect(second.keyframes).toBe(first.keyframes);
expect(third.keyframes).toBe(first.keyframes);
expect(firstReads).toBeGreaterThan(40);
expect((reads - firstReads) / 2).toBeLessThanOrEqual(4);
// A call in a later task bakes again.
await Promise.resolve();
const later = createMotionEngine(document.createElement('div'), {
now: () => clock,
requestFrame,
});
later.play({x: curve});
expect(live('translate').at(-1)?.keyframes).not.toBe(first.keyframes);
});
it('a call whose other values differ keeps its own keyframes, at the shared times', () => {
stubMedia(false, false);
let reads = 0;
const curve = {
duration: 0.4,
at: (t: number) => {
reads += 1;
return 300 * t * t;
},
velocity: (t: number) => 600 * t,
};
const plain = createMotionEngine(document.createElement('div'), {
now: () => clock,
requestFrame,
});
const lifted = createMotionEngine(document.createElement('div'), {
now: () => clock,
requestFrame,
});
lifted.set({y: 5});
plain.play({x: curve});
const firstReads = reads;
lifted.play({x: curve});
const [own, other] = live('translate');
expect(other.keyframes).not.toBe(own.keyframes);
expect(other.keyframes.map(frame => frame.offset)).toEqual(
own.keyframes.map(frame => frame.offset),
);
for (const [i, frame] of other.keyframes.entries()) {
const [x, y] = parse(frame.translate);
expect(x).toBe(parse(own.keyframes[i].translate)[0]);
expect(y).toBe(5);
}
// Its values are read once each, at the times the first call sampled.
expect(reads - firstReads).toBeLessThan(firstReads);
});
it('a curve played and rebased in one task bakes the shifted keyframes', () => {
const {animator} = setup();
const curve = {
duration: 0.4,
at: (t: number) => 120 * t,
velocity: () => 120,
};
animator.play({x: curve});
animator.rebase({x: -16});
// The curve plays 0 to 48. Shifted by -16, it plays -16 to 32.
const [animation] = live('translate');
const xs = animation.keyframes.map(frame => parse(frame.translate)[0]);
expect(xs[0]).toBeCloseTo(-16, 6);
expect(xs.at(-1)).toBeCloseTo(32, 6);
});
it('finishes true at its end, false when interrupted', async () => {
const {animator} = setup();
const done = animator.play({
x: {duration: 0.2, at: t => 100 * t, velocity: () => 100},
});
await advance(250);
await expect(done.finished).resolves.toBe(true);
const cut = animator.play({
x: {duration: 0.2, at: t => 20 + 100 * t, velocity: () => 100},
});
await advance(50);
animator.set({x: 0});
await expect(cut.finished).resolves.toBe(false);
});
it('a later animate starts from the played value and velocity', async () => {
const {animator} = setup();
animator.play({scale: pressCurve});
await advance(120);
const value = animator.get('scale');
const velocity = animator.getVelocity('scale');
expect(value).toBeCloseTo(press.value(0.12), 12);
animator.animate({scale: 1.06}, {spring: springs.contextMenuLift});
expect(animator.get('scale')).toBeCloseTo(value, 9);
expect(animator.getVelocity('scale')).toBeCloseTo(velocity, 9);
});
it('a zero-length curve puts the value in place', () => {
const {animator, element} = setup();
animator.play({opacity: {duration: 0, at: () => 0.4, velocity: () => 0}});
expect(live('opacity')).toHaveLength(0);
expect(animator.get('opacity')).toBe(0.4);
expect(element.style.opacity).toBe('0.4');
});
it('under Reduced Motion a played travel cross-fades to its end', async () => {
const reduced = setup({
reduced: true,
coarse: true,
});
reduced.animator.play({
x: {duration: 0.3, at: t => 300 * t, velocity: () => 300},
});
await commitFrame(clock); // the browser starts it
const [opacity] = live('opacity');
expect(opacity).toBeDefined();
expect(live('translate')).toHaveLength(0);
await advance(timing.reducedMotionCrossFadeMs);
expect(reduced.animator.get('x')).toBeCloseTo(90, 9);
});
it('its handle retargets only with a spring', () => {
const {animator} = setup();
const handle = animator.play({
x: {duration: 0.3, at: t => 300 * t, velocity: () => 300},
});
expect(() => handle.retarget({x: 0})).toThrow(/spring/);
handle.retarget({x: 0}, {spring: springs.settle});
expect(animator.getVelocity('x')).toBeCloseTo(300, 9);
});
it('lets an explicit axis win over scale, in either order', () => {
const {animator} = setup();
const flat = (value: number) => ({
duration: 0,
at: () => value,
velocity: () => 0,
});
animator.play({scaleY: flat(0.5), scale: flat(2)});
expect(animator.get('scaleX')).toBe(2);
expect(animator.get('scaleY')).toBe(0.5);
animator.play({scale: flat(3), scaleX: flat(0.25)});
expect(animator.get('scaleX')).toBe(0.25);
expect(animator.get('scaleY')).toBe(3);
});
it('rejects a curve without a finite duration', () => {
const {animator} = setup();
expect(() =>
animator.play({
x: {duration: Number.POSITIVE_INFINITY, at: () => 0, velocity: () => 0},
}),
).toThrow(RangeError);
});
});
describe('decay: momentum curves (a coast)', () => {
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 it
const glide = solveDecay({from: 0, velocity: -2400});
for (const t of [0, 16, 100, 400, 1200]) {
expect(animator.get('y', 1000 + t)).toBeCloseTo(glide.value(t / 1000), 9);
}
const [animation] = live('translate');
for (let t = 0; t < 1500; t += 3) {
expect(
Math.abs(
sampleAt(animation, 'translate', 1000 + t)[1] - glide.value(t / 1000),
),
).toBeLessThan(0.26);
}
expect(animator.get('y', 1e7)).toBeCloseTo(glide.rest, 9);
});
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 it
const glide = solveDecay({from: -100, velocity: 3000});
const contact = 1000 + (glide.timeToReach(0) as number) * 1000;
expect(animator.get('y', contact)).toBeCloseTo(0, 6);
expect(animator.getVelocity('y', contact - 1e-6)).toBeCloseTo(
animator.getVelocity('y', contact + 1e-6),
2,
);
// It overshoots past the edge, then comes back to it.
expect(animator.get('y', contact + 60)).toBeGreaterThan(0);
expect(animator.get('y', 1e7)).toBe(0);
});
it('a release past an edge springs straight back with the release velocity', 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 it
expect(animator.getVelocity('x')).toBeCloseTo(400, 6);
const curve = solveSpring(toSpring(scroll.bounce), {
from: 60,
to: 0,
velocity: 400,
});
expect(animator.get('x', 1100)).toBeCloseTo(curve.value(0.1), 9);
});
it('a coast continues a running spring from its presentation value', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
await commitFrame(clock); // the browser starts it
clock += 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', async () => {
const {animator} = setup();
const linear = {
duration: 0.5,
at: (t: number) => 200 * t,
velocity: () => 200,
};
animator.decay({
x: linear,
y: {duration: 0, at: () => 5, velocity: () => 0},
});
await commitFrame(clock); // the browser starts it
expect(animator.get('x', 1250)).toBeCloseTo(50, 9);
expect(animator.get('x', 1e7)).toBeCloseTo(100, 9);
expect(animator.get('y')).toBe(5);
});
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 it
expect(animator.getVelocity('x', 1016)).toBeGreaterThan(900);
// No cross-fade: the coast moves the element and leaves opacity alone.
expect(live('translate')).toHaveLength(1);
expect(live('opacity')).toHaveLength(0);
expect(element.style.opacity).toBe('');
});
it('ships the Reduce Motion fade, not the rest of the timing table', () => {
// Bundled for a page, the animator 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(['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.map(file => file.text).join("\\n"));',
].join('\n');
const bundle = execFileSync(
process.execPath,
['--input-type=module', '-e', script],
{cwd: path.resolve(__dirname, '../../../..'), encoding: 'utf8'},
);
expect(bundle).toContain('durationMs');
for (const row of [
'stateChangeMs',
'highlightOutMs',
'navigationBarHideShowMs',
]) {
expect(bundle).not.toContain(row);
}
});
it('imports neither the coast math nor the scroll table', () => {
// Only a surface that coasts pays for them (coast.ts).
const source = fs.readFileSync(
path.resolve(__dirname, 'animator.ts'),
'utf8',
);
expect(source).not.toMatch(/from '\.\/decay'/);
expect(source).not.toMatch(/from '\.\/uikit\/scroll'/);
});
});
describe('pseudoElement: a dialog\u2019s ::backdrop', () => {
it('targets the pseudo-element, writes no inline style and holds the end state', async () => {
const {animator, element} = setup({pseudoElement: '::backdrop'});
animator.set({opacity: 0});
const [held] = live('opacity');
expect(held.options).toMatchObject({
fill: 'both',
pseudoElement: '::backdrop',
});
expect(held.keyframes.map(k => k.opacity)).toEqual(['0', '0']);
expect(element.style.opacity).toBe('');
animator.animate({opacity: 1}, {spring: springs.alertPresent});
// The new animation exists before the hold goes: no frame in between.
expect(held.cancelled).toBe(true);
const [fade] = live('opacity');
expect(fade.options).toMatchObject({
fill: 'both',
pseudoElement: '::backdrop',
});
expect(fade.keyframes[fade.keyframes.length - 1].opacity).toBe('1');
expect(element.style.opacity).toBe('');
await advance(Number(fade.options.duration) + 1000);
// Past the curve's end, a static animation holds the end value.
expect(fade.cancelled).toBe(true);
const [rest] = live('opacity');
expect(rest.options).toMatchObject({
fill: 'both',
pseudoElement: '::backdrop',
});
expect(rest.keyframes.map(k => k.opacity)).toEqual(['1', '1']);
expect(animator.get('opacity')).toBe(1);
});
it('an exit holds 0 until the next animation replaces it', async () => {
const {animator} = setup({
pseudoElement: '::backdrop',
initial: {opacity: 1},
});
animator.animate({opacity: 0}, {spring: springs.alertDismiss});
const [fade] = live('opacity');
await advance(Number(fade.options.duration) + 1000);
const [rest] = live('opacity');
expect(rest.keyframes.map(k => k.opacity)).toEqual(['0', '0']);
animator.animate({opacity: 1}, {spring: springs.alertPresent});
expect(rest.cancelled).toBe(true);
expect(live('opacity')).toHaveLength(1);
});
});
describe('base: what a pseudo-element\u2019s stylesheet shows at rest', () => {
const clear = {
pseudoElement: '::after',
initial: {opacity: 0},
base: {opacity: 0},
} as const;
it('a value at its base leaves no holding animation, and any other value still holds', async () => {
const {animator} = setup(clear);
animator.set({opacity: 0});
expect(live('opacity')).toHaveLength(0);
animator.set({opacity: 0.5});
const [held] = live('opacity');
expect(held.keyframes.map(k => k.opacity)).toEqual(['0.5', '0.5']);
animator.animate({opacity: 0}, {spring: springs.alertDismiss});
expect(held.cancelled).toBe(true);
const [fade] = live('opacity');
await advance(Number(fade.options.duration) + 1000);
// Past the curve's end the stylesheet shows the base: nothing holds it.
expect(fade.cancelled).toBe(true);
expect(live('opacity')).toHaveLength(0);
expect(animator.get('opacity')).toBe(0);
animator.animate({opacity: 1}, {spring: springs.alertPresent});
const [rise] = live('opacity');
await advance(Number(rise.options.duration) + 1000);
// An end other than the base is held, as with no base.
const [rest] = live('opacity');
expect(rest.keyframes.map(k => k.opacity)).toEqual(['1', '1']);
});
it('a curve that settles to within the sampling tolerance of its base leaves no hold', async () => {
const {animator} = setup(clear);
// Seconds, as a curve's time is.
const settlingTo = (end: number) => ({
duration: 0.3,
at: (t: number) => 1 + (end - 1) * Math.min(1, t / 0.3),
velocity: () => 0,
});
animator.play({opacity: settlingTo(0.001)});
await advance(1300);
expect(live('opacity')).toHaveLength(0);
animator.play({opacity: settlingTo(0.01)});
await advance(1300);
const [held] = live('opacity');
expect(held.keyframes.map(k => k.opacity)).toEqual(['0.01', '0.01']);
});
it('a node replaced at rest holds nothing at its base', () => {
const {animator} = setup(clear);
animator.set({opacity: 0});
animator.attach(document.createElement('div'));
expect(live('opacity')).toHaveLength(0);
animator.set({opacity: 0.5});
animator.attach(document.createElement('div'));
const held = live('opacity');
expect(held).toHaveLength(1);
expect(held[0].keyframes.map(k => k.opacity)).toEqual(['0.5', '0.5']);
});
it('a Reduce Motion dip that lands on its base leaves no opacity animation', async () => {
const {animator} = setup({
reduced: true,
coarse: true,
pseudoElement: '::after',
base: {opacity: 1},
});
animator.set({opacity: 1});
expect(live('opacity')).toHaveLength(0);
animator.animate({x: 100}, {spring: springs.navigationPush});
await commitFrame(clock);
expect(live('opacity').length).toBeGreaterThan(0);
await advance(END_HOLD_MS + 5000);
expect(animator.get('x')).toBe(100);
expect(live('opacity')).toHaveLength(0);
});
it('in development, the first hold it drops warns once when the stylesheet shows another value', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
pseudoStylesheet = {opacity: '1'};
const {animator} = setup(clear);
animator.set({opacity: 0});
// The read waits for a later task.
expect(warn).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(warn).toHaveBeenCalledTimes(1);
expect(String(warn.mock.calls[0][0])).toMatch(
/::after stylesheet shows opacity 1, not its declared base 0/,
);
animator.set({opacity: 0.5});
animator.set({opacity: 0});
await vi.advanceTimersByTimeAsync(1);
expect(warn).toHaveBeenCalledTimes(1);
});
it('a stylesheet that shows its base raises no warning', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
pseudoStylesheet = {opacity: '0'};
const {animator} = setup(clear);
animator.set({opacity: 0});
await vi.advanceTimersByTimeAsync(1);
expect(warn).not.toHaveBeenCalled();
});
});
describe('attach', () => {
it('keeps state without an element and resumes the curve on attach', () => {
const animator = createMotionEngine(null, {
now: () => clock,
});
animator.animate({x: 300}, {spring: springs.settle});
expect(recorded).toHaveLength(0);
clock += 100;
const element = document.createElement('div');
animator.attach(element);
const [animation] = live('translate');
expect(animation.startTime).toBe(1100);
const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
expect(sampleAt(animation, 'translate', 1100)[0]).toBeCloseTo(
curve.value(0.1),
1,
);
// The value on screen, not the end.
expect(parse(element.style.translate)[0]).toBeCloseTo(curve.value(0.1), 2);
});
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('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 it
animator.attach(null);
expect(recorded.every(a => a.cancelled)).toBe(true);
expect(animator.get('x', 1050)).toBeGreaterThan(0);
});
it('writes nothing for channels at identity', () => {
const element = document.createElement('div');
createMotionEngine(element);
expect(element.getAttribute('style')).toBeNull();
});
});
describe('the presented offset iOS hit testing reads', () => {
it('reports translate while it moves: drawn minus where its animation started, zero before the browser starts it', async () => {
const {element, animator} = setup();
animator.animate({y: 300}, {spring: springs.sheetPresent});
// A call from rest starts at the browser's commit: nothing has moved yet.
expect(presentedOffsetOf(element)).toEqual({x: 0, y: 0});
await commitFrame(clock);
expect(presentedElements()).toContain(element);
expect(presentedOffsetOf(element)).toEqual({x: 0, y: 0});
clock += 120;
await vi.advanceTimersByTimeAsync(120);
const offset = presentedOffsetOf(element);
expect(offset.x).toBe(0);
expect(offset.y).toBeCloseTo(animator.get('y'), 9);
expect(offset.y).toBeGreaterThan(0);
expect(offset.y).toBeLessThan(300);
// The curve ends and its animation retires: nothing left to report.
clock += 5000;
await vi.advanceTimersByTimeAsync(5000);
expect(presentedElements()).not.toContain(element);
});
it('stops reporting on stop, set, dispose and detach, and never for a pseudo-element or opacity alone', async () => {
const {element, animator} = setup();
const play = async () => {
animator.animate({x: 200}, {spring: springs.sheetPresent});
await advance(16);
expect(presentedElements()).toContain(element);
};
await play();
animator.stop();
expect(presentedElements()).not.toContain(element);
await play();
animator.set({x: 10});
expect(presentedElements()).not.toContain(element);
await play();
const other = document.createElement('div');
animator.attach(other);
expect(presentedElements()).not.toContain(element);
expect(presentedElements()).toContain(other);
animator.dispose();
expect(presentedElements()).not.toContain(other);
const fade = setup();
fade.animator.animate({opacity: 0}, {spring: springs.sheetPresent});
await advance(16);
expect(presentedElements()).not.toContain(fade.element);
const backdrop = setup({pseudoElement: '::backdrop'});
backdrop.animator.animate({y: 100}, {spring: springs.sheetPresent});
await advance(16);
expect(presentedElements()).not.toContain(backdrop.element);
backdrop.animator.dispose();
fade.animator.dispose();
});
it('resolves where it is drawn on request: one custom-property write, the offset restarting there', async () => {
const {element, animator} = setup();
animator.play({y: {duration: 1, at: t => 300 * t, velocity: () => 300}});
await advance(400);
expect(presentedOffsetOf(element).y).toBeCloseTo(120, 6);
resolvePresented([element]);
expect(element.style.getPropertyValue('--astryx-presented')).toBe('1');
expect(presentedOffsetOf(element).y).toBeCloseTo(0, 6);
await advance(100);
expect(presentedOffsetOf(element).y).toBeCloseTo(30, 6);
// Unreported once at rest, the property goes too.
animator.stop();
expect(element.style.getPropertyValue('--astryx-presented')).toBe('');
animator.dispose();
});
it('starts over from the current value when a rebase or a retarget builds a new animation', async () => {
const {element, animator} = setup();
animator.play({y: {duration: 1, at: t => 300 * t, velocity: () => 300}});
await advance(500);
expect(presentedOffsetOf(element).y).toBeCloseTo(150, 6);
animator.rebase({y: 40});
// The new animation starts where the element is drawn now.
expect(presentedOffsetOf(element).y).toBeCloseTo(0, 6);
await advance(100);
expect(presentedOffsetOf(element).y).toBeCloseTo(30, 6);
animator.animate({y: 0}, {spring: springs.sheetPresent});
await commitFrame(clock);
expect(presentedOffsetOf(element).y).toBeCloseTo(0, 6);
animator.dispose();
});
});
describe("a theme's reduced-motion mark", () => {
// The person's setting is off and the pointer is fine: only the mark can
// reduce the motion.
function underMark(marked: boolean) {
stubMedia(false, false);
const theme = document.createElement('div');
if (marked) {
theme.setAttribute('data-astryx-reduced-motion', '');
}
const element = document.createElement('div');
theme.append(element);
document.body.append(theme);
const animator = createMotionEngine(element, {
now: () => clock,
requestFrame,
});
return {theme, animator};
}
it('counts as the Reduce Motion setting: a move lands at once on a fine pointer', () => {
const {theme, animator} = underMark(true);
animator.animate({x: 100}, {spring: springs.navigationPush});
expect(recorded).toHaveLength(0);
expect(animator.get('x')).toBe(100);
theme.remove();
});
it('without the mark, the same move springs', () => {
const {theme, animator} = underMark(false);
animator.animate({x: 100}, {spring: springs.navigationPush});
expect(recorded.length).toBeGreaterThan(0);
theme.remove();
});
});
describe('rebase towards a new rest', () => {
const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
/** A spring to 300 whose first frame came late, its start still unread. */
async function lateStart() {
const ready = setup();
const handle = ready.animator.animate({x: 300}, {spring: springs.settle});
const [animation] = live('translate');
clock = 1070;
await commitFrame(1070, {startUnread: true});
clock = 1170;
return {...ready, handle, animation};
}
it('before its first frame, a spring heading for the new rest keeps its own velocity', () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1033;
animator.rebase({x: -300}, {towards: {x: 0}});
// The curve has not started, so it keeps its own course. 33 ms in, it has
// its own velocity, not that of a new spring dated from the call.
expect(animator.get('x')).toBeCloseTo(-300, 6);
expect(animator.getVelocity('x')).toBeCloseTo(curve.velocity(0.033), 3);
});
it('while its start is unread, a spring heading for the new rest moves whole in the model only', async () => {
const {element, animator, animation} = await lateStart();
const keyframes = animation.keyframes;
const under = inlineX(element);
const shown = animator.get('x');
animator.rebase({x: -300}, {towards: {x: 0}});
// Within the task, the animation on screen keeps its keyframes, its
// inline value and the compositor's start; the model reads the shift.
expect(live('translate')).toEqual([animation]);
expect(animation.keyframes).toBe(keyframes);
expect(animation.startTime).toBeNull();
expect(inlineX(element)).toBe(under);
expect(animator.get('x')).toBeCloseTo(shown - 300, 6);
});
it('a call in the same task rebuilds the channel from the shifted curve, and nothing rebuilds it again', async () => {
const {animator, animation} = await lateStart();
animator.rebase({x: -300}, {towards: {x: 0}});
const shown = animator.get('x');
animator.animate({x: 0}, {spring: springs.settle});
const rebuilt = live('translate').at(-1) as Recorded;
expect(rebuilt).not.toBe(animation);
expect(parse(rebuilt.keyframes[0].translate)[0]).toBeCloseTo(shown, 1);
expect(parse(rebuilt.keyframes.at(-1)?.translate)[0]).toBeCloseTo(0, 1);
await Promise.resolve();
expect(live('translate')).toEqual([rebuilt]);
});
it('with no call after it, the end of the task rebuilds the channel from the shifted curve', async () => {
const {animator, animation} = await lateStart();
animator.rebase({x: -300}, {towards: {x: 0}});
const shown = animator.get('x');
await Promise.resolve();
const [healed] = live('translate');
expect(healed).not.toBe(animation);
expect(animation.cancelled).toBe(true);
expect(parse(healed.keyframes[0].translate)[0]).toBeCloseTo(shown, 1);
expect(parse(healed.keyframes.at(-1)?.translate)[0]).toBeCloseTo(0, 1);
});
it('a dispose in the same task leaves nothing for the end of the task to rebuild', async () => {
const {animator, animation} = await lateStart();
animator.rebase({x: -300}, {towards: {x: 0}});
animator.dispose();
await Promise.resolve();
expect(animation.cancelled).toBe(true);
expect(live('translate')).toEqual([]);
});
it('a spring with a known start moves whole on its own course', async () => {
const {animator} = setup();
animator.animate({x: 300}, {spring: springs.settle});
clock = 1016;
await commitFrame(1016);
clock = 1116;
animator.rebase({x: -300}, {towards: {x: 0}});
const rebuilt = live('translate').at(-1) as Recorded;
clock = 1216;
expect(animator.get('x')).toBeCloseTo(curve.value(0.2) - 300, 6);
expect(sampleAt(rebuilt, 'translate', 1216)[0]).toBeCloseTo(
curve.value(0.2) - 300,
0,
);
});
it('a target the shift does not bring to `towards` rebases as without it', async () => {
const plain = await lateStart();
plain.animator.rebase({x: -16});
const plainX = plain.animator.get('x');
recorded = [];
clock = 1000;
const toward = await lateStart();
toward.animator.rebase({x: -16}, {towards: {x: 0}});
expect(toward.animator.get('x')).toBe(plainX);
expect(live('translate')).not.toContain(toward.animation);
});
});