# Combobox

> A text field that filters a list as you type, for picking one option from many or several as removable tags.

Docs: https://plumbago.ochotzas.com/components/combobox

## Installation

```sh
npx plumbago add combobox
```

This copies `components/ui/combobox.tsx` into your project, along with `cn`, `morph`, `scroll-fade`, and installs `@base-ui/react`.

## Usage

```tsx
import { Combobox, ComboboxContent, ComboboxField, ComboboxItem } from "@/components/ui/combobox"

const dishes = [
  { value: "ramen", label: "Tonkotsu ramen" },
  { value: "gyoza", label: "Pork gyoza" },
]

<Combobox items={dishes}>
  <ComboboxField placeholder="Search dishes" aria-label="Dish" />
  <ComboboxContent empty={(query) => `No dish called “${query}”.`}>
    {(dish) => <ComboboxItem value={dish} />}
  </ComboboxContent>
</Combobox>
```

## Examples

### Preview

```tsx
import { Avatar } from "@/components/ui/avatar"
import { Combobox, ComboboxContent, ComboboxField, ComboboxItem } from "@/components/ui/combobox"

const photos: Record<string, string> = {
  ana: "/people/ana-lima.webp",
  marta: "/people/marta-rossi.webp",
  jonas: "/people/jonas-weber.webp",
}

const chefs = [
  { value: "ana", label: "Ána Lima", subtitle: "Head chef" },
  { value: "marta", label: "Marta Rossi", subtitle: "Sous chef" },
  { value: "jonas", label: "Jonas Weber", subtitle: "Pastry chef" },
  { value: "tomas", label: "Tomás Silva", subtitle: "Grill" },
  { value: "priya", label: "Priya Nair", subtitle: "Sauce station" },
  { value: "li", label: "Li Wei", subtitle: "Prep cook" },
  { value: "omar", label: "Omar Haddad", subtitle: "Line cook" },
]

export default function ComboboxDemo() {
  return (
    <div className="w-full max-w-80">
      <Combobox items={chefs} defaultValue={chefs.find((chef) => chef.value === "marta")}>
        <ComboboxField
          placeholder="Assign a chef"
          aria-label="Chef"
          leading={(chef) => <Avatar name={chef.label} src={photos[chef.value]} tone="category" size="sm" />}
        />
        <ComboboxContent empty={(query) => `No one called “${query}”.`}>
          {(chef) => <ComboboxItem value={chef} avatar={<Avatar name={chef.label} src={photos[chef.value]} tone="category" size="sm" />} />}
        </ComboboxContent>
      </Combobox>
    </div>
  )
}
```

### Plain list

```tsx
import { Combobox, ComboboxContent, ComboboxField, ComboboxItem } from "@/components/ui/combobox"

const dishes = [
  { value: "ramen", label: "Tonkotsu ramen" },
  { value: "gyoza", label: "Pork gyoza" },
  { value: "bao", label: "Braised pork bao" },
  { value: "tempura", label: "Vegetable tempura" },
  { value: "katsu", label: "Chicken katsu curry" },
  { value: "udon", label: "Beef udon" },
  { value: "edamame", label: "Salted edamame" },
  { value: "mochi", label: "Matcha mochi" },
  { value: "miso", label: "Miso soup" },
  { value: "tartare", label: "Tuna tartare" },
]

export default function ComboboxPlainList() {
  return (
    <div className="w-full max-w-80">
      <Combobox items={dishes}>
        <ComboboxField placeholder="Search dishes" aria-label="Dish" />
        <ComboboxContent empty={(query) => `No dish called “${query}”.`}>{(dish) => <ComboboxItem value={dish} />}</ComboboxContent>
      </Combobox>
    </div>
  )
}
```

### Multiple

