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.

Sharing: Share and Publish in the Library, the viewer, folders and Cinema, and a Shared view

Claudef2bb6f69baec
diff --git a/src/app/(studio)/layout.tsx b/src/app/(studio)/layout.tsx
index c5e759ca..931737bd 100644
--- a/src/app/(studio)/layout.tsx
+++ b/src/app/(studio)/layout.tsx
@@ -1,5 +1,10 @@
import { StudioChrome } from "@/components/app-sidebar";
+import { ShareProvider } from "@/components/share/share-provider";
export default function StudioLayout({ children }: { children: React.ReactNode }) {
- return <StudioChrome>{children}</StudioChrome>;
+ return (
+ <StudioChrome>
+ <ShareProvider>{children}</ShareProvider>
+ </StudioChrome>
+ );
}
diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsx
index a902cf06..25a6c3c0 100644
--- a/src/components/cinema/workspace.tsx
+++ b/src/components/cinema/workspace.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Bot, ChevronLeft, Clapperboard, Copy, FileText, Folder, FolderOpen, FolderTree, Heart, Library, MoreHorizontal, Pin, PinOff, Settings2, Upload } from "lucide-react";
+import { Bot, ChevronLeft, Clapperboard, Copy, FileText, Folder, FolderOpen, FolderTree, Heart, Library, MoreHorizontal, Pin, PinOff, Settings2, Share2, Upload } from "lucide-react";
import { nanoid } from "nanoid";
import dynamic from "next/dynamic";
import Link from "next/link";
@@ -30,6 +30,7 @@ import { formatUsd } from "./money";
import { foreign, useAutosave, useCinemaGenerate, useCinemaItems, useCinemaProject, useItemActions, useStudioGenerations, useUpdateProject, type CinemaGeneration, type ProjectView } from "./hooks";
import { cutGrid } from "./media";
import { ProjectDialog } from "./project-settings";
+import { useShare } from "@/components/share/share-provider";
import { PromptBar, useAddRefs } from "./prompt-bar";
import { SceneCreateDialog, askSceneConfirmAgain, sceneTake, skipSceneConfirm, usePlanPrice, useScenePlan, type SceneTake } from "./scene-actions";
import { SidePanel } from "./side-panel";
@@ -164,6 +165,7 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
const { project, folders, spentUsd, context } = data;
const id = project.id;
const router = useRouter();
+ const share = useShare();
const [engine, setEngine] = useEngine();
const [view, setView] = useState<CinemaView>({ kind: "home" });
const [nested, setNested] = useState(true);
@@ -441,6 +443,16 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
</TooltipTrigger>
<TooltipContent>Project brief — prepended to every prompt</TooltipContent>
</Tooltip>
+ {share && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon-sm" onClick={() => share.share({ kind: "cinema", id, title: project.name })} aria-label="Share a read-only link" className="shrink-0 max-sm:hidden">
+ <Share2 />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Share a read-only link to the project&apos;s takes</TooltipContent>
+ </Tooltip>
+ )}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" aria-label="Project menu" className="shrink-0">
@@ -462,6 +474,11 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG
>
<Copy /> Copy link
</DropdownMenuItem>
+ {share && (
+ <DropdownMenuItem onClick={() => share.share({ kind: "cinema", id, title: project.name })}>
+ <Share2 /> Share read-only link…
+ </DropdownMenuItem>
+ )}
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href="/cinema">
diff --git a/src/components/library-view.tsx b/src/components/library-view.tsx
index a67300e0..443f2955 100644
--- a/src/components/library-view.tsx
+++ b/src/components/library-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArchiveRestore, CheckCheck, CheckSquare, ChevronUp, CircleDot, Download, FolderInput, Heart, Loader2, Pin, PinOff, Search, Trash2, X } from "lucide-react";
+import { ArchiveRestore, CheckCheck, CheckSquare, ChevronUp, CircleDot, Download, FolderInput, Globe, Heart, Loader2, Pin, PinOff, Search, Trash2, X } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -12,6 +12,8 @@ import { ReviewMenuItems } from "@/components/library/review";
import { UploadDeleteProvider } from "@/components/library/upload-delete";
import { useViewPrefs, ViewOptions, type ViewPrefs } from "@/components/library/view-options";
import { PageShell } from "@/components/page-shell";
+import { useShare } from "@/components/share/share-provider";
+import { SharedLinks } from "@/components/share/shared-links";
import { downloadUrl, ForeverConfirmProvider, useConfirmForever } from "@/components/studio/result-actions";
import { useEdgeFade } from "@/components/studio/use-edge-fade";
import { Viewer } from "@/components/studio/viewer";
@@ -28,14 +30,15 @@ import {
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Kbd } from "@/components/ui/kbd";
import { Skeleton } from "@/components/ui/skeleton";
-import { BULK_MAX, useCreateGeneration, useFolders, useGenerationActions, useLibrary, useLibraryFacets, useUploads, type Asset, type FeedFilter } from "@/lib/api";
+import { BULK_MAX, useCreateGeneration, useFolders, useGenerationActions, useLibrary, useLibraryFacets, useShares, useUploads, type Asset, type FeedFilter } from "@/lib/api";
import type { Generation, MediaKind } from "@/lib/catalog/types";
import { keyCombo, useModKey } from "@/lib/keys";
import { buildEntries, folderAndDescendants, reviewInfo, splitByDate, toggleAll, TRASH_DAYS, type LibraryEntry } from "@/lib/library";
import { isLayered, shownOutputs } from "@/lib/output-actions";
+import { isExpired } from "@/lib/share";
import { cn } from "@/lib/utils";
-type TabId = "all" | "images" | "videos" | "audio" | "text" | "3d" | "favorites" | "uploads" | "trash";
+type TabId = "all" | "images" | "videos" | "audio" | "text" | "3d" | "favorites" | "uploads" | "shared" | "trash";
const TABS: { id: TabId; label: string; kinds?: MediaKind[] }[] = [
{ id: "all", label: "All" },
@@ -46,6 +49,7 @@ const TABS: { id: TabId; label: string; kinds?: MediaKind[] }[] = [
{ id: "3d", label: "3D", kinds: ["model3d"] },
{ id: "favorites", label: "Favorites" },
{ id: "uploads", label: "Uploads" },
+ { id: "shared", label: "Shared" },
{ id: "trash", label: "Trash" },
];
@@ -216,6 +220,8 @@ function Inner() {
const folderId = sp.get("folder") ?? undefined;
const trash = tab.id === "trash";
const uploadsTab = tab.id === "uploads";
+ // Library → Shared: the share links, not results (no search, selection or filters there).
+ const sharedTab = tab.id === "shared";
const [q, setQ] = useState("");
const dq = useDebounced(q.trim(), 250);
const [chosen, setFilters] = useState<Filters>(NO_FILTERS);
@@ -245,9 +251,11 @@ function Inner() {
[tab, trash, folderId, subtree, dq, filters],
);
// Pinned results sit above the rest of the view (not in the Trash or Uploads); the Pinned filter shows only them.
- const split = !trash && !uploadsTab && !filters.pinned;
+ const split = !trash && !uploadsTab && !sharedTab && !filters.pinned;
const pinnedLib = useLibrary(useMemo(() => ({ ...filter, pinned: true, limit: 200 }), [filter]), { enabled: split });
- const lib = useLibrary(useMemo(() => (trash || uploadsTab ? filter : { ...filter, pinned: filters.pinned }), [filter, trash, uploadsTab, filters.pinned]));
+ const lib = useLibrary(useMemo(() => (trash || uploadsTab ? filter : { ...filter, pinned: filters.pinned }), [filter, trash, uploadsTab, filters.pinned]), { enabled: !sharedTab });
+ const shares = useShares();
+ const share = useShare();
const uploads = useUploads();
const pinnedItems = useMemo(() => (split ? (pinnedLib.data?.pages.flat() ?? []) : []), [split, pinnedLib.data]);
const mainItems = useMemo(() => {
@@ -416,6 +424,7 @@ function Inner() {
const f = facets.data;
if (!f) return undefined;
if (t.id === "trash") return f.trash || undefined;
+ if (t.id === "shared") return shares.data?.items.filter((x) => !x.gone && !isExpired(x)).length || undefined;
if (t.id === "favorites") return f.favorites || undefined;
if (t.kinds) return f.kinds[t.kinds[0]] || undefined;
return undefined;
@@ -496,7 +505,7 @@ function Inner() {
<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={cn("flex w-full items-center gap-2 sm:w-auto", sharedTab && "hidden")}>
<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
@@ -594,7 +603,7 @@ function Inner() {
</div>
) : null}
- {!uploadsTab && !missingFolder && (
+ {!uploadsTab && !sharedTab && !missingFolder && (
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
<FilterBar value={filters} onChange={setFilters} facets={facets.data} subfolders={!!folder?.folders} scoped={!!folderId || tab.id !== "all" || !!dq} trash={trash} />
{trash && (
@@ -610,7 +619,9 @@ function Inner() {
</div>
)}
- {missingFolder ? (
+ {sharedTab ? (
+ <SharedLinks />
+ ) : missingFolder ? (
<Empty title="This folder no longer exists">
It may have been deleted; what was in it is back in your Library.{" "}
<button onClick={() => go({ folder: undefined })} className="text-brand-text underline underline-offset-2">
@@ -704,7 +715,7 @@ function Inner() {
</div>
)}
- {(selecting || selected.size > 0) && !uploadsTab && (
+ {(selecting || selected.size > 0) && !uploadsTab && !sharedTab && (
<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">
{/* Phones show just the count, so every action fits at 390 px. */}
@@ -765,6 +776,14 @@ function Inner() {
<ReviewMenuItems value={sameReview} onPick={(r) => void actions.review(selectedGens, r).then((n) => n && toast(r ? `Marked ${n} as ${reviewInfo(r)?.label}` : `Cleared the review status of ${n}`))} />
</DropdownMenuContent>
</DropdownMenu>
+ {share && (
+ <BarButton
+ icon={Globe}
+ label="Publish"
+ disabled={!selectedGens.some((g) => g.status === "succeeded")}
+ onClick={() => share.publish(selectedGens.filter((g) => g.status === "succeeded"))}
+ />
+ )}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild disabled={!selectedGens.length}>
<button className={BAR} disabled={!selectedGens.length} aria-label="Move to">
diff --git a/src/components/library/folders.tsx b/src/components/library/folders.tsx
index c769d9b4..98b7d07a 100644
--- a/src/components/library/folders.tsx
+++ b/src/components/library/folders.tsx
@@ -1,8 +1,9 @@
"use client";
-import { Check, ChevronLeft, ChevronRight, Download, Folder as FolderIcon, FolderInput, FolderOpen, FolderPlus, MoreHorizontal, Pencil, Pin, PinOff, Trash2 } from "lucide-react";
+import { Check, ChevronLeft, ChevronRight, Download, Folder as FolderIcon, FolderInput, FolderOpen, FolderPlus, MoreHorizontal, Pencil, Pin, PinOff, Share2, Trash2 } from "lucide-react";
import { useRef, useState } from "react";
import { toast } from "sonner";
+import { useShare } from "@/components/share/share-provider";
import { downloadUrl, useCanHover } from "@/components/studio/result-actions";
import { MediaThumb } from "@/components/studio/result-media";
import {
@@ -243,6 +244,7 @@ async function downloadFolder(f: Folder, steps?: boolean) {
function FolderMenu({ folder, all, onOpen, onGone, steps, triggerClassName }: { folder: Folder; all: Folder[]; onOpen?: () => void; onGone?: () => void; steps?: boolean; triggerClassName: string }) {
const actions = useFolderActions();
const move = useMoveFolder(all);
+ const share = useShare();
const [dialog, setDialog] = useState<null | "edit" | "new" | "delete">(null);
const parent = folder.parentId ? all.find((f) => f.id === folder.parentId) : undefined;
// Open dialogs once the menu has closed and handed focus back, so the dialog keeps it.
@@ -291,6 +293,11 @@ function FolderMenu({ folder, all, onOpen, onGone, steps, triggerClassName }: {
<DropdownMenuItem onSelect={() => void downloadFolder(folder, steps)}>
<Download /> Download (.zip)
</DropdownMenuItem>
+ {share && (
+ <DropdownMenuItem onSelect={() => share.share({ kind: "folder", id: folder.id, title: folder.name })}>
+ <Share2 /> Share link…
+ </DropdownMenuItem>
+ )}
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onSelect={later("delete")}>
<Trash2 /> Delete folder
diff --git a/src/components/share/publish-wizard.tsx b/src/components/share/publish-wizard.tsx
new file mode 100644
index 00000000..1186e5e1
--- /dev/null
+++ b/src/components/share/publish-wizard.tsx
@@ -0,0 +1,309 @@
+"use client";
+
+import { ArrowDown, ArrowUp, Check, Eye, EyeOff, Globe, Loader2, X } from "lucide-react";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { MediaThumb } from "@/components/studio/result-media";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { useShareActions } from "@/lib/api";
+import type { Generation } from "@/lib/catalog/types";
+import { userTitle } from "@/lib/library";
+import { shownOutputs } from "@/lib/output-actions";
+import { MAX_TAGS, moveItem, parseTags, pieces, PUBLISH_LAYOUTS, type ShareCreated, type ShareLayout } from "@/lib/share";
+import { cn } from "@/lib/utils";
+import { ExpiryPicker } from "./share-dialog";
+
+const STEPS = ["Details", "Assets", "Cover", "Access"] as const;
+type Step = (typeof STEPS)[number];
+
+/** A publishable piece: finished, with something to show. */
+const publishable = (g: Generation) => g.status === "succeeded" && g.outputs.length > 0 && !g.deletedAt && g.feature !== "upload";
+
+/** The thumbnail of a piece: its first shown output. */
+const firstShown = (g: Generation) => shownOutputs(g)[0] ?? 0;
+
+/**
+ * Publish a selection as a portfolio page (Higgsfield's Publish wizard, made a share link):
+ * Details (title, description, tags) → Assets (Feature, Series or Carousel, in your order) →
+ * Cover → Access (with prompts or prompts hidden, and when the link stops working).
+ */
+export function PublishWizard({ items, onClose, onPublished }: { items: Generation[]; onClose: () => void; onPublished: (c: ShareCreated) => void }) {
+ const ready = useMemo(() => items.filter(publishable).slice(0, 100), [items]);
+ const skipped = items.length - ready.length;
+ const [step, setStep] = useState<Step>("Details");
+ const [title, setTitle] = useState("");
+ const [description, setDescription] = useState("");
+ const [tags, setTags] = useState("");
+ const [layout, setLayout] = useState<Exclude<ShareLayout, "grid">>("feature");
+ const [order, setOrder] = useState<Generation[]>(ready);
+ const [cover, setCover] = useState<{ generationId: string; index: number } | null>(null);
+ const [showPrompts, setShowPrompts] = useState(false);
+ const [days, setDays] = useState<number | null>(null);
+ const [busy, setBusy] = useState(false);
+ const actions = useShareActions();
+ const at = STEPS.indexOf(step);
+ const blocker = !title.trim() ? "Give the page a title" : !order.length ? "Keep at least one result" : null;
+ const coverOf = cover && order.some((g) => g.id === cover.generationId) ? cover : null;
+
+ const publish = async () => {
+ setBusy(true);
+ try {
+ onPublished(
+ await actions.create({ kind: "publish", items: order.map((g) => g.id), title, description, tags, layout, cover: coverOf, showPrompts, expiresInDays: days }),
+ );
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+ const next = () => {
+ if (step === "Details" && !title.trim()) return toast.error("Give the page a title first");
+ if (at < STEPS.length - 1) setStep(STEPS[at + 1]);
+ else if (!blocker && !busy) void publish();
+ };
+
+ return (
+ <Dialog open onOpenChange={(v) => !v && onClose()}>
+ <DialogContent className="max-h-[92svh] grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden sm:max-w-[600px]">
+ <DialogHeader>
+ <DialogTitle>Publish {pieces(order.length)}</DialogTitle>
+ <DialogDescription>
+ A read-only page anyone with the link can open.
+ {skipped > 0 && ` ${skipped} of your selection ${skipped === 1 ? "isn't" : "aren't"} finished, so ${skipped === 1 ? "it stays" : "they stay"} out.`}
+ </DialogDescription>
+ <ol className="mt-1 grid grid-cols-4 gap-1" aria-label="Steps">
+ {STEPS.map((s, i) => (
+ <li key={s}>
+ <button
+ type="button"
+ onClick={() => (i <= at || !blocker ? setStep(s) : undefined)}
+ disabled={i > at && (!title.trim() || !order.length)}
+ aria-current={s === step ? "step" : undefined}
+ className={cn(
+ "flex w-full flex-col items-start gap-1 rounded-lg px-1 pt-1 pb-1.5 text-left text-[12px] outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",
+ s === step ? "font-medium text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <span className={cn("h-1 w-full rounded-full", i <= at ? "bg-primary" : "bg-muted")} />
+ <span className="truncate">
+ <span className="max-sm:hidden">{i + 1}. </span>
+ {s}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ol>
+ </DialogHeader>
+
+ <form
+ id="publish-form"
+ className="-mx-4 min-h-0 overflow-y-auto px-4 py-1"
+ onSubmit={(e) => {
+ e.preventDefault();
+ next();
+ }}
+ >
+ {step === "Details" && (
+ <div className="grid gap-4">
+ <div className="grid gap-1.5">
+ <Label htmlFor="publish-title">Title</Label>
+ <Input id="publish-title" autoFocus value={title} maxLength={120} onChange={(e) => setTitle(e.target.value)} placeholder="Night city, a series" />
+ </div>
+ <div className="grid gap-1.5">
+ <Label htmlFor="publish-description">
+ Description <span className="font-normal text-muted-foreground">(optional)</span>
+ </Label>
+ <Textarea id="publish-description" value={description} maxLength={1000} rows={3} onChange={(e) => setDescription(e.target.value)} placeholder="What it is, how you made it" />
+ </div>
+ <div className="grid gap-1.5">
+ <Label htmlFor="publish-tags">
+ Tags <span className="font-normal text-muted-foreground">(optional, up to {MAX_TAGS})</span>
+ </Label>
+ <Input id="publish-tags" value={tags} onChange={(e) => setTags(e.target.value)} placeholder="cinematic, neon, portrait" aria-describedby="publish-tags-shown" />
+ <ul id="publish-tags-shown" className="flex min-h-5 flex-wrap gap-1" aria-label="Tags on the page">
+ {parseTags(tags).map((t) => (
+ <li key={t} className="rounded-full bg-brand-faint px-2 py-0.5 text-[11px] font-medium text-brand-text">
+ #{t}
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ )}
+
+ {step === "Assets" && (
+ <div className="grid gap-4">
+ <div role="radiogroup" aria-label="Layout" onKeyDown={radioKeys} className="grid gap-2 sm:grid-cols-3">
+ {PUBLISH_LAYOUTS.map((l) => {
+ const on = layout === l.id;
+ return (
+ <button
+ key={l.id}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ tabIndex={radioTab(on)}
+ onClick={() => setLayout(l.id)}
+ className={cn(
+ "flex items-start gap-3 rounded-xl border p-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring sm:flex-col sm:gap-2",
+ on ? "border-primary bg-brand-faint" : "hover:bg-muted/60",
+ )}
+ >
+ <LayoutGlyph layout={l.id} />
+ <span className="min-w-0">
+ <span className="block text-[13px] font-medium">{l.label}</span>
+ <span className="block text-[12px] leading-snug text-muted-foreground">{l.hint}</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ <div>
+ <p className="mb-1.5 text-[12px] text-muted-foreground">{layout === "series" ? "Episodes, in this order." : layout === "feature" ? "The cover's piece goes on top; the rest follow in this order." : "Slides, in this order."}</p>
+ <ol className="grid gap-1" aria-label="Order">
+ {order.map((g, i) => (
+ <li key={g.id} className="flex min-w-0 items-center gap-2 rounded-lg border p-1.5">
+ <span className="w-5 shrink-0 text-center font-mono text-[11px] text-muted-foreground">{i + 1}</span>
+ <MediaThumb output={g.outputs[firstShown(g)]} g={g} className="size-10 shrink-0 overflow-hidden rounded-md" />
+ <span className="min-w-0 flex-1 truncate text-[13px]">{userTitle(g)}</span>
+ <Button type="button" variant="ghost" size="icon-sm" disabled={i === 0} onClick={() => setOrder((o) => moveItem(o, i, i - 1))} aria-label={`Move ${i + 1} up`}>
+ <ArrowUp />
+ </Button>
+ <Button type="button" variant="ghost" size="icon-sm" disabled={i === order.length - 1} onClick={() => setOrder((o) => moveItem(o, i, i + 1))} aria-label={`Move ${i + 1} down`}>
+ <ArrowDown />
+ </Button>
+ <Button type="button" variant="ghost" size="icon-sm" disabled={order.length === 1} onClick={() => setOrder((o) => o.filter((x) => x.id !== g.id))} aria-label={`Leave ${i + 1} out`}>
+ <X />
+ </Button>
+ </li>
+ ))}
+ </ol>
+ </div>
+ </div>
+ )}
+
+ {step === "Cover" && (
+ <div className="grid gap-2">
+ <p className="text-[12px] text-muted-foreground">The picture people see first{layout === "feature" ? ", and the piece on top" : ""}. Without one, it&apos;s the first piece.</p>
+ <div role="radiogroup" aria-label="Cover" onKeyDown={radioKeys} className="grid grid-cols-3 gap-2 sm:grid-cols-4">
+ {order.map((g, i) => {
+ const index = firstShown(g);
+ const on = coverOf ? coverOf.generationId === g.id : i === 0;
+ return (
+ <button
+ key={g.id}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ aria-label={`${i + 1}: ${userTitle(g)}`}
+ tabIndex={radioTab(on)}
+ onClick={() => setCover({ generationId: g.id, index })}
+ className={cn("relative aspect-square overflow-hidden rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring", on ? "ring-2 ring-primary ring-offset-2 ring-offset-background" : "opacity-80 hover:opacity-100")}
+ >
+ <MediaThumb output={g.outputs[index]} g={g} className="size-full" />
+ {on && (
+ <span className="absolute top-1.5 right-1.5 grid size-5 place-items-center rounded-full bg-primary text-primary-foreground">
+ <Check className="size-3" />
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {step === "Access" && (
+ <div className="grid gap-4">
+ <div role="radiogroup" aria-label="Access" onKeyDown={radioKeys} className="grid gap-2 sm:grid-cols-2">
+ {[
+ { on: true, icon: Eye, label: "With prompts", hint: "Viewers see each prompt and can copy it with Recreate in your Fuobe." },
+ { on: false, icon: EyeOff, label: "Prompts hidden", hint: "Only the results and the model names. No Recreate." },
+ ].map((o) => {
+ const picked = showPrompts === o.on;
+ return (
+ <button
+ key={o.label}
+ type="button"
+ role="radio"
+ aria-checked={picked}
+ tabIndex={radioTab(picked)}
+ onClick={() => setShowPrompts(o.on)}
+ className={cn("flex items-start gap-3 rounded-xl border p-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring", picked ? "border-primary bg-brand-faint" : "hover:bg-muted/60")}
+ >
+ <o.icon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <span>
+ <span className="block text-[13px] font-medium">{o.label}</span>
+ <span className="block text-[12px] leading-snug text-muted-foreground">{o.hint}</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ <ExpiryPicker value={days} onChange={setDays} />
+ <p className="rounded-xl bg-muted/60 p-3 text-[12px] text-muted-foreground">
+ “{title.trim() || "Untitled"}”: a {PUBLISH_LAYOUTS.find((l) => l.id === layout)?.label.toLowerCase()} page of {pieces(order.length)}, {showPrompts ? "with prompts" : "prompts hidden"}. You can turn it off any
+ time in Library → Shared.
+ </p>
+ </div>
+ )}
+ </form>
+
+ <DialogFooter className="flex-row items-center justify-between sm:justify-between">
+ <Button type="button" variant="ghost" onClick={() => (at === 0 ? onClose() : setStep(STEPS[at - 1]))}>
+ {at === 0 ? "Cancel" : "Back"}
+ </Button>
+ <Button type="submit" form="publish-form" disabled={busy || (step === "Access" && !!blocker)}>
+ {step === "Access" ? (
+ <>
+ {busy ? <Loader2 className="animate-spin" /> : <Globe />} Publish
+ </>
+ ) : (
+ "Next"
+ )}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** A small drawing of each layout. */
+function LayoutGlyph({ layout }: { layout: Exclude<ShareLayout, "grid"> }) {
+ const box = "rounded-[3px] bg-current opacity-35";
+ return (
+ <span aria-hidden className="grid h-10 w-14 shrink-0 place-items-stretch text-primary">
+ {layout === "feature" ? (
+ <span className="grid grid-rows-[1.6fr_1fr] gap-0.5">
+ <span className={box} />
+ <span className="grid grid-cols-3 gap-0.5">
+ <span className={box} />
+ <span className={box} />
+ <span className={box} />
+ </span>
+ </span>
+ ) : layout === "series" ? (
+ <span className="grid grid-rows-3 gap-0.5">
+ {[0, 1, 2].map((i) => (
+ <span key={i} className="grid grid-cols-[0.5fr_2fr] gap-0.5">
+ <span className={cn(box, "opacity-60")} />
+ <span className={box} />
+ </span>
+ ))}
+ </span>
+ ) : (
+ <span className="grid grid-cols-[0.3fr_2fr_0.3fr] items-center gap-0.5">
+ <span className={cn(box, "h-2/3")} />
+ <span className={cn(box, "h-full")} />
+ <span className={cn(box, "h-2/3")} />
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/src/components/share/share-dialog.tsx b/src/components/share/share-dialog.tsx
new file mode 100644
index 00000000..4b7555b2
--- /dev/null
+++ b/src/components/share/share-dialog.tsx
@@ -0,0 +1,216 @@
+"use client";
+
+import { Check, Copy, ExternalLink, Link2, Loader2, TriangleAlert } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { useShareActions, useShares } from "@/lib/api";
+import type { Generation } from "@/lib/catalog/types";
+import { copyWithToast } from "@/lib/clipboard";
+import { EXPIRY_CHOICES, expiryLabel, type ShareCreated, type ShareInfo } from "@/lib/share";
+import { cn } from "@/lib/utils";
+import { PublishWizard } from "./publish-wizard";
+import { rememberLink, shareUrl, type ShareTarget } from "./share-provider";
+
+const NOUN: Record<ShareTarget["kind"], string> = { result: "this result", folder: "this folder", cinema: "this project" };
+
+/** What the provider has open: the Share dialog (a target, then its new link), a link to show, or the Publish wizard. */
+export type ShareOpen = { target: ShareTarget } | { made: ShareCreated } | { publish: Generation[] };
+
+/** The dialogs behind useShare(), loaded the first time one opens (ShareProvider in share-provider.tsx). */
+export function ShareDialogs({ open, onOpen, onClose }: { open: ShareOpen; onOpen: (o: ShareOpen) => void; onClose: () => void }) {
+ const made = (c: ShareCreated) => {
+ rememberLink(c.share.id, c.token);
+ onOpen({ made: c });
+ };
+ if ("publish" in open) return <PublishWizard items={open.publish} onClose={onClose} onPublished={made} />;
+ return (
+ <Dialog open onOpenChange={(v) => !v && onClose()}>
+ <DialogContent className="max-h-[92svh] overflow-y-auto sm:max-w-[480px]">
+ {"made" in open ? <LinkResult created={open.made} onDone={onClose} /> : <ShareForm target={open.target} onMade={made} />}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ShareForm({ target, onMade }: { target: ShareTarget; onMade: (c: ShareCreated) => void }) {
+ const actions = useShareActions();
+ const shares = useShares();
+ const [showPrompts, setShowPrompts] = useState(false);
+ // Untouched, the title follows the switch: a prompt-made one would show the prompt on a page that hides it.
+ const [typed, setTyped] = useState<string | null>(null);
+ const title = typed ?? (showPrompts && target.promptTitle ? target.promptTitle : target.title);
+ const [days, setDays] = useState<number | null>(null);
+ const [busy, setBusy] = useState(false);
+ const existing = (shares.data?.items ?? []).filter((s) => s.kind === target.kind && s.targetId === target.id).length;
+ const create = async () => {
+ setBusy(true);
+ try {
+ onMade(await actions.create({ kind: target.kind, targetId: target.id, title, showPrompts, expiresInDays: days }));
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <form
+ className="grid gap-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (!busy) void create();
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>Share {NOUN[target.kind]}</DialogTitle>
+ <DialogDescription>
+ Anyone with the link can view {target.kind === "result" ? "it" : "what's in it"} — no sign-in, nothing they can change, nothing else of your studio.
+ {target.kind !== "result" && " Results you add later show up too."}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-1.5">
+ <Label htmlFor="share-title">Title on the page</Label>
+ <Input id="share-title" value={title} maxLength={120} onChange={(e) => setTyped(e.target.value)} placeholder="Untitled" />
+ </div>
+ <PromptsSwitch value={showPrompts} onChange={setShowPrompts} />
+ <ExpiryPicker value={days} onChange={setDays} />
+ {existing > 0 && (
+ <p className="text-[12px] text-muted-foreground">
+ {existing === 1 ? "There's already a link" : `There are already ${existing} links`} to {NOUN[target.kind]}.{" "}
+ <Link href="/library?tab=shared" className="text-brand-text underline underline-offset-2">
+ Manage links
+ </Link>
+ </p>
+ )}
+ <DialogFooter>
+ <Button type="submit" disabled={busy}>
+ {busy ? <Loader2 className="animate-spin" /> : <Link2 />} Create link
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
+
+export function PromptsSwitch({ value, onChange }: { value: boolean; onChange: (v: boolean) => void }) {
+ return (
+ <div className="flex items-start justify-between gap-4 rounded-xl border p-3">
+ <div className="min-w-0">
+ <Label htmlFor="share-prompts">Show prompts</Label>
+ <p id="share-prompts-hint" className="mt-0.5 text-[12px] text-muted-foreground">
+ {value ? "Viewers see each prompt and can copy it with Recreate in your Fuobe." : "Viewers see the results and the model names only."}
+ </p>
+ </div>
+ <Switch id="share-prompts" checked={value} onCheckedChange={onChange} aria-describedby="share-prompts-hint" />
+ </div>
+ );
+}
+
+/** Never / 1 day / 7 days / 30 days, as a segmented radio row. */
+export function ExpiryPicker({ value, onChange }: { value: number | null; onChange: (days: number | null) => void }) {
+ return (
+ <div className="grid gap-1.5">
+ <p id="share-expiry" className="text-sm leading-none font-medium">
+ Link stops working
+ </p>
+ <div role="radiogroup" aria-labelledby="share-expiry" onKeyDown={radioKeys} className="flex flex-wrap gap-1 rounded-xl bg-muted p-1">
+ {EXPIRY_CHOICES.map((c) => {
+ const on = c.days === value;
+ return (
+ <button
+ key={c.id}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ tabIndex={radioTab(on)}
+ onClick={() => onChange(c.days)}
+ className={cn(
+ "h-7 flex-1 rounded-lg px-2.5 text-[13px] whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ on ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {c.days === null ? "Never" : `After ${c.label}`}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+const LOCAL = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\]|::1)$/i;
+
+/** The link just made: copy or open it, what it shows, and what to check before sending it. */
+export function LinkResult({ created, onDone }: { created: ShareCreated; onDone: () => void }) {
+ const shares = useShares();
+ const url = shareUrl(created.token);
+ const [copied, setCopied] = useState(false);
+ const s: ShareInfo = created.share;
+ const local = typeof window !== "undefined" && LOCAL.test(window.location.hostname);
+ const signIn = shares.data?.signIn;
+ return (
+ <div className="grid min-w-0 gap-4">
+ <DialogHeader>
+ <DialogTitle>Your link is ready</DialogTitle>
+ <DialogDescription>
+ {s.showPrompts ? "Prompts shown" : "Prompts hidden"} · {expiryLabel(s.expiresAt).toLowerCase()}. Turn it off any time in{" "}
+ <Link href="/library?tab=shared" onClick={onDone} className="text-brand-text underline underline-offset-2">
+ Library → Shared
+ </Link>
+ .
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex min-w-0 gap-1.5">
+ <Input readOnly value={url} aria-label="Share link" onFocus={(e) => e.currentTarget.select()} className="min-w-0 flex-1 font-mono text-[12px]" />
+ <Button
+ type="button"
+ onClick={() =>
+ void copyWithToast(url, "Link copied").then((ok) => {
+ if (ok) setCopied(true);
+ })
+ }
+ >
+ {copied ? <Check /> : <Copy />} {copied ? "Copied" : "Copy"}
+ </Button>
+ </div>
+ {(local || signIn === false) && (
+ <div className="grid gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-[12px] leading-relaxed">
+ {local && (
+ <p className="flex gap-2">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-600 dark:text-amber-400" />
+ <span>This address is this computer only (localhost). To share outside it, open Fuobe at an address others can reach, then copy the link there.</span>
+ </p>
+ )}
+ {signIn === false && (
+ <p className="flex gap-2">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-600 dark:text-amber-400" />
+ <span>
+ Sign-in is off: anyone who can reach this address can use your whole studio, not just this page.{" "}
+ <Link href="/settings#security" onClick={onDone} className="text-brand-text underline underline-offset-2">
+ Set a password
+ </Link>{" "}
+ before you send links outside your network.
+ </span>
+ </p>
+ )}
+ </div>
+ )}
+ <p className="text-[12px] text-muted-foreground">Only this browser can copy the link again later. Elsewhere, Library → Shared can make a new one.</p>
+ <DialogFooter>
+ <Button type="button" variant="outline" asChild>
+ <a href={url} target="_blank" rel="noreferrer">
+ <ExternalLink /> Open page
+ </a>
+ </Button>
+ <Button type="button" onClick={onDone}>
+ Done
+ </Button>
+ </DialogFooter>
+ </div>
+ );
+}
diff --git a/src/components/share/share-provider.tsx b/src/components/share/share-provider.tsx
new file mode 100644
index 00000000..76fd5d56
--- /dev/null
+++ b/src/components/share/share-provider.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import dynamic from "next/dynamic";
+import { createContext, useCallback, useContext, useMemo, useState, useSyncExternalStore } from "react";
+import type { Generation } from "@/lib/catalog/types";
+import { sharePath, type ShareCreated, type ShareKind } from "@/lib/share";
+import type { ShareOpen } from "./share-dialog";
+
+// ---------------------------------------------------------------------------
+// Links this browser made (the server keeps only a hash, so only the browser that made a link can copy it again)
+
+const KEY = "fuobe.shareLinks";
+
+function rawLinks(): string {
+ try {
+ return localStorage.getItem(KEY) ?? "{}";
+ } catch {
+ return "{}";
+ }
+}
+
+function parseLinks(raw: string): Record<string, string> {
+ try {
+ const v = JSON.parse(raw) as unknown;
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, string>) : {};
+ } catch {
+ return {};
+ }
+}
+
+const listeners = new Set<() => void>();
+
+function writeLinks(all: Record<string, string>) {
+ try {
+ localStorage.setItem(KEY, JSON.stringify(all));
+ } catch {
+ // Storage off (a private window): the link can't be copied again later, only renewed.
+ }
+ listeners.forEach((l) => l());
+}
+
+/** Remember a link's token in this browser (replacing `previousId`'s after a new link). */
+export function rememberLink(id: string, token: string, previousId?: string) {
+ const all = parseLinks(rawLinks());
+ if (previousId) delete all[previousId];
+ writeLinks({ ...all, [id]: token });
+}
+
+export function forgetLink(id: string) {
+ const all = parseLinks(rawLinks());
+ delete all[id];
+ writeLinks(all);
+}
+
+function subscribe(cb: () => void) {
+ listeners.add(cb);
+ window.addEventListener("storage", cb);
+ return () => {
+ listeners.delete(cb);
+ window.removeEventListener("storage", cb);
+ };
+}
+
+/** The tokens this browser made, by link id (none while rendering on the server). */
+export function useRememberedLinks(): Record<string, string> {
+ const raw = useSyncExternalStore(subscribe, rawLinks, () => "{}");
+ return useMemo(() => parseLinks(raw), [raw]);
+}
+
+/** The full address of a link, at the address this studio is open on. */
+export const shareUrl = (token: string) => `${typeof window === "undefined" ? "" : window.location.origin}${sharePath(token)}`;
+
+// ---------------------------------------------------------------------------
+// Share and Publish from anywhere under the studio layout
+
+export interface ShareTarget {
+ kind: Exclude<ShareKind, "publish">;
+ id: string;
+ /** Prefills the link's title. */
+ title: string;
+ /** A title made from the prompt, offered instead while "Show prompts" is on. */
+ promptTitle?: string;
+}
+
+interface ShareApi {
+ /** Share a result, a folder or a Cinema project. */
+ share: (t: ShareTarget) => void;
+ /** Publish a selection (the four-step wizard). */
+ publish: (items: Generation[]) => void;
+ /** Show a link just made or renewed (Library → Shared's New link). */
+ showLink: (created: ShareCreated) => void;
+}
+
+const ShareCtx = createContext<ShareApi | null>(null);
+
+/** Share and Publish for every view in the studio (null outside one). */
+export const useShare = () => useContext(ShareCtx);
+
+// The dialogs (forms, the wizard, thumbnails) load the first time one opens, not with every page.
+const ShareDialogs = dynamic(() => import("./share-dialog").then((m) => m.ShareDialogs), { ssr: false });
+
+export function ShareProvider({ children }: { children: React.ReactNode }) {
+ const [open, setOpen] = useState<ShareOpen | null>(null);
+ // After a menu has closed and handed focus back, so the dialog keeps it.
+ const later = useCallback((o: ShareOpen) => setTimeout(() => setOpen(o), 0), []);
+ const api = useMemo<ShareApi>(() => ({ share: (target) => later({ target }), publish: (items) => later({ publish: items }), showLink: (made) => later({ made }) }), [later]);
+ return (
+ <ShareCtx.Provider value={api}>
+ {children}
+ {open && <ShareDialogs open={open} onOpen={later} onClose={() => setOpen(null)} />}
+ </ShareCtx.Provider>
+ );
+}
diff --git a/src/components/share/shared-links.tsx b/src/components/share/shared-links.tsx
new file mode 100644
index 00000000..c20fc507
--- /dev/null
+++ b/src/components/share/shared-links.tsx
@@ -0,0 +1,233 @@
+"use client";
+
+import { Clock, Copy, ExternalLink, Eye, EyeOff, Globe, Link2, MoreHorizontal, RefreshCw, Trash2 } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { MediaThumb } from "@/components/studio/result-media";
+import { useNow } from "@/components/studio/use-now";
+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,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useShareActions, useShares } from "@/lib/api";
+import { copyWithToast } from "@/lib/clipboard";
+import { timeAgo } from "@/lib/format";
+import { EXPIRY_CHOICES, expiryLabel, isExpired, KIND_LABELS, pieces, PUBLISH_LAYOUTS, type ShareListItem } from "@/lib/share";
+import { cn } from "@/lib/utils";
+import { forgetLink, rememberLink, shareUrl, useRememberedLinks, useShare } from "./share-provider";
+
+/**
+ * Library → Shared: every share link, live ones first, with what each shows, its access and expiry,
+ * views, and Copy / Open (when this browser made it), prompts on or off, a new expiry, a new link,
+ * and Revoke.
+ */
+export function SharedLinks() {
+ const shares = useShares();
+ // Tokens live in this browser's storage only.
+ const known = useRememberedLinks();
+ // Expiry labels and the live / not working split stay right while the list is open.
+ const now = useNow(60_000);
+ const items = shares.data?.items;
+ if (shares.isLoading) {
+ return (
+ <div className="grid gap-2" aria-busy="true" aria-label="Loading links">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-[76px] rounded-xl" />
+ ))}
+ </div>
+ );
+ }
+ if (shares.isError) return <p className="text-[14px] text-destructive">Couldn&apos;t load your links: {(shares.error as Error).message}</p>;
+ const live = (items ?? []).filter((s) => !s.gone && !isExpired(s, now));
+ const ended = (items ?? []).filter((s) => s.gone || isExpired(s, now));
+ if (!live.length && !ended.length) {
+ return (
+ <div className="rounded-xl border border-primary/10 bg-brand-faint px-6 py-12 text-center">
+ <p className="font-heading text-[22px]">Nothing shared yet</p>
+ <p className="mx-auto mt-1 max-w-md text-[14px] text-muted-foreground">
+ Share a result from its ⋯ menu, a folder from its menu, a Cinema project from its header, or select results and choose Publish to make a page of them.
+ </p>
+ </div>
+ );
+ }
+ return (
+ <div className="space-y-7">
+ {shares.data?.signIn === false && (
+ <p className="rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-[13px]">
+ Sign-in is off, so anyone who can reach this studio can use all of it, not just the shared pages. Set a password in Settings → Security before sending links outside your network.
+ </p>
+ )}
+ <section aria-label="Live links">
+ <h2 className="mb-2.5 text-[13px] font-medium">
+ Live <span className="font-mono text-[11px] font-normal text-muted-foreground">{live.length}</span>
+ </h2>
+ {live.length ? (
+ <ul className="grid gap-2">
+ {live.map((s) => (
+ <Row key={s.id} s={s} token={known[s.id]} now={now} />
+ ))}
+ </ul>
+ ) : (
+ <p className="text-[13px] text-muted-foreground">No live links.</p>
+ )}
+ </section>
+ {ended.length > 0 && (
+ <section aria-label="Links that no longer work">
+ <h2 className="mb-2.5 text-[13px] font-medium">
+ Not working <span className="font-mono text-[11px] font-normal text-muted-foreground">{ended.length}</span>
+ </h2>
+ <ul className="grid gap-2">
+ {ended.map((s) => (
+ <Row key={s.id} s={s} token={known[s.id]} now={now} />
+ ))}
+ </ul>
+ </section>
+ )}
+ </div>
+ );
+}
+
+function Row({ s, token, now }: { s: ShareListItem; token?: string; now: number }) {
+ const actions = useShareActions();
+ const share = useShare();
+ const [confirm, setConfirm] = useState(false);
+ const expired = isExpired(s, now);
+ const dead = s.gone || expired;
+ const fail = (e: Error) => toast.error(e.message);
+ const kind = s.kind === "publish" ? `${PUBLISH_LAYOUTS.find((l) => l.id === s.layout)?.label ?? "Published"} page` : KIND_LABELS[s.kind];
+ const renew = () =>
+ void actions
+ .update(s.id, { newLink: true })
+ .then((r) => {
+ if (!r.token || !r.path) return;
+ rememberLink(r.share.id, r.token, s.id);
+ share?.showLink({ share: r.share, token: r.token, path: r.path });
+ })
+ .catch(fail);
+ return (
+ <li className={cn("flex min-w-0 items-center gap-3 rounded-xl border bg-card p-2.5", dead && "opacity-75")}>
+ <div className="grid size-14 shrink-0 place-items-center overflow-hidden rounded-lg bg-muted">
+ {s.thumb ? <MediaThumb output={{ url: s.thumb.url, kind: s.thumb.kind }} className="size-full" /> : s.kind === "publish" ? <Globe className="size-5 text-muted-foreground" /> : <Link2 className="size-5 text-muted-foreground" />}
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[14px] font-medium">{s.title}</p>
+ <p className="truncate text-[12px] text-muted-foreground">
+ {kind} · {s.gone ? "removed from your studio" : pieces(s.count)}
+ </p>
+ <p className="mt-0.5 flex flex-wrap items-center gap-x-2.5 gap-y-0.5 text-[12px] text-muted-foreground">
+ <span className="inline-flex items-center gap-1">
+ {s.showPrompts ? <Eye className="size-3" /> : <EyeOff className="size-3" />} {s.showPrompts ? "Prompts shown" : "Prompts hidden"}
+ </span>
+ <span className={cn("inline-flex items-center gap-1", expired && "text-destructive")}>
+ <Clock className="size-3" /> {expiryLabel(s.expiresAt, now)}
+ </span>
+ <span>
+ {s.views} view{s.views === 1 ? "" : "s"}
+ {s.lastViewedAt ? `, last ${timeAgo(s.lastViewedAt, now)}` : ""}
+ </span>
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {token && !dead && (
+ <>
+ <Button variant="outline" size="sm" className="max-sm:hidden" onClick={() => void copyWithToast(shareUrl(token), "Link copied")}>
+ <Copy /> Copy link
+ </Button>
+ <Button variant="ghost" size="icon-sm" asChild>
+ <a href={shareUrl(token)} target="_blank" rel="noreferrer" aria-label={`Open the page for ${s.title}`} title="Open page">
+ <ExternalLink />
+ </a>
+ </Button>
+ </>
+ )}
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-sm" aria-label={`Link options for ${s.title}`}>
+ <MoreHorizontal />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-52">
+ {token && !dead && (
+ <DropdownMenuItem onSelect={() => void copyWithToast(shareUrl(token), "Link copied")}>
+ <Copy /> Copy link
+ </DropdownMenuItem>
+ )}
+ {!s.gone && (
+ <DropdownMenuItem onSelect={renew}>
+ <RefreshCw /> {token ? "New link (the old one stops)" : "New link to copy"}
+ </DropdownMenuItem>
+ )}
+ {!s.gone && (
+ <DropdownMenuItem onSelect={() => void actions.update(s.id, { showPrompts: !s.showPrompts }).then(() => toast(s.showPrompts ? "Prompts hidden on the page" : "Prompts shown on the page")).catch(fail)}>
+ {s.showPrompts ? <EyeOff /> : <Eye />} {s.showPrompts ? "Hide prompts" : "Show prompts"}
+ </DropdownMenuItem>
+ )}
+ {!s.gone && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Clock /> {expired ? "Turn back on for" : "Stops working"}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {EXPIRY_CHOICES.map((c) => (
+ <DropdownMenuItem key={c.id} onSelect={() => void actions.update(s.id, { expiresInDays: c.days }).then((r) => toast(expiryLabel(r.share.expiresAt))).catch(fail)}>
+ {c.days === null ? "Never" : `In ${c.label}`}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => setTimeout(() => setConfirm(true), 0)}>
+ <Trash2 /> {dead ? "Remove" : "Revoke link"}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ <AlertDialog open={confirm} onOpenChange={setConfirm}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{dead ? "Remove this link?" : "Revoke this link?"}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {dead ? "It already doesn't work; this takes it off the list." : `“${s.title}” stops opening at once for everyone who has the link. What it shows stays in your studio.`}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() =>
+ void actions
+ .revoke(s.id)
+ .then(() => {
+ forgetLink(s.id);
+ toast(dead ? "Removed" : "Link revoked");
+ })
+ .catch(fail)
+ }
+ >
+ {dead ? "Remove" : "Revoke"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </li>
+ );
+}
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 5109ad5b..97c6d145 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -22,6 +22,7 @@ import {
Pin,
Repeat,
RotateCcw,
+ Share2,
SlidersHorizontal,
Sparkles,
Trash2,
@@ -56,12 +57,13 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ReviewMenuItems } from "@/components/library/review";
+import { useShare } from "@/components/share/share-provider";
import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useCreateGeneration, useGenerationActions, useSaveElement } from "@/lib/api";
import { ELEMENT_KINDS, type ElementKind } from "@/lib/catalog/elements";
-import type { Generation, OutputFile } from "@/lib/catalog/types";
-import { downloadName } from "@/lib/library";
+import { OPERATION_LABELS, type Generation, type OutputFile } from "@/lib/catalog/types";
+import { downloadName, userTitle } from "@/lib/library";
import { toSrt, toVtt } from "@/lib/cues";
import { cuesOf, outputActions, textOf, type ActionContext, type OutputAction, type OutputActionId } from "@/lib/output-actions";
import { cn } from "@/lib/utils";
@@ -95,6 +97,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
compare: Columns2,
reuse: RotateCcw,
"copy-prompt": Copy,
+ share: Share2,
pin: Pin,
review: CircleDot,
delete: Trash2,
@@ -198,6 +201,7 @@ export function useActionRunner(opts: RunnerOptions = {}) {
const create = useCreateGeneration();
const confirmForever = useConfirmForever();
const deleteUpload = useContext(UploadDeleteContext);
+ const share = useShare();
return (a: OutputAction, g: Generation, index: number) => {
const o = g.outputs[index];
switch (a.id) {
@@ -207,6 +211,10 @@ export function useActionRunner(opts: RunnerOptions = {}) {
return void copyWithToast(textOf(o));
case "copy-prompt":
return void copyWithToast(g.prompt ?? "", "Prompt copied");
+ case "share":
+ if (!share) return void toast.error("Share from the Library or a studio page");
+ // The prompt-made title only while prompts are shared (the dialog switches between them).
+ return share.share({ kind: "result", id: g.id, title: `${OPERATION_LABELS[g.op] ?? "Result"}${g.modelName ? ` · ${g.modelName}` : ""}`, promptTitle: userTitle(g).slice(0, 120) });
case "download-txt":
return saveBlob(textOf(o), downloadName(g, o, index, "txt"), "text/plain");
case "download-srt":
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 732ca060..a2d0005d 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -26,6 +26,7 @@ import {
type StreamEvent,
} from "./generation-stream";
import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folder } from "./library";
+import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";
export interface Asset {
id: string;
@@ -678,6 +679,39 @@ export function useFolderActions() {
}, [qc]);
}
+// ---------------------------------------------------------------------------
+// Share links (Library → Shared, the Share dialog, the Publish wizard)
+
+/** Every link, and whether sign-in is on (a link to a studio without a password opens more than the page). */
+export function useShares(opts: { enabled?: boolean } = {}) {
+ return useQuery({
+ queryKey: ["shares"],
+ queryFn: async () => json<{ items: ShareListItem[]; signIn: boolean }>(await fetch("/api/shares")),
+ staleTime: 10_000,
+ enabled: opts.enabled ?? true,
+ });
+}
+
+export function useShareActions() {
+ const qc = useQueryClient();
+ return useMemo(() => {
+ const send = async <T,>(url: string, method: string, body?: unknown) => {
+ const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ const out = res.status === 204 ? (undefined as T) : await json<T>(res);
+ void qc.invalidateQueries({ queryKey: ["shares"] });
+ return out;
+ };
+ return {
+ /** A new link; the answer carries its token once. */
+ create: (body: ShareRequest) => send<ShareCreated>("/api/shares", "POST", body),
+ /** Change it; with newLink, a new token (in the answer) replaces the old one. */
+ update: (id: string, patch: SharePatch) => send<{ share: ShareInfo; token?: string; path?: string }>(`/api/shares/${id}`, "PATCH", patch),
+ /** Revoke: the link stops working at once. */
+ revoke: (id: string) => send<void>(`/api/shares/${id}`, "DELETE"),
+ };
+ }, [qc]);
+}
+
// ---------------------------------------------------------------------------
// Uploads & assets
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 8429d682..71eeeeb1 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -9,6 +9,7 @@ import type { Generation, OutputFile, VideoFormat } from "./catalog/types";
import { cueText, type Cue } from "./cues";
import { downloadHref, downloadName, extensionOf } from "./library";
import { PRESETS as GRADE_PRESETS } from "./grade";
+import { storedPath } from "./share";
export type OutputActionId =
| "animate"
@@ -38,6 +39,7 @@ export type OutputActionId =
| "compare"
| "reuse"
| "copy-prompt"
+ | "share"
| "pin"
| "review"
| "delete"
@@ -149,6 +151,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
if (ctx.compare) out.push({ id: "compare", label: "Compare with original", placement: "menu" });
if (ctx.reuse) out.push({ id: "reuse", label: "Reuse settings", placement: "menu" });
if (g.prompt) out.push({ id: "copy-prompt", label: "Copy prompt", placement: "menu" });
+ // A read-only link (src/lib/share.ts): finished results whose files Fuobe keeps.
+ if (g.status === "succeeded" && g.outputs.some((x) => storedPath(x.url))) out.push({ id: "share", label: "Share link…", placement: "menu" });
// Library: pinned results stay at the top of their view; the review status is a sub-menu of its own.
out.push({ id: "pin", label: g.pinnedAt ? "Unpin" : "Pin to top", placement: "menu" }, { id: "review", label: "Review status", placement: "menu" });
out.push({ id: "delete", label: "Delete", placement: "menu", destructive: true });
diff --git a/src/lib/share.ts b/src/lib/share.ts
index 089899f0..fdf6f57b 100644
--- a/src/lib/share.ts
+++ b/src/lib/share.ts
@@ -65,6 +65,43 @@ export interface ShareListItem extends ShareInfo {
gone: boolean;
}
+/** POST /api/shares: a new link. */
+export interface ShareRequest {
+ kind: ShareKind;
+ /** The result, folder or Cinema project (not for a published selection). */
+ targetId?: string | null;
+ /** A published selection's results, in page order. */
+ items?: string[];
+ title?: string;
+ description?: string;
+ tags?: string[] | string;
+ layout?: ShareLayout;
+ cover?: { generationId: string; index: number } | null;
+ showPrompts?: boolean;
+ /** Days until the link stops working; null or left out: until revoked. */
+ expiresInDays?: number | null;
+}
+
+/** PATCH /api/shares/[id]. */
+export interface SharePatch {
+ title?: string;
+ description?: string;
+ tags?: string[] | string;
+ layout?: ShareLayout;
+ showPrompts?: boolean;
+ /** Days from now; null: never expires. */
+ expiresInDays?: number | null;
+ /** A new token: the old link stops working. */
+ newLink?: true;
+}
+
+/** A link as created (or renewed): the token is in this answer only. */
+export interface ShareCreated {
+ share: ShareInfo;
+ token: string;
+ path: string;
+}
+
// ---------------------------------------------------------------------------
// Tokens and the public routes
diff --git a/src/server/shares.ts b/src/server/shares.ts
index a46c4469..c8edbd4b 100644
--- a/src/server/shares.ts
+++ b/src/server/shares.ts
@@ -27,6 +27,8 @@ import {
type ShareKind,
type ShareLayout,
type ShareListItem,
+ type SharePatch,
+ type ShareRequest,
} from "@/lib/share";
import { db } from "./db";
import { toGeneration } from "./generations";
@@ -207,21 +209,7 @@ export function recordView(id: string, now = Date.now()): void {
// ---------------------------------------------------------------------------
// The owner's side
-export interface CreateShareInput {
- kind: ShareKind;
- /** The result, folder or Cinema project (not for a published selection). */
- targetId?: string | null;
- /** A published selection's results, in page order. */
- items?: string[];
- title?: string;
- description?: string;
- tags?: string[] | string;
- layout?: ShareLayout;
- cover?: { generationId: string; index: number } | null;
- showPrompts?: boolean;
- /** Days until the link stops working; null or left out: until revoked. */
- expiresInDays?: number | null;
-}
+export type CreateShareInput = ShareRequest;
const clean = (s: string | undefined, max: number) => (s ?? "").replace(/\s+/g, (w) => (w.includes("\n") ? "\n" : " ")).trim().slice(0, max);
@@ -313,18 +301,6 @@ export function listShares(): ShareListItem[] {
});
}
-export interface SharePatch {
- title?: string;
- description?: string;
- tags?: string[] | string;
- layout?: ShareLayout;
- showPrompts?: boolean;
- /** Days from now; null: never expires. */
- expiresInDays?: number | null;
- /** A new token: the old link stops working. */
- newLink?: boolean;
-}
-
/** Change a link (its words, prompts on or off, a new expiry from now), or give it a new token. */
export function updateShare(id: string, patch: SharePatch, now = Date.now()): { share: ShareInfo; token?: string; path?: string } | null {
const r = rowOf(id);
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 3a63bfb3..08ea713b 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -78,6 +78,7 @@ describe("outputActions", () => {
"menu:save-character",
"menu:reuse",
"menu:copy-prompt",
+ "menu:share",
"menu:pin",
"menu:review",
"menu:delete",
@@ -90,7 +91,7 @@ describe("outputActions", () => {
it("gives SVG results no raster hand-offs, but keeps them on demo placeholders", () => {
const svg = (p: Partial<Generation>, o: Partial<Generation["outputs"][number]> = {}) => gen({ provider: "fal", outputs: [{ url: "/api/files/outputs/d/logo.svg", kind: "image", contentType: "image/svg+xml", ...o }], ...p });
- expect(ids(svg({}))).toEqual(["bar:download", "bar:favorite", "menu:copy-prompt", "menu:pin", "menu:review", "menu:delete"]);
+ expect(ids(svg({}))).toEqual(["bar:download", "bar:favorite", "menu:copy-prompt", "menu:share", "menu:pin", "menu:review", "menu:delete"]);
expect(ids(svg({}, { url: "https://v3.fal.media/files/x/logo.svg", contentType: undefined }))[0]).toBe("bar:download");
expect(ids(svg({ feature: "upload", provider: "local" }))).toEqual(["bar:download", "menu:delete-upload"]);
// A demo picture is an SVG standing in for a raster result: it can still be animated (a demo Vectorize result can't).
@@ -113,6 +114,7 @@ describe("outputActions", () => {
"menu:genjutsu",
"menu:finalize",
"menu:copy-prompt",
+ "menu:share",
"menu:pin",
"menu:review",
"menu:delete",
diff --git a/tests/share-links.test.ts b/tests/share-links.test.ts
index 40d12cc4..eb6e3404 100644
--- a/tests/share-links.test.ts
+++ b/tests/share-links.test.ts
@@ -6,6 +6,8 @@ import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
+import type { ShareListItem } from "@/lib/share";
+import type { ShareRow } from "@/server/share-access";
// Route handlers call connection() (no request scope in a test).
vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
@@ -132,7 +134,7 @@ describe("tokens", () => {
expect(p).toBe(`/s/${token}`);
expect(share.isShareToken(token)).toBe(true);
expect(s.id).toBe(token.slice(0, share.SHARE_ID_LENGTH));
- const row = db().prepare("SELECT * FROM shares WHERE id = ?").get(s.id) as access.ShareRow;
+ const row = db().prepare("SELECT * FROM shares WHERE id = ?").get(s.id) as ShareRow;
expect(row.token_hash).toBe(crypto.createHash("sha256").update(token).digest("hex"));
expect(JSON.stringify(db().prepare("SELECT * FROM shares").all())).not.toContain(token.slice(share.SHARE_ID_LENGTH));
@@ -315,7 +317,7 @@ describe("the owner's API", () => {
expect(created.status).toBe(201);
const { share: s, token } = (await created.json()) as { share: { id: string; expiresAt: number }; token: string };
expect(s.expiresAt).toBeGreaterThan(Date.now());
- const list = (await (await listRoute.GET()).json()) as { items: (share.ShareListItem & { token?: string })[]; signIn: boolean };
+ const list = (await (await listRoute.GET()).json()) as { items: ShareListItem[]; signIn: boolean };
const row = list.items.find((x) => x.id === s.id)!;
expect(row).toMatchObject({ count: 1, gone: false, thumb: { kind: "image" } });
expect(JSON.stringify(list)).not.toContain(token);
diff --git a/tests/vectorize.test.ts b/tests/vectorize.test.ts
index aa52aede..e9845749 100644
--- a/tests/vectorize.test.ts
+++ b/tests/vectorize.test.ts
@@ -114,7 +114,7 @@ describe("Vectorize app", () => {
expect(download.download).toMatch(/\.svg$/);
expect(download.href).toContain(`${out.url}?download=`);
// No raster hand-offs (Animate, Edit, Upscale…): those models can't read an SVG.
- expect(outputActions(done, 0).map((a) => `${a.placement}:${a.id}`)).toEqual(["bar:download", "bar:favorite", "menu:copy-prompt", "menu:pin", "menu:review", "menu:delete"]);
+ expect(outputActions(done, 0).map((a) => `${a.placement}:${a.id}`)).toEqual(["bar:download", "bar:favorite", "menu:copy-prompt", "menu:share", "menu:pin", "menu:review", "menu:delete"]);
expect(download.label).toBe("Download .svg");
});
});