Ant Design Svelte

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.

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.

Dimensions

large, medium and small. Without local size, the field inherits its size from the context.

Design options

outlined, filled, borderless and underlined with the same text and tooltips model.

Request: —; found: 0

Asynchronous hints

Demo source responds after 300 ms. New search string, reset and unmount undo previous work; loading blocks selection until options are received.

At least two mentions with the @ prefix.

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.

Search: @; selected: —

Various prefixes

@ suggests participants, # - topics. The second argument to onSearch specifies a set of options; onSelect reports the selected prefix.

Inaccessible field and reading

disabled blocks control, readonly preserves focus and the ability to copy text. Hints and changes are locked in both cases.

Prompt position

placement specifies the preferred position of top or bottom relative to the caret reference.

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.

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.

Automatic height

autoSize limits the field to two to four lines; further text scrolls inside the textarea.

Test states

Error and warning; status can also come from FormItem.

0 / 40

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.

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.

Prefixes @ and # · space separator

[{"prefix":"@","value":"alice"},{"prefix":"#","value":"svelte"},{"prefix":"@","value":"bob"}]

Prefix # · separator |

[{"prefix":"#","value":"svelte"},{"prefix":"#","value":"typescript"}]

Retrieval via getMentions

The function returns prefix/value pairs. Parsing options are consistent with the field: several prefixes and a literal delimiter |.

Hello, @
General: suite; local: project-mentions

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.

Coverage Examples

Each topic links to a working Svelte example. A separate example uses getMentions and split to parse text.

ThemeConditionExample and limitations
BasicImplementedManaged string, caret selection and mention retrieval.
SizeImplementedThree field sizes.
VariantsImplementedFour design options.
Asynchronous loadingImplementedLocal source, loading and cancellation of outdated search.
With FormImplementedgetMentions check, required field, submit and reset.
Customize Trigger TokenImplementedSets options for @ and #.
disabled or readOnlyImplementedThe Svelte attributes disabled and readonly are used.
PlacementImplementedHints above and below.
Customize PopupImplementedMatch count in the heading and custom labels in the standard list.
With clear iconImplementedNormal and its own icon, several lines and disabled cleaning.
autoSizeImplementedGrowth and contraction within minRows/maxRows.
StatusImplementedError and warning.
Custom semantic dom stylingImplementedUse 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.

Main parameters Mentions
PropertyDescriptionTypeDefault
prefixClsFull 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.stringConfigProvider.prefixCls + "-mentions"
valueFull text. Controlled via onChange; bind:value is not supported in the current Mentions.stringundefined
defaultValueInitial local value.stringEmpty string
optionslabel 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[][]
prefixOne or more search triggers. onSearch and onSelect report the prefix found.string | readonly string[]@
splitLiteral separator when inserting. Use the same split when parsing via getMentions.stringSpace
filterOptionThe 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
validateSearchDetermines the validity of the current search fragment; false hides tooltips.(text: string, split?: string) => booleanThe text does not contain split
loadingShows a loading indicator in place of the options. By default, pressing Enter during loading keeps the list open.booleanfalse
notFoundContentContents of empty result; null removes the text.string | number | Snippet | nullFrom locale.emptyText
placementPreferred position relative to the current mention.top | bottombottom
silentDisables selection with Enter in the editor while suggestions are open.booleanloading
popupRenderThe 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.MentionsPopupRenderStandard menu
getPopupContainerLocal container without a required trigger argument. The generic ConfigProvider.getPopupContainer is not used.() => HTMLElement | ShadowRootNative placement
directionChooses the edge of the prefix that anchors the suggestions. Use dir for text direction.'ltr' | 'rtl'ConfigProvider.direction
transitionNameCSS transition name for showing the list. An empty string disables the named transition.string—
autoFocusFocuses the field when it appears. An explicit autofocus attribute takes precedence.booleanfalse
autoSizeChanges the height of the textarea according to the content; minRows/maxRows set the boundaries.boolean | { minRows?: number; maxRows?: number }false
countshow displays the counter, strategy sets the counting method and max marks overflow. Use exceedFormatter to trim excess input.InputCountConfig—
maxLengthNative input limit in UTF-16 code units. Takes precedence over maxlength.number—
allowClearClears the full text. Pass false locally to disable an inherited clear button. The object accepts clearIcon and disabled.boolean | InputAllowClearConfigProvider.mentions.allowClear / false
sizelarge, medium or small. The size is inherited from SpaceCompact and ConfigProvider.ComponentSizeFrom context
variantLocal variant → nearest Form.variant → ConfigProvider.mentions.variant → shared ConfigProvider.variant → outlined.outlined | filled | borderless | underlinedoutlined
statusCheck status. The error is reflected in aria-invalid.error | warning | success | validatingFrom FormItem
classNamesClasses for the root, textarea, popup and suffix slots. Accepts a map or a function of { props }.MentionsSemantic—
stylesCSS declarations for the same slots. Local styles extend the settings from ConfigProvider.mentions.MentionsSemantic—
onChangeGets the entire row on input, insertion, and clearing.(text: string) => void—
onSearchGets the fragment after the prefix at the carriage; you can change options or start downloading.(text: string, prefix: string) => void—
onSelectReceives 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—
onPressEnterWith the list closed, this runs before onKeyDown and the native onkeydown handler.(event: KeyboardEvent) => void—
onResizeThe size of the textarea when its geometry changes. onPopupScroll reports that the list is scrolling.(size: { width: number; height: number }) => void—

