Skip to content

Commit 8fe480c

Browse files
feat(studio): operators get a magnetic main track that closes gaps on delete (#4069)
* feat(studio): closing a gap on the main track closes it automatically Adds a Ripple toggle to the timeline toolbar (default on). With it on, deleting a clip on the main track shifts every later main-track clip left to close the gap, folded into the delete's own undo step. Linked overlays and the auto-snap/insert behaviors are separate follow-ups. * refactor(studio): one shared resolver for gap shifts, no scaffolding ahead of its caller Consolidates three separate shift-to-element lookups (the gap-close menu's two and the delete-ripple's one) into a single resolveShiftedElements, built without a non-null assertion. Also drops resolveOpenGapShifts and its tests from this branch: it ships with its actual caller in the next PR. * fix(studio): canvas Delete on a timeline clip uses the timeline's own delete op Clicking a clip then pressing Delete went through the DOM/canvas delete path, which never ripples the main track — only the timeline's own right-click Delete did. Both paths now converge: a DOM/canvas selection that resolves to an exact timeline row hands off to the timeline delete op instead of the REST remove-elements path, so ripple and undo-coalescing apply from every gesture, not just one of two. * test(studio): cover the delete-routing handoff and a stale-session ripple persist Adds an end-to-end test that a canvas selection resolving to a timeline row is handed to the timeline delete op rather than the REST path, plus a test proving an SDK-eligible ripple persist after a delete rebases on the post-delete disk bytes instead of resurrecting the deleted element from a stale in-memory session. Also drops the unused single-element handleDomEditElementDelete plumbing in useDomEditCommits.ts / useElementLifecycleOps.ts, dead since before this branch. * test(studio): cover the multi-member delete-routing handoff Closes an adversarial-review should-fix: the marquee-group path (expandGroup, 2+ members all resolving to timeline rows) was verified at the resolver level but not through the useDomEditSession integration wrapper end to end. * fix(studio): ripple delete closes only the gap it opened resolveMainTrackDeleteRippleShifts compacted the whole main track (resolveAllTrackGaps) instead of the deleted clip's own span, so a delete also swallowed any pre-existing gap further down the lane, or pulled every clip to zero when nothing followed the deleted clip. Now each survivor shifts left by exactly the duration of the deleted clips before it. * chore(studio): trim playerStore.ts under the file-size cap Rebasing onto main put this file's line count over the cap once combined with this branch's own additions; tightens the playbackRequest doc comment, no behavior change. * test(studio): cover multi-select ripple delete of non-adjacent clips Closes the should-fix from the second adversarial review: a marquee delete of two or more non-adjacent main-track clips in one batch had no regression coverage, though the shift-sum logic already handled it. * fix(studio): undo after a rippled delete names the delete, not the move editHistory.ts coalesces a folded ripple move into the delete's own undo entry by keeping the LAST recordEdit call's label — which was always "Move timeline clips", so the toast read "Undid Move timeline clips" after a keyboard Delete instead of naming what the user did. handleTimelineGroupMove now accepts a label override, and the ripple delete path passes its own "Delete timeline clip" label through it. * fix(studio): surface and de-dup the ripple's post-delete failure path A ripple that failed to persist after a committed delete was only logged to the console, leaving the user with an unexplained gap; now shows an error toast. The delete's history label was also duplicated as a literal at both call sites (the delete write and the folded ripple move) with no shared source; both now read from one constant so they cannot drift apart. * test(studio): dedupe the two delete-ops harness mounts Fallow's duplication check flagged the two new ripple tests' harness setup as a clone group; extracted a shared mountDeleteHarness helper. * fix(studio): one toast, not two, on a ripple-persist failure The generic group-move failure toast and the delete op's own specific one both fired on the same ripple-persist error, telling the user about one action twice. handleTimelineGroupMove now accepts a suppressFailureToast option (console-logged instead, not silenced) for a caller with its own more specific message, and the delete op's unconditional "Deleted X" toast is skipped when the ripple failed. * test(studio): cover suppressFailureToast through the real move hook The prior test mocked handleTimelineGroupMove entirely, so it proved the call site passes the option but not that the hook's own catch honors it. A missing project id makes enqueueGroupOperation reject before any persist runs, reaching the real catch block without faking the SDK/server path. * test(studio): dedupe the shared move-change fixture Fallow flagged the two suppressFailureToast tests' identical "change" object as a within-file clone group; hoisted to the describe scope. * test(studio): unmount the React root in the group-move harness
1 parent 2679ebd commit 8fe480c

22 files changed

Lines changed: 794 additions & 98 deletions

‎packages/studio/src/App.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,7 @@ export function StudioApp() {
292292
sdkSession: editFlowSdkSession,
293293
publishSdkSession: sdkHandle.publish,
294294
forceReloadSdkSession: sdkHandle.forceReload,
295+
handleTimelineElementsDelete: timelineEditing.handleTimelineElementsDelete,
295296
});
296297
domEditSelectionBridgeRef.current = domEditSession.domEditSelection;
297298
handleDomZIndexReorderCommitRef.current = domEditSession.handleDomZIndexReorderCommit;

