Skip to content
  1. Examples

Select

This example shows how to use the nodesSelected, edgesSelected, nodesUnselected and edgesUnselected events to listen to the selection of nodes and edges in the graph.

Left click on a node or edge to select it. Hold "ctrl" to select multiple nodes/edges at the same time.

ts
import Ogma from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container',
  options: {
    interactions: {
      // disable the selection completely
      // selection: { enabled: false }
    }
  }
});

const printSelectionStatus = () => {
  const status = document.getElementById('status')!;
  const nodes = ogma.getSelectedNodes();
  const edges = ogma.getSelectedEdges();
  status.innerHTML = '';
  if (nodes.size > 0) {
    status.innerHTML += `<p><strong>nodes:</strong> ${nodes.getId().join(',')}</p>`;
  }
  if (edges.size > 0) {
    status.innerHTML += `<p><strong>edges:</strong> ${ogma.getSelectedEdges().getId().join(',')}</p>`;
  }
  if (nodes.size === 0 && edges.size === 0) {
    status.innerHTML = '<p>Nothing selected</p>';
  }
};
printSelectionStatus();

ogma.events
  .on('nodesSelected', selection => {
    const nodes = selection.nodes;
    console.log('nodes', nodes.getId().join(), 'added to selection');
    printSelectionStatus();
  })
  .on('edgesSelected', selection => {
    const edges = selection.edges;
    console.log('edges', edges.getId().join(), 'added to selection');
    printSelectionStatus();
  })
  .on('nodesUnselected', selection => {
    const nodes = selection.nodes;
    console.log('nodes', nodes.getId().join(), 'removed from selection');
    printSelectionStatus();
  })
  .on('edgesUnselected', selection => {
    const edges = selection.edges;
    console.log('edges', edges.getId().join(), 'removed from selection');
    printSelectionStatus();
  });

// Generate a random graph and assign it to Ogma.
ogma.generate
  .random({ nodes: 15, edges: 30 })
  .then(g => ogma.setGraph(g))
  .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>
    <div class="info" id="status"></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;
}

.info {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.75);
  color: #ffffff;
  font-family: Georgia, 'Times New Roman', Times, serif;
  border-radius: 5px;
}