UI

Mention

A multi-line text input where @ people and

import { MentionInput } from '@uthereal/ui/mention-input'

Mention input playground

Loading interactive preview…

Overview

MentionInput renders a multi-line text field inside the shared field anatomy where trigger characters (@, #, or custom symbols) open a caret-anchored suggestion list. Choosing an item inserts an atomic token such as @Alex Morgan that the caret steps over and one Backspace removes. Without triggers, the field loads sample @ people and # channel lists; pass [] for a plain field.

CapabilityBehavior
Triggers & kindsUp to 4 unique single-character triggers; person shows avatars/initials and accent tokens, channel shows glyphs and counts
Atomic tokensCaret skips inside tokens, selections widen to full tokens, and Backspace or Delete removes one token whole (undo-safe)
Value & markupReports { text, mentions, markup } with @[label](id) markup; hidden <input type="hidden"> submits markup when name is set
Composer & handleOptional submitOnEnter (Shift+Enter adds a line, IME ignored) with onSubmit/submitAction, plus MentionInputHandle
Host suggestionsOverride ranking with filterItems or fetch suggestions dynamically via onQueryChange

Use MentionInput for comments, chat composers, and descriptions that reference people, channels, or records. Use Text for plain single-line or multi-line text, Tags for discrete token lists, and Multiselect for searchable selection from a list.

Usage

'use client'
import { useRef, useState } from 'react'
import {
  MentionInput,
  type MentionInputHandle,
  type MentionInputValue,
} from '@uthereal/ui/mention-input'

const triggers = [
  {
    char: '@',
    label: 'People',
    kind: 'person' as const,
    items: [
      { id: 'alex-morgan', label: 'Alex Morgan', description: 'Design lead' },
      { id: 'jordan-lee', label: 'Jordan Lee', description: 'Engineer' },
    ],
  },
  {
    char: '#',
    label: 'Channels',
    kind: 'channel' as const,
    items: [
      {
        id: 'launch',
        label: 'launch',
        description: 'Release planning',
        count: 14,
      },
      {
        id: 'design',
        label: 'design',
        description: 'Critique and feedback',
        count: 12,
      },
    ],
  },
]

export function CommentComposer() {
  const inputRef = useRef<MentionInputHandle>(null)
  const [draft, setDraft] = useState<MentionInputValue>()

  function handleSubmit(submitted: MentionInputValue) {
    // submitted.markup: "Thanks @[Alex Morgan](alex-morgan)!"
    // submitted.mentions: [{ trigger: '@', id: 'alex-morgan', label: 'Alex Morgan', start: 7, end: 19 }]
    console.log('Send comment:', submitted.markup)
    inputRef.current?.clear()
  }

  return (
    <MentionInput
      ref={inputRef}
      label="Comment"
      name="comment_markup"
      placeholder="Write a comment, @ to mention"
      triggers={triggers}
      submitOnEnter
      submitAction="send_comment"
      onValueChange={setDraft}
      onSubmit={handleSubmit}
      onMentionAdd={(mention) => console.log('Mentioned:', mention.id)}
      onAction={(action) => console.log('Host action:', action, draft?.markup)}
    />
  )
}

Omit value for an uncontrolled field initialized from defaultValue. onValueChange fires in both controlled and uncontrolled modes with { text, mentions, markup }. When name is set, a hidden <input type="hidden"> submits the serialized markup with native HTML forms unless the field is disabled.

Examples

People and channels

Type @ or # at the start of a word to open suggestions at the caret. Matches rank by label prefix, word prefix, label substring, and description substring, with the matched substring highlighted in full ink. person rows render an avatar image or initials and insert accent-tinted tokens; channel rows render an icon (# by default) with an optional member count and insert neutral tokens. The field starts at minRows (1 by default), grows smoothly up to maxRows, and scrolls beyond that limit.

Press Enter to submit, or Shift+Enter for a new line.

Mention mechanics

  • Trigger matching: A trigger opens suggestions at a word boundary (start of text, after whitespace, or after an opening bracket or quote), outside existing mentions, within 48 characters of the caret. Person queries allow up to two words; channel queries allow one word. Neither allows another trigger character.
  • Choosing and empty state: Enter, Tab, or clicking a row inserts the mention plus a trailing space unless whitespace already follows, using browser editing so Ctrl+Z / ⌘Z undoes it. An unmatched single-word query keeps the popup open with emptyLabel (or labels.noPeople / labels.noChannels) and announces labels.noResults; typing a space closes it so normal prose continues.
  • Atomic editing: Arrow keys step over mentions, clicks snap to the nearer edge, range selections expand to whole mentions, and Backspace or Delete adjacent to a mention selects and deletes the whole token. Pasting or editing inside a mention reverts it to plain text.
  • Markup helpers: serializeMentions, parseMentions, and mentionText are exported from @uthereal/ui/mention-input to convert between structured MentionValue objects and @[label](id) storage markup.
  • Host suggestions: Pass filterItems(query, items, trigger) to replace built-in ranking with alias or fuzzy search. Listen to onQueryChange(query | null) to load remote suggestions into triggers.

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
labelstringDefault: "Message"Visible label and accessible name. Name the information asked for, in sentence case.
hideLabelbooleanDefault: falseHide the label visually when the context already names the field. It is still announced.
descriptionstring—Supporting text below the field, announced with it. Use it for format hints and constraints.
errorstring—Validation message from your application. Setting it marks the field invalid; the message is linked to the field and announced politely.
requiredbooleanDefault: falseMarks the field as required for assistive technology and shows an indicator. Your application validates the value.
readOnlybooleanDefault: falseThe text can be focused, selected, and copied, but not edited, and no suggestions open. It is still submitted with a form.
disabledbooleanDefault: falseUnavailable and removed from the tab order. A disabled field is not submitted with a form.
namestring—Native form field name, submitted with the value in a form.
placeholderstring—Example text while the field is empty. Never a substitute for the label.
submitOnEnterbooleanDefault: falseEnter submits the field (Shift+Enter still adds a line, and keys pressed during IME composition never submit); off by default, so Enter adds a line. Submitting reports the value through onSubmit and onAction.
submitActionstring—Host action name sent with onAction when Enter submits the field, for chat and composer fields wired to a registered send action.
defaultValuestringDefault: ""Initial text, with mentions written as markup: @[Alex Morgan](alex-morgan). Later argument edits do not reset an existing instance; use value and onValueChange to control it.
triggersMentionInputTrigger[]Default: [{"char":"@","label":"People","kind":"person","items":[{"id":"alex-morgan","label":"Alex Morgan","description":"Design lead"},{"id":"jordan-lee","label":"Jordan Lee","description":"Engineer"},{"id":"sam-patel","label":"Sam Patel","description":"Product manager"},{"id":"riley-chen","label":"Riley Chen","description":"Researcher"},{"id":"taylor-brooks","label":"Taylor Brooks","description":"Writer"}]},{"char":"#","label":"Channels","kind":"channel","items":[{"id":"launch","label":"launch","description":"Release planning","count":14},{"id":"general","label":"general","description":"Team-wide updates","count":48},{"id":"design","label":"design","description":"Critique and feedback","count":12}]}]The characters that start a mention, each with the name of its list, its kind, an optional text shown when nothing matches (otherwise the labels of its kind), and its items (id, label, optional description, icon, avatar image and count), e.g. @ for people and # for channels. A trigger opens suggestions at the start of a word; a person query may run to two words, a channel query to one. person rows show a portrait or initials and their mentions take the accent; channel rows show a glyph (icon, # by default) and their mentions stay neutral. Defaults to a sample @ trigger with five people and a # trigger with three channels; set it to [] for a plain field.
maxSuggestionsintegerDefault: 6Most suggestions shown at once, best matches first.
minRowsintegerDefault: 1Visible lines when empty; one by default, as in Arc. The field springs to its content up to maxRows.
maxRowsintegerDefault: 8Lines before the field scrolls. Never below minRows.
variantoutline | soft | ghostDefault: "outline"Field surface: outline for forms, soft on busy surfaces, ghost for inline editing without a border.
sizesm | md | lgDefault: "md"Text size and padding: matches text inputs of the same size.
placementPlacementDefault: "bottom-start"Preferred side and alignment of the suggestions against the trigger character. They flip and shift to stay in view.
labelsMentionInputLabels—The count announced while suggestions are open ({count} people, 1 person, {count} channels, 1 channel), the announcement when a query matches nothing, and the empty text per kind (No people match “{query}”). Translate them with the rest of your interface.
recipestudio | softDefault: "studio"Visual treatment. Both recipes use the same interaction behavior.
themeMentionInputTheme—Color mode, accent, and semantic tokens. See Theming for all keys and defaults.
motionnone | subtle | expressiveDefault: "subtle"The field height following its text, the suggestions popping in and resizing as matches change, the highlight glide (pointer and keyboard), message copy, hover and focus transitions. none makes them immediate; system reduced motion disables springs and travel while keeping subtle opacity fades.
motionOptionsMentionInputMotionOptions—Suggestion transition (travel and scale; the fade stays 160ms, as in Arc), entrance and exit poses, and the highlight glide (indicator). Durations are milliseconds.
dirltr | rtl—Reading direction. Omit it to inherit the page direction.

React integration

PropPurpose
value, onValueChangeControlled MentionValue ({ text, mentions }). onValueChange fires in both modes with MentionInputValue (including markup).
onMentionAddFires with the inserted Mention whenever a suggestion is chosen and committed into the text.
onSubmitFires with MentionInputValue when Enter submits non-empty text under submitOnEnter.
onActionFires with submitAction when Enter submits non-empty text under submitOnEnter.
filterItemsCustom filter and ranking function (query, items, trigger) => MentionItem[].
onQueryChangeFires with { trigger, start, query } as the active query changes, or null when it closes.
refImperative MentionInputHandle: { focus(), insert(text), openSuggestions(kind), clear(), textarea }.
presetApplication defaults (such as maxSuggestions, size, and translated labels), overridden by explicit props.
tokensCSS custom properties (--ui-*) applied after the typed theme on both the field root and suggestion portal.
renderIcon(name, context)Custom icon renderer; context holds size and slot ('suggestion' or 'channel'). Keep rendered icons decorative.
portalContainerOptional portal mount target, such as an element inside a native modal <dialog> top layer.
className, styleApplied to the root field element, which carries the resolved --ui-* tokens.
Native attributesForwarded to <textarea> (spellCheck, autoComplete, maxLength, aria-*).

MentionInputHandle exposes focus() (focuses the textarea), insert(text) (inserts undo-safe text at the caret), openSuggestions('person' | 'channel') (inserts the first matching trigger character with a leading space if needed and returns false if unavailable), clear() (empties text and mentions), and textarea (underlying <textarea> element). insert, openSuggestions, and clear are no-ops when disabled or readOnly is true.

Keyboard & accessibility

KeyInteraction
Trigger characterAt a word boundary: opens the suggestion list at the caret.
ArrowDown, ArrowUpWith suggestions open: moves the active highlight, wrapping around.
Enter, TabWith matching suggestions open: inserts the active suggestion.
EnterWith submitOnEnter and no matching suggestions open: submits non-empty text (ignored in IME).
Shift+EnterAlways inserts a newline, even when suggestions are open or submitOnEnter is enabled.
Shift+TabMoves focus out of the field.
EscapeDismisses the suggestion list for the current trigger until the query changes.
Backspace, DeleteAdjacent to a mention: removes the whole mention token (undo restores it).

Focus stays in the native <textarea> at all times so standard editing, undo, spellcheck, and IME composition work natively; keys pressed during IME composition (isComposing or keyCode === 229) never select a suggestion or submit. The textarea is labelled via aria-labelledby, described via aria-describedby (description and error), sets aria-required and aria-invalid, and exposes aria-autocomplete="list", aria-controls (when matches exist), and aria-activedescendant pointing to the active role="option" inside the role="listbox" named by the trigger's label.

A pre-mounted role="status" region announces suggestion counts (labels.people, labels.person, labels.channels, labels.channel) and empty results (labels.noResults). Avatars, channel glyphs, and member counts are decorative (aria-hidden="true"). In dir="rtl", caret anchoring, horizontal clamping, and popup transform origins mirror from inline-start. Under forced-colors: active, the textarea paints CanvasText directly, mentions show a CanvasText outline, and the highlighted suggestion uses Highlight and HighlightText.

Motion and theming

  • Field height and edge: The field grows to match its text up to maxRows on the smooth spring; the outline rests on --ui-border and shifts to --ui-border-strong on focus.
  • Suggestions and highlight: The 272px panel (clamped to the field width) opens 6px from the caret line (flipping above when under 300px remains below), popping from 0.96 scale and 4px travel on the snappy spring with a 160ms fade in and a 126ms exit. Panel height springs smoothly as matches filter, and the active highlight glides on motionOptions.indicator.
  • Reduced motion: prefers-reduced-motion: reduce disables height springs, popup travel and scale, and highlight glide while keeping 160ms fade-in and 126ms fade-out on suggestions and 120ms fades on field messages. motion="none" makes every update immediate (0ms).

theme accepts the core, control, and popupList token groups plus borderStrong, accentStrong, and accentSubtle (for person mention tokens). An optional UtherealProvider supplies application-wide defaults.

Composition

MentionInput is a leaf component. Its structured value (text, mentions, and markup) is host state stored at /fields/instance-<id>/value, initialized from defaultValue and reconciled from markup against current triggers across configuration edits. When submitAction is set, the definition collects it for host action registration. See Building with agents.

{
  "type": "MentionInput",
  "props": {
    "label": "Comment",
    "placeholder": "Write a comment, @ to mention",
    "submitOnEnter": true,
    "submitAction": "send_comment",
    "triggers": [
      {
        "char": "@",
        "label": "People",
        "kind": "person",
        "items": [
          {
            "id": "alex-morgan",
            "label": "Alex Morgan",
            "description": "Design lead"
          }
        ]
      }
    ]
  },
  "children": []
}

On this page