‎packages/studio/src/components/TimelineToolbar.tsx‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { useEffect, useRef } from "react";
2-
import { Image, Magnet, MagnifyingGlassMinus, MagnifyingGlassPlus } from "@phosphor-icons/react";
2+
import {
3+
Image,
4+
Magnet,
5+
MagnifyingGlassMinus,
6+
MagnifyingGlassPlus,
7+
Waves,
8+
} from "@phosphor-icons/react";
39
import {
410
useEnableKeyframes,
511
isPlayheadWithinTween,
@@ -126,6 +132,8 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
126132
const setActiveTool = usePlayerStore((s) => s.setActiveTool);
127133
const timelineSnapEnabled = usePlayerStore((s) => s.timelineSnapEnabled);
128134
const setTimelineSnapEnabled = usePlayerStore((s) => s.setTimelineSnapEnabled);
135+
const rippleEditEnabled = usePlayerStore((s) => s.rippleEditEnabled);
136+
const setRippleEditEnabled = usePlayerStore((s) => s.setRippleEditEnabled);
129137
const autoKeyframeEnabled = usePlayerStore((s) => s.autoKeyframeEnabled);
130138
const setAutoKeyframeEnabled = usePlayerStore((s) => s.setAutoKeyframeEnabled);
131139
const thumbnailMode = usePlayerStore((s) => s.thumbnailMode);
@@ -228,6 +236,23 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
228236
<Magnet size={16} weight="bold" aria-hidden="true" />
229237
</button>
230238
</Tooltip>
239+
<Tooltip
240+
label={
241+
rippleEditEnabled
242+
? "Ripple on — keeps the main track gapless"
243+
: "Ripple off — deleting a main-track clip leaves a gap"
244+
}
245+
>
246+
<button
247+
type="button"
248+
onClick={() => setRippleEditEnabled(!rippleEditEnabled)}
249+
aria-label="Toggle ripple edit"
250+
aria-pressed={rippleEditEnabled}
251+
className={rippleEditEnabled ? flatActive : flatIdle}
252+
>
253+
<Waves size={16} weight="bold" aria-hidden="true" />
254+
</button>
255+
</Tooltip>
231256
{/* Always rendered (CapCut-style): with no keyframeable selection the
232257
button fades to a disabled state instead of unmounting, so the
233258
toolbar layout never shifts. */}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, expect, it } from "vitest";
2+
import { timelineElementsForDelete } from "./domEditDeleteMembers";
3+
import type { DomEditSelection } from "../components/editor/domEditingTypes";
4+
import type { TimelineElement } from "../player";
5+
6+
const sel = (id: string, sourceFile = "index.html") => ({ id, sourceFile }) as DomEditSelection;
7+
8+
const clip = (id: string, domId: string, sourceFile = "index.html"): TimelineElement =>
9+
({ id, domId, sourceFile, tag: "video", start: 0, duration: 1, track: 0 }) as TimelineElement;
10+
11+
describe("timelineElementsForDelete", () => {
12+
it("resolves every member to its exact timeline row", () => {
13+
const elements = [clip("a", "clip-a"), clip("b", "clip-b")];
14+
const result = timelineElementsForDelete([sel("clip-a"), sel("clip-b")], elements);
15+
expect(result).toEqual([elements[0], elements[1]]);
16+
});
17+
18+
it("returns null when any member has no timeline row of its own", () => {
19+
const elements = [clip("a", "clip-a")];
20+
// "plain-child" is not a timeline element — a nested DOM node inside a clip.
21+
const result = timelineElementsForDelete([sel("clip-a"), sel("plain-child")], elements);
22+
expect(result).toBeNull();
23+
});
24+
25+
it("does not fall back to the ancestor clip for a nested child", () => {
26+
// A click inside a clip must not resolve to (and so delete) the whole clip.
27+
const elements = [clip("a", "clip-a")];
28+
expect(timelineElementsForDelete([sel("nested-text")], elements)).toBeNull();
29+
});
30+
});

