AutoComplete
Free text input with hints, search and option selection.
When to use
AutoComplete helps you enter free text: an address, a search query, or a city. Tooltips speed up input, but the user may save a string that is not in options. If you need to select a known value, use Select.
Make tooltip labels clear and the resulting value suitable for insertion into a field. Groups and additional description help compare results, but do not change the string type of the model. Categories of hints show separate label and value.
AutoComplete CSS prefixes show global ConfigProvider.prefixCls and local prefixCls without resetting state. AutoComplete uses namespace Select; prefixCls specifies the full prefix of this control and popup. The nested Input/TextArea chooses its prefix independently. Free input and carriage are preserved.
Model and events
The managed field receives a value and updates the state via onChange. In the current API, this property does not support bind:value. For the initial local value, use defaultValue; changing it later does not reinitialize the input.
| Problem | Setting | Example |
|---|---|---|
| Store the entered string | value, onChange |
Basic input |
| Prepare hints | showSearch.onSearch |
Search results |
| Process confirmed option | onSelect |
Address tips |
| Link a field to a form model | value from Form and onChange |
Free input in Form |
Finding and changing a value are different events. Selecting an option triggers onChange and onSelect, but is not a new search input. Don't store the model only in showSearch.onSearch: this is especially important with IME composition. Cleanup might report undefined, then an empty string; normalize the new value through next ?? '', as in cleaning example.
FormItem links the signature and messages, and the value is passed explicitly. Example form checks that the string is required and accepts a city outside the suggested list. If the server must accept only known values, such a check is specified by the application or Select is used.
Search and keyboard
By default, options contains value strings and optional labels, and groups combine options through options. Enable the desired filtering explicitly via showSearch.filterOption. Case insensitive search compares strings after case conversion. When preparing results from an external source, disable repeated local filtering and check the relevance of the answer in the application.
The arrows move the active tooltip and skip disabled options. Enter confirms the active option, Escape closes the list. backfill shows preview text during navigation without committing the model until confirmed. Keyboard example shows selection and deselection separately.
In the package defaultActiveFirstOption is set to false, but on ant.design it is set to true. If the input is non-empty, the package will also activate the first option starting with the entered line. Focus on visible lighting and aria-activedescendant. During IME composition, Enter should not prematurely acknowledge the prompt.
Own control and list
children snippet receives AutoCompleteInput: attributes and register. Pass attributes to the native input/textarea and register the real element; when unmount, release the registration. Own TextArea uses public bind:nativeElement TextArea, preserving focus and keyboard handlers.
In the custom editors example, components.input renders an input or a textarea. Forward attributes and attach register to the element to keep editing, selection and focus working. showAction opens the first list on focus, and maxLength limits typing in both editors. Use components.root to replace the entire field. In this example, a textarea with rows=3 is one line tall. For three visible lines, use the TextArea example.
The local getPopupContainer gets the Select root and takes precedence over the ConfigProvider. Container example shows empty result via notFoundContent and classNames.popup.root decoration. In the current package, the empty list is hidden if there are no options or non-empty notFoundContent; This is a clarification to the FAQ of the official page.
ConfigProvider.popupOverflow selects the visible viewport or the scroll document region for overflow calculation. The shared example demonstrates inheritance and resetting to viewport. The mode does not change the DOM container, input or focus; new coordinates apply on the next opening, resize or scroll. The popup remains a fixed native popover, with its width determined by popupMatchSelectWidth.
classNames/styles and popupRender style parts of the control and extend the popup. prefix adds content before the editor. suffix changes the trailing area, and allowClear sets the clear icon and its accessible name; see the supported features in API.
AutoComplete uses design tokens from the current theme for its appearance.
popupMatchSelectWidth inherits ConfigProvider when the local prop is omitted or undefined. A value of true matches the control width, false fits the content, and a number sets the width in px; the control width remains the minimum. Shared popup width demonstrates inheritance and local precedence. Changing the width preserves input and selection.
Long suggestion lists
The grouped example demonstrates switching ConfigProvider.virtual and jumping to the last suggestion. Virtualization keeps a visible window in the DOM and measures option and group heading heights separately.
listHeight caps the inner viewport at 256 px by default; 0 removes the limit. Popup padding and borders are added outside it. listItemHeight provides an estimate before measurement, defaulting to token.controlHeight; 0 disables windowing. showScrollBar accepts true, false, or optional; optional displays the bar during scrolling or a scrollTo call and hides it after 3 seconds.
Without a local virtual prop, ConfigProvider.virtual applies. An explicitly supplied virtual=undefined enables default=true even under provider=false. popupMatchSelectWidth=false disables virtualization; numeric 0 preserves it. For a complete accessible listbox, set virtual=false; with virtualization it contains the active option and its neighbors.
bind:this provides AutoCompleteRef with focus, blur, and scrollTo. A number passed to scrollTo is a row index, including group headings. Set key on the source record for key scrolling: without it, the literal value is used, then an automatic key, independently of fieldNames.value. An index/key request runs after opening and updating the DOM with tick, as shown in the example. bind:inputElement returns the editor and bind:nativeElement the root; with components, these are the registered elements.
onActive receives the active value or null and does not replace onChange or onSelect. onPopupScroll forwards the native event from the inner viewport; currentTarget and this refer to that div.
Source suggestion fields
To use application records without converting them into value/label, set fieldNames. The value, label, options, and groupLabel names can point to custom fields; one level of groups is supported. The source suggestion example keeps the label, input text, and site section separate.
AutoCompleteProps<OptionType> preserves the record type in filters and callbacks. onSelect provides a shallow copy of the source record, including additional fields, and also runs for repeated selection. onChange receives Partial<optionType> or undefined; free input remains a string and does not require a matching option.
The showSearch.filterOption predicate receives a copy of the source option or group. A group match retains its children; otherwise individual suggestions are filtered. The example switch compares filtering by source fields with the complete list.
Rendering suggestions
Custom content uses optionRender: a Snippet receiving SelectFlattenOption<string, OptionType> and { index }. Data contains the raw record; the index is absolute and includes group headings, including with virtualization. Only the option content changes: value, filtering, title and events remain intact. Do not nest interactive elements inside the native option button.
labelRender is a pure function receiving Select metadata; it also runs during SSR. null/undefined falls back to the raw value. The standard editor retains its raw string and an invisible label DOM; a custom input suppresses this DOM while keeping function calls. To change editor text, update value through onChange. tagRender appears in types and metadata but is not called in AutoComplete; labelInValue and optionLabelProp apply only to Select.
Popup and styling
The custom popup uses the same pure popupRender as Select. A Snippet receives the original menu and can add an adjacent explanation. The function runs while closed and during SSR; visited content survives closing. A nullish result leaves an empty popup without restoring the default menu. A custom popup isolates FormItem status/feedback and Compact.
Styling individual parts demonstrates prefix, classNames/styles and ConfigProvider.select. Slots include root, prefix, input, placeholder, content, clear and popup.root/list/listItem; suffix and tag slots are absent. Objects and functions receiving props are supported; AutoComplete metadata contains its own raw props. Both a CSS object and a style string style the same root; rootClassName also applies to the popup.
Shared ConfigProvider.select provides variant, class/style, classNames/styles and showSearch. An explicit nested select replaces the parent record. A local popup leaf replaces the corresponding shared styles entirely. AutoComplete’s own allowClear defaults to false even with provider allowClear=true. showSearch=false keeps the combobox editable and the string unrestricted.
Suffix and clearing
The suffix example shows a search icon and the loading state. suffix replaces the trailing area including Form feedback; its function receives SelectSuffixInfo. searchValue contains the main value without temporary backfill text. Keep the function pure: it also runs during SSR and while the list is closed. Return a snippet from the function or pass it inside an array.
The clear button receives clearIcon and a translated label through allowClear. An object without label uses “clear” by default; the existing form with only a snippet clearIcon retains the localized name. boolean true also uses the locale. AutoComplete requires a local allowClear setting and does not inherit it from ConfigProvider.select. The object’s disabled and tabIndex fields are not available yet.
Examples
Basic input
Local and controlled value. showSearch.onSearch prepares tooltips, onChange updates the text, onSelect reports the selection.
<script lang="ts">
import { AutoComplete } from '@woodger/antd';
let search = $state('');
let value = $state('');
let controlledSearch = $state('');
let selected = $state('');
const options = $derived(
search
? [1, 2, 3].map(count => ({ value: search.repeat(count) }))
: []
);
const controlledOptions = $derived(
controlledSearch
? [1, 2, 3].map(count => ({ value: controlledSearch.repeat(count) }))
: []
);
</script>
<style>
.example {
display: grid;
gap: 20px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<AutoComplete options={(options)} showSearch={{
onSearch: next => { search = next; }
}}
onSelect={next => { selected = next; }} aria-label={("Local AutoComplete")}
placeholder={("Local value")} />
<AutoComplete {value} options={(controlledOptions)}
showSearch={{ onSearch: next => { controlledSearch = next; } }}
onChange={next => { value = next ?? ''; }} onSelect={next => { selected = next; }}
aria-label={("Controlled AutoComplete")} placeholder={("Controlled value")} />
<output
aria-label={("Basic AutoComplete value")}
>{("Text: ")}{(value || '—')}</output>
<output
aria-label={("Selected AutoComplete prompt")}
>{("Selected: ")}{(selected || '—')}</output>
</div>
Value:
Address hints
Domains are substituted for the entered name. The review example is reused, including cleanup, backfill, and external reset.
<script lang="ts">
import { AutoComplete, Button } from '@woodger/antd';
let value = $state('');
let search = $state('');
let options = $derived(
search
? ['example.com', 'mail.org', 'team.dev']
.map(domain => ({ value: `${search.split('@')[0]}@${domain}` }))
: []
);
</script>
<div style="max-width:440px">
<AutoComplete
aria-label={("Address with tips")}
placeholder={("Enter mailbox name")}
{value}
options={(options)}
allowClear
backfill
onChange={next => { value = next ?? ''; }}
showSearch={{ onSearch: next => { search = next; } }}
/>
<p>{("Value: ")}<output
aria-label={("AutoComplete value")}
>{(value || '—')}</output></p>
<Button
onclick={() => {
value = '';
search = '';
}}
>{("Reset hints")}</Button>
</div>
Own TextArea
children snippet receives attributes and register. The TextArea from the package passes the native element for focus and tooltip selection; registration is cleared upon unmount.
<script lang="ts">
import { onDestroy } from 'svelte';
import { AutoComplete, TextArea, type AutoCompleteInput } from '@woodger/antd';
let value = $state('');
let textarea = $state<HTMLTextAreaElement>();
let unregister: (() => void) | undefined;
const options = [{ value: 'project ready' }, { value: 'project review' }, {
value: 'publish docs'
}];
onDestroy(() => unregister?.());
</script>
<AutoComplete
{value}
options={(options)}
showSearch={{ filterOption: true }}
defaultActiveFirstOption
onChange={next => { value = next ?? ''; }}
aria-label={("Hints in TextArea")}
placeholder={("Enter project")}
>
{#snippet children(control: AutoCompleteInput)}
<TextArea {...control.attributes} rows={3} bind:nativeElement={
() => textarea,
element => {
unregister?.();
textarea = element;
unregister = element ? control.register(element).destroy : undefined;
}
} />
{/snippet}
</AutoComplete>
Case insensitive search
showSearch.filterOption compares the entered text and value in a case-insensitive manner. Local filtering is explicitly enabled.
<script lang="ts">
import { AutoComplete } from '@woodger/antd';
const options = [{ value: 'Burns Bay Road' }, { value: 'Downing Street' }, {
value: 'Wall Street'
}];
</script>
<AutoComplete options={(options)} aria-label={("Case insensitive search")} placeholder={("Enter b or STREET")}
showSearch={{
filterOption: (text, option) => 'value' in option
&& option.value.toUpperCase().includes(text.toUpperCase())
}} />
Hint categories
Groups separate components and settings. Snippets show additional information; The value of the selected option is stored in the field.
<script lang="ts">
import { AutoComplete } from '@woodger/antd';
let value = $state('');
</script>
<style>
.option {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 8px;
}
.count {
color: var(--ant-color-text-secondary);
font-size: 12px;
}
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
}
</style>
{#snippet buttonLabel()}
<span class="option"><span>Button</span><span class="count">
{("15 examples")}
</span></span>
{/snippet}
{#snippet inputLabel()}
<span class="option"><span>Input</span><span class="count">
{("21 examples")}
</span></span>
{/snippet}
{#snippet themeLabel()}<span
class="option"
><span>{("Interface theme")}</span><span
class="count"
>{("Settings")}</span></span>{/snippet}
<AutoComplete {value} onChange={next => { value = next ?? ''; }} aria-label={("Search by category")}
placeholder={("Components and Settings")} options={([
{
label: "Components", options: [{ value: 'Button', label: buttonLabel }, {
value: 'Input',
label: inputLabel
}]
},
{ label: "Settings", options: [{ value: "Interface theme", label: themeLabel }] }
])} />
<output aria-label={("Selection by category")}>{("Value: ")}{(value
|| '—')}</output>
Source suggestion fields
fieldNames maps group and suggestion fields; filters and onSelect receive source records.
<script lang="ts">
import { AutoComplete, Checkbox } from '@woodger/antd';
interface Suggestion {
key: string;
input?: string;
caption?: string;
category?: string;
children?: readonly Suggestion[];
section?: string;
}
const SearchInput = AutoComplete<Suggestion>;
const options: readonly Suggestion[] = [
{
key: 'components',
category: ("Components"),
children: [
{
key: 'button',
input: 'Button',
caption: ("Buttons"),
section: 'components'
},
{
key: 'input',
input: 'Input',
caption: ("Input fields"),
section: 'components'
}
]
},
{
key: 'documentation',
category: ("Documentation"),
children: [
{
key: 'theme',
input: 'Theme',
caption: ("Theme customization"),
section: 'design'
}
]
}
];
let value = $state('');
let filter = $state(true);
let selected = $state('—');
function matchesSuggestion(search: string, option: Suggestion) {
const query = search.toLocaleLowerCase("en");
const fields = [option.input, option.caption, option.category];
return fields.some(field => field?.toLocaleLowerCase("en").includes(query));
}
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
output {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
<div class="example">
<Checkbox bind:checked={filter}>{("Filter by source fields")}</Checkbox>
<SearchInput
{options}
{value}
fieldNames={{ value: 'input', label: 'caption', options: 'children', groupLabel: 'category' }}
showSearch={{ filterOption: filter ? matchesSuggestion : false }}
onChange={next => { value = next ?? ''; }}
onSelect={(_next, option) => { selected = JSON.stringify(option); }}
allowClear
aria-label={("AutoComplete with record fields")}
placeholder={("Find a component or setting")}
style="width:100%"
/>
<output aria-label={("AutoComplete source record")}>{selected}</output>
</div>
Search results
The demo source generates results based on the search string. Selection is separate from search; label contains an explanation, value is the final text.
<script lang="ts">
import { AutoComplete } from '@woodger/antd';
let value = $state('');
let search = $state('');
let selected = $state('');
</script>
<style>
.result {
display: grid;
gap: 4px;
}
small { color: var(--ant-color-text-secondary); }
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
{#snippet docs()}
<span
class="result"
><span>{("Documentation for \"")}{search}»</span><small>
{("Sections and API reference")}
</small></span>
{/snippet}
{#snippet examples()}
<span
class="result"
><span>{("Examples for \"")}{search}»</span><small>
{("Interactive scenarios")}
</small></span>
{/snippet}
<AutoComplete {value} aria-label={("Tips on request")} placeholder={("Enter your request")}
onChange={next => { value = next ?? ''; }} showSearch={{ onSearch: next => { search = next; } }}
onSelect={next => { selected = next; }} options={(search ? [
{ value: `${search} docs`, label: docs },
{ value: `${search} examples`, label: examples }
] : [])} />
<output
aria-label={("Selected query result")}
>{("Selected: ")}{(selected || '—')}</output>
States
Error, warning and inaccessible field. The error is also reflected in aria-invalid.
<script lang="ts">
import { AutoComplete } from '@woodger/antd';
const options = [{ value: 'Svelte' }, { value: 'TypeScript' }];
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">
<AutoComplete options={(options)} status="error" aria-label={("AutoComplete error")} placeholder={("Error")} />
<AutoComplete options={(options)} status="warning" aria-label={("Warning AutoComplete")} placeholder={("Warning")} />
<AutoComplete
options={(options)}
disabled
defaultValue="Svelte"
aria-label={("Unavailable AutoComplete")}
/>
</div>
Design options
outlined, filled, borderless and underlined change the appearance of the field without changing the input model.
<script lang="ts">
import { AutoComplete, type AutoCompleteProps } from '@woodger/antd';
const variants =
[
'outlined',
'filled',
'borderless',
'underlined'
] as const satisfies readonly AutoCompleteProps['variant'][];
const options = [{ value: 'Svelte' }, { value: 'TypeScript' }];
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">{#each variants as variant (variant)}
<AutoComplete {variant} options={(options)} aria-label={("AutoComplete option " + String((variant)) + "")} placeholder={(variant)} />
{/each}</div>
Your own cleaning icon
allowClear sets the clear icon and accessible name. onChange updates the string; onClear counts clear actions separately.
<script lang="ts">
import { AutoComplete } from '@woodger/antd';
let value = $state('Svelte');
let clears = $state(0);
const options = [{ value: 'Svelte' }, { value: 'TypeScript' }];
</script>
<style>
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
}
</style>
{#snippet clearIcon()}<span aria-hidden="true">×</span>{/snippet}
<AutoComplete
{value}
options={(options)}
allowClear={{ clearIcon, label: ("Clear suggestion") }}
aria-label={("Own cleaning AutoComplete")}
onChange={next => { value = next ?? ''; }}
onClear={() => { clears += 1; }}
/>
<output
aria-label={("AutoComplete cleaning result")}
>{("Cleared: ")}{clears}{("; meaning: ")}{(value || '—')}</output>
Suffix and clearing
suffix shows a search icon or loading state; allowClear sets the clear icon and accessible name.
<script lang="ts">
import { AutoComplete, Checkbox, type SelectSuffixInfo } from '@woodger/antd';
const options = [{ value: 'Svelte' }, { value: 'TypeScript' }, { value: 'CSS' }];
let loading = $state(false);
</script>
<style>
.example {
display: grid;
gap: 16px;
}
svg {
display: block;
width: 1em;
height: 1em;
}
</style>
{#snippet searchIcon()}
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" aria-hidden="true">
<circle cx="6.5" cy="6.5" r="4.5" /><path d="m10 10 4 4" />
</svg>
{/snippet}
<div class="example">
<Checkbox bind:checked={loading}>{("Show loading")}</Checkbox>
<AutoComplete
{options}
{loading}
allowClear={{ clearIcon: '×', label: ("Clear technology search") }}
showSearch={{ filterOption: true }}
suffix={(info: SelectSuffixInfo) => info.loading ? '…' : searchIcon}
aria-label={("Technology search with an icon")}
/>
</div>
Keyboard and backfill
Shooters skip unavailable options. backfill shows the preliminary text, Enter accepts it, Escape cancels the preliminary selection.
<script lang="ts">
import { AutoComplete, Checkbox } from '@woodger/antd';
let value = $state('');
let backfill = $state(true);
const options = [{ value: 'Amsterdam' }, { value: 'Berlin', disabled: true }, {
value: 'Copenhagen'
}];
</script>
<style>
.example {
display: grid;
gap: 20px;
}
output { color: var(--ant-color-text-secondary); }
</style>
<div class="example">
<Checkbox
bind:checked={backfill}
>{("AutoComplete Prefill")}</Checkbox>
<AutoComplete {value} options={(options)} {backfill} aria-label={("Keyboard AutoComplete")}
onChange={next => { value = next ?? ''; }} placeholder={("Enter text then use arrows")} />
<output
aria-label={("Accepted AutoComplete value")}
>{("Accepted: ")}{(value || '—')}</output>
</div>
Free input into Form
Check required field, send and reset. You can select a city or enter it yourself; matching with options is not necessary.
<script lang="ts">
import { AutoComplete, Button, Form, FormItem, createForm } from '@woodger/antd';
let result = $state('');
const form = createForm({
initialValues: { city: '' },
rules: ({ city: [{ required: true, message: "Enter city." }] })
});
const options = [{ value: "Moscow" }, { value: "St. Petersburg" }, { value: "Kazan" }];
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
output {
display: block;
margin-top: 16px;
color: var(--ant-color-success);
overflow-wrap: anywhere;
}
</style>
<Form {form} onFinish={values => { result = values.city; }}>
<FormItem name="city" label={("City")} help={("You can choose a hint or write your city.")}>
<AutoComplete options={(options)} value={form.values.city} showSearch={{
filterOption: true
}} allowClear
onChange={next => { form.setFieldValue('city', next ?? ''); result = ''; }}
aria-label={("City for application")} />
</FormItem>
<div class="actions">
<Button type="primary" htmlType="submit">{("Send request")}</Button>
<Button
htmlType="reset"
onclick={() => { result = ''; }}
>{("Reset request")}</Button>
</div>
</Form>
{#if result}
<output aria-label={("AutoComplete application result")}>{("City: ")}{result}</output>
{/if}
Container and empty result
getPopupContainer puts the list into a local container, classNames.popup.root specifies its class. notFoundContent shows a message when the filter did not find any hints.
<script lang="ts">
import { AutoComplete } from '@woodger/antd';
const options = [{ value: 'Apple' }, { value: 'Banana' }, { value: 'Pear' }];
</script>
<style>
.host {
position: relative;
padding: 16px;
border: 1px solid var(--ant-color-border-secondary);
border-radius: 8px;
}
:global(.auto-complete-example-popup) {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
</style>
<div class="host">
<AutoComplete
options={(options)}
showSearch={{ filterOption: true }}
listHeight={120}
aria-label={("Local list AutoComplete")}
classNames={{ popup: { root: 'auto-complete-example-popup' } }}
getPopupContainer={trigger => trigger.parentElement ?? trigger}
notFoundContent={("There are no hints for this text")}
placeholder={("Enter Apple or other text")}
/>
</div>
Custom editors
components.input connects a native input and textarea. showAction opens the first list on focus, and maxLength limits typing to five characters.
<script lang="ts">
import { AutoComplete, type SelectInputContext } from '@woodger/antd';
const options = [{ value: 'Alpha' }, { value: 'Beta' }];
</script>
{#snippet inputEditor({ attributes, register }: SelectInputContext)}
<input {...attributes} {@attach register} />
{/snippet}
{#snippet textareaEditor({ attributes, register }: SelectInputContext<HTMLTextAreaElement>)}
{@const { value, ...rest } = attributes}
<textarea {...rest} {value} rows={3} {@attach register}></textarea>
{/snippet}
<div class="example">
<AutoComplete
{options}
components={{ input: inputEditor }}
showAction={['focus']}
maxLength={5}
allowClear
aria-label={("Single-line editor")}
/>
<AutoComplete
{options}
components={{ input: textareaEditor }}
maxLength={5}
allowClear
aria-label={("Multiline editor")}
/>
</div>
<style>
.example {
display: grid;
gap: 16px;
max-width: 320px;
}
</style>
Long suggestion list
Groups, ConfigProvider.virtual, scrolling by key and onActive through AutoCompleteRef.
<script lang="ts">
import { tick } from 'svelte';
import {
AutoComplete,
Button,
Checkbox,
ConfigProvider,
type AutoCompleteRef
} from '@woodger/antd';
const options = ['component', 'theme', 'document'].map(group => ({
label: group,
options: Array.from({ length: 100 }, (_, index) => ({
key: `${group}-${index}`,
value: `${group}-${index}`
}))
}));
let control = $state<AutoCompleteRef>();
let value = $state('');
let active = $state<string | null>(null);
let opened = $state(false);
let virtual = $state(true);
let scrollTop = $state(0);
async function showLastSuggestion() {
opened = true;
await tick();
control?.scrollTo({ key: 'document-99', align: 'bottom' });
control?.focus();
}
</script>
<style>
.example {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
output + output { margin-block-start: 8px; }
output {
display: block;
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<div class="actions">
<Checkbox bind:checked={virtual}>ConfigProvider.virtual</Checkbox>
<Button onclick={showLastSuggestion}>{("Go to last suggestion")}</Button>
</div>
<ConfigProvider {virtual}>
<AutoComplete
{options}
{value}
bind:this={control}
open={opened}
onOpenChange={next => { opened = next; }}
listHeight={192}
listItemHeight={32}
showScrollBar="optional"
onChange={next => { value = next ?? ''; }}
onActive={next => { active = next; }}
onPopupScroll={event => { scrollTop = event.currentTarget.scrollTop; }}
aria-label={("Virtual AutoComplete suggestions")}
placeholder={("Enter text or open the list")}
style="width:100%"
/>
</ConfigProvider>
<div>
<output aria-label={("Active suggestion")}>
{active ?? '—'}
</output>
<output aria-label={("Suggestion scroll position")}>
{Math.round(scrollTop)} px
</output>
</div>
</div>
Suggestion content
optionRender changes option content; labelRender preserves the editor string.
<script lang="ts">
import { AutoComplete, type SelectFlattenOption } from '@woodger/antd';
interface Suggestion {
value?: string;
label: string;
detail?: string;
options?: Suggestion[];
}
const Completion = AutoComplete<Suggestion>;
const options: Suggestion[] = [{
label: "Components",
options: [
{ value: 'button', label: 'Button', detail: "User action" },
{ value: 'input', label: 'Input', detail: "Text input" }
]
}];
let value = $state('button');
</script>
<style>
.option {
display: grid;
gap: 2px;
}
small { color: var(--ant-color-text-secondary); }
output {
display: block;
margin-top: 12px;
overflow-wrap: anywhere;
}
</style>
{#snippet optionContent(option: SelectFlattenOption<string, Suggestion>, info: { index: number })}
<span class="option" data-render-index={info.index}>
<strong>{option.data.label}</strong>
<small>{(option.data.detail ?? '')}</small>
</span>
{/snippet}
{#snippet selectedLabel()}<strong data-completion-label>Button</strong>{/snippet}
<Completion
options={(options)}
{value}
optionRender={optionContent}
labelRender={info => info.value === 'button' ? selectedLabel : undefined}
onChange={next => { value = next ?? ''; }}
showSearch={{ filterOption: true }}
defaultActiveFirstOption
allowClear
aria-label={("AutoComplete with custom suggestions")}
/>
<output aria-label={("AutoComplete custom suggestion value")}>{value || '—'}</output>
Custom suggestion popup
popupRender adds an explanation alongside the original menu.
<script lang="ts">
import type { Snippet } from 'svelte';
import { AutoComplete, Divider } from '@woodger/antd';
const options = [{ value: 'button' }, { value: 'input' }, { value: 'select' }];
let value = $state('');
</script>
<style>
.hint {
display: block;
padding: 4px 8px;
color: var(--ant-color-text-secondary);
}
output {
display: block;
margin-top: 12px;
overflow-wrap: anywhere;
}
</style>
{#snippet popupContent(origin: Snippet)}
{@render origin()}
<Divider style="margin: 8px 0;" />
<small class="hint">{("Choose a suggestion or continue typing.")}</small>
{/snippet}
<AutoComplete
{options}
{value}
popupRender={() => popupContent}
onChange={next => { value = next ?? ''; }}
aria-label={("AutoComplete with a custom popup")}
/>
<output aria-label={("AutoComplete custom popup value")}>
{value || '—'}
</output>
Styling AutoComplete parts
Prefix and semantic styles inherit ConfigProvider.select; typing remains unrestricted.
<script lang="ts">
import { AutoComplete, Checkbox, ConfigProvider } from '@woodger/antd';
const options = [{ value: 'button' }, { value: 'input' }];
let value = $state('');
let warning = $state(false);
</script>
<style>
.example {
display: grid;
gap: 16px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<Checkbox bind:checked={warning}>{("Warning status")}</Checkbox>
<ConfigProvider select={{
showSearch: false,
classNames: { root: 'shared-completion' },
styles: { root: { borderRadius: 12 } }
}}>
<AutoComplete
{options}
{value}
prefix={("Component")}
status={warning ? 'warning' : undefined}
rootClassName="component-completion"
classNames={({ props }) => ({ root: props.status === 'warning' ? 'completion-warning' : '' })}
styles={{
prefix: { color: 'var(--ant-color-text-secondary)' },
popup: { listItem: { paddingInline: 16 } }
}}
onChange={next => { value = next ?? ''; }}
allowClear
aria-label={("AutoComplete with semantic styles")}
/>
</ConfigProvider>
<output aria-label={("Styled AutoComplete value")}>{value || '—'}</output>
</div>
AutoComplete uses namespace Select; prefixCls specifies the full prefix of this control and popup. The nested Input/TextArea chooses its prefix independently. Free input and carriage are preserved.
CSS prefixes AutoComplete
Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.
<script lang="ts">
import { Checkbox, ConfigProvider, AutoComplete } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-auto-complete' : '');
let value = $state('');
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("General prefix AutoComplete suite")}</Checkbox>
<Checkbox bind:checked={local}>{("AutoComplete local prefix")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'auto-complete-theme' } }}>
<div class="prefix-stage">
<AutoComplete prefixCls={localPrefix} {value} onChange={next => value = next ?? ''}
aria-label={("AutoComplete with prefix")} style="width:100%" options={([
{ value: 'Svelte' }, { value: 'TypeScript' }
])} />
<output aria-label={("AutoComplete input with prefix")}>{(value || '—')}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS prefix AutoComplete")}
>{("General: ")}{prefix}{("; local: ")}{(localPrefix
|| ("from the provider"))}</output>
<p>
{("AutoComplete uses namespace Select; prefixCls specifies the full prefix of this control and popup. The nested Input/TextArea chooses its prefix independently. Free input and carriage are preserved.")}
</p>
</div>
Coverage Examples
Ten themes mapped to AutoComplete's live page on ant.design. Additional cards show backfill, Form and local container. Inaccessible parts of the API are clearly marked.
| Theme | Condition | Example and limitations |
|---|---|---|
| Basic Usage | Implemented | Local and controlled state, search and selection. |
| Customized | Implemented | Address hints from the review. |
| Customize Input Component | Implemented | TextArea via Svelte snippet, attributes and register. |
| Non-case-sensitive AutoComplete | Implemented | Custom filter. |
| Lookup-Patterns — Certain Category | Implemented | Groups and labels with snippets. |
| Lookup-Patterns — Uncertain Category | Implemented | Hints on request from demo source. |
| Status | Implemented | Error and warning. |
| Variants | Implemented | Four design options. |
| Customize clear button | Partially | clearIcon and label are supported; disabled and tabIndex on the clear object are not available yet. |
| Custom semantic dom styling | Implemented | classNames/styles support objects and functions, including ConfigProvider.select. |
API
The main parameters are checked against the public AutoCompleteProps, AutoCompleteOption and AutoCompleteInput of the @woodger/antd package.
| Property | Description | Type | Default |
|---|---|---|---|
showAction | The focus value opens the list when the editor receives focus. | readonly ("focus" | "click")[] | — |
virtual | Enables list windowing; ConfigProvider.virtual applies without a local prop. | boolean | ConfigProvider / true |
listHeight | Maximum inner viewport height in px; 0 removes the limit. | number | 256 |
listItemHeight | Estimated row height before measurement; 0 disables windowing. | number | token.controlHeight |
showScrollBar | Optional displays the scrollbar during scrolling and hides it after 3 seconds. | boolean | 'optional' | optional |
onActive | Reports the active suggestion or null; does not replace onChange or onSelect. | (value: string | null) => void | — |
prefixCls | Full prefix Select control and popup; without a local value, the general prefix + -select is used. Nested Input/TextArea is independent. | string | ConfigProvider.prefixCls + "-select" |
classNames | Classes for root/prefix/input/placeholder/content/clear and popup.root/list/listItem. | AutoCompleteClassNames | ((info: AutoCompleteSemanticInfo) => AutoCompleteClassNames) | undefined |
styles | Styles for control and popup parts, including CSS objects and shared Select settings. | AutoCompleteStyles | ((info: AutoCompleteSemanticInfo) => AutoCompleteStyles) | undefined |
popupRender | A pure function receives the original menu; it also runs during SSR and while closed. | SelectPopupRender | undefined |
prefix | Content before the editor. Falsy scalars, including 0, create no element. | RenderEmptyContent | undefined |
suffix | Trailing area, including replacement of Form feedback. A pure function receives state; searchValue contains the main string without temporary backfill. | SelectRenderNode<SelectSuffixInfo> | undefined |
loading | Pending state for the suffix. The application manages requests and icon content. | boolean | undefined |
menuItemSelectedIcon | A pure suggestion-icon function receives value and disabled; isSelected is always false. | SelectRenderNode<SelectMenuItemIconInfo<string>> | From context |
components | components.input replaces the editor and components.root replaces the whole field. Forward attributes and register to the native element. | SelectComponents<RootElement, EditorElement> | undefined |
nativeElement | The root div or the registered components.root element after mount. | RootElement | HTMLDivElement | undefined | undefined |
inputElement | bind:inputElement returns the registered editor after mount. | EditorElement | HTMLInputElement | HTMLTextAreaElement | undefined | undefined |
rootClassName | A shared class for the AutoComplete root and popup. | string | undefined |
style | A CSS object or string styles the same AutoComplete root. | SelectStyle | undefined |
optionRender | Option content. The absolute index includes groups and the virtual window. | Snippet<[SelectFlattenOption<string, OptionType>, { index: number }]> | undefined |
labelRender | A pure display function; the editor retains the raw value string. | (info: SelectLabelRenderInfo<string>) => RenderEmptyContent | undefined |
value | Arbitrary string; no matching with options is required. Control via onChange, without bind:value. | string | undefined |
defaultValue | Initial local value. Native reset restores it. | string | undefined |
options | Source records and groups; AutoCompleteItem by default. The input model remains a string. | readonly OptionType[] | [] |
fieldNames | Source field names for the value, label, children, and group heading. | SelectFieldNames | value / label / options; groupLabel = label |
maxLength | Maximum input length. A custom editor receives it in attributes. | number | — |
showSearch | An object configures onSearch/filterOption. Even false preserves free input. | boolean | AutoCompleteSearchConfig<OptionType> | ConfigProvider.select / true |
onChange | Input and selection. Cleanup might pass undefined, then an empty string; for the string model use next ?? empty string. | (value: string | undefined, option: Partial<OptionType> | undefined) => void | — |
onSelect | Selection and repeated selection of a suggestion; the second argument preserves source fields. | (value: string, option: OptionType) => void | — |
backfill | Pre-fills the field when moving through the list. The model changes after confirmation. | boolean | false |
defaultActiveFirstOption | Initial activity of the first option; default false is different from true on ant.design. If the text is non-empty, the package will also fire the first match at the beginning of value. | boolean | false |
allowClear | The object sets clearIcon and label. onClear reports clearing separately. This setting is local and is not inherited from ConfigProvider.select. | boolean | SelectAllowClear | false |
open | Controlled visibility. Without options and notFoundContent the list is hidden. defaultOpen sets the initial visibility. | boolean | Local state |
onOpenChange | Request to change visibility. With managed open, update the model from the outside. | (open: boolean) => void | — |
notFoundContent | Contents of the empty result. Non-empty content allows the list to be shown without options. | string | number | Snippet | null | undefined |
popupMatchSelectWidth | true uses the control width, false fits the content, and a number sets the width in px. The control width remains the minimum; undefined inherits ConfigProvider. false disables virtualization. | boolean | number | ConfigProvider / true |
getPopupContainer | The local container takes precedence over the global setting; without a getter, the native placement of the popup is preserved. | (trigger: HTMLElement) => HTMLElement | ShadowRoot | From ConfigProvider |
size | large, medium or small; inherits from SpaceCompact and ConfigProvider. | ComponentSize | From context |
variant | Local variant → closest Form.variant → ConfigProvider.select.variant → general ConfigProvider.variant → outlined. | outlined | filled | borderless | underlined | outlined |
status | Check status. disabled and readonly preserve native input restrictions. | error | warning | From FormItem |
children | Own control must apply attributes and register input/textarea via register with clearing when unmounted. | Snippet<[AutoCompleteInput]> | Native input |
showSearch
| Property | Description | Type | Default |
|---|---|---|---|
showSearch.filterOption | Filtering is disabled by default. true searches by value, case insensitive; the function also receives groups. | boolean | ((text, option) => boolean) | false |
showSearch.onSearch | Preparing input prompts. Selecting an option is not a new search query. | (text: string) => void | — |
Options and groups
valuelabelkeydisabledtitleclassstyleA group uses label, key, and options by default; fieldNames specifies other field names. label can be a snippet, while value remains a string. Keyboard navigation skips groups and disabled options.
Native id, name, disabled, readonly and ARIA are passed to the input. popupRender, classNames and styles support custom popup styling. Clearing accepts a boolean or an object with clearIcon and label. The disabled field from React AllowClearConfig is not supported.
Methods
bind:this provides AutoCompleteRef with focus, blur and scrollTo methods.
bind:inputElement returns the registered editor after mount.
bind:nativeElement returns the root div or the registered components.root.
| Method | Type | Application |
|---|---|---|
focus | (options?: FocusOptions) => void | Focuses the editor. |
blur | () => void | Blurs the editor. |
scrollTo | (config?: SelectScrollConfig | null) => void | Scrolls the list by index, key or top/left position. |
Long suggestion list demonstrates scrolling by key and the onActive event.
<script lang="ts">
import { AutoComplete, Button, type AutoCompleteRef } from '@woodger/antd';
let control = $state<AutoCompleteRef>();
</script>
<style>
.example {
display: grid;
gap: 20px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
</style>
<div class="example">
<AutoComplete
bind:this={control}
options={([{ value: 'Svelte' }])}
aria-label={("AutoComplete Methods")}
/>
<div class="actions">
<Button onclick={() => control?.focus()}>{("Focus AutoComplete")}</Button>
<Button onclick={() => control?.blur()}>{("Remove Focus AutoComplete")}</Button>
</div>
</div>
Semantic DOM
classNames and styles accept an object or a pure function. Shared values come from ConfigProvider.select; suffix and tag slots are absent in AutoComplete. Styling AutoComplete parts.
root / prefix / input / placeholder / content / clear /
popup.root / popup.list / popup.listItem
The field has the role of combobox and is connected to the list via aria-controls and aria-activedescendant. Arrows move the active option, Enter and Tab confirm it, Escape closes the list and cancels the backfill.
Registration tokens
AutoComplete uses Select theme: customize ConfigProvider.theme.components.Select. The tables of 24 component and 62 common tokens match on the Select and AutoComplete live pages. Multiple tokens belong to the general Select; AutoComplete works with one line.
Local example sets a light green palette along with the text color to remain readable in both site themes.
<script lang="ts">
import { AutoComplete, ConfigProvider } from '@woodger/antd';
</script>
<ConfigProvider theme={{
cssVar: {},
token: {
colorText: '#135200',
colorTextPlaceholder: '#466125',
colorBgElevated: '#fff'
},
components: {
Select: {
selectorBg: '#f6ffed',
optionActiveBg: '#f6ffed',
optionSelectedBg: '#d9f7be',
optionHeight: 36,
activeBorderColor: '#389e0d'
}
}
}}>
<AutoComplete options={([{ value: 'Svelte' }, { value: 'TypeScript' }])}
aria-label={("Custom AutoComplete theme")} placeholder={("Topic via Select tokens")} />
</ConfigProvider>
| Token | Purpose |
|---|---|
activeBorderColor | Frame color when focused. |
activeOutlineColor | Focus outline color. |
clearBg | Clean button background. |
hoverBorderColor | Hover frame. |
multipleItemBg | Background of the selected tag. |
multipleItemBorderColor | Frame of the selected tag. |
multipleItemBorderColorDisabled | Frame of an inaccessible tag. |
multipleItemColorDisabled | Text of an inaccessible tag. |
multipleItemHeight | Normal tag height. |
multipleItemHeightLG | Large tag height. |
multipleItemHeightSM | Small tag height. |
multipleSelectorBgDisabled | Background of inaccessible multiple Select. |
optionActiveBg | Background of the active variant. |
optionFontSize | Option text size. |
optionHeight | Height option. |
optionLineHeight | Variant row height. |
optionPadding | Option indents. |
optionSelectedBg | Background of the selected option. |
optionSelectedColor | Text of the selected option. |
optionSelectedFontWeight | Text thickness of the selected option. |
selectorBg | Field background. |
showArrowPaddingInlineEnd | Place for arrow. |
singleItemHeightLG | Height of a large single value. |
zIndexPopup | List layer. |
Common tokens of the current topic
The values are read through theme.useToken() and react to the settings in the header.
| Token | Purpose | Current value |
|---|---|---|
colorBgContainer | Background of a regular field. | #ffffff |
colorBgContainerDisabled | Background of the inaccessible icon. | rgba(0,0,0,0.04) |
colorBgElevated | Dropdown background. | #ffffff |
colorBorder | Frame color. | #d9d9d9 |
colorBorderDisabled | Frame of an inaccessible element. | #d9d9d9 |
colorError | Primary color of the error. | #ff4d4f |
colorErrorAffix | Color of additions when there is an error. | #ff4d4f |
colorErrorBg | Error background. | #fff2f0 |
colorErrorBgHover | Hover error background. | #fff1f0 |
colorErrorBorderHover | Hover error frame. | #ffa39e |
colorErrorOutline | Error circuit. | rgba(255,38,5,0.06) |
colorErrorText | Error text. | #ff4d4f |
colorFillQuaternary | Weak filling. | rgba(0,0,0,0.02) |
colorFillSecondary | Secondary filling. | rgba(0,0,0,0.06) |
colorFillTertiary | Tertiary fill. | rgba(0,0,0,0.04) |
colorIcon | Icon color. | rgba(0,0,0,0.45) |
colorIconHover | Color of icons when hovering. | rgba(0,0,0,0.88) |
colorPrimary | Primary color of interactive states. | #2f54eb |
colorPrimaryBorder | Light outline of the main color. | #adc6ff |
colorSplit | Separator color. | rgba(5,5,5,0.06) |
colorText | Label color. | rgba(0,0,0,0.88) |
colorTextDescription | Description color. | rgba(0,0,0,0.45) |
colorTextDisabled | Color of unavailable label. | rgba(0,0,0,0.25) |
colorTextPlaceholder | Input prompt color. | rgba(0,0,0,0.25) |
colorTextQuaternary | Secondary text color. | rgba(0,0,0,0.25) |
colorWarning | Primary warning color. | #faad14 |
colorWarningAffix | Color warning additions. | #faad14 |
colorWarningBg | Warning background. | #fffbe6 |
colorWarningBgHover | Hover alert background. | #fff1b8 |
colorWarningHover | Hover alert color. | #ffd666 |
colorWarningOutline | Warning circuit. | rgba(255,215,5,0.1) |
borderRadius | Normal rounding. | 6 |
borderRadiusLG | Large rounding. | 8 |
borderRadiusSM | Icon rounding. | 4 |
borderRadiusXS | Minimum rounding. | 2 |
boxShadowSecondary | Drop-down shadow. |
0 6px 16px 0 rgba(0,0,0,0.08),
0 3px 6px -4px rgba(0,0,0,0.12),
0 9px 28px 8px rgba(0,0,0,0.05)
|
controlHeight | Normal field height. | 32 |
controlHeightLG | Large field height. | 40 |
controlHeightSM | Height of the small field. | 24 |
controlItemBgActiveHover | Background of the selected item when hovering. | #d6e4ff |
controlOutlineWidth | Thickness of the element outline. | 2 |
controlPaddingHorizontal | Horizontal padding of the element. | 12 |
fontFamily | Font family. | -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji' |
fontSize | Basic text size. | 14 |
fontSizeIcon | Icon size. | 12 |
fontSizeLG | Large text size. | 16 |
fontSizeSM | Small text size. | 12 |
lineHeight | Label line height. | 1.5714285714285714 |
lineHeightLG | Large line height. | 1.5 |
lineType | Frame line type. | solid |
lineWidth | Frame thickness. | 1 |
marginXS | Small external indent. | 8 |
motionDurationMid | Duration of main transitions. | 0.2s |
motionDurationSlow | Duration of slow transitions. | 0.3s |
motionEaseInOut | Smooth transition curve. | cubic-bezier(0.645, 0.045, 0.355, 1) |
motionEaseInOutCirc | Transition curve. | cubic-bezier(0.78, 0.14, 0.15, 0.86) |
motionEaseInQuint | Transition acceleration curve. | cubic-bezier(0.755, 0.05, 0.855, 0.06) |
motionEaseOutCirc | Transition deceleration curve. | cubic-bezier(0.08, 0.82, 0.17, 1) |
motionEaseOutQuint | Transition deceleration curve. | cubic-bezier(0.23, 1, 0.32, 1) |
paddingSM | Small internal indent. | 12 |
paddingXS | Indentation of the label from the icon. | 8 |
paddingXXS | Minimum internal space. | 4 |
FAQ
How is AutoComplete different from Select?
AutoComplete saves free text and offers hints. Select selects known values. The options string is not required to match in example Form either.
Why does the model need to be updated via onChange?
The showSearch.onSearch handler prepares hints, but does not cover option selection. Store value via onChange, including input from the IME; use onSelect to react separately to the confirmed option.
Why doesn't open=true show an empty list?
The current package needs options or a non-empty notFoundContent. Without both, the list is hidden, but free input remains available. Local list displays a message when the filter result is empty.
Why doesn't Enter always select the first option?
The defaultActiveFirstOption property in the package is false by default. The input may activate an option with a suitable starting value; You can use the arrows to select another one. Check the backlight, not the supposed first element. backfill remains provisional text until confirmed.
How to connect your TextArea?
Use attributes and register from AutoCompleteInput. The real textarea is passed to register, and the registration is cleared upon unmount. Example preserves the default keyboard and focus via a public TextArea element.