# Shortcut recorder

> A tactile hairline keyboard shortcut recorder with physically depressed modifier keycaps, spring chord lock-in, layout-safe event.code capture and inline conflict swapping.

Custom keyboard shortcut inputs usually break in the same places: plain text fields flicker as modifiers arrive, Option+K on macOS captures accented glyphs instead of K, and colliding shortcuts either fail silently or overwrite another command without asking. ShortcutRecorder turns binding a key combo into a tactile hairline instrument. Clicking arms the recessed well with a quiet 1.5px 8×8 Bayer optical listening band along its edges while keeping every label crisp. As you hold modifiers (⌘, ⇧, ⌥, ⌃), each physical hairline keycap springs into place visibly depressed with its bottom switch skirt compressed away, beside a waiting trigger slot. Pressing the trigger key rebounds the entire chord upward together on a shared spring as the keycap skirts pop back into relief, swept by an emerald Bayer wavefront. It ships with layout-safe event.code capture, portable mod normalization across macOS and Windows, browser-reserved shortcut guards, live collision detection with one-click Swap, and exported matchesShortcut and formatShortcut helpers so you can wire recorded bindings straight into your app.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/shortcut-recorder.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): none
- Docs and live preview: https://hairlineui.com/ui/shortcut-recorder
- Registry item (source): https://hairlineui.com/r/shortcut-recorder.json

## Usage

```tsx
import { ShortcutRecorder, matchesShortcut } from "@/components/shortcut-recorder";

<ShortcutRecorder
  label="Command menu"
  value={shortcut}
  defaultShortcut="mod+k"
  conflicts={{ "mod+b": "Toggle sidebar" }}
  onChange={setShortcut}
  onConflictSwap={(next, action) => swapBinding(next, action)}
/>

// Match the recorded canonical string in your global keydown listener
window.addEventListener("keydown", (e) => {
  if (matchesShortcut(e, shortcut)) {
    e.preventDefault();
    openCommandMenu();
  }
});
```

## Connected keymap settings with live swapping and global listener

Store user shortcuts as a single canonical map, feed sibling entries into each row via conflicts, and pass the active string straight into matchesShortcut.

```tsx
"use client";
import { useEffect, useState } from "react";
import { ShortcutRecorder, matchesShortcut } from "@/components/shortcut-recorder";

const ACTIONS = [
  { id: "command", label: "Command menu", fallback: "mod+k" },
  { id: "issue", label: "New issue", fallback: "mod+shift+n" },
] as const;

export function KeymapSettings({ onRun }: { onRun: (id: string) => void }) {
  const [map, setMap] = useState<Record<string, string | null>>({
    command: "mod+k",
    issue: "mod+shift+n",
  });

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      for (const action of ACTIONS) {
        if (matchesShortcut(e, map[action.id])) {
          e.preventDefault();
          onRun(action.id);
          return;
        }
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [map, onRun]);

  return (
    <div className="space-y-3">
      {ACTIONS.map((action) => {
        const conflicts: Record<string, string> = {};
        for (const other of ACTIONS) {
          if (other.id !== action.id && map[other.id]) conflicts[map[other.id]!] = other.label;
        }
        return (
          <div key={action.id} className="flex items-center justify-between gap-4">
            <span className="text-sm font-medium">{action.label}</span>
            <div className="w-56">
              <ShortcutRecorder
                label={action.label}
                value={map[action.id]}
                defaultShortcut={action.fallback}
                conflicts={conflicts}
                onChange={(next) => setMap((prev) => ({ ...prev, [action.id]: next }))}
                onConflictSwap={(next, owner) => {
                  const partner = ACTIONS.find((a) => a.label === owner);
                  setMap((prev) => ({
                    ...prev,
                    [action.id]: next,
                    ...(partner ? { [partner.id]: prev[action.id] } : {}),
                  }));
                }}
              />
            </div>
          </div>
        );
      })}
    </div>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value / defaultValue / defaultShortcut / onChange` | `string \| null / (v) => void` | `null` | Controlled or uncontrolled canonical shortcut string (e.g. "mod+shift+k"), optional default to restore via Reset, and commit callback. |
