Mention
defineMentionSource는 멘션을 한 번 설명합니다. 그 객체를 useMentions에 넘기면 제안에 쓰이고, MentionText에 넘기면 보낸 메시지에 쓰입니다. renderPeek가 피크의 유일한 내용입니다. Todae는 그것을 Popover 안에 그립니다. 이 소스를 쓰고 캐럿이 멘션 안에 있는 동안 피크를 보여 주는 채팅 카드는 채팅 작성창 멘션 레시피입니다.
이 페이지의 내용
const people = defineMentionSource({
char: '@',
options,
resolve: (id, signal) => loadPerson(id, signal),
peekLabel: (person) => person.name,
renderPeek: (person, peek) => (
<button type="button" onClick={peek.close}>
{person.name}
</button>
),
});
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>
);
}
키보드
| 키 | 제안 목록 | 멘션 |
|---|---|---|
| ArrowDown / ArrowUp | 활성 옵션을 옮깁니다 | |
| Enter 또는 Tab | 옵션을 고릅니다. Enter는 보내지 않습니다 | 링크 위에서는 Enter가 그 링크로 이동합니다 |
| Escape | 목록을 닫습니다 | 피크를 닫습니다. 포커스는 멘션에 남습니다 |
| Space | 피크를 열거나 닫습니다 |
Todae에는 자체 캐럿 피크가 없습니다. 캐럿이 토큰 안에 있고 목록이 닫혀 있으면 useMentions가 caretPeekAnchorName을 반환하고, 레시피는 그 자리에 포커스를 받지 않고 텍스트 영역을 설명하는 피크를 엽니다. Escape는 목록을 먼저 닫고, 그다음 그 피크를 닫습니다.
피크
포커스를 받을 수 있는 컨트롤이 있는 피크는 peekLabel 또는 멘션 텍스트로 이름이 붙는 dialog입니다. 텍스트만 있는 피크는 트리거의 설명이고 role이 없습니다. peek.mode는 보낸 멘션에서 interactive입니다. 직접 만드는 캐럿 피크는 레시피처럼 caret을 넘깁니다. 보낸 멘션에서 peek.close()는 피크를 닫고 포커스를 멘션으로 되돌립니다.
호버나 포커스는 피크를 열고 포커스를 그대로 둡니다. 그래서 포인터가 떠나거나 포커스가 옮겨 가면 피크가 닫힙니다. 클릭이나 링크에서의 Space는 피크를 열어 고정하고, dialog 피크 안으로 포커스를 옮기며, 닫힐 때 포커스를 멘션으로 되돌립니다. 피크는 <span>을 렌더링하므로 멘션을 Text.Root 같은 문단 안에 둘 수 있습니다. 피크의 내용은 처음 열릴 때부터 렌더링되고 닫히는 동안에도 남아 있으므로, 카드가 보여 주던 내용과 함께 사라집니다.
쓸 때
보낸 메시지에서 멘션은 실제 버튼이나 링크여야 하고, 작성창 레시피에서 캐럿이 그 멘션 안에 있을 때와 같은 피크를 보여 줍니다.
쓰지 않을 때
멘션이 아닌 제안 목록은 useCombobox입니다. 피크 없는 칠해진 토큰은 useMentions와 Field.Textarea입니다.
Props
| 이름 | 타입 | 설명 |
|---|---|---|
source 필수 | MentionSource | useMentions 트리거에 resolve, renderPeek, peekLabel, href를 더한 값입니다. renderPeek(entity, { id, mode, close })가 피크의 유일한 내용입니다. |
| 이름 | 타입 | 설명 |
|---|---|---|
source 필수 | MentionSource | 이 멘션을 찾고 피크를 그리는 소스입니다. |
id 필수 | string | 토큰 값입니다. source.resolve와 source.href에 전달됩니다. |
children | React.ReactNode | @Mina Park 같은 멘션 텍스트입니다. |
| 이름 | 타입 | 설명 |
|---|---|---|
value 필수 | MentionDraft | 텍스트와 그 토큰입니다. |
sources 필수 | readonly MentionSource[] | 맞는 토큰을 Mention.Root로 바꿀 때 쓰는 소스입니다. |
className | string | 감싸는 span의 class입니다. |