{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "use-hotkeys",
  "type": "registry:lib",
  "title": "Use Hotkeys",
  "description": "Binds keyboard shortcuts (\"mod+k\", \"shift+?\", \"g i\") to handlers on the page or on one element, by the key's place for letters so they work on keyboards of every script, left alone while typing in a field; and formats a shortcut for showing (\"⌘K\" on Apple, \"Ctrl+K\" elsewhere).",
  "categories": [
    "lib"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme"
  ],
  "files": [
    {
      "path": "registry/lib/use-hotkeys.ts",
      "type": "registry:lib",
      "target": "lib/use-hotkeys.ts",
      "content": "\"use client\";\n/**\n * @name use-hotkeys\n * @category lib\n * @description Binds keyboard shortcuts (\"mod+k\", \"shift+?\", \"g i\") to handlers on the page or on one element, by the key's place for letters so they work on keyboards of every script, left alone while typing in a field; and formats a shortcut for showing (\"⌘K\" on Apple, \"Ctrl+K\" elsewhere).\n * @when Shortcuts for frequent actions: opening command, saving, moving between items. Show each one where its action is (kbd, a menu's shortcut slot) and keep a list of them. Do not take keys a screen reader or the browser uses (single letters without a modifier only inside a focused widget; never Tab or the arrows on the page).\n * @example\n * useHotkeys(\"mod+k\", () => setOpen(true));\n * useHotkeys(\"g i\", () => router.push(\"/inbox\"), { sequenceTimeout: 800 });\n * <Kbd>{formatHotkey(\"mod+k\")}</Kbd>\n */\nimport { useEffect, useRef, type RefObject } from \"react\";\n\nexport type HotkeyOptions = {\n  /** Default true. */\n  enabled?: boolean;\n  /** Listen on this element only (and what is inside it) instead of the whole page. */\n  target?: RefObject<HTMLElement | null>;\n  /** Fire while focus is in a text field. Default false: typing is never taken over. */\n  inInputs?: boolean;\n  /** Default true. */\n  preventDefault?: boolean;\n  /** The longest pause between the keys of a sequence (\"g i\"), in milliseconds. Default 1000. */\n  sequenceTimeout?: number;\n};\n\ntype Chord = { key: string; mod: boolean; ctrl: boolean; meta: boolean; alt: boolean; shift: boolean };\n\nconst isApple = (): boolean => typeof navigator !== \"undefined\" && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);\n\nfunction parseChord(text: string): Chord {\n  const parts = text.toLowerCase().split(\"+\").map((p) => p.trim());\n  const key = parts.pop() ?? \"\";\n  return { key, mod: parts.includes(\"mod\"), ctrl: parts.includes(\"ctrl\"), meta: parts.includes(\"meta\") || parts.includes(\"cmd\"), alt: parts.includes(\"alt\") || parts.includes(\"option\"), shift: parts.includes(\"shift\") };\n}\n\n/** The key of an event as the binding names it: letters and digits by their place (event.code), so \"k\" is the same key on any layout. */\nfunction keyOf(event: KeyboardEvent): string {\n  const code = event.code;\n  if (/^Key[A-Z]$/.test(code)) return code.slice(3).toLowerCase();\n  if (/^Digit\\d$/.test(code)) return code.slice(5);\n  return event.key.toLowerCase();\n}\n\nfunction matches(chord: Chord, event: KeyboardEvent): boolean {\n  const apple = isApple();\n  const wantCtrl = chord.ctrl || (chord.mod && !apple);\n  const wantMeta = chord.meta || (chord.mod && apple);\n  // A shifted symbol (\"?\") is matched by its own key; shift is then implied.\n  const symbol = chord.key.length === 1 && !/[a-z0-9]/.test(chord.key);\n  const key = symbol ? event.key.toLowerCase() : keyOf(event);\n  return key === chord.key && event.ctrlKey === wantCtrl && event.metaKey === wantMeta && event.altKey === chord.alt && (symbol || event.shiftKey === chord.shift);\n}\n\nconst typing = (target: EventTarget | null): boolean => {\n  const element = target as HTMLElement | null;\n  if (!element) return false;\n  return element.isContentEditable || /^(input|textarea|select)$/i.test(element.tagName);\n};\n\n/** Calls `handler` when the shortcut is pressed. A space separates the keys of a sequence: \"g i\". */\nexport function useHotkeys(binding: string, handler: (event: KeyboardEvent) => void, options: HotkeyOptions = {}): void {\n  const { enabled = true, target, inInputs = false, preventDefault = true, sequenceTimeout = 1000 } = options;\n  const latest = useRef(handler);\n  useEffect(() => {\n    latest.current = handler;\n  });\n  useEffect(() => {\n    if (!enabled) return;\n    const steps = binding.split(\" \").filter(Boolean).map(parseChord);\n    let position = 0;\n    let last = 0;\n    const node: HTMLElement | Document = target?.current ?? document;\n    const listener = (event: Event): void => {\n      const key = event as KeyboardEvent;\n      if (key.repeat || (!inInputs && typing(key.target))) return;\n      if (position > 0 && key.timeStamp - last > sequenceTimeout) position = 0;\n      const step = steps[position];\n      if (step && matches(step, key)) {\n        position += 1;\n        last = key.timeStamp;\n        if (position === steps.length) {\n          position = 0;\n          if (preventDefault) key.preventDefault();\n          latest.current(key);\n        }\n      } else if (![\"Shift\", \"Control\", \"Alt\", \"Meta\"].includes(key.key)) {\n        position = steps[0] && matches(steps[0], key) ? 1 : 0;\n        last = key.timeStamp;\n      }\n    };\n    node.addEventListener(\"keydown\", listener);\n    return () => node.removeEventListener(\"keydown\", listener);\n  }, [binding, enabled, target, inInputs, preventDefault, sequenceTimeout]);\n}\n\n/** A shortcut as people read it: \"⌘K\" on Apple systems, \"Ctrl+K\" elsewhere; a sequence as \"G then I\". */\nexport function formatHotkey(binding: string, words: { then: string } = { then: \"then\" }): string {\n  const apple = isApple();\n  return binding\n    .split(\" \")\n    .filter(Boolean)\n    .map((chord) => {\n      const parts = chord.split(\"+\").map((p) => p.trim().toLowerCase());\n      const key = parts.pop() ?? \"\";\n      const names = parts.map((p) => (p === \"mod\" ? (apple ? \"⌘\" : \"Ctrl\") : p === \"meta\" || p === \"cmd\" ? (apple ? \"⌘\" : \"Win\") : p === \"ctrl\" ? (apple ? \"⌃\" : \"Ctrl\") : p === \"alt\" || p === \"option\" ? (apple ? \"⌥\" : \"Alt\") : p === \"shift\" ? (apple ? \"⇧\" : \"Shift\") : p));\n      const shown = key.length === 1 ? key.toUpperCase() : key[0]?.toUpperCase() + key.slice(1);\n      return apple ? [...names, shown].join(\"\") : [...names, shown].join(\"+\");\n    })\n    .join(` ${words.then} `);\n}\n"
    }
  ],
  "meta": {
    "category": "lib",
    "when": "Shortcuts for frequent actions: opening command, saving, moving between items. Show each one where its action is (kbd, a menu's shortcut slot) and keep a list of them. Do not take keys a screen reader or the browser uses (single letters without a modifier only inside a focused widget; never Tab or the arrows on the page).",
    "example": "useHotkeys(\"mod+k\", () => setOpen(true));\nuseHotkeys(\"g i\", () => router.push(\"/inbox\"), { sequenceTimeout: 800 });\n<Kbd>{formatHotkey(\"mod+k\")}</Kbd>",
    "client": true
  }
}
