The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Layers: one undo step per slider drag, tablet-width header, stricter file paths
Claude2734e47cbabc
diff --git a/src/app/api/layers/route.ts b/src/app/api/layers/route.tsindex 224154fc..ce00b3f4 100644--- a/src/app/api/layers/route.ts+++ b/src/app/api/layers/route.ts@@ -1,10 +1,10 @@import { connection } from "next/server";import { z } from "zod";-import { createProject, LayersError, listProjects } from "@/server/layers";+import { createProject, FileUrl, LayersError, listProjects } from "@/server/layers";const Body = z.object({/** The image to open: an upload or a result (an /api/files/ URL). */- source: z.string().max(2000).startsWith("/api/files/"),+ source: FileUrl,/** Its pixel size, read by the browser that loaded it. */width: z.number().positive().max(20_000),height: z.number().positive().max(20_000),diff --git a/src/components/layers/editor-context.tsx b/src/components/layers/editor-context.tsxindex 86e60461..4691ed3d 100644--- a/src/components/layers/editor-context.tsx+++ b/src/components/layers/editor-context.tsx@@ -26,7 +26,8 @@ export interface EditorCtx {versions: LayerVersion[];headVersionId: string;doc: LayerDoc;- commit: (doc: LayerDoc) => void;+ /** Save an edit as an undo step; commits with the same `merge` key in quick succession (a slider drag) are one step. */+ commit: (doc: LayerDoc, merge?: string) => void;selectedId: string | null;selected: LayerNode | undefined;select: (id: string | null) => void;diff --git a/src/components/layers/layers-editor.tsx b/src/components/layers/layers-editor.tsxindex 805f11ff..e05c3df5 100644--- a/src/components/layers/layers-editor.tsx+++ b/src/components/layers/layers-editor.tsx@@ -125,7 +125,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()const [brushSize, setBrushSize] = useState(() => Math.round(Math.max(initial.doc.width, initial.doc.height) / 30));const [compare, setCompare] = useState(false);- const commit = useCallback((d: LayerDoc) => dispatch({ type: "commit", doc: d }), []);+ const commit = useCallback((d: LayerDoc, merge?: string) => dispatch({ type: "commit", doc: d, merge, at: Date.now() }), []);const resetTo = useCallback((v: LayerProjectView) => {setHead(v.headVersionId);@@ -411,7 +411,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()const step = e.shiftKey ? 10 : 1;const dx = e.key === "ArrowLeft" ? -step : e.key === "ArrowRight" ? step : 0;const dy = e.key === "ArrowUp" ? -step : e.key === "ArrowDown" ? step : 0;- commit(updateNode(d, sel.id, { x: sel.x + dx, y: sel.y + dy }));+ commit(updateNode(d, sel.id, { x: sel.x + dx, y: sel.y + dy }), `nudge:${sel.id}`);return;}const k = e.key.toLowerCase();diff --git a/src/components/layers/layers-panel.tsx b/src/components/layers/layers-panel.tsxindex 120fb19e..6cb075fb 100644--- a/src/components/layers/layers-panel.tsx+++ b/src/components/layers/layers-panel.tsx@@ -567,7 +567,7 @@ function SelectedLayer({ node }: { node: LayerNode }) {</div>)}<Field label="Opacity" hint={`${Math.round((node.opacity ?? 1) * 100)}%`}>- <Slider aria-label="Opacity" min={0} max={100} step={1} value={[Math.round((node.opacity ?? 1) * 100)]} onValueChange={([v]) => commit(updateNode(doc, node.id, { opacity: v / 100 }))} />+ <Slider aria-label="Opacity" min={0} max={100} step={1} value={[Math.round((node.opacity ?? 1) * 100)]} onValueChange={([v]) => commit(updateNode(doc, node.id, { opacity: v / 100 }), `opacity:${node.id}`)} /></Field><div className="grid grid-cols-5 gap-1.5">{(@@ -590,7 +590,7 @@ function SelectedLayer({ node }: { node: LayerNode }) {onChange={(e) => {const v = Number(e.target.value);if (!Number.isFinite(v) || ((k === "w" || k === "h") && v < 1)) return;- commit(updateNode(doc, node.id, { [k]: v }));+ commit(updateNode(doc, node.id, { [k]: v }), `${k}:${node.id}`);}}/></label>@@ -644,7 +644,7 @@ export function LayersPanel() {};return (- <aside className="flex min-h-0 w-[264px] shrink-0 flex-col border-l bg-background xl:w-[300px]" aria-label="Layers panel">+ <aside className="flex min-h-0 w-[240px] shrink-0 flex-col border-l bg-background lg:w-[264px] xl:w-[300px]" aria-label="Layers panel"><div className="flex h-12 shrink-0 items-center gap-2 px-3"><h2 className="text-[13px] font-semibold">Layers</h2><span className="font-mono text-[12px] text-subtle-foreground">{doc.nodes.length}</span>diff --git a/src/components/layers/stage.tsx b/src/components/layers/stage.tsxindex 041d9624..03dc7bf6 100644--- a/src/components/layers/stage.tsx+++ b/src/components/layers/stage.tsx@@ -481,17 +481,18 @@ export function Stage(p: StageProps) {</>)}<ModeButton icon={Minus} label="Zoom out" k="−" onClick={() => zoomBy(0.8)} />- <button type="button" onClick={refit} className="h-8 min-w-12 shrink-0 rounded-full px-1.5 font-mono text-[12px] text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Fit to screen">+ <button type="button" onClick={refit} className="h-8 min-w-12 shrink-0 rounded-full px-1.5 font-mono text-[12px] text-muted-foreground hover:bg-accent hover:text-foreground" aria-label={`Zoom ${Math.round(view.zoom * 100)}%: fit to screen`}>{Math.round(view.zoom * 100)}%</button><ModeButton icon={Plus} label="Zoom in" k="+" onClick={() => zoomBy(1.25)} />- <ModeButton icon={Maximize} label="Fit to screen" k="0" onClick={refit} />+ {/* Below 1024 px the percentage (also “Fit to screen”) does this, so the bar fits a narrow stage. */}+ <ModeButton icon={Maximize} label="Fit to screen" k="0" onClick={refit} className="max-lg:hidden" /></div></div>);}-function ModeButton({ icon: Icon, label, k, active, disabled, onClick }: { icon: typeof Hand; label: string; k?: string; active?: boolean; disabled?: boolean; onClick: () => void }) {+function ModeButton({ icon: Icon, label, k, active, disabled, onClick, className }: { icon: typeof Hand; label: string; k?: string; active?: boolean; disabled?: boolean; onClick: () => void; className?: string }) {return (<Tooltip><TooltipTrigger asChild>@@ -504,6 +505,7 @@ function ModeButton({ icon: Icon, label, k, active, disabled, onClick }: { icon:className={cn("grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent",active && "bg-brand-faint text-brand-text hover:bg-brand-faint-hover",+ className,)}><Icon className="size-4" />diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsxindex 6bf42b87..2c418592 100644--- a/src/components/layers/tools.tsx+++ b/src/components/layers/tools.tsx@@ -761,17 +761,17 @@ function RegionalTool() {max={Math.round(Math.min(pair.edited.w, pair.edited.h) / 2)}step={1}value={[Math.round(pair.edited.feather ?? 0)]}- onValueChange={([v]) => commit({ ...doc, nodes: doc.nodes.map((n) => (n.id === pair.edited.id ? { ...n, feather: v } : n)) })}+ onValueChange={([v]) => commit({ ...doc, nodes: doc.nodes.map((n) => (n.id === pair.edited.id ? { ...n, feather: v } : n)) }, `feather:${pair.edited.id}`)}/></Field>- <div className="flex gap-2">- <Button size="sm" className="flex-1 rounded-full" onClick={() => void merge()} disabled={merging}>+ <div className="flex flex-wrap gap-2">+ <Button size="sm" className="grow rounded-full" onClick={() => void merge()} disabled={merging}>{merging && <Loader2 className="animate-spin" />} Merge layers</Button><Buttonsize="sm"variant="outline"- className="flex-1 rounded-full"+ className="grow rounded-full"onClick={() => {setRegion(null);setPrompt("");diff --git a/src/components/layers/top-bar.tsx b/src/components/layers/top-bar.tsxindex 96daaa7e..0e910a89 100644--- a/src/components/layers/top-bar.tsx+++ b/src/components/layers/top-bar.tsx@@ -186,7 +186,10 @@ export function TopBar(p: {</TooltipTrigger><TooltipContent>{p.doc.nodes.length ? "Copy the layers as a design file (JSON)" : "Add a layer to copy as JSON."}</TooltipContent></Tooltip>- <EngineSwitch value={p.engine} onChange={p.setEngine} />+ {/* Icons only below 1024 px (names stay in the tooltips and aria labels), so a tablet with the sidebar open keeps both engines in reach. */}+ <div className="flex shrink-0 max-lg:[&_a>span]:hidden max-lg:[&_button>span]:hidden">+ <EngineSwitch value={p.engine} onChange={p.setEngine} />+ </div></div><Sheet open={historyOpen} onOpenChange={setHistoryOpen}>diff --git a/src/lib/layers.ts b/src/lib/layers.tsindex 34c7f35f..59f87c41 100644--- a/src/lib/layers.ts+++ b/src/lib/layers.ts@@ -715,17 +715,31 @@ export interface History {past: LayerDoc[];present: LayerDoc;future: LayerDoc[];+ /** The last commit's merge key and time: a burst of commits with the same key is one undo step. */+ merge?: { key: string; at: number };}-export type HistoryAction = { type: "commit"; doc: LayerDoc } | { type: "undo" } | { type: "redo" } | { type: "reset"; doc: LayerDoc };+/**+ * `merge` (with `at`, ms) folds a continuous edit into one undo step: a slider drag, typing in a+ * number field, arrow-key nudges. Commits with the same key less than {@link MERGE_WINDOW_MS} apart+ * replace the present instead of adding a step.+ */+export type HistoryAction = { type: "commit"; doc: LayerDoc; merge?: string; at?: number } | { type: "undo" } | { type: "redo" } | { type: "reset"; doc: LayerDoc };export const HISTORY_LIMIT = 100;+export const MERGE_WINDOW_MS = 1200;export function historyReducer(h: History, a: HistoryAction): History {switch (a.type) {- case "commit":+ case "commit": {if (a.doc === h.present) return h;- return { past: [...h.past, h.present].slice(-HISTORY_LIMIT), present: a.doc, future: [] };+ const at = a.at ?? 0;+ const merge = a.merge ? { key: a.merge, at } : undefined;+ if (merge && h.merge?.key === merge.key && h.past.length && at - h.merge.at < MERGE_WINDOW_MS) {+ return { past: h.past, present: a.doc, future: [], merge };+ }+ return { past: [...h.past, h.present].slice(-HISTORY_LIMIT), present: a.doc, future: [], ...(merge ? { merge } : {}) };+ }case "undo":if (!h.past.length) return h;return { past: h.past.slice(0, -1), present: h.past[h.past.length - 1], future: [h.present, ...h.future] };diff --git a/src/server/layers.ts b/src/server/layers.tsindex ecd38fba..a8ec2e65 100644--- a/src/server/layers.ts+++ b/src/server/layers.ts@@ -71,8 +71,11 @@ export class LayersError extends Error {// ---------------------------------------------------------------------------// Validation of documents and job requests coming from the browser-/** Files the document may point at: stored assets only. */-const FileUrl = z.string().max(2000).startsWith("/api/files/");+/** Files the document may point at: stored assets only (no quotes or brackets: thumbnails put them in CSS url()). */+export const FileUrl = z+ .string()+ .max(2000)+ .regex(/^\/api\/files\/[^"'()\\\s<>]+$/);const num = z.number().finite();const BoxSchema = z.tuple([num, num, num, num]);const clamped = (max: number) => z.string().transform((s) => s.slice(0, max));diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.tsindex 82030a79..4cfec64f 100644--- a/tests/layers-api.test.ts+++ b/tests/layers-api.test.ts@@ -232,6 +232,9 @@ describe("layers API", () => {// Files from elsewhere are refused.res = await one.PATCH(req("PATCH", { doc: { ...moved, nodes: [{ ...moved.nodes[0], src: "http://evil.example/x.png" }] } }), ctx({ id }));expect(res.status).toBe(400);+ // A stored-file path can't smuggle quotes or brackets into the thumbnails' CSS url().+ res = await one.PATCH(req("PATCH", { doc: { ...moved, nodes: [{ ...moved.nodes[0], src: '/api/files/x.png"),url(http://evil.example/' }] } }), ctx({ id }));+ expect(res.status).toBe(400);res = await one.PATCH(req("PATCH", { doc: { ...initialDoc("/api/files/other.png", 10, 10) } }), ctx({ id }));expect(res.status).toBe(400);});diff --git a/tests/layers.test.ts b/tests/layers.test.tsindex 36c56533..61f68921 100644--- a/tests/layers.test.ts+++ b/tests/layers.test.ts@@ -19,6 +19,7 @@ import {duplicateNode,expandPads,historyReducer,+ MERGE_WINDOW_MS,initialDoc,layerFileName,moveNode,@@ -346,6 +347,34 @@ describe("edit history", () => {expect(historyReducer(h, { type: "reset", doc: d0 })).toEqual({ past: [], present: d0, future: [] });});+ it("folds a burst of commits with the same merge key into one undo step", () => {+ const d0 = initialDoc("/s.png", 10, 10, 1);+ const at = (w: number) => ({ ...d0, width: w });+ let h: History = { past: [], present: d0, future: [] };+ // A slider drag: 11 → 12 → 13 within the window is one step back to d0.+ h = historyReducer(h, { type: "commit", doc: at(11), merge: "opacity:a", at: 1000 });+ h = historyReducer(h, { type: "commit", doc: at(12), merge: "opacity:a", at: 1100 });+ h = historyReducer(h, { type: "commit", doc: at(13), merge: "opacity:a", at: 2000 });+ expect(h.past).toEqual([d0]);+ expect(h.present.width).toBe(13);+ // A pause longer than the window starts a new step.+ h = historyReducer(h, { type: "commit", doc: at(14), merge: "opacity:a", at: 2000 + MERGE_WINDOW_MS });+ expect(h.past.map((d) => d.width)).toEqual([10, 13]);+ // Another key, or a plain commit, never folds into the previous step.+ h = historyReducer(h, { type: "commit", doc: at(15), merge: "x:a", at: 3300 });+ h = historyReducer(h, { type: "commit", doc: at(16), at: 3301 });+ h = historyReducer(h, { type: "commit", doc: at(17), merge: "x:a", at: 3302 });+ expect(h.past.map((d) => d.width)).toEqual([10, 13, 14, 15, 16]);+ // Undo ends the burst: the next commit with the same key is its own step.+ h = historyReducer(h, { type: "undo" });+ h = historyReducer(h, { type: "commit", doc: at(18), merge: "x:a", at: 3303 });+ expect(h.past.map((d) => d.width)).toEqual([10, 13, 14, 15, 16]);+ expect(h.present.width).toBe(18);+ h = historyReducer(h, { type: "commit", doc: at(19), merge: "x:a", at: 3304 });+ expect(h.past.map((d) => d.width)).toEqual([10, 13, 14, 15, 16]);+ expect(h.present.width).toBe(19);+ });+it("keeps at most 100 steps", () => {let h: History = { past: [], present: initialDoc("/s.png", 1, 1, 0), future: [] };for (let i = 0; i < 130; i++) h = historyReducer(h, { type: "commit", doc: { ...h.present, width: i + 2 } });