채팅 작성창 멘션
패키지 네임스페이스가 아닌 레시피입니다. 카드는 Field, Button, Attachment로 만들고, 제안은 Popover와 OptionList로 보여 주며, 하나의 people 소스를 useMentions와 MentionText에 함께 넘깁니다. 카드 프레임은 이 페이지의 것이고 패키지 파트가 아닙니다. @를 입력하면 제안이 나오고, 캐럿을 @Mina Park 안에 두면 피크가 열리며, 보내면 보낸 메시지에서 멘션을 볼 수 있습니다.
이 페이지의 내용
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>
);
}
캐럿 피크
목록이 닫혀 있고 캐럿이 멘션 안에 있는 동안, useMentions는 그 멘션에 붙인 앵커 이름인 caretPeekAnchorName을 반환합니다. 이 값을 usePopover의 anchorName으로 넘기고, 팝오버를 소스의 renderPeek를 caret 모드로 호출한 결과로 채웁니다. 이 팝오버는 포커스를 받지 않고 캐럿이 필드에 남아 있으므로 inert로 만듭니다. 브라우저는 inert 텍스트를 설명에서 빼므로, 피크가 열려 있는 동안에는 피크 내용을 VisuallyHidden으로 옮긴 사본으로 textarea를 설명합니다. 훅은 캐럿이 어느 멘션에 있는지 알려 주지 않으므로, 레시피는 textarea의 선택 영역을 읽고 resolve로 멘션을 조회하며, 캐럿이 다른 곳으로 옮겨 가면 조회를 중단합니다.
접근성을 지키는 조합
Todae가 맡는 것: getTextareaProps()는 aria-autocomplete와 aria-haspopup을 설정하고, 목록이 열려 있는 동안에는 aria-controls와 aria-activedescendant를 설정합니다. 이 둘은 getListboxProps()와 getOptionProps()가 목록과 옵션에 주는 id를 가리킵니다. 목록에서 ArrowDown, ArrowUp, Enter, Tab, Escape를 처리합니다. OptionList는 role="listbox"와 role="option" 행을 렌더링하고, Popover는 Escape와 바깥 누르기로 닫힙니다. 보낸 메시지의 멘션은 MentionText가 그리는, 피크가 달린 버튼이나 링크입니다.
직접 제공할 것: 필드의 이름입니다. 여기서는 Field.Root의 aria-label="Message"이고, Label을 써도 됩니다. OptionList.Root {...getListboxProps()}와 항목마다 OptionList.Option {...getOptionProps(item)}를 담은 Popover.Root입니다. 그래야 textarea가 가리키는 id가 실제로 존재합니다. 캐럿 피크가 열려 있는 동안 textarea의 aria-describedby에 넣을, 피크 텍스트의 시각적으로 숨긴 사본입니다. 피크 자체의 텍스트는 inert이기 때문입니다. 일치하는 옵션이 없을 때 role="status" 요소에 넣을 텍스트이며, 이때 목록은 언마운트하지 않고 hidden으로 둡니다. 아이콘만 있는 보내기 버튼의 이름입니다. 보내기는 Enter로 하되 IME 조합 중에는 보내지 않고, Shift+Enter는 줄을 바꿉니다. 첨부 파일 목록의 레이블입니다. 보낸 뒤와 마지막 첨부 파일을 지운 뒤에는 보내기 버튼이 비활성화되고 목록이 사라지므로, 포커스를 필드로 돌려놓습니다.
주의할 점: 직접 만든 role="listbox"와 role="option" 요소로 목록을 만들면, 그 id가 textarea가 가리키는 id와 어긋납니다. "+"나 "/" 같은 기호로만 이름 붙였거나 아무 동작도 하지 않는 툴바 버튼입니다. getter를 펼친 뒤에 직접 넣은 onFocus나 onBlur는 훅의 핸들러를 대체합니다. 레시피처럼 getTextareaProps()에 넘기세요.
When to use
@로 사람을 멘션하는 채팅 입력창, 그리고 보낸 메시지에서 같은 피크로 그 멘션을 보여 줄 때.
When not to use
토큰이 되지 않는 제안 목록은 Combobox입니다.