Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): a deleted clip leaves the timeline as soon as the file drops it (#4447)
Miguel Ángel65a266b29d47
diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.tsindex cfd64d3988..7e21adce9f 100644--- a/packages/studio/src/hooks/timelineEditingHelpers.ts+++ b/packages/studio/src/hooks/timelineEditingHelpers.ts@@ -182,6 +182,17 @@ export function patchIframeDomTiming(}}+/** 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();+}+export function playbackStartAttributeForElement(element: Pick<TimelineElement, "kind" | "playbackStartAttr">,): "data-media-start" | "data-playback-start" {diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsxindex add8d450f3..8bef8f57e0 100644--- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx+++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx@@ -2,7 +2,7 @@import { act } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { TimelineElement } from "../player";+import { usePlayerStore, type TimelineElement } from "../player";import { applyRippleShifts, useTimelineDeleteOps } from "./useTimelineDeleteOps";import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";import { useTrackPendingTimelineEdit } from "./useTrackPendingTimelineEdit";@@ -78,9 +78,30 @@ describe("useTimelineDeleteOps: ripple undo label", () => {return null;}mountReactHarness(<Harness />);- return { b: elements[1], getHook: () => hook! };+ return { elements, b: elements[1], getHook: () => hook! };}+ it("drops the deleted clip from the timeline while the ripple is still saving", async () => {+ let finishRipple = () => {};+ const handleTimelineGroupMove = vi.fn(+ () => new Promise<void>((resolve) => (finishRipple = resolve)),+ );+ const { elements, b, getHook } = mountDeleteHarness({ handleTimelineGroupMove });+ usePlayerStore.getState().setElements(elements);++ let deleting = Promise.resolve();+ await act(async () => {+ deleting = getHook().handleTimelineElementDelete(b);+ await vi.waitFor(() => expect(handleTimelineGroupMove).toHaveBeenCalled());+ });+ expect(usePlayerStore.getState().elements.map((e) => e.id)).toEqual(["hf-a", "hf-c"]);++ await act(async () => {+ finishRipple();+ await deleting;+ });+ });+// editHistory.ts's coalescing keeps the LAST recordEdit call's label, so the// folded ripple move must carry the delete's label, not its own.it("passes the delete's own label to the folded ripple move, not 'Move timeline clips'", async () => {@@ -228,3 +249,65 @@ describe("useTimelineDeleteOps: undo race", () => {});});});++// Regression: the live preview kept a deleted clip until its reload landed, and composition+// enrichment re-read it from there, so the clip stayed drawn after the file dropped it.+describe("useTimelineDeleteOps: live preview", () => {+ const html = `<!DOCTYPE html><html data-composition-variables='[]'><body>+<div data-hf-id="hf-stage" data-composition-id="main" data-duration="4">+<div data-hf-id="hf-a" data-start="0" data-duration="2"></div>+<div data-hf-id="hf-b" data-start="2" data-duration="2"></div>+</div>+</body></html>`;++ beforeEach(() => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(JSON.stringify({ changed: true, content: html }))),+ );+ });++ afterEach(() => {+ document.body.innerHTML = "";+ vi.unstubAllGlobals();+ });++ it("takes the deleted clip out of the live preview before its reload", async () => {+ const preview = document.implementation.createHTMLDocument();+ preview.documentElement.innerHTML = html;+ const iframe = { contentDocument: preview } as unknown as HTMLIFrameElement;+ const clip = (id: string, start: number): TimelineElement => ({+ id,+ tag: "div",+ start,+ duration: 2,+ track: 0,+ hfId: id,+ sourceFile: "index.html",+ });+ const elements = [clip("hf-a", 0), clip("hf-b", 2)];+ let hook: ReturnType<typeof useTimelineDeleteOps> | null = null;+ function Harness() {+ hook = useTimelineDeleteOps({+ projectIdRef: { current: "test-project" },+ activeCompPath: "index.html",+ timelineElements: elements,+ showToast: vi.fn(),+ writeProjectFile: vi.fn().mockResolvedValue(undefined),+ recordEdit: vi.fn().mockResolvedValue(undefined),+ reloadPreview: vi.fn(),+ previewIframeRef: { current: iframe },+ handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined),+ });+ return null;+ }+ mountReactHarness(<Harness />);++ await act(async () => {+ await hook!.handleTimelineElementDelete(elements[1]);+ });++ expect(preview.querySelector('[data-hf-id="hf-b"]')).toBeNull();+ expect(preview.querySelector('[data-hf-id="hf-a"]')).not.toBeNull();+ });+});diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.tsindex 5c0a297dd7..a2240206c5 100644--- a/packages/studio/src/hooks/useTimelineDeleteOps.ts+++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts@@ -8,7 +8,7 @@ import { usePlayerStore } from "../player";import { saveProjectFilesWithHistory, type RecordEditInput } from "../utils/studioFileHistory";import { studioWriteHeaders } from "../utils/studioFileVersion";import { getTimelineElementLabel } from "../utils/studioHelpers";-import { buildPatchTarget } from "./timelineEditingHelpers";+import { buildPatchTarget, removeIframeTimelineElements } from "./timelineEditingHelpers";import { captureDurationRollback, readFileContent } from "./timelineTimingSync";import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";import { furthestClipEndFromSource } from "../player/lib/timelineElementHelpers";@@ -172,6 +172,7 @@ export function useTimelineDeleteOps({throw error;}+ removeIframeTimelineElements(previewIframeRef.current, sameFile, activeCompPath);const deletedKeys = new Set(sameFile.map((te) => te.key ?? te.id));const survivors = timelineElements.filter((te) => !deletedKeys.has(te.key ?? te.id));@@ -184,10 +185,11 @@ export function useTimelineDeleteOps({sameFile,usePlayerStore.getState().rippleEditEnabled,);- let rippleApplied: TimelineGroupMoveChange[] | null = null;+ const rippleChanges = rippleShifts ? resolveShiftedElements(survivors, rippleShifts) : null;+ // The timeline follows the delete's write at once, as the owner of the ripple's optimistic update.+ usePlayerStore.getState().setElements(applyRippleShifts(survivors, rippleChanges));let rippleFailed = false;- if (rippleShifts) {- const rippleChanges = resolveShiftedElements(survivors, rippleShifts);+ if (rippleChanges) {try {await handleTimelineGroupMove(rippleChanges, {coalesceKey,@@ -200,18 +202,17 @@ export function useTimelineDeleteOps({// the generic one would tell the user about one action twice.suppressFailureToast: true,});- rippleApplied = rippleChanges;} catch (error) {// The delete already committed; a failed ripple leaves the gap the// toggle-off behaviour would have left anyway — not worth undoing// an otherwise-successful delete over.rippleFailed = true;+ usePlayerStore.getState().setElements(survivors);console.error("[Timeline] ripple-edit failed to persist after delete", error);showToast("Clip deleted, but the gap could not be closed.", "error");}}- usePlayerStore.getState().setElements(applyRippleShifts(survivors, rippleApplied));usePlayerStore.getState().setSelectedElementId(null);usePlayerStore.getState().setSelectedElementIds(new Set());forceReloadSdkSession?.();@@ -224,7 +225,7 @@ export function useTimelineDeleteOps({"info",);}- if (rippleApplied && !rippleNoticeShownRef.current) {+ if (rippleChanges && !rippleFailed && !rippleNoticeShownRef.current) {rippleNoticeShownRef.current = true;showToast("Ripple closed the gap on the main track. Undo (⌘Z) restores it, or turn off " +