Skip to content

Write HTML. Render video. Built for agents.

feat(studio): operators get a magnetic main track that closes gaps on delete (#4069)

Miguel Ángel8fe480c0a0a4
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index 362999fc81..525bc6396a 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -292,6 +292,7 @@ export function StudioApp() {
sdkSession: editFlowSdkSession,
publishSdkSession: sdkHandle.publish,
forceReloadSdkSession: sdkHandle.forceReload,
+ handleTimelineElementsDelete: timelineEditing.handleTimelineElementsDelete,
});
domEditSelectionBridgeRef.current = domEditSession.domEditSelection;
handleDomZIndexReorderCommitRef.current = domEditSession.handleDomZIndexReorderCommit;
diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx
index 12cde02a6c..5304c7c39d 100644
--- a/packages/studio/src/components/TimelineToolbar.tsx
+++ b/packages/studio/src/components/TimelineToolbar.tsx
@@ -1,5 +1,11 @@
import { useEffect, useRef } from "react";
-import { Image, Magnet, MagnifyingGlassMinus, MagnifyingGlassPlus } from "@phosphor-icons/react";
+import {
+ Image,
+ Magnet,
+ MagnifyingGlassMinus,
+ MagnifyingGlassPlus,
+ Waves,
+} from "@phosphor-icons/react";
import {
useEnableKeyframes,
isPlayheadWithinTween,
@@ -126,6 +132,8 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
const setActiveTool = usePlayerStore((s) => s.setActiveTool);
const timelineSnapEnabled = usePlayerStore((s) => s.timelineSnapEnabled);
const setTimelineSnapEnabled = usePlayerStore((s) => s.setTimelineSnapEnabled);
+ const rippleEditEnabled = usePlayerStore((s) => s.rippleEditEnabled);
+ const setRippleEditEnabled = usePlayerStore((s) => s.setRippleEditEnabled);
const autoKeyframeEnabled = usePlayerStore((s) => s.autoKeyframeEnabled);
const setAutoKeyframeEnabled = usePlayerStore((s) => s.setAutoKeyframeEnabled);
const thumbnailMode = usePlayerStore((s) => s.thumbnailMode);
@@ -228,6 +236,23 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
<Magnet size={16} weight="bold" aria-hidden="true" />
</button>
</Tooltip>
+ <Tooltip
+ label={
+ rippleEditEnabled
+ ? "Ripple on — keeps the main track gapless"
+ : "Ripple off — deleting a main-track clip leaves a gap"
+ }
+ >
+ <button
+ type="button"
+ onClick={() => setRippleEditEnabled(!rippleEditEnabled)}
+ aria-label="Toggle ripple edit"
+ aria-pressed={rippleEditEnabled}
+ className={rippleEditEnabled ? flatActive : flatIdle}
+ >
+ <Waves size={16} weight="bold" aria-hidden="true" />
+ </button>
+ </Tooltip>
{/* Always rendered (CapCut-style): with no keyframeable selection the
button fades to a disabled state instead of unmounting, so the
toolbar layout never shifts. */}
diff --git a/packages/studio/src/hooks/domEditDeleteMembers.test.ts b/packages/studio/src/hooks/domEditDeleteMembers.test.ts
new file mode 100644
index 0000000000..4d0250bb2f
--- /dev/null
+++ b/packages/studio/src/hooks/domEditDeleteMembers.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { timelineElementsForDelete } from "./domEditDeleteMembers";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import type { TimelineElement } from "../player";
+
+const sel = (id: string, sourceFile = "index.html") => ({ id, sourceFile }) as DomEditSelection;
+
+const clip = (id: string, domId: string, sourceFile = "index.html"): TimelineElement =>
+ ({ id, domId, sourceFile, tag: "video", start: 0, duration: 1, track: 0 }) as TimelineElement;
+
+describe("timelineElementsForDelete", () => {
+ it("resolves every member to its exact timeline row", () => {
+ const elements = [clip("a", "clip-a"), clip("b", "clip-b")];
+ const result = timelineElementsForDelete([sel("clip-a"), sel("clip-b")], elements);
+ expect(result).toEqual([elements[0], elements[1]]);
+ });
+
+ it("returns null when any member has no timeline row of its own", () => {
+ const elements = [clip("a", "clip-a")];
+ // "plain-child" is not a timeline element — a nested DOM node inside a clip.
+ const result = timelineElementsForDelete([sel("clip-a"), sel("plain-child")], elements);
+ expect(result).toBeNull();
+ });
+
+ it("does not fall back to the ancestor clip for a nested child", () => {
+ // A click inside a clip must not resolve to (and so delete) the whole clip.
+ const elements = [clip("a", "clip-a")];
+ expect(timelineElementsForDelete([sel("nested-text")], elements)).toBeNull();
+ });
+});
diff --git a/packages/studio/src/hooks/domEditDeleteMembers.ts b/packages/studio/src/hooks/domEditDeleteMembers.ts
index cc3a1fae08..ed4bb733ec 100644
--- a/packages/studio/src/hooks/domEditDeleteMembers.ts
+++ b/packages/studio/src/hooks/domEditDeleteMembers.ts
@@ -7,6 +7,8 @@
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import type { EditHistoryKind } from "../utils/editHistory";
+import type { TimelineElement } from "../player";
+import { findMatchingTimelineElementId } from "../utils/studioHelpers";
/** One entry in the studio's edit history, as `useDomEditSession`'s caller
* supplies it. */
@@ -32,3 +34,20 @@ export function membersForDelete(
): DomEditSelection[] {
return options?.expandGroup && group.length > 0 ? group : [selection];
}
+
+/** The timeline row for each member, only when EVERY member is one — a mixed
+ * group stays on the DOM path. Exact-identity match only, no ancestor
+ * fallback: a click inside a clip must not delete the whole clip. */
+export function timelineElementsForDelete(
+ members: readonly DomEditSelection[],
+ elements: TimelineElement[],
+): TimelineElement[] | null {
+ const matches: TimelineElement[] = [];
+ for (const member of members) {
+ const id = findMatchingTimelineElementId(member, elements);
+ const match = id ? elements.find((el) => (el.key ?? el.id) === id) : undefined;
+ if (!match) return null;
+ matches.push(match);
+ }
+ return matches;
+}
diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts
index 36dc21207b..6937deba05 100644
--- a/packages/studio/src/hooks/useDomEditCommits.ts
+++ b/packages/studio/src/hooks/useDomEditCommits.ts
@@ -456,20 +456,19 @@ export function useDomEditCommits({
// ── Element lifecycle (delete, z-index reorder) ──
- const { handleDomEditElementDelete, handleDomEditElementsDelete, handleDomZIndexReorderCommit } =
- useElementLifecycleOps({
- activeCompPath,
- showToast,
- writeProjectFile,
- editHistory,
- projectIdRef,
- reloadPreview,
- clearDomSelection,
- onTrySdkDelete,
- onReorderShadow,
- forceReloadSdkSession,
- commitDomEditPatchBatches,
- });
+ const { handleDomEditElementsDelete, handleDomZIndexReorderCommit } = useElementLifecycleOps({
+ activeCompPath,
+ showToast,
+ writeProjectFile,
+ editHistory,
+ projectIdRef,
+ reloadPreview,
+ clearDomSelection,
+ onTrySdkDelete,
+ onReorderShadow,
+ forceReloadSdkSession,
+ commitDomEditPatchBatches,
+ });
return {
resolveImportedFontAsset,
@@ -491,7 +490,6 @@ export function useDomEditCommits({
handleDomBoxSizeCommit,
handleDomRotationCommit,
handleDomManualEditsReset,
- handleDomEditElementDelete,
handleDomEditElementsDelete,
handleDomZIndexReorderCommit,
};
diff --git a/packages/studio/src/hooks/useDomEditSession.test.tsx b/packages/studio/src/hooks/useDomEditSession.test.tsx
index 9bfc359604..1a1edea7d8 100644
--- a/packages/studio/src/hooks/useDomEditSession.test.tsx
+++ b/packages/studio/src/hooks/useDomEditSession.test.tsx
@@ -6,6 +6,7 @@ import { shouldUseSdkCutover } from "../utils/sdkCutover";
import type { PatchOperation } from "../utils/sourcePatcher";
import type { Composition } from "@hyperframes/sdk";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import type { TimelineElement } from "../player";
import type { UseDomEditSessionParams } from "./useDomEditSession";
const styleOp = (property: string, value: string): PatchOperation => ({
@@ -97,6 +98,7 @@ function createSessionParams(
syncPreviewHotkeys: vi.fn(),
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
+ handleTimelineElementsDelete: vi.fn(),
...overrides,
};
}
@@ -105,6 +107,7 @@ vi.mock("../utils/sdkResolverShadow", () => ({
runResolverShadow: vi.fn(),
recordResolverParity: (...args: unknown[]) => recordResolverParity(...args),
}));
+const handleDomEditElementsDeleteMock = vi.fn(async () => ({ ok: true }) as const);
vi.mock("./useDomEditCommits", () => ({
useDomEditCommits: (params: { onReorderShadow?: (targets: string[]) => void }) => {
capturedOnReorderShadow.fn = params.onReorderShadow;
@@ -120,7 +123,7 @@ vi.mock("./useDomEditCommits", () => ({
handleDomRemoveTextField: vi.fn(),
handleDomBoxSizeCommit: vi.fn(),
handleDomManualEditsReset: vi.fn(),
- handleDomEditElementDelete: vi.fn(),
+ handleDomEditElementsDelete: handleDomEditElementsDeleteMock,
handleDomZIndexReorderCommit: vi.fn(),
};
},
@@ -461,3 +464,89 @@ describe("handleGroupSelection with audio in the selection", () => {
expect(groupSelectionSpy).toHaveBeenCalledTimes(1);
});
});
+
+// ── Delete routing: a timeline row goes through the timeline's own delete op ──
+
+describe("handleDomEditElementDelete routing", () => {
+ const domSel = (id: string): DomEditSelection =>
+ ({
+ id,
+ element: document.createElement("div"),
+ sourceFile: "index.html",
+ }) as unknown as DomEditSelection;
+
+ async function deleteViaSession(
+ selection: DomEditSelection,
+ timelineElements: TimelineElement[],
+ options?: { expandGroup?: boolean; group?: DomEditSelection[] },
+ ) {
+ const { useDomEditSession } = await import("./useDomEditSession");
+ handleDomEditElementsDeleteMock.mockClear();
+ domEditGroupSelectionsRef.current = options?.group ?? [];
+ const handleTimelineElementsDelete = vi.fn(async () => {});
+ const captured: {
+ fn?: (selection: DomEditSelection, options?: { expandGroup?: boolean }) => Promise<void>;
+ } = {};
+ function Probe() {
+ captured.fn = useDomEditSession(
+ createSessionParams({ timelineElements, handleTimelineElementsDelete }),
+ ).handleDomEditElementDelete;
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(<Probe />));
+ await act(async () => captured.fn?.(selection, { expandGroup: options?.expandGroup }));
+ act(() => root.unmount());
+ domEditGroupSelectionsRef.current = [];
+ return { handleTimelineElementsDelete };
+ }
+
+ it("hands a selection that IS a timeline row to the timeline delete op, not the REST path", async () => {
+ const clip = {
+ id: "clip-a",
+ domId: "clip-a",
+ sourceFile: "index.html",
+ tag: "video",
+ start: 0,
+ duration: 2,
+ track: 0,
+ } as TimelineElement;
+ const { handleTimelineElementsDelete } = await deleteViaSession(domSel("clip-a"), [clip]);
+ expect(handleTimelineElementsDelete).toHaveBeenCalledWith([clip]);
+ expect(handleDomEditElementsDeleteMock).not.toHaveBeenCalled();
+ });
+
+ it("falls through to the REST path for a selection with no timeline row of its own", async () => {
+ const { handleTimelineElementsDelete } = await deleteViaSession(domSel("nested-child"), []);
+ expect(handleTimelineElementsDelete).not.toHaveBeenCalled();
+ expect(handleDomEditElementsDeleteMock).toHaveBeenCalledWith([domSel("nested-child")]);
+ });
+
+ it("expands a multi-member marquee group to the timeline op when every member resolves", async () => {
+ const clipA = {
+ id: "clip-a",
+ domId: "clip-a",
+ sourceFile: "index.html",
+ tag: "video",
+ start: 0,
+ duration: 2,
+ track: 0,
+ } as TimelineElement;
+ const clipB = {
+ id: "clip-b",
+ domId: "clip-b",
+ sourceFile: "index.html",
+ tag: "video",
+ start: 2,
+ duration: 2,
+ track: 0,
+ } as TimelineElement;
+ const group = [domSel("clip-a"), domSel("clip-b")];
+ const { handleTimelineElementsDelete } = await deleteViaSession(group[0], [clipA, clipB], {
+ expandGroup: true,
+ group,
+ });
+ expect(handleTimelineElementsDelete).toHaveBeenCalledWith([clipA, clipB]);
+ expect(handleDomEditElementsDeleteMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index ffa72cce03..e9d4d819a5 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -1,6 +1,7 @@
import { useCallback } from "react";
import { trackStudioEvent } from "../utils/studioTelemetry";
import { isAudioDomElement } from "../utils/timelineInspector";
+import type { TimelineElement } from "../player";
import type { ImportedFontAsset } from "../components/editor/fontAssets";
import type { RightPanelTab } from "../utils/studioHelpers";
import type { PatchTarget } from "../utils/sourcePatcher";
@@ -20,7 +21,7 @@ import { useGsapAwareEditing } from "./useGsapAwareEditing";
import { useStudioSelectionPublisher } from "./useStudioSelectionPublisher";
import { useKeyframeEaseCommits } from "./useKeyframeEaseCommits";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
-import { membersForDelete } from "./domEditDeleteMembers";
+import { membersForDelete, timelineElementsForDelete } from "./domEditDeleteMembers";
import type { RecordEditInput } from "./domEditDeleteMembers";
import type { DomEditTimelineParams } from "./useDomSelectionTypes";
// Re-exported: the delete rule lives in its own module now, and callers (and its
@@ -57,6 +58,9 @@ export interface UseDomEditSessionParams extends DomEditTimelineParams {
sdkSession?: Composition | null;
publishSdkSession?: PublishSdkSession;
forceReloadSdkSession?: () => void;
+ /** The timeline context menu's delete op — a canvas selection that IS a
+ * timeline row hands off here instead of the REST remove-elements path. */
+ handleTimelineElementsDelete: (elements: TimelineElement[]) => Promise<void>;
}
export function useDomEditSession({
@@ -98,6 +102,7 @@ export function useDomEditSession({
sdkSession,
publishSdkSession,
forceReloadSdkSession,
+ handleTimelineElementsDelete,
}: UseDomEditSessionParams) {
const isMasterView = !activeCompPath || activeCompPath === "index.html";
void _setRefreshKey;
@@ -249,11 +254,9 @@ export function useDomEditSession({
forceReloadSdkSession,
onTrySdkPersist: sdkSession
? (selection, operations, originalContent, targetPath, options) => {
- // Resolver shadow runs regardless of the cutover flag — decoupled tripwire.
- // Pass originalContent so the runtime-node filter can suppress hf-ids
- // absent from source (script-created nodes the SDK can't model), and
- // the paths so cross-file edits (session models only the active comp)
- // skip instead of emitting structural element_not_found noise.
+ // Decoupled tripwire, runs regardless of the cutover flag. originalContent lets
+ // the runtime-node filter suppress hf-ids absent from source (script-created
+ // nodes); the paths let a cross-file edit skip instead of a false not-found.
runResolverShadow(sdkSession, selection.hfId, operations, originalContent, {
targetPath,
compositionPath: activeCompPath,
@@ -287,9 +290,8 @@ export function useDomEditSession({
publishSession: publishSdkSession,
})
: undefined,
- // Resolver shadow for the z-index reorder edit: it takes the server path (no
- // SDK persist), but the tripwire is decoupled from cutover — record whether
- // the SDK resolves each reordered element (the reorderElements op's targets).
+ // Z-index reorder takes the server path (no SDK persist); this decoupled
+ // tripwire still records whether the SDK resolves each reordered target.
onReorderShadow: sdkSession
? (targets: string[]) => {
// Single-flight: every target in one reorder batch shares the same file, so
@@ -320,17 +322,28 @@ export function useDomEditSession({
const handleDomEditElementDelete = useCallback(
async (selection: DomEditSelection, options?: { expandGroup?: boolean }) => {
- // Same structural edit the timeline delete refuses mid-recording, so it
- // refuses here too — this is now the path a Delete press takes whenever
- // the canvas holds a selection.
+ // Same structural edit the timeline delete refuses mid-recording.
if (isRecordingRef?.current) {
showToast("Cannot edit timeline while recording", "error");
return;
}
const members = membersForDelete(selection, domEditGroupSelectionsRef.current, options);
+ // A selection that is itself timeline rows shares the context menu's delete op.
+ const timelineTargets = timelineElementsForDelete(members, timelineElements);
+ if (timelineTargets) {
+ await handleTimelineElementsDelete(timelineTargets);
+ return;
+ }
await handleDomEditElementsDelete(members);
},
- [domEditGroupSelectionsRef, handleDomEditElementsDelete, isRecordingRef, showToast],
+ [
+ domEditGroupSelectionsRef,
+ handleDomEditElementsDelete,
+ handleTimelineElementsDelete,
+ isRecordingRef,
+ showToast,
+ timelineElements,
+ ],
);
const handleGroupSelection = useCallback(() => {
@@ -341,14 +354,8 @@ export function useDomEditSession({
showToast("Select at least 2 elements to group", "info");
return;
}
- // A layout group is a positioned wrapper: it takes the members' bounding
- // box, rebases each child's left/top against it, and adopts the topmost
- // z-index. An <audio> clip has no box — offsetWidth/Height are 0 — so
- // grouping audio produced a 0x0 div with inline left/top written onto
- // elements that have never been laid out, and the timeline gained a
- // wrapper standing for nothing audible. The audio answer to "these clips
- // belong together" is an <hf-audio-group> bus, which the timeline's own FX
- // pointer creates, so the refusal names it rather than just declining.
+ // A layout group takes the members' bounding box; audio has no box (0x0),
+ // so it groups into an <hf-audio-group> bus via the track's FX pointer instead.
if (members.some((m) => isAudioDomElement(m.element))) {
showToast(
members.every((m) => isAudioDomElement(m.element))
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.ts
index c5d9512e82..15a45194ca 100644
--- a/packages/studio/src/hooks/useElementLifecycleOps.ts
+++ b/packages/studio/src/hooks/useElementLifecycleOps.ts
@@ -389,15 +389,7 @@ export function useElementLifecycleOps({
[commitDomEditPatchBatches, onReorderShadow],
);
- const handleDomEditElementDelete = useCallback(
- async (selection: DomEditSelection) => {
- await handleDomEditElementsDelete([selection]);
- },
- [handleDomEditElementsDelete],
- );
-
return {
- handleDomEditElementDelete,
handleDomEditElementsDelete,
handleDomZIndexReorderCommit,
};
diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
new file mode 100644
index 0000000000..682cb5e829
--- /dev/null
+++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
@@ -0,0 +1,119 @@
+// @vitest-environment happy-dom
+
+import { act } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { TimelineElement } from "../player";
+import { applyRippleShifts, useTimelineDeleteOps } from "./useTimelineDeleteOps";
+import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";
+
+installReactActEnvironment();
+
+function el(id: string, start: number, duration: number, track = 0): TimelineElement {
+ return { id, tag: "video", start, duration, track, domId: id };
+}
+
+describe("applyRippleShifts", () => {
+ it("returns survivors unchanged when there are no changes", () => {
+ const survivors = [el("a", 0, 2), el("c", 8, 1)];
+ expect(applyRippleShifts(survivors, null)).toBe(survivors);
+ });
+
+ it("rewrites only the starts named by the changes", () => {
+ const survivors = [el("a", 0, 2), el("c", 8, 1)];
+ const result = applyRippleShifts(survivors, [{ element: survivors[1], start: 2 }]);
+ expect(result).toEqual([el("a", 0, 2), el("c", 2, 1)]);
+ expect(result[0]).toBe(survivors[0]);
+ });
+});
+
+describe("useTimelineDeleteOps: ripple undo label", () => {
+ const html = `<!DOCTYPE html><html data-composition-variables='[]'><body>
+<div data-hf-id="hf-stage" data-hf-root data-duration="6">
+<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 data-hf-id="hf-c" data-start="4" data-duration="2"></div>
+</div>
+</body></html>`;
+
+ beforeEach(() => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes("/file-mutations/remove-element/")) {
+ return new Response(JSON.stringify({ changed: true, content: html }), { status: 200 });
+ }
+ return new Response(JSON.stringify({ content: html }), { status: 200 });
+ }),
+ );
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+ });
+
+ type DeleteOpsOptions = Parameters<typeof useTimelineDeleteOps>[0];
+
+ function mountDeleteHarness(overrides: {
+ handleTimelineGroupMove: DeleteOpsOptions["handleTimelineGroupMove"];
+ showToast?: DeleteOpsOptions["showToast"];
+ }) {
+ const elements = [el("hf-a", 0, 2), el("hf-b", 2, 2), el("hf-c", 4, 2)];
+ let hook: ReturnType<typeof useTimelineDeleteOps> | null = null;
+ function Harness() {
+ hook = useTimelineDeleteOps({
+ projectIdRef: { current: "test-project" },
+ activeCompPath: "index.html",
+ timelineElements: elements,
+ showToast: overrides.showToast ?? vi.fn(),
+ writeProjectFile: vi.fn().mockResolvedValue(undefined),
+ recordEdit: vi.fn().mockResolvedValue(undefined),
+ reloadPreview: vi.fn(),
+ previewIframeRef: { current: null },
+ handleTimelineGroupMove: overrides.handleTimelineGroupMove,
+ });
+ return null;
+ }
+ mountReactHarness(<Harness />);
+ return { b: elements[1], getHook: () => hook! };
+ }
+
+ // 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 () => {
+ const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined);
+ const { b, getHook } = mountDeleteHarness({ handleTimelineGroupMove });
+
+ await act(async () => {
+ await getHook().handleTimelineElementDelete(b);
+ });
+
+ expect(handleTimelineGroupMove).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ label: "Delete timeline clip" }),
+ );
+ });
+
+ it("shows exactly one toast when a ripple fails to persist after a committed delete", async () => {
+ const handleTimelineGroupMove = vi.fn().mockRejectedValue(new Error("persist failed"));
+ const showToast = vi.fn();
+ const { b, getHook } = mountDeleteHarness({ handleTimelineGroupMove, showToast });
+
+ await act(async () => {
+ await getHook().handleTimelineElementDelete(b);
+ });
+
+ // The user did one thing (delete); the generic move-failure toast is
+ // suppressed on this call so only the specific message reaches them.
+ expect(showToast).toHaveBeenCalledTimes(1);
+ expect(showToast).toHaveBeenCalledWith(
+ "Clip deleted, but the gap could not be closed.",
+ "error",
+ );
+ expect(handleTimelineGroupMove).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ suppressFailureToast: true }),
+ );
+ });
+});
diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts
index 03a01f9869..5c0a297dd7 100644
--- a/packages/studio/src/hooks/useTimelineDeleteOps.ts
+++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts
@@ -2,7 +2,7 @@ import { buildProjectApiPath } from "../utils/projectRouting";
// Timeline clip deletion: the marquee/multi path and the single-clip wrapper
// the context menu uses. Extracted verbatim from useTimelineEditing.ts to keep
// it under the studio 600-line cap, following useTimelineAssetDropOps.
-import { useCallback, type MutableRefObject, type RefObject } from "react";
+import { useCallback, useRef, type MutableRefObject, type RefObject } from "react";
import type { TimelineElement } from "../player";
import { usePlayerStore } from "../player";
import { saveProjectFilesWithHistory, type RecordEditInput } from "../utils/studioFileHistory";
@@ -12,6 +12,28 @@ import { buildPatchTarget } from "./timelineEditingHelpers";
import { captureDurationRollback, readFileContent } from "./timelineTimingSync";
import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";
import { furthestClipEndFromSource } from "../player/lib/timelineElementHelpers";
+import {
+ resolveMainTrackDeleteRippleShifts,
+ resolveShiftedElements,
+} from "../player/components/timelineGapCommit";
+import type {
+ TimelineGroupCommitOptions,
+ TimelineGroupMoveChange,
+} from "./useTimelineGroupEditing";
+
+/** Apply already-resolved ripple changes to the surviving elements for the
+ * optimistic store update after a delete. Pure — no IO. */
+export function applyRippleShifts(
+ survivors: TimelineElement[],
+ changes: readonly TimelineGroupMoveChange[] | null,
+): TimelineElement[] {
+ if (!changes) return survivors;
+ const newStartByElement = new Map(changes.map((c) => [c.element, c.start]));
+ return survivors.map((te) => {
+ const newStart = newStartByElement.get(te);
+ return newStart != null ? { ...te, start: newStart } : te;
+ });
+}
interface UseTimelineDeleteOpsOptions {
projectIdRef: MutableRefObject<string | null>;
@@ -24,8 +46,20 @@ interface UseTimelineDeleteOpsOptions {
isRecordingRef?: MutableRefObject<boolean>;
forceReloadSdkSession?: () => void;
previewIframeRef: RefObject<HTMLIFrameElement | null>;
+ /** The same atomic multi-clip move commit the track-gap menu uses, reused
+ * to ripple the main track after a delete, folded into the delete's own
+ * undo entry via a shared coalesceKey. */
+ handleTimelineGroupMove: (
+ changes: TimelineGroupMoveChange[],
+ options?: TimelineGroupCommitOptions,
+ ) => Promise<void>;
}
+// Per-gesture-unique coalesce key — a monotonic counter, not Date.now() /
+// Math.random() (determinism rules), mirroring gapCloseGestureSeq in
+// timelineGapCommit.ts.
+let deleteGestureSeq = 0;
+
export function useTimelineDeleteOps({
projectIdRef,
activeCompPath,
@@ -37,7 +71,12 @@ export function useTimelineDeleteOps({
isRecordingRef,
forceReloadSdkSession,
previewIframeRef,
+ handleTimelineGroupMove,
}: UseTimelineDeleteOpsOptions) {
+ // First-use-per-session notice for the ripple. Plain info toast: Studio's
+ // toast system has no action buttons, so Undo and the toggle location are
+ // named in words instead.
+ const rippleNoticeShownRef = useRef(false);
// fallow-ignore-next-line complexity
const handleTimelineElementsDelete = useCallback(
// fallow-ignore-next-line complexity
@@ -109,11 +148,17 @@ export function useTimelineDeleteOps({
usePlayerStore.getState().setDuration(deleteContentEnd);
}
+ // Shared with the ripple move below so a folded ripple is one undo
+ // step with the delete, not two (editHistory.ts coalesces by key +
+ // window across separate recordEdit calls, not by label).
+ const coalesceKey = `main-track-ripple-delete:${deleteGestureSeq++}`;
+ const deleteHistoryLabel = "Delete timeline clip";
try {
await saveProjectFilesWithHistory({
projectId: pid,
- label: "Delete timeline clip",
+ label: deleteHistoryLabel,
kind: "timeline",
+ coalesceKey,
files: { [targetPath]: patchedContent },
readFile: async () => originalContent,
// remove-element already wrote the removal, so disk holds THAT — not the
@@ -128,17 +173,65 @@ export function useTimelineDeleteOps({
}
const deletedKeys = new Set(sameFile.map((te) => te.key ?? te.id));
- usePlayerStore
- .getState()
- .setElements(timelineElements.filter((te) => !deletedKeys.has(te.key ?? te.id)));
+ const survivors = timelineElements.filter((te) => !deletedKeys.has(te.key ?? te.id));
+
+ // Ripple: close the gap the delete left on the main track. Pure decision
+ // first (resolveMainTrackDeleteRippleShifts — off, no main-track clip
+ // deleted, already gapless, or a locked survivor all resolve to null),
+ // then the one write, folded into the delete's undo entry above.
+ const rippleShifts = resolveMainTrackDeleteRippleShifts(
+ survivors,
+ sameFile,
+ usePlayerStore.getState().rippleEditEnabled,
+ );
+ let rippleApplied: TimelineGroupMoveChange[] | null = null;
+ let rippleFailed = false;
+ if (rippleShifts) {
+ const rippleChanges = resolveShiftedElements(survivors, rippleShifts);
+ try {
+ await handleTimelineGroupMove(rippleChanges, {
+ coalesceKey,
+ coalesceMs: Number.POSITIVE_INFINITY,
+ // Coalescing keeps the LAST entry's label; without this the undo
+ // toast reads "Undid Move timeline clips" after a delete, naming
+ // the ripple's mechanics instead of what the user actually did.
+ label: deleteHistoryLabel,
+ // This call gets its own, more specific failure toast below —
+ // 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;
+ 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?.();
reloadPreview();
- showToast(
- `Deleted ${label}. Use Undo to restore ${sameFile.length === 1 ? "it" : "them"}.`,
- "info",
- );
+ // A failed ripple already showed its own toast above; the user did one
+ // thing (delete), so they get one message, not this generic follow-up too.
+ if (!rippleFailed) {
+ showToast(
+ `Deleted ${label}. Use Undo to restore ${sameFile.length === 1 ? "it" : "them"}.`,
+ "info",
+ );
+ }
+ if (rippleApplied && !rippleNoticeShownRef.current) {
+ rippleNoticeShownRef.current = true;
+ showToast(
+ "Ripple closed the gap on the main track. Undo (⌘Z) restores it, or turn off " +
+ "Ripple in the timeline toolbar.",
+ "info",
+ );
+ }
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to delete timeline clip";
showToast(message);
@@ -155,6 +248,7 @@ export function useTimelineDeleteOps({
isRecordingRef,
forceReloadSdkSession,
previewIframeRef,
+ handleTimelineGroupMove,
],
);
diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts
index 85ade9c898..ab6b37df18 100644
--- a/packages/studio/src/hooks/useTimelineEditing.ts
+++ b/packages/studio/src/hooks/useTimelineEditing.ts
@@ -413,6 +413,7 @@ export function useTimelineEditing({
isRecordingRef,
forceReloadSdkSession,
previewIframeRef,
+ handleTimelineGroupMove: groupEditing.handleTimelineGroupMove,
});
const { handleTimelineAssetDrop, handleTimelineFileDrop, handleTimelineCompositionDrop } =
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx
new file mode 100644
index 0000000000..998ae8513f
--- /dev/null
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx
@@ -0,0 +1,74 @@
+// @vitest-environment happy-dom
+
+import { act } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { Root } from "react-dom/client";
+import type { TimelineElement } from "../player";
+import { useTimelineGroupEditing } from "./useTimelineGroupEditing";
+import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";
+
+installReactActEnvironment();
+
+function el(id: string, start: number, duration: number, track = 0): TimelineElement {
+ return { id, tag: "video", start, duration, track, domId: id };
+}
+
+describe("useTimelineGroupEditing: handleTimelineGroupMove suppressFailureToast", () => {
+ let root: Root | null = null;
+
+ afterEach(() => {
+ if (root) act(() => root!.unmount());
+ root = null;
+ document.body.innerHTML = "";
+ });
+
+ type GroupEditingOptions = Parameters<typeof useTimelineGroupEditing>[0];
+
+ // No project id makes enqueueGroupOperation reject before any persist runs,
+ // exercising the move's real catch block without faking the SDK/server path.
+ function mountFailingHarness(showToast: GroupEditingOptions["showToast"]) {
+ let hook: ReturnType<typeof useTimelineGroupEditing> | null = null;
+ function Harness() {
+ hook = useTimelineGroupEditing({
+ activeCompPath: "index.html",
+ editQueueRef: { current: Promise.resolve() },
+ pendingTimelineEditPathRef: { current: new Set() },
+ previewIframeRef: { current: null },
+ projectIdRef: { current: null },
+ recordEdit: vi.fn().mockResolvedValue(undefined),
+ reloadPreview: vi.fn(),
+ showToast,
+ writeProjectFile: vi.fn().mockResolvedValue(undefined),
+ });
+ return null;
+ }
+ root = mountReactHarness(<Harness />);
+ return () => hook!;
+ }
+
+ const change = { element: el("a", 0, 2), start: 2 };
+
+ it("shows no toast when suppressFailureToast is set on a failed move", async () => {
+ const showToast = vi.fn();
+ const getHook = mountFailingHarness(showToast);
+
+ await act(async () => {
+ await expect(
+ getHook().handleTimelineGroupMove([change], { suppressFailureToast: true }),
+ ).rejects.toThrow();
+ });
+
+ expect(showToast).not.toHaveBeenCalled();
+ });
+
+ it("shows one toast when suppressFailureToast is not set on a failed move", async () => {
+ const showToast = vi.fn();
+ const getHook = mountFailingHarness(showToast);
+
+ await act(async () => {
+ await expect(getHook().handleTimelineGroupMove([change])).rejects.toThrow();
+ });
+
+ expect(showToast).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts
index d6faa74d56..17da428e3c 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts
@@ -47,6 +47,15 @@ export interface TimelineGroupCommitOptions {
coalesceKey?: string;
/** Per-entry undo coalesce window override (ms) — see EditHistoryEntry.coalesceMs. */
coalesceMs?: number;
+ /** Overrides the default "Move timeline clips" undo-history label. Coalescing
+ * keeps the LAST entry's label (editHistory.ts), so a mechanical follow-up
+ * move folded into another gesture's coalesceKey (e.g. the ripple after a
+ * delete) should carry that gesture's own label, not its own. */
+ label?: string;
+ /** Skips this call's own generic failure toast (the error is still logged
+ * to the console) — for a caller that shows its own more specific message
+ * on the same failure, so the user isn't told about one action twice. */
+ suppressFailureToast?: boolean;
}
interface UseTimelineGroupEditingOptions {
@@ -272,21 +281,22 @@ export function useTimelineGroupEditing({
syncPreviewContentDuration(previewIframeRef.current);
const coalesceKey = options?.coalesceKey ?? moveCoalesceKey(changes);
const coalesceMs = options?.coalesceMs;
- return enqueueGroupOperation("Move timeline clips", async (projectId) => {
+ const label = options?.label ?? "Move timeline clips";
+ return enqueueGroupOperation(label, async (projectId) => {
await options?.beforeTiming;
const handledBySdk = await trySdkBatchPersist({
changes,
sdkChanges: toSdkTimingChanges(changes, (change) => ({ start: change.start })),
eligible: changes.every((change) => change.track == null),
needsExtension,
- label: "Move timeline clips",
+ label,
coalesceKey,
coalesceMs,
});
if (!handledBySdk) {
await persistServerBatch(
projectId,
- "Move timeline clips",
+ label,
changes.map((change) => ({
element: change.element,
buildPatches: (original, target) =>
@@ -315,7 +325,7 @@ export function useTimelineGroupEditing({
projectId,
iframe: previewIframeRef.current,
reloadPreview,
- label: "Move timeline clips",
+ label,
errorLabel: "Failed to shift GSAP positions",
coalesceKey,
recordEdit,
@@ -336,7 +346,11 @@ export function useTimelineGroupEditing({
// Failed persist: revert the optimistic duration readout + live root
// alongside the gesture owner's store rollback.
rollbackDuration();
- showToast(getStudioSaveErrorMessage(error), "error");
+ if (options?.suppressFailureToast) {
+ console.error("[Timeline] group move failed to persist", error);
+ } else {
+ showToast(getStudioSaveErrorMessage(error), "error");
+ }
throw error;
});
},
diff --git a/packages/studio/src/player/components/timelineGapCommit.test.ts b/packages/studio/src/player/components/timelineGapCommit.test.ts
index 5fdb280398..ec77bf6685 100644
--- a/packages/studio/src/player/components/timelineGapCommit.test.ts
+++ b/packages/studio/src/player/components/timelineGapCommit.test.ts
@@ -5,6 +5,8 @@ import {
canShiftTrackGapClips,
commitCloseAllTrackGaps,
commitCloseTrackGap,
+ resolveMainTrackDeleteRippleShifts,
+ resolveShiftedElements,
} from "./timelineGapCommit";
import { resolveAllTrackGaps } from "./timelineGaps";
@@ -150,6 +152,25 @@ describe("commitCloseAllTrackGaps", () => {
});
});
+describe("resolveShiftedElements", () => {
+ it("maps each shift to its element and new start", () => {
+ const elements = [el("a", 0, 2), el("c", 8, 1)];
+ const resolved = resolveShiftedElements(elements, [{ key: "c", newStart: 2 }]);
+ expect(resolved).toEqual([{ element: elements[1], start: 2 }]);
+ });
+
+ it("resolves by key when present, falling back to id", () => {
+ const withKey: TimelineElement = { ...el("a", 0, 2), key: "a-key" };
+ const resolved = resolveShiftedElements([withKey], [{ key: "a-key", newStart: 5 }]);
+ expect(resolved).toEqual([{ element: withKey, start: 5 }]);
+ });
+
+ it("drops a shift whose key matches no element", () => {
+ const elements = [el("a", 0, 2)];
+ expect(resolveShiftedElements(elements, [{ key: "ghost", newStart: 0 }])).toEqual([]);
+ });
+});
+
describe("canShiftTrackGapClips", () => {
it("is true only when every named clip is movable", () => {
const lane = [el("a", 1, 2), lockedEl("b", 5, 3)];
@@ -161,3 +182,78 @@ describe("canShiftTrackGapClips", () => {
expect(canShiftTrackGapClips([el("a", 0, 1)], [{ key: "ghost", newStart: 0 }])).toBe(false);
});
});
+
+describe("resolveMainTrackDeleteRippleShifts", () => {
+ it("closes the gap left by a deleted main-track clip", () => {
+ const deleted = [el("b", 2, 2)];
+ const survivors = [el("a", 0, 2), el("c", 8, 1)]; // "b" already removed from this set
+ // "c" shifts left by exactly "b"'s 2s duration (8 -> 6), not all the way
+ // to 2: the 4-6..8 span was already an open gap before the delete, and
+ // ripple must not also swallow it.
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deleted, true)).toEqual([
+ { key: "c", newStart: 6 },
+ ]);
+ });
+
+ it("does not also close a pre-existing gap the delete never touched", () => {
+ // a(0-2), b(2-4)[deleted], GAP(4-6), c(6-7): deleting b should slide c
+ // left by b's 2s only, landing at 4 — flush against a, the pre-existing
+ // gap collapsed only because it's now adjacent, not doubly-counted.
+ const deleted = [el("b", 2, 2)];
+ const survivors = [el("a", 0, 2), el("c", 6, 1)];
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deleted, true)).toEqual([
+ { key: "c", newStart: 4 },
+ ]);
+ });
+
+ it("leaves an untouched clip before the delete point exactly where it was", () => {
+ // a(0-2), GAP(2-5), b(5-7)[deleted]: nothing follows b, so nothing
+ // shifts — a keeps its own leading position, ripple included.
+ const deleted = [el("b", 5, 2)];
+ const survivors = [el("a", 0, 2)];
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deleted, true)).toBeNull();
+ });
+
+ it("returns null when ripple is off", () => {
+ const deleted = [el("b", 2, 2)];
+ const survivors = [el("a", 0, 2), el("c", 8, 1)];
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deleted, false)).toBeNull();
+ });
+
+ it("returns null when nothing deleted was on the main track", () => {
+ const deletedOverlay = [el("o", 2, 2, 1)]; // track 1, not main
+ const survivors = [el("a", 0, 2), el("c", 8, 1)];
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deletedOverlay, true)).toBeNull();
+ });
+
+ it("returns null when the survivors are already gapless", () => {
+ const deleted = [el("b", 100, 1)]; // deleted from far off the end
+ const survivors = [el("a", 0, 2), el("c", 2, 1)]; // already contiguous
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deleted, true)).toBeNull();
+ });
+
+ it("refuses the whole ripple (not a partial one) when a shifting survivor is locked", () => {
+ const deleted = [el("b", 2, 2)];
+ const survivors = [el("a", 0, 2), lockedEl("c", 8, 1)];
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deleted, true)).toBeNull();
+ });
+
+ it("ignores audio and non-main-track survivors even when a main-track clip was deleted", () => {
+ const deleted = [el("b", 2, 2)];
+ const survivors = [el("a", 0, 2), el("c", 8, 1), el("overlay", 3, 1, 1)];
+ const shifts = resolveMainTrackDeleteRippleShifts(survivors, deleted, true);
+ expect(shifts).toEqual([{ key: "c", newStart: 6 }]); // "overlay" (track 1) untouched
+ });
+
+ it("sums only the deleted spans that precede each survivor, for a multi-select delete", () => {
+ // a(0-2), b(2-4)[deleted], c(4-6), d(6-8)[deleted], e(8-9): a marquee
+ // delete of b and d in one batch. "c" sits before d, so it shifts by
+ // b's 2s alone; "e" sits after both, so it shifts by their 4s combined.
+ const deleted = [el("b", 2, 2), el("d", 6, 2)];
+ const survivors = [el("a", 0, 2), el("c", 4, 2), el("e", 8, 1)];
+ expect(resolveMainTrackDeleteRippleShifts(survivors, deleted, true)).toEqual([
+ { key: "c", newStart: 2 },
+ { key: "e", newStart: 4 },
+ ]);
+ });
+});
diff --git a/packages/studio/src/player/components/timelineGapCommit.ts b/packages/studio/src/player/components/timelineGapCommit.ts
index 217dc29ac6..a937a15c76 100644
--- a/packages/studio/src/player/components/timelineGapCommit.ts
+++ b/packages/studio/src/player/components/timelineGapCommit.ts
@@ -10,8 +10,11 @@ import {
resolveAllTrackGaps,
resolveCloseGapShifts,
resolveTrackGapAt,
+ round3,
+ TRACK_GAP_EPSILON_S,
type TrackGapShift,
} from "./timelineGaps";
+import { isMainTrackElement } from "./timelineZones";
/**
* Commit layer for the track-gap context menu ("Close gap" / "Close all gaps").
@@ -35,16 +38,29 @@ const keyOf = (e: TimelineElement) => e.key ?? e.id;
// timelineClipDragCommit.ts.
let gapCloseGestureSeq = 0;
-/** True when every clip named in `shifts` may be time-moved. */
+/** Resolve each shift to its named element, dropping any shift whose key
+ * matches nothing — the type stays honest without a non-null assertion. */
+export function resolveShiftedElements(
+ elements: readonly TimelineElement[],
+ shifts: readonly TrackGapShift[],
+): Array<{ element: TimelineElement; start: number }> {
+ const byKey = new Map(elements.map((e) => [keyOf(e), e]));
+ return shifts.flatMap((s) => {
+ const element = byKey.get(s.key);
+ return element ? [{ element, start: s.newStart }] : [];
+ });
+}
+
+/** True when every shift names a real clip that may be time-moved. */
export function canShiftTrackGapClips(
laneElements: readonly TimelineElement[],
shifts: readonly TrackGapShift[],
): boolean {
- const byKey = new Map(laneElements.map((e) => [keyOf(e), e]));
- return shifts.every((s) => {
- const element = byKey.get(s.key);
- return element != null && getTimelineEditCapabilities(element).canMove;
- });
+ const resolved = resolveShiftedElements(laneElements, shifts);
+ return (
+ resolved.length === shifts.length &&
+ resolved.every((r) => getTimelineEditCapabilities(r.element).canMove)
+ );
}
function buildShiftEdits(
@@ -52,11 +68,10 @@ function buildShiftEdits(
shifts: readonly TrackGapShift[],
): TimelineMoveEdit[] | null {
if (shifts.length === 0 || !canShiftTrackGapClips(laneElements, shifts)) return null;
- const byKey = new Map(laneElements.map((e) => [keyOf(e), e]));
- return shifts.map((s) => {
- const element = byKey.get(s.key)!;
- return { element, updates: { start: s.newStart, track: element.track } };
- });
+ return resolveShiftedElements(laneElements, shifts).map(({ element, start }) => ({
+ element,
+ updates: { start, track: element.track },
+ }));
}
function commitShifts(
@@ -101,3 +116,33 @@ export function commitCloseAllTrackGaps(
deps,
);
}
+
+/** What a ripple-edit delete must additionally shift on the main track. Pure
+ * — no IO; the caller persists the shifts itself. Null means nothing to
+ * ripple: off, nothing deleted was on the main track, already gapless, or a
+ * shifting clip is locked (same whole-action refusal as the gap-close menu). */
+export function resolveMainTrackDeleteRippleShifts(
+ survivingElements: readonly TimelineElement[],
+ deletedElements: readonly TimelineElement[],
+ rippleEnabled: boolean,
+): TrackGapShift[] | null {
+ const deletedMainTrack = deletedElements.filter(isMainTrackElement);
+ if (!rippleEnabled || deletedMainTrack.length === 0) return null;
+ const survivors = survivingElements.filter(isMainTrackElement);
+ // Shift each survivor left by the duration of the deleted clips before it —
+ // the removed span itself, not a gap re-resolved on the survivors, which
+ // can't tell an untouched adjacent gap from the one just opened.
+ const shifts: TrackGapShift[] = [];
+ for (const survivor of survivors) {
+ const width = deletedMainTrack
+ .filter((d) => d.start < survivor.start)
+ .reduce((sum, d) => sum + d.duration, 0);
+ if (width <= 0) continue;
+ const newStart = round3(Math.max(laneGapFloor(survivors), survivor.start - width));
+ if (Math.abs(newStart - survivor.start) > TRACK_GAP_EPSILON_S) {
+ shifts.push({ key: keyOf(survivor), newStart });
+ }
+ }
+ if (shifts.length === 0 || !canShiftTrackGapClips(survivors, shifts)) return null;
+ return shifts;
+}
diff --git a/packages/studio/src/player/components/timelineGaps.ts b/packages/studio/src/player/components/timelineGaps.ts
index ce76fa7a25..aef99c1671 100644
--- a/packages/studio/src/player/components/timelineGaps.ts
+++ b/packages/studio/src/player/components/timelineGaps.ts
@@ -13,7 +13,7 @@ import type { TimelineElement } from "../store/playerStore";
* - Computed starts are rounded to millisecond precision, matching the drag
* commit's `round3`.
*/
-const TRACK_GAP_EPSILON_S = 1e-3;
+export const TRACK_GAP_EPSILON_S = 1e-3;
const keyOf = (e: TimelineElement) => e.key ?? e.id;
@@ -28,7 +28,7 @@ const keyOf = (e: TimelineElement) => e.key ?? e.id;
export function laneGapFloor(elements: readonly TimelineElement[]): number {
return Math.max(0, ...elements.map((e) => e.expandedParentStart ?? 0));
}
-const round3 = (v: number) => Math.round(v * 1000) / 1000;
+export const round3 = (v: number) => Math.round(v * 1000) / 1000;
const endOf = (e: TimelineElement) => e.start + e.duration;
/** Lane clips sorted by start (key as a deterministic tie-break). */
diff --git a/packages/studio/src/player/components/timelineZones.test.ts b/packages/studio/src/player/components/timelineZones.test.ts
index 02e721379e..bdf7ab1393 100644
--- a/packages/studio/src/player/components/timelineZones.test.ts
+++ b/packages/studio/src/player/components/timelineZones.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { TimelineElement } from "../store/playerStore";
-import { classifyZone, normalizeToZones } from "./timelineZones";
+import { classifyZone, isMainTrackElement, normalizeToZones } from "./timelineZones";
function el(id: string, tag: string, track: number, duration = 2): TimelineElement {
return { id, tag, start: 0, duration, track };
@@ -55,6 +55,25 @@ describe("classifyZone", () => {
});
});
+describe("isMainTrackElement", () => {
+ it("is true for a visual clip on display track 0", () => {
+ expect(isMainTrackElement(el("v", "video", 0))).toBe(true);
+ });
+
+ it("is false for a visual clip on any other track", () => {
+ expect(isMainTrackElement(el("v", "video", 1))).toBe(false);
+ });
+
+ it("is false for an audio clip even on track 0 (audio-only project has no main track)", () => {
+ expect(isMainTrackElement(el("m", "audio", 0))).toBe(false);
+ });
+
+ it("is false for an inline-expanded sub-composition child on track 0", () => {
+ const child: TimelineElement = { ...el("c", "video", 0), expandedParentStart: 4 };
+ expect(isMainTrackElement(child)).toBe(false);
+ });
+});
+
describe("normalizeToZones — CapCut-stable lanes follow the track-index (never z)", () => {
it("orders visual lanes by authored track-index (ascending), audio at the bottom", () => {
// img (track 0), vid (track 2), mus (audio, track 5). Lanes follow the track
diff --git a/packages/studio/src/player/components/timelineZones.ts b/packages/studio/src/player/components/timelineZones.ts
index 5db1028df4..fc010ec4a5 100644
--- a/packages/studio/src/player/components/timelineZones.ts
+++ b/packages/studio/src/player/components/timelineZones.ts
@@ -2,9 +2,9 @@ import type { TimelineElement } from "../store/playerStore";
import { isAudioTimelineElement } from "../../utils/timelineInspector";
/**
- * Free-form vertical zones, top → bottom: visual, audio. There is no "main track"
- * — canvas layering is CSS z-index (the renderer ignores track index), so the
- * timeline's only job is to keep visual clips grouped above audio clips.
+ * Free-form vertical zones, top → bottom: visual, audio. Canvas layering is
+ * CSS z-index (the renderer ignores track index), so a track's only structural
+ * job is to keep visual clips grouped above audio clips.
*/
export type TrackZone = "visual" | "audio";
@@ -14,6 +14,13 @@ export function classifyZone(el: TimelineElement): TrackZone {
return isAudioTimelineElement(el) ? "audio" : "visual";
}
+/** The "main track" is a convention, not a schema field: the first
+ * visual-zone display lane, matched only when it actually holds a visual
+ * clip and isn't an inline-expanded sub-composition child. */
+export function isMainTrackElement(el: TimelineElement): boolean {
+ return el.track === 0 && classifyZone(el) === "visual" && el.expandedParentStart == null;
+}
+
const keyOf = (el: TimelineElement) => el.key ?? el.id;
const EPS = 1e-6;
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
index 2fd2b802ba..0ee7ee3af2 100644
--- a/packages/studio/src/player/store/playerStore.ts
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -108,14 +108,14 @@ interface PlayerState extends PlayerStoreSlices {
/** Timeline magnet toggle — when false, clip drags/trims/drops never snap. */
timelineSnapEnabled: boolean;
setTimelineSnapEnabled: (enabled: boolean) => void;
+ /** Keeps the main track gapless on delete; distinct from the magnet above. */
+ rippleEditEnabled: boolean;
+ setRippleEditEnabled: (enabled: boolean) => void;
/** Transport + ruler readout: timecode ("time") or frame number ("frame"). */
timeDisplayMode: TimelineTimeDisplayMode;
setTimeDisplayMode: (mode: TimelineTimeDisplayMode) => void;
- /**
- * Pin the timeline zoom to its current visual scale before a duration-changing
- * edit, so a subsequent duration change (which recomputes fit-pps) stops
- * rescaling every clip. No-op once already pinned (mode is "manual").
- */
+ /** Pin the timeline zoom to its current scale before a duration change, so
+ * it stops rescaling every clip. No-op once already pinned. */
pinTimelineZoom: (currentPixelsPerSecond: number, fitPixelsPerSecond: number) => void;
/** The timeline's live pixels-per-second + fit basis, published by <Timeline>. */
timelinePps: number;
@@ -149,26 +149,16 @@ interface PlayerState extends PlayerStoreSlices {
/** Clears project data without creating a new hard-project session. */
reset: () => void;
- /**
- * Request a seek from outside the player loop (e.g. Layers panel).
- * useTimelinePlayer subscribes and calls adapter.seek() + liveTime.notify().
- */
+ /** Request a seek from outside the player loop (e.g. Layers panel);
+ * useTimelinePlayer subscribes and calls adapter.seek() + liveTime.notify(). */
requestedSeekTime: number | null;
requestSeek: (time: number) => void;
clearSeekRequest: () => void;
- /**
- * Request the transport start or stop from outside the player loop.
- *
- * The FX rack auditions a preset by writing it to the running graph, which is
- * silent while the transport is paused — so hovering one has to start
- * playback, and leaving has to put the playhead back where it was. Hovering is
- * not an edit and must not cost the author their place.
- *
- * A nonce rather than a bare boolean: two hovers in a row both want play, and
- * without it the second request is indistinguishable from the first having
- * already been served.
- */
+ /** Request the transport start or stop from outside the player loop: the FX
+ * rack starts playback to audition a preset (silent while paused) and
+ * restores the playhead on leave, without costing the author their place.
+ * A nonce, not a bare boolean, so two hovers in a row both register. */
playbackRequest: { playing: boolean; returnTo: number | null; nonce: number } | null;
requestPlayback: (playing: boolean, returnTo?: number | null) => void;
clearPlaybackRequest: () => void;
@@ -475,6 +465,11 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
writeStudioUiPreferences({ timelineSnapEnabled: enabled });
set({ timelineSnapEnabled: enabled });
},
+ rippleEditEnabled: readStudioUiPreferences().rippleEditEnabled ?? true, // default on
+ setRippleEditEnabled: (enabled) => {
+ writeStudioUiPreferences({ rippleEditEnabled: enabled });
+ set({ rippleEditEnabled: enabled });
+ },
timeDisplayMode: readStudioUiPreferences().timeDisplayMode ?? "time",
setTimeDisplayMode: (mode) => {
writeStudioUiPreferences({ timeDisplayMode: mode });
diff --git a/packages/studio/src/utils/sdkCutover.test.ts b/packages/studio/src/utils/sdkCutover.test.ts
index d5644bc0e3..a71d2ff0a4 100644
--- a/packages/studio/src/utils/sdkCutover.test.ts
+++ b/packages/studio/src/utils/sdkCutover.test.ts
@@ -649,6 +649,57 @@ window.__timelines = { main: tl };</script></div>
for (const candidate of published) candidate.dispose();
});
+ it("does not resurrect an element a prior REST write already deleted, even with a stale live session", async () => {
+ // A delete persists via the server REST path, then a same-gesture ripple
+ // move reaches an SDK-eligible batch persist while `live` was never
+ // reloaded. Prove the candidate rebases on the post-delete disk bytes.
+ const twoElementHtml = `<!DOCTYPE html><html data-composition-variables='[]'><body>
+<div data-hf-id="hf-stage" data-hf-root>
+<div data-hf-id="hf-a" data-start="0" data-duration="2"></div>
+<div data-hf-id="hf-b" data-start="5" data-duration="2"></div>
+</div>
+</body></html>`;
+ const live = await openComposition(twoElementHtml, { history: false });
+
+ // Disk already reflects hf-b's deletion — a separate write that completed
+ // before this persist started, exactly like the delete's own REST call
+ // that `handleTimelineElementsDelete` awaits before the ripple begins.
+ const postDelete = await openComposition(twoElementHtml, { history: false });
+ postDelete.removeElement("hf-b");
+ let disk = postDelete.serialize();
+ postDelete.dispose();
+ expect(disk).not.toContain("hf-b");
+
+ const writeProjectFile = vi.fn(async (_path: string, content: string) => {
+ disk = content;
+ });
+ const deps = {
+ editHistory: { recordEdit: vi.fn().mockResolvedValue(undefined) },
+ writeProjectFile,
+ readProjectFile: vi.fn(async () => disk),
+ reloadPreview: vi.fn(),
+ publishSession: vi.fn().mockReturnValue("published"),
+ };
+
+ // The ripple: only survivors move, mirroring resolveShiftedElements — this
+ // never touches hf-b, which `live` (unlike disk) still believes exists.
+ const result = await persistSdkCandidateMutation(
+ live,
+ "/comp.html",
+ twoElementHtml,
+ deps,
+ (candidate) => candidate.setTiming("hf-a", { start: 3 }),
+ );
+
+ expect(result.status).toBe("committed");
+ expect(disk).not.toContain("hf-b");
+ const written = await openComposition(disk, { history: false });
+ expect(written.getElement("hf-a")?.start).toBe(3);
+ expect(written.getElement("hf-b")).toBeNull();
+ written.dispose();
+ live.dispose();
+ });
+
it("fails instead of cloning stale bytes when the authoritative queued read rejects", async () => {
const live = await openComposition(html, { history: false });
let disk = html;
diff --git a/packages/studio/src/utils/studioUiPreferences.test.ts b/packages/studio/src/utils/studioUiPreferences.test.ts
index 012ccf67e7..9e80b0abf2 100644
--- a/packages/studio/src/utils/studioUiPreferences.test.ts
+++ b/packages/studio/src/utils/studioUiPreferences.test.ts
@@ -73,6 +73,20 @@ describe("timelineSnapEnabled preference", () => {
});
});
+describe("rippleEditEnabled preference", () => {
+ it("round-trips through storage", () => {
+ const storage = createStorage();
+ writeStudioUiPreferences({ rippleEditEnabled: false }, storage);
+ expect(readStudioUiPreferences(storage).rippleEditEnabled).toBe(false);
+ });
+
+ it("ignores non-boolean values", () => {
+ const storage = createStorage();
+ storage.setItem("hf-studio-ui-preferences", JSON.stringify({ rippleEditEnabled: "yes" }));
+ expect(readStudioUiPreferences(storage).rippleEditEnabled).toBeUndefined();
+ });
+});
+
describe("thumbnailMode preference", () => {
it("round-trips the adaptive mode", () => {
const storage = createStorage();
diff --git a/packages/studio/src/utils/studioUiPreferences.ts b/packages/studio/src/utils/studioUiPreferences.ts
index 1a14318d7e..e38d89d395 100644
--- a/packages/studio/src/utils/studioUiPreferences.ts
+++ b/packages/studio/src/utils/studioUiPreferences.ts
@@ -24,6 +24,9 @@ export interface StudioUiPreferences {
snapToGrid?: boolean;
/** Timeline magnet: snap clip drags/trims/drops to playhead, clip edges, and beats. */
timelineSnapEnabled?: boolean;
+ /** Keeps the main track gapless: deleting a clip closes the gap. Distinct
+ * from `timelineSnapEnabled` ("Magnet", drag/trim snapping). */
+ rippleEditEnabled?: boolean;
/** Transport + ruler readout mode: timecode or frame number. */
timeDisplayMode?: TimelineTimeDisplayMode;
/**
@@ -136,6 +139,9 @@ function readStorage(storage: Storage | null): StudioUiPreferences {
if (typeof parsed.timelineSnapEnabled === "boolean") {
preferences.timelineSnapEnabled = parsed.timelineSnapEnabled;
}
+ if (typeof parsed.rippleEditEnabled === "boolean") {
+ preferences.rippleEditEnabled = parsed.rippleEditEnabled;
+ }
if (parsed.timeDisplayMode === "time" || parsed.timeDisplayMode === "frame") {
preferences.timeDisplayMode = parsed.timeDisplayMode;
}