@dloizides/game-input
Framework-agnostic game input primitives. v1 ships safe, player-toggleable haptics — a thin wrapper over the Web Vibration API that no-ops silently when disabled, unsupported, or blocked, so call sites can fire haptics unconditionally alongside their SFX/visual feedback.
Zero runtime dependencies. Isomorphic (no DOM lib required — navigator and storage are structural and
injectable), so it works in browser games, React Native shells, and tests alike.
Scope note: keyboard/gamepad normalization is intentionally not in v1. The games that were audited (Aurora, Morphe) implemented input with fundamentally different designs — there is no shared logic to extract yet. It will be added when a genuine 2nd same-stack consumer appears (extract-on-2nd-use).
Steering without a bundler
createSteerInput is for continuous movement (fly, drive); createMenuNav still walks menus. dist/index.mjs has no imports, so a plain page can load it directly with no import map:
<script type="module">
import { createSteerInput, STANDARD_BUTTON } from 'https://cdn.jsdelivr.net/npm/@dloizides/[email protected]/dist/index.mjs';
const steer = createSteerInput({ surface: canvas, enabled: () => playing });
function frame() {
const { x, y, back, pressed, touch } = steer.read();
move(x, y);
if (back) exitPlay();
if (pressed.includes(STANDARD_BUTTON.south)) act();
drawStick(touch);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
Call read() once per frame: back and pressed are consumed by the read. Give surface the CSS touch-action: none. Return false from enabled while a menu or dialog owns input; keys then stay with the page. touch carries the press point in client px plus the steer, for drawing a stick.
Install
npm install @dloizides/game-input
Usage
import { createHaptics, HAPTIC_PATTERNS } from '@dloizides/game-input';
// One controller per game; the storage key namespaces the player's preference.
const haptics = createHaptics({ storageKey: 'aurora.haptics' });
// Fire unconditionally — disabled/unsupported just no-ops.
haptics.vibrate(HAPTIC_PATTERNS.tap); // menu navigation / selection
haptics.vibrate(HAPTIC_PATTERNS.success); // level cleared
haptics.vibrate([0, 14, 24, 14]); // or your own pattern
// Settings toggle — returns the new state, fires a confirming tick when enabling.
function onHapticsToggle(): boolean {
return haptics.toggle();
}
haptics.isEnabled();
Semantic pattern vocabulary
HAPTIC_PATTERNS is a shared set of tuned vibration patterns keyed by intent, so every game uses the same
feel instead of re-picking magic durations:
| Intent | Pattern | Use |
|---|---|---|
tap | 10 | menu nav / select / undo / restart |
select | 12 | pick up a tool/charm/item |
lock | 18 | something locks into place |
bump | 24 | action blocked |
navigate | 16 | portal / page turn |
success | [0,40,50,90] | level/chamber cleared |
error | [0,14,24,14] | fatal/destructive event |
loss | [0,40,50,40] | player loses / falls |
reveal | [0,14,20,18,26,24] | puzzle resolves / exit opens |
API
createHaptics(options?)→Haptics—{ isEnabled, setEnabled, toggle, vibrate }. Nothing vibrates before a user gesture:navigator.userActivation.hasBeenActivewhere present, else the firstpointerdown/keydown/touchstartonoptions.activationTarget(defaultglobalThis).options.storageKey(defaultgame.haptics) — localStorage key for the on/off preference.options.enableConfirmation(default a15ms tick; passnullto disable) — fired when turning ON.options.navigator/options.storage— inject for tests/RN; default toglobalThis.
HAPTIC_PATTERNS,DEFAULT_HAPTICS_STORAGE_KEY,DEFAULT_ENABLE_CONFIRMATION.createGamepadPoller({ getPads, requestFrame, cancelFrame, onAction })→{ start, stop }— polls the first connected W3C Standard Gamepad each frame and callsonAction(PadAction). Pass() => navigator.getGamepads(),requestAnimationFrame,cancelAnimationFramein the browser.- Buttons by POSITION: south →
confirm, east →back, west →view, north →mood, L/R shoulder →pagePrev/pageNext(rising edge only). - D-pad or left stick (0.5 dead-zone) →
up/down/left/right: fires once, repeats after 380 ms, then every 110 ms.
- Buttons by POSITION: south →
stepPad(prev, next, repeat, now)— the pure per-frame reducer behind the poller;IDLE_REPEAT,PAD_ACTIONS,STANDARD_BUTTON.
License
MIT
Canvas menus: the walk hook (NAV-1)
A game whose menus are drawn on a canvas (no DOM buttons) publishes its menu state so the shared walker in
@dloizides/game-e2e (expectHookMenuWalkable) can prove every item is reachable by arrows and pad:
import { installMenuWalkHook } from '@dloizides/game-input';
installMenuWalkHook({
screen: () => menu.screenId, // e.g. 'title', 'settings'
items: () => menu.items.map((i) => i.id),
focused: () => menu.focusedId ?? null,
});
Tab pager (createTabPager)
const pager = createTabPager({ host: dialogEl, ignore: '.h-rail' });
const onPad = (a: PadAction): void => { if (!pager.pad(a)) menuNav.pad(a); };
host must stay mounted; everything inside it may re-render. Tabs need role="tab" inside a role="tablist", aria-selected, and a click handler that selects them; the panel is the tab's aria-controls target or the first role="tabpanel". Arrows and the d-pad move focus along the tab row without switching tabs (manual activation); Enter/Space/click, the shoulder buttons or a swipe activate one.
Controller scrolling (MenuNav.stick)
const poller = createGamepadPoller({ getPads, requestFrame, cancelFrame, onAction: (a) => menuNav.pad(a), onScroll: (y, now) => menuNav.stick(y, now) });
// own poll loop: menuNav.stick(pad.axes[RIGHT_STICK_Y] ?? 0, now) every frame
The right stick scrolls the focused control's scroll container (else the first scrollable one in the menu, a tab panel included) with a dead zone and a squared speed curve; when it scrolls the focused control out of view, focus moves to the first control in view. Up/Down (d-pad, left stick, arrow keys) scroll half a view instead of moving focus when the next control is more than a step away, after the end of the scrolling list, or missing (text pages), and wrap only once the container is at its end. Focus moves scroll the new control into view at block: nearest, smoothly unless prefers-reduced-motion.
Action prompts (1.11.0)
import { createBindings, createInputDeviceTracker, glyphSvg, PadFamily, promptFor } from '@dloizides/game-input';
const binds = createBindings({ actions: ['jump'], keys: { jump: 'Space' }, pad: { jump: 0 }, storageKey: 'surge.binds' });
const tracker = createInputDeviceTracker({ target: window, getPads: () => navigator.getGamepads() });
const prompt = promptFor(binds, 'jump', tracker.current());
const icon = prompt.glyph === null ? '' : glyphSvg(prompt.glyph, tracker.current().family ?? PadFamily.Generic);
Call tracker.poll() once per frame. Style glyphs with --gi-fg and --gi-bg. A hidden prompt (touch, or no binding on that device) renders nothing.
Action chips (createActionPrompts, 1.12.0)
import { createActionPrompts } from '@dloizides/game-input';
const prompts = createActionPrompts({ bindings: () => binds, onBindingsChanged: (repaint) => binds.onChange(repaint) });
prompts.tag(jumpButton, 'jump');
prompts.tagFixed(pauseButton, 'pause', { key: 'Esc', pad: 'Menu' });
prompts.untag(jumpButton);
Each tagged control gets data-gi-action and a .gi-chip (data-kind="key"|"pad") holding a glyph span and .gi-text[data-gi-prompt]. Chips follow the last-used device and the current bindings, hide on touch, and re-append themselves if the control re-renders. Pads are polled on requestAnimationFrame; pass schedule: null to poll yourself, or your own tracker. Attribute and class names are options (defaults in ACTION_CHIP_DOM).