KeyboardManager.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. Copyright (C) 2017 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. let eventAdded = false
  15. let listeners: any[] = []
  16. const keyDownHandler = (evt: KeyboardEvent) => {
  17. let maxPriority = 0
  18. listeners.forEach(l => { maxPriority = Math.max(l.priority, maxPriority) })
  19. const prioritizedListeners = listeners.filter(l => l.priority === maxPriority)
  20. prioritizedListeners.forEach(listener => {
  21. if (listener.callback && !window.handlingEnterKey) listener.callback(evt)
  22. })
  23. }
  24. export default class KeyboardManager {
  25. static eventAdded = false
  26. static onKeyDown(
  27. id: string,
  28. callback: ((event: KeyboardEvent) => void) | null,
  29. priority?: number,
  30. ) {
  31. if (!eventAdded) {
  32. eventAdded = true
  33. document.addEventListener('keydown', (evt: KeyboardEvent) => { keyDownHandler(evt) })
  34. }
  35. const listener = listeners.find(l => l.id === id)
  36. if (listener) {
  37. return
  38. }
  39. listeners.push({ id, callback, priority: priority || 0 })
  40. }
  41. static onEnter(id: string, callback: (evt: KeyboardEvent) => void, priority?: number) {
  42. this.onKeyDown(`${id}-enter`, evt => {
  43. if (evt.key === 'Enter') {
  44. callback(evt)
  45. }
  46. }, priority)
  47. }
  48. static onEsc(id: string, callback: (evt: KeyboardEvent) => void, priority?: number) {
  49. this.onKeyDown(`${id}-esc`, evt => {
  50. if (evt.key === 'Escape') {
  51. callback(evt)
  52. }
  53. }, priority)
  54. }
  55. static removeKeyDown(id: string) {
  56. listeners = listeners.filter(l => l.id !== id && l.id !== `${id}-enter` && l.id !== `${id}-esc`)
  57. }
  58. }