{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "command",
  "type": "registry:ui",
  "title": "Command",
  "description": "The command primitive.",
  "dependencies": [
    "lucide-react@^1.49.0",
    "radix-ui@^1.6.7"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/kbd.json",
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/command.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/command.tsx",
      "content": "import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';\nimport { Dialog as D } from 'radix-ui';\nimport { Search } from 'lucide-react';\nimport { ThemeRootScope, useThemeRoot } from '../lib/theme-root';\nimport { cn } from '../lib/utils';\nimport { Kbd } from './kbd';\n\nexport interface CommandItem {\n  /** What onSelect receives. Unique. */\n  value: string;\n  label: string;\n  /** Extra words that find it (\"preferences\" for Settings). */\n  keywords?: string[];\n  /** Keys shown at the end, one Kbd each: ['⌘', ','] . They only remind; the app binds them. */\n  shortcut?: string[];\n  icon?: ReactNode;\n  disabled?: boolean;\n}\nexport interface CommandGroup {\n  heading?: string;\n  items: CommandItem[];\n}\nexport interface CommandProps {\n  groups: CommandGroup[];\n  onSelect?: (value: string) => void;\n  placeholder?: string;\n  /** Shown when nothing matches. */\n  emptyText?: string;\n  /** Required: names the search box and the list. */\n  'aria-label': string;\n  /** What is announced as you type: default \"3 results\". Pass it translated. */\n  resultsLabel?: (count: number) => string;\n  query?: string;\n  onQueryChange?: (query: string) => void;\n  autoFocus?: boolean;\n  className?: string;\n}\n\n/**\n * A search box over a list of actions: the WAI-ARIA combobox with a listbox popup that is always open. Typing narrows the list\n * (every word must match the label or a keyword), Up and Down move the highlight (focus stays in the box), Enter chooses, Escape\n * clears the text. The number of results is announced as you type. Put it in a CommandDialog for the usual Cmd+K palette.\n */\nexport function Command({ groups, onSelect, placeholder = 'Type a command or search…', emptyText = 'No results', resultsLabel = (n) => `${n} ${n === 1 ? 'result' : 'results'}`, query, onQueryChange, autoFocus, className, ...aria }: CommandProps) {\n  const id = useId();\n  const [own, setOwn] = useState('');\n  const text = query ?? own;\n  const setText = (q: string) => {\n    setOwn(q);\n    onQueryChange?.(q);\n  };\n  const terms = text.toLowerCase().split(/\\s+/).filter(Boolean);\n  const shown = useMemo(\n    () => groups.map((g) => ({ ...g, items: g.items.filter((i) => terms.every((t) => `${i.label} ${(i.keywords ?? []).join(' ')}`.toLowerCase().includes(t))) })).filter((g) => g.items.length > 0),\n    [groups, text], // eslint-disable-line react-hooks/exhaustive-deps\n  );\n  const flat = shown.flatMap((g) => g.items);\n  const [active, setActive] = useState(0);\n  const list = useRef<HTMLDivElement>(null);\n  useEffect(() => setActive(Math.max(0, flat.findIndex((i) => !i.disabled))), [text]); // eslint-disable-line react-hooks/exhaustive-deps\n  useEffect(() => {\n    list.current?.querySelector<HTMLElement>(`[id=\"${id}-o${active}\"]`)?.scrollIntoView?.({ block: 'nearest' });\n  }, [active, id]);\n  const step = (dir: 1 | -1) => {\n    if (flat.every((i) => i.disabled)) return;\n    let n = active;\n    do n = (n + dir + flat.length) % flat.length;\n    while (flat[n]!.disabled);\n    setActive(n);\n  };\n  const choose = (i: number) => {\n    const item = flat[i];\n    if (item && !item.disabled) onSelect?.(item.value);\n  };\n  const onKey = (e: KeyboardEvent) => {\n    if (e.key === 'ArrowDown') {\n      e.preventDefault();\n      step(1);\n    } else if (e.key === 'ArrowUp') {\n      e.preventDefault();\n      step(-1);\n    } else if (e.key === 'Enter') {\n      e.preventDefault();\n      choose(active);\n    } else if (e.key === 'Escape' && text) {\n      e.preventDefault();\n      e.stopPropagation();\n      setText('');\n    }\n  };\n  let n = -1;\n  return (\n    <div className={cn('flex min-h-0 flex-col', className)}>\n      <div className=\"flex items-center gap-3 border-b border-kh-line px-4\">\n        <Search aria-hidden className=\"size-4 shrink-0 text-kh-muted\" />\n        <input\n          role=\"combobox\"\n          aria-expanded=\"true\"\n          aria-controls={`${id}-list`}\n          aria-autocomplete=\"list\"\n          aria-activedescendant={flat.length ? `${id}-o${active}` : undefined}\n          aria-label={aria['aria-label']}\n          autoComplete=\"off\"\n          spellCheck={false}\n          autoFocus={autoFocus}\n          placeholder={placeholder}\n          value={text}\n          onChange={(e) => setText(e.target.value)}\n          onKeyDown={onKey}\n          className=\"min-h-12 min-w-0 flex-1 bg-transparent text-kh-body text-kh-ink outline-none placeholder:text-kh-muted\"\n        />\n      </div>\n      <p role=\"status\" className=\"sr-only\">\n        {flat.length ? resultsLabel(flat.length) : emptyText}\n      </p>\n      <div ref={list} id={`${id}-list`} role=\"listbox\" aria-label={aria['aria-label']} className=\"max-h-80 overflow-y-auto p-2\">\n        {flat.length === 0 && <p className=\"px-3 py-8 text-center text-kh-small text-kh-muted\">{emptyText}</p>}\n        {shown.map((g, gi) => (\n          <div key={gi} role=\"group\" aria-labelledby={g.heading ? `${id}-g${gi}` : undefined} className=\"[&:not(:first-child)]:mt-2\">\n            {g.heading && (\n              <div id={`${id}-g${gi}`} role=\"presentation\" className=\"px-3 py-1.5 text-kh-caption font-medium text-kh-muted\">\n                {g.heading}\n              </div>\n            )}\n            {g.items.map((i) => {\n              n += 1;\n              const idx = n;\n              return (\n                <div\n                  key={i.value}\n                  id={`${id}-o${idx}`}\n                  role=\"option\"\n                  aria-selected={idx === active}\n                  aria-disabled={i.disabled || undefined}\n                  onPointerMove={() => !i.disabled && setActive(idx)}\n                  onMouseDown={(e) => e.preventDefault()}\n                  onClick={() => choose(idx)}\n                  className={cn(\n                    'flex min-h-11 cursor-pointer items-center gap-3 rounded-kh px-3 text-kh-small text-kh-ink',\n                    idx === active && 'bg-kh-surface-2',\n                    i.disabled && 'cursor-not-allowed text-kh-muted',\n                  )}\n                >\n                  {i.icon && <span aria-hidden className=\"shrink-0 text-kh-muted [&_svg]:size-4\">{i.icon}</span>}\n                  <span className=\"min-w-0 flex-1 truncate\">{i.label}</span>\n                  {i.shortcut && (\n                    <span aria-hidden className=\"flex shrink-0 gap-1\">\n                      {i.shortcut.map((k, ki) => (\n                        <Kbd key={ki}>{k}</Kbd>\n                      ))}\n                    </span>\n                  )}\n                </div>\n              );\n            })}\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n\nexport interface CommandDialogProps extends Omit<CommandProps, 'autoFocus' | 'query' | 'onQueryChange'> {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /** Required: names the dialog for assistive tech. Not shown. */\n  title: string;\n  /** A letter that opens and closes it with Cmd or Ctrl held: 'k'. */\n  hotkey?: string;\n}\n\n/** The palette: a Command in a dialog near the top of the page. Choosing an item closes it. Escape clears the text first, then closes. */\nexport function CommandDialog({ open, onOpenChange, title, hotkey, onSelect, ...rest }: CommandDialogProps) {\n  const root = useThemeRoot();\n  const [query, setQuery] = useState('');\n  const asked = useRef(query);\n  asked.current = query;\n  // Without a trigger of its own, the dialog gives focus back to whatever had it when it opened (a button, or the page for a hotkey).\n  const from = useRef<HTMLElement | null>(null);\n  const wasOpen = useRef(false);\n  if (open && !wasOpen.current && typeof document !== 'undefined') from.current = document.activeElement as HTMLElement | null;\n  wasOpen.current = open;\n  useEffect(() => {\n    if (!hotkey) return;\n    const on = (e: globalThis.KeyboardEvent) => {\n      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === hotkey.toLowerCase()) {\n        e.preventDefault();\n        onOpenChange(!open);\n      }\n    };\n    window.addEventListener('keydown', on);\n    return () => window.removeEventListener('keydown', on);\n  }, [hotkey, open, onOpenChange]);\n  useEffect(() => {\n    if (!open) setQuery('');\n  }, [open]);\n  return (\n    <ThemeRootScope>\n      <D.Root open={open} onOpenChange={onOpenChange}>\n        <D.Portal container={root}>\n          <D.Overlay className=\"fixed inset-0 z-50 bg-(--kh-scrim)\" />\n          <D.Content\n            onEscapeKeyDown={(e) => asked.current && e.preventDefault()}\n            onCloseAutoFocus={(e) => {\n              e.preventDefault();\n              from.current?.focus?.();\n            }}\n            className=\"fixed left-1/2 top-[12dvh] z-50 flex max-h-[76dvh] w-[min(36rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-kh-xl border border-kh-line bg-kh-surface text-kh-ink shadow-kh-3 outline-none\"\n          >\n            <D.Title className=\"sr-only\">{title}</D.Title>\n            <D.Description className=\"sr-only\">{title}</D.Description>\n            <Command\n              {...rest}\n              query={query}\n              onQueryChange={setQuery}\n              onSelect={(v) => {\n                onSelect?.(v);\n                onOpenChange(false);\n              }}\n            />\n          </D.Content>\n        </D.Portal>\n      </D.Root>\n    </ThemeRootScope>\n  );\n}\n"
    }
  ]
}
