The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Feed and viewer: no re-render per keystroke, shared result actions, phone viewer, new-result pill
Claudea4bd7ca8cf09
diff --git a/package.json b/package.jsonindex d41fa54f..982de6bb 100644--- a/package.json+++ b/package.json@@ -16,6 +16,7 @@"dependencies": {"@anthropic-ai/sdk": "^0.135.0","@fal-ai/client": "^1.10.1",+ "@google/model-viewer": "4.3.1","@tanstack/react-query": "^5.104.3","better-sqlite3": "^13.0.3","class-variance-authority": "^0.7.1",@@ -33,6 +34,7 @@"server-only": "^0.0.1","shadcn": "^4.22.0","sonner": "^2.0.8",+ "three": "0.183.2","tw-animate-css": "^1.4.0","zod": "^4.6.7"},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5f867306..f5326c02 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -14,6 +14,9 @@ importers:'@fal-ai/client':specifier: ^1.10.1version: 1.10.1+ '@google/model-viewer':+ specifier: 4.3.1+ version: 4.3.1([email protected])'@tanstack/react-query':specifier: ^5.104.3version: 5.104.3([email protected])@@ -65,6 +68,9 @@ importers:sonner:specifier: ^2.0.8+ three:+ specifier: 0.183.2+ version: 0.183.2tw-animate-css:specifier: ^1.4.0version: 1.4.0@@ -333,6 +339,12 @@ packages:'@floating-ui/[email protected]':resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}+ '@google/[email protected]':+ resolution: {integrity: sha512-GP+inXhAtY31E8rILVmByA6z8CZZjdlNajddppyI1/j1eIaSQiZcMRaUqTFe7+jv4mzRzwKIOiKBud0apiv+WQ==}+ engines: {node: '>=6.0.0'}+ peerDependencies:+ three: ^0.183.0+'@hono/[email protected]':resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==}engines: {node: '>=20'}@@ -521,6 +533,12 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}+ '@lit-labs/[email protected]':+ resolution: {integrity: sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==}++ '@lit/[email protected]':+ resolution: {integrity: sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==}+'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==}engines: {node: '>=18'}@@ -531,6 +549,11 @@ packages:'@cfworker/json-schema':optional: true+ '@monogrid/[email protected]':+ resolution: {integrity: sha512-2Z0FATFHaoYJ8b+Y4y4Hgfn3FRFwuU5zRrk+9dFWp4uGAdHGqVEdP7HP+gLA3X469KXHmfupJaUbKo1b/aDKIg==}+ peerDependencies:+ three: '>= 0.159.0'+'@msgpack/[email protected]':resolution: {integrity: sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==}engines: {node: '>= 18'}@@ -1568,6 +1591,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}+'@types/[email protected]':resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}@@ -2694,6 +2720,9 @@ packages:resolution: {integrity: sha512-/8UvqAPU9DGTI9k4mxtf49U37Isfwr8Uts96+SBHIkFxPJnHS0Ew4f00sM4Scd8V8EjM0jUNtVDdv1kPdt35lg==}engines: {node: '>= 4'}+ resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==}+resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==}engines: {node: '>=6'}@@ -2838,6 +2867,9 @@ packages:resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}engines: {node: '>=12'}+ resolution: {integrity: sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==}+resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}@@ -2998,6 +3030,9 @@ packages:resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}engines: {node: '>= 0.8.0'}+ resolution: {integrity: sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==}+resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}engines: {node: '>= 12.0.0'}@@ -3138,6 +3173,15 @@ packages:resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}engines: {node: '>= 12.0.0'}+ resolution: {integrity: sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==}++ resolution: {integrity: sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==}++ resolution: {integrity: sha512-fycuvZg/hkpozL00lm1pEJH5nN/lr9ZXd6mJI2HSN4+Bzc+LDNdEApJ6HFbPkdFNHLvOplIIuJvxkS4XUxqirw==}+resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==}engines: {node: '>=6'}@@ -3620,6 +3664,9 @@ packages:resolution: {integrity: sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-bN+0ehEnrXfxV2ZQvU2PetO0n4gqBD4ulq3MI1WOPLgr7/Mg9yRQkX5+0v1vagr74ZTsl7XtzlaYDo2EuCeYJw==}+resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}engines: {node: '>= 6'}@@ -4030,6 +4077,9 @@ packages:resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}engines: {node: '>=6'}+ resolution: {integrity: sha512-di3BsL2FEQ1PA7Hcvn4fyJOlxRRgFYBpMTcyOgkwJIaDOdJMebEFPA+t98EvjuljDx4hNulAGwF6KIjtwI5jgQ==}+resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}@@ -4688,6 +4738,12 @@ snapshots:'@floating-ui/[email protected]': {}+ '@google/[email protected]([email protected])':+ dependencies:+ '@monogrid/gainmap-js': 3.4.0([email protected])+ lit: 3.3.3+ three: 0.183.2+'@hono/[email protected]([email protected])':dependencies:hono: 4.13.13@@ -4834,6 +4890,12 @@ snapshots:'@jridgewell/resolve-uri': 3.1.2'@jridgewell/sourcemap-codec': 1.6.0+ '@lit-labs/[email protected]': {}++ '@lit/[email protected]':+ dependencies:+ '@lit-labs/ssr-dom-shim': 1.6.0+'@modelcontextprotocol/[email protected]([email protected])':dependencies:'@hono/node-server': 2.1.5([email protected])@@ -4856,6 +4918,11 @@ snapshots:transitivePeerDependencies:- supports-color+ '@monogrid/[email protected]([email protected])':+ dependencies:+ promise-worker-transferable: 1.0.4+ three: 0.183.2+'@msgpack/[email protected]': {}@@ -5888,6 +5955,8 @@ snapshots:dependencies:csstype: 3.2.3+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -7168,6 +7237,8 @@ snapshots:+ [email protected]: {}+dependencies:parent-module: 1.0.1@@ -7295,6 +7366,8 @@ snapshots:+ [email protected]: {}+@@ -7436,6 +7509,10 @@ snapshots:prelude-ls: 1.2.1type-check: 0.4.0+ dependencies:+ immediate: 3.0.6+optional: true@@ -7534,6 +7611,22 @@ snapshots:lightningcss-win32-arm64-msvc: 1.33.0lightningcss-win32-x64-msvc: 1.33.0+ dependencies:+ '@lit-labs/ssr-dom-shim': 1.6.0+ '@lit/reactive-element': 2.1.2+ lit-html: 3.3.3++ dependencies:+ '@types/trusted-types': 2.0.7++ dependencies:+ '@lit/reactive-element': 2.1.2+ lit-element: 4.2.2+ lit-html: 3.3.3+dependencies:p-locate: 3.0.0@@ -8224,6 +8317,11 @@ snapshots:dependencies:parse-ms: 4.0.0+ dependencies:+ is-promise: 2.2.2+ lie: 3.3.0+dependencies:kleur: 3.0.3@@ -8840,6 +8938,8 @@ snapshots:+ [email protected]: {}+diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex 6c457b39..e33b0664 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -1,29 +1,7 @@"use client";-import {- AudioLines,- Clapperboard,- Copy,- Download,- Heart,- ImagePlus,- Mic2,- MoreHorizontal,- RotateCcw,- Trash2,- Wand2,- X,- ZoomIn,- Cpu,- Cloud,- Crop,- FastForward,- Sparkles,- UserRoundPlus,-} from "lucide-react";-import Link from "next/link";-import { useRouter } from "next/navigation";-import { useState } from "react";+import { Cloud, Copy, Cpu, FolderDown, Heart, MoreHorizontal, RotateCcw, Sparkles, Trash2, X } from "lucide-react";+import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import {DropdownMenu,@@ -33,100 +11,24 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { getModel, getPreset } from "@/lib/catalog";-import { OPERATION_LABELS, type Generation, type OutputFile } from "@/lib/catalog/types";-import { useCreateGeneration, useGenerationActions, useSaveElement } from "@/lib/api";+import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";+import { useCreateGeneration, useGenerationActions } from "@/lib/api";import { elapsed, formatCost, ratioValue, timeAgo } from "@/lib/format";+import { userTitle } from "@/lib/library";+import { isLayered } from "@/lib/output-actions";import { cn } from "@/lib/utils";+import { TileActions, useCanHover, type RunnerOptions } from "./result-actions";+import { LayersStack, MediaThumb } from "./result-media";import { Viewer } from "./viewer";-/** "a 26-year-old surfer from Lisbon, freckles" → "Surfer From Lisbon" — a starting name, renamed on the element page. */-function characterName(prompt: string | undefined): string {- const words = (prompt ?? "").replace(/@\S+/g, "").replace(/[^\p{L}\p{N}\s'-]/gu, " ").split(/\s+/).filter((w) => w.length > 2 && !/\d/.test(w) && !/^(the|and|with|from|who|year|old|of)$/i.test(w));- const pick = words.slice(0, 3).map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join(" ");- return pick || "New character";-}--/** Save an image as a character element (AI Influencer sheets, any portrait) to @mention it later. */-function useSaveAsCharacter() {- const save = useSaveElement();- const router = useRouter();- return (g: Generation, o: OutputFile) =>- save.mutate(- { name: characterName(g.request.prompt), kind: "character", references: [o.url] },- {- onSuccess: (el) => toast.success(`Saved as @${el.handle}`, { action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } }),- onError: (e) => toast.error((e as Error).message),- },- );-}--export function downloadName(g: Generation, o: OutputFile, i: number): string {- const ext = o.url.split(".").pop()?.split("?")[0] ?? "bin";- const base = (g.request.prompt || g.prompt || g.modelId).slice(0, 40).replace(/[^\w]+/g, "-").replace(/^-|-$/g, "") || "fuobe";- return `${base}-${g.id.slice(0, 6)}${i ? `-${i + 1}` : ""}.${ext}`;-}--function IconAction({ label, onClick, href, children }: { label: string; onClick?: () => void; href?: string; children: React.ReactNode }) {- const cls = "grid size-8 place-items-center rounded-lg text-white/90 transition-colors hover:bg-white/20 hover:text-white";- return (- <Tooltip>- <TooltipTrigger asChild>- {href ? (- <Link href={href} className={cls} aria-label={label} onClick={(e) => e.stopPropagation()}>- {children}- </Link>- ) : (- <button- className={cls}- aria-label={label}- onClick={(e) => {- e.stopPropagation();- onClick?.();- }}- >- {children}- </button>- )}- </TooltipTrigger>- <TooltipContent>{label}</TooltipContent>- </Tooltip>- );-}--export function MediaThumb({ output, className, autoPlay }: { output: OutputFile; className?: string; autoPlay?: boolean }) {- if (output.kind === "video") {- return (- <video- src={`${output.url}#t=0.1`}- muted- loop- playsInline- preload="metadata"- autoPlay={autoPlay}- onMouseEnter={(e) => void e.currentTarget.play().catch(() => {})}- onMouseLeave={(e) => {- if (!autoPlay) e.currentTarget.pause();- }}- className={cn("size-full object-cover", className)}- />- );- }- if (output.kind === "audio") {- return (- <div className={cn("flex size-full flex-col items-center justify-center gap-3 bg-brand-faint p-4 text-brand-text", className)}>- <AudioLines className="size-8" />- <audio src={output.url} controls className="w-full" onClick={(e) => e.stopPropagation()} />- </div>- );- }- // eslint-disable-next-line @next/next/no-img-element- return <img src={output.url} alt="" loading="lazy" className={cn("size-full object-cover", className)} />;-}+export { MediaThumb } from "./result-media";+export { downloadName } from "@/lib/library";+/** A result's tile shape: its aspect ratio (the request's or the model's default, from the server). */export function tileRatio(g: Generation): number {- const ar = g.request.params?.aspectRatio ?? getModel(g.modelId)?.defaults?.aspectRatio;if (g.kind === "audio") return 1.6;+ if (g.kind === "text") return 0.85;+ const ar = g.request.params?.aspectRatio ?? g.aspectRatio ?? undefined;return ratioValue(ar && ar !== "auto" ? ar : undefined, g.kind === "video" ? 16 / 9 : 1);}@@ -147,7 +49,14 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {</div><Tooltip><TooltipTrigger asChild>- <button onClick={() => void cancel(g)} className="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground hover:text-foreground" aria-label="Cancel">+ <button+ onClick={(e) => {+ e.stopPropagation();+ void cancel(g);+ }}+ className="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground hover:text-foreground"+ aria-label="Cancel"+ ><X className="size-3.5" /></button></TooltipTrigger>@@ -170,7 +79,13 @@ export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number<p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>{g.error && <p className="line-clamp-5 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground">{g.error}</p>}</div>- <button onClick={onRetry} className="mt-2 inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent">+ <button+ onClick={(e) => {+ e.stopPropagation();+ onRetry();+ }}+ className="mt-2 inline-flex h-7 w-fit 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>@@ -187,33 +102,107 @@ export function useFinalizeDraft() {);}-export function GenerationGroup({- g,- onOpen,- onReuse,-}: {- g: Generation;- onOpen: (g: Generation, index: number) => void;- onReuse?: (g: Generation) => void;-}) {- const { favorite, remove } = useGenerationActions();- const create = useCreateGeneration();- const model = getModel(g.modelId);- const preset = g.presetId ? getPreset(g.presetId) : undefined;+// ---------------------------------------------------------------------------+// Feed: one stable context for every group, so a poll or a keystroke re-renders only what changed.++interface FeedApi {+ open: (g: Generation, index: number) => void;+ retry: (g: Generation) => void;+ runner: RunnerOptions;+ reuse?: (g: Generation) => void;+}++const FeedCtx = createContext<FeedApi | null>(null);++function useFeed(): FeedApi {+ const c = useContext(FeedCtx);+ if (!c) throw new Error("GenerationGroup outside Feed");+ return c;+}++function DraftButton({ g, draftId }: { g: Generation; draftId: string }) {+ const finalize = useFinalizeDraft();+ return (+ <button+ onClick={(e) => {+ e.stopPropagation();+ finalize(g, draftId);+ }}+ className="absolute top-2 left-2 inline-flex h-7 items-center gap-1 rounded-full bg-black/55 pr-2.5 pl-2 text-[12px] font-medium text-white backdrop-blur transition-colors hover:bg-black/75"+ >+ <Sparkles className="size-3.5" /> Draft · render 1080p+ </button>+ );+}++const OutputTile = memo(function OutputTile({ g, index, ratio, layered }: { g: Generation; index: number; ratio: number; layered?: boolean }) {+ const feed = useFeed();+ const canHover = useCanHover();+ // Actions mount on first hover / focus / tap: a long feed shouldn't hold thousands of menus and tooltips.+ const [hot, setHot] = useState<false | "bar" | "menu">(false);+ const o = g.outputs[index];+ const ctx = useMemo(() => ({ reuse: !!feed.reuse }), [feed.reuse]);+ return (+ <div+ role="button"+ tabIndex={0}+ aria-label={`Open ${o.kind === "text" ? "text" : o.kind}${g.outputs.length > 1 && !layered ? ` ${index + 1} of ${g.outputs.length}` : ""}`}+ onClick={() => feed.open(g, index)}+ onKeyDown={(e) => {+ if (e.target === e.currentTarget && (e.key === "Enter" || e.key === " ")) {+ e.preventDefault();+ feed.open(g, index);+ }+ }}+ onPointerEnter={(e) => e.pointerType === "mouse" && !hot && setHot("bar")}+ onFocus={() => canHover && !hot && setHot("bar")}+ className="group/tile relative h-56 max-w-full animate-fade-up cursor-zoom-in overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring sm:h-64"+ style={{ aspectRatio: o.kind === "audio" ? 1.6 : layered ? Math.max(ratio, 0.8) : ratio }}+ >+ {layered ? <LayersStack g={g} /> : <MediaThumb output={o} g={g} />}+ {o.draftId && <DraftButton g={g} draftId={o.draftId} />}+ {g.favorite && <Heart className="absolute top-2 right-2 size-4 fill-highlight text-highlight drop-shadow" />}+ {o.kind !== "audio" && canHover && hot === "bar" && (+ <TileActions+ g={g}+ index={index}+ ctx={ctx}+ opts={feed.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/tile:opacity-100 group-hover/tile:opacity-100"+ />+ )}+ {!canHover &&+ (hot === "menu" ? (+ <TileActions g={g} index={index} ctx={ctx} opts={feed.runner} menuOnly className={cn("absolute right-2", g.favorite ? "top-8" : "top-2")} />+ ) : (+ <button+ aria-label="More actions"+ onClick={(e) => {+ e.stopPropagation();+ setHot("menu");+ }}+ className={cn("absolute right-2 grid size-8 place-items-center rounded-lg bg-black/45 text-white backdrop-blur", g.favorite ? "top-8" : "top-2")}+ >+ <MoreHorizontal className="size-4" />+ </button>+ ))}+ </div>+ );+});++/** One request: the user's words in serif, a meta line, then its outputs (or progress / failure). */+export const GenerationGroup = memo(function GenerationGroup({ g }: { g: Generation }) {+ const feed = useFeed();+ const { favorite, trash } = useGenerationActions();const ratio = tileRatio(g);const active = g.status === "queued" || g.status === "running";const placeholders = Math.max(1, g.request.params?.numOutputs ?? 1);- const retry = () =>- create.mutate(g.request, {- onError: (e) => toast.error((e as Error).message),- });- const finalize = useFinalizeDraft();- const saveCharacter = useSaveAsCharacter();+ const layered = g.status === "succeeded" && isLayered(g);const p = g.request.params ?? {};const meta = [g.request.step?.label,- preset?.name,- model?.name ?? g.modelId,+ g.presetName,+ g.modelName ?? g.modelId,OPERATION_LABELS[g.op],p.aspectRatio,p.resolution,@@ -221,11 +210,11 @@ export function GenerationGroup({].filter(Boolean);return (- <section className="group/gen animate-fade-up space-y-2.5">+ <section data-gen-id={g.id} className="group/gen animate-fade-up space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]"><header className="flex items-start gap-3"><div className="min-w-0 flex-1"><h3 className="line-clamp-2 font-heading text-[19px] leading-snug" title={g.prompt ?? undefined}>- {g.request.prompt?.trim() || preset?.name || g.prompt || "Untitled"}+ {userTitle(g)}</h3><p className="mt-0.5 flex flex-wrap items-center gap-x-1.5 text-[12px] text-muted-foreground"><span className="inline-flex items-center gap-1">@@ -241,18 +230,17 @@ export function GenerationGroup({{g.costUsd ? <span className="font-mono before:mr-1.5 before:content-['·']">{formatCost(g.costUsd)}</span> : null}</p></div>- <div className="flex shrink-0 items-center gap-0.5 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/gen:opacity-100 sm:focus-within:opacity-100">- {onReuse && (- <Tooltip>- <TooltipTrigger asChild>- <button onClick={() => onReuse(g)} className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground">- <RotateCcw className="size-3.5" /> Reuse- </button>- </TooltipTrigger>- <TooltipContent>Load prompt, model and settings into the composer</TooltipContent>- </Tooltip>+ <div className="flex shrink-0 items-center gap-0.5 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/gen:opacity-100 sm:focus-within:opacity-100 [@media(hover:none)]:opacity-100">+ {feed.reuse && (+ <button+ onClick={() => feed.reuse?.(g)}+ title="Load prompt, model and settings into the composer"+ className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground"+ >+ <RotateCcw className="size-3.5" /> Reuse+ </button>)}- <DropdownMenu>+ <DropdownMenu modal={false}><DropdownMenuTrigger asChild><button className="grid size-8 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="More"><MoreHorizontal className="size-4" />@@ -260,27 +248,28 @@ export function GenerationGroup({</DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem- onClick={() => {+ onSelect={() => {void navigator.clipboard.writeText(g.prompt ?? "");toast("Prompt copied");}}><Copy /> Copy prompt</DropdownMenuItem>- <DropdownMenuItem onClick={retry}>+ <DropdownMenuItem onSelect={() => feed.retry(g)}><RotateCcw /> Run again</DropdownMenuItem>- <DropdownMenuItem onClick={() => void favorite(g)}>+ <DropdownMenuItem onSelect={() => void favorite(g)}><Heart /> {g.favorite ? "Remove from favorites" : "Add to favorites"}</DropdownMenuItem>+ {g.status === "succeeded" && g.outputs.length > 1 && (+ <DropdownMenuItem asChild>+ <a href={`/api/generations/zip?ids=${g.id}`} download>+ <FolderDown /> Download all ({g.outputs.length})+ </a>+ </DropdownMenuItem>+ )}<DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- onClick={() => {- void remove(g);- toast("Deleted");- }}- >+ <DropdownMenuItem variant="destructive" onSelect={() => void trash([g])}><Trash2 /> Delete</DropdownMenuItem></DropdownMenuContent>@@ -296,86 +285,15 @@ export function GenerationGroup({))}{(g.status === "failed" || g.status === "canceled") && (<div className="h-56 max-w-full sm:h-64">- <FailedTile g={g} ratio={ratio} onRetry={retry} />+ <FailedTile g={g} ratio={ratio} onRetry={() => feed.retry(g)} /></div>)}{g.status === "succeeded" &&- g.outputs.map((o, i) => (- <div- key={o.url}- role="button"- tabIndex={0}- onClick={() => onOpen(g, i)}- onKeyDown={(e) => e.key === "Enter" && onOpen(g, i)}- className="group/tile relative h-56 max-w-full animate-fade-up cursor-zoom-in overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring sm:h-64"- style={{ aspectRatio: o.kind === "audio" ? 1.6 : ratio }}- >- <MediaThumb output={o} />- {o.draftId && (- <button- onClick={(e) => {- e.stopPropagation();- finalize(g, o.draftId!);- }}- className="absolute top-2 left-2 inline-flex h-7 items-center gap-1 rounded-full bg-black/55 pr-2.5 pl-2 text-[12px] font-medium text-white backdrop-blur transition-colors hover:bg-black/75"- >- <Sparkles className="size-3.5" /> Draft · render 1080p- </button>- )}- {g.favorite && <Heart className="absolute top-2 right-2 size-4 fill-highlight text-highlight drop-shadow" />}- {o.kind !== "audio" && (- <div className="absolute inset-x-0 bottom-0 flex items-center gap-0.5 bg-gradient-to-t from-black/60 to-transparent p-2 pt-8 opacity-0 transition-opacity duration-100 group-focus-within/tile:opacity-100 group-hover/tile:opacity-100">- <IconAction label="Download" href={`${o.url}?download=${encodeURIComponent(downloadName(g, o, i))}`}>- <Download className="size-4" />- </IconAction>- <IconAction label={g.favorite ? "Unfavorite" : "Favorite"} onClick={() => void favorite(g)}>- <Heart className={cn("size-4", g.favorite && "fill-current")} />- </IconAction>- {o.kind === "image" ? (- <>- <IconAction label="Animate" href={`/video?image=${encodeURIComponent(o.url)}`}>- <Clapperboard className="size-4" />- </IconAction>- <IconAction label="Edit" href={`/edit?image=${encodeURIComponent(o.url)}`}>- <Wand2 className="size-4" />- </IconAction>- <IconAction label="Upscale" href={`/upscale?image=${encodeURIComponent(o.url)}`}>- <ZoomIn className="size-4" />- </IconAction>- <IconAction label="Use as reference" href={`/image?ref=${encodeURIComponent(o.url)}`}>- <ImagePlus className="size-4" />- </IconAction>- <IconAction label="Save as character" onClick={() => saveCharacter(g, o)}>- <UserRoundPlus className="size-4" />- </IconAction>- </>- ) : (- <>- <IconAction label="Extend" href={`/extend?video=${encodeURIComponent(o.url)}`}>- <FastForward className="size-4" />- </IconAction>- <IconAction label="Reframe" href={`/reframe?video=${encodeURIComponent(o.url)}`}>- <Crop className="size-4" />- </IconAction>- <IconAction label="Lipsync" href={`/lipsync?video=${encodeURIComponent(o.url)}`}>- <Mic2 className="size-4" />- </IconAction>- <IconAction label="Upscale" href={`/upscale?video=${encodeURIComponent(o.url)}`}>- <ZoomIn className="size-4" />- </IconAction>- <IconAction label="Add sound" href={`/audio?video=${encodeURIComponent(o.url)}`}>- <AudioLines className="size-4" />- </IconAction>- </>- )}- </div>- )}- </div>- ))}+ (layered ? <OutputTile g={g} index={0} ratio={ratio} layered /> : g.outputs.map((o, i) => <OutputTile key={o.url} g={g} index={i} ratio={ratio} />))}</div></section>);-}+});export function Feed({items,@@ -387,26 +305,46 @@ export function Feed({empty?: React.ReactNode;}) {const [open, setOpen] = useState<{ id: string; index: number } | null>(null);+ const create = useCreateGeneration();+ // Groups get stable callbacks that read the latest props through refs.+ const createRef = useRef(create);+ const reuseRef = useRef(onReuse);+ useEffect(() => {+ createRef.current = create;+ reuseRef.current = onReuse;+ });+ const hasReuse = !!onReuse;+ const openAt = useCallback((g: Generation, index: number) => setOpen({ id: g.id, index }), []);+ const api = useMemo<FeedApi>(+ () => ({+ open: openAt,+ retry: (g) => createRef.current.mutate(g.request, { onError: (e) => toast.error((e as Error).message) }),+ reuse: hasReuse ? (g) => reuseRef.current?.(g) : undefined,+ runner: { onOpen: openAt, onReuse: hasReuse ? (g) => reuseRef.current?.(g) : undefined },+ }),+ [openAt, hasReuse],+ );if (!items.length) return <>{empty}</>;- const flat = items.flatMap((g) => (g.status === "succeeded" ? g.outputs.map((_, i) => ({ g, i })) : []));- const pos = open ? flat.findIndex((f) => f.g.id === open.id && f.i === open.index) : -1;+ const flat = items.flatMap((g) => (g.status === "succeeded" ? (isLayered(g) ? [{ g, i: 0 }] : g.outputs.map((_, i) => ({ g, i }))) : []));+ const pos = open ? flat.findIndex((f) => f.g.id === open.id && (f.i === open.index || isLayered(f.g))) : -1;return (- <>+ <FeedCtx.Provider value={api}><div className="space-y-9">{items.map((g) => (- <GenerationGroup key={g.id} g={g} onOpen={(gg, i) => setOpen({ id: gg.id, index: i })} onReuse={onReuse} />+ <GenerationGroup key={g.id} g={g} />))}</div>{open && pos >= 0 && (<Viewergeneration={flat[pos].g}- index={flat[pos].i}+ 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}onReuse={onReuse}/>)}- </>+ </FeedCtx.Provider>);}diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxnew file mode 100644index 00000000..cd76bb07--- /dev/null+++ b/src/components/studio/result-actions.tsx@@ -0,0 +1,388 @@+"use client";++import {+ ArchiveRestore,+ AudioLines,+ Box,+ Clapperboard,+ Columns2,+ Copy,+ Crop,+ Download,+ FastForward,+ FileDown,+ FolderDown,+ Heart,+ ImagePlus,+ Mic2,+ MoreHorizontal,+ RotateCcw,+ SlidersHorizontal,+ Sparkles,+ Trash2,+ UserRoundPlus,+ Wand2,+ ZoomIn,+ type LucideIcon,+} from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useMemo, useState, useSyncExternalStore } from "react";+import { toast } from "sonner";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+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 { cuesOf, cuesToSrt, outputActions, textOf, type ActionContext, type OutputAction, type OutputActionId } from "@/lib/output-actions";+import { cn } from "@/lib/utils";++export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {+ animate: Clapperboard,+ edit: Wand2,+ upscale: ZoomIn,+ reference: ImagePlus,+ grade: SlidersHorizontal,+ "save-character": UserRoundPlus,+ extend: FastForward,+ reframe: Crop,+ lipsync: Mic2,+ "add-sound": AudioLines,+ "voice-change": AudioLines,+ "copy-text": Copy,+ "view-3d": Box,+ download: Download,+ "download-txt": FileDown,+ "download-srt": FileDown,+ "download-all": FolderDown,+ favorite: Heart,+ finalize: Sparkles,+ compare: Columns2,+ reuse: RotateCcw,+ "copy-prompt": Copy,+ delete: Trash2,+ restore: ArchiveRestore,+ "delete-forever": Trash2,+};++/** "a 26-year-old surfer from Lisbon, freckles" → "Surfer From Lisbon": a starting name the popover lets you change. */+export function characterName(prompt: string | undefined): string {+ const words = (prompt ?? "")+ .replace(/@\S+/g, "")+ .replace(/[^\p{L}\p{N}\s'-]/gu, " ")+ .split(/\s+/)+ .filter((w) => w.length > 2 && !/\d/.test(w) && !/^(the|and|with|from|who|year|old|of)$/i.test(w));+ const pick = words+ .slice(0, 3)+ .map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase())+ .join(" ");+ return pick || "New character";+}++function saveBlob(text: string, name: string, type: string) {+ const url = URL.createObjectURL(new Blob([text], { type }));+ const a = document.createElement("a");+ a.href = url;+ a.download = name;+ a.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}++/** Download a file URL without navigating (keyboard shortcut, menus). */+export function downloadUrl(href: string, name?: string) {+ const a = document.createElement("a");+ a.href = href;+ a.download = name ?? "";+ a.click();+}++export interface RunnerOptions {+ onOpen?: (g: Generation, index: number) => void;+ onReuse?: (g: Generation) => void;+ onCompare?: () => void;+ onDeleted?: () => void;+}++/** Handlers for the actions that aren't plain links. "save-character" is handled by the caller's popover. */+export function useActionRunner(opts: RunnerOptions = {}) {+ const actions = useGenerationActions();+ const create = useCreateGeneration();+ return (a: OutputAction, g: Generation, index: number) => {+ const o = g.outputs[index];+ switch (a.id) {+ case "favorite":+ return void actions.favorite(g);+ case "copy-text":+ void navigator.clipboard.writeText(textOf(o));+ return void toast("Copied");+ case "copy-prompt":+ void navigator.clipboard.writeText(g.prompt ?? "");+ return void toast("Prompt copied");+ case "download-txt":+ return saveBlob(textOf(o), downloadName(g, o, index, "txt"), "text/plain");+ case "download-srt":+ return saveBlob(cuesToSrt(cuesOf(o)), downloadName(g, o, index, "srt"), "application/x-subrip");+ case "finalize":+ return create.mutate(+ { feature: g.feature, modelId: g.modelId, op: "finalize", prompt: g.request.prompt, params: { draftId: o.draftId, resolution: "1080p", duration: g.request.params?.duration } },+ { onSuccess: () => toast.success("Rendering the final 1080p version"), onError: (e) => toast.error((e as Error).message) },+ );+ case "reuse":+ return opts.onReuse?.(g);+ case "compare":+ return opts.onCompare?.();+ case "view-3d":+ return opts.onOpen?.(g, index);+ case "delete":+ void actions.trash([g]);+ return opts.onDeleted?.();+ case "restore":+ void actions.restore([g]);+ return void toast("Restored");+ case "delete-forever":+ void actions.deleteForever([g]);+ toast("Deleted for good");+ return opts.onDeleted?.();+ }+ };+}++/** Name + kind before saving an output as an @element (U26). */+export function SaveElementForm({ g, o, onDone }: { g: Generation; o: OutputFile; onDone: () => void }) {+ const save = useSaveElement();+ const router = useRouter();+ const [name, setName] = useState(() => characterName(g.request.prompt));+ const [kind, setKind] = useState<ElementKind>("character");+ const submit = () =>+ save.mutate(+ { name: name.trim() || "New character", kind, references: [o.url] },+ {+ onSuccess: (el) => {+ onDone();+ toast.success(`Saved as @${el.handle}`, { action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } });+ },+ onError: (e) => toast.error((e as Error).message),+ },+ );+ return (+ <form+ className="space-y-3"+ onSubmit={(e) => {+ e.preventDefault();+ submit();+ }}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="space-y-1">+ <label htmlFor={`el-name-${g.id}`} className="text-[12px] font-medium text-muted-foreground">+ Save as element+ </label>+ <input+ id={`el-name-${g.id}`}+ autoFocus+ value={name}+ onChange={(e) => setName(e.target.value)}+ maxLength={60}+ placeholder="e.g. “Maya”"+ className="h-9 w-full rounded-lg border bg-background px-3 text-[14px] outline-none focus:border-primary focus:ring-4 focus:ring-brand-faint"+ />+ </div>+ <div role="radiogroup" aria-label="Kind" className="flex flex-wrap gap-1 rounded-full bg-muted p-0.5">+ {ELEMENT_KINDS.filter((k) => k.kind !== "voice").map((k) => (+ <button+ key={k.kind}+ type="button"+ role="radio"+ aria-checked={kind === k.kind}+ onClick={() => setKind(k.kind)}+ className={cn("h-7 flex-1 rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap transition-colors", kind === k.kind ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}+ >+ {k.label}+ </button>+ ))}+ </div>+ <button+ type="submit"+ disabled={save.isPending}+ className="inline-flex h-8 w-full items-center justify-center gap-1.5 rounded-full bg-primary text-[13px] font-medium text-primary-foreground transition hover:opacity-90 disabled:opacity-60"+ >+ <UserRoundPlus className="size-3.5" /> Save+ </button>+ </form>+ );+}++const stop = (e: React.SyntheticEvent) => e.stopPropagation();++const HOVER = "(hover: hover)";+/** Whether the device can hover (mouse, trackpad); false on touch screens. True until hydrated. */+export function useCanHover(): boolean {+ return useSyncExternalStore(+ (cb) => {+ const m = window.matchMedia(HOVER);+ m.addEventListener("change", cb);+ return () => m.removeEventListener("change", cb);+ },+ () => window.matchMedia(HOVER).matches,+ () => true,+ );+}++const TILE_ICON = "grid size-8 place-items-center rounded-lg text-white/90 transition-colors hover:bg-white/20 hover:text-white focus-visible:bg-white/20 outline-none";++/**+ * The action strip on a result tile: a labelled primary pill, Download and Favorite icons, and a ⋯+ * menu with the rest. Tiles mount it lazily (on first hover or focus), so long feeds don't mount+ * thousands of tooltips, menus and mutation observers. `menuOnly` (touch screens): just the ⋯ menu+ * with every action, opened right away.+ */+export function TileActions({+ g,+ index,+ ctx,+ opts,+ menuOnly,+ className,+}: {+ g: Generation;+ index: number;+ ctx?: ActionContext;+ opts?: RunnerOptions;+ menuOnly?: boolean;+ className?: string;+}) {+ const run = useActionRunner(opts);+ const list = useMemo(() => outputActions(g, index, ctx), [g, index, ctx]);+ const [saving, setSaving] = useState(false);+ const popover = saving && (+ <Popover open onOpenChange={(v) => !v && setSaving(false)}>+ <PopoverAnchor className="absolute right-2 bottom-2" />+ <PopoverContent align="end" collisionPadding={12} className="w-72" onClick={stop}>+ <SaveElementForm g={g} o={g.outputs[index]} onDone={() => setSaving(false)} />+ </PopoverContent>+ </Popover>+ );+ 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")} />+ {popover}+ </div>+ );+ }+ const primary = list.find((a) => a.placement === "primary");+ const bar = list.filter((a) => a.placement === "bar");+ const icon = TILE_ICON;+ const pill = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full bg-white/90 px-3 text-[12px] font-medium text-black shadow-soft transition-colors hover:bg-white outline-none focus-visible:ring-2 focus-visible:ring-white";+ const PrimaryIcon = primary ? ACTION_ICONS[primary.id] : null;+ return (+ <div className={cn("flex items-center gap-0.5", className)} onClick={stop} onKeyDown={stop}>+ {primary &&+ PrimaryIcon &&+ (primary.href ? (+ <Link href={primary.href} prefetch={false} className={pill}>+ <PrimaryIcon className="size-3.5" /> {primary.label}+ </Link>+ ) : (+ <button className={pill} onClick={() => run(primary, g, index)}>+ <PrimaryIcon className="size-3.5" /> {primary.label}+ </button>+ ))}+ <span className="flex-1" />+ {bar.map((a) => {+ const Icon = ACTION_ICONS[a.id];+ const body = <Icon className={cn("size-4", a.id === "favorite" && g.favorite && "fill-current")} />;+ return (+ <Tooltip key={a.id}>+ <TooltipTrigger asChild>+ {a.download !== undefined ? (+ <a href={a.href} download={a.download} className={icon} aria-label={a.label}>+ {body}+ </a>+ ) : (+ <button className={icon} aria-label={a.label} aria-pressed={a.id === "favorite" ? g.favorite : undefined} onClick={() => run(a, g, index)}>+ {body}+ </button>+ )}+ </TooltipTrigger>+ <TooltipContent>{a.label}</TooltipContent>+ </Tooltip>+ );+ })}+ <ActionMenu g={g} index={index} list={list.filter((a) => a.placement === "menu")} run={run} onSave={() => setSaving(true)} triggerClassName={icon} />+ {popover}+ </div>+ );+}++/** The ⋯ menu. On touch screens tiles show only this (every action is inside). */+export function ActionMenu({+ g,+ index,+ list,+ run,+ onSave,+ triggerClassName,+ label = "More actions",+ defaultOpen,+}: {+ g: Generation;+ index: number;+ list: OutputAction[];+ run: ReturnType<typeof useActionRunner>;+ onSave: () => void;+ triggerClassName?: string;+ label?: string;+ defaultOpen?: boolean;+}) {+ const destructive = list.filter((a) => a.destructive);+ const rest = list.filter((a) => !a.destructive);+ const item = (a: OutputAction) => {+ const Icon = ACTION_ICONS[a.id];+ if (a.href && a.download !== undefined) {+ return (+ <DropdownMenuItem key={a.id} asChild>+ <a href={a.href} download={a.download}>+ <Icon /> {a.label}+ </a>+ </DropdownMenuItem>+ );+ }+ if (a.href) {+ return (+ <DropdownMenuItem key={a.id} asChild>+ <Link href={a.href} prefetch={false}>+ <Icon /> {a.label}+ </Link>+ </DropdownMenuItem>+ );+ }+ return (+ <DropdownMenuItem key={a.id} variant={a.destructive ? "destructive" : "default"} onSelect={() => (a.id === "save-character" ? onSave() : run(a, g, index))}>+ <Icon className={cn(a.id === "favorite" && g.favorite && "fill-current")} /> {a.id === "save-character" ? "Save as element…" : a.label}+ </DropdownMenuItem>+ );+ };+ return (+ <DropdownMenu modal={false} defaultOpen={defaultOpen}>+ <DropdownMenuTrigger asChild>+ <button className={triggerClassName} aria-label={label} onClick={stop}>+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" collisionPadding={12} className="min-w-48" onClick={stop} onCloseAutoFocus={(e) => e.preventDefault()}>+ {rest.map(item)}+ {destructive.length > 0 && <DropdownMenuSeparator />}+ {destructive.map(item)}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/src/components/studio/result-media.tsx b/src/components/studio/result-media.tsxnew file mode 100644index 00000000..c1b1ea2f--- /dev/null+++ b/src/components/studio/result-media.tsx@@ -0,0 +1,170 @@+"use client";++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 { cn } from "@/lib/utils";++/** Any result as a tile picture: image, video (plays on hover), audio, text card, 3D preview. */+export function MediaThumb({+ output,+ g,+ className,+ autoPlay,+ fit,+}: {+ output: OutputFile;+ /** The generation it belongs to (3D models show a sibling turntable or poster). */+ g?: Pick<Generation, "outputs">;+ className?: string;+ autoPlay?: boolean;+ /** Letterbox instead of crop (Library "Fit"). */+ fit?: boolean;+}) {+ const object = fit ? "object-contain" : "object-cover";+ if (output.kind === "video") {+ return (+ <video+ src={`${output.url}#t=0.1`}+ muted+ loop+ playsInline+ preload="metadata"+ autoPlay={autoPlay}+ onMouseEnter={(e) => void e.currentTarget.play().catch(() => {})}+ onMouseLeave={(e) => {+ if (!autoPlay) e.currentTarget.pause();+ }}+ className={cn("size-full", object, className)}+ />+ );+ }+ if (output.kind === "audio") {+ return (+ <div className={cn("flex size-full flex-col items-center justify-center gap-3 bg-brand-faint p-4 text-brand-text", className)}>+ <AudioLines className="size-8" />+ <audio src={output.url} controls className="w-full max-w-64" onClick={(e) => e.stopPropagation()} />+ </div>+ );+ }+ if (output.kind === "text") return <TextPreview output={output} className={className} />;+ if (output.kind === "model3d") {+ const { poster, video } = modelPreview(g ?? { outputs: [output] }, output);+ if (video) return <MediaThumb output={{ url: video, kind: "video" }} autoPlay={autoPlay} fit={fit} className={className} />;+ return (+ <div className={cn("relative flex size-full flex-col items-center justify-center gap-2 bg-muted text-muted-foreground", className)}>+ {poster ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={poster} alt="" loading="lazy" decoding="async" className={cn("absolute inset-0 size-full", object)} />+ ) : (+ <>+ <Box className="size-8" />+ <span className="text-[12px] font-medium">3D model</span>+ </>+ )}+ </div>+ );+ }+ // eslint-disable-next-line @next/next/no-img-element+ return <img src={output.url} alt="" loading="lazy" decoding="async" className={cn("size-full", object, className)} />;+}++/** 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);+ const text = textOf(output).trim();+ return (+ <div className={cn("flex size-full flex-col gap-2 bg-card p-4 text-left", className)}>+ <span className="inline-flex items-center gap-1.5 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">+ <FileText className="size-3.5" /> {cues.length ? `Transcript · ${cues.length} lines` : "Text"}+ </span>+ <p className="line-clamp-[8] min-h-0 flex-1 overflow-hidden text-[13px] leading-relaxed break-words whitespace-pre-line text-foreground">{text || "Empty"}</p>+ </div>+ );+}++/** The full text, with cue timings when there are any (viewer). */+export function TextReader({ output }: { output: OutputFile }) {+ const cues = cuesOf(output);+ if (!cues.length) {+ return <div className="size-full overflow-y-auto p-6 text-body leading-relaxed whitespace-pre-wrap text-foreground sm:p-10">{textOf(output) || "Empty"}</div>;+ }+ return (+ <ol className="size-full space-y-1 overflow-y-auto p-4 sm:p-8">+ {cues.map((c, i) => (+ <li key={i} className="grid grid-cols-[auto_1fr] gap-x-4 rounded-lg px-2 py-1.5 hover:bg-accent">+ <span className="pt-0.5 font-mono text-[12px] text-muted-foreground tabular-nums">+ {cueTime(c.start)} – {cueTime(c.end)}+ </span>+ <span className="text-body leading-relaxed">{c.text}</span>+ </li>+ ))}+ </ol>+ );+}++/** 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 }) {+ const layers = g.outputs.map((o, i) => ({ o, ...layerInfo(o, i) })).sort((a, b) => a.z - b.z);+ 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>+ <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+ </span>+ </div>+ <ul className="absolute inset-x-2 bottom-2 flex flex-wrap gap-1">+ {[...layers].reverse().slice(0, 4).map((l) => (+ <li key={l.o.url} className="max-w-32 truncate rounded-full bg-background/85 px-2 py-0.5 text-[11px] font-medium backdrop-blur">+ {l.name}+ </li>+ ))}+ {layers.length > 4 && <li className="rounded-full bg-background/85 px-2 py-0.5 text-[11px] text-muted-foreground backdrop-blur">+{layers.length - 4}</li>}+ </ul>+ </div>+ );+}++/** A .glb in an orbitable viewer. @google/model-viewer (with three.js) loads only when one is opened. */+export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }) {+ const [ready, setReady] = useState(false);+ const [failed, setFailed] = useState(false);+ useEffect(() => {+ let live = true;+ import("@google/model-viewer").then(+ () => live && setReady(true),+ () => live && setFailed(true),+ );+ return () => {+ live = false;+ };+ }, []);+ const { poster } = modelPreview(g, output);+ if (failed) return <p className="text-[13px] text-white/80">Couldn't load the 3D viewer. Download the .glb to open it.</p>;+ if (!ready) {+ return (+ <div className="flex flex-col items-center gap-2 text-white/80">+ <Box className="size-8 animate-pulse" />+ <span className="text-[13px]">Loading 3D viewer…</span>+ </div>+ );+ }+ return createElement("model-viewer", {+ src: output.url,+ poster,+ alt: g.request.prompt || "3D model",+ "camera-controls": "",+ "auto-rotate": "",+ "shadow-intensity": "1",+ exposure: "1",+ "touch-action": "pan-y",+ style: { width: "100%", height: "100%", background: "transparent" },+ });+}diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsxindex 0910518d..1f3a3c37 100644--- a/src/components/studio/studio-context.tsx+++ b/src/components/studio/studio-context.tsx@@ -52,23 +52,37 @@ export interface Draft {mix?: { presetId: string; strength: number };}-interface Ctx {+interface Actions {config: StudioConfig;- draft: Draft;setDraft: (patch: Partial<Draft> | ((d: Draft) => Partial<Draft>)) => void;setSlot: (key: SlotKey, v: SlotValue | null) => void;/** Put an image somewhere sensible (first empty image slot, else references). */addImage: (v: SlotValue) => void;}-const StudioCtx = createContext<Ctx | null>(null);+interface Ctx extends Actions {+ draft: Draft;+}-export function useStudio(): Ctx {- const c = useContext(StudioCtx);- if (!c) throw new Error("useStudio outside StudioProvider");+// Two contexts: the draft changes on every keystroke, the config and actions never do, so the+// page shell and the feed (which only need actions) don't re-render while you type.+const ActionsCtx = createContext<Actions | null>(null);+const DraftCtx = createContext<Draft | null>(null);++/** Config and stable actions only: use this where the draft isn't needed (no re-render per keystroke). */+export function useStudioActions(): Actions {+ const c = useContext(ActionsCtx);+ if (!c) throw new Error("useStudioActions outside StudioProvider");return c;}+/** Everything, including the draft (re-renders on every draft change). */+export function useStudio(): Ctx {+ const actions = useStudioActions();+ const draft = useContext(DraftCtx)!;+ return useMemo(() => ({ ...actions, draft }), [actions, draft]);+}+export function StudioProvider({config,initial,@@ -98,11 +112,15 @@ export function StudioProvider({},[config],);- const value = useMemo(() => ({ config, draft, setDraft, setSlot, addImage }), [config, draft, setDraft, setSlot, addImage]);- return <StudioCtx.Provider value={value}>{children}</StudioCtx.Provider>;+ const actions = useMemo(() => ({ config, setDraft, setSlot, addImage }), [config, setDraft, setSlot, addImage]);+ return (+ <ActionsCtx.Provider value={actions}>+ <DraftCtx.Provider value={draft}>{children}</DraftCtx.Provider>+ </ActionsCtx.Provider>+ );}/** Replace a slot value by key, updating only when it's the same upload (async upload callbacks). */-export function slotUpdater(setSlot: Ctx["setSlot"], key: SlotKey) {+export function slotUpdater(setSlot: Actions["setSlot"], key: SlotKey) {return (v: SlotValue | null) => setSlot(key, v);}diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsxindex 3b7dd7bd..795d5466 100644--- a/src/components/studio/studio-page.tsx+++ b/src/components/studio/studio-page.tsx@@ -1,8 +1,8 @@"use client";-import { Upload } from "lucide-react";+import { ArrowUp, Loader2, Upload } from "lucide-react";import { useSearchParams } from "next/navigation";-import { Suspense, useMemo, useRef, useState } from "react";+import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";import { nanoid } from "nanoid";import { SidebarTrigger } from "@/components/ui/sidebar";import { Skeleton } from "@/components/ui/skeleton";@@ -14,7 +14,7 @@ import { Composer } from "./composer";import { EngineSwitch } from "./engine-switch";import { Feed } from "./feed";import { fileToSlot, type SlotValue } from "./media-slot";-import { StudioProvider, useStudio, type Draft, type StudioConfig } from "./studio-context";+import { StudioProvider, useStudioActions, type Draft, type StudioConfig } from "./studio-context";function kindOfUrl(url: string): MediaKind {if (/\.(mp4|webm|mov)(\?|$)/i.test(url)) return "video";@@ -82,21 +82,85 @@ function draftFromGeneration(g: Generation, config: StudioConfig): Partial<Draft};}+/**+ * New results land at the top of the feed while the composer is docked at the bottom: when one+ * arrives off-screen (you scrolled down into your history), a pill above the composer jumps to it (U4).+ */+function useOffscreenResults(items: Generation[] | undefined) {+ const since = useRef(0);+ const seen = useRef<Set<string> | null>(null);+ const [fresh, setFresh] = useState<string[]>([]);+ useEffect(() => {+ since.current = Date.now() - 2000;+ }, []);+ useEffect(() => {+ if (!items) return;+ if (!seen.current) {+ seen.current = new Set(items.map((g) => g.id));+ return;+ }+ const known = seen.current;+ const added = items.filter((g) => !known.has(g.id) && g.createdAt >= since.current);+ items.forEach((g) => known.add(g.id));+ if (!added.length) return;+ const raf = requestAnimationFrame(() => {+ const off = added.filter((g) => !inView(g.id)).map((g) => g.id);+ if (off.length) setFresh((f) => [...new Set([...off, ...f])]);+ });+ return () => cancelAnimationFrame(raf);+ }, [items]);+ // Clear the ones you scrolled to.+ const pending = fresh.length > 0;+ useEffect(() => {+ if (!pending) return;+ let raf = 0;+ const check = () => {+ cancelAnimationFrame(raf);+ raf = requestAnimationFrame(() => setFresh((f) => (f.some(inView) ? f.filter((id) => !inView(id)) : f)));+ };+ window.addEventListener("scroll", check, { passive: true, capture: true });+ return () => {+ cancelAnimationFrame(raf);+ window.removeEventListener("scroll", check, { capture: true });+ };+ }, [pending]);+ const present = fresh.filter((id) => items?.some((g) => g.id === id));+ const working = present.filter((id) => items?.some((g) => g.id === id && (g.status === "queued" || g.status === "running"))).length;+ const jump = () => {+ document.querySelector(`[data-gen-id="${present[0]}"]`)?.scrollIntoView({ behavior: "smooth", block: "start" });+ setFresh([]);+ };+ return { count: present.length, working, jump };+}++function inView(id: string): boolean {+ const el = document.querySelector(`[data-gen-id="${id}"]`);+ if (!el) return false;+ const r = el.getBoundingClientRect();+ return r.bottom > 56 && r.top < window.innerHeight - 160;+}++const EMPTY: Generation[] = [];+function StudioBody({ header }: { header?: React.ReactNode }) {- const { config, setDraft, addImage } = useStudio();+ // Config and actions only: the draft lives in the composer, so typing doesn't re-render the page or the feed.+ const { config, setDraft, addImage } = useStudioActions();const [engine, setEngine] = useEngine();const feed = useGenerations(config.feed);const [dragging, setDragging] = useState(false);const dragDepth = useRef(0);- const items = feed.data ?? [];+ const items = feed.data ?? EMPTY;const hasItems = items.length > 0;+ const offscreen = useOffscreenResults(feed.data);- const reuse = (g: Generation) => {- setDraft(draftFromGeneration(g, config));- const model = getModel(g.modelId);- if (model && model.engine !== engine) setEngine(model.engine);- requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>("[data-composer] textarea")?.focus());- };+ const reuse = useCallback(+ (g: Generation) => {+ setDraft(draftFromGeneration(g, config));+ if (g.engine !== engine) setEngine(g.engine);+ requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>("[data-composer] textarea")?.focus());+ },+ [config, engine, setDraft, setEngine],+ );const composer = (docked: boolean) => (<div data-composer className={cn("mx-auto w-full", docked ? "max-w-[800px]" : "max-w-[760px]")}>@@ -173,6 +237,18 @@ function StudioBody({ header }: { header?: React.ReactNode }) {{hasItems && (<div className="sticky bottom-0 z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6">+ {offscreen.count > 0 && (+ <div className="pointer-events-none absolute inset-x-0 -top-2 flex justify-center">+ <button+ onClick={offscreen.jump}+ className="pointer-events-auto inline-flex h-8 animate-pop-in items-center gap-1.5 rounded-full bg-foreground px-3.5 text-[13px] font-medium text-background shadow-strong transition hover:opacity-90"+ >+ {offscreen.working ? <Loader2 className="size-3.5 animate-spin" /> : null}+ {offscreen.working ? `${offscreen.working} generating` : `${offscreen.count} new result${offscreen.count === 1 ? "" : "s"}`}+ <ArrowUp className="size-3.5" />+ </button>+ </div>+ )}{composer(true)}</div>)}diff --git a/src/components/studio/viewer.tsx b/src/components/studio/viewer.tsxindex 2247f9e8..3d313dc3 100644--- a/src/components/studio/viewer.tsx+++ b/src/components/studio/viewer.tsx@@ -1,26 +1,100 @@"use client";-import { ChevronLeft, ChevronRight, Clapperboard, Columns2, Crop, FastForward, SlidersHorizontal, Sparkles, Copy, Download, Heart, RotateCcw, Trash2, Wand2, X, ZoomIn } from "lucide-react";+import { ChevronLeft, ChevronRight, Columns2, Copy, Info, Layers, MoreHorizontal, X } from "lucide-react";import Link from "next/link";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";import { Kbd } from "@/components/ui/kbd";-import { getModel, getPreset } from "@/lib/catalog";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";-import { useGenerationActions } from "@/lib/api";import { formatCost, timeAgo } from "@/lib/format";+import { trashDaysLeft, userTitle } from "@/lib/library";+import { isLayered, layerInfo, outputActions, type OutputAction } from "@/lib/output-actions";import { cn } from "@/lib/utils";import { CompareSlider } from "./compare-slider";-import { downloadName, useFinalizeDraft } from "./feed";+import { ACTION_ICONS, downloadUrl, SaveElementForm, useActionRunner } from "./result-actions";+import { LayersStack, ModelViewer, TextReader } from "./result-media";+function Row({ label, value, mono }: { label: string; value?: React.ReactNode; mono?: boolean }) {if (value === undefined || value === null || value === "") return null;return (<div className="flex justify-between gap-4 py-1.5 text-[13px]"><span className="text-muted-foreground">{label}</span>- <span className={cn("text-right", mono && "font-mono")}>{value}</span>+ <span className={cn("min-w-0 text-right break-words", mono && "font-mono")}>{value}</span>+ </div>+ );+}++/** Keys the viewer leaves alone: typing, browser shortcuts (⌘F, ⌘D…), held-down repeats, a focused player. */+function ignoreKey(e: KeyboardEvent): boolean {+ if (e.metaKey || e.ctrlKey || e.altKey || e.repeat || e.defaultPrevented) return true;+ const t = e.target as HTMLElement | null;+ if (!t) return false;+ if (t.isContentEditable || t.closest("input,textarea,select,[contenteditable]")) return true;+ // Arrows and space seek / play in a focused <video> or <audio>.+ return !!t.closest("video,audio,model-viewer") && (e.key.startsWith("Arrow") || e.key === " ");+}++function Details({ g, index }: { g: Generation; index: number }) {+ const p = g.request.params ?? {};+ const title = userTitle(g);+ return (+ <div className="space-y-4">+ <div>+ <p className="font-heading text-[20px] leading-snug">{title}</p>+ {g.prompt && g.prompt !== title && <p className="mt-1 text-[12px] leading-relaxed break-words text-muted-foreground">Sent to the model: {g.prompt}</p>}+ {g.prompt && (+ <button+ onClick={() => {+ void navigator.clipboard.writeText(g.prompt ?? "");+ toast("Prompt copied");+ }}+ className="mt-1 inline-flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground"+ >+ <Copy className="size-3" /> Copy prompt+ </button>+ )}+ </div>+ <div className="divide-y rounded-lg border px-3">+ <Row label="Model" value={g.modelName ?? g.modelId} />+ <Row label="Engine" value={g.provider === "mock" ? "Demo" : g.provider === "local" ? "In your browser" : g.engine === "open" ? "Open source · ComfyUI" : `Cloud · ${g.provider}`} />+ <Row label="Mode" value={OPERATION_LABELS[g.op]} />+ <Row label="Preset" value={g.presetName} />+ <Row label="Step" value={g.request.step?.label} />+ {isLayered(g) && <Row label="Layer" value={`${layerInfo(g.outputs[index], index).name} · ${index + 1} of ${g.outputs.length}`} />}+ <Row label="Aspect ratio" value={p.aspectRatio ?? g.aspectRatio} />+ <Row label="Quality" value={p.resolution} />+ <Row label="Duration" value={p.duration ? `${p.duration}s` : undefined} />+ <Row label="Seed" value={p.seed} mono />+ <Row label="Cost" value={g.costUsd != null ? formatCost(g.costUsd) : undefined} mono />+ <Row label="Made" value={timeAgo(g.createdAt)} />+ {g.deletedAt && <Row label="In Trash" value={`${trashDaysLeft(g.deletedAt)} days left`} />}+ </div>+ {g.request.negativePrompt && <p className="text-[12px] text-muted-foreground">Negative: {g.request.negativePrompt}</p>}+ </div>+ );+}++function LayerList({ g, index, all, onPick, onAll }: { g: Generation; index: number; all: boolean; onPick: (i: number) => void; onAll: () => void }) {+ const layers = g.outputs.map((o, i) => ({ o, i, ...layerInfo(o, i) })).sort((a, b) => b.z - a.z);+ const item = "flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] transition-colors hover:bg-accent";+ return (+ <div className="space-y-1">+ <p className="px-2 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Layers</p>+ <button onClick={onAll} className={cn(item, all && "bg-brand-faint text-brand-text")}>+ <Layers className="size-4" /> All layers+ </button>+ {layers.map((l) => (+ <button key={l.o.url} onClick={() => onPick(l.i)} className={cn(item, !all && index === l.i && "bg-brand-faint text-brand-text")}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={l.o.url} alt="" className="checkerboard size-8 shrink-0 rounded object-contain" />+ <span className="min-w-0 truncate">{l.name}</span>+ </button>+ ))}</div>);}@@ -32,6 +106,7 @@ export function Viewer({onPrev,onNext,onReuse,+ onIndex,}: {generation: Generation;index: number;@@ -39,206 +114,312 @@ export function Viewer({onPrev?: () => void;onNext?: () => void;onReuse?: (g: Generation) => void;+ /** Switch between the outputs of this generation (layers). */+ onIndex?: (index: number) => void;}) {- const { favorite, remove } = useGenerationActions();- const o = g.outputs[index];- const model = getModel(g.modelId);- const preset = g.presetId ? getPreset(g.presetId) : undefined;- const p = g.request.params ?? {};- const dl = `${o.url}?download=${encodeURIComponent(downloadName(g, o, index))}`;+ const o = g.outputs[index] ?? g.outputs[0];+ const layered = isLayered(g);// Edits, inpaints, upscales and app results can be compared with the image they started from.- const source = o.kind === "image" && g.op !== "t2i" ? g.request.inputs?.images?.[0] : undefined;+ const source = o.kind === "image" && g.op !== "t2i" && !layered ? g.request.inputs?.images?.[0] : undefined;const [comparing, setComparing] = useState(false);- const finalize = useFinalizeDraft();+ const [allLayers, setAllLayers] = useState(layered);+ const [drawer, setDrawer] = useState(false);+ const [saving, setSaving] = useState(false);+ const run = useActionRunner({ onReuse: onReuse && ((x) => (onReuse(x), onClose())), onCompare: () => setComparing((v) => !v), onDeleted: onClose });+ const list = useMemo(() => outputActions(g, index, { reuse: !!onReuse, compare: !!source, inViewer: true }), [g, index, onReuse, source]);+ // Read the latest values from the key handler without re-subscribing on every render.+ const latest = useRef({ list, run, g, index, onPrev, onNext, source });+ useEffect(() => {+ latest.current = { list, run, g, index, onPrev, onNext, source };+ });useEffect(() => {const onKey = (e: KeyboardEvent) => {- if ((e.target as HTMLElement)?.closest("input,textarea")) return;- if (e.key === "ArrowLeft") onPrev?.();- else if (e.key === "ArrowRight") onNext?.();- else if (e.key.toLowerCase() === "f") void favorite(g);- else if (e.key.toLowerCase() === "c" && source) setComparing((v) => !v);- else if (e.key.toLowerCase() === "d") {- const a = document.createElement("a");- a.href = dl;- a.click();- }- else if (e.key.toLowerCase() === "r" && onReuse) {- onReuse(g);- onClose();- }+ if (ignoreKey(e)) return;+ const { list, run, g, index, onPrev, onNext, source } = latest.current;+ const act = (id: OutputAction["id"]) => {+ const a = list.find((x) => x.id === id);+ if (!a) return false;+ if (a.href && a.download !== undefined) downloadUrl(a.href, a.download);+ else run(a, g, index);+ return true;+ };+ const k = e.key.toLowerCase();+ if (e.key === "ArrowLeft" && onPrev) onPrev();+ else if (e.key === "ArrowRight" && onNext) onNext();+ else if (k === "f") act("favorite");+ else if (k === "c" && source) setComparing((v) => !v);+ else if (k === "d") act("download");+ else if (k === "r") act("reuse");+ else return;+ e.preventDefault();};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);- }, [onPrev, onNext, favorite, g, dl, onReuse, onClose, source]);+ }, []);++ // Swipe left / right to browse on touch screens.+ const swipe = useRef<{ x: number; y: number; t: number } | null>(null);+ const onTouchStart = (e: React.TouchEvent) => {+ const t = e.touches[0];+ swipe.current = e.touches.length === 1 ? { x: t.clientX, y: t.clientY, t: Date.now() } : null;+ };+ const onTouchEnd = (e: React.TouchEvent) => {+ const s = swipe.current;+ swipe.current = null;+ const t = e.changedTouches[0];+ if (!s || !t || Date.now() - s.t > 600) return;+ const dx = t.clientX - s.x;+ const dy = t.clientY - s.y;+ if (Math.abs(dx) < 50 || Math.abs(dx) < Math.abs(dy) * 1.5) return;+ if (dx < 0) onNext?.();+ else onPrev?.();+ };++ const primary = list.find((a) => a.placement === "primary");+ const bar = list.filter((a) => a.placement === "bar");+ const menu = list.filter((a) => a.placement === "menu");++ const actionButton = (a: OutputAction, opts: { variant?: "default" | "secondary" | "ghost"; className?: string; onDone?: () => void } = {}) => {+ const Icon = ACTION_ICONS[a.id];+ const label = a.id === "favorite" ? (g.favorite ? "Favorited" : "Favorite") : a.id === "save-character" ? "Save as element" : a.label;+ const icon = <Icon className={cn(a.id === "favorite" && g.favorite && "fill-current text-highlight")} />;+ const cls = cn(a.destructive && "text-destructive hover:text-destructive", opts.className);+ const variant = a.destructive ? "ghost" : (opts.variant ?? "secondary");+ if (a.href && a.download !== undefined) {+ return (+ <Button key={a.id} asChild variant={variant} size="sm" className={cls}>+ <a href={a.href} download={a.download} onClick={opts.onDone}>+ {icon} {label}+ </a>+ </Button>+ );+ }+ if (a.href) {+ return (+ <Button key={a.id} asChild variant={variant} size="sm" className={cls}>+ <Link href={a.href} prefetch={false}>+ {icon} {label}+ </Link>+ </Button>+ );+ }+ if (a.id === "save-character") {+ return (+ <Popover key={a.id} open={saving} onOpenChange={setSaving}>+ <PopoverTrigger asChild>+ <Button variant={variant} size="sm" className={cls}>+ {icon} {label}+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" collisionPadding={12} className="w-72">+ <SaveElementForm g={g} o={o} onDone={() => setSaving(false)} />+ </PopoverContent>+ </Popover>+ );+ }+ return (+ <Button+ key={a.id}+ variant={variant}+ size="sm"+ className={cls}+ aria-pressed={a.id === "favorite" ? g.favorite : a.id === "compare" ? comparing : undefined}+ onClick={() => {+ run(a, g, index);+ opts.onDone?.();+ }}+ >+ {icon} {label}+ </Button>+ );+ };++ const media =+ o.kind === "video" ? (+ <video key={o.url} src={o.url} controls autoPlay loop playsInline className="max-h-full max-w-full" />+ ) : o.kind === "audio" ? (+ <audio key={o.url} src={o.url} controls autoPlay className="w-[min(90%,560px)]" />+ ) : o.kind === "text" ? (+ <div className="size-full max-w-3xl bg-background text-foreground sm:rounded-xl">+ <TextReader output={o} />+ </div>+ ) : o.kind === "model3d" ? (+ <ModelViewer key={o.url} output={o} g={g} />+ ) : layered && allLayers ? (+ <LayersStack g={g} className="max-h-full" />+ ) : comparing && source ? (+ <CompareSlider before={source} after={o.url} alt={g.prompt ?? ""} />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element+ <img key={o.url} src={o.url} alt={g.prompt ?? ""} className={cn("max-h-full max-w-full object-contain", layered && "checkerboard")} />+ );return (<Dialog open onOpenChange={(v) => !v && onClose()}><DialogContentshowCloseButton={false}- className="flex h-[min(92vh,900px)] w-[min(96vw,1400px)] max-w-none gap-0 overflow-hidden rounded-xl p-0 sm:max-w-none"+ className="flex h-[100svh] w-screen max-w-none gap-0 overflow-hidden rounded-none p-0 sm:max-w-none md:h-[min(92vh,900px)] md:w-[min(96vw,1400px)] md:rounded-xl">- <DialogTitle className="sr-only">{g.prompt ?? "Generation"}</DialogTitle>- <DialogDescription className="sr-only">Preview and details</DialogDescription>- <div className="relative flex min-w-0 flex-1 items-center justify-center bg-media">- {o.kind === "video" ? (- <video key={o.url} src={o.url} controls autoPlay loop playsInline className="max-h-full max-w-full" />- ) : o.kind === "audio" ? (- <audio key={o.url} src={o.url} controls autoPlay className="w-2/3" />- ) : comparing && source ? (- <CompareSlider before={source} after={o.url} alt={g.prompt ?? ""} />- ) : (- // eslint-disable-next-line @next/next/no-img-element- <img key={o.url} src={o.url} alt={g.prompt ?? ""} className="max-h-full max-w-full object-contain" />- )}- {source && (- <button- onClick={() => setComparing((v) => !v)}- className={cn(- "absolute bottom-4 left-1/2 inline-flex h-9 -translate-x-1/2 items-center gap-1.5 rounded-full px-4 text-[13px] font-medium backdrop-blur transition-colors",- comparing ? "bg-white text-black" : "bg-white/15 text-white hover:bg-white/25",- )}- >- <Columns2 className="size-4" /> {comparing ? "Hide original" : "Compare"}- </button>- )}- {onPrev && (- <button onClick={onPrev} aria-label="Previous" className="absolute top-1/2 left-3 grid size-10 -translate-y-1/2 place-items-center rounded-full bg-white/10 text-white backdrop-blur hover:bg-white/20">- <ChevronLeft className="size-5" />- </button>- )}- {onNext && (- <button onClick={onNext} aria-label="Next" className="absolute top-1/2 right-3 grid size-10 -translate-y-1/2 place-items-center rounded-full bg-white/10 text-white backdrop-blur hover:bg-white/20">- <ChevronRight className="size-5" />- </button>- )}+ <DialogTitle className="sr-only">{userTitle(g)}</DialogTitle>+ <DialogDescription className="sr-only">Preview, actions and details</DialogDescription>+ <div className="relative flex min-w-0 flex-1 flex-col bg-media">+ <div className="relative flex min-h-0 flex-1 items-center justify-center p-0 md:p-2" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>+ {media}+ {source && (+ <button+ onClick={() => setComparing((v) => !v)}+ className={cn(+ "absolute bottom-4 left-1/2 hidden h-9 -translate-x-1/2 items-center gap-1.5 rounded-full px-4 text-[13px] font-medium backdrop-blur transition-colors md:inline-flex",+ comparing ? "bg-white text-black" : "bg-white/15 text-white hover:bg-white/25",+ )}+ >+ <Columns2 className="size-4" /> {comparing ? "Hide original" : "Compare"}+ </button>+ )}+ {onPrev && (+ <button onClick={onPrev} aria-label="Previous" className="absolute top-1/2 left-3 hidden size-10 -translate-y-1/2 place-items-center rounded-full bg-white/10 text-white backdrop-blur hover:bg-white/20 md:grid">+ <ChevronLeft className="size-5" />+ </button>+ )}+ {onNext && (+ <button onClick={onNext} aria-label="Next" className="absolute top-1/2 right-3 hidden size-10 -translate-y-1/2 place-items-center rounded-full bg-white/10 text-white backdrop-blur hover:bg-white/20 md:grid">+ <ChevronRight className="size-5" />+ </button>+ )}+ </div>++ {/* Phones: the main actions stay at the bottom; the rest and the details are in a drawer. */}+ <div className="flex shrink-0 items-center gap-1.5 border-t border-white/10 bg-media px-3 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] md:hidden">+ {onPrev ? (+ <button onClick={onPrev} aria-label="Previous" className="grid size-10 shrink-0 place-items-center rounded-full text-white/90 hover:bg-white/10">+ <ChevronLeft className="size-5" />+ </button>+ ) : (+ <span className="size-10 shrink-0" />+ )}+ <div className="flex min-w-0 flex-1 items-center justify-center gap-1.5">+ {primary && actionButton(primary, { variant: "default", className: "rounded-full" })}+ {bar.map((a) => {+ const Icon = ACTION_ICONS[a.id];+ const cls = "grid size-10 shrink-0 place-items-center rounded-full text-white/90 hover:bg-white/10";+ return a.href && a.download !== undefined ? (+ <a key={a.id} href={a.href} download={a.download} aria-label={a.label} className={cls}>+ <Icon className="size-5" />+ </a>+ ) : (+ <button key={a.id} aria-label={a.label} aria-pressed={a.id === "favorite" ? g.favorite : undefined} onClick={() => run(a, g, index)} className={cls}>+ <Icon className={cn("size-5", a.id === "favorite" && g.favorite && "fill-current text-highlight")} />+ </button>+ );+ })}+ <button onClick={() => setDrawer(true)} aria-label="More actions and details" className="grid size-10 shrink-0 place-items-center rounded-full text-white/90 hover:bg-white/10">+ <MoreHorizontal className="size-5" />+ </button>+ </div>+ {onNext ? (+ <button onClick={onNext} aria-label="Next" className="grid size-10 shrink-0 place-items-center rounded-full text-white/90 hover:bg-white/10">+ <ChevronRight className="size-5" />+ </button>+ ) : (+ <span className="size-10 shrink-0" />+ )}+ </div></div>+<aside className="hidden w-80 shrink-0 flex-col border-l bg-card md:flex"><div className="flex items-center justify-between px-4 pt-3">- <span className="text-[12px] text-muted-foreground">{timeAgo(g.createdAt)}</span>+ <span className="inline-flex items-center gap-1 text-[12px] text-muted-foreground">+ <Info className="size-3.5" /> Details+ </span><button onClick={onClose} className="grid size-8 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Close"><X className="size-4" /></button></div><div className="flex-1 space-y-4 overflow-y-auto px-4 pb-4">- <div>- <p className="font-heading text-[20px] leading-snug">{g.request.prompt?.trim() || preset?.name || g.prompt}</p>- {g.prompt && g.prompt !== g.request.prompt?.trim() && <p className="mt-1 text-[12px] leading-relaxed text-muted-foreground">Sent to the model: {g.prompt}</p>}- {g.prompt && (- <button- onClick={() => {- void navigator.clipboard.writeText(g.prompt ?? "");- toast("Prompt copied");- }}- className="mt-1 inline-flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground"- >- <Copy className="size-3" /> Copy prompt- </button>- )}- </div>- <div className="divide-y rounded-lg border px-3">- <Row label="Model" value={model?.name ?? g.modelId} />- <Row label="Engine" value={g.provider === "mock" ? "Demo" : g.provider === "local" ? "In your browser" : g.engine === "open" ? "Open source · ComfyUI" : `Cloud · ${g.provider}`} />- <Row label="Mode" value={OPERATION_LABELS[g.op]} />- <Row label="Preset" value={preset?.name} />- <Row label="Aspect ratio" value={p.aspectRatio} />- <Row label="Quality" value={p.resolution} />- <Row label="Duration" value={p.duration ? `${p.duration}s` : undefined} />- <Row label="Seed" value={p.seed} mono />- <Row label="Cost" value={g.costUsd != null ? formatCost(g.costUsd) : undefined} mono />- </div>- {g.request.negativePrompt && <p className="text-[12px] text-muted-foreground">Negative: {g.request.negativePrompt}</p>}+ <Details g={g} index={index} />+ {layered && (+ <LayerList+ g={g}+ index={index}+ all={allLayers}+ onAll={() => setAllLayers(true)}+ onPick={(i) => {+ setAllLayers(false);+ onIndex?.(i);+ }}+ />+ )}</div><div className="grid grid-cols-2 gap-2 border-t p-3">- <Button asChild variant="default" size="sm">- <a href={dl}>- <Download /> Download- </a>- </Button>- <Button variant="secondary" size="sm" onClick={() => void favorite(g)}>- <Heart className={cn(g.favorite && "fill-current text-highlight")} /> {g.favorite ? "Favorited" : "Favorite"}- </Button>- {o.kind === "image" && (- <>- <Button asChild variant="secondary" size="sm">- <Link href={`/video?image=${encodeURIComponent(o.url)}&prompt=${encodeURIComponent("")}`}>- <Clapperboard /> Animate- </Link>- </Button>- <Button asChild variant="secondary" size="sm">- <Link href={`/edit?image=${encodeURIComponent(o.url)}`}>- <Wand2 /> Edit- </Link>- </Button>- </>- )}- {o.draftId && (- <Button variant="default" size="sm" className="col-span-2" onClick={() => finalize(g, o.draftId!)}>- <Sparkles /> Render this draft in 1080p- </Button>+ {primary && actionButton(primary, { variant: "default" })}+ {bar.map((a) => actionButton(a))}+ {menu.filter((a) => !a.destructive && a.id !== "compare").map((a) => actionButton(a))}+ {menu.filter((a) => a.destructive).map((a) => actionButton(a, { className: "col-span-2" }))}+ </div>+ <p className="flex flex-wrap gap-x-3 gap-y-1 border-t px-4 py-2 text-[11px] text-muted-foreground">+ {(onPrev || onNext) && (+ <span>+ <Kbd>←</Kbd> <Kbd>→</Kbd> browse+ </span>)}- {o.kind === "video" && (- <>- <Button asChild variant="secondary" size="sm">- <Link href={`/extend?video=${encodeURIComponent(o.url)}`}>- <FastForward /> Extend- </Link>- </Button>- <Button asChild variant="secondary" size="sm">- <Link href={`/reframe?video=${encodeURIComponent(o.url)}`}>- <Crop /> Reframe- </Link>- </Button>- </>+ {!g.deletedAt && (+ <span>+ <Kbd>F</Kbd> favorite+ </span>)}- {(o.kind === "image" || o.kind === "video") && (- <Button asChild variant="secondary" size="sm">- <Link href={`/color-grade?${o.kind}=${encodeURIComponent(o.url)}`}>- <SlidersHorizontal /> Grade- </Link>- </Button>+ {source && (+ <span>+ <Kbd>C</Kbd> compare+ </span>)}- <Button asChild variant="secondary" size="sm">- <Link href={`/upscale?${o.kind === "video" ? "video" : "image"}=${encodeURIComponent(o.url)}`}>- <ZoomIn /> Upscale- </Link>- </Button>+ <span>+ <Kbd>D</Kbd> download+ </span>{onReuse && (- <Button- variant="secondary"- size="sm"- onClick={() => {- onReuse(g);- onClose();- }}- >- <RotateCcw /> Reuse- </Button>+ <span>+ <Kbd>R</Kbd> reuse+ </span>)}- <Button- variant="ghost"- size="sm"- className="col-span-2 text-destructive hover:text-destructive"- onClick={() => {- void remove(g);- onClose();- toast("Deleted");- }}- >- <Trash2 /> Delete- </Button>- </div>- <p className="flex flex-wrap gap-x-3 gap-y-1 border-t px-4 py-2 text-[11px] text-muted-foreground">- <span><Kbd>←</Kbd> <Kbd>→</Kbd> browse</span>- <span><Kbd>F</Kbd> favorite</span>- {source && <span><Kbd>C</Kbd> compare</span>}- <span><Kbd>D</Kbd> download</span>- {onReuse && <span><Kbd>R</Kbd> reuse</span>}</p></aside>- <button onClick={onClose} className="absolute top-3 right-3 grid size-9 place-items-center rounded-full bg-white/10 text-white backdrop-blur md:hidden" aria-label="Close">- <X className="size-4" />++ <button onClick={onClose} className="absolute top-3 right-3 grid size-10 place-items-center rounded-full bg-black/40 text-white backdrop-blur md:hidden" aria-label="Close">+ <X className="size-5" /></button>++ <Sheet open={drawer} onOpenChange={setDrawer}>+ <SheetContent side="bottom" className="max-h-[85svh] gap-0 rounded-t-2xl pb-[max(1rem,env(safe-area-inset-bottom))] md:hidden">+ <SheetHeader className="pb-2">+ <SheetTitle className="text-[15px]">More</SheetTitle>+ <SheetDescription className="sr-only">Every action and the details of this result</SheetDescription>+ </SheetHeader>+ <div className="space-y-4 overflow-y-auto px-4">+ <div className="grid grid-cols-2 gap-2">+ {source && (+ <Button variant="secondary" size="sm" aria-pressed={comparing} onClick={() => (setComparing((v) => !v), setDrawer(false))}>+ <Columns2 /> {comparing ? "Hide original" : "Compare"}+ </Button>+ )}+ {menu.filter((a) => !a.destructive && a.id !== "compare").map((a) => actionButton(a, { onDone: () => a.id !== "save-character" && setDrawer(false) }))}+ {menu.filter((a) => a.destructive).map((a) => actionButton(a, { className: "col-span-2", onDone: () => setDrawer(false) }))}+ </div>+ {layered && (+ <LayerList+ g={g}+ index={index}+ all={allLayers}+ onAll={() => setAllLayers(true)}+ onPick={(i) => {+ setAllLayers(false);+ onIndex?.(i);+ }}+ />+ )}+ <Details g={g} index={index} />+ </div>+ </SheetContent>+ </Sheet></DialogContent></Dialog>);