keyboard_handler.js 1.7 KB

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