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.

feat(editor): node-graph canvas UX - anchors, right-click, infinite canvas

esengine8f359d2da7d9
diff --git a/desktop/src/panels/BtTreeEditor.tsx b/desktop/src/panels/BtTreeEditor.tsx
index a83dccc8a..7c470fece 100644
--- a/desktop/src/panels/BtTreeEditor.tsx
+++ b/desktop/src/panels/BtTreeEditor.tsx
@@ -13,13 +13,13 @@
import { useRef, useState, useSyncExternalStore, type CSSProperties } from 'react';
import { Trash2, Save } from 'lucide-react';
import {
- btNodes, btEdges, addBtChild, removeBtNode, moveBtNode, setBtNodeField, reparentBtNode,
- canHaveChildren, aiRegistry,
+ btNodes, btEdges, addBtChild, addBtOrphan, removeBtNode, moveBtNode, setBtNodeField, reparentBtNode,
+ canHaveChildren, maxChildren, aiRegistry,
type BtNode, type BtNodeType, type BtDefinition, type BtEdge,
} from 'esengine';
import { BtDocument } from '@/bt/BtDocument';
import { EditorHistory } from '@/engine/EditorHistory';
-import { NodeGraphCanvas, type CanvasNode } from '@/panels/NodeGraphCanvas';
+import { NodeGraphCanvas, type CanvasNode, type MenuItem } from '@/panels/NodeGraphCanvas';
type BtCanvasNode = BtNode & CanvasNode;
@@ -106,6 +106,7 @@ export function BtTreeEditor() {
selectedNode={selected}
selectedEdge={null}
nodeSize={() => ({ width: NODE_W, height: NODE_H })}
+ hasInput={n => def.root.id !== n.id}
onSelectNode={setSelected}
onSelectEdge={() => { /* BT edges are structural; not independently selectable */ }}
onMoveNodeStart={() => { dragBefore.current = def; }}
@@ -118,6 +119,25 @@ export function BtTreeEditor() {
onConnect={(from, to) => BtDocument.edit('Reparent', d => Object.assign(d, reparentBtNode(d, to, from)))}
onDeleteNode={id => { if (def.root.id !== id) { BtDocument.edit('Delete node', d => Object.assign(d, removeBtNode(d, id))); setSelected(null); } }}
onDeleteEdge={() => { /* structural */ }}
+ menuItems={target => {
+ // Canvas → create an unconnected node (wire it by dragging a
+ // parent's handle onto it). Node → add a child under it directly.
+ if (target.kind === 'canvas') {
+ return BT_TYPES.map(spec => ({ label: `Add ${spec.label}`, onClick: () => BtDocument.edit('Add node', d => Object.assign(d, addBtOrphan(d, spec.type, target.x, target.y))) }));
+ }
+ const parentId = target.nodeId!;
+ const parent = nodes.find(n => n.id === parentId);
+ const full = !parent || (parent.children?.length ?? 0) >= maxChildren(parent.type);
+ const items: MenuItem[] = [];
+ if (parent && canHaveChildren(parent.type) && !full) {
+ for (const spec of BT_TYPES) items.push({ label: `Add child: ${spec.label}`, onClick: () => BtDocument.edit('Add node', d => Object.assign(d, addBtChild(d, parentId, spec.type, target.x, target.y))) });
+ }
+ if (def.root.id !== parentId) {
+ if (items.length) items.push({ label: '', sep: true, onClick: () => { /* separator */ } });
+ items.push({ label: 'Delete node', onClick: () => { BtDocument.edit('Delete node', d => Object.assign(d, removeBtNode(d, parentId))); setSelected(null); } });
+ }
+ return items;
+ }}
toolbar={toolbar}
emptyHint="Drag from a node's handle to another to set parent → child."
renderNode={(n, sel) => {
diff --git a/desktop/src/panels/NodeGraphCanvas.tsx b/desktop/src/panels/NodeGraphCanvas.tsx
index 0676bf9ff..0bf26bd13 100644
--- a/desktop/src/panels/NodeGraphCanvas.tsx
+++ b/desktop/src/panels/NodeGraphCanvas.tsx
@@ -11,7 +11,7 @@
* guarded edges, cycles) and BT (parent/child tree edges) both drive it. Extracted
* from the proven StateMachineEditor canvas.
*/
-import { useEffect, useRef, useState, type ReactNode, type CSSProperties } from 'react';
+import { useEffect, useRef, useState, type ReactNode, type CSSProperties, type MouseEvent as ReactMouseEvent } from 'react';
export interface CanvasNode {
id: string;
@@ -25,6 +25,22 @@ export interface CanvasEdge {
to: string;
}
+export interface MenuItem {
+ label: string;
+ onClick: () => void;
+ disabled?: boolean;
+ /** Render a separator instead of an item (label/onClick ignored). */
+ sep?: boolean;
+}
+
+export interface ContextTarget {
+ kind: 'canvas' | 'node';
+ nodeId?: string;
+ /** Canvas-space position of the right-click — where a new node should go. */
+ x: number;
+ y: number;
+}
+
export interface NodeGraphCanvasProps<N extends CanvasNode, E extends CanvasEdge> {
nodes: N[];
edges: E[];
@@ -37,6 +53,8 @@ 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. */
+ hasInput?: (n: N) => boolean;
onSelectNode: (id: string | null) => void;
onSelectEdge: (id: string | null) => void;
onMoveNode: (id: string, x: number, y: number) => void;
@@ -45,6 +63,8 @@ export interface NodeGraphCanvasProps<N extends CanvasNode, E extends CanvasEdge
onConnect: (from: string, to: string) => void;
onDeleteNode: (id: string) => void;
onDeleteEdge: (id: string) => void;
+ /** Context-menu items for a right-click on empty canvas or on a node. */
+ menuItems?: (target: ContextTarget) => MenuItem[];
/** Toolbar row above the canvas. */
toolbar?: ReactNode;
/** Shown when there are no nodes. */
@@ -62,10 +82,23 @@ 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, onSelectNode, onSelectEdge, onMoveNode, onMoveNodeStart, onMoveNodeEnd,
+ allowSelfLoop, hasInput, menuItems, onSelectNode, onSelectEdge, onMoveNode, onMoveNodeStart, onMoveNodeEnd,
onConnect, onDeleteNode, onDeleteEdge, toolbar, emptyHint,
} = props;
+ 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
+ // world coords inside a transformed container, so there are no scrollbars.
+ const [vp, setVp] = useState({ x: 0, y: 0, zoom: 1 });
+ const pan = useRef<{ sx: number; sy: number; vx: number; vy: number } | null>(null);
+
+ const openMenu = (e: ReactMouseEvent, target: ContextTarget) => {
+ if (!menuItems) return;
+ e.preventDefault();
+ setMenu({ screenX: e.clientX, screenY: e.clientY, target });
+ };
+
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);
@@ -75,11 +108,12 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
const out = (n: N) => { const s = nodeSize(n); return { x: nx(n) + s.width, y: ny(n) + s.height / 2 }; };
const inp = (n: N) => ({ x: nx(n), y: ny(n) + nodeSize(n).height / 2 });
+ // 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 + el.scrollLeft, y: clientY - r.top + el.scrollTop };
+ return { x: (clientX - r.left - vp.x) / vp.zoom, y: (clientY - r.top - vp.y) / vp.zoom };
};
const nodeAt = (x: number, y: number): N | null => {
@@ -92,11 +126,17 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
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) onMoveNode(drag.current.id, p.x - drag.current.offX, p.y - drag.current.offY);
else if (wire.current) setCursor(p);
};
const onUp = (e: PointerEvent) => {
+ pan.current = null;
if (drag.current) {
onMoveNodeEnd?.(drag.current.id);
drag.current = null;
@@ -108,6 +148,7 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
if (target && (allowSelfLoop || target.id !== from)) onConnect(from, target.id);
wire.current = null;
setCursor(null);
+ setWiring(false);
}
};
window.addEventListener('pointermove', onMove);
@@ -117,7 +158,7 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
window.removeEventListener('pointerup', onUp);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [nodes]);
+ }, [nodes, vp]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -140,8 +181,26 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
return (
<div className="panel" style={S.root}>
{toolbar && <div style={S.bar}>{toolbar}</div>}
- <div style={S.canvas} ref={canvasRef} onPointerDown={() => { onSelectNode(null); onSelectEdge(null); }}>
+ <div style={{ ...S.canvas, backgroundSize: `${20 * vp.zoom}px ${20 * vp.zoom}px`, backgroundPosition: `${vp.x}px ${vp.y}px` }} ref={canvasRef}
+ onPointerDown={e => {
+ if (e.button === 1) { e.preventDefault(); pan.current = { sx: e.clientX, sy: e.clientY, vx: vp.x, vy: vp.y }; return; }
+ onSelectNode(null); onSelectEdge(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 => { const p = toCanvas(e.clientX, e.clientY); openMenu(e, { kind: 'canvas', x: p.x, y: p.y }); }}>
{nodes.length === 0 && emptyHint && <div style={S.empty}>{emptyHint}</div>}
+ <div style={{ position: 'absolute', top: 0, left: 0, transform: `translate(${vp.x}px, ${vp.y}px) scale(${vp.zoom})`, transformOrigin: '0 0' }}>
<svg style={S.svg}>
{edges.map(e => {
const from = byId.get(e.from);
@@ -185,22 +244,45 @@ 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;
return (
- <div key={n.id} style={{ ...S.node, left: nx(n), top: ny(n), width: s.width, height: s.height }}
+ <div key={n.id} style={{ ...S.node, left: nx(n), top: ny(n), width: s.width, height: s.height, outline: droppable ? '2px dashed #6ea9ff' : undefined, outlineOffset: 3 }}
onPointerDown={e => {
e.stopPropagation();
onSelectNode(n.id); onSelectEdge(null);
const p = toCanvas(e.clientX, e.clientY);
drag.current = { id: n.id, offX: p.x - nx(n), offY: p.y - ny(n) };
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 style={{ ...S.inAnchor, top: s.height / 2 - 5 }} aria-hidden title="Edges land here" />}
{renderNode(n, selectedNode === n.id)}
- <span style={{ ...S.handle, top: s.height / 2 - 6 }} title="Drag to another node to connect"
- onPointerDown={e => { e.stopPropagation(); wire.current = { from: n.id }; setCursor(toCanvas(e.clientX, e.clientY)); }} />
+ <span style={{ ...S.handle, 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)); }} />
</div>
);
})}
+ </div>
</div>
+
+ {menu && menuItems && (
+ <>
+ <div style={S.menuOverlay} onPointerDown={() => setMenu(null)} onContextMenu={e => { e.preventDefault(); setMenu(null); }} />
+ <div style={{ ...S.menu, left: menu.screenX, top: menu.screenY }}>
+ {menuItems(menu.target).map((it, i) => it.sep
+ ? <div key={i} style={S.menuSep} />
+ : (
+ <button key={i} type="button" disabled={it.disabled}
+ style={{ ...S.menuItem, ...(it.disabled ? S.menuItemDisabled : null) }}
+ onClick={() => { it.onClick(); setMenu(null); }}>
+ {it.label}
+ </button>
+ ))}
+ </div>
+ </>
+ )}
</div>
);
}
@@ -208,10 +290,18 @@ export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(prop
const S: Record<string, CSSProperties> = {
root: { display: 'flex', flexDirection: 'column', height: '100%' },
bar: { display: 'flex', alignItems: 'center', gap: 6, padding: '6px 8px', borderBottom: '1px solid var(--border, #2a2f36)' },
- canvas: { position: 'relative', flex: 1, overflow: 'auto', background: 'var(--canvas, #191c20)', backgroundImage: 'radial-gradient(var(--grid, #262b31) 1px, transparent 1px)', backgroundSize: '20px 20px' },
+ canvas: { position: 'relative', flex: 1, overflow: 'hidden', background: 'var(--canvas, #191c20)', backgroundImage: 'radial-gradient(var(--grid, #262b31) 1px, transparent 1px)' },
empty: { position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: 0.5, fontSize: 13, pointerEvents: 'none' },
svg: { position: 'absolute', top: 0, left: 0, width: 4000, height: 4000, overflow: 'visible' },
node: { position: 'absolute', boxSizing: 'border-box', cursor: 'grab', userSelect: 'none' },
- handle: { position: 'absolute', right: -6, width: 11, height: 11, borderRadius: '50%', background: '#6ea9ff', border: '2px solid var(--canvas, #191c20)', cursor: 'crosshair' },
+ // Output handle (right): drag it to another node to connect.
+ handle: { position: 'absolute', right: -7, width: 14, height: 14, borderRadius: '50%', background: '#6ea9ff', border: '2px solid var(--canvas, #191c20)', boxShadow: '0 0 0 1px #6ea9ff88', cursor: 'crosshair', zIndex: 2 },
+ // Input anchor (left): a visual cue that edges land on this node.
+ inAnchor: { position: 'absolute', left: -5, width: 10, height: 10, borderRadius: '50%', background: '#5a6470', border: '2px solid var(--canvas, #191c20)', pointerEvents: 'none' },
edgeLabel: { position: 'absolute', width: 80, textAlign: 'center', fontSize: 10, padding: '1px 3px', borderRadius: 3, background: 'var(--canvas, #191c20)', border: '1px solid transparent', color: '#aeb6c0', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
+ menuOverlay: { position: 'fixed', inset: 0, zIndex: 100 },
+ menu: { position: 'fixed', zIndex: 101, minWidth: 156, padding: 4, borderRadius: 6, background: 'var(--panel, #232830)', border: '1px solid var(--border, #333)', boxShadow: '0 4px 16px rgba(0,0,0,0.5)', display: 'flex', flexDirection: 'column' },
+ menuItem: { textAlign: 'left', padding: '4px 10px', fontSize: 12, border: 'none', background: 'transparent', color: 'inherit', cursor: 'pointer', borderRadius: 4 },
+ menuItemDisabled: { opacity: 0.4, cursor: 'default' },
+ menuSep: { height: 1, margin: '4px 2px', background: 'var(--border, #333)' },
};
diff --git a/desktop/src/panels/StateMachineEditor.tsx b/desktop/src/panels/StateMachineEditor.tsx
index b2b2d681c..85e7cceee 100644
--- a/desktop/src/panels/StateMachineEditor.tsx
+++ b/desktop/src/panels/StateMachineEditor.tsx
@@ -111,6 +111,13 @@ export function StateMachineEditor() {
onConnect={(from, to) => FsmGraphDocument.edit('Add transition', d => Object.assign(d, addTransition(d, from, to)))}
onDeleteNode={id => { FsmGraphDocument.edit('Delete state', d => Object.assign(d, removeState(d, id))); setSelState(null); }}
onDeleteEdge={id => { const p = parseEdgeId(id); if (p) FsmGraphDocument.edit('Delete transition', d => Object.assign(d, removeTransition(d, p.from, p.index))); setSelEdge(null); }}
+ menuItems={target => target.kind === 'canvas'
+ ? [{ label: 'Add State', onClick: () => { const name = uniqueName(def, 'State'); FsmGraphDocument.edit('Add state', d => Object.assign(d, addState(d, name, target.x, target.y))); setSelState(name); setSelEdge(null); } }]
+ : [
+ { label: 'Set as initial', disabled: def.initial === target.nodeId, onClick: () => FsmGraphDocument.edit('Set initial', d => Object.assign(d, setInitial(d, target.nodeId!))) },
+ { label: '', sep: true, onClick: () => { /* separator */ } },
+ { label: 'Delete state', onClick: () => { FsmGraphDocument.edit('Delete state', d => Object.assign(d, removeState(d, target.nodeId!))); setSelState(null); } },
+ ]}
toolbar={toolbar}
emptyHint="Add a state, then drag from its handle to another to add a transition."
renderEdgeLabel={e => <>{edgeSummary(e.transition)}</>}