chevron_right Demos chevron_right Tutorial: Graph Builder chevron_right 13 Tree Builder
12 Adjacency Graph Builder

Building a graph with TreeBuilder

In this tutorial step we show how to use TreeBuilder to build a graph from data, where nodes and their children are already available in a tree-like format.

The data

Consider the following data object, which represents a basic organization chart:

{
  position: 'Chief Executive Officer',
  name: 'Eric Joplin',
  colleagues: [
    {
      position: 'Chief Executive Assistant',
      name: 'Gary Roberts',
      colleagues: [
        { position: 'Senior Executive Assistant', name: 'Alexander Burns' },
        { position: 'Junior Executive Assistant', name: 'Linda Newland' }
      ]
    },
    {
      position: 'Vice President of Production',
      name: 'Amy Kain',
      colleagues: [
        { position: 'Production Supervisor', name: 'Kathy Maxwell' }
      ]
    }
  ]
}

Every data object can have an optional colleagues property. The colleagues property, if available, contains a list of the object’s children as data. The colleagues are of the same type as the data object itself:

export type OrgChartEntry = {
  position: string
  name: string
  colleagues?: OrgChartEntry[]
}

Building the graph

In the first step, we instantiate TreeBuilder and configure a TreeNodesSource:

const treeBuilder = new TreeBuilder(graph)

const rootNodesSource = treeBuilder.createRootNodesSource(nodesData, null)

In the second step, we configure a child NodesSource on the TreeNodesSource:

// the childDataProvider identifies the property of a node object that contains its child nodes
rootNodesSource.addChildNodesSource(
  (data) => data.colleagues,
  rootNodesSource
)

Note that we have used the rootNodesSource as the source for the colleagues recursively. The TreeBuilder makes sure no nodes or edges with the same id are created twice.

Finally, we add labels to the graph building process by providing a label binding for the NodesSource's NodeCreator.

rootNodesSource.nodeCreator.createLabelBinding({
  text: (dataItem) => dataItem.name
})
Note

TreeBuilder supports the same labeling functionality as the GraphBuilder.

See the Developer’s Guide section about TreeBuilder for a deeper discussion of the TreeBuilder type.

Note

Please have a look in this tutorial step’s demo code in tree-graph-building.ts and play around with the different ways to import business data.