{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"shortcut-recorder","type":"registry:component","title":"Shortcut recorder","description":"A tactile hairline keyboard shortcut recorder with physically depressed modifier keycaps, spring chord lock-in, layout-safe event.code capture and inline conflict swapping.","author":"Hairline UI","dependencies":["lucide-react"],"files":[{"path":"registry/shortcut-recorder.tsx","type":"registry:component","content":"// Hairline UI · shortcut-recorder · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowLeftRight, RotateCcw, X } from \"lucide-react\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  MATERIAL_RECESS,\n  createSpring,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * SHORTCUT RECORDER: tactile hairline keycap recorder & matcher\n *\n * Built for real desktop-grade web apps (Linear, Raycast, Figma):\n *   - Click to arm -> recessed keywell wakes with a subtle 1.5px 8×8\n *     Bayer optical listening band while preserving razor-sharp contrast\n *   - Hold modifiers (⌘, ⇧, ⌥, ⌃) -> physical hairline keycaps spring\n *     into place visibly depressed (bottom switch skirt compressed away),\n *     paired with a waiting trigger slot\n *   - Hit trigger key -> all held keycaps rebound upward together on a\n *     shared spring as their 3D hairline skirts pop into relief, swept\n *     by an emerald 8×8 Bayer lock-in wavefront\n *   - Real infra included: layout-safe event.code capture (so Option+K\n *     on macOS records alt+k, never ˚), Mac/Windows normalization, live\n *     conflict detection with 1-click inline Swap, browser-reserved guard,\n *     plus exported matchesShortcut / formatShortcut / normalizeShortcut\n * ───────────────────────────────────────────────────────── */\n\nexport type ShortcutPlatform = \"mac\" | \"other\";\n\nexport interface ShortcutRecorderProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"defaultValue\" | \"onChange\"> {\n  /** Controlled canonical shortcut string (e.g. \"mod+shift+k\"), or null when unbound. */\n  value?: string | null;\n  /** Initial uncontrolled shortcut (e.g. \"mod+k\"). */\n  defaultValue?: string | null;\n  /** Default shortcut restored by the inline reset control when the binding differs. */\n  defaultShortcut?: string | null;\n  /** Called whenever a valid shortcut is committed or cleared. */\n  onChange?: (shortcut: string | null) => void;\n  /** Map of existing bindings (canonical shortcut -> action label) to detect collisions live. */\n  conflicts?: Record<string, string>;\n  /** Called when the user confirms Swap on a conflict; parent can hand the previous shortcut to the conflicting action. */\n  onConflictSwap?: (shortcut: string, conflictingAction: string) => void;\n  /** Require a non-shift modifier (mod, ctrl, alt) for letter/number bindings (default true). */\n  requireModifier?: boolean;\n  /** Store Command (Mac) / Control (Windows & Linux) as portable \"mod\" (default true). */\n  useMod?: boolean;\n  /** Allow clearing the shortcut via Backspace/Delete while armed or the inline Clear control (default true). */\n  clearable?: boolean;\n  /** Allow browser-reserved combinations like mod+w or mod+t (default false). */\n  allowReserved?: boolean;\n  /** Additional canonical shortcuts to reject as reserved. */\n  reserved?: string[];\n  /** Override OS symbol rendering (\"mac\" renders ⌘ ⌥ ⇧ ⌃; \"other\" renders Ctrl Alt Shift). */\n  platform?: ShortcutPlatform;\n  /** Accessible name describing the command being bound (e.g. \"Command menu\"). */\n  label?: string;\n  /** Copy shown when no shortcut is bound (default \"Add shortcut\"). */\n  placeholder?: string;\n  /** Disable recording and controls. */\n  disabled?: boolean;\n  /** Opt-in quiet Web Audio key ticks and chord lock-in chime (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\nconst MOD_ORDER = [\"mod\", \"ctrl\", \"meta\", \"alt\", \"shift\"] as const;\ntype ModToken = (typeof MOD_ORDER)[number];\n\nconst MOD_ALIASES: Record<string, ModToken> = {\n  mod: \"mod\",\n  cmdorctrl: \"mod\",\n  commandorcontrol: \"mod\",\n  ctrl: \"ctrl\",\n  control: \"ctrl\",\n  cmd: \"meta\",\n  command: \"meta\",\n  meta: \"meta\",\n  win: \"meta\",\n  super: \"meta\",\n  alt: \"alt\",\n  option: \"alt\",\n  opt: \"alt\",\n  shift: \"shift\",\n};\n\nconst MOD_CODES = new Set([\n  \"MetaLeft\",\n  \"MetaRight\",\n  \"ControlLeft\",\n  \"ControlRight\",\n  \"AltLeft\",\n  \"AltRight\",\n  \"ShiftLeft\",\n  \"ShiftRight\",\n]);\n\nconst IGNORED_CODES = new Set([\n  \"CapsLock\",\n  \"NumLock\",\n  \"ScrollLock\",\n  \"ContextMenu\",\n  \"Fn\",\n  \"FnLock\",\n  \"Hyper\",\n  \"OSLeft\",\n  \"OSRight\",\n  \"Pause\",\n  \"PrintScreen\",\n  \"Insert\",\n  \"Unidentified\",\n]);\n\nconst CODE_TO_KEY: Record<string, string> = {\n  Space: \"space\",\n  Enter: \"enter\",\n  NumpadEnter: \"enter\",\n  Tab: \"tab\",\n  Backspace: \"backspace\",\n  Delete: \"delete\",\n  Escape: \"escape\",\n  ArrowUp: \"up\",\n  ArrowDown: \"down\",\n  ArrowLeft: \"left\",\n  ArrowRight: \"right\",\n  Home: \"home\",\n  End: \"end\",\n  PageUp: \"pageup\",\n  PageDown: \"pagedown\",\n  Minus: \"-\",\n  Equal: \"=\",\n  BracketLeft: \"[\",\n  BracketRight: \"]\",\n  Backslash: \"\\\\\",\n  Semicolon: \";\",\n  Quote: \"'\",\n  Backquote: \"`\",\n  Comma: \",\",\n  Period: \".\",\n  Slash: \"/\",\n};\n\nconst KEY_ALIASES: Record<string, string> = {\n  esc: \"escape\",\n  return: \"enter\",\n  arrowup: \"up\",\n  arrowdown: \"down\",\n  arrowleft: \"left\",\n  arrowright: \"right\",\n  \" \": \"space\",\n  spacebar: \"space\",\n  del: \"delete\",\n};\n\nconst NAV_OR_FUNC_RE = /^(f([1-9]|1[0-2])|tab|enter|escape|backspace|delete|up|down|left|right|home|end|pageup|pagedown)$/;\nconst FUNC_KEY_RE = /^f([1-9]|1[0-2])$/;\n\nconst DEFAULT_RESERVED = new Set([\n  \"mod+w\",\n  \"mod+t\",\n  \"mod+n\",\n  \"mod+r\",\n  \"mod+q\",\n  \"mod+l\",\n  \"mod+tab\",\n  \"ctrl+tab\",\n  \"alt+f4\",\n]);\n\nconst MAC_GLYPHS: Record<string, string> = {\n  mod: \"⌘\",\n  meta: \"⌘\",\n  ctrl: \"⌃\",\n  alt: \"⌥\",\n  shift: \"⇧\",\n  enter: \"↵\",\n  backspace: \"⌫\",\n  delete: \"⌦\",\n  tab: \"⇥\",\n  escape: \"Esc\",\n  space: \"Space\",\n  up: \"↑\",\n  down: \"↓\",\n  left: \"←\",\n  right: \"→\",\n  home: \"Home\",\n  end: \"End\",\n  pageup: \"PgUp\",\n  pagedown: \"PgDn\",\n};\n\nconst PC_GLYPHS: Record<string, string> = {\n  mod: \"Ctrl\",\n  meta: \"Win\",\n  ctrl: \"Ctrl\",\n  alt: \"Alt\",\n  shift: \"Shift\",\n  enter: \"Enter\",\n  backspace: \"Bksp\",\n  delete: \"Del\",\n  tab: \"Tab\",\n  escape: \"Esc\",\n  space: \"Space\",\n  up: \"↑\",\n  down: \"↓\",\n  left: \"←\",\n  right: \"→\",\n  home: \"Home\",\n  end: \"End\",\n  pageup: \"PgUp\",\n  pagedown: \"PgDn\",\n};\n\nconst subscribeNoop = () => () => {};\nfunction detectMac(): boolean {\n  if (typeof navigator === \"undefined\") return true;\n  return /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent);\n}\n\n/** Extract a layout-safe canonical key token from a KeyboardEvent (uses event.code so Option+K stays \"k\", never \"˚\"). */\nfunction extractTriggerKey(e: KeyboardEvent | React.KeyboardEvent): string | null {\n  const code = e.code || \"\";\n  if (MOD_CODES.has(code) || IGNORED_CODES.has(code)) return null;\n  if (/^Key[A-Z]$/.test(code)) return code.slice(3).toLowerCase();\n  if (/^Digit[0-9]$/.test(code)) return code.slice(5);\n  if (/^F([1-9]|1[0-2])$/.test(code)) return code.toLowerCase();\n  if (code in CODE_TO_KEY) return CODE_TO_KEY[code];\n\n  const k = (e.key || \"\").toLowerCase();\n  if (!k || k === \"meta\" || k === \"control\" || k === \"alt\" || k === \"shift\" || k === \"dead\" || k === \"process\" || k === \"unidentified\") {\n    return null;\n  }\n  if (k in KEY_ALIASES) return KEY_ALIASES[k];\n  if (k.length === 1) return k;\n  if (NAV_OR_FUNC_RE.test(k)) return k;\n  return null;\n}\n\n/** Canonicalise any shortcut string (e.g. \"Shift+Cmd+k\" -> \"mod+shift+k\"). */\nexport function normalizeShortcut(shortcut: string | null | undefined): string | null {\n  if (!shortcut) return null;\n  const rawParts = shortcut\n    .split(\"+\")\n    .map((p) => p.trim().toLowerCase())\n    .filter(Boolean);\n  if (rawParts.length === 0) return null;\n\n  const mods = new Set<ModToken>();\n  let trigger: string | null = null;\n  for (const part of rawParts) {\n    if (part in MOD_ALIASES) {\n      mods.add(MOD_ALIASES[part]);\n    } else {\n      trigger = KEY_ALIASES[part] ?? part;\n    }\n  }\n  if (!trigger) return null;\n  const ordered: string[] = [];\n  for (const m of MOD_ORDER) {\n    if (mods.has(m)) ordered.push(m);\n  }\n  ordered.push(trigger);\n  return ordered.join(\"+\");\n}\n\nfunction splitTokens(shortcut: string | null | undefined): string[] {\n  const norm = normalizeShortcut(shortcut);\n  return norm ? norm.split(\"+\") : [];\n}\n\nfunction tokenLabel(token: string, platform: ShortcutPlatform): string {\n  const lower = token.toLowerCase();\n  const table = platform === \"mac\" ? MAC_GLYPHS : PC_GLYPHS;\n  if (lower in table) return table[lower];\n  if (FUNC_KEY_RE.test(lower)) return lower.toUpperCase();\n  return lower.length === 1 ? lower.toUpperCase() : lower[0].toUpperCase() + lower.slice(1);\n}\n\nfunction tokenSpoken(token: string, platform: ShortcutPlatform): string {\n  const lower = token.toLowerCase();\n  const isMac = platform === \"mac\";\n  if (lower === \"mod\") return isMac ? \"Command\" : \"Control\";\n  if (lower === \"meta\") return isMac ? \"Command\" : \"Windows\";\n  if (lower === \"ctrl\") return \"Control\";\n  if (lower === \"alt\") return isMac ? \"Option\" : \"Alt\";\n  if (lower === \"shift\") return \"Shift\";\n  if (lower === \"up\" || lower === \"down\" || lower === \"left\" || lower === \"right\") return `${lower} arrow`;\n  return tokenLabel(lower, \"other\");\n}\n\n/** Format a canonical shortcut string into platform-accurate display keycap labels. */\nexport function formatShortcut(shortcut: string | null | undefined, platform?: ShortcutPlatform): string[] {\n  const resolved: ShortcutPlatform = platform ?? (detectMac() ? \"mac\" : \"other\");\n  return splitTokens(shortcut).map((t) => tokenLabel(t, resolved));\n}\n\n/** Layout-safe matcher for binding a recorded shortcut to real KeyboardEvents in your app. */\nexport function matchesShortcut(\n  event: KeyboardEvent | React.KeyboardEvent,\n  shortcut: string | null | undefined,\n  platform?: ShortcutPlatform,\n): boolean {\n  const norm = normalizeShortcut(shortcut);\n  if (!norm) return false;\n  const parts = norm.split(\"+\");\n  const trigger = parts[parts.length - 1];\n  const mods = new Set(parts.slice(0, -1));\n  const isMac = (platform ?? (detectMac() ? \"mac\" : \"other\")) === \"mac\";\n\n  const wantMeta = (mods.has(\"mod\") && isMac) || mods.has(\"meta\");\n  const wantCtrl = (mods.has(\"mod\") && !isMac) || mods.has(\"ctrl\");\n  const wantAlt = mods.has(\"alt\");\n  const wantShift = mods.has(\"shift\");\n\n  if (event.metaKey !== wantMeta) return false;\n  if (event.ctrlKey !== wantCtrl) return false;\n  if (event.altKey !== wantAlt) return false;\n  if (event.shiftKey !== wantShift) return false;\n\n  const actualKey = extractTriggerKey(event);\n  return actualKey === trigger;\n}\n\n/* ── 8×8 Bayer optical well canvas utilities ── */\n\ntype Rgb = [number, number, number];\n\nconst BAYER8: Float32Array = (() => {\n  const m = [\n    [0, 32, 8, 40, 2, 34, 10, 42],\n    [48, 16, 56, 24, 50, 18, 58, 26],\n    [12, 44, 4, 36, 14, 46, 6, 38],\n    [60, 28, 52, 20, 62, 30, 54, 22],\n    [3, 35, 11, 43, 1, 33, 9, 41],\n    [51, 19, 59, 27, 49, 17, 57, 25],\n    [15, 47, 7, 39, 13, 45, 5, 37],\n    [63, 31, 55, 23, 61, 29, 53, 21],\n  ];\n  const out = new Float32Array(64);\n  for (let y = 0; y < 8; y++) {\n    for (let x = 0; x < 8; x++) {\n      out[(y << 3) | x] = (m[y][x] + 0.5) / 64;\n    }\n  }\n  return out;\n})();\n\nconst IS_LE = (() => {\n  const b = new ArrayBuffer(4);\n  new Uint32Array(b)[0] = 0x0a0b0c0d;\n  return new Uint8Array(b)[0] === 0x0d;\n})();\n\nfunction packRgba(r: number, g: number, b: number, a: number): number {\n  const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0;\n  const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0;\n  const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0;\n  const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0;\n  return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;\n}\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\nconst clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\n\nlet swatchCtx: CanvasRenderingContext2D | null = null;\nfunction cssToRgb(host: Element, cssColor: string, fallback: Rgb): Rgb {\n  const probe = document.createElement(\"span\");\n  probe.style.display = \"none\";\n  probe.style.color = cssColor;\n  host.appendChild(probe);\n  const resolved = getComputedStyle(probe).color;\n  probe.remove();\n  if (/^rgba?\\(/.test(resolved)) {\n    const m = resolved.match(/[\\d.]+/g)?.map(Number);\n    if (m && m.length >= 3) return [m[0], m[1], m[2]];\n  }\n  if (!swatchCtx) {\n    const c = document.createElement(\"canvas\");\n    c.width = 1;\n    c.height = 1;\n    swatchCtx = c.getContext(\"2d\", { willReadFrequently: true });\n  }\n  if (swatchCtx) {\n    swatchCtx.clearRect(0, 0, 1, 1);\n    swatchCtx.fillStyle = \"#808080\";\n    swatchCtx.fillStyle = resolved;\n    swatchCtx.fillRect(0, 0, 1, 1);\n    const d = swatchCtx.getImageData(0, 0, 1, 1).data;\n    return [d[0], d[1], d[2]];\n  }\n  return fallback;\n}\n\nfunction detectLightHost(el: Element | null): boolean {\n  if (!el) return false;\n  const rgb = cssToRgb(el, getComputedStyle(el).color, [240, 240, 240]);\n  return (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255 < 0.52;\n}\n\ntype FlashKind = \"none\" | \"lock\" | \"conflict\" | \"error\";\n\ninterface KeycapProps {\n  token: string;\n  platform: ShortcutPlatform;\n  pressed?: boolean;\n  tone?: \"default\" | \"conflict\";\n  reduced: boolean;\n}\n\nfunction Keycap({ token, platform, pressed = false, tone = \"default\", reduced }: KeycapProps) {\n  const text = tokenLabel(token, platform);\n  const isWide = text.length > 1;\n  return (\n    <span\n      aria-hidden=\"true\"\n      data-pressed={pressed ? \"true\" : undefined}\n      className={`inline-flex h-[26px] select-none items-center justify-center rounded-[7px] font-sans font-medium leading-none tracking-[-0.01em] ${\n        isWide ? \"min-w-[28px] px-2 text-[11.5px]\" : \"min-w-[26px] px-1.5 text-[12.5px]\"\n      } ${\n        pressed\n          ? \"translate-y-[1.5px] scale-[0.97] bg-[color-mix(in_oklab,var(--card)_86%,var(--foreground)_14%)] text-foreground shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--primary)_55%,var(--border)),inset_0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--primary)_60%,var(--border)),inset_0_1px_2px_rgb(0_0_0/0.45)]\"\n          : tone === \"conflict\"\n            ? \"-translate-y-[0.5px] bg-background text-amber-700 shadow-[inset_0_0_0_1px_rgb(245_158_11/0.45),0_2px_0_0_rgb(245_158_11/0.28),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:bg-[color-mix(in_oklab,var(--card)_88%,var(--foreground)_12%)] dark:text-amber-300 dark:shadow-[inset_0_0_0_1px_rgb(251_191_36/0.4),0_2px_0_0_rgb(0_0_0/0.65),inset_0_0.5px_0_rgb(255_255_255/0.1)]\"\n            : \"-translate-y-[0.5px] bg-background text-foreground shadow-[inset_0_0_0_1px_var(--border),0_2px_0_0_color-mix(in_oklab,var(--border)_85%,var(--foreground)_14%),inset_0_0.5px_0_rgb(255_255_255/0.85)] dark:bg-[color-mix(in_oklab,var(--card)_88%,var(--foreground)_12%)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.12),0_2px_0_0_rgb(0_0_0/0.72),inset_0_0.5px_0_rgb(255_255_255/0.12)]\"\n      }`}\n      style={{\n        transition: reduced\n          ? \"none\"\n          : `transform 140ms ${EASE_OUT}, box-shadow 140ms ${EASE_OUT}, background-color 140ms ${EASE_OUT}, color 140ms ${EASE_OUT}`,\n      }}\n    >\n      {text}\n    </span>\n  );\n}\n\nexport function ShortcutRecorder({\n  value: controlledValue,\n  defaultValue = null,\n  defaultShortcut,\n  onChange,\n  conflicts,\n  onConflictSwap,\n  requireModifier = true,\n  useMod = true,\n  clearable = true,\n  allowReserved = false,\n  reserved,\n  platform: platformProp,\n  label = \"Keyboard shortcut\",\n  placeholder = \"Add shortcut\",\n  disabled = false,\n  sound = false,\n  className = \"\",\n  ...props\n}: ShortcutRecorderProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();\n  const detectedMac = React.useSyncExternalStore(subscribeNoop, detectMac, () => true);\n  const platform: ShortcutPlatform = platformProp ?? (detectedMac ? \"mac\" : \"other\");\n  const isMac = platform === \"mac\";\n\n  const [ownValue, setOwnValue] = React.useState<string | null>(() => normalizeShortcut(defaultValue));\n  const value = controlledValue !== undefined ? normalizeShortcut(controlledValue) : ownValue;\n  const normDefault = React.useMemo(() => normalizeShortcut(defaultShortcut), [defaultShortcut]);\n\n  const [recording, setRecording] = React.useState(false);\n  const [heldMods, setHeldMods] = React.useState<ModToken[]>([]);\n  const [notice, setNotice] = React.useState<{ kind: \"error\" | \"conflict\"; message: string; shortcut?: string; action?: string } | null>(null);\n  const [liveStatus, setLiveStatus] = React.useState(\"\");\n\n  const wellRef = React.useRef<HTMLDivElement>(null);\n  const triggerBtnRef = React.useRef<HTMLButtonElement>(null);\n  const keyGroupRef = React.useRef<HTMLSpanElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n\n  const normalizedConflicts = React.useMemo(() => {\n    const map = new Map<string, string>();\n    if (!conflicts) return map;\n    for (const [rawKey, action] of Object.entries(conflicts)) {\n      const k = normalizeShortcut(rawKey);\n      if (k) map.set(k, action);\n    }\n    return map;\n  }, [conflicts]);\n\n  const reservedSet = React.useMemo(() => {\n    const set = new Set<string>(allowReserved ? [] : DEFAULT_RESERVED);\n    if (reserved) {\n      for (const item of reserved) {\n        const k = normalizeShortcut(item);\n        if (k) set.add(k);\n      }\n    }\n    return set;\n  }, [allowReserved, reserved]);\n\n  const cfgRef = React.useRef({ recording, heldCount: heldMods.length, reduced });\n  React.useLayoutEffect(() => {\n    cfgRef.current = { recording, heldCount: heldMods.length, reduced };\n  });\n\n  const engineRef = React.useRef<{\n    w: number;\n    h: number;\n    dpr: number;\n    isLight: boolean;\n    ink: Rgb;\n    primary: Rgb;\n    time: number;\n    listenMix: Spring;\n    chargeMix: Spring;\n    reboundY: Spring;\n    recoilX: Spring;\n    flashKind: FlashKind;\n    flashAge: number;\n    flashLife: number;\n    refreshTheme: () => void;\n    triggerFlash: (kind: Exclude<FlashKind, \"none\">) => void;\n    triggerRebound: () => void;\n    triggerRecoil: () => void;\n    stepAndDraw: (dt: number) => boolean;\n    wake: () => void;\n  } | null>(null);\n\n  const rafRef = React.useRef(0);\n  const runningRef = React.useRef(false);\n  const wakeRef = React.useRef<() => void>(() => {});\n\n  // Core 8×8 Bayer optical well sensor + tactile keycap rebound & recoil springs\n  React.useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!root || !canvas || !ctx) return;\n\n    const gridCanvas = document.createElement(\"canvas\");\n    const gridCtx = gridCanvas.getContext(\"2d\");\n    if (!gridCtx) return;\n    let gridImg: ImageData | null = null;\n    let gridU32: Uint32Array | null = null;\n    let gCols = 0;\n    let gRows = 0;\n\n    const ensureGrid = (cols: number, rows: number) => {\n      if (cols === gCols && rows === gRows && gridImg && gridU32) return;\n      gCols = cols;\n      gRows = rows;\n      gridCanvas.width = cols;\n      gridCanvas.height = rows;\n      gridImg = gridCtx.createImageData(cols, rows);\n      gridU32 = new Uint32Array(gridImg.data.buffer);\n    };\n\n    const wakeOnSpring = () => wakeRef.current();\n    const listenMix = createSpring(0, { stiffness: 180, damping: 24 }, wakeOnSpring, 0.002);\n    const chargeMix = createSpring(0, { stiffness: 220, damping: 22 }, wakeOnSpring, 0.002);\n    const reboundY = createSpring(\n      0,\n      { stiffness: 360, damping: 18 },\n      () => {\n        const el = keyGroupRef.current;\n        if (!el) return;\n        const y = reboundY.get();\n        el.style.transform = Math.abs(y) > 0.03 ? `translate3d(0, ${y.toFixed(2)}px, 0)` : \"\";\n      },\n      0.03,\n    );\n    const recoilX = createSpring(\n      0,\n      { stiffness: 460, damping: 16 },\n      () => {\n        const el = wellRef.current;\n        if (!el) return;\n        const x = recoilX.get();\n        el.style.transform = Math.abs(x) > 0.04 ? `translate3d(${x.toFixed(2)}px, 0, 0)` : \"\";\n      },\n      0.04,\n    );\n\n    const eng: NonNullable<typeof engineRef.current> = {\n      w: 0,\n      h: 0,\n      dpr: Math.min(2, window.devicePixelRatio || 1),\n      isLight: false,\n      ink: [164, 170, 182],\n      primary: [48, 93, 222],\n      time: 0.4,\n      listenMix,\n      chargeMix,\n      reboundY,\n      recoilX,\n      flashKind: \"none\",\n      flashAge: 0,\n      flashLife: 0.54,\n\n      refreshTheme() {\n        eng.isLight = detectLightHost(root);\n        eng.primary = cssToRgb(root, \"var(--primary)\", [48, 93, 222]);\n        eng.ink = eng.isLight ? [72, 80, 94] : [168, 174, 186];\n      },\n\n      triggerFlash(kind) {\n        if (cfgRef.current.reduced) return;\n        eng.flashKind = kind;\n        eng.flashAge = 0;\n        eng.flashLife = kind === \"error\" ? 0.44 : 0.56;\n        eng.wake();\n      },\n\n      triggerRebound() {\n        if (cfgRef.current.reduced) return;\n        eng.reboundY.jump(2.5);\n        eng.reboundY.set(0);\n        eng.reboundY.push(-34);\n      },\n\n      triggerRecoil() {\n        if (cfgRef.current.reduced) return;\n        eng.recoilX.jump(0);\n        eng.recoilX.set(0);\n        eng.recoilX.push(190);\n      },\n\n      stepAndDraw(dt: number): boolean {\n        const w = eng.w;\n        const h = eng.h;\n        if (w <= 0 || h <= 0) return false;\n\n        const { recording: isRec, reduced: isRed } = cfgRef.current;\n        const lm = clamp01(eng.listenMix.get());\n        const ch = clamp01(eng.chargeMix.get());\n\n        if ((isRec || lm > 0.01) && !isRed) eng.time += dt;\n\n        if (eng.flashKind !== \"none\" && dt > 0) {\n          eng.flashAge += dt;\n          if (eng.flashAge >= eng.flashLife) eng.flashKind = \"none\";\n        }\n\n        ctx.setTransform(eng.dpr, 0, 0, eng.dpr, 0, 0);\n        ctx.clearRect(0, 0, w, h);\n\n        const needsPaint = (lm > 0.01 || eng.flashKind !== \"none\") && !isRed;\n        if (needsPaint) {\n          const pitch = 1.5;\n          const cols = Math.max(1, Math.ceil(w / pitch));\n          const rows = Math.max(1, Math.ceil(h / pitch));\n          ensureGrid(cols, rows);\n          const u32 = gridU32!;\n          u32.fill(0);\n\n          const t = eng.time;\n          const fk = eng.flashKind !== \"none\" ? eng.flashAge / eng.flashLife : 0;\n          const flashFront = (1 - Math.pow(1 - fk, 2.2)) * 1.18 - 0.06;\n          const flashFade = Math.sin(Math.PI * Math.pow(fk, 0.72));\n\n          const listenRgb: Rgb = eng.isLight ? eng.primary : [118, 169, 250];\n          const lockRgb: Rgb = eng.isLight ? [5, 150, 105] : [52, 211, 153];\n          const conflictRgb: Rgb = eng.isLight ? [217, 119, 6] : [251, 191, 36];\n          const errRgb: Rgb = eng.isLight ? [220, 38, 38] : [248, 113, 113];\n          const flashRgb: Rgb = eng.flashKind === \"conflict\" ? conflictRgb : eng.flashKind === \"error\" ? errRgb : lockRgb;\n\n          // Subtle optical scanning crest while listening\n          const scanU = 0.5 + 0.42 * Math.sin(t * 1.35);\n\n          for (let r = 0; r < rows; r++) {\n            const cy = (r + 0.5) * pitch;\n            const v = cy / h;\n            // Low-slung bottom optical horizon while listening (clear upper canvas so prompts & keycaps stay crisp)\n            const floorV = Math.pow(clamp01((v - 0.28) / 0.72), 1.9);\n            const rimV = Math.pow(Math.abs(v - 0.5) * 2, 1.8);\n            const rowOff = r * cols;\n            const bRow = (r & 7) << 3;\n\n            for (let c = 0; c < cols; c++) {\n              const cx = (c + 0.5) * pitch;\n              const u = cx / w;\n\n              let density = 0;\n              let accentMix = 0;\n              let flashBoost = 0;\n\n              // A) Subtle recessed listening horizon along the lower well + localized floor charge under depressed modifiers\n              if (lm > 0.01) {\n                const wave = 0.55 + 0.45 * Math.sin(u * 8.5 - t * 2.2 + v * 2.4);\n                const scan = Math.exp(-((u - scanU) ** 2) / 0.085);\n                const baseHorizon = floorV * (0.28 + 0.24 * wave + 0.34 * scan);\n\n                // When modifiers are held down, brighten the optical floor right beneath the left keycap bay\n                const chargeReach = 0.22 + ch * 0.3;\n                const keyZone = ch > 0.01 ? Math.exp(-Math.pow(Math.max(0, u - chargeReach) / 0.14, 2)) * (0.22 + 0.78 * floorV) * ch * 0.48 : 0;\n\n                density = (baseHorizon + keyZone) * lm;\n                accentMix = clamp01((scan * 0.65 + ch * 0.8) * lm);\n              }\n\n              // B) Lock-in emerald / conflict amber / error rose Bayer wavefront across entire capture well\n              if (eng.flashKind !== \"none\") {\n                if (eng.flashKind === \"error\") {\n                  // Symmetrical outer-edge recoil pulse\n                  const edge = Math.pow(1 - Math.min(u, 1 - u) * 2, 2.0) * 0.72 + rimV * 0.38;\n                  flashBoost = edge * flashFade * 0.85;\n                } else {\n                  const df = u - flashFront;\n                  const lead = Math.exp(-(df * df) / 0.018);\n                  const tail = df < 0 ? Math.exp(df / 0.22) * 0.48 : 0;\n                  flashBoost = (lead + tail) * flashFade * (0.42 + 0.58 * rimV + 0.22 * (1 - rimV));\n                }\n                if (flashBoost * 0.78 > density) density = flashBoost * 0.78;\n              }\n\n              if (density <= 0.035) continue;\n              const bayer = BAYER8[bRow | (c & 7)];\n              const hit = clamp01((density - bayer + 0.05) / 0.12);\n              if (hit <= 0.02) continue;\n\n              let cr = lerp(eng.ink[0], listenRgb[0], accentMix * 0.88);\n              let cg = lerp(eng.ink[1], listenRgb[1], accentMix * 0.88);\n              let cb = lerp(eng.ink[2], listenRgb[2], accentMix * 0.88);\n\n              if (flashBoost > 0.04) {\n                const fm = clamp01(flashBoost * 1.15);\n                cr = lerp(cr, flashRgb[0], fm);\n                cg = lerp(cg, flashRgb[1], fm);\n                cb = lerp(cb, flashRgb[2], fm);\n              }\n\n              const baseAlpha = eng.isLight ? 0.38 : 0.46;\n              const alpha = hit * clamp01(baseAlpha + accentMix * 0.24 + flashBoost * 0.38);\n              u32[rowOff + c] = packRgba(cr, cg, cb, alpha * 255);\n            }\n          }\n\n          gridCtx.putImageData(gridImg!, 0, 0);\n          ctx.save();\n          ctx.imageSmoothingEnabled = false;\n          ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch);\n          ctx.restore();\n        }\n\n        const springsPending =\n          Math.abs(eng.listenMix.getTarget() - lm) > 0.002 ||\n          Math.abs(eng.chargeMix.getTarget() - ch) > 0.002 ||\n          Math.abs(eng.listenMix.getVelocity()) > 0.004 ||\n          Math.abs(eng.chargeMix.getVelocity()) > 0.004;\n\n        return !isRed && (springsPending || isRec || lm > 0.01 || eng.flashKind !== \"none\");\n      },\n\n      wake() {\n        wakeRef.current();\n      },\n    };\n\n    engineRef.current = eng;\n\n    const resize = () => {\n      const rect = canvas.getBoundingClientRect();\n      const nw = Math.round(rect.width);\n      const nh = Math.round(rect.height);\n      if (nw <= 0 || nh <= 0) return;\n      const dpr = Math.min(2, window.devicePixelRatio || 1);\n      if (nw !== eng.w || nh !== eng.h || dpr !== eng.dpr) {\n        eng.w = nw;\n        eng.h = nh;\n        eng.dpr = dpr;\n        canvas.width = Math.round(nw * dpr);\n        canvas.height = Math.round(nh * dpr);\n      }\n      eng.refreshTheme();\n      eng.stepAndDraw(0);\n    };\n\n    resize();\n    const ro = new ResizeObserver(resize);\n    ro.observe(canvas);\n\n    const mo = new MutationObserver(() => {\n      eng.refreshTheme();\n      eng.stepAndDraw(0);\n    });\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n\n    return () => {\n      ro.disconnect();\n      mo.disconnect();\n      listenMix.stop();\n      chargeMix.stop();\n      reboundY.stop();\n      recoilX.stop();\n      engineRef.current = null;\n    };\n  }, [rootRef]);\n\n  // Drive optical well springs when recording / held modifiers change\n  React.useEffect(() => {\n    const eng = engineRef.current;\n    if (!eng) return;\n    if (reduced) {\n      eng.listenMix.jump(recording ? 1 : 0);\n      eng.chargeMix.jump(Math.min(1, heldMods.length / 2.5));\n      eng.stepAndDraw(0);\n      return;\n    }\n    eng.listenMix.set(recording ? 1 : 0);\n    eng.chargeMix.set(recording ? Math.min(1, heldMods.length / 2.5) : 0);\n    eng.wake();\n  }, [recording, heldMods.length, reduced]);\n\n  // Synchronized lock-in rebound when an external controlled value changes (e.g. partner row during a Swap)\n  const prevValueRef = React.useRef<string | null | undefined>(undefined);\n  const internalCommitRef = React.useRef(false);\n  React.useEffect(() => {\n    if (prevValueRef.current === undefined) {\n      prevValueRef.current = value;\n      return;\n    }\n    if (prevValueRef.current !== value) {\n      prevValueRef.current = value;\n      if (!internalCommitRef.current && value) {\n        engineRef.current?.triggerRebound();\n        engineRef.current?.triggerFlash(\"lock\");\n      }\n      internalCommitRef.current = false;\n    }\n  }, [value]);\n\n  // Canvas animation frame loop (sleeps completely at rest!)\n  React.useEffect(() => {\n    if (!onScreen || reduced) {\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n      if (reduced) engineRef.current?.stepAndDraw(0);\n      return;\n    }\n\n    let last = 0;\n    const tick = (now: number) => {\n      const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60;\n      last = now;\n      const eng = engineRef.current;\n      if (!eng) {\n        rafRef.current = 0;\n        runningRef.current = false;\n        return;\n      }\n      if (eng.stepAndDraw(dt)) {\n        rafRef.current = requestAnimationFrame(tick);\n      } else {\n        rafRef.current = 0;\n        runningRef.current = false;\n      }\n    };\n\n    const start = () => {\n      if (runningRef.current) return;\n      runningRef.current = true;\n      last = 0;\n      rafRef.current = requestAnimationFrame(tick);\n    };\n    wakeRef.current = start;\n    if (cfgRef.current.recording) start();\n\n    return () => {\n      wakeRef.current = () => {};\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n    };\n  }, [onScreen, reduced]);\n\n  const commitShortcut = React.useCallback(\n    (next: string | null, announce?: string) => {\n      const norm = normalizeShortcut(next);\n      internalCommitRef.current = true;\n      if (controlledValue === undefined) setOwnValue(norm);\n      onChange?.(norm);\n      setRecording(false);\n      setHeldMods([]);\n      setNotice(null);\n      if (norm) {\n        engineRef.current?.triggerRebound();\n        engineRef.current?.triggerFlash(\"lock\");\n        if (sound) playSound(\"success\", 0.36);\n        const spoken = splitTokens(norm)\n          .map((t) => tokenSpoken(t, platform))\n          .join(\" \");\n        setLiveStatus(announce ?? `${label} set to ${spoken}`);\n      } else {\n        if (sound) playSound(\"fold\", 0.3);\n        setLiveStatus(announce ?? `${label} cleared`);\n      }\n    },\n    [controlledValue, onChange, sound, platform, label],\n  );\n\n  const cancelRecording = React.useCallback(() => {\n    setRecording(false);\n    setHeldMods([]);\n    setNotice((prev) => (prev?.kind === \"error\" ? null : prev));\n    setLiveStatus(\"Recording cancelled\");\n  }, []);\n\n  const armRecording = React.useCallback(() => {\n    if (disabled) return;\n    setNotice(null);\n    setHeldMods([]);\n    setRecording(true);\n    if (sound) playSound(\"tick\", 0.32);\n    setLiveStatus(`Recording ${label}. Press a key combination, or Escape to cancel.`);\n    triggerBtnRef.current?.focus();\n  }, [disabled, sound, label]);\n\n  // Global key capture while armed + safe click-outside / blur exit\n  React.useEffect(() => {\n    if (!recording) return;\n\n    const readModifiers = (e: KeyboardEvent): ModToken[] => {\n      const list: ModToken[] = [];\n      if (useMod) {\n        const modActive = isMac ? e.metaKey : e.ctrlKey;\n        if (modActive) list.push(\"mod\");\n        if (isMac && e.ctrlKey) list.push(\"ctrl\");\n        if (!isMac && e.metaKey) list.push(\"meta\");\n      } else {\n        if (e.ctrlKey) list.push(\"ctrl\");\n        if (e.metaKey) list.push(\"meta\");\n      }\n      if (e.altKey) list.push(\"alt\");\n      if (e.shiftKey) list.push(\"shift\");\n      return list;\n    };\n\n    const onKeyDown = (e: KeyboardEvent) => {\n      e.preventDefault();\n      e.stopPropagation();\n\n      const mods = readModifiers(e);\n\n      // Bare Escape always cancels cleanly without wiping the previous binding\n      if (e.key === \"Escape\" && mods.length === 0) {\n        if (sound) playSound(\"fold\", 0.28);\n        cancelRecording();\n        return;\n      }\n\n      // Bare Backspace / Delete clears when clearable\n      if ((e.key === \"Backspace\" || e.key === \"Delete\") && mods.length === 0 && clearable) {\n        commitShortcut(null);\n        return;\n      }\n\n      // Update live physically-depressed modifier keycaps\n      const isModifierOnly = MOD_CODES.has(e.code) || e.key === \"Meta\" || e.key === \"Control\" || e.key === \"Alt\" || e.key === \"Shift\";\n      if (isModifierOnly) {\n        setHeldMods((prev) => {\n          const same = prev.length === mods.length && prev.every((m, idx) => m === mods[idx]);\n          if (!same) {\n            if (sound && mods.length > prev.length) playSound(\"tick\", 0.34);\n            setNotice(null);\n          }\n          return same ? prev : mods;\n        });\n        return;\n      }\n\n      const trigger = extractTriggerKey(e);\n      if (!trigger) return;\n\n      // Validate modifier requirement for printable keys (F1..F12 and nav keys with Shift are always allowed)\n      const hasPrimaryMod = mods.some((m) => m === \"mod\" || m === \"ctrl\" || m === \"alt\" || m === \"meta\");\n      const isFuncKey = FUNC_KEY_RE.test(trigger);\n      const isNavWithShift = NAV_OR_FUNC_RE.test(trigger) && mods.includes(\"shift\");\n\n      if (requireModifier && !hasPrimaryMod && !isFuncKey && !isNavWithShift) {\n        const hint = isMac ? \"Include ⌘, ⌥ or ⌃\" : \"Include Ctrl or Alt\";\n        setNotice({ kind: \"error\", message: hint });\n        setLiveStatus(hint);\n        engineRef.current?.triggerFlash(\"error\");\n        engineRef.current?.triggerRecoil();\n        if (sound) playSound(\"error\", 0.34);\n        return;\n      }\n\n      const candidate = normalizeShortcut([...mods, trigger].join(\"+\"));\n      if (!candidate) return;\n\n      // Guard browser-reserved chords\n      if (reservedSet.has(candidate)) {\n        const readable = formatShortcut(candidate, platform).join(isMac ? \"\" : \"+\");\n        const msg = `${readable} is reserved by the browser`;\n        setNotice({ kind: \"error\", message: msg });\n        setLiveStatus(msg);\n        engineRef.current?.triggerFlash(\"error\");\n        engineRef.current?.triggerRecoil();\n        if (sound) playSound(\"error\", 0.34);\n        return;\n      }\n\n      // Same shortcut as already bound -> clean tactile confirmation without firing unnecessary conflict\n      if (candidate === value) {\n        commitShortcut(candidate);\n        return;\n      }\n\n      // Live conflict detection against sibling bindings\n      const conflictAction = normalizedConflicts.get(candidate);\n      if (conflictAction) {\n        setRecording(false);\n        setHeldMods([]);\n        setNotice({\n          kind: \"conflict\",\n          message: `Used by ${conflictAction}`,\n          shortcut: candidate,\n          action: conflictAction,\n        });\n        engineRef.current?.triggerRebound();\n        engineRef.current?.triggerFlash(\"conflict\");\n        if (sound) playSound(\"pop\", 0.34);\n        setLiveStatus(`Conflict: already used by ${conflictAction}.`);\n        return;\n      }\n\n      commitShortcut(candidate);\n    };\n\n    const onKeyUp = (e: KeyboardEvent) => {\n      const mods = readModifiers(e);\n      setHeldMods((prev) => (prev.length === mods.length && prev.every((m, i) => m === mods[i]) ? prev : mods));\n    };\n\n    const onPointerDown = (e: PointerEvent) => {\n      if (rootRef.current && !rootRef.current.contains(e.target as Node)) {\n        cancelRecording();\n      }\n    };\n\n    const onWindowBlur = () => cancelRecording();\n\n    window.addEventListener(\"keydown\", onKeyDown, true);\n    window.addEventListener(\"keyup\", onKeyUp, true);\n    window.addEventListener(\"pointerdown\", onPointerDown, true);\n    window.addEventListener(\"blur\", onWindowBlur);\n    return () => {\n      window.removeEventListener(\"keydown\", onKeyDown, true);\n      window.removeEventListener(\"keyup\", onKeyUp, true);\n      window.removeEventListener(\"pointerdown\", onPointerDown, true);\n      window.removeEventListener(\"blur\", onWindowBlur);\n    };\n  }, [\n    recording,\n    useMod,\n    isMac,\n    clearable,\n    requireModifier,\n    reservedSet,\n    platform,\n    value,\n    normalizedConflicts,\n    sound,\n    cancelRecording,\n    commitShortcut,\n    rootRef,\n  ]);\n\n  const handleConflictSwap = () => {\n    if (!notice || notice.kind !== \"conflict\" || !notice.shortcut || !notice.action) return;\n    const { shortcut, action } = notice;\n    const norm = normalizeShortcut(shortcut);\n    internalCommitRef.current = true;\n    if (controlledValue === undefined) setOwnValue(norm);\n    onConflictSwap?.(shortcut, action);\n    setRecording(false);\n    setHeldMods([]);\n    setNotice(null);\n    engineRef.current?.triggerRebound();\n    engineRef.current?.triggerFlash(\"lock\");\n    if (sound) playSound(\"success\", 0.36);\n    setLiveStatus(`Swapped with ${action}`);\n  };\n\n  const handleDismissNotice = () => {\n    setNotice(null);\n    if (sound) playSound(\"fold\", 0.26);\n    setLiveStatus(\"Kept existing shortcut\");\n  };\n\n  const showReset = !disabled && !recording && normDefault !== null && value !== normDefault;\n  const showClear = !disabled && clearable && (recording || Boolean(value));\n\n  const displayTokens = React.useMemo(() => {\n    if (recording) return heldMods;\n    if (notice?.kind === \"conflict\" && notice.shortcut) return splitTokens(notice.shortcut);\n    return splitTokens(value);\n  }, [recording, heldMods, notice, value]);\n\n  const spokenCurrent = value\n    ? splitTokens(value)\n        .map((t) => tokenSpoken(t, platform))\n        .join(\" \")\n    : \"Not set\";\n\n  const wellStateBorder = recording\n    ? \"border-foreground/25\"\n    : notice?.kind === \"conflict\"\n      ? \"border-amber-500/45 dark:border-amber-400/40\"\n      : notice?.kind === \"error\"\n        ? \"border-red-500/40 dark:border-red-400/40\"\n        : \"border-border hover:border-foreground/20\";\n\n  return (\n    <div ref={rootRef} className={`flex w-full flex-col ${className}`} {...props}>\n      <div\n        ref={wellRef}\n        data-recording={recording ? \"true\" : \"false\"}\n        data-conflict={notice?.kind === \"conflict\" ? \"true\" : undefined}\n        className={`relative flex h-11 w-full items-center rounded-[13px] border bg-card text-card-foreground transition-[border-color,box-shadow,background-color] duration-200 ${wellStateBorder} ${\n          recording\n            ? MATERIAL_RECESS\n            : \"shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)]\"\n        } ${disabled ? \"opacity-55\" : \"\"}`}\n      >\n        {/* Optical 8×8 Bayer sensor inlaid behind keycaps (0% CPU / transparent at rest) */}\n        <canvas\n          ref={canvasRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-1 z-0 h-[calc(100%_-_8px)] w-[calc(100%_-_8px)] rounded-[9px]\"\n        />\n\n        {/* Full-width interactive capture trigger */}\n        <button\n          ref={triggerBtnRef}\n          type=\"button\"\n          disabled={disabled}\n          aria-label={recording ? `Recording ${label}. Press keys, or Escape to cancel.` : `${label}, ${spokenCurrent}. Activate to record.`}\n          aria-pressed={recording}\n          onClick={() => (recording ? cancelRecording() : armRecording())}\n          className={`relative z-10 flex h-full min-w-0 flex-1 items-center justify-between gap-2 rounded-[12px] pl-3 pr-2 text-left ${\n            disabled ? \"cursor-not-allowed\" : \"cursor-pointer\"\n          } ${INTERACTION_FOCUS}`}\n        >\n          <span ref={keyGroupRef} className=\"inline-flex min-w-0 items-center gap-1.5\">\n            {recording ? (\n              heldMods.length > 0 ? (\n                <>\n                  {heldMods.map((mod) => (\n                    <Keycap key={mod} token={mod} platform={platform} pressed reduced={reduced} />\n                  ))}\n                  {/* Waiting keycap slot inviting the trigger key */}\n                  <span\n                    aria-hidden=\"true\"\n                    className=\"inline-flex h-[26px] min-w-[26px] items-center justify-center rounded-[7px] border border-dashed border-foreground/25 bg-card px-1.5 text-[11px] font-medium text-muted-foreground\"\n                  >\n                    +\n                  </span>\n                </>\n              ) : (\n                <span className=\"inline-flex items-center gap-2 text-[13px] text-muted-foreground\">\n                  <span\n                    aria-hidden=\"true\"\n                    className=\"size-1.5 animate-pulse rounded-full bg-primary motion-reduce:animate-none\"\n                  />\n                  Press keys…\n                </span>\n              )\n            ) : displayTokens.length > 0 ? (\n              displayTokens.map((tok, i) => (\n                <Keycap\n                  key={`${tok}-${i}`}\n                  token={tok}\n                  platform={platform}\n                  tone={notice?.kind === \"conflict\" ? \"conflict\" : \"default\"}\n                  reduced={reduced}\n                />\n              ))\n            ) : (\n              <span className=\"text-[13px] text-muted-foreground\">{placeholder}</span>\n            )}\n          </span>\n\n          {recording && (\n            <span aria-hidden=\"true\" className=\"shrink-0 rounded-[5px] border border-border bg-card px-1.5 py-0.5 text-[10.5px] font-medium text-muted-foreground\">\n              Esc\n            </span>\n          )}\n        </button>\n\n        {/* Quiet inline utility actions (Reset to default & Clear) */}\n        {(showReset || showClear) && (\n          <div className=\"relative z-10 flex shrink-0 items-center gap-0.5 pr-1.5\">\n            {showReset && (\n              <button\n                type=\"button\"\n                aria-label={`Reset ${label} to default`}\n                title=\"Reset to default\"\n                onMouseDown={(e) => e.preventDefault()}\n                onClick={() => commitShortcut(normDefault, `${label} reset to default`)}\n                className={`flex size-7 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <RotateCcw className=\"size-[13.5px]\" strokeWidth={1.9} />\n              </button>\n            )}\n            {showClear && (\n              <button\n                type=\"button\"\n                aria-label={`Clear ${label}`}\n                title=\"Clear shortcut\"\n                onMouseDown={(e) => e.preventDefault()}\n                onClick={() => commitShortcut(null)}\n                className={`flex size-7 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <X className=\"size-[14px]\" strokeWidth={1.9} />\n              </button>\n            )}\n          </div>\n        )}\n      </div>\n\n      {/* Inline hairline fold for live conflict resolution (1-click Swap) or validation errors */}\n      <div\n        aria-hidden={!notice || undefined}\n        className={`grid ${!notice ? \"pointer-events-none\" : \"\"}`}\n        style={{\n          gridTemplateRows: notice ? \"1fr\" : \"0fr\",\n          opacity: notice ? 1 : 0,\n          transition: reduced ? \"none\" : `grid-template-rows 260ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,\n        }}\n      >\n        <div className=\"min-h-0 overflow-hidden\">\n          {notice?.kind === \"conflict\" ? (\n            <div className=\"flex flex-wrap items-center justify-between gap-x-2 gap-y-1 px-1 pt-1.5\">\n              <p role=\"alert\" className=\"text-[12px] leading-5 text-amber-700 dark:text-amber-300\">\n                {notice.message}\n              </p>\n              <div className=\"flex shrink-0 items-center gap-1\">\n                {onConflictSwap && (\n                  <button\n                    type=\"button\"\n                    onClick={handleConflictSwap}\n                    className={`inline-flex h-6 cursor-pointer items-center gap-1 rounded-[7px] border border-border bg-card px-2 text-[11.5px] font-medium text-foreground hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                  >\n                    <ArrowLeftRight className=\"size-3 text-muted-foreground\" strokeWidth={2} aria-hidden=\"true\" />\n                    Swap\n                  </button>\n                )}\n                <button\n                  type=\"button\"\n                  onClick={handleDismissNotice}\n                  className={`inline-flex h-6 cursor-pointer items-center rounded-[7px] px-1.5 text-[11.5px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                >\n                  Cancel\n                </button>\n              </div>\n            </div>\n          ) : (\n            <p role=\"alert\" className=\"px-1 pt-1.5 text-[12px] leading-5 text-red-600 dark:text-red-400\">\n              {notice?.message ?? \"\"}\n            </p>\n          )}\n        </div>\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {liveStatus}\n      </span>\n    </div>\n  );\n}\n\nexport default ShortcutRecorder;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · shortcut-recorder · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · shortcut-recorder · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * UI SOUNDS: small interface sounds, made in code\n *\n * No files and nothing to license: every sound is built from a\n * tone or a burst of noise with the Web Audio API the moment it\n * plays. They're short and quiet, made to sit under an interface,\n * and components only play them when you pass `sound`.\n *\n *   fold     paper creasing: two short crisp bursts\n *   unfold   paper opening: a soft rising sweep\n *   drop     something small landing: a low, soft knock\n *   tick     a light click\n *   pop      a quick bright blip\n *   success  two soft rising notes\n *   error    two low falling notes\n *\n * Browsers only start audio after the visitor has pressed\n * something on the page, so a sound before that stays silent.\n * ───────────────────────────────────────────────────────── */\n\nexport type UiSound = \"fold\" | \"unfold\" | \"drop\" | \"tick\" | \"pop\" | \"success\" | \"error\";\n\nlet context: AudioContext | null = null;\nlet noise: AudioBuffer | null = null;\n\nfunction audio() {\n  if (typeof window === \"undefined\") return null;\n  if (!context) {\n    const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!Ctx) return null;\n    context = new Ctx();\n  }\n  if (context.state === \"suspended\") void context.resume().catch(() => {});\n  return context;\n}\n\nfunction noiseBuffer(ctx: AudioContext) {\n  if (noise && noise.sampleRate === ctx.sampleRate) return noise;\n  noise = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 0.5), ctx.sampleRate);\n  const data = noise.getChannelData(0);\n  for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n  return noise;\n}\n\n/** A burst of filtered noise. */\nfunction burst(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"bandpass\", from = 2000, to = from, q = 0.9, level = 0.5 }: { type?: BiquadFilterType; from?: number; to?: number; q?: number; level?: number }) {\n  const src = ctx.createBufferSource();\n  src.buffer = noiseBuffer(ctx);\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(from, at);\n  filter.frequency.exponentialRampToValueAtTime(Math.max(40, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + Math.min(0.012, length / 3));\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  src.connect(filter).connect(gain).connect(out);\n  src.start(at, Math.random() * 0.3, length + 0.02);\n}\n\n/** A tone that glides from one pitch to another. */\nfunction tone(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"sine\", from, to = from, level = 0.4 }: { type?: OscillatorType; from: number; to?: number; level?: number }) {\n  const osc = ctx.createOscillator();\n  osc.type = type;\n  osc.frequency.setValueAtTime(from, at);\n  osc.frequency.exponentialRampToValueAtTime(Math.max(20, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + 0.006);\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  osc.connect(gain).connect(out);\n  osc.start(at);\n  osc.stop(at + length + 0.02);\n}\n\n/** Plays one sound. `volume` is 0 to 1; the default sits quietly under an interface. */\nexport function playSound(name: UiSound, volume = 0.5) {\n  const ctx = audio();\n  if (!ctx) return;\n  const out = ctx.createGain();\n  out.gain.value = Math.max(0, Math.min(1, volume)) * 0.5;\n  out.connect(ctx.destination);\n  const t = ctx.currentTime + 0.005;\n  switch (name) {\n    case \"fold\":\n      burst(ctx, out, t, 0.05, { type: \"highpass\", from: 2600, q: 0.7, level: 0.45 });\n      burst(ctx, out, t + 0.07, 0.07, { type: \"bandpass\", from: 3200, to: 1800, q: 1.2, level: 0.35 });\n      break;\n    case \"unfold\":\n      burst(ctx, out, t, 0.16, { type: \"bandpass\", from: 900, to: 2800, q: 0.8, level: 0.3 });\n      break;\n    case \"drop\":\n      tone(ctx, out, t, 0.12, { from: 180, to: 70, level: 0.55 });\n      burst(ctx, out, t, 0.03, { type: \"lowpass\", from: 1200, q: 0.5, level: 0.2 });\n      break;\n    case \"tick\":\n      tone(ctx, out, t, 0.025, { type: \"triangle\", from: 1900, to: 1500, level: 0.25 });\n      break;\n    case \"pop\":\n      tone(ctx, out, t, 0.06, { from: 620, to: 980, level: 0.3 });\n      break;\n    case \"success\":\n      tone(ctx, out, t, 0.11, { from: 660, level: 0.22 });\n      tone(ctx, out, t + 0.09, 0.16, { from: 990, level: 0.22 });\n      break;\n    case \"error\":\n      tone(ctx, out, t, 0.12, { type: \"triangle\", from: 330, level: 0.25 });\n      tone(ctx, out, t + 0.1, 0.18, { type: \"triangle\", from: 247, level: 0.25 });\n      break;\n  }\n  window.setTimeout(() => out.disconnect(), 600);\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/shortcut-recorder. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}