Open source CapCut alternative.
TypeScript
feat(site): save timeline selection as a by-reference template
David Le832932136135
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 279efb62..f936a3bb 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -24,13 +24,16 @@ import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";import { deleteExport, revealExport } from "@/cut/lib/exportClient";import {addLibraryAssetToProject,+ addTemplateToProject,deleteFromLibrary,+ deleteTemplate,fetchLibrary,moveLibraryAsset,saveAssetToLibrary,type LibraryAsset,type LibraryFolder,} from "@/cut/lib/library";+import type { LibraryTemplate } from "@/cut/lib/types";import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";import { useEditor } from "@/cut/lib/store";import { formatTime } from "@/cut/lib/time";@@ -488,6 +491,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: stringfunction LibraryPanel({ projectId }: { projectId: string }) {const [assets, setAssets] = useState<LibraryAsset[] | null>(null);const [folders, setFolders] = useState<LibraryFolder[]>([]);+ const [templates, setTemplates] = useState<LibraryTemplate[]>([]);const [activeFolder, setActiveFolder] = useState<string | null>(null);const [deleting, setDeleting] = useState<LibraryAsset | null>(null);@@ -496,9 +500,15 @@ function LibraryPanel({ projectId }: { projectId: string }) {.then((d) => {setAssets(d.assets);setFolders(d.folders);+ setTemplates(d.templates);}).catch(() => setAssets([]));+ const removeTemplate = async (id: string) => {+ setTemplates((prev) => prev.filter((t) => t.id !== id));+ await deleteTemplate(id).catch(() => void reload());+ };+useEffect(() => {void reload();}, []);@@ -531,6 +541,41 @@ function LibraryPanel({ projectId }: { projectId: string }) {<p className="px-4 pb-2 text-[11.5px] leading-relaxed text-muted-foreground">Reusable clips & music. Drag onto the timeline, or press + to add a copy.</p>+ {templates.length > 0 && (+ <div className="px-3.5 pb-3">+ <div className="mb-1.5 text-[11px] font-semibold text-muted-foreground">Templates</div>+ <div className="flex flex-col gap-1.5">+ {templates.map((t) => (+ <div+ key={t.id}+ className="group flex items-center gap-2 rounded-lg border border-border bg-background px-2.5 py-1.5"+ >+ <Layers className="size-3.5 shrink-0 text-violet-500" />+ <div className="min-w-0 flex-1">+ <div className="truncate text-[12px] font-medium">{t.name}</div>+ <div className="text-[10.5px] text-muted-foreground">+ {formatTime(t.duration)} · {t.media.length + t.layers.length + t.audio.length} parts+ </div>+ </div>+ <button+ title="Add to this project"+ className="grid size-6 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground hover:brightness-110"+ onClick={() => void addTemplateToProject(projectId, t)}+ >+ <Plus className="size-3.5" />+ </button>+ <button+ title="Delete template"+ className="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground"+ onClick={() => void removeTemplate(t.id)}+ >+ <Trash2 className="size-3.5" />+ </button>+ </div>+ ))}+ </div>+ </div>+ )}{folders.length > 0 && (<div className="flex gap-1.5 overflow-x-auto px-3.5 pb-2.5">{[{ id: null as string | null, name: "All" }, ...folders].map((f) => (diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 86d2c569..2d553975 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -1,7 +1,7 @@"use client";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { AudioLines, Blend, EllipsisVertical, Pause, Play, Plus, Scissors, SkipBack, Trash2, Type, VolumeX } from "lucide-react";+import { AudioLines, Blend, Check, EllipsisVertical, FolderPlus, Loader2, Pause, Play, Plus, Scissors, SkipBack, Trash2, Type, VolumeX } from "lucide-react";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -19,7 +19,7 @@ import {hasAssetDrag,hasLibraryDrag,} from "@/cut/lib/assetDrag";-import { importLibraryAsset } from "@/cut/lib/library";+import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";import { startDrag } from "@/cut/lib/drag";import { ensurePeaks } from "@/cut/lib/media";import { clipLen, clipSpeed, getClipSpans, TIMELINE_H_MAX, totalDuration, useEditor } from "@/cut/lib/store";@@ -419,6 +419,7 @@ export function Timeline() {><Trash2 /> {multiSelection.length > 1 ? `Delete ${multiSelection.length}` : "Delete"}</Button>+ <SaveSelectionButton /><Transport total={total} />@@ -642,6 +643,50 @@ function HoverLine({);}+/**+ * Saves the current multi-selection as a by-reference library template — the+ * source media plus the edit that arranges it, never a flattened video. Re-adding+ * it from the library re-materializes editable clips, overlays, and captions.+ */+function SaveSelectionButton() {+ const multiSelection = useEditor((s) => s.multiSelection);+ const [state, setState] = useState<"idle" | "saving" | "done">("idle");+ if (multiSelection.length === 0) return null;++ const save = async () => {+ const s = useEditor.getState();+ const input = s.selectionTemplate();+ if (!s.projectId || !input) return;+ setState("saving");+ try {+ await saveTemplate(s.projectId, input);+ setState("done");+ setTimeout(() => setState("idle"), 1800);+ } catch {+ setState("idle");+ }+ };++ return (+ <Button+ variant="ghost"+ size="sm"+ title="Save the selection as a reusable template (kept by reference)"+ disabled={state === "saving"}+ onClick={save}+ >+ {state === "saving" ? (+ <Loader2 className="animate-spin" />+ ) : state === "done" ? (+ <Check />+ ) : (+ <FolderPlus />+ )}+ {state === "done" ? "Saved" : "Save template"}+ </Button>+ );+}+/** Playback transport, centered in the timeline toolbar. */function Transport({ total }: { total: number }) {const playing = useEditor((s) => s.playing);diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 879938f2..329ad588 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -2,7 +2,7 @@import { apiFetch, apiUrl } from "./api";import { useEditor } from "./store";-import type { MediaAsset } from "./types";+import type { LibraryTemplate, MediaAsset, TemplateMedia, TemplateSaveInput } from "./types";import { mediaUrl } from "./types";export interface LibrarySource {@@ -34,6 +34,7 @@ export interface LibraryFolder {export interface LibraryData {assets: LibraryAsset[];folders: LibraryFolder[];+ templates: LibraryTemplate[];}export const libraryMediaUrl = (fileName: string) =>@@ -148,6 +149,60 @@ export async function addLibraryAssetToProject(return asset;}+/** Save the current timeline selection as a by-reference template. */+export async function saveTemplate(+ projectId: string,+ input: TemplateSaveInput+): Promise<LibraryTemplate> {+ const res = await apiFetch("/api/cut/library/templates", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ projectId, ...input }),+ });+ const body = (await res.json()) as LibraryTemplate & { error?: string };+ if (!res.ok) throw new Error(body.error ?? "Could not save the template.");+ return body;+}++export async function deleteTemplate(id: string): Promise<void> {+ const res = await apiFetch(`/api/cut/library/templates/${id}`, { method: "DELETE" });+ if (!res.ok) throw new Error("Could not delete the template.");+}++/** Copy a template's media into the open project and re-materialize its clips,+ * overlays, and captions at the playhead — everything editable, nothing baked. */+export async function addTemplateToProject(+ projectId: string,+ template: LibraryTemplate+): Promise<void> {+ const res = await apiFetch(`/api/cut/library/templates/${template.id}/use`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ projectId }),+ });+ const body = (await res.json()) as { media?: TemplateMedia[]; error?: string };+ if (!res.ok || !body.media) throw new Error(body.error ?? "Could not add the template.");++ const s = useEditor.getState();+ // Each returned media file (in template.media order) becomes a project asset;+ // the layer/audio media indices resolve against this array.+ const assetIds = body.media.map((m) => {+ const asset: MediaAsset = {+ id: crypto.randomUUID().slice(0, 8),+ fileName: m.fileName,+ name: m.name,+ type: m.type,+ duration: m.duration,+ width: m.width,+ height: m.height,+ url: mediaUrl(projectId, m.fileName),+ };+ s.addAsset(asset);+ return asset.id;+ });+ s.insertTemplate(template, assetIds, useEditor.getState().currentTime);+}+/** Copy a project asset into the shared library for reuse. */export async function saveAssetToLibrary(projectId: string, asset: MediaAsset) {const res = await apiFetch("/api/cut/library/save", {diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 84237102..7eaf6401 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -5,6 +5,7 @@ import type {Aspect,AudioClip,ClipSpan,+ LibraryTemplate,MediaAsset,OverlayClip,ProjectDoc,@@ -12,6 +13,10 @@ import type {StoredAsset,SubtitleCue,SubtitlesBlock,+ TemplateAudio,+ TemplateLayer,+ TemplateMedia,+ TemplateSaveInput,TextOverlay,VideoClip,} from "./types";@@ -142,6 +147,15 @@ interface EditorState {updateCueTransient: (id: string, patch: Partial<SubtitleCue>) => void;sortCues: () => void;deleteSelection: () => void;+ /** Timeline window [start, end) spanned by the current selection, or null if+ * nothing selectable is chosen. */+ selectionRange: () => { start: number; end: number } | null;+ /** Build a by-reference template from the current selection (media + the edit+ * that arranges it, rebased to 0), or null if nothing usable is selected. */+ selectionTemplate: () => TemplateSaveInput | null;+ /** Re-materialize a template into the project at `offset` seconds. `assetIds`+ * maps each `template.media` index to a freshly-added project asset id. */+ insertTemplate: (template: LibraryTemplate, assetIds: string[], offset: number) => void;select: (sel: Selection) => void;/** ⌘/⇧-click: add the item to the selection (or remove it if already in),* making it the new primary. */@@ -697,6 +711,176 @@ export const useEditor = create<EditorState>((set, get) => {}));},+ selectionRange: () => {+ const s = get();+ const sels = (s.multiSelection.length ? s.multiSelection : s.selection ? [s.selection] : [])+ .filter((x): x is NonNullable<Selection> => !!x);+ if (sels.length === 0) return null;+ const spans = getClipSpans(s.clips, s.assets);+ let start = Infinity;+ let end = -Infinity;+ const add = (a: number, b: number) => {+ start = Math.min(start, a);+ end = Math.max(end, b);+ };+ for (const sel of sels) {+ if (sel.kind === "clip") {+ const sp = spans.find((x) => x.clip.id === sel.id);+ if (sp) add(sp.start, sp.start + sp.len);+ } else if (sel.kind === "overlayClip") {+ const c = s.overlayClips.find((x) => x.id === sel.id);+ if (c) {+ const sp = c.speed && c.speed > 0 ? c.speed : 1;+ add(c.start, c.start + Math.max(0.1, (c.out - c.in) / sp));+ }+ } else if (sel.kind === "audio") {+ const c = s.audioClips.find((x) => x.id === sel.id);+ if (c) add(c.start, c.start + clipLen(c));+ } else if (sel.kind === "text") {+ const o = s.overlays.find((x) => x.id === sel.id);+ if (o) add(o.start, o.end);+ } else if (sel.kind === "cue") {+ const c = s.subtitles.cues.find((x) => x.id === sel.id);+ if (c) add(c.start, c.end);+ }+ }+ return Number.isFinite(start) && end > start ? { start, end } : null;+ },++ selectionTemplate: () => {+ const s = get();+ const sels = (s.multiSelection.length ? s.multiSelection : s.selection ? [s.selection] : [])+ .filter((x): x is NonNullable<Selection> => !!x);+ if (sels.length === 0) return null;+ const range = get().selectionRange();+ const start0 = range ? range.start : 0;+ const spans = getClipSpans(s.clips, s.assets);++ // Media is referenced by array index; each source is listed once.+ const media: TemplateMedia[] = [];+ const indexByAsset = new Map<string, number>();+ const mediaFor = (assetId: string): number | null => {+ const cached = indexByAsset.get(assetId);+ if (cached != null) return cached;+ const a = s.assets.find((x) => x.id === assetId);+ if (!a) return null;+ const i = media.length;+ media.push({ fileName: a.fileName, name: a.name, type: a.type, duration: a.duration, width: a.width, height: a.height });+ indexByAsset.set(assetId, i);+ return i;+ };++ const layers: TemplateLayer[] = [];+ const audio: TemplateAudio[] = [];+ const texts: TextOverlay[] = [];+ const cues: SubtitleCue[] = [];+ for (const sel of sels) {+ if (sel.kind === "clip") {+ const sp = spans.find((x) => x.clip.id === sel.id);+ if (!sp) continue;+ const mi = mediaFor(sp.clip.assetId);+ if (mi == null) continue;+ // Base-track clips re-materialize onto the base track (onBase), so a+ // template stands up its own video instead of an empty base.+ layers.push({ media: mi, start: sp.start - start0, in: sp.clip.in, out: sp.clip.out, frame: sp.clip.frame, fit: sp.clip.fit, muted: sp.clip.muted, speed: sp.clip.speed, track: 1, onBase: true });+ } else if (sel.kind === "overlayClip") {+ const c = s.overlayClips.find((x) => x.id === sel.id);+ if (!c) continue;+ const mi = mediaFor(c.assetId);+ if (mi == null) continue;+ layers.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, frame: c.frame, fit: c.fit, muted: c.muted, speed: c.speed, track: c.track + 1 });+ } else if (sel.kind === "audio") {+ const c = s.audioClips.find((x) => x.id === sel.id);+ if (!c) continue;+ const mi = mediaFor(c.assetId);+ if (mi == null) continue;+ audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed });+ } else if (sel.kind === "text") {+ const o = s.overlays.find((x) => x.id === sel.id);+ if (o) texts.push({ ...o, start: o.start - start0, end: o.end - start0 });+ } else if (sel.kind === "cue") {+ const c = s.subtitles.cues.find((x) => x.id === sel.id);+ if (c) cues.push({ ...c, start: c.start - start0, end: c.end - start0 });+ }+ }+ if (media.length === 0 && texts.length === 0 && cues.length === 0) return null;+ const duration = range+ ? range.end - range.start+ : Math.max(0.1, ...texts.map((t) => t.end), ...cues.map((c) => c.end));+ return { name: "Template", duration, media, layers, audio, texts, cues };+ },++ insertTemplate: (template, assetIds, offset) => {+ push();+ const usable = template.layers.filter((l) => assetIds[l.media]);+ const baseLayers = usable.filter((l) => l.onBase);+ const overlayLayers = usable.filter((l) => !l.onBase);+ // Base clips append (magnetic) at the end of the current base track; the+ // free-positioned parts (overlays, audio, captions) shift to line up with+ // that segment. A template with no base clips drops in at the playhead.+ const shift = baseLayers.length ? totalDuration(get().clips) : Math.max(0, offset);+ const newClips: VideoClip[] = [...baseLayers]+ .sort((a, b) => a.start - b.start)+ .map((l) => ({+ id: uid(),+ assetId: assetIds[l.media],+ in: l.in,+ out: l.out,+ muted: l.muted,+ ...(l.frame ? { frame: l.frame } : {}),+ ...(l.fit ? { fit: l.fit } : {}),+ ...(l.speed ? { speed: l.speed } : {}),+ }));+ const baseTrack = Math.max(0, ...get().overlayClips.map((c) => c.track));+ const newOverlays: OverlayClip[] = overlayLayers.map((l) => ({+ id: uid(),+ assetId: assetIds[l.media],+ track: baseTrack + l.track,+ start: l.start + shift,+ in: l.in,+ out: l.out,+ muted: l.muted,+ ...(l.frame ? { frame: l.frame } : {}),+ ...(l.fit ? { fit: l.fit } : {}),+ ...(l.speed ? { speed: l.speed } : {}),+ }));+ const newAudio: AudioClip[] = template.audio+ .filter((a) => assetIds[a.media])+ .map((a) => ({+ id: uid(),+ assetId: assetIds[a.media],+ start: a.start + shift,+ in: a.in,+ out: a.out,+ volume: a.volume,+ ...(a.fadeIn ? { fadeIn: a.fadeIn } : {}),+ ...(a.fadeOut ? { fadeOut: a.fadeOut } : {}),+ ...(a.speed ? { speed: a.speed } : {}),+ }));+ const newTexts: TextOverlay[] = template.texts.map((o) => ({+ ...o,+ id: uid(),+ start: o.start + shift,+ end: o.end + shift,+ }));+ const newCues: SubtitleCue[] = template.cues.map((c) => ({+ ...c,+ id: uid(),+ start: c.start + shift,+ end: c.end + shift,+ }));+ set((s) => ({+ clips: [...s.clips, ...newClips],+ overlayClips: [...s.overlayClips, ...newOverlays],+ audioClips: [...s.audioClips, ...newAudio],+ overlays: [...s.overlays, ...newTexts],+ subtitles: {+ ...s.subtitles,+ cues: [...s.subtitles.cues, ...newCues].sort((a, b) => a.start - b.start),+ },+ }));+ },+select: (sel) => set({ selection: sel, multiSelection: sel ? [sel] : [] }),toggleSelect: (sel) =>diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex f263b8be..f9cf1b54 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -164,6 +164,58 @@ export interface AudioClip {speed?: number;}+/**+ * A reusable timeline selection saved *by reference* — the source media plus+ * the edit that arranges it, never a flattened video. `layers`/`audio` point at+ * `media` by array index. Adding it to a project copies the media in and+ * re-materializes editable clips, overlays, and captions.+ */+export interface TemplateMedia {+ fileName: string;+ name: string;+ type: AssetType;+ duration: number;+ width?: number;+ height?: number;+}+export interface TemplateLayer {+ media: number; // index into `media`+ start: number;+ in: number;+ out: number;+ frame?: FrameRect;+ fit?: "fit" | "fill";+ muted: boolean;+ speed?: number;+ track: number;+ /** Came from the base (magnetic) track — re-materializes onto it, not an+ * overlay track, so a template stands up its own base video. */+ onBase?: boolean;+}+export interface TemplateAudio {+ media: number;+ start: number;+ in: number;+ out: number;+ volume: number;+ fadeIn?: number;+ fadeOut?: number;+ speed?: number;+}+export interface LibraryTemplate {+ id: string;+ name: string;+ addedAt: number;+ duration: number;+ media: TemplateMedia[];+ layers: TemplateLayer[];+ audio: TemplateAudio[];+ texts: TextOverlay[];+ cues: SubtitleCue[];+}+/** What the client sends to save a selection (media are project file names). */+export type TemplateSaveInput = Omit<LibraryTemplate, "id" | "addedAt">;+export type FontId = "sf" | "serif" | "rounded" | "mono" | "impact";export interface FontDef {diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex c04d6794..ecb5aedd 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -3,14 +3,19 @@ import {addUpload,createFolder,deleteFolder,+ deleteTemplate,ensureLibraryThumb,libMediaPath,listFolders,listLibrary,+ listTemplates,moveAsset,removeAsset,renameFolder,+ saveTemplate,useInProject,+ useTemplate,+ type TemplateInput,} from "../library";import { serveFileRange } from "../serveFile";import { importFromUrl } from "../urlImport";@@ -22,8 +27,41 @@ const caught = (e: unknown, fallback: string) =>/** The shared library: reusable media outside any project. */export const libraryApi = {async list() {- const [assets, folders] = await Promise.all([listLibrary(), listFolders()]);- return Response.json({ assets, folders });+ const [assets, folders, templates] = await Promise.all([+ listLibrary(),+ listFolders(),+ listTemplates(),+ ]);+ return Response.json({ assets, folders, templates });+ },++ /** Save a timeline selection as a by-reference template. */+ async saveTemplate(req: Request) {+ try {+ const { projectId, ...input } = (await req.json()) as { projectId: string } & TemplateInput;+ return Response.json(await saveTemplate(projectId, input));+ } catch (e) {+ return caught(e, "Could not save the template.");+ }+ },++ /** Materialize a template into a project (copies its media in). */+ async useTemplate(req: Request, { id }: { id: string }) {+ try {+ const { projectId } = (await req.json()) as { projectId: string };+ return Response.json(await useTemplate(id, projectId));+ } catch (e) {+ return caught(e, "Could not add the template.");+ }+ },++ async removeTemplate(_req: Request, { id }: { id: string }) {+ try {+ await deleteTemplate(id);+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete the template.");+ }},/** A sharp, cached still for a library video. */diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 3fee009a..182dfcfd 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -49,6 +49,9 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "POST", path: "/api/cut/library/save", handler: (req) => libraryApi.save(req) },{ method: "POST", path: "/api/cut/library/import-url", handler: (req) => libraryApi.importUrl(req) },{ method: "POST", path: "/api/cut/library/move", handler: (req) => libraryApi.move(req) },+ { method: "POST", path: "/api/cut/library/templates", handler: (req) => libraryApi.saveTemplate(req) },+ { method: "POST", path: "/api/cut/library/templates/:id/use", handler: (req, p) => libraryApi.useTemplate(req, { id: p.id }) },+ { method: "DELETE", path: "/api/cut/library/templates/:id", handler: (req, p) => libraryApi.removeTemplate(req, { id: p.id }) },{ method: "POST", path: "/api/cut/library/folders", handler: (req) => libraryApi.createFolder(req) },{ method: "PUT", path: "/api/cut/library/folders/:id", handler: (req, p) => libraryApi.renameFolder(req, { id: p.id }) },{ method: "DELETE", path: "/api/cut/library/folders/:id", handler: (req, p) => libraryApi.deleteFolder(req, { id: p.id }) },diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex ec664035..d9d685dd 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -39,9 +39,60 @@ export interface LibraryFolder {createdAt: number;}+/**+ * A saved timeline selection kept *by reference*: the source media plus the+ * edit that arranges it (trims, layout regions, overlays, captions), never a+ * flattened video. Re-adding it copies the media into the project and+ * re-materializes editable clips. Its media files live privately in the library+ * (not as loose assets), so a template stays whole even if the project it came+ * from is deleted. `layers`/`audio` reference `media` by array index.+ */+export interface TemplateMedia {+ fileName: string; // private copy inside the library media folder+ name: string;+ type: "video" | "audio";+ duration: number;+ width?: number;+ height?: number;+}+export interface TemplateLayer {+ media: number; // index into template.media+ start: number;+ in: number;+ out: number;+ frame?: { x: number; y: number; w: number; h: number };+ fit?: "fit" | "fill";+ muted: boolean;+ speed?: number;+ track: number;+ onBase?: boolean; // re-materializes onto the base track rather than an overlay+}+export interface TemplateAudio {+ media: number;+ start: number;+ in: number;+ out: number;+ volume: number;+ fadeIn?: number;+ fadeOut?: number;+ speed?: number;+}+export interface LibraryTemplate {+ id: string;+ name: string;+ addedAt: number;+ duration: number;+ media: TemplateMedia[];+ layers: TemplateLayer[];+ audio: TemplateAudio[];+ texts: unknown[]; // opaque TextOverlay[] round-tripped for the client+ cues: unknown[]; // opaque SubtitleCue[]+}+interface LibraryIndex {assets: LibraryAsset[];folders?: LibraryFolder[];+ templates?: LibraryTemplate[];}export function libMediaPath(fileName: string) {@@ -335,3 +386,80 @@ export async function moveAsset(assetId: string, folderId: string | null) {asset.folderId = folderId;await writeIndex(idx);}++// --- Templates: reusable selections saved by reference (see LibraryTemplate). ---++/** What the client sends to save a selection: source media (project files) plus+ * the edit that arranges them, referencing media by array index. */+export interface TemplateInput {+ name: string;+ duration: number;+ media: { fileName: string; name: string; type: "video" | "audio"; duration: number; width?: number; height?: number }[];+ layers: TemplateLayer[];+ audio: TemplateAudio[];+ texts: unknown[];+ cues: unknown[];+}++export async function listTemplates(): Promise<LibraryTemplate[]> {+ const idx = await readIndex();+ return (idx.templates ?? []).slice().sort((a, b) => b.addedAt - a.addedAt);+}++/** Save a selection as a template: copy each source into the library privately+ * and store the edit that references it. */+export async function saveTemplate(projectId: string, input: TemplateInput): Promise<LibraryTemplate> {+ if (!(await readProject(projectId))) throw new Error("Project not found.");+ if (!input.media?.length && !input.texts?.length && !input.cues?.length) {+ throw new Error("Nothing to save.");+ }+ await mkdir(LIB_MEDIA, { recursive: true });+ const media: TemplateMedia[] = [];+ for (const m of input.media) {+ const src = projectMediaPath(projectId, m.fileName);+ if (!(await exists(src))) throw new Error("Media file not found in project.");+ const dest = await freeName(m.fileName);+ await copyFile(src, libMediaPath(dest));+ media.push({ fileName: dest, name: m.name, type: m.type, duration: m.duration, width: m.width, height: m.height });+ }+ const template: LibraryTemplate = {+ id: crypto.randomUUID().slice(0, 8),+ name: (input.name || "Template").trim().slice(0, 80),+ addedAt: Date.now(),+ duration: input.duration,+ media,+ layers: input.layers ?? [],+ audio: input.audio ?? [],+ texts: input.texts ?? [],+ cues: input.cues ?? [],+ };+ const idx = await readIndex();+ idx.templates = [...(idx.templates ?? []), template];+ await writeIndex(idx);+ return template;+}++/** Materialize a template into a project: copy its media in and hand the client+ * the project file names (in template media order) plus the stored edit. */+export async function useTemplate(templateId: string, projectId: string) {+ if (!(await readProject(projectId))) throw new Error("Project not found.");+ const idx = await readIndex();+ const template = (idx.templates ?? []).find((x) => x.id === templateId);+ if (!template) throw new Error("Template not found.");+ const media: TemplateMedia[] = [];+ for (const m of template.media) {+ const dest = await uniqueName(m.fileName, (n) => projectMediaPath(projectId, n));+ await copyFile(libMediaPath(m.fileName), projectMediaPath(projectId, dest));+ media.push({ ...m, fileName: dest });+ }+ return { template, media };+}++export async function deleteTemplate(id: string) {+ const idx = await readIndex();+ const template = (idx.templates ?? []).find((x) => x.id === id);+ idx.templates = (idx.templates ?? []).filter((x) => x.id !== id);+ await writeIndex(idx);+ // The media copies are private to this template, so removing them is safe.+ for (const m of template?.media ?? []) await rm(libMediaPath(m.fileName), { force: true });+}