Skip to content

Components

Combobox

A form field where the user types to narrow a list and picks one value from it. It follows the WAI-ARIA combobox pattern with list autocomplete: focus stays in the input while the highlighted option is announced.

Live demo

This is the Tailwind wrapper from the recipe below, running over every IANA timezone. Type part of a name, such as jakar, and pick one.

value = null

Usage

Items are the same data as Select: options, separators and labelled groups. Unlike Select, you filter them. Bind query to the typed text and pass the options to show as items. The value is always one of the options; free text is not a value.

<script>
	import { Combobox } from '@frostycle/rime/combobox';

	let timezone = $state(null);
	let query = $state('');

	const visible = $derived(timezones.filter((zone) => contains(zone.label, query)));
</script>

<label for="timezone">Timezone</label>
<Combobox id="timezone" items={visible} bind:value={timezone} bind:query name="timezone" placeholder="Search timezones">
	{#snippet empty({ query })}<p>No timezone matches “{query}”.</p>{/snippet}
</Combobox>

Filtering

The component has no matching rules of its own. Each change to query with text in it highlights the first enabled option, so Enter picks the best match. This is the case- and accent-insensitive "contains" filter the demo uses.

const plain = (text) => text.toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, '');

const contains = (label, query) => plain(label).includes(plain(query));

To search a server, fetch the results yourself and pass them as items with no further filtering. While query is empty, include the current option in items. The input takes its label from the option with the selected value, and a value whose option was never in items shows an empty input.

<script>
	import { Combobox } from '@frostycle/rime/combobox';

	const saved = { value: 'id', label: 'Indonesia' };

	let country = $state(saved.value);
	let query = $state('');
	let results = $state([]);

	$effect(() => {
		const controller = new AbortController();
		fetch(`/api/countries?q=${encodeURIComponent(query)}`, { signal: controller.signal })
			.then((response) => response.json())
			.then((found) => (results = found));
		return () => controller.abort();
	});

	const items = $derived(query === '' ? [saved, ...results.filter((r) => r.value !== saved.value)] : results);
</script>

<label for="country">Country</label>
<Combobox id="country" {items} bind:value={country} bind:query />

There is no fetching, debouncing or loading state. The empty snippet receives query, so render "Searching…" from your own flag. When a filter removes the selected option, the input keeps the label of the option most recently picked or found.

Labelling

The input is a labelable element, so <label for> pointing at its id names it, and clicking the label focuses it. The list takes the same label text as its accessible name when it opens. A custom input snippet must keep the spread id.

The input has role="combobox", aria-autocomplete="list", aria-expanded, aria-controls while open and aria-activedescendant while an option is highlighted. The list, options, groups and separators are exactly Select's. The optional toggle button is hidden from assistive technology and outside the tab order, because the input already opens the list with Down.

Props

PropTypeNotes
items(T | ComboboxSeparator | ComboboxGroup<T>)[]Required. The options to show now, already filtered by you. T extends ComboboxOption, so extra fields such as an icon flow into the option snippet. Same shape as Select.
valuestring | nullBindable. null means nothing is selected. Default null.
querystringBindable. The text being typed; '' while the user is not editing. Default ''.
onchange(value: string | null) => voidCalled when the user picks a different value or clears the field.
idstringThe input's id, so <label for> names the field. Default a generated id.
namestringRenders a hidden input carrying the value, empty when null. The text input has no name, so typed text is never submitted. A pick or clear fires bubbling input and change events from the hidden input.
placeholderstringThe input's placeholder.
placementPlacementFrom @floating-ui/dom. Default bottom-start.
disabledbooleanDisables the input, closes the list if it is open, and renders no hidden input.
transitionbooleanKeeps the popup mounted through its CSS transition, as on the date pickers. Default false.
classes{ input, popup, option, separator, group, groupLabel }Classes for default-rendered elements. The toggle button exists only through the button snippet, so it has no class entry.

Snippets

All optional. Spread each props onto your element.

  • input

    props, open, selected

    Replaces the default <input>; spread props on an <input>. selected is the selected option, or null.

  • button

    props, open

    A toggle button rendered after the input. There is none without this snippet. It has tabindex="-1" and aria-hidden="true", and pressing it keeps focus in the input. Closing the list with it keeps the typed text.

  • popup

    props, content

    Render content for the default body.

  • option

    option, props, selected, highlighted, disabled

  • separator

    props

    Renders with role="none" inside the list, since a listbox may contain only options and groups.

  • groupLabel

    label, props

  • empty

    query

    Shown in the open list when items has no options. Without it, the list stays closed when there is nothing to show.

While empty shows, the popup has no listbox role and the message is rendered in a role="status" element. Nothing is highlighted then.

Keyboard

Focus never leaves the input; the highlighted option is announced through aria-activedescendant. Disabled options are skipped, and hovering an enabled option highlights it. Escape and Enter during IME composition, including Safari's keyCode 229, are ignored. Unlike Select, Tab does not pick: the highlight follows typing, so committing on Tab would pick by accident.

