keyboard_handler.js 2.0 KB

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