keyboard_handler.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. class KeyboardHandler {
  2. constructor() {
  3. this.queue = [];
  4. this.shortcuts = {};
  5. this.triggers = [];
  6. }
  7. on(combination, callback) {
  8. this.shortcuts[combination] = callback;
  9. this.triggers.push(combination.split(" ")[0]);
  10. }
  11. listen() {
  12. document.onkeydown = (event) => {
  13. let key = this.getKey(event);
  14. if (this.isEventIgnored(event, key) || this.isModifierKeyDown(event)) {
  15. return;
  16. } else {
  17. event.preventDefault();
  18. }
  19. this.queue.push(key);
  20. for (let combination in this.shortcuts) {
  21. let keys = combination.split(" ");
  22. if (keys.every((value, index) => value === this.queue[index])) {
  23. this.queue = [];
  24. this.shortcuts[combination](event);
  25. return;
  26. }
  27. if (keys.length === 1 && key === keys[0]) {
  28. this.queue = [];
  29. this.shortcuts[combination](event);
  30. return;
  31. }
  32. }
  33. if (this.queue.length >= 2) {
  34. this.queue = [];
  35. }
  36. };
  37. }
  38. isEventIgnored(event, key) {
  39. return event.target.tagName === "INPUT" ||
  40. event.target.tagName === "TEXTAREA" ||
  41. (this.queue.length < 1 && !this.triggers.includes(key));
  42. }
  43. isModifierKeyDown(event) {
  44. return event.getModifierState("Control") || event.getModifierState("Alt") || event.getModifierState("Meta");
  45. }
  46. getKey(event) {
  47. const mapping = {
  48. 'Esc': 'Escape',
  49. 'Up': 'ArrowUp',
  50. 'Down': 'ArrowDown',
  51. 'Left': 'ArrowLeft',
  52. 'Right': 'ArrowRight'
  53. };
  54. for (let key in mapping) {
  55. if (mapping.hasOwnProperty(key) && key === event.key) {
  56. return mapping[key];
  57. }
  58. }
  59. return event.key;
  60. }
  61. }