Skip to content

Commit fa44d76

Browse files
feat(core): a composition with no authored length takes it from its clips (#4174)
* feat(core): a composition with no authored length takes it from its clips A new resolver in @hyperframes/parsers returns a composition length as authored, derived from its latest clip end, or unresolved, and counts clips whose length is still pending. The runtime uses it in its two existing max-end loops with identical results, and as a last resort only when no timeline, floor or caller length exists, so a composition that has a length today keeps it. The derived source is published on window.__hf.durationSource for render telemetry. Lint reports a root that has timed clips but no data-duration as a warning that says where to author it, and still errors when there is nothing to derive from. * refactor(core): resolve the runtime duration floor in one call The declared duration and sub-composition ends were resolved separately and maxed by hand; one resolver call over both gives the same latest end. * fix(core): a derived composition length waits for every clip length and reports honestly Review follow-up. The runtime returns a content-derived length only when no clip is still pending, so a renderer that reads duration once cannot lock in a short one. window.__hf.durationSource is cleared whenever a timeline or floor supplies the length, and the diagnostic fires only for a derived length. Lint says "at least Ns", counts reference-start clips as known only at runtime, and ignores a data-end before data-start. * fix(core): a sub-composition with no known length counts as pending A host whose own timeline is not registered yet no longer lets the content-derived length show early. Tests pin the pending host and that the diagnostic fires only for a derived length. * fix(core): a loaded Lottie with no registered animation keeps the length pending Lottie registers from author scripts with no DOM marker, and nothing re-derives the length after it registers. A composition with clips and a loaded Lottie library therefore stays at zero, as before, instead of locking in the clips length and cutting the animation short. * test(core): a registered Lottie supplies the length and the clips length is not used Pins the other side of the pending Lottie rule. Once an animation reports a length it enters the duration floor, so the content-derived fallback is never consulted. * test(core): the declared and DotLottie pending branches are covered
1 parent ac0d8ce commit fa44d76

13 files changed

Lines changed: 451 additions & 12 deletions

File tree

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

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3122,6 +3122,126 @@ describe("initSandboxRuntimeModular", () => {
31223122
delete (window as Window & { __hfLottie?: unknown[] }).__hfLottie;
31233123
});
31243124

3125+
describe("a root with no data-duration and no timeline takes its length from its clips", () => {
3126+
const mountRoot = (children: string) => {
3127+
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-start="0" data-width="1920" data-height="1080">${children}</div>`;
3128+
window.__timelines = {};
3129+
initSandboxRuntimeModular();
3130+
};
3131+
3132+
it("counts a timed image at the dropped-image default and reports the derived source", () => {
3133+
mountRoot('<img id="a" data-start="2" src="a.png" />');
3134+
expect(window.__player?.getDuration()).toBe(5);
3135+
expect(window.__hf?.durationSource).toEqual({
3136+
source: "derived",
3137+
seconds: 5,
3138+
pendingClips: 0,
3139+
});
3140+
});
3141+
3142+
it("counts a plain clip with data-start and data-duration", () => {
3143+
mountRoot('<div class="clip" data-start="1" data-duration="4"></div>');
3144+
expect(window.__player?.getDuration()).toBe(5);
3145+
});
3146+
3147+
it("stays at zero while a video's length is pending, so a renderer never locks in a short one", () => {
3148+
mountRoot(
3149+
'<div class="clip" data-start="0" data-duration="2"></div><video data-start="0"></video>',
3150+
);
3151+
expect(window.__player?.getDuration()).toBe(0);
3152+
expect(window.__hf?.durationSource).toEqual({
3153+
source: "unresolved",
3154+
seconds: null,
3155+
pendingClips: 1,
3156+
});
3157+
});
3158+
3159+
it("stays at zero while a sub-composition's own length is not known yet", () => {
3160+
mountRoot(
3161+
'<div class="clip" data-start="0" data-duration="2"></div><div data-composition-id="sub" data-start="0"></div>',
3162+
);
3163+
expect(window.__player?.getDuration()).toBe(0);
3164+
expect(window.__hf?.durationSource?.pendingClips).toBe(1);
3165+
});
3166+
3167+
it("stays at zero while a loaded Lottie has registered no animation, instead of locking in the clip's length", () => {
3168+
const lottieWindow = window as Window & { lottie?: unknown };
3169+
lottieWindow.lottie = { getRegisteredAnimations: () => [] };
3170+
try {
3171+
mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');
3172+
expect(window.__player?.getDuration()).toBe(0);
3173+
expect(window.__hf?.durationSource).toEqual({
3174+
source: "unresolved",
3175+
seconds: null,
3176+
pendingClips: 1,
3177+
});
3178+
} finally {
3179+
delete lottieWindow.lottie;
3180+
}
3181+
});
3182+
3183+
it("treats a declared data-lottie-src or a loaded DotLottie as a pending clip too", () => {
3184+
mountRoot(
3185+
'<div class="clip" data-start="0" data-duration="2"></div><div data-lottie-src="a.json"></div>',
3186+
);
3187+
expect(window.__player?.getDuration()).toBe(0);
3188+
const dotLottieWindow = window as Window & { DotLottie?: unknown };
3189+
dotLottieWindow.DotLottie = class {};
3190+
try {
3191+
mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');
3192+
expect(window.__hf?.durationSource?.pendingClips).toBe(1);
3193+
} finally {
3194+
delete dotLottieWindow.DotLottie;
3195+
}
3196+
});
3197+
3198+
it("uses the Lottie's own length once it is registered, not the clips' length", () => {
3199+
const lottieWindow = window as Window & { lottie?: unknown; __hfLottie?: unknown[] };
3200+
lottieWindow.lottie = { getRegisteredAnimations: () => [] };
3201+
lottieWindow.__hfLottie = [
3202+
{ play: () => {}, pause: () => {}, totalFrames: 150, frameRate: 30 },
3203+
];
3204+
try {
3205+
mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');
3206+
expect(window.__player?.getDuration()).toBe(5);
3207+
expect(window.__hf?.durationSource).toBeUndefined();
3208+
} finally {
3209+
delete lottieWindow.lottie;
3210+
delete lottieWindow.__hfLottie;
3211+
}
3212+
});
3213+
3214+
it("posts the derived-length diagnostic only for a derived length", () => {
3215+
const spy = vi.spyOn(window, "postMessage");
3216+
const codes = () =>
3217+
spy.mock.calls
3218+
.map(([message]) => (message as { code?: string } | undefined)?.code)
3219+
.filter((code) => code === "composition_duration_derived");
3220+
mountRoot("<p>static</p>");
3221+
expect(codes()).toHaveLength(0);
3222+
mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');
3223+
expect(codes()).toHaveLength(1);
3224+
});
3225+
3226+
it("reports no derived source when a timeline supplies the length", () => {
3227+
mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');
3228+
expect(window.__hf?.durationSource?.source).toBe("derived");
3229+
document.body.innerHTML = "";
3230+
window.__timelines = {};
3231+
document.body.innerHTML =
3232+
'<div data-composition-id="main" data-root="true" data-start="0" data-duration="8"></div>';
3233+
initSandboxRuntimeModular();
3234+
expect(window.__player?.getDuration()).toBe(8);
3235+
expect(window.__hf?.durationSource).toBeUndefined();
3236+
});
3237+
3238+
it("stays at zero, reported unresolved, when there is no timed content", () => {
3239+
mountRoot("<p>static</p>");
3240+
expect(window.__player?.getDuration()).toBe(0);
3241+
expect(window.__hf?.durationSource?.source).toBe("unresolved");
3242+
});
3243+
});
3244+
31253245
it("regression: a GSAP timeline's duration is unaffected by adapter duration inference", () => {
31263246
// A GSAP composition can legitimately have an incidental, short CSS
31273247
// animation running alongside the timeline (e.g. a decorative shimmer).

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

Lines changed: 108 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import { createPickerModule } from "./picker";
3737
import { createRuntimePlayer, type RuntimePlayerTransport } from "./player";
3838
import { createRuntimeState } from "./state";
3939
import { collectRuntimeTimelinePayload } from "./timeline";
40+
import { resolveCompositionDuration } from "@hyperframes/parsers/composition-duration";
4041
import { createRuntimeStartTimeResolver } from "./startResolver";
4142
import { createClipTree } from "./clipTree";
4243
import { loadExternalCompositions, loadInlineTemplateCompositions } from "./compositionLoader";
@@ -920,15 +921,19 @@ export function initSandboxRuntimeModular(): void {
920921
// this every tick, and it should not pay for a resolver it never uses.
921922
if (mediaNodes.length === 0) return null;
922923
return withTimingResolver(() => {
923-
let maxWindowEndSeconds = 0;
924+
const clipEnds: number[] = [];
924925
for (const node of mediaNodes) {
925926
const start = resolveAbsoluteMediaStartSeconds(node);
926927
if (!Number.isFinite(start)) continue;
927928
const duration = resolveMediaElementDurationSeconds(node);
928929
if (duration == null || duration <= MIN_VALID_TIMELINE_DURATION_SECONDS) continue;
929-
maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);
930+
clipEnds.push(Math.max(0, start) + duration);
930931
}
931-
return maxWindowEndSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxWindowEndSeconds : null;
932+
const { seconds } = resolveCompositionDuration({
933+
authoredDurationSeconds: null,
934+
clipEndsSeconds: clipEnds,
935+
});
936+
return seconds !== null && seconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? seconds : null;
932937
});
933938
};
934939

@@ -940,16 +945,13 @@ export function initSandboxRuntimeModular(): void {
940945
timelineRegistry: timelines,
941946
includeAuthoredTimingAttrs: true,
942947
});
943-
let maxWindowEndSeconds = 0;
944948
// The root's own data-duration is the authored source of truth for
945949
// composition length. Without it in the floor, a GSAP timeline that ends
946950
// even slightly short of the declared duration shrinks the playable
947951
// window — and duration-gated consumers (e.g. the studio's adapter
948952
// selection) silently reject the runtime player, losing audio playback.
949953
const rootDeclaredSeconds = parseStrictFiniteTimingNumber(rootEl.getAttribute("data-duration"));
950-
if (rootDeclaredSeconds != null && rootDeclaredSeconds > 0) {
951-
maxWindowEndSeconds = rootDeclaredSeconds;
952-
}
954+
const subCompositionEnds: number[] = [];
953955
const compositionNodes = Array.from(
954956
rootEl.querySelectorAll("[data-composition-id][data-start]"),
955957
);
@@ -960,9 +962,98 @@ export function initSandboxRuntimeModular(): void {
960962
const start = startResolver.resolveStartForElement(node, 0);
961963
const duration = startResolver.resolveDurationForElement(node);
962964
if (!Number.isFinite(start) || duration == null || duration <= 0) continue;
963-
maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);
965+
subCompositionEnds.push(Math.max(0, start) + duration);
964966
}
965-
return maxWindowEndSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxWindowEndSeconds : null;
967+
// A floor, not a resolution: the declared duration and every sub-composition end all hold,
968+
// so the latest of them is the floor.
969+
const { seconds: floorSeconds } = resolveCompositionDuration({
970+
authoredDurationSeconds: null,
971+
clipEndsSeconds: [rootDeclaredSeconds, ...subCompositionEnds],
972+
});
973+
return floorSeconds !== null && floorSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS
974+
? floorSeconds
975+
: null;
976+
};
977+
978+
/** The last-resort length: the latest end among the root's timed clips, used only when no
979+
* timeline, floor or caller-supplied length exists. Pending media is counted, not guessed. */
980+
// A sub-composition's length comes from its own timeline, which may not be registered yet.
981+
const isCompositionHost = (node: Element): boolean =>
982+
node.hasAttribute("data-composition-id") || node.hasAttribute("data-composition-src");
983+
// Lottie registers its animations from author scripts, often after the runtime is ready, and
984+
// nothing in the DOM says when. A loaded Lottie library or a declared source means a length
985+
// that has not been registered yet, so it counts as a pending clip like media does.
986+
const hasUnregisteredLottie = (rootEl: Element): boolean => {
987+
const lottieWindow = window as Window & { lottie?: unknown; DotLottie?: unknown };
988+
return Boolean(
989+
lottieWindow.lottie || lottieWindow.DotLottie || rootEl.querySelector("[data-lottie-src]"),
990+
);
991+
};
992+
const resolveContentDerivedDuration = () => {
993+
const rootEl = resolveRootCompositionElement();
994+
if (!rootEl)
995+
return resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: [] });
996+
const startResolver = createRuntimeStartTimeResolver({
997+
timelineRegistry: (window.__timelines ?? {}) as Record<
998+
string,
999+
RuntimeTimelineLike | undefined
1000+
>,
1001+
includeAuthoredTimingAttrs: true,
1002+
});
1003+
const clipEnds: Array<number | null> = [];
1004+
for (const node of Array.from(rootEl.querySelectorAll("[data-start]"))) {
1005+
if (!isElementNode(node)) continue;
1006+
const start = startResolver.resolveStartForElement(node, 0);
1007+
if (!Number.isFinite(start)) continue;
1008+
const duration = startResolver.resolveDurationForElement(node);
1009+
if (duration != null) clipEnds.push(Math.max(0, start) + duration);
1010+
else if (isMediaElement(node) || isCompositionHost(node)) clipEnds.push(null);
1011+
}
1012+
if (hasUnregisteredLottie(rootEl)) clipEnds.push(null);
1013+
const result = resolveCompositionDuration({
1014+
authoredDurationSeconds: null,
1015+
clipEndsSeconds: clipEnds,
1016+
});
1017+
// A length that a pending clip can still extend is not final, and a renderer that reads the
1018+
// duration once would lock the short one in: stay at zero until every clip's length is known.
1019+
return result.pendingClips > 0
1020+
? {
1021+
...result,
1022+
seconds: null,
1023+
source: "unresolved" as const,
1024+
reason: "a clip's length is pending",
1025+
}
1026+
: result;
1027+
};
1028+
1029+
let contentDerivedCache: {
1030+
revision: number;
1031+
result: ReturnType<typeof resolveContentDerivedDuration>;
1032+
} | null = null;
1033+
/** Cached per timing revision like the floors; the render path never reads a cache. */
1034+
const readContentDerivedDuration = () => {
1035+
if (renderCaptureSeekStarted) return resolveContentDerivedDuration();
1036+
const revision = readCompositionTimingRevision();
1037+
if (contentDerivedCache?.revision !== revision) {
1038+
contentDerivedCache = { revision, result: resolveContentDerivedDuration() };
1039+
}
1040+
return contentDerivedCache.result;
1041+
};
1042+
1043+
/** Carries how a length that no timeline supplied was found, for render telemetry. */
1044+
const publishDerivedDuration = (result: ReturnType<typeof resolveCompositionDuration>) => {
1045+
window.__hf = window.__hf || {};
1046+
window.__hf.durationSource = {
1047+
source: result.source,
1048+
seconds: result.seconds,
1049+
pendingClips: result.pendingClips,
1050+
};
1051+
if (result.source !== "derived") return;
1052+
postRuntimeDiagnosticOnce(
1053+
"composition_duration_derived",
1054+
{ source: result.source, seconds: result.seconds, pendingClips: result.pendingClips },
1055+
`composition_duration_derived:${result.seconds}`,
1056+
);
9661057
};
9671058

9681059
const resolveMediaDurationFloorSeconds = (): number | null => {
@@ -1217,14 +1308,21 @@ export function initSandboxRuntimeModular(): void {
12171308
const fallbackDuration =
12181309
Number.isFinite(fallback) && fallback > MIN_VALID_TIMELINE_DURATION_SECONDS ? fallback : 0;
12191310
let safeDuration = 0;
1311+
let derivedDuration: ReturnType<typeof resolveContentDerivedDuration> | null = null;
12201312
// Timeline is the source of truth for authored composition duration.
12211313
if (isUsableTimelineDuration(timelineDuration)) {
12221314
safeDuration = Math.max(timelineDuration, durationFloor, fallbackDuration);
12231315
} else if (isUsableTimelineDuration(durationFloor)) {
12241316
safeDuration = Math.max(durationFloor, fallbackDuration);
1225-
} else {
1317+
} else if (fallbackDuration > 0) {
12261318
safeDuration = fallbackDuration;
1319+
} else {
1320+
derivedDuration = readContentDerivedDuration();
1321+
safeDuration = derivedDuration.seconds ?? 0;
12271322
}
1323+
// The published source describes only a length that was derived; any other source clears it.
1324+
if (derivedDuration) publishDerivedDuration(derivedDuration);
1325+
else if (window.__hf?.durationSource) delete window.__hf.durationSource;
12281326
return safeDuration > 0 ? Math.max(0, safeDuration) : 0;
12291327
};
12301328

‎packages/core/src/runtime/window.d.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ declare global {
4646
onSwallowed?: (label: string, err: unknown) => void;
4747
seek?: (timeSeconds: number, options?: RuntimeSeekOptions) => void;
4848
duration?: number;
49+
/** How a length that no timeline supplied was found: the render telemetry reads this. */
50+
durationSource?: {
51+
source: "authored" | "derived" | "unresolved";
52+
seconds: number | null;
53+
pendingClips: number;
54+
};
4955
/** Borrow an element's playback while the transport clock is paused, so the
5056
* runtime's paused-side enforcement leaves it alone. Always release. */
5157
leasePausedMedia?: (el: HTMLMediaElement) => void;

‎packages/lint/src/rules/composition.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,6 +1639,55 @@ describe("composition rules", () => {
16391639
expect(finding?.severity).toBe("error");
16401640
});
16411641

1642+
it("warns, and says where to author the length, when timed clips give the root a length", async () => {
1643+
const html = `<html><body>
1644+
<div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">
1645+
<img src="a.png" data-start="2" />
1646+
<div class="clip" data-start="0" data-duration="6"></div>
1647+
</div>
1648+
</body></html>`;
1649+
const result = await lintHyperframeHtml(html);
1650+
expect(find(result.findings)).toBeUndefined();
1651+
const derived = result.findings.find((f) => f.code === "root_composition_duration_derived");
1652+
expect(derived?.severity).toBe("warning");
1653+
expect(derived?.message).toContain("at least 6s");
1654+
expect(derived?.fixHint).toContain("data-duration");
1655+
});
1656+
1657+
it("counts a clip with a reference start or a video with no length as known only at runtime", async () => {
1658+
const html = `<html><body>
1659+
<div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">
1660+
<img src="a.png" data-start="0" />
1661+
<video src="v.mp4" data-start="0"></video>
1662+
<div class="clip" data-start="a+1" data-duration="2"></div>
1663+
</div>
1664+
</body></html>`;
1665+
const result = await lintHyperframeHtml(html);
1666+
const derived = result.findings.find((f) => f.code === "root_composition_duration_derived");
1667+
expect(derived?.message).toContain("at least 3s");
1668+
expect(derived?.message).toContain("2 clip(s) whose length is only known at runtime");
1669+
});
1670+
1671+
it("does not count a clip whose data-end is before its start", async () => {
1672+
const html = `<html><body>
1673+
<div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">
1674+
<div class="clip" data-start="5" data-end="3"></div>
1675+
</div>
1676+
</body></html>`;
1677+
const result = await lintHyperframeHtml(html);
1678+
expect(find(result.findings)?.severity).toBe("error");
1679+
});
1680+
1681+
it("still errors when the only clips have no length to derive from", async () => {
1682+
const html = `<html><body>
1683+
<div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">
1684+
<div class="clip" data-start="0"></div>
1685+
</div>
1686+
</body></html>`;
1687+
const result = await lintHyperframeHtml(html);
1688+
expect(find(result.findings)?.severity).toBe("error");
1689+
});
1690+
16421691
it("does not error when data-duration is declared on the root", async () => {
16431692
const html = `<html><body>
16441693
<div data-composition-id="main" data-start="0" data-duration="6" data-width="1920" data-height="1080">

0 commit comments

Comments
 (0)