25 lines
865 B
JavaScript
25 lines
865 B
JavaScript
import dagre from "dagre";
|
||
|
||
export const NODE_W = 150;
|
||
export const NODE_H = 54;
|
||
|
||
/**
|
||
* dagre 自动布局,返回带 position 的 nodes
|
||
* @param {Array} nodes Vue Flow 节点(id 必须为字符串)
|
||
* @param {Array} edges Vue Flow 边
|
||
* @param {Object} opts { rankdir: TB|BT|LR|RL, nodeW, nodeH }
|
||
*/
|
||
export function layoutGraph(nodes, edges, opts = {}) {
|
||
const { rankdir = "TB", nodeW = NODE_W, nodeH = NODE_H } = opts;
|
||
const g = new dagre.graphlib.Graph();
|
||
g.setGraph({ rankdir, nodesep: 30, ranksep: 56, marginx: 20, marginy: 20 });
|
||
g.setDefaultEdgeLabel(() => ({}));
|
||
nodes.forEach((n) => g.setNode(n.id, { width: nodeW, height: nodeH }));
|
||
edges.forEach((e) => g.setEdge(e.source, e.target));
|
||
dagre.layout(g);
|
||
return nodes.map((n) => {
|
||
const gn = g.node(n.id);
|
||
return { ...n, position: { x: gn.x - nodeW / 2, y: gn.y - nodeH / 2 } };
|
||
});
|
||
}
|