{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "keys",
  "title": "Keys",
  "description": "What a key is called, how each platform draws and orders it (Mod is ⌘ on a Mac and Ctrl elsewhere), what a screen reader says for it, and which keys are held now, from one listener for the whole page; and ui-sdk's shortcuts as a React hook and an `aria-keyshortcuts` ref.",
  "dependencies": [
    "@ui-sdk/core"
  ],
  "files": [
    {
      "path": "registry/lib/keys.tsx",
      "content": "'use client'\n\nimport { ariaKeyshortcuts } from '@ui-sdk/core'\nimport { shortcuts } from '@ui-sdk/core/shortcuts'\nimport {\n  Children,\n  isValidElement,\n  type ReactNode,\n  type RefCallback,\n  useCallback,\n  useEffect,\n  useRef,\n  useSyncExternalStore,\n} from 'react'\n\n/*\n * What a key is called, how it is drawn and spoken, and which keys the person\n * is holding now. Shared by every Kbd: one listener on the window, however\n * many keys a page shows.\n */\n\n/** A key as `KeyboardEvent.key` names it, with letters in lower case and `Mod` for ⌘ or Ctrl. */\nexport type KeyName = string\n\nconst ALIASES: Record<string, KeyName> = {\n  '⌘': 'Meta',\n  cmd: 'Meta',\n  command: 'Meta',\n  meta: 'Meta',\n  '⌃': 'Control',\n  ctrl: 'Control',\n  control: 'Control',\n  '⌥': 'Alt',\n  alt: 'Alt',\n  opt: 'Alt',\n  option: 'Alt',\n  '⇧': 'Shift',\n  shift: 'Shift',\n  mod: 'Mod',\n  '↵': 'Enter',\n  '⏎': 'Enter',\n  enter: 'Enter',\n  return: 'Enter',\n  '⎋': 'Escape',\n  esc: 'Escape',\n  escape: 'Escape',\n  '⌫': 'Backspace',\n  backspace: 'Backspace',\n  '⌦': 'Delete',\n  del: 'Delete',\n  delete: 'Delete',\n  '⇥': 'Tab',\n  tab: 'Tab',\n  '↑': 'ArrowUp',\n  up: 'ArrowUp',\n  arrowup: 'ArrowUp',\n  '↓': 'ArrowDown',\n  down: 'ArrowDown',\n  arrowdown: 'ArrowDown',\n  '←': 'ArrowLeft',\n  left: 'ArrowLeft',\n  arrowleft: 'ArrowLeft',\n  '→': 'ArrowRight',\n  right: 'ArrowRight',\n  arrowright: 'ArrowRight',\n  '␣': ' ',\n  space: ' ',\n  pgup: 'PageUp',\n  pageup: 'PageUp',\n  'page up': 'PageUp',\n  pgdn: 'PageDown',\n  pagedown: 'PageDown',\n  'page down': 'PageDown',\n  home: 'Home',\n  end: 'End',\n}\n\n/** The key a label names: `⌘` and `Cmd` are `Meta`, `K` is `k`, `Page Down` is `PageDown`. */\nexport function keyFromLabel(label: string): KeyName {\n  const trimmed = label.trim()\n  const alias = ALIASES[trimmed.toLowerCase()]\n  if (alias) return alias\n  if (/^f\\d{1,2}$/i.test(trimmed)) return trimmed.toUpperCase()\n  return trimmed.length === 1 ? trimmed.toLowerCase() : trimmed\n}\n\n/** `Mod` is Command on Apple's systems and Control everywhere else. */\nexport function resolveKey(key: KeyName, apple: boolean): KeyName {\n  if (key === 'Mod') return apple ? 'Meta' : 'Control'\n  return key\n}\n\n/** What a key shows, by each platform's own convention: ⌘ on a Mac, Ctrl elsewhere. */\nexport function keyLabel(key: KeyName, apple: boolean): string {\n  const resolved = resolveKey(key, apple)\n  const labels: Record<string, [mac: string, other: string]> = {\n    Meta: ['⌘', 'Win'],\n    Control: ['⌃', 'Ctrl'],\n    Alt: ['⌥', 'Alt'],\n    Shift: ['⇧', 'Shift'],\n    Enter: ['↵', 'Enter'],\n    Escape: ['Esc', 'Esc'],\n    Backspace: ['⌫', 'Backspace'],\n    Delete: ['⌦', 'Del'],\n    Tab: ['⇥', 'Tab'],\n    ArrowUp: ['↑', '↑'],\n    ArrowDown: ['↓', '↓'],\n    ArrowLeft: ['←', '←'],\n    ArrowRight: ['→', '→'],\n    ' ': ['Space', 'Space'],\n    PageUp: ['Page Up', 'Page Up'],\n    PageDown: ['Page Down', 'Page Down'],\n  }\n  const label = labels[resolved]\n  if (label) return label[apple ? 0 : 1]\n  return resolved.length === 1 ? resolved.toUpperCase() : resolved\n}\n\n/** A key in words, as a screen reader should say it: `Command`, `Up arrow`, `K`. */\nexport function keyWord(key: KeyName, apple: boolean): string {\n  const resolved = resolveKey(key, apple)\n  const words: Record<string, string> = {\n    Meta: apple ? 'Command' : 'Windows',\n    Control: 'Control',\n    Alt: apple ? 'Option' : 'Alt',\n    Shift: 'Shift',\n    Enter: apple ? 'Return' : 'Enter',\n    Escape: 'Escape',\n    Backspace: apple ? 'Delete' : 'Backspace',\n    Delete: 'Forward delete',\n    Tab: 'Tab',\n    ArrowUp: 'Up arrow',\n    ArrowDown: 'Down arrow',\n    ArrowLeft: 'Left arrow',\n    ArrowRight: 'Right arrow',\n    ' ': 'Space',\n    PageUp: 'Page up',\n    PageDown: 'Page down',\n    '/': 'Slash',\n    '\\\\': 'Backslash',\n    '?': 'Question mark',\n    ',': 'Comma',\n    '.': 'Period',\n    '+': 'Plus',\n    '-': 'Minus',\n    '[': 'Left bracket',\n    ']': 'Right bracket',\n  }\n  return words[resolved] ?? (resolved.length === 1 ? resolved.toUpperCase() : resolved)\n}\n\n/**\n * The words to read in place of a label drawn as a symbol (⌘, ↵, /), or\n * undefined when it reads well as it is (`Ctrl`, `K`, `F2`). Screen readers\n * speak symbols unevenly and ignore a name on a `kbd`, so the symbol is\n * hidden and these words are read instead. The modifier symbols are Apple's,\n * so they are read as a Mac names them on any system.\n */\nexport function spokenLabel(label: string): string | undefined {\n  if (/^[\\p{L}\\p{N} ]+$/u.test(label)) return undefined\n  return keyWord(keyFromLabel(label), true)\n}\n\nconst NAMED = new Set([\n  'Meta',\n  'Control',\n  'Alt',\n  'Shift',\n  'Enter',\n  'Escape',\n  'Backspace',\n  'Delete',\n  'Tab',\n  'ArrowUp',\n  'ArrowDown',\n  'ArrowLeft',\n  'ArrowRight',\n  'PageUp',\n  'PageDown',\n  'Home',\n  'End',\n  ' ',\n])\n\n/**\n * Every name a key press answers to. A letter answers by its position as\n * well as by what it typed, because ⌥ and ⇧ change what a key types (⌥K\n * types ˚) but not which key it is.\n */\nexport function eventKeys({ key, code }: Pick<KeyboardEvent, 'key' | 'code'>): KeyName[] {\n  if (NAMED.has(key) || /^F\\d{1,2}$/.test(key)) return [key]\n  const names = new Set<KeyName>()\n  if (key.length === 1) names.add(key.toLowerCase())\n  const letter = /^Key([A-Z])$/.exec(code)\n  if (letter) names.add(letter[1].toLowerCase())\n  const digit = /^Digit(\\d)$/.exec(code)\n  if (digit) names.add(digit[1])\n  return [...names]\n}\n\nconst MODIFIERS = new Set(['Meta', 'Control', 'Alt', 'Shift'])\n\n/**\n * Whether a press only types into a field, so no shortcut runs and no hint\n * should answer it: a key other than a modifier, in a text field, with no\n * modifier but Shift.\n */\nexport function onlyTypes(\n  {\n    key,\n    ctrlKey,\n    metaKey,\n    altKey,\n  }: Pick<KeyboardEvent, 'key' | 'ctrlKey' | 'metaKey' | 'altKey'>,\n  inField: boolean,\n) {\n  // ⌥ with a letter types a character on a Mac (⌥C is ç), and a dead key starts one.\n  return (\n    inField &&\n    !MODIFIERS.has(key) &&\n    !ctrlKey &&\n    !metaKey &&\n    (!altKey || key.length === 1 || key === 'Dead')\n  )\n}\n\n/**\n * Runs `onPress` when the person presses `keys`, ui-sdk's shortcut string\n * (`'mod+k'`, `'/'`), through ui-sdk's one shortcut listener. A plain key\n * typed in a field stays text, and a modal over the page pauses it. `layer`\n * is ui-sdk's: an element on the page, or one inside a popup, so the\n * shortcut runs while that popup is open, such as ⌘K closing the dialog it\n * opened.\n */\nexport function useShortcut(\n  keys: string | null | undefined,\n  onPress: (event: KeyboardEvent) => void,\n  layer?: Element | null,\n) {\n  const press = useRef(onPress)\n  useEffect(() => {\n    press.current = onPress\n  })\n  useEffect(() => {\n    if (!keys) return undefined\n    return shortcuts.register(keys, (event) => press.current(event), {\n      layer: layer ?? undefined,\n    })\n  }, [keys, layer])\n}\n\n/**\n * A ref callback that sets `aria-keyshortcuts` from ui-sdk's shortcut string\n * once the element is in the page, where the platform is known, so the\n * server's and the client's first render agree.\n */\nexport function useAriaKeyshortcuts(\n  keys: string | null | undefined,\n): RefCallback<Element> {\n  return useCallback(\n    (element: Element | null) => {\n      if (!element || !keys) return undefined\n      element.setAttribute('aria-keyshortcuts', ariaKeyshortcuts(keys))\n      return () => element.removeAttribute('aria-keyshortcuts')\n    },\n    [keys],\n  )\n}\n\n/** The keys of ui-sdk's shortcut string, each as `Kbd` names it: `'mod+shift+k'` is Mod, Shift, k. */\nexport function shortcutKeys(keys: string): KeyName[] {\n  return keys.split('+').map(keyFromLabel)\n}\n\nfunction inField(target: EventTarget | null) {\n  return (\n    target instanceof Element &&\n    target.closest(\n      'input, textarea, select, [contenteditable]:not([contenteditable=\"false\"])',\n    ) !== null\n  )\n}\n\n/** Each held key, with the physical keys holding it: both Shift keys hold `Shift`. */\nconst held = new Map<KeyName, Set<string>>()\nconst listeners = new Set<() => void>()\n\nfunction notify() {\n  for (const listener of listeners) listener()\n}\n\nfunction release() {\n  if (held.size === 0) return\n  held.clear()\n  notify()\n}\n\nfunction onKeyDown(event: KeyboardEvent) {\n  if (event.repeat || onlyTypes(event, inField(event.target))) return\n  for (const name of eventKeys(event)) {\n    const codes = held.get(name) ?? new Set()\n    codes.add(event.code)\n    held.set(name, codes)\n  }\n  notify()\n}\n\nfunction onKeyUp(event: KeyboardEvent) {\n  // While ⌘ is down a Mac sends no keyup for the other keys, so letting go of ⌘ lets go of all of them.\n  if (event.key === 'Meta') return release()\n  let changed = false\n  for (const [name, codes] of held) {\n    if (!codes.delete(event.code)) continue\n    changed = true\n    if (codes.size === 0) held.delete(name)\n  }\n  if (changed) notify()\n}\n\nfunction onVisibility() {\n  if (document.hidden) release()\n}\n\n/** Listens while any key is shown, and lets every key go when the window loses focus. */\nexport function subscribeToHeldKeys(listener: () => void) {\n  if (listeners.size === 0) {\n    window.addEventListener('keydown', onKeyDown, true)\n    window.addEventListener('keyup', onKeyUp, true)\n    window.addEventListener('blur', release)\n    document.addEventListener('visibilitychange', onVisibility)\n  }\n  listeners.add(listener)\n  return () => {\n    listeners.delete(listener)\n    if (listeners.size > 0) return\n    window.removeEventListener('keydown', onKeyDown, true)\n    window.removeEventListener('keyup', onKeyUp, true)\n    window.removeEventListener('blur', release)\n    document.removeEventListener('visibilitychange', onVisibility)\n    held.clear()\n  }\n}\n\nexport function isHeld(key: KeyName) {\n  return held.has(key)\n}\n\n/** Apple's systems, where ⌘ takes Ctrl's place. */\nexport function isApplePlatform(platform: string) {\n  return /mac|iphone|ipad|ipod/i.test(platform)\n}\n\n/** Apple writes modifiers ⌃⌥⇧⌘; Windows writes Win, Ctrl, Alt, Shift. */\nconst MODIFIER_ORDER = {\n  apple: ['Control', 'Alt', 'Shift', 'Meta'],\n  other: ['Meta', 'Control', 'Alt', 'Shift'],\n} as const\n\n/**\n * The keys of a shortcut in the order the platform writes them: modifiers\n * first, in its own order, then the rest as given. `Mod+Shift+Z` is ⇧⌘Z on a\n * Mac and Ctrl+Shift+Z elsewhere.\n */\nexport function orderKeys<T>(keys: { key: KeyName; item: T }[], apple: boolean): T[] {\n  const order: readonly string[] = MODIFIER_ORDER[apple ? 'apple' : 'other']\n  const rank = (key: KeyName) => {\n    const index = order.indexOf(resolveKey(key, apple))\n    return index === -1 ? order.length : index\n  }\n  return keys\n    .map((entry, index) => ({ ...entry, index }))\n    .sort((a, b) => rank(a.key) - rank(b.key) || a.index - b.index)\n    .map(({ item }) => item)\n}\n\nfunction subscribeToNothing() {\n  return () => {}\n}\n\nfunction readPlatform() {\n  const agent = navigator as Navigator & {\n    userAgentData?: { platform?: string }\n  }\n  return isApplePlatform(agent.userAgentData?.platform ?? navigator.platform)\n}\n\n/** Whether the page runs on Apple's systems; false while it renders on the server. */\nexport function useApplePlatform() {\n  return useSyncExternalStore(subscribeToNothing, readPlatform, () => false)\n}\n\nexport interface KbdKeyProps {\n  /**\n   * The key, as `KeyboardEvent.key` names it (`ArrowUp`, `Enter`), or `Mod`\n   * for ⌘ on a Mac and Ctrl elsewhere. Read from the label when it is text;\n   * needed when the label is an icon.\n   */\n  name?: KeyName\n  children?: ReactNode\n}\n\n/**\n * Which key a Kbd shows, what it draws and says, and whether the person is\n * holding it now. Only a key whose held state changes renders again.\n */\nexport function useKbdKey({ name, children }: KbdKeyProps) {\n  const apple = useApplePlatform()\n  const text = typeof children === 'string' ? children : undefined\n  const key = resolveKey(name ?? (text === undefined ? '' : keyFromLabel(text)), apple)\n  const held = useSyncExternalStore(\n    subscribeToHeldKeys,\n    () => key !== '' && isHeld(key),\n    () => false,\n  )\n  // A modifier, `Mod` or a key given only by name is drawn the platform's way: ⇧⌘ on a Mac, Ctrl+Shift elsewhere.\n  const drawn =\n    children === undefined || MODIFIERS.has(key) ? keyLabel(key, apple) : children\n  const spoken =\n    typeof drawn === 'string' ? spokenLabel(drawn) : key ? keyWord(key, apple) : undefined\n  const label = spoken ? (\n    <>\n      <span aria-hidden className='inline-flex items-center'>\n        {drawn}\n      </span>\n      <span className='sr-only'>{spoken}</span>\n    </>\n  ) : (\n    drawn\n  )\n  return { key, held, apple, label }\n}\n\n/** A group's keys in the order the platform writes a shortcut (`orderKeys`). */\nexport function useOrderedKeys(children: ReactNode) {\n  const apple = useApplePlatform()\n  const keys = Children.toArray(children).map((item) => {\n    if (!isValidElement<KbdKeyProps>(item)) return { key: '', item }\n    const { name, children: label } = item.props\n    return {\n      key: name ?? (typeof label === 'string' ? keyFromLabel(label) : ''),\n      item,\n    }\n  })\n  return { apple, keys: orderKeys(keys, apple) }\n}\n",
      "type": "registry:lib",
      "target": "@lib/keys.tsx"
    }
  ],
  "type": "registry:lib"
}