Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): remove empty space closes one track's gap, tinted red while the menu decides [rebuild]

David Ledf3699c47ada
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 768b1e60..4231af78 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, track0GapAt, clipLen, clipSpeed, footprints, getClipSpans, nextFreeStart, overlayLayers, projectDuration, rippleInsert, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
+import { track0Clips, trackGapAt, 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";
@@ -315,10 +315,13 @@ 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);
+ // Right-click on a video row's empty space: a small popover offering to
+ // close that track's gap under the cursor. The cut is track-local — only
+ // the clicked track's later clips slide left — so the menu carries the gap
+ // it would cut and the row tints it red while the menu is open.
+ const [gapMenu, setGapMenu] = useState<
+ { x: number; y: number; track: number; gap: { start: number; len: number } } | null
+ >(null);
useEffect(() => {
if (!gapMenu) return;
const close = (e: KeyboardEvent) => {
@@ -649,6 +652,29 @@ export function Timeline() {
/>
) : null;
+ // 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 openGapMenu = (track: number) => (e: React.MouseEvent) => {
+ const gap = trackGapAt(useEditor.getState().clips, track, timeAt(e.clientX));
+ if (!gap) return;
+ e.preventDefault();
+ setGapMenu({ x: e.clientX, y: e.clientY, track, gap });
+ };
+
+ // The span the open gap menu would cut, tinted red on its own track.
+ const gapHighlight = (track: number, h: number) =>
+ gapMenu?.track === track ? (
+ <div
+ className="pointer-events-none absolute top-0.5 z-10 rounded-lg bg-red-500/15"
+ style={{
+ left: gapMenu.gap.start * pps,
+ width: Math.max(2, gapMenu.gap.len * pps - CLIP_GAP),
+ height: h,
+ }}
+ />
+ ) : null;
+
// The would-be new video track, one row past the stack's edge — the same
// grown-row experience as the audio and title lanes. Dropping here opens a
// brand-new track at z-level `level`.
@@ -935,9 +961,11 @@ export function Timeline() {
style={{ height: OVERLAY_H }}
data-drop={placementAttr({ kind: "track", track })}
onPointerDown={deselectIfSelf}
+ onContextMenu={openGapMenu(track)}
{...overlayDropHandlers({ kind: "track", track })}
>
{laneRail(OVERLAY_H - 2)}
+ {gapHighlight(track, OVERLAY_H - 4)}
{draggedOverlayTrack === track && laneDrag && (
<LaneSlot
drag={laneDrag}
@@ -995,17 +1023,10 @@ 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 });
- }}
+ onContextMenu={openGapMenu(0)}
>
{spans.length > 0 && laneRail(VIDEO_H - 2)}
+ {gapHighlight(0, VIDEO_H - 4)}
{trackSlot(TRACK_ZERO, VIDEO_H - 4)}
{laneDrag?.kind === "clip" && !laneDrag.away && (
<LaneSlot
@@ -1288,7 +1309,7 @@ export function Timeline() {
<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);
+ useEditor.getState().removeGap(gapMenu.track, gapMenu.gap.start);
setGapMenu(null);
}}
>
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index c27fb524..20e6c882 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, track0GapAt, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";
+import { applyOverlayPatchSettled, track0Clips, trackGapAt, 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";
@@ -470,10 +470,11 @@ export async function runAiTool(
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 };
+ const track = isNum(input.track) ? input.track : 0;
+ const gap = trackGapAt(s.clips, track, input.at);
+ if (!gap) throw new ToolError(`No track-${track} gap at ${input.at}s — pass a time inside the empty span.`);
+ s.removeGap(track, input.at);
+ return { closed: { track, ...gap } };
}
case "add_title": {
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index e71ec294..51d80341 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -347,23 +347,33 @@ describe("delete ripple and gaps", () => {
expect(clipById(layer.id).start).toBeCloseTo(1);
});
- test("removeGap closes the empty span across the whole document", () => {
+ test("removeGap closes the gap on its own track only", () => {
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);
+ s().removeGap(0, 1);
expect(clipById(b.id).start).toBeCloseTo(0);
- expect(clipById(layer.id).start).toBeCloseTo(0.5);
- expect(audioById(au.id).start).toBeCloseTo(1);
+ expect(clipById(layer.id).start).toBeCloseTo(2.5);
+ expect(audioById(au.id).start).toBeCloseTo(3);
+ });
+
+ test("removeGap between clips on an upper track slides only that track", () => {
+ const base = vclip({ track: 0, start: 0, out: 2 });
+ const l1 = vclip({ track: 1, start: 0, out: 1 });
+ const l2 = vclip({ track: 1, start: 3, out: 1 });
+ useEditor.setState({ clips: [base, l1, l2] });
+ s().removeGap(1, 2);
+ expect(clipById(l2.id).start).toBeCloseTo(1);
+ expect(clipById(base.id).start).toBeCloseTo(0);
});
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
+ s().removeGap(0, 1); // on a clip
+ s().removeGap(0, 6); // past the end
expect(clipById(a.id).start).toBeCloseTo(0);
expect(clipById(b.id).start).toBeCloseTo(3);
});
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 56b88185..acbbfbc9 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -286,11 +286,10 @@ export interface EditorState {
* 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;
+ /** Close the empty span on `track` containing `at`: that track's later
+ * clips slide left to shut the gap; every other track, the soundtrack,
+ * titles, and captions stay put. No-op when `at` isn't inside a gap. */
+ removeGap: (track: number, 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;
@@ -1655,23 +1654,19 @@ export const useEditor = create<EditorState>((baseSet, get) => {
});
},
- removeGap: (at) => {
- const gap = track0GapAt(get().clips, at);
+ removeGap: (track, at) => {
+ const gap = trackGapAt(get().clips, track, 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 },
- };
- });
+ set((s) => ({
+ clips: s.clips
+ .map((c) =>
+ c.track === track && c.start >= gap.start + gap.len - 0.001
+ ? { ...c, start: c.start - gap.len }
+ : c
+ )
+ .sort((a, b) => a.start - b.start),
+ }));
},
selectionRange: () => {
@@ -2789,15 +2784,15 @@ 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(
+/** The empty span on `track` containing time `t` — the stretch between two
+ * clip footprints (or before the first one). Null when `t` sits on a clip or
+ * past the last one (there is nothing after trailing space to pull left). */
+export function trackGapAt(
clips: VideoClip[],
+ track: number,
t: number
): { start: number; len: number } | null {
- const spine = track0Clips(clips).sort((a, b) => a.start - b.start);
+ const spine = clips.filter((c) => c.track === track).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) {
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 4e60df7a..fcb7240e 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -171,8 +171,11 @@ export const AI_TOOLS: AiToolDef[] = [
{
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"]),
+ "Close the empty span on one video track containing `at` seconds: that track's later clips slide left to shut the gap; every other track, titles, captions, and the soundtrack stay put. Errors unless `at` falls inside a gap on that track.",
+ inputSchema: obj({
+ at: num("A time (seconds) inside the gap to close"),
+ track: num("Video track the gap is on (default 0)"),
+ }, ["at"]),
},
{
name: "add_overlay_video",
@@ -701,7 +704,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.
-- 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.
+- 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 by sliding that track's later clips left). 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.