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.

Layout N7-2: Layout mode in the Image studio, its editor, Reuse and Edit layout

Claude7ef14c5caa7a
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 611ec13c..3112b5e5 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArrowUp, AtSign, GalleryHorizontalEnd, Loader2, Sparkles, X } from "lucide-react";
+import { ArrowUp, AtSign, GalleryHorizontalEnd, LayoutDashboard, Loader2, Sparkles, X } from "lucide-react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -9,7 +9,7 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Kbd } from "@/components/ui/kbd";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";
+import { estimateCost, layoutCanvas, planGeneration, routesFor, type Plan } from "@/lib/catalog/plan";
import type { Engine, GenerationRequest, MediaKind, ModelDef, Operation, Preset, VideoFormat } from "@/lib/catalog/types";
import { dualEngine } from "@/lib/catalog/engines";
import { locksByDefault } from "@/lib/catalog/palettes";
@@ -41,6 +41,7 @@ import {
costLabel,
engineSwitchModel,
enterFrames,
+ enterLayout,
filterModels,
firstMissingSlot,
followEngineParams,
@@ -48,7 +49,12 @@ import {
framesShape,
framesSlots,
framesUploading,
+ layoutModelNote,
+ layoutRequest,
+ layoutShape,
+ layoutSizeWarning,
leaveFrames,
+ leaveLayout,
namedImageSlots,
needsMask,
onImageChange,
@@ -69,6 +75,7 @@ import { AttachMenu } from "./attach-menu";
import { useAttach, useComposerBridge, useUploadReaper } from "./attachments";
import { DialogueEditor, LanguageChip, VoicePicker } from "./audio-controls";
import { FramesStrip, type FramesNotice } from "./frames-strip";
+import { LayoutStrip } from "./layout-strip";
import { loadFullCatalog, useCatalog } from "./catalog";
import { Chip, chipBase, chipIdle } from "./chip";
import { MediaSlot, SlotPreview, type SlotValue } from "./media-slot";
@@ -91,6 +98,12 @@ const PresetChips = dynamic(() => import("./preset-chips"), {
loading: () => <span aria-hidden className="h-8 w-32 shrink-0 animate-pulse rounded-full bg-secondary" />,
});
+/** Layout mode's editor (the canvas, the boxes and their rows): its own chunk, loaded when Layout is turned on. */
+const LayoutEditor = dynamic(() => import("./layout-editor").then((m) => m.LayoutEditor));
+
+/** The model Layout mode suggests where the picked one reads boxes as words: MOSS-Image on each engine. */
+const BOX_MODELS: Record<Engine, string> = { open: "oss-moss-image", cloud: "moss-image" };
+
/** Fuobe Soul's Look picker (the look cards): its own chunk. */
const LookChip = dynamic(() => import("./look-chip"), {
loading: () => <span aria-hidden className="h-8 w-28 shrink-0 animate-pulse rounded-full bg-secondary" />,
@@ -121,7 +134,7 @@ interface FramesContext {
function buildRequest(
feature: string,
- draft: Pick<Draft, "slots" | "refs" | "presetId" | "modelId" | "prompt" | "negativePrompt" | "params" | "presetOptions" | "presetStrength" | "mix" | "frames">,
+ draft: Pick<Draft, "slots" | "refs" | "presetId" | "modelId" | "prompt" | "negativePrompt" | "params" | "presetOptions" | "presetStrength" | "mix" | "frames" | "layout">,
op: Operation | undefined,
promptSuffix?: string,
refKind: MediaKind = "image",
@@ -147,6 +160,8 @@ function buildRequest(
params = { ...params, ...sent.params };
pinned = op ?? sent.op;
}
+ // Layout mode: the boxes ride as params.extra.layout, captioned with the prompt; the plan compiles them for the model.
+ if (draft.layout) params = layoutRequest(draft.layout, draft.prompt, params).params;
return {
feature,
presetId: draft.presetId,
@@ -372,6 +387,9 @@ export function Composer({ docked }: { docked: boolean }) {
const framesAt = framesCtx && draft.frames ? frameTimes(draft.frames.map((f) => f.at), framesCtx.duration) : [];
// The open chain's gaps (and one frame's clip) must be clips its model makes; the planner checks two or more frames too.
const framesGap = framesCtx?.chained && model && framesAt.length ? chainGapProblem(framesAt, framesCtx.duration, chainTiming(model)) : null;
+ // Layout mode (Image studio): boxes on the picture, one row each, compiled for the model at the size it renders.
+ const layoutOn = !!config.layout && !!draft.layout;
+ const [layoutEditing, setLayoutEditing] = useState(false);
// The page's drop zone hands its files to this composer.
useEffect(() => {
@@ -416,6 +434,8 @@ export function Composer({ docked }: { docked: boolean }) {
// The run goes to a LoRA endpoint whose price isn't published (fal's MOSS-Image /lora).
let loraPriceUnknown = false;
let planError: string | null = null;
+ // What the plan made of the layout: the form the model reads it in and the canvas it was compiled at.
+ let laid: Plan["layout"];
if (model && !engineError && !presetLoading) {
try {
const stand = (v: SlotValue | null | undefined, kind: MediaKind): SlotValue | null | undefined => (v?.uploading ? { ...v, ref: PLACEHOLDER[kind] } : v);
@@ -433,6 +453,7 @@ export function Composer({ docked }: { docked: boolean }) {
});
const plan = planGeneration({ ...planned, prompt: planned.prompt || (config.promptOptional ? " " : "") }, catalog.getModel, catalog.getPreset);
op = plan.op;
+ laid = plan.layout;
// A run with LoRAs (a Soul look) goes to the route's LoRA endpoint, which has its own price.
const withLoras = plan.loras.length > 0 && routesFor(plan.model, plan.op).some((r) => !!r.loraEndpoint);
cost = estimateCost(plan.model, plan.params, plan.jobs, plan.op, withLoras);
@@ -452,7 +473,15 @@ export function Composer({ docked }: { docked: boolean }) {
if (signed.blocker) planError = signed.blocker;
// Models that take no prompt (try-on, 3D, transcription, upscalers), or can run without one, never ask for one.
const promptMissing =
- !config.promptOptional && !opts.promptless && !opts.promptOptional && preset?.userPrompt !== "none" && preset?.userPrompt !== "optional" && !draft.prompt.trim() && !draft.params.shots?.some((s) => s.prompt.trim());
+ !config.promptOptional &&
+ !opts.promptless &&
+ !opts.promptOptional &&
+ preset?.userPrompt !== "none" &&
+ preset?.userPrompt !== "optional" &&
+ !draft.prompt.trim() &&
+ !draft.params.shots?.some((s) => s.prompt.trim()) &&
+ // Boxes say what the picture holds: the whole picture's caption can stay empty.
+ !(layoutOn && draft.layout!.items.length > 0);
const blocker = blockerFor({
// A model outside the studio's slice (remembered, or handed over) is known once the full catalog arrives: loading until then, not "Pick a model".
loading: !catalog.ready || (!model && !catalog.complete) ? "Loading models…" : presetLoading ? "Loading presets…" : null,
@@ -542,7 +571,7 @@ export function Composer({ docked }: { docked: boolean }) {
};
// Enhance writes a scene; a tool's optional words (FLUX.3 Upscale's details) stay as typed.
const baseShape = settingsShape(model, effectiveOp, config.kind, showPrompt && !config.hidePrompt, p, config.ops, studioFormats);
- const shape = framesCtx ? framesShape(baseShape, framesCtx.chained) : baseShape;
+ const shape = framesCtx ? framesShape(baseShape, framesCtx.chained) : layoutOn ? layoutShape(baseShape) : baseShape;
const outcome = config.clipFacts && draft.slots.video?.ref ? clipOutcome(effectiveOp, facts, p, model) : null;
const video = draft.slots.video?.ref;
const alternative = config.comfyOnly?.alternative;
@@ -640,6 +669,53 @@ export function Composer({ docked }: { docked: boolean }) {
if (dropped) toast(`Frames off — frames 1 and ${draft.frames.length} are your start and end frames`, { action: { label: "Undo", onClick: () => setDraft(before) } });
};
+ // Layout on: an empty layout on the picture's shape, and the editor opens to draw the first box. Off: the boxes go (Undo
+ // brings them back); the prompt stays as written.
+ const toggleLayout = () => {
+ if (!draft.layout) {
+ setDraft((d) => ({ layout: enterLayout(d.params, model) }));
+ setLayoutEditing(true);
+ setFocused(true);
+ return;
+ }
+ const before = { layout: draft.layout, params: draft.params };
+ const { params, dropped } = leaveLayout(draft.layout, draft.params);
+ setDraft({ layout: undefined, params });
+ if (dropped) toast(`Layout off — ${dropped} box${dropped === 1 ? "" : "es"} set aside`, { id: "layout-off", action: { label: "Undo", onClick: () => setDraft(before) } });
+ };
+ // The canvas the boxes are drawn on: the size this model renders (src/lib/catalog/plan.ts layoutCanvas).
+ const canvasFor = (aspect: string | undefined) => layoutCanvas(model!, { ...draft.params, aspectRatio: aspect }, studioOp ?? "t2i");
+ const layoutCanvasNow = layoutOn && model ? canvasFor(p.aspectRatio ?? model.defaults?.aspectRatio) : undefined;
+ const boxModel = layoutOn && model && layoutModelNote(model) ? catalog.getModel(BOX_MODELS[model.engine]) : undefined;
+ const layoutNotes: { text: string; tone: "info" | "warn" }[] = [];
+ if (layoutOn && model) {
+ const words = layoutModelNote(model);
+ if (words) layoutNotes.push({ text: words, tone: "info" });
+ const big = layoutCanvasNow && layoutSizeWarning(layoutCanvasNow, model.name);
+ if (big) layoutNotes.push({ text: big, tone: "warn" });
+ }
+ const layoutSummary = !model
+ ? ""
+ : laid?.width
+ ? `Compiled for ${model.name} at ${laid.width} × ${laid.height}, the size it renders`
+ : laid?.format === "flux3" || laid?.format === "ideogram"
+ ? `${model.name} reads the boxes in place (its own layout form)`
+ : laid
+ ? `Sent to ${model.name} as sentences`
+ : layoutCanvasNow
+ ? `Drawn at ${layoutCanvasNow.exact ? "" : "about "}${layoutCanvasNow.width} × ${layoutCanvasNow.height}`
+ : "";
+ const layoutChip = config.layout ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Chip icon={LayoutDashboard} active={layoutOn} aria-pressed={layoutOn} onClick={toggleLayout}>
+ Layout
+ </Chip>
+ </TooltipTrigger>
+ <TooltipContent>{layoutOn ? "Back to a plain prompt" : "Draw boxes for where things go, with the exact words"}</TooltipContent>
+ </Tooltip>
+ ) : null;
+
// What the model does with the frames, said under the strip before anything runs (with the model that takes them all).
let framesNotice: FramesNotice | null = null;
if (framesCtx && model && draft.frames) {
@@ -740,6 +816,7 @@ export function Composer({ docked }: { docked: boolean }) {
);
const hasSecondary =
!!config.frames ||
+ !!config.layout ||
(!!model && (!!opts.voices?.length || !!opts.voiceClone || !!opts.languages || !!opts.controls || !!opts.looks)) ||
!!config.presetPicker ||
!!config.signature ||
@@ -790,6 +867,36 @@ export function Composer({ docked }: { docked: boolean }) {
notice={framesNotice}
/>
)}
+ {layoutOn && !collapsed && draft.layout && (
+ <LayoutStrip
+ layout={draft.layout}
+ aspect={p.aspectRatio ?? model?.defaults?.aspectRatio}
+ summary={layoutSummary}
+ notes={layoutNotes}
+ action={boxModel && boxModel.id !== model?.id ? { label: `Use ${boxModel.name}`, onClick: () => pickModel(boxModel) } : undefined}
+ onEdit={() => setLayoutEditing(true)}
+ onClose={toggleLayout}
+ />
+ )}
+ {layoutEditing && layoutOn && draft.layout && model && (
+ <LayoutEditor
+ open
+ onOpenChange={(o) => !o && setLayoutEditing(false)}
+ layout={draft.layout}
+ caption={draft.prompt}
+ aspect={p.aspectRatio ?? model.defaults?.aspectRatio}
+ aspects={model.options.aspectRatios}
+ canvasFor={canvasFor}
+ model={model}
+ onDone={(r) =>
+ setDraft((d) => ({
+ layout: r.layout,
+ prompt: r.caption,
+ ...(r.aspect && r.aspect !== (d.params.aspectRatio ?? model.defaults?.aspectRatio) && { params: { ...d.params, aspectRatio: r.aspect } }),
+ }))
+ }
+ />
+ )}
{showAttachments && !collapsed && !framesOn && (
<div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1.5 pb-2">
{slots.map((s) => (
@@ -845,7 +952,11 @@ export function Composer({ docked }: { docked: boolean }) {
value={draft.prompt}
onChange={(v) => setDraft({ prompt: v })}
onSubmit={submit}
- placeholder={preset?.promptPlaceholder ?? (config.hidePrompt && config.modelPrompt ? config.modelPrompt : config.placeholder)}
+ placeholder={
+ layoutOn
+ ? "Describe the whole picture… the boxes say what goes where"
+ : (preset?.promptPlaceholder ?? (config.hidePrompt && config.modelPrompt ? config.modelPrompt : config.placeholder))
+ }
elements={elements}
collapsed={collapsed}
/>
@@ -948,6 +1059,7 @@ export function Composer({ docked }: { docked: boolean }) {
onEngineChange={setEngine}
defaultModels={config.defaultModels}
onChange={pickModel}
+ boxes={layoutOn}
/>
) : (
<Chip icon={Loader2} disabled className="[&>svg]:animate-spin">
@@ -986,6 +1098,7 @@ export function Composer({ docked }: { docked: boolean }) {
)}
<span className="contents max-sm:hidden">
{framesChip}
+ {layoutChip}
{voiceChips}
</span>
<SettingsChip
@@ -1008,6 +1121,7 @@ export function Composer({ docked }: { docked: boolean }) {
hasSecondary ? (
<>
{framesChip}
+ {layoutChip}
{voiceChips}
{styleChips}
</>
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index 736366f7..3de8b8eb 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -249,8 +249,11 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g:
const single = g.status === "succeeded" && shown.length === 1 ? g.outputs[shown[0]] : null;
const singleName = single ? downloadName(g, single, shown[0]) : "";
const p = g.request.params ?? {};
+ // A layout run says so, with its box count (Edit layout reopens them).
+ const boxes = (p.extra?.layout as { items?: unknown[] } | undefined)?.items?.length;
const meta = [
g.request.step?.label,
+ boxes ? `Layout · ${boxes} box${boxes === 1 ? "" : "es"}` : undefined,
g.presetName,
g.modelName ?? g.modelId,
OPERATION_LABELS[g.op],
diff --git a/src/components/studio/layout-editor.tsx b/src/components/studio/layout-editor.tsx
new file mode 100644
index 00000000..4efc6182
--- /dev/null
+++ b/src/components/studio/layout-editor.tsx
@@ -0,0 +1,636 @@
+"use client";
+
+import { ArrowDownToLine, ClipboardCopy, FileJson, FlaskConical, Import, Plus, Trash2, X } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { copyWithToast } from "@/lib/clipboard";
+import type { ModelDef } from "@/lib/catalog/types";
+import { boxesAt, drawnBox, movedBox, newBox, nudgedBox, pickBox, resizedBox, type Handle } from "@/lib/layout-edit";
+import { layoutCompilerFor, parseLayout, readsBoxes, type LayoutBox, type LayoutCanvas as CanvasType, type LayoutDraft, type LayoutItem, type LayoutLabel, type LayoutSource } from "@/lib/layout-prompt";
+import { cn } from "@/lib/utils";
+import { radioKeys, radioTab } from "./radio-keys";
+
+/**
+ * The Layout editor (Image studio, Layout mode): the picture's canvas in its aspect ratio, a box drawn per element and
+ * one row per box (an object, a character or exact words). Built like the sketch editor (a dialog over the composer);
+ * the box maths is src/lib/layout-edit.ts. Desktop: the rows beside the canvas. Phones: the canvas on top and the rows
+ * in a sheet under it; boxes drag by touch (pointer events, no page scroll on the canvas).
+ */
+
+export interface LayoutEditorResult {
+ layout: LayoutDraft;
+ /** The whole picture in words: the composer's prompt. */
+ caption: string;
+ aspect?: string;
+}
+
+/** The size a canvas renders at, for the editor's pixels, the compiled prompt and the size line. */
+export interface EditorCanvas {
+ width: number;
+ height: number;
+ asked: { width: number; height: number };
+ exact: boolean;
+}
+
+const LABELS: { value: LayoutLabel; label: string }[] = [
+ { value: "object", label: "Object" },
+ { value: "character", label: "Character" },
+ { value: "text", label: "Text" },
+];
+const CANVASES: { value: CanvasType; label: string }[] = [
+ { value: "single", label: "Single" },
+ { value: "multi_panel", label: "Panels" },
+ { value: "collage", label: "Collage" },
+];
+/** Box outlines by kind when a box has no colour of its own. */
+const KIND_COLOR: Record<LayoutLabel, string> = { object: "#0a84ff", character: "#34c759", text: "#ff9f0a" };
+const SOURCE_WORDS: Record<LayoutSource, string> = {
+ fuobe: "a Fuobe layout",
+ linxce: "a ComfyUI layout draft",
+ compiled: "a MOSS-Image prompt",
+ scene: "a scene prompt",
+ elements: "bounding boxes",
+};
+const HANDLES: Handle[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
+const HANDLE_POS: Record<Handle, string> = {
+ nw: "left-0 top-0 cursor-nwse-resize",
+ n: "left-1/2 top-0 cursor-ns-resize",
+ ne: "left-full top-0 cursor-nesw-resize",
+ e: "left-full top-1/2 cursor-ew-resize",
+ se: "left-full top-full cursor-nwse-resize",
+ s: "left-1/2 top-full cursor-ns-resize",
+ sw: "left-0 top-full cursor-nesw-resize",
+ w: "left-0 top-1/2 cursor-ew-resize",
+};
+
+const ratioOf = (aspect: string | undefined) => {
+ const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(aspect ?? "");
+ return m ? Number(m[1]) / Number(m[2]) : 1;
+};
+const colorOf = (it: LayoutItem) => it.color ?? KIND_COLOR[it.label];
+const pct = (v: number) => `${v * 100}%`;
+/** Typing focus: keys there edit text, not boxes. */
+const typing = (el: EventTarget | null) => el instanceof HTMLElement && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
+
+export function LayoutEditor(props: {
+ open: boolean;
+ onOpenChange: (o: boolean) => void;
+ layout: LayoutDraft;
+ caption: string;
+ aspect: string | undefined;
+ /** The aspect ratios the model offers (the canvas can change shape here). */
+ aspects?: string[];
+ /** The canvas the model renders for an aspect ratio. */
+ canvasFor: (aspect: string | undefined) => EditorCanvas;
+ model?: ModelDef;
+ onDone: (r: LayoutEditorResult) => void;
+}) {
+ const content = useRef<HTMLDivElement>(null);
+ const escapeRef = useRef<() => boolean>(() => false);
+ return (
+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>
+ <DialogContent
+ ref={content}
+ showCloseButton={false}
+ aria-describedby="layout-editor-hint"
+ className="flex h-[100svh] w-screen max-w-none flex-col gap-0 overflow-hidden rounded-none p-0 outline-none sm:h-[min(92vh,880px)] sm:w-[min(96vw,1180px)] sm:max-w-none sm:rounded-xl"
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ content.current?.focus();
+ }}
+ onEscapeKeyDown={(e) => {
+ if (escapeRef.current()) e.preventDefault();
+ }}
+ >
+ {props.open && <LayoutBoard {...props} escapeRef={escapeRef} />}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+type Drag =
+ | { mode: "draw"; x0: number; y0: number; x1: number; y1: number; id: number }
+ | { mode: "move"; index: number; box: LayoutBox; sx: number; sy: number; moved: boolean; id: number }
+ | { mode: "resize"; index: number; box: LayoutBox; handle: Handle; sx: number; sy: number; id: number };
+
+function LayoutBoard({
+ onOpenChange,
+ layout,
+ caption: startCaption,
+ aspect: startAspect,
+ aspects,
+ canvasFor,
+ model,
+ onDone,
+ escapeRef,
+}: Parameters<typeof LayoutEditor>[0] & { escapeRef: React.RefObject<() => boolean> }) {
+ const [items, setItems] = useState<LayoutItem[]>(layout.items);
+ const [canvasType, setCanvasType] = useState<CanvasType>(layout.summary.canvas);
+ const [tags, setTags] = useState(layout.summary.meta.join(", "));
+ const [caption, setCaption] = useState(startCaption);
+ const [aspect, setAspect] = useState(startAspect ?? layout.aspect ?? "1:1");
+ const [selected, setSelected] = useState<number | null>(layout.items.length ? 0 : null);
+ const [drag, setDrag] = useState<Drag | null>(null);
+ const [importing, setImporting] = useState(false);
+ const [sheetOpen, setSheetOpen] = useState(true);
+ const board = useRef<HTMLDivElement>(null);
+ const lastPress = useRef<{ x: number; y: number } | null>(null);
+ const size = canvasFor(aspect);
+ const ratio = ratioOf(aspect);
+
+ const draft = useMemo<LayoutDraft>(
+ () => ({
+ summary: {
+ caption: caption.trim(),
+ meta: tags
+ .split(",")
+ .map((t) => t.trim())
+ .filter(Boolean),
+ canvas: canvasType,
+ ...(layout.summary.palette?.length && { palette: layout.summary.palette }),
+ },
+ items,
+ aspect,
+ }),
+ [caption, tags, canvasType, items, aspect, layout.summary.palette],
+ );
+
+ // Escape first lets go of a selected box, then closes the editor (which keeps the boxes).
+ useEffect(() => {
+ escapeRef.current = () => {
+ if (importing) return (setImporting(false), true);
+ if (selected !== null) return (setSelected(null), true);
+ return false;
+ };
+ }, [escapeRef, importing, selected]);
+
+ const finish = () => {
+ onDone({ layout: { ...draft, summary: { ...draft.summary, caption: "" } }, caption, aspect });
+ onOpenChange(false);
+ };
+
+ const patch = (i: number, p: Partial<LayoutItem>) => setItems((xs) => xs.map((x, j) => (j === i ? { ...x, ...p } : x)));
+ const remove = (i: number) => {
+ const before = items;
+ setItems((xs) => xs.filter((_, j) => j !== i));
+ setSelected((s) => (s === null ? null : s === i ? (items.length > 1 ? Math.max(0, i - 1) : null) : s > i ? s - 1 : s));
+ toast(`Box ${i + 1} removed`, { id: "layout-removed", action: { label: "Undo", onClick: () => setItems(before) } });
+ };
+ const add = (box: LayoutBox) => {
+ setItems((xs) => [...xs, { label: "object", caption: "", box }]);
+ setSelected(items.length);
+ setSheetOpen(true);
+ };
+
+ /** Pointer position in canvas pixels. */
+ const at = (e: React.PointerEvent) => {
+ const r = board.current!.getBoundingClientRect();
+ return { x: ((e.clientX - r.left) / r.width) * size.width, y: ((e.clientY - r.top) / r.height) * size.height, sx: e.clientX, sy: e.clientY };
+ };
+
+ const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
+ if (e.button !== 0) return;
+ const handle = (e.target as HTMLElement).closest<HTMLElement>("[data-handle]")?.dataset.handle as Handle | undefined;
+ const p = at(e);
+ board.current?.setPointerCapture(e.pointerId);
+ if (handle && selected !== null) {
+ setDrag({ mode: "resize", index: selected, box: items[selected].box, handle, sx: p.x, sy: p.y, id: e.pointerId });
+ return;
+ }
+ // A box's number tab picks that box; elsewhere a press picks from the boxes under it (again on the same spot: the next one down).
+ const tab = (e.target as HTMLElement).closest<HTMLElement>("[data-box-tab]")?.dataset.boxTab;
+ const stack = boxesAt(
+ items.map((x) => x.box),
+ p.x / size.width,
+ p.y / size.height,
+ );
+ const again = !!lastPress.current && Math.hypot(lastPress.current.x - p.sx, lastPress.current.y - p.sy) < 6;
+ const picked = tab !== undefined ? Number(tab) : pickBox(stack, selected, again);
+ if (picked === null) {
+ lastPress.current = null;
+ setSelected(null);
+ setDrag({ mode: "draw", x0: p.x, y0: p.y, x1: p.x, y1: p.y, id: e.pointerId });
+ return;
+ }
+ setSelected(picked);
+ setDrag({ mode: "move", index: picked, box: items[picked].box, sx: p.x, sy: p.y, moved: false, id: e.pointerId });
+ lastPress.current = { x: p.sx, y: p.sy };
+ };
+
+ const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
+ if (!drag || drag.id !== e.pointerId) return;
+ const p = at(e);
+ if (drag.mode === "draw") return setDrag({ ...drag, x1: p.x, y1: p.y });
+ const dx = p.x - drag.sx;
+ const dy = p.y - drag.sy;
+ if (drag.mode === "move") {
+ if (!drag.moved && Math.hypot(dx, dy) < 3) return;
+ if (!drag.moved) setDrag({ ...drag, moved: true });
+ patch(drag.index, { box: movedBox(drag.box, dx, dy, size.width, size.height) });
+ return;
+ }
+ patch(drag.index, { box: resizedBox(drag.box, drag.handle, dx, dy, size.width, size.height) });
+ };
+
+ const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
+ if (!drag || drag.id !== e.pointerId) return;
+ if (drag.mode === "draw") {
+ const box = drawnBox(drag.x0, drag.y0, drag.x1, drag.y1, size.width, size.height);
+ if (box) add(box);
+ }
+ // A drag isn't a press on the same spot: the next press there picks the top box again.
+ if (drag.mode === "move" && drag.moved) lastPress.current = null;
+ setDrag(null);
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (typing(e.target) || selected === null || !items[selected]) return;
+ if (e.key === "Delete" || e.key === "Backspace") {
+ e.preventDefault();
+ return remove(selected);
+ }
+ const box = nudgedBox(items[selected].box, e.key, e.shiftKey, size.width, size.height);
+ if (box) {
+ e.preventDefault();
+ patch(selected, { box });
+ }
+ };
+
+ const ghost = drag?.mode === "draw" ? drawnBox(drag.x0, drag.y0, drag.x1, drag.y1, size.width, size.height) : null;
+ const compiled = () => layoutCompilerFor(model)(draft, size.width, size.height).prompt;
+ const textErrors = items.map((it) => it.label === "text" && !it.text?.trim());
+ const reads = !model || readsBoxes(model);
+
+ const importText = (text: string): boolean => {
+ const parsed = parseLayout(text, { width: size.width, height: size.height });
+ if (!parsed) {
+ toast.error("No layout found there: paste a Fuobe or ComfyUI layout, a MOSS-Image prompt or bounding boxes");
+ return false;
+ }
+ const before = { items, caption, tags, canvasType, aspect };
+ const own = parsed.draft.aspect && aspects?.includes(parsed.draft.aspect) ? parsed.draft.aspect : undefined;
+ setItems(parsed.draft.items);
+ if (parsed.draft.summary.caption.trim()) setCaption(parsed.draft.summary.caption.trim());
+ if (parsed.draft.summary.meta.length) setTags(parsed.draft.summary.meta.join(", "));
+ setCanvasType(parsed.draft.summary.canvas);
+ if (own) setAspect(own);
+ setSelected(parsed.draft.items.length ? 0 : null);
+ const n = parsed.draft.items.length;
+ toast(`Imported ${n} box${n === 1 ? "" : "es"} from ${SOURCE_WORDS[parsed.from]}`, {
+ id: "layout-import",
+ action: {
+ label: "Undo",
+ onClick: () => {
+ setItems(before.items);
+ setCaption(before.caption);
+ setTags(before.tags);
+ setCanvasType(before.canvasType);
+ setAspect(before.aspect);
+ },
+ },
+ });
+ return true;
+ };
+
+ const rows = (
+ <div className="space-y-3">
+ <div className="space-y-2 rounded-xl border p-3">
+ <label htmlFor="layout-caption" className="text-[12px] font-medium">
+ The whole picture
+ </label>
+ <Textarea id="layout-caption" value={caption} onChange={(e) => setCaption(e.target.value)} rows={2} placeholder="A warm autumn sale poster for a candle shop" className="min-h-0 resize-none text-[13px]" />
+ <div className="flex flex-wrap items-center gap-2">
+ <span id="layout-canvas-label" className="text-[12px] text-muted-foreground">
+ Canvas
+ </span>
+ <Segmented label="Canvas" labelledBy="layout-canvas-label" options={CANVASES} value={canvasType} onChange={setCanvasType} />
+ </div>
+ <Input aria-label="Style tags (optional, comma separated)" value={tags} onChange={(e) => setTags(e.target.value)} placeholder="Style tags (optional): poster, flat design" className="h-8 text-[13px]" />
+ </div>
+ {items.length === 0 && <p className="px-1 text-[13px] text-muted-foreground">Drag on the picture to draw a box for each thing to place: a headline, a product, a person.</p>}
+ {items.map((it, i) => (
+ <BoxRow
+ key={i}
+ index={i}
+ item={it}
+ selected={selected === i}
+ error={textErrors[i]}
+ onSelect={() => setSelected(i)}
+ onChange={(p) => patch(i, p)}
+ onRemove={() => remove(i)}
+ />
+ ))}
+ </div>
+ );
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <header className="flex flex-wrap items-center gap-2 border-b px-3 py-2 sm:px-4">
+ <DialogTitle className="font-heading text-[18px] font-normal">Layout</DialogTitle>
+ <Badge variant="secondary" className="h-5 gap-1 rounded-full px-2 text-[11px]">
+ <FlaskConical className="size-3" /> Experimental
+ </Badge>
+ <div className="ml-auto flex items-center gap-1.5">
+ {aspects && aspects.length > 1 && (
+ <select
+ aria-label="Aspect ratio"
+ value={aspect}
+ onChange={(e) => setAspect(e.target.value)}
+ className="h-8 rounded-full border bg-background px-2.5 text-[13px] focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"
+ >
+ {aspects.filter((a) => a !== "auto").map((a) => (
+ <option key={a} value={a}>
+ {a}
+ </option>
+ ))}
+ </select>
+ )}
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" size="sm" className="h-8 rounded-full px-3 text-[13px]">
+ <FileJson className="size-3.5" /> Import / Export
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-60">
+ <DropdownMenuItem onSelect={() => setImporting(true)}>
+ <Import /> Import a layout…
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem disabled={!items.length} onSelect={() => void copyWithToast(compiled(), `${model?.name ?? "Model"} prompt copied`)}>
+ <ClipboardCopy /> Copy the compiled prompt
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => void copyWithToast(JSON.stringify(draft, null, 2), "Layout copied")}>
+ <ClipboardCopy /> Copy the layout (JSON)
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => downloadJson(draft)}>
+ <ArrowDownToLine /> Download the layout (.json)
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Button size="sm" className="h-8 rounded-full px-4" onClick={finish}>
+ Done
+ </Button>
+ </div>
+ <DialogDescription id="layout-editor-hint" className="w-full text-[12px] leading-snug text-muted-foreground">
+ Drag to draw a box, then say what goes in it. Layout prompts are experimental in MOSS-Image&apos;s own guide: boxes guide the picture, they don&apos;t pin it.
+ </DialogDescription>
+ </header>
+
+ <div className="flex min-h-0 flex-1 flex-col sm:flex-row">
+ {/* The canvas, in the picture's shape. */}
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 bg-muted/40 p-3 sm:p-5">
+ <div className="relative flex min-h-0 w-full flex-1 items-center justify-center" style={{ containerType: "size" }}>
+ <div
+ ref={board}
+ role="application"
+ aria-label={`Layout canvas, ${size.width} by ${size.height}: drag to draw a box. With a box picked, arrow keys move it and Delete removes it.`}
+ tabIndex={0}
+ data-layout-canvas
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={() => setDrag(null)}
+ onKeyDown={onKeyDown}
+ className="relative touch-none rounded-md border-2 border-dashed border-border-strong bg-background bg-[linear-gradient(to_right,var(--border)_1px,transparent_1px),linear-gradient(to_bottom,var(--border)_1px,transparent_1px)] bg-[size:33.333%_33.333%] select-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:outline-none"
+ style={{ aspectRatio: `${ratio}`, width: `min(100cqw, calc(100cqh * ${ratio}))` }}
+ >
+ {items.map((it, i) => (
+ <div
+ key={i}
+ data-layout-box={i + 1}
+ className={cn("absolute rounded-[3px] border-2", selected === i ? "z-10 shadow-[0_0_0_2px_var(--background)]" : "opacity-90")}
+ style={{ left: pct(it.box[0]), top: pct(it.box[1]), width: pct(it.box[2] - it.box[0]), height: pct(it.box[3] - it.box[1]), borderColor: colorOf(it), background: `color-mix(in oklab, ${colorOf(it)} 14%, transparent)` }}
+ >
+ <button
+ type="button"
+ data-box-tab={i}
+ onFocus={() => setSelected(i)}
+ onClick={() => setSelected(i)}
+ aria-label={`Box ${i + 1}: ${it.label === "text" ? `the words ${it.text || "(not typed yet)"}` : it.caption || it.label}`}
+ aria-pressed={selected === i}
+ className="absolute bottom-full -left-0.5 flex h-5 min-w-5 items-center justify-center rounded-t-md px-1.5 text-[11px] leading-none font-semibold text-white focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none [@media(pointer:coarse)]:h-6 [@media(pointer:coarse)]:min-w-7"
+ style={{ background: colorOf(it) }}
+ >
+ {i + 1}
+ </button>
+ <span className="pointer-events-none absolute inset-x-1.5 top-1 line-clamp-2 text-[11px] leading-tight break-words text-foreground/80">
+ {it.label === "text" ? (it.text ? `“${it.text}”` : "") : it.caption}
+ </span>
+ {selected === i &&
+ HANDLES.map((h) => (
+ <span
+ key={h}
+ data-handle={h}
+ aria-hidden
+ className={cn("absolute size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 bg-background [@media(pointer:coarse)]:size-5", HANDLE_POS[h])}
+ style={{ borderColor: colorOf(it) }}
+ />
+ ))}
+ </div>
+ ))}
+ {ghost && (
+ <div
+ className="pointer-events-none absolute rounded-[3px] border-2 border-dashed border-primary bg-primary/10"
+ style={{ left: pct(ghost[0]), top: pct(ghost[1]), width: pct(ghost[2] - ghost[0]), height: pct(ghost[3] - ghost[1]) }}
+ />
+ )}
+ {!items.length && !ghost && (
+ <p className="pointer-events-none absolute inset-0 grid place-items-center p-4 text-center text-[13px] text-muted-foreground">Drag here to draw your first box</p>
+ )}
+ </div>
+ </div>
+ <div className="flex w-full flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12px] text-muted-foreground">
+ <Button variant="ghost" size="sm" className="h-7 gap-1 px-2 text-[12px]" onClick={() => add(newBox(items.length))}>
+ <Plus className="size-3.5" /> Add box
+ </Button>
+ <span className="tabular-nums">
+ {aspect} · {size.exact ? "" : "about "}
+ {size.width} × {size.height}
+ </span>
+ {!reads && <span>This model reads the layout as words, not exact positions.</span>}
+ </div>
+ </div>
+
+ {/* The rows: beside the canvas on desktop, in a sheet under it on phones. */}
+ <aside
+ aria-label="Boxes"
+ className={cn(
+ "flex min-h-0 flex-col border-t bg-popover max-sm:rounded-t-2xl max-sm:shadow-strong sm:w-[380px] sm:border-t-0 sm:border-l",
+ sheetOpen ? "max-sm:max-h-[48svh]" : "max-sm:max-h-12",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => setSheetOpen((v) => !v)}
+ aria-expanded={sheetOpen}
+ className="relative flex h-12 shrink-0 items-center gap-2 px-4 pt-1.5 text-left text-[13px] font-medium sm:hidden"
+ >
+ <span aria-hidden className="absolute top-1.5 left-1/2 h-1 w-10 -translate-x-1/2 rounded-full bg-border-strong" />
+ {items.length ? `${items.length} box${items.length === 1 ? "" : "es"}` : "No boxes yet"}
+ {selected !== null && <span className="text-muted-foreground">· box {selected + 1} picked</span>}
+ <span className="ml-auto text-[12px] text-brand-text">{sheetOpen ? "Hide" : "Show"}</span>
+ </button>
+ <div className={cn("min-h-0 flex-1 overflow-y-auto overscroll-contain p-3 sm:p-4", !sheetOpen && "max-sm:hidden")}>
+ {importing ? <ImportPanel onImport={(t) => importText(t) && setImporting(false)} onCancel={() => setImporting(false)} /> : rows}
+ </div>
+ </aside>
+ </div>
+ </div>
+ );
+}
+
+function downloadJson(draft: LayoutDraft) {
+ const url = URL.createObjectURL(new Blob([JSON.stringify(draft, null, 2)], { type: "application/json" }));
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "layout.json";
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
+function Segmented<T extends string>({ label, labelledBy, options, value, onChange }: { label: string; labelledBy?: string; options: { value: T; label: string }[]; value: T; onChange: (v: T) => void }) {
+ return (
+ <div role="radiogroup" aria-label={labelledBy ? undefined : label} aria-labelledby={labelledBy} onKeyDown={radioKeys} className="inline-flex rounded-full bg-muted p-0.5">
+ {options.map((o) => {
+ const on = o.value === value;
+ return (
+ <button
+ key={o.value}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ tabIndex={radioTab(on)}
+ onClick={() => onChange(o.value)}
+ className={cn(
+ "h-7 rounded-full px-2.5 text-[12px] font-medium transition-colors focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:outline-none",
+ on ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {o.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+function BoxRow({
+ index,
+ item,
+ selected,
+ error,
+ onSelect,
+ onChange,
+ onRemove,
+}: {
+ index: number;
+ item: LayoutItem;
+ selected: boolean;
+ error: boolean;
+ onSelect: () => void;
+ onChange: (p: Partial<LayoutItem>) => void;
+ onRemove: () => void;
+}) {
+ const n = index + 1;
+ const row = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (selected) row.current?.scrollIntoView({ block: "nearest" });
+ }, [selected]);
+ return (
+ <div
+ ref={row}
+ data-layout-row={n}
+ onFocusCapture={onSelect}
+ onPointerDown={onSelect}
+ className={cn("space-y-2 rounded-xl border p-3 transition-colors", selected ? "border-primary bg-brand-faint/50" : "hover:border-border-strong")}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="grid size-6 shrink-0 place-items-center rounded-md text-[12px] font-semibold text-white" style={{ background: colorOf(item) }} aria-hidden>
+ {n}
+ </span>
+ <Segmented label={`Box ${n} is`} options={LABELS} value={item.label} onChange={(label) => onChange({ label, ...(label === "text" ? { text: item.text ?? "" } : {}) })} />
+ <button type="button" onClick={onRemove} aria-label={`Remove box ${n}`} className="ml-auto grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <Trash2 className="size-3.5" />
+ </button>
+ </div>
+ <Input aria-label={`Box ${n}: what it looks like`} value={item.caption} onChange={(e) => onChange({ caption: e.target.value })} placeholder="What it looks like" className="h-8 text-[13px]" />
+ {item.label === "text" && (
+ <div>
+ <Input
+ aria-label={`Box ${n}: exact words`}
+ aria-invalid={error}
+ aria-describedby={error ? `layout-words-${n}` : undefined}
+ value={item.text ?? ""}
+ onChange={(e) => onChange({ text: e.target.value })}
+ placeholder="Exact words, e.g. 30% OFF"
+ className="h-8 text-[13px]"
+ />
+ {error && (
+ <p id={`layout-words-${n}`} className="mt-1 text-[12px] text-destructive">
+ Type the words for box {n}
+ </p>
+ )}
+ </div>
+ )}
+ <div className="flex items-center gap-2 text-[12px] text-muted-foreground">
+ <label className="inline-flex items-center gap-1.5">
+ <input
+ type="color"
+ value={item.color ?? KIND_COLOR[item.label]}
+ onChange={(e) => onChange({ color: e.target.value })}
+ aria-label={`Box ${n}: colour on the canvas (optional)`}
+ className="size-6 cursor-pointer rounded border bg-transparent p-0"
+ />
+ Colour (optional, only on this canvas)
+ </label>
+ {item.color && (
+ <button type="button" onClick={() => onChange({ color: undefined })} className="inline-flex items-center gap-0.5 underline-offset-2 hover:text-foreground hover:underline">
+ <X className="size-3" /> Clear
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function ImportPanel({ onImport, onCancel }: { onImport: (text: string) => void; onCancel: () => void }) {
+ const [text, setText] = useState("");
+ const file = useRef<HTMLInputElement>(null);
+ return (
+ <div className="space-y-2">
+ <p className="text-[13px] font-medium">Import a layout</p>
+ <p className="text-[12px] leading-snug text-muted-foreground">
+ Paste a Fuobe layout, a ComfyUI layout draft, a MOSS-Image prompt (read on this canvas), a scene prompt or CreateBoundingBoxes boxes. It replaces the boxes here.
+ </p>
+ <Textarea aria-label="Layout to import" value={text} onChange={(e) => setText(e.target.value)} rows={8} className="font-mono text-[12px]" placeholder='{"summary": …, "items": […]}' />
+ <input
+ ref={file}
+ type="file"
+ accept=".json,.txt,application/json,text/plain"
+ hidden
+ onChange={async (e) => {
+ const f = e.target.files?.[0];
+ if (f) setText(await f.text());
+ e.target.value = "";
+ }}
+ />
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" onClick={() => onImport(text)} disabled={!text.trim()}>
+ Import
+ </Button>
+ <Button size="sm" variant="secondary" onClick={() => file.current?.click()}>
+ From a file…
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onCancel}>
+ Cancel
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/studio/layout-strip.tsx b/src/components/studio/layout-strip.tsx
new file mode 100644
index 00000000..570229e2
--- /dev/null
+++ b/src/components/studio/layout-strip.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { FlaskConical, PencilRuler, X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import type { LayoutDraft } from "@/lib/layout-prompt";
+import { cn } from "@/lib/utils";
+
+const KIND_COLOR = { object: "#0a84ff", character: "#34c759", text: "#ff9f0a" } as const;
+
+const ratioOf = (aspect: string | undefined) => {
+ const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(aspect ?? "");
+ return m ? Number(m[1]) / Number(m[2]) : 1;
+};
+
+/**
+ * Layout mode's strip above the prompt (as Frames mode has its strip): a small picture of the boxes, what the model
+ * makes of them and at what size, the notes (a model that reads words, a size past what box models were made for, the
+ * plan's refusal), Edit and the way out. The editor itself opens in a dialog (layout-editor.tsx).
+ */
+export function LayoutStrip({
+ layout,
+ aspect,
+ summary,
+ notes,
+ action,
+ onEdit,
+ onClose,
+}: {
+ layout: LayoutDraft;
+ aspect: string | undefined;
+ /** "Compiled for MOSS-Image at 1360 × 768". */
+ summary: string;
+ notes: { text: string; tone: "info" | "warn" }[];
+ /** A one-tap fix offered with the notes (Use MOSS-Image). */
+ action?: { label: string; onClick: () => void };
+ onEdit: () => void;
+ onClose: () => void;
+}) {
+ const ratio = ratioOf(aspect ?? layout.aspect);
+ const n = layout.items.length;
+ return (
+ <div className="mx-1 mt-1 mb-2 flex flex-wrap items-start gap-x-3 gap-y-2 rounded-2xl border bg-muted/40 p-2" data-layout-strip>
+ <button
+ type="button"
+ onClick={onEdit}
+ aria-label={n ? `Edit the layout: ${n} box${n === 1 ? "" : "es"}` : "Draw the layout"}
+ className="relative h-16 shrink-0 overflow-hidden rounded-lg border bg-background transition-colors hover:border-primary focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:outline-none"
+ style={{ width: `${Math.round(Math.min(112, Math.max(40, 64 * ratio)))}px` }}
+ >
+ {layout.items.map((it, i) => (
+ <span
+ key={i}
+ aria-hidden
+ className="absolute rounded-[2px] border"
+ style={{
+ left: `${it.box[0] * 100}%`,
+ top: `${it.box[1] * 100}%`,
+ width: `${(it.box[2] - it.box[0]) * 100}%`,
+ height: `${(it.box[3] - it.box[1]) * 100}%`,
+ borderColor: it.color ?? KIND_COLOR[it.label],
+ background: `color-mix(in oklab, ${it.color ?? KIND_COLOR[it.label]} 18%, transparent)`,
+ }}
+ />
+ ))}
+ {!n && <PencilRuler aria-hidden className="absolute inset-0 m-auto size-4 text-muted-foreground" />}
+ </button>
+ <div className="min-w-[9rem] flex-1 space-y-0.5 pt-0.5">
+ <p className="flex flex-wrap items-center gap-x-1.5 text-[13px] font-medium">
+ Layout
+ <span className="inline-flex items-center gap-0.5 rounded-full bg-secondary px-1.5 text-[11px] font-medium text-secondary-foreground">
+ <FlaskConical aria-hidden className="size-3" /> Experimental
+ </span>
+ <span className="font-normal text-muted-foreground">
+ · {n ? `${n} box${n === 1 ? "" : "es"}` : "no boxes yet"}
+ </span>
+ </p>
+ <p className="text-[12px] leading-snug text-muted-foreground">{summary}</p>
+ {notes.map((x, i) => (
+ <p key={i} className={cn("text-[12px] leading-snug", x.tone === "warn" ? "text-warning" : "text-muted-foreground")}>
+ {x.text}
+ {i === 0 && action && (
+ <>
+ {" "}
+ <button type="button" onClick={action.onClick} className="font-medium text-brand-text underline-offset-2 hover:underline">
+ {action.label}
+ </button>
+ </>
+ )}
+ </p>
+ ))}
+ </div>
+ <div className="ml-auto flex shrink-0 items-center gap-1">
+ <Button variant="secondary" size="sm" className="h-8 rounded-full px-3 text-[13px]" onClick={onEdit}>
+ {n ? "Edit boxes" : "Draw boxes"}
+ </Button>
+ <button type="button" onClick={onClose} aria-label="Layout off" className="grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <X className="size-4" />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index 749e1c55..b56c6409 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -10,6 +10,7 @@ import { useIsMobile } from "@/hooks/use-mobile";
import { type Engine, type ModelDef } from "@/lib/catalog/types";
import { useEngineMode, useStatus } from "@/lib/api";
import { bestForStudio, groupModels, toggleIn } from "@/lib/composer";
+import { readsBoxes } from "@/lib/layout-prompt";
import { formatCost } from "@/lib/format";
import { ISOLATED_NOTE } from "@/lib/model-rows";
import { cn } from "@/lib/utils";
@@ -80,12 +81,15 @@ function ModelRow({
selected,
starred,
showEngine,
+ boxes,
onStar,
}: {
m: ModelDef;
selected: boolean;
starred: boolean;
showEngine: boolean;
+ /** Layout mode: a "Reads boxes" badge on the models that place boxes by their coordinates. */
+ boxes?: boolean;
onStar: () => void;
}) {
return (
@@ -97,7 +101,13 @@ function ModelRow({
{m.name}
{starred && <span className="sr-only">, starred</span>}
</span>
- <ModelBadges model={m} max={2} />
+ {boxes && readsBoxes(m) ? (
+ <Badge variant="secondary" className="h-4 shrink-0 rounded-[4px] bg-brand-faint px-1 text-[10px] font-medium text-brand-text">
+ Reads boxes
+ </Badge>
+ ) : (
+ <ModelBadges model={m} max={2} />
+ )}
{showEngine && (
<span className="inline-flex shrink-0 items-center gap-0.5 rounded-[4px] bg-muted px-1 text-[10px] leading-4 font-medium text-muted-foreground">
{m.engine === "open" ? <Cpu className="size-2.5!" /> : <Cloud className="size-2.5!" />}
@@ -145,6 +155,8 @@ interface PickerProps {
engine: Engine;
onEngineChange: (e: Engine) => void;
defaultModels?: { cloud: string; open: string };
+ /** Layout mode: the models that read boxes come first, badged. */
+ boxes?: boolean;
}
/**
@@ -177,7 +189,7 @@ export function ModelPicker(props: PickerProps) {
}
/** The searchable list (mounted by the popover / sheet only while it shows). */
-function PickerList({ models, value, onChange, engine, onEngineChange, defaultModels, onPicked }: PickerProps & { onPicked: () => void }) {
+function PickerList({ models, value, onChange, engine, onEngineChange, defaultModels, boxes, onPicked }: PickerProps & { onPicked: () => void }) {
const [q, setQ] = useState("");
const status = useStatus().data;
const mode = useEngineMode();
@@ -191,7 +203,7 @@ function PickerList({ models, value, onChange, engine, onEngineChange, defaultMo
const op = models.find((m) => m.id === id)?.routes[0]?.op;
return bestForStudio(models, engine, id, 4, op).map((m) => m.id);
}, [models, engine, defaultModels]);
- const { groups, count } = useMemo(() => groupModels({ models, engine, engines, query: q, recent, starred, best }), [models, engine, engines, q, recent, starred, best]);
+ const { groups, count } = useMemo(() => groupModels({ models, engine, engines, query: q, recent, starred, best, boxes }), [models, engine, engines, q, recent, starred, best, boxes]);
const ready = (m: ModelDef) => m.routes.some((r) => status?.providers[r.provider]?.configured);
const shown = groups.flatMap((g) => g.models);
const demo = status && status.demoMode !== "off" && shown.some((m) => !ready(m));
@@ -239,7 +251,7 @@ function PickerList({ models, value, onChange, engine, onEngineChange, defaultMo
data-checked={value?.id === m.id}
className={cn("gap-2.5 rounded-lg px-2 py-1.5 [&>svg:last-child]:hidden", value?.id === m.id && "bg-brand-faint data-selected:bg-brand-faint-hover")}
>
- <ModelRow m={m} selected={value?.id === m.id} starred={starred.includes(m.id)} showEngine={!!q || m.engine !== engine} onStar={() => setStarred((s) => toggleIn(s, m.id))} />
+ <ModelRow m={m} selected={value?.id === m.id} starred={starred.includes(m.id)} showEngine={!!q || m.engine !== engine} boxes={boxes} onStar={() => setStarred((s) => toggleIn(s, m.id))} />
</CommandItem>
))}
</CommandGroup>
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index 6c968c06..8bfdd8ea 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -5,6 +5,7 @@ import type { GenParams, InputSlot, MediaKind, Operation, Preset } from "@/lib/c
import type { FeedFilter } from "@/lib/api";
import type { Signature } from "@/lib/catalog/palettes";
import type { FrameAttachment } from "@/lib/composer";
+import type { LayoutDraft } from "@/lib/layout-prompt";
import type { SlotValue } from "./media-slot";
export type SlotKey = InputSlot["key"];
@@ -75,6 +76,11 @@ export interface StudioConfig {
comfyOnly?: { note: string; alternative?: { label: string; href: string } };
/** Frames mode (Video studio): up to 10 stills, each at its own time in the clip, instead of a start and an end frame. */
frames?: boolean;
+ /**
+ * Layout mode (Image studio): boxes drawn on the picture, one row each (an object, a character or exact words),
+ * compiled for the model at the size it renders (src/lib/layout-prompt.ts); the prompt is the whole picture's caption.
+ */
+ layout?: boolean;
}
export interface Draft {
@@ -93,6 +99,8 @@ export interface Draft {
signature?: Signature;
/** Frames mode is on (studios with `frames`): the stills in order, each at its place in the clip. */
frames?: FrameAttachment<SlotValue>[];
+ /** Layout mode is on (studios with `layout`): the boxes, as fractions of the picture (the prompt is its caption). */
+ layout?: LayoutDraft;
}
interface Actions {
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 81909caf..3d8a7334 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -10,7 +10,8 @@ import { toast } from "sonner";
import { SidebarTrigger } from "@/components/ui/sidebar";
import type { Generation, MediaKind, ModelDef, Preset } from "@/lib/catalog/types";
import { useEngine, useGenerations } from "@/lib/api";
-import { claimStartToken, followEngineDefault, handoffKey, mergeHandoff, presetModel, promptShown, START_PARAM, withoutStart } from "@/lib/composer";
+import { claimStartToken, followEngineDefault, handoffKey, mergeHandoff, presetModel, promptShown, START_PARAM, withoutLayout, withoutStart } from "@/lib/composer";
+import { editableLayout, EDIT_LAYOUT_PARAM, readEditLayoutParam } from "@/lib/output-actions";
import { positionsFrom } from "@/lib/catalog/keyframes";
import { reuseSignature, withSignatureWords } from "@/lib/catalog/palettes";
import { currentModelId, migrateRequest } from "@/lib/catalog/replaced";
@@ -111,11 +112,14 @@ function draftFromGeneration(g: Generation, config: StudioConfig, getModel: (id:
// A spoken language stored as a name (Assist's "Spanish") or a locale comes back as the model's own code.
const languages = getModel(r.modelId)?.options.sourceLanguages;
if (languages?.length && params.sourceLanguage) params.sourceLanguage = matchSpokenLanguage(params.sourceLanguage, languages) ?? params.sourceLanguage;
+ // A layout run comes back in Layout mode (studios that have it): its boxes in the editor, the prompt as their caption.
+ const laid = config.layout ? withoutLayout(params) : { params, layout: undefined };
return {
prompt: r.prompt ?? "",
negativePrompt: r.negativePrompt ?? "",
modelId: r.modelId,
- params,
+ params: laid.params,
+ layout: laid.layout,
slots: frames ? {} : slots,
refs: frames ? [] : refs,
frames,
@@ -451,6 +455,46 @@ function HandoffSync({
);
}
+/**
+ * Edit layout (`/image?layout=<generation>[.<picture>]`, from a result's menu anywhere): the picture's boxes open in
+ * Layout mode with its words, model and seed: the request's own layout, or the one fal's MOSS-Image planned (decoded at
+ * the picture's size). The param isn't part of the hand-off key, so the draft on screen isn't reset first; it is taken
+ * out of the address once read, so a reload doesn't open it again.
+ */
+function LayoutHandoff() {
+ const sp = useSearchParams();
+ const value = sp.get(EDIT_LAYOUT_PARAM);
+ const { config, setDraft } = useStudioActions();
+ const catalog = useCatalog();
+ const [engine, setEngine] = useEngine();
+ const opened = useRef<string | null>(null);
+ const ref = config.layout ? readEditLayoutParam(value) : null;
+ useEffect(() => {
+ if (!ref || !value || opened.current === value || !catalog.ready) return;
+ opened.current = value;
+ void fetch(`/api/generations/${encodeURIComponent(ref.id)}`)
+ .then(async (res) => {
+ if (!res.ok) throw new Error("That picture isn't in your library any more");
+ const g = (await res.json()) as Generation;
+ const e = editableLayout(g, ref.index);
+ if (!e) throw new Error("This picture has no layout to open");
+ const base = draftFromGeneration(g, config, catalog.getModel);
+ const params = { ...(base.params ?? {}), ...(e.seed !== undefined && { seed: e.seed }) };
+ setDraft({ ...base, prompt: e.caption, params, layout: { ...e.draft, summary: { ...e.draft.summary, caption: "" } } });
+ if (g.engine !== engine) setEngine(g.engine);
+ toast(e.seed !== undefined ? "Layout opened with the picture's seed: move a box or change a word, then generate" : "Layout opened: move a box or change a word, then generate", { id: "edit-layout" });
+ requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>("[data-composer] textarea")?.focus());
+ })
+ .catch((err: Error) => toast.error(err.message, { id: "edit-layout" }))
+ .finally(() => {
+ const u = new URL(window.location.href);
+ u.searchParams.delete(EDIT_LAYOUT_PARAM);
+ window.history.replaceState(null, "", `${u.pathname}${u.search}${u.hash}`);
+ });
+ }, [ref, value, catalog, config, engine, setDraft, setEngine]);
+ return null;
+}
+
/** One draft's page: the studio and its hand-off. The start request resets with the draft (a new epoch). */
function StudioSession({ header, tabs, sync }: { header?: React.ReactNode; tabs?: React.ReactNode; sync: Omit<React.ComponentProps<typeof HandoffSync>, "onStart"> }) {
const [startRequest, setStartRequest] = useState(0);
@@ -459,6 +503,9 @@ function StudioSession({ header, tabs, sync }: { header?: React.ReactNode; tabs?
<StartRequestCtx.Provider value={startRequest}>
<StudioBody header={header} tabs={tabs} />
<HandoffSync {...sync} onStart={onStart} />
+ <Suspense fallback={null}>
+ <LayoutHandoff />
+ </Suspense>
</StartRequestCtx.Provider>
);
}
diff --git a/src/lib/layout-edit.ts b/src/lib/layout-edit.ts
new file mode 100644
index 00000000..9e5e4387
--- /dev/null
+++ b/src/lib/layout-edit.ts
@@ -0,0 +1,89 @@
+/*
+ * Box maths for the Layout editor (src/components/studio/layout-editor.tsx): drawing, picking, moving, resizing and
+ * nudging boxes on a canvas of the size the model renders. Pure. Boxes are LayoutBox fractions ([x0, y0, x1, y1] of the
+ * canvas); the editing happens in the canvas's own pixels, so a box snaps to whole pixels of the picture made (the
+ * Layers editor's rectFrom and resizeBox, src/lib/layers.ts).
+ */
+import { rectFrom, resizeBox, type Handle } from "./layers";
+import type { LayoutBox } from "./layout-prompt";
+
+export type { Handle };
+
+/** The smallest box the editor draws, in canvas pixels (a click that barely moves is a click, not a box). */
+export const MIN_BOX_PX = 16;
+
+const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
+const snap = (v: number) => Math.round(v * 1e6) / 1e6;
+const toBox = (x: number, y: number, w: number, h: number, width: number, height: number): LayoutBox => [snap(x / width), snap(y / height), snap((x + w) / width), snap((y + h) / height)];
+
+/** A box drawn from one corner to the other (canvas pixels), kept inside the canvas; null when smaller than MIN_BOX_PX. */
+export function drawnBox(x0: number, y0: number, x1: number, y1: number, width: number, height: number): LayoutBox | null {
+ const r = rectFrom(x0, y0, x1, y1, { width, height }, MIN_BOX_PX);
+ return r ? toBox(r[0], r[1], r[2], r[3], width, height) : null;
+}
+
+/** The boxes under a point (fractions), the one drawn last (on top) first. */
+export function boxesAt(boxes: LayoutBox[], fx: number, fy: number): number[] {
+ const out: number[] = [];
+ for (let i = boxes.length - 1; i >= 0; i--) {
+ const [x0, y0, x1, y1] = boxes[i];
+ if (fx >= x0 && fx <= x1 && fy >= y0 && fy <= y1) out.push(i);
+ }
+ return out;
+}
+
+/**
+ * Which box a press picks among the stack under it: pressing the same spot again (`again`, after a press that didn't
+ * drag) steps to the next box down the stack, round to the top (LinXce's editor does this); otherwise the selected box
+ * stays picked when it is in the stack (so it can be dragged out from under another), else the top one.
+ */
+export function pickBox(stack: number[], selected: number | null, again: boolean): number | null {
+ if (!stack.length) return null;
+ const at = selected === null ? -1 : stack.indexOf(selected);
+ if (again && at >= 0) return stack[(at + 1) % stack.length];
+ return at >= 0 ? selected : stack[0];
+}
+
+/** A box moved by dx, dy canvas pixels, kept whole inside the canvas. */
+export function movedBox(box: LayoutBox, dx: number, dy: number, width: number, height: number): LayoutBox {
+ const [x0, y0, x1, y1] = box;
+ const w = (x1 - x0) * width;
+ const h = (y1 - y0) * height;
+ const x = clamp(x0 * width + dx, 0, Math.max(0, width - w));
+ const y = clamp(y0 * height + dy, 0, Math.max(0, height - h));
+ return toBox(Math.round(x), Math.round(y), Math.round(w), Math.round(h), width, height);
+}
+
+/**
+ * A box resized by dragging one of its handles dx, dy canvas pixels: the opposite edge or corner stays put, corners
+ * resize freely (resizeBox, unrotated), no side below MIN_BOX_PX, and the box stays inside the canvas.
+ */
+export function resizedBox(box: LayoutBox, handle: Handle, dx: number, dy: number, width: number, height: number): LayoutBox {
+ const [x0, y0, x1, y1] = box;
+ const node = { x: x0 * width, y: y0 * height, w: (x1 - x0) * width, h: (y1 - y0) * height, rotation: 0 };
+ const r = resizeBox(node, handle, dx, dy, true);
+ // Held at the canvas edges and the minimum size, the opposite side where it was.
+ let left = r.x;
+ let top = r.y;
+ let right = r.x + r.w;
+ let bottom = r.y + r.h;
+ if (handle.includes("w")) left = clamp(left, 0, right - MIN_BOX_PX);
+ if (handle.includes("e")) right = clamp(right, left + MIN_BOX_PX, width);
+ if (handle.includes("n")) top = clamp(top, 0, bottom - MIN_BOX_PX);
+ if (handle.includes("s")) bottom = clamp(bottom, top + MIN_BOX_PX, height);
+ const [l, t, rr, b] = [left, top, right, bottom].map(Math.round);
+ return toBox(l, t, rr - l, b - t, width, height);
+}
+
+/** Arrow keys: one canvas pixel a press, ten with Shift. */
+export function nudgedBox(box: LayoutBox, key: string, shift: boolean, width: number, height: number): LayoutBox | null {
+ const step = shift ? 10 : 1;
+ const d = ({ ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] } as Record<string, [number, number]>)[key];
+ return d ? movedBox(box, d[0], d[1], width, height) : null;
+}
+
+/** A new box in the middle of the canvas, for the keyboard (Add box): a third of each side, nudged down for each one already there. */
+export function newBox(count: number): LayoutBox {
+ const off = Math.min(0.3, (count % 6) * 0.05);
+ return [snap(1 / 3 + off / 2), snap(1 / 3 + off), snap(2 / 3 + off / 2), snap(2 / 3 + off)].map((v) => Math.min(1, v)) as LayoutBox;
+}
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index cfc8e515..22b5fb10 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -20,6 +20,8 @@ export const IMAGE_STUDIO: StudioConfig = {
defaultModels: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" },
// A model's own settings (MOSS-Image's Quality, Ideogram's speed) sit under "Options".
controlsTitle: "Options",
+ // Layout mode: boxes on the picture, one row each, read in place by MOSS-Image, FLUX.3 and Ideogram 4.5.
+ layout: true,
// Color signature + Moodboard chips, and the models they can move a request to. Fuobe Soul's PixeletedFace look runs
// the face mosaic after the picture: its step's model is known here so the price counts it before the run.
signature: true,