```tsx
import { Combobox, ComboboxContent, ComboboxField, ComboboxItem } from "@/components/ui/combobox"

const allergens = [
  { value: "sesame", label: "Sesame" },
  { value: "gluten", label: "Gluten" },
  { value: "dairy", label: "Dairy" },
  { value: "nuts", label: "Nuts" },
  { value: "eggs", label: "Eggs" },
  { value: "shellfish", label: "Shellfish" },
  { value: "soy", label: "Soy" },
  { value: "fish", label: "Fish" },
  { value: "celery", label: "Celery" },
  { value: "mustard", label: "Mustard" },
]

export default function ComboboxMultiple() {
  return (
    <div className="w-full max-w-sm">
      <Combobox multiple items={allergens} defaultValue={allergens.filter((allergen) => ["sesame", "dairy"].includes(allergen.value))}>
        <ComboboxField placeholder="Add allergens" aria-label="Allergens" />
        <ComboboxContent empty={(query) => `No allergen called “${query}”.`}>{(allergen) => <ComboboxItem value={allergen} />}</ComboboxContent>
      </Combobox>
    </div>
  )
}
```

### In an island

```tsx
import { Avatar } from "@/components/ui/avatar"
import { Combobox, ComboboxContent, ComboboxField, ComboboxItem } from "@/components/ui/combobox"
import { Island, IslandLabel } from "@/components/ui/island"

const servers = [
  { value: "noor", label: "Noor Haddad", subtitle: "Floor lead" },
  { value: "felix", label: "Felix Brandt", subtitle: "Bar" },
  { value: "sofia", label: "Sofia Marques", subtitle: "Terrace" },
  { value: "kai", label: "Kai Tanaka", subtitle: "Host" },
]

export default function ComboboxInAnIsland() {
  return (
    <Island className="w-full max-w-80">
      <IslandLabel>Table 12</IslandLabel>
      <Combobox items={servers}>
        <ComboboxField placeholder="Assign a server" aria-label="Server" leading={(server) => <Avatar name={server.label} tone="category" size="sm" />} />
        <ComboboxContent empty={(query) => `No one called “${query}”.`}>
          {(server) => <ComboboxItem value={server} avatar={<Avatar name={server.label} tone="category" size="sm" />} />}
        </ComboboxContent>
      </Combobox>
    </Island>
  )
}
```

### With a label

```tsx
import { Combobox, ComboboxContent, ComboboxField, ComboboxItem } from "@/components/ui/combobox"
import { FieldDescription, FieldLabel, FieldRoot } from "@/components/ui/field"

const allergens = [
  { value: "sesame", label: "Sesame" },
  { value: "gluten", label: "Gluten" },
  { value: "dairy", label: "Dairy" },
  { value: "nuts", label: "Nuts" },
  { value: "eggs", label: "Eggs" },
  { value: "shellfish", label: "Shellfish" },
  { value: "soy", label: "Soy" },
]

export default function ComboboxWithALabel() {
  return (
    <FieldRoot className="max-w-80">
      <FieldLabel>Contains</FieldLabel>
      <Combobox multiple items={allergens}>
        <ComboboxField placeholder="Add allergens" />
        <ComboboxContent empty={(query) => `No allergen called “${query}”.`}>{(allergen) => <ComboboxItem value={allergen} />}</ComboboxContent>
      </Combobox>
      <FieldDescription>Shown to guests on the menu.</FieldDescription>
    </FieldRoot>
  )
}
```

## Built on Base UI

Combobox wraps these Base UI parts and keeps their props:

