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.

Canvas: toolbar (V H D E N R T C), groups that move and run together, comment pins, drawings, page tabs, and the new nodes' panels

Claude2d2a1eee3df8
diff --git a/src/components/canvas/board.tsx b/src/components/canvas/board.tsx
new file mode 100644
index 00000000..10a2dee1
--- /dev/null
+++ b/src/components/canvas/board.tsx
@@ -0,0 +1,417 @@
+"use client";
+
+import { NodeResizer, NodeToolbar, Position, type NodeProps } from "@xyflow/react";
+import { Check, MoreHorizontal, Pencil, Play, RotateCcw, Trash2, Ungroup } from "lucide-react";
+import { memo, useEffect, useRef, useState } from "react";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { newId, type CanvasGraph } from "@/lib/catalog/canvas";
+import { BOARD_COLOR_LABEL, BOARD_COLORS, BOARD_LIMITS, COMMENT_AUTHOR, groupMembers, strokePath, type BoardColor, type CanvasComment, type CanvasGroup, type CanvasShape } from "@/lib/catalog/canvas-board";
+import { timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { useEditorActions, useEditorGlobals, useEditorSelector, type EditorSnapshot } from "./canvas-context";
+import type { FlowNode } from "./nodes";
+
+/**
+ * What's drawn on a page besides the node graph: groups (frames), comment pins and annotation shapes. On the
+ * board they are React Flow nodes like the others (so they select, drag, resize and delete the same way);
+ * in the stored page they are the graph's groups, comments and shapes (src/lib/catalog/canvas-board.ts).
+ */
+export type BoardType = "group" | "comment" | "shape";
+export const BOARD_TYPES: ReadonlySet<string> = new Set<BoardType>(["group", "comment", "shape"]);
+export const isBoardNode = (n: { type?: string }) => BOARD_TYPES.has(n.type ?? "");
+
+/** Stacking: groups behind everything (edges included), drawings under the nodes, comments above all. */
+const Z = { group: -2000, shape: -1, comment: 3000 } as const;
+
+export const BOARD_COLOR_VAR: Record<BoardColor, string> = {
+ ink: "var(--foreground)",
+ "chart-1": "var(--chart-1)",
+ "chart-2": "var(--chart-2)",
+ "chart-3": "var(--chart-3)",
+ "chart-4": "var(--chart-4)",
+ "chart-5": "var(--chart-5)",
+};
+
+const NO_DRAG = "nodrag nopan nowheel";
+
+/** Ids of annotations just made with a tool: they open for typing when they mount (a text box, a comment). */
+export const focusOnMount = new Set<string>();
+
+/**
+ * Focus a just-made annotation's field. React Flow keeps a new node hidden until it has measured it, and a
+ * hidden field can't take the focus: try each frame until it does (half a second at most).
+ */
+function useFocusOnMount(id: string, field: React.RefObject<HTMLElement | null>) {
+ useEffect(() => {
+ if (!focusOnMount.has(id)) return;
+ let frame = 0;
+ let tries = 0;
+ const tick = () => {
+ field.current?.focus();
+ if (document.activeElement === field.current) return void focusOnMount.delete(id);
+ if (++tries < 30) frame = requestAnimationFrame(tick);
+ };
+ frame = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(frame);
+ }, [id, field]);
+}
+
+// ---------------------------------------------------------------------------
+// Page graph ⇄ React Flow nodes
+
+export function boardToFlow(g: CanvasGraph): FlowNode[] {
+ return [
+ ...(g.groups ?? []).map((x): FlowNode => ({ id: x.id, type: "group", position: { x: x.x, y: x.y }, width: x.width, height: x.height, zIndex: Z.group, dragHandle: ".canvas-group-bar", data: { label: x.title, color: x.color } })),
+ ...(g.shapes ?? []).map(
+ (x): FlowNode => ({ id: x.id, type: "shape", position: { x: x.x, y: x.y }, width: x.width, height: x.height, zIndex: Z.shape, data: { kind: x.kind, color: x.color, text: x.text, points: x.points } }),
+ ),
+ ...(g.comments ?? []).map((x): FlowNode => ({ id: x.id, type: "comment", position: { x: x.x, y: x.y }, zIndex: Z.comment, data: { text: x.text, author: x.author, at: x.at, resolved: x.resolved, replies: x.replies } })),
+ ];
+}
+
+const r = Math.round;
+const color = (v: unknown): BoardColor => ((BOARD_COLORS as readonly unknown[]).includes(v) ? (v as BoardColor) : "ink");
+
+/** The groups, comments and shapes among the board's nodes, as stored. */
+export function flowToBoard(nodes: FlowNode[]): Pick<CanvasGraph, "groups" | "comments" | "shapes"> {
+ const groups: CanvasGroup[] = [];
+ const comments: CanvasComment[] = [];
+ const shapes: CanvasShape[] = [];
+ for (const n of nodes) {
+ const d = n.data;
+ const w = r(n.width ?? n.measured?.width ?? 0);
+ const h = r(n.height ?? n.measured?.height ?? 0);
+ if (n.type === "group") groups.push({ id: n.id, title: (d.label ?? "Group").slice(0, BOARD_LIMITS.groupTitle), color: color(d.color), x: r(n.position.x), y: r(n.position.y), width: Math.max(1, w), height: Math.max(1, h) });
+ else if (n.type === "shape") {
+ shapes.push({
+ id: n.id,
+ kind: d.kind as CanvasShape["kind"],
+ x: r(n.position.x),
+ y: r(n.position.y),
+ width: Math.max(1, w),
+ height: Math.max(1, h),
+ color: color(d.color),
+ ...(typeof d.text === "string" && { text: d.text }),
+ ...(Array.isArray(d.points) && { points: d.points as [number, number][] }),
+ });
+ } else if (n.type === "comment") {
+ comments.push({
+ id: n.id,
+ x: r(n.position.x),
+ y: r(n.position.y),
+ author: String(d.author ?? COMMENT_AUTHOR),
+ text: String(d.text ?? ""),
+ at: Number(d.at ?? Date.now()),
+ ...(d.resolved === true && { resolved: true }),
+ ...(Array.isArray(d.replies) && d.replies.length && { replies: d.replies as CanvasComment["replies"] }),
+ });
+ }
+ }
+ return { ...(groups.length && { groups }), ...(comments.length && { comments }), ...(shapes.length && { shapes }) };
+}
+
+export function shapeNode(s: CanvasShape): FlowNode {
+ return boardToFlow({ nodes: [], edges: [], shapes: [s] })[0];
+}
+
+export function groupNode(g: CanvasGroup): FlowNode {
+ return boardToFlow({ nodes: [], edges: [], groups: [g] })[0];
+}
+
+export function commentNode(at: { x: number; y: number }): FlowNode {
+ return { id: newId("comment"), type: "comment", position: at, zIndex: Z.comment, data: { text: "", author: COMMENT_AUTHOR, at: Date.now() } };
+}
+
+// ---------------------------------------------------------------------------
+// Colour swatches (shapes, groups, the toolbar)
+
+export function Swatches({ value, onChange, className }: { value?: BoardColor; onChange: (c: BoardColor) => void; className?: string }) {
+ return (
+ <div className={cn("flex items-center gap-1", className)} role="radiogroup" aria-label="Colour">
+ {BOARD_COLORS.map((c) => (
+ <button
+ key={c}
+ type="button"
+ role="radio"
+ aria-checked={value === c}
+ aria-label={BOARD_COLOR_LABEL[c]}
+ title={BOARD_COLOR_LABEL[c]}
+ onClick={() => onChange(c)}
+ className={cn("grid size-6 place-items-center rounded-full transition-transform hover:scale-110", value === c && "ring-2 ring-primary ring-offset-2 ring-offset-popover")}
+ >
+ <span className="size-4 rounded-full" style={{ background: BOARD_COLOR_VAR[c] }} />
+ </button>
+ ))}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Group
+
+const selectGroupCount = (s: EditorSnapshot, id: string) => {
+ const g = s.graph.groups?.find((x) => x.id === id);
+ return g ? groupMembers(s.graph, g).length : 0;
+};
+
+const GroupNode = memo(function GroupNode({ id, data, selected }: NodeProps<FlowNode>) {
+ const actions = useEditorActions();
+ const { readOnly, running } = useEditorGlobals();
+ const count = useEditorSelector(selectGroupCount, id);
+ const [editing, setEditing] = useState(false);
+ const c = BOARD_COLOR_VAR[color(data.color)];
+ const title = data.label || "Group";
+ return (
+ <div
+ className="canvas-group size-full rounded-2xl border-2"
+ style={{ borderColor: `color-mix(in oklab, ${c} ${selected ? 80 : 45}%, transparent)`, background: `color-mix(in oklab, ${c} 6%, transparent)` }}
+ data-testid={`canvas-group-${id}`}
+ >
+ {!readOnly && <NodeResizer isVisible={!!selected} minWidth={200} minHeight={120} color={c} handleClassName="canvas-resize-handle" lineClassName="canvas-resize-line" />}
+ <div className={cn("canvas-group-bar flex h-11 items-center gap-2 rounded-t-2xl px-3", !readOnly && "cursor-grab active:cursor-grabbing")}>
+ <span className="size-2.5 shrink-0 rounded-full" style={{ background: c }} />
+ {editing ? (
+ <input
+ autoFocus
+ defaultValue={title}
+ maxLength={BOARD_LIMITS.groupTitle}
+ onFocus={(e) => e.currentTarget.select()}
+ onBlur={(e) => {
+ setEditing(false);
+ actions.update(id, { label: e.currentTarget.value.trim() || "Group" });
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ if (e.key === "Escape") setEditing(false);
+ e.stopPropagation();
+ }}
+ aria-label="Group name"
+ className={cn("h-7 min-w-0 flex-1 rounded-md border bg-background px-1.5 text-[14px] font-semibold outline-none focus:border-primary", NO_DRAG)}
+ />
+ ) : (
+ <span className="min-w-0 truncate text-[14px] font-semibold" onDoubleClick={() => !readOnly && setEditing(true)} title={readOnly ? undefined : "Double-click to rename"}>
+ {title}
+ </span>
+ )}
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{count === 1 ? "1 node" : `${count} nodes`}</span>
+ {!readOnly && (
+ <div className={cn("ml-auto flex shrink-0 items-center gap-1", NO_DRAG)}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={() => actions.runGroup(id)}
+ disabled={running || !count}
+ className="inline-flex h-7 items-center gap-1 rounded-full bg-primary px-2.5 text-[12px] font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
+ >
+ <Play className="size-3" /> Run group
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Runs the nodes in this group, and what they need</TooltipContent>
+ </Tooltip>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button className="grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" aria-label={`Actions for ${title}`}>
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ <DropdownMenuItem onSelect={() => actions.runGroup(id)} disabled={!count}>
+ <Play className="size-4" /> Run group
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setTimeout(() => setEditing(true), 0)}>
+ <Pencil className="size-4" /> Rename
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="size-4 rounded-full" style={{ background: c }} /> Colour
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="p-2">
+ <Swatches value={color(data.color)} onChange={(v) => actions.update(id, { color: v })} />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => actions.remove(id)}>
+ <Ungroup className="size-4" /> Ungroup <span className="ml-auto text-[11px] text-muted-foreground">keeps the nodes</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Shapes and drawings
+
+const ShapeNode = memo(function ShapeNode({ id, data, selected, width, height }: NodeProps<FlowNode>) {
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
+ const kind = data.kind as CanvasShape["kind"];
+ const c = BOARD_COLOR_VAR[color(data.color)];
+ const w = Math.max(1, width ?? 1);
+ const h = Math.max(1, height ?? 1);
+ const points = (data.points as [number, number][] | undefined) ?? [];
+ const text = useRef<HTMLTextAreaElement>(null);
+ useFocusOnMount(id, text);
+ const marker = `arrow-${id}`;
+ return (
+ <div className="size-full" style={{ color: c }} data-testid={`canvas-shape-${id}`} aria-label={kind === "text" ? "Text" : kind === "pen" ? "Drawing" : kind}>
+ {!readOnly && kind !== "pen" && <NodeResizer isVisible={!!selected} minWidth={16} minHeight={kind === "text" ? 32 : 16} color="var(--primary)" handleClassName="canvas-resize-handle" lineClassName="canvas-resize-line" />}
+ {selected && !readOnly && (
+ <NodeToolbar position={Position.Top} offset={10} className="flex items-center gap-1 rounded-full border bg-popover p-1 shadow-normal">
+ <Swatches value={color(data.color)} onChange={(v) => actions.update(id, { color: v })} />
+ <button onClick={() => actions.remove(id)} className="ml-1 grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Delete">
+ <Trash2 className="size-3.5" />
+ </button>
+ </NodeToolbar>
+ )}
+ {kind === "text" ? (
+ <textarea
+ ref={text}
+ value={String(data.text ?? "")}
+ onChange={(e) => actions.update(id, { text: e.target.value })}
+ onBlur={(e) => !e.currentTarget.value.trim() && actions.remove(id)}
+ onKeyDown={(e) => {
+ // Escape leaves the text (the board's letter shortcuts work again).
+ if (e.key === "Escape") e.currentTarget.blur();
+ e.stopPropagation();
+ }}
+ readOnly={readOnly}
+ maxLength={BOARD_LIMITS.shapeText}
+ rows={1}
+ placeholder="Type something"
+ aria-label="Text on the board"
+ className={cn("field-sizing-content size-full min-h-8 resize-none bg-transparent font-heading text-[20px] leading-snug outline-none placeholder:text-muted-foreground", selected && NO_DRAG)}
+ style={{ color: c }}
+ />
+ ) : (
+ <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} overflow="visible" className="block">
+ {kind === "rect" && <rect x={1} y={1} width={Math.max(0, w - 2)} height={Math.max(0, h - 2)} rx={10} fill="currentColor" fillOpacity={0.07} stroke="currentColor" strokeWidth={2} />}
+ {kind === "ellipse" && <ellipse cx={w / 2} cy={h / 2} rx={Math.max(0, w / 2 - 1)} ry={Math.max(0, h / 2 - 1)} fill="currentColor" fillOpacity={0.07} stroke="currentColor" strokeWidth={2} />}
+ {kind === "arrow" && points.length === 2 && (
+ <>
+ <defs>
+ <marker id={marker} viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
+ <path d="M0 0 L10 5 L0 10 z" fill="currentColor" />
+ </marker>
+ </defs>
+ <line x1={points[0][0] * w} y1={points[0][1] * h} x2={points[1][0] * w} y2={points[1][1] * h} stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" markerEnd={`url(#${marker})`} />
+ </>
+ )}
+ {kind === "pen" && <path d={strokePath(points, w, h)} fill="none" stroke="currentColor" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />}
+ </svg>
+ )}
+ </div>
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Comments
+
+type Reply = NonNullable<CanvasComment["replies"]>[number];
+
+const CommentNode = memo(function CommentNode({ id, data, selected }: NodeProps<FlowNode>) {
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
+ const text = String(data.text ?? "");
+ const replies = (data.replies as Reply[] | undefined) ?? [];
+ const resolved = data.resolved === true;
+ const [open, setOpen] = useState(() => focusOnMount.has(id));
+ const [draft, setDraft] = useState("");
+ const first = useRef<HTMLTextAreaElement>(null);
+ useFocusOnMount(id, first);
+ // Closing a comment nobody wrote anything in removes it.
+ const close = () => {
+ setOpen(false);
+ if (!text.trim() && !replies.length) actions.remove(id);
+ };
+ const reply = () => {
+ const t = draft.trim();
+ if (!t) return;
+ actions.update(id, { replies: [...replies, { id: newId("reply"), author: COMMENT_AUTHOR, text: t.slice(0, BOARD_LIMITS.commentText), at: Date.now() }].slice(-BOARD_LIMITS.replies) });
+ setDraft("");
+ };
+ const count = (text.trim() ? 1 : 0) + replies.length;
+ return (
+ <div className="relative" data-testid={`canvas-comment-${id}`} onKeyDown={(e) => open && e.key === "Escape" && (e.stopPropagation(), close())}>
+ <button
+ onClick={() => (open ? close() : setOpen(true))}
+ className={cn(
+ "grid size-8 place-items-center rounded-full rounded-bl-none border-2 border-background text-[12px] font-semibold shadow-normal transition-transform hover:scale-105",
+ resolved ? "bg-muted text-muted-foreground" : "bg-primary text-primary-foreground",
+ selected && "ring-2 ring-primary ring-offset-2 ring-offset-background",
+ )}
+ aria-label={resolved ? "Resolved comment" : `Comment${count > 1 ? `, ${count} messages` : ""}`}
+ aria-expanded={open}
+ >
+ {resolved ? <Check className="size-3.5" /> : COMMENT_AUTHOR[0]}
+ </button>
+ {open && (
+ <div className={cn("absolute top-0 left-10 w-72 animate-pop-in cursor-default rounded-xl border bg-popover p-3 text-popover-foreground shadow-strong", NO_DRAG)}>
+ <div className="flex items-center gap-2 text-[12px]">
+ <span className="grid size-5 place-items-center rounded-full bg-primary text-[10px] font-semibold text-primary-foreground">{COMMENT_AUTHOR[0]}</span>
+ <span className="font-medium">{String(data.author ?? COMMENT_AUTHOR)}</span>
+ <span className="text-muted-foreground">{typeof data.at === "number" ? timeAgo(data.at) : "just now"}</span>
+ {resolved && <span className="rounded-full bg-success/15 px-1.5 text-[10px] font-semibold text-success">Resolved</span>}
+ </div>
+ <textarea
+ ref={first}
+ value={text}
+ onChange={(e) => actions.update(id, { text: e.target.value })}
+ readOnly={readOnly}
+ rows={2}
+ maxLength={BOARD_LIMITS.commentText}
+ placeholder="Add a comment"
+ aria-label="Comment"
+ className="mt-2 field-sizing-content max-h-40 min-h-12 w-full resize-none rounded-lg bg-muted px-2.5 py-2 text-[13px] leading-snug outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint"
+ />
+ {replies.length > 0 && (
+ <ul className="mt-2 max-h-48 space-y-2 overflow-y-auto">
+ {replies.map((x) => (
+ <li key={x.id} className="text-[13px] leading-snug">
+ <span className="font-medium">{x.author}</span> <span className="text-[11px] text-muted-foreground">{timeAgo(x.at)}</span>
+ <p className="break-words whitespace-pre-line">{x.text}</p>
+ </li>
+ ))}
+ </ul>
+ )}
+ {!readOnly && text.trim() && (
+ <input
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") reply();
+ e.stopPropagation();
+ }}
+ placeholder="Reply"
+ aria-label="Reply"
+ className="mt-2 h-8 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none focus:border-primary"
+ />
+ )}
+ {!readOnly && (
+ <div className="mt-2 flex items-center gap-1">
+ <button
+ onClick={() => actions.update(id, { resolved: !resolved })}
+ disabled={!text.trim()}
+ className="inline-flex h-7 items-center gap-1 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-50"
+ >
+ {resolved ? <RotateCcw className="size-3" /> : <Check className="size-3" />} {resolved ? "Reopen" : "Resolve"}
+ </button>
+ <button onClick={() => actions.remove(id)} className="ml-auto grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Delete comment">
+ <Trash2 className="size-3.5" />
+ </button>
+ <button onClick={close} className="inline-flex h-7 items-center rounded-full px-2.5 text-[12px] font-medium hover:bg-accent">
+ Done
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+});
+
+export const BOARD_NODE_TYPES = { group: GroupNode, shape: ShapeNode, comment: CommentNode } satisfies Record<BoardType, React.ComponentType<NodeProps<FlowNode>>>;
diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsx
index a2bfcf4f..05ca8080 100644
--- a/src/components/canvas/canvas-context.tsx
+++ b/src/components/canvas/canvas-context.tsx
@@ -3,6 +3,7 @@
import {
AtSign,
AudioLines,
+ AudioWaveform,
Clapperboard,
Columns3,
Combine,
@@ -11,6 +12,7 @@ import {
Frame,
GalleryHorizontal,
ImageIcon,
+ Languages,
MessageSquareText,
Mic2,
MonitorPlay,
@@ -18,6 +20,7 @@ import {
Sparkles,
StickyNote,
Type,
+ UserRound,
ZoomIn,
type LucideIcon,
} from "lucide-react";
@@ -30,6 +33,7 @@ import {
type CanvasNode,
type CanvasNodeData,
type CanvasPlan,
+ type ClipSettings,
type Connection,
type NodeDescription,
type PortType,
@@ -57,6 +61,9 @@ export const ICONS: Record<string, LucideIcon> = {
Package,
GalleryHorizontal,
Columns3,
+ AudioWaveform,
+ UserRound,
+ Languages,
};
/** A node type's or template's icon, by lucide name. */
@@ -91,7 +98,8 @@ export interface NodeResults {
export const EMPTY_RESULTS: NodeResults = { gens: [], state: "idle", progress: null, message: null, error: null, outputs: [] };
-export function foldResults(gens: Generation[]): NodeResults {
+/** A node's latest run folded into one status; `out` (a node made in several steps) is the generation whose outputs it shows. */
+export function foldResults(gens: Generation[], out?: string): NodeResults {
if (!gens.length) return EMPTY_RESULTS;
const has = (s: GenerationStatus) => gens.some((g) => g.status === s);
const state: NodeState = has("running") ? "running" : has("queued") ? "queued" : has("failed") ? "failed" : has("canceled") ? "canceled" : "succeeded";
@@ -103,14 +111,14 @@ export function foldResults(gens: Generation[]): NodeResults {
progress: progress && progress > 0 ? progress : null,
message: live[0]?.message ?? null,
error: gens.find((g) => g.status === "failed")?.error ?? null,
- outputs: gens.flatMap((g) => (g.status === "succeeded" ? g.outputs.map((o, i) => ({ g, o, i })) : [])),
+ outputs: gens.flatMap((g) => (g.status === "succeeded" && (!out || g.id === out) ? g.outputs.map((o, i) => ({ g, o, i })) : [])),
};
}
/** The same results object when the node's generations are the very same objects (memoized nodes skip a render). */
-export function foldResultsKeep(prev: NodeResults | undefined, gens: Generation[]): NodeResults {
+export function foldResultsKeep(prev: NodeResults | undefined, gens: Generation[], out?: string): NodeResults {
if (prev && prev.gens.length === gens.length && prev.gens.every((g, i) => g === gens[i])) return prev;
- return foldResults(gens);
+ return foldResults(gens, out);
}
// ---------------------------------------------------------------------------
@@ -203,6 +211,8 @@ export class DescribeCache {
for (const e of into.get(n.id) ?? []) {
const s = byId.get(e.source);
key.push(e.source, e.targetHandle, s?.type, s?.data, s?.position.x, s?.position.y);
+ // A cloned voice passes on what's wired into it: that is an input of this node too.
+ if (s?.type === "clone-voice") for (const f of into.get(s.id) ?? []) key.push(f.source, byId.get(f.source)?.type, byId.get(f.source)?.data);
}
const old = this.entries.get(n.id);
const entry = old && old.key.length === key.length && old.key.every((k, i) => k === key[i]) ? old : { key, info: { d: describeNode(graph, n, { engineMode: mode }), op: effectiveOp(graph, n) } };
@@ -289,6 +299,10 @@ export interface EditorActions {
remove: (id: string) => void;
duplicate: (id: string) => void;
run: (targets?: string[], force?: boolean) => void;
+ /** Run a group's nodes (and what they need upstream). */
+ runGroup: (groupId: string) => void;
+ /** Change one clip of a Video concatenator (its cut, its sound, or the facts measured from its file). */
+ patchClip: (nodeId: string, clipId: string, patch: Partial<ClipSettings>) => void;
cancel: (id: string) => void;
open: (id: string, index?: number) => void;
/** Add an input node holding this node's first output, wired nowhere yet. */
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsx
index 2c25eea8..6fe2f281 100644
--- a/src/components/canvas/canvas-editor.tsx
+++ b/src/components/canvas/canvas-editor.tsx
@@ -14,6 +14,7 @@ import {
Panel,
ReactFlow,
ReactFlowProvider,
+ SelectionMode,
useNodesInitialized,
useReactFlow,
type Connection,
@@ -22,6 +23,7 @@ import {
type FitViewOptions,
type NodeChange,
type OnConnectEnd,
+ type OnNodeDrag,
type Viewport,
} from "@xyflow/react";
import { ChevronDown, ChevronLeft, Check, Cloud, Cpu, LayoutGrid, List, Loader2, Play, RotateCcw, Sparkles, TriangleAlert } from "lucide-react";
@@ -43,6 +45,19 @@ import { useIsMobile } from "@/hooks/use-mobile";
import { useElements, useEngine, useStatus, type EngineMode } from "@/lib/api";
import { getModel } from "@/lib/catalog";
import { onEngine, runsOn } from "@/lib/catalog/engines";
+import {
+ BOARD_LIMITS,
+ copyPage,
+ dragShape,
+ groupAround,
+ nextPageName,
+ penShape,
+ shapeHit,
+ withPageGraph,
+ type BoardColor,
+ type CanvasPage,
+ type CanvasShape,
+} from "@/lib/catalog/canvas-board";
import {
acceptsType,
cleanGraph,
@@ -69,6 +84,7 @@ import {
type CanvasGraph,
type CanvasNode,
type CanvasNodeData,
+ type ClipSettings,
type PaletteItem,
type PortType,
} from "@/lib/catalog/canvas";
@@ -89,9 +105,11 @@ import {
type EditorSnapshot,
type NodeResults,
} from "./canvas-context";
+import { BOARD_COLOR_VAR, boardToFlow, commentNode, flowToBoard, focusOnMount, groupNode, isBoardNode, shapeNode } from "./board";
import { NodeList } from "./node-list";
import { NODE_TYPES, type FlowNode } from "./nodes";
import { AddMenu, DRAG_TYPE, Palette, PaletteToggle } from "./palette";
+import { BoardToolbar, PageTabs, TOOL_KEYS, type DragShape, type PageOps, type Tool } from "./toolbar";
import { saveCanvas, useCanvasView, useRunCanvas, type CanvasView } from "./use-canvas";
const GRID: [number, number] = [16, 16];
@@ -104,21 +122,41 @@ const READABLE_ZOOM = 0.5;
const toFlowNode = (n: CanvasNode): FlowNode => ({ id: n.id, type: n.type, position: n.position, data: n.data, ...(n.type === "output" && n.width ? { width: n.width } : {}) });
const toFlowEdge = (e: CanvasEdge): Edge => ({ id: e.id, source: e.source, target: e.target, sourceHandle: e.sourceHandle ?? OUT, targetHandle: e.targetHandle ?? null });
+/** A page's board as React Flow nodes: its groups, drawings and comments first (they sit under the graph), then its nodes. */
+const toFlowNodes = (g: CanvasGraph): FlowNode[] => [...boardToFlow(g), ...g.nodes.map(toFlowNode)];
function toGraph(nodes: FlowNode[], edges: Edge[], viewport?: Viewport): CanvasGraph {
+ const graphNodes: CanvasNode[] = [];
+ const board: FlowNode[] = [];
+ for (const n of nodes) {
+ if (isBoardNode(n)) board.push(n);
+ else
+ graphNodes.push({
+ id: n.id,
+ type: n.type as CanvasNode["type"],
+ position: { x: Math.round(n.position.x), y: Math.round(n.position.y) },
+ data: n.data,
+ ...(n.type === "output" && n.width ? { width: n.width } : {}),
+ });
+ }
return {
- nodes: nodes.map((n) => ({
- id: n.id,
- type: n.type as CanvasNode["type"],
- position: { x: Math.round(n.position.x), y: Math.round(n.position.y) },
- data: n.data,
- ...(n.type === "output" && n.width ? { width: n.width } : {}),
- })),
+ nodes: graphNodes,
edges: edges.map((e) => ({ id: e.id, source: e.source, target: e.target, sourceHandle: e.sourceHandle ?? OUT, targetHandle: e.targetHandle ?? null })),
...(viewport && { viewport: { x: Math.round(viewport.x), y: Math.round(viewport.y), zoom: Math.round(viewport.zoom * 1000) / 1000 } }),
+ ...(board.length && flowToBoard(board)),
};
}
+/** A drawing on the board as stored (for the eraser's hit test). */
+const asShape = (n: FlowNode): CanvasShape | null =>
+ n.type === "shape" ? (flowToBoard([n]).shapes?.[0] ?? null) : null;
+
+/** Focus is in a field (typing there never switches tools). */
+const typing = (t: EventTarget | null) => !!(t as HTMLElement | null)?.closest?.("input, textarea, select, [contenteditable='true'], [role='menu'], [role='listbox'], [role='dialog']");
+
+/** Board tools that turn a drag or click on the board into a drawing, a note or a comment. */
+const GESTURE_TOOLS = new Set<Tool>(["draw", "erase", "note", "shape", "text", "comment"]);
+
/** Edges whose handles still exist after a model / op change. */
function pruneEdges(nodes: FlowNode[], edges: Edge[]): Edge[] {
const keep = new Set(cleanGraph(toGraph(nodes, edges)).edges.map((e) => e.id));
@@ -181,9 +219,19 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const runM = useRunCanvas(id);
const runMutate = runM.mutate;
- const [nodes, setNodes] = useState<FlowNode[]>(() => initial.pages[0].graph.nodes.map(toFlowNode));
+ // Pages: the active one lives in nodes / edges; the others (and the active one as last switched to) in `pages`.
+ const [pages, setPages] = useState<CanvasPage[]>(() => initial.pages);
+ const [pageId, setPageId] = useState(() => initial.pages[0].id);
+ const [nodes, setNodes] = useState<FlowNode[]>(() => toFlowNodes(initial.pages[0].graph));
const [edges, setEdges] = useState<Edge[]>(() => initial.pages[0].graph.edges.map(toFlowEdge));
const [name, setName] = useState(initial.name);
+ const [tool, setTool] = useState<Tool>("select");
+ const [shapeKind, setShapeKind] = useState<DragShape>("rect");
+ const [ink, setInk] = useState<BoardColor>("chart-2");
+ const toolNow = useRef(tool);
+ useEffect(() => {
+ toolNow.current = tool;
+ }, [tool]);
const [tab, setTab] = useState<"board" | "list">("board");
const [paletteOpen, setPaletteOpen] = useState(true);
const [menu, setMenu] = useState<MenuState | null>(null);
@@ -199,12 +247,14 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const savedName = useRef(initial.name);
// Latest state for event handlers and the save on leave (synced right after each commit).
- const latest = useRef({ nodes, edges, rev });
+ const latest = useRef({ nodes, edges, rev, pages, pageId });
useLayoutEffect(() => {
- latest.current = { nodes, edges, rev };
- }, [nodes, edges, rev]);
+ latest.current = { nodes, edges, rev, pages, pageId };
+ }, [nodes, edges, rev, pages, pageId]);
const touch = useCallback(() => setRev((r) => r + 1), []);
+ /** Every page as it is now (the active one from the board), as saved. */
+ const docOf = useCallback(() => withPageGraph(latest.current.pages, latest.current.pageId, toGraph(latest.current.nodes, latest.current.edges, viewport.current)), []);
// ---- derived: graph, plan, results, and the per-node views the nodes subscribe to
const [store] = useState(() => new EditorStore());
@@ -246,8 +296,10 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
// eslint-disable-next-line react-hooks/exhaustive-deps
[planned, plan, described, results, runErrors],
);
- const selected = useMemo(() => nodes.filter((n) => n.selected).map((n) => n.id), [nodes]);
+ // What Run selected runs (the graph's nodes; frames, drawings and comments aren't run).
+ const selected = useMemo(() => nodes.filter((n) => n.selected && !isBoardNode(n)).map((n) => n.id), [nodes]);
const busy = [...results.values()].filter((r) => r.state === "running" || r.state === "queued").length;
+ const selectedForGroup = useMemo(() => nodes.filter((n) => n.selected && n.type !== "group" && n.type !== "comment").length, [nodes]);
const generators = graph.nodes.filter(isGenerator);
const isDemo = useCallback(
@@ -267,7 +319,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
// Fit around the nodes, leaving the palette's side free.
const fitFor = useCallback(
(withPalette: boolean): FitViewOptions<FlowNode> => ({
- padding: { top: "56px", right: "56px", bottom: "56px", left: withPalette && !isMobile ? `${PALETTE_SPACE}px` : isMobile ? "16px" : "56px" },
+ padding: { top: isMobile ? "56px" : "72px", right: "56px", bottom: isMobile ? "56px" : "72px", left: withPalette && !isMobile ? `${PALETTE_SPACE}px` : isMobile ? "16px" : "56px" },
maxZoom: 1,
minZoom: isMobile ? 0.3 : 0.5,
}),
@@ -299,6 +351,14 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
});
return () => cancelAnimationFrame(frame);
}, [initialized, savedViewport, rf, fitFor, paletteOpen, isMobile]);
+ // A page opened without a saved view (new, or on a phone): fitted once its nodes have their sizes.
+ const pageFit = useRef(false);
+ useEffect(() => {
+ if (!initialized || !pageFit.current) return;
+ pageFit.current = false;
+ const frame = requestAnimationFrame(() => void rf.fitView({ ...fitFor(paletteOpen), minZoom: isMobile ? 0.15 : 0.3 }));
+ return () => cancelAnimationFrame(frame);
+ }, [initialized, nodes.length, rf, fitFor, paletteOpen, isMobile]);
// ---- autosave
const save = useCallback(
@@ -307,7 +367,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
if (at === savedRev.current) return;
setSaveState("saving");
try {
- await saveCanvas(id, { graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) }, keepalive);
+ await saveCanvas(id, { pages: docOf() }, keepalive);
savedRev.current = Math.max(savedRev.current, at);
setSaveState("saved");
setSaveRefused(false);
@@ -322,7 +382,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
}
}
},
- [id, qc],
+ [id, qc, docOf],
);
useEffect(() => {
if (rev === 0) return;
@@ -353,13 +413,13 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const at = latest.current.rev;
if (at === savedRev.current) return;
savedRev.current = at;
- void saveCanvas(id, { graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) }, true)
+ void saveCanvas(id, { pages: docOf() }, true)
.then(() => qc.invalidateQueries({ queryKey: ["canvases"], exact: true }))
.catch(() => {
// Not saved after all: the next edit (or the next visit) saves again.
savedRev.current = -1;
});
- }, [id, qc]);
+ }, [id, qc, docOf]);
useEffect(() => flushOnLeave, [flushOnLeave]);
const rename = async (next: string) => {
@@ -404,8 +464,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
/** Deleted nodes come back with their edges from the toast's Undo. */
const offerUndo = useCallback(
- (count: number, before: { nodes: FlowNode[]; edges: Edge[] }) =>
- toast(count === 1 ? "Node deleted" : `${count} nodes deleted`, {
+ (count: number, before: { nodes: FlowNode[]; edges: Edge[] }, what = "node") =>
+ toast(count === 1 ? `${what[0].toUpperCase()}${what.slice(1)} deleted` : `${count} ${what}s deleted`, {
duration: 5000,
action: {
label: "Undo",
@@ -422,10 +482,15 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const remove = useCallback(
(nodeId: string) => {
const before = latest.current;
+ const type = before.nodes.find((n) => n.id === nodeId)?.type;
setNodes((ns) => ns.filter((n) => n.id !== nodeId));
setEdges((es) => es.filter((e) => e.source !== nodeId && e.target !== nodeId));
touch();
- offerUndo(1, before);
+ // Ungrouping keeps the nodes: no undo needed for a frame. An empty comment closing goes quietly.
+ if (type === "group") return void toast("Ungrouped — the nodes stay where they are", { duration: 2500, action: { label: "Undo", onClick: () => (setNodes(before.nodes), touch()) } });
+ const n = before.nodes.find((x) => x.id === nodeId);
+ if (type === "comment" && !String(n?.data.text ?? "").trim()) return;
+ offerUndo(1, before, type === "comment" ? "comment" : type === "shape" ? "drawing" : "node");
},
[touch, offerUndo],
);
@@ -480,13 +545,38 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[engine, mode, touch],
);
+ // A group moves what's inside it: its members as they were when the drag started (not what it sweeps over).
+ const groupDrag = useRef(new Map<string, { origin: { x: number; y: number }; members: Map<string, { x: number; y: number }> }>());
+ const onNodeDragStart: OnNodeDrag<FlowNode> = useCallback((_e, _node, dragged) => {
+ groupDrag.current.clear();
+ const moving = new Set(dragged.map((n) => n.id));
+ for (const g of dragged) {
+ if (g.type !== "group") continue;
+ const box = { x: g.position.x, y: g.position.y, w: g.width ?? g.measured?.width ?? 0, h: g.height ?? g.measured?.height ?? 0 };
+ const members = latest.current.nodes.filter((n) => !moving.has(n.id) && n.position.x >= box.x && n.position.y >= box.y && n.position.x <= box.x + box.w && n.position.y <= box.y + box.h);
+ groupDrag.current.set(g.id, { origin: { ...g.position }, members: new Map(members.map((m) => [m.id, { ...m.position }])) });
+ }
+ }, []);
+ const onNodeDragStop = useCallback(() => groupDrag.current.clear(), []);
+
const onNodesChange = useCallback(
(changes: NodeChange<FlowNode>[]) => {
- const removed = changes.filter((c) => c.type === "remove").length;
+ const removed = changes.filter((c) => c.type === "remove");
const before = latest.current;
- setNodes((ns) => applyNodeChanges(changes, ns));
- if (changes.some((c) => c.type === "remove" || c.type === "add" || c.type === "replace" || (c.type === "position" && !c.dragging))) touch();
- if (removed) offerUndo(removed, before);
+ const follow: NodeChange<FlowNode>[] = [];
+ for (const c of changes) {
+ const drag = c.type === "position" && c.position ? groupDrag.current.get(c.id) : undefined;
+ if (!drag || c.type !== "position" || !c.position) continue;
+ const dx = c.position.x - drag.origin.x;
+ const dy = c.position.y - drag.origin.y;
+ for (const [mid, p] of drag.members) follow.push({ type: "position", id: mid, position: { x: p.x + dx, y: p.y + dy }, dragging: c.dragging });
+ }
+ setNodes((ns) => applyNodeChanges(follow.length ? [...changes, ...follow] : changes, ns));
+ if (changes.some((c) => c.type === "remove" || c.type === "add" || c.type === "replace" || (c.type === "position" && !c.dragging) || (c.type === "dimensions" && c.resizing === false))) touch();
+ if (removed.length) {
+ const kinds = new Set(removed.map((c) => before.nodes.find((n) => n.id === c.id)?.type));
+ offerUndo(removed.length, before, kinds.size === 1 && kinds.has("comment") ? "comment" : kinds.size === 1 && kinds.has("shape") ? "drawing" : kinds.size === 1 && kinds.has("group") ? "group" : "node");
+ }
},
[touch, offerUndo],
);
@@ -558,13 +648,13 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
});
}, [menu, engine, palette]);
- // ---- running
+ // ---- running (the page on the board)
const run = useCallback(
- (targets?: string[], force?: boolean) => {
+ (targets?: string[], force?: boolean, group?: string) => {
const go = (t?: string[], f?: boolean) => {
const at = latest.current.rev;
runMutate(
- { targets: t, force: f, graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) },
+ { page: latest.current.pageId, targets: t, group, force: f, graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) },
{
onSuccess: (r) => {
// The run saved the board too.
@@ -610,6 +700,187 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
toast("Added as an input — connect it anywhere");
};
+ /** One clip of a Video concatenator: merged into what the node holds now (several clips report their lengths at once). */
+ const patchClip = useCallback(
+ (nodeId: string, clipId: string, patch: Partial<ClipSettings>) => {
+ setNodes((ns) =>
+ ns.map((n) => {
+ if (n.id !== nodeId) return n;
+ const clips = { ...n.data.clips };
+ const next: ClipSettings = { ...clips[clipId], ...patch };
+ for (const k of Object.keys(next) as (keyof ClipSettings)[]) if (next[k] === undefined) delete next[k];
+ clips[clipId] = next;
+ return { ...n, data: { ...n.data, clips } };
+ }),
+ );
+ touch();
+ },
+ [touch],
+ );
+
+ // ---- groups
+ const groupSelection = useCallback(() => {
+ const sel = latest.current.nodes.filter((n) => n.selected && n.type !== "group" && n.type !== "comment");
+ if (!sel.length) return void toast("Select what to group first: drag a box around the nodes, or ⇧-click them");
+ const g = groupAround(newId("group"), [rf.getNodesBounds(sel)], "Group");
+ if (!g) return;
+ setNodes((ns) => [groupNode(g), ...ns.map((n) => (n.selected ? { ...n, selected: false } : n))]);
+ touch();
+ toast(`Grouped ${sel.length === 1 ? "1 node" : `${sel.length} nodes`}`, { description: "Drag the group's title to move them together; Run group runs them", duration: 3000 });
+ }, [rf, touch]);
+ const ungroupSelection = useCallback(() => {
+ const ids = latest.current.nodes.filter((n) => n.selected && n.type === "group").map((n) => n.id);
+ if (!ids.length) return;
+ const before = latest.current.nodes;
+ setNodes((ns) => ns.filter((n) => !ids.includes(n.id)));
+ touch();
+ toast(ids.length === 1 ? "Ungrouped" : `${ids.length} groups ungrouped`, { duration: 2500, action: { label: "Undo", onClick: () => (setNodes(before), touch()) } });
+ }, [touch]);
+
+ // ---- pages
+ /** Show another page: the board's page is put back into `pages` first, so nothing on it is lost. */
+ const showPage = useCallback(
+ (next: CanvasPage[], to: string) => {
+ const target = next.find((p) => p.id === to) ?? next[0];
+ setPages(next);
+ setPageId(target.id);
+ setNodes(toFlowNodes(target.graph));
+ setEdges(target.graph.edges.map(toFlowEdge));
+ setRunErrors({});
+ setMenu(null);
+ setViewer(null);
+ viewport.current = target.graph.viewport;
+ if (target.graph.viewport && !isMobile) rf.setViewport(target.graph.viewport);
+ else pageFit.current = true;
+ },
+ [rf, isMobile],
+ );
+ const pageOps = useMemo<PageOps>(
+ () => ({
+ switchTo: (to) => {
+ if (to !== latest.current.pageId) showPage(docOf(), to);
+ },
+ add: () => {
+ const doc = docOf();
+ if (doc.length >= BOARD_LIMITS.pages) return;
+ const page: CanvasPage = { id: newId("page"), name: nextPageName(doc), graph: { nodes: [], edges: [] } };
+ showPage([...doc, page], page.id);
+ touch();
+ },
+ rename: (pid, nm) => {
+ setPages(docOf().map((p) => (p.id === pid ? { ...p, name: nm.slice(0, 60) } : p)));
+ touch();
+ },
+ duplicate: (pid) => {
+ const doc = docOf();
+ const src = doc.find((p) => p.id === pid);
+ if (!src || doc.length >= BOARD_LIMITS.pages) return;
+ const copy = copyPage(src, newId("page"), `${src.name} copy`.slice(0, 60), newId);
+ const at = doc.indexOf(src) + 1;
+ showPage([...doc.slice(0, at), copy, ...doc.slice(at)], copy.id);
+ touch();
+ },
+ remove: (pid) => {
+ const doc = docOf();
+ if (doc.length < 2) return;
+ const was = latest.current.pageId;
+ const at = doc.findIndex((p) => p.id === pid);
+ const next = doc.filter((p) => p.id !== pid);
+ showPage(next, pid === was ? next[Math.max(0, at - 1)].id : was);
+ touch();
+ toast(`Deleted “${doc[at].name}”`, {
+ description: "Its results stay in your library",
+ duration: 6000,
+ action: {
+ label: "Undo",
+ onClick: () => {
+ showPage(doc, was);
+ touch();
+ },
+ },
+ });
+ },
+ }),
+ [docOf, showPage, touch],
+ );
+
+ // ---- board tools: a drag or click on the board draws, erases, or places a note, text or comment
+ const [stroke, setStroke] = useState<{ points: { x: number; y: number }[]; kind: Tool } | null>(null);
+ const placeShape = useCallback(
+ (s: CanvasShape, focus = false) => {
+ if (focus) focusOnMount.add(s.id);
+ setNodes((ns) => [...ns.map((n) => (n.selected ? { ...n, selected: false } : n)), { ...shapeNode(s), selected: !focus }]);
+ touch();
+ },
+ [touch],
+ );
+ const onToolPointerDown = (e: React.PointerEvent) => {
+ if (isMobile || !GESTURE_TOOLS.has(tool) || e.button !== 0) return;
+ const el = e.target as HTMLElement;
+ if (el.closest(".react-flow__panel, .react-flow__controls, .react-flow__minimap, [data-board-ui]")) return;
+ e.preventDefault();
+ e.stopPropagation();
+ const rect = wrapper.current!.getBoundingClientRect();
+ const flowAt = (x: number, y: number) => rf.screenToFlowPosition({ x, y });
+ const start = flowAt(e.clientX, e.clientY);
+ const screen = [{ x: e.clientX - rect.left, y: e.clientY - rect.top }];
+ const points = [start];
+ const before = latest.current;
+ let erased = 0;
+ const erase = (p: { x: number; y: number }) => {
+ const tol = 8 / rf.getZoom();
+ const hit = new Set(latest.current.nodes.filter((n) => n.type === "shape").filter((n) => { const sh = asShape(n); return sh && shapeHit(sh, p, tol); }).map((n) => n.id));
+ if (!hit.size) return;
+ erased += hit.size;
+ latest.current = { ...latest.current, nodes: latest.current.nodes.filter((n) => !hit.has(n.id)) };
+ setNodes((ns) => ns.filter((n) => !hit.has(n.id)));
+ };
+ if (tool === "erase") erase(start);
+ const move = (ev: PointerEvent) => {
+ const p = flowAt(ev.clientX, ev.clientY);
+ points.push(p);
+ screen.push({ x: ev.clientX - rect.left, y: ev.clientY - rect.top });
+ if (tool === "erase") erase(p);
+ else if (tool === "draw" || tool === "shape") setStroke({ points: tool === "draw" ? [...screen] : [screen[0], screen[screen.length - 1]], kind: tool });
+ };
+ const up = (ev: PointerEvent) => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ setStroke(null);
+ const end = flowAt(ev.clientX, ev.clientY);
+ const dragged = Math.hypot(ev.clientX - rect.left - screen[0].x, ev.clientY - rect.top - screen[0].y) > 6;
+ if (tool === "erase") {
+ if (erased) {
+ touch();
+ offerUndo(erased, before, "drawing");
+ }
+ return;
+ }
+ if (tool === "draw") {
+ const s = penShape(newId("shape"), points, ink);
+ if (s) placeShape(s);
+ return;
+ }
+ if (tool === "shape") {
+ const b = dragged ? end : { x: start.x + 160, y: start.y + (shapeKind === "arrow" ? 0 : 100) };
+ placeShape(dragShape(newId("shape"), shapeKind, start, b, ink));
+ } else if (tool === "text") {
+ placeShape({ id: newId("shape"), kind: "text", x: Math.round(start.x), y: Math.round(start.y - 16), width: 260, height: 40, color: ink, text: "" }, true);
+ } else if (tool === "note") {
+ addNode(palette.find((p) => p.id === "note")!, start);
+ } else if (tool === "comment") {
+ const c = commentNode(start);
+ focusOnMount.add(c.id);
+ setNodes((ns) => [...ns.map((n) => (n.selected ? { ...n, selected: false } : n)), c]);
+ touch();
+ }
+ // Placing is one-off: back to Select (drawing and erasing stay on until switched off).
+ setTool("select");
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ };
+
// ---- engine
const boardEngine = graphEngine(graph) ?? engine;
const switchEngine = (e: Engine) => {
@@ -655,6 +926,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
remove,
duplicate,
run,
+ runGroup: (gid) => run(undefined, false, gid),
+ patchClip,
cancel: (nid) => void cancel(nid),
open: (nid, index = 0) => setViewer({ nodeId: nid, index }),
toInput,
@@ -669,6 +942,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
remove: (...a) => handlers.current!.remove(...a),
duplicate: (...a) => handlers.current!.duplicate(...a),
run: (...a) => handlers.current!.run(...a),
+ runGroup: (...a) => handlers.current!.runGroup(...a),
+ patchClip: (...a) => handlers.current!.patchClip(...a),
cancel: (...a) => handlers.current!.cancel(...a),
open: (...a) => handlers.current!.open(...a),
toInput: (...a) => handlers.current!.toInput(...a),
@@ -679,11 +954,28 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[],
);
- // ---- keyboard: ⌘↵ runs (the selection, else everything), ⌘D duplicates
+ // ---- keyboard: ⌘↵ runs (the selection, else everything), ⌘D duplicates, ⌘G groups (⇧⌘G ungroups),
+ // and the board tools by letter: V H D E N R T C (Escape goes back to Select)
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey;
- if (!mod) return;
+ if (!mod) {
+ if (e.altKey || isMobile || typing(e.target)) return;
+ if (e.key === "Escape") return void setTool("select");
+ const t = TOOL_KEYS[e.key.toLowerCase()];
+ if (!t || e.repeat) return;
+ e.preventDefault();
+ // R again cycles rectangle → ellipse → arrow.
+ if (t === "shape" && toolNow.current === "shape") setShapeKind((k) => (k === "rect" ? "ellipse" : k === "ellipse" ? "arrow" : "rect"));
+ setTool(t);
+ return;
+ }
+ if (e.key.toLowerCase() === "g" && !typing(e.target)) {
+ e.preventDefault();
+ if (e.shiftKey) ungroupSelection();
+ else groupSelection();
+ return;
+ }
if (e.key === "Enter") {
e.preventDefault();
const sel = latest.current.nodes.filter((n) => n.selected).map((n) => n.id);
@@ -697,7 +989,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [actions, duplicate]);
+ }, [actions, duplicate, isMobile, groupSelection, ungroupSelection]);
// ---- drop from the palette, or files from the desktop
const onDragOver = (e: React.DragEvent) => {
@@ -771,6 +1063,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[edges, edgeLook],
);
const miniColor = useCallback((n: FlowNode) => {
+ if (n.type === "group") return "color-mix(in oklab, var(--muted-foreground) 18%, transparent)";
+ if (n.type === "shape" || n.type === "comment") return "transparent";
const t = typeOfNode(n);
return t ? PORT_COLOR[t] : "var(--muted-foreground)";
}, []);
@@ -843,6 +1137,15 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
</button>
))}
</div>
+ {pages.length > 1 && (
+ <select value={pageId} onChange={(e) => pageOps.switchTo(e.target.value)} aria-label="Page" className="h-9 max-w-32 min-w-0 truncate rounded-full bg-muted px-3 text-[13px] font-medium outline-none">
+ {pages.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.name}
+ </option>
+ ))}
+ </select>
+ )}
<span className="ml-auto truncate font-mono text-[11px] text-muted-foreground">{busy ? `${busy} running` : summary}</span>
</div>
)}
@@ -880,6 +1183,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
<div
ref={wrapper}
className="relative min-h-0 flex-1"
+ data-tool={isMobile ? undefined : tool}
+ onPointerDownCapture={onToolPointerDown}
onDragOver={onDragOver}
onDrop={onDrop}
onDoubleClick={(e) => {
@@ -895,6 +1200,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onConnectEnd={onConnectEnd}
+ onNodeDragStart={onNodeDragStart}
+ onNodeDragStop={onNodeDragStop}
isValidConnection={isValidConnection}
onPaneContextMenu={(e) => {
e.preventDefault();
@@ -916,7 +1223,13 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
zoomOnDoubleClick={false}
deleteKeyCode={isMobile ? null : ["Backspace", "Delete"]}
multiSelectionKeyCode={["Meta", "Shift", "Control"]}
- nodesDraggable={!isMobile}
+ // Select (V): a drag on the board draws a selection box, Space or the middle button pans. Pan (H): a
+ // drag moves the board. The drawing tools take the pointer themselves (onToolPointerDown).
+ panOnDrag={isMobile || tool === "hand" ? true : tool === "select" ? [1] : false}
+ selectionOnDrag={!isMobile && tool === "select"}
+ selectionMode={SelectionMode.Partial}
+ elementsSelectable={isMobile || tool !== "hand"}
+ nodesDraggable={!isMobile && tool === "select"}
nodesConnectable={!isMobile}
// Tab goes node to node (each node's menu connects and disconnects from the keyboard).
edgesFocusable={false}
@@ -933,7 +1246,30 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
{paletteOpen ? <Palette items={palette} onAdd={ui.addAtCenter} onClose={closePalette} /> : <PaletteToggle onOpen={() => setPaletteOpen(true)} />}
</Panel>
)}
+ {!isMobile && (
+ <Panel position="top-center" className="m-3! max-w-[min(560px,calc(100%-34rem))] min-w-0">
+ <PageTabs pages={pages} active={pageId} ops={pageOps} readOnly={false} />
+ </Panel>
+ )}
+ {!isMobile && (
+ <Panel position="bottom-center" className="m-3!">
+ <BoardToolbar tool={tool} setTool={setTool} shape={shapeKind} setShape={setShapeKind} ink={ink} setInk={setInk} selected={selectedForGroup} onGroup={groupSelection} />
+ </Panel>
+ )}
</ReactFlow>
+ {stroke && (
+ <svg className="pointer-events-none absolute inset-0 z-10 size-full" aria-hidden>
+ {stroke.kind === "draw" ? (
+ <polyline points={stroke.points.map((p) => `${p.x},${p.y}`).join(" ")} fill="none" stroke={BOARD_COLOR_VAR[ink]} strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" />
+ ) : shapeKind === "arrow" ? (
+ <line x1={stroke.points[0].x} y1={stroke.points[0].y} x2={stroke.points[1].x} y2={stroke.points[1].y} stroke={BOARD_COLOR_VAR[ink]} strokeWidth={2.5} strokeLinecap="round" />
+ ) : shapeKind === "ellipse" ? (
+ <ellipse cx={(stroke.points[0].x + stroke.points[1].x) / 2} cy={(stroke.points[0].y + stroke.points[1].y) / 2} rx={Math.abs(stroke.points[1].x - stroke.points[0].x) / 2} ry={Math.abs(stroke.points[1].y - stroke.points[0].y) / 2} fill="none" stroke={BOARD_COLOR_VAR[ink]} strokeWidth={2} strokeDasharray="6 4" />
+ ) : (
+ <rect x={Math.min(stroke.points[0].x, stroke.points[1].x)} y={Math.min(stroke.points[0].y, stroke.points[1].y)} width={Math.abs(stroke.points[1].x - stroke.points[0].x)} height={Math.abs(stroke.points[1].y - stroke.points[0].y)} rx={8} fill="none" stroke={BOARD_COLOR_VAR[ink]} strokeWidth={2} strokeDasharray="6 4" />
+ )}
+ </svg>
+ )}
{nodes.length === 0 && (
<div className="pointer-events-none absolute inset-0 grid place-items-center p-6">
diff --git a/src/components/canvas/canvas-list.tsx b/src/components/canvas/canvas-list.tsx
index 8783b318..265ef5e7 100644
--- a/src/components/canvas/canvas-list.tsx
+++ b/src/components/canvas/canvas-list.tsx
@@ -95,6 +95,7 @@ function CanvasCard({ c, onRename, onDelete }: { c: CanvasSummary; onRename: ()
<h3 className="mt-2 truncate pr-9 text-[14px] font-medium">{c.name}</h3>
<p className="text-[12px] text-muted-foreground">
{c.editedAt ? `Edited ${timeAgo(c.editedAt)}` : "Never edited"} · {c.nodeCount} node{c.nodeCount === 1 ? "" : "s"}
+ {c.pageCount > 1 && ` · ${c.pageCount} pages`}
</p>
</Link>
<DropdownMenu>
diff --git a/src/components/canvas/canvas.css b/src/components/canvas/canvas.css
index 499795f2..0a39fbc7 100644
--- a/src/components/canvas/canvas.css
+++ b/src/components/canvas/canvas.css
@@ -121,3 +121,65 @@
.fuobe-canvas .react-flow__pane.dragging {
cursor: grabbing;
}
+
+/* Groups, drawings and comment pins (./board.tsx). Our "group" type shares React Flow's built-in class
+ name: drop the built-in look. A group's body lets clicks through to the board (box-select, double-click
+ to add); only its title bar and resize handles take the pointer. */
+.fuobe-canvas .react-flow__node-group {
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ color: inherit;
+ font-size: inherit;
+ text-align: start;
+ pointer-events: none !important;
+}
+.fuobe-canvas .react-flow__node-group.selectable:hover,
+.fuobe-canvas .react-flow__node-group.selectable.selected,
+.fuobe-canvas .react-flow__node-group.selectable:focus,
+.fuobe-canvas .react-flow__node-group.selectable:focus-visible {
+ box-shadow: none;
+}
+.fuobe-canvas .react-flow__node-group .canvas-group-bar,
+.fuobe-canvas .react-flow__node-group .react-flow__resize-control {
+ pointer-events: auto;
+}
+.fuobe-canvas .react-flow__resize-control.handle.canvas-resize-handle {
+ width: 9px;
+ height: 9px;
+ border-radius: 3px;
+ border: 1.5px solid var(--primary);
+ background: var(--background);
+}
+.fuobe-canvas .react-flow__resize-control.line.canvas-resize-line {
+ border-color: color-mix(in oklab, var(--primary) 55%, transparent);
+}
+.fuobe-canvas .react-flow__node-shape.selected > div {
+ outline: 1.5px dashed color-mix(in oklab, var(--primary) 70%, transparent);
+ outline-offset: 3px;
+ border-radius: 6px;
+}
+
+/* Board tools: the pointer says what a click or drag will do. */
+.fuobe-canvas [data-tool="draw"] .react-flow__pane,
+.fuobe-canvas [data-tool="draw"] .react-flow__node,
+.fuobe-canvas [data-tool="shape"] .react-flow__pane,
+.fuobe-canvas [data-tool="shape"] .react-flow__node,
+.fuobe-canvas [data-tool="note"] .react-flow__pane,
+.fuobe-canvas [data-tool="comment"] .react-flow__pane {
+ cursor: crosshair;
+}
+.fuobe-canvas [data-tool="text"] .react-flow__pane {
+ cursor: text;
+}
+.fuobe-canvas [data-tool="erase"] .react-flow__pane,
+.fuobe-canvas [data-tool="erase"] .react-flow__node {
+ cursor: cell;
+}
+.fuobe-canvas [data-tool="hand"] .react-flow__pane {
+ cursor: grab;
+}
+.fuobe-canvas [data-tool="select"] .react-flow__pane.draggable {
+ cursor: default;
+}
diff --git a/src/components/canvas/node-list.tsx b/src/components/canvas/node-list.tsx
index 93d2dd5e..7388e4cb 100644
--- a/src/components/canvas/node-list.tsx
+++ b/src/components/canvas/node-list.tsx
@@ -11,7 +11,7 @@ import { cn } from "@/lib/utils";
import { EMPTY_VIEW, NodeIcon, useEditorActions, useEditorSnapshot } from "./canvas-context";
import { costLabel, ElementPicker, EngineBadge, LibraryButton, MediaPreview, OutputThumb, Results } from "./nodes";
-const KIND: Partial<Record<CanvasNode["type"], MediaKind>> = { "image-input": "image", "video-input": "video", "audio-input": "audio" };
+const KIND: Partial<Record<CanvasNode["type"], MediaKind>> = { "image-input": "image", "video-input": "video", "audio-input": "audio", "clone-voice": "audio" };
const field = "field-sizing-content max-h-40 min-h-12 w-full resize-none rounded-lg bg-muted px-3 py-2 text-[15px] leading-snug outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint";
const pill = "inline-flex h-9 items-center gap-1.5 rounded-full bg-secondary px-3.5 text-[13px] font-medium";
diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsx
index 163f6625..91e412e9 100644
--- a/src/components/canvas/nodes.tsx
+++ b/src/components/canvas/nodes.tsx
@@ -3,6 +3,8 @@
import { Handle, Position, useUpdateNodeInternals, type Node, type NodeProps } from "@xyflow/react";
import {
AlertCircle,
+ ArrowDown,
+ ArrowUp,
AudioLines,
Box,
Cable,
@@ -26,6 +28,8 @@ import {
Trash2,
Unplug,
Upload,
+ Volume2,
+ VolumeX,
X,
} from "lucide-react";
import Link from "next/link";
@@ -61,10 +65,19 @@ import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";
import { ControlsChip } from "@/components/studio/model-controls";
import { ModelPicker } from "@/components/studio/model-picker";
import { ResponsivePanel } from "@/components/studio/responsive-panel";
+import { VoiceRecorder } from "@/components/studio/voice-recorder";
+import { toast } from "sonner";
+import { useQueryClient } from "@tanstack/react-query";
import { useAssets, useElements } from "@/lib/api";
import { dualEngine, onEngine } from "@/lib/catalog/engines";
import {
CANVAS_TEXT_MAX,
+ CONCAT_LIMITS,
+ CONCAT_MODELS,
+ CONCAT_RATIOS,
+ CONCAT_SIZE,
+ concatClips,
+ concatRatio,
connectionError,
defaultModelFor,
EMPTY_GRAPH,
@@ -75,6 +88,7 @@ import {
nodeLabel,
nodeModel,
nodeOps,
+ OPEN_DUB_HINT,
OUT,
outputType,
PORT_TYPE_LABEL,
@@ -86,6 +100,7 @@ import {
type CanvasNode,
type CanvasNodeData,
type CanvasNodeType,
+ type ClipSettings,
type Connection,
type PortDef,
type PortType,
@@ -95,9 +110,11 @@ import { formatCost } from "@/lib/format";
import { matchSpokenLanguage, spokenLanguageName, spokenLanguageOptions } from "@/lib/speech-languages";
import { keyCombo } from "@/lib/keys";
import { cn } from "@/lib/utils";
+import { BOARD_NODE_TYPES, type BoardType } from "./board";
import { NodeIcon, PORT_COLOR, useEditorActions, useEditorGlobals, useEditorSelector, useNodeResults, useNodeView, type EditorSnapshot, type NodeResults } from "./canvas-context";
-export type FlowNode = Node<CanvasNodeData, CanvasNodeType>;
+/** A node on the board: a graph node, or a group, comment pin or drawing (./board.tsx). */
+export type FlowNode = Node<CanvasNodeData, CanvasNodeType | BoardType>;
/** Interactive controls inside a node must not drag the node or zoom the board. */
const NO_DRAG = "nodrag nopan nowheel";
@@ -642,7 +659,8 @@ function costLabel(isDemo: (m: ModelDef) => boolean, model: ModelDef | undefined
return cost == null ? "Price unknown" : cost === 0 ? "Free" : `≈ ${formatCost(cost)}`;
}
-const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }: NodeProps<FlowNode>) {
+const GeneratorNode = memo(function GeneratorNode({ id, type: flowType, data, selected }: NodeProps<FlowNode>) {
+ const type = flowType as CanvasNodeType;
const actions = useEditorActions();
const g = useEditorGlobals();
const v = useNodeView(id);
@@ -678,10 +696,11 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
setBrowseEngine(null);
};
- // Upscale / Remove background: image or video.
- const variants = NODE_SPECS[type].ops && NODE_SPECS[type].ops!.length === 2 ? NODE_SPECS[type].ops! : null;
+ // Upscale / Remove background: image or video. Translate: text or video.
+ const spec = NODE_SPECS[type];
+ const variants = spec.ops && spec.variants ? spec.variants : null;
const setVariant = (kind: MediaKind) => {
- const op = variants![kind === "video" ? 1 : 0];
+ const op = spec.ops![kind === variants![1] ? 1 : 0];
const engine = model?.engine ?? g.engine;
const m = defaultModelFor(op, engine, { hidden: true }) ?? (g.mode === "both" ? defaultModelFor(op, engine === "open" ? "cloud" : "open", { hidden: true }) : undefined);
actions.update(id, { mediaKind: kind, modelId: m?.id, op: undefined, params: undefined });
@@ -789,21 +808,24 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
{ports.length > 0 && <div className="border-b py-1">{ports.map((p) => <InPort key={p.id} port={p} count={v.counts[p.id] ?? 0} />)}</div>}
<div className="space-y-2 p-3">
{variants && (
- <div className={cn("inline-grid h-7 grid-cols-2 rounded-full bg-muted p-0.5 text-[12px] font-medium", NO_DRAG)} role="radiogroup" aria-label="Image or video">
- {(["image", "video"] as const).map((k) => (
- <button key={k} role="radio" aria-checked={(data.mediaKind ?? "image") === k} disabled={g.readOnly} onClick={() => setVariant(k)} className={cn("rounded-full px-2.5 capitalize", (data.mediaKind ?? "image") === k ? "bg-background shadow-soft" : "text-muted-foreground")}>
+ <div className={cn("inline-grid h-7 grid-cols-2 rounded-full bg-muted p-0.5 text-[12px] font-medium", NO_DRAG)} role="radiogroup" aria-label={`${variants[0]} or ${variants[1]}`}>
+ {variants.map((k) => (
+ <button key={k} role="radio" aria-checked={(data.mediaKind ?? variants[0]) === k} disabled={g.readOnly} onClick={() => setVariant(k)} className={cn("rounded-full px-2.5 capitalize", (data.mediaKind ?? variants[0]) === k ? "bg-background shadow-soft" : "text-muted-foreground")}>
{k}
</button>
))}
</div>
)}
+ {type === "concat" ? (
+ <ConcatPanel id={id} data={data} engine={model?.engine ?? g.engine} />
+ ) : (
<div className={cn("flex flex-wrap items-center gap-1.5 [&>button]:h-7 [&>button]:text-[12px]", g.readOnly && "pointer-events-none")}>
{choices.length ? (
<div className={NO_DRAG}>
<ModelPicker models={choices} value={model} onChange={pickModel} engine={pickerEngine} onEngineChange={setBrowseEngine} />
</div>
) : (
- <p className="text-[12px] text-muted-foreground">No model for this yet.</p>
+ <p className="text-[12px] text-muted-foreground">{type === "translate" ? "No open-source dubbing model yet." : "No model for this yet."}</p>
)}
{auto && model && (
<OptionSelect
@@ -815,6 +837,7 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
/>
)}
</div>
+ )}
{promptPort && !showPrompt && !g.readOnly && (
<button className={chip} onClick={() => setAddWords(true)}>
<Plus className="size-3" /> Add your own words
@@ -834,7 +857,7 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
className={cn("field-sizing-content max-h-36 min-h-14 w-full resize-none rounded-lg bg-muted px-2.5 py-2 text-[13px] leading-snug outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint", NO_DRAG)}
/>
)}
- {model && !g.readOnly && <ModelOptions id={id} model={model} data={data} />}
+ {model && !g.readOnly && type !== "concat" && <ModelOptions id={id} model={model} data={data} />}
<Results id={id} r={r} />
{error && r.state !== "failed" && (
<p className={cn("flex items-start gap-1.5 text-[12px] leading-snug", v.runError ? "text-destructive" : "text-warning")}>
@@ -842,11 +865,178 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
{error}
</p>
)}
+ {error === OPEN_DUB_HINT && (
+ <Link href="/audio/translate" className={cn(chip, "w-fit")}>
+ Open Translate &amp; dub
+ </Link>
+ )}
</div>
</NodeShell>
);
}, sameNodeProps);
+// ---------------------------------------------------------------------------
+// Video concatenator: the film's frame, and each clip's cut and sound in the order they play
+
+interface ClipRow {
+ nodeId: string;
+ label: string;
+ /** The clip's file when it's known now: an uploaded clip, or a finished result upstream. */
+ url?: string;
+}
+
+const sameRows = (a: ClipRow[], b: ClipRow[]) => a.length === b.length && a.every((x, i) => x.nodeId === b[i].nodeId && x.label === b[i].label && x.url === b[i].url);
+
+const selectClipRows = (s: EditorSnapshot, id: string): ClipRow[] => {
+ const n = s.byId.get(id);
+ if (!n) return [];
+ return concatClips(s.graph, n).map(({ nodeId }) => {
+ const src = s.byId.get(nodeId);
+ const url = src?.type === "video-input" ? src.data.url : s.views.get(nodeId)?.results.outputs.find((x) => x.o.kind === "video")?.o.url;
+ return { nodeId, label: src ? nodeLabel(src) : "Clip", ...(url && { url }) };
+ });
+};
+
+const seconds = (v: number | undefined) => (v === undefined ? "" : `${Math.round(v * 10) / 10} s`);
+
+/** A clip's length and frame size, read from its file's header in the browser (once per file). */
+function useClipFacts(url: string | undefined, onFacts: (f: Pick<ClipSettings, "length" | "width" | "height">) => void) {
+ const report = useRef(onFacts);
+ useEffect(() => {
+ report.current = onFacts;
+ });
+ useEffect(() => {
+ if (!url) return;
+ const v = document.createElement("video");
+ v.preload = "metadata";
+ v.muted = true;
+ const done = () => {
+ if (Number.isFinite(v.duration) && v.duration > 0) report.current({ length: Math.round(v.duration * 1000) / 1000, ...(v.videoWidth && { width: v.videoWidth, height: v.videoHeight }) });
+ v.removeAttribute("src");
+ v.load();
+ };
+ v.addEventListener("loadedmetadata", done, { once: true });
+ v.src = url;
+ return () => {
+ v.removeEventListener("loadedmetadata", done);
+ v.removeAttribute("src");
+ };
+ }, [url]);
+}
+
+function TimeField({ label, value, placeholder, max, onChange, disabled }: { label: string; value?: number; placeholder: string; max?: number; onChange: (v: number | undefined) => void; disabled?: boolean }) {
+ const [draft, setDraft] = useState<string | null>(null);
+ return (
+ <label className="flex min-w-0 items-center gap-1 text-[11px] text-muted-foreground">
+ {label}
+ <input
+ type="number"
+ inputMode="decimal"
+ min={0}
+ max={max}
+ step={0.1}
+ value={draft ?? (value === undefined ? "" : String(Math.round(value * 100) / 100))}
+ placeholder={placeholder}
+ disabled={disabled}
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={() => {
+ if (draft === null) return;
+ const n = draft.trim() === "" ? undefined : Number(draft);
+ setDraft(null);
+ onChange(n === undefined || !Number.isFinite(n) ? undefined : Math.max(0, max ? Math.min(n, max) : n));
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ e.stopPropagation();
+ }}
+ aria-label={label}
+ className={cn("h-7 w-16 rounded-md bg-muted px-1.5 font-mono text-[12px] text-foreground outline-none focus:ring-2 focus:ring-brand-faint disabled:opacity-60", NO_DRAG)}
+ />
+ </label>
+ );
+}
+
+function ClipItem({ id, row, index, count, settings, readOnly, onMove }: { id: string; row: ClipRow; index: number; count: number; settings: ClipSettings; readOnly: boolean; onMove: (from: number, to: number) => void }) {
+ const actions = useEditorActions();
+ const set = (patch: Partial<ClipSettings>) => actions.patchClip(id, row.nodeId, patch);
+ // The file's facts (length, size) are what the cuts are checked against.
+ useClipFacts(row.url, (f) => {
+ if (f.length !== settings.length || f.width !== settings.width || f.height !== settings.height) set(f);
+ });
+ const muted = !!settings.mute;
+ return (
+ <li className="rounded-lg bg-muted/60 p-2">
+ <div className="flex items-center gap-1.5">
+ <span className="grid size-5 shrink-0 place-items-center rounded-full bg-background font-mono text-[10px]">{index + 1}</span>
+ <span className="min-w-0 flex-1 truncate text-[12px] font-medium">{row.label}</span>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{seconds(settings.length)}</span>
+ {!readOnly && (
+ <>
+ <button onClick={() => set({ mute: !muted })} aria-pressed={muted} aria-label={muted ? `Unmute clip ${index + 1}` : `Mute clip ${index + 1}`} title={muted ? "Muted: plays silent" : "Plays with its sound"} className={cn("grid size-6 place-items-center rounded-md hover:bg-accent", muted ? "text-warning" : "text-muted-foreground", NO_DRAG)}>
+ {muted ? <VolumeX className="size-3.5" /> : <Volume2 className="size-3.5" />}
+ </button>
+ <button onClick={() => onMove(index, index - 1)} disabled={index === 0} aria-label={`Move clip ${index + 1} earlier`} className={cn("grid size-6 place-items-center rounded-md text-muted-foreground hover:bg-accent disabled:opacity-30", NO_DRAG)}>
+ <ArrowUp className="size-3.5" />
+ </button>
+ <button onClick={() => onMove(index, index + 1)} disabled={index === count - 1} aria-label={`Move clip ${index + 1} later`} className={cn("grid size-6 place-items-center rounded-md text-muted-foreground hover:bg-accent disabled:opacity-30", NO_DRAG)}>
+ <ArrowDown className="size-3.5" />
+ </button>
+ </>
+ )}
+ </div>
+ {!readOnly && (
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1">
+ <TimeField label="From" value={settings.start} placeholder="0" max={settings.length} onChange={(v) => set({ start: v })} />
+ <TimeField label="to" value={settings.end} placeholder={settings.length ? String(Math.round(settings.length * 10) / 10) : "end"} max={settings.length} onChange={(v) => set({ end: v })} />
+ </div>
+ )}
+ </li>
+ );
+}
+
+function ConcatPanel({ id, data, engine }: { id: string; data: CanvasNodeData; engine: Engine }) {
+ const actions = useEditorActions();
+ const g = useEditorGlobals();
+ const rows = useEditorSelector(selectClipRows, id, sameRows);
+ const ratio = concatRatio(data.params?.aspectRatio);
+ const size = CONCAT_SIZE[ratio];
+ const move = (from: number, to: number) => {
+ if (to < 0 || to >= rows.length) return;
+ const order = rows.map((r) => r.nodeId);
+ const [x] = order.splice(from, 1);
+ order.splice(to, 0, x);
+ actions.update(id, { order });
+ };
+ return (
+ <div className="space-y-2">
+ <div className={cn("flex flex-wrap items-center gap-1.5", g.readOnly && "pointer-events-none")}>
+ <OptionSelect label="Aspect ratio" value={ratio} options={[...CONCAT_RATIOS]} onChange={(v) => actions.update(id, { params: { ...data.params, aspectRatio: v } })} />
+ {g.mode === "both" && (
+ <div className={cn("inline-grid h-7 grid-cols-2 rounded-full bg-muted p-0.5 text-[12px] font-medium", NO_DRAG)} role="radiogroup" aria-label="Engine">
+ {(["cloud", "open"] as const).map((e) => (
+ <button key={e} role="radio" aria-checked={engine === e} onClick={() => actions.update(id, { modelId: CONCAT_MODELS[e] })} className={cn("rounded-full px-2.5", engine === e ? "bg-background shadow-soft" : "text-muted-foreground")}>
+ {e === "cloud" ? "Cloud" : "Open source"}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ <p className="text-[11px] text-muted-foreground">
+ {size.width}×{size.height} · {CONCAT_LIMITS.fps} fps · up to {CONCAT_LIMITS.clips} clips, 512 MB each
+ </p>
+ {rows.length ? (
+ <ol className="max-h-80 space-y-1.5 overflow-y-auto" aria-label="Clips, in the order they play">
+ {rows.map((row, i) => (
+ <ClipItem key={row.nodeId} id={id} row={row} index={i} count={rows.length} settings={data.clips?.[row.nodeId] ?? {}} readOnly={g.readOnly} onMove={move} />
+ ))}
+ </ol>
+ ) : (
+ <p className="rounded-lg border border-dashed p-2.5 text-[12px] text-muted-foreground">Connect clips to Clips: they play top to bottom, and you can reorder, cut and mute each one here.</p>
+ )}
+ </div>
+ );
+}
+
// ---------------------------------------------------------------------------
// Inputs
@@ -854,7 +1044,7 @@ const PromptNode = memo(function PromptNode({ id, type, data, selected }: NodePr
const actions = useEditorActions();
const { readOnly } = useEditorGlobals();
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} out="text" width={280}>
+ <NodeShell id={id} type={type as CanvasNodeType} data={data} selected={!!selected} out="text" width={280}>
<div className="p-3">
<textarea
value={data.text ?? ""}
@@ -946,7 +1136,7 @@ function MediaPreview({ kind, url }: { kind: MediaKind; url: string }) {
const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }: NodeProps<FlowNode>) {
const actions = useEditorActions();
const { readOnly } = useEditorGlobals();
- const kind = KIND_OF[type]!;
+ const kind = KIND_OF[type as CanvasNodeType]!;
const input = useRef<HTMLInputElement>(null);
const [pending, setPending] = useState<SlotValue | null>(null);
const [over, setOver] = useState(false);
@@ -963,7 +1153,7 @@ const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }
);
const accept = kind === "image" ? "image/png,image/jpeg,image/webp,image/gif" : kind === "video" ? "video/mp4,video/webm,video/quicktime" : "audio/*";
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} out={kind} width={260}>
+ <NodeShell id={id} type={type as CanvasNodeType} data={data} selected={!!selected} out={kind} width={260}>
<div
className="space-y-2 p-3"
onDragOver={(e) => {
@@ -1095,7 +1285,7 @@ const ElementNode = memo(function ElementNode({ id, type, data, selected }: Node
const actions = useEditorActions();
const { readOnly } = useEditorGlobals();
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} out="element" width={240}>
+ <NodeShell id={id} type={type as CanvasNodeType} data={data} selected={!!selected} out="element" width={240}>
<div className="space-y-2 p-3">
{data.handle ? (
<div className="flex items-center gap-2.5">
@@ -1117,6 +1307,143 @@ const ElementNode = memo(function ElementNode({ id, type, data, selected }: Node
);
}, sameNodeProps);
+// ---------------------------------------------------------------------------
+// Clone voice: a sample to speak with (recorded, uploaded, a saved voice, or wired in)
+
+const selectSampleSource = (s: EditorSnapshot, id: string) => {
+ const e = s.graph.edges.find((x) => x.target === id && x.targetHandle === "audio");
+ const n = e && s.byId.get(e.source);
+ return n ? nodeLabel(n) : null;
+};
+
+const CloneVoiceNode = memo(function CloneVoiceNode({ id, data, selected }: NodeProps<FlowNode>) {
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
+ const qc = useQueryClient();
+ const wired = useEditorSelector(selectSampleSource, id);
+ const voices = (useElements().data ?? []).filter((e) => e.kind === "voice" && e.references[0]);
+ const node = useMemo(() => asNode(id, "clone-voice", data), [id, data]);
+ const ports = useMemo(() => inputPorts(node), [node]);
+ const file = useRef<HTMLInputElement>(null);
+ const [pending, setPending] = useState(false);
+ const [naming, setNaming] = useState<string | null>(null);
+ const take = (f: File) => {
+ if (f.size > 11 * 1024 * 1024) return void toast.error("That sample is over 11 MB — 10–60 s of speech is plenty");
+ setPending(true);
+ void fileToSlot(
+ f,
+ (v) => {
+ if (v?.uploading) return;
+ setPending(false);
+ if (v) actions.update(id, { url: v.ref, name: v.name, elementId: undefined });
+ },
+ "audio",
+ );
+ };
+ const saved = voices.find((e) => e.id === data.elementId || e.references[0] === data.url);
+ const save = async () => {
+ const name = naming?.trim();
+ if (!name || !data.url) return;
+ const res = await fetch("/api/elements", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, kind: "voice", references: [data.url] }) });
+ const body = (await res.json().catch(() => ({}))) as { id?: string; name?: string; error?: string };
+ if (!res.ok || !body.id) return void toast.error(body.error ?? "Couldn't save the voice");
+ actions.update(id, { elementId: body.id, name: body.name });
+ setNaming(null);
+ void qc.invalidateQueries({ queryKey: ["elements"] });
+ toast.success(`Saved “${body.name}” to your voices`);
+ };
+ return (
+ <NodeShell id={id} type="clone-voice" data={data} selected={!!selected} out="voice" width={270}>
+ <div className="border-b py-1">
+ {ports.map((p) => (
+ <InPort key={p.id} port={p} count={wired ? 1 : 0} />
+ ))}
+ </div>
+ <div className="space-y-2 p-3">
+ {wired ? (
+ <p className="text-[12px] text-muted-foreground">
+ Speaks with the voice in <span className="font-medium text-foreground">“{wired}”</span>.
+ </p>
+ ) : pending ? (
+ <div className="flex h-12 items-center justify-center gap-2 rounded-lg bg-muted text-[12px] text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" /> Uploading…
+ </div>
+ ) : data.url ? (
+ <>
+ <MediaPreview kind="audio" url={data.url} />
+ <p className="truncate text-[12px] text-muted-foreground">{saved ? `Your voice “${saved.name}”` : (data.name ?? "Your sample")}</p>
+ </>
+ ) : (
+ <p className="text-[12px] text-muted-foreground">Record or upload 10–60 s of clean speech (MP3 or WAV, up to 11 MB), or pick one of your voices.</p>
+ )}
+ {!readOnly && !wired && (
+ <div className="flex flex-wrap gap-1">
+ <div className={NO_DRAG}>
+ <VoiceRecorder onRecorded={(v) => actions.update(id, { url: v.ref, name: v.name ?? "Recording", elementId: undefined })} className={chip} />
+ </div>
+ <button className={chip} onClick={() => file.current?.click()}>
+ <Upload className="size-3" /> {data.url ? "Replace" : "Upload"}
+ </button>
+ {voices.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button className={chip}>
+ <Library className="size-3" /> My voices
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="max-h-72 w-56 overflow-y-auto">
+ {voices.map((e) => (
+ <DropdownMenuItem key={e.id} onSelect={() => actions.update(id, { url: e.references[0], name: e.name, elementId: e.id })}>
+ <AudioLines className="size-4" /> <span className="truncate">{e.name}</span>
+ {e.id === saved?.id && <Check className="ml-auto size-3.5" />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {data.url && !saved && naming === null && (
+ <button className={chip} onClick={() => setNaming(data.name?.replace(/\.[a-z0-9]+$/i, "") ?? "My voice")}>
+ <Plus className="size-3" /> Save as a voice
+ </button>
+ )}
+ </div>
+ )}
+ {naming !== null && (
+ <div className={cn("flex items-center gap-1", NO_DRAG)}>
+ <input
+ autoFocus
+ value={naming}
+ maxLength={60}
+ onChange={(e) => setNaming(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") void save();
+ if (e.key === "Escape") setNaming(null);
+ e.stopPropagation();
+ }}
+ aria-label="Voice name"
+ className="h-7 min-w-0 flex-1 rounded-md border bg-background px-2 text-[12px] outline-none focus:border-primary"
+ />
+ <button className={chip} onClick={() => void save()} disabled={!naming.trim()}>
+ Save
+ </button>
+ </div>
+ )}
+ <input
+ ref={file}
+ type="file"
+ accept="audio/mpeg,audio/wav,audio/x-wav,audio/mp4,audio/webm,audio/*"
+ hidden
+ onChange={(e) => {
+ const f = e.target.files?.[0];
+ if (f) take(f);
+ e.target.value = "";
+ }}
+ />
+ </div>
+ </NodeShell>
+ );
+}, sameNodeProps);
+
// ---------------------------------------------------------------------------
// Output preview and notes
@@ -1144,7 +1471,7 @@ const OutputNode = memo(function OutputNode({ id, type, data, selected }: NodePr
const w = width ?? (sources.length > 1 ? 560 : 320);
const menu: MenuItem[] = [{ label: "Run what feeds this", icon: Play, onSelect: () => actions.run([id]) }];
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} menu={menu} width={w}>
+ <NodeShell id={id} type={type as CanvasNodeType} data={data} selected={!!selected} menu={menu} width={w}>
<div className="relative p-3">
<Handle type="target" position={Position.Left} id={PREVIEW_IN} className="canvas-handle canvas-handle-any" aria-label="Preview input (any type)" />
{sources.length === 0 ? (
@@ -1172,7 +1499,7 @@ function SourcePreview({ node }: { node: Source }) {
if (r.state !== "idle") return <Results id={node.id} r={r} compact />;
return <div className="grid h-20 place-items-center rounded-lg bg-muted text-[11px] text-muted-foreground">Not run yet</div>;
}
- const kind = KIND_OF[node.type];
+ const kind = node.type === "clone-voice" ? "audio" : KIND_OF[node.type];
if (kind && node.data.url) return <MediaPreview kind={kind} url={node.data.url} />;
if (node.type === "prompt") return <p className="line-clamp-6 rounded-lg bg-muted p-2.5 text-[12px] leading-snug">{node.data.text || "Empty text"}</p>;
return <div className="grid h-20 place-items-center rounded-lg bg-muted text-[11px] text-muted-foreground">Nothing yet</div>;
@@ -1182,7 +1509,7 @@ const NoteNode = memo(function NoteNode({ id, type, data, selected }: NodeProps<
const actions = useEditorActions();
const { readOnly } = useEditorGlobals();
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} width={240} tone="note">
+ <NodeShell id={id} type={type as CanvasNodeType} data={data} selected={!!selected} width={240} tone="note">
<div className="p-3">
<textarea
value={data.text ?? ""}
@@ -1212,11 +1539,12 @@ export const NODE_TYPES = {
"bg-remove": GeneratorNode,
tts: GeneratorNode,
"voice-change": GeneratorNode,
- "clone-voice": MediaInputNode,
+ "clone-voice": CloneVoiceNode,
translate: GeneratorNode,
concat: GeneratorNode,
output: OutputNode,
note: NoteNode,
-} satisfies Record<CanvasNodeType, React.ComponentType<NodeProps<FlowNode>>>;
+ ...BOARD_NODE_TYPES,
+} satisfies Record<CanvasNodeType | BoardType, React.ComponentType<NodeProps<FlowNode>>>;
export { MediaPreview, OutputThumb, Results, EngineBadge, costLabel };
diff --git a/src/components/canvas/toolbar.tsx b/src/components/canvas/toolbar.tsx
new file mode 100644
index 00000000..257a969b
--- /dev/null
+++ b/src/components/canvas/toolbar.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { ArrowUpRight, Circle, Copy, Eraser, Group, Hand, MessageCircle, MousePointer2, MoreHorizontal, Pencil, Plus, Square, StickyNote, Trash2, Type, type LucideIcon } from "lucide-react";
+import { memo, useState } from "react";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Kbd } from "@/components/ui/kbd";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { BOARD_LIMITS, SHAPE_LABEL, type BoardColor } from "@/lib/catalog/canvas-board";
+import { useModKey } from "@/lib/keys";
+import { cn } from "@/lib/utils";
+import { BOARD_COLOR_VAR, Swatches } from "./board";
+
+/** What a drag or click on the board does (Higgsfield's toolbar: V, H, D, E, N, R, T, C). */
+export type Tool = "select" | "hand" | "draw" | "erase" | "note" | "shape" | "text" | "comment";
+export type DragShape = "rect" | "ellipse" | "arrow";
+
+export const TOOL_KEYS: Record<string, Tool> = { v: "select", h: "hand", d: "draw", e: "erase", n: "note", r: "shape", t: "text", c: "comment" };
+
+const TOOLS: { tool: Tool; label: string; key: string; icon: LucideIcon; hint: string }[] = [
+ { tool: "select", label: "Select", key: "V", icon: MousePointer2, hint: "Drag to select · hold Space to pan" },
+ { tool: "hand", label: "Pan", key: "H", icon: Hand, hint: "Drag to move around the board" },
+ { tool: "draw", label: "Draw", key: "D", icon: Pencil, hint: "Draw freehand on the board" },
+ { tool: "erase", label: "Eraser", key: "E", icon: Eraser, hint: "Drag over drawings and shapes to erase them" },
+ { tool: "note", label: "Sticky note", key: "N", icon: StickyNote, hint: "Click to place a note" },
+ { tool: "shape", label: "Shapes", key: "R", icon: Square, hint: "Drag to draw a shape" },
+ { tool: "text", label: "Text", key: "T", icon: Type, hint: "Click to write on the board" },
+ { tool: "comment", label: "Comment", key: "C", icon: MessageCircle, hint: "Click to pin a comment" },
+];
+
+const SHAPE_ICON: Record<DragShape, LucideIcon> = { rect: Square, ellipse: Circle, arrow: ArrowUpRight };
+
+/** Tools that draw with a colour. */
+const INKED = new Set<Tool>(["draw", "shape", "text"]);
+
+export const BoardToolbar = memo(function BoardToolbar({
+ tool,
+ setTool,
+ shape,
+ setShape,
+ ink,
+ setInk,
+ selected,
+ onGroup,
+}: {
+ tool: Tool;
+ setTool: (t: Tool) => void;
+ shape: DragShape;
+ setShape: (s: DragShape) => void;
+ ink: BoardColor;
+ setInk: (c: BoardColor) => void;
+ /** Nodes selected that a group could frame. */
+ selected: number;
+ onGroup: () => void;
+}) {
+ const mod = useModKey();
+ return (
+ <div className="flex items-center gap-0.5 rounded-full border bg-popover/95 p-1 shadow-normal backdrop-blur" role="toolbar" aria-label="Board tools" data-board-ui>
+ {TOOLS.map((t, i) => {
+ const Icon = t.tool === "shape" ? SHAPE_ICON[shape] : t.icon;
+ const active = tool === t.tool;
+ return (
+ <div key={t.tool} className="flex items-center">
+ {(i === 2 || i === 4 || i === 7) && <span className="mx-0.5 h-5 w-px bg-border" aria-hidden />}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={() => setTool(t.tool)}
+ aria-pressed={active}
+ aria-label={`${t.tool === "shape" ? SHAPE_LABEL[shape] : t.label} (${t.key})`}
+ className={cn("grid size-8 place-items-center rounded-full transition-colors", active ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-accent hover:text-foreground")}
+ >
+ <Icon className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {t.tool === "shape" ? SHAPE_LABEL[shape] : t.label} <Kbd>{t.key}</Kbd>
+ <span className="block text-[11px] opacity-80">{t.hint}</span>
+ </TooltipContent>
+ </Tooltip>
+ {t.tool === "shape" && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button className="-ml-1 grid h-8 w-4 place-items-center rounded-full text-muted-foreground hover:text-foreground" aria-label="Pick a shape">
+ <span className="text-[9px]">▾</span>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="center" side="top">
+ {(Object.keys(SHAPE_ICON) as DragShape[]).map((k) => {
+ const I = SHAPE_ICON[k];
+ return (
+ <DropdownMenuItem
+ key={k}
+ onSelect={() => {
+ setShape(k);
+ setTool("shape");
+ }}
+ >
+ <I className="size-4" /> {SHAPE_LABEL[k]}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ );
+ })}
+ {INKED.has(tool) && (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button className="ml-0.5 grid size-8 place-items-center rounded-full hover:bg-accent" aria-label="Colour">
+ <span className="size-4 rounded-full ring-2 ring-border" style={{ background: BOARD_COLOR_VAR[ink] }} />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent side="top" className="w-auto rounded-full p-1.5">
+ <Swatches value={ink} onChange={setInk} />
+ </PopoverContent>
+ </Popover>
+ )}
+ {selected > 0 && (
+ <>
+ <span className="mx-0.5 h-5 w-px bg-border" aria-hidden />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button onClick={onGroup} className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium hover:bg-accent">
+ <Group className="size-4" /> Group
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>
+ Frame the {selected === 1 ? "selected node" : `${selected} selected nodes`}: they move and run together <Kbd>{mod}</Kbd>
+ <Kbd>G</Kbd>
+ </TooltipContent>
+ </Tooltip>
+ </>
+ )}
+ </div>
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Pages
+
+export interface PageOps {
+ switchTo: (id: string) => void;
+ add: () => void;
+ rename: (id: string, name: string) => void;
+ duplicate: (id: string) => void;
+ remove: (id: string) => void;
+}
+
+/** The canvas's pages as tabs: each its own board. Double-click a tab to rename it. */
+export const PageTabs = memo(function PageTabs({ pages, active, ops, readOnly }: { pages: { id: string; name: string }[]; active: string; ops: PageOps; readOnly: boolean }) {
+ const [editing, setEditing] = useState<string | null>(null);
+ const full = pages.length >= BOARD_LIMITS.pages;
+ return (
+ <div className="flex max-w-full items-center gap-0.5 rounded-full border bg-popover/95 p-1 shadow-normal backdrop-blur" data-board-ui>
+ <div className="flex min-w-0 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]" role="tablist" aria-label="Pages">
+ {pages.map((p) =>
+ editing === p.id ? (
+ <input
+ key={p.id}
+ autoFocus
+ defaultValue={p.name}
+ maxLength={60}
+ onFocus={(e) => e.currentTarget.select()}
+ onBlur={(e) => {
+ setEditing(null);
+ const v = e.currentTarget.value.trim();
+ if (v && v !== p.name) ops.rename(p.id, v);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ if (e.key === "Escape") setEditing(null);
+ e.stopPropagation();
+ }}
+ aria-label="Page name"
+ className="h-7 w-32 rounded-full border bg-background px-3 text-[13px] outline-none focus:border-primary"
+ />
+ ) : (
+ <button
+ key={p.id}
+ role="tab"
+ aria-selected={p.id === active}
+ onClick={() => ops.switchTo(p.id)}
+ onDoubleClick={() => !readOnly && setEditing(p.id)}
+ title={readOnly ? p.name : `${p.name} · double-click to rename`}
+ className={cn("h-7 max-w-36 shrink-0 truncate rounded-full px-3 text-[13px] font-medium transition-colors", p.id === active ? "bg-secondary text-foreground" : "text-muted-foreground hover:bg-accent hover:text-foreground")}
+ >
+ {p.name}
+ </button>
+ ),
+ )}
+ </div>
+ {!readOnly && (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Page actions">
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-52">
+ <DropdownMenuItem onSelect={() => setTimeout(() => setEditing(active), 0)}>
+ <Pencil className="size-4" /> Rename page
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => ops.duplicate(active)} disabled={full}>
+ <Copy className="size-4" /> Duplicate page
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => ops.remove(active)} disabled={pages.length < 2}>
+ <Trash2 className="size-4" /> Delete page
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button onClick={ops.add} disabled={full} className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40" aria-label="Add a page">
+ <Plus className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{full ? `A canvas holds up to ${BOARD_LIMITS.pages} pages` : "Add a page: a board of its own"}</TooltipContent>
+ </Tooltip>
+ </>
+ )}
+ </div>
+ );
+});
diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.ts
index 9806f839..ff2cbc63 100644
--- a/src/components/canvas/use-canvas.ts
+++ b/src/components/canvas/use-canvas.ts
@@ -3,6 +3,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useGenerationStream } from "@/lib/api";
import type { Canvas, CanvasGraph, CanvasPlan, CanvasSummary } from "@/lib/catalog/canvas";
+import type { CanvasPage } from "@/lib/catalog/canvas-board";
import type { Engine, Generation } from "@/lib/catalog/types";
/** Client hooks for /api/canvases (kept next to the canvas UI; the shapes live in src/lib/catalog/canvas.ts). */
@@ -75,8 +76,8 @@ export function useCanvasActions() {
};
}
-/** Save the board (autosave). `keepalive` lets a save started while leaving the page finish. */
-export async function saveCanvas(id: string, patch: { name?: string; graph?: CanvasGraph }, keepalive = false): Promise<Canvas> {
+/** Save the pages (autosave) or the name. `keepalive` lets a save started while leaving the page finish. */
+export async function saveCanvas(id: string, patch: { name?: string; pages?: CanvasPage[] }, keepalive = false): Promise<Canvas> {
return json<Canvas>(await send(`/api/canvases/${id}`, "PATCH", patch, { keepalive }));
}
@@ -92,7 +93,7 @@ export interface RunResponse {
export function useRunCanvas(id: string) {
const qc = useQueryClient();
return useMutation({
- mutationFn: async (body: { targets?: string[]; force?: boolean; graph: CanvasGraph }) => {
+ mutationFn: async (body: { page: string; targets?: string[]; group?: string; force?: boolean; graph: CanvasGraph }) => {
const res = await send(`/api/canvases/${id}/run`, "POST", body);
const data = (await res.json().catch(() => ({}))) as Partial<RunResponse> & { error?: string };
if (!res.ok && !data.errors) throw new Error(data.error ?? `Request failed (${res.status})`);