fix(studio): show a sealed composition's clip on the timeline (#8408)

* fix(studio): show a sealed composition's clip on the timeline

* fix(studio): keep a sealed load's clip bound to its own preview and length

* fix(studio): an older preview read never replaces a newer timeline

* fix(studio): only the preview on screen writes the timeline

* fix(studio): a removed preview frame's pending read writes nothing
This commit is contained in:
Miguel Ángel
2026-11-22 02:04:37 +00:00
committed by GitHub
parent 0495a57f76
commit 28502224a5
8 changed files with 421 additions and 43 deletions
@@ -156,6 +156,7 @@ describe("hydrateTimelineFromPreview", () => {
iframe,
adapter: { getDuration: () => 1 } as unknown as PlaybackAdapter,
processTimelineMessage: vi.fn(),
readSealedTimeline: vi.fn(),
enrichMissingCompositions: vi.fn(),
applyPreviewAudioState: vi.fn(),
attachIframeShortcutListeners,
@@ -30,6 +30,7 @@ import {
normalizePreviewViewport,
} from "../lib/timelineIframeHelpers";
import { inspectStudioRuntimeMessage } from "../lib/runtimeProtocol";
import { previewClipManifest, previewFrameOpaque } from "../lib/previewChannel";
/** Reject non-finite, non-positive, and absurdly large (loop-inflated) values. */
export function sanitizeDurationSeconds(value: number): number {
@@ -342,19 +343,15 @@ export function syncAdapterDuration(
* Without it a composition the runtime never enumerated shows an empty timeline
* rather than one row spanning its own duration.
*/
function syncFallbackTimelineFromDom(
export function fallbackTimelineFromDom(
doc: Document,
iframe: HTMLIFrameElement | null,
rootDuration: number,
syncTimelineElements: (els: TimelineElement[], duration?: number) => void,
): void {
): TimelineElement[] {
const els = parseTimelineFromDOM(doc, rootDuration);
if (els.length > 0) {
syncTimelineElements(els);
return;
}
if (els.length > 0) return els;
const rootComp = doc.querySelector("[data-composition-id]");
if (!rootComp || rootDuration <= 0) return;
if (!rootComp || rootDuration <= 0) return [];
const fallbackElement = buildStandaloneRootTimelineElement({
compositionId: rootComp.getAttribute("data-composition-id") || "composition",
tagName: (rootComp as HTMLElement).tagName || "div",
@@ -362,7 +359,7 @@ function syncFallbackTimelineFromDom(
iframeSrc: iframe?.src || "",
selector: getTimelineElementSelector(rootComp),
});
if (fallbackElement) syncTimelineElements([fallbackElement]);
return fallbackElement ? [fallbackElement] : [];
}
/** The runtime's timeline message, as the preview posts it. */
@@ -400,10 +397,18 @@ export function isPreviewReadinessMessage(
return inspectStudioRuntimeMessage(data).status !== "unsupported";
}
/** Reads a sealed frame's rows for a clip list still on its way; `null` from it commits nothing. */
export type SealedTimelineRead = (
iframe: HTMLIFrameElement,
manifest: Promise<RuntimeTimelineMessage | null>,
previewDuration: number,
) => void;
export interface HydrateTimelineFromPreviewInput {
iframe: HTMLIFrameElement | null;
adapter: PlaybackAdapter;
processTimelineMessage: (manifest: RuntimeTimelineMessage) => void;
readSealedTimeline: SealedTimelineRead;
enrichMissingCompositions: () => void;
applyPreviewAudioState: () => void;
attachIframeShortcutListeners: () => void;
@@ -426,12 +431,20 @@ function normalizePreviewDom(doc: Document | null, iframeWin: IframeWindow | nul
}
/** Hand the runtime's own clip manifest to the timeline, if it published one. */
function applyRuntimeClipManifest(
iframeWin: IframeWindow | null,
processTimelineMessage: (manifest: RuntimeTimelineMessage) => void,
): void {
const manifest = iframeWin?.__clipManifest;
if (manifest && manifest.clips.length > 0) processTimelineMessage(manifest);
function applyRuntimeClipManifest(input: HydrateTimelineFromPreviewInput): void {
const { iframe, adapter } = input;
if (iframe && previewFrameOpaque(iframe)) {
// The frame's own clip list decides, empty included; with none posted yet, only an empty timeline falls back.
const manifest = previewClipManifest(iframe).then((found) =>
found || usePlayerStore.getState().elements.length > 0
? found
: { clips: [], durationInFrames: 0 },
);
input.readSealedTimeline(iframe, manifest, adapter.getDuration());
return;
}
const manifest = (iframe?.contentWindow as IframeWindow | null)?.__clipManifest;
if (manifest) input.processTimelineMessage(manifest);
}
export function hydrateTimelineFromPreview(input: HydrateTimelineFromPreviewInput): void {
@@ -441,11 +454,12 @@ export function hydrateTimelineFromPreview(input: HydrateTimelineFromPreviewInpu
const iframeWin = (iframe?.contentWindow as IframeWindow | null) ?? null;
normalizePreviewDom(doc, iframeWin);
input.attachIframeShortcutListeners();
applyRuntimeClipManifest(iframeWin, input.processTimelineMessage);
applyRuntimeClipManifest(input);
input.enrichMissingCompositions();
input.applyPreviewAudioState();
if (doc && usePlayerStore.getState().elements.length === 0) {
syncFallbackTimelineFromDom(doc, iframe, adapter.getDuration(), syncTimelineElements);
const els = fallbackTimelineFromDom(doc, iframe, adapter.getDuration());
if (els.length > 0) syncTimelineElements(els);
}
} catch {
// Cross-origin or mid-navigation preview — the adapter is still initialised.
@@ -336,6 +336,7 @@ export function useShadowPreviewReload({
const getShadowAdapter = useCallback(() => getAdapter(shadowIframeRef.current), [getAdapter]);
const isCurrentShadow = useCallback((gen?: number) => gen === shadowGenRef.current, []);
const liveFrame = useCallback(() => iframeRef.current, [iframeRef]);
const previewGeneration = useCallback(() => shadowGenRef.current, []);
const markAdapterReady = useCallback(
(iframe: HTMLIFrameElement | null, gen: number | undefined, commit: () => void) => {
@@ -370,6 +371,7 @@ export function useShadowPreviewReload({
onAdapterReady: markAdapterReady,
isCurrent: isCurrentShadow,
hostOwnsDeadline: true,
liveFrame,
});
cancelPendingLoadRef.current = cancelPendingLoad;
@@ -42,6 +42,7 @@ function reloadedFilm() {
const { win } = makeAdapterWindow({ duration: 2 });
const frame = win as unknown as Record<string, unknown>;
const iframe = detachedFakeIframe(frame);
Object.defineProperty(iframe, "isConnected", { value: true });
iframe.contentDocument!.body.innerHTML = FILM;
frame.__clipManifest = RELOADED;
const markup = {
@@ -4,8 +4,11 @@ import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, expect, it, onTestFinished, vi } from "vitest";
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
import type { PlaybackAdapter } from "../lib/playbackTypes";
import { useTimelineSyncCallbacks } from "./useTimelineSyncCallbacks";
import { sealedPreviewFrame } from "../lib/sealedPreviewFrame.test-helpers";
import { previewClipParents, previewDocumentCopy } from "../lib/previewChannel";
import { detachedFakeIframe } from "./timelinePlayerTestHarness";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -13,16 +16,22 @@ afterEach(() => {
document.body.innerHTML = "";
});
function processWith(iframe: HTMLIFrameElement) {
const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>();
function processWith(
iframe: HTMLIFrameElement,
adapter: PlaybackAdapter | null = null,
isCurrent?: () => boolean,
sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(),
liveFrame?: () => HTMLIFrameElement | null,
) {
let callbacks: ReturnType<typeof useTimelineSyncCallbacks> | undefined;
const iframeRef: { current: HTMLIFrameElement | null } = { current: iframe };
function Harness() {
callbacks = useTimelineSyncCallbacks({
iframeRef: { current: iframe },
iframeRef,
probeIntervalRef: { current: undefined },
pendingSeekRef: { current: null },
isRefreshingRef: { current: false },
getAdapter: () => null,
getAdapter: () => adapter,
syncTimelineElements: sync,
setDuration: () => {},
setCurrentTime: () => {},
@@ -30,12 +39,22 @@ function processWith(iframe: HTMLIFrameElement) {
setIsPlaying: () => {},
attachIframeShortcutListeners: () => {},
applyPreviewAudioState: () => {},
onAdapterReady: (_iframe, _context, commit) => commit(),
isCurrent,
liveFrame,
});
return null;
}
const host = document.createElement("div");
act(() => createRoot(host).render(createElement(Harness)));
return { sync, process: callbacks!.processTimelineMessage };
const { processTimelineMessage, initializeAdapter, onIframeLoad } = callbacks!;
return {
sync,
iframeRef,
process: processTimelineMessage,
initialize: () => act(() => initializeAdapter()),
load: () => act(() => onIframeLoad()),
};
}
const boxClip = {
@@ -104,3 +123,278 @@ it("fills a sealed scene's children and the runtime's clip parents", async () =>
await vi.waitFor(() => expect(usePlayerStore.getState().clipParentMap.get("cue")).toBe("scene"));
expect(usePlayerStore.getState().domClipChildren.map((child) => child.id)).toContain("title");
});
const rootOnly = `<section id="scene5-root" data-composition-id="scene5" data-duration="5">
<h1>Scene 6</h1>
</section>`;
const adapterOf = (duration: number): PlaybackAdapter => ({
pause() {},
seek() {},
play() {},
getTime: () => 0,
getDuration: () => duration,
isPlaying: () => false,
});
function rootRow(sync: ReturnType<typeof processWith>["sync"]) {
return sync.mock.calls.at(-1)?.[0].map((row) => `${row.id}@${row.start}+${row.duration}`);
}
// fails without the fix: an empty clip list from a sealed frame committed no rows, so the composition had no clip.
it("shows a sealed composition the runtime lists no clips for as its own row", async () => {
document.body.innerHTML = rootOnly;
const { sync, process } = processWith(sealedPreviewFrame().iframe);
process({ clips: [], durationInFrames: 0 });
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"]));
});
// fails without the fix: reading the sealed frame's manifest threw, so loading it ended with no clip.
it("gives a sealed composition its row when the preview loads", async () => {
document.body.innerHTML = rootOnly;
usePlayerStore.getState().setElements([]);
const { sync, initialize } = processWith(sealedPreviewFrame().iframe, adapterOf(5));
initialize();
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"]));
});
// fails without the fix: the reply was read against the frame ref, which a shadow promotion has already cleared.
it("keeps a sealed load's row when its frame is promoted before the reply", async () => {
document.body.innerHTML = rootOnly;
usePlayerStore.getState().setElements([]);
const promoted = sealedPreviewFrame().iframe;
// The shadow's own ref lets go at promotion; the live ref, the one on screen, now holds its frame.
const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>();
const shadow = processWith(
promoted,
adapterOf(5),
() => true,
sync,
() => promoted,
);
shadow.initialize();
shadow.iframeRef.current = null;
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"]));
});
// fails without the fix: the previous preview's late reply replaced the rows of the preview loaded after it.
it("drops a sealed load's reply that arrives after the next preview loaded", async () => {
document.body.innerHTML = rootOnly;
(window as unknown as { __clipManifest: unknown }).__clipManifest = {
clips: [{ ...boxClip, id: "stale" }],
durationInFrames: 60,
};
onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest);
usePlayerStore.getState().setElements([]);
const sealed = sealedPreviewFrame().iframe;
const { sync, iframeRef, initialize, load } = processWith(sealed, adapterOf(5));
initialize();
iframeRef.current = detachedFakeIframe({
__clipManifest: { clips: [{ ...boxClip, id: "next" }], durationInFrames: 60 },
scrollTo() {},
});
load();
// The channel answers in order: once a later request is back, the first load's reply has landed too.
await previewDocumentCopy(sealed);
await previewClipParents(sealed);
expect(sync.mock.calls.flatMap(([rows]) => rows.map((row) => row.id))).not.toContain("stale");
expect(rootRow(sync)).toEqual(["next@0+2"]);
});
// fails without the fix: the row took the frame-rounded total, 151 frames, instead of the authored 5.01 s.
it("gives a composition's own row its authored length, not the frame-rounded total", async () => {
document.body.innerHTML = rootOnly.replace('data-duration="5"', 'data-duration="5.01"');
const { sync, process } = processWith(sealedPreviewFrame().iframe);
process({ clips: [], durationInFrames: 151 });
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5.01"]));
});
// fails without the fix: with no clip list and no authored length, the preview's own duration was ignored.
it("gives a sealed composition with no authored length the preview's duration", async () => {
document.body.innerHTML = rootOnly.replace(' data-duration="5"', "");
usePlayerStore.getState().setElements([]);
const { sync, initialize } = processWith(sealedPreviewFrame().iframe, adapterOf(4));
initialize();
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+4"]));
});
/** Studio's end of the port, holding the frame's replies until released, newest first: an older read lands last. */
function heldReplies() {
const queue: MessageEvent[] = [];
let holding = false;
let deliver: ((event: MessageEvent) => void) | null = null;
const wrap = (port: MessagePort) =>
({
postMessage: (data: unknown) => port.postMessage(data),
start: () => port.start(),
close: () => port.close(),
get onmessage() {
return port.onmessage;
},
set onmessage(listener: ((event: MessageEvent) => void) | null) {
deliver = listener;
port.onmessage = listener && ((event) => (holding ? queue.push(event) : listener(event)));
},
}) as unknown as MessagePort;
const releaseNewestFirst = () => {
holding = false;
for (const event of queue.splice(0).reverse()) deliver?.(event);
};
return { wrap, hold: () => (holding = true), held: () => queue.length, releaseNewestFirst };
}
// fails without the fix: an empty clip list was dropped while the timeline held rows, so a deleted clip stayed.
it("replaces the timeline's rows when a sealed load's own clip list is empty", async () => {
document.body.innerHTML = rootOnly;
(window as unknown as { __clipManifest: unknown }).__clipManifest = {
clips: [],
durationInFrames: 0,
};
onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest);
usePlayerStore
.getState()
.setElements([{ id: "deleted", start: 0, duration: 2 } as TimelineElement]);
const { sync, initialize } = processWith(sealedPreviewFrame().iframe, adapterOf(5));
initialize();
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"]));
});
// fails without the fix: the shadow's and the live hook's reads were ordered apart, so the older one landed last.
it("keeps a newer clip list over a promotion's read that answers after it", async () => {
document.body.innerHTML = `<div data-composition-id="main">
<div id="old" data-start="0" data-duration="2"></div><div id="fresh" data-start="0" data-duration="2"></div>
</div>`;
(window as unknown as { __clipManifest: unknown }).__clipManifest = {
clips: [{ ...boxClip, id: "old" }],
durationInFrames: 60,
};
onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest);
const replies = heldReplies();
const frame = sealedPreviewFrame({ wrapHandedOverPort: replies.wrap }).iframe;
await previewDocumentCopy(frame);
const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>();
const shadow = processWith(frame, adapterOf(2), () => true, sync);
const live = processWith(frame, adapterOf(2), undefined, sync);
replies.hold();
shadow.initialize();
live.process({ clips: [{ ...boxClip, id: "fresh" }], durationInFrames: 60 });
// The promotion's clip list, copy and tree, then the live message's copy and tree.
await vi.waitFor(() => expect(replies.held()).toBe(5));
replies.releaseNewestFirst();
await vi.waitFor(() => expect(sync).toHaveBeenCalled());
await previewDocumentCopy(frame);
expect(rootRow(sync)).toEqual(["fresh@0+2"]);
});
// fails without the fix: the row took the preview's 4 s, then the empty list's default total clamped it to 1 s.
it("keeps a sealed root row at the preview's length over an empty list's default total", async () => {
document.body.innerHTML = rootOnly.replace(' data-duration="5"', "");
const { sync, process } = processWith(sealedPreviewFrame().iframe, adapterOf(4));
process({ clips: [], durationInFrames: 30 });
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+4"]));
});
// fails without the fix: a replaced frame's reply still landed until the replacement's load callback ran.
it("drops a reply from a frame once another is on screen, before that one loads", async () => {
document.body.innerHTML = `<div data-composition-id="main"><div id="stale" data-start="0" data-duration="2"></div></div>`;
const replaced = sealedPreviewFrame().iframe;
const { sync, iframeRef, process } = processWith(replaced, adapterOf(2));
process({ clips: [{ ...boxClip, id: "stale" }], durationInFrames: 60 });
iframeRef.current = detachedFakeIframe({ scrollTo() {} });
await previewDocumentCopy(replaced);
await previewClipParents(replaced);
expect(sync).not.toHaveBeenCalled();
});
// fails without the fix: the hidden reload's load cancelled the on-screen frame's read, so its rows never came.
it("keeps the on-screen frame's read when a hidden reload starts loading", async () => {
document.body.innerHTML = `<div data-composition-id="main"><div id="fresh" data-start="0" data-duration="2"></div></div>`;
const onScreen = sealedPreviewFrame().iframe;
const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>();
const live = processWith(onScreen, adapterOf(2), undefined, sync);
const hidden = processWith(
detachedFakeIframe({ scrollTo() {} }),
null,
() => true,
sync,
() => live.iframeRef.current,
);
live.process({ clips: [{ ...boxClip, id: "fresh" }], durationInFrames: 60 });
hidden.load();
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["fresh@0+2"]));
});
// fails without the fix: Studio left the player while the read was out, and its old rows still landed.
it("drops a sealed read whose frame its player removed before the reply", async () => {
document.body.innerHTML = `<div data-composition-id="main"><div id="old" data-start="0" data-duration="2"></div></div>`;
(window as unknown as { __clipManifest: unknown }).__clipManifest = {
clips: [{ ...boxClip, id: "old" }],
durationInFrames: 60,
};
onTestFinished(() => delete (window as unknown as { __clipManifest?: unknown }).__clipManifest);
const replies = heldReplies();
const promoted = sealedPreviewFrame({ wrapHandedOverPort: replies.wrap }).iframe;
await previewDocumentCopy(promoted);
const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>();
const shadow = processWith(
promoted,
adapterOf(2),
() => true,
sync,
() => promoted,
);
replies.hold();
shadow.initialize();
await vi.waitFor(() => expect(replies.held()).toBe(3));
promoted.remove();
replies.releaseNewestFirst();
await previewDocumentCopy(promoted);
expect(sync).not.toHaveBeenCalled();
});
// Pins the promotion path: the retiring live Player's removal must not take the promoted frame's read with it.
it("lands a promoted frame's read after the old live player is removed", async () => {
document.body.innerHTML = rootOnly;
usePlayerStore.getState().setElements([]);
const retiring = sealedPreviewFrame().iframe;
const promoted = sealedPreviewFrame().iframe;
const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>();
const live = processWith(retiring, adapterOf(5), undefined, sync);
const shadow = processWith(
promoted,
adapterOf(5),
() => true,
sync,
() => live.iframeRef.current,
);
live.iframeRef.current = promoted;
shadow.initialize();
retiring.remove();
await vi.waitFor(() => expect(rootRow(sync)).toEqual(["scene5@0+5"]));
});
@@ -19,6 +19,7 @@ import { previewClipParents, previewDocumentCopy, previewFrameOpaque } from "../
import { useLinkedClipPreferences } from "../../utils/linkedClipPreferences";
import {
buildTimelineElementsFromClips,
fallbackTimelineFromDom,
syncManifestTimeline,
clipTreeParentMap,
collectSubCompositionDomChildren,
@@ -30,7 +31,13 @@ import {
seekAdapterToRestorePoint,
syncAdapterDuration,
type RuntimeTimelineMessage,
type SealedTimelineRead,
} from "./timelineSyncHydration";
import {
landTimelineRevision,
nextTimelineRevision,
supersedeTimelineReads,
} from "../lib/timelineRevision";
// Re-exported for the tests and callers that have always imported it from here.
export { resolveReloadSeekTime } from "./timelineSyncHydration";
@@ -62,6 +69,8 @@ export interface UseTimelineSyncCallbacksParams {
/** Fires when no adapter appeared within the wait window. */
onLoadGiveUp?: (context?: number) => void;
hostOwnsDeadline?: boolean;
/** The frame on screen, when it is not this hook's own (a shadow, hidden until promoted). */
liveFrame?: () => HTMLIFrameElement | null;
}
/**
@@ -179,10 +188,25 @@ export function useTimelineSyncCallbacks({
isCurrent,
onLoadGiveUp,
hostOwnsDeadline,
liveFrame,
}: UseTimelineSyncCallbacksParams) {
const onScreen = useCallback(
() => (liveFrame ? liveFrame() : iframeRef.current),
[liveFrame, iframeRef],
);
// Convert a runtime timeline message (from iframe postMessage) into TimelineElements
const applyTimelineMessage = useCallback(
(data: RuntimeTimelineMessage, iframeDoc: Document | null, parentMap: Map<string, string>) => {
(
data: RuntimeTimelineMessage,
iframeDoc: Document | null,
parentMap: Map<string, string>,
iframe: HTMLIFrameElement | null,
previewDuration: number,
revision: number,
) => {
// A read lands only from the frame on screen, and only over nothing newer.
if (iframe !== onScreen() || !landTimelineRevision(revision)) return;
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));
const filtered = data.clips.filter(
@@ -199,7 +223,6 @@ export function useTimelineSyncCallbacks({
// A document the walk cannot read leaves the maps empty.
}
const els = buildTimelineElementsFromClips(filtered, iframeDoc);
// Clamp non-finite or absurdly large durations — the runtime can emit
// Infinity when it detects a loop-inflated GSAP timeline without an
// explicit data-duration on the root composition. Floor the manifest total
@@ -212,36 +235,52 @@ export function useTimelineSyncCallbacks({
manifestDurationSeconds: data.durationInFrames / fps,
authoredRootDurationSeconds: readTimelineDurationFromDocument(iframeDoc),
});
// The composition's own row keeps its exact length; the transport total is frame-rounded.
const ownDuration =
sanitizeDurationSeconds(readTimelineDurationFromDocument(iframeDoc)) ||
sanitizeDurationSeconds(previewDuration) ||
newDuration;
const fallback = data.clips.length === 0 && iframeDoc !== null;
const els = fallback
? fallbackTimelineFromDom(iframeDoc, iframe, ownDuration)
: buildTimelineElementsFromClips(filtered, iframeDoc);
syncManifestTimeline(
els,
newDuration,
fallback ? Math.max(newDuration, ownDuration) : newDuration,
usePlayerStore.getState().duration,
syncTimelineElements,
);
},
[syncTimelineElements],
[onScreen, syncTimelineElements],
);
const timelineReads = useRef(0);
const processTimelineMessage = useCallback(
(data: RuntimeTimelineMessage) => {
if (!data.clips) return;
usePlayerStore.getState().setClipManifest(data.clips);
const iframe = iframeRef.current;
const read = ++timelineReads.current;
if (!iframe || !previewFrameOpaque(iframe)) {
applyTimelineMessage(data, safeContentDocument(iframe), openClipParents(iframe));
return;
}
// A sealed frame's rows bind to its document copy and clip tree from the editing port; the newest read wins.
void Promise.all([previewDocumentCopy(iframe), previewClipParents(iframe)]).then(
([doc, parents]) => {
if (read === timelineReads.current && iframeRef.current === iframe)
applyTimelineMessage(data, doc, parents);
// A sealed frame's rows bind to its document copy and clip tree from the editing port.
const readSealedTimeline = useCallback<SealedTimelineRead>(
(iframe, manifest, previewDuration) => {
const revision = nextTimelineRevision();
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);
},
);
},
[iframeRef, applyTimelineMessage],
[applyTimelineMessage],
);
const processTimelineMessage = useCallback(
(data: RuntimeTimelineMessage) => {
if (!data.clips) return;
const iframe = iframeRef.current;
const previewDuration = getAdapter()?.getDuration() ?? 0;
if (iframe && previewFrameOpaque(iframe))
return readSealedTimeline(iframe, Promise.resolve(data), previewDuration);
const doc = safeContentDocument(iframe);
const parents = openClipParents(iframe);
applyTimelineMessage(data, doc, parents, iframe, previewDuration, nextTimelineRevision());
},
[iframeRef, getAdapter, readSealedTimeline, applyTimelineMessage],
);
const enrichMissingCompositions = useCallback(() => {
@@ -296,6 +335,7 @@ export function useTimelineSyncCallbacks({
iframe: iframeRef.current,
adapter,
processTimelineMessage,
readSealedTimeline,
enrichMissingCompositions,
applyPreviewAudioState,
attachIframeShortcutListeners,
@@ -312,6 +352,7 @@ export function useTimelineSyncCallbacks({
requestTimelineReady,
setIsPlaying,
processTimelineMessage,
readSealedTimeline,
enrichMissingCompositions,
syncTimelineElements,
attachIframeShortcutListeners,
@@ -329,6 +370,7 @@ export function useTimelineSyncCallbacks({
const onIframeLoad = useCallback(
(context?: number) => {
if (onScreen() === iframeRef.current) supersedeTimelineReads();
const loadedDoc = safeContentDocument(iframeRef.current);
if (loadedDoc) usePlayerStore.getState().markPreviewLoadStep(loadedDoc);
applyPreviewAudioState();
@@ -385,6 +427,7 @@ export function useTimelineSyncCallbacks({
applyPreviewAudioState,
onLoadGiveUp,
hostOwnsDeadline,
onScreen,
],
);
@@ -26,6 +26,12 @@ export function sealedPreviewFrame(
});
const iframe = detachedFakeIframe(frame);
Object.defineProperty(iframe, "contentDocument", { value: null });
let onPageUntilPlayerRemovesIt = true;
Object.defineProperty(iframe, "isConnected", {
configurable: true,
get: () => onPageUntilPlayerRemovesIt,
});
iframe.remove = () => void (onPageUntilPlayerRemovesIt = false);
const wrap = options.wrapHandedOverPort ?? ((port: MessagePort) => port);
const parent = {
postMessage: (data: unknown, _origin: string, ports: MessagePort[]) =>
@@ -0,0 +1,17 @@
// An older preview read never replaces a newer one on the timeline, whichever frame or hook it came through.
let issued = 0;
let landed = 0;
export function nextTimelineRevision(): number {
return ++issued;
}
export function landTimelineRevision(revision: number): boolean {
if (revision < landed) return false;
landed = revision;
return true;
}
export function supersedeTimelineReads(): void {
landed = ++issued;
}