@dloizides/game-input

中文文档
1.14.0发布于 2026/11/11MITTypeScriptESM + CJS零依赖近 30 天下载 3164

Framework-agnostic game input primitives. v1 ships safe, player-toggleable haptics (Vibration API wrapper, localStorage-gated, zero deps). Extracted from Aurora; consumed across EisaiPollis games.

原始使用文档
文档目录11 节
  1. Steering without a bundler
  2. Install
  3. Usage
  4. Semantic pattern vocabulary
  5. API
  6. License
  7. Canvas menus: the walk hook (NAV-1)
  8. Tab pager ( createTabPager )
  9. Controller scrolling ( MenuNav.stick )
  10. Action prompts (1.11.0)
  11. Action chips ( createActionPrompts , 1.12.0)

@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:

IntentPatternUse
tap10menu nav / select / undo / restart
select12pick up a tool/charm/item
lock18something locks into place
bump24action blocked
navigate16portal / 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.hasBeenActive where present, else the first pointerdown / keydown / touchstart on options.activationTarget (default globalThis).
    • options.storageKey (default game.haptics) — localStorage key for the on/off preference.
    • options.enableConfirmation (default a 15ms tick; pass null to disable) — fired when turning ON.
    • options.navigator / options.storage — inject for tests/RN; default to globalThis.
  • 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 calls onAction(PadAction). Pass () => navigator.getGamepads(), requestAnimationFrame, cancelAnimationFrame in 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.
  • 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).

版本与发布记录

@dloizides/game-input 共发布 21 个版本,首次发布于 2026/06/17;过去 12 个月发布了 21 个版本。

版本发布日期距今
1.14.0latest2026/11/111 天前
1.13.02026/11/0210 天前
1.12.12026/10/2419 天前
1.12.02026/10/2319 天前
1.11.12026/10/2320 天前
1.11.02026/10/2320 天前

关于 @dloizides/game-input 的常见问题

@dloizides/game-input 是什么?

Framework-agnostic game input primitives. v1 ships safe, player-toggleable haptics (Vibration API wrapper, localStorage-gated, zero deps). Extracted from Aurora; consumed across EisaiPollis games.

如何安装 @dloizides/game-input?

在项目目录运行 npm install @dloizides/game-input,或使用 pnpm add / yarn add / bun add。

@dloizides/game-input 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dloizides/game-input 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@dloizides/game-input 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dloizides/game-input 可以商用吗?

@dloizides/game-input 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dloizides/game-input 的下载量有多少?

根据 npm 官方下载统计,@dloizides/game-input 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,164 次,日均约 105 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dloizides/game-input 还在维护吗?

最新版本 1.14.0 发布于 2026/11/11(1 天前);至今共发布 21 个版本,其中过去 12 个月发布了 21 个;首次发布于 2026/06/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。