🎉 JointJS has new documentation! ðŸ¥³

JointJS+ constructTree

graphUtils.constructTree


constructTree(parent, opt)

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: [...] }, ...]
}

opt.children is the property specifying the children array (default is 'children'). If opt.children is a function, it will be called with the current node as an argument and must return an array of its child nodes. opt.makeElement() is a function that is passed the current tree node and returns a JointJS element for it. opt.makeLink() is a function that is passed a parent and child nodes and returns a JointJS link for the edge. Example:

const cells = joint.graphUtils.constructTree(
    {
        name: 'my top',
        children: [{
            name: 'my child 1'
        }, {
            name: 'my child 2'
        }]
    },
    {
        makeElement: function(node) {
            return new joint.shapes.standard.Rectangle({
                size: { width: 80, height: 30 },
                attrs: { label: { text: node.name }}
            });
        },
        makeLink: function(parentElement, childElement) {
            return new joint.shapes.standard.Link({
                source: { id: parentElement.id },
                target: { id: childElement.id }
            });
        }
    }
);
graph.addCells(cells);

Example of an adjacency list:

const adjacencyList = {
  'a': ['b', 'c'],
  'b': ['d', 'e'],
  'c': [],
  'd': ['f'],
  'e': [],
  'f': []
};

const cells = joint.graphUtils.constructTree(
  'a', // root
  {
      makeElement: function(name) {
          return new joint.shapes.standard.Rectangle({
              size: { width: 80, height: 30 },
              attrs: { label: { text: name }}
          });
      },
      makeLink: function(parentElement, childElement) {
          return new joint.shapes.standard.Link({
              source: { id: parentElement.id },
              target: { id: childElement.id }
          });
      },
      children: (name) => adjacencyList[name]
  }
);
graph.addCells(cells);