Hint options

valuelabelkeydisabledclassstyle

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

Component Mentions Tokens
TokenPurpose
activeBgActive field background.
activeBorderColorFrame when focusing.
activeShadowFocus shadow.
addonBgBackground of the additional area.
controlItemWidthMinimum width of the tooltip option.
dropdownHeightHeight of the tooltip list.
errorActiveShadowFocus shadow on error.
hoverBgBackground when hovering.
hoverBorderColorHover frame.
inputFontSizeAverage field text size.
inputFontSizeLGLarge field text size.
inputFontSizeSMSmall field text size.
paddingBlockRegular vertical margins.
paddingBlockLGVertical indents of a large field.
paddingBlockSMSmall margin vertical indents.
paddingInlineNormal horizontal padding.
paddingInlineLGHorizontal indents of a large field.
paddingInlineSMSmall margin horizontal indents.
warningActiveShadowFocus shadow when warning.
zIndexPopupList 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.

Common tokens of the current topic
TokenPurposeCurrent value
colorBgContainerField background.#ffffff
colorBgContainerDisabledBackground of an inaccessible field.rgba(0,0,0,0.04)
colorBgElevatedPop-up list background.#ffffff
colorBorderFrame color.#d9d9d9
colorBorderDisabledInaccessible field frame.#d9d9d9
colorErrorPrimary color of the error.#ff4d4f
colorErrorAffixColor of an additional element in case of an error.#ff4d4f
colorErrorBgError background.#fff2f0
colorErrorBgHoverHover error background.#fff1f0
colorErrorBorderHoverHover error frame.#ffa39e
colorErrorTextError text.#ff4d4f
colorFillSecondarySecondary filling.rgba(0,0,0,0.06)
colorFillTertiaryTertiary fill.rgba(0,0,0,0.04)
colorIconIcon color.rgba(0,0,0,0.45)
colorTextPrimary text color.rgba(0,0,0,0.88)
colorTextDisabledInaccessible text.rgba(0,0,0,0.25)
colorTextPlaceholderField hint color.rgba(0,0,0,0.25)
colorTextQuaternaryColor of secondary icons.rgba(0,0,0,0.25)
colorWarningPrimary warning color.#faad14
colorWarningAffixAdditional element for warning.#faad14
colorWarningBgWarning background.#fffbe6
colorWarningBgHoverHover alert background.#fff1b8
colorWarningBorderHoverHover warning frame.#ffd666
colorWarningTextWarning text.#faad14
borderRadiusNormal rounding.6
borderRadiusLGLarge rounding.8
borderRadiusSMSmall rounding.4
boxShadowSecondaryPop-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)
controlHeightNormal field height.32
controlHeightLGLarge field height.40
controlHeightSMSmall field height.24
controlItemBgHoverVariant background on hover.rgba(0,0,0,0.04)
controlPaddingHorizontalHorizontal margin padding.12
fontFamilyFont 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'
fontSizeBasic text size.14
fontSizeIconIcon size.12
fontWeightStrongThickness of the selected text.600
lineHeightNormal line height.1.5714285714285714
lineHeightLGLine height of the large field.1.5
lineTypeFrame line type.solid
lineWidthFrame line thickness.1
marginXSSmall external indent.8
motionDurationMidDuration of main transitions.0.2s
motionDurationSlowDuration of slow transitions.0.3s
paddingXXSMinimum 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.