From 0a95900c555880b32936a97af02f78533d6a6e35 Mon Sep 17 00:00:00 2001 From: lagaffe <> Date: Sun, 19 Apr 2026 13:26:59 +0200 Subject: [PATCH] add class for keyboard events --- src/common/index.js | 1 + src/common/keyBoardEvents.js | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/common/keyBoardEvents.js diff --git a/src/common/index.js b/src/common/index.js index aaea758..a0a301e 100644 --- a/src/common/index.js +++ b/src/common/index.js @@ -1,3 +1,4 @@ export { backgroundLayout } from "./layouts"; export { makeDragable, makeUnDragable } from "./dragAndDrop"; export { getIntersection } from "./helpers"; +export { KeyBoardListener } from "./keyBoardEvents"; diff --git a/src/common/keyBoardEvents.js b/src/common/keyBoardEvents.js new file mode 100644 index 0000000..c8020df --- /dev/null +++ b/src/common/keyBoardEvents.js @@ -0,0 +1,46 @@ +export class KeyBoardListener { + static _listenersKeyUp = {}; + static _listenersKeyDown = {}; + static ready = false; + static _listenCount = 0; + static init() { + document.addEventListener("keydown", (event) => { + for (const listener of Object.values( + KeyBoardListener._listenersKeyDown, + )) { + listener(event); + } + }); + document.addEventListener("keyup", (event) => { + for (const listener of Object.values( + KeyBoardListener._listenersKeyUp, + )) { + listener(event); + } + }); + + KeyBoardListener.ready = true; + } + + /* return id used to remove the listener */ + static onKeyDown(callback) { + const id = KeyBoardListener._listenCount++; + KeyBoardListener._listenersKeyDown[id] = callback; + return id; + } + + static offKeyDown(id) { + delete KeyBoardListener._listenersKeyDown[id]; + } + + /* return id used to remove the listener */ + static onKeyUp(callback) { + const id = KeyBoardListener._listenCount++; + KeyBoardListener._listenersKeyUp[id] = callback; + return id; + } + + static offKeyUp(id) { + delete KeyBoardListener._listenersKeyUp[id]; + } +}