Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(core): the runtime reports where a composition's animations end, one cycle each (#4541)
Miguel Ángele0e6442d9c59
diff --git a/bun.lock b/bun.lockindex dd42c38398..f036f672dd 100644--- a/bun.lock+++ b/bun.lock@@ -123,6 +123,7 @@"@types/jsdom": "^28.0.0","@types/node": "^25.0.10","@vitest/coverage-v8": "^4.1.11",+ "gsap": "^3.15.0","jsdom": "^29.0.0","tsx": "^4.21.0","typescript": "^5.0.0",diff --git a/packages/core/package.json b/packages/core/package.jsonindex f9c2dc86a9..f1a2329544 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -757,6 +757,7 @@"@types/jsdom": "^28.0.0","@types/node": "^25.0.10","@vitest/coverage-v8": "^4.1.11",+ "gsap": "^3.15.0","jsdom": "^29.0.0","tsx": "^4.21.0","typescript": "^5.0.0",diff --git a/packages/core/src/runtime/adapters/css.test.ts b/packages/core/src/runtime/adapters/css.test.tsindex 06c192c41a..59369b9858 100644--- a/packages/core/src/runtime/adapters/css.test.ts+++ b/packages/core/src/runtime/adapters/css.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi } from "vitest";+import { afterEach, describe, it, expect, vi } from "vitest";import { createCssAdapter } from "./css";describe("css adapter", () => {@@ -329,4 +329,82 @@ describe("css adapter", () => {vi.restoreAllMocks();});});++ describe("cycle end", () => {+ const mountAnimated = (style: Partial<CSSStyleDeclaration>) => {+ const el = document.createElement("div");+ el.setAttribute("data-start", "2");+ document.body.appendChild(el);+ vi.spyOn(window, "getComputedStyle").mockImplementation(+ () =>+ ({ animationDelay: el.style.animationDelay || "0s", ...style }) as CSSStyleDeclaration,+ );+ return el;+ };++ afterEach(() => {+ document.body.replaceChildren();+ vi.restoreAllMocks();+ });++ it("reads one cycle per animation from the computed lists, not the live animations", () => {+ // A display:none clip or a finished animation has no live handle; its CSS still counts.+ const el = mountAnimated({+ animationName: "a, none, b, c",+ animationDuration: "1s, 9s, 1500ms",+ animationDelay: "0s, 0s, 0s, 2s",+ });+ el.getAnimations = () => [];++ const adapter = createCssAdapter();+ adapter.discover();++ // c pairs the 2s delay with the first duration again: 2 + 2 + 1.+ expect(adapter.getAnimationCycleEndSeconds?.()).toBe(5);+ expect(adapter.getInferredDurationSeconds?.()).toBeNull();+ });++ it("skips an animation whose negative delay ends it before it starts", () => {+ mountAnimated({ animationName: "a", animationDuration: "1s", animationDelay: "-2s" });++ const adapter = createCssAdapter();+ adapter.discover();++ expect(adapter.getAnimationCycleEndSeconds?.()).toBeNull();+ });++ it("keeps the authored delay when rediscovered after a fallback seek", () => {+ const el = mountAnimated({ animationName: "pulse", animationDuration: "1s" });+ el.getAnimations = () => [];++ const adapter = createCssAdapter();+ adapter.discover();+ adapter.seek({ time: 5 });+ expect(el.style.animationDelay).toBe("-3s");+ adapter.discover();+ adapter.pause();++ expect(adapter.getAnimationCycleEndSeconds?.()).toBe(3);+ expect(el.style.animationDelay).toBe("");+ });++ it("skips an element removed after discover", () => {+ const el = mountAnimated({});+ vi.mocked(window.getComputedStyle).mockImplementation(+ (node) =>+ ({+ animationName: node === el ? "a" : "none",+ animationDuration: "1s",+ animationDelay: "0s",+ }) as CSSStyleDeclaration,+ );++ const adapter = createCssAdapter();+ adapter.discover();+ expect(adapter.getAnimationCycleEndSeconds?.()).toBe(3);+ el.remove();++ expect(adapter.getAnimationCycleEndSeconds?.()).toBeNull();+ });+ });});diff --git a/packages/core/src/runtime/adapters/css.ts b/packages/core/src/runtime/adapters/css.tsindex 7614adb8ee..00235be45c 100644--- a/packages/core/src/runtime/adapters/css.ts+++ b/packages/core/src/runtime/adapters/css.ts@@ -10,6 +10,7 @@ export function createCssAdapter(params?: {baseDelay: string;basePlayState: string;animations: Animation[];+ cycleSeconds: number;}> = [];const getAnimationsForElement = (el: HTMLElement): Animation[] => {@@ -26,6 +27,23 @@ export function createCssAdapter(params?: {? params.resolveStartSeconds(el): Number.parseFloat(el.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 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) => {+ if (name.trim() === "none") return;+ const cycle = delays[i % delays.length]! + durations[i % durations.length]!;+ if (cycle > end) end = cycle;+ });+ return end;+ };+/*** End time (seconds, relative to composition start) for one WAAPI* animation handle. `endSeconds` is set only when the timing is readable@@ -105,6 +123,8 @@ export function createCssAdapter(params?: {return {name: "css",discover: () => {+ // A fallback seek's inline delay must not be read back as the authored one.+ for (const entry of entries) restoreInlineStyles(entry);entries = [];const all = document.querySelectorAll("*");for (const rawEl of all) {@@ -116,9 +136,18 @@ export function createCssAdapter(params?: {baseDelay: rawEl.style.animationDelay || "",basePlayState: rawEl.style.animationPlayState || "",animations: getAnimationsForElement(rawEl),+ cycleSeconds: readCycleSeconds(style),});}},+ getAnimationCycleEndSeconds: () => {+ let end = 0;+ for (const entry of entries) {+ if (!entry.el.isConnected || entry.cycleSeconds <= 0) continue;+ end = Math.max(end, resolveEntryStartSeconds(entry.el) + entry.cycleSeconds);+ }+ return end > 0 ? end : null;+ },getInferredDurationSeconds: () => {let maxEndSeconds = 0;for (const entry of entries) {diff --git a/packages/core/src/runtime/adapters/lottie.test.ts b/packages/core/src/runtime/adapters/lottie.test.tsindex 3697c060fd..1ccb8a5921 100644--- a/packages/core/src/runtime/adapters/lottie.test.ts+++ b/packages/core/src/runtime/adapters/lottie.test.ts@@ -47,6 +47,7 @@ describe("lottie adapter", () => {afterEach(() => {delete lottieWindow.lottie;delete lottieWindow.__hfLottie;+ document.body.innerHTML = "";});it("has correct name", () => {@@ -84,16 +85,16 @@ describe("lottie adapter", () => {});});- describe("seek", () => {- function mountedAt(start: string) {- document.body.innerHTML = `<div data-composition-id="root"><div data-composition-id="host" data-start="${start}"><div data-composition-id="walk"><div id="player"></div></div></div></div>`;- const { resolveStartForElement } = createRuntimeStartTimeResolver({});- const adapter = createLottieAdapter({- resolveStartSeconds: (el) => resolveStartForElement(el, 0),- });- return { adapter, player: document.getElementById("player")! };- }+ function mountedAt(start: string) {+ document.body.innerHTML = `<div data-composition-id="root"><div data-composition-id="host" data-start="${start}"><div data-composition-id="walk"><div id="player"></div></div></div></div>`;+ const { resolveStartForElement } = createRuntimeStartTimeResolver({});+ const adapter = createLottieAdapter({+ resolveStartSeconds: (el) => resolveStartForElement(el, 0),+ });+ return { adapter, player: document.getElementById("player")! };+ }+ describe("seek", () => {it("seeks a player in a mounted composition to the time since that composition started", () => {const { adapter, player } = mountedAt("3");const anim = { ...createLottieWebAnim(), wrapper: player };@@ -104,7 +105,6 @@ describe("lottie adapter", () => {expect(dot.setCurrentRawFrameValue).toHaveBeenCalledWith(30);adapter.seek({ time: 1 });expect(anim.goToAndStop).toHaveBeenLastCalledWith(0, false);- document.body.innerHTML = "";});it("keeps page time for a player in a composition that starts at 0", () => {@@ -113,7 +113,6 @@ describe("lottie adapter", () => {lottieWindow.__hfLottie = [anim];adapter.seek({ time: 2 });expect(anim.goToAndStop).toHaveBeenCalledWith(2000, false);- document.body.innerHTML = "";});it("seeks lottie-web with goToAndStop in ms", () => {@@ -304,5 +303,42 @@ describe("lottie adapter", () => {const adapter = createLottieAdapter();expect(adapter.getInferredDurationSeconds?.()).toBeNull();});++ it("reports a player's own length, ignoring its composition's start and counting removed ones", () => {+ const { adapter, player } = mountedAt("5");+ lottieWindow.__hfLottie = [{ ...createLottieWebAnim({ totalFrames: 60 }), wrapper: player }];+ expect(adapter.getInferredDurationSeconds?.()).toBe(2);+ const gone = document.body.appendChild(document.createElement("div"));+ gone.remove();+ lottieWindow.__hfLottie.push({ ...createLottieWebAnim({ totalFrames: 90 }), wrapper: gone });+ expect(adapter.getInferredDurationSeconds?.()).toBe(3);+ });+ });++ describe("getAnimationCycleEndSeconds", () => {+ it("ends one loop after the start of the player's composition", () => {+ const { adapter, player } = mountedAt("5");+ lottieWindow.__hfLottie = [{ ...createLottieWebAnim({ totalFrames: 60 }), wrapper: player }];+ expect(adapter.getAnimationCycleEndSeconds?.()).toBe(7);+ });++ it("skips a player whose element was removed", () => {+ const { adapter, player } = mountedAt("0");+ const gone = document.body.appendChild(document.createElement("div"));+ gone.remove();+ lottieWindow.__hfLottie = [+ { ...createLottieWebAnim({ totalFrames: 60 }), wrapper: player },+ { ...createLottieWebAnim({ totalFrames: 300 }), wrapper: gone },+ ];+ expect(adapter.getAnimationCycleEndSeconds?.()).toBe(2);+ });++ it("ends one loop in for a player at the root", () => {+ const { adapter } = mountedAt("5");+ const root = document.querySelector('[data-composition-id="root"]')!;+ const player = root.appendChild(document.createElement("div"));+ lottieWindow.__hfLottie = [{ ...createLottieWebAnim({ totalFrames: 60 }), wrapper: player }];+ expect(adapter.getAnimationCycleEndSeconds?.()).toBe(2);+ });});});diff --git a/packages/core/src/runtime/adapters/lottie.ts b/packages/core/src/runtime/adapters/lottie.tsindex 3f7c3c2d8c..761f2622bb 100644--- a/packages/core/src/runtime/adapters/lottie.ts+++ b/packages/core/src/runtime/adapters/lottie.ts@@ -52,15 +52,16 @@ import { swallow } from "../diagnostics";export function createLottieAdapter(params?: {resolveStartSeconds?: (element: Element) => number;}): RuntimeDeterministicAdapter {- const secondsIntoComposition = (anim: unknown, pageTime: number): number => {- const el = isLottieWebAnimation(anim) ? anim.wrapper : (anim as DotLottiePlayer).canvas;+ const compositionStartSeconds = (anim: unknown): number => {+ const el = lottieElement(anim);const composition =el && typeof (el as Element).closest === "function"? (el as Element).closest("[data-composition-id]"): null;- if (!composition || !params?.resolveStartSeconds) return pageTime;- return Math.max(0, pageTime - params.resolveStartSeconds(composition));+ return composition && params?.resolveStartSeconds ? params.resolveStartSeconds(composition) : 0;};+ const secondsIntoComposition = (anim: unknown, pageTime: number): number =>+ Math.max(0, pageTime - compositionStartSeconds(anim));return {name: "lottie",@@ -166,32 +167,50 @@ export function createLottieAdapter(params?: {// Just let them be garbage collected naturally.},- getInferredDurationSeconds: () => {- const instances = (window as LottieWindow).__hfLottie;- if (!instances || instances.length === 0) return null;- let maxSeconds = 0;- let sawAny = false;- for (const anim of instances) {- let seconds: number | null = null;- try {- seconds = inferAnimationDurationSeconds(anim);- } catch (err) {- // ignore per-animation failures — keep going for other instances- swallow("runtime.adapters.lottie.site4", err);- }- if (seconds == null) continue;- sawAny = true;- maxSeconds = Math.max(maxSeconds, seconds);- }- // Not-yet-loaded animations report totalFrames=0 — return null (not 0)- // so the caller doesn't treat "still loading" as "genuinely zero- // duration". A later discover cycle will pick up the real value once- // the JSON has loaded.- return sawAny ? maxSeconds : null;- },+ getInferredDurationSeconds: () => latestInstanceEnd((_, length) => length),++ // Plays from its composition's start, as seek anchors it; a removed scene's instance stays registered.+ getAnimationCycleEndSeconds: () =>+ latestInstanceEnd((anim, length) =>+ (lottieElement(anim) as Node | undefined)?.isConnected === false+ ? null+ : compositionStartSeconds(anim) + length,+ ),};}+/** Max of `endOf(instance, its length)` over registered instances; null skips an instance. */+function latestInstanceEnd(+ endOf: (anim: LottieWebAnimation | DotLottiePlayer, length: number) => number | null,+): number | null {+ const instances = (window as LottieWindow).__hfLottie;+ if (!instances || instances.length === 0) return null;+ let maxSeconds = 0;+ let sawAny = false;+ for (const anim of instances) {+ let end: number | null = null;+ try {+ const length = inferAnimationDurationSeconds(anim);+ end = length == null ? null : endOf(anim, length);+ } catch (err) {+ // ignore per-animation failures — keep going for other instances+ swallow("runtime.adapters.lottie.site4", err);+ }+ if (end == null) continue;+ sawAny = true;+ maxSeconds = Math.max(maxSeconds, end);+ }+ // Not-yet-loaded animations report totalFrames=0 — return null (not 0)+ // so the caller doesn't treat "still loading" as "genuinely zero+ // duration". A later discover cycle will pick up the real value once+ // the JSON has loaded.+ return sawAny ? maxSeconds : null;+}++function lottieElement(anim: unknown): unknown {+ return isLottieWebAnimation(anim) ? anim.wrapper : (anim as DotLottiePlayer).canvas;+}+/** `frame` wrapped into [0, total); a float hair under a whole cycle is the next cycle's first frame. */function wrapFrame(frame: number, total: number): number {const wrapped = frame % total;diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 0dc5664a55..81100cead8 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -5,12 +5,16 @@ import { initSandboxRuntimeModular } from "./init";import { collectRuntimeTimelinePayload } from "./timeline";import { TYPEGPU_PRESENT_HEARTBEAT_MS } from "./adapters/typegpu";import { WebAudioTransport } from "./webAudioTransport";-import type { RuntimeTimelineLike } from "./types";+import type { RuntimeTimelineChildLike, RuntimeTimelineLike } from "./types";import {registerRuntimeDataHandler,resetRuntimeDataForTests,setRuntimeData,} from "./runtimeData";+import gsap from "gsap";++// Importing gsap installs it on window; a test opts in by setting window.gsap itself.+delete window.gsap;it("schedules WebAudio element gain from author volume without bridge volume", () => {const source = readFileSync("src/runtime/init.ts", "utf8");@@ -57,20 +61,70 @@ function createMockTimeline(duration: number): RuntimeTimelineLike {};}+type MockTimelineChild = RuntimeTimelineChildLike & {+ totalDuration: () => number;+ timeScale: () => number;+};++// Mirrors GSAP: a tween's duration() is one iteration, its totalDuration() counts the repeats.+function mockTween(start: number, duration: number, repeat = 0, data?: unknown): MockTimelineChild {+ return {+ startTime: () => start,+ duration: () => duration,+ totalDuration: () => duration * (repeat + 1),+ timeScale: () => 1,+ data,+ };+}++// Mirrors GSAP: a timeline ends where its last child's repeats end, in the timeline's time.+function endOfChildren(children: MockTimelineChild[]): number {+ return Math.max(+ 0,+ ...children.map((c) => (c.startTime?.() ?? 0) + c.totalDuration() / c.timeScale()),+ );+}++function mockNestedTimeline(+ start: number,+ timeScale: number,+ children: MockTimelineChild[],+): MockTimelineChild {+ const duration = endOfChildren(children);+ return {+ startTime: () => start,+ duration: () => duration,+ totalDuration: () => duration,+ timeScale: () => timeScale,+ getChildren: () => children,+ };+}++function createMockTimelineOf(children: MockTimelineChild[]): RuntimeTimelineLike {+ return { ...createMockTimeline(endOfChildren(children)), getChildren: () => children };+}+function createPaddableMockTimeline(duration: number): RuntimeTimelineLike {- const timeline = createMockTimeline(duration) as RuntimeTimelineLike & {- to: (_target: object, vars: { duration: number }, position?: number) => void;+ const children = duration > 0 ? [mockTween(0, duration)] : [];+ const timeline = createMockTimelineOf(children) as RuntimeTimelineLike & {+ to: (+ _target: object,+ vars: { duration: number; data?: unknown },+ position?: number,+ ) => RuntimeTimelineLike;};- const baseDuration = timeline.duration;- let paddedDuration = baseDuration();- timeline.duration = () => paddedDuration;- // Mirrors GSAP: an omitted position appends sequentially at the current end.+ timeline.duration = () => endOfChildren(children);+ // Mirrors GSAP: an omitted position appends at the current end, and to() returns the timeline.timeline.to = (_target, vars, position) => {- const resolvedPosition = position ?? paddedDuration;- paddedDuration = Math.max(- paddedDuration,- resolvedPosition + Math.max(0, Number(vars.duration) || 0),+ children.push(+ mockTween(+ position ?? endOfChildren(children),+ Math.max(0, Number(vars.duration) || 0),+ 0,+ vars.data,+ ),);+ return timeline;};return timeline;}@@ -1369,6 +1423,300 @@ describe("initSandboxRuntimeModular", () => {expect(window.__player?.getDuration()).toBe(10);});+ describe("animation end", () => {+ const mountRoot = (declared: string) => {+ 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", declared);+ document.body.appendChild(root);+ };++ it("reports where a padded timeline's animation ends, not the declared length", () => {+ mountRoot("10");+ const timeline = createPaddableMockTimeline(4);+ window.__timelines = { main: timeline };+ initSandboxRuntimeModular();++ expect(timeline.duration()).toBe(10);+ expect(window.__hf?.animationEnd?.()).toBe(4);+ });++ it("keeps the animation end when a longer declared length pads the timeline again", () => {+ mountRoot("10");+ const timeline = createPaddableMockTimeline(4);+ window.__timelines = { main: timeline };+ initSandboxRuntimeModular();++ document.querySelector("[data-root]")!.setAttribute("data-duration", "12");+ (window as Window & { __hfForceTimelineRebind?: () => void }).__hfForceTimelineRebind?.();++ expect(timeline.duration()).toBe(12);+ expect(window.__hf?.animationEnd?.()).toBe(4);+ });++ it("reports no animation for an empty root timeline the runtime fills to the declared length", () => {+ mountRoot("10");+ window.gsap = {+ timeline: () => createPaddableMockTimeline(0),+ } as unknown as typeof window.gsap;+ window.__timelines = { main: createMockTimeline(0) };+ initSandboxRuntimeModular();++ expect(window.__player?.getDuration()).toBe(10);+ expect(window.__hf?.animationEnd?.()).toBeNull();+ });++ it("counts an animation adapter that runs past the root timeline", () => {+ mountRoot("3");+ window.__hfLottie = [{ goToAndStop: () => {}, totalFrames: 600, frameRate: 30 }] as never;+ window.__timelines = { main: createMockTimelineOf([mockTween(0, 2)]) };+ try {+ initSandboxRuntimeModular();+ expect(window.__hf?.animationEnd?.()).toBeCloseTo(20, 3);+ } finally {+ delete (window as Window & { __hfLottie?: unknown[] }).__hfLottie;+ }+ });++ it("reports an animation that runs past the declared length", () => {+ mountRoot("3");+ window.__timelines = { main: createMockTimelineOf([mockTween(0, 5)]) };+ initSandboxRuntimeModular();++ expect(window.__hf?.animationEnd?.()).toBe(5);+ });++ it("reports no end for a loop-inflated timeline", () => {+ mountRoot("3");+ window.__timelines = { main: createMockTimelineOf([mockTween(0, 100_000)]) };+ initSandboxRuntimeModular();++ expect(window.__hf?.animationEnd?.()).toBeNull();+ });++ it("counts one cycle of a repeating tween, not its repeats", () => {+ mountRoot("10");+ const timeline = createMockTimelineOf([mockTween(0.5, 1, 40)]);+ window.__timelines = { main: timeline };+ initSandboxRuntimeModular();++ expect(timeline.duration()).toBe(41.5);+ expect(window.__hf?.animationEnd?.()).toBe(1.5);+ });++ it("counts one cycle of a repeating tween inside a nested, time-scaled timeline", () => {+ mountRoot("10");+ const timeline = createMockTimelineOf([+ mockTween(0, 0.5),+ mockNestedTimeline(2, 2, [mockTween(0, 1, 40)]),+ ]);+ window.__timelines = { main: timeline };+ initSandboxRuntimeModular();++ expect(timeline.duration()).toBe(22.5);+ expect(window.__hf?.animationEnd?.()).toBe(2.5);+ });++ it("skips a child that is still endless and keeps the others", () => {+ mountRoot("3");+ window.__timelines = { main: createMockTimelineOf([mockTween(0, 2), mockTween(0, 1e10)]) };+ initSandboxRuntimeModular();++ expect(window.__hf?.animationEnd?.()).toBe(2);+ });++ // Its end is anchored where the runtime first sees it, so it would move with seeks and swaps.+ it("does not count a script-created WAAPI animation", () => {+ mountRoot("10");+ const doc = document as Document & { getAnimations?: () => unknown[] };+ doc.getAnimations = () => [+ {+ currentTime: 0,+ pause: () => {},+ addEventListener: () => {},+ effect: {+ getComputedTiming: () => ({+ delay: 0,+ duration: 1000,+ iterations: 40,+ endTime: 40_000,+ }),+ },+ },+ ];+ window.__timelines = { main: createMockTimelineOf([mockTween(0, 0.5)]) };+ try {+ initSandboxRuntimeModular();+ expect(window.__hf?.animationEnd?.()).toBe(0.5);+ } finally {+ delete doc.getAnimations;+ }+ });++ describe("under real GSAP", () => {+ const paused = () => gsap.timeline({ paused: true });+ const initWithRoot = (declared: string, root: ReturnType<typeof paused>) => {+ mountRoot(declared);+ window.gsap = gsap as unknown as typeof window.gsap;+ window.__timelines = { main: root as unknown as RuntimeTimelineLike };+ initSandboxRuntimeModular();+ };++ it("skips the filler that pads a short timeline to the declared length", () => {+ const root = paused().to({ x: 0 }, { x: 1, duration: 4 }, 0);+ initWithRoot("10", root);++ expect(root.duration()).toBe(10);+ expect(window.__hf?.animationEnd?.()).toBe(4);+ });++ it("reports no animation for an empty timeline the runtime fills", () => {+ initWithRoot("10", paused());++ expect(window.__player?.getDuration()).toBe(10);+ expect(window.__hf?.animationEnd?.()).toBeNull();+ });++ it("counts one cycle of a repeating tween", () => {+ const root = paused().to({ x: 0 }, { x: 1, duration: 1, repeat: 40 }, 0.5);+ initWithRoot("10", root);++ expect(root.duration()).toBe(41.5);+ expect(window.__hf?.animationEnd?.()).toBe(1.5);+ });++ it("counts a nested timeline's cycle in its parent's time", () => {+ const nested = gsap.timeline().to({ x: 0 }, { x: 1, duration: 1, repeat: 40 }).timeScale(2);+ const root = paused().to({ x: 0 }, { x: 1, duration: 0.5 }, 0).add(nested, 2);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBe(2.5);+ });++ it("counts a reversed tween forwards", () => {+ const reversed = gsap.to({ x: 0 }, { x: 1, duration: 2 }).reverse();+ const root = paused().add(reversed, 1);+ initWithRoot("20", root);++ expect(reversed.timeScale()).toBe(-1);+ expect(window.__hf?.animationEnd?.()).toBe(3);+ });++ const dots = (n: number) => Array.from({ length: n }, () => ({ x: 0 }));++ it("counts the first pass of a stagger that repeats each item", () => {+ const root = paused().to(+ dots(3),+ { x: 1, duration: 1, stagger: { each: 0.2, repeat: 2 } },+ 0,+ );+ initWithRoot("10", root);++ expect(root.getChildren()[0]!.duration()).toBeCloseTo(3.4, 6);+ expect(window.__hf?.animationEnd?.()).toBeCloseTo(1.4, 6);+ });++ it("counts the first pass of a stagger that repeats each item forever", () => {+ const root = paused()+ .to({ x: 0 }, { x: 1, duration: 1 }, 0)+ .to(dots(5), { x: 1, duration: 1, stagger: { each: 1, repeat: -1 } }, 0);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBe(5);+ });++ it("counts one cycle of repeating keyframes", () => {+ const keyframes = [+ { x: 1, duration: 1 },+ { x: 2, duration: 1 },+ ];+ const root = paused().to({ x: 0 }, { keyframes, repeat: 3 }, 0);+ initWithRoot("10", root);++ expect(root.getChildren()[0]!.totalDuration()).toBe(8);+ expect(window.__hf?.animationEnd?.()).toBe(2);+ });++ it("counts a plain stagger to its last item's end", () => {+ const root = paused().to(dots(3), { x: 1, duration: 1, stagger: 0.2 }, 0.5);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBeCloseTo(1.9, 6);+ });++ it("stretches array keyframes to the tween's own duration", () => {+ const keyframes = [{ x: 0 }, { x: 100 }, { x: 200 }, { x: 300 }];+ const root = paused().to({ x: 0 }, { keyframes, duration: 4.4, ease: "none" }, 1);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBeCloseTo(5.4, 6);+ });++ it("stretches each staggered item's keyframes to the tween's duration", () => {+ const keyframes = [{ x: 10 }, { x: 20 }];+ const root = paused().to(dots(3), { keyframes, duration: 3, stagger: 0.5 }, 0);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBeCloseTo(4, 6);+ });++ it("counts a stagger tween at the duration set after it was made", () => {+ const stagger = gsap.to(dots(3), { x: 1, duration: 1, stagger: 0.2 }).duration(4);+ const root = paused().add(stagger, 0);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBeCloseTo(4, 6);+ });++ it("keeps the end when zero-length keyframes give no stretch", () => {+ const keyframes = [+ { x: 1, duration: 0 },+ { x: 2, duration: 0 },+ ];+ const root = paused()+ .to({ x: 0 }, { x: 1, duration: 1 }, 0)+ .to({ x: 0 }, { keyframes }, 0.5);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBe(1);+ });++ // GSAP leaves a paused child out of its parent, but author code may play it later.+ it("counts a paused child the same before and after author code plays it", () => {+ const sub = paused().to({ x: 0 }, { x: 100, duration: 6 });+ const root = paused().to({ x: 0 }, { x: 1, duration: 1 }, 0).add(sub, 1);+ root.call(() => void sub.play(), undefined, 0.5);+ initWithRoot("10", root);++ expect(window.__hf?.animationEnd?.()).toBe(7);+ root.seek(2, false);+ expect(sub.paused()).toBe(false);+ expect(window.__hf?.animationEnd?.()).toBe(7);+ });++ it("caps an auto-nested sub-composition at its host clip's end", () => {+ mountRoot("9");+ const host = document.createElement("div");+ host.setAttribute("data-composition-id", "scene");+ host.setAttribute("data-start", "1");+ host.setAttribute("data-duration", "3");+ host.classList.add("clip");+ document.querySelector("[data-root]")!.appendChild(host);+ // Authored scene timelines are commonly padded to their full length.+ const scene = paused().to({ x: 0 }, { x: 1, duration: 2 }, 0).to({}, { duration: 8 }, 0);+ const root = paused().to({ x: 0 }, { x: 1, duration: 1 }, 0);+ window.gsap = gsap as unknown as typeof window.gsap;+ window.__timelines = { main: root, scene } as never;+ initSandboxRuntimeModular();++ expect(root.duration()).toBe(9);+ expect(window.__hf?.animationEnd?.()).toBe(4);+ });+ });+ });+// #6: a single timeline registered under a key that does NOT match the root's// data-composition-id must still bind (sole-timeline fallback) instead of// silently rendering the frozen t=0 DOM.diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex da94a6aa87..ebd8165211 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -37,7 +37,11 @@ import { probeAndCacheElementVolume, type VolumeKeyframe } from "./mediaVolumeEnimport { createPickerModule } from "./picker";import { createRuntimePlayer, type RuntimePlayerTransport } from "./player";import { createRuntimeState } from "./state";-import { collectRuntimeTimelinePayload, isRuntimeElementVisibleAt } from "./timeline";+import {+ collectRuntimeTimelinePayload,+ isRuntimeElementVisibleAt,+ LOOP_INFLATED_TIMELINE_SECONDS,+} from "./timeline";import {findRootCompositionElement,parseCompositionDimension,@@ -83,6 +87,7 @@ import type {RuntimeDeterministicAdapter,RuntimeJson,RuntimeSeekOptions,+ RuntimeTimelineChildLike,RuntimeTimelineLike,} from "./types";import type { PlayerAPI } from "../core.types";@@ -239,6 +244,8 @@ const MEDIA_URL_ATTRS = new Map([]);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";export function initSandboxRuntimeModular(): void {const state = createRuntimeState();@@ -1058,10 +1065,12 @@ export function initSandboxRuntimeModular(): void {// media windows already use — makes data-duration optional wherever the// runtime can figure the duration out on its own, instead of hard-failing// capture with "Composition has zero duration".- const resolveAdapterDurationFloorSeconds = (): number | null => {+ const resolveAdapterDurationFloorSeconds = (oneCycle = false): number | null => {let maxSeconds = 0;for (const adapter of state.deterministicAdapters) {- const getter = adapter.getInferredDurationSeconds;+ const getter = oneCycle+ ? adapter.getAnimationCycleEndSeconds+ : adapter.getInferredDurationSeconds;if (typeof getter !== "function") continue;let inferred: number | null = null;try {@@ -1308,6 +1317,9 @@ export function initSandboxRuntimeModular(): void {return safeDuration > 0 ? Math.max(0, safeDuration) : 0;};+ // Sub-composition timelines the runtime nested into the root, by host composition id.+ const autoNestedHostIds = new WeakMap<object, string>();+const resolveRootTimelineFromDocument = (): TimelineResolution => {const timelines = (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>;// DX fallback (#6): when the root timeline cannot be resolved by id but@@ -1354,6 +1366,13 @@ export function initSandboxRuntimeModular(): void {if (!node) return 0;return startResolver.resolveStartForElement(node, 0);};+ const nestAtHostStart = (+ parent: RuntimeTimelineLike,+ candidate: { compositionId: string; timeline: RuntimeTimelineLike },+ ): void => {+ parent.add(candidate.timeline, resolveCompositionStartSeconds(candidate.compositionId));+ autoNestedHostIds.set(candidate.timeline, candidate.compositionId);+ };const createCompositeTimelineFromCandidates = (candidates: Array<{compositionId: string;@@ -1364,12 +1383,7 @@ export function initSandboxRuntimeModular(): void {const gsapApi = window.gsap;if (!gsapApi || typeof gsapApi.timeline !== "function") return null;const compositeTimeline = gsapApi.timeline({ paused: true }) as RuntimeTimelineLike;- for (const candidate of candidates) {- compositeTimeline.add(- candidate.timeline,- resolveCompositionStartSeconds(candidate.compositionId),- );- }+ for (const candidate of candidates) nestAtHostStart(compositeTimeline, candidate);return compositeTimeline;};const createDurationFloorTimeline = (@@ -1389,11 +1403,11 @@ export function initSandboxRuntimeModular(): void {}}const withTween = fallbackTimeline as RuntimeTimelineLike & {- to?: (target: object, vars: { duration?: number }) => unknown;+ to?: (target: object, vars: { duration?: number; data?: string }) => unknown;};if (typeof withTween.to === "function") {try {- withTween.to({}, { duration: durationSeconds });+ withTween.to({}, { duration: durationSeconds, data: RUNTIME_FILLER });} catch (err) {// no-op; if tween creation fails, caller will discard by unusable durationswallow("runtime.init.site3", err);@@ -1436,8 +1450,7 @@ export function initSandboxRuntimeModular(): void {const alreadyIncluded = existingChildren.some((child) => child === candidate.timeline);if (alreadyIncluded) continue;try {- const startSec = resolveCompositionStartSeconds(candidate.compositionId);- rootTimeline.add(candidate.timeline, startSec);+ nestAtHostStart(rootTimeline, candidate);addedIds.push(candidate.compositionId);} catch (err) {// ignore broken child add attempts@@ -1644,13 +1657,17 @@ export function initSandboxRuntimeModular(): void {rootDurationFloorSeconds >= rootDurationSeconds + 0.5) {const tlWithTo = rootTimeline as RuntimeTimelineLike & {- to?: (target: object, vars: { duration: number }, position: number) => unknown;+ to?: (+ target: object,+ vars: { duration: number; data: string },+ position: number,+ ) => unknown;};if (typeof tlWithTo.to === "function") {try {// Placing a zero-duration tween at the floor extends// timeline.duration() to exactly that point.- tlWithTo.to({}, { duration: 0 }, rootDurationFloorSeconds);+ tlWithTo.to({}, { duration: 0, data: RUNTIME_FILLER }, rootDurationFloorSeconds);} catch (err) {// keep runtime resilientswallow("runtime.init.site6", err);@@ -2769,6 +2786,47 @@ export function initSandboxRuntimeModular(): void {};window.__hf.leasePausedMedia = leasePausedMedia;window.__hf.releasePausedMedia = releasePausedMedia;+ // A sub-composition is hidden after its host clip, so its animation counts only until then.+ const autoNestedHostEndSeconds = (child: RuntimeTimelineChildLike): number => {+ const hostId = autoNestedHostIds.get(child);+ const host = hostId+ ? document.querySelector(`[data-composition-id="${CSS.escape(hostId)}"]`)+ : null;+ const duration = host ? resolveDurationForElement(host) : null;+ return host && duration ? resolveStartForElement(host, 0) + duration : Infinity;+ };+ // GSAP's duration() of a tween is one iteration; a timeline's duration() counts its children's repeats.+ const readOneCycleEndSeconds = (children: RuntimeTimelineChildLike[]): number => {+ let end = 0;+ for (const child of children) {+ if (child.data === RUNTIME_FILLER) continue;+ // A stagger or keyframes tween runs an inner timeline; its duration() counts per-item repeats.+ const nested = child.getChildren+ ? child+ : (child as { timeline?: RuntimeTimelineChildLike }).timeline;+ // GSAP plays a tween's inner timeline stretched to the tween's own duration() (1 for a timeline).+ const stretch = Number(child.duration?.()) / Number(nested?.duration?.());+ const cycle = nested?.getChildren+ ? readOneCycleEndSeconds(nested.getChildren(false, true, true)) *+ (Number.isFinite(stretch) && stretch > 0 ? stretch : 1)+ : Number(child.duration?.()) || 0;+ // startTime() is in the parent's time, the cycle in the child's own; reversed reports -1.+ const scale = Math.abs(Number((child as { timeScale?: () => number }).timeScale?.()) || 1);+ const childEnd = (Number(child.startTime?.()) || 0) + cycle / scale;+ // A child still endless here reports ~1e10 s; skip it, as the adapters skip loops.+ if (childEnd >= LOOP_INFLATED_TIMELINE_SECONDS) continue;+ end = Math.max(end, Math.min(childEnd, autoNestedHostEndSeconds(child)));+ }+ return end;+ };+ window.__hf.animationEnd = () => {+ const timeline = state.capturedTimeline;+ const timelineEnd = timeline?.getChildren+ ? readOneCycleEndSeconds(timeline.getChildren(false, true, true))+ : (getTimelineDurationSeconds(timeline) ?? 0);+ const end = Math.max(timelineEnd, resolveAdapterDurationFloorSeconds(true) ?? 0);+ return end > 0 && end < LOOP_INFLATED_TIMELINE_SECONDS ? end : null;+ };window.__hf.audioMeter = {start: () => webAudio.startMetering(),stop: () => webAudio.stopMetering(),diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.tsindex a2097ba262..fd924f0702 100644--- a/packages/core/src/runtime/timeline.ts+++ b/packages/core/src/runtime/timeline.ts@@ -31,7 +31,7 @@ import { isElementNode, isMediaElement } from "./domRealm";/** A root timeline this long is an endless loop, not a film: GSAP reports 1e10 s for `repeat: -1`.* Studio's sanitizeDurationSeconds rejects the same length. Animations that simply end past the* voiceover are real duration, and the runtime player already plays them. */-const LOOP_INFLATED_TIMELINE_SECONDS = 7200;+export const LOOP_INFLATED_TIMELINE_SECONDS = 7200;export function isRuntimeElementVisibleAt(rawNode: HTMLElement,diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.tsindex 2782405873..97836f35c3 100644--- a/packages/core/src/runtime/types.ts+++ b/packages/core/src/runtime/types.ts@@ -288,7 +288,9 @@ export type RuntimeTimelineChildLike = {vars?: unknown;startTime?: () => number;duration?: () => number;+ data?: unknown;parent?: RuntimeTimelineChildLike;+ getChildren?: RuntimeTimelineLike["getChildren"];};export type RuntimeTimelineLike = {@@ -356,6 +358,7 @@ export type RuntimeDeterministicAdapter = {* (Lottie JSON fetch, etc.) resolves.*/getInferredDurationSeconds?: () => number | null;+ getAnimationCycleEndSeconds?: () => number | null;};export type RuntimeGsapSetTarget = string | Element | Element[] | null;diff --git a/packages/core/src/runtime/window.d.ts b/packages/core/src/runtime/window.d.tsindex 8e3c9a8f28..38d353de40 100644--- a/packages/core/src/runtime/window.d.ts+++ b/packages/core/src/runtime/window.d.ts@@ -54,6 +54,10 @@ declare global {seconds: number | null;pendingClips: number;};+ /** Where each animation's FIRST cycle ends, latest wins, in seconds (root timeline, CSS and+ * Lottie; never script-created WAAPI, media or the declared length); repeats may run past it.+ * Null when unknown. Studio reads it. */+ animationEnd?: () => number | null;/** Borrow an element's playback while the transport clock is paused, so the* runtime's paused-side enforcement leaves it alone. Always release. */leasePausedMedia?: (el: HTMLMediaElement) => void;