Skip to content
Likable Aurora @likable-hair/svelte 5

AsyncAutocomplete

Autocomplete whose options come from a server: while the user types, it calls searcher with the text and shows the items it returns. A search starts when the text reaches searchThreshold characters (2 by default), debounceTimeout ms after the last keystroke, and only while the list is open; a newer search aborts the older one through signal, so a slow response never replaces a newer one. While searching, the field shows a spinner and the list shows skeleton rows. Below the threshold the list shows items, for example recent choices, filtered locally, or a "Type at least N characters" row. A failed search shows an error row and calls onerror. With searchThreshold={0} the first search runs as soon as the list opens. The results of the last search are kept, so reopening the list with the same text does not search again; search(), called through bind:this, runs the search again for the current text. Everything else works as in Autocomplete, including its props, snippets, events and --autocomplete-* variables.

import { AsyncAutocomplete } from '@likable-hair/svelte';

src/lib/components/composed/forms/AsyncAutocomplete.svelte · Markdown for LLMs

Search on a server

searcher receives the typed text and an AbortSignal and returns the items. In an app it calls the API, passing the signal so a newer search cancels the older one: fetch(url, { signal }). Here a fake API answers after 700ms. The search starts at 2 characters, half a second after the last keystroke, and meanwhile the list shows skeleton rows. itemIconSnippet adds an avatar to each client.

Selected: none

Code
<script lang="ts">
	import { AsyncAutocomplete, type Item } from '@likable-hair/svelte';

	const CLIENTS = [
		'Giulia Marini',
		'Giorgio Neri',
		'Martina Galli',
		'Marco Rossi',
		'Mario Esposito',
		'Sara Bianchi',
		'Sofia Ricci',
		'Luca Conti',
		'Elena Ferrari',
		'Marta Romano',
		'Davide Colombo',
		'Chiara Greco'
	];

	function wait(ms: number, signal: AbortSignal) {
		return new Promise<void>((resolve, reject) => {
			const timer = setTimeout(resolve, ms);
			signal.addEventListener('abort', () => {
				clearTimeout(timer);
				reject(signal.reason);
			});
		});
	}

	async function searchClients({ searchText, signal }: { searchText: string; signal: AbortSignal }) {
		await wait(700, signal);
		const query = searchText.toLowerCase();
		return CLIENTS.filter((name) => name.toLowerCase().includes(query)).map((name) => ({
			value: name,
			label: name
		}));
	}

	const initials = (name: string) =>
		name
			.split(' ')
			.map((part) => part[0])
			.join('');

	let values: Item[] = $state([]);
</script>

