{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "select",
  "type": "registry:ui",
  "title": "Select",
  "description": "A custom dropdown following the ARIA select-only combobox pattern: arrows, Home, End, Page keys, type-ahead, a hidden input for forms.",
  "dependencies": [
    "lucide-react@^1.49.0"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/select.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/select.tsx",
      "content": "import { forwardRef, useCallback, useEffect, useId, useRef, useState, type KeyboardEvent } from 'react';\nimport { Check, ChevronDown } from 'lucide-react';\nimport { cn } from '../lib/utils';\n\nexport interface SelectOption {\n  value: string;\n  label: string;\n  disabled?: boolean;\n}\n\nexport interface SelectProps {\n  options: SelectOption[];\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Shown while nothing is chosen. */\n  placeholder?: string;\n  /** Submits the value with a form. */\n  name?: string;\n  id?: string;\n  disabled?: boolean;\n  invalid?: boolean;\n  /** Needed when no <label htmlFor> or Field names it. */\n  'aria-label'?: string;\n  'aria-labelledby'?: string;\n  'aria-describedby'?: string;\n  className?: string;\n}\n\n/** Controlled or uncontrolled string value. */\nexport function useChoice(value: string | undefined, defaultValue: string | undefined, onChange?: (v: string) => void) {\n  const [own, setOwn] = useState(defaultValue ?? '');\n  const current = value ?? own;\n  const set = useCallback((v: string) => { setOwn(v); onChange?.(v); }, [onChange]);\n  return [current, set] as const;\n}\n\n/** The index of the enabled option to move to, from `from`, wrapping never: it stops at the ends. */\nexport const stepEnabled = (options: SelectOption[], from: number, dir: 1 | -1, by = 1) => {\n  let i = from;\n  let moved = 0;\n  for (let n = from + dir; n >= 0 && n < options.length && moved < by; n += dir) {\n    if (!options[n]!.disabled) { i = n; moved++; }\n  }\n  return i;\n};\nexport const firstEnabled = (options: SelectOption[]) => options.findIndex((o) => !o.disabled);\nexport const lastEnabled = (options: SelectOption[]) => options.length - 1 - [...options].reverse().findIndex((o) => !o.disabled);\n\nexport const listboxClass =\n  'absolute inset-x-0 top-full z-30 mt-1.5 max-h-64 overflow-y-auto overscroll-contain rounded-kh-lg border border-kh-line bg-kh-surface p-1 text-kh-ink shadow-kh-3';\nexport const optionClass =\n  'flex min-h-11 cursor-pointer select-none items-center justify-between gap-3 rounded-kh px-3 text-kh-small ' +\n  'data-[active=true]:bg-kh-surface-2 aria-disabled:cursor-not-allowed aria-disabled:opacity-50 aria-selected:font-medium';\n\n/**\n * A custom dropdown that follows the WAI-ARIA \"select-only combobox\" pattern: a button-like combobox that owns a\n * listbox, with arrow, Home, End, Page, type-ahead, Enter/Space, Escape and Tab behaviour. Tab commits the highlighted option; a click outside only closes the list. The list opens below the\n * control and is clipped by an ancestor that scrolls, so inside a small scrolling panel prefer NativeSelect.\n */\nexport const Select = forwardRef<HTMLButtonElement, SelectProps>(function Select(\n  { options, value, defaultValue, onValueChange, placeholder = 'Choose…', 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 [open, setOpen] = useState(false);\n  const [active, setActive] = useState(-1);\n  const typed = useRef({ text: '', at: 0 });\n  const list = useRef<HTMLUListElement>(null);\n  const selectedIndex = options.findIndex((o) => o.value === current);\n  const selected = options[selectedIndex];\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    setActive(at ?? (selectedIndex >= 0 ? selectedIndex : firstEnabled(options)));\n  };\n  const commit = (i: number) => {\n    const o = options[i];\n    if (o?.disabled) return; // a click on a disabled option does nothing\n    if (o) setCurrent(o.value);\n    setOpen(false);\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLButtonElement>) => {\n    if (disabled) return;\n    const k = e.key;\n    if (!open) {\n      if (k === 'ArrowDown' || k === 'ArrowUp' || k === 'Enter' || k === ' ') { e.preventDefault(); show(); return; }\n      if (k === 'Home') { e.preventDefault(); show(firstEnabled(options)); return; }\n      if (k === 'End') { e.preventDefault(); show(lastEnabled(options)); return; }\n    } else {\n      if (k === 'ArrowDown' && e.altKey) return;\n      if (k === 'ArrowDown') { e.preventDefault(); setActive((a) => stepEnabled(options, a, 1)); return; }\n      if (k === 'ArrowUp' && e.altKey) { e.preventDefault(); commit(active); return; }\n      if (k === 'ArrowUp') { e.preventDefault(); setActive((a) => stepEnabled(options, a, -1)); return; }\n      if (k === 'PageDown') { e.preventDefault(); setActive((a) => stepEnabled(options, a, 1, 10)); return; }\n      if (k === 'PageUp') { e.preventDefault(); setActive((a) => stepEnabled(options, a, -1, 10)); return; }\n      if (k === 'Home') { e.preventDefault(); setActive(firstEnabled(options)); return; }\n      if (k === 'End') { e.preventDefault(); setActive(lastEnabled(options)); return; }\n      if (k === 'Enter' || k === ' ') { e.preventDefault(); commit(active); return; }\n      if (k === 'Escape') { e.preventDefault(); e.stopPropagation(); setOpen(false); return; }\n      if (k === 'Tab') { commit(active); return; }\n    }\n    // Type-ahead: letters typed within a second of each other make one search string; a repeated letter cycles.\n    if (k.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey && k !== ' ') {\n      const t = typed.current;\n      t.text = e.timeStamp - t.at < 1000 ? t.text + k.toLowerCase() : k.toLowerCase();\n      t.at = e.timeStamp;\n      const same = [...t.text].every((c) => c === t.text[0]);\n      const needle = same ? t.text[0]! : t.text;\n      const from = open ? active : selectedIndex;\n      const start = from < 0 ? 0 : from + (same && t.text.length > 1 ? 1 : 0);\n      const order = options.map((_, i) => (start + i) % options.length);\n      const hit = order.find((i) => !options[i]!.disabled && options[i]!.label.toLowerCase().startsWith(needle));\n      if (hit !== undefined) { e.preventDefault(); if (open) setActive(hit); else show(hit); }\n    }\n  };\n\n  return (\n    <span className={cn('relative inline-flex min-w-0 max-w-full flex-col', className)}>\n      <button\n        ref={ref}\n        id={cid}\n        type=\"button\"\n        role=\"combobox\"\n        aria-haspopup=\"listbox\"\n        aria-expanded={open}\n        aria-controls={listId}\n        aria-activedescendant={open && active >= 0 ? `${cid}-o${active}` : undefined}\n        aria-invalid={invalid || undefined}\n        disabled={disabled}\n        onClick={() => (open ? setOpen(false) : show())}\n        // Leaving by pointer or script only closes the list: the arrowed option is committed by Enter, Space or Tab, never by a click elsewhere.\n        onBlur={() => setOpen(false)}\n        onKeyDown={onKeyDown}\n        className={cn(\n          'flex min-h-11 w-full min-w-0 items-center justify-between gap-2 rounded-kh border border-kh-line-strong bg-kh-surface py-2 pl-3 pr-3 text-left text-kh-body shadow-kh-1',\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          selected ? 'text-kh-ink' : 'text-kh-muted',\n        )}\n        {...aria}\n      >\n        <span className=\"truncate\">{selected ? selected.label : placeholder}</span>\n        <ChevronDown aria-hidden className={cn('size-4 shrink-0 text-kh-muted transition-transform duration-(--kh-dur)', open && 'rotate-180')} />\n      </button>\n      {name && <input type=\"hidden\" name={name} value={current} />}\n      {/* Pressing an option must not blur the combobox, or the blur handler would close the list before the click lands. */}\n      <ul ref={list} id={listId} role=\"listbox\" hidden={!open} aria-label={aria['aria-label']} aria-labelledby={aria['aria-labelledby']} onMouseDown={(e) => e.preventDefault()} className={listboxClass}>\n        {options.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={() => commit(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    </span>\n  );\n});\n"
    }
  ]
}
