Skip to main content

Tree layout

layout.TreeLayout is a layout algorithm for tree-like graphs. It's great for displaying org charts, mind maps, class hierarchies and other tree structures. The layout.TreeLayout is strong in combination with the TreeLayoutView component which implements drag&drop functionality useful when editing a tree structure.

Usage

To use tree layout create an object of layout.TreeLayout class passing your graph (object of type dia.Graph) as a parameter. Then you can just call the layout() method and the graph will be automatically laid out. It's important to note that the position of the root element of the tree will stay the same as it was before the layout. This allows you to move the tree to a position you want or have your tree be laid out around the root.

import { layout } from '@joint/plus';

const graphLayout = new layout.TreeLayout({
graph: graph,
parentGap: 20,
siblingGap: 20
});

// Root element position stays the same after the layout.
// In this demo, we assume the root is the first element.
const root = graph.getElements()[0].position(200, 200);

graphLayout.layout();

To control layout behavior, TreeLayout class constructor provides options parameter with multiple settings. You can look at the full list in our API.

Besides the constructor options, you can change the behavior of a layout process via special element attributes. For example, you can use margin attribute on the element to extend the area occupied by the element.

element.set({
direction: 'R',
size: { width: 100, height: 100 },
margin: 20
});
// as the `element` siblings are located above and under the element,
// it will in fact occupied an area of { width: 100, height: 140 }

Here is the small example with the tree layout in action:

note

The TreeLayout is meant to be used for tree graph structures only. Each node has a maximum of 1 parent, and there are no cycles. For generic graphs, you would need to use other layouts (DirectedGraph). You could also make the TreeLayout ignore the links that go back (with the filter option), and draw them as a curve for instance (a different style than other links, not affecting the position of other elements), or style the links with stubs as seen in the Links demo.

Stay in the know

Be where thousands of diagramming enthusiasts meet

Star us on GitHub