Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Library = Assets: layouts, filters, date sections, paging, stacks, select + bulk, folders, Trash

Claude09d94212dff8
diff --git a/src/components/library-view.tsx b/src/components/library-view.tsx
index d49904f4..dcb51255 100644
--- a/src/components/library-view.tsx
+++ b/src/components/library-view.tsx
@@ -1,84 +1,697 @@
"use client";
+import { ArchiveRestore, CheckSquare, ChevronUp, Download, FolderInput, Heart, Loader2, Search, Trash2, X } from "lucide-react";
import Link from "next/link";
-import { useRouter, useSearchParams } from "next/navigation";
-import { Search } from "lucide-react";
-import { Suspense, useState } from "react";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { AssetCard, cardRatio, type CardApi } from "@/components/library/asset-card";
+import { FilterBar, filterFields, hasFilters, NO_FILTERS, type Filters } from "@/components/library/filters";
+import { FolderDialog, FolderHeader, FolderStrip, MoveMenuItems } from "@/components/library/folders";
+import { useViewPrefs, ViewOptions, type ViewPrefs } from "@/components/library/view-options";
import { PageShell } from "@/components/page-shell";
-import { PageHeader } from "@/components/preset-gallery";
-import { Feed } from "@/components/studio/feed";
+import { downloadUrl } from "@/components/studio/result-actions";
+import { Viewer } from "@/components/studio/viewer";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Kbd } from "@/components/ui/kbd";
import { Skeleton } from "@/components/ui/skeleton";
-import { useGenerations, type FeedFilter } from "@/lib/api";
+import { useCreateGeneration, useFolders, useGenerationActions, useLibrary, useLibraryFacets, useUploads, type Asset, type FeedFilter } from "@/lib/api";
+import type { Generation, MediaKind } from "@/lib/catalog/types";
+import { buildEntries, splitByDate, TRASH_DAYS, type LibraryEntry } from "@/lib/library";
+import { isLayered } from "@/lib/output-actions";
import { cn } from "@/lib/utils";
-const TABS: { id: string; label: string; filter: FeedFilter }[] = [
- { id: "all", label: "All", filter: {} },
- { id: "images", label: "Images", filter: { kind: "image" } },
- { id: "videos", label: "Videos", filter: { kind: "video" } },
- { id: "audio", label: "Audio", filter: { kind: "audio" } },
- { id: "favorites", label: "Favorites", filter: { favorites: true } },
+type TabId = "all" | "images" | "videos" | "audio" | "text" | "3d" | "favorites" | "uploads" | "trash";
+
+const TABS: { id: TabId; label: string; kinds?: MediaKind[] }[] = [
+ { id: "all", label: "All" },
+ { id: "images", label: "Images", kinds: ["image"] },
+ { id: "videos", label: "Videos", kinds: ["video"] },
+ { id: "audio", label: "Audio", kinds: ["audio"] },
+ { id: "text", label: "Text", kinds: ["text"] },
+ { id: "3d", label: "3D", kinds: ["model3d"] },
+ { id: "favorites", label: "Favorites" },
+ { id: "uploads", label: "Uploads" },
+ { id: "trash", label: "Trash" },
];
+const singles = new WeakMap<Generation, LibraryEntry>();
+/** A stack member as its own card entry (cached per object so memoized cards stay put). */
+function singleEntry(g: Generation): LibraryEntry {
+ let e = singles.get(g);
+ if (!e) singles.set(g, (e = { type: "single", key: g.id, g }));
+ return e;
+}
+
+const ids = (e: LibraryEntry) => (e.type === "single" ? [e.g.id] : e.items.map((g) => g.id));
+const members = (e: LibraryEntry) => (e.type === "single" ? [e.g] : e.items);
+
+/** Keep entry objects whose content didn't change, so memoized cards skip re-rendering on polls. */
+function useStableEntries(next: LibraryEntry[]): LibraryEntry[] {
+ // "Storing information from previous renders": recompute only when the list itself changes.
+ const [state, setState] = useState<{ next: LibraryEntry[] | null; out: LibraryEntry[]; map: Map<string, LibraryEntry> }>({ next: null, out: [], map: new Map() });
+ if (state.next === next) return state.out;
+ const out = stabilize(state.map, next);
+ setState({ next, out: out.list, map: out.map });
+ return out.list;
+}
+
+function stabilize(prev: Map<string, LibraryEntry>, next: LibraryEntry[]): { list: LibraryEntry[]; map: Map<string, LibraryEntry> } {
+ {
+ const map = new Map<string, LibraryEntry>();
+ const out = next.map((e) => {
+ const p = prev.get(e.key);
+ const same =
+ p &&
+ p.type === e.type &&
+ (e.type === "single"
+ ? (p as typeof e).g === e.g
+ : (p as typeof e).title === e.title && (p as typeof e).label === e.label && (p as typeof e).items.length === e.items.length && (p as typeof e).items.every((g, i) => g === e.items[i]));
+ const keep = same ? p : e;
+ map.set(e.key, keep);
+ return keep;
+ });
+ return { list: out, map };
+ }
+}
+
+/** An upload, shaped like a finished generation so the cards and the viewer can show it. */
+function uploadAsGeneration(a: Asset): Generation {
+ return {
+ id: a.id,
+ batchId: null,
+ feature: "upload",
+ presetId: null,
+ modelId: "upload",
+ modelName: "Your upload",
+ engine: "open",
+ provider: "local",
+ op: a.kind === "video" ? "v2v" : "edit",
+ kind: a.kind,
+ status: "succeeded",
+ progress: 1,
+ message: null,
+ prompt: null,
+ request: { feature: "upload", modelId: "upload", prompt: a.name ?? "Upload" },
+ outputs: [{ url: a.url, kind: a.kind, contentType: a.contentType, assetId: a.id }],
+ error: null,
+ costUsd: null,
+ favorite: false,
+ createdAt: a.createdAt,
+ updatedAt: a.createdAt,
+ completedAt: a.createdAt,
+ };
+}
+
+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;
+}
+
+function Empty({ title, children }: { title: string; children?: React.ReactNode }) {
+ return (
+ <div className="rounded-xl border border-primary/10 bg-brand-faint px-6 py-12 text-center">
+ <p className="font-heading text-[22px]">{title}</p>
+ {children && <div className="mt-1 text-[14px] text-muted-foreground">{children}</div>}
+ </div>
+ );
+}
+
+const GAP = 8;
+
+/**
+ * Masonry that keeps reading order left to right: each card goes into the shortest column, by the
+ * aspect ratios we already know (CSS columns would fill top to bottom, scattering the newest).
+ */
+function Masonry({ entries, size, render }: { entries: LibraryEntry[]; size: number; render: (e: LibraryEntry) => React.ReactNode }) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(0);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const ro = new ResizeObserver(([e]) => setWidth(Math.round(e.contentRect.width)));
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+ const cols = width ? Math.max(width < 640 ? 2 : 1, Math.floor((width + GAP) / (size + GAP))) : 4;
+ const columns = useMemo(() => {
+ const heights = Array.from({ length: cols }, () => 0);
+ const out = Array.from({ length: cols }, () => [] as LibraryEntry[]);
+ for (const e of entries) {
+ const k = heights.indexOf(Math.min(...heights));
+ out[k].push(e);
+ heights[k] += 1 / cardRatio(e, "masonry") + 0.04;
+ }
+ return out;
+ }, [entries, cols]);
+ return (
+ <div ref={ref} className="flex items-start gap-2">
+ {columns.map((c, i) => (
+ <div key={i} className="flex min-w-0 flex-1 flex-col gap-2">
+ {c.map(render)}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/** One section's cards in the chosen layout; an expanded stack opens as a full-width panel after its card. */
+function Cards({ entries, prefs, expanded, render, panel }: { entries: LibraryEntry[]; prefs: ViewPrefs; expanded: Set<string>; render: (e: LibraryEntry) => React.ReactNode; panel: (e: LibraryEntry) => React.ReactNode }) {
+ if (prefs.layout === "list") return <div className="flex flex-col gap-0.5">{entries.flatMap((e) => (expanded.has(e.key) ? [render(e), panel(e)] : [render(e)]))}</div>;
+ if (prefs.layout === "square") {
+ const style = { "--card": `min(${prefs.size}px, calc(50vw - 22px))` } as React.CSSProperties;
+ return (
+ <div style={style} className="grid grid-cols-[repeat(auto-fill,minmax(var(--card),1fr))] gap-2">
+ {entries.flatMap((e) => (expanded.has(e.key) ? [render(e), panel(e)] : [render(e)]))}
+ </div>
+ );
+ }
+ // Masonry: split at expanded stacks so their panels span the full width.
+ const runs: LibraryEntry[][] = [[]];
+ const panels: LibraryEntry[] = [];
+ for (const e of entries) {
+ runs.at(-1)!.push(e);
+ if (expanded.has(e.key)) {
+ panels.push(e);
+ runs.push([]);
+ }
+ }
+ return (
+ <div className="space-y-2">
+ {runs.map((run, i) => (
+ <div key={i} className="space-y-2">
+ {run.length > 0 && <Masonry entries={run} size={prefs.size} render={render} />}
+ {panels[i] && panel(panels[i])}
+ </div>
+ ))}
+ </div>
+ );
+}
+
function Inner() {
const sp = useSearchParams();
const router = useRouter();
+ const pathname = usePathname();
const tab = TABS.find((t) => t.id === sp.get("tab")) ?? TABS[0];
+ const folderId = sp.get("folder") ?? undefined;
+ const trash = tab.id === "trash";
+ const uploadsTab = tab.id === "uploads";
const [q, setQ] = useState("");
- const feed = useGenerations({ ...tab.filter, q: q || undefined, limit: 120 });
+ const dq = useDebounced(q.trim(), 250);
+ const [filters, setFilters] = useState<Filters>(NO_FILTERS);
+ const [prefs, setPrefs] = useViewPrefs();
+ const facets = useLibraryFacets();
+ const folders = useFolders();
+ const folder = folderId ? folders.data?.find((f) => f.id === folderId) : undefined;
+ const actions = useGenerationActions();
+ const create = useCreateGeneration();
+
+ const filter = useMemo<FeedFilter>(
+ () => ({
+ ...(tab.kinds && { kinds: tab.kinds }),
+ ...(tab.id === "favorites" && { favorites: true }),
+ ...(trash && { trashed: true }),
+ ...(folderId && !trash && { folderId }),
+ ...(dq && { q: dq }),
+ ...filterFields(filters),
+ }),
+ [tab, trash, folderId, dq, filters],
+ );
+ const lib = useLibrary(filter);
+ const uploads = useUploads();
+ const items = useMemo(() => (uploadsTab ? (uploads.data ?? []).map(uploadAsGeneration) : (lib.data?.pages.flat() ?? [])), [uploadsTab, uploads.data, lib.data]);
+ const built = useMemo(() => buildEntries(items, { stacks: prefs.stacks && !trash && !uploadsTab }), [items, prefs.stacks, trash, uploadsTab]);
+ const entries = useStableEntries(built);
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
+ const sections = useMemo(() => {
+ const when = (e: LibraryEntry) => Math.max(...members(e).map((g) => (trash ? (g.deletedAt ?? g.createdAt) : g.createdAt)));
+ return prefs.splitByDate ? splitByDate(entries, when) : [{ key: 0, label: "", items: entries }];
+ }, [entries, prefs.splitByDate, trash]);
+
+ // --- Selection ---------------------------------------------------------------------------
+ const [selecting, setSelecting] = useState(false);
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const order = useMemo(() => sections.flatMap((s) => s.items.flatMap((e) => [e, ...(e.type === "stack" && expanded.has(e.key) ? e.items.map((g) => ({ type: "single" as const, key: g.id, g })) : [])])), [sections, expanded]);
+ const latest = useRef({ order, selected, items });
+ useEffect(() => {
+ latest.current = { order, selected, items };
+ });
+ const lastKey = useRef<string | null>(null);
+ const clear = useCallback(() => {
+ setSelected(new Set());
+ setSelecting(false);
+ }, []);
+ // A new tab or folder starts a new selection.
+ const scope = `${tab.id}/${folderId ?? ""}`;
+ const [lastScope, setLastScope] = useState(scope);
+ if (lastScope !== scope) {
+ setLastScope(scope);
+ setSelected(new Set());
+ setSelecting(false);
+ }
+
+ const selectedGens = useMemo(() => items.filter((g) => selected.has(g.id)), [items, selected]);
+
+ // --- Viewer --------------------------------------------------------------------------------
+ const [open, setOpen] = useState<{ id: string; index: number } | null>(null);
+ const flat = useMemo(
+ () => order.flatMap((e) => members(e)).filter((g, i, all) => g.status === "succeeded" && g.outputs.length && all.findIndex((x) => x.id === g.id) === i).flatMap((g) => (isLayered(g) ? [{ g, i: 0 }] : g.outputs.map((_, i) => ({ g, i })))),
+ [order],
+ );
+ const pos = open ? flat.findIndex((f) => f.g.id === open.id && (f.i === open.index || isLayered(f.g))) : -1;
+
+ const api = useMemo<CardApi>(
+ () => ({
+ open: (g, index) => setOpen({ id: g.id, index }),
+ expand: (key) =>
+ setExpanded((s) => {
+ const n = new Set(s);
+ if (n.has(key)) n.delete(key);
+ else n.add(key);
+ return n;
+ }),
+ toggle: (key, list, shift) => {
+ setSelecting(true);
+ const { order, selected } = latest.current;
+ const next = new Set(selected);
+ if (shift && lastKey.current) {
+ const a = order.findIndex((e) => e.key === lastKey.current);
+ const b = order.findIndex((e) => e.key === key);
+ if (a >= 0 && b >= 0) {
+ for (const e of order.slice(Math.min(a, b), Math.max(a, b) + 1)) ids(e).forEach((id) => next.add(id));
+ lastKey.current = key;
+ setSelected(next);
+ return;
+ }
+ }
+ const all = list.every((id) => next.has(id));
+ list.forEach((id) => (all ? next.delete(id) : next.add(id)));
+ lastKey.current = key;
+ setSelected(next);
+ },
+ dragIds: (list) => {
+ const { selected } = latest.current;
+ return list.every((id) => selected.has(id)) ? [...selected] : list;
+ },
+ retry: (g) => create.mutate(g.request, { onError: (e) => toast.error((e as Error).message) }),
+ runner: { onOpen: (g, index) => setOpen({ id: g.id, index }) },
+ }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [],
+ );
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if ((e.target as HTMLElement)?.closest("input,textarea,[contenteditable],[role=dialog],[role=menu]")) return;
+ if (e.key === "Escape" && (selecting || latest.current.selected.size)) {
+ e.preventDefault();
+ clear();
+ } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "a" && selecting) {
+ e.preventDefault();
+ setSelected(new Set(latest.current.items.map((g) => g.id)));
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [selecting, clear]);
+
+ // --- Paging ---------------------------------------------------------------------------------
+ const sentinel = useRef<HTMLDivElement>(null);
+ const { hasNextPage, isFetchingNextPage, fetchNextPage } = lib;
+ useEffect(() => {
+ const el = sentinel.current;
+ if (!el || !hasNextPage || uploadsTab) return;
+ const io = new IntersectionObserver((es) => es.some((x) => x.isIntersecting) && !isFetchingNextPage && void fetchNextPage(), { rootMargin: "600px" });
+ io.observe(el);
+ return () => io.disconnect();
+ }, [hasNextPage, isFetchingNextPage, fetchNextPage, uploadsTab]);
+
+ const go = (params: Record<string, string | undefined>) => {
+ const next = new URLSearchParams(sp.toString());
+ for (const [k, v] of Object.entries(params)) {
+ if (v) next.set(k, v);
+ else next.delete(k);
+ }
+ const s = next.toString();
+ router.replace(s ? `${pathname}?${s}` : pathname, { scroll: false });
+ window.scrollTo({ top: 0 });
+ };
+
+ const moveTo = async (list: string[], folderIdTo: string | null, name: string) => {
+ const gens = list.map((id) => latest.current.items.find((g) => g.id === id)).filter((g): g is Generation => !!g);
+ if (!gens.length) return;
+ const n = await actions.move(gens, folderIdTo);
+ if (n) toast.success(folderIdTo ? `Moved ${n} to “${name}”` : `Took ${n} out of the folder`);
+ clear();
+ };
+
+ const [newFolderFor, setNewFolderFor] = useState<string[] | null>(null);
+ const [confirmForever, setConfirmForever] = useState<Generation[] | null>(null);
+ const [confirmEmpty, setConfirmEmpty] = useState(false);
+
+ const loading = uploadsTab ? uploads.isLoading : lib.isLoading;
+ const refreshing = !uploadsTab && lib.isPlaceholderData;
+ const count = (t: (typeof TABS)[number]) => {
+ const f = facets.data;
+ if (!f) return undefined;
+ if (t.id === "trash") return f.trash || undefined;
+ if (t.id === "favorites") return f.favorites || undefined;
+ if (t.kinds) return f.kinds[t.kinds[0]] || undefined;
+ return undefined;
+ };
+ const visibleTabs = TABS.filter((t) => !t.kinds || t.id === "images" || t.id === "videos" || t.id === "audio" || (facets.data?.kinds[t.kinds[0]] ?? 0) > 0 || tab.id === t.id);
+ const allFav = selectedGens.length > 0 && selectedGens.every((g) => g.favorite);
+
+ const empty = () => {
+ if (dq) {
+ return (
+ <Empty title={`No matches for “${dq}”`}>
+ Try another word.{" "}
+ <button onClick={() => setQ("")} className="text-brand-text hover:underline">
+ Clear search
+ </button>
+ </Empty>
+ );
+ }
+ if (hasFilters(filters)) {
+ return (
+ <Empty title="Nothing matches your filters">
+ <button onClick={() => setFilters(NO_FILTERS)} className="text-brand-text hover:underline">
+ Clear filters
+ </button>
+ </Empty>
+ );
+ }
+ if (trash) return <Empty title="Trash is empty">Generations you delete stay here for {TRASH_DAYS} days, then go for good.</Empty>;
+ if (folder) return <Empty title="This folder is empty">Drag cards onto it, or select some and choose Move to folder.</Empty>;
+ if (tab.id === "favorites") return <Empty title="Nothing liked yet">Mark the ones you like with the heart to keep them here.</Empty>;
+ if (uploadsTab) return <Empty title="No uploads yet">Files you add to a studio show up here.</Empty>;
+ return (
+ <Empty title="Your creations will appear here">
+ Generate something and it lands here.{" "}
+ <Link href="/image" className="text-brand-text hover:underline">
+ Create an image
+ </Link>
+ </Empty>
+ );
+ };
+
return (
- <PageShell>
- <PageHeader title="Library" description="Everything you make lands here — across cloud and open-source runs.">
- <div className="relative">
- <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
- <input
- value={q}
- onChange={(e) => setQ(e.target.value)}
- placeholder="Search prompts"
- className="h-8 w-56 rounded-lg border bg-background pr-2 pl-8 text-sm outline-none focus:border-primary"
- />
+ <PageShell wide>
+ <div className="flex flex-wrap items-end justify-between gap-x-4 gap-y-3 pb-5">
+ {folder ? (
+ <FolderHeader folder={folder} onBack={() => go({ folder: undefined })} onMoveOut={(list) => void moveTo(list, null, "Library")} />
+ ) : (
+ <div className="min-w-0">
+ <h1 className="font-heading text-[34px] leading-tight">Library</h1>
+ <p className="mt-1 max-w-2xl text-[15px] text-muted-foreground">Everything you make, across cloud and open-source runs.</p>
+ </div>
+ )}
+ <div className="flex w-full items-center gap-2 sm:w-auto">
+ <div className="relative min-w-0 flex-1 sm:w-64 sm:flex-none">
+ <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <input
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ onKeyDown={(e) => e.key === "Escape" && setQ("")}
+ placeholder="Search prompts"
+ aria-label="Search prompts"
+ className="h-8 w-full rounded-full border bg-background pr-8 pl-8 text-[13px] outline-none focus:border-primary focus:ring-4 focus:ring-brand-faint"
+ />
+ {refreshing || (q.trim() !== dq && q.trim()) ? (
+ <Loader2 className="absolute top-1/2 right-2.5 size-3.5 -translate-y-1/2 animate-spin text-muted-foreground" />
+ ) : q ? (
+ <button onClick={() => setQ("")} aria-label="Clear search" className="absolute top-1/2 right-1.5 grid size-5 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <X className="size-3.5" />
+ </button>
+ ) : null}
+ </div>
+ {!uploadsTab && (
+ <button
+ onClick={() => (selecting ? clear() : setSelecting(true))}
+ aria-pressed={selecting}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors",
+ selecting ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",
+ )}
+ >
+ <CheckSquare className="size-3.5" /> <span className="hidden sm:inline">{selecting ? "Done" : "Select"}</span>
+ </button>
+ )}
+ <ViewOptions prefs={prefs} onChange={setPrefs} />
</div>
- </PageHeader>
- <div className="mb-6 flex gap-4 border-b">
- {TABS.map((t) => (
- <button
- key={t.id}
- onClick={() => router.replace(`/library?tab=${t.id}`)}
- className={cn(
- "-mb-px border-b-2 border-transparent px-1 pb-2 text-[14px] text-muted-foreground transition-colors hover:text-foreground",
- tab.id === t.id && "border-foreground font-medium text-foreground",
- )}
- >
- {t.label}
- </button>
- ))}
</div>
- {feed.isLoading ? (
- <div className="flex gap-2">
- <Skeleton className="h-56 w-56 rounded-xl" />
- <Skeleton className="h-56 w-80 rounded-xl" />
+
+ {!folder && (
+ <div className="scrollbar-none mb-4 flex gap-4 overflow-x-auto border-b">
+ {visibleTabs.map((t) => {
+ const n = count(t);
+ return (
+ <button
+ key={t.id}
+ onClick={() => go({ tab: t.id === "all" ? undefined : t.id, folder: undefined })}
+ className={cn(
+ "-mb-px inline-flex shrink-0 items-center gap-1.5 border-b-2 border-transparent px-1 pb-2 text-[14px] whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground",
+ tab.id === t.id && "border-foreground font-medium text-foreground",
+ )}
+ >
+ {t.label}
+ {n ? <span className="font-mono text-[11px] text-muted-foreground">{n}</span> : null}
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ {tab.id === "all" && !folder && (folders.data?.length || !loading) ? (
+ <div className="mb-4">
+ <FolderStrip folders={folders.data ?? []} onOpen={(f) => go({ folder: f.id })} onMove={(list, f) => void moveTo(list, f.id, f.name)} />
+ </div>
+ ) : null}
+
+ {!uploadsTab && (
+ <div className="mb-4 flex flex-wrap items-center justify-between gap-2">
+ <FilterBar value={filters} onChange={setFilters} facets={facets.data} />
+ {trash && (
+ <div className="flex items-center gap-3 text-[13px] text-muted-foreground">
+ <span>Items stay here for {TRASH_DAYS} days.</span>
+ {items.length > 0 && (
+ <button onClick={() => setConfirmEmpty(true)} className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 font-medium text-destructive hover:bg-accent">
+ <Trash2 className="size-3.5" /> Empty trash
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {loading && !items.length ? (
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(min(200px,calc(50vw-22px)),1fr))] gap-2">
+ {Array.from({ length: 8 }, (_, i) => (
+ <Skeleton key={i} className="aspect-square rounded-xl" />
+ ))}
</div>
+ ) : !items.length ? (
+ empty()
) : (
- <Feed
- items={feed.data ?? []}
- empty={
- <div className="rounded-xl border border-primary/10 bg-brand-faint px-6 py-12 text-center">
- <p className="font-heading text-[22px]">{q ? `No matches for “${q}”` : "Nothing here yet"}</p>
- <p className="mt-1 text-[14px] text-muted-foreground">
- {q ? "Try another word." : "Generate something and it will show up here."}{" "}
- {!q && (
- <Link href="/image" className="text-brand-text hover:underline">
- Create an image
- </Link>
+ <div className={cn("space-y-7 transition-opacity", refreshing && "opacity-70")}>
+ {sections.map((s) => (
+ <section key={s.key} aria-label={s.label || "Results"}>
+ {s.label && (
+ <h2 className="mb-2.5 flex items-baseline gap-2 text-[13px] font-medium">
+ {s.label} <span className="font-mono text-[11px] font-normal text-muted-foreground">{s.items.reduce((n, e) => n + members(e).length, 0)}</span>
+ </h2>
+ )}
+ <Cards
+ entries={s.items}
+ prefs={prefs}
+ expanded={expanded}
+ render={(e) => (
+ <AssetCard key={e.key} entry={e} layout={prefs.layout} fit={prefs.fit} selecting={selecting} selected={ids(e).every((id) => selected.has(id))} expanded={expanded.has(e.key)} api={api} />
)}
- </p>
- </div>
- }
+ panel={(e) =>
+ e.type === "stack" && (
+ <div key={`${e.key}:open`} className={cn("rounded-2xl border bg-card p-3", prefs.layout === "square" && "col-span-full", prefs.layout === "list" && "my-1")}>
+ <div className="mb-2.5 flex items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <p className="font-heading text-[19px] leading-snug">{e.title}</p>
+ <p className="text-[12px] text-muted-foreground">{e.label}</p>
+ </div>
+ <button onClick={() => api.expand(e.key)} className="inline-flex h-8 shrink-0 items-center gap-1 rounded-full px-2.5 text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground">
+ <ChevronUp className="size-4" /> Collapse
+ </button>
+ </div>
+ <div className={cn(prefs.layout === "list" ? "flex flex-col gap-0.5" : "grid grid-cols-[repeat(auto-fill,minmax(min(170px,calc(50vw-40px)),1fr))] gap-2")}>
+ {e.items.map((g) => (
+ <AssetCard
+ key={g.id}
+ entry={singleEntry(g)}
+ layout={prefs.layout === "list" ? "list" : "square"}
+ fit={prefs.fit}
+ selecting={selecting}
+ selected={selected.has(g.id)}
+ api={api}
+ />
+ ))}
+ </div>
+ </div>
+ )
+ }
+ />
+ </section>
+ ))}
+ <div ref={sentinel} className="flex flex-col items-center gap-2 py-4">
+ {!uploadsTab && hasNextPage ? (
+ <button
+ onClick={() => void fetchNextPage()}
+ disabled={isFetchingNextPage}
+ className="inline-flex h-9 items-center gap-2 rounded-full bg-secondary px-4 text-[13px] font-medium hover:bg-accent disabled:opacity-60"
+ >
+ {isFetchingNextPage && <Loader2 className="size-3.5 animate-spin" />} Load more
+ </button>
+ ) : (
+ <p className="text-[12px] text-subtle-foreground">{items.length > 12 ? "That's everything" : ""}</p>
+ )}
+ </div>
+ </div>
+ )}
+
+ {(selecting || selected.size > 0) && !uploadsTab && (
+ <div className="pointer-events-none fixed inset-x-0 bottom-0 z-30 flex justify-center px-3 pb-[max(1rem,env(safe-area-inset-bottom))] md:pl-[var(--sidebar-width,0px)]">
+ <div role="toolbar" aria-label="Selection" className="pointer-events-auto flex max-w-full items-center gap-1 overflow-x-auto rounded-full border bg-background p-1.5 shadow-strong">
+ <span className="shrink-0 px-2.5 text-[13px] font-medium whitespace-nowrap">{selected.size ? `${selected.size} selected` : "Select items"}</span>
+ {trash ? (
+ <>
+ <BarButton icon={ArchiveRestore} label="Restore" disabled={!selected.size} onClick={() => void actions.restore(selectedGens).then((n) => (n && toast(`Restored ${n}`), clear()))} />
+ <BarButton icon={Trash2} label="Delete forever" destructive disabled={!selected.size} onClick={() => setConfirmForever(selectedGens)} />
+ </>
+ ) : (
+ <>
+ <BarButton
+ icon={Download}
+ label="Download"
+ disabled={!selectedGens.some((g) => g.status === "succeeded")}
+ onClick={() => downloadUrl(`/api/generations/zip?ids=${[...selected].slice(0, 500).join(",")}`)}
+ />
+ <BarButton icon={Heart} label={allFav ? "Unlike" : "Like"} disabled={!selected.size} onClick={() => void actions.favoriteMany(selectedGens, !allFav)} />
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild disabled={!selected.size}>
+ <button className={BAR} disabled={!selected.size}>
+ <FolderInput className="size-4" /> <span className="hidden sm:inline">Move to</span>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="top" align="center" collisionPadding={12}>
+ <MoveMenuItems folders={folders.data ?? []} current={folderId} onMove={(fid, name) => void moveTo([...selected], fid, name)} onNew={() => setNewFolderFor([...selected])} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <BarButton
+ icon={Trash2}
+ label="Delete"
+ destructive
+ disabled={!selected.size}
+ onClick={() => {
+ void actions.trash(selectedGens);
+ clear();
+ }}
+ />
+ </>
+ )}
+ <span className="mx-1 h-5 w-px shrink-0 bg-border" />
+ <button onClick={clear} className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[13px] whitespace-nowrap text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Unselect all">
+ <X className="size-3.5" /> <span className="hidden sm:inline">Unselect all</span> <Kbd className="hidden sm:inline-flex">Esc</Kbd>
+ </button>
+ </div>
+ </div>
+ )}
+
+ {newFolderFor && (
+ <FolderDialog
+ open
+ onOpenChange={(v) => !v && setNewFolderFor(null)}
+ onSaved={(f) => {
+ void moveTo(newFolderFor, f.id, f.name);
+ setNewFolderFor(null);
+ }}
+ />
+ )}
+
+ <AlertDialog open={!!confirmForever} onOpenChange={(v) => !v && setConfirmForever(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {confirmForever?.length === 1 ? "this for good" : `${confirmForever?.length} items for good`}?</AlertDialogTitle>
+ <AlertDialogDescription>They&apos;ll be removed with their files and can&apos;t be recovered.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ if (confirmForever) void actions.deleteForever(confirmForever).then((n) => n && toast(`Deleted ${n} for good`));
+ clear();
+ }}
+ >
+ Delete forever
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ <AlertDialog open={confirmEmpty} onOpenChange={setConfirmEmpty}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Empty the Trash?</AlertDialogTitle>
+ <AlertDialogDescription>Everything in it, including what your filters hide, is deleted with its files and can&apos;t be recovered.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ void actions.emptyTrash().then(() => toast("Trash emptied"));
+ }}
+ >
+ Empty trash
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ {open && pos >= 0 && (
+ <Viewer
+ generation={flat[pos].g}
+ index={isLayered(flat[pos].g) ? open.index : flat[pos].i}
+ onIndex={(index) => setOpen({ id: flat[pos].g.id, index })}
+ onClose={() => setOpen(null)}
+ onPrev={pos > 0 ? () => setOpen({ id: flat[pos - 1].g.id, index: flat[pos - 1].i }) : undefined}
+ onNext={pos < flat.length - 1 ? () => setOpen({ id: flat[pos + 1].g.id, index: flat[pos + 1].i }) : undefined}
/>
)}
</PageShell>
);
}
+const BAR = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[13px] font-medium whitespace-nowrap transition-colors hover:bg-accent disabled:pointer-events-none disabled:opacity-40";
+
+function BarButton({ icon: Icon, label, onClick, disabled, destructive }: { icon: typeof Download; label: string; onClick: () => void; disabled?: boolean; destructive?: boolean }) {
+ return (
+ <button onClick={onClick} disabled={disabled} aria-label={label} title={label} className={cn(BAR, destructive && "text-destructive")}>
+ <Icon className="size-4" /> <span className="hidden sm:inline">{label}</span>
+ </button>
+ );
+}
+
export function LibraryView() {
return (
<Suspense fallback={null}>
diff --git a/src/components/library/asset-card.tsx b/src/components/library/asset-card.tsx
new file mode 100644
index 00000000..66a9fb46
--- /dev/null
+++ b/src/components/library/asset-card.tsx
@@ -0,0 +1,292 @@
+"use client";
+
+import { Check, ChevronDown, Heart, Layers, MoreHorizontal, RotateCcw } from "lucide-react";
+import { memo, useMemo, useState } from "react";
+import { tileRatio } from "@/components/studio/feed";
+import { TileActions, useCanHover, type RunnerOptions } from "@/components/studio/result-actions";
+import { LayersStack, MediaThumb, SmallThumb } from "@/components/studio/result-media";
+import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";
+import { elapsed, timeAgo } from "@/lib/format";
+import { coverOf, trashDaysLeft, userTitle, type LibraryEntry } from "@/lib/library";
+import { isLayered } from "@/lib/output-actions";
+import { cn } from "@/lib/utils";
+import { DRAG_TYPE } from "./folders";
+import type { Layout } from "./view-options";
+
+/** Stable callbacks from the Library (refs inside), so cards re-render only when their own data changes. */
+export interface CardApi {
+ open: (g: Generation, index: number) => void;
+ /** Toggle these generations; shift extends a range from the last toggled card. */
+ toggle: (key: string, ids: string[], shift: boolean) => void;
+ expand: (key: string) => void;
+ /** What a drag carries: the whole selection when the card is part of it. */
+ dragIds: (ids: string[]) => string[];
+ retry: (g: Generation) => void;
+ runner: RunnerOptions;
+}
+
+/** A card's width / height: square in the Square layout, else its cover's own shape. */
+export function cardRatio(e: LibraryEntry, layout: Layout): number {
+ if (layout === "square") return 1;
+ if (e.type === "stack") {
+ const c = coverOf(e.items);
+ return c ? tileRatio(c.g) : 1;
+ }
+ const g = e.g;
+ return g.status === "succeeded" ? (isLayered(g) ? Math.max(tileRatio(g), 0.8) : tileRatio(g)) : Math.max(tileRatio(g), 0.8);
+}
+
+const LIST_MENU ="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-background hover:text-foreground";
+
+const idsOf = (e: LibraryEntry) => (e.type === "single" ? [e.g.id] : e.items.map((g) => g.id));
+
+function StatusCover({ g }: { g: Generation }) {
+ if (g.status === "queued" || g.status === "running") {
+ const pct = g.progress != null ? Math.round(g.progress * 100) : null;
+ return (
+ <div className="relative size-full bg-muted">
+ <div className="skeleton-sweep absolute inset-0 animate-skeleton" />
+ <div className="absolute inset-x-0 bottom-0 p-3">
+ <p className="shimmer-text animate-shimmer-text truncate text-[13px] font-medium">{g.message ?? (g.status === "queued" ? "Queued" : "Generating…")}</p>
+ <p className="font-mono text-[11px] text-muted-foreground">
+ {pct != null ? `${pct}% · ` : ""}
+ {elapsed(g.createdAt)}
+ </p>
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div className="flex size-full flex-col justify-between border border-dashed bg-background p-3">
+ <div className="min-h-0 space-y-1 overflow-hidden">
+ <p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>
+ {g.error && <p className="line-clamp-4 text-[12px] leading-snug break-words text-muted-foreground">{g.error}</p>}
+ </div>
+ </div>
+ );
+}
+
+function Cover({ g, fit }: { g: Generation; fit: boolean }) {
+ if (g.status !== "succeeded" || !g.outputs.length) return <StatusCover g={g} />;
+ if (isLayered(g)) return <LayersStack g={g} />;
+ return <MediaThumb output={g.outputs[0]} g={g} fit={fit} className={cn(fit && "bg-muted")} />;
+}
+
+function SelectDot({ selected, visible, onToggle, label }: { selected: boolean; visible: boolean; onToggle: (shift: boolean) => void; label: string }) {
+ return (
+ <button
+ role="checkbox"
+ aria-checked={selected}
+ aria-label={label}
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggle(e.shiftKey);
+ }}
+ className={cn(
+ "absolute top-2 left-2 z-10 grid size-6 place-items-center rounded-full border-2 transition-opacity",
+ selected ? "border-primary bg-primary text-primary-foreground" : "border-white/90 bg-black/25 text-transparent backdrop-blur",
+ visible || selected ? "opacity-100" : "opacity-0 group-hover/card:opacity-100 group-focus-within/card:opacity-100",
+ )}
+ >
+ <Check className="size-3.5" strokeWidth={3} />
+ </button>
+ );
+}
+
+export const AssetCard = memo(function AssetCard({
+ entry,
+ layout,
+ fit,
+ selecting,
+ selected,
+ expanded,
+ api,
+}: {
+ entry: LibraryEntry;
+ layout: Layout;
+ fit: boolean;
+ selecting: boolean;
+ selected: boolean;
+ expanded?: boolean;
+ api: CardApi;
+}) {
+ const canHover = useCanHover();
+ const [hot, setHot] = useState<false | "bar" | "menu">(false);
+ const stack = entry.type === "stack" ? entry : null;
+ const cover = useMemo(() => (stack ? coverOf(stack.items) : null), [stack]);
+ const g = stack ? (cover?.g ?? stack.items[0]) : (entry as Extract<LibraryEntry, { type: "single" }>).g;
+ const ids = useMemo(() => idsOf(entry), [entry]);
+ const title = stack ? stack.title : userTitle(g);
+ const trashed = !!g.deletedAt;
+ const done = g.status === "succeeded" && g.outputs.length > 0;
+ const ratio = cardRatio(entry, layout);
+
+ const activate = (shift: boolean) => {
+ if (selecting) api.toggle(entry.key, ids, shift);
+ else if (stack) api.expand(entry.key);
+ else if (done) api.open(g, 0);
+ };
+ const common = {
+ role: "button" as const,
+ tabIndex: 0,
+ "aria-label": stack ? `${title} — ${stack.label}` : title,
+ "aria-pressed": selecting ? selected : undefined,
+ "aria-expanded": stack ? !!expanded : undefined,
+ onClick: (e: React.MouseEvent) => activate(e.shiftKey),
+ onKeyDown: (e: React.KeyboardEvent) => {
+ if (e.target !== e.currentTarget) return;
+ if (e.key === "Enter" || (e.key === " " && selecting)) {
+ e.preventDefault();
+ activate(e.shiftKey);
+ }
+ },
+ draggable: canHover && !trashed,
+ onDragStart: (e: React.DragEvent) => {
+ const dragged = api.dragIds(ids);
+ e.dataTransfer.setData(DRAG_TYPE, JSON.stringify(dragged));
+ e.dataTransfer.setData("text/plain", `${dragged.length} item${dragged.length === 1 ? "" : "s"}`);
+ e.dataTransfer.effectAllowed = "move";
+ },
+ onPointerEnter: (e: React.PointerEvent) => e.pointerType === "mouse" && !hot && setHot("bar"),
+ onFocus: () => canHover && !hot && setHot("bar"),
+ };
+ const showActions = !selecting && !stack && done && g.outputs[0].kind !== "audio";
+ const badges = (
+ <>
+ {g.favorite && !stack && <Heart className="absolute top-2.5 right-2.5 size-4 fill-highlight text-highlight drop-shadow" />}
+ {!stack && g.outputs.length > 1 && !isLayered(g) && (
+ <span className="absolute top-2 right-8 rounded-full bg-black/55 px-1.5 py-0.5 font-mono text-[11px] text-white backdrop-blur">×{g.outputs.length}</span>
+ )}
+ {trashed && (
+ <span className="absolute bottom-2 left-2 rounded-full bg-background/85 px-2 py-0.5 text-[11px] font-medium backdrop-blur">
+ {trashDaysLeft(g.deletedAt!)} days left
+ </span>
+ )}
+ </>
+ );
+ const actions =
+ showActions &&
+ (canHover ? (
+ hot === "bar" && (
+ <TileActions
+ g={g}
+ index={0}
+ opts={api.runner}
+ className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent p-2 pt-8 opacity-0 transition-opacity duration-100 group-focus-within/card:opacity-100 group-hover/card:opacity-100"
+ />
+ )
+ ) : hot === "menu" ? (
+ <TileActions g={g} index={0} opts={api.runner} menuOnly className="absolute right-2 bottom-2" />
+ ) : (
+ <button
+ aria-label="More actions"
+ onClick={(e) => {
+ e.stopPropagation();
+ setHot("menu");
+ }}
+ className="absolute right-2 bottom-2 grid size-8 place-items-center rounded-lg bg-black/45 text-white backdrop-blur"
+ >
+ <MoreHorizontal className="size-4" />
+ </button>
+ ));
+
+ if (layout === "list") {
+ return (
+ <div
+ {...common}
+ className={cn(
+ "group/card relative flex min-h-16 cursor-pointer items-center gap-3 rounded-xl px-2 py-2 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
+ selected && "bg-brand-faint hover:bg-brand-faint-hover",
+ )}
+ >
+ <div className="relative size-14 shrink-0 overflow-hidden rounded-lg bg-muted">
+ {stack ? cover ? <SmallThumb output={cover.o} g={cover.g} /> : <StatusCover g={g} /> : done ? <SmallThumb output={g.outputs[0]} g={g} /> : <StatusCover g={g} />}
+ <SelectDot selected={selected} visible={selecting} onToggle={(s) => api.toggle(entry.key, ids, s)} label={`Select ${title}`} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[14px] font-medium">{title}</p>
+ <p className="truncate text-[12px] text-muted-foreground">
+ {stack ? `${stack.label} · ` : `${g.modelName ?? g.modelId} · ${OPERATION_LABELS[g.op]} · `}
+ {trashed ? `${trashDaysLeft(g.deletedAt!)} days left in Trash` : timeAgo(g.createdAt)}
+ {!stack && g.status !== "succeeded" && ` · ${g.status === "failed" ? "Failed" : g.status === "canceled" ? "Canceled" : "In progress"}`}
+ </p>
+ </div>
+ {g.favorite && !stack && <Heart className="size-4 shrink-0 fill-highlight text-highlight" />}
+ {stack && <ChevronDown className={cn("size-4 shrink-0 text-muted-foreground transition-transform", expanded && "rotate-180")} />}
+ {!stack && (g.status === "failed" || g.status === "canceled") && !trashed && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ api.retry(g);
+ }}
+ className="inline-flex h-7 shrink-0 items-center gap-1 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent"
+ >
+ <RotateCcw className="size-3" /> Retry
+ </button>
+ )}
+ {showActions &&
+ (hot === "menu" ? (
+ <TileActions g={g} index={0} opts={api.runner} menuOnly triggerClassName={LIST_MENU} />
+ ) : (
+ <button
+ aria-label="More actions"
+ onClick={(e) => {
+ e.stopPropagation();
+ setHot("menu");
+ }}
+ className={LIST_MENU}
+ >
+ <MoreHorizontal className="size-4" />
+ </button>
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <div className="group/card relative">
+ {stack && (
+ // The stack look: two sheets peeking out behind the cover.
+ <>
+ <div className="absolute inset-x-3 -top-1.5 h-4 rounded-xl bg-border" aria-hidden />
+ <div className="absolute inset-x-1.5 -top-0.75 h-4 rounded-xl bg-border-strong" aria-hidden />
+ </>
+ )}
+ <div
+ {...common}
+ className={cn(
+ "relative w-full cursor-pointer overflow-hidden rounded-xl bg-muted outline-none transition-[box-shadow] focus-visible:ring-2 focus-visible:ring-ring",
+ !selecting && done && !stack && "cursor-zoom-in",
+ selected && "ring-3 ring-primary",
+ expanded && "ring-2 ring-border-strong",
+ )}
+ style={{ aspectRatio: ratio }}
+ >
+ {stack ? cover ? <MediaThumb output={cover.o} g={cover.g} fit={fit} /> : <StatusCover g={g} /> : <Cover g={g} fit={fit} />}
+ {selected && <div className="pointer-events-none absolute inset-0 bg-primary/15" />}
+ {stack && (
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 via-black/30 to-transparent p-3 pt-10 text-white">
+ <p className="line-clamp-2 font-heading text-[17px] leading-snug">{title}</p>
+ <p className="mt-0.5 flex items-center gap-1 text-[12px] text-white/80">
+ <Layers className="size-3" /> {stack.label}
+ </p>
+ </div>
+ )}
+ {badges}
+ <SelectDot selected={selected} visible={selecting} onToggle={(s) => api.toggle(entry.key, ids, s)} label={`Select ${title}`} />
+ {actions}
+ {!stack && (g.status === "failed" || g.status === "canceled") && !trashed && !selecting && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ api.retry(g);
+ }}
+ className="absolute bottom-2 left-2 inline-flex h-7 items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent"
+ >
+ <RotateCcw className="size-3" /> Retry
+ </button>
+ )}
+ </div>
+ </div>
+ );
+});
diff --git a/src/components/library/filters.tsx b/src/components/library/filters.tsx
new file mode 100644
index 00000000..f6fddeb6
--- /dev/null
+++ b/src/components/library/filters.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import { Calendar, Check, ChevronDown, CircleDot, Cpu, X } from "lucide-react";
+import { useState } from "react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import type { LibraryFacets } from "@/lib/api";
+import type { GenerationStatus } from "@/lib/catalog/types";
+import { dayStart } from "@/lib/library";
+import { cn } from "@/lib/utils";
+
+export type DateRange = { id: "any" | "today" | "7d" | "30d" } | { id: "custom"; from: string; to: string };
+export type StatusFilter = "all" | "done" | "active" | "failed" | "hide-failed";
+
+export interface Filters {
+ models: string[];
+ date: DateRange;
+ status: StatusFilter;
+}
+
+export const NO_FILTERS: Filters = { models: [], date: { id: "any" }, status: "all" };
+
+const DAY = 86_400_000;
+
+/** Filters → FeedFilter fields (createdAt range and statuses). */
+export function filterFields(f: Filters, now = Date.now()): { models?: string[]; since?: number; until?: number; statuses?: GenerationStatus[] } {
+ const out: { models?: string[]; since?: number; until?: number; statuses?: GenerationStatus[] } = {};
+ if (f.models.length) out.models = f.models;
+ const d = f.date;
+ if (d.id === "today") out.since = dayStart(now);
+ else if (d.id === "7d") out.since = dayStart(now - 6 * DAY);
+ else if (d.id === "30d") out.since = dayStart(now - 29 * DAY);
+ else if (d.id === "custom") {
+ if (d.from) out.since = new Date(`${d.from}T00:00:00`).getTime();
+ if (d.to) out.until = new Date(`${d.to}T00:00:00`).getTime() + DAY;
+ }
+ if (f.status === "done") out.statuses = ["succeeded"];
+ else if (f.status === "active") out.statuses = ["queued", "running"];
+ else if (f.status === "failed") out.statuses = ["failed", "canceled"];
+ else if (f.status === "hide-failed") out.statuses = ["queued", "running", "succeeded"];
+ return out;
+}
+
+export const hasFilters = (f: Filters) => f.models.length > 0 || f.date.id !== "any" || f.status !== "all";
+
+function Chip({ active, children, ...props }: { active: boolean; children: React.ReactNode } & React.ComponentProps<"button">) {
+ return (
+ <button
+ {...props}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors",
+ active ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+function Option({ checked, onClick, children }: { checked: boolean; onClick: () => void; children: React.ReactNode }) {
+ return (
+ <button
+ role="menuitemcheckbox"
+ aria-checked={checked}
+ onClick={onClick}
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] transition-colors hover:bg-accent"
+ >
+ <span className={cn("grid size-4 shrink-0 place-items-center rounded border", checked && "border-primary bg-primary text-primary-foreground")}>{checked && <Check className="size-3" />}</span>
+ <span className="min-w-0 flex-1 truncate">{children}</span>
+ </button>
+ );
+}
+
+const DATES: { id: Exclude<DateRange["id"], "custom">; label: string }[] = [
+ { id: "any", label: "Any time" },
+ { id: "today", label: "Today" },
+ { id: "7d", label: "Last 7 days" },
+ { id: "30d", label: "Last 30 days" },
+];
+
+const STATUSES: { id: StatusFilter; label: string }[] = [
+ { id: "all", label: "Any status" },
+ { id: "done", label: "Finished" },
+ { id: "active", label: "In progress" },
+ { id: "failed", label: "Failed" },
+ { id: "hide-failed", label: "Hide failed" },
+];
+
+export function FilterBar({ value, onChange, facets }: { value: Filters; onChange: (f: Filters) => void; facets?: LibraryFacets }) {
+ const [custom, setCustom] = useState<{ from: string; to: string }>(value.date.id === "custom" ? { from: value.date.from, to: value.date.to } : { from: "", to: "" });
+ const models = facets?.models ?? [];
+ const modelLabel = value.models.length === 0 ? "Any model" : value.models.length === 1 ? (models.find((m) => m.id === value.models[0])?.name ?? "1 model") : `${value.models.length} models`;
+ const d = value.date;
+ const dateLabel = d.id === "custom" ? [d.from, d.to].filter(Boolean).join(" → ") || "Custom range" : DATES.find((x) => x.id === d.id)!.label;
+ return (
+ <div className="scrollbar-none -mx-1 flex items-center gap-1.5 overflow-x-auto px-1 py-0.5">
+ <Popover>
+ <PopoverTrigger asChild>
+ <Chip active={value.models.length > 0}>
+ <Cpu className="size-3.5" /> {modelLabel} <ChevronDown className="size-3.5 opacity-60" />
+ </Chip>
+ </PopoverTrigger>
+ <PopoverContent align="start" collisionPadding={12} className="max-h-80 w-[min(92vw,280px)] overflow-y-auto p-1.5">
+ {models.length === 0 && <p className="px-2 py-1.5 text-[13px] text-muted-foreground">Nothing made yet</p>}
+ {models.map((m) => (
+ <Option
+ key={m.id}
+ checked={value.models.includes(m.id)}
+ onClick={() => onChange({ ...value, models: value.models.includes(m.id) ? value.models.filter((x) => x !== m.id) : [...value.models, m.id] })}
+ >
+ {m.name} <span className="font-mono text-[11px] text-muted-foreground">{m.count}</span>
+ </Option>
+ ))}
+ </PopoverContent>
+ </Popover>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Chip active={d.id !== "any"}>
+ <Calendar className="size-3.5" /> {dateLabel} <ChevronDown className="size-3.5 opacity-60" />
+ </Chip>
+ </PopoverTrigger>
+ <PopoverContent align="start" collisionPadding={12} className="w-[min(92vw,280px)] space-y-2 p-1.5">
+ <div>
+ {DATES.map((x) => (
+ <Option key={x.id} checked={d.id === x.id} onClick={() => onChange({ ...value, date: { id: x.id } })}>
+ {x.label}
+ </Option>
+ ))}
+ </div>
+ <div className="space-y-2 border-t px-2 pt-2 pb-1">
+ <p className="text-[12px] font-medium text-muted-foreground">Custom range</p>
+ <div className="grid grid-cols-2 gap-2">
+ <label className="space-y-1 text-[11px] text-muted-foreground">
+ From
+ <input type="date" value={custom.from} max={custom.to || undefined} onChange={(e) => setCustom({ ...custom, from: e.target.value })} className="h-8 w-full rounded-md border bg-background px-2 text-[13px] text-foreground" />
+ </label>
+ <label className="space-y-1 text-[11px] text-muted-foreground">
+ To
+ <input type="date" value={custom.to} min={custom.from || undefined} onChange={(e) => setCustom({ ...custom, to: e.target.value })} className="h-8 w-full rounded-md border bg-background px-2 text-[13px] text-foreground" />
+ </label>
+ </div>
+ <button
+ disabled={!custom.from && !custom.to}
+ onClick={() => onChange({ ...value, date: { id: "custom", ...custom } })}
+ className="h-8 w-full rounded-full bg-primary text-[13px] font-medium text-primary-foreground disabled:opacity-50"
+ >
+ Apply range
+ </button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Chip active={value.status !== "all"}>
+ <CircleDot className="size-3.5" /> {STATUSES.find((s) => s.id === value.status)!.label}
+ {facets?.failed && value.status === "all" ? <span className="font-mono text-[11px] text-muted-foreground">{facets.failed} failed</span> : null}
+ <ChevronDown className="size-3.5 opacity-60" />
+ </Chip>
+ </PopoverTrigger>
+ <PopoverContent align="start" collisionPadding={12} className="w-[min(92vw,220px)] p-1.5">
+ {STATUSES.map((s) => (
+ <Option key={s.id} checked={value.status === s.id} onClick={() => onChange({ ...value, status: s.id })}>
+ {s.label}
+ </Option>
+ ))}
+ </PopoverContent>
+ </Popover>
+ {hasFilters(value) && (
+ <button onClick={() => onChange(NO_FILTERS)} className="inline-flex h-8 shrink-0 items-center gap-1 rounded-full px-2.5 text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground">
+ <X className="size-3.5" /> Clear filters
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/library/folders.tsx b/src/components/library/folders.tsx
new file mode 100644
index 00000000..8b10473d
--- /dev/null
+++ b/src/components/library/folders.tsx
@@ -0,0 +1,252 @@
+"use client";
+
+import { Check, ChevronLeft, Folder as FolderIcon, FolderPlus, MoreHorizontal, Pencil, Trash2 } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { useFolderActions } from "@/lib/api";
+import { DEFAULT_FOLDER_COLOR, FOLDER_COLORS, folderSwatch, type Folder } from "@/lib/library";
+import { cn } from "@/lib/utils";
+import { MediaThumb } from "@/components/studio/result-media";
+
+/** Generation ids dragged from a card (the selection when the card is selected). */
+export const DRAG_TYPE = "application/x-fuobe-generations";
+
+export function readDrag(e: React.DragEvent): string[] | null {
+ if (!e.dataTransfer.types.includes(DRAG_TYPE)) return null;
+ try {
+ return JSON.parse(e.dataTransfer.getData(DRAG_TYPE)) as string[];
+ } catch {
+ return null;
+ }
+}
+
+/** A drop target for dragged cards (folders, the "Library" crumb). */
+export function useDropTarget(onDrop: (ids: string[]) => void) {
+ const [over, setOver] = useState(false);
+ return {
+ over,
+ props: {
+ onDragOver: (e: React.DragEvent) => {
+ if (!e.dataTransfer.types.includes(DRAG_TYPE)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ setOver(true);
+ },
+ onDragLeave: () => setOver(false),
+ onDrop: (e: React.DragEvent) => {
+ setOver(false);
+ const ids = readDrag(e);
+ if (!ids?.length) return;
+ e.preventDefault();
+ onDrop(ids);
+ },
+ },
+ };
+}
+
+export function FolderDialog({ folder, open, onOpenChange, onSaved }: { folder?: Folder; open: boolean; onOpenChange: (v: boolean) => void; onSaved?: (f: Folder) => void }) {
+ const actions = useFolderActions();
+ const [name, setName] = useState(folder?.name ?? "");
+ const [color, setColor] = useState(folder?.color ?? DEFAULT_FOLDER_COLOR);
+ const [busy, setBusy] = useState(false);
+ const save = async () => {
+ setBusy(true);
+ try {
+ const f = folder ? await actions.update(folder.id, { name, color }) : await actions.create({ name, color });
+ onOpenChange(false);
+ onSaved?.(f);
+ if (!folder) toast.success(`Created “${f.name}”`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="w-[min(92vw,400px)] gap-4">
+ <DialogTitle className="font-heading text-[22px] font-normal">{folder ? "Edit folder" : "New folder"}</DialogTitle>
+ <DialogDescription className="sr-only">Name and colour</DialogDescription>
+ <form
+ className="space-y-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (name.trim()) void save();
+ }}
+ >
+ <input
+ autoFocus
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ maxLength={60}
+ placeholder="e.g. “Spring campaign”"
+ aria-label="Folder name"
+ className="h-10 w-full rounded-lg border bg-background px-3 text-[15px] outline-none focus:border-primary focus:ring-4 focus:ring-brand-faint"
+ />
+ <div role="radiogroup" aria-label="Colour" className="flex flex-wrap gap-2">
+ {FOLDER_COLORS.map((c) => (
+ <button
+ key={c.id}
+ type="button"
+ role="radio"
+ aria-checked={color === c.id}
+ aria-label={c.label}
+ title={c.label}
+ onClick={() => setColor(c.id)}
+ className={cn("grid size-8 place-items-center rounded-full ring-offset-2 ring-offset-background transition", color === c.id && "ring-2 ring-foreground")}
+ style={{ background: folderSwatch(c.id) }}
+ >
+ {color === c.id && <Check className="size-4 text-black/70" />}
+ </button>
+ ))}
+ </div>
+ <div className="flex justify-end gap-2">
+ <button type="button" onClick={() => onOpenChange(false)} className="h-9 rounded-full px-4 text-[13px] font-medium text-muted-foreground hover:bg-accent">
+ Cancel
+ </button>
+ <button type="submit" disabled={busy || !name.trim()} className="h-9 rounded-full bg-primary px-4 text-[13px] font-medium text-primary-foreground disabled:opacity-50">
+ {folder ? "Save" : "Create folder"}
+ </button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function FolderCard({ folder, onOpen, onDropIds }: { folder: Folder; onOpen: () => void; onDropIds: (ids: string[]) => void }) {
+ const drop = useDropTarget(onDropIds);
+ return (
+ <button
+ onClick={onOpen}
+ {...drop.props}
+ className={cn(
+ "group flex w-[min(44vw,190px)] shrink-0 items-center gap-2.5 rounded-xl border bg-background p-2 text-left transition-[background-color,box-shadow,border-color] hover:bg-accent",
+ drop.over && "border-primary shadow-heavy ring-4 ring-brand-faint",
+ )}
+ >
+ <span className="relative grid size-11 shrink-0 place-items-center overflow-hidden rounded-lg" style={{ background: folderSwatch(folder.color) }}>
+ {folder.cover ? <MediaThumb output={folder.cover} className="pointer-events-none" /> : <FolderIcon className="size-5 text-black/60" />}
+ {folder.cover && <span className="absolute inset-x-0 bottom-0 h-1.5" style={{ background: folderSwatch(folder.color) }} />}
+ </span>
+ <span className="min-w-0">
+ <span className="block truncate text-[13px] font-medium">{folder.name}</span>
+ <span className="block text-[12px] text-muted-foreground">{drop.over ? "Drop to move here" : `${folder.count} item${folder.count === 1 ? "" : "s"}`}</span>
+ </span>
+ </button>
+ );
+}
+
+export function FolderStrip({ folders, onOpen, onMove }: { folders: Folder[]; onOpen: (f: Folder) => void; onMove: (ids: string[], f: Folder) => void }) {
+ const [creating, setCreating] = useState(false);
+ return (
+ <div className="scrollbar-none -mx-1 flex gap-2 overflow-x-auto px-1 py-1">
+ {folders.map((f) => (
+ <FolderCard key={f.id} folder={f} onOpen={() => onOpen(f)} onDropIds={(ids) => onMove(ids, f)} />
+ ))}
+ <button
+ onClick={() => setCreating(true)}
+ className="flex w-[min(44vw,160px)] shrink-0 items-center gap-2.5 rounded-xl border border-dashed p-2 text-left text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ >
+ <span className="grid size-11 shrink-0 place-items-center rounded-lg bg-muted">
+ <FolderPlus className="size-5" />
+ </span>
+ <span className="text-[13px] font-medium">New folder</span>
+ </button>
+ {creating && <FolderDialog open onOpenChange={setCreating} />}
+ </div>
+ );
+}
+
+/** Folder view header: back to the Library (also a drop target to take items out), rename, colour, delete. */
+export function FolderHeader({ folder, onBack, onMoveOut }: { folder: Folder; onBack: () => void; onMoveOut: (ids: string[]) => void }) {
+ const actions = useFolderActions();
+ const [editing, setEditing] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const drop = useDropTarget(onMoveOut);
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <button
+ onClick={onBack}
+ {...drop.props}
+ className={cn("inline-flex h-8 shrink-0 items-center gap-1 rounded-full pr-3 pl-2 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground", drop.over && "bg-brand-faint text-brand-text ring-4 ring-brand-faint")}
+ >
+ <ChevronLeft className="size-4" /> {drop.over ? "Drop to take out" : "Library"}
+ </button>
+ <span className="size-3 shrink-0 rounded-full" style={{ background: folderSwatch(folder.color) }} />
+ <h2 className="min-w-0 truncate font-heading text-[24px] leading-none">{folder.name}</h2>
+ <span className="shrink-0 text-[13px] text-muted-foreground">{folder.count}</span>
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild>
+ <button className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Folder actions">
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuItem onSelect={() => setEditing(true)}>
+ <Pencil /> Rename or recolour
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => setDeleting(true)}>
+ <Trash2 /> Delete folder
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {editing && <FolderDialog folder={folder} open onOpenChange={setEditing} />}
+ <AlertDialog open={deleting} onOpenChange={setDeleting}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete “{folder.name}”?</AlertDialogTitle>
+ <AlertDialogDescription>The folder goes away; the {folder.count} item{folder.count === 1 ? "" : "s"} in it stay in your Library.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={async () => {
+ await actions.remove(folder.id);
+ toast("Folder deleted");
+ onBack();
+ }}
+ >
+ Delete folder
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+/** "Move to folder" choices for the bulk bar and card menus. */
+export function MoveMenuItems({ folders, current, onMove, onNew }: { folders: Folder[]; current?: string; onMove: (folderId: string | null, name: string) => void; onNew: () => void }) {
+ return (
+ <>
+ {folders.map((f) => (
+ <DropdownMenuItem key={f.id} disabled={f.id === current} onSelect={() => onMove(f.id, f.name)}>
+ <span className="size-3 rounded-full" style={{ background: folderSwatch(f.color) }} /> {f.name}
+ </DropdownMenuItem>
+ ))}
+ {current && (
+ <DropdownMenuItem onSelect={() => onMove(null, "Library")}>
+ <ChevronLeft /> Take out of the folder
+ </DropdownMenuItem>
+ )}
+ {folders.length > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuItem onSelect={onNew}>
+ <FolderPlus /> New folder…
+ </DropdownMenuItem>
+ </>
+ );
+}
diff --git a/src/components/library/view-options.tsx b/src/components/library/view-options.tsx
new file mode 100644
index 00000000..1ec458dc
--- /dev/null
+++ b/src/components/library/view-options.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { LayoutGrid, LayoutList, Rows3, SlidersHorizontal } from "lucide-react";
+import { useCallback, useSyncExternalStore } from "react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Switch } from "@/components/ui/switch";
+import { cn } from "@/lib/utils";
+
+export type Layout = "square" | "masonry" | "list";
+
+export interface ViewPrefs {
+ layout: Layout;
+ fit: boolean;
+ /** Card width in px (grid column minimum). */
+ size: number;
+ splitByDate: boolean;
+ stacks: boolean;
+}
+
+const KEY = "fuobe.library.view";
+const DEFAULTS: ViewPrefs = { layout: "masonry", fit: false, size: 220, splitByDate: true, stacks: true };
+const listeners = new Set<() => void>();
+let cache: { raw: string | null; value: ViewPrefs } | null = null;
+
+function read(): ViewPrefs {
+ let raw: string | null = null;
+ try {
+ raw = localStorage.getItem(KEY);
+ } catch {}
+ if (cache?.raw === raw) return cache.value;
+ let value = DEFAULTS;
+ try {
+ value = raw ? { ...DEFAULTS, ...(JSON.parse(raw) as Partial<ViewPrefs>) } : DEFAULTS;
+ } catch {}
+ cache = { raw, value };
+ return value;
+}
+
+/** Layout, Fit/Fill, card size, split by date and stacks, remembered in this browser. */
+export function useViewPrefs(): [ViewPrefs, (patch: Partial<ViewPrefs>) => void] {
+ const prefs = useSyncExternalStore(
+ (cb) => {
+ listeners.add(cb);
+ return () => listeners.delete(cb);
+ },
+ read,
+ () => DEFAULTS,
+ );
+ const set = useCallback((patch: Partial<ViewPrefs>) => {
+ try {
+ localStorage.setItem(KEY, JSON.stringify({ ...read(), ...patch }));
+ } catch {}
+ listeners.forEach((l) => l());
+ }, []);
+ return [prefs, set];
+}
+
+const LAYOUTS: { id: Layout; label: string; icon: typeof LayoutGrid }[] = [
+ { id: "square", label: "Square", icon: LayoutGrid },
+ { id: "masonry", label: "Masonry", icon: Rows3 },
+ { id: "list", label: "List", icon: LayoutList },
+];
+
+function Segmented<T extends string>({ value, options, onChange, label }: { value: T; options: { id: T; label: string; icon?: typeof LayoutGrid }[]; onChange: (v: T) => void; label: string }) {
+ return (
+ <div role="radiogroup" aria-label={label} className="flex rounded-full bg-muted p-0.5">
+ {options.map((o) => (
+ <button
+ key={o.id}
+ role="radio"
+ aria-checked={value === o.id}
+ onClick={() => onChange(o.id)}
+ className={cn(
+ "inline-flex h-7 flex-1 items-center justify-center gap-1.5 rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap transition-colors",
+ value === o.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {o.icon && <o.icon className="size-3.5" />} {o.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+export function ViewOptions({ prefs, onChange }: { prefs: ViewPrefs; onChange: (patch: Partial<ViewPrefs>) => void }) {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium text-secondary-foreground transition-colors hover:bg-accent" aria-label="View options">
+ <SlidersHorizontal className="size-3.5" /> <span className="hidden sm:inline">View</span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="end" collisionPadding={12} className="w-[min(92vw,300px)] space-y-4">
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium text-muted-foreground">Layout</p>
+ <Segmented label="Layout" value={prefs.layout} options={LAYOUTS} onChange={(layout) => onChange({ layout })} />
+ </div>
+ {prefs.layout !== "list" && (
+ <>
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium text-muted-foreground">Previews</p>
+ <Segmented
+ label="Previews"
+ value={prefs.fit ? "fit" : "fill"}
+ options={[
+ { id: "fill", label: "Fill" },
+ { id: "fit", label: "Fit" },
+ ]}
+ onChange={(v) => onChange({ fit: v === "fit" })}
+ />
+ </div>
+ <label className="block space-y-1.5">
+ <span className="flex justify-between text-[12px] font-medium text-muted-foreground">
+ Card size <span className="font-mono">{prefs.size}px</span>
+ </span>
+ <input
+ type="range"
+ min={120}
+ max={380}
+ step={10}
+ value={prefs.size}
+ onChange={(e) => onChange({ size: Number(e.target.value) })}
+ className="w-full accent-primary"
+ />
+ </label>
+ </>
+ )}
+ <label className="flex items-center justify-between gap-3 text-[13px]">
+ Split by date
+ <Switch checked={prefs.splitByDate} onCheckedChange={(splitByDate) => onChange({ splitByDate })} />
+ </label>
+ <label className="flex items-center justify-between gap-3 text-[13px]">
+ <span>
+ Stack batches
+ <span className="block text-[12px] text-muted-foreground">Storyboards, films and takes as one card</span>
+ </span>
+ <Switch checked={prefs.stacks} onCheckedChange={(stacks) => onChange({ stacks })} />
+ </label>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index cd76bb07..2eca3d61 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -251,6 +251,7 @@ export function TileActions({
opts,
menuOnly,
className,
+ triggerClassName,
}: {
g: Generation;
index: number;
@@ -258,6 +259,8 @@ export function TileActions({
opts?: RunnerOptions;
menuOnly?: boolean;
className?: string;
+ /** menuOnly: the ⋯ button's look (default: white on a dark chip, for media). */
+ triggerClassName?: string;
}) {
const run = useActionRunner(opts);
const list = useMemo(() => outputActions(g, index, ctx), [g, index, ctx]);
@@ -273,7 +276,7 @@ export function TileActions({
if (menuOnly) {
return (
<div className={className} onClick={stop} onKeyDown={stop}>
- <ActionMenu g={g} index={index} list={list} run={run} onSave={() => setSaving(true)} defaultOpen triggerClassName={cn(TILE_ICON, "bg-black/45 backdrop-blur")} />
+ <ActionMenu g={g} index={index} list={list} run={run} onSave={() => setSaving(true)} defaultOpen triggerClassName={triggerClassName ?? cn(TILE_ICON, "bg-black/45 backdrop-blur")} />
{popover}
</div>
);
diff --git a/src/components/studio/result-media.tsx b/src/components/studio/result-media.tsx
index c1b1ea2f..c1e203f9 100644
--- a/src/components/studio/result-media.tsx
+++ b/src/components/studio/result-media.tsx
@@ -3,7 +3,7 @@
import { AudioLines, Box, FileText, Layers } from "lucide-react";
import { createElement, useEffect, useState } from "react";
import type { Generation, OutputFile } from "@/lib/catalog/types";
-import { cuesOf, cueTime, layerInfo, modelPreview, textOf } from "@/lib/output-actions";
+import { cuesOf, cueTime, isLayered, layerInfo, modelPreview, textOf } from "@/lib/output-actions";
import { cn } from "@/lib/utils";
/** Any result as a tile picture: image, video (plays on hover), audio, text card, 3D preview. */
@@ -70,6 +70,20 @@ export function MediaThumb({
return <img src={output.url} alt="" loading="lazy" decoding="async" className={cn("size-full", object, className)} />;
}
+/** A 56 px thumbnail for list rows: media where it reads at that size, an icon where it doesn't. */
+export function SmallThumb({ g, output }: { g: Generation; output: OutputFile }) {
+ if (output.kind === "audio" || output.kind === "text") {
+ const Icon = output.kind === "audio" ? AudioLines : FileText;
+ return (
+ <div className="grid size-full place-items-center bg-brand-faint text-brand-text">
+ <Icon className="size-5" />
+ </div>
+ );
+ }
+ if (isLayered(g)) return <LayersStack g={g} bare />;
+ return <MediaThumb output={output} g={g} />;
+}
+
/** A transcript, translation or script as a readable card: the first lines and a cue count. */
export function TextPreview({ output, className }: { output: OutputFile; className?: string }) {
const cues = cuesOf(output);
@@ -105,16 +119,20 @@ export function TextReader({ output }: { output: OutputFile }) {
}
/** Layers of one picture as a stack: the composite on a checkerboard and the layer names. */
-export function LayersStack({ g, className }: { g: Generation; className?: string }) {
+export function LayersStack({ g, className, bare }: { g: Generation; className?: string; bare?: boolean }) {
const layers = g.outputs.map((o, i) => ({ o, ...layerInfo(o, i) })).sort((a, b) => a.z - b.z);
+ const composite = (
+ <div className="checkerboard absolute inset-0">
+ {layers.map((l) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={l.o.url} src={l.o.url} alt="" loading="lazy" decoding="async" className="absolute inset-0 size-full object-contain" />
+ ))}
+ </div>
+ );
+ if (bare) return <div className={cn("relative size-full overflow-hidden", className)}>{composite}</div>;
return (
<div className={cn("relative size-full overflow-hidden", className)}>
- <div className="checkerboard absolute inset-0">
- {layers.map((l) => (
- // eslint-disable-next-line @next/next/no-img-element
- <img key={l.o.url} src={l.o.url} alt="" loading="lazy" decoding="async" className="absolute inset-0 size-full object-contain" />
- ))}
- </div>
+ {composite}
<div className="absolute top-2 left-2 flex max-w-[calc(100%-1rem)] flex-wrap gap-1">
<span className="inline-flex h-6 items-center gap-1 rounded-full bg-black/55 px-2 text-[11px] font-medium text-white backdrop-blur">
<Layers className="size-3" /> {layers.length} layers
diff --git a/src/components/studio/viewer.tsx b/src/components/studio/viewer.tsx
index 3d313dc3..258e2a79 100644
--- a/src/components/studio/viewer.tsx
+++ b/src/components/studio/viewer.tsx
@@ -42,6 +42,18 @@ function ignoreKey(e: KeyboardEvent): boolean {
function Details({ g, index }: { g: Generation; index: number }) {
const p = g.request.params ?? {};
const title = userTitle(g);
+ if (g.feature === "upload") {
+ return (
+ <div className="space-y-4">
+ <p className="font-heading text-[20px] leading-snug break-words">{title}</p>
+ <div className="divide-y rounded-lg border px-3">
+ <Row label="Source" value="Your upload" />
+ <Row label="Type" value={g.outputs[index]?.contentType} />
+ <Row label="Added" value={timeAgo(g.createdAt)} />
+ </div>
+ </div>
+ );
+ }
return (
<div className="space-y-4">
<div>
@@ -178,7 +190,8 @@ export function Viewer({
const primary = list.find((a) => a.placement === "primary");
const bar = list.filter((a) => a.placement === "bar");
- const menu = list.filter((a) => a.placement === "menu");
+ // "Copy prompt" sits under the title in the details, so it isn't repeated as a button.
+ const menu = list.filter((a) => a.placement === "menu" && a.id !== "copy-prompt");
const actionButton = (a: OutputAction, opts: { variant?: "default" | "secondary" | "ghost"; className?: string; onDone?: () => void } = {}) => {
const Icon = ACTION_ICONS[a.id];
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 356d9dc4..f95813a2 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -318,6 +318,19 @@ export function useGenerationActions() {
}, [qc]);
}
+/** Files you uploaded (the Library's Uploads tab), newest first. */
+export function useUploads(kind?: MediaKind) {
+ return useQuery({
+ queryKey: ["assets", "upload", kind, 200],
+ queryFn: async () => {
+ const qs = new URLSearchParams({ source: "upload", limit: "200" });
+ if (kind) qs.set("kind", kind);
+ return (await json<{ items: Asset[] }>(await fetch(`/api/assets?${qs}`))).items;
+ },
+ placeholderData: keepPreviousData,
+ });
+}
+
// ---------------------------------------------------------------------------
// Library folders
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 72395c42..fd90e806 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -107,6 +107,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
out.push({ ...file, label: `Download .${ext}` }, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
break;
}
+ // Uploads (the Library's Uploads tab) are files, not generations: hand-offs and download only.
+ if (g.feature === "upload") return out.filter((a) => a.id !== "favorite");
if (g.outputs.length > 1) out.push({ id: "download-all", label: `Download all ${g.outputs.length} (.zip)`, placement: "menu", href: `/api/generations/zip?ids=${g.id}`, download: "" });
if (o.draftId) out.push({ id: "finalize", label: "Render this draft in 1080p", placement: "menu" });
if (ctx.compare) out.push({ id: "compare", label: "Compare with original", placement: "menu" });
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 0bdc7abb..73bd8706 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -75,6 +75,8 @@ describe("outputActions", () => {
expect(outputActions(layers, 1).find((a) => a.id === "download-all")?.href).toBe(`/api/generations/zip?ids=${layers.id}`);
expect(outputActions(gen({ favorite: true }), 0)[2].label).toBe("Unfavorite");
expect(ids(gen({ deletedAt: 5 }))).toEqual(["primary:restore", "bar:download", "menu:delete-forever"]);
+ expect(ids(gen({ feature: "upload" }))).not.toContain("menu:delete");
+ expect(ids(gen({ feature: "upload" }))).not.toContain("bar:favorite");
expect(outputActions(gen(), 3)).toEqual([]);
});
});