diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.ts index ab7227bbb7..0a418c14c7 100644 --- a/packages/core/src/runtime/timeline.test.ts +++ b/packages/core/src/runtime/timeline.test.ts @@ -139,6 +139,36 @@ describe("collectRuntimeTimelinePayload", () => { ]); }); + // fails without the fix: a sealed preview's timeline could not tell a nested composition's own timeline length + // from the one it inherits from its parent, so it showed a row an open preview leaves out. + it("sends a nested composition's own timeline length, and none for one with no timeline", () => { + const root = document.createElement("div"); + root.setAttribute("data-composition-id", "main"); + root.setAttribute("data-duration", "20"); + root.innerHTML = ` +
+ +
+
`; + document.body.appendChild(root); + (window as TimelineTestWindow).__timelines = { + main: { duration: () => 20 }, + intro: { duration: () => 9 }, + outro: { duration: () => 4 }, + }; + + const lengths = collectRuntimeTimelinePayload(defaultParams).clips.map((clip) => [ + clip.id, + clip.duration, + clip.timelineDuration, + ]); + expect(lengths).toEqual([ + ["intro", 10, 9], + ["logo", 7, null], + ["outro", 4, 4], + ]); + }); + it("still lists every clip, with the labels it can read, when one timeline's labels throw", () => { const root = document.createElement("div"); root.setAttribute("data-composition-id", "main"); diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts index f06324c0ab..5d14807420 100644 --- a/packages/core/src/runtime/timeline.ts +++ b/packages/core/src/runtime/timeline.ts @@ -282,6 +282,15 @@ export function collectRuntimeTimelinePayload(params: { const duration = readTimelineDurationSeconds(timelineRegistry[compositionId]); return duration != null && duration > 0 ? duration : null; }; + const ownTimelineLength = (compositionId: string): number | null => { + try { + const length = timelineRegistry[compositionId]?.duration?.(); + return typeof length === "number" && Number.isFinite(length) ? length : null; + } catch (err) { + swallow("runtime.timeline.ownLength", err); + return null; + } + }; const resolveMediaWindowEndSeconds = (): number | null => { const mediaNodes = Array.from( document.querySelectorAll("video[data-start], audio[data-start]"), @@ -508,6 +517,7 @@ export function collectRuntimeTimelinePayload(params: { timelinePriority: parseNum(node.getAttribute("data-timeline-priority")), text: readSentTextLayer(node), transitionLabel: transitionLabels.get(node) ?? null, + timelineDuration: isNestedHost ? ownTimelineLength(nodeCompositionId) : null, }; }; const addClip = (clip: RuntimeTimelineClip) => { @@ -640,6 +650,7 @@ export function collectRuntimeTimelinePayload(params: { timelinePriority: parseNum(el.getAttribute("data-timeline-priority")), text: readSentTextLayer(el), transitionLabel: transitionLabels.get(el) ?? null, + timelineDuration: null, }); gsapClipIds.add(el.id); } @@ -699,6 +710,7 @@ export function collectRuntimeTimelinePayload(params: { timelinePriority: parseNum(el.getAttribute("data-timeline-priority")), text: readSentTextLayer(el), transitionLabel: transitionLabels.get(el) ?? null, + timelineDuration: null, }); gsapClipIds.add(el.id); } diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts index a23b5ea119..50d409b26d 100644 --- a/packages/core/src/runtime/types.ts +++ b/packages/core/src/runtime/types.ts @@ -101,6 +101,7 @@ export type RuntimeTimelineClip = RuntimeTimelineClipIdentity & { timelinePriority: number | null; text: TextLayerRead | null; transitionLabel: string | null; + timelineDuration: number | null; }; export type RuntimeTimelineScene = { diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx index 2e7fb5a0a7..dea7ba859e 100644 --- a/packages/studio/src/hooks/useTimelineEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx @@ -14,6 +14,7 @@ import { parseTimelineFromDOM, } from "../player/lib/timelineDOM"; import type { ClipManifestClip, IframeWindow } from "../player/lib/playbackTypes"; +import { manifestTimelines } from "../player/lib/timelineIframeHelpers"; import { computeResizePreview } from "../player/components/timelineClipDragPreview"; import { buildTimelineGroupResizeMembers, @@ -1537,8 +1538,10 @@ function setupNestedHarness() { const clip = { ...intro, tagName: "div", compositionId: "intro" } as ClipManifestClip; const hostEl = doc.getElementById("intro"); const roots = [createTimelineElementFromManifestClip({ clip, fallbackIndex: 0, doc, hostEl })]; - const win = iframe.contentWindow as IframeWindow; - return buildMissingCompositionElements(doc, win, roots, 20).missing.find( + // A sealed preview's pass reads the timelines from the manifest; HF_PARITY_MODE=sealed runs that one. + const sealed = process.env.HF_PARITY_MODE === "sealed"; + const timelines = sealed ? manifestTimelines([clip]) : (iframe.contentWindow as IframeWindow); + return buildMissingCompositionElements(doc, timelines, roots, 20).missing.find( (e) => e.domId === domId, )!; }; diff --git a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts index 5e37174470..2f2c0ed1d3 100644 --- a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts +++ b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts @@ -52,6 +52,7 @@ function processWith( sync, iframeRef, process: processTimelineMessage, + enrich: () => callbacks!.enrichMissingCompositions(), initialize: () => act(() => initializeAdapter()), load: () => act(() => onIframeLoad()), }; @@ -398,3 +399,94 @@ it("lands a promoted frame's read after the old live player is removed", async ( await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"])); }); + +const NESTED = `
+
+ +
+
`; +const introClip = { ...boxClip, id: "intro", label: "intro", start: 2, duration: 10 }; +const nestedManifest = { + clips: [ + { ...introClip, kind: "composition" as const, compositionId: "intro", timelineDuration: 10 }, + { + ...introClip, + ...{ id: "logo", label: "logo", start: 5, duration: 5, kind: "composition" as const }, + ...{ compositionId: "logo", parentCompositionId: "intro", timelineDuration: 5 }, + }, + ], + durationInFrames: 600, +}; + +// fails without the fix: sealed, the pass that adds a composition nested in a sub-composition read the frame's +// window and never ran, so the nested host had no row; open, it gets one from its timeline's length. +it.each(["unsealed", "sealed"])( + "gives a composition nested in a sub-composition its row, %s", + async (mode) => { + usePlayerStore.getState().setElements([]); + usePlayerStore.getState().setDuration(20); + const sync = vi.fn((els: TimelineElement[]) => usePlayerStore.getState().setElements(els)); + let iframe: HTMLIFrameElement; + if (mode === "sealed") { + document.body.innerHTML = NESTED; + iframe = sealedPreviewFrame().iframe; + } else { + iframe = document.createElement("iframe"); + document.body.append(iframe); + iframe.contentDocument!.body.innerHTML = NESTED; + const logo = { duration: () => 5 }; + Object.assign(iframe.contentWindow!, { + __timelines: { intro: { duration: () => 10 }, logo }, + }); + } + const { process, enrich } = processWith(iframe, null, undefined, sync); + + process(nestedManifest); + enrich(); + + const rows = () => + usePlayerStore.getState().elements.map((r) => `${r.domId}@${r.start}+${r.duration}`); + await vi.waitFor(() => expect(rows()).toEqual(["intro@2+10", "logo@5+5"])); + }, +); + +const NO_LENGTH = NESTED; +const inheritedManifest = { + clips: nestedManifest.clips.map((clip) => + clip.id === "logo" ? { ...clip, duration: 7, timelineDuration: null } : clip, + ), + durationInFrames: 600, +}; + +// fails without the fix: sealed took the length the runtime's clip list inherits for a nested composition with no +// length and no timeline, so it showed a row the open preview leaves out. +it.each(["unsealed", "sealed"])( + "leaves out a nested composition with no length and no timeline, %s", + async (mode) => { + usePlayerStore.getState().setElements([]); + usePlayerStore.getState().setDuration(20); + const sync = vi.fn((els: TimelineElement[]) => usePlayerStore.getState().setElements(els)); + let iframe: HTMLIFrameElement; + if (mode === "sealed") { + document.body.innerHTML = NO_LENGTH; + iframe = sealedPreviewFrame().iframe; + } else { + iframe = document.createElement("iframe"); + document.body.append(iframe); + iframe.contentDocument!.body.innerHTML = NO_LENGTH; + Object.assign(iframe.contentWindow!, { __timelines: { intro: { duration: () => 10 } } }); + } + const { process, enrich } = processWith(iframe, null, undefined, sync); + + process(inheritedManifest); + enrich(); + await vi.waitFor(() => expect(usePlayerStore.getState().elements).not.toHaveLength(0)); + // The channel answers in order: once this later request is back, the timeline read's pass has run. + if (mode === "sealed") await previewClipParents(iframe); + + const rows = usePlayerStore + .getState() + .elements.map((r) => `${r.domId}@${r.start}+${r.duration}`); + expect(rows).toEqual(["intro@2+10"]); + }, +); diff --git a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts index 3c91d25303..d624a11c72 100644 --- a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts +++ b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts @@ -13,7 +13,7 @@ import { liveTime, usePlayerStore } from "../store/playerStore"; import type { TimelineElement } from "../store/playerStore"; import type { PlaybackAdapter, IframeWindow } from "../lib/playbackTypes"; import { readTimelineDurationFromDocument } from "../lib/timelineDOM"; -import { buildMissingCompositionElements } from "../lib/timelineIframeHelpers"; +import { buildMissingCompositionElements, manifestTimelines } from "../lib/timelineIframeHelpers"; import { acceptedRuntimeMessageFps } from "../lib/runtimeProtocol"; import { previewClipParents, previewDocumentCopy, previewFrameOpaque } from "../lib/previewChannel"; import { useLinkedClipPreferences } from "../../utils/linkedClipPreferences"; @@ -205,7 +205,7 @@ export function useTimelineSyncCallbacks({ revision: number, ) => { // A read lands only from the frame on screen, and only over nothing newer. - if (iframe !== onScreen() || !landTimelineRevision(revision)) return; + if (iframe !== onScreen() || !landTimelineRevision(revision)) return false; usePlayerStore.getState().setClipManifest(data.clips); // Show root-level clips: no parentCompositionId, OR parent is a "phantom wrapper" const clipCompositionIds = new Set(data.clips.map((c) => c.compositionId).filter(Boolean)); @@ -250,10 +250,27 @@ export function useTimelineSyncCallbacks({ usePlayerStore.getState().duration, syncTimelineElements, ); + return true; }, [onScreen, syncTimelineElements], ); + const addMissingCompositions = useCallback( + (doc: Document, timelines: Parameters[1]) => { + const { elements, duration } = usePlayerStore.getState(); + const { missing, updatedEls, patched } = buildMissingCompositionElements( + doc, + timelines, + elements, + duration, + ); + if (missing.length === 0 && !patched) return; + const finalIds = new Set(updatedEls.map((e) => e.id)); + syncTimelineElements([...updatedEls, ...missing.filter((m) => !finalIds.has(m.id))]); + }, + [syncTimelineElements], + ); + // A sealed frame's rows bind to its document copy and clip tree from the editing port. const readSealedTimeline = useCallback( (iframe, manifest, previewDuration) => { @@ -261,12 +278,13 @@ export function useTimelineSyncCallbacks({ void Promise.all([manifest, previewDocumentCopy(iframe), previewClipParents(iframe)]).then( ([data, doc, parents]) => { // A frame its player removed is gone: callback refs keep it (promotion repoints them), the page does not. - if (data && iframe.isConnected) - applyTimelineMessage(data, doc, parents, iframe, previewDuration, revision); + if (!data || !iframe.isConnected) return; + if (applyTimelineMessage(data, doc, parents, iframe, previewDuration, revision) && doc) + addMissingCompositions(doc, manifestTimelines(data.clips)); }, ); }, - [applyTimelineMessage], + [applyTimelineMessage, addMissingCompositions], ); const processTimelineMessage = useCallback( @@ -288,25 +306,9 @@ export function useTimelineSyncCallbacks({ const iframe = iframeRef.current; const doc = iframe?.contentDocument; const iframeWin = iframe?.contentWindow as IframeWindow | null; - if (!doc || !iframeWin) return; - - const currentEls = usePlayerStore.getState().elements; - const rootDuration = usePlayerStore.getState().duration; - const { missing, updatedEls, patched } = buildMissingCompositionElements( - doc, - iframeWin, - currentEls, - rootDuration, - ); - - if (missing.length > 0 || patched) { - // Dedup: ensure no missing element duplicates an existing one - const finalIds = new Set(updatedEls.map((e) => e.id)); - const dedupedMissing = missing.filter((m) => !finalIds.has(m.id)); - syncTimelineElements([...updatedEls, ...dedupedMissing]); - } + if (doc && iframeWin) addMissingCompositions(doc, iframeWin); } catch {} - }, [iframeRef, syncTimelineElements]); + }, [iframeRef, addMissingCompositions]); const initializeAdapter = useCallback( (context?: number) => { diff --git a/packages/studio/src/player/lib/manifestClips.ts b/packages/studio/src/player/lib/manifestClips.ts index 645a61b349..ba868a4e52 100644 --- a/packages/studio/src/player/lib/manifestClips.ts +++ b/packages/studio/src/player/lib/manifestClips.ts @@ -28,7 +28,7 @@ const stringsOnly = (fields: Record): boolean => (ancestor) => typeof ancestor === "string" && boundedId(ancestor), ))); -const OPTIONAL_NUMBERS = ["zIndex", "playbackStart", "playbackRate"] as const; +const OPTIONAL_NUMBERS = ["zIndex", "playbackStart", "playbackRate", "timelineDuration"] as const; export const clipNumber = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) ? value : null; diff --git a/packages/studio/src/player/lib/playbackTypes.ts b/packages/studio/src/player/lib/playbackTypes.ts index b7bd51ad2f..8a37e8d14c 100644 --- a/packages/studio/src/player/lib/playbackTypes.ts +++ b/packages/studio/src/player/lib/playbackTypes.ts @@ -48,6 +48,7 @@ export interface ClipManifestClip extends RuntimeTimelineClipIdentity { playbackStart?: number; playbackRate?: number; transitionLabel?: string; + timelineDuration?: number | null; } export interface ClipManifest { diff --git a/packages/studio/src/player/lib/timelineIframeHelpers.ts b/packages/studio/src/player/lib/timelineIframeHelpers.ts index befddaaab4..29a3e6b9d2 100644 --- a/packages/studio/src/player/lib/timelineIframeHelpers.ts +++ b/packages/studio/src/player/lib/timelineIframeHelpers.ts @@ -11,7 +11,7 @@ */ import type { TimelineElement } from "../store/playerStore"; -import type { IframeWindow } from "./playbackTypes"; +import type { ClipManifestClip, TimelineLike } from "./playbackTypes"; import { readClipTiming } from "@hyperframes/core/composition-contract"; import { createRuntimeStartTimeResolver } from "@hyperframes/core/runtime/start-resolver"; import { @@ -249,7 +249,24 @@ export function stopScrubPreviewAudio(): void { // Enrich missing compositions from DOM // --------------------------------------------------------------------------- -function timelineDuration(iframeWin: IframeWindow, compositionId: string): number { +type TimelineRegistry = { + __timelines?: Record>; +}; + +/** A sealed frame's timelines for the missing-host pass, from each composition clip's own timeline length; + * 0 where it has none, which every reader takes as no length, as it does a missing timeline. */ +export function manifestTimelines(clips: readonly ClipManifestClip[]): TimelineRegistry { + const timelines: Record> = {}; + for (const clip of clips) { + if (!clip.compositionId) continue; + const labels = clip.transitionLabel ? { [clip.transitionLabel]: 0 } : {}; + const length = clip.timelineDuration ?? 0; + timelines[clip.compositionId] = { duration: () => length, getLabels: () => labels }; + } + return { __timelines: timelines }; +} + +function timelineDuration(iframeWin: TimelineRegistry, compositionId: string): number { return ( ( iframeWin.__timelines?.[compositionId] as { duration?: () => number } | undefined @@ -273,7 +290,7 @@ function createTimedElementLookup(doc: Document): Map { function createReferenceEndResolver( timedById: ReadonlyMap, - iframeWin: IframeWindow, + iframeWin: TimelineRegistry, ): (refId: string, visiting: ReadonlySet) => number | null { const resolveEnd = (refId: string, visiting: ReadonlySet): number | null => { if (visiting.has(refId)) return null; @@ -327,7 +344,7 @@ function attachCompositionSource( function buildMissingCompositionEntry(params: { doc: Document; - iframeWin: IframeWindow; + iframeWin: TimelineRegistry; element: HTMLElement; compositionId: string; rootDuration: number; @@ -402,7 +419,7 @@ function buildMissingCompositionEntry(params: { */ export function buildMissingCompositionElements( doc: Document, - iframeWin: IframeWindow, + iframeWin: TimelineRegistry, currentEls: readonly TimelineElement[], rootDuration: number, ): { missing: TimelineElement[]; updatedEls: TimelineElement[]; patched: boolean } {