keyboard_handler.js 2.0 KB

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