- [Combobox](https://base-ui.com/react/components/combobox)

## Source

```tsx
import { Combobox as BaseCombobox } from "@base-ui/react/combobox"
import { cn } from "@/lib/cn"
import { morphColor, morphPanel, morphUnfold } from "@/lib/morph"
import { ScrollFade } from "@/components/ui/scroll-fade"
import { type ComponentProps, createContext, Fragment, type ReactNode, useContext, useEffect, useId, useRef, useState } from "react"

export type ComboboxOption = {
  value: string
  label: string
  subtitle?: string
}

type ComboboxContextValue = {
  multiple: boolean
  query: string
}

const ComboboxContext = createContext<ComboboxContextValue>({ multiple: false, query: "" })

const foldedCharacter = (character: string) => character.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase()

function fold(text: string) {
  let folded = ""
  const starts: number[] = []
  let offset = 0
  for (const character of text) {
    const replacement = foldedCharacter(character)
    for (let index = 0; index < replacement.length; index++) starts.push(offset)
    folded += replacement
    offset += character.length
  }
  starts.push(offset)
  return { folded, starts }
}

function matchRange(text: string, query: string) {
  const needle = fold(query.trim()).folded
  if (needle === "") return null
  const { folded, starts } = fold(text)
  const found = folded.indexOf(needle)
  if (found === -1) return null
  return { start: starts[found] ?? 0, end: starts[found + needle.length] ?? text.length }
}

function matchesOption(option: ComboboxOption, query: string) {
  if (query.trim() === "") return true
  return matchRange(option.label, query) !== null || (option.subtitle !== undefined && matchRange(option.subtitle, query) !== null)
}

export function ComboboxHighlight({ text, query }: { text: string; query: string }) {
  const range = matchRange(text, query)
  if (!range) return text
  return (
    <>
      {text.slice(0, range.start)}
      <span className="font-semibold">{text.slice(range.start, range.end)}</span>
      {text.slice(range.end)}
    </>
  )
}

export type ComboboxProps<Item extends ComboboxOption, Multiple extends boolean | undefined = false> = Omit<
  BaseCombobox.Root.Props<Item, Multiple>,
  "filter" | "itemToStringLabel"
>

export function Combobox<Item extends ComboboxOption, Multiple extends boolean | undefined = false>({
  multiple,
  onValueChange,
  onInputValueChange,
  onOpenChange,
  ...props
}: ComboboxProps<Item, Multiple>) {
  const [query, setQuery] = useState("")
  const [announcement, setAnnouncement] = useState("")
  const chosen = useRef<readonly Item[]>(toList(props.value ?? props.defaultValue))
  const [inputValue, setInputValue] = useState(multiple ? "" : (chosen.current[0]?.label ?? ""))
  const [controlledValue, setControlledValue] = useState(props.value)

  if (props.value !== controlledValue) {
    setControlledValue(props.value)
    chosen.current = toList(props.value)
    if (!multiple) setInputValue(chosen.current[0]?.label ?? "")
  }

  return (
    <ComboboxContext.Provider value={{ multiple: Boolean(multiple), query }}>
      <BaseCombobox.Root<Item, Multiple>
        multiple={multiple}
        inputValue={inputValue}
        filter={matchesOption}
        itemToStringLabel={(item) => item.label}
        isItemEqualToValue={(item, value) => item.value === value.value}
        onValueChange={(value, details) => {
          const previous = chosen.current
          const next = toList(value)
          chosen.current = next
          if (multiple) {
            const added = next.find((item) => !previous.some((existing) => existing.value === item.value))
            const removed = previous.find((item) => !next.some((existing) => existing.value === item.value))
            if (added) setAnnouncement(`${added.label} added`)
            else if (removed) setAnnouncement(`${removed.label} removed`)
          }
          onValueChange?.(value, details)
        }}
        onInputValueChange={(value, details) => {
          setQuery(details.reason === "input-change" ? value : "")
          setInputValue(value)
          onInputValueChange?.(value, details)
        }}
        onOpenChange={(open, details) => {
          if (!open) {
            setQuery("")
            if (!multiple) setInputValue(chosen.current[0]?.label ?? "")
          }
          onOpenChange?.(open, details)
        }}
        {...props}
      />
      {multiple && (
        <div data-slot="combobox-status" role="status" aria-live="polite" className="sr-only">
          {announcement}
        </div>
      )}
    </ComboboxContext.Provider>
  )
}

function toList<Item>(value: Item | readonly Item[] | null | undefined): readonly Item[] {
  if (value === null || value === undefined) return []
  return Array.isArray(value) ? value : [value as Item]
}

export type ComboboxFieldProps<Item extends ComboboxOption> = Omit<ComponentProps<typeof BaseCombobox.Input>, "className"> & {
  leading?: (item: Item) => ReactNode
  className?: string
}

const fieldStyles = cn(
  "relative flex w-full cursor-text items-center rounded-md bg-fill-field text-body text-ink",
  "transition-shadow duration-fast ease-out focus-within:ring-2 focus-within:ring-accent data-popup-open:ring-2 data-popup-open:ring-accent",
  "data-invalid:ring-2 data-invalid:ring-danger data-disabled:cursor-default data-disabled:opacity-40",
)

const inputStyles = "min-w-0 flex-1 border-0 bg-transparent p-0 text-body text-ink outline-none placeholder:text-ink-3 disabled:cursor-default"

export function ComboboxField<Item extends ComboboxOption>({ leading, className, ...props }: ComboboxFieldProps<Item>) {
  const { multiple } = useContext(ComboboxContext)
  return (
    <BaseCombobox.InputGroup data-slot="combobox-field" className={cn(fieldStyles, multiple ? "min-h-11 py-2 pr-11 pl-2" : "h-11", className)}>
      {multiple ? <ChipsInput {...props} /> : <SingleInput leading={leading} {...props} />}
      <BaseCombobox.Trigger
        data-slot="combobox-trigger"
        aria-label="Show options"
        tabIndex={-1}
        className="group/trigger absolute inset-y-0 right-0 grid w-11 cursor-pointer place-items-center text-ink-3 outline-none after:absolute after:inset-0 after:content-[''] data-disabled:cursor-default"
      >
        <ChevronDown />
      </BaseCombobox.Trigger>
    </BaseCombobox.InputGroup>
  )
}

function SingleInput<Item extends ComboboxOption>({ leading, ...props }: Omit<ComboboxFieldProps<Item>, "className">) {
  const { query } = useContext(ComboboxContext)
  return (
    <>
      {leading && query === "" && (
        <BaseCombobox.Value>{(item: Item | null) => (item ? <span className="-mr-1.5 flex shrink-0 pl-3">{leading(item)}</span> : null)}</BaseCombobox.Value>
      )}
      <BaseCombobox.Input data-slot="combobox-input" className={cn(inputStyles, "h-full truncate pr-11 pl-4")} {...props} />
    </>
  )
}

const chipStyles =
  "inline-flex h-7 max-w-full cursor-default items-center gap-1 rounded-full bg-bg in-[.on-surface]:bg-surface pr-1 pl-2.5 text-[13px] leading-none font-semibold tracking-[0.01em] whitespace-nowrap text-ink outline-none focus-visible:ring-2 focus-visible:ring-accent data-highlighted:ring-2 data-highlighted:ring-accent"

const leavingDuration = 220

function ChipsInput({ placeholder, ...props }: Omit<ComboboxFieldProps<ComboboxOption>, "className" | "leading">) {
  const { query } = useContext(ComboboxContext)
  return (
    <BaseCombobox.Value>
      {(selected: ComboboxOption[]) => (
        <BaseCombobox.Chips data-slot="combobox-chips" className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
          <ChipList selected={selected} />
          <BaseCombobox.Input
            data-slot="combobox-input"
            placeholder={selected.length > 0 ? undefined : placeholder}
            aria-description={
              selected.length > 0 ? `${selected.length} selected. From the start of the input, press Left Arrow to focus the selected items` : undefined
            }
            className={cn(inputStyles, "h-7 w-0 flex-1", selected.length > 0 && query === "" ? "min-w-px px-0" : "min-w-20 px-1")}
            {...props}
          />
        </BaseCombobox.Chips>
      )}
    </BaseCombobox.Value>
  )
}

type LeavingChip = { item: ComboboxOption; index: number }

function ChipList({ selected }: { selected: ComboboxOption[] }) {
  const [previous, setPrevious] = useState(selected)
  const [leaving, setLeaving] = useState<LeavingChip[]>([])

  const valuesOf = (items: ComboboxOption[]) => items.map((item) => item.value).join("\n")
  if (valuesOf(previous) !== valuesOf(selected)) {
    const removed = previous.flatMap((item, index) => (selected.some((kept) => kept.value === item.value) ? [] : [{ item, index }]))
    setPrevious(selected)
    if (removed.length > 0) setLeaving((current) => [...current.filter((chip) => !selected.some((kept) => kept.value === chip.item.value)), ...removed])
  }

  useEffect(() => {
    if (leaving.length === 0) return
    const timer = setTimeout(() => setLeaving([]), leavingDuration)
    return () => clearTimeout(timer)
  }, [leaving])

  const rendered: ReactNode[] = selected.map((item) => <ComboboxChip key={item.value} label={item.label} />)
  for (const chip of [...leaving].sort((first, second) => first.index - second.index)) {
    rendered.splice(Math.min(chip.index, rendered.length), 0, <LeavingComboboxChip key={`leaving-${chip.item.value}`} label={chip.item.label} />)
  }
  return rendered
}

function LeavingComboboxChip({ label }: { label: string }) {
  return (
    <span
      aria-hidden="true"
      data-slot="combobox-chip-leaving"
      className={cn(
        chipStyles,
        "pointer-events-none scale-90 opacity-0 transition-[opacity,scale,filter] duration-base ease-in motion-safe:blur-[4px] starting:scale-100 starting:opacity-100 starting:blur-none",
      )}
    >
      <span className="truncate">{label}</span>
      <span className="grid size-5 shrink-0 place-items-center">
        <RemoveIcon />
      </span>
    </span>
  )
}

function ComboboxChip({ label }: { label: string }) {
  return (
    <BaseCombobox.Chip
      data-slot="combobox-chip"
      aria-label={label}
      aria-description="Press Backspace or Delete to remove"
      className={cn(
        chipStyles,
        "transition-[opacity,scale,filter] duration-spring ease-spring starting:scale-90 starting:opacity-0 motion-safe:starting:blur-[4px]",
      )}
    >
      <span className="truncate">{label}</span>
      <BaseCombobox.ChipRemove
        data-slot="combobox-chip-remove"
        aria-label={`Remove ${label}`}
        className="group/remove relative grid size-5 shrink-0 cursor-pointer place-items-center rounded-full border-0 bg-transparent p-0 text-ink after:absolute after:-inset-3 after:content-['']"
      >
        <RemoveIcon />
      </BaseCombobox.ChipRemove>
    </BaseCombobox.Chip>
  )
}

function RemoveIcon() {
  const maskId = useId()
  return (
    <svg
      viewBox="0 0 16 16"
      aria-hidden="true"
      className="size-4 opacity-55 transition-opacity duration-fast ease-out group-hover/remove:opacity-85 group-active/remove:opacity-100"
    >
      <mask id={maskId}>
        <rect width="16" height="16" fill="white" />
        <path d="m5.5 5.5 5 5m0-5-5 5" stroke="black" strokeWidth="1.6" strokeLinecap="round" />
      </mask>
      <circle cx="8" cy="8" r="8" fill="currentColor" mask={`url(#${maskId})`} />
    </svg>
  )
}

