Mentions
Mentions of participants and topics within the text with hints at the carriage.
When to use
Mentions adds mentions of members, teams, or topics within the text. After the prefix, the list at the carriage opens; the selection replaces the current fragment while preserving the surrounding text. For a hint that replaces the value of an entire field, use AutoComplete.
Set label to give a suggestion visible text. If the label is omitted or null, a supplied value gives the option an accessible name for screen readers, but the row is visually empty. The basic example shows each participant’s name and role in the list and inserts their username into the text. Give the field an accessible name and tell users which prefixes they can type.
CSS prefixes Mentions show global ConfigProvider.prefixCls and local prefixCls without resetting state. CSS prefixCls does not change the text trigger prefix="@". Editor, mirror and popup use the allowed namespace; the caret, selection, and native form are preserved.
Text and events
Mentions model - entire textarea row. The managed value is passed via value and updated via onChange; bind:value is not available in the current API. defaultValue specifies the initial local text.
| Problem | Setting | Example |
|---|---|---|
| Edit text with mention | value, onChange, options |
Basic mentions |
| Select options for the current prefix | onSearch(text, prefix) |
Various prefixes |
| Download options | options, loading |
Asynchronous hints |
| Check and extract mentions | getMentions(text, config) |
Validation in Form |
The onChange handler reports the complete new text. The onSearch handler receives only the search fragment and the found prefix, and onSelect receives the selected option and prefix. Don't replace the model with the value of one option from onSelect. Clearing with allowClear removes the entire line, not just the last occurrence.
With focus in the editor, the Up and Down arrow keys move between suggestions, Enter inserts the active option, and Escape closes the list. With focus on an option, Enter or Space selects it. Escape closes the list, returns focus to the editor and restores the previous text selection. The caret stays in the text after insertion. If you set the selection on the textarea, selectionStart and selectionEnd use UTF-16 offsets. The basic example preserves the text on either side of the replaced fragment.
When suggestions are closed and no IME composition is in progress, Enter calls onPressEnter, then onKeyDown and onkeydown. With suggestions open, silent blocks selection with Enter in the editor. During IME composition, Enter leaves the list open. Hydration preserves focus and selection when the textarea text matches its initial value.
Prefixes and search
By default, prefix is @, split is a space. prefix can be an array; onSearch reports which prefix is found. Pass the same prefix and split to the field and getMentions, otherwise insertion and subsequent parsing will work according to different rules. split is a literal string, not a regular expression.
The filterOption property takes a function from the request and option or false to disable local filtering. validateSearch separately determines whether tooltips can be shown for the current fragment. For external searches, the application updates options, shows loading, and undoes previous work or discards an outdated answer. Asynchronous example uses a local timer and clears it on new request, reset and unmount.
When value is omitted or set to undefined, the default filter treats it as an empty string. The option appears for an empty query. Selecting it inserts the prefix and the split separator. The fields passed to onSelect distinguish an omitted value, an explicit undefined and an empty string.
Give options distinct key values when their values repeat or are omitted. Keys are compared as strings. If keys match, a click selects the first item with that key in the displayed list. If that item is disabled, the list stays open. Enter in the editor selects by position in the original search results.
placement specifies the top or bottom position of the list. The local getPopupContainer is called without a required argument and does not inherit from ConfigProvider.getPopupContainer: it is a separate Mentions contract.
In the custom popup example, the popupRender snippet receives menu and info. The current search results are available in info.options. During loading, this contains one disabled option with a spinner. The CSS classes for the list and its items use info.prefixCls. Once the popup is positioned and its enter animation finishes, info.opened becomes true. Passing opened: false to the menu keeps the list visible and turns off automatic scrolling to the active option.
Use direction to choose which edge of the prefix anchors the list. Set dir for the text direction. Use transitionName to apply a CSS transition when the list appears.
Extraction, form and design
The getMentions function returns elements with prefix and value, but does not check for the presence of a member in options. The verification of existence, access rights, and valid destinations belongs to the application. Extract example uses several prefixes and its own delimiter.
In Form, pass value from the model and update it via onChange. Test example requires at least two mentions and a non-empty description; the model retains the original rows. The extracted participants array can be prepared separately before sending.
The autoSize property adjusts the height of the textarea and accepts minRows/maxRows. The readonly property preserves focus and readability, and the disabled property disables the field. These states are shown in reading example. Size, variant, status and design tokens for Mentions style the field without changing the string.
Enable count.show to display the length. count.max sets a soft limit, while maxLength caps native input. The default count uses UTF-16 code units. Use count.strategy for a different measure. To trim excess input, supply count.exceedFormatter. During IME input, formatting waits until composition ends. onCompositionStart and onCompositionEnd receive the native events.
Set variant, allowClear, class, style, classNames and styles through ConfigProvider.mentions. A local allowClear={false} disables the inherited clear button. In the counter example, the field inherits clearing and applies its own styles to the list and textarea. Semantic DOM lists the available slots. The allowClear object supports clearIcon and disabled. The label and tabIndex options from Ant Design 6.7 are not yet available in the Svelte package.
Examples
Mentions:
Basic mentions
Example from the review: search after @, selection at the carriage, extraction of mentions and external reset. The model is reused.
<script lang="ts">
import { Mentions, Button, getMentions } from '@woodger/antd';
let value = $state('');
const options = [
{ value: 'alice', label: "Alice - development" },
{ value: 'bob', label: "Bob - design" },
{ value: 'team', label: "The whole team" }
];
</script>
<div style="max-width:500px">
<Mentions
aria-label={("Text with mentions")}
placeholder={("Enter @ to select participant")}
{value}
options={(options)}
autoSize={{ minRows: 2, maxRows: 5 }}
allowClear
onChange={next => { value = next; }}
/>
<p>{("Mentions: ")}<output
aria-label={("Selected Mentions")}
>{(getMentions(value).map(item => item.value).join(', ') || '—')}</output></p>
<Button onclick={() => { value = ''; }}>{("Reset mentions")}</Button>
</div>
Dimensions
large, medium and small. Without local size, the field inherits its size from the context.
<script lang="ts">
import { Mentions } from '@woodger/antd';
const options = ['alice', 'bob'].map(value => ({ value, label: value }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">
<Mentions options={(options)} size="large" aria-label={("Size Mentions large")} placeholder={("Large size @")} />
<Mentions options={(options)} size="medium" aria-label={("Size Mentions medium")} placeholder={("Medium size @")} />
<Mentions options={(options)} size="small" aria-label={("Mentions size small")} placeholder={("Small size @")} />
</div>
Design options
outlined, filled, borderless and underlined with the same text and tooltips model.
<script lang="ts">
import { Mentions, type MentionsProps } from '@woodger/antd';
const variants =
[
'outlined',
'filled',
'borderless',
'underlined'
] as const satisfies readonly MentionsProps['variant'][];
const options = ['alice', 'bob'].map(value => ({ value, label: value }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">{#each variants as variant (variant)}
<Mentions {variant} options={(options)} aria-label={("Option Mentions " + String((variant)) + "")} placeholder={("" + String((variant)) + " · @")} />
{/each}</div>
Asynchronous hints
Demo source responds after 300 ms. New search string, reset and unmount undo previous work; loading blocks selection until options are received.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Button, Mentions, type MentionsOption } from '@woodger/antd';
let value = $state('');
let query = $state('');
let loading = $state(false);
let options = $state<MentionsOption[]>([]);
const users = ['alice', 'alex', 'bob', 'support'];
let timer: ReturnType<typeof setTimeout> | undefined;
let sequence = 0;
function cancel() {
sequence += 1;
if (timer !== undefined) clearTimeout(timer);
timer = undefined;
}
function search(text: string) {
cancel();
query = text;
options = [];
loading = Boolean(text);
if (!text) {
return;
}
const current = sequence;
timer = setTimeout(() => {
if (current !== sequence) {
return;
}
options = users.filter(user => user.includes(text.toLowerCase())).map(user => ({
value: user, label: user
}));
loading = false;
timer = undefined;
}, 300);
}
function reset() {
cancel();
value = '';
query = '';
options = [];
loading = false;
}
onDestroy(cancel);
</script>
<style>
.example {
display: grid;
justify-items: start;
gap: 16px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<Mentions
{value}
options={(options)}
{loading}
filterOption={false}
onSearch={search}
onChange={next => { value = next; }}
aria-label={("Search for Mentions members")}
placeholder={("Enter @a or @b")}
notFoundContent={("No matches")}
/>
<output aria-label={("Mentions Search Status")}>{("Request: ")}{(query
|| '—')}; {(loading ? "loading" : `found: ${options.length}`)}</output>
<Button onclick={reset}>{("Reset search for participants")}</Button>
</div>
Validation in Form
getMentions checks for at least two mentions; description is required. Full lines are saved in the Form, submit and reset work together.
<script lang="ts">
import { Button, Form, FormItem, Mentions, createForm, getMentions } from '@woodger/antd';
let result = $state('');
const form = createForm({
initialValues: { reviewers: '', bio: '' },
rules: ({
reviewers: [{ validator: value => getMentions(String(value ?? '')).length >= 2
? undefined
: "Please provide at least two references." }],
bio: [{ required: true, message: "Enter a description." }]
})
});
const options = ['alice', 'bob', 'team'].map(value => ({ value, label: value }));
</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 = ("Participants: " + String((getMentions(values.reviewers).map(
item => item.value
).join(', '))) + ". Description: " + String((values.bio)) + "");
}}>
<FormItem name="reviewers" label={("Members")} help={("At least two mentions with the @ prefix.")}>
<Mentions options={(options)} value={form.values.reviewers} aria-label={("Participants for verification")}
onChange={next => { form.setFieldValue('reviewers', next); result = ''; }} />
</FormItem>
<FormItem name="bio" label={("Description")}>
<Mentions
options={(options)}
rows={3}
value={form.values.bio}
aria-label={("Participant Description")}
onChange={next => { form.setFieldValue('bio', next); result = ''; }}
/>
</FormItem>
<div class="actions">
<Button type="primary" htmlType="submit">{("Save mentions")}</Button>
<Button htmlType="reset" onclick={() => { result = ''; }}>
{("Reset Mentions form")}
</Button>
</div>
</Form>
{#if result}<output aria-label={("Mentions form result")}>{result}</output>{/if}
Various prefixes
@ suggests participants, # - topics. The second argument to onSearch specifies a set of options; onSelect reports the selected prefix.
<script lang="ts">
import { Mentions } from '@woodger/antd';
let value = $state('');
let prefix = $state('@');
let selected = $state('');
const options = $derived(
(
prefix === '#'
? ['svelte', 'typescript']
: ['alice', 'bob']
).map(value => ({ value, label: value }))
);
</script>
<style>
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<Mentions
{value}
options={(options)}
prefix={['@', '#']}
aria-label={("Prefixes Mentions")}
placeholder={("@ - participants, # - topics")}
onChange={next => { value = next; }}
onSearch={(_, next) => { prefix = next; }}
onSelect={(option, token) => { selected = token + (option.value ?? ''); }}
/>
<output
aria-label={("Result of Mentions prefixes")}
>{("Search: ")}{prefix}{("; selected: ")}{(selected || '—')}</output>
Inaccessible field and reading
disabled blocks control, readonly preserves focus and the ability to copy text. Hints and changes are locked in both cases.
<script lang="ts">
import { Mentions } from '@woodger/antd';
const options = ['alice', 'bob'].map(value => ({ value, label: value }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">
<Mentions options={(options)} disabled defaultValue="@alice" aria-label={("Unavailable Mentions")} />
<Mentions options={(options)} readonly defaultValue="@bob" aria-label={("Mentions read only")} />
</div>
Prompt position
placement specifies the preferred position of top or bottom relative to the caret reference.
<script lang="ts">
import { Mentions } from '@woodger/antd';
const options = ['alice', 'bob'].map(value => ({ value, label: value }));
</script>
<style>
.example {
display: grid;
gap: 24px;
}
</style>
<div class="example">
<Mentions options={(options)} placement="top" aria-label={("Mentions tips from above")} placeholder={("Top · enter @")} />
<Mentions options={(options)} placement="bottom" aria-label={("Mentions below")} placeholder={("Bottom · enter @")} />
</div>
Your own popup
Type @ and start entering a handle. The heading shows how many options match, and each name shows the handle it inserts. The option without a value inserts the prefix and a space.
<script lang="ts">
import { Divider, Mentions, type MentionsPopupMenu, type MentionsPopupRenderInfo } from '@woodger/antd';
const options = [
{ value: 'alice', label: 'Alice' },
{ value: 'bob', label: 'Bob' },
{ value: 'team', label: teamLabel },
{ key: 'prefix-only', label: "Insert @ and a space" }
];
</script>
<style>
.header {
padding: 8px 12px;
color: var(--ant-color-text-secondary);
font-weight: 600;
}
</style>
{#snippet teamLabel()}<strong>{("The whole team")}</strong>{/snippet}
{#snippet popup(menu: MentionsPopupMenu, info: MentionsPopupRenderInfo)}
{@const menuOptions = info.options.map(option => option.value
? { ...option, label: [option.label, ` (@${option.value})`] }
: option)}
<div class="header">{("Mention suggestions")} ({info.options.length})</div>
<Divider style="margin:4px 0" />
{@render menu({ options: menuOptions })}
{/snippet}
<Mentions options={(options)} popupRender={popup} aria-label={("Own menu Mentions")} placeholder={("Enter @ for menu with title")} />
Text clearing
A regular icon, its own snippet and a multi-line field use one line. allowClear.disabled only blocks the fourth field clear button.
<script lang="ts">
import { Mentions } from '@woodger/antd';
let value = $state(("Hello, @alice"));
const options = ['alice', 'bob'].map(value => ({ value, label: value }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
{#snippet clearIcon()}<span aria-hidden="true">×</span>{/snippet}
<div class="example">
<Mentions {value} options={(options)} allowClear onChange={next => {
value = next;
}} aria-label={("Normal cleaning Mentions")} />
<Mentions
{value}
options={(options)}
allowClear={{ clearIcon }}
onChange={next => { value = next; }}
aria-label={("Own cleaning Mentions")}
/>
<Mentions {value} options={(options)} rows={3} allowClear onChange={next => {
value = next;
}} aria-label={("Multi-line clearing Mentions")} />
<Mentions options={(options)} defaultValue="Очистка заблокирована" allowClear={{
disabled: true
}} aria-label={("Mentions cleaning disabled")} />
</div>
Automatic height
autoSize limits the field to two to four lines; further text scrolls inside the textarea.
<script lang="ts">
import { Mentions } from '@woodger/antd';
const options = ['alice', 'bob'].map(value => ({ value, label: value }));
</script>
<Mentions
options={(options)}
autoSize={{ minRows: 2, maxRows: 4 }}
aria-label={("Auto Height Mentions")}
placeholder={("From two to four lines. Enter text or @ for mention.")}
/>
Test states
Error and warning; status can also come from FormItem.
<script lang="ts">
import { Mentions } from '@woodger/antd';
const options = ['alice', 'bob'].map(value => ({ value, label: value }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">
<Mentions
options={(options)}
status="error"
defaultValue="@alice"
aria-label={("Error Mentions")}
/>
<Mentions
options={(options)}
status="warning"
defaultValue="@alice"
aria-label={("Warning Mentions")}
/>
</div>
Field styling and character count
The field inherits its clear button from ConfigProvider. The counter shows when you exceed 40 characters. The native maxLength stops input at 80.
<script lang="ts">
import { ConfigProvider, Mentions } from '@woodger/antd';
</script>
<style>
:global(.review-mentions-popup) {
border-inline-start: 3px solid var(--ant-color-primary, #1677ff);
}
</style>
<ConfigProvider mentions={{ allowClear: true, styles: { root: 'border-inline-start-width: 3px' } }}>
<Mentions
aria-label={("Comment with mentions")}
placeholder={("Enter @ to select participant")}
options={[{ value: 'alice', label: 'alice' }, { value: 'bob', label: 'bob' }]}
count={{ show: true, max: 40 }}
maxLength={80}
classNames={{ popup: 'review-mentions-popup' }}
styles={{
textarea: 'min-height: 4em',
suffix: 'align-self: flex-start'
}}
/>
</ConfigProvider>
Component Mentions Theme
Indents and border of the field, width and height of the list. Switching the theme keeps the text, caret, and open tooltips.
<script lang="ts">
import type { Snippet } from 'svelte';
import { Button, ConfigProvider, Mentions } from '@woodger/antd';
let enabled = $state(true);
let value = $state('');
const options = ['alice', 'bob', 'charlie', 'diana', 'emma', 'frank']
.map(value => ({ value, label: value }));
const tokens = {
activeBorderColor: '#d48806',
activeShadow: '0 0 0 2px rgba(212, 136, 6, 0.2)',
paddingBlock: 8,
paddingInline: 14,
controlItemWidth: 180,
dropdownHeight: 120,
zIndexPopup: 1300
};
</script>
<style>
.settings {
padding: 8px 12px;
border-bottom: 1px solid var(--ant-color-border-secondary);
}
</style>
{#snippet popup(menu: Snippet)}
<div class="settings">
<Button
aria-pressed={enabled}
onmousedown={event => event.preventDefault()}
onclick={() => { enabled = !enabled; }}
>{("\n Own theme Mentions\n ")}</Button>
</div>
{@render menu()}
{/snippet}
<ConfigProvider theme={{ components: { Mentions: enabled ? tokens : {} } }}>
<Mentions {value} options={(options)} rows={2} allowClear
onChange={next => { value = next; }} popupRender={popup} popupClassName="mentions-theme-popup"
placeholder={("Enter @ for list of participants")} aria-label={("Mentions Theme")} />
</ConfigProvider>
Prefixes @ and # · space separator
Prefix # · separator |
Retrieval via getMentions
The function returns prefix/value pairs. Parsing options are consistent with the field: several prefixes and a literal delimiter |.
<script lang="ts">
import { Mentions, getMentions } from '@woodger/antd';
let standard = $state('@alice #svelte @bob');
let separated = $state('#svelte|#typescript|');
const options = ['alice', 'bob', 'svelte', 'typescript'].map(value => ({ value, label: value }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
p {
margin: 0 0 12px;
color: var(--ant-color-text-secondary);
}
output {
display: block;
margin-top: 12px;
color: var(--ant-color-text-secondary);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
<div class="example">
<div><p>{("Prefixes @ and # · space separator")}</p>
<Mentions
options={(options)}
value={standard}
prefix={['@', '#']}
aria-label={("Mention extraction")}
onChange={next => { standard = next; }}
/>
<output aria-label={("Mentions with different prefixes")}>{JSON.stringify(
getMentions(
standard,
{ prefix: ['@', '#'] }
)
)}</output>
</div>
<div><p>{("Prefix # · separator |")}</p>
<Mentions
options={(options)}
value={separated}
prefix="#"
split="|"
aria-label={("Mentions separated by separator")}
onChange={next => { separated = next; }}
/>
<output aria-label={("Mentions separated by a vertical bar")}>{JSON.stringify(
getMentions(
separated,
{ prefix: '#', split: '|' }
)
)}</output>
</div>
</div>
CSS prefixCls does not change the text trigger prefix="@". Editor, mirror and popup use the allowed namespace; the caret, selection, and native form are preserved.
CSS prefixes Mentions
Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.
<script lang="ts">
import { Checkbox, ConfigProvider, Mentions } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-mentions' : '');
let value = $state(("Hello, @"));
</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 Mentions suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Local prefix Mentions")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'mentions-theme' } }}>
<div class="prefix-stage">
<Mentions prefixCls={localPrefix} {value} onChange={next => value = next}
prefix="@" options={([{ value: 'woodger', label: 'woodger' }, {
value: 'svelte',
label: 'svelte'
}])}
aria-label={("Mentions with prefix")} style="width:100%" />
<output aria-label={("Text Mentions with prefix")}>{value}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS prefix Mentions")}
>{("General: ")}{prefix}{("; local: ")}{(localPrefix
|| ("from the provider"))}</output>
<p>
{("CSS prefixCls does not change the text trigger prefix=\"@\". Editor, mirror and popup use the allowed namespace; the caret, selection, and native form are preserved.")}
</p>
</div>
Coverage Examples
Each topic links to a working Svelte example. A separate example uses getMentions and split to parse text.
| Theme | Condition | Example and limitations |
|---|---|---|
| Basic | Implemented | Managed string, caret selection and mention retrieval. |
| Size | Implemented | Three field sizes. |
| Variants | Implemented | Four design options. |
| Asynchronous loading | Implemented | Local source, loading and cancellation of outdated search. |
| With Form | Implemented | getMentions check, required field, submit and reset. |
| Customize Trigger Token | Implemented | Sets options for @ and #. |
| disabled or readOnly | Implemented | The Svelte attributes disabled and readonly are used. |
| Placement | Implemented | Hints above and below. |
| Customize Popup | Implemented | Match count in the heading and custom labels in the standard list. |
| With clear icon | Implemented | Normal and its own icon, several lines and disabled cleaning. |
| autoSize | Implemented | Growth and contraction within minRows/maxRows. |
| Status | Implemented | Error and warning. |
| Custom semantic dom styling | Implemented | Use classNames and styles to customize the textarea, suggestion list and clear button area. |
API
The main parameters are checked against the public MentionsProps, MentionsOption and MentionsConfig of the @woodger/antd package.
| Property | Description | Type | Default |
|---|---|---|---|
prefixCls | Full CSS prefix of the component and its parts. A non-empty local prop takes precedence; empty string and undefined inherit ConfigProvider. The namespace of the topic is set separately. | string | ConfigProvider.prefixCls + "-mentions" |
value | Full text. Controlled via onChange; bind:value is not supported in the current Mentions. | string | undefined |
defaultValue | Initial local value. | string | Empty string |
options | label sets the visible content and accepts text, a number, a snippet or an array of these. The optional value is used for search and insertion. | readonly MentionsOption[] | [] |
prefix | One or more search triggers. onSearch and onSelect report the prefix found. | string | readonly string[] | @ |
split | Literal separator when inserting. Use the same split when parsing via getMentions. | string | Space |
filterOption | The value false disables the local filter for external searches. label itself does not participate in the filter. | false | ((text, option: MentionsOption) => boolean) | By value case insensitive |
validateSearch | Determines the validity of the current search fragment; false hides tooltips. | (text: string, split?: string) => boolean | The text does not contain split |
loading | Shows a loading indicator in place of the options. By default, pressing Enter during loading keeps the list open. | boolean | false |
notFoundContent | Contents of empty result; null removes the text. | string | number | Snippet | null | From locale.emptyText |
placement | Preferred position relative to the current mention. | top | bottom | bottom |
silent | Disables selection with Enter in the editor while suggestions are open. | boolean | loading |
popupRender | The snippet receives menu and info. Call menu() to render the standard list. Each call can override options, prefixCls and opened. The content is recreated each time the popup opens. | MentionsPopupRender | Standard menu |
getPopupContainer | Local container without a required trigger argument. The generic ConfigProvider.getPopupContainer is not used. | () => HTMLElement | ShadowRoot | Native placement |
direction | Chooses the edge of the prefix that anchors the suggestions. Use dir for text direction. | 'ltr' | 'rtl' | ConfigProvider.direction |
transitionName | CSS transition name for showing the list. An empty string disables the named transition. | string | — |
autoFocus | Focuses the field when it appears. An explicit autofocus attribute takes precedence. | boolean | false |
autoSize | Changes the height of the textarea according to the content; minRows/maxRows set the boundaries. | boolean | { minRows?: number; maxRows?: number } | false |
count | show displays the counter, strategy sets the counting method and max marks overflow. Use exceedFormatter to trim excess input. | InputCountConfig | — |
maxLength | Native input limit in UTF-16 code units. Takes precedence over maxlength. | number | — |
allowClear | Clears the full text. Pass false locally to disable an inherited clear button. The object accepts clearIcon and disabled. | boolean | InputAllowClear | ConfigProvider.mentions.allowClear / false |
size | large, medium or small. The size is inherited from SpaceCompact and ConfigProvider. | ComponentSize | From context |
variant | Local variant → nearest Form.variant → ConfigProvider.mentions.variant → shared ConfigProvider.variant → outlined. | outlined | filled | borderless | underlined | outlined |
status | Check status. The error is reflected in aria-invalid. | error | warning | success | validating | From FormItem |
classNames | Classes for the root, textarea, popup and suffix slots. Accepts a map or a function of { props }. | MentionsSemantic | — |
styles | CSS declarations for the same slots. Local styles extend the settings from ConfigProvider.mentions. | MentionsSemantic | — |
onChange | Gets the entire row on input, insertion, and clearing. | (text: string) => void | — |
onSearch | Gets the fragment after the prefix at the carriage; you can change options or start downloading. | (text: string, prefix: string) => void | — |
onSelect | Receives the selected option’s fields and the prefix after insertion. If the option omitted value, the callback receives no value field. | (option: MentionsOption, prefix: string) => void | — |
onPressEnter | With the list closed, this runs before onKeyDown and the native onkeydown handler. | (event: KeyboardEvent) => void | — |
onResize | The size of the textarea when its geometry changes. onPopupScroll reports that the list is scrolling. | (size: { width: number; height: number }) => void | — |
Hint options
valuelabelkeydisabledclassstyleThe default filter searches value without case sensitivity. If label is omitted or null, the option has no visible text. A supplied value provides its accessible name.
Native id, name, rows, disabled, readonly and ARIA are transferred to textarea. Use the Svelte readonly attribute for read mode. A disabled field inherits the state of the Form and ConfigProvider.
Enabled allowClear clears the entire line and passes an empty string to onChange. The object option allows you to replace the icon and separately disable cleaning via disabled.
Methods and getMentions
Via bind:this available focus(options?: FocusOptions) and blur(). bind:nativeElement returns root div; the native field after mount is accessible via nativeElement.querySelector('textarea').
<script lang="ts">
import { Button, Mentions } from '@woodger/antd';
let control = $state<ReturnType<typeof Mentions>>();
</script>
<style>
.example {
display: grid;
gap: 20px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
</style>
<div class="example">
<Mentions
bind:this={control}
options={([{ value: 'alice', label: 'alice' }])}
aria-label={("Methods Mentions")}
style="border-color:#389e0d"
placeholder={("Local frame via style")}
/>
<div class="actions">
<Button onclick={() => control?.focus()}>{("Focus Mentions")}</Button>
<Button onclick={() => control?.blur()}>{("Remove Focus Mentions")}</Button>
</div>
</div>
Mention extraction
getMentions(value, { prefix, split }) is imported separately from @woodger/antd and returns a MentionsEntity array with prefix and value. By default, prefix is @, split is space. split is a literal string, not a regular expression.
The function does not check the presence of a participant in options. Parsing example uses the same parameters as the field. Form checks the number of mentions while preserving the original text.
Semantic DOM
The root, textarea, popup and suffix slots target the wrapper, field, suggestion list and clear button area. classNames and styles accept a map or a function of { props } with the resolved disabled and status values.
Each call to menu() creates a list with its own IDs. On the combobox, aria-controls lists the IDs of the mounted lists, and aria-activedescendant points to the option in the first mounted list that has an item at the active index.
Insert preserves the rest of the text and returns caret focus after the mention. Don't recreate control every time you enter it; update the row via onChange.
Registration tokens
The 20 component tokens correspond to the Mentions table on ant.design and are listed in the ComponentTokenMap. theme.components.Mentions specifies the design of the field and the individual popup, including padding, border, list dimensions and layer. Switching the theme keeps the text, caret, and active tooltip; local style takes precedence.
| Token | Purpose |
|---|---|
activeBg | Active field background. |
activeBorderColor | Frame when focusing. |
activeShadow | Focus shadow. |
addonBg | Background of the additional area. |
controlItemWidth | Minimum width of the tooltip option. |
dropdownHeight | Height of the tooltip list. |
errorActiveShadow | Focus shadow on error. |
hoverBg | Background when hovering. |
hoverBorderColor | Hover frame. |
inputFontSize | Average field text size. |
inputFontSizeLG | Large field text size. |
inputFontSizeSM | Small field text size. |
paddingBlock | Regular vertical margins. |
paddingBlockLG | Vertical indents of a large field. |
paddingBlockSM | Small margin vertical indents. |
paddingInline | Normal horizontal padding. |
paddingInlineLG | Horizontal indents of a large field. |
paddingInlineSM | Small margin horizontal indents. |
warningActiveShadow | Focus shadow when warning. |
zIndexPopup | List layer. |
Common tokens of the current topic
45 common tokens from the Mentions table are read through theme.useToken() and respond to settings in the header.
| Token | Purpose | Current value |
|---|---|---|
colorBgContainer | Field background. | #ffffff |
colorBgContainerDisabled | Background of an inaccessible field. | rgba(0,0,0,0.04) |
colorBgElevated | Pop-up list background. | #ffffff |
colorBorder | Frame color. | #d9d9d9 |
colorBorderDisabled | Inaccessible field frame. | #d9d9d9 |
colorError | Primary color of the error. | #ff4d4f |
colorErrorAffix | Color of an additional element in case of an error. | #ff4d4f |
colorErrorBg | Error background. | #fff2f0 |
colorErrorBgHover | Hover error background. | #fff1f0 |
colorErrorBorderHover | Hover error frame. | #ffa39e |
colorErrorText | Error text. | #ff4d4f |
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) |
colorText | Primary text color. | rgba(0,0,0,0.88) |
colorTextDisabled | Inaccessible text. | rgba(0,0,0,0.25) |
colorTextPlaceholder | Field hint color. | rgba(0,0,0,0.25) |
colorTextQuaternary | Color of secondary icons. | rgba(0,0,0,0.25) |
colorWarning | Primary warning color. | #faad14 |
colorWarningAffix | Additional element for warning. | #faad14 |
colorWarningBg | Warning background. | #fffbe6 |
colorWarningBgHover | Hover alert background. | #fff1b8 |
colorWarningBorderHover | Hover warning frame. | #ffd666 |
colorWarningText | Warning text. | #faad14 |
borderRadius | Normal rounding. | 6 |
borderRadiusLG | Large rounding. | 8 |
borderRadiusSM | Small rounding. | 4 |
boxShadowSecondary | Pop-up list 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 | Small field height. | 24 |
controlItemBgHover | Variant background on hover. | rgba(0,0,0,0.04) |
controlPaddingHorizontal | Horizontal margin padding. | 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 |
fontWeightStrong | Thickness of the selected text. | 600 |
lineHeight | Normal line height. | 1.5714285714285714 |
lineHeightLG | Line height of the large field. | 1.5 |
lineType | Frame line type. | solid |
lineWidth | Frame line thickness. | 1 |
marginXS | Small external indent. | 8 |
motionDurationMid | Duration of main transitions. | 0.2s |
motionDurationSlow | Duration of slow transitions. | 0.3s |
paddingXXS | Minimum internal space. | 4 |
FAQ
Why is the entire string stored and not an array of participants?
Mentions edits the text along with mentions. Use getMentions to validate or prepare a submission, storing the string as a field model.
How to coordinate several prefixes and your own separator?
Pass the same prefix and split to the field and getMentions. onSearch reports the current prefix so that the application selects the desired set of options. Parsing example shows the literal delimiter.
How to download variants securely?
Update options from onSearch, show loading and check the relevance of the answer. Cancel timers or queries on line changes and unmount as in local example.
How to add a title to a list?
Render the heading before calling menu(). The popup example shows the number of matches in the heading. It calls menu({ options }) to add handles to the labels and keeps the same order and values. If you change the order or values, a click selects from the displayed list, while Enter in the editor selects from the original search results.
Why is getPopupContainer different from AutoComplete?
Mentions accepts a local getter without a required argument and does not inherit ConfigProvider.getPopupContainer. The container refers to the carriage tooltips; use a component specific contract.