Skip to content
  1. Examples

Keyboard interactions

This example shows how to use the keyboard module to bind actions to key combinations. In this example, we bind two shortcuts:

  • Press ALT + A to add a node to the graph
  • Press ALT + R to remove a node from the graph
ts
import Ogma from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container'
});

let addCounter = 0,
  removeCounter = 0;

const addNode = () => {
  ogma.addNode({
    id: addCounter++,
    attributes: { x: Math.random() * 100, y: Math.random() * 100 }
  });
  console.log('Node added');
  ogma.view.locateGraph();
};

const removeNode = () => {
  if (removeCounter < addCounter) {
    ogma.removeNode(removeCounter++);
    console.log('Node removed');
  }
};

ogma.events.onKeyPress('alt a', addNode);
ogma.events.onKeyPress('alt r', removeNode);

for (let i = 0; i < 5; ++i) {
  addNode();
}
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;
}