export type ComboboxContentProps<Item extends ComboboxOption> = Omit<ComponentProps<typeof BaseCombobox.Popup>, "className" | "children"> & {
  children: (item: Item, index: number) => ReactNode
  empty?: (query: string) => ReactNode
  side?: BaseCombobox.Positioner.Props["side"]
  align?: BaseCombobox.Positioner.Props["align"]
  sideOffset?: number
  className?: string
}

export function ComboboxContent<Item extends ComboboxOption>({
  children,
  empty = (query) => `No matches for “${query}”.`,
  side = "bottom",
  align = "start",
  sideOffset = 6,
  className,
  ...props
}: ComboboxContentProps<Item>) {
  const { query } = useContext(ComboboxContext)
  return (
    <BaseCombobox.Portal>
      <BaseCombobox.Positioner
        ref={morphColor}
        data-slot="combobox-positioner"
        side={side}
        align={align}
        sideOffset={sideOffset}
        collisionPadding={8}
        className={cn(morphUnfold, "z-50 outline-none")}
      >
        <BaseCombobox.Popup
          data-slot="combobox-content"
          className={cn(
            "flex max-h-[min(var(--available-height),15rem)] w-(--anchor-width) max-w-(--available-width) flex-col overflow-hidden rounded-md text-ink",
            morphPanel,
            className,
          )}
          {...props}
        >
          <BaseCombobox.Empty data-slot="combobox-empty" className="px-4 py-3 text-footnote text-ink-2 empty:hidden">
            {empty(query)}
          </BaseCombobox.Empty>
          <ScrollFade className="max-h-[inherit] data-has-overflow-y:[&>[data-slot=scroll-fade-viewport]]:scroll-py-1.5" viewportClassName="max-h-[inherit]">
            <BaseCombobox.List data-slot="combobox-list" className="flex flex-col p-1.5 outline-none empty:hidden">
              {(item: Item, index: number) => <Fragment key={item.value}>{children(item, index)}</Fragment>}
            </BaseCombobox.List>
          </ScrollFade>
        </BaseCombobox.Popup>
      </BaseCombobox.Positioner>
    </BaseCombobox.Portal>
  )
}

