Skip to content

Open source CapCut alternative.

TypeScript

fix(site): harden timeline gestures and subtitle tracks from review findings [rebuild]

David Le805047b571b6
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index 2830cb54..d4fe6f8c 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -12,6 +12,7 @@ import {
karaokeLook,
laneCues,
subtitleLaneCount,
+ trackLocale,
} from "@/cut/lib/subtitles";
import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";
import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";
@@ -43,16 +44,12 @@ const TIMELINE_H_WITH_SUBS = Math.max(TIMELINE_H_MIN, 276);
/** A track's short pill label: its language code (EN, KO, …). */
function laneLabel(subs: SubtitlesBlock, lane: number): string {
- const locale =
- subs.tracks?.[lane]?.locale ?? (lane === 0 ? subs.locale : undefined) ?? "en-US";
- return locale.split("-")[0].toUpperCase();
+ return trackLocale(subs, lane).split("-")[0].toUpperCase();
}
/** A track's language name from the locale picker list, else its short code. */
function laneLanguage(subs: SubtitlesBlock, lane: number): string {
- const locale =
- subs.tracks?.[lane]?.locale ?? (lane === 0 ? subs.locale : undefined) ?? "en-US";
- return LOCALES.find(([id]) => id === locale)?.[1] ?? laneLabel(subs, lane);
+ return LOCALES.find(([id]) => id === trackLocale(subs, lane))?.[1] ?? laneLabel(subs, lane);
}
export function SubtitlesPanel() {
@@ -387,8 +384,7 @@ function EmptyState({
}) {
const subtitles = useEditor((s) => s.subtitles);
const lane = useEditor((s) => s.subtitleLane);
- const locale =
- subtitles.tracks?.[lane]?.locale ?? (lane === 0 ? subtitles.locale : undefined) ?? "en-US";
+ const locale = trackLocale(subtitles, lane);
// Other tracks that already have captions — each can seed this one by translation.
const sources = Array.from({ length: subtitleLaneCount(subtitles) }, (_, i) => i).filter(
(i) => i !== lane && laneCues(subtitles, i).length > 0
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 835d7f75..7a7b4dcf 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -24,7 +24,7 @@ import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";
import { ensurePeaks, importImage, importStockVideo } from "@/cut/lib/media";
-import { clipLen, clipSpeed, getClipSpans, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
+import { clipLen, clipSpeed, getClipSpans, nextFreeStart, projectDuration, 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";
@@ -571,7 +571,15 @@ export function Timeline() {
setAssetDrop(null);
return;
}
- setAssetDrop({ t: Math.max(0, timeAt(e.clientX)), len: duration });
+ // Preview the true landing spot: the drop slides past occupied
+ // stretches to the next free slot, so the dashed box must too — a
+ // box under the pointer that lands minutes away is a lie.
+ const cur = useEditor.getState();
+ const taken = cur.clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));
+ setAssetDrop({
+ t: nextFreeStart(taken, Math.max(0, timeAt(e.clientX)), duration),
+ len: duration,
+ });
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
@@ -677,7 +685,7 @@ export function Timeline() {
</Button>
</div>
- <div ref={scrollRef} className="tl-scroll min-h-0 flex-1 overflow-auto">
+ <div ref={scrollRef} data-tl-scroll className="tl-scroll min-h-0 flex-1 overflow-auto">
<div className="flex min-h-full flex-col" style={{ width: contentW + PAD_SIDE * 2 }}>
<div
ref={innerRef}
@@ -1303,6 +1311,9 @@ function ClipView({
rowH: VIDEO_H,
laneCount: 0,
homeRow: 0,
+ // The box is inset by half the incoming dissolve; click-to-seek anchors
+ // on where the box is drawn, not the clip's footprint start.
+ visStart,
onDrag,
onSnap,
vertical: {
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index bc5ee193..e6771456 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -29,7 +29,7 @@
import type React from "react";
import { refFromAsset, startPointerRefDrag } from "./assetRef";
import { startDrag } from "./drag";
-import { clipLen, getClipSpans, projectDuration, useEditor } from "./store";
+import { clipLen, getClipSpans, projectDuration, transitionOverlap, useEditor } from "./store";
import type {
AudioClip,
MediaAsset,
@@ -87,6 +87,10 @@ interface LaneAdapter<T> {
assetOf?(s: S, raw: T): MediaAsset | undefined;
/** After a committed move (e.g. keep cues sorted). */
onMoved?(): void;
+ /** Legal physical overlap (seconds) of `raw` into the same-lane item after
+ * it — a video cross-dissolve's declared width. Gestures treat overlap up
+ * to this as contact, not intrusion. Absent = footprints are solid. */
+ overlapInto?(raw: T, next: T): number;
}
const speedOf = (c: { speed?: number }) => (c.speed && c.speed > 0 ? c.speed : 1);
@@ -117,6 +121,7 @@ const clipAdapter: LaneAdapter<VideoClip> = {
},
assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),
onMoved: () => useEditor.getState().sortClips(),
+ overlapInto: (c, next) => transitionOverlap(c, next),
};
const audioAdapter: LaneAdapter<AudioClip> = {
@@ -293,6 +298,10 @@ export interface LaneMoveUI<V = unknown> {
laneCount: number;
/** The grabbed item's current display row. */
homeRow: number;
+ /** Timeline second the item's box is rendered at, when it differs from the
+ * item's start (a clip after a cross-dissolve draws inset by half the
+ * overlap) — keeps click-to-seek under the pointer. */
+ visStart?: number;
/** Publish (or clear) the in-flight drag so the slot and rows track it. */
onDrag(d: LaneDrag | null): void;
/** Paint (or clear) the snap guide at this stage-x pixel. */
@@ -329,7 +338,10 @@ export function startLaneMove<V = unknown>(
const self = ad.view(raw0);
s.select({ kind, id } as Selection);
// Clicking anywhere on the timeline moves the playhead — bars included.
- s.seek(self.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / ui.pps);
+ s.seek(
+ (ui.visStart ?? self.start) +
+ (e.clientX - e.currentTarget.getBoundingClientRect().left) / ui.pps
+ );
s.pushHistory();
const start0 = self.start;
@@ -345,10 +357,15 @@ export function startLaneMove<V = unknown>(
);
const targets = snapTargets(s, kind, id);
const tol = SNAP_PX / ui.pps;
+ const allow = (a: LaneRaw, b: LaneRaw) => ad.overlapInto?.(a, b) ?? 0;
// Dragging a media-backed item can also hand its asset to a reference drop
// zone (AI chat, the image/video creators).
const asset = ad.assetOf?.(s, raw0);
const refDrag = asset ? startPointerRefDrag(refFromAsset(asset)) : null;
+ // Dragging against a viewport edge scrolls the timeline so off-screen times
+ // stay reachable; the scroll distance folds back into the drag delta.
+ const scroller = (e.currentTarget as HTMLElement).closest<HTMLElement>("[data-tl-scroll]");
+ const sc0 = scroller?.scrollLeft ?? 0;
let live = false;
let targetRow = ui.homeRow;
@@ -356,7 +373,24 @@ export function startLaneMove<V = unknown>(
let ds = start0;
let awayTarget: V | null = null;
- const restRestore = () => ad.apply(rest.map((x) => ad.movePatch(x.raw, x.view.start)));
+ // Patch only items whose position actually changes this frame (plus
+ // restores of previously shifted ones): dragging one cue must not rebuild
+ // hundreds of unmoved neighbors on every mousemove.
+ const shifted = new Map<string, number>();
+ const applyMoves = (startFor: (x: (typeof rest)[number]) => number) => {
+ const patches: Patch<LaneRaw>[] = [];
+ for (const x of rest) {
+ const want = startFor(x);
+ const cur = shifted.get(x.view.id) ?? x.view.start;
+ if (Math.abs(want - cur) > 1e-9) {
+ patches.push(ad.movePatch(x.raw, want));
+ if (Math.abs(want - x.view.start) > 1e-9) shifted.set(x.view.id, want);
+ else shifted.delete(x.view.id);
+ }
+ }
+ if (patches.length) ad.apply(patches);
+ };
+ const restRestore = () => applyMoves((x) => x.view.start);
startDrag(e, {
onMove: (dx, dy, ev) => {
@@ -364,7 +398,13 @@ export function startLaneMove<V = unknown>(
if (!live) ui.vertical?.setActive?.(true);
live = true;
refDrag?.move(ev);
- ds = Math.max(0, start0 + dx / ui.pps);
+ if (scroller) {
+ const r = scroller.getBoundingClientRect();
+ if (ev.clientX > r.right - 36) scroller.scrollLeft += 14;
+ else if (ev.clientX < r.left + 36) scroller.scrollLeft -= 14;
+ }
+ const effDx = dx + ((scroller?.scrollLeft ?? sc0) - sc0);
+ ds = Math.max(0, start0 + effDx / ui.pps);
// Carried off its own lane set (an upper video layer headed to another
// track, down to track 0, or an insert gap): neighbors flow back and
@@ -395,8 +435,15 @@ export function startLaneMove<V = unknown>(
targetRow = ad.multiLane
? Math.min(ui.laneCount, Math.max(0, ui.homeRow + Math.round(dy / ui.rowH)))
: ui.homeRow;
- // A brand-new row has no neighbors to part.
- const lane = targetRow < usedLanes.length ? usedLanes[targetRow] : Infinity;
+ // Which lane to part/collide on: multi-lane rows are display indexes
+ // into the compacted used-lane list (a row past the end is a brand-new
+ // lane with no neighbors); single-lane kinds stay on their own lane —
+ // their row number is not an index into that list.
+ const lane = ad.multiLane
+ ? targetRow < usedLanes.length
+ ? usedLanes[targetRow]
+ : Infinity
+ : self.lane;
// Snap whichever edge of the moving item lands nearest a logical time.
let start = ds;
@@ -417,24 +464,34 @@ export function startLaneMove<V = unknown>(
}
// Same-lane neighbors part around the slot: ones whose midpoint sits
// left of the ghost's center keep their spot (the slot lands after
- // them), the rest slide right as a run to make room.
+ // them), the rest slide right as a run to make room. A cross-dissolve
+ // is contact, not intrusion: the slot may overlap the neighbor before
+ // it by that neighbor's declared transition, and only pushes the run
+ // after it once the overlap into its first item exceeds the item's own
+ // declared transition.
const others = rest
.filter((x) => x.view.lane === lane)
.sort((a, b) => a.view.start - b.view.start);
const center = ds + len / 2;
const before = others.filter((x) => x.view.start + x.view.len / 2 <= center);
const after = others.filter((x) => x.view.start + x.view.len / 2 > center);
- const clamped = Math.max(start, ...before.map((b) => b.view.start + b.view.len));
+ const prev = before[before.length - 1];
+ const clampFloor = prev
+ ? Math.max(
+ 0,
+ ...before.slice(0, -1).map((b) => b.view.start + b.view.len),
+ prev.view.start + prev.view.len - allow(prev.raw, raw0)
+ )
+ : 0;
+ const clamped = Math.max(start, clampFloor);
if (clamped !== start) guide = null;
slotStart = clamped;
- const delta = after.length ? Math.max(0, clamped + len - after[0].view.start) : 0;
+ const delta = after.length
+ ? Math.max(0, clamped + len - allow(raw0, after[0].raw) - after[0].view.start)
+ : 0;
const pushed = new Set(after.map((x) => x.view.id));
ui.onSnap(guide);
- ad.apply(
- rest.map((x) =>
- ad.movePatch(x.raw, pushed.has(x.view.id) ? x.view.start + delta : x.view.start)
- )
- );
+ applyMoves((x) => (pushed.has(x.view.id) ? x.view.start + delta : x.view.start));
ui.onDrag({ kind, id, targetRow, ghostX: ds * ui.pps, slotStart: clamped, len });
},
onUp: (_dx, _dy, moved) => {
@@ -504,6 +561,7 @@ export function startLaneTrim(
s.pushHistory();
const targets = snapTargets(s, kind, id);
const tol = SNAP_PX / ui.pps;
+ const allow = (a: LaneRaw, b: LaneRaw) => ad.overlapInto?.(a, b) ?? 0;
const sameLane = ad
.raws(s)
.map((r) => ({ raw: r, view: ad.view(r) }))
@@ -512,17 +570,24 @@ export function startLaneTrim(
if (side === "l") {
const start0 = self.start;
const maxStart = start0 + self.len - ad.minLen;
- // Items before this one, at their original spots. The edge grows freely
- // into the open gap; past the neighbor it shoves the run left, closing
- // gap after gap until everything sits flush against 0 — plus a media
- // item's own floor: the edge can't reveal earlier than its first sample.
+ // Items before this one (start-ordered), at their original spots. The
+ // edge grows freely into the open gap; past the neighbor it shoves the
+ // run left, closing gap after gap until everything sits flush against 0 —
+ // plus a media item's own floor: the edge can't reveal earlier than its
+ // first sample. The nearest leader may be a cross-dissolve partner whose
+ // footprint crosses this item's start: it yields its declared overlap
+ // before the edge starts pushing it.
const leaders = sameLane
- .filter((x) => x.view.start + x.view.len <= start0 + 1e-3)
+ .filter((x) => x.view.start < start0 - 1e-3)
.sort((a, b) => a.view.start - b.view.start);
- const prevEnd = leaders.reduce((m, l) => Math.max(m, l.view.start + l.view.len), 0);
- const runFloor = leaders.reduce((sum, l) => sum + l.view.len, 0);
+ const last = leaders[leaders.length - 1];
+ const lastAllow = last ? allow(last.raw, raw0) : 0;
+ const prevEnd =
+ leaders.reduce((m, l) => Math.max(m, l.view.start + l.view.len), 0) - lastAllow;
+ const runFloor = leaders.reduce((sum, l) => sum + l.view.len, 0) - lastAllow;
const floor = Math.max(runFloor, ad.leftFloor(raw0));
const free = Math.max(prevEnd, ad.leftFloor(raw0));
+ const moved = new Map<string, number>();
startDrag(e, {
onMove: (dx, _dy, ev) => {
cancelAnimationFrame(snapBackRaf);
@@ -549,14 +614,21 @@ export function startLaneTrim(
}
// Re-lay the leaders right-to-left from their resting spots: each one
// slides only as far as the pushed edge (or the item it now abuts)
- // forces it, so a retreating drag lets the run flow back.
+ // forces it, so a retreating drag lets the run flow back. Unmoved
+ // leaders get no patch (they'd re-render for nothing).
const patches = [ad.trimLeftPatch(raw0, start)];
- let limit = Math.max(start, runFloor);
+ let limit = Math.max(start, runFloor) + lastAllow;
for (let i = leaders.length - 1; i >= 0; i--) {
const l = leaders[i];
const end = Math.min(l.view.start + l.view.len, limit);
- patches.push(ad.movePatch(l.raw, end - l.view.len));
- limit = end - l.view.len;
+ const ns = end - l.view.len;
+ const cur = moved.get(l.view.id) ?? l.view.start;
+ if (Math.abs(ns - cur) > 1e-9) {
+ patches.push(ad.movePatch(l.raw, ns));
+ if (Math.abs(ns - l.view.start) > 1e-9) moved.set(l.view.id, ns);
+ else moved.delete(l.view.id);
+ }
+ limit = ns;
}
ad.apply(patches);
},
@@ -584,11 +656,16 @@ export function startLaneTrim(
const maxEnd = self.start + ad.maxLen(s, raw0);
// Items after this one, at their original spots: extending the edge past
// the first of them pushes the whole run right (their gaps preserved);
- // pulling back lets them return.
+ // pulling back lets them return. A cross-dissolve into the first follower
+ // is contact, not intrusion — the edge only pushes once the overlap
+ // exceeds the declared transition, so grabbing a dissolved clip's handle
+ // never shoves its partner.
const followers = sameLane
.filter((x) => x.view.start >= self.start)
.sort((a, b) => a.view.start - b.view.start);
const nextStart = followers.length ? followers[0].view.start : Infinity;
+ const nextAllow = followers.length ? allow(raw0, followers[0].raw) : 0;
+ let lastDelta = 0;
startDrag(e, {
onMove: (dx, _dy, ev) => {
let end = Math.max(minEnd, Math.min(maxEnd, end0 + dx / ui.pps));
@@ -597,11 +674,13 @@ export function startLaneTrim(
end = hit;
ui.onSnap(rightGuide(end, ui.pps));
} else ui.onSnap(null);
- const delta = Math.max(0, end - nextStart);
- ad.apply([
- ad.trimRightPatch(raw0, end),
- ...followers.map((f) => ad.movePatch(f.raw, f.view.start + delta)),
- ]);
+ const delta = Math.max(0, end - nextAllow - nextStart);
+ const run =
+ delta === lastDelta
+ ? []
+ : followers.map((f) => ad.movePatch(f.raw, f.view.start + delta));
+ lastDelta = delta;
+ ad.apply([ad.trimRightPatch(raw0, end), ...run]);
},
onUp: () => ui.onSnap(null),
});
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index ce962483..50fd1823 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -23,6 +23,7 @@ import type {
VideoClip,
} from "./types";
import { apiFetch, apiJson } from "./api";
+import { trackLocale } from "./subtitles";
import { emptySubtitles, IMAGE_CLIP_SECONDS, isCrossStyle, MAX_SUBTITLE_LANES, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";
import { readTextStyle } from "./textStyle";
import { loadUiState, saveUiState } from "./uiState";
@@ -162,7 +163,9 @@ export interface EditorState {
/** Keep the clips array sorted by start (consumers read `clips[0]` as the
* timeline's first clip). Called after a lane-coordinator move commits. */
sortClips: () => void;
- /** Reorder video track 0 by index and re-pack it (the AI reorder op). */
+ /** Reorder video track 0 by index (the AI reorder op): the clip lifts out
+ * (leaving a gap) and a slot opens at the target index — clips from the
+ * landing point shift right; nothing else moves. */
moveClip: (id: string, toIndex: number) => void;
/** Add a video asset to the timeline at a placement: an existing track or a
* freshly inserted one. Used by media / library drops. */
@@ -645,16 +648,36 @@ export const useEditor = create<EditorState>((set, get) => {
const newLen = Math.max(MIN_LEN, (clip.out - clip.in) / clamped);
push();
get().updateClipTransient(id, { speed: clamped });
- // Free track: a longer footprint pushes the following run right by the
- // overflow (like a resize); a shorter one just opens a gap.
const followers = s.clips.filter((c) => c.id !== id && c.start >= clip.start);
- const nextStart = followers.reduce((m, c) => Math.min(m, c.start), Infinity);
- const delta = Math.max(0, clip.start + newLen - nextStart);
- if (delta > 1e-6) {
+ const next = followers.reduce<VideoClip | null>(
+ (m, c) => (!m || c.start < m.start ? c : m),
+ null
+ );
+ const nextStart = next?.start ?? Infinity;
+ // A live dissolve into the next clip stays a dissolve: the run follows
+ // the resize (both directions) so the pair keeps its overlap. Otherwise
+ // free-track rules — a longer footprint pushes the run right by the
+ // overflow (like a resize); a shorter one just opens a gap.
+ const keep = next
+ ? Math.min(
+ transitionOverlap(clip, next),
+ Math.max(0, clip.start + clipLen(clip) - nextStart),
+ newLen * 0.9
+ )
+ : 0;
+ const delta =
+ keep > 1e-6
+ ? clip.start + newLen - keep - nextStart
+ : Math.max(0, clip.start + newLen - nextStart);
+ if (Math.abs(delta) > 1e-6) {
set((st) => ({
- clips: st.clips.map((c) =>
- c.id !== id && c.start >= clip.start ? { ...c, start: c.start + delta } : c
- ),
+ clips: st.clips
+ .map((c) =>
+ c.id !== id && c.start >= clip.start
+ ? { ...c, start: Math.max(0, c.start + delta) }
+ : c
+ )
+ .sort((a, b) => a.start - b.start),
}));
}
},
@@ -788,18 +811,31 @@ export const useEditor = create<EditorState>((set, get) => {
})),
moveClip: (id, toIndex) => {
- // The AI reorder op: splice the clip to the target index (in start
- // order) and re-pack the whole track. Pointer drags never come here —
- // they free-place through the lane coordinator.
+ // The AI reorder op: lift the clip out (its old spot becomes a gap) and
+ // open a slot at the target index — the landing clip and everything
+ // after it shift right by the moved footprint, everything else keeps
+ // its absolute time, so audio, titles, and captions stay synced to the
+ // clips they annotate. Pointer drags never come here — they free-place
+ // through the lane coordinator.
const clips = [...get().clips].sort((a, b) => a.start - b.start);
const from = clips.findIndex((c) => c.id === id);
if (from < 0) return;
const to = Math.max(0, Math.min(clips.length - 1, toIndex));
if (to === from) return;
push();
- const [moved] = clips.splice(from, 1);
- clips.splice(to, 0, moved);
- set({ clips: packStarts(clips) });
+ const moved = clips[from];
+ const others = clips.filter((c) => c.id !== id);
+ const len = clipLen(moved);
+ const anchor = to < others.length ? others[to] : null;
+ const newStart = anchor ? anchor.start : totalDuration(others);
+ set({
+ clips: [
+ ...others.map((c) =>
+ c.start >= newStart - 1e-6 ? { ...c, start: c.start + len } : c
+ ),
+ { ...moved, start: newStart },
+ ].sort((a, b) => a.start - b.start),
+ });
},
addVideoFromAsset: (assetId, place, start) => {
@@ -1301,7 +1337,7 @@ export const useEditor = create<EditorState>((set, get) => {
const lane = s.subtitleLane;
const spec = {
duration,
- locale: s.subtitles.tracks?.[lane]?.locale ?? s.subtitles.locale ?? "en-US",
+ locale: trackLocale(s.subtitles, lane),
// The transcribe mix is a sequential fold, so gaps between the
// free-placed clips ship as explicit silent spacers (empty file).
clips: spanSequence(spans).flatMap(({ gapBefore, span: sp }) => [
@@ -1337,7 +1373,10 @@ export const useEditor = create<EditorState>((set, get) => {
// Only the active track's cues are replaced; other languages stay.
const tagged = cues.map((c) => ({ ...c, ...(lane > 0 ? { lane } : {}) }));
if (cues.length === 0) {
- // No speech in the audio — leave the other tracks untouched.
+ // No speech in the audio — leave the other tracks untouched. This
+ // still deletes the active track's cues (possibly hand-edited), so
+ // it checkpoints like the replace path: ⌘Z brings them back.
+ if (get().subtitles.cues.some((c) => (c.lane ?? 0) === lane)) push();
set((cur) => ({
subtitles: {
...cur.subtitles,
@@ -1383,7 +1422,7 @@ export const useEditor = create<EditorState>((set, get) => {
// clip says even when its timeline audio is muted.
const spec = {
duration: sp.len,
- locale: s.subtitles.tracks?.[lane]?.locale ?? s.subtitles.locale ?? "en-US",
+ locale: trackLocale(s.subtitles, lane),
clips: [
{
file: sp.asset.fileName,
@@ -1453,7 +1492,7 @@ export const useEditor = create<EditorState>((set, get) => {
body: JSON.stringify({
frames,
duration,
- locale: s.subtitles.tracks?.[lane]?.locale ?? s.subtitles.locale ?? "en-US",
+ locale: trackLocale(s.subtitles, lane),
}),
});
const body = await apiJson<{
@@ -1560,10 +1599,7 @@ export const useEditor = create<EditorState>((set, get) => {
const laneOf = (c: SubtitleCue) => c.lane ?? 0;
const source = s.subtitles.cues.filter((c) => laneOf(c) === fromLane);
if (source.length === 0) return;
- const locale =
- s.subtitles.tracks?.[lane]?.locale ??
- (lane === 0 ? s.subtitles.locale : undefined) ??
- "en-US";
+ const locale = trackLocale(s.subtitles, lane);
const projectId = s.projectId;
set({ subtitleStatus: "running", subtitleError: null });
try {
@@ -1664,6 +1700,11 @@ export const useEditor = create<EditorState>((set, get) => {
subtitles: {
...cur.subtitles,
tracks,
+ // The block-level legacy locale and dragged anchor described the
+ // first track; when that track goes, they go with it — the
+ // promoted track must not inherit the deleted one's language or
+ // caption spot.
+ ...(lane === 0 ? { locale: undefined, x: undefined, y: undefined } : {}),
cues: cur.subtitles.cues
.filter((c) => (c.lane ?? 0) !== lane)
.map((c) => {
@@ -2087,8 +2128,7 @@ export function totalDuration(clips: VideoClip[]) {
type LegacyClip = Omit<VideoClip, "start"> & { start?: number };
/** Assign packed sequential starts (each clip after the previous, dissolves
- * overlapping): the layout older docs implied by array order. Also the shape
- * `moveClip` (the AI reorder op) re-lays the track into. */
+ * overlapping): the layout older docs implied by array order. */
function packStarts(clips: LegacyClip[]): VideoClip[] {
let t = 0;
const out: VideoClip[] = [];
diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.ts
index d128464c..67692f6e 100644
--- a/site/src/cut/lib/subtitles.ts
+++ b/site/src/cut/lib/subtitles.ts
@@ -23,6 +23,14 @@ export function laneCues(subs: SubtitlesBlock, lane: number): SubtitleCue[] {
return subs.cues.filter((c) => (c.lane ?? 0) === lane);
}
+/** A track's language: its own meta, then the block-level legacy locale (which
+ * described the first track only), then English. The panel's language select
+ * and every generation path read this same chain, so the language shown is
+ * always the language sent. */
+export function trackLocale(subs: SubtitlesBlock, lane: number): string {
+ return subs.tracks?.[lane]?.locale ?? (lane === 0 ? subs.locale : undefined) ?? "en-US";
+}
+
/** A track's effective caption anchor plus the block's karaoke overrides —
* the `pos` argument `cueOverlay` takes. The track's own dragged spot wins,
* then the block-level legacy spot (first track only), then the style's
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index dafd5467..59e36d56 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -70,7 +70,7 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "move_clip",
description:
- "Reorder a track-0 video clip to a new index and re-pack the track end-to-end — this closes every gap. To move one clip in time (keeping gaps), use place_clip.",
+ "Reorder a track-0 video clip to a new index: it lifts out (its old spot becomes a gap) and clips from the landing index shift right to make room — nothing else moves, so sound and titles stay synced. To move one clip in time, use place_clip.",
inputSchema: obj({ clipId: str("Video clip id"), toIndex: num("Target index, 0-based") }, ["clipId", "toIndex"]),
},
{
@@ -99,7 +99,7 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "delete_item",
description:
- "Delete a video clip, overlay video, soundtrack clip, or title by id. Every track is free-positioned, so deleting leaves a gap; close it with move_clip if the cut should stay tight.",
+ "Delete a video clip, overlay video, soundtrack clip, or title by id. Every track is free-positioned, so deleting leaves a gap; place_clip can slide a neighbor into it if the cut should stay tight.",
inputSchema: obj({
kind: { type: "string", enum: ["clip", "overlayClip", "audio", "text"], description: "Item kind" },
id: str("Item id"),
@@ -486,7 +486,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). Deleting leaves a gap. videoTrack entries in editor_state report gapBefore where one exists.
-- 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 and re-packs the whole track end-to-end — the right call for "put this first" or "tighten the cut", wrong when the user laid out deliberate gaps. Index-based inserts (freeze_frame, generated clips) also re-pack.
+- 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.
- Overlay video: a video/image asset can sit on a track above track 0 (track 1, 2… — topmost wins) or behind it (track -1…). 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/below track 0; they drag the region in the preview.
- A clip's timeline length is (out-in)/speed; total duration runs to the last clip's end, gaps included, minus cross-style transition overlaps.
- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index 0819a626..77c2e165 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -467,9 +467,12 @@ async function runExport(job: Job, spec: ExportSpec) {
const filters: string[] = [];
- // Per-clip timeline length (source span compressed/expanded by speed).
+ // Per-clip timeline length (source span compressed/expanded by speed). A
+ // gap spacer (no file) keeps its exact length: flooring it at 0.1s would
+ // land everything after the gap later than the timeline shows, drifting
+ // burned-in captions off the picture.
const clipDur = (c: ExportSpec["clips"][number]) =>
- Math.max(0.1, (c.out - c.in) / clipRate(c));
+ c.file ? Math.max(0.1, (c.out - c.in) / clipRate(c)) : Math.max(0, c.out - c.in);
// Per-clip normalized video + audio segments for the join below.
spec.clips.forEach((c, j) => {
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index 2623e771..7bdedad1 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -219,10 +219,12 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
const filters: string[] = [];
// Per-clip timeline length: a sped-up clip is shorter and time-stretched,
- // so the transcript's cue times line up with what the user sees.
+ // so the transcript's cue times line up with what the user sees. A gap
+ // spacer (no file) keeps its exact length — flooring it at 0.1s would
+ // land every cue after the gap late.
const clipDur = (c: TranscribeSpec["clips"][number]) => {
const speed = c.speed && c.speed > 0 ? c.speed : 1;
- return Math.max(0.1, (c.out - c.in) / speed);
+ return c.file ? Math.max(0.1, (c.out - c.in) / speed) : Math.max(0, c.out - c.in);
};
spec.clips.forEach((c, j) => {
const speed = c.speed && c.speed > 0 ? c.speed : 1;