Open source CapCut alternative.
TypeScript
fix(cut): segments never overlap — settle every placement and committed update
David Le011cda63709d
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex e8ab3f63..b273f4cf 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, getClipSpans, overlayLayers, projectDuration, rippleInsert, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";+import { track0Clips, 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";@@ -265,10 +265,20 @@ export function Timeline() {}, []);// Drive the drop preview while a clip is dragged across tracks: highlight the- // target track's slot or a between-track insertion line.+ // target track's slot or a between-track insertion line. An existing track+ // slides the drop to its next free slot, so the slot previews where the clip+ // will actually land, not the raw pointer time.const previewCross = useCallback((target: TrackTarget | null, start = 0, len = 0) => {if (target === null) return setOverlayDrop(null);- setOverlayDrop({ target, t: start, len });+ const t =+ target.kind === "track"+ ? nextFreeStart(+ footprints(useEditor.getState().clips.filter((c) => c.track === target.track)),+ Math.max(0, start),+ len+ )+ : start;+ setOverlayDrop({ target, t, len });}, []);// Releasing a track-0 clip on any other track lifts it out onto that track@@ -549,7 +559,7 @@ export function Timeline() {e.dataTransfer.dropEffect = "copy";setAssetDrop(null);setDropType("video"); // keep the insertion zones lit however the drag entered- setOverlayDrop({ target: place, t: Math.max(0, timeAt(e.clientX)), len: vid.duration });+ previewCross(place, Math.max(0, timeAt(e.clientX)), vid.duration);},onDragLeave: (e: React.DragEvent) => {if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setOverlayDrop(null);diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 1bceaf24..5dcd7c3b 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 "./refMediimport { characterPrompt, stockTitle } from "./stock";import { STOCK_IMAGES } from "./stockManifest";import { STOCK_VIDEOS } from "./stockVideoManifest";-import { track0Clips, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";+import { applyOverlayPatchSettled, track0Clips, 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";@@ -476,7 +476,7 @@ export async function runAiTool(const cur = useEditor.getState();const sel = cur.selection;if (sel?.kind !== "text") throw new ToolError("Could not create the title.");- cur.updateOverlayTransient(sel.id, titlePatch({ ...input, id: sel.id }));+ applyOverlayPatchSettled(sel.id, titlePatch({ ...input, id: sel.id }));const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;return { id: o.id, text: o.text, start: o.start, end: o.end };}@@ -512,7 +512,14 @@ export async function runAiTool(if (!("duck" in patch) && Object.keys(patch).length === 0)throw new ToolError("Nothing to change.");s.updateAudio(a.id, patch);- return { id: a.id, ...patch };+ // Report where the clip actually sits: the store slides a committed move+ // to the lane's next free slot when the requested start overlaps.+ const landed = useEditor.getState().audioClips.find((c) => c.id === a.id)!;+ return {+ id: a.id,+ ...patch,+ ...("start" in patch ? { start: round2(landed.start) } : {}),+ };}case "set_framing": {@@ -1420,9 +1427,7 @@ export async function runAiTool(const start = isNum(input.start) ? Math.max(0, input.start) : cue.start;const end = isNum(input.end) ? input.end : cue.end;if (end - start < 0.15) throw new ToolError("Cue must stay at least 0.15s long.");- s.pushHistory();- s.updateCueTransient(cue.id, { start, end, words: undefined });- s.sortCues();+ s.setCueTiming(cue.id, start, end);}const next = useEditor.getState().subtitles.cues.find((c) => c.id === cue.id);return next ? { id: next.id, start: next.start, end: next.end, text: next.text } : { deleted: cue.id };diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 20342e30..da741ba5 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -262,6 +262,10 @@ export interface EditorState {mergeCueIntoPrev: (id: string) => void;deleteCue: (id: string) => void;updateCueTransient: (id: string, patch: Partial<SubtitleCue>) => void;+ /** Committed single-cue retime: keep the requested window's length, slide+ * right past occupied stretches on the cue's own lane so cues never overlap,+ * and detach the word timings (they described the old window). One undo step. */+ setCueTiming: (id: string, start: number, end: number) => void;/** Re-time listed cues to a generated voiceover: set each cue's [start, end]* and spread its words across the new span (the AI voice paces differently* from the original recording, so the word highlighter would otherwise drift). */@@ -353,6 +357,136 @@ let clipboard: ClipboardItem[] = [];* what is now a different language's track. */let laneEpoch = 0;+/** Fields whose committed change moves or resizes a footprint. `in` checks+ * (not undefined-checks) because some patches clear a field by writing+ * `undefined` (e.g. speed back to 1×). */+const touches = (patch: object, keys: readonly string[]) => keys.some((k) => k in patch);++/**+ * Committed patches keep the lane invariant: segments never overlap. Each+ * settle runs after a committed update lands, scoped to the item's own lane.+ * A move (start / track / lane) re-places the item at the first spot where it+ * intrudes into no resident; a resize (in / out / speed / end) keeps its start+ * and pushes the following same-lane run right by the overflow. For video+ * clips a declared cross-dissolve is contact, not intrusion — the pair may+ * overlap by the declared transition, exactly as the drag gestures allow.+ * Writes are transient: the committed action that calls this owns the history+ * entry, so the patch and its settle undo as one step.+ */+function settleClipFootprint(id: string, patch: Partial<VideoClip>) {+ const moved = touches(patch, ["start", "track"]);+ if (!moved && !touches(patch, ["in", "out", "speed"])) return;+ const st = useEditor.getState();+ const clip = st.clips.find((c) => c.id === id);+ if (!clip) return;+ const others = st.clips+ .filter((c) => c.id !== id && c.track === clip.track)+ .sort((a, b) => a.start - b.start);+ const len = clipLen(clip);+ if (moved) {+ let at = clip.start;+ for (const c of others) {+ const blockEnd = c.start + clipLen(c) - transitionOverlap(c, clip);+ if (blockEnd <= at + 1e-3) continue;+ if (c.start + transitionOverlap(clip, c) >= at + len - 1e-3) break;+ at = blockEnd;+ }+ if (Math.abs(at - clip.start) > 1e-9) st.updateClipTransient(id, { start: at });+ st.sortClips();+ return;+ }+ const next = others.find((c) => c.start >= clip.start - 1e-9);+ if (!next) return;+ const delta = clip.start + len - transitionOverlap(clip, next) - next.start;+ if (delta <= 1e-9) return;+ useEditor.setState((s) => ({+ clips: s.clips+ .map((c) =>+ c.id !== id && c.track === clip.track && c.start >= next.start - 1e-9+ ? { ...c, start: c.start + delta }+ : c+ )+ .sort((a, b) => a.start - b.start),+ }));+}++function settleAudioFootprint(id: string, patch: Partial<AudioClip>) {+ const moved = touches(patch, ["start", "lane"]);+ if (!moved && !touches(patch, ["in", "out", "speed"])) return;+ const st = useEditor.getState();+ const self = st.audioClips.find((a) => a.id === id);+ if (!self) return;+ const others = st.audioClips+ .filter((a) => a.id !== id && (a.lane ?? 0) === (self.lane ?? 0))+ .sort((a, b) => a.start - b.start);+ const len = clipLen(self);+ if (moved) {+ const at = nextFreeStart(footprints(others), self.start, len);+ if (Math.abs(at - self.start) > 1e-9) st.updateAudioTransient(id, { start: at });+ return;+ }+ const next = others.find((a) => a.start >= self.start - 1e-9);+ if (!next) return;+ const delta = self.start + len - next.start;+ if (delta <= 1e-9) return;+ useEditor.setState((s) => ({+ audioClips: s.audioClips.map((a) =>+ a.id !== id && (a.lane ?? 0) === (self.lane ?? 0) && a.start >= next.start - 1e-9+ ? { ...a, start: a.start + delta }+ : a+ ),+ }));+}++/** Apply a committed title patch and settle its lane. A start move without an+ * explicit end translates the title — its length rides along; an end change+ * resizes in place and pushes the run. Writes are transient: callers own the+ * history entry (exported for the AI's add_title, which patches inside the+ * add's own undo step; everything else comes through `updateOverlay`). */+export function applyOverlayPatchSettled(id: string, patch: Partial<TextOverlay>) {+ const st = useEditor.getState();+ const before = st.overlays.find((o) => o.id === id);+ if (!before) return;+ const p = { ...patch };+ if ("start" in p && !("end" in p) && p.start !== undefined)+ p.end = p.start + (before.end - before.start);+ st.updateOverlayTransient(id, p);+ settleOverlayFootprint(id, p);+}++function settleOverlayFootprint(id: string, patch: Partial<TextOverlay>) {+ const moved = touches(patch, ["start", "lane"]);+ if (!moved && !touches(patch, ["end"])) return;+ const st = useEditor.getState();+ const self = st.overlays.find((o) => o.id === id);+ if (!self) return;+ const others = st.overlays+ .filter((o) => o.id !== id && (o.lane ?? 0) === (self.lane ?? 0))+ .sort((a, b) => a.start - b.start);+ const len = Math.max(0.2, self.end - self.start);+ if (moved) {+ const at = nextFreeStart(+ others.map((o) => ({ start: o.start, end: o.end })),+ self.start,+ len+ );+ if (Math.abs(at - self.start) > 1e-9)+ st.updateOverlayTransient(id, { start: at, end: at + len });+ return;+ }+ const next = others.find((o) => o.start >= self.start - 1e-9);+ if (!next) return;+ const delta = self.end - next.start;+ if (delta <= 1e-9) return;+ useEditor.setState((s) => ({+ overlays: s.overlays.map((o) =>+ o.id !== id && (o.lane ?? 0) === (self.lane ?? 0) && o.start >= next.start - 1e-9+ ? { ...o, start: o.start + delta, end: o.end + delta }+ : o+ ),+ }));+}+/** Resize a clip's footprint to `newLen` (a trim or speed change), keeping its* own track sound: a live dissolve into the next clip stays a dissolve (the* run follows the resize so the pair keeps its overlap); otherwise a longer@@ -1016,6 +1150,7 @@ export const useEditor = create<EditorState>((set, get) => {updateClip: (id, patch) => {push();get().updateClipTransient(id, patch);+ settleClipFootprint(id, patch);},setClipSpeed: (id, speed) => {@@ -1081,10 +1216,11 @@ export const useEditor = create<EditorState>((set, get) => {updateAudio: (id, patch) => {push();get().updateAudioTransient(id, patch);+ settleAudioFootprint(id, patch);},updateOverlay: (id, patch) => {push();- get().updateOverlayTransient(id, patch);+ applyOverlayPatchSettled(id, patch);},updateOverlayTransient: (id, patch) =>@@ -2320,6 +2456,19 @@ export const useEditor = create<EditorState>((set, get) => {},})),+ setCueTiming: (id, start, end) => {+ const cue = get().subtitles.cues.find((c) => c.id === id);+ if (!cue) return;+ const len = Math.max(0.15, end - start);+ const taken = get()+ .subtitles.cues.filter((c) => c.id !== id && (c.lane ?? 0) === (cue.lane ?? 0))+ .map((c) => ({ start: c.start, end: c.end }));+ const at = nextFreeStart(taken, Math.max(0, start), len);+ push();+ get().updateCueTransient(id, { start: at, end: at + len, words: undefined });+ get().sortCues();+ },+retimeCues: (entries) => {if (entries.length === 0) return;const byId = new Map(entries.map((e) => [e.id, e]));