KeyboardManager.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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(id: string,
  27. callback: ((event: KeyboardEvent) => void) | null, priority?: number) {
  28. if (!eventAdded) {
  29. eventAdded = true
  30. document.addEventListener('keydown', (evt: KeyboardEvent) => { keyDownHandler(evt) })
  31. }
  32. const listener = listeners.find(l => l.id === id)
  33. if (listener) {
  34. return
  35. }
  36. listeners.push({ id, callback, priority: priority || 0 })
  37. }
  38. static onEnter(id: string, callback: (evt: KeyboardEvent) => void, priority?: number) {
  39. this.onKeyDown(`${id}-enter`, evt => {
  40. if (evt.keyCode === 13) {
  41. callback(evt)
  42. }
  43. }, priority)
  44. }
  45. static onEsc(id: string, callback: (evt: KeyboardEvent) => void, priority?: number) {
  46. this.onKeyDown(`${id}-esc`, evt => {
  47. if (evt.keyCode === 27) {
  48. callback(evt)
  49. }
  50. }, priority)
  51. }
  52. static removeKeyDown(id: string) {
  53. listeners = listeners.filter(l => l.id !== id && l.id !== `${id}-enter` && l.id !== `${id}-esc`)
  54. }
  55. }