Construct a tree
JointJS+ provides a constructTree
plugin that enables the ability to construct a tree
from a JSON object.
Installation​
Access constructTree
via the graphUtils
namespace.
import { shapes, graphUtils } from '@joint/plus';
const cells = graphUtils.constructTree(
{
name: 'my top',
children: [{
name: 'my child 1'
}, {
name: 'my child 2'
}]
},
{
makeElement: function(node) {
return new shapes.standard.Rectangle({
size: { width: 80, height: 30 },
attrs: { label: { text: node.name }}
});
},
makeLink: function(parentElement, childElement) {
return new shapes.standard.Link({
source: { id: parentElement.id },
target: { id: childElement.id }
});
}
}
);
graph.addCells(cells);
There is also a UMD version available
Include joint.graphUtils.js
in your HTML:
<script src="joint.js"></script>
<script src="joint.graphUtils.js"></script>
Access constructTree
through the joint.graphUtils
namespace:
const cells = joint.graphUtils.constructTree(
{
name: 'my top',
children: [{
name: 'my child 1'
}, {
name: 'my child 2'
}]
},
{
makeElement: (node) => {
return new joint.shapes.standard.Rectangle({
size: { width: 80, height: 30 },
attrs: { label: { text: node.name }}
});
},
makeLink: (parentElement, childElement) => {
return new joint.shapes.standard.Link({
source: { id: parentElement.id },
target: { id: childElement.id }
});
}
}
);
graph.addCells(cells);
How does constructTree work?​
Construct a tree from a JSON object (parent
, i.e. the top level node). This method returns an array of cells
(elements and links) that constitute the tree. The parent
parameter must be a JSON of the form:
{
name: 'my label',
children: [ { name: 'my label 2', children: [...] }, ...]
}
config.children
is the property specifying the children array (the default is 'children'
). If config.children
is a
function, it will be called with the current node as an argument, and must return an array of its child nodes.
config.makeElement()
is a function that is passed the current tree node, and returns a JointJS element for it.
config.makeLink()
is a function that is passed a parent and child nodes, and returns a JointJS link for the edge.
Example of an adjacency list​
import { shapes, graphUtils } from '@joint/plus';
const adjacencyList = {
'a': ['b', 'c'],
'b': ['d', 'e'],
'c': [],
'd': ['f'],
'e': [],
'f': []
};
const cells = graphUtils.constructTree(
'a', // root
{
makeElement: (name) => {
return new shapes.standard.Rectangle({
size: { width: 80, height: 30 },
attrs: { label: { text: name }}
});
},
makeLink: (parentElement, childElement) => {
return new shapes.standard.Link({
source: { id: parentElement.id },
target: { id: childElement.id }
});
},
children: (name) => adjacencyList[name]
}
);
graph.addCells(cells);