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 { useKeyboard } from "@gridland/utils"Usage
useKeyboard((event) => {
if (event.name === "q") quit()
if (event.name === "return") submit()
})useKeyboard((event) => {
if (event.ctrl && event.name === "s") save()
if (event.shift && event.name === "Tab") focusPrevious()
})useKeyboard((event) => {
if (event.eventType === "release") {
heldKeys.delete(event.name)
} else {
heldKeys.add(event.name)
}
}, { release: true })Focus-aware routing
const { focusId } = useFocus()
useKeyboard((e) => {
if (e.name === "return") submit()
}, { focusId })useKeyboard((e) => {
if (e.ctrl && e.name === "q") quit()
}, { global: true })Parameters
| Param | Type | Default | Description |
|---|---|---|---|
handler | (key: KeyEvent) => void | -- | Called on each keypress |
options.release | boolean | false | Also receive key release events |
options.focusId | string | -- | Only fire when this ID is focused (from useFocus()) |
options.global | boolean | -- | Always fire regardless of focus state |
KeyEvent
| Property | Type | Description |
|---|---|---|
name | string | Key name ("a", "return", "escape", "up", etc.) |
ctrl | boolean | Whether Ctrl was held |
shift | boolean | Whether Shift was held |
repeated | boolean | Whether this is a key repeat |
eventType | "press" | "release" | Only present when release: true |