Skip to content

Write HTML. Render video. Built for agents.

fix(core): a CSS animation in a later clip shows the right frame after a seek (#4554)

Miguel Ángel8dfdceb167b6
diff --git a/packages/core/src/runtime/adapters/css.test.ts b/packages/core/src/runtime/adapters/css.test.ts
index 59369b9858..dd47f12358 100644
--- a/packages/core/src/runtime/adapters/css.test.ts
+++ b/packages/core/src/runtime/adapters/css.test.ts
@@ -1,7 +1,43 @@
-import { afterEach, describe, it, expect, vi } from "vitest";
+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import { createCssAdapter } from "./css";
+// jsdom has no Animation subclasses; the adapter tells them apart with instanceof CSSAnimation.
+class FakeAnimation {}
+class FakeCSSAnimation extends FakeAnimation {}
+class FakeCSSTransition extends FakeAnimation {}
+
+const makeAnimation = (target: Element, kind: typeof FakeAnimation = FakeCSSAnimation) =>
+ Object.assign(new kind(), {
+ currentTime: 0,
+ pause: vi.fn(),
+ play: vi.fn(),
+ effect: { target },
+ }) as unknown as Animation;
+
+// The browser answers the same list per element and document-wide; returns a setter to replace it.
+const mockLiveAnimations = (el: HTMLElement, initial: Animation[]) => {
+ let live = initial;
+ el.getAnimations = () => live;
+ document.getAnimations = () => live;
+ return (next: Animation[]) => {
+ live = next;
+ };
+};
+
+// Like the runtime's resolver, reads only the element it is handed.
+const ownStart = (el: Element) => Number(el.getAttribute("data-start") ?? 0);
+
describe("css adapter", () => {
+ beforeEach(() => {
+ vi.stubGlobal("CSSAnimation", FakeCSSAnimation);
+ vi.stubGlobal("CSSTransition", FakeCSSTransition);
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(document, "getAnimations");
+ vi.unstubAllGlobals();
+ });
+
it("has correct name", () => {
expect(createCssAdapter().name).toBe("css");
});
@@ -70,7 +106,7 @@ describe("css adapter", () => {
vi.restoreAllMocks();
});
- it("pause restores base play state", () => {
+ it("pause keeps the fallback pose of an element with no live animation; play restores base", () => {
const el = document.createElement("div");
el.style.animationName = "spin";
el.style.animationPlayState = "running";
@@ -86,13 +122,31 @@ describe("css adapter", () => {
adapter.seek({ time: 1 });
expect(el.style.animationPlayState).toBe("paused");
+ // A render seeks, pauses, then shows the clip: the browser's new animation starts from this pose.
adapter.pause();
+ expect(el.style.animationPlayState).toBe("paused");
+ expect(el.style.animationDelay).toBe("-1s");
+
+ adapter.play?.();
expect(el.style.animationPlayState).toBe("running");
+ expect(el.style.animationDelay).toBe("");
document.body.removeChild(el);
vi.restoreAllMocks();
});
+ it("does not scan document animations when no element has a CSS animation", () => {
+ const getAnimations = vi.fn(() => []);
+ document.getAnimations = getAnimations;
+
+ const adapter = createCssAdapter();
+ adapter.discover();
+ adapter.seek({ time: 1 });
+ adapter.pause();
+
+ expect(getAnimations).not.toHaveBeenCalled();
+ });
+
it("revert clears entries", () => {
const adapter = createCssAdapter();
adapter.revert!();
@@ -110,8 +164,8 @@ describe("css adapter", () => {
return { animationName: "spin" } as CSSStyleDeclaration;
});
- const animation = { currentTime: 0, pause: vi.fn(), play: vi.fn() } as unknown as Animation;
- (el as HTMLElement & { getAnimations?: () => Animation[] }).getAnimations = () => [animation];
+ const animation = makeAnimation(el);
+ mockLiveAnimations(el, [animation]);
const adapter = createCssAdapter();
adapter.discover();
@@ -126,30 +180,232 @@ describe("css adapter", () => {
vi.restoreAllMocks();
});
- it("does not rescan element animations on every seek", () => {
+ describe("after the browser replaces an element's CSSAnimation", () => {
const el = document.createElement("div");
- el.style.animationName = "spin";
- document.body.appendChild(el);
+ el.setAttribute("data-start", "1");
+ el.style.animationName = "slide";
- vi.spyOn(window, "getComputedStyle").mockImplementation(() => {
- return { animationName: "spin" } as CSSStyleDeclaration;
+ const setup = (initial: Animation[]) => {
+ document.body.appendChild(el);
+ vi.spyOn(window, "getComputedStyle").mockImplementation(() => {
+ return { animationName: "slide" } as CSSStyleDeclaration;
+ });
+ const replace = mockLiveAnimations(el, initial);
+ const adapter = createCssAdapter();
+ adapter.discover();
+ return { adapter, replace };
+ };
+
+ afterEach(() => {
+ el.remove();
+ el.style.removeProperty("animation-delay");
+ el.style.removeProperty("animation-play-state");
+ vi.restoreAllMocks();
});
- const animation = { currentTime: 0, pause: vi.fn(), play: vi.fn() } as unknown as Animation;
- const getAnimations = vi.fn(() => [animation]);
- (el as HTMLElement & { getAnimations?: () => Animation[] }).getAnimations = getAnimations;
+ it("seek drives the live animation, not the one seen at discover", () => {
+ const stale = makeAnimation(el);
+ const current = makeAnimation(el);
+ const { adapter, replace } = setup([stale]);
- const adapter = createCssAdapter();
- adapter.discover();
- adapter.seek({ time: 1 });
- adapter.seek({ time: 2 });
- adapter.seek({ time: 3 });
+ replace([current]);
+ adapter.seek({ time: 3 });
- expect(getAnimations).toHaveBeenCalledTimes(1);
- expect(animation.currentTime).toBe(3000);
+ expect(current.currentTime).toBe(2000);
+ expect(current.pause).toHaveBeenCalled();
+ expect(stale.currentTime).toBe(0);
+ });
- document.body.removeChild(el);
- vi.restoreAllMocks();
+ it("seeks from the pass's shared page list without a scan of its own", () => {
+ const current = makeAnimation(el);
+ const { adapter } = setup([]);
+ const getAnimations = vi.spyOn(document, "getAnimations");
+
+ adapter.seek({ time: 3, pageAnimations: () => [current] });
+
+ expect(getAnimations).not.toHaveBeenCalled();
+ expect(current.currentTime).toBe(2000);
+ });
+
+ it("pause takes the seek pass's page list when given one and scans without it", () => {
+ const current = makeAnimation(el);
+ const { adapter } = setup([current]);
+ const getAnimations = vi.spyOn(document, "getAnimations");
+
+ adapter.pause({ pageAnimations: () => [current] });
+ expect(getAnimations).not.toHaveBeenCalled();
+ expect(current.pause).toHaveBeenCalledTimes(1);
+
+ adapter.pause();
+ expect(getAnimations).toHaveBeenCalledTimes(1);
+ expect(current.pause).toHaveBeenCalledTimes(2);
+ });
+
+ it("seeks back into a finished no-fill animation after it left the page's list", () => {
+ const finished = makeAnimation(el);
+ const { adapter, replace } = setup([finished]);
+
+ adapter.seek({ time: 1.5 });
+ replace([]);
+ adapter.seek({ time: 1.25 });
+
+ expect(finished.currentTime).toBe(250);
+ expect(el.style.animationDelay).toBe("");
+ });
+
+ it("never writes to an animation the browser cancelled, and falls back to the inline pose", () => {
+ const cancelled = makeAnimation(el);
+ const { adapter, replace } = setup([cancelled]);
+
+ adapter.seek({ time: 1.5 });
+ replace([]);
+ Object.assign(cancelled, { playState: "idle", currentTime: null });
+ adapter.seek({ time: 2 });
+
+ expect(cancelled.currentTime).toBeNull();
+ expect(el.style.animationDelay).toBe("-1s");
+ });
+
+ it("forgets a cancelled animation instead of checking it on every seek", () => {
+ const { adapter, replace } = setup([]);
+ const playStateReads: Array<() => string> = [];
+ for (let showing = 0; showing < 3; showing++) {
+ const shown = makeAnimation(el);
+ const readPlayState = vi.fn(() => "idle");
+ Object.defineProperty(shown, "playState", { get: readPlayState });
+ playStateReads.push(readPlayState);
+ replace([shown]);
+ adapter.seek({ time: 1.5 });
+ replace([]);
+ adapter.seek({ time: 2 });
+ adapter.seek({ time: 2.5 });
+ }
+
+ for (const readPlayState of playStateReads) expect(readPlayState).toHaveBeenCalledTimes(1);
+ });
+
+ it("forgets every known animation on revert", () => {
+ const finished = makeAnimation(el);
+ const { adapter, replace } = setup([finished]);
+
+ adapter.seek({ time: 1.5 });
+ adapter.revert?.();
+ adapter.discover();
+ replace([]);
+ adapter.seek({ time: 1.25 });
+
+ expect(finished.currentTime).toBe(500);
+ });
+
+ it("rediscover keeps a remembered handle for an element still in the page", () => {
+ const finished = makeAnimation(el);
+ const { adapter, replace } = setup([finished]);
+
+ adapter.seek({ time: 1.5 });
+ replace([]);
+ adapter.discover();
+ adapter.seek({ time: 1.25 });
+
+ expect(finished.currentTime).toBe(250);
+ expect(el.style.animationDelay).toBe("");
+ });
+
+ it("rediscover forgets the handles of an element no longer in the page", () => {
+ const finished = makeAnimation(el);
+ const { adapter, replace } = setup([finished]);
+
+ adapter.seek({ time: 1.5 });
+ replace([]);
+ el.remove();
+ adapter.discover();
+ document.body.appendChild(el);
+ adapter.discover();
+ adapter.seek({ time: 1.25 });
+
+ expect(finished.currentTime).toBe(500);
+ expect(el.style.animationDelay).toBe("-0.25s");
+ });
+
+ it("leaves the element's pseudo-element animations alone, as el.getAnimations() does", () => {
+ const own = makeAnimation(el);
+ const before = Object.assign(makeAnimation(el), {
+ effect: { target: el, pseudoElement: "::before" },
+ });
+ const { adapter } = setup([own, before]);
+
+ adapter.seek({ time: 3 });
+
+ expect(own.currentTime).toBe(2000);
+ expect(before.currentTime).toBe(0);
+ });
+
+ it("leaves CSS transitions and script animations on the element to the WAAPI adapter", () => {
+ const own = makeAnimation(el);
+ const others = [makeAnimation(el, FakeCSSTransition), makeAnimation(el, FakeAnimation)];
+ const { adapter } = setup([own, ...others]);
+
+ adapter.seek({ time: 3 });
+ adapter.play?.();
+ adapter.pause();
+
+ expect(own.currentTime).toBe(2000);
+ for (const other of others) {
+ expect(other.currentTime).toBe(0);
+ expect(other.pause).not.toHaveBeenCalled();
+ expect(other.play).not.toHaveBeenCalled();
+ }
+ });
+
+ it("seeks every animation where the browser has no CSSAnimation to tell them apart", () => {
+ vi.stubGlobal("CSSAnimation", undefined);
+ const animation = makeAnimation(el, FakeAnimation);
+ const { adapter } = setup([animation]);
+
+ adapter.seek({ time: 3 });
+
+ expect(animation.currentTime).toBe(2000);
+ });
+
+ it("play and pause act on the live animation", () => {
+ const stale = makeAnimation(el);
+ const current = makeAnimation(el);
+ const { adapter, replace } = setup([stale]);
+
+ replace([current]);
+ adapter.play?.();
+ adapter.pause();
+
+ expect(current.play).toHaveBeenCalled();
+ expect(current.pause).toHaveBeenCalled();
+ expect(stale.play).not.toHaveBeenCalled();
+ expect(stale.pause).not.toHaveBeenCalled();
+ });
+
+ it("drops the fallback's inline delay once a live animation exists", () => {
+ const current = makeAnimation(el);
+ const { adapter, replace } = setup([]);
+
+ adapter.seek({ time: 3 });
+ expect(el.style.animationDelay).toBe("-2s");
+
+ replace([current]);
+ adapter.seek({ time: 4 });
+
+ expect(el.style.animationDelay).toBe("");
+ expect(el.style.animationPlayState).toBe("");
+ expect(current.currentTime).toBe(3000);
+ });
+
+ it("rediscover does not read a fallback seek's inline delay back as authored", () => {
+ const { adapter } = setup([]);
+
+ adapter.seek({ time: 3 });
+ adapter.discover();
+ adapter.pause();
+
+ expect(el.style.animationDelay).toBe("");
+ expect(el.style.animationPlayState).toBe("");
+ });
});
it("play resumes WAAPI animations and restores inline styles", () => {
@@ -162,8 +418,8 @@ describe("css adapter", () => {
return { animationName: "spin" } as CSSStyleDeclaration;
});
- const animation = { currentTime: 0, pause: vi.fn(), play: vi.fn() } as unknown as Animation;
- (el as HTMLElement & { getAnimations?: () => Animation[] }).getAnimations = () => [animation];
+ const animation = makeAnimation(el);
+ mockLiveAnimations(el, [animation]);
const adapter = createCssAdapter();
adapter.discover();
@@ -407,4 +663,127 @@ describe("css adapter", () => {
expect(adapter.getAnimationCycleEndSeconds?.()).toBeNull();
});
});
+
+ describe("a child without its own data-start", () => {
+ const mount = (clipStart: string | null) => {
+ const box = document.createElement("div");
+ if (clipStart === null) {
+ document.body.appendChild(box);
+ } else {
+ const clip = document.createElement("div");
+ clip.setAttribute("data-start", clipStart);
+ clip.appendChild(box);
+ document.body.appendChild(clip);
+ }
+ vi.spyOn(window, "getComputedStyle").mockImplementation(
+ (node) => ({ animationName: node === box ? "slide" : "none" }) as CSSStyleDeclaration,
+ );
+ const animation = makeAnimation(box);
+ mockLiveAnimations(box, [animation]);
+ return animation;
+ };
+
+ afterEach(() => {
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ ["the runtime's resolver", { resolveStartSeconds: ownStart }],
+ ["no resolver", undefined],
+ ])("is timed from its clip's start with %s", (_, params) => {
+ const animation = mount("6");
+ const adapter = createCssAdapter(params);
+ adapter.discover();
+
+ adapter.seek({ time: 8 });
+
+ expect(animation.currentTime).toBe(2000);
+ });
+
+ it.each([
+ ["inside a clip at 0", "0"],
+ ["outside any clip", null],
+ ])("keeps start 0 %s", (_, clipStart) => {
+ const animation = mount(clipStart);
+ const adapter = createCssAdapter({ resolveStartSeconds: ownStart });
+ adapter.discover();
+
+ adapter.seek({ time: 3 });
+
+ expect(animation.currentTime).toBe(3000);
+ });
+ });
+
+ describe("a hidden late clip's fallback pose", () => {
+ // <div class="clip" data-start="6" style="display:none"><div id="box" style="animation: ..."></div></div>
+ const mountHiddenClip = (style: Partial<CSSStyleDeclaration>, inlineDelay = "") => {
+ const clip = document.createElement("div");
+ clip.setAttribute("data-start", "6");
+ clip.style.display = "none";
+ const box = document.createElement("div");
+ box.style.animationDelay = inlineDelay;
+ clip.appendChild(box);
+ document.body.appendChild(clip);
+ box.getAnimations = () => [];
+ vi.spyOn(window, "getComputedStyle").mockImplementation(
+ (node) =>
+ (node === box
+ ? {
+ animationDuration: "4s",
+ animationDelay: box.style.animationDelay || "0s",
+ ...style,
+ }
+ : { animationName: "none" }) as CSSStyleDeclaration,
+ );
+ const adapter = createCssAdapter({ resolveStartSeconds: ownStart });
+ adapter.discover();
+ return { adapter, box };
+ };
+
+ afterEach(() => {
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+ });
+
+ it("waits out the authored delay before it moves, and runs from it after", () => {
+ const { adapter, box } = mountHiddenClip({ animationName: "slide", animationDelay: "1s" });
+
+ // 0.5 s into the clip, 0.5 s of the 1 s delay remain: the first visible frame is unstarted.
+ adapter.seek({ time: 6.5 });
+ adapter.pause();
+ expect(box.style.animationDelay).toBe("0.5s");
+ expect(box.style.animationPlayState).toBe("paused");
+
+ // 2 s into the clip is 1 s into the animation, a quarter of its 4 s.
+ adapter.seek({ time: 8 });
+ adapter.pause();
+ expect(box.style.animationDelay).toBe("-1s");
+ });
+
+ it("shifts each animation by its own delay, repeating a shorter delay list", () => {
+ const { adapter, box } = mountHiddenClip({
+ animationName: "slide, fade, spin",
+ animationDelay: "1s, 250ms",
+ });
+
+ adapter.seek({ time: 6.5 });
+
+ expect(box.style.animationDelay).toBe("0.5s, -0.25s, 0.5s");
+ });
+
+ it("honours a delay written in the element's style attribute, also after a rediscover", () => {
+ const { adapter, box } = mountHiddenClip({ animationName: "slide" }, "1s");
+
+ adapter.seek({ time: 6.5 });
+ expect(box.style.animationDelay).toBe("0.5s");
+
+ adapter.discover();
+ adapter.seek({ time: 8 });
+ expect(box.style.animationDelay).toBe("-1s");
+
+ adapter.play?.();
+ expect(box.style.animationDelay).toBe("1s");
+ });
+ });
});
diff --git a/packages/core/src/runtime/adapters/css.ts b/packages/core/src/runtime/adapters/css.ts
index 00235be45c..d859e0896e 100644
--- a/packages/core/src/runtime/adapters/css.ts
+++ b/packages/core/src/runtime/adapters/css.ts
@@ -9,39 +9,67 @@ export function createCssAdapter(params?: {
el: HTMLElement;
baseDelay: string;
basePlayState: string;
- animations: Animation[];
cycleSeconds: number;
+ delays: number[];
+ handles?: Animation[];
}> = [];
- const getAnimationsForElement = (el: HTMLElement): Animation[] => {
- if (typeof el.getAnimations !== "function") return [];
+ const safeGetAnimations = (
+ source: Document | HTMLElement,
+ read = () => source.getAnimations(),
+ ): Animation[] => {
+ if (typeof source.getAnimations !== "function") return [];
try {
- return el.getAnimations();
+ return read();
} catch {
return [];
}
};
- const resolveEntryStartSeconds = (el: HTMLElement): number =>
- params?.resolveStartSeconds
- ? params.resolveStartSeconds(el)
- : Number.parseFloat(el.getAttribute("data-start") ?? "0") || 0;
+ const readLiveAnimations = (pageAnimations?: () => Animation[]): Map<Element, Animation[]> => {
+ const byElement = new Map<Element, Animation[]>();
+ if (entries.length === 0) return byElement;
+ const canTellCss = typeof CSSAnimation !== "undefined";
+ for (const animation of safeGetAnimations(document, pageAnimations)) {
+ if (canTellCss && !(animation instanceof CSSAnimation)) continue;
+ const effect = animation.effect as KeyframeEffect | null;
+ if (!effect?.target || effect.pseudoElement) continue;
+ const list = byElement.get(effect.target);
+ if (list) list.push(animation);
+ else byElement.set(effect.target, [animation]);
+ }
+ return byElement;
+ };
+
+ // A finished no-fill animation leaves the scan but stays; a write revives a cancelled (idle) one.
+ const keepHandles = (known: Animation[] = [], scanned: Animation[] = []): Animation[] => [
+ ...scanned,
+ ...known.filter((animation) => !scanned.includes(animation) && animation.playState !== "idle"),
+ ];
+
+ const resolveEntryStartSeconds = (el: HTMLElement): number => {
+ const clip = el.closest("[data-start]") ?? el;
+ return params?.resolveStartSeconds
+ ? params.resolveStartSeconds(clip)
+ : Number.parseFloat(clip.getAttribute("data-start") ?? "0") || 0;
+ };
// Computed lists pair by index, repeating the shorter; unlike getAnimations(), they outlive display:none.
- const readCycleSeconds = (style: CSSStyleDeclaration): number => {
+ const readAnimationTimes = (style: CSSStyleDeclaration) => {
const seconds = (list: string | undefined) =>
(list || "")
.split(",")
.map((v) => Number.parseFloat(v) / (v.trim().endsWith("ms") ? 1000 : 1));
const durations = seconds(style.animationDuration);
const delays = seconds(style.animationDelay);
- let end = 0;
- style.animationName.split(",").forEach((name, i) => {
+ const names = style.animationName.split(",");
+ let cycleSeconds = 0;
+ names.forEach((name, i) => {
if (name.trim() === "none") return;
const cycle = delays[i % delays.length]! + durations[i % durations.length]!;
- if (cycle > end) end = cycle;
+ if (cycle > cycleSeconds) cycleSeconds = cycle;
});
- return end;
+ return { cycleSeconds, delays: names.map((_, i) => delays[i % delays.length] || 0) };
};
/**
@@ -125,6 +153,7 @@ export function createCssAdapter(params?: {
discover: () => {
// A fallback seek's inline delay must not be read back as the authored one.
for (const entry of entries) restoreInlineStyles(entry);
+ const known = new Map(entries.map((entry) => [entry.el, entry.handles]));
entries = [];
const all = document.querySelectorAll("*");
for (const rawEl of all) {
@@ -135,8 +164,8 @@ export function createCssAdapter(params?: {
el: rawEl,
baseDelay: rawEl.style.animationDelay || "",
basePlayState: rawEl.style.animationPlayState || "",
- animations: getAnimationsForElement(rawEl),
- cycleSeconds: readCycleSeconds(style),
+ ...readAnimationTimes(style),
+ handles: known.get(rawEl),
});
}
},
@@ -153,7 +182,7 @@ export function createCssAdapter(params?: {
for (const entry of entries) {
if (!entry.el.isConnected) continue;
const start = resolveEntryStartSeconds(entry.el);
- for (const animation of getAnimationsForElement(entry.el)) {
+ for (const animation of safeGetAnimations(entry.el)) {
const result = inferAnimationEndSeconds(animation, start);
// Unbounded (Infinity/NaN endTime) animations are skipped here —
// they never contribute to maxEndSeconds. A finite animation
@@ -166,36 +195,42 @@ export function createCssAdapter(params?: {
},
seek: (ctx) => {
const time = Number(ctx.time) || 0;
+ const live = readLiveAnimations(ctx.pageAnimations);
+ // All playState reads before any write: each read flushes the style a write dirties.
+ for (const entry of entries) entry.handles = keepHandles(entry.handles, live.get(entry.el));
for (const entry of entries) {
if (!entry.el.isConnected) continue;
const start = resolveEntryStartSeconds(entry.el);
const localTimeMs = Math.max(0, time - start) * 1000;
- const animations = entry.animations;
- if (animations.length > 0) {
- seekAnimations(animations, localTimeMs);
+ if (entry.handles?.length) {
+ if (entry.el.style.animationDelay !== entry.baseDelay) restoreInlineStyles(entry);
+ seekAnimations(entry.handles, localTimeMs);
continue;
}
- // Fallback for environments without WAAPI-backed CSS animation handles.
+ // No live CSSAnimation (no WAAPI, a hidden clip): pause keeps this pose for the next one.
entry.el.style.animationPlayState = "paused";
- entry.el.style.animationDelay = `-${(localTimeMs / 1000).toFixed(3)}s`;
+ entry.el.style.animationDelay = entry.delays
+ .map((delay) => `${Number((delay - localTimeMs / 1000).toFixed(3))}s`)
+ .join(", ");
}
},
- pause: () => {
+ pause: (ctx) => {
+ const live = readLiveAnimations(ctx?.pageAnimations);
for (const entry of entries) {
if (!entry.el.isConnected) continue;
- const animations = entry.animations;
- if (animations.length > 0) {
- pauseAnimations(animations);
- }
+ const animations = live.get(entry.el);
+ if (!animations) continue;
+ pauseAnimations(animations);
restoreInlineStyles(entry);
}
},
play: () => {
+ const live = readLiveAnimations();
for (const entry of entries) {
if (!entry.el.isConnected) continue;
restoreInlineStyles(entry);
- playAnimations(entry.animations);
+ playAnimations(live.get(entry.el) ?? []);
}
},
revert: () => {
diff --git a/packages/core/src/runtime/adapters/waapi.test.ts b/packages/core/src/runtime/adapters/waapi.test.ts
index d113489d07..9b29ce5d2b 100644
--- a/packages/core/src/runtime/adapters/waapi.test.ts
+++ b/packages/core/src/runtime/adapters/waapi.test.ts
@@ -164,6 +164,21 @@ describe("waapi adapter", () => {
expect(getAnimations).toHaveBeenCalledTimes(1);
});
+ it("seek takes new animations from the pass's shared page list instead of scanning", () => {
+ const existing = makeAnimation();
+ const getAnimations = setAnimations([existing]);
+ const adapter = createWaapiAdapter();
+ adapter.discover();
+ getAnimations.mockClear();
+
+ const late = makeAnimation();
+ adapter.seek({ time: 0.5, pageAnimations: () => [existing, late] as unknown as Animation[] });
+
+ expect(getAnimations).not.toHaveBeenCalled();
+ expect(existing.currentTime).toBe(500);
+ expect(late.pause).toHaveBeenCalled();
+ });
+
it("tracks WAAPI animations created after an empty discover via Element.animate", () => {
const getAnimations = setAnimations([]);
diff --git a/packages/core/src/runtime/adapters/waapi.ts b/packages/core/src/runtime/adapters/waapi.ts
index 0ed5b1fa97..7ed4333988 100644
--- a/packages/core/src/runtime/adapters/waapi.ts
+++ b/packages/core/src/runtime/adapters/waapi.ts
@@ -22,10 +22,10 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
}
>();
- const snapshotAnimations = () => {
+ const snapshotAnimations = (read = () => document.getAnimations()) => {
if (!document.getAnimations) return [];
try {
- return document.getAnimations();
+ return read();
} catch {
return [];
}
@@ -154,7 +154,7 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
// After an empty discover, skip the per-frame global scan until authored
// code creates a WAAPI animation via Element.animate (hooked above).
if (!didDiscover || animations.size > 0) {
- trackAnimations(snapshotAnimations(), didDiscover ? timeMs : 0);
+ trackAnimations(snapshotAnimations(ctx.pageAnimations), didDiscover ? timeMs : 0);
}
for (const animation of animations) {
const baseline = didDiscover
@@ -176,9 +176,9 @@ export function createWaapiAdapter(): RuntimeDeterministicAdapter {
}
}
},
- pause: () => {
+ pause: (ctx) => {
if (!didDiscover) {
- trackAnimations(snapshotAnimations(), lastSeekTimeMs);
+ trackAnimations(snapshotAnimations(ctx?.pageAnimations), lastSeekTimeMs);
}
for (const animation of animations) {
try {
diff --git a/packages/core/src/runtime/init.swapScenes.test.ts b/packages/core/src/runtime/init.swapScenes.test.ts
index e96ee262a1..e26e1f13ed 100644
--- a/packages/core/src/runtime/init.swapScenes.test.ts
+++ b/packages/core/src/runtime/init.swapScenes.test.ts
@@ -607,23 +607,35 @@ describe("__hfSwapScenes", () => {
it("puts the swapped scene's CSS animations under the playhead", async () => {
const { root } = trackingRoot();
- const animation = { currentTime: null as number | null, pause: vi.fn(), play: vi.fn() };
- const proto = HTMLElement.prototype as unknown as { getAnimations?: () => unknown[] };
- proto.getAnimations = function (this: HTMLElement) {
- return this.textContent === "A two" ? [animation] : [];
+ // jsdom has no CSSAnimation; the CSS adapter seeks only its instances, read live document-wide.
+ class CSSAnimation {}
+ vi.stubGlobal("CSSAnimation", CSSAnimation);
+ const animation = Object.assign(new CSSAnimation(), {
+ currentTime: null as number | null,
+ pause: vi.fn(),
+ play: vi.fn(),
+ effect: { target: null as Element | null },
+ });
+ document.getAnimations = () => {
+ animation.effect.target =
+ Array.from(document.querySelectorAll("p")).find((p) => p.textContent === "A two") ?? null;
+ return animation.effect.target ? [animation as unknown as Animation] : [];
};
try {
boot([A1, B], root);
await tick();
+ window.__player?.renderSeek(2);
const animated: Scene = {
...A2,
body: '<p style="animation-name: spin; animation-duration: 2s">A two</p>',
};
await window.__hfSwapScenes!(preview([animated, B]).html);
- expect(animation.currentTime).toBeTypeOf("number");
+ // The CSS adapter's seek to 1 s into scene a, hosted at 1; WAAPI alone would leave 0.
+ expect(animation.currentTime).toBe(1000);
expect(animation.pause).toHaveBeenCalled();
} finally {
- delete proto.getAnimations;
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(document, "getAnimations");
}
});
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.ts
index 81100cead8..37b7429c7d 100644
--- a/packages/core/src/runtime/init.test.ts
+++ b/packages/core/src/runtime/init.test.ts
@@ -3699,6 +3699,161 @@ describe("initSandboxRuntimeModular", () => {
expect(window.__player?.getDuration()).toBe(0);
});
+ it("reads document animations once per seek pass across the WAAPI and CSS adapters", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-duration", "10");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ document.body.appendChild(root);
+
+ const animated = document.createElement("div");
+ animated.setAttribute("data-start", "1");
+ root.appendChild(animated);
+
+ vi.spyOn(window, "getComputedStyle").mockImplementation((target) => {
+ const real =
+ Object.getPrototypeOf(window).getComputedStyle ?? (() => ({}) as CSSStyleDeclaration);
+ return {
+ ...real,
+ animationName: target === animated ? "slide" : "none",
+ } as CSSStyleDeclaration;
+ });
+ // jsdom has no CSSAnimation; the CSS adapter seeks only its instances.
+ class CSSAnimation {}
+ vi.stubGlobal("CSSAnimation", CSSAnimation);
+ const animation = Object.assign(new CSSAnimation(), {
+ currentTime: 0,
+ pause: vi.fn(),
+ play: vi.fn(),
+ addEventListener: vi.fn(),
+ effect: { target: animated },
+ }) as unknown as Animation;
+ const getAnimations = vi.fn(() => [animation]);
+ document.getAnimations = getAnimations;
+ window.__timelines = {};
+
+ try {
+ initSandboxRuntimeModular();
+
+ getAnimations.mockClear();
+ window.__player!.renderSeek(2);
+ expect(getAnimations).toHaveBeenCalledTimes(1);
+ // The WAAPI adapter writes 2000; only the CSS adapter, reading the same list, writes clip time.
+ expect(animation.currentTime).toBe(1000);
+
+ getAnimations.mockClear();
+ window.__player!.seek(3);
+ expect(getAnimations).toHaveBeenCalledTimes(1);
+
+ // Each pass reads afresh: the runtime can show a clip between two seeks.
+ getAnimations.mockClear();
+ window.__player!.seek(4);
+ window.__player!.seek(5);
+ expect(getAnimations).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(document, "getAnimations");
+ }
+ });
+
+ it("times a CSS animation without data-start from its clip inside a nested composition", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-duration", "12");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-id", "sub");
+ host.setAttribute("data-start", "6");
+ host.setAttribute("data-duration", "4");
+ const clip = document.createElement("div");
+ clip.className = "clip";
+ clip.setAttribute("data-start", "1");
+ clip.setAttribute("data-duration", "3");
+ const box = document.createElement("div");
+ clip.appendChild(box);
+ host.appendChild(clip);
+ root.appendChild(host);
+ document.body.appendChild(root);
+
+ vi.spyOn(window, "getComputedStyle").mockImplementation(
+ (target) => ({ animationName: target === box ? "slide" : "none" }) as CSSStyleDeclaration,
+ );
+ class CSSAnimation {}
+ vi.stubGlobal("CSSAnimation", CSSAnimation);
+ const animation = Object.assign(new CSSAnimation(), {
+ currentTime: 0,
+ pause: vi.fn(),
+ play: vi.fn(),
+ addEventListener: vi.fn(),
+ effect: { target: box },
+ }) as unknown as Animation;
+ document.getAnimations = () => [animation];
+ window.__timelines = {};
+
+ try {
+ initSandboxRuntimeModular();
+
+ // The clip starts 1 s into a sub-composition hosted at 6 s: 8 s is 1 s into the clip.
+ window.__player!.seek(8);
+ expect(animation.currentTime).toBe(1000);
+ window.__player!.renderSeek(9);
+ expect(animation.currentTime).toBe(2000);
+ } finally {
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(document, "getAnimations");
+ }
+ });
+
+ it("keeps an authored CSS animation delay when seeking into a clip that started hidden", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-duration", "10");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ const clip = document.createElement("div");
+ clip.className = "clip";
+ clip.setAttribute("data-start", "6");
+ clip.setAttribute("data-duration", "3");
+ const box = document.createElement("div");
+ clip.appendChild(box);
+ root.appendChild(clip);
+ document.body.appendChild(root);
+
+ vi.spyOn(window, "getComputedStyle").mockImplementation(
+ (target) =>
+ (target === box
+ ? { animationName: "slide", animationDelay: "1s", animationDuration: "2s" }
+ : { animationName: "none" }) as CSSStyleDeclaration,
+ );
+ // A hidden clip has no live CSSAnimation, so the runtime poses it through the inline delay.
+ document.getAnimations = () => [];
+ window.__timelines = {};
+
+ try {
+ initSandboxRuntimeModular();
+ const player = window.__player!;
+ for (const move of [player.seek, player.renderSeek]) {
+ player.seek(0);
+ expect(clip.style.visibility).toBe("hidden");
+ // 0.5 s into the clip, 0.5 s of the authored 1 s delay is still to run.
+ move(6.5);
+ expect(box.style.animationDelay).toBe("0.5s");
+ move(8);
+ expect(box.style.animationDelay).toBe("-1s");
+ }
+ } finally {
+ Reflect.deleteProperty(document, "getAnimations");
+ }
+ });
+
it("infers hf.duration from a registered Lottie animation without data-duration or a GSAP timeline", () => {
const root = document.createElement("div");
root.setAttribute("data-composition-id", "main");
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index fee3e2607e..159f473190 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -249,6 +249,12 @@ const SLOW_IDLE_HEARTBEAT_MS = 1000;
// GSAP `data` on the tweens the runtime adds to stretch a timeline; never animation.
const RUNTIME_FILLER = "hf-runtime-filler";
+// One document.getAnimations() per seek and the pause after it, read on first use, shared by all adapters.
+function pageAnimationsForOnePass(): () => Animation[] {
+ let list: Animation[] | undefined;
+ return () => (list ??= document.getAnimations());
+}
+
export function initSandboxRuntimeModular(): void {
const state = createRuntimeState();
// Each video and audio as written, captured before the runtime writes to it; a swap keeps only these.
@@ -3049,11 +3055,15 @@ export function initSandboxRuntimeModular(): void {
postState(true);
};
- const runAdapters = (method: "discover" | "pause" | "play", timeSeconds = 0) => {
+ const runAdapters = (
+ method: "discover" | "pause" | "play",
+ timeSeconds = 0,
+ pageAnimations?: () => Animation[],
+ ) => {
for (const adapter of state.deterministicAdapters) {
try {
if (method === "discover") adapter.discover();
- if (method === "pause") adapter.pause();
+ if (method === "pause") adapter.pause({ pageAnimations });
if (method === "play" && adapter.play) adapter.play();
} catch (err) {
// keep runtime resilient against adapter-specific failures
@@ -3460,8 +3470,8 @@ export function initSandboxRuntimeModular(): void {
state.mediaForceSyncNextTick = true;
const tl = state.capturedTimeline;
pauseTimelineIfPossible(tl);
- seekTimelineAndAdapters(state.currentTime);
- runAdapters("pause");
+ const pageAnimations = seekTimelineAndAdapters(state.currentTime);
+ runAdapters("pause", 0, pageAnimations);
if (options?.keepPlaying && wasPlaying) {
transport.play();
return;
@@ -3485,11 +3495,11 @@ export function initSandboxRuntimeModular(): void {
state.currentTime = clock.now();
state.isPlaying = false;
state.mediaForceSyncNextTick = true;
- seekTimelineAndAdapters(state.currentTime, {
+ const pageAnimations = seekTimelineAndAdapters(state.currentTime, {
activateChildren: true,
suppressEvents: options?.suppressEvents,
});
- runAdapters("pause");
+ runAdapters("pause", 0, pageAnimations);
syncMediaForCurrentState();
colorGrading.redraw();
paintVfx(state.currentTime, { engineMode: true });
@@ -3882,14 +3892,14 @@ export function initSandboxRuntimeModular(): void {
function seekTimelineAndAdapters(
t: number,
opts?: { activateChildren?: boolean; suppressEvents?: boolean },
- ) {
+ ): () => Animation[] {
const tl = state.capturedTimeline;
// Critical for a sub-composition whose data-start is at or near 0: it is added
// to the root while the root is paused and may never receive an explicit
// play(), so without the rearm it holds its initial CSS state (opacity:0).
const rearmed = tl && opts?.activateChildren ? activateSiblingTimelines(tl) : [];
try {
- seekRootChildrenAndAdapters(tl, t, opts);
+ return seekRootChildrenAndAdapters(tl, t, opts);
} finally {
for (const sibling of rearmed) pauseTimelineIfPossible(sibling);
}
@@ -3899,7 +3909,7 @@ export function initSandboxRuntimeModular(): void {
tl: RuntimeTimelineLike | null,
t: number,
opts?: { activateChildren?: boolean; suppressEvents?: boolean },
- ) {
+ ): () => Animation[] {
const suppressEvents = opts?.suppressEvents === true;
if (tl) {
// #10: when data-duration exceeds the timeline's intrinsic length the
@@ -3946,14 +3956,16 @@ export function initSandboxRuntimeModular(): void {
// the deterministic adapters, syncTimedElementVisibility, the hf-timelines-built
// handler and __hfReseekGpu. It only ever moved the state the seek left behind.
seekStandaloneRegisteredTimelines(t, opts);
+ const pageAnimations = pageAnimationsForOnePass();
for (const adapter of state.deterministicAdapters) {
if (adapter.name === "gsap" && tl) continue;
try {
- adapter.seek({ time: t, suppressEvents });
+ adapter.seek({ time: t, suppressEvents, pageAnimations });
} catch (err) {
swallow("runtime.init.transport.adapter", err);
}
}
+ return pageAnimations;
}
// True while the Studio is mid-drag on an element (the gesture marker is
diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts
index 97836f35c3..977cad94cd 100644
--- a/packages/core/src/runtime/types.ts
+++ b/packages/core/src/runtime/types.ts
@@ -316,8 +316,12 @@ export type RuntimeTimelineLike = {
export type RuntimeDeterministicAdapter = {
name: string;
discover: () => void;
- seek: (ctx: { time: number; suppressEvents?: boolean }) => void;
- pause: () => void;
+ seek: (ctx: {
+ time: number;
+ suppressEvents?: boolean;
+ pageAnimations?: () => Animation[];
+ }) => void;
+ pause: (ctx?: { pageAnimations?: () => Animation[] }) => void;
play?: () => void;
revert?: () => void;
/**