Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): multi-track deletes leave their gap; remove_gap closes it

David Le44a0beab66b9
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index b273f4cf..b14138ba 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -34,7 +34,7 @@ import { useExports } from "@/cut/lib/exportStore";
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";
import { ensurePeaks, importImage, importStockMusic, importStockVideo } from "@/cut/lib/media";
-import { track0Clips, clipLen, clipSpeed, footprints, getClipSpans, nextFreeStart, overlayLayers, projectDuration, rippleInsert, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
+import { track0Clips, track0GapAt, clipLen, clipSpeed, footprints, getClipSpans, nextFreeStart, overlayLayers, projectDuration, rippleInsert, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
import { subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
@@ -307,6 +307,19 @@ export function Timeline() {
// landing slot, and grow its row stack while a new row is hovered.
const [laneDrag, setLaneDrag] = useState<LaneDrag | null>(null);
+ // Right-click on empty track-0 space: a small popover offering to close the
+ // gap under the cursor. Multi-track deletes leave their gap in place (a
+ // ripple would shear the layers), so this is the manual close.
+ const [gapMenu, setGapMenu] = useState<{ x: number; y: number; at: number } | null>(null);
+ useEffect(() => {
+ if (!gapMenu) return;
+ const close = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setGapMenu(null);
+ };
+ window.addEventListener("keydown", close);
+ return () => window.removeEventListener("keydown", close);
+ }, [gapMenu]);
+
// Title tracks: overlays carry a `lane`; used lanes compact to contiguous
// display rows, so empty tracks disappear on their own.
const overlayLanes = useMemo(() => {
@@ -982,6 +995,15 @@ export function Timeline() {
style={{ height: VIDEO_H }}
data-drop={placementAttr(TRACK_ZERO)}
onPointerDown={deselectIfSelf}
+ onContextMenu={(e) => {
+ // Only empty space gets the menu: a right-click on a clip sits
+ // on a footprint, so the gap lookup misses and the event falls
+ // through to the browser.
+ const at = timeAt(e.clientX);
+ if (!track0GapAt(useEditor.getState().clips, at)) return;
+ e.preventDefault();
+ setGapMenu({ x: e.clientX, y: e.clientY, at });
+ }}
>
{spans.length > 0 && laneRail(VIDEO_H - 2)}
{/* An external asset drag previews as an on-track segment ghost
@@ -1278,6 +1300,32 @@ export function Timeline() {
{fileDropHint && (
<div className="pointer-events-none absolute inset-x-0 top-11 bottom-0 z-40 bg-[#0a84ff]/5 ring-2 ring-[#0a84ff]/30 ring-inset" />
)}
+ {gapMenu && (
+ <div
+ className="fixed inset-0 z-50"
+ onPointerDown={() => setGapMenu(null)}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setGapMenu(null);
+ }}
+ >
+ <div
+ className="absolute min-w-44 rounded-md border bg-popover p-1 text-popover-foreground shadow-md"
+ style={{ left: gapMenu.x, top: gapMenu.y }}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <button
+ className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"
+ onClick={() => {
+ useEditor.getState().removeGap(gapMenu.at);
+ setGapMenu(null);
+ }}
+ >
+ <Scissors className="size-3.5 text-muted-foreground" /> Remove empty space
+ </button>
+ </div>
+ </div>
+ )}
</footer>
);
}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 5dcd7c3b..0945dc6d 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -24,7 +24,7 @@ import { blobToInlineAudio, refToInlineAudio, type InlineImage } from "./refMedi
import { characterPrompt, stockTitle } from "./stock";
import { STOCK_IMAGES } from "./stockManifest";
import { STOCK_VIDEOS } from "./stockVideoManifest";
-import { applyOverlayPatchSettled, track0Clips, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";
+import { applyOverlayPatchSettled, track0Clips, track0GapAt, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";
import { buildAiContext } from "./aiContext";
import { laneCues, subtitleLaneCount } from "./subtitles";
import { synthesizeMusic } from "./audioGen";
@@ -468,6 +468,14 @@ export async function runAiTool(
return { deleted: { kind: selKind, id } };
}
+ case "remove_gap": {
+ if (!isNum(input.at)) throw new ToolError("at (seconds) is required.");
+ const gap = track0GapAt(s.clips, input.at);
+ if (!gap) throw new ToolError(`No track-0 gap at ${input.at}s — pass a time inside the empty span.`);
+ s.removeGap(input.at);
+ return { closed: gap };
+ }
+
case "add_title": {
if (typeof input.text !== "string" || !input.text.trim())
throw new ToolError("text is required.");
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index aa5b7a12..8a32961c 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -316,6 +316,59 @@ describe("subtitle cues", () => {
});
});
+describe("delete ripple and gaps", () => {
+ test("single-track delete ripples: later items on every track slide left", () => {
+ const a = vclip({ track: 0, start: 0, out: 2 });
+ const b = vclip({ track: 0, start: 2, out: 2 });
+ const au = aclip({ start: 3, out: 2 });
+ const t = title({ start: 3, end: 4 });
+ useEditor.setState({
+ clips: [a, b],
+ audioClips: [au],
+ overlays: [t],
+ selection: { kind: "clip", id: a.id },
+ });
+ s().deleteSelection();
+ expect(clipById(b.id).start).toBeCloseTo(0);
+ expect(audioById(au.id).start).toBeCloseTo(1);
+ expect(s().overlays[0].start).toBeCloseTo(1);
+ });
+
+ test("delete with an overlay video track leaves the gap in place", () => {
+ const a = vclip({ track: 0, start: 0, out: 2 });
+ const b = vclip({ track: 0, start: 2, out: 2 });
+ const layer = vclip({ track: 1, start: 1, out: 2 });
+ useEditor.setState({
+ clips: [a, b, layer],
+ selection: { kind: "clip", id: a.id },
+ });
+ s().deleteSelection();
+ expect(clipById(b.id).start).toBeCloseTo(2);
+ expect(clipById(layer.id).start).toBeCloseTo(1);
+ });
+
+ test("removeGap closes the empty span across the whole document", () => {
+ const b = vclip({ track: 0, start: 2, out: 2 });
+ const layer = vclip({ track: 1, start: 2.5, out: 2 });
+ const au = aclip({ start: 3, out: 2 });
+ useEditor.setState({ clips: [b, layer], audioClips: [au] });
+ s().removeGap(1);
+ expect(clipById(b.id).start).toBeCloseTo(0);
+ expect(clipById(layer.id).start).toBeCloseTo(0.5);
+ expect(audioById(au.id).start).toBeCloseTo(1);
+ });
+
+ test("removeGap outside a gap is a no-op", () => {
+ const a = vclip({ track: 0, start: 0, out: 2 });
+ const b = vclip({ track: 0, start: 3, out: 2 });
+ useEditor.setState({ clips: [a, b] });
+ s().removeGap(1); // on a clip
+ s().removeGap(6); // past the end
+ expect(clipById(a.id).start).toBeCloseTo(0);
+ expect(clipById(b.id).start).toBeCloseTo(3);
+ });
+});
+
describe("spine grounding", () => {
test("deleting the last track-0 clip grounds the layers above it", () => {
const spine = vclip({ track: 0, start: 0, out: 2 });
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 4417f170..9c329981 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -280,11 +280,18 @@ export interface EditorState {
* from the original recording, so the word highlighter would otherwise drift). */
retimeCues: (entries: { id: string; start: number; end: number }[]) => void;
sortCues: () => void;
- /** Delete the current selection. A track-0 clip delete ripples: the
- * footprint it occupied closes and everything after it — clips, titles,
- * captions, soundtrack — slides left in sync (see exciseRange). Deletes on
- * every other track remove just that item. */
+ /** Delete the current selection. While track 0 is the only video track, a
+ * track-0 clip delete ripples: the footprint it occupied closes and
+ * everything after it — clips, titles, captions, soundtrack — slides left
+ * in sync (see exciseRange). With upper video layers present the slide
+ * would shear them against track 0, so the delete leaves the gap; closing
+ * it is `removeGap`. Deletes on every other track remove just that item. */
deleteSelection: () => void;
+ /** Close the empty track-0 span containing `at`: cut that timeline range
+ * out of the whole document (see exciseRange), so everything after it —
+ * clips on every track, titles, captions, soundtrack — slides left in
+ * sync. No-op when `at` isn't inside a gap. */
+ removeGap: (at: number) => void;
/** Timeline window [start, end) spanned by the current selection, or null if
* nothing selectable is chosen. */
selectionRange: () => { start: number; end: number } | null;
@@ -1605,13 +1612,19 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// Deleting a track-0 clip closes the hole it leaves: everything after
// it — clips, titles, captions, soundtrack — slides left with the
// surviving footage, and anything living inside the hole annotated
- // footage that is gone, so it goes too. Deletes on every other track
- // are plain removals (already applied above). Holes close
+ // footage that is gone, so it goes too. That ripple runs only while
+ // track 0 is the only video track: with upper layers surviving, the
+ // slide would shear them against the footage they were composed over,
+ // so the delete leaves the gap and closing it is an explicit act
+ // (removeGap, via right-click on the empty space). Deletes on every
+ // other track are plain removals (already applied above). Holes close
// right-to-left so each one's coordinates stay valid while the ones
// before it are unprocessed.
- const holes = s.clips
- .filter((c) => c.track === 0 && clipIds.has(c.id))
- .sort((a, b) => b.start - a.start);
+ const holes = clips.some((c) => c.track !== 0)
+ ? []
+ : s.clips
+ .filter((c) => c.track === 0 && clipIds.has(c.id))
+ .sort((a, b) => b.start - a.start);
for (const gone of holes) {
const next = clips.reduce(
(acc, c) => (c.track === 0 && c.start > gone.start + 0.001 ? Math.min(acc, c.start) : acc),
@@ -1639,6 +1652,25 @@ export const useEditor = create<EditorState>((baseSet, get) => {
});
},
+ removeGap: (at) => {
+ const gap = track0GapAt(get().clips, at);
+ if (!gap) return;
+ push();
+ set((s) => {
+ const { clips, audioClips, overlays, cues } = exciseRange(
+ { clips: s.clips, audioClips: s.audioClips, overlays: s.overlays, cues: s.subtitles.cues },
+ gap.start,
+ gap.len
+ );
+ return {
+ clips: clips.sort((a, b) => a.start - b.start),
+ audioClips,
+ overlays,
+ subtitles: { ...s.subtitles, cues },
+ };
+ });
+ },
+
selectionRange: () => {
const s = get();
const sels = (s.multiSelection.length ? s.multiSelection : s.selection ? [s.selection] : [])
@@ -2752,6 +2784,25 @@ export function getClipSpans(
return spans;
}
+/** The empty track-0 span containing time `t` — the stretch between two clip
+ * footprints (or before the first one) that plays black. Null when `t` sits
+ * on a clip or past the last one (there is nothing after trailing space to
+ * pull left). */
+export function track0GapAt(
+ clips: VideoClip[],
+ t: number
+): { start: number; len: number } | null {
+ const spine = track0Clips(clips).sort((a, b) => a.start - b.start);
+ let prevEnd = 0;
+ for (const c of spine) {
+ if (c.start - prevEnd > 0.05 && t >= prevEnd && t < c.start) {
+ return { start: prevEnd, len: c.start - prevEnd };
+ }
+ prevEnd = Math.max(prevEnd, c.start + clipLen(c));
+ }
+ return null;
+}
+
/** Cut the timeline range [at, at + delta) out of the whole document — the
* ripple half of a track-0 delete. Items past the hole slide left by delta;
* items wholly inside it are removed; items straddling an edge keep the part
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 3534a923..6b2e9834 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -162,12 +162,18 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "delete_item",
description:
- "Delete a video clip (any track), soundtrack clip, or title by id. Deleting a track-0 clip ripples: its footprint closes and everything after it — clips, titles, captions, soundtrack — slides left in sync; items wholly inside that span are removed with it, straddlers are trimmed. Deletes on other tracks remove just that item.",
+ "Delete a video clip (any track), soundtrack clip, or title by id. While track 0 is the only video track, deleting a track-0 clip ripples: its footprint closes and everything after it — clips, titles, captions, soundtrack — slides left in sync; items wholly inside that span are removed with it, straddlers are trimmed. With overlay video tracks present the delete leaves its gap in place (remove_gap closes it). Deletes on other tracks remove just that item.",
inputSchema: obj({
kind: { type: "string", enum: ["clip", "audio", "text"], description: "Item kind — 'clip' is any video clip, whatever track" },
id: str("Item id"),
}, ["kind", "id"]),
},
+ {
+ name: "remove_gap",
+ description:
+ "Close the empty track-0 span containing `at` seconds: that timeline range is cut out of the whole document, so everything after it — clips on every track, titles, captions, soundtrack — slides left in sync; items wholly inside it go with it, straddlers are trimmed. Errors unless `at` falls inside a gap.",
+ inputSchema: obj({ at: num("A time (seconds) inside the gap to close") }, ["at"]),
+ },
{
name: "add_overlay_video",
description:
@@ -695,7 +701,7 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim
"timeline-editing": `# Timeline editing
- Every track is free-positioned: items carry a start time, gaps are allowed, and a track-0 gap plays black (and silence). videoTrack entries in editor_state report gapBefore where one exists.
-- Deleting a track-0 clip ripples: the span it occupied closes, later items on every track slide left together, items wholly inside the span go with it, and straddlers are trimmed. A gap that already existed stays. Deletes on other tracks remove just that item.
+- While track 0 is the only video track, deleting a track-0 clip ripples: the span it occupied closes, later items on every track slide left together, items wholly inside the span go with it, and straddlers are trimmed. A gap that already existed stays. With overlay video tracks present the delete leaves its gap (remove_gap closes it — the same document-wide slide). Deletes on other tracks remove just that item.
- Two ways to move a track-0 clip: place_clip sets its start (respects gaps, slides right if the spot is taken); move_clip reorders by index, opening a slot at the landing point — clips after it shift right, every other gap survives. Index-based inserts (freeze_frame, generated clips) open a slot the same way.
- add_clip puts a project asset on the timeline the way a drag does: video/image onto track 0 (a \`start\`, an \`index\` insert, or appended at the end), audio onto the soundtrack.
- Overlay video: a video/image asset can sit on a track above track 0 (track 1, 2… — topmost wins). A full-frame overlay covers everything below it; give it a layout to share the frame — top/bottom/left/right halves for a split screen, pip for a floating corner box, or a custom region rect. add_overlay_video creates one from a media asset; update_overlay_video moves/trims/regions/mutes/hides it. The user makes them by dragging media above track 0; they drag the region in the preview.