keyboard_handler.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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)) {
  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.execute(combination, event);
  20. return;
  21. }
  22. if (keys.length === 1 && key === keys[0]) {
  23. this.execute(combination, event);
  24. return;
  25. }
  26. }
  27. if (this.queue.length >= 2) {
  28. this.queue = [];
  29. }
  30. };
  31. }
  32. execute(combination, event) {
  33. event.preventDefault();
  34. event.stopPropagation();
  35. this.queue = [];
  36. this.shortcuts[combination](event);
  37. }
  38. isEventIgnored(event) {
  39. return event.target.tagName === "INPUT" || event.target.tagName === "TEXTAREA";
  40. }
  41. getKey(event) {
  42. const mapping = {
  43. 'Esc': 'Escape',
  44. 'Up': 'ArrowUp',
  45. 'Down': 'ArrowDown',
  46. 'Left': 'ArrowLeft',
  47. 'Right': 'ArrowRight'
  48. };
  49. for (let key in mapping) {
  50. if (mapping.hasOwnProperty(key) && key === event.key) {
  51. return mapping[key];
  52. }
  53. }
  54. return event.key;
  55. }
  56. }