Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

feat(captions): land a caption run as one undoable batch

Jareer51925e624368
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index dc2c3f81..fef75b99 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -72,8 +72,6 @@ import { useTransport } from "./lib/transport";
const MIN_SECONDS_PER_PIXEL = 0.0005;
const MAX_SECONDS_PER_PIXEL = 2;
-/** Matches the engine's default title length, for caption timing math. */
-const DEFAULT_TEXT_DURATION = 4;
/** What the editor renders for the frame or two before the session opens. */
const EMPTY_PROJECT: EditorProject = {
@@ -310,10 +308,11 @@ function Editor({
setEcho(null);
return;
}
- void (async () => {
- for (const command of commands) await dispatch(command);
- setEcho(null);
- })();
+ // A gesture that resolves to several commands is still one gesture, so
+ // it lands as one batch: one round trip, one undo step.
+ const command: EditorCommand =
+ commands.length === 1 ? commands[0] : { op: "batch", commands };
+ void dispatch(command).then(() => setEcho(null));
}, [dispatch]);
// ── the session ──────────────────────────────────────────────────────────
@@ -724,25 +723,21 @@ function Editor({
await dispatch({ op: "renameTrack", trackId, name: "Captions" });
}
- for (const segment of segments) {
- const start = clip.start + segment.start / clip.speed;
- const wanted = Math.max(0.4, (segment.end - segment.start) / clip.speed);
- const clipId = await dispatch({
+ // One batch, one undo: "undo the captions" must not mean sixty
+ // presses. Each caption carries its own length and placement, so no
+ // per-clip follow-up commands are needed.
+ await dispatch({
+ op: "batch",
+ commands: segments.map((segment) => ({
op: "addTextClip",
trackId,
- start,
+ start: clip.start + segment.start / clip.speed,
+ duration: Math.max(0.4, (segment.end - segment.start) / clip.speed),
+ offsetY: 0.38,
// Caption-sized and lower-third, not title-sized and centred.
style: { ...defaultTextStyle(), content: segment.text, fontSize: 0.045 },
- });
- if (!clipId) continue;
- await dispatch({
- op: "trimClip",
- clipId,
- edge: "end",
- delta: wanted - DEFAULT_TEXT_DURATION,
- });
- await dispatch({ op: "setClipTransform", clipId, offsetY: 0.38 });
- }
+ })),
+ });
setToast({
id: Date.now(),
message: `Added ${segments.length} caption${segments.length === 1 ? "" : "s"}`,
diff --git a/desktop/src/lib/editor.ts b/desktop/src/lib/editor.ts
index 2eff3021..8f8b43be 100644
--- a/desktop/src/lib/editor.ts
+++ b/desktop/src/lib/editor.ts
@@ -169,7 +169,18 @@ export type EditorCommand =
| { op: "batch"; commands: EditorCommand[] }
| { op: "addClip"; mediaId: string; trackId: string; start: number }
| { op: "addClipAtFirstFree"; mediaId: string; start: number }
- | { op: "addTextClip"; trackId: string | null; start: number; style: TextStyle | null }
+ | {
+ op: "addTextClip";
+ trackId: string | null;
+ start: number;
+ style: TextStyle | null;
+ /** Seconds on the timeline; the editorial default when absent. Lets a
+ * caption run land as one batch - a batch cannot trim ids it cannot
+ * know yet. */
+ duration?: number;
+ /** Vertical placement as a frame-height fraction; lower thirds. */
+ offsetY?: number;
+ }
| { op: "moveClips"; moves: ClipMove[] }
| { op: "trimClip"; clipId: string; edge: "start" | "end"; delta: number }
| { op: "splitClips"; clipIds: string[]; time: number }
diff --git a/engine/crates/relay-project/src/commands.rs b/engine/crates/relay-project/src/commands.rs
index 245d70f9..7e3b6fd7 100644
--- a/engine/crates/relay-project/src/commands.rs
+++ b/engine/crates/relay-project/src/commands.rs
@@ -120,7 +120,20 @@ pub enum Command {
Batch { commands: Vec<Command> },
AddClip { media_id: String, track_id: String, start: f64 },
AddClipAtFirstFree { media_id: String, start: f64 },
- AddTextClip { track_id: Option<String>, start: f64, style: Option<TextStyle> },
+ AddTextClip {
+ track_id: Option<String>,
+ start: f64,
+ style: Option<TextStyle>,
+ /// Seconds on the timeline; the editorial default when absent. Here
+ /// so a caption run can land as one batch instead of add-then-trim
+ /// per clip - a batch cannot trim a clip whose id it cannot know yet.
+ #[serde(default)]
+ duration: Option<f64>,
+ /// Vertical placement as a frame-height fraction, clamped like
+ /// SetClipTransform. Lower thirds are made of this.
+ #[serde(default)]
+ offset_y: Option<f64>,
+ },
MoveClips { moves: Vec<ClipMove> },
TrimClip { clip_id: String, edge: TrimEdge, delta: f64 },
SplitClips { clip_ids: Vec<String>, time: f64 },
@@ -455,13 +468,14 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
Ok(Outcome { created_id: Some(id) })
}
- Command::AddTextClip { track_id, start, style } => {
+ Command::AddTextClip { track_id, start, style, duration, offset_y } => {
let style = style.unwrap_or_default();
+ let duration = duration.unwrap_or(DEFAULT_TEXT_DURATION).max(MIN_CLIP_DURATION);
let timeline = project.active_mut();
let track_id = match track_id {
Some(id) if timeline.track(&id).is_some() => id,
Some(_) => return Err("That track no longer exists.".to_owned()),
- None => first_free_track(timeline, start, DEFAULT_TEXT_DURATION)
+ None => first_free_track(timeline, start, duration)
.ok_or("There are no tracks.")?,
};
let id = mint.next("c");
@@ -472,14 +486,14 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
name: first_line(&style.content),
kind: ClipKind::Text,
start: start.max(0.0),
- duration: DEFAULT_TEXT_DURATION,
+ duration,
source_start: 0.0,
volume: 1.0,
fade_in: 0.0,
fade_out: 0.0,
scale: 1.0,
offset_x: 0.0,
- offset_y: 0.0,
+ offset_y: offset_y.unwrap_or(0.0).clamp(-MAX_OFFSET, MAX_OFFSET),
rotation: 0.0,
opacity: 1.0,
speed: 1.0,
diff --git a/engine/crates/relay-project/src/lib.rs b/engine/crates/relay-project/src/lib.rs
index d6b35f7e..05d740e0 100644
--- a/engine/crates/relay-project/src/lib.rs
+++ b/engine/crates/relay-project/src/lib.rs
@@ -507,11 +507,28 @@ mod tests {
track_id: None,
start: 2.0,
style: Some(TextStyle { content: "Lower third\nsecond line".to_owned(), ..TextStyle::default() }),
+ duration: Some(2.5),
+ offset_y: Some(0.38),
})
.expect("adds")
.created_id
.expect("id");
- assert_eq!(editor.project().active().clip(&clip_id).expect("exists").name, "Lower third");
+ {
+ let clip = editor.project().active().clip(&clip_id).expect("exists");
+ assert_eq!(clip.name, "Lower third");
+ assert_eq!(clip.duration, 2.5, "a stated duration lands directly");
+ assert_eq!(clip.offset_y, 0.38, "and so does the placement");
+ }
+
+ // The pre-templates wire shape still parses: both fields default.
+ let bare: Command = serde_json::from_value(json!({
+ "op": "addTextClip", "trackId": null, "start": 1.0, "style": null
+ }))
+ .expect("old wire shape parses");
+ assert!(matches!(
+ bare,
+ Command::AddTextClip { duration: None, offset_y: None, .. }
+ ));
let document = editor.to_document(&settings());
let restored = Editor::from_document(&document).expect("loads");