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
Jareer030458291b7c
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 993fe419..65e4a61b 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -4,6 +4,7 @@ import { open as openDialog } from "@tauri-apps/plugin-dialog";import { getCurrentWebview } from "@tauri-apps/api/webview";import { getCurrentWindow } from "@tauri-apps/api/window";+import { ConfirmDialog } from "./components/ConfirmDialog";import { ContextMenu, type ContextTarget } from "./components/ContextMenu";import { ExportDialog, type ExportTitle } from "./components/ExportDialog";import { Icon } from "./components/Icon";@@ -29,6 +30,7 @@ import { getTranscriberLanguage, getTranscriberModel } from "./lib/settings";import {addClip,addMedia,+ addTimeline,addTrack,clipsAt,createProject,@@ -47,13 +49,18 @@ import {reattachAudio,removeClips,removeFont,+ removeMediaEverywhere,+ removeTimeline,removeTrack,+ renameTimeline,renameTrack,setClipSpeed,setClipTransform,setTrackFlag,snapTime,splitClip,+ switchTimeline,+ timelineClipCount,toMediaItem,updateClip,trimClip,@@ -61,6 +68,7 @@ import {type Clip,type MediaItem,type Project,+ type TimelineMeta,} from "./lib/project";import { buildChain } from "./lib/filters";import { familyForPath, registerFont } from "./lib/text";@@ -267,6 +275,60 @@ function Editor({});}, []);+ // ── 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;++ playheadByTimeline.current.delete(timelineId);+ setProject(next);+ if (wasActive) {+ setSelectedClipIds([]);+ transport.pause();+ transport.seek(playheadByTimeline.current.get(next.activeTimelineId) ?? 0);+ }+ },+ [transport],+ );+/** Adds a font file to the project and makes it available immediately. */const pickFont = useCallback(async () => {try {@@ -1095,13 +1157,7 @@ function Editor({setSelectedClipIds([]);}}onImport={(paths) => void importPaths(paths)}- onRemove={(id) =>- setProject((current) => ({- ...current,- media: current.media.filter((item) => item.id !== id),- clips: current.clips.filter((clip) => clip.mediaId !== id),- }))- }+ onRemove={(id) => setProject((current) => removeMediaEverywhere(current, id))}onDismissError={() => setError(null)}onBeginDrag={beginMediaDrag}onAddToTimeline={addToTimeline}@@ -1247,6 +1303,15 @@ function Editor({setProject((current) => setTrackFlag(current, trackId, flag, value))}clipTools={clipTools}+ onSelectTimeline={selectTimeline}+ onAddTimeline={createTimeline}+ onRenameTimeline={(timelineId, name) =>+ setProject((current) => renameTimeline(current, timelineId, name))+ }+ onRequestRemoveTimeline={(timelineId) => {+ const meta = project.timelines.find((candidate) => candidate.id === timelineId);+ if (meta) setTimelineToDelete(meta);+ }}onAddTrack={() => setProject((current) => addTrack(current).project)}onRenameTrack={(trackId, name) =>setProject((current) => renameTrack(current, trackId, name))@@ -1371,6 +1436,25 @@ function Editor({{context && <ContextMenu target={context} onClose={() => setContext(null)} />}{settingsOpen && <SettingsDialog onClose={() => setSettingsOpen(false)} />}+ {timelineToDelete && (+ <ConfirmDialog+ title={`Delete "${timelineToDelete.name}"?`}+ 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 timeline is empty; nothing else is affected.";+ })()}+ confirmLabel="Delete timeline"+ onConfirm={() => {+ deleteTimelineNow(timelineToDelete.id);+ setTimelineToDelete(null);+ }}+ onCancel={() => setTimelineToDelete(null)}+ />+ )}+{toast && (<divkey={toast.id}diff --git a/desktop/src/components/ConfirmDialog.tsx b/desktop/src/components/ConfirmDialog.tsxnew file mode 100644index 00000000..f0b57740--- /dev/null+++ b/desktop/src/components/ConfirmDialog.tsx@@ -0,0 +1,74 @@+import { useEffect } from "react";++import { Icon } from "./Icon";++/**+ * A small blocking confirmation, for actions that destroy work.+ *+ * There is no undo system yet, so "are you sure" is the only line of defence+ * a destructive action has. Kept deliberately plain: a title that names the+ * thing, one sentence of consequence, and a danger-coloured button that+ * repeats the verb - never just "OK", because the button is what people read+ * when they skip the sentence.+ */+export function ConfirmDialog({+ title,+ message,+ confirmLabel,+ onConfirm,+ onCancel,+}: {+ title: string;+ message: string;+ /** The verb, e.g. "Delete timeline". Shown on the danger button. */+ confirmLabel: string;+ onConfirm: () => void;+ onCancel: () => void;+}) {+ // Escape cancels, like every sheet. Enter deliberately does not confirm:+ // a destructive default keyed to the most reflexive key would delete work.+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") onCancel();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onCancel]);++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-8+ backdrop-blur-[2px]"+ onMouseDown={(event) => {+ if (event.target === event.currentTarget) onCancel();+ }}+ >+ <div className="surface w-full max-w-sm rounded-2xl p-6">+ <div className="mb-2 flex items-center gap-2">+ <Icon name="trash" size={16} className="text-danger" />+ <h2 className="text-sm font-semibold text-primary">{title}</h2>+ </div>+ <p className="mb-5 text-xs leading-relaxed text-secondary">{message}</p>+ <div className="flex gap-1.5">+ <button+ type="button"+ autoFocus+ onClick={onCancel}+ className="flex-1 cursor-pointer rounded-lg bg-hover px-4 py-2 text-sm text-primary+ transition-colors hover:bg-active"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={onConfirm}+ className="flex-1 cursor-pointer rounded-lg bg-danger px-4 py-2 text-sm font-medium+ text-white transition-colors hover:opacity-90"+ >+ {confirmLabel}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/desktop/src/components/TimelinePanel.tsx b/desktop/src/components/TimelinePanel.tsxindex e0d5dcfb..f8c54598 100644--- a/desktop/src/components/TimelinePanel.tsx+++ b/desktop/src/components/TimelinePanel.tsx@@ -6,7 +6,7 @@ import type {import type { MediaAssets, Peaks } from "../lib/assets";import { themeColor, type Theme } from "../lib/theme";-import type { Clip, ClipMove, Project, Track } from "../lib/project";+import type { Clip, ClipMove, Project, TimelineMeta, Track } from "../lib/project";import { snapTime } from "../lib/project";import { timecode } from "../lib/time";import { Icon, IconButton } from "./Icon";@@ -145,6 +145,10 @@ export function TimelinePanel({onRenameTrack,onClipContextMenu,clipTools,+ onSelectTimeline,+ onAddTimeline,+ onRenameTimeline,+ onRequestRemoveTimeline,}: {project: Project;playhead: number;@@ -190,6 +194,11 @@ export function TimelinePanel({* owns the selection logic; this panel only hangs it in the tray.*/clipTools: MenuOption[][];+ onSelectTimeline: (timelineId: string) => void;+ onAddTimeline: () => void;+ onRenameTimeline: (timelineId: string, name: string) => void;+ /** Asks the app to confirm and delete; the panel never deletes directly. */+ onRequestRemoveTimeline: (timelineId: string) => void;}) {const canvasRef = useRef<HTMLCanvasElement>(null);const drag = useRef<DragState | null>(null);@@ -700,6 +709,30 @@ export function TimelinePanel({return (<div className={PANEL_SHELL}>+ {/*+ The timeline tabs. One per timeline in the project, like sequences in+ any other editor: the active one is what the canvas below, the preview+ and the exporter all show. Kept above the tool bar so switching reads+ as changing documents, not changing tools.+ */}+ <div+ className="thin-scroll flex h-8 shrink-0 items-center gap-1 overflow-x-auto+ border-b border-hairline px-1.5"+ >+ {project.timelines.map((timeline) => (+ <TimelineTab+ key={timeline.id}+ timeline={timeline}+ active={timeline.id === project.activeTimelineId}+ closable={project.timelines.length > 1}+ onSelect={onSelectTimeline}+ onRename={onRenameTimeline}+ onRequestRemove={onRequestRemoveTimeline}+ />+ ))}+ <IconButton icon="plus" label="New timeline" size={7} onClick={onAddTimeline} />+ </div>+<Bar><IconButtonicon="select"@@ -834,6 +867,91 @@ export function TimelinePanel({);}+/**+ * One timeline tab.+ *+ * Click switches, double-click renames in place (the same commit-on-blur rule+ * as a track rename), and the close button asks the app to confirm - deleting+ * a timeline throws away every clip on it, so the panel never does it+ * directly.+ */+function TimelineTab({+ timeline,+ active,+ closable,+ onSelect,+ onRename,+ onRequestRemove,+}: {+ timeline: TimelineMeta;+ active: boolean;+ closable: boolean;+ onSelect: (timelineId: string) => void;+ onRename: (timelineId: string, name: string) => void;+ onRequestRemove: (timelineId: string) => void;+}) {+ const [renaming, setRenaming] = useState(false);++ if (renaming) {+ return (+ <input+ autoFocus+ defaultValue={timeline.name}+ spellCheck={false}+ onFocus={(event) => event.currentTarget.select()}+ onBlur={(event) => {+ onRename(timeline.id, event.target.value);+ setRenaming(false);+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") event.currentTarget.blur();+ if (event.key === "Escape") {+ event.currentTarget.value = timeline.name;+ event.currentTarget.blur();+ }+ }}+ className="w-28 shrink-0 rounded bg-sunken px-1.5 py-0.5 text-xs text-primary+ outline-none ring-1 ring-accent"+ />+ );+ }++ return (+ <span+ role="tab"+ aria-selected={active}+ title={active ? timeline.name : `Switch to ${timeline.name}`}+ onClick={() => onSelect(timeline.id)}+ onDoubleClick={() => setRenaming(true)}+ className={`group flex max-w-44 shrink-0 cursor-pointer items-center gap-1 rounded-md+ px-2 py-0.5 text-xs transition-colors ${+ active+ ? "bg-active text-primary"+ : "text-secondary hover:bg-hover hover:text-primary"+ }`}+ >+ <span className="truncate">{timeline.name}</span>+ {closable && (+ <button+ type="button"+ aria-label={`Delete ${timeline.name}`}+ title={`Delete ${timeline.name}`}+ onClick={(event) => {+ // The x must not also switch tabs: deleting an inactive timeline+ // should not first drag the editor onto it.+ event.stopPropagation();+ onRequestRemove(timeline.id);+ }}+ className="invisible shrink-0 cursor-pointer rounded p-0.5 text-tertiary+ transition-colors hover:bg-danger-soft hover:text-danger group-hover:visible"+ >+ <Icon name="close" size={10} />+ </button>+ )}+ </span>+ );+}+/*** One lane's controls.*diff --git a/desktop/src/lib/persist.ts b/desktop/src/lib/persist.tsindex cddf5caf..72b03e58 100644--- a/desktop/src/lib/persist.ts+++ b/desktop/src/lib/persist.ts@@ -17,15 +17,34 @@ 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 {@@ -43,6 +62,14 @@ export function toDocument(session: ProjectSession, project: Project): ProjectDotracks: 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,};}@@ -95,27 +122,28 @@ export function fromDocument(raw: unknown): Project | null {}): [];- const tracks: Track[] = Array.isArray(document.tracks)- ? document.tracks.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 known = new Set(tracks.map((track) => track.id));const mediaIds = new Set(media.map((item) => item.id));- const clips: Clip[] = Array.isArray(document.clips)- ? document.clips.flatMap((entry) => {+ 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 [];@@ -196,13 +224,74 @@ export function fromDocument(raw: unknown): Project | null {}): [];- // A file with no tracks at all is not something to open silently as empty.- if (tracks.length === 0) return null;+ // 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, tracks, clips, fonts });+ return adoptProject({+ media,+ fonts,+ tracks: active.tracks,+ clips: active.clips,+ timelines: parsed.map((timeline) => ({ id: timeline.id, name: timeline.name })),+ activeTimelineId: active.id,+ shelved,+ });}/**diff --git a/desktop/src/lib/project.ts b/desktop/src/lib/project.tsindex 3c1b1a84..0a023623 100644--- a/desktop/src/lib/project.ts+++ b/desktop/src/lib/project.ts@@ -179,9 +179,26 @@ export interface Clip {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.@@ -191,6 +208,22 @@ export interface Project {* 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. */@@ -236,28 +269,51 @@ export function adoptProject(project: Project): Project {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): T[] => {- const seen = new Set<string>();- return items.map((item) => {+ 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"),- tracks: reMint(project.tracks, "t"),- clips: reMint(project.clips, "c"),+ media: reMint(project.media, "m", new Set()),+ timelines: reMint(project.timelines, "tl", new Set()),+ tracks: active.tracks,+ clips: active.clips,+ shelved,};}-/** A project with four empty lanes. */+/** A project with one timeline of four empty lanes. */export function createProject(): Project {return {media: [],@@ -271,6 +327,148 @@ export function createProject(): Project {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,};}