Skip to content

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

TypeScript

test(harness): a page freeze, so a proof can act at an instant of the scene's own time (#9698)

Christopher Chedeau14550c05024f
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.md
index 9ba7150801..c4371c5452 100644
--- a/internal/interaction-harness/README.md
+++ b/internal/interaction-harness/README.md
@@ -282,6 +282,67 @@ the page's surface right after it changes ("Unable to capture screenshot"); a
storyboard takes that photograph again two frames later, up to three attempts
in all, and lists each retake under `recaptures` in the trace.
+## Page freeze
+
+A proof that must act on a component mid-animation (a second tap mid-slide, a
+finger that lands before the last lift reaches the app) races the test
+process: on a loaded runner the motion has moved on, or ended, before the next
+command reaches the page. The page freeze (`src/freeze.ts`) stops the scene
+instead, and the proof acts at an instant of the scene's own time.
+
+- `installPageFreeze(page)` installs the page clock, before the page loads
+ (before `openStory`); then `installTimerGate` as usual. A page that never
+ calls it keeps its own clock. Code that kept a bound `performance.now`
+ before the install keeps the real clock.
+- `freezePage` and `thawPage` stop and start the scene in one page task.
+- `freezePageOn(page, type)` freezes on the next `type` event, in that
+ event's own task and before any page listener for it: the install adds one
+ window capture listener for each pointer, touch, mouse, key, wheel and
+ scroll event before any page script runs, and the call arms it. Any other
+ type throws.
+ A freeze armed on `scroll` lands when the scroll event fires, after the
+ scroll position has already moved.
+- `freezePageWhen(page, predicate, arg)` freezes on the first real frame the
+ predicate holds, and rejects after its timeout.
+- `advanceFrozenPage(page, ms)` moves the page's clock and every held
+ animation on together by `ms`; timers and frame callbacks stay held.
+
+While frozen, every animation in the document is paused where it stands (Web
+Animations, CSS animations and transitions), and so is any the page starts
+meanwhile, at its start. The timer gate holds the page's timers and frame
+callbacks. These clocks stand still: `performance.now()`, `Date.now()`,
+`event.timeStamp`, frame callback times, `document.timeline.currentTime`
+and `Animation.startTime`. `new Date()` keeps the real clock. Timeouts the
+page set before the freeze stop counting too, and come due on the page's clock
+after the thaw. An interval keeps the real clock and skips its ticks while
+frozen. The harness's own waits keep the real clock, so they still sample,
+hold and time out on a frozen page. Only animations on the document timeline are held: one on a
+scroll or view timeline follows its scroller, frozen or not. Input still
+arrives, and its handlers run, each reading the frozen instant. An animation
+reads as it did before the freeze (`playState` stays `running`).
+
+At the thaw every held animation plays on from where it stood, dated on the
+timeline's own time, so it is drawn where it stood in the thaw frame. That
+includes one whose start the page wrote while frozen: the timeline reads the
+current frame's time, which trails the page's clock by however far into the
+frame the thaw runs, so a start dated from now would sit before its start for
+the rest of that frame. After a thaw the page's times run again, behind real
+time by every frozen span so far, so the page's clock and its animations on
+the compositor agree as they did before the freeze.
+
+Not held yet: a run the page reverses, or a finished run it plays again,
+while frozen. A freeze holds the top document; a frame's content keeps running.
+A CSS animation a freeze held no longer follows `animation-play-state` after
+the thaw. A freeze in which no frame starts ends at the frame before it, so the page's
+clock and its runs come out of it up to a frame ahead.
+
+The clock lives in script because no engine has a native freeze that holds
+animations. Chromium's `Emulation.setVirtualTimePolicy` stops
+`performance.now()` and timers but not Web Animations or frame callbacks in
+the headless shell (300 ms into a pause the timeline had advanced 300 ms and a
+compositor animation 45 px), and its `advance` policy cannot return to real
+time: it fast-forwards whenever the page is idle.
+
## Engine limits (measured with Playwright 1.61)
| | Chromium 149 | WebKit 26.5 (Linux build) |
diff --git a/internal/interaction-harness/src/busy.ts b/internal/interaction-harness/src/busy.ts
index 9e83fea66f..b2daaa5a0a 100644
--- a/internal/interaction-harness/src/busy.ts
+++ b/internal/interaction-harness/src/busy.ts
@@ -96,15 +96,31 @@ export async function startBusyControl(
// The harness's own waits run on the real timers (see blockMainThread).
const gate = (
window as unknown as {
- __harnessTimerGate?: {frame?: typeof requestAnimationFrame};
+ __harnessTimerGate?: {
+ frame?: typeof requestAnimationFrame;
+ now?: () => number;
+ };
}
).__harnessTimerGate;
+ // A frozen page holds the control's own animation.
+ if (
+ (window as unknown as {__harnessFreeze?: {frozen: boolean}})
+ .__harnessFreeze?.frozen === true
+ ) {
+ reject(
+ new Error(
+ 'startBusyControl: the page is frozen; start the control first',
+ ),
+ );
+ return;
+ }
const frame = gate?.frame ?? window.requestAnimationFrame.bind(window);
- const deadline = performance.now() + 5_000;
+ const realNow = gate?.now ?? (() => performance.now());
+ const deadline = realNow() + 5_000;
const tick = () => {
if (!animation.pending && Number(animation.currentTime ?? 0) >= 16) {
resolve();
- } else if (performance.now() > deadline) {
+ } else if (realNow() > deadline) {
reject(new Error('startBusyControl: the control did not start'));
} else {
frame(tick);
@@ -218,11 +234,19 @@ export async function blockMainThread(
// One reading starts the loop and one ends it. A coarsened clock can
// step back between two reads, so a separate read would end it early.
// The loop tests the span it returns, which a sum rounded down would not.
- const start = performance.now();
+ // It reads the timer gate's real clock: a page freeze stops the page's
+ // own, which then trails the frames after the thaw.
+ const read =
+ (
+ window as unknown as {
+ __harnessTimerGate?: {now?: () => number};
+ }
+ ).__harnessTimerGate?.now ?? (() => performance.now());
+ const start = read();
let now = start;
let spins = 0;
while (now - start < duration) {
- now = performance.now();
+ now = read();
spins += 1;
}
return {
@@ -242,13 +266,15 @@ export async function blockMainThread(
window as unknown as {
__harnessTimerGate?: {
frame?: typeof requestAnimationFrame;
+ now?: () => number;
timeout?: typeof setTimeout;
};
}
).__harnessTimerGate;
const frame = gate?.frame ?? window.requestAnimationFrame.bind(window);
const later = gate?.timeout ?? window.setTimeout.bind(window);
- const deadline = performance.now() + wait;
+ const realNow = gate?.now ?? (() => performance.now());
+ const deadline = realNow() + wait;
// The busy-window control animates on its own, inside a dialog with
// `within`: it never stands for the animation under test.
const isControl = (a: Animation) => {
@@ -273,10 +299,11 @@ export async function blockMainThread(
// the animation: it runs once that frame's rendering update has
// handed the animation to the compositor.
later(() => {
- const start = performance.now();
+ const read = realNow;
+ const start = read();
let now = start;
while (now - start < duration) {
- now = performance.now();
+ now = read();
}
resolve({
from: performance.timeOrigin + start,
@@ -284,7 +311,7 @@ export async function blockMainThread(
spanMs: now - start,
});
}, 0);
- } else if (performance.now() > deadline) {
+ } else if (realNow() > deadline) {
reject(new Error('blockMainThread: no animation started'));
} else {
frame(tick);
diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.ts
index 63aaec1b34..4b1569efa7 100644
--- a/internal/interaction-harness/src/curves.ts
+++ b/internal/interaction-harness/src/curves.ts
@@ -77,6 +77,12 @@ function animationRecorder(): void {
}[] = [];
// Each recorded animation's entry.
const entries = new WeakMap<Animation, (typeof log)[number]>();
+ // The times kept below are real: a page time plus the span a page freeze
+ // stood still so far. A later freeze then leaves them where they were.
+ const span = () =>
+ (window as unknown as {__harnessFreeze?: {offset: number}}).__harnessFreeze
+ ?.offset ?? 0;
+ const real = (time: number | null) => (time == null ? null : time + span());
// Entries whose start time has not resolved yet (still pending when seen).
let unstarted: (typeof log)[number][] = [];
let armedAt = performance.now();
@@ -123,13 +129,14 @@ function animationRecorder(): void {
.endTime ?? 0,
);
const speed = Math.abs(animation.playbackRate || 1);
+ // The finish event's timeline time is the engine's own, already real.
entry.finishStart =
- playStart(animation) ??
+ real(playStart(animation)) ??
entry.startedAt ??
(at == null ? null : at - end / speed);
entry.finishedAt =
entry.finishStart == null
- ? performance.now()
+ ? performance.now() + span()
: entry.finishStart + end / speed;
if (entry.startedAt == null) {
// Cancelled before a frame read its start: back from where it ended.
@@ -144,7 +151,7 @@ function animationRecorder(): void {
// kept is the one it runs on, which its finish falls back to once the
// page has cancelled it.
if (animation.playState === 'running' && animation.startTime != null) {
- recorded.startedAt = playStart(animation);
+ recorded.startedAt = real(playStart(animation));
}
return;
}
@@ -167,7 +174,7 @@ function animationRecorder(): void {
animation,
seenAt: performance.now(),
finishedAt: null as number | null,
- startedAt: playStart(animation),
+ startedAt: real(playStart(animation)),
finishStart: null as number | null,
ancestors,
};
@@ -190,7 +197,7 @@ function animationRecorder(): void {
}
unstarted = unstarted.filter(entry => {
if (entry.startedAt == null && entry.animation.startTime != null) {
- entry.startedAt = playStart(entry.animation);
+ entry.startedAt = real(playStart(entry.animation));
}
return entry.startedAt == null && entry.animation.playState !== 'idle';
});
@@ -709,6 +716,7 @@ export async function armHold(
) => unknown[];
__harnessTimerGate?: {
frame?: typeof requestAnimationFrame;
+ now?: () => number;
timeout?: typeof setTimeout;
};
__harnessArmed?: Record<number, Promise<unknown[]>>;
@@ -720,7 +728,9 @@ export async function armHold(
window.requestAnimationFrame.bind(window);
const later =
w.__harnessTimerGate?.timeout ?? window.setTimeout.bind(window);
- const deadline = performance.now() + wait;
+ // The deadline reads the real clock, which a page freeze does not stop.
+ const realNow = w.__harnessTimerGate?.now ?? (() => performance.now());
+ const deadline = realNow() + wait;
// With `newOnly`, what the document has when armed neither counts nor
// joins the hold: a motion already running goes on, and the page holds
// the one that starts after it.
@@ -773,7 +783,7 @@ export async function armHold(
} catch (error) {
reject(error);
}
- } else if (performance.now() > deadline) {
+ } else if (realNow() > deadline) {
done = true;
reject(
new Error(
@@ -1294,6 +1304,13 @@ export async function waitForAnimation(
const curveEnd = w.__harnessCurveEnd;
const recorder = w.__harnessAnimations;
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
+ // takes that span as it stands now. The stamps then share the trace's
+ // clock.
+ const span =
+ (window as unknown as {__harnessFreeze?: {offset: number}})
+ .__harnessFreeze?.offset ?? 0;
const describe = (
a: Animation,
finishedAt: number | null,
@@ -1316,9 +1333,10 @@ export async function waitForAnimation(
? finishStart
: a.startTime == null
? recordedStart
- : rate < 0
- ? Number(a.startTime) - endTime / speed
- : Number(a.startTime);
+ : span +
+ (rate < 0
+ ? Number(a.startTime) - endTime / speed
+ : Number(a.startTime));
const startedAt =
performance.timeOrigin + Number(start ?? Number.NaN);
const name =
@@ -1437,9 +1455,12 @@ export async function waitForAnimation(
(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 (
+ span +
+ (a.playbackRate < 0
+ ? Number(a.startTime)
+ : Number(a.startTime) + end / Math.abs(a.playbackRate || 1))
+ );
};
return recorded
.filter(e => finishedAt(e) != null)
@@ -1591,7 +1612,15 @@ export async function waitForRest(
await locator.evaluate(
(element, {ms, need}) =>
new Promise<void>((resolve, reject) => {
- const deadline = performance.now() + ms;
+ // The deadline reads the real clock, which a page freeze does not
+ // stop.
+ const realNow =
+ (
+ window as unknown as {
+ __harnessTimerGate?: {now?: () => number};
+ }
+ ).__harnessTimerGate?.now ?? (() => performance.now());
+ const deadline = realNow() + ms;
const curveEnd = (
window as unknown as {__harnessCurveEnd: (a: Animation) => number}
).__harnessCurveEnd;
@@ -1639,7 +1668,7 @@ export async function waitForRest(
}
).__harnessAnimations?.arm();
resolve();
- } else if (performance.now() > deadline) {
+ } else if (realNow() > deadline) {
reject(new Error(`waitForRest: still moving (${now})`));
} else {
frame(tick);
diff --git a/internal/interaction-harness/src/frames.ts b/internal/interaction-harness/src/frames.ts
index 83841d259c..b5f6e72387 100644
--- a/internal/interaction-harness/src/frames.ts
+++ b/internal/interaction-harness/src/frames.ts
@@ -433,27 +433,35 @@ export async function sampleRects(
window as unknown as {
__harnessTimerGate?: {
frame?: typeof requestAnimationFrame;
+ now?: () => number;
};
}
).__harnessTimerGate;
const frame = gate?.frame ?? window.requestAnimationFrame.bind(window);
+ // The deadline reads the real clock, which a page freeze does not stop.
+ const realNow = gate?.now ?? (() => performance.now());
const samples: {
t: number;
box: {x: number; y: number; width: number; height: number} | null;
transform: string;
opacity: number;
}[] = [];
- const end = performance.now() + duration;
+ // A frame's time is the page's. After a page freeze it trails real
+ // time by the frozen span, which the stamp adds back.
+ const freeze = (
+ window as unknown as {__harnessFreeze?: {offset: number}}
+ ).__harnessFreeze;
+ const end = realNow() + duration;
const tick = (now: number) => {
const rect = element.getBoundingClientRect();
const style = getComputedStyle(element);
samples.push({
- t: performance.timeOrigin + now,
+ t: performance.timeOrigin + now + (freeze?.offset ?? 0),
box: {x: rect.x, y: rect.y, width: rect.width, height: rect.height},
transform: style.transform,
opacity: Number(style.opacity),
});
- if (now < end) {
+ if (realNow() < end) {
frame(tick);
} else {
resolve(samples);
diff --git a/internal/interaction-harness/src/freeze.ts b/internal/interaction-harness/src/freeze.ts
new file mode 100644
index 0000000000..b6dc55144f
--- /dev/null
+++ b/internal/interaction-harness/src/freeze.ts
@@ -0,0 +1,392 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file freeze.ts
+ * @input A Playwright `Page`, before the page under test loads
+ * @output `installPageFreeze`, `freezePage`, `thawPage`, `freezePageOn`,
+ * `freezePageWhen` and `advanceFrozenPage`. Stop a scene (its animations,
+ * frames, timeouts and every time it reads), step it by its own clock, and
+ * start it again. An interval skips its ticks while frozen.
+ * @position Input timed by the scene, not by the test process: a proof freezes
+ * the scene where it wants to act, acts, and thaws. The README's "Page
+ * freeze" section says what a freeze holds and why it lives in script.
+ */
+
+import type {Page} from '@playwright/test';
+
+const FREEZE_SCRIPT = `(() => {
+ if (window.__harnessFreeze) return;
+ if (window.__harnessTimerGate) {
+ throw new Error('installPageFreeze: install it before installTimerGate (and before the page loads)');
+ }
+ const perf = window.performance;
+ const nativeNow = Performance.prototype.now;
+ const rawNow = () => nativeNow.call(perf);
+ const nativeDateNow = Date.now;
+ const state = {offset: 0, frozenAt: null, dateFrozenAt: 0, timelineFrozenAt: null, held: new Set(), deferred: new Map(), watching: false, atFreeze: new WeakMap()};
+ // Real time minus every frozen span so far; the freeze instant while frozen.
+ const now = real => (state.frozenAt != null && real >= state.frozenAt ? state.frozenAt : real) - state.offset;
+ Performance.prototype.now = function () { return now(nativeNow.call(this)); };
+ Date.now = () => (state.frozenAt != null ? state.dateFrozenAt : nativeDateNow()) - state.offset;
+ const define = (proto, name, make) => {
+ const own = Object.getOwnPropertyDescriptor(proto, name);
+ if (own) Object.defineProperty(proto, name, Object.assign({}, own, make(own)));
+ };
+ define(Event.prototype, 'timeStamp', d => ({get() { return now(d.get.call(this)); }}));
+ // Only the document's timeline is re-timed. A scroll or view timeline
+ // reads its scroller, not time, so it keeps its own getter.
+ const timelineDescriptor = Object.getOwnPropertyDescriptor(DocumentTimeline.prototype, 'currentTime') || Object.getOwnPropertyDescriptor(AnimationTimeline.prototype, 'currentTime');
+ const timelineTime = timelineDescriptor.get;
+ // The timeline's time is its last frame's: frozen, it stays what it was.
+ // Never back: after a thaw the timeline's last frame can sit a little
+ // before the frozen frame on the shifted clock.
+ let last = -Infinity;
+ Object.defineProperty(DocumentTimeline.prototype, 'currentTime', {
+ configurable: true,
+ enumerable: timelineDescriptor.enumerable,
+ get() {
+ if (state.frozenAt != null) {
+ last = Math.max(last, state.frozenAt - state.offset);
+ return last;
+ }
+ const real = timelineTime.call(this);
+ if (real == null) return real;
+ last = Math.max(last, Number(real) - state.offset);
+ return last;
+ },
+ });
+ // A freeze holds the document timeline's animations only: one on a scroll
+ // or view timeline follows its scroller, frozen or not.
+ const isTimed = animation => animation.timeline === document.timeline;
+ const startTime = Object.getOwnPropertyDescriptor(Animation.prototype, 'startTime');
+ const currentTime = Object.getOwnPropertyDescriptor(Animation.prototype, 'currentTime');
+ const playState = Object.getOwnPropertyDescriptor(Animation.prototype, 'playState');
+ const nativePause = Animation.prototype.pause;
+ const nativePlay = Animation.prototype.play;
+ const nativeCancel = Animation.prototype.cancel;
+ const nativeFinish = Animation.prototype.finish;
+ // Paused exactly where it stands: a pause alone completes on the next frame
+ // (Chromium advances one more frame first. WebKit lost a time set by script).
+ const hold = animation => {
+ if (!isTimed(animation) || state.held.has(animation)) return;
+ const at = currentTime.get.call(animation);
+ nativePause.call(animation);
+ if (at != null) currentTime.set.call(animation, at);
+ state.held.add(animation);
+ };
+ const release = animation => { state.held.delete(animation); state.deferred.delete(animation); };
+ Object.defineProperty(Animation.prototype, 'startTime', Object.assign({}, startTime, {
+ get() {
+ if (!isTimed(this)) return startTime.get.call(this);
+ if (state.deferred.has(this)) return state.deferred.get(this);
+ if (state.held.has(this)) {
+ // Held, it reads as running: the start it had, on the page's clock.
+ const at = currentTime.get.call(this);
+ return at == null || this.playbackRate === 0 ? null : state.frozenAt - state.offset - Number(at) / this.playbackRate;
+ }
+ const real = startTime.get.call(this);
+ return real == null ? real : Number(real) - state.offset;
+ },
+ set(value) {
+ if (!isTimed(this)) { startTime.set.call(this, value); return; }
+ if (value == null) { state.deferred.delete(this); startTime.set.call(this, value); return; }
+ if (state.frozenAt != null) {
+ // Held where it would stand at the frozen instant; the thaw starts it.
+ hold(this);
+ state.deferred.set(this, Number(value));
+ currentTime.set.call(this, (state.frozenAt - state.offset - Number(value)) * this.playbackRate);
+ return;
+ }
+ startTime.set.call(this, Number(value) + state.offset);
+ },
+ }));
+ Object.defineProperty(Animation.prototype, 'playState', Object.assign({}, playState, {
+ get() { return state.held.has(this) ? 'running' : playState.get.call(this); },
+ }));
+ Animation.prototype.play = function () {
+ if (state.frozenAt != null && isTimed(this)) { hold(this); return; }
+ return nativePlay.call(this);
+ };
+ Animation.prototype.pause = function () { release(this); return nativePause.call(this); };
+ Animation.prototype.cancel = function () { release(this); return nativeCancel.call(this); };
+ Animation.prototype.finish = function () { release(this); return nativeFinish.call(this); };
+ const nativeAnimate = Element.prototype.animate;
+ Element.prototype.animate = function (...args) {
+ const animation = nativeAnimate.apply(this, args);
+ if (state.frozenAt != null) hold(animation);
+ return animation;
+ };
+ // Frame callbacks get the page's time; the timer gate, installed after
+ // this, holds them while frozen.
+ const nativeFrame = window.requestAnimationFrame.bind(window);
+ window.requestAnimationFrame = callback => nativeFrame(time => callback(now(time)));
+ // A CSS animation or transition the page starts while frozen: held at its
+ // start on the next frame. One that existed at the freeze and that the page
+ // resumes is held where it stood at the freeze.
+ const watch = () => {
+ if (state.frozenAt == null) { state.watching = false; return; }
+ for (const animation of document.getAnimations()) {
+ if (isTimed(animation) && !state.held.has(animation) && playState.get.call(animation) === 'running') {
+ nativePause.call(animation);
+ currentTime.set.call(animation, state.atFreeze.get(animation) ?? 0);
+ state.held.add(animation);
+ }
+ }
+ nativeFrame(watch);
+ };
+ // One capture listener on the window for each input a freeze can be armed on,
+ // added before any page script runs. An armed freeze then lands before every
+ // page listener for that input, in the input's own task.
+ const ARMABLE = ['pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'mousedown', 'mousemove', 'mouseup', 'click', 'keydown', 'keyup', 'wheel', 'scroll'];
+ const armed = new Set();
+ for (const type of ARMABLE) {
+ window.addEventListener(type, () => {
+ if (!armed.delete(type)) return;
+ window.__harnessFreeze.freeze();
+ if (window.__harnessTimerGate) window.__harnessTimerGate.freeze(true);
+ }, {capture: true, passive: true});
+ }
+ window.__harnessFreeze = {
+ // The real frames, for the harness's own waits while frozen.
+ frame: nativeFrame,
+ // The real clock, for the harness's own deadlines while frozen.
+ realNow: rawNow,
+ // Arms a one-shot freeze on the next event of this type.
+ arm(type) {
+ if (!ARMABLE.includes(type)) {
+ throw new Error('freezePageOn: a freeze arms only on ' + ARMABLE.join(', ') + '; got ' + type);
+ }
+ armed.add(type);
+ },
+ get frozen() { return state.frozenAt != null; },
+ // The frozen span so far. Once thawed, a page time plus it is real time.
+ get offset() { return state.offset; },
+ freeze() {
+ if (state.frozenAt != null) return;
+ state.frozenAt = rawNow();
+ state.dateFrozenAt = nativeDateNow();
+ const timeline = timelineTime.call(document.timeline);
+ state.timelineFrozenAt = timeline == null ? null : Number(timeline);
+ // Each running animation is held at the freeze instant, not at the last
+ // frame's time. The page's clock and its animations then agree exactly
+ // (the screen moves on by less than a frame as the freeze lands).
+ const ahead = state.timelineFrozenAt == null ? 0 : state.frozenAt - state.timelineFrozenAt;
+ state.atFreeze = new WeakMap(document.getAnimations().map(animation => [animation, currentTime.get.call(animation)]));
+ for (const animation of document.getAnimations()) {
+ if (!isTimed(animation) || playState.get.call(animation) !== 'running') continue;
+ const at = currentTime.get.call(animation);
+ hold(animation);
+ if (at != null) currentTime.set.call(animation, Number(at) + ahead * animation.playbackRate);
+ }
+ if (!state.watching) { state.watching = true; nativeFrame(watch); }
+ },
+ // Moves the frozen scene on by ms: the page's clock and every held
+ // animation together, timers and frames still held.
+ advance(ms) {
+ if (state.frozenAt == null) throw new Error('advanceFrozenPage: the page is not frozen');
+ state.offset -= ms;
+ for (const animation of state.held) {
+ if (state.deferred.has(animation)) {
+ currentTime.set.call(animation, (state.frozenAt - state.offset - state.deferred.get(animation)) * animation.playbackRate);
+ } else {
+ const at = currentTime.get.call(animation);
+ if (at != null) currentTime.set.call(animation, Number(at) + ms * animation.playbackRate);
+ }
+ }
+ },
+ thaw() {
+ if (state.frozenAt == null) return;
+ // The held runs restart from the timeline's last frame time below. The
+ // frozen span ends at that same instant, so the page's clock and its
+ // runs stay together.
+ const frame = timelineTime.call(document.timeline);
+ state.offset += (frame == null ? rawNow() : Number(frame)) - state.frozenAt;
+ state.frozenAt = null;
+ const held = [...state.held];
+ state.held.clear();
+ for (const animation of held) {
+ const deferred = state.deferred.has(animation);
+ const value = state.deferred.get(animation);
+ state.deferred.delete(animation);
+ // On from where it stood, dated on the timeline's own time. A plain
+ // play() resolves its start later, and WebKit then resumed at the start
+ // it had before the pause. A start the page wrote while frozen resumes
+ // the same way, from the time it held. The timeline reads the current
+ // frame's time, which trails the page's clock by however far into the
+ // frame the thaw runs. So a start dated from now would sit before its
+ // start for the rest of that frame.
+ const at = currentTime.get.call(animation);
+ const timeline = timelineTime.call(document.timeline);
+ if (playState.get.call(animation) === 'idle') {
+ // A run the page cancelled while frozen (a CSS transition it
+ // reversed, a CSS animation it removed) stays cancelled.
+ } else if (at != null && timeline != null && animation.playbackRate !== 0) {
+ startTime.set.call(animation, Number(timeline) - Number(at) / animation.playbackRate);
+ } else if (deferred) {
+ startTime.set.call(animation, value + state.offset);
+ } else {
+ nativePlay.call(animation);
+ }
+ }
+ },
+ };
+})()`;
+
+/**
+ * Installs the page clock a freeze needs, for this page and every document it
+ * loads from now on. Opt-in: a page without it is untouched. Call it before
+ * the page under test loads, and before `installTimerGate`.
+ */
+export async function installPageFreeze(page: Page): Promise<void> {
+ await page.addInitScript(FREEZE_SCRIPT);
+ await page.evaluate(FREEZE_SCRIPT);
+}
+
+/**
+ * Freezes the scene in one page task. Every animation pauses where it stands,
+ * the timer gate holds timers and frame callbacks, and every time the page
+ * reads stands still. Needs `installPageFreeze` before the page loaded and
+ * `installTimerGate` after.
+ */
+export async function freezePage(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __harnessFreeze?: {freeze(): void};
+ __harnessTimerGate?: {freeze(isClockStopped: boolean): void};
+ };
+ if (w.__harnessFreeze == null || w.__harnessTimerGate == null) {
+ throw new Error(
+ 'freezePage: call installPageFreeze before the page loads, then installTimerGate',
+ );
+ }
+ w.__harnessFreeze.freeze();
+ w.__harnessTimerGate.freeze(true);
+ });
+}
+
+/**
+ * Arms a one-shot freeze on the page's next `type` event (a `touchstart`, a
+ * `touchend`, a `scroll`). The scene freezes in the event's own task, before
+ * any page listener for it runs. So what the page starts for that input is held
+ * at its start however late the test process reacts. Pointer, touch, mouse,
+ * key, wheel and scroll events can arm a freeze; any other type throws.
+ */
+export async function freezePageOn(page: Page, type: string): Promise<void> {
+ await page.evaluate(eventType => {
+ const w = window as unknown as {
+ __harnessFreeze?: {arm(type: string): void};
+ __harnessTimerGate?: {freeze(isClockStopped: boolean): void};
+ };
+ if (w.__harnessFreeze == null || w.__harnessTimerGate == null) {
+ throw new Error(
+ 'freezePageOn: call installPageFreeze before the page loads, then installTimerGate',
+ );
+ }
+ w.__harnessFreeze.arm(eventType);
+ }, type);
+}
+
+/**
+ * Freezes the scene in the first frame where `predicate(arg)` holds in the
+ * page, checked on every real frame. The scene stops where the proof wants it
+ * however late the test process reacts. `predicate` runs in the page (it is
+ * serialized, as for `page.waitForFunction`); it may read layout. Rejects past
+ * `timeout` ms without freezing.
+ */
+export async function freezePageWhen<A>(
+ page: Page,
+ predicate: (arg: A) => boolean,
+ arg: A,
+ {timeout = 5_000}: {timeout?: number} = {},
+): Promise<void> {
+ await page.evaluate(
+ ([source, value, wait]) =>
+ new Promise<void>((resolve, reject) => {
+ const w = window as unknown as {
+ __harnessFreeze?: {
+ freeze(): void;
+ frame: (callback: () => void) => number;
+ realNow: () => number;
+ };
+ __harnessTimerGate?: {freeze(isClockStopped: boolean): void};
+ };
+ const freeze = w.__harnessFreeze;
+ const gate = w.__harnessTimerGate;
+ if (freeze == null || gate == null) {
+ reject(
+ new Error(
+ 'freezePageWhen: call installPageFreeze before the page loads, then installTimerGate',
+ ),
+ );
+ return;
+ }
+ const check = new Function(`return (${source});`)() as (
+ value: unknown,
+ ) => boolean;
+ // The real clock: the page's own stands still while it is frozen.
+ const deadline = freeze.realNow() + wait;
+ const tick = () => {
+ let isMet: boolean;
+ try {
+ isMet = check(value);
+ } catch (error) {
+ reject(error);
+ return;
+ }
+ if (isMet) {
+ freeze.freeze();
+ gate.freeze(true);
+ resolve();
+ } else if (freeze.realNow() > deadline) {
+ reject(
+ new Error(
+ `freezePageWhen: the condition did not hold within ${wait} ms`,
+ ),
+ );
+ } else {
+ freeze.frame(tick);
+ }
+ };
+ freeze.frame(tick);
+ }),
+ [predicate.toString(), arg, timeout] as const,
+ );
+}
+
+/**
+ * Moves a frozen scene on by `ms`. The page's clock and every held animation
+ * advance together, as if `ms` had passed, while timers and frame callbacks
+ * stay held for the thaw. A proof steps the scene to the instant it wants (a
+ * lens mid-slide) by the scene's own time, however loaded the runner is.
+ */
+export async function advanceFrozenPage(page: Page, ms: number): Promise<void> {
+ await page.evaluate(step => {
+ const w = window as unknown as {
+ __harnessFreeze?: {advance(ms: number): void};
+ __harnessTimerGate?: {catchUp(): void};
+ };
+ if (w.__harnessFreeze == null) {
+ throw new Error('advanceFrozenPage: call installPageFreeze first');
+ }
+ w.__harnessFreeze.advance(step);
+ // Timeouts the page's clock reached are held for the thaw.
+ w.__harnessTimerGate?.catchUp();
+ }, ms);
+}
+
+/**
+ * Thaws the scene in one page task. Every animation held by the freeze plays on
+ * from where it stood, one the page started while frozen from its start. The
+ * page's time runs again, and the held timers and frame callbacks run in the
+ * order they came due.
+ */
+export async function thawPage(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __harnessFreeze?: {thaw(): void};
+ __harnessTimerGate?: {thaw(): void};
+ };
+ w.__harnessFreeze?.thaw();
+ w.__harnessTimerGate?.thaw();
+ });
+}
diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
index a7997f1d79..3beb43d008 100644
--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts
+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
@@ -31,7 +31,10 @@
* until the filmstrip is done, drops callbacks the page cancels, stamps held
* frames with the time they run, and leaves the harness its own frames; a
* cast filmstrip keeps exactly the presented frames of its window, labelled
- * from its zero, as PNG.
+ * from its zero, as PNG; a page freeze holds every animation, timer and
+ * clock the page reads and thaws each animation from where it stood (one the
+ * page dated while frozen too), arms on an input ahead of the page's own
+ * listeners, steps by the scene's own clock, and freezes on a condition.
* @position The harness's own test. A component spec trusts these
* instruments; this file is why it may.
*/
@@ -42,6 +45,7 @@ import path from 'node:path';
import {expect, test, type Page} from '@playwright/test';
import type {CastFrame, TrackedFrame} from './frames';
import {
+ advanceFrozenPage,
armHold,
animationStoryboard,
castStoryboard,
@@ -55,11 +59,15 @@ import {
drag,
flick,
frames,
+ freezePage,
+ freezePageOn,
+ freezePageWhen,
freezeTimers,
holdAnimations,
installInputLog,
type InputRecord,
installLongTaskLog,
+ installPageFreeze,
installTimerGate,
markElement,
merge,
@@ -80,6 +88,7 @@ import {
startBusyControl,
Storyboard,
tap,
+ thawPage,
thawTimers,
timeline,
touchDriver,
@@ -4182,3 +4191,567 @@ test.describe('storyboards', {tag: '@storyboard'}, () => {
await expect(empty.write(testInfo)).rejects.toThrow(/no frames/);
});
});
+
+const FREEZE_FIXTURE = `<!doctype html><meta name=viewport content="width=device-width,initial-scale=1">
+<style>body{margin:0} #box{position:absolute;left:0;top:40px;width:40px;height:40px;background:#0a7}</style>
+<div id="box"></div>
+<script>
+ // The page's own key handler, registered at load on the window's capture
+ // phase: it records whether a freeze was already on, starts a run and then
+ // keeps the main thread busy. The loop counts work, not time: the page's
+ // clocks stand still while it is frozen.
+ window.addEventListener('keydown', () => {
+ window.frozenAtHandler = window.__harnessFreeze?.frozen ?? null;
+ document.getElementById('box').animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(400px)'}],
+ {duration: 2000, easing: 'linear'},
+ );
+ let work = 0;
+ for (let i = 0; i < 4e7; i++) work += i % 7;
+ window.work = work;
+ }, true);
+</script>`;
+
+async function freezeFixture(page: Page) {
+ await page.route('http://freeze.test/', route =>
+ route.fulfill({contentType: 'text/html', body: FREEZE_FIXTURE}),
+ );
+ await page.goto('http://freeze.test/');
+}
+
+/** The box's run as the page reads it, and the page's clocks. */
+const readScene = (page: Page) =>
+ page.locator('#box').evaluate(el => {
+ const animation = el.getAnimations()[0];
+ return {
+ x: new DOMMatrix(getComputedStyle(el).transform).m41,
+ now: performance.now(),
+ date: Date.now(),
+ timeline: Number(document.timeline.currentTime),
+ current: animation == null ? null : Number(animation.currentTime),
+ state: animation?.playState ?? null,
+ };
+ });
+
+/** Starts a 2 s linear run of the box over 400 px. */
+const startRun = (page: Page) =>
+ page.locator('#box').evaluate(el => {
+ el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(400px)'}],
+ {duration: 2_000, easing: 'linear'},
+ );
+ });
+
+test.describe('page freeze', () => {
+ test('a frozen scene stands still and reads no time passing; thawed, it plays on from where it stood, and the frozen span counts for neither its clock nor its animation', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await startRun(page);
+ await waitForAnimation(page.locator('#box'), {minProgressMs: 100});
+ await freezePage(page);
+ const frozen = await readScene(page);
+ const frozenAt = Date.now();
+ await page.waitForTimeout(300);
+ const still = await readScene(page);
+ expect(still).toEqual(frozen);
+ expect(still.state).toBe('running');
+ // Read in the thaw's own task: the run resumes exactly where it stood.
+ const atThaw = await page.locator('#box').evaluate(el => {
+ (
+ window as unknown as {__harnessFreeze: {thaw(): void}}
+ ).__harnessFreeze.thaw();
+ return Number(el.getAnimations()[0].currentTime);
+ });
+ expect(atThaw).toBeCloseTo(frozen.current ?? NaN, 3);
+ await thawPage(page);
+ await page.waitForTimeout(200);
+ const thawed = await readScene(page);
+ const elapsed = Date.now() - frozenAt;
+ const moved = (thawed.current ?? 0) - (frozen.current ?? 0);
+ expect(moved).toBeGreaterThan(100);
+ expect(thawed.x).toBeGreaterThan(frozen.x);
+ // The 300 ms frozen span counts for neither the run nor the page's clock.
+ expect(elapsed - moved).toBeGreaterThan(250);
+ expect(elapsed - (thawed.now - frozen.now)).toBeGreaterThan(250);
+ });
+
+ test("a freeze armed on an input lands before the page's own listeners for it, so a slow handler's run is held at its start", async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await freezePageOn(page, 'keydown');
+ await page.keyboard.press('a');
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {frozenAtHandler: unknown}).frozenAtHandler,
+ ),
+ ).toBe(true);
+ const held = await readScene(page);
+ expect(held.current).toBe(0);
+ await page.waitForTimeout(250);
+ expect((await readScene(page)).current).toBe(0);
+ await thawPage(page);
+ // Only an input the install listens for can arm a freeze.
+ await expect(freezePageOn(page, 'focus')).rejects.toThrow(/arms only on/);
+ });
+
+ test('without a freeze the same slow handler runs first, and a late read finds its run well along', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await page.keyboard.press('a');
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {frozenAtHandler: unknown}).frozenAtHandler,
+ ),
+ ).toBe(false);
+ await page.waitForTimeout(250);
+ expect((await readScene(page)).current).toBeGreaterThan(150);
+ });
+
+ test("an advance moves the page's clock and every held animation on together, while timers stay held", async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await startRun(page);
+ await waitForAnimation(page.locator('#box'), {minProgressMs: 50});
+ await freezePage(page);
+ await page.evaluate(() => {
+ setTimeout(() => {
+ (window as unknown as {timerRan?: boolean}).timerRan = true;
+ }, 10);
+ });
+ const before = await readScene(page);
+ await advanceFrozenPage(page, 120);
+ const after = await readScene(page);
+ expect(after.now - before.now).toBeCloseTo(120, 6);
+ expect(after.timeline - before.timeline).toBeCloseTo(120, 6);
+ expect((after.current ?? 0) - (before.current ?? 0)).toBeCloseTo(120, 6);
+ expect(after.x - before.x).toBeCloseTo(24, 1);
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {timerRan?: boolean}).timerRan,
+ ),
+ ).toBeUndefined();
+ await thawPage(page);
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {timerRan?: boolean}).timerRan,
+ ),
+ ).toBe(true);
+ });
+
+ test('a freeze on a condition stops the scene on the first frame it holds, and rejects when it never does', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ const reached = freezePageWhen(
+ page,
+ (min: number) => {
+ const box = document.getElementById('box');
+ return (
+ box != null &&
+ new DOMMatrix(getComputedStyle(box).transform).m41 >= min
+ );
+ },
+ 100,
+ );
+ await startRun(page);
+ await reached;
+ const frozen = await readScene(page);
+ expect(frozen.x).toBeGreaterThanOrEqual(100);
+ expect(frozen.x).toBeLessThan(400);
+ await page.waitForTimeout(200);
+ expect((await readScene(page)).x).toBe(frozen.x);
+ // On a frozen page the page's clock stands still: the timeout runs on
+ // the real one.
+ await expect(
+ freezePageWhen(page, () => false, null, {timeout: 300}),
+ ).rejects.toThrow(/did not hold within 300 ms/);
+ await thawPage(page);
+ await expect(
+ freezePageWhen(page, () => false, null, {timeout: 300}),
+ ).rejects.toThrow(/did not hold within 300 ms/);
+ });
+
+ test('a start the page dates while frozen resumes at the thaw from where it held, in the thaw task itself', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await freezePage(page);
+ await page.locator('#box').evaluate(el => {
+ const animation = el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(400px)'}],
+ {duration: 2_000, easing: 'linear'},
+ );
+ animation.startTime = performance.now();
+ });
+ await advanceFrozenPage(page, 100);
+ expect((await readScene(page)).current).toBeCloseTo(100, 6);
+ // Read in the thaw's own task, before any frame: the timeline still
+ // reads its last frame's time, which trails the page's clock.
+ const atThaw = await page.locator('#box').evaluate(el => {
+ (
+ window as unknown as {__harnessFreeze: {thaw(): void}}
+ ).__harnessFreeze.thaw();
+ return Number(el.getAnimations()[0].currentTime);
+ });
+ expect(atThaw).toBeCloseTo(100, 3);
+ await thawPage(page);
+ });
+
+ test('a timeout pending across a freeze comes due on the page’s clock, not early by the frozen span', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ // A 3 s run and a 1 s timeout started together: they share the page's
+ // clock, so the timeout comes due with the run 1 s in.
+ await page.locator('#box').evaluate(el => {
+ const animation = el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(400px)'}],
+ {duration: 3_000, easing: 'linear'},
+ );
+ setTimeout(() => {
+ (window as unknown as {firedAt?: number}).firedAt = Number(
+ animation.currentTime,
+ );
+ }, 1_000);
+ });
+ await page.waitForTimeout(100);
+ await freezePage(page);
+ await page.waitForTimeout(600);
+ await thawPage(page);
+ const firedAt = () =>
+ page.evaluate(
+ () => (window as unknown as {firedAt?: number}).firedAt ?? null,
+ );
+ await expect.poll(firedAt, {timeout: 5_000}).not.toBeNull();
+ // On the real clock it would come 600 ms early, the run about 400 ms in.
+ // The run's time is its last frame's: up to two frames behind.
+ expect(await firedAt()).toBeGreaterThan(1_000 - 34);
+ expect(await firedAt()).toBeLessThan(3_000);
+ });
+
+ test('a scroll-driven animation is left to its scroller, and the page’s timeline keeps reading time', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ const hasScrollTimeline = await page.evaluate(
+ () =>
+ typeof (window as {ScrollTimeline?: unknown}).ScrollTimeline ===
+ 'function',
+ );
+ test.skip(!hasScrollTimeline, 'this engine has no ScrollTimeline');
+ await page.evaluate(() => {
+ const spacer = document.createElement('div');
+ spacer.style.height = '4000px';
+ document.body.append(spacer);
+ const ScrollTimeline = (
+ window as unknown as {
+ ScrollTimeline: new (options: {source: Element}) => AnimationTimeline;
+ }
+ ).ScrollTimeline;
+ const source = document.scrollingElement ?? document.documentElement;
+ const timeline = new ScrollTimeline({source});
+ document
+ .getElementById('box')
+ ?.animate([{opacity: 0}, {opacity: 1}], {timeline});
+ // A scroll timeline's time is a percentage, read once here.
+ void timeline.currentTime;
+ });
+ const pageTime = () =>
+ page.evaluate(() => Number(document.timeline.currentTime));
+ const scrollTime = () =>
+ page.evaluate(() => {
+ const animation = document
+ .getElementById('box')
+ ?.getAnimations()
+ .find(each => each.timeline !== document.timeline);
+ return animation == null ? null : String(animation.currentTime);
+ });
+ expect(Number.isFinite(await pageTime())).toBe(true);
+ await freezePage(page);
+ const before = await scrollTime();
+ expect(before).not.toBeNull();
+ // Frozen, the scroll-driven run still follows its scroller.
+ await page.evaluate(() => window.scrollTo(0, 2_000));
+ await expect.poll(scrollTime).not.toBe(before);
+ expect(Number.isFinite(await pageTime())).toBe(true);
+ await thawPage(page);
+ expect(Number.isFinite(await pageTime())).toBe(true);
+ });
+
+ test('on a frozen page the harness still samples, arms a hold and blocks the main thread, on the real clock', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await freezePage(page);
+ const box = page.locator('#box');
+ const samples = await sampleRects(box, 200);
+ expect(samples.length).toBeGreaterThan(3);
+ const hold = await armHold(page, box, {timeout: 300});
+ await expect(hold.held()).rejects.toThrow(
+ 'armHold: no animation under the scope ran within 300 ms',
+ );
+ const blocked = await blockMainThread(page, 50);
+ expect(blocked.spanMs).toBeGreaterThanOrEqual(50);
+ await thawPage(page);
+ });
+
+ test('a CSS animation the page resumes while frozen is held where it stands, not at its start', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ // A CSS run paused 500 ms in, before the freeze.
+ await page.locator('#box').evaluate(el => {
+ const style = document.createElement('style');
+ style.textContent =
+ '@keyframes slide { to { transform: translateX(400px); } }';
+ document.head.append(style);
+ (el as HTMLElement).style.animation = 'slide 2s linear paused';
+ el.getAnimations()[0].currentTime = 500;
+ });
+ const at = () =>
+ page
+ .locator('#box')
+ .evaluate(el => Number(el.getAnimations()[0].currentTime));
+ expect(await at()).toBeCloseTo(500, 0);
+ await freezePage(page);
+ // The page resumes it by CSS while frozen.
+ await page.locator('#box').evaluate(el => {
+ (el as HTMLElement).style.animationPlayState = 'running';
+ });
+ await page.waitForTimeout(100);
+ expect(await at()).toBeCloseTo(500, 0);
+ await thawPage(page);
+ await page.waitForTimeout(100);
+ expect(await at()).toBeGreaterThan(500);
+ });
+
+ test('a CSS transition the page reverses while frozen plays the reversal after the thaw, not the old run from its start', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ const box = page.locator('#box');
+ await box.evaluate(el => {
+ const element = el as HTMLElement;
+ element.style.transition = 'transform 1s linear';
+ void getComputedStyle(element).transform;
+ element.style.transform = 'translateX(400px)';
+ });
+ // About 160 px along, frozen; the page sends the box back.
+ await page.waitForTimeout(400);
+ await freezePage(page);
+ await box.evaluate(el => {
+ (el as HTMLElement).style.transform = 'translateX(0px)';
+ });
+ const frozenAt = (await box.boundingBox())?.x ?? NaN;
+ await thawPage(page);
+ await page.waitForTimeout(100);
+ const soon = (await box.boundingBox())?.x ?? NaN;
+ await page.waitForTimeout(500);
+ const later = (await box.boundingBox())?.x ?? NaN;
+ // Back toward 0 all along: never past where it stood when frozen.
+ expect(soon).toBeLessThanOrEqual(frozenAt + 1);
+ expect(later).toBeLessThanOrEqual(soon + 1);
+ });
+
+ test('after a thaw, blockMainThread stamps its window on the real clock', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await freezePage(page);
+ await page.waitForTimeout(600);
+ await thawPage(page);
+ const before = Date.now();
+ const blocked = await blockMainThread(page, 50);
+ const after = Date.now();
+ // The page's own clock trails the real one by the 600 ms frozen span.
+ expect(blocked.from).toBeGreaterThan(before - 50);
+ expect(blocked.to).toBeLessThan(after + 50);
+ });
+
+ test('after a thaw, waitForAnimation and sampleRects stamp on the real clock', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await freezePage(page);
+ await page.waitForTimeout(600);
+ await thawPage(page);
+ const box = page.locator('#box');
+ const before = Date.now();
+ await box.evaluate(el => {
+ el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(100px)'}],
+ {duration: 400},
+ );
+ });
+ const [run] = await waitForAnimation(box);
+ const samples = await sampleRects(box, 100);
+ const after = Date.now();
+ // The page's own clock trails the real one by the 600 ms frozen span.
+ expect(run.from).toBeGreaterThan(before - 50);
+ expect(run.from).toBeLessThan(after + 50);
+ expect(samples.length).toBeGreaterThan(0);
+ for (const sample of samples) {
+ expect(sample.t).toBeGreaterThan(before - 50);
+ expect(sample.t).toBeLessThan(after + 50);
+ }
+ });
+
+ test('a CSS animation the page dates and then removes while frozen stays removed after the thaw', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ const box = page.locator('#box');
+ await page.evaluate(() => {
+ const style = document.createElement('style');
+ style.textContent =
+ '@keyframes slide { to { transform: translateX(400px); } }';
+ document.head.append(style);
+ });
+ await freezePage(page);
+ // Started, dated and removed, all while frozen.
+ await box.evaluate(el => {
+ (el as HTMLElement).style.animation = 'slide 2s linear';
+ });
+ await page.waitForTimeout(100);
+ await box.evaluate(el => {
+ el.getAnimations()[0].startTime = document.timeline.currentTime;
+ (el as HTMLElement).style.animation = 'none';
+ // Style is read at once, so the run is cancelled before the thaw.
+ void getComputedStyle(el).animationName;
+ });
+ await page.waitForTimeout(100);
+ await thawPage(page);
+ await page.waitForTimeout(300);
+ expect(await box.evaluate(el => el.getAnimations().length)).toBe(0);
+ expect(await box.evaluate(el => getComputedStyle(el).transform)).toBe(
+ 'none',
+ );
+ });
+
+ test('a run that finished before a freeze is dated where it ran, read after the thaw', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ const box = page.locator('#box');
+ const watch = await watchAnimations(box);
+ const startedAt = Date.now();
+ await box.evaluate(el => {
+ el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(100px)'}],
+ {duration: 200},
+ );
+ });
+ // Over before the freeze, and read only after the thaw.
+ await page.waitForTimeout(400);
+ const frozenAt = Date.now();
+ await freezePage(page);
+ await page.waitForTimeout(600);
+ await thawPage(page);
+ const [finished] = await watch.started();
+ expect(finished.from).toBeGreaterThan(startedAt - 50);
+ expect(finished.from).toBeLessThan(frozenAt);
+ expect(finished.finishedAt).not.toBeNull();
+ expect(Number(finished.finishedAt)).toBeLessThan(frozenAt);
+ });
+
+ test('the page’s clock and its runs stay together across ten freeze and thaw cycles', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await page.locator('#box').evaluate(el => {
+ (window as unknown as {run?: Animation}).run = el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(400px)'}],
+ {duration: 60_000, easing: 'linear'},
+ );
+ });
+ await page.waitForTimeout(100);
+ // Where the run started, on the page's clock, before any freeze.
+ const startedAt = await page.evaluate(() =>
+ Number((window as unknown as {run: Animation}).run.startTime),
+ );
+ for (let cycle = 0; cycle < 10; cycle++) {
+ await freezePage(page);
+ await page.waitForTimeout(50);
+ await thawPage(page);
+ await page.waitForTimeout(30);
+ }
+ // In one frame: the run's time against the page's time since it started.
+ const drift = await page.evaluate(
+ start =>
+ new Promise<number>(resolve => {
+ requestAnimationFrame(time => {
+ const run = (window as unknown as {run: Animation}).run;
+ resolve(Number(run.currentTime) - (time - start));
+ });
+ }),
+ startedAt,
+ );
+ expect(Math.abs(drift)).toBeLessThan(5);
+ });
+
+ test('a condition that throws rejects freezePageWhen with its error', async ({
+ page,
+ }) => {
+ await installPageFreeze(page);
+ await freezeFixture(page);
+ await installTimerGate(page);
+ await expect(
+ freezePageWhen(
+ page,
+ () => {
+ throw new Error('the condition broke');
+ },
+ undefined,
+ {timeout: 2_000},
+ ),
+ ).rejects.toThrow('the condition broke');
+ });
+
+ test('a page without the freeze keeps its own clock, and a freeze there refuses to start', async ({
+ page,
+ }) => {
+ await freezeFixture(page);
+ await installTimerGate(page);
+ expect(await page.evaluate(() => '__harnessFreeze' in window)).toBe(false);
+ await expect(freezePage(page)).rejects.toThrow(/installPageFreeze/);
+ await expect(freezePageOn(page, 'keydown')).rejects.toThrow(
+ /installPageFreeze/,
+ );
+ });
+});
diff --git a/internal/interaction-harness/src/index.ts b/internal/interaction-harness/src/index.ts
index d875069dc5..e4d636021e 100644
--- a/internal/interaction-harness/src/index.ts
+++ b/internal/interaction-harness/src/index.ts
@@ -17,6 +17,7 @@
export * from './busy';
export * from './curves';
export * from './frames';
+export * from './freeze';
export * from './math';
export * from './output';
export * from './scripts';
diff --git a/internal/interaction-harness/src/story.ts b/internal/interaction-harness/src/story.ts
index 627969a663..a791579373 100644
--- a/internal/interaction-harness/src/story.ts
+++ b/internal/interaction-harness/src/story.ts
@@ -154,7 +154,10 @@ 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.
+// 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.
const TIMER_GATE = `(() => {
if (window.__harnessTimerGate) return;
const realTimeout = window.setTimeout.bind(window);
@@ -162,17 +165,81 @@ const TIMER_GATE = `(() => {
const realInterval = window.setInterval.bind(window);
const realFrame = window.requestAnimationFrame.bind(window);
const realCancelFrame = window.cancelAnimationFrame.bind(window);
- const gate = {frozen: false, queue: [], frame: realFrame, timeout: realTimeout};
+ // The page freeze (freeze.ts) installs first and keeps the real clock.
+ const realNow = window.__harnessFreeze ? window.__harnessFreeze.realNow : () => performance.now();
+ // Timeouts not yet due, by the id the page holds: the real timer that runs
+ // it, and when it comes due on the page's clock (performance.now, which a
+ // page freeze stops).
+ const pending = new Map();
+ let isPaused = false;
+ const fire = (id, entry) => {
+ pending.delete(id);
+ if (gate.frozen) gate.queue.push({key: 't' + id, run: entry.run}); else entry.run();
+ };
+ const arm = (id, entry, ms) => { entry.real = realTimeout(() => fire(id, entry), ms); };
+ const gate = {
+ frozen: false,
+ queue: [],
+ frame: realFrame,
+ now: realNow,
+ timeout: realTimeout,
+ // Holds every callback that comes due. With the page's clock stopped as
+ // well, the timeouts not yet due stop counting.
+ freeze(isClockStopped = false) {
+ gate.frozen = true;
+ if (isClockStopped && !isPaused) {
+ isPaused = true;
+ for (const entry of pending.values()) realClearTimeout(entry.real);
+ }
+ },
+ // Holds the stopped timeouts the page's clock has reached, in the order
+ // they came due.
+ catchUp() {
+ if (!isPaused) return;
+ const now = performance.now();
+ const due = [...pending].filter(([, entry]) => entry.due <= now).sort((a, b) => a[1].due - b[1].due);
+ for (const [id, entry] of due) {
+ pending.delete(id);
+ gate.queue.push({key: 't' + id, run: entry.run});
+ }
+ },
+ // Runs the held callbacks in the order they came due, then restarts the
+ // stopped timeouts for what is left of them on the page's clock.
+ thaw() {
+ gate.catchUp();
+ gate.frozen = false;
+ try {
+ // One at a time from the live queue: a callback may cancel a later
+ // one. A callback that throws still leaves the clock running.
+ while (gate.queue.length > 0) gate.queue.shift().run();
+ } finally {
+ if (isPaused) {
+ isPaused = false;
+ const now = performance.now();
+ for (const [id, entry] of pending) arm(id, entry, Math.max(0, entry.due - now));
+ }
+ }
+ },
+ };
window.__harnessTimerGate = gate;
const drop = key => { gate.queue = gate.queue.filter(entry => entry.key !== key); };
window.setTimeout = (fn, ms, ...args) => {
- const id = realTimeout(() => {
- const run = () => (typeof fn === 'function' ? fn(...args) : 0);
- if (gate.frozen) gate.queue.push({key: 't' + id, run}); else run();
- }, ms);
+ const delay = Math.max(0, Number(ms) || 0);
+ const entry = {due: performance.now() + delay, real: 0, run: () => (typeof fn === 'function' ? fn(...args) : 0)};
+ // The first real timer's id is the one the page holds. A stopped clock
+ // starts it again at the thaw.
+ const id = realTimeout(() => fire(id, entry), delay);
+ entry.real = id;
+ pending.set(id, entry);
+ if (isPaused) realClearTimeout(id);
return id;
};
- window.clearTimeout = id => { realClearTimeout(id); drop('t' + id); };
+ window.clearTimeout = id => {
+ const entry = pending.get(id);
+ pending.delete(id);
+ realClearTimeout(entry == null ? id : entry.real);
+ drop('t' + id);
+ };
window.setInterval = (fn, ms, ...args) => realInterval(() => { if (!gate.frozen && typeof fn === 'function') fn(...args); }, ms);
window.requestAnimationFrame = fn => {
const id = realFrame(time => {
@@ -202,35 +269,22 @@ export async function installTimerGate(page: Page): Promise<void> {
*/
export async function freezeTimers(page: Page): Promise<void> {
await page.evaluate(() => {
- const gate = (window as unknown as {__harnessTimerGate?: {frozen: boolean}})
+ const gate = (window as unknown as {__harnessTimerGate?: {freeze(): void}})
.__harnessTimerGate;
if (gate == null) {
throw new Error(
'freezeTimers: call installTimerGate before the animation starts',
);
}
- gate.frozen = true;
+ gate.freeze();
});
}
/** Releases the gate: held callbacks run now, in the order they came due. */
export async function thawTimers(page: Page): Promise<void> {
await page.evaluate(() => {
- const gate = (
- window as unknown as {
- __harnessTimerGate?: {
- frozen: boolean;
- queue: {key: string; run: () => void}[];
- };
- }
- ).__harnessTimerGate;
- if (gate == null) {
- return;
- }
- gate.frozen = false;
- // One at a time from the live queue: a callback may cancel a later one.
- while (gate.queue.length > 0) {
- gate.queue.shift()?.run();
- }
+ (
+ window as unknown as {__harnessTimerGate?: {thaw(): void}}
+ ).__harnessTimerGate?.thaw();
});
}
diff --git a/internal/interaction-harness/src/webInput.ts b/internal/interaction-harness/src/webInput.ts
index 539edb2eef..369070c9e5 100644
--- a/internal/interaction-harness/src/webInput.ts
+++ b/internal/interaction-harness/src/webInput.ts
@@ -452,18 +452,23 @@ async function untilRunReceived(
}>(resolve => {
// The harness's own wait runs on the real timer: a frozen timer gate
// (story.ts) holds only the page's.
- const later =
- (
- window as unknown as {
- __harnessTimerGate?: {timeout?: typeof setTimeout};
- }
- ).__harnessTimerGate?.timeout ?? window.setTimeout.bind(window);
- const deadline = performance.now() + ms;
+ const gate = (
+ window as unknown as {
+ __harnessTimerGate?: {
+ now?: () => number;
+ timeout?: typeof setTimeout;
+ };
+ }
+ ).__harnessTimerGate;
+ const later = gate?.timeout ?? window.setTimeout.bind(window);
+ // The deadline reads the real clock, which a page freeze does not stop.
+ const realNow = gate?.now ?? (() => performance.now());
+ const deadline = realNow() + ms;
const whole = () =>
Math.abs(run.dx - total.dx) < 0.01 &&
Math.abs(run.dy - total.dy) < 0.01;
const check = () => {
- if (whole() || performance.now() > deadline) {
+ if (whole() || realNow() > deadline) {
run.stop();
resolve({
stamps: run.stamps.slice(),