Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Shorts Studio and Mixed Media pages, and a reusable video trimmer

Claude8d5a505f4865
diff --git a/src/app/(studio)/mixed-media/page.tsx b/src/app/(studio)/mixed-media/page.tsx
new file mode 100644
index 00000000..14d96c95
--- /dev/null
+++ b/src/app/(studio)/mixed-media/page.tsx
@@ -0,0 +1,13 @@
+import type { Metadata } from "next";
+import { MixedStudio } from "@/components/mixed-media/mixed-studio";
+import { MIXED_MODELS } from "@/lib/catalog/mixed-media";
+import { modelInfos } from "@/lib/catalog/shorts-models";
+
+export const metadata: Metadata = { title: "Mixed Media" };
+
+/** The restyle models per engine, slimmed on the server so the page ships no catalog. */
+const MODELS = { cloud: modelInfos(MIXED_MODELS.cloud), open: modelInfos(MIXED_MODELS.open) };
+
+export default function Page() {
+ return <MixedStudio models={MODELS} />;
+}
diff --git a/src/app/(studio)/shorts/[id]/page.tsx b/src/app/(studio)/shorts/[id]/page.tsx
new file mode 100644
index 00000000..6bb39d42
--- /dev/null
+++ b/src/app/(studio)/shorts/[id]/page.tsx
@@ -0,0 +1,18 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { ShortsSessionView } from "@/components/shorts/session-view";
+
+export const metadata: Metadata = { title: "Your short" };
+
+async function Session({ params }: { params: PageProps<"/shorts/[id]">["params"] }) {
+ const { id } = await params;
+ return <ShortsSessionView id={id} />;
+}
+
+export default function Page({ params }: PageProps<"/shorts/[id]">) {
+ return (
+ <Suspense fallback={null}>
+ <Session params={params} />
+ </Suspense>
+ );
+}
diff --git a/src/app/(studio)/shorts/page.tsx b/src/app/(studio)/shorts/page.tsx
new file mode 100644
index 00000000..64bec3d6
--- /dev/null
+++ b/src/app/(studio)/shorts/page.tsx
@@ -0,0 +1,13 @@
+import type { Metadata } from "next";
+import { ShortsStudio } from "@/components/shorts/shorts-studio";
+import { SHORTS_MODELS } from "@/lib/catalog/shorts";
+import { modelInfos } from "@/lib/catalog/shorts-models";
+
+export const metadata: Metadata = { title: "Shorts Studio" };
+
+/** The restyle models per engine, slimmed on the server so the page ships no catalog. */
+const MODELS = { cloud: modelInfos(SHORTS_MODELS.cloud), open: modelInfos(SHORTS_MODELS.open) };
+
+export default function Page() {
+ return <ShortsStudio models={MODELS} />;
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index 8ea7fba1..96e694d0 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -38,6 +38,8 @@ import {
Library,
PersonStanding,
Scissors,
+ Shapes,
+ Smartphone,
type LucideIcon,
} from "lucide-react";
import {
@@ -110,6 +112,8 @@ const NAV: NavGroupDef[] = [
label: "Studios",
items: [
{ href: "/cinema", label: "Cinema Studio", icon: Clapperboard },
+ { href: "/shorts", label: "Shorts Studio", icon: Smartphone },
+ { href: "/mixed-media", label: "Mixed Media", icon: Shapes },
{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },
{ href: "/motion-control", label: "Motion control", icon: PersonStanding },
{ href: "/video-edit", label: "Edit video", icon: Scissors },
diff --git a/src/components/mixed-media/history.tsx b/src/components/mixed-media/history.tsx
new file mode 100644
index 00000000..24fcd7eb
--- /dev/null
+++ b/src/components/mixed-media/history.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import { Download, Shapes } from "lucide-react";
+import { useState } from "react";
+import { Skeleton } from "@/components/ui/skeleton";
+import { PendingTile } from "@/components/studio/feed";
+import { MediaThumb } from "@/components/studio/result-media";
+import { Viewer } from "@/components/studio/viewer";
+import { useGenerations } from "@/lib/api";
+import { MIXED_FEATURE } from "@/lib/catalog/mixed-media";
+import type { Generation } from "@/lib/catalog/types";
+import { timeAgo } from "@/lib/format";
+import { downloadHref, downloadName, userTitle } from "@/lib/library";
+
+const FILTER = { features: [MIXED_FEATURE], limit: 60 };
+
+/** History: the finished (and rendering) Mixed Media videos, newest first. */
+export function MixedHistory({ onStart }: { onStart: () => void }) {
+ const list = useGenerations(FILTER);
+ const [open, setOpen] = useState<Generation | null>(null);
+ if (list.isLoading)
+ return (
+ <div className="grid grid-cols-2 gap-3 pt-8 sm:grid-cols-3 lg:grid-cols-4">
+ {Array.from({ length: 8 }, (_, i) => (
+ <Skeleton key={i} className="aspect-square rounded-xl" />
+ ))}
+ </div>
+ );
+ if (!list.data?.length)
+ return (
+ <div className="mx-auto flex max-w-md flex-col items-center py-20 text-center">
+ <span className="grid size-12 place-items-center rounded-full bg-brand-faint text-brand-text">
+ <Shapes className="size-5" />
+ </span>
+ <p className="mt-4 font-heading text-[22px]">Nothing here yet</p>
+ <p className="mt-1 text-[14px] text-muted-foreground">Pick a preset, add a clip of up to 10 seconds and generate — your mixed-media videos show up here.</p>
+ <button type="button" onClick={onStart} className="mt-5 h-9 rounded-full bg-primary px-4 text-[13px] font-medium text-primary-foreground hover:bg-primary/90">
+ Browse presets
+ </button>
+ </div>
+ );
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-3 pt-8 sm:grid-cols-3 lg:grid-cols-4">
+ {list.data.map((g) => {
+ const out = g.status === "succeeded" ? g.outputs.find((o) => o.kind === "video") : undefined;
+ return (
+ <div key={g.id} className="min-w-0">
+ <div className="relative aspect-square overflow-hidden rounded-xl bg-muted">
+ {out ? (
+ <button type="button" onClick={() => setOpen(g)} aria-label={`Open ${userTitle(g)}`} className="block size-full outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <MediaThumb output={out} />
+ </button>
+ ) : g.status === "queued" || g.status === "running" ? (
+ <PendingTile g={g} ratio={1} />
+ ) : (
+ <div className="flex size-full flex-col justify-center gap-1 border border-dashed p-3">
+ <p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't render this one"}</p>
+ {g.error && <p className="line-clamp-4 text-[12px] text-muted-foreground">{g.error}</p>}
+ </div>
+ )}
+ </div>
+ <div className="flex items-start gap-1 px-0.5 pt-2">
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[13px] font-medium">{userTitle(g)}</p>
+ <p className="truncate text-[12px] text-muted-foreground">{timeAgo(g.createdAt)}</p>
+ </div>
+ {out && (
+ <a href={downloadHref(out.url, downloadName(g, out, 0))} download={downloadName(g, out, 0)} aria-label="Download" className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <Download className="size-3.5" />
+ </a>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ {open && <Viewer generation={open} index={0} onClose={() => setOpen(null)} />}
+ </>
+ );
+}
diff --git a/src/components/mixed-media/hooks.ts b/src/components/mixed-media/hooks.ts
new file mode 100644
index 00000000..2fdaee5b
--- /dev/null
+++ b/src/components/mixed-media/hooks.ts
@@ -0,0 +1,79 @@
+"use client";
+
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useDeferredValue } from "react";
+import type { MixedResolution, MixedValues } from "@/lib/catalog/mixed-media";
+import type { Engine, Generation } from "@/lib/catalog/types";
+import { useGenerationEvents } from "@/lib/api";
+import { send } from "@/components/shorts/hooks";
+
+/** React Query hooks for /api/mixed-media/** (renders, preview frames, estimates). */
+
+export interface MixedBody {
+ engine: Engine;
+ presetId: string;
+ values: MixedValues;
+ source: { url: string; name?: string; duration?: number; fps?: number };
+ range: { start: number; end: number };
+ fps: number;
+ resolution: MixedResolution;
+ modelId?: string;
+ anchor?: string;
+ frameUrl?: string;
+}
+
+export interface MixedEstimate {
+ costUsd: number | null;
+ previewUsd: number | null;
+ demo: boolean;
+ frames: number;
+ fps: number;
+ notes: string[];
+}
+
+export function useMixedEstimate(body: MixedBody | null) {
+ const key = useDeferredValue(body ? JSON.stringify(body) : null);
+ return useQuery({
+ queryKey: ["mixed-media", "estimate", key],
+ queryFn: async () => send<MixedEstimate>("/api/mixed-media/estimate", "POST", JSON.parse(key!)),
+ enabled: !!key,
+ placeholderData: keepPreviousData,
+ retry: false,
+ staleTime: 30_000,
+ });
+}
+
+const active = (g?: Generation | null) => !!g && (g.status === "queued" || g.status === "running");
+
+/** Follow one generation (a preview frame, the latest render) until it settles. */
+export function useWatchedGeneration(id: string | null) {
+ const qc = useQueryClient();
+ const connected = useGenerationEvents((ev) => {
+ if (!id) return;
+ if (ev.type === "generation" && ev.generation.id === id) qc.setQueryData(["mixed-media", "generation", id], ev.generation);
+ });
+ return useQuery({
+ queryKey: ["mixed-media", "generation", id],
+ queryFn: async () => send<Generation>(`/api/generations/${id}`, "GET"),
+ enabled: !!id,
+ refetchInterval: (q) => (active(q.state.data) ? (connected ? 5000 : 1200) : false),
+ });
+}
+
+export function useMixedActions() {
+ const qc = useQueryClient();
+ const seed = (g: Generation) => qc.setQueryData(["mixed-media", "generation", g.id], g);
+ return {
+ render: useMutation({
+ mutationFn: (b: MixedBody) => send<{ final: Generation; items: Generation[] }>("/api/mixed-media", "POST", b),
+ onSuccess: (r) => {
+ seed(r.final);
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ },
+ }),
+ preview: useMutation({
+ mutationFn: (b: MixedBody) => send<Generation>("/api/mixed-media/preview", "POST", b),
+ onSuccess: seed,
+ }),
+ };
+}
diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsx
new file mode 100644
index 00000000..a2058fe5
--- /dev/null
+++ b/src/components/mixed-media/mixed-studio.tsx
@@ -0,0 +1,575 @@
+"use client";
+
+import { ArrowDown, Cloud, Cpu, Download, ImageIcon, Info, Loader2, Search, Sparkles, Wand2, X } from "lucide-react";
+import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { MediaThumb } from "@/components/studio/result-media";
+import { VideoTrimmer, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";
+import { LookCard } from "@/components/shorts/preset-card";
+import { ClipBar, ClipDrop, costText, Field, Segmented } from "@/components/shorts/ui";
+import { clipDuration, useSourceClip } from "@/components/shorts/use-source-clip";
+import { uploadFile, useEngine } from "@/lib/api";
+import {
+ clampFps,
+ defaultValues,
+ fpsChoices,
+ MIXED,
+ MIXED_PRESETS,
+ mixedFrames,
+ mixedPreview,
+ mixedRangeProblem,
+ type MixedPreset,
+ type MixedResolution,
+ type MixedValues,
+} from "@/lib/catalog/mixed-media";
+import type { RestyleModelInfo } from "@/lib/catalog/shorts-models";
+import type { Engine, Generation } from "@/lib/catalog/types";
+import { downloadHref, downloadName } from "@/lib/library";
+import type { TrimRange } from "@/lib/trim-range";
+import { cn } from "@/lib/utils";
+import { MixedHistory } from "./history";
+import { useMixedActions, useMixedEstimate, useWatchedGeneration, type MixedBody } from "./hooks";
+import { AdvancedSettings, loadSaved } from "./settings";
+
+type Tab = "presets" | "history" | "how";
+const TABS: { id: Tab; label: string }[] = [
+ { id: "presets", label: "All presets" },
+ { id: "history", label: "History" },
+ { id: "how", label: "How it works" },
+];
+
+const HOW = [
+ { step: "Choose a preset", text: "Browse 33 mixed-media looks — sketch, comic, paper, neon, marble — and pick the one that fits your clip." },
+ { step: "Upload your video", text: "Add a clip and trim it to up to 10 seconds. It needs at least 4 frames per second." },
+ { step: "Customize settings", text: "Each preset has its own colours, materials and intensity. Save them per preset; they stay in this browser." },
+ { step: "Generate & preview", text: "Make one preview frame first to check the look, then render the whole video. Frames are restyled at the rate you pick." },
+];
+
+/** Mixed Media: pick a look, add a ≤10 s clip, tune the settings, preview one frame, render. */
+export function MixedStudio({ models }: { models: Record<Engine, RestyleModelInfo[]> }) {
+ const [tab, setTab] = useState<Tab>("presets");
+ const [engine, setEngine] = useEngine();
+ useEffect(() => {
+ const t = new URLSearchParams(window.location.search).get("tab");
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- read once after hydration
+ if (t === "history" || t === "how") setTab(t);
+ }, []);
+ const pick = (t: Tab) => {
+ setTab(t);
+ const url = new URL(window.location.href);
+ if (t === "presets") url.searchParams.delete("tab");
+ else url.searchParams.set("tab", t);
+ window.history.replaceState(null, "", url);
+ };
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <h1 className="sr-only font-heading text-[22px] leading-none sm:not-sr-only sm:truncate">Mixed Media</h1>
+ <div role="tablist" aria-label="Mixed Media" className="fade-x scrollbar-none flex h-8 min-w-0 items-center overflow-x-auto rounded-full bg-muted p-0.5 sm:ml-4">
+ {TABS.map((t) => (
+ <button
+ key={t.id}
+ role="tab"
+ type="button"
+ aria-selected={tab === t.id}
+ onClick={() => pick(t.id)}
+ className={cn("h-7 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground", tab === t.id && "bg-background text-foreground shadow-soft")}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+ <div className="ml-auto shrink-0">
+ <EngineSwitch value={engine} onChange={setEngine} />
+ </div>
+ </header>
+ <main className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-3 pb-28 sm:px-6 lg:pb-16">
+ {tab === "history" ? (
+ <MixedHistory onStart={() => pick("presets")} />
+ ) : tab === "how" ? (
+ <How onStart={() => pick("presets")} />
+ ) : (
+ <>
+ <div className="mx-auto max-w-[720px] pt-8 pb-6 text-center sm:pt-12">
+ <p className="text-[12px] font-semibold tracking-[0.14em] text-brand-text uppercase">No prompts, just vibe</p>
+ <h2 className="mt-2 font-heading text-display text-balance">Turn any video into mixed-media art</h2>
+ <p className="mx-auto mt-2 max-w-[560px] text-body text-pretty text-muted-foreground">
+ 33 looks, each with its own colours and materials. Every frame is restyled at the frame rate you choose — preview one frame first.
+ </p>
+ </div>
+ <Workspace engine={engine} models={models[engine]} />
+ </>
+ )}
+ </main>
+ </div>
+ );
+}
+
+function How({ onStart }: { onStart: () => void }) {
+ return (
+ <div className="mx-auto max-w-[920px] pt-10">
+ <h2 className="text-center font-heading text-[34px] leading-tight">How it works</h2>
+ <ol className="mt-8 grid gap-3 sm:grid-cols-2">
+ {HOW.map((h, i) => (
+ <li key={h.step} className="rounded-2xl border bg-background p-5">
+ <span className="grid size-7 place-items-center rounded-full bg-primary text-[13px] font-semibold text-primary-foreground">{i + 1}</span>
+ <p className="mt-3 text-[15px] font-semibold">{h.step}</p>
+ <p className="mt-1 text-[14px] text-muted-foreground">{h.text}</p>
+ </li>
+ ))}
+ </ol>
+ <div className="mt-6 rounded-2xl bg-muted/60 p-5 text-[13px] text-muted-foreground">
+ <p className="font-medium text-foreground">Cost</p>
+ <p className="mt-1">
+ A render is counted in frames: seconds × frame rate, rounded down (10 s at 8 FPS = 80 frames). On the open engine every frame runs on your GPU for free; cloud
+ models are priced by the model (per second or per video) and the estimate shows before you generate.
+ </p>
+ </div>
+ <div className="mt-6 text-center">
+ <button type="button" onClick={onStart} className="h-10 rounded-full bg-primary px-5 text-[14px] font-medium text-primary-foreground hover:bg-primary/90">
+ Choose a preset
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function Workspace({ engine, models }: { engine: Engine; models: RestyleModelInfo[] }) {
+ const [presetId, setPresetId] = useState<string | null>(null);
+ const preset = MIXED_PRESETS.find((p) => p.id === presetId) ?? null;
+ const [values, setValues] = useState<MixedValues>({});
+ const [q, setQ] = useState("");
+ const query = useDeferredValue(q.trim().toLowerCase());
+ const list = useMemo(() => MIXED_PRESETS.filter((p) => !query || `${p.name} ${p.description}`.toLowerCase().includes(query)), [query]);
+ const panel = useRef<HTMLElement>(null);
+ const [panelVisible, setPanelVisible] = useState(false);
+ useEffect(() => {
+ const el = panel.current;
+ if (!el) return;
+ const io = new IntersectionObserver(([e]) => setPanelVisible(e.isIntersecting), { rootMargin: "0px 0px -30% 0px" });
+ io.observe(el);
+ return () => io.disconnect();
+ }, []);
+
+ const select = (id: string) => {
+ setPresetId(id);
+ const p = MIXED_PRESETS.find((x) => x.id === id)!;
+ setValues(loadSaved(p) ?? defaultValues(p));
+ };
+
+ return (
+ <div className="grid min-w-0 gap-6 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-start">
+ <section aria-labelledby="mm-presets" className="min-w-0 space-y-4">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
+ <h3 id="mm-presets" className="flex items-center gap-2 text-[15px] font-semibold">
+ <span className="grid size-6 place-items-center rounded-full bg-primary text-[12px] text-primary-foreground">1</span>
+ Choose a preset
+ </h3>
+ <div className="relative w-full sm:ml-auto sm:w-64">
+ <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="search"
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ placeholder={`Search ${MIXED_PRESETS.length} presets`}
+ aria-label="Search presets"
+ className="h-9 w-full rounded-full border bg-background pr-9 pl-9 text-[14px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint [&::-webkit-search-cancel-button]:hidden"
+ />
+ {q && (
+ <button type="button" onClick={() => setQ("")} aria-label="Clear search" className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-accent">
+ <X className="size-3.5" />
+ </button>
+ )}
+ </div>
+ </div>
+ {list.length ? (
+ <div className="grid grid-cols-2 gap-1 sm:grid-cols-3 xl:grid-cols-4">
+ {list.map((p) => (
+ <LookCard key={p.id} id={p.id} name={p.name} description={p.description} preview={mixedPreview(p)} hue={p.hue} selected={presetId === p.id} onSelect={select} />
+ ))}
+ </div>
+ ) : (
+ <div className="py-12 text-center">
+ <p className="font-heading text-[22px]">No presets match “{q.trim()}”</p>
+ <button type="button" onClick={() => setQ("")} className="mt-3 h-8 rounded-full border px-3 text-[13px] font-medium hover:bg-accent">
+ Clear search
+ </button>
+ </div>
+ )}
+ </section>
+ <aside ref={panel} id="mm-editor" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">
+ <Editor engine={engine} models={models} preset={preset} values={values} setValues={setValues} />
+ </aside>
+ {preset && !panelVisible && (
+ <div className="fixed inset-x-3 bottom-[max(0.75rem,env(safe-area-inset-bottom))] z-30 lg:hidden">
+ <button
+ type="button"
+ onClick={() => panel.current?.scrollIntoView({ behavior: "smooth", block: "start" })}
+ className="flex h-12 w-full items-center gap-2 rounded-full bg-foreground px-4 text-[14px] font-medium text-background shadow-strong"
+ >
+ <Sparkles className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate text-left">{preset.name}</span>
+ <span className="flex shrink-0 items-center gap-1">
+ Add a clip <ArrowDown className="size-4" />
+ </span>
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+const LIMITS = "MP4 or MOV · 1 to 10 s · up to 50 MB · at least 4 FPS";
+type FpsChoice = number | "manual";
+
+function Editor({
+ engine,
+ models,
+ preset,
+ values,
+ setValues,
+}: {
+ engine: Engine;
+ models: RestyleModelInfo[];
+ preset: MixedPreset | null;
+ values: MixedValues;
+ setValues: (v: MixedValues) => void;
+}) {
+ const source = useSourceClip(MIXED.maxBytes);
+ const { clip } = source;
+ const trimmer = useRef<VideoTrimmerHandle>(null);
+ const [range, setRange] = useState<TrimRange | null>(null);
+ const [fpsChoice, setFpsChoice] = useState<FpsChoice>(MIXED.defaultFps as number);
+ const [manual, setManual] = useState<number>(MIXED.defaultFps);
+ const [resolution, setResolution] = useState<MixedResolution>("1K");
+ const [pickedModel, setModel] = useState<Record<Engine, string>>({ cloud: "", open: "" });
+ const modelId = pickedModel[engine] || models[0]?.id;
+ const model = models.find((m) => m.id === modelId);
+ const [previewId, setPreviewId] = useState<string | null>(null);
+ const [renderId, setRenderId] = useState<string | null>(null);
+ const [anchorOff, setAnchorOff] = useState(false);
+ const [grabbing, setGrabbing] = useState(false);
+ const actions = useMixedActions();
+ const preview = useWatchedGeneration(previewId).data;
+ const render = useWatchedGeneration(renderId).data;
+
+ const duration = clipDuration(clip);
+ const sourceFps = clip?.info?.fps;
+ const fps = clampFps(fpsChoice === "manual" ? manual : fpsChoice, sourceFps);
+ // A choice above the clip's own frame rate drops to the highest allowed ("Uploaded video has 6 FPS").
+ const choices = fpsChoices(sourceFps);
+ const mmRange = range ? { start: range.startTime, end: range.endTime } : null;
+ const problem = mmRange ? mixedRangeProblem(mmRange, duration, sourceFps) : null;
+ const frames = mmRange ? mixedFrames(mmRange.end - mmRange.start, fps) : 0;
+ const previewImage = preview?.status === "succeeded" ? preview.outputs.find((o) => o.kind === "image") : undefined;
+ const anchor = engine === "cloud" && model?.image && previewImage && !anchorOff ? previewImage.url : undefined;
+
+ const body: MixedBody | null =
+ preset && mmRange && !problem
+ ? {
+ engine,
+ presetId: preset.id,
+ values,
+ source: { url: clip?.url ?? "/api/files/placeholder.mp4", name: clip?.name, duration, fps: sourceFps },
+ range: mmRange,
+ fps,
+ resolution,
+ modelId,
+ ...(anchor ? { anchor } : {}),
+ }
+ : null;
+ const estimate = useMixedEstimate(body);
+ const est = estimate.data;
+
+ // A new clip, preset or engine starts without a preview.
+ const key = `${preset?.id}|${clip?.preview}|${engine}`;
+ const [lastKey, setLastKey] = useState(key);
+ if (key !== lastKey) {
+ setLastKey(key);
+ setPreviewId(null);
+ setAnchorOff(false);
+ }
+
+ const blocker = !preset
+ ? "Pick a preset first"
+ : !clip
+ ? "Add a clip"
+ : clip.error
+ ? clip.error
+ : !duration || !range
+ ? "Reading the clip…"
+ : problem
+ ? problem
+ : clip.uploading
+ ? clip.progress < 1
+ ? `Uploading… ${Math.round(clip.progress * 100)}%`
+ : "Reading the clip…"
+ : estimate.error
+ ? (estimate.error as Error).message
+ : null;
+
+ const makePreview = async () => {
+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });
+ let frameUrl: string | undefined;
+ if (engine === "cloud") {
+ setGrabbing(true);
+ try {
+ const blob = await trimmer.current?.grabFrame(range!.startTime);
+ if (!blob) return void toast.error("This browser can't read frames of this clip — try an MP4 (H.264), or generate the full video");
+ frameUrl = (await uploadFile(new File([blob], "frame.jpg", { type: "image/jpeg" }))).url;
+ } catch (e) {
+ return void toast.error((e as Error).message);
+ } finally {
+ setGrabbing(false);
+ }
+ }
+ actions.preview.mutate({ ...body, frameUrl }, { onSuccess: (g) => setPreviewId(g.id), onError: (e) => toast.error((e as Error).message) });
+ };
+
+ const generate = () => {
+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });
+ actions.render.mutate(body, {
+ onSuccess: (r) => {
+ setRenderId(r.final.id);
+ toast("Rendering your video", { description: "It shows up in History too." });
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+ };
+
+ return (
+ <div className="space-y-5 rounded-2xl border bg-background p-4 shadow-soft sm:p-5">
+ <div className="flex items-start gap-2 rounded-lg bg-muted/60 px-3 py-2 text-[13px]">
+ <Sparkles className="mt-0.5 size-4 shrink-0 text-brand-text" />
+ {preset ? (
+ <span className="min-w-0">
+ <span className="font-medium">{preset.name}</span> <span className="text-muted-foreground">· {preset.description}</span>
+ </span>
+ ) : (
+ <span className="text-muted-foreground">Pick a preset to start</span>
+ )}
+ </div>
+
+ <Field label="Your video">
+ {!clip ? (
+ <ClipDrop
+ accept={MIXED.accept}
+ limits={LIMITS}
+ onFile={(f) => {
+ const err = source.pick(f);
+ if (err) toast.error(err);
+ else setRange(null);
+ }}
+ onLibrary={(url, name) => {
+ source.adopt(url, name);
+ setRange(null);
+ }}
+ />
+ ) : (
+ <div className="space-y-3">
+ <ClipBar
+ clip={clip}
+ onRemove={() => {
+ source.clear();
+ setRange(null);
+ }}
+ />
+ <VideoTrimmer
+ ref={trimmer}
+ src={clip.preview}
+ value={range}
+ onChange={setRange}
+ min={MIXED.minSeconds}
+ max={MIXED.maxSeconds}
+ duration={clip.info?.duration}
+ label="Part of the clip to transform"
+ onMeta={(m) => source.setBrowserDuration(m.duration)}
+ />
+ </div>
+ )}
+ </Field>
+
+ <Field label="Frame rate" hint={sourceFps ? `Uploaded video has ${Math.round(sourceFps)} FPS` : "8 FPS is the classic stop-motion look"}>
+ <Segmented<FpsChoice>
+ label="Frame rate"
+ value={fpsChoice}
+ onChange={setFpsChoice}
+ options={[
+ ...choices.map((c) => ({ value: c.fps as FpsChoice, label: String(c.fps), disabled: c.disabled, title: c.disabled ? "Above the clip's own frame rate" : `${c.fps} FPS` })),
+ { value: "manual" as FpsChoice, label: "Manual" },
+ ]}
+ />
+ {fpsChoice === "manual" && (
+ <label className="flex items-center gap-2 text-[12px] text-muted-foreground">
+ Choose frames manually
+ <input
+ type="number"
+ min={MIXED.manualFps.min}
+ max={Math.min(MIXED.manualFps.max, sourceFps ? Math.floor(sourceFps) : MIXED.manualFps.max)}
+ value={manual}
+ onChange={(e) => setManual(Number(e.target.value) || MIXED.manualFps.min)}
+ aria-label="Frames per second"
+ className="h-7 w-16 rounded-md border bg-background px-2 font-mono text-[12px] text-foreground outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"
+ />
+ FPS
+ </label>
+ )}
+ {fps !== (fpsChoice === "manual" ? manual : fpsChoice) && <p className="text-[12px] text-warning">Using {fps} FPS — the clip itself has no more frames than that.</p>}
+ </Field>
+
+ <Field label="Resolution">
+ <Segmented<MixedResolution> label="Resolution" value={resolution} onChange={setResolution} options={MIXED.resolutions.map((r) => ({ value: r, label: r }))} />
+ </Field>
+
+ {preset && <AdvancedSettings preset={preset} values={values} onChange={setValues} />}
+
+ <Field
+ label="Model"
+ hint={
+ engine === "open" ? (
+ <span className="inline-flex items-center gap-1">
+ <Cpu className="size-3" /> Open source
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1">
+ <Cloud className="size-3" /> Cloud
+ </span>
+ )
+ }
+ >
+ {models.length > 1 ? (
+ <Select value={modelId} onValueChange={(v) => setModel((m) => ({ ...m, [engine]: v }))}>
+ <SelectTrigger className="w-full" aria-label="Model">
+ <SelectValue>
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate">{model?.name}</span>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{model?.price}</span>
+ </span>
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {models.map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate">{m.name}</span>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{m.price}</span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <div className="rounded-lg border px-3 py-2 text-[13px]">
+ <span className="font-medium">{model?.name ?? "—"}</span> <span className="text-muted-foreground">· {model?.price}</span>
+ </div>
+ )}
+ {model && <p className="text-[12px] leading-snug text-muted-foreground">{model.tagline}</p>}
+ </Field>
+
+ <div className="space-y-2 rounded-xl border p-3">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[13px] font-medium">Preview frame</span>
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">Preview costs: {est ? costText({ costUsd: est.previewUsd, demo: est.demo }, engine) : "—"}</span>
+ </div>
+ <p className="text-[12px] text-muted-foreground">Generate one frame with your current settings before creating the full video.</p>
+ {preview && (
+ <div className="relative mx-auto aspect-video w-full max-w-[320px] overflow-hidden rounded-lg bg-muted">
+ {preview.status === "succeeded" && preview.outputs[0] ? (
+ <MediaThumb output={preview.outputs[0]} fit />
+ ) : preview.status === "failed" || preview.status === "canceled" ? (
+ <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">{preview.error ?? "Canceled"}</div>
+ ) : (
+ <div className="skeleton-sweep grid size-full animate-skeleton place-items-center">
+ <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">Restyling one frame…</span>
+ </div>
+ )}
+ </div>
+ )}
+ {anchor && (
+ <p className="flex items-center gap-1.5 text-[12px] text-brand-text">
+ <Wand2 className="size-3.5 shrink-0" /> {model?.name} follows this frame for the whole video
+ <button type="button" onClick={() => setAnchorOff(true)} className="ml-auto text-muted-foreground underline-offset-2 hover:underline">
+ Don&apos;t use it
+ </button>
+ </p>
+ )}
+ <button
+ type="button"
+ onClick={makePreview}
+ aria-disabled={!!blocker || actions.preview.isPending || grabbing}
+ className={cn(
+ "flex h-9 w-full items-center justify-center gap-2 rounded-full border text-[13px] font-medium",
+ blocker ? "text-subtle-foreground" : "bg-background hover:bg-accent",
+ )}
+ >
+ {actions.preview.isPending || grabbing ? <Loader2 className="size-4 animate-spin" /> : <ImageIcon className="size-4" />}
+ {preview ? "Generate another preview frame" : "Generate preview frame"}
+ </button>
+ </div>
+
+ <div className="space-y-3 border-t pt-4">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="text-[13px] text-muted-foreground">{frames ? `${frames} frames · ${fps} FPS` : "Estimate"}</span>
+ <span className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums" aria-live="polite">
+ {estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" />}
+ {body ? costText(est, engine) : "—"}
+ </span>
+ </div>
+ {est?.notes.map((n) => (
+ <p key={n} className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground">
+ <Info className="mt-0.5 size-3.5 shrink-0" />
+ {n}
+ </p>
+ ))}
+ <button
+ type="button"
+ onClick={generate}
+ aria-disabled={!!blocker || actions.render.isPending}
+ aria-describedby={blocker ? "mm-blocker" : undefined}
+ className={cn(
+ "flex h-11 w-full items-center justify-center gap-2 rounded-full text-[14px] font-medium transition-colors",
+ blocker ? "bg-muted text-subtle-foreground" : "bg-primary text-primary-foreground hover:bg-primary/90",
+ )}
+ >
+ {actions.render.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}
+ Generate video
+ </button>
+ {blocker && (
+ <p id="mm-blocker" className="text-center text-[12px] text-muted-foreground">
+ {blocker}
+ </p>
+ )}
+ {render && <LatestRender g={render} />}
+ </div>
+ </div>
+ );
+}
+
+function LatestRender({ g }: { g: Generation }) {
+ const out = g.status === "succeeded" ? g.outputs.find((o) => o.kind === "video") : undefined;
+ return (
+ <div className="space-y-2 rounded-xl bg-muted/50 p-3" aria-live="polite">
+ <p className="text-[13px] font-medium">Your video</p>
+ <div className="relative mx-auto aspect-video w-full overflow-hidden rounded-lg bg-muted">
+ {out ? (
+ <video src={out.url} controls playsInline preload="metadata" className="size-full bg-black object-contain" />
+ ) : g.status === "failed" || g.status === "canceled" ? (
+ <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">{g.error ?? "Canceled"}</div>
+ ) : (
+ <div className="skeleton-sweep grid size-full animate-skeleton place-items-center">
+ <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">{g.message ?? "Rendering…"}</span>
+ </div>
+ )}
+ </div>
+ {out && (
+ <a href={downloadHref(out.url, downloadName(g, out, 0))} download={downloadName(g, out, 0)} className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent">
+ <Download className="size-3.5" /> Download
+ </a>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/mixed-media/settings.tsx b/src/components/mixed-media/settings.tsx
new file mode 100644
index 00000000..4dd7c48c
--- /dev/null
+++ b/src/components/mixed-media/settings.tsx
@@ -0,0 +1,220 @@
+"use client";
+
+import { RotateCcw, Save } from "lucide-react";
+import { useCallback, useId, useState, useSyncExternalStore } from "react";
+import { toast } from "sonner";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { cleanValues, defaultValues, type MixedPreset, type MixedSetting, type MixedValues } from "@/lib/catalog/mixed-media";
+
+/**
+ * Per-preset advanced settings (Higgsfield's param_configs): colours (or "describe the colour"),
+ * dropdowns with a custom option, text. Saved per preset in this browser (localStorage).
+ */
+
+const KEY = (id: string) => `fuobe.mixed-media.settings.${id}`;
+const listeners = new Set<() => void>();
+const notify = () => listeners.forEach((l) => l());
+
+function readRaw(id: string): string | null {
+ try {
+ return localStorage.getItem(KEY(id));
+ } catch {
+ return null;
+ }
+}
+
+/** The saved settings of a preset (cleaned), or null. */
+export function loadSaved(p: MixedPreset): MixedValues | null {
+ const raw = readRaw(p.id);
+ if (!raw) return null;
+ try {
+ return cleanValues(p, JSON.parse(raw) as Record<string, unknown>);
+ } catch {
+ return null;
+ }
+}
+
+/** The raw saved string, as a subscribable store (so "Saved" follows other tabs too). */
+export function useSavedRaw(id: string | null): string | null {
+ return useSyncExternalStore(
+ useCallback((cb: () => void) => {
+ listeners.add(cb);
+ window.addEventListener("storage", cb);
+ return () => {
+ listeners.delete(cb);
+ window.removeEventListener("storage", cb);
+ };
+ }, []),
+ () => (id ? readRaw(id) : null),
+ () => null,
+ );
+}
+
+export function saveSettings(p: MixedPreset, v: MixedValues) {
+ try {
+ localStorage.setItem(KEY(p.id), JSON.stringify(v));
+ toast.success("Settings saved");
+ } catch {
+ toast.error("Couldn't save in this browser");
+ }
+ notify();
+}
+
+export function resetSettings(p: MixedPreset) {
+ try {
+ localStorage.removeItem(KEY(p.id));
+ } catch {}
+ notify();
+}
+
+function ColorSetting({ s, value, onChange }: { s: Extract<MixedSetting, { type: "color" }>; value: string; onChange: (v: string) => void }) {
+ const id = useId();
+ const words = value.startsWith("text:");
+ return (
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <label htmlFor={id} className="text-[12px] font-medium">
+ {s.label}
+ </label>
+ <label className="inline-flex cursor-pointer items-center gap-1.5 text-[11px] text-muted-foreground">
+ <input type="checkbox" checked={words} onChange={(e) => onChange(e.target.checked ? "text:" : s.default)} className="size-3.5 accent-[var(--primary)]" />
+ Describe instead
+ </label>
+ </div>
+ {words ? (
+ <input
+ id={id}
+ value={value.slice(5)}
+ onChange={(e) => onChange(`text:${e.target.value}`)}
+ maxLength={120}
+ placeholder="Describe the colour, e.g. “rusty orange”"
+ className="h-8 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-2 focus:ring-brand-faint"
+ />
+ ) : (
+ <div className="flex items-center gap-2">
+ <input id={id} type="color" value={value} onChange={(e) => onChange(e.target.value.toLowerCase())} className="h-8 w-10 cursor-pointer rounded-md border bg-background p-0.5" />
+ <input
+ aria-label={`${s.label} (hex)`}
+ value={value.toUpperCase()}
+ onChange={(e) => {
+ const v = e.target.value.trim();
+ if (/^#[0-9a-f]{6}$/i.test(v)) onChange(v.toLowerCase());
+ }}
+ maxLength={7}
+ className="h-8 w-24 rounded-lg border bg-background px-2 font-mono text-[12px] uppercase outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SelectSetting({ s, value, onChange }: { s: Extract<MixedSetting, { type: "select" }>; value: string; onChange: (v: string) => void }) {
+ const id = useId();
+ const custom = value.startsWith("text:");
+ return (
+ <div className="space-y-1.5">
+ <label htmlFor={id} className="text-[12px] font-medium">
+ {s.label}
+ </label>
+ <Select value={custom ? "__custom" : value} onValueChange={(v) => onChange(v === "__custom" ? "text:" : v)}>
+ <SelectTrigger id={id} className="h-8 w-full text-[13px]">
+ <SelectValue>{custom ? "Custom…" : (s.options.find((o) => o.value === value)?.label ?? s.options[0].label)}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {s.options.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ {s.custom && <SelectItem value="__custom">Custom…</SelectItem>}
+ </SelectContent>
+ </Select>
+ {custom && (
+ <input
+ aria-label={`${s.label}: describe what you want`}
+ value={value.slice(5)}
+ onChange={(e) => onChange(`text:${e.target.value}`)}
+ maxLength={120}
+ autoFocus
+ placeholder="Describe what you want"
+ className="h-8 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-2 focus:ring-brand-faint"
+ />
+ )}
+ </div>
+ );
+}
+
+function TextSetting({ s, value, onChange }: { s: Extract<MixedSetting, { type: "text" }>; value: string; onChange: (v: string) => void }) {
+ const id = useId();
+ return (
+ <div className="space-y-1.5">
+ <label htmlFor={id} className="text-[12px] font-medium">
+ {s.label}
+ </label>
+ <input
+ id={id}
+ value={value}
+ maxLength={s.max}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={s.placeholder}
+ className="h-8 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-2 focus:ring-brand-faint"
+ />
+ </div>
+ );
+}
+
+export function AdvancedSettings({ preset, values, onChange }: { preset: MixedPreset; values: MixedValues; onChange: (v: MixedValues) => void }) {
+ const saved = useSavedRaw(preset.id);
+ const [open, setOpen] = useState(true);
+ const cleaned = cleanValues(preset, values);
+ const isSaved = !!saved && saved === JSON.stringify(cleaned);
+ const isDefault = JSON.stringify(cleaned) === JSON.stringify(defaultValues(preset));
+ const set = (k: string, v: string) => onChange({ ...values, [k]: v });
+ return (
+ <div className="rounded-xl border">
+ <button type="button" onClick={() => setOpen((o) => !o)} aria-expanded={open} className="flex w-full items-center justify-between gap-2 px-3 py-2.5 text-left">
+ <span className="text-[13px] font-medium">Advanced settings</span>
+ <span className="text-[11px] text-muted-foreground">{isSaved ? "Saved" : isDefault ? "Preset defaults" : "Not saved"}</span>
+ </button>
+ {open && (
+ <div className="space-y-3 border-t px-3 pt-3 pb-3">
+ <div className="grid gap-3">
+ {preset.settings.map((s) => (
+ <div key={s.key}>
+ {s.type === "color" ? (
+ <ColorSetting s={s} value={values[s.key] ?? s.default} onChange={(v) => set(s.key, v)} />
+ ) : s.type === "select" ? (
+ <SelectSetting s={s} value={values[s.key] ?? s.default} onChange={(v) => set(s.key, v)} />
+ ) : (
+ <TextSetting s={s} value={values[s.key] ?? s.default} onChange={(v) => set(s.key, v)} />
+ )}
+ </div>
+ ))}
+ </div>
+ <div className="flex gap-2">
+ <button
+ type="button"
+ onClick={() => saveSettings(preset, cleaned)}
+ disabled={isSaved}
+ className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent disabled:opacity-50"
+ >
+ <Save className="size-3.5" /> Save
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ resetSettings(preset);
+ onChange(defaultValues(preset));
+ }}
+ disabled={isDefault && !saved}
+ className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"
+ >
+ <RotateCcw className="size-3.5" /> Reset
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/shorts/custom-preset-dialog.tsx b/src/components/shorts/custom-preset-dialog.tsx
new file mode 100644
index 00000000..cc3e6f5b
--- /dev/null
+++ b/src/components/shorts/custom-preset-dialog.tsx
@@ -0,0 +1,218 @@
+"use client";
+
+import { ImagePlus, Loader2, Trash2, X } from "lucide-react";
+import { useEffect, useId, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { uploadFile } from "@/lib/api";
+import { SHORTS, type ShortsCustomPreset } from "@/lib/catalog/shorts";
+import { cn } from "@/lib/utils";
+import { usePresetActions } from "./hooks";
+
+interface Ref {
+ id: string;
+ preview: string;
+ url?: string;
+ uploading?: boolean;
+}
+
+/** "Create a preset from references": up to 10 images of the look; a name and a few words are optional. */
+export function CustomPresetDialog({
+ open,
+ onOpenChange,
+ preset,
+ onSaved,
+}: {
+ open: boolean;
+ onOpenChange: (v: boolean) => void;
+ /** Edit this one (else create). */
+ preset?: ShortsCustomPreset;
+ onSaved: (p: ShortsCustomPreset) => void;
+}) {
+ const ids = useId();
+ const actions = usePresetActions();
+ const [name, setName] = useState("");
+ const [description, setDescription] = useState("");
+ const [refs, setRefs] = useState<Ref[]>([]);
+ const input = useRef<HTMLInputElement>(null);
+ const [over, setOver] = useState(false);
+
+ // Start from the preset being edited (or empty) each time the dialog opens.
+ const [openedFor, setOpenedFor] = useState<string | null>(null);
+ const key = open ? (preset?.id ?? "new") : null;
+ if (key !== openedFor) {
+ setOpenedFor(key);
+ if (key) {
+ setName(preset?.name ?? "");
+ setDescription(preset?.description ?? "");
+ setRefs((preset?.references ?? []).map((url, i) => ({ id: `${i}-${url}`, preview: url, url })));
+ }
+ }
+
+ // Object URLs of local previews are released when they leave the list or the dialog closes.
+ const previews = useRef(new Set<string>());
+ useEffect(() => {
+ const set = previews.current;
+ return () => set.forEach((u) => URL.revokeObjectURL(u));
+ }, []);
+
+ const add = (files: File[]) => {
+ const room = SHORTS.maxReferences - refs.length;
+ const images = files.filter((f) => f.type.startsWith("image/"));
+ if (images.length < files.length) toast("Only images can be references");
+ if (images.length > room) toast(`A preset takes up to ${SHORTS.maxReferences} images`);
+ for (const f of images.slice(0, Math.max(0, room))) {
+ const local = URL.createObjectURL(f);
+ previews.current.add(local);
+ const id = `${Date.now()}-${Math.random()}`;
+ setRefs((xs) => [...xs, { id, preview: local, uploading: true }]);
+ uploadFile(f)
+ .then((a) => setRefs((xs) => xs.map((r) => (r.id === id ? { ...r, url: a.url, uploading: false } : r))))
+ .catch((e) => {
+ toast.error((e as Error).message);
+ setRefs((xs) => xs.filter((r) => r.id !== id));
+ });
+ }
+ };
+
+ const uploading = refs.some((r) => r.uploading);
+ const ready = refs.filter((r) => r.url).map((r) => r.url!);
+ const busy = actions.create.isPending || actions.update.isPending || actions.remove.isPending;
+
+ const save = () => {
+ if (!ready.length) return void toast("Add at least one reference image");
+ const body = { name: name.trim() || undefined, description: description.trim(), references: ready };
+ const done = (p: ShortsCustomPreset) => {
+ toast.success(preset ? "Preset updated" : "Preset created");
+ onSaved(p);
+ onOpenChange(false);
+ };
+ const fail = (e: Error) => toast.error(e.message);
+ if (preset) actions.update.mutate({ id: preset.id, ...body }, { onSuccess: done, onError: fail });
+ else actions.create.mutate(body, { onSuccess: done, onError: fail });
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[92svh] overflow-y-auto sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{preset ? "Edit preset" : "Create a preset from references"}</DialogTitle>
+ <DialogDescription>Add reference images that show the look you want. The preset learns the style from them.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ add([...e.dataTransfer.files]);
+ }}
+ className={cn("grid grid-cols-4 gap-1.5 rounded-xl border border-dashed p-2 sm:grid-cols-5", over && "border-primary bg-brand-faint")}
+ >
+ {refs.map((r) => (
+ <div key={r.id} className="relative aspect-square overflow-hidden rounded-lg bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={r.preview} alt="" className="size-full object-cover" />
+ {r.uploading && (
+ <span className="absolute inset-0 grid place-items-center bg-background/60" role="status" aria-label="Uploading">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={() => setRefs((xs) => xs.filter((x) => x.id !== r.id))}
+ aria-label="Remove this reference"
+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ {refs.length < SHORTS.maxReferences && (
+ <button
+ type="button"
+ onClick={() => input.current?.click()}
+ className="flex aspect-square flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-border-strong text-muted-foreground hover:border-primary hover:bg-brand-faint hover:text-brand-text"
+ >
+ <ImagePlus className="size-4" />
+ <span className="text-[10px] font-medium">Add</span>
+ </button>
+ )}
+ <input
+ ref={input}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ multiple
+ hidden
+ onChange={(e) => {
+ add([...(e.target.files ?? [])]);
+ e.target.value = "";
+ }}
+ />
+ </div>
+ <p className="text-[12px] text-muted-foreground">
+ {refs.length} of {SHORTS.maxReferences} · stills or frames of shorts in the look you like work best
+ </p>
+ <div className="space-y-1.5">
+ <label htmlFor={`${ids}-name`} className="text-[13px] font-medium">
+ Name
+ </label>
+ <input
+ id={`${ids}-name`}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ maxLength={60}
+ placeholder="Warm slow look"
+ className="h-9 w-full rounded-lg border bg-background px-3 text-[14px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <label htmlFor={`${ids}-desc`} className="text-[13px] font-medium">
+ Describe the look <span className="font-normal text-muted-foreground">(optional)</span>
+ </label>
+ <textarea
+ id={`${ids}-desc`}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ maxLength={300}
+ rows={2}
+ placeholder="e.g. “grainy 16 mm film, warm faded colours, soft halation”"
+ className="w-full resize-none rounded-lg border bg-background px-3 py-2 text-[14px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint"
+ />
+ </div>
+ </div>
+ <DialogFooter className="gap-2 sm:justify-between">
+ {preset ? (
+ <Button
+ variant="ghost"
+ className="text-destructive"
+ disabled={busy}
+ onClick={() =>
+ actions.remove.mutate(preset.id, {
+ onSuccess: () => {
+ toast("Preset deleted");
+ onOpenChange(false);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ })
+ }
+ >
+ <Trash2 /> Delete
+ </Button>
+ ) : (
+ <span />
+ )}
+ <Button onClick={save} disabled={busy || uploading || !ready.length} className="rounded-full">
+ {busy && <Loader2 className="animate-spin" />}
+ {uploading ? "Uploading…" : preset ? "Update preset" : "Create preset"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/shorts/history.tsx b/src/components/shorts/history.tsx
new file mode 100644
index 00000000..24a18b63
--- /dev/null
+++ b/src/components/shorts/history.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { Clapperboard, Cloud, Cpu, Loader2 } from "lucide-react";
+import Link from "next/link";
+import { Skeleton } from "@/components/ui/skeleton";
+import { MediaThumb } from "@/components/studio/result-media";
+import { formatSeconds } from "@/lib/catalog/shorts";
+import { timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { useShortsSessions, type ShortsSessionCard } from "./hooks";
+
+/** History: every session, newest first, with its finished video (or where it got to). */
+export function ShortsHistory({ onStart }: { onStart: () => void }) {
+ const sessions = useShortsSessions();
+ if (sessions.isLoading)
+ return (
+ <div className="grid grid-cols-2 gap-3 pt-8 sm:grid-cols-3 lg:grid-cols-4">
+ {Array.from({ length: 8 }, (_, i) => (
+ <Skeleton key={i} className="aspect-[9/14] rounded-xl" />
+ ))}
+ </div>
+ );
+ if (sessions.error) return <p className="py-16 text-center text-[14px] text-muted-foreground">{(sessions.error as Error).message}</p>;
+ if (!sessions.data?.length)
+ return (
+ <div className="mx-auto flex max-w-md flex-col items-center py-20 text-center">
+ <span className="grid size-12 place-items-center rounded-full bg-brand-faint text-brand-text">
+ <Clapperboard className="size-5" />
+ </span>
+ <p className="mt-4 font-heading text-[22px]">No shorts yet</p>
+ <p className="mt-1 text-[14px] text-muted-foreground">Pick a preset and upload a clip — your shorts and their segments show up here.</p>
+ <button type="button" onClick={onStart} className="mt-5 h-9 rounded-full bg-primary px-4 text-[13px] font-medium text-primary-foreground hover:bg-primary/90">
+ Choose a preset
+ </button>
+ </div>
+ );
+ return (
+ <div className="grid grid-cols-2 gap-3 pt-8 sm:grid-cols-3 lg:grid-cols-4">
+ {sessions.data.map((s) => (
+ <SessionCard key={s.id} s={s} />
+ ))}
+ </div>
+ );
+}
+
+function SessionCard({ s }: { s: ShortsSessionCard }) {
+ const out = s.cover?.status === "succeeded" ? s.cover.outputs.find((o) => o.kind === "video") : undefined;
+ return (
+ <Link href={`/shorts/${s.id}`} className="group/card min-w-0 rounded-xl p-1.5 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">
+ <div className="relative aspect-[9/14] overflow-hidden rounded-lg bg-muted">
+ {out ? (
+ <MediaThumb output={out} />
+ ) : (
+ <div className="skeleton-sweep absolute inset-0 grid place-items-center">{s.status === "rendering" && <Loader2 className="size-5 animate-spin text-muted-foreground" />}</div>
+ )}
+ <span
+ className={cn(
+ "absolute top-1.5 left-1.5 rounded-[4px] px-1.5 text-[10px] font-semibold",
+ s.status === "ready" ? "bg-success text-white" : s.status === "failed" ? "bg-destructive text-white" : "bg-background/85 text-foreground",
+ )}
+ >
+ {s.status === "ready" ? "Ready" : s.status === "failed" ? "Needs a look" : "Rendering"}
+ </span>
+ <span className="absolute top-1.5 right-1.5 grid size-5 place-items-center rounded-full bg-black/35 text-white" title={s.engine === "open" ? "Open source" : "Cloud"}>
+ {s.engine === "open" ? <Cpu className="size-3" /> : <Cloud className="size-3" />}
+ </span>
+ </div>
+ <div className="min-w-0 px-0.5 pt-2">
+ <p className="truncate text-[13px] font-medium">{s.title}</p>
+ <p className="truncate text-[12px] text-muted-foreground">
+ {s.segments} segment{s.segments === 1 ? "" : "s"} · {formatSeconds(s.seconds)} · {timeAgo(s.createdAt)}
+ </p>
+ </div>
+ </Link>
+ );
+}
diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.ts
new file mode 100644
index 00000000..b09f76d9
--- /dev/null
+++ b/src/components/shorts/hooks.ts
@@ -0,0 +1,168 @@
+"use client";
+
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useDeferredValue } from "react";
+import type { ShortsCustomPreset, ShortsRange, ShortsRatio, ShortsSession } from "@/lib/catalog/shorts";
+import type { Engine, Generation } from "@/lib/catalog/types";
+import { useGenerationEvents } from "@/lib/api";
+
+/** React Query hooks for /api/shorts/** (kept next to the studio that uses them). */
+
+async function json<T>(res: Response): Promise<T> {
+ if (res.status === 204) return undefined as T;
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
+ return body;
+}
+
+export const send = async <T>(url: string, method: string, body?: unknown) =>
+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+
+export interface ShortsBody {
+ engine: Engine;
+ presetId: string;
+ source: { url: string; name?: string; duration?: number };
+ range: ShortsRange;
+ aspectRatio: ShortsRatio;
+ language: string;
+ modelId?: string;
+}
+
+export interface ShortsEstimate {
+ costUsd: number | null;
+ perSegmentUsd: number | null;
+ demo: boolean;
+ segments: number;
+ seconds: number;
+ refsSent: number;
+ notes: string[];
+}
+
+export interface ShortsSessionView extends ShortsSession {
+ generations: Record<string, Generation>;
+ regenerateUsd: number | null;
+}
+
+export interface ShortsSessionCard {
+ id: string;
+ title: string;
+ engine: Engine;
+ lookName: string;
+ segments: number;
+ seconds: number;
+ createdAt: number;
+ updatedAt: number;
+ cover: Generation | null;
+ status: "rendering" | "ready" | "failed";
+}
+
+const active = (g?: Generation) => !!g && (g.status === "queued" || g.status === "running");
+
+/** Price and shape of a session before it starts (debounced by React's deferred value). */
+export function useShortsEstimate(body: ShortsBody | null) {
+ const key = useDeferredValue(body ? JSON.stringify(body) : null);
+ return useQuery({
+ queryKey: ["shorts", "estimate", key],
+ queryFn: async () => send<ShortsEstimate>("/api/shorts/estimate", "POST", JSON.parse(key!)),
+ enabled: !!key,
+ placeholderData: keepPreviousData,
+ retry: false,
+ staleTime: 30_000,
+ });
+}
+
+export function useShortsSessions() {
+ const qc = useQueryClient();
+ const connected = useGenerationEvents((ev) => {
+ if (ev.type === "generation" && ev.generation.feature === "shorts") void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] });
+ });
+ return useQuery({
+ queryKey: ["shorts", "sessions"],
+ queryFn: async () => (await json<{ items: ShortsSessionCard[] }>(await fetch("/api/shorts/sessions"))).items,
+ refetchInterval: (q) => (q.state.data?.some((s) => s.status === "rendering") ? (connected ? 10_000 : 2500) : false),
+ });
+}
+
+export function useShortsSession(id: string) {
+ const qc = useQueryClient();
+ const connected = useGenerationEvents((ev) => {
+ const data = qc.getQueryData<ShortsSessionView>(["shorts", "session", id]);
+ const gid = ev.type === "generation" ? ev.generation.id : ev.id;
+ if (!data) return;
+ if (ev.type === "generation" && data.generations[gid]) {
+ // Patch the row in place (progress, status, outputs); a new id refetches the session.
+ qc.setQueryData<ShortsSessionView>(["shorts", "session", id], { ...data, generations: { ...data.generations, [gid]: ev.generation } });
+ } else if (ev.type === "deleted" && data.generations[gid]) void qc.invalidateQueries({ queryKey: ["shorts", "session", id] });
+ });
+ return useQuery({
+ queryKey: ["shorts", "session", id],
+ queryFn: async () => json<ShortsSessionView>(await fetch(`/api/shorts/sessions/${id}`)),
+ retry: (n, e) => n < 1 && !/no longer exists/.test((e as Error).message),
+ refetchInterval: (q) => (Object.values(q.state.data?.generations ?? {}).some(active) ? (connected ? 8000 : 1500) : false),
+ });
+}
+
+export function useShortsPresets() {
+ return useQuery({
+ queryKey: ["shorts", "presets"],
+ queryFn: async () => (await json<{ items: ShortsCustomPreset[] }>(await fetch("/api/shorts/presets"))).items,
+ staleTime: 30_000,
+ });
+}
+
+export function useShortsActions(id?: string) {
+ const qc = useQueryClient();
+ const put = (s: ShortsSessionView) => {
+ qc.setQueryData(["shorts", "session", s.id], (old: ShortsSessionView | undefined) => ({ ...s, regenerateUsd: old?.regenerateUsd ?? null }));
+ void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] });
+ };
+ return {
+ create: useMutation({
+ mutationFn: (body: ShortsBody) => send<ShortsSession>("/api/shorts/sessions", "POST", body),
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] }),
+ }),
+ regenerate: useMutation({
+ mutationFn: (index: number) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${index}`, "POST"),
+ onSuccess: put,
+ }),
+ primary: useMutation({
+ mutationFn: (v: { index: number; generationId: string }) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${v.index}/primary`, "POST", { generationId: v.generationId }),
+ onSuccess: put,
+ }),
+ stitch: useMutation({
+ mutationFn: () => send<ShortsSessionView>(`/api/shorts/sessions/${id}/stitch`, "POST"),
+ onSuccess: put,
+ }),
+ rename: useMutation({
+ mutationFn: (title: string) => send<ShortsSession>(`/api/shorts/sessions/${id}`, "PATCH", { title }),
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["shorts"] }),
+ }),
+ remove: useMutation({
+ mutationFn: (sid: string) => send<{ trashed: number }>(`/api/shorts/sessions/${sid}`, "DELETE"),
+ onSuccess: () => {
+ void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] });
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ void qc.invalidateQueries({ queryKey: ["library"] });
+ },
+ }),
+ };
+}
+
+export function usePresetActions() {
+ const qc = useQueryClient();
+ const done = () => void qc.invalidateQueries({ queryKey: ["shorts", "presets"] });
+ return {
+ create: useMutation({
+ mutationFn: (b: { name?: string; description?: string; references: string[] }) => send<ShortsCustomPreset>("/api/shorts/presets", "POST", b),
+ onSuccess: done,
+ }),
+ update: useMutation({
+ mutationFn: (b: { id: string; name?: string; description?: string; references?: string[] }) => send<ShortsCustomPreset>(`/api/shorts/presets/${b.id}`, "PATCH", b),
+ onSuccess: done,
+ }),
+ remove: useMutation({
+ mutationFn: (pid: string) => send<void>(`/api/shorts/presets/${pid}`, "DELETE"),
+ onSuccess: done,
+ }),
+ };
+}
diff --git a/src/components/shorts/preset-card.tsx b/src/components/shorts/preset-card.tsx
new file mode 100644
index 00000000..11b9f806
--- /dev/null
+++ b/src/components/shorts/preset-card.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import { Check, Pencil, Plus } from "lucide-react";
+import { memo } from "react";
+import { PresetPreview, usePreviewPlayback } from "@/components/preset-preview";
+import type { PresetPreview as Preview } from "@/lib/preset-cards";
+import { cn } from "@/lib/utils";
+
+/**
+ * A selectable look card (Shorts Studio and Mixed Media): the procedural preview from the
+ * galleries (plays on hover or focus, the centred card on phones), name and one line.
+ */
+export const LookCard = memo(function LookCard({
+ id,
+ name,
+ description,
+ preview,
+ hue,
+ selected,
+ onSelect,
+ badge,
+}: {
+ id: string;
+ name: string;
+ description: string;
+ preview: Preview;
+ hue: number;
+ selected: boolean;
+ onSelect: (id: string) => void;
+ badge?: string;
+}) {
+ const { ref, playing, handlers } = usePreviewPlayback<HTMLButtonElement>(id);
+ return (
+ <button
+ ref={ref}
+ type="button"
+ {...handlers}
+ onClick={() => onSelect(id)}
+ aria-pressed={selected}
+ data-look={id}
+ className={cn(
+ "group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 text-left transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
+ selected && "bg-brand-faint hover:bg-brand-faint-hover",
+ )}
+ >
+ <div className={cn("relative aspect-[4/5] w-full overflow-hidden rounded-lg bg-muted ring-offset-2 ring-offset-background transition-shadow", selected && "ring-2 ring-primary")}>
+ <PresetPreview preview={preview} hue={hue} playing={playing} />
+ <span className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-black/40 to-transparent" />
+ {badge && <span className="absolute top-1.5 left-1.5 rounded-[4px] bg-black/45 px-1.5 text-[10px] font-medium text-white backdrop-blur">{badge}</span>}
+ {selected && (
+ <span className="absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground shadow-soft">
+ <Check className="size-3.5" />
+ </span>
+ )}
+ </div>
+ <div className="min-w-0 px-0.5">
+ <p className="truncate text-[13px] font-medium">{name}</p>
+ <p className="line-clamp-2 text-[12px] leading-snug text-muted-foreground">{description}</p>
+ </div>
+ </button>
+ );
+});
+
+/** A custom preset: its reference images as a mosaic. */
+export function CustomCard({
+ id,
+ name,
+ description,
+ references,
+ selected,
+ onSelect,
+ onEdit,
+}: {
+ id: string;
+ name: string;
+ description: string;
+ references: string[];
+ selected: boolean;
+ onSelect: (id: string) => void;
+ onEdit: (id: string) => void;
+}) {
+ const tiles = references.slice(0, 4);
+ return (
+ <div className={cn("group/card relative flex min-w-0 flex-col gap-2 rounded-xl p-1.5 transition-colors hover:bg-accent", selected && "bg-brand-faint hover:bg-brand-faint-hover")}>
+ <button
+ type="button"
+ onClick={() => onSelect(id)}
+ aria-pressed={selected}
+ data-look={id}
+ className="flex min-w-0 flex-col gap-2 rounded-lg text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <div className={cn("relative grid aspect-[4/5] w-full gap-0.5 overflow-hidden rounded-lg bg-muted ring-offset-2 ring-offset-background", tiles.length > 1 && "grid-cols-2", selected && "ring-2 ring-primary")}>
+ {tiles.map((src, i) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={i} src={src} alt="" loading="lazy" className={cn("size-full object-cover", tiles.length === 3 && i === 0 && "row-span-2")} />
+ ))}
+ <span className="absolute top-1.5 left-1.5 rounded-[4px] bg-black/45 px-1.5 text-[10px] font-medium text-white backdrop-blur">Created by you</span>
+ {selected && (
+ <span className="absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground shadow-soft">
+ <Check className="size-3.5" />
+ </span>
+ )}
+ </div>
+ <div className="min-w-0 px-0.5">
+ <p className="truncate pr-7 text-[13px] font-medium">{name}</p>
+ <p className="line-clamp-2 text-[12px] leading-snug text-muted-foreground">{description || `${references.length} reference image${references.length === 1 ? "" : "s"}`}</p>
+ </div>
+ </button>
+ <button
+ type="button"
+ onClick={() => onEdit(id)}
+ aria-label={`Edit ${name}`}
+ className="absolute right-2 bottom-[2.6rem] grid size-7 place-items-center rounded-full text-muted-foreground opacity-100 transition-opacity hover:bg-background hover:text-foreground focus-visible:opacity-100 sm:opacity-0 sm:group-hover/card:opacity-100"
+ >
+ <Pencil className="size-3.5" />
+ </button>
+ </div>
+ );
+}
+
+/** "Create a preset from references". */
+export function CreateCard({ onClick }: { onClick: () => void }) {
+ return (
+ <button type="button" onClick={onClick} className="group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">
+ <div className="flex aspect-[4/5] w-full flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border-strong text-muted-foreground transition-colors group-hover/card:border-primary group-hover/card:text-brand-text">
+ <span className="grid size-10 place-items-center rounded-full bg-brand-faint text-brand-text">
+ <Plus className="size-5" />
+ </span>
+ <span className="px-3 text-center text-[12px] leading-snug">From your references</span>
+ </div>
+ <div className="min-w-0 px-0.5">
+ <p className="truncate text-[13px] font-medium">Create a preset</p>
+ <p className="line-clamp-2 text-[12px] leading-snug text-muted-foreground">Up to 10 images of the look you want</p>
+ </div>
+ </button>
+ );
+}
diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsx
new file mode 100644
index 00000000..b01b67ea
--- /dev/null
+++ b/src/components/shorts/session-view.tsx
@@ -0,0 +1,394 @@
+"use client";
+
+import { ArrowLeft, Check, Cloud, Cpu, Download, FolderDown, Layers, Loader2, RotateCcw, Scissors, Trash2 } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { NotFoundState } from "@/components/empty-state";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { MediaThumb } from "@/components/studio/result-media";
+import { Viewer } from "@/components/studio/viewer";
+import { chainState, formatSeconds, stitchCurrent, stitchSteps, takeSteps, type ChainState, type ShortsSessionSegment } from "@/lib/catalog/shorts";
+import type { Generation } from "@/lib/catalog/types";
+import { formatCost, ratioValue, timeAgo } from "@/lib/format";
+import { downloadHref, downloadName } from "@/lib/library";
+import { cn } from "@/lib/utils";
+import { useShortsActions, useShortsSession, type ShortsSessionView as View } from "./hooks";
+import { Steps } from "./ui";
+
+const STEPS = ["Choose preset", "Upload video", "Download"];
+
+const videoOf = (g?: Generation) => (g?.status === "succeeded" ? g.outputs.find((o) => o.kind === "video") : undefined);
+
+function StateChip({ state }: { state: ChainState }) {
+ return (
+ <span
+ className={cn(
+ "inline-flex h-6 shrink-0 items-center gap-1 rounded-full px-2 text-[11px] font-medium",
+ state.status === "done" && "bg-success/15 text-success",
+ state.status === "working" && "bg-brand-faint text-brand-text",
+ (state.status === "failed" || state.status === "gone") && "bg-destructive/10 text-destructive",
+ )}
+ >
+ {state.status === "done" ? <Check className="size-3" /> : state.status === "working" ? <Loader2 className="size-3 animate-spin" /> : null}
+ {state.status === "done" ? "Ready" : state.status === "working" ? `${Math.round(state.progress * 100)}%` : state.status === "gone" ? "Deleted" : "Failed"}
+ </span>
+ );
+}
+
+/** Step 3: the session — the full video, the segments with their takes, Regenerate, Stitch again, downloads. */
+export function ShortsSessionView({ id }: { id: string }) {
+ const q = useShortsSession(id);
+ if (q.isLoading)
+ return (
+ <Frame title="Loading…">
+ <div className="mt-8 grid gap-8 lg:grid-cols-[minmax(0,380px)_minmax(0,1fr)]">
+ <Skeleton className="mx-auto aspect-[9/16] w-full max-w-[360px] rounded-2xl" />
+ <div className="space-y-3">
+ {Array.from({ length: 3 }, (_, i) => (
+ <Skeleton key={i} className="h-36 rounded-2xl" />
+ ))}
+ </div>
+ </div>
+ </Frame>
+ );
+ if (q.error || !q.data)
+ return (
+ <Frame title="Shorts Studio">
+ <NotFoundState title="This short no longer exists">It was deleted, or the link is wrong. Its videos may still be in your Library or the Trash.</NotFoundState>
+ </Frame>
+ );
+ return <Session s={q.data} />;
+}
+
+function Frame({ title, children, actions }: { title: string; children: React.ReactNode; actions?: React.ReactNode }) {
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <Link href="/shorts?tab=history" aria-label="Back to your shorts" className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <ArrowLeft className="size-4" />
+ </Link>
+ <h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{title}</h1>
+ <div className="ml-auto flex items-center gap-1">{actions}</div>
+ </header>
+ <main className="mx-auto w-full max-w-[1180px] min-w-0 flex-1 px-3 pb-16 sm:px-6">{children}</main>
+ </div>
+ );
+}
+
+function Session({ s }: { s: View }) {
+ const router = useRouter();
+ const actions = useShortsActions(s.id);
+ const [open, setOpen] = useState<Generation | null>(null);
+ const [confirm, setConfirm] = useState(false);
+ const gens = s.generations;
+ const stitch = s.stitches[s.stitches.length - 1];
+ const finalState = stitch ? chainState(stitchSteps(stitch, gens)) : null;
+ const segStates = s.segments.map((seg) => {
+ const take = seg.takes.find((t) => t.look === seg.primary) ?? seg.takes[seg.takes.length - 1];
+ return chainState(takeSteps(take, gens));
+ });
+ const allDone = segStates.every((x) => x.status === "done");
+ const outdated = !stitchCurrent(s);
+ const final = stitch ? gens[stitch.final] : undefined;
+ const finalVideo = videoOf(final);
+ const canStitch = allDone && (outdated || finalState?.status === "failed" || finalState?.status === "gone");
+ const ratio = ratioValue(s.settings.aspectRatio, 9 / 16);
+ const working = segStates.filter((x) => x.status === "working").length;
+ const overall = (segStates.reduce((n, x) => n + (x.status === "done" ? 1 : x.progress), 0) + (finalState?.status === "done" ? 1 : (finalState?.progress ?? 0))) / (segStates.length + 1);
+ const parts = s.segments.map((g) => g.primary).filter((id) => videoOf(gens[id]));
+
+ const stitchAgain = () =>
+ actions.stitch.mutate(undefined, {
+ onSuccess: () => toast("Stitching your short"),
+ onError: (e) => toast.error((e as Error).message),
+ });
+
+ return (
+ <Frame
+ title={s.title}
+ actions={
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button type="button" onClick={() => setConfirm(true)} aria-label="Delete this short" className="grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-destructive">
+ <Trash2 className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Delete this short</TooltipContent>
+ </Tooltip>
+ }
+ >
+ <Steps steps={STEPS} current={finalVideo && !outdated ? 3 : 2} className="pt-6" />
+ <div className="mt-6 grid min-w-0 gap-8 lg:grid-cols-[minmax(0,380px)_minmax(0,1fr)] lg:items-start">
+ <section aria-label="Full video" className="min-w-0 space-y-3 lg:sticky lg:top-16">
+ <div className="relative mx-auto max-h-[72svh] w-full overflow-hidden rounded-2xl bg-muted" style={{ aspectRatio: ratio, maxWidth: ratio < 1 ? 360 : undefined }}>
+ {finalVideo ? (
+ <video src={finalVideo.url} controls playsInline preload="metadata" className="size-full bg-black object-contain" aria-label="Your short" />
+ ) : finalState?.status === "failed" || finalState?.status === "gone" ? (
+ <div className="flex size-full flex-col justify-center gap-2 p-5 text-center">
+ <p className="text-[14px] font-medium">{finalState.status === "gone" ? "The full video was deleted" : "Couldn't stitch the full video"}</p>
+ {finalState.error && <p className="line-clamp-6 text-[12px] break-words text-muted-foreground">{finalState.error}</p>}
+ </div>
+ ) : (
+ <div className="flex size-full flex-col items-center justify-center gap-2 p-5 text-center">
+ <div className="skeleton-sweep absolute inset-0 animate-skeleton" />
+ <p className="shimmer-text relative animate-shimmer-text text-[14px] font-medium">Preparing full video…</p>
+ <p className="relative font-mono text-[12px] text-muted-foreground tabular-nums">
+ {working ? `${working} of ${segStates.length} segment${segStates.length === 1 ? "" : "s"} rendering · ` : (finalState?.label ?? "") + " · "}
+ {Math.round(overall * 100)}%
+ </p>
+ <div className="relative h-1 w-40 overflow-hidden rounded-full bg-background/70">
+ <div className="h-full bg-primary transition-[width] duration-500" style={{ width: `${Math.round(overall * 100)}%` }} />
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="flex flex-wrap justify-center gap-2 lg:justify-start">
+ {finalVideo && final && (
+ <a
+ href={downloadHref(finalVideo.url, downloadName(final, finalVideo, 0))}
+ download={downloadName(final, finalVideo, 0)}
+ className="inline-flex h-9 items-center gap-1.5 rounded-full bg-primary px-4 text-[13px] font-medium text-primary-foreground hover:bg-primary/90"
+ >
+ <Download className="size-4" /> Download full video
+ </a>
+ )}
+ {parts.length > 0 && (
+ <a href={`/api/generations/zip?ids=${parts.join(",")}`} className="inline-flex h-9 items-center gap-1.5 rounded-full border bg-background px-4 text-[13px] font-medium hover:bg-accent">
+ <FolderDown className="size-4" /> Download parts{parts.length < s.segments.length ? ` (${parts.length})` : ""}
+ </a>
+ )}
+ {(canStitch || (outdated && !allDone)) && (
+ <button
+ type="button"
+ onClick={stitchAgain}
+ aria-disabled={!canStitch || actions.stitch.isPending}
+ className={cn(
+ "inline-flex h-9 items-center gap-1.5 rounded-full border px-4 text-[13px] font-medium",
+ canStitch ? "bg-background hover:bg-accent" : "cursor-not-allowed text-subtle-foreground",
+ )}
+ title={canStitch ? undefined : "Ready when every segment has rendered"}
+ >
+ {actions.stitch.isPending ? <Loader2 className="size-4 animate-spin" /> : <Layers className="size-4" />} Stitch again
+ </button>
+ )}
+ </div>
+ {outdated && <p className="text-center text-[12px] text-brand-text lg:text-left">You picked different takes — stitch again to update the full video.</p>}
+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1 rounded-xl bg-muted/50 p-3 text-[12px]">
+ <dt className="text-muted-foreground">Preset</dt>
+ <dd className="truncate">{s.look.name}</dd>
+ <dt className="text-muted-foreground">Engine</dt>
+ <dd className="flex items-center gap-1">
+ {s.engine === "open" ? <Cpu className="size-3" /> : <Cloud className="size-3" />}
+ {s.engine === "open" ? "Open source" : "Cloud"}
+ </dd>
+ <dt className="text-muted-foreground">Selection</dt>
+ <dd>
+ {formatSeconds(s.range.start)}–{formatSeconds(s.range.end)} ({(s.range.end - s.range.start).toFixed(1)} s)
+ </dd>
+ <dt className="text-muted-foreground">Output</dt>
+ <dd>
+ {s.settings.aspectRatio} · {s.settings.language === "auto" ? "Auto language" : s.settings.language}
+ {s.source.hasAudio === false ? " · no sound" : ""}
+ </dd>
+ <dt className="text-muted-foreground">Started</dt>
+ <dd>{timeAgo(s.createdAt)}</dd>
+ </dl>
+ </section>
+
+ <section aria-labelledby="segments-title" className="min-w-0 space-y-3">
+ <div className="flex items-baseline justify-between gap-2">
+ <h2 id="segments-title" className="text-[15px] font-semibold">
+ {s.segments.length} segment{s.segments.length === 1 ? "" : "s"}
+ </h2>
+ <span className="text-[12px] text-muted-foreground">Regenerate one, then pick the take you like</span>
+ </div>
+ <div className="grid gap-3 sm:grid-cols-2">
+ {s.segments.map((seg, i) => (
+ <SegmentCard
+ key={seg.index}
+ seg={seg}
+ index={i}
+ state={segStates[i]}
+ gens={gens}
+ ratio={ratio}
+ cost={s.regenerateUsd}
+ demo={Object.values(gens).some((g) => g.provider === "mock")}
+ onOpen={setOpen}
+ onRegenerate={() =>
+ actions.regenerate.mutate(i, {
+ onSuccess: () => toast(`New take of segment ${i + 1} on the way`),
+ onError: (e) => toast.error((e as Error).message),
+ })
+ }
+ regenerating={actions.regenerate.isPending && actions.regenerate.variables === i}
+ onPrimary={(gid) => actions.primary.mutate({ index: i, generationId: gid }, { onError: (e) => toast.error((e as Error).message) })}
+ />
+ ))}
+ </div>
+ </section>
+ </div>
+ {open && <Viewer generation={open} index={0} onClose={() => setOpen(null)} />}
+ <AlertDialog open={confirm} onOpenChange={setConfirm}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete this short?</AlertDialogTitle>
+ <AlertDialogDescription>Its segments and videos move to the Trash, where you can restore them for 30 days.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep it</AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive text-white hover:bg-destructive/90"
+ onClick={() =>
+ actions.remove.mutate(s.id, {
+ onSuccess: () => {
+ toast("Moved to Trash");
+ router.push("/shorts?tab=history");
+ },
+ onError: (e) => toast.error((e as Error).message),
+ })
+ }
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </Frame>
+ );
+}
+
+function SegmentCard({
+ seg,
+ index,
+ state,
+ gens,
+ ratio,
+ cost,
+ demo,
+ onOpen,
+ onRegenerate,
+ regenerating,
+ onPrimary,
+}: {
+ seg: ShortsSessionSegment;
+ index: number;
+ state: ChainState;
+ gens: Record<string, Generation>;
+ ratio: number;
+ cost: number | null;
+ demo: boolean;
+ onOpen: (g: Generation) => void;
+ onRegenerate: () => void;
+ regenerating: boolean;
+ onPrimary: (id: string) => void;
+}) {
+ const primary = gens[seg.primary];
+ const video = videoOf(primary);
+ const price = demo ? "Demo · free" : cost === null ? "" : cost === 0 ? "Free" : `≈ ${formatCost(cost)}`;
+ return (
+ <article className="min-w-0 rounded-2xl border bg-background p-3 sm:p-4" aria-label={`Segment ${index + 1}`}>
+ <div className="flex items-center gap-2">
+ <Scissors className="size-3.5 shrink-0 text-muted-foreground" />
+ <h3 className="text-[14px] font-medium">Segment {index + 1}</h3>
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">
+ {formatSeconds(seg.start)}–{formatSeconds(seg.end)}
+ </span>
+ <span className="ml-auto">
+ <StateChip state={state} />
+ </span>
+ </div>
+ <div className="mt-3 min-w-0 space-y-3">
+ <div className="relative mx-auto h-44 max-w-full overflow-hidden rounded-xl bg-muted sm:h-52" style={{ aspectRatio: ratio }}>
+ {video && primary ? (
+ <button type="button" onClick={() => onOpen(primary)} aria-label={`Open segment ${index + 1}`} className="block size-full outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <MediaThumb output={video} />
+ </button>
+ ) : state.status === "working" ? (
+ <div className="skeleton-sweep absolute inset-0 animate-skeleton" />
+ ) : (
+ <div className="grid size-full place-items-center p-2 text-center text-[11px] text-muted-foreground">{state.status === "gone" ? "Deleted" : "No video"}</div>
+ )}
+ </div>
+ <div className="min-w-0 space-y-2">
+ {state.status === "working" && (
+ <p className="shimmer-text animate-shimmer-text text-[13px] font-medium" aria-live="polite">
+ {state.label}…
+ </p>
+ )}
+ {(state.status === "failed" || state.status === "gone") && (
+ <div className="space-y-0.5">
+ <p className="text-[13px] font-medium">{state.label}</p>
+ {state.error && <p className="line-clamp-3 text-[12px] break-words text-muted-foreground">{state.error}</p>}
+ </div>
+ )}
+ {state.status === "done" && <p className="text-[13px] text-muted-foreground">Take {seg.takes.findIndex((t) => t.look === seg.primary) + 1} is in the full video.</p>}
+ {seg.takes.length > 1 && (
+ <div role="radiogroup" aria-label={`Takes of segment ${index + 1}`} className="flex flex-wrap gap-1.5">
+ {seg.takes.map((t, ti) => {
+ const g = gens[t.look];
+ const v = videoOf(g);
+ const st = chainState(takeSteps(t, gens));
+ const chosen = seg.primary === t.look;
+ return (
+ <button
+ key={t.look}
+ type="button"
+ role="radio"
+ aria-checked={chosen}
+ aria-label={`Take ${ti + 1}${st.status === "done" ? "" : ` (${st.status === "working" ? "rendering" : st.status})`}`}
+ disabled={st.status !== "done" || chosen}
+ onClick={() => onPrimary(t.look)}
+ title={st.status === "done" ? (chosen ? "In the full video" : "Use this take") : st.status === "working" ? "Still rendering" : st.error}
+ className={cn(
+ "relative size-12 overflow-hidden rounded-lg bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default",
+ chosen ? "ring-2 ring-primary" : st.status === "done" && "hover:ring-2 hover:ring-border-strong",
+ )}
+ >
+ {v ? <MediaThumb output={v} /> : st.status === "working" ? <Loader2 className="mx-auto size-3.5 animate-spin text-muted-foreground" /> : null}
+ <span className="absolute bottom-0.5 left-0.5 rounded bg-black/55 px-1 text-[10px] font-semibold text-white">{ti + 1}</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ onClick={onRegenerate}
+ disabled={regenerating}
+ className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent disabled:opacity-60"
+ >
+ {regenerating ? <Loader2 className="size-3.5 animate-spin" /> : <RotateCcw className="size-3.5" />}
+ Regenerate
+ {price && <span className="font-mono text-[11px] font-normal text-muted-foreground">{price}</span>}
+ </button>
+ {video && primary && (
+ <a
+ href={downloadHref(video.url, downloadName(primary, video, 0))}
+ download={downloadName(primary, video, 0)}
+ className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
+ >
+ <Download className="size-3.5" /> Part {index + 1}
+ </a>
+ )}
+ </div>
+ </div>
+ </div>
+ </article>
+ );
+}
diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsx
new file mode 100644
index 00000000..4b2d20cb
--- /dev/null
+++ b/src/components/shorts/shorts-studio.tsx
@@ -0,0 +1,501 @@
+"use client";
+
+import { ArrowDown, ArrowRight, Cloud, Cpu, Info, Loader2, Search, Sparkles, X } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { VideoTrimmer } from "@/components/studio/video-trimmer";
+import { useEngine } from "@/lib/api";
+import {
+ rangeProblem,
+ SHORTS,
+ SHORTS_CATEGORIES,
+ SHORTS_LANGUAGES,
+ SHORTS_PRESETS,
+ SHORTS_RATIOS,
+ shortsPreview,
+ type ShortsCustomPreset,
+ type ShortsRatio,
+} from "@/lib/catalog/shorts";
+import type { RestyleModelInfo } from "@/lib/catalog/shorts-models";
+import type { Engine } from "@/lib/catalog/types";
+import type { TrimRange } from "@/lib/trim-range";
+import { cn } from "@/lib/utils";
+import { CustomPresetDialog } from "./custom-preset-dialog";
+import { useShortsActions, useShortsEstimate, useShortsPresets, type ShortsBody } from "./hooks";
+import { CreateCard, CustomCard, LookCard } from "./preset-card";
+import { ShortsHistory } from "./history";
+import { ClipBar, ClipDrop, costText, Field, Segmented, Steps } from "./ui";
+import { clipDuration, useSourceClip } from "./use-source-clip";
+
+export type ModelChoice = RestyleModelInfo;
+
+const STEPS = ["Choose preset", "Upload video", "Download"];
+const CUSTOM = "Created by you";
+
+/** Shorts Studio: choose a preset → upload and trim a clip → generate a session (then /shorts/[id]). */
+export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]> }) {
+ const [tab, setTab] = useState<"presets" | "history">("presets");
+ const [engine, setEngine] = useEngine();
+ const [presetId, setPresetId] = useState<string | null>(null);
+ const source = useSourceClip(SHORTS.maxBytes);
+ const { clip } = source;
+ const [range, setRange] = useState<TrimRange | null>(null);
+
+ // Hand-offs: /shorts?tab=history, ?preset=shorts-claymation, ?video=/api/files/….
+ useEffect(() => {
+ const p = new URLSearchParams(window.location.search);
+ /* eslint-disable react-hooks/set-state-in-effect -- read once after hydration (no Suspense boundary needed) */
+ if (p.get("tab") === "history") setTab("history");
+ const preset = p.get("preset");
+ if (preset) setPresetId(preset);
+ /* eslint-enable react-hooks/set-state-in-effect */
+ const video = p.get("video");
+ if (video?.startsWith("/api/files/")) source.adopt(video, video.split("/").pop());
+ // Once, on arrival.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const pickTab = (t: "presets" | "history") => {
+ setTab(t);
+ const url = new URL(window.location.href);
+ if (t === "history") url.searchParams.set("tab", "history");
+ else url.searchParams.delete("tab");
+ window.history.replaceState(null, "", url);
+ };
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <h1 className="truncate font-heading text-[22px] leading-none">Shorts Studio</h1>
+ <div role="tablist" aria-label="Shorts Studio" className="ml-2 flex h-8 items-center rounded-full bg-muted p-0.5 sm:ml-4">
+ {(["presets", "history"] as const).map((t) => (
+ <button
+ key={t}
+ role="tab"
+ type="button"
+ aria-selected={tab === t}
+ onClick={() => pickTab(t)}
+ className={cn("h-7 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:text-foreground", tab === t && "bg-background text-foreground shadow-soft")}
+ >
+ {t === "presets" ? "Presets" : "History"}
+ </button>
+ ))}
+ </div>
+ <div className="ml-auto">
+ <EngineSwitch value={engine} onChange={setEngine} />
+ </div>
+ </header>
+ <main className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-3 pb-28 sm:px-6 lg:pb-16">
+ {tab === "history" ? (
+ <ShortsHistory onStart={() => pickTab("presets")} />
+ ) : (
+ <>
+ <div className="mx-auto max-w-[720px] pt-8 pb-6 text-center sm:pt-12">
+ <p className="text-[12px] font-semibold tracking-[0.14em] text-brand-text uppercase">Restyle your own footage</p>
+ <h2 className="mt-2 font-heading text-display text-balance">Give your footage the spotlight</h2>
+ <p className="mx-auto mt-2 max-w-[560px] text-body text-pretty text-muted-foreground">
+ Upload a clip, pick a look, get a finished short. Motion stays yours — up to 2 minutes in, cut into segments and stitched back under your sound.
+ </p>
+ <Steps steps={STEPS} current={!presetId ? 0 : !clip?.url ? 1 : 1} className="mt-5" />
+ </div>
+ <Workspace
+ engine={engine}
+ models={models[engine]}
+ presetId={presetId}
+ setPresetId={setPresetId}
+ source={source}
+ range={range}
+ setRange={setRange}
+ />
+ </>
+ )}
+ </main>
+ </div>
+ );
+}
+
+function Workspace({
+ engine,
+ models,
+ presetId,
+ setPresetId,
+ source,
+ range,
+ setRange,
+}: {
+ engine: Engine;
+ models: ModelChoice[];
+ presetId: string | null;
+ setPresetId: (id: string) => void;
+ source: ReturnType<typeof useSourceClip>;
+ range: TrimRange | null;
+ setRange: (r: TrimRange | null) => void;
+}) {
+ const custom = useShortsPresets();
+ const [dialog, setDialog] = useState<{ open: boolean; preset?: ShortsCustomPreset }>({ open: false });
+ const setup = useRef<HTMLElement>(null);
+ const selectedBuiltIn = SHORTS_PRESETS.find((p) => p.id === presetId);
+ const selectedCustom = custom.data?.find((p) => p.id === presetId);
+ const selectedName = selectedBuiltIn?.name ?? selectedCustom?.name;
+
+ // Phones: after picking a look, a bar points down to the upload step until it's on screen.
+ const [setupVisible, setSetupVisible] = useState(false);
+ useEffect(() => {
+ const el = setup.current;
+ if (!el) return;
+ const io = new IntersectionObserver(([e]) => setSetupVisible(e.isIntersecting), { rootMargin: "0px 0px -30% 0px" });
+ io.observe(el);
+ return () => io.disconnect();
+ }, []);
+
+ return (
+ <div className="grid min-w-0 gap-6 lg:grid-cols-[minmax(0,1fr)_400px] lg:items-start">
+ <section aria-labelledby="shorts-step-1" className="min-w-0 space-y-4">
+ <PresetGrid
+ custom={custom.data ?? []}
+ presetId={presetId}
+ onSelect={setPresetId}
+ onCreate={() => setDialog({ open: true })}
+ onEdit={(id) => setDialog({ open: true, preset: custom.data?.find((p) => p.id === id) })}
+ />
+ </section>
+ <aside ref={setup} id="shorts-setup" aria-labelledby="shorts-step-2" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">
+ <SetupPanel
+ engine={engine}
+ models={models}
+ presetId={presetId}
+ presetName={selectedName}
+ customRefs={selectedCustom?.references.length ?? 0}
+ source={source}
+ range={range}
+ setRange={setRange}
+ />
+ </aside>
+ {selectedName && !setupVisible && (
+ <div className="fixed inset-x-3 bottom-[max(0.75rem,env(safe-area-inset-bottom))] z-30 lg:hidden">
+ <button
+ type="button"
+ onClick={() => setup.current?.scrollIntoView({ behavior: "smooth", block: "start" })}
+ className="flex h-12 w-full items-center gap-2 rounded-full bg-foreground px-4 text-[14px] font-medium text-background shadow-strong"
+ >
+ <Sparkles className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate text-left">{selectedName}</span>
+ <span className="flex shrink-0 items-center gap-1">
+ Upload video <ArrowDown className="size-4" />
+ </span>
+ </button>
+ </div>
+ )}
+ <CustomPresetDialog open={dialog.open} preset={dialog.preset} onOpenChange={(open) => setDialog((d) => ({ ...d, open }))} onSaved={(p) => setPresetId(p.id)} />
+ </div>
+ );
+}
+
+function PresetGrid({
+ custom,
+ presetId,
+ onSelect,
+ onCreate,
+ onEdit,
+}: {
+ custom: ShortsCustomPreset[];
+ presetId: string | null;
+ onSelect: (id: string) => void;
+ onCreate: () => void;
+ onEdit: (id: string) => void;
+}) {
+ const [q, setQ] = useState("");
+ const [cat, setCat] = useState<string>("All");
+ const query = useDeferredValue(q.trim().toLowerCase());
+ const cats = ["All", ...(custom.length ? [CUSTOM] : []), ...SHORTS_CATEGORIES];
+ const list = useMemo(
+ () => SHORTS_PRESETS.filter((p) => (cat === "All" || p.category === cat) && (!query || `${p.name} ${p.description} ${p.category}`.toLowerCase().includes(query))),
+ [cat, query],
+ );
+ const mine = custom.filter((p) => (cat === "All" || cat === CUSTOM) && (!query || `${p.name} ${p.description}`.toLowerCase().includes(query)));
+ const showBuiltIn = cat !== CUSTOM;
+ return (
+ <>
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
+ <h3 id="shorts-step-1" className="flex items-center gap-2 text-[15px] font-semibold">
+ <span className="grid size-6 place-items-center rounded-full bg-primary text-[12px] text-primary-foreground">1</span>
+ Choose a preset
+ </h3>
+ <div className="relative w-full sm:ml-auto sm:w-64">
+ <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="search"
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ placeholder={`Search ${SHORTS_PRESETS.length} presets`}
+ aria-label="Search presets"
+ className="h-9 w-full rounded-full border bg-background pr-9 pl-9 text-[14px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint [&::-webkit-search-cancel-button]:hidden"
+ />
+ {q && (
+ <button type="button" onClick={() => setQ("")} aria-label="Clear search" className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-accent">
+ <X className="size-3.5" />
+ </button>
+ )}
+ </div>
+ </div>
+ <div role="group" aria-label="Categories" className="fade-x scrollbar-none -mx-1 flex gap-1 overflow-x-auto px-1">
+ {cats.map((c) => (
+ <button
+ key={c}
+ type="button"
+ aria-pressed={cat === c}
+ onClick={() => setCat(c)}
+ className={cn("h-8 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent hover:text-foreground", cat === c && "bg-secondary text-foreground")}
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ <div className="grid grid-cols-2 gap-1 sm:grid-cols-3 xl:grid-cols-4">
+ {!query && (cat === "All" || cat === CUSTOM) && <CreateCard onClick={onCreate} />}
+ {mine.map((p) => (
+ <CustomCard key={p.id} {...p} selected={presetId === p.id} onSelect={onSelect} onEdit={onEdit} />
+ ))}
+ {showBuiltIn &&
+ list.map((p) => (
+ <LookCard key={p.id} id={p.id} name={p.name} description={p.description} preview={shortsPreview(p)} hue={p.hue} selected={presetId === p.id} onSelect={onSelect} badge={p.type ? "Type" : undefined} />
+ ))}
+ </div>
+ {showBuiltIn && !list.length && !mine.length && (
+ <div className="py-12 text-center">
+ <p className="font-heading text-[22px]">No presets match “{q.trim()}”</p>
+ <button type="button" onClick={() => (setQ(""), setCat("All"))} className="mt-3 h-8 rounded-full border px-3 text-[13px] font-medium hover:bg-accent">
+ Clear filters
+ </button>
+ </div>
+ )}
+ </>
+ );
+}
+
+const LIMITS = "MP4 or MOV · 4 s to 2 min · up to 200 MB";
+
+function SetupPanel({
+ engine,
+ models,
+ presetId,
+ presetName,
+ customRefs,
+ source,
+ range,
+ setRange,
+}: {
+ engine: Engine;
+ models: ModelChoice[];
+ presetId: string | null;
+ presetName?: string;
+ customRefs: number;
+ source: ReturnType<typeof useSourceClip>;
+ range: TrimRange | null;
+ setRange: (r: TrimRange | null) => void;
+}) {
+ const router = useRouter();
+ const { clip } = source;
+ const [ratio, setRatio] = useState<ShortsRatio>("9:16");
+ const [language, setLanguage] = useState("auto");
+ const [pickedModel, setModel] = useState<Record<Engine, string>>({ cloud: "", open: "" });
+ const modelId = pickedModel[engine] || models[0]?.id;
+ const model = models.find((m) => m.id === modelId);
+ const duration = clipDuration(clip);
+ const actions = useShortsActions();
+ const presetType = SHORTS_PRESETS.find((p) => p.id === presetId)?.type;
+
+ const shortsRange = range ? { start: range.startTime, end: range.endTime } : null;
+ const problem = shortsRange ? rangeProblem(shortsRange, duration) : null;
+ const estimateBody: ShortsBody | null =
+ presetId && shortsRange && !problem
+ ? { engine, presetId, source: { url: clip?.url ?? "/api/files/placeholder.mp4", name: clip?.name, duration }, range: shortsRange, aspectRatio: ratio, language, modelId }
+ : null;
+ const estimate = useShortsEstimate(estimateBody);
+ const est = estimate.data;
+
+ const blocker = !presetId
+ ? "Pick a preset first"
+ : !clip
+ ? "Upload a video"
+ : clip.error
+ ? clip.error
+ : !duration || !range
+ ? "Reading the clip…"
+ : problem
+ ? problem
+ : clip.uploading
+ ? clip.progress < 1
+ ? `Uploading… ${Math.round(clip.progress * 100)}%`
+ : "Reading the clip…"
+ : estimate.error
+ ? (estimate.error as Error).message
+ : null;
+
+ const generate = () => {
+ if (blocker) return void toast(blocker, { id: "shorts-blocker" });
+ actions.create.mutate(estimateBody!, {
+ onSuccess: (s) => router.push(`/shorts/${s.id}`),
+ onError: (e) => toast.error((e as Error).message),
+ });
+ };
+
+ return (
+ <div className="space-y-5 rounded-2xl border bg-background p-4 shadow-soft sm:p-5">
+ <h3 id="shorts-step-2" className="flex items-center gap-2 text-[15px] font-semibold">
+ <span className="grid size-6 place-items-center rounded-full bg-primary text-[12px] text-primary-foreground">2</span>
+ Upload your video
+ </h3>
+ <div className="flex items-center gap-2 rounded-lg bg-muted/60 px-3 py-2 text-[13px]">
+ <Sparkles className="size-4 shrink-0 text-brand-text" />
+ {presetName ? (
+ <span className="min-w-0 truncate">
+ Preset: <span className="font-medium">{presetName}</span>
+ </span>
+ ) : (
+ <span className="text-muted-foreground">Please select a preset</span>
+ )}
+ </div>
+
+ {!clip ? (
+ <ClipDrop
+ accept={SHORTS.accept}
+ limits={LIMITS}
+ onFile={(f) => {
+ const err = source.pick(f);
+ if (err) toast.error(err);
+ else setRange(null);
+ }}
+ onLibrary={(url, name) => {
+ source.adopt(url, name);
+ setRange(null);
+ }}
+ />
+ ) : (
+ <div className="space-y-3">
+ <ClipBar
+ clip={clip}
+ onRemove={() => {
+ source.clear();
+ setRange(null);
+ }}
+ />
+ <VideoTrimmer
+ src={clip.preview}
+ value={range}
+ onChange={setRange}
+ min={SHORTS.minSeconds}
+ max={SHORTS.maxSeconds}
+ duration={clip.info?.duration}
+ label="Part of the clip to restyle"
+ onMeta={(m) => source.setBrowserDuration(m.duration)}
+ />
+ </div>
+ )}
+
+ <Field label="Output">
+ <Segmented
+ label="Output ratio"
+ value={ratio}
+ onChange={setRatio}
+ options={SHORTS_RATIOS.map((r) => ({ value: r.value, label: r.label, hint: r.hint }))}
+ />
+ </Field>
+
+ <Field label="Language" hint={presetType ? "for the on-screen words" : "used by type presets"}>
+ <Select value={language} onValueChange={setLanguage}>
+ <SelectTrigger className="w-full" aria-label="Language">
+ <SelectValue>{language === "auto" ? "Auto-detect" : language}</SelectValue>
+ </SelectTrigger>
+ <SelectContent className="max-h-72">
+ <SelectItem value="auto">Auto-detect</SelectItem>
+ {SHORTS_LANGUAGES.map((l) => (
+ <SelectItem key={l} value={l}>
+ {l}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field label="Model" hint={engine === "open" ? <span className="inline-flex items-center gap-1"><Cpu className="size-3" /> Open source</span> : <span className="inline-flex items-center gap-1"><Cloud className="size-3" /> Cloud</span>}>
+ {models.length > 1 ? (
+ <Select value={modelId} onValueChange={(v) => setModel((m) => ({ ...m, [engine]: v }))}>
+ <SelectTrigger className="w-full" aria-label="Restyle model">
+ <SelectValue>
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate">{model?.name}</span>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{model?.price}</span>
+ </span>
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {models.map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate">{m.name}</span>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{m.price}</span>
+ {m.refs > 0 && <span className="shrink-0 rounded bg-brand-faint px-1 text-[10px] text-brand-text">refs</span>}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <div className="rounded-lg border px-3 py-2 text-[13px]">
+ <span className="font-medium">{model?.name ?? "—"}</span> <span className="text-muted-foreground">· {model?.price}</span>
+ </div>
+ )}
+ {model && <p className="text-[12px] leading-snug text-muted-foreground">{engine === "open" ? "Each ≤5 s segment: its first frame is restyled with Qwen-Image-Edit, then Wan 2.2 Fun VACE follows it and the clip's depth." : model.tagline}</p>}
+ {customRefs > 0 && engine === "cloud" && model && !model.refs && (
+ <p className="flex gap-1.5 text-[12px] leading-snug text-warning">
+ <Info className="mt-0.5 size-3.5 shrink-0" />
+ {model.name} restyles from words only — your reference images are used by {models.filter((m) => m.refs).map((m) => m.name).join(" and ")}.
+ </p>
+ )}
+ </Field>
+
+ <div className="space-y-3 border-t pt-4">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="text-[13px] text-muted-foreground">{est ? `${est.segments} segment${est.segments === 1 ? "" : "s"} · ${est.seconds} s` : "Estimate"}</span>
+ <span className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums" aria-live="polite">
+ {estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" />}
+ {estimateBody ? costText(est, engine) : "—"}
+ </span>
+ </div>
+ {est && !est.demo && engine === "cloud" && <p className="text-[12px] text-muted-foreground">You&apos;re only charged for the actual length.</p>}
+ {est?.notes.map((n) => (
+ <p key={n} className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground">
+ <Info className="mt-0.5 size-3.5 shrink-0" />
+ {n}
+ </p>
+ ))}
+ <button
+ type="button"
+ onClick={generate}
+ aria-disabled={!!blocker || actions.create.isPending}
+ aria-describedby={blocker ? "shorts-blocker" : undefined}
+ className={cn(
+ "flex h-11 w-full items-center justify-center gap-2 rounded-full text-[14px] font-medium transition-colors",
+ blocker ? "bg-muted text-subtle-foreground" : "bg-primary text-primary-foreground hover:bg-primary/90",
+ )}
+ >
+ {actions.create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}
+ Generate short
+ <ArrowRight className="size-4" />
+ </button>
+ {blocker && (
+ <p id="shorts-blocker" className="text-center text-[12px] text-muted-foreground">
+ {blocker}
+ </p>
+ )}
+ <p className="text-center text-[12px] text-muted-foreground">Next: export as one video, or download the parts separately.</p>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/shorts/ui.tsx b/src/components/shorts/ui.tsx
new file mode 100644
index 00000000..270cd0d7
--- /dev/null
+++ b/src/components/shorts/ui.tsx
@@ -0,0 +1,201 @@
+"use client";
+
+import { Check, CircleAlert, Film, Library, Loader2, Upload, X } from "lucide-react";
+import { useRef, useState } from "react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { LibraryGrid } from "@/components/studio/media-slot";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
+import { cn } from "@/lib/utils";
+import type { SourceClip } from "./use-source-clip";
+
+/** Small pieces shared by Shorts Studio and Mixed Media. */
+
+export function Segmented<T extends string | number>({
+ label,
+ value,
+ options,
+ onChange,
+ className,
+}: {
+ label: string;
+ value: T;
+ options: { value: T; label: string; hint?: string; disabled?: boolean; title?: string }[];
+ onChange: (v: T) => void;
+ className?: string;
+}) {
+ return (
+ <div role="radiogroup" aria-label={label} onKeyDown={radioKeys} className={cn("flex w-full rounded-full bg-muted p-0.5", className)}>
+ {options.map((o) => (
+ <button
+ key={String(o.value)}
+ type="button"
+ role="radio"
+ aria-checked={value === o.value}
+ tabIndex={radioTab(value === o.value)}
+ disabled={o.disabled}
+ title={o.title}
+ onClick={() => onChange(o.value)}
+ className={cn(
+ "flex h-8 min-w-0 flex-1 items-center justify-center gap-1 rounded-full px-2 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:text-muted-foreground",
+ value === o.value && "bg-background text-foreground shadow-soft",
+ )}
+ >
+ {o.label}
+ {o.hint && <span className="hidden text-[11px] font-normal text-muted-foreground sm:inline">{o.hint}</span>}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+/** A labelled block in a setup panel. */
+export function Field({ label, htmlFor, hint, children }: { label: string; htmlFor?: string; hint?: React.ReactNode; children: React.ReactNode }) {
+ return (
+ <div className="min-w-0 space-y-1.5">
+ <div className="flex items-baseline justify-between gap-2">
+ {htmlFor ? (
+ <label htmlFor={htmlFor} className="text-[13px] font-medium">
+ {label}
+ </label>
+ ) : (
+ <span className="text-[13px] font-medium">{label}</span>
+ )}
+ {hint && <span className="truncate text-[12px] text-muted-foreground">{hint}</span>}
+ </div>
+ {children}
+ </div>
+ );
+}
+
+/** "Upload a video to edit": click, drop, or pick from the Library. */
+export function ClipDrop({ accept, limits, onFile, onLibrary }: { accept: string; limits: string; onFile: (f: File) => void; onLibrary: (url: string, name?: string) => void }) {
+ const input = useRef<HTMLInputElement>(null);
+ const [over, setOver] = useState(false);
+ const [lib, setLib] = useState(false);
+ return (
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ const f = e.dataTransfer.files?.[0];
+ if (f) onFile(f);
+ }}
+ className={cn(
+ "flex flex-col items-center gap-3 rounded-xl border border-dashed border-border-strong px-4 py-7 text-center transition-colors",
+ over && "border-primary bg-brand-faint",
+ )}
+ >
+ <span className="grid size-11 place-items-center rounded-full bg-brand-faint text-brand-text">{over ? <Upload className="size-5" /> : <Film className="size-5" />}</span>
+ <div>
+ <p className="text-[14px] font-medium">Upload a video to edit</p>
+ <p className="mt-0.5 text-[12px] text-muted-foreground">{limits}</p>
+ </div>
+ <div className="flex flex-wrap justify-center gap-2">
+ <button type="button" onClick={() => input.current?.click()} className="inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3.5 text-[13px] font-medium text-primary-foreground hover:bg-primary/90">
+ <Upload className="size-3.5" /> Choose a video
+ </button>
+ <Popover open={lib} onOpenChange={setLib}>
+ <PopoverTrigger asChild>
+ <button type="button" className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3.5 text-[13px] font-medium hover:bg-accent">
+ <Library className="size-3.5" /> From library
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[min(92vw,340px)] p-2" collisionPadding={12}>
+ <p className="px-1 pb-2 text-[13px] font-medium">Videos in your library</p>
+ {lib && (
+ <LibraryGrid
+ kinds={["video"]}
+ onPick={(v) => {
+ setLib(false);
+ onLibrary(v.ref ?? v.preview, v.name);
+ }}
+ />
+ )}
+ </PopoverContent>
+ </Popover>
+ </div>
+ <p className="text-[11px] text-subtle-foreground">or drop it here</p>
+ <input
+ ref={input}
+ type="file"
+ accept={accept}
+ hidden
+ onChange={(e) => {
+ const f = e.target.files?.[0];
+ if (f) onFile(f);
+ e.target.value = "";
+ }}
+ />
+ </div>
+ );
+}
+
+const mb = (n: number) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`);
+
+/** The clip's name, upload progress and a remove button. */
+export function ClipBar({ clip, onRemove }: { clip: SourceClip; onRemove: () => void }) {
+ return (
+ <div className="flex min-w-0 items-center gap-2 rounded-lg bg-muted/60 px-2.5 py-2">
+ <span className={cn("grid size-7 shrink-0 place-items-center rounded-full", clip.error ? "bg-destructive/10 text-destructive" : "bg-background text-muted-foreground")}>
+ {clip.error ? <CircleAlert className="size-3.5" /> : clip.uploading ? <Loader2 className="size-3.5 animate-spin" /> : <Check className="size-3.5 text-success" />}
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[13px] font-medium">{clip.name}</p>
+ <p className="truncate text-[11px] text-muted-foreground" aria-live="polite">
+ {clip.error
+ ? clip.error
+ : clip.uploading
+ ? clip.progress < 1
+ ? `Uploading… ${Math.round(clip.progress * 100)}%`
+ : "Reading the clip…"
+ : [clip.size ? mb(clip.size) : null, clip.info?.fps ? `${Math.round(clip.info.fps)} fps` : null, clip.info?.hasAudio === false ? "no sound" : null].filter(Boolean).join(" · ") || "Uploaded"}
+ </p>
+ {clip.uploading && clip.progress < 1 && (
+ <div className="mt-1 h-1 overflow-hidden rounded-full bg-background">
+ <div className="h-full bg-primary transition-[width]" style={{ width: `${Math.round(clip.progress * 100)}%` }} />
+ </div>
+ )}
+ </div>
+ <button type="button" onClick={onRemove} aria-label="Remove the clip" className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <X className="size-3.5" />
+ </button>
+ </div>
+ );
+}
+
+/** "1 Choose preset · 2 Upload video · 3 Download", with the steps done so far ticked. */
+export function Steps({ steps, current, className }: { steps: string[]; current: number; className?: string }) {
+ return (
+ <ol className={cn("flex flex-wrap items-center justify-center gap-x-2 gap-y-1 text-[12px]", className)} aria-label="Steps">
+ {steps.map((s, i) => (
+ <li key={s} className="flex items-center gap-2" aria-current={i === current ? "step" : undefined}>
+ {i > 0 && <span className="h-px w-4 bg-border-strong sm:w-6" aria-hidden />}
+ <span
+ className={cn(
+ "grid size-5 place-items-center rounded-full text-[11px] font-semibold",
+ i < current ? "bg-success text-white" : i === current ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground",
+ )}
+ >
+ {i < current ? <Check className="size-3" /> : i + 1}
+ </span>
+ <span className={cn("font-medium whitespace-nowrap", i === current ? "text-foreground" : "text-muted-foreground")}>{s}</span>
+ </li>
+ ))}
+ </ol>
+ );
+}
+
+/** "≈ $0.42", "Demo · free", "Free · your GPU". */
+export function costText(e: { costUsd: number | null; demo: boolean } | undefined, engine: "cloud" | "open"): string {
+ if (!e) return "…";
+ if (e.demo) return "Demo · free";
+ if (engine === "open") return "Free · your GPU";
+ if (e.costUsd === null) return "Price unknown";
+ if (e.costUsd === 0) return "Free";
+ return `≈ $${e.costUsd < 1 ? e.costUsd.toFixed(3).replace(/0$/, "") : e.costUsd.toFixed(2)}`;
+}
diff --git a/src/components/shorts/use-source-clip.ts b/src/components/shorts/use-source-clip.ts
new file mode 100644
index 00000000..92abb55f
--- /dev/null
+++ b/src/components/shorts/use-source-clip.ts
@@ -0,0 +1,129 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+/**
+ * The clip a studio works on: shown at once from the file (object URL), uploaded in the background
+ * with progress, then read by the server (length, frame rate, sound) from its header. Shared by
+ * Shorts Studio and Mixed Media.
+ */
+
+export interface SourceInfo {
+ duration?: number;
+ width?: number;
+ height?: number;
+ fps?: number;
+ hasAudio?: boolean;
+}
+
+export interface SourceClip {
+ name: string;
+ size: number;
+ /** What the trimmer plays: the local file until the upload is done, then the uploaded copy. */
+ preview: string;
+ /** The uploaded file (/api/files/…), once uploaded. */
+ url?: string;
+ /** 0–1 while uploading. */
+ progress: number;
+ uploading: boolean;
+ error?: string;
+ info?: SourceInfo;
+ /** Length as the browser read it (formats the server can't read). */
+ browserDuration?: number;
+}
+
+const VIDEO_TYPE = /^video\/(mp4|quicktime|webm|x-m4v)$/;
+const VIDEO_EXT = /\.(mp4|mov|m4v|webm)$/i;
+
+export function checkClipFile(file: File, maxBytes: number): string | null {
+ if (!VIDEO_TYPE.test(file.type) && !VIDEO_EXT.test(file.name)) return "That isn't a video — use an MP4 or MOV";
+ if (file.size > maxBytes) return `That file's over ${Math.round(maxBytes / 1024 / 1024)} MB. Try a shorter or smaller clip.`;
+ return null;
+}
+
+function upload(file: File, onProgress: (p: number) => void, signal: AbortSignal): Promise<{ url: string; name?: string }> {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", "/api/uploads");
+ xhr.responseType = "json";
+ xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(e.loaded / e.total);
+ xhr.onload = () => {
+ const body = xhr.response as { url?: string; name?: string; error?: string } | null;
+ if (xhr.status >= 200 && xhr.status < 300 && body?.url) resolve({ url: body.url, name: body.name });
+ else reject(new Error(body?.error ?? `Upload failed (${xhr.status})`));
+ };
+ xhr.onerror = () => reject(new Error("Upload failed — check your connection"));
+ xhr.onabort = () => reject(new DOMException("Aborted", "AbortError"));
+ signal.addEventListener("abort", () => xhr.abort());
+ const form = new FormData();
+ form.append("file", file);
+ xhr.send(form);
+ });
+}
+
+async function probe(url: string): Promise<SourceInfo> {
+ const res = await fetch("/api/shorts/probe", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url }) });
+ return res.ok ? ((await res.json()) as SourceInfo) : {};
+}
+
+export function useSourceClip(maxBytes: number) {
+ const [clip, setClip] = useState<SourceClip | null>(null);
+ const abort = useRef<AbortController | null>(null);
+ const objectUrl = useRef<string | null>(null);
+
+ const release = () => {
+ abort.current?.abort();
+ abort.current = null;
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
+ objectUrl.current = null;
+ };
+ useEffect(() => release, []);
+
+ const pick = useCallback(
+ (file: File): string | null => {
+ const problem = checkClipFile(file, maxBytes);
+ if (problem) return problem;
+ release();
+ const local = URL.createObjectURL(file);
+ objectUrl.current = local;
+ const ctrl = new AbortController();
+ abort.current = ctrl;
+ setClip({ name: file.name, size: file.size, preview: local, progress: 0, uploading: true });
+ void (async () => {
+ try {
+ const up = await upload(file, (p) => setClip((c) => (c && c.preview === local ? { ...c, progress: p } : c)), ctrl.signal);
+ const info = await probe(up.url).catch(() => ({}) as SourceInfo);
+ if (ctrl.signal.aborted) return;
+ // Keep playing the local copy (no reload mid-trim); the uploaded one is what jobs use.
+ setClip((c) => (c && c.preview === local ? { ...c, url: up.url, uploading: false, progress: 1, info } : c));
+ } catch (e) {
+ if ((e as Error).name === "AbortError") return;
+ setClip((c) => (c && c.preview === local ? { ...c, uploading: false, error: (e as Error).message } : c));
+ }
+ })();
+ return null;
+ },
+ [maxBytes],
+ );
+
+ /** Use a clip that is already uploaded (a hand-off from the Library or a result). */
+ const adopt = useCallback((url: string, name = "clip") => {
+ release();
+ setClip({ name, size: 0, preview: url, url, progress: 1, uploading: true });
+ void probe(url)
+ .catch(() => ({}) as SourceInfo)
+ .then((info) => setClip((c) => (c && c.url === url ? { ...c, uploading: false, info } : c)));
+ }, []);
+
+ const clear = useCallback(() => {
+ release();
+ setClip(null);
+ }, []);
+
+ const setBrowserDuration = useCallback((d: number) => setClip((c) => (c && d > 0 ? { ...c, browserDuration: d } : c)), []);
+
+ return { clip, pick, adopt, clear, setBrowserDuration };
+}
+
+/** The clip's length: its header's, else what the browser read. */
+export const clipDuration = (c: SourceClip | null) => c?.info?.duration ?? c?.browserDuration;
diff --git a/src/components/studio/video-trimmer.tsx b/src/components/studio/video-trimmer.tsx
new file mode 100644
index 00000000..5580eba6
--- /dev/null
+++ b/src/components/studio/video-trimmer.tsx
@@ -0,0 +1,498 @@
+"use client";
+
+import { Pause, Play, Volume2, VolumeX } from "lucide-react";
+import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
+import { clampRange, clock, initialRange, moveRange, setEdge, thumbTimes, trimHint, type TrimLimits, type TrimRange } from "@/lib/trim-range";
+import { cn } from "@/lib/utils";
+
+export type { TrimRange } from "@/lib/trim-range";
+
+/**
+ * Pick a part of a clip: a filmstrip of frames grabbed in the browser, a draggable window with two
+ * handles (min/max length enforced), "play the selection", and typed start/end times. Keyboard: the
+ * handles and the window are sliders (arrows 0.1 s, Shift ×10, Page Up/Down 5 s, Home/End).
+ * Used by Shorts Studio and Mixed Media; reusable anywhere a clip needs trimming (Ad Multiplier,
+ * Motion control).
+ */
+
+export interface VideoTrimmerHandle {
+ /** A still of the clip at `time` (default: the selection's start) as a JPEG, or null if this browser can't decode it. */
+ grabFrame(time?: number, maxSide?: number): Promise<Blob | null>;
+}
+
+export interface VideoTrimmerProps {
+ src: string;
+ /** The selection (null until the clip's length is known: the trimmer then proposes one). */
+ value: TrimRange | null;
+ onChange: (v: TrimRange) => void;
+ /** Shortest and longest selection, in seconds. */
+ min?: number;
+ max?: number;
+ /** The clip's length when known from elsewhere (some formats don't report one in the browser). */
+ duration?: number;
+ /** Accessible name of the control. */
+ label?: string;
+ /** Overrides the "Select a 10-second segment" line. */
+ hint?: string;
+ onMeta?: (m: { duration: number; width: number; height: number }) => void;
+ /** Hide the clip preview above the filmstrip. */
+ noPreview?: boolean;
+ className?: string;
+}
+
+/** Seek a (hidden) video and wait for the frame. */
+function seek(v: HTMLVideoElement, t: number, ms = 4000): Promise<boolean> {
+ return new Promise((resolve) => {
+ const done = (ok: boolean) => {
+ clearTimeout(timer);
+ v.removeEventListener("seeked", onSeeked);
+ v.removeEventListener("error", onError);
+ resolve(ok);
+ };
+ const onSeeked = () => done(true);
+ const onError = () => done(false);
+ const timer = setTimeout(() => done(false), ms);
+ v.addEventListener("seeked", onSeeked);
+ v.addEventListener("error", onError);
+ v.currentTime = Math.max(0, t);
+ });
+}
+
+function loaded(v: HTMLVideoElement, ms = 8000): Promise<boolean> {
+ return new Promise((resolve) => {
+ if (v.readyState >= 2) return resolve(true);
+ const done = (ok: boolean) => {
+ clearTimeout(timer);
+ v.removeEventListener("loadeddata", onData);
+ v.removeEventListener("error", onError);
+ resolve(ok);
+ };
+ const onData = () => done(true);
+ const onError = () => done(false);
+ const timer = setTimeout(() => done(false), ms);
+ v.addEventListener("loadeddata", onData);
+ v.addEventListener("error", onError);
+ });
+}
+
+function draw(v: HTMLVideoElement, height: number, maxSide?: number): HTMLCanvasElement | null {
+ if (!v.videoWidth || !v.videoHeight) return null;
+ const c = document.createElement("canvas");
+ let w = Math.round((v.videoWidth / v.videoHeight) * height);
+ let h = height;
+ if (maxSide && Math.max(w, h) > maxSide) {
+ const k = maxSide / Math.max(w, h);
+ w = Math.round(w * k);
+ h = Math.round(h * k);
+ }
+ c.width = w;
+ c.height = h;
+ const ctx = c.getContext("2d");
+ if (!ctx) return null;
+ ctx.drawImage(v, 0, 0, w, h);
+ return c;
+}
+
+function makeVideo(src: string): HTMLVideoElement {
+ const v = document.createElement("video");
+ v.muted = true;
+ v.playsInline = true;
+ v.preload = "auto";
+ v.crossOrigin = "anonymous";
+ v.src = src;
+ return v;
+}
+
+const STEP = 0.1;
+
+export const VideoTrimmer = forwardRef<VideoTrimmerHandle, VideoTrimmerProps>(function VideoTrimmer(
+ { src, value, onChange, min, max, duration: knownDuration, label = "Part of the clip", hint, onMeta, noPreview, className },
+ ref,
+) {
+ const video = useRef<HTMLVideoElement>(null);
+ const track = useRef<HTMLDivElement>(null);
+ const [duration, setDuration] = useState<number | null>(null);
+ const [shape, setShape] = useState(16 / 9);
+ const [thumbs, setThumbs] = useState<string[]>([]);
+ const [unsupported, setUnsupported] = useState(false);
+ const [playing, setPlaying] = useState(false);
+ const [muted, setMuted] = useState(false);
+ const [now, setNow] = useState(0);
+ const d = duration ?? knownDuration ?? 0;
+ const limits: TrimLimits = { duration: d, min, max };
+ const range = value ?? (d ? initialRange(d, max) : null);
+
+ // Read the latest props from long-lived handlers (drag, playback loop).
+ const latest = useRef({ range, limits, onChange });
+ useEffect(() => {
+ latest.current = { range, limits, onChange };
+ });
+
+ // Propose a selection as soon as the length is known; keep an old one valid for a new clip.
+ useEffect(() => {
+ if (!d) return;
+ const { range: r, limits: l, onChange: set } = latest.current;
+ if (!value) set(initialRange(d, max));
+ else {
+ const ok = clampRange(r!, l, "end");
+ if (ok.startTime !== r!.startTime || ok.endTime !== r!.endTime) set(ok);
+ }
+ // Only when the clip (or its length) changes.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [d, src]);
+
+ // Filmstrip: frames grabbed from a hidden copy of the clip, one by one, as soon as they decode.
+ const [stripFor, setStripFor] = useState(src);
+ if (stripFor !== src) {
+ setStripFor(src);
+ setThumbs([]);
+ setUnsupported(false);
+ }
+ useEffect(() => {
+ let cancelled = false;
+ const v = makeVideo(src);
+ (async () => {
+ const ok = await loaded(v);
+ if (cancelled) return;
+ const len = Number.isFinite(v.duration) && v.duration > 0 ? v.duration : (knownDuration ?? 0);
+ if (!ok || !v.videoWidth || !len) {
+ setUnsupported(true);
+ return;
+ }
+ // Without the preview, this copy is where the length and shape come from.
+ if (noPreview) {
+ setDuration((cur) => cur ?? len);
+ onMeta?.({ duration: len, width: v.videoWidth, height: v.videoHeight });
+ }
+ const width = track.current?.clientWidth ?? 640;
+ const tile = 56 * (v.videoWidth / v.videoHeight);
+ const n = Math.max(4, Math.min(14, Math.round(width / Math.max(28, tile))));
+ for (const t of thumbTimes(len, n)) {
+ if (cancelled) return;
+ if (!(await seek(v, Math.min(t, len - 0.05)))) break;
+ const c = draw(v, 112);
+ if (!c || cancelled) break;
+ const url = c.toDataURL("image/jpeg", 0.7);
+ setThumbs((xs) => [...xs, url]);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ v.removeAttribute("src");
+ v.load();
+ };
+ // knownDuration only matters for formats without a length; don't re-grab when it arrives.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [src]);
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ async grabFrame(time, maxSide = 1536) {
+ const v = makeVideo(src);
+ try {
+ if (!(await loaded(v))) return null;
+ if (!(await seek(v, time ?? latest.current.range?.startTime ?? 0))) return null;
+ const c = draw(v, v.videoHeight, maxSide);
+ if (!c) return null;
+ return await new Promise<Blob | null>((resolve) => c.toBlob((b) => resolve(b), "image/jpeg", 0.92));
+ } catch {
+ return null;
+ } finally {
+ v.removeAttribute("src");
+ v.load();
+ }
+ },
+ }),
+ [src],
+ );
+
+ // Play the selection, then stop at its end (back to its start).
+ useEffect(() => {
+ if (!playing) return;
+ let raf = 0;
+ const tick = () => {
+ const v = video.current;
+ const r = latest.current.range;
+ if (v && r) {
+ setNow(v.currentTime);
+ if (v.currentTime >= r.endTime - 0.02 || v.ended) {
+ v.pause();
+ v.currentTime = r.startTime;
+ setPlaying(false);
+ return;
+ }
+ }
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [playing]);
+
+ const togglePlay = () => {
+ const v = video.current;
+ if (!v || !range) return;
+ if (playing) {
+ v.pause();
+ setPlaying(false);
+ return;
+ }
+ if (v.currentTime < range.startTime || v.currentTime >= range.endTime - 0.05) v.currentTime = range.startTime;
+ void v
+ .play()
+ .then(() => setPlaying(true))
+ .catch(() => setPlaying(false));
+ };
+
+ /** Show the frame at an edge while it's being moved. */
+ const scrub = useCallback((t: number) => {
+ const v = video.current;
+ if (!v || !v.paused) return;
+ v.currentTime = t;
+ setNow(t);
+ }, []);
+
+ const commit = useCallback(
+ (next: TrimRange, show?: number) => {
+ latest.current.onChange(next);
+ if (show !== undefined) scrub(show);
+ },
+ [scrub],
+ );
+
+ // Dragging: an edge, the whole window, or a press on the strip (the window jumps there).
+ const drag = useRef<{ kind: "start" | "end" | "move"; x0: number; r0: TrimRange } | null>(null);
+ const timeAt = (clientX: number) => {
+ const el = track.current;
+ if (!el || !d) return 0;
+ const box = el.getBoundingClientRect();
+ return Math.min(d, Math.max(0, ((clientX - box.left) / box.width) * d));
+ };
+ const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
+ if (!range || !d || e.button > 0) return;
+ const target = (e.target as HTMLElement).closest<HTMLElement>("[data-trim]");
+ const kind = (target?.dataset.trim as "start" | "end" | "move" | undefined) ?? null;
+ e.currentTarget.setPointerCapture(e.pointerId);
+ if (kind) {
+ drag.current = { kind, x0: e.clientX, r0: range };
+ target?.focus({ preventScroll: true });
+ return;
+ }
+ // A press outside the window moves it there (keeping its length), then drags it.
+ const len = range.endTime - range.startTime;
+ const next = moveRange(range, timeAt(e.clientX) - len / 2 - range.startTime, limits);
+ commit(next, next.startTime);
+ drag.current = { kind: "move", x0: e.clientX, r0: next };
+ };
+ const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
+ const g = drag.current;
+ const el = track.current;
+ if (!g || !el || !d) return;
+ const dt = ((e.clientX - g.x0) / el.getBoundingClientRect().width) * d;
+ const l = latest.current.limits;
+ if (g.kind === "move") {
+ const next = moveRange(g.r0, dt, l);
+ commit(next, next.startTime);
+ } else {
+ const next = setEdge(g.r0, g.kind, (g.kind === "start" ? g.r0.startTime : g.r0.endTime) + dt, l);
+ commit(next, g.kind === "start" ? next.startTime : next.endTime);
+ }
+ };
+ const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
+ drag.current = null;
+ if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
+ };
+
+ const onKey = (e: React.KeyboardEvent<HTMLElement>) => {
+ const kind = e.currentTarget.dataset.trim as "start" | "end" | "move" | undefined;
+ if (!range || !d || !kind) return;
+ const big = e.shiftKey ? 10 : 1;
+ let delta: number | null = null;
+ let to: number | null = null;
+ if (e.key === "ArrowLeft" || e.key === "ArrowDown") delta = -STEP * big;
+ else if (e.key === "ArrowRight" || e.key === "ArrowUp") delta = STEP * big;
+ else if (e.key === "PageDown") delta = -5;
+ else if (e.key === "PageUp") delta = 5;
+ else if (e.key === "Home") to = 0;
+ else if (e.key === "End") to = d;
+ else if (e.key === " " || e.key === "Enter") {
+ e.preventDefault();
+ togglePlay();
+ return;
+ } else return;
+ e.preventDefault();
+ if (kind === "move") {
+ const next = moveRange(range, to !== null ? (to === 0 ? -range.startTime : d - range.endTime) : delta!, limits);
+ commit(next, next.startTime);
+ } else {
+ const cur = kind === "start" ? range.startTime : range.endTime;
+ const next = setEdge(range, kind, to ?? cur + delta!, limits);
+ commit(next, kind === "start" ? next.startTime : next.endTime);
+ }
+ };
+
+ const pct = (t: number) => (d ? `${(t / d) * 100}%` : "0%");
+ const len = range ? range.endTime - range.startTime : 0;
+ const line = hint ?? (d ? trimHint(limits) : null);
+
+ return (
+ <div className={cn("min-w-0 space-y-3", className)}>
+ {!noPreview && (
+ <div className="relative mx-auto w-full overflow-hidden rounded-xl bg-black" style={{ aspectRatio: shape, maxHeight: 360, maxWidth: shape < 1 ? 360 * shape : undefined }}>
+ <video
+ ref={video}
+ src={src}
+ playsInline
+ muted={muted}
+ preload="metadata"
+ className="size-full object-contain"
+ onLoadedMetadata={(e) => {
+ const v = e.currentTarget;
+ const len = Number.isFinite(v.duration) && v.duration > 0 ? v.duration : (knownDuration ?? 0);
+ if (v.videoWidth && v.videoHeight) setShape(v.videoWidth / v.videoHeight);
+ if (len) setDuration(len);
+ onMeta?.({ duration: len, width: v.videoWidth, height: v.videoHeight });
+ }}
+ onPause={() => setPlaying(false)}
+ onClick={togglePlay}
+ />
+ <div className="absolute inset-x-0 bottom-0 flex items-center gap-2 bg-gradient-to-t from-black/60 to-transparent p-2 text-white">
+ <button
+ type="button"
+ onClick={togglePlay}
+ disabled={!range}
+ aria-label={playing ? "Pause" : "Play the selection"}
+ title={playing ? "Pause" : "Play the selection"}
+ className="grid size-8 shrink-0 place-items-center rounded-full bg-white/20 backdrop-blur transition-colors hover:bg-white/30 disabled:opacity-50"
+ >
+ {playing ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}
+ </button>
+ <span className="min-w-0 truncate font-mono text-[11px] tabular-nums opacity-90">
+ {clock(now)}
+ <span className="opacity-70"> / {clock(d)}</span>
+ </span>
+ <button
+ type="button"
+ onClick={() => setMuted((m) => !m)}
+ aria-label={muted ? "Unmute" : "Mute"}
+ className="ml-auto grid size-8 place-items-center rounded-full bg-white/15 backdrop-blur hover:bg-white/25"
+ >
+ {muted ? <VolumeX className="size-3.5" /> : <Volume2 className="size-3.5" />}
+ </button>
+ </div>
+ </div>
+ )}
+
+ <div role="group" aria-label={label} className="space-y-2">
+ <div
+ ref={track}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerUp}
+ className={cn("relative h-14 touch-none overflow-hidden rounded-lg bg-muted select-none", !range && "animate-pulse")}
+ >
+ <div className="absolute inset-0 flex" aria-hidden>
+ {unsupported ? (
+ <div className="size-full bg-[repeating-linear-gradient(135deg,var(--muted)_0_10px,var(--accent)_10px_20px)]" />
+ ) : (
+ thumbs.map((t, i) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={i} src={t} alt="" draggable={false} className="h-full min-w-0 flex-1 object-cover" />
+ ))
+ )}
+ </div>
+ {range && d > 0 && (
+ <>
+ <div className="pointer-events-none absolute inset-y-0 left-0 bg-black/55" style={{ width: pct(range.startTime) }} />
+ <div className="pointer-events-none absolute inset-y-0 right-0 bg-black/55" style={{ width: `calc(100% - ${pct(range.endTime)})` }} />
+ <div
+ data-trim="move"
+ role="slider"
+ tabIndex={0}
+ aria-label="Selection position"
+ aria-valuemin={0}
+ aria-valuemax={Math.max(0, Math.round((d - len) * 10) / 10)}
+ aria-valuenow={range.startTime}
+ aria-valuetext={`${clock(range.startTime)} to ${clock(range.endTime)}`}
+ onKeyDown={onKey}
+ className="absolute inset-y-0 cursor-grab rounded-md border-2 border-primary outline-none focus-visible:ring-4 focus-visible:ring-brand-faint active:cursor-grabbing"
+ style={{ left: pct(range.startTime), width: pct(len) }}
+ />
+ {(["start", "end"] as const).map((edge) => (
+ <div
+ key={edge}
+ data-trim={edge}
+ role="slider"
+ tabIndex={0}
+ aria-label={edge === "start" ? "Start of selection" : "End of selection"}
+ aria-valuemin={0}
+ aria-valuemax={Math.round(d * 10) / 10}
+ aria-valuenow={edge === "start" ? range.startTime : range.endTime}
+ aria-valuetext={clock(edge === "start" ? range.startTime : range.endTime)}
+ onKeyDown={onKey}
+ className="group/handle absolute inset-y-0 z-10 flex w-6 cursor-ew-resize items-center justify-center outline-none"
+ style={{ left: `calc(${pct(edge === "start" ? range.startTime : range.endTime)} - ${edge === "start" ? "4px" : "20px"})` }}
+ >
+ <span className="h-full w-2.5 rounded-sm bg-primary shadow-soft transition-transform group-focus-visible/handle:scale-x-125 group-focus-visible/handle:ring-4 group-focus-visible/handle:ring-brand-faint">
+ <span className="mx-auto mt-[22px] block h-3 w-0.5 rounded-full bg-primary-foreground/80" />
+ </span>
+ </div>
+ ))}
+ {!noPreview && <div className="pointer-events-none absolute inset-y-0 w-0.5 bg-white/90 shadow" style={{ left: pct(now) }} aria-hidden />}
+ </>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-[12px] text-muted-foreground">
+ <TimeField label="Start" value={range?.startTime} disabled={!range} onCommit={(t) => range && commit(setEdge(range, "start", t, limits), t)} />
+ <span className="font-mono tabular-nums text-foreground" aria-live="polite">
+ {range ? `${len.toFixed(1)} s selected` : "Reading the clip…"}
+ </span>
+ <TimeField label="End" value={range?.endTime} disabled={!range} onCommit={(t) => range && commit(setEdge(range, "end", t, limits), t)} />
+ {line && <span className="w-full text-[12px] text-brand-text sm:ml-auto sm:w-auto">{line}</span>}
+ {unsupported && <span className="w-full text-[12px]">This browser can&apos;t show frames of this clip — pick the part by time.</span>}
+ </div>
+ </div>
+ </div>
+ );
+});
+
+/** A seconds field that commits on Enter or blur (typing "12.5" or "0:12.5"). */
+function TimeField({ label, value, disabled, onCommit }: { label: string; value?: number; disabled?: boolean; onCommit: (t: number) => void }) {
+ const [draft, setDraft] = useState<string | null>(null);
+ const shown = draft ?? (value !== undefined ? value.toFixed(1) : "");
+ const parse = (s: string) => {
+ const m = /^\s*(?:(\d+):)?(\d+(?:\.\d+)?)\s*s?\s*$/.exec(s);
+ return m ? Number(m[1] ?? 0) * 60 + Number(m[2]) : NaN;
+ };
+ const done = () => {
+ if (draft !== null) {
+ const t = parse(draft);
+ if (Number.isFinite(t)) onCommit(t);
+ }
+ setDraft(null);
+ };
+ return (
+ <label className="inline-flex items-center gap-1.5">
+ <span>{label}</span>
+ <input
+ type="text"
+ inputMode="decimal"
+ disabled={disabled}
+ value={shown}
+ aria-label={`${label} (seconds)`}
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={done}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ done();
+ } else if (e.key === "Escape") setDraft(null);
+ }}
+ className="h-7 w-16 rounded-md border bg-background px-2 font-mono text-[12px] text-foreground tabular-nums outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint disabled:opacity-50"
+ />
+ <span aria-hidden>s</span>
+ </label>
+ );
+}