43 lines
1.1 KiB
TypeScript
43 lines
1.1 KiB
TypeScript
![]() |
import { Edge, Node } from '@xyflow/react';
|
||
|
import dagre from 'dagre';
|
||
|
|
||
|
export const getLayoutedElements = (nodes: Node[], edges: Edge[], direction = 'LR') => {
|
||
|
const dagreGraph = new dagre.graphlib.Graph();
|
||
|
dagreGraph.setDefaultEdgeLabel(() => ({}));
|
||
|
|
||
|
const nodeWidth = 200;
|
||
|
const nodeHeight = 50;
|
||
|
|
||
|
dagreGraph.setGraph({
|
||
|
rankdir: direction,
|
||
|
nodesep: 80,
|
||
|
ranksep: 100
|
||
|
});
|
||
|
|
||
|
// 添加节点
|
||
|
nodes.forEach((node) => {
|
||
|
dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
|
||
|
});
|
||
|
|
||
|
// 添加边
|
||
|
edges.forEach((edge) => {
|
||
|
dagreGraph.setEdge(edge.source, edge.target);
|
||
|
});
|
||
|
|
||
|
// 计算布局
|
||
|
dagre.layout(dagreGraph);
|
||
|
|
||
|
// 获取新的节点位置
|
||
|
const layoutedNodes = nodes.map((node) => {
|
||
|
const nodeWithPosition = dagreGraph.node(node.id);
|
||
|
return {
|
||
|
...node,
|
||
|
position: {
|
||
|
x: nodeWithPosition.x - nodeWidth / 2,
|
||
|
y: nodeWithPosition.y - nodeHeight / 2,
|
||
|
},
|
||
|
};
|
||
|
});
|
||
|
|
||
|
return { nodes: layoutedNodes, edges };
|
||
|
};
|