gridland
Hooks

useKeyboard

Subscribe to keyboard events

The useKeyboard hook subscribes to keyboard events inside a <TUI> component. By default it receives press events (including key repeats). Use options.release to also receive release events.

Import
import { useKeyboard } from "@gridland/utils"

Usage

Basic
useKeyboard((event) => {
  if (event.name === "q") quit()
  if (event.name === "return") submit()
})
With modifiers
useKeyboard((event) => {
  if (event.ctrl && event.name === "s") save()
  if (event.shift && event.name === "Tab") focusPrevious()
})
With release events
useKeyboard((event) => {
  if (event.eventType === "release") {
    heldKeys.delete(event.name)
  } else {
    heldKeys.add(event.name)
  }
}, { release: true })

Focus-aware routing

Focus-scoped: only fires when this component is focused
const { focusId } = useFocus()
useKeyboard((e) => {
  if (e.name === "return") submit()
}, { focusId })
Global: always fires regardless of focus
useKeyboard((e) => {
  if (e.ctrl && e.name === "q") quit()
}, { global: true })

Parameters

ParamTypeDefaultDescription
handler(key: KeyEvent) => void--Called on each keypress
options.releasebooleanfalseAlso receive key release events
options.focusIdstring--Only fire when this ID is focused (from useFocus())
options.globalboolean--Always fire regardless of focus state

KeyEvent

PropertyTypeDescription
namestringKey name ("a", "return", "escape", "up", etc.)
ctrlbooleanWhether Ctrl was held
shiftbooleanWhether Shift was held
repeatedbooleanWhether this is a key repeat
eventType"press" | "release"Only present when release: true