Atom Engine

Input State System

Purpose

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).


Lifecycle

Creation → Update → Destruction

Creation

Update

Per-frame maintenance

Destruction


Public API

InputState

type InputState = {
    keys: Set<string>;
    pressed: Set<string>;
    blockedKeys: Set<string>;
};

createInputState(blockedKeys?: string[]): InputState

Creates and returns a new input state object.


attachInput(state: InputState): void

Registers global keyboard event listeners and updates the provided state:


clearPressed(state: InputState): void

Clears the pressed set.


isKeyDown(state: InputState, key: string): boolean

Returns whether a key is currently being held down.


isKeyPressed(state: InputState, key: string): boolean

Returns whether a key was pressed once since the last clearPressed() call.


Internal Behavior

Key Tracking Model

The system distinguishes between:

Event Handling

Limitations


Example

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();