keyboard_handler.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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.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. getKey(event) {
  38. const mapping = {
  39. 'Esc': 'Escape',
  40. 'Up': 'ArrowUp',
  41. 'Down': 'ArrowDown',
  42. 'Left': 'ArrowLeft',
  43. 'Right': 'ArrowRight'
  44. };
  45. for (let key in mapping) {
  46. if (mapping.hasOwnProperty(key) && key === event.key) {
  47. return mapping[key];
  48. }
  49. }
  50. return event.key;
  51. }
  52. }