All versions of this documentation
X

Hierarchical with custom root

Click a node to make it top of the hierarchical layout, or click an edge to make its extremities the top of the layout. Use the direction control on the right to rotate the layout.

Open in a new window.
          <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../build/ogma.min.js"></script>
  <style>
    #graph-container { top: 0; bottom: 0; left: 0; right: 0; position: absolute; margin: 0; overflow: hidden; }
    #directionMode-wrapper {
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 400;
      background: white;
      padding: 10px;
    }

    .control-bar {
      font-family: Helvetica, Arial, sans-serif;
      box-shadow: 0 1px 5px rgba(0,0,0,0.65);
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <div id="graph-container"></div>
  <div id="directionMode-wrapper" class="control-bar">
    <label>Change Direction:</label>
    <select name="directionMode" id="directionMode" onChange="runWithDirection()">
        <option value="TB">Top Down</option>
        <option value="BT">Bottom Up</option>
        <option value="LR">Left to Right</option>
        <option value="RL">Right to Left</option>
    </select>
  </div>

<script>
'use strict';
var ogma = new Ogma({
  container: 'graph-container',
});

var defaultLayoutOptions = {
  direction: 'TB',           // Direction of the layout. Can be TB, BT, LR, or RL,
                            // where T = top, B = bottom, L = left, and R = right.
  duration: 300,           // Duration of the animation
  nodeDistance:  50,       // Number of pixels that separate nodes horizontally in the layout.
  levelDistance: 50,       // Number of pixels between each layer in the layout.
};

ogma.generate.balancedTree({
  children : 2,
  height: 5
}).then(function(graph) {

  ogma.events.onClick(function (evt) {
    var target = evt.target;
    var roots = [];

    // If the user clicked a node set it as root,
    // otherwise pick the link ends and make them roots
    if (target){
      if(target.isNode) {
        roots.push(target.getId());
      } else {
        roots = target.getExtremities();
      }
    }

    runWithDirection(roots);
  });


  return ogma.setGraph(graph);

}).then(function(){
  ogma.getNode(0).setSelected(true);
  runWithDirection();

});

function runLayout(options){
  // Run layout
  ogma.layouts.hierarchical(options)
  .then(function() {
    console.log('done');
    ogma.view.locateGraph({
      easing: 'linear',
      duration: 300
    });
  });
}

function runWithDirection(roots){
  // create fresh new options
  var newOptions = {};
  for( var prop in defaultLayoutOptions){
    newOptions[prop] = defaultLayoutOptions[prop];
  }
  // pass the roots to the layout
  newOptions.roots = roots;
  // now add the chosen one
  newOptions.direction = document.getElementById('directionMode').value;
  runLayout(newOptions);
}

</script>
</body>
</html>