Open source CapCut alternative.
TypeScript
feat(site): templates become project-scoped in Media, pushable to the shared Library [rebuild]
David Le7428e2d05e2b
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 16995304..32fb3493 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -182,6 +182,7 @@ export function Editor({s.clips !== (last.clips as unknown) ||s.audioClips !== (last.audioClips as unknown) ||s.overlays !== (last.overlays as unknown) ||+ s.templates !== (last.templates as unknown) ||s.subtitles !== (last.subtitles as unknown) ||s.aspect !== last.aspect ||s.fadeIn !== (last.fadeIn ?? 0) ||diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 1096c021..cc478836 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -30,20 +30,24 @@ import {DialogTitle,} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";-import { clearAssetDrag, setLibraryDragData } from "@/cut/lib/assetDrag";+import { clearAssetDrag, setCardDragImage, setLibraryDragData } from "@/cut/lib/assetDrag";import {createLibraryFolder,deleteFromLibrary,deleteLibraryFolder,+ deleteTemplate,fetchLibrary,importUrlToLibrary,libraryMediaUrl,moveLibraryAsset,renameLibraryFolder,+ renameTemplate,uploadToLibrary,type LibraryAsset,type LibraryFolder,} from "@/cut/lib/library";+import type { LibraryTemplate } from "@/cut/lib/types";+import { TemplateCard } from "./TemplateCard";import { homeHref, useCutBase } from "@/cut/lib/nav";import { useRevealFlash } from "@/cut/lib/refReveal";import { formatTime } from "@/cut/lib/time";@@ -61,6 +65,7 @@ export function LibraryView() {const base = useCutBase();const [assets, setAssets] = useState<LibraryAsset[] | null>(null);const [folders, setFolders] = useState<LibraryFolder[]>([]);+ const [templates, setTemplates] = useState<LibraryTemplate[]>([]);// The open folder lives in the URL (?folder=…) so the browser's back button// steps folder → root and the location survives reloads.const openFolder = useSearchParams().get("folder");@@ -79,9 +84,20 @@ export function LibraryView() {.then((d) => {setAssets(d.assets);setFolders(d.folders);+ setTemplates(d.templates);}).catch(() => setAssets([]));+ const renameTpl = async (id: string, name: string) => {+ setTemplates((prev) => prev.map((t) => (t.id === id ? { ...t, name } : t)));+ await renameTemplate(id, name).catch(() => void reload());+ };++ const removeTpl = async (id: string) => {+ setTemplates((prev) => prev.filter((t) => t.id !== id));+ await deleteTemplate(id).catch(() => void reload());+ };+useEffect(() => {void reload();}, []);@@ -155,21 +171,26 @@ export function LibraryView() {// Carry the current selection (or just this card) as a folder-move payload,// with a ghost — alongside the timeline-drag payload the card already sets.+ // A single card drags as itself; a multi-selection keeps the counted stack.const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {const ids = selected.has(a.id) && selected.size > 0 ? Array.from(selected) : [a.id];if (!selected.has(a.id)) setSelected(new Set([a.id]));e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(ids));e.dataTransfer.effectAllowed = "copyMove";- const ghost = buildDragGhost(ids.length, ids.length > 1 ? `${ids.length} items` : a.name);- document.body.appendChild(ghost);- e.dataTransfer.setDragImage(ghost, 18, 16);- setTimeout(() => ghost.remove(), 0);+ if (ids.length > 1) {+ const ghost = buildDragGhost(ids.length, `${ids.length} items`);+ document.body.appendChild(ghost);+ e.dataTransfer.setDragImage(ghost, 18, 16);+ setTimeout(() => ghost.remove(), 0);+ } else {+ setCardDragImage(e, e.currentTarget as HTMLElement);+ }};const all = assets ?? [];const shown = all.filter((a) => (a.folderId ?? null) === openFolder);const openFolderName = folders.find((f) => f.id === openFolder)?.name;- const hasContent = all.length > 0 || folders.length > 0;+ const hasContent = all.length > 0 || folders.length > 0 || templates.length > 0;return (<div className="mx-auto w-full max-w-6xl px-10 py-9">@@ -239,6 +260,20 @@ export function LibraryView() {/>) : null}+ {openFolder === null && templates.length > 0 && (+ <div className="mb-6 grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-3">+ {templates.map((t) => (+ <TemplateCard+ key={t.id}+ template={t}+ mediaSrc={libraryMediaUrl}+ onRename={(name) => void renameTpl(t.id, name)}+ onDelete={() => void removeTpl(t.id)}+ />+ ))}+ </div>+ )}+{assets === null ? (<div className="grid place-items-center py-24 text-muted-foreground"><Loader2 className="size-5 animate-spin" />diff --git a/site/src/cut/components/RefDropZone.tsx b/site/src/cut/components/RefDropZone.tsxnew file mode 100644index 00000000..32f7b1f7--- /dev/null+++ b/site/src/cut/components/RefDropZone.tsx@@ -0,0 +1,26 @@+"use client";++import { useAssetDrop, type AssetRef } from "@/cut/lib/assetRef";+import { cn } from "@/lib/utils";++/** Wrap any element to make it a media drop target for both transports: HTML5+ * card drags and pointer drags (timeline clips). The callback receives the+ * dragged ref; filter by `ref.scope` for targets that only take some sources. */+export function RefDropZone({+ onRef,+ className,+ activeClassName,+ children,+}: {+ onRef: (ref: AssetRef) => void;+ className?: string;+ activeClassName?: string;+ children: React.ReactNode;+}) {+ const { active, attachTarget, targetProps } = useAssetDrop(onRef);+ return (+ <div ref={attachTarget} {...targetProps} className={cn(className, active && activeClassName)}>+ {children}+ </div>+ );+}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex c485b878..6354b364 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -1,7 +1,7 @@"use client";import { Fragment, useEffect, useRef, useState } from "react";-import { Captions, Check, Clapperboard, ClipboardList, Copy, Film, FolderOpen, FolderPlus, Image as ImageIcon, Layers, Loader2, MoreHorizontal, Music, Pencil, Plus, Trash2, Upload } from "lucide-react";+import { Captions, Check, Clapperboard, ClipboardList, Copy, Film, FolderOpen, FolderPlus, Image as ImageIcon, Loader2, Music, Plus, Trash2, Upload } from "lucide-react";import { Button } from "@/components/ui/button";import { LiveElapsed } from "@/cut/components/Elapsed";import {@@ -15,33 +15,42 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import { SectionTitle } from "@/cut/components/SectionTitle";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { Input } from "@/components/ui/input";+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";import { apiFetch, apiUrl } from "@/cut/lib/api";-import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";+import {+ clearAssetDrag,+ draggingLibrary,+ draggingTemplate,+ hasLibraryDrag,+ hasTemplateDrag,+ setAssetDragData,+ setCardDragImage,+} from "@/cut/lib/assetDrag";+import type { AssetRef } from "@/cut/lib/assetRef";+import { RefDropZone } from "./RefDropZone";import { deleteExport, revealExport } from "@/cut/lib/exportClient";import { useExport } from "@/cut/lib/exportStore";import {+ addAssetToLibraryTemplate,addLibraryAssetToProject,+ addProjectTemplateToTimeline,addTemplateToProject,deleteFromLibrary,deleteLibraryFolder,deleteTemplate,fetchLibrary,+ importLibraryAsset,+ importTemplateToProject,+ libraryMediaUrl,moveLibraryAsset,renameLibraryFolder,renameTemplate,saveAssetToLibrary,+ saveTemplate,type LibraryAsset,type LibraryFolder,} from "@/cut/lib/library";-import type { LibraryTemplate } from "@/cut/lib/types";+import { mediaUrl, type LibraryTemplate } from "@/cut/lib/types";import { isGenTab, useGenNotify, useWatchGenTab } from "@/cut/lib/genNotify";import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";import { useEditor } from "@/cut/lib/store";@@ -49,11 +58,11 @@ import { formatTime } from "@/cut/lib/time";import { useLocalPref } from "@/cut/lib/uiState";import type { MediaAsset } from "@/cut/lib/types";import { cn } from "@/lib/utils";-import { cardIconButton } from "@/cut/components/iconButton";import { useRevealEffect, useRevealFlash } from "@/cut/lib/refReveal";import { CopyNameLabel } from "./AssetRefs";import { AudioCardFace, AudioPanel } from "./AudioPanel";-import { buildDragGhost, FolderCrumb, FolderShelf } from "./desktopFolders";+import { FolderCrumb, FolderShelf } from "./desktopFolders";+import { TemplateCard } from "./TemplateCard";import { GenerateVideoPanel } from "./GeneratePanel";import { ImageGenPanel } from "./ImageGenPanel";import { StockImagesPanel } from "./StockImagesPanel";@@ -90,6 +99,29 @@ export function SidePanel({const [tab, setTab] = useLocalPref<Tab>("cut-side-tab", "media", (v) =>TABS.some((t) => t.id === v));+ // Rail tiles as drop targets: a Library card (asset or template) dropped on+ // Media joins the project; a Media card dropped on Library saves it there.+ // Project media (cards and timeline clips) arrives through the ref zones+ // below; these HTML5 handlers cover the library-asset and template drags.+ const [dropTab, setDropTab] = useState<Tab | null>(null);+ const acceptsDrop = (id: Tab, e: React.DragEvent) => {+ const tpl = hasTemplateDrag(e) ? draggingTemplate() : null;+ if (id === "media") return hasLibraryDrag(e) || tpl?.scope === "library";+ if (id === "library") return tpl?.scope === "project";+ return false;+ };+ // A project asset dropped on a rail tile — from a Media card or dragged+ // straight off the timeline: Media reveals it in the panel (clears its+ // origin tag), Library saves a copy to the shared library.+ const dropRefOnTab = (id: Tab, ref: AssetRef) => {+ if (ref.scope !== "project") return;+ if (id === "media") {+ useEditor.getState().updateAsset(ref.id, { origin: undefined, chatId: undefined });+ } else {+ const asset = useEditor.getState().assets.find((a) => a.id === ref.id);+ if (asset) void saveAssetToLibrary(projectId, asset);+ }+ };// Generations that finished while their tab was closed: a blue count rides// the rail icon, and opening the tab lets the new tiles pulse for a beat.const unseen = useGenNotify((s) => s.unseen);@@ -123,7 +155,8 @@ export function SidePanel({<spanclassName={cn("relative grid size-9 place-items-center rounded-lg transition-colors",- tab === id ? "bg-muted text-foreground" : "hover:bg-muted/60"+ tab === id ? "bg-muted text-foreground" : "hover:bg-muted/60",+ dropTab === id && "bg-primary/15 text-primary")}><Icon className="size-4.5" />@@ -139,19 +172,56 @@ export function SidePanel({</>);+ const tile = (+ <button+ className={tileClass}+ aria-pressed={tab === id}+ onClick={() => setTab(id)}+ onDragOver={(e) => {+ if (!acceptsDrop(id, e)) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ setDropTab(id);+ }}+ onDragLeave={() => setDropTab((d) => (d === id ? null : d))}+ onDrop={(e) => {+ if (!acceptsDrop(id, e)) return;+ e.preventDefault();+ setDropTab(null);+ const tpl = draggingTemplate();+ if (id === "media") {+ if (tpl?.scope === "library") void importTemplateToProject(projectId, tpl.template);+ else {+ const lib = draggingLibrary();+ if (lib) void importLibraryAsset(projectId, lib);+ }+ } else if (tpl?.scope === "project") {+ void saveTemplate(projectId, tpl.template);+ }+ clearAssetDrag();+ }}+ >+ {inner}+ </button>+ );+return (<Fragment key={id}>{/* Soft breaks between the file tabs, the AI-generate tabs, and the finishing tabs. */}{(id === "video" || id === "subtitles") && (<div aria-hidden className="my-1 h-px w-8 shrink-0 bg-border" />)}- <button- className={tileClass}- aria-pressed={tab === id}- onClick={() => setTab(id)}- >- {inner}- </button>+ {id === "media" || id === "library" ? (+ <RefDropZone+ onRef={(ref) => dropRefOnTab(id, ref)}+ className="shrink-0 rounded-lg"+ activeClassName="bg-primary/10"+ >+ {tile}+ </RefDropZone>+ ) : (+ tile+ )}</Fragment>);})}@@ -216,6 +286,7 @@ function MediaPanel({// generations, voiceovers, freeze frames, stock adds) is tagged with an// `origin` and stays where it was made.const assets = useEditor((s) => s.assets).filter((a) => a.origin == null);+ const templates = useEditor((s) => s.templates);const exportOpen = useEditor((s) => s.exportOpen);// A render that finishes in the background (dialog closed) drops a new file in// the exports folder; re-read the list when it lands so it shows without a@@ -278,6 +349,30 @@ function MediaPanel({</div><div className="min-h-0 flex-1 overflow-y-auto pb-3.5">+ {templates.length > 0 && (+ <div className="flex flex-col gap-1.5 px-3.5 pb-3">+ {templates.map((t) => (+ <TemplateCard+ key={t.id}+ template={t}+ mediaSrc={(f) => mediaUrl(projectId, f)}+ dragScope="project"+ addTitle="Add to timeline"+ onAdd={() => addProjectTemplateToTimeline(projectId, t)}+ onRename={(name) => useEditor.getState().renameTemplate(t.id, name)}+ onDelete={() => useEditor.getState().removeTemplate(t.id)}+ onRefDrop={(r) => {+ if (r.scope === "project") useEditor.getState().addAssetToTemplate(t.id, r.id);+ }}+ extraMenu={+ <DropdownMenuItem onClick={() => void saveTemplate(projectId, t)}>+ <FolderPlus /> Add to Library+ </DropdownMenuItem>+ }+ />+ ))}+ </div>+ )}{assets.length === 0 && !importing ? (<div className="mx-3.5 px-4 py-7 text-center text-xs leading-relaxed text-muted-foreground"><div className="mb-3 flex justify-center gap-3.5">@@ -443,7 +538,10 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: stringclassName="asset-card group flex flex-col gap-1.5 text-left"title="Drag onto the timeline, or click + to add"draggable- onDragStart={(e) => setAssetDragData(e, asset.id)}+ onDragStart={(e) => {+ setAssetDragData(e, asset.id);+ setCardDragImage(e, e.currentTarget);+ }}onDragEnd={clearAssetDrag}onMouseEnter={() => {void videoRef.current?.play().catch(() => {});@@ -602,8 +700,6 @@ function LibraryPanel({ projectId }: { projectId: string }) {await deleteTemplate(id).catch(() => void reload());};- const [renamingTemplate, setRenamingTemplate] = useState<string | null>(null);- const [templateDraft, setTemplateDraft] = useState("");const commitTemplateRename = async (id: string, name: string) => {setTemplates((prev) => prev.map((t) => (t.id === id ? { ...t, name } : t)));await renameTemplate(id, name).catch(() => void reload());@@ -632,14 +728,11 @@ function LibraryPanel({ projectId }: { projectId: string }) {};// Let a clip be dragged onto a folder tile to file it (alongside the timeline- // drag payload the card already sets).+ // drag payload the card already sets). The ghost is the card itself.const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([a.id]));e.dataTransfer.effectAllowed = "copyMove";- const ghost = buildDragGhost(1, a.name);- document.body.appendChild(ghost);- e.dataTransfer.setDragImage(ghost, 18, 16);- setTimeout(() => ghost.remove(), 0);+ setCardDragImage(e, e.currentTarget as HTMLElement);};const all = assets ?? [];@@ -653,72 +746,26 @@ function LibraryPanel({ projectId }: { projectId: string }) {<div className="shrink-0 px-3.5 pb-3"><div className="flex flex-col gap-1.5">{templates.map((t) => (- <div+ <TemplateCardkey={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">- {renamingTemplate === t.id ? (- <Input- autoFocus- value={templateDraft}- className="h-6 w-full text-[12px]"- onChange={(e) => setTemplateDraft(e.target.value)}- onBlur={() => setRenamingTemplate(null)}- onKeyDown={(e) => {- if (e.key === "Enter" && templateDraft.trim()) {- void commitTemplateRename(t.id, templateDraft.trim());- setRenamingTemplate(null);- } else if (e.key === "Escape") setRenamingTemplate(null);- }}- />- ) : (- <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>- <div className="flex shrink-0 flex-col gap-1">- <DropdownMenu>- <DropdownMenuTrigger- render={- <button- title="Template options"- className={cn(- cardIconButton,- "opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"- )}- />- }- >- <MoreHorizontal className="size-3.5" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() => {- setTemplateDraft(t.name);- setRenamingTemplate(t.id);- }}- >- <Pencil /> Rename- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" onClick={() => void removeTemplate(t.id)}>- <Trash2 /> Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- <button- title="Add to this project"- className="grid size-6 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 hover:brightness-110 group-hover:opacity-100"- onClick={() => void addTemplateToProject(projectId, t)}- >- <Plus className="size-3.5" />- </button>- </div>- </div>+ template={t}+ mediaSrc={libraryMediaUrl}+ dragScope="library"+ addTitle="Add to this project"+ onAdd={() => void addTemplateToProject(projectId, t)}+ onRename={(name) => void commitTemplateRename(t.id, name)}+ onDelete={() => void removeTemplate(t.id)}+ onRefDrop={(r) => {+ if (r.scope !== "project") return;+ const asset = useEditor.getState().assets.find((a) => a.id === r.id);+ if (!asset) return;+ void addAssetToLibraryTemplate(projectId, t.id, asset)+ .then((updated) =>+ setTemplates((prev) => prev.map((x) => (x.id === updated.id ? updated : x)))+ )+ .catch(() => void reload());+ }}+ />))}</div></div>@@ -753,6 +800,17 @@ function LibraryPanel({ projectId }: { projectId: string }) {await deleteLibraryFolder(id).catch(() => void reload());}}onDropIds={(ids, fid) => ids.forEach((id) => void move(id, fid))}+ onRefDrop={(ref, fid) => {+ // Project media dropped on a folder tile (a Media card or a+ // timeline clip): save it to the library, filed in that folder.+ if (ref.scope !== "project") return;+ const asset = useEditor.getState().assets.find((a) => a.id === ref.id);+ if (!asset) return;+ void saveAssetToLibrary(projectId, asset)+ .then((saved) => moveLibraryAsset(saved.id, fid))+ .then(() => void reload())+ .catch(() => {});+ }}/></div>) : null}diff --git a/site/src/cut/components/TemplateCard.tsx b/site/src/cut/components/TemplateCard.tsxnew file mode 100644index 00000000..c0405508--- /dev/null+++ b/site/src/cut/components/TemplateCard.tsx@@ -0,0 +1,298 @@+"use client";++import { useState } from "react";+import {+ Captions,+ ChevronDown,+ Film,+ Image as ImageIcon,+ Layers,+ MoreHorizontal,+ Music,+ Pencil,+ Plus,+ Trash2,+ Type,+} from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import {+ clearAssetDrag,+ setCardDragImage,+ setTemplateDragData,+} from "@/cut/lib/assetDrag";+import { useAssetDrop, type AssetRef } from "@/cut/lib/assetRef";+import { cardIconButton } from "@/cut/components/iconButton";+import { formatTime } from "@/cut/lib/time";+import type { LibraryTemplate, TemplateMedia } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++/** A template row card: name and parts, a "…" menu (Rename / extras / Delete)+ * and an optional "+" action, both revealed on hover. Rename swaps the name+ * into an inline input. With `dragScope` set the card drags like any other+ * item — onto the timeline, or onto the Media/Library rail tiles. Clicking the+ * card expands it to preview what's inside: each clip, sound, and title, plus+ * a caption count. Hovering a video/image row floats a live preview (video+ * plays muted); hovering a sound row plays it aloud with a small equalizer in+ * place of the row icon. */+export function TemplateCard({+ template: t,+ mediaSrc,+ dragScope,+ onAdd,+ addTitle,+ onRename,+ onDelete,+ onRefDrop,+ extraMenu,+}: {+ template: LibraryTemplate;+ /** Resolve a template media file to a playable URL (project or library). */+ mediaSrc: (fileName: string) => string;+ /** Where this card lives; makes it draggable with a template payload. */+ dragScope?: "project" | "library";+ /** The "+" action; omit to drop the button (e.g. no open project). */+ onAdd?: () => void;+ addTitle?: string;+ onRename: (name: string) => void;+ onDelete: () => void;+ /** When set, the card accepts media drops (cards and timeline clips) —+ * filter by `ref.scope` and append the item to the template. */+ onRefDrop?: (ref: AssetRef) => void;+ /** Extra menu items rendered between Rename and Delete. */+ extraMenu?: React.ReactNode;+}) {+ const refDrop = useAssetDrop((r) => onRefDrop?.(r));+ const [renaming, setRenaming] = useState(false);+ const [draft, setDraft] = useState("");+ const [expanded, setExpanded] = useState(false);+ const [preview, setPreview] = useState<{+ media: TemplateMedia;+ top: number;+ left: number;+ } | null>(null);+ // Hovered audio row: plays aloud with the row's icon swapped for a small+ // equalizer — sound needs no floating preview.+ const [audioRow, setAudioRow] = useState<number | null>(null);++ const itemCount = t.layers.length + t.audio.length + t.texts.length + t.cues.length;++ // The contents, one row per item, in save order: clips and stills, sounds,+ // titles, then a caption count.+ const speedLen = (x: { in: number; out: number; speed?: number }) =>+ (x.out - x.in) / (x.speed && x.speed > 0 ? x.speed : 1);+ const parts: {+ icon: typeof Film;+ label: string;+ time?: number;+ media?: TemplateMedia;+ }[] = [+ ...t.layers.map((l) => ({+ icon: t.media[l.media]?.type === "image" ? ImageIcon : Film,+ label: t.media[l.media]?.name ?? "Media",+ time: speedLen(l),+ media: t.media[l.media],+ })),+ ...t.audio.map((a) => ({+ icon: Music,+ label: t.media[a.media]?.name ?? "Audio",+ time: speedLen(a),+ media: t.media[a.media],+ })),+ ...t.texts.map((o) => ({+ icon: Type,+ label: o.text || "Title",+ time: o.end - o.start,+ })),+ ...(t.cues.length+ ? [+ {+ icon: Captions,+ label: `${t.cues.length} caption${t.cues.length === 1 ? "" : "s"}`,+ },+ ]+ : []),+ ];++ return (+ <div+ ref={onRefDrop ? refDrop.attachTarget : undefined}+ {...(onRefDrop ? refDrop.targetProps : {})}+ className={cn(+ "group flex flex-col rounded-lg border border-border bg-background px-2.5 py-1.5",+ dragScope ? "cursor-grab active:cursor-grabbing" : "cursor-pointer",+ onRefDrop && refDrop.active && "border-primary bg-primary/10",+ )}+ draggable={!!dragScope}+ onDragStart={(e) => {+ if (!dragScope) return;+ setTemplateDragData(e, dragScope, t);+ setCardDragImage(e, e.currentTarget);+ }}+ onDragEnd={clearAssetDrag}+ onClick={(e) => {+ // Buttons and the rename input own their clicks; the card body toggles.+ if ((e.target as HTMLElement).closest("button,input")) return;+ setExpanded((v) => !v);+ }}+ >+ <div className="flex items-center gap-2">+ <Layers className="size-3.5 shrink-0 text-violet-500" />+ <div className="min-w-0 flex-1">+ {renaming ? (+ <Input+ autoFocus+ value={draft}+ className="h-6 w-full text-[12px]"+ onChange={(e) => setDraft(e.target.value)}+ onBlur={() => setRenaming(false)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && draft.trim()) {+ onRename(draft.trim());+ setRenaming(false);+ } else if (e.key === "Escape") setRenaming(false);+ }}+ />+ ) : (+ <div className="truncate text-[12px] font-medium">{t.name}</div>+ )}+ <div className="flex items-center gap-0.5 text-[10.5px] text-muted-foreground">+ {formatTime(t.duration)} · {itemCount} item{itemCount === 1 ? "" : "s"}+ <ChevronDown+ className={cn(+ "size-3 transition-transform",+ expanded && "rotate-180",+ )}+ />+ </div>+ </div>+ <div className="flex shrink-0 flex-col gap-1">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ title="Template options"+ className={cn(+ cardIconButton,+ "opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100",+ )}+ />+ }+ >+ <MoreHorizontal className="size-3.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-40">+ <DropdownMenuItem+ onClick={() => {+ setDraft(t.name);+ setRenaming(true);+ }}+ >+ <Pencil /> Rename+ </DropdownMenuItem>+ {extraMenu}+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={onDelete}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ {onAdd && (+ <button+ title={addTitle}+ className="grid size-6 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 hover:brightness-110 group-hover:opacity-100"+ onClick={onAdd}+ >+ <Plus className="size-3.5" />+ </button>+ )}+ </div>+ </div>+ {expanded && parts.length > 0 && (+ <div className="mt-1.5 flex flex-col gap-1 border-t border-border pt-1.5">+ {parts.map(({ icon: Icon, label, time, media }, i) => (+ <div+ key={i}+ className={cn(+ "-mx-1 flex min-w-0 shrink-0 items-center gap-1.5 rounded-md px-1 py-0.5 text-[11px] text-muted-foreground",+ media && "hover:bg-muted/60 hover:text-foreground",+ )}+ onMouseEnter={(e) => {+ if (!media) return;+ if (media.type === "audio") {+ setAudioRow(i);+ return;+ }+ const r = e.currentTarget.getBoundingClientRect();+ setPreview({+ media,+ top: Math.max(+ 8,+ Math.min(r.top - 8, window.innerHeight - 160),+ ),+ left: Math.min(r.right + 10, window.innerWidth - 200),+ });+ }}+ onMouseLeave={() => {+ setPreview(null);+ setAudioRow((v) => (v === i ? null : v));+ }}+ >+ {audioRow === i && media ? (+ <span className="flex size-3 shrink-0 items-center justify-center gap-[1.5px] text-[#0F6E56]">+ {[0, 1, 2].map((b) => (+ <span+ key={b}+ className="tpl-eq-bar w-[2px] rounded-full bg-current"+ style={{ animationDelay: `${b * 0.13}s` }}+ />+ ))}+ <audio src={mediaSrc(media.fileName)} autoPlay />+ <style>{`@keyframes tpl-eq{0%,100%{height:25%}50%{height:85%}}.tpl-eq-bar{height:30%;animation:tpl-eq .8s ease-in-out infinite}`}</style>+ </span>+ ) : (+ <Icon className="size-3 shrink-0" />+ )}+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {time != null && (+ <span className="shrink-0 font-mono text-[10px] tabular-nums">+ {formatTime(time)}+ </span>+ )}+ </div>+ ))}+ </div>+ )}+ {preview && (+ <div+ className="pointer-events-none fixed z-50"+ style={{ top: preview.top, left: preview.left }}+ >+ {preview.media.type === "video" ? (+ <video+ src={mediaSrc(preview.media.fileName)}+ autoPlay+ muted+ loop+ playsInline+ className="w-44 rounded-lg border border-border bg-black shadow-lg"+ />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element -- engine media file, not Next-optimizable+ <img+ src={mediaSrc(preview.media.fileName)}+ alt={preview.media.name}+ className="w-44 rounded-lg border border-border shadow-lg"+ />+ )}+ </div>+ )}+ </div>+ );+}diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 03068a5d..738c313d 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -17,11 +17,18 @@ import {draggedLibraryId,draggingAssetId,draggingLibrary,+ draggingTemplate,hasAssetDrag,hasLibraryDrag,+ hasTemplateDrag,} from "@/cut/lib/assetDrag";import { draggingRef, hasRefDrag, type AssetRef } from "@/cut/lib/assetRef";-import { importLibraryAsset, saveAssetToLibrary, saveTemplate } from "@/cut/lib/library";+import {+ addProjectTemplateToTimeline,+ addTemplateToProject,+ importLibraryAsset,+ saveAssetToLibrary,+} from "@/cut/lib/library";import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";import { ensurePeaks, importImage, importStockVideo } from "@/cut/lib/media";@@ -583,6 +590,17 @@ export function Timeline() {className="relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border bg-card select-none"style={{ height: timelineH }}onDragOver={(e) => {+ // A template materializes as a whole arrangement, so it accepts the+ // drop without a single-clip landing preview.+ if (hasTemplateDrag(e)) {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ setAssetDrop(null);+ setOverlayDrop(null);+ setAudioDrop(null);+ setDropType(null);+ return;+ }const isLib = hasLibraryDrag(e);const still = draggingStill(e);const stockVideo = draggingStockVideo(e);@@ -668,8 +686,15 @@ export function Timeline() {const libId = draggedLibraryId(e);const still = draggingStill(e);const stockVideo = draggingStockVideo(e);+ const tpl = draggingTemplate();const projectId = useEditor.getState().projectId;clearAssetDrag();+ if (tpl && projectId) {+ e.preventDefault();+ if (tpl.scope === "project") addProjectTemplateToTimeline(projectId, tpl.template, t);+ else void addTemplateToProject(projectId, tpl.template, t).catch(() => {});+ return;+ }if (libId && lib && projectId) {e.preventDefault();void importLibraryAsset(projectId, lib)@@ -1206,27 +1231,23 @@ 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.+ * Saves the current multi-selection as a by-reference template in this+ * project's Media — the source media plus the edit that arranges it, never a+ * flattened video. Re-adding it re-materializes editable clips, overlays, and+ * captions; the Media panel can push it to the shared Library.*/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 save = () => {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");- }+ if (!input) return;+ s.addTemplate(input);+ setState("done");+ setTimeout(() => setState("idle"), 1800);};return (diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsxindex 48584382..fac9b683 100644--- a/site/src/cut/components/desktopFolders.tsx+++ b/site/src/cut/components/desktopFolders.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useRef, useState } from "react";+import { Fragment, useEffect, useRef, useState } from "react";import { Folder, MoreHorizontal, Pencil, Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";import {@@ -11,6 +11,8 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Input } from "@/components/ui/input";+import type { AssetRef } from "@/cut/lib/assetRef";+import { RefDropZone } from "./RefDropZone";import { cn } from "@/lib/utils";// A desktop-style folder surface shared by the projects home and the library:@@ -208,6 +210,7 @@ export function FolderShelf<F extends DeskFolder>({onDelete,onDropIds,onDropFiles,+ onRefDrop,creating = false,onCreatingChange,}: {@@ -221,6 +224,9 @@ export function FolderShelf<F extends DeskFolder>({onDropIds: (ids: string[], folderId: string) => void;/** Desktop files dropped onto a folder tile — dropped straight into it. */onDropFiles?: (files: FileList, folderId: string) => void;+ /** When set, folder tiles also take media drops from cards and timeline+ * clips — filter by `ref.scope` and file the media into the folder. */+ onRefDrop?: (ref: AssetRef, folderId: string) => void;creating?: boolean;onCreatingChange?: (creating: boolean) => void;}) {@@ -248,26 +254,27 @@ export function FolderShelf<F extends DeskFolder>({{folders.map((f) => {const s = statOf(f.id);const isOver = over === f.id;- return editingId === f.id ? (- <div key={f.id} className="flex w-[92px] flex-col items-start gap-1 px-2 pt-1.5">- <FolderGlyph className="size-[40px]" />- <Input- autoFocus- value={draft}- className="h-6 w-full text-[11px]"- onChange={(e) => setDraft(e.target.value)}- onBlur={closeRename}- onKeyDown={(e) => {- if (e.key === "Enter" && draft.trim()) {- void onRename(f.id, draft.trim());- closeRename();- } else if (e.key === "Escape") closeRename();- }}- />- </div>- ) : (+ if (editingId === f.id)+ return (+ <div key={f.id} className="flex w-[92px] flex-col items-start gap-1 px-2 pt-1.5">+ <FolderGlyph className="size-[40px]" />+ <Input+ autoFocus+ value={draft}+ className="h-6 w-full text-[11px]"+ onChange={(e) => setDraft(e.target.value)}+ onBlur={closeRename}+ onKeyDown={(e) => {+ if (e.key === "Enter" && draft.trim()) {+ void onRename(f.id, draft.trim());+ closeRename();+ } else if (e.key === "Escape") closeRename();+ }}+ />+ </div>+ );+ const tile = (<div- key={f.id}className="group/f relative flex w-[92px] cursor-pointer flex-col items-start rounded-xl px-2 py-1.5 text-left transition-colors hover:bg-muted/60"onClick={() => onOpen(f.id)}onDoubleClick={() => {@@ -336,6 +343,17 @@ export function FolderShelf<F extends DeskFolder>({</DropdownMenu></div>);+ return onRefDrop ? (+ <RefDropZone+ key={f.id}+ onRef={(r) => onRefDrop(r, f.id)}+ activeClassName="rounded-xl bg-primary/10"+ >+ {tile}+ </RefDropZone>+ ) : (+ <Fragment key={f.id}>{tile}</Fragment>+ );})}{creating && (diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 75233e9e..23dc1330 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -17,7 +17,6 @@ import {moveLibraryAsset,renameLibraryFolder,saveAssetToLibrary,- saveTemplate,} from "./library";import { enrichAsset, ensurePeaks, importImage, importStockVideo, importUrlMedia } from "./media";import { refToInlineAudio } from "./refMedia";@@ -936,7 +935,7 @@ export async function runAiTool(id: t.id,name: t.name,duration: round2(t.duration),- parts: t.media.length + t.layers.length + t.audio.length + t.texts.length,+ parts: t.layers.length + t.audio.length + t.texts.length + t.cues.length,})),};}@@ -982,13 +981,12 @@ export async function runAiTool(return {added: t.name,duration: round2(t.duration),- parts: t.media.length + t.layers.length + t.audio.length + t.texts.length,+ parts: t.layers.length + t.audio.length + t.texts.length + t.cues.length,};}case "save_template": {- const projectId = s.projectId;- if (!projectId) throw new ToolError("No project open.");+ if (!s.projectId) throw new ToolError("No project open.");const name = String(input.name ?? "").trim();if (!name) throw new ToolError("A template name is required.");const ids = Array.isArray(input.item_ids) ? input.item_ids.map(String) : [];@@ -1006,7 +1004,7 @@ export async function runAiTool(for (const sel of sels.slice(1)) s.toggleSelect(sel);const built = useEditor.getState().selectionTemplate();if (!built) throw new ToolError("Could not build a template from those items.");- const saved = await saveTemplate(projectId, { ...built, name });+ const saved = useEditor.getState().addTemplate({ ...built, name });return { id: saved.id, name: saved.name, duration: round2(saved.duration) };}diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.tsindex 9c2feadb..807aa680 100644--- a/site/src/cut/lib/assetDrag.ts+++ b/site/src/cut/lib/assetDrag.ts@@ -4,6 +4,7 @@ import type React from "react";import { clearRefDrag, refFromAsset, refFromLibrary, setRefDragData } from "./assetRef";import type { LibraryAsset } from "./library";import { useEditor } from "./store";+import type { LibraryTemplate } from "./types";/** Internal HTML5 drag payload for project media assets. The custom MIME* keeps these drags invisible to the window-level OS-file import overlay,@@ -60,10 +61,93 @@ export function draggedLibraryId(e: React.DragEvent | DragEvent): string | nullreturn dt.getData(LIBRARY_MIME) || null;}+/** A template dragged from the Media panel (project scope) or the Library+ * panel (library scope), so the rail tiles can move it the other way. */+export const TEMPLATE_MIME = "application/x-cut-template";++let inFlightTemplate: { scope: "project" | "library"; template: LibraryTemplate } | null = null;++export function setTemplateDragData(+ e: React.DragEvent,+ scope: "project" | "library",+ template: LibraryTemplate+) {+ e.dataTransfer.setData(TEMPLATE_MIME, template.id);+ e.dataTransfer.effectAllowed = "copy";+ inFlightTemplate = { scope, template };+}++/** The template drag in flight, readable during `dragover`. */+export function draggingTemplate() {+ return inFlightTemplate;+}++export function hasTemplateDrag(e: React.DragEvent | DragEvent): boolean {+ const dt = "dataTransfer" in e ? e.dataTransfer : null;+ return !!dt && Array.from(dt.types).includes(TEMPLATE_MIME);+}++/** Use the card itself as the drag ghost: a clone at rendered size, so the+ * ghost matches the card exactly — rounded corners, fills, labels. Live+ * `<video>`/`<canvas>` content is baked into the clone (clones of those paint+ * blank), and hover-revealed controls drop out since the clone is not hovered.+ * The clone lives off-screen just long enough for the browser to snapshot it. */+export function setCardDragImage(e: React.DragEvent, el: HTMLElement) {+ const rect = el.getBoundingClientRect();+ const clone = el.cloneNode(true) as HTMLElement;+ const srcMedia = el.querySelectorAll<HTMLElement>("video, canvas");+ clone.querySelectorAll<HTMLElement>("video, canvas").forEach((node, i) => {+ const src = srcMedia[i];+ if (!src) return;+ const r = src.getBoundingClientRect();+ const c = document.createElement("canvas");+ c.width = Math.max(1, Math.round(r.width * devicePixelRatio));+ c.height = Math.max(1, Math.round(r.height * devicePixelRatio));+ c.className = node.className;+ c.style.cssText = node.style.cssText;+ c.style.width = `${r.width}px`;+ c.style.height = `${r.height}px`;+ const ctx = c.getContext("2d");+ if (ctx) {+ try {+ if (src instanceof HTMLVideoElement) {+ // Match object-cover: scale to fill and center-crop.+ const vw = src.videoWidth || r.width;+ const vh = src.videoHeight || r.height;+ const scale = Math.max(c.width / vw, c.height / vh);+ ctx.drawImage(+ src,+ (c.width - vw * scale) / 2,+ (c.height - vh * scale) / 2,+ vw * scale,+ vh * scale+ );+ } else {+ ctx.drawImage(src as HTMLCanvasElement, 0, 0, c.width, c.height);+ }+ } catch {+ // A frame that cannot be painted just leaves that slot blank.+ }+ }+ node.replaceWith(c);+ });+ clone.style.position = "absolute";+ clone.style.top = "-1000px";+ clone.style.left = "-1000px";+ clone.style.width = `${rect.width}px`;+ clone.style.height = `${rect.height}px`;+ clone.style.margin = "0";+ clone.style.pointerEvents = "none";+ document.body.appendChild(clone);+ e.dataTransfer.setDragImage(clone, e.clientX - rect.left, e.clientY - rect.top);+ setTimeout(() => clone.remove(), 0);+}+/** Clear the in-flight ids; call on `dragend` and after a drop. */export function clearAssetDrag() {inFlightAssetId = null;inFlightLibrary = null;+ inFlightTemplate = null;clearRefDrag();}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 8cdb5ed5..013704ff 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -4,7 +4,7 @@ import { apiFetch, apiJson, apiUrl } from "./api";import { enrichAsset } from "./media";import { useEditor } from "./store";import type { LibraryTemplate, MediaAsset, TemplateMedia, TemplateSaveInput } from "./types";-import { mediaUrl } from "./types";+import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";export interface LibrarySource {url: string;@@ -164,6 +164,41 @@ export async function saveTemplate(return body;}+/** Append a project asset to a library template as one more part at its end:+ * the engine copies the file into the library and returns the updated+ * template. */+export async function addAssetToLibraryTemplate(+ projectId: string,+ templateId: string,+ asset: MediaAsset+): Promise<LibraryTemplate> {+ const len = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;+ const part =+ asset.type === "audio"+ ? { audio: { in: 0, out: len, volume: 1 } }+ : { layer: { in: 0, out: len, muted: false, track: 1, asClip: true } };+ const res = await apiFetch(`/api/cut/library/templates/${templateId}/add`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ projectId,+ media: {+ fileName: asset.fileName,+ name: asset.name,+ type: asset.type,+ duration: asset.duration,+ width: asset.width,+ height: asset.height,+ },+ extend: len,+ ...part,+ }),+ });+ const body = await apiJson<LibraryTemplate>(res);+ if (!res.ok) throw new Error(body.error ?? "Could not add to the template.");+ return body;+}+export async function renameTemplate(id: string, name: string): Promise<void> {const res = await apiFetch(`/api/cut/library/templates/${id}`, {method: "PUT",@@ -182,7 +217,8 @@ export async function deleteTemplate(id: string): Promise<void> {* overlays, and captions at the playhead — everything editable, nothing baked. */export async function addTemplateToProject(projectId: string,- template: LibraryTemplate+ template: LibraryTemplate,+ at?: number): Promise<void> {const res = await apiFetch(`/api/cut/library/templates/${template.id}/use`, {method: "POST",@@ -194,7 +230,8 @@ export async function addTemplateToProject(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.+ // the layer/audio media indices resolve against this array. Enrichment gives+ // the new clips their filmstrip thumbnails and waveform peaks.const assetIds = body.media.map((m) => {const asset: MediaAsset = {id: crypto.randomUUID().slice(0, 8),@@ -207,9 +244,64 @@ export async function addTemplateToProject(url: mediaUrl(projectId, m.fileName),};s.addAsset(asset);+ void enrichAsset(asset);+ return asset.id;+ });+ s.insertTemplate(template, assetIds, at ?? useEditor.getState().currentTime);+}++/** Copy a library template into the project as a project template: its media+ * land in the project's media folder and the template joins the Media panel.+ * Nothing is placed on the timeline. */+export async function importTemplateToProject(+ 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 apiJson<{ media?: TemplateMedia[] }>(res);+ if (!res.ok || !body.media) throw new Error(body.error ?? "Could not add the template.");+ useEditor.getState().addTemplate({+ name: template.name,+ duration: template.duration,+ media: body.media,+ layers: template.layers,+ audio: template.audio,+ texts: template.texts,+ cues: template.cues,+ });+}++/** Materialize a project template onto the timeline at the playhead. Its media+ * already live in the project; assets are matched by file name and re-registered+ * if the Media entry was removed. */+export function addProjectTemplateToTimeline(+ projectId: string,+ template: LibraryTemplate,+ at?: number+) {+ const s = useEditor.getState();+ const assetIds = template.media.map((m) => {+ const existing = s.assets.find((a) => a.fileName === m.fileName);+ if (existing) return existing.id;+ 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);+ void enrichAsset(asset);return asset.id;});- s.insertTemplate(template, assetIds, useEditor.getState().currentTime);+ useEditor.getState().insertTemplate(template, assetIds, at ?? useEditor.getState().currentTime);}/** Copy a project asset into the shared library for reuse. */diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 73238c8a..5d16936e 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -279,6 +279,14 @@ export interface EditorState {/** 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;+ /** Templates saved in this project (shown in the Media panel; persisted on+ * the doc). Their media reference project files by name. */+ templates: LibraryTemplate[];+ addTemplate: (input: TemplateSaveInput) => LibraryTemplate;+ renameTemplate: (id: string, name: string) => void;+ removeTemplate: (id: string) => void;+ /** Append a project asset to a template as one more part at its end. */+ addAssetToTemplate: (templateId: string, assetId: string) => void;select: (sel: Selection) => void;/** ⌘/⇧-click: add the item to the selection (or remove it if already in),* making it the new primary. */@@ -519,6 +527,7 @@ export const useEditor = create<EditorState>((set, get) => {clips: [],audioClips: [],overlays: [],+ templates: [],aspect: "9:16",fadeIn: 0,fadeOut: 0,@@ -558,6 +567,7 @@ export const useEditor = create<EditorState>((set, get) => {clips: [],audioClips: [],overlays: [],+ templates: [],aspect: "9:16",fadeIn: 0,fadeOut: 0,@@ -614,6 +624,7 @@ export const useEditor = create<EditorState>((set, get) => {clips: merged,audioClips: doc.audioClips,overlays: doc.overlays,+ templates: doc.templates ?? [],aspect: doc.aspect ?? "9:16",fadeIn: doc.fadeIn ?? 0,fadeOut: doc.fadeOut ?? 0,@@ -1498,6 +1509,55 @@ export const useEditor = create<EditorState>((set, get) => {return { name: "Template", duration, media, layers, audio, texts, cues };},+ addTemplate: (input) => {+ const t: LibraryTemplate = { id: uid(), addedAt: Date.now(), ...input };+ set({ templates: [t, ...get().templates] });+ return t;+ },++ renameTemplate: (id, name) =>+ set({+ templates: get().templates.map((t) => (t.id === id ? { ...t, name } : t)),+ }),++ removeTemplate: (id) => set({ templates: get().templates.filter((t) => t.id !== id) }),++ addAssetToTemplate: (templateId, assetId) => {+ const s = get();+ const t = s.templates.find((x) => x.id === templateId);+ const a = s.assets.find((x) => x.id === assetId);+ if (!t || !a) return;+ // Reuse the media entry when the template already references this file.+ const existing = t.media.findIndex((m) => m.fileName === a.fileName);+ const media =+ existing >= 0+ ? t.media+ : [+ ...t.media,+ { fileName: a.fileName, name: a.name, type: a.type, duration: a.duration, width: a.width, height: a.height },+ ];+ const mi = existing >= 0 ? existing : media.length - 1;+ const len = a.type === "image" ? IMAGE_CLIP_SECONDS : a.duration;+ const updated: LibraryTemplate =+ a.type === "audio"+ ? {+ ...t,+ media,+ duration: t.duration + len,+ audio: [...t.audio, { media: mi, start: t.duration, in: 0, out: len, volume: 1 }],+ }+ : {+ ...t,+ media,+ duration: t.duration + len,+ layers: [+ ...t.layers,+ { media: mi, start: t.duration, in: 0, out: len, muted: false, track: 1, asClip: true },+ ],+ };+ set({ templates: s.templates.map((x) => (x.id === templateId ? updated : x)) });+ },+insertTemplate: (template, assetIds, offset) => {push();const usable = template.layers.filter((l) => assetIds[l.media]);@@ -2365,6 +2425,7 @@ export function serializeDoc(s: {clips: VideoClip[];audioClips: AudioClip[];overlays: TextOverlay[];+ templates: LibraryTemplate[];aspect: Aspect;fadeIn: number;fadeOut: number;@@ -2379,6 +2440,7 @@ export function serializeDoc(s: {clips: s.clips,audioClips: s.audioClips,overlays: s.overlays,+ templates: s.templates,aspect: s.aspect,fadeIn: s.fadeIn,fadeOut: s.fadeOut,diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex d35874f6..4bc2bcdc 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -468,6 +468,9 @@ export interface ProjectDoc {publishedAt?: string; // ISO date (yyyy-mm-dd)links?: string[];};+ /** Templates saved in this project (their media reference project files by+ * name). Adding one to the shared Library copies its media out. */+ templates?: LibraryTemplate[];/** Which project folder this belongs to (null/absent = ungrouped). */folderId?: string | null;/** In-progress or finished brief-to-video run (genvideo). Persisted so adiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 41117bb2..f31950c2 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -411,7 +411,7 @@ export const AI_TOOLS: AiToolDef[] = [{name: "save_template",description:- "Save timeline items as a reusable Library template, kept by reference — the source media plus the edit arranging it, re-editable when added back. Pass the ids of the items to include: video clips (any track), soundtrack clips, titles, and subtitle cues.",+ "Save timeline items as a reusable template in this project's Media, kept by reference — the source media plus the edit arranging it, re-editable when added back. The user can push it to the shared Library from the Media panel. Pass the ids of the items to include: video clips (any track), soundtrack clips, titles, and subtitle cues.",inputSchema: obj({name: str("Template name"),item_ids: {diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex d7447961..f667c302 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -1,5 +1,6 @@import {addFromProject,+ addMediaToTemplate,addUpload,createFolder,deleteFolder,@@ -55,6 +56,18 @@ export const libraryApi = {}},+ /** Append a project media file to a template as one more part. */+ async addToTemplate(req: Request, { id }: { id: string }) {+ try {+ const { projectId, ...input } = (await req.json()) as { projectId: string } & Parameters<+ typeof addMediaToTemplate+ >[2];+ return Response.json(await addMediaToTemplate(id, projectId, input));+ } catch (e) {+ return caught(e, "Could not add to the template.");+ }+ },+async renameTemplate(req: Request, { id }: { id: string }) {try {const { name } = (await req.json()) as { name?: string };diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex 5a8ded16..d70bdc15 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -119,6 +119,7 @@ export const projectsApi = {? []: existing.overlayClips,overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,+ templates: Array.isArray(body.templates) ? body.templates : existing.templates,aspect: body.aspect === "9:16" || body.aspect === "16:9" ? body.aspect : existing.aspect,fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex f94a4612..7a2d2557 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -57,6 +57,7 @@ export const CUT_ROUTES: CutRoute[] = [{ 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: "POST", path: "/api/cut/library/templates/:id/add", handler: (req, p) => libraryApi.addToTemplate(req, { id: p.id }) },{ method: "PUT", path: "/api/cut/library/templates/:id", handler: (req, p) => libraryApi.renameTemplate(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) },diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex c98312ef..aa4c6e38 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -419,6 +419,42 @@ export async function useTemplate(templateId: string, projectId: string) {return { template, media };}+/** Append one project media file to a template as a part at its end: the file+ * is copied into the library (templates own their media privately) and the+ * given layer/audio shape lands re-pointed at the new media entry, starting at+ * the template's current end. `extend` grows the stored duration. */+export async function addMediaToTemplate(+ templateId: string,+ projectId: string,+ input: {+ media: Omit<TemplateMedia, "fileName"> & { fileName: string };+ layer?: Omit<TemplateLayer, "media" | "start">;+ audio?: Omit<TemplateAudio, "media" | "start">;+ extend: number;+ }+): Promise<LibraryTemplate> {+ const src = projectMediaPath(projectId, input.media.fileName);+ if (!(await exists(src))) throw new Error("Media file not found in project.");+ await mkdir(LIB_MEDIA, { recursive: true });+ const dest = await freeName(input.media.fileName);+ await copyFile(src, libMediaPath(dest));+ try {+ return await mutateIndex((idx) => {+ const t = (idx.templates ?? []).find((x) => x.id === templateId);+ if (!t) throw new Error("Template not found.");+ const mi = t.media.length;+ t.media = [...t.media, { ...input.media, fileName: dest }];+ if (input.audio) t.audio = [...t.audio, { ...input.audio, media: mi, start: t.duration }];+ else if (input.layer) t.layers = [...t.layers, { ...input.layer, media: mi, start: t.duration }];+ t.duration += input.extend;+ return t;+ });+ } catch (e) {+ await rm(libMediaPath(dest), { force: true });+ throw e;+ }+}+export async function renameTemplate(id: string, name: string): Promise<LibraryTemplate> {const trimmed = name.trim();if (!trimmed) throw new Error("Template name required.");