microkeys docs

Everything microkeys exports, with bindings checked at compile time.

Install

$ npm i microkeys

Usage

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
ModifierAliases (case-insensitive)
Shift—
ControlCtrl
AltOption, Opt
MetaCmd, Command
AltGraph—
$modMeta 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 },
})
OptionDefaultDescription
handler—(event, { binding }) => void
preventDefaultglobalCall event.preventDefault() when fired
stopPropagationglobalCall event.stopPropagation() when fired
repeatfalseFire on auto-repeat events
when—Fire only if it returns true; otherwise try the next binding
oncefalseRemove the binding after it fires

Global options

OptionDefaultDescription
event"keydown"Or "keyup"
capturefalseListen in the capture phase
signal—AbortSignal; aborting unsubscribes
timeout1000Max ms between presses in a sequence
preventDefaultfalseDefault for every binding
stopPropagationfalseDefault for every binding
ignoredefaultReturn true to skip an event
onConflictconsole.warnCalled when a binding yields to a longer sequence; false silences it
exclusivefalseTake 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. $mod and Control combos, Escape, and F-keys still fire, except text editing ones like $mod+a, $mod+c, and $mod+z.
  • On buttons, links, and checkboxes: plain Enter and Space.
  • 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

Record a shortcut to see its binding
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 listener

recordKeybinding 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 sequences

Also exported: parseKeybinding, matchKeybindingPress, eventModifiers, IS_APPLE, and the types Keybindings, KeybindingConfig, IsValidKeybinding.