9.3 节点图布局与撤销
大图手摆节点累,自动布局把图拍成层:按拓扑深度分列,节点按层排列。布局、移动节点都是可撤销操作——撤销栈用快照保证任意回退。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 图求值 | 9.2 图求值:编译与执行 | 求值给拓扑;布局复用拓扑深度 |
| 撤销系统 | helio-ed-core | 卷一的命令栈思想在此轻量化 |
| 全卷脉络 | 本卷目录 | toc 列章节;布局与撤销让图可维护 |
从零实现:节点图布局与撤销
layeredLayout 按拓扑深度把节点分列,同层节点均匀排布。SnapshotUndoStack 以「快照 + 撤销」为原语:push 前压入旧快照,undo 弹出并恢复;新 push 清空 redo。布局与移动共用这一个栈。
布局计算与撤销边界
helio 示例在有向无环图上计算节点层号,再按列排布。含环图应在调用布局前拒绝或先压缩强连通分量。节点坐标属于显示状态,布局撤销恢复坐标快照。连线和节点内容的编辑需要独立命令。
可运行产物:6 条用例
下面是 src/graph-layout.ts,层级 L1,完整可编译。运行命令 node --test test/09-3-node-graph-undo-layout.test.ts:
// file: src/graph-layout.ts
// tier: L1
// verify: node --test test/09-3-node-graph-undo-layout.test.ts
//
// 视图(第九章):节点图编辑器通用架构——节点图撤销与自动布局。
// 节点图编辑器需要两个支撑能力:自动布局(按依赖层级把节点摆成从左到右
// 的分层图,避免用户手工摆成一团)与图级撤销(保存/恢复整张图快照)。
// 撤销栈是通用的快照栈,节点图与子编辑器都能复用。
import type { GraphNode, Wire } from './node-graph.ts';
export interface Position {
x: number;
y: number;
}
/**
* 分层布局:按最长路径给节点分层(无上游为第 0 层),同层按输入顺序纵向
* 排列。返回每个节点的坐标。
*/
export function layeredLayout(
nodes: GraphNode[],
wires: Wire[],
origin: Position = { x: 0, y: 0 },
spacing = { x: 220, y: 140 },
): Record<string, Position> {
const layer = new Map<string, number>();
for (const n of nodes) layer.set(n.id, 0);
// 迭代松弛求最长路径层号(图是 DAG)。
let changed = true;
let guard = 0;
while (changed && guard < nodes.length + 1) {
changed = false;
guard += 1;
for (const w of wires) {
const fromLayer = layer.get(w.fromNode) ?? 0;
const toLayer = layer.get(w.toNode) ?? 0;
if (toLayer <= fromLayer) {
layer.set(w.toNode, fromLayer + 1);
changed = true;
}
}
}
const byLayer = new Map<number, string[]>();
for (const n of nodes) {
const l = layer.get(n.id) ?? 0;
if (!byLayer.has(l)) byLayer.set(l, []);
byLayer.get(l)!.push(n.id);
}
const out: Record<string, Position> = {};
for (const [l, ids] of byLayer) {
ids.forEach((id, row) => {
out[id] = { x: origin.x + l * spacing.x, y: origin.y + row * spacing.y };
});
}
return out;
}
/** 通用快照撤销栈(深拷贝入栈,避免外部修改污染历史)。 */
export class SnapshotUndoStack<T> {
#undo: T[] = [];
#redo: T[] = [];
#limit: number;
constructor(limit = 100) {
this.#limit = limit;
}
push(snapshot: T): void {
this.#undo.push(structuredClone(snapshot));
if (this.#undo.length > this.#limit) this.#undo.shift();
this.#redo = [];
}
undo(current: T): T | null {
const prev = this.#undo.pop();
if (prev === undefined) return null;
this.#redo.push(structuredClone(current));
return prev;
}
redo(current: T): T | null {
const next = this.#redo.pop();
if (next === undefined) return null;
this.#undo.push(structuredClone(current));
return next;
}
canUndo(): boolean {
return this.#undo.length > 0;
}
canRedo(): boolean {
return this.#redo.length > 0;
}
}
layeredLayout 的列号就是拓扑深度:深度 0 是输入侧、深度最大是输出侧,跨层连线自然跨列。撤销栈用深拷贝快照而非命令逆,简化实现——代价是内存,收益是「什么都能退」。redo 由 push 清空,语义与编辑器一致。
下面是 test/09-3-node-graph-undo-layout.test.ts,层级 L1:
// file: test/09-3-node-graph-undo-layout.test.ts
// tier: L1
// verify: node --test test/09-3-node-graph-undo-layout.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { layeredLayout, SnapshotUndoStack } from '../src/graph-layout.ts';
import type { GraphNode, Wire } from '../src/node-graph.ts';
function node(id: string): GraphNode {
return { id, type: 'n', ports: [] };
}
const NODES = [node('a'), node('b'), node('c')];
const WIRES: Wire[] = [
{ id: 'w1', fromNode: 'a', fromPort: 'out', toNode: 'b', toPort: 'in' },
{ id: 'w2', fromNode: 'b', fromPort: 'out', toNode: 'c', toPort: 'in' },
];
test('链式依赖分三层', () => {
const pos = layeredLayout(NODES, WIRES);
assert.equal(pos.a.x, 0);
assert.equal(pos.b.x, 220);
assert.equal(pos.c.x, 440);
});
test('同层节点纵向排列', () => {
const nodes = [node('a'), node('b')];
const pos = layeredLayout(nodes, []);
assert.equal(pos.a.y, 0);
assert.equal(pos.b.y, 140);
});
test('自定义原点与间距', () => {
const pos = layeredLayout([node('a'), node('b')], [WIRES[0]], { x: 10, y: 10 }, { x: 100, y: 50 });
assert.deepEqual(pos.a, { x: 10, y: 10 });
assert.deepEqual(pos.b, { x: 110, y: 10 });
});
test('快照撤销:push 后可 undo 恢复', () => {
const stack = new SnapshotUndoStack<{ v: number }>();
stack.push({ v: 1 });
assert.equal(stack.canUndo(), true);
const prev = stack.undo({ v: 2 });
assert.deepEqual(prev, { v: 1 });
assert.equal(stack.canRedo(), true);
});
test('redo 恢复被撤销的状态', () => {
const stack = new SnapshotUndoStack<{ v: number }>();
stack.push({ v: 1 });
const prev = stack.undo({ v: 2 })!;
const next = stack.redo(prev);
assert.deepEqual(next, { v: 2 });
});
test('快照深拷贝:外部修改不影响历史', () => {
const stack = new SnapshotUndoStack<{ v: number }>();
const s = { v: 1 };
stack.push(s);
s.v = 99;
assert.deepEqual(stack.undo({ v: 2 }), { v: 1 });
});
test('新 push 清空 redo', () => {
const stack = new SnapshotUndoStack<{ v: number }>();
stack.push({ v: 1 });
stack.undo({ v: 2 });
assert.equal(stack.canRedo(), true);
stack.push({ v: 3 });
assert.equal(stack.canRedo(), false);
assert.deepEqual(stack.undo({ v: 4 }), { v: 3 });
});
本机实测(Node v26.5.0,node --test test/09-3-node-graph-undo-layout.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。
前两条钉分层分列与跨层节点。第三条钉同层顺序。第四条钉快照深拷贝。第五、六条钉 undo 恢复与新 push 清 redo。
小结
- 自动布局 = 拓扑深度分列 + 同层排布。
- 快照撤销栈让布局与移动都能任意回退。
- push 清空 redo,语义与编辑器一致。
- 节点图通用架构章齐了:模型、求值、布局。
阅读导航:上一节:图求值:编译与执行 · 下一节:节点图材质:从图到着色参数 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。