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
Layers studio: projects grid and editor
Claude06f9d3fa0a3a
diff --git a/src/app/(studio)/layers/[id]/page.tsx b/src/app/(studio)/layers/[id]/page.tsxnew file mode 100644index 00000000..c573d687--- /dev/null+++ b/src/app/(studio)/layers/[id]/page.tsx@@ -0,0 +1,39 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { LayersEditor } from "@/components/layers/layers-editor";+import { getModel } from "@/lib/catalog";+import { CUTOUT_MODELS, TOOL_MODELS, type LayerModelInfo } from "@/lib/layers";++export const metadata: Metadata = { title: "Layers" };++/** Names, prices and providers of the tools' models, built here so the editor ships no catalog. */+function toolModels(): Record<string, LayerModelInfo> {+ const ids = new Set([...Object.values(TOOL_MODELS).flatMap((t) => [...t.cloud, ...t.open]), CUTOUT_MODELS.cloud, CUTOUT_MODELS.open]);+ const out: Record<string, LayerModelInfo> = {};+ for (const id of ids) {+ const m = getModel(id);+ if (!m) continue;+ out[id] = {+ id,+ name: m.name,+ engine: m.engine,+ tagline: m.tagline,+ ...(m.pricing ? { pricing: { unit: m.pricing.unit, usd: m.pricing.usd, ...(m.pricing.note ? { note: m.pricing.note } : {}) } } : {}),+ providers: [...new Set(m.routes.map((r) => r.provider))],+ };+ }+ return out;+}++async function Editor({ params }: { params: PageProps<"/layers/[id]">["params"] }) {+ const { id } = await params;+ return <LayersEditor id={id} models={toolModels()} />;+}++export default function Page({ params }: PageProps<"/layers/[id]">) {+ return (+ <Suspense fallback={null}>+ <Editor params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/layers/page.tsx b/src/app/(studio)/layers/page.tsxnew file mode 100644index 00000000..82d9e179--- /dev/null+++ b/src/app/(studio)/layers/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { LayersProjects } from "@/components/layers/projects-view";++export const metadata: Metadata = { title: "Layers" };++export default function Page() {+ return <LayersProjects />;+}diff --git a/src/app/api/layers/[id]/route.ts b/src/app/api/layers/[id]/route.tsindex 4dd45d42..8a9007ee 100644--- a/src/app/api/layers/[id]/route.ts+++ b/src/app/api/layers/[id]/route.ts@@ -8,6 +8,8 @@ const Patch = z.object({doc: z.unknown().optional(),/** The head version the editor started from (a mismatch means another tab saved a version). */versionId: z.string().max(40).optional(),+ /** The card's cover: a small JPEG/WebP data URL of the composite. */+ cover: z.string().max(300_000).optional(),});/** The project, its versions, the head document and its tools' jobs (with their results). */@@ -25,7 +27,7 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/layers/[idconst doc = parsed.data.doc === undefined ? undefined : parseDoc(parsed.data.doc);if (doc === null) return Response.json({ error: "Those layers couldn't be saved" }, { status: 400 });try {- const p = updateProject(id, { name: parsed.data.name, doc, versionId: parsed.data.versionId });+ const p = updateProject(id, { name: parsed.data.name, doc, versionId: parsed.data.versionId, cover: parsed.data.cover });return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof LayersError ? e.status : 422 });diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 8ea7fba1..c3b71a1e 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -9,6 +9,7 @@ import {MessageCircle,GalleryHorizontal,Layers,+ Layers2,Crop,FastForward,Brush,@@ -97,6 +98,7 @@ const NAV: NavGroupDef[] = [{ href: "/image", label: "Image", icon: ImageIcon },{ href: "/video", label: "Video", icon: Video },{ href: "/edit", label: "Edit", icon: Wand2 },+ { href: "/layers", label: "Layers", icon: Layers2 },{ href: "/inpaint", label: "Inpaint", icon: Brush },{ href: "/color-grade", label: "Color grading", icon: SlidersHorizontal },{ href: "/motions", label: "Camera motions", icon: Film },diff --git a/src/components/layers/apply.ts b/src/components/layers/apply.tsnew file mode 100644index 00000000..0e85b38c--- /dev/null+++ b/src/components/layers/apply.ts@@ -0,0 +1,148 @@+"use client";++import {+ addNodes,+ addRevision,+ getNode,+ nodesFromOutputs,+ placeOutput,+ reframeDoc,+ replaceNodes,+ tightenToAlpha,+ type Box,+ type LayerDoc,+ type LayerJob,+ type LayerNode,+ type LayerRevision,+ type MeasuredOutput,+} from "@/lib/layers";+import { alphaBox, loadImage, sizeOf } from "./render";++/**+ * What a finished tool job does to the document: decompositions and splits become layers (placed by+ * their boxes, or cropped to their alpha), edits become a new revision of their layer (or a new+ * layer on top for the whole image), a region edit becomes the Original / New pair, Expand grows the+ * canvas with the fill underneath.+ */++const NEW_LAYER_NAMES: Partial<Record<LayerJob["tool"], string>> = {+ regenerate: "Edited layer",+ "text-edit": "Text edit",+ "bg-remove": "Cut-out",+ upscale: "Upscaled",+ relight: "Relit",+ angles: "New angle",+};++export interface Applied {+ doc: LayerDoc;+ /** Toast text. */+ message: string;+ /** The layer to select afterwards. */+ select?: string;+}++async function measure(url: string) {+ const img = await loadImage(url);+ return { img, natural: sizeOf(img) };+}++/** Keep the frame's centre and width; take the height from the image's shape. */+function fitBox(frame: Box, natural: [number, number]): Box {+ const h = frame[2] * (natural[1] / natural[0]);+ return [frame[0], frame[1] + frame[3] / 2 - h / 2, frame[2], h];+}++function newNode(id: string, name: string, box: Box, src: string, natural: [number, number], label: string, at: number, crop: Box | null = null, prompt?: string): LayerNode {+ const rev: LayerRevision = { src, crop, natural, label, at, ...(prompt ? { prompt } : {}) };+ return { id, name: name.slice(0, 80), z: 0, x: box[0], y: box[1], w: box[2], h: box[3], rotation: 0, src, crop, natural, revisions: [rev], revision: 0 };+}++export async function applyJob(doc: LayerDoc, job: LayerJob, newId: () => string): Promise<Applied> {+ const outputs = (job.result?.outputs ?? []).filter((o) => o.kind === "image");+ if (!outputs.length) throw new Error("The model returned no image");+ const at = Date.now();+ const prompt = typeof job.settings?.prompt === "string" ? job.settings.prompt : undefined;++ if (job.tool === "decompose" || job.tool === "split") {+ const target = job.tool === "split" ? getNode(doc, job.nodeId) : undefined;+ const frame: Box = target ? [target.x, target.y, target.w, target.h] : job.frame;+ const measured = await Promise.all(outputs.map(async (o) => ({ o, ...(await measure(o.url)) })));+ // Seedream's pixel boxes are measured on its base layer (z 0).+ const base = measured.find((m) => m.o.meta?.z === 0) ?? measured[0];+ const placed: MeasuredOutput[] = [];+ for (const m of measured) {+ let p = placeOutput(frame, m.natural, m.o.meta ?? {}, base.natural);+ if (p.needsAlpha) {+ const t = tightenToAlpha(frame, m.natural, alphaBox(m.img));+ if (!t) continue; // an empty layer+ p = t;+ }+ placed.push({ url: m.o.url, meta: m.o.meta, natural: m.natural, placement: p });+ }+ if (!placed.length) throw new Error("No layers came back from the split");+ const nodes = nodesFromOutputs(placed, {+ id: newId,+ label: job.tool === "split" ? "Separated" : "Decomposed",+ at,+ ...(target ? { baseName: target.name, frame, rotation: target.rotation } : {}),+ });+ if (job.tool === "decompose") {+ return { doc: { ...doc, decomposed: true, nodes }, message: `Decomposed into ${nodes.length} layers` };+ }+ const next = target ? replaceNodes(doc, [target.id], nodes) : addNodes(doc, nodes);+ return { doc: next, message: `${target?.name ?? "Layer"} split into ${nodes.length} layers`, select: nodes[nodes.length - 1]?.id };+ }++ const out = outputs[outputs.length - 1];+ const { img, natural } = await measure(out.url);++ if (job.tool === "regional") {+ const original = typeof job.settings?.image === "string" ? job.settings.image : undefined;+ const rect = job.frame;+ const add: LayerNode[] = [];+ if (original) {+ const before = await measure(original).catch(() => null);+ if (before) add.push({ ...newNode(newId(), "Original", rect, original, before.natural, "Original", at), role: "original" });+ }+ const feather = typeof job.settings?.feather === "number" ? job.settings.feather : 12;+ const edited = { ...newNode(newId(), "New", rect, out.url, natural, "Regional edit", at, null, prompt), role: "new" as const, feather };+ add.push(edited);+ return { doc: addNodes(doc, add), message: "Region edited", select: edited.id };+ }++ if (job.tool === "expand") {+ const grown = reframeDoc(doc, job.frame);+ const fill = newNode(newId(), "Expanded fill", [0, 0, grown.width, grown.height], out.url, natural, "Expand", at);+ return { doc: addNodes(grown, [fill], 0), message: "Canvas expanded", select: fill.id };+ }++ if (job.tool === "generate-layer") {+ const alpha = alphaBox(img);+ const crop = alpha ?? null;+ const [cw, ch] = crop ? [crop[2], crop[3]] : natural;+ const k = Math.min((doc.width * 0.5) / cw, (doc.height * 0.5) / ch);+ const w = cw * k;+ const h = ch * k;+ const name = prompt ? prompt.split(/\s+/).slice(0, 4).join(" ") : "Generated layer";+ const n = newNode(newId(), name.charAt(0).toUpperCase() + name.slice(1), [(doc.width - w) / 2, (doc.height - h) / 2, w, h], out.url, natural, "Generated", at, crop, prompt);+ return { doc: addNodes(doc, [n]), message: "Layer added", select: n.id };+ }++ // Edits: a new revision of the layer, or a new layer over the whole picture.+ const node = getNode(doc, job.nodeId);+ if (node) {+ const next = addRevision(node, { src: out.url, crop: null, natural, label: job.label, at, ...(prompt ? { prompt } : {}) });+ return { doc: { ...doc, nodes: doc.nodes.map((n) => (n.id === node.id ? next : n)) }, message: `${node.name}: ${job.label.toLowerCase()} done`, select: node.id };+ }+ // A whole-image result covers the picture as it is now (the canvas may have been expanded or cropped meanwhile).+ const whole: Box = job.nodeId ? job.frame : [0, 0, doc.width, doc.height];+ const n = newNode(newId(), NEW_LAYER_NAMES[job.tool] ?? job.label, fitBox(whole, natural), out.url, natural, job.label, at, null, prompt);+ let next = addNodes(doc, [n]);+ if (job.tool === "bg-remove") {+ // A cut-out of the whole picture only shows once what was under it is hidden.+ next = { ...next, nodes: next.nodes.map((x) => (x.id === n.id ? x : { ...x, hidden: true })) };+ return { doc: next, message: "Background removed — the layers underneath are hidden", select: n.id };+ }+ return { doc: next, message: `${n.name} added on top`, select: n.id };+}diff --git a/src/components/layers/bits.tsx b/src/components/layers/bits.tsxnew file mode 100644index 00000000..28ab47bd--- /dev/null+++ b/src/components/layers/bits.tsx@@ -0,0 +1,68 @@+"use client";++import { radioKeys, radioTab } from "@/components/studio/radio-keys";+import { cn } from "@/lib/utils";++/** Segmented control (the app's track + white thumb), a radio group for keyboards and screen readers. */+export function Segmented<T extends string>({+ label,+ value,+ options,+ onChange,+ className,+ disabled,+}: {+ label: string;+ value: T;+ options: readonly (readonly [T, string])[];+ onChange: (v: T) => void;+ className?: string;+ disabled?: boolean;+}) {+ return (+ <div role="radiogroup" aria-label={label} onKeyDown={radioKeys} className={cn("grid h-9 rounded-full bg-muted p-0.5 text-[13px] font-medium", className)} style={{ gridTemplateColumns: `repeat(${options.length}, minmax(0, 1fr))` }}>+ {options.map(([v, text]) => (+ <button+ key={v}+ type="button"+ role="radio"+ aria-checked={value === v}+ tabIndex={radioTab(value === v)}+ disabled={disabled}+ onClick={() => onChange(v)}+ className={cn(+ "truncate rounded-full px-2 transition-colors disabled:opacity-50",+ value === v ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {text}+ </button>+ ))}+ </div>+ );+}++/** A labelled row inside a tool form. */+export function Field({ label, hint, children, htmlFor }: { label: string; hint?: React.ReactNode; children: React.ReactNode; htmlFor?: string }) {+ return (+ <div className="space-y-1.5">+ <div className="flex items-baseline justify-between gap-2">+ <label htmlFor={htmlFor} className="text-[12px] font-medium text-muted-foreground">+ {label}+ </label>+ {hint && <span className="font-mono text-[12px] text-subtle-foreground">{hint}</span>}+ </div>+ {children}+ </div>+ );+}++/** Checkerboard-backed thumbnail of a transparent image. */+export function Thumb({ src, alt = "", className }: { src: string; alt?: string; className?: string }) {+ return (+ <span className={cn("checkerboard grid shrink-0 place-items-center overflow-hidden rounded-md border", className)}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={src} alt={alt} loading="lazy" draggable={false} className="max-h-full max-w-full object-contain" />+ </span>+ );+}diff --git a/src/components/layers/editor-context.tsx b/src/components/layers/editor-context.tsxnew file mode 100644index 00000000..86e60461--- /dev/null+++ b/src/components/layers/editor-context.tsx@@ -0,0 +1,96 @@+"use client";++import { createContext, useContext } from "react";+import type { Engine } from "@/lib/catalog/types";+import { formatCost } from "@/lib/format";+import type { Box, LayerDoc, LayerJob, LayerJobInput, LayerModelInfo, LayerNode, LayerProject, LayerTool, LayerVersion } from "@/lib/layers";++export type StageMode = "select" | "hand" | "brush" | "eraser" | "region" | "frame";++/** The part of the picture a tool works on. */+export type Target = { kind: "node"; node: LayerNode } | { kind: "whole" } | { kind: "region"; rect: Box };++/** A tool run as the editor asks for it: the editor renders and uploads the picture and fills in engine and frame. */+export type RunInput = Omit<LayerJobInput, "engine" | "frame" | "image" | "nodeId"> & { target: Target; image?: string; frame?: Box };++export interface MaskEdit {+ nodeId: string;+ canvas: HTMLCanvasElement;+ size: number;+ version: number;+}++export interface EditorCtx {+ projectId: string;+ project: LayerProject;+ versions: LayerVersion[];+ headVersionId: string;+ doc: LayerDoc;+ commit: (doc: LayerDoc) => void;+ selectedId: string | null;+ selected: LayerNode | undefined;+ select: (id: string | null) => void;+ engine: Engine;+ models: Record<string, LayerModelInfo>;+ isDemo: (m: LayerModelInfo | undefined) => boolean;+ jobs: LayerJob[];+ /** The job still working on a layer (queued, running, or finished but not laid out yet). */+ busyJob: (nodeId: string) => LayerJob | undefined;+ /** Start a tool; resolves to the job, or null when it couldn't start (the reason was shown). */+ run: (input: RunInput) => Promise<LayerJob | null>;+ /** Dismiss a failed job, cancel a running one, or mark one used (a text detection that filled Edit text). */+ endJob: (jobId: string, how: "dismiss" | "cancel" | "applied") => void;+ mode: StageMode;+ setMode: (m: StageMode) => void;+ region: Box | null;+ setRegion: (r: Box | null) => void;+ frame: Box | null;+ setFrame: (r: Box | null) => void;+ mask: MaskEdit | null;+ /** A box (doc px) to outline on the canvas (an Edit text row under the pointer). */+ setHighlight: (b: Box | null) => void;+ /** Live previews drawn instead of a layer (colour grading), by node id ("__whole" = an overlay over everything). */+ setPreview: (id: string, c: HTMLCanvasElement | null) => void;+ /** The tool form shown in the rail. */+ tool: ToolId | null;+ openTool: (t: ToolId | null) => void;+ /** Layer id to split when the decomposition tool opens from a layer's menu. */+ splitTarget: string | null;+ setSplitTarget: (id: string | null) => void;+}++export type ToolId = "decompose" | "edit-text" | "remove-bg" | "regional" | "upscale" | "relight" | "angles" | "expand" | "grade";++export const Ctx = createContext<EditorCtx | null>(null);++export function useEditor(): EditorCtx {+ const c = useContext(Ctx);+ if (!c) throw new Error("useEditor outside the Layers editor");+ return c;+}++/** "Demo · free", "Free · your GPU", "≈ $0.27" or "Price unknown". */+export function costLabel(m: LayerModelInfo | undefined, demo: boolean, usd?: number | null): string {+ if (!m) return "";+ if (demo) return "Demo · free";+ if (m.engine === "open") return "Free · your GPU";+ const v = usd !== undefined ? usd : m.pricing && ["image", "request", "megapixel"].includes(m.pricing.unit) ? m.pricing.usd : null;+ return v == null ? "Price unknown" : v === 0 ? "Free" : `≈ ${formatCost(v)}`;+}++/** The tool's models on an engine, as the page described them. */+export function modelsFor(models: Record<string, LayerModelInfo>, ids: string[]): LayerModelInfo[] {+ return ids.map((id) => models[id]).filter((m): m is LayerModelInfo => !!m);+}++export const isRunning = (j: LayerJob) => j.state === "pending" && (!j.result || j.result.status === "queued" || j.result.status === "running");+export const isFailed = (j: LayerJob) => j.state === "pending" && !!j.result && (j.result.status === "failed" || j.result.status === "canceled");++/** The newest job of these tools that isn't dismissed (what a tool form shows). */+export function latestJob(jobs: LayerJob[], tools: LayerTool[], nodeId?: string | null): LayerJob | undefined {+ for (let i = jobs.length - 1; i >= 0; i--) {+ const j = jobs[i];+ if (tools.includes(j.tool) && j.state !== "dismissed" && (nodeId === undefined || (j.nodeId ?? null) === nodeId)) return j;+ }+ return undefined;+}diff --git a/src/components/layers/grade-gl.ts b/src/components/layers/grade-gl.tsnew file mode 100644index 00000000..70eed47b--- /dev/null+++ b/src/components/layers/grade-gl.ts@@ -0,0 +1,83 @@+"use client";++import { FRAGMENT, uniforms, VERTEX, type Grade } from "@/lib/grade";+import { loseContext } from "@/lib/media-release";++/**+ * The Color grading tool's WebGL grade (src/lib/grade.ts) applied to a layer: the shader grades the+ * colours, then the layer's own alpha is put back (the shader writes opaque pixels).+ */+export class LayerGrader {+ private canvas = document.createElement("canvas");+ private gl: WebGLRenderingContext;+ private prog: WebGLProgram;+ private loc = new Map<string, WebGLUniformLocation | null>();++ constructor() {+ const gl = this.canvas.getContext("webgl", { preserveDrawingBuffer: true, premultipliedAlpha: false });+ if (!gl) throw new Error("WebGL isn't available in this browser");+ this.gl = gl;+ const sh = (type: number, src: string) => {+ const s = gl.createShader(type)!;+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) ?? "shader error");+ return s;+ };+ const prog = gl.createProgram()!;+ gl.attachShader(prog, sh(gl.VERTEX_SHADER, VERTEX));+ gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FRAGMENT));+ gl.linkProgram(prog);+ gl.useProgram(prog);+ this.prog = prog;+ const buf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);+ const pos = gl.getAttribLocation(prog, "a_pos");+ gl.enableVertexAttribArray(pos);+ gl.vertexAttribPointer(pos, 2, gl.FLOAT, false, 0, 0);+ gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());+ for (const [k, v] of [+ [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE],+ [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE],+ [gl.TEXTURE_MIN_FILTER, gl.LINEAR],+ [gl.TEXTURE_MAG_FILTER, gl.LINEAR],+ ])+ gl.texParameteri(gl.TEXTURE_2D, k, v);+ }++ private u(name: string) {+ if (!this.loc.has(name)) this.loc.set(name, this.gl.getUniformLocation(this.prog, name));+ return this.loc.get(name)!;+ }++ /** The graded copy of `src` (same size), with `src`'s transparency. */+ grade(src: HTMLCanvasElement, grade: Grade): HTMLCanvasElement {+ const gl = this.gl;+ const { width, height } = src;+ this.canvas.width = width;+ this.canvas.height = height;+ gl.viewport(0, 0, width, height);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, src);+ for (const [k, v] of Object.entries(uniforms(grade))) {+ if (Array.isArray(v)) gl.uniform3f(this.u(k), v[0], v[1], v[2]);+ else gl.uniform1f(this.u(k), v);+ }+ gl.uniform2f(this.u("u_texel"), 1 / Math.max(1, width), 1 / Math.max(1, height));+ gl.uniform1f(this.u("u_seed"), 1);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ const out = document.createElement("canvas");+ out.width = width;+ out.height = height;+ const ctx = out.getContext("2d")!;+ ctx.drawImage(this.canvas, 0, 0);+ ctx.globalCompositeOperation = "destination-in";+ ctx.drawImage(src, 0, 0);+ ctx.globalCompositeOperation = "source-over";+ return out;+ }++ dispose() {+ loseContext(this.gl);+ }+}diff --git a/src/components/layers/layers-editor.tsx b/src/components/layers/layers-editor.tsxnew file mode 100644index 00000000..cece6fa4--- /dev/null+++ b/src/components/layers/layers-editor.tsx@@ -0,0 +1,563 @@+"use client";++import { Check, Loader2, X } from "lucide-react";+import { nanoid } from "nanoid";+import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from "react";+import { toast } from "sonner";+import { ErrorState, NotFoundState } from "@/components/empty-state";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { CompareSlider } from "@/components/studio/compare-slider";+import { useIsMobile } from "@/hooks/use-mobile";+import { uploadFile, useEngine, useStatus } from "@/lib/api";+import {+ APPLIES_TO_DOC,+ deleteNode,+ duplicateNode,+ getNode,+ historyReducer,+ nativeSize,+ updateNode,+ type Box,+ type LayerDoc,+ type LayerModelInfo,+ type LayerNode,+ type LayerProjectView,+} from "@/lib/layers";+import { applyJob } from "./apply";+import { Ctx, isFailed, isRunning, type EditorCtx, type MaskEdit, type RunInput, type StageMode, type ToolId } from "./editor-context";+import { LayersPanel } from "./layers-panel";+import { MobileView } from "./mobile-view";+import { loadImage, ratioOf, renderDoc, renderNative, toBlob, uploadRender } from "./render";+import { Stage } from "./stage";+import { ToolRail } from "./tools";+import { TopBar, type SaveState } from "./top-bar";+import { LayersRequestError, saveCover, saveDoc, useLayerActions, useLayerProject } from "./use-layers";++const typing = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));++/** The document is still just the image it was opened on (models can take the original file as is). */+function pristine(doc: LayerDoc): boolean {+ if (doc.nodes.length !== 1) return false;+ const n = doc.nodes[0];+ return n.src === doc.source && !n.crop && !n.maskSrc && !n.feather && !n.rotation && !n.hidden && (n.opacity ?? 1) === 1 && n.x === 0 && n.y === 0 && n.w === doc.width && n.h === doc.height;+}++/** A layer whose file is exactly what it shows. */+const plain = (n: LayerNode) => !n.crop && !n.maskSrc && !n.feather;++function EditorSkeleton() {+ return (+ <div className="flex h-svh min-w-0 flex-col overflow-hidden md:h-[calc(100svh-0.5rem)]">+ <div className="flex h-14 items-center gap-3 border-b px-3">+ <Skeleton className="h-6 w-40" />+ <Skeleton className="ml-auto h-8 w-64 rounded-full" />+ </div>+ <div className="flex min-h-0 flex-1">+ <div className="hidden w-[280px] space-y-2 border-r p-3 md:block">+ {Array.from({ length: 8 }, (_, i) => (+ <Skeleton key={i} className="h-11 rounded-lg" />+ ))}+ </div>+ <div className="grid flex-1 place-items-center bg-muted/40">+ <Skeleton className="aspect-[4/3] w-1/2 rounded-sm" />+ </div>+ <div className="hidden w-[300px] space-y-2 border-l p-3 md:block">+ {Array.from({ length: 4 }, (_, i) => (+ <Skeleton key={i} className="h-14 rounded-lg" />+ ))}+ </div>+ </div>+ </div>+ );+}++export function LayersEditor({ id, models }: { id: string; models: Record<string, LayerModelInfo> }) {+ const q = useLayerProject(id);+ if (q.data) return <Editor key={id} initial={q.data} models={models} />;+ if (q.error) {+ if (q.error instanceof LayersRequestError && q.error.status === 404) {+ return <NotFoundState title="This project doesn't exist">It may have been deleted. The images it was opened on are still in your library.</NotFoundState>;+ }+ return <ErrorState error={q.error} retry={() => void q.refetch()} />;+ }+ return <EditorSkeleton />;+}++function Editor({ initial, models }: { initial: LayerProjectView; models: Record<string, LayerModelInfo> }) {+ const id = initial.project.id;+ const q = useLayerProject(id);+ const view = q.data ?? initial;+ const actions = useLayerActions();+ const isMobile = useIsMobile();+ const [engine, setEngine] = useEngine();+ const status = useStatus().data;++ const [hist, dispatch] = useReducer(historyReducer, initial.doc, (doc) => ({ past: [], present: doc, future: [] }));+ const doc = hist.present;+ const docRef = useRef(doc);+ useLayoutEffect(() => {+ docRef.current = doc;+ }, [doc]);+ const headRef = useRef(initial.headVersionId);+ const [head, setHeadState] = useState(initial.headVersionId);+ const setHead = useCallback((v: string) => {+ headRef.current = v;+ setHeadState(v);+ }, []);+ const savedRef = useRef<LayerDoc>(initial.doc);+ const [save, setSave] = useState<SaveState>("saved");++ const [selectedId, setSelectedId] = useState<string | null>(null);+ const selected = getNode(doc, selectedId);+ const [tool, setTool] = useState<ToolId | null>(() => (!initial.doc.decomposed && initial.doc.nodes.length === 1 ? "decompose" : null));+ const [splitTarget, setSplitTarget] = useState<string | null>(null);+ const [mode, setModeState] = useState<StageMode>("select");+ const [region, setRegion] = useState<Box | null>(null);+ const [frame, setFrame] = useState<Box | null>(null);+ const [highlight, setHighlight] = useState<Box | null>(null);+ const [previews, setPreviews] = useState<Map<string, HTMLCanvasElement>>(() => new Map());+ const [mask, setMask] = useState<MaskEdit | null>(null);+ const [maskVersion, setMaskVersion] = useState(0);+ const [brushSize, setBrushSize] = useState(() => Math.round(Math.max(initial.doc.width, initial.doc.height) / 30));+ const [compare, setCompare] = useState(false);++ const commit = useCallback((d: LayerDoc) => dispatch({ type: "commit", doc: d }), []);+ const resetTo = useCallback(+ (v: LayerProjectView) => {+ setHead(v.headVersionId);+ savedRef.current = v.doc;+ dispatch({ type: "reset", doc: v.doc });+ setSave("saved");+ },+ [setHead],+ );+ const refetch = q.refetch;++ // ---- Autosave into the head version (debounced; flushed with keepalive when leaving).+ const pending = useRef<LayerDoc | null>(null);+ useEffect(() => {+ if (doc === savedRef.current) return;+ pending.current = doc;+ setSave("dirty");+ const t = setTimeout(async () => {+ setSave("saving");+ try {+ await saveDoc(id, doc, headRef.current);+ savedRef.current = doc;+ if (pending.current === doc) pending.current = null;+ setSave("saved");+ } catch (e) {+ if (e instanceof LayersRequestError && e.status === 409) {+ setSave("conflict");+ toast.error(e.message, { id: "layers-conflict", action: { label: "Reload", onClick: () => void refetch().then((r) => r.data && resetTo(r.data)) } });+ } else setSave("error");+ }+ }, 700);+ return () => clearTimeout(t);+ }, [doc, id, refetch, resetTo]);+ useEffect(() => {+ const flush = () => {+ const d = pending.current;+ if (d && d !== savedRef.current) void saveDoc(id, d, headRef.current, true).catch(() => {});+ };+ const onHide = () => document.visibilityState === "hidden" && flush();+ document.addEventListener("visibilitychange", onHide);+ window.addEventListener("pagehide", flush);+ return () => {+ document.removeEventListener("visibilitychange", onHide);+ window.removeEventListener("pagehide", flush);+ flush();+ };+ }, [id]);++ // ---- The project card's cover follows the composite (a small JPEG, a few seconds after edits settle).+ useEffect(() => {+ if (doc === initial.doc) return;+ let gone = false;+ const t = setTimeout(async () => {+ try {+ const c = await renderDoc(doc, { scale: Math.min(1, 360 / Math.max(doc.width, doc.height)), fill: "#ffffff" });+ if (!gone) await saveCover(id, c.toDataURL("image/jpeg", 0.8));+ } catch {+ // The card keeps its last cover.+ }+ }, 2500);+ return () => {+ gone = true;+ clearTimeout(t);+ };+ }, [doc, id, initial.doc]);++ // ---- Jobs: start, and lay out their results as they land.+ const busyJob = useCallback(+ (nodeId: string) => view.jobs.find((j) => j.nodeId === nodeId && j.tool !== "text-detect" && j.state === "pending" && !isFailed(j)),+ [view.jobs],+ );++ const run = useCallback<EditorCtx["run"]>(+ async (input: RunInput) => {+ const d = docRef.current;+ const { target, image: given, frame: givenFrame, ...rest } = input;+ try {+ let image = given;+ let jobFrame = givenFrame;+ let aspect: string | undefined;+ const needsImage = !(input.tool === "generate-layer");+ if (target.kind === "node") {+ const n = target.node;+ jobFrame ??= [n.x, n.y, n.w, n.h];+ if (!image && needsImage) {+ if (plain(n)) image = n.src;+ else image = await uploadRender(await renderNative(n), `layers-${n.name}`);+ }+ const [w, h] = nativeSize(n, 1e9);+ aspect = ratioOf(w, h);+ } else if (target.kind === "region") {+ jobFrame ??= target.rect;+ if (!image) image = await uploadRender(await renderDoc(d, { rect: target.rect, scale: Math.min(1, 2048 / Math.max(target.rect[2], target.rect[3])) }), "layers-region");+ aspect = ratioOf(target.rect[2], target.rect[3]);+ } else {+ jobFrame ??= [0, 0, d.width, d.height];+ if (!image && needsImage) image = pristine(d) ? d.source : await uploadRender(await renderDoc(d, { scale: Math.min(1, 4096 / Math.max(d.width, d.height)) }), "layers-composite");+ aspect = ratioOf(d.width, d.height);+ }+ return await actions.startJob(id, {+ ...rest,+ engine,+ image,+ frame: jobFrame,+ nodeId: target.kind === "node" ? target.node.id : undefined,+ settings: { aspect, ...rest.settings },+ });+ } catch (e) {+ toast.error((e as Error).message || "Could not start the tool");+ return null;+ }+ },+ [actions, engine, id],+ );++ const endJob = useCallback<EditorCtx["endJob"]>(+ (jobId, how) => void actions.endJob(id, jobId, how).catch((e) => toast.error((e as Error).message)),+ [actions, id],+ );++ const applying = useRef(new Set<string>());+ const queue = useRef<Promise<void>>(Promise.resolve());+ useEffect(() => {+ for (const j of view.jobs) {+ if (j.state !== "pending" || j.result?.status !== "succeeded" || !APPLIES_TO_DOC.has(j.tool) || applying.current.has(j.id)) continue;+ applying.current.add(j.id);+ queue.current = queue.current.then(async () => {+ try {+ const res = await applyJob(docRef.current, j, () => nanoid(8));+ const v = await actions.version(id, { doc: res.doc, label: j.label, jobId: j.id });+ setHead(v.headVersionId);+ savedRef.current = res.doc;+ dispatch({ type: "commit", doc: res.doc });+ if (res.select) setSelectedId(res.select);+ if (j.tool === "split") setSplitTarget(null);+ toast.success(res.message, { duration: 2500 });+ } catch (e) {+ if (e instanceof LayersRequestError && e.status === 409) {+ // Another tab laid it out first: take the saved version.+ const r = await refetch();+ if (r.data) resetTo(r.data);+ } else {+ toast.error(`Couldn't add the result to your layers: ${(e as Error).message}`);+ endJob(j.id, "dismiss");+ }+ }+ });+ }+ }, [view.jobs, actions, id, refetch, resetTo, endJob, setHead]);++ // ---- Masks (brush paints the layer back, eraser hides it).+ const setMode = useCallback(+ (m: StageMode) => {+ setModeState(m);+ if (m !== "brush" && m !== "eraser") setMask(null);+ },+ [],+ );+ useEffect(() => {+ if ((mode !== "brush" && mode !== "eraser") || !selected) return;+ if (mask?.nodeId === selected.id) return;+ let gone = false;+ const node = selected;+ void (async () => {+ const [w, h] = nativeSize(node, 1024);+ const c = document.createElement("canvas");+ c.width = w;+ c.height = h;+ const ctx = c.getContext("2d")!;+ if (node.maskSrc) {+ try {+ ctx.drawImage(await loadImage(node.maskSrc), 0, 0, w, h);+ } catch {+ ctx.fillStyle = "#fff";+ ctx.fillRect(0, 0, w, h);+ }+ } else {+ ctx.fillStyle = "#fff";+ ctx.fillRect(0, 0, w, h);+ }+ if (!gone) setMask({ nodeId: node.id, canvas: c, size: w, version: 0 });+ })();+ return () => {+ gone = true;+ };+ }, [mode, selected, mask?.nodeId]);+ const [savingMask, setSavingMask] = useState(false);+ const finishMask = async () => {+ if (!mask) return;+ setSavingMask(true);+ try {+ const blob = await toBlob(mask.canvas);+ const asset = await uploadFile(new File([blob], "layer-mask.png", { type: "image/png" }));+ commit(updateNode(docRef.current, mask.nodeId, { maskSrc: asset.url }));+ toast.success("Mask saved", { duration: 1500 });+ setMode("select");+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setSavingMask(false);+ }+ };++ // ---- Selection changes end mask editing and per-layer previews.+ const select = useCallback(+ (nid: string | null) => {+ setSelectedId(nid);+ setModeState((m) => (m === "brush" || m === "eraser" ? "select" : m));+ setMask((m) => (m && m.nodeId !== nid ? null : m));+ },+ [],+ );++ const setPreview = useCallback((pid: string, c: HTMLCanvasElement | null) => {+ setPreviews((old) => {+ if (!c && !old.has(pid)) return old;+ const next = new Map(old);+ if (c) next.set(pid, c);+ else next.delete(pid);+ return next;+ });+ }, []);++ const openTool = useCallback((t: ToolId | null) => {+ setTool(t);+ if (t !== "decompose") setSplitTarget(null);+ }, []);++ // ---- Keyboard.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (typing(e.target)) return;+ const mod = e.metaKey || e.ctrlKey;+ if (mod && e.key.toLowerCase() === "z") {+ e.preventDefault();+ dispatch({ type: e.shiftKey ? "redo" : "undo" });+ return;+ }+ if (mod && e.key.toLowerCase() === "y") {+ e.preventDefault();+ dispatch({ type: "redo" });+ return;+ }+ const d = docRef.current;+ const sel = getNode(d, selectedId);+ if (mod && e.key.toLowerCase() === "d" && sel) {+ e.preventDefault();+ commit(duplicateNode(d, sel.id, nanoid(8)));+ return;+ }+ if (mod || e.altKey) return;+ if (e.key === "Escape") {+ if (mode === "brush" || mode === "eraser") setMode("select");+ else select(null);+ return;+ }+ if ((e.key === "Delete" || e.key === "Backspace") && sel) {+ e.preventDefault();+ if (busyJob(sel.id)) toast.error("Can't delete while this layer is generating");+ else {+ commit(deleteNode(d, sel.id));+ select(null);+ }+ return;+ }+ if (sel && e.key.startsWith("Arrow")) {+ e.preventDefault();+ const step = e.shiftKey ? 10 : 1;+ const dx = e.key === "ArrowLeft" ? -step : e.key === "ArrowRight" ? step : 0;+ const dy = e.key === "ArrowUp" ? -step : e.key === "ArrowDown" ? step : 0;+ commit(updateNode(d, sel.id, { x: sel.x + dx, y: sel.y + dy }));+ return;+ }+ const k = e.key.toLowerCase();+ if (k === "v") setMode("select");+ else if (k === "h") setMode("hand");+ else if ((k === "b" || k === "e") && sel) setMode(k === "b" ? "brush" : "eraser");+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [selectedId, mode, commit, select, setMode, busyJob]);++ // ---- Compare: the original against the current composite.+ const [composite, setComposite] = useState<string | null>(null);+ useEffect(() => {+ if (!compare) return;+ let url: string | null = null;+ let gone = false;+ void renderDoc(doc, { scale: Math.min(1, 1600 / Math.max(doc.width, doc.height)) })+ .then((c) => toBlob(c))+ .then((b) => {+ if (gone) return;+ url = URL.createObjectURL(b);+ setComposite(url);+ })+ .catch(() => toast.error("Couldn't render the comparison"));+ return () => {+ gone = true;+ if (url) URL.revokeObjectURL(url);+ setComposite(null);+ };+ }, [compare, doc]);++ const isDemo = useCallback(+ (m: LayerModelInfo | undefined) => {+ if (!m || !status) return false;+ if (status.demoMode === "on") return true;+ if (status.demoMode === "off") return false;+ return !m.providers.some((p) => status.providers[p]?.configured);+ },+ [status],+ );++ const busy = useMemo(() => {+ const m = new Map<string, string>();+ for (const j of view.jobs) if (j.nodeId && j.state === "pending" && isRunning(j)) m.set(j.nodeId, j.tool === "split" ? "Separating…" : `${j.label}…`);+ return m;+ }, [view.jobs]);++ const sources = useMemo(() => ({ masks: mask ? new Map([[mask.nodeId, mask.canvas]]) : undefined, maskVersion, previews }), [mask, maskVersion, previews]);+ const overlay = useMemo<LayerNode[] | undefined>(() => {+ if (!previews.has("__whole")) return undefined;+ return [{ id: "__whole", name: "Preview", z: 1e6, x: 0, y: 0, w: doc.width, h: doc.height, rotation: 0, src: doc.source, revisions: [], revision: 0 }];+ }, [previews, doc.width, doc.height, doc.source]);++ const ctx: EditorCtx = {+ projectId: id,+ project: view.project,+ versions: view.versions,+ headVersionId: head,+ doc,+ commit,+ selectedId,+ selected,+ select,+ engine,+ models,+ isDemo,+ jobs: view.jobs,+ busyJob,+ run,+ endJob,+ mode,+ setMode,+ region,+ setRegion,+ frame,+ setFrame,+ mask,+ setHighlight,+ setPreview,+ tool,+ openTool,+ splitTarget,+ setSplitTarget,+ };++ if (isMobile) return <MobileView project={view.project} doc={doc} jobs={view.jobs} />;++ return (+ <Ctx.Provider value={ctx}>+ <div className="flex h-svh min-w-0 flex-col overflow-hidden md:h-[calc(100svh-0.5rem)]">+ <TopBar+ name={view.project.name}+ onRename={(n) => void actions.rename(id, n).catch((e) => toast.error((e as Error).message))}+ save={save}+ canUndo={hist.past.length > 0}+ canRedo={hist.future.length > 0}+ onUndo={() => dispatch({ type: "undo" })}+ onRedo={() => dispatch({ type: "redo" })}+ versions={view.versions}+ headVersionId={head}+ onRestore={async (vid) => {+ try {+ const v = await actions.version(id, { from: vid });+ resetTo(v);+ select(null);+ toast.success("Version restored", { duration: 1500 });+ } catch (e) {+ toast.error((e as Error).message);+ }+ }}+ compare={compare}+ onCompare={setCompare}+ doc={doc}+ jobs={view.jobs}+ engine={engine}+ setEngine={setEngine}+ />+ <div className="flex min-h-0 flex-1">+ <ToolRail />+ <main className="relative flex min-w-0 flex-1 flex-col">+ {compare ? (+ <div className="checkerboard grid min-h-0 flex-1 place-items-center overflow-hidden p-6">+ {composite ? <CompareSlider before={doc.source} after={composite} alt="Your layers" /> : <Loader2 className="size-5 animate-spin text-muted-foreground" />}+ </div>+ ) : (+ <Stage+ doc={doc}+ selectedId={selectedId}+ onSelect={select}+ onCommit={commit}+ mode={mode}+ setMode={setMode}+ region={region}+ setRegion={setRegion}+ frame={frame}+ setFrame={setFrame}+ mask={mask}+ onMaskChange={() => setMaskVersion((v) => v + 1)}+ brushSize={brushSize}+ setBrushSize={setBrushSize}+ highlight={highlight}+ sources={sources}+ overlay={overlay}+ busy={busy}+ />+ )}+ {mask && selected && !compare && (+ <div className="absolute top-3 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full border bg-background/95 py-1 pr-1 pl-3.5 text-[12px] shadow-normal backdrop-blur" role="status">+ <span className="max-w-[40vw] truncate">+ Mask · <span className="font-medium">{selected.name}</span> — the eraser hides, the brush paints back+ </span>+ <Button size="xs" variant="ghost" className="rounded-full" onClick={() => setMode("select")}>+ <X /> Cancel+ </Button>+ <Button size="xs" className="rounded-full" onClick={() => void finishMask()} disabled={savingMask}>+ {savingMask ? <Loader2 className="animate-spin" /> : <Check />} Done+ </Button>+ </div>+ )}+ </main>+ <LayersPanel />+ </div>+ </div>+ </Ctx.Provider>+ );+}diff --git a/src/components/layers/layers-panel.tsx b/src/components/layers/layers-panel.tsxnew file mode 100644index 00000000..9867d09d--- /dev/null+++ b/src/components/layers/layers-panel.tsx@@ -0,0 +1,671 @@+"use client";++import {+ ArrowDown,+ ArrowUp,+ Brush,+ ChevronLeft,+ ChevronRight,+ Copy,+ Download,+ Eye,+ EyeOff,+ GripVertical,+ ImagePlus,+ Library,+ Loader2,+ MoreHorizontal,+ Pencil,+ Plus,+ RotateCcw,+ Scissors,+ Sparkles,+ SplitSquareVertical,+ Trash2,+ Upload,+ X,+} from "lucide-react";+import { nanoid } from "nanoid";+import { useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Slider } from "@/components/ui/slider";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { LibraryGrid } from "@/components/studio/media-slot";+import { uploadFile } from "@/lib/api";+import { addNodes, deleteNode, duplicateNode, jobStatusText, moveNode, setRevision, TOOL_MODELS, updateNode, type LayerNode, type LayerRevision } from "@/lib/layers";+import { cn } from "@/lib/utils";+import { Field } from "./bits";+import { costLabel, isFailed, latestJob, modelsFor, useEditor } from "./editor-context";+import { downloadLayer, loadImage, sizeOf } from "./render";++/** A layer's thumbnail showing just the part of its image it uses (its crop), on a checkerboard. */+export function LayerThumb({ node, className }: { node: Pick<LayerNode, "src" | "crop" | "natural" | "w" | "h">; className?: string }) {+ const crop = node.crop;+ const nat = node.natural;+ const aspect = node.w / node.h;+ const style: React.CSSProperties =+ crop && nat+ ? {+ backgroundImage: `url("${node.src}")`,+ backgroundSize: `${(nat[0] / crop[2]) * 100}% ${(nat[1] / crop[3]) * 100}%`,+ backgroundPosition: `${nat[0] === crop[2] ? 0 : (crop[0] / (nat[0] - crop[2])) * 100}% ${nat[1] === crop[3] ? 0 : (crop[1] / (nat[1] - crop[3])) * 100}%`,+ }+ : { backgroundImage: `url("${node.src}")`, backgroundSize: "100% 100%" };+ return (+ <span className={cn("checkerboard grid size-10 shrink-0 place-items-center overflow-hidden rounded-md border", className)}>+ <span className="block max-h-full max-w-full bg-no-repeat" style={{ ...style, aspectRatio: `${aspect}`, width: aspect >= 1 ? "100%" : "auto", height: aspect >= 1 ? "auto" : "100%" }} />+ </span>+ );+}++/** Add a layer from a file or the library: sized to fit 80% of the canvas, centred. */+async function layerFromImage(url: string, name: string, doc: { width: number; height: number }): Promise<LayerNode> {+ const img = await loadImage(url);+ const natural = sizeOf(img);+ const k = Math.min(1, (doc.width * 0.8) / natural[0], (doc.height * 0.8) / natural[1]);+ const w = natural[0] * k;+ const h = natural[1] * k;+ const rev: LayerRevision = { src: url, crop: null, natural, label: "Added", at: Date.now() };+ return { id: nanoid(8), name: name.slice(0, 80) || "Uploaded layer", z: 0, x: (doc.width - w) / 2, y: (doc.height - h) / 2, w, h, rotation: 0, src: url, crop: null, natural, revisions: [rev], revision: 0 };+}++function AddLayer() {+ const { doc, commit, select, run, engine, models, isDemo } = useEditor();+ const file = useRef<HTMLInputElement>(null);+ const [picking, setPicking] = useState(false);+ const [generating, setGenerating] = useState(false);+ const [prompt, setPrompt] = useState("");+ const [ref, setRef] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const options = modelsFor(models, TOOL_MODELS["generate-layer"][engine]);+ const [modelId, setModelId] = useState<string | undefined>();+ const model = options.find((m) => m.id === modelId) ?? options[0];++ const add = async (url: string, name: string) => {+ try {+ const n = await layerFromImage(url, name, doc);+ commit(addNodes(doc, [n]));+ select(n.id);+ toast.success("Layer added", { duration: 1500 });+ } catch {+ toast.error("Failed to add layer");+ }+ };++ return (+ <>+ <input+ ref={file}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ className="sr-only"+ tabIndex={-1}+ aria-hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ try {+ const a = await uploadFile(f);+ await add(a.url, f.name.replace(/\.[^.]+$/, "") || "Uploaded layer");+ } catch (err) {+ toast.error((err as Error).message);+ }+ }}+ />+ <Popover open={picking} onOpenChange={setPicking}>+ <DropdownMenu>+ <PopoverAnchor asChild>+ <DropdownMenuTrigger asChild>+ <Button size="xs" variant="secondary" className="rounded-full">+ <Plus /> Add layer+ </Button>+ </DropdownMenuTrigger>+ </PopoverAnchor>+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuItem onSelect={() => setTimeout(() => setPicking(true))}>+ <Library /> Choose asset+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => file.current?.click()}>+ <Upload /> Upload image+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => setTimeout(() => setGenerating(true))}>+ <Sparkles /> Generate layer+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <PopoverContent align="end" className="w-[min(92vw,380px)] p-2" collisionPadding={12}>+ <p className="px-1 pb-2 text-[13px] font-medium">Choose an image to add as a layer</p>+ {picking && (+ <LibraryGrid+ kinds={["image"]}+ onPick={(v) => {+ setPicking(false);+ void add(v.ref, v.name ?? "Library layer");+ }}+ />+ )}+ </PopoverContent>+ </Popover>++ <Dialog open={generating} onOpenChange={setGenerating}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Generate layer</DialogTitle>+ <DialogDescription>Describe one element. It arrives on its own transparent layer, ready to place.</DialogDescription>+ </DialogHeader>+ <form+ className="space-y-3"+ onSubmit={async (e) => {+ e.preventDefault();+ if (!prompt.trim()) return;+ setBusy(true);+ const job = await run({ tool: "generate-layer", target: { kind: "whole" }, prompt: prompt.trim(), refs: ref ? [ref] : undefined, modelId: ref ? undefined : model?.id, label: "Generate layer" });+ setBusy(false);+ if (job) {+ setGenerating(false);+ setPrompt("");+ setRef(null);+ }+ }}+ >+ <Textarea autoFocus value={prompt} onChange={(e) => setPrompt(e.target.value)} maxLength={2000} placeholder="e.g. “a red paper lantern with a gold tassel”" aria-label="Describe the layer" className="min-h-20" />+ <div className="flex flex-wrap items-center gap-2">+ <RefPicker value={ref} onChange={setRef} />+ {!ref && options.length > 1 && (+ <Select value={model?.id} onValueChange={setModelId}>+ <SelectTrigger size="sm" className="h-8 rounded-full" aria-label="Model">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {options.map((m) => (+ <SelectItem key={m.id} value={m.id}>+ {m.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </div>+ <DialogFooter className="items-center sm:justify-between">+ <span className="font-mono text-[12px] text-muted-foreground">{costLabel(model, isDemo(model))}</span>+ <Button type="submit" className="rounded-full" disabled={!prompt.trim() || busy}>+ {busy ? <Loader2 className="animate-spin" /> : <Sparkles />} Generate layer+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </>+ );+}++/** "Add reference": upload or pick an image, shown as a removable thumbnail. */+export function RefPicker({ value, onChange }: { value: string | null; onChange: (url: string | null) => void }) {+ const file = useRef<HTMLInputElement>(null);+ const [open, setOpen] = useState(false);+ const [uploading, setUploading] = useState(false);+ if (value) {+ return (+ <span className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary pr-1 pl-1 text-[13px]">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={value} alt="Reference" className="size-6 rounded-full object-cover" />+ Reference+ <button type="button" className="grid size-6 place-items-center rounded-full hover:bg-accent" aria-label="Remove reference" onClick={() => onChange(null)}>+ <X className="size-3.5" />+ </button>+ </span>+ );+ }+ return (+ <>+ <input+ ref={file}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ className="sr-only"+ tabIndex={-1}+ aria-hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ setUploading(true);+ try {+ onChange((await uploadFile(f)).url);+ } catch (err) {+ toast.error((err as Error).message);+ } finally {+ setUploading(false);+ }+ }}+ />+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Button type="button" size="sm" variant="secondary" className="rounded-full" disabled={uploading}>+ {uploading ? <Loader2 className="animate-spin" /> : <ImagePlus />} Add reference+ </Button>+ </PopoverTrigger>+ <PopoverContent align="start" className="w-[min(92vw,360px)] p-2" collisionPadding={12}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="mb-2 w-full"+ onClick={() => {+ setOpen(false);+ file.current?.click();+ }}+ >+ <Upload /> Upload an image+ </Button>+ {open && (+ <LibraryGrid+ kinds={["image"]}+ onPick={(v) => {+ setOpen(false);+ onChange(v.ref);+ }}+ />+ )}+ </PopoverContent>+ </Popover>+ </>+ );+}++function LayerRow({+ node,+ selected,+ busy,+ index,+ total,+ onDragHandle,+ dropBefore,+}: {+ node: LayerNode;+ selected: boolean;+ busy?: string;+ index: number;+ total: number;+ onDragHandle: (e: React.PointerEvent, id: string) => void;+ dropBefore: boolean;+}) {+ const { doc, commit, select, busyJob, openTool, setSplitTarget, setMode, mode } = useEditor();+ const [renaming, setRenaming] = useState(false);+ const [draft, setDraft] = useState(node.name);+ const job = busyJob(node.id);+ const move = (dz: number) => {+ const to = node.z + dz;+ if (to < 0 || to >= total) return;+ commit(moveNode(doc, node.id, to));+ };+ const remove = () => {+ if (job) {+ toast.error(job.tool === "split" ? "Can't delete while this layer is being split" : "Can't delete while this layer is generating");+ return;+ }+ commit(deleteNode(doc, node.id));+ select(null);+ toast("Layer deleted", { duration: 1500 });+ };+ const finishRename = () => {+ setRenaming(false);+ const name = draft.trim();+ if (name && name !== node.name) commit(updateNode(doc, node.id, { name }));+ else setDraft(node.name);+ };++ return (+ <li className="relative">+ {dropBefore && <span className="absolute -top-px right-2 left-2 z-10 h-0.5 rounded-full bg-primary" aria-hidden />}+ <div+ className={cn(+ "group/row flex h-14 items-center gap-1.5 rounded-lg pr-1 pl-0.5 transition-colors",+ selected ? "bg-brand-faint" : "hover:bg-accent",+ node.hidden && "opacity-60",+ )}+ >+ <button+ type="button"+ className="grid h-10 w-5 shrink-0 cursor-grab touch-none place-items-center rounded text-subtle-foreground hover:text-foreground active:cursor-grabbing"+ aria-label={`Reorder ${node.name}. Use the up and down arrow keys to move it.`}+ onPointerDown={(e) => onDragHandle(e, node.id)}+ onKeyDown={(e) => {+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {+ e.preventDefault();+ move(e.key === "ArrowUp" ? 1 : -1);+ }+ }}+ >+ <GripVertical className="size-4" />+ </button>+ <button type="button" className="flex min-w-0 flex-1 items-center gap-2 text-left" onClick={() => select(node.id)} onDoubleClick={() => setRenaming(true)} aria-pressed={selected} aria-label={`Select layer ${node.name}`}>+ <LayerThumb node={node} />+ <span className="min-w-0 flex-1">+ {renaming ? null : <span className={cn("block truncate text-[13px]", selected && "font-medium text-brand-text")}>{node.name}</span>}+ <span className="block truncate text-[11px] text-muted-foreground">+ {busy ?? (node.revisions.length > 1 ? `Version ${node.revision + 1} of ${node.revisions.length}` : node.maskSrc ? "Masked" : `Layer ${index}`)}+ </span>+ </span>+ </button>+ {renaming && (+ <Input+ autoFocus+ value={draft}+ maxLength={80}+ aria-label="Layer name"+ className="absolute top-2 right-16 left-[4.25rem] h-7 text-[13px]"+ onChange={(e) => setDraft(e.target.value)}+ onFocus={(e) => e.currentTarget.select()}+ onBlur={finishRename}+ onKeyDown={(e) => {+ if (e.key === "Enter") finishRename();+ if (e.key === "Escape") {+ setDraft(node.name);+ setRenaming(false);+ }+ }}+ />+ )}+ {job && <Loader2 className="size-3.5 shrink-0 animate-spin text-brand-text" aria-hidden />}+ <button+ type="button"+ className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background/60 hover:text-foreground"+ aria-label={node.hidden ? `Show layer ${node.name}` : `Hide layer ${node.name}`}+ aria-pressed={!node.hidden}+ onClick={() => commit(updateNode(doc, node.id, { hidden: !node.hidden }))}+ >+ {node.hidden ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />}+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button type="button" className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background/60 hover:text-foreground data-[state=open]:bg-background/60" aria-label={`Actions for ${node.name}`}>+ <MoreHorizontal className="size-3.5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuItem onSelect={() => setTimeout(() => setRenaming(true), 50)}>+ <Pencil /> Rename layer+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => commit(duplicateNode(doc, node.id, nanoid(8)))}>+ <Copy /> Duplicate+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => void downloadLayer(doc, node).catch(() => toast.error("Could not download the layer."))}>+ <Download /> Download+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={() => {+ select(node.id);+ setSplitTarget(node.id);+ openTool("decompose");+ }}+ >+ <SplitSquareVertical /> Separate layer+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={() => {+ select(node.id);+ setMode("eraser");+ }}+ disabled={mode === "brush" || mode === "eraser"}+ >+ <Brush /> {node.maskSrc ? "Edit mask" : "Add mask"}+ </DropdownMenuItem>+ {node.maskSrc && (+ <DropdownMenuItem onSelect={() => commit(updateNode(doc, node.id, { maskSrc: undefined }))}>+ <Scissors /> Delete mask+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => move(1)} disabled={node.z >= total - 1}>+ <ArrowUp /> Bring forward+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => move(-1)} disabled={node.z <= 0}>+ <ArrowDown /> Send backward+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onSelect={remove}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </li>+ );+}++/** Per-layer AI: “Layer edit prompt” + reference → Generate / Regenerate, and the layer's revisions. */+function SelectedLayer({ node }: { node: LayerNode }) {+ const { doc, commit, run, engine, models, isDemo, jobs, endJob, busyJob } = useEditor();+ const [prompt, setPrompt] = useState(node.prompt ?? "");+ const [ref, setRef] = useState<string | null>(node.refSrc ?? null);+ const options = modelsFor(models, TOOL_MODELS.regenerate[engine]);+ const [modelId, setModelId] = useState<string | undefined>();+ const model = options.find((m) => m.id === modelId) ?? options[0];+ // Layers cut out of a picture keep their transparency; the bottom layer is usually a full picture.+ const [keepAlpha, setKeepAlpha] = useState(node.z > 0);+ const [starting, setStarting] = useState(false);+ const running = busyJob(node.id);+ const failed = useMemo(() => {+ const j = latestJob(jobs, ["regenerate"], node.id);+ return j && isFailed(j) ? j : undefined;+ }, [jobs, node.id]);+ const edited = node.revisions.length > 1;+ const rev = node.revisions[node.revision];++ const go = async () => {+ if (!prompt.trim()) {+ toast.error("Describe the change in the layer edit prompt");+ return;+ }+ setStarting(true);+ commit(updateNode(doc, node.id, { prompt: prompt.trim(), refSrc: ref ?? undefined }));+ await run({ tool: "regenerate", target: { kind: "node", node }, prompt: prompt.trim(), refs: ref ? [ref] : undefined, modelId: model?.id, settings: { keepAlpha }, label: "Layer edit" });+ setStarting(false);+ };++ return (+ <div className="space-y-3 border-t px-3 pt-3 pb-4">+ <div className="flex items-center justify-between gap-2">+ <h3 className="truncate text-[13px] font-medium">{node.name}</h3>+ <span className="shrink-0 font-mono text-[11px] text-subtle-foreground">+ {Math.round(node.w)} × {Math.round(node.h)}+ </span>+ </div>+ <Field label="Layer edit prompt" htmlFor="layer-prompt">+ <Textarea+ id="layer-prompt"+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ maxLength={2000}+ placeholder="e.g. “make the jacket red leather”"+ className="min-h-16 text-[13px]"+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void go();+ }}+ />+ </Field>+ <div className="flex flex-wrap items-center gap-2">+ <RefPicker value={ref} onChange={setRef} />+ {options.length > 1 && (+ <Select value={model?.id} onValueChange={setModelId}>+ <SelectTrigger size="sm" className="h-8 max-w-[11rem] rounded-full text-[12px]" aria-label="Model">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {options.map((m) => (+ <SelectItem key={m.id} value={m.id}>+ {m.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </div>+ <label className="flex items-center justify-between gap-2 text-[12px] text-muted-foreground">+ Keep transparency (cut the background back out)+ <Switch checked={keepAlpha} onCheckedChange={setKeepAlpha} aria-label="Keep transparency" />+ </label>+ {running ? (+ <div className="flex items-center gap-2 rounded-lg bg-muted px-3 py-2 text-[12px]">+ <Loader2 className="size-3.5 animate-spin text-brand-text" />+ <span className="min-w-0 flex-1 truncate">+ {running.label} · {jobStatusText(running.result)}+ </span>+ <button type="button" className="text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" onClick={() => endJob(running.id, "cancel")}>+ Cancel+ </button>+ </div>+ ) : (+ <div className="flex items-center justify-between gap-2">+ <span className="font-mono text-[12px] text-muted-foreground">{costLabel(model, isDemo(model))}</span>+ <Button size="sm" className="rounded-full" onClick={() => void go()} disabled={starting || !model}>+ {starting ? <Loader2 className="animate-spin" /> : <Sparkles />} {edited ? "Regenerate layer" : "Generate layer"}+ </Button>+ </div>+ )}+ {failed && (+ <div role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-[12px]">+ <p className="font-medium text-destructive">Layer generation failed</p>+ <p className="text-muted-foreground">{failed.result?.error ?? "Try again."}</p>+ <div className="mt-1.5 flex gap-3">+ <button type="button" className="font-medium text-brand-text hover:underline" onClick={() => void go()}>+ Try again+ </button>+ <button type="button" className="text-muted-foreground hover:underline" onClick={() => endJob(failed.id, "dismiss")}>+ Dismiss+ </button>+ </div>+ </div>+ )}+ {edited && (+ <div className="space-y-1.5 rounded-lg bg-muted/60 p-2">+ <div className="flex items-center gap-1">+ <Button size="icon-xs" variant="ghost" aria-label="Show previous versions" disabled={node.revision === 0} onClick={() => commit(updateNode(doc, node.id, setRevision(node, node.revision - 1)))}>+ <ChevronLeft />+ </Button>+ <span className="min-w-0 flex-1 truncate text-center text-[12px]">+ <span className="font-medium">{rev?.label ?? "Version"}</span> · {node.revision + 1}/{node.revisions.length}+ </span>+ <Button size="icon-xs" variant="ghost" aria-label="Show next versions" disabled={node.revision >= node.revisions.length - 1} onClick={() => commit(updateNode(doc, node.id, setRevision(node, node.revision + 1)))}>+ <ChevronRight />+ </Button>+ </div>+ <Button size="xs" variant="ghost" className="w-full" disabled={node.revision === 0} onClick={() => commit(updateNode(doc, node.id, setRevision(node, 0)))}>+ <RotateCcw /> Reset layer+ </Button>+ </div>+ )}+ <Field label="Opacity" hint={`${Math.round((node.opacity ?? 1) * 100)}%`}>+ <Slider aria-label="Opacity" min={0} max={100} step={1} value={[Math.round((node.opacity ?? 1) * 100)]} onValueChange={([v]) => commit(updateNode(doc, node.id, { opacity: v / 100 }))} />+ </Field>+ <div className="grid grid-cols-5 gap-1.5">+ {(+ [+ ["x", "X"],+ ["y", "Y"],+ ["w", "W"],+ ["h", "H"],+ ["rotation", "°"],+ ] as const+ ).map(([k, label]) => (+ <label key={k} className="space-y-0.5">+ <span className="block text-center text-[11px] text-muted-foreground">{label}</span>+ <Input+ type="number"+ inputMode="decimal"+ aria-label={k === "rotation" ? "Rotation in degrees" : `${label} in pixels`}+ className="h-7 px-1 text-center font-mono text-[12px]"+ value={Math.round(node[k])}+ onChange={(e) => {+ const v = Number(e.target.value);+ if (!Number.isFinite(v) || ((k === "w" || k === "h") && v < 1)) return;+ commit(updateNode(doc, node.id, { [k]: v }));+ }}+ />+ </label>+ ))}+ </div>+ </div>+ );+}++export function LayersPanel() {+ const { doc, commit, selected, busyJob } = useEditor();+ const rows = useMemo(() => [...doc.nodes].sort((a, b) => b.z - a.z), [doc.nodes]);+ const list = useRef<HTMLUListElement>(null);+ const [dragging, setDragging] = useState<{ id: string; before: number } | null>(null);++ // Drag a row by its handle: drop it between two rows (top of the list = front).+ const onDragHandle = (e: React.PointerEvent, id: string) => {+ if (e.button !== 0) return;+ e.preventDefault();+ const el = list.current;+ if (!el) return;+ const items = [...el.querySelectorAll<HTMLElement>(":scope > li")];+ const target = e.currentTarget as HTMLElement;+ target.setPointerCapture(e.pointerId);+ const slot = (y: number) => {+ const i = items.findIndex((li) => {+ const r = li.getBoundingClientRect();+ return y < r.top + r.height / 2;+ });+ return i < 0 ? items.length : i;+ };+ let before = slot(e.clientY);+ setDragging({ id, before });+ const move = (ev: PointerEvent) => {+ before = slot(ev.clientY);+ setDragging({ id, before });+ };+ const up = () => {+ target.removeEventListener("pointermove", move);+ target.removeEventListener("pointerup", up);+ target.removeEventListener("pointercancel", up);+ setDragging(null);+ const from = rows.findIndex((r) => r.id === id);+ let to = before > from ? before - 1 : before;+ to = Math.max(0, Math.min(rows.length - 1, to));+ if (to !== from) commit(moveNode(doc, id, rows.length - 1 - to));+ };+ target.addEventListener("pointermove", move);+ target.addEventListener("pointerup", up);+ target.addEventListener("pointercancel", up);+ };++ return (+ <aside className="flex min-h-0 w-[300px] shrink-0 flex-col border-l bg-background" aria-label="Layers panel">+ <div className="flex h-12 shrink-0 items-center gap-2 px-3">+ <h2 className="text-[13px] font-semibold">Layers</h2>+ <span className="font-mono text-[12px] text-subtle-foreground">{doc.nodes.length}</span>+ <div className="ml-auto">+ <AddLayer />+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain">+ <ul ref={list} className="space-y-0.5 px-2 pb-2" aria-label="Layers, front to back">+ {rows.map((n, i) => {+ const job = busyJob(n.id);+ const busy = job ? `${job.tool === "split" ? `Separating ${n.name}` : job.label} · ${jobStatusText(job.result)}` : undefined;+ return <LayerRow key={n.id} node={n} index={n.z} total={rows.length} selected={n.id === selected?.id} busy={busy} onDragHandle={onDragHandle} dropBefore={!!dragging && dragging.before === i && dragging.id !== n.id} />;+ })}+ {dragging && dragging.before === rows.length && <li className="mx-2 h-0.5 rounded-full bg-primary" aria-hidden />}+ </ul>+ {selected ? (+ <SelectedLayer key={selected.id} node={selected} />+ ) : (+ <p className="border-t px-4 py-4 text-[12px] text-pretty text-muted-foreground">Select a layer in the Layers panel, then move it, resize it, or describe your change in its prompt.</p>+ )}+ </div>+ </aside>+ );+}diff --git a/src/components/layers/mobile-view.tsx b/src/components/layers/mobile-view.tsxnew file mode 100644index 00000000..232028d0--- /dev/null+++ b/src/components/layers/mobile-view.tsx@@ -0,0 +1,78 @@+"use client";++import { ArrowLeft, EyeOff, MonitorSmartphone } from "lucide-react";+import Link from "next/link";+import { useEffect, useState } from "react";+import { Button } from "@/components/ui/button";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import type { LayerDoc, LayerJob, LayerProject } from "@/lib/layers";+import { LayerThumb } from "./layers-panel";+import { renderDoc, toBlob } from "./render";+import { DownloadMenu } from "./top-bar";++/** Phones: a friendly read-only view with the picture, its layers and the downloads. */+export function MobileView({ project, doc, jobs }: { project: LayerProject; doc: LayerDoc; jobs: LayerJob[] }) {+ const [preview, setPreview] = useState<string | null>(null);+ useEffect(() => {+ let url: string | null = null;+ let gone = false;+ void renderDoc(doc, { scale: Math.min(1, 1200 / Math.max(doc.width, doc.height)) })+ .then((c) => toBlob(c))+ .then((b) => {+ if (gone) return;+ url = URL.createObjectURL(b);+ setPreview(url);+ })+ .catch(() => setPreview(doc.source));+ return () => {+ gone = true;+ if (url) URL.revokeObjectURL(url);+ };+ }, [doc]);+ const rows = [...doc.nodes].sort((a, b) => b.z - a.z);++ return (+ <div className="flex min-h-svh min-w-0 flex-col">+ <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur">+ <SidebarTrigger />+ <Button asChild variant="ghost" size="icon-sm" aria-label="All projects">+ <Link href="/layers">+ <ArrowLeft />+ </Link>+ </Button>+ <h1 className="min-w-0 flex-1 truncate font-heading text-[20px]">{project.name}</h1>+ <DownloadMenu doc={doc} name={project.name} jobs={jobs} compact />+ </header>+ <main className="mx-auto w-full max-w-xl flex-1 space-y-5 px-4 pb-12">+ <div className="flex items-start gap-3 rounded-xl border bg-card p-3">+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-brand-faint text-brand-text">+ <MonitorSmartphone className="size-4" />+ </span>+ <div className="min-w-0">+ <p className="text-[14px] font-medium">Layers works best on a larger screen</p>+ <p className="text-[13px] text-pretty text-muted-foreground">Open this project on a computer to separate, move and edit layers. Here you can preview it and download the layers.</p>+ </div>+ </div>+ <div className="checkerboard overflow-hidden rounded-xl border" style={{ aspectRatio: `${doc.width} / ${doc.height}` }}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {preview ? <img src={preview} alt={`${project.name}, all visible layers`} className="size-full object-contain" /> : <Skeleton className="size-full rounded-none" />}+ </div>+ <section aria-labelledby="mobile-layers">+ <h2 id="mobile-layers" className="mb-2 text-[13px] font-semibold">+ Layers <span className="font-mono font-normal text-subtle-foreground">{rows.length}</span>+ </h2>+ <ul className="divide-y rounded-xl border">+ {rows.map((n) => (+ <li key={n.id} className="flex items-center gap-3 px-3 py-2">+ <LayerThumb node={n} />+ <span className="min-w-0 flex-1 truncate text-[14px]">{n.name}</span>+ {n.hidden && <EyeOff className="size-4 text-muted-foreground" aria-label="Hidden" />}+ </li>+ ))}+ </ul>+ </section>+ </main>+ </div>+ );+}diff --git a/src/components/layers/projects-view.tsx b/src/components/layers/projects-view.tsxnew file mode 100644index 00000000..401a5814--- /dev/null+++ b/src/components/layers/projects-view.tsx@@ -0,0 +1,391 @@+"use client";++import { ChevronLeft, ChevronRight, ExternalLink, ImagePlus, Layers, Library, Loader2, MonitorSmartphone, MoreHorizontal, Pencil, RotateCcw, Sun, Trash2, Type, Upload, Wand2, Sparkles } from "lucide-react";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import { Suspense, useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";+import { Input } from "@/components/ui/input";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Skeleton } from "@/components/ui/skeleton";+import { LibraryGrid } from "@/components/studio/media-slot";+import { PageShell } from "@/components/page-shell";+import { uploadFile } from "@/lib/api";+import { timeAgo } from "@/lib/format";+import type { LayerProject } from "@/lib/layers";+import { cn } from "@/lib/utils";+import { loadImage, sizeOf } from "./render";+import { useLayerActions, useLayerProjects } from "./use-layers";++const CAPABILITIES = [+ { label: "Layer Decomposition", icon: Layers, text: "Split any flat image into clean, editable layers — subject, background and details." },+ { label: "Edit text", icon: Type, text: "Find the words on a poster and rewrite them in the original design." },+ { label: "Relight", icon: Sun, text: "Change the light on one layer or the whole picture." },+ { label: "Inpaint", icon: Wand2, text: "Draw a box, describe the change, and blend it back in." },+ { label: "Effects", icon: Sparkles, text: "Upscale, remove backgrounds, new angles and colour grades per layer." },+] as const;++const IMAGE_TYPES = "image/png,image/jpeg,image/webp";++/** Upload or pick an image, read its size, create the project and open it. */+function useOpenImage() {+ const router = useRouter();+ const { create } = useLayerActions();+ const [busy, setBusy] = useState<string | null>(null);+ const open = async (source: string, opts: { name?: string; generationId?: string; label?: string } = {}) => {+ setBusy(opts.label ?? "Preparing your project");+ try {+ const img = await loadImage(source).catch(() => {+ throw new Error("This image cannot be decomposed — Layer decomposition needs a generated or uploaded image.");+ });+ const [width, height] = sizeOf(img);+ const v = await create({ source, width, height, name: opts.name, generationId: opts.generationId });+ router.replace(`/layers/${v.project.id}`);+ } catch (e) {+ toast.error((e as Error).message || "Couldn't open the editor for this image. Please try again.");+ setBusy(null);+ }+ };+ const openFile = async (file: File) => {+ if (!/^image\/(png|jpeg|webp)$/.test(file.type)) {+ toast.error("Only images can be edited here. Pick an image or upload one.");+ return;+ }+ setBusy("Uploading…");+ try {+ const asset = await uploadFile(file);+ await open(asset.url, { name: file.name.replace(/\.[^.]+$/, "").slice(0, 80) });+ } catch (e) {+ toast.error((e as Error).message);+ setBusy(null);+ }+ };+ return { busy, open, openFile };+}++function ProjectCard({ p, onRename, onDelete }: { p: LayerProject; onRename: () => void; onDelete: () => void }) {+ return (+ <article className="group/card relative min-w-0">+ <Link href={`/layers/${p.id}`} aria-label={`Open project ${p.name}`} className="block rounded-xl outline-none focus-visible:ring-4 focus-visible:ring-brand-faint">+ <div className="checkerboard relative aspect-[4/3] overflow-hidden rounded-xl border transition-shadow group-hover/card:shadow-normal">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={p.coverUrl} alt="" loading="lazy" className="size-full object-contain" />+ {p.status !== "ready" && (+ <span+ className={cn(+ "absolute top-2 left-2 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[12px] font-medium backdrop-blur",+ p.status === "processing" ? "bg-background/85 text-foreground" : "bg-destructive/90 text-white",+ )}+ >+ {p.status === "processing" ? <Loader2 className="size-3 animate-spin" /> : null}+ {p.status === "processing" ? "Processing…" : "Couldn't be processed"}+ </span>+ )}+ </div>+ <h3 className="mt-2 truncate pr-9 text-[14px] font-medium">{p.name}</h3>+ <p className="text-[12px] text-muted-foreground">+ {timeAgo(p.updatedAt)} · {p.layers} layer{p.layers === 1 ? "" : "s"}+ </p>+ </Link>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="absolute right-0 bottom-5 grid size-8 place-items-center rounded-md text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground focus-visible:opacity-100 data-[state=open]:opacity-100 sm:opacity-0 sm:group-hover/card:opacity-100"+ aria-label={`Actions for ${p.name}`}+ >+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuItem asChild>+ <Link href={`/layers/${p.id}`}>+ <ExternalLink /> Open+ </Link>+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => setTimeout(onRename)}>+ <Pencil /> Rename+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onSelect={() => setTimeout(onDelete)}>+ <Trash2 /> Delete project+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </article>+ );+}++function Capabilities() {+ const [at, setAt] = useState(0);+ const c = CAPABILITIES[at];+ return (+ <div className="mt-6">+ <div className="flex items-center justify-center gap-1.5">+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Previous capability" onClick={() => setAt((at + CAPABILITIES.length - 1) % CAPABILITIES.length)}>+ <ChevronLeft />+ </Button>+ <div className="scrollbar-none flex min-w-0 gap-1.5 overflow-x-auto" role="tablist" aria-label="What Layers can do">+ {CAPABILITIES.map((x, i) => (+ <button+ key={x.label}+ role="tab"+ aria-selected={i === at}+ onClick={() => setAt(i)}+ className={cn(+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors",+ i === at ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",+ )}+ >+ <x.icon className="size-3.5" /> {x.label}+ </button>+ ))}+ </div>+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Next capability" onClick={() => setAt((at + 1) % CAPABILITIES.length)}>+ <ChevronRight />+ </Button>+ </div>+ <p className="mt-2 text-center text-[13px] text-muted-foreground" aria-live="polite">+ {c.text}+ </p>+ </div>+ );+}++function ProjectsInner() {+ const params = useSearchParams();+ const projects = useLayerProjects();+ const { rename, remove } = useLayerActions();+ const { busy, open, openFile } = useOpenImage();+ const file = useRef<HTMLInputElement>(null);+ const [picking, setPicking] = useState(false);+ const [renaming, setRenaming] = useState<LayerProject | null>(null);+ const [draft, setDraft] = useState("");+ const [deleting, setDeleting] = useState<LayerProject | null>(null);+ const [dragging, setDragging] = useState(false);++ // Deep link: /layers?image=<url>[&generation=<id>&name=…] opens that image as a project.+ const deep = params.get("image");+ const started = useRef(false);+ useEffect(() => {+ if (!deep || started.current) return;+ started.current = true;+ if (!deep.startsWith("/api/files/")) {+ toast.error("Only images from your library can be edited here. Pick an image or upload one.");+ return;+ }+ void open(deep, { generationId: params.get("generation") ?? undefined, name: params.get("name") ?? undefined });+ }, [deep, params, open]);++ const items = projects.data ?? [];++ return (+ <PageShell wide>+ <div+ className="relative"+ onDragOver={(e) => {+ if (e.dataTransfer.types.includes("Files")) {+ e.preventDefault();+ setDragging(true);+ }+ }}+ onDragLeave={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragging(false);+ }}+ onDrop={(e) => {+ e.preventDefault();+ setDragging(false);+ const f = e.dataTransfer.files[0];+ if (f) void openFile(f);+ }}+ >+ <section className="mx-auto max-w-[820px] pt-[4vh] text-center">+ <span className="mx-auto grid size-11 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Layers className="size-5" />+ </span>+ <h1 className="mt-4 font-heading text-display text-balance">+ Turn flat images+ <br className="hidden sm:block" /> into editable layers.+ </h1>+ <p className="mx-auto mt-2 max-w-[560px] text-body text-pretty text-muted-foreground">Separate, edit, and rebuild any image. Every element, now yours to edit.</p>+ <Capabilities />+ <div className="mt-7 flex flex-wrap items-center justify-center gap-2">+ <input+ ref={file}+ type="file"+ accept={IMAGE_TYPES}+ className="sr-only"+ tabIndex={-1}+ aria-hidden+ onChange={(e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (f) void openFile(f);+ }}+ />+ <Button size="lg" className="rounded-full px-5" onClick={() => file.current?.click()} disabled={!!busy}>+ {busy ? <Loader2 className="animate-spin" /> : <Upload />} Upload Media+ </Button>+ <Popover open={picking} onOpenChange={setPicking}>+ <PopoverTrigger asChild>+ <Button size="lg" variant="secondary" className="rounded-full px-5" disabled={!!busy}>+ <Library /> From your library+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,420px)] p-2" collisionPadding={12}>+ <p className="px-1 pb-2 text-[13px] font-medium">Pick an image you uploaded or generated</p>+ {picking && (+ <LibraryGrid+ kinds={["image"]}+ onPick={(v) => {+ setPicking(false);+ void open(v.ref, { name: v.name });+ }}+ />+ )}+ </PopoverContent>+ </Popover>+ </div>+ <p className="mt-3 text-[12px] text-subtle-foreground">Upload an image, or pick one you already generated. Images only — JPG, PNG or WebP.</p>+ <p className="mx-auto mt-4 flex max-w-md items-center justify-center gap-2 rounded-full bg-muted px-3 py-1.5 text-[12px] text-muted-foreground md:hidden">+ <MonitorSmartphone className="size-3.5 shrink-0" /> Layers works best on a larger screen — on a phone you can preview and download.+ </p>+ </section>++ <section className="mt-14" aria-labelledby="my-projects">+ <h2 id="my-projects" className="font-heading text-[24px]">+ My projects+ </h2>+ {projects.isLoading ? (+ <div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">+ {Array.from({ length: 5 }, (_, i) => (+ <div key={i}>+ <Skeleton className="aspect-[4/3] rounded-xl" />+ <Skeleton className="mt-2 h-4 w-2/3" />+ </div>+ ))}+ </div>+ ) : projects.isError ? (+ <Empty className="mt-4 border">+ <EmptyHeader>+ <EmptyTitle className="text-[22px]">We couldn't load your projects</EmptyTitle>+ <EmptyDescription>{(projects.error as Error).message}</EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button variant="outline" className="rounded-full" onClick={() => void projects.refetch()}>+ <RotateCcw /> Try loading projects again+ </Button>+ </EmptyContent>+ </Empty>+ ) : items.length ? (+ <div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">+ {items.map((p) => (+ <ProjectCard+ key={p.id}+ p={p}+ onRename={() => {+ setDraft(p.name);+ setRenaming(p);+ }}+ onDelete={() => setDeleting(p)}+ />+ ))}+ </div>+ ) : (+ <Empty className="mt-4 border">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <ImagePlus />+ </EmptyMedia>+ <EmptyTitle className="font-heading text-[22px]">Your edit projects will appear here</EmptyTitle>+ <EmptyDescription>Upload an image to separate it into editable layers — every project you start is saved here.</EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button className="rounded-full" onClick={() => file.current?.click()} disabled={!!busy}>+ <Upload /> Upload Media+ </Button>+ </EmptyContent>+ </Empty>+ )}+ </section>++ {dragging && (+ <div className="pointer-events-none fixed inset-0 z-40 grid place-items-center bg-overlay/40 backdrop-blur-[2px]">+ <p className="rounded-2xl border bg-background px-6 py-4 text-[15px] font-medium shadow-heavy">Drop an image to open it in Layers</p>+ </div>+ )}+ {busy && (+ <div role="status" className="fixed inset-0 z-50 grid place-items-center bg-background/80 backdrop-blur-sm">+ <div className="flex flex-col items-center gap-3 text-center">+ <Loader2 className="size-6 animate-spin text-brand-text" />+ <p className="font-heading text-[22px]">{busy}</p>+ <p className="text-[13px] text-muted-foreground">Your image opens as the first layer.</p>+ </div>+ </div>+ )}+ </div>++ <Dialog open={!!renaming} onOpenChange={(o) => !o && setRenaming(null)}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>Rename project</DialogTitle>+ <DialogDescription className="sr-only">Give this project a new name</DialogDescription>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ const p = renaming!;+ const name = draft.trim();+ setRenaming(null);+ if (name && name !== p.name) void rename(p.id, name).then(() => toast.success("Renamed", { duration: 1500 }), (err) => toast.error((err as Error).message));+ }}+ >+ <Input autoFocus value={draft} maxLength={80} onChange={(e) => setDraft(e.target.value)} aria-label="Project name" onFocus={(e) => e.currentTarget.select()} />+ <DialogFooter className="mt-4">+ <Button type="button" variant="ghost" onClick={() => setRenaming(null)}>+ Cancel+ </Button>+ <Button type="submit" disabled={!draft.trim()}>+ Save+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete this project?</AlertDialogTitle>+ <AlertDialogDescription>This project and all of its layers will be permanently deleted. This cannot be undone. The image it was opened on stays in your gallery.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ const p = deleting!;+ setDeleting(null);+ void remove(p.id).then(() => toast("Project deleted", { duration: 1500 }), (e) => toast.error((e as Error).message));+ }}+ >+ Delete project+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </PageShell>+ );+}++export function LayersProjects() {+ return (+ <Suspense fallback={null}>+ <ProjectsInner />+ </Suspense>+ );+}diff --git a/src/components/layers/render.ts b/src/components/layers/render.tsnew file mode 100644index 00000000..d645377f--- /dev/null+++ b/src/components/layers/render.ts@@ -0,0 +1,324 @@+"use client";++/**+ * Drawing the layer document with a 2D canvas: the stage, the composite, the two zips and the+ * pictures handed to models all go through drawNode, so what you download is what you see.+ */++import { uploadFile } from "@/lib/api";+import { bboxFromAlpha, cropRect, nativeSize, slugify, sourceRect, storedZip, zipPlan, type Box, type LayerDoc, type LayerNode } from "@/lib/layers";++// ---------------------------------------------------------------------------+// Images++const loading = new Map<string, Promise<HTMLImageElement>>();+const loaded = new Map<string, HTMLImageElement>();++export function loadImage(src: string): Promise<HTMLImageElement> {+ let p = loading.get(src);+ if (!p) {+ p = new Promise<HTMLImageElement>((resolve, reject) => {+ const img = new Image();+ img.decoding = "async";+ img.onload = () => {+ loaded.set(src, img);+ resolve(img);+ };+ img.onerror = () => {+ loading.delete(src);+ reject(new Error("Couldn't load an image of this project"));+ };+ img.src = src;+ });+ loading.set(src, p);+ }+ return p;+}++/** The image if it's loaded; otherwise starts loading it and calls `onLoad` when it is. */+export function readyImage(src: string, onLoad?: () => void): HTMLImageElement | undefined {+ const img = loaded.get(src);+ if (img) return img;+ void loadImage(src).then(+ () => onLoad?.(),+ () => {},+ );+ return undefined;+}++/** Pixel size of an image (SVGs without a size read as 1024 wide). */+export function sizeOf(img: HTMLImageElement): [number, number] {+ const w = img.naturalWidth || img.width || 1024;+ const h = img.naturalHeight || img.height || Math.round(w);+ return [w, h];+}++/** A layer's source rectangle in the loaded image's own pixels (the stored crop may be in other units for SVGs). */+function srcRectFor(node: LayerNode, img: HTMLImageElement): Box {+ const [iw, ih] = sizeOf(img);+ const r = sourceRect(node);+ if (!r) return [0, 0, iw, ih];+ const [nw, nh] = node.natural ?? [iw, ih];+ const kx = iw / nw;+ const ky = ih / nh;+ return [r[0] * kx, r[1] * ky, r[2] * kx, r[3] * ky];+}++// ---------------------------------------------------------------------------+// Drawing++export interface Sources {+ /** Mask canvases being painted (by node id): drawn instead of the saved mask. */+ masks?: Map<string, HTMLCanvasElement>;+ /** Changes bumped while painting, so cached layers redraw. */+ maskVersion?: number;+ /** Live previews (colour grading) by node id: drawn instead of the layer's image. */+ previews?: Map<string, HTMLCanvasElement>;+}++/** Layers with a mask or a soft edge are drawn through a small cache of offscreen canvases. */+const softCache = new Map<string, HTMLCanvasElement>();++function featherInto(ctx: CanvasRenderingContext2D, w: number, h: number, f: number) {+ if (f <= 0) return;+ ctx.globalCompositeOperation = "destination-in";+ const fx = Math.min(0.5, f / w);+ const fy = Math.min(0.5, f / h);+ const gx = ctx.createLinearGradient(0, 0, w, 0);+ gx.addColorStop(0, "rgba(0,0,0,0)");+ gx.addColorStop(fx, "rgba(0,0,0,1)");+ gx.addColorStop(1 - fx, "rgba(0,0,0,1)");+ gx.addColorStop(1, "rgba(0,0,0,0)");+ ctx.fillStyle = gx;+ ctx.fillRect(0, 0, w, h);+ const gy = ctx.createLinearGradient(0, 0, 0, h);+ gy.addColorStop(0, "rgba(0,0,0,0)");+ gy.addColorStop(fy, "rgba(0,0,0,1)");+ gy.addColorStop(1 - fy, "rgba(0,0,0,1)");+ gy.addColorStop(1, "rgba(0,0,0,0)");+ ctx.fillStyle = gy;+ ctx.fillRect(0, 0, w, h);+ ctx.globalCompositeOperation = "source-over";+}++/**+ * One layer alone, unrotated, at `w × h` pixels: its pixels (crop), its mask and soft edge applied.+ * Returns null while an image it needs is still loading.+ */+export function layerCanvas(node: LayerNode, w: number, h: number, src: Sources = {}, onLoad?: () => void, cache = true): HTMLCanvasElement | null {+ const preview = src.previews?.get(node.id);+ const img = preview ?? readyImage(node.src, onLoad);+ if (!img) return null;+ const maskOverride = src.masks?.get(node.id);+ const mask = maskOverride ?? (node.maskSrc ? readyImage(node.maskSrc, onLoad) : undefined);+ if (node.maskSrc && !maskOverride && !mask) return null;+ const key = cache && !preview ? `${node.src}|${node.crop?.join(",")}|${node.maskSrc}|${maskOverride ? src.maskVersion : ""}|${node.feather ?? 0}|${w}x${h}` : "";+ const hit = key ? softCache.get(key) : undefined;+ if (hit) return hit;+ const c = document.createElement("canvas");+ c.width = Math.max(1, Math.round(w));+ c.height = Math.max(1, Math.round(h));+ const ctx = c.getContext("2d")!;+ if (preview) ctx.drawImage(preview, 0, 0, c.width, c.height);+ else {+ const [sx, sy, sw, sh] = srcRectFor(node, img as HTMLImageElement);+ ctx.drawImage(img, sx, sy, sw, sh, 0, 0, c.width, c.height);+ }+ if (mask) {+ ctx.globalCompositeOperation = "destination-in";+ ctx.drawImage(mask, 0, 0, c.width, c.height);+ ctx.globalCompositeOperation = "source-over";+ }+ featherInto(ctx, c.width, c.height, ((node.feather ?? 0) * c.width) / node.w);+ if (key) {+ softCache.set(key, c);+ if (softCache.size > 60) softCache.delete(softCache.keys().next().value!);+ }+ return c;+}++/**+ * Draw a layer in document coordinates (the context's transform maps document px to the target).+ * `pxPerDoc` is how many target pixels one document pixel covers (sizes the offscreen copy). Returns+ * false while an image is still loading.+ */+export function drawNode(ctx: CanvasRenderingContext2D, node: LayerNode, pxPerDoc: number, src: Sources = {}, onLoad?: () => void): boolean {+ const soft = !!(node.maskSrc || node.feather || src.masks?.has(node.id) || src.previews?.has(node.id));+ ctx.save();+ ctx.globalAlpha = node.opacity ?? 1;+ ctx.translate(node.x + node.w / 2, node.y + node.h / 2);+ if (node.rotation) ctx.rotate((node.rotation * Math.PI) / 180);+ let ok = true;+ if (soft) {+ // Offscreen at the size it's shown, capped (a 4K layer on a small stage doesn't need 4K pixels).+ const k = Math.min(1, 2048 / Math.max(node.w * pxPerDoc, node.h * pxPerDoc));+ const c = layerCanvas(node, Math.ceil(node.w * pxPerDoc * k), Math.ceil(node.h * pxPerDoc * k), src, onLoad);+ if (c) ctx.drawImage(c, -node.w / 2, -node.h / 2, node.w, node.h);+ else ok = false;+ } else {+ const img = readyImage(node.src, onLoad);+ if (img) {+ const [sx, sy, sw, sh] = srcRectFor(node, img);+ ctx.drawImage(img, sx, sy, sw, sh, -node.w / 2, -node.h / 2, node.w, node.h);+ } else ok = false;+ }+ ctx.restore();+ return ok;+}++/** Wait until every image the layers need is loaded (for exports and renders handed to models). */+export async function preload(nodes: LayerNode[]): Promise<void> {+ await Promise.all(nodes.flatMap((n) => [loadImage(n.src), ...(n.maskSrc ? [loadImage(n.maskSrc)] : [])]));+}++/**+ * Render part of the document (`rect`, doc px; default the whole canvas) at `scale`, with every+ * visible layer, or only the layer `only` (hidden or not). `fill` paints a background first.+ */+export async function renderDoc(doc: LayerDoc, opts: { rect?: Box; scale?: number; only?: string; fill?: string; src?: Sources } = {}): Promise<HTMLCanvasElement> {+ const rect = opts.rect ?? [0, 0, doc.width, doc.height];+ const scale = opts.scale ?? 1;+ const nodes = [...doc.nodes].sort((a, b) => a.z - b.z).filter((n) => (opts.only ? n.id === opts.only : !n.hidden));+ await preload(nodes);+ const c = document.createElement("canvas");+ c.width = Math.max(1, Math.round(rect[2] * scale));+ c.height = Math.max(1, Math.round(rect[3] * scale));+ const ctx = c.getContext("2d")!;+ if (opts.fill) {+ ctx.fillStyle = opts.fill;+ ctx.fillRect(0, 0, c.width, c.height);+ }+ ctx.scale(scale, scale);+ ctx.translate(-rect[0], -rect[1]);+ for (const n of nodes) drawNode(ctx, n, scale, opts.src);+ return c;+}++/** One layer alone at its own resolution, unrotated (what tools hand to a model). */+export async function renderNative(node: LayerNode, max = 2048): Promise<HTMLCanvasElement> {+ await preload([node]);+ const [w, h] = nativeSize(node, max);+ return layerCanvas(node, w, h, {}, undefined, false)!;+}++export function toBlob(c: HTMLCanvasElement, type = "image/png", quality?: number): Promise<Blob> {+ return new Promise((resolve, reject) => c.toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't render the image"))), type, quality));+}++/** Upload a render as a PNG and return its /api/files URL. */+export async function uploadRender(c: HTMLCanvasElement, name: string): Promise<string> {+ const blob = await toBlob(c);+ const asset = await uploadFile(new File([blob], `${slugify(name) || "layer"}.png`, { type: "image/png" }));+ return asset.url;+}++/** The alpha box of an image in its own pixels (measured on a copy at most 1024 px wide). */+export function alphaBox(img: HTMLImageElement): Box | null {+ const [nw, nh] = sizeOf(img);+ const k = Math.min(1, 1024 / Math.max(nw, nh));+ const w = Math.max(1, Math.round(nw * k));+ const h = Math.max(1, Math.round(nh * k));+ const c = document.createElement("canvas");+ c.width = w;+ c.height = h;+ const ctx = c.getContext("2d", { willReadFrequently: true })!;+ ctx.drawImage(img, 0, 0, w, h);+ const b = bboxFromAlpha(ctx.getImageData(0, 0, w, h).data, w, h, 8);+ if (!b) return null;+ const x0 = Math.max(0, Math.floor(b[0] / k));+ const y0 = Math.max(0, Math.floor(b[1] / k));+ const x1 = Math.min(nw, Math.ceil((b[0] + b[2]) / k));+ const y1 = Math.min(nh, Math.ceil((b[1] + b[3]) / k));+ return [x0, y0, x1 - x0, y1 - y0];+}++// ---------------------------------------------------------------------------+// Hit testing by alpha (clicking a subject selects it, not the transparent canvas above it)++const alphaMaps = new Map<string, { data: Uint8ClampedArray; w: number; h: number }>();++/** Whether a layer is opaque at its local point (u, v in 0–1). Unknown (still loading) counts as opaque. */+export function opaqueAt(node: LayerNode, u: number, v: number): boolean {+ const img = loaded.get(node.src);+ if (!img) return true;+ let map = alphaMaps.get(node.src);+ if (!map) {+ const [nw, nh] = sizeOf(img);+ const k = Math.min(1, 256 / Math.max(nw, nh));+ const w = Math.max(1, Math.round(nw * k));+ const h = Math.max(1, Math.round(nh * k));+ const c = document.createElement("canvas");+ c.width = w;+ c.height = h;+ const ctx = c.getContext("2d", { willReadFrequently: true })!;+ ctx.drawImage(img, 0, 0, w, h);+ try {+ map = { data: ctx.getImageData(0, 0, w, h).data, w, h };+ } catch {+ return true;+ }+ alphaMaps.set(node.src, map);+ }+ const [sx, sy, sw, sh] = srcRectFor(node, img);+ const [iw, ih] = sizeOf(img);+ const x = Math.min(map.w - 1, Math.max(0, Math.floor(((sx + u * sw) / iw) * map.w)));+ const y = Math.min(map.h - 1, Math.max(0, Math.floor(((sy + v * sh) / ih) * map.h)));+ return map.data[(y * map.w + x) * 4 + 3] > 16;+}++// ---------------------------------------------------------------------------+// Downloads (built in the browser, no server round trip)++function save(blob: Blob, name: string) {+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = name;+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 30_000);+}++const bytes = async (c: HTMLCanvasElement) => new Uint8Array(await (await toBlob(c)).arrayBuffer());++/**+ * cropped-layers.zip (each layer alone, cut to its rotation-aware box) or positioned-layers.zip+ * (each layer alone on a transparent canvas the size of the document), both with composite.png.+ */+export async function downloadZip(doc: LayerDoc, kind: "cropped" | "positioned"): Promise<number> {+ if (!doc.nodes.length) throw new Error("No layers to download");+ const byId = new Map(doc.nodes.map((n) => [n.id, n]));+ const files: { name: string; data: Uint8Array }[] = [];+ for (const { nodeId, file } of zipPlan(doc)) {+ const n = byId.get(nodeId)!;+ const rect = kind === "cropped" ? cropRect(n, doc) : ([0, 0, doc.width, doc.height] as Box);+ if (!rect) continue; // entirely off the canvas+ files.push({ name: file, data: await bytes(await renderDoc(doc, { rect, only: n.id })) });+ }+ files.push({ name: "composite.png", data: await bytes(await renderDoc(doc)) });+ save(new Blob([storedZip(files) as BlobPart], { type: "application/zip" }), kind === "cropped" ? "cropped-layers.zip" : "positioned-layers.zip");+ return files.length - 1;+}++export async function downloadPng(doc: LayerDoc, name: string): Promise<void> {+ save(await toBlob(await renderDoc(doc)), `${slugify(name) || "image"}.png`);+}++/** One layer as you see it (cropped to its box). */+export async function downloadLayer(doc: LayerDoc, node: LayerNode): Promise<void> {+ const rect = cropRect(node, doc);+ if (!rect) throw new Error("This layer is outside the canvas");+ save(await toBlob(await renderDoc(doc, { rect, only: node.id })), zipPlan(doc).find((e) => e.nodeId === node.id)?.file ?? "layer.png");+}++/** "16:9" for 1920×1080; a decimal ratio ("1.37:1") when the numbers don't reduce. */+export function ratioOf(w: number, h: number): string {+ const W = Math.round(w);+ const H = Math.round(h);+ const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);+ const g = gcd(W, H) || 1;+ const a = W / g;+ const b = H / g;+ return a <= 64 && b <= 64 ? `${a}:${b}` : `${(W / H).toFixed(2)}:1`;+}diff --git a/src/components/layers/stage.tsx b/src/components/layers/stage.tsxnew file mode 100644index 00000000..3c5c1935--- /dev/null+++ b/src/components/layers/stage.tsx@@ -0,0 +1,503 @@+"use client";++import { Brush, Eraser, Hand, Maximize, Minus, MousePointer2, Plus } from "lucide-react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { Slider } from "@/components/ui/slider";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { Kbd } from "@/components/ui/kbd";+import { resizeBox, rotationTo, toLocal, type Box, type Handle, type LayerDoc, type LayerNode } from "@/lib/layers";+import { cn } from "@/lib/utils";+import type { MaskEdit, StageMode } from "./editor-context";+import { drawNode, opaqueAt, type Sources } from "./render";++interface View {+ zoom: number;+ x: number;+ y: number;+}++type Drag =+ | { kind: "pan"; sx: number; sy: number; vx: number; vy: number }+ | { kind: "move"; id: string; px: number; py: number; node: LayerNode; moved: boolean }+ | { kind: "resize"; id: string; handle: Handle; px: number; py: number; node: LayerNode }+ | { kind: "rotate"; id: string; node: LayerNode }+ | { kind: "region"; px: number; py: number }+ | { kind: "frame"; handle: Handle | "move"; px: number; py: number; start: Box }+ | { kind: "paint"; last: [number, number] | null };++const HANDLES: Handle[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];+const HANDLE_POS: Record<Handle, [number, number]> = { nw: [0, 0], n: [0.5, 0], ne: [1, 0], e: [1, 0.5], se: [1, 1], s: [0.5, 1], sw: [0, 1], w: [0, 0.5] };+const HANDLE_CURSOR: Record<Handle, string> = { nw: "nwse-resize", se: "nwse-resize", ne: "nesw-resize", sw: "nesw-resize", n: "ns-resize", s: "ns-resize", e: "ew-resize", w: "ew-resize" };++const typing = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));++export interface StageProps {+ doc: LayerDoc;+ selectedId: string | null;+ onSelect: (id: string | null) => void;+ onCommit: (doc: LayerDoc) => void;+ mode: StageMode;+ setMode: (m: StageMode) => void;+ region: Box | null;+ setRegion: (r: Box | null) => void;+ frame: Box | null;+ setFrame: (r: Box | null) => void;+ mask: MaskEdit | null;+ onMaskChange: () => void;+ brushSize: number;+ setBrushSize: (n: number) => void;+ highlight: Box | null;+ sources: Sources;+ /** Extra layers drawn over the document without being part of it (a whole-image grade preview). */+ overlay?: LayerNode[];+ /** Layers a tool is working on, with what to say. */+ busy: Map<string, string>;+ readOnly?: boolean;+}++export function Stage(p: StageProps) {+ const { doc, selectedId, mode } = p;+ const box = useRef<HTMLDivElement>(null);+ const canvas = useRef<HTMLCanvasElement>(null);+ const [size, setSize] = useState({ w: 0, h: 0 });+ const [view, setView] = useState<View>({ zoom: 1, x: 0, y: 0 });+ const fitted = useRef("");+ const drag = useRef<Drag | null>(null);+ /** Geometry while a layer is dragged (committed on release). */+ const [live, setLive] = useState<LayerNode | null>(null);+ const [hover, setHover] = useState<string | null>(null);+ const [space, setSpace] = useState(false);+ const [pointer, setPointer] = useState<[number, number] | null>(null);+ const [tick, setTick] = useState(0);+ /** What the pointer is doing (render-safe copy of drag.current's kind). */+ const [dragKind, setDragKind] = useState<Drag["kind"] | null>(null);+ const redraw = useCallback(() => setTick((t) => t + 1), []);++ // Container size.+ useLayoutEffect(() => {+ const el = box.current;+ if (!el) return;+ const ro = new ResizeObserver(([e]) => setSize({ w: Math.round(e.contentRect.width), h: Math.round(e.contentRect.height) }));+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ const fit = useCallback(() => {+ if (!size.w || !size.h) return;+ const pad = size.w < 500 ? 24 : 56;+ const zoom = Math.min((size.w - pad * 2) / doc.width, (size.h - pad * 2) / doc.height, 4);+ setView({ zoom, x: (size.w - doc.width * zoom) / 2, y: (size.h - doc.height * zoom) / 2 });+ }, [size.w, size.h, doc.width, doc.height]);++ // Fit on first layout and whenever the canvas changes size (Expand & Crop).+ useEffect(() => {+ const key = `${doc.width}x${doc.height}|${size.w > 0}`;+ if (!size.w || fitted.current === key) return;+ fitted.current = key;+ fit();+ }, [doc.width, doc.height, size.w, fit]);++ const nodes = useMemo(() => {+ const list = [...doc.nodes].sort((a, b) => a.z - b.z).map((n) => (live && n.id === live.id ? live : n));+ return p.overlay?.length ? [...list, ...p.overlay] : list;+ }, [doc.nodes, live, p.overlay]);++ // Paint.+ useEffect(() => {+ const c = canvas.current;+ if (!c || !size.w) return;+ const dpr = window.devicePixelRatio || 1;+ const W = Math.round(size.w * dpr);+ const H = Math.round(size.h * dpr);+ if (c.width !== W || c.height !== H) {+ c.width = W;+ c.height = H;+ }+ const ctx = c.getContext("2d")!;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, W, H);+ ctx.setTransform(dpr * view.zoom, 0, 0, dpr * view.zoom, dpr * view.x, dpr * view.y);+ ctx.save();+ ctx.beginPath();+ ctx.rect(0, 0, doc.width, doc.height);+ ctx.clip();+ ctx.imageSmoothingQuality = "high";+ for (const n of nodes) if (!n.hidden) drawNode(ctx, n, dpr * view.zoom, p.sources, redraw);+ ctx.restore();+ }, [nodes, view, size, doc.width, doc.height, p.sources, redraw, tick]);++ // Wheel: pinch / ⌘-scroll zooms around the pointer, scrolling pans.+ useEffect(() => {+ const el = box.current;+ if (!el) return;+ const onWheel = (e: WheelEvent) => {+ e.preventDefault();+ const r = el.getBoundingClientRect();+ const mx = e.clientX - r.left;+ const my = e.clientY - r.top;+ setView((v) => {+ if (e.ctrlKey || e.metaKey) {+ const zoom = Math.min(16, Math.max(0.05, v.zoom * Math.exp(-e.deltaY * 0.01)));+ return { zoom, x: mx - ((mx - v.x) / v.zoom) * zoom, y: my - ((my - v.y) / v.zoom) * zoom };+ }+ return { ...v, x: v.x - e.deltaX, y: v.y - e.deltaY };+ });+ };+ el.addEventListener("wheel", onWheel, { passive: false });+ return () => el.removeEventListener("wheel", onWheel);+ }, []);++ // Space held = hand tool; zoom keys.+ const zoomBy = useCallback(+ (k: number) =>+ setView((v) => {+ const zoom = Math.min(16, Math.max(0.05, v.zoom * k));+ const cx = size.w / 2;+ const cy = size.h / 2;+ return { zoom, x: cx - ((cx - v.x) / v.zoom) * zoom, y: cy - ((cy - v.y) / v.zoom) * zoom };+ }),+ [size.w, size.h],+ );+ useEffect(() => {+ const down = (e: KeyboardEvent) => {+ if (typing(e.target) || e.metaKey || e.ctrlKey || e.altKey) return;+ if (e.code === "Space" && !e.repeat) {+ setSpace(true);+ e.preventDefault();+ } else if (e.key === "+" || e.key === "=") zoomBy(1.25);+ else if (e.key === "-") zoomBy(0.8);+ else if (e.key === "0") fit();+ };+ const up = (e: KeyboardEvent) => {+ if (e.code === "Space") setSpace(false);+ };+ window.addEventListener("keydown", down);+ window.addEventListener("keyup", up);+ return () => {+ window.removeEventListener("keydown", down);+ window.removeEventListener("keyup", up);+ };+ }, [zoomBy, fit]);++ const toDoc = (clientX: number, clientY: number): [number, number] => {+ const r = box.current!.getBoundingClientRect();+ return [(clientX - r.left - view.x) / view.zoom, (clientY - r.top - view.y) / view.zoom];+ };++ /** The topmost visible layer under a point, by its pixels (transparent parts let clicks through). */+ const hitTest = (px: number, py: number): LayerNode | undefined => {+ for (let i = nodes.length - 1; i >= 0; i--) {+ const n = nodes[i];+ if (n.hidden || n.id.startsWith("__")) continue;+ const uv = toLocal(n, px, py);+ if (uv && opaqueAt(n, uv[0], uv[1])) return n;+ }+ return undefined;+ };++ const paint = (px: number, py: number) => {+ const m = p.mask;+ const d = drag.current;+ if (!m || d?.kind !== "paint") return;+ const n = doc.nodes.find((x) => x.id === m.nodeId);+ if (!n) return;+ // Local coordinates may run past the edges; strokes there are simply clipped.+ const cx = n.x + n.w / 2;+ const cy = n.y + n.h / 2;+ const r = (-n.rotation * Math.PI) / 180;+ const lx = (px - cx) * Math.cos(r) - (py - cy) * Math.sin(r);+ const ly = (px - cx) * Math.sin(r) + (py - cy) * Math.cos(r);+ const x = (lx / n.w + 0.5) * m.canvas.width;+ const y = (ly / n.h + 0.5) * m.canvas.height;+ const ctx = m.canvas.getContext("2d")!;+ ctx.globalCompositeOperation = mode === "eraser" ? "destination-out" : "source-over";+ ctx.strokeStyle = "#fff";+ ctx.fillStyle = "#fff";+ ctx.lineCap = "round";+ ctx.lineJoin = "round";+ ctx.lineWidth = (p.brushSize * m.canvas.width) / n.w;+ ctx.beginPath();+ if (d.last) {+ ctx.moveTo(d.last[0], d.last[1]);+ ctx.lineTo(x, y);+ ctx.stroke();+ } else {+ ctx.arc(x, y, ctx.lineWidth / 2, 0, Math.PI * 2);+ ctx.fill();+ }+ ctx.globalCompositeOperation = "source-over";+ d.last = [x, y];+ p.onMaskChange();+ };++ const onPointerDown = (e: React.PointerEvent) => {+ if (e.button === 2) return;+ const [px, py] = toDoc(e.clientX, e.clientY);+ const panning = e.button === 1 || mode === "hand" || space || (p.readOnly && mode !== "region");+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);+ const begin = (d: Drag) => {+ drag.current = d;+ setDragKind(d.kind);+ };+ if (panning) {+ begin({ kind: "pan", sx: e.clientX, sy: e.clientY, vx: view.x, vy: view.y });+ return;+ }+ if ((mode === "brush" || mode === "eraser") && p.mask) {+ begin({ kind: "paint", last: null });+ paint(px, py);+ return;+ }+ if (mode === "region") {+ begin({ kind: "region", px, py });+ p.setRegion(null);+ return;+ }+ if (mode === "frame") return;+ const hit = hitTest(px, py);+ p.onSelect(hit?.id ?? null);+ if (hit && !p.readOnly) begin({ kind: "move", id: hit.id, px, py, node: hit, moved: false });+ };++ const startHandle = (e: React.PointerEvent, kind: "resize" | "rotate" | "move", handle?: Handle) => {+ e.stopPropagation();+ if (e.button !== 0 || p.readOnly) return;+ const node = nodes.find((n) => n.id === selectedId);+ if (!node) return;+ box.current!.setPointerCapture(e.pointerId);+ const [px, py] = toDoc(e.clientX, e.clientY);+ drag.current = kind === "rotate" ? { kind, id: node.id, node } : kind === "resize" ? { kind, id: node.id, handle: handle!, px, py, node } : { kind: "move", id: node.id, px, py, node, moved: false };+ setDragKind(drag.current.kind);+ };++ const startFrame = (e: React.PointerEvent, handle: Handle | "move") => {+ e.stopPropagation();+ if (e.button !== 0 || !p.frame) return;+ box.current!.setPointerCapture(e.pointerId);+ const [px, py] = toDoc(e.clientX, e.clientY);+ drag.current = { kind: "frame", handle, px, py, start: p.frame };+ setDragKind("frame");+ };++ const onPointerMove = (e: React.PointerEvent) => {+ const [px, py] = toDoc(e.clientX, e.clientY);+ setPointer([px, py]);+ const d = drag.current;+ if (!d) {+ if (mode === "select" && !space) setHover(hitTest(px, py)?.id ?? null);+ return;+ }+ switch (d.kind) {+ case "pan":+ setView((v) => ({ ...v, x: d.vx + e.clientX - d.sx, y: d.vy + e.clientY - d.sy }));+ break;+ case "paint":+ paint(px, py);+ break;+ case "move": {+ const dx = px - d.px;+ const dy = py - d.py;+ if (!d.moved && Math.hypot(dx * view.zoom, dy * view.zoom) < 3) return;+ d.moved = true;+ setLive({ ...d.node, x: d.node.x + dx, y: d.node.y + dy });+ break;+ }+ case "resize":+ setLive({ ...d.node, ...resizeBox(d.node, d.handle, px - d.px, py - d.py, e.shiftKey) });+ break;+ case "rotate":+ setLive({ ...d.node, rotation: rotationTo(d.node.x + d.node.w / 2, d.node.y + d.node.h / 2, px, py, e.shiftKey) });+ break;+ case "region": {+ const x0 = Math.max(0, Math.min(doc.width, Math.min(d.px, px)));+ const y0 = Math.max(0, Math.min(doc.height, Math.min(d.py, py)));+ const x1 = Math.max(0, Math.min(doc.width, Math.max(d.px, px)));+ const y1 = Math.max(0, Math.min(doc.height, Math.max(d.py, py)));+ p.setRegion(x1 - x0 >= 2 && y1 - y0 >= 2 ? [Math.round(x0), Math.round(y0), Math.round(x1 - x0), Math.round(y1 - y0)] : null);+ break;+ }+ case "frame": {+ const [x, y, w, h] = d.start;+ const dx = px - d.px;+ const dy = py - d.py;+ if (d.handle === "move") p.setFrame([Math.round(x + dx), Math.round(y + dy), w, h]);+ else {+ const r = resizeBox({ x, y, w, h, rotation: 0 }, d.handle, dx, dy, true);+ p.setFrame([Math.round(r.x), Math.round(r.y), Math.max(8, Math.round(r.w)), Math.max(8, Math.round(r.h))]);+ }+ break;+ }+ }+ };++ const onPointerUp = () => {+ const d = drag.current;+ drag.current = null;+ setDragKind(null);+ if (!d) return;+ if ((d.kind === "move" && d.moved) || d.kind === "resize" || d.kind === "rotate") {+ const n = live;+ setLive(null);+ if (n && n.id === d.id) {+ const g = { x: n.x, y: n.y, w: n.w, h: n.h, rotation: n.rotation };+ p.onCommit({ ...doc, nodes: doc.nodes.map((x) => (x.id === n.id ? { ...x, ...g } : x)) });+ }+ }+ if (d.kind === "region" && p.region && (p.region[2] < 8 || p.region[3] < 8)) p.setRegion(null);+ };++ const sel = nodes.find((n) => n.id === selectedId && !n.hidden);+ const hov = hover && hover !== selectedId ? nodes.find((n) => n.id === hover) : undefined;+ const at = (b: Box | Pick<LayerNode, "x" | "y" | "w" | "h">) => {+ const [x, y, w, h] = Array.isArray(b) ? b : [b.x, b.y, b.w, b.h];+ return { left: view.x + x * view.zoom, top: view.y + y * view.zoom, width: w * view.zoom, height: h * view.zoom };+ };+ const cursor = space || mode === "hand" ? (dragKind === "pan" ? "grabbing" : "grab") : mode === "region" ? "crosshair" : mode === "brush" || mode === "eraser" ? "none" : undefined;+ const maskNode = p.mask ? doc.nodes.find((n) => n.id === p.mask!.nodeId) : undefined;++ return (+ <div className="relative min-h-0 min-w-0 flex-1 overflow-hidden bg-muted/40" style={{ cursor }}>+ <div+ ref={box}+ className="absolute inset-0 touch-none select-none"+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerUp}+ onPointerLeave={() => {+ setHover(null);+ setPointer(null);+ }}+ >+ <div className="checkerboard absolute shadow-soft" style={at([0, 0, doc.width, doc.height])} />+ <canvas ref={canvas} className="absolute inset-0 size-full" role="img" aria-label={`Canvas, ${doc.nodes.length} layer${doc.nodes.length === 1 ? "" : "s"}`} />++ {/* Layers a tool is working on. */}+ {[...p.busy].map(([id, text]) => {+ const n = nodes.find((x) => x.id === id);+ if (!n) return null;+ return (+ <div key={id} className="pointer-events-none absolute" style={{ ...at(n), transform: `rotate(${n.rotation}deg)` }}>+ <div className="absolute inset-0 animate-pulse rounded-sm border-2 border-dashed border-primary bg-primary/10" />+ <span className="absolute top-1 left-1 max-w-[calc(100%-8px)] truncate rounded-full bg-background/90 px-2 py-0.5 text-[11px] font-medium shadow-soft">{text}</span>+ </div>+ );+ })}++ {hov && mode === "select" && !dragKind && (+ <div className="pointer-events-none absolute border border-primary/70" style={{ ...at(hov), transform: `rotate(${hov.rotation}deg)` }} />+ )}++ {sel && mode === "select" && !p.readOnly && (+ <div className="absolute border-[1.5px] border-primary" style={{ ...at(sel), transform: `rotate(${sel.rotation}deg)` }}>+ <div className="absolute inset-0 cursor-move" onPointerDown={(e) => startHandle(e, "move")} aria-hidden />+ <button+ type="button"+ aria-label="Rotate layer"+ title="Rotate layer (Shift snaps to 15°)"+ className="absolute -top-7 left-1/2 size-4 -translate-x-1/2 cursor-grab rounded-full border-[1.5px] border-primary bg-background shadow-soft"+ onPointerDown={(e) => startHandle(e, "rotate")}+ />+ <span className="pointer-events-none absolute -top-3 left-1/2 h-3 w-px -translate-x-1/2 bg-primary" />+ {HANDLES.map((h) => (+ <span+ key={h}+ aria-hidden+ onPointerDown={(e) => startHandle(e, "resize", h)}+ className="absolute size-2.5 -translate-1/2 rounded-[3px] border-[1.5px] border-primary bg-background"+ style={{ left: `${HANDLE_POS[h][0] * 100}%`, top: `${HANDLE_POS[h][1] * 100}%`, cursor: HANDLE_CURSOR[h] }}+ />+ ))}+ </div>+ )}++ {p.highlight && <div className="pointer-events-none absolute rounded-sm ring-2 ring-primary ring-offset-1 ring-offset-transparent" style={at(p.highlight)} />}++ {p.region && (+ <div className="pointer-events-none absolute border-2 border-dashed border-primary bg-primary/10 shadow-[0_0_0_9999px_rgb(0_0_0/0.35)]" style={at(p.region)}>+ <span className="absolute -top-6 left-0 rounded-full bg-primary px-2 py-0.5 font-mono text-[11px] text-primary-foreground">+ {p.region[2]} × {p.region[3]}+ </span>+ </div>+ )}++ {mode === "frame" && p.frame && (+ <div className="absolute border-2 border-primary shadow-[0_0_0_9999px_rgb(0_0_0/0.35)]" style={at(p.frame)}>+ <div className="absolute inset-0 cursor-move" onPointerDown={(e) => startFrame(e, "move")} aria-hidden />+ <span className="pointer-events-none absolute -top-6 left-0 rounded-full bg-primary px-2 py-0.5 font-mono text-[11px] text-primary-foreground">+ {p.frame[2]} × {p.frame[3]}+ </span>+ {HANDLES.map((h) => (+ <span+ key={h}+ aria-hidden+ onPointerDown={(e) => startFrame(e, h)}+ className="absolute size-3 -translate-1/2 rounded-[3px] border-2 border-primary bg-background"+ style={{ left: `${HANDLE_POS[h][0] * 100}%`, top: `${HANDLE_POS[h][1] * 100}%`, cursor: HANDLE_CURSOR[h] }}+ />+ ))}+ </div>+ )}++ {maskNode && (mode === "brush" || mode === "eraser") && (+ <div className="pointer-events-none absolute border border-dashed border-primary" style={{ ...at(maskNode), transform: `rotate(${maskNode.rotation}deg)` }} />+ )}+ {pointer && (mode === "brush" || mode === "eraser") && p.mask && (+ <div+ className="pointer-events-none absolute rounded-full border-2 border-white mix-blend-difference"+ style={{ left: view.x + pointer[0] * view.zoom - (p.brushSize * view.zoom) / 2, top: view.y + pointer[1] * view.zoom - (p.brushSize * view.zoom) / 2, width: p.brushSize * view.zoom, height: p.brushSize * view.zoom }}+ />+ )}+ </div>++ {/* Canvas tools */}+ <div className="absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-0.5 rounded-full border bg-background/95 p-1 shadow-normal backdrop-blur">+ {!p.readOnly && (+ <>+ <ModeButton icon={MousePointer2} label="Select and move" k="V" active={mode === "select"} onClick={() => p.setMode("select")} />+ <ModeButton icon={Hand} label="Pan" k="H" active={mode === "hand"} onClick={() => p.setMode("hand")} />+ <ModeButton icon={Brush} label={selectedId ? "Brush: paint the mask back" : "Brush (pick a layer first)"} k="B" active={mode === "brush"} disabled={!selectedId} onClick={() => p.setMode("brush")} />+ <ModeButton icon={Eraser} label={selectedId ? "Eraser: hide parts of the layer" : "Eraser (pick a layer first)"} k="E" active={mode === "eraser"} disabled={!selectedId} onClick={() => p.setMode("eraser")} />+ {(mode === "brush" || mode === "eraser") && (+ <div className="flex w-32 items-center gap-2 px-2">+ <Slider aria-label="Brush size" min={4} max={Math.max(64, Math.round(Math.max(doc.width, doc.height) / 6))} step={1} value={[p.brushSize]} onValueChange={([v]) => p.setBrushSize(v)} />+ </div>+ )}+ <span className="mx-1 h-5 w-px bg-border" />+ </>+ )}+ <ModeButton icon={Minus} label="Zoom out" k="−" onClick={() => zoomBy(0.8)} />+ <button type="button" onClick={fit} className="h-8 min-w-12 rounded-full px-1.5 font-mono text-[12px] text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Fit to screen">+ {Math.round(view.zoom * 100)}%+ </button>+ <ModeButton icon={Plus} label="Zoom in" k="+" onClick={() => zoomBy(1.25)} />+ <ModeButton icon={Maximize} label="Fit to screen" k="0" onClick={fit} />+ </div>+ </div>+ );+}++function ModeButton({ icon: Icon, label, k, active, disabled, onClick }: { icon: typeof Hand; label: string; k?: string; active?: boolean; disabled?: boolean; onClick: () => void }) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={label}+ aria-pressed={active}+ disabled={disabled}+ onClick={onClick}+ className={cn(+ "grid size-8 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent",+ active && "bg-brand-faint text-brand-text hover:bg-brand-faint-hover",+ )}+ >+ <Icon className="size-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>+ {label} {k && <Kbd>{k}</Kbd>}+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsxnew file mode 100644index 00000000..3ac73ac7--- /dev/null+++ b/src/components/layers/tools.tsx@@ -0,0 +1,1117 @@+"use client";++import {+ ArrowLeft,+ Crop,+ Layers,+ Loader2,+ Plus,+ RefreshCw,+ Rotate3d,+ Scissors,+ SlidersHorizontal,+ SquareDashedMousePointer,+ Sun,+ TriangleAlert,+ Type,+ Wand2,+ X,+ ZoomIn,+} from "lucide-react";+import { nanoid } from "nanoid";+import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Progress } from "@/components/ui/progress";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Slider } from "@/components/ui/slider";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { applyPreset, CONTROLS, isNeutral, NEUTRAL, PRESETS, type Grade } from "@/lib/grade";+import {+ addNodes,+ addRevision,+ ANGLES,+ clampLayers,+ DECOMPOSE_COPY,+ decomposeCost,+ expandPads,+ getNode,+ jobStatusText,+ LAYER_PRICES,+ reframeDoc,+ RELIGHT_DIRECTIONS,+ RELIGHT_LIGHTS,+ replaceNodes,+ STALL_MS,+ textBlocksFrom,+ textChanges,+ textJobTitle,+ TOOL_MODELS,+ type Box,+ type LayerJob,+ type LayerJobInput,+ type LayerNode,+ type LayerTool,+ type TextBlock,+} from "@/lib/layers";+import { cn } from "@/lib/utils";+import { Field, Segmented } from "./bits";+import { costLabel, isFailed, isRunning, latestJob, modelsFor, useEditor, type Target, type ToolId } from "./editor-context";+import { LayerGrader } from "./grade-gl";+import { LayerThumb } from "./layers-panel";+import { loadImage, ratioOf, renderDoc, renderNative, sizeOf, uploadRender } from "./render";++export const TOOLS: { id: ToolId; label: string; icon: typeof Layers; isNew?: boolean; hint: string }[] = [+ { id: "decompose", label: "Layer Decomposition", icon: Layers, isNew: true, hint: "Split the image into editable layers" },+ { id: "edit-text", label: "Edit text", icon: Type, isNew: true, hint: "Rewrite the words, keep the design" },+ { id: "remove-bg", label: "Remove background", icon: Scissors, hint: "Keep the subject on transparency" },+ { id: "regional", label: "Regional editing", icon: SquareDashedMousePointer, hint: "Draw a box and describe the change" },+ { id: "upscale", label: "Upscale", icon: ZoomIn, hint: "More pixels, sharper detail" },+ { id: "relight", label: "Relight", icon: Sun, hint: "New light on a layer or the picture" },+ { id: "angles", label: "Angles", icon: Rotate3d, hint: "See it from another camera angle" },+ { id: "expand", label: "Expand & Crop", icon: Crop, isNew: true, hint: "Resize the canvas, fill it with AI" },+ { id: "grade", label: "Color grading", icon: SlidersHorizontal, hint: "Film looks and colour, in your browser" },+];++// ---------------------------------------------------------------------------+// Shared pieces++/** What a tool works on: the selected layer, else the whole image. */+function useTarget(): { target: Target; node?: LayerNode } {+ const { selected } = useEditor();+ return selected ? { target: { kind: "node", node: selected }, node: selected } : { target: { kind: "whole" } };+}++function Scope({ node }: { node?: LayerNode }) {+ const { select } = useEditor();+ return (+ <div className="flex items-center gap-2 rounded-lg bg-muted/70 px-2.5 py-2 text-[12px]">+ {node ? <LayerThumb node={node} className="size-8" /> : <Layers className="size-4 text-muted-foreground" />}+ <div className="min-w-0 flex-1">+ <p className="truncate font-medium">{node ? node.name : "The whole image"}</p>+ <p className="truncate text-muted-foreground">{node ? "Deselect the layer to use this tool on the whole image" : "Select a layer to work on it alone"}</p>+ </div>+ {node && (+ <Button size="icon-xs" variant="ghost" aria-label="Use the whole image" onClick={() => select(null)}>+ <X />+ </Button>+ )}+ </div>+ );+}++function ModelSelect({ tool, value, onChange }: { tool: LayerTool; value?: string; onChange: (id: string) => void }) {+ const { engine, models } = useEditor();+ const options = modelsFor(models, TOOL_MODELS[tool][engine]);+ if (options.length < 2) return options[0] ? <p className="text-[12px] text-muted-foreground">Model · {options[0].name}</p> : null;+ return (+ <Field label="Model">+ <Select value={value ?? options[0].id} onValueChange={onChange}>+ <SelectTrigger className="h-9 w-full rounded-lg" aria-label="Model">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {options.map((m) => (+ <SelectItem key={m.id} value={m.id}>+ {m.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ );+}++/** The model the tool will run (picked, or the engine's default). */+function useToolModel(tool: LayerTool) {+ const { engine, models } = useEditor();+ const [picked, setPicked] = useState<string | undefined>();+ const options = TOOL_MODELS[tool][engine];+ const id = picked && options.includes(picked) ? picked : options[0];+ return { modelId: id, model: id ? models[id] : undefined, setModelId: setPicked };+}++/** A running or failed job of this tool on this target. */+function JobState({ job, onRetry, failedTitle = "That didn't work" }: { job?: LayerJob; onRetry?: () => void; failedTitle?: string }) {+ const { endJob } = useEditor();+ if (!job || job.state !== "pending") return null;+ if (isRunning(job)) {+ const p = job.result?.progress;+ return (+ <div className="space-y-2 rounded-lg bg-muted px-3 py-2.5" role="status">+ <div className="flex items-center gap-2 text-[12px]">+ <Loader2 className="size-3.5 animate-spin text-brand-text" />+ <span className="min-w-0 flex-1 truncate font-medium">{job.label}</span>+ <button type="button" className="text-muted-foreground hover:text-foreground hover:underline" onClick={() => endJob(job.id, "cancel")}>+ Cancel+ </button>+ </div>+ <Progress value={p ? p * 100 : 8} className="h-1" aria-label="Progress" />+ <p className="text-[11px] text-muted-foreground">{jobStatusText(job.result)}</p>+ </div>+ );+ }+ if (isFailed(job)) {+ return (+ <div role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-[12px]">+ <p className="flex items-center gap-1.5 font-medium text-destructive">+ <TriangleAlert className="size-3.5" /> {failedTitle}+ </p>+ <p className="mt-0.5 text-muted-foreground">{job.result?.error ?? "The model didn't finish."}</p>+ <div className="mt-2 flex gap-3">+ {onRetry && (+ <button type="button" className="font-medium text-brand-text hover:underline" onClick={onRetry}>+ Try again+ </button>+ )}+ <button type="button" className="text-muted-foreground hover:underline" onClick={() => endJob(job.id, "dismiss")}>+ Dismiss+ </button>+ </div>+ </div>+ );+ }+ return (+ <div className="flex items-center gap-2 rounded-lg bg-muted px-3 py-2 text-[12px]" role="status">+ <Loader2 className="size-3.5 animate-spin" /> Adding the result to your layers…+ </div>+ );+}++function RunRow({ cost, busy, disabled, onClick, children }: { cost: string; busy: boolean; disabled?: boolean; onClick: () => void; children: React.ReactNode }) {+ return (+ <div className="flex items-center justify-between gap-2 pt-1">+ <span className="font-mono text-[12px] text-muted-foreground">{cost}</span>+ <Button className="rounded-full" onClick={onClick} disabled={busy || disabled}>+ {busy && <Loader2 className="animate-spin" />}+ {children}+ </Button>+ </div>+ );+}++function KeepAlpha({ node, value, onChange }: { node?: LayerNode; value: boolean; onChange: (v: boolean) => void }) {+ if (!node) return null;+ return (+ <label className="flex items-center justify-between gap-2 text-[12px] text-muted-foreground">+ Keep transparency (cut the background back out)+ <Switch checked={value} onCheckedChange={onChange} aria-label="Keep transparency" />+ </label>+ );+}++function HowItWorks({ children }: { children: React.ReactNode }) {+ return (+ <div className="rounded-lg border bg-card px-3 py-2.5">+ <p className="text-[12px] font-medium">How it works</p>+ <p className="mt-0.5 text-[12px] text-pretty text-muted-foreground">{children}</p>+ </div>+ );+}++/** Run a tool with a busy flag (rendering and uploading the picture can take a moment). */+function useRun() {+ const { run } = useEditor();+ const [busy, setBusy] = useState(false);+ return {+ busy,+ go: async (input: Parameters<typeof run>[0]) => {+ setBusy(true);+ try {+ return await run(input);+ } finally {+ setBusy(false);+ }+ },+ };+}++// ---------------------------------------------------------------------------+// Layer Decomposition (and Separate layer)++function DecomposeTool() {+ const { doc, engine, isDemo, jobs, splitTarget, setSplitTarget, selected, endJob } = useEditor();+ // Separate layer: picked from a layer's menu, or with the button below once the image is decomposed.+ const splitNode = getNode(doc, splitTarget);+ const tool: LayerTool = splitNode ? "split" : "decompose";+ const { modelId, model, setModelId } = useToolModel(tool);+ const [resolution, setResolution] = useState<"1K" | "1.5K" | "2K">("1K");+ const [mode, setMode] = useState<"standard" | "fast">("standard");+ const [layers, setLayers] = useState(8);+ const [prompt, setPrompt] = useState("");+ const { busy, go } = useRun();+ const [phase, setPhase] = useState<"setting-up" | "submitting" | null>(null);+ const job = splitNode ? latestJob(jobs, ["split"], splitNode.id) : latestJob(jobs, ["decompose"]);+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!job || !isRunning(job)) return;+ const t = setInterval(() => setNow(Date.now()), 5000);+ return () => clearInterval(t);+ }, [job]);++ const max = LAYER_PRICES[modelId ?? ""]?.maxLayers ?? 10;+ const n = clampLayers(modelId ?? "", Math.min(layers, max));+ const hasRes = !!modelId && (modelId.startsWith("seedream") || modelId.startsWith("oss-"));+ const hasMode = modelId === "seedream-5-layers" || !!modelId?.startsWith("oss-");+ const usd = decomposeCost(modelId ?? "", n, resolution);+ const cost = costLabel(model, isDemo(model), usd);++ const start = async () => {+ setPhase("setting-up");+ setTimeout(() => setPhase((p) => (p ? "submitting" : p)), 300);+ const target: Target = splitNode ? { kind: "node", node: splitNode } : { kind: "whole" };+ await go({+ tool,+ target,+ modelId,+ prompt: prompt.trim() || undefined,+ settings: { resolution, mode, layers: n },+ label: splitNode ? `Separating ${splitNode.name}` : "Layer decomposition",+ });+ setPhase(null);+ };++ const state: keyof typeof DECOMPOSE_COPY | null = phase+ ? phase+ : job?.state === "pending"+ ? isRunning(job)+ ? job.result?.status === "queued" && now - job.createdAt > STALL_MS+ ? "stalled"+ : "processing"+ : isFailed(job)+ ? "failed"+ : "ready"+ : !splitNode && doc.decomposed+ ? "decomposed"+ : null;++ if (state && state !== "decomposed") {+ const [title, body] = DECOMPOSE_COPY[state];+ return (+ <div className="space-y-3" role="status" aria-live="polite">+ <div className="rounded-xl border bg-card p-4 text-center">+ {state === "failed" || state === "stalled" ? <TriangleAlert className="mx-auto size-5 text-warning" /> : <Loader2 className="mx-auto size-5 animate-spin text-brand-text" />}+ <p className="mt-2 font-heading text-[19px] leading-snug">{splitNode && state === "processing" ? `Separating ${splitNode.name}` : title}</p>+ <p className="mt-1 text-[12px] text-pretty text-muted-foreground">{state === "failed" ? (job?.result?.error ?? body) : body}</p>+ {state === "processing" && job?.result?.progress ? <Progress value={job.result.progress * 100} className="mt-3 h-1" aria-label="Progress" /> : null}+ {(state === "processing" || state === "stalled") && <p className="mt-2 text-[11px] text-subtle-foreground">{jobStatusText(job?.result)}</p>}+ </div>+ {state === "failed" && job && (+ <div className="flex gap-2">+ <Button variant="outline" className="flex-1 rounded-full" onClick={() => endJob(job.id, "dismiss")}>+ Back to settings+ </Button>+ <Button+ className="flex-1 rounded-full"+ onClick={() => {+ endJob(job.id, "dismiss");+ void start();+ }}+ >+ Try again+ </Button>+ </div>+ )}+ {(state === "processing" || state === "stalled") && job && (+ <Button variant="ghost" className="w-full" onClick={() => endJob(job.id, "cancel")}>+ Cancel+ </Button>+ )}+ </div>+ );+ }++ if (!splitNode && doc.decomposed) {+ const [title, body] = DECOMPOSE_COPY.decomposed;+ return (+ <div className="space-y-3">+ <div className="rounded-xl border bg-card p-4">+ <p className="font-heading text-[19px]">{title}</p>+ <p className="mt-1 text-[12px] text-pretty text-muted-foreground">{body.replace("#", String(doc.nodes.length))}</p>+ </div>+ <p className="text-[12px] text-muted-foreground">An image can only be decomposed once. Select a layer to separate it further, with an optional description of what to pull out.</p>+ {selected && (+ <Button variant="secondary" className="w-full rounded-full" onClick={() => setSplitTarget(selected.id)}>+ <Layers /> <span className="truncate">Separate {selected.name}</span>+ </Button>+ )}+ </div>+ );+ }++ return (+ <div className="space-y-4">+ {splitNode ? (+ <div className="space-y-2">+ <div className="flex items-center gap-2 rounded-lg bg-muted/70 px-2.5 py-2 text-[12px]">+ <LayerThumb node={splitNode} className="size-8" />+ <p className="min-w-0 flex-1 truncate">+ Separate <span className="font-medium">{splitNode.name}</span> into more layers+ </p>+ {splitTarget && (+ <Button size="icon-xs" variant="ghost" aria-label="Stop separating this layer" onClick={() => setSplitTarget(null)}>+ <X />+ </Button>+ )}+ </div>+ <Field label="What to pull out (optional)" htmlFor="split-prompt">+ <Input id="split-prompt" value={prompt} onChange={(e) => setPrompt(e.target.value)} maxLength={200} placeholder="e.g. “the guitar”" className="h-9" />+ </Field>+ {engine === "open" && prompt.trim() && <p className="text-[11px] text-muted-foreground">A named element runs on Qwen-Image-Layered Control.</p>}+ </div>+ ) : (+ <p className="text-[12px] text-pretty text-muted-foreground">Break the image into clean, editable layers — subject, background and details. An image can only be decomposed once; you can separate any layer again later.</p>+ )}+ <ModelSelect tool={tool} value={modelId} onChange={setModelId} />+ {hasRes && (+ <Field label="Resolution">+ <Segmented+ label="Resolution"+ value={resolution}+ onChange={setResolution}+ options={[+ ["1K", "1K"],+ ["1.5K", "1.5K"],+ ["2K", "2K"],+ ]}+ />+ </Field>+ )}+ {hasMode && (+ <Field label="Mode">+ <Segmented+ label="Mode"+ value={mode}+ onChange={setMode}+ options={[+ ["standard", "Standard"],+ ["fast", "Fast"],+ ]}+ />+ </Field>+ )}+ <Field label="Layers" hint={modelId?.startsWith("seedream") ? `up to ${n}` : n}>+ <Slider aria-label="Layers" min={modelId === "oss-qwen-layered-control" ? 2 : 3} max={Math.max(3, max)} step={1} value={[n]} onValueChange={([v]) => setLayers(v)} />+ </Field>+ {modelId?.startsWith("seedream") && <p className="text-[11px] text-subtle-foreground">Seedream decides the final count (up to 16) and names each layer.</p>}+ {!model && <p className="text-[12px] text-muted-foreground">No {engine === "open" ? "open-source" : "cloud"} model can split layers yet.</p>}+ <RunRow cost={cost} busy={busy} disabled={!model} onClick={() => void start()}>+ <Layers /> {splitNode ? "Separate layer" : "Separate layers"}+ </RunRow>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Edit text++function EditTextTool() {+ const { engine, models, isDemo, jobs, setHighlight, endJob } = useEditor();+ const { target, node } = useTarget();+ const scopeId = node?.id ?? null;+ const detect = latestJob(jobs, ["text-detect"], scopeId);+ const editJob = latestJob(jobs, ["text-edit"], scopeId);+ const { modelId, model, setModelId } = useToolModel("text-edit");+ const detectModel = models[TOOL_MODELS["text-detect"].cloud[0]];+ const { busy, go } = useRun();+ const [rows, setRows] = useState<{ from: string; to: string; box: Box | null }[]>([]);+ const [restored, setRestored] = useState(false);+ const loadedFor = useRef<string | null>(null);++ // Rows from the newest finished detection (boxes measured on its image, placed in its frame).+ useEffect(() => {+ if (!detect || detect.result?.status !== "succeeded" || loadedFor.current === detect.id) return;+ loadedFor.current = detect.id;+ const out = detect.result.outputs[0];+ if (!out) return;+ let gone = false;+ void loadImage(out.url)+ .then((img) => sizeOf(img))+ .catch(() => undefined)+ .then((natural) => {+ if (gone) return;+ const blocks: TextBlock[] = textBlocksFrom(out.meta, natural);+ const f = detect.frame;+ setRows(blocks.map((b) => ({ from: b.text, to: b.text, box: b.box ? [f[0] + b.box[0] * f[2], f[1] + b.box[1] * f[3], b.box[2] * f[2], b.box[3] * f[3]] : null })));+ setRestored(detect.state === "applied");+ if (detect.state === "pending") endJob(detect.id, "applied");+ });+ return () => {+ gone = true;+ };+ }, [detect, endJob]);+ useEffect(() => () => setHighlight(null), [setHighlight]);++ const changes = textChanges(rows);+ const detecting = detect && isRunning(detect);+ const startDetect = () => {+ loadedFor.current = null;+ setRestored(false);+ void go({ tool: "text-detect", target, label: "Detect text" });+ };+ const generate = () =>+ void go({ tool: "text-edit", target, modelId, settings: { rows: changes.map(({ from, to }) => ({ from, to })), keepAlpha: !!node && node.z > 0 }, label: textJobTitle(changes) });++ return (+ <div className="space-y-4">+ <Scope node={node} />+ <HowItWorks>Edit text finds the text on your image and lists it here. Change any line, then generate a new image with your wording in the original design.</HowItWorks>+ {engine === "cloud" ? (+ !rows.length && (+ <div className="space-y-2">+ <Button variant="secondary" className="w-full rounded-full" onClick={startDetect} disabled={busy || !!detecting}>+ {detecting ? <Loader2 className="animate-spin" /> : <Type />} {detecting ? "Reading the text…" : "Detect text"}+ </Button>+ <p className="text-center font-mono text-[11px] text-subtle-foreground">{costLabel(detectModel, isDemo(detectModel))}</p>+ {detect?.result?.status === "succeeded" && !rows.length && <p className="text-center text-[12px] text-muted-foreground">No text was found on this image.</p>}+ {detect && isFailed(detect) && <JobState job={detect} failedTitle="Could not read the text on this image." onRetry={startDetect} />}+ </div>+ )+ ) : (+ <p className="rounded-lg bg-muted/70 px-3 py-2 text-[12px] text-muted-foreground">Text detection runs on the cloud engine (Ideogram). On open source, type each line you want to change.</p>+ )}+ {restored && rows.length > 0 && <p className="text-[11px] text-muted-foreground">Restored from your last detection — the image may have changed since. Re-detect if the regions look off.</p>}+ {(rows.length > 0 || engine === "open") && (+ <ol className="space-y-2" aria-label="Text on the image">+ {rows.map((r, i) => (+ <li key={i} className="flex items-start gap-2" onPointerEnter={() => setHighlight(r.box)} onPointerLeave={() => setHighlight(null)} onFocus={() => setHighlight(r.box)} onBlur={() => setHighlight(null)}>+ <span className="mt-2 w-4 shrink-0 text-right font-mono text-[11px] text-subtle-foreground">{i + 1}</span>+ <div className="min-w-0 flex-1 space-y-1">+ {engine === "open" && !r.box ? (+ <Input value={r.from} onChange={(e) => setRows(rows.map((x, j) => (j === i ? { ...x, from: e.target.value } : x)))} placeholder="Text on the image now" aria-label={`Text region ${i + 1}: current text`} className="h-8 text-[13px]" />+ ) : (+ <p className="truncate text-[11px] text-muted-foreground" title={r.from}>+ {r.from}+ </p>+ )}+ <Input+ value={r.to}+ onChange={(e) => setRows(rows.map((x, j) => (j === i ? { ...x, to: e.target.value } : x)))}+ placeholder="Remove this text"+ aria-label={`Text region ${i + 1}`}+ className={cn("h-8 text-[13px]", r.to.trim() !== r.from.trim() && "border-primary")}+ />+ </div>+ {engine === "open" && (+ <Button size="icon-xs" variant="ghost" className="mt-1" aria-label={`Remove row ${i + 1}`} onClick={() => setRows(rows.filter((_, j) => j !== i))}>+ <X />+ </Button>+ )}+ </li>+ ))}+ {engine === "open" && (+ <li>+ <Button size="sm" variant="ghost" className="rounded-full" onClick={() => setRows([...rows, { from: "", to: "", box: null }])}>+ <Plus /> Add a line+ </Button>+ </li>+ )}+ </ol>+ )}+ {(rows.length > 0 || engine === "open") && (+ <>+ <ModelSelect tool="text-edit" value={modelId} onChange={setModelId} />+ <JobState job={editJob} failedTitle="Failed to apply the text changes" onRetry={generate} />+ <div className="flex items-center gap-2">+ {engine === "cloud" && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="icon" aria-label="Detect text again" onClick={startDetect} disabled={busy || !!detecting}>+ <RefreshCw />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Detect again · {costLabel(detectModel, isDemo(detectModel))}</TooltipContent>+ </Tooltip>+ )}+ <div className="flex-1">+ <RunRow cost={costLabel(model, isDemo(model))} busy={busy} disabled={!changes.length || (editJob && isRunning(editJob))} onClick={generate}>+ <Wand2 /> Generate+ </RunRow>+ </div>+ </div>+ {!changes.length && <p className="text-[11px] text-subtle-foreground">Change a line (or empty it to remove that text), then Generate.</p>}+ </>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Remove background, Upscale, Relight, Angles++function SimpleTool({ tool, verb, failedTitle, children, settings, prompt, disabled }: { tool: LayerTool; verb: string; failedTitle: string; children?: React.ReactNode; settings?: LayerJobInput["settings"]; prompt?: string; disabled?: boolean }) {+ const { jobs, isDemo } = useEditor();+ const { target, node } = useTarget();+ const { modelId, model, setModelId } = useToolModel(tool);+ const { busy, go } = useRun();+ const job = latestJob(jobs, [tool], node?.id ?? null);+ const run = () => void go({ tool, target, modelId, prompt, settings, label: verb });+ return (+ <div className="space-y-4">+ <Scope node={node} />+ {children}+ <ModelSelect tool={tool} value={modelId} onChange={setModelId} />+ <JobState job={job} failedTitle={failedTitle} onRetry={run} />+ <RunRow cost={costLabel(model, isDemo(model))} busy={busy} disabled={disabled || !model || (!!job && isRunning(job))} onClick={run}>+ {verb}+ </RunRow>+ </div>+ );+}++function RelightTool() {+ const { selected } = useEditor();+ const [light, setLight] = useState(RELIGHT_LIGHTS[0][0]);+ const [direction, setDirection] = useState(RELIGHT_DIRECTIONS[0][0]);+ const [extra, setExtra] = useState("");+ const [keepAlpha, setKeepAlpha] = useState(!!selected && selected.z > 0);+ return (+ <SimpleTool tool="relight" verb="Relight" failedTitle="Couldn't relight it" settings={{ light, direction, keepAlpha: !!selected && keepAlpha }} prompt={extra.trim() || undefined}>+ <Field label="Lighting">+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Lighting">+ {RELIGHT_LIGHTS.map(([l]) => (+ <Chip key={l} active={light === l} onClick={() => setLight(l)}>+ {l}+ </Chip>+ ))}+ </div>+ </Field>+ <Field label="Direction">+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Direction">+ {RELIGHT_DIRECTIONS.map(([d]) => (+ <Chip key={d} active={direction === d} onClick={() => setDirection(d)}>+ {d}+ </Chip>+ ))}+ </div>+ </Field>+ <Field label="Anything else (optional)" htmlFor="relight-extra">+ <Input id="relight-extra" value={extra} onChange={(e) => setExtra(e.target.value)} maxLength={300} placeholder="e.g. “a soft blue fill from the right”" className="h-9" />+ </Field>+ <KeepAlpha node={selected} value={keepAlpha} onChange={setKeepAlpha} />+ </SimpleTool>+ );+}++function AnglesTool() {+ const { selected, engine } = useEditor();+ const { modelId } = useToolModel("angles");+ const [rotate, setRotate] = useState(45);+ const [tilt, setTilt] = useState(0);+ const [zoom, setZoom] = useState(5);+ const [angle, setAngle] = useState(ANGLES[0][0]);+ const [keepAlpha, setKeepAlpha] = useState(!!selected && selected.z > 0);+ const sliders = modelId === "qwen-multiple-angles" && engine === "cloud";+ return (+ <SimpleTool tool="angles" verb="New angle" failedTitle="Couldn't make the new angle" settings={{ rotate, tilt, zoom, angle, keepAlpha: !!selected && keepAlpha }}>+ {sliders ? (+ <>+ <Field label="Rotate" hint={`${rotate}°`}>+ <Slider aria-label="Rotate" min={0} max={360} step={1} value={[rotate]} onValueChange={([v]) => setRotate(v)} />+ </Field>+ <Field label="Tilt" hint={`${tilt}°`}>+ <Slider aria-label="Tilt" min={-30} max={90} step={1} value={[tilt]} onValueChange={([v]) => setTilt(v)} />+ </Field>+ <Field label="Zoom" hint={zoom}>+ <Slider aria-label="Zoom" min={0} max={10} step={1} value={[zoom]} onValueChange={([v]) => setZoom(v)} />+ </Field>+ </>+ ) : (+ <Field label="Camera">+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Camera angle">+ {ANGLES.map(([a]) => (+ <Chip key={a} active={angle === a} onClick={() => setAngle(a)}>+ {a}+ </Chip>+ ))}+ </div>+ </Field>+ )}+ <KeepAlpha node={selected} value={keepAlpha} onChange={setKeepAlpha} />+ </SimpleTool>+ );+}++function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={active}+ onClick={onClick}+ className={cn(+ "inline-flex h-7 items-center rounded-full px-2.5 text-[12px] font-medium transition-colors",+ active ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",+ )}+ >+ {children}+ </button>+ );+}++// ---------------------------------------------------------------------------+// Regional editing++function RegionalTool() {+ const { doc, commit, jobs, isDemo, region, setRegion, setMode, select, selected } = useEditor();+ const { modelId, model, setModelId } = useToolModel("regional");+ const [prompt, setPrompt] = useState("");+ const [merging, setMerging] = useState(false);+ const { busy, go } = useRun();+ const job = latestJob(jobs, ["regional"]);+ useEffect(() => {+ setMode("region");+ return () => {+ setMode("select");+ setRegion(null);+ };+ }, [setMode, setRegion]);++ // The newest Original / New pair on the canvas.+ const pair = useMemo(() => {+ const sorted = [...doc.nodes].sort((a, b) => b.z - a.z);+ const edited = sorted.find((n) => n.role === "new");+ if (!edited) return null;+ const original = sorted.find((n) => n.role === "original" && n.z === edited.z - 1 && Math.abs(n.x - edited.x) < 1 && Math.abs(n.y - edited.y) < 1);+ return { edited, original };+ }, [doc.nodes]);++ const run = () => {+ if (!region) return;+ void go({ tool: "regional", target: { kind: "region", rect: region }, modelId, prompt: prompt.trim(), settings: { feather: Math.round(Math.min(region[2], region[3]) * 0.06) }, label: "Editing region" });+ };++ const merge = async () => {+ if (!pair) return;+ setMerging(true);+ const t = toast.loading("Merging…");+ try {+ const { edited, original } = pair;+ const rect: Box = [Math.round(edited.x), Math.round(edited.y), Math.round(edited.w), Math.round(edited.h)];+ const parts = original ? [original, edited] : [edited];+ const flat = await renderDoc({ ...doc, nodes: parts.map((p, i) => ({ ...p, hidden: false, z: i })) }, { rect });+ const url = await uploadRender(flat, "edited-region");+ const at = Date.now();+ const merged: LayerNode = {+ id: nanoid(8),+ name: "Edited region",+ z: 0,+ x: rect[0],+ y: rect[1],+ w: rect[2],+ h: rect[3],+ rotation: 0,+ src: url,+ crop: null,+ natural: [flat.width, flat.height],+ revisions: [{ src: url, crop: null, natural: [flat.width, flat.height], label: "Merged", at }],+ revision: 0,+ };+ commit(replaceNodes(doc, parts.map((p) => p.id), [merged]));+ select(merged.id);+ toast.success("Layers merged", { id: t, duration: 1500 });+ } catch {+ toast.error("Failed to merge layers", { id: t });+ } finally {+ setMerging(false);+ }+ };++ return (+ <div className="space-y-4">+ <div className="rounded-lg border bg-card px-3 py-2.5">+ <p className="text-[12px] font-medium">Select an area to edit</p>+ <p className="mt-0.5 text-[12px] text-pretty text-muted-foreground">Draw a rectangle over the image, then describe your changes in the prompt below it.</p>+ </div>+ {region ? (+ <p className="flex items-center justify-between font-mono text-[12px] text-muted-foreground">+ Area {region[2]} × {region[3]}+ <button type="button" className="font-sans text-[12px] hover:text-foreground hover:underline" onClick={() => setRegion(null)}>+ Clear selection+ </button>+ </p>+ ) : (+ <p className="text-[12px] text-subtle-foreground">Drag on the canvas to draw the area.</p>+ )}+ <Field label="Prompt" htmlFor="region-prompt">+ <Textarea id="region-prompt" value={prompt} onChange={(e) => setPrompt(e.target.value)} maxLength={2000} placeholder="e.g. “replace the cup with a glass of orange juice”" className="min-h-16 text-[13px]" />+ </Field>+ <ModelSelect tool="regional" value={modelId} onChange={setModelId} />+ <JobState job={job} failedTitle="Failed to edit image" onRetry={run} />+ <RunRow cost={costLabel(model, isDemo(model))} busy={busy} disabled={!region || !prompt.trim() || !model || (!!job && isRunning(job))} onClick={run}>+ <Wand2 /> Edit region+ </RunRow>+ {pair && (+ <div className="space-y-3 rounded-lg border p-3">+ <p className="text-[12px] font-medium">Original and New</p>+ <div className="flex gap-1.5">+ {[pair.original, pair.edited].filter((n): n is LayerNode => !!n).map((n) => (+ <Button key={n.id} size="xs" variant={selected?.id === n.id ? "default" : "secondary"} className="rounded-full" onClick={() => select(n.id)}>+ {n.name}+ </Button>+ ))}+ </div>+ <Field label="Mask feather" hint={`${Math.round(pair.edited.feather ?? 0)} px`}>+ <Slider+ aria-label="Mask feather"+ min={0}+ max={Math.round(Math.min(pair.edited.w, pair.edited.h) / 2)}+ step={1}+ value={[Math.round(pair.edited.feather ?? 0)]}+ onValueChange={([v]) => commit({ ...doc, nodes: doc.nodes.map((n) => (n.id === pair.edited.id ? { ...n, feather: v } : n)) })}+ />+ </Field>+ <div className="flex gap-2">+ <Button size="sm" className="flex-1 rounded-full" onClick={() => void merge()} disabled={merging}>+ {merging && <Loader2 className="animate-spin" />} Merge layers+ </Button>+ <Button+ size="sm"+ variant="outline"+ className="flex-1 rounded-full"+ onClick={() => {+ setRegion(null);+ setPrompt("");+ select(null);+ }}+ >+ Edit another region+ </Button>+ </div>+ </div>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Expand & Crop++const FRAME_RATIOS: [string, number | null][] = [+ ["Free", null],+ ["1:1", 1],+ ["4:5", 4 / 5],+ ["3:4", 3 / 4],+ ["16:9", 16 / 9],+ ["9:16", 9 / 16],+];++/** The smallest frame of this shape that contains the whole canvas, centred on it. */+function frameAround(w: number, h: number, ratio: number): Box {+ const fw = Math.max(w, h * ratio);+ const fh = fw / ratio;+ return [Math.round((w - fw) / 2), Math.round((h - fh) / 2), Math.round(fw), Math.round(fh)];+}++function ExpandTool() {+ const { doc, commit, engine, isDemo, jobs, frame, setFrame, setMode } = useEditor();+ const { modelId, model } = useToolModel("expand");+ const [fill, setFill] = useState(true);+ const { busy, go } = useRun();+ const job = latestJob(jobs, ["expand"]);+ useEffect(() => {+ setMode("frame");+ setFrame([0, 0, doc.width, doc.height]);+ return () => {+ setMode("select");+ setFrame(null);+ };+ // Reset the frame when the canvas itself changes size.+ }, [setMode, setFrame, doc.width, doc.height]);++ const f = frame ?? ([0, 0, doc.width, doc.height] as Box);+ const pads = expandPads(doc, f);+ const grows = pads.left + pads.top + pads.right + pads.bottom > 0;++ const apply = () => {+ try {+ commit(reframeDoc(doc, f));+ toast.success(grows ? "Canvas expanded" : "Canvas cropped", { duration: 1500 });+ } catch (e) {+ toast.error((e as Error).message);+ }+ };++ const generate = async () => {+ try {+ reframeDoc(doc, f); // the same check as Apply+ } catch (e) {+ toast.error((e as Error).message);+ return;+ }+ const [fx, fy, fw, fh] = f.map(Math.round) as Box;+ if (engine === "open") {+ // FLUX Fill pads the picture itself (multiples of 8, ≤ 2048 px in all).+ const s = Math.min(1, 2048 / Math.max(doc.width + pads.left + pads.right, doc.height + pads.top + pads.bottom));+ const flat = await renderDoc(doc, { scale: s });+ const image = await uploadRender(flat, "expand-source");+ const k = (n: number) => Math.ceil((n * s) / 8) * 8;+ await go({ tool: "expand", target: { kind: "whole" }, image, frame: [fx, fy, fw, fh], modelId, settings: { pads: { left: k(pads.left), top: k(pads.top), right: k(pads.right), bottom: k(pads.bottom) } }, label: "Expand" });+ } else {+ // Cloud edit models fill the grey margins of the larger picture.+ const s = Math.min(1, 2048 / Math.max(fw, fh));+ const flat = await renderDoc(doc, { rect: [fx, fy, fw, fh], scale: s, fill: "#808080" });+ const image = await uploadRender(flat, "expand-source");+ await go({ tool: "expand", target: { kind: "whole" }, image, frame: [fx, fy, fw, fh], modelId, settings: { aspect: ratioOf(fw, fh) }, label: "Expand" });+ }+ };++ return (+ <div className="space-y-4">+ <p className="text-[12px] text-pretty text-muted-foreground">Drag the edges or corners. Crop keeps pixels on layers. Expand adds empty canvas, or turn on Fill with AI to generate it.</p>+ <Field label="Shape">+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Frame shape">+ {FRAME_RATIOS.map(([label, r]) => (+ <Chip key={label} active={r === null ? false : Math.abs(f[2] / f[3] - r) < 0.01} onClick={() => setFrame(r ? frameAround(doc.width, doc.height, r) : [0, 0, doc.width, doc.height])}>+ {r === null ? "Reset" : label}+ </Chip>+ ))}+ </div>+ </Field>+ <div className="grid grid-cols-2 gap-2 font-mono text-[12px] text-muted-foreground">+ <span>+ Now {doc.width} × {doc.height}+ </span>+ <span className="text-right text-foreground">+ New {f[2]} × {f[3]}+ </span>+ </div>+ <label className="flex items-center justify-between gap-2 text-[13px]">+ Fill with AI+ <Switch checked={fill} onCheckedChange={setFill} disabled={!grows} aria-label="Fill with AI" />+ </label>+ <JobState job={job} failedTitle="Could not start Expand & Crop. Please try again." onRetry={() => void generate()} />+ {fill && grows ? (+ <RunRow cost={costLabel(model, isDemo(model))} busy={busy} disabled={!model || (!!job && isRunning(job))} onClick={() => void generate()}>+ <Wand2 /> Generate+ </RunRow>+ ) : (+ <div className="flex justify-end">+ <Button className="rounded-full" onClick={apply} disabled={f[0] === 0 && f[1] === 0 && f[2] === doc.width && f[3] === doc.height}>+ <Crop /> Apply+ </Button>+ </div>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Color grading (WebGL in the browser, no model)++function GradeTool() {+ const { doc, commit, select, setPreview } = useEditor();+ const { node } = useTarget();+ const [grade, setGrade] = useState<Grade>(NEUTRAL);+ const [preset, setPreset] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);+ const grader = useRef<LayerGrader | null>(null);+ const source = useRef<{ key: string; canvas: HTMLCanvasElement } | null>(null);+ const previewId = node?.id ?? "__whole";+ const key = node ? `${node.id}|${node.src}|${node.crop?.join(",")}|${node.maskSrc}` : `whole|${doc.nodes.map((n) => `${n.id}${n.src}${n.x}${n.y}${n.w}${n.h}${n.rotation}${n.hidden}`).join(";")}`;++ useEffect(() => {+ try {+ grader.current = new LayerGrader();+ } catch (e) {+ toast.error((e as Error).message);+ }+ return () => {+ grader.current?.dispose();+ grader.current = null;+ };+ }, []);++ // Live preview (at most 1024 px): the layer, or the whole picture as an overlay.+ useEffect(() => {+ let gone = false;+ const run = async () => {+ if (!grader.current) return;+ if (isNeutral(grade)) {+ setPreview(previewId, null);+ return;+ }+ if (source.current?.key !== key) {+ const c = node ? await renderNative(node, 1024) : await renderDoc(doc, { scale: Math.min(1, 1024 / Math.max(doc.width, doc.height)) });+ source.current = { key, canvas: c };+ }+ if (!gone && grader.current) setPreview(previewId, grader.current.grade(source.current.canvas, grade));+ };+ const t = setTimeout(() => void run(), 40);+ return () => {+ gone = true;+ clearTimeout(t);+ };+ }, [grade, key, node, doc, previewId, setPreview]);+ useEffect(() => () => setPreview(previewId, null), [previewId, setPreview]);++ const save = async () => {+ if (!grader.current) return;+ setSaving(true);+ try {+ const full = node ? await renderNative(node, 4096) : await renderDoc(doc);+ const graded = grader.current.grade(full, grade);+ const url = await uploadRender(graded, node ? `${node.name}-graded` : "graded");+ const at = Date.now();+ const label = PRESETS.find((p) => p.id === preset)?.name ?? "Color grade";+ const natural: [number, number] = [graded.width, graded.height];+ if (node) commit({ ...doc, nodes: doc.nodes.map((n) => (n.id === node.id ? addRevision(n, { src: url, crop: null, natural, label, at }) : n)) });+ else {+ const id = nanoid(8);+ commit(addNodes(doc, [{ id, name: "Color graded", z: 0, x: 0, y: 0, w: doc.width, h: doc.height, rotation: 0, src: url, crop: null, natural, revisions: [{ src: url, crop: null, natural, label, at }], revision: 0 }]));+ select(id);+ }+ setGrade(NEUTRAL);+ setPreset(null);+ toast.success("Grade applied", { duration: 1500 });+ } catch (e) {+ toast.error((e as Error).message || "Couldn't apply the grade");+ } finally {+ setSaving(false);+ }+ };++ const groups = ["Light", "Color", "Split tone", "Effects"] as const;+ return (+ <div className="space-y-4">+ <Scope node={node} />+ <Field label="Looks">+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Looks">+ {PRESETS.map((p) => (+ <Chip+ key={p.id}+ active={preset === p.id}+ onClick={() => {+ setPreset(p.id);+ setGrade(applyPreset(p));+ }}+ >+ {p.name}+ </Chip>+ ))}+ </div>+ </Field>+ {groups.map((g) => (+ <fieldset key={g} className="space-y-2.5">+ <legend className="mb-1 text-[11px] font-semibold tracking-wide text-subtle-foreground uppercase">{g}</legend>+ {CONTROLS.filter((c) => c.group === g).map((c) => (+ <Field key={c.key} label={c.label} hint={grade[c.key]}>+ <Slider aria-label={c.label} min={c.min} max={c.max} step={1} value={[grade[c.key]]} onValueChange={([v]) => setGrade({ ...grade, [c.key]: v })} />+ </Field>+ ))}+ </fieldset>+ ))}+ <div className="sticky bottom-0 flex items-center justify-between gap-2 bg-background pt-2 pb-1">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => {+ setGrade(NEUTRAL);+ setPreset(null);+ }}+ disabled={isNeutral(grade)}+ >+ Reset+ </Button>+ <Button className="rounded-full" onClick={() => void save()} disabled={saving || isNeutral(grade)}>+ {saving && <Loader2 className="animate-spin" />} Apply grade+ </Button>+ </div>+ <p className="text-[11px] text-subtle-foreground">Runs in your browser — free on both engines.</p>+ </div>+ );+}++// ---------------------------------------------------------------------------+// The rail++export function ToolRail() {+ const { tool, openTool, mask, selected, setSplitTarget, jobs } = useEditor();+ const current = TOOLS.find((t) => t.id === tool);+ const running = jobs.filter(isRunning).length;+ return (+ <aside className="flex min-h-0 w-[280px] shrink-0 flex-col border-r bg-background" aria-label="Tools">+ {current ? (+ <>+ <div className="flex h-12 shrink-0 items-center gap-1 px-2">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Back to tools"+ onClick={() => {+ openTool(null);+ setSplitTarget(null);+ }}+ >+ <ArrowLeft />+ </Button>+ <current.icon className="size-4 text-brand-text" />+ <h2 className="truncate text-[13px] font-semibold">{current.label}</h2>+ </div>+ <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain">+ <div className="px-3 pt-1 pb-6">+ {tool === "decompose" && <DecomposeTool />}+ {tool === "edit-text" && <EditTextTool />}+ {tool === "remove-bg" && (+ <SimpleTool tool="bg-remove" verb="Remove background" failedTitle="Failed to load image. Please try again.">+ <HowItWorks>Remove background finds the main subject of your image and cuts everything else away, giving you the subject on a transparent background.</HowItWorks>+ </SimpleTool>+ )}+ {tool === "regional" && <RegionalTool />}+ {tool === "upscale" && (+ <SimpleTool tool="upscale" verb="Upscale" failedTitle="Couldn't upscale it">+ <p className="text-[12px] text-muted-foreground">{selected ? "The layer gets more pixels in the same place on the canvas; switch back any time in its versions." : "The upscaled picture arrives as a new layer on top."}</p>+ </SimpleTool>+ )}+ {tool === "relight" && <RelightTool />}+ {tool === "angles" && <AnglesTool />}+ {tool === "expand" && <ExpandTool />}+ {tool === "grade" && <GradeTool />}+ </div>+ </div>+ </>+ ) : (+ <>+ <div className="flex h-12 shrink-0 items-center gap-2 px-3">+ <h2 className="text-[13px] font-semibold">Tools</h2>+ {running > 0 && (+ <span className="ml-auto inline-flex items-center gap-1 rounded-full bg-brand-faint px-2 py-0.5 text-[11px] font-medium text-brand-text">+ <Loader2 className="size-3 animate-spin" /> {running} running+ </span>+ )}+ </div>+ <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain">+ <ul className="space-y-0.5 px-2 pb-4">+ {TOOLS.map((t) => (+ <li key={t.id}>+ <button+ type="button"+ disabled={!!mask}+ title={mask ? "Unavailable while editing a mask" : undefined}+ onClick={() => openTool(t.id)}+ className="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-accent disabled:opacity-50 disabled:hover:bg-transparent"+ >+ <span className="grid size-8 shrink-0 place-items-center rounded-lg bg-muted text-foreground">+ <t.icon className="size-4" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-1.5 text-[13px] font-medium">+ {t.label}+ {t.isNew && <span className="rounded-full bg-highlight px-1.5 py-px text-[10px] font-semibold text-highlight-foreground">New</span>}+ </span>+ <span className="block truncate text-[11px] text-muted-foreground">{t.hint}</span>+ </span>+ </button>+ </li>+ ))}+ </ul>+ <p className="px-4 pb-4 text-[11px] text-pretty text-subtle-foreground">Tools act on the selected layer. Deselect the layer to use a tool on the whole image.</p>+ </div>+ </>+ )}+ </aside>+ );+}diff --git a/src/components/layers/top-bar.tsx b/src/components/layers/top-bar.tsxnew file mode 100644index 00000000..7ff0f94f--- /dev/null+++ b/src/components/layers/top-bar.tsx@@ -0,0 +1,238 @@+"use client";++import { ArrowLeft, Braces, Check, CloudOff, Columns2, Download, FileArchive, History, ImageDown, Loader2, Redo2, Undo2 } from "lucide-react";+import Link from "next/link";+import { useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Kbd } from "@/components/ui/kbd";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { EngineSwitch } from "@/components/studio/engine-switch";+import type { Engine } from "@/lib/catalog/types";+import { timeAgo } from "@/lib/format";+import { docJson, type LayerDoc, type LayerJob, type LayerVersion } from "@/lib/layers";+import { cn } from "@/lib/utils";+import { downloadPng, downloadZip } from "./render";++export type SaveState = "saved" | "saving" | "dirty" | "error" | "conflict";++/** The download menu (shared with the phone view): the two zips and the flat PNG, built in the browser. */+export function DownloadMenu({ doc, name, jobs, compact }: { doc: LayerDoc; name: string; jobs: LayerJob[]; compact?: boolean }) {+ const [busy, setBusy] = useState(false);+ const splitting = jobs.some((j) => (j.tool === "decompose" || j.tool === "split") && j.state === "pending");+ const go = async (kind: "cropped" | "positioned" | "image") => {+ if (!doc.nodes.length) {+ toast.error("No layers to download");+ return;+ }+ if (splitting && kind !== "image") {+ toast.error("Wait for all layers to finish, then try again.");+ return;+ }+ setBusy(true);+ const t = toast.loading(kind === "image" ? "Rendering the image…" : "Packing the layers…");+ try {+ if (kind === "image") await downloadPng(doc, name);+ else await downloadZip(doc, kind);+ toast.success("Downloaded", { id: t, duration: 1500 });+ } catch (e) {+ toast.error((e as Error).message || "Couldn't download this version. Please try again.", { id: t });+ } finally {+ setBusy(false);+ }+ };+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button size={compact ? "icon" : "sm"} variant="secondary" className="rounded-full" disabled={busy} aria-label="Download">+ {busy ? <Loader2 className="animate-spin" /> : <Download />}+ {!compact && "Download"}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ <DropdownMenuItem onSelect={() => void go("cropped")}>+ <FileArchive /> Cropped layers .zip+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => void go("positioned")}>+ <FileArchive /> Positioned Layers .zip+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => void go("image")}>+ <ImageDown /> Image .png+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function SaveBadge({ state }: { state: SaveState }) {+ const text = { saved: "Saved", saving: "Saving…", dirty: "Saving…", error: "Not saved — retrying", conflict: "Changed in another tab" }[state];+ return (+ <span className={cn("hidden items-center gap-1 text-[12px] whitespace-nowrap lg:inline-flex", state === "error" || state === "conflict" ? "text-warning" : "text-subtle-foreground")} role="status" aria-live="polite">+ {state === "saved" ? <Check className="size-3.5" /> : state === "error" || state === "conflict" ? <CloudOff className="size-3.5" /> : <Loader2 className="size-3.5 animate-spin" />}+ {text}+ </span>+ );+}++export function TopBar(p: {+ name: string;+ onRename: (name: string) => void;+ save: SaveState;+ canUndo: boolean;+ canRedo: boolean;+ onUndo: () => void;+ onRedo: () => void;+ versions: LayerVersion[];+ headVersionId: string;+ onRestore: (versionId: string) => Promise<void>;+ compare: boolean;+ onCompare: (on: boolean) => void;+ doc: LayerDoc;+ jobs: LayerJob[];+ engine: Engine;+ setEngine: (e: Engine) => void;+}) {+ const [draft, setDraft] = useState(p.name);+ const [historyOpen, setHistoryOpen] = useState(false);+ const [restoring, setRestoring] = useState<string | null>(null);+ const copyJson = async () => {+ try {+ await navigator.clipboard.writeText(docJson(p.doc, window.location.origin));+ toast.success("JSON copied", { duration: 1500 });+ } catch {+ toast.error("Could not copy to the clipboard. Try again.");+ }+ };+ const mod = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform) ? "⌘" : "Ctrl";++ return (+ <header className="flex h-14 shrink-0 items-center gap-1.5 border-b bg-background px-2 sm:px-3">+ <SidebarTrigger className="md:hidden" />+ <Tooltip>+ <TooltipTrigger asChild>+ <Button asChild variant="ghost" size="icon-sm" aria-label="All projects">+ <Link href="/layers">+ <ArrowLeft />+ </Link>+ </Button>+ </TooltipTrigger>+ <TooltipContent>All projects</TooltipContent>+ </Tooltip>+ <input+ value={draft}+ maxLength={80}+ aria-label="Project name"+ onChange={(e) => setDraft(e.target.value)}+ onFocus={(e) => e.currentTarget.select()}+ onBlur={() => {+ const n = draft.trim();+ if (!n) setDraft(p.name);+ else if (n !== p.name) p.onRename(n);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "Escape") {+ setDraft(p.name);+ e.currentTarget.blur();+ }+ }}+ className="h-8 w-[clamp(8rem,18vw,16rem)] min-w-0 truncate rounded-md border border-transparent bg-transparent px-2 font-heading text-[19px] outline-none hover:border-border focus:border-primary focus:ring-4 focus:ring-brand-faint"+ />+ <SaveBadge state={p.save} />++ <div className="ml-auto flex items-center gap-1">+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="icon-sm" aria-label="Undo" disabled={!p.canUndo} onClick={p.onUndo}>+ <Undo2 />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ Undo <Kbd>{mod}</Kbd>+ <Kbd>Z</Kbd>+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="icon-sm" aria-label="Redo" disabled={!p.canRedo} onClick={p.onRedo}>+ <Redo2 />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ Redo <Kbd>{mod}</Kbd>+ <Kbd>⇧</Kbd>+ <Kbd>Z</Kbd>+ </TooltipContent>+ </Tooltip>+ <Button variant="ghost" size="sm" className="rounded-full" onClick={() => setHistoryOpen(true)} aria-label="Edit history">+ <History /> <span className="hidden xl:inline">Edit history</span>+ </Button>+ <Button variant={p.compare ? "default" : "ghost"} size="sm" className="rounded-full" aria-pressed={p.compare} onClick={() => p.onCompare(!p.compare)}>+ <Columns2 /> <span className="hidden xl:inline">Compare</span>+ </Button>+ <span className="mx-1 hidden h-5 w-px bg-border sm:block" />+ <DownloadMenu doc={p.doc} name={p.name} jobs={p.jobs} />+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Button variant="ghost" size="sm" className="rounded-full" disabled={!p.doc.nodes.length} onClick={() => void copyJson()}>+ <Braces /> <span className="hidden xl:inline">Copy JSON</span>+ </Button>+ </span>+ </TooltipTrigger>+ <TooltipContent>{p.doc.nodes.length ? "Copy the layers as a design file (JSON)" : "Add a layer to copy as JSON."}</TooltipContent>+ </Tooltip>+ <EngineSwitch value={p.engine} onChange={p.setEngine} />+ </div>++ <Sheet open={historyOpen} onOpenChange={setHistoryOpen}>+ <SheetContent className="w-[min(92vw,380px)]">+ <SheetHeader>+ <SheetTitle>Edit history</SheetTitle>+ <SheetDescription>Every tool result is saved as a version. Restoring one adds it on top — nothing is lost.</SheetDescription>+ </SheetHeader>+ <ol className="space-y-1 overflow-y-auto px-4 pb-6">+ {p.versions.map((v, i) => {+ const current = v.id === p.headVersionId;+ return (+ <li key={v.id} className={cn("flex items-center gap-3 rounded-lg px-3 py-2.5", current ? "bg-brand-faint" : "hover:bg-accent")}>+ <span className="grid size-6 shrink-0 place-items-center rounded-full bg-muted font-mono text-[11px] text-muted-foreground">{p.versions.length - i}</span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[13px] font-medium">{v.label}</span>+ <span className="block text-[11px] text-muted-foreground">+ {current ? "Open now · " : ""}+ {timeAgo(v.updatedAt)}+ </span>+ </span>+ {!current && (+ <Button+ size="xs"+ variant="secondary"+ className="rounded-full"+ disabled={!!restoring}+ onClick={async () => {+ setRestoring(v.id);+ try {+ await p.onRestore(v.id);+ setHistoryOpen(false);+ } finally {+ setRestoring(null);+ }+ }}+ >+ {restoring === v.id ? <Loader2 className="animate-spin" /> : null} Restore+ </Button>+ )}+ </li>+ );+ })}+ </ol>+ </SheetContent>+ </Sheet>+ </header>+ );+}diff --git a/src/components/layers/use-layers.ts b/src/components/layers/use-layers.tsnew file mode 100644index 00000000..3dd8a769--- /dev/null+++ b/src/components/layers/use-layers.ts@@ -0,0 +1,130 @@+"use client";++import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useCallback, useRef } from "react";+import { useGenerationEvents } from "@/lib/api";+import type { LayerDoc, LayerJob, LayerJobInput, LayerProject, LayerProjectView } from "@/lib/layers";++/** Client hooks for /api/layers (kept next to the Layers UI; the shapes live in src/lib/layers.ts). */++export class LayersRequestError extends Error {+ constructor(+ message: string,+ public status: number,+ ) {+ super(message);+ }+}++async function json<T>(res: Response): Promise<T> {+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };+ if (!res.ok) throw new LayersRequestError(body.error ?? `Request failed (${res.status})`, res.status);+ return body;+}++const send = (url: string, method: string, body?: unknown, init?: RequestInit) =>+ fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), ...init });++const isActive = (j: LayerJob) => j.state === "pending" && (!j.result || j.result.status === "queued" || j.result.status === "running");++export function useLayerProjects() {+ return useQuery({+ queryKey: ["layers"],+ queryFn: async () => (await json<{ items: LayerProject[] }>(await fetch("/api/layers"))).items,+ refetchInterval: (q) => (q.state.data?.some((p) => p.status === "processing") ? 4000 : false),+ });+}++/**+ * One project with its tools' jobs. Polls while a job renders (slowly when the app's shared live+ * stream is connected, which also refetches as soon as one of its generations changes).+ */+export function useLayerProject(id: string) {+ const qc = useQueryClient();+ const ids = useRef(new Set<string>());+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const live = useGenerationEvents(+ useCallback(+ (ev) => {+ const gid = ev.type === "generation" ? ev.generation.id : ev.id;+ if (!ids.current.has(gid)) return;+ // Coalesce bursts (progress ticks) into one refetch.+ if (timer.current) return;+ timer.current = setTimeout(() => {+ timer.current = null;+ void qc.invalidateQueries({ queryKey: ["layers", id], exact: true });+ }, 250);+ },+ [qc, id],+ ),+ );+ return useQuery({+ queryKey: ["layers", id],+ queryFn: async () => {+ const v = await json<LayerProjectView>(await fetch(`/api/layers/${id}`));+ ids.current = new Set(v.jobs.filter((j) => j.state === "pending").flatMap((j) => j.generationIds));+ return v;+ },+ refetchInterval: (q) => (q.state.data?.jobs.some(isActive) ? (live ? 8000 : 1500) : false),+ // The editor owns the document once loaded; refetches only bring jobs and versions.+ refetchOnWindowFocus: false,+ retry: (n, e) => !(e instanceof LayersRequestError && e.status === 404) && n < 1,+ });+}++export function useLayerActions() {+ const qc = useQueryClient();+ const refreshList = () => void qc.invalidateQueries({ queryKey: ["layers"], exact: true });+ return {+ create: async (body: { source: string; width: number; height: number; name?: string; generationId?: string }) => {+ const v = await json<LayerProjectView>(await send("/api/layers", "POST", body));+ qc.setQueryData(["layers", v.project.id], v);+ refreshList();+ return v;+ },+ rename: async (id: string, name: string) => {+ qc.setQueryData<LayerProject[]>(["layers"], (old) => old?.map((p) => (p.id === id ? { ...p, name } : p)));+ qc.setQueryData<LayerProjectView>(["layers", id], (old) => (old ? { ...old, project: { ...old.project, name } } : old));+ await json<LayerProject>(await send(`/api/layers/${id}`, "PATCH", { name }));+ refreshList();+ },+ remove: async (id: string) => {+ qc.setQueryData<LayerProject[]>(["layers"], (old) => old?.filter((p) => p.id !== id));+ const res = await fetch(`/api/layers/${id}`, { method: "DELETE" });+ if (!res.ok && res.status !== 404) throw new Error("Couldn't delete this project. Please try again.");+ qc.removeQueries({ queryKey: ["layers", id] });+ refreshList();+ },+ /** A milestone version (a tool's result, `jobId` marks it applied) or a restore (`from`). */+ version: async (id: string, body: { doc?: LayerDoc; label?: string; jobId?: string; from?: string }) => {+ const v = await json<LayerProjectView>(await send(`/api/layers/${id}/versions`, "POST", body));+ qc.setQueryData(["layers", id], v);+ refreshList();+ return v;+ },+ startJob: async (id: string, input: LayerJobInput) => {+ const job = await json<LayerJob>(await send(`/api/layers/${id}/jobs`, "POST", input));+ qc.setQueryData<LayerProjectView>(["layers", id], (old) => (old ? { ...old, jobs: [...old.jobs, job] } : old));+ void qc.invalidateQueries({ queryKey: ["layers", id], exact: true });+ refreshList();+ return job;+ },+ endJob: async (id: string, jobId: string, how: "dismiss" | "cancel" | "applied") => {+ const res = how === "cancel" ? await fetch(`/api/layers/${id}/jobs/${jobId}`, { method: "DELETE" }) : await send(`/api/layers/${id}/jobs/${jobId}`, "PATCH", { state: how === "applied" ? "applied" : "dismissed" });+ const job = await json<LayerJob>(res);+ qc.setQueryData<LayerProjectView>(["layers", id], (old) => (old ? { ...old, jobs: old.jobs.map((j) => (j.id === jobId ? job : j)) } : old));+ refreshList();+ return job;+ },+ };+}++/** Refresh the project card's cover (a small data URL of the composite). */+export async function saveCover(id: string, cover: string): Promise<void> {+ await json<LayerProject>(await send(`/api/layers/${id}`, "PATCH", { cover }));+}++/** Autosave the document into the head version. `keepalive` lets a save started while leaving the page finish. */+export async function saveDoc(id: string, doc: LayerDoc, versionId: string, keepalive = false): Promise<LayerProject> {+ return json<LayerProject>(await send(`/api/layers/${id}`, "PATCH", { doc, versionId }, { keepalive }));+}diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex d821cb7c..47ae5bae 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -14,6 +14,7 @@ import {FolderDown,Heart,ImagePlus,+ Layers2,Mic2,MoreHorizontal,RotateCcw,@@ -62,6 +63,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {upscale: ZoomIn,reference: ImagePlus,grade: SlidersHorizontal,+ layers: Layers2,"save-character": UserRoundPlus,extend: FastForward,reframe: Crop,diff --git a/src/lib/layers.ts b/src/lib/layers.tsindex 5674ee59..34c7f35f 100644--- a/src/lib/layers.ts+++ b/src/lib/layers.ts@@ -226,6 +226,17 @@ export const ANGLES: [string, string][] = [["Wide", "a wide shot showing the full environment"],];+/** What the editor knows about a tool's model (built by its page, so the browser needs no catalog). */+export interface LayerModelInfo {+ id: string;+ name: string;+ engine: "cloud" | "open";+ tagline: string;+ pricing?: { unit: string; usd: number; note?: string };+ /** Providers its routes run on (demo detection: none of them connected). */+ providers: string[];+}+/** Cuts the background back out after an edit model repaints a transparent layer. */export const CUTOUT_MODELS = { cloud: "birefnet-cloud", open: "oss-rmbg" } as const;diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 7d38f29c..56948458 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -15,6 +15,7 @@ export type OutputActionId =| "upscale"| "reference"| "grade"+ | "layers"| "save-character"| "extend"| "reframe"@@ -83,6 +84,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =link("upscale", "Upscale", `/upscale?image=${q(o.url)}`);link("reference", "Use as reference", `/image?ref=${q(o.url)}`);link("grade", "Color grade", `/color-grade?image=${q(o.url)}`);+ link("layers", "Open in Layers", layersHref(g, o.url));out.push({ id: "save-character", label: "Save as character", placement: "menu" });break;case "video":@@ -123,6 +125,16 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =return out;}+/**+ * Open an image in the Layers editor (/layers?image=…). A layers result opens with its layers+ * already split, on the picture it was made from.+ */+export function layersHref(g: Pick<Generation, "id" | "op" | "status" | "request">, url: string): string {+ const source = g.request?.inputs?.images?.[0];+ if (g.op === "layers" && g.status === "succeeded" && source?.startsWith("/api/files/")) return `/layers?image=${q(source)}&generation=${g.id}`;+ return `/layers?image=${q(url)}`;+}+// ---------------------------------------------------------------------------// Text, layers and 3D outputsdiff --git a/src/server/layers.ts b/src/server/layers.tsindex 00bd42c6..0b4d05ed 100644--- a/src/server/layers.ts+++ b/src/server/layers.ts@@ -26,7 +26,8 @@ import {} from "@/lib/layers";import { createPipeline, type PipelineStep } from "./chains";import { db } from "./db";-import { cancelGeneration, getGeneration } from "./generations";+import { cancelGeneration, getGeneration, previewGeneration } from "./generations";+import { getAsset } from "./storage";/*** Layers studio (Higgsfield Layers): projects, saved versions of their layer document, and the AI@@ -439,6 +440,17 @@ function insertVersion(projectId: string, label: string, doc: LayerDoc, now: numreturn id;}+/** A project's starting name: the result's title or prompt (first words), else the uploaded file's name. */+function nameFor(source: string): string | undefined {+ const assetId = /\/([A-Za-z0-9_-]{12})\.[a-z0-9]+$/i.exec(source)?.[1];+ const asset = assetId ? getAsset(assetId) : null;+ if (!asset) return undefined;+ const g = asset.generationId ? getGeneration(asset.generationId, { includeDeleted: true }) : null;+ const text = g?.request.title ?? g?.prompt ?? asset.name?.replace(/\.[^.]+$/, "");+ const words = text?.replace(/\s+/g, " ").trim().split(" ").slice(0, 6).join(" ");+ return words ? words.charAt(0).toUpperCase() + words.slice(1, 80) : undefined;+}+/*** A new project on an image (an upload or a result): the image is its first layer. With* `generationId` (a finished layers result), its layers arrive like a decomposition that just finished.@@ -455,7 +467,7 @@ export function createProject(input: { source: string; width: number; height: nujobs.push({ id: nanoid(8), tool: "decompose", label: "Layers from your result", frame: [0, 0, width, height], generationIds: [g.id], state: "pending", createdAt: now });}const id = nanoid(10);- const name = input.name?.trim().slice(0, 80) || "Untitled project";+ const name = input.name?.trim().slice(0, 80) || nameFor(input.source) || "Untitled project";db().transaction(() => {db().prepare("INSERT INTO layer_projects (id, name, source_url, cover_url, width, height, head_version_id, jobs_json, created_at, updated_at) VALUES (?, ?, ?, NULL, ?, ?, NULL, ?, ?, ?)")@@ -467,12 +479,18 @@ export function createProject(input: { source: string; width: number; height: nu}/** Rename, and/or autosave the document into the head version (409 when another tab moved the head). */-export function updateProject(id: string, patch: { name?: string; doc?: LayerDoc; versionId?: string }): LayerProject | null {+/** The project card's cover: a small JPEG/WebP of the current composite, rendered by the editor (data URL). */+export const COVER_MAX = 300_000;+const isCover = (v: string) => /^data:image\/(jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(v) && v.length <= COVER_MAX;++export function updateProject(id: string, patch: { name?: string; doc?: LayerDoc; versionId?: string; cover?: string }): LayerProject | null {const row = getRow(id);if (!row) return null;const now = Date.now();+ if (patch.cover !== undefined && !isCover(patch.cover)) throw new LayersError("That cover isn't a small JPEG or WebP image", 400);db().transaction(() => {if (patch.name !== undefined) db().prepare("UPDATE layer_projects SET name = ?, updated_at = ? WHERE id = ?").run(patch.name.trim().slice(0, 80) || "Untitled project", now, id);+ if (patch.cover !== undefined) db().prepare("UPDATE layer_projects SET cover_url = ? WHERE id = ?").run(patch.cover, id);if (patch.doc) {if (patch.versionId && patch.versionId !== row.head_version_id) throw new LayersError("This project changed in another tab. Reload to see the latest version.", 409);if (patch.doc.source !== row.source_url) throw new LayersError("That document belongs to another image", 400);@@ -557,6 +575,16 @@ export function startJob(id: string, input: LayerJobInput): LayerJob {throw new LayersError("A generation is already running on this layer", 409);}const steps = jobSteps(input, { batchTitle: `Layers · ${row.name}` });+ // Seedream's layer-count instruction means nothing to the demo provider, which would print it on its sample text layer.+ if ((input.tool === "decompose" || input.tool === "split") && !input.prompt?.trim()) {+ for (const s of steps) {+ try {+ if (s.request.op === "layers" && s.request.prompt && previewGeneration(s.request).demo) s.request = { ...s.request, prompt: undefined };+ } catch {+ // createPipeline below reports what's wrong with the request.+ }+ }+ }let ids: string[];try {ids = createPipeline(steps, { batchId: `layers-${id}` }).items.map((g) => g.id);@@ -570,7 +598,8 @@ export function startJob(id: string, input: LayerJobInput): LayerJob {label: input.label?.trim() || TOOL_LABELS[input.tool],...(input.nodeId ? { nodeId: input.nodeId } : {}),frame: input.frame as Box,- settings: { ...(input.settings ?? {}), ...(input.prompt ? { prompt: input.prompt } : {}), ...(input.modelId ? { modelId: input.modelId } : {}) },+ // The input too: a regional edit lays its result over the region as it was (Original / New).+ settings: { ...(input.settings ?? {}), ...(input.prompt ? { prompt: input.prompt } : {}), ...(input.modelId ? { modelId: input.modelId } : {}), ...(input.image ? { image: input.image } : {}) },generationIds: ids,state: "pending",createdAt: Date.now(),diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.tsindex 71bedf11..0ddade16 100644--- a/tests/layers-api.test.ts+++ b/tests/layers-api.test.ts@@ -263,6 +263,18 @@ describe("layers API", () => {expect(((await res.json()) as { error: string }).error).toMatch(/Describe your changes/);});+ it("keeps a small cover of the composite for the card, and names projects after their image", async () => {+ const cover = `data:image/jpeg;base64,${Buffer.from("not really a jpeg").toString("base64")}`;+ let res = await one.PATCH(req("PATCH", { cover }), ctx({ id }));+ expect(res.status).toBe(200);+ expect(((await res.json()) as LayerProject).coverUrl).toBe(cover);+ res = await one.PATCH(req("PATCH", { cover: "javascript:alert(1)" }), ctx({ id }));+ expect(res.status).toBe(400);+ // No name given: the uploaded file's name ("poster.png").+ res = await list.POST(req("POST", { source: upload(), width: 10, height: 10 }));+ expect(((await res.json()) as LayerProjectView).project.name).toBe("Poster");+ });+it("restores an older version as a new head", async () => {const original = view.versions[view.versions.length - 1];const res = await versions.POST(req("POST", { from: original.id }), ctx({ id }));diff --git a/tests/layers.test.ts b/tests/layers.test.tsindex 092b36c9..36c56533 100644--- a/tests/layers.test.ts+++ b/tests/layers.test.ts@@ -5,6 +5,7 @@ import path from "node:path";import { describe, expect, it } from "vitest";import { getModel, supportsOp } from "@/lib/catalog";import type { Operation } from "@/lib/catalog/types";+import { layersHref } from "@/lib/output-actions";import {addNodes,addRevision,@@ -388,6 +389,18 @@ describe("edit text", () => {});});+describe("Open in Layers", () => {+ it("opens an image result as a new project, and a layers result with its layers", () => {+ const base = { feature: "image", modelId: "m" };+ expect(layersHref({ id: "g1", op: "t2i", status: "succeeded", request: base }, "/api/files/o/a.png")).toBe("/layers?image=%2Fapi%2Ffiles%2Fo%2Fa.png");+ expect(layersHref({ id: "g2", op: "layers", status: "succeeded", request: { ...base, inputs: { images: ["/api/files/u/src.png"] } } }, "/api/files/o/l1.png")).toBe(+ "/layers?image=%2Fapi%2Ffiles%2Fu%2Fsrc.png&generation=g2",+ );+ // A layers result made from an image that isn't stored here opens just that layer.+ expect(layersHref({ id: "g3", op: "layers", status: "succeeded", request: { ...base, inputs: { images: ["https://x.example/a.png"] } } }, "/api/files/o/l1.png")).toBe("/layers?image=%2Fapi%2Ffiles%2Fo%2Fl1.png");+ });+});+describe("tools and prices", () => {const OPS: Record<string, Operation[]> = {decompose: ["layers"],diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.tsindex 5c969321..2a233eb4 100644--- a/tests/library-pure.test.ts+++ b/tests/library-pure.test.ts@@ -48,6 +48,7 @@ describe("outputActions", () => {"menu:upscale","menu:reference","menu:grade",+ "menu:layers","menu:save-character","menu:reuse","menu:copy-prompt",