‎packages/studio/src/hooks/domEditDeleteMembers.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
import type { DomEditSelection } from "../components/editor/domEditingTypes";
99
import type { EditHistoryKind } from "../utils/editHistory";
10+
import type { TimelineElement } from "../player";
11+
import { findMatchingTimelineElementId } from "../utils/studioHelpers";
1012

1113
/** One entry in the studio's edit history, as `useDomEditSession`'s caller
1214
* supplies it. */
@@ -32,3 +34,20 @@ export function membersForDelete(
3234
): DomEditSelection[] {
3335
return options?.expandGroup && group.length > 0 ? group : [selection];
3436
}
37+
38+
/** The timeline row for each member, only when EVERY member is one — a mixed
39+
* group stays on the DOM path. Exact-identity match only, no ancestor
40+
* fallback: a click inside a clip must not delete the whole clip. */
41+
export function timelineElementsForDelete(
42+
members: readonly DomEditSelection[],
43+
elements: TimelineElement[],
44+
): TimelineElement[] | null {
45+
const matches: TimelineElement[] = [];
46+
for (const member of members) {
47+
const id = findMatchingTimelineElementId(member, elements);
48+
const match = id ? elements.find((el) => (el.key ?? el.id) === id) : undefined;
49+
if (!match) return null;
50+
matches.push(match);
51+
}
52+
return matches;
53+
}

