Skip to content

Open source CapCut alternative.

TypeScript

feat(site): Cut background export & authoritative export delete

David Le5f91f6289e37
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 1c9f0761..bc55c71f 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -5,10 +5,13 @@ import Link from "next/link";
import { Clapperboard, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { apiFetch } from "@/cut/lib/api";
+import { renderPreviewProxy } from "@/cut/lib/exportClient";
+import { useExport } from "@/cut/lib/exportStore";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
import { serializeDoc, totalDuration, useEditor } from "@/cut/lib/store";
import { AiPanel } from "./AiPanel";
import { ExportDialog } from "./ExportDialog";
+import { ExportStatus } from "./ExportStatus";
import { Inspector } from "./Inspector";
import { Preview } from "./Preview";
import { SidePanel } from "./SidePanel";
@@ -21,6 +24,9 @@ export function Editor({ projectId }: { projectId: string }) {
const dropActive = useEditor((s) => s.dropActive);
const exportOpen = useEditor((s) => s.exportOpen);
const aiOpen = useEditor((s) => s.aiOpen);
+ // The inspector only earns its column when something is selected; otherwise it
+ // is an empty white panel, so collapse it and let the preview take the space.
+ const hasInspector = useEditor((s) => s.selection != null);
const [importing, setImporting] = useState(0);
const dragDepth = useRef(0);
@@ -32,6 +38,66 @@ export function Editor({ projectId }: { projectId: string }) {
.then(() => {
for (const asset of useEditor.getState().assets) void enrichAsset(asset);
});
+ // Rejoin an export that's still rendering (e.g. after a reload).
+ void useExport.getState().reconnect(projectId);
+ }, [projectId]);
+
+ // Keep the project card's hover proxy fresh: rebuild it a few seconds after
+ // the cut settles. Best-effort and single-flight; skips when there's no cut.
+ useEffect(() => {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let rendering = false;
+ const render = async () => {
+ const s = useEditor.getState();
+ if (rendering || !s.loaded || s.projectId !== projectId || s.clips.length === 0) return;
+ rendering = true;
+ try {
+ await renderPreviewProxy(
+ projectId,
+ {
+ assets: s.assets,
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ subtitles: s.subtitles,
+ },
+ s.aspect
+ );
+ } finally {
+ rendering = false;
+ }
+ };
+ let last: {
+ clips: unknown;
+ audioClips: unknown;
+ overlays: unknown;
+ subtitles: unknown;
+ aspect: string;
+ } | null = null;
+ const unsub = useEditor.subscribe((s) => {
+ if (!s.loaded || s.projectId !== projectId) return;
+ const changed =
+ last !== null &&
+ (s.clips !== last.clips ||
+ s.audioClips !== last.audioClips ||
+ s.overlays !== last.overlays ||
+ s.subtitles !== last.subtitles ||
+ s.aspect !== last.aspect);
+ last = {
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ subtitles: s.subtitles,
+ aspect: s.aspect,
+ };
+ if (!changed) return; // first tick just primes the baseline
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => void render(), 8000);
+ });
+ return () => {
+ unsub();
+ if (timer) clearTimeout(timer);
+ };
}, [projectId]);
// Autosave: debounce document changes into PUT /api/cut/projects/<id>.
@@ -79,6 +145,9 @@ export function Editor({ projectId }: { projectId: string }) {
s.publish.tags !== last.publish?.tags ||
s.publish.soundTitle !== last.publish?.soundTitle ||
s.publish.handle !== last.publish?.handle ||
+ s.notes.text !== last.notes?.text ||
+ s.notes.publishedAt !== last.notes?.publishedAt ||
+ s.notes.links.join("") !== (last.notes?.links ?? []).join("") ||
s.projectName !== lastName;
if (!changed) return;
last = serializeDoc(s);
@@ -232,18 +301,23 @@ export function Editor({ projectId }: { projectId: string }) {
}
return (
- <div className="flex h-screen min-w-[900px] select-none overflow-hidden">
+ <div className="flex h-screen min-w-[900px] overflow-hidden">
<div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto]">
<TopBar />
- <div className="grid min-h-0 grid-cols-[auto_minmax(0,1fr)_272px]">
+ <div
+ className={`grid min-h-0 ${
+ hasInspector ? "grid-cols-[auto_minmax(0,1fr)_272px]" : "grid-cols-[auto_minmax(0,1fr)]"
+ }`}
+ >
<SidePanel projectId={projectId} onImport={importFiles} importing={importing > 0} />
<Preview />
- <Inspector />
+ {hasInspector && <Inspector />}
</div>
<Timeline />
</div>
{aiOpen && <AiPanel onClose={() => useEditor.getState().setAiOpen(false)} />}
{exportOpen && <ExportDialog />}
+ <ExportStatus />
{dropActive && (
<div className="fixed inset-0 z-60 grid place-items-center bg-background/70 backdrop-blur-md">
<div className="pointer-events-none flex flex-col items-center gap-2 rounded-2xl border-2 border-dashed border-[#0a84ff] bg-[#0a84ff]/10 px-12 py-9 text-[#0a84ff]">
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index 0ef86a4f..682db129 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useMemo, useState } from "react";
import { Check, FolderCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
@@ -10,27 +10,20 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import {
- EXPORT_PRESETS,
- originalSettings,
- presetSettings,
- startExport,
- type ExportHandle,
-} from "@/cut/lib/exportClient";
+import { EXPORT_PRESETS, originalSettings, presetSettings } from "@/cut/lib/exportClient";
+import { useExport } from "@/cut/lib/exportStore";
import { useEditor } from "@/cut/lib/store";
import { cn } from "@/lib/utils";
-type Phase =
- | { kind: "idle" }
- | { kind: "running"; stage: string; ratio: number }
- | { kind: "done"; outName: string }
- | { kind: "error"; message: string };
-
export function ExportDialog() {
const setExportOpen = useEditor((s) => s.setExportOpen);
const aspect = useEditor((s) => s.aspect);
const clips = useEditor((s) => s.clips);
const assets = useEditor((s) => s.assets);
+ const status = useExport((s) => s.status);
+ const stage = useExport((s) => s.stage);
+ const ratio = useExport((s) => s.ratio);
+ const error = useExport((s) => s.error);
// "Original" leads: sized from the footage on the timeline, so it is always
// the highest option. The fixed presets follow, flipped to the aspect.
const presets = useMemo(
@@ -51,13 +44,11 @@ export function ExportDialog() {
[aspect, clips, assets]
);
const [presetId, setPresetId] = useState("original");
- const [phase, setPhase] = useState<Phase>({ kind: "idle" });
- const handleRef = useRef<ExportHandle | null>(null);
-
- useEffect(() => () => handleRef.current?.cancel(), []);
+ // Closing never cancels a running render — it keeps going in the background
+ // and the status chip tracks it. A finished/failed export is cleared on close.
const close = () => {
- handleRef.current?.cancel();
+ if (useExport.getState().status !== "running") useExport.getState().dismiss();
setExportOpen(false);
};
@@ -65,24 +56,13 @@ export function ExportDialog() {
const s = useEditor.getState();
if (!s.projectId) return;
const settings = (presets.find((p) => p.id === presetId) ?? presets[0]).settings;
- const handle = startExport(
- s.projectId,
- {
- assets: s.assets,
- clips: s.clips,
- audioClips: s.audioClips,
- overlays: s.overlays,
- subtitles: s.subtitles,
- },
- settings,
- (stage, ratio) => setPhase({ kind: "running", stage, ratio })
- );
- handleRef.current = handle;
- handle.done
- .then(({ outName }) => setPhase({ kind: "done", outName }))
- .catch((err: unknown) =>
- setPhase({ kind: "error", message: err instanceof Error ? err.message : String(err) })
- );
+ useExport.getState().start(s.projectId, {
+ assets: s.assets,
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ subtitles: s.subtitles,
+ }, settings);
};
return (
@@ -92,7 +72,7 @@ export function ExportDialog() {
<DialogTitle>Export</DialogTitle>
</DialogHeader>
- {phase.kind === "idle" && (
+ {status === "idle" && (
<>
<div className="flex flex-col gap-2" role="radiogroup" aria-label="Export preset">
{presets.map((p) => (
@@ -121,27 +101,34 @@ export function ExportDialog() {
</>
)}
- {phase.kind === "running" && (
+ {status === "running" && (
<div className="pt-1">
<div className="h-1.5 overflow-hidden rounded-full bg-secondary">
<div
className="h-full rounded-full bg-primary transition-[width] duration-300"
- style={{ width: `${Math.round(phase.ratio * 100)}%` }}
+ style={{ width: `${Math.round(ratio * 100)}%` }}
/>
</div>
<div className="mt-2.5 flex justify-between text-xs text-muted-foreground">
- <span>{phase.stage}</span>
- <span className="font-mono tabular-nums">{Math.round(phase.ratio * 100)}%</span>
+ <span>{stage}</span>
+ <span className="font-mono tabular-nums">{Math.round(ratio * 100)}%</span>
</div>
<DialogFooter className="mt-4">
- <Button variant="ghost" onClick={close}>
+ <Button
+ variant="ghost"
+ onClick={() => {
+ useExport.getState().cancel();
+ setExportOpen(false);
+ }}
+ >
Cancel
</Button>
+ <Button onClick={() => setExportOpen(false)}>Continue in background</Button>
</DialogFooter>
</div>
)}
- {phase.kind === "done" && (
+ {status === "done" && (
<div className="flex flex-col items-center pt-2 text-center">
<span className="mb-3 grid size-11 place-items-center rounded-full bg-[#30d158] text-[#04180b]">
<Check className="size-5" />
@@ -152,26 +139,26 @@ export function ExportDialog() {
Saved into the project’s exports folder and downloaded.
</div>
<DialogFooter className="mt-4 w-full">
- <Button className="w-full" onClick={() => setExportOpen(false)}>
+ <Button className="w-full" onClick={close}>
Done
</Button>
</DialogFooter>
</div>
)}
- {phase.kind === "error" && (
+ {status === "error" && (
<div>
<div className="mb-2 text-sm font-medium text-destructive">
Export didn’t finish
</div>
<pre className="max-h-36 overflow-auto rounded-lg border border-border bg-background p-2.5 font-mono text-[10.5px] leading-relaxed break-words whitespace-pre-wrap text-muted-foreground select-text">
- {phase.message}
+ {error}
</pre>
<DialogFooter className="mt-4">
<Button variant="ghost" onClick={close}>
Close
</Button>
- <Button onClick={() => setPhase({ kind: "idle" })}>Try again</Button>
+ <Button onClick={() => useExport.getState().dismiss()}>Try again</Button>
</DialogFooter>
</div>
)}
diff --git a/site/src/cut/components/ExportStatus.tsx b/site/src/cut/components/ExportStatus.tsx
new file mode 100644
index 00000000..b0acc1c7
--- /dev/null
+++ b/site/src/cut/components/ExportStatus.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { Check, FolderOpen, Loader2, X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { revealExport } from "@/cut/lib/exportClient";
+import { useExport } from "@/cut/lib/exportStore";
+import { useEditor } from "@/cut/lib/store";
+
+/** A small floating chip that tracks a background export after the dialog is
+ * closed, so the render keeps going and the result is still one click away. */
+export function ExportStatus() {
+ const status = useExport((s) => s.status);
+ const stage = useExport((s) => s.stage);
+ const ratio = useExport((s) => s.ratio);
+ const outName = useExport((s) => s.outName);
+ const projectId = useExport((s) => s.projectId);
+ const exportOpen = useEditor((s) => s.exportOpen);
+
+ // The dialog owns the UI while it's open.
+ if (exportOpen || status === "idle") return null;
+
+ return (
+ <div className="fixed right-4 bottom-4 z-50 flex items-center gap-2.5 rounded-xl border border-border bg-card px-3 py-2 shadow-lg">
+ {status === "running" && (
+ <>
+ <Loader2 className="size-4 animate-spin text-primary" />
+ <span className="text-xs font-medium">
+ Exporting… <span className="tabular-nums text-muted-foreground">{Math.round(ratio * 100)}%</span>
+ </span>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Cancel export"
+ onClick={() => useExport.getState().cancel()}
+ >
+ <X />
+ </Button>
+ </>
+ )}
+ {status === "done" && (
+ <>
+ <span className="grid size-5 place-items-center rounded-full bg-[#30d158] text-[#04180b]">
+ <Check className="size-3" />
+ </span>
+ <span className="text-xs font-medium">Export ready</span>
+ {projectId && outName && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Show in Finder"
+ title="Show in Finder"
+ onClick={() => void revealExport(projectId, outName).catch(() => {})}
+ >
+ <FolderOpen />
+ </Button>
+ )}
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Dismiss"
+ onClick={() => useExport.getState().dismiss()}
+ >
+ <X />
+ </Button>
+ </>
+ )}
+ {status === "error" && (
+ <>
+ <span className="text-xs font-medium text-destructive">Export failed</span>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Dismiss"
+ onClick={() => useExport.getState().dismiss()}
+ >
+ <X />
+ </Button>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 20b557a9..99c5c419 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -26,8 +26,10 @@ import {
addLibraryAssetToProject,
deleteFromLibrary,
fetchLibrary,
+ moveLibraryAsset,
saveAssetToLibrary,
type LibraryAsset,
+ type LibraryFolder,
} from "@/cut/lib/library";
import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";
import { useEditor } from "@/cut/lib/store";
@@ -182,11 +184,15 @@ function MediaPanel({
setDeletingExport(null);
try {
await deleteExport(projectId, it.file);
- setExports((prev) => prev.filter((e) => e.file !== it.file));
- if (preview?.file === it.file) setPreview(null);
} catch {
- // Leave the list as-is on failure; it mirrors what's on disk.
+ // Fall through and re-read the folder so the list mirrors disk truth
+ // (a failed delete stays visible rather than reappearing later).
}
+ const list = await apiFetch(`/api/cut/projects/${projectId}/exports`)
+ .then((r) => (r.ok ? (r.json() as Promise<ExportItem[]>) : []))
+ .catch(() => [] as ExportItem[]);
+ setExports(list);
+ if (preview && !list.some((e) => e.file === preview.file)) setPreview(null);
};
return (
@@ -466,10 +472,20 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
function LibraryPanel({ projectId }: { projectId: string }) {
const [assets, setAssets] = useState<LibraryAsset[] | null>(null);
+ const [folders, setFolders] = useState<LibraryFolder[]>([]);
+ const [activeFolder, setActiveFolder] = useState<string | null>(null);
const [deleting, setDeleting] = useState<LibraryAsset | null>(null);
+ const reload = () =>
+ fetchLibrary()
+ .then((d) => {
+ setAssets(d.assets);
+ setFolders(d.folders);
+ })
+ .catch(() => setAssets([]));
+
useEffect(() => {
- void fetchLibrary().then(setAssets).catch(() => setAssets([]));
+ void reload();
}, []);
const remove = async () => {
@@ -481,28 +497,57 @@ function LibraryPanel({ projectId }: { projectId: string }) {
await deleteFromLibrary(id);
} catch {
// Server delete failed; pull a fresh list so the UI stays truthful.
- void fetchLibrary().then(setAssets).catch(() => {});
+ void reload();
}
};
+ const move = async (assetId: string, folderId: string | null) => {
+ setAssets((prev) => (prev ?? []).map((a) => (a.id === assetId ? { ...a, folderId } : a)));
+ await moveLibraryAsset(assetId, folderId).catch(() => void reload());
+ };
+
+ const shown = (assets ?? []).filter((a) =>
+ activeFolder === null ? true : (a.folderId ?? null) === activeFolder
+ );
+
return (
<>
<PanelHead title="Library" />
- <p className="px-4 pb-3 text-[11.5px] leading-relaxed text-muted-foreground">
- Reusable clips & music. Click to add a copy to this project.
+ <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>
+ {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) => (
+ <button
+ key={f.id ?? "all"}
+ className={cn(
+ "shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors",
+ activeFolder === f.id
+ ? "border-primary bg-primary/10 text-primary"
+ : "border-border text-muted-foreground hover:text-foreground"
+ )}
+ onClick={() => setActiveFolder(f.id)}
+ >
+ {f.name}
+ </button>
+ ))}
+ </div>
+ )}
{assets === null ? (
<div className="grid flex-1 place-items-center text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
</div>
- ) : assets.length === 0 ? null : (
+ ) : shown.length === 0 ? null : (
<div className="grid grid-cols-2 content-start gap-2.5 overflow-y-auto px-3.5 pb-3.5">
- {assets.map((a) => (
+ {shown.map((a) => (
<LibraryCard
key={a.id}
asset={a}
+ folders={folders}
onUse={() => void addLibraryAssetToProject(projectId, a)}
onDelete={() => setDeleting(a)}
+ onMove={(folderId) => void move(a.id, folderId)}
/>
))}
</div>
@@ -557,6 +602,8 @@ function CopyChip({ text, label }: { text: string; label: string }) {
function PublishPanel() {
const publish = useEditor((s) => s.publish);
const setPublish = useEditor((s) => s.setPublish);
+ const notes = useEditor((s) => s.notes);
+ const setNotes = useEditor((s) => s.setNotes);
const tagsLine = normalizeTags(publish.tags);
const combined = [publish.caption.trim(), tagsLine].filter(Boolean).join("\n\n");
const count = combined.length;
@@ -623,6 +670,31 @@ function PublishPanel() {
</p>
</div>
+ <div className="flex flex-col gap-1.5 border-t border-border pt-4">
+ <span className={field}>Notes</span>
+ <label className="flex items-center justify-between gap-2 text-[12px] text-muted-foreground">
+ Published
+ <input
+ type="date"
+ className="notes-date rounded-lg border border-input bg-transparent px-2 py-1 text-[12px] outline-none focus:border-ring"
+ value={notes.publishedAt}
+ onChange={(e) => setNotes({ publishedAt: e.target.value })}
+ />
+ </label>
+ <textarea
+ className="notes-links min-h-[54px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-[11.5px] leading-relaxed outline-none focus:border-ring"
+ placeholder={"Links, one per line\nhttps://tiktok.com/…"}
+ value={notes.links.join("\n")}
+ onChange={(e) => setNotes({ links: e.target.value.split("\n") })}
+ />
+ <textarea
+ className="notes-text min-h-[70px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
+ placeholder="Anything worth remembering about this cut…"
+ value={notes.text}
+ onChange={(e) => setNotes({ text: e.target.value })}
+ />
+ </div>
+
<div className="mt-1 flex flex-col gap-2">
<Button
className="w-full"
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index f2d71e04..92def260 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -2,7 +2,7 @@
import { apiFetch, apiUrl } from "./api";
import { clipSpeed, getClipSpans, totalDuration } from "./store";
-import { cueOverlay } from "./subtitles";
+import { captionStyle, cueOverlay } from "./subtitles";
import { renderOverlayPng } from "./textRender";
import { FRAME } from "./types";
import type { Aspect, AudioClip, MediaAsset, SubtitlesBlock, TextOverlay, VideoClip } from "./types";
@@ -79,11 +79,26 @@ export async function revealExport(projectId: string, file: string) {
);
}
-/** Delete a rendered export from the project folder. */
+/** Delete a rendered export from the project folder. Throws on failure so the
+ * UI can stay truthful instead of optimistically dropping a file that's still
+ * on disk (which is why deleted exports used to reappear on the next refresh). */
export async function deleteExport(projectId: string, file: string) {
- await apiFetch(`/api/cut/projects/${projectId}/exports/${encodeURIComponent(file)}`, {
- method: "DELETE",
- });
+ const res = await apiFetch(
+ `/api/cut/projects/${projectId}/exports/${encodeURIComponent(file)}`,
+ { method: "DELETE" }
+ );
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { error?: string };
+ throw new Error(body.error ?? "Could not delete the export.");
+ }
+}
+
+export interface ExportDoc {
+ assets: MediaAsset[];
+ clips: VideoClip[];
+ audioClips: AudioClip[];
+ overlays: TextOverlay[];
+ subtitles: SubtitlesBlock;
}
export interface ExportHandle {
@@ -91,118 +106,132 @@ export interface ExportHandle {
done: Promise<{ outName: string }>;
}
-export function startExport(
+/** Build the export FormData from the cut. Media already lives in the project
+ * folder — the spec references it by file name; only overlay PNGs travel with
+ * the request. Shared by full exports and the low-res hover proxy. */
+async function buildExportForm(
projectId: string,
- doc: {
- assets: MediaAsset[];
- clips: VideoClip[];
- audioClips: AudioClip[];
- overlays: TextOverlay[];
- subtitles: SubtitlesBlock;
- },
+ doc: ExportDoc,
settings: ExportSettings,
- onProgress: (stage: string, ratio: number) => void
-): ExportHandle {
- let jobId: string | null = null;
- let canceled = false;
+ target: "export" | "preview"
+): Promise<FormData> {
+ const spans = getClipSpans(doc.clips, doc.assets);
+ if (spans.length === 0) throw new Error("Add a video to the timeline first.");
+ const duration = totalDuration(doc.clips);
+ const form = new FormData();
+ const assetById = new Map(doc.assets.map((a) => [a.id, a]));
- const done = (async () => {
- const spans = getClipSpans(doc.clips, doc.assets);
- if (spans.length === 0) throw new Error("Add a video to the timeline first.");
- const duration = totalDuration(doc.clips);
+ const clips = spans.map((sp) => ({
+ file: sp.asset.fileName,
+ in: sp.clip.in,
+ out: sp.clip.out,
+ muted: sp.clip.muted,
+ fit: sp.clip.fit ?? "fit",
+ panX: sp.clip.panX ?? 0,
+ panY: sp.clip.panY ?? 0,
+ speed: clipSpeed(sp.clip),
+ transition: sp.transitionOut,
+ }));
- onProgress("Preparing", 0);
- const form = new FormData();
- const assetById = new Map(doc.assets.map((a) => [a.id, a]));
-
- // Media already lives in the project folder — the spec references it by
- // file name; only overlay PNGs travel with the request.
- const clips = spans.map((sp) => ({
- file: sp.asset.fileName,
- in: sp.clip.in,
- out: sp.clip.out,
- muted: sp.clip.muted,
- fit: sp.clip.fit ?? "fit",
- panX: sp.clip.panX ?? 0,
- panY: sp.clip.panY ?? 0,
- speed: clipSpeed(sp.clip),
- // The already-clamped dissolve overlap into the next clip.
- transition: sp.transitionOut,
+ const audio = doc.audioClips
+ .filter((a) => a.start < duration && assetById.has(a.assetId))
+ .map((a) => ({
+ file: assetById.get(a.assetId)!.fileName,
+ in: a.in,
+ out: a.out,
+ start: a.start,
+ volume: a.volume,
+ fadeIn: a.fadeIn ?? 0,
+ fadeOut: a.fadeOut ?? 0,
+ speed: a.speed,
}));
- const audio = doc.audioClips
- .filter((a) => a.start < duration && assetById.has(a.assetId))
- .map((a) => ({
- file: assetById.get(a.assetId)!.fileName,
- in: a.in,
- out: a.out,
- start: a.start,
- volume: a.volume,
- fadeIn: a.fadeIn ?? 0,
- fadeOut: a.fadeOut ?? 0,
- speed: a.speed,
- }));
-
- const overlays: { file: string; start: number; end: number }[] = [];
- for (let i = 0; i < doc.overlays.length; i++) {
- const o = doc.overlays[i];
- if (o.start >= duration || !o.text.trim()) continue;
- const png = await renderOverlayPng(o, settings.width, settings.height);
- const key = `overlay_${i}.png`;
+ const overlays: { file: string; start: number; end: number }[] = [];
+ for (let i = 0; i < doc.overlays.length; i++) {
+ const o = doc.overlays[i];
+ if (o.start >= duration || !o.text.trim()) continue;
+ const png = await renderOverlayPng(o, settings.width, settings.height);
+ const key = `overlay_${i}.png`;
+ form.append(key, png, key);
+ overlays.push({ file: key, start: o.start, end: Math.min(o.end, duration) });
+ }
+
+ if (doc.subtitles.showOnVideo) {
+ const capStyle = captionStyle(doc.subtitles.style);
+ for (let i = 0; i < doc.subtitles.cues.length; i++) {
+ const cue = doc.subtitles.cues[i];
+ if (cue.start >= duration || !cue.text.trim()) continue;
+ const png = await renderOverlayPng(
+ cueOverlay(cue, capStyle, i === 0),
+ settings.width,
+ settings.height
+ );
+ const key = `sub_${i}.png`;
form.append(key, png, key);
- overlays.push({ file: key, start: o.start, end: Math.min(o.end, duration) });
+ overlays.push({ file: key, start: cue.start, end: Math.min(cue.end, duration) });
}
+ }
- // Subtitles burn in through the same overlay pipeline. When there are no
- // cues (no speech was found) nothing is added to the video.
- if (doc.subtitles.showOnVideo) {
- for (let i = 0; i < doc.subtitles.cues.length; i++) {
- const cue = doc.subtitles.cues[i];
- if (cue.start >= duration || !cue.text.trim()) continue;
- const png = await renderOverlayPng(cueOverlay(cue), settings.width, settings.height);
- const key = `sub_${i}.png`;
- form.append(key, png, key);
- overlays.push({ file: key, start: cue.start, end: Math.min(cue.end, duration) });
- }
- }
+ form.append(
+ "spec",
+ JSON.stringify({ projectId, target, ...settings, duration, clips, audio, overlays })
+ );
+ return form;
+}
+
+/** Poll an export job to completion, reporting progress. Returns the file name. */
+export async function pollExport(
+ jobId: string,
+ onProgress: (stage: string, ratio: number) => void,
+ isCanceled: () => boolean = () => false
+): Promise<string> {
+ for (;;) {
+ if (isCanceled()) throw new Error("Export canceled.");
+ await new Promise((r) => setTimeout(r, 400));
+ const st = await apiFetch(`/api/cut/export/${jobId}`);
+ const status = (await st.json()) as {
+ status: string;
+ progress: number;
+ error?: string;
+ outName?: string;
+ };
+ if (status.status === "error") throw new Error(status.error ?? "Export failed.");
+ onProgress("Rendering", status.progress);
+ if (status.status === "done") return status.outName ?? "export.mp4";
+ }
+}
+
+/** Trigger a browser download of a finished export by job id. */
+export function downloadExport(jobId: string, outName: string) {
+ const a = document.createElement("a");
+ a.href = apiUrl(`/api/cut/export/${jobId}/file`);
+ a.download = outName;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+}
- form.append(
- "spec",
- JSON.stringify({ projectId, ...settings, duration, clips, audio, overlays })
- );
+export function startExport(
+ projectId: string,
+ doc: ExportDoc,
+ settings: ExportSettings,
+ onProgress: (stage: string, ratio: number) => void
+): ExportHandle {
+ let jobId: string | null = null;
+ let canceled = false;
+ const done = (async () => {
+ onProgress("Preparing", 0);
+ const form = await buildExportForm(projectId, doc, settings, "export");
onProgress("Starting encoder", 0);
const res = await apiFetch("/api/cut/export", { method: "POST", body: form });
const body = (await res.json()) as { id?: string; error?: string };
if (!res.ok || !body.id) throw new Error(body.error ?? "Export failed to start.");
jobId = body.id;
- let outName = "export.mp4";
- for (;;) {
- if (canceled) throw new Error("Export canceled.");
- await new Promise((r) => setTimeout(r, 400));
- const st = await apiFetch(`/api/cut/export/${jobId}`);
- const status = (await st.json()) as {
- status: string;
- progress: number;
- error?: string;
- outName?: string;
- };
- if (status.status === "error") throw new Error(status.error ?? "Export failed.");
- onProgress("Rendering", status.progress);
- if (status.status === "done") {
- outName = status.outName ?? outName;
- break;
- }
- }
-
+ const outName = await pollExport(jobId, onProgress, () => canceled);
onProgress("Done", 1);
- const a = document.createElement("a");
- a.href = apiUrl(`/api/cut/export/${jobId}/file`);
- a.download = outName;
- document.body.appendChild(a);
- a.click();
- a.remove();
+ downloadExport(jobId, outName);
return { outName };
})();
@@ -214,3 +243,22 @@ export function startExport(
},
};
}
+
+/** Low-res proxy of the actual edit for the project card's hover preview.
+ * Renders through the same pipeline (overlays and all), writing the project's
+ * preview.mp4. Best-effort: silently no-ops if a slot is busy or there's no
+ * footage yet. */
+export async function renderPreviewProxy(projectId: string, doc: ExportDoc, aspect: Aspect) {
+ const [width, height] = aspect === "16:9" ? [640, 360] : [360, 640];
+ const settings: ExportSettings = { width, height, fps: 24, crf: 30, preset: "veryfast" };
+ let form: FormData;
+ try {
+ form = await buildExportForm(projectId, doc, settings, "preview");
+ } catch {
+ return; // no clips yet
+ }
+ const res = await apiFetch("/api/cut/export", { method: "POST", body: form });
+ const body = (await res.json().catch(() => ({}))) as { id?: string };
+ if (!res.ok || !body.id) return; // a slot was busy; try again later
+ await pollExport(body.id, () => {}).catch(() => {});
+}
diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.ts
new file mode 100644
index 00000000..0a22f8ed
--- /dev/null
+++ b/site/src/cut/lib/exportStore.ts
@@ -0,0 +1,89 @@
+"use client";
+
+import { create } from "zustand";
+import { apiFetch } from "./api";
+import {
+ downloadExport,
+ pollExport,
+ startExport,
+ type ExportDoc,
+ type ExportHandle,
+ type ExportSettings,
+} from "./exportClient";
+
+// The current export, held outside the dialog so it keeps running (and stays
+// visible) after the dialog closes. One export at a time is plenty here.
+
+type Status = "idle" | "running" | "done" | "error";
+
+interface ExportState {
+ status: Status;
+ stage: string;
+ ratio: number;
+ outName?: string;
+ error?: string;
+ projectId: string | null;
+ handle: ExportHandle | null;
+ start: (projectId: string, doc: ExportDoc, settings: ExportSettings) => void;
+ cancel: () => void;
+ dismiss: () => void;
+ /** After a reopen or reload, rejoin an export still running for a project. */
+ reconnect: (projectId: string) => Promise<void>;
+}
+
+export const useExport = create<ExportState>((set, get) => ({
+ status: "idle",
+ stage: "",
+ ratio: 0,
+ projectId: null,
+ handle: null,
+
+ start: (projectId, doc, settings) => {
+ get().handle?.cancel();
+ set({
+ status: "running",
+ stage: "Preparing",
+ ratio: 0,
+ error: undefined,
+ outName: undefined,
+ projectId,
+ });
+ const handle = startExport(projectId, doc, settings, (stage, ratio) => set({ stage, ratio }));
+ set({ handle });
+ handle.done
+ .then(({ outName }) => set({ status: "done", outName, ratio: 1, handle: null }))
+ .catch((err: unknown) =>
+ set({
+ status: "error",
+ error: err instanceof Error ? err.message : String(err),
+ handle: null,
+ })
+ );
+ },
+
+ cancel: () => {
+ get().handle?.cancel();
+ set({ status: "idle", handle: null, ratio: 0, stage: "" });
+ },
+
+ dismiss: () =>
+ set({ status: "idle", ratio: 0, stage: "", error: undefined, outName: undefined }),
+
+ reconnect: async (projectId) => {
+ if (get().status === "running") return;
+ const list = (await apiFetch(`/api/cut/projects/${projectId}/export-jobs`)
+ .then((r) => (r.ok ? r.json() : []))
+ .catch(() => [])) as { id: string; status: string; progress: number; outName?: string }[];
+ const running = list.find((j) => j.status === "running");
+ if (!running) return;
+ set({ status: "running", stage: "Rendering", ratio: running.progress, projectId });
+ pollExport(running.id, (stage, ratio) => set({ stage, ratio }))
+ .then((outName) => {
+ downloadExport(running.id, outName);
+ set({ status: "done", outName, ratio: 1 });
+ })
+ .catch((err: unknown) =>
+ set({ status: "error", error: err instanceof Error ? err.message : String(err) })
+ );
+ },
+}));
diff --git a/site/src/cut/server/http/export.ts b/site/src/cut/server/http/export.ts
index 8e909421..1b6357af 100644
--- a/site/src/cut/server/http/export.ts
+++ b/site/src/cut/server/http/export.ts
@@ -1,8 +1,14 @@
-import { cancelJob, createJob, getJob } from "../jobs";
+import { cancelJob, createJob, getJob, listJobsForProject } from "../jobs";
import { serveFileRange } from "../serveFile";
/** Export rendering: start a job, poll it, cancel it, download the result. */
export const exportApi = {
+ /** Export jobs (running or recently settled) for a project, so a reopened or
+ * reloaded editor can reconnect to a render still in flight. */
+ activeForProject(_req: Request, { id }: { id: string }) {
+ return Response.json(listJobsForProject(id));
+ },
+
async create(req: Request) {
try {
const form = await req.formData();
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index 36743303..c23853ba 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -4,11 +4,14 @@ import os from "node:os";
import path from "node:path";
import { assertLocalRuntime } from "./local-only";
import { createJobRegistry } from "./jobRegistry";
-import { exportsDir, mediaPath, readProject } from "./projects";
+import { exportsDir, mediaPath, projectDir, readProject } from "./projects";
import { atempoChain, hasStream, num } from "./util";
export interface ExportSpec {
projectId: string;
+ /** "preview" renders the low-res hover proxy into the project's preview.mp4
+ * instead of a stamped file in exports/. */
+ target?: "export" | "preview";
width: number;
height: number;
fps: number;
@@ -44,6 +47,7 @@ export interface ExportSpec {
export interface Job {
id: string;
+ projectId: string;
status: "running" | "done" | "error";
progress: number; // 0..1
error?: string;
@@ -62,6 +66,20 @@ export function getJob(id: string) {
return jobs.get(id);
}
+/** Running and recently-settled export jobs for a project, so a client that
+ * reopened (or reloaded) can reconnect to an export still in flight. */
+export function listJobsForProject(projectId: string) {
+ return [...jobs.values()]
+ .filter((j) => j.projectId === projectId)
+ .map((j) => ({
+ id: j.id,
+ status: j.status,
+ progress: j.progress,
+ outName: j.outName,
+ error: j.error,
+ }));
+}
+
export function cancelJob(id: string) {
const job = jobs.get(id);
if (job?.proc && job.status === "running") {
@@ -85,6 +103,7 @@ export async function createJob(form: FormData): Promise<Job> {
if (runningCount() >= MAX_RUNNING) {
const job: Job = {
id,
+ projectId: spec.projectId,
status: "error",
progress: 0,
tmpDir: "",
@@ -97,12 +116,14 @@ export async function createJob(form: FormData): Promise<Job> {
retire(job);
return job;
}
- const outDir = exportsDir(spec.projectId);
+ const preview = spec.target === "preview";
+ const outDir = preview ? projectDir(spec.projectId) : exportsDir(spec.projectId);
// Include the unique job id so two exports in the same second can't collide
// on the same output path (which would clobber the first render).
- const outName = `export-${stamp()}-${id}.mp4`;
+ const outName = preview ? "preview.mp4" : `export-${stamp()}-${id}.mp4`;
const job: Job = {
id,
+ projectId: spec.projectId,
status: "running",
progress: 0,
tmpDir: "",