借助 dagre 算法将布局好的页面根据页面尺寸再调整
import dagre from 'dagre';
export default function autoLayout(data, ranksep = 100, canvasWidth = 800, canvasHeight = 350) {
const g = new dagre.graphlib.Graph();
// 设置边上的标签
g.setDefaultEdgeLabel(() => {
return {};
});
// 设置布局方式
g.setGraph({
rankdir: 'LR',
ranksep
});
// 设置节点id与尺寸
data.nodes.forEach(node => {
let width = node.size ? node.size[0] : 50;
let height = node.size ? node.size[0] : 50;
g.setNode(node.id, {width, height});
});
// 设置边的起始节点和终止节点
data.edges.forEach(edge => {
g.setEdge(edge.source, edge.target);
});
// 执行布局
dagre.layout(g);
let nodes = [];
for (const key in g._nodes) {
if (g._nodes[key]) {
nodes.push(g._nodes[key]);
}
}
// 拿到dagre布局后节点位置,计算后让布局居中
let nodeX = [];
let nodeY = [];
nodes.forEach(item => {
nodeX.push(item.x);
nodeY.push(item.y);
});
const xLen = (canvasWidth - (Math.max(...nodeX) - Math.min(...nodeX))) / 2;
const yLen = (canvasHeight - (Math.max(...nodeY) - Math.min(...nodeY))) / 2;
nodes.forEach((item, index) => {
data.nodes[index].x = item.x + xLen - 50;
data.nodes[index].y = item.y + yLen - 50;
});
return data;
};