Skip to content

Early previewhamur is not on npm yet. The components are being built in the open, follow along on GitHub.

UtilitiesReact

Hotkeys

A way to run your code when the user presses a key combination, from anywhere on the page or only while focus is inside an element.

Rendered by React 19.3.1

import * as React from 'react'
import { getHotkeyKeys, registerHotkey } from '@hamur/react/hotkeys'

const glyphs: Record<string, string> = { Meta: '⌘', Control: 'Ctrl' }
const keys = getHotkeyKeys('Mod+S')[0]
const shortcut = keys.map((key) => glyphs[key] ?? key).join(keys.includes('Meta') ? '' : '+')

export default function HotkeysExample() {
  const button = React.useRef<HTMLButtonElement>(null)
  const [count, setCount] = React.useState(0)

  React.useEffect(
    () =>
      registerHotkey('Mod+S', () => setCount((value) => value + 1), {
        control: button.current ?? undefined,
      }),
    [],
  )

  return (
    <div className="stack">
      <div className="row">
        <button
          ref={button}
          className="button"
          type="button"
          onClick={() => setCount((value) => value + 1)}
        >
          Save <kbd aria-hidden="true">{shortcut}</kbd>
        </button>
      </div>
      <p className="muted">Saved {count} times</p>
    </div>
  )
}
Not measured yetTests passing in React
3.4 KiBSize
Not measured yetMemory
Not measured yetSpeed
[N] commits

Installation

npm i @hamur/react

Not on npm yet. The package goes out under the chosen name.

Anatomy

Hotkeys has no parts. Import its functions from @hamur/react/hotkeys and call them.

Examples

Setting

A ? shortcut that opens a help panel, with a checkbox that turns it off and a field that remaps it, checked with isValidHotkey.

HotkeysSetting.tsx
import * as React from 'react'
import { isValidHotkey, registerHotkey } from '@hamur/react/hotkeys'

export default function HotkeysSettingExample() {
  const [enabled, setEnabled] = React.useState(true)
  const [hotkey, setHotkey] = React.useState('?')
  const [open, setOpen] = React.useState(false)
  const valid = isValidHotkey(hotkey)

  React.useEffect(() => {
    if (!enabled || !valid) return undefined
    return registerHotkey(hotkey, () => setOpen((value) => !value))
  }, [enabled, valid, hotkey])

  return (
    <div className="stack">
      <label className="row">
        <input
          type="checkbox"
          checked={enabled}
          onChange={(event) => setEnabled(event.target.checked)}
        />
        Single-character shortcuts
      </label>
      <div className="field">
        <label htmlFor="hotkeys-help-key">Help shortcut</label>
        <input
          id="hotkeys-help-key"
          className="input"
          value={hotkey}
          onChange={(event) => setHotkey(event.target.value)}
        />
        {valid ? null : <span className="error">Not a valid hotkey</span>}
      </div>
      <p className="muted">Help is {open ? 'open' : 'closed'}</p>
    </div>
  )
}

API reference

Hotkeys has no parts. It is 4 functions you call.

Functions
FunctionDescription
getHotkeyKeysThe tokens of each alternative in display order, Mod resolved for the detected platform.
isValidHotkeyWhether hotkey is a valid hotkey string.
matchesHotkeyWhether a keydown matches hotkey, apple defaulting to the detected platform.
registerHotkeyRuns callback when hotkey is pressed; returns the function that removes it.

Keyboard and accessibility

Keyboard

Keyboard
KeysDoesPart
ControlSMetaSRuns the callback from anywhere on the page and prevents the browser's ownregisterHotkey
?Runs the callback of a single-character shortcut, while the setting is onregisterHotkey

Accessibility

What the parts set
PartSetsSo that
registerHotkeyaria-keyshortcuts on control, while the registration exists; no role or ida screen reader can announce the shortcut of a control, and the attribute never outlives it

Focus order

  1. Hotkeys is not focusable and takes no part in the tab order.
  2. A hotkey never moves the focus and never clicks the control; the callback decides what happens.