An open source design system that's fully customizable and agent ready
TypeScript
feat(interaction): animation-state waits for interaction proofs (#8505)
Cindy Zhang42a30b47e659
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex cd53a4b9ca..95931b9147 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -26,7 +26,7 @@ pnpm test:interaction <spec file> # one spec, both engines| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `scripts.ts` | Touch scripts as data: `tap`, `drag` (hold, rest), `flick` (exact final-move speed, velocity profiles), `holdThenDrag`, `pinch`, `rotate`, `path`, `merge` (a second finger mid-gesture), `releaseVelocity`, `toTouchEvents`. || `touch.ts` | `touchDriver(page).play(script)`: the script as real engine input. `installInputLog` / `readInputLog`: what the page received. |-| `curves.ts` | `holdAnimations`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `releaseAnimations`. |+| `curves.ts` | `holdAnimations`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `waitForAnimation`, `watchAnimations`, `waitForRest`, `releaseAnimations`. || `math.ts` | Oracles independent of the code under test: `cubicBezier`, `timingFunction`, `springStep` (SwiftUI response / dampingFraction, initial velocity), `projectDecay`, `rubberBand`, `parseTransform`, `compareCurve`, `timeline`. || `story.ts` | `phone`, `withStorybook`, `openStory`, `frames`. |@@ -54,13 +54,30 @@ budget (for a spring baked into `linear()` stops of `h` ms, chords err by up toinside it, the last frame it presents, and the sample says so (`presentedAt`,where oracles are read). An animation whose keyframes end in a run ofidentical values (an end value held so a later interruption can read it)-ends where that run starts: `curveEndMs` stops there. That holds for an-animation that plays forward under a linear or cubic-bézier effect easing (the-time the run starts is solved from the curve); under any other effect easing-(steps, `linear()` stops, an overshoot) or another direction the curve is read-to its full end. `holdAnimations` refuses an animation running backward-(`reverse()`, a negative playback rate): seeking and sampling run a curve-forward.+ends where that run starts: `curveEndMs` and `waitForAnimation`'s interval+stop there, and `waitForRest`, which judges the+presented `transform`, `translate`, `rotate`, `scale` and `opacity` rather+than `playState`, does not wait the hold out. That holds for an animation that+plays forward under a linear or cubic-bézier effect easing (the time the run+starts is solved from the curve); under any other effect easing (steps,+`linear()` stops, an overshoot) or another direction the curve is read to its+full end, and `waitForRest` waits the hold out. An animation reversed before it starts (`reverse()`+on a new animation, a negative playback rate from the start) is reported by+`waitForAnimation` from when it started, but `holdAnimations` refuses it:+seeking and sampling run a curve forward. The recorder keeps one entry per+`Animation` object, so one 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. Take a fresh animation for each run a proof reads.++**Waiting for an animation.** The page records every animation from the first+call into `curves.ts` on it (and on every later document): a frame loop on the+page's own `requestAnimationFrame`, the CSS animation and transition events,+and `Element.animate` as it is called, pending animations included. So+`waitForAnimation` also reports one that started after the last+`waitForRest`, `waitForAnimation` or `watchAnimations` and has already finished (`finishedAt`+set): a short entrance no longer races the first look on a cold page. When the+action may be the page's first contact with the harness, take+`watchAnimations(locator)` before it and read `watch.started()` after.## Engine limits (measured with Playwright 1.61)diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.tsindex 394e285915..f3b03ffe45 100644--- a/internal/interaction-harness/src/curves.ts+++ b/internal/interaction-harness/src/curves.ts@@ -10,7 +10,9 @@* its offset), `sampleCurve` (the presented* transform/opacity at each t, with the individual `translate`, `rotate` and* `scale` properties composed in), `releaseAnimations`, `curveOf`, which- * picks one channel out of the samples for ./math's `compareCurve`.+ * picks one channel out of the samples for ./math's `compareCurve`, and the+ * animation-state waits `waitForAnimation`, `watchAnimations` and+ * `waitForRest`.* @position Curve sampling: the exact presented value of an animation at a* fixed time, independent of frame timing, so a curve can be compared with* the UIKit reference to a fraction of a pixel. A paused animation's effect@@ -23,6 +25,156 @@ import {parseTransform, type TimedValue, type Transform2D} from './math';/** How far inside its end a seek past an animation's end lands, ms. */export const END_INSET_MS = 0.5;+/**+ * Page side: records every animation the document runs, from its first frame+ * or its creation (a frame loop on the page's real requestAnimationFrame, and+ * the CSS animation and transition events), so an animation that starts and+ * ends before a test looks is still seen, with the time it finished. Each+ * entry keeps the animation's start time too: a page that cancels a finished+ * animation (an entrance whose class is removed on `animationend`) nulls its+ * `startTime`.+ */+function animationRecorder(): void {+ const w = window as unknown as {__harnessAnimations?: unknown};+ if (w.__harnessAnimations) {+ return;+ }+ const frame = window.requestAnimationFrame.bind(window);+ const seen = new WeakSet<Animation>();+ const log: {+ animation: Animation;+ seenAt: number;+ finishedAt: number | null;+ startedAt: number | null;+ }[] = [];+ // Entries whose start time has not resolved yet (still pending when seen).+ let unstarted: (typeof log)[number][] = [];+ let armedAt = performance.now();+ // When the animation began to play, on the document timeline. A run going+ // backward reports as its startTime the moment its current time would+ // reach 0, a whole run after it began (it begins at its end).+ const playStart = (animation: Animation): number | null => {+ if (animation.startTime == null) {+ return null;+ }+ const rate = animation.playbackRate;+ if (rate >= 0) {+ return Number(animation.startTime);+ }+ const end = Number(+ (animation.effect as KeyframeEffect | null)?.getComputedTiming()+ .endTime ?? 0,+ );+ return Number(animation.startTime) - end / Math.abs(rate);+ };+ const remember = (animation: Animation) => {+ // A running animation is recorded while still pending: on a cold page the+ // next frame can come only after a short animation has finished.+ if (seen.has(animation) || animation.playState !== 'running') {+ return;+ }+ seen.add(animation);+ // The target's ancestors as recorded: an exit whose element the page+ // removes at its end is still reported for the container it left.+ const ancestors: Element[] = [];+ for (+ let node = (animation.effect as KeyframeEffect | null)?.target ?? null;+ node != null;+ node = node.parentElement+ ) {+ ancestors.push(node);+ }+ const entry = {+ animation,+ seenAt: performance.now(),+ finishedAt: null as number | null,+ startedAt: playStart(animation),+ ancestors,+ };+ if (entry.startedAt == null) {+ unstarted.push(entry);+ }+ animation.addEventListener('finish', event => {+ entry.finishedAt = performance.now();+ if (entry.startedAt == null) {+ // Cancelled before a frame read its start: back from where it ended.+ const end = Number(+ (animation.effect as KeyframeEffect | null)?.getComputedTiming()+ .endTime ?? 0,+ );+ const at = (event as AnimationPlaybackEvent).timelineTime;+ entry.startedAt =+ playStart(animation) ??+ (at == null ? entry.finishedAt : Number(at)) -+ end / Math.abs(animation.playbackRate || 1);+ }+ });+ log.push(entry);+ if (log.length > 5000) {+ log.splice(0, log.length - 5000);+ }+ };+ const record = () => {+ for (const animation of document.getAnimations()) {+ remember(animation);+ }+ unstarted = unstarted.filter(entry => {+ if (entry.startedAt == null && entry.animation.startTime != null) {+ entry.startedAt = playStart(entry.animation);+ }+ return entry.startedAt == null && entry.animation.playState !== 'idle';+ });+ };+ const tick = () => {+ record();+ 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.+ record();+ frame(tick);+ for (const type of ['animationstart', 'transitionrun', 'transitionstart']) {+ document.addEventListener(type, record, true);+ }+ // A script animation is recorded as it is made: WebKit can start and finish+ // a short one between two frames of a fresh page.+ const animate = Element.prototype.animate;+ Element.prototype.animate = function (+ this: Element,+ ...args: Parameters<Element['animate']>+ ) {+ const animation = animate.apply(this, args);+ remember(animation);+ return animation;+ };+ w.__harnessAnimations = {+ log,+ record,+ // 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();+ const newest = log.length === 0 ? 0 : log[log.length - 1].seenAt;+ armedAt = Math.max(performance.now(), newest + 0.001);+ return armedAt;+ },+ armedAt: () => armedAt,+ };+}++const recordingPages = new WeakSet<Page>();++/** Starts the recorder now and on every later document of the page. */+async function installRecorder(page: Page): Promise<void> {+ if (!recordingPages.has(page)) {+ recordingPages.add(page);+ await page.addInitScript(animationRecorder);+ }+ await page.evaluate(animationRecorder);+}+/*** Installs `window.__harnessCurveEnd(animation)`: the local time (ms, delay* included) where the animation's effect stops changing. An animation whose@@ -32,6 +184,7 @@ export const END_INSET_MS = 0.5;* starts is solved from the curve); any other ends at its end time.*/async function installCurveEnd(page: Page): Promise<void> {+ await installRecorder(page);await page.evaluate(() => {const w = window as unknown as {__harnessCurveEnd?: (animation: Animation) => number;@@ -643,3 +796,399 @@ export function curveOf(value: channel === 'opacity' ? s.opacity : s.transform[channel],}));}++export interface ActiveAnimation {+ readonly kind: string;+ readonly name: string | null;+ /**+ * Epoch ms (page clock) when the animation's curve starts and ends. A held+ * end value (see `HeldAnimation.curveEndMs`, which says when one is read)+ * is not part of the curve.+ */+ readonly from: number;+ readonly to: number;+ readonly durationMs: number;+ readonly easing: string;+ readonly keyframes: readonly Record<string, unknown>[];+ /**+ * Epoch ms (page clock) when it finished, if it had already finished when+ * it was reported; null while it runs.+ */+ readonly finishedAt: number | null;+}++/**+ * 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+ * at its end) or never mounted would hold the wait to the test's timeout;+ * this turns that into the wait's own rejection. A read that runs out of time+ * on an element still present returns null: the caller's own deadline+ * message applies.+ */+async function withinTimeout<T>(+ name: string,+ locator: Locator,+ deadline: number,+ read: (timeout: number) => Promise<T>,+): Promise<T | null> {+ try {+ return await read(Math.max(1, deadline - Date.now()));+ } catch (error) {+ if ((error as Error | null)?.name === 'TimeoutError') {+ 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 error;+ }+}++/**+ * Waits until an animation is running on `locator`'s element (or inside it)+ * and has presented `minProgressMs` of its curve (after any delay), and+ * returns its active+ * interval on the page clock. Use it before blocking the main thread: an+ * animation that has not started yet cannot start while the thread is blocked.+ *+ * It does not race a short animation: the page records every animation from+ * its first frame (from the first call into this module on the page: this,+ * `waitForRest`, `watchAnimations`, sampling or holding), so one that started+ * after the last `waitForRest`, `waitForAnimation` or `watchAnimations` and has already+ * finished is reported too, with `finishedAt` set. For an action that may be+ * the page's first contact with this module, take `watchAnimations(locator)`+ * before the action instead.+ *+ * A run going backward is read when it was reversed before it started. The+ * 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.+ */+export async function waitForAnimation(+ locator: Locator,+ {+ timeout = 5_000,+ minProgressMs = 1,+ since,+ }: {+ timeout?: number;+ minProgressMs?: number;+ /** Page-clock ms (performance.now): only animations first seen after it. */+ since?: number;+ } = {},+): Promise<ActiveAnimation[]> {+ const deadline = Date.now() + timeout;+ await installCurveEnd(locator.page());+ for (;;) {+ const read = await withinTimeout(+ 'waitForAnimation',+ locator,+ deadline,+ evaluateTimeout =>+ locator.evaluate(+ (element, {minProgress, since: watchedFrom}) => {+ const w = window as unknown as {+ __harnessCurveEnd: (a: Animation) => number;+ __harnessAnimations: {+ log: {+ animation: Animation;+ seenAt: number;+ finishedAt: number | null;+ startedAt: number | null;+ ancestors: Element[];+ }[];+ record: () => void;+ armedAt: () => number;+ };+ };+ const curveEnd = w.__harnessCurveEnd;+ const recorder = w.__harnessAnimations;+ recorder.record();+ const describe = (+ a: Animation,+ finishedAt: number | null,+ recordedStart: number | null,+ ) => {+ const effect = a.effect as KeyframeEffect | null;+ const timing = effect?.getComputedTiming();+ // The recorded start stands in once the page has cancelled it. A+ // run going backward began at its end: its startTime is where its+ // current time would reach 0, a whole run later.+ const rate = a.playbackRate;+ const speed = Math.abs(rate || 1);+ const endTime = Number(timing?.endTime ?? 0);+ const delay = Number(timing?.delay ?? 0);+ const start =+ a.startTime == null+ ? recordedStart+ : rate < 0+ ? Number(a.startTime) - endTime / speed+ : Number(a.startTime);+ const startedAt =+ performance.timeOrigin + Number(start ?? Number.NaN);+ const name =+ 'transitionProperty' in a+ ? (a as unknown as {transitionProperty: string})+ .transitionProperty+ : 'animationName' in a+ ? (a as unknown as {animationName: string}).animationName+ : null;+ return {+ kind: a.constructor.name,+ name,+ // Through the playback rate's speed: at rate 2 a curve runs in half+ // its duration. Backward, the end delay plays first and the start+ // delay last.+ from:+ rate < 0+ ? startedAt + Number(timing?.endDelay ?? 0) / speed+ : startedAt + delay / speed,+ to:+ rate < 0+ ? startedAt + (endTime - delay) / speed+ : startedAt + curveEnd(a) / speed,+ durationMs: Number(timing?.duration ?? 0),+ easing: String(effect?.getTiming().easing ?? 'linear'),+ keyframes: (effect?.getKeyframes() ?? []).map(+ (k): Record<string, unknown> => ({...k}),+ ),+ finishedAt:+ finishedAt == null+ ? null+ : performance.timeOrigin + finishedAt,+ };+ };+ const inside = (a: Animation) => {+ const target =+ (a.effect as KeyframeEffect | null)?.target ?? null;+ return (+ target != null &&+ (target === element || element.contains(target))+ );+ };+ const after = watchedFrom ?? recorder.armedAt();+ // Document-timeline animations only, as for holdAnimations: a scroll-+ // or view-timeline one that reached its end is not a finished curve.+ const recorded = recorder.log.filter(+ e =>+ e.seenAt >= after &&+ (inside(e.animation) || e.ancestors.includes(element)) &&+ e.animation.timeline instanceof DocumentTimeline,+ );+ // Running: since the watch, or (without one) any on the element. A+ // pending one (no start time yet) counts too: the action's animation+ // may still be pending at the first look, and an earlier one that+ // 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 live = (+ watchedFrom == null+ ? element.getAnimations({subtree: true})+ : recorded+ .filter(e => e.finishedAt == null)+ .map(e => e.animation)+ ).filter(+ a =>+ a.playState === 'running' &&+ a.timeline instanceof DocumentTimeline,+ );+ 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 time = Number(a.currentTime ?? 0);+ const local =+ a.playbackRate < 0+ ? Number(timing?.endTime ?? 0) -+ Number(timing?.endDelay ?? 0) -+ time+ : time - Number(timing?.delay ?? 0);+ return local / Math.abs(a.playbackRate || 1) >= minProgress;+ });+ if (progressed.length > 0) {+ return progressed.map(a => describe(a, null, null));+ }+ if (live.length > 0) {+ return [];+ }+ // Finished: by its finish event, or by its state when the event has not+ // been delivered yet (then at its scheduled end, through the rate's+ // speed; a run going backward ends at its startTime, where its current+ // time reaches 0).+ const finishedAt = (e: (typeof recorded)[number]) => {+ if (e.finishedAt != null) {+ return e.finishedAt;+ }+ const a = e.animation;+ if (a.playState !== 'finished' || a.startTime == null) {+ return null;+ }+ const end = Number(+ (a.effect as KeyframeEffect | null)?.getComputedTiming()+ .endTime ?? 0,+ );+ return a.playbackRate < 0+ ? Number(a.startTime)+ : Number(a.startTime) + end / Math.abs(a.playbackRate || 1);+ };+ return recorded+ .filter(e => finishedAt(e) != null)+ .map(e => describe(e.animation, finishedAt(e), e.startedAt));+ },+ {minProgress: minProgressMs, since: since ?? null},+ {timeout: evaluateTimeout},+ ),+ );+ const found = read ?? [];+ if (found.length > 0) {+ await armRecorder(locator.page());+ return found;+ }+ if (Date.now() > deadline) {+ throw new Error(+ 'waitForAnimation: no animation started on the element, none running ' ++ 'and none recorded since the last wait. If the action is the ' ++ "page's first contact with the harness, take " ++ 'watchAnimations(locator) before it.',+ );+ }+ await new Promise(resolve => setTimeout(resolve, 4));+ }+}++/** 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(),+ );+}++export interface AnimationWatch {+ /**+ * Resolves with the animations on the element that started after the watch+ * was taken: running ones once they have presented `minProgressMs`, or,+ * when none runs, those that already finished.+ */+ started(options?: {+ timeout?: number;+ minProgressMs?: number;+ }): Promise<ActiveAnimation[]>;+}++/**+ * 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):+ *+ * const watch = await watchAnimations(sheet);+ * await driver.play(tap(button));+ * const [entrance] = await watch.started();+ */+export async function watchAnimations(+ locator: Locator,+): Promise<AnimationWatch> {+ await installCurveEnd(locator.page());+ const since = await armRecorder(locator.page());+ return {+ started: options => waitForAnimation(locator, {...options, since}),+ };+}++/**+ * Resolves once `locator`'s element is at rest: no animation on it (or inside+ * it) is pending or still before the end of its curve, and its presented+ * `transform`, `translate`, `rotate`, `scale` and `opacity` (and `::backdrop`+ * opacity) have held still for `frames` consecutive frames.+ *+ * It judges curves and presented values, not `playState`: an animation that+ * holds its end value (a run of identical final keyframes kept so a later+ * interruption can read it) still reports `running` while nothing moves.+ * A hold is read as such only where `HeldAnimation.curveEndMs` reads it (a+ * 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".+ */+export async function waitForRest(+ locator: Locator,+ {timeout = 5_000, frames = 3}: {timeout?: number; frames?: number} = {},+): Promise<void> {+ await installCurveEnd(locator.page());+ // The page-side wait rejects at its own deadline; the read gets a second+ // more, so only an element that is gone runs it out.+ const rested = await withinTimeout(+ 'waitForRest',+ locator,+ Date.now() + timeout + 1_000,+ async evaluateTimeout => {+ await locator.evaluate(+ (element, {ms, need}) =>+ new Promise<void>((resolve, reject) => {+ const deadline = performance.now() + ms;+ const curveEnd = (+ window as unknown as {__harnessCurveEnd: (a: Animation) => number}+ ).__harnessCurveEnd;+ const read = () => {+ const style = getComputedStyle(element);+ const backdrop = getComputedStyle(element, '::backdrop').opacity;+ return [+ style.transform,+ style.translate,+ style.rotate,+ style.scale,+ style.opacity,+ backdrop,+ ].join(' | ');+ };+ const frame = requestAnimationFrame;+ let last = read();+ let still = 0;+ const tick = () => {+ const now = read();+ const moving = element.getAnimations({subtree: true}).some(+ a =>+ a.pending ||+ (a.playState === 'running' &&+ // Going backward the curve ends at the start delay, after+ // the end delay (which plays first) and the curve itself.+ (a.playbackRate < 0+ ? Number(a.currentTime ?? 0) >+ Number(a.effect?.getComputedTiming().delay ?? 0)+ : Number(a.currentTime ?? 0) < curveEnd(a))),+ );+ 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();+ } else if (performance.now() > deadline) {+ reject(new Error(`waitForRest: still moving (${now})`));+ } else {+ frame(tick);+ }+ };+ frame(tick);+ }),+ {ms: timeout, need: frames},+ {timeout: evaluateTimeout},+ );+ return true;+ },+ );+ if (rested == null) {+ throw new Error('waitForRest: still moving at the deadline');+ }+}diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.tsindex 21417851b0..7a0df1c845 100644--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts@@ -6,8 +6,10 @@* @output Proof that each harness instrument measures what it claims:* scripted timestamps reach the page; a flick flings natively (Chromium);* a second finger and a pinch arrive as distinct pointers; sampled curves- * match the oracles; a held end is not part of the curve, and individual- * transform properties are sampled; a sample at+ * match the oracles; the 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; individual transform properties are sampled; 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* was read, adds a second hold to the held set without moving the first@@ -16,7 +18,7 @@* instruments; this file is why it may.*/-import {expect, test, type Locator, type Page} from '@playwright/test';+import {expect, test, type Page} from '@playwright/test';import {compareCurve,cubicBezier,@@ -26,6 +28,7 @@ import {holdAnimations,installInputLog,merge,+ parseTransform,PARTIAL_LIFT_SKIP,pinch,readInputLog,@@ -36,6 +39,9 @@ import {tap,timeline,touchDriver,+ waitForAnimation,+ waitForRest,+ watchAnimations,withFinger,} from './index';@@ -61,37 +67,6 @@ async function fixture(page: Page) {await page.goto('http://harness.test/');}-/** Until an animation on the element runs with a start time, `ms` into it. */-async function untilRunning(locator: Locator, ms = 0) {- await expect- .poll(() =>- locator.evaluate(- (el, min) =>- el- .getAnimations()- .some(- a =>- a.playState === 'running' &&- a.startTime != null &&- Number(a.currentTime ?? 0) >= min,- ),- ms,- ),- )- .toBe(true);-}--/** Until nothing on the element is running. */-async function untilIdle(locator: Locator) {- await expect- .poll(() =>- locator.evaluate(el =>- el.getAnimations().some(a => a.playState === 'running'),- ),- )- .toBe(false);-}-test.describe('touch input', () => {test('the page receives trusted touches and pointers at the scripted positions and times', async ({page,@@ -535,12 +510,34 @@ test.describe('holding', () => {await releaseAnimations(page);});- test('a faster playback rate is read on the timeline by seeks and samples', async ({+ test('a reversed run counts its progress from its end, and a faster playback rate is read on the timeline by waits, seeks and samples', async ({page,}) => {await fixture(page);const box = page.locator('#box');- // At playback rate 2 a seek or sample at t reads the curve at 2t.+ // Reversed, the run starts at its end: progress counts down from there,+ // so a wait for 100 ms of it returns once the run has presented that much.+ const watch = await watchAnimations(box);+ await box.evaluate(el => {+ el.animate([{translate: '0px 0px'}, {translate: '100px 0px'}], {+ duration: 1000,+ easing: 'linear',+ }).reverse();+ });+ await watch.started({minProgressMs: 100});+ const presented = await box.evaluate(el => {+ const [animation] = el.getAnimations();+ return (+ Number(animation.effect?.getComputedTiming().endTime ?? 0) -+ Number(animation.currentTime ?? 0)+ );+ });+ expect(presented).toBeGreaterThanOrEqual(100);+ await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));++ // At playback rate 2 a 1,000 ms curve runs 500 ms: its interval, and a+ // seek or sample at t reads the curve at 2t.+ const fast = await watchAnimations(box);await box.evaluate(el => {const animation = el.animate([{translate: '0px 0px'}, {translate: '100px 0px'}],@@ -548,6 +545,8 @@ test.describe('holding', () => {);animation.playbackRate = 2;});+ const [running] = await fast.started();+ expect(running.to - running.from).toBeCloseTo(500, 0);await holdAnimations(page, box);await seekAnimations(page, 125);const x = await box.evaluate(@@ -610,9 +609,11 @@ test.describe('holding', () => {expect(reversed.curveEndMs).toBeCloseTo(1000, 0);await releaseAnimations(page, {finish: true});- // One reversed by `reverse()` (a negative playback rate) is refused by- // a hold, which seeks curves forward only.- await box.evaluate(async el => {+ // One reversed by `reverse()` (a negative playback rate) is reported as+ // starting when it did, running its whole curve, and is refused by a+ // hold, which seeks curves forward only.+ const watch = await watchAnimations(box);+ const readyAt = await box.evaluate(async el => {const animation = el.animate([{translate: '0px 0px', offset: 0},@@ -623,9 +624,11 @@ test.describe('holding', () => {);animation.reverse();await animation.ready;+ return performance.timeOrigin + performance.now();});- // Chromium lists a reversed run in getAnimations() a frame after ready.- await untilRunning(box);+ const [running] = await watch.started();+ expect(Math.abs(running.from - readyAt)).toBeLessThan(100);+ expect(running.to - running.from).toBeCloseTo(1000, -1);await expect(holdAnimations(page, box)).rejects.toThrow(/runs backward/);await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));@@ -677,7 +680,7 @@ test.describe('holding', () => {);});const box = page.locator('#box');- await untilRunning(box, 50);+ await waitForAnimation(box, {minProgressMs: 50});const [held] = await holdAnimations(page, box);// Two frames later, the held animation is still where the hold read it.const after = await box.evaluate(@@ -720,7 +723,7 @@ test.describe('holding', () => {await releaseAnimations(page);// The first hold was released too: the move runs to its end, and rest is// its end, not the frame it was held on.- await untilIdle(box);+ await waitForRest(box);expect(await box.evaluate(el => getComputedStyle(el).transform)).toBe('matrix(1, 0, 0, 1, 300, 0)',);@@ -759,7 +762,7 @@ test.describe('holding', () => {}),);const box = page.locator('#box');- await untilRunning(box);+ await waitForAnimation(box);// The later-started element is held first.const [first] = await holdAnimations(page, box);const [later] = await holdAnimations(page, page.locator('#early'));@@ -783,7 +786,7 @@ test.describe('holding', () => {el.getBoundingClientRect();el.style.transform = 'translateX(300px)';});- await untilRunning(box);+ await waitForAnimation(box);expect(await holdAnimations(page, box)).toHaveLength(1);// The page sends the box back: the held transition is cancelled, and a// new one runs from where the box is.@@ -806,7 +809,7 @@ test.describe('holding', () => {await seekAnimations(page, 150);expect(await state()).toEqual({cancelled: 'idle', held: 0});await releaseAnimations(page);- await untilIdle(box);+ await waitForRest(box);expect(await state()).toEqual({cancelled: 'idle', held: 0});expect(await box.evaluate(el => getComputedStyle(el).transform)).toBe('none',@@ -841,7 +844,374 @@ test.describe('holding', () => {});});-test.describe('held ends', () => {+test.describe('animation state', () => {+ test('waitForAnimation reports a running transition and waitForRest resolves after it', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el => {+ el.style.transition = 'transform 300ms linear';+ void (el as HTMLElement).offsetWidth;+ el.style.transform = 'translateY(100px)';+ });+ const [running] = await waitForAnimation(box);+ expect(running.kind).toBe('CSSTransition');+ expect(running.name).toBe('transform');+ expect(running.durationMs).toBe(300);+ expect(running.to - running.from).toBeCloseTo(300, 0);+ await waitForRest(box);+ const settledAt = await page.evaluate(+ () => performance.timeOrigin + performance.now(),+ );+ expect(settledAt).toBeGreaterThanOrEqual(running.to);+ const transform = await box.evaluate(el => getComputedStyle(el).transform);+ expect(parseTransform(transform).translateY).toBeCloseTo(100, 1);+ });++ test("waitForAnimation's progress starts after a transition's delay", async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el => {+ el.style.transition = 'transform 300ms linear 200ms';+ void (el as HTMLElement).offsetWidth;+ el.style.transform = 'translateY(100px)';+ });+ await waitForAnimation(box, {minProgressMs: 50});+ // 50 ms along the curve: past the 200 ms delay, not inside it.+ const currentTime = await box.evaluate(el =>+ Number(el.getAnimations()[0]?.currentTime),+ );+ expect(currentTime).toBeGreaterThanOrEqual(250);+ await waitForRest(box);+ });++ test('waitForAnimation reports a short animation that ended before it looked', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await waitForRest(box);+ await box.evaluate(el => {+ el.style.transition = 'transform 60ms linear';+ void (el as HTMLElement).offsetWidth;+ el.style.transform = 'translateY(40px)';+ });+ // A cold page answers late: the transition is over before the first look.+ await page.waitForTimeout(250);+ const [ended] = await waitForAnimation(box);+ expect(ended.kind).toBe('CSSTransition');+ expect(ended.durationMs).toBe(60);+ expect(ended.finishedAt).not.toBeNull();+ expect(ended.finishedAt ?? 0).toBeGreaterThanOrEqual(ended.to - 1);+ });++ test("a watch taken before the action catches an entrance on the page's first contact", async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ const watch = await watchAnimations(box);+ await box.evaluate(el =>+ el.animate([{opacity: 0}, {opacity: 1}], {duration: 50}),+ );+ await page.waitForTimeout(250);+ const [entrance] = await watch.started();+ expect(entrance.kind).toBe('Animation');+ expect(entrance.durationMs).toBe(50);+ expect(entrance.finishedAt).not.toBeNull();+ });++ test("a watch taken on the page's first contact ignores an animation already running", async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ // An endless spinner, started before the harness has touched the page.+ await box.evaluate(el =>+ el.animate([{rotate: '0deg'}, {rotate: '360deg'}], {+ duration: 1000,+ iterations: Infinity,+ }),+ );+ const watch = await watchAnimations(box);+ await expect(watch.started({timeout: 300})).rejects.toThrow(+ /no animation started/,+ );+ await box.evaluate(el =>+ el.animate([{opacity: 1}, {opacity: 0.5}], {duration: 300}),+ );+ const started = await watch.started();+ expect(started.map(a => a.durationMs)).toEqual([300]);+ });++ test('a wait answers with the animation the action started, not one that finished before it', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ const frames = [{opacity: 0.2}, {opacity: 1}];+ // The recorder runs and is armed from here.+ await waitForRest(box);+ // A short one runs and ends; then the action starts a longer one, still+ // pending when the wait first looks.+ await box.evaluate(+ (el, keyframes) => el.animate(keyframes, {duration: 40}).finished,+ frames,+ );+ await box.evaluate((el, keyframes) => {+ el.animate(keyframes, {duration: 1000});+ }, frames);+ const [found] = await waitForAnimation(box);+ expect(found.durationMs).toBe(1000);+ await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));+ });++ test('a scroll-timeline animation in scope does not hold up a wait', async ({+ page,+ }) => {+ await fixture(page);+ const scroller = page.locator('#scroller');+ await waitForRest(scroller);+ // A row driven by its scroller's timeline (it moves only on scroll), and+ // a short document animation that ends.+ await scroller.evaluate(el => {+ const [row, other] = [...el.children] as HTMLElement[];+ row.animate([{opacity: 0.5}, {opacity: 1}], {+ timeline: new ScrollTimeline({source: el}),+ });+ // Scrolled to its end, the scroll-driven one has finished too: it is+ // not a finished curve either.+ el.scrollTop = el.scrollHeight;+ return other.animate([{opacity: 0.2}, {opacity: 1}], {duration: 40})+ .finished;+ });+ const [found] = await waitForAnimation(scroller, {timeout: 2000});+ expect(found.durationMs).toBe(40);+ expect(found.finishedAt).not.toBeNull();+ });++ test('a watch taken right after a style change does not report that change', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await waitForRest(box);+ // 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,+ }) => {+ await fixture(page);+ await page.evaluate(() => {+ const wrap = document.createElement('div');+ wrap.id = 'wrap';+ const leaf = document.createElement('div');+ leaf.id = 'leaf';+ leaf.style.cssText = 'width:20px;height:20px;background:#c33';+ wrap.append(leaf);+ document.body.append(wrap);+ });+ const wrap = page.locator('#wrap');+ const watch = await watchAnimations(wrap);+ await page.evaluate(() => {+ const leaf = document.getElementById('leaf') as HTMLElement;+ const exit = leaf.animate([{opacity: 1}, {opacity: 0}], {duration: 60});+ exit.finished.then(() => leaf.remove());+ });+ await expect+ .poll(() => page.evaluate(() => document.getElementById('leaf') == null))+ .toBe(true);+ const [exit] = await watch.started();+ expect(exit.durationMs).toBe(60);+ expect(exit.finishedAt).not.toBeNull();+ });++ test('a wait on an element no longer in the document rejects at its own timeout', async ({+ page,+ }) => {+ 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());+ for (const wait of [+ () => watch.started({timeout: 300}),+ () => waitForAnimation(gone, {timeout: 300}),+ () => waitForRest(gone, {timeout: 300}),+ ]) {+ const startedAt = Date.now();+ await expect(wait()).rejects.toThrow(/not in the document/);+ expect(Date.now() - startedAt).toBeLessThan(3_000);+ }+ });++ test('a watch reports only what started after it', async ({page}) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el =>+ el.animate([{opacity: 0}, {opacity: 1}], {duration: 40}),+ );+ await page.waitForTimeout(150);+ const watch = await watchAnimations(box);+ await expect(watch.started({timeout: 300})).rejects.toThrow(+ /no animation started/,+ );+ await box.evaluate(el =>+ el.animate([{opacity: 1}, {opacity: 0.5}], {duration: 70}),+ );+ const started = await watch.started();+ expect(started.map(a => a.durationMs)).toEqual([70]);+ });++ test('an entrance the page cancels when it ends keeps its start', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await page.addStyleTag({+ content:+ '@keyframes enter { from { opacity: 0 } to { opacity: 1 } }' ++ ' .entering { animation: enter 60ms linear }',+ });+ const watch = await watchAnimations(box);+ // The page's time origin, where a lost start lands, is well before the+ // trigger.+ await page.waitForTimeout(200);+ // Removing the class on animationend cancels the finished CSS animation,+ // which nulls its startTime.+ const triggeredAt = await box.evaluate(el => {+ el.addEventListener(+ 'animationend',+ () => el.classList.remove('entering'),+ {once: true},+ );+ el.classList.add('entering');+ return performance.timeOrigin + performance.now();+ });+ await expect+ .poll(() => box.evaluate(el => el.classList.contains('entering')))+ .toBe(false);+ const [entrance] = await watch.started();+ expect(entrance.kind).toBe('CSSAnimation');+ expect(entrance.finishedAt).not.toBeNull();+ // It started on a frame after the trigger, not at the page's time origin.+ expect(entrance.from).toBeGreaterThan(triggeredAt - 17);+ expect(entrance.from).toBeLessThan(triggeredAt + 500);+ expect(entrance.to - entrance.from).toBeCloseTo(60, 3);+ expect(entrance.finishedAt ?? 0).toBeGreaterThanOrEqual(entrance.to - 1);+ });++ test('a run going backward is dated from when it began: with a delay, ended before the look, or cancelled when it ends', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ const frames = [+ {translate: '0px 0px', offset: 0},+ {translate: '100px 0px', offset: 1},+ ];++ // A 300 ms delay plays last when going backward: the curve starts at once.+ let watch = await watchAnimations(box);+ let readyAt = await box.evaluate(async (el, keyframes) => {+ const animation = el.animate(keyframes, {duration: 400, delay: 300});+ animation.reverse();+ await animation.ready;+ return performance.timeOrigin + performance.now();+ }, frames);+ const [delayed] = await watch.started();+ expect(Math.abs(delayed.from - readyAt)).toBeLessThan(50);+ expect(delayed.to - delayed.from).toBeCloseTo(400, 0);+ await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));++ // A short one that ended before the look keeps its curve inside its life.+ watch = await watchAnimations(box);+ readyAt = await box.evaluate(async (el, keyframes) => {+ const animation = el.animate(keyframes, {duration: 60});+ animation.reverse();+ await animation.ready;+ return performance.timeOrigin + performance.now();+ }, frames);+ await page.waitForTimeout(200);+ const [ended] = await watch.started();+ expect(ended.finishedAt).not.toBeNull();+ expect(Math.abs(ended.from - readyAt)).toBeLessThan(50);+ expect(ended.to).toBeLessThanOrEqual((ended.finishedAt ?? 0) + 1);++ // One the page cancels when it ends keeps its start.+ watch = await watchAnimations(box);+ readyAt = await box.evaluate(async (el, keyframes) => {+ const animation = el.animate(keyframes, {duration: 60});+ animation.addEventListener('finish', () => animation.cancel(), {+ once: true,+ });+ animation.reverse();+ await animation.ready;+ return performance.timeOrigin + performance.now();+ }, frames);+ await page.waitForTimeout(200);+ const [cancelled] = await watch.started();+ expect(Math.abs(cancelled.from - readyAt)).toBeLessThan(50);+ expect(cancelled.to - cancelled.from).toBeCloseTo(60, 0);++ // Read right after finish(), before the finish event is delivered: the+ // scheduled end goes through the rate (backward, it is the startTime).+ for (const rate of [-1, 2]) {+ watch = await watchAnimations(box);+ await box.evaluate(+ async (el, [keyframes, playbackRate]) => {+ const animation = el.animate(keyframes as Keyframe[], {+ duration: 1000,+ });+ animation.playbackRate = playbackRate as number;+ await animation.ready;+ animation.finish();+ },+ [frames, rate] as const,+ );+ const [read] = await watch.started();+ expect(read.finishedAt).not.toBeNull();+ expect(Math.abs((read.finishedAt ?? 0) - read.to)).toBeLessThan(50);+ }++ // Going backward, an end delay presents nothing: a run still inside it+ // has not progressed.+ await box.evaluate((el, keyframes) => {+ const animation = el.animate(keyframes, {duration: 400, endDelay: 500});+ animation.reverse();+ }, frames);+ await expect(+ waitForAnimation(box, {minProgressMs: 100, timeout: 300}),+ ).rejects.toThrow();+ await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));++ // Nor is it rest: waitForRest waits out the end delay and the curve.+ const restFrom = await box.evaluate((el, keyframes) => {+ el.animate(keyframes, {duration: 600, endDelay: 500}).reverse();+ return performance.now();+ }, frames);+ await waitForRest(box, {timeout: 5_000});+ const restAt = await box.evaluate(() => performance.now());+ expect(restAt - restFrom).toBeGreaterThan(1_000);+ });+test('an end value held by the keyframes is not part of the curve, and individual transform properties are sampled', async ({page,}) => {@@ -859,6 +1229,20 @@ test.describe('held ends', () => {{duration: 5300, fill: 'forwards'},);});+ const startedAt = await page.evaluate(() => performance.now());+ const [active] = await waitForAnimation(box);+ expect(active.to - active.from).toBeCloseTo(300, 0); // the curve, not the hold+ await waitForRest(box, {timeout: 3_000});+ const after = await box.evaluate(el => ({+ at: performance.now(),+ running: el.getAnimations().some(a => a.playState === 'running'),+ translate: getComputedStyle(el).translate,+ }));+ expect(after.running).toBe(true); // still holding its end value+ expect(after.at - startedAt).toBeGreaterThanOrEqual(300);+ expect(after.at - startedAt).toBeLessThan(1_500);+ expect(after.translate).toBe('0px 120px');+const held = await holdAnimations(page, box);expect(held[0].curveEndMs).toBeCloseTo(300, 0);const [mid, end] = await sampleCurve(box, [150, 300]);