{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "command-palette",
  "type": "registry:component",
  "title": "Command Palette",
  "description": "A Cmd+K modal with fuzzy search, grouped results, arrow-key navigation and a focus trap.",
  "author": "Hyperblur <hello@hyperblur.dev>",
  "dependencies": [],
  "registryDependencies": [],
  "categories": [
    "app-ui",
    "command",
    "search",
    "modal",
    "cmdk",
    "keyboard"
  ],
  "docs": "https://hyperblur.dev/effects/command-palette",
  "files": [
    {
      "path": "registry/hyperblur/command-palette.tsx",
      "type": "registry:component",
      "target": "components/hyperblur/command-palette.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface CommandPaletteItem {\n  id: string;\n  label: string;\n  group?: string;\n  hint?: string;\n  icon?: React.ReactNode;\n  onSelect?: () => void;\n}\n\nexport interface CommandPaletteProps\n  extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\" | \"onSelect\"> {\n  items: CommandPaletteItem[];\n  placeholder?: string;\n  hotkey?: boolean;\n  open?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  onSelect?: (id: string) => void;\n  inline?: boolean;\n  color?: string;\n  children?: React.ReactNode;\n}\n\nconst css = `\n.hb-cp {\n  position: relative;\n  color: #ededed;\n  font-family: var(--font-sans, ui-sans-serif, system-ui, sans-serif);\n  --hb-cp-accent: #2f7bff;\n}\n.hb-cp[data-inline=\"true\"] { width: 100%; }\n.hb-cp-trigger {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  box-sizing: border-box;\n  width: 100%;\n  min-width: 220px;\n  height: 36px;\n  margin: 0;\n  padding: 0 8px 0 10px;\n  border: 1px solid #262626;\n  border-radius: 10px;\n  background: #111111;\n  color: #8f8f8f;\n  font: inherit;\n  font-size: 13px;\n  text-align: left;\n  cursor: pointer;\n  transition: border-color .15s ease, background-color .15s ease, color .15s ease;\n  -webkit-tap-highlight-color: transparent;\n}\n.hb-cp-trigger:hover { border-color: #333333; background: #171717; color: #ededed; }\n.hb-cp-trigger:focus-visible { outline: 2px solid var(--hb-cp-accent); outline-offset: 2px; }\n.hb-cp-trigger-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.hb-cp-kbd {\n  flex: none;\n  padding: 1px 6px;\n  border: 1px solid #262626;\n  border-radius: 6px;\n  background: #171717;\n  color: #8f8f8f;\n  font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);\n  font-size: 11px;\n  line-height: 16px;\n}\n.hb-cp-svg { flex: none; width: 16px; height: 16px; }\n.hb-cp-overlay {\n  position: fixed;\n  inset: 0;\n  z-index: 1000;\n  display: flex;\n  align-items: flex-start;\n  justify-content: center;\n  box-sizing: border-box;\n  padding: 12vh 16px 16px;\n  background: rgba(0, 0, 0, .62);\n  animation: hb-cp-fade .16s ease both;\n}\n.hb-cp-panel {\n  width: 100%;\n  max-width: 560px;\n  overflow: hidden;\n  border: 1px solid #262626;\n  border-radius: 14px;\n  background: #111111;\n  box-shadow: 0 24px 80px rgba(0, 0, 0, .6);\n  text-align: left;\n}\n.hb-cp-overlay .hb-cp-panel { animation: hb-cp-pop .2s cubic-bezier(.2, .9, .2, 1) both; }\n.hb-cp[data-inline=\"true\"] .hb-cp-panel { max-width: none; box-shadow: none; }\n.hb-cp-field {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  box-sizing: border-box;\n  height: 44px;\n  padding: 0 14px;\n  border-bottom: 1px solid #262626;\n  color: #8f8f8f;\n}\n.hb-cp[data-inline=\"true\"] .hb-cp-field { height: 38px; }\n.hb-cp-input {\n  flex: 1;\n  min-width: 0;\n  margin: 0;\n  padding: 0;\n  border: 0;\n  outline: none;\n  background: transparent;\n  color: #ededed;\n  font: inherit;\n  font-size: 14px;\n}\n.hb-cp-input::placeholder { color: #8f8f8f; opacity: 1; }\n.hb-cp-list {\n  position: relative;\n  box-sizing: border-box;\n  max-height: 340px;\n  padding: 6px;\n  overflow-y: auto;\n  overscroll-behavior: contain;\n  scrollbar-width: thin;\n  scrollbar-color: #2a2a2a transparent;\n}\n.hb-cp[data-inline=\"true\"] .hb-cp-list { max-height: 132px; }\n.hb-cp-group-label {\n  padding: 8px 10px 4px;\n  color: #8f8f8f;\n  font-size: 11px;\n  font-weight: 500;\n  letter-spacing: .04em;\n  text-transform: uppercase;\n}\n.hb-cp[data-inline=\"true\"] .hb-cp-group-label { padding-top: 4px; }\n.hb-cp-item {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  padding: 6px 10px;\n  border-radius: 8px;\n  color: #ededed;\n  font-size: 13px;\n  line-height: 18px;\n  cursor: pointer;\n  user-select: none;\n}\n.hb-cp-item[aria-selected=\"true\"] { background: #1f1f1f; }\n.hb-cp-icon {\n  display: grid;\n  flex: none;\n  place-items: center;\n  width: 16px;\n  height: 16px;\n  color: #8f8f8f;\n  transition: color .15s ease;\n}\n.hb-cp-item[aria-selected=\"true\"] .hb-cp-icon { color: var(--hb-cp-accent); }\n.hb-cp-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.hb-cp-mark { color: var(--hb-cp-accent); font-weight: 600; }\n.hb-cp-empty { padding: 28px 16px; color: #8f8f8f; font-size: 13px; text-align: center; }\n@keyframes hb-cp-fade { from { opacity: 0; } to { opacity: 1; } }\n@keyframes hb-cp-pop {\n  from { opacity: 0; transform: translate3d(0, 8px, 0) scale(.97); }\n  to { opacity: 1; transform: translate3d(0, 0, 0) scale(1); }\n}\n@media (prefers-reduced-motion: reduce) {\n  .hb-cp-overlay, .hb-cp-overlay .hb-cp-panel { animation: none; }\n  .hb-cp-trigger, .hb-cp-icon { transition: none; }\n}\n`;\n\ninterface Row {\n  item: CommandPaletteItem;\n  idx: number[];\n  score: number;\n  n: number;\n}\n\ninterface Section {\n  key: string;\n  rows: Row[];\n}\n\nfunction fuzzy(q: string, text: string): { score: number; idx: number[] } | null {\n  if (!q) return { score: 0, idx: [] };\n  const t = text.toLowerCase();\n  const idx: number[] = [];\n  let from = 0;\n  let prev = -2;\n  let score = 0;\n  for (let i = 0; i < q.length; i++) {\n    const at = t.indexOf(q[i], from);\n    if (at < 0) return null;\n    idx.push(at);\n    score += 1;\n    if (at === prev + 1) score += 5;\n    if (at === 0 || \" -_\".includes(t[at - 1])) score += 4;\n    score -= (at - from) * 0.1;\n    prev = at;\n    from = at + 1;\n  }\n  if (t.startsWith(q)) score += 10;\n  else if (t.includes(q)) score += 6;\n  return { score, idx };\n}\n\nfunction Highlight({ text, idx }: { text: string; idx: number[] }) {\n  if (idx.length === 0) return <>{text}</>;\n  const marked = new Set(idx);\n  const parts: React.ReactNode[] = [];\n  let buf = \"\";\n  let on = false;\n  const flush = (key: number) => {\n    if (!buf) return;\n    parts.push(on ? <span key={key} className=\"hb-cp-mark\">{buf}</span> : buf);\n    buf = \"\";\n  };\n  for (let i = 0; i < text.length; i++) {\n    const m = marked.has(i);\n    if (m !== on) {\n      flush(i);\n      on = m;\n    }\n    buf += text[i];\n  }\n  flush(text.length);\n  return <>{parts}</>;\n}\n\nfunction SearchIcon() {\n  return (\n    <svg className=\"hb-cp-svg\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <circle cx=\"7\" cy=\"7\" r=\"4.5\" />\n      <path d=\"M10.5 10.5L14 14\" />\n    </svg>\n  );\n}\n\nfunction ArrowIcon() {\n  return (\n    <svg className=\"hb-cp-svg\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <path d=\"M3 8h9M8.5 4.5L12 8l-3.5 3.5\" />\n    </svg>\n  );\n}\n\ninterface PanelProps {\n  uid: string;\n  items: CommandPaletteItem[];\n  placeholder: string;\n  inline: boolean;\n  onClose: () => void;\n  onPick: (item: CommandPaletteItem) => void;\n}\n\nfunction Panel({ uid, items, placeholder, inline, onClose, onPick }: PanelProps) {\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const [query, setQuery] = React.useState(\"\");\n  const [active, setActive] = React.useState(0);\n\n  const { sections, flat } = React.useMemo(() => {\n    const q = query.replace(/\\s+/g, \"\").toLowerCase();\n    const matched: Row[] = [];\n    items.forEach((item) => {\n      const m = fuzzy(q, item.label);\n      if (m) matched.push({ item, idx: m.idx, score: m.score, n: 0 });\n    });\n    if (q) matched.sort((a, b) => b.score - a.score);\n    const out: Section[] = [];\n    const byKey = new Map<string, Section>();\n    matched.forEach((row) => {\n      const key = row.item.group ?? \"\";\n      let s = byKey.get(key);\n      if (!s) {\n        s = { key, rows: [] };\n        byKey.set(key, s);\n        out.push(s);\n      }\n      s.rows.push(row);\n    });\n    const all = out.flatMap((s) => s.rows);\n    all.forEach((row, i) => {\n      row.n = i;\n    });\n    return { sections: out, flat: all };\n  }, [items, query]);\n\n  const safe = flat.length === 0 ? -1 : Math.min(active, flat.length - 1);\n\n  React.useEffect(() => {\n    if (inline) return;\n    const previous = document.activeElement as HTMLElement | null;\n    const overflow = document.body.style.overflow;\n    document.body.style.overflow = \"hidden\";\n    inputRef.current?.focus();\n    return () => {\n      document.body.style.overflow = overflow;\n      if (previous && previous.isConnected) previous.focus();\n    };\n  }, [inline]);\n\n  React.useEffect(() => {\n    const list = listRef.current;\n    if (!list || safe < 0) return;\n    const el = list.querySelector<HTMLElement>(`[data-n=\"${safe}\"]`);\n    if (!el) return;\n    const top = el.offsetTop;\n    const bottom = top + el.offsetHeight;\n    if (top - 28 < list.scrollTop) list.scrollTop = Math.max(0, top - 28);\n    else if (bottom + 6 > list.scrollTop + list.clientHeight) list.scrollTop = bottom + 6 - list.clientHeight;\n  }, [safe]);\n\n  function handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {\n    const n = flat.length;\n    if (e.key === \"Escape\") {\n      if (inline) return;\n      e.preventDefault();\n      e.stopPropagation();\n      onClose();\n    } else if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      if (n) setActive(safe < 0 ? 0 : (safe + 1) % n);\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      if (n) setActive(safe < 0 ? n - 1 : (safe - 1 + n) % n);\n    } else if (e.key === \"Home\") {\n      if (n) {\n        e.preventDefault();\n        setActive(0);\n      }\n    } else if (e.key === \"End\") {\n      if (n) {\n        e.preventDefault();\n        setActive(n - 1);\n      }\n    } else if (e.key === \"Enter\") {\n      if (safe >= 0) {\n        e.preventDefault();\n        onPick(flat[safe].item);\n      }\n    } else if (e.key === \"Tab\" && !inline) {\n      e.preventDefault();\n      inputRef.current?.focus();\n    }\n  }\n\n  const listId = `${uid}-list`;\n\n  return (\n    <div\n      className=\"hb-cp-panel\"\n      role={inline ? \"group\" : \"dialog\"}\n      aria-modal={inline ? undefined : true}\n      aria-label=\"Command palette\"\n      onKeyDown={handleKeyDown}\n    >\n      <div className=\"hb-cp-field\">\n        <SearchIcon />\n        <input\n          ref={inputRef}\n          className=\"hb-cp-input\"\n          type=\"text\"\n          role=\"combobox\"\n          aria-expanded=\"true\"\n          aria-controls={listId}\n          aria-autocomplete=\"list\"\n          aria-activedescendant={safe >= 0 ? `${uid}-opt-${safe}` : undefined}\n          aria-label=\"Search commands\"\n          placeholder={placeholder}\n          value={query}\n          autoComplete=\"off\"\n          autoCorrect=\"off\"\n          spellCheck={false}\n          onChange={(e) => {\n            setQuery(e.target.value);\n            setActive(0);\n          }}\n        />\n      </div>\n      <div ref={listRef} id={listId} className=\"hb-cp-list\" role=\"listbox\" aria-label=\"Results\">\n        {flat.length === 0 ? (\n          <div className=\"hb-cp-empty\" role=\"status\">\n            No results for &ldquo;{query.trim()}&rdquo;\n          </div>\n        ) : (\n          sections.map((section) => {\n            const labelId = `${uid}-g-${section.key}`;\n            return (\n              <div key={section.key} role=\"group\" aria-labelledby={section.key ? labelId : undefined}>\n                {section.key ? (\n                  <div id={labelId} className=\"hb-cp-group-label\" role=\"presentation\">\n                    {section.key}\n                  </div>\n                ) : null}\n                {section.rows.map((row) => (\n                  <div\n                    key={row.item.id}\n                    id={`${uid}-opt-${row.n}`}\n                    role=\"option\"\n                    aria-selected={safe === row.n}\n                    data-n={row.n}\n                    className=\"hb-cp-item\"\n                    onPointerMove={() => {\n                      if (safe !== row.n) setActive(row.n);\n                    }}\n                    onClick={() => onPick(row.item)}\n                  >\n                    <span className=\"hb-cp-icon\" aria-hidden=\"true\">\n                      {row.item.icon ?? <ArrowIcon />}\n                    </span>\n                    <span className=\"hb-cp-label\">\n                      <Highlight text={row.item.label} idx={row.idx} />\n                    </span>\n                    {row.item.hint ? <kbd className=\"hb-cp-kbd\">{row.item.hint}</kbd> : null}\n                  </div>\n                ))}\n              </div>\n            );\n          })\n        )}\n      </div>\n    </div>\n  );\n}\n\nexport function CommandPalette({\n  items,\n  placeholder = \"Search…\",\n  hotkey = true,\n  open,\n  onOpenChange,\n  onSelect,\n  inline = false,\n  color = \"#2f7bff\",\n  children,\n  className = \"\",\n  style,\n  ...rest\n}: CommandPaletteProps) {\n  const uid = React.useId();\n  const [inner, setInner] = React.useState(false);\n  const isOpen = inline || (open ?? inner);\n\n  const setOpen = React.useCallback(\n    (next: boolean) => {\n      if (open === undefined) setInner(next);\n      onOpenChange?.(next);\n    },\n    [open, onOpenChange],\n  );\n\n  React.useEffect(() => {\n    if (!hotkey || inline) return;\n    const onKey = (e: KeyboardEvent) => {\n      if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === \"k\") {\n        e.preventDefault();\n        setOpen(!isOpen);\n      }\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [hotkey, inline, isOpen, setOpen]);\n\n  function pick(item: CommandPaletteItem) {\n    item.onSelect?.();\n    onSelect?.(item.id);\n    if (!inline) setOpen(false);\n  }\n\n  const vars = { \"--hb-cp-accent\": color, ...style } as React.CSSProperties;\n\n  const panel = (\n    <Panel\n      uid={uid}\n      items={items}\n      placeholder={placeholder}\n      inline={inline}\n      onClose={() => setOpen(false)}\n      onPick={pick}\n    />\n  );\n\n  return (\n    <div className={`hb-cp ${className}`} data-inline={inline} style={vars} {...rest}>\n      <style href=\"hb-command-palette\" precedence=\"default\">{css}</style>\n      {inline ? null : (\n        <button\n          type=\"button\"\n          className=\"hb-cp-trigger\"\n          aria-haspopup=\"dialog\"\n          aria-expanded={isOpen}\n          onClick={() => setOpen(true)}\n        >\n          {children ?? (\n            <>\n              <SearchIcon />\n              <span className=\"hb-cp-trigger-label\">{placeholder}</span>\n              {hotkey ? <kbd className=\"hb-cp-kbd\">⌘K</kbd> : null}\n            </>\n          )}\n        </button>\n      )}\n      {isOpen ? (\n        inline ? (\n          panel\n        ) : (\n          <div\n            className=\"hb-cp-overlay\"\n            onPointerDown={(e) => {\n              if (e.target === e.currentTarget) setOpen(false);\n            }}\n          >\n            {panel}\n          </div>\n        )\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ]
}