keyboard_handler.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. }
  17. event.preventDefault();
  18. this.queue.push(key);
  19. for (let combination in this.shortcuts) {
  20. let keys = combination.split(" ");
  21. if (keys.every((value, index) => value === this.queue[index])) {
  22. this.queue = [];
  23. this.shortcuts[combination](event);
  24. return;
  25. }
  26. if (keys.length === 1 && key === keys[0]) {
  27. this.queue = [];
  28. this.shortcuts[combination](event);
  29. return;
  30. }
  31. }
  32. if (this.queue.length >= 2) {
  33. this.queue = [];
  34. }
  35. };
  36. }
  37. isEventIgnored(event, key) {
  38. return event.target.tagName === "INPUT" ||
  39. event.target.tagName === "TEXTAREA" ||
  40. (this.queue.length < 1 && !this.triggers.includes(key));
  41. }
  42. isModifierKeyDown(event) {
  43. return event.getModifierState("Control") || event.getModifierState("Alt") || event.getModifierState("Meta");
  44. }
  45. getKey(event) {
  46. const mapping = {
  47. 'Esc': 'Escape',
  48. 'Up': 'ArrowUp',
  49. 'Down': 'ArrowDown',
  50. 'Left': 'ArrowLeft',
  51. 'Right': 'ArrowRight'
  52. };
  53. for (let key in mapping) {
  54. if (mapping.hasOwnProperty(key) && key === event.key) {
  55. return mapping[key];
  56. }
  57. }
  58. return event.key;
  59. }
  60. }