Skip to content

Commit 31095ca

Browse files
authored
fix(core): stop script loading time from shifting WAAPI frames
1 parent dd7290a commit 31095ca

3 files changed

Lines changed: 253 additions & 4 deletions

File tree

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
import { createWaapiAdapter } from "./waapi";
3+
4+
class TestAnimation {
5+
constructor(public currentTime = 0) {}
6+
playState = "running";
7+
playbackRate = 1;
8+
timeline: object | null = timeline;
9+
addEventListener = vi.fn();
10+
pause = vi.fn(() => {
11+
this.playState = "paused";
12+
});
13+
}
14+
class TestCssAnimation extends TestAnimation {}
15+
class TestCssTransition extends TestAnimation {}
16+
const timeline = {};
17+
18+
describe("initial WAAPI baseline", () => {
19+
let items: TestAnimation[];
20+
const create = (time = 300) => {
21+
const animation = new TestAnimation(time);
22+
items.push(animation);
23+
return animation;
24+
};
25+
26+
beforeEach(() => {
27+
items = [];
28+
vi.stubGlobal("document", { timeline, getAnimations: () => items });
29+
vi.stubGlobal("CSSAnimation", TestCssAnimation);
30+
vi.stubGlobal("CSSTransition", TestCssTransition);
31+
vi.stubGlobal("Element", undefined);
32+
});
33+
afterEach(() => vi.unstubAllGlobals());
34+
35+
it.each([0, 16, 90, 300, 1500])(
36+
"does not retain %d ms of initial wall-clock progress",
37+
(time) => {
38+
const animation = create(time);
39+
const adapter = createWaapiAdapter();
40+
adapter.discover();
41+
for (const t of [0, 2, 3.5, 2]) {
42+
adapter.seek({ time: t });
43+
expect(animation.currentTime).toBe(t * 1000);
44+
expect(animation.playState).toBe("paused");
45+
}
46+
},
47+
);
48+
49+
it.each(["seek", "pause"])("also anchors when %s is called before discover", (method) => {
50+
const animation = create();
51+
const adapter = createWaapiAdapter();
52+
if (method === "pause") adapter.pause();
53+
adapter.seek({ time: 2 });
54+
expect(animation.currentTime).toBe(2000);
55+
});
56+
57+
it("rewinds an animation that finished before initial discovery", () => {
58+
const animation = create(80);
59+
animation.playState = "finished";
60+
const adapter = createWaapiAdapter();
61+
adapter.discover();
62+
adapter.seek({ time: 0.04 });
63+
expect(animation.currentTime).toBe(40);
64+
});
65+
66+
it("does not reinterpret an idle animation", () => {
67+
const animation = create(500);
68+
animation.playState = "idle";
69+
const adapter = createWaapiAdapter();
70+
adapter.discover();
71+
adapter.seek({ time: 2 });
72+
expect(animation.currentTime).toBe(2500);
73+
});
74+
75+
it("keeps the captured baseline across repeated discovery at composition zero", () => {
76+
const animation = create(300);
77+
const adapter = createWaapiAdapter();
78+
adapter.discover();
79+
animation.currentTime = 900;
80+
adapter.discover();
81+
adapter.seek({ time: 2 });
82+
expect(animation.currentTime).toBe(2000);
83+
});
84+
85+
it.each([0, 500])("preserves a paused authored offset of %d ms", (time) => {
86+
const animation = create(time);
87+
animation.playState = "paused";
88+
const adapter = createWaapiAdapter();
89+
adapter.discover();
90+
adapter.seek({ time: 2 });
91+
expect(animation.currentTime).toBe(2000 + time);
92+
});
93+
94+
it.each([TestCssAnimation, TestCssTransition])("leaves $name baselines unchanged", (Type) => {
95+
const animation = new Type(500);
96+
items.push(animation);
97+
const adapter = createWaapiAdapter();
98+
adapter.discover();
99+
adapter.seek({ time: 2 });
100+
expect(animation.currentTime).toBe(2500);
101+
});
102+
103+
it.each([null, {}])("leaves an alternate or absent timeline unchanged", (otherTimeline) => {
104+
const animation = create(500);
105+
animation.timeline = otherTimeline;
106+
const adapter = createWaapiAdapter();
107+
adapter.discover();
108+
adapter.seek({ time: 2 });
109+
expect(animation.currentTime).toBe(2500);
110+
});
111+
112+
it.each([-1, 0, 2])("does not reinterpret a playback rate of %d", (rate) => {
113+
const animation = create(500);
114+
animation.playbackRate = rate;
115+
const adapter = createWaapiAdapter();
116+
adapter.discover();
117+
adapter.seek({ time: 2 });
118+
expect(animation.currentTime).toBe(2500);
119+
});
120+
121+
it("preserves late discovery and rediscovery relative to composition time", () => {
122+
const adapter = createWaapiAdapter();
123+
create(100);
124+
adapter.discover();
125+
adapter.seek({ time: 1 });
126+
const late = create(0);
127+
adapter.seek({ time: 1.2 });
128+
expect(late.currentTime).toBe(0);
129+
adapter.discover();
130+
adapter.seek({ time: 2 });
131+
expect(late.currentTime).toBe(800);
132+
});
133+
134+
it("can capture initial animations again after revert", () => {
135+
const adapter = createWaapiAdapter();
136+
const animation = create();
137+
adapter.discover();
138+
adapter.seek({ time: 2 });
139+
adapter.revert();
140+
animation.currentTime = 300;
141+
animation.playState = "running";
142+
adapter.discover();
143+
adapter.seek({ time: 2 });
144+
expect(animation.currentTime).toBe(2000);
145+
});
146+
});

