useLayoutSupport
A React hook that provides helper function that prepare the data for the layout algorithm and retrieve the result.
This hook is tailored for users interested in delving into yFiles for HTML, exploring various layout algorithms, and crafting advanced layout code for their applications.
const edgeTypes = {
default: PolylineEdge
}
const nodeTypes = {
default: MultiHandleNode
}
const LayoutFlow = () => {
const [nodes, setNodes] = useNodesState(initialNodes)
const [edges, setEdges] = useEdgesState(initialEdges)
const { fitView, getZoom } = useReactFlow()
const { buildGraph, transferLayout } = useLayoutSupport()
const runLayout = useCallback(() => {
// create a graph from data
const graph = buildGraph(nodes, edges, getZoom())
// configure a layout
const hierarchicalLayout = new HierarchicalLayout()
const hierarchicalLayoutData = new HierarchicalLayoutData({
ports: {
sourcePortCandidates: (edge: IEdge) => {
const candidates = new EdgePortCandidates()
if (edge.tag.id === 'e0') {
candidates.addFreeCandidate(PortSides.LEFT)
} else if (edge.tag.id === 'e1') {
candidates.addFreeCandidate(PortSides.RIGHT)
} else {
candidates.addFreeCandidate(PortSides.START_IN_FLOW)
}
return candidates
}
}
})
// apply the layout
graph.applyLayout(hierarchicalLayout, hierarchicalLayoutData)
// transfer the new coordinates to the data
const { arrangedEdges, arrangedNodes } = transferLayout(graph)
setNodes(arrangedNodes)
setEdges(arrangedEdges)
// fit the graph into the view
window.requestAnimationFrame(() => fitView())
}, [nodes, edges, buildGraph, transferLayout, setNodes, setEdges, fitView, getZoom])
return (
<ReactFlow
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
>
<Panel position="top-right">
<button onClick={runLayout}>Layout</button>
</Panel>
</ReactFlow>
)
}
export default function Flow() {
return (
<ReactFlowProvider>
<LayoutFlow />
</ReactFlowProvider>
)
}
Parameters
Name | Description | Type |
---|---|---|
reactFlowRef? | An optional reference to the React Flow element. This reference is particularly useful in scenarios where there are multiple React Flow elements on the same page or when the flow is encapsulated within a closed shadow DOM. | RefObject<HTMLElement> |
Returns
Type | Description |
---|---|
LayoutSupport | Returns functions to transfer the data into a graph and get the layout information from the graph. |