{"$schema":"https:\/\/ui.particle.academy\/schema\/registry-item.json","name":"hotkey-capture","type":"registry:ui","title":"HotkeyCapture","description":"Records a keyboard shortcut as a normalised string; controlled, keycap display, Escape cancels, announced politely.","package":"react-fancy","dependencies":["tailwind-merge"],"registryDependencies":["kbd"],"files":[{"path":"components\/fancy\/hotkey-capture\/HotkeyCapture.tsx","content":"import { forwardRef, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"..\/lib\/utils\/cn\";\nimport { fillLabel } from \"..\/lib\/utils\/label-template\";\nimport { visuallyHidden } from \"..\/lib\/utils\/visually-hidden\";\nimport { browserPlatformHints, detectPlatform, type FancyPlatform } from \"..\/lib\/utils\/platform\";\nimport { useControllableState } from \"..\/lib\/hooks\/use-controllable-state\";\nimport { Kbd } from \"..\/kbd\";\nimport {\n  APPLE_KEY_NAMES,\n  comboFromEvent,\n  DEFAULT_KEY_NAMES,\n  formatHotkey,\n  hotkeyCaps as capsFor,\n  parseHotkey,\n  type HotkeyCombo,\n} from \".\/hotkey\";\nimport type { HotkeyCaptureLabels, HotkeyCaptureProps } from \".\/HotkeyCapture.types\";\n\nconst DEFAULT_LABELS: Required<Omit<HotkeyCaptureLabels, \"keys\">> = {\n  label: \"Keyboard shortcut\",\n  empty: \"Not set\",\n  prompt: \"Press the keys\u2026\",\n  captured: \"Shortcut set to {combo}\",\n  cancelled: \"Cancelled\",\n  cleared: \"Shortcut cleared\",\n  clear: \"Clear shortcut\",\n  trigger: \"{label}: {combo}\",\n};\n\n\/**\n * HotkeyCapture \u2014 records a keyboard shortcut (CC-fancy-0022).\n *\n * Click it (or press Enter or Space on it) and it captures the next key\n * combination. A modifier pressed alone only shows as held; the first\n * non-modifier key commits. Escape, or moving focus away, cancels and leaves\n * the previous value untouched \u2014 nothing is written until a capture commits,\n * so \"restore\" is simply not having changed it.\n *\n * The value is a normalised string, `\"ctrl+shift+k\"`; see `parseHotkey`.\n *\/\nexport const HotkeyCapture = forwardRef<HTMLDivElement, HotkeyCaptureProps>(function HotkeyCapture(\n  {\n    value: controlledValue,\n    defaultValue = \"\",\n    onChange,\n    label,\n    clearable = true,\n    disabled = false,\n    name,\n    platform,\n    labels,\n    size = \"sm\",\n    className,\n    ...rest\n  },\n  ref,\n) {\n  const [value, setValue] = useControllableState(controlledValue, defaultValue, onChange);\n  const [capturing, setCapturing] = useState(false);\n  const [held, setHeld] = useState<Partial<HotkeyCombo>>({});\n  const [announcement, setAnnouncement] = useState(\"\");\n  const triggerRef = useRef<HTMLButtonElement>(null);\n\n  \/\/ Resolved after mount, never during render, so the server's HTML and the\n  \/\/ first client render agree. The default names keys every keyboard has.\n  const [detected, setDetected] = useState<FancyPlatform>(\"generic\");\n  useEffect(() => {\n    if (platform) return;\n    setDetected(detectPlatform(browserPlatformHints()));\n  }, [platform]);\n  const apple = (platform ?? detected) === \"apple\";\n\n  const words = { ...DEFAULT_LABELS, ...labels };\n  const names: Record<string, string> = {\n    ...DEFAULT_KEY_NAMES,\n    ...(apple ? APPLE_KEY_NAMES : {}),\n    ...(labels?.keys as Record<string, string> | undefined),\n  };\n\n  const combo = parseHotkey(value);\n  const normalised = formatHotkey(combo);\n  const caps = combo ? capsFor(combo, names) : [];\n  const spoken = caps.join(\"+\");\n  const heldCaps = capsFor(held, names);\n\n  const start = () => {\n    if (disabled) return;\n    setHeld({});\n    setCapturing(true);\n  };\n\n  const stop = (message: string) => {\n    setCapturing(false);\n    setHeld({});\n    setAnnouncement(message);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {\n    if (disabled) return;\n    if (!capturing) {\n      if (e.key === \"Enter\" || e.key === \" \") {\n        \/\/ Claimed here so the button's own activation does not toggle it twice.\n        e.preventDefault();\n        start();\n      }\n      return;\n    }\n\n    \/\/ While capturing, every key belongs to the capture: nothing else on the\n    \/\/ page (a palette, a modal's Escape) should act on it.\n    e.preventDefault();\n    e.stopPropagation();\n\n    if (e.key === \"Escape\" && !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {\n      stop(words.cancelled);\n      return;\n    }\n\n    const next = comboFromEvent(e);\n    if (!next) {\n      setHeld({ ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, meta: e.metaKey });\n      return;\n    }\n\n    setValue(formatHotkey(next));\n    stop(fillLabel(words.captured, { combo: capsFor(next, names).join(\"+\") }));\n    \/\/ A button activates on Space's keyup: without this, capturing Space would\n    \/\/ start a fresh capture the moment the key comes back up.\n    swallowKeyUp.current = true;\n  };\n\n  const swallowKeyUp = useRef(false);\n  const onKeyUp = (e: React.KeyboardEvent<HTMLButtonElement>) => {\n    if (capturing || swallowKeyUp.current) e.preventDefault();\n    swallowKeyUp.current = false;\n  };\n\n  const shown = capturing ? words.prompt : spoken || words.empty;\n\n  return (\n    <div\n      ref={ref}\n      data-react-fancy-hotkey-capture=\"\"\n      data-state={capturing ? \"capturing\" : \"idle\"}\n      data-value={normalised}\n      className={cn(\"relative inline-flex items-center gap-1.5\", className)}\n      {...rest}\n    >\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        data-react-fancy-hotkey-capture-trigger=\"\"\n        disabled={disabled}\n        aria-pressed={capturing}\n        aria-label={fillLabel(words.trigger, { label: label ?? words.label, combo: shown })}\n        onClick={() => (capturing ? undefined : start())}\n        onKeyDown={onKeyDown}\n        onKeyUp={onKeyUp}\n        onBlur={() => {\n          if (capturing) stop(words.cancelled);\n        }}\n        className={cn(\n          \"inline-flex min-h-8 min-w-[6rem] items-center gap-1.5 rounded-md border px-2 py-1 text-sm transition\",\n          \"border-[color:var(--fancy-border-strong,var(--color-zinc-500))] bg-[color:var(--fancy-surface,var(--color-white))]\",\n          \"text-[color:var(--fancy-text-soft,var(--color-zinc-700))]\",\n          \"dark:border-[color:var(--fancy-border-strong-dark,var(--color-zinc-500))] dark:bg-[color:var(--fancy-surface-dark,var(--color-zinc-900))] dark:text-[color:var(--fancy-text-soft-dark,var(--color-zinc-300))]\",\n          \"focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-[color:var(--fancy-focus,var(--color-blue-500))] dark:focus-visible:ring-[color:var(--fancy-focus-dark,var(--color-blue-400))]\",\n          \"cursor-pointer disabled:cursor-not-allowed disabled:opacity-50\",\n          capturing && \"border-[color:var(--fancy-focus,var(--color-blue-500))] dark:border-[color:var(--fancy-focus-dark,var(--color-blue-400))]\",\n        )}\n      >\n        {capturing ? (\n          <>\n            {heldCaps.length > 0 && <Kbd keys={heldCaps} size={size} \/>}\n            <span data-react-fancy-hotkey-capture-prompt=\"\">{words.prompt}<\/span>\n          <\/>\n        ) : caps.length > 0 ? (\n          <Kbd keys={caps} size={size} \/>\n        ) : (\n          <span data-react-fancy-hotkey-capture-empty=\"\">{words.empty}<\/span>\n        )}\n      <\/button>\n      {clearable && combo && !capturing && !disabled && (\n        <button\n          type=\"button\"\n          data-react-fancy-hotkey-capture-clear=\"\"\n          aria-label={words.clear}\n          onClick={() => {\n            setValue(\"\");\n            setAnnouncement(words.cleared);\n            triggerRef.current?.focus();\n          }}\n          className=\"inline-grid h-6 w-6 place-items-center rounded text-[color:var(--fancy-text-muted,var(--color-zinc-500))] hover:bg-[color:var(--fancy-surface-muted,var(--color-zinc-100))] focus:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--fancy-focus,var(--color-blue-500))] dark:text-[color:var(--fancy-text-muted-dark,var(--color-zinc-400))] dark:hover:bg-[color:var(--fancy-surface-muted-dark,var(--color-zinc-800))]\"\n        >\n          <span aria-hidden=\"true\">\u00d7<\/span>\n        <\/button>\n      )}\n      {name && <input type=\"hidden\" name={name} value={normalised} \/>}\n      <span\n        data-react-fancy-hotkey-capture-status=\"\"\n        aria-live=\"polite\"\n        aria-atomic=\"true\"\n        className=\"sr-only\"\n        style={visuallyHidden}\n      >\n        {announcement}\n      <\/span>\n    <\/div>\n  );\n});\n\nHotkeyCapture.displayName = \"HotkeyCapture\";\n","type":"registry:ui","target":"components\/fancy\/hotkey-capture\/HotkeyCapture.tsx"},{"path":"components\/fancy\/hotkey-capture\/HotkeyCapture.types.ts","content":"import type { HTMLAttributes } from \"react\";\nimport type { FancyPlatform } from \"..\/lib\/utils\/platform\";\nimport type { HotkeyModifier } from \".\/hotkey\";\n\n\/** Every word HotkeyCapture shows or announces, for translation. *\/\nexport interface HotkeyCaptureLabels {\n  \/** Default accessible name, used when no `label` prop is given. @default \"Keyboard shortcut\" *\/\n  label?: string;\n  \/** Shown when no shortcut is set. @default \"Not set\" *\/\n  empty?: string;\n  \/** Shown while capturing. @default \"Press the keys\u2026\" *\/\n  prompt?: string;\n  \/** Announced after a capture. `{combo}` is the spoken combination. @default \"Shortcut set to {combo}\" *\/\n  captured?: string;\n  \/** Announced when a capture is cancelled. @default \"Cancelled\" *\/\n  cancelled?: string;\n  \/** Announced when the shortcut is cleared. @default \"Shortcut cleared\" *\/\n  cleared?: string;\n  \/** Accessible name of the clear button. @default \"Clear shortcut\" *\/\n  clear?: string;\n  \/**\n   * Accessible name of the trigger. `{label}` is the name, `{combo}` the\n   * current combination (or `empty`, or `prompt` while capturing).\n   * @default \"{label}: {combo}\"\n   *\/\n  trigger?: string;\n  \/**\n   * Key cap names, by modifier or by normalised key (`\"space\"`, `\"arrowup\"`).\n   * Merged over the defaults: Ctrl, Alt, Shift, and Meta (`\u2318` \/ Option on Apple).\n   *\/\n  keys?: Partial<Record<HotkeyModifier | string, string>>;\n}\n\nexport interface HotkeyCaptureProps\n  extends Omit<HTMLAttributes<HTMLDivElement>, \"onChange\" | \"defaultValue\"> {\n  \/**\n   * The shortcut as a normalised string, `\"ctrl+shift+k\"`: modifiers in the\n   * order ctrl, alt, shift, meta, then one key, lower case. `\"\"` is unset.\n   *\/\n  value?: string;\n  \/** Uncontrolled initial value. *\/\n  defaultValue?: string;\n  \/** Called with the normalised string on a capture, or `\"\"` when cleared. *\/\n  onChange?: (value: string) => void;\n  \/** Accessible name. Defaults to `labels.label`. *\/\n  label?: string;\n  \/** Show a clear button when a shortcut is set. @default true *\/\n  clearable?: boolean;\n  disabled?: boolean;\n  \/** Form field name: a hidden input carries the value. *\/\n  name?: string;\n  \/** Which modifier names to show. Detected after mount when omitted (SSR-safe). *\/\n  platform?: FancyPlatform;\n  \/** Words, for translation. *\/\n  labels?: HotkeyCaptureLabels;\n  \/** Key cap size. @default \"sm\" *\/\n  size?: \"xs\" | \"sm\" | \"md\";\n}\n","type":"registry:ui","target":"components\/fancy\/hotkey-capture\/HotkeyCapture.types.ts"},{"path":"components\/fancy\/hotkey-capture\/hotkey.ts","content":"\/**\n * The hotkey value: a normalised string such as `\"ctrl+shift+k\"`.\n *\n * Modifiers come first in a FIXED order (`ctrl`, `alt`, `shift`, `meta`), then\n * exactly one key, everything lower case. A string rather than an object\n * because the contract asks for JSON-friendly state: two equal shortcuts are\n * `===` equal, the value stores in a settings row as-is, and an agent can read\n * or write one without building anything. `parseHotkey` gives the object back\n * when a host wants to match a `KeyboardEvent` against it.\n *\n * The key is the PHYSICAL key for letters and digits (`KeyK` is `k`, `Digit1`\n * is `1`), so Shift+1 records as `shift+1` and not `!`, and macOS Option\n * combinations record the letter rather than the symbol Option types.\n *\/\nexport interface HotkeyCombo {\n  \/** The non-modifier key, lower case: `\"k\"`, `\"1\"`, `\"f5\"`, `\"enter\"`, `\"space\"`, `\"arrowup\"`. *\/\n  key: string;\n  ctrl: boolean;\n  alt: boolean;\n  shift: boolean;\n  meta: boolean;\n}\n\nexport const HOTKEY_MODIFIERS = [\"ctrl\", \"alt\", \"shift\", \"meta\"] as const;\nexport type HotkeyModifier = (typeof HOTKEY_MODIFIERS)[number];\n\nconst MODIFIER_ALIASES: Record<string, HotkeyModifier> = {\n  ctrl: \"ctrl\",\n  control: \"ctrl\",\n  alt: \"alt\",\n  option: \"alt\",\n  shift: \"shift\",\n  meta: \"meta\",\n  cmd: \"meta\",\n  command: \"meta\",\n  super: \"meta\",\n  win: \"meta\",\n};\n\n\/** `KeyboardEvent.key` values that are modifiers on their own. *\/\nconst MODIFIER_KEYS = new Set([\"Control\", \"Shift\", \"Alt\", \"AltGraph\", \"Meta\", \"OS\", \"Super\", \"Hyper\"]);\n\n\/** Format a combination as the normalised string. *\/\nexport function formatHotkey(combo: Partial<HotkeyCombo> | null | undefined): string {\n  if (!combo || !combo.key) return \"\";\n  const parts: string[] = HOTKEY_MODIFIERS.filter((m) => combo[m]);\n  parts.push(combo.key.toLowerCase());\n  return parts.join(\"+\");\n}\n\n\/**\n * Parse any `+`-joined spelling (`\"Shift+Ctrl+K\"`, `\"cmd+k\"`) into a\n * combination. `null` for an empty string or one with no non-modifier key.\n *\/\nexport function parseHotkey(value: string | null | undefined): HotkeyCombo | null {\n  if (!value) return null;\n  const combo: HotkeyCombo = { key: \"\", ctrl: false, alt: false, shift: false, meta: false };\n  \/\/ `+` itself can be the key: \"ctrl++\" splits to [\"ctrl\", \"\", \"\"].\n  const raw = value.trim().toLowerCase();\n  const parts = raw.endsWith(\"++\") ? [...raw.slice(0, -2).split(\"+\"), \"+\"] : raw.split(\"+\");\n  for (const part of parts) {\n    const p = part.trim();\n    if (!p) continue;\n    const mod = MODIFIER_ALIASES[p];\n    if (mod) combo[mod] = true;\n    else combo.key = p;\n  }\n  return combo.key ? combo : null;\n}\n\n\/**\n * Key cap names every keyboard has. Shared by HotkeyCapture and PromptInput's\n * send hint, so a combination recorded in one is named the same in the other.\n *\/\nexport const DEFAULT_KEY_NAMES: Record<string, string> = {\n  ctrl: \"Ctrl\",\n  alt: \"Alt\",\n  shift: \"Shift\",\n  meta: \"Meta\",\n  space: \"Space\",\n  enter: \"Enter\",\n  escape: \"Esc\",\n  tab: \"Tab\",\n  backspace: \"Backspace\",\n  delete: \"Delete\",\n  arrowup: \"Up\",\n  arrowdown: \"Down\",\n  arrowleft: \"Left\",\n  arrowright: \"Right\",\n  pageup: \"PgUp\",\n  pagedown: \"PgDn\",\n  home: \"Home\",\n  end: \"End\",\n};\n\n\/** Apple keyboards: the true key names. `\u2318` is the one high glyph, and Apple-only. *\/\nexport const APPLE_KEY_NAMES: Record<string, string> = { meta: \"\u2318\", alt: \"Option\" };\n\n\/** The cap name of one normalised key, from `names` or derived from the key. *\/\nexport function hotkeyKeyName(key: string, names: Record<string, string>): string {\n  if (names[key]) return names[key];\n  if (key.length === 1) return key.toUpperCase();\n  if (\/^f\\d{1,2}$\/.test(key)) return key.toUpperCase();\n  return key.charAt(0).toUpperCase() + key.slice(1);\n}\n\n\/** Cap names for a combination, modifiers first in the fixed order. *\/\nexport function hotkeyCaps(combo: Partial<HotkeyCombo>, names: Record<string, string>): string[] {\n  const caps: string[] = HOTKEY_MODIFIERS.filter((m) => combo[m]).map((m) => hotkeyKeyName(m, names));\n  if (combo.key) caps.push(hotkeyKeyName(combo.key, names));\n  return caps;\n}\n\n\/** Whether a keydown is a modifier pressed on its own. *\/\nexport function isModifierOnly(event: Pick<KeyboardEvent, \"key\">): boolean {\n  return MODIFIER_KEYS.has(event.key);\n}\n\n\/** The key part of a keydown, normalised. Physical for letters and digits. *\/\nexport function eventKey(event: Pick<KeyboardEvent, \"key\" | \"code\">): string {\n  const code = event.code ?? \"\";\n  const letter = \/^Key([A-Z])$\/.exec(code);\n  if (letter) return letter[1].toLowerCase();\n  const digit = \/^(?:Digit|Numpad)(\\d)$\/.exec(code);\n  if (digit) return digit[1];\n  if (event.key === \" \" || code === \"Space\") return \"space\";\n  if (event.key === \"+\") return \"+\";\n  return event.key.toLowerCase();\n}\n\n\/** The combination a keydown makes, or `null` when it is a modifier alone. *\/\nexport function comboFromEvent(\n  event: Pick<KeyboardEvent, \"key\" | \"code\" | \"ctrlKey\" | \"altKey\" | \"shiftKey\" | \"metaKey\">,\n): HotkeyCombo | null {\n  if (isModifierOnly(event)) return null;\n  return {\n    key: eventKey(event),\n    ctrl: event.ctrlKey,\n    alt: event.altKey,\n    shift: event.shiftKey,\n    meta: event.metaKey,\n  };\n}\n","type":"registry:ui","target":"components\/fancy\/hotkey-capture\/hotkey.ts"},{"path":"components\/fancy\/hotkey-capture\/index.ts","content":"export { HotkeyCapture } from \".\/HotkeyCapture\";\nexport {\n  formatHotkey,\n  parseHotkey,\n  comboFromEvent,\n  isModifierOnly,\n  HOTKEY_MODIFIERS,\n} from \".\/hotkey\";\nexport type { HotkeyCombo, HotkeyModifier } from \".\/hotkey\";\nexport type { HotkeyCaptureProps, HotkeyCaptureLabels } from \".\/HotkeyCapture.types\";\n","type":"registry:ui","target":"components\/fancy\/hotkey-capture\/index.ts"},{"path":"components\/fancy\/lib\/utils\/cn.ts","content":"import { twMerge } from \"tailwind-merge\";\n\n\/**\n * A class value: a string, a number, a conditional map, an array of any of\n * those, or nothing. Mirrors what `clsx` accepted, because every component in\n * this package already passes these shapes.\n *\/\nexport type ClassValue =\n  | string\n  | number\n  | bigint\n  | null\n  | undefined\n  | false\n  | ClassDictionary\n  | ClassValue[];\n\ntype ClassDictionary = Record<string, unknown>;\n\n\/**\n * Flatten class values into a space-separated string.\n *\n * This was `clsx` until 2026-08-19. It is roughly twenty lines of logic, it\n * shipped as a RUNTIME dependency to every consumer of this package, and its\n * last commit was 801 days old \u2014 so it fell to the rule that third-party code\n * must be both approved and actively maintained. Owning it costs less than\n * carrying it.\n *\n * `tailwind-merge` deliberately stays: deciding which of two conflicting\n * Tailwind utilities wins requires modelling the entire utility space, which is\n * emphatically not twenty lines, and it is actively maintained.\n *\n * Falsy values are dropped \u2014 including `0` and `\"\"`, which is what `clsx` did\n * and what `tests\/cn.test.ts` pins. A truthy number is kept, because digits are\n * legal class names. `bigint` is admitted because clsx's signature did and\n * the compiler proved it reachable from two call sites here.\n *\/\nfunction flatten(value: ClassValue): string {\n  if (!value) return \"\";\n\n  if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"bigint\") {\n    return String(value);\n  }\n\n  if (Array.isArray(value)) {\n    let out = \"\";\n    for (const item of value) {\n      const part = flatten(item);\n      if (part) out = out ? `${out} ${part}` : part;\n    }\n    return out;\n  }\n\n  let out = \"\";\n  for (const key in value) {\n    if (value[key]) out = out ? `${out} ${key}` : key;\n  }\n  return out;\n}\n\nexport function cn(...inputs: ClassValue[]): string {\n  return twMerge(flatten(inputs));\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/cn.ts"},{"path":"components\/fancy\/lib\/utils\/label-template.ts","content":"\/**\n * Fill a label template's `{name}` slots: `\"Digit {n} of {total}\"`,\n * `\"Open {host}\"`. Single braces, for translatable labels only; a slot with no\n * value stays as written. Literal replacement, never evaluated.\n *\/\nexport function fillLabel(template: string, values: Record<string, string | number>): string {\n  return template.replace(\/\\{(\\w+)\\}\/g, (whole: string, name: string) =>\n    Object.prototype.hasOwnProperty.call(values, name) ? String(values[name]) : whole,\n  );\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/label-template.ts"},{"path":"components\/fancy\/lib\/utils\/visually-hidden.ts","content":"import type { CSSProperties } from \"react\";\n\n\/**\n * The standard sr-only clip pattern as an inline style: the same declarations\n * Tailwind's `sr-only` utility emits. Pair it with `className=\"sr-only\"`.\n *\n * Inline because a visually hidden element must not depend on the host's\n * Tailwind build having generated `sr-only` for react-fancy's classes. Without\n * it the element renders as visible, unclipped text (genie#1290).\n *\n * The element is `position: absolute`, so whatever holds it must be positioned\n * too. Otherwise it escapes to the nearest positioned ancestor, which can sit\n * outside an unpositioned scroll container and stretch the document.\n *\/\nexport const visuallyHidden: CSSProperties = {\n  position: \"absolute\",\n  width: \"1px\",\n  height: \"1px\",\n  padding: 0,\n  margin: \"-1px\",\n  overflow: \"hidden\",\n  clip: \"rect(0, 0, 0, 0)\",\n  whiteSpace: \"nowrap\",\n  border: 0,\n};\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/visually-hidden.ts"},{"path":"components\/fancy\/lib\/utils\/platform.ts","content":"\/**\n * Which modifier key the user actually has.\n *\n * This exists because a keyboard hint is a CLAIM about the reader's hardware.\n * `\u2318 + Enter to send` on Windows or Linux names a key that is not on the\n * keyboard, and a reader who cannot act on a hint learns to ignore hints \u2014 so\n * the cost is not one wrong glyph, it is the credibility of every hint beside\n * it. (Reported from a real Electron app running on Linux, where the glyph had\n * no font behind it either and rendered as tofu.)\n *\n * Two deliberate choices:\n *\n * 1. **The platform is an ARGUMENT, never a global read.** `detectPlatform`\n *    takes the hints; `modifierKeyLabel` takes the verdict. Both branches are\n *    therefore reachable from one machine, which is the only way a test can\n *    cover the platform you are not sitting at. A function that reads\n *    `navigator` internally can only ever be tested on the developer's own OS.\n * 2. **`generic` is the fallback, and that is not arbitrary.** Every Fancy\n *    surface that submits on a modifier accepts `metaKey || ctrlKey`, so\n *    `Ctrl` is a TRUE label on an Apple keyboard while `\u2318` is a FALSE one\n *    everywhere else. The honest default is the one that is pressable on all\n *    of them.\n *\/\nexport type FancyPlatform = \"apple\" | \"generic\";\n\n\/**\n * The parts of `navigator` the detection reads \u2014 nothing more, so a caller can\n * hand it a literal (a test, an Electron main process forwarding `process.platform`,\n * a server with a stored preference).\n *\/\nexport interface PlatformHints {\n  \/** `navigator.userAgentData` \u2014 the modern, non-spoofed answer where it exists. *\/\n  userAgentData?: { platform?: string } | null;\n  \/** `navigator.platform` \u2014 deprecated, still the most reliable legacy signal. *\/\n  platform?: string | null;\n  \/** `navigator.userAgent` \u2014 last resort. *\/\n  userAgent?: string | null;\n}\n\n\/**\n * `userAgentData.platform` is a short enumerated token (\"macOS\", \"Windows\",\n * \"Linux\", \"Android\", \"iOS\"), so it is matched exactly rather than by substring.\n *\/\nconst APPLE_UA_DATA_PLATFORMS = new Set([\"macos\", \"ios\", \"ipados\"]);\n\n\/**\n * Legacy `platform` \/ `userAgent` are free text. iPadOS reports `MacIntel`, and\n * iOS user agents say \"like Mac OS X\" \u2014 both are Apple, so a Mac match is\n * correct for them too.\n *\/\nconst APPLE_FREE_TEXT = \/\\b(mac|macintosh|iphone|ipad|ipod|darwin)\/i;\n\n\/** Resolve a platform from navigator-shaped hints. Unknown or absent \u21d2 `generic`. *\/\nexport function detectPlatform(hints?: PlatformHints | null): FancyPlatform {\n  if (!hints) return \"generic\";\n\n  const uaData = hints.userAgentData?.platform;\n  if (typeof uaData === \"string\" && uaData.length > 0) {\n    \/\/ When the browser gives an enumerated answer, TRUST IT and stop. Falling\n    \/\/ through to the free-text test would let a Windows UA string containing\n    \/\/ the word \"Mac\" (a font name, a device model) overturn it.\n    return APPLE_UA_DATA_PLATFORMS.has(uaData.trim().toLowerCase()) ? \"apple\" : \"generic\";\n  }\n\n  for (const value of [hints.platform, hints.userAgent]) {\n    if (typeof value === \"string\" && APPLE_FREE_TEXT.test(value)) return \"apple\";\n  }\n\n  return \"generic\";\n}\n\n\/**\n * The modifier key to NAME for a platform.\n *\n * `\u2318` is emitted for `apple` and nothing else. A test enumerates the platform\n * values and counts that no other one can produce it, because a hint that names\n * the wrong key is worse than no hint.\n *\/\nexport function modifierKeyLabel(platform: FancyPlatform): \"\u2318\" | \"Ctrl\" {\n  return platform === \"apple\" ? \"\u2318\" : \"Ctrl\";\n}\n\n\/** SSR-safe read of the live browser hints. `null` off a browser. *\/\nexport function browserPlatformHints(): PlatformHints | null {\n  if (typeof navigator === \"undefined\") return null;\n  return navigator as PlatformHints;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/platform.ts"},{"path":"components\/fancy\/lib\/hooks\/use-controllable-state.ts","content":"import { useCallback, useRef, useState } from \"react\";\n\n\/**\n * One state slot that works controlled or uncontrolled.\n *\n * ---------------------------------------------------------------------------\n * Why the value is tracked in a ref (fixed 5.32.0)\n * ---------------------------------------------------------------------------\n *\n * This resolved a functional update against the RENDER CLOSURE's `value` and then\n * handed React an already-computed value:\n *\n *     const nextValue = typeof next === \"function\" ? next(value) : next;\n *     setUncontrolledValue(nextValue);\n *\n * So `setValue(fn)` twice in one batch had both calls compute from the same stale\n * `value`, and **the first update was silently lost.** React's own `setState`\n * updater form does not have that problem precisely because React resolves it\n * against the latest state; passing a pre-computed value gives that up.\n *\n * Found by a hook test that paste-held two items inside one `act()` and got one.\n * It is not an exotic case \u2014 any caller that loops, or handles two events in a\n * batch, hits it, and the symptom is a dropped update with nothing to indicate one\n * happened.\n *\n * The fix cannot be \"pass the updater to React\", because `onChange` has to be\n * called with the resulting value and an updater must stay pure \u2014 React may invoke\n * it twice (StrictMode), which would fire `onChange` twice. So the previous value\n * comes from a ref that is re-synced from the authoritative `value` on every render\n * and advanced on every set. Within a batch the ref carries intent; after a render\n * the real value wins.\n *\n * A side effect worth having: `setValue` no longer depends on `value`, so it is\n * stable for the life of the component.\n *\/\nexport function useControllableState<T>(\n  controlledValue: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n): [T, (value: T | ((prev: T) => T)) => void] {\n  const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);\n  const isControlled = controlledValue !== undefined;\n  const value = isControlled ? controlledValue : uncontrolledValue;\n\n  const onChangeRef = useRef(onChange);\n  onChangeRef.current = onChange;\n\n  \/\/ Re-synced every render from whichever side owns the value. A controlled parent\n  \/\/ that ignores `onChange` therefore wins on the next render rather than being\n  \/\/ overridden by what this hook optimistically recorded.\n  const valueRef = useRef(value);\n  valueRef.current = value;\n\n  const isControlledRef = useRef(isControlled);\n  isControlledRef.current = isControlled;\n\n  const setValue = useCallback((next: T | ((prev: T) => T)) => {\n    const nextValue =\n      typeof next === \"function\"\n        ? (next as (prev: T) => T)(valueRef.current)\n        : next;\n\n    \/\/ Advance the ref BEFORE notifying, so a second call in the same batch builds\n    \/\/ on this one instead of on what the last render saw.\n    valueRef.current = nextValue;\n\n    if (!isControlledRef.current) {\n      setUncontrolledValue(nextValue);\n    }\n\n    onChangeRef.current?.(nextValue);\n  }, []);\n\n  return [value, setValue];\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/hooks\/use-controllable-state.ts"}]}