Skip to content
  1. Examples

Selection API

This example shows how to use the getSelectedNodes, getSelectedEdges, getNonSelectedNodes and getNonSelectedEdges methods to get the selected and non-selected nodes and edges in the graph.

ts
import Ogma from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container',
  options: {
    interactions: {
      selection: {
        // Override the key to hold to select multiple
        // elements (by default, 'ctrl' key is used).
        multiSelectionKey: 'alt'
      }
    }
  }
});
// Define a style for selected nodes
ogma.styles.setSelectedNodeAttributes({ color: 'red' });

// Generate a random graph and assign it to Ogma.
ogma.generate
  .random({ nodes: 10, edges: 15 })
  .then(graph => {
    // Add a property 'age' with a random value between 0 and 100
    graph.nodes.forEach(n => {
      n.data = {
        age: Math.random() * 100
      };
    });

    return ogma.setGraph(graph);
  })
  .then(() => ogma.view.locateGraph())
  .then(() => {
    // Select three nodes
    ogma.getNodes(['0', '1', '2']).setSelected(true);

    // Add their neighbors to the current selection
    // ogma.getSelectedNodes().getAdjacentNodes().setSelected(true);

    // Deselect a node
    // ogma.getNode('0').setSelected(false);

    // Inverse selection
    const selected = ogma.getSelectedNodes();
    const not_selected = ogma.getNonSelectedNodes();
    not_selected.setSelected(true);
    selected.setSelected(false);

    // Select every node for which data.age > 50.
    ogma.clearSelection();
    ogma
      .getNodes()
      .filter(node => {
        return node.getData('age') >= 50;
      })
      .setSelected(true);

    // Clear the selection
    // ogma.clearSelection();
  });
html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />

    <link type="text/css" rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div id="graph-container"></div>
    <script type="module" src="index.ts"></script>
  </body>
</html>
css
#graph-container {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
  margin: 0;
  overflow: hidden;
}