‎packages/core/src/runtime/adapters/waapi.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
5353
return animationTimeMs;
5454
};
5555

56+
const shouldAnchorAtCompositionOrigin = (animation: Animation, compositionTimeMs: number) =>
57+
!didDiscover &&
58+
compositionTimeMs === 0 &&
59+
(animation.playState === "running" || animation.playState === "finished") &&
60+
animation.playbackRate === 1 &&
61+
!!document.timeline &&
62+
animation.timeline === document.timeline &&
63+
!isBrowserCreatedCss(animation);
64+
5665
const ensureBaseline = (animation: Animation, compositionTimeMs: number) => {
5766
const existing = baselines.get(animation);
5867
if (existing) {
@@ -61,9 +70,11 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
6170

6271
const baseline = {
6372
compositionTimeMs,
64-
animationTimeMs: didDiscover
65-
? normalizeInitialAnimationTimeMs(readAnimationTimeMs(animation), compositionTimeMs)
66-
: readAnimationTimeMs(animation),
73+
animationTimeMs: shouldAnchorAtCompositionOrigin(animation, compositionTimeMs)
74+
? 0
75+
: didDiscover
76+
? normalizeInitialAnimationTimeMs(readAnimationTimeMs(animation), compositionTimeMs)
77+
: readAnimationTimeMs(animation),
6778
};
6879
baselines.set(animation, baseline);
6980
return baseline;
@@ -147,9 +158,9 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
147158
return {
148159
name: "waapi",
149160
discover: () => {
150-
didDiscover = true;
151161
installAnimateHook();
152162
trackAnimations(snapshotAnimations(), lastSeekTimeMs);
163+
didDiscover = true;
153164
},
154165
seek: (ctx) => {
155166
const timeMs = Math.max(0, (Number(ctx.time) || 0) * 1000);

‎packages/producer/src/services/coreRuntimeBrowser.test.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,98 @@ describe("core runtime browser contract", () => {
199199
});
200200
});
201201

202+
it.each([
203+
{ name: "running after 80 ms", elapsed: 80 },
204+
{ name: "running after 250 ms", elapsed: 250 },
205+
{ name: "positive delay", elapsed: 80, delay: 500 },
206+
{ name: "negative delay", elapsed: 80, delay: -500 },
207+
{ name: "reverse keyframes", elapsed: 80, reverse: true },
208+
{ name: "finished before discovery", elapsed: 200, duration: 200 },
209+
{ name: "paused authored offset", elapsed: 80, paused: true, offset: 500 },
210+
{ name: "paused at zero", elapsed: 80, paused: true, offset: 0 },
211+
{ name: "running currentTime is not a baseline offset", elapsed: 80, offset: 500 },
212+
])(
213+
"seeks initial WAAPI in composition time: $name",
214+
async ({
215+
elapsed,
216+
delay = 0,
217+
duration = 4000,
218+
reverse = false,
219+
paused = false,
220+
offset = 0,
221+
}) => {
222+
const animationPage = await browser.newPage();
223+
try {
224+
await animationPage.setContent(`<!doctype html>
225+
<div data-composition-id="root" data-root="true" data-no-timeline
226+
data-start="0" data-duration="4" data-width="320" data-height="180">
227+
<div id="waapi-box" class="clip" data-start="0" data-duration="4"></div>
228+
</div>`);
229+
await animationPage.evaluate(
230+
({ delay, duration, reverse, paused, offset }) => {
231+
const box = document.getElementById("waapi-box");
232+
if (!box) throw new Error("waapi-box missing");
233+
const animation = box.animate(
234+
[{ transform: "translateX(0px)" }, { transform: "translateX(100px)" }],
235+
{ duration, delay, direction: reverse ? "reverse" : "normal", fill: "both" },
236+
);
237+
if (paused) animation.pause();
238+
if (offset || paused) animation.currentTime = offset;
239+
},
240+
{ delay, duration, reverse, paused, offset },
241+
);
242+
if (!paused) {
243+
// Wait for actual browser progress, not a guessed sleep duration.
244+
await animationPage.waitForFunction(
245+
(minimumTime) =>
246+
Number(document.getElementById("waapi-box")?.getAnimations()[0]?.currentTime) >=
247+
minimumTime,
248+
{},
249+
elapsed + offset,
250+
);
251+
}
252+
await animationPage.addScriptTag({ content: readFileSync(RUNTIME_PATH, "utf8") });
253+
await animationPage.waitForFunction(
254+
() =>
255+
(window as unknown as { __playerReady?: boolean }).__playerReady === true &&
256+
(window as unknown as { __renderReady?: boolean }).__renderReady === true,
257+
);
258+
const times = duration === 200 ? [0, 0.1, 1 / 6, 0.1] : [0, 2, 3, 2];
259+
const samples = await animationPage.evaluate(async (times) => {
260+
// The runtime is injected as a built script, outside this test's module graph.
261+
const player = (
262+
window as unknown as {
263+
__player: { seek: (time: number) => void; renderSeek: (time: number) => void };
264+
}
265+
).__player;
266+
const box = document.getElementById("waapi-box");
267+
if (!box || !player) throw new Error("WAAPI fixture did not initialize");
268+
const samples = [];
269+
for (const method of ["seek", "renderSeek"] as const) {
270+
for (const time of times) {
271+
await player[method](time);
272+
samples.push({
273+
time,
274+
x: new DOMMatrixReadOnly(getComputedStyle(box).transform).m41,
275+
playState: box.getAnimations()[0]?.playState,
276+
});
277+
}
278+
}
279+
return samples;
280+
}, times);
281+
for (const sample of samples) {
282+
const localTime = sample.time * 1000 + (paused ? offset : 0) - delay;
283+
const progress = Math.max(0, Math.min(1, localTime / duration));
284+
expect(sample.x).toBeCloseTo((reverse ? 1 - progress : progress) * 100, 3);
285+
expect(sample.playState).toBe("paused");
286+
}
287+
} finally {
288+
await animationPage.close();
289+
}
290+
},
291+
30_000,
292+
);
293+
202294
it.each([24, 30, 60, 30_000 / 1_001])(
203295
"keeps the real public player running across a seek at %s fps",
204296
async (fps) => {

0 commit comments

Comments
 (0)