| `conflicts / onConflictSwap` | `Record<string, string> / (shortcut, action) => void` | – | Map of existing bindings to action names for live collision checks, plus one-click inline Swap handler. |
| `requireModifier / useMod / allowReserved / reserved` | `boolean / boolean / boolean / string[]` | `true / true / false / –` | Enforce a primary modifier on printable keys, store Command/Ctrl as portable "mod", and guard browser-reserved chords like mod+w or mod+t. |
| `clearable / platform / label / placeholder / sound` | `boolean / "mac" \| "other" / string / string / boolean` | `true / auto / "Keyboard shortcut" / "Add shortcut" / false` | Clear control and Backspace-to-clear while armed, OS glyph override, accessible name, empty label and opt-in Web Audio switch ticks. |
| `matchesShortcut / formatShortcut / normalizeShortcut` | `exported helper functions` | – | Layout-safe KeyboardEvent matcher, platform glyph formatter and canonical key-order normaliser exported from the same file. |

## States

- **idle**: Crisp hairline capsule showing bound physical keycaps (or Add shortcut when unbound) with subtle reset-to-default and clear icons; the optical canvas sleeps at 0% CPU.
- **listening (armed)**: Well recesses cleanly and wakes a perimeter-weighted 1.5px 8×8 Bayer optical band behind a pulsing Press keys prompt and an Esc cancel badge.
- **modifiers held**: Each held modifier appears as a physically depressed hairline keycap (skirt compressed away) alongside a dashed trigger slot while the Bayer sensor brightens underneath the key bay.
- **locked in**: Trigger key commits the chord: all keycaps spring upward together into relief and an emerald Bayer wavefront sweeps left to right across the well.
- **conflict**: An amber hairline ring and Bayer sweep highlight the collision while an inline fold explains which action owns the binding, offering one-click Swap or Cancel.
- **reserved / invalid**: A damped spring recoil nudges the well horizontally with a brief rose Bayer edge pulse and an inline alert, keeping the recorder armed for your next keypress.
- **reduced motion**: No canvas loop, recoil travel or spring overshoot: keycaps, conflicts and announcements update cleanly in place.

## What it handles

Real keymap screens need layout-safe key capture, portable platform modifiers, browser-reserved guards and a safe way to resolve collisions without making the user hunt through another row.

- **Physically depressed modifier keycaps**: Holding modifiers materialises tactile hairline keycaps sunk into the recessed keywell beside a waiting trigger slot; releasing without a trigger restores the previous binding cleanly.
- **Synchronised spring chord lock-in**: Pressing the trigger key rebounds all keycaps upward together on a shared spring as their 3D skirts pop into relief, paired with an emerald 8×8 Bayer sweep.
- **Layout-safe event.code capture**: Reads physical key codes so Option+K on macOS always records alt+k instead of an accented character, and non-Latin keyboard layouts stay consistent.
- **Live conflicts with one-click Swap**: Pass a conflicts map and onConflictSwap handler: colliding chords pulse amber and unfold an inline Swap control that exchanges both bindings in sync.
- **Browser-reserved and modifier guards**: Rejects footgun chords like ⌘W, ⌘T or ⌘R (and bare letters when requireModifier is true) with a damped spring recoil and an inline reason, staying armed so you can try again immediately.
- **Built-in matchesShortcut matcher**: Exports matchesShortcut, formatShortcut and normalizeShortcut alongside the component so recorded strings bind directly to window keydown listeners.

## Replaces

custom keybinding input, hotkey recorder, react-hotkeys recorder, manual keydown parser, framer-motion

## Where it fits

- **Workspace keyboard settings**: Let power users rebind command menus, navigation and action chords with live conflict detection and one-click swapping.
- **Desktop-grade editors and canvases**: Capture layout-safe shortcuts via event.code so Option chords on macOS and non-Latin keyboards record reliably.
- **AI assistants and global launchers**: Store a single portable mod+shift+k string that renders ⌘ ⇧ K on macOS and Ctrl Shift K on Windows and Linux.
- **Single-key triage workflows**: Set requireModifier={false} for Linear-style or Gmail-style single-letter bindings such as C or /.

## Notes

- Canonical shortcuts always sort modifiers in a fixed order (mod, ctrl, meta, alt, shift) followed by the trigger key, so conflict maps match reliably regardless of input order.
- Physical key codes (event.code) are read before event.key so Option chords on macOS and non-Latin keyboard layouts record clean, predictable bindings.
- The 8×8 Bayer optical sensor sleeps completely at rest (0 rAF calls) and runs only while armed or during a short 0.5s lock-in, conflict or recoil pulse.
- When a controlled value changes externally (such as a partner row receiving a swapped binding), that row fires a matching spring rebound and emerald sweep automatically.
- Under prefers-reduced-motion: reduce, the canvas loop and spring recoil are skipped while every state, conflict swap and screen-reader announcement remains intact.

License: MIT (https://hairlineui.com/license#components)
