Chat composer mentions
A recipe, not a package namespace. Build the card with Field, Button and Attachment, show the suggestions with Popover and OptionList, and give one people source to useMentions and to MentionText. The card frame is this page, not a package part. Type @ for suggestions, rest the caret in @Mina Park for its peek, and send to see the mention in the sent message.
On this page
import {
Attachment,
Avatar,
Button,
Field,
Message,
MentionText,
OptionList,
Popover,
Stack,
Text,
VisuallyHidden,
defineMentionSource,
useMentions,
usePopover,
type MentionDraft,
type MentionToken,
type UseMentionsResult,
} from '@tounsoo/todae';
import { ArrowUp, FileText, Image } from 'lucide-react';
import { useEffect, useId, useState, type FormEvent, type KeyboardEvent } from 'react';
type Person = { name: string; initials: string; role: string; place: string };
// Stands in for the product's directory. A real `resolve` fetches, and passes the signal on.
const DIRECTORY: Record<string, Person> = {
mina: { name: 'Mina Park', initials: 'MP', role: 'Design systems', place: 'Seoul' },
minjun: { name: 'Min-jun Choi', initials: 'MC', role: 'Engineering', place: 'Seoul' },
mira: { name: 'Mira Seo', initials: 'MS', role: 'Design', place: 'Busan' },
};
// One source feeds the suggestions, the caret peek in the composer and the mention in a sent message.
const people = defineMentionSource<Person>({
char: '@',
label: 'People',
options: Object.entries(DIRECTORY).map(([value, person]) => ({ value, label: person.name })),
resolve: (id) => DIRECTORY[id],
peekLabel: (person) => person.name,
renderPeek: (person, peek) => (
<Stack.Root gap="condensed">
<Stack.Root direction="row" align="center">
<Avatar.Root>
<Avatar.Fallback>{person.initials}</Avatar.Fallback>
</Avatar.Root>
<div>
<Text.Root weight="medium">{person.name}</Text.Root>
<Text.Root tone="muted">
{person.role} · {peek.mode === 'caret' ? 'Active now' : person.place}
</Text.Root>
</div>
</Stack.Root>
{peek.mode === 'interactive' ? (
<Button.Root variant="secondary" onClick={peek.close}>
Close
</Button.Root>
) : null}
</Stack.Root>
),
});
const SOURCES = [people];
/** The token the caret rests in. A boundary belongs to the token that ends there. */
function tokenAt(tokens: readonly MentionToken[], caret: number | null): MentionToken | null {
return caret === null ? null : (tokens.find((token) => caret > token.start && caret <= token.end) ?? null);
}
/**
* The peek while the caret rests in a mention. `useMentions` puts `caretPeekAnchorName` on that
* token; this finds who it names, looks them up, and opens a peek that never takes focus.
*/
function useCaretPeek(mentions: UseMentionsResult) {
const [caret, setCaret] = useState<number | null>(null);
const [focused, setFocused] = useState(false);
const [dismissed, setDismissed] = useState<string | null>(null);
const [found, setFound] = useState<{ id: string; person: Person | undefined } | null>(null);
const descriptionId = useId();
const token = mentions.open ? null : tokenAt(mentions.value.tokens, caret);
const key = token ? `${token.start}:${token.value}` : null;
// A peek closed with Escape or an outside press stays closed until the caret moves to another mention.
if (dismissed !== null && dismissed !== key) setDismissed(null);
const id = token?.value ?? null;
const person = found && found.id === id ? found.person : undefined;
const { textareaRef } = mentions;
useEffect(() => {
const field = textareaRef.current;
if (!field) return;
const sync = () => setCaret(field.selectionStart === field.selectionEnd ? field.selectionStart : null);
sync();
const events = ['selectionchange', 'keyup', 'pointerup'] as const;
for (const type of events) field.addEventListener(type, sync);
return () => {
for (const type of events) field.removeEventListener(type, sync);
};
}, [textareaRef]);
useEffect(() => {
if (id === null) return;
const controller = new AbortController();
// A promise around the call also catches a `resolve` that throws before it returns.
new Promise<Person | undefined>((done) => done(people.resolve?.(id, controller.signal))).then(
(person) => {
if (!controller.signal.aborted) setFound({ id, person });
},
() => {
if (!controller.signal.aborted) setFound({ id, person: undefined });
},
);
return () => controller.abort();
}, [id]);
const open = focused && key !== null && person !== undefined && dismissed !== key;
// What the peek last showed. It keeps it while it fades out, after the caret has left the mention.
const [shown, setShown] = useState<{ key: string; id: string; person: Person } | null>(null);
if (open && token && key !== null && person && (shown?.key !== key || shown.person !== person)) {
setShown({ key, id: token.value, person });
}
const popover = usePopover({
open,
anchorName: mentions.caretPeekAnchorName,
onOpenChange: (next) => {
if (!next) setDismissed(key);
},
});
const wire = popover.getPopoverProps();
return {
textareaProps: {
// The peek is inert, and browsers leave inert text out of a description, so the field
// is described by a visually hidden copy of what the peek says.
'aria-describedby': open ? descriptionId : undefined,
onFocus: () => setFocused(true),
onBlur: () => setFocused(false),
onPointerDown: () => setDismissed(null),
},
peek: (
<>
<Popover.Root {...wire} inert>
{shown && people.renderPeek
? people.renderPeek(shown.person, { id: shown.id, mode: 'caret', close: () => setDismissed(shown.key) })
: null}
</Popover.Root>
{open && person ? (
<VisuallyHidden.Root id={descriptionId}>
{person.name}, {person.role}, active now
</VisuallyHidden.Root>
) : null}
</>
),
};
}
const SHIP = 'Shipping the Acid fix. @Mina Park can you sanity check the dark track?';
const AT = SHIP.indexOf('@Mina Park');
const START: MentionDraft = {
text: SHIP,
tokens: [{ char: '@', value: 'mina', text: '@Mina Park', start: AT, end: AT + '@Mina Park'.length }],
};
const EMPTY: MentionDraft = { text: '', tokens: [] };
type Upload = { name: string; size: string; kind: 'image' | 'document' };
type Sent = MentionDraft & { id: number };
// Enter sends and Shift+Enter starts a new line. Enter that ends an IME composition only commits it.
function sendOnEnter(event: KeyboardEvent<HTMLFormElement>) {
if (event.key !== 'Enter' || event.shiftKey || event.defaultPrevented) return;
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (!(event.target instanceof HTMLTextAreaElement)) return;
event.preventDefault();
event.currentTarget.requestSubmit();
}
export default function ChatComposer() {
const [draft, setDraft] = useState(START);
const [files, setFiles] = useState<Upload[]>([
{ name: 'peek-card.png', size: '248 KB', kind: 'image' },
{ name: 'm8-contrast.pdf', size: '1.2 MB', kind: 'document' },
]);
const [sent, setSent] = useState<Sent[]>([]);
const mentions = useMentions({ triggers: SOURCES, value: draft, onValueChange: setDraft });
const caretPeek = useCaretPeek(mentions);
const send = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (mentions.value.text.trim() === '') return;
setSent((all) => [...all, { id: all.length, ...mentions.value }]);
setDraft(EMPTY);
setFiles([]);
// Sending from the Send button disables it, so keep focus in the field.
mentions.textareaRef.current?.focus();
};
const remove = (file: Upload) => {
// The list goes with its last file, so focus moves to the field.
if (files.length === 1) mentions.textareaRef.current?.focus();
setFiles((all) => all.filter((other) => other !== file));
};
return (
<Stack.Root gap="normal" style={{ inlineSize: '100%', maxInlineSize: '36rem' }}>
{sent.map((message) => (
<Message.Root key={message.id} from="user" aria-label="You">
<Message.Content>
<MentionText value={message} sources={SOURCES} />
</Message.Content>
</Message.Root>
))}
<form onSubmit={send} onKeyDown={sendOnEnter}>
<Field.Root aria-label="Message">
{files.length > 0 ? (
<Field.Row>
<Stack.Root as="ul" direction="row" gap="condensed" wrap aria-label="Attached files">
{files.map((file) => (
<li key={file.name}>
<Attachment.Root>
<Attachment.Preview>{file.kind === 'image' ? <Image aria-hidden /> : <FileText aria-hidden />}</Attachment.Preview>
<Attachment.Name>{file.name}</Attachment.Name>
<Attachment.Meta>{file.size}</Attachment.Meta>
<Attachment.Remove onClick={() => remove(file)} />
</Attachment.Root>
</li>
))}
</Stack.Root>
</Field.Row>
) : null}
<Field.Textarea
{...mentions.getTextareaProps({ ...caretPeek.textareaProps, spellCheck: false })}
autoGrow
maxRows={6}
placeholder="Message, or type @ to mention"
/>
<Field.Row>
<Field.Affix style={{ marginInlineStart: 'auto' }}>Enter to send</Field.Affix>
<Button.Root type="submit" variant="primary" aria-label="Send" disabled={draft.text.trim() === ''}>
<Button.Icon>
<ArrowUp />
</Button.Icon>
</Button.Root>
</Field.Row>
</Field.Root>
</form>
<Popover.Root {...mentions.getPopoverProps()}>
{/* Hidden, not unmounted, when nothing matches, so the field's aria-controls still points at it. */}
<OptionList.Root {...mentions.getListboxProps()} hidden={mentions.isEmpty}>
{mentions.items.map((item) => (
<OptionList.Option key={item.id} {...mentions.getOptionProps(item)} />
))}
</OptionList.Root>
<Text.Root as="span" role="status" tone="muted">
{mentions.isEmpty ? 'No one matches' : ''}
</Text.Root>
</Popover.Root>
{caretPeek.peek}
</Stack.Root>
);
}
Caret peek
While the list is closed and the caret rests in a mention, useMentions returns caretPeekAnchorName, the anchor name it puts on that mention. Pass it to usePopover as anchorName and fill the popover with the source's renderPeek in caret mode. Make that popover inert, since it never takes focus and the caret stays in the field. Browsers leave inert text out of a description, so while the peek is open, describe the textarea with a VisuallyHidden copy of what it says. The hook doesn't say which mention the caret is in, so the recipe reads the textarea's selection, looks the mention up with resolve, and aborts the lookup when the caret moves on.
Accessible composition
Todae handles: getTextareaProps() sets aria-autocomplete and aria-haspopup, and while the list is open, aria-controls and aria-activedescendant, which point at the ids that getListboxProps() and getOptionProps() give the list and its options. It runs ArrowDown, ArrowUp, Enter, Tab and Escape in the list. OptionList renders the role="listbox" and role="option" rows, and Popover closes on Escape and on an outside press. A mention in a sent message is a button or a link with its peek, from MentionText.
You supply: A name for the field, here aria-label="Message" on Field.Root, or a Label. The Popover.Root with OptionList.Root {...getListboxProps()} and an OptionList.Option {...getOptionProps(item)} for each item, so the ids the textarea points at exist. A visually hidden copy of the caret peek's text in the textarea's aria-describedby while the peek is open, since its own text is inert. Text in a role="status" element when no option matches, with the list hidden rather than unmounted. A name for the icon-only send button. Enter that sends, but not while an IME composition is open, and Shift+Enter for a new line. A label on the list of attached files. Focus back in the field after a send and after the last attachment is removed, since the Send button turns disabled and the list goes away.
Watch for: A list built from your own role="listbox" and role="option" elements, whose ids drift from the ones the textarea points at. Toolbar buttons named only by a symbol, such as "+" or "/", or that do nothing. Your own onFocus or onBlur after the getter's spread, which replaces the hook's handlers: pass them to getTextareaProps() instead, as the recipe does.
When to use
A chat box where someone types @ to mention a person, and the sent message shows that mention with the same peek.
When not to use
A suggestion list that does not become a token → Combobox.