41 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-12-30 23:50:15 +01:00
import dagre from 'dagre'
2024-12-31 13:55:42 +01:00
import type {Edge, Node} from '@xyflow/react'
import { Position} from '@xyflow/react'
2024-08-16 13:56:52 +02:00
2024-12-30 23:50:15 +01:00
export const getLayoutedElements = (nodes: Node[], edges: Edge[], direction = 'TB') => {
2024-08-22 00:56:58 +02:00
const dagreGraph = new dagre.graphlib.Graph()
dagreGraph.setDefaultEdgeLabel(() => ({}))
2024-08-16 13:56:52 +02:00
2024-08-22 00:56:58 +02:00
const nodeWidth = 172
const nodeHeight = 200
2024-08-16 13:56:52 +02:00
2024-12-30 23:50:15 +01:00
const isHorizontal = direction === 'LR'
dagreGraph.setGraph({rankdir: direction})
2024-08-16 13:56:52 +02:00
2024-12-30 23:50:15 +01:00
nodes.forEach(node => {
dagreGraph.setNode(node.id, {width: nodeWidth, height: nodeHeight})
})
2024-08-16 13:56:52 +02:00
2024-12-30 23:50:15 +01:00
edges.forEach(edge => {
dagreGraph.setEdge(edge.source, edge.target)
})
2024-08-16 13:56:52 +02:00
2024-12-30 23:50:15 +01:00
dagre.layout(dagreGraph)
2024-08-16 13:56:52 +02:00
2024-12-30 23:50:15 +01:00
const newNodes: Node[] = nodes.map(node => {
2024-08-16 13:56:52 +02:00
const nodeWithPosition = dagreGraph.node(node.id)
return {
...node,
2024-12-30 23:50:15 +01:00
targetPosition: isHorizontal ? Position.Left : Position.Top,
sourcePosition: isHorizontal ? Position.Right : Position.Bottom,
2024-08-16 13:56:52 +02:00
position: {
x: nodeWithPosition.x - nodeWidth / 2,
y: nodeWithPosition.y - nodeHeight / 2
2024-12-30 23:50:15 +01:00
}
}
})
2024-08-16 13:56:52 +02:00
2024-12-30 23:50:15 +01:00
return {nodes: newNodes, edges}
}