Skip to content
  1. Examples

Custom selection

This example demonstrates the implementation of a new selection mechanism based on capturing events on nodes. Left-clicking a node sets it as the selection, right-clicking adds to it and left clicking the background clears the selection.

js
import Ogma from '@linkurious/ogma';

// Initialize Ogma
const ogma = new Ogma({
  container: 'graph-container',
  // Deactivate the default selection mode.
  options: {
    interactions: {
      selection: {
        enabled: false
      }
    }
  }
});

// Or deactivate the default selection mode dynamically
// ogma.setOptions({ interactions: { selection: { enabled: false }} });

// Define a new selection mechanism

ogma.events.on('click', event => {
  const button = event.button,
    target = event.target;

  if (!target) {
    // If no node/edge is clicked, clear the selection regardless of the button used

    ogma.clearSelection();
    console.log('selection cleared');
  } else if (button === 'left') {
    // If a node or edge is left clicked, we clear the selection and set the clicked node/edge as the selection

    ogma.clearSelection();
    target.setSelected(true);

    console.log('selection set to: ', ogma.getSelectedNodes().getId().join());
  } else if (button === 'right') {
    // If a node or edge is right clicked, we add it to the selection

    target.setSelected(true);
    console.log('selection expanded: ', ogma.getSelectedNodes().getId().join());
  }
});

// generate and set random graph
ogma.generate
  .random({ nodes: 10, edges: 10 })
  .then(graph => ogma.setGraph(graph))
  // for the nodes to be well apart and visible
  .then(() => ogma.layouts.grid({ duration: 0 }))
  .then(() => ogma.view.locateGraph());
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 src="index.js"></script>
  </body>
</html>
css
#graph-container {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
  margin: 0;
  overflow: hidden;
}