This module provides a lightweight keyboard input tracking system for browser-based applications (commonly games or interactive simulations). It maintains real-time state for currently held keys, newly pressed keys (per frame), and optionally blocks default browser behavior for specific keys.
It is designed to support both continuous input (e.g., movement while holding a key) and discrete input events (e.g., single press actions).
Creation → Update → Destruction
Creation
createInputState() initializes the input state object with empty tracking sets and optional blocked keys.Update
attachInput() registers global keydown and keyup listeners on window.Per-frame maintenance
clearPressed() is typically called once per update/frame cycle to reset “just pressed” state.Destruction
InputStatetype InputState = {
keys: Set<string>;
pressed: Set<string>;
blockedKeys: Set<string>;
};
keys: All keys currently held down.pressed: Keys that were pressed once (non-repeating) since the last reset.blockedKeys: Keys whose default browser behavior should be prevented.createInputState(blockedKeys?: string[]): InputStateCreates and returns a new input state object.
blockedKeys (optional): List of key values whose default browser behavior should be prevented.ArrowUp, ArrowDown, ArrowLeft, ArrowRight)" ")"e"attachInput(state: InputState): voidRegisters global keyboard event listeners and updates the provided state:
keydown:
keyspressed only if it is not an auto-repeated eventblockedKeyskeyup:
keysblockedKeysclearPressed(state: InputState): voidClears the pressed set.
pressed only reflects keys triggered since the last update cycle.isKeyDown(state: InputState, key: string): booleanReturns whether a key is currently being held down.
state.keys.isKeyPressed(state: InputState, key: string): booleanReturns whether a key was pressed once since the last clearPressed() call.
state.pressed.The system distinguishes between:
keys)
keydown and keyuppressed)
keydown events (e.repeat === false)window.addEventListener for keyboard events.KeyboardEvent.key values.blockedKeys, useful for:
blockedKeys.const input = createInputState();
// Attach global listeners
attachInput(input);
// Game loop
function update() {
if (isKeyDown(input, "ArrowRight")) {
console.log("Moving right continuously");
}
if (isKeyPressed(input, " ")) {
console.log("Jump triggered once");
}
// Reset per-frame pressed state
clearPressed(input);
requestAnimationFrame(update);
}
update();
KeyboardEvent (Web API)