# CountriesAutocomplete

Autocomplete of countries, with their flags. The names come from the browser in the language of `locale` (the one set with `setDefaultLocale`, else English), so every language works, and the list is sorted by name in that language. The search ignores case and accents and also matches the ISO code (`us` finds the United States): names that start with the text come first, then the country with that code, then names with a word that starts with it, then the rest. `values` holds `Item`s whose `value` is the uppercase ISO 3166-1 alpha-2 code (`IT`); they can be set with the code alone, `[{ value: 'IT' }]`: the component fills in the name in `locale` and the dialing code. With `dialCode` every option also shows its dialing code (`+39`), which is in `item.data.dialCode` anyway. For a subset of the countries, or other labels, pass `items`, for example `countryItems('it', ['IT', 'SM', 'VA'])`. Everything else works as in `Autocomplete`, including its props, snippets, events and `--autocomplete-*` variables; the flags take the `--flag-icon-*` ones.

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

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

## Examples

### Country

Every country with its flag, sorted by name. The search ignores accents and also matches the ISO code: try “sviz”, “cura” or “us”. `values` holds items whose `value` is the ISO code, and can be set with the code alone.

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

	let values: Item<CountryData>[] = $state([{ value: 'IT' }]);
</script>

<div class="demo">
	<CountriesAutocomplete label="Country" placeholder="Search a country…" bind:values />
	<p>Code: {values[0]?.value ?? 'none'}</p>
</div>

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

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

### Language and dialing codes

`locale` sets the language of the names, which come from the browser, and the order of the list. `dialCode` shows the dialing code of each country, also available as `item.data.dialCode`.

```svelte
<script lang="ts">
	import { CountriesAutocomplete, Select, type CountryData, type Item } from '@likable-hair/svelte';

	const LANGUAGES: Item[] = [
		{ value: 'en', label: 'English' },
		{ value: 'it', label: 'Italiano' },
		{ value: 'fr', label: 'Français' },
		{ value: 'de', label: 'Deutsch' },
		{ value: 'ja', label: '日本語' }
	];

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

<div class="demo">
	<Select label="Language" items={LANGUAGES} bind:value={locale} />
	<CountriesAutocomplete
		label="Phone prefix"
		placeholder="Search…"
		{locale}
		dialCode
		bind:values
	/>
	<p>Prefix: {values[0]?.data?.dialCode ?? 'none'}</p>
</div>

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

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

### Some countries in a form

`countryItems(locale, codes)` builds the items of a subset of the countries. With `multiple` and `name`, every selected code is submitted with the form.

```svelte
<script lang="ts">
	import { Button, CountriesAutocomplete, countryItems } from '@likable-hair/svelte';

	const EUROZONE = [
		'AT', 'BE', 'HR', 'CY', 'EE', 'FI', 'FR', 'DE', 'GR', 'IE',
		'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PT', 'SK', 'SI', 'ES'
	];

	const items = countryItems('en', EUROZONE);
	let submitted = $state('');
</script>

<form
	class="demo"
	onsubmit={(event) => {
		event.preventDefault();
		submitted = new FormData(event.currentTarget).getAll('markets').join(', ');
	}}
>
	<CountriesAutocomplete
		label="Markets"
		placeholder="Eurozone countries…"
		{items}
		multiple
		name="markets"
		maxVisibleChips={3}
	/>
	<Button type="submit">Save</Button>
	{#if submitted}<p>Submitted: {submitted}</p>{/if}
</form>

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

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

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `locale` | `string` |  | Language of the country names and of the texts, as a BCP 47 tag such as `en`, `it` or `fr-CH` (the texts are English for languages other than `it` and `en`). Defaults to the one set with `setDefaultLocale`, else `en`. |
| `items` | `Item<CountryData>[]` |  | Countries to choose from. Defaults to all of them, named in `locale`, that is `countryItems(locale)`. |
| `dialCode` | `boolean` | `false` | Shows the dialing code of every country (`+39`) at the end of its option. |
| `class` | `AutocompleteProps['class'] & { flag?: string; dialCode?: string }` | `{}` | Classes of the parts: those of `Autocomplete`, plus `flag` on every flag and `dialCode` on every dialing code. |

### From Autocomplete

It accepts the props, snippets and events of Autocomplete (`/components/autocomplete.md`), listed in the tables "From Autocomplete". Except `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. |
| `icon` | `string` |  | SVG path of an icon at the start of the field, for example a magnifier from `@mdi/js`. |
| `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. |
| `loading` | `boolean` | `false` | Shows a spinner in the field and a loading row in place of the options, for example while results are fetched. |
| `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`. |
| `input` (bindable) | `HTMLInputElement` |  | The native `<input>` element. |

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

## Snippets

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

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

## Types

Exported by the package: `import type { Item, CountryData } 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. |

### CountryData

Extra data of the country items made by `countryItems`.

`type CountryData = { … }`

| Name | Type | Description |
| --- | --- | --- |
| `dialCode` | `string` | International dialing code with the plus sign, for example `+39`. Missing for territories without one. |

## CSS variables

For a single instance, pass them as style props: `<CountriesAutocomplete --countries-autocomplete-dial-code-color="tomato">`. The `--countries-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 |
| --- | --- |
| `--countries-autocomplete-dial-code-color` | `--countries-autocomplete-default-dial-code-color`: `var(--global-color-text-3)` |
| `--countries-autocomplete-dial-code-font-family` | `--countries-autocomplete-default-dial-code-font-family`: `var(--global-font-family-mono)` |
| `--countries-autocomplete-dial-code-font-size` | `--countries-autocomplete-default-dial-code-font-size`: `11px` |
