factory_web/src/components/flow/dagreLayout.js

25 lines
865 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 } };
});
}