{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "addon-picker",
  "title": "Addon picker",
  "description": "A picker inside a text control's box, at its start or end, such as a phone number's country or an amount's currency: a button that shows the pick, and the Combobox's list with a search.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/combobox.json",
    "https://kinoui.com/r/input-group.json",
    "https://kinoui.com/r/filter-list.json",
    "https://kinoui.com/r/list-rows.json"
  ],
  "files": [
    {
      "path": "registry/lib/addon-picker.tsx",
      "content": "'use client'\n\nimport {\n  Combobox,\n  ComboboxContent,\n  ComboboxEmpty,\n  ComboboxInput,\n  ComboboxItem,\n  ComboboxItemText,\n  ComboboxLabel,\n  ComboboxList,\n  ComboboxTrigger,\n} from '@/registry/components/kino/combobox'\nimport { InputGroupAddon, InputGroupButton } from '@/registry/components/kino/input-group'\nimport { FilterListChevron } from '@/registry/lib/filter-list'\nimport { RowShortcut } from '@/registry/lib/list-rows'\nimport { matchRanges } from '@ui-sdk/core/text-match'\nimport { Field as FieldPrimitive, useFieldControl } from '@ui-sdk/react/field'\nimport { type ReactNode, type RefObject, useId, useMemo, useRef, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A picker that sits in a text control's box, at its start or end: a country\n * for a phone number, a currency for an amount. Its button shows the pick;\n * its list is the Combobox's, as wide as the box, with its search at the\n * top. The box is an Input group, or any built on `inputBoxClassName`.\n */\n\ninterface AddonPickerOption {\n  value: string\n  /** The name the list shows and the search matches, such as \"United Kingdom\". */\n  label: string\n  /** What the row shows after the name, such as a dial code; the search matches it too. */\n  detail?: string\n  /** What the row shows before the name, such as a flag. */\n  visual?: ReactNode\n  /** Other words the search matches, such as a country's code. */\n  keywords?: readonly string[]\n}\n\n/** Where `query` first matches in `text`, ignoring case and accents, as ui-sdk's lists match. */\nfunction matchStart(text: string, query: string) {\n  return matchRanges(text, query, 'contains')[0]?.start ?? -1\n}\n\n/**\n * How well `option` matches what was typed, which ranks the list: 2 when\n * its name or a keyword starts with it, so Enter after \"ger\" picks Germany,\n * not Algeria; 1 when one holds it, or its detail starts with it, so \"44\"\n * finds +44 and not +244; 0 when nothing does.\n */\nfunction optionScore(option: AddonPickerOption, query: string): number {\n  const words = query.trim()\n  if (!words) return 1\n  const starts = [option.label, ...(option.keywords ?? [])].map((text) =>\n    matchStart(text, words),\n  )\n  if (starts.includes(0)) return 2\n  if (starts.some((start) => start > 0)) return 1\n  // The detail from its start, past a sign such as + or $.\n  const typed = words.replace(/^\\W+/, '')\n  const detail = (option.detail ?? '').replace(/^\\W+/, '')\n  // A sign alone, such as +, is the start of every detail.\n  return typed === '' || matchStart(detail.slice(0, typed.length), typed) === 0 ? 1 : 0\n}\n\n/** The box the picker sits in (any built on the box every text control has), which its list opens under. */\nfunction fieldOf(trigger: HTMLElement | null) {\n  return trigger?.closest<HTMLElement>('.group\\\\/input') ?? trigger\n}\n\nfunction AddonPicker({\n  options,\n  value,\n  onValueChange,\n  label,\n  searchPlaceholder,\n  noMatch,\n  align = 'inline-start',\n  disabled,\n  readOnly,\n  returnFocus,\n  className,\n  children,\n}: {\n  options: readonly AddonPickerOption[]\n  value: string\n  /** Called with the pick and the event behind it. */\n  onValueChange: (value: string, event: Event | undefined) => void\n  /** What is picked, such as \"Country\": the button reads \"Country: United Kingdom\", and the list takes it as its name. */\n  label: string\n  searchPlaceholder: string\n  /** What the list says when nothing matches `query`. */\n  noMatch: (query: string) => ReactNode\n  align?: 'inline-start' | 'inline-end'\n  disabled?: boolean\n  readOnly?: boolean\n  /** Where focus goes once a pick closes the list, such as the field's input; Escape returns it to the button. */\n  returnFocus?: RefObject<HTMLElement | null>\n  className?: string\n  /** What the button shows: the pick, such as its flag. */\n  children: ReactNode\n}) {\n  const [query, setQuery] = useState('')\n  const picked = useRef(false)\n  const searchId = useId()\n  const [box, setBox] = useState<HTMLElement | null>(null)\n  // Read here, since the picker is a Field of its own inside the control's: a\n  // disabled Field disables the pick too.\n  const outer = useFieldControl()\n  const byValue = useMemo(\n    () => new Map(options.map((option) => [option.value, option])),\n    [options],\n  )\n  const items = useMemo(\n    () =>\n      options.map((option) => ({\n        value: option.value,\n        label: option.label,\n        keywords: [...(option.keywords ?? [])],\n      })),\n    [options],\n  )\n  const selected = byValue.get(value)\n  return (\n    <InputGroupAddon\n      align={align}\n      className={cn(align === 'inline-start' ? 'ps-1' : 'pe-1', className)}\n    >\n      {/* The control's Field names its input; the picker sits outside it. */}\n      <FieldPrimitive className='contents'>\n        <Combobox\n          items={items}\n          value={selected ? value : null}\n          onValueChange={(next, details) => {\n            if (next === null) return\n            picked.current = true\n            onValueChange(next, details.event)\n          }}\n          onOpenChange={(open) => {\n            // As the pick closes it, not once it has closed, so the next keys\n            // reach the field: while it is open, focus stays in its search.\n            if (open || !picked.current) return\n            picked.current = false\n            returnFocus?.current?.focus({ preventScroll: true })\n          }}\n          onQueryChange={setQuery}\n          filter={(item, typed) => {\n            const option = byValue.get(item.value)\n            return option ? optionScore(option, typed) : 0\n          }}\n          disabled={disabled || outer?.disabled === true}\n          readOnly={readOnly}\n          // A read-only pick has no list to offer.\n          open={readOnly ? false : undefined}\n        >\n          <ComboboxLabel className='sr-only'>{label}</ComboboxLabel>\n          <ComboboxTrigger\n            ref={(trigger: HTMLButtonElement | null) => setBox(fieldOf(trigger))}\n            data-addon-picker-trigger=''\n            // The detail is in the name too, since the button may show it: speech users say what they see.\n            aria-label={\n              selected\n                ? `${label}: ${selected.label}${selected.detail ? `, ${selected.detail}` : ''}`\n                : label\n            }\n            render={<InputGroupButton className='text-foreground ps-1.5 pe-1' />}\n          >\n            {children}\n            {/* In the button's end slot, which stays still while the pick changes. */}\n            <span\n              data-addon-picker-chevron=''\n              data-icon='inline-end'\n              className='text-muted-foreground flex'\n            >\n              <FilterListChevron />\n            </span>\n          </ComboboxTrigger>\n          <ComboboxContent aria-label={label} anchor={box}>\n            {/* Named by what it shows, not by the picker's label. */}\n            <ComboboxInput\n              id={searchId}\n              placeholder={searchPlaceholder}\n              aria-label={searchPlaceholder}\n              aria-labelledby={searchId}\n            />\n            <ComboboxEmpty>{noMatch(query)}</ComboboxEmpty>\n            <ComboboxList aria-label={label}>\n              {(state) =>\n                state.items.map((item) => {\n                  const option =\n                    typeof item === 'object' && 'value' in item\n                      ? byValue.get(String(item.value))\n                      : undefined\n                  if (!option) return null\n                  return (\n                    <ComboboxItem\n                      key={option.value}\n                      value={option.value}\n                      label={option.label}\n                    >\n                      {option.visual}\n                      <ComboboxItemText className='flex-1 whitespace-normal wrap-break-word'>\n                        {option.label}\n                      </ComboboxItemText>\n                      {option.detail ? <RowShortcut>{option.detail}</RowShortcut> : null}\n                    </ComboboxItem>\n                  )\n                })\n              }\n            </ComboboxList>\n          </ComboboxContent>\n        </Combobox>\n      </FieldPrimitive>\n    </InputGroupAddon>\n  )\n}\n\nexport { AddonPicker, optionScore }\nexport type { AddonPickerOption }\n",
      "type": "registry:lib",
      "target": "@lib/addon-picker.tsx"
    }
  ],
  "type": "registry:lib"
}