<div class="demo">
	<AsyncAutocomplete label="Client" placeholder="Search a client…" searcher={searchClients} bind:values>
		{#snippet itemIconSnippet({ item })}
			<span class="avatar">{initials(String(item.label))}</span>
		{/snippet}
	</AsyncAutocomplete>
	<p>Selected: {values[0]?.label ?? 'none'}</p>
</div>

<style>
	.demo {
		width: 100%;
		max-width: 340px;
	}

	.avatar {
		display: grid;
		place-items: center;
		flex-shrink: 0;
		width: 24px;
		height: 24px;
		border-radius: 50%;
		background: var(--global-color-primary-soft);
		color: var(--global-color-primary);
		font-size: 10px;
		font-weight: 700;
	}

	p {
		margin: 10px 0 0;
		color: var(--global-color-text-3);
		font-size: 13px;
	}
</style>

Suggestions and multiple selection

Below searchThreshold the list shows items, here the recent services, filtered locally while the first letter is typed; without items it shows a "Type at least N characters" row. bind:searching tells whether a search is waiting or running.

0 selected

Code
<script lang="ts">
	import { AsyncAutocomplete, type Item } from '@likable-hair/svelte';

	const SERVICES = [
		'Haircut',
		'Long blow-dry',
		'Short blow-dry',
		'Color',
		'Root touch-up',
		'Balayage',
		'Highlights',
		'Keratin treatment',
		'Hair mask',
		'Manicure',
		'Pedicure',
		'Beard trim'
	];

	const recent: Item[] = ['Haircut', 'Color', 'Beard trim'].map((name) => ({
		value: name,
		label: name
	}));

	function wait(ms: number, signal: AbortSignal) {
		return new Promise<void>((resolve, reject) => {
			const timer = setTimeout(resolve, ms);
			signal.addEventListener('abort', () => {
				clearTimeout(timer);
				reject(signal.reason);
			});
		});
	}

	async function searchServices({ searchText, signal }: { searchText: string; signal: AbortSignal }) {
		await wait(600, signal);
		const query = searchText.toLowerCase();
		return SERVICES.filter((name) => name.toLowerCase().includes(query)).map((name) => ({
			value: name,
			label: name
		}));
	}

	let values: Item[] = $state([]);
	let searching = $state(false);
</script>

<div class="demo">
	<AsyncAutocomplete
		label="Services"
		placeholder="Search services…"
		searcher={searchServices}
		items={recent}
		multiple
		bind:values
		bind:searching
	/>
	<p>{searching ? 'Searching…' : `${values.length} selected`}</p>
</div>

<style>
	.demo {
		width: 100%;
		max-width: 340px;
	}

	p {
		margin: 10px 0 0;
		color: var(--global-color-text-3);
		font-size: 13px;
	}
</style>

Errors

When searcher throws or rejects, the list shows errorText and onerror receives the error; searches aborted by a newer one are not errors. errorSnippet replaces the error row: its search runs the search again. Turn on the switch to make the fake API fail.

Errors: 0

Code
<script lang="ts">
	import { mdiRefresh } from '@mdi/js';
	import { AsyncAutocomplete, Button, Switch } from '@likable-hair/svelte';

	const PRODUCTS = ['Shampoo', 'Conditioner', 'Hair mask', 'Hair oil', 'Hairspray', 'Styling gel'];

	let failing = $state(true);
	let errors = $state(0);

	function wait(ms: number, signal: AbortSignal) {
		return new Promise<void>((resolve, reject) => {
			const timer = setTimeout(resolve, ms);
			signal.addEventListener('abort', () => {
				clearTimeout(timer);
				reject(signal.reason);
			});
		});
	}

	async function searchProducts({ searchText, signal }: { searchText: string; signal: AbortSignal }) {
		await wait(600, signal);
		if (failing) throw new Error('Service unavailable');
		const query = searchText.toLowerCase();
		return PRODUCTS.filter((name) => name.toLowerCase().includes(query)).map((name) => ({
			value: name,
			label: name
		}));
	}
</script>

<div class="demo">
	<Switch label="Make the server fail" bind:checked={failing} />
	<AsyncAutocomplete
		label="Product"
		placeholder="Search a product…"
		searcher={searchProducts}
		onerror={() => errors++}
	>
		{#snippet errorSnippet({ error, search })}
			<span class="error">
				{error instanceof Error ? error.message : "Couldn't load results"}
				<Button buttonType="text" size="sm" icon={mdiRefresh} onclick={search}>Retry</Button>
			</span>
		{/snippet}
	</AsyncAutocomplete>
	<p>Errors: {errors}</p>
</div>

<style>
	.demo {
		display: flex;
		flex-direction: column;
		gap: 14px;
		width: 100%;
		max-width: 340px;
	}

	.error {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 8px;
		color: var(--global-color-error);
	}

	p {
		margin: 0;
		color: var(--global-color-text-3);
		font-size: 13px;
	}
</style>

Load on open and refresh

With searchThreshold={0} the first search runs, with an empty text, as soon as the list opens: the server can answer with its first results. They are kept, so reopening the list does not search again; search(), called on the instance bound with bind:this, loads them again.

Searches: 0
Code
<script lang="ts">
	import { mdiRefresh } from '@mdi/js';
	import { AsyncAutocomplete, Button } from '@likable-hair/svelte';

	const STAFF = ['Anna', 'Beatrice', 'Carlo', 'Daniela', 'Enrico', 'Federica', 'Gianni', 'Ilaria'];

	let loads = $state(0);
	let autocomplete: ReturnType<typeof AsyncAutocomplete> | undefined = $state();

	function wait(ms: number, signal: AbortSignal) {
		return new Promise<void>((resolve, reject) => {
			const timer = setTimeout(resolve, ms);
			signal.addEventListener('abort', () => {
				clearTimeout(timer);
				reject(signal.reason);
			});
		});
	}

	async function searchStaff({ searchText, signal }: { searchText: string; signal: AbortSignal }) {
		await wait(600, signal);
		loads++;
		const query = searchText.toLowerCase();
		return STAFF.filter((name) => name.toLowerCase().includes(query)).map((name) => ({
			value: name,
			label: name
		}));
	}
</script>

<div class="demo">
	<AsyncAutocomplete
		bind:this={autocomplete}
		label="Stylist"
		placeholder="Choose a stylist…"
		searcher={searchStaff}
		searchThreshold={0}
		debounceTimeout={300}
	/>
	<div class="row">
		<Button variant="secondary" size="sm" icon={mdiRefresh} onclick={() => autocomplete?.search()}>
			Refresh
		</Button>
		<span>Searches: {loads}</span>
	</div>
</div>

<style>
	.demo {
		display: flex;
		flex-direction: column;
		gap: 12px;
		width: 100%;
		max-width: 340px;
	}

	.row {
		display: flex;
		align-items: center;
		gap: 12px;
		color: var(--global-color-text-3);
		font-size: 13px;
	}
</style>

Props

NameTypeDefaultDescription
searcher required(params: { searchText: string; signal: AbortSignal }) => Promise<Item<Data>[]>Fetches the options for a text. signal is aborted when a newer search starts or the component is destroyed: pass it to fetch.
items Item<Data>[][]Options shown while the text is shorter than searchThreshold, for example recent or suggested choices. They are filtered locally.
searchThreshold number2Number of characters that starts a search. With 0 the first search runs as soon as the list opens.
debounceTimeout number500Milliseconds to wait after the last keystroke before searching.
searching bindable booleanWhether a search is waiting or running. Read it with bind:searching.
icon stringSEARCH_ICONSVG path of the icon at the start of the field. An empty string removes it.
thresholdText stringText of the row shown below searchThreshold when no items match. Defaults to "Type at least N characters", in the language of locale.
errorText stringText of the row shown when a search fails. Defaults to "Couldn't load results", in the language of locale.

From Autocomplete

It accepts the props, snippets and events of Autocomplete, listed in the tables "From Autocomplete". Except loading, searchFunction.

NameTypeDefaultDescription
values bindable Item<Data>[]Selected options. With single selection it holds at most one item.
multiple booleanfalseAllows selecting more than one option.
searchText bindable stringText typed in the field.
open bindable booleanWhether the list is open. undefined counts as closed.
label stringVisible label above the field, linked to the input. In the mobile drawer it is the title.
hint stringText below the field. With state it becomes the error or success message.
state 'error' | 'success'Validation state: colors the border and the hint and shows an icon. error also sets aria-invalid.
placeholder stringPlaceholder of the search input.
disabled booleanfalseDisables the field: the list does not open and the values cannot be removed.
mandatory booleanfalsePrevents removing the last selected value.
id stringid of the input. Generated when missing, so the label always points to the input.
name stringForm field name: each selected value is submitted under this name.
maxVisibleChips numberShows at most this many chips, followed by a "+N" counter whose Tooltip lists the hidden values.
closeOnSelect booleanCloses the list after an option is selected. Defaults to true with single selection and to false with multiple.
clearSearchOnClose booleantrueEmpties searchText when the list closes.
placement 'bottom-start' | 'bottom' | 'bottom-end' | 'top-start' | 'top' | 'top-end' | 'left-start' | 'left' | 'left-end' | 'right-start' | 'right' | 'right-end''bottom-start'Side of the field the list opens on. It flips when there is not enough space.
mobileDrawer booleanfalseOn screens up to 1024px wide, opens the list in a bottom drawer with its own search field instead of a menu.
drawerSearch booleantrueShows the search field at the top of the mobile drawer. Without it the list itself takes the focus and the keyboard, as with a trigger that cannot type.
drawerTitle stringTitle of the mobile drawer. Defaults to label.
columns numberLays the options out in a grid with this many columns, for example for icons: the left and right arrows move to the previous and next option, the up and down arrows to the one above and below. In a text field the left and right arrows keep moving the caret. The menu takes the width of the grid instead of the one of the field.
loadingText stringText of the loading row. Defaults to "Loading…", in the language of locale.
noResultsText stringText shown when no option matches. Defaults to "No results", in the language of locale.
removeLabel stringAccessible name of the chip remove buttons, followed by the option label. Defaults to "Remove", in the language of locale.
closeLabel stringAccessible name of the close button of the mobile drawer. Defaults to "Close", in the language of locale.
locale stringBCP 47 locale of the texts: it and en are built in, other languages fall back to English. Defaults to the one set with setDefaultLocale, else en.
input bindable HTMLInputElementThe native <input> element.
class { container?: string; label?: string; field?: string; input?: string; chip?: string; menu?: string; option?: string; hint?: string; }{}Extra classes for each part.

It also accepts the native attributes and events of <input> (for example id, title, aria-label, onkeydown), which are forwarded to the element.

Snippets

NameParametersDescription
errorSnippet{ error: unknown; search: () => void }Replaces the content of the row shown when a search fails. search runs it again.

From Autocomplete

NameParametersDescription
labelSnippet{ label: string | undefined }Replaces the label content. It stays linked to the input.
hintSnippet{ hint: string | undefined }Replaces the hint below the field.
stateIconSnippet{ state: 'error' | 'success' }Replaces the icon shown for state. Render nothing to hide it.
selectionContainerSnippet{ values: Item<Data>[]; searchText: string | undefined; disabled: boolean; openMenu: () => void; handleKeyDown: (event: KeyboardEvent) => void; select: (item: Item<Data>) => void; unselect: (item: Item<Data>) => void; attributes: HTMLAttributes<HTMLElement>; }Replaces the whole field with a custom trigger, such as a button. Spread attributes on its focusable element and call handleKeyDown from its onkeydown, so it works as a combobox for keyboards and screen readers.
selectionSnippet{ selection: Item<Data>; unselect: (item: Item<Data>) => void }Replaces each selected chip.
chipLabelSnippet{ selection: Item<Data> }Replaces the text inside each selected chip.
chipIconSnippet{ selection: Item<Data> }Replaces the icon of each selected chip (item.icon), for example with an avatar or a flag.
iconSnippetReplaces the icon at the start of the field.
exceedCounterSnippet{ notVisibleChipNumber: number; maxVisibleChips: number; values: Item<Data>[]; searchText: string | undefined; disabled: boolean; }Replaces the "+N" counter shown with maxVisibleChips.
itemSnippet{ item: Item<Data>; index: number; selected: boolean; highlighted: boolean }Replaces the content of each option (icon, label and check mark). The option keeps its click handling, role and state.
itemLabelSnippet{ item: Item<Data> }Replaces the label of each option, keeping its icon and check mark.
itemIconSnippet{ item: Item<Data> }Replaces the icon of each option (item.icon), for example with an avatar or a flag.
itemAppendSnippet{ item: Item<Data>; selected: boolean }Content at the end of each option, before the check mark, for example a price or a code.
loadingSnippetReplaces the content of the loading row.
emptySnippet{ searchText: string | undefined }Replaces the content of the row shown when no option matches.

Events

NameTypeDescription
onerror(error: unknown) => voidCalled when searcher throws or rejects, except for searches aborted by a newer one.

From Autocomplete

NameTypeDescription
onchange(change: { select?: Item<Data>; unselect?: Item<Data>; selection: Item<Data>[]; }) => voidCalled when an option is selected or removed, with the option added (select), the one removed (unselect, with single selection also the one replaced) and the new selection.
onclose() => voidCalled whenever the list closes.

Methods

Call them on the instance: <AsyncAutocomplete bind:this={ref} />, then ref.search().

SignatureDescription

Types

Exported by the package: import type { Item } from '@likable-hair/svelte';

Item

An option of a picker (Autocomplete, Select, ...).

type Item<Data = unknown> = { … }

NameTypeDescription
value requiredstring | numberIdentity of the option: two items are the same option when their values are equal (===).
label string | numberText shown and searched. Defaults to value.
icon stringSVG path of an icon shown before the label, for example from @mdi/js.
data DataAny extra data, available in snippets and callbacks.

CSS variables

For a single instance, pass them as style props: <AsyncAutocomplete --async-autocomplete-skeleton-color="tomato">. The --async-autocomplete-default-* defaults apply to the whole app: override them in :root or in a theme.

It also takes the variables of Autocomplete.

Per-instance variableDefault
--async-autocomplete-skeleton-gap
--async-autocomplete-default-skeleton-gap 12px
--async-autocomplete-skeleton-row-gap
--async-autocomplete-default-skeleton-row-gap 10px
--async-autocomplete-skeleton-color
--async-autocomplete-default-skeleton-color var(--global-color-surface-2)
--async-autocomplete-skeleton-highlight-color
--async-autocomplete-default-skeleton-highlight-color var(--global-color-surface-3)
--async-autocomplete-skeleton-duration
--async-autocomplete-default-skeleton-duration 1.6s
--async-autocomplete-skeleton-avatar-size
--async-autocomplete-default-skeleton-avatar-size 24px
--async-autocomplete-skeleton-avatar-border-radius
--async-autocomplete-default-skeleton-avatar-border-radius var(--global-radius-full)
--async-autocomplete-skeleton-line-height
--async-autocomplete-default-skeleton-line-height 10px
--async-autocomplete-skeleton-line-border-radius
--async-autocomplete-default-skeleton-line-border-radius var(--global-radius-xs)