{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "combobox",
  "type": "registry:ui",
  "title": "Combobox",
  "description": "A text field that filters a list as you type and picks one option: ARIA list-autocomplete combobox, match count announced, a form value.",
  "dependencies": [
    "lucide-react@^1.49.0"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/select.json",
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/combobox.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/combobox.tsx",
      "content": "import { forwardRef, useEffect, useId, useRef, useState, type KeyboardEvent } from 'react';\nimport { Check, ChevronDown } from 'lucide-react';\nimport { cn } from '../lib/utils';\nimport { firstEnabled, lastEnabled, listboxClass, optionClass, stepEnabled, useChoice, type SelectOption } from './select';\n\nexport interface ComboboxProps {\n  options: SelectOption[];\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  placeholder?: string;\n  /** Shown when the typed text matches nothing. */\n  emptyText?: string;\n  name?: string;\n  id?: string;\n  disabled?: boolean;\n  invalid?: boolean;\n  'aria-label'?: string;\n  'aria-labelledby'?: string;\n  'aria-describedby'?: string;\n  className?: string;\n}\n\n/**\n * A text field that filters a list as you type and picks one option: the WAI-ARIA combobox with a listbox popup and\n * list autocomplete. For fewer than about seven options use Select; for free text use Input. Leaving the field with\n * text that matches no option puts the chosen label back, so the shown text always equals the value.\n */\nexport const Combobox = forwardRef<HTMLInputElement, ComboboxProps>(function Combobox(\n  { options, value, defaultValue, onValueChange, placeholder, emptyText = 'No matches', name, id, disabled, invalid, className, ...aria },\n  ref,\n) {\n  const auto = useId();\n  const cid = id ?? auto;\n  const listId = `${cid}-list`;\n  const [current, setCurrent] = useChoice(value, defaultValue, onValueChange);\n  const labelOf = (v: string) => options.find((o) => o.value === v)?.label ?? '';\n  const [text, setText] = useState(labelOf(current));\n  const [open, setOpen] = useState(false);\n  const [filtering, setFiltering] = useState(false);\n  const [active, setActive] = useState(-1);\n  const list = useRef<HTMLUListElement>(null);\n\n  // Keep the text in step when the value changes from outside.\n  useEffect(() => { setText(labelOf(current)); setFiltering(false); }, [current]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const shown = filtering ? options.filter((o) => o.label.toLowerCase().includes(text.trim().toLowerCase())) : options;\n\n  useEffect(() => {\n    if (!open || active < 0) return;\n    list.current?.querySelector<HTMLElement>(`[id=\"${cid}-o${active}\"]`)?.scrollIntoView?.({ block: 'nearest' });\n  }, [open, active, cid]);\n\n  const show = (at?: number) => {\n    setOpen(true);\n    const sel = shown.findIndex((o) => o.value === current);\n    setActive(at ?? (sel >= 0 ? sel : firstEnabled(shown)));\n  };\n  const close = () => { setOpen(false); setFiltering(false); setText(labelOf(current)); };\n  const pick = (i: number) => {\n    const o = shown[i];\n    if (!o || o.disabled) return;\n    setCurrent(o.value);\n    setText(o.label);\n    setOpen(false);\n    setFiltering(false);\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n    const k = e.key;\n    if (k === 'ArrowDown') {\n      e.preventDefault();\n      if (!open) show();\n      else setActive((a) => (a < 0 ? firstEnabled(shown) : stepEnabled(shown, a, 1)));\n    } else if (k === 'ArrowUp') {\n      e.preventDefault();\n      if (!open) show(lastEnabled(shown));\n      else setActive((a) => (a < 0 ? lastEnabled(shown) : stepEnabled(shown, a, -1)));\n    } else if (k === 'Enter') {\n      if (open && active >= 0) { e.preventDefault(); pick(active); }\n    } else if (k === 'Escape') {\n      if (open) { e.preventDefault(); e.stopPropagation(); close(); }\n      else if (text) { e.preventDefault(); setText(''); setFiltering(false); setCurrent(''); }\n    }\n    // Home, End, PageUp/PageDown and the other keys stay with the text field.\n  };\n\n  return (\n    <span className={cn('relative inline-flex min-w-0 max-w-full flex-col', className)}>\n      <input\n        ref={ref}\n        id={cid}\n        type=\"text\"\n        role=\"combobox\"\n        autoComplete=\"off\"\n        aria-autocomplete=\"list\"\n        aria-expanded={open}\n        aria-controls={listId}\n        aria-activedescendant={open && active >= 0 && shown[active] ? `${cid}-o${active}` : undefined}\n        aria-invalid={invalid || undefined}\n        disabled={disabled}\n        placeholder={placeholder}\n        value={text}\n        onChange={(e) => {\n          const next = e.target.value;\n          setText(next);\n          setFiltering(true);\n          setOpen(true);\n          const hits = options.filter((o) => o.label.toLowerCase().includes(next.trim().toLowerCase()));\n          setActive(firstEnabled(hits));\n          if (!next) setCurrent('');\n        }}\n        onKeyDown={onKeyDown}\n        onBlur={() => close()}\n        className={cn(\n          'min-h-11 w-full min-w-0 rounded-kh border border-kh-line-strong bg-kh-surface py-2 pl-3 pr-10 text-kh-body text-kh-ink shadow-kh-1 placeholder:text-kh-muted',\n          'hover:border-kh-muted focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-(--kh-focus)',\n          'disabled:cursor-not-allowed disabled:bg-kh-surface-2 disabled:text-kh-muted aria-[invalid=true]:border-kh-danger',\n        )}\n        {...aria}\n      />\n      <ChevronDown aria-hidden className=\"pointer-events-none absolute right-3 top-[1.375rem] size-4 -translate-y-1/2 text-kh-muted\" />\n      {name && <input type=\"hidden\" name={name} value={current} />}\n      <ul ref={list} id={listId} role=\"listbox\" hidden={!open || shown.length === 0} aria-label={aria['aria-label']} aria-labelledby={aria['aria-labelledby']} onMouseDown={(e) => e.preventDefault()} className={listboxClass}>\n        {shown.map((o, i) => (\n          <li\n            key={o.value}\n            id={`${cid}-o${i}`}\n            role=\"option\"\n            aria-selected={o.value === current}\n            aria-disabled={o.disabled || undefined}\n            data-active={i === active}\n            onClick={() => pick(i)}\n            onMouseMove={() => !o.disabled && i !== active && setActive(i)}\n            className={optionClass}\n          >\n            <span className=\"truncate\">{o.label}</span>\n            {o.value === current && <Check aria-hidden className=\"size-4 shrink-0\" />}\n          </li>\n        ))}\n      </ul>\n      {open && shown.length === 0 && (\n        <div aria-hidden className={cn(listboxClass, 'px-3 py-3 text-kh-small text-kh-muted')}>{emptyText}</div>\n      )}\n      {/* Announces how many options match, so a screen reader hears the list change as the person types. */}\n      <span role=\"status\" className=\"sr-only\">{open && filtering ? (shown.length === 0 ? emptyText : `${shown.length} ${shown.length === 1 ? 'option' : 'options'} available`) : ''}</span>\n    </span>\n  );\n});\n"
    }
  ]
}
