dash14 / v-network-graph

An interactive network graph visualization component for Vue 3
https://dash14.github.io/v-network-graph/
MIT License
485 stars 44 forks source link

Keyboard events #62

Closed Mamiglia closed 2 years ago

Mamiglia commented 2 years ago

I did some tests, and it appears that keyboard events doesn't bubble out of the graph component, am I wrong?

For instance I would like to delete a node whenever the user presses 'delete', but using @keyup / @keypress / @keydown seems useless

Is this a bug? Thanks in advance

dash14 commented 2 years ago

Hi @Mamiglia, v-network-graph does not handle any keyboard events. And, browsers do not fire key events on any elements that are not input controls (<div>, <span>, etc.) normally. To fire key events on these elements (including v-network-graph), specify the tabindex attribute on the element.

An example of firing a key event is shown below.

<script setup lang="ts">
import { defineConfigs, Edges, Nodes } from "v-network-graph";

const nodes: Nodes = {
  node0: { name: "Node 0" },
  node1: { name: "Node 1" },
  node2: { name: "Node 2" },
  node3: { name: "Node 3" },
};

const edges: Edges = {
  edge1: { source: "node0", target: "node1" },
  edge2: { source: "node1", target: "node2" },
  edge3: { source: "node2", target: "node3" },
};

const configs = defineConfigs({
  node: {
    selectable: true,
  },
});

function keydown(event: KeyboardEvent) {
  console.log("keydown", event);
}
function keyup(event: KeyboardEvent) {
  console.log("keyup", event);
}
function keypress(event: KeyboardEvent) {
  console.log("keypress", event);
}
</script>

<template>
  <div class="graph">
    <v-network-graph
      tabindex="0"
      :nodes="nodes"
      :edges="edges"
      :configs="configs"
      @keydown="keydown"
      @keyup="keyup"
      @keypress="keypress"
    />
  </div>
</template>

<style scoped lang="scss">
.graph {
  border: 1px solid #888;
  width: 600px;
  height: 400px;
  margin: 0 auto;
}
.v-network-graph[tabindex] {
  outline: none;
}
</style>
Mamiglia commented 2 years ago

I'm really sorry for for asking such a basic question, I thought it had something to do with the library, instead it was plain DOM knowledge.

Thank you again for your help