Skip to content

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

TypeScript

test(interaction-harness): a late block throws BusyWindowTooLateError (#9505)

Christopher Chedeau9a74db415a7d
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.md
index f9c17469db..87b057343d 100644
--- a/internal/interaction-harness/README.md
+++ b/internal/interaction-harness/README.md
@@ -152,7 +152,9 @@ WebKit's JPEG cast, whose 4:2:0 chroma holds the marker's color in 2 by 2
pixel blocks and so makes the tail's plateaus longer. Two steps stop at the
same tail in either engine while a freeze further from rest is still judged. A judged part shorter than four of the
screencast's intervals fails: the animation under test was not moving during
-the block. With
+the block. One that had already settled when the judged part began (nothing in
+the window to judge) throws `BusyWindowTooLateError`, with the numbers: the
+block ran too late, which is no reading of the component. With
`during`, `blockMainThread` starts the loop from a task queued in the frame
that saw the animation, after that frame's rendering update: WebKit hands a
newly started animation to its compositor there, and a loop inside the rAF
@@ -160,7 +162,12 @@ callback would freeze even a compositor animation. Call it before the release
that starts a settle and await it after, so the page is already waiting when
the settle begins. An animation counts once it is no longer pending and has
run at least one frame: a `minProgressMs` under 16 is raised to 16, since one
-created in the frame the page looks is not on the compositor yet. The `verdict` judges the
+created in the frame the page looks is not on the compositor yet. It counts
+only before its curve's held tail (keyframes that end in a run of identical
+values, read as `waitForRest` reads them): when the only animation running
+there started while the page waited, or the wait times out with only such
+animations, the page looked too late, and the wait rejects with
+`BusyWindowTooLateError`. The `verdict` judges the
frames the screencast delivered, whatever its rate (a loaded machine's can
deliver one frame in five or six), and tolerates nothing a frozen animation
does: at least one frame in the judged part, no stall longer than three of the
diff --git a/internal/interaction-harness/src/busy.test.ts b/internal/interaction-harness/src/busy.test.ts
index 0ad22a1bcf..a979656518 100644
--- a/internal/interaction-harness/src/busy.test.ts
+++ b/internal/interaction-harness/src/busy.test.ts
@@ -16,7 +16,7 @@
*/
import {describe, expect, it} from 'vitest';
-import {busyWindowProof, castStep} from './busy';
+import {busyWindowProof, BusyWindowTooLateError, castStep} from './busy';
import * as skip from './busy.skip.fixture';
import * as slowTail from './busy.slowtail.fixture';
import * as webkitDecel from './busy.webkitdecel.fixture';
@@ -172,18 +172,66 @@ describe('busyWindowProof verdict', () => {
expect(proof.verdict.failures.join('\n')).toMatch(/expected frames moved/);
});
- it('fails a window in which the animation under test was not moving', () => {
- // Settled before the block: the judgment ends where it starts.
+ it('names a block that began after the motion had settled, with its numbers', () => {
+ // Settled 50 ms before the block: nothing in it is left to judge.
const settled = moving().map(f =>
f.t < 950
? f
: ({...f, box: {...f.box!, y: 3 * at(950)}} as TrackedFrame),
);
- const before = busyWindowProof(settled, BLOCK, {settledWithin: 2});
- expect(before.verdict.pass).toBe(false);
- expect(before.verdict.failures.join('\n')).toMatch(
- /judged = -?\d+ frames < 4: the animation under test was not moving/,
+ let thrown: unknown;
+ try {
+ busyWindowProof(settled, BLOCK, {settledWithin: 2});
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(BusyWindowTooLateError);
+ const late = thrown as BusyWindowTooLateError;
+ expect(late.message).toMatch(
+ /within 2 px of where it ends from 0 ms after the block began, before the judged part began at 20 ms/,
+ );
+ expect(late.numbers).toEqual({
+ settledAtMs: 0,
+ judgedFromMs: 20,
+ presented: expect.any(Number),
+ });
+ });
+
+ it('names a late block on a sparse screencast, whichever frames it delivers', () => {
+ // Settled 100 ms before the block, one frame in six: the block's first
+ // frame can come after the judged part begins.
+ const settled = moving().map(f =>
+ f.t < 900
+ ? f
+ : ({...f, box: {...f.box!, y: 3 * at(900)}} as TrackedFrame),
+ );
+ for (let phase = 0; phase < 6; phase += 1) {
+ const sixth = settled.filter((_, i) => i % 6 === phase);
+ expect(() => busyWindowProof(sixth, BLOCK, {settledWithin: 2})).toThrow(
+ BusyWindowTooLateError,
+ );
+ }
+ // The fourth phase's first frame in the block comes 50 ms in, after the
+ // judged part begins. The frame 50 ms before the block names the settle.
+ let thrown: unknown;
+ try {
+ busyWindowProof(
+ settled.filter((_, i) => i % 6 === 3),
+ BLOCK,
+ {settledWithin: 2},
+ );
+ } catch (error) {
+ thrown = error;
+ }
+ expect((thrown as BusyWindowTooLateError).message).toMatch(
+ /within 2 px of where it ends from 50 ms before the block began/,
);
+ expect((thrown as BusyWindowTooLateError).numbers.settledAtMs).toBeCloseTo(
+ -50,
+ );
+ });
+
+ it('fails a window in which the animation under test was not moving', () => {
// Settled 40 ms into the block: two frames, too few to judge.
const early = moving().map(f =>
f.t < 1040
diff --git a/internal/interaction-harness/src/busy.ts b/internal/interaction-harness/src/busy.ts
index 4e1585a6c3..58a20bf66a 100644
--- a/internal/interaction-harness/src/busy.ts
+++ b/internal/interaction-harness/src/busy.ts
@@ -8,8 +8,9 @@
* compositor-only control animation recorded in the same window —,
* `busyWindowProof`, which reads frame evidence for that window, against
* the control when it has one, `castStep`, the screencast's position step
- * read from its frames, and `pooledBusyProof`, which judges several short
- * blocks as one.
+ * read from its frames, `pooledBusyProof`, which judges several short
+ * blocks as one, and `BusyWindowTooLateError`, for a block that began
+ * after the motion it was meant to catch had ended.
* @position The busy-main-thread proof: an animation that runs on the
* compositor keeps advancing at display rate while JavaScript holds the main
* thread; one driven from the main thread (rAF, style writes, layout
@@ -20,6 +21,7 @@
*/
import type {Locator, Page} from '@playwright/test';
+import {defineCurveEnd} from './curve-end';
import {frameStats, type FrameStats, type TrackedFrame} from './frames';
/** The control's colour, apart from the component's marker (`MARKER_RGB`). */
@@ -214,10 +216,38 @@ export interface BlockedWindow extends BusyWindow {
* frame the page looks is still pending, not yet on the compositor
* (Chromium), and in WebKit its start time resolves before its layer is
* flushed: a block that started on it froze it.
+ *
+ * It counts only while it still moves: before its curve's held tail (where
+ * its keyframes end in a run of identical values, read as `waitForRest`
+ * reads it). A block in that tail would judge an animation that has stopped.
+ * When the only animation running there started while the page waited, or
+ * the wait times out with only such animations, the page looked too late:
+ * that rejects with `BusyWindowTooLateError`, with the numbers.
*/
/** One display frame, ms: the least progress `blockMainThread` waits for. */
const ONE_FRAME_MS = 16;
+/**
+ * The block began after the motion it was meant to catch had ended, so the
+ * window holds nothing to judge: when the block ran, not how the component
+ * moved. Thrown by `blockMainThread` (with `during`) when the animation under
+ * test is already in its curve's held tail where the page first looks, and by
+ * `busyWindowProof` when the tracked value had settled before the judged part
+ * of the window began. Always a red, with the numbers; never a pass. Start the
+ * block earlier: call `blockMainThread` before the action that starts the
+ * motion, and await it after.
+ */
+export class BusyWindowTooLateError extends Error {
+ constructor(
+ message: string,
+ /** The times the error is read from, ms. */
+ readonly numbers: Readonly<Record<string, number>>,
+ ) {
+ super(message);
+ this.name = 'BusyWindowTooLateError';
+ }
+}
+
export async function blockMainThread(
page: Page,
ms: number,
@@ -258,7 +288,10 @@ export async function blockMainThread(
};
}, ms);
}
- return during.evaluate(
+ // The curve end the wait reads, defined in the page first: sent before the
+ // wait and not awaited, so the wait starts no later than it did.
+ const defined = page.evaluate(defineCurveEnd);
+ const waited = during.evaluate(
(element, {duration, minProgress, wait}) =>
new Promise<BlockedWindow>((resolve, reject) => {
// The harness's own waits run on the real timers: a frozen timer gate
@@ -285,16 +318,55 @@ export async function blockMainThread(
target.closest('[data-harness-control]') != null
);
};
+ // Where each animation's curve ends, its held tail excluded.
+ const curveEnd =
+ (
+ window as unknown as {
+ __harnessCurveEnd?: (animation: Animation) => number;
+ }
+ ).__harnessCurveEnd ??
+ ((a: Animation) => {
+ const timing = a.effect?.getComputedTiming();
+ return (
+ Number(timing?.delay ?? 0) + Number(timing?.activeDuration ?? 0)
+ );
+ });
+ // What already ran when the wait began.
+ const before = new Set(element.getAnimations({subtree: true}));
+ const numbersOf = (a: Animation) => ({
+ currentTimeMs: Number(a.currentTime ?? 0),
+ curveEndMs: curveEnd(a),
+ startedWhileWaiting: before.has(a) ? 0 : 1,
+ });
+ // The first run the wait saw in its held tail, as it was then: it may
+ // finish, or be cancelled once its curve ends, before the wait times
+ // out.
+ let heldSeen: ReturnType<typeof numbersOf> | null = null;
+ const tooLate = (numbers: ReturnType<typeof numbersOf>) =>
+ new Error(`BusyWindowTooLate ${JSON.stringify(numbers)}`);
const tick = () => {
- const running = element
+ const ran = element
.getAnimations({subtree: true})
- .some(
+ .filter(
a =>
!isControl(a) &&
a.playState === 'running' &&
!a.pending &&
Number(a.currentTime ?? 0) >= minProgress,
);
+ // Still moving: before its curve's held tail. One running backward
+ // ends at its start, so it moves while it runs.
+ const running = ran.some(
+ a => a.playbackRate < 0 || Number(a.currentTime ?? 0) < curveEnd(a),
+ );
+ if (!running && ran.length > 0) {
+ heldSeen ??= numbersOf(ran[0]);
+ }
+ // In its held tail: started while the page waited, or, when the
+ // wait times out, what is left there or the first such run it saw.
+ const late = ran.find(a => !before.has(a));
+ const timedOut = realNow() > deadline;
+ const leftover = ran.length > 0 ? numbersOf(ran[0]) : heldSeen;
if (running) {
// The same loop as above, from a task queued in the frame that saw
// the animation: it runs once that frame's rendering update has
@@ -312,7 +384,11 @@ export async function blockMainThread(
spanMs: now - start,
});
}, 0);
- } else if (realNow() > deadline) {
+ } else if (late != null) {
+ reject(tooLate(numbersOf(late)));
+ } else if (timedOut && leftover != null) {
+ reject(tooLate(leftover));
+ } else if (timedOut) {
reject(new Error('blockMainThread: no animation started'));
} else {
frame(tick);
@@ -322,6 +398,26 @@ export async function blockMainThread(
}),
{duration: ms, minProgress, wait: timeout},
);
+ try {
+ const [, held] = await Promise.all([defined, waited]);
+ return held;
+ } catch (error) {
+ const late = /BusyWindowTooLate (\{.*\})/.exec(
+ error instanceof Error ? error.message : String(error),
+ );
+ if (late == null) {
+ throw error;
+ }
+ const numbers = JSON.parse(late[1]) as {
+ currentTimeMs: number;
+ curveEndMs: number;
+ startedWhileWaiting: number;
+ };
+ throw new BusyWindowTooLateError(
+ `blockMainThread: the animation under test was ${numbers.currentTimeMs.toFixed(0)} ms in, past the end of its curve at ${numbers.curveEndMs.toFixed(0)} ms, when the page ${numbers.startedWhileWaiting ? 'first saw it' : 'gave up waiting for one that moves'}: its motion had ended, so a block now holds nothing to judge. Call blockMainThread before the action that starts the motion, and await it after.`,
+ numbers,
+ );
+ }
}
export interface BusyVerdict {
@@ -680,6 +776,47 @@ export function busyWindowProof(
if (arrived != null) {
end = Math.min(end, arrived.t);
}
+ // A sparse screencast can deliver the block's first frame after the
+ // judged part begins. Then the frame before the block shows the settle,
+ // when it and the block's first frame are both within the bound.
+ let before: (typeof valued)[number] | undefined;
+ for (const f of valued) {
+ if (f.t >= window.from) break;
+ before = f;
+ }
+ const firstInBlock = valued.find(f => f.t >= window.from);
+ const settledBy =
+ arrived != null && arrived.t <= window.from + marginMs
+ ? arrived.t
+ : before != null &&
+ arrived != null &&
+ arrived === firstInBlock &&
+ final != null &&
+ Math.abs(before.value - final) <= settledWithinPx
+ ? before.t
+ : null;
+ // Within the bound of where it ends before the judged part began: the
+ // block started after the motion had settled, so the window holds
+ // nothing to judge. That is when the block ran, not how the component
+ // moved.
+ if (settledBy != null) {
+ const presented = tracked.filter(
+ f => f.t >= window.from && f.t <= window.to,
+ ).length;
+ const fromBlock = settledBy - window.from;
+ const when =
+ fromBlock < 0
+ ? `${(-fromBlock).toFixed(0)} ms before`
+ : `${fromBlock.toFixed(0)} ms after`;
+ throw new BusyWindowTooLateError(
+ `busyWindowProof: the tracked ${axis} was within ${settledWithinPx} px of where it ends from ${when} the block began, before the judged part began at ${marginMs} ms (${presented} frames presented in the block): the block started after the motion had settled, so there is nothing in it to judge. Start the block earlier.`,
+ {
+ settledAtMs: fromBlock,
+ judgedFromMs: marginMs,
+ presented,
+ },
+ );
+ }
}
const inner = {from: window.from + marginMs, to: end};
const values = tracked
diff --git a/internal/interaction-harness/src/curve-end.ts b/internal/interaction-harness/src/curve-end.ts
new file mode 100644
index 0000000000..0a12ed2f8b
--- /dev/null
+++ b/internal/interaction-harness/src/curve-end.ts
@@ -0,0 +1,134 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file curve-end.ts
+ * @input The Web Animations API in the page
+ * @output `defineCurveEnd`, a page function that installs
+ * `window.__harnessCurveEnd(animation)` once: the local time (ms, delay
+ * included) where the animation's effect stops changing.
+ * @position Shared by ./curves.ts (holds, `waitForRest`) and ./busy.ts
+ * (`blockMainThread`'s `during`), so both read an animation's held tail the
+ * same way. Not exported from the package: a page function, evaluated in
+ * the page.
+ *
+ * SYNC: When modified, update ./curves.ts (installCurveEnd) and ./busy.ts
+ * (blockMainThread).
+ */
+
+/**
+ * Installs `window.__harnessCurveEnd(animation)` in the page, once. An
+ * animation whose keyframes end in a run of identical values (an end value
+ * held so that a later interruption can read it) ends where that run starts,
+ * when it plays forward under a linear or cubic-bézier effect easing (the time
+ * the run starts is solved from the curve); any other ends at its end time. A
+ * page function: it closes over nothing.
+ */
+export function defineCurveEnd(): void {
+ const w = window as unknown as {
+ __harnessCurveEnd?: (animation: Animation) => number;
+ };
+ if (w.__harnessCurveEnd) {
+ return;
+ }
+ const timingKeys = new Set([
+ 'offset',
+ 'computedOffset',
+ 'easing',
+ 'composite',
+ ]);
+ const values = (k: ComputedKeyframe) =>
+ JSON.stringify(
+ Object.keys(k)
+ .filter(p => !timingKeys.has(p))
+ .sort()
+ .map(p => [p, String(k[p])]),
+ );
+ w.__harnessCurveEnd = animation => {
+ const effect = animation.effect as KeyframeEffect | null;
+ const timing = effect?.getComputedTiming();
+ const delay = Number(timing?.delay ?? 0);
+ const active = Number(timing?.activeDuration ?? 0);
+ if (
+ effect == null ||
+ !Number.isFinite(active) ||
+ Number(timing?.iterations ?? 1) !== 1
+ ) {
+ return delay + active;
+ }
+ // A held end is read only for an animation that plays forward: run
+ // backward (a reverse or alternating direction, or `reverse()`'s
+ // negative playback rate), the held run is where its motion starts.
+ if (
+ (timing?.direction ?? 'normal') !== 'normal' ||
+ animation.playbackRate < 0
+ ) {
+ return delay + active;
+ }
+ const frames = effect.getKeyframes();
+ // A run holds only when it reaches offset 1 and every frame in it keys
+ // every property the animation keys: a property left out, or a last
+ // frame before offset 1, gets an implicit end frame and keeps moving.
+ const keyed = new Set(
+ frames.flatMap(k => Object.keys(k).filter(p => !timingKeys.has(p))),
+ );
+ const keysAll = (k: ComputedKeyframe) =>
+ [...keyed].every(p => k[p] !== undefined);
+ const last = frames[frames.length - 1];
+ if (last == null || Number(last.computedOffset) !== 1 || !keysAll(last)) {
+ return delay + active;
+ }
+ let first = frames.length - 1;
+ while (
+ first > 0 &&
+ keysAll(frames[first - 1]) &&
+ values(frames[first - 1]) === values(frames[first])
+ ) {
+ first -= 1;
+ }
+ const offset = Number(frames[first]?.computedOffset ?? 1);
+ if (offset >= 1) {
+ return delay + active;
+ }
+ // Keyframe offsets are progress, not time. Under a cubic-bézier effect
+ // easing (the CSS keywords included) whose progress only rises, the
+ // time the held run starts is solved from the curve; under any other
+ // easing (steps, linear() stops, an overshoot) the curve is read to the
+ // full end.
+ const easing = String(effect.getTiming().easing ?? 'linear').trim();
+ const named: Record<string, number[]> = {
+ linear: [0, 0, 1, 1],
+ ease: [0.25, 0.1, 0.25, 1],
+ 'ease-in': [0.42, 0, 1, 1],
+ 'ease-out': [0, 0, 0.58, 1],
+ 'ease-in-out': [0.42, 0, 0.58, 1],
+ };
+ const match = /^cubic-bezier\(([^)]+)\)$/.exec(easing);
+ const points =
+ named[easing] ?? (match ? match[1].split(',').map(Number) : null);
+ if (
+ points == null ||
+ points.length !== 4 ||
+ !points.every(Number.isFinite) ||
+ points[1] < 0 ||
+ points[1] > 1 ||
+ points[3] < 0 ||
+ points[3] > 1
+ ) {
+ return delay + active;
+ }
+ const [x1, y1, x2, y2] = points;
+ const bezier = (u: number, p1: number, p2: number) =>
+ 3 * (1 - u) * (1 - u) * u * p1 + 3 * (1 - u) * u * u * p2 + u * u * u;
+ let lo = 0;
+ let hi = 1;
+ for (let i = 0; i < 60; i += 1) {
+ const mid = (lo + hi) / 2;
+ if (bezier(mid, y1, y2) < offset) {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+ return delay + bezier((lo + hi) / 2, x1, x2) * active;
+ };
+}
diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.ts
index 4b1569efa7..d2e2bb6998 100644
--- a/internal/interaction-harness/src/curves.ts
+++ b/internal/interaction-harness/src/curves.ts
@@ -23,6 +23,7 @@
*/
import type {Locator, Page} from '@playwright/test';
+import {defineCurveEnd} from './curve-end';
import {parseTransform, type TimedValue, type Transform2D} from './math';
/** How far inside its end a seek past an animation's end lands, ms. */
@@ -376,221 +377,126 @@ async function installRecorder(page: Page): Promise<void> {
*/
async function installCurveEnd(page: Page): Promise<void> {
await installRecorder(page);
- await page.evaluate(() => {
+ // The hold, installed with the curve end it reads: one round trip installs
+ // both, so a hold sent from the test costs no extra one.
+ await page.evaluate(
+ `(${defineCurveEnd.toString()})();(${defineHold.toString()})();`,
+ );
+}
+
+/**
+ * Installs `window.__harnessHold(root)` in the page, once (see
+ * `installCurveEnd`). A page function: it closes over nothing, and reads the
+ * curve end `defineCurveEnd` installs.
+ */
+function defineHold(): void {
+ const w = window as unknown as {
+ __harnessHold?: (
+ root: Element | null,
+ skip?: ReadonlySet<Animation>,
+ ) => unknown[];
+ };
+ if (w.__harnessHold) {
+ return;
+ }
+ w.__harnessHold = (root: Element | null, skip?: ReadonlySet<Animation>) => {
+ const curveEnd = (
+ window as unknown as {__harnessCurveEnd: (a: Animation) => number}
+ ).__harnessCurveEnd;
+ const describe = (node: Element | null) =>
+ node == null
+ ? null
+ : node.tagName.toLowerCase() +
+ (node.id ? `#${node.id}` : '') +
+ (node.classList.length
+ ? `.${[...node.classList].slice(0, 2).join('.')}`
+ : '');
+ const now = Number(document.timeline.currentTime ?? performance.now());
+ const all = document.getAnimations().filter(animation => {
+ const target =
+ (animation.effect as KeyframeEffect | null)?.target ?? null;
+ return (
+ animation.playState === 'running' &&
+ animation.timeline instanceof DocumentTimeline &&
+ !(skip?.has(animation) ?? false) &&
+ (root == null ||
+ (target != null && (root === target || root.contains(target))))
+ );
+ });
+ // Seeking and sampling run a curve forward: an animation running
+ // backward (`reverse()`, a negative playback rate) cannot be held and
+ // read, so it is refused rather than misread.
+ const backward = all.find(animation => animation.playbackRate < 0);
+ if (backward != null) {
+ throw new Error(
+ `holdAnimations: ${describe((backward.effect as KeyframeEffect | null)?.target ?? null) ?? 'an animation'} runs backward (reverse() or a negative playback rate); hold and sample a forward run instead`,
+ );
+ }
+ // Each animation's start on the document timeline, read before the pause
+ // clears it. A pending play has no start time yet: it starts now, as far
+ // back as its current time reaches through its playback rate (at rate 2,
+ // a run covers its curve in half the timeline), as seeking reads it.
+ const starts = all.map(animation =>
+ animation.startTime != null
+ ? Number(animation.startTime)
+ : now -
+ Number(animation.currentTime ?? 0) / (animation.playbackRate || 1),
+ );
+ const held = all.map(animation => {
+ animation.pause();
+ // `pause()` only schedules the pause: the engine takes the hold time at
+ // its next frame, a frame past where this read it. Setting the current
+ // time completes a pending pause at once, here.
+ // eslint-disable-next-line no-self-assign
+ animation.currentTime = animation.currentTime;
+ return animation;
+ });
+ // A later hold adds to the held set: what an earlier one held stays held
+ // (it is paused, so it is not taken again above) until released.
const w = window as unknown as {
- __harnessCurveEnd?: (animation: Animation) => number;
- __harnessHold?: (
- root: Element | null,
- skip?: ReadonlySet<Animation>,
- ) => unknown[];
+ __harnessHeld?: Animation[];
+ __harnessHeldStarts?: number[];
+ __harnessHeldOrigin?: number;
};
- if (w.__harnessCurveEnd) {
- return;
- }
- const timingKeys = new Set([
- 'offset',
- 'computedOffset',
- 'easing',
- 'composite',
- ]);
- const values = (k: ComputedKeyframe) =>
- JSON.stringify(
- Object.keys(k)
- .filter(p => !timingKeys.has(p))
- .sort()
- .map(p => [p, String(k[p])]),
- );
- w.__harnessCurveEnd = animation => {
+ w.__harnessHeld = [...(w.__harnessHeld ?? []), ...held];
+ w.__harnessHeldStarts = [...(w.__harnessHeldStarts ?? []), ...starts];
+ // Times count from the origin the first hold set (its earliest start)
+ // until the release: a later hold, even of an animation that started
+ // earlier (its offset is then negative), and dropping one never move it,
+ // so every offsetMs already returned stays true.
+ const origin = Number.isFinite(w.__harnessHeldOrigin ?? Number.NaN)
+ ? (w.__harnessHeldOrigin as number)
+ : Math.min(...starts);
+ w.__harnessHeldOrigin = origin;
+ const offsets = starts.map(start => start - origin);
+ return held.map((animation, index) => {
const effect = animation.effect as KeyframeEffect | null;
const timing = effect?.getComputedTiming();
- const delay = Number(timing?.delay ?? 0);
- const active = Number(timing?.activeDuration ?? 0);
- if (
- effect == null ||
- !Number.isFinite(active) ||
- Number(timing?.iterations ?? 1) !== 1
- ) {
- return delay + active;
- }
- // A held end is read only for an animation that plays forward: run
- // backward (a reverse or alternating direction, or `reverse()`'s
- // negative playback rate), the held run is where its motion starts.
- if (
- (timing?.direction ?? 'normal') !== 'normal' ||
- animation.playbackRate < 0
- ) {
- return delay + active;
- }
- const frames = effect.getKeyframes();
- // A run holds only when it reaches offset 1 and every frame in it keys
- // every property the animation keys: a property left out, or a last
- // frame before offset 1, gets an implicit end frame and keeps moving.
- const keyed = new Set(
- frames.flatMap(k => Object.keys(k).filter(p => !timingKeys.has(p))),
- );
- const keysAll = (k: ComputedKeyframe) =>
- [...keyed].every(p => k[p] !== undefined);
- const last = frames[frames.length - 1];
- if (last == null || Number(last.computedOffset) !== 1 || !keysAll(last)) {
- return delay + active;
- }
- let first = frames.length - 1;
- while (
- first > 0 &&
- keysAll(frames[first - 1]) &&
- values(frames[first - 1]) === values(frames[first])
- ) {
- first -= 1;
- }
- const offset = Number(frames[first]?.computedOffset ?? 1);
- if (offset >= 1) {
- return delay + active;
- }
- // Keyframe offsets are progress, not time. Under a cubic-bézier effect
- // easing (the CSS keywords included) whose progress only rises, the
- // time the held run starts is solved from the curve; under any other
- // easing (steps, linear() stops, an overshoot) the curve is read to the
- // full end.
- const easing = String(effect.getTiming().easing ?? 'linear').trim();
- const named: Record<string, number[]> = {
- linear: [0, 0, 1, 1],
- ease: [0.25, 0.1, 0.25, 1],
- 'ease-in': [0.42, 0, 1, 1],
- 'ease-out': [0, 0, 0.58, 1],
- 'ease-in-out': [0.42, 0, 0.58, 1],
- };
- const match = /^cubic-bezier\(([^)]+)\)$/.exec(easing);
- const points =
- named[easing] ?? (match ? match[1].split(',').map(Number) : null);
- if (
- points == null ||
- points.length !== 4 ||
- !points.every(Number.isFinite) ||
- points[1] < 0 ||
- points[1] > 1 ||
- points[3] < 0 ||
- points[3] > 1
- ) {
- return delay + active;
- }
- const [x1, y1, x2, y2] = points;
- const bezier = (u: number, p1: number, p2: number) =>
- 3 * (1 - u) * (1 - u) * u * p1 + 3 * (1 - u) * u * u * p2 + u * u * u;
- let lo = 0;
- let hi = 1;
- for (let i = 0; i < 60; i += 1) {
- const mid = (lo + hi) / 2;
- if (bezier(mid, y1, y2) < offset) {
- lo = mid;
- } else {
- hi = mid;
- }
- }
- return delay + bezier((lo + hi) / 2, x1, x2) * active;
- };
- // The hold, installed with the curve end it reads: one round trip
- // installs both, so a hold sent from the test costs no extra one.
- w.__harnessHold = (root: Element | null, skip?: ReadonlySet<Animation>) => {
- const curveEnd = (
- window as unknown as {__harnessCurveEnd: (a: Animation) => number}
- ).__harnessCurveEnd;
- const describe = (node: Element | null) =>
- node == null
- ? null
- : node.tagName.toLowerCase() +
- (node.id ? `#${node.id}` : '') +
- (node.classList.length
- ? `.${[...node.classList].slice(0, 2).join('.')}`
- : '');
- const now = Number(document.timeline.currentTime ?? performance.now());
- const all = document.getAnimations().filter(animation => {
- const target =
- (animation.effect as KeyframeEffect | null)?.target ?? null;
- return (
- animation.playState === 'running' &&
- animation.timeline instanceof DocumentTimeline &&
- !(skip?.has(animation) ?? false) &&
- (root == null ||
- (target != null && (root === target || root.contains(target))))
- );
- });
- // Seeking and sampling run a curve forward: an animation running
- // backward (`reverse()`, a negative playback rate) cannot be held and
- // read, so it is refused rather than misread.
- const backward = all.find(animation => animation.playbackRate < 0);
- if (backward != null) {
- throw new Error(
- `holdAnimations: ${describe((backward.effect as KeyframeEffect | null)?.target ?? null) ?? 'an animation'} runs backward (reverse() or a negative playback rate); hold and sample a forward run instead`,
- );
- }
- // Each animation's start on the document timeline, read before the pause
- // clears it. A pending play has no start time yet: it starts now, as far
- // back as its current time reaches through its playback rate (at rate 2,
- // a run covers its curve in half the timeline), as seeking reads it.
- const starts = all.map(animation =>
- animation.startTime != null
- ? Number(animation.startTime)
- : now -
- Number(animation.currentTime ?? 0) / (animation.playbackRate || 1),
- );
- const held = all.map(animation => {
- animation.pause();
- // `pause()` only schedules the pause: the engine takes the hold time at
- // its next frame, a frame past where this read it. Setting the current
- // time completes a pending pause at once, here.
- // eslint-disable-next-line no-self-assign
- animation.currentTime = animation.currentTime;
- return animation;
- });
- // A later hold adds to the held set: what an earlier one held stays held
- // (it is paused, so it is not taken again above) until released.
- const w = window as unknown as {
- __harnessHeld?: Animation[];
- __harnessHeldStarts?: number[];
- __harnessHeldOrigin?: number;
+ const cssName =
+ 'transitionProperty' in animation
+ ? (animation as unknown as {transitionProperty: string})
+ .transitionProperty
+ : 'animationName' in animation
+ ? (animation as unknown as {animationName: string}).animationName
+ : null;
+ return {
+ index,
+ kind: animation.constructor.name,
+ name: cssName,
+ target: describe((effect?.target as Element | null) ?? null),
+ durationMs: Number(timing?.duration ?? 0),
+ delayMs: Number(timing?.delay ?? 0),
+ curveEndMs: curveEnd(animation),
+ easing: String(effect?.getTiming().easing ?? 'linear'),
+ keyframes: (effect?.getKeyframes() ?? []).map(
+ (k): Record<string, unknown> => ({...k}),
+ ),
+ heldAtMs:
+ animation.currentTime == null ? null : Number(animation.currentTime),
+ offsetMs: offsets[index],
};
- w.__harnessHeld = [...(w.__harnessHeld ?? []), ...held];
- w.__harnessHeldStarts = [...(w.__harnessHeldStarts ?? []), ...starts];
- // Times count from the origin the first hold set (its earliest start)
- // until the release: a later hold, even of an animation that started
- // earlier (its offset is then negative), and dropping one never move it,
- // so every offsetMs already returned stays true.
- const origin = Number.isFinite(w.__harnessHeldOrigin ?? Number.NaN)
- ? (w.__harnessHeldOrigin as number)
- : Math.min(...starts);
- w.__harnessHeldOrigin = origin;
- const offsets = starts.map(start => start - origin);
- return held.map((animation, index) => {
- const effect = animation.effect as KeyframeEffect | null;
- const timing = effect?.getComputedTiming();
- const cssName =
- 'transitionProperty' in animation
- ? (animation as unknown as {transitionProperty: string})
- .transitionProperty
- : 'animationName' in animation
- ? (animation as unknown as {animationName: string}).animationName
- : null;
- return {
- index,
- kind: animation.constructor.name,
- name: cssName,
- target: describe((effect?.target as Element | null) ?? null),
- durationMs: Number(timing?.duration ?? 0),
- delayMs: Number(timing?.delay ?? 0),
- curveEndMs: curveEnd(animation),
- easing: String(effect?.getTiming().easing ?? 'linear'),
- keyframes: (effect?.getKeyframes() ?? []).map(
- (k): Record<string, unknown> => ({...k}),
- ),
- heldAtMs:
- animation.currentTime == null
- ? null
- : Number(animation.currentTime),
- offsetMs: offsets[index],
- };
- });
- };
- });
+ });
+ };
}
export interface HeldAnimation {
diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
index 3beb43d008..6e1f8b0020 100644
--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts
+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
@@ -51,6 +51,7 @@ import {
castStoryboard,
blockMainThread,
busyWindowProof,
+ BusyWindowTooLateError,
compareCurve,
countBetween,
cubicBezier,
@@ -3933,6 +3934,87 @@ test.describe('storyboards', {tag: '@storyboard'}, () => {
await thawTimers(page);
});
+ test("blockMainThread with during names a block that would begin in the motion's held tail, and waits past an older run held there", async ({
+ page,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ // Moves for its first 30%, then holds its end value: its curve ends at
+ // 900 ms of 3 s.
+ const held = [
+ {transform: 'translateX(0px)', offset: 0},
+ {transform: 'translateX(200px)', offset: 0.3},
+ {transform: 'translateX(200px)', offset: 1},
+ ];
+ // Started while the page waits, already 1.5 s in: past its curve, so a
+ // block now would judge a run that has stopped.
+ const late = blockMainThread(page, 100, {during: box, timeout: 2_000}).then(
+ () => null,
+ (error: unknown) => error,
+ );
+ await page.waitForTimeout(100);
+ await box.evaluate((el, keyframes) => {
+ const run = el.animate(keyframes, {duration: 3_000, easing: 'linear'});
+ run.currentTime = 1_500;
+ }, held);
+ const error = await late;
+ expect(error).toBeInstanceOf(BusyWindowTooLateError);
+ const {numbers} = error as BusyWindowTooLateError;
+ expect(numbers.curveEndMs).toBeCloseTo(900, 3);
+ expect(numbers.currentTimeMs).toBeGreaterThanOrEqual(1_500);
+ expect(numbers.startedWhileWaiting).toBe(1);
+ // That run still holds its end when the next wait begins: the page waits
+ // for one that moves, and blocks while it does.
+ const moving = blockMainThread(page, 100, {during: box, timeout: 2_000});
+ await page.waitForTimeout(100);
+ const startedAt = await box.evaluate(el => {
+ el.animate([{translate: '0 0'}, {translate: '0 100px'}], {
+ duration: 1_000,
+ easing: 'linear',
+ });
+ return performance.timeOrigin + performance.now();
+ });
+ const window = await moving;
+ expect(window.from).toBeGreaterThan(startedAt);
+ });
+
+ test('blockMainThread with during names a late block when the run it saw held ends before the wait times out', async ({
+ page,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ // Already in its held tail (its curve ends at 900 ms of 3 s) when the
+ // wait begins, then cancelled, as Core's animator cancels a held run
+ // once its curve ends: nothing runs when the wait times out.
+ await box.evaluate(el => {
+ const run = el.animate(
+ [
+ {transform: 'translateX(0px)', offset: 0},
+ {transform: 'translateX(200px)', offset: 0.3},
+ {transform: 'translateX(200px)', offset: 1},
+ ],
+ {duration: 3_000, easing: 'linear'},
+ );
+ run.currentTime = 1_500;
+ (window as unknown as {heldRun: Animation}).heldRun = run;
+ });
+ await page.waitForTimeout(100);
+ const late = blockMainThread(page, 100, {during: box, timeout: 1_000}).then(
+ () => null,
+ (error: unknown) => error,
+ );
+ await page.waitForTimeout(300);
+ await page.evaluate(() =>
+ (window as unknown as {heldRun: Animation}).heldRun.cancel(),
+ );
+ const error = await late;
+ expect(error).toBeInstanceOf(BusyWindowTooLateError);
+ const {numbers} = error as BusyWindowTooLateError;
+ expect(numbers.curveEndMs).toBeCloseTo(900, 3);
+ expect(numbers.currentTimeMs).toBeGreaterThanOrEqual(1_500);
+ expect(numbers.startedWhileWaiting).toBe(0);
+ });
+
test('the timer gate holds a component timer until the filmstrip is done', async ({
page,
}, testInfo) => {