Typing, Backspace, paste
Edit the text, filter through query, and open the list
Down, Up, Alt+Down on the closed input
Open the list
Down, Up
Move between enabled options, stopping at the ends
Page Down, Page Up
Move ten enabled options
Enter
With an option highlighted, pick it and close. While editing with nothing highlighted, an empty input clears the value and other text restores the selected label; the form is not submitted. When not editing, submits the form as in any text field
Escape
While editing: close the list, restore the selected label, and stop the event so a surrounding <dialog> stays open. When not editing, the <dialog> handles it
Tab
Close without picking and let focus move on; the text returns to the selected label
Home, End, Left, Right
Move the caret, as in any input. There is no type-ahead

State attributes

Style state with data-* attributes rather than props. They are present or absent, with no value.

ElementAttributes
Inputdata-open, data-disabled, data-hover, data-focus, data-active
Buttondata-open, data-disabled, data-hover, data-active
Popupdata-open, plus data-closed, data-enter and data-leave with transition
Optiondata-highlighted, data-selected, data-disabled

Forms

With name, a hidden input carries the value, empty when it is null. The text input has no name, so what the user typed is never submitted. A pick or a clear fires bubbling input then change from the hidden input, like a native select. A form reset restores the value from when the component mounted and sets query to ''. The input has autocomplete="off" so the browser's suggestions do not cover the list. There is no required yet.

Emptying the input and leaving the field, or pressing Enter with nothing highlighted, sets the value to null and calls onchange(null). Leaving with other text that was not picked restores the selected label and keeps the value.

Tailwind recipe

The library ships no Tailwind classes, so there is nothing to configure or override. Copy this wrapper into your project and own it. It needs Tailwind CSS v4, whose bare data-highlighted: variants it uses; in v3 write data-[highlighted]:.

import type { ComboboxClasses } from '@frostycle/rime/combobox';

export const comboboxClasses: ComboboxClasses = {
	input:
		'w-64 rounded-md border border-gray-300 bg-white py-2 pr-9 pl-3 text-sm text-gray-900 placeholder:text-gray-500 data-hover:bg-gray-50 data-focus:outline-2 data-focus:outline-offset-2 data-focus:outline-blue-600 data-open:border-blue-600 data-disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder:text-gray-400 dark:data-hover:bg-gray-700',
	popup:
		'max-h-72 w-64 overflow-y-auto rounded-lg border border-gray-200 bg-white p-1.5 text-sm text-gray-900 shadow-lg transition duration-150 ease-out outline-none data-closed:-translate-y-1 data-closed:opacity-0 motion-reduce:transition-none dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100',
	option:
		'block w-full rounded-md px-2.5 py-1.5 text-start data-highlighted:bg-gray-100 data-selected:font-semibold data-disabled:opacity-50 dark:data-highlighted:bg-gray-700',
	separator: 'mx-1 my-1.5 h-px bg-gray-200 dark:bg-gray-700',
	groupLabel: 'px-2.5 pt-1.5 pb-1 text-xs font-semibold text-gray-500 dark:text-gray-400'
};
<script lang="ts" generics="T extends ComboboxOption">
	import { Combobox, type ComboboxOption, type ComboboxProps } from '@frostycle/rime/combobox';
	import { comboboxClasses } from './combobox-classes.js';

	let { value = $bindable(null), query = $bindable(''), ...props }: ComboboxProps<T> = $props();
</script>

<div class="relative inline-block">
	<Combobox transition classes={comboboxClasses} bind:value bind:query {...props}>
		{#snippet button({ props: buttonProps })}
			<button
				{...buttonProps}
				class="absolute inset-y-0 right-0 px-2.5 text-gray-500 data-disabled:opacity-50 dark:text-gray-400"
			>
				<svg viewBox="0 0 20 20" class="size-4 fill-none stroke-current stroke-2" aria-hidden="true">
					<path d="M5 8l5 5 5-5" />
				</svg>
			</button>
		{/snippet}
		{#snippet empty({ query: typed })}
			<p class="m-0 px-2.5 py-1.5 text-gray-500 dark:text-gray-400">No match for “{typed}”.</p>
		{/snippet}
	</Combobox>
</div>
<AppCombobox id="timezone" items={visible} bind:value={timezone} bind:query name="timezone" />

Behaviour to plan for

While the user is not editing, the input shows the selected label. Typing replaces it with the typed text and sets query; a pick, Escape, leaving the field, clicking outside the list or a form reset set query back to ''. Leaving or clicking outside with the input emptied clears the value. The component never rewrites the input while the user types, and an emptied input highlights nothing until Down or Up.

When items has no options, the empty snippet is shown in the open list. Without it the list closes, and reopens when options return while the user is still typing. Closing the list with the toggle button keeps the typed text, and results arriving later do not reopen it until the user types again or presses Down or Up. When items change without a query change, such as late server results, the highlight stays on an option the user moved to; otherwise it goes to the first enabled option. Separators left at either end of the list, or next to each other, by groups your filter emptied are not rendered.

Disabling an open combobox closes it and disables the input, so focus falls to <body>. Move focus yourself if you disable one while it is in use. Free-text values, several values, opening on focus and virtualised lists are not supported.