fix(studio): timing edits patch the clip and the duration readout in a sealed preview (#8684)

This commit is contained in:
Miguel Ángel
2026-11-24 19:30:48 +00:00
committed by GitHub
parent bf26dcbaab
commit 5db64b4adf
9 changed files with 238 additions and 53 deletions
@@ -0,0 +1,91 @@
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import type { Browser } from "puppeteer-core";
import { afterAll, beforeAll, expect, it, vi } from "vitest";
import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils";
import { buildStudioBundle, openPreview, type Preview } from "../../tests/sealedPreviewHarness";
vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
const require = createRequire(import.meta.url);
const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"];
let browser: Browser;
let studioBundle: string;
beforeAll(async () => {
browser = await launchTestChrome();
studioBundle = await buildStudioBundle([
`export { captureDurationRollback, patchIframeDomTiming, syncPreviewContentDuration } from "./hooks/previewTimingPatch";`,
]);
});
afterAll(() => closeTestChrome(browser));
function previewHtml(): string {
const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8");
return `<!doctype html><html><head><meta charset="UTF-8" />
<meta name="hyperframes-studio-preview" content="1" />
</head><body>
<div id="root" data-composition-id="main" data-start="0" data-duration="4" data-width="1920" data-height="1080">
<div id="a" class="clip" data-start="0" data-duration="4" data-track-index="1"></div>
<div id="b" class="clip" data-start="0" data-duration="2" data-track-index="2"></div>
</div>
<script>${runtime}</script></body></html>`;
}
type Studio = {
usePlayerStore: { getState(): { duration: number }; setState(state: object): void };
patchIframeDomTiming(...args: unknown[]): void;
syncPreviewContentDuration(iframe: HTMLIFrameElement): void;
captureDurationRollback(iframe: HTMLIFrameElement): () => void;
};
const shown = async ({ page, frame }: Preview) => ({
duration: await page.evaluate(
() => (window as unknown as { hfStudio: Studio }).hfStudio.usePlayerStore.getState().duration,
),
frame: await frame.evaluate(() => {
const a = document.getElementById("a")!;
return {
start: a.getAttribute("data-start"),
length: a.getAttribute("data-duration"),
root: document.getElementById("root")!.getAttribute("data-duration"),
};
}),
});
async function timingEdit(mode: string) {
const preview = await openPreview(browser, studioBundle, previewHtml(), mode);
try {
await preview.page.evaluate(() => {
const studio = (window as unknown as { hfStudio: Studio }).hfStudio;
const iframe = document.querySelector("iframe")!;
studio.usePlayerStore.setState({ duration: 4 });
const clip = {
id: "a",
domId: "a",
selector: "#a",
sourceFile: "index.html",
kind: "element",
};
studio.patchIframeDomTiming(iframe, clip, [
["data-start", "2"],
["data-duration", "3"],
]);
(window as unknown as { rollback: () => void }).rollback =
studio.captureDurationRollback(iframe);
studio.syncPreviewContentDuration(iframe);
});
const patched = { duration: 5, frame: { start: "2", length: "3", root: "5" } };
await expect.poll(() => shown(preview)).toEqual(patched);
await preview.page.evaluate(() => (window as unknown as { rollback: () => void }).rollback());
await expect
.poll(() => shown(preview))
.toEqual({ ...patched, duration: 4, frame: { ...patched.frame, root: "4" } });
} finally {
await preview.page.close();
}
}
it.each(MODES)("a timing edit patches the clip and the duration in a %s preview", async (mode) => {
await timingEdit(mode);
});
@@ -0,0 +1,135 @@
import { applyAuthoredTiming, RUNTIME_STAMPED_ATTR } from "@hyperframes/core/studio-preview-mark";
import { type TimelineElement, usePlayerStore } from "../player/store/playerStore";
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
import { furthestClipEndFromDocument } from "../player/lib/timelineElementHelpers";
import { previewDocumentCopy, previewFrameOpaque } from "../player/lib/previewChannel";
import { editPreviewElement, queryPreviewElements } from "../player/lib/previewElements";
import {
findPreviewElementForSelection,
findPreviewElementForTimelineElement,
} from "../components/editor/previewSelection";
import { patchDocumentRootDuration } from "./timelineEditingGsap";
import { findTimelineElementInIframe } from "./timelineEditingHelpers";
const sealedWrites = new WeakMap<HTMLIFrameElement, Promise<unknown>>();
/** A sealed frame's timing writes and reads run one after another, in the order the edit made them. */
function inOrder(iframe: HTMLIFrameElement, step: () => Promise<unknown>): void {
const next = (sealedWrites.get(iframe) ?? Promise.resolve()).then(step).catch(() => undefined);
sealedWrites.set(iframe, next);
}
export function patchIframeDomTiming(
iframe: HTMLIFrameElement | null,
element: TimelineElement,
attrs: Array<[string, string]>,
activeCompositionPath: string | null = null,
): void {
if (iframe && previewFrameOpaque(iframe)) {
inOrder(iframe, () => patchSealedTiming(iframe, element, attrs, activeCompositionPath));
return;
}
try {
const el = findTimelineElementInIframe(iframe, element, activeCompositionPath);
if (!el) return;
applyAuthoredTiming(el, attrs);
} catch {
// Cross-origin or mid-navigation — file save is enqueued; iframe patch is best-effort.
}
}
async function patchSealedTiming(
iframe: HTMLIFrameElement,
element: TimelineElement,
attrs: Array<[string, string]>,
activeCompositionPath: string | null,
): Promise<void> {
const found =
element.kind === "composition" && element.compositionSrc
? await findPreviewElementForTimelineElement(iframe, element, {
activeCompositionPath,
isMasterView: true,
})
: await findPreviewElementForSelection(
iframe,
{
hfId: element.hfId,
id: element.domId,
selector: element.selector,
selectorIndex: element.selectorIndex,
sourceFile: element.sourceFile || activeCompositionPath || "index.html",
},
activeCompositionPath,
);
if (!found) return;
const attributes: Array<[string, string | null]> = [...attrs, [RUNTIME_STAMPED_ATTR, null]];
await editPreviewElement(iframe, found.handle, { attributes }).drawn;
}
function patchIframeRootDuration(iframe: HTMLIFrameElement | null, contentEnd: number): void {
if (iframe && previewFrameOpaque(iframe)) {
inOrder(iframe, async () =>
patchSealedRootDuration(iframe, await previewDocumentCopy(iframe), contentEnd),
);
return;
}
try {
patchDocumentRootDuration(iframe?.contentDocument ?? null, contentEnd);
} catch {
// Cross-origin or mid-navigation — file save is enqueued; iframe patch is best-effort.
}
}
/** `patchDocumentRootDuration` on the frame, its root found in `copy` and matched by document order. */
async function patchSealedRootDuration(
iframe: HTMLIFrameElement,
copy: Document | null,
contentEnd: number,
): Promise<void> {
if (!copy || !Number.isFinite(contentEnd) || contentEnd <= 0) return;
const nodes = Array.from(copy.querySelectorAll("[data-composition-id]"));
const root =
nodes.find((node) => !node.parentElement?.closest("[data-composition-id]")) ?? nodes[0];
const handle =
root &&
(await queryPreviewElements(iframe, "[data-composition-id]"))?.matches[nodes.indexOf(root)]
?.handle;
if (!handle) return;
const duration = formatTimelineAttributeNumber(contentEnd);
await editPreviewElement(iframe, handle, { attributes: [["data-duration", duration]] }).drawn;
}
function syncContentDuration(
iframe: HTMLIFrameElement | null,
doc: Document | null,
): Promise<void> {
const end = furthestClipEndFromDocument(doc);
if (end <= 0) return Promise.resolve();
usePlayerStore.getState().setDuration(end);
if (iframe && previewFrameOpaque(iframe)) return patchSealedRootDuration(iframe, doc, end);
patchIframeRootDuration(iframe, end);
return Promise.resolve();
}
/** Keep the duration readout and live root aligned with optimistically patched clips. */
export function syncPreviewContentDuration(iframe: HTMLIFrameElement | null): void {
if (iframe && previewFrameOpaque(iframe)) {
inOrder(iframe, async () => syncContentDuration(iframe, await previewDocumentCopy(iframe)));
return;
}
void syncContentDuration(iframe, iframe?.contentDocument ?? null);
}
/** Restore both store and live-root duration when a timing persist fails. */
export function captureDurationRollback(iframe: HTMLIFrameElement | null): () => void {
const previousDuration = usePlayerStore.getState().duration;
const rollback = () => {
if (usePlayerStore.getState().duration === previousDuration) return;
usePlayerStore.getState().setDuration(previousDuration);
patchIframeRootDuration(iframe, previousDuration);
};
return () => {
if (iframe && previewFrameOpaque(iframe)) inOrder(iframe, async () => rollback());
else rollback();
};
}
@@ -6,13 +6,13 @@ import {
buildTimelineResizeTimingPatch,
deleteSelectedKeyframes,
extendRootDurationIfNeeded,
patchIframeDomTiming,
persistElementAttribute,
persistTimelineBatchEdit,
persistTimelineEdit,
readTargetAttribute,
type PersistTimelineBatchChange,
} from "./timelineEditingHelpers";
import { patchIframeDomTiming } from "./previewTimingPatch";
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import { parseTimelineFromDOM } from "../player/lib/timelineDOM";
import type { TimelineElement } from "../player/store/playerStore";
@@ -1,4 +1,3 @@
import { applyAuthoredTiming } from "@hyperframes/core/studio-preview-mark";
import { type TimelineElement, usePlayerStore } from "../player/store/playerStore";
import { toAuthoredStart } from "../player/store/timelineElement";
import {
@@ -116,21 +115,6 @@ export function findTimelineElementInDocument(
return null;
}
}
export function patchIframeDomTiming(
iframe: HTMLIFrameElement | null,
element: TimelineElement,
attrs: Array<[string, string]>,
activeCompositionPath: string | null = null,
): void {
try {
const el = findTimelineElementInIframe(iframe, element, activeCompositionPath);
if (!el) return;
applyAuthoredTiming(el, attrs);
} catch {
// Cross-origin or mid-navigation — file save is enqueued; iframe patch is best-effort.
}
}
/** Takes deleted clips out of the live preview at once: until the reload lands, anything that re-reads the
* preview (composition enrichment) would otherwise put them back on the timeline. */
export function removeIframeTimelineElements(
@@ -3,8 +3,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { usePlayerStore } from "../player/store/playerStore";
import { jsonResponse, requestUrl } from "./fetchStubTestUtils";
import type { TimelineElement } from "../player/store/playerStore";
import { captureDurationRollback } from "./previewTimingPatch";
import {
captureDurationRollback,
finishClipTimingFallback,
finishGroupTimingGsapFallback,
finishTimelineTimingFallback,
@@ -10,9 +10,7 @@ import {
readNestedFiles,
settleNestedReads,
} from "../utils/gsapSoftReload";
import { furthestClipEndFromDocument } from "../player/lib/timelineElementHelpers";
import type { RecordEditInput } from "../utils/studioFileHistory";
import { patchDocumentRootDuration } from "./timelineEditingGsap";
import {
GsapOwnershipProtocolError,
GsapPreviewConvergenceError,
@@ -52,34 +50,6 @@ export async function readFileContent(projectId: string, targetPath: string): Pr
return data.content;
}
/** Best-effort live-iframe wrapper for patchDocumentRootDuration (see timelineEditingGsap). */
function patchIframeRootDuration(iframe: HTMLIFrameElement | null, contentEnd: number): void {
try {
patchDocumentRootDuration(iframe?.contentDocument ?? null, contentEnd);
} catch {
// Cross-origin or mid-navigation — file save is enqueued; iframe patch is best-effort.
}
}
/** Keep the duration readout and live root aligned with optimistically patched clips. */
export function syncPreviewContentDuration(iframe: HTMLIFrameElement | null): void {
const end = furthestClipEndFromDocument(iframe?.contentDocument ?? null);
if (end > 0) {
usePlayerStore.getState().setDuration(end);
patchIframeRootDuration(iframe, end);
}
}
/** Restore both store and live-root duration when a timing persist fails. */
export function captureDurationRollback(iframe: HTMLIFrameElement | null): () => void {
const previousDuration = usePlayerStore.getState().duration;
return () => {
if (usePlayerStore.getState().duration === previousDuration) return;
usePlayerStore.getState().setDuration(previousDuration);
patchIframeRootDuration(iframe, previousDuration);
};
}
/** Re-derive live timing windows without re-executing composition scripts.
* Works for zero-GSAP compositions; false asks the caller to full-reload. */
function rebindPreviewTiming(iframe: HTMLIFrameElement | null, currentTime: number): boolean {
@@ -2,7 +2,6 @@ import { useCallback } from "react";
import type { TimelineElement } from "../player";
import { toAuthoredStart, toCompositionTime } from "../player/store/timelineElement";
import {
patchIframeDomTiming,
persistTimelineEdit,
formatTimelineAttributeNumber,
formatTimelineMediaOffset,
@@ -14,10 +13,13 @@ import {
import { playbackStartAttributeForElement } from "../player/lib/timelineElementHelpers";
import {
captureDurationRollback,
patchIframeDomTiming,
syncPreviewContentDuration,
} from "./previewTimingPatch";
import {
finishClipTimingFallback,
sdkTimingGsapSync,
readFileContent,
syncPreviewContentDuration,
timingGestureStep,
} from "./timelineTimingSync";
import { cutoverCommittedOrThrow, sdkTimingPersist, type CutoverResult } from "../utils/sdkCutover";
@@ -14,7 +14,8 @@ import {
removeIframeTimelineElements,
syncCompositionDurationWithEnd,
} from "./timelineEditingHelpers";
import { captureDurationRollback, timingGestureStep } from "./timelineTimingSync";
import { timingGestureStep } from "./timelineTimingSync";
import { captureDurationRollback } from "./previewTimingPatch";
import { setLinkInSource } from "../components/editor/mediaLinkEdits";
import {
resolveMainTrackDeleteRippleShifts,
@@ -15,7 +15,6 @@ import {
extendRootDurationIfNeeded,
formatTimelineAttributeNumber,
formatTimelineMediaOffset,
patchIframeDomTiming,
persistTimelineBatchEdit,
type PersistTimelineBatchChange,
type RecordEditInput,
@@ -23,13 +22,16 @@ import {
import { playbackStartAttributeForElement } from "../player/lib/timelineElementHelpers";
import {
captureDurationRollback,
patchIframeDomTiming,
syncPreviewContentDuration,
} from "./previewTimingPatch";
import {
finishGroupTimingGsapFallback,
timingGestureStep,
sdkTimingGsapSync,
readFileContent,
scaleGsapMutation,
shiftGsapMutation,
syncPreviewContentDuration,
} from "./timelineTimingSync";
import type { GsapMutationStatus } from "./gsapMutationClient";
import { getStudioSaveErrorMessage, getStudioSaveErrorTone } from "../utils/studioSaveDiagnostics";