# 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.

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

Category: composed. Source: `src/lib/components/composed/forms/AsyncAutocomplete.svelte`.

## Examples

### 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.

```svelte
<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.

```svelte
<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.

```svelte
<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.

```svelte
<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

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `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` | `number` | `2` | Number of characters that starts a search. With `0` the first search runs as soon as the list opens. |
| `debounceTimeout` | `number` | `500` | Milliseconds to wait after the last keystroke before searching. |
| `searching` (bindable) | `boolean` |  | Whether a search is waiting or running. Read it with `bind:searching`. |
| `icon` | `string` | `SEARCH_ICON` | SVG path of the icon at the start of the field. An empty string removes it. |
| `thresholdText` | `string` |  | Text of the row shown below `searchThreshold` when no `items` match. Defaults to "Type at least N characters", in the language of `locale`. |
| `errorText` | `string` |  | Text 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 (`/components/autocomplete.md`), listed in the tables "From Autocomplete". Except `loading`, `searchFunction`.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `values` (bindable) | `Item<Data>[]` |  | Selected options. With single selection it holds at most one item. |
| `multiple` | `boolean` | `false` | Allows selecting more than one option. |
| `searchText` (bindable) | `string` |  | Text typed in the field. |
| `open` (bindable) | `boolean` |  | Whether the list is open. `undefined` counts as closed. |
| `label` | `string` |  | Visible label above the field, linked to the input. In the mobile drawer it is the title. |
| `hint` | `string` |  | Text 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` | `string` |  | Placeholder of the search input. |
| `disabled` | `boolean` | `false` | Disables the field: the list does not open and the values cannot be removed. |
| `mandatory` | `boolean` | `false` | Prevents removing the last selected value. |
| `id` | `string` |  | `id` of the input. Generated when missing, so the label always points to the input. |
| `name` | `string` |  | Form field name: each selected `value` is submitted under this name. |
| `maxVisibleChips` | `number` |  | Shows at most this many chips, followed by a "+N" counter whose Tooltip lists the hidden values. |
| `closeOnSelect` | `boolean` |  | Closes the list after an option is selected. Defaults to `true` with single selection and to `false` with `multiple`. |
| `clearSearchOnClose` | `boolean` | `true` | Empties `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` | `boolean` | `false` | On screens up to 1024px wide, opens the list in a bottom drawer with its own search field instead of a menu. |
| `drawerSearch` | `boolean` | `true` | Shows 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` | `string` |  | Title of the mobile drawer. Defaults to `label`. |
| `columns` | `number` |  | Lays 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` | `string` |  | Text of the loading row. Defaults to "Loading…", in the language of `locale`. |
| `noResultsText` | `string` |  | Text shown when no option matches. Defaults to "No results", in the language of `locale`. |
| `removeLabel` | `string` |  | Accessible name of the chip remove buttons, followed by the option label. Defaults to "Remove", in the language of `locale`. |
| `closeLabel` | `string` |  | Accessible name of the close button of the mobile drawer. Defaults to "Close", in the language of `locale`. |
| `locale` | `string` |  | BCP 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) | `HTMLInputElement` |  | The 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

| Name | Parameters | Description |
| --- | --- | --- |
| `errorSnippet` | `{ error: unknown; search: () => void }` | Replaces the content of the row shown when a search fails. `search` runs it again. |

### From Autocomplete

| Name | Parameters | Description |
| --- | --- | --- |
| `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. |
| `iconSnippet` |  | Replaces 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. |
| `loadingSnippet` |  | Replaces the content of the loading row. |
| `emptySnippet` | `{ searchText: string \| undefined }` | Replaces the content of the row shown when no option matches. |

## Events

| Name | Type | Description |
| --- | --- | --- |
| `onerror` | `(error: unknown) => void` | Called when `searcher` throws or rejects, except for searches aborted by a newer one. |

### From Autocomplete

| Name | Type | Description |
| --- | --- | --- |
| `onchange` | `(change: { select?: Item<Data>; unselect?: Item<Data>; selection: Item<Data>[]; }) => void` | Called 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` | `() => void` | Called whenever the list closes. |

## Methods

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

| Signature | Description |
| --- | --- |
| `search()` | Runs the search again for the current text, also below `searchThreshold`. |

## Types

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

### Item

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

`type Item<Data = unknown> = { … }`

| Name | Type | Description |
| --- | --- | --- |
| `value` (required) | `string \| number` | Identity of the option: two items are the same option when their `value`s are equal (`===`). |
| `label` | `string \| number` | Text shown and searched. Defaults to `value`. |
| `icon` | `string` | SVG path of an icon shown before the label, for example from `@mdi/js`. |
| `data` | `Data` | Any 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 (`/components/autocomplete.md`).

| Per-instance variable | Default |
| --- | --- |
| `--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)` |