‎packages/studio/src/hooks/useDomEditCommits.ts‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -456,20 +456,19 @@ export function useDomEditCommits({
456456

457457
// ── Element lifecycle (delete, z-index reorder) ──
458458

459-
const { handleDomEditElementDelete, handleDomEditElementsDelete, handleDomZIndexReorderCommit } =
460-
useElementLifecycleOps({
461-
activeCompPath,
462-
showToast,
463-
writeProjectFile,
464-
editHistory,
465-
projectIdRef,
466-
reloadPreview,
467-
clearDomSelection,
468-
onTrySdkDelete,
469-
onReorderShadow,
470-
forceReloadSdkSession,
471-
commitDomEditPatchBatches,
472-
});
459+
const { handleDomEditElementsDelete, handleDomZIndexReorderCommit } = useElementLifecycleOps({
460+
activeCompPath,
461+
showToast,
462+
writeProjectFile,
463+
editHistory,
464+
projectIdRef,
465+
reloadPreview,
466+
clearDomSelection,
467+
onTrySdkDelete,
468+
onReorderShadow,
469+
forceReloadSdkSession,
470+
commitDomEditPatchBatches,
471+
});
473472

474473
return {
475474
resolveImportedFontAsset,
@@ -491,7 +490,6 @@ export function useDomEditCommits({
491490
handleDomBoxSizeCommit,
492491
handleDomRotationCommit,
493492
handleDomManualEditsReset,
494-
handleDomEditElementDelete,
495493
handleDomEditElementsDelete,
496494
handleDomZIndexReorderCommit,
497495
};

‎packages/studio/src/hooks/useDomEditSession.test.tsx‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { shouldUseSdkCutover } from "../utils/sdkCutover";
66
import type { PatchOperation } from "../utils/sourcePatcher";
77
import type { Composition } from "@hyperframes/sdk";
88
import type { DomEditSelection } from "../components/editor/domEditingTypes";
9+
import type { TimelineElement } from "../player";
910
import type { UseDomEditSessionParams } from "./useDomEditSession";
1011

1112
const styleOp = (property: string, value: string): PatchOperation => ({
@@ -97,6 +98,7 @@ function createSessionParams(
9798
syncPreviewHotkeys: vi.fn(),
9899
reloadPreview: vi.fn(),
99100
setRefreshKey: vi.fn(),
101+
handleTimelineElementsDelete: vi.fn(),
100102
...overrides,
101103
};
102104
}
@@ -105,6 +107,7 @@ vi.mock("../utils/sdkResolverShadow", () => ({
105107
runResolverShadow: vi.fn(),
106108
recordResolverParity: (...args: unknown[]) => recordResolverParity(...args),
107109
}));
110+
const handleDomEditElementsDeleteMock = vi.fn(async () => ({ ok: true }) as const);
108111
vi.mock("./useDomEditCommits", () => ({
109112
useDomEditCommits: (params: { onReorderShadow?: (targets: string[]) => void }) => {
110113
capturedOnReorderShadow.fn = params.onReorderShadow;
@@ -120,7 +123,7 @@ vi.mock("./useDomEditCommits", () => ({
120123
handleDomRemoveTextField: vi.fn(),
121124
handleDomBoxSizeCommit: vi.fn(),
122125
handleDomManualEditsReset: vi.fn(),
123-
handleDomEditElementDelete: vi.fn(),
126+
handleDomEditElementsDelete: handleDomEditElementsDeleteMock,
124127
handleDomZIndexReorderCommit: vi.fn(),
125128
};
126129
},
@@ -461,3 +464,89 @@ describe("handleGroupSelection with audio in the selection", () => {
461464
expect(groupSelectionSpy).toHaveBeenCalledTimes(1);
462465
});
463466
});
467+
468+
// ── Delete routing: a timeline row goes through the timeline's own delete op ──
469+
470+
describe("handleDomEditElementDelete routing", () => {
471+
const domSel = (id: string): DomEditSelection =>
472+
({
473+
id,
474+
element: document.createElement("div"),
475+
sourceFile: "index.html",
476+
}) as unknown as DomEditSelection;
477+
478+
async function deleteViaSession(
479+
selection: DomEditSelection,
480+
timelineElements: TimelineElement[],
481+
options?: { expandGroup?: boolean; group?: DomEditSelection[] },
482+
) {
483+
const { useDomEditSession } = await import("./useDomEditSession");
484+
handleDomEditElementsDeleteMock.mockClear();
485+
domEditGroupSelectionsRef.current = options?.group ?? [];
486+
const handleTimelineElementsDelete = vi.fn(async () => {});
487+
const captured: {
488+
fn?: (selection: DomEditSelection, options?: { expandGroup?: boolean }) => Promise<void>;
489+
} = {};
490+
function Probe() {
491+
captured.fn = useDomEditSession(
492+
createSessionParams({ timelineElements, handleTimelineElementsDelete }),
493+
).handleDomEditElementDelete;
494+
return null;
495+
}
496+
const root = createRoot(document.createElement("div"));
497+
act(() => root.render(<Probe />));
498+
await act(async () => captured.fn?.(selection, { expandGroup: options?.expandGroup }));
499+
act(() => root.unmount());
500+
domEditGroupSelectionsRef.current = [];
501+
return { handleTimelineElementsDelete };
502+
}
503+
504+
it("hands a selection that IS a timeline row to the timeline delete op, not the REST path", async () => {
505+
const clip = {
506+
id: "clip-a",
507+
domId: "clip-a",
508+
sourceFile: "index.html",
509+
tag: "video",
510+
start: 0,
511+
duration: 2,
512+
track: 0,
513+
} as TimelineElement;
514+
const { handleTimelineElementsDelete } = await deleteViaSession(domSel("clip-a"), [clip]);
515+
expect(handleTimelineElementsDelete).toHaveBeenCalledWith([clip]);
516+
expect(handleDomEditElementsDeleteMock).not.toHaveBeenCalled();
517+
});
518+
519+
it("falls through to the REST path for a selection with no timeline row of its own", async () => {
520+
const { handleTimelineElementsDelete } = await deleteViaSession(domSel("nested-child"), []);
521+
expect(handleTimelineElementsDelete).not.toHaveBeenCalled();
522+
expect(handleDomEditElementsDeleteMock).toHaveBeenCalledWith([domSel("nested-child")]);
523+
});
524+
525+
it("expands a multi-member marquee group to the timeline op when every member resolves", async () => {
526+
const clipA = {
527+
id: "clip-a",
528+
domId: "clip-a",
529+
sourceFile: "index.html",
530+
tag: "video",
531+
start: 0,
532+
duration: 2,
533+
track: 0,
534+
} as TimelineElement;
535+
const clipB = {
536+
id: "clip-b",
537+
domId: "clip-b",
538+
sourceFile: "index.html",
539+
tag: "video",
540+
start: 2,
541+
duration: 2,
542+
track: 0,
543+
} as TimelineElement;
544+
const group = [domSel("clip-a"), domSel("clip-b")];
545+
const { handleTimelineElementsDelete } = await deleteViaSession(group[0], [clipA, clipB], {
546+
expandGroup: true,
547+
group,
548+
});
549+
expect(handleTimelineElementsDelete).toHaveBeenCalledWith([clipA, clipB]);
550+
expect(handleDomEditElementsDeleteMock).not.toHaveBeenCalled();
551+
});
552+
});

‎packages/studio/src/hooks/useDomEditSession.ts‎

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useCallback } from "react";
22
import { trackStudioEvent } from "../utils/studioTelemetry";
33
import { isAudioDomElement } from "../utils/timelineInspector";
4+
import type { TimelineElement } from "../player";
45
import type { ImportedFontAsset } from "../components/editor/fontAssets";
56
import type { RightPanelTab } from "../utils/studioHelpers";
67
import type { PatchTarget } from "../utils/sourcePatcher";
@@ -20,7 +21,7 @@ import { useGsapAwareEditing } from "./useGsapAwareEditing";
2021
import { useStudioSelectionPublisher } from "./useStudioSelectionPublisher";
2122
import { useKeyframeEaseCommits } from "./useKeyframeEaseCommits";
2223
import type { DomEditSelection } from "../components/editor/domEditingTypes";
23-
import { membersForDelete } from "./domEditDeleteMembers";
24+
import { membersForDelete, timelineElementsForDelete } from "./domEditDeleteMembers";
2425
import type { RecordEditInput } from "./domEditDeleteMembers";
2526
import type { DomEditTimelineParams } from "./useDomSelectionTypes";
2627
// Re-exported: the delete rule lives in its own module now, and callers (and its
@@ -57,6 +58,9 @@ export interface UseDomEditSessionParams extends DomEditTimelineParams {
5758
sdkSession?: Composition | null;
5859
publishSdkSession?: PublishSdkSession;
5960
forceReloadSdkSession?: () => void;
61+
/** The timeline context menu's delete op — a canvas selection that IS a
62+
* timeline row hands off here instead of the REST remove-elements path. */
63+
handleTimelineElementsDelete: (elements: TimelineElement[]) => Promise<void>;
6064
}
6165

6266
export function useDomEditSession({
@@ -98,6 +102,7 @@ export function useDomEditSession({
98102
sdkSession,
99103
publishSdkSession,
100104
forceReloadSdkSession,
105+
handleTimelineElementsDelete,
101106
}: UseDomEditSessionParams) {
102107
const isMasterView = !activeCompPath || activeCompPath === "index.html";
103108
void _setRefreshKey;
@@ -249,11 +254,9 @@ export function useDomEditSession({
249254
forceReloadSdkSession,
250255
onTrySdkPersist: sdkSession
251256
? (selection, operations, originalContent, targetPath, options) => {
252-
// Resolver shadow runs regardless of the cutover flag — decoupled tripwire.
253-
// Pass originalContent so the runtime-node filter can suppress hf-ids
254-
// absent from source (script-created nodes the SDK can't model), and
255-
// the paths so cross-file edits (session models only the active comp)
256-
// skip instead of emitting structural element_not_found noise.
257+
// Decoupled tripwire, runs regardless of the cutover flag. originalContent lets
258+
// the runtime-node filter suppress hf-ids absent from source (script-created
259+
// nodes); the paths let a cross-file edit skip instead of a false not-found.
257260
runResolverShadow(sdkSession, selection.hfId, operations, originalContent, {
258261
targetPath,
259262
compositionPath: activeCompPath,
@@ -287,9 +290,8 @@ export function useDomEditSession({
287290
publishSession: publishSdkSession,
288291
})
289292
: undefined,
290-
// Resolver shadow for the z-index reorder edit: it takes the server path (no
291-
// SDK persist), but the tripwire is decoupled from cutover — record whether
292-
// the SDK resolves each reordered element (the reorderElements op's targets).
293+
// Z-index reorder takes the server path (no SDK persist); this decoupled
294+
// tripwire still records whether the SDK resolves each reordered target.
293295
onReorderShadow: sdkSession
294296
? (targets: string[]) => {
295297
// Single-flight: every target in one reorder batch shares the same file, so
@@ -320,17 +322,28 @@ export function useDomEditSession({
320322

321323
const handleDomEditElementDelete = useCallback(
322324
async (selection: DomEditSelection, options?: { expandGroup?: boolean }) => {
323-
// Same structural edit the timeline delete refuses mid-recording, so it
324-
// refuses here too — this is now the path a Delete press takes whenever
325-
// the canvas holds a selection.
325+
// Same structural edit the timeline delete refuses mid-recording.
326326
if (isRecordingRef?.current) {
327327
showToast("Cannot edit timeline while recording", "error");
328328
return;
329329
}
330330
const members = membersForDelete(selection, domEditGroupSelectionsRef.current, options);
331+
// A selection that is itself timeline rows shares the context menu's delete op.
332+
const timelineTargets = timelineElementsForDelete(members, timelineElements);
333+
if (timelineTargets) {
334+
await handleTimelineElementsDelete(timelineTargets);
335+
return;
336+
}
331337
await handleDomEditElementsDelete(members);
332338
},
333-
[domEditGroupSelectionsRef, handleDomEditElementsDelete, isRecordingRef, showToast],
339+
[
340+
domEditGroupSelectionsRef,
341+
handleDomEditElementsDelete,
342+
handleTimelineElementsDelete,
343+
isRecordingRef,
344+
showToast,
345+
timelineElements,
346+
],
334347
);
335348

336349
const handleGroupSelection = useCallback(() => {
@@ -341,14 +354,8 @@ export function useDomEditSession({
341354
showToast("Select at least 2 elements to group", "info");
342355
return;
343356
}
344-
// A layout group is a positioned wrapper: it takes the members' bounding
345-
// box, rebases each child's left/top against it, and adopts the topmost
346-
// z-index. An <audio> clip has no box — offsetWidth/Height are 0 — so
347-
// grouping audio produced a 0x0 div with inline left/top written onto
348-
// elements that have never been laid out, and the timeline gained a
349-
// wrapper standing for nothing audible. The audio answer to "these clips
350-
// belong together" is an <hf-audio-group> bus, which the timeline's own FX
351-
// pointer creates, so the refusal names it rather than just declining.
357+
// A layout group takes the members' bounding box; audio has no box (0x0),
358+
// so it groups into an <hf-audio-group> bus via the track's FX pointer instead.
352359
if (members.some((m) => isAudioDomElement(m.element))) {
353360
showToast(
354361
members.every((m) => isAudioDomElement(m.element))

0 commit comments

Comments
 (0)