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: editor Undo, tests for the box maths, Layout mode in the composer e2e script

Claude8d550ce57624
diff --git a/src/components/studio/layout-editor.tsx b/src/components/studio/layout-editor.tsx
index 4efc6182..72a3a22b 100644
--- a/src/components/studio/layout-editor.tsx
+++ b/src/components/studio/layout-editor.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArrowDownToLine, ClipboardCopy, FileJson, FlaskConical, Import, Plus, Trash2, X } from "lucide-react";
+import { ArrowDownToLine, ClipboardCopy, FileJson, FlaskConical, Import, Plus, Trash2, Undo2, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
@@ -116,8 +116,17 @@ export function LayoutEditor(props: {
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 };
+ | { mode: "move"; index: number; box: LayoutBox; sx: number; sy: number; moved: boolean; id: number; before: LayoutItem[] }
+ | { mode: "resize"; index: number; box: LayoutBox; handle: Handle; sx: number; sy: number; id: number; before: LayoutItem[] };
+
+/** What Undo goes back to (the editor's own: a toast behind the dialog can't be pressed). */
+interface Snapshot {
+ items: LayoutItem[];
+ caption: string;
+ tags: string;
+ canvasType: CanvasType;
+ aspect: string;
+}
function LayoutBoard({
onOpenChange,
@@ -139,6 +148,7 @@ function LayoutBoard({
const [drag, setDrag] = useState<Drag | null>(null);
const [importing, setImporting] = useState(false);
const [sheetOpen, setSheetOpen] = useState(true);
+ const [history, setHistory] = useState<Snapshot[]>([]);
const board = useRef<HTMLDivElement>(null);
const lastPress = useRef<{ x: number; y: number } | null>(null);
const size = canvasFor(aspect);
@@ -176,13 +186,26 @@ function LayoutBoard({
};
const patch = (i: number, p: Partial<LayoutItem>) => setItems((xs) => xs.map((x, j) => (j === i ? { ...x, ...p } : x)));
+ /** Keep the state before a change Undo can take back (drawing, moving, resizing, removing, importing). */
+ const remember = (over: Partial<Snapshot> = {}) => setHistory((h) => [...h.slice(-49), { items, caption, tags, canvasType, aspect, ...over }]);
+ const undo = () => {
+ const last = history.at(-1);
+ if (!last) return;
+ setHistory(history.slice(0, -1));
+ setItems(last.items);
+ setCaption(last.caption);
+ setTags(last.tags);
+ setCanvasType(last.canvasType);
+ setAspect(last.aspect);
+ setSelected((s) => (s !== null && s < last.items.length ? s : null));
+ };
const remove = (i: number) => {
- const before = items;
+ remember();
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) => {
+ remember();
setItems((xs) => [...xs, { label: "object", caption: "", box }]);
setSelected(items.length);
setSheetOpen(true);
@@ -200,7 +223,7 @@ function LayoutBoard({
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 });
+ setDrag({ mode: "resize", index: selected, box: items[selected].box, handle, sx: p.x, sy: p.y, id: e.pointerId, before: items });
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).
@@ -219,7 +242,7 @@ function LayoutBoard({
return;
}
setSelected(picked);
- setDrag({ mode: "move", index: picked, box: items[picked].box, sx: p.x, sy: p.y, moved: false, id: e.pointerId });
+ setDrag({ mode: "move", index: picked, box: items[picked].box, sx: p.x, sy: p.y, moved: false, id: e.pointerId, before: items });
lastPress.current = { x: p.sx, y: p.sy };
};
@@ -246,11 +269,17 @@ function LayoutBoard({
}
// 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;
+ if (drag.mode !== "draw" && drag.before[drag.index]?.box !== items[drag.index]?.box) remember({ items: drag.before });
setDrag(null);
};
const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
- if (typing(e.target) || selected === null || !items[selected]) return;
+ if (typing(e.target)) return;
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "z" && !e.shiftKey) {
+ e.preventDefault();
+ return undo();
+ }
+ if (selected === null || !items[selected]) return;
if (e.key === "Delete" || e.key === "Backspace") {
e.preventDefault();
return remove(selected);
@@ -273,7 +302,7 @@ function LayoutBoard({
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 };
+ remember();
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());
@@ -282,19 +311,7 @@ function LayoutBoard({
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);
- },
- },
- });
+ toast(`Imported ${n} box${n === 1 ? "" : "es"} from ${SOURCE_WORDS[parsed.from]} · Undo is under the canvas`, { id: "layout-import" });
return true;
};
@@ -377,7 +394,7 @@ function LayoutBoard({
Done
</Button>
</div>
- <DialogDescription id="layout-editor-hint" className="w-full text-[12px] leading-snug text-muted-foreground">
+ <DialogDescription id="layout-editor-hint" className="w-full text-[12px] leading-snug text-muted-foreground max-sm:sr-only">
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>
@@ -449,6 +466,9 @@ function LayoutBoard({
<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>
+ <Button variant="ghost" size="sm" className="h-7 gap-1 px-2 text-[12px]" onClick={undo} disabled={!history.length} aria-keyshortcuts="Control+Z Meta+Z">
+ <Undo2 className="size-3.5" /> Undo
+ </Button>
<span className="tabular-nums">
{aspect} · {size.exact ? "" : "about "}
{size.width} × {size.height}
diff --git a/tests/e2e/composer-flows.mjs b/tests/e2e/composer-flows.mjs
index 8ca38bd8..3f6a8029 100644
--- a/tests/e2e/composer-flows.mjs
+++ b/tests/e2e/composer-flows.mjs
@@ -9,6 +9,9 @@
// 6. A blocked Generate says why in a line under the composer on a phone; a tap opens the missing tile's file
// picker (focus inside the composer), and the line moves on to the next input. A desktop composer shows the
// line only while its tiles are folded away.
+// 7. Layout mode (Image studio, MOSS-Image in the cloud, demo mode): draw one box by mouse and one by touch at
+// 390 px, a Text box asks for its words, Generate sends the layout (compiled at the size fal renders, prompt
+// expansion off) and the feed says "Layout · 1 box"; Edit layout from the tile reopens the boxes.
//
// Playwright: the `playwright` (or `playwright-core`) package if it resolves, else the global install at
// /opt/node22/lib/node_modules. Chromium: $CHROMIUM_PATH, else the newest /opt/pw-browsers/chromium-*.
@@ -235,6 +238,70 @@ async function ready(page, url) {
await desk.close();
}
+// 7. Layout mode.
+{
+ const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
+ await ready(page, "/image?model=moss-image");
+ await page.waitForTimeout(800);
+ await page.getByRole("button", { name: "Layout", exact: true }).first().click();
+ const canvas = page.locator("[data-layout-canvas]");
+ await canvas.waitFor({ timeout: 30_000 });
+ const c = await canvas.boundingBox();
+ await page.mouse.move(c.x + c.width * 0.1, c.y + c.height * 0.08);
+ await page.mouse.down();
+ await page.mouse.move(c.x + c.width * 0.9, c.y + c.height * 0.24, { steps: 8 });
+ await page.mouse.up();
+ check("layout: a drag draws a box", (await page.locator("[data-layout-box]").count()) === 1);
+ const row = page.locator('[data-layout-row="1"]');
+ await row.getByRole("radio", { name: "Text" }).click();
+ check("layout: a Text box asks for its words", await row.getByText("Type the words for box 1").isVisible());
+ await row.getByLabel("Box 1: exact words").fill("30% OFF");
+ await page.locator("#layout-caption").fill("A candle sale poster");
+ await page.getByRole("button", { name: "Done" }).click();
+ const strip = await page.locator("[data-layout-strip]").innerText();
+ check("layout: the strip says the size it's compiled at", /Compiled for MOSS-Image at \d+ × \d+/.test(strip), strip.replace(/\n/g, " "));
+ const sent = page.waitForRequest((r) => r.url().endsWith("/api/generations") && r.method() === "POST", { timeout: 30_000 });
+ await page.getByRole("button", { name: /^Generate/ }).click();
+ const body = JSON.parse((await sent).postData() ?? "{}");
+ const layout = body.params?.extra?.layout;
+ check("layout: Generate sends the draft with the prompt as its caption", layout?.items?.length === 1 && layout.items[0].text === "30% OFF" && layout.summary?.caption === "A candle sale poster");
+ const tile = page.locator("[data-gen-id]", { has: page.locator("header", { hasText: "Layout · 1 box" }) }).first();
+ check("layout: the feed says it's a layout", await tile.waitFor({ timeout: 30_000 }).then(() => true, () => false));
+ const preview = await page.request.post(`${app}/api/generations?preview=1`, { data: body }).then((r) => r.json()).catch(() => ({}));
+ check("layout: the run gets the compiled MOSS prompt", typeof preview.prompt === "string" && preview.prompt.includes('"bbox_coord_space":"abs_centralized"'), (preview.prompt ?? preview.error ?? "").slice(0, 80));
+ await page.waitForFunction(() => document.querySelector("[data-gen-id] img, [data-gen-id] video"), null, { timeout: 60_000 }).catch(() => {});
+ const t = tile.locator(".group\\/tile").first();
+ await t.hover();
+ await t.getByRole("button", { name: "More actions" }).first().click();
+ await page.getByRole("menuitem", { name: "Edit layout" }).click();
+ await page.waitForFunction(() => !location.search.includes("layout="), null, { timeout: 30_000 }).catch(() => {});
+ await page.locator("[data-layout-strip]").waitFor({ timeout: 30_000 }).catch(() => {});
+ check("layout: Edit layout reopens the boxes", /1 box/.test(await page.locator("[data-layout-strip]").innerText().catch(() => "")));
+ await page.close();
+
+ const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
+ const phone = await ctx.newPage();
+ await ready(phone, "/image?model=moss-image");
+ await phone.waitForTimeout(800);
+ await phone.getByRole("button", { name: /^Settings/ }).first().tap();
+ await phone.getByRole("button", { name: "Layout", exact: true }).first().tap();
+ await phone.locator("[data-layout-canvas]").waitFor({ timeout: 30_000 });
+ const pc = await phone.locator("[data-layout-canvas]").boundingBox();
+ const cdp = await ctx.newCDPSession(phone);
+ const pt = (x, y) => [{ x: pc.x + pc.width * x, y: pc.y + pc.height * y }];
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: pt(0.2, 0.3) });
+ for (let i = 1; i <= 8; i++) await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: pt(0.2 + 0.06 * i, 0.3 + 0.05 * i) });
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
+ await phone.waitForTimeout(300);
+ check("layout (390 px): a touch drag draws a box", (await phone.locator("[data-layout-box]").count()) === 1);
+ const sheet = await phone.locator('aside[aria-label="Boxes"]').boundingBox();
+ const board = await phone.locator("[data-layout-canvas]").boundingBox();
+ check("layout (390 px): the rows sit in a sheet under the canvas", !!sheet && !!board && sheet.y >= board.y + board.height, `canvas ends at ${Math.round(board?.y + board?.height)}, sheet starts at ${Math.round(sheet?.y)}`);
+ const wide = await phone.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
+ check("layout (390 px): nothing scrolls sideways", wide <= 0, `${wide}px`);
+ await ctx.close();
+}
+
await browser.close();
console.log(failures.length ? `\n${failures.length} check(s) failed: ${failures.join(", ")}` : "\nAll composer checks passed.");
process.exit(failures.length ? 1 : 0);
diff --git a/tests/layout-mode.test.ts b/tests/layout-mode.test.ts
index c8d2dd42..a66e30c5 100644
--- a/tests/layout-mode.test.ts
+++ b/tests/layout-mode.test.ts
@@ -7,6 +7,7 @@ import type { Generation, GenerationRequest, ModelDef, ModelRoute } from "@/lib/
import { fitCanvas } from "@/lib/comfy";
import { enterLayout, groupModels, layoutModelNote, layoutRequest, layoutShape, layoutSizeWarning, leaveLayout, settingsShape, withoutLayout } from "@/lib/composer";
import { compileFlux3, compileIdeogram, compileMoss, compileWords, type LayoutDraft } from "@/lib/layout-prompt";
+import { boxesAt, drawnBox, movedBox, newBox, nudgedBox, pickBox, resizedBox } from "@/lib/layout-edit";
import { editableLayout, editLayoutHref, outputActions, readEditLayoutParam } from "@/lib/output-actions";
import { slimModel } from "@/lib/studio-catalog";
@@ -246,3 +247,49 @@ describe("Edit layout", () => {
for (const bad of ["", null, "../etc", "a.b", "x".repeat(80)]) expect(readEditLayoutParam(bad)).toBeNull();
});
});
+
+describe("the editor's box maths", () => {
+ // Whole pixels at this size: boxes snap to the canvas's pixels.
+ const W = 1000;
+ const H = 500;
+
+ it("draws a box corner to corner on the canvas's own pixels, kept inside, none for a click", () => {
+ expect(drawnBox(100, 50, 500, 250, W, H)).toEqual([0.1, 0.1, 0.5, 0.5]);
+ // Dragged up and to the left, and past the edge; snapped to whole pixels.
+ expect(drawnBox(500, 250, -50, -50, W, H)).toEqual([0, 0, 0.5, 0.5]);
+ expect(drawnBox(100.4, 50.4, 500.4, 250.4, W, H)).toEqual([0.1, 0.1, 0.5, 0.5]);
+ expect(drawnBox(100, 100, 108, 104, W, H)).toBeNull();
+ });
+
+ it("picks the top box, keeps a picked one under another, and cycles on the same spot", () => {
+ const boxes: [number, number, number, number][] = [
+ [0, 0, 1, 1],
+ [0.2, 0.2, 0.6, 0.6],
+ [0.4, 0.4, 0.8, 0.8],
+ ];
+ const stack = boxesAt(boxes, 0.5, 0.5);
+ expect(stack).toEqual([2, 1, 0]);
+ expect(pickBox(stack, null, false)).toBe(2);
+ expect(pickBox(stack, 0, false)).toBe(0);
+ expect(pickBox(stack, 2, true)).toBe(1);
+ expect(pickBox(stack, 1, true)).toBe(0);
+ expect(pickBox(stack, 0, true)).toBe(2);
+ expect(pickBox([], 1, true)).toBeNull();
+ });
+
+ it("moves, resizes and nudges within the canvas, never below 16 px", () => {
+ const box: [number, number, number, number] = [0.1, 0.1, 0.5, 0.5];
+ expect(movedBox(box, 100, 50, W, H)).toEqual([0.2, 0.2, 0.6, 0.6]);
+ // Pushed past the right edge: held there whole.
+ expect(movedBox(box, 5000, 0, W, H)).toEqual([0.6, 0.1, 1, 0.5]);
+ // The south-east handle drags the corner; the north-west corner stays.
+ expect(resizedBox(box, "se", 100, 50, W, H)).toEqual([0.1, 0.1, 0.6, 0.6]);
+ expect(resizedBox(box, "n", 0, -1000, W, H)[1]).toBe(0);
+ const tiny = resizedBox(box, "e", -5000, 0, W, H);
+ expect(Math.round((tiny[2] - tiny[0]) * W)).toBe(16);
+ expect(nudgedBox(box, "ArrowRight", false, W, H)).toEqual([0.101, 0.1, 0.501, 0.5]);
+ expect(nudgedBox(box, "ArrowUp", true, W, H)).toEqual([0.1, 0.08, 0.5, 0.48]);
+ expect(nudgedBox(box, "Enter", false, W, H)).toBeNull();
+ expect(newBox(0)).toEqual([0.333333, 0.333333, 0.666667, 0.666667]);
+ });
+});