From 02cef8e072c71b238b848cb92a168c59763a8f97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 25 Nov 2026 03:43:28 +0000 Subject: [PATCH] fix(studio): a timeline delete takes its clips out of a sealed preview at once (#8719) * fix(studio): timing edits patch the clip and the duration readout in a sealed preview * fix(studio): a timeline delete takes its clips out of a sealed preview at once * refactor(studio): keep the preview patch module's comment share * test(core): a timeline delete removes every kind of clip the runtime lists * fix(core): a timeline delete removes what the runtime's timeline calls a clip * test(studio): the delete test hears only the preview frame's own messages * test(core): a sealed delete counts each clip it takes out once * fix(core): a sealed delete counts each clip it takes out once * test(core): a sealed delete counts a clip once when its child is named first * fix(core): a sealed delete counts a clip once whichever order the batch names it --- packages/core/src/runtime/clipNodes.ts | 2 + .../runtime/editing/removeElements.test.ts | 100 ++++++++++++++++++ .../src/runtime/editing/removeElements.ts | 40 +++++++ .../core/src/runtime/editingAgent.test.ts | 1 + packages/core/src/runtime/editingAgent.ts | 2 + packages/core/src/runtime/editingPort.test.ts | 1 + packages/core/src/runtime/editingPort.ts | 3 + packages/core/src/runtime/timeline.ts | 2 +- .../hooks/previewTimingPatch.browser.test.ts | 44 +++++++- .../src/hooks/previewTimingPatch.test.ts | 41 +++++++ .../studio/src/hooks/previewTimingPatch.ts | 68 ++++++++---- .../src/hooks/timelineEditingHelpers.ts | 11 -- .../studio/src/hooks/useTimelineDeleteOps.ts | 8 +- 13 files changed, 286 insertions(+), 37 deletions(-) create mode 100644 packages/core/src/runtime/clipNodes.ts create mode 100644 packages/core/src/runtime/editing/removeElements.test.ts create mode 100644 packages/core/src/runtime/editing/removeElements.ts create mode 100644 packages/studio/src/hooks/previewTimingPatch.test.ts diff --git a/packages/core/src/runtime/clipNodes.ts b/packages/core/src/runtime/clipNodes.ts new file mode 100644 index 0000000000..304ad8ccf4 --- /dev/null +++ b/packages/core/src/runtime/clipNodes.ts @@ -0,0 +1,2 @@ +export const CLIP_NODES = + "[data-start], [data-track-index], [data-composition-id], video, audio, img"; diff --git a/packages/core/src/runtime/editing/removeElements.test.ts b/packages/core/src/runtime/editing/removeElements.test.ts new file mode 100644 index 0000000000..47acaa7bac --- /dev/null +++ b/packages/core/src/runtime/editing/removeElements.test.ts @@ -0,0 +1,100 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { handleFor } from "../editingHandles"; +import { removeElements } from "./removeElements"; + +afterEach(() => { + document.body.innerHTML = ""; +}); + +function film() { + document.body.innerHTML = ` +
+
+
B
+
+ +
`; + const handle = (id: string) => handleFor(document.getElementById(id)!); + const present = () => + ["root", "a", "b", "inner", "host", "s"].filter((id) => document.getElementById(id)); + return { handle, present }; +} + +function kinds() { + document.body.innerHTML = ` +
+ + + +
+
+
`; +} + +describe("remove-elements", () => { + it("removes every named clip, a composition host among them", () => { + const { handle, present } = film(); + expect(removeElements({ handles: [handle("a"), handle("host")] })).toEqual({ removed: 2 }); + expect(present()).toEqual(["root", "b", "inner", "s"]); + }); + + it.each([ + ["an image", "pic"], + ["a video without data-start", "vid"], + ["an audio without data-start", "aud"], + ["a clip placed only by data-track-index", "lane"], + ])("removes %s, which the runtime's timeline lists as a clip", (_, id) => { + kinds(); + expect(removeElements({ handles: [handleFor(document.getElementById(id)!)] })).toEqual({ + removed: 1, + }); + expect(document.getElementById(id)).toBeNull(); + }); + + it.each([ + ["the clip first", ["p", "c", "p"]], + ["its child first", ["c", "p"]], + ])( + "counts each clip once, though a batch names it twice or names its child too (%s)", + (_, ids) => { + document.body.innerHTML = ` +
+
+
`; + const handles = ids.map((id) => handleFor(document.getElementById(id)!)); + expect(removeElements({ handles })).toEqual({ removed: 1 }); + expect(document.getElementById("p")).toBeNull(); + }, + ); + + it("removes every kind of clip the runtime's timeline lists, all of them in one mixed delete", () => { + kinds(); + const ids = ["pic", "vid", "aud", "lane", "timed"]; + const handles = ids.map((id) => handleFor(document.getElementById(id)!)); + expect(removeElements({ handles })).toEqual({ removed: 5 }); + expect(ids.filter((id) => document.getElementById(id))).toEqual([]); + expect(document.getElementById("root")).not.toBeNull(); + }); + + it.each([ + ["the root composition", "root"], + ["an element that is not a clip", "inner"], + ["a script", "s"], + ])("removes nothing when one handle names %s", (_, id) => { + const { handle, present } = film(); + expect(removeElements({ handles: [handle("a"), handle(id)] })).toEqual({ removed: 0 }); + expect(present()).toEqual(["root", "a", "b", "inner", "host", "s"]); + }); + + it("removes nothing for the page's own elements or a handle of an element already gone", () => { + const { handle, present } = film(); + const gone = handle("b"); + document.getElementById("b")!.remove(); + expect(removeElements({ handles: [handle("a"), gone] })).toEqual({ removed: 0 }); + expect(removeElements({ handles: [handleFor(document.body)] })).toEqual({ removed: 0 }); + expect(removeElements({ handles: [handleFor(document.documentElement)] })).toEqual({ + removed: 0, + }); + expect(present()).toEqual(["root", "a", "host", "s"]); + }); +}); diff --git a/packages/core/src/runtime/editing/removeElements.ts b/packages/core/src/runtime/editing/removeElements.ts new file mode 100644 index 0000000000..b49dbec7fd --- /dev/null +++ b/packages/core/src/runtime/editing/removeElements.ts @@ -0,0 +1,40 @@ +// `remove-elements`: a timeline delete takes its clips out of the frame before the save's reload, as +// Studio does in a frame it can script. Only clips the frame named, never the root or the page itself. +import type { EditingElementHandle } from "../editingElement"; +import { elementForHandle } from "../editingHandles"; +import { CLIP_NODES } from "../clipNodes"; + +const NEVER_CLIPS = new Set([ + "html", + "head", + "body", + "script", + "style", + "link", + "meta", + "template", + "noscript", +]); + +const isRootComposition = (element: Element) => + element.hasAttribute("data-composition-id") && + !element.parentElement?.closest("[data-composition-id]"); + +function removableClip(element: Element | null): element is Element { + if (!element || NEVER_CLIPS.has(element.localName) || isRootComposition(element)) return false; + return element.matches(CLIP_NODES); +} + +/** Removes every named clip, or none when any handle is stale or names something that is not a clip. */ +export function removeElements({ handles }: { handles: EditingElementHandle[] }): { + removed: number; +} { + const elements = handles.map(elementForHandle); + if (!elements.every(removableClip)) return { removed: 0 }; + // A clip named twice, or inside another named clip, leaves with it and counts once. + const outermost = [...new Set(elements)].filter( + (element, _, all) => !all.some((other) => other !== element && other.contains(element)), + ); + for (const element of outermost) element.remove(); + return { removed: outermost.length }; +} diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index c0ce3c9cd0..77702ec84c 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -223,6 +223,7 @@ describe("installEditingAgent", () => { "max-z-index", "crop-lift", "edit-element", + "remove-elements", "stacking-family", "gsap-set", "patch-tweens", diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index 9dca5a6e5f..ba4bbefd6a 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -62,6 +62,7 @@ import { colorGradingPlayback } from "./editing/color-grading-playback"; import { assignAudioGroup } from "./editing/assignAudioGroup"; import { audioMeter } from "./editing/audioMeter"; import { documentMarkup } from "./editing/documentMarkup"; +import { removeElements } from "./editing/removeElements"; import { authoredStyles, fontFaces } from "./editing/textStyleReads"; import { setAudioGroupAttribute } from "./editing/setAudioGroupAttribute"; import { editElement } from "./editing/editElement"; @@ -232,6 +233,7 @@ const HANDLERS: Handlers = { "max-z-index": () => maxZIndex(), "crop-lift": cropLift, "edit-element": editElement, + "remove-elements": removeElements, "stacking-family": stackingFamily, "gsap-set": gsapSet, "patch-tweens": patchTweens, diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts index 69d119331d..0c1bd666a5 100644 --- a/packages/core/src/runtime/editingPort.test.ts +++ b/packages/core/src/runtime/editingPort.test.ts @@ -106,6 +106,7 @@ describe("createEditingPortClient", () => { "max-z-index", "crop-lift", "edit-element", + "remove-elements", "stacking-family", "gsap-set", "patch-tweens", diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index a1884ec386..853ac8d6c6 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -214,6 +214,7 @@ export const EDITING_REQUEST_KINDS = [ "max-z-index", "crop-lift", "edit-element", + "remove-elements", "stacking-family", "gsap-set", "patch-tweens", @@ -397,6 +398,7 @@ export interface EditingRequests { result: { lifted: boolean; clipPath: string | null }; }; "edit-element": { params: EditElementParams; result: EditElementResult }; + "remove-elements": { params: { handles: EditingElementHandle[] }; result: { removed: number } }; "stacking-family": { params: { handle: EditingElementHandle }; result: { family: EditingStackingSibling[] | null; locked: boolean }; @@ -701,6 +703,7 @@ const PARAM_PARSERS: { ? { handle: params.handle, lift: params.lift } : null, "edit-element": parseEditElement, + "remove-elements": handleList, "stacking-family": (params) => hasKeys(params, "handle") && isHandle(params.handle) ? { handle: params.handle } : null, "gsap-set": gsapSetWithDrafts, diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts index c248d2ed47..f06324c0ab 100644 --- a/packages/core/src/runtime/timeline.ts +++ b/packages/core/src/runtime/timeline.ts @@ -8,6 +8,7 @@ import type { import { transitionLabelsForDocument } from "./transitionLabels"; import { unproxiedSrc } from "./proxySrc"; import { stableClipId } from "./clipTree"; +import { CLIP_NODES } from "./clipNodes"; import { findRootCompositionElement, parseCompositionDimension } from "./compositionDimension"; import { AUTHORED_DURATION_ATTR, @@ -430,7 +431,6 @@ export function collectRuntimeTimelinePayload(params: { // as clips — they have no declared timing so the timeline can't show their // actual visibility window. They can still appear as scenes via the separate // scene collection below. - const CLIP_NODES = "[data-start], [data-track-index], [data-composition-id], video, audio, img"; const nodes = Array.from(document.querySelectorAll(CLIP_NODES)); let maxEnd = 0; const clipOf = (node: Element, i: number): RuntimeTimelineClip | null => { diff --git a/packages/studio/src/hooks/previewTimingPatch.browser.test.ts b/packages/studio/src/hooks/previewTimingPatch.browser.test.ts index 45b59fdfb7..8a1eb153d2 100644 --- a/packages/studio/src/hooks/previewTimingPatch.browser.test.ts +++ b/packages/studio/src/hooks/previewTimingPatch.browser.test.ts @@ -14,7 +14,7 @@ let studioBundle: string; beforeAll(async () => { browser = await launchTestChrome(); studioBundle = await buildStudioBundle([ - `export { captureDurationRollback, patchIframeDomTiming, syncPreviewContentDuration } from "./hooks/previewTimingPatch";`, + `export { captureDurationRollback, patchIframeDomTiming, removeIframeTimelineElements, syncPreviewContentDuration } from "./hooks/previewTimingPatch";`, ]); }); @@ -37,6 +37,7 @@ type Studio = { patchIframeDomTiming(...args: unknown[]): void; syncPreviewContentDuration(iframe: HTMLIFrameElement): void; captureDurationRollback(iframe: HTMLIFrameElement): () => void; + removeIframeTimelineElements(iframe: HTMLIFrameElement, elements: unknown[]): void; }; const shown = async ({ page, frame }: Preview) => ({ @@ -89,3 +90,44 @@ async function timingEdit(mode: string) { it.each(MODES)("a timing edit patches the clip and the duration in a %s preview", async (mode) => { await timingEdit(mode); }); + +async function deleteClip(mode: string) { + const preview = await openPreview(browser, studioBundle, previewHtml(), mode); + try { + await preview.page.evaluate(() => { + const posted: string[][] = []; + const frame = document.querySelector("iframe")!; + window.addEventListener("message", ({ source, data }) => { + if (source !== frame.contentWindow) return; + if (data?.source === "hf-preview" && data.type === "timeline") + posted.push(data.clips.map((clip: { id: string | null }) => clip.id)); + }); + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const clip = { + id: "b", + domId: "b", + selector: "#b", + sourceFile: "index.html", + kind: "element", + }; + studio.removeIframeTimelineElements(frame, [clip]); + (window as unknown as { posted: string[][] }).posted = posted; + }); + const inFrame = () => + preview.frame.evaluate(() => ["root", "a", "b"].filter((id) => document.getElementById(id))); + await expect.poll(inFrame).toEqual(["root", "a"]); + const lastPosted = () => + preview.page.evaluate(() => (window as unknown as { posted: string[][] }).posted.at(-1)); + await expect.poll(lastPosted).toEqual(expect.arrayContaining(["a"])); + expect(await lastPosted()).not.toContain("b"); + } finally { + await preview.page.close(); + } +} + +it.each(MODES)( + "a deleted clip leaves the frame, and the frame's next clip list leaves it out, in a %s preview", + async (mode) => { + await deleteClip(mode); + }, +); diff --git a/packages/studio/src/hooks/previewTimingPatch.test.ts b/packages/studio/src/hooks/previewTimingPatch.test.ts new file mode 100644 index 0000000000..a6fb043f4a --- /dev/null +++ b/packages/studio/src/hooks/previewTimingPatch.test.ts @@ -0,0 +1,41 @@ +// @vitest-environment jsdom +import { afterEach, expect, it } from "vitest"; +import type { TimelineElement } from "../player/store/playerStore"; +import { removeIframeTimelineElements } from "./previewTimingPatch"; + +afterEach(() => { + document.body.innerHTML = ""; +}); + +function preview(): HTMLIFrameElement { + const iframe = document.createElement("iframe"); + document.body.appendChild(iframe); + const doc = iframe.contentDocument!; + doc.open(); + doc.write(` +
+
+
+
`); + doc.close(); + return iframe; +} + +const present = (iframe: HTMLIFrameElement) => + ["root", "a", "host"].filter((id) => iframe.contentDocument!.getElementById(id)); + +it("a timeline delete never removes the root composition, even for a clip it cannot find", () => { + const iframe = preview(); + const unfound = { id: "outro", kind: "composition", compositionSrc: "outro.html" }; + const bare = { id: "main", kind: "composition", compositionSrc: "missing.html" }; + removeIframeTimelineElements( + iframe, + [unfound, bare] as unknown as TimelineElement[], + "index.html", + ); + expect(present(iframe)).toEqual(["root", "a", "host"]); + + const host = { id: "intro", kind: "composition", compositionSrc: "intro.html" }; + removeIframeTimelineElements(iframe, [host] as unknown as TimelineElement[], "index.html"); + expect(present(iframe)).toEqual(["root", "a"]); +}); diff --git a/packages/studio/src/hooks/previewTimingPatch.ts b/packages/studio/src/hooks/previewTimingPatch.ts index eebed48988..e820f8cdcb 100644 --- a/packages/studio/src/hooks/previewTimingPatch.ts +++ b/packages/studio/src/hooks/previewTimingPatch.ts @@ -2,7 +2,11 @@ import { applyAuthoredTiming, RUNTIME_STAMPED_ATTR } from "@hyperframes/core/stu 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 { + previewDocumentCopy, + previewFrameOpaque, + previewRequest, +} from "../player/lib/previewChannel"; import { editPreviewElement, queryPreviewElements } from "../player/lib/previewElements"; import { findPreviewElementForSelection, @@ -38,34 +42,62 @@ export function patchIframeDomTiming( } } +function findSealedTimelineElement( + iframe: HTMLIFrameElement, + element: TimelineElement, + activeCompositionPath: string | null, +) { + if (element.kind === "composition" && element.compositionSrc) + return findPreviewElementForTimelineElement(iframe, element, { + activeCompositionPath, + isMasterView: true, + }); + return findPreviewElementForSelection( + iframe, + { + hfId: element.hfId, + id: element.domId, + selector: element.selector, + selectorIndex: element.selectorIndex, + sourceFile: element.sourceFile || activeCompositionPath || "index.html", + }, + activeCompositionPath, + ); +} + 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, - ); + const found = await findSealedTimelineElement(iframe, element, activeCompositionPath); if (!found) return; const attributes: Array<[string, string | null]> = [...attrs, [RUNTIME_STAMPED_ATTR, null]]; await editPreviewElement(iframe, found.handle, { attributes }).drawn; } +export function removeIframeTimelineElements( + iframe: HTMLIFrameElement | null, + elements: TimelineElement[], + activeCompositionPath: string | null = null, +): void { + if (iframe && previewFrameOpaque(iframe)) { + inOrder(iframe, async () => { + const found = await Promise.all( + elements.map((element) => + findSealedTimelineElement(iframe, element, activeCompositionPath), + ), + ); + const handles = found.flatMap((element) => (element ? [element.handle] : [])); + if (handles.length) await previewRequest(iframe, "remove-elements", { handles }); + }); + return; + } + for (const element of elements) + findTimelineElementInIframe(iframe, element, activeCompositionPath)?.remove(); +} + function patchIframeRootDuration(iframe: HTMLIFrameElement | null, contentEnd: number): void { if (iframe && previewFrameOpaque(iframe)) { inOrder(iframe, async () => diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.ts index f4efe2ed27..1a8eb55042 100644 --- a/packages/studio/src/hooks/timelineEditingHelpers.ts +++ b/packages/studio/src/hooks/timelineEditingHelpers.ts @@ -115,17 +115,6 @@ export function findTimelineElementInDocument( return null; } } -/** 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( - iframe: HTMLIFrameElement | null, - elements: TimelineElement[], - activeCompositionPath: string | null = null, -): void { - for (const element of elements) - findTimelineElementInIframe(iframe, element, activeCompositionPath)?.remove(); -} - // fallow-ignore-next-line complexity function resolveResizePlaybackStart( original: string, diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index 17fd1cd4c9..0a20bcb3e5 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -9,13 +9,9 @@ import { usePlayerStore } from "../player"; import { saveServerRewriteWithHistory, type RecordEditInput } from "../utils/studioFileHistory"; import { studioWriteHeaders } from "../utils/studioFileVersion"; import { deletedNotice, getTimelineElementLabel } from "../utils/studioHelpers"; -import { - buildPatchTarget, - removeIframeTimelineElements, - syncCompositionDurationWithEnd, -} from "./timelineEditingHelpers"; +import { buildPatchTarget, syncCompositionDurationWithEnd } from "./timelineEditingHelpers"; import { timingGestureStep } from "./timelineTimingSync"; -import { captureDurationRollback } from "./previewTimingPatch"; +import { captureDurationRollback, removeIframeTimelineElements } from "./previewTimingPatch"; import { setLinkInSource } from "../components/editor/mediaLinkEdits"; import { resolveMainTrackDeleteRippleShifts,