From 5db64b4adfdb1e13474be7724a4aad335eaf01e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 19:30:48 +0000 Subject: [PATCH] fix(studio): timing edits patch the clip and the duration readout in a sealed preview (#8684) --- .../hooks/previewTimingPatch.browser.test.ts | 91 ++++++++++++ .../studio/src/hooks/previewTimingPatch.ts | 135 ++++++++++++++++++ .../src/hooks/timelineEditingHelpers.test.ts | 2 +- .../src/hooks/timelineEditingHelpers.ts | 16 --- .../src/hooks/timelineTimingSync.test.ts | 2 +- .../studio/src/hooks/timelineTimingSync.ts | 30 ---- .../src/hooks/useTimelineClipTimingEditing.ts | 6 +- .../studio/src/hooks/useTimelineDeleteOps.ts | 3 +- .../src/hooks/useTimelineGroupEditing.ts | 6 +- 9 files changed, 238 insertions(+), 53 deletions(-) create mode 100644 packages/studio/src/hooks/previewTimingPatch.browser.test.ts create mode 100644 packages/studio/src/hooks/previewTimingPatch.ts diff --git a/packages/studio/src/hooks/previewTimingPatch.browser.test.ts b/packages/studio/src/hooks/previewTimingPatch.browser.test.ts new file mode 100644 index 0000000000..45b59fdfb7 --- /dev/null +++ b/packages/studio/src/hooks/previewTimingPatch.browser.test.ts @@ -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 ` + + +
+
+
+
+ `; +} + +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); +}); diff --git a/packages/studio/src/hooks/previewTimingPatch.ts b/packages/studio/src/hooks/previewTimingPatch.ts new file mode 100644 index 0000000000..eebed48988 --- /dev/null +++ b/packages/studio/src/hooks/previewTimingPatch.ts @@ -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>(); + +/** 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): 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 { + 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 { + 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 { + 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(); + }; +} diff --git a/packages/studio/src/hooks/timelineEditingHelpers.test.ts b/packages/studio/src/hooks/timelineEditingHelpers.test.ts index 8173f87f22..2d436be749 100644 --- a/packages/studio/src/hooks/timelineEditingHelpers.test.ts +++ b/packages/studio/src/hooks/timelineEditingHelpers.test.ts @@ -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"; diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.ts index 57027df912..f4efe2ed27 100644 --- a/packages/studio/src/hooks/timelineEditingHelpers.ts +++ b/packages/studio/src/hooks/timelineEditingHelpers.ts @@ -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( diff --git a/packages/studio/src/hooks/timelineTimingSync.test.ts b/packages/studio/src/hooks/timelineTimingSync.test.ts index 85974a1b49..b22190be48 100644 --- a/packages/studio/src/hooks/timelineTimingSync.test.ts +++ b/packages/studio/src/hooks/timelineTimingSync.test.ts @@ -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, diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.ts index d1afc052bf..3e5146e9fc 100644 --- a/packages/studio/src/hooks/timelineTimingSync.ts +++ b/packages/studio/src/hooks/timelineTimingSync.ts @@ -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 { diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts index 630a8f35ca..c10fe8fba2 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts @@ -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"; diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index 6d8d874d61..17fd1cd4c9 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -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, diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts index 378cb1dd39..fefef47453 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.ts +++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts @@ -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";