All versions of this documentation
X

Node collapsing


Open in a new window.
          <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link href="fonts/font-awesome/css/font-awesome.min.css" rel="stylesheet">
  <script src="../build/ogma.min.js"></script>
  <style>
    #graph-container { top: 0; bottom: 0; left: 0; right: 0; position: absolute; margin: 0; overflow: hidden; }
    button { position: absolute; top:10px; left: 10px; }
  </style>
</head>
<body>
<div id="graph-container"></div>
<button id="btn" onclick="toggle()">Collapse</button>
</body>
<script>
  'use strict';

  var ogma = new Ogma({
    container: 'graph-container',
    renderer: 'canvas',
    graph: {
      nodes: [
        {id: 0, data: {type: 'person', name: 'John Smith'}, attributes: {x: 0, y: 0}},
        {id: 1, data: {type: 'company', name: 'Proton Brews'}, attributes: {x: 30, y: -20}},
        {id: 2, data: {type: 'building', name: '211 Golden Star Rd'}, attributes: {x: 60, y: 0}}
      ],
      edges: [
        {id: 0, source: 0, target: 1, data: {type: 'employee_of'}},
        {id: 1, source: 1, target: 2, data: {type: 'located_at'}}
      ]
    }
  });

  var ICONS = {
    person: '\uf007',
    company: '\uf155',
    building: '\uf1ad'
  };

  var COLORS = {
    person: 'orange',
    company: 'dodgerblue',
    building: 'green'
  };

  ogma.styles.addRule({
    nodeAttributes: {
      color: function(node) {
        return COLORS[node.getData('type')];
      },
      text: function(node) {
        return node.getData('name')
      },
      icon: {
        content: function(node) {
          return ICONS[node.getData('type')];
        },
        font: 'FontAwesome'
      }
    },
    edgeAttributes: {
      shape: 'arrow',
      text: function(edge) {
        return edge.getData('type')
      }
    }
  });

  var button = document.getElementById('btn');
  var transformation = null;

  function enableButton() {
    button.disabled = false;
    button.textContent = button.textContent === 'Collapse' ? 'Undo' : 'Collapse';
  }

  function toggle() {
    if (transformation) {
      transformation.destroy({duration: 500}).then(enableButton);
      button.disabled = true;
      transformation = null;
    } else {
      transformation = ogma.transformations.addNodeCollapsing({
        selector: function(node) {
          return node.getData('type') === 'company';
        },
        edgeGenerator: function(hiddenNode) {
          console.log('generating edge from node', hiddenNode.getId());

          return {data: {type: 'works_at'}};
        },
        duration: 500
      });
      button.disabled = true;
      transformation.whenApplied().then(enableButton);
    }
  }
</script>
</html>