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