Elkjs Tree
import type { Edge, Node } from '@xyflow/vue';
import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk-api';
import { Position } from '@xyflow/vue';
import ELK from 'elkjs/lib/elk.bundled';
export function useElkjsLayout() {
const elk = new ELK();
return async (
nodes: Node[],
edges: Edge[],
options: Record<string, string> = {},
): Promise<{ nodes: Node[]; edges: Edge[] }> => {
const isHorizontal = options['elk.direction'] === 'RIGHT';
const graph: ElkNode = {
id: 'root',
layoutOptions: options,
children: nodes.map((node) => ({
...node,
// adjust the target/source handle positions to the layout direction
targetPosition: isHorizontal ? Position.Left : Position.Top,
sourcePosition: isHorizontal ? Position.Right : Position.Bottom,
// hardcode a width/height for elk to lay out with
width: 150,
height: 50,
})) as unknown as ElkNode[],
edges: edges as unknown as ElkExtendedEdge[],
};
const layoutedGraph = await elk.layout(graph);
return {
nodes: (layoutedGraph.children ?? []).map((node) => ({
...(node as unknown as Node),
// Vue Flow expects a `position` property instead of elk's `x`/`y`
position: { x: node.x ?? 0, y: node.y ?? 0 },
})),
edges: (layoutedGraph.edges ?? []) as unknown as Edge[],
};
};
}Last updated on