summaryrefslogtreecommitdiff
path: root/client/lib/keys.js
blob: 687517f57cba72d4f7d25dd98db39c62be9b02e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * Keyboard helper
 * @module lib/keys.js;
 */

const keys = {};
const key_numbers = {};
const letters = "zxcvbnmasdfghjklqwertyuiop";
const numbers = "1234567890";

let callback = function () {};

letters
  .toUpperCase()
  .split("")
  .map(function (k, i) {
    keys[k.charCodeAt(0)] = i;
  });

numbers.split("").map(function (k, i) {
  keys[k.charCodeAt(0)] = i + letters.length;
  key_numbers[k.charCodeAt(0)] = true;
});

window.addEventListener("keydown", keydown, true);
function keydown(e) {
  if (e.altKey || e.ctrlKey || e.metaKey) {
    e.stopPropagation();
    return;
  }
  if (
    document.activeElement instanceof HTMLInputElement &&
    e.keyCode in key_numbers
  ) {
    e.stopPropagation();
    return;
  }
  if (!(e.keyCode in keys)) return;
  var index = keys[e.keyCode];
  if (e.shiftKey) index += letters.length;
  callback(index);
}

function listen(fn) {
  callback = fn;
}

export default { listen };