Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Layers editor: Inpaint and Enhancer tools, detection on both engines, Save as element

Claude172a72da73b0
diff --git a/src/components/layers/editor-context.tsx b/src/components/layers/editor-context.tsx
index 655ac98c..dee4ca4a 100644
--- a/src/components/layers/editor-context.tsx
+++ b/src/components/layers/editor-context.tsx
@@ -5,7 +5,7 @@ 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";
+export type StageMode = "select" | "hand" | "brush" | "eraser" | "region" | "frame" | "inpaint";
/** The part of the picture a tool works on. */
export type Target = { kind: "node"; node: LayerNode } | { kind: "whole" } | { kind: "region"; rect: Box };
@@ -20,6 +20,18 @@ export interface MaskEdit {
version: number;
}
+/**
+ * Inpaint's painted area: white strokes on a transparent canvas the size of the picture the tool
+ * sends, over a layer (it follows the layer as it moves) or the whole image.
+ */
+export interface PaintEdit {
+ /** The layer it's painted on; none = the whole image. */
+ nodeId?: string;
+ canvas: HTMLCanvasElement;
+ /** The eraser takes paint away. */
+ erase: boolean;
+}
+
export interface EditorCtx {
projectId: string;
project: LayerProject;
@@ -54,6 +66,14 @@ export interface EditorCtx {
frame: Box | null;
setFrame: (r: Box | null) => void;
mask: MaskEdit | null;
+ /** Inpaint's painted area (the stage paints into it while the mode is "inpaint"). */
+ paint: PaintEdit | null;
+ setPaint: (p: PaintEdit | null) => void;
+ /** Bumped on every stroke into the painted area. */
+ paintVersion: number;
+ /** Brush size in document pixels (masks and Inpaint). */
+ brushSize: number;
+ setBrushSize: (n: number) => void;
/** 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). */
diff --git a/src/components/layers/layers-editor.tsx b/src/components/layers/layers-editor.tsx
index 89da6da6..abdd62db 100644
--- a/src/components/layers/layers-editor.tsx
+++ b/src/components/layers/layers-editor.tsx
@@ -33,7 +33,7 @@ import {
type LayerTool,
} from "@/lib/layers";
import { applyMeasured, idPool, type Applied } from "./apply";
-import { costLabel, Ctx, isFailed, isRunning, keysBelongElsewhere, latestJob, TOOL_FOR_JOB, type EditorCtx, type MaskEdit, type RunInput, type StageMode, type ToolId } from "./editor-context";
+import { costLabel, Ctx, isFailed, isRunning, keysBelongElsewhere, latestJob, TOOL_FOR_JOB, type EditorCtx, type MaskEdit, type PaintEdit, type RunInput, type StageMode, type ToolId } from "./editor-context";
import { LayersPanel } from "./layers-panel";
import { measureJob } from "./measure";
import { MobileView } from "./mobile-view";
@@ -160,6 +160,8 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()
const [previews, setPreviews] = useState<Map<string, HTMLCanvasElement>>(() => new Map());
const [mask, setMask] = useState<MaskEdit | null>(null);
const [maskVersion, setMaskVersion] = useState(0);
+ const [paint, setPaint] = useState<PaintEdit | null>(null);
+ const [paintVersion, setPaintVersion] = useState(0);
const [brushSize, setBrushSize] = useState(() => Math.round(Math.max(initial.doc.width, initial.doc.height) / 30));
const [compare, setCompare] = useState(false);
const toolRef = useRef(tool);
@@ -533,7 +535,8 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()
if (mod || e.altKey) return;
if (e.key === "Escape") {
if (mode === "brush" || mode === "eraser") setMode("select");
- else select(null);
+ // Inpaint's paint belongs to the layer it's on: Escape doesn't drop it.
+ else if (mode !== "inpaint") select(null);
return;
}
if ((e.key === "Delete" || e.key === "Backspace") && sel) {
@@ -555,13 +558,19 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()
return;
}
const k = e.key.toLowerCase();
+ // Inpaint is open: B paints the area, E erases paint.
+ if (paint && (k === "b" || k === "e")) {
+ setPaint((p) => (p ? { ...p, erase: k === "e" } : p));
+ setMode("inpaint");
+ return;
+ }
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]);
+ }, [selectedId, mode, commit, select, setMode, busyJob, paint]);
// ---- Compare: the original, where it sits in the document now, against the current composite.
const [pair, setPair] = useState<{ before: string; after: string } | null>(null);
@@ -634,6 +643,11 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()
frame,
setFrame,
mask,
+ paint,
+ setPaint,
+ paintVersion,
+ brushSize,
+ setBrushSize,
setHighlight,
setPreview,
tool,
@@ -714,6 +728,10 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()
setFrame={setFrame}
mask={mask}
onMaskChange={() => setMaskVersion((v) => v + 1)}
+ paint={paint}
+ paintVersion={paintVersion}
+ onPaintChange={() => setPaintVersion((v) => v + 1)}
+ setPaintErase={(erase) => setPaint((p) => (p ? { ...p, erase } : p))}
brushSize={brushSize}
setBrushSize={setBrushSize}
highlight={highlight}
diff --git a/src/components/layers/layers-panel.tsx b/src/components/layers/layers-panel.tsx
index 5688ef42..5eb333fa 100644
--- a/src/components/layers/layers-panel.tsx
+++ b/src/components/layers/layers-panel.tsx
@@ -3,6 +3,7 @@
import {
ArrowDown,
ArrowUp,
+ BookmarkPlus,
Brush,
ChevronLeft,
ChevronRight,
@@ -64,6 +65,7 @@ import { cn } from "@/lib/utils";
import { Field } from "./bits";
import { costLabel, modelsFor, TOOL_FOR_JOB, useEditor } from "./editor-context";
import { downloadLayer, loadImage, sizeOf } from "./render";
+import { SaveElementDialog } from "./save-element";
/**
* A layer's thumbnail showing just the part of its image it uses (its crop), on a mid-grey
@@ -330,6 +332,7 @@ function LayerRow({
const { doc, commit, select, busyJob, failedJob, openTool, setSplitTarget, setMode, mode } = useEditor();
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(node.name);
+ const [savingElement, setSavingElement] = useState(false);
const job = busyJob(node.id);
// A failed run stays on its row until it's dismissed (its layer card or tool form says why).
const failed = busy ? undefined : failedJob(node.id);
@@ -439,6 +442,9 @@ function LayerRow({
<DropdownMenuItem onSelect={() => void downloadLayer(doc, node).catch(() => toast.error("Could not download the layer."))}>
<Download /> Download
</DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setTimeout(() => setSavingElement(true))}>
+ <BookmarkPlus /> Save as element
+ </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => {
@@ -477,6 +483,7 @@ function LayerRow({
</DropdownMenuContent>
</DropdownMenu>
</div>
+ {savingElement && <SaveElementDialog node={node} open onOpenChange={setSavingElement} />}
</li>
);
}
diff --git a/src/components/layers/save-element.tsx b/src/components/layers/save-element.tsx
new file mode 100644
index 00000000..cfd6822a
--- /dev/null
+++ b/src/components/layers/save-element.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { AtSign, BookmarkPlus, Loader2 } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { 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 { Input } from "@/components/ui/input";
+import { useSaveElement } from "@/lib/api";
+import { bboxFromAlpha, elementDraft, LAYER_ELEMENT_KINDS, type LayerElementKind, type LayerNode } from "@/lib/layers";
+import { Field, Segmented } from "./bits";
+import { LayerThumb } from "./layers-panel";
+import { renderNative, uploadRender } from "./render";
+
+/** The layer alone at its own detail (mask applied), trimmed to its visible pixels; null when it's empty. */
+async function layerPng(node: LayerNode): Promise<HTMLCanvasElement | null> {
+ const c = await renderNative(node, 2048);
+ const box = bboxFromAlpha(c.getContext("2d")!.getImageData(0, 0, c.width, c.height).data, c.width, c.height, 8);
+ if (!box) return null;
+ if (box[2] === c.width && box[3] === c.height) return c;
+ const out = document.createElement("canvas");
+ out.width = box[2];
+ out.height = box[3];
+ out.getContext("2d")!.drawImage(c, box[0], box[1], box[2], box[3], 0, 0, box[2], box[3]);
+ return out;
+}
+
+/**
+ * Save as element (from a layer's menu): the layer's PNG, transparency kept, becomes an @character,
+ * prop or style that any prompt can mention.
+ */
+export function SaveElementDialog({ node, open, onOpenChange }: { node: LayerNode; open: boolean; onOpenChange: (v: boolean) => void }) {
+ const router = useRouter();
+ const save = useSaveElement();
+ const [draft] = useState(() => elementDraft(node));
+ const [name, setName] = useState(draft.name);
+ const [kind, setKind] = useState<LayerElementKind>(draft.kind);
+ const [busy, setBusy] = useState(false);
+ const info = LAYER_ELEMENT_KINDS.find((k) => k.kind === kind)!;
+
+ const submit = async () => {
+ if (!name.trim()) return;
+ setBusy(true);
+ try {
+ const png = await layerPng(node);
+ if (!png) throw new Error("This layer has nothing visible to save");
+ const url = await uploadRender(png, `element-${name}`);
+ const el = await save.mutateAsync({ name: name.trim(), kind, ...(draft.description ? { description: draft.description } : {}), references: [url] });
+ onOpenChange(false);
+ toast.success(`Saved as @${el.handle}`, { description: `${info.label} · use it in any prompt`, action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } });
+ } catch (e) {
+ toast.error((e as Error).message || "Couldn't save the element");
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !busy && onOpenChange(v)}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Save as element</DialogTitle>
+ <DialogDescription>
+ The layer&apos;s picture (transparency kept) becomes a reusable element. Mention it with <AtSign className="inline size-3" />
+ its name in any prompt to bring it back.
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ className="space-y-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void submit();
+ }}
+ >
+ <div className="flex items-center gap-3 rounded-lg bg-muted/70 p-2.5">
+ <LayerThumb node={node} className="size-14" />
+ <p className="min-w-0 flex-1 truncate text-[13px]">
+ From <span className="font-medium">{node.name}</span>
+ </p>
+ </div>
+ <Field label="Name" htmlFor="element-name">
+ <Input id="element-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} className="h-9" autoFocus />
+ </Field>
+ <Field label="Kind">
+ <Segmented label="Kind" value={kind} onChange={setKind} options={LAYER_ELEMENT_KINDS.map((k) => [k.kind, k.label] as const)} />
+ </Field>
+ <p className="-mt-2 text-[12px] text-muted-foreground">{info.hint}.</p>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
+ Cancel
+ </Button>
+ <Button type="submit" className="rounded-full" disabled={busy || !name.trim()}>
+ {busy ? <Loader2 className="animate-spin" /> : <BookmarkPlus />} Save element
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/layers/stage.tsx b/src/components/layers/stage.tsx
index 955b2f4d..8755527e 100644
--- a/src/components/layers/stage.tsx
+++ b/src/components/layers/stage.tsx
@@ -1,13 +1,13 @@
"use client";
-import { Brush, Eraser, Hand, Maximize, Minus, MousePointer2, Plus } from "lucide-react";
+import { Brush, Eraser, Hand, Maximize, Minus, MousePointer2, Paintbrush, 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 { INPAINT_TINT, resizeBox, rotationTo, toLocal, type Box, type Handle, type LayerDoc, type LayerNode } from "@/lib/layers";
import { cn } from "@/lib/utils";
-import { keysBelongElsewhere, type MaskEdit, type StageMode } from "./editor-context";
+import { keysBelongElsewhere, type MaskEdit, type PaintEdit, type StageMode } from "./editor-context";
import { drawNode, opaqueAt, type Sources } from "./render";
interface View {
@@ -29,6 +29,27 @@ 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" };
+type Geometry = Pick<LayerNode, "x" | "y" | "w" | "h" | "rotation">;
+
+/** The painted area in the tint it's shown (and sent) in, redrawn once per stroke. */
+const tinted = new WeakMap<HTMLCanvasElement, { version: number; canvas: HTMLCanvasElement }>();
+function tintOf(src: HTMLCanvasElement, version: number): HTMLCanvasElement {
+ const hit = tinted.get(src);
+ if (hit?.version === version) return hit.canvas;
+ const c = hit?.canvas ?? document.createElement("canvas");
+ c.width = src.width;
+ c.height = src.height;
+ const ctx = c.getContext("2d")!;
+ ctx.globalCompositeOperation = "source-over";
+ ctx.clearRect(0, 0, c.width, c.height);
+ ctx.drawImage(src, 0, 0);
+ ctx.globalCompositeOperation = "source-in";
+ ctx.fillStyle = INPAINT_TINT;
+ ctx.fillRect(0, 0, c.width, c.height);
+ ctx.globalCompositeOperation = "source-over";
+ tinted.set(src, { version, canvas: c });
+ return c;
+}
export interface StageProps {
doc: LayerDoc;
@@ -43,6 +64,11 @@ export interface StageProps {
setFrame: (r: Box | null) => void;
mask: MaskEdit | null;
onMaskChange: () => void;
+ /** Inpaint's painted area, painted while the mode is "inpaint" and shown tinted over its layer. */
+ paint?: PaintEdit | null;
+ paintVersion?: number;
+ onPaintChange?: () => void;
+ setPaintErase?: (erase: boolean) => void;
brushSize: number;
setBrushSize: (n: number) => void;
highlight: Box | null;
@@ -106,6 +132,13 @@ export function Stage(p: StageProps) {
return p.overlay?.length ? [...list, ...p.overlay] : list;
}, [doc.nodes, live, p.overlay]);
+ /** Where Inpaint's painted area sits: on its layer (as it is moved), else over the whole image. */
+ const paintBox = useMemo<Geometry | null>(() => {
+ if (!p.paint) return null;
+ if (!p.paint.nodeId) return { x: 0, y: 0, w: doc.width, h: doc.height, rotation: 0 };
+ return nodes.find((n) => n.id === p.paint!.nodeId) ?? null;
+ }, [p.paint, nodes, doc.width, doc.height]);
+
// Paint.
useEffect(() => {
const c = canvas.current;
@@ -127,8 +160,14 @@ export function Stage(p: StageProps) {
ctx.clip();
ctx.imageSmoothingQuality = "high";
for (const n of nodes) if (!n.hidden) drawNode(ctx, n, dpr * view.zoom, p.sources, redraw);
+ const pb = paintBox;
+ if (p.paint && pb) {
+ ctx.translate(pb.x + pb.w / 2, pb.y + pb.h / 2);
+ ctx.rotate((pb.rotation * Math.PI) / 180);
+ ctx.drawImage(tintOf(p.paint.canvas, p.paintVersion ?? 0), -pb.w / 2, -pb.h / 2, pb.w, pb.h);
+ }
ctx.restore();
- }, [nodes, view, size, doc.width, doc.height, p.sources, redraw, tick]);
+ }, [nodes, view, size, doc.width, doc.height, p.sources, redraw, tick, p.paint, p.paintVersion, paintBox]);
// Wheel: pinch / ⌘-scroll zooms around the pointer, scrolling pans.
useEffect(() => {
@@ -207,27 +246,34 @@ export function Stage(p: StageProps) {
return undefined;
};
- const paint = (px: number, py: number) => {
+ /** What a stroke paints into: Inpaint's area, or the selected layer's visibility mask. */
+ const strokeTarget = (): { canvas: HTMLCanvasElement; n: Geometry; erase: boolean; done: () => void } | null => {
+ if (mode === "inpaint") return p.paint && paintBox ? { canvas: p.paint.canvas, n: paintBox, erase: p.paint.erase, done: () => p.onPaintChange?.() } : null;
const m = p.mask;
+ const n = m && doc.nodes.find((x) => x.id === m.nodeId);
+ return m && n ? { canvas: m.canvas, n, erase: mode === "eraser", done: p.onMaskChange } : null;
+ };
+
+ const paint = (px: number, py: number) => {
+ const t = strokeTarget();
const d = drag.current;
- if (!m || d?.kind !== "paint") return;
- const n = doc.nodes.find((x) => x.id === m.nodeId);
- if (!n) return;
+ if (!t || d?.kind !== "paint") return;
+ const { n, canvas: target } = t;
// 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";
+ const x = (lx / n.w + 0.5) * target.width;
+ const y = (ly / n.h + 0.5) * target.height;
+ const ctx = target.getContext("2d")!;
+ ctx.globalCompositeOperation = t.erase ? "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.lineWidth = (p.brushSize * target.width) / n.w;
ctx.beginPath();
if (d.last) {
ctx.moveTo(d.last[0], d.last[1]);
@@ -239,7 +285,7 @@ export function Stage(p: StageProps) {
}
ctx.globalCompositeOperation = "source-over";
d.last = [x, y];
- p.onMaskChange();
+ t.done();
};
const onPointerDown = (e: React.PointerEvent) => {
@@ -256,7 +302,7 @@ export function Stage(p: StageProps) {
begin({ kind: "pan", sx: e.clientX, sy: e.clientY, vx: view.x, vy: view.y });
return;
}
- if ((mode === "brush" || mode === "eraser") && p.mask) {
+ if (((mode === "brush" || mode === "eraser") && p.mask) || (mode === "inpaint" && p.paint)) {
begin({ kind: "paint", last: null });
paint(px, py);
return;
@@ -365,8 +411,9 @@ export function Stage(p: StageProps) {
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;
+ const painting = ((mode === "brush" || mode === "eraser") && !!p.mask) || (mode === "inpaint" && !!p.paint);
+ const cursor = space || mode === "hand" ? (dragKind === "pan" ? "grabbing" : "grab") : mode === "region" ? "crosshair" : painting ? "none" : undefined;
+ const maskNode = p.mask ? doc.nodes.find((n) => n.id === p.mask!.nodeId) : mode === "inpaint" && p.paint?.nodeId ? (paintBox ?? undefined) : undefined;
return (
<div className="relative min-h-0 min-w-0 flex-1 overflow-hidden bg-muted/40" style={{ cursor }}>
@@ -452,10 +499,10 @@ export function Stage(p: StageProps) {
</div>
)}
- {maskNode && (mode === "brush" || mode === "eraser") && (
+ {maskNode && (mode === "brush" || mode === "eraser" || mode === "inpaint") && (
<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 && (
+ {pointer && painting && (
<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 }}
@@ -469,9 +516,27 @@ export function Stage(p: StageProps) {
<>
<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") && (
+ {p.paint ? (
+ // Inpaint is open: the brush paints the area to change.
+ <>
+ <ModeButton icon={Paintbrush} label="Paint the area to change" k="B" active={mode === "inpaint" && !p.paint.erase} onClick={() => {
+ p.setPaintErase?.(false);
+ p.setMode("inpaint");
+ }}
+ />
+ <ModeButton icon={Eraser} label="Erase paint" k="E" active={mode === "inpaint" && p.paint.erase} onClick={() => {
+ p.setPaintErase?.(true);
+ p.setMode("inpaint");
+ }}
+ />
+ </>
+ ) : (
+ <>
+ <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" || mode === "inpaint") && (
<div className="flex w-32 shrink-0 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>
diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsx
index a50da179..dbdc018f 100644
--- a/src/components/layers/tools.tsx
+++ b/src/components/layers/tools.tsx
@@ -4,12 +4,15 @@ import {
ArrowLeft,
Crop,
Layers,
+ Eraser,
Loader2,
+ Paintbrush,
Plus,
RefreshCw,
Rotate3d,
Scissors,
SlidersHorizontal,
+ Sparkles,
SquareDashedMousePointer,
Sun,
TriangleAlert,
@@ -34,26 +37,36 @@ import {
addNodes,
addRevision,
ANGLES,
+ bboxFromAlpha,
clampLayers,
DECOMPOSE_COPY,
decomposeCost,
defaultLayers,
+ ENHANCE_LOOKS,
+ enhanceModels,
expandPads,
getNode,
+ INPAINT_SEES_TINT,
+ INPAINT_TINT,
jobStatusText,
LAYER_PRICES,
layersModelFor,
minLayers,
+ nativeSize,
+ needsDetectedSize,
+ placeTextBlocks,
reframeDoc,
RELIGHT_DIRECTIONS,
RELIGHT_LIGHTS,
replaceNodes,
+ scaledSize,
STALL_MS,
textBlocksFrom,
textChanges,
textJobTitle,
TOOL_MODELS,
type Box,
+ type EnhanceLook,
type LayerJob,
type LayerJobInput,
type LayerNode,
@@ -73,7 +86,9 @@ export const TOOLS: { id: ToolId; label: string; icon: typeof Layers; isNew?: bo
{ 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: "inpaint", label: "Inpaint", icon: Paintbrush, isNew: true, hint: "Paint an area, say what goes there" },
{ id: "upscale", label: "Upscale", icon: ZoomIn, hint: "More pixels, sharper detail" },
+ { id: "enhance", label: "Enhancer", icon: Sparkles, isNew: true, hint: "Retouch skin, sharpen, restore 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" },
@@ -107,14 +122,14 @@ function Scope({ node }: { node?: LayerNode }) {
);
}
-function ModelSelect({ tool, value, onChange }: { tool: LayerTool; value?: string; onChange: (id: string) => void }) {
+function ModelSelect({ tool, ids, value, onChange, label = "Model" }: { tool: LayerTool; ids?: string[]; value?: string; onChange: (id: string) => void; label?: string }) {
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;
+ const options = modelsFor(models, ids ?? TOOL_MODELS[tool][engine]);
+ if (options.length < 2) return options[0] ? <p className="text-[12px] text-muted-foreground">{label} · {options[0].name}</p> : null;
return (
- <Field label="Model">
+ <Field label={label}>
<Select value={value ?? options[0].id} onValueChange={onChange}>
- <SelectTrigger className="h-9 w-full rounded-lg" aria-label="Model">
+ <SelectTrigger className="h-9 w-full rounded-lg" aria-label={label}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -130,10 +145,10 @@ function ModelSelect({ tool, value, onChange }: { tool: LayerTool; value?: strin
}
/** The model the tool will run (picked, or the engine's default); `picked` is what the user chose, if anything. */
-function useToolModel(tool: LayerTool) {
+function useToolModel(tool: LayerTool, ids?: string[]) {
const { engine, models } = useEditor();
const [picked, setPicked] = useState<string | undefined>();
- const options = TOOL_MODELS[tool][engine];
+ const options = ids ?? TOOL_MODELS[tool][engine];
const chosen = picked && options.includes(picked) ? picked : undefined;
const id = chosen ?? options[0];
return { modelId: id, model: id ? models[id] : undefined, setModelId: setPicked, picked: chosen };
@@ -430,32 +445,39 @@ function DecomposeTool() {
// Edit text
function EditTextTool() {
- const { engine, models, isDemo, jobs, setHighlight, endJob } = useEditor();
+ const { isDemo, jobs, setHighlight, endJob, engine } = 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 detector = useToolModel("text-detect");
const { busy, go } = useRun();
const [rows, setRows] = useState<{ from: string; to: string; box: Box | null }[]>([]);
const [restored, setRestored] = useState(false);
+ /** The detector answered, but not with lines (shown as a failure to read). */
+ const [unreadable, setUnreadable] = useState(false);
+ /** Lines typed by hand: the fallback when detection can't run or misses one. */
+ const [typing, setTyping] = useState(false);
/** The detection whose rows are in the list (set once they've loaded). */
const [loadedFor, setLoadedFor] = useState<string | null>(null);
- // Rows from the newest finished detection (boxes measured on its image, placed in its frame). A
- // refetch (or React's strict-mode re-run) mid-load just loads it again.
+ // Rows from the newest finished detection, laid out in the frame it read. Pixel boxes are measured
+ // against what was read: Ideogram's returned background, else (an OCR answer without a size) the
+ // picture that was sent. A refetch (or React's strict-mode re-run) mid-load just loads it again.
useEffect(() => {
if (!detect || detect.result?.status !== "succeeded" || loadedFor === detect.id) return;
const out = detect.result.outputs[0];
+ const sent = typeof detect.settings?.image === "string" ? detect.settings.image : undefined;
+ const measure = out?.kind === "image" ? out.url : needsDetectedSize(out?.meta) ? sent : undefined;
let gone = false;
- void (out ? loadImage(out.url).then((img) => sizeOf(img)) : Promise.reject(new Error("no output")))
+ void (measure ? loadImage(measure).then((img) => sizeOf(img)) : Promise.resolve(undefined))
.catch(() => undefined)
.then((natural) => {
if (gone) return;
const blocks: TextBlock[] = out ? 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 })));
+ setRows(placeTextBlocks(blocks, detect.frame));
+ setUnreadable(!!out?.meta?.unreadable);
setRestored(detect.state === "applied");
setLoadedFor(detect.id);
if (detect.state === "pending") endJob(detect.id, "applied");
@@ -467,41 +489,58 @@ function EditTextTool() {
useEffect(() => () => setHighlight(null), [setHighlight]);
const changes = textChanges(rows);
- const detecting = detect && isRunning(detect);
+ const detecting = !!detect && isRunning(detect);
+ const detectCost = costLabel(detector.model, isDemo(detector.model));
const startDetect = () => {
setLoadedFor(null);
setRestored(false);
- void go({ tool: "text-detect", target, label: "Detect text" });
+ setUnreadable(false);
+ void go({ tool: "text-detect", target, modelId: detector.modelId, label: "Detect text" });
+ };
+ const addLine = () => {
+ setTyping(true);
+ setRows([...rows, { from: "", to: "", box: null }]);
};
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) });
+ const listed = rows.length > 0 || typing;
+ const found = detect?.result?.status === "succeeded" && loadedFor === detect.id;
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" && loadedFor === detect.id && !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>
+ {!rows.length && (
+ <div className="space-y-2">
+ <ModelSelect tool="text-detect" value={detector.modelId} onChange={detector.setModelId} label="Detector" />
+ {detector.model && TOOL_MODELS["text-detect"][engine].length > 1 && <p className="text-[11px] text-pretty text-subtle-foreground">{detector.model.tagline}</p>}
+ <Button variant="secondary" className="w-full rounded-full" onClick={startDetect} disabled={busy || detecting || !detector.model}>
+ {detecting ? <Loader2 className="animate-spin" /> : <Type />} {detecting ? "Reading the text…" : "Detect text"}
+ </Button>
+ <p className="text-center font-mono text-[11px] text-subtle-foreground">{detectCost}</p>
+ {detector.model?.engine === "open" && !detecting && <p className="text-center text-[11px] text-pretty text-subtle-foreground">Reads the lines on your ComfyUI: seconds on a GPU, a few minutes on a CPU.</p>}
+ {detecting && <JobState job={detect} />}
+ {found && !rows.length && (
+ <p className="text-center text-[12px] text-muted-foreground" role="status">
+ {unreadable ? "Could not read the text on this image." : "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} />}
+ {!typing && (
+ <button type="button" className="mx-auto block text-[12px] font-medium text-brand-text hover:underline" onClick={addLine}>
+ Type the lines instead
+ </button>
+ )}
+ </div>
)}
{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") && (
+ {listed && (
<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 ? (
+ {!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}>
@@ -516,37 +555,35 @@ function EditTextTool() {
className={cn("h-8 text-[13px]", r.to.trim() !== r.from.trim() && "border-primary")}
/>
</div>
- {engine === "open" && (
+ {!r.box && (
<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>
- )}
+ <li>
+ <Button size="sm" variant="ghost" className="rounded-full" onClick={addLine}>
+ <Plus /> Add a line
+ </Button>
+ </li>
</ol>
)}
- {(rows.length > 0 || engine === "open") && (
+ {listed && (
<>
<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>
- )}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon" aria-label={found ? "Detect text again" : "Detect text"} onClick={startDetect} disabled={busy || detecting || !detector.model}>
+ {detecting ? <Loader2 className="animate-spin" /> : <RefreshCw />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {found ? "Detect again" : "Detect text"} · {detectCost}
+ </TooltipContent>
+ </Tooltip>
<div className="flex-1">
<RunRow cost={costLabel(model, isDemo(model))} busy={busy} disabled={!changes.length || (editJob && isRunning(editJob))} onClick={generate}>
<Wand2 /> Generate
@@ -818,6 +855,183 @@ function RegionalTool() {
);
}
+// ---------------------------------------------------------------------------
+// Inpaint (brush an area, say what goes there)
+
+/** A blank canvas of a size. */
+function blankCanvas(w: number, h: number): [HTMLCanvasElement, CanvasRenderingContext2D] {
+ const c = document.createElement("canvas");
+ c.width = w;
+ c.height = h;
+ return [c, c.getContext("2d")!];
+}
+
+function InpaintTool() {
+ const { doc, isDemo, jobs, setMode, mode, paint, setPaint, paintVersion, brushSize, setBrushSize } = useEditor();
+ const { target, node } = useTarget();
+ const { modelId, model, setModelId } = useToolModel("inpaint");
+ const [prompt, setPrompt] = useState("");
+ const [keepAlpha, setKeepAlpha] = useState(!!node && node.z > 0);
+ const [painted, setPainted] = useState<Box | null>(null);
+ const { busy, go } = useRun();
+ const [preparing, setPreparing] = useState(false);
+ const job = latestJob(jobs, ["inpaint"], node?.id ?? null);
+ // The painted area matches the picture the tool sends: the layer at its own detail, or the composite (≤ 2048 px).
+ const [pw, ph] = node ? nativeSize(node, 2048) : scaledSize(doc.width, doc.height, Math.min(1, 2048 / Math.max(doc.width, doc.height)));
+ const surface = `${node ? `${node.id}|${node.src}|${node.crop?.join(",")}` : "whole"}|${pw}x${ph}`;
+
+ useEffect(() => {
+ setMode("inpaint");
+ return () => {
+ setMode("select");
+ setPaint(null);
+ };
+ }, [setMode, setPaint]);
+ // A fresh area for each layer (or the whole image) it's painted on.
+ const nodeId = node?.id;
+ useEffect(() => {
+ // (The measuring below then finds it empty.) `surface` names the picture: a new revision starts afresh too.
+ setPaint({ nodeId, canvas: blankCanvas(pw, ph)[0], erase: false });
+ }, [surface, nodeId, pw, ph, setPaint]);
+ // What's painted, measured once the strokes pause.
+ useEffect(() => {
+ if (!paint) return;
+ const t = setTimeout(() => {
+ const c = paint.canvas;
+ setPainted(bboxFromAlpha(c.getContext("2d")!.getImageData(0, 0, c.width, c.height).data, c.width, c.height, 8));
+ }, 150);
+ return () => clearTimeout(t);
+ }, [paint, paintVersion]);
+
+ const clear = () => {
+ if (!paint) return;
+ paint.canvas.getContext("2d")!.clearRect(0, 0, paint.canvas.width, paint.canvas.height);
+ setPaint({ ...paint });
+ setPainted(null);
+ };
+
+ const run = async () => {
+ if (!paint || !painted) return;
+ setPreparing(true);
+ try {
+ // The picture, its mask (white = change) and, for models without a mask input, the picture tinted where painted.
+ const picture = node ? await renderNative(node, 2048) : await renderDoc(doc, { scale: paint.canvas.width / doc.width });
+ const { width: W, height: H } = picture;
+ const [mask, m] = blankCanvas(W, H);
+ m.fillStyle = "#000";
+ m.fillRect(0, 0, W, H);
+ m.drawImage(paint.canvas, 0, 0, W, H);
+ const [tint, t] = blankCanvas(W, H);
+ t.drawImage(paint.canvas, 0, 0, W, H);
+ t.globalCompositeOperation = "source-in";
+ t.fillStyle = INPAINT_TINT;
+ t.fillRect(0, 0, W, H);
+ const [sketch, sk] = blankCanvas(W, H);
+ sk.drawImage(picture, 0, 0);
+ sk.drawImage(tint, 0, 0);
+ const name = node?.name ?? "image";
+ const [image, maskUrl, sketchUrl] = await Promise.all([uploadRender(picture, `inpaint-${name}`), uploadRender(mask, `inpaint-mask-${name}`), uploadRender(sketch, `inpaint-marked-${name}`)]);
+ await go({ tool: "inpaint", target, image, mask: maskUrl, sketch: sketchUrl, modelId, prompt: prompt.trim(), settings: { keepAlpha: !!node && keepAlpha }, label: "Inpaint" });
+ } catch (e) {
+ toast.error((e as Error).message || "Couldn't prepare the painted area");
+ } finally {
+ setPreparing(false);
+ }
+ };
+
+ const erase = !!paint?.erase;
+ return (
+ <div className="space-y-4">
+ <Scope node={node} />
+ <HowItWorks>Paint over what you want to change, then say what goes there. Only the painted area changes; the rest stays as it is.</HowItWorks>
+ <Field label="Brush" hint={`${brushSize} px`}>
+ <div className="space-y-2.5">
+ <Segmented
+ label="Brush"
+ value={mode === "inpaint" && erase ? "erase" : "paint"}
+ onChange={(v) => {
+ if (paint) setPaint({ ...paint, erase: v === "erase" });
+ setMode("inpaint");
+ }}
+ options={[
+ ["paint", "Paint"],
+ ["erase", "Erase"],
+ ]}
+ />
+ <Slider aria-label="Brush size" min={4} max={Math.max(64, Math.round(Math.max(doc.width, doc.height) / 6))} step={1} value={[brushSize]} onValueChange={([v]) => setBrushSize(v)} />
+ </div>
+ </Field>
+ <p className="flex items-center justify-between gap-2 text-[12px] text-muted-foreground" role="status">
+ {painted ? <span>Painted area {Math.round((painted[2] * (node?.w ?? doc.width)) / (paint?.canvas.width || 1))} × {Math.round((painted[3] * (node?.h ?? doc.height)) / (paint?.canvas.height || 1))}</span> : <span>Paint on the canvas — the area shows in red.</span>}
+ {painted && (
+ <button type="button" className="shrink-0 hover:text-foreground hover:underline" onClick={clear}>
+ <Eraser className="mr-1 inline size-3" />
+ Clear
+ </button>
+ )}
+ </p>
+ <Field label="What goes there" htmlFor="inpaint-prompt">
+ <Textarea
+ id="inpaint-prompt"
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ maxLength={2000}
+ placeholder="e.g. “a vase of white tulips”, or “remove it, fill in the background”"
+ className="min-h-16 text-[13px]"
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && painted && prompt.trim()) void run();
+ }}
+ />
+ </Field>
+ <ModelSelect tool="inpaint" value={modelId} onChange={setModelId} />
+ {model && <p className="-mt-2 text-[11px] text-subtle-foreground">{INPAINT_SEES_TINT.has(model.id) ? `${model.name} has no mask input: it's shown the painted area tinted red.` : `${model.name} takes the painted mask itself.`}</p>}
+ <KeepAlpha node={node} value={keepAlpha} onChange={setKeepAlpha} />
+ <JobState job={job} failedTitle="Couldn't inpaint it" onRetry={() => void run()} />
+ <RunRow cost={costLabel(model, isDemo(model))} busy={busy || preparing} disabled={!painted || !prompt.trim() || !model || (!!job && isRunning(job))} onClick={() => void run()}>
+ <Paintbrush /> Inpaint
+ </RunRow>
+ {!painted ? <p className="text-[11px] text-subtle-foreground">Paint the area first{prompt.trim() ? "" : ", then describe it"}.</p> : !prompt.trim() && <p className="text-[11px] text-subtle-foreground">Say what should fill the painted area.</p>}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Enhancer (retouch, sharpen, detail)
+
+function EnhanceTool() {
+ const { engine, isDemo, jobs } = useEditor();
+ const { target, node } = useTarget();
+ const [look, setLook] = useState<EnhanceLook>("skin");
+ const info = ENHANCE_LOOKS.find((l) => l.id === look)!;
+ const { modelId, model, setModelId } = useToolModel("enhance", enhanceModels(look, engine));
+ const [extra, setExtra] = useState("");
+ const [keepAlpha, setKeepAlpha] = useState(!!node && node.z > 0);
+ const { busy, go } = useRun();
+ const job = latestJob(jobs, ["enhance"], node?.id ?? null);
+ const detail = look === "detail";
+ const run = () => void go({ tool: "enhance", target, modelId, prompt: detail ? undefined : extra.trim() || undefined, settings: { look, keepAlpha: !detail && !!node && keepAlpha }, label: info.verb });
+ return (
+ <div className="space-y-4">
+ <Scope node={node} />
+ <Field label="Enhance">
+ <Chips label="Enhance" value={look} options={ENHANCE_LOOKS.map((l) => l.id)} names={(id) => ENHANCE_LOOKS.find((l) => l.id === id)!.label} onChange={setLook} />
+ </Field>
+ <p className="-mt-2 text-[12px] text-pretty text-muted-foreground">{info.hint}.</p>
+ {!detail && (
+ <Field label="Anything else (optional)" htmlFor="enhance-extra">
+ <Input id="enhance-extra" value={extra} onChange={(e) => setExtra(e.target.value)} maxLength={300} placeholder="e.g. “keep the freckles”" className="h-9" />
+ </Field>
+ )}
+ <ModelSelect tool="enhance" ids={enhanceModels(look, engine)} value={modelId} onChange={setModelId} />
+ {!detail && <KeepAlpha node={node} value={keepAlpha} onChange={setKeepAlpha} />}
+ <JobState job={job} failedTitle="Couldn't enhance it" onRetry={run} />
+ <RunRow cost={costLabel(model, isDemo(model))} busy={busy} disabled={!model || (!!job && isRunning(job))} onClick={run}>
+ <Sparkles /> {info.verb}
+ </RunRow>
+ </div>
+ );
+}
+
// ---------------------------------------------------------------------------
// Expand & Crop
@@ -1094,11 +1308,14 @@ export function ToolRail() {
</SimpleTool>
)}
{tool === "regional" && <RegionalTool />}
+ {/* Its painted area belongs to one layer (or the whole image): picking another starts afresh. */}
+ {tool === "inpaint" && <InpaintTool key={selected?.id ?? "whole"} />}
{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 === "enhance" && <EnhanceTool key={selected?.id ?? "whole"} />}
{tool === "relight" && <RelightTool />}
{tool === "angles" && <AnglesTool />}
{tool === "expand" && <ExpandTool />}
diff --git a/src/lib/layers.ts b/src/lib/layers.ts
index cdac73ef..8ed5404f 100644
--- a/src/lib/layers.ts
+++ b/src/lib/layers.ts
@@ -248,26 +248,29 @@ export const TOOL_MODELS: Record<LayerTool, { cloud: string[]; open: string[] }>
export type EnhanceLook = "skin" | "glow" | "sharpen" | "detail";
/** The looks: what each does, and the instruction an edit model gets (Detail has none: an upscaler restores it). */
-export const ENHANCE_LOOKS: { id: EnhanceLook; label: string; hint: string; prompt?: string }[] = [
+export const ENHANCE_LOOKS: { id: EnhanceLook; label: string; verb: string; hint: string; prompt?: string }[] = [
{
id: "skin",
label: "Skin",
+ verb: "Retouch skin",
hint: "A natural retouch: blemishes and redness even out, pores and freckles stay",
prompt: "Give the portrait a subtle natural retouch: even out redness and blemishes while keeping every pore, freckle and fine line.",
},
{
id: "glow",
label: "Soft glow",
+ verb: "Add a soft glow",
hint: "A soft beauty retouch with a healthy, dewy glow",
prompt: "Give the portrait a soft beauty retouch with a healthy dewy glow, still keeping real pore texture.",
},
{
id: "sharpen",
label: "Sharpen",
+ verb: "Sharpen",
hint: "Removes blur and noise, restores crisp edges",
prompt: "Sharpen the image: remove blur, noise and compression artefacts and restore crisp detail in edges, eyes, hair, fabric and text.",
},
- { id: "detail", label: "Detail", hint: "An upscaler rebuilds fine detail: twice the pixels, same place on the canvas" },
+ { id: "detail", label: "Detail", verb: "Restore detail", hint: "An upscaler rebuilds fine detail: twice the pixels, same place on the canvas" },
];
/** The upscalers behind the Detail look (the Upscale tool's, Topaz with its face pass first). */
@@ -1020,6 +1023,9 @@ export function placeTextBlocks(blocks: TextBlock[], frame: Box): (TextRow & { b
/** The painted area on the picture handed to edit models without a mask input (the Inpaint studio's red). */
export const INPAINT_TINT = "rgba(255, 59, 48, 0.55)";
+/** Inpaint models with no mask input: they're shown the painted area tinted red instead. */
+export const INPAINT_SEES_TINT = new Set(["nano-banana-pro"]);
+
/** The instruction an Inpaint run sends: what goes in the painted area, and that nothing else changes. */
export function inpaintPrompt(prompt: string, keepAlpha = false): string {
const p = prompt.trim().replace(/[.\s]+$/, "");