An open source design system that's fully customizable and agent ready
TypeScript
fix(core): the calls from rest that one frame commits start at one time (#10584)
Christopher Chedeau7b8dc581a433
diff --git a/.changeset/motion-one-frame-one-start.md b/.changeset/motion-one-frame-one-start.mdnew file mode 100644index 0000000000..3fa1298ab0--- /dev/null+++ b/.changeset/motion-one-frame-one-start.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Motion: elements that start moving from rest in the same frame now start at one time. Before, each element took its own reading of the clock in that frame, so items starting together, such as a carousel's pages as they settle, could start apart by as long as the frame callbacks between them ran.++@vjeuxdiff --git a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.tsindex a6b2a362c6..6b8209e1b4 100644--- a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts@@ -849,6 +849,65 @@ test('no Layout or Paint runs while it animates', async ({expect(counts.Paint ?? 0).toBe(0);});+test('the calls from rest that one frame commits start at one time, however long the frame callbacks between them run', async ({+ page,+}) => {+ await open(page);+ const result = await page.evaluate(async () => {+ const box = document.getElementById('box') as HTMLElement;+ const other = box.cloneNode() as HTMLElement;+ other.id = 'other';+ other.style.top = '120px';+ document.body.append(other);+ const second = Motion.createMotionEngine(other);+ const frame = async () =>+ new Promise<void>(resolve => {+ requestAnimationFrame(() => resolve());+ });+ await frame();+ // Out of the frame: calls made in a task, which the next frame commits.+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ const spring = {response: 0.6, dampingRatio: 1};+ const first = window.animator.animate({x: 300}, {spring});+ // A page's own frame callback runs 3 ms between the two animators'.+ requestAnimationFrame(() => {+ const end = performance.now() + 3;+ while (performance.now() < end) {+ // the page's own frame work+ }+ });+ const next = second.animate({x: 300}, {spring});+ const starts = await Promise.all([first.started, next.started]);+ const [a] = box.getAnimations();+ const [b] = other.getAnimations();+ // Both animations' own times, frame by frame through the motion.+ const apart: number[] = [];+ for (let i = 0; i < 20; i++) {+ await frame();+ if (a.currentTime == null || b.currentTime == null) {+ break;+ }+ apart.push(Math.abs(Number(a.currentTime) - Number(b.currentTime)));+ }+ return {+ starts,+ startTimes: [Number(a.startTime), Number(b.startTime)],+ apart,+ };+ });+ test.info().annotations.push({+ type: 'two calls, one frame',+ description: JSON.stringify(result),+ });+ // Both move, frame after frame, before their clocks are compared.+ expect(result.apart.length).toBeGreaterThan(5);+ expect(result.startTimes[1]).toBe(result.startTimes[0]);+ expect(result.starts[1]).toBe(result.starts[0]);+ expect(Math.max(...result.apart)).toBe(0);+});+test('the engine plays the analytic curve, all channels on one clock', async ({page,}) => {diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex e4cd8c8a35..b370c23743 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -63,8 +63,10 @@ interface Recorded {let clock = 1000;let recorded: Recorded[] = [];/** Callbacks waiting for the next animation frame (`requestFrame`). */-let frameQueue: (() => void)[] = [];-const requestFrame = (callback: () => void) => {+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);};/**@@ -240,8 +242,11 @@ async function commitFrame(}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();+ callback(frameStamp);}await Promise.resolve();await Promise.resolve();@@ -945,6 +950,85 @@ describe('a call from rest starts at the commit, as Core Animation does', () =>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, sodiff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 906abe3868..002d2779c3 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -368,10 +368,11 @@ export interface AnimatorOptions {/** Clock in ms on the document timeline's time base. */now?: () => number;/**- * Runs a callback in the next animation frame; `requestAnimationFrame` by- * default. A call from rest reads the start the browser gave it there.+ * Runs a callback in the next animation frame, with the frame's timestamp;+ * `requestAnimationFrame` by default. A call from rest reads the start the+ * browser gave it there.*/- requestFrame?: (callback: () => void) => void;+ requestFrame?: (callback: (frame?: number) => void) => void;}/**@@ -753,6 +754,36 @@ function markTask(time: number, clock: () => number): TaskMark {return openTask;}+/** The first read of the time an animation frame runs, by its timestamp. */+let frameRead: {readonly frame: number; readonly time: number} | null = null;++/**+ * The time the animation frame with timestamp `frame` runs, read once in+ * that frame. Every animator's callback in the frame takes that read, so the+ * calls from rest that one frame commits start together. A long callback+ * before them does not move their start. A call on a moving element keeps+ * its own clock. The read ends with the frame's task, so a frame+ * source that repeats a timestamp still reads each frame anew. A frame+ * source with no timestamp reads the clock.+ */+function frameTime(frame: number | undefined, clock: () => number): number {+ if (frame == null) {+ return clock();+ }+ if (frameRead?.frame === frame) {+ return frameRead.time;+ }+ const read = {frame, time: clock()};+ frameRead = read;+ // A browser runs every callback of a frame before its next task.+ setTimeout(() => {+ if (frameRead === read) {+ frameRead = null;+ }+ }, 0);+ return read.time;+}+/** Above this many keyframes the tolerance is relaxed. */const MAX_KEYFRAMES = 1200;/**@@ -1016,8 +1047,8 @@ export function createMotionEngine(const frameSource =options.requestFrame ??(typeof requestAnimationFrame === 'function'- ? (callback: () => void) => {- requestAnimationFrame(() => callback());+ ? (callback: (frame?: number) => void) => {+ requestAnimationFrame(frame => callback(frame));}: null);// Every frame callback of an animator's counts itself, so a call made in@@ -1025,11 +1056,11 @@ export function createMotionEngine(const requestFrame =frameSource == null? null- : (callback: () => void) => {- frameSource(() => {+ : (callback: (frame?: number) => void) => {+ frameSource(frame => {frameDepth += 1;try {- callback();+ callback(frame);} finally {frameDepth -= 1;}@@ -1743,14 +1774,14 @@ export function createMotionEngine(if (rebuiltAfterFirstFrame) {// The frame that commits it dates this channel's start again. The// call's other channels keep their own.- requestFrame?.(() => {+ requestFrame?.(frame => {if (!waiting.resolved &&running.get(channel) === animation &&animation.startTime == null &&animation.playState === 'running') {- (waiting.latest ??= new Map()).set(channel, now());+ (waiting.latest ??= new Map()).set(channel, frameTime(frame, now));}});}@@ -2438,7 +2469,7 @@ export function createMotionEngine(// or when its compositor starts them (Chromium). Read it in that first// frame, ahead of anything that might pause or seek the animations, and// when `ready` settles.- requestFrame?.(() => {+ requestFrame?.(frame => {syncGroup(group);group.framed = true;// Chromium's compositor starts a composited animation when the frame@@ -2446,24 +2477,28 @@ export function createMotionEngine(// more later (longer under load). Until then the call would read as// not started while the screen moves it, and a retarget or a rebase// would replay its curve from the start. A call made in a task, still- // waiting in the first frame after it, starts now, which the compositor- // then takes as its start: the time this frame runs, not its timestamp,+ // waiting in the first frame after it, starts when this frame runs. The+ // compositor takes that time as its start. All calls the frame commits+ // take one read of it (frameTime). That read is not the frame timestamp,// which after a block is the frame time from before the block. Only// when this frame is the one that commits it: not for a call made in a// frame callback, whose frame committed it already, nor when a block// ran between the call and this frame (more than LATE_START_MS), after// which this frame cannot tell a call made in a task from one a page's// own frame callback made; those keep the browser's start.+ if (group.resolved) {+ return;+ }+ const at = frameTime(frame, now);if (- !group.resolved &&group.madeInFrame !== true &&- now() - (group.task?.first ?? group.provisional) <= LATE_START_MS &&+ at - (group.task?.first ?? group.provisional) <= LATE_START_MS &&group.animations.some(animation =>animation.startTime == null && animation.playState === 'running',)) {- resolveGroup(group, now());+ resolveGroup(group, at);}// The browser's start is still unread. The compositor starts the call// near this frame, so each moving channel's reads take the curve from@@ -2477,7 +2512,7 @@ export function createMotionEngine(animation.startTime == null &&animation.playState === 'running') {- (group.latest ??= new Map()).set(channel, now());+ (group.latest ??= new Map()).set(channel, at);}}}