documentationfor yFiles for HTML 2.6

TreeBuilder

The TreeBuilder creates trees from a tree-shaped data model. Each node data item may define its child nodes. Edges are created implicitly, so there is no separate edge data collection. TreeBuilder supports the creation of a forest which is a set of tree structures that are part of the same graph.

In the following example the tree consists of alternating levels of red and blue nodes. The root nodes of the trees are all red nodes.

/**
 * @typedef {Object} RedNode
 * @property {Array.<BlueNode>} children
 */

/**
 * @typedef {Object} BlueNode
 * @property {Array.<RedNode>} children
 */
interface RedNode {
  children: BlueNode[]
}

interface BlueNode {
  children: RedNode[]
}

To bind the tree data to the TreeBuilder, start by creating a root nodes source.

const treeBuilder = new TreeBuilder()

const treeData = getTreeData()
// create a nodes source for the root(s) (red nodes) of the tree
const redNodesSource = treeBuilder.createRootNodesSource(treeData)

This root nodes source is responsible for creating all red roots of the trees and is bound to the entire tree data.

In order to create a child level with blue nodes, create a new nodes source as child nodes source of the root nodes source:

// create a nodes source for children of red nodes as child source of redNodesSource
const blueNodesSource = redNodesSource.createChildNodesSource((redNodeDataItem) => redNodeDataItem.children)

This time, no data collection is passed. Instead, a childDataProvider returns the child data collection (consisting of only blue nodes) for each red node. The TreeBuilder will now create an edge between each parent (red) node and child (blue) node.

To recursively create the whole tree, the redNodesSource is added as child nodes source of blueNodesSource again:

// tie the knot
blueNodesSource.addChildNodesSource((blueNodeDataItem) => blueNodeDataItem.children, redNodesSource)

It is possible to create multiple nodes sources from different data and with different stylings. The visual appearance, locations and labels of the nodes can be customized via the NodeCreator<TDataItem>. The parentEdgeCreator defines the styling of an edge between a node and its parent. See the Configuring the Visual Appearance of Graph Items section for further details.

It is also possible to add group nodes from group data. Groups may appear both at the top level as unconnected nodes as well as within the tree. See the createRootGroupNodesSource<TDataItem> and the Grouping section for details.

After the sources and creators have been configured, a graph can be created and later updated if the business data has changed.

Tutorial Demo Code

The demos Simple Graph Builder and Tree Builder show how to use a TreeBuilder to build a tree from user data. See the multistep GraphBuilder Tutorial for in-depth explanations of the various concepts.