Skip to content

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

TypeScript

test(interaction-harness): blockMainThread picks the animation it holds (#10541)

Christopher Chedeauac0046c53351
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.md
index f95401dc87..274c61ba57 100644
--- a/internal/interaction-harness/README.md
+++ b/internal/interaction-harness/README.md
@@ -218,7 +218,16 @@ animations, the page looked too late, and the wait rejects with
`BusyWindowTooLateError`. With `pseudoElement` (`'::before'` or
`'::after'`), only that pseudo-element's animations on `during` itself count,
as `sampleCurve` reads them: a child's animation, such as a switch thumb's
-press, does not start the block. The `verdict` judges the
+press, does not start the block. With `property`, only animations that set
+that property count, named as CSS names it (`translate`, `background-color`,
+`--press-strength`), as a hold's judged motion names it. The animation must
+also be the same one the page saw at its frame before:
+a component can rebuild a running animation on its old clock, and the page sees
+it running before the compositor shows a frame of it. The window names the
+animation it caught (`animation`): when it started and where its curve ends.
+These times are on the real clock, as the window's own are, after a page
+freeze too.
+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/animated-properties.ts b/internal/interaction-harness/src/animated-properties.ts
new file mode 100644
index 0000000000..6c25b3279b
--- /dev/null
+++ b/internal/interaction-harness/src/animated-properties.ts
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file animated-properties.ts
+ * @input The Web Animations API and the page's style sheets
+ * @output `defineAnimatedProperties`, a page function. It installs
+ * `window.__harnessAnimatedProperties(animation)` once: the properties the
+ * animation sets, as `getKeyframes()` names them. It also installs
+ * `window.__harnessAnimates(animation, property)`: whether the animation
+ * sets a property named as CSS names it.
+ * @position Shared by ./curves.ts (a hold's judged motions) and ./busy.ts
+ * (`blockMainThread`'s `property`), so both match a property 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.__harnessAnimatedProperties(animation)` and
+ * `window.__harnessAnimates(animation, property)` in the page, once. A page
+ * function: it closes over nothing.
+ */
+export function defineAnimatedProperties(): void {
+ const w = window as unknown as {
+ __harnessAnimatedProperties?: (animation: Animation) => string[];
+ __harnessAnimates?: (animation: Animation, property: string) => boolean;
+ };
+ if (w.__harnessAnimatedProperties) {
+ return;
+ }
+ // `getKeyframes()` names a property in camel case, except a custom
+ // property.
+ const keyframeName = (property: string) =>
+ property.startsWith('--')
+ ? property
+ : property.replace(/-([a-z])/g, (_, letter: string) =>
+ letter.toUpperCase(),
+ );
+ // Chromium's `getKeyframes()` leaves out a custom property that a CSS
+ // animation animates. The `@keyframes` rule of that name lists it. The
+ // rule can sit inside a grouping rule (`@layer`, `@media`).
+ const keyframesRules = (rules: readonly CSSRule[]): CSSKeyframesRule[] =>
+ rules.flatMap(rule =>
+ rule instanceof CSSKeyframesRule
+ ? [rule]
+ : rule instanceof CSSGroupingRule
+ ? keyframesRules([...rule.cssRules])
+ : [],
+ );
+ const ruleProperties = (name: string) =>
+ [...document.styleSheets, ...document.adoptedStyleSheets].flatMap(sheet => {
+ let rules: CSSRule[] = [];
+ try {
+ rules = [...sheet.cssRules];
+ } catch {
+ // A cross-origin sheet does not expose its rules.
+ }
+ return keyframesRules(rules)
+ .filter(rule => rule.name === name)
+ .flatMap(rule =>
+ [...rule.cssRules].flatMap(keyframe => [
+ ...(keyframe as CSSKeyframeRule).style,
+ ]),
+ );
+ });
+ // A keyframe also names its offset, easing and composite. These are not
+ // properties the animation sets.
+ const timingKeys = new Set([
+ 'offset',
+ 'computedOffset',
+ 'easing',
+ 'composite',
+ ]);
+ const properties = (animation: Animation) => [
+ ...new Set([
+ ...((animation.effect as KeyframeEffect | null)?.getKeyframes() ?? [])
+ .flatMap(keyframe => Object.keys(keyframe))
+ .filter(name => !timingKeys.has(name)),
+ ...(animation instanceof CSSAnimation
+ ? ruleProperties(animation.animationName).map(keyframeName)
+ : []),
+ ]),
+ ];
+ w.__harnessAnimatedProperties = properties;
+ w.__harnessAnimates = (animation, property) =>
+ properties(animation).includes(keyframeName(property));
+}
diff --git a/internal/interaction-harness/src/busy.ts b/internal/interaction-harness/src/busy.ts
index b1959a97aa..dc272dcfcf 100644
--- a/internal/interaction-harness/src/busy.ts
+++ b/internal/interaction-harness/src/busy.ts
@@ -25,6 +25,7 @@
*/
import type {Locator, Page} from '@playwright/test';
+import {defineAnimatedProperties} from './animated-properties';
import {defineCurveEnd} from './curve-end';
import {
frameStats,
@@ -375,6 +376,13 @@ export interface BlockedWindow extends BusyWindow {
* it started and ended on. It is never less than the time asked for.
*/
readonly spanMs: number;
+ /**
+ * With `during`: the animation the block caught, epoch ms on the page's
+ * clock. `from` is its start, and `to` is where its curve ends, its held
+ * tail excluded. It is absent when the animation's `playbackRate` is 0 or
+ * less, since its curve then has no forward end.
+ */
+ readonly animation?: {readonly from: number; readonly to: number};
}
/**
@@ -402,12 +410,22 @@ export interface BlockedWindow extends BusyWindow {
* With `pseudoElement`, only that pseudo-element's animations on `during`
* itself count, as `sampleCurve` reads them. A child's animation, such as a
* switch thumb's press, then does not start the block.
+ * With `property`, only animations that set that property count, named as
+ * CSS names it (`translate`, `background-color`, `--press-strength`), as a
+ * hold's judged motion names it.
+ * A thumb's `translate` travel then starts the block, and its press `scale`
+ * does not.
*
* An animation counts once it is no longer pending and has run at least one
* frame (`minProgressMs` below 16 ms is raised to 16). One created in the
* 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 must also be the same animation the page saw at its frame before. A
+ * component can rebuild a running animation on its old clock. The page then
+ * sees it running and not pending, before the compositor shows a frame of it,
+ * so the block waits one frame more. An animation rebuilt at every frame never
+ * qualifies: at the timeout the wait rejects and names that.
*
* 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`
@@ -415,6 +433,10 @@ export interface BlockedWindow extends BusyWindow {
* 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.
+ *
+ * The window it resolves with names the animation it caught (`animation`):
+ * when it started and where its curve ends. These times are on the real
+ * clock, as the window's own are, after a page freeze too.
*/
/** One display frame, ms: the least progress `blockMainThread` waits for. */
const ONE_FRAME_MS = 16;
@@ -446,11 +468,13 @@ export async function blockMainThread(
{
during,
minProgressMs = 16,
+ property,
pseudoElement,
timeout = 5_000,
}: {
during?: Locator;
minProgressMs?: number;
+ property?: string;
pseudoElement?: '::before' | '::after';
timeout?: number;
} = {},
@@ -461,6 +485,11 @@ export async function blockMainThread(
'blockMainThread: pseudoElement names a part of `during`; pass `during` too',
);
}
+ if (property != null && during == null) {
+ throw new TypeError(
+ 'blockMainThread: property picks an animation of `during`; pass `during` too',
+ );
+ }
if (during == null) {
return page.evaluate(duration => {
// The harness's own work: a trace sets it apart (trace.ts HARNESS_READ).
@@ -491,11 +520,14 @@ export async function blockMainThread(
};
}, ms);
}
- // 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);
+ // The wait reads the curve end and the property match, defined in the page
+ // first. Both are sent before the wait and not awaited: the wait starts no
+ // later than before.
+ const defined = page.evaluate(
+ `(${defineCurveEnd.toString()})();(${defineAnimatedProperties.toString()})();`,
+ );
const waited = during.evaluate(
- (element, {duration, minProgress, pseudo, wait}) =>
+ (element, {duration, minProgress, prop, pseudo, wait}) =>
new Promise<BlockedWindow>((resolve, reject) => {
// The harness's own waits run on the real timers: a frozen timer gate
// (story.ts) holds only the page's.
@@ -521,17 +553,27 @@ export async function blockMainThread(
target.closest('[data-harness-control]') != null
);
};
- // With a pseudo-element, only its own animations on the element.
+ // With a pseudo-element, only its own animations on the element; with
+ // a property, only animations that set it, matched as a hold's judged
+ // motion is.
+ const animates = (
+ window as unknown as {
+ __harnessAnimates: (a: Animation, property: string) => boolean;
+ }
+ ).__harnessAnimates;
const counts = (a: Animation) => {
if (isControl(a)) {
return false;
}
const effect = a.effect as KeyframeEffect | null;
- return (
- pseudo == null ||
- (effect?.target === element &&
- (effect.pseudoElement ?? null) === pseudo)
- );
+ if (
+ pseudo != null &&
+ (effect?.target !== element ||
+ (effect.pseudoElement ?? null) !== pseudo)
+ ) {
+ return false;
+ }
+ return prop == null || animates(a, prop);
};
// Where each animation's curve ends, its held tail excluded.
const curveEnd =
@@ -561,21 +603,25 @@ export async function blockMainThread(
let heldSeen: ReturnType<typeof numbersOf> | null = null;
const tooLate = (numbers: ReturnType<typeof numbersOf>) =>
new Error(`BusyWindowTooLate ${JSON.stringify(numbers)}`);
+ // The animations that counted at the frame before, pending ones too.
+ let seen = new Set<Animation>();
const tick = () => {
- const ran = element
- .getAnimations({subtree: true})
- .filter(
- a =>
- counts(a) &&
- a.playState === 'running' &&
- !a.pending &&
- Number(a.currentTime ?? 0) >= minProgress,
- );
+ const present = element.getAnimations({subtree: true}).filter(counts);
+ const ran = present.filter(
+ 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),
- );
+ const moves = (a: Animation) =>
+ a.playbackRate < 0 || Number(a.currentTime ?? 0) < curveEnd(a);
+ const running = ran.some(moves);
+ // One first seen this frame can be rebuilt on its old clock, and not
+ // on the compositor yet: the block waits for the next frame.
+ const caught = ran.find(a => moves(a) && seen.has(a));
+ seen = new Set(present);
if (!running && ran.length > 0) {
heldSeen ??= numbersOf(ran[0]);
}
@@ -584,7 +630,18 @@ export async function blockMainThread(
const late = ran.find(a => !before.has(a));
const timedOut = realNow() > deadline;
const leftover = ran.length > 0 ? numbersOf(ran[0]) : heldSeen;
- if (running) {
+ if (caught != null) {
+ const startTime = caught.startTime;
+ // A start time is a page time. It trails the real clock, which the
+ // window reads, by every span a page freeze stood still.
+ const frozen =
+ (window as unknown as {__harnessFreeze?: {offset: number}})
+ .__harnessFreeze?.offset ?? 0;
+ const from = performance.timeOrigin + Number(startTime) + frozen;
+ const animation =
+ startTime != null && caught.playbackRate > 0
+ ? {from, to: from + curveEnd(caught) / caught.playbackRate}
+ : undefined;
// 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
// handed the animation to the compositor.
@@ -599,8 +656,19 @@ export async function blockMainThread(
from: performance.timeOrigin + start,
to: performance.timeOrigin + now,
spanMs: now - start,
+ ...(animation == null ? {} : {animation}),
});
}, 0);
+ } else if (running) {
+ if (timedOut) {
+ reject(
+ new Error(
+ 'blockMainThread: no animation of `during` ran on two frames in a row',
+ ),
+ );
+ } else {
+ frame(tick);
+ }
} else if (late != null) {
reject(tooLate(numbersOf(late)));
} else if (timedOut && leftover != null) {
@@ -613,7 +681,13 @@ export async function blockMainThread(
};
frame(tick);
}),
- {duration: ms, minProgress, pseudo: pseudoElement ?? null, wait: timeout},
+ {
+ duration: ms,
+ minProgress,
+ prop: property ?? null,
+ pseudo: pseudoElement ?? null,
+ wait: timeout,
+ },
);
try {
const [, held] = await Promise.all([defined, waited]);
diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.ts
index 58cda652a1..3d97fcae88 100644
--- a/internal/interaction-harness/src/curves.ts
+++ b/internal/interaction-harness/src/curves.ts
@@ -24,6 +24,7 @@
*/
import type {Locator, Page} from '@playwright/test';
+import {defineAnimatedProperties} from './animated-properties';
import {defineCurveEnd} from './curve-end';
import {FRAME_STARVATION_MS, FrameStarvationError} from './frames';
import {parseTransform, type TimedValue, type Transform2D} from './math';
@@ -497,10 +498,11 @@ async function installRecorder(page: Page): Promise<void> {
*/
async function installCurveEnd(page: Page): Promise<void> {
await installRecorder(page);
- // 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.
+ // The hold is installed with the curve end it reads and the property match
+ // of its judged motions. One round trip installs all three, so a hold sent
+ // from the test costs no extra one.
await page.evaluate(
- `(${defineCurveEnd.toString()})();(${defineHold.toString()})();`,
+ `(${defineCurveEnd.toString()})();(${defineHold.toString()})();(${defineAnimatedProperties.toString()})();`,
);
}
@@ -987,61 +989,11 @@ async function expectJudgedMotionsHeld(
([armed, elements, wanted]) => {
const w = window as unknown as {
__harnessTook?: Record<number, Animation[]>;
+ __harnessAnimatedProperties: (animation: Animation) => string[];
+ __harnessAnimates: (animation: Animation, property: string) => boolean;
};
const animations = w.__harnessTook?.[armed] ?? [];
delete w.__harnessTook?.[armed];
- // `getKeyframes()` names a property in camel case, except a custom
- // property.
- const keyframeName = (property: string) =>
- property.startsWith('--')
- ? property
- : property.replace(/-([a-z])/g, (_, letter: string) =>
- letter.toUpperCase(),
- );
- // Chromium's `getKeyframes()` leaves out a custom property that a CSS
- // animation animates. The `@keyframes` rule of that name lists it. The
- // rule can sit inside a grouping rule (`@layer`, `@media`).
- const keyframesRules = (rules: readonly CSSRule[]): CSSKeyframesRule[] =>
- rules.flatMap(rule =>
- rule instanceof CSSKeyframesRule
- ? [rule]
- : rule instanceof CSSGroupingRule
- ? keyframesRules([...rule.cssRules])
- : [],
- );
- const ruleProperties = (name: string) =>
- [...document.styleSheets, ...document.adoptedStyleSheets].flatMap(
- sheet => {
- let rules: CSSRule[] = [];
- try {
- rules = [...sheet.cssRules];
- } catch {
- // A cross-origin sheet does not expose its rules.
- }
- return keyframesRules(rules)
- .filter(rule => rule.name === name)
- .flatMap(rule =>
- [...rule.cssRules].flatMap(keyframe => [
- ...(keyframe as CSSKeyframeRule).style,
- ]),
- );
- },
- );
- const properties = (animation: Animation) => [
- ...new Set([
- ...((animation.effect as KeyframeEffect | null)?.getKeyframes() ?? [])
- .flatMap(keyframe => Object.keys(keyframe))
- .filter(
- name =>
- !['offset', 'computedOffset', 'easing', 'composite'].includes(
- name,
- ),
- ),
- ...(animation instanceof CSSAnimation
- ? ruleProperties(animation.animationName).map(keyframeName)
- : []),
- ]),
- ];
const describe = (animation: Animation) => {
const effect = animation.effect as KeyframeEffect | null;
const target = effect?.target ?? null;
@@ -1053,7 +1005,7 @@ async function expectJudgedMotionsHeld(
(target.classList.length
? `.${[...target.classList].slice(0, 2).join('.')}`
: '');
- return `${name}${effect?.pseudoElement ?? ''} ${properties(animation).join(' ')}`;
+ return `${name}${effect?.pseudoElement ?? ''} ${w.__harnessAnimatedProperties(animation).join(' ')}`;
};
return {
missing: wanted.flatMap((motion, index) =>
@@ -1063,7 +1015,7 @@ async function expectJudgedMotionsHeld(
effect != null &&
effect.target === elements[index] &&
(effect.pseudoElement ?? null) === motion.pseudoElement &&
- properties(animation).includes(keyframeName(motion.property))
+ w.__harnessAnimates(animation, motion.property)
);
})
? []
diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
index 55235b0e35..f593d0465e 100644
--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts
+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
@@ -6032,6 +6032,192 @@ test.describe('storyboards', {tag: '@storyboard'}, () => {
).rejects.toThrow(/pass `during` too/);
});
+ test('blockMainThread with during waits a frame for an animation rebuilt on its old clock, and names the animation it caught', async ({
+ page,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ // When each of the page's frames ran, page ms.
+ await page.evaluate(() => {
+ const w = window as unknown as {frameTimes: number[]};
+ w.frameTimes = [];
+ const count = () => {
+ w.frameTimes.push(performance.now());
+ requestAnimationFrame(count);
+ };
+ requestAnimationFrame(count);
+ });
+ const blocking = blockMainThread(page, 100, {during: box, timeout: 3_000});
+ await page.waitForTimeout(100);
+ // A travel rebuilt 200 ms into its curve, between two frames: the page
+ // first sees it running and not pending.
+ const rebuilt = await box.evaluate(
+ el =>
+ new Promise<{framesBefore: number; startTime: number}>(resolve => {
+ setTimeout(() => {
+ const run = el.animate(
+ [{translate: '0 0'}, {translate: '200px 0'}],
+ {duration: 1_000, easing: 'linear'},
+ );
+ run.startTime = Number(document.timeline.currentTime) - 200;
+ resolve({
+ framesBefore: (window as unknown as {frameTimes: number[]})
+ .frameTimes.length,
+ startTime: Number(run.startTime),
+ });
+ }, 0);
+ }),
+ );
+ const held = await blocking;
+ // Frames that ran after the travel was built and up to the block. WebKit
+ // reads its clock to the millisecond, so a frame can share the block's
+ // start time. That frame still ran before the block, which no frame
+ // interrupts.
+ const framesBefore = await page.evaluate(
+ ([first, from]) =>
+ (window as unknown as {frameTimes: number[]}).frameTimes
+ .slice(first)
+ .filter(t => t <= from - performance.timeOrigin).length,
+ [rebuilt.framesBefore, held.from] as const,
+ );
+ // The frame that first saw it, and the frame after, ran before the block.
+ expect(framesBefore).toBeGreaterThanOrEqual(2);
+ // The window names that animation: its start, and its curve's end.
+ const timeOrigin = await page.evaluate(() => performance.timeOrigin);
+ const caught = held.animation;
+ expect(caught).toBeDefined();
+ expect(caught?.from).toBeCloseTo(timeOrigin + rebuilt.startTime, 3);
+ expect((caught?.to ?? 0) - (caught?.from ?? 0)).toBeCloseTo(1_000, 3);
+ });
+
+ test('blockMainThread with during and a property starts on an animation of that property, not on an earlier one of another', async ({
+ page,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ const blocking = blockMainThread(page, 100, {
+ during: box,
+ property: 'translate',
+ minProgressMs: 50,
+ timeout: 3_000,
+ });
+ await page.waitForTimeout(100);
+ // A press scale starts first, and the travel 300 ms after it.
+ const travelStartedAt = await box.evaluate(async el => {
+ el.animate([{scale: '1'}, {scale: '0.9'}], {
+ duration: 1_000,
+ fill: 'forwards',
+ });
+ await new Promise(resolve => setTimeout(resolve, 300));
+ el.animate([{translate: '0 0'}, {translate: '200px 0'}], {
+ duration: 1_000,
+ });
+ return performance.timeOrigin + performance.now();
+ });
+ const held = await blocking;
+ // The block began once the travel had run 50 ms, never on the scale.
+ expect(held.from).toBeGreaterThanOrEqual(travelStartedAt + 50);
+ // A property picks an animation of `during`, so it needs one.
+ await expect(
+ blockMainThread(page, 100, {property: 'translate'}),
+ ).rejects.toThrow(/pass `during` too/);
+ });
+
+ test('blockMainThread with during takes a property as CSS names it, a custom property too, and offset names no animation', async ({
+ page,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ const colour = blockMainThread(page, 50, {
+ during: box,
+ property: 'background-color',
+ minProgressMs: 50,
+ timeout: 3_000,
+ });
+ await box.evaluate(el => {
+ el.animate(
+ [
+ {backgroundColor: 'rgb(255, 0, 0)'},
+ {backgroundColor: 'rgb(0, 0, 255)'},
+ ],
+ {duration: 1_000},
+ );
+ });
+ // The block waits for 50 ms of the colour by the colour's own clock,
+ // whether it watches before the animation starts or after.
+ const heldColour = await colour;
+ expect(heldColour.animation).toBeDefined();
+ expect(heldColour.from).toBeGreaterThanOrEqual(
+ (heldColour.animation?.from ?? Infinity) + 50,
+ );
+ // A custom property keeps its CSS name in the keyframes.
+ const press = blockMainThread(page, 50, {
+ during: box,
+ property: '--press-strength',
+ minProgressMs: 50,
+ timeout: 3_000,
+ });
+ await box.evaluate(el => {
+ el.animate([{'--press-strength': '0'}, {'--press-strength': '1'}], {
+ duration: 1_000,
+ });
+ });
+ const heldPress = await press;
+ expect(heldPress.animation).toBeDefined();
+ expect(heldPress.from).toBeGreaterThanOrEqual(
+ (heldPress.animation?.from ?? Infinity) + 50,
+ );
+ // Every keyframe names its offset, but no animation sets it. A long scale
+ // runs for the whole wait.
+ await box.evaluate(el => {
+ el.animate([{scale: '1'}, {scale: '0.9'}], {duration: 5_000});
+ });
+ await expect(
+ blockMainThread(page, 50, {
+ during: box,
+ property: 'offset',
+ timeout: 500,
+ }),
+ ).rejects.toThrow(/no animation started/);
+ });
+
+ test('blockMainThread with during names an animation rebuilt at every frame, which it never holds, at its timeout', async ({
+ page,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ // Each frame replaces the travel with a new one on the same clock, as an
+ // animator that rebuilds its run while it follows.
+ await box.evaluate(el => {
+ const w = window as unknown as {stopRebuilding?: boolean};
+ let start: number | null = null;
+ const rebuild = () => {
+ if (w.stopRebuilding === true) {
+ return;
+ }
+ for (const animation of el.getAnimations()) {
+ animation.cancel();
+ }
+ const run = el.animate([{translate: '0 0'}, {translate: '200px 0'}], {
+ duration: 5_000,
+ });
+ start ??= Number(document.timeline.currentTime);
+ run.startTime = start;
+ requestAnimationFrame(rebuild);
+ };
+ requestAnimationFrame(rebuild);
+ });
+ await expect(
+ blockMainThread(page, 100, {during: box, timeout: 600}),
+ ).rejects.toThrow(/no animation of `during` ran on two frames in a row/);
+ await box.evaluate(el => {
+ (window as unknown as {stopRebuilding?: boolean}).stopRebuilding = true;
+ for (const animation of el.getAnimations()) {
+ animation.cancel();
+ }
+ });
+ });
+
test('blockMainThread with during names a late block when the run it saw held ends before the wait times out', async ({
page,
}) => {
@@ -6973,6 +7159,34 @@ test.describe('page freeze', () => {
expect(blocked.to).toBeLessThan(after + 50);
});
+ test('after a thaw, blockMainThread with during stamps the animation it caught on the real clock', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await freezePage(page);
+ // The frozen span itself, which the page's clock then trails by.
+ await page.waitForTimeout(1_000);
+ await thawPage(page);
+ const box = page.locator('#box');
+ // The block catches the animation a frame or two after it starts, whether
+ // it watches before the animation starts or after.
+ const blocking = blockMainThread(page, 50, {during: box, timeout: 3_000});
+ await box.evaluate(el => {
+ el.animate([{translate: '0 0'}, {translate: '200px 0'}], {
+ duration: 1_000,
+ });
+ });
+ const held = await blocking;
+ // The page's own clock trails the real one by the 1 s frozen span. The
+ // block starts a frame or two after the animation, on either clock.
+ expect(held.animation).toBeDefined();
+ const sinceStart = held.from - (held.animation?.from ?? 0);
+ expect(sinceStart).toBeGreaterThanOrEqual(0);
+ expect(sinceStart).toBeLessThan(500);
+ });
+
test('after a thaw, waitForAnimation and sampleRects stamp on the real clock', async ({
page,
}) => {