Skip to content

Commit 1781a91

Browse files
committed
fix(core): a CSS animation in a later clip shows the right frame after a seek
1 parent 640e990 commit 1781a91

8 files changed

Lines changed: 685 additions & 73 deletions

File tree

‎packages/core/src/runtime/adapters/css.test.ts‎

Lines changed: 402 additions & 23 deletions
Large diffs are not rendered by default.

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

Lines changed: 62 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,39 +9,67 @@ export function createCssAdapter(params?: {
99
el: HTMLElement;
1010
baseDelay: string;
1111
basePlayState: string;
12-
animations: Animation[];
1312
cycleSeconds: number;
13+
delays: number[];
14+
handles?: Animation[];
1415
}> = [];
1516

16-
const getAnimationsForElement = (el: HTMLElement): Animation[] => {
17-
if (typeof el.getAnimations !== "function") return [];
17+
const safeGetAnimations = (
18+
source: Document | HTMLElement,
19+
read = () => source.getAnimations(),
20+
): Animation[] => {
21+
if (typeof source.getAnimations !== "function") return [];
1822
try {
19-
return el.getAnimations();
23+
return read();
2024
} catch {
2125
return [];
2226
}
2327
};
2428

25-
const resolveEntryStartSeconds = (el: HTMLElement): number =>
26-
params?.resolveStartSeconds
27-
? params.resolveStartSeconds(el)
28-
: Number.parseFloat(el.getAttribute("data-start") ?? "0") || 0;
29+
const readLiveAnimations = (pageAnimations?: () => Animation[]): Map<Element, Animation[]> => {
30+
const byElement = new Map<Element, Animation[]>();
31+
if (entries.length === 0) return byElement;
32+
const canTellCss = typeof CSSAnimation !== "undefined";
33+
for (const animation of safeGetAnimations(document, pageAnimations)) {
34+
if (canTellCss && !(animation instanceof CSSAnimation)) continue;
35+
const effect = animation.effect as KeyframeEffect | null;
36+
if (!effect?.target || effect.pseudoElement) continue;
37+
const list = byElement.get(effect.target);
38+
if (list) list.push(animation);
39+
else byElement.set(effect.target, [animation]);
40+
}
41+
return byElement;
42+
};
43+
44+
// A finished no-fill animation leaves the scan but stays; a write revives a cancelled (idle) one.
45+
const keepHandles = (known: Animation[] = [], scanned: Animation[] = []): Animation[] => [
46+
...scanned,
47+
...known.filter((animation) => !scanned.includes(animation) && animation.playState !== "idle"),
48+
];
49+
50+
const resolveEntryStartSeconds = (el: HTMLElement): number => {
51+
const clip = el.closest("[data-start]") ?? el;
52+
return params?.resolveStartSeconds
53+
? params.resolveStartSeconds(clip)
54+
: Number.parseFloat(clip.getAttribute("data-start") ?? "0") || 0;
55+
};
2956

3057
// Computed lists pair by index, repeating the shorter; unlike getAnimations(), they outlive display:none.
31-
const readCycleSeconds = (style: CSSStyleDeclaration): number => {
58+
const readAnimationTimes = (style: CSSStyleDeclaration) => {
3259
const seconds = (list: string | undefined) =>
3360
(list || "")
3461
.split(",")
3562
.map((v) => Number.parseFloat(v) / (v.trim().endsWith("ms") ? 1000 : 1));
3663
const durations = seconds(style.animationDuration);
3764
const delays = seconds(style.animationDelay);
38-
let end = 0;
39-
style.animationName.split(",").forEach((name, i) => {
65+
const names = style.animationName.split(",");
66+
let cycleSeconds = 0;
67+
names.forEach((name, i) => {
4068
if (name.trim() === "none") return;
4169
const cycle = delays[i % delays.length]! + durations[i % durations.length]!;
42-
if (cycle > end) end = cycle;
70+
if (cycle > cycleSeconds) cycleSeconds = cycle;
4371
});
44-
return end;
72+
return { cycleSeconds, delays: names.map((_, i) => delays[i % delays.length] || 0) };
4573
};
4674

4775
/**
@@ -125,6 +153,7 @@ export function createCssAdapter(params?: {
125153
discover: () => {
126154
// A fallback seek's inline delay must not be read back as the authored one.
127155
for (const entry of entries) restoreInlineStyles(entry);
156+
const known = new Map(entries.map((entry) => [entry.el, entry.handles]));
128157
entries = [];
129158
const all = document.querySelectorAll("*");
130159
for (const rawEl of all) {
@@ -135,8 +164,8 @@ export function createCssAdapter(params?: {
135164
el: rawEl,
136165
baseDelay: rawEl.style.animationDelay || "",
137166
basePlayState: rawEl.style.animationPlayState || "",
138-
animations: getAnimationsForElement(rawEl),
139-
cycleSeconds: readCycleSeconds(style),
167+
...readAnimationTimes(style),
168+
handles: known.get(rawEl),
140169
});
141170
}
142171
},
@@ -153,7 +182,7 @@ export function createCssAdapter(params?: {
153182
for (const entry of entries) {
154183
if (!entry.el.isConnected) continue;
155184
const start = resolveEntryStartSeconds(entry.el);
156-
for (const animation of getAnimationsForElement(entry.el)) {
185+
for (const animation of safeGetAnimations(entry.el)) {
157186
const result = inferAnimationEndSeconds(animation, start);
158187
// Unbounded (Infinity/NaN endTime) animations are skipped here —
159188
// they never contribute to maxEndSeconds. A finite animation
@@ -166,36 +195,42 @@ export function createCssAdapter(params?: {
166195
},
167196
seek: (ctx) => {
168197
const time = Number(ctx.time) || 0;
198+
const live = readLiveAnimations(ctx.pageAnimations);
199+
// All playState reads before any write: each read flushes the style a write dirties.
200+
for (const entry of entries) entry.handles = keepHandles(entry.handles, live.get(entry.el));
169201
for (const entry of entries) {
170202
if (!entry.el.isConnected) continue;
171203
const start = resolveEntryStartSeconds(entry.el);
172204
const localTimeMs = Math.max(0, time - start) * 1000;
173-
const animations = entry.animations;
174-
if (animations.length > 0) {
175-
seekAnimations(animations, localTimeMs);
205+
if (entry.handles?.length) {
206+
if (entry.el.style.animationDelay !== entry.baseDelay) restoreInlineStyles(entry);
207+
seekAnimations(entry.handles, localTimeMs);
176208
continue;
177209
}
178210

179-
// Fallback for environments without WAAPI-backed CSS animation handles.
211+
// No live CSSAnimation (no WAAPI, a hidden clip): pause keeps this pose for the next one.
180212
entry.el.style.animationPlayState = "paused";
181-
entry.el.style.animationDelay = `-${(localTimeMs / 1000).toFixed(3)}s`;
213+
entry.el.style.animationDelay = entry.delays
214+
.map((delay) => `${Number((delay - localTimeMs / 1000).toFixed(3))}s`)
215+
.join(", ");
182216
}
183217
},
184-
pause: () => {
218+
pause: (ctx) => {
219+
const live = readLiveAnimations(ctx?.pageAnimations);
185220
for (const entry of entries) {
186221
if (!entry.el.isConnected) continue;
187-
const animations = entry.animations;
188-
if (animations.length > 0) {
189-
pauseAnimations(animations);
190-
}
222+
const animations = live.get(entry.el);
223+
if (!animations) continue;
224+
pauseAnimations(animations);
191225
restoreInlineStyles(entry);
192226
}
193227
},
194228
play: () => {
229+
const live = readLiveAnimations();
195230
for (const entry of entries) {
196231
if (!entry.el.isConnected) continue;
197232
restoreInlineStyles(entry);
198-
playAnimations(entry.animations);
233+
playAnimations(live.get(entry.el) ?? []);
199234
}
200235
},
201236
revert: () => {

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,21 @@ describe("waapi adapter", () => {
164164
expect(getAnimations).toHaveBeenCalledTimes(1);
165165
});
166166

167+
it("seek takes new animations from the pass's shared page list instead of scanning", () => {
168+
const existing = makeAnimation();
169+
const getAnimations = setAnimations([existing]);
170+
const adapter = createWaapiAdapter();
171+
adapter.discover();
172+
getAnimations.mockClear();
173+
174+
const late = makeAnimation();
175+
adapter.seek({ time: 0.5, pageAnimations: () => [existing, late] as unknown as Animation[] });
176+
177+
expect(getAnimations).not.toHaveBeenCalled();
178+
expect(existing.currentTime).toBe(500);
179+
expect(late.pause).toHaveBeenCalled();
180+
});
181+
167182
it("tracks WAAPI animations created after an empty discover via Element.animate", () => {
168183
const getAnimations = setAnimations([]);
169184

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
2222
}
2323
>();
2424

25-
const snapshotAnimations = () => {
25+
const snapshotAnimations = (read = () => document.getAnimations()) => {
2626
if (!document.getAnimations) return [];
2727
try {
28-
return document.getAnimations();
28+
return read();
2929
} catch {
3030
return [];
3131
}
@@ -154,7 +154,7 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
154154
// After an empty discover, skip the per-frame global scan until authored
155155
// code creates a WAAPI animation via Element.animate (hooked above).
156156
if (!didDiscover || animations.size > 0) {
157-
trackAnimations(snapshotAnimations(), didDiscover ? timeMs : 0);
157+
trackAnimations(snapshotAnimations(ctx.pageAnimations), didDiscover ? timeMs : 0);
158158
}
159159
for (const animation of animations) {
160160
const baseline = didDiscover
@@ -176,9 +176,9 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
176176
}
177177
}
178178
},
179-
pause: () => {
179+
pause: (ctx) => {
180180
if (!didDiscover) {
181-
trackAnimations(snapshotAnimations(), lastSeekTimeMs);
181+
trackAnimations(snapshotAnimations(ctx?.pageAnimations), lastSeekTimeMs);
182182
}
183183
for (const animation of animations) {
184184
try {

‎packages/core/src/runtime/init.swapScenes.test.ts‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -607,23 +607,35 @@ describe("__hfSwapScenes", () => {
607607

608608
it("puts the swapped scene's CSS animations under the playhead", async () => {
609609
const { root } = trackingRoot();
610-
const animation = { currentTime: null as number | null, pause: vi.fn(), play: vi.fn() };
611-
const proto = HTMLElement.prototype as unknown as { getAnimations?: () => unknown[] };
612-
proto.getAnimations = function (this: HTMLElement) {
613-
return this.textContent === "A two" ? [animation] : [];
610+
// jsdom has no CSSAnimation; the CSS adapter seeks only its instances, read live document-wide.
611+
class CSSAnimation {}
612+
vi.stubGlobal("CSSAnimation", CSSAnimation);
613+
const animation = Object.assign(new CSSAnimation(), {
614+
currentTime: null as number | null,
615+
pause: vi.fn(),
616+
play: vi.fn(),
617+
effect: { target: null as Element | null },
618+
});
619+
document.getAnimations = () => {
620+
animation.effect.target =
621+
Array.from(document.querySelectorAll("p")).find((p) => p.textContent === "A two") ?? null;
622+
return animation.effect.target ? [animation as unknown as Animation] : [];
614623
};
615624
try {
616625
boot([A1, B], root);
617626
await tick();
627+
window.__player?.renderSeek(2);
618628
const animated: Scene = {
619629
...A2,
620630
body: '<p style="animation-name: spin; animation-duration: 2s">A two</p>',
621631
};
622632
await window.__hfSwapScenes!(preview([animated, B]).html);
623-
expect(animation.currentTime).toBeTypeOf("number");
633+
// The CSS adapter's seek to 1 s into scene a, hosted at 1; WAAPI alone would leave 0.
634+
expect(animation.currentTime).toBe(1000);
624635
expect(animation.pause).toHaveBeenCalled();
625636
} finally {
626-
delete proto.getAnimations;
637+
vi.unstubAllGlobals();
638+
Reflect.deleteProperty(document, "getAnimations");
627639
}
628640
});
629641

0 commit comments

Comments
 (0)