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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Faceless Studio and Explainer UI
Claude23406cd289c9
diff --git a/src/app/(studio)/explainer/[id]/page.tsx b/src/app/(studio)/explainer/[id]/page.tsxnew file mode 100644index 00000000..f579f91a--- /dev/null+++ b/src/app/(studio)/explainer/[id]/page.tsx@@ -0,0 +1,18 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { EpisodeView } from "@/components/faceless/episode-view";++export const metadata: Metadata = { title: "Explainer" };++async function Explainer({ params }: { params: PageProps<"/explainer/[id]">["params"] }) {+ const { id } = await params;+ return <EpisodeView id={id} backHref="/explainer" backLabel="Explainer" />;+}++export default function Page({ params }: PageProps<"/explainer/[id]">) {+ return (+ <Suspense fallback={null}>+ <Explainer params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/explainer/page.tsx b/src/app/(studio)/explainer/page.tsxnew file mode 100644index 00000000..928c26f1--- /dev/null+++ b/src/app/(studio)/explainer/page.tsx@@ -0,0 +1,10 @@+import type { Metadata } from "next";+import { ExplainerStudio } from "@/components/explainer/explainer-studio";+import { getModel } from "@/lib/catalog";+import { pickerData } from "@/lib/catalog/faceless";++export const metadata: Metadata = { title: "Explainer" };++export default function Page() {+ return <ExplainerStudio picker={pickerData(getModel)} />;+}diff --git a/src/app/(studio)/faceless/[id]/[episode]/page.tsx b/src/app/(studio)/faceless/[id]/[episode]/page.tsxnew file mode 100644index 00000000..f6277745--- /dev/null+++ b/src/app/(studio)/faceless/[id]/[episode]/page.tsx@@ -0,0 +1,18 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { EpisodeView } from "@/components/faceless/episode-view";++export const metadata: Metadata = { title: "Episode" };++async function Episode({ params }: { params: PageProps<"/faceless/[id]/[episode]">["params"] }) {+ const { id, episode } = await params;+ return <EpisodeView id={episode} backHref={`/faceless/${id}`} backLabel="Channel" />;+}++export default function Page({ params }: PageProps<"/faceless/[id]/[episode]">) {+ return (+ <Suspense fallback={null}>+ <Episode params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/faceless/[id]/new/page.tsx b/src/app/(studio)/faceless/[id]/new/page.tsxnew file mode 100644index 00000000..b7e0ac34--- /dev/null+++ b/src/app/(studio)/faceless/[id]/new/page.tsx@@ -0,0 +1,20 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { EpisodeWizard } from "@/components/faceless/episode-wizard";+import { getModel } from "@/lib/catalog";+import { pickerData } from "@/lib/catalog/faceless";++export const metadata: Metadata = { title: "New episode" };++async function Wizard({ params }: { params: PageProps<"/faceless/[id]/new">["params"] }) {+ const { id } = await params;+ return <EpisodeWizard channelId={id} picker={pickerData(getModel)} />;+}++export default function Page({ params }: PageProps<"/faceless/[id]/new">) {+ return (+ <Suspense fallback={null}>+ <Wizard params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/faceless/[id]/page.tsx b/src/app/(studio)/faceless/[id]/page.tsxnew file mode 100644index 00000000..fb6f8293--- /dev/null+++ b/src/app/(studio)/faceless/[id]/page.tsx@@ -0,0 +1,20 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { ChannelView } from "@/components/faceless/channel-view";+import { getModel } from "@/lib/catalog";+import { pickerData } from "@/lib/catalog/faceless";++export const metadata: Metadata = { title: "Faceless channel" };++async function Channel({ params }: { params: PageProps<"/faceless/[id]">["params"] }) {+ const { id } = await params;+ return <ChannelView id={id} picker={pickerData(getModel)} />;+}++export default function Page({ params }: PageProps<"/faceless/[id]">) {+ return (+ <Suspense fallback={null}>+ <Channel params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/faceless/page.tsx b/src/app/(studio)/faceless/page.tsxnew file mode 100644index 00000000..df7c90d6--- /dev/null+++ b/src/app/(studio)/faceless/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { FacelessHome } from "@/components/faceless/faceless-home";++export const metadata: Metadata = { title: "Faceless Studio" };++export default function Page() {+ return <FacelessHome />;+}diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 8ea7fba1..c2038d4c 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -38,6 +38,8 @@ import {Library,PersonStanding,Scissors,+ Tv,+ Presentation,type LucideIcon,} from "lucide-react";import {@@ -110,6 +112,8 @@ const NAV: NavGroupDef[] = [label: "Studios",items: [{ href: "/cinema", label: "Cinema Studio", icon: Clapperboard },+ { href: "/faceless", label: "Faceless Studio", icon: Tv },+ { href: "/explainer", label: "Explainer", icon: Presentation },{ 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/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsxnew file mode 100644index 00000000..a746d64b--- /dev/null+++ b/src/components/explainer/explainer-studio.tsx@@ -0,0 +1,435 @@+"use client";++import { Download, FileText, Image as ImageIcon, Link2, Loader2, Paperclip, Search, Settings2, Sparkles, X } from "lucide-react";+import { useRouter } from "next/navigation";+import { useId, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import { Switch } from "@/components/ui/switch";+import { EngineSwitch } from "@/components/studio/engine-switch";+import { fileToSlot } from "@/components/studio/media-slot";+import { useEngine } from "@/lib/api";+import {+ ANIMATION_MODES,+ AUTO_SECONDS,+ defaultSettings,+ defaultVoice,+ EXPLAINER_DURATIONS,+ EXPLAINER_MAX,+ EXPLAINER_MIN,+ EXPLAINER_STYLE_IDS,+ genreInfo,+ getStyle,+ MAX_SOURCES,+ MAX_TOPIC,+ type EpisodeSettings,+ type ExplainerSource,+ type PickerData,+} from "@/lib/catalog/faceless";+import { cn } from "@/lib/utils";+import { EpisodeTile } from "../faceless/cards";+import { EstimateLine, Segmented, ToggleRow } from "../faceless/controls";+import { readLink, useCreateExplainer, useEstimate, useExplainers, useLikeEpisode } from "../faceless/hooks";+import { NarratorChip } from "../faceless/narrator";+import { StyleArt, StyleGrid } from "../faceless/style-art";++const DOC_TYPES = /\.(txt|md|markdown|csv|srt|vtt|json)$/i;+const MAX_DOC = 20_000;++type Draft = { kind: "image"; id: string; url: string; name: string; preview: string; uploading?: boolean } | Exclude<ExplainerSource, { kind: "image" }>;++const STEPS = [+ { icon: Sparkles, title: "Choose Preset", text: "One of 22 looks: whiteboard, pixel art, paper diorama…" },+ { icon: Paperclip, title: "Attach a file or just prompt", text: "Images, a document or a link — or only a topic." },+ { icon: Download, title: "Download your result", text: "A narrated, subtitled video; fix any scene in the timeline." },+];++function SourceChip({ s, onRemove }: { s: Draft; onRemove: () => void }) {+ const label = s.kind === "image" ? s.name : s.kind === "text" ? s.name : (s.title ?? s.url);+ return (+ <span className="inline-flex h-9 max-w-full min-w-0 items-center gap-1.5 rounded-full bg-secondary pr-1 pl-1 text-[12px] font-medium">+ {s.kind === "image" ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={s.preview} alt="" className="size-7 rounded-full object-cover" />+ ) : (+ <span className="grid size-7 place-items-center rounded-full bg-background text-muted-foreground">{s.kind === "text" ? <FileText className="size-3.5" /> : <Link2 className="size-3.5" />}</span>+ )}+ <span className="min-w-0 truncate">{label}</span>+ {s.kind === "image" && s.uploading && <Loader2 className="size-3.5 shrink-0 animate-spin" />}+ <button type="button" onClick={onRemove} className="grid size-6 shrink-0 place-items-center rounded-full hover:bg-accent" aria-label={`Remove ${label}`}>+ <X className="size-3.5" />+ </button>+ </span>+ );+}++/** Paste a link: the page is fetched and summarised for the writer. */+function LinkPopover({ engine, disabled, onAdd }: { engine: EpisodeSettings["engine"]; disabled: boolean; onAdd: (s: Extract<ExplainerSource, { kind: "link" }>) => void }) {+ const [open, setOpen] = useState(false);+ const [url, setUrl] = useState("");+ const [busy, setBusy] = useState(false);+ const id = useId();+ const add = async () => {+ if (!url.trim()) return;+ setBusy(true);+ try {+ onAdd(await readLink(url.trim(), engine));+ setUrl("");+ setOpen(false);+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setBusy(false);+ }+ };+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ disabled={disabled}+ onClick={(e) => {+ if (disabled) {+ e.preventDefault();+ toast("Up to 3 sources per video — remove one to add another");+ }+ }}+ className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent"+ >+ <Link2 className="size-3.5" /> Paste a link+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,380px)] p-3" align="start" collisionPadding={12}>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ void add();+ }}+ className="space-y-2"+ >+ <label htmlFor={id} className="text-[13px] font-medium">+ Paste a link – article, page+ </label>+ <div className="flex gap-2">+ <input id={id} autoFocus value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://…" className="h-9 min-w-0 flex-1 rounded-lg border bg-background px-2.5 text-[13px] outline-none focus:border-primary" />+ <Button type="submit" disabled={busy || !url.trim()}>+ {busy ? <Loader2 className="animate-spin" /> : "Add"}+ </Button>+ </div>+ <p className="text-[12px] text-muted-foreground">The page is read and summarised for the script. Public pages only.</p>+ </form>+ </PopoverContent>+ </Popover>+ );+}++/** Higgsfield Explainer's form: a style, what to explain, up to 3 sources, the format; plus your history. */+export function ExplainerStudio({ picker }: { picker: PickerData }) {+ const router = useRouter();+ const [engine, setEngine] = useEngine();+ const genre = genreInfo("education");+ const [draft, setDraft] = useState<EpisodeSettings>(() => ({ ...defaultSettings("cloud", genre, { explainer: true }), auto: true }));+ const [prompt, setPrompt] = useState("");+ const [sources, setSources] = useState<Draft[]>([]);+ const [duration, setDuration] = useState<string>("auto");+ const [manual, setManual] = useState("45");+ const [review, setReview] = useState(false);+ const [stylesOpen, setStylesOpen] = useState(false);+ const [tab, setTab] = useState<"all" | "liked">("all");+ const [q, setQ] = useState("");+ const file = useRef<HTMLInputElement>(null);+ const create = useCreateExplainer();+ const history = useExplainers({ q, liked: tab === "liked" });+ const like = useLikeEpisode();+ const promptId = useId();++ const manualSecs = Math.round(Number(manual));+ const manualBad = duration === "manual" && (!Number.isInteger(Number(manual)) || manualSecs < EXPLAINER_MIN || manualSecs > EXPLAINER_MAX);+ const length = duration === "auto" ? AUTO_SECONDS : duration === "manual" ? Math.max(EXPLAINER_MIN, Math.min(EXPLAINER_MAX, manualSecs || AUTO_SECONDS)) : Number(duration);+ const voice = engine === "open" && draft.voice?.kind === "preset" ? null : engine === "cloud" && !draft.voice ? defaultVoice("cloud", genre, true) : draft.voice;+ const settings: EpisodeSettings = {+ ...draft,+ engine,+ voice,+ length,+ auto: duration === "auto",+ sourceImages: sources.flatMap((s) => (s.kind === "image" && !s.uploading ? [s.url] : [])),+ };+ const estimate = useEstimate({ kind: "explainer", settings });+ const set = (p: Partial<EpisodeSettings>) => setDraft((d) => ({ ...d, ...p }));+ const style = getStyle(settings.styleId);++ const addFiles = async (files: File[]) => {+ let room = MAX_SOURCES - sources.length;+ for (const f of files) {+ if (room <= 0) return void toast("Up to 3 sources per video — remove one to add another");+ if (f.type.startsWith("image/")) {+ room--;+ const id = `${f.name}:${Date.now()}:${room}`;+ void fileToSlot(+ f,+ (v) =>+ setSources((xs) => {+ const at = xs.findIndex((x) => x.kind === "image" && x.id === id);+ if (!v) return xs.filter((_, i) => i !== at);+ const next: Draft = { kind: "image", id, url: v.ref, name: f.name, preview: v.preview, uploading: v.uploading };+ // A source removed while it uploads stays removed.+ if (at < 0) return v.uploading ? [...xs, next] : xs;+ return xs.map((x, i) => (i === at ? next : x));+ }),+ "image",+ );+ } else if (DOC_TYPES.test(f.name) || f.type.startsWith("text/")) {+ const text = (await f.text()).trim().slice(0, MAX_DOC);+ if (!text) {+ toast.error(`${f.name} is empty`);+ continue;+ }+ room--;+ setSources((xs) => [...xs, { kind: "text", name: f.name, text }]);+ } else {+ toast.error(`${f.name}: only images and documents are supported`);+ }+ }+ };++ const generate = () => {+ if (!prompt.trim() && !sources.length) return void toast("Add a prompt, or attach a file or link", { id: "faceless-blocker" });+ if (manualBad) return void toast("Duration must be Auto or a whole number of seconds between 15 and 600", { id: "faceless-blocker" });+ if (sources.some((s) => s.kind === "image" && s.uploading)) return void toast("Uploading…", { id: "faceless-blocker" });+ if (engine === "open" && settings.voice?.kind !== "sample" && estimate.data?.error) return void toast(estimate.data.error, { id: "faceless-blocker" });+ const payload: ExplainerSource[] = sources.map((s) => (s.kind === "image" ? { kind: "image", url: s.url, name: s.name } : s));+ create.mutate(+ { prompt: prompt.trim(), sources: payload, settings, review },+ {+ onSuccess: (ep) => router.push(`/explainer/${ep.id}`),+ onError: (e) => toast.error((e as Error).message),+ },+ );+ };++ 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">Explainer</h1>+ <div className="ml-auto">+ <EngineSwitch value={engine} onChange={setEngine} />+ </div>+ </header>+ <main className="mx-auto grid w-full max-w-[1240px] min-w-0 flex-1 gap-8 px-3 pt-6 pb-16 sm:px-6 lg:grid-cols-[minmax(0,520px)_minmax(0,1fr)]">+ <section aria-label="New explainer" className="min-w-0 lg:sticky lg:top-20 lg:self-start">+ <div className="rounded-[20px] border bg-background p-3 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer sm:p-4">+ <p className="px-1 text-[11px] font-semibold tracking-[0.14em] text-muted-foreground uppercase">Fuobe Explainer</p>+ <div className="mt-2 flex items-center gap-3 rounded-2xl bg-muted/60 p-2">+ <div className="h-14 w-24 shrink-0 overflow-hidden rounded-xl">+ <StyleArt styleId={settings.styleId} />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[14px] font-medium">{style.name}</p>+ <p className="line-clamp-2 text-[12px] leading-snug text-muted-foreground">{style.description}</p>+ </div>+ <Button variant="outline" size="sm" onClick={() => setStylesOpen(true)}>+ Change+ </Button>+ </div>++ <label htmlFor={promptId} className="mt-4 block px-1 text-[13px] font-medium">+ What should the video explain?+ </label>+ <textarea+ id={promptId}+ value={prompt}+ maxLength={MAX_TOPIC}+ onChange={(e) => setPrompt(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ generate();+ }+ }}+ rows={4}+ placeholder="Type a topic, or attach files below — e.g. “Explain how dinosaurs went extinct, for kids”"+ className="mt-1 w-full resize-none bg-transparent px-1 text-body leading-relaxed outline-none [field-sizing:content] placeholder:text-subtle-foreground"+ />+ <p className="px-1 text-right font-mono text-[11px] text-muted-foreground tabular-nums">+ {prompt.length.toLocaleString()} / {MAX_TOPIC.toLocaleString()}+ </p>++ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ {sources.map((s, i) => (+ <SourceChip key={i} s={s} onRemove={() => setSources((xs) => xs.filter((_, j) => j !== i))} />+ ))}+ <button+ type="button"+ onClick={() => (sources.length >= MAX_SOURCES ? toast("Up to 3 sources per video — remove one to add another") : file.current?.click())}+ className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent"+ >+ <Paperclip className="size-3.5" /> Attach a file+ </button>+ <LinkPopover engine={engine} disabled={sources.length >= MAX_SOURCES} onAdd={(s) => setSources((xs) => [...xs, s].slice(0, MAX_SOURCES))} />+ <input+ ref={file}+ type="file"+ multiple+ accept="image/png,image/jpeg,image/webp,.txt,.md,.markdown,.csv,text/plain,text/markdown"+ hidden+ onChange={(e) => {+ const fs = [...(e.target.files ?? [])];+ e.target.value = "";+ void addFiles(fs);+ }}+ />+ </div>++ <div className="mt-4 flex flex-wrap items-center gap-2 border-t pt-3">+ <Segmented+ label="Aspect ratio"+ value={settings.aspect}+ options={[+ { value: "16:9", label: "Horizontal" },+ { value: "9:16", label: "Vertical" },+ ]}+ onChange={(aspect) => set({ aspect })}+ />+ <Select value={duration} onValueChange={setDuration}>+ <SelectTrigger className="h-8 w-auto gap-1.5 rounded-full border-0 bg-secondary px-3 text-[13px] font-medium" aria-label="Duration">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {EXPLAINER_DURATIONS.map((d) => (+ <SelectItem key={String(d.value)} value={String(d.value)}>+ {d.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {duration === "manual" && (+ <label className="inline-flex h-8 items-center gap-1 rounded-full bg-secondary pr-3 pl-1 text-[13px]">+ <input+ value={manual}+ onChange={(e) => setManual(e.target.value.replace(/[^\d]/g, "").slice(0, 3))}+ inputMode="numeric"+ aria-label="Seconds (15–600)"+ aria-invalid={manualBad}+ className={cn("h-7 w-12 rounded-full bg-background text-center font-mono text-[13px] outline-none", manualBad && "text-destructive")}+ />+ s+ </label>+ )}+ <NarratorChip engine={engine} voices={picker.voices} value={settings.voice} onChange={(v) => set({ voice: v })} />+ <label className="inline-flex h-8 items-center gap-2 rounded-full bg-secondary px-3 text-[13px] font-medium">+ Subtitles+ <Switch size="sm" checked={settings.subtitles} onCheckedChange={(subtitles) => set({ subtitles })} aria-label="Subtitles" />+ </label>+ <Popover>+ <PopoverTrigger asChild>+ <button type="button" className="grid size-8 place-items-center rounded-full bg-secondary hover:bg-accent" aria-label="More settings">+ <Settings2 className="size-4" />+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,340px)] space-y-4 p-3" align="end" collisionPadding={12}>+ <div className="space-y-2">+ <p className="text-[11px] font-semibold tracking-wide text-muted-foreground uppercase">Animation</p>+ <Segmented label="Animation" value={settings.animation} options={ANIMATION_MODES.map((m) => ({ value: m.id, label: m.label }))} onChange={(animation) => set({ animation, resolution: undefined })} />+ <p className="text-[12px] text-muted-foreground">{ANIMATION_MODES.find((m) => m.id === settings.animation)?.copy}</p>+ </div>+ <ToggleRow label="Background music" hint={engine === "cloud" ? "Mixed under the voice by ComfyUI (the cloud mixer takes one track)" : "An ACE-Step instrumental bed"} checked={settings.music} onChange={(music) => set({ music })} />+ <ToggleRow label="Review the script first" hint="Edit the scenes before anything renders" checked={review} onChange={setReview} />+ </PopoverContent>+ </Popover>+ </div>++ <div className="mt-3 flex flex-wrap items-center gap-3">+ <EstimateLine data={estimate.data} loading={estimate.isFetching} engine={engine} className="min-w-0 flex-1" />+ <Button onClick={generate} disabled={create.isPending} className="rounded-full">+ {create.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} Generate+ </Button>+ </div>+ </div>++ <ol className="mt-6 grid gap-2 sm:grid-cols-3 lg:grid-cols-1 xl:grid-cols-3" aria-label="How it works">+ {STEPS.map((s, i) => (+ <li key={s.title} className="flex gap-2.5 rounded-2xl bg-muted/50 p-3">+ <span className="grid size-8 shrink-0 place-items-center rounded-lg bg-background text-brand-text shadow-soft">+ <s.icon className="size-4" />+ </span>+ <span className="min-w-0">+ <span className="block text-[13px] font-medium">+ {i + 1}. {s.title}+ </span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{s.text}</span>+ </span>+ </li>+ ))}+ </ol>+ </section>++ <section aria-labelledby="history-title" className="min-w-0 space-y-4">+ <div className="flex flex-wrap items-center gap-2">+ <h2 id="history-title" className="mr-auto font-heading text-[24px]">+ History+ </h2>+ <Segmented+ label="Show"+ value={tab}+ options={[+ { value: "all", label: "Show all" },+ { value: "liked", label: "Liked" },+ ]}+ onChange={setTab}+ />+ <div className="flex h-8 w-full items-center gap-1.5 rounded-full bg-secondary px-3 sm:w-52">+ <Search className="size-3.5 shrink-0 text-muted-foreground" />+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search" aria-label="Search your explainers" className="h-full min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-subtle-foreground" />+ </div>+ </div>+ {history.isLoading ? (+ <div className="grid grid-cols-2 gap-4 xl:grid-cols-3">+ {Array.from({ length: 6 }, (_, i) => (+ <Skeleton key={i} className="aspect-video rounded-xl" />+ ))}+ </div>+ ) : history.data?.length ? (+ <div className="grid grid-cols-2 gap-x-4 gap-y-6 xl:grid-cols-3">+ {history.data.map((ep) => (+ <EpisodeTile key={ep.id} ep={ep} href={`/explainer/${ep.id}`} onLike={() => like.mutate({ id: ep.id, favorite: !ep.favorite })} />+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center rounded-2xl border border-dashed px-6 py-12 text-center">+ <div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">{tab === "liked" ? <ImageIcon className="size-5" /> : <Sparkles className="size-5" />}</div>+ <p className="mt-3 font-heading text-[22px]">{q ? `Nothing matches “${q}”` : tab === "liked" ? "No liked explainers yet" : "Your explainers show up here"}</p>+ <p className="mt-1 max-w-sm text-[13px] text-muted-foreground">{tab === "liked" ? "Like an explainer to keep it here." : "Pick a style, say what to explain, and press Generate."}</p>+ </div>+ )}+ </section>+ </main>++ <Sheet open={stylesOpen} onOpenChange={setStylesOpen}>+ <SheetContent className="w-full overflow-y-auto sm:max-w-[640px]">+ <SheetHeader>+ <SheetTitle>Styles</SheetTitle>+ <SheetDescription>One visual style for the whole video.</SheetDescription>+ </SheetHeader>+ <div className="px-4 pb-8">+ <StyleGrid+ ids={EXPLAINER_STYLE_IDS}+ value={settings.styleId}+ onChange={(styleId) => {+ set({ styleId });+ setStylesOpen(false);+ }}+ className="sm:grid-cols-3 lg:grid-cols-3"+ />+ </div>+ </SheetContent>+ </Sheet>+ </div>+ );+}diff --git a/src/components/faceless/cards.tsx b/src/components/faceless/cards.tsxnew file mode 100644index 00000000..2e0ade34--- /dev/null+++ b/src/components/faceless/cards.tsx@@ -0,0 +1,140 @@+"use client";++import { AlertTriangle, Heart, Loader2, PenLine, Tv } from "lucide-react";+import Link from "next/link";+import { MediaThumb } from "@/components/studio/feed";+import { formatLength, genreInfo, getStyle, type EpisodeCard as Card, type FacelessChannel } from "@/lib/catalog/faceless";+import { timeAgo } from "@/lib/format";+import { cn } from "@/lib/utils";+import { StyleArt } from "./style-art";++const hueOf = (s: string) => {+ let h = 0;+ for (const ch of s) h = (h * 31 + ch.charCodeAt(0)) % 360;+ return h;+};++const initials = (name: string) =>+ name+ .split(/\s+/)+ .filter((w) => /^[\p{L}\p{N}]/u.test(w) && !/^(the|of|and|a|an)$/i.test(w))+ .slice(0, 2)+ .map((w) => w[0]!.toUpperCase())+ .join("") || "?";++/** The channel's avatar, or its initials on a colour of its own. */+export function ChannelAvatar({ channel, className }: { channel: Pick<FacelessChannel, "id" | "name" | "avatarUrl">; className?: string }) {+ const hue = hueOf(channel.id);+ if (channel.avatarUrl)+ // eslint-disable-next-line @next/next/no-img-element+ return <img src={channel.avatarUrl} alt="" className={cn("size-10 shrink-0 rounded-full object-cover", className)} />;+ return (+ <span+ aria-hidden+ className={cn("grid size-10 shrink-0 place-items-center rounded-full font-heading text-[16px] text-white", className)}+ style={{ background: `linear-gradient(135deg, oklch(0.62 0.14 ${hue}), oklch(0.42 0.12 ${(hue + 50) % 360}))` }}+ >+ {initials(channel.name)}+ </span>+ );+}++export function ChannelCard({ channel }: { channel: FacelessChannel }) {+ const cover = channel.cover?.outputs.find((o) => o.kind === "video" || o.kind === "image");+ return (+ <Link href={`/faceless/${channel.id}`} className="group/card block animate-fade-up rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <div className="relative aspect-video overflow-hidden rounded-xl bg-muted">+ {cover ? <MediaThumb output={cover} className="transition-transform duration-300 ease-move group-hover/card:scale-[1.02]" /> : <StyleArt styleId={channel.settings.styleId} className="opacity-90" />}+ <span className="absolute bottom-2 left-2 rounded-full bg-black/45 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">{genreInfo(channel.genre).label}</span>+ </div>+ <div className="mt-2.5 flex min-w-0 items-center gap-2.5 px-0.5">+ <ChannelAvatar channel={channel} className="size-8 text-[13px]" />+ <div className="min-w-0">+ <h3 className="truncate text-[15px] font-medium">{channel.name}</h3>+ <p className="truncate text-[12px] text-muted-foreground">+ {channel.episodes ?? 0} episode{channel.episodes === 1 ? "" : "s"} · {getStyle(channel.settings.styleId).name}+ </p>+ </div>+ </div>+ </Link>+ );+}++const STATUS: Record<Card["status"], string> = {+ writing: "Writing the script…",+ "write-failed": "Couldn't write the script",+ review: "Script ready to review",+ rendering: "Rendering",+ done: "",+ failed: "A step failed",+};++/** An episode in a channel's list or the Explainer history. */+export function EpisodeTile({ ep, href, onLike }: { ep: Card; href: string; onLike?: () => void }) {+ const poster = ep.poster?.outputs.find((o) => o.kind === "video" || o.kind === "image");+ const vertical = ep.aspect === "9:16";+ return (+ <div className="group/card relative min-w-0 animate-fade-up">+ <Link href={href} className="block rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label={`Open ${ep.title}`}>+ <div className={cn("relative overflow-hidden rounded-xl bg-muted", vertical ? "aspect-[4/5]" : "aspect-video")}>+ {poster ? (+ <MediaThumb output={poster} className={cn("transition-transform duration-300 ease-move group-hover/card:scale-[1.02]", ep.status !== "done" && "opacity-70")} />+ ) : (+ <StyleArt styleId={ep.styleId} className="opacity-80" />+ )}+ {ep.status !== "done" && (+ <div className="absolute inset-x-0 bottom-0 flex items-center gap-1.5 bg-gradient-to-t from-black/70 to-transparent p-2.5 pt-8 text-[12px] font-medium text-white">+ {ep.status === "rendering" || ep.status === "writing" ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : ep.status === "review" ? (+ <PenLine className="size-3.5" />+ ) : (+ <AlertTriangle className="size-3.5" />+ )}+ <span className="truncate">{STATUS[ep.status]}</span>+ {ep.status === "rendering" && <span className="ml-auto font-mono tabular-nums">{Math.round(ep.progress * 100)}%</span>}+ </div>+ )}+ {ep.status === "rendering" && (+ <div className="absolute inset-x-0 top-0 h-0.5">+ <div className="h-full bg-primary transition-[width] duration-500" style={{ width: `${Math.round(ep.progress * 100)}%` }} />+ </div>+ )}+ {ep.status === "done" && <span className="absolute right-2 bottom-2 rounded-full bg-black/55 px-1.5 py-0.5 font-mono text-[11px] text-white tabular-nums">{formatLength(ep.seconds)}</span>}+ </div>+ <div className="mt-2 min-w-0 px-0.5">+ <h3 className="line-clamp-2 text-[14px] leading-snug font-medium">{ep.title}</h3>+ <p className="mt-0.5 truncate text-[12px] text-muted-foreground">+ {getStyle(ep.styleId).name} · {timeAgo(ep.createdAt)}+ </p>+ </div>+ </Link>+ {onLike && (+ <button+ type="button"+ onClick={onLike}+ aria-pressed={ep.favorite}+ aria-label={ep.favorite ? `Unlike ${ep.title}` : `Like ${ep.title}`}+ className={cn(+ "absolute top-2 right-2 grid size-8 place-items-center rounded-full bg-black/45 text-white backdrop-blur transition-opacity hover:bg-black/65 focus-visible:opacity-100",+ ep.favorite ? "opacity-100" : "opacity-100 sm:opacity-0 sm:group-hover/card:opacity-100",+ )}+ >+ <Heart className={cn("size-4", ep.favorite && "fill-highlight text-highlight")} />+ </button>+ )}+ </div>+ );+}++export function EmptyChannels() {+ return (+ <div className="flex flex-col items-center rounded-2xl border border-dashed px-6 py-10 text-center">+ <div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Tv className="size-5" />+ </div>+ <p className="mt-3 font-heading text-[22px]">No channels yet</p>+ <p className="mt-1 max-w-sm text-[13px] text-muted-foreground">Describe a channel above: it keeps its look, narrator and format, so every episode feels like the same show.</p>+ </div>+ );+}diff --git a/src/components/faceless/channel-view.tsx b/src/components/faceless/channel-view.tsxnew file mode 100644index 00000000..a33d025f--- /dev/null+++ b/src/components/faceless/channel-view.tsx@@ -0,0 +1,318 @@+"use client";++import { ArrowLeft, Check, ImagePlus, Link2, Loader2, MoreHorizontal, Pencil, Plus, Settings2, Trash2, Tv } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import { NotFoundState } from "@/components/empty-state";+import { FACELESS_STYLE_IDS, genreInfo, getStyle, type ChannelSettings, type FacelessChannel, type PickerData } from "@/lib/catalog/faceless";+import { cn } from "@/lib/utils";+import { ChannelAvatar, EpisodeTile } from "./cards";+import { Section, Segmented, ToggleRow } from "./controls";+import { makeAvatar, useChannel, useDeleteChannel, useLikeEpisode, useUpdateChannel, waitFor } from "./hooks";+import { NarratorList, voiceLabel } from "./narrator";+import { StyleArt, StyleGrid } from "./style-art";++/** The look and sound saved on a channel (every new episode starts from it). */+function ChannelSettingsSheet({ channel, picker, open, onOpenChange }: { channel: FacelessChannel; picker: PickerData; open: boolean; onOpenChange: (v: boolean) => void }) {+ const update = useUpdateChannel(channel.id);+ const [s, setS] = useState<ChannelSettings>(channel.settings);+ const set = (p: Partial<ChannelSettings>) => setS((x) => ({ ...x, ...p }));+ return (+ <Sheet+ open={open}+ onOpenChange={(v) => {+ if (v) setS(channel.settings);+ onOpenChange(v);+ }}+ >+ <SheetContent className="w-full overflow-y-auto sm:max-w-[560px]">+ <SheetHeader>+ <SheetTitle>Channel look and sound</SheetTitle>+ <SheetDescription>Saved on the channel so every episode looks and sounds the same.</SheetDescription>+ </SheetHeader>+ <div className="space-y-6 px-4 pb-24">+ <Section title="Style">+ <StyleGrid ids={FACELESS_STYLE_IDS} value={s.styleId} onChange={(styleId) => set({ styleId, styleRefs: [] })} compact className="sm:grid-cols-3 lg:grid-cols-3" />+ </Section>+ <Section title="Format">+ <Segmented+ label="Aspect ratio"+ value={s.aspect}+ options={[+ { value: "16:9", label: "Horizontal 16:9" },+ { value: "9:16", label: "Vertical 9:16" },+ ]}+ onChange={(aspect) => set({ aspect })}+ />+ <div className="space-y-3 rounded-xl border p-3">+ <ToggleRow label="Subtitles" checked={s.subtitles} onChange={(subtitles) => set({ subtitles })} />+ <ToggleRow label="Background music" checked={s.music} onChange={(music) => set({ music })} />+ </div>+ </Section>+ <Section title="Narrator">+ <div className="rounded-xl border p-2">+ <NarratorList engine={s.engine} voices={picker.voices} value={s.voice} onChange={(voice) => set({ voice })} />+ </div>+ </Section>+ </div>+ <div className="sticky bottom-0 flex justify-end gap-2 border-t bg-background p-3">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button+ disabled={update.isPending}+ onClick={() =>+ update.mutate(+ { settings: s },+ {+ onSuccess: () => {+ toast.success("Saved");+ onOpenChange(false);+ },+ onError: (e) => toast.error((e as Error).message),+ },+ )+ }+ >+ {update.isPending ? <Loader2 className="animate-spin" /> : <Check />} Save+ </Button>+ </div>+ </SheetContent>+ </Sheet>+ );+}++function Chip({ children, className }: { children: React.ReactNode; className?: string }) {+ return <span className={cn("inline-flex h-7 max-w-full items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium text-secondary-foreground", className)}>{children}</span>;+}++export function ChannelView({ id, picker }: { id: string; picker: PickerData }) {+ const router = useRouter();+ const { data, isLoading, error } = useChannel(id);+ const update = useUpdateChannel(id);+ const del = useDeleteChannel();+ const like = useLikeEpisode();+ const [editing, setEditing] = useState(false);+ const [name, setName] = useState("");+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [confirm, setConfirm] = useState(false);+ const [avatarBusy, setAvatarBusy] = useState(false);++ if (error && /not found/i.test((error as Error).message)) return <NotFoundState title="This channel doesn't exist">It may have been deleted. Your episodes' videos are still in your library.</NotFoundState>;+ const channel = data?.channel;++ const drawAvatar = async () => {+ setAvatarBusy(true);+ try {+ const g = await waitFor((await makeAvatar(id)).id);+ const url = g.outputs.find((o) => o.kind === "image")?.url;+ if (g.status !== "succeeded" || !url) throw new Error(g.error ?? "Couldn't draw the avatar");+ await update.mutateAsync({ avatarUrl: url });+ toast.success("Avatar updated");+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setAvatarBusy(false);+ }+ };++ 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="/faceless" className="inline-flex min-w-0 items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground">+ <ArrowLeft className="size-4 shrink-0" /> <span className="truncate">Faceless Studio</span>+ </Link>+ </header>+ <main className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 space-y-8 px-3 pb-16 sm:px-6">+ {isLoading || !channel ? (+ <div className="space-y-4 pt-6">+ <div className="flex items-center gap-4">+ <Skeleton className="size-16 rounded-full" />+ <div className="flex-1 space-y-2">+ <Skeleton className="h-7 w-64" />+ <Skeleton className="h-4 w-80 max-w-full" />+ </div>+ </div>+ <div className="grid grid-cols-1 gap-5 pt-6 sm:grid-cols-2 lg:grid-cols-4">+ {Array.from({ length: 4 }, (_, i) => (+ <Skeleton key={i} className="aspect-video rounded-xl" />+ ))}+ </div>+ </div>+ ) : (+ <>+ <section className="flex flex-wrap items-start gap-4 pt-6">+ <div className="relative">+ <ChannelAvatar channel={channel} className="size-16 text-[24px]" />+ {avatarBusy && (+ <span className="absolute inset-0 grid place-items-center rounded-full bg-background/60" role="status" aria-label="Drawing the avatar">+ <Loader2 className="size-5 animate-spin" />+ </span>+ )}+ </div>+ <div className="min-w-0 flex-1 basis-64">+ {editing ? (+ <form+ className="flex items-center gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ update.mutate({ name }, { onError: (err) => toast.error((err as Error).message) });+ setEditing(false);+ }}+ >+ <input+ autoFocus+ value={name}+ maxLength={60}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => e.key === "Escape" && setEditing(false)}+ aria-label="Channel name"+ className="h-10 min-w-0 flex-1 rounded-lg border bg-background px-3 font-heading text-[26px] outline-none focus:border-primary"+ />+ <Button type="submit" size="icon" aria-label="Save the name">+ <Check />+ </Button>+ </form>+ ) : (+ <div className="flex min-w-0 items-center gap-1.5">+ <h1 className="truncate font-heading text-[32px] leading-tight">{channel.name}</h1>+ <button+ type="button"+ onClick={() => {+ setName(channel.name);+ setEditing(true);+ }}+ className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground"+ aria-label="Rename channel"+ >+ <Pencil className="size-3.5" />+ </button>+ </div>+ )}+ <p className="mt-0.5 line-clamp-2 text-[14px] text-muted-foreground">+ {genreInfo(channel.genre).label} · {channel.idea}+ </p>+ <div className="mt-3 flex flex-wrap gap-1.5">+ <Chip>+ <span className="h-4 w-6 overflow-hidden rounded-sm">+ <StyleArt styleId={channel.settings.styleId} />+ </span>+ {channel.settings.styleRefs.length ? "Your own style" : getStyle(channel.settings.styleId).name}+ </Chip>+ <Chip>{voiceLabel(channel.settings.voice, picker.voices, channel.settings.engine)}</Chip>+ <Chip>{channel.settings.aspect === "9:16" ? "Vertical 9:16" : "Horizontal 16:9"}</Chip>+ <Chip>{channel.settings.subtitles ? "Subtitles on" : "No subtitles"}</Chip>+ {channel.settings.music && <Chip>Music</Chip>}+ {channel.reference && (+ <a href={channel.reference.url} target="_blank" rel="noreferrer" className="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent">+ <Link2 className="size-3.5 shrink-0" /> <span className="truncate">{channel.reference.title ?? "Reference"}</span>+ </a>+ )}+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Button asChild>+ <Link href={`/faceless/${channel.id}/new`}>+ <Plus /> New episode+ </Link>+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="icon" aria-label="Channel actions">+ <MoreHorizontal />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => setTimeout(() => setSettingsOpen(true))}>+ <Settings2 /> Look and sound+ </DropdownMenuItem>+ <DropdownMenuItem disabled={avatarBusy} onClick={() => void drawAvatar()}>+ <ImagePlus /> Draw an avatar+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={() => setTimeout(() => setConfirm(true))}>+ <Trash2 /> Delete channel+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </section>++ <section aria-labelledby="episodes-title" className="space-y-4">+ <h2 id="episodes-title" className="font-heading text-[24px]">+ Episodes+ </h2>+ {data.episodes.length ? (+ <div className="grid grid-cols-2 gap-x-4 gap-y-6 md:grid-cols-3 lg:grid-cols-4">+ {data.episodes.map((ep) => (+ <EpisodeTile key={ep.id} ep={ep} href={`/faceless/${channel.id}/${ep.id}`} onLike={() => like.mutate({ id: ep.id, favorite: !ep.favorite })} />+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center rounded-2xl border border-dashed px-6 py-12 text-center">+ <div className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Tv className="size-5" />+ </div>+ <p className="mt-3 font-heading text-[22px]">No episodes yet</p>+ <p className="mt-1 max-w-sm text-[13px] text-muted-foreground">Pick a topic, review the script, and the first episode renders in the channel's look.</p>+ <Button asChild className="mt-5">+ <Link href={`/faceless/${channel.id}/new`}>+ <Plus /> Create the first episode+ </Link>+ </Button>+ </div>+ )}+ </section>++ <ChannelSettingsSheet channel={channel} picker={picker} open={settingsOpen} onOpenChange={setSettingsOpen} />+ <AlertDialog open={confirm} onOpenChange={setConfirm}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete “{channel.name}”?</AlertDialogTitle>+ <AlertDialogDescription>+ The channel and its {data.episodes.length} episode{data.episodes.length === 1 ? "" : "s"} are removed from Faceless Studio. Their videos stay in your Library.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() =>+ del.mutate(channel.id, {+ onSuccess: () => {+ toast("Channel deleted");+ router.push("/faceless");+ },+ onError: (e) => toast.error((e as Error).message),+ })+ }+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )}+ </main>+ </div>+ );+}diff --git a/src/components/faceless/controls.tsx b/src/components/faceless/controls.tsxnew file mode 100644index 00000000..08551d17--- /dev/null+++ b/src/components/faceless/controls.tsx@@ -0,0 +1,119 @@+"use client";++import { AlertTriangle, Info, Loader2 } from "lucide-react";+import { useId } from "react";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Switch } from "@/components/ui/switch";+import { radioKeys, radioTab } from "@/components/studio/radio-keys";+import { formatLength, PART_LABELS, type EstimateResult, type StepPart } from "@/lib/catalog/faceless";+import type { Engine } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";++/** A segmented control (Liner style: muted track, white thumb), keyboard like a radio group. */+export function Segmented<T extends string | number>({+ value,+ options,+ onChange,+ label,+ className,+}: {+ value: T;+ options: { value: T; label: string; hint?: string }[];+ onChange: (v: T) => void;+ label: string;+ className?: string;+}) {+ return (+ <div role="radiogroup" aria-label={label} onKeyDown={radioKeys} className={cn("inline-flex max-w-full flex-wrap gap-0.5 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)}+ title={o.hint}+ onClick={() => onChange(o.value)}+ className={cn(+ "h-8 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition outline-none focus-visible:ring-2 focus-visible:ring-ring",+ value === o.value ? "bg-background text-foreground shadow-soft" : "hover:text-foreground",+ )}+ >+ {o.label}+ </button>+ ))}+ </div>+ );+}++/** A labelled switch row. */+export function ToggleRow({ label, hint, checked, onChange, disabled }: { label: string; hint?: string; checked: boolean; onChange: (v: boolean) => void; disabled?: boolean }) {+ const id = useId();+ return (+ <div className="flex items-start justify-between gap-4">+ <label htmlFor={id} className="min-w-0 cursor-pointer">+ <span className="block text-[13px] font-medium">{label}</span>+ {hint && <span className="block text-[12px] leading-snug text-muted-foreground">{hint}</span>}+ </label>+ <Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} className="mt-0.5" />+ </div>+ );+}++/** A form section with a small uppercase title. */+export function Section({ title, hint, children, className }: { title: string; hint?: React.ReactNode; children: React.ReactNode; className?: string }) {+ return (+ <section className={cn("space-y-2.5", className)}>+ <div>+ <h3 className="text-[11px] font-semibold tracking-wide text-muted-foreground uppercase">{title}</h3>+ {hint && <p className="mt-0.5 text-[12px] text-muted-foreground">{hint}</p>}+ </div>+ {children}+ </section>+ );+}++export const usd = (n: number) => (n >= 10 ? `$${n.toFixed(0)}` : `$${n.toFixed(2)}`);++/** "≈ $7.02" / "Demo · free" / "Free · your GPU", with what it's made of in a popover. */+export function EstimateLine({ data, loading, engine, className }: { data: EstimateResult | undefined; loading?: boolean; engine: Engine; className?: string }) {+ if (!data) return <span className={cn("inline-flex items-center gap-1.5 font-mono text-[12px] text-muted-foreground", className)}>{loading && <Loader2 className="size-3 animate-spin" />}Estimating…</span>;+ const price = data.demo ? "Demo · free" : engine === "open" ? "Free · your GPU" : `≈ ${usd(data.estimate.total)}${data.estimate.unknown ? "+" : ""}`;+ const parts = Object.entries(data.estimate.parts).filter(([, v]) => (v ?? 0) > 0) as [StepPart, number][];+ return (+ <div className={cn("flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1", className)}>+ <Popover>+ <PopoverTrigger asChild>+ <button type="button" className="inline-flex items-center gap-1 rounded-full font-mono text-[12px] text-foreground tabular-nums hover:underline">+ {price}+ <Info className="size-3 text-muted-foreground" />+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-72 p-3 text-[13px]" collisionPadding={12}>+ <p className="font-medium">How the price works</p>+ <p className="mt-1 text-[12px] text-muted-foreground">You're only charged for the actual length. The exact cost isn't known upfront — this is an estimate from your providers' prices.</p>+ {parts.length > 0 && !data.demo && (+ <dl className="mt-2.5 space-y-1">+ {parts.map(([k, v]) => (+ <div key={k} className="flex justify-between gap-3 font-mono text-[12px] tabular-nums">+ <dt className="font-sans text-muted-foreground">{PART_LABELS[k]}</dt>+ <dd>{usd(v)}</dd>+ </div>+ ))}+ </dl>+ )}+ {data.demo && <p className="mt-2 text-[12px] text-muted-foreground">Nothing is connected for some steps, so this runs as a free demo with placeholder results.</p>}+ </PopoverContent>+ </Popover>+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">+ {formatLength(data.seconds)} · {data.blocks} scene{data.blocks === 1 ? "" : "s"}+ </span>+ {data.error && (+ <span role="alert" className="inline-flex min-w-0 items-start gap-1 text-[12px] text-warning">+ <AlertTriangle className="mt-0.5 size-3 shrink-0" />+ <span className="min-w-0">{data.error}</span>+ </span>+ )}+ </div>+ );+}diff --git a/src/components/faceless/episode-view.tsx b/src/components/faceless/episode-view.tsxnew file mode 100644index 00000000..4d1b1f60--- /dev/null+++ b/src/components/faceless/episode-view.tsx@@ -0,0 +1,586 @@+"use client";++import {+ AlertTriangle,+ ArrowLeft,+ AudioLines,+ Captions,+ Check,+ Clapperboard,+ Download,+ Film,+ Heart,+ History,+ Loader2,+ MoreHorizontal,+ Music,+ Pencil,+ RotateCcw,+ Trash2,+ Undo2,+ Wand2,+ X,+} from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useMemo, useState } from "react";+import { toast } from "sonner";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import { NotFoundState } from "@/components/empty-state";+import { MediaThumb } from "@/components/studio/feed";+import { Viewer } from "@/components/studio/viewer";+import {+ blockTimes,+ formatLength,+ getStyle,+ PART_LABELS,+ tooLong,+ type ChangePart,+ type EpisodeView as View,+ type StepView,+} from "@/lib/catalog/faceless";+import type { Generation } from "@/lib/catalog/types";+import { timeAgo } from "@/lib/format";+import { downloadHref, downloadName } from "@/lib/library";+import { cn } from "@/lib/utils";+import { Segmented, usd } from "./controls";+import { useApplyChange, useChangePreview, useDeleteEpisode, useEpisode, useEpisodeAction, useUpdateEpisode, type ChangeDraft } from "./hooks";+import { ScriptReview } from "./script-review";++const done = (g: Generation | null | undefined) => g?.status === "succeeded";+const broken = (g: Generation | null | undefined) => g?.status === "failed" || g?.status === "canceled";+const active = (g: Generation | null | undefined) => g?.status === "queued" || g?.status === "running";++function StatusDot({ g, className }: { g: Generation | null | undefined; className?: string }) {+ if (done(g)) return <Check className={cn("size-3 text-success", className)} aria-label="Done" />;+ if (broken(g)) return <AlertTriangle className={cn("size-3 text-destructive", className)} aria-label="Failed" />;+ if (g?.status === "running") return <Loader2 className={cn("size-3 animate-spin text-brand-text", className)} aria-label="Running" />;+ return <span className={cn("size-2 rounded-full bg-border-strong", className)} aria-label="Waiting" />;+}++/** The finished film, the last one while a change renders, or the progress of the first render. */+function Player({ view, onRetry, retrying }: { view: View; onRetry: () => void; retrying: boolean }) {+ const ep = view.episode;+ const film = view.final ?? view.previousFinal;+ const out = film?.outputs.find((o) => o.kind === "video");+ const vertical = ep.settings.aspect === "9:16";+ const stepsDone = view.steps.filter((s) => done(s.generation)).length;+ return (+ <div className={cn("relative mx-auto overflow-hidden rounded-2xl bg-media", vertical ? "aspect-[9/16] max-h-[72vh] max-w-[420px]" : "aspect-video w-full")}>+ {out ? (+ <video key={out.url} src={out.url} controls playsInline preload="metadata" className="size-full bg-black object-contain" aria-label={`${ep.title} — the episode`} />+ ) : (+ <div className="absolute inset-0 grid place-items-center bg-muted p-6">+ <div className="skeleton-sweep absolute inset-0 animate-skeleton" />+ <div className="relative max-w-sm text-center">+ {ep.status === "failed" ? (+ <>+ <AlertTriangle className="mx-auto size-6 text-destructive" />+ <p className="mt-3 font-heading text-[22px]">A step didn't finish</p>+ <p className="mt-1 line-clamp-4 text-[13px] text-muted-foreground">{ep.error}</p>+ <Button className="mt-4" onClick={onRetry} disabled={retrying}>+ {retrying ? <Loader2 className="animate-spin" /> : <RotateCcw />} Retry what failed+ </Button>+ </>+ ) : (+ <>+ <p className="shimmer-text animate-shimmer-text font-heading text-[24px]">Generating your episode</p>+ <p className="mt-1 text-[13px] text-muted-foreground">This can take a while for longer videos. You can close this page — it will keep running.</p>+ <div className="mx-auto mt-4 h-1.5 w-56 overflow-hidden rounded-full bg-background/70" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(view.progress * 100)} aria-label="Episode progress">+ <div className="h-full rounded-full bg-primary transition-[width] duration-700" style={{ width: `${Math.max(3, Math.round(view.progress * 100))}%` }} />+ </div>+ <p className="mt-2 font-mono text-[12px] text-muted-foreground tabular-nums">+ {stepsDone} of {view.steps.length} steps · {Math.round(view.progress * 100)}%+ </p>+ </>+ )}+ </div>+ </div>+ )}+ {!view.final && view.previousFinal && ep.status === "rendering" && (+ <span className="absolute top-3 left-3 inline-flex items-center gap-1.5 rounded-full bg-black/60 px-2.5 py-1 text-[12px] font-medium text-white backdrop-blur">+ <Loader2 className="size-3 animate-spin" /> Updating · {Math.round(view.progress * 100)}%+ </span>+ )}+ </div>+ );+}++interface SceneRow {+ id: string;+ index: number;+ narration: string;+ seconds: number;+ start: number;+ still: StepView | undefined;+ clips: StepView[];+}++/** A scene in the timeline: its picture, how far it got, its length. */+function SceneTile({ scene, selected, onSelect, aspect }: { scene: SceneRow; selected: boolean; onSelect: (e: React.MouseEvent) => void; aspect: string }) {+ const still = scene.still?.generation;+ const img = still?.outputs.find((o) => o.kind === "image");+ const clipsDone = scene.clips.filter((c) => done(c.generation)).length;+ const failed = [scene.still, ...scene.clips].some((s) => broken(s?.generation));+ const running = [scene.still, ...scene.clips].some((s) => active(s?.generation));+ return (+ <button+ type="button"+ aria-pressed={selected}+ aria-label={`Scene ${scene.index + 1}, ${formatLength(scene.start)}, ${failed ? "failed" : running ? "rendering" : clipsDone === scene.clips.length ? "done" : "waiting"}`}+ onClick={onSelect}+ className={cn(+ "group/scene relative w-[132px] shrink-0 overflow-hidden rounded-xl border-2 bg-muted text-left outline-none focus-visible:ring-2 focus-visible:ring-ring sm:w-[156px]",+ selected ? "border-primary" : "border-transparent hover:border-border-strong",+ )}+ >+ <div className={cn("relative w-full", aspect === "9:16" ? "aspect-[3/4]" : "aspect-video")}>+ {img ? <MediaThumb output={img} /> : <div className={cn("absolute inset-0", running && "skeleton-sweep animate-skeleton")} />}+ {failed && <div className="absolute inset-0 grid place-items-center bg-destructive/15"><AlertTriangle className="size-5 text-destructive" /></div>}+ <span className="absolute top-1.5 left-1.5 grid size-5 place-items-center rounded-full bg-background/90 font-mono text-[10px] font-semibold shadow-soft">{scene.index + 1}</span>+ <span className="absolute right-1.5 bottom-1.5 rounded bg-black/55 px-1 font-mono text-[10px] text-white tabular-nums">{scene.seconds}s</span>+ </div>+ <div className="flex items-center gap-1 px-2 py-1.5">+ <StatusDot g={still} />+ {scene.clips.map((c) => (+ <StatusDot key={c.key} g={c.generation} />+ ))}+ <span className="ml-auto truncate font-mono text-[10px] text-muted-foreground tabular-nums">{formatLength(scene.start)}</span>+ </div>+ </button>+ );+}++const TAIL_ICON = { join: Film, narration: AudioLines, music: Music, mix: Clapperboard, words: Captions, captions: Captions } as const;++/** The steps after the scenes: joining, the voice-over, music, the mix and subtitles. */+function TailSteps({ steps, onOpen }: { steps: StepView[]; onOpen: (g: Generation) => void }) {+ const tail = steps.filter((s) => s.part !== "still" && s.part !== "clip");+ const groups = new Map<string, StepView[]>();+ for (const s of tail) groups.set(s.part, [...(groups.get(s.part) ?? []), s]);+ return (+ <div className="flex flex-wrap gap-1.5">+ {[...groups.entries()].map(([part, list]) => {+ const Icon = TAIL_ICON[part as keyof typeof TAIL_ICON] ?? Film;+ const last = list[list.length - 1];+ const g = last.generation;+ const all = list.filter((s) => done(s.generation)).length;+ const audio = part === "narration" || part === "music" ? g?.outputs.find((o) => o.kind === "audio") : undefined;+ return (+ <button+ key={part}+ type="button"+ disabled={!done(g)}+ onClick={() => g && onOpen(g)}+ className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[12px] font-medium transition-colors enabled:hover:bg-accent disabled:cursor-default"+ title={g?.error ?? undefined}+ >+ <Icon className="size-3.5 text-muted-foreground" />+ {PART_LABELS[part as keyof typeof PART_LABELS]}+ {list.length > 1 && <span className="font-mono text-[11px] text-muted-foreground tabular-nums">{all}/{list.length}</span>}+ <StatusDot g={g} />+ {audio && <span className="sr-only">Opens the audio</span>}+ </button>+ );+ })}+ </div>+ );+}++const PART_OPTIONS: { value: ChangePart; label: string }[] = [+ { value: "picture", label: "Picture" },+ { value: "motion", label: "Motion" },+ { value: "narration", label: "Narration" },+];++/** Change the selected scenes: describe the change, see what re-runs and the price, apply or discard. */+function SceneEditor({ view, scenes, onClose, onOpen }: { view: View; scenes: SceneRow[]; onClose: () => void; onOpen: (g: Generation) => void }) {+ const ep = view.episode;+ const [part, setPart] = useState<ChangePart>("picture");+ const [instruction, setInstruction] = useState("");+ const [lines, setLines] = useState<string[]>(() => scenes.map((s) => s.narration));+ const apply = useApplyChange(ep.id);+ const ids = scenes.map((s) => s.id);+ const draft: ChangeDraft | null =+ part === "narration"+ ? lines.some((l, i) => l.trim() && l.trim() !== scenes[i].narration)+ ? { blocks: ids, part, narration: lines }+ : null+ : instruction.trim()+ ? { blocks: ids, part, instruction: instruction.trim() }+ : null;+ const preview = useChangePreview(ep.id, draft);+ const busy = ep.status === "rendering";+ const one = scenes.length === 1 ? scenes[0] : null;+ const still = one?.still?.generation;+ const stillImg = still?.outputs.find((o) => o.kind === "image");++ const discard = () => {+ setInstruction("");+ setLines(scenes.map((s) => s.narration));+ };+ const go = () => {+ if (!draft) return void toast(part === "narration" ? "Change the lines first" : "Describe the change first", { id: "faceless-blocker" });+ apply.mutate(draft, {+ onSuccess: () => {+ toast.success(`Re-rendering ${scenes.length > 1 ? `${scenes.length} scenes` : `scene ${scenes[0].index + 1}`}`);+ discard();+ },+ onError: (e) => toast.error((e as Error).message),+ });+ };++ return (+ <section aria-label="Change scenes" className="animate-fade-up rounded-2xl border bg-background p-3 sm:p-4">+ <div className="flex items-center gap-2">+ <h3 className="text-[15px] font-medium">{one ? `Scene ${one.index + 1}` : `${scenes.length} scenes`}</h3>+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">{one ? `${formatLength(one.start)} – ${formatLength(one.start + one.seconds)}` : scenes.map((s) => s.index + 1).join(", ")}</span>+ <Button variant="ghost" size="icon-sm" className="ml-auto" onClick={onClose} aria-label="Close the scene editor">+ <X />+ </Button>+ </div>+ {one && (+ <div className="mt-3 grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">+ <div className="grid grid-cols-2 gap-2">+ <button type="button" disabled={!done(still)} onClick={() => still && onOpen(still)} className="relative aspect-video overflow-hidden rounded-lg bg-muted" aria-label="Open the picture">+ {stillImg && <MediaThumb output={stillImg} />}+ <span className="absolute bottom-1 left-1 rounded bg-black/55 px-1.5 text-[10px] text-white">Picture</span>+ </button>+ {one.clips.slice(0, 1).map((c) => {+ const v = c.generation?.outputs.find((o) => o.kind === "video");+ return (+ <button key={c.key} type="button" disabled={!done(c.generation)} onClick={() => c.generation && onOpen(c.generation)} className="relative aspect-video overflow-hidden rounded-lg bg-muted" aria-label="Open the clip">+ {v && <MediaThumb output={v} />}+ <span className="absolute bottom-1 left-1 rounded bg-black/55 px-1.5 text-[10px] text-white">Clip{one.clips.length > 1 ? ` · ${one.clips.length}` : ""}</span>+ </button>+ );+ })}+ </div>+ <p className="text-[13px] leading-relaxed text-muted-foreground">“{one.narration}”</p>+ </div>+ )}+ <div className="mt-4 space-y-3">+ <Segmented label="What to change" value={part} options={PART_OPTIONS} onChange={setPart} />+ {part === "narration" ? (+ <div className="space-y-2">+ {scenes.map((s, i) => (+ <label key={s.id} className="block space-y-1">+ <span className="text-[12px] text-muted-foreground">Scene {s.index + 1}</span>+ <textarea+ value={lines[i]}+ maxLength={2000}+ onChange={(e) => setLines((ls) => ls.map((l, j) => (j === i ? e.target.value : l)))}+ rows={2}+ className="w-full resize-none rounded-lg border bg-background px-2.5 py-2 text-[14px] outline-none [field-sizing:content] focus:border-primary"+ />+ {tooLong(lines[i]) && <span className="text-[12px] text-warning">Longer than the scene: the voice runs over into the next one.</span>}+ </label>+ ))}+ <p className="text-[12px] text-muted-foreground">The whole voice-over is read again, so it stays one natural take.</p>+ </div>+ ) : (+ <textarea+ value={instruction}+ onChange={(e) => setInstruction(e.target.value)}+ maxLength={1000}+ rows={2}+ aria-label={part === "picture" ? "Describe what to change in the picture" : "Describe the new movement"}+ placeholder={part === "picture" ? "e.g. make it night, add a lighthouse on the cliff" : "e.g. slow zoom out, the flags wave in the wind"}+ className="w-full resize-none rounded-lg border bg-background px-2.5 py-2 text-[14px] outline-none [field-sizing:content] focus:border-primary placeholder:text-subtle-foreground"+ />+ )}+ <div className="flex flex-wrap items-center gap-2">+ <p className="min-w-0 flex-1 text-[12px] text-muted-foreground" aria-live="polite">+ {busy+ ? "Wait for the current render to finish to change scenes."+ : !draft+ ? part === "picture"+ ? "The picture is edited, then the scene is animated again."+ : part === "motion"+ ? "The picture is kept; the scene is animated again."+ : "Edit the lines above."+ : preview.isError+ ? (preview.error as Error).message+ : preview.data+ ? `Re-renders ${preview.data.labels.length} step${preview.data.labels.length === 1 ? "" : "s"} (${[...new Set(preview.data.labels.map((l) => l.replace(/^Scene \d+ · /, "")))].slice(0, 4).join(", ")}) · ${preview.data.demo ? "Demo · free" : ep.settings.engine === "open" ? "Free · your GPU" : preview.data.costUsd === null ? "price unknown" : `≈ ${usd(preview.data.costUsd)}`}`+ : "Pricing…"}+ </p>+ <Button variant="ghost" onClick={discard} disabled={!draft}>+ Discard+ </Button>+ <Button onClick={go} disabled={!draft || busy || apply.isPending || preview.isError} className="rounded-full">+ {apply.isPending ? <Loader2 className="animate-spin" /> : <Wand2 />} Apply+ </Button>+ </div>+ <p className="text-[11px] text-muted-foreground">Applying re-renders this change and publishes it when it's done; Undo brings the version before back. Spent credits aren't refunded.</p>+ </div>+ </section>+ );+}++function Timeline({ view, onOpen }: { view: View; onOpen: (g: Generation) => void }) {+ const ep = view.episode;+ const [selected, setSelected] = useState<string[]>([]);+ const [anchor, setAnchor] = useState<number | null>(null);+ const scenes = useMemo<SceneRow[]>(() => {+ const times = blockTimes(ep.script.blocks);+ return ep.script.blocks.map((b, i) => ({+ id: b.id,+ index: i,+ narration: b.narration,+ seconds: b.seconds,+ start: times[i].start,+ still: view.steps.find((s) => s.key === `still-${b.id}`),+ clips: view.steps.filter((s) => s.part === "clip" && s.key.startsWith(`clip-${b.id}-`)),+ }));+ }, [ep.script.blocks, view.steps]);+ const pick = (i: number, e: React.MouseEvent) => {+ const id = scenes[i].id;+ if (e.shiftKey && anchor !== null) {+ const [a, b] = [Math.min(anchor, i), Math.max(anchor, i)];+ setSelected(scenes.slice(a, b + 1).map((s) => s.id).slice(0, 12));+ return;+ }+ if (e.metaKey || e.ctrlKey) {+ setSelected((s) => (s.includes(id) ? s.filter((x) => x !== id) : [...s, id].slice(0, 12)));+ setAnchor(i);+ return;+ }+ setSelected((s) => (s.length === 1 && s[0] === id ? [] : [id]));+ setAnchor(i);+ };+ const chosen = scenes.filter((s) => selected.includes(s.id));+ return (+ <section aria-labelledby="timeline-title" className="space-y-3">+ <div className="flex flex-wrap items-baseline justify-between gap-2">+ <h2 id="timeline-title" className="font-heading text-[22px]">+ Timeline+ </h2>+ <p className="text-[12px] text-muted-foreground">Pick a scene to change it · Shift for a run, ⌘/Ctrl for several</p>+ </div>+ <div className="scrollbar-none -mx-3 flex gap-2 overflow-x-auto px-3 pb-1 sm:-mx-0 sm:px-0" role="group" aria-label="Scenes">+ {scenes.map((s) => (+ <SceneTile key={s.id} scene={s} selected={selected.includes(s.id)} onSelect={(e) => pick(s.index, e)} aspect={ep.settings.aspect} />+ ))}+ </div>+ <TailSteps steps={view.steps} onOpen={onOpen} />+ {chosen.length > 0 && <SceneEditor key={chosen.map((s) => s.id).join("|")} view={view} scenes={chosen} onClose={() => setSelected([])} onOpen={onOpen} />}+ </section>+ );+}++function Changes({ view }: { view: View }) {+ const changes = view.episode.plan?.changes ?? [];+ if (!changes.length) return null;+ const blocks = view.episode.script.blocks;+ return (+ <details className="group/changes rounded-2xl border px-4 py-3">+ <summary className="flex cursor-pointer list-none items-center gap-2 text-[13px] font-medium">+ <History className="size-4 text-muted-foreground" /> {changes.length} change{changes.length === 1 ? "" : "s"}+ </summary>+ <ul className="mt-2 space-y-1.5">+ {[...changes].reverse().map((c) => (+ <li key={c.at} className="flex flex-wrap items-baseline gap-x-2 text-[12px]">+ <span className="font-medium">+ Scene {c.blocks.map((b) => blocks.findIndex((x) => x.id === b) + 1 || "?").join(", ")} · {c.part}+ </span>+ <span className="min-w-0 truncate text-muted-foreground">{c.instruction}</span>+ <span className="ml-auto font-mono text-muted-foreground tabular-nums">+ {c.costUsd != null ? `≈ ${usd(c.costUsd)} · ` : ""}+ {timeAgo(c.at)}+ </span>+ </li>+ ))}+ </ul>+ </details>+ );+}++/** One episode (Faceless or Explainer): writing → review → render, then the film and its timeline editor. */+export function EpisodeView({ id, backHref, backLabel }: { id: string; backHref: string; backLabel: string }) {+ const router = useRouter();+ const { data: view, error, isLoading } = useEpisode(id);+ const action = useEpisodeAction(id);+ const update = useUpdateEpisode(id);+ const del = useDeleteEpisode();+ const [renaming, setRenaming] = useState(false);+ const [title, setTitle] = useState("");+ const [open, setOpen] = useState<Generation | null>(null);+ const [confirm, setConfirm] = useState(false);++ if (error && /not found/i.test((error as Error).message)) return <NotFoundState title="This episode doesn't exist">It may have been deleted. Its videos are still in your library.</NotFoundState>;+ const ep = view?.episode;+ const film = view?.final;+ const filmOut = film?.outputs.find((o) => o.kind === "video");+ const run = (a: "retry" | "rewrite" | "undo", ok?: string) => action.mutate(a, { onSuccess: () => ok && toast.success(ok), onError: (e) => toast.error((e as Error).message) });++ 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={backHref} className="inline-flex min-w-0 shrink items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground">+ <ArrowLeft className="size-4 shrink-0" />+ <span className="truncate">{view?.channel?.name ?? backLabel}</span>+ </Link>+ {ep && (+ <div className="ml-auto flex shrink-0 items-center gap-1">+ {filmOut && film && (+ <Button asChild variant="outline" size="sm">+ <a href={downloadHref(filmOut.url, downloadName(film, filmOut, 0))} download>+ <Download /> <span className="hidden sm:inline">Download</span>+ </a>+ </Button>+ )}+ <Button variant="ghost" size="icon" aria-pressed={ep.favorite} aria-label={ep.favorite ? "Unlike" : "Like"} onClick={() => update.mutate({ favorite: !ep.favorite })}>+ <Heart className={cn(ep.favorite && "fill-highlight text-highlight")} />+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon" aria-label="Episode actions">+ <MoreHorizontal />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onClick={() => {+ setTitle(ep.title);+ setRenaming(true);+ }}+ >+ <Pencil /> Rename+ </DropdownMenuItem>+ {ep.plan?.previous && ep.status !== "rendering" && (+ <DropdownMenuItem onClick={() => run("undo", "Back to the version before")}>+ <Undo2 /> Undo the last change+ </DropdownMenuItem>+ )}+ <DropdownMenuItem variant="destructive" onClick={() => setTimeout(() => setConfirm(true))}>+ <Trash2 /> Delete episode+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ )}+ </header>+ <main className="mx-auto w-full max-w-[1100px] min-w-0 flex-1 space-y-6 px-3 pb-16 sm:px-6">+ {isLoading || !view || !ep ? (+ <div className="space-y-4 pt-6">+ <Skeleton className="h-8 w-96 max-w-full" />+ <Skeleton className="aspect-video w-full rounded-2xl" />+ </div>+ ) : (+ <>+ <div className="pt-5">+ {renaming ? (+ <form+ className="flex items-center gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ update.mutate({ title });+ setRenaming(false);+ }}+ >+ <input+ autoFocus+ value={title}+ maxLength={120}+ onChange={(e) => setTitle(e.target.value)}+ onKeyDown={(e) => e.key === "Escape" && setRenaming(false)}+ aria-label="Episode title"+ className="h-11 min-w-0 flex-1 rounded-lg border bg-background px-3 font-heading text-[26px] outline-none focus:border-primary"+ />+ <Button type="submit" size="icon" aria-label="Save the title">+ <Check />+ </Button>+ </form>+ ) : (+ <h1 className="font-heading text-[30px] leading-tight text-balance">{ep.title}</h1>+ )}+ <p className="mt-1 text-[13px] text-muted-foreground">+ {getStyle(ep.settings.styleId).name} · {ep.settings.aspect === "9:16" ? "Vertical" : "Horizontal"} · {ep.settings.animation === "frames" ? "Frame by frame" : "Fully animated"}+ {ep.script.blocks.length > 0 && ` · ${formatLength(ep.script.blocks.reduce((n, b) => n + b.seconds, 0))}`}+ {view.spentUsd > 0 && <span className="font-mono"> · ≈ {usd(view.spentUsd)} spent</span>}+ </p>+ </div>++ {ep.status === "writing" ? (+ <div className="grid min-h-[40vh] place-items-center rounded-2xl border border-dashed p-8 text-center">+ <div>+ <Loader2 className="mx-auto size-6 animate-spin text-brand-text" />+ <p className="shimmer-text animate-shimmer-text mt-3 font-heading text-[24px]">{ep.script.source === "pasted" ? "Splitting your script into scenes…" : "Writing your script…"}</p>+ <p className="mt-1 text-[13px] text-muted-foreground">A few seconds with Claude, up to a minute with a local model.</p>+ </div>+ </div>+ ) : ep.status === "write-failed" ? (+ <div className="grid min-h-[30vh] place-items-center rounded-2xl border border-dashed p-8 text-center">+ <div className="max-w-md">+ <AlertTriangle className="mx-auto size-6 text-destructive" />+ <p className="mt-3 font-heading text-[24px]">Couldn't write the script</p>+ <p className="mt-1 text-[13px] text-muted-foreground">{ep.error}</p>+ <Button className="mt-4" onClick={() => run("rewrite")} disabled={action.isPending}>+ <RotateCcw /> Try again+ </Button>+ </div>+ </div>+ ) : ep.status === "review" ? (+ <ScriptReview view={view} />+ ) : (+ <>+ <Player view={view} onRetry={() => run("retry", "Retrying what failed")} retrying={action.isPending} />+ {ep.status === "failed" && film === null && view.previousFinal && (+ <p role="alert" className="flex items-center gap-2 text-[13px] text-destructive">+ <AlertTriangle className="size-4" /> {ep.error}+ <Button size="sm" variant="outline" onClick={() => run("retry", "Retrying what failed")}>+ <RotateCcw /> Retry+ </Button>+ </p>+ )}+ <Timeline view={view} onOpen={setOpen} />+ <Changes view={view} />+ </>+ )}+ </>+ )}+ </main>+ {open && <Viewer generation={open} index={0} onClose={() => setOpen(null)} />}+ <AlertDialog open={confirm} onOpenChange={setConfirm}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete this episode?</AlertDialogTitle>+ <AlertDialogDescription>It's removed from {view?.channel ? "the channel" : "your explainers"}. Its pictures, clips and video stay in your Library.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() =>+ del.mutate(id, {+ onSuccess: () => {+ toast("Episode deleted");+ router.push(backHref);+ },+ onError: (e) => toast.error((e as Error).message),+ })+ }+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}diff --git a/src/components/faceless/episode-wizard.tsx b/src/components/faceless/episode-wizard.tsxnew file mode 100644index 00000000..777eee84--- /dev/null+++ b/src/components/faceless/episode-wizard.tsx@@ -0,0 +1,352 @@+"use client";++import { ArrowLeft, ArrowRight, Check, FileText, Loader2, RefreshCw, Sparkles, Upload } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useEffect, useId, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import { NotFoundState } from "@/components/empty-state";+import { EngineSwitch } from "@/components/studio/engine-switch";+import { useEngine } from "@/lib/api";+import {+ defaultVoice,+ FACELESS_STYLE_IDS,+ genreInfo,+ MAX_SCRIPT,+ MAX_TOPIC,+ splitScript,+ wordCount,+ type EpisodeSettings,+ type PickerData,+ type TopicIdea,+} from "@/lib/catalog/faceless";+import { cn } from "@/lib/utils";+import { ChannelAvatar } from "./cards";+import { EstimateLine, Section, Segmented } from "./controls";+import { pendingScriptKey } from "./faceless-home";+import { suggestTopics, useChannel, useCreateEpisode, useEstimate } from "./hooks";+import { EpisodeSettingsForm } from "./settings-form";++function Steps({ step }: { step: 1 | 2 }) {+ const items = ["Topic", "Video settings", "Review the script"];+ return (+ <ol className="flex items-center gap-2 text-[12px] font-medium" aria-label="Steps">+ {items.map((label, i) => {+ const n = i + 1;+ const state = n < step ? "done" : n === step ? "current" : "next";+ return (+ <li key={label} className="flex min-w-0 items-center gap-2" aria-current={state === "current" ? "step" : undefined}>+ {i > 0 && <span className="h-px w-4 bg-border sm:w-8" aria-hidden />}+ <span+ className={cn(+ "grid size-5 shrink-0 place-items-center rounded-full text-[11px]",+ state === "done" ? "bg-primary text-primary-foreground" : state === "current" ? "bg-brand-faint text-brand-text" : "bg-muted text-muted-foreground",+ )}+ >+ {state === "done" ? <Check className="size-3" /> : n}+ </span>+ <span className={cn("truncate", state === "next" ? "hidden text-muted-foreground sm:inline" : state === "done" ? "hidden sm:inline" : "")}>{label}</span>+ </li>+ );+ })}+ </ol>+ );+}++/** New episode: a topic (suggested or your own), the video settings and the script source; then the script is written for review. */+export function EpisodeWizard({ channelId, picker }: { channelId: string; picker: PickerData }) {+ const router = useRouter();+ const { data, error } = useChannel(channelId);+ const [engine, setEngine] = useEngine();+ const create = useCreateEpisode();+ const [step, setStep] = useState<1 | 2>(1);+ const [topics, setTopics] = useState<TopicIdea[] | null>(null);+ const [offline, setOffline] = useState(false);+ const [round, setRound] = useState(0);+ const [loadingTopics, setLoadingTopics] = useState(false);+ const [picked, setPicked] = useState<string | null>(null);+ const [own, setOwn] = useState("");+ const [scriptMode, setScriptMode] = useState<"ai" | "pasted">("ai");+ const [script, setScript] = useState("");+ const [draft, setDraft] = useState<EpisodeSettings | null>(null);+ const file = useRef<HTMLInputElement>(null);+ const ownId = useId();+ const scriptId = useId();+ const channel = data?.channel;+ const genre = genreInfo(channel?.genre);++ // Start from the channel's saved look and sound (once the channel has loaded), and the script uploaded with it.+ const [startedFor, setStartedFor] = useState<string | null>(null);+ if (channel && startedFor !== channel.id) {+ setStartedFor(channel.id);+ const s = channel.settings;+ setDraft({ ...s, styleRefs: s.styleRefs ?? [], elements: [], engine });+ let pending: string | null = null;+ try {+ pending = sessionStorage.getItem(pendingScriptKey(channel.id));+ } catch {}+ if (pending) {+ setScript(pending);+ setScriptMode("pasted");+ }+ }+ useEffect(() => {+ if (!startedFor) return;+ try {+ sessionStorage.removeItem(pendingScriptKey(startedFor));+ } catch {}+ }, [startedFor]);++ // The engine follows the header switch; a premade voice doesn't exist on the open engine.+ const settings = useMemo<EpisodeSettings | null>(() => {+ if (!draft) return null;+ const voice = engine === "open" && draft.voice?.kind === "preset" ? null : engine === "cloud" && !draft.voice ? defaultVoice("cloud", genre) : draft.voice;+ return { ...draft, engine, voice, videoModel: draft.engine === engine ? draft.videoModel : undefined, resolution: draft.engine === engine ? draft.resolution : undefined };+ }, [draft, engine, genre]);++ const loadTopics = async (r: number, avoid: string[] = []) => {+ setLoadingTopics(true);+ try {+ const res = await suggestTopics({ channelId, engine, round: r, avoid });+ setTopics(res.topics);+ setOffline(res.offline);+ setPicked(null);+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setLoadingTopics(false);+ }+ };+ const asked = useRef(false);+ useEffect(() => {+ if (!channel || asked.current) return;+ asked.current = true;+ void loadTopics(0);+ // Once, when the channel arrives.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [channel]);++ const topic = own.trim() || topics?.find((t) => t.title === picked)?.title || "";+ const pastedBlocks = scriptMode === "pasted" && script.trim() ? splitScript(script) : undefined;+ const estimate = useEstimate(settings && step === 2 ? { kind: "faceless", settings, genre: genre.id, ...(pastedBlocks && { blocks: pastedBlocks }) } : null);++ if (error && /not found/i.test((error as Error).message)) return <NotFoundState title="This channel doesn't exist" />;++ const next = () => {+ if (!topic && !(scriptMode === "pasted" && script.trim())) return void toast("Pick a topic, or write your own", { id: "faceless-blocker" });+ setStep(2);+ window.scrollTo({ top: 0, behavior: "smooth" });+ };++ const write = () => {+ if (!settings) return;+ if (scriptMode === "pasted" && !script.trim()) return void toast("Paste your script, or let it be written for you", { id: "faceless-blocker" });+ if (settings.engine === "open" && settings.voice?.kind !== "sample" && estimate.data?.error) return void toast(estimate.data.error, { id: "faceless-blocker" });+ create.mutate(+ { channelId, topic: topic || script.trim().slice(0, 120), script: scriptMode === "pasted" ? script : undefined, settings },+ {+ onSuccess: (ep) => router.push(`/faceless/${channelId}/${ep.id}`),+ onError: (e) => toast.error((e as Error).message),+ },+ );+ };++ 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={`/faceless/${channelId}`} className="inline-flex min-w-0 items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground">+ <ArrowLeft className="size-4 shrink-0" />+ <span className="truncate">{channel?.name ?? "Channel"}</span>+ </Link>+ <div className="ml-auto">+ <EngineSwitch value={engine} onChange={setEngine} />+ </div>+ </header>+ <main className="mx-auto w-full max-w-[920px] min-w-0 flex-1 px-3 pb-32 sm:px-6">+ <div className="flex flex-wrap items-center justify-between gap-3 pt-6">+ <Steps step={step} />+ </div>+ {!channel || !settings ? (+ <div className="space-y-3 pt-8">+ <Skeleton className="h-9 w-80 max-w-full" />+ <div className="grid gap-3 sm:grid-cols-2">+ {Array.from({ length: 4 }, (_, i) => (+ <Skeleton key={i} className="h-24 rounded-xl" />+ ))}+ </div>+ </div>+ ) : step === 1 ? (+ <div className="space-y-6 pt-6">+ <div className="flex items-center gap-3">+ <ChannelAvatar channel={channel} />+ <div className="min-w-0">+ <h1 className="font-heading text-[30px] leading-tight text-balance">{data.episodes.length ? "Choose the next episode's topic" : "Choose topic of the first episode"}</h1>+ <p className="text-[13px] text-muted-foreground">+ {genre.label} · {genre.hint}+ </p>+ </div>+ </div>++ <section aria-label="Topic suggestions" className="space-y-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className={cn("text-[13px] text-muted-foreground", loadingTopics && "shimmer-text animate-shimmer-text")}>{loadingTopics ? "Writing topic suggestions…" : offline ? "Suggestions written offline — connect Claude or Ollama in Settings for fresher ones." : "Tick one, or write your own below."}</p>+ <Button+ variant="outline"+ size="sm"+ disabled={loadingTopics}+ onClick={() => {+ const r = round + 1;+ setRound(r);+ void loadTopics(r, topics?.map((t) => t.title));+ }}+ >+ <RefreshCw className={cn(loadingTopics && "animate-spin")} /> Generate new topic suggestions+ </Button>+ </div>+ <div role="radiogroup" aria-label="Suggested topics" className="grid gap-2.5 sm:grid-cols-2">+ {loadingTopics && !topics+ ? Array.from({ length: 4 }, (_, i) => <Skeleton key={i} className="h-[76px] rounded-xl" />)+ : topics?.map((t) => {+ const on = picked === t.title && !own.trim();+ return (+ <button+ key={t.title}+ type="button"+ role="radio"+ aria-checked={on}+ onClick={() => {+ setPicked(t.title);+ setOwn("");+ }}+ className={cn(+ "flex min-w-0 items-start gap-3 rounded-xl border p-3 text-left transition-[border-color,box-shadow] outline-none focus-visible:ring-2 focus-visible:ring-ring",+ on ? "border-primary ring-2 ring-brand-faint" : "hover:border-border-strong",+ loadingTopics && "opacity-60",+ )}+ >+ <span className={cn("mt-0.5 grid size-5 shrink-0 place-items-center rounded-full border", on ? "border-primary bg-primary text-primary-foreground" : "border-border-strong")}>{on && <Check className="size-3" />}</span>+ <span className="min-w-0">+ <span className="block text-[14px] leading-snug font-medium">{t.title}</span>+ {t.hook && <span className="mt-0.5 block text-[12px] leading-snug text-muted-foreground">{t.hook}</span>}+ </span>+ </button>+ );+ })}+ </div>+ </section>++ <section className="space-y-2">+ <label htmlFor={ownId} className="text-[13px] font-medium">+ Or write your own+ </label>+ <div className="rounded-2xl border bg-background p-3 transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">+ <textarea+ id={ownId}+ value={own}+ maxLength={MAX_TOPIC}+ onChange={(e) => setOwn(e.target.value)}+ rows={3}+ placeholder="What is the episode about? e.g. “How Roman roads were built, and why some still stand”"+ className="w-full resize-none bg-transparent text-body outline-none [field-sizing:content] placeholder:text-subtle-foreground"+ />+ <p className="text-right font-mono text-[11px] text-muted-foreground tabular-nums">+ {own.length.toLocaleString()} / {MAX_TOPIC.toLocaleString()}+ </p>+ </div>+ </section>+ </div>+ ) : (+ <div className="space-y-8 pt-6">+ <div>+ <h1 className="font-heading text-[30px] leading-tight text-balance">Video settings</h1>+ <p className="mt-1 line-clamp-2 text-[14px] text-muted-foreground">{topic || "Your script"}</p>+ </div>++ <Section title="Script">+ <Segmented+ label="Script"+ value={scriptMode}+ options={[+ { value: "ai", label: "Write it for me" },+ { value: "pasted", label: "Use my script" },+ ]}+ onChange={setScriptMode}+ />+ {scriptMode === "pasted" && (+ <div className="rounded-2xl border bg-background p-3 transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">+ <label htmlFor={scriptId} className="sr-only">+ Your script+ </label>+ <textarea+ id={scriptId}+ value={script}+ maxLength={MAX_SCRIPT}+ onChange={(e) => setScript(e.target.value)}+ rows={8}+ placeholder="Paste the narration. It's split into scenes of about 10 seconds; you can edit them before rendering."+ className="max-h-[50vh] w-full resize-none overflow-y-auto bg-transparent text-[14px] leading-relaxed outline-none [field-sizing:content] placeholder:text-subtle-foreground"+ />+ <div className="flex flex-wrap items-center justify-between gap-2 pt-1">+ <button type="button" onClick={() => file.current?.click()} className="inline-flex h-7 items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent">+ <Upload className="size-3.5" /> Upload .txt+ </button>+ <input+ ref={file}+ type="file"+ accept=".txt,.md,text/plain,text/markdown"+ hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ const text = (await f.text()).trim();+ if (text.length > MAX_SCRIPT) return void toast.error("That script is too long to narrate. Shorten it and try again.");+ setScript(text);+ }}+ />+ <span className="font-mono text-[11px] text-muted-foreground tabular-nums">+ {wordCount(script)} words · {script.length.toLocaleString()} / {MAX_SCRIPT.toLocaleString()}+ </span>+ </div>+ </div>+ )}+ {scriptMode === "ai" && <p className="text-[12px] text-muted-foreground">The script is written for this channel, paced for the length you pick. You review every scene before anything renders.</p>}+ </Section>++ <EpisodeSettingsForm kind="faceless" value={settings} onChange={(p) => setDraft((d) => ({ ...d!, ...p, engine }))} picker={picker} styleIds={FACELESS_STYLE_IDS} />+ </div>+ )}+ </main>++ {channel && settings && (+ <div className="sticky bottom-0 z-20 border-t bg-background/90 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur">+ <div className="mx-auto flex w-full max-w-[920px] min-w-0 flex-wrap items-center gap-3 px-3 pt-3 sm:px-6">+ {step === 2 ? (+ <>+ <Button variant="ghost" onClick={() => setStep(1)}>+ <ArrowLeft /> Topic+ </Button>+ <EstimateLine data={estimate.data} loading={estimate.isFetching} engine={engine} className="min-w-0 flex-1" />+ <Button onClick={write} disabled={create.isPending} className="rounded-full">+ {create.isPending ? <Loader2 className="animate-spin" /> : scriptMode === "pasted" ? <FileText /> : <Sparkles />}+ {scriptMode === "pasted" ? "Split into scenes" : "Write the script"}+ </Button>+ </>+ ) : (+ <>+ <p className="min-w-0 flex-1 truncate text-[13px] text-muted-foreground">{topic ? `Topic: ${topic}` : "Pick a topic to continue"}</p>+ <Button onClick={next} className="rounded-full">+ Next <ArrowRight />+ </Button>+ </>+ )}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/src/components/faceless/faceless-home.tsx b/src/components/faceless/faceless-home.tsxnew file mode 100644index 00000000..16441a5f--- /dev/null+++ b/src/components/faceless/faceless-home.tsx@@ -0,0 +1,231 @@+"use client";++import { ArrowRight, FileText, Link2, ListChecks, Loader2, Sparkles, Upload, Wand2, X } from "lucide-react";+import { useRouter } from "next/navigation";+import { useId, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import { EngineSwitch } from "@/components/studio/engine-switch";+import { radioKeys, radioTab } from "@/components/studio/radio-keys";+import { useEngine } from "@/lib/api";+import { CHANNEL_IDEAS, GENRES, MAX_IDEA, MAX_SCRIPT, wordCount, youtubeKind, YOUTUBE_ERROR, type FacelessGenre } from "@/lib/catalog/faceless";+import { cn } from "@/lib/utils";+import { ChannelCard, EmptyChannels } from "./cards";+import { useChannels, useCreateChannel } from "./hooks";++/** The pasted or uploaded script travels to the new channel's first episode in this tab. */+export const pendingScriptKey = (channelId: string) => `fuobe.faceless.script.${channelId}`;++const STEPS = [+ { icon: Sparkles, title: "Describe the channel", text: "A genre and an idea. The name and the look come with it." },+ { icon: ListChecks, title: "Pick a topic", text: "From suggestions, or your own — then the length, style and narrator." },+ { icon: Wand2, title: "Review and render", text: "Edit the script scene by scene, render, then fix any scene in the timeline." },+];++export function FacelessHome() {+ const router = useRouter();+ const [engine, setEngine] = useEngine();+ const [genre, setGenre] = useState<FacelessGenre>("education");+ const [idea, setIdea] = useState("");+ const [reference, setReference] = useState("");+ const [refError, setRefError] = useState("");+ const [script, setScript] = useState<{ name: string; text: string } | null>(null);+ const file = useRef<HTMLInputElement>(null);+ const create = useCreateChannel();+ const channels = useChannels();+ const ideaId = useId();+ const refId = useId();+ const g = GENRES.find((x) => x.id === genre)!;++ const checkRef = (v: string) => {+ const bad = v.trim() && !youtubeKind(v);+ setRefError(bad ? YOUTUBE_ERROR : "");+ return !bad;+ };++ const submit = () => {+ if (!idea.trim()) return void toast("Describe the channel first", { id: "faceless-blocker" });+ if (!checkRef(reference)) return;+ create.mutate(+ { idea: idea.trim(), genre, engine, ...(reference.trim() && { reference: reference.trim() }) },+ {+ onSuccess: (c) => {+ if (script) {+ try {+ sessionStorage.setItem(pendingScriptKey(c.id), script.text);+ } catch {}+ }+ router.push(`/faceless/${c.id}/new`);+ },+ onError: (e) => toast.error((e as Error).message),+ },+ );+ };++ 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">Faceless Studio</h1>+ <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 space-y-12 px-3 pb-16 sm:px-6">+ <div className="mx-auto max-w-[760px] pt-[6vh] text-center sm:pt-[9vh]">+ <h2 className="font-heading text-display text-balance">Create your Faceless channel</h2>+ <p className="mx-auto mt-2 max-w-[560px] text-body text-muted-foreground">A narrated, illustrated show — scripts, voice-over, animation, music and subtitles — with the same look in every episode.</p>++ <div className="mt-7 rounded-[20px] border bg-background p-3 text-left shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer sm:p-4">+ <div role="radiogroup" aria-label="Genre" onKeyDown={radioKeys} className="scrollbar-none flex gap-1 overflow-x-auto">+ {GENRES.map((x) => (+ <button+ key={x.id}+ type="button"+ role="radio"+ aria-checked={genre === x.id}+ tabIndex={radioTab(genre === x.id)}+ onClick={() => setGenre(x.id)}+ className={cn(+ "h-8 shrink-0 rounded-full px-3 text-[13px] font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",+ genre === x.id ? "bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent hover:text-foreground",+ )}+ >+ {x.label}+ </button>+ ))}+ </div>+ <p className="px-1 pt-1.5 text-[12px] text-muted-foreground">{g.hint}</p>+ <label htmlFor={ideaId} className="sr-only">+ Channel idea+ </label>+ <textarea+ id={ideaId}+ value={idea}+ maxLength={MAX_IDEA}+ onChange={(e) => setIdea(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault();+ submit();+ }+ }}+ rows={2}+ placeholder="Channel idea, e.g. “Channel about survival in the wild”"+ className="mt-2 w-full resize-none bg-transparent px-1 text-body leading-relaxed outline-none [field-sizing:content] placeholder:text-subtle-foreground"+ />+ <div className="scrollbar-none -mx-1 flex gap-1.5 overflow-x-auto px-1 pb-1">+ {CHANNEL_IDEAS.map((ex) => (+ <button key={ex} type="button" onClick={() => setIdea(ex)} className="h-7 shrink-0 rounded-full bg-secondary px-2.5 text-[12px] text-secondary-foreground hover:bg-accent">+ {ex.replace(/^Channel (about|with) /, "")}+ </button>+ ))}+ </div>+ <div className="mt-2 flex flex-wrap items-center gap-2 border-t pt-3">+ <div className="flex h-8 min-w-0 flex-1 basis-56 items-center gap-1.5 rounded-full bg-secondary px-3">+ <Link2 className="size-3.5 shrink-0 text-muted-foreground" />+ <label htmlFor={refId} className="sr-only">+ Reference (YouTube link)+ </label>+ <input+ id={refId}+ value={reference}+ onChange={(e) => {+ setReference(e.target.value);+ if (refError) checkRef(e.target.value);+ }}+ onBlur={() => checkRef(reference)}+ placeholder="Reference: a YouTube channel, video or playlist"+ aria-invalid={!!refError}+ aria-describedby={refError ? `${refId}-err` : undefined}+ className="h-full min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-subtle-foreground"+ />+ </div>+ {script ? (+ <span className="inline-flex h-8 max-w-full items-center gap-1.5 rounded-full bg-brand-faint pr-1 pl-3 text-[13px] font-medium text-brand-text">+ <FileText className="size-3.5 shrink-0" />+ <span className="truncate">+ {script.name} · {wordCount(script.text)} words+ </span>+ <button type="button" onClick={() => setScript(null)} className="grid size-6 place-items-center rounded-full hover:bg-brand-faint-hover" aria-label="Remove the script">+ <X className="size-3.5" />+ </button>+ </span>+ ) : (+ <button type="button" onClick={() => file.current?.click()} className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent">+ <Upload className="size-3.5" /> Upload script+ </button>+ )}+ <input+ ref={file}+ type="file"+ accept=".txt,.md,text/plain,text/markdown"+ hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ const text = (await f.text()).trim();+ if (text.length > MAX_SCRIPT) return void toast.error("That script is too long to narrate. Shorten it and try again.");+ if (!text) return void toast.error("That file is empty");+ setScript({ name: f.name, text });+ }}+ />+ <Button onClick={submit} disabled={create.isPending} className="ml-auto h-9 rounded-full px-4">+ {create.isPending ? <Loader2 className="animate-spin" /> : <ArrowRight />}+ {create.isPending ? "Creating…" : "Next"}+ </Button>+ </div>+ {refError && (+ <p id={`${refId}-err`} role="alert" className="px-1 pt-2 text-[12px] text-destructive">+ {refError}+ </p>+ )}+ </div>+ </div>++ <section aria-labelledby="channels-title" className="space-y-4">+ <h2 id="channels-title" className="font-heading text-[24px]">+ My channels+ </h2>+ {channels.isLoading ? (+ <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-4">+ {Array.from({ length: 4 }, (_, i) => (+ <div key={i}>+ <Skeleton className="aspect-video rounded-xl" />+ <Skeleton className="mt-3 h-4 w-2/3" />+ </div>+ ))}+ </div>+ ) : channels.data?.length ? (+ <div className="grid grid-cols-1 gap-x-5 gap-y-7 sm:grid-cols-2 lg:grid-cols-4">+ {channels.data.map((c) => (+ <ChannelCard key={c.id} channel={c} />+ ))}+ </div>+ ) : (+ <EmptyChannels />+ )}+ </section>++ <section aria-label="How it works" className="grid gap-3 sm:grid-cols-3">+ {STEPS.map((s, i) => (+ <div key={s.title} className="flex gap-3 rounded-2xl bg-muted/50 p-4">+ <span className="grid size-9 shrink-0 place-items-center rounded-xl bg-background text-brand-text shadow-soft">+ <s.icon className="size-4" />+ </span>+ <div className="min-w-0">+ <p className="text-[13px] font-medium">+ {i + 1}. {s.title}+ </p>+ <p className="mt-0.5 text-[12px] leading-snug text-muted-foreground">{s.text}</p>+ </div>+ </div>+ ))}+ </section>+ </main>+ </div>+ );+}diff --git a/src/components/faceless/hooks.ts b/src/components/faceless/hooks.tsnew file mode 100644index 00000000..1d28c059--- /dev/null+++ b/src/components/faceless/hooks.ts@@ -0,0 +1,251 @@+"use client";++import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useEffect, useRef, useState } from "react";+import { useGenerationEvents } from "@/lib/api";+import type {+ ChangePart,+ ChangePreview,+ ChannelSettings,+ EpisodeCard,+ EpisodeSettings,+ EpisodeView,+ EstimateResult,+ ExplainerSource,+ FacelessChannel,+ FacelessEpisode,+ FacelessGenre,+ ScriptBlock,+ TopicIdea,+} from "@/lib/catalog/faceless";+import type { Engine, Generation } from "@/lib/catalog/types";++/** React Query hooks for /api/faceless/** and /api/explainer/** (kept next to the views that use 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;+}++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) }));++const inFlight = (s: string) => s === "writing" || s === "rendering";++// ---------------------------------------------------------------------------+// Channels++export function useChannels() {+ return useQuery({+ queryKey: ["faceless", "channels"],+ queryFn: async () => (await json<{ items: FacelessChannel[] }>(await fetch("/api/faceless/channels"))).items,+ refetchInterval: (q) => (q.state.data?.length ? 15_000 : false),+ });+}++export function useChannel(id: string) {+ return useQuery({+ queryKey: ["faceless", "channel", id],+ queryFn: async () => json<{ channel: FacelessChannel; episodes: EpisodeCard[] }>(await fetch(`/api/faceless/channels/${id}`)),+ retry: (n, e) => !/not found/i.test((e as Error).message) && n < 1,+ refetchInterval: (q) => (q.state.data?.episodes.some((e) => inFlight(e.status)) ? 3000 : false),+ });+}++export function useCreateChannel() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (b: { idea: string; genre: FacelessGenre; engine: Engine; reference?: string }) => send<FacelessChannel>("/api/faceless/channels", "POST", b),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["faceless", "channels"] }),+ });+}++export function useUpdateChannel(id: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (b: { name?: string; idea?: string; genre?: FacelessGenre; avatarUrl?: string | null; reference?: string | null; settings?: Partial<ChannelSettings> }) =>+ send<FacelessChannel>(`/api/faceless/channels/${id}`, "PATCH", b),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["faceless"] }),+ });+}++export function useDeleteChannel() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => send<void>(`/api/faceless/channels/${id}`, "DELETE"),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["faceless", "channels"] }),+ });+}++export const makeAvatar = (id: string) => send<Generation>(`/api/faceless/channels/${id}/avatar`, "POST");++export const suggestTopics = (b: { channelId?: string; idea?: string; genre?: FacelessGenre; engine: Engine; avoid?: string[]; round?: number }) =>+ send<{ topics: TopicIdea[]; offline: boolean }>("/api/faceless/topics", "POST", b);++// ---------------------------------------------------------------------------+// Episodes++export function useCreateEpisode() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (b: { channelId: string; topic: string; script?: string; settings: EpisodeSettings }) => send<FacelessEpisode>("/api/faceless/episodes", "POST", b),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["faceless"] }),+ });+}++/**+ * One episode with its steps. It follows the shared live stream (a step's generation changing refetches+ * the view) and polls slowly as a safety net while something is writing or rendering.+ */+export function useEpisode(id: string) {+ const qc = useQueryClient();+ const ids = useRef<Set<string>>(new Set());+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const connected = useGenerationEvents((ev) => {+ if (!ids.current.has(ev.type === "deleted" ? ev.id : ev.generation.id)) return;+ // Several steps change at once: refetch once per burst.+ if (timer.current) return;+ timer.current = setTimeout(() => {+ timer.current = null;+ void qc.invalidateQueries({ queryKey: ["faceless", "episode", id] });+ }, 400);+ });+ useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);+ const q = useQuery({+ queryKey: ["faceless", "episode", id],+ queryFn: async () => json<EpisodeView>(await fetch(`/api/faceless/episodes/${id}`)),+ retry: (n, e) => !/not found/i.test((e as Error).message) && n < 1,+ refetchInterval: (q) => {+ const s = q.state.data?.episode.status;+ if (!s || !inFlight(s)) return false;+ return s === "writing" ? 1500 : connected ? 8000 : 2000;+ },+ });+ useEffect(() => {+ ids.current = new Set(Object.values(q.data?.episode.plan?.ids ?? {}));+ }, [q.data]);+ return q;+}++function useEpisodeMutation<B>(id: string, run: (b: B) => Promise<EpisodeView>) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: run,+ onSuccess: (v) => {+ qc.setQueryData(["faceless", "episode", id], v);+ void qc.invalidateQueries({ queryKey: ["faceless", "channel"] });+ void qc.invalidateQueries({ queryKey: ["faceless", "explainers"] });+ },+ });+}++export function useUpdateEpisode(id: string) {+ return useEpisodeMutation(id, (b: { title?: string; favorite?: boolean; blocks?: Partial<ScriptBlock>[]; settings?: Partial<EpisodeSettings> }) =>+ send<EpisodeView>(`/api/faceless/episodes/${id}`, "PATCH", b),+ );+}++export function useEpisodeAction(id: string) {+ return useEpisodeMutation(id, (action: "render" | "retry" | "rewrite" | "undo") => send<EpisodeView>(`/api/faceless/episodes/${id}/${action}`, "POST"));+}++export interface ChangeDraft {+ blocks: string[];+ part: ChangePart;+ instruction?: string;+ narration?: string[];+}++export function useApplyChange(id: string) {+ return useEpisodeMutation(id, (c: ChangeDraft) => send<EpisodeView>(`/api/faceless/episodes/${id}/change`, "POST", { ...c, apply: true }));+}++export function useDeleteEpisode() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => send<void>(`/api/faceless/episodes/${id}`, "DELETE"),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["faceless"] }),+ });+}++/** What a change would re-run and cost, recomputed (debounced) as the draft changes. */+export function useChangePreview(id: string, draft: ChangeDraft | null) {+ const key = draft && JSON.stringify(draft);+ const debounced = useDebounced(key, 450);+ return useQuery({+ queryKey: ["faceless", "change", id, debounced],+ enabled: !!debounced,+ queryFn: async () => send<ChangePreview>(`/api/faceless/episodes/${id}/change`, "POST", JSON.parse(debounced!)),+ placeholderData: keepPreviousData,+ retry: false,+ staleTime: 30_000,+ });+}++// ---------------------------------------------------------------------------+// Estimates, voices, Explainer++export function useDebounced<T>(value: T, ms: number): T {+ const [v, setV] = useState(value);+ useEffect(() => {+ const t = setTimeout(() => setV(value), ms);+ return () => clearTimeout(t);+ }, [value, ms]);+ return v;+}++export function useEstimate(input: { kind: "faceless" | "explainer"; settings: EpisodeSettings; blocks?: ScriptBlock[]; genre?: FacelessGenre } | null) {+ const key = input && JSON.stringify(input);+ const debounced = useDebounced(key, 350);+ return useQuery({+ queryKey: ["faceless", "estimate", debounced],+ enabled: !!debounced,+ queryFn: async () => send<EstimateResult>("/api/faceless/estimate", "POST", JSON.parse(debounced!)),+ placeholderData: keepPreviousData,+ staleTime: 20_000,+ retry: false,+ });+}++export const voicePreview = (id: string) => send<Generation>("/api/faceless/voices/preview", "POST", { id });+export const readGeneration = async (id: string) => json<Generation>(await fetch(`/api/generations/${id}`));++/** Follow one generation until it finishes (voice previews, avatars). */+export async function waitFor(id: string, signal?: AbortSignal): Promise<Generation> {+ for (;;) {+ const g = await readGeneration(id);+ if (g.status === "succeeded" || g.status === "failed" || g.status === "canceled") return g;+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");+ await new Promise((r) => setTimeout(r, 900));+ }+}++export function useExplainers(o: { q: string; liked: boolean }) {+ const q = useDebounced(o.q, 250);+ return useQuery({+ queryKey: ["faceless", "explainers", q, o.liked],+ queryFn: async () => (await json<{ items: EpisodeCard[] }>(await fetch(`/api/explainer?${new URLSearchParams({ ...(q && { q }), ...(o.liked && { liked: "1" }) })}`))).items,+ placeholderData: keepPreviousData,+ refetchInterval: (query) => (query.state.data?.some((e) => inFlight(e.status)) ? 3000 : false),+ });+}++export function useCreateExplainer() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (b: { prompt: string; sources: ExplainerSource[]; settings: EpisodeSettings; review?: boolean }) => send<FacelessEpisode>("/api/explainer", "POST", b),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["faceless", "explainers"] }),+ });+}++export const readLink = (url: string, engine: Engine) => send<Extract<ExplainerSource, { kind: "link" }>>("/api/explainer/link", "POST", { url, engine });++export function useLikeEpisode() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (b: { id: string; favorite: boolean }) => send<EpisodeView>(`/api/faceless/episodes/${b.id}`, "PATCH", { favorite: b.favorite }),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["faceless"] }),+ });+}diff --git a/src/components/faceless/narrator.tsx b/src/components/faceless/narrator.tsxnew file mode 100644index 00000000..6cad5d8a--- /dev/null+++ b/src/components/faceless/narrator.tsx@@ -0,0 +1,226 @@+"use client";++import { AudioLines, Check, Loader2, Mic, Pause, Play, Upload } from "lucide-react";+import Link from "next/link";+import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { fileToSlot } from "@/components/studio/media-slot";+import { VoiceRecorder } from "@/components/studio/voice-recorder";+import { useElements } from "@/lib/api";+import type { NarratorVoice, PickerData } from "@/lib/catalog/faceless";+import type { Engine } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";+import { voicePreview, waitFor } from "./hooks";++/** One shared player, so starting a sample stops the one before. */+const player = { audio: null as HTMLAudioElement | null, owner: "" };++function usePlayer() {+ const [playing, setPlaying] = useState("");+ const [loading, setLoading] = useState("");+ const cache = useRef(new Map<string, string>());+ useEffect(+ () => () => {+ player.audio?.pause();+ },+ [],+ );+ const play = (key: string, url: string) => {+ player.audio?.pause();+ const a = new Audio(url);+ player.audio = a;+ player.owner = key;+ a.onended = () => setPlaying((p) => (p === key ? "" : p));+ a.onpause = () => setPlaying((p) => (p === key ? "" : p));+ void a.play().then(+ () => setPlaying(key),+ () => toast.error("Couldn't play that sample"),+ );+ };+ const toggle = async (key: string, load: () => Promise<string | null>) => {+ if (playing === key) return void player.audio?.pause();+ const known = cache.current.get(key);+ if (known) return play(key, known);+ setLoading(key);+ try {+ const url = await load();+ if (!url) return;+ cache.current.set(key, url);+ play(key, url);+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setLoading((l) => (l === key ? "" : l));+ }+ };+ return { playing, loading, toggle };+}++/** A premade voice's sample: one short speech generation the first time, the same file after that. */+async function presetSample(id: string): Promise<string | null> {+ const g = await voicePreview(id);+ const done = g.status === "succeeded" ? g : await waitFor(g.id);+ if (done.status !== "succeeded") throw new Error(done.error ?? "Couldn't make a sample of that voice");+ return done.outputs.find((o) => o.kind === "audio")?.url ?? null;+}++function PlayButton({ active, loading, onClick, label }: { active: boolean; loading: boolean; onClick: () => void; label: string }) {+ return (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onClick();+ }}+ aria-label={active ? `Pause ${label}` : `Play a sample of ${label}`}+ className="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ >+ {loading ? <Loader2 className="size-3.5 animate-spin" /> : active ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}+ </button>+ );+}++const sameVoice = (a: NarratorVoice | null, b: NarratorVoice) => !!a && a.kind === b.kind && (a.kind === "preset" ? a.id === (b as { id: string }).id : a.url === (b as { url: string }).url);++/**+ * Pick the narrator: a premade voice (cloud, each with a sample to play) or your own voice to clone —+ * a saved voice element, a recording or an upload (any engine; the only choice for open-source narration).+ */+export function NarratorList({ engine, voices, value, onChange }: { engine: Engine; voices: PickerData["voices"]; value: NarratorVoice | null; onChange: (v: NarratorVoice) => void }) {+ const saved = (useElements().data ?? []).filter((e) => e.kind === "voice" && e.references[0]);+ const file = useRef<HTMLInputElement>(null);+ const [q, setQ] = useState("");+ const [uploading, setUploading] = useState(false);+ const p = usePlayer();+ const list = voices.filter((v) => !q || `${v.name} ${v.hint ?? ""}`.toLowerCase().includes(q.toLowerCase()));+ const own = value?.kind === "sample" && !saved.some((e) => e.references[0] === value.url) ? value : null;++ const row = (key: string, v: NarratorVoice, name: string, hint: string | undefined, sample: () => Promise<string | null>) => {+ const active = sameVoice(value, v);+ return (+ <div key={key} className={cn("flex items-center gap-1.5 rounded-lg pl-1.5 transition-colors hover:bg-accent", active && "bg-brand-faint hover:bg-brand-faint-hover")}>+ <PlayButton active={p.playing === key} loading={p.loading === key} onClick={() => void p.toggle(key, sample)} label={name} />+ <button+ type="button"+ role="radio"+ aria-checked={active}+ onClick={() => onChange(v)}+ className="flex min-w-0 flex-1 items-center gap-2 rounded-lg py-1.5 pr-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="min-w-0 flex-1">+ <span className={cn("block truncate text-[13px] font-medium", active && "text-brand-text")}>{name}</span>+ {hint && <span className="block truncate text-[11px] text-muted-foreground">{hint}</span>}+ </span>+ {active && <Check className="size-4 shrink-0 text-brand-text" />}+ </button>+ </div>+ );+ };++ return (+ <div className="space-y-3" role="radiogroup" aria-label="Narrator voice">+ {engine === "cloud" && (+ <div>+ <div className="flex items-center justify-between gap-2 px-1 pb-1.5">+ <p className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Narrators</p>+ <input+ value={q}+ onChange={(e) => setQ(e.target.value)}+ placeholder="Search voices"+ aria-label="Search voices"+ className="h-7 w-36 rounded-md border bg-background px-2 text-[12px] outline-none focus:border-primary"+ />+ </div>+ <div className="max-h-64 space-y-0.5 overflow-y-auto pr-1">+ {list.map((v) => row(`preset:${v.id}`, { kind: "preset", id: v.id, name: v.name }, v.name, v.hint, () => presetSample(v.id)))}+ {!list.length && <p className="px-2 py-3 text-[13px] text-muted-foreground">No voice matches “{q}”.</p>}+ </div>+ </div>+ )}+ <div>+ <p className="px-1 pb-1.5 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{engine === "open" ? "Narrator to clone" : "Your own voice"}</p>+ {engine === "open" && <p className="px-1 pb-2 text-[12px] text-muted-foreground">Open-source narration clones a voice: pick a saved voice, or record or upload 10–60 s of clean speech.</p>}+ <div className="space-y-0.5">+ {saved.map((e) => row(`saved:${e.id}`, { kind: "sample", url: e.references[0], name: e.name }, e.name, e.description ?? "Saved voice", async () => e.references[0]))}+ {own && row(`own:${own.url}`, own, own.name ?? "Your recording", "Recorded or uploaded", async () => own.url)}+ </div>+ <div className="flex flex-wrap items-center gap-1.5 px-1 pt-2">+ <VoiceRecorder onRecorded={(v) => onChange({ kind: "sample", url: v.ref, name: v.name ?? "Your recording" })} />+ <button+ type="button"+ onClick={() => file.current?.click()}+ disabled={uploading}+ className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent disabled:opacity-60"+ >+ {uploading ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />} Upload+ </button>+ <input+ ref={file}+ type="file"+ accept="audio/*"+ hidden+ onChange={(e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ void fileToSlot(+ f,+ (v) => {+ setUploading(!!v?.uploading);+ if (v && !v.uploading) onChange({ kind: "sample", url: v.ref, name: f.name.replace(/\.[^.]+$/, "") });+ },+ "audio",+ );+ }}+ />+ {!saved.length && (+ <Link href="/elements?new=1" className="ml-auto text-[12px] text-brand-text hover:underline">+ Save voices in Elements+ </Link>+ )}+ </div>+ </div>+ </div>+ );+}++export function voiceLabel(value: NarratorVoice | null, voices: PickerData["voices"], engine: Engine): string {+ if (!value) return engine === "open" ? "Add a voice" : "Default voice";+ if (value.kind === "sample") return value.name ?? "Your voice";+ return value.name ?? voices.find((v) => v.id === value.id)?.name ?? "Narrator";+}++/** The narrator as a chip that opens the list (Explainer's settings row, the channel page). */+export function NarratorChip(props: { engine: Engine; voices: PickerData["voices"]; value: NarratorVoice | null; onChange: (v: NarratorVoice) => void; className?: string }) {+ const [open, setOpen] = useState(false);+ const label = voiceLabel(props.value, props.voices, props.engine);+ const missing = props.engine === "open" && props.value?.kind !== "sample";+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label={`Narrator: ${label}`}+ className={cn(+ "inline-flex h-8 max-w-full min-w-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors",+ missing ? "bg-secondary text-muted-foreground hover:bg-accent" : "bg-brand-faint text-brand-text hover:bg-brand-faint-hover",+ props.className,+ )}+ >+ {props.value?.kind === "sample" ? <Mic className="size-3.5 shrink-0" /> : <AudioLines className="size-3.5 shrink-0" />}+ <span className="truncate">{label}</span>+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,360px)] p-2" align="start" collisionPadding={12}>+ <NarratorList+ {...props}+ onChange={(v) => {+ props.onChange(v);+ setOpen(false);+ }}+ />+ </PopoverContent>+ </Popover>+ );+}diff --git a/src/components/faceless/script-review.tsx b/src/components/faceless/script-review.tsxnew file mode 100644index 00000000..361302ea--- /dev/null+++ b/src/components/faceless/script-review.tsx@@ -0,0 +1,191 @@+"use client";++import { AlertTriangle, ArrowDown, ArrowUp, Check, Info, Loader2, Plus, Trash2, Wand2 } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { blockId, formatLength, secondsFor, tooLong, totalSeconds, wordCount, type EpisodeView, type ScriptBlock } from "@/lib/catalog/faceless";+import { cn } from "@/lib/utils";+import { EstimateLine } from "./controls";+import { useEpisodeAction, useEstimate, useUpdateEpisode } from "./hooks";++const field = "w-full resize-none rounded-lg border bg-background px-2.5 py-2 text-[14px] leading-relaxed outline-none transition-colors [field-sizing:content] focus:border-primary placeholder:text-subtle-foreground";++function SceneCard({+ block,+ index,+ count,+ onChange,+ onMove,+ onRemove,+ onAdd,+}: {+ block: ScriptBlock;+ index: number;+ count: number;+ onChange: (p: Partial<ScriptBlock>) => void;+ onMove: (d: -1 | 1) => void;+ onRemove: () => void;+ onAdd: () => void;+}) {+ const long = tooLong(block.narration);+ const secs = secondsFor(block.narration);+ return (+ <li className="group/scene rounded-2xl border bg-background p-3 sm:p-4">+ <div className="flex items-center gap-2">+ <span className="grid size-7 shrink-0 place-items-center rounded-full bg-muted font-mono text-[12px] font-semibold">{index + 1}</span>+ <span className={cn("font-mono text-[12px] tabular-nums", long ? "text-warning" : "text-muted-foreground")}>+ ≈ {secs} s · {wordCount(block.narration)} words+ </span>+ <div className="ml-auto flex items-center gap-0.5">+ <Button variant="ghost" size="icon-sm" disabled={index === 0} onClick={() => onMove(-1)} aria-label={`Move scene ${index + 1} up`}>+ <ArrowUp />+ </Button>+ <Button variant="ghost" size="icon-sm" disabled={index === count - 1} onClick={() => onMove(1)} aria-label={`Move scene ${index + 1} down`}>+ <ArrowDown />+ </Button>+ <Button variant="ghost" size="icon-sm" onClick={onAdd} aria-label={`Add a scene after scene ${index + 1}`}>+ <Plus />+ </Button>+ <Button variant="ghost" size="icon-sm" disabled={count === 1} onClick={onRemove} aria-label={`Delete scene ${index + 1}`}>+ <Trash2 />+ </Button>+ </div>+ </div>+ <div className="mt-3 grid gap-3 md:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">+ <label className="block min-w-0 space-y-1">+ <span className="text-[11px] font-semibold tracking-wide text-muted-foreground uppercase">Narration</span>+ <textarea value={block.narration} onChange={(e) => onChange({ narration: e.target.value })} rows={3} maxLength={2000} className={field} placeholder="What the narrator says over this scene" />+ {long && (+ <span className="flex items-center gap-1 text-[12px] text-warning">+ <AlertTriangle className="size-3" /> More than 10 seconds — it'll be split into two scenes.+ </span>+ )}+ </label>+ <div className="min-w-0 space-y-3">+ <label className="block space-y-1">+ <span className="text-[11px] font-semibold tracking-wide text-muted-foreground uppercase">Picture</span>+ <textarea value={block.visual} onChange={(e) => onChange({ visual: e.target.value })} rows={2} maxLength={1200} className={cn(field, "text-[13px]")} placeholder="What the picture shows" />+ </label>+ <label className="block space-y-1">+ <span className="text-[11px] font-semibold tracking-wide text-muted-foreground uppercase">Movement</span>+ <input value={block.motion} onChange={(e) => onChange({ motion: e.target.value })} maxLength={400} className={cn(field, "h-9 py-0 text-[13px]")} placeholder="e.g. slow push-in, leaves drift" />+ </label>+ </div>+ </div>+ </li>+ );+}++/**+ * Review the script before anything renders: every scene's narration, picture and movement, editable,+ * reorderable; saved as you type. Render starts the whole episode.+ */+export function ScriptReview({ view }: { view: EpisodeView }) {+ const ep = view.episode;+ const [blocks, setBlocks] = useState<ScriptBlock[]>(ep.script.blocks);+ const [dirty, setDirty] = useState(false);+ const update = useUpdateEpisode(ep.id);+ const action = useEpisodeAction(ep.id);+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const latest = useRef(blocks);+ const estimate = useEstimate({ kind: ep.kind, settings: ep.settings, blocks });++ // A rewrite brings a new script.+ const scriptKey = ep.script.blocks.map((b) => b.id).join("|");+ const seen = useRef(scriptKey);+ useEffect(() => {+ if (seen.current === scriptKey || dirty) return;+ seen.current = scriptKey;+ setBlocks(ep.script.blocks);+ }, [scriptKey, dirty, ep.script.blocks]);++ const save = async (bs = latest.current) => {+ if (timer.current) clearTimeout(timer.current);+ timer.current = null;+ const v = await update.mutateAsync({ blocks: bs.map(({ id, narration, visual, motion }) => ({ id, narration, visual, motion })) });+ seen.current = v.episode.script.blocks.map((b) => b.id).join("|");+ setDirty(false);+ return v;+ };++ const edit = (next: ScriptBlock[]) => {+ setBlocks(next);+ latest.current = next;+ setDirty(true);+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => void save().catch((e) => toast.error((e as Error).message)), 900);+ };+ useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);++ const change = (i: number, p: Partial<ScriptBlock>) => edit(blocks.map((b, j) => (j === i ? { ...b, ...p, ...(p.narration !== undefined && { seconds: secondsFor(p.narration) }) } : b)));+ const move = (i: number, d: -1 | 1) => {+ const next = [...blocks];+ [next[i], next[i + d]] = [next[i + d], next[i]];+ edit(next);+ };++ const render = async () => {+ try {+ if (dirty) {+ const v = await save();+ setBlocks(v.episode.script.blocks);+ }+ await action.mutateAsync("render");+ } catch (e) {+ toast.error((e as Error).message);+ }+ };++ const seconds = totalSeconds(blocks.map((b) => ({ seconds: secondsFor(b.narration) })));+ return (+ <div className="space-y-5">+ <div className="flex flex-wrap items-end justify-between gap-3">+ <div>+ <h2 className="font-heading text-[26px] leading-tight">Review the script</h2>+ <p className="text-[13px] text-muted-foreground">Edit any scene before it renders. Each scene is about 10 seconds of narration with its own picture.</p>+ </div>+ <Button variant="outline" size="sm" disabled={action.isPending} onClick={() => action.mutate("rewrite", { onError: (e) => toast.error((e as Error).message) })}>+ <Wand2 /> Write it again+ </Button>+ </div>+ {ep.script.offline && (+ <p className="flex items-start gap-2 rounded-xl bg-muted/60 px-3 py-2.5 text-[13px] text-muted-foreground">+ <Info className="mt-0.5 size-4 shrink-0" /> {ep.script.note}+ </p>+ )}+ {ep.error && (+ <p role="alert" className="flex items-start gap-2 rounded-xl border border-warning/40 bg-warning/10 px-3 py-2.5 text-[13px]">+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-warning" /> {ep.error}+ </p>+ )}+ <ol className="space-y-3" aria-label="Scenes">+ {blocks.map((b, i) => (+ <SceneCard+ key={b.id}+ block={b}+ index={i}+ count={blocks.length}+ onChange={(p) => change(i, p)}+ onMove={(d) => move(i, d)}+ onRemove={() => edit(blocks.filter((_, j) => j !== i))}+ onAdd={() => edit([...blocks.slice(0, i + 1), { id: blockId(), narration: "", visual: "", motion: "", seconds: 4 }, ...blocks.slice(i + 1)])}+ />+ ))}+ </ol>+ <div className="sticky bottom-0 z-10 -mx-3 border-t bg-background/90 px-3 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur sm:-mx-6 sm:px-6">+ <div className="flex flex-wrap items-center gap-3">+ <span className="inline-flex items-center gap-1.5 text-[12px] text-muted-foreground" aria-live="polite">+ {update.isPending ? <Loader2 className="size-3 animate-spin" /> : dirty ? null : <Check className="size-3" />}+ {update.isPending ? "Saving…" : dirty ? "Unsaved" : "Saved"}+ </span>+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">{formatLength(seconds)}</span>+ <EstimateLine data={estimate.data} loading={estimate.isFetching} engine={ep.settings.engine} className="min-w-0 flex-1" />+ <Button onClick={() => void render()} disabled={action.isPending || update.isPending} className="rounded-full">+ {action.isPending ? <Loader2 className="animate-spin" /> : <Wand2 />} Render episode+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/faceless/settings-form.tsx b/src/components/faceless/settings-form.tsxnew file mode 100644index 00000000..991c1f37--- /dev/null+++ b/src/components/faceless/settings-form.tsx@@ -0,0 +1,247 @@+"use client";++import { AtSign, ChevronDown, Film, Images, Plus, X } from "lucide-react";+import Link from "next/link";+import { useEffect, useState } from "react";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";+import { fileToList, SlotPreview, type SlotValue } from "@/components/studio/media-slot";+import { useElements } from "@/lib/api";+import {+ ANIMATION_MODES,+ DEFAULT_RESOLUTION,+ ENGINE_MODELS,+ FACELESS_LENGTHS,+ MAX_STYLE_REFS,+ type EpisodeSettings,+ type PickerData,+} from "@/lib/catalog/faceless";+import { cn } from "@/lib/utils";+import { Section, Segmented, ToggleRow } from "./controls";+import { NarratorList } from "./narrator";+import { StyleGrid } from "./style-art";++/** Up to 3 style reference images (they replace the preset). */+export function StyleRefs({ value, onChange }: { value: string[]; onChange: (urls: string[]) => void }) {+ const [list, setList] = useState<SlotValue[]>(() => value.map((url) => ({ ref: url, preview: url, kind: "image" })));+ const sync = setList;+ // Finished uploads become the settings' references.+ const done = list.filter((x) => !x.uploading && x.ref).map((x) => x.ref);+ const key = done.join("|");+ useEffect(() => {+ if (key !== value.join("|")) onChange(key ? key.split("|") : []);+ // Only when the uploaded list changes; `value` follows it.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key]);+ return (+ <div className="flex flex-wrap items-center gap-2">+ {list.map((v, i) => (+ <div key={v.id ?? v.ref ?? i} className="relative size-20 overflow-hidden rounded-xl border bg-muted">+ <SlotPreview value={v} />+ <button+ type="button"+ onClick={() => sync((xs) => xs.filter((x) => x !== v))}+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-foreground text-background shadow-soft"+ aria-label={`Remove style reference ${i + 1}`}+ >+ <X className="size-3" />+ </button>+ </div>+ ))}+ {list.length < MAX_STYLE_REFS && (+ <label className="flex size-20 cursor-pointer flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-border-strong text-[11px] font-medium text-muted-foreground transition-colors hover:border-primary hover:bg-brand-faint hover:text-brand-text focus-within:ring-2 focus-within:ring-ring">+ <Plus className="size-4" />+ Add image+ <input+ type="file"+ accept="image/png,image/jpeg,image/webp"+ multiple+ className="sr-only"+ onChange={(e) => {+ const files = [...(e.target.files ?? [])].slice(0, MAX_STYLE_REFS - list.length);+ e.target.value = "";+ for (const f of files) fileToList(f, sync, "image");+ }}+ />+ </label>+ )}+ </div>+ );+}++/** Characters and places the script may use (their @handles go into the scenes). */+export function ElementsPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) {+ const els = (useElements().data ?? []).filter((e) => e.kind === "character" || e.kind === "location" || e.kind === "prop");+ if (!els.length)+ return (+ <p className="text-[12px] text-muted-foreground">+ Save characters and places in <Link href="/elements?new=1" className="text-brand-text hover:underline">Elements</Link> to keep them the same in every scene.+ </p>+ );+ return (+ <div className="flex flex-wrap gap-1.5">+ {els.map((e) => {+ const on = value.includes(e.handle);+ return (+ <button+ key={e.id}+ type="button"+ aria-pressed={on}+ onClick={() => onChange(on ? value.filter((h) => h !== e.handle) : [...value, e.handle].slice(0, 8))}+ className={cn(+ "inline-flex h-8 items-center gap-1.5 rounded-full pr-3 pl-1 text-[13px] font-medium transition-colors",+ on ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary hover:bg-accent",+ )}+ >+ {e.references[0] ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={e.references[0]} alt="" className="size-6 rounded-full object-cover" />+ ) : (+ <AtSign className="ml-1 size-3.5" />+ )}+ @{e.handle}+ </button>+ );+ })}+ </div>+ );+}++/**+ * Video settings for an episode (Faceless) or an explainer: length, animation, format, style (or style+ * references), narrator, the characters to use, and the video model and quality.+ */+export function EpisodeSettingsForm({+ kind,+ value,+ onChange,+ picker,+ styleIds,+}: {+ kind: "faceless" | "explainer";+ value: EpisodeSettings;+ onChange: (patch: Partial<EpisodeSettings>) => void;+ picker: PickerData;+ styleIds: string[];+}) {+ const [own, setOwn] = useState(value.styleRefs.length > 0);+ const videos = picker.videoModels.filter((m) => m.engine === value.engine);+ const video = videos.find((m) => m.id === value.videoModel) ?? videos.find((m) => m.id === ENGINE_MODELS[value.engine].video) ?? videos[0];+ const resolution = value.resolution && video?.resolutions.includes(value.resolution) ? value.resolution : (DEFAULT_RESOLUTION[video?.id ?? ""]?.[value.animation] ?? video?.resolutions[0]);+ return (+ <div className="space-y-7">+ {kind === "faceless" && (+ <Section title="Length">+ <Segmented label="Episode length" value={value.length} options={FACELESS_LENGTHS.map((s) => ({ value: s, label: `${s / 60} min` }))} onChange={(length) => onChange({ length })} />+ </Section>+ )}++ <Section title="Animation">+ <div role="radiogroup" aria-label="Animation" className="grid gap-2 sm:grid-cols-2">+ {ANIMATION_MODES.map((m) => {+ const on = value.animation === m.id;+ return (+ <button+ key={m.id}+ type="button"+ role="radio"+ aria-checked={on}+ onClick={() => onChange({ animation: m.id, resolution: undefined })}+ className={cn(+ "flex items-start gap-3 rounded-xl border p-3 text-left transition-[border-color,box-shadow] outline-none focus-visible:ring-2 focus-visible:ring-ring",+ on ? "border-primary ring-2 ring-brand-faint" : "hover:border-border-strong",+ )}+ >+ <span className={cn("grid size-9 shrink-0 place-items-center rounded-lg", on ? "bg-brand-faint text-brand-text" : "bg-muted text-muted-foreground")}>+ {m.id === "animated" ? <Film className="size-4" /> : <Images className="size-4" />}+ </span>+ <span className="min-w-0">+ <span className="block text-[14px] font-medium">{m.label}</span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{m.copy}</span>+ </span>+ </button>+ );+ })}+ </div>+ </Section>++ <Section title="Format">+ <div className="flex flex-wrap items-center gap-3">+ <Segmented+ label="Aspect ratio"+ value={value.aspect}+ options={[+ { value: "16:9", label: "Horizontal 16:9" },+ { value: "9:16", label: "Vertical 9:16" },+ ]}+ onChange={(aspect) => onChange({ aspect })}+ />+ </div>+ <div className="grid gap-3 rounded-xl border p-3 sm:grid-cols-2">+ <ToggleRow label="Subtitles" hint="Burned into the video, timed to the voice" checked={value.subtitles} onChange={(subtitles) => onChange({ subtitles })} />+ <ToggleRow+ label="Background music"+ hint={value.engine === "cloud" ? "An instrumental bed under the voice (mixed by ComfyUI: the cloud mixer takes one track)" : "An instrumental bed under the voice (ACE-Step)"}+ checked={value.music}+ onChange={(music) => onChange({ music })}+ />+ </div>+ </Section>++ <Section title="Style" hint="Choose either a style preset or your own style references.">+ <Segmented+ label="Style source"+ value={own ? "own" : "preset"}+ options={[+ { value: "preset", label: "Style presets" },+ { value: "own", label: "Use your own style" },+ ]}+ onChange={(v) => {+ setOwn(v === "own");+ if (v === "preset") onChange({ styleRefs: [] });+ }}+ />+ {own ? (+ <div className="space-y-2">+ <StyleRefs value={value.styleRefs} onChange={(styleRefs) => onChange({ styleRefs })} />+ <p className="text-[12px] text-muted-foreground">Up to 3 images in the look you want: palette, technique and texture are matched, nothing is copied.</p>+ </div>+ ) : (+ <StyleGrid ids={styleIds} value={value.styleId} onChange={(styleId) => onChange({ styleId })} />+ )}+ </Section>++ <Section title="Narrator">+ <div className="rounded-xl border p-2">+ <NarratorList engine={value.engine} voices={picker.voices} value={value.voice} onChange={(voice) => onChange({ voice })} />+ </div>+ </Section>++ <Section title="Characters and places" hint="The script puts them in the scenes where they belong; their pictures keep them the same.">+ <ElementsPicker value={value.elements} onChange={(elements) => onChange({ elements })} />+ </Section>++ <Collapsible>+ <CollapsibleTrigger className="group/adv inline-flex items-center gap-1 rounded text-[13px] font-medium text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">+ <ChevronDown className="size-4 transition-transform group-data-[state=open]/adv:rotate-180" /> Advanced+ </CollapsibleTrigger>+ <CollapsibleContent className="mt-3 space-y-3">+ {videos.length > 1 && (+ <Section title="Video model">+ <Segmented label="Video model" value={video?.id ?? ""} options={videos.map((m) => ({ value: m.id, label: m.name }))} onChange={(videoModel) => onChange({ videoModel, resolution: undefined })} />+ </Section>+ )}+ {video && video.resolutions.length > 1 && (+ <Section title="Quality" hint={value.animation === "frames" ? "Frame by frame renders at a lower quality to keep it light; raise it here." : undefined}>+ <Segmented label="Quality" value={resolution ?? ""} options={video.resolutions.map((r) => ({ value: r, label: r }))} onChange={(r) => onChange({ resolution: r })} />+ </Section>+ )}+ <p className="text-[12px] text-muted-foreground">+ {value.engine === "cloud"+ ? `Pictures: Nano Banana Pro · Video: ${video?.name ?? "Gemini Omni Flash"} · Voice: ElevenLabs v4 (Chatterbox for your own voice) · Subtitles: Auto Subtitle`+ : "Pictures: Z-Image Turbo · Video: Wan 2.2 Lightning · Voice: Chatterbox · Music: ACE-Step · Subtitles: Qwen3-ASR + burn-in"}+ </p>+ </CollapsibleContent>+ </Collapsible>+ </div>+ );+}diff --git a/src/components/faceless/style-art.tsx b/src/components/faceless/style-art.tsxnew file mode 100644index 00000000..33e2f84a--- /dev/null+++ b/src/components/faceless/style-art.tsx@@ -0,0 +1,235 @@+"use client";++import { Check } from "lucide-react";+import { memo, useId } from "react";+import { getStyle, type VisualStyle } from "@/lib/catalog/faceless";+import { cn } from "@/lib/utils";++/**+ * A small procedural picture of each visual style (no generated samples needed): a motif per family —+ * cutouts and labels, line drawings, paper layers, 3D spheres, watercolour blooms, flat shapes, pixels,+ * clay — tinted with the style's hue.+ */++type Motif = "graphics" | "lines" | "paper" | "solid3d" | "paint" | "flat" | "pixel" | "clay" | "iso" | "poly";++const MOTIF: Record<string, Motif> = {+ "editorial-motion-graphics": "graphics",+ "stickman-cartoon": "lines",+ "watercolor-chronicle": "paint",+ "fairy-tale-myth": "paint",+ "paper-diorama": "paper",+ "pastel-flat-2d": "flat",+ "colorful-3d": "solid3d",+ "hand-drawn": "lines",+ "poster-vector": "flat",+ mannequin: "solid3d",+ "whiteboard-doodle": "lines",+ "3d-papercraft": "paper",+ "mixed-media": "graphics",+ "low-poly": "poly",+ "2d-illustrator": "flat",+ "pixel-art": "pixel",+ claymotion: "clay",+ "isometric-flat-vector": "iso",+ "3d-mix": "solid3d",+ "studio-3d": "solid3d",+ "fluffy-toy": "clay",+ "paper-collage": "paper",+};++const c = (l: number, ch: number, h: number) => `oklch(${l} ${ch} ${h % 360})`;++function Motif({ style, u }: { style: VisualStyle; u: string }) {+ const h = style.hue;+ const m = MOTIF[style.id] ?? "flat";+ switch (m) {+ case "graphics":+ return (+ <>+ <rect width="160" height="100" fill={c(0.93, 0.03, h)} />+ <rect x="18" y="16" width="70" height="52" rx="4" fill={c(0.62, 0.15, h)} />+ <circle cx="112" cy="40" r="22" fill={c(0.78, 0.13, h + 60)} />+ <rect x="96" y="70" width="48" height="8" rx="4" fill={c(0.3, 0.05, h)} />+ <rect x="18" y="76" width="38" height="6" rx="3" fill={c(0.3, 0.05, h)} />+ <path d="M60 86 L92 58" stroke={c(0.3, 0.05, h)} strokeWidth="2.5" strokeLinecap="round" />+ <path d="M86 56 L93 57 L91 64" fill="none" stroke={c(0.3, 0.05, h)} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />+ </>+ );+ case "lines": {+ const ink = style.id === "whiteboard-doodle" ? "#1f2937" : c(0.25, 0.03, h);+ const paper = style.id === "whiteboard-doodle" ? "#fbfbfa" : c(0.96, 0.02, h + 40);+ return (+ <>+ <rect width="160" height="100" fill={paper} />+ <g fill="none" stroke={ink} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="52" cy="30" r="9" />+ <path d="M52 39 L52 64 M52 46 L38 56 M52 46 L68 40 M52 64 L42 82 M52 64 L62 82" />+ <circle cx="112" cy="34" r="9" />+ <path d="M112 43 L112 66 M112 50 L98 44 M112 50 L126 58 M112 66 L104 84 M112 66 L121 84" />+ <path d="M74 30 Q82 22 90 30" strokeWidth="2" />+ </g>+ <circle cx="132" cy="18" r="6" fill={c(0.72, 0.16, h)} />+ </>+ );+ }+ case "paper":+ return (+ <>+ <rect width="160" height="100" fill={c(0.88, 0.05, h + 30)} />+ <path d="M0 62 Q30 44 60 58 T120 52 T160 56 V100 H0Z" fill={c(0.72, 0.1, h)} filter={`url(#${u}pshadow)`} />+ <path d="M0 76 Q40 62 80 74 T160 70 V100 H0Z" fill={c(0.6, 0.12, h + 20)} filter={`url(#${u}pshadow)`} />+ <path d="M0 90 Q50 80 100 88 T160 86 V100 H0Z" fill={c(0.48, 0.1, h + 40)} filter={`url(#${u}pshadow)`} />+ <circle cx="120" cy="26" r="12" fill={c(0.85, 0.12, h + 70)} filter={`url(#${u}pshadow)`} />+ <path d="M40 66 L46 46 L52 66Z" fill={c(0.35, 0.06, h)} />+ </>+ );+ case "solid3d":+ return (+ <>+ <rect width="160" height="100" fill={style.id === "studio-3d" ? c(0.9, 0.01, h) : c(0.86, 0.06, h + 20)} />+ <ellipse cx="80" cy="84" rx="54" ry="8" fill="black" opacity="0.12" />+ <circle cx="62" cy="54" r="24" fill={`url(#${u}ball)`} />+ <circle cx="106" cy="62" r="16" fill={`url(#${u}ball2)`} />+ <rect x="88" y="22" width="24" height="24" rx="6" fill={c(0.7, 0.14, h + 120)} />+ </>+ );+ case "paint":+ return (+ <>+ <rect width="160" height="100" fill={c(0.95, 0.02, h + 50)} />+ <g filter={`url(#${u}blur)`} opacity="0.85">+ <circle cx="50" cy="44" r="28" fill={c(0.72, 0.12, h)} />+ <circle cx="104" cy="56" r="30" fill={c(0.66, 0.12, h + 50)} />+ <circle cx="84" cy="26" r="16" fill={c(0.82, 0.1, h + 100)} />+ </g>+ <path d="M18 84 Q60 70 100 82 T150 80" stroke={c(0.4, 0.06, h)} strokeWidth="2" fill="none" opacity="0.6" />+ </>+ );+ case "pixel": {+ const cells: React.ReactNode[] = [];+ for (let y = 0; y < 10; y++)+ for (let x = 0; x < 16; x++) {+ const ground = y >= 7;+ const sun = (x - 12) ** 2 + (y - 2) ** 2 <= 2;+ const hill = y >= 5 && Math.abs(x - 5) <= y - 5;+ const fill = sun ? c(0.85, 0.16, h + 60) : ground ? c(0.55, 0.14, h + 100 + ((x + y) % 2) * 8) : hill ? c(0.5, 0.12, h + 140) : c(0.8, 0.08, h + ((x + y) % 3) * 4);+ cells.push(<rect key={`${x}-${y}`} x={x * 10} y={y * 10} width="10" height="10" fill={fill} />);+ }+ return <>{cells}</>;+ }+ case "clay":+ return (+ <>+ <rect width="160" height="100" fill={c(0.88, 0.05, h + 40)} />+ <ellipse cx="80" cy="86" rx="60" ry="10" fill={c(0.7, 0.08, h + 40)} />+ <ellipse cx="66" cy="58" rx="22" ry="26" fill={`url(#${u}ball)`} />+ <circle cx="60" cy="52" r="3" fill="#222" />+ <circle cx="74" cy="52" r="3" fill="#222" />+ <ellipse cx="108" cy="66" rx="14" ry="16" fill={`url(#${u}ball2)`} />+ </>+ );+ case "iso":+ return (+ <>+ <rect width="160" height="100" fill={c(0.94, 0.03, h)} />+ <path d="M80 20 L120 40 L80 60 L40 40Z" fill={c(0.8, 0.1, h)} />+ <path d="M40 40 L80 60 L80 86 L40 66Z" fill={c(0.62, 0.13, h)} />+ <path d="M120 40 L80 60 L80 86 L120 66Z" fill={c(0.5, 0.12, h)} />+ <path d="M104 22 L118 29 L104 36 L90 29Z" fill={c(0.86, 0.12, h + 120)} />+ </>+ );+ case "poly":+ return (+ <>+ <rect width="160" height="100" fill={c(0.9, 0.04, h)} />+ <path d="M0 100 L40 40 L70 100Z" fill={c(0.55, 0.1, h)} />+ <path d="M40 40 L90 100 L70 100Z" fill={c(0.45, 0.1, h)} />+ <path d="M60 100 L105 30 L150 100Z" fill={c(0.62, 0.11, h + 20)} />+ <path d="M105 30 L130 100 L150 100Z" fill={c(0.5, 0.1, h + 20)} />+ <path d="M120 18 L130 24 L124 32 L114 26Z" fill={c(0.85, 0.14, h + 70)} />+ </>+ );+ default:+ return (+ <>+ <rect width="160" height="100" fill={c(0.94, 0.04, h)} />+ <circle cx="118" cy="30" r="16" fill={c(0.84, 0.1, h + 60)} />+ <path d="M0 74 Q40 54 80 70 T160 64 V100 H0Z" fill={c(0.76, 0.09, h + 140)} />+ <rect x="40" y="38" width="22" height="38" rx="11" fill={c(0.66, 0.12, h)} />+ <circle cx="51" cy="32" r="9" fill={c(0.82, 0.08, h + 30)} />+ </>+ );+ }+}++export const StyleArt = memo(function StyleArt({ styleId, className }: { styleId: string; className?: string }) {+ const style = getStyle(styleId);+ const h = style.hue;+ // Gradient and filter ids are document-wide: each picture gets its own.+ const u = useId().replace(/[^a-zA-Z0-9_-]/g, "");+ return (+ <svg viewBox="0 0 160 100" preserveAspectRatio="xMidYMid slice" className={cn("size-full", className)} aria-hidden>+ <defs>+ <filter id={`${u}pshadow`} x="-10%" y="-10%" width="120%" height="140%">+ <feDropShadow dx="0" dy="2" stdDeviation="1.6" floodOpacity="0.25" />+ </filter>+ <filter id={`${u}blur`}>+ <feGaussianBlur stdDeviation="5" />+ </filter>+ <radialGradient id={`${u}ball`} cx="35%" cy="30%" r="75%">+ <stop offset="0" stopColor={c(0.92, 0.08, h)} />+ <stop offset="0.6" stopColor={c(0.66, 0.16, h)} />+ <stop offset="1" stopColor={c(0.42, 0.12, h)} />+ </radialGradient>+ <radialGradient id={`${u}ball2`} cx="35%" cy="30%" r="75%">+ <stop offset="0" stopColor={c(0.94, 0.06, h + 60)} />+ <stop offset="0.6" stopColor={c(0.72, 0.14, h + 60)} />+ <stop offset="1" stopColor={c(0.48, 0.1, h + 60)} />+ </radialGradient>+ </defs>+ <Motif style={style} u={u} />+ </svg>+ );+});++/** A selectable style card (radio). */+export function StyleCard({ styleId, selected, onSelect, compact }: { styleId: string; selected: boolean; onSelect: () => void; compact?: boolean }) {+ const s = getStyle(styleId);+ return (+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ onClick={onSelect}+ className={cn(+ "group/style relative min-w-0 overflow-hidden rounded-xl border bg-background text-left transition-[box-shadow,border-color] outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "border-primary ring-2 ring-brand-faint" : "hover:border-border-strong",+ )}+ >+ <div className={cn("relative w-full overflow-hidden", compact ? "aspect-[16/9]" : "aspect-[16/10]")}>+ <StyleArt styleId={styleId} className="transition-transform duration-300 ease-move group-hover/style:scale-[1.04]" />+ {selected && (+ <span className="absolute top-1.5 right-1.5 grid size-5 place-items-center rounded-full bg-primary text-primary-foreground shadow-soft">+ <Check className="size-3" />+ </span>+ )}+ </div>+ <div className="px-2.5 py-2">+ <p className="truncate text-[13px] font-medium">{s.name}</p>+ {!compact && <p className="line-clamp-2 text-[11px] leading-snug text-muted-foreground">{s.description}</p>}+ </div>+ </button>+ );+}++/** The style grid (12 Faceless or 22 Explainer styles), a radio group. */+export function StyleGrid({ ids, value, onChange, compact, className }: { ids: string[]; value: string; onChange: (id: string) => void; compact?: boolean; className?: string }) {+ return (+ <div role="radiogroup" aria-label="Visual style" className={cn("grid grid-cols-2 gap-2.5 sm:grid-cols-3 lg:grid-cols-4", className)}>+ {ids.map((id) => (+ <StyleCard key={id} styleId={id} selected={value === id} onSelect={() => onChange(id)} compact={compact} />+ ))}+ </div>+ );+}diff --git a/src/lib/catalog/faceless.ts b/src/lib/catalog/faceless.tsindex c23ee4ae..b428ed09 100644--- a/src/lib/catalog/faceless.ts+++ b/src/lib/catalog/faceless.ts@@ -1447,6 +1447,23 @@ export function defaultSettings(engine: Engine, genre: GenreInfo, o: { explainer};}+/** Narrator voices and video model choices for the browser (built on the server, so the client needs no catalog). */+export interface PickerData {+ voices: { id: string; name: string; hint?: string }[];+ videoModels: { id: string; name: string; engine: Engine; resolutions: string[] }[];+}++export function pickerData(lookup: ModelLookup): PickerData {+ const voices = lookup(ENGINE_MODELS.cloud.narration)?.options.voices ?? [];+ const videoModels = (["cloud", "open"] as const).flatMap((engine) =>+ ENGINE_MODELS[engine].videoChoices.flatMap((id) => {+ const m = lookup(id);+ return m ? [{ id, name: m.name, engine, resolutions: m.options.resolutions ?? [] }] : [];+ }),+ );+ return { voices: voices.map((v) => ({ id: v.id, name: v.name, ...(v.hint && { hint: v.hint }) })), videoModels };+}+/** A short line the narrator reads for a voice preview. */export const previewLine = (name: string) => `Hi, I'm ${name}. I'll be narrating your episode — here's how I sound.`;