Mention Input
SaveA prompt field where @ mentions people, files, or tools and / runs a command from a menu at the caret; picks become chips that delete as one unit and keep working with undo and copy and paste.
- Category
- AI elements
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Mention Input preview
Type @ to mention someone or something, or / for a command.
Value
Ask @[Maya Chen](person:maya) to check @[rate-limits.md](file:limits)
- 4-14person Maya Chen
- 24-39file rate-limits.md
Installation
npx @shakenui/cli add mention-inputReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add mention-input --dry-runUsage
mention-input-example.tsx
"use client";
import { type MentionItem, MentionInput } from "@/components/shaken/agent/mention-input";
const mentions: MentionItem[] = [
{ id: "maya", label: "Maya Chen", kind: "person", detail: "Design" },
{ id: "tomas", label: "Tomás Ortega", kind: "person", detail: "Billing" },
{ id: "priya", label: "Priya Raman", kind: "person", detail: "Support" },
{ id: "webhook", label: "webhook.ts", kind: "file", detail: "src/billing/webhook.ts" },
{ id: "invoices", label: "invoices.sql", kind: "file", detail: "db/migrations/0042_invoices.sql" },
{ id: "search_docs", label: "search_docs", kind: "tool", detail: "Docs index" },
{ id: "run_tests", label: "run_tests", kind: "tool", detail: "CI runner" },
];
const commands: MentionItem[] = [
{ id: "summarize", label: "summarize", kind: "command", detail: "Recap the thread" },
{ id: "plan", label: "plan", kind: "command", detail: "Draft steps first" },
{ id: "review", label: "review", kind: "command", detail: "Review a diff" },
{ id: "test", label: "test", kind: "command", detail: "Write tests" },
];
export default function MentionInputExample() {
return (
<div className="grid w-full max-w-md gap-2">
<MentionInput
aria-label="Message the agent"
mentions={mentions}
commands={commands}
defaultValue="/[review](command:review) @[webhook.ts](file:webhook) and ask @[Tomás Ortega](person:tomas) about the retry "
placeholder="Ask anything. Type @ to mention, / for commands"
/>
<p className="text-xs text-zinc-500">Backspace removes a chip in one go. Undo brings it back.</p>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| mentions | MentionItem[] | (query, { signal }) => Promise<MentionItem[]> | — | Items offered after @. An item is { id, label, kind?, detail?, icon? }; kind (person, file, tool) groups the menu. A function loads results per query. |
| commands | MentionItem[] | (query, { signal }) => Promise<MentionItem[]> | — | Commands offered after / at the start of a line or after a space. |
| defaultValue / value | string | — | The value as markup, e.g. Ask @[Maya Chen](person:maya). Pass value with onValueChange to control it. |
| onValueChange | (markup, { text, tokens }) => void | — | Called on every change with markup and the structured value: plain text plus each chip's trigger, item, start, and end. |
| onSubmit | (markup, { text, tokens }) => void | — | Enter sends and Shift+Enter adds a line. Without it, Enter adds a line. |
| groupLabels | Record<string, string> | People, Files, Tools, Commands | Menu group headings by item kind. |
| containerClassName | string | — | Classes for the bordered field; className styles the text area. |
| parseMentions / serializeMentions | (markup) => MentionValue / (value) => string | — | Helpers that convert between markup and { text, tokens }. |
Accessibility
- The field is a native textarea with role="combobox", aria-autocomplete="list", aria-expanded, aria-controls, and aria-activedescendant pointing at the highlighted option; focus never leaves the text.
- The menu is a listbox of role="option" rows in groups labelled by kind. Up and Down move the highlight, Enter or Tab inserts, Escape closes the menu until the trigger is retyped.
- Filtering ignores case and accents. A polite status region announces the result count, "No matches", and each inserted or removed chip.
- Chips are plain text to assistive technology ("@Maya Chen"). Backspace or Delete next to a chip removes the whole chip; arrow keys step over it; a click inside a chip moves the caret to its edge.
- Insertions and removals are native edits, so Undo and Redo restore chips with their text. Copy and cut carry chips as markup to other Mention Inputs, with plain text for everything else.
- With reduced motion the menu appears without scaling and new chips do not flash.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/mention-input.tsxmention-input- npm packages: noneReact and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/mention-input/0.1.0.json.
agent/mention-input.tsxShowHide
agent/mention-input.tsx
"use client";
import {
type ChangeEvent,
type ClipboardEvent,
type ComponentProps,
type KeyboardEvent,
type ReactNode,
type SyntheticEvent,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
export type MentionTrigger = "@" | "/";
export interface MentionItem {
id: string;
label: string;
/** Groups the menu and picks the default glyph: "person", "file", "tool", "command", or your own. */
kind?: string;
/** Secondary text at the end of the row, such as a path or a role. */
detail?: string;
/** A 16px glyph. Defaults to initials for people and a glyph per kind. */
icon?: ReactNode;
}
export interface MentionToken {
trigger: MentionTrigger;
item: Pick<MentionItem, "id" | "label" | "kind">;
/** Where the chip's text starts and ends in `text`. */
start: number;
end: number;
}
export interface MentionValue {
/** Plain text, with each chip written as its trigger and label: "Ask @Maya Chen to /summarize". */
text: string;
tokens: MentionToken[];
}
export type MentionSource = MentionItem[] | ((query: string, options: { signal: AbortSignal }) => Promise<MentionItem[]>);
export interface MentionInputProps
extends Omit<ComponentProps<"textarea">, "value" | "defaultValue" | "onChange" | "onSubmit" | "children"> {
/** People, files, or tools offered after "@". A function loads them for each query. */
mentions?: MentionSource;
/** Commands offered after "/" at the start of a line or after a space. */
commands?: MentionSource;
/** The value as markup, e.g. `Ask @[Maya Chen](person:maya)`. Pass with `onValueChange` to control it. */
value?: string;
defaultValue?: string;
/** Called on every change with the markup and the structured value. */
onValueChange?: (markup: string, value: MentionValue) => void;
/** Enter sends (Shift+Enter adds a line). Without it, Enter adds a line. */
onSubmit?: (markup: string, value: MentionValue) => void;
/** Headings for menu groups, by item kind. */
groupLabels?: Record<string, string>;
/** Classes for the bordered field. `className` styles the text area. */
containerClassName?: string;
}
const defaultGroupLabels: Record<string, string> = {
person: "People",
file: "Files",
tool: "Tools",
command: "Commands",
};
// ---------------------------------------------------------------------------
// Markup
function escapeMarkup(text: string) {
return text.replace(/[\\\]\)]/g, (char) => `\\${char}`);
}
function unescapeMarkup(text: string) {
return text.replace(/\\(.)/g, "$1");
}
/** Writes text and chips as markup: `@[Maya Chen](person:maya)`, `/[summarize](command:summarize)`. */
export function serializeMentions({ text, tokens }: MentionValue): string {
let out = "";
let cursor = 0;
for (const token of [...tokens].sort((a, b) => a.start - b.start)) {
out += text.slice(cursor, token.start);
out += `${token.trigger}[${escapeMarkup(token.item.label)}](${escapeMarkup(token.item.kind ?? "")}:${escapeMarkup(token.item.id)})`;
cursor = token.end;
}
return out + text.slice(cursor);
}
const markupPattern = /([@/])\[((?:\\.|[^\]\\])*)\]\(((?:\\.|[^:)\\])*):((?:\\.|[^)\\])*)\)/g;
/** Reads markup back into plain text and chip positions. Text without markup comes back as is. */
export function parseMentions(markup: string): MentionValue {
let text = "";
const tokens: MentionToken[] = [];
let cursor = 0;
let match: RegExpExecArray | null;
markupPattern.lastIndex = 0;
while ((match = markupPattern.exec(markup))) {
text += markup.slice(cursor, match.index);
const trigger = match[1] as MentionTrigger;
const label = unescapeMarkup(match[2] ?? "");
const kind = unescapeMarkup(match[3] ?? "") || undefined;
const start = text.length;
text += trigger + label;
tokens.push({ trigger, item: { id: unescapeMarkup(match[4] ?? ""), label, kind }, start, end: text.length });
cursor = match.index + match[0].length;
}
return { text: text + markup.slice(cursor), tokens };
}
// ---------------------------------------------------------------------------
// Matching
function fold(text: string) {
return text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
}
function filterItems(items: MentionItem[], query: string): MentionItem[] {
const q = fold(query);
if (!q) return items.slice(0, 50);
const scored: { item: MentionItem; score: number }[] = [];
for (const item of items) {
const label = fold(item.label);
const words = label.split(/[\s._/-]+/);
const score = label.startsWith(q) ? 0 : words.some((word) => word.startsWith(q)) ? 1 : label.includes(q) ? 2 : fold(item.detail ?? "").includes(q) ? 3 : -1;
if (score >= 0) scored.push({ item, score });
}
// Array.prototype.sort is stable, so equal scores keep their given order.
return scored.sort((a, b) => a.score - b.score).slice(0, 50).map((entry) => entry.item);
}
interface Menu {
trigger: MentionTrigger;
/** Index of the trigger character. */
start: number;
query: string;
}
/** Shifts chips across an edit and drops any the edit touched. */
function shiftTokens(tokens: Chip[], previous: string, next: string, caret: number): Chip[] {
// The edit ends at the caret in the new text; the rest of the text after it is unchanged.
let suffix = next.length - caret;
if (suffix < 0 || previous.slice(previous.length - suffix) !== next.slice(caret) || suffix > previous.length) {
suffix = 0;
while (suffix < previous.length && suffix < next.length && previous[previous.length - 1 - suffix] === next[next.length - 1 - suffix]) suffix++;
}
let prefix = 0;
const limit = Math.min(previous.length - suffix, next.length - suffix);
while (prefix < limit && previous[prefix] === next[prefix]) prefix++;
const oldEnd = previous.length - suffix;
const delta = next.length - previous.length;
const out: Chip[] = [];
for (const token of tokens) {
if (token.end <= prefix) out.push(token);
else if (token.start >= oldEnd) out.push({ ...token, start: token.start + delta, end: token.end + delta });
}
return out;
}
interface Chip extends MentionToken {
/** Stable across edits, so a chip only animates when it is new. */
uid: number;
}
let uidCounter = 0;
function withUids(tokens: MentionToken[]): Chip[] {
return tokens.map((token) => ({ ...token, uid: ++uidCounter }));
}
function strip(chips: Chip[]): MentionToken[] {
return chips.map(({ uid: _uid, ...token }) => token);
}
/**
* A prompt field where "@" mentions people, files, or tools and "/" runs a command, from a menu at
* the caret. Picked items become chips that delete as one unit, survive undo, and copy and paste
* as markup. The value is plain text plus chip positions, or markup.
*/
export function MentionInput({
mentions,
commands,
value: valueProp,
defaultValue = "",
onValueChange,
onSubmit,
groupLabels,
containerClassName,
className,
placeholder,
disabled,
rows = 2,
onKeyDown,
onSelect,
onScroll,
onBlur,
"aria-describedby": describedBy,
...props
}: MentionInputProps) {
const id = useId();
const listId = `${id}-list`;
const [state, setState] = useState(() => {
const parsed = parseMentions(valueProp ?? defaultValue);
return { text: parsed.text, chips: withUids(parsed.tokens) };
});
const { text, chips } = state;
const [menu, setMenu] = useState<Menu | null>(null);
const [dismissed, setDismissed] = useState<number | null>(null);
const [results, setResults] = useState<MentionItem[]>([]);
const [loading, setLoading] = useState(false);
const [active, setActive] = useState(0);
const [announcement, setAnnouncement] = useState("");
const [place, setPlace] = useState<{ left: number; top: number; above: boolean; width: number } | null>(null);
const fieldRef = useRef<HTMLTextAreaElement>(null);
const mirrorRef = useRef<HTMLDivElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
// Chips for every text this field has held, so undo and redo bring chips back with their text.
const history = useRef(new Map<string, Chip[]>());
const pending = useRef<{ at: number; tokens: MentionToken[] } | null>(null);
const emitted = useRef<string | null>(null);
const fresh = useRef(new Set<number>());
const labels = { ...defaultGroupLabels, ...groupLabels };
function remember(nextText: string, nextChips: Chip[]) {
const map = history.current;
map.delete(nextText);
map.set(nextText, nextChips);
if (map.size > 200) map.delete(map.keys().next().value as string);
}
useEffect(() => {
remember(text, chips);
// Only the initial value; later values are remembered as they happen.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// A controlled value that changed from outside replaces the content.
useEffect(() => {
if (valueProp === undefined || valueProp === emitted.current) return;
const parsed = parseMentions(valueProp);
const nextChips = withUids(parsed.tokens);
remember(parsed.text, nextChips);
setState({ text: parsed.text, chips: nextChips });
}, [valueProp]);
function commit(nextText: string, nextChips: Chip[]) {
remember(nextText, nextChips);
setState({ text: nextText, chips: nextChips });
const structured = { text: nextText, tokens: strip(nextChips) };
const markup = serializeMentions(structured);
emitted.current = markup;
onValueChange?.(markup, structured);
}
function handleChange(event: ChangeEvent<HTMLTextAreaElement>) {
const field = event.target;
const nextText = field.value;
const caret = field.selectionEnd;
let nextChips: Chip[];
const known = history.current.get(nextText);
if (pending.current) {
const { at, tokens } = pending.current;
pending.current = null;
const shifted = shiftTokens(chips, text, nextText, caret);
const added = withUids(tokens.map((token) => ({ ...token, start: token.start + at, end: token.end + at })));
added.forEach((chip) => fresh.current.add(chip.uid));
nextChips = [...shifted, ...added].sort((a, b) => a.start - b.start);
} else if (known) {
nextChips = known;
} else {
nextChips = shiftTokens(chips, text, nextText, caret);
}
const removed = chips.filter((chip) => !nextChips.some((next) => next.uid === chip.uid));
if (removed.length === 1 && nextText.length < text.length) setAnnouncement(`Removed ${removed[0]!.item.label}`);
commit(nextText, nextChips);
detect(nextText, caret, nextChips);
}
/** Opens, updates, or closes the menu from the text before the caret. */
function detect(value: string, caret: number, current: Chip[]) {
const field = fieldRef.current;
if (!field || field.selectionStart !== field.selectionEnd) return setMenu(null);
const before = value.slice(0, caret);
const match = /(^|[\s(])([@/])([^\s@/]{0,40})$/.exec(before);
if (!match) {
if (dismissed !== null) setDismissed(null);
return setMenu(null);
}
const trigger = match[2] as MentionTrigger;
const query = match[3] ?? "";
const start = caret - query.length - 1;
const source = trigger === "@" ? mentions : commands;
if (!source || current.some((chip) => start >= chip.start && start < chip.end) || dismissed === start) return setMenu(null);
setMenu((open) => {
if (!open || open.start !== start || open.trigger !== trigger) setActive(0);
return { trigger, start, query };
});
}
// Load results for the menu's query.
useEffect(() => {
if (!menu) {
setResults([]);
setLoading(false);
return;
}
const source = menu.trigger === "@" ? mentions : commands;
if (!source) return;
if (Array.isArray(source)) {
setResults(filterItems(source, menu.query));
setLoading(false);
return;
}
const abort = new AbortController();
setLoading(true);
const timer = setTimeout(() => {
source(menu.query, { signal: abort.signal })
.then((items) => {
if (abort.signal.aborted) return;
setResults(items);
setLoading(false);
})
.catch(() => {
if (!abort.signal.aborted) setLoading(false);
});
}, 120);
return () => {
abort.abort();
clearTimeout(timer);
};
}, [menu?.trigger, menu?.query, menu === null, mentions, commands]); // eslint-disable-line react-hooks/exhaustive-deps
// Menu items in group order, so arrow keys follow what is on screen.
const groups: { kind: string; items: MentionItem[] }[] = [];
for (const item of results) {
const kind = item.kind ?? (menu?.trigger === "/" ? "command" : "other");
let group = groups.find((entry) => entry.kind === kind);
if (!group) groups.push((group = { kind, items: [] }));
group.items.push(item);
}
const ordered = groups.flatMap((group) => group.items);
const open = menu !== null && (ordered.length > 0 || loading || menu.query.length > 0);
const activeIndex = Math.min(active, Math.max(0, ordered.length - 1));
const optionId = (index: number) => `${id}-option-${index}`;
useEffect(() => {
if (!menu) return;
setAnnouncement(loading ? "Searching…" : ordered.length ? `${ordered.length} ${ordered.length === 1 ? "result" : "results"}` : "No matches");
}, [ordered.length, loading, menu === null]); // eslint-disable-line react-hooks/exhaustive-deps
// Keep the active option in view when it moves by keyboard.
useEffect(() => {
if (!open) return;
document.getElementById(optionId(activeIndex))?.scrollIntoView({ block: "nearest" });
}, [activeIndex, open]); // eslint-disable-line react-hooks/exhaustive-deps
// Place the menu at the trigger character, below the line or above it when there is no room.
useLayoutEffect(() => {
if (!open) {
setPlace(null);
return;
}
const anchor = mirrorRef.current?.querySelector<HTMLElement>("[data-anchor]");
const root = rootRef.current;
const mirror = mirrorRef.current;
if (!anchor || !root || !mirror) return;
const rootBox = root.getBoundingClientRect();
const anchorBox = anchor.getBoundingClientRect();
const width = Math.min(288, rootBox.width);
const height = menuRef.current?.offsetHeight ?? 240;
const left = Math.max(0, Math.min(rootBox.width - width, anchorBox.left - rootBox.left - 8));
const below = anchorBox.bottom - rootBox.top + 6;
const above = anchorBox.bottom + 6 + height > window.innerHeight - 8 && anchorBox.top - height - 6 > 8;
const top = above ? anchorBox.top - rootBox.top - 6 : below;
setPlace((current) =>
current && current.left === left && current.top === top && current.above === above && current.width === width ? current : { left, top, above, width },
);
});
function choose(item: MentionItem) {
const field = fieldRef.current;
if (!field || !menu) return;
const label = menu.trigger + item.label;
const caret = field.selectionEnd;
field.focus();
field.setSelectionRange(menu.start, caret);
pending.current = { at: menu.start, tokens: [{ trigger: menu.trigger, item: { id: item.id, label: item.label, kind: item.kind }, start: 0, end: label.length }] };
insertText(field, `${label} `);
setMenu(null);
setAnnouncement(`Inserted ${item.label}`);
}
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
onKeyDown?.(event);
if (event.defaultPrevented) return;
const field = event.currentTarget;
const { selectionStart: from, selectionEnd: to } = field;
if (open && !event.nativeEvent.isComposing) {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!ordered.length) return;
const step = event.key === "ArrowDown" ? 1 : -1;
setActive((activeIndex + step + ordered.length) % ordered.length);
return;
}
if ((event.key === "Enter" || event.key === "Tab") && ordered.length && !event.shiftKey) {
event.preventDefault();
choose(ordered[activeIndex]!);
return;
}
if (event.key === "Escape") {
event.preventDefault();
setDismissed(menu!.start);
setMenu(null);
return;
}
}
if (event.key === "Enter" && !event.shiftKey && onSubmit && !event.nativeEvent.isComposing) {
event.preventDefault();
const structured = { text, tokens: strip(chips) };
onSubmit(serializeMentions(structured), structured);
return;
}
// A chip deletes as one unit: widen the selection to cover it, then let the key delete.
if ((event.key === "Backspace" || event.key === "Delete") && !event.altKey && !event.metaKey && !event.ctrlKey) {
if (from === to) {
const chip = chips.find((item) => (event.key === "Backspace" ? item.end === from : item.start === from) || (item.start < from && from < item.end));
if (chip) field.setSelectionRange(chip.start, chip.end);
} else {
const [start, end] = cover(from, to);
if (start !== from || end !== to) field.setSelectionRange(start, end);
}
return;
}
// Arrow keys step over a chip in one move.
if ((event.key === "ArrowLeft" || event.key === "ArrowRight") && !event.shiftKey && !event.altKey && !event.metaKey && from === to) {
const left = event.key === "ArrowLeft";
const chip = chips.find((item) => (left ? item.end === from : item.start === from));
if (chip) {
event.preventDefault();
const at = left ? chip.start : chip.end;
field.setSelectionRange(at, at);
detect(text, at, chips);
}
}
}
/** Extends a range so it never cuts through a chip. */
function cover(from: number, to: number): [number, number] {
let start = from;
let end = to;
for (const chip of chips) {
if (chip.start < start && start < chip.end) start = chip.start;
if (chip.start < end && end < chip.end) end = chip.end;
}
return [start, end];
}
function handleSelect(event: SyntheticEvent<HTMLTextAreaElement>) {
onSelect?.(event);
const field = event.currentTarget;
const { selectionStart: from, selectionEnd: to } = field;
if (from === to) {
// A click inside a chip puts the caret at its nearer edge.
const chip = chips.find((item) => item.start < from && from < item.end);
if (chip) {
const at = from - chip.start < chip.end - from ? chip.start : chip.end;
field.setSelectionRange(at, at);
return;
}
detect(text, from, chips);
} else {
const [start, end] = cover(from, to);
if (start !== from || end !== to) field.setSelectionRange(start, end, field.selectionDirection);
setMenu(null);
}
}
function selectedValue(field: HTMLTextAreaElement): MentionValue {
const [start, end] = cover(field.selectionStart, field.selectionEnd);
const tokens = chips
.filter((chip) => chip.start >= start && chip.end <= end)
.map((chip) => ({ trigger: chip.trigger, item: chip.item, start: chip.start - start, end: chip.end - start }));
return { text: text.slice(start, end), tokens };
}
function handleCopy(event: ClipboardEvent<HTMLTextAreaElement>, cut: boolean) {
const field = event.currentTarget;
if (field.selectionStart === field.selectionEnd) return;
const selected = selectedValue(field);
if (!selected.tokens.length) return;
event.preventDefault();
event.clipboardData.setData("text/plain", selected.text);
event.clipboardData.setData(MARKUP_TYPE, serializeMentions(selected));
if (cut) {
const [start, end] = cover(field.selectionStart, field.selectionEnd);
field.setSelectionRange(start, end);
insertText(field, "");
}
}
function handlePaste(event: ClipboardEvent<HTMLTextAreaElement>) {
const field = event.currentTarget;
const markup = event.clipboardData.getData(MARKUP_TYPE) || event.clipboardData.getData("text/plain");
const parsed = parseMentions(markup);
if (!parsed.tokens.length) return;
event.preventDefault();
const [start, end] = cover(field.selectionStart, field.selectionEnd);
field.setSelectionRange(start, end);
pending.current = { at: start, tokens: parsed.tokens };
insertText(field, parsed.text);
setAnnouncement(`Pasted ${parsed.tokens.length === 1 ? parsed.tokens[0]!.item.label : `${parsed.tokens.length} mentions`}`);
}
// The mirror scrolls with the field.
useEffect(() => {
const field = fieldRef.current;
const mirror = mirrorRef.current;
if (field && mirror) mirror.scrollTop = field.scrollTop;
});
// Chips are only "fresh" for the render that adds them.
useEffect(() => {
if (fresh.current.size === 0) return;
const timer = setTimeout(() => fresh.current.clear(), 600);
return () => clearTimeout(timer);
});
const metrics = "px-3 py-2.5 text-sm leading-6 whitespace-pre-wrap break-words [scrollbar-gutter:stable]";
// The mirror: plain runs, chips, and an anchor around the open trigger character.
const parts: ReactNode[] = [];
let cursor = 0;
const pushPlain = (from: number, to: number) => {
if (to <= from) return;
if (menu && menu.start >= from && menu.start < to) {
parts.push(text.slice(from, menu.start));
parts.push(
<span key="anchor" data-anchor="">
{text[menu.start]}
</span>,
);
parts.push(text.slice(menu.start + 1, to));
} else {
parts.push(text.slice(from, to));
}
};
for (const chip of chips) {
pushPlain(cursor, chip.start);
const isFresh = fresh.current.has(chip.uid);
parts.push(
<span
key={chip.uid}
data-chip={chip.item.kind ?? chip.trigger}
className={cx(
"rounded-[5px] box-decoration-clone text-zinc-950 dark:text-white",
"bg-zinc-950/[0.06] shadow-[0_0_0_2px_rgb(9_9_11/0.06)] dark:bg-white/[0.11] dark:shadow-[0_0_0_2px_rgb(255_255_255/0.11)]",
isFresh &&
`transition-[background-color,box-shadow] duration-500 ${ease} motion-reduce:transition-none starting:bg-zinc-950/[0.16] starting:shadow-[0_0_0_2px_rgb(9_9_11/0.16)] dark:starting:bg-white/[0.26] dark:starting:shadow-[0_0_0_2px_rgb(255_255_255/0.26)]`,
)}
>
<span className="text-zinc-500 dark:text-zinc-400">{chip.trigger}</span>
{text.slice(chip.start + 1, chip.end)}
</span>,
);
cursor = chip.end;
}
pushPlain(cursor, text.length);
let optionIndex = -1;
return (
<div
ref={rootRef}
data-disabled={disabled || undefined}
className={cx(
"relative w-full rounded-xl border border-zinc-950/15 bg-white text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
"transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
"hover:border-zinc-950/25 focus-within:border-zinc-950/30 focus-within:shadow-[0_0_0_3px_rgb(14_165_233/0.16)]",
"dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)] dark:hover:border-white/25 dark:focus-within:border-white/30 dark:focus-within:shadow-[0_0_0_3px_rgb(56_189_248/0.18)]",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-60",
containerClassName,
)}
>
<textarea
ref={fieldRef}
value={text}
rows={rows}
disabled={disabled}
placeholder={placeholder}
role="combobox"
aria-autocomplete="list"
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? listId : undefined}
aria-activedescendant={open && ordered.length ? optionId(activeIndex) : undefined}
aria-describedby={cx(describedBy, `${id}-help`)}
onChange={handleChange}
onKeyDown={handleKeyDown}
onSelect={handleSelect}
onCopy={(event) => handleCopy(event, false)}
onCut={(event) => handleCopy(event, true)}
onPaste={handlePaste}
onScroll={(event) => {
onScroll?.(event);
if (mirrorRef.current) mirrorRef.current.scrollTop = event.currentTarget.scrollTop;
}}
onBlur={(event) => {
onBlur?.(event);
setMenu(null);
}}
{...props}
className={cx(
"absolute inset-0 block size-full resize-none overflow-y-auto bg-transparent focus:outline-none",
// The text itself is drawn by the mirror underneath, so chips can sit behind their words.
"text-transparent caret-zinc-950 placeholder:text-zinc-500 selection:bg-sky-500/25 dark:caret-white dark:selection:bg-sky-400/30",
metrics,
className,
)}
/>
<div
ref={mirrorRef}
aria-hidden="true"
style={{ minHeight: `calc(${rows} * 1.5rem + 1.25rem)` }}
className={cx("pointer-events-none relative max-h-60 overflow-hidden text-zinc-950 dark:text-white", metrics)}
>
{parts}
{""}
</div>
{open ? (
<div
ref={menuRef}
style={{
left: place?.left ?? 0,
top: place?.top ?? 0,
width: place?.width ?? 288,
visibility: place ? "visible" : "hidden",
translate: place?.above ? "0 -100%" : undefined,
}}
onMouseDown={(event) => event.preventDefault()}
className={cx(
"absolute z-20 overflow-hidden rounded-xl border border-zinc-950/10 bg-white text-zinc-950 shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)]",
"dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
place?.above ? "origin-bottom-left" : "origin-top-left",
`transition-[opacity,scale] duration-160 ${ease} motion-reduce:transition-none starting:opacity-0 motion-safe:starting:scale-96`,
)}
>
<div id={listId} role="listbox" aria-label={menu!.trigger === "@" ? "Mentions" : "Commands"} className="max-h-64 scroll-py-1.5 overflow-y-auto overscroll-contain p-1.5">
{groups.map((group) => (
<div key={group.kind} role="group" aria-labelledby={`${id}-group-${group.kind}`} className="not-first:mt-1">
<div id={`${id}-group-${group.kind}`} className="px-2 pt-1.5 pb-1 text-xs font-medium text-zinc-500 select-none">
{labels[group.kind] ?? group.kind}
</div>
{group.items.map((item) => {
optionIndex += 1;
const index = optionIndex;
const selected = index === activeIndex;
return (
<div
key={`${item.kind}-${item.id}`}
id={optionId(index)}
role="option"
aria-selected={selected}
onMouseMove={() => index !== activeIndex && setActive(index)}
onClick={() => choose(item)}
className={cx(
"flex h-8 cursor-default items-center gap-2.5 rounded-md px-2 text-sm select-none",
selected ? "bg-zinc-950/[0.05] text-zinc-950 dark:bg-white/[0.08] dark:text-white" : "text-zinc-700 dark:text-zinc-300",
)}
>
<ItemGlyph item={item} trigger={menu!.trigger} />
<span className="min-w-0 flex-1 truncate">
{menu!.trigger === "/" ? <span className="text-zinc-500">/</span> : null}
{item.label}
</span>
{item.detail ? <span className="max-w-[45%] shrink-0 truncate font-mono text-xs text-zinc-400 dark:text-zinc-500">{item.detail}</span> : null}
</div>
);
})}
</div>
))}
{!ordered.length ? (
<div className="px-2 py-2 text-sm text-zinc-500">{loading ? "Searching…" : `No matches for “${menu!.query}”`}</div>
) : null}
</div>
</div>
) : null}
<span id={`${id}-help`} className="sr-only">
Type @ to mention someone or something, or / for a command.
</span>
<span role="status" className="sr-only">
{announcement}
</span>
</div>
);
}
/** Custom clipboard type that carries chips between Mention Inputs; plain text goes alongside it. */
const MARKUP_TYPE = "application/x-mention-markup";
/** Inserts text over the selection as a native edit, so undo and redo treat it as one step. */
function insertText(field: HTMLTextAreaElement, text: string) {
const done = typeof document.execCommand === "function" && document.execCommand(text ? "insertText" : "delete", false, text);
if (done) return;
field.setRangeText(text, field.selectionStart, field.selectionEnd, "end");
field.dispatchEvent(new Event("input", { bubbles: true }));
}
function initials(label: string) {
const words = label.trim().split(/\s+/);
return ((words[0]?.[0] ?? "") + (words.length > 1 ? (words[words.length - 1]?.[0] ?? "") : "")).toUpperCase();
}
const glyph = { fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" } as const;
function ItemGlyph({ item, trigger }: { item: MentionItem; trigger: MentionTrigger }) {
const kind = item.kind ?? (trigger === "/" ? "command" : "other");
return (
<span aria-hidden="true" className="flex size-5 shrink-0 items-center justify-center text-zinc-500 dark:text-zinc-400 [&_svg]:size-4">
{item.icon ??
(kind === "person" ? (
<span className="flex size-5 items-center justify-center rounded-full bg-zinc-950/[0.06] text-[9px] font-semibold text-zinc-600 dark:bg-white/[0.1] dark:text-zinc-300">
{initials(item.label)}
</span>
) : kind === "file" ? (
<svg viewBox="0 0 16 16" {...glyph}>
<path d="M9 2.25H5.25a1 1 0 0 0-1 1v9.5a1 1 0 0 0 1 1h5.5a1 1 0 0 0 1-1V5Z" />
<path d="M9 2.25V5h2.75" />
</svg>
) : kind === "tool" ? (
<svg viewBox="0 0 16 16" {...glyph}>
<path d="M10.25 2.5a3.25 3.25 0 0 0-3 4.5l-4.5 4.5 1.75 1.75L9 8.75a3.25 3.25 0 0 0 4.5-3l-1.75 1.75-1.75-.5-.5-1.75z" />
</svg>
) : kind === "command" ? (
<svg viewBox="0 0 16 16" {...glyph}>
<rect x="2.25" y="2.25" width="11.5" height="11.5" rx="2.5" />
<path d="m9.5 5-3 6" />
</svg>
) : (
<svg viewBox="0 0 16 16" {...glyph}>
<circle cx="8" cy="8" r="2.5" />
<path d="M10.5 8v1a2 2 0 0 0 3.25 1.5A6 6 0 1 0 11 13.2" />
</svg>
))}
</span>
);
}