An open source design system that's fully customizable and agent ready
TypeScript
fix(interaction): the animation recorder stands down while a trace runs (#8446)
Christopher Chedeau273031c7fcee
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex 3a85354968..224204cd66 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -283,8 +283,31 @@ after are the stall check's. WebKit has no such trace:**No Layout / Paint.** `traceRendering` records a Chromium trace around theinteraction; `countBetween` counts the steady middle of an animation (itsfirst and last frames may commit). A transform/opacity animation does no-Layout or Paint there; a layout-property animation does one per frame. Its-`longTasks` are the page's own: only a task the harness marked as its own read+Layout or Paint there; a layout-property animation does one per frame. The+harness's own animation recorder stands down while the trace runs, since its+frame loop would make every frame a main-thread one, restyling each running+animation's target and laying out an anchored one: it reads only the element a+CSS animation or transition event names, once, when that animation starts, and+catches up afterwards. A `waitForRest` awaited inside the traced body stands+down too: it waits on timers for the scheduled ends of the element's curves+(looking `frames` times a frame apart before settling on none, so an+animation the action starts a frame or two later is waited for) and polls no+style until the trace ends (in the anchored fixture's steady middle,+24 Layouts before, 0 now). Its one read of the element's animations, as it is+called, restyles the element (2 Layouts and 2 style recalculations in the+anchored fixture when called 200 ms into its animation), so await it right+after the action that starts the motion, before the window a proof counts. So do `waitForAnimation` and a watch's+`started()`: they take the element's animations from the recorder's log,+judge a started one by its own times, and reach the element through a handle,+since each `locator.evaluate` makes a main-thread frame (there too, 24+Layouts before, 0 now). That holds for script animations and CSS+transitions. On a CSS `@keyframes` animation (and, unwatched, a cancelled CSS+transition), `waitForAnimation` and `started()` read the animation's timing,+which flushes its style and adds Layouts to the trace: wait on one with+`waitForRest`, or after the trace. Taking a watch (`watchAnimations`) inside+a trace reads the watched element's animations, which restyles it (and lays+out an anchored one), so a proof takes its traced watch before the window it+counts. The trace's `longTasks` are the page's own: only a task the harness marked as its own read(`waitForAnimation` describing keyframes, `blockMainThread` without `during`)is in `devtoolsTasks` instead, and only when no page script ran inside it. Atest's own `page.evaluate` stays a long task, whether it calls page codediff --git a/internal/interaction-harness/src/curve-end.ts b/internal/interaction-harness/src/curve-end.tsindex 0a12ed2f8b..bf399e14ea 100644--- a/internal/interaction-harness/src/curve-end.ts+++ b/internal/interaction-harness/src/curve-end.ts@@ -5,7 +5,9 @@* @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.+ * included) where the animation's effect stops changing; and+ * `window.__harnessTiming(effect)`, the effect's timing, read without a+ * style update inside a rendering trace.* @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@@ -26,10 +28,46 @@export function defineCurveEnd(): void {const w = window as unknown as {__harnessCurveEnd?: (animation: Animation) => number;+ __harnessTiming?: (+ effect: AnimationEffect | null | undefined,+ ) => ComputedEffectTiming | null;+ };+ // An effect's timing as getComputedTiming() reports it. Inside a rendering+ // trace it is worked out from getTiming() instead: getComputedTiming()+ // updates a running animation on demand, which restyles its target in the+ // next frame (and lays out an anchored one), exactly what a trace counts.+ w.__harnessTiming ??= effect => {+ if (effect == null) {+ return null;+ }+ if (+ (window as unknown as {__harnessRenderingTrace?: boolean})+ .__harnessRenderingTrace !== true+ ) {+ return effect.getComputedTiming();+ }+ const timing = effect.getTiming();+ const duration = typeof timing.duration === 'number' ? timing.duration : 0;+ const iterations = Number(timing.iterations ?? 1);+ const delay = Number(timing.delay ?? 0);+ const endDelay = Number(timing.endDelay ?? 0);+ const activeDuration =+ duration === 0 || iterations === 0 ? 0 : duration * iterations;+ const derived: ComputedEffectTiming = {+ ...timing,+ duration,+ iterations,+ delay,+ endDelay,+ activeDuration,+ endTime: Math.max(delay + activeDuration + endDelay, 0),+ };+ return derived;};if (w.__harnessCurveEnd) {return;}+ const timingOf = w.__harnessTiming;const timingKeys = new Set(['offset','computedOffset',@@ -45,7 +83,7 @@ export function defineCurveEnd(): void {);w.__harnessCurveEnd = animation => {const effect = animation.effect as KeyframeEffect | null;- const timing = effect?.getComputedTiming();+ const timing = timingOf(effect);const delay = Number(timing?.delay ?? 0);const active = Number(timing?.activeDuration ?? 0);if (diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.tsindex d2e2bb6998..a60c059ba3 100644--- a/internal/interaction-harness/src/curves.ts+++ b/internal/interaction-harness/src/curves.ts@@ -203,15 +203,41 @@ function animationRecorder(): void {return entry.startedAt == null && entry.animation.playState !== 'idle';});};+ // While a rendering trace runs (traceRendering sets+ // `__harnessRenderingTrace`), the recorder stands down. Its per-frame+ // callback would make every frame a main-thread frame, in which Blink+ // restyles each running animation's target, a composited one included (and+ // lays out an anchored one), and document.getAnimations() flushes style:+ // exactly what the trace counts. So it runs no frame callback, and a CSS+ // animation or transition event reads only the animations of the element it+ // names, once, at that animation's start (one that ends inside the trace is+ // otherwise never seen). The animate() wrapper below still records script+ // animations (it reads no style), and traceRendering resumes the recorder+ // once the trace ends.+ const tracing = () =>+ (window as unknown as {__harnessRenderingTrace?: boolean})+ .__harnessRenderingTrace === true;+ let looping = false;const tick = () => {+ if (tracing()) {+ looping = false;+ return;+ }record();frame(tick);};+ const loop = () => {+ if (!looping) {+ looping = true;+ frame(tick);+ }+ };// What already runs when the recorder starts (a spinner on a page the// harness touches for the first time) is seen now, before any watch arms;// first seen a frame later, it would read as started by the watched action.+ // (A recorder that starts during a trace reads once here, then waits.)record();- frame(tick);+ loop();// A start event with nothing left to read: a CSS animation shorter than the// gap between two of the page's frames can start and finish inside it, and// WebKit sends its start event only at the next frame, when@@ -234,6 +260,20 @@ function animationRecorder(): void {);};const onStart = (event: Event) => {+ if (tracing()) {+ // Inside a trace, read only the element the event names, once: a+ // document-wide read flushes style.+ const target = event.target;+ if (target instanceof Element) {+ // A pseudo-element's animation (`::backdrop`) is in the subtree.+ const pseudo = (event as AnimationEvent | TransitionEvent)+ .pseudoElement;+ for (const animation of target.getAnimations({subtree: !!pseudo})) {+ remember(animation);+ }+ }+ return;+ }record();// Only a live run answers: a replay of an animation that finished on the// same element is a new run, and missed if nothing recorded it. A run the@@ -331,12 +371,36 @@ function animationRecorder(): void {w.__harnessAnimations = {log,unread,- record,+ // A read from outside the recorder (a wait's poll) stands down while a+ // trace runs, as the frame loop does: document.getAnimations() flushes+ // style. CSS start events and the animate() wrapper still log what+ // starts, and resume() catches up.+ record: () => {+ if (!tracing()) {+ record();+ }+ },+ // Catches up on what started during a trace, then runs its frames again.+ resume: () => {+ record();+ loop();+ },// Record first, then stamp strictly after the newest entry: a step that// changed style just before has its transition created by that read,- // and it started before the arm.- arm: () => {- record();+ // and it started before the arm. While a trace runs the page-wide read+ // stands down, as record() does; the watched element's own animations+ // are still read, which resolves its pending style change. That read+ // restyles the element (and lays out an anchored one) in the task that+ // takes the watch, so a traced proof takes its watch before the window+ // it counts (README: No Layout / Paint).+ arm: (element?: Element) => {+ if (!tracing()) {+ record();+ } else if (element != null) {+ for (const animation of element.getAnimations({subtree: true})) {+ remember(animation);+ }+ }const newest = log.length === 0 ? 0 : log[log.length - 1].seenAt;armedAt = Math.max(performance.now(), newest + 0.001);return armedAt;@@ -1111,6 +1175,47 @@ export interface ActiveAnimation {readonly finishedAt: number | null;}+/**+ * Runs `fn` on `locator`'s element: through the locator, or, `quietly`,+ * through a handle to the element it matches now (none yet: `[]`). Each+ * locator.evaluate makes a main-thread frame, which a trace counts;+ * `elementHandles()` and a handle's evaluate make none.+ */+async function readElement<A, R>(+ locator: Locator,+ quietly: boolean,+ fn: (element: Element, arg: A) => R[],+ arg: A,+ timeout: number,+): Promise<R[]> {+ const run = fn as unknown as (element: Element, arg: unknown) => R[];+ if (!quietly) {+ return locator.evaluate(run, arg as unknown, {timeout});+ }+ const handles = await locator.elementHandles();+ try {+ if (handles.length > 1) {+ throw new Error(+ `waitForAnimation: ${String(locator)} matches ${handles.length} elements`,+ );+ }+ return handles.length === 0+ ? []+ : await handles[0].evaluate(run, arg as unknown);+ } finally {+ await Promise.all(handles.map(handle => handle.dispose()));+ }+}++/** The rejection for a wait whose element is not in the document. */+function notInDocument(name: string, cause?: unknown): Error {+ return new Error(+ `${name}: the element is not in the document. An exit that removes ` ++ 'its element is read through its container (watch the parent).',+ cause === undefined ? undefined : {cause},+ );+}+/*** Runs a locator read within the wait's own deadline. A locator waits for* its element with no timeout of its own, so one the page removed (an exit@@ -1132,11 +1237,7 @@ async function withinTimeout<T>(if ((await locator.count()) > 0) {return null;}- throw new Error(- `${name}: the element is not in the document. An exit that removes ` +- 'its element is read through its container (watch the parent).',- {cause: error},- );+ throw notInDocument(name, error);}throw error;}@@ -1166,6 +1267,15 @@ async function withinTimeout<T>(* recorder keeps one entry per `Animation` object, so an animation reversed* or replayed mid-run is misread: a watch taken before the reversal rejects,* and an unwatched wait returns at once with a curve dated before it.+ *+ * Started inside a `traceRendering` body, it stands down as the recorder+ * does, so it adds no frame the trace counts: it takes the element's+ * animations from the recorder's log, judges a started one by its own times,+ * and reaches the element through a handle to what the locator matches at+ * each look. That holds for script animations and CSS transitions. On a CSS+ * `@keyframes` animation (and, unwatched, a cancelled CSS transition) it reads+ * the animation's timing, which flushes its style and adds Layouts to the+ * trace: wait on one with `waitForRest`, or after the trace.*/export async function waitForAnimation(locator: Locator,@@ -1181,19 +1291,34 @@ export async function waitForAnimation(} = {},): Promise<ActiveAnimation[]> {const deadline = Date.now() + timeout;- await installCurveEnd(locator.page());+ const page = locator.page();+ await installCurveEnd(page);+ // Inside a rendering trace the wait stands down (see the page function),+ // and it reads the element through handles: each locator.evaluate makes a+ // main-thread frame (a Layout of an anchored element), where a handle's+ // evaluate adds none.+ const traced = await page.evaluate(+ () =>+ (window as unknown as {__harnessRenderingTrace?: boolean})+ .__harnessRenderingTrace === true,+ );for (;;) {const read = await withinTimeout('waitForAnimation',locator,deadline,evaluateTimeout =>- locator.evaluate(+ readElement(+ locator,+ traced,(element, {minProgress, since: watchedFrom}) => {// The harness's own read: a trace sets it apart (trace.ts HARNESS_READ).console.timeStamp('harness-read');const w = window as unknown as {__harnessCurveEnd: (a: Animation) => number;+ __harnessTiming: (+ effect: AnimationEffect | null | undefined,+ ) => ComputedEffectTiming | null;__harnessAnimations: {log: {animation: Animation;@@ -1209,6 +1334,13 @@ export async function waitForAnimation(};const curveEnd = w.__harnessCurveEnd;const recorder = w.__harnessAnimations;+ // Inside a rendering trace the wait stands down as the recorder does:+ // record() reads nothing, the animations come from the recorder's log+ // rather than getAnimations(), and a started one runs by its own+ // times, since playState flushes a CSS animation's style.+ const traced =+ (window as unknown as {__harnessRenderingTrace?: boolean})+ .__harnessRenderingTrace === true;recorder.record();// The recorder keeps real times. A live start time is a page time.// It trails real time by the span a page freeze stood still, so it@@ -1224,7 +1356,7 @@ export async function waitForAnimation(finishStart: number | null = null,) => {const effect = a.effect as KeyframeEffect | null;- const timing = effect?.getComputedTiming();+ const timing = w.__harnessTiming(effect);// A finished run is dated from its start as its finish recorded// it: a later startTime read can say otherwise. The recorded// start stands in once the page has cancelled it. A run going@@ -1311,25 +1443,36 @@ export async function waitForAnimation(// finished must not answer for it. Only document-timeline animations// count, as for holdAnimations: a scroll- or view-timeline one moves// only when something scrolls and never progresses on its own.+ const runs = (a: Animation) => {+ if (!(a.timeline instanceof DocumentTimeline)) {+ return false;+ }+ if (!traced || a.startTime == null) {+ return a.playState === 'running';+ }+ const time = Number(a.currentTime ?? 0);+ return a.playbackRate < 0+ ? time > 0+ : time < Number(w.__harnessTiming(a.effect)?.endTime ?? 0);+ };+ const onElement = () =>+ recorder.log.filter(+ e => inside(e.animation) || e.ancestors.includes(element),+ );const live = (- watchedFrom == null+ watchedFrom == null && !traced? element.getAnimations({subtree: true})- : recorded+ : (watchedFrom == null ? onElement() : recorded).filter(e => e.finishedAt == null).map(e => e.animation)- ).filter(- a =>- !isControl(a) &&- a.playState === 'running' &&- a.timeline instanceof DocumentTimeline,- );+ ).filter(a => !isControl(a) && runs(a));const running = live.filter(a => a.startTime != null);// Progress along the curve, on the timeline: a delay presents nothing// (going backward, the end delay plays first), a run going backward// (`reverse()`) progresses from its end, and a faster rate presents// more curve per ms.const progressed = running.filter(a => {- const timing = a.effect?.getComputedTiming();+ const timing = w.__harnessTiming(a.effect);const time = Number(a.currentTime ?? 0);const local =a.playbackRate < 0@@ -1354,13 +1497,20 @@ export async function waitForAnimation(return e.finishedAt;}const a = e.animation;- if (a.playState !== 'finished' || a.startTime == null) {+ if (a.startTime == null) {+ return null;+ }+ const end = Number(w.__harnessTiming(a.effect)?.endTime ?? 0);+ // Traced, by its own times; otherwise by its state.+ const time = Number(a.currentTime ?? 0);+ const done = traced+ ? a.playbackRate < 0+ ? time <= 0+ : time >= end+ : a.playState === 'finished';+ if (!done) {return null;}- const end = Number(- (a.effect as KeyframeEffect | null)?.getComputedTiming()- .endTime ?? 0,- );return (span +(a.playbackRate < 0@@ -1380,7 +1530,7 @@ export async function waitForAnimation();},{minProgress: minProgressMs, since: since ?? null},- {timeout: evaluateTimeout},+ evaluateTimeout,),);const found = read ?? [];@@ -1389,6 +1539,12 @@ export async function waitForAnimation(return found;}if (Date.now() > deadline) {+ // A traced read goes through handles, which find no element rather+ // than wait for one: a missing element is reported as missing, as the+ // untraced read reports it.+ if (traced && (await locator.count()) === 0) {+ throw notInDocument('waitForAnimation');+ }// Start events on the element that found nothing to read: animations// that started and finished between two of the page's frames.const missed = await locator@@ -1449,13 +1605,31 @@ export async function releaseAnimationLog(page: Page): Promise<void> {);}-/** Marks now as the point later waits count animations from. */-async function armRecorder(page: Page): Promise<number> {- return page.evaluate(() =>- (- window as unknown as {__harnessAnimations: {arm: () => number}}- ).__harnessAnimations.arm(),- );+/**+ * Marks now as the point later waits count animations from. With a locator,+ * its element's pending style change is resolved first, also inside a trace+ * (reached through a handle, which adds no main-thread frame).+ */+async function armRecorder(page: Page, locator?: Locator): Promise<number> {+ const handles = locator == null ? [] : await locator.elementHandles();+ try {+ if (handles.length === 1) {+ return await handles[0].evaluate(element =>+ (+ window as unknown as {+ __harnessAnimations: {arm: (element?: Element) => number};+ }+ ).__harnessAnimations.arm(element as Element),+ );+ }+ return await page.evaluate(() =>+ (+ window as unknown as {__harnessAnimations: {arm: () => number}}+ ).__harnessAnimations.arm(),+ );+ } finally {+ await Promise.all(handles.map(handle => handle.dispose()));+ }}export interface AnimationWatch {@@ -1473,7 +1647,9 @@ export interface AnimationWatch {/*** Starts watching `locator`'s element before an action, so the animation the* action starts is caught even when it ends before the test looks (a short- * entrance on a cold page):+ * entrance on a cold page). Taking the watch reads the element's animations,+ * which restyles it, inside a rendering trace too: take a traced watch before+ * the window the proof counts:** const watch = await watchAnimations(sheet);* await driver.play(tap(button));@@ -1483,7 +1659,7 @@ export async function watchAnimations(locator: Locator,): Promise<AnimationWatch> {await installCurveEnd(locator.page());- const since = await armRecorder(locator.page());+ const since = await armRecorder(locator.page(), locator);return {started: options => waitForAnimation(locator, {...options, since}),};@@ -1502,6 +1678,19 @@ export async function watchAnimations(* forward run under a linear or cubic-bézier effect easing); under any other* easing or direction, waitForRest waits the hold out, and a hold longer than* `timeout` rejects with "still moving".+ *+ * While a rendering trace runs (`traceRendering`), it stands down as the+ * animation recorder does: a per-frame callback would make every frame a+ * main-thread frame, which the trace counts. It then waits on timers for the+ * scheduled ends of the curves on the element instead (a run going backward,+ * until it finishes), so motion that no animation drives (a script writing+ * styles) is not seen until the trace ends. Its one read of the element's+ * animations, as it is called, restyles the element (and lays out an anchored+ * one) when an animation is already running there: await it right after the+ * action that starts the motion, before the window a proof counts, not in its+ * middle (README: No Layout / Paint). Finding no animation, it looks again `frames` times a frame+ * apart before settling, so one the action starts a few frames later is+ * waited for.*/export async function waitForRest(locator: Locator,@@ -1542,15 +1731,94 @@ export async function waitForRest(backdrop,].join(' | ');};- // The page's real frames, even while a timer gate holds its callbacks.- const frame =+ // The page's real frames and timers, even while a timer gate holds+ // its callbacks: a frozen gate never holds the wait itself.+ const gate = (+ window as unknown as {+ __harnessTimerGate?: {+ frame: typeof requestAnimationFrame;+ timeout?: typeof setTimeout;+ };+ }+ ).__harnessTimerGate;+ const frame = gate?.frame ?? requestAnimationFrame;+ const timeout = gate?.timeout ?? setTimeout;+ // Set by traceRendering while it traces (see the recorder above).+ const tracing = () =>+ (window as unknown as {__harnessRenderingTrace?: boolean})+ .__harnessRenderingTrace === true;+ const settle = () => {+ // Later waits count animations from here.(- window as unknown as {- __harnessTimerGate?: {frame: typeof requestAnimationFrame};- }- ).__harnessTimerGate?.frame ?? requestAnimationFrame;- let last = read();+ window as unknown as {__harnessAnimations?: {arm: () => number}}+ ).__harnessAnimations?.arm();+ resolve();+ };+ let last = '';let still = 0;+ const frames = () => {+ last = read();+ still = 0;+ frame(tick);+ };+ // While traced: one look at the animations, then a timer to the latest+ // scheduled curve end. One not started yet is looked at again a frame+ // later; a trace that has ended hands over to the per-frame check.+ // Finding nothing settles only after `frames` looks a frame apart, as+ // the per-frame check needs `frames` still frames: an animation the+ // action starts a frame or two later is still waited for.+ let idle = 0;+ const scheduled = () => {+ let wait = 0;+ for (const a of element.getAnimations({subtree: true})) {+ // A scroll- or view-timeline animation moves only when something+ // scrolls: it has no scheduled end to wait for (holdAnimations+ // skips it the same way).+ if (!(a.timeline instanceof DocumentTimeline)) {+ continue;+ }+ if (+ a.pending ||+ (a.playState === 'running' && a.startTime == null)+ ) {+ wait = Math.max(wait, 16);+ } else if (a.playState === 'running') {+ // The curve's time left through the playback rate: forward, to+ // its (held) end; backward (`reverse()`), to local time 0,+ // where it finishes, as the untraced path waits it out.+ const rate = a.playbackRate || 1;+ const at = Number(a.currentTime ?? 0);+ const left =+ rate > 0 ? (curveEnd(a) - at) / rate : at / -rate;+ wait = Math.max(wait, left);+ }+ }+ if (wait <= 0) {+ idle += 1;+ if (idle >= need) {+ settle();+ return;+ }+ wait = 16;+ } else {+ idle = 0;+ }+ const room = deadline - realNow();+ timeout(+ () => {+ if (realNow() > deadline) {+ reject(+ new Error('waitForRest: still moving at the deadline'),+ );+ } else if (tracing()) {+ scheduled();+ } else {+ frames();+ }+ },+ Math.min(wait, Math.max(0, room)) + 1,+ );+ };const tick = () => {const now = read();const moving = element.getAnimations({subtree: true}).some(@@ -1567,20 +1835,20 @@ export async function waitForRest(still = !moving && now === last ? still + 1 : 0;last = now;if (still >= need) {- // Later waits count animations from here.- (- window as unknown as {- __harnessAnimations?: {arm: () => number};- }- ).__harnessAnimations?.arm();- resolve();+ settle();} else if (realNow() > deadline) {reject(new Error(`waitForRest: still moving (${now})`));+ } else if (tracing()) {+ scheduled();} else {frame(tick);}};- frame(tick);+ if (tracing()) {+ scheduled();+ } else {+ frames();+ }}),{ms: timeout, need: frames},{timeout: evaluateTimeout},diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.tsindex 9bf03eefcd..f1735bdfbb 100644--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts@@ -12,9 +12,11 @@* a pinch arrive as distinct pointers; the screencast shows a compositor* animation advancing through a blocked main thread while a rAF animation* freezes; the trace counts zero Layout for a transform animation and one- * per frame for a `top` animation; the long-task log records the page's- * own long task but not a DevTools evaluate, which the trace counts;- * sampled curves+ * per frame for a `top` animation, and none from the harness's own+ * animation recorder while an anchored element's composited animation runs+ * (a page that asks for a frame every frame lays it out in each); the+ * long-task log records the page's own long task but not a DevTools+ * evaluate, which the trace counts; sampled curves* match the oracles, individual transform properties included; a sample at* an end reports the time it was read at; holding takes only running* document-timeline animations, each at its own offset, holds each where it@@ -23,7 +25,10 @@* animation-state waits report a running transition and its end, and judge* rest by presented values even while an animation holds its end, and a* watch taken on first contact ignores an animation already running and- * keeps the start of one the page cancels when it ends; storyboards write a+ * keeps the start of one the page cancels when it ends, and the recorder+ * reads only at CSS starts while a rendering trace runs and catches up+ * after it;+ * storyboards write a* sheet and a trace that follows the curve, an endless animation does not* set their length, and a photograph Chromium returns empty is taken again* two frames later; a touch filmstrip keeps scripted event times while a@@ -116,6 +121,16 @@ import {writeEvidence,} from './index';+// An element positioned against an anchor: a composited animation of it lays+// out in every main-thread frame, so it shows any per-frame main-thread work.+const ANCHORED = `<!doctype html><meta name=viewport content="width=device-width,initial-scale=1">+<style>+ body { margin: 0; }+ #anchor { position: absolute; top: 100px; left: 20px; width: 80px; height: 40px; anchor-name: --a; }+ #pop { position: fixed; position-anchor: --a; top: anchor(bottom); left: anchor(left); width: 160px; height: 120px; background: #c33; }+</style>+<button id=anchor>open</button><div id=pop></div>`;+const FIXTURE = `<!doctype html><meta name=viewport content="width=device-width,initial-scale=1"><style>body { margin: 0; font: 14px sans-serif; background: #fff; }@@ -1383,6 +1398,343 @@ test.describe('frame evidence', () => {expect(top.counts.Layout ?? 0).toBeGreaterThanOrEqual(top.frames - 1);});+ test("the trace counts no Layout from the harness's own animation recorder, which stands down while it runs", async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await page.route('http://anchored.test/', route =>+ route.fulfill({contentType: 'text/html', body: ANCHORED}),+ );+ await page.goto('http://anchored.test/');+ const pop = page.locator('#pop');+ // The recorder runs, as in any spec that waited for an animation first.+ await waitForRest(pop);+ const watch = await watchAnimations(pop);+ const middle = async (askEveryFrame: boolean) => {+ let started = 0;+ const trace = await traceRendering(page, async () => {+ started = await pop.evaluate((el, every) => {+ const w = window as unknown as {stop?: boolean};+ w.stop = false;+ if (every) {+ const ask = () => {+ if (!w.stop) {+ requestAnimationFrame(ask);+ }+ };+ requestAnimationFrame(ask);+ }+ el.animate(+ [+ {transform: 'translateY(0px)', opacity: 1},+ {transform: 'translateY(100px)', opacity: 0.5},+ ],+ {duration: 600},+ );+ return performance.timeOrigin + performance.now();+ }, askEveryFrame);+ await page.waitForTimeout(700);+ await page.evaluate(() => {+ (window as unknown as {stop?: boolean}).stop = true;+ });+ });+ // The steady middle: starting and ending it may lay out once each.+ return countBetween(trace, started + 100, started + 500);+ };+ expect((await middle(false)).Layout ?? 0).toBe(0);+ // Control: a page that asks for a frame every frame lays it out in each.+ expect((await middle(true)).Layout ?? 0).toBeGreaterThan(18);+ // Nothing the traces ran went unrecorded.+ const started = await watch.started();+ expect(started.map(a => a.durationMs)).toEqual([600, 600]);+ });++ test('a waitForRest awaited inside a traced body stands down too, so the trace counts no Layout from it', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await page.route('http://anchored.test/', route =>+ route.fulfill({contentType: 'text/html', body: ANCHORED}),+ );+ await page.goto('http://anchored.test/');+ const pop = page.locator('#pop');+ await waitForRest(pop);+ let started = 0;+ const trace = await traceRendering(page, async () => {+ started = await pop.evaluate(el => {+ el.animate(+ [+ {transform: 'translateY(0px)', opacity: 1},+ {transform: 'translateY(100px)', opacity: 0.5},+ ],+ {duration: 600},+ );+ return performance.timeOrigin + performance.now();+ });+ // A per-frame wait here would make every frame a main-thread frame.+ await waitForRest(pop);+ });+ expect(countBetween(trace, started + 100, started + 500).Layout ?? 0).toBe(+ 0,+ );+ // It still waited for the curve to end.+ expect(trace.window.to - started).toBeGreaterThanOrEqual(590);+ });++ test('a waitForAnimation or watch.started() awaited inside a traced body stands down too, so the trace counts no Layout from it', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await page.route('http://anchored.test/', route =>+ route.fulfill({contentType: 'text/html', body: ANCHORED}),+ );+ await page.goto('http://anchored.test/');+ const pop = page.locator('#pop');+ await waitForRest(pop);+ const watch = await watchAnimations(pop);+ let started = 0;+ let waited: {durationMs: number}[] = [];+ let watched: {durationMs: number}[] = [];+ const trace = await traceRendering(page, async () => {+ started = await pop.evaluate(el => {+ el.animate(+ [+ {transform: 'translateY(0px)', opacity: 1},+ {transform: 'translateY(100px)', opacity: 0.5},+ ],+ {duration: 600},+ );+ return performance.timeOrigin + performance.now();+ });+ // Both poll until 450 ms of the curve has played, across the steady+ // middle; a read of the page's animations each time would lay it out.+ waited = await waitForAnimation(pop, {minProgressMs: 450});+ watched = await watch.started({minProgressMs: 450});+ await page.waitForTimeout(200);+ });+ expect(countBetween(trace, started + 100, started + 500).Layout ?? 0).toBe(+ 0,+ );+ // Each still answered with the animation once 450 ms of it had played.+ expect(waited.map(a => a.durationMs)).toEqual([600]);+ expect(watched.map(a => a.durationMs)).toEqual([600]);+ expect(trace.window.to - started).toBeGreaterThanOrEqual(590);+ });++ test('a waitForRest awaited inside a traced body waits for an animation the action starts two frames later', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await page.route('http://anchored.test/', route =>+ route.fulfill({contentType: 'text/html', body: ANCHORED}),+ );+ await page.goto('http://anchored.test/');+ const pop = page.locator('#pop');+ await waitForRest(pop);+ const trace = await traceRendering(page, async () => {+ // The action starts the animation two frames later, as a component's+ // effect often does.+ await pop.evaluate(el => {+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ (window as unknown as {__started: number}).__started =+ performance.timeOrigin + performance.now();+ el.animate(+ [+ {transform: 'translateY(0px)'},+ {transform: 'translateY(100px)'},+ ],+ {duration: 600},+ );+ }),+ );+ });+ await waitForRest(pop);+ });+ const started = await page.evaluate(+ () => (window as unknown as {__started?: number}).__started ?? null,+ );+ // The traced window holds the whole animation.+ expect(started).not.toBeNull();+ expect(trace.window.to - (started as number)).toBeGreaterThanOrEqual(590);+ });++ test('a waitForRest awaited inside a traced body waits for a run going backward to its end, and no longer', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await page.route('http://anchored.test/', route =>+ route.fulfill({contentType: 'text/html', body: ANCHORED}),+ );+ await page.goto('http://anchored.test/');+ const pop = page.locator('#pop');+ await waitForRest(pop);+ // How long a traced waitForRest holds after a 600 ms move starts.+ const traced = async (reverse: boolean, endDelay = 0) => {+ let started = 0;+ const trace = await traceRendering(page, async () => {+ started = await pop.evaluate(+ (el, {reverse, endDelay}) => {+ const run = el.animate(+ [+ {transform: 'translateY(0px)'},+ {transform: 'translateY(100px)'},+ ],+ {duration: 600, endDelay},+ );+ if (reverse) {+ // Its current time falls from its end time to 0.+ run.reverse();+ }+ return performance.timeOrigin + performance.now();+ },+ {reverse, endDelay},+ );+ await waitForRest(pop);+ });+ await waitForRest(pop);+ return trace.window.to - started;+ };+ // Reversed with a 200 ms end delay: the move plays from 200 to 800 ms.+ expect(await traced(true, 200)).toBeGreaterThanOrEqual(790);+ // A reversed run is waited for as long as the same run forward, not+ // twice as long.+ const forward = await traced(false);+ const backward = await traced(true);+ expect(backward).toBeGreaterThanOrEqual(590);+ expect(backward).toBeLessThan(forward * 1.5);+ });++ test('a waitForRest awaited inside a traced body runs on the real timers, so a frozen timer gate cannot hold it', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await page.route('http://anchored.test/', route =>+ route.fulfill({contentType: 'text/html', body: ANCHORED}),+ );+ await page.goto('http://anchored.test/');+ const pop = page.locator('#pop');+ await waitForRest(pop);+ await installTimerGate(page);+ await freezeTimers(page);+ let outcome = '';+ await traceRendering(page, async () => {+ await pop.evaluate(el => {+ el.animate(+ [{transform: 'translateY(0px)'}, {transform: 'translateY(100px)'}],+ {duration: 300},+ );+ });+ // Held by the gate, the wait would neither resolve nor reach its+ // deadline: the race reads that as "held".+ outcome = await Promise.race([+ waitForRest(pop, {timeout: 2000}).then(+ () => 'rested',+ () => 'rejected',+ ),+ new Promise<string>(resolve => setTimeout(() => resolve('held'), 4000)),+ ]);+ });+ await thawTimers(page);+ expect(outcome).toBe('rested');+ });++ test('inside a trace, waitForRest rests beside a scroll-timeline animation', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await fixture(page);+ const scroller = page.locator('#scroller');+ await waitForRest(scroller);+ let outcome = '';+ await traceRendering(page, async () => {+ // A row driven by its scroller's timeline: it moves only on scroll.+ await scroller.evaluate(el => {+ const row = el.firstElementChild as HTMLElement;+ row.animate([{opacity: 0.5}, {opacity: 1}], {+ timeline: new ScrollTimeline({source: el}),+ });+ });+ outcome = await waitForRest(scroller, {timeout: 2000}).then(+ () => 'rested',+ (error: Error) => error.message,+ );+ });+ expect(outcome).toBe('rested');+ });++ test('a CSS transition and animation that start and end inside a trace are reported, and lay out nothing in between', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await page.route('http://anchored.test/', route =>+ route.fulfill({contentType: 'text/html', body: ANCHORED}),+ );+ await page.goto('http://anchored.test/');+ await page.addStyleTag({+ content:+ '@keyframes harness-fade { from { opacity: 1 } to { opacity: 0.6 } }',+ });+ const pop = page.locator('#pop');+ // The recorder runs, and a watch is taken before the trace.+ await waitForRest(pop);+ const watch = await watchAnimations(pop);+ let started = 0;+ const trace = await traceRendering(page, async () => {+ started = await pop.evaluate(el => {+ const pop = el as HTMLElement;+ pop.style.transition = 'transform 400ms linear';+ void pop.offsetWidth;+ pop.style.transform = 'translateY(100px)';+ pop.style.animation = 'harness-fade 400ms linear';+ return performance.timeOrigin + performance.now();+ });+ await page.waitForTimeout(600);+ });+ // Its reads at the two starts fall before the steady middle.+ expect(countBetween(trace, started + 100, started + 300).Layout ?? 0).toBe(+ 0,+ );+ const ended = await watch.started({timeout: 1_000});+ expect(ended.map(a => a.kind).sort()).toEqual([+ 'CSSAnimation',+ 'CSSTransition',+ ]);+ expect(ended.every(a => a.finishedAt != null)).toBe(true);+ });+test('the compositor record refuses another open page, whose frames it could not tell apart', async ({page,browserName,@@ -3082,6 +3434,91 @@ test.describe('animation state', () => {expect(started.map(a => a.durationMs)).toEqual([300]);});+ test('while a rendering trace runs the recorder reads only at CSS starts, and catches up after it', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ const watch = await watchAnimations(box);+ // Counts the recorder's reads of the page's animations (each one flushes+ // style): the whole document's, and one element's. Then flags a trace, as+ // traceRendering does.+ await page.evaluate(() => {+ const w = window as unknown as {+ __reads: number;+ __elementReads: number;+ __harnessRenderingTrace?: boolean;+ };+ w.__reads = 0;+ w.__elementReads = 0;+ const read = document.getAnimations.bind(document);+ document.getAnimations = () => {+ w.__reads += 1;+ return read();+ };+ const readElement = Element.prototype.getAnimations;+ Element.prototype.getAnimations = function (+ this: Element,+ ...args: Parameters<Element['getAnimations']>+ ) {+ w.__elementReads += 1;+ return readElement.apply(this, args);+ };+ w.__harnessRenderingTrace = true;+ });+ // During the trace: a CSS transition and a CSS animation that both end+ // inside it, and a script animation still running after it.+ await page.addStyleTag({+ content:+ '@keyframes harness-fade { from { opacity: 1 } to { opacity: 0.6 } }',+ });+ await box.evaluate(el => {+ const box = el as HTMLElement;+ box.style.transition = 'transform 120ms linear';+ void box.offsetWidth;+ box.style.transform = 'translateX(100px)';+ box.style.animation = 'harness-fade 120ms linear';+ box.animate([{scale: '1'}, {scale: '0.9'}], {duration: 600});+ });+ await page.waitForTimeout(300);+ const reads = () =>+ page.evaluate(() => (window as unknown as {__reads: number}).__reads);+ // No frame loop: no document-wide read. One element read per CSS start+ // event (transitionrun, transitionstart, animationstart), not per frame.+ expect(await reads()).toBe(0);+ expect(+ await page.evaluate(+ () => (window as unknown as {__elementReads: number}).__elementReads,+ ),+ ).toBeLessThanOrEqual(3);+ // The trace ends: traceRendering clears the flag and resumes the recorder,+ // which reads again, every frame.+ await page.evaluate(() => {+ const w = window as unknown as {+ __harnessRenderingTrace?: boolean;+ __harnessAnimations: {resume: () => void};+ };+ w.__harnessRenderingTrace = false;+ w.__harnessAnimations.resume();+ });+ await frames(page, 3);+ expect(await reads()).toBeGreaterThan(2);+ // All three are reported, the two CSS ones that ended inside the trace+ // with the time they finished.+ await waitForRest(box);+ const started = await watch.started();+ expect(started.map(a => a.kind).sort()).toEqual([+ 'Animation',+ 'CSSAnimation',+ 'CSSTransition',+ ]);+ expect(+ started+ .filter(a => a.kind !== 'Animation')+ .map(a => a.finishedAt != null),+ ).toEqual([true, true]);+ });+test('a wait answers with the animation the action started, not one that finished before it', async ({page,}) => {@@ -3146,6 +3583,28 @@ test.describe('animation state', () => {await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));});+ test('inside a rendering trace too, a watch taken right after a style change does not report that change', async ({+ page,+ browserName,+ }) => {+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');+ await fixture(page);+ const box = page.locator('#box');+ await waitForRest(box);+ await traceRendering(page, async () => {+ // The step: a transition the next style read creates.+ await box.evaluate(el => {+ el.style.transition = 'opacity 300ms linear';+ el.style.opacity = '0.5';+ });+ const watch = await watchAnimations(box);+ await expect(watch.started({timeout: 200})).rejects.toThrow(+ /waitForAnimation/,+ );+ });+ await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));+ });+test('an exit whose element the page removes at its end is still reported', async ({page,}) => {@@ -3197,6 +3656,43 @@ test.describe('animation state', () => {}});+ test('inside a rendering trace too, a wait on an element no longer in the document rejects as missing', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'rendering traces are Chromium-only (README: engine limits)',+ );+ await fixture(page);+ await page.evaluate(() => {+ const gone = document.createElement('div');+ gone.id = 'gone';+ document.body.append(gone);+ });+ const gone = page.locator('#gone');+ const watch = await watchAnimations(gone);+ await page.evaluate(() => document.getElementById('gone')?.remove());+ const outcomes: string[] = [];+ await traceRendering(page, async () => {+ for (const wait of [+ () => watch.started({timeout: 300}),+ () => waitForAnimation(gone, {timeout: 300}),+ ]) {+ outcomes.push(+ await wait().then(+ () => 'resolved',+ (error: Error) => error.message,+ ),+ );+ }+ });+ expect(outcomes).toHaveLength(2);+ for (const outcome of outcomes) {+ expect(outcome).toMatch(/not in the document/);+ }+ });+test('a watch reports only what started after it', async ({page}) => {await fixture(page);const box = page.locator('#box');diff --git a/internal/interaction-harness/src/story.ts b/internal/interaction-harness/src/story.tsindex c64acfca0a..fcf5a8358e 100644--- a/internal/interaction-harness/src/story.ts+++ b/internal/interaction-harness/src/story.ts@@ -171,11 +171,12 @@ export async function frames(page: Page, count = 2): Promise<void> {// A held callback is queued under its timer or frame id, so the page's own// clearTimeout and cancelAnimationFrame still cancel it while frozen; a held-// frame callback gets the time it actually runs at. `frame` stays the real-// requestAnimationFrame, for the harness's own waits, and `now` the real clock-// for their deadlines, which a page freeze does not stop. The gate's freeze() and-// thaw() are its one way in: freezeTimers and thawTimers call them, and so-// does a page freeze (freeze.ts), which stops the page's clock too.+// frame callback gets the time it actually runs at. `frame` and `timeout`+// stay the real requestAnimationFrame and setTimeout, for the harness's own+// waits, and `now` the real clock for their deadlines, which a page freeze+// does not stop. The gate's freeze() and thaw() are its one way in:+// freezeTimers and thawTimers call them, and so does a page freeze+// (freeze.ts), which stops the page's clock too.const TIMER_GATE = `(() => {if (window.__harnessTimerGate) return;const realTimeout = window.setTimeout.bind(window);diff --git a/internal/interaction-harness/src/trace.ts b/internal/interaction-harness/src/trace.tsindex c3756fd5d7..eb45378e42 100644--- a/internal/interaction-harness/src/trace.ts+++ b/internal/interaction-harness/src/trace.ts@@ -126,7 +126,15 @@ export interface TraceEvent {/*** Traces the page while `body` runs and counts the rendering work its main* thread did between a start mark (placed just before `body`) and an end mark- * (just after).+ * (just after). The harness's animation recorder, `waitForRest`,+ * `waitForAnimation` and a watch's `started()` stand down meanwhile, so a body+ * may wait with any of them and add no frame of its own, with one gap: on a+ * CSS `@keyframes` animation (and, for an unwatched `waitForAnimation`, a+ * cancelled CSS transition) the wait reads its timing, which flushes that+ * animation's style, so wait on such an animation with `waitForRest`, or+ * after the trace. Taking a watch, or calling `waitForRest` while an+ * animation already runs on the element, reads its animations once, which+ * restyles it: do either before the window a proof counts.*/export async function traceRendering(page: Page,@@ -158,9 +166,35 @@ export async function traceRendering(n => performance.timeOrigin + performance.mark(n).startTime,name,);- const fromEpoch = await mark(`${tag}:start`);- await body();- const toEpoch = await mark(`${tag}:end`);+ // The harness's animation recorder (curves.ts) runs a callback every frame,+ // which makes each frame a main-thread one where Blink restyles every running+ // animation's target (and lays out an anchored one), and it reads the page's+ // animations, which flushes style: exactly what this counts. It stands down+ // while this flag is set, a recorder the body itself starts included, and+ // resumes once the trace ends.+ const standDown = (on: boolean) =>+ page.evaluate(value => {+ const w = window as unknown as {+ __harnessRenderingTrace?: boolean;+ __harnessAnimations?: {resume?: () => void};+ };+ w.__harnessRenderingTrace = value;+ if (!value) {+ w.__harnessAnimations?.resume?.();+ }+ }, on);+ await standDown(true);+ let fromEpoch: number;+ let toEpoch: number;+ try {+ fromEpoch = await mark(`${tag}:start`);+ await body();+ toEpoch = await mark(`${tag}:end`);+ } finally {+ // Its catch-up read lands after the end mark, outside the counted window.+ // A failure here would hide the body's own error, which is the one to see.+ await standDown(false).catch(() => {});+ }await cdp.send('Tracing.end');await complete;await cdp.detach().catch(() => {});