microkeys docs
Everything microkeys exports, with bindings checked at compile time.
Install
$ npm i microkeysUsage
microkeys(target, bindings, options?) returns an unsubscribe function.
import { microkeys } from "microkeys"
const unsubscribe = microkeys(window, {
"Shift+D": () => alert("Shift and D pressed together"),
"g i": () => goToInbox(), // sequence: g, then i
"$mod+k": { handler: openPalette, preventDefault: true },
"(F[1-9])": (event) => openTab(event.key), // regex key
})Handlers receive the event and a context carrying the matched binding.
microkeys(window, {
"$mod+s": (event, { binding }) => {
// event: KeyboardEvent, binding: "$mod+s" (literal type)
},
})Syntax
<sequence> = <press> <press> ... whitespace-separated
<press> = <key> | <mods>+<key>
<mod> = <modifier> (required) | [<modifier>] (optional)
<key> = KeyboardEvent.key | KeyboardEvent.code (case-insensitive)
<key> = (<regex>) → /^(?:<regex>)$/i, tested against key and code| Modifier | Aliases (case-insensitive) |
|---|---|
Shift | — |
Control | Ctrl |
Alt | Option, Opt |
Meta | Cmd, Command |
AltGraph | — |
$mod | Meta on Apple devices, else Control |
A modifier that isn't in the binding blocks the match: a doesn't fire on ⇧A unless it's optional, as in [Shift]+a. Shifted symbols need Shift spelled out: Shift+?, not ?.
Literal bindings are type-checked. "Hyper+k" and "Shift+" fail to compile; computed strings that slip through throw a SyntaxError when the handler is created.
Letters match the character typed, so $mod+z follows the Z key on AZERTY and Dvorak. When the typed character isn't ASCII (Russian я, or å from Option+A on macOS), the letter or digit of the physical key is used instead, so Control+s and Alt+a still work. Write KeyZ to bind the physical key.
On Windows, AltGr reports as Control+Alt. A character typed with AltGr (@ on a German keyboard) doesn't fire a Control+Alt+KeyQ binding. Bind it with AltGraph+KeyQ or Control+Alt+@.
Binding options
A binding's value is a handler or a config object.
microkeys(window, {
ArrowDown: { handler: next, repeat: true }, // fire while held
Enter: { handler: save, when: () => isEditing }, // falls through when false
enter: open, // runs when the binding above doesn't
"Shift+?": { handler: showHelp, once: true },
Escape: { handler: close, preventDefault: true, stopPropagation: true },
})| Option | Default | Description |
|---|---|---|
handler | — | (event, { binding }) => void |
preventDefault | global | Call event.preventDefault() when fired |
stopPropagation | global | Call event.stopPropagation() when fired |
repeat | false | Fire on auto-repeat events |
when | — | Fire only if it returns true; otherwise try the next binding |
once | false | Remove the binding after it fires |
Global options
| Option | Default | Description |
|---|---|---|
event | "keydown" | Or "keyup" |
capture | false | Listen in the capture phase |
signal | — | AbortSignal; aborting unsubscribes |
timeout | 1000 | Max ms between presses in a sequence |
preventDefault | false | Default for every binding |
stopPropagation | false | Default for every binding |
ignore | default | Return true to skip an event |
onConflict | console.warn | Called when a binding yields to a longer sequence; false silences it |
exclusive | false | Take over the keyboard while subscribed |
A key fires at most one binding per subscription. When a key both completes a binding and starts a longer sequence, the one listed first wins: an earlier sequence holds the key back and calls onConflict, an earlier binding fires and the sequence never starts. To have both, subscribe them separately.
The default ignore leaves keys to the browser or the focused control when they belong there:
- During IME composition: every key.
- In inputs, textareas, selects, and contenteditable: typing.
$modandControlcombos,Escape, and F-keys still fire, except text editing ones like$mod+a,$mod+c, and$mod+z. - On buttons, links, and checkboxes: plain
EnterandSpace. - Inside menus, listboxes, grids, and tablists: plain arrow keys, unless the listener is on that widget.
It never ignores events whose target is the listener's own target. To extend it:
import { defaultKeybindingsHandlerIgnore } from "microkeys"
microkeys(window, bindings, {
ignore: (e) =>
defaultKeybindingsHandlerIgnore(e) || (e.target as Element).closest("dialog") != null,
})Exclusive scopes
A dialog can take over the keyboard. While an exclusive subscription is active, every other subscription pauses, so Escape closes the dialog without also reaching the page. Exclusive subscriptions stack: the newest wins, and the previous one resumes when it unsubscribes.
function openDialog() {
const close = microkeys(window, { Escape: () => close() }, { exclusive: true })
}Recording shortcuts
import { recordKeybinding, keybindingFromEvent } from "microkeys"
const binding = await recordKeybinding() // user presses ⌘⇧K → "$mod+Shift+k"
microkeys(window, { [binding]: run })
recordKeybinding(window, { signal: controller.signal, mod: false }) // "Meta+Shift+k"
keybindingFromEvent(event) // same conversion for your own listenerrecordKeybinding waits for a non-modifier key, then preventDefaults it. The result matches the press that produced it.
React
import { useKeybinding, useKeybindings } from "microkeys/react"
function Editor() {
const ref = useRef<HTMLDivElement>(null)
useKeybindings({
"$mod+s": { handler: save, preventDefault: true },
"g i": goToInbox,
})
useKeybinding("Escape", close, {
target: ref,
exclusive: true,
enabled: isOpen,
})
return <div ref={ref} />
}Hooks take every global option, plus target (an element or ref, default window) and enabled. Handlers, when, ignore, and onConflict always use the latest render, so inline functions don't resubscribe. Other per-binding options apply when the listener is created.
Formatting
formatKeybinding turns a binding into display text, with Apple symbols on macOS and iOS.
import { formatKeybinding } from "microkeys"
formatKeybinding("$mod+Shift+k") // "⇧⌘K" on macOS, "Ctrl+Shift+K" elsewhere
formatKeybinding("g i") // "G I"
formatKeybinding("Control+Enter", { apple: true }) // "⌃↩"
formatKeybinding("$mod+k", { apple: false }) // "Ctrl+K", even on macOS
formatKeybinding("g i", { sequenceSeparator: " then " }) // "G then I"Lower-level API
import { createKeybindingsHandler } from "microkeys"
const listener = createKeybindingsHandler({ "g i": goToInbox })
element.addEventListener("keydown", listener)
listener.reset() // clear in-progress sequencesAlso exported: parseKeybinding, matchKeybindingPress, eventModifiers, IS_APPLE, and the types Keybindings, KeybindingConfig, IsValidKeybinding.