import React, { useEffect, useState } from 'react'; import ReactFlow, { ReactFlowProvider, addEdge, removeElements, Controls, isNode } from 'react-flow-renderer'; import dagre from 'dagre'; import initialElements from './initial-elements'; import './layouting.css'; const dagreGraph = new dagre.graphlib.Graph(); dagreGraph.setDefaultEdgeLabel(() => ({})); const LayoutFlow = () => { const [elements, setElements] = useState(initialElements); const onConnect = (params) => setElements((els) => addEdge(params, els)); const onElementsRemove = (elementsToRemove) => setElements((els) => removeElements(elementsToRemove, els)); const onLayout = (direction) => { const isHorizontal = direction === 'LR'; dagreGraph.setGraph({ rankdir: direction }); elements.forEach((el) => { if (isNode(el)) { dagreGraph.setNode(el.id, { width: 150, height: 50 }); } else { dagreGraph.setEdge(el.source, el.target); } }); dagre.layout(dagreGraph); const layoutedElements = elements.map((el) => { if (isNode(el)) { const nodeWithPosition = dagreGraph.node(el.id); el.targetPosition = isHorizontal ? 'left' : 'top'; el.sourcePosition = isHorizontal ? 'right' : 'bottom'; // we need to pass a slighltiy different position in order to notify react flow about the change // @TODO how can we change the position handling so that we dont need this hack? el.position = { x: nodeWithPosition.x + Math.random() / 1000, y: nodeWithPosition.y }; } return el; }); setElements(layoutedElements); }; useEffect(() => { onLayout('TB'); }, []); return (
); }; export default LayoutFlow;