Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(editor): port-level unified node canvas - material graph joins

yhh13e139cb13af
diff --git a/desktop/src/panels/MaterialGraphEditor.tsx b/desktop/src/panels/MaterialGraphEditor.tsx
index e11d11c74..9c2606bb6 100644
--- a/desktop/src/panels/MaterialGraphEditor.tsx
+++ b/desktop/src/panels/MaterialGraphEditor.tsx
@@ -2,13 +2,18 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file MaterialGraphEditor.tsx
- * @brief The `.esmatgraph` node editor (Material Graph, P5b) — a canvas of node boxes wired by
- * bezier connections. All graph mutation goes through the pure, tested SDK ops
- * (addNode/connect/disconnect/removeNode/moveNode) on the reactive MaterialGraphDocument;
- * NODE_SPECS drives the palette, ports, and node-param fields so the editor and the
- * compiler never drift. Save compiles the graph to its sibling `.esshader` (P5a).
+ * @brief The `.esmatgraph` node editor — typed material nodes on the shared
+ * <NodeGraphCanvas> (pan/zoom, wire-to-connect, selection, menus are
+ * the canvas's). This file supplies only the material domain: NODE_SPECS
+ * drives ports (typed, colored), node bodies, and the add menu; all
+ * mutation goes through the pure SDK ops on MaterialGraphDocument.
+ * Save compiles the graph to its sibling `.esshader`.
+ *
+ * Wires land on typed input ports (nearest-port snap on drop); a wired
+ * input disconnects on click, and wires are selectable — Delete removes
+ * them like any edge.
*/
-import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { useRef, useState, useSyncExternalStore } from 'react';
import { Save, Plus, Trash2 } from 'lucide-react';
import {
NODE_SPECS,
@@ -26,18 +31,20 @@ import { saveMaterialGraph } from '@/material/openMaterialGraph';
import { EditorHistory } from '@/engine/EditorHistory';
import { NumField, ColorControl } from '@/panels/Details';
import { DirtyDot } from '@/components/DirtyDot';
-import { ContextMenu, type MenuItem } from '@/components/Menu';
+import {
+ NodeGraphCanvas,
+ type CanvasEdge,
+ type CanvasNode,
+ type CanvasPort,
+ type NodeGraphCanvasApi,
+} from '@/panels/NodeGraphCanvas';
+
+type MatCanvasNode = MaterialGraph['nodes'][number] & CanvasNode;
const NODE_W = 168;
const HEADER_H = 28;
const ROW_H = 24;
-// A node's input/output port positions in canvas coordinates (node.x/.y are canvas px).
-const nodeX = (n: { x?: number }) => n.x ?? 0;
-const nodeY = (n: { y?: number }) => n.y ?? 0;
-const outPort = (n: { x?: number; y?: number }) => ({ x: nodeX(n) + NODE_W, y: nodeY(n) + HEADER_H / 2 });
-const inPort = (n: { x?: number; y?: number }, i: number) => ({ x: nodeX(n), y: nodeY(n) + HEADER_H + ROW_H * i + ROW_H / 2 });
-
// Port hue by GLSL type — the same legend the compiler's types imply.
const TYPE_COLOR: Record<GraphType, string> = {
float: '#9aa7b5',
@@ -46,11 +53,6 @@ const TYPE_COLOR: Record<GraphType, string> = {
vec4: '#c0917a',
};
-function bezier(x1: number, y1: number, x2: number, y2: number): string {
- const dx = Math.max(40, Math.abs(x2 - x1) * 0.5);
- return `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`;
-}
-
const rgbaToHex = (c: number[]) => {
const h = (v: number) => Math.max(0, Math.min(255, Math.round((v ?? 0) * 255))).toString(16).padStart(2, '0');
return `#${h(c[0])}${h(c[1])}${h(c[2])}${h(c[3] ?? 1)}`;
@@ -61,308 +63,160 @@ const hexToRgba = (hex: string): number[] => {
return [n(0), n(2), n(4), s.length >= 8 ? n(6) : 1];
};
+const nodeHeight = (n: MatCanvasNode): number => {
+ const spec = NODE_SPECS[n.type];
+ return HEADER_H + Math.max(spec.inputs.length, 1) * ROW_H + spec.params.length * ROW_H;
+};
+
+/** One edge per wired input slot; the id round-trips to (node, slot) for delete. */
+const wireId = (to: string, slot: string) => `${to}#${slot}`;
+const parseWireId = (id: string): { to: string; slot: string } | null => {
+ const i = id.lastIndexOf('#');
+ return i > 0 ? { to: id.slice(0, i), slot: id.slice(i + 1) } : null;
+};
+
export function MaterialGraphEditor() {
useSyncExternalStore(MaterialGraphDocument.subscribe, MaterialGraphDocument.getRevision);
const graph = MaterialGraphDocument.asset;
const filePath = MaterialGraphDocument.filePath;
const dirty = MaterialGraphDocument.dirty;
- const canvasRef = useRef<HTMLDivElement>(null);
const [selected, setSelected] = useState<string | null>(null);
- // Right-click / Add menu: screen position for the shared ContextMenu + the
- // canvas position where an added node should land (and the node under it).
- const [menu, setMenu] = useState<{ sx: number; sy: number; cx: number; cy: number; nodeId?: string } | null>(null);
- // Infinite-canvas viewport — the same pan/zoom model as NodeGraphCanvas
- // (middle-drag pans, wheel zooms about the cursor; content in world coords).
- const [vp, setVp] = useState({ x: 0, y: 0, zoom: 1 });
- const pan = useRef<{ sx: number; sy: number; vx: number; vy: number } | null>(null);
- // Live cursor (canvas coords) while connecting, to draw the in-progress wire.
- const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);
- const drag = useRef<{ id: string; offX: number; offY: number; before: MaterialGraph } | null>(null);
- const wire = useRef<{ fromId: string } | null>(null);
-
- // Screen point → world coord (inverse of the viewport transform).
- const toCanvas = (clientX: number, clientY: number) => {
- const el = canvasRef.current;
- if (!el) return { x: clientX, y: clientY };
- const r = el.getBoundingClientRect();
- return { x: (clientX - r.left - vp.x) / vp.zoom, y: (clientY - r.top - vp.y) / vp.zoom };
- };
-
- // Window-level move/up so a drag or wire keeps tracking outside the node it started on.
- useEffect(() => {
- const onMove = (e: PointerEvent) => {
- if (pan.current) {
- const { sx, sy, vx, vy } = pan.current;
- setVp((v) => ({ ...v, x: vx + (e.clientX - sx), y: vy + (e.clientY - sy) }));
- return;
- }
- const p = toCanvas(e.clientX, e.clientY);
- if (drag.current && graph) {
- MaterialGraphDocument.replaceAsset(moveNode(graph, drag.current.id, p.x - drag.current.offX, p.y - drag.current.offY), { dirty: true });
- } else if (wire.current) {
- setCursor(p);
- }
- };
- const onUp = (e: PointerEvent) => {
- pan.current = null;
- if (drag.current && graph) {
- const after = graph;
- const before = drag.current.before;
- EditorHistory.record('Move node', () => MaterialGraphDocument.replaceAsset(after), () => MaterialGraphDocument.replaceAsset(before));
- drag.current = null;
- }
- if (wire.current && graph) {
- const p = toCanvas(e.clientX, e.clientY);
- const hit = nearestInputPort(graph, p.x, p.y);
- if (hit) MaterialGraphDocument.edit('Connect', (d) => Object.assign(d, connect(d, wire.current!.fromId, hit.nodeId, hit.slot)));
- wire.current = null;
- setCursor(null);
- }
- };
- window.addEventListener('pointermove', onMove);
- window.addEventListener('pointerup', onUp);
- return () => {
- window.removeEventListener('pointermove', onMove);
- window.removeEventListener('pointerup', onUp);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [graph, vp]);
-
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if ((e.key === 'Delete' || e.key === 'Backspace') && selected && graph) {
- MaterialGraphDocument.edit('Delete node', (d) => Object.assign(d, removeNode(d, selected)));
- setSelected(null);
- }
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [selected, graph]);
+ const [selectedEdge, setSelectedEdge] = useState<string | null>(null);
+ const dragBefore = useRef<MaterialGraph | null>(null);
+ const canvas = useRef<NodeGraphCanvasApi>(null);
if (!graph || !filePath) {
- return (
- <div className="panel mg">
- <div className="empty">
- <p>Open a `.esmatgraph` from the Content Browser to edit it.</p>
- </div>
- </div>
- );
+ return <div className="panel ng-placeholder"><p>Open a <code>.esmatgraph</code> from the Content Browser to edit it.</p></div>;
}
- const addAt = (type: GraphNodeType, x: number, y: number) => {
- MaterialGraphDocument.edit(`Add ${type}`, (d) => Object.assign(d, addNode(d, type, x, y).graph));
- };
-
- // The Add button and the canvas right-click share one menu; only where the
- // new node lands differs (view center vs. the click point).
- const openAddMenu = (sx: number, sy: number, cx: number, cy: number) => setMenu({ sx, sy, cx, cy });
- const menuItems = (): MenuItem[] => {
- if (!menu) return [];
- if (menu.nodeId) {
- const id = menu.nodeId;
- return [
- {
- label: 'Delete node',
- danger: true,
- onClick: () => {
- MaterialGraphDocument.edit('Delete node', (d) => Object.assign(d, removeNode(d, id)));
- setSelected(null);
- },
- },
- ];
+ const nodes = graph.nodes as MatCanvasNode[];
+ const edges: CanvasEdge[] = [];
+ for (const n of nodes) {
+ for (const port of NODE_SPECS[n.type].inputs) {
+ const src = n.inputs?.[port.name];
+ if (src) edges.push({ id: wireId(n.id, port.name), from: src, to: n.id, toPort: port.name });
}
- return (Object.keys(NODE_SPECS) as GraphNodeType[])
- .filter((t) => NODE_SPECS[t].addable)
- .map((t) => ({ label: `Add ${NODE_SPECS[t].label}`, onClick: () => addAt(t, menu.cx, menu.cy) }));
- };
+ }
+ const deleteNode = (id: string) => {
+ MaterialGraphDocument.edit('Delete node', (d) => Object.assign(d, removeNode(d, id)));
+ setSelected(null);
+ };
+ const disconnectSlot = (nodeId: string, slot: string) =>
+ MaterialGraphDocument.edit('Disconnect', (d) => Object.assign(d, disconnect(d, nodeId, slot)));
const setNodeParam = (id: string, key: string, value: unknown) =>
MaterialGraphDocument.edit(`Set ${key}`, (d) => {
const n = d.nodes.find((m) => m.id === id);
if (n) (n.params ??= {})[key] = value as never;
});
- // Connections: each node's wired input slots → a bezier from the source output port.
- const wires: { key: string; d: string }[] = [];
- for (const n of graph.nodes) {
- const spec = NODE_SPECS[n.type];
- spec.inputs.forEach((port, i) => {
- const src = n.inputs?.[port.name];
- if (!src) return;
- const from = graph.nodes.find((m) => m.id === src);
- if (!from) return;
- const a = outPort(from);
- const b = inPort(n, i);
- wires.push({ key: `${n.id}.${port.name}`, d: bezier(a.x, a.y, b.x, b.y) });
- });
- }
-
- return (
- <div className="panel mg">
- <div className="mg-bar">
- <button
- type="button"
- className="mg-add"
- title="Add node"
- onClick={(e) => {
- const r = e.currentTarget.getBoundingClientRect();
- const el = canvasRef.current;
- const cr = el?.getBoundingClientRect();
- const c = cr ? toCanvas(cr.left + cr.width / 2 - 80, cr.top + cr.height / 3) : { x: 60, y: 60 };
- openAddMenu(r.left, r.bottom + 2, c.x, c.y);
- }}
- >
- <Plus size={13} strokeWidth={2} /> Add
- </button>
- {selected && (
- <button type="button" className="mg-del" onClick={() => { MaterialGraphDocument.edit('Delete node', (d) => Object.assign(d, removeNode(d, selected))); setSelected(null); }} title="Delete selected">
- <Trash2 size={13} strokeWidth={1.9} />
- </button>
- )}
- <span className="mg-title">{filePath.split('/').pop()}{dirty && <DirtyDot />}</span>
- <span style={{ flex: 1 }} />
- <button type="button" className="primary" disabled={!dirty} onClick={() => void saveMaterialGraph(filePath, graph)}>
- <Save size={13} strokeWidth={1.9} /> Save
- </button>
- </div>
-
- <div
- className="mg-canvas"
- ref={canvasRef}
- style={{ backgroundSize: `${20 * vp.zoom}px ${20 * vp.zoom}px`, backgroundPosition: `${vp.x}px ${vp.y}px` }}
- onPointerDown={(e) => {
- if (e.button === 1) {
- e.preventDefault();
- pan.current = { sx: e.clientX, sy: e.clientY, vx: vp.x, vy: vp.y };
- return;
- }
- setSelected(null);
- }}
- onWheel={(e) => {
- const el = canvasRef.current;
- if (!el) return;
- const r = el.getBoundingClientRect();
- const mx = e.clientX - r.left;
- const my = e.clientY - r.top;
- setVp((v) => {
- const zoom = Math.min(2.5, Math.max(0.25, v.zoom * (e.deltaY < 0 ? 1.1 : 1 / 1.1)));
- const k = zoom / v.zoom;
- return { x: mx - (mx - v.x) * k, y: my - (my - v.y) * k, zoom };
- });
- }}
- onContextMenu={(e) => {
- e.preventDefault();
- const p = toCanvas(e.clientX, e.clientY);
- openAddMenu(e.clientX, e.clientY, p.x, p.y);
+ const toolbar = (
+ <>
+ <button
+ type="button"
+ className="ng-btn"
+ title="Add node"
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ canvas.current?.openMenuAt(r.left, r.bottom + 2);
}}
>
- <div style={{ position: 'absolute', top: 0, left: 0, transform: `translate(${vp.x}px, ${vp.y}px) scale(${vp.zoom})`, transformOrigin: '0 0' }}>
- <svg className="mg-wires" aria-hidden="true">
- {wires.map((w) => <path key={w.key} d={w.d} />)}
- {wire.current && cursor && (() => {
- const from = graph.nodes.find((m) => m.id === wire.current!.fromId);
- if (!from) return null;
- const a = outPort(from);
- return <path className="mg-wire-live" d={bezier(a.x, a.y, cursor.x, cursor.y)} />;
- })()}
- </svg>
-
- {graph.nodes.map((n) => {
- const spec = NODE_SPECS[n.type];
- const h = HEADER_H + Math.max(spec.inputs.length, 1) * ROW_H + spec.params.length * ROW_H;
- return (
- <div
- key={n.id}
- className={`mg-node${selected === n.id ? ' sel' : ''}`}
- style={{ left: nodeX(n), top: nodeY(n), width: NODE_W, minHeight: h }}
- onPointerDown={(e) => { e.stopPropagation(); setSelected(n.id); }}
- onContextMenu={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setSelected(n.id);
- const p = toCanvas(e.clientX, e.clientY);
- setMenu({ sx: e.clientX, sy: e.clientY, cx: p.x, cy: p.y, nodeId: n.id });
- }}
- >
- <div
- className="mg-node-head"
- onPointerDown={(e) => {
- e.stopPropagation();
- setSelected(n.id);
- const p = toCanvas(e.clientX, e.clientY);
- drag.current = { id: n.id, offX: p.x - nodeX(n), offY: p.y - nodeY(n), before: graph };
- }}
- >
- {spec.label}
- </div>
-
- {/* Output port (right edge, at the header row). */}
- {spec.output && (
- <span
- className="mg-port out"
- style={{ top: HEADER_H / 2, background: TYPE_COLOR[spec.output] }}
- title={spec.output}
- onPointerDown={(e) => { e.stopPropagation(); wire.current = { fromId: n.id }; setCursor(toCanvas(e.clientX, e.clientY)); }}
- />
- )}
-
- {/* Input ports + rows. Click a wired input to disconnect it. */}
- {spec.inputs.map((port) => (
- <div className="mg-row" key={port.name} style={{ height: ROW_H }}>
- <span
- className="mg-port in"
- style={{ top: '50%', background: TYPE_COLOR[port.type] }}
- title={port.type}
- onPointerDown={(e) => {
- e.stopPropagation();
- if (n.inputs?.[port.name]) MaterialGraphDocument.edit('Disconnect', (d) => Object.assign(d, disconnect(d, n.id, port.name)));
- }}
- />
- <span className="mg-row-label">{port.name}</span>
- </div>
- ))}
-
- {/* Node literal params (constColor / constFloat / textureSample). */}
- {spec.params.map((pf) => (
- <div className="mg-param" key={pf.key} style={{ height: ROW_H }}>
- <span className="mg-row-label">{pf.label}</span>
- {pf.kind === 'color' && (
- <ColorControl value={rgbaToHex((n.params?.value as number[]) ?? [1, 1, 1, 1])} onChange={(hex) => setNodeParam(n.id, 'value', hexToRgba(hex))} />
- )}
- {pf.kind === 'float' && (
- <NumField value={typeof n.params?.value === 'number' ? n.params.value : 0} onCommit={(v) => setNodeParam(n.id, 'value', v)} />
- )}
- {pf.kind === 'texture' && (
- <span className="mg-texname">{String(n.params?.name ?? '')}</span>
- )}
- </div>
- ))}
- </div>
- );
- })}
- </div>
- </div>
-
- {menu && <ContextMenu x={menu.sx} y={menu.sy} items={menuItems()} onClose={() => setMenu(null)} />}
- </div>
+ <Plus size={13} strokeWidth={2} /> Add
+ </button>
+ {selected && (
+ <button type="button" className="ng-btn" title="Delete selected" onClick={() => deleteNode(selected)}>
+ <Trash2 size={13} strokeWidth={1.9} />
+ </button>
+ )}
+ <span className="ng-doc-title">{filePath.split('/').pop()}{dirty && <DirtyDot />}</span>
+ <span style={{ flex: 1 }} />
+ <button type="button" className="ng-btn primary" disabled={!dirty} onClick={() => void saveMaterialGraph(filePath, graph)}>
+ <Save size={13} strokeWidth={1.9} /> Save
+ </button>
+ </>
);
-}
-// The input port nearest (@p x,@p y) within a small radius — the connect-drop hit test.
-function nearestInputPort(graph: MaterialGraph, x: number, y: number): { nodeId: string; slot: string } | null {
- let best: { nodeId: string; slot: string } | null = null;
- let bestD2 = 18 * 18;
- for (const n of graph.nodes) {
- const inputs = NODE_SPECS[n.type].inputs;
- for (let i = 0; i < inputs.length; i++) {
- const p = inPort(n, i);
- const d2 = (p.x - x) ** 2 + (p.y - y) ** 2;
- if (d2 < bestD2) {
- bestD2 = d2;
- best = { nodeId: n.id, slot: inputs[i].name };
+ return (
+ <NodeGraphCanvas<MatCanvasNode, CanvasEdge>
+ apiRef={canvas}
+ nodes={nodes}
+ edges={edges}
+ selectedNode={selected}
+ selectedEdge={selectedEdge}
+ nodeSize={(n) => ({ width: NODE_W, height: nodeHeight(n) })}
+ outputs={(n) => {
+ const out = NODE_SPECS[n.type].output;
+ return out ? [{ id: '', y: HEADER_H / 2, color: TYPE_COLOR[out], title: out }] : [];
+ }}
+ inputs={(n) =>
+ NODE_SPECS[n.type].inputs.map((port, i): CanvasPort => ({
+ id: port.name,
+ y: HEADER_H + ROW_H * i + ROW_H / 2,
+ color: TYPE_COLOR[port.type],
+ title: `${port.name}: ${port.type}`,
+ }))
}
- }
- }
- return best;
+ onInputPortDown={(nodeId, slot) => {
+ const n = nodes.find((m) => m.id === nodeId);
+ if (n?.inputs?.[slot]) disconnectSlot(nodeId, slot);
+ }}
+ onSelectNode={setSelected}
+ onSelectEdge={setSelectedEdge}
+ onMoveNodeStart={() => { dragBefore.current = graph; }}
+ onMoveNode={(id, x, y) => MaterialGraphDocument.replaceAsset(moveNode(graph, id, x, y), { dirty: true })}
+ onMoveNodeEnd={() => {
+ const after = MaterialGraphDocument.asset;
+ const before = dragBefore.current;
+ if (after && before) EditorHistory.record('Move node', () => MaterialGraphDocument.replaceAsset(after), () => MaterialGraphDocument.replaceAsset(before));
+ }}
+ onConnect={(from, to, _fromPort, toPort) =>
+ MaterialGraphDocument.edit('Connect', (d) => Object.assign(d, connect(d, from, to, toPort)))}
+ onDeleteNode={deleteNode}
+ onDeleteEdge={(id) => {
+ const w = parseWireId(id);
+ if (w) disconnectSlot(w.to, w.slot);
+ setSelectedEdge(null);
+ }}
+ menuItems={(target) =>
+ target.kind === 'node'
+ ? [{ label: 'Delete node', danger: true, onClick: () => deleteNode(target.nodeId!) }]
+ : (Object.keys(NODE_SPECS) as GraphNodeType[])
+ .filter((t) => NODE_SPECS[t].addable)
+ .map((t) => ({
+ label: `Add ${NODE_SPECS[t].label}`,
+ onClick: () => MaterialGraphDocument.edit(`Add ${t}`, (d) => Object.assign(d, addNode(d, t, target.x, target.y).graph)),
+ }))}
+ toolbar={toolbar}
+ emptyHint="Right-click to add a node, then drag from an output port into a typed input."
+ renderNode={(n, sel) => {
+ const spec = NODE_SPECS[n.type];
+ return (
+ <div className={`mg-node${sel ? ' sel' : ''}`}>
+ <div className="mg-node-head">{spec.label}</div>
+ {spec.inputs.map((port) => (
+ <div className="mg-row" key={port.name} style={{ height: ROW_H }}>
+ <span className="mg-row-label">{port.name}</span>
+ </div>
+ ))}
+ {spec.inputs.length === 0 && <div className="mg-row" style={{ height: ROW_H }} />}
+ {spec.params.map((pf) => (
+ <div className="mg-param" key={pf.key} style={{ height: ROW_H }} onPointerDown={(e) => e.stopPropagation()}>
+ <span className="mg-row-label">{pf.label}</span>
+ {pf.kind === 'color' && (
+ <ColorControl value={rgbaToHex((n.params?.value as number[]) ?? [1, 1, 1, 1])} onChange={(hex) => setNodeParam(n.id, 'value', hexToRgba(hex))} />
+ )}
+ {pf.kind === 'float' && (
+ <NumField value={typeof n.params?.value === 'number' ? n.params.value : 0} onCommit={(v) => setNodeParam(n.id, 'value', v)} />
+ )}
+ {pf.kind === 'texture' && (
+ <span className="mg-texname">{String(n.params?.name ?? '')}</span>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+ }}
+ />
+ );
}
diff --git a/desktop/src/panels/NodeGraphCanvas.tsx b/desktop/src/panels/NodeGraphCanvas.tsx
index 37dfa2338..b1aa32f90 100644
--- a/desktop/src/panels/NodeGraphCanvas.tsx
+++ b/desktop/src/panels/NodeGraphCanvas.tsx
@@ -5,14 +5,16 @@
* @brief Generic node-graph canvas — draggable nodes wired by selectable bezier
* edges, shared by the state-machine and behavior-tree editors.
*
- * Owns only the interaction (pan-by-scroll, node drag, wire-to-connect, edge/node
+ * Owns only the interaction (pan/zoom, node drag, wire-to-connect, edge/node
* selection, delete, bezier + self-loops). Everything domain-specific — node body,
- * edge label, sizes, connect policy — is injected via props, so FSM (arbitrary
- * guarded edges, cycles) and BT (parent/child tree edges) both drive it. Extracted
- * from the proven StateMachineEditor canvas. Styling lives in theme/nodegraph.css;
- * right-click menus are the shared <ContextMenu>.
+ * edge label, sizes, ports, connect policy — is injected via props, so FSM
+ * (arbitrary guarded edges, cycles), BT (parent/child tree edges), and the
+ * material graph (typed multi-input ports) all drive it. Nodes default to one
+ * input/output port at mid-height; `inputs`/`outputs` inject per-node port lists
+ * (position, color) and edges carry optional port ids. Styling lives in
+ * theme/nodegraph.css; right-click menus are the shared <ContextMenu>.
*/
-import { useEffect, useRef, useState, type ReactNode, type MouseEvent as ReactMouseEvent } from 'react';
+import { useEffect, useImperativeHandle, useRef, useState, type ReactNode, type Ref, type MouseEvent as ReactMouseEvent } from 'react';
import { ContextMenu, type MenuItem } from '@/components/Menu';
export type { MenuItem };
@@ -27,6 +29,25 @@ export interface CanvasEdge {
id: string;
from: string;
to: string;
+ /** Source/target port ids on multi-port nodes (default port = ''). */
+ fromPort?: string;
+ toPort?: string;
+}
+
+export interface CanvasPort {
+ /** Port id within its node ('' = the default single port). */
+ id: string;
+ /** Vertical offset of the port center within the node (px, node coords). */
+ y: number;
+ /** Dot color (defaults to the shared handle/anchor styling). */
+ color?: string;
+ title?: string;
+}
+
+/** Imperative surface exposed via `apiRef` (e.g. a toolbar Add button opening
+ * the canvas context menu without owning the viewport math). */
+export interface NodeGraphCanvasApi {
+ openMenuAt(screenX: number, screenY: number): void;
}
export interface ContextTarget {
@@ -49,14 +70,23 @@ export interface NodeGraphCanvasProps<N extends CanvasNode, E extends CanvasEdge
renderEdgeLabel?: (e: E) => ReactNode;
/** Allow an edge from a node to itself (FSM self-transition). */
allowSelfLoop?: boolean;
- /** Whether a node shows a left input anchor (can receive an edge). Default: all can. */
+ /** Whether a node shows a left input anchor (can receive an edge). Default: all can.
+ * Ignored when `inputs` is given. */
hasInput?: (n: N) => boolean;
+ /** Output ports on the node's right edge. Default: one at mid-height. */
+ outputs?: (n: N) => CanvasPort[];
+ /** Input ports on the node's left edge. Default: one at mid-height. */
+ inputs?: (n: N) => CanvasPort[];
+ /** Pressing an input port (e.g. the material graph's click-to-disconnect).
+ * Providing this makes input anchors interactive. */
+ onInputPortDown?: (nodeId: string, portId: string) => void;
onSelectNode: (id: string | null) => void;
onSelectEdge: (id: string | null) => void;
onMoveNode: (id: string, x: number, y: number) => void;
onMoveNodeStart?: (id: string) => void;
onMoveNodeEnd?: (id: string) => void;
- onConnect: (from: string, to: string) => void;
+ /** A wire dropped on a target: port ids are '' for default single-port nodes. */
+ onConnect: (from: string, to: string, fromPort: string, toPort: string) => void;
onDeleteNode: (id: string) => void;
onDeleteEdge: (id: string) => void;
/** Context-menu items for a right-click on empty canvas or on a node. */
@@ -65,6 +95,8 @@ export interface NodeGraphCanvasProps<N extends CanvasNode, E extends CanvasEdge
toolbar?: ReactNode;
/** Shown when there are no nodes. */
emptyHint?: ReactNode;
+ /** Receives the imperative canvas API (menu opening). */
+ apiRef?: Ref<NodeGraphCanvasApi>;
}
const nx = (n: CanvasNode) => n.x ?? 0;
@@ -79,10 +111,19 @@ function bezier(x1: number, y1: number, x2: number, y2: number): string {
export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(props: NodeGraphCanvasProps<N, E>) {
const {
nodes, edges, selectedNode, selectedEdge, nodeSize, renderNode, renderEdgeLabel,
- allowSelfLoop, hasInput, menuItems, onSelectNode, onSelectEdge, onMoveNode, onMoveNodeStart, onMoveNodeEnd,
- onConnect, onDeleteNode, onDeleteEdge, toolbar, emptyHint,
+ allowSelfLoop, hasInput, outputs, inputs, onInputPortDown,
+ menuItems, onSelectNode, onSelectEdge, onMoveNode, onMoveNodeStart, onMoveNodeEnd,
+ onConnect, onDeleteNode, onDeleteEdge, toolbar, emptyHint, apiRef,
} = props;
+ // Port model: single mid-height ports unless the consumer injects lists.
+ const outPorts = (n: N): CanvasPort[] =>
+ outputs ? outputs(n) : [{ id: '', y: nodeSize(n).height / 2 }];
+ const inPorts = (n: N): CanvasPort[] =>
+ inputs ? inputs(n) : (hasInput?.(n) ?? true) ? [{ id: '', y: nodeSize(n).height / 2 }] : [];
+ const portY = (ports: CanvasPort[], id: string | undefined, fallback: number): number =>
+ (ports.find((p) => p.id === (id ?? '')) ?? ports[0])?.y ?? fallback;
+
const [wiring, setWiring] = useState(false);
const [menu, setMenu] = useState<{ screenX: number; screenY: number; target: ContextTarget } | null>(null);
// Infinite-canvas viewport: pan offset (screen px) + zoom. Content is drawn in
@@ -99,10 +140,17 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
const canvasRef = useRef<HTMLDivElement>(null);
const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);
const drag = useRef<{ id: string; offX: number; offY: number } | null>(null);
- const wire = useRef<{ from: string } | null>(null);
+ const wire = useRef<{ from: string; port: CanvasPort } | null>(null);
const byId = new Map(nodes.map(n => [n.id, n]));
- const out = (n: N) => { const s = nodeSize(n); return { x: nx(n) + s.width, y: ny(n) + s.height / 2 }; };
+ const outPos = (n: N, port: CanvasPort) => ({ x: nx(n) + nodeSize(n).width, y: ny(n) + port.y });
+
+ useImperativeHandle(apiRef, () => ({
+ openMenuAt: (screenX: number, screenY: number) => {
+ const p = toCanvas(screenX, screenY);
+ setMenu({ screenX, screenY, target: { kind: 'canvas', x: p.x, y: p.y } });
+ },
+ }));
// Screen point → world coord (inverse of the viewport transform).
const toCanvas = (clientX: number, clientY: number) => {
@@ -139,9 +187,33 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
}
if (wire.current) {
const p = toCanvas(e.clientX, e.clientY);
- const target = nodeAt(p.x, p.y);
const from = wire.current.from;
- if (target && (allowSelfLoop || target.id !== from)) onConnect(from, target.id);
+ const fromPort = wire.current.port.id;
+ const accepts = (n: N) => (allowSelfLoop || n.id !== from) && inPorts(n).length > 0;
+ // Dropping on a node snaps to its nearest input port; a near-miss outside
+ // any node still lands on the closest port within a small radius.
+ let dest: { node: N; port: CanvasPort } | null = null;
+ const target = nodeAt(p.x, p.y);
+ if (target && accepts(target)) {
+ const ports = inPorts(target);
+ const nearest = ports.reduce((a, b) =>
+ Math.abs(ny(target) + a.y - p.y) <= Math.abs(ny(target) + b.y - p.y) ? a : b,
+ );
+ dest = { node: target, port: nearest };
+ } else {
+ let bestD2 = 18 * 18;
+ for (const n of nodes) {
+ if (!accepts(n)) continue;
+ for (const port of inPorts(n)) {
+ const d2 = (nx(n) - p.x) ** 2 + (ny(n) + port.y - p.y) ** 2;
+ if (d2 < bestD2) {
+ bestD2 = d2;
+ dest = { node: n, port };
+ }
+ }
+ }
+ }
+ if (dest) onConnect(from, dest.node.id, fromPort, dest.port.id);
wire.current = null;
setCursor(null);
setWiring(false);
@@ -174,17 +246,17 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
return `M ${cx - 16} ${y} C ${cx - 30} ${y - 40}, ${cx + 30} ${y - 40}, ${cx + 16} ${y}`;
};
- // Edge geometry: anchors chosen on the side facing the target, plus a bow
- // offset for bidirectional pairs so they don't overlap.
+ // Edge geometry: anchors on the nodes' port positions, plus a bow offset for
+ // bidirectional pairs so they don't overlap.
const edgeGeom = (from: N, to: N, e: E) => {
if (e.from === e.to) {
return { d: selfLoopPath(from), mx: nx(from) + nodeSize(from).width / 2, my: ny(from) - 22 };
}
const fs = nodeSize(from);
const ts = nodeSize(to);
- // Output (right edge) -> input (left edge), matching the node handles.
- const a = { x: nx(from) + fs.width, y: ny(from) + fs.height / 2 };
- const b = { x: nx(to), y: ny(to) + ts.height / 2 };
+ // Output (right edge) -> input (left edge), matching the node port dots.
+ const a = { x: nx(from) + fs.width, y: ny(from) + portY(outPorts(from), e.fromPort, fs.height / 2) };
+ const b = { x: nx(to), y: ny(to) + portY(inPorts(to), e.toPort, ts.height / 2) };
// Target to the right: a direct S-curve. Otherwise it's a back-edge (the
// source sits right of the target) - route it as a compact arc bowing below
// the nodes, not a wide horizontal S that flings far past them.
@@ -252,7 +324,7 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
{wire.current && cursor && (() => {
const from = byId.get(wire.current.from);
if (!from) return null;
- const a = out(from);
+ const a = outPos(from, wire.current.port);
return <path d={bezier(a.x, a.y, cursor.x, cursor.y)} stroke="var(--star-hi)" strokeWidth={1.6} strokeDasharray="4 3" fill="none" />;
})()}
</svg>
@@ -273,8 +345,7 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
{nodes.map(n => {
const s = nodeSize(n);
// While dragging a wire, outline the nodes it can land on.
- const droppable = wiring && wire.current !== null && (allowSelfLoop || wire.current.from !== n.id);
- const showInput = hasInput?.(n) ?? true;
+ const droppable = wiring && wire.current !== null && (allowSelfLoop || wire.current.from !== n.id) && inPorts(n).length > 0;
return (
<div key={n.id} className={`ng-node${droppable ? ' droppable' : ''}`} style={{ left: nx(n), top: ny(n), width: s.width, height: s.height }}
onPointerDown={e => {
@@ -285,10 +356,26 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
onMoveNodeStart?.(n.id);
}}
onContextMenu={e => { e.stopPropagation(); onSelectNode(n.id); const p = toCanvas(e.clientX, e.clientY); openMenu(e, { kind: 'node', nodeId: n.id, x: p.x, y: p.y }); }}>
- {showInput && <span className="ng-in-anchor" style={{ top: s.height / 2 - 5 }} aria-hidden title="Edges land here" />}
+ {inPorts(n).map(port => (
+ <span
+ key={`in:${port.id}`}
+ className={`ng-in-anchor${onInputPortDown ? ' clickable' : ''}`}
+ style={{ top: port.y - 5, background: port.color }}
+ aria-hidden={onInputPortDown ? undefined : true}
+ title={port.title ?? 'Edges land here'}
+ onPointerDown={onInputPortDown ? (e) => { e.stopPropagation(); onInputPortDown(n.id, port.id); } : undefined}
+ />
+ ))}
{renderNode(n, selectedNode === n.id)}
- <span className="ng-handle" style={{ top: s.height / 2 - 7 }} title="Drag to another node to connect"
- onPointerDown={e => { e.stopPropagation(); wire.current = { from: n.id }; setWiring(true); setCursor(toCanvas(e.clientX, e.clientY)); }} />
+ {outPorts(n).map(port => (
+ <span
+ key={`out:${port.id}`}
+ className="ng-handle"
+ style={{ top: port.y - 7, background: port.color }}
+ title={port.title ?? 'Drag to another node to connect'}
+ onPointerDown={e => { e.stopPropagation(); wire.current = { from: n.id, port }; setWiring(true); setCursor(toCanvas(e.clientX, e.clientY)); }}
+ />
+ ))}
</div>
);
})}
diff --git a/desktop/src/theme/material.css b/desktop/src/theme/material.css
index 9e4689cdf..fb6369120 100644
--- a/desktop/src/theme/material.css
+++ b/desktop/src/theme/material.css
@@ -25,29 +25,13 @@
.mat-sync { padding: 4px 10px; font-size: var(--fs-2xs); color: var(--text-mute); border-bottom: 1px solid var(--border); flex-shrink: 0; }
.mat-hint { padding: 8px 10px; font-size: var(--fs-xs); color: var(--text-mute); }
-/* ── Material Graph node editor (P5b) ─────────────────────────────────────── */
-.panel.mg { display: flex; flex-direction: column; min-height: 0; height: 100%; }
-.mg-bar { position: relative; display: flex; align-items: center; gap: 8px; height: 34px; flex-shrink: 0; padding: 0 10px; border-bottom: 1px solid var(--border); background: var(--srf-2); }
-.mg-bar .mg-add, .mg-bar .mg-del { display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-sm); color: var(--text); cursor: pointer; }
-.mg-bar .mg-add:hover, .mg-bar .mg-del:hover { background: var(--srf-4); }
-.mg-title { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-sm); color: var(--text); }
-/* Pan/zoom canvas — same infinite-viewport model as the FSM/BT node canvas
- (middle-drag pans, wheel zooms; dot grid scale/offset set inline). */
-.mg-canvas { position: relative; flex: 1; min-height: 0; overflow: hidden; background-color: var(--srf-1); background-image: radial-gradient(circle, var(--srf-3) 1px, transparent 1px); }
-.mg-wires { position: absolute; top: 0; left: 0; width: 3000px; height: 3000px; pointer-events: none; overflow: visible; }
-.mg-wires path { fill: none; stroke: var(--text-mute); stroke-width: 2; }
-.mg-wires path.mg-wire-live { stroke: var(--acc); stroke-dasharray: 5 4; opacity: 0.8; }
-
-.mg-node { position: absolute; background: var(--srf-2); border: 1px solid var(--border-line); border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35); user-select: none; }
-.mg-node.sel { border-color: var(--acc); box-shadow: 0 0 0 1px var(--acc), 0 2px 8px rgba(0, 0, 0, 0.4); }
-.mg-node-head { height: 28px; display: flex; align-items: center; padding: 0 10px; font-size: var(--fs-xs); font-weight: 600; color: var(--text); border-bottom: 1px solid var(--border); border-radius: 6px 6px 0 0; cursor: grab; background: var(--srf-3); }
-.mg-node .mg-row, .mg-node .mg-param { position: relative; display: flex; align-items: center; gap: 6px; padding: 0 10px; }
+/* ── Material Graph node body — the canvas chrome (pan/zoom, ports, wires,
+ toolbar) is the shared NodeGraphCanvas / nodegraph.css; only the node's
+ inner face is material-specific. ──────────────────────────────────────── */
+.mg-node { width: 100%; height: 100%; background: var(--srf-2); border: 1px solid var(--border-line); border-radius: var(--r-lg); box-shadow: var(--shadow-1); user-select: none; overflow: hidden; }
+.mg-node.sel { border-color: var(--acc); box-shadow: 0 0 0 1px var(--acc), var(--shadow-1); }
+.mg-node-head { height: 28px; display: flex; align-items: center; padding: 0 10px; font-size: var(--fs-xs); font-weight: 600; color: var(--text); border-bottom: 1px solid var(--border); cursor: grab; background: var(--srf-3); }
+.mg-node .mg-row, .mg-node .mg-param { display: flex; align-items: center; gap: 6px; padding: 0 10px; }
.mg-row-label { font-size: var(--fs-2xs); color: var(--text-dim); }
-.mg-param { gap: 6px; }
.mg-param .mg-row-label { min-width: 38px; }
.mg-texname { font-size: var(--fs-2xs); color: var(--text-mute); font-family: var(--font-mono, monospace); }
-
-.mg-port { position: absolute; width: 11px; height: 11px; border-radius: 50%; border: 2px solid var(--srf-1); cursor: crosshair; }
-.mg-port.out { right: -6px; transform: translateY(-50%); }
-.mg-port.in { left: -6px; transform: translateY(-50%); }
-.mg-port:hover { box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.15); }
diff --git a/desktop/src/theme/nodegraph.css b/desktop/src/theme/nodegraph.css
index c92dfdad7..6710b236d 100644
--- a/desktop/src/theme/nodegraph.css
+++ b/desktop/src/theme/nodegraph.css
@@ -62,7 +62,8 @@
z-index: 2;
}
.ng-handle:hover { background: var(--star-hi); }
-/* Input anchor (left): a visual cue that edges land on this node. */
+/* Input anchor (left): a visual cue that edges land on this node. Interactive
+ when the consumer handles port presses (material click-to-disconnect). */
.ng-in-anchor {
position: absolute;
left: -5px;
@@ -72,7 +73,10 @@
background: var(--srf-6);
border: 2px solid var(--srf-1);
pointer-events: none;
+ z-index: 2;
}
+.ng-in-anchor.clickable { pointer-events: auto; cursor: pointer; }
+.ng-in-anchor.clickable:hover { box-shadow: 0 0 0 2px var(--star-line); }
.ng-edge-label {
position: absolute;