Async Search Combobox
Combobox that asks a remote source as the user types, with debounced requests and a popup that shows skeleton rows, results, an empty state or an error with Retry. Use when the option set is too large to ship.
How it differs. Every remote state lives inside the popup: minimum characters hint, skeleton rows, capped result count, empty and error panels with one action each, and stale responses dropped.
Install
pnpm dlx shadcn@latest add @hazine/combobox-async-searchAdds 1 file, 4 shadcn primitives (button, command, popover, skeleton), 1 Hazine item (@hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/combobox-async-search.tsx, 449 lines
"use client"
import * as React from "react"
import { ChevronsUpDown, CircleAlert, SearchX } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
Command,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Skeleton } from "@/components/ui/skeleton"
import { useControllableState } from "@/hooks/use-controllable-state"
export interface ComboboxAsyncSearchOption {
value: string
label: string
/** Second line under the label, for example an email address. */
description?: string
/** Short trailing fact, for example "3 open". */
meta?: string
disabled?: boolean
}
export interface ComboboxAsyncSearchResult {
options: ComboboxAsyncSearchOption[]
/** Matches on the server when the response is capped. Defaults to the number of options. */
total?: number
}
export interface ComboboxAsyncSearchLabels {
/** Shown while the query is shorter than `minQueryLength`. */
hint: (remaining: number) => string
/** Announced when a request starts. */
loading: string
/** Footer under the results, also announced. */
results: (shown: number, total: number) => string
empty: (query: string) => string
emptyHint: string
clear: string
error: string
errorHint: string
retry: string
/** Heading over the chosen option, and the spoken mark on its row. */
selected: string
}
const integer = new Intl.NumberFormat("en-US")
const DEFAULT_LABELS: ComboboxAsyncSearchLabels = {
hint: (remaining) =>
`Type ${remaining} more ${remaining === 1 ? "character" : "characters"} to search.`,
loading: "Searching",
results: (shown, total) =>
shown < total
? `Showing ${integer.format(shown)} of ${integer.format(total)} results. Keep typing to narrow.`
: `${integer.format(total)} ${total === 1 ? "result" : "results"}`,
empty: (query) => `No results for "${query}".`,
emptyHint: "Check the spelling or try fewer characters.",
clear: "Clear search",
error: "Results could not be loaded.",
errorHint: "Check your connection, then retry.",
retry: "Retry",
selected: "Current selection",
}
const SKELETON_ROWS = [
["w-28", "w-40"],
["w-36", "w-44"],
["w-24", "w-36"],
["w-32", "w-40"],
] as const
// The active row of the host command list is a solid muted fill, where muted
// text falls under 4.5:1, so secondary text turns to foreground there.
const secondaryClass =
"text-xs text-muted-foreground group-data-selected/command-item:text-foreground"
interface SettledRequest {
key: string
options: ComboboxAsyncSearchOption[]
total: number
failed: boolean
}
function LoadingRows() {
return (
<div data-slot="combobox-async-search-loading" aria-hidden="true" className="p-1">
{SKELETON_ROWS.map(([title, detail]) => (
<div key={title} className="flex items-center gap-2 px-2 py-1.5">
<div className="flex min-w-0 flex-1 flex-col gap-1.5 py-0.5">
<Skeleton className={cn("h-3.5 motion-reduce:animate-none", title)} />
<Skeleton className={cn("h-3 motion-reduce:animate-none", detail)} />
</div>
<Skeleton className="h-3 w-10 motion-reduce:animate-none" />
</div>
))}
</div>
)
}
// The host command root cancels Enter for its list, which would also cancel
// the press on a button inside it, so the key stops at the button.
function keepEnter(event: React.KeyboardEvent) {
if (event.key === "Enter") event.stopPropagation()
}
interface NoticeProps {
icon: React.ReactNode
lead: string
detail: string
tone?: "neutral" | "destructive"
action: string
onAction: () => void
}
function Notice({ icon, lead, detail, tone = "neutral", action, onAction }: NoticeProps) {
return (
<div className="flex flex-col items-start gap-3 p-3">
<div className="flex gap-2">
{icon}
<p className="min-w-0 text-sm wrap-anywhere text-muted-foreground">
<span
className={cn(
"font-medium",
tone === "destructive" ? "text-destructive" : "text-foreground"
)}
>
{lead}
</span>{" "}
{detail}
</p>
</div>
<Button variant="outline" size="sm" onClick={onAction} onKeyDown={keepEnter}>
{action}
</Button>
</div>
)
}
/** Remaining props are spread to the trigger button, which carries the field semantics. */
export interface ComboboxAsyncSearchProps
extends Omit<
React.ComponentProps<typeof Button>,
"value" | "defaultValue" | "name" | "children" | "asChild" | "type"
> {
/** Runs the search. Reject to show the error row. Abort on `signal` to cancel a stale request. */
loadOptions: (query: string, signal: AbortSignal) => Promise<ComboboxAsyncSearchResult>
/** The chosen option. The whole option is kept, since its label cannot be looked up without a request. */
value?: ComboboxAsyncSearchOption | null
defaultValue?: ComboboxAsyncSearchOption | null
onValueChange?: (value: ComboboxAsyncSearchOption | null) => void
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
query?: string
defaultQuery?: string
onQueryChange?: (query: string) => void
/** Characters needed before a request is sent. */
minQueryLength?: number
/** Quiet time after the last keystroke before a request is sent. */
debounceMs?: number
/** Trigger text while nothing is chosen. */
placeholder?: string
/** Placeholder and accessible name of the search field. */
searchPlaceholder?: string
labels?: Partial<ComboboxAsyncSearchLabels>
/** Adds a hidden input so the chosen value is submitted with a form. */
name?: string
}
export function ComboboxAsyncSearch({
loadOptions,
value: valueProp,
defaultValue = null,
onValueChange,
open: openProp,
defaultOpen = false,
onOpenChange,
query: queryProp,
defaultQuery = "",
onQueryChange,
minQueryLength = 2,
debounceMs = 250,
placeholder = "Select an option",
searchPlaceholder = "Search",
labels: labelsProp,
name,
className,
onKeyDown,
...props
}: ComboboxAsyncSearchProps) {
const labels = { ...DEFAULT_LABELS, ...labelsProp }
const [value, setValue] = useControllableState({
value: valueProp,
defaultValue,
onChange: onValueChange,
})
const [open, setOpen] = useControllableState({
value: openProp,
defaultValue: defaultOpen,
onChange: onOpenChange,
})
const [query, setQuery] = useControllableState({
value: queryProp,
defaultValue: defaultQuery,
onChange: onQueryChange,
})
const [settled, setSettled] = React.useState<SettledRequest | null>(null)
const [attempt, setAttempt] = React.useState(0)
const inputRef = React.useRef<HTMLInputElement>(null)
const hintId = React.useId()
const loadRef = React.useRef(loadOptions)
React.useEffect(() => {
loadRef.current = loadOptions
})
const term = query.trim()
const remaining = Math.max(0, minQueryLength - term.length)
const key = `${attempt}:${term}`
const current = settled?.key === key ? settled : null
const status =
remaining > 0
? "idle"
: current === null
? "loading"
: current.failed
? "error"
: current.options.length === 0
? "empty"
: "success"
const waiting = open && status === "loading"
// The request belongs to this effect run. A newer keystroke, a retry or
// closing the popup cleans the run up, which cancels the debounce, aborts
// the request and drops a response that still arrives.
React.useEffect(() => {
if (!waiting) return
const controller = new AbortController()
const settle = (result: ComboboxAsyncSearchResult | null) => {
if (controller.signal.aborted) return
const options = result?.options ?? []
setSettled({
key,
options,
total: Math.max(result?.total ?? 0, options.length),
failed: result === null,
})
}
const timer = window.setTimeout(() => {
Promise.resolve()
.then(() => loadRef.current(term, controller.signal))
.then(settle, () => settle(null))
}, debounceMs)
return () => {
window.clearTimeout(timer)
controller.abort()
}
}, [waiting, key, term, debounceMs])
const rows =
current !== null && status === "success"
? current.options
: status === "idle" && value
? [value]
: []
const total = current?.total ?? 0
const announcement = !open
? ""
: status === "loading"
? labels.loading
: status === "success"
? labels.results(rows.length, total)
: status === "empty"
? labels.empty(term)
: ""
function choose(option: ComboboxAsyncSearchOption) {
setValue(option)
setQuery("")
setOpen(false)
}
// The panel that holds the button is removed by the action, so focus goes
// back to the search field first.
function clearSearch() {
inputRef.current?.focus()
setQuery("")
}
function retry() {
inputRef.current?.focus()
setAttempt((count) => count + 1)
}
return (
<div
data-slot="combobox-async-search"
data-state={open ? "open" : "closed"}
className={cn("grid min-w-0", className)}
>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
className="w-full justify-between font-normal"
onKeyDown={(event) => {
onKeyDown?.(event)
if (event.defaultPrevented || event.key !== "ArrowDown") return
event.preventDefault()
setOpen(true)
}}
{...props}
>
<span
data-slot="combobox-async-search-value"
title={value?.label}
className={cn("truncate", !value && "text-muted-foreground")}
>
{value?.label ?? placeholder}
</span>
<ChevronsUpDown aria-hidden="true" className="text-muted-foreground" />
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
aria-label={searchPlaceholder}
className="w-(--radix-popover-trigger-width) max-w-(--radix-popover-content-available-width) min-w-64 gap-0 p-0"
>
<Command shouldFilter={false} label={searchPlaceholder}>
<CommandInput
ref={inputRef}
value={query}
onValueChange={setQuery}
placeholder={searchPlaceholder}
aria-describedby={status === "idle" ? hintId : undefined}
onKeyDown={(event) => {
if (event.key !== "Enter" || status !== "error") return
if (event.nativeEvent.isComposing) return
event.preventDefault()
retry()
}}
/>
<CommandList aria-busy={status === "loading"}>
{status === "loading" ? <LoadingRows /> : null}
{rows.length > 0 ? (
<CommandGroup
heading={status === "idle" ? labels.selected : undefined}
>
{rows.map((option) => (
<CommandItem
key={option.value}
value={option.value}
disabled={option.disabled}
data-checked={option.value === value?.value}
onSelect={() => choose(option)}
>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate font-medium" title={option.label}>
{option.label}
</span>
{option.description ? (
<span
className={cn("truncate", secondaryClass)}
title={option.description}
>
{option.description}
</span>
) : null}
</span>
{option.meta ? (
<span className={cn("shrink-0 tabular-nums", secondaryClass)}>
{option.meta}
</span>
) : null}
{option.value === value?.value && status !== "idle" ? (
<span className="sr-only">{labels.selected}</span>
) : null}
</CommandItem>
))}
</CommandGroup>
) : null}
</CommandList>
{status === "idle" ? (
<p
id={hintId}
data-slot="combobox-async-search-hint"
className="px-3 py-2.5 text-sm text-muted-foreground"
>
{labels.hint(remaining)}
</p>
) : null}
{status === "success" ? (
<p
data-slot="combobox-async-search-count"
className="-mx-1 mt-1 border-t border-border px-4 pt-2 pb-1 text-xs text-muted-foreground tabular-nums"
>
{labels.results(rows.length, total)}
</p>
) : null}
{status === "empty" ? (
<Notice
icon={
<SearchX
aria-hidden="true"
className="mt-0.5 size-4 shrink-0 text-muted-foreground"
/>
}
lead={labels.empty(term)}
detail={labels.emptyHint}
action={labels.clear}
onAction={clearSearch}
/>
) : null}
<div role="alert" data-slot="combobox-async-search-error">
{status === "error" ? (
<Notice
tone="destructive"
icon={
<CircleAlert
aria-hidden="true"
className="mt-0.5 size-4 shrink-0 text-destructive"
/>
}
lead={labels.error}
detail={labels.errorHint}
action={labels.retry}
onAction={retry}
/>
) : null}
</div>
</Command>
</PopoverContent>
</Popover>
<p role="status" data-slot="combobox-async-search-status" className="sr-only">
{announcement}
</p>
{name ? (
<input type="hidden" name={name} value={value?.value ?? ""} disabled={props.disabled} />
) : null}
</div>
)
}
The demo in the preview, 303 lines
"use client"
import * as React from "react"
import { CircleAlert } from "lucide-react"
import { Label } from "@/components/ui/label"
import {
ComboboxAsyncSearch,
type ComboboxAsyncSearchOption,
type ComboboxAsyncSearchResult,
} from "@/components/hazine/combobox-async-search"
interface Customer {
id: string
name: string
email: string
openInvoices: number
openBalance: number
}
const CUSTOMERS: Customer[] = [
{ id: "cus_1041", name: "Halden Freight", email: "billing@haldenfreight.example", openInvoices: 3, openBalance: 4260 },
{ id: "cus_1042", name: "Hallworth Dental Group", email: "accounts@hallworthdental.example", openInvoices: 1, openBalance: 890 },
{ id: "cus_1043", name: "Okafor and Lindqvist Architects", email: "marisol@okaforlindqvist.example", openInvoices: 0, openBalance: 0 },
{ id: "cus_1044", name: "Northgate Bakery", email: "orders@northgatebakery.example", openInvoices: 2, openBalance: 318 },
{ id: "cus_1045", name: "Tarn Valley Cycles", email: "ines@tarnvalleycycles.example", openInvoices: 1, openBalance: 1475 },
{ id: "cus_1046", name: "Brightwater Physiotherapy", email: "frontdesk@brightwaterphysio.example", openInvoices: 0, openBalance: 0 },
{ id: "cus_1047", name: "Sato Print Works", email: "kenji@satoprintworks.example", openInvoices: 4, openBalance: 2032 },
{ id: "cus_1048", name: "Harrow Lane Nursery", email: "hello@harrowlanenursery.example", openInvoices: 1, openBalance: 240 },
{ id: "cus_1049", name: "Meridian Roofing", email: "dispatch@meridianroofing.example", openInvoices: 2, openBalance: 6900 },
{ id: "cus_1050", name: "Castellan Legal", email: "ap@castellanlegal.example", openInvoices: 0, openBalance: 0 },
{ id: "cus_1051", name: "Wexham Veterinary Clinic", email: "practice@wexhamvets.example", openInvoices: 1, openBalance: 565 },
{ id: "cus_1052", name: "Adeyemi Catering", email: "tolu@adeyemicatering.example", openInvoices: 2, openBalance: 1120 },
]
const PAGE_SIZE = 5
const SEARCH_DELAY_MS = 450
const money = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
})
function toOption(customer: Customer): ComboboxAsyncSearchOption {
return {
value: customer.id,
label: customer.name,
description: customer.email,
meta: customer.openInvoices > 0 ? `${customer.openInvoices} open` : "Paid up",
}
}
function matchCustomers(query: string): ComboboxAsyncSearchResult {
const needle = query.toLowerCase()
const matches = CUSTOMERS.filter(
(customer) =>
customer.name.toLowerCase().includes(needle) ||
customer.email.toLowerCase().includes(needle)
)
return {
options: matches.slice(0, PAGE_SIZE).map(toOption),
total: matches.length,
}
}
// Stands in for a request to the customers endpoint. It honours the abort
// signal the way a real request does.
function searchCustomers(query: string, signal: AbortSignal) {
return new Promise<ComboboxAsyncSearchResult>((resolve, reject) => {
const timer = window.setTimeout(
() => resolve(matchCustomers(query)),
SEARCH_DELAY_MS
)
signal.addEventListener("abort", () => {
window.clearTimeout(timer)
reject(new Error("Search aborted"))
})
})
}
const CUSTOMER_LABELS = {
error: "Customers could not be loaded.",
emptyHint: "Check the spelling or search by email address.",
}
interface CustomerFieldProps
extends Partial<React.ComponentProps<typeof ComboboxAsyncSearch>> {
label?: string
/** Keeps room under the field so an open popup stays inside the frame. */
popupSpace?: boolean
children?: React.ReactNode
}
function CustomerField({
label = "Bill to",
popupSpace = false,
children,
...props
}: CustomerFieldProps) {
const id = React.useId()
const labelId = React.useId()
return (
<div className={popupSpace ? "min-h-96 w-full" : "w-full"}>
<div className="mx-auto flex max-w-sm flex-col gap-2">
<Label id={labelId} htmlFor={id}>
{label}
</Label>
<ComboboxAsyncSearch
id={id}
// A label names a button outright, so the button itself is listed
// too and the chosen customer is read after the label.
aria-labelledby={`${labelId} ${id}`}
loadOptions={searchCustomers}
placeholder="Select a customer"
searchPlaceholder="Search customers by name or email"
labels={CUSTOMER_LABELS}
{...props}
/>
{children}
</div>
</div>
)
}
export default function ComboboxAsyncSearchDemo() {
const hintId = React.useId()
const [selected, setSelected] =
React.useState<ComboboxAsyncSearchOption | null>(null)
const customer = CUSTOMERS.find((entry) => entry.id === selected?.value)
return (
<CustomerField
value={selected}
onValueChange={setSelected}
aria-describedby={hintId}
name="customer_id"
>
<p id={hintId} className="text-sm text-muted-foreground">
{customer === undefined ? (
<>
<span className="font-medium text-foreground tabular-nums">
{CUSTOMERS.length} customers
</span>{" "}
on this account. Search by name or email.
</>
) : customer.openInvoices === 0 ? (
<>
<span className="font-medium text-foreground">
No open invoices.
</span>{" "}
This one will be the only balance due.
</>
) : (
<>
<span className="font-medium text-foreground tabular-nums">
{money.format(customer.openBalance)} open
</span>{" "}
across {customer.openInvoices}{" "}
{customer.openInvoices === 1 ? "invoice" : "invoices"} already sent.
</>
)}
</p>
</CustomerField>
)
}
const instantSearch = (query: string) => Promise.resolve(matchCustomers(query))
function LoadingScenario() {
return (
<CustomerField
popupSpace
defaultOpen
defaultQuery="hal"
debounceMs={0}
loadOptions={() => new Promise<ComboboxAsyncSearchResult>(() => {})}
/>
)
}
function EmptyScenario() {
return (
<CustomerField
popupSpace
defaultOpen
defaultQuery="zephyr logistics"
debounceMs={0}
loadOptions={instantSearch}
/>
)
}
// The first request fails. Retry sends a second one, which succeeds.
function ErrorScenario() {
const requests = React.useRef(0)
return (
<CustomerField
popupSpace
defaultOpen
defaultQuery="ha"
debounceMs={0}
loadOptions={(query) => {
requests.current += 1
return requests.current === 1
? Promise.reject(new Error("Network unreachable"))
: Promise.resolve(matchCustomers(query))
}}
/>
)
}
const LONG_NAMES = [
"Internationale Speditionsgesellschaft Rheinhafen Nord",
"Kowalczyk, Brennan and Achterberg Chartered Accountants",
"St. Aldhelm Community Health and Wellbeing Partnership",
]
const OVERFLOW_OPTIONS: ComboboxAsyncSearchOption[] = Array.from(
{ length: 18 },
(_, index) => ({
value: `cus_${2001 + index}`,
label: `${LONG_NAMES[index % LONG_NAMES.length]}, branch ${index + 1}`,
description: `accounts.payable.branch${index + 1}@international-holdings.example`,
meta: `${(index + 1) * 12} open`,
})
)
function OverflowScenario() {
return (
<CustomerField
label="Bill to (parent account or any of its branches)"
popupSpace
defaultOpen
defaultQuery="in"
debounceMs={0}
defaultValue={OVERFLOW_OPTIONS[1]}
loadOptions={() =>
Promise.resolve({ options: OVERFLOW_OPTIONS, total: 1284 })
}
/>
)
}
function CurrentSelectionScenario() {
return (
<CustomerField
popupSpace
defaultOpen
defaultValue={toOption(CUSTOMERS[0])}
/>
)
}
function InvalidScenario() {
const errorId = React.useId()
const [selected, setSelected] =
React.useState<ComboboxAsyncSearchOption | null>(null)
const invalid = selected === null
return (
<CustomerField
value={selected}
onValueChange={setSelected}
aria-invalid={invalid}
aria-describedby={invalid ? errorId : undefined}
>
{invalid ? (
<p
id={errorId}
className="flex items-center gap-1.5 text-sm text-destructive"
>
<CircleAlert aria-hidden="true" className="size-3.5 shrink-0" />
Choose a customer before sending the invoice.
</p>
) : null}
</CustomerField>
)
}
function DisabledScenario() {
const reasonId = React.useId()
return (
<CustomerField
defaultValue={toOption(CUSTOMERS[4])}
aria-describedby={reasonId}
disabled
>
<p id={reasonId} className="text-sm text-muted-foreground">
The customer is locked once an invoice has been sent.
</p>
</CustomerField>
)
}
export const scenarios = {
loading: LoadingScenario,
empty: EmptyScenario,
error: ErrorScenario,
overflow: OverflowScenario,
"current-selection": CurrentSelectionScenario,
invalid: InvalidScenario,
disabled: DisabledScenario,
}
Props16
- loadOptionsrequired
- (query: string, signal: AbortSignal) => Promise<ComboboxAsyncSearchResult>
- Runs the search. Reject to show the error row. Abort on `signal` to cancel a stale request.
- value
- ComboboxAsyncSearchOption | null
- The chosen option. The whole option is kept, since its label cannot be looked up without a request.
- defaultValue
- ComboboxAsyncSearchOption | null = null
- onValueChange
- (value: ComboboxAsyncSearchOption | null) => void
- open
- boolean
- defaultOpen
- boolean = false
- onOpenChange
- (open: boolean) => void
- query
- string
- defaultQuery
- string = ""
- onQueryChange
- (query: string) => void
- minQueryLength
- number = 2
- Characters needed before a request is sent.
- debounceMs
- number = 250
- Quiet time after the last keystroke before a request is sent.
- placeholder
- string = "Select an option"
- Trigger text while nothing is chosen.
- searchPlaceholder
- string = "Search"
- Placeholder and accessible name of the search field.
- labels
- Partial<ComboboxAsyncSearchLabels>
- name
- string
- Adds a hidden input so the chosen value is submitted with a form.
Also accepts every prop of Omit< React.ComponentProps<typeof Button>, "value" | "defaultValue" | "name" | "children" | "asChild" | "type" >.
Accessibility
- Keyboard
Keyboard support for Async Search Combobox Key Effect Enter, Space or Arrow Down on the trigger Opens the popup and moves focus to the search field Arrow Up, Arrow Down Moves the active option Home, End Moves to the first or last option Enter Chooses the active option and closes the popup, or sends the request again after an error Tab Moves from the search field to Clear search or Retry when one is shown Enter or Space on Clear search or Retry Runs the action and returns focus to the search field Escape Closes the popup and returns focus to the trigger - Screen reader
A button opens a labelled popup. The search field inside is the combobox and controls a listbox through aria-activedescendant. The minimum characters hint describes the search field. The list is aria-busy while loading, counts go to a polite status region and a failed request to an alert.
- Announces: Searching
- Announces: Showing {shown} of {total} results. Keep typing to narrow.
- Announces: {total} results
- Announces: No results for "{query}".
- Announces: Results could not be loaded. Check your connection, then retry.
- Reduced motion
- Skeleton rows stop pulsing. The popup keeps the host popover transition.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies6
- button
- command
- popover
- skeleton
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.