Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
refactor(core): one pure owner for composition length and root size (#4990)
Miguel Ángel34ff5ca1dea1
diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.jsonindex dc5ef6b14d..eead54ea7c 100644--- a/packages/core/package-subpaths.json+++ b/packages/core/package-subpaths.json@@ -314,6 +314,12 @@"types": "./dist/runtime/startResolver.d.ts","environments": ["browser", "bun", "node"]},+ "./runtime/composition-length": {+ "source": "./src/runtime/compositionLength.ts",+ "runtime": "./dist/runtime/compositionLength.js",+ "types": "./dist/runtime/compositionLength.d.ts",+ "environments": ["browser", "bun", "node"]+ },"./runtime/protocol": {"source": "./src/runtime/protocol.ts","runtime": "./dist/runtime/protocol.js",diff --git a/packages/core/package.json b/packages/core/package.jsonindex 11e8ab9b1a..df95a78960 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -323,6 +323,12 @@"import": "./src/runtime/startResolver.ts","types": "./src/runtime/startResolver.ts"},+ "./runtime/composition-length": {+ "bun": "./src/runtime/compositionLength.ts",+ "node": "./dist/runtime/compositionLength.js",+ "import": "./src/runtime/compositionLength.ts",+ "types": "./src/runtime/compositionLength.ts"+ },"./runtime/protocol": {"bun": "./src/runtime/protocol.ts","node": "./dist/runtime/protocol.js",@@ -699,6 +705,10 @@"import": "./dist/runtime/startResolver.js","types": "./dist/runtime/startResolver.d.ts"},+ "./runtime/composition-length": {+ "import": "./dist/runtime/compositionLength.js",+ "types": "./dist/runtime/compositionLength.d.ts"+ },"./runtime/protocol": {"import": "./dist/runtime/protocol.js","types": "./dist/runtime/protocol.d.ts"diff --git a/packages/core/src/runtime/compositionDimension.ts b/packages/core/src/runtime/compositionDimension.tsindex 5ade559768..1fbcb5bffc 100644--- a/packages/core/src/runtime/compositionDimension.ts+++ b/packages/core/src/runtime/compositionDimension.ts@@ -14,9 +14,9 @@ export function parseCompositionDimension(value: string | null | undefined): numreturn Number.isFinite(parsed) && parsed > 0 ? parsed : null;}-export function findRootCompositionElement(): HTMLElement | null {- const explicitRoot = document.querySelector('[data-composition-id][data-root="true"]');+export function findRootCompositionElement(doc: ParentNode = document): HTMLElement | null {+ const explicitRoot = doc.querySelector('[data-composition-id][data-root="true"]');if (isHtmlElement(explicitRoot)) return explicitRoot;// The first composition in document order never sits inside another one.- return document.querySelector<HTMLElement>("[data-composition-id]");+ return doc.querySelector<HTMLElement>("[data-composition-id]");}diff --git a/packages/core/src/runtime/compositionLength.test.ts b/packages/core/src/runtime/compositionLength.test.tsnew file mode 100644index 0000000000..cbcb591d55--- /dev/null+++ b/packages/core/src/runtime/compositionLength.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it, vi } from "vitest";+import { parseHTMLContent } from "../compiler/htmlDocument";+import {+ findRootCompositionElement,+ MIN_VALID_TIMELINE_DURATION_SECONDS,+ readStaticCompositionMeta,+ resolveCompositionLengthSeconds,+} from "./compositionLength";++describe("resolveCompositionLengthSeconds", () => {+ const base = {+ declared: null,+ timeline: () => null,+ floors: () => [],+ fallback: 0,+ derived: () => 0,+ };++ it("takes a declared length and reads nothing else", () => {+ const timeline = vi.fn(() => 10);+ const floors = vi.fn(() => [12]);+ const derived = vi.fn(() => 7);+ expect(+ resolveCompositionLengthSeconds({ ...base, declared: 4, timeline, floors, derived }),+ ).toBe(4);+ expect(timeline).not.toHaveBeenCalled();+ expect(floors).not.toHaveBeenCalled();+ expect(derived).not.toHaveBeenCalled();+ });++ it("does not take an infinite declared length", () => {+ expect(+ resolveCompositionLengthSeconds({ ...base, declared: Infinity, timeline: () => 6 }),+ ).toBe(6);+ });++ it("takes the longest of timeline, floors and fallback", () => {+ expect(+ resolveCompositionLengthSeconds({+ ...base,+ timeline: () => 6,+ floors: () => [8, null],+ fallback: 5,+ }),+ ).toBe(8);+ });++ it("ignores a timeline of one frame or less", () => {+ const oneFrame = MIN_VALID_TIMELINE_DURATION_SECONDS;+ expect(+ resolveCompositionLengthSeconds({ ...base, timeline: () => oneFrame, derived: () => 2 }),+ ).toBe(2);+ });++ it("derives the length only when nothing else gives one", () => {+ expect(resolveCompositionLengthSeconds({ ...base, derived: () => 2.5 })).toBe(2.5);+ expect(resolveCompositionLengthSeconds({ ...base, fallback: 9, derived: () => 2.5 })).toBe(9);+ });+});++// Server-side callers parse with linkedom, browsers with DOMParser: both must agree.+const parsers: Array<[string, (html: string) => Document]> = [+ ["linkedom", (html) => parseHTMLContent(html)],+ ["DOMParser", (html) => new DOMParser().parseFromString(html, "text/html")],+];++describe.each(parsers)("readStaticCompositionMeta (%s)", (_name, parse) => {+ const meta = (html: string) => readStaticCompositionMeta(parse(html));++ it("reads the data-root composition's declared length and size", () => {+ const html =+ `<div data-composition-id="card" data-width="800" data-height="600" data-duration="9"></div>` ++ `<div data-composition-id="main" data-root="true" data-width="1080" data-height="1920" data-duration="4"></div>`;+ expect(meta(html)).toEqual({ width: 1080, height: 1920, fps: 30, durationSeconds: 4 });+ });++ it("extends to a nested video's authored end at its absolute start", () => {+ const html =+ `<div data-composition-id="main"><div data-composition-id="scene" data-start="3">` ++ `<video data-start="1" data-duration="4"></video></div></div>`;+ expect(meta(html)?.durationSeconds).toBe(8);+ });++ it("extends to a sub-composition's declared end", () => {+ const html = `<div data-composition-id="main"><div data-composition-id="scene" data-start="1" data-duration="5"></div></div>`;+ expect(meta(html)?.durationSeconds).toBe(6);+ });++ it("derives the length from the clips, and is 0 while one is pending", () => {+ expect(+ meta(`<div data-composition-id="main"><div data-start="1" data-duration="3"></div></div>`)+ ?.durationSeconds,+ ).toBe(4);+ const pending = `<div data-composition-id="main"><div data-start="0" data-duration="3"></div><video data-start="0"></video></div>`;+ expect(meta(pending)?.durationSeconds).toBe(0);+ });++ it("is null without a composition", () => {+ expect(meta("<div></div>")).toBeNull();+ });+});++describe("findRootCompositionElement", () => {+ it("reads the document it is given, not the global one", () => {+ const doc = parseHTMLContent(+ `<div data-composition-id="a"></div><div data-composition-id="b" data-root="true"></div>`,+ );+ expect(findRootCompositionElement(doc)?.getAttribute("data-composition-id")).toBe("b");+ });+});diff --git a/packages/core/src/runtime/compositionLength.ts b/packages/core/src/runtime/compositionLength.tsnew file mode 100644index 0000000000..7cae2572d7--- /dev/null+++ b/packages/core/src/runtime/compositionLength.ts@@ -0,0 +1,166 @@+import {+ resolveCompositionDuration,+ type CompositionDurationResult,+} from "@hyperframes/parsers/composition-duration";+import { findRootCompositionElement, parseCompositionDimension } from "./compositionDimension";+import { isMediaElement } from "./domRealm";+import { parseStrictFiniteTimingNumber, resolveMediaElementDurationSeconds } from "./playbackRate";+import { createRuntimeStartTimeResolver } from "./startResolver";+import { createRuntimeState } from "./state";++export { findRootCompositionElement };++/** One frame at 60 fps: a timeline, floor or fallback this short or shorter is no length at all. */+export const MIN_VALID_TIMELINE_DURATION_SECONDS = 1 / 60;++type StartResolver = Pick<+ ReturnType<typeof createRuntimeStartTimeResolver>,+ "resolveStartForElement" | "resolveDurationForElement"+>;++const aboveOneFrame = (seconds: number | null): number | null =>+ seconds !== null && seconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? seconds : null;++/** The size the runtime reports to its host. */+export function readCompositionSize(root: Element): {+ width: number | null;+ height: number | null;+} {+ return {+ width: parseCompositionDimension(root.getAttribute("data-width")),+ height: parseCompositionDimension(root.getAttribute("data-height")),+ };+}++/** The latest end among the document's timed video and audio, at their absolute starts. */+export function resolveMediaWindowDurationSeconds(+ doc: ParentNode,+ media: {+ mediaStart: (el: HTMLMediaElement) => number;+ mediaDuration: (el: HTMLMediaElement) => number | null;+ },+): number | null {+ const clipEnds: number[] = [];+ for (const node of doc.querySelectorAll<HTMLMediaElement>(+ "video[data-start], audio[data-start]",+ )) {+ const start = media.mediaStart(node);+ if (!Number.isFinite(start)) continue;+ const duration = media.mediaDuration(node);+ if (duration == null || duration <= MIN_VALID_TIMELINE_DURATION_SECONDS) continue;+ clipEnds.push(Math.max(0, start) + duration);+ }+ return aboveOneFrame(+ resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: clipEnds })+ .seconds,+ );+}++/** The latest of the root's declared length and its direct sub-compositions' ends. */+export function resolveAuthoredCompositionFloorSeconds(+ root: Element,+ startResolver: StartResolver,+): number | null {+ const subCompositionEnds: number[] = [];+ for (const node of root.querySelectorAll("[data-composition-id][data-start]")) {+ if (node.parentElement?.closest("[data-composition-id]") !== root) continue;+ const start = startResolver.resolveStartForElement(node, 0);+ const duration = startResolver.resolveDurationForElement(node);+ if (!Number.isFinite(start) || duration == null || duration <= 0) continue;+ subCompositionEnds.push(Math.max(0, start) + duration);+ }+ const declared = parseStrictFiniteTimingNumber(root.getAttribute("data-duration"));+ return aboveOneFrame(+ resolveCompositionDuration({+ authoredDurationSeconds: null,+ clipEndsSeconds: [declared, ...subCompositionEnds],+ }).seconds,+ );+}++const isCompositionHost = (node: Element): boolean =>+ node.hasAttribute("data-composition-id") || node.hasAttribute("data-composition-src");++/** The last-resort length: the latest end among the root's timed clips. Until every clip's length+ * is known it is unresolved, so a renderer that reads it once cannot lock in a short one.+ * `unregisteredLottie`: a Lottie library is loaded, so animations may still register. */+export function resolveContentDerivedDuration(+ root: Element,+ startResolver: StartResolver,+ { unregisteredLottie }: { unregisteredLottie: boolean },+): CompositionDurationResult {+ const clipEnds: Array<number | null> = [];+ for (const node of root.querySelectorAll("[data-start]")) {+ const start = startResolver.resolveStartForElement(node, 0);+ if (!Number.isFinite(start)) continue;+ const duration = startResolver.resolveDurationForElement(node);+ if (duration != null) clipEnds.push(Math.max(0, start) + duration);+ else if (isMediaElement(node) || isCompositionHost(node)) clipEnds.push(null);+ }+ if (unregisteredLottie || root.querySelector("[data-lottie-src]")) clipEnds.push(null);+ const result = resolveCompositionDuration({+ authoredDurationSeconds: null,+ clipEndsSeconds: clipEnds,+ });+ return result.pendingClips > 0+ ? { ...result, seconds: null, source: "unresolved", reason: "a clip's length is pending" }+ : result;+}++export type CompositionLengthInputs = {+ declared: number | null;+ // Read only when nothing is declared: they can run author or adapter code.+ timeline: () => number | null;+ floors: () => ReadonlyArray<number | null>;+ fallback: number;+ derived: () => number;+};++/** A declared root length is the length (a longer timeline is cut off); else the timeline, the+ * floors and the fallback, whichever is longest; else the length derived from the clips. */+export function resolveCompositionLengthSeconds(input: CompositionLengthInputs): number {+ if (input.declared !== null && Number.isFinite(input.declared) && input.declared > 0) {+ return input.declared;+ }+ const timeline = aboveOneFrame(input.timeline());+ const floor = Math.max(0, ...input.floors().map((seconds) => seconds ?? 0));+ const fallback =+ Number.isFinite(input.fallback) && input.fallback > MIN_VALID_TIMELINE_DURATION_SECONDS+ ? input.fallback+ : 0;+ let seconds: number;+ if (timeline !== null) seconds = Math.max(timeline, floor, fallback);+ else if (aboveOneFrame(floor) !== null) seconds = Math.max(floor, fallback);+ else if (fallback > 0) seconds = fallback;+ else seconds = input.derived();+ return seconds > 0 ? seconds : 0;+}++/** Size, frame rate and length of a composition nothing is running (a server-parsed or detached+ * document): no timelines, no adapters, and media without a known source length is pending. */+export function readStaticCompositionMeta(+ doc: Document,+): { width: number | null; height: number | null; fps: number; durationSeconds: number } | null {+ const root = findRootCompositionElement(doc);+ if (!root) return null;+ const resolver = createRuntimeStartTimeResolver({+ timelineRegistry: {},+ includeAuthoredTimingAttrs: true,+ documentRef: doc,+ });+ const durationSeconds = resolveCompositionLengthSeconds({+ declared: parseStrictFiniteTimingNumber(root.getAttribute("data-duration")),+ timeline: () => null,+ floors: () => [+ resolveMediaWindowDurationSeconds(doc, {+ mediaStart: resolver.resolveMediaStartForElement,+ mediaDuration: resolveMediaElementDurationSeconds,+ }),+ resolveAuthoredCompositionFloorSeconds(root, resolver),+ ],+ fallback: 0,+ derived: () =>+ resolveContentDerivedDuration(root, resolver, { unregisteredLottie: false }).seconds ?? 0,+ });+ return { ...readCompositionSize(root), fps: createRuntimeState().canonicalFps, durationSeconds };+}diff --git a/packages/core/src/runtime/init.compositionLength.test.ts b/packages/core/src/runtime/init.compositionLength.test.tsnew file mode 100644index 0000000000..a74b8922b5--- /dev/null+++ b/packages/core/src/runtime/init.compositionLength.test.ts@@ -0,0 +1,116 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { initSandboxRuntimeModular } from "./init";+import type { RuntimeTimelineLike } from "./types";+import {+ createMockTimeline,+ installImmediateAnimationFrame,+ resetRuntimeFixtureDom,+ stubDuration,+} from "./runtimeSeekFixture.test-helpers";++// Pins what the running runtime reports as a composition's length and size.+describe("runtime composition length and size", () => {+ const originalRequestAnimationFrame = window.requestAnimationFrame;+ const originalCancelAnimationFrame = window.cancelAnimationFrame;++ beforeEach(() => {+ resetRuntimeFixtureDom();+ installImmediateAnimationFrame();+ });++ afterEach(() => {+ window.__hfRuntimeTeardown?.();+ window.requestAnimationFrame = originalRequestAnimationFrame;+ window.cancelAnimationFrame = originalCancelAnimationFrame;+ vi.restoreAllMocks();+ delete window.__player;+ delete window.__playerReady;+ delete window.__hf;+ });++ const lengthOf = (+ html: string,+ timelines: Record<string, RuntimeTimelineLike>,+ durations: Record<string, number> = {},+ ): number | undefined => {+ document.body.innerHTML = html;+ for (const [id, seconds] of Object.entries(durations)) {+ stubDuration(document.getElementById(id) as HTMLMediaElement, seconds);+ }+ window.__timelines = timelines;+ initSandboxRuntimeModular();+ return window.__player?.getDuration();+ };++ it("cuts a longer timeline at the root's declared length", () => {+ const html = `<div data-composition-id="main" data-root="true" data-duration="4"></div>`;+ expect(lengthOf(html, { main: createMockTimeline(10) })).toBe(4);+ });++ it("takes the timeline's length when the root declares none", () => {+ const html = `<div data-composition-id="main" data-root="true"></div>`;+ expect(lengthOf(html, { main: createMockTimeline(6) })).toBe(6);+ });++ it("extends to a nested video's end at its absolute start", () => {+ const html =+ `<div data-composition-id="main" data-root="true">` ++ `<div data-composition-id="scene" data-start="3">` ++ `<video id="v" data-start="1" data-duration="4"></video></div></div>`;+ expect(lengthOf(html, { main: createMockTimeline(2) }, { v: 10 })).toBe(8);+ });++ it("extends to a sub-composition's declared end", () => {+ const html =+ `<div data-composition-id="main" data-root="true">` ++ `<div data-composition-id="scene" data-start="1" data-duration="5"></div></div>`;+ expect(lengthOf(html, { main: createMockTimeline(2) })).toBe(6);+ });++ it("derives the length from the clips when nothing else gives one", () => {+ const html =+ `<div data-composition-id="main" data-root="true">` ++ `<div data-start="1" data-duration="3"></div></div>`;+ expect(lengthOf(html, {})).toBe(4);+ expect(window.__hf?.durationSource).toEqual({ source: "derived", seconds: 4, pendingClips: 0 });+ });++ it("reports 0 while a clip's length is pending", () => {+ const html =+ `<div data-composition-id="main" data-root="true">` ++ `<div data-start="0" data-duration="3"></div><video data-start="0"></video></div>`;+ expect(lengthOf(html, {})).toBe(0);+ expect(window.__hf?.durationSource).toEqual({+ source: "unresolved",+ seconds: null,+ pendingClips: 1,+ });+ });++ it("ignores a timeline shorter than a frame and keeps a tiny derived clip", () => {+ const html =+ `<div data-composition-id="main" data-root="true">` ++ `<div data-start="0" data-duration="0.01"></div></div>`;+ expect(lengthOf(html, { main: createMockTimeline(0.01) })).toBe(0.01);+ });++ it("reads the data-root composition, not the first one in the document", () => {+ const html =+ `<div data-composition-id="card" data-duration="9"></div>` ++ `<div data-composition-id="main" data-root="true" data-duration="4"></div>`;+ expect(lengthOf(html, { main: createMockTimeline(10) })).toBe(4);+ });++ it("reports the root's size to the host", () => {+ const sizes: string[] = [];+ vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {+ const m = message as { type?: string; width?: number; height?: number };+ if (m?.type === "stage-size") sizes.push(`${m.width}x${m.height}`);+ });+ const html =+ `<div data-composition-id="card" data-width="800" data-height="600"></div>` ++ `<div data-composition-id="main" data-root="true" data-duration="4" data-width="1280.9" data-height="720"></div>`;+ lengthOf(html, { main: createMockTimeline(4) });+ expect(new Set(sizes)).toEqual(new Set(["1280x720"]));+ });+});diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex e22fae957d..20b7a3e9f0 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -52,12 +52,16 @@ import {LOOP_INFLATED_TIMELINE_SECONDS,parseAuthoredTrack,} from "./timeline";-import {- findRootCompositionElement,- parseCompositionDimension,- parseLayoutDimension,-} from "./compositionDimension";+import { findRootCompositionElement, parseLayoutDimension } from "./compositionDimension";import { resolveCompositionDuration } from "@hyperframes/parsers/composition-duration";+import {+ MIN_VALID_TIMELINE_DURATION_SECONDS,+ readCompositionSize,+ resolveAuthoredCompositionFloorSeconds,+ resolveCompositionLengthSeconds,+ resolveContentDerivedDuration as resolveContentDerivedDurationFor,+ resolveMediaWindowDurationSeconds as resolveMediaWindowDurationSecondsIn,+} from "./compositionLength";import { createRuntimeStartTimeResolver } from "./startResolver";import { createClipTree } from "./clipTree";import { loadExternalCompositions, loadInlineTemplateCompositions } from "./compositionLoader";@@ -643,7 +647,6 @@ export function initSandboxRuntimeModular(): void {};};- const MIN_VALID_TIMELINE_DURATION_SECONDS = 1 / 60;const TIMELINE_FLOOR_COVERAGE_RATIO = 0.75;const METADATA_REBIND_MIN_DURATION_GAIN_SECONDS = 0.05;const METADATA_REBIND_DEBOUNCE_MS = 100;@@ -996,21 +999,12 @@ export function initSandboxRuntimeModular(): void {// Checked before the scope opens: a composition with no timed media runs// this every tick, and it should not pay for a resolver it never uses.if (mediaNodes.length === 0) return null;- return withTimingResolver(() => {- const clipEnds: number[] = [];- for (const node of mediaNodes) {- const start = resolveAbsoluteMediaStartSeconds(node);- if (!Number.isFinite(start)) continue;- const duration = resolveMediaElementDurationSeconds(node);- if (duration == null || duration <= MIN_VALID_TIMELINE_DURATION_SECONDS) continue;- clipEnds.push(Math.max(0, start) + duration);- }- const { seconds } = resolveCompositionDuration({- authoredDurationSeconds: null,- clipEndsSeconds: clipEnds,- });- return seconds !== null && seconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? seconds : null;- });+ return withTimingResolver(() =>+ resolveMediaWindowDurationSecondsIn(document, {+ mediaStart: resolveAbsoluteMediaStartSeconds,+ mediaDuration: resolveMediaElementDurationSeconds,+ }),+ );};const resolveAuthoredCompositionDurationFloorSeconds = (): number | null => {@@ -1024,44 +1018,16 @@ export function initSandboxRuntimeModular(): void {// getSafeTimelineDurationSeconds returns the declared length first; here it only sizes the// stand-in timeline that resolveRootTimelineFromDocument builds for a root timeline with no// length.- const rootDeclaredSeconds = parseStrictFiniteTimingNumber(rootEl.getAttribute("data-duration"));- const subCompositionEnds: number[] = [];- const compositionNodes = Array.from(- rootEl.querySelectorAll("[data-composition-id][data-start]"),- );- for (const node of compositionNodes) {- if (!isElementNode(node)) continue;- const parentComposition = node.parentElement?.closest("[data-composition-id]");- if (parentComposition !== rootEl) continue;- const start = startResolver.resolveStartForElement(node, 0);- const duration = startResolver.resolveDurationForElement(node);- if (!Number.isFinite(start) || duration == null || duration <= 0) continue;- subCompositionEnds.push(Math.max(0, start) + duration);- }- // A floor, not a resolution: the declared duration and every sub-composition end all hold,- // so the latest of them is the floor.- const { seconds: floorSeconds } = resolveCompositionDuration({- authoredDurationSeconds: null,- clipEndsSeconds: [rootDeclaredSeconds, ...subCompositionEnds],- });- return floorSeconds !== null && floorSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS- ? floorSeconds- : null;+ return resolveAuthoredCompositionFloorSeconds(rootEl, startResolver);};/** The last-resort length: the latest end among the root's timed clips, used only when no* timeline, floor or caller-supplied length exists. Pending media is counted, not guessed. */- // A sub-composition's length comes from its own timeline, which may not be registered yet.- const isCompositionHost = (node: Element): boolean =>- node.hasAttribute("data-composition-id") || node.hasAttribute("data-composition-src");// Lottie registers its animations from author scripts, often after the runtime is ready, and- // nothing in the DOM says when. A loaded Lottie library or a declared source means a length- // that has not been registered yet, so it counts as a pending clip like media does.- const hasUnregisteredLottie = (rootEl: Element): boolean => {+ // nothing in the DOM says when: a loaded library means a length that is still pending.+ const hasLottieLibrary = (): boolean => {const lottieWindow = window as Window & { lottie?: unknown; DotLottie?: unknown };- return Boolean(- lottieWindow.lottie || lottieWindow.DotLottie || rootEl.querySelector("[data-lottie-src]"),- );+ return Boolean(lottieWindow.lottie || lottieWindow.DotLottie);};const resolveContentDerivedDuration = () => {const rootEl = resolveRootCompositionElement();@@ -1074,30 +1040,9 @@ export function initSandboxRuntimeModular(): void {>,includeAuthoredTimingAttrs: true,});- const clipEnds: Array<number | null> = [];- for (const node of Array.from(rootEl.querySelectorAll("[data-start]"))) {- if (!isElementNode(node)) continue;- const start = startResolver.resolveStartForElement(node, 0);- if (!Number.isFinite(start)) continue;- const duration = startResolver.resolveDurationForElement(node);- if (duration != null) clipEnds.push(Math.max(0, start) + duration);- else if (isMediaElement(node) || isCompositionHost(node)) clipEnds.push(null);- }- if (hasUnregisteredLottie(rootEl)) clipEnds.push(null);- const result = resolveCompositionDuration({- authoredDurationSeconds: null,- clipEndsSeconds: clipEnds,+ return resolveContentDerivedDurationFor(rootEl, startResolver, {+ unregisteredLottie: hasLottieLibrary(),});- // A length that a pending clip can still extend is not final, and a renderer that reads the- // duration once would lock the short one in: stay at zero until every clip's length is known.- return result.pendingClips > 0- ? {- ...result,- seconds: null,- source: "unresolved" as const,- reason: "a clip's length is pending",- }- : result;};let contentDerivedCache: {@@ -1369,48 +1314,28 @@ export function initSandboxRuntimeModular(): void {fallback = 0,timingRevision?: number,): number => {- // The root's declared length is the film's length, as in the render: a longer timeline is cut- // off.- const declaredDuration = parseStrictFiniteTimingNumber(- resolveRootCompositionElement()?.getAttribute("data-duration"),- );- // Any positive length counts, even one frame: the render accepts it too.- if (declaredDuration !== null && declaredDuration > 0) {- if (window.__hf?.durationSource) delete window.__hf.durationSource;- return declaredDuration;- }- const timelineDuration = getTimelineDurationSeconds(timeline);- const { media: mediaFloor, authoredComposition: authoredCompositionFloor } =- resolveDurationFloors(timingRevision);- // Deliberately NOT cached: adapters infer their duration from live- // animation objects (CSS/WAAPI/Lottie), which can change without any DOM- // mutation or media event to observe. It is also a short loop over the- // registered adapters, not a document scan.- const adapterFloor = resolveAdapterDurationFloorSeconds();- const durationFloor = Math.max(- mediaFloor ?? 0,- authoredCompositionFloor ?? 0,- adapterFloor ?? 0,- );- const fallbackDuration =- Number.isFinite(fallback) && fallback > MIN_VALID_TIMELINE_DURATION_SECONDS ? fallback : 0;- let safeDuration = 0;let derivedDuration: ReturnType<typeof resolveContentDerivedDuration> | null = null;- // Timeline is the source of truth for authored composition duration.- if (isUsableTimelineDuration(timelineDuration)) {- safeDuration = Math.max(timelineDuration, durationFloor, fallbackDuration);- } else if (isUsableTimelineDuration(durationFloor)) {- safeDuration = Math.max(durationFloor, fallbackDuration);- } else if (fallbackDuration > 0) {- safeDuration = fallbackDuration;- } else {- derivedDuration = readContentDerivedDuration();- safeDuration = derivedDuration.seconds ?? 0;- }+ const seconds = resolveCompositionLengthSeconds({+ declared: parseStrictFiniteTimingNumber(+ resolveRootCompositionElement()?.getAttribute("data-duration"),+ ),+ timeline: () => getTimelineDurationSeconds(timeline),+ floors: () => {+ const { media, authoredComposition } = resolveDurationFloors(timingRevision);+ // Deliberately NOT cached: adapters infer their duration from live animation objects+ // (CSS/WAAPI/Lottie), which can change without any DOM mutation to observe.+ return [media, authoredComposition, resolveAdapterDurationFloorSeconds()];+ },+ fallback,+ derived: () => {+ derivedDuration = readContentDerivedDuration();+ return derivedDuration.seconds ?? 0;+ },+ });// The published source describes only a length that was derived; any other source clears it.if (derivedDuration) publishDerivedDuration(derivedDuration);else if (window.__hf?.durationSource) delete window.__hf.durationSource;- return safeDuration > 0 ? Math.max(0, safeDuration) : 0;+ return seconds;};// Sub-composition timelines the runtime nested into the root, by host composition id.@@ -3221,8 +3146,7 @@ export function initSandboxRuntimeModular(): void {// Post resolved stage size so the parent can scale the iframe containerconst stageSizeRootEl = resolveRootCompositionElement();if (stageSizeRootEl) {- const width = parseCompositionDimension(stageSizeRootEl.getAttribute("data-width"));- const height = parseCompositionDimension(stageSizeRootEl.getAttribute("data-height"));+ const { width, height } = readCompositionSize(stageSizeRootEl);if (width !== null && height !== null) {postRuntimeMessage({ source: "hf-preview", type: "stage-size", width, height });}diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonindex 8956a57d01..20b8ada6c2 100644--- a/packages/core/tsconfig.json+++ b/packages/core/tsconfig.json@@ -15,6 +15,7 @@},"files": ["src/runtime/clipTree.ts",+ "src/runtime/compositionLength.ts","src/runtime/customEase.ts","src/runtime/mediaVolumeEnvelope.ts","src/runtime/positionEdits.ts",