@basenative/keyboard

中文文档
3.0.0发布于 2026/10/31Apache-2.0TypeScriptES Module零依赖构建来源已验证

Accessible mobile-first on-screen virtual keyboard primitive — layout-agnostic, signal-driven key state coloring, themable

原始使用文档
文档目录11 节
  1. Why
  2. Install
  3. Quick start — game keyboard
  4. Numpad
  5. Custom layout
  6. Theming
  7. Mobile Safari focus fix
  8. Hardware keyboard parity
  9. Mobile testing notes
  10. API
  11. License

@basenative/keyboard

Accessible, mobile-first on-screen virtual keyboard primitive — layout-agnostic, signal-driven, themable.

Part of the BaseNative ecosystem.

Built for puzzle games, kiosk apps, accessible inputs, and any time you need an on-screen keyboard that doesn't fight with mobile Safari.

Why

Mobile browsers have a lot of opinions about keyboards. The native one pops up uninvited, focus jumps around, hit targets are too small, animations break for users who asked them not to. This package is a single primitive that:

  • Renders semantic <button> elements (works without JS — SSR pre-paint friendly).
  • Dispatches taps via signal-aware handlers, with hardware-key mirroring so a Bluetooth keyboard goes through the exact same dispatch path.
  • Applies per-key status classes from a state getter (green / yellow / absent / staked) — perfect for Wordle-style games or any feedback-driven UI.
  • Themes entirely through --kb-* CSS custom properties. No bundled palette assumptions.
  • Has 44pt min hit targets by default (WCAG 2.5.5 AA), default-palette WCAG AA contrast on every status state, and honors prefers-reduced-motion.
  • Fixes the mobile-Safari focus-steal bug (more on this below).

Install

pnpm add @basenative/keyboard @basenative/runtime

Quick start — game keyboard

import { Keyboard, LAYOUTS } from '@basenative/keyboard';
import { signal, effect } from '@basenative/runtime';
import '@basenative/keyboard/css';

const keyStatus = signal({ A: 'green', E: 'yellow', X: 'absent' });

const kb = Keyboard({
  layout: LAYOUTS.qwerty,
  primary: 'ENTER',
  state: keyStatus.get,
  runtime: { effect },
  onKey:    (char) => guessSignal.update(g => g + char),
  onAction: (a) => {
    if (a === 'ENTER') submitGuess();
    if (a === 'BACKSPACE') guessSignal.update(g => g.slice(0, -1));
  },
});

document.querySelector('#kb-mount').innerHTML = kb.html;
kb.hydrate(document.querySelector('[data-bn="keyboard"]'));

Numpad

import { Keyboard } from '@basenative/keyboard';

const pad = Keyboard({
  layout: 'numpad',
  primary: 'ENTER',
  onKey: (digit) => pin.update(s => s + digit),
  onAction: (a) => a === 'BACKSPACE' && pin.update(s => s.slice(0, -1)),
});

Custom layout

import { defineLayout, Keyboard } from '@basenative/keyboard';

const dvorak = defineLayout([
  ['1','2','3','4','5','6','7','8','9','0'],
  ["'", ',', '.', 'P', 'Y', 'F', 'G', 'C', 'R', 'L'],
  ['A', 'O', 'E', 'U', 'I', 'D', 'H', 'T', 'N', 'S'],
  [
    { type: 'action', label: '⌫', key: 'BACKSPACE', span: 1.5, variant: 'backspace' },
    ';', 'Q', 'J', 'K', 'X', 'B', 'M', 'W', 'V', 'Z',
    { type: 'action', label: 'GO', key: 'ENTER', span: 1.5, variant: 'enter' },
  ],
]);

const kb = Keyboard({ layout: dvorak, primary: 'ENTER', onKey, onAction });

Theming

All visuals are CSS custom properties. Override at any ancestor:

.my-app [data-bn="keyboard"] {
  --kb-bg: #fff;
  --kb-key-bg: #f4f4f5;
  --kb-key-fg: #18181b;
  --kb-key-active: #d4d4d8;
  --kb-key-green:  #16a34a;
  --kb-key-yellow: #eab308;
  --kb-key-absent: #d4d4d8;
  --kb-key-radius: 8px;
  --kb-min-tap: 48px;
}
TokenPurposeDefault
--kb-bgKeyboard surface background#0C0B09
--kb-key-bgDefault key background#3A3530
--kb-key-fgDefault key text#F0EDE4
--kb-key-activePressed-state background#5A5550
--kb-key-greenStatus: correct position#2E8B5A
--kb-key-yellowStatus: correct letter, wrong position#D4B445
--kb-key-absentStatus: not in answer#1E1C18
--kb-key-radiusPer-key corner radius6px
--kb-gapHorizontal gap between keys4px
--kb-min-tapMinimum hit target (WCAG 2.5.5 AA)44px

Mobile Safari focus fix

When you tap a key, mobile Safari briefly moves focus to the <button>, which blurs the active text input. That blur causes Safari to dismiss the keyboard — and on the next focus, it raises the native keyboard alongside ours. The fix is to call preventDefault on mousedown / touchstart so focus never moves at all.

hydrateKeyboard does this automatically. If you ever need a key that does take focus (rare — usually a key that submits a form via native semantics), set data-bn-kb-focusable="true" on the button.

Hardware keyboard parity

When bindHardware is true (default), keydown events on document are translated into the same onKey / onAction calls as taps. So a Bluetooth keyboard or a desktop user gets identical behavior — no separate input pipeline.

To restrict the chars the hardware listener forwards, pass a charSet via the lower-level bindHardwareKeys(...) API.

Mobile testing notes

  • iOS 16/17 Safari (iPhone 12, 14 Pro, SE 3rd gen): tap dispatch, no native-keyboard pop-up, haptics fire.
  • Android 13/14 Chrome (Pixel 6, 7): tap dispatch, navigator.vibrate(8) fires, hit targets pass Lighthouse a11y audit.
  • Reduced-motion: tested with iOS "Reduce Motion" and prefers-reduced-motion: reduce in DevTools — press scale animation drops to a flat color change.

API

import {
  Keyboard,            // factory: { html, hydrate(rootEl) }
  renderKeyboard,      // SSR: returns HTML string
  hydrateKeyboard,     // wire reactivity to an existing root
  LAYOUTS,             // { qwerty, alphanumeric, numpad, phone }
  defineLayout,        // (rows, meta?) => Layout
  validateLayout,      // throw on shape mismatch
  keyState,            // single-letter status reader
  applyAriaAttributes,
  preventFocusSteal,
  bindHardwareKeys,
  haptic,
} from '@basenative/keyboard';

See types/index.d.ts for full signatures.

License

Apache-2.0

版本与发布记录

@basenative/keyboard 共发布 11 个版本,首次发布于 2026/10/18;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.0latest2026/10/312 天前
2.4.02026/10/268 天前
2.3.22026/10/2212 天前
2.3.12026/10/2212 天前
2.3.02026/10/2212 天前
2.2.02026/10/2113 天前

关于 @basenative/keyboard 的常见问题

@basenative/keyboard 是什么?

可访问的移动-第一个屏幕上的虚拟键盘原语-布局不可知,信号驱动的键状态着色,主题

如何安装 @basenative/keyboard?

在项目目录运行 npm install @basenative/keyboard,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@basenative/runtime(3.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@basenative/keyboard 支持 TypeScript 吗?

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

@basenative/keyboard 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@basenative/keyboard 可以商用吗?

@basenative/keyboard 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@basenative/keyboard 还在维护吗?

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