{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "combobox",
  "title": "Combobox",
  "description": "Single-value combobox: a Select you can type into. Local filtering or an async source (abort, status, retry), optional groups; the list docks to the frame.",
  "dependencies": [
    "@base-ui/react@1.9.0"
  ],
  "registryDependencies": [
    "@keyline-ui/keyline",
    "utils",
    "@keyline-ui/keyline-scope",
    "@keyline-ui/options",
    "@keyline-ui/field",
    "@keyline-ui/keyline-render"
  ],
  "files": [
    {
      "path": "src/registry/keyline/ui/combobox.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { Combobox as ComboboxPrimitive } from \"@base-ui/react/combobox\";\nimport { Field as FieldPrimitive } from \"@base-ui/react/field\";\n\nimport { cn } from \"@/lib/utils\";\nimport { dockGeometry, scopeProps, useKeylineScope } from \"../lib/keyline-scope\";\nimport { resolveClassName, resolveStyle } from \"../lib/keyline-render\";\nimport { groupBy, hasGroups } from \"../lib/options\";\nimport { FieldMessages, type FieldParticipantProps } from \"./field\";\n\n/*\n * Combobox, as parts named as Base UI names them, and `Combobox`, the field built from them (a label, options or\n * an async source, the field's messages). One field frame of cells:\n *\n *   ┌────────────────────────────────┬────┬────┐\n *   │ Rotterdam Europoort            │ ×  │ ⌄  │   input cell · clear cell (while chosen) · caret cell\n *   └────────────────────────────────┴────┴────┘\n *\n * The list docks to the frame exactly like Select's (dock geometry, owner weight on the shared edge, no cut) and\n * uses Select's two cues: the chosen option carries the exclusive-choice mark, the cursor is the inverse row.\n */\n\ntype Layout = \"control\" | \"cell\";\n\n/* ------------------------------------------------------------------ parts */\n\n/** Base UI's Combobox.Root: state, filtering, the form value. Generic over the item value and `multiple`. */\nconst ComboboxRoot = ComboboxPrimitive.Root;\n\nconst cellButton = cn(\n  \"grid w-9 flex-none cursor-pointer place-items-center bg-transparent p-0 text-inherit\",\n  \"hover:bg-kl-tint active:bg-kl-press active:[&>svg]:translate-y-px\",\n  // a button cell inside the frame draws its own inset ring, never the frame's edge (one indicator)\n  \"focus-visible:outline-(length:--kl-ring) focus-visible:outline-offset-(--kl-ring-in) focus-visible:outline-kl-focus\",\n  \"focus-visible:outline-solid\",\n  \"data-disabled:cursor-not-allowed data-disabled:text-kl-dis data-disabled:hover:bg-transparent\",\n);\n\n/**\n * The field frame: a row of cells (the input, then the clear and caret cells). Its edge is the focus indicator.\n * `layout=\"cell\"`: it fills a cell of an enclosing frame (a toolbar) instead of drawing its own.\n */\nfunction ComboboxInputGroup({\n  layout = \"control\",\n  className,\n  ...props\n}: ComboboxPrimitive.InputGroup.Props & { layout?: Layout }): React.ReactElement {\n  return (\n    <ComboboxPrimitive.InputGroup\n      data-kl-layout={layout}\n      className={resolveClassName(\n        cn(\n          \"kl-ctl kl-cells kl-field-frame kl-edge cursor-text\",\n          \"data-[kl-layout=cell]:h-full data-[kl-layout=cell]:min-h-(--kl-row)\",\n          // invalid: red frame, and the edge at ring weight, as a field\n          \"data-invalid:border-kl-red data-invalid:[--kl-cut-line:var(--kl-red)] data-invalid:[--kl-edge-w:var(--kl-ring)]\",\n          // disabled: out of service\n          \"data-disabled:cursor-not-allowed data-disabled:border-kl-dis-line data-disabled:bg-(image:--kl-hatch)\",\n          \"data-disabled:[--kl-cut-line:var(--kl-dis-line)] data-disabled:[&>*+*]:border-kl-dis-line\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-input-group\"\n    />\n  );\n}\n\n/** The text input cell. */\nfunction ComboboxInput({ className, ...props }: ComboboxPrimitive.Input.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Input\n      className={resolveClassName(\n        cn(\n          \"m-0 w-0 min-w-0 flex-[1_1_auto] bg-transparent px-(--kl-inset) text-ellipsis text-inherit outline-0\",\n          \"font-(family-name:--kl-font) text-(length:--kl-text-lead)\",\n          \"placeholder:text-kl-ink-3 placeholder:opacity-100\",\n          \"data-disabled:cursor-not-allowed data-disabled:text-kl-dis\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-input\"\n    />\n  );\n}\n\n/** The caret cell: opens the list; inverse while it is open, as Select's. */\nfunction ComboboxTrigger({\n  className,\n  children,\n  nativeButton,\n  role,\n  ...props\n}: ComboboxPrimitive.Trigger.Props): React.ReactElement {\n  // Base UI gives a trigger beside the input no role, which drops the button role a non-native element needs\n  // (`render={<div />}` with `nativeButton={false}`); restore it. An explicit `role` wins.\n  const restored = role ?? (nativeButton === false ? \"button\" : undefined);\n  return (\n    <ComboboxPrimitive.Trigger\n      nativeButton={nativeButton}\n      {...(restored ? { role: restored } : null)}\n      className={resolveClassName(\n        cn(\n          cellButton,\n          \"data-popup-open:bg-kl-inverse data-popup-open:text-kl-on-inverse\",\n          \"forced-colors:data-popup-open:bg-[Highlight] forced-colors:data-popup-open:text-[HighlightText]\",\n          \"forced-colors:data-popup-open:forced-color-adjust-none\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-trigger\"\n    >\n      {children ?? (\n        <svg\n          viewBox=\"0 0 16 16\"\n          width=\"16\"\n          height=\"16\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth=\"1.75\"\n          strokeLinecap=\"square\"\n          aria-hidden\n        >\n          <path d=\"m4 6 4 4 4-4\" />\n        </svg>\n      )}\n    </ComboboxPrimitive.Trigger>\n  );\n}\n\nconst Cross = () => (\n  <svg\n    viewBox=\"0 0 16 16\"\n    width=\"12\"\n    height=\"12\"\n    fill=\"none\"\n    stroke=\"currentColor\"\n    strokeWidth=\"2.25\"\n    strokeLinecap=\"square\"\n    aria-hidden\n  >\n    <path d=\"m4.5 4.5 7 7m0-7-7 7\" />\n  </svg>\n);\n\n/** The clear cell. Give it an accessible name (`aria-label`): it shows only a cross. */\nfunction ComboboxClear({\n  className,\n  children,\n  ...props\n}: ComboboxPrimitive.Clear.Props & { \"aria-label\": string }): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Clear\n      className={resolveClassName(cn(cellButton, \"text-kl-ink-2 hover:text-kl-ink\"), className)}\n      {...props}\n      data-slot=\"combobox-clear\"\n    >\n      {children ?? <Cross />}\n    </ComboboxPrimitive.Clear>\n  );\n}\n\ntype PopupProps = ComboboxPrimitive.Popup.Props &\n  Pick<\n    ComboboxPrimitive.Positioner.Props,\n    \"anchor\" | \"side\" | \"align\" | \"sideOffset\" | \"alignOffset\" | \"collisionPadding\"\n  > & {\n    /** The frame the list docks to: `cell` when the input group has `layout=\"cell\"`. */\n    layout?: Layout;\n    /** Where the portal renders (defaults to <body>). */\n    container?: ComboboxPrimitive.Portal.Props[\"container\"];\n    /** Props for Base UI's Combobox.Portal. */\n    portalProps?: Omit<ComboboxPrimitive.Portal.Props, \"container\" | \"children\">;\n  };\n\n/**\n * The list's surface: Base UI's Portal, Positioner and Popup in one part, with the positioner's placement props\n * lifted. It docks to the frame (its shared edge on the frame's keyline, no cut) and carries the configuration\n * (cut, density, motion, theme, dir) of the place it is written. `aria-busy` dims the list.\n */\nfunction ComboboxPopup({\n  layout = \"control\",\n  anchor,\n  side,\n  align = \"start\",\n  sideOffset,\n  alignOffset,\n  collisionPadding = 12,\n  container,\n  portalProps,\n  className,\n  style,\n  ...props\n}: PopupProps): React.ReactElement {\n  const dock = dockGeometry(layout);\n  const [marker, scope, probe] = useKeylineScope(false, container);\n  return (\n    <>\n      {marker}\n      <ComboboxPrimitive.Portal container={container} {...portalProps}>\n        {probe}\n        <ComboboxPrimitive.Positioner\n          anchor={anchor}\n          side={side}\n          align={align}\n          sideOffset={sideOffset ?? dock.sideOffset}\n          alignOffset={alignOffset ?? dock.alignOffset}\n          collisionPadding={collisionPadding}\n          {...scopeProps(scope, { className: \"kl-positioner\" })}\n        >\n          <ComboboxPrimitive.Popup\n            className={resolveClassName(\n              cn(\n                \"kl-attached kl-dock kl-dock-min group/combobox-popup [--kl-dock-w:15rem]\",\n                \"flex max-h-[min(var(--available-height),380px)] flex-col bg-kl-cell text-kl-ink outline-0\",\n              ),\n              className,\n            )}\n            style={resolveStyle(dock.style, style)}\n            {...props}\n            data-slot=\"combobox-popup\"\n          />\n        </ComboboxPrimitive.Positioner>\n      </ComboboxPrimitive.Portal>\n    </>\n  );\n}\n\n/** The live region that says what the list is (searching, n matches, an error), in the Code voice. */\nfunction ComboboxStatus({ className, ...props }: ComboboxPrimitive.Status.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Status\n      className={resolveClassName(\"data-kl-error:font-bold data-kl-error:text-kl-red-text\", className)}\n      {...props}\n      data-slot=\"combobox-status\"\n    />\n  );\n}\n\n/** The options. Rows are separated by soft rules; it is not drawn while it has none. */\nfunction ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.List\n      className={resolveClassName(\n        cn(\n          \"flex-[1_1_auto] scroll-py-1 overflow-auto overscroll-contain outline-0 empty:hidden\",\n          \"[scrollbar-width:thin] [scrollbar-color:var(--kl-ink-3)_transparent]\",\n          \"group-aria-busy/combobox-popup:opacity-55\",\n          \"[&_[data-slot=combobox-item]+[data-slot=combobox-item]]:border-t-(length:--kl-k1)\",\n          \"[&_[data-slot=combobox-item]+[data-slot=combobox-item]]:border-t-kl-line-soft\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-list\"\n    />\n  );\n}\n\n/** Base UI's Combobox.Collection: renders a Group's items with a function child. */\nconst ComboboxCollection = ComboboxPrimitive.Collection;\n\ntype ItemProps = ComboboxPrimitive.Item.Props & {\n  description?: React.ReactNode;\n  /** Trailing code cell (an ID, a unit, a short key). */\n  code?: React.ReactNode;\n};\n\n/**\n * One option: the choice mark (the exclusive-choice square, shown while chosen), the label with an optional\n * description, and an optional trailing code. The cursor is the inverse row.\n */\nfunction ComboboxItem({ className, description, code, children, ...props }: ItemProps): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Item\n      className={resolveClassName(\n        cn(\n          \"group/combobox-item grid min-h-(--kl-row) cursor-default grid-cols-[36px_minmax(0,1fr)_auto] items-stretch\",\n          \"outline-0 select-none\",\n          \"data-highlighted:bg-kl-inverse data-highlighted:text-kl-on-inverse\",\n          \"data-disabled:cursor-not-allowed data-disabled:bg-(image:--kl-hatch) data-disabled:text-kl-dis\",\n          \"forced-colors:data-highlighted:outline-3 forced-colors:data-highlighted:outline-offset-[-4px]\",\n          \"forced-colors:data-highlighted:outline-[Highlight]\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-item\"\n    >\n      <span\n        className=\"grid place-items-center border-e-(length:--kl-k1) border-e-kl-seam group-data-highlighted/combobox-item:border-e-kl-on-inverse\"\n        aria-hidden\n      >\n        <ComboboxPrimitive.ItemIndicator\n          data-slot=\"combobox-item-indicator\"\n          className=\"grid size-4 place-items-center border-2 border-current not-data-selected:invisible\"\n          keepMounted\n        >\n          <span className=\"size-1.5 bg-current\" />\n        </ComboboxPrimitive.ItemIndicator>\n      </span>\n      <span\n        data-slot=\"combobox-item-label\"\n        className=\"grid min-w-0 content-center gap-px px-(--kl-inset) py-2 leading-[1.3] wrap-anywhere\"\n      >\n        <span>{children}</span>\n        {description ? (\n          <small\n            className={cn(\n              \"text-(length:--kl-text-meta) text-kl-ink-2 group-data-disabled/combobox-item:text-kl-ink-2\",\n              \"group-data-highlighted/combobox-item:text-inherit\",\n            )}\n          >\n            {description}\n          </small>\n        ) : null}\n      </span>\n      {code != null ? (\n        <span\n          data-slot=\"combobox-item-code\"\n          className=\"kl-code flex items-center px-(--kl-inset) whitespace-nowrap group-data-highlighted/combobox-item:text-inherit\"\n        >\n          {code}\n        </span>\n      ) : null}\n    </ComboboxPrimitive.Item>\n  );\n}\n\n/** Options under one heading. A group after a group is divided by a seam. */\nfunction ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Group\n      className={resolveClassName(\n        \"[[data-slot=combobox-group]+&]:border-t-(length:--kl-k1) [[data-slot=combobox-group]+&]:border-t-kl-seam\",\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-group\"\n    />\n  );\n}\n\n/** A group's heading, in the Code voice; the group's first option sits on its seam. */\nfunction ComboboxGroupLabel({ className, ...props }: ComboboxPrimitive.GroupLabel.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.GroupLabel\n      className={resolveClassName(\n        cn(\n          \"block px-(--kl-inset) pt-2.5 pb-1 text-kl-ink-2\",\n          \"font-(family-name:--kl-font-mono) text-(length:--kl-text-code)/[1.2] font-medium\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-group-label\"\n    />\n  );\n}\n\n/** Shown in place of the list while no option matches; render nothing in it while a search is pending. */\nfunction ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Empty\n      className={resolveClassName(\n        \"not-empty:grid not-empty:min-h-16 not-empty:grid-cols-[72px_1fr] not-empty:items-center\",\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-empty\"\n    />\n  );\n}\n\n/** The chosen values of a `multiple` combobox, before the input, in the frame. */\nfunction ComboboxChips({ className, ...props }: ComboboxPrimitive.Chips.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Chips\n      className={resolveClassName(\"flex min-w-0 flex-1 flex-wrap items-center gap-1 px-1.5 py-1\", className)}\n      {...props}\n      data-slot=\"combobox-chips\"\n    />\n  );\n}\n\n/**\n * One chosen value: a yellow tag. Reached with the arrow keys it is the cursor (ink); the frame shows the focus\n * edge, so the chip draws no ring of its own.\n */\nfunction ComboboxChip({ className, ...props }: ComboboxPrimitive.Chip.Props): React.ReactElement {\n  return (\n    <ComboboxPrimitive.Chip\n      className={resolveClassName(\n        cn(\n          \"kl-edge-part group/combobox-chip inline-flex h-[26px] items-stretch\",\n          \"border-(length:--kl-k1) border-kl-on-yellow bg-kl-yellow text-kl-on-yellow\",\n          \"text-(length:--kl-text-label) font-(--kl-weight-strong)\",\n          \"[&>span]:flex [&>span]:items-center [&>span]:px-2 [&>span]:whitespace-nowrap\",\n          \"focus:border-kl-on-inverse focus:bg-kl-inverse focus:text-kl-on-inverse focus:outline-0\",\n          \"forced-colors:border-[HighlightText] forced-colors:bg-[Highlight] forced-colors:text-[HighlightText]\",\n          \"forced-colors:forced-color-adjust-none forced-colors:focus:border-2 forced-colors:focus:border-[Highlight]\",\n          \"forced-colors:focus:bg-[Canvas] forced-colors:focus:text-[CanvasText]\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-chip\"\n    />\n  );\n}\n\n/** Removes its chip. Its accessible name is required (`aria-label`, e.g. \"Remove Rotterdam\"): it shows only a cross. */\nfunction ComboboxChipRemove({\n  className,\n  children,\n  ...props\n}: ComboboxPrimitive.ChipRemove.Props & { \"aria-label\": string }): React.ReactElement {\n  return (\n    <ComboboxPrimitive.ChipRemove\n      className={resolveClassName(\n        cn(\n          \"grid w-6 cursor-pointer place-items-center bg-transparent p-0 text-inherit\",\n          \"border-s-(length:--kl-k1) border-s-kl-on-yellow active:[&>svg]:translate-y-px\",\n          \"group-data-highlighted/combobox-chip:bg-kl-on-yellow hover:bg-kl-on-yellow hover:text-kl-yellow\",\n          \"group-data-highlighted/combobox-chip:text-kl-yellow\",\n          \"group-focus/combobox-chip:border-s-kl-on-inverse group-focus/combobox-chip:bg-transparent\",\n          \"group-focus/combobox-chip:text-inherit\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"combobox-chip-remove\"\n    >\n      {children ?? <Cross />}\n    </ComboboxPrimitive.ChipRemove>\n  );\n}\n\n/* ------------------------------------------------------------------ the field */\n\nexport type ComboboxOption = {\n  value: string;\n  label: string;\n  description?: React.ReactNode;\n  /** Trailing code cell (an ID, a unit, a short key). */\n  code?: React.ReactNode;\n  /** Options sharing a group are listed under one heading, in first-appearance order. */\n  group?: string;\n  disabled?: boolean;\n};\n\ntype Group = { value: string; items: ComboboxOption[] };\n\ntype ComboboxProps = {\n  label: React.ReactNode;\n  /**\n   * Local options, filtered by Base UI as the user types (label match, locale-aware).\n   * With `loadOptions`, these are the options known before any search (recents, the current value):\n   * they are listed for an empty query and give a controlled value its label.\n   */\n  options?: ComboboxOption[];\n  /** Async source. Called on open and on every edit; a superseded request is aborted. Errors offer Retry. */\n  loadOptions?: (query: string, signal: AbortSignal) => Promise<ComboboxOption[]>;\n  /** The chosen option's `value`. `null` is no choice. */\n  value?: string | null;\n  defaultValue?: string | null;\n  /** Called with the chosen value, its option, and Base UI's event details (the reason, the event). */\n  onValueChange?: (\n    value: string | null,\n    option: ComboboxOption | null,\n    eventDetails: ComboboxPrimitive.Root.ChangeEventDetails,\n  ) => void;\n  placeholder?: string;\n  /** Names the things listed, for the status line and the empty state. */\n  noun?: [singular: string, plural: string];\n  /** control: its own 2px frame. cell: a cell of an enclosing frame (e.g. a toolbar); the label is visually hidden. */\n  layout?: Layout;\n  disabled?: boolean;\n  readOnly?: boolean;\n  required?: boolean;\n  /** Form field name; the submitted value (FormData and Base UI Form values) is the option's `value`. */\n  name?: string;\n  /** Offer a clear cell while a value is chosen. Default true. */\n  clearable?: boolean;\n  id?: string;\n  className?: string;\n  container?: ComboboxPrimitive.Portal.Props[\"container\"];\n} & FieldParticipantProps;\n\n/* the typed text, underlined in each match */\nfunction highlight(text: string, q: string) {\n  const i = q ? text.toLocaleLowerCase().indexOf(q.toLocaleLowerCase()) : -1;\n  if (i < 0) return text;\n  return (\n    <>\n      {text.slice(0, i)}\n      <mark\n        className={cn(\n          \"bg-transparent font-[inherit] text-inherit underline decoration-kl-cobalt-text decoration-2 underline-offset-3\",\n          \"group-data-highlighted/combobox-item:decoration-kl-yellow\",\n        )}\n      >\n        {text.slice(i, i + q.length)}\n      </mark>\n      {text.slice(i + q.length)}\n    </>\n  );\n}\n\nfunction grouped(list: ComboboxOption[]): ComboboxOption[] | Group[] {\n  return hasGroups(list) ? groupBy(list).map((g) => ({ value: g.group, items: g.items })) : list;\n}\n\n/**\n * Single-value combobox: a Select you can type into, built from the parts above.\n *\n * Two sources:\n * - `options`: local, filtered by Base UI as you type;\n * - `loadOptions`: async. A status line says what the list is (searching, n matches, the error with\n *   Retry); a superseded request is aborted; a pending search runs the pending segment on the panel's\n *   keyline. The chosen option stays known, so its label survives a new search.\n *\n * Keyboard, typeahead, focus return, form value and ARIA are Base UI Combobox's. Escape closes the list\n * and the input shows the chosen label again. Escape on a closed field keeps the choice (Base UI would clear\n * it) and passes on, so an enclosing dialog closes; the clear cell is the way to clear.\n *\n * The wrapper is a Base UI Field.Root: a Form collects the value under `name`, and the Form's\n * `errors`, `validate` and `required` produce the message under the frame.\n */\nfunction Combobox({\n  label,\n  options = [],\n  loadOptions,\n  value,\n  defaultValue = null,\n  onValueChange,\n  placeholder = \"Search…\",\n  noun = [\"option\", \"options\"],\n  layout = \"control\",\n  disabled,\n  readOnly,\n  required,\n  invalid,\n  error: errorMessage,\n  description,\n  validate,\n  validationMode,\n  orientation,\n  name,\n  clearable = true,\n  id: idProp,\n  className,\n  container,\n}: ComboboxProps) {\n  const autoId = React.useId();\n  const id = idProp ?? autoId;\n  const async = !!loadOptions;\n\n  // every option this instance has seen, so a value (controlled or chosen from a past search) has a label\n  const known = React.useRef(new Map<string, ComboboxOption>());\n  for (const o of options) known.current.set(o.value, o);\n\n  const [inner, setInner] = React.useState<string | null>(defaultValue);\n  const current = value !== undefined ? value : inner;\n  const selected = current != null ? (known.current.get(current) ?? null) : null;\n\n  const [query, setQuery] = React.useState(\"\");\n  const [results, setResults] = React.useState<ComboboxOption[] | null>(null);\n  const [error, setError] = React.useState<string | null>(null);\n  const [pending, setPending] = React.useState(false);\n  const ctrl = React.useRef<AbortController | null>(null);\n  // The open handler runs in the same event as the input change that opened the list (a paste opens and\n  // searches at once), before React re-renders: it reads the latest query and the request in flight from\n  // refs, never from the render it was created in, so it cannot supersede that search with a stale one.\n  const latest = React.useRef(\"\");\n  const inflight = React.useRef(false);\n\n  const load = React.useCallback(\n    (q: string) => {\n      if (!loadOptions) return;\n      ctrl.current?.abort();\n      const c = new AbortController();\n      ctrl.current = c;\n      inflight.current = true;\n      setPending(true);\n      setError(null);\n      loadOptions(q, c.signal).then(\n        (r) => {\n          if (c.signal.aborted) return;\n          inflight.current = false;\n          r.forEach((o) => known.current.set(o.value, o));\n          setResults(r);\n          setPending(false);\n        },\n        (e: unknown) => {\n          if (c.signal.aborted) return;\n          inflight.current = false;\n          setError(e instanceof Error ? e.message : \"Couldn't load options\");\n          setPending(false);\n        },\n      );\n    },\n    [loadOptions],\n  );\n  React.useEffect(() => () => ctrl.current?.abort(), []);\n\n  // async: the list is the latest results (the known options before the first search); the chosen option\n  // is kept in the collection so Base UI can always resolve the value\n  const list = React.useMemo(() => {\n    if (!async) return options;\n    const base = results ?? options;\n    return selected && !base.some((o) => o.value === selected.value) ? [...base, selected] : base;\n  }, [async, options, results, selected]);\n  const items = React.useMemo(() => grouped(list), [list]);\n  const isGrouped = items[0] !== undefined && \"items\" in items[0];\n\n  const shown = async ? (results ?? options).length : null;\n  const status = !async\n    ? null\n    : pending\n      ? \"Searching…\"\n      : error\n        ? error\n        : query\n          ? `${shown} ${shown === 1 ? \"match\" : \"matches\"} for “${query}”`\n          : `${shown} ${shown === 1 ? noun[0] : noun[1]}`;\n\n  const renderItem = (o: ComboboxOption) => (\n    <ComboboxItem key={o.value} value={o} disabled={o.disabled} description={o.description} code={o.code}>\n      {highlight(o.label, query)}\n    </ComboboxItem>\n  );\n\n  return (\n    <FieldPrimitive.Root\n      data-slot=\"combobox\"\n      data-kl-layout={layout}\n      data-kl-orientation={orientation}\n      name={name}\n      disabled={disabled}\n      invalid={invalid}\n      validate={validate}\n      validationMode={validationMode}\n      className={cn(\"kl-field\", layout === \"cell\" && \"flex-1 gap-0 self-stretch\", className)}\n    >\n      <ComboboxRoot<ComboboxOption>\n        items={items}\n        value={selected}\n        onValueChange={(o, details) => {\n          // Escape on a closed field: Base UI clears the value; keep it (see onInputValueChange)\n          if (details.reason === \"escape-key\") return details.cancel();\n          const option = o ?? null;\n          if (option) known.current.set(option.value, option);\n          if (value === undefined) setInner(option?.value ?? null);\n          onValueChange?.(option?.value ?? null, option, details);\n        }}\n        itemToStringLabel={(o) => o.label}\n        itemToStringValue={(o) => o.value}\n        isItemEqualToValue={(a, b) => a.value === b.value}\n        filter={async ? null : undefined}\n        disabled={disabled}\n        readOnly={readOnly}\n        required={required}\n        name={name}\n        autoHighlight\n        onOpenChange={(o) => {\n          if (o && async && results == null && !inflight.current) load(latest.current);\n        }}\n        onInputValueChange={(q, details) => {\n          // Escape on a closed field with a choice: keep the label in the input (the value change that follows\n          // is cancelled too) and let the key reach an enclosing overlay, since it changed nothing here\n          if (details.reason === \"escape-key\" && selected) {\n            details.cancel();\n            details.allowPropagation();\n            return;\n          }\n          // the input shows the chosen label when a choice is made; that is not a search\n          if (details.reason === \"item-press\" || (selected && q === selected.label)) {\n            latest.current = \"\";\n            setQuery(\"\");\n            return;\n          }\n          latest.current = q;\n          setQuery(q);\n          if (async) load(q);\n        }}\n      >\n        <FieldPrimitive.Label htmlFor={id} className={cn(\"kl-field-label\", layout === \"cell\" && \"kl-sr\")}>\n          {label}\n        </FieldPrimitive.Label>\n        <ComboboxInputGroup layout={layout}>\n          <span className=\"kl-slot kl-field-bang\" aria-hidden>\n            <span>\n              <span>!</span>\n            </span>\n          </span>\n          <ComboboxInput id={id} placeholder={placeholder} />\n          {clearable && selected && !disabled && !readOnly ? (\n            <ComboboxClear aria-label={`Clear ${typeof label === \"string\" ? label : noun[0]}`} />\n          ) : null}\n          <ComboboxTrigger aria-label={`Show ${noun[1]}`} />\n        </ComboboxInputGroup>\n        <FieldMessages description={description} error={errorMessage} invalid={invalid} layout={layout} />\n        <ComboboxPopup layout={layout} container={container} aria-busy={pending || undefined}>\n          {async ? (\n            <div\n              className={cn(\n                \"relative flex min-h-8 flex-none items-center justify-between gap-2 px-(--kl-inset)\",\n                \"border-b-(length:--kl-k1) border-b-kl-seam text-kl-ink-2\",\n                \"font-(family-name:--kl-font-mono) text-(length:--kl-text-code)/[1.2] font-medium\",\n              )}\n            >\n              <ComboboxStatus data-kl-error={error ? \"\" : undefined}>{status}</ComboboxStatus>\n              {error ? (\n                <button\n                  type=\"button\"\n                  className={cn(\n                    \"cursor-pointer bg-transparent py-1.5 text-kl-cobalt-text underline decoration-[1.5px] underline-offset-3\",\n                    \"font-(family-name:--kl-font) text-(length:--kl-text-label)/none font-bold\",\n                  )}\n                  onClick={() => load(query)}\n                >\n                  Retry\n                </button>\n              ) : null}\n              {pending ? <span className=\"kl-pending [inset-block-end:-1px] h-0.5\" aria-hidden /> : null}\n            </div>\n          ) : null}\n          <ComboboxEmpty>\n            {!pending && !error ? (\n              <>\n                <span\n                  className={cn(\n                    \"kl-count grid place-items-center self-stretch border-e-(length:--kl-k1) border-e-kl-seam\",\n                    \"text-(length:--kl-text-display)\",\n                  )}\n                >\n                  0\n                </span>\n                <span className=\"px-(--kl-inset) text-kl-ink-2\">\n                  {query ? `No ${noun[1]} match “${query}”.` : `No ${noun[1]} yet.`}\n                </span>\n              </>\n            ) : null}\n          </ComboboxEmpty>\n          <ComboboxList>\n            {isGrouped\n              ? (g: Group) => (\n                  <ComboboxGroup key={g.value} items={g.items}>\n                    {g.value ? <ComboboxGroupLabel>{g.value}</ComboboxGroupLabel> : null}\n                    <ComboboxCollection>{renderItem}</ComboboxCollection>\n                  </ComboboxGroup>\n                )\n              : renderItem}\n          </ComboboxList>\n        </ComboboxPopup>\n      </ComboboxRoot>\n    </FieldPrimitive.Root>\n  );\n}\n\nexport {\n  Combobox,\n  ComboboxRoot,\n  ComboboxInputGroup,\n  ComboboxInput,\n  ComboboxTrigger,\n  ComboboxClear,\n  ComboboxPopup,\n  ComboboxStatus,\n  ComboboxList,\n  ComboboxCollection,\n  ComboboxItem,\n  ComboboxGroup,\n  ComboboxGroupLabel,\n  ComboboxEmpty,\n  ComboboxChips,\n  ComboboxChip,\n  ComboboxChipRemove,\n};\n",
      "type": "registry:ui",
      "target": "components/keyline/ui/combobox.tsx"
    }
  ],
  "type": "registry:ui"
}