export type ComboboxItemProps<Item extends ComboboxOption> = Omit<ComponentProps<typeof BaseCombobox.Item>, "className" | "value" | "children"> & {
  value: Item
  avatar?: ReactNode
  className?: string
}

export function ComboboxItem<Item extends ComboboxOption>({ value, avatar, className, ...props }: ComboboxItemProps<Item>) {
  const { query } = useContext(ComboboxContext)
  return (
    <BaseCombobox.Item
      data-slot="combobox-item"
      value={value}
      className={cn(
        "flex shrink-0 cursor-pointer items-center gap-2.5 rounded-sm px-2.5 text-body text-ink outline-none select-none",
        value.subtitle ? "h-11" : "h-9",
        "transition-colors duration-fast ease-out data-highlighted:bg-press data-disabled:cursor-default data-disabled:text-ink-3",
        className,
      )}
      {...props}
    >
      {avatar && <span className="flex shrink-0">{avatar}</span>}
      <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
        <span className="shrink-0 truncate">
          <ComboboxHighlight text={value.label} query={query} />
        </span>
        {value.subtitle && (
          <span className="min-w-0 truncate text-footnote text-ink-2">
            <ComboboxHighlight text={value.subtitle} query={query} />
          </span>
        )}
      </span>
      <BaseCombobox.ItemIndicator data-slot="combobox-item-indicator" className="flex shrink-0 text-ink">
        <Check />
      </BaseCombobox.ItemIndicator>
    </BaseCombobox.Item>
  )
}

function ChevronDown() {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden="true"
      className="size-5 fill-none stroke-current transition-transform duration-spring ease-spring group-data-popup-open/trigger:rotate-180"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M6 9.5l6 6 6-6" />
    </svg>
  )
}

function Check() {
  return (
    <svg viewBox="0 0 12 12" aria-hidden="true" className="size-3.5 fill-none stroke-current" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2.5 6.3l2.3 2.2L9.5 3.5" />
    </svg>
  )
}
```
