MazInputAutocomplete
MazInputAutocomplete is a text input suggesting values while typing, from a local list (fuzzy search with typo tolerance) or from an async source (an API), with keyboard navigation, highlight of the matches and the ARIA combobox pattern.
Before use it, you should install the MazUi plugin in your project, follow instructions in Getting Started
Unlike MazSelect, the value is the text typed: a suggestion fills the input, and any other text stays allowed. v-model:selected gives the chosen suggestion (undefined once the text is edited).
Basic usage
The items are searched with fuzzySearch: prefixes, words in any order, initials ("nwz"), typos ("Franse"), accents and case. The best matches come first, the matched characters are highlighted.
Text: empty
Selected: none
<script lang="ts" setup>
import MazInputAutocomplete from 'maz-ui/components/MazInputAutocomplete'
import { useDisplayNames } from 'maz-ui/composables/useDisplayNames'
import { ref } from 'vue'
interface Country {
label: string
value: string
}
const countries: Country[] = useDisplayNames('en-US')
.getAllDisplayNames({ type: 'region' })
.value
.map(({ code, name }) => ({ label: name, value: code }))
const country = ref('')
const selectedCountry = ref<Country>()
</script>
<template>
<MazInputAutocomplete
v-model="country"
v-model:selected="selectedCountry"
label="Country"
:items="countries"
:limit="8"
block
/>
</template>Items
The items can be strings, numbers or objects. For objects, item-label gives the text (key or function, default label) and item-value the identity used to find the selected suggestion (default value).
search-keys changes the searched keys, with their weight (default: the label).
<MazInputAutocomplete
v-model="user"
label="User"
:items="users"
:item-label="user => `${user.firstName} ${user.lastName}`"
item-value="id"
:search-keys="[
user => `${user.firstName} ${user.lastName}`,
{ key: 'email', weight: 0.6 },
]"
/>search-threshold is the tolerance to typos: the minimal similarity (from 0 to 1) of a whole value with the query. 1 disables it (default 0.75).
Async source
source loads the suggestions of a query: an API, a database. It is called after debounce ms (default 300), with an AbortSignal aborted when a new query is typed, and its results are displayed in their order (the matched characters are still highlighted). The input shows a loader meanwhile.
<script lang="ts" setup>
import type { MazInputAutocompleteSourceContext } from 'maz-ui/components/MazInputAutocomplete'
import MazInputAutocomplete from 'maz-ui/components/MazInputAutocomplete'
import { ref } from 'vue'
interface City {
label: string
value: string
country: string
}
const city = ref('')
async function searchCities(query: string, { signal }: MazInputAutocompleteSourceContext) {
const response = await fetch(`/api/cities?q=${encodeURIComponent(query)}`, { signal })
return response.json() as Promise<City[]>
}
</script>
<template>
<MazInputAutocomplete
v-model="city"
label="City"
:source="searchCities"
:min-chars="2"
block
>
<template #item="{ item, segments }">
<span class="flex w-full items-center justify-between gap-2">
<span>
<template v-for="(segment, index) in segments" :key="index">
<b v-if="segment.match">{{ segment.text }}</b>
<template v-else>{{ segment.text }}</template>
</template>
</span>
<span class="text-muted">{{ item.country }}</span>
</span>
</template>
</MazInputAutocomplete>
</template>When the source throws, the error slot (with a retry function) is displayed and the error event is emitted.
Open on focus
open-on-focus opens the suggestions on focus. With min-chars at 0, every item is listed before typing (or the source is called with an empty query).
<MazInputAutocomplete
v-model="fruit"
label="Fruit"
:items="['Apple', 'Apricot', 'Banana', 'Cherry', 'Grape', 'Kiwi', 'Mango', 'Orange', 'Peach', 'Pear']"
:min-chars="0"
open-on-focus
/>Accessibility
The input is a combobox (aria-autocomplete="list"): the focus stays in it, aria-activedescendant points to the active suggestion, and the number of results is announced to the screen readers.
| Key | Action |
|---|---|
ArrowDown, ArrowUp | Open the list, move the active suggestion (Alt only opens) |
Enter | Choose the active suggestion, or the first one |
Escape | Close the list, a second time clear the input |
Tab | Close the list and move the focus |
TIP
This component can be translated globally using the MazUi plugin.
Props
| Name | Description | Type | Required | Default | Possible values |
|---|---|---|---|---|---|
| id | The id of the input | string | No | - | - |
| model-value | v-model The text of the input | string | No | "" | - |
| selected | v-model:selected The chosen suggestion, undefined once the text is edited | T | No | - | - |
| items | The suggestions searched locally (fuzzy search: prefixes, words in any order, scattered letters, typos, accents) | T[] | No | - | - |
| source | Load the suggestions of a query (an API...): they are displayed as they are, in their order. The previous request is aborted with the signal when a new query is typed | ((query: string, context: MazInputAutocompleteSourceContext) => T[] | Promise<T[]>) | No | - | - |
| item-label | The key or the function giving the text of a suggestion (displayed in the list and in the input once chosen) | string | ((item: T) => string) | No | "label" | - |
| item-value | The key or the function giving the identity of a suggestion (to find the selected one) | string | ((item: T) => unknown) | No | "value" | - |
| search-keys | The keys searched in the items, with their weight (see fuzzySearch of @maz-ui/utils) | FuzzySearchKey<T>[] | No | the label of the items | - |
| search-threshold | Tolerance of the search in the items to typos: the minimal similarity (from 0 to 1) of a whole value with the query. 1 disables the typo tolerance | number | No | 0.75 | - |
| min-chars | Minimal number of characters typed to search | number | No | 1 | - |
| debounce | Delay in ms between the last character typed and the call of the source | number | No | 300 | - |
| limit | Maximum number of suggestions displayed | number | No | - | - |
| highlight | Highlight the characters matching the query in the suggestions | boolean | No | true | - |
| open-on-focus | Open the suggestions on focus, with min-chars at 0 it lists every item | boolean | No | false | - |
| label | The label of the input | string | No | - | - |
| top-label | Static label displayed above the input | string | No | - | - |
| placeholder | The placeholder of the input | string | No | - | - |
| size | The size of the input | "xs" | "sm" | "md" | "lg" | "xl" | "mini" | No | 'md' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'mini' |
| color | The color of the input and of the selected suggestion | "primary" | "secondary" | "accent" | "info" | "success" | "warning" | "destructive" | "contrast" | "transparent" | No | "primary" | 'primary' | 'secondary' | 'accent' | 'info' | 'success' | 'warning' | 'destructive' | 'contrast' | 'transparent' |
| disabled | Disable the component | boolean | No | - | - |
| block | The input will be displayed in full width | boolean | No | - | - |
| max-list-height | The max height of the list | number | No | 240 | - |
| list-position | The position of the list | MazPopoverPosition | No | "auto" | - |
| transition | The transition of the list | string | No | "scale-fade" | - |
| translations | The translations of the component | Partial<{ noResults: string; loading: string; error: string; results: string; }> | No | { noResults: 'No results', loading: 'Loading...', error: 'An error occurred, try again', results: 'Results: {count}' } | - |
Events
| Event name | Payload | Description |
|---|---|---|
| open | - | The list is opened |
| error | error: unknown | The source failed |
| close | - | The list is closed |
| select | item: T | A suggestion is chosen |
| blur | event: Event | The input is blurred |
| focus | event: Event | The input is focused |
| update:modelValue | value: string | |
| update:selected | value: T | undefined |
Slots
| Name | Description | Bindings |
|---|---|---|
| item | A suggestion | item Tindex numberisActive booleanisSelected booleansegments FuzzySearchSegment[] |
| empty | No suggestion for the query | query string |
| loading | The source is loading | - |
| error | The source failed | error unknownretry () => void |
| header | Content above the suggestions | - |
| footer | Content below the suggestions | - |
| start-icon | Content of the inline-start edge of the input | - |
| end-icon | Content of the inline-end edge of the input | - |