The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
updates
Jareer485a6b1a841b
diff --git a/desktop/README.md b/desktop/README.mdindex e8af97e8..ec14f52c 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -37,7 +37,7 @@ src/Inspector.tsx properties of the selectionlib/engine.ts the ONLY file that calls invoke(). Typed IPC boundary.- project.ts the provisional edit model and its operations+ editor.ts type mirrors of the engine model, selectors, gesture echotransport.ts the playback clock (follows the engine's position events)effects.ts video effect & transition catalogue -> ffmpeg chains + live previewsfilters.ts audio filter catalogue -> ffmpeg chains@@ -55,12 +55,11 @@ src-tauri/- **The timeline is not DOM.** One canvas, one rAF loop. See decision 0002.- **No time arithmetic in TypeScript.** The engine works in exact rationalseconds; JS numbers are `f64` and drift. `lib/time.ts` formats, nothing more.-- **The UI does not own the edit — but it does today.** `lib/project.ts` holds- a provisional model because the engine has no project API yet. Every- operation there is a pure `(project, args) => project` function, which is the- shape an engine command will have, so the call sites survive the migration.- Do not let it grow an undo stack or a serialiser; those belong to the engine,- and building them twice is how the two copies drift apart.+- **The engine owns the edit.** Every mutation is an `editor_apply` command+ into `relay-project` (engine decision 0007); the UI renders the state that+ comes back and holds only a transient gesture echo while a drag is in+ flight. Undo, serialisation and the operations themselves live in Rust -+ do not reintroduce model logic in TypeScript.## Keyboarddiff --git a/desktop/docs/decisions/0006-multiple-timelines.md b/desktop/docs/decisions/0006-multiple-timelines.mdnew file mode 100644index 00000000..e07d5495--- /dev/null+++ b/desktop/docs/decisions/0006-multiple-timelines.md@@ -0,0 +1,28 @@+# 0006 - Multiple timelines, and the shelf that made them cheap++## Decision+A project holds several timelines (tabs above the timeline tray). In the+frozen UI model the active timeline's tracks and clips stay at the top of the+project - exactly where they always were - and inactive timelines park their+content in a `shelved` map. Switching swaps content in and out at one seam.++## Why the shelf+Every edit operation and every reader (the canvas draw loop included) already+worked on `project.tracks`/`project.clips`. The shelf made "which timeline am+I editing" a fact decided in exactly one place, and no other code had to+learn timelines exist. Thirty operations, zero changes.++## Its known ugliness, and the exit+Two homes for the same kind of data is a real smell - which is why the+engine model (`relay-project`, engine decision 0007) has **no shelf**: it+stores a plain list of timelines and an active id, and operations address the+active one. The shelf dies with `lib/project.ts` when the UI flips. The+*document* format never had a shelf either; both models read and write the+same `timelines` array.++## Rules that hold either way+- New timelines mint fresh track ids - reusing `T1..T4` across timelines+ would make duplicate-id repair orphan clips.+- Deleting is confirmed (no undo existed when this shipped), floors at one+ timeline, and switches to a neighbour first when the active one dies.+- Per-timeline playhead positions are window state, never saved.diff --git a/desktop/docs/decisions/0007-preview-approximation-layer.md b/desktop/docs/decisions/0007-preview-approximation-layer.mdnew file mode 100644index 00000000..19e29c56--- /dev/null+++ b/desktop/docs/decisions/0007-preview-approximation-layer.md@@ -0,0 +1,33 @@+# 0007 - The monitor is an approximation layer, and that is the plan++## Decision+The webview monitor draws every effect and transition live, through per-effect+preview mechanisms declared next to their FFmpeg chains in `lib/effects.ts`:+CSS filters where CSS is faithful, SVG filters for matrices and convolutions,+overlay layers (vignette, grain), a canvas redraw pass for geometry (pixelate,+mirror, fisheye), deterministic playhead-clocked jitter (shake), and a second+ghost video element for cross-fades. This layer is the **plan of record**, not+scaffolding: it stays until the engine can present frames, and it is allowed+to grow with the effect catalogue.++## What this supersedes+Decision 0004 called the monitor "scaffolding with a known demolition date."+That story is dead - deliberately. Users evaluate an editor by what they see+while editing, and "export only" effects tested as a retention killer. We+traded single-renderer purity for a live monitor, with eyes open.++## The drift risk, and its containment+This is a second implementation of effect *appearance* - exactly the shape+the architecture doctrine warns about. Containment:++- Both renderings read the **same parameters** from the same clip; there is+ no preview-only knob anywhere.+- The export chain is ground truth; the preview is documented as its+ approximation, never the reverse.+- Every effect's chain and preview live in **one catalogue entry**, so adding+ or changing an effect touches one place.++## What would change our mind+The engine presentation path (frame cache + reader pool + native surface).+When the engine can show its own frames at interactive rates, this layer+retires bottom-up: composite first, effects last.diff --git a/desktop/docs/decisions/0008-bundled-ffmpeg-and-releases.md b/desktop/docs/decisions/0008-bundled-ffmpeg-and-releases.mdnew file mode 100644index 00000000..976418b7--- /dev/null+++ b/desktop/docs/decisions/0008-bundled-ffmpeg-and-releases.md@@ -0,0 +1,28 @@+# 0008 - Releases bundle static FFmpeg, staged by CI++## Decision+Every packaged build ships its own `ffmpeg`/`ffprobe` pair in the app's+resources; `build.rs` refuses a release build without them staged, because a+packaged app without FFmpeg ships broken (no PATH to fall back on from+Finder). CI stages the pair before building: BtbN static GPL builds on+Windows, Martin Riedl static builds on macOS (arm64), both verified runnable+and - on macOS - verified present and executable inside the bundle after+packaging.++Tags matching `v*` additionally publish the installers to a GitHub release;+a hyphen in the tag marks a pre-release. The release body links+`THIRD_PARTY_NOTICES.md` for the FFmpeg licensing story (the builds are GPL;+we invoke, never link - see engine decisions 0002 and 0005).++## Why download static builds instead of our trimmed workflow's output+The `ffmpeg.yml` workflow builds a cut-down FFmpeg whose feature list is+matched to exactly what the app invokes, but it is Windows-only today and its+output must be staged by hand. Full static builds are ~100 MB heavier and+always sufficient; correctness beats size for the alpha. When the trimmed+build graduates (both platforms, automated staging), its enable-filter list+already tracks the effect catalogue - keep it that way.++## What would change our mind+Nothing about bundling. The source of the binaries flips to the trimmed+build when it covers both platforms; the guard in `build.rs` and the CI+verification step stay regardless.diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lockindex 2a49c633..f0336bf8 100644--- a/desktop/src-tauri/Cargo.lock+++ b/desktop/src-tauri/Cargo.lock@@ -3259,6 +3259,7 @@ dependencies = ["memmap2","relay-core","relay-media",+ "relay-project","relay-render","rusqlite","serde",@@ -3279,6 +3280,14 @@ dependencies = ["thiserror 2.0.20",]+[[package]]+name = "relay-project"+version = "0.1.0"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "relay-render"version = "0.1.0"diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex 01a89d18..04b98189 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -26,6 +26,7 @@ serde_json = "1"# depend on there being a desktop app.relay-core = { path = "../../engine/crates/relay-core" }relay-media = { path = "../../engine/crates/relay-media" }+relay-project = { path = "../../engine/crates/relay-project" }relay-render = { path = "../../engine/crates/relay-render", features = ["gpu"] }rusqlite = { version = "0.40.2", features = ["bundled"] }diff --git a/desktop/src-tauri/src/editor_api.rs b/desktop/src-tauri/src/editor_api.rsnew file mode 100644index 00000000..b66f2ee2--- /dev/null+++ b/desktop/src-tauri/src/editor_api.rs@@ -0,0 +1,187 @@+//! The engine-owned editing session, exposed to the UI.+//!+//! One session at a time, held in managed state: open a project and the+//! engine holds the edit; every mutation arrives as a `relay_project`+//! [`Command`], is applied with undo recorded, and the new state goes back+//! over the wire. The UI's provisional model (`lib/project.ts`) is frozen+//! and being replaced by calls into this module - see+//! `engine/docs/decisions/0007-engine-owns-the-project.md`.+//!+//! Saving reuses `projects::save`'s temp-file-and-rename, so the document on+//! disk is written by exactly one code path whichever side owns the model.++use std::sync::Mutex;++use relay_project::{Command, DocumentSettings, Editor};+use serde::Serialize;++use crate::projects;++/// The one editing session, or None before a project is opened.+pub struct EditorState(pub Mutex<Option<Session>>);++pub struct Session {+ /// The project folder, for saving.+ path: String,+ settings: DocumentSettings,+ editor: Editor,+}++/// What every mutating call returns: the authoritative state plus history+/// availability, so the UI's undo/redo affordances are never guessing.+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct EditorView {+ project: relay_project::Project,+ can_undo: bool,+ can_redo: bool,+ /// The settings as the session holds them - the document's own output+ /// size wins over the manifest's on open, exactly as the old loader+ /// preferred it.+ settings: SettingsView,+ /// The id a creating command minted, if any.+ #[serde(skip_serializing_if = "Option::is_none")]+ created_id: Option<String>,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SettingsView {+ name: String,+ width: u32,+ height: u32,+ rate_num: i64,+ rate_den: i64,+}++fn view(session: &Session, created_id: Option<String>) -> EditorView {+ EditorView {+ project: session.editor.project().clone(),+ can_undo: session.editor.can_undo(),+ can_redo: session.editor.can_redo(),+ settings: SettingsView {+ name: session.settings.name.clone(),+ width: session.settings.width,+ height: session.settings.height,+ rate_num: session.settings.rate_num,+ rate_den: session.settings.rate_den,+ },+ created_id,+ }+}++fn with_session<T>(+ state: &EditorState,+ operation: impl FnOnce(&mut Session) -> Result<T, String>,+) -> Result<T, String> {+ let mut guard = state.0.lock().map_err(|_| "editor state poisoned".to_owned())?;+ let session = guard.as_mut().ok_or("no project is open")?;+ operation(session)+}++/// Opens a project folder as the editing session and returns its state.+///+/// A folder whose document is missing or unreadable opens as an empty+/// project rather than failing - the same grace the TS loader extends -+/// but a *corrupt* document is an error, because silently replacing an+/// edit with emptiness is how projects get lost.+#[tauri::command]+pub fn editor_open(+ state: tauri::State<'_, EditorState>,+ path: String,+ name: String,+ width: u32,+ height: u32,+ rate_num: i64,+ rate_den: i64,+) -> Result<EditorView, String> {+ let mut settings = DocumentSettings { name, width, height, rate_num, rate_den };+ let editor = match projects::read_document(&path) {+ Ok(document) => {+ // The document's frame wins over the manifest: it is where an+ // edited output size was saved.+ if let Some(video) = document.get("video") {+ if let (Some(width), Some(height)) = (+ video.get("width").and_then(|value| value.as_u64()),+ video.get("height").and_then(|value| value.as_u64()),+ ) {+ if width > 0 && height > 0 {+ settings.width = width as u32;+ settings.height = height as u32;+ }+ }+ }+ Editor::from_document(&document)+ .ok_or_else(|| format!("{path} holds a document this build cannot read"))?+ }+ // No document yet - a project created moments ago.+ Err(_) => Editor::new(),+ };++ let mut guard = state.0.lock().map_err(|_| "editor state poisoned".to_owned())?;+ *guard = Some(Session { path, settings, editor });+ let session = guard.as_ref().expect("just set");+ Ok(view(session, None))+}++/// Applies one edit command and returns the new state.+#[tauri::command]+pub fn editor_apply(+ state: tauri::State<'_, EditorState>,+ command: Command,+) -> Result<EditorView, String> {+ with_session(&state, |session| {+ let outcome = session.editor.apply(command)?;+ Ok(view(session, outcome.created_id))+ })+}++#[tauri::command]+pub fn editor_undo(state: tauri::State<'_, EditorState>) -> Result<EditorView, String> {+ with_session(&state, |session| {+ session.editor.undo();+ Ok(view(session, None))+ })+}++#[tauri::command]+pub fn editor_redo(state: tauri::State<'_, EditorState>) -> Result<EditorView, String> {+ with_session(&state, |session| {+ session.editor.redo();+ Ok(view(session, None))+ })+}++/// The current state without changing anything.+#[tauri::command]+pub fn editor_state(state: tauri::State<'_, EditorState>) -> Result<EditorView, String> {+ with_session(&state, |session| Ok(view(session, None)))+}++/// Writes the session's document to its project folder. The output size can+/// have been edited in the preview footer, so it rides along here.+#[tauri::command]+pub fn editor_save(+ state: tauri::State<'_, EditorState>,+ width: Option<u32>,+ height: Option<u32>,+) -> Result<(), String> {+ with_session(&state, |session| {+ if let Some(width) = width {+ session.settings.width = width;+ }+ if let Some(height) = height {+ session.settings.height = height;+ }+ let document = session.editor.to_document(&session.settings);+ projects::save(&session.path, &document)+ })+}++/// Closes the session, dropping its undo history.+#[tauri::command]+pub fn editor_close(state: tauri::State<'_, EditorState>) {+ if let Ok(mut guard) = state.0.lock() {+ *guard = None;+ }+}diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex 72b81190..1553cc42 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -8,6 +8,7 @@// Public so the integration tests can drive a real export; see tests/.pub mod export;+mod editor_api;mod playback;mod projects;mod transcribe;@@ -547,6 +548,7 @@ pub fn run() {app.manage(transcribe::TranscribeState(std::sync::Arc::new(std::sync::Mutex::new(None),)));+ app.manage(editor_api::EditorState(std::sync::Mutex::new(None)));Ok(())}).plugin(tauri_plugin_opener::init())@@ -571,6 +573,13 @@ pub fn run() {forget_project,export_project,cancel_export,+ editor_api::editor_open,+ editor_api::editor_apply,+ editor_api::editor_undo,+ editor_api::editor_redo,+ editor_api::editor_state,+ editor_api::editor_save,+ editor_api::editor_close,transcribe::transcriber_status,transcribe::set_transcriber_binary,transcribe::download_transcriber_model,diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 05c9e0a8..c5790b9a 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -9,6 +9,7 @@ import { ContextMenu, type ContextTarget } from "./components/ContextMenu";import { ExportDialog, type ExportTitle } from "./components/ExportDialog";import { Icon } from "./components/Icon";import { ALL_MEDIA, MediaBin, type BinFilter } from "./components/MediaBin";+import type { MenuOption } from "./components/Menu";import { Preview, type PreviewSource, type TextOverlay } from "./components/Preview";import { Resizer } from "./components/Resizer";import { RightPanel, type RightTab } from "./components/RightPanel";@@ -18,79 +19,81 @@ import { TitleBar } from "./components/TitleBar";import { TimelinePanel, resolveDrop, type Tool } from "./components/TimelinePanel";import { createAssets, requestAssets, requestVideoPeaks } from "./lib/assets";import {- engineVersion,- loadProject,- probeMedia,- readMediaBytes,- saveProject,- transcribeClip,- type ExportClip,-} from "./lib/engine";-import { getTranscriberLanguage, getTranscriberModel } from "./lib/settings";-import {- addClip,- addMedia,- addTimeline,- addTrack,+ activeTimeline,clipsAt,- createProject,- detachAudio,+ commandsForEcho,detachedAudioOf,findClip,- firstFreeTrack,findMedia,findTrack,- addFont,- addTextClip,- mergeClips,- moveClip,- moveClips,+ precedingClip,projectDuration,- reattachAudio,- removeClips,- removeFont,- removeMediaEverywhere,- removeTimeline,- removeTrack,- renameTimeline,- renameTrack,- setClipSpeed,- setClipTransform,- setTrackFlag,snapTime,- splitClip,- switchTimeline,+ speedPatch,timelineClipCount,- toMediaItem,- updateClip,- trimClip,+ transformPatch,+ trimPatch,whyNotMerge,+ withEcho,type Clip,+ type Echo,+ type EditorCommand,+ type EditorProject,+ type EditorView,type MediaItem,- type Project,type TimelineMeta,-} from "./lib/project";-import { buildChain } from "./lib/filters";+} from "./lib/editor";import {- buildEffectChain,- findTransition,-} from "./lib/effects";-import { precedingClip } from "./lib/project";-import { familyForPath, registerFont } from "./lib/text";-import { fromDocument, toDocument } from "./lib/persist";+ editorApply,+ editorClose,+ editorOpen,+ editorRedo,+ editorSave,+ editorUndo,+ engineVersion,+ probeMedia,+ readMediaBytes,+ transcribeClip,+ type ExportClip,+} from "./lib/engine";+import { getTranscriberLanguage, getTranscriberModel } from "./lib/settings";+import { buildChain } from "./lib/filters";+import { buildEffectChain, findTransition } from "./lib/effects";+import { defaultTextStyle, familyForPath, registerFont } from "./lib/text";import { useTheme, type Theme } from "./lib/theme";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 = {+ media: [],+ fonts: [],+ timelines: [+ {+ id: "TL1",+ name: "Timeline 1",+ tracks: [1, 2, 3, 4].map((number) => ({+ id: `T${number}`,+ name: `Track ${number}`,+ visible: true,+ muted: false,+ })),+ clips: [],+ },+ ],+ activeTimelineId: "TL1",+};/*** The window: either the launch screen or an open editor.** The editor is a separate component rather than a branch inside one, so that- * every hook it owns - transport, asset cache - mounts when a project- * opens and unmounts when it closes. Closing a project therefore cannot leave- * a stale audio element or a half-finished waveform behind.+ * every hook it owns - transport, asset cache, the engine session - mounts+ * when a project opens and unmounts when it closes.*/export function App() {const [session, setSession] = useState<ProjectSession | null>(null);@@ -122,14 +125,12 @@ export function App() {/*** The editor shell.*- * Layout follows CapCut's shape: a thin custom title bar, a three-up top row- * (bin, preview, details) and a full-width timeline beneath, every divider- * draggable. Panels are docked and flush - in an editor, gutters are wasted- * timeline.- *- * State here is window state (what is selected, where the playhead is, how- * panels are sized) plus, for now, the edit itself. See lib/project.ts for why- * the edit lives here temporarily and what makes moving it to the engine cheap.+ * The engine owns the edit (see engine decision 0007). This component holds+ * *window* state - selection, playhead, panel sizes - plus the latest+ * `EditorView` the engine returned, and a transient gesture echo: during a+ * drag the change previews locally with the engine's own arithmetic, and one+ * command commits on release. Every mutation is a command; every render draws+ * the state that came back.*/function Editor({session,@@ -142,7 +143,8 @@ function Editor({onToggleTheme: () => void;onCloseProject: () => void;}) {- const [project, setProject] = useState<Project>(createProject);+ const [view, setView] = useState<EditorView | null>(null);+ const [echo, setEcho] = useState<Echo | null>(null);const [selectedClipIds, setSelectedClipIds] = useState<string[]>([]);const [selectedMediaId, setSelectedMediaId] = useState<string | null>(null);const [tool, setTool] = useState<Tool>("select");@@ -159,11 +161,11 @@ function Editor({const [exporting, setExporting] = useState(false);const [rightTab, setRightTab] = useState<RightTab>("details");const [saveState, setSaveState] = useState<"idle" | "saving" | "saved" | "failed">("idle");- /** Blocks autosave until the project on disk has been read in. */- const [loaded, setLoaded] = useState(false);+ /** Families whose font files failed to load - shown in the picker. */+ const [missingFonts, setMissingFonts] = useState<Set<string>>(new Set());/*** The output frame. Starts from the project settings but is editable from- * the preview footer, and the edited value is what the document keeps.+ * the preview footer; the engine persists whatever this holds on save.*/const [frame, setFrame] = useState({ width: session.width, height: session.height });@@ -180,6 +182,14 @@ function Editor({const zoomRef = useRef(secondsPerPixel);zoomRef.current = secondsPerPixel;+ const loaded = view !== null;+ // What the window draws: the engine's state with the gesture echo on top.+ const project = useMemo(+ () => withEcho(view?.project ?? EMPTY_PROJECT, echo),+ [view, echo],+ );+ const timeline = activeTimeline(project);+const duration = projectDuration(project);const transport = useTransport({ duration });const { playhead, playing } = transport;@@ -187,293 +197,167 @@ function Editor({// Read by event listeners that outlive the render that installed them.const latest = useRef({ project, secondsPerPixel, scrollLeft, trackScroll, snap, playhead, frame });latest.current = { project, secondsPerPixel, scrollLeft, trackScroll, snap, playhead, frame };+ const viewRef = useRef(view);+ viewRef.current = view;+ const echoRef = useRef(echo);+ echoRef.current = echo;- // The project's rate is authoritative, not the first clip's. Timecode that- // changes meaning when you import a 25fps file is worse than useless.+ // The project's rate is authoritative, not the first clip's.const frameRate = session.frameRate;- // Load the saved timeline before anything can autosave over it.- useEffect(() => {- let cancelled = false;- void loadProject(session.path)- .then((document) => {- const restored = fromDocument(document);- if (!cancelled && restored) setProject(restored);- // The document's frame wins over the manifest: it is where an edited- // output size was saved.- const video = (document as { video?: { width?: unknown; height?: unknown } }).video;- if (- !cancelled &&- typeof video?.width === "number" &&- typeof video?.height === "number" &&- video.width > 0 &&- video.height > 0- ) {- setFrame({ width: Math.round(video.width), height: Math.round(video.height) });- }- })- .catch(() => undefined)- .finally(() => {- if (!cancelled) setLoaded(true);- });- return () => {- cancelled = true;- };- }, [session.path]);-- // Bring back every font the project names, once, when it opens.- //- // Without this a reopened project renders its titles in the fallback face- // while still *claiming* the custom family, which looks like the styling was- // lost. A font whose file has moved is marked rather than dropped: the entry- // stays visible in the picker so it is obvious what is missing.- useEffect(() => {- if (!loaded || project.fonts.length === 0) return;-- let cancelled = false;- void Promise.all(- project.fonts.map(async (font) => ({- family: font.family,- ok: await registerFont(font, readMediaBytes),- })),- ).then((results) => {- const failed = results.filter((result) => !result.ok).map((result) => result.family);- if (cancelled || failed.length === 0) return;-- setProject((current) => ({- ...current,- fonts: current.fonts.map((font) =>- failed.includes(font.family) ? { ...font, missing: true } : font,- ),- }));+ // ── the command queue ────────────────────────────────────────────────────+ // Commands are serialised so responses can never land out of order and+ // overwrite newer state with older. Errors surface as the toast - they are+ // user-meaningful sentences from the engine ("Merged clips must touch...").+ const queue = useRef<Promise<unknown>>(Promise.resolve());+ const dispatch = useCallback((command: EditorCommand): Promise<string | undefined> => {+ const run = queue.current.then(async () => {+ const next = await editorApply(command);+ viewRef.current = next;+ setView(next);+ return next.createdId;});+ queue.current = run.catch(() => undefined);+ return run.catch((cause: unknown) => {+ setToast({ id: Date.now(), message: String(cause), failed: true });+ return undefined;+ });+ }, []);- return () => {- cancelled = true;- };- // Deliberately keyed on `loaded` alone. Depending on `project.fonts` would- // re-run this on the very state update it performs.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [loaded]);-- /**- * Puts a title on the timeline at the playhead.- *- * It lands on the first track with room, the same rule dropped media- * follows, and is selected immediately with the Text tab open - the words- * are the first thing anyone wants to change, so putting the panel in front- * of them saves a click every single time.- */- const addText = useCallback(() => {- setProject((current) => {- const at = latest.current.playhead;- const track = firstFreeTrack(current, at, 4);- if (!track) return current;+ const undoAction = useCallback(() => {+ queue.current = queue.current+ .then(async () => {+ const next = await editorUndo();+ viewRef.current = next;+ setView(next);+ setEcho(null);+ })+ .catch(() => undefined);+ }, []);- const { project: next, clipId } = addTextClip(current, { trackId: track.id, start: at });- if (clipId) {- setSelectedClipIds([clipId]);- setSelectedMediaId(null);- setRightTab("text");- }- return next;- });+ const redoAction = useCallback(() => {+ queue.current = queue.current+ .then(async () => {+ const next = await editorRedo();+ viewRef.current = next;+ setView(next);+ setEcho(null);+ })+ .catch(() => undefined);}, []);- // ── effects and transitions ──────────────────────────────────────────────+ // ── the gesture echo ─────────────────────────────────────────────────────- /**- * Applies one effect from the bin's Effects page to the selected clip.- *- * The card is clickable whatever is selected, so the misses have to explain- * themselves: no selection, or a selection that has no picture, each get a- * toast saying what to do instead of nothing happening.- */- const applyEffect = useCallback((effectId: string) => {- const current = latest.current.project;- const selected = selectedClipIds.length === 1 ? findClip(current, selectedClipIds[0]) : null;- if (!selected || (selected.kind !== "video" && selected.kind !== "image")) {- setToast({- id: Date.now(),- message: "Select a video or image clip on the timeline first",- failed: true,- });- return;- }- setProject((project) =>- updateClip(project, selected.id, {- videoEffects: [...selected.videoEffects, { id: effectId, params: {} }],- }),- );- setRightTab("effects");- }, [selectedClipIds]);+ /** Live: merges a patch into the echo for one clip. */+ const liveClip = useCallback((clipId: string, patch: Partial<Clip>) => {+ setEcho((current) => ({+ ...(current ?? {}),+ [clipId]: { ...(current?.[clipId] ?? {}), ...patch },+ }));+ }, []);/**- * Puts a transition on the selected clip's cut.- *- * A transition needs a cut: a clip ending exactly where the selected one- * starts. Without one there is nothing to dissolve across, and saying so- * beats silently attaching a transition that renders as nothing.+ * Commit: everything echoed becomes engine commands - one per gesture is+ * the point, so undo undoes the drag rather than a pixel of it. Multi-clip+ * moves collapse into a single MoveClips. The echo clears only after the+ * engine's state arrives, so nothing flashes back mid-flight.*/- const applyTransition = useCallback(- (transitionId: string) => {- const definition = findTransition(transitionId);- if (!definition?.implemented) return;-- const current = latest.current.project;- const selected = selectedClipIds.length === 1 ? findClip(current, selectedClipIds[0]) : null;- if (!selected || (selected.kind !== "video" && selected.kind !== "image")) {- setToast({- id: Date.now(),- message: "Select the incoming clip - the one after the cut - first",- failed: true,- });- return;+ const commitEcho = useCallback(() => {+ const pending = echoRef.current;+ const engineProject = viewRef.current?.project;+ if (!pending || !engineProject) return;++ const active = activeTimeline(engineProject);+ const commands: EditorCommand[] = [];+ const moves: { clipId: string; start: number; trackId: string }[] = [];++ for (const [clipId, patch] of Object.entries(pending)) {+ const base = active.clips.find((clip) => clip.id === clipId);+ if (!base) continue;+ for (const command of commandsForEcho(base, patch)) {+ if (command.op === "moveClips") moves.push(...command.moves);+ else commands.push(command);}- if (!precedingClip(current, selected.id)) {- setToast({- id: Date.now(),- message: "No clip ends where this one starts - transitions need a cut",- failed: true,- });- return;- }- setProject((project) =>- updateClip(project, selected.id, {- transitionIn: { id: transitionId, duration: definition.defaultDuration },- }),- );- setRightTab("effects");- setToast({- id: Date.now(),- message: `${definition.label} added to the cut`,- failed: false,- });- },- [selectedClipIds],- );-- // ── timelines ────────────────────────────────────────────────────────────- // The timeline awaiting delete confirmation, if any. Deleting throws away- // every clip on it and there is no undo, hence the prompt.- const [timelineToDelete, setTimelineToDelete] = useState<TimelineMeta | null>(null);- // Where the playhead was parked on each timeline, so switching back lands- // where you left off. Window state, deliberately not saved in the document.- const playheadByTimeline = useRef(new Map<string, number>());-- const selectTimeline = useCallback(- (timelineId: string) => {- const current = latest.current.project;- if (timelineId === current.activeTimelineId) return;- const next = switchTimeline(current, timelineId);- if (next === current) return;-- playheadByTimeline.current.set(current.activeTimelineId, latest.current.playhead);- setProject(next);- // The selection names clips on the timeline being left; keeping it- // would aim every clip operation at things no longer on screen.- setSelectedClipIds([]);- transport.pause();- transport.seek(playheadByTimeline.current.get(timelineId) ?? 0);- },- [transport],- );-- const createTimeline = useCallback(() => {- const current = latest.current.project;- playheadByTimeline.current.set(current.activeTimelineId, latest.current.playhead);- setProject(addTimeline(current).project);- setSelectedClipIds([]);- transport.pause();- transport.seek(0);- }, [transport]);-- /** Runs after the ConfirmDialog's Delete button; never called directly. */- const deleteTimelineNow = useCallback(- (timelineId: string) => {- const current = latest.current.project;- const wasActive = timelineId === current.activeTimelineId;- const next = removeTimeline(current, timelineId);- if (next === current) return;+ }+ if (moves.length > 0) commands.push({ op: "moveClips", moves });- playheadByTimeline.current.delete(timelineId);- setProject(next);- if (wasActive) {- setSelectedClipIds([]);- transport.pause();- transport.seek(playheadByTimeline.current.get(next.activeTimelineId) ?? 0);- }- },- [transport],- );+ if (commands.length === 0) {+ setEcho(null);+ return;+ }+ void (async () => {+ for (const command of commands) await dispatch(command);+ setEcho(null);+ })();+ }, [dispatch]);- /** Adds a font file to the project and makes it available immediately. */- const pickFont = useCallback(async () => {- try {- const picked = await openDialog({- multiple: false,- title: "Add a font",- filters: [{ name: "Fonts", extensions: ["ttf", "otf", "woff", "woff2", "ttc"] }],+ // ── the session ──────────────────────────────────────────────────────────+ useEffect(() => {+ let cancelled = false;+ editorOpen({+ path: session.path,+ name: session.name,+ width: session.width,+ height: session.height,+ rateNum: session.rateNum,+ rateDen: session.rateDen,+ })+ .then((opened) => {+ if (cancelled) return;+ viewRef.current = opened;+ setView(opened);+ setFrame({ width: opened.settings.width, height: opened.settings.height });+ })+ .catch((cause: unknown) => {+ if (!cancelled) setError(String(cause));});- if (typeof picked !== "string") return;-- const current = latest.current.project;- if (current.fonts.some((font) => font.path === picked)) return;-- const font = {- family: familyForPath(- picked,- current.fonts.map((existing) => existing.family),- ),- path: picked,- };-- // Registered before it is stored, so a file the webview cannot parse is- // reported now rather than becoming a broken entry in the picker.- if (!(await registerFont(font, readMediaBytes))) {- setError(`Could not read ${picked.split(/[\/]/).pop() ?? picked} as a font.`);- return;- }+ return () => {+ cancelled = true;+ void editorClose().catch(() => undefined);+ };+ }, [session]);- setProject((project) => addFont(project, font));- } catch (cause) {- setError(String(cause));- }- }, []);+ // A selection can name clips an undo or a command just removed.+ useEffect(() => {+ setSelectedClipIds((ids) => {+ const kept = ids.filter((id) => timeline.clips.some((clip) => clip.id === id));+ return kept.length === ids.length ? ids : kept;+ });+ setSelectedMediaId((id) =>+ id && project.media.some((item) => item.id === id) ? id : null,+ );+ // Keyed on the engine state, not the echo - the echo never removes clips.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [view]);- const save = useCallback(async () => {- setSaveState("saving");- try {- await saveProject(- session.path,- toDocument(- { ...session, width: latest.current.frame.width, height: latest.current.frame.height },- latest.current.project,- ),- );- setSaveState("saved");- return true;- } catch (cause) {- setSaveState("failed");- setError(String(cause));- return false;- }- }, [session]);+ // Autosave, debounced. The engine writes the document; the UI only says+ // when, and carries the output frame the preview footer can edit.+ useEffect(() => {+ if (!loaded) return;+ const timer = window.setTimeout(() => {+ setSaveState("saving");+ editorSave(latest.current.frame)+ .then(() => setSaveState("saved"))+ .catch(() => setSaveState("failed"));+ }, 1500);+ return () => clearTimeout(timer);+ }, [view, frame, loaded]);- // A deliberate save deserves an acknowledgement; the autosave stays silent- // because a toast every 1.5 seconds of editing would be noise, not news.const [toast, setToast] = useState<{ id: number; message: string; failed: boolean } | null>(null,);const saveAndNotify = useCallback(() => {- void save().then((saved) =>- setToast({- id: Date.now(),- message: saved ? "Project saved" : "Save failed",- failed: !saved,- }),- );- }, [save]);+ setSaveState("saving");+ editorSave(latest.current.frame)+ .then(() => {+ setSaveState("saved");+ setToast({ id: Date.now(), message: "Project saved", failed: false });+ })+ .catch((cause: unknown) => {+ setSaveState("failed");+ setToast({ id: Date.now(), message: `Save failed: ${cause}`, failed: true });+ });+ }, []);useEffect(() => {if (!toast) return;@@ -481,150 +365,38 @@ function Editor({return () => window.clearTimeout(timer);}, [toast]);- const [settingsOpen, setSettingsOpen] = useState(false);- const [transcribing, setTranscribing] = useState(false);-- /**- * Transcribes one clip's audio and lays the result out as text clips on a- * "Captions" track (created on first use, reused after).- *- * The clip's identity is captured when the menu item is built, so the- * timestamps map is computed against exactly the clip that was clicked -- * even if the selection has moved on by the time whisper finishes. Segment- * times come back relative to the source window; dividing by speed and- * adding the clip's start is the same affine map the preview and exporter- * use, run in reverse.- */- const autoCaption = useCallback(- async (clip: Clip, media: MediaItem) => {- setTranscribing(true);- setToast({ id: Date.now(), message: "Transcribing...", failed: false });- try {- const segments = await transcribeClip({- path: media.path,- sourceStart: clip.sourceStart,- window: clip.duration * clip.speed,- language: getTranscriberLanguage(),- modelId: getTranscriberModel(),- });-- if (segments.length === 0) {- setToast({ id: Date.now(), message: "No speech found", failed: false });- return;- }-- setProject((current) => {- let next = current;- let trackId = next.tracks.find((track) => track.name === "Captions")?.id ?? "";- if (!trackId) {- const grown = addTrack(next);- next = renameTrack(grown.project, grown.trackId, "Captions");- trackId = grown.trackId;- }+ // Bring back every font the project names, once, when it opens. A font+ // whose file has moved is marked rather than dropped.+ useEffect(() => {+ if (!loaded || !view || view.project.fonts.length === 0) return;+ let cancelled = false;+ void Promise.all(+ view.project.fonts.map(async (font) => ({+ family: font.family,+ ok: await registerFont(font, readMediaBytes),+ })),+ ).then((results) => {+ if (cancelled) return;+ const failed = results.filter((result) => !result.ok).map((result) => result.family);+ if (failed.length > 0) setMissingFonts(new Set(failed));+ });+ return () => {+ cancelled = true;+ };+ // Deliberately keyed on `loaded` alone: fonts are registered once per open.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [loaded]);- for (const segment of segments) {- const start = clip.start + segment.start / clip.speed;- const duration = Math.max(0.4, (segment.end - segment.start) / clip.speed);- const made = addTextClip(next, {- trackId,- start,- // Caption-sized and lower-third, not title-sized and centred.- style: { content: segment.text, fontSize: 0.045 },- });- next = made.clipId- ? updateClip(made.project, made.clipId, { duration, offsetY: 0.38 })- : made.project;- }- return next;- });- setToast({- id: Date.now(),- message: `Added ${segments.length} caption${segments.length === 1 ? "" : "s"}`,- failed: false,- });- } catch (cause) {- setToast({ id: Date.now(), message: String(cause), failed: true });- } finally {- setTranscribing(false);- }- },- [],+ const fontsForUi = useMemo(+ () =>+ project.fonts.map((font) =>+ missingFonts.has(font.family) ? { ...font, missing: true } : font,+ ),+ [project.fonts, missingFonts],);- /**- * The audio/video tools dropdown in the timeline tray.- *- * Shown only while a clip that can carry sound is selected - a title has no- * audio to detach or transcribe, and offering the menu anyway would be a- * drawer of permanently grey items. Within an eligible selection, items are- * still disabled rather than hidden, so what the tool *could* do stays- * visible.- */- const clipTools = useMemo(() => {- const clip = selectedClipIds.length === 1 ? findClip(project, selectedClipIds[0]) : null;- const media = clip ? findMedia(project, clip.mediaId) : null;-- // No sound-capable clip, no menu: the panel hides the whole dropdown.- if (!clip || (clip.kind !== "video" && clip.kind !== "audio")) return [];-- const hasSound = Boolean(- clip && (clip.kind === "video" || clip.kind === "audio") && media?.hasAudio,- );- const canDetach = Boolean(- clip &&- clip.kind === "video" &&- !clip.muted &&- media?.hasAudio &&- detachedAudioOf(project, clip.id).length === 0,- );- const canReattach = Boolean(- clip &&- ((clip.kind === "video" && detachedAudioOf(project, clip.id).length > 0) ||- (clip.kind === "audio" && clip.detachedFrom && findClip(project, clip.detachedFrom))),- );-- return [- [- {- label: transcribing ? "Transcribing..." : "Auto captions",- icon: "type" as const,- disabled: !hasSound || transcribing,- onSelect: () => {- if (clip && media) void autoCaption(clip, media);- },- },- ],- [- {- label: "Detach audio",- icon: "waveform" as const,- disabled: !canDetach,- onSelect: () => {- if (clip) setProject((current) => detachAudio(current, clip.id));- },- },- {- label: "Reattach audio",- icon: "merge" as const,- disabled: !canReattach,- onSelect: () => {- if (clip) {- setProject((current) => reattachAudio(current, clip.id));- setSelectedClipIds([]);- }- },- },- ],- ];- }, [project, selectedClipIds, transcribing, autoCaption]);-- // Autosave, debounced. The edit is the thing people lose; making them- // remember a keystroke to keep it is a design decision nobody wants.- useEffect(() => {- if (!loaded) return;- const timer = window.setTimeout(() => void save(), 1500);- return () => clearTimeout(timer);- }, [project, frame, loaded, save]);+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [transcribing, setTranscribing] = useState(false);useEffect(() => {engineVersion()@@ -636,34 +408,90 @@ function Editor({// from inside its draw loop, so artwork arriving needs no re-render.const assets = useRef(createAssets());+ // ── clip edits (echo + commit) ───────────────────────────────────────────++ /** Live patch from a panel control; committed by its onCommit. */+ const changeClip = useCallback(+ (patch: Partial<Clip>) => {+ const clipId = selectedClipIds.length === 1 ? selectedClipIds[0] : null;+ if (!clipId) return;+ // Transform-family fields get the engine's clamps applied to the echo,+ // so what previews is what will commit.+ const { scale, offsetX, offsetY, rotation, ...rest } = patch;+ const clamped =+ scale !== undefined || offsetX !== undefined || offsetY !== undefined || rotation !== undefined+ ? transformPatch({ scale, offsetX, offsetY, rotation })+ : {};+ liveClip(clipId, { ...rest, ...clamped });+ },+ [selectedClipIds, liveClip],+ );++ const changeSpeed = useCallback(+ (speed: number) => {+ const clipId = selectedClipIds.length === 1 ? selectedClipIds[0] : null;+ if (!clipId) return;+ const clip = findClip(latest.current.project, clipId);+ if (clip) liveClip(clipId, speedPatch(clip, speed));+ },+ [selectedClipIds, liveClip],+ );+// ── media import ─────────────────────────────────────────────────────────- const importPaths = useCallback(async (paths: string[]) => {- setBusy(true);- setError(null);- for (const path of paths) {- try {- const item = toMediaItem(await probeMedia(path));- setProject((current) => addMedia(current, item));- setSelectedMediaId(item.id);- // Fire and forget: the clip draws flat until the artwork lands.- requestAssets(assets.current, item, session.path);- } catch (cause) {- // The engine's errors already name the file and quote FFmpeg.- setError(String(cause));+ const importPaths = useCallback(+ async (paths: string[]) => {+ setBusy(true);+ setError(null);+ for (const path of paths) {+ try {+ const summary = await probeMedia(path);+ const name = summary.path.split(/[\\/]/).pop() ?? summary.path;+ const mediaId = await dispatch({+ op: "addMedia",+ item: {+ path: summary.path,+ name,+ duration: summary.duration,+ kind: summary.kind,+ width: summary.video?.width ?? null,+ height: summary.video?.height ?? null,+ frameRate: summary.video?.frameRate ?? null,+ frameRateFraction: summary.video?.frameRateFraction ?? null,+ videoCodec: summary.video?.codec ?? null,+ audioCodec: summary.audio?.codec ?? null,+ hasAudio: summary.audio !== null,+ },+ });+ if (mediaId) {+ setSelectedMediaId(mediaId);+ // Fire and forget: the clip draws flat until the artwork lands.+ requestAssets(+ assets.current,+ {+ id: mediaId,+ path: summary.path,+ kind: summary.kind,+ duration: summary.duration,+ hasAudio: summary.audio !== null,+ },+ session.path,+ );+ }+ } catch (cause) {+ setError(String(cause));+ }}- }- setBusy(false);- }, [session.path]);+ setBusy(false);+ },+ [dispatch, session.path],+ );// Artwork for everything already in the project: a reopened project should- // get its thumbnails and waveforms back without re-importing anything. The- // disk cache makes the second launch cheap; requestAssets dedupes the rest.+ // get its thumbnails and waveforms back without re-importing anything.useEffect(() => {if (!loaded) return;- // Audio clips cut from a video (detached, or split out) draw a waveform,- // so those videos - and only those - need peaks decoded.const wantsPeaks = new Set(- project.clips.filter((clip) => clip.kind === "audio").map((clip) => clip.mediaId),+ timeline.clips.filter((clip) => clip.kind === "audio").map((clip) => clip.mediaId),);for (const item of project.media) {requestAssets(assets.current, item, session.path);@@ -671,13 +499,11 @@ function Editor({requestVideoPeaks(assets.current, item, session.path);}}- }, [loaded, project.media, project.clips, session.path]);+ }, [loaded, project.media, timeline.clips, session.path]);- // Files dropped from the OS. Tauri intercepts these before the webview sees- // them, which is why this is an event subscription and not an HTML5 handler.+ // Files dropped from the OS.useEffect(() => {if (!isTauri()) return;-let stop: (() => void) | undefined;void getCurrentWebview().onDragDropEvent((event) => {@@ -690,18 +516,13 @@ function Editor({.then((unlisten) => {stop = unlisten;});-return () => stop?.();}, [importPaths]);// ── audio playback ───────────────────────────────────────────────────────- // The engine mixes everything audible - see src-tauri/src/playback.rs. The- // UI's whole job is to describe the audible clip set whenever it changes:- // audio clips, plus video clips that still own their sound. The engine- // decodes what is new (cached across sessions) and remixes the rest.const audibleClips = useMemo(() =>- project.clips.flatMap((clip) => {+ timeline.clips.flatMap((clip) => {if (clip.kind !== "audio" && clip.kind !== "video") return [];if (clip.kind === "video" && clip.muted) return [];const track = findTrack(project, clip.trackId);@@ -723,13 +544,11 @@ function Editor({},];}),- [project],+ [project, timeline],);useEffect(() => {if (!isTauri()) return;- // Debounced so a slider drag settles before its chain re-decodes; gain- // and position changes are cheap remixes either way.const timer = window.setTimeout(() => {void invoke("audio_set_clips", { project: session.path, clips: audibleClips }).catch((cause: unknown) => console.error("WolfCut: could not update the mix", cause),@@ -738,93 +557,289 @@ function Editor({return () => window.clearTimeout(timer);}, [audibleClips, session.path]);- /**- * Every title live at the playhead, bottom track first.- *- * All of them, not just the top one: titles stack, and a lower third plus a- * name card is a normal thing to want on screen at once. Order follows track- * order so the compositing matches what the timeline shows.- */- const textOverlays = useMemo<TextOverlay[]>(() => {- const depth = (trackId: string) => project.tracks.findIndex((track) => track.id === trackId);+ // ── text, effects, transitions ───────────────────────────────────────────++ const addText = useCallback(() => {+ void dispatch({+ op: "addTextClip",+ trackId: null,+ start: latest.current.playhead,+ style: null,+ }).then((clipId) => {+ if (clipId) {+ setSelectedClipIds([clipId]);+ setSelectedMediaId(null);+ setRightTab("text");+ }+ });+ }, [dispatch]);++ const pickFont = useCallback(async () => {+ try {+ const picked = await openDialog({+ multiple: false,+ title: "Add a font",+ filters: [{ name: "Fonts", extensions: ["ttf", "otf", "woff", "woff2", "ttc"] }],+ });+ if (typeof picked !== "string") return;+ const current = latest.current.project;+ if (current.fonts.some((font) => font.path === picked)) return;++ const font = {+ family: familyForPath(+ picked,+ current.fonts.map((existing) => existing.family),+ ),+ path: picked,+ };+ // Registered before it is stored, so a file the webview cannot parse is+ // reported now rather than becoming a broken entry in the picker.+ if (!(await registerFont(font, readMediaBytes))) {+ setError(`Could not read ${picked.split(/[\/]/).pop() ?? picked} as a font.`);+ return;+ }+ void dispatch({ op: "addFont", family: font.family, path: font.path });+ } catch (cause) {+ setError(String(cause));+ }+ }, [dispatch]);++ const applyEffect = useCallback(+ (effectId: string) => {+ const current = latest.current.project;+ const selected = selectedClipIds.length === 1 ? findClip(current, selectedClipIds[0]) : null;+ if (!selected || (selected.kind !== "video" && selected.kind !== "image")) {+ setToast({+ id: Date.now(),+ message: "Select a video or image clip on the timeline first",+ failed: true,+ });+ return;+ }+ void dispatch({+ op: "updateClip",+ clipId: selected.id,+ patch: { videoEffects: [...selected.videoEffects, { id: effectId, params: {} }] },+ });+ setRightTab("effects");+ },+ [selectedClipIds, dispatch],+ );++ const applyTransition = useCallback(+ (transitionId: string) => {+ const definition = findTransition(transitionId);+ if (!definition?.implemented) return;+ const current = latest.current.project;+ const selected = selectedClipIds.length === 1 ? findClip(current, selectedClipIds[0]) : null;+ if (!selected || (selected.kind !== "video" && selected.kind !== "image")) {+ setToast({+ id: Date.now(),+ message: "Select the incoming clip - the one after the cut - first",+ failed: true,+ });+ return;+ }+ if (!precedingClip(current, selected.id)) {+ setToast({+ id: Date.now(),+ message: "No clip ends where this one starts - transitions need a cut",+ failed: true,+ });+ return;+ }+ void dispatch({+ op: "updateClip",+ clipId: selected.id,+ patch: { transitionIn: { id: transitionId, duration: definition.defaultDuration } },+ });+ setRightTab("effects");+ setToast({ id: Date.now(), message: `${definition.label} added to the cut`, failed: false });+ },+ [selectedClipIds, dispatch],+ );++ /**+ * Transcribes one clip's audio and lays the result out as text clips on a+ * "Captions" track (created on first use, reused after).+ */+ const autoCaption = useCallback(+ async (clip: Clip, media: MediaItem) => {+ setTranscribing(true);+ setToast({ id: Date.now(), message: "Transcribing...", failed: false });+ try {+ const segments = await transcribeClip({+ path: media.path,+ sourceStart: clip.sourceStart,+ window: clip.duration * clip.speed,+ language: getTranscriberLanguage(),+ modelId: getTranscriberModel(),+ });+ if (segments.length === 0) {+ setToast({ id: Date.now(), message: "No speech found", failed: false });+ return;+ }++ let trackId = activeTimeline(latest.current.project).tracks.find(+ (track) => track.name === "Captions",+ )?.id;+ if (!trackId) {+ trackId = await dispatch({ op: "addTrack" });+ if (!trackId) return;+ 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({+ op: "addTextClip",+ trackId,+ start,+ // 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"}`,+ failed: false,+ });+ } catch (cause) {+ setToast({ id: Date.now(), message: String(cause), failed: true });+ } finally {+ setTranscribing(false);+ }+ },+ [dispatch],+ );- return clipsAt(project, playhead)- .filter((clip) => clip.kind === "text" && clip.text !== undefined)- .filter((clip) => findTrack(project, clip.trackId)?.visible !== false)- .sort((a, b) => depth(a.trackId) - depth(b.trackId))- .map((clip) => ({- clipId: clip.id,- style: clip.text!,- offsetX: clip.offsetX,- offsetY: clip.offsetY,- }));- }, [project, playhead]);+ /** The audio/video tools dropdown. Hidden entirely for soundless clips. */+ const clipTools = useMemo<MenuOption[][]>(() => {+ const clip = selectedClipIds.length === 1 ? findClip(project, selectedClipIds[0]) : null;+ const media = clip ? findMedia(project, clip.mediaId) : null;+ if (!clip || (clip.kind !== "video" && clip.kind !== "audio")) return [];- // The top-most video clip under the playhead is what the monitor shows.- const previewSource = useMemo<PreviewSource | null>(() => {- // Stills are picture too, so they compete for the monitor with footage.- // Titles do not: they are drawn *over* whatever is showing, so they are- // handled as overlays below rather than as a source.- const active = clipsAt(project, playhead).filter(- (clip) => clip.kind !== "audio" && clip.kind !== "text",+ const hasSound = Boolean(media?.hasAudio);+ const canDetach = Boolean(+ clip.kind === "video" &&+ !clip.muted &&+ media?.hasAudio &&+ detachedAudioOf(project, clip.id).length === 0,);- if (active.length === 0) return null;-- const depth = (trackId: string) => project.tracks.findIndex((track) => track.id === trackId);- const top = active.reduce((best, clip) =>- depth(clip.trackId) > depth(best.trackId) ? clip : best,+ const canReattach = Boolean(+ (clip.kind === "video" && detachedAudioOf(project, clip.id).length > 0) ||+ (clip.kind === "audio" && clip.detachedFrom && findClip(project, clip.detachedFrom)),);- const media = findMedia(project, top.mediaId);- if (!media) return null;+ return [+ [+ {+ label: transcribing ? "Transcribing..." : "Auto captions",+ icon: "type" as const,+ disabled: !hasSound || transcribing,+ onSelect: () => {+ if (clip && media) void autoCaption(clip, media);+ },+ },+ ],+ [+ {+ label: "Detach audio",+ icon: "waveform" as const,+ disabled: !canDetach,+ onSelect: () => void dispatch({ op: "detachAudio", clipId: clip.id }),+ },+ {+ label: "Reattach audio",+ icon: "merge" as const,+ disabled: !canReattach,+ onSelect: () => {+ void dispatch({ op: "reattachAudio", clipId: clip.id });+ setSelectedClipIds([]);+ },+ },+ ],+ ];+ }, [project, selectedClipIds, transcribing, autoCaption, dispatch]);- return {- clipId: top.id,- path: media.path,- // A timeline second covers `speed` source seconds - the same map the- // exporter's frame plan applies.- time: top.sourceStart + (playhead - top.start) * top.speed,- speed: top.speed,- isStill: top.kind === "image",- };- }, [project, playhead]);+ // ── timelines ────────────────────────────────────────────────────────────+ const [timelineToDelete, setTimelineToDelete] = useState<TimelineMeta | null>(null);+ const playheadByTimeline = useRef(new Map<string, number>());- // What the monitor's transform gizmo works on: the displayed clip's picture- // transform, and the source's pixel size so the fitted rect can be computed.- const previewClip = previewSource ? findClip(project, previewSource.clipId) : null;- const previewMedia = previewClip ? findMedia(project, previewClip.mediaId) : null;+ const selectTimeline = useCallback(+ (timelineId: string) => {+ const current = latest.current.project;+ if (timelineId === current.activeTimelineId) return;+ playheadByTimeline.current.set(current.activeTimelineId, latest.current.playhead);+ void dispatch({ op: "selectTimeline", timelineId }).then(() => {+ setSelectedClipIds([]);+ transport.pause();+ transport.seek(playheadByTimeline.current.get(timelineId) ?? 0);+ });+ },+ [dispatch, transport],+ );- // ── edit operations ──────────────────────────────────────────────────────- const placeMedia = useCallback((mediaId: string, trackId: string, start: number) => {- setProject((current) => {- const { project: next, clipId } = addClip(current, { mediaId, trackId, start });- if (clipId) setSelectedClipIds([clipId]);- return next;+ const createTimeline = useCallback(() => {+ playheadByTimeline.current.set(+ latest.current.project.activeTimelineId,+ latest.current.playhead,+ );+ void dispatch({ op: "addTimeline" }).then(() => {+ setSelectedClipIds([]);+ transport.pause();+ transport.seek(0);});- }, []);+ }, [dispatch, transport]);++ const deleteTimelineNow = useCallback(+ (timelineId: string) => {+ const wasActive = timelineId === latest.current.project.activeTimelineId;+ playheadByTimeline.current.delete(timelineId);+ void dispatch({ op: "removeTimeline", timelineId }).then(() => {+ if (wasActive) {+ setSelectedClipIds([]);+ transport.pause();+ const nextActive = viewRef.current?.project.activeTimelineId;+ transport.seek((nextActive && playheadByTimeline.current.get(nextActive)) || 0);+ }+ });+ },+ [dispatch, transport],+ );++ // ── edit operations ──────────────────────────────────────────────────────+ const placeMedia = useCallback(+ (mediaId: string, trackId: string, start: number) => {+ void dispatch({ op: "addClip", mediaId, trackId, start }).then((clipId) => {+ if (clipId) setSelectedClipIds([clipId]);+ });+ },+ [dispatch],+ );const addToTimeline = useCallback((mediaId: string) => {- const media = findMedia(project, mediaId);- if (!media) return;- // Stack onto the lowest lane that is free here, rather than piling- // everything onto track 1 on top of itself.- const track = firstFreeTrack(project, playhead, media.duration ?? 5);- if (track) placeMedia(media.id, track.id, playhead);+ void dispatch({+ op: "addClipAtFirstFree",+ mediaId,+ start: latest.current.playhead,+ }).then((clipId) => {+ if (clipId) setSelectedClipIds([clipId]);+ });},- [placeMedia, playhead, project],+ [dispatch],);- /**- * Drags a bin item onto the timeline.- *- * Window-level pointer listeners rather than pointer capture on the source- * row: capture would deliver every move to the bin item, and the drop has to- * be resolved against the timeline, which is a different element entirely.- *- * `latest` is read inside the listeners because they are installed once per- * drag and would otherwise close over stale zoom and scroll values.- */const beginMediaDrag = useCallback((item: MediaItem, clientX: number, clientY: number) => {setMediaDrag({ item, x: clientX, y: clientY });@@ -834,7 +849,6 @@ function Editor({current ? { ...current, x: event.clientX, y: event.clientY } : null,);};-const onUp = (event: PointerEvent) => {window.removeEventListener("pointermove", onMove);window.removeEventListener("pointerup", onUp);@@ -842,13 +856,11 @@ function Editor({const state = latest.current;const drop = resolveDrop(event.clientX, event.clientY, {- tracks: state.project.tracks,+ tracks: activeTimeline(state.project).tracks,secondsPerPixel: state.secondsPerPixel,scrollLeft: state.scrollLeft,trackScroll: state.trackScroll,});- // Null means outside the canvas or over the ruler; both mean "do- // nothing". Any lane accepts any media.if (!drop) return;const start = state.snap@@ -857,7 +869,6 @@ function Editor({playhead: state.playhead,}): drop.start;-placeMedia(item.id, drop.trackId, Math.max(0, start));};@@ -868,30 +879,27 @@ function Editor({);const splitAtPlayhead = useCallback(() => {- setProject((current) => {- // Split whatever is selected, or everything under the playhead if- // nothing is - which is what the keyboard shortcut is usually for.- const targets =- selectedClipIds.length > 0- ? selectedClipIds- : clipsAt(current, playhead).map((clip) => clip.id);- return targets.reduce((next, clipId) => splitClip(next, clipId, playhead), current);- });- }, [playhead, selectedClipIds]);+ const current = latest.current.project;+ const at = latest.current.playhead;+ const targets =+ selectedClipIds.length > 0+ ? selectedClipIds+ : clipsAt(current, at).map((clip) => clip.id);+ if (targets.length === 0) return;+ void dispatch({ op: "splitClips", clipIds: targets, time: at });+ }, [selectedClipIds, dispatch]);const mergeSelected = useCallback(() => {- setProject((current) => {- const { project: next, clipId } = mergeClips(current, selectedClipIds);+ void dispatch({ op: "mergeClips", clipIds: selectedClipIds }).then((clipId) => {if (clipId) setSelectedClipIds([clipId]);- return next;});- }, [selectedClipIds]);+ }, [selectedClipIds, dispatch]);const deleteSelected = useCallback(() => {if (selectedClipIds.length === 0) return;- setProject((current) => removeClips(current, selectedClipIds));+ void dispatch({ op: "removeClips", clipIds: selectedClipIds });setSelectedClipIds([]);- }, [selectedClipIds]);+ }, [selectedClipIds, dispatch]);const zoom = useCallback((factor: number, anchor?: number) => {const previous = zoomRef.current;@@ -901,8 +909,6 @@ function Editor({);zoomRef.current = next;setSecondsPerPixel(next);-- // Keep the time under the pointer pinned to the same pixel.if (anchor !== undefined) {setScrollLeft((left) => Math.max(0, anchor - (anchor - left) * (next / previous)));}@@ -926,9 +932,6 @@ function Editor({// ── keyboard ─────────────────────────────────────────────────────────────useEffect(() => {const onKey = (event: KeyboardEvent) => {- // Never steal keys from anywhere text is being written: inputs, the- // text panel's textarea, and inline editing (contentEditable). Space- // must insert a space there, and Backspace must not delete a clip.const target = event.target;if (target instanceof HTMLInputElement ||@@ -939,15 +942,17 @@ function Editor({return;}- /*- * Modified shortcuts are handled separately and then we return.- *- * Without this the two sets ran together: Ctrl+S matched the bare `S`- * case and split the clip instead of saving, which is exactly the sort- * of thing that makes an app feel hostile.- */if (event.ctrlKey || event.metaKey) {switch (event.code) {+ case "KeyZ":+ event.preventDefault();+ if (event.shiftKey) redoAction();+ else undoAction();+ break;+ case "KeyY":+ event.preventDefault();+ redoAction();+ break;case "KeyS":event.preventDefault();saveAndNotify();@@ -966,7 +971,6 @@ function Editor({return;}- // Alt is left alone entirely; nothing here claims it.if (event.altKey) return;const step = event.shiftKey ? 10 : 1;@@ -1013,78 +1017,70 @@ function Editor({window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);- }, [deleteSelected, duration, frameRate, mergeSelected, saveAndNotify, splitAtPlayhead, transport]);+ }, [+ deleteSelected,+ duration,+ frameRate,+ mergeSelected,+ redoAction,+ saveAndNotify,+ splitAtPlayhead,+ transport,+ undoAction,+ ]);++ // ── derived views ────────────────────────────────────────────────────────- // The exporter works from a flat list: the engine rebuilds a real timeline- // from it, so track *order* has to survive the trip even though track- // identity does not.- const exportClips = useMemo<ExportClip[]>(- () =>- project.clips.flatMap((clip) => {- // Titles have no file to hand the exporter, so they are rasterised- // separately and appended as full-frame overlays - see `textLayers`.- if (clip.kind === "text") return [];+ const textOverlays = useMemo<TextOverlay[]>(() => {+ const depth = (trackId: string) =>+ timeline.tracks.findIndex((track) => track.id === trackId);+ return clipsAt(project, playhead)+ .filter((clip) => clip.kind === "text" && clip.text !== undefined)+ .filter((clip) => findTrack(project, clip.trackId)?.visible !== false)+ .sort((a, b) => depth(a.trackId) - depth(b.trackId))+ .map((clip) => ({+ clipId: clip.id,+ style: clip.text!,+ offsetX: clip.offsetX,+ offsetY: clip.offsetY,+ }));+ }, [project, timeline, playhead]);- const media = findMedia(project, clip.mediaId);- const track = findTrack(project, clip.trackId);- const index = project.tracks.findIndex((candidate) => candidate.id === clip.trackId);- if (!media || !track || index < 0) return [];- return [- {- path: media.path,- kind: clip.kind,- start: clip.start,- duration: clip.duration,- sourceStart: clip.sourceStart,- track: index,- hidden: !track.visible,- muted: track.muted || clip.muted === true,- volume: clip.volume,- fadeIn: clip.fadeIn,- fadeOut: clip.fadeOut,- filterChain: buildChain(clip.filters) ?? "",- speed: clip.speed,- preservePitch: clip.preservePitch,- scale: clip.scale,- offsetX: clip.offsetX,- offsetY: clip.offsetY,- rotation: clip.rotation,- opacity: clip.opacity,- videoFilterChain: buildEffectChain(clip.videoEffects) ?? "",- // The transition rides along only while its cut still exists;- // the host would orphan it anyway, but not sending it keeps the- // request honest about what will render.- transition:- clip.transitionIn && precedingClip(project, clip.id)- ? { kind: clip.transitionIn.id, duration: clip.transitionIn.duration }- : null,- mediaWidth: media.width,- mediaHeight: media.height,- },- ];- }),- [project],- );+ const previewSource = useMemo<PreviewSource | null>(() => {+ const active = clipsAt(project, playhead).filter(+ (clip) => clip.kind !== "audio" && clip.kind !== "text",+ );+ if (active.length === 0) return null;+ const depth = (trackId: string) =>+ timeline.tracks.findIndex((track) => track.id === trackId);+ const top = active.reduce((best, clip) =>+ depth(clip.trackId) > depth(best.trackId) ? clip : best,+ );+ const media = findMedia(project, top.mediaId);+ if (!media) return null;+ return {+ clipId: top.id,+ path: media.path,+ time: top.sourceStart + (playhead - top.start) * top.speed,+ speed: top.speed,+ isStill: top.kind === "image",+ };+ }, [project, timeline, playhead]);++ const previewClip = previewSource ? findClip(project, previewSource.clipId) : null;+ const previewMedia = previewClip ? findMedia(project, previewClip.mediaId) : null;- /**- * A cross-fade window the playhead currently sits inside: the incoming- * clip's pre-roll, faded in over the outgoing picture. This is the same- * overlap the export builds - the ghost plays the handle before the- * incoming clip's in-point, ramping from zero to solid at the cut.- */const previewGhost = useMemo(() => {- for (const clip of project.clips) {+ for (const clip of timeline.clips) {const transition = clip.transitionIn;if (!transition || transition.id !== "cross-fade") continue;if (clip.kind !== "video" && clip.kind !== "image") continue;if (!precedingClip(project, clip.id)) continue;-- // The dissolve clamps to the source handle, like the export does.- const handle = clip.kind === "image" ? Infinity : clip.sourceStart / Math.max(0.0625, clip.speed);+ const handle =+ clip.kind === "image" ? Infinity : clip.sourceStart / Math.max(0.0625, clip.speed);const d = Math.min(transition.duration, handle);const cut = clip.start;if (d <= 0 || playhead < cut - d || playhead >= cut) continue;-const media = findMedia(project, clip.mediaId);if (!media) continue;return {@@ -1096,25 +1092,17 @@ function Editor({};}return null;- }, [project, playhead]);+ }, [project, timeline, playhead]);- /**- * The fade-to-colour wash over the monitor while the playhead crosses a- * fade-black/white transition. Mirrors the exporter's shape exactly: half- * the duration out on the old clip, half in on the new one, meeting fully- * opaque at the cut.- */const previewVeil = useMemo(() => {- for (const clip of project.clips) {+ for (const clip of timeline.clips) {const transition = clip.transitionIn;if (!transition) continue;if (transition.id !== "fade-black" && transition.id !== "fade-white") continue;if (!precedingClip(project, clip.id)) continue;-const half = transition.duration / 2;const cut = clip.start;if (playhead < cut - half || playhead > cut + half) continue;-const opacity =playhead <= cut ? (playhead - (cut - half)) / half : (cut + half - playhead) / half;return {@@ -1123,18 +1111,57 @@ function Editor({};}return null;- }, [project, playhead]);+ }, [project, timeline, playhead]);++ // The exporter works from a flat list of the active timeline's clips.+ const exportClips = useMemo<ExportClip[]>(+ () =>+ timeline.clips.flatMap((clip) => {+ if (clip.kind === "text") return [];+ const media = findMedia(project, clip.mediaId);+ const track = findTrack(project, clip.trackId);+ const index = timeline.tracks.findIndex((candidate) => candidate.id === clip.trackId);+ if (!media || !track || index < 0) return [];+ return [+ {+ path: media.path,+ kind: clip.kind as "video" | "audio" | "image",+ start: clip.start,+ duration: clip.duration,+ sourceStart: clip.sourceStart,+ track: index,+ hidden: !track.visible,+ muted: track.muted || clip.muted === true,+ volume: clip.volume,+ fadeIn: clip.fadeIn,+ fadeOut: clip.fadeOut,+ filterChain: buildChain(clip.filters) ?? "",+ speed: clip.speed,+ preservePitch: clip.preservePitch,+ scale: clip.scale,+ offsetX: clip.offsetX,+ offsetY: clip.offsetY,+ rotation: clip.rotation,+ opacity: clip.opacity,+ videoFilterChain: buildEffectChain(clip.videoEffects) ?? "",+ transition:+ clip.transitionIn && precedingClip(project, clip.id)+ ? { kind: clip.transitionIn.id, duration: clip.transitionIn.duration }+ : null,+ mediaWidth: media.width,+ mediaHeight: media.height,+ },+ ];+ }),+ [project, timeline],+ );- // Titles for the exporter. They have no file to hand over - the dialog- // rasterises them into full-frame PNGs at export time - so all it needs is- // the style and where the clip sits. Hidden tracks drop out here, the same- // cut `exportClips` makes with `hidden`.const exportTitles = useMemo<ExportTitle[]>(() =>- project.clips.flatMap((clip) => {+ timeline.clips.flatMap((clip) => {if (clip.kind !== "text" || !clip.text) return [];const track = findTrack(project, clip.trackId);- const index = project.tracks.findIndex((candidate) => candidate.id === clip.trackId);+ const index = timeline.tracks.findIndex((candidate) => candidate.id === clip.trackId);if (!track || !track.visible || index < 0) return [];return [{@@ -1148,11 +1175,9 @@ function Editor({},];}),- [project],+ [project, timeline],);- // The inspector shows one clip's properties; with several selected there is- // no single set of values to show, so it falls back to the bin item.const selectedClip =selectedClipIds.length === 1 ? findClip(project, selectedClipIds[0]) : null;const inspectorMedia = selectedClip@@ -1238,6 +1263,22 @@ function Editor({{label: "Edit",groups: [+ [+ {+ label: "Undo",+ icon: "chevronUp",+ hint: "Ctrl+Z",+ disabled: !view?.canUndo,+ onSelect: undoAction,+ },+ {+ label: "Redo",+ icon: "chevronDown",+ hint: "Ctrl+Shift+Z",+ disabled: !view?.canRedo,+ onSelect: redoAction,+ },+ ],[{ label: "Split at playhead", icon: "razor", hint: "Ctrl+B", onSelect: splitAtPlayhead },{@@ -1306,7 +1347,7 @@ function Editor({setSelectedClipIds([]);}}onImport={(paths) => void importPaths(paths)}- onRemove={(id) => setProject((current) => removeMediaEverywhere(current, id))}+ onRemove={(id) => void dispatch({ op: "removeMedia", mediaId: id })}onDismissError={() => setError(null)}onBeginDrag={beginMediaDrag}onAddToTimeline={addToTimeline}@@ -1353,28 +1394,21 @@ function Editor({selectedClipId={selectedClipIds.length === 1 ? selectedClipIds[0] : null}onSelectClip={(clipId) => setSelectedClipIds([clipId])}onTransformChange={(clipId, transform) =>- setProject((current) => setClipTransform(current, clipId, transform))- }- onOverlayChange={(clipId, change) =>- setProject((current) => {- let next = current;- if (change.offsetX !== undefined || change.offsetY !== undefined) {- next = setClipTransform(next, clipId, {- offsetX: change.offsetX,- offsetY: change.offsetY,- });- }- if (change.fontSize !== undefined) {- const clip = findClip(next, clipId);- if (clip?.text) {- next = updateClip(next, clipId, {- text: { ...clip.text, fontSize: change.fontSize },- });- }- }- return next;- })+ liveClip(clipId, transformPatch(transform))}+ onTransformEnd={commitEcho}+ onOverlayChange={(clipId, change) => {+ const patch: Partial<Clip> = transformPatch({+ offsetX: change.offsetX,+ offsetY: change.offsetY,+ });+ if (change.fontSize !== undefined) {+ const clip = findClip(latest.current.project, clipId);+ if (clip?.text) patch.text = { ...clip.text, fontSize: change.fontSize };+ }+ liveClip(clipId, patch);+ }}+ onOverlayEnd={commitEcho}onFrameChange={(width, height) => setFrame({ width, height })}onTogglePlay={transport.toggle}onStep={(frames) => transport.step(frames, frameRate)}@@ -1396,21 +1430,17 @@ function Editor({clip={selectedClip}media={inspectorMedia}project={project}+ fonts={fontsForUi}projectName={session.name}projectPath={session.path}frame={frame}duration={duration}frameRate={frameRate}onAddFont={() => void pickFont()}- onRemoveFont={(family) => setProject((current) => removeFont(current, family))}- onChangeClip={(patch) => {- if (selectedClipIds.length !== 1) return;- setProject((current) => updateClip(current, selectedClipIds[0], patch));- }}- onSpeedChange={(speed) => {- if (selectedClipIds.length !== 1) return;- setProject((current) => setClipSpeed(current, selectedClipIds[0], speed));- }}+ onRemoveFont={(family) => void dispatch({ op: "removeFont", family })}+ onChangeClip={changeClip}+ onCommitClip={commitEcho}+ onSpeedChange={changeSpeed}/></div></div>@@ -1440,10 +1470,16 @@ function Editor({onSnapChange={setSnap}onScrub={transport.seek}onSelectClips={setSelectedClipIds}- onMoveClips={(moves) => setProject((current) => moveClips(current, moves))}- onTrimClip={(clipId, edge, delta) =>- setProject((current) => trimClip(current, clipId, edge, delta))- }+ onMoveClips={(moves) => {+ for (const move of moves) {+ liveClip(move.clipId, { start: Math.max(0, move.start), trackId: move.trackId });+ }+ }}+ onTrimClip={(clipId, edge, delta) => {+ const clip = findClip(latest.current.project, clipId);+ if (clip) liveClip(clipId, trimPatch(clip, edge, delta));+ }}+ onGestureEnd={commitEcho}onSplitAtPlayhead={splitAtPlayhead}onMergeSelected={mergeSelected}mergeBlockedBecause={whyNotMerge(project, selectedClipIds)}@@ -1454,38 +1490,28 @@ function Editor({onTrackScroll={setTrackScroll}onFit={fit}onTrackFlag={(trackId, flag, value) =>- setProject((current) => setTrackFlag(current, trackId, flag, value))+ void dispatch({ op: "setTrackFlag", trackId, flag, value })}clipTools={clipTools}onSelectTimeline={selectTimeline}onAddTimeline={createTimeline}onRenameTimeline={(timelineId, name) =>- setProject((current) => renameTimeline(current, timelineId, name))+ void dispatch({ op: "renameTimeline", timelineId, name })}onRequestRemoveTimeline={(timelineId) => {const meta = project.timelines.find((candidate) => candidate.id === timelineId);- if (meta) setTimelineToDelete(meta);+ if (meta) setTimelineToDelete({ id: meta.id, name: meta.name });}}- onAddTrack={() => setProject((current) => addTrack(current).project)}+ onAddTrack={() => void dispatch({ op: "addTrack" })}onRenameTrack={(trackId, name) =>- setProject((current) => renameTrack(current, trackId, name))- }- onRemoveTrack={(trackId) =>- setProject((current) => {- setSelectedClipIds((ids) =>- ids.filter((id) => findClip(current, id)?.trackId !== trackId),- );- return removeTrack(current, trackId);- })+ void dispatch({ op: "renameTrack", trackId, name })}+ onRemoveTrack={(trackId) => void dispatch({ op: "removeTrack", trackId })}onClipContextMenu={(clipId, x, y) => {- // Right-clicking outside the selection replaces it; inside it,- // the menu acts on everything selected.const target = selectedClipIds.includes(clipId) ? selectedClipIds : [clipId];setSelectedClipIds(target);const clip = findClip(project, clipId);- const track = clip ? findTrack(project, clip.trackId) : null;const many = target.length > 1;setContext({@@ -1508,11 +1534,6 @@ function Editor({},]: []),- // "Detach audio" and its reverse, offered only where they- // mean something: one clip, with a link to make or unmake.- // Captions come from the clip's own sound, so the item only- // appears where there is sound to transcribe - and only one- // transcription runs at a time....(() => {const media = clip ? findMedia(project, clip.mediaId) : null;return !many &&@@ -1538,7 +1559,7 @@ function Editor({{label: "Detach audio",icon: "waveform" as const,- onSelect: () => setProject((current) => detachAudio(current, clipId)),+ onSelect: () => void dispatch({ op: "detachAudio", clipId }),},]: []),@@ -1553,7 +1574,7 @@ function Editor({label: "Reattach audio",icon: "merge" as const,onSelect: () => {- setProject((current) => reattachAudio(current, clipId));+ void dispatch({ op: "reattachAudio", clipId });setSelectedClipIds([]);},},@@ -1562,13 +1583,21 @@ function Editor({{label: "Move to playhead",icon: "select",- onSelect: () =>- setProject((current) =>- moveClip(current, clipId, {- start: playhead,- trackId: track?.id ?? "",- }),- ),+ onSelect: () => {+ const moving = findClip(latest.current.project, clipId);+ if (moving) {+ void dispatch({+ op: "moveClips",+ moves: [+ {+ clipId,+ start: latest.current.playhead,+ trackId: moving.trackId,+ },+ ],+ });+ }+ },},{label: many ? `Delete ${target.length} clips` : "Delete",@@ -1576,7 +1605,7 @@ function Editor({hint: "Del",danger: true,onSelect: () => {- setProject((current) => removeClips(current, target));+ void dispatch({ op: "removeClips", clipIds: target });setSelectedClipIds([]);},},@@ -1596,8 +1625,7 @@ function Editor({message={(() => {const count = timelineClipCount(project, timelineToDelete.id);return count > 0- ? `The ${count} clip${count === 1 ? "" : "s"} on this timeline will be lost. ` +- "There is no undo."+ ? `The ${count} clip${count === 1 ? "" : "s"} on this timeline will be lost.`: "The timeline is empty; nothing else is affected.";})()}confirmLabel="Delete timeline"@@ -1640,8 +1668,7 @@ function Editor({/>)}- {/* The dragged item follows the pointer. Offset down-right so it never- sits under the cursor and hides the lane being targeted. */}+ {/* The dragged item follows the pointer. */}{mediaDrag && (<divstyle={{ left: mediaDrag.x + 14, top: mediaDrag.y + 14 }}@@ -1655,7 +1682,6 @@ function Editor({<span className="max-w-48 truncate text-xs text-primary">{mediaDrag.item.name}</span></div>)}-</div>);}diff --git a/desktop/src/components/AdjustPanel.tsx b/desktop/src/components/AdjustPanel.tsxindex e61c6d1c..1de2e7e8 100644--- a/desktop/src/components/AdjustPanel.tsx+++ b/desktop/src/components/AdjustPanel.tsx@@ -1,4 +1,4 @@-import { MAX_SCALE, MIN_SCALE, type Clip } from "../lib/project";+import { MAX_SCALE, MIN_SCALE, type Clip } from "../lib/editor";import { Group, Slider, Toggle } from "./controls";import { Icon } from "./Icon";import { Empty } from "./Panel";@@ -48,10 +48,14 @@ function formatDecibels(decibels: number): string {export function AdjustPanel({clip,onChange,+ onCommit,onSpeedChange,}: {clip: Clip | null;+ /** Live change - echoed locally while the gesture is in flight. */onChange: (patch: Partial<Clip>) => void;+ /** Gesture finished - the accumulated change becomes one engine command. */+ onCommit: () => void;/** Separate, because changing speed also rescales the clip's duration. */onSpeedChange: (speed: number) => void;}) {@@ -82,8 +86,9 @@ export function AdjustPanel({max={MAX_SCALE}step={0.01}format={(value) => `${Math.round(value * 100)}%`}- onReset={() => onChange({ scale: 1 })}+ onReset={() => { onChange({ scale: 1 }); onCommit(); }}onChange={(scale) => onChange({ scale })}+ onCommit={onCommit}/><Sliderlabel="Position X"@@ -92,8 +97,9 @@ export function AdjustPanel({max={1}step={0.005}format={(value) => `${Math.round(value * 100)}%`}- onReset={() => onChange({ offsetX: 0 })}+ onReset={() => { onChange({ offsetX: 0 }); onCommit(); }}onChange={(offsetX) => onChange({ offsetX })}+ onCommit={onCommit}/><Sliderlabel="Position Y"@@ -102,8 +108,9 @@ export function AdjustPanel({max={1}step={0.005}format={(value) => `${Math.round(value * 100)}%`}- onReset={() => onChange({ offsetY: 0 })}+ onReset={() => { onChange({ offsetY: 0 }); onCommit(); }}onChange={(offsetY) => onChange({ offsetY })}+ onCommit={onCommit}/><Sliderlabel="Rotation"@@ -112,8 +119,9 @@ export function AdjustPanel({max={180}step={1}format={(value) => `${Math.round(value)}°`}- onReset={() => onChange({ rotation: 0 })}+ onReset={() => { onChange({ rotation: 0 }); onCommit(); }}onChange={(rotation) => onChange({ rotation })}+ onCommit={onCommit}/><Sliderlabel="Opacity"@@ -122,8 +130,9 @@ export function AdjustPanel({max={1}step={0.01}format={(value) => `${Math.round(value * 100)}%`}- onReset={() => onChange({ opacity: 1 })}+ onReset={() => { onChange({ opacity: 1 }); onCommit(); }}onChange={(opacity) => onChange({ opacity })}+ onCommit={onCommit}/></Group>)}@@ -137,8 +146,9 @@ export function AdjustPanel({max={MAX_DB}step={0.5}format={formatDecibels}- onReset={() => onChange({ volume: 1 })}+ onReset={() => { onChange({ volume: 1 }); onCommit(); }}onChange={(decibels) => onChange({ volume: fromDecibels(decibels) })}+ onCommit={onCommit}/></Group>)}@@ -158,14 +168,15 @@ export function AdjustPanel({max={16}step={0.05}format={(value) => `${value.toFixed(2)}x`}- onReset={() => onSpeedChange(1)}+ onReset={() => { onSpeedChange(1); onCommit(); }}onChange={onSpeedChange}+ onCommit={onCommit}/><Togglelabel="Change pitch with speed"hint="Off keeps the voice where it is. On is tape behaviour - faster also means higher."checked={!clip.preservePitch}- onChange={(checked) => onChange({ preservePitch: !checked })}+ onChange={(checked) => { onChange({ preservePitch: !checked }); onCommit(); }}/></Group>)}@@ -179,8 +190,9 @@ export function AdjustPanel({max={fadeLimit}step={0.05}format={(value) => (value === 0 ? "none" : `${value.toFixed(2)}s`)}- onReset={() => onChange({ fadeIn: 0 })}+ onReset={() => { onChange({ fadeIn: 0 }); onCommit(); }}onChange={(fadeIn) => onChange({ fadeIn })}+ onCommit={onCommit}/><Sliderlabel="Fade out"@@ -189,8 +201,9 @@ export function AdjustPanel({max={fadeLimit}step={0.05}format={(value) => (value === 0 ? "none" : `${value.toFixed(2)}s`)}- onReset={() => onChange({ fadeOut: 0 })}+ onReset={() => { onChange({ fadeOut: 0 }); onCommit(); }}onChange={(fadeOut) => onChange({ fadeOut })}+ onCommit={onCommit}/></Group>)}diff --git a/desktop/src/components/EffectsPanel.tsx b/desktop/src/components/EffectsPanel.tsxindex 1e7872b3..89601399 100644--- a/desktop/src/components/EffectsPanel.tsx+++ b/desktop/src/components/EffectsPanel.tsx@@ -6,7 +6,7 @@ import {type AppliedEffect,type ClipTransition,} from "../lib/effects";-import type { Clip } from "../lib/project";+import type { Clip } from "../lib/editor";import { HelpTip, Slider } from "./controls";import { Icon, IconButton } from "./Icon";import { Empty } from "./Panel";@@ -25,12 +25,15 @@ export function EffectsPanel({hasPreceding,onChangeEffects,onChangeTransition,+ onCommit,}: {clip: Clip | null;/** Whether a clip ends where this one starts - what a transition needs. */hasPreceding: boolean;onChangeEffects: (effects: AppliedEffect[]) => void;onChangeTransition: (transition: ClipTransition | undefined) => void;+ /** Ends the gesture: the accumulated change becomes one engine command. */+ onCommit: () => void;}) {if (!clip || (clip.kind !== "video" && clip.kind !== "image")) {return (@@ -44,18 +47,27 @@ export function EffectsPanel({const transition = clip.transitionIn;const transitionDefinition = transition ? findTransition(transition.id) : null;- const add = (id: string) => onChangeEffects([...applied, { id, params: {} }]);- const remove = (index: number) => onChangeEffects(applied.filter((_, at) => at !== index));+ const commitEffects = (effects: AppliedEffect[]) => {+ onChangeEffects(effects);+ onCommit();+ };+ const add = (id: string) => commitEffects([...applied, { id, params: {} }]);+ const remove = (index: number) => commitEffects(applied.filter((_, at) => at !== index));const patch = (index: number, change: Partial<AppliedEffect>) =>- onChangeEffects(applied.map((effect, at) => (at === index ? { ...effect, ...change } : effect)));+ commitEffects(applied.map((effect, at) => (at === index ? { ...effect, ...change } : effect)));+ // Live: parameters echo while the slider moves and commit on release.const setParam = (index: number, key: string, value: number) =>- patch(index, { params: { ...applied[index].params, [key]: value } });+ onChangeEffects(+ applied.map((effect, at) =>+ at === index ? { ...effect, params: { ...effect.params, [key]: value } } : effect,+ ),+ );const move = (index: number, by: number) => {const target = index + by;if (target < 0 || target >= applied.length) return;const next = [...applied];[next[index], next[target]] = [next[target], next[index]];- onChangeEffects(next);+ commitEffects(next);};return (@@ -76,7 +88,10 @@ export function EffectsPanel({label={`Remove ${transitionDefinition.label}`}size={7}tone="danger"- onClick={() => onChangeTransition(undefined)}+ onClick={() => {+ onChangeTransition(undefined);+ onCommit();+ }}/></div>{!hasPreceding && (@@ -92,10 +107,12 @@ export function EffectsPanel({max={3}step={0.1}format={(value) => `${value.toFixed(1)}s`}- onReset={() =>- onChangeTransition({ ...transition, duration: transitionDefinition.defaultDuration })- }+ onReset={() => {+ onChangeTransition({ ...transition, duration: transitionDefinition.defaultDuration });+ onCommit();+ }}onChange={(value) => onChangeTransition({ ...transition, duration: value })}+ onCommit={onCommit}/></div></section>@@ -166,8 +183,12 @@ export function EffectsPanel({max={param.max}step={param.step}format={param.format}- onReset={() => setParam(index, param.key, param.default)}+ onReset={() => {+ setParam(index, param.key, param.default);+ onCommit();+ }}onChange={(value) => setParam(index, param.key, value)}+ onCommit={onCommit}/>))}{definition.params.length === 0 && (diff --git a/desktop/src/components/FiltersPanel.tsx b/desktop/src/components/FiltersPanel.tsxindex b6be3c94..79b4d0e5 100644--- a/desktop/src/components/FiltersPanel.tsx+++ b/desktop/src/components/FiltersPanel.tsx@@ -9,7 +9,7 @@ import {type FilterCategory,type FilterDefinition,} from "../lib/filters";-import type { Clip } from "../lib/project";+import type { Clip } from "../lib/editor";import { HelpTip, Slider } from "./controls";import { Icon, IconButton } from "./Icon";import { Empty } from "./Panel";@@ -29,9 +29,12 @@ import { Empty } from "./Panel";export function FiltersPanel({clip,onChange,+ onCommit,}: {clip: Clip | null;onChange: (filters: ClipFilter[]) => void;+ /** Ends the gesture: the accumulated change becomes one engine command. */+ onCommit: () => void;}) {const [category, setCategory] = useState<FilterCategory>("voice");const [query, setQuery] = useState("");@@ -54,18 +57,27 @@ export function FiltersPanel({const applied = clip.filters;- const add = (id: string) => onChange([...applied, { id, params: {} }]);- const remove = (index: number) => onChange(applied.filter((_, at) => at !== index));+ const commitChange = (filters: ClipFilter[]) => {+ onChange(filters);+ onCommit();+ };+ const add = (id: string) => commitChange([...applied, { id, params: {} }]);+ const remove = (index: number) => commitChange(applied.filter((_, at) => at !== index));const patch = (index: number, change: Partial<ClipFilter>) =>- onChange(applied.map((filter, at) => (at === index ? { ...filter, ...change } : filter)));+ commitChange(applied.map((filter, at) => (at === index ? { ...filter, ...change } : filter)));+ // Live: parameters echo while the slider moves and commit on release.const setParam = (index: number, key: string, value: number) =>- patch(index, { params: { ...applied[index].params, [key]: value } });+ onChange(+ applied.map((filter, at) =>+ at === index ? { ...filter, params: { ...filter.params, [key]: value } } : filter,+ ),+ );const move = (index: number, by: number) => {const target = index + by;if (target < 0 || target >= applied.length) return;const next = [...applied];[next[index], next[target]] = [next[target], next[index]];- onChange(next);+ commitChange(next);};// A search cuts across the categories: when you know the name you should@@ -144,8 +156,12 @@ export function FiltersPanel({max={param.max}step={param.step}format={param.format}- onReset={() => setParam(index, param.key, param.default)}+ onReset={() => {+ setParam(index, param.key, param.default);+ onCommit();+ }}onChange={(value) => setParam(index, param.key, value)}+ onCommit={onCommit}/>))}</div>diff --git a/desktop/src/components/Inspector.tsx b/desktop/src/components/Inspector.tsxindex 26736b73..13ca72c7 100644--- a/desktop/src/components/Inspector.tsx+++ b/desktop/src/components/Inspector.tsx@@ -1,6 +1,6 @@import type { ReactNode } from "react";-import type { Clip, MediaItem, Project } from "../lib/project";+import { activeTimeline, type Clip, type EditorProject, type MediaItem } from "../lib/editor";import { shortDuration, timecode } from "../lib/time";/**@@ -24,7 +24,7 @@ export function Inspector({clip: Clip | null;media: MediaItem | null;frameRate: number;- project: Project;+ project: EditorProject;projectName: string;projectPath: string;/** The output size, as currently set in the preview footer. */@@ -45,8 +45,8 @@ export function Inspector({</Section><Section title="Contents"><Row label="Media" value={`${project.media.length}`} mono />- <Row label="Tracks" value={`${project.tracks.length}`} mono />- <Row label="Clips" value={`${project.clips.length}`} mono />+ <Row label="Tracks" value={`${activeTimeline(project).tracks.length}`} mono />+ <Row label="Clips" value={`${activeTimeline(project).clips.length}`} mono /></Section></div>) : (diff --git a/desktop/src/components/MediaBin.tsx b/desktop/src/components/MediaBin.tsxindex dc3548bc..689f91cf 100644--- a/desktop/src/components/MediaBin.tsx+++ b/desktop/src/components/MediaBin.tsx@@ -12,7 +12,7 @@ import {type EffectCategory,type TransitionCategory,} from "../lib/effects";-import type { MediaItem } from "../lib/project";+import type { MediaItem } from "../lib/editor";import { themeColor } from "../lib/theme";import { shortDuration } from "../lib/time";import { ErrorNotice } from "./ErrorNotice";diff --git a/desktop/src/components/Preview.tsx b/desktop/src/components/Preview.tsxindex 54f74f38..6efe3be5 100644--- a/desktop/src/components/Preview.tsx+++ b/desktop/src/components/Preview.tsx@@ -10,7 +10,7 @@ import { convertFileSrc } from "@tauri-apps/api/core";import { buildPreviewLook, type AppliedEffect, type CanvasOp } from "../lib/effects";import { timecode } from "../lib/time";-import { MAX_SCALE, MIN_SCALE } from "../lib/project";+import { MAX_SCALE, MIN_SCALE } from "../lib/editor";import { textCss, type TextStyle } from "../lib/text";import { Icon, IconButton } from "./Icon";import { Menu } from "./Menu";@@ -217,7 +217,9 @@ export function Preview({selectedClipId,onSelectClip,onTransformChange,+ onTransformEnd,onOverlayChange,+ onOverlayEnd,onFrameChange,onTogglePlay,onStep,@@ -250,12 +252,16 @@ export function Preview({selectedClipId: string | null;onSelectClip: (clipId: string) => void;onTransformChange: (clipId: string, transform: Partial<PreviewTransform>) => void;+ /** The gizmo drag ended - the echoed transform becomes one engine command. */+ onTransformEnd: () => void;/** Edits to a title dragged in the monitor: position, and size from the* corner handles. */onOverlayChange: (clipId: string,change: { offsetX?: number; offsetY?: number; fontSize?: number },) => void;+ /** The title drag ended - the echoed change becomes one engine command. */+ onOverlayEnd: () => void;onFrameChange: (width: number, height: number) => void;onTogglePlay: () => void;onStep: (frames: number) => void;@@ -575,6 +581,7 @@ export function Preview({selected={selectedClipId === source.clipId}onSelect={onSelectClip}onChange={onTransformChange}+ onChangeEnd={onTransformEnd}onGuides={setGuides}/>)}@@ -603,6 +610,7 @@ export function Preview({selected={selectedClipId === overlay.clipId}onSelect={onSelectClip}onChange={onOverlayChange}+ onChangeEnd={onOverlayEnd}onGuides={setGuides}/>))}@@ -947,6 +955,7 @@ function TransformGizmo({selected,onSelect,onChange,+ onChangeEnd,onGuides,}: {clipId: string;@@ -956,6 +965,8 @@ function TransformGizmo({selected: boolean;onSelect: (clipId: string) => void;onChange: (clipId: string, transform: Partial<PreviewTransform>) => void;+ /** The drag finished; whatever was echoed becomes one engine command. */+ onChangeEnd: () => void;onGuides: (guides: Guides) => void;}) {const box = useRef<HTMLDivElement>(null);@@ -1042,6 +1053,7 @@ function TransformGizmo({() => {onGuides(NO_GUIDES);detach.current = null;+ onChangeEnd();},);};@@ -1131,6 +1143,7 @@ function TextOverlayBox({selected,onSelect,onChange,+ onChangeEnd,onGuides,}: {overlay: TextOverlay;@@ -1138,6 +1151,8 @@ function TextOverlayBox({selected: boolean;onSelect: (clipId: string) => void;onChange: (clipId: string, change: { offsetX?: number; offsetY?: number; fontSize?: number }) => void;+ /** The drag finished; whatever was echoed becomes one engine command. */+ onChangeEnd: () => void;onGuides: (guides: Guides) => void;}) {const block = useRef<HTMLDivElement>(null);@@ -1192,6 +1207,7 @@ function TextOverlayBox({() => {onGuides(NO_GUIDES);detach.current = null;+ onChangeEnd();},);};diff --git a/desktop/src/components/RightPanel.tsx b/desktop/src/components/RightPanel.tsxindex c6dc3c2e..218704b6 100644--- a/desktop/src/components/RightPanel.tsx+++ b/desktop/src/components/RightPanel.tsx@@ -1,6 +1,12 @@import type { AppliedEffect, ClipTransition } from "../lib/effects";import type { ClipFilter } from "../lib/filters";-import { precedingClip, type Clip, type MediaItem, type Project } from "../lib/project";+import {+ precedingClip,+ type Clip,+ type CustomFont,+ type EditorProject,+ type MediaItem,+} from "../lib/editor";import { AdjustPanel } from "./AdjustPanel";import { EffectsPanel } from "./EffectsPanel";import { FiltersPanel } from "./FiltersPanel";@@ -50,12 +56,14 @@ export function RightPanel({clip,media,project,+ fonts,projectName,projectPath,frame,duration,frameRate,onChangeClip,+ onCommitClip,onSpeedChange,onAddFont,onRemoveFont,@@ -64,13 +72,17 @@ export function RightPanel({onTab: (tab: RightTab) => void;clip: Clip | null;media: MediaItem | null;- project: Project;+ project: EditorProject;+ /** Custom fonts with the UI's missing-file marks applied. */+ fonts: CustomFont[];projectName: string;projectPath: string;frame: { width: number; height: number };duration: number;frameRate: number;onChangeClip: (patch: Partial<Clip>) => void;+ /** Ends a control gesture: the accumulated change becomes one command. */+ onCommitClip: () => void;onSpeedChange: (speed: number) => void;onAddFont: () => void;onRemoveFont: (family: string) => void;@@ -125,19 +137,26 @@ export function RightPanel({{active === "text" && (<TextPanelclip={clip}- project={project}+ fonts={fonts}onChange={onChangeClip}+ onCommit={onCommitClip}onAddFont={onAddFont}onRemoveFont={onRemoveFont}/>)}{active === "adjust" && (- <AdjustPanel clip={clip} onChange={onChangeClip} onSpeedChange={onSpeedChange} />+ <AdjustPanel+ clip={clip}+ onChange={onChangeClip}+ onCommit={onCommitClip}+ onSpeedChange={onSpeedChange}+ />)}{active === "filters" && (<FiltersPanelclip={clip}onChange={(filters: ClipFilter[]) => onChangeClip({ filters })}+ onCommit={onCommitClip}/>)}{active === "effects" && (@@ -148,6 +167,7 @@ export function RightPanel({onChangeTransition={(transitionIn: ClipTransition | undefined) =>onChangeClip({ transitionIn })}+ onCommit={onCommitClip}/>)}</Panel>diff --git a/desktop/src/components/TextPanel.tsx b/desktop/src/components/TextPanel.tsxindex 508bfa1d..74fd1a46 100644--- a/desktop/src/components/TextPanel.tsx+++ b/desktop/src/components/TextPanel.tsx@@ -1,5 +1,5 @@-import type { Clip, Project } from "../lib/project";-import { FONTS, WEIGHTS, type CustomFont, type TextStyle } from "../lib/text";+import type { Clip, CustomFont } from "../lib/editor";+import { FONTS, WEIGHTS, type TextStyle } from "../lib/text";import { Group, Slider, Toggle } from "./controls";import { Icon } from "./Icon";import { Empty } from "./Panel";@@ -17,14 +17,19 @@ import { Empty } from "./Panel";*/export function TextPanel({clip,- project,+ fonts,onChange,+ onCommit,onAddFont,onRemoveFont,}: {clip: Clip | null;- project: Project;+ /** The project's custom fonts, with the UI's missing-file marks applied. */+ fonts: CustomFont[];+ /** Live change - echoed locally while the gesture is in flight. */onChange: (patch: Partial<Clip>) => void;+ /** Gesture finished - the accumulated change becomes one engine command. */+ onCommit: () => void;onAddFont: () => void;onRemoveFont: (family: string) => void;}) {@@ -49,7 +54,14 @@ export function TextPanel({);};- const custom: CustomFont[] = project.fonts;+ // Discrete controls commit immediately; sliders and the textarea echo+ // live and commit on release or blur.+ const commitSet = (patch: Partial<TextStyle>) => {+ set(patch);+ onCommit();+ };++ const custom: CustomFont[] = fonts;return (<div className="px-3 py-3">@@ -57,6 +69,7 @@ export function TextPanel({<textareavalue={style.content}onChange={(event) => set({ content: event.target.value })}+ onBlur={onCommit}rows={3}spellCheck={false}placeholder="Your text"@@ -69,7 +82,7 @@ export function TextPanel({<Group title="Font"><selectvalue={style.fontFamily}- onChange={(event) => set({ fontFamily: event.target.value })}+ onChange={(event) => commitSet({ fontFamily: event.target.value })}className="mb-2 w-full cursor-pointer rounded-lg border border-hairline-strong bg-sunkenpx-2.5 py-2 text-[12px] text-primary outline-none focus:border-accent">@@ -140,7 +153,7 @@ export function TextPanel({<selectvalue={style.fontWeight}- onChange={(event) => set({ fontWeight: Number(event.target.value) })}+ onChange={(event) => commitSet({ fontWeight: Number(event.target.value) })}className="mb-3 w-full cursor-pointer rounded-lg border border-hairline-strong bg-sunkenpx-2.5 py-2 text-[12px] text-primary outline-none focus:border-accent">@@ -161,14 +174,15 @@ export function TextPanel({// is. Points would be a lie: the frame can be any resolution.format={(value) => `${(value * 100).toFixed(1)}% of height`}onChange={(fontSize) => set({ fontSize })}- onReset={() => set({ fontSize: 0.09 })}+ onCommit={onCommit}+ onReset={() => commitSet({ fontSize: 0.09 })}/>- <Toggle label="Italic" checked={style.italic} onChange={(italic) => set({ italic })} />+ <Toggle label="Italic" checked={style.italic} onChange={(italic) => commitSet({ italic })} /></Group><Group title="Colour">- <Swatch label="Fill" value={style.color} onChange={(color) => set({ color })} />+ <Swatch label="Fill" value={style.color} onChange={(color) => commitSet({ color })} /><Sliderlabel="Opacity"@@ -177,27 +191,28 @@ export function TextPanel({max={1}format={(value) => `${Math.round(value * 100)}%`}onChange={(opacity) => set({ opacity })}- onReset={() => set({ opacity: 1 })}+ onCommit={onCommit}+ onReset={() => commitSet({ opacity: 1 })}/><Togglelabel="Drop shadow"hint="Keeps text readable over bright footage."checked={style.shadow}- onChange={(shadow) => set({ shadow })}+ onChange={(shadow) => commitSet({ shadow })}/><Togglelabel="Plate behind text"hint="A solid block, for when a shadow is not enough."checked={style.background !== ""}- onChange={(on) => set({ background: on ? "#000000" : "" })}+ onChange={(on) => commitSet({ background: on ? "#000000" : "" })}/>{style.background !== "" && (<Swatchlabel="Plate colour"value={style.background}- onChange={(background) => set({ background })}+ onChange={(background) => commitSet({ background })}/>)}</Group>@@ -211,13 +226,14 @@ export function TextPanel({step={0.005}format={(value) => (value === 0 ? "none" : `${(value * 100).toFixed(1)}%`)}onChange={(strokeWidth) => set({ strokeWidth })}- onReset={() => set({ strokeWidth: 0 })}+ onCommit={onCommit}+ onReset={() => commitSet({ strokeWidth: 0 })}/>{style.strokeWidth > 0 && (<Swatchlabel="Outline colour"value={style.strokeColor}- onChange={(strokeColor) => set({ strokeColor })}+ onChange={(strokeColor) => commitSet({ strokeColor })}/>)}</Group>@@ -229,7 +245,7 @@ export function TextPanel({key={align}type="button"aria-pressed={style.align === align}- onClick={() => set({ align })}+ onClick={() => commitSet({ align })}className={`flex-1 cursor-pointer rounded-[6px] px-2 py-1 text-[11px] capitalizetransition-colors ${style.align === align@@ -250,7 +266,8 @@ export function TextPanel({step={0.05}format={(value) => value.toFixed(2)}onChange={(lineHeight) => set({ lineHeight })}- onReset={() => set({ lineHeight: 1.2 })}+ onCommit={onCommit}+ onReset={() => commitSet({ lineHeight: 1.2 })}/><Slider@@ -261,7 +278,8 @@ export function TextPanel({step={0.005}format={(value) => `${value >= 0 ? "+" : ""}${(value * 100).toFixed(1)}%`}onChange={(tracking) => set({ tracking })}- onReset={() => set({ tracking: 0 })}+ onCommit={onCommit}+ onReset={() => commitSet({ tracking: 0 })}/></Group>@@ -281,7 +299,8 @@ export function TextPanel({Math.abs(value) < 0.0025 ? "centred" : `${(value * 100).toFixed(1)}%`}onChange={(offsetX) => onChange({ offsetX })}- onReset={() => onChange({ offsetX: 0 })}+ onCommit={onCommit}+ onReset={() => { onChange({ offsetX: 0 }); onCommit(); }}/><Sliderlabel="Vertical"@@ -293,7 +312,8 @@ export function TextPanel({Math.abs(value) < 0.0025 ? "centred" : `${(value * 100).toFixed(1)}%`}onChange={(offsetY) => onChange({ offsetY })}- onReset={() => onChange({ offsetY: 0 })}+ onCommit={onCommit}+ onReset={() => { onChange({ offsetY: 0 }); onCommit(); }}/></Group></div>diff --git a/desktop/src/components/TimelinePanel.tsx b/desktop/src/components/TimelinePanel.tsxindex 791d52f2..beb45941 100644--- a/desktop/src/components/TimelinePanel.tsx+++ b/desktop/src/components/TimelinePanel.tsx@@ -6,8 +6,15 @@ import type {import type { MediaAssets, Peaks } from "../lib/assets";import { themeColor, type Theme } from "../lib/theme";-import type { Clip, ClipMove, Project, TimelineMeta, Track } from "../lib/project";-import { snapTime } from "../lib/project";+import {+ activeTimeline,+ snapTime,+ type Clip,+ type ClipMove,+ type EditorProject,+ type TimelineMeta,+ type Track,+} from "../lib/editor";import { timecode } from "../lib/time";import { Icon, IconButton } from "./Icon";import { Menu, type MenuOption } from "./Menu";@@ -149,8 +156,9 @@ export function TimelinePanel({onAddTimeline,onRenameTimeline,onRequestRemoveTimeline,+ onGestureEnd,}: {- project: Project;+ project: EditorProject;playhead: number;/** Drives the view following the playhead during playback. */playing: boolean;@@ -199,6 +207,8 @@ export function TimelinePanel({onRenameTimeline: (timelineId: string, name: string) => void;/** Asks the app to confirm and delete; the panel never deletes directly. */onRequestRemoveTimeline: (timelineId: string) => void;+ /** A move or trim drag finished; the echoed change becomes one command. */+ onGestureEnd: () => void;}) {const canvasRef = useRef<HTMLCanvasElement>(null);const drag = useRef<DragState | null>(null);@@ -212,9 +222,11 @@ export function TimelinePanel({scrollRef.current = onScroll;/** The header column, kept in step with the canvas's vertical offset. */const headerScroll = useRef<HTMLDivElement>(null);+ // The lane and clip set being drawn: the active timeline's.+ const timeline = activeTimeline(project);// Top-most track first on screen; the model stores them bottom-most first to// match the engine's compositing order.- const rows: Track[] = [...project.tracks].reverse();+ const rows: Track[] = [...timeline.tracks].reverse();// Which lane a dragged bin item would land on. Tracks are untyped, so any// lane under the pointer is a valid target.@@ -235,8 +247,8 @@ export function TimelinePanel({// The draw loop reads everything through this ref, so a prop change never// tears down and rebuilds the loop.- const view = useRef({ project, playhead, playing, secondsPerPixel, scrollLeft, trackScroll, frameRate, selected, rows, dropTrack, assets, tool });- view.current = { project, playhead, playing, secondsPerPixel, scrollLeft, trackScroll, frameRate, selected, rows, dropTrack, assets, tool };+ const view = useRef({ project, timeline, playhead, playing, secondsPerPixel, scrollLeft, trackScroll, frameRate, selected, rows, dropTrack, assets, tool });+ view.current = { project, timeline, playhead, playing, secondsPerPixel, scrollLeft, trackScroll, frameRate, selected, rows, dropTrack, assets, tool };const timeAt = useCallback((clientX: number) => {@@ -263,11 +275,11 @@ export function TimelinePanel({const track = rowAt(clientY);if (!track) return null;const time = timeAt(clientX);- const { project, secondsPerPixel } = view.current;+ const { timeline, secondsPerPixel } = view.current;// Later clips draw on top, so search back to front.- for (let index = project.clips.length - 1; index >= 0; index -= 1) {- const clip = project.clips[index];+ for (let index = timeline.clips.length - 1; index >= 0; index -= 1) {+ const clip = timeline.clips[index];if (clip.trackId !== track.id) continue;if (time < clip.start || time > clip.start + clip.duration) continue;@@ -365,7 +377,7 @@ export function TimelinePanel({context.rect(0, RULER_HEIGHT, width, Math.max(0, height - RULER_HEIGHT));context.clip();- for (const clip of state.project.clips) {+ for (const clip of state.timeline.clips) {const rowIndex = state.rows.findIndex((track) => track.id === clip.trackId);if (rowIndex < 0) continue;@@ -400,7 +412,7 @@ export function TimelinePanel({const overClip =localY > RULER_HEIGHT &&track !== undefined &&- state.project.clips.some(+ state.timeline.clips.some((clip) =>clip.trackId === track.id && time > clip.start && time < clip.start + clip.duration,);@@ -534,7 +546,7 @@ export function TimelinePanel({grab: timeAt(event.clientX) - hit.clip.start,originRow,origins: moving.flatMap((clipId) => {- const clip = project.clips.find((candidate) => candidate.id === clipId);+ const clip = timeline.clips.find((candidate) => candidate.id === clipId);if (!clip) return [];return [{@@ -589,7 +601,7 @@ export function TimelinePanel({}if (state.kind === "move") {- const primary = project.clips.find((candidate) => candidate.id === state.primary);+ const primary = timeline.clips.find((candidate) => candidate.id === state.primary);const anchor = state.origins.find((origin) => origin.clipId === state.primary);if (!primary || !anchor) return;@@ -623,7 +635,7 @@ export function TimelinePanel({return;}- const clip = project.clips.find((candidate) => candidate.id === state.clipId);+ const clip = timeline.clips.find((candidate) => candidate.id === state.clipId);if (!clip) return;if (state.kind === "trimStart") onTrimClip(clip.id, "start", time - clip.start);if (state.kind === "trimEnd") onTrimClip(clip.id, "end", time - (clip.start + clip.duration));@@ -672,11 +684,15 @@ export function TimelinePanel({}const state = drag.current;+ // A move or trim was echoing locally; releasing is what makes it real.+ if (state?.kind === "move" || state?.kind === "trimStart" || state?.kind === "trimEnd") {+ onGestureEnd();+ }if (state?.kind === "marquee") {// Commit on release rather than live: selecting as the band sweeps looks// busy and makes a mistaken sweep hard to back out of.const band = normalise(state);- const caught = project.clips.filter((clip) => {+ const caught = timeline.clips.filter((clip) => {const rect = clipRect(clip, rows, secondsPerPixel, scrollLeft, trackScroll);return rect !== null && intersects(band, rect);});diff --git a/desktop/src/components/controls.tsx b/desktop/src/components/controls.tsxindex 9d9d45c5..2804ca5c 100644--- a/desktop/src/components/controls.tsx+++ b/desktop/src/components/controls.tsx@@ -64,6 +64,7 @@ export function Slider({step = 0.01,format,onChange,+ onCommit,onReset,}: {label: string;@@ -74,6 +75,12 @@ export function Slider({/** Turns the raw value into what the reader sees. */format: (value: number) => string;onChange: (value: number) => void;+ /**+ * Fires when a gesture finishes: pointer released, typed value committed,+ * or a keyboard step. The engine records one undo entry per commit, so+ * this is what makes a drag one undoable edit instead of sixty.+ */+ onCommit?: () => void;/** Double-clicking the label returns the control to this value. */onReset?: () => void;}) {@@ -114,6 +121,7 @@ export function Slider({const parsed = Number.parseFloat(typing.replace(",", "."));if (Number.isFinite(parsed)) onChange(clampStep(parsed));setTyping(null);+ onCommit?.();};const fill = max === min ? 0 : Math.min(1, Math.max(0, (value - min) / (max - min)));@@ -147,6 +155,9 @@ export function Slider({if (event.key === "ArrowLeft") onChange(clampStep(value - by));if (event.key === "ArrowRight") onChange(clampStep(value + by));}}+ onKeyUp={(event) => {+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") onCommit?.();+ }}onPointerDown={(event) => {event.currentTarget.setPointerCapture(event.pointerId);lastX.current = event.clientX;@@ -156,6 +167,12 @@ export function Slider({onPointerMove={(event) => {if (event.currentTarget.hasPointerCapture(event.pointerId)) commit(event);}}+ onPointerUp={(event) => {+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {+ event.currentTarget.releasePointerCapture(event.pointerId);+ }+ onCommit?.();+ }}className="relative h-6 min-w-0 flex-1 cursor-ew-resize touch-none select-noneoverflow-hidden rounded-md bg-sunken">@@ -197,6 +214,7 @@ export function Slider({const by = (event.shiftKey ? step * 10 : step) * (event.key === "ArrowUp" ? 1 : -1);setTyping(null);onChange(clampStep(value + by));+ onCommit?.();}}}className="h-6 w-14 shrink-0 rounded-md border border-hairline bg-sunken px-1.5diff --git a/desktop/src/lib/editor.ts b/desktop/src/lib/editor.tsnew file mode 100644index 00000000..ab62fa7e--- /dev/null+++ b/desktop/src/lib/editor.ts@@ -0,0 +1,477 @@+/**+ * The UI's view of the engine-owned edit.+ *+ * The engine (`relay-project`, via the `editor_*` commands) is the model of+ * record: every mutation is an [`EditorCommand`] sent through+ * `lib/engine.ts`, and the state that comes back is the truth. What lives+ * here is everything that is legitimately the UI's:+ *+ * - the TypeScript mirror of the engine's types (field for field - serde on+ * the other side writes exactly these names),+ * - read-only selectors over that state,+ * - the *gesture echo*: during a drag the UI previews the edit locally with+ * the same arithmetic the engine will apply, then commits one command on+ * release. One command per gesture is what keeps undo meaning "undo the+ * drag", not "undo one pixel of it".+ *+ * No mutation of project state happens in TypeScript outside the echo, and+ * the echo never survives past its commit.+ */++import type { AppliedEffect, ClipTransition } from "./effects";+import type { ClipFilter } from "./filters";+import type { TextStyle } from "./text";++// ── the engine's types, mirrored ─────────────────────────────────────────────++export type MediaKind = "video" | "audio" | "image";+export type ClipKind = MediaKind | "text";++export interface MediaItem {+ id: string;+ path: string;+ name: string;+ duration: number | null;+ kind: MediaKind;+ width: number | null;+ height: number | null;+ frameRate: number | null;+ frameRateFraction: string | null;+ videoCodec: string | null;+ audioCodec: string | null;+ hasAudio: boolean;+}++export interface Track {+ id: string;+ name: string;+ visible: boolean;+ muted: boolean;+}++export interface Clip {+ id: string;+ trackId: string;+ mediaId: string;+ name: string;+ kind: ClipKind;+ start: number;+ duration: number;+ sourceStart: number;+ volume: number;+ fadeIn: number;+ fadeOut: number;+ scale: number;+ offsetX: number;+ offsetY: number;+ rotation: number;+ opacity: number;+ speed: number;+ preservePitch: boolean;+ filters: ClipFilter[];+ videoEffects: AppliedEffect[];+ muted?: boolean;+ detachedFrom?: string;+ transitionIn?: ClipTransition;+ text?: TextStyle;+}++export interface TimelineData {+ id: string;+ name: string;+ tracks: Track[];+ clips: Clip[];+}++/** A timeline's identity, for the tab strip. */+export type TimelineMeta = Pick<TimelineData, "id" | "name">;++/** Transform limits, shared with the preview gizmo. The engine clamps too. */+export const MIN_SCALE = 0.05;+export const MAX_SCALE = 8;++export interface CustomFont {+ family: string;+ path: string;+ /** UI-only: a load attempt failed. Never sent to or from the engine. */+ missing?: boolean;+}++export interface EditorProject {+ media: MediaItem[];+ fonts: CustomFont[];+ timelines: TimelineData[];+ activeTimelineId: string;+}++export interface EditorSettings {+ name: string;+ width: number;+ height: number;+ rateNum: number;+ rateDen: number;+}++/** What every editor call returns: the authoritative state. */+export interface EditorView {+ project: EditorProject;+ canUndo: boolean;+ canRedo: boolean;+ settings: EditorSettings;+ createdId?: string;+}++// ── commands: the whole edit vocabulary ──────────────────────────────────────++/** A partial clip update. `null` clears `transitionIn`/`text`; absent leaves+ * a field untouched - the wire distinction the engine's double-options keep. */+export interface ClipPatch {+ name?: string;+ volume?: number;+ fadeIn?: number;+ fadeOut?: number;+ opacity?: number;+ preservePitch?: boolean;+ filters?: ClipFilter[];+ videoEffects?: AppliedEffect[];+ transitionIn?: ClipTransition | null;+ text?: TextStyle | null;+}++export interface ClipMove {+ clipId: string;+ start: number;+ trackId: string;+}++export interface NewMedia {+ path: string;+ name: string;+ duration: number | null;+ kind: MediaKind;+ width: number | null;+ height: number | null;+ frameRate: number | null;+ frameRateFraction: string | null;+ videoCodec: string | null;+ audioCodec: string | null;+ hasAudio: boolean;+}++export type EditorCommand =+ | { op: "addMedia"; item: NewMedia }+ | { op: "removeMedia"; mediaId: string }+ | { 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: "moveClips"; moves: ClipMove[] }+ | { op: "trimClip"; clipId: string; edge: "start" | "end"; delta: number }+ | { op: "splitClips"; clipIds: string[]; time: number }+ | { op: "mergeClips"; clipIds: string[] }+ | { op: "removeClips"; clipIds: string[] }+ | { op: "updateClip"; clipId: string; patch: ClipPatch }+ | { op: "setClipSpeed"; clipId: string; speed: number }+ | {+ op: "setClipTransform";+ clipId: string;+ scale?: number;+ offsetX?: number;+ offsetY?: number;+ rotation?: number;+ }+ | { op: "detachAudio"; clipId: string }+ | { op: "reattachAudio"; clipId: string }+ | { op: "addTrack" }+ | { op: "removeTrack"; trackId: string }+ | { op: "renameTrack"; trackId: string; name: string }+ | { op: "setTrackFlag"; trackId: string; flag: "visible" | "muted"; value: boolean }+ | { op: "addTimeline" }+ | { op: "removeTimeline"; timelineId: string }+ | { op: "renameTimeline"; timelineId: string; name: string }+ | { op: "selectTimeline"; timelineId: string }+ | { op: "addFont"; family: string; path: string }+ | { op: "removeFont"; family: string };++// ── selectors ────────────────────────────────────────────────────────────────++export function activeTimeline(project: EditorProject): TimelineData {+ return (+ project.timelines.find((timeline) => timeline.id === project.activeTimelineId) ??+ project.timelines[0]+ );+}++export function findClip(project: EditorProject, clipId: string): Clip | null {+ return activeTimeline(project).clips.find((clip) => clip.id === clipId) ?? null;+}++export function findTrack(project: EditorProject, trackId: string): Track | null {+ return activeTimeline(project).tracks.find((track) => track.id === trackId) ?? null;+}++export function findMedia(project: EditorProject, mediaId: string): MediaItem | null {+ return project.media.find((item) => item.id === mediaId) ?? null;+}++/** Where the last clip of the active timeline ends. */+export function projectDuration(project: EditorProject): number {+ return activeTimeline(project).clips.reduce(+ (end, clip) => Math.max(end, clip.start + clip.duration),+ 0,+ );+}++/** Clips under the playhead on tracks that are not disabled. */+export function clipsAt(project: EditorProject, time: number): Clip[] {+ const timeline = activeTimeline(project);+ return timeline.clips.filter((clip) => {+ const track = timeline.tracks.find((candidate) => candidate.id === clip.trackId);+ if (!track) return false;+ if (clip.kind !== "audio" && !track.visible) return false;+ if (clip.kind === "audio" && track.muted) return false;+ return time >= clip.start && time < clip.start + clip.duration;+ });+}++/** The audio clips holding sound detached from this video clip, if any. */+export function detachedAudioOf(project: EditorProject, videoClipId: string): Clip[] {+ return activeTimeline(project).clips.filter((clip) => clip.detachedFrom === videoClipId);+}++/**+ * The clip that ends exactly where this one starts, on the same track - what+ * a transition needs to exist. Whole-frame tolerance, matching the engine's+ * exporter-side adjacency test.+ */+export function precedingClip(project: EditorProject, clipId: string): Clip | null {+ const timeline = activeTimeline(project);+ const clip = timeline.clips.find((candidate) => candidate.id === clipId);+ if (!clip) return null;+ return (+ timeline.clips.find(+ (other) =>+ other.id !== clip.id &&+ other.trackId === clip.trackId &&+ other.kind !== "audio" &&+ Math.abs(other.start + other.duration - clip.start) < 1 / 60,+ ) ?? null+ );+}++/** How many clips a timeline holds. For the delete prompt. */+export function timelineClipCount(project: EditorProject, timelineId: string): number {+ return project.timelines.find((timeline) => timeline.id === timelineId)?.clips.length ?? 0;+}++const JOIN_EPSILON = 1e-6;++/**+ * Why these clips cannot be merged, or null if they can - the UI's read-only+ * twin of the engine's own check, for the disabled button's tooltip. The+ * engine re-validates on the command; this only phrases the reason early.+ */+export function whyNotMerge(project: EditorProject, clipIds: readonly string[]): string | null {+ if (clipIds.length < 2) return "Select two or more clips to merge.";+ const timeline = activeTimeline(project);+ const clips = clipIds.flatMap((id) => {+ const clip = timeline.clips.find((candidate) => candidate.id === id);+ return clip ? [clip] : [];+ });+ if (clips.length < 2) return "Select two or more clips to merge.";+ if (clips.some((clip) => clip.trackId !== clips[0].trackId)) {+ return "Merged clips must be on the same track.";+ }+ if (clips.some((clip) => clip.mediaId !== clips[0].mediaId)) {+ return "Merged clips must come from the same file.";+ }+ if (clips.some((clip) => clip.speed !== clips[0].speed)) {+ return "Merged clips must play at the same speed.";+ }+ const ordered = [...clips].sort((left, right) => left.start - right.start);+ for (let index = 1; index < ordered.length; index += 1) {+ const previous = ordered[index - 1];+ const current = ordered[index];+ if (Math.abs(current.start - (previous.start + previous.duration)) > JOIN_EPSILON) {+ return "Merged clips must touch, with no gap or overlap.";+ }+ if (+ Math.abs(+ current.sourceStart - (previous.sourceStart + previous.duration * previous.speed),+ ) > JOIN_EPSILON+ ) {+ return "These pieces are no longer in their original order.";+ }+ }+ return null;+}++/**+ * The nearest interesting time to `time`, within `threshold` seconds. Pure+ * view logic: snapping decides what the gesture *proposes*, the engine only+ * ever sees the snapped result.+ */+export function snapTime(+ project: EditorProject,+ time: number,+ { threshold, playhead, exclude }: { threshold: number; playhead: number; exclude?: string },+): number {+ const targets = [0, playhead];+ for (const clip of activeTimeline(project).clips) {+ if (clip.id === exclude) continue;+ targets.push(clip.start, clip.start + clip.duration);+ }+ let best = time;+ let bestDistance = threshold;+ for (const target of targets) {+ const distance = Math.abs(target - time);+ if (distance < bestDistance) {+ best = target;+ bestDistance = distance;+ }+ }+ return best;+}++// ── the gesture echo ─────────────────────────────────────────────────────────++/** Transient per-clip patches shown during a gesture, keyed by clip id. */+export type Echo = Record<string, Partial<Clip>>;++/** The project as the monitor and timeline should draw it mid-gesture. */+export function withEcho(project: EditorProject, echo: Echo | null): EditorProject {+ if (!echo || Object.keys(echo).length === 0) return project;+ return {+ ...project,+ timelines: project.timelines.map((timeline) =>+ timeline.id === project.activeTimelineId+ ? {+ ...timeline,+ clips: timeline.clips.map((clip) =>+ echo[clip.id] ? { ...clip, ...echo[clip.id] } : clip,+ ),+ }+ : timeline,+ ),+ };+}++const MIN_CLIP_DURATION = 1 / 60;++/** The trim arithmetic, identical to the engine's, for the live echo. */+export function trimPatch(clip: Clip, edge: "start" | "end", delta: number): Partial<Clip> {+ if (edge === "end") {+ return { duration: Math.max(MIN_CLIP_DURATION, clip.duration + delta) };+ }+ const shift = Math.min(delta, clip.duration - MIN_CLIP_DURATION);+ const start = Math.max(0, clip.start + shift);+ const applied = start - clip.start;+ return {+ start,+ duration: clip.duration - applied,+ sourceStart: Math.max(0, clip.sourceStart + applied * clip.speed),+ };+}++/** The speed arithmetic, identical to the engine's, for the live echo. */+export function speedPatch(clip: Clip, speed: number): Partial<Clip> {+ const next = Math.max(0.0625, Math.min(16, speed));+ const sourceCovered = clip.duration * clip.speed;+ return { speed: next, duration: Math.max(MIN_CLIP_DURATION, sourceCovered / next) };+}++/** The transform clamps, identical to the engine's, for the live echo. */+export function transformPatch(+ patch: Partial<Pick<Clip, "scale" | "offsetX" | "offsetY" | "rotation">>,+): Partial<Clip> {+ const clamped: Partial<Clip> = {};+ if (patch.scale !== undefined) clamped.scale = Math.max(0.05, Math.min(8, patch.scale));+ if (patch.offsetX !== undefined) clamped.offsetX = Math.max(-3, Math.min(3, patch.offsetX));+ if (patch.offsetY !== undefined) clamped.offsetY = Math.max(-3, Math.min(3, patch.offsetY));+ if (patch.rotation !== undefined) {+ const wrapped = ((patch.rotation % 360) + 540) % 360 - 180;+ clamped.rotation = wrapped === -180 ? 180 : wrapped;+ }+ return clamped;+}++/**+ * Turns one clip's accumulated echo into the command(s) that make it real.+ *+ * A gesture touches one family of fields, so this usually yields exactly one+ * command; the ordering (speed, then transform, then move/trim, then the+ * patch) only matters for mixed accumulations from a busy panel.+ */+export function commandsForEcho(base: Clip, patch: Partial<Clip>): EditorCommand[] {+ const commands: EditorCommand[] = [];+ const has = (key: keyof Clip) => key in patch;++ if (has("speed") && patch.speed !== undefined) {+ commands.push({ op: "setClipSpeed", clipId: base.id, speed: patch.speed });+ }++ if (has("scale") || has("offsetX") || has("offsetY") || has("rotation")) {+ commands.push({+ op: "setClipTransform",+ clipId: base.id,+ ...(has("scale") ? { scale: patch.scale } : {}),+ ...(has("offsetX") ? { offsetX: patch.offsetX } : {}),+ ...(has("offsetY") ? { offsetY: patch.offsetY } : {}),+ ...(has("rotation") ? { rotation: patch.rotation } : {}),+ });+ }++ const durationChanged =+ !has("speed") && has("duration") && patch.duration !== undefined+ ? patch.duration !== base.duration+ : false;+ const startChanged = has("start") && patch.start !== undefined && patch.start !== base.start;++ if (durationChanged && startChanged) {+ commands.push({+ op: "trimClip",+ clipId: base.id,+ edge: "start",+ delta: (patch.start ?? base.start) - base.start,+ });+ } else if (durationChanged) {+ commands.push({+ op: "trimClip",+ clipId: base.id,+ edge: "end",+ delta: (patch.duration ?? base.duration) - base.duration,+ });+ } else if (startChanged || has("trackId")) {+ commands.push({+ op: "moveClips",+ moves: [+ {+ clipId: base.id,+ start: patch.start ?? base.start,+ trackId: patch.trackId ?? base.trackId,+ },+ ],+ });+ }++ const update: ClipPatch = {};+ if (has("name") && patch.name !== undefined) update.name = patch.name;+ if (has("volume") && patch.volume !== undefined) update.volume = patch.volume;+ if (has("fadeIn") && patch.fadeIn !== undefined) update.fadeIn = patch.fadeIn;+ if (has("fadeOut") && patch.fadeOut !== undefined) update.fadeOut = patch.fadeOut;+ if (has("opacity") && patch.opacity !== undefined) update.opacity = patch.opacity;+ if (has("preservePitch") && patch.preservePitch !== undefined) {+ update.preservePitch = patch.preservePitch;+ }+ if (has("filters") && patch.filters !== undefined) update.filters = patch.filters;+ if (has("videoEffects") && patch.videoEffects !== undefined) {+ update.videoEffects = patch.videoEffects;+ }+ // Key present with undefined means "clear" for the two clearable fields.+ if (has("transitionIn")) update.transitionIn = patch.transitionIn ?? null;+ if (has("text")) update.text = patch.text ?? null;+ if (Object.keys(update).length > 0) {+ commands.push({ op: "updateClip", clipId: base.id, patch: update });+ }++ return commands;+}diff --git a/desktop/src/lib/engine.ts b/desktop/src/lib/engine.tsindex 8fd2d91b..76795593 100644--- a/desktop/src/lib/engine.ts+++ b/desktop/src/lib/engine.ts@@ -11,6 +11,8 @@import { invoke } from "@tauri-apps/api/core";import { listen, type UnlistenFn } from "@tauri-apps/api/event";+import type { EditorCommand, EditorView } from "./editor";+export interface VideoStreamInfo {index: number;codec: string;@@ -95,14 +97,52 @@ export async function openProject(path: string): Promise<ProjectInfo> {return invoke<ProjectInfo>("open_project", { path });}-/** Writes the whole project document to the project folder. */-export async function saveProject(path: string, document: unknown): Promise<void> {- return invoke<void>("save_project", { path, document });+// ── the editing session ────────────────────────────────────────────────────+// The engine owns the edit (see engine decision 0007): the UI opens a+// session, sends commands, and renders the state that comes back.++/** Opens a project folder as the engine's editing session. */+export async function editorOpen(session: {+ path: string;+ name: string;+ width: number;+ height: number;+ rateNum: number;+ rateDen: number;+}): Promise<EditorView> {+ return invoke<EditorView>("editor_open", session);+}++/** Applies one edit command; the returned state is the truth. */+export async function editorApply(command: EditorCommand): Promise<EditorView> {+ return invoke<EditorView>("editor_apply", { command });+}++export async function editorUndo(): Promise<EditorView> {+ return invoke<EditorView>("editor_undo");+}++export async function editorRedo(): Promise<EditorView> {+ return invoke<EditorView>("editor_redo");+}++/** The current state, without changing anything. */+export async function editorState(): Promise<EditorView> {+ return invoke<EditorView>("editor_state");+}++/** Writes the session's document to disk. The output size rides along+ * because the preview footer can edit it. */+export async function editorSave(frame?: { width: number; height: number }): Promise<void> {+ return invoke<void>("editor_save", {+ width: frame?.width ?? null,+ height: frame?.height ?? null,+ });}-/** Reads the whole project document back. */-export async function loadProject(path: string): Promise<unknown> {- return invoke<unknown>("load_project", { path });+/** Closes the session, dropping its undo history. */+export async function editorClose(): Promise<void> {+ return invoke<void>("editor_close");}/** Recently opened projects, newest first, with vanished folders left out. */diff --git a/desktop/src/lib/persist.ts b/desktop/src/lib/persist.tsdeleted file mode 100644index 81247437..00000000--- a/desktop/src/lib/persist.ts+++ /dev/null@@ -1,356 +0,0 @@-/**- * Reading and writing the project document.- *- * The document is the file on disk. It is deliberately *not* the same shape as- * the in-memory `Project`: loading fills in anything a file predates, so a- * project saved before a feature existed still opens instead of arriving with- * `undefined` where a number should be.- *- * That tolerance is the whole job of this module. Everything else is a- * one-to-one copy.- */--import type { ProjectSession } from "../components/StartScreen";-import { adoptProject, type Clip, type ClipKind, type MediaItem, type Project, type Track } from "./project";-import { defaultTextStyle, type CustomFont, type TextStyle } from "./text";--/** Bumped only when a change cannot be absorbed by defaulting. */-const DOCUMENT_VERSION = 1;--/** One timeline, as the file stores it. */-export interface TimelineDocument {- id: string;- name: string;- tracks: Track[];- clips: Clip[];-}--export interface ProjectDocument {- relay: string;- version: number;- name: string;- video: { width: number; height: number; rateNum: number; rateDen: number };- media: MediaItem[];- /**- * The ACTIVE timeline's lanes and clips, duplicated out of `timelines`.- *- * Deliberate redundancy: a build that predates multiple timelines reads- * exactly these two fields, so a new document still opens there - showing- * the timeline that was active, which is the least surprising slice of the- * project to survive a downgrade.- */- tracks: Track[];- clips: Clip[];- fonts: CustomFont[];- /** Every timeline, in tab order. The source of truth on load. */- timelines: TimelineDocument[];- activeTimelineId: string;-}--export function toDocument(session: ProjectSession, project: Project): ProjectDocument {- return {- relay: "0.1.0",- version: DOCUMENT_VERSION,- name: session.name,- video: {- width: session.width,- height: session.height,- rateNum: session.rateNum,- rateDen: session.rateDen,- },- media: project.media,- tracks: project.tracks,- clips: project.clips,- fonts: project.fonts,- timelines: project.timelines.map((meta) => {- const content =- meta.id === project.activeTimelineId- ? { tracks: project.tracks, clips: project.clips }- : (project.shelved[meta.id] ?? { tracks: [], clips: [] });- return { id: meta.id, name: meta.name, tracks: content.tracks, clips: content.clips };- }),- activeTimelineId: project.activeTimelineId,- };-}--const number = (value: unknown, fallback: number): number =>- typeof value === "number" && Number.isFinite(value) ? value : fallback;--const text = (value: unknown, fallback: string): string =>- typeof value === "string" ? value : fallback;--const flag = (value: unknown, fallback: boolean): boolean =>- typeof value === "boolean" ? value : fallback;--/**- * Rebuilds a project from a document.- *- * Every field is defaulted rather than trusted. A hand-edited or older file- * should degrade to something openable, not produce a timeline full of `NaN`- * that fails somewhere far away from the cause.- *- * Returns null only when there is nothing recognisable to load at all.- */-export function fromDocument(raw: unknown): Project | null {- if (typeof raw !== "object" || raw === null) return null;- const document = raw as Record<string, unknown>;-- const media: MediaItem[] = Array.isArray(document.media)- ? document.media.flatMap((entry) => {- if (typeof entry !== "object" || entry === null) return [];- const item = entry as Record<string, unknown>;- if (typeof item.id !== "string" || typeof item.path !== "string") return [];-- const kind = item.kind === "audio" || item.kind === "image" ? item.kind : "video";- return [- {- id: item.id,- path: item.path,- name: text(item.name, item.path),- duration: typeof item.duration === "number" ? item.duration : null,- kind,- width: typeof item.width === "number" ? item.width : null,- height: typeof item.height === "number" ? item.height : null,- frameRate: typeof item.frameRate === "number" ? item.frameRate : null,- frameRateFraction:- typeof item.frameRateFraction === "string" ? item.frameRateFraction : null,- videoCodec: typeof item.videoCodec === "string" ? item.videoCodec : null,- audioCodec: typeof item.audioCodec === "string" ? item.audioCodec : null,- hasAudio: flag(item.hasAudio, false),- },- ];- })- : [];-- const mediaIds = new Set(media.map((item) => item.id));-- const readTracks = (raw: unknown): Track[] =>- Array.isArray(raw)- ? raw.flatMap((entry) => {- if (typeof entry !== "object" || entry === null) return [];- const track = entry as Record<string, unknown>;- if (typeof track.id !== "string") return [];- return [- {- id: track.id,- name: text(track.name, track.id),- visible: flag(track.visible, true),- muted: flag(track.muted, false),- },- ];- })- : [];-- const readClips = (raw: unknown, known: Set<string>): Clip[] =>- Array.isArray(raw)- ? raw.flatMap((entry) => {- if (typeof entry !== "object" || entry === null) return [];- const clip = entry as Record<string, unknown>;- if (typeof clip.id !== "string") return [];-- // A clip whose track or media vanished has nowhere to live and nothing- // to play. Dropping it beats keeping a reference that resolves to- // nothing everywhere it is used.- if (typeof clip.trackId !== "string" || !known.has(clip.trackId)) return [];-- // A text clip is its own content, so it has no media to resolve. Only- // the kinds that come from the bin are dropped when their source is- // gone - applying that rule to titles would delete every one of them- // on reload, because an empty id is never in the media set.- const isText = clip.kind === "text";- if (!isText && (typeof clip.mediaId !== "string" || !mediaIds.has(clip.mediaId))) {- return [];- }-- const kind: ClipKind = isText- ? "text"- : clip.kind === "audio" || clip.kind === "image"- ? clip.kind- : "video";- return [- {- id: clip.id,- trackId: clip.trackId,- mediaId: isText ? "" : (clip.mediaId as string),- name: text(clip.name, "clip"),- kind,- start: Math.max(0, number(clip.start, 0)),- duration: Math.max(0.01, number(clip.duration, 1)),- sourceStart: Math.max(0, number(clip.sourceStart, 0)),- volume: Math.max(0, number(clip.volume, 1)),- fadeIn: Math.max(0, number(clip.fadeIn, 0)),- fadeOut: Math.max(0, number(clip.fadeOut, 0)),- scale: Math.max(0.05, number(clip.scale, 1)),- offsetX: number(clip.offsetX, 0),- offsetY: number(clip.offsetY, 0),- rotation: number(clip.rotation, 0),- // Clamped, not just defaulted: a hand-edited 2 would export- // differently from how the preview clamps it on screen.- opacity: Math.min(1, Math.max(0, number(clip.opacity, 1))),- speed: Math.max(0.0625, Math.min(16, number(clip.speed, 1))),- preservePitch: flag(clip.preservePitch, true),- muted: flag(clip.muted, false) || undefined,- detachedFrom: typeof clip.detachedFrom === "string" ? clip.detachedFrom : undefined,- filters: Array.isArray(clip.filters)- ? clip.filters.flatMap((filter) => {- if (typeof filter !== "object" || filter === null) return [];- const applied = filter as Record<string, unknown>;- if (typeof applied.id !== "string") return [];- return [- {- id: applied.id,- params:- typeof applied.params === "object" && applied.params !== null- ? (applied.params as Record<string, number>)- : {},- // Absent in files saved before bypass existed: enabled.- enabled: flag(applied.enabled, true),- },- ];- })- : [],- videoEffects: Array.isArray(clip.videoEffects)- ? clip.videoEffects.flatMap((effect) => {- if (typeof effect !== "object" || effect === null) return [];- const applied = effect as Record<string, unknown>;- if (typeof applied.id !== "string") return [];- return [- {- id: applied.id,- params:- typeof applied.params === "object" && applied.params !== null- ? (applied.params as Record<string, number>)- : {},- enabled: flag(applied.enabled, true),- },- ];- })- : [],- transitionIn: (() => {- if (typeof clip.transitionIn !== "object" || clip.transitionIn === null) {- return undefined;- }- const transition = clip.transitionIn as Record<string, unknown>;- if (typeof transition.id !== "string") return undefined;- return {- id: transition.id,- duration: Math.max(0.1, number(transition.duration, 1)),- };- })(),- ...(isText ? { text: readTextStyle(clip.text) } : {}),- },- ];- })- : [];-- const fonts: CustomFont[] = Array.isArray(document.fonts)- ? document.fonts.flatMap((entry) => {- if (typeof entry !== "object" || entry === null) return [];- const font = entry as Record<string, unknown>;- if (typeof font.family !== "string" || typeof font.path !== "string") return [];- return [{ family: font.family, path: font.path }];- })- : [];-- // The `timelines` array is the source of truth when it is present and- // usable; a file from before multiple timelines existed has only the flat- // tracks/clips, which load as the single timeline they always were.- interface ParsedTimeline {- id: string;- name: string;- tracks: Track[];- clips: Clip[];- }- const parsed: ParsedTimeline[] = [];- if (Array.isArray(document.timelines)) {- for (const entry of document.timelines) {- if (typeof entry !== "object" || entry === null) continue;- const timeline = entry as Record<string, unknown>;- if (typeof timeline.id !== "string") continue;- // A second timeline with the same id could only come from a hand-edited- // file; keeping the first is the same rule the id re-mint applies.- if (parsed.some((existing) => existing.id === timeline.id)) continue;- const timelineTracks = readTracks(timeline.tracks);- // A timeline with no lanes has nowhere to put anything; skip it rather- // than open a dead tab.- if (timelineTracks.length === 0) continue;- parsed.push({- id: timeline.id,- name: text(timeline.name, "Timeline"),- tracks: timelineTracks,- clips: readClips(timeline.clips, new Set(timelineTracks.map((track) => track.id))),- });- }- }- if (parsed.length === 0) {- const tracks = readTracks(document.tracks);- // A file with no tracks at all is not something to open silently as empty.- if (tracks.length === 0) return null;- parsed.push({- id: "TL1",- name: "Timeline 1",- tracks,- clips: readClips(document.clips, new Set(tracks.map((track) => track.id))),- });- }-- const activeId =- typeof document.activeTimelineId === "string" &&- parsed.some((timeline) => timeline.id === document.activeTimelineId)- ? document.activeTimelineId- : parsed[0].id;- const active = parsed.find((timeline) => timeline.id === activeId) ?? parsed[0];-- const shelved: Record<string, { tracks: Track[]; clips: Clip[] }> = {};- for (const timeline of parsed) {- if (timeline.id !== active.id) {- shelved[timeline.id] = { tracks: timeline.tracks, clips: timeline.clips };- }- }-- // The restored ids were minted by an earlier session; the counter must move- // past them - and any baked-in duplicates must be re-minted - before- // anything new is added, or identities collide.- return adoptProject({- media,- fonts,- tracks: active.tracks,- clips: active.clips,- timelines: parsed.map((timeline) => ({ id: timeline.id, name: timeline.name })),- activeTimelineId: active.id,- shelved,- });-}--/**- * Rebuilds a text style, defaulting every field.- *- * Same tolerance as the rest of this module: a title saved before a styling- * option existed opens with that option at its default rather than- * `undefined`, which would otherwise reach the CSS and render as nothing.- */-function readTextStyle(raw: unknown): TextStyle {- const base = defaultTextStyle();- if (typeof raw !== "object" || raw === null) return base;- const style = raw as Record<string, unknown>;-- const align = style.align;- return {- content: text(style.content, base.content),- fontFamily: text(style.fontFamily, base.fontFamily),- // Clamped, not just defaulted: a hand-edited 0 would render an invisible- // title, and a 10 would be one letter filling the frame.- fontSize: Math.min(1, Math.max(0.01, number(style.fontSize, base.fontSize))),- fontWeight: Math.min(900, Math.max(100, number(style.fontWeight, base.fontWeight))),- italic: flag(style.italic, base.italic),- color: text(style.color, base.color),- align: align === "left" || align === "center" || align === "right" ? align : base.align,- opacity: Math.min(1, Math.max(0, number(style.opacity, base.opacity))),- strokeWidth: Math.max(0, number(style.strokeWidth, base.strokeWidth)),- strokeColor: text(style.strokeColor, base.strokeColor),- shadow: flag(style.shadow, base.shadow),- background: text(style.background, base.background),- lineHeight: Math.max(0.5, number(style.lineHeight, base.lineHeight)),- tracking: number(style.tracking, base.tracking),- };-}diff --git a/desktop/src/lib/project.ts b/desktop/src/lib/project.tsdeleted file mode 100644index 843e427f..00000000--- a/desktop/src/lib/project.ts+++ /dev/null@@ -1,1204 +0,0 @@-/**- * The prototype's edit model.- *- * A note on where this lives: the engine is the eventual owner of the timeline,- * and `relay-core` already has a far better version of these types (exact- * rational time, arena handles, generational IDs). This module exists because- * the engine has no project *API* yet - no commands, no undo, no- * serialisation - and the UI needs something to draw.- *- * So this is explicitly provisional. Two rules keep the eventual migration- * cheap, and both are worth honouring:- *- * 1. Every operation is a pure function `(project, args) => project`. That is- * the same shape a command sent to the engine will have, so the call sites- * do not change when the implementation moves.- * 2. No component mutates a project. They call these functions.- *- * Times are seconds as JS numbers, which is a real downgrade from the engine's- * exact rationals. Acceptable while nothing here is authoritative; not- * acceptable once it is. See docs/decisions/0004.- */--import type { AppliedEffect, ClipTransition } from "./effects";-import type { MediaSummary } from "./engine";-import type { ClipFilter } from "./filters";-import { defaultTextStyle, type CustomFont, type TextStyle } from "./text";--/**- * What a piece of media is.- *- * A still is not a video with one frame: it has no intrinsic duration, so how- * long it lasts on the timeline is an editorial choice rather than a property- * of the file. Everything downstream of that difference - the default clip- * length, how it is previewed, how it is decoded on export - follows from- * keeping the two apart.- */-export type MediaKind = "video" | "audio" | "image";--/** Kept as an alias so existing call sites read naturally. */-export type TrackKind = MediaKind;--/**- * What a clip can be.- *- * Wider than `MediaKind` because a text clip has no file behind it - it *is*- * its own content. That is the whole reason for the distinction: everything in- * the bin is a `MediaKind`, but not everything on the timeline came from the- * bin. A text clip carries `mediaId: ""` and a `text` style instead.- */-export type ClipKind = MediaKind | "text";--export interface MediaItem {- id: string;- path: string;- name: string;- /** Seconds. Null when the container did not say. */- duration: number | null;- kind: TrackKind;- width: number | null;- height: number | null;- frameRate: number | null;- /** The exact fraction the engine works in, e.g. "30000/1001". */- frameRateFraction: string | null;- videoCodec: string | null;- audioCodec: string | null;- hasAudio: boolean;-}--/**- * A lane. Deliberately untyped: any media goes on any track.- *- * Typed video/audio lanes are an assumption inherited from tape, and they cost- * you every time an mp3 belongs next to a cutaway or a clip needs to move down- * one row. A clip knows what it is; a track does not need to.- *- * Both flags therefore exist on every track, because one track can carry- * picture and sound at the same time.- */-export interface Track {- id: string;- name: string;- /** Video clips on this track are left out of the composite when false. */- visible: boolean;- /** Audio on this track is silent when true. */- muted: boolean;-}--export interface Clip {- id: string;- trackId: string;- mediaId: string;- /** Empty for a text clip, which has no file behind it. */- name: string;- kind: ClipKind;- /** Seconds from the start of the timeline. */- start: number;- duration: number;- /** In-point: how far into the media the clip starts. */- sourceStart: number;-- /**- * Linear gain, 1 being unity. Above 1 is a boost.- *- * Linear rather than decibels because that is what both the audio element- * and ffmpeg's `volume` filter take; the UI converts for display.- */- volume: number;- /** Fade-in length in seconds. Zero means no fade. */- fadeIn: number;- /** Fade-out length in seconds. Zero means no fade. */- fadeOut: number;-- /**- * How big the picture is drawn, where 1 fills the frame.- *- * "Fills the frame" means the size the clip would be with no transform at- * all - fitted to the project's frame, preserving its aspect. Everything is- * relative to that, so a transform means the same thing on a 4K clip and a- * 720p one.- */- scale: number;- /** Offset from centred, as a fraction of frame width. */- offsetX: number;- /** Offset from centred, as a fraction of frame height. */- offsetY: number;- /** Clockwise rotation in degrees, about the picture's centre. */- rotation: number;- /**- * Blend strength over whatever is beneath, in `0..1`. One is solid.- *- * The picture-side sibling of `volume`: the preview applies it as CSS- * opacity and the exporter hands it to the compositor, both reading this- * one number.- */- opacity: number;-- /**- * Playback rate. 1 is normal, 2 is twice as fast.- *- * Changing it rescales the clip's timeline duration, because the same span- * of source now takes a different amount of time to play. That is what every- * editor does and what people expect from a speed control.- */- speed: number;- /**- * Whether pitch stays put when the speed changes.- *- * True is the modern default - time-stretching that leaves the voice where- * it was. False is the tape behaviour, where faster also means higher.- */- preservePitch: boolean;-- /**- * Audio filters, applied in order.- *- * An array rather than a set because order is audible: an EQ before a- * limiter is a different sound from the reverse.- */- filters: ClipFilter[];-- /**- * Video effects, applied in order. The visual sibling of `filters`: one- * FFmpeg chain built in `lib/effects.ts`, run by the exporter at decode.- */- videoEffects: AppliedEffect[];-- /**- * The transition on the cut *into* this clip, if any.- *- * On the incoming clip rather than in a separate table because a transition- * has no life of its own: it exists exactly as long as this clip starts- * where another one ends. Moving the clips apart orphans it, and an- * orphaned transition renders as a plain cut rather than an error.- */- transitionIn?: ClipTransition;-- /**- * True when this video clip's embedded audio is left out of preview and- * export - the state "Detach audio" puts it in. Meaningless on other kinds.- */- muted?: boolean;-- /**- * On a detached audio clip: the id of the video clip the sound came from.- * The link is what makes "Reattach audio" possible from either side.- */- detachedFrom?: string;-- /**- * The overlay, when this is a text clip. Absent on every other kind.- *- * On the clip rather than in the bin because two titles are two different- * pieces of content even when they share a face - there is no shared source- * to point at, so there is nothing to put in the bin.- */- text?: TextStyle;-}--/**- * One timeline's identity. The content lives either at the top of the project- * (the active timeline) or in `shelved` (everything else) - see `Project`.- */-export interface TimelineMeta {- id: string;- name: string;-}--/** The parked content of an inactive timeline. */-export interface ShelvedTimeline {- tracks: Track[];- clips: Clip[];-}--export interface Project {- media: MediaItem[];- /** The ACTIVE timeline's lanes. */- tracks: Track[];- /** The ACTIVE timeline's clips. */- clips: Clip[];- /**- * Font files the user added, by path.- *- * On the project rather than in app settings because a title's face is part- * of the edit: opening the project has to bring the font back with it, or- * the composition silently changes.- */- fonts: CustomFont[];- /**- * Every timeline in the project, in tab order. Always at least one, and- * always includes the active one.- *- * The active timeline's tracks and clips live at the top of the project -- * exactly where they always did - and only *inactive* timelines keep their- * content in `shelved`. That invariant is the whole design: every edit- * operation in this file, and every reader from the draw loop to the- * exporter, already works on `project.tracks`/`project.clips`, so "which- * timeline am I editing" is decided in exactly one place (the switch) and- * nowhere else has to know timelines exist.- */- timelines: TimelineMeta[];- activeTimelineId: string;- /** Content of every inactive timeline, by timeline id. Never the active one. */- shelved: Record<string, ShelvedTimeline>;-}--/** Fallback length for media whose container reports no duration. */-const UNKNOWN_DURATION = 5;-/** How long a still lasts when first placed. Editorial default, not a fact. */-export const DEFAULT_IMAGE_DURATION = 5;-const MIN_CLIP_DURATION = 1 / 60;--let counter = 0;-const nextId = (prefix: string) => `${prefix}${(counter += 1)}`;--/**- * Makes a restored project safe to mint new ids against.- *- * Ids come from a session-local counter, but a restored project carries ids- * minted by an *earlier* session, and the counter starts back at zero on- * every launch. Without this, the first thing added after opening a saved- * project reuses an id that is already on the timeline - two clips with one- * identity. React renders the duplicate keys as a single element (one clip- * silently vanishes) and `updateClip` patches both (a title's text style- * lands on the footage it collided with).- *- * Two steps, in this order:- *- * 1. Advance the counter past every id the file uses.- * 2. Re-mint any id that appears twice - a file saved *while* the collision- * was live has the duplicates baked in, and they must not survive the- * reload. The first occurrence keeps the id, because that is the one- * every lookup already resolved to; references to a re-minted duplicate- * therefore keep meaning what they always did.- *- * Every restore path must run its project through this before anything new- * can be added.- */-export function adoptProject(project: Project): Project {- let highest = 0;- const consider = (id: string) => {- const digits = /(\d+)$/.exec(id)?.[1];- if (!digits) return;- const value = Number.parseInt(digits, 10);- if (Number.isFinite(value) && value > highest) highest = value;- };- for (const item of project.media) consider(item.id);- for (const track of project.tracks) consider(track.id);- for (const clip of project.clips) consider(clip.id);- for (const meta of project.timelines) consider(meta.id);- for (const shelf of Object.values(project.shelved)) {- for (const track of shelf.tracks) consider(track.id);- for (const clip of shelf.clips) consider(clip.id);- }- if (highest > counter) counter = highest;-- const reMint = <T extends { id: string }>(items: T[], prefix: string, seen: Set<string>): T[] =>- items.map((item) => {- if (!seen.has(item.id)) {- seen.add(item.id);- return item;- }- return { ...item, id: nextId(prefix) };- });-- // Track and clip ids must be unique across *every* timeline, not just within- // one - the shared sets are what catches a duplicate that spans two. The- // active timeline goes first, so on a collision it is the shelved copy that- // gets re-minted, never the one on screen.- const seenTracks = new Set<string>();- const seenClips = new Set<string>();- const active = {- tracks: reMint(project.tracks, "t", seenTracks),- clips: reMint(project.clips, "c", seenClips),- };- const shelved: Record<string, ShelvedTimeline> = {};- for (const [timelineId, shelf] of Object.entries(project.shelved)) {- shelved[timelineId] = {- tracks: reMint(shelf.tracks, "t", seenTracks),- clips: reMint(shelf.clips, "c", seenClips),- };- }-- return {- ...project,- media: reMint(project.media, "m", new Set()),- timelines: reMint(project.timelines, "tl", new Set()),- tracks: active.tracks,- clips: active.clips,- shelved,- };-}--/** A project with one timeline of four empty lanes. */-export function createProject(): Project {- return {- media: [],- fonts: [],- // Bottom-most first, matching the engine's compositing order, so track 1- // sits at the bottom of the screen the way it does in every other editor.- tracks: [1, 2, 3, 4].map((number) => ({- id: `T${number}`,- name: `Track ${number}`,- visible: true,- muted: false,- })),- clips: [],- timelines: [{ id: "TL1", name: "Timeline 1" }],- activeTimelineId: "TL1",- shelved: {},- };-}--/**- * Four fresh lanes for a brand-new timeline.- *- * Minted ids rather than the first timeline's static `T1..T4`: track ids must- * be unique across the whole project, or `adoptProject`'s duplicate sweep- * would re-mint one timeline's lanes and orphan every clip on them.- */-function freshLanes(): Track[] {- return [1, 2, 3, 4].map((number) => ({- id: nextId("t"),- name: `Track ${number}`,- visible: true,- muted: false,- }));-}--/**- * Adds a timeline and switches to it.- *- * Numbered from the highest number already in a timeline name, the same rule- * `addTrack` uses, so deleting Timeline 2 and adding another does not produce- * a second Timeline 3.- */-export function addTimeline(project: Project): { project: Project; timelineId: string } {- const highest = project.timelines.reduce((best, meta) => {- const number = Number.parseInt(meta.name.replace(/\D+/g, ""), 10);- return Number.isFinite(number) ? Math.max(best, number) : best;- }, 0);-- const meta: TimelineMeta = { id: nextId("tl"), name: `Timeline ${highest + 1}` };- return {- project: {- ...project,- timelines: [...project.timelines, meta],- shelved: {- ...project.shelved,- [project.activeTimelineId]: { tracks: project.tracks, clips: project.clips },- },- activeTimelineId: meta.id,- tracks: freshLanes(),- clips: [],- },- timelineId: meta.id,- };-}--/**- * Makes another timeline the one being edited.- *- * The current content is parked in `shelved` and the target's content becomes- * the project's tracks and clips - after which every operation in this file- * works on the new timeline without knowing a switch happened.- */-export function switchTimeline(project: Project, timelineId: string): Project {- if (timelineId === project.activeTimelineId) return project;- const target = project.shelved[timelineId];- if (!target || !project.timelines.some((meta) => meta.id === timelineId)) return project;-- const shelved = {- ...project.shelved,- [project.activeTimelineId]: { tracks: project.tracks, clips: project.clips },- };- delete shelved[timelineId];-- return {- ...project,- activeTimelineId: timelineId,- tracks: target.tracks,- clips: target.clips,- shelved,- };-}--/**- * Removes a timeline and everything on it.- *- * Refuses to remove the last one, the same rule as `removeTrack` and for the- * same reason: an editor with nowhere to put a clip is not a recoverable- * state. Deleting the active timeline switches to a neighbour first, so there- * is always something on screen afterwards.- */-export function removeTimeline(project: Project, timelineId: string): Project {- if (project.timelines.length <= 1) return project;- const index = project.timelines.findIndex((meta) => meta.id === timelineId);- if (index < 0) return project;-- let base = project;- if (timelineId === project.activeTimelineId) {- const neighbour = project.timelines[index + 1] ?? project.timelines[index - 1];- base = switchTimeline(project, neighbour.id);- }-- const shelved = { ...base.shelved };- delete shelved[timelineId];- return {- ...base,- timelines: base.timelines.filter((meta) => meta.id !== timelineId),- shelved,- };-}--/** Renames a timeline. An empty or whitespace-only name is ignored. */-export function renameTimeline(project: Project, timelineId: string, name: string): Project {- const trimmed = name.trim();- if (!trimmed) return project;- return {- ...project,- timelines: project.timelines.map((meta) =>- meta.id === timelineId ? { ...meta, name: trimmed } : meta,- ),- };-}--/** How many clips a timeline holds, active or shelved. For the delete prompt. */-export function timelineClipCount(project: Project, timelineId: string): number {- if (timelineId === project.activeTimelineId) return project.clips.length;- return project.shelved[timelineId]?.clips.length ?? 0;-}--/**- * Removes a bin item and every clip cut from it, on every timeline.- *- * All timelines, not just the active one: a shelved clip whose media is gone- * would linger as a dead reference until the next reload silently dropped it.- */-export function removeMediaEverywhere(project: Project, mediaId: string): Project {- const purge = (clips: Clip[]) => clips.filter((clip) => clip.mediaId !== mediaId);- const shelved: Record<string, ShelvedTimeline> = {};- for (const [timelineId, shelf] of Object.entries(project.shelved)) {- shelved[timelineId] = { tracks: shelf.tracks, clips: purge(shelf.clips) };- }- return {- ...project,- media: project.media.filter((item) => item.id !== mediaId),- clips: purge(project.clips),- shelved,- };-}--/** Turns a probe result into a bin item. */-export function toMediaItem(summary: MediaSummary): MediaItem {- const name = summary.path.split(/[\\/]/).pop() ?? summary.path;- return {- id: nextId("m"),- path: summary.path,- name,- duration: summary.duration,- kind: summary.kind,- width: summary.video?.width ?? null,- height: summary.video?.height ?? null,- frameRate: summary.video?.frameRate ?? null,- frameRateFraction: summary.video?.frameRateFraction ?? null,- videoCodec: summary.video?.codec ?? null,- audioCodec: summary.audio?.codec ?? null,- hasAudio: summary.audio !== null,- };-}--/** Adds media to the bin, ignoring a path that is already there. */-export function addMedia(project: Project, item: MediaItem): Project {- if (project.media.some((existing) => existing.path === item.path)) return project;- return { ...project, media: [...project.media, item] };-}--export function findMedia(project: Project, mediaId: string): MediaItem | null {- return project.media.find((item) => item.id === mediaId) ?? null;-}--export function findClip(project: Project, clipId: string): Clip | null {- return project.clips.find((clip) => clip.id === clipId) ?? null;-}--export function findTrack(project: Project, trackId: string): Track | null {- return project.tracks.find((track) => track.id === trackId) ?? null;-}--/**- * The lowest track with nothing already occupying `[start, start + duration)`,- * falling back to the bottom track.- *- * Used when material is added without being dropped somewhere specific, so- * repeatedly adding clips stacks them up the tracks instead of piling them all- * onto one lane on top of each other.- */-export function firstFreeTrack(project: Project, start: number, duration: number): Track | null {- const end = start + duration;- const free = project.tracks.find(- (track) =>- !project.clips.some(- (clip) =>- clip.trackId === track.id && clip.start < end && start < clip.start + clip.duration,- ),- );- return free ?? project.tracks[0] ?? null;-}--/** Places media on a track. Returns the project unchanged if either is unknown. */-export function addClip(- project: Project,- { mediaId, trackId, start }: { mediaId: string; trackId: string; start: number },-): { project: Project; clipId: string | null } {- const media = findMedia(project, mediaId);- const track = findTrack(project, trackId);- if (!media || !track) return { project, clipId: null };-- const clip: Clip = {- id: nextId("c"),- trackId,- mediaId,- name: media.name,- // The clip's kind comes from the media, never from the lane it lands on.- kind: media.kind,- start: Math.max(0, start),- duration:- media.kind === "image" ? DEFAULT_IMAGE_DURATION : (media.duration ?? UNKNOWN_DURATION),- sourceStart: 0,- volume: 1,- fadeIn: 0,- fadeOut: 0,- scale: 1,- offsetX: 0,- offsetY: 0,- rotation: 0,- opacity: 1,- speed: 1,- preservePitch: true,- filters: [],- videoEffects: [],- };-- return { project: { ...project, clips: [...project.clips, clip] }, clipId: clip.id };-}--/** How long a title lasts when first placed. Editorial default, not a fact. */-export const DEFAULT_TEXT_DURATION = 4;--/**- * Puts a title on the timeline.- *- * Unlike `addClip` this needs no media, which is the entire point: a text clip- * carries its own content, so there is nothing to import first. It still takes- * a track and a start so it behaves like any other clip once placed - it can- * be moved, trimmed, split and stacked with no special cases downstream.- */-export function addTextClip(- project: Project,- { trackId, start, style }: { trackId: string; start: number; style?: Partial<TextStyle> },-): { project: Project; clipId: string | null } {- const track = findTrack(project, trackId);- if (!track) return { project, clipId: null };-- const text: TextStyle = { ...defaultTextStyle(), ...style };-- const clip: Clip = {- id: nextId("c"),- trackId,- // No media to point at. Every consumer keys off `kind` rather than- // probing this, so an empty id is never dereferenced.- mediaId: "",- // The name follows the words, so the timeline reads like the title looks.- // It is snapshotted rather than derived so that renaming the clip and- // editing the text stay independent.- name: firstLine(text.content),- kind: "text",- start: Math.max(0, start),- duration: DEFAULT_TEXT_DURATION,- sourceStart: 0,- volume: 1,- fadeIn: 0,- fadeOut: 0,- scale: 1,- offsetX: 0,- offsetY: 0,- rotation: 0,- opacity: 1,- speed: 1,- preservePitch: true,- filters: [],- videoEffects: [],- text,- };-- return { project: { ...project, clips: [...project.clips, clip] }, clipId: clip.id };-}--/** A one-line label for a block of text, for the timeline and the bin. */-export function firstLine(content: string): string {- const line = content.split("\n").find((candidate) => candidate.trim() !== "");- return (line ?? "Text").trim().slice(0, 40) || "Text";-}--/** Registers a font file against the project, ignoring one already added. */-export function addFont(project: Project, font: CustomFont): Project {- if (project.fonts.some((existing) => existing.path === font.path)) return project;- return { ...project, fonts: [...project.fonts, font] };-}--/**- * Forgets a font.- *- * Clips already using it keep the family name: the face may come back when the- * file does, and silently rewriting a title's styling because a list entry was- * removed would be a worse surprise than a temporary fallback.- */-export function removeFont(project: Project, family: string): Project {- return { ...project, fonts: project.fonts.filter((font) => font.family !== family) };-}--/** Moves a clip in time, and optionally to another track of the same kind. */-export function moveClip(- project: Project,- clipId: string,- { start, trackId }: { start: number; trackId?: string },-): Project {- return {- ...project,- clips: project.clips.map((clip) => {- if (clip.id !== clipId) return clip;- // Any clip may sit on any track, so the only check is that it exists.- const target = trackId ? findTrack(project, trackId) : null;- return { ...clip, start: Math.max(0, start), trackId: target?.id ?? clip.trackId };- }),- };-}--/** Trims a clip from one edge, keeping the source content under the other. */-export function trimClip(- project: Project,- clipId: string,- edge: "start" | "end",- delta: number,-): Project {- return {- ...project,- clips: project.clips.map((clip) => {- if (clip.id !== clipId) return clip;- if (edge === "end") {- return { ...clip, duration: Math.max(MIN_CLIP_DURATION, clip.duration + delta) };- }- // Dragging the head moves the in-point too, so the pixels under the- // remaining part of the clip do not slide.- const shift = Math.min(delta, clip.duration - MIN_CLIP_DURATION);- const start = Math.max(0, clip.start + shift);- const applied = start - clip.start;- return {- ...clip,- start,- duration: clip.duration - applied,- // A timeline second covers `speed` source seconds, so the in-point- // moves that much further on a retimed clip.- sourceStart: Math.max(0, clip.sourceStart + applied * clip.speed),- };- }),- };-}--/** Where one clip is going. */-export interface ClipMove {- clipId: string;- start: number;- trackId: string;-}--/**- * Moves several clips at once.- *- * A single pass rather than repeated `moveClip` calls, so that a multi-clip- * drag is one new project object per frame instead of one per selected clip.- */-export function moveClips(project: Project, moves: ClipMove[]): Project {- if (moves.length === 0) return project;- const byId = new Map(moves.map((move) => [move.clipId, move]));-- return {- ...project,- clips: project.clips.map((clip) => {- const move = byId.get(clip.id);- if (!move) return clip;- const target = findTrack(project, move.trackId);- return { ...clip, start: Math.max(0, move.start), trackId: target?.id ?? clip.trackId };- }),- };-}--/**- * Changes some of a clip's properties.- *- * The generic patch keeps the panel that edits a clip from needing one- * function per field, while the `Partial<Clip>` type still stops it inventing- * fields that do not exist.- */-export function updateClip(project: Project, clipId: string, patch: Partial<Clip>): Project {- return {- ...project,- clips: project.clips.map((clip) => (clip.id === clipId ? { ...clip, ...patch } : clip)),- };-}--/**- * A clip's gain at a timeline instant, fades included.- *- * Shared between the audio preview and anything else that needs to know how- * loud a clip is right now, so the two cannot disagree about where a fade- * reaches full volume.- */-export function clipGainAt(clip: Clip, time: number): number {- const local = time - clip.start;- if (local < 0 || local > clip.duration) return 0;-- let gain = clip.volume;- if (clip.fadeIn > 0) gain *= Math.min(1, local / clip.fadeIn);- if (clip.fadeOut > 0) gain *= Math.min(1, (clip.duration - local) / clip.fadeOut);-- return Math.max(0, gain);-}--export function removeClip(project: Project, clipId: string): Project {- return { ...project, clips: project.clips.filter((clip) => clip.id !== clipId) };-}--export function removeClips(project: Project, clipIds: readonly string[]): Project {- const doomed = new Set(clipIds);- return { ...project, clips: project.clips.filter((clip) => !doomed.has(clip.id)) };-}--/** The audio clips holding sound detached from this video clip, if any. */-export function detachedAudioOf(project: Project, videoClipId: string): Clip[] {- return project.clips.filter((clip) => clip.detachedFrom === videoClipId);-}--/**- * Splits a video clip's sound onto its own audio clip - "Detach audio".- *- * The video clip goes quiet (`muted`) and a linked audio clip appears with the- * same span of the same file, taking the audio filters with it - they were- * always about the sound. The link (`detachedFrom`) is what reattachment- * follows later. Does nothing for a clip that has no audio to give.- */-export function detachAudio(project: Project, clipId: string): Project {- const clip = findClip(project, clipId);- const media = clip ? findMedia(project, clip.mediaId) : null;- if (!clip || clip.kind !== "video" || clip.muted || !media?.hasAudio) return project;- if (detachedAudioOf(project, clipId).length > 0) return project;-- // A lane free for the whole span, or a fresh one - never on top of a clip.- const end = clip.start + clip.duration;- const free = project.tracks.find(- (track) =>- !project.clips.some(- (other) =>- other.trackId === track.id &&- other.start < end &&- clip.start < other.start + other.duration,- ),- );- let base = project;- let trackId = free?.id ?? "";- if (!trackId) {- const grown = addTrack(project);- base = grown.project;- trackId = grown.trackId;- }-- const sound: Clip = {- ...clip,- id: nextId("c"),- trackId,- kind: "audio",- filters: [...clip.filters],- // Sound has no picture: effects and transitions stay with the video clip.- videoEffects: [],- transitionIn: undefined,- detachedFrom: clip.id,- muted: undefined,- };-- return {- ...base,- clips: [- ...base.clips.map((other) =>- other.id === clipId ? { ...other, muted: true, filters: [] } : other,- ),- sound,- ],- };-}--/**- * Puts detached audio back into its video clip - "Reattach audio".- *- * Accepts either side of the link: the muted video clip or any of its- * detached audio clips. Every linked audio clip is absorbed (a detached clip- * that was split leaves several), the video clip sounds again, and the audio- * filters ride back with it. Does nothing when the other side is gone.- */-export function reattachAudio(project: Project, clipId: string): Project {- const clip = findClip(project, clipId);- if (!clip) return project;-- const videoId = clip.kind === "audio" && clip.detachedFrom ? clip.detachedFrom : clip.id;- const video = findClip(project, videoId);- const sounds = detachedAudioOf(project, videoId);- if (!video || sounds.length === 0) return project;-- const doomed = new Set(sounds.map((sound) => sound.id));- return {- ...project,- clips: project.clips- .filter((other) => !doomed.has(other.id))- .map((other) =>- other.id === videoId- ? { ...other, muted: undefined, filters: [...sounds[0].filters] }- : other,- ),- };-}--/** Cuts a clip in two at `time`. Does nothing if the cut misses the clip. */-export function splitClip(project: Project, clipId: string, time: number): Project {- const clip = findClip(project, clipId);- if (!clip) return project;-- const offset = time - clip.start;- if (offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION) {- return project;- }-- const head: Clip = {- ...clip,- duration: offset,- filters: [...clip.filters],- videoEffects: [...clip.videoEffects],- };- const tail: Clip = {- ...clip,- id: nextId("c"),- start: clip.start + offset,- duration: clip.duration - offset,- // Timeline offset times speed is how much source the head consumed - on a- // 2x clip the cut is twice as far into the file as it is into the clip.- sourceStart: clip.sourceStart + offset * clip.speed,- filters: [...clip.filters],- videoEffects: [...clip.videoEffects],- // The transition belongs to the cut at the original clip's start, which- // the head keeps. The split point is continuous material - a transition- // there would dissolve a frame into its own neighbour.- transitionIn: undefined,- };-- return {- ...project,- clips: project.clips.flatMap((current) => (current.id === clipId ? [head, tail] : [current])),- };-}--/**- * Adds a lane on top of the stack.- *- * Numbered from the highest number already in use rather than from the track- * count, so removing Track 2 and adding another does not produce a second- * Track 3 sitting next to the first.- */-export function addTrack(project: Project): { project: Project; trackId: string } {- const highest = project.tracks.reduce((best, track) => {- const number = Number.parseInt(track.name.replace(/\D+/g, ""), 10);- return Number.isFinite(number) ? Math.max(best, number) : best;- }, 0);-- const track: Track = {- id: nextId("t"),- name: `Track ${highest + 1}`,- visible: true,- muted: false,- };-- // Appended, and the timeline draws the array reversed, so a new track- // appears at the top of the stack.- return { project: { ...project, tracks: [...project.tracks, track] }, trackId: track.id };-}--/**- * Removes a lane and everything on it.- *- * Refuses to remove the last one: a timeline with no tracks has nowhere to- * drop anything, and recovering from that would need its own undo.- */-export function removeTrack(project: Project, trackId: string): Project {- if (project.tracks.length <= 1) return project;- return {- ...project,- tracks: project.tracks.filter((track) => track.id !== trackId),- clips: project.clips.filter((clip) => clip.trackId !== trackId),- };-}--/** Renames a lane. An empty or whitespace-only name is ignored. */-export function renameTrack(project: Project, trackId: string, name: string): Project {- const trimmed = name.trim();- if (!trimmed) return project;-- return {- ...project,- tracks: project.tracks.map((track) =>- track.id === trackId ? { ...track, name: trimmed } : track,- ),- };-}--/** Which clips sit on a track. Used to warn before removing a full one. */-export function clipsOnTrack(project: Project, trackId: string): Clip[] {- return project.clips.filter((clip) => clip.trackId === trackId);-}--/**- * How far apart two clips may sit and still count as touching, in seconds.- *- * Splitting produces edges that meet exactly, but the numbers have been- * through float arithmetic on the way, so an exact comparison would- * occasionally refuse to rejoin a clip it had just cut.- */-const JOIN_EPSILON = 1e-6;--/**- * The clip that ends exactly where this one starts, on the same track - the- * outgoing half of a cut. This is what a transition needs to exist: no- * preceding clip, no cut, nothing to transition across.- *- * A whole-frame tolerance rather than JOIN_EPSILON, because clips placed by- * dragging land wherever the pointer was; edges that *look* joined on the- * timeline should accept a transition.- */-export function precedingClip(project: Project, clipId: string): Clip | null {- const clip = findClip(project, clipId);- if (!clip) return null;- return (- project.clips.find(- (other) =>- other.id !== clip.id &&- other.trackId === clip.trackId &&- other.kind !== "audio" &&- Math.abs(other.start + other.duration - clip.start) < 1 / 60,- ) ?? null- );-}--/**- * Why these clips cannot be merged, or `null` if they can.- *- * Merge is the inverse of split: it rejoins pieces of *one* source that are- * still lying end to end. It is not a way to weld two different files into a- * single clip - that is a compound clip, which needs nesting and a render of- * its own, and pretending otherwise here would produce a clip whose source- * range means nothing.- *- * Returns a sentence, because a disabled button that will not say why is worse- * than no button.- */-export function whyNotMerge(project: Project, clipIds: readonly string[]): string | null {- if (clipIds.length < 2) return "Select two or more clips to merge.";-- const clips = clipIds.flatMap((id) => {- const clip = findClip(project, id);- return clip ? [clip] : [];- });- if (clips.length < 2) return "Select two or more clips to merge.";-- if (clips.some((clip) => clip.trackId !== clips[0].trackId)) {- return "Merged clips must be on the same track.";- }- if (clips.some((clip) => clip.mediaId !== clips[0].mediaId)) {- return "Merged clips must come from the same file.";- }- // One clip has one rate; pieces playing at different rates cannot be one.- if (clips.some((clip) => clip.speed !== clips[0].speed)) {- return "Merged clips must play at the same speed.";- }-- const ordered = [...clips].sort((left, right) => left.start - right.start);- for (let index = 1; index < ordered.length; index += 1) {- const previous = ordered[index - 1];- const current = ordered[index];-- if (Math.abs(current.start - (previous.start + previous.duration)) > JOIN_EPSILON) {- return "Merged clips must touch, with no gap or overlap.";- }- // The source has to be continuous too. Two halves that were rearranged- // are adjacent on the timeline but no longer a single run of the file,- // and joining them would silently change what plays. A retimed piece- // consumes `duration * speed` of source, so continuity is measured there.- if (- Math.abs(- current.sourceStart - (previous.sourceStart + previous.duration * previous.speed),- ) > JOIN_EPSILON- ) {- return "These pieces are no longer in their original order.";- }- }-- return null;-}--/**- * Rejoins adjacent pieces of one source into a single clip.- *- * Does nothing unless [`whyNotMerge`] returns null. The surviving clip keeps- * the first piece's identity, so a selection referring to it stays valid.- */-export function mergeClips(- project: Project,- clipIds: readonly string[],-): { project: Project; clipId: string | null } {- if (whyNotMerge(project, clipIds) !== null) return { project, clipId: null };-- const ordered = clipIds- .flatMap((id) => {- const clip = findClip(project, id);- return clip ? [clip] : [];- })- .sort((left, right) => left.start - right.start);-- const first = ordered[0];- const last = ordered[ordered.length - 1];- const doomed = new Set(ordered.slice(1).map((clip) => clip.id));-- const merged: Clip = {- ...first,- duration: last.start + last.duration - first.start,- // Gain and fades come from the first piece; the later ones are discarded- // along with their clips, which is what "these are one clip again" means.- };-- return {- project: {- ...project,- clips: project.clips- .filter((clip) => !doomed.has(clip.id))- .map((clip) => (clip.id === first.id ? merged : clip)),- },- clipId: first.id,- };-}--/**- * Changes a clip's speed, rescaling its duration to match.- *- * The amount of *source* the clip covers is held constant - that is what makes- * this a speed change rather than a trim. Playing the same material twice as- * fast means occupying half as much timeline.- */-export function setClipSpeed(project: Project, clipId: string, speed: number): Project {- const clip = findClip(project, clipId);- if (!clip) return project;-- // The engine's SPEED_RANGE (relay-media audio.rs), verbatim. One number,- // one truth: a rate the exporter would clamp must not survive in the model.- const next = Math.max(0.0625, Math.min(16, speed));- const sourceCovered = clip.duration * clip.speed;-- return updateClip(project, clipId, {- speed: next,- duration: Math.max(MIN_CLIP_DURATION, sourceCovered / next),- });-}--/** Limits, so a clip cannot be scaled or dragged out of reach. */-export const MIN_SCALE = 0.05;-export const MAX_SCALE = 8;-const MAX_OFFSET = 3;--/** Moves, resizes and rotates a clip's picture, clamped to something recoverable. */-export function setClipTransform(- project: Project,- clipId: string,- transform: Partial<Pick<Clip, "scale" | "offsetX" | "offsetY" | "rotation">>,-): Project {- const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value));-- const patch: Partial<Clip> = {};- if (transform.scale !== undefined) {- patch.scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, transform.scale));- }- if (transform.offsetX !== undefined) patch.offsetX = clamp(transform.offsetX, MAX_OFFSET);- if (transform.offsetY !== undefined) patch.offsetY = clamp(transform.offsetY, MAX_OFFSET);- if (transform.rotation !== undefined) {- // Kept in (-180, 180] so a full drag around the dial never accumulates- // turns - the number in the panel always reads like an angle, not a count.- const wrapped = ((transform.rotation % 360) + 540) % 360 - 180;- patch.rotation = wrapped === -180 ? 180 : wrapped;- }-- return updateClip(project, clipId, patch);-}--export function setTrackFlag(- project: Project,- trackId: string,- flag: "visible" | "muted",- value: boolean,-): Project {- return {- ...project,- tracks: project.tracks.map((track) =>- track.id === trackId ? { ...track, [flag]: value } : track,- ),- };-}--/** Where the last clip ends. */-export function projectDuration(project: Project): number {- return project.clips.reduce((end, clip) => Math.max(end, clip.start + clip.duration), 0);-}--/** Clips under the playhead on tracks that are not disabled. */-export function clipsAt(project: Project, time: number): Clip[] {- return project.clips.filter((clip) => {- const track = findTrack(project, clip.trackId);- if (!track) return false;- // Stills are picture, so the eye switches them off just like footage.- if (clip.kind !== "audio" && !track.visible) return false;- if (clip.kind === "audio" && track.muted) return false;- return time >= clip.start && time < clip.start + clip.duration;- });-}--/**- * The nearest interesting time to `time`, within `threshold` seconds.- *- * Snap targets are zero, the playhead, and every clip edge except those of the- * clip being dragged - snapping a clip to itself would pin it in place.- */-export function snapTime(- project: Project,- time: number,- { threshold, playhead, exclude }: { threshold: number; playhead: number; exclude?: string },-): number {- const targets = [0, playhead];- for (const clip of project.clips) {- if (clip.id === exclude) continue;- targets.push(clip.start, clip.start + clip.duration);- }-- let best = time;- let bestDistance = threshold;- for (const target of targets) {- const distance = Math.abs(target - time);- if (distance < bestDistance) {- best = target;- bestDistance = distance;- }- }- return best;-}diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 22270340..3fd70a40 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -932,6 +932,14 @@ dependencies = ["thiserror",]+[[package]]+name = "relay-project"+version = "0.1.0"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "relay-render"version = "0.1.0"diff --git a/engine/README.md b/engine/README.mdindex 1fe0dd9b..9b595743 100644--- a/engine/README.md+++ b/engine/README.md@@ -8,6 +8,7 @@ The video engine behind Relay. Rust, no GC, no hidden control flow.|---|---|---|| `relay-core` | Time, arena, frames, timeline model. The vocabulary every other crate speaks. | **none** (std only) || `relay-media` | Getting pixels in and out of files. FFmpeg lives here and nowhere else. | `relay-core`, serde_json |+| `relay-project` | The edit itself: document model, operations as commands, undo, relay.json IO. | serde, serde_json || `relay-render` | Turning a timeline plus a timestamp into one finished frame. | `relay-core` || `relay-cli` | A binary to drive the above. The vertical slice. | all of them |diff --git a/engine/crates/relay-project/Cargo.toml b/engine/crates/relay-project/Cargo.tomlnew file mode 100644index 00000000..bfee8088--- /dev/null+++ b/engine/crates/relay-project/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "relay-project"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+license.workspace = true+description = "The edit itself: the project document, its operations, and undo. The engine's ownership of the model."++[dependencies]+serde = { version = "1", features = ["derive"] }+serde_json.workspace = truediff --git a/engine/crates/relay-project/src/commands.rs b/engine/crates/relay-project/src/commands.rsnew file mode 100644index 00000000..72046f18--- /dev/null+++ b/engine/crates/relay-project/src/commands.rs@@ -0,0 +1,802 @@+//! Every edit operation, as data.+//!+//! A [`Command`] is what the UI sends over IPC; [`apply`] is the one place+//! its meaning lives. The semantics are ported line for line from+//! `desktop/src/lib/project.ts` - same clamps, same tolerances, same rules -+//! because during the migration both sides must agree about every edit, and+//! after it this file is simply the only copy.++use serde::{Deserialize, Serialize};++use crate::model::{+ AppliedFilter, Clip, ClipKind, CustomFont, MediaItem, MediaKind, Project, TextStyle,+ Timeline, Track, Transition,+};++/// Fallback length for media whose container reports no duration.+const UNKNOWN_DURATION: f64 = 5.0;+/// How long a still lasts when first placed. Editorial default, not a fact.+const DEFAULT_IMAGE_DURATION: f64 = 5.0;+/// How long a title lasts when first placed.+const DEFAULT_TEXT_DURATION: f64 = 4.0;+const MIN_CLIP_DURATION: f64 = 1.0 / 60.0;+/// The engine's speed range (relay-media `SPEED_RANGE`), verbatim.+const MIN_SPEED: f64 = 0.0625;+const MAX_SPEED: f64 = 16.0;+const MIN_SCALE: f64 = 0.05;+const MAX_SCALE: f64 = 8.0;+const MAX_OFFSET: f64 = 3.0;+/// How far apart two clips may sit and still count as touching, in seconds.+const JOIN_EPSILON: f64 = 1e-6;++#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum TrimEdge {+ Start,+ End,+}++#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum TrackFlag {+ Visible,+ Muted,+}++/// Where one clip is going, in a multi-clip move.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ClipMove {+ pub clip_id: String,+ pub start: f64,+ pub track_id: String,+}++/// A partial update to one clip. Every field optional; `transition_in` and+/// `text` are double-optional so "clear it" and "leave it alone" stay+/// distinct on the wire (absent = untouched, null = cleared).+#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ClipPatch {+ pub name: Option<String>,+ pub volume: Option<f64>,+ pub fade_in: Option<f64>,+ pub fade_out: Option<f64>,+ pub opacity: Option<f64>,+ pub preserve_pitch: Option<bool>,+ pub filters: Option<Vec<AppliedFilter>>,+ pub video_effects: Option<Vec<AppliedFilter>>,+ #[serde(default, with = "double_option", skip_serializing_if = "Option::is_none")]+ pub transition_in: Option<Option<Transition>>,+ #[serde(default, with = "double_option", skip_serializing_if = "Option::is_none")]+ pub text: Option<Option<TextStyle>>,+}++/// `Option<Option<T>>` over JSON: absent → None, null → Some(None).+mod double_option {+ use serde::{Deserialize, Deserializer, Serialize, Serializer};++ pub fn serialize<T: Serialize, S: Serializer>(+ value: &Option<Option<T>>,+ serializer: S,+ ) -> Result<S::Ok, S::Error> {+ match value {+ Some(inner) => inner.serialize(serializer),+ None => serializer.serialize_none(),+ }+ }++ pub fn deserialize<'de, T: Deserialize<'de>, D: Deserializer<'de>>(+ deserializer: D,+ ) -> Result<Option<Option<T>>, D::Error> {+ Option::<T>::deserialize(deserializer).map(Some)+ }+}++/// A media item as probed by the host, before the model mints its id.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NewMedia {+ pub path: String,+ pub name: String,+ pub duration: Option<f64>,+ pub kind: MediaKind,+ pub width: Option<u32>,+ pub height: Option<u32>,+ pub frame_rate: Option<f64>,+ pub frame_rate_fraction: Option<String>,+ pub video_codec: Option<String>,+ pub audio_codec: Option<String>,+ pub has_audio: bool,+}++#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]+pub enum Command {+ AddMedia { item: NewMedia },+ RemoveMedia { media_id: String },+ 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> },+ MoveClips { moves: Vec<ClipMove> },+ TrimClip { clip_id: String, edge: TrimEdge, delta: f64 },+ SplitClips { clip_ids: Vec<String>, time: f64 },+ MergeClips { clip_ids: Vec<String> },+ RemoveClips { clip_ids: Vec<String> },+ UpdateClip { clip_id: String, patch: ClipPatch },+ SetClipSpeed { clip_id: String, speed: f64 },+ SetClipTransform {+ clip_id: String,+ scale: Option<f64>,+ offset_x: Option<f64>,+ offset_y: Option<f64>,+ rotation: Option<f64>,+ },+ DetachAudio { clip_id: String },+ ReattachAudio { clip_id: String },+ AddTrack,+ RemoveTrack { track_id: String },+ RenameTrack { track_id: String, name: String },+ SetTrackFlag { track_id: String, flag: TrackFlag, value: bool },+ AddTimeline,+ RemoveTimeline { timeline_id: String },+ RenameTimeline { timeline_id: String, name: String },+ SelectTimeline { timeline_id: String },+ AddFont { family: String, path: String },+ RemoveFont { family: String },+}++/// What a command produced, beyond the new state: the ids it minted, so the+/// UI can select what it just created.+#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Outcome {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub created_id: Option<String>,+}++/// Mints ids. Owned by the editor so restored projects advance it past every+/// id a file already uses - the collision class `adoptProject` fixed in the+/// UI is prevented here instead.+#[derive(Clone, Default, Debug)]+pub struct IdMint {+ counter: u64,+}++impl IdMint {+ pub fn next(&mut self, prefix: &str) -> String {+ self.counter += 1;+ format!("{prefix}{}", self.counter)+ }++ /// Advances the counter past `id`'s numeric suffix, if it has one.+ pub fn adopt(&mut self, id: &str) {+ let digits: String = id+ .chars()+ .rev()+ .take_while(char::is_ascii_digit)+ .collect::<String>()+ .chars()+ .rev()+ .collect();+ if let Ok(value) = digits.parse::<u64>() {+ self.counter = self.counter.max(value);+ }+ }++ pub fn adopt_project(&mut self, project: &Project) {+ for item in &project.media {+ self.adopt(&item.id);+ }+ for timeline in &project.timelines {+ self.adopt(&timeline.id);+ for track in &timeline.tracks {+ self.adopt(&track.id);+ }+ for clip in &timeline.clips {+ self.adopt(&clip.id);+ }+ }+ }+}++fn default_clip(id: String, track_id: String, media: &MediaItem, start: f64) -> Clip {+ Clip {+ id,+ track_id,+ media_id: media.id.clone(),+ name: media.name.clone(),+ kind: match media.kind {+ MediaKind::Video => ClipKind::Video,+ MediaKind::Audio => ClipKind::Audio,+ MediaKind::Image => ClipKind::Image,+ },+ start: start.max(0.0),+ duration: match media.kind {+ MediaKind::Image => DEFAULT_IMAGE_DURATION,+ _ => media.duration.unwrap_or(UNKNOWN_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,+ rotation: 0.0,+ opacity: 1.0,+ speed: 1.0,+ preserve_pitch: true,+ filters: Vec::new(),+ video_effects: Vec::new(),+ muted: None,+ detached_from: None,+ transition_in: None,+ text: None,+ }+}++/// The lowest track with nothing occupying `[start, start + duration)`,+/// falling back to the bottom track.+fn first_free_track(timeline: &Timeline, start: f64, duration: f64) -> Option<String> {+ let end = start + duration;+ timeline+ .tracks+ .iter()+ .find(|track| {+ !timeline.clips.iter().any(|clip| {+ clip.track_id == track.id && clip.start < end && start < clip.start + clip.duration+ })+ })+ .or(timeline.tracks.first())+ .map(|track| track.id.clone())+}++/// A one-line label for a block of text.+fn first_line(content: &str) -> String {+ let line = content+ .lines()+ .find(|candidate| !candidate.trim().is_empty())+ .unwrap_or("Text")+ .trim();+ let label: String = line.chars().take(40).collect();+ if label.is_empty() { "Text".to_owned() } else { label }+}++/// "Track 5" from the highest number already in use, not from the count.+fn next_numbered(name: &str, existing: impl Iterator<Item = String>) -> String {+ let highest = existing+ .filter_map(|candidate| {+ let digits: String = candidate.chars().filter(char::is_ascii_digit).collect();+ digits.parse::<u64>().ok()+ })+ .max()+ .unwrap_or(0);+ format!("{name} {}", highest + 1)+}++/// Why these clips cannot be merged, or None if they can. A sentence, because+/// a disabled button that will not say why is worse than no button.+pub fn why_not_merge(timeline: &Timeline, clip_ids: &[String]) -> Option<String> {+ if clip_ids.len() < 2 {+ return Some("Select two or more clips to merge.".to_owned());+ }+ let clips: Vec<&Clip> = clip_ids.iter().filter_map(|id| timeline.clip(id)).collect();+ if clips.len() < 2 {+ return Some("Select two or more clips to merge.".to_owned());+ }+ if clips.iter().any(|clip| clip.track_id != clips[0].track_id) {+ return Some("Merged clips must be on the same track.".to_owned());+ }+ if clips.iter().any(|clip| clip.media_id != clips[0].media_id) {+ return Some("Merged clips must come from the same file.".to_owned());+ }+ if clips.iter().any(|clip| clip.speed != clips[0].speed) {+ return Some("Merged clips must play at the same speed.".to_owned());+ }++ let mut ordered = clips.clone();+ ordered.sort_by(|left, right| left.start.total_cmp(&right.start));+ for pair in ordered.windows(2) {+ let (previous, current) = (pair[0], pair[1]);+ if (current.start - (previous.start + previous.duration)).abs() > JOIN_EPSILON {+ return Some("Merged clips must touch, with no gap or overlap.".to_owned());+ }+ if (current.source_start - (previous.source_start + previous.duration * previous.speed))+ .abs()+ > JOIN_EPSILON+ {+ return Some("These pieces are no longer in their original order.".to_owned());+ }+ }+ None+}++/// Applies one command. Errors are user-meaningful sentences; a command that+/// legitimately does nothing (a no-op rename, an out-of-range split) returns+/// Ok with no created id, matching the tolerant TS operations it replaces.+pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Result<Outcome, String> {+ match command {+ Command::AddMedia { item } => {+ if project.media.iter().any(|existing| existing.path == item.path) {+ return Ok(Outcome::default());+ }+ let id = mint.next("m");+ project.media.push(MediaItem {+ id: id.clone(),+ path: item.path,+ name: item.name,+ duration: item.duration,+ kind: item.kind,+ width: item.width,+ height: item.height,+ frame_rate: item.frame_rate,+ frame_rate_fraction: item.frame_rate_fraction,+ video_codec: item.video_codec,+ audio_codec: item.audio_codec,+ has_audio: item.has_audio,+ });+ Ok(Outcome { created_id: Some(id) })+ }++ Command::RemoveMedia { media_id } => {+ // All timelines, not just the active one: a shelved clip whose+ // media is gone would linger as a dead reference.+ project.media.retain(|item| item.id != media_id);+ for timeline in &mut project.timelines {+ timeline.clips.retain(|clip| clip.media_id != media_id);+ }+ Ok(Outcome::default())+ }++ Command::AddClip { media_id, track_id, start } => {+ let media = project+ .media_by_id(&media_id)+ .ok_or("That media is no longer in the bin.")?+ .clone();+ let timeline = project.active_mut();+ if timeline.track(&track_id).is_none() {+ return Err("That track no longer exists.".to_owned());+ }+ let id = mint.next("c");+ timeline.clips.push(default_clip(id.clone(), track_id, &media, start));+ Ok(Outcome { created_id: Some(id) })+ }++ Command::AddClipAtFirstFree { media_id, start } => {+ let media = project+ .media_by_id(&media_id)+ .ok_or("That media is no longer in the bin.")?+ .clone();+ let duration = match media.kind {+ MediaKind::Image => DEFAULT_IMAGE_DURATION,+ _ => media.duration.unwrap_or(UNKNOWN_DURATION),+ };+ let timeline = project.active_mut();+ let track_id =+ first_free_track(timeline, start, duration).ok_or("There are no tracks.")?;+ let id = mint.next("c");+ timeline.clips.push(default_clip(id.clone(), track_id, &media, start));+ Ok(Outcome { created_id: Some(id) })+ }++ Command::AddTextClip { track_id, start, style } => {+ let style = style.unwrap_or_default();+ 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)+ .ok_or("There are no tracks.")?,+ };+ let id = mint.next("c");+ timeline.clips.push(Clip {+ id: id.clone(),+ track_id,+ media_id: String::new(),+ name: first_line(&style.content),+ kind: ClipKind::Text,+ start: start.max(0.0),+ duration: DEFAULT_TEXT_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,+ rotation: 0.0,+ opacity: 1.0,+ speed: 1.0,+ preserve_pitch: true,+ filters: Vec::new(),+ video_effects: Vec::new(),+ muted: None,+ detached_from: None,+ transition_in: None,+ text: Some(style),+ });+ Ok(Outcome { created_id: Some(id) })+ }++ Command::MoveClips { moves } => {+ let timeline = project.active_mut();+ let track_ids: Vec<String> =+ timeline.tracks.iter().map(|track| track.id.clone()).collect();+ for wanted in moves {+ if let Some(clip) = timeline.clip_mut(&wanted.clip_id) {+ clip.start = wanted.start.max(0.0);+ if track_ids.contains(&wanted.track_id) {+ clip.track_id = wanted.track_id;+ }+ }+ }+ Ok(Outcome::default())+ }++ Command::TrimClip { clip_id, edge, delta } => {+ let timeline = project.active_mut();+ let Some(clip) = timeline.clip_mut(&clip_id) else {+ return Ok(Outcome::default());+ };+ match edge {+ TrimEdge::End => {+ clip.duration = (clip.duration + delta).max(MIN_CLIP_DURATION);+ }+ TrimEdge::Start => {+ // Dragging the head moves the in-point too, so the pixels+ // under the remaining part of the clip do not slide.+ let shift = delta.min(clip.duration - MIN_CLIP_DURATION);+ let start = (clip.start + shift).max(0.0);+ let applied = start - clip.start;+ clip.start = start;+ clip.duration -= applied;+ clip.source_start = (clip.source_start + applied * clip.speed).max(0.0);+ }+ }+ Ok(Outcome::default())+ }++ Command::SplitClips { clip_ids, time } => {+ let timeline = project.active_mut();+ let mut created = None;+ for clip_id in clip_ids {+ let Some(index) = timeline.clips.iter().position(|clip| clip.id == clip_id)+ else {+ continue;+ };+ let clip = &timeline.clips[index];+ let offset = time - clip.start;+ if offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION {+ continue;+ }+ let mut tail = clip.clone();+ tail.id = mint.next("c");+ tail.start = clip.start + offset;+ tail.duration = clip.duration - offset;+ tail.source_start = clip.source_start + offset * clip.speed;+ // The transition belongs to the cut at the original clip's+ // start, which the head keeps.+ tail.transition_in = None;+ created = Some(tail.id.clone());+ timeline.clips[index].duration = offset;+ timeline.clips.insert(index + 1, tail);+ }+ Ok(Outcome { created_id: created })+ }++ Command::MergeClips { clip_ids } => {+ let timeline = project.active_mut();+ if let Some(reason) = why_not_merge(timeline, &clip_ids) {+ return Err(reason);+ }+ let mut ordered: Vec<Clip> =+ clip_ids.iter().filter_map(|id| timeline.clip(id).cloned()).collect();+ ordered.sort_by(|left, right| left.start.total_cmp(&right.start));+ let first = ordered.first().expect("validated above").clone();+ let last = ordered.last().expect("validated above");+ let merged_duration = last.start + last.duration - first.start;++ let doomed: Vec<String> =+ ordered.iter().skip(1).map(|clip| clip.id.clone()).collect();+ timeline.clips.retain(|clip| !doomed.contains(&clip.id));+ let survivor =+ timeline.clip_mut(&first.id).expect("the first piece survives the retain");+ survivor.duration = merged_duration;+ Ok(Outcome { created_id: Some(first.id) })+ }++ Command::RemoveClips { clip_ids } => {+ let timeline = project.active_mut();+ timeline.clips.retain(|clip| !clip_ids.contains(&clip.id));+ Ok(Outcome::default())+ }++ Command::UpdateClip { clip_id, patch } => {+ let timeline = project.active_mut();+ let Some(clip) = timeline.clip_mut(&clip_id) else {+ return Ok(Outcome::default());+ };+ if let Some(name) = patch.name {+ clip.name = name;+ }+ if let Some(volume) = patch.volume {+ clip.volume = volume.max(0.0);+ }+ if let Some(fade_in) = patch.fade_in {+ clip.fade_in = fade_in.max(0.0);+ }+ if let Some(fade_out) = patch.fade_out {+ clip.fade_out = fade_out.max(0.0);+ }+ if let Some(opacity) = patch.opacity {+ clip.opacity = opacity.clamp(0.0, 1.0);+ }+ if let Some(preserve) = patch.preserve_pitch {+ clip.preserve_pitch = preserve;+ }+ if let Some(filters) = patch.filters {+ clip.filters = filters;+ }+ if let Some(effects) = patch.video_effects {+ clip.video_effects = effects;+ }+ if let Some(transition) = patch.transition_in {+ clip.transition_in = transition;+ }+ if let Some(text) = patch.text {+ // The name follows the words, like addTextClip snapshots it.+ if let Some(style) = &text {+ clip.name = first_line(&style.content);+ }+ clip.text = text;+ }+ Ok(Outcome::default())+ }++ Command::SetClipSpeed { clip_id, speed } => {+ let timeline = project.active_mut();+ let Some(clip) = timeline.clip_mut(&clip_id) else {+ return Ok(Outcome::default());+ };+ // The amount of source covered is held constant - that is what+ // makes this a speed change rather than a trim.+ let next = speed.clamp(MIN_SPEED, MAX_SPEED);+ let source_covered = clip.duration * clip.speed;+ clip.speed = next;+ clip.duration = (source_covered / next).max(MIN_CLIP_DURATION);+ Ok(Outcome::default())+ }++ Command::SetClipTransform { clip_id, scale, offset_x, offset_y, rotation } => {+ let timeline = project.active_mut();+ let Some(clip) = timeline.clip_mut(&clip_id) else {+ return Ok(Outcome::default());+ };+ if let Some(scale) = scale {+ clip.scale = scale.clamp(MIN_SCALE, MAX_SCALE);+ }+ if let Some(offset) = offset_x {+ clip.offset_x = offset.clamp(-MAX_OFFSET, MAX_OFFSET);+ }+ if let Some(offset) = offset_y {+ clip.offset_y = offset.clamp(-MAX_OFFSET, MAX_OFFSET);+ }+ if let Some(rotation) = rotation {+ // Kept in (-180, 180] so a full drag never accumulates turns.+ let wrapped = ((rotation % 360.0) + 540.0) % 360.0 - 180.0;+ clip.rotation = if wrapped == -180.0 { 180.0 } else { wrapped };+ }+ Ok(Outcome::default())+ }++ Command::DetachAudio { clip_id } => {+ let has_audio = {+ let timeline = project.active();+ let Some(clip) = timeline.clip(&clip_id) else {+ return Ok(Outcome::default());+ };+ clip.kind == ClipKind::Video+ && clip.muted != Some(true)+ && project+ .media_by_id(&clip.media_id)+ .is_some_and(|media| media.has_audio)+ && !timeline+ .clips+ .iter()+ .any(|other| other.detached_from.as_deref() == Some(clip_id.as_str()))+ };+ if !has_audio {+ return Ok(Outcome::default());+ }++ let timeline = project.active_mut();+ let clip = timeline.clip(&clip_id).expect("checked above").clone();+ // A lane free for the whole span, or a fresh one.+ let track_id = {+ let end = clip.start + clip.duration;+ let free = timeline.tracks.iter().find(|track| {+ !timeline.clips.iter().any(|other| {+ other.track_id == track.id+ && other.start < end+ && clip.start < other.start + other.duration+ })+ });+ match free {+ Some(track) => track.id.clone(),+ None => {+ let id = mint.next("t");+ let name = next_numbered(+ "Track",+ timeline.tracks.iter().map(|track| track.name.clone()),+ );+ timeline.tracks.push(Track {+ id: id.clone(),+ name,+ visible: true,+ muted: false,+ });+ id+ }+ }+ };++ let mut sound = clip.clone();+ sound.id = mint.next("c");+ sound.track_id = track_id;+ sound.kind = ClipKind::Audio;+ sound.video_effects = Vec::new();+ sound.transition_in = None;+ sound.detached_from = Some(clip_id.clone());+ sound.muted = None;+ let sound_id = sound.id.clone();+ timeline.clips.push(sound);++ let video = timeline.clip_mut(&clip_id).expect("still present");+ video.muted = Some(true);+ video.filters = Vec::new();+ Ok(Outcome { created_id: Some(sound_id) })+ }++ Command::ReattachAudio { clip_id } => {+ let timeline = project.active_mut();+ let Some(clip) = timeline.clip(&clip_id) else {+ return Ok(Outcome::default());+ };+ let video_id = match (&clip.kind, &clip.detached_from) {+ (ClipKind::Audio, Some(source)) => source.clone(),+ _ => clip.id.clone(),+ };+ if timeline.clip(&video_id).is_none() {+ return Ok(Outcome::default());+ }+ let sounds: Vec<Clip> = timeline+ .clips+ .iter()+ .filter(|other| other.detached_from.as_deref() == Some(video_id.as_str()))+ .cloned()+ .collect();+ if sounds.is_empty() {+ return Ok(Outcome::default());+ }+ let doomed: Vec<String> = sounds.iter().map(|sound| sound.id.clone()).collect();+ timeline.clips.retain(|other| !doomed.contains(&other.id));+ let video = timeline.clip_mut(&video_id).expect("checked above");+ video.muted = None;+ video.filters = sounds[0].filters.clone();+ Ok(Outcome::default())+ }++ Command::AddTrack => {+ let timeline = project.active_mut();+ let id = mint.next("t");+ let name =+ next_numbered("Track", timeline.tracks.iter().map(|track| track.name.clone()));+ timeline.tracks.push(Track { id: id.clone(), name, visible: true, muted: false });+ Ok(Outcome { created_id: Some(id) })+ }++ Command::RemoveTrack { track_id } => {+ let timeline = project.active_mut();+ if timeline.tracks.len() <= 1 {+ return Err("A timeline needs at least one track.".to_owned());+ }+ timeline.tracks.retain(|track| track.id != track_id);+ timeline.clips.retain(|clip| clip.track_id != track_id);+ Ok(Outcome::default())+ }++ Command::RenameTrack { track_id, name } => {+ let trimmed = name.trim();+ if trimmed.is_empty() {+ return Ok(Outcome::default());+ }+ let timeline = project.active_mut();+ if let Some(track) = timeline.tracks.iter_mut().find(|track| track.id == track_id) {+ track.name = trimmed.to_owned();+ }+ Ok(Outcome::default())+ }++ Command::SetTrackFlag { track_id, flag, value } => {+ let timeline = project.active_mut();+ if let Some(track) = timeline.tracks.iter_mut().find(|track| track.id == track_id) {+ match flag {+ TrackFlag::Visible => track.visible = value,+ TrackFlag::Muted => track.muted = value,+ }+ }+ Ok(Outcome::default())+ }++ Command::AddTimeline => {+ let id = mint.next("tl");+ let name = next_numbered(+ "Timeline",+ project.timelines.iter().map(|timeline| timeline.name.clone()),+ );+ let tracks = (1..=4)+ .map(|number| Track {+ id: mint.next("t"),+ name: format!("Track {number}"),+ visible: true,+ muted: false,+ })+ .collect();+ project.timelines.push(Timeline { id: id.clone(), name, tracks, clips: Vec::new() });+ project.active_timeline_id = id.clone();+ Ok(Outcome { created_id: Some(id) })+ }++ Command::RemoveTimeline { timeline_id } => {+ if project.timelines.len() <= 1 {+ return Err("A project needs at least one timeline.".to_owned());+ }+ let Some(index) =+ project.timelines.iter().position(|timeline| timeline.id == timeline_id)+ else {+ return Ok(Outcome::default());+ };+ if project.active_timeline_id == timeline_id {+ let neighbour = if index + 1 < project.timelines.len() { index + 1 } else { index - 1 };+ project.active_timeline_id = project.timelines[neighbour].id.clone();+ }+ project.timelines.remove(index);+ Ok(Outcome::default())+ }++ Command::RenameTimeline { timeline_id, name } => {+ let trimmed = name.trim();+ if trimmed.is_empty() {+ return Ok(Outcome::default());+ }+ if let Some(timeline) =+ project.timelines.iter_mut().find(|timeline| timeline.id == timeline_id)+ {+ timeline.name = trimmed.to_owned();+ }+ Ok(Outcome::default())+ }++ Command::SelectTimeline { timeline_id } => {+ if project.timelines.iter().any(|timeline| timeline.id == timeline_id) {+ project.active_timeline_id = timeline_id;+ }+ Ok(Outcome::default())+ }++ Command::AddFont { family, path } => {+ if !project.fonts.iter().any(|font| font.path == path) {+ project.fonts.push(CustomFont { family, path });+ }+ Ok(Outcome::default())+ }++ Command::RemoveFont { family } => {+ // Clips keep the family name: the face may come back when the+ // file does.+ project.fonts.retain(|font| font.family != family);+ Ok(Outcome::default())+ }+ }+}diff --git a/engine/crates/relay-project/src/doc.rs b/engine/crates/relay-project/src/doc.rsnew file mode 100644index 00000000..18477c91--- /dev/null+++ b/engine/crates/relay-project/src/doc.rs@@ -0,0 +1,315 @@+//! Reading and writing `relay.json`.+//!+//! The reader is a port of `desktop/src/lib/persist.ts`, tolerance rules+//! included: every field defaults rather than being trusted, clips whose+//! track or media vanished are dropped, text clips survive without media,+//! legacy flat documents load as a single timeline. A hand-edited or older+//! file must degrade to something openable, never to a load error.+//!+//! The writer produces the same structure `toDocument` writes - including the+//! flat `tracks`/`clips` mirror of the active timeline that keeps documents+//! openable in builds that predate multiple timelines.++use serde_json::{Map, Value, json};++use crate::model::{+ AppliedFilter, Clip, ClipKind, CustomFont, MediaItem, MediaKind, Project, TextAlign,+ TextStyle, Timeline, Track, Transition,+};++/// Bumped only when a change cannot be absorbed by defaulting.+const DOCUMENT_VERSION: u64 = 1;++fn text(value: Option<&Value>, fallback: &str) -> String {+ value.and_then(Value::as_str).unwrap_or(fallback).to_owned()+}++fn number(value: Option<&Value>, fallback: f64) -> f64 {+ value.and_then(Value::as_f64).filter(|n| n.is_finite()).unwrap_or(fallback)+}++fn flag(value: Option<&Value>, fallback: bool) -> bool {+ value.and_then(Value::as_bool).unwrap_or(fallback)+}++fn opt_u32(value: Option<&Value>) -> Option<u32> {+ value.and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())+}++fn opt_string(value: Option<&Value>) -> Option<String> {+ value.and_then(Value::as_str).map(str::to_owned)+}++fn read_media(raw: Option<&Value>) -> Vec<MediaItem> {+ let Some(entries) = raw.and_then(Value::as_array) else { return Vec::new() };+ entries+ .iter()+ .filter_map(|entry| {+ let id = entry.get("id")?.as_str()?.to_owned();+ let path = entry.get("path")?.as_str()?.to_owned();+ let kind = match entry.get("kind").and_then(Value::as_str) {+ Some("audio") => MediaKind::Audio,+ Some("image") => MediaKind::Image,+ _ => MediaKind::Video,+ };+ Some(MediaItem {+ name: text(entry.get("name"), &path),+ duration: entry.get("duration").and_then(Value::as_f64),+ kind,+ width: opt_u32(entry.get("width")),+ height: opt_u32(entry.get("height")),+ frame_rate: entry.get("frameRate").and_then(Value::as_f64),+ frame_rate_fraction: opt_string(entry.get("frameRateFraction")),+ video_codec: opt_string(entry.get("videoCodec")),+ audio_codec: opt_string(entry.get("audioCodec")),+ has_audio: flag(entry.get("hasAudio"), false),+ id,+ path,+ })+ })+ .collect()+}++fn read_tracks(raw: Option<&Value>) -> Vec<Track> {+ let Some(entries) = raw.and_then(Value::as_array) else { return Vec::new() };+ entries+ .iter()+ .filter_map(|entry| {+ let id = entry.get("id")?.as_str()?.to_owned();+ Some(Track {+ name: text(entry.get("name"), &id),+ visible: flag(entry.get("visible"), true),+ muted: flag(entry.get("muted"), false),+ id,+ })+ })+ .collect()+}++fn read_filters(raw: Option<&Value>) -> Vec<AppliedFilter> {+ let Some(entries) = raw.and_then(Value::as_array) else { return Vec::new() };+ entries+ .iter()+ .filter_map(|entry| {+ let id = entry.get("id")?.as_str()?.to_owned();+ let params = entry+ .get("params")+ .and_then(Value::as_object)+ .map(|map| {+ map.iter()+ .filter_map(|(key, value)| Some((key.clone(), value.as_f64()?)))+ .collect()+ })+ .unwrap_or_default();+ Some(AppliedFilter { id, params, enabled: flag(entry.get("enabled"), true) })+ })+ .collect()+}++fn read_text_style(raw: Option<&Value>) -> TextStyle {+ let base = TextStyle::default();+ let Some(style) = raw.filter(|value| value.is_object()) else { return base };+ TextStyle {+ content: text(style.get("content"), &base.content),+ font_family: text(style.get("fontFamily"), &base.font_family),+ // Clamped, not just defaulted: a hand-edited 0 would render an+ // invisible title.+ font_size: number(style.get("fontSize"), base.font_size).clamp(0.01, 1.0),+ font_weight: number(style.get("fontWeight"), base.font_weight).clamp(100.0, 900.0),+ italic: flag(style.get("italic"), base.italic),+ color: text(style.get("color"), &base.color),+ align: match style.get("align").and_then(Value::as_str) {+ Some("left") => TextAlign::Left,+ Some("right") => TextAlign::Right,+ _ => TextAlign::Center,+ },+ opacity: number(style.get("opacity"), base.opacity).clamp(0.0, 1.0),+ stroke_width: number(style.get("strokeWidth"), base.stroke_width).max(0.0),+ stroke_color: text(style.get("strokeColor"), &base.stroke_color),+ shadow: flag(style.get("shadow"), base.shadow),+ background: text(style.get("background"), &base.background),+ line_height: number(style.get("lineHeight"), base.line_height).max(0.5),+ tracking: number(style.get("tracking"), base.tracking),+ }+}++fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec<Clip> {+ let Some(entries) = raw.and_then(Value::as_array) else { return Vec::new() };+ entries+ .iter()+ .filter_map(|entry| {+ let id = entry.get("id")?.as_str()?.to_owned();+ let track_id = entry.get("trackId")?.as_str()?.to_owned();+ // A clip whose track vanished has nowhere to live.+ if !tracks.iter().any(|track| track.id == track_id) {+ return None;+ }++ let is_text = entry.get("kind").and_then(Value::as_str) == Some("text");+ let media_id = if is_text {+ String::new()+ } else {+ let media_id = entry.get("mediaId")?.as_str()?.to_owned();+ // Only the kinds that come from the bin are dropped when+ // their source is gone.+ if !media.iter().any(|item| item.id == media_id) {+ return None;+ }+ media_id+ };++ let kind = if is_text {+ ClipKind::Text+ } else {+ match entry.get("kind").and_then(Value::as_str) {+ Some("audio") => ClipKind::Audio,+ Some("image") => ClipKind::Image,+ _ => ClipKind::Video,+ }+ };++ Some(Clip {+ name: text(entry.get("name"), "clip"),+ kind,+ start: number(entry.get("start"), 0.0).max(0.0),+ duration: number(entry.get("duration"), 1.0).max(0.01),+ source_start: number(entry.get("sourceStart"), 0.0).max(0.0),+ volume: number(entry.get("volume"), 1.0).max(0.0),+ fade_in: number(entry.get("fadeIn"), 0.0).max(0.0),+ fade_out: number(entry.get("fadeOut"), 0.0).max(0.0),+ scale: number(entry.get("scale"), 1.0).max(0.05),+ offset_x: number(entry.get("offsetX"), 0.0),+ offset_y: number(entry.get("offsetY"), 0.0),+ rotation: number(entry.get("rotation"), 0.0),+ // Clamped: a hand-edited 2 would export differently from how+ // the preview clamps it on screen.+ opacity: number(entry.get("opacity"), 1.0).clamp(0.0, 1.0),+ speed: number(entry.get("speed"), 1.0).clamp(0.0625, 16.0),+ preserve_pitch: flag(entry.get("preservePitch"), true),+ filters: read_filters(entry.get("filters")),+ video_effects: read_filters(entry.get("videoEffects")),+ muted: flag(entry.get("muted"), false).then_some(true),+ detached_from: opt_string(entry.get("detachedFrom")),+ transition_in: entry.get("transitionIn").and_then(|transition| {+ Some(Transition {+ id: transition.get("id")?.as_str()?.to_owned(),+ duration: number(transition.get("duration"), 1.0).max(0.1),+ })+ }),+ text: is_text.then(|| read_text_style(entry.get("text"))),+ id,+ track_id,+ media_id,+ })+ })+ .collect()+}++/// Rebuilds a project from a document. Returns None only when there is+/// nothing recognisable to load at all.+pub fn from_document(document: &Value) -> Option<Project> {+ if !document.is_object() {+ return None;+ }+ let media = read_media(document.get("media"));++ // The timelines array is the source of truth when present and usable; a+ // file from before multiple timelines loads its flat fields as the one+ // timeline they always were.+ let mut timelines: Vec<Timeline> = Vec::new();+ if let Some(entries) = document.get("timelines").and_then(Value::as_array) {+ for entry in entries {+ let Some(id) = entry.get("id").and_then(Value::as_str) else { continue };+ if timelines.iter().any(|existing| existing.id == id) {+ continue;+ }+ let tracks = read_tracks(entry.get("tracks"));+ if tracks.is_empty() {+ continue;+ }+ let clips = read_clips(entry.get("clips"), &tracks, &media);+ timelines.push(Timeline {+ id: id.to_owned(),+ name: text(entry.get("name"), "Timeline"),+ tracks,+ clips,+ });+ }+ }+ if timelines.is_empty() {+ let tracks = read_tracks(document.get("tracks"));+ if tracks.is_empty() {+ return None;+ }+ let clips = read_clips(document.get("clips"), &tracks, &media);+ timelines.push(Timeline {+ id: "TL1".to_owned(),+ name: "Timeline 1".to_owned(),+ tracks,+ clips,+ });+ }++ let active_timeline_id = document+ .get("activeTimelineId")+ .and_then(Value::as_str)+ .filter(|id| timelines.iter().any(|timeline| timeline.id == *id))+ .unwrap_or(&timelines[0].id)+ .to_owned();++ let fonts = document+ .get("fonts")+ .and_then(Value::as_array)+ .map(|entries| {+ entries+ .iter()+ .filter_map(|entry| {+ Some(CustomFont {+ family: entry.get("family")?.as_str()?.to_owned(),+ path: entry.get("path")?.as_str()?.to_owned(),+ })+ })+ .collect()+ })+ .unwrap_or_default();++ Some(Project { media, fonts, timelines, active_timeline_id })+}++/// Settings the host manages around the edit: the manifest's identity fields.+#[derive(Clone, Debug)]+pub struct DocumentSettings {+ pub name: String,+ pub width: u32,+ pub height: u32,+ pub rate_num: i64,+ pub rate_den: i64,+}++/// Builds the full `relay.json` document.+pub fn to_document(settings: &DocumentSettings, project: &Project) -> Value {+ let active = project.active();+ let mut document = Map::new();+ document.insert("relay".into(), json!("0.1.0"));+ document.insert("version".into(), json!(DOCUMENT_VERSION));+ document.insert("name".into(), json!(settings.name));+ document.insert(+ "video".into(),+ json!({+ "width": settings.width,+ "height": settings.height,+ "rateNum": settings.rate_num,+ "rateDen": settings.rate_den,+ }),+ );+ document.insert("media".into(), serde_json::to_value(&project.media).expect("serialises"));+ // The flat mirror of the active timeline, for builds that predate+ // multiple timelines.+ document.insert("tracks".into(), serde_json::to_value(&active.tracks).expect("serialises"));+ document.insert("clips".into(), serde_json::to_value(&active.clips).expect("serialises"));+ document.insert("fonts".into(), serde_json::to_value(&project.fonts).expect("serialises"));+ document+ .insert("timelines".into(), serde_json::to_value(&project.timelines).expect("serialises"));+ document.insert("activeTimelineId".into(), json!(project.active_timeline_id));+ Value::Object(document)+}diff --git a/engine/crates/relay-project/src/editor.rs b/engine/crates/relay-project/src/editor.rsnew file mode 100644index 00000000..991ad65d--- /dev/null+++ b/engine/crates/relay-project/src/editor.rs@@ -0,0 +1,102 @@+//! The editing session: a project, its id mint, and undo.+//!+//! Undo is whole-state snapshots. The document is small - a heavy project is+//! a few hundred kilobytes - so cloning per edit is cheaper than maintaining+//! inverse operations and impossible to get wrong. The depth cap bounds the+//! memory; two hundred undos of a large project is tens of megabytes, which+//! an editor holding gigabytes of frame data does not notice.++use serde_json::Value;++use crate::commands::{Command, IdMint, Outcome, apply};+use crate::doc::{DocumentSettings, from_document, to_document};+use crate::model::Project;++const UNDO_DEPTH: usize = 200;++pub struct Editor {+ project: Project,+ mint: IdMint,+ undo: Vec<Project>,+ redo: Vec<Project>,+}++impl Editor {+ /// A fresh, empty project.+ pub fn new() -> Self {+ Self { project: Project::new(), mint: IdMint::default(), undo: Vec::new(), redo: Vec::new() }+ }++ /// Restores a project from a document, adopting every id it uses so the+ /// mint can never re-issue one. Returns None when the document holds+ /// nothing recognisable.+ pub fn from_document(document: &Value) -> Option<Self> {+ let project = from_document(document)?;+ let mut mint = IdMint::default();+ mint.adopt_project(&project);+ Some(Self { project, mint, undo: Vec::new(), redo: Vec::new() })+ }++ pub fn project(&self) -> &Project {+ &self.project+ }++ /// Applies one command, recording the state before it for undo.+ ///+ /// A command that fails leaves the project and history untouched - the+ /// snapshot is only kept when something actually changed, so undo never+ /// replays a no-op.+ pub fn apply(&mut self, command: Command) -> Result<Outcome, String> {+ let before = self.project.clone();+ let outcome = apply(&mut self.project, &mut self.mint, command)?;+ if self.project != before {+ self.undo.push(before);+ if self.undo.len() > UNDO_DEPTH {+ self.undo.remove(0);+ }+ self.redo.clear();+ }+ Ok(outcome)+ }++ /// Steps back one edit. Returns whether anything changed.+ pub fn undo(&mut self) -> bool {+ match self.undo.pop() {+ Some(previous) => {+ self.redo.push(std::mem::replace(&mut self.project, previous));+ true+ }+ None => false,+ }+ }++ /// Steps forward again. Returns whether anything changed.+ pub fn redo(&mut self) -> bool {+ match self.redo.pop() {+ Some(next) => {+ self.undo.push(std::mem::replace(&mut self.project, next));+ true+ }+ None => false,+ }+ }++ pub fn can_undo(&self) -> bool {+ !self.undo.is_empty()+ }++ pub fn can_redo(&self) -> bool {+ !self.redo.is_empty()+ }++ /// The full document for saving.+ pub fn to_document(&self, settings: &DocumentSettings) -> Value {+ to_document(settings, &self.project)+ }+}++impl Default for Editor {+ fn default() -> Self {+ Self::new()+ }+}diff --git a/engine/crates/relay-project/src/lib.rs b/engine/crates/relay-project/src/lib.rsnew file mode 100644index 00000000..f67daf47--- /dev/null+++ b/engine/crates/relay-project/src/lib.rs@@ -0,0 +1,368 @@+//! The edit itself, owned by the engine.+//!+//! `desktop/src/lib/project.ts` held a provisional copy of this model while+//! the engine had no project API; this crate is that API. The model+//! ([`model`]), every operation as a serialisable [`commands::Command`], the+//! tolerant document reader and compatible writer ([`doc`]), and the undo+//! stack ([`editor::Editor`]) - all headless, all testable without a window.+//!+//! Two compatibility guarantees hold while the UI migrates:+//!+//! 1. **Documents are interchangeable.** A `relay.json` written by either+//! side loads in the other, tolerance rules included.+//! 2. **Operations mean the same thing.** The command semantics are ports of+//! the TS operations, clamp for clamp - which is what makes flipping the+//! UI onto this crate a mechanical change rather than a behavioural one.+//!+//! Deliberately a separate crate rather than part of `relay-core`: the+//! document model needs serde, and relay-core's zero-dependency rule is worth+//! more than the adjacency.++pub mod commands;+pub mod doc;+pub mod editor;+pub mod model;++pub use commands::{Command, Outcome, why_not_merge};+pub use doc::{DocumentSettings, from_document, to_document};+pub use editor::Editor;+pub use model::Project;++#[cfg(test)]+mod tests {+ use serde_json::json;++ use crate::commands::{ClipMove, ClipPatch, Command, TrimEdge};+ use crate::doc::{DocumentSettings, from_document};+ use crate::editor::Editor;+ use crate::model::{ClipKind, MediaKind, TextStyle};++ fn media(path: &str, duration: f64, has_audio: bool) -> Command {+ Command::AddMedia {+ item: crate::commands::NewMedia {+ path: path.to_owned(),+ name: path.rsplit('/').next().unwrap_or(path).to_owned(),+ duration: Some(duration),+ kind: MediaKind::Video,+ width: Some(1920),+ height: Some(1080),+ frame_rate: Some(30.0),+ frame_rate_fraction: Some("30/1".to_owned()),+ video_codec: Some("h264".to_owned()),+ audio_codec: has_audio.then(|| "aac".to_owned()),+ has_audio,+ },+ }+ }++ fn settings() -> DocumentSettings {+ DocumentSettings {+ name: "Test".to_owned(),+ width: 1920,+ height: 1080,+ rate_num: 30,+ rate_den: 1,+ }+ }++ /// Editor with one media item and one clip at [0, 10) on track one.+ fn fixture() -> (Editor, String, String) {+ let mut editor = Editor::new();+ let media_id =+ editor.apply(media("/a.mp4", 10.0, true)).expect("adds").created_id.expect("id");+ let track_id = editor.project().active().tracks[0].id.clone();+ let clip_id = editor+ .apply(Command::AddClip { media_id: media_id.clone(), track_id, start: 0.0 })+ .expect("adds")+ .created_id+ .expect("id");+ (editor, media_id, clip_id)+ }++ #[test]+ fn a_new_project_has_one_timeline_and_four_lanes() {+ let editor = Editor::new();+ assert_eq!(editor.project().timelines.len(), 1);+ assert_eq!(editor.project().active().tracks.len(), 4);+ }++ #[test]+ fn duplicate_media_paths_are_ignored() {+ let mut editor = Editor::new();+ editor.apply(media("/a.mp4", 10.0, true)).expect("adds");+ editor.apply(media("/a.mp4", 10.0, true)).expect("no-op");+ assert_eq!(editor.project().media.len(), 1);+ }++ #[test]+ fn split_produces_source_continuous_halves_and_merge_rejoins_them() {+ let (mut editor, _, clip_id) = fixture();+ editor+ .apply(Command::SplitClips { clip_ids: vec![clip_id.clone()], time: 4.0 })+ .expect("splits");++ let clips = &editor.project().active().clips;+ assert_eq!(clips.len(), 2);+ assert_eq!(clips[0].duration, 4.0);+ assert_eq!(clips[1].start, 4.0);+ assert_eq!(clips[1].source_start, 4.0);++ let ids: Vec<String> = clips.iter().map(|clip| clip.id.clone()).collect();+ editor.apply(Command::MergeClips { clip_ids: ids }).expect("merges");+ let clips = &editor.project().active().clips;+ assert_eq!(clips.len(), 1);+ assert_eq!(clips[0].duration, 10.0);+ assert_eq!(clips[0].id, clip_id, "the first piece keeps its identity");+ }++ #[test]+ fn rearranged_pieces_refuse_to_merge() {+ let (mut editor, _, clip_id) = fixture();+ editor+ .apply(Command::SplitClips { clip_ids: vec![clip_id.clone()], time: 4.0 })+ .expect("splits");+ let tail_id = editor.project().active().clips[1].id.clone();+ let track_id = editor.project().active().tracks[0].id.clone();+ // Swap the two pieces on the timeline: adjacent, but out of order.+ editor+ .apply(Command::MoveClips {+ moves: vec![+ ClipMove { clip_id: clip_id.clone(), start: 6.0, track_id: track_id.clone() },+ ClipMove { clip_id: tail_id.clone(), start: 0.0, track_id },+ ],+ })+ .expect("moves");+ let refused = editor.apply(Command::MergeClips { clip_ids: vec![tail_id, clip_id] });+ assert!(refused.unwrap_err().contains("no longer in their original order"));+ }++ #[test]+ fn a_head_trim_moves_the_in_point_with_speed() {+ let (mut editor, _, clip_id) = fixture();+ editor.apply(Command::SetClipSpeed { clip_id: clip_id.clone(), speed: 2.0 }).expect("ok");+ // 10s of source at 2x occupies 5s of timeline.+ assert_eq!(editor.project().active().clips[0].duration, 5.0);+ editor+ .apply(Command::TrimClip { clip_id, edge: TrimEdge::Start, delta: 1.0 })+ .expect("trims");+ let clip = &editor.project().active().clips[0];+ assert_eq!(clip.start, 1.0);+ assert_eq!(clip.duration, 4.0);+ assert_eq!(clip.source_start, 2.0, "a timeline second covers two source seconds");+ }++ #[test]+ fn speed_clamps_to_the_engine_range() {+ let (mut editor, _, clip_id) = fixture();+ editor.apply(Command::SetClipSpeed { clip_id: clip_id.clone(), speed: 100.0 }).expect("ok");+ assert_eq!(editor.project().active().clips[0].speed, 16.0);+ editor.apply(Command::SetClipSpeed { clip_id, speed: 0.0 }).expect("ok");+ assert_eq!(editor.project().active().clips[0].speed, 0.0625);+ }++ #[test]+ fn detach_and_reattach_round_trip_the_sound() {+ let (mut editor, _, clip_id) = fixture();+ let sound_id = editor+ .apply(Command::DetachAudio { clip_id: clip_id.clone() })+ .expect("detaches")+ .created_id+ .expect("sound clip");++ let timeline = editor.project().active();+ assert_eq!(timeline.clips.len(), 2);+ let sound = timeline.clip(&sound_id).expect("exists");+ assert_eq!(sound.kind, ClipKind::Audio);+ assert_eq!(sound.detached_from.as_deref(), Some(clip_id.as_str()));+ assert_eq!(timeline.clip(&clip_id).expect("exists").muted, Some(true));++ editor.apply(Command::ReattachAudio { clip_id: sound_id }).expect("reattaches");+ let timeline = editor.project().active();+ assert_eq!(timeline.clips.len(), 1);+ assert_eq!(timeline.clip(&clip_id).expect("exists").muted, None);+ }++ #[test]+ fn timelines_add_switch_and_delete_with_a_floor_of_one() {+ let mut editor = Editor::new();+ let second =+ editor.apply(Command::AddTimeline).expect("adds").created_id.expect("id");+ assert_eq!(editor.project().active_timeline_id, second);+ assert_eq!(editor.project().timelines[1].name, "Timeline 2");+ assert!(+ editor.project().timelines[1].tracks.iter().all(|track| track.id != "T1"),+ "fresh lanes must not reuse the first timeline's ids"+ );++ editor.apply(Command::SelectTimeline { timeline_id: "TL1".to_owned() }).expect("ok");+ assert_eq!(editor.project().active_timeline_id, "TL1");++ editor.apply(Command::RemoveTimeline { timeline_id: "TL1".to_owned() }).expect("ok");+ assert_eq!(editor.project().active_timeline_id, second);+ let last = editor.project().timelines[0].id.clone();+ let refused = editor.apply(Command::RemoveTimeline { timeline_id: last });+ assert!(refused.is_err(), "the last timeline cannot be deleted");+ }++ #[test]+ fn undo_and_redo_walk_the_history() {+ let (mut editor, _, clip_id) = fixture();+ editor+ .apply(Command::SplitClips { clip_ids: vec![clip_id], time: 5.0 })+ .expect("splits");+ assert_eq!(editor.project().active().clips.len(), 2);++ assert!(editor.undo());+ assert_eq!(editor.project().active().clips.len(), 1);+ assert!(editor.redo());+ assert_eq!(editor.project().active().clips.len(), 2);+ assert!(editor.undo() && editor.undo() && editor.undo());+ assert!(editor.project().media.is_empty(), "all the way back to empty");+ }++ #[test]+ fn a_failed_command_records_no_history() {+ let (mut editor, _, _) = fixture();+ let before_can_undo = editor.can_undo();+ let _ = editor.apply(Command::MergeClips { clip_ids: vec!["nope".to_owned()] });+ assert_eq!(editor.can_undo(), before_can_undo);+ }++ #[test]+ fn the_document_round_trips() {+ let (mut editor, _, clip_id) = fixture();+ editor+ .apply(Command::UpdateClip {+ clip_id: clip_id.clone(),+ patch: ClipPatch {+ volume: Some(0.5),+ transition_in: Some(Some(crate::model::Transition {+ id: "cross-fade".to_owned(),+ duration: 1.5,+ })),+ ..ClipPatch::default()+ },+ })+ .expect("updates");+ editor.apply(Command::AddTimeline).expect("adds");++ let document = editor.to_document(&settings());+ let restored = Editor::from_document(&document).expect("loads");+ assert_eq!(restored.project(), editor.project());+ }++ #[test]+ fn a_typescript_written_document_loads() {+ // The exact shape desktop/src/lib/persist.ts toDocument produces,+ // optional fields omitted the way JSON.stringify drops undefined.+ let document = json!({+ "relay": "0.1.0", "version": 1, "name": "TS",+ "video": { "width": 1920, "height": 1080, "rateNum": 30, "rateDen": 1 },+ "media": [{ "id": "m1", "path": "/a.mp4", "name": "a.mp4", "duration": 10.0,+ "kind": "video", "width": 1920, "height": 1080, "frameRate": 30.0,+ "frameRateFraction": "30/1", "videoCodec": "h264",+ "audioCodec": null, "hasAudio": false }],+ "tracks": [{ "id": "T1", "name": "Track 1", "visible": true, "muted": false }],+ "clips": [{ "id": "c1", "trackId": "T1", "mediaId": "m1", "name": "a.mp4",+ "kind": "video", "start": 0.0, "duration": 10.0, "sourceStart": 0.0,+ "volume": 1.0, "fadeIn": 0.0, "fadeOut": 0.0, "scale": 1.0,+ "offsetX": 0.0, "offsetY": 0.0, "rotation": 0.0, "opacity": 1.0,+ "speed": 1.0, "preservePitch": true, "filters": [],+ "videoEffects": [{ "id": "sepia", "params": {}, "enabled": true }] }],+ "fonts": [],+ "timelines": [{ "id": "TL1", "name": "Timeline 1",+ "tracks": [{ "id": "T1", "name": "Track 1", "visible": true, "muted": false }],+ "clips": [{ "id": "c1", "trackId": "T1", "mediaId": "m1", "name": "a.mp4",+ "kind": "video", "start": 0.0, "duration": 10.0, "sourceStart": 0.0,+ "volume": 1.0, "fadeIn": 0.0, "fadeOut": 0.0, "scale": 1.0,+ "offsetX": 0.0, "offsetY": 0.0, "rotation": 0.0, "opacity": 1.0,+ "speed": 1.0, "preservePitch": true, "filters": [],+ "videoEffects": [{ "id": "sepia", "params": {}, "enabled": true }] }] }],+ "activeTimelineId": "TL1"+ });+ let editor = Editor::from_document(&document).expect("loads");+ let project = editor.project();+ assert_eq!(project.timelines.len(), 1);+ assert_eq!(project.active().clips[0].video_effects[0].id, "sepia");+ }++ #[test]+ fn a_legacy_flat_document_loads_as_one_timeline() {+ let document = json!({+ "name": "Old", "version": 1,+ "media": [],+ "tracks": [{ "id": "T1", "name": "Track 1", "visible": true, "muted": false }],+ "clips": []+ });+ let editor = Editor::from_document(&document).expect("loads");+ assert_eq!(editor.project().timelines.len(), 1);+ assert_eq!(editor.project().timelines[0].name, "Timeline 1");+ }++ #[test]+ fn restored_ids_can_never_be_reissued() {+ let (mut editor, _, _) = fixture();+ let document = editor.to_document(&settings());+ let mut restored = Editor::from_document(&document).expect("loads");+ let media_id = restored+ .apply(media("/b.mp4", 5.0, false))+ .expect("adds")+ .created_id+ .expect("id");+ assert!(+ restored.project().media.iter().filter(|item| item.id == media_id).count() == 1+ && editor.project().media.iter().all(|item| item.id != media_id),+ "the fresh id collides with nothing"+ );+ }++ #[test]+ fn commands_arrive_in_camel_case() {+ // The wire format the UI speaks. A snake_case field here means the+ // TypeScript side silently sends values serde never sees.+ let command: Command = serde_json::from_value(json!({+ "op": "addClip", "mediaId": "m1", "trackId": "T1", "start": 2.0+ }))+ .expect("camelCase fields deserialize");+ assert!(matches!(command, Command::AddClip { .. }));++ let transform: Command = serde_json::from_value(json!({+ "op": "setClipTransform", "clipId": "c1", "offsetX": 0.5+ }))+ .expect("optional camelCase fields deserialize");+ assert!(matches!(transform, Command::SetClipTransform { .. }));++ // ClipPatch double-options: absent leaves alone, null clears.+ let patch: crate::commands::ClipPatch =+ serde_json::from_value(json!({ "transitionIn": null })).expect("parses");+ assert_eq!(patch.transition_in, Some(None));+ let untouched: crate::commands::ClipPatch =+ serde_json::from_value(json!({})).expect("parses");+ assert_eq!(untouched.transition_in, None);+ }++ #[test]+ fn a_garbage_document_is_none_not_a_panic() {+ assert!(Editor::from_document(&json!("nonsense")).is_none());+ assert!(Editor::from_document(&json!({ "tracks": [] })).is_none());+ }++ #[test]+ fn text_clips_survive_without_media_and_carry_their_words() {+ let mut editor = Editor::new();+ let clip_id = editor+ .apply(Command::AddTextClip {+ track_id: None,+ start: 2.0,+ style: Some(TextStyle { content: "Lower third\nsecond line".to_owned(), ..TextStyle::default() }),+ })+ .expect("adds")+ .created_id+ .expect("id");+ assert_eq!(editor.project().active().clip(&clip_id).expect("exists").name, "Lower third");++ let document = editor.to_document(&settings());+ let restored = Editor::from_document(&document).expect("loads");+ assert_eq!(restored.project(), editor.project());+ }+}diff --git a/engine/crates/relay-project/src/model.rs b/engine/crates/relay-project/src/model.rsnew file mode 100644index 00000000..723458cb--- /dev/null+++ b/engine/crates/relay-project/src/model.rs@@ -0,0 +1,312 @@+//! The document model: what a WolfCut project *is*.+//!+//! This is the same shape `desktop/src/lib/project.ts` holds - deliberately,+//! field for field, because the two must describe identical documents while+//! the UI migrates onto this crate. Times are `f64` seconds here because that+//! is what the on-disk format stores; the conversion to exact rationals stays+//! at the render boundary (`export.rs`), exactly as it does today. Moving the+//! *document* to rational time is a format decision for later, made once,+//! here, instead of twice.+//!+//! Serde names are camelCase so a document written by this crate is byte-level+//! compatible with one written by the TypeScript side.++use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++/// What a piece of media is. A still is not a video with one frame: it has no+/// intrinsic duration, so its length on a timeline is editorial.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum MediaKind {+ Video,+ Audio,+ Image,+}++/// What a clip can be - wider than [`MediaKind`] because a text clip has no+/// file behind it; it *is* its own content.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum ClipKind {+ Video,+ Audio,+ Image,+ Text,+}++impl ClipKind {+ /// True for the kinds that put pixels on screen.+ pub fn is_visual(self) -> bool {+ matches!(self, ClipKind::Video | ClipKind::Image)+ }+}++#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MediaItem {+ pub id: String,+ pub path: String,+ pub name: String,+ /// Seconds. None when the container did not say.+ pub duration: Option<f64>,+ pub kind: MediaKind,+ pub width: Option<u32>,+ pub height: Option<u32>,+ pub frame_rate: Option<f64>,+ /// The exact fraction the engine works in, e.g. "30000/1001".+ pub frame_rate_fraction: Option<String>,+ pub video_codec: Option<String>,+ pub audio_codec: Option<String>,+ pub has_audio: bool,+}++/// A lane. Deliberately untyped: any media goes on any track.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Track {+ pub id: String,+ pub name: String,+ /// Video clips on this track are left out of the composite when false.+ pub visible: bool,+ /// Audio on this track is silent when true.+ pub muted: bool,+}++/// One applied audio filter or video effect: a catalogue id plus whatever+/// parameters were set. The catalogues themselves (and the FFmpeg strings+/// they build) live in the UI today; the model only stores the numbers.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AppliedFilter {+ pub id: String,+ #[serde(default)]+ pub params: BTreeMap<String, f64>,+ /// False bypasses without losing settings. Absent means enabled.+ #[serde(default = "yes")]+ pub enabled: bool,+}++fn yes() -> bool {+ true+}++/// A transition on the cut into a clip.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Transition {+ pub id: String,+ /// Seconds the transition covers.+ pub duration: f64,+}++#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum TextAlign {+ Left,+ Center,+ Right,+}++/// A title's styling. Sizes are fractions of the frame, so a title composed+/// against 1080p lands correctly exported at 4K.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct TextStyle {+ pub content: String,+ pub font_family: String,+ /// Cap height as a fraction of frame height.+ pub font_size: f64,+ pub font_weight: f64,+ pub italic: bool,+ pub color: String,+ pub align: TextAlign,+ pub opacity: f64,+ pub stroke_width: f64,+ pub stroke_color: String,+ pub shadow: bool,+ /// A solid plate behind the text. Empty string for none.+ pub background: String,+ pub line_height: f64,+ pub tracking: f64,+}++impl Default for TextStyle {+ fn default() -> Self {+ Self {+ content: "Your text".to_owned(),+ font_family: "\"Cabinet Grotesk\"".to_owned(),+ font_size: 0.09,+ font_weight: 700.0,+ italic: false,+ color: "#ffffff".to_owned(),+ align: TextAlign::Center,+ opacity: 1.0,+ stroke_width: 0.0,+ stroke_color: "#000000".to_owned(),+ shadow: true,+ background: String::new(),+ line_height: 1.2,+ tracking: 0.0,+ }+ }+}++#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Clip {+ pub id: String,+ pub track_id: String,+ /// Empty for a text clip, which has no file behind it.+ pub media_id: String,+ pub name: String,+ pub kind: ClipKind,+ /// Seconds from the start of the timeline.+ pub start: f64,+ pub duration: f64,+ /// In-point: how far into the media the clip starts.+ pub source_start: f64,+ /// Linear gain, 1 being unity.+ pub volume: f64,+ pub fade_in: f64,+ pub fade_out: f64,+ /// Multiplier over the fitted size. 1 fills the frame, preserving aspect.+ pub scale: f64,+ /// Offset from centred, as a fraction of frame width / height.+ pub offset_x: f64,+ pub offset_y: f64,+ /// Clockwise rotation in degrees, about the picture's centre.+ pub rotation: f64,+ /// Blend strength over whatever is beneath, in 0..1.+ pub opacity: f64,+ /// Playback rate. 1 is normal.+ pub speed: f64,+ pub preserve_pitch: bool,+ /// Audio filters, in order - order is audible.+ #[serde(default)]+ pub filters: Vec<AppliedFilter>,+ /// Video effects, in order - the visual sibling of `filters`.+ #[serde(default)]+ pub video_effects: Vec<AppliedFilter>,+ /// True when a video clip's embedded audio is detached out of it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub muted: Option<bool>,+ /// On a detached audio clip: the video clip the sound came from.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub detached_from: Option<String>,+ /// The transition on the cut into this clip, if any.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub transition_in: Option<Transition>,+ /// The overlay, when this is a text clip.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text: Option<TextStyle>,+}++/// One timeline: a name and its lanes and clips. Unlike the UI's provisional+/// model there is no "shelf" - that split existed only so the TypeScript+/// operations could stay ignorant of timelines. Here every operation takes+/// the project and works on whichever timeline is active.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Timeline {+ pub id: String,+ pub name: String,+ pub tracks: Vec<Track>,+ pub clips: Vec<Clip>,+}++/// A font the user added from disk.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CustomFont {+ pub family: String,+ pub path: String,+}++/// The edit: everything the document stores except the app-level settings+/// (name, output format) that the host manages around it.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Project {+ pub media: Vec<MediaItem>,+ pub fonts: Vec<CustomFont>,+ /// Every timeline, in tab order. Always at least one.+ pub timelines: Vec<Timeline>,+ pub active_timeline_id: String,+}++impl Project {+ /// A new project: one timeline, four lanes.+ pub fn new() -> Self {+ Self {+ media: Vec::new(),+ fonts: Vec::new(),+ timelines: vec![Timeline {+ id: "TL1".to_owned(),+ name: "Timeline 1".to_owned(),+ tracks: (1..=4)+ .map(|number| Track {+ id: format!("T{number}"),+ name: format!("Track {number}"),+ visible: true,+ muted: false,+ })+ .collect(),+ clips: Vec::new(),+ }],+ active_timeline_id: "TL1".to_owned(),+ }+ }++ /// The timeline being edited. The active id is maintained by the command+ /// layer, so a broken invariant here is a bug, not user input - but it+ /// degrades to the first timeline rather than panicking.+ pub fn active(&self) -> &Timeline {+ self.timelines+ .iter()+ .find(|timeline| timeline.id == self.active_timeline_id)+ .unwrap_or(&self.timelines[0])+ }++ pub fn active_mut(&mut self) -> &mut Timeline {+ let index = self+ .timelines+ .iter()+ .position(|timeline| timeline.id == self.active_timeline_id)+ .unwrap_or(0);+ &mut self.timelines[index]+ }++ pub fn media_by_id(&self, media_id: &str) -> Option<&MediaItem> {+ self.media.iter().find(|item| item.id == media_id)+ }+}++impl Default for Project {+ fn default() -> Self {+ Self::new()+ }+}++impl Timeline {+ pub fn clip(&self, clip_id: &str) -> Option<&Clip> {+ self.clips.iter().find(|clip| clip.id == clip_id)+ }++ pub fn clip_mut(&mut self, clip_id: &str) -> Option<&mut Clip> {+ self.clips.iter_mut().find(|clip| clip.id == clip_id)+ }++ pub fn track(&self, track_id: &str) -> Option<&Track> {+ self.tracks.iter().find(|track| track.id == track_id)+ }++ /// Where the last clip ends. Zero for an empty timeline.+ pub fn duration(&self) -> f64 {+ self.clips+ .iter()+ .map(|clip| clip.start + clip.duration)+ .fold(0.0, f64::max)+ }+}diff --git a/engine/docs/decisions/0006-transitions-in-the-exporter.md b/engine/docs/decisions/0006-transitions-in-the-exporter.mdnew file mode 100644index 00000000..033c0cf8--- /dev/null+++ b/engine/docs/decisions/0006-transitions-in-the-exporter.md@@ -0,0 +1,37 @@+# 0006 - Transitions resolve in the exporter, ramps live in the core++## Decision+A transition is stored on the *incoming* clip of a cut (`transitionIn`), and+is turned into things the renderer already understands at export time, by+`resolve_transitions` in the host's `export.rs`:++- **Cross-fade**: the incoming clip is extended backwards over the outgoing+ one - consuming its source handle, clamped to what exists - moved onto a+ synthetic lane directly above it (every track index is doubled; incoming+ clips take the odd lane), and given a `video_fade_in` opacity ramp.+- **Fade to black/white**: frame-exact `fade` filters appended to each side's+ decode chain. Nothing moves.++`relay-core::Clip` grew exactly one concept: `video_fade_in`/`video_fade_out`+ramps, multiplied into the frame plan's layer opacity. The compositor never+learns transitions exist.++## Why this shape+- Binding a transition to the cut by *adjacency* (a clip ends where this one+ starts) means moving the clips apart orphans it into a plain cut - no+ dangling entity, no repair pass.+- Resolving in the exporter keeps the engine timeline free of a transition+ type it would only ever lower into overlaps anyway.+- The handle rule (a dissolve consumes source before the in-point) is what+ every NLE does, and the clamp means "no handle, shorter dissolve" instead+ of frozen frames.++## What it costs+- Chained cross-fades within one dissolve window degrade (the synthetic-lane+ trick assumes one incoming clip per cut). Pathological, documented in code.+- The motion transitions (wipe, push, zoom) need animated transforms in the+ engine and stay "Soon" until it has them.++## What would change our mind+Animated transforms landing in `relay-core` - at which point wipes arrive and+cross-fade could become a first-class engine op instead of an export lowering.diff --git a/engine/docs/decisions/0007-engine-owns-the-project.md b/engine/docs/decisions/0007-engine-owns-the-project.mdnew file mode 100644index 00000000..92be01d8--- /dev/null+++ b/engine/docs/decisions/0007-engine-owns-the-project.md@@ -0,0 +1,50 @@+# 0007 - The engine owns the project++## Decision+`relay-project` is the model of record for the edit: the document types,+every operation as a serialisable `Command`, whole-state undo, and the+tolerant `relay.json` reader/writer - all ported semantics-for-semantics from+the UI's provisional `lib/project.ts`. The host exposes it as the `editor_*`+commands (open / apply / undo / redo / save / state / close).++`lib/project.ts` is **frozen**: bug fixes only, mirrored into `relay-project`+in the same commit, until the UI has flipped onto the engine API and the file+is deleted.++## Why now+The provisional model was meant to be scaffolding, but it was accreting+features faster than the engine grew an API - multiple timelines, effects and+transitions all landed UI-side, and every one raised the migration bill. The+audit that preceded this decision called it the repo's biggest strategic+debt; this crate is the answer.++## Shape choices worth recording+- **A separate crate, not part of relay-core.** The document model needs+ serde; relay-core's zero-dependency rule is worth more than adjacency.+- **String ids and f64 seconds in the document model.** These match the+ on-disk format and the ten projects that already exist. The arena-handled,+ rational-time `relay-core::Timeline` remains the *render* model; the+ exporter converts, as it always has. Moving the document itself to exact+ time is a format decision to make once, deliberately, later.+- **Undo is whole-state snapshots**, capped at 200. A heavy project is a few+ hundred kilobytes; cloning per edit is cheaper than inverse operations and+ impossible to get wrong.+- **Compatibility is tested**, both ways: a document written by the TS side+ loads here (fixture test), and this crate's writer produces the same+ structure - including the flat active-timeline mirror for old builds.++## The migration plan+1. *(done)* Crate, commands, undo, document IO, host API, freeze.+2. *(done)* UI flipped: App state is the `EditorView` the host returns; every+ mutation is a serialised command; drags echo locally with the engine's own+ arithmetic (`lib/editor.ts`) and commit one command on release, so undo+ means "undo the drag"; Ctrl+Z / Ctrl+Shift+Z and the Edit menu drive the+ engine's history.+3. *(done)* `lib/project.ts` and `lib/persist.ts` are deleted. What remains+ in the UI is `lib/editor.ts`: type mirrors, read-only selectors, and the+ echo - view logic, not model ownership.++## What would change our mind+Nothing about ownership. IPC round-trip cost could force a finer-grained+state-sync protocol (patches instead of full snapshots) if profiling demands+it - that changes the wire format, not who owns the model.