{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-chip-input",
  "title": "Prompt Chip Input",
  "description": "An AI prompt field where the @mention, ~model, or /command you type is wrapped in a live capsule that solidifies into a chip on commit and melts back into editable text on Backspace.",
  "dependencies": [
    "@rexa-developer/tiks",
    "motion",
    "web-haptics"
  ],
  "files": [
    {
      "path": "src/registry/components/prompt-chip-input/prompt-chip-input.tsx",
      "content": "\"use client\";\n\nimport { useTiks } from \"@rexa-developer/tiks/react\";\nimport {\n\tAnimatePresence,\n\ttype AnimationPlaybackControls,\n\tanimate,\n\tdomAnimation,\n\tLazyMotion,\n\tm,\n\tuseMotionValue,\n\tuseReducedMotion,\n} from \"motion/react\";\nimport {\n\ttype ClipboardEvent,\n\ttype ComponentProps,\n\ttype DragEvent,\n\ttype KeyboardEvent,\n\ttype MouseEvent,\n\ttype PointerEvent,\n\ttype ReactNode,\n\ttype Ref,\n\tuseEffect,\n\tuseId,\n\tuseImperativeHandle,\n\tuseLayoutEffect,\n\tuseRef,\n\tuseState,\n} from \"react\";\nimport { createPortal, flushSync } from \"react-dom\";\nimport { useWebHaptics } from \"web-haptics/react\";\nimport { cn } from \"@/lib/utils\";\n\n/** Rows the suggestion list shows at most. */\nconst MAX_RESULTS = 6;\n/**\n * Px the live capsule reaches past the typed text on each side, so the caret\n * sits inside it. The overlay overhangs the text by as much, so a capsule at\n * the start of a line isn't clipped.\n */\nconst CAPSULE_PAD = 3;\n/** Px between the capsule's edge and the loading spinner. */\nconst SPINNER_GAP = 4;\n/** Chip height, in em of the field's font size. */\nconst CHIP_HEIGHT = 1.45;\n/** Px between the capsule and the list, and between the list and the viewport edge. */\nconst POPOVER_GAP = 6;\nconst VIEWPORT_PAD = 8;\n\n// Motion. The capsule's width follows the query on a spring; the solidify\n// morph is a critically damped spring, so nothing overshoots.\nconst growSpring = { type: \"spring\", stiffness: 500, damping: 40 } as const;\nconst highlightSpring = {\n\ttype: \"spring\",\n\tstiffness: 600,\n\tdamping: 45,\n} as const;\nconst solidifySpring = {\n\ttype: \"spring\",\n\tduration: 0.26,\n\tbounce: 0,\n\trestDelta: 0.001,\n} as const;\nconst MELT_MS = 180;\nconst APPEAR_MS = 120;\nconst HIDE_MS = 100;\n/** Reduced motion swaps capsule and chip states with a short cross-fade. */\nconst FADE_MS = 100;\n/** Px the icon slides in from the chip's inline-start edge. */\nconst ICON_SLIDE = 4;\n\n/** Minimum ms between commit and melt sounds. */\nconst CUE_THROTTLE_MS = 80;\n/** Typing within this many ms of the last keystroke undoes as one step. */\nconst UNDO_GROUP_MS = 1000;\nconst UNDO_LIMIT = 100;\n\n/** Clipboard type that carries chips between prompt fields. */\nconst CLIPBOARD_TYPE = \"application/x-tentui-prompt-chips+json\";\n/** Custom highlight that hides raw text while a melting chip covers it. */\nconst HIDDEN_HIGHLIGHT = \"tentui-prompt-chip-hidden\";\n/** Characters after which a trigger opens, besides whitespace. */\nconst OPENERS = \"([{\";\n\n// Hoisted and deduplicated by React, so many fields share one sheet.\n// Chip initials are generated content with empty alt text, so they stay out\n// of the textbox's value for screen readers.\nconst STYLES =\n\t`::highlight(${HIDDEN_HIGHLIGHT}){color:transparent}` +\n\t'[data-initials]::before{content:attr(data-initials);content:attr(data-initials)/\"\"}';\n\nconst CHIP_CLASS =\n\t\"inline-block h-[1.45em] cursor-default whitespace-nowrap rounded-md px-1.5 align-baseline font-medium leading-[1.45em]\";\nconst ICON_CLASS =\n\t\"me-1 inline-block size-3.5 overflow-hidden align-[-0.15em] [&>svg]:block [&>svg]:size-full\";\nconst INITIALS_CLASS =\n\t\"flex size-full items-center justify-center rounded-full bg-current/15 font-semibold text-[7px] uppercase leading-none tracking-tight\";\nconst AVATAR_CLASS = \"block size-full rounded-full object-cover\";\n\nconst SPARKLE_PATH =\n\t\"M8 1.5c.35 2.85 1.25 4.3 2.4 5.1 1 .7 2.2 1.05 3.6 1.4-1.4.35-2.6.7-3.6 1.4-1.15.8-2.05 2.25-2.4 5.1-.35-2.85-1.25-4.3-2.4-5.1C4.6 8.7 3.4 8.35 2 8c1.4-.35 2.6-.7 3.6-1.4C6.75 5.8 7.65 4.35 8 1.5Z\";\nconst SPARKLE_SVG = `<svg viewBox=\"0 0 16 16\" fill=\"currentColor\" aria-hidden=\"true\"><path d=\"${SPARKLE_PATH}\"/></svg>`;\n\n// A soft, short tick when a chip solidifies, and a lower, softer one when it\n// melts back into text.\nconst COMMIT_SOUND = {\n\tname: \"prompt-chip-commit\",\n\tbaseFreq: 1500,\n\tnoiseColor: \"white\",\n\toscType: \"sine\",\n\tfilterFreq: 4200,\n\tfilterQ: 3,\n\tattack: 0.001,\n\tdecay: 0.45,\n\tbrightness: 5200,\n} as const;\nconst MELT_SOUND = {\n\t...COMMIT_SOUND,\n\tname: \"prompt-chip-melt\",\n\tbaseFreq: 880,\n\tfilterFreq: 2400,\n\tdecay: 0.4,\n\tbrightness: 3000,\n} as const;\n\nexport interface PromptChipItem {\n\tid: string;\n\tlabel: string;\n\t/** What the chip stands for in `value.text`, after the trigger. Defaults to `label`. */\n\tvalue?: string;\n\t/** Dim secondary text in the suggestion row, such as a team or a price note. */\n\tdescription?: string;\n\t/** Shown before the label in the row and the chip. */\n\ticon?: ReactNode;\n\t/** Image URL for a round 14 px avatar in the chip. Takes precedence over `icon`. */\n\tavatar?: string;\n}\n\nexport interface PromptChipTrigger {\n\t/** The character that opens suggestions, such as `\"@\"`, `\"/\"`, or `\"~\"`. */\n\tchar: string;\n\t/** Which entry of `kinds` styles the chips this trigger makes. */\n\tkind: string;\n\t/** Items to filter, or a search called with the query. The latest async result wins. */\n\titems:\n\t\t| PromptChipItem[]\n\t\t| ((query: string) => PromptChipItem[] | Promise<PromptChipItem[]>);\n\t/** Keep the list open across spaces in the query. */\n\tallowSpaces?: boolean;\n\t/** `\"start\"` opens only at the start of a line. Defaults to `\"start\"` for the `command` kind, else `\"any\"`. */\n\tposition?: \"any\" | \"start\";\n}\n\nexport interface PromptChipKind {\n\t/** Read before the label by screen readers, as in \"Mention: Ana Lima\". */\n\tlabel?: string;\n\t/** Announced after a commit, as in \"Ana Lima mentioned\". */\n\taction?: string;\n\t/** Chip classes: a soft tint background and a text color. The live capsule shows a lighter wash of the tint. */\n\tclassName?: string;\n\t/** Show the trigger in the chip, as in \"/summarize\". */\n\tshowTrigger?: boolean;\n\t/** Shown when an item has no `icon` or `avatar`. `\"initials\"` draws the label's initials and `\"sparkle\"` a small star. */\n\ticon?: ReactNode | \"initials\" | \"sparkle\";\n}\n\nexport interface PromptChipData {\n\tkind: string;\n\t/** Defaults to the `char` of the first trigger of this kind. */\n\ttrigger?: string;\n\tid: string;\n\tlabel: string;\n\t/** Defaults to `label`. */\n\tvalue?: string;\n\tavatar?: string;\n\ticon?: ReactNode;\n}\n\nexport type PromptChipSegment =\n\t| { type: \"text\"; text: string }\n\t| ({ type: \"chip\" } & PromptChipData);\n\nexport interface PromptChipValue {\n\t/** Model-ready text, with each chip written as its trigger plus its value: \"@ana\", \"/summarize\", \"~claude-opus-5-5\". */\n\ttext: string;\n\tchips: { kind: string; id: string; label: string; value: string }[];\n\t/** Text and chips in order. Pass these back as `value` or `defaultValue`. */\n\tsegments: PromptChipSegment[];\n}\n\nexport interface PromptChipInputHandle {\n\t/** Focuses the field with the caret at the end. */\n\tfocus: () => void;\n\tclear: () => void;\n\t/** Inserts a chip at the caret, or at the end when the field isn't focused. */\n\tinsertChip: (kind: string, item: PromptChipItem) => void;\n\tgetValue: () => PromptChipValue;\n}\n\nexport interface PromptChipInputProps\n\textends Omit<\n\t\tComponentProps<\"div\">,\n\t\t\"children\" | \"defaultValue\" | \"onChange\" | \"onSubmit\" | \"ref\"\n\t> {\n\t/** What opens suggestions, and the items each one offers. */\n\ttriggers: PromptChipTrigger[];\n\t/** Styles and screen reader names per chip kind. `mention`, `model`, and `command` come preset. */\n\tkinds?: Record<string, PromptChipKind>;\n\t/** Controlled content. The field re-renders only when this differs from what it last reported. */\n\tvalue?: PromptChipSegment[] | string;\n\t/** Initial content when uncontrolled. */\n\tdefaultValue?: PromptChipSegment[] | string;\n\t/** Called on every edit, chip commit, and melt. */\n\tonValueChange?: (value: PromptChipValue) => void;\n\t/** Called on Enter. Shift+Enter inserts a newline; Enter never submits during IME composition. */\n\tonSubmit?: (value: PromptChipValue) => void;\n\tplaceholder?: string;\n\tdisabled?: boolean;\n\t/** Lines the field grows to before it scrolls. */\n\tmaxRows?: number;\n\t/** Empty the field after `onSubmit`. */\n\tclearOnSubmit?: boolean;\n\t/** Backspace after a chip melts it back into editable text first. Off deletes the chip at once. */\n\tmeltOnBackspace?: boolean;\n\t/** Play a soft tick when a chip commits and a lower one when it melts. */\n\tsound?: boolean;\n\t/** A light haptic tick when a chip is committed from touch. */\n\thaptics?: boolean;\n\t/** Accessible name of the field. Defaults to \"Message\" unless `aria-labelledby` is set. */\n\t\"aria-label\"?: string;\n\t\"aria-labelledby\"?: string;\n\t/** Classes for the editable text area. */\n\teditableClassName?: string;\n\t/** Rendered below the text inside the card, such as a toolbar with a send button. */\n\tchildren?: ReactNode;\n\tref?: Ref<PromptChipInputHandle>;\n}\n\nconst DEFAULT_KINDS: Record<string, PromptChipKind> = {\n\tmention: {\n\t\tlabel: \"Mention\",\n\t\taction: \"mentioned\",\n\t\ticon: \"initials\",\n\t\tclassName:\n\t\t\t\"bg-sky-500/10 text-sky-700 dark:bg-sky-400/15 dark:text-sky-300\",\n\t},\n\tmodel: {\n\t\tlabel: \"Model\",\n\t\taction: \"selected\",\n\t\ticon: \"sparkle\",\n\t\tclassName:\n\t\t\t\"bg-violet-500/10 text-violet-700 dark:bg-violet-400/15 dark:text-violet-300\",\n\t},\n\tcommand: {\n\t\tlabel: \"Command\",\n\t\taction: \"added\",\n\t\tshowTrigger: true,\n\t\tclassName: \"bg-foreground/[0.06] font-mono text-foreground\",\n\t},\n};\n\ninterface ResolvedKind {\n\tlabel: string;\n\taction: string;\n\tclassName: string;\n\tshowTrigger: boolean;\n\ticon: ReactNode;\n}\n\ninterface ChipData {\n\tkind: string;\n\ttrigger: string;\n\tid: string;\n\tlabel: string;\n\tvalue: string;\n\tavatar?: string;\n\ticon?: ReactNode;\n}\n\ntype ChipSegment = { type: \"chip\" } & ChipData;\ntype Segment = { type: \"text\"; text: string } | ChipSegment;\n\ninterface Session {\n\tnode: Text;\n\tstart: number;\n\tend: number;\n\ttriggerIndex: number;\n\t/** A melted chip keeps its menu open across the spaces in its label. */\n\tmelted: boolean;\n}\n\ninterface MenuState {\n\ttriggerIndex: number;\n\tquery: string;\n\tresults: PromptChipItem[];\n\tloading: boolean;\n\tactive: number;\n}\n\ninterface Snapshot {\n\tsegments: Segment[];\n\tcaret: number | null;\n}\n\ninterface IconSlot {\n\tkey: number;\n\tel: Element;\n\ticon: ReactNode;\n}\n\ninterface Box {\n\tx: number;\n\ty: number;\n\tw: number;\n\th: number;\n}\n\nfunction capitalize(text: string) {\n\treturn text.charAt(0).toUpperCase() + text.slice(1);\n}\n\nfunction resolveKind(\n\tkinds: Record<string, PromptChipKind> | undefined,\n\tname: string,\n): ResolvedKind {\n\tconst preset = DEFAULT_KINDS[name];\n\tconst custom = kinds?.[name];\n\treturn {\n\t\tlabel: custom?.label ?? preset?.label ?? capitalize(name),\n\t\taction: custom?.action ?? preset?.action ?? \"added\",\n\t\tclassName:\n\t\t\tcustom?.className ??\n\t\t\tpreset?.className ??\n\t\t\t\"bg-foreground/[0.06] text-foreground\",\n\t\tshowTrigger: custom?.showTrigger ?? preset?.showTrigger ?? false,\n\t\ticon: custom && \"icon\" in custom ? custom.icon : preset?.icon,\n\t};\n}\n\nfunction triggerPosition(trigger: PromptChipTrigger) {\n\treturn trigger.position ?? (trigger.kind === \"command\" ? \"start\" : \"any\");\n}\n\nfunction escapeHtml(text: string) {\n\treturn text\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\");\n}\n\nfunction initials(label: string) {\n\tconst words = label.trim().split(/\\s+/).filter(Boolean);\n\treturn words\n\t\t.slice(0, 2)\n\t\t.map((word) => Array.from(word)[0] ?? \"\")\n\t\t.join(\"\");\n}\n\ntype IconSpec =\n\t| { type: \"avatar\"; src: string }\n\t| { type: \"initials\" }\n\t| { type: \"sparkle\" }\n\t| { type: \"node\"; node: ReactNode }\n\t| null;\n\nfunction iconSpec(\n\tchip: { avatar?: string; icon?: ReactNode },\n\tkind: ResolvedKind,\n): IconSpec {\n\tif (chip.avatar) return { type: \"avatar\", src: chip.avatar };\n\tconst icon = chip.icon !== undefined ? chip.icon : kind.icon;\n\tif (icon === \"initials\") return { type: \"initials\" };\n\tif (icon === \"sparkle\") return { type: \"sparkle\" };\n\tif (icon === null || icon === undefined || icon === false) return null;\n\treturn { type: \"node\", node: icon };\n}\n\nfunction chipText(\n\tchip: { trigger: string; label: string },\n\tkind: ResolvedKind,\n) {\n\treturn kind.showTrigger ? chip.trigger + chip.label : chip.label;\n}\n\n/** A chip's markup. Built as a string so the server renders it too. */\nfunction chipHtml(chip: ChipData, kind: ResolvedKind) {\n\tconst spec = iconSpec(chip, kind);\n\tlet icon = \"\";\n\tif (spec) {\n\t\tconst inner =\n\t\t\tspec.type === \"avatar\"\n\t\t\t\t? `<img src=\"${escapeHtml(spec.src)}\" alt=\"\" draggable=\"false\" class=\"${AVATAR_CLASS}\">`\n\t\t\t\t: spec.type === \"initials\"\n\t\t\t\t\t? `<span data-initials=\"${escapeHtml(initials(chip.label))}\" class=\"${INITIALS_CLASS}\"></span>`\n\t\t\t\t\t: spec.type === \"sparkle\"\n\t\t\t\t\t\t? SPARKLE_SVG\n\t\t\t\t\t\t: \"\";\n\t\ticon = `<span data-slot=\"prompt-chip-icon\" aria-hidden=\"true\" class=\"${ICON_CLASS}\">${inner}</span>`;\n\t}\n\tconst data = [\n\t\t[\"kind\", chip.kind],\n\t\t[\"id\", chip.id],\n\t\t[\"label\", chip.label],\n\t\t[\"value\", chip.value],\n\t\t[\"trigger\", chip.trigger],\n\t\t...(chip.avatar ? [[\"avatar\", chip.avatar]] : []),\n\t]\n\t\t.map(([key, value]) => `data-${key}=\"${escapeHtml(value)}\"`)\n\t\t.join(\" \");\n\treturn `<span contenteditable=\"false\" data-slot=\"prompt-chip\" ${data} class=\"${escapeHtml(cn(CHIP_CLASS, kind.className))}\"><span class=\"sr-only\">${escapeHtml(kind.label)}: </span>${icon}<span data-slot=\"prompt-chip-label\">${escapeHtml(chipText(chip, kind))}</span></span>`;\n}\n\nfunction segmentsHtml(\n\tsegments: Segment[],\n\tkinds: Record<string, PromptChipKind> | undefined,\n) {\n\treturn `${segments\n\t\t.map((segment) =>\n\t\t\tsegment.type === \"text\"\n\t\t\t\t? escapeHtml(segment.text)\n\t\t\t\t: chipHtml(segment, resolveKind(kinds, segment.kind)),\n\t\t)\n\t\t.join(\"\")}<br>`;\n}\n\nfunction isChip(node: Node | null | undefined): node is HTMLElement {\n\treturn (\n\t\t!!node &&\n\t\tnode.nodeType === Node.ELEMENT_NODE &&\n\t\t(node as HTMLElement).dataset.slot === \"prompt-chip\"\n\t);\n}\n\nfunction isText(node: Node | null | undefined): node is Text {\n\treturn !!node && node.nodeType === Node.TEXT_NODE;\n}\n\n/** Fills in each chip's trigger and value, and merges adjacent text. */\nfunction normalizeSegments(\n\tinput: readonly PromptChipSegment[] | string | undefined,\n\ttriggers: readonly PromptChipTrigger[],\n): Segment[] {\n\tif (input === undefined) return [];\n\tconst list: readonly PromptChipSegment[] =\n\t\ttypeof input === \"string\" ? [{ type: \"text\", text: input }] : input;\n\tconst out: Segment[] = [];\n\tfor (const segment of list) {\n\t\tif (segment.type === \"text\") {\n\t\t\tif (!segment.text) continue;\n\t\t\tconst last = out[out.length - 1];\n\t\t\tif (last?.type === \"text\") last.text += segment.text;\n\t\t\telse out.push({ type: \"text\", text: segment.text });\n\t\t\tcontinue;\n\t\t}\n\t\tout.push({\n\t\t\ttype: \"chip\",\n\t\t\tkind: segment.kind,\n\t\t\ttrigger:\n\t\t\t\tsegment.trigger ??\n\t\t\t\ttriggers.find((trigger) => trigger.kind === segment.kind)?.char ??\n\t\t\t\t\"\",\n\t\t\tid: segment.id,\n\t\t\tlabel: segment.label,\n\t\t\tvalue: segment.value ?? segment.label,\n\t\t\tavatar: segment.avatar,\n\t\t\ticon: segment.icon,\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction segmentsKey(segments: readonly Segment[]) {\n\treturn JSON.stringify(\n\t\tsegments.map((segment) =>\n\t\t\tsegment.type === \"text\"\n\t\t\t\t? segment.text\n\t\t\t\t: [segment.kind, segment.id, segment.label, segment.value],\n\t\t),\n\t);\n}\n\nfunction serialize(segments: readonly Segment[], use: \"value\" | \"label\") {\n\treturn segments\n\t\t.map((segment) =>\n\t\t\tsegment.type === \"text\"\n\t\t\t\t? segment.text\n\t\t\t\t: segment.trigger + (use === \"value\" ? segment.value : segment.label),\n\t\t)\n\t\t.join(\"\");\n}\n\nfunction toValue(segments: Segment[]): PromptChipValue {\n\treturn {\n\t\ttext: serialize(segments, \"value\"),\n\t\tchips: segments.flatMap((segment) =>\n\t\t\tsegment.type === \"chip\"\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: segment.kind,\n\t\t\t\t\t\t\tid: segment.id,\n\t\t\t\t\t\t\tlabel: segment.label,\n\t\t\t\t\t\t\tvalue: segment.value,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t\t),\n\t\tsegments: segments.map((segment) => ({ ...segment })),\n\t};\n}\n\n/** Reads text and chips from the field, or from a copied fragment. */\nfunction readSegments(root: Node, icons: WeakMap<Element, ReactNode>) {\n\tconst out: Segment[] = [];\n\tlet text = \"\";\n\tconst flush = () => {\n\t\tif (text) out.push({ type: \"text\", text });\n\t\ttext = \"\";\n\t};\n\t// The field always ends in a <br> that holds the last line open.\n\tconst sentinel = root.lastChild?.nodeName === \"BR\" ? root.lastChild : null;\n\tconst walk = (parent: Node) => {\n\t\tfor (const node of Array.from(parent.childNodes)) {\n\t\t\tif (isText(node)) {\n\t\t\t\ttext += node.data.replace(/\\u00a0/g, \" \").replace(/\\u200b/g, \"\");\n\t\t\t} else if (isChip(node)) {\n\t\t\t\tflush();\n\t\t\t\tconst data = node.dataset;\n\t\t\t\tout.push({\n\t\t\t\t\ttype: \"chip\",\n\t\t\t\t\tkind: data.kind ?? \"\",\n\t\t\t\t\ttrigger: data.trigger ?? \"\",\n\t\t\t\t\tid: data.id ?? \"\",\n\t\t\t\t\tlabel: data.label ?? \"\",\n\t\t\t\t\tvalue: data.value ?? data.label ?? \"\",\n\t\t\t\t\tavatar: data.avatar,\n\t\t\t\t\ticon: icons.get(node),\n\t\t\t\t});\n\t\t\t} else if (node.nodeName === \"BR\") {\n\t\t\t\tif (node !== sentinel) text += \"\\n\";\n\t\t\t} else if (node.nodeType === Node.ELEMENT_NODE) {\n\t\t\t\tconst block = node.nodeName === \"DIV\" || node.nodeName === \"P\";\n\t\t\t\tif (block && (text || out.length) && !text.endsWith(\"\\n\")) {\n\t\t\t\t\ttext += \"\\n\";\n\t\t\t\t}\n\t\t\t\twalk(node);\n\t\t\t}\n\t\t}\n\t};\n\twalk(root);\n\tflush();\n\treturn out;\n}\n\n/** Characters before a point, counting a chip or a line break as one. */\nfunction lengthOf(root: Node) {\n\tlet length = 0;\n\tconst walk = (parent: Node) => {\n\t\tfor (const node of Array.from(parent.childNodes)) {\n\t\t\tif (isText(node)) length += node.data.length;\n\t\t\telse if (isChip(node) || node.nodeName === \"BR\") length += 1;\n\t\t\telse walk(node);\n\t\t}\n\t};\n\twalk(root);\n\treturn length;\n}\n\nfunction rankItems(items: readonly PromptChipItem[], query: string) {\n\tconst q = query.toLowerCase();\n\tif (!q) return items.slice(0, MAX_RESULTS);\n\tconst ranked: Array<{ item: PromptChipItem; rank: number }> = [];\n\tfor (const item of items) {\n\t\tconst label = item.label.toLowerCase();\n\t\tconst value = (item.value ?? \"\").toLowerCase();\n\t\tlet rank = -1;\n\t\tif (label.startsWith(q)) rank = 0;\n\t\telse if (label.split(/[\\s\\-_.]+/).some((word) => word.startsWith(q)))\n\t\t\trank = 1;\n\t\telse if (value.startsWith(q)) rank = 1;\n\t\tif (rank >= 0) ranked.push({ item, rank });\n\t}\n\treturn ranked\n\t\t.sort((a, b) => a.rank - b.rank)\n\t\t.slice(0, MAX_RESULTS)\n\t\t.map(({ item }) => item);\n}\n\nfunction cssZoom(element: Element) {\n\treturn (element as Element & { currentCSSZoom?: number }).currentCSSZoom ?? 1;\n}\n\n/**\n * The box around a range's last line. Bidi text can split one line into\n * several rects, as Latin \"@an\" in a right-to-left paragraph does.\n */\nfunction lastRect(range: Range) {\n\tconst rects = Array.from(range.getClientRects()).filter(\n\t\t(rect) => rect.width > 0 || rect.height > 0,\n\t);\n\tconst last = rects[rects.length - 1];\n\tif (!last) return null;\n\tconst line = rects.filter(\n\t\t(rect) =>\n\t\t\tMath.abs(rect.top + rect.height / 2 - (last.top + last.height / 2)) <\n\t\t\tlast.height / 2,\n\t);\n\tconst left = Math.min(...line.map((rect) => rect.left));\n\tconst right = Math.max(...line.map((rect) => rect.right));\n\tconst top = Math.min(...line.map((rect) => rect.top));\n\tconst bottom = Math.max(...line.map((rect) => rect.bottom));\n\treturn new DOMRect(left, top, right - left, bottom - top);\n}\n\nfunction clamp(value: number, min = 0, max = 1) {\n\treturn Math.min(Math.max(value, min), max);\n}\n\nfunction lerp(from: number, to: number, t: number) {\n\treturn from + (to - from) * t;\n}\n\nfunction easeOut(t: number) {\n\treturn 1 - (1 - t) ** 3;\n}\n\nconst RTL_TEXT = /[\\u0590-\\u08ff\\ufb1d-\\ufdfd\\ufe70-\\ufefc]/;\n\n/** A chip's icon or avatar, for list rows and static chips. */\nfunction ItemIcon({\n\tspec,\n\tlabel,\n\tclassName,\n\tinitialsClassName,\n}: {\n\tspec: IconSpec;\n\tlabel: string;\n\tclassName?: string;\n\tinitialsClassName?: string;\n}) {\n\tif (!spec) return null;\n\treturn (\n\t\t<span\n\t\t\taria-hidden\n\t\t\tdata-slot=\"prompt-chip-icon\"\n\t\t\tclassName={cn(ICON_CLASS, className)}\n\t\t>\n\t\t\t{spec.type === \"avatar\" ? (\n\t\t\t\t// biome-ignore lint/performance/noImgElement: a 14 px avatar in user content\n\t\t\t\t<img src={spec.src} alt=\"\" draggable={false} className={AVATAR_CLASS} />\n\t\t\t) : spec.type === \"initials\" ? (\n\t\t\t\t<span className={cn(INITIALS_CLASS, initialsClassName)}>\n\t\t\t\t\t{initials(label)}\n\t\t\t\t</span>\n\t\t\t) : spec.type === \"sparkle\" ? (\n\t\t\t\t<svg viewBox=\"0 0 16 16\" fill=\"currentColor\" aria-hidden>\n\t\t\t\t\t<path d={SPARKLE_PATH} />\n\t\t\t\t</svg>\n\t\t\t) : (\n\t\t\t\tspec.node\n\t\t\t)}\n\t\t</span>\n\t);\n}\n\n/**\n * A chip outside the field, styled like the ones in it, for rendering sent\n * messages from `value.segments`.\n */\nexport function PromptChip({\n\tchip,\n\tkinds,\n\tclassName,\n}: {\n\tchip: PromptChipData;\n\tkinds?: Record<string, PromptChipKind>;\n\tclassName?: string;\n}) {\n\tconst kind = resolveKind(kinds, chip.kind);\n\treturn (\n\t\t<span\n\t\t\tdata-slot=\"prompt-chip\"\n\t\t\tdata-kind={chip.kind}\n\t\t\tclassName={cn(CHIP_CLASS, kind.className, className)}\n\t\t>\n\t\t\t<span className=\"sr-only\">{kind.label}: </span>\n\t\t\t<ItemIcon spec={iconSpec(chip, kind)} label={chip.label} />\n\t\t\t<span data-slot=\"prompt-chip-label\">\n\t\t\t\t{chipText({ trigger: chip.trigger ?? \"\", label: chip.label }, kind)}\n\t\t\t</span>\n\t\t</span>\n\t);\n}\n\nexport function PromptChipInput({\n\ttriggers,\n\tkinds,\n\tvalue: valueProp,\n\tdefaultValue,\n\tonValueChange,\n\tonSubmit,\n\tplaceholder,\n\tdisabled = false,\n\tmaxRows = 8,\n\tclearOnSubmit = true,\n\tmeltOnBackspace = true,\n\tsound = false,\n\thaptics = true,\n\t\"aria-label\": ariaLabel,\n\t\"aria-labelledby\": ariaLabelledBy,\n\teditableClassName,\n\tclassName,\n\tchildren,\n\tref,\n\t...props\n}: PromptChipInputProps) {\n\tconst reducedMotion = useReducedMotion() ?? false;\n\tconst { trigger: haptic } = useWebHaptics();\n\t// Sound stays on under reduced motion; only movement is reduced.\n\tconst { click: playCommit } = useTiks({\n\t\ttheme: COMMIT_SOUND,\n\t\tvolume: 0.25,\n\t\trespectReducedMotion: false,\n\t});\n\tconst { click: playMelt } = useTiks({\n\t\ttheme: MELT_SOUND,\n\t\tvolume: 0.15,\n\t\trespectReducedMotion: false,\n\t});\n\n\tconst ids = useId().replace(/[^\\w-]/g, \"\");\n\tconst listId = `prompt-chip-input-${ids}-list`;\n\tconst optionId = (index: number) =>\n\t\t`prompt-chip-input-${ids}-option-${index}`;\n\n\tconst [initial] = useState(() =>\n\t\tnormalizeSegments(valueProp ?? defaultValue, triggers),\n\t);\n\tconst [initialHtml] = useState(() => ({\n\t\t__html: segmentsHtml(initial, kinds),\n\t}));\n\tconst [empty, setEmpty] = useState(initial.length === 0);\n\tconst [focused, setFocused] = useState(false);\n\tconst [menu, setMenuState] = useState<MenuState | null>(null);\n\tconst [capsuleKind, setCapsuleKind] = useState(\n\t\t() => triggers[0]?.kind ?? \"mention\",\n\t);\n\tconst [iconSlots, setIconSlots] = useState<IconSlot[]>([]);\n\tconst [announcement, setAnnouncement] = useState(\"\");\n\n\tconst rootRef = useRef<HTMLDivElement>(null);\n\tconst editableRef = useRef<HTMLDivElement>(null);\n\tconst layerRef = useRef<HTMLDivElement>(null);\n\tconst boxRef = useRef<HTMLSpanElement>(null);\n\tconst liveRef = useRef<HTMLSpanElement>(null);\n\tconst solidRef = useRef<HTMLSpanElement>(null);\n\tconst typedRef = useRef<HTMLSpanElement>(null);\n\tconst labelRef = useRef<HTMLSpanElement>(null);\n\tconst ghostRef = useRef<HTMLSpanElement>(null);\n\tconst ghostTextRef = useRef<HTMLSpanElement>(null);\n\tconst spinnerRef = useRef<HTMLSpanElement>(null);\n\tconst listRef = useRef<HTMLDivElement>(null);\n\tconst rowRefs = useRef<(HTMLDivElement | null)[]>([]);\n\n\t// The capsule's box in the overlay, in px.\n\tconst boxX = useMotionValue(0);\n\tconst boxY = useMotionValue(0);\n\tconst boxW = useMotionValue(0);\n\tconst boxH = useMotionValue(0);\n\tconst boxScale = useMotionValue(1);\n\tconst boxOrigin = useMotionValue(0);\n\tconst highlightY = useMotionValue(0);\n\tconst highlightH = useMotionValue(0);\n\n\tconst menuRef = useRef<MenuState | null>(null);\n\tconst sessionRef = useRef<Session | null>(null);\n\t/** A trigger closed with Esc stays closed until a new one is typed. */\n\tconst dismissedRef = useRef<{ node: Text; start: number } | null>(null);\n\t/** What the overlay is drawing: nothing, a live capsule, or a morph. */\n\tconst phaseRef = useRef<\"idle\" | \"live\" | \"solid\" | \"melt\">(\"idle\");\n\tconst transitionRef = useRef<{\n\t\tcontrols: AnimationPlaybackControls;\n\t\tfinish: () => void;\n\t} | null>(null);\n\t/** The capsule's position and width springs. */\n\tconst geometryRef = useRef<AnimationPlaybackControls[]>([]);\n\t/** The capsule's fade and scale in or out. */\n\tconst fadeRef = useRef<AnimationPlaybackControls[]>([]);\n\tconst anchorRef = useRef<{\n\t\tleft: number;\n\t\tright: number;\n\t\ttop: number;\n\t\tbottom: number;\n\t} | null>(null);\n\tconst sideRef = useRef<\"top\" | \"bottom\" | null>(null);\n\tconst highlightShownRef = useRef(false);\n\tconst requestRef = useRef(0);\n\t/** The session waiting to announce its result count. */\n\tconst announceCountRef = useRef(false);\n\tconst lastKeyRef = useRef(segmentsKey(initial));\n\t/** The chip just committed; one Backspace across its trailing space melts it. */\n\tconst lastCommitRef = useRef<HTMLElement | null>(null);\n\tconst historyRef = useRef({\n\t\tpast: [] as Snapshot[],\n\t\tfuture: [] as Snapshot[],\n\t\tlastKind: \"\",\n\t\tlastAt: 0,\n\t});\n\tconst composingRef = useRef(false);\n\tconst touchRef = useRef(false);\n\tconst pointerTypeRef = useRef(\"mouse\");\n\tconst lastCueRef = useRef(Number.NEGATIVE_INFINITY);\n\tconst chipIconsRef = useRef(new WeakMap<Element, ReactNode>());\n\tconst itemCacheRef = useRef(new Map<string, PromptChipItem>());\n\tconst pendingSlotsRef = useRef<IconSlot[]>([]);\n\tconst slotKeyRef = useRef(0);\n\tconst iconSlotsRef = useRef<IconSlot[]>([]);\n\n\tconst kindFor = (name: string) => resolveKind(kinds, name);\n\n\tconst setMenu = (next: MenuState | null) => {\n\t\tmenuRef.current = next;\n\t\tsetMenuState(next);\n\t};\n\n\tconst announce = (message: string) => {\n\t\t// A zero-width space makes a repeated message announce again.\n\t\tsetAnnouncement((previous) =>\n\t\t\tprevious === message ? `${message}\\u200b` : message,\n\t\t);\n\t};\n\n\t// --- DOM model -----------------------------------------------------------\n\n\tconst read = () => {\n\t\tconst editable = editableRef.current;\n\t\treturn editable ? readSegments(editable, chipIconsRef.current) : [];\n\t};\n\n\tconst lookupItem = (kind: string, id: string) => {\n\t\tconst cached = itemCacheRef.current.get(`${kind}\\u0000${id}`);\n\t\tif (cached) return cached;\n\t\tfor (const trigger of triggers) {\n\t\t\tif (trigger.kind !== kind || typeof trigger.items === \"function\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst item = trigger.items.find((candidate) => candidate.id === id);\n\t\t\tif (item) return item;\n\t\t}\n\t\treturn undefined;\n\t};\n\n\tconst createChip = (data: ChipData) => {\n\t\tconst kind = kindFor(data.kind);\n\t\tconst template = document.createElement(\"template\");\n\t\ttemplate.innerHTML = chipHtml(data, kind);\n\t\tconst chip = template.content.firstElementChild as HTMLElement;\n\t\tif (data.icon !== undefined) chipIconsRef.current.set(chip, data.icon);\n\t\tconst spec = iconSpec(data, kind);\n\t\tconst slot = chip.querySelector('[data-slot=\"prompt-chip-icon\"]');\n\t\tif (spec?.type === \"node\" && slot) {\n\t\t\tpendingSlotsRef.current.push({\n\t\t\t\tkey: ++slotKeyRef.current,\n\t\t\t\tel: slot,\n\t\t\t\ticon: spec.node,\n\t\t\t});\n\t\t}\n\t\treturn chip;\n\t};\n\n\t/** Mounts icons for new chips and drops the ones that left the field. */\n\tconst syncIconSlots = (sync = false) => {\n\t\tconst pending = pendingSlotsRef.current;\n\t\tconst stale = iconSlotsRef.current.some((slot) => !slot.el.isConnected);\n\t\tif (pending.length === 0 && !stale) return;\n\t\tpendingSlotsRef.current = [];\n\t\tconst next = [\n\t\t\t...iconSlotsRef.current.filter((slot) => slot.el.isConnected),\n\t\t\t...pending,\n\t\t];\n\t\ticonSlotsRef.current = next;\n\t\tif (sync) flushSync(() => setIconSlots(next));\n\t\telse setIconSlots(next);\n\t};\n\n\tconst buildFragment = (segments: readonly Segment[]) => {\n\t\tconst fragment = document.createDocumentFragment();\n\t\tfor (const segment of segments) {\n\t\t\tfragment.append(\n\t\t\t\tsegment.type === \"text\"\n\t\t\t\t\t? document.createTextNode(segment.text)\n\t\t\t\t\t: createChip(segment),\n\t\t\t);\n\t\t}\n\t\treturn fragment;\n\t};\n\n\tconst render = (segments: readonly Segment[]) => {\n\t\teditableRef.current?.replaceChildren(\n\t\t\tbuildFragment(segments),\n\t\t\tdocument.createElement(\"br\"),\n\t\t);\n\t\tsyncIconSlots();\n\t};\n\n\t// --- Caret ---------------------------------------------------------------\n\n\tconst selectionRange = () => {\n\t\tconst editable = editableRef.current;\n\t\tconst selection = window.getSelection();\n\t\tif (!editable || !selection || selection.rangeCount === 0) return null;\n\t\tconst range = selection.getRangeAt(0);\n\t\treturn editable.contains(range.commonAncestorContainer) ? range : null;\n\t};\n\n\tconst getCaret = () => {\n\t\tconst range = selectionRange();\n\t\tif (!range?.collapsed) return null;\n\t\treturn { node: range.startContainer, offset: range.startOffset };\n\t};\n\n\tconst placeCaret = (node: Node, offset: number) => {\n\t\tconst selection = window.getSelection();\n\t\tif (!selection) return;\n\t\tconst range = document.createRange();\n\t\trange.setStart(node, offset);\n\t\trange.collapse(true);\n\t\tselection.removeAllRanges();\n\t\tselection.addRange(range);\n\t};\n\n\tconst caretOffset = () => {\n\t\tconst editable = editableRef.current;\n\t\tconst caret = getCaret();\n\t\tif (!editable || !caret) return null;\n\t\tconst range = document.createRange();\n\t\trange.setStart(editable, 0);\n\t\trange.setEnd(caret.node, caret.offset);\n\t\treturn lengthOf(range.cloneContents());\n\t};\n\n\tconst setCaretOffset = (target: number) => {\n\t\tconst editable = editableRef.current;\n\t\tif (!editable) return;\n\t\tlet remaining = target;\n\t\tconst nodes = Array.from(editable.childNodes);\n\t\tfor (const [index, node] of nodes.entries()) {\n\t\t\tif (isText(node)) {\n\t\t\t\tif (remaining <= node.data.length) {\n\t\t\t\t\tplaceCaret(node, remaining);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tremaining -= node.data.length;\n\t\t\t} else if (node === editable.lastChild && node.nodeName === \"BR\") {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tif (remaining === 0) {\n\t\t\t\t\tplaceCaret(editable, index);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tremaining -= 1;\n\t\t\t}\n\t\t}\n\t\tconst last = editable.lastChild;\n\t\tplaceCaret(\n\t\t\teditable,\n\t\t\tMath.max(0, nodes.length - (last?.nodeName === \"BR\" ? 1 : 0)),\n\t\t);\n\t};\n\n\t/** Merges split text and keeps the trailing <br>, holding the caret in place. */\n\tconst tidy = () => {\n\t\tconst editable = editableRef.current;\n\t\tif (!editable) return;\n\t\tconst nodes = Array.from(editable.childNodes);\n\t\tconst messy = nodes.some(\n\t\t\t(node, index) =>\n\t\t\t\tisText(node) && (node.data === \"\" || isText(nodes[index + 1])),\n\t\t);\n\t\tif (messy) {\n\t\t\tconst offset = caretOffset();\n\t\t\teditable.normalize();\n\t\t\tif (offset !== null) setCaretOffset(offset);\n\t\t}\n\t\tif (editable.lastChild?.nodeName !== \"BR\") {\n\t\t\teditable.appendChild(document.createElement(\"br\"));\n\t\t}\n\t};\n\n\t/** The chip right before the caret, or before a just-committed chip's space. */\n\tconst chipBeforeCaret = (allowSpace: boolean) => {\n\t\tconst caret = getCaret();\n\t\tif (!caret) return null;\n\t\tconst { node, offset } = caret;\n\t\tlet before: Node | null = null;\n\t\tif (isText(node)) {\n\t\t\tconst text = node.data.slice(0, offset);\n\t\t\tif (text === \"\") before = node.previousSibling;\n\t\t\telse if (\n\t\t\t\tallowSpace &&\n\t\t\t\t/^[ \\u00a0]$/.test(text) &&\n\t\t\t\tnode.previousSibling === lastCommitRef.current\n\t\t\t) {\n\t\t\t\tbefore = node.previousSibling;\n\t\t\t}\n\t\t} else if (node === editableRef.current) {\n\t\t\tbefore = node.childNodes[offset - 1] ?? null;\n\t\t}\n\t\twhile (isText(before) && before.data === \"\")\n\t\t\tbefore = before.previousSibling;\n\t\treturn isChip(before) ? before : null;\n\t};\n\n\tconst chipAfterCaret = () => {\n\t\tconst caret = getCaret();\n\t\tif (!caret) return null;\n\t\tconst { node, offset } = caret;\n\t\tlet after: Node | null = null;\n\t\tif (isText(node)) {\n\t\t\tif (offset === node.data.length) after = node.nextSibling;\n\t\t} else if (node === editableRef.current) {\n\t\t\tafter = node.childNodes[offset] ?? null;\n\t\t}\n\t\twhile (isText(after) && after.data === \"\") after = after.nextSibling;\n\t\treturn isChip(after) ? after : null;\n\t};\n\n\t// --- Value and history ---------------------------------------------------\n\n\tconst emit = () => {\n\t\tconst segments = read();\n\t\tsetEmpty(segments.length === 0);\n\t\tconst key = segmentsKey(segments);\n\t\tif (key === lastKeyRef.current) return;\n\t\tlastKeyRef.current = key;\n\t\tonValueChange?.(toValue(segments));\n\t};\n\n\tconst snapshot = (): Snapshot => ({ segments: read(), caret: caretOffset() });\n\n\tconst record = (kind: \"type\" | \"delete\" | \"op\") => {\n\t\tconst history = historyRef.current;\n\t\tconst now = performance.now();\n\t\tif (\n\t\t\tkind !== \"op\" &&\n\t\t\tkind === history.lastKind &&\n\t\t\tnow - history.lastAt < UNDO_GROUP_MS\n\t\t) {\n\t\t\thistory.lastAt = now;\n\t\t\treturn;\n\t\t}\n\t\thistory.past.push(snapshot());\n\t\tif (history.past.length > UNDO_LIMIT) history.past.shift();\n\t\thistory.future = [];\n\t\thistory.lastKind = kind;\n\t\thistory.lastAt = now;\n\t};\n\n\t// --- Overlay -------------------------------------------------------------\n\n\tconst stopGeometry = () => {\n\t\tfor (const controls of geometryRef.current) controls.stop();\n\t\tgeometryRef.current = [];\n\t};\n\n\t/** The capsule's opacity, written directly so it stays on the JS frame loop. */\n\tconst setBoxOpacity = (opacity: number) => {\n\t\tif (boxRef.current) boxRef.current.style.opacity = String(opacity);\n\t};\n\n\tconst stopFade = () => {\n\t\tfor (const controls of fadeRef.current) controls.stop();\n\t\tfadeRef.current = [];\n\t};\n\n\tconst fadeBox = (to: number, ms: number) => {\n\t\tconst from = Number(boxRef.current?.style.opacity || 0);\n\t\treturn animate(from, to, {\n\t\t\tduration: ms / 1000,\n\t\t\tease: \"easeOut\",\n\t\t\tonUpdate: setBoxOpacity,\n\t\t});\n\t};\n\n\tconst resetOverlay = () => {\n\t\tif (liveRef.current) liveRef.current.style.opacity = \"\";\n\t\tif (solidRef.current) solidRef.current.style.opacity = \"0\";\n\t\tconst typed = typedRef.current;\n\t\tif (typed) {\n\t\t\ttyped.textContent = \"\";\n\t\t\ttyped.style.opacity = \"\";\n\t\t\ttyped.style.filter = \"\";\n\t\t}\n\t\tlabelRef.current?.replaceChildren();\n\t\tCSS.highlights?.delete(HIDDEN_HIGHLIGHT);\n\t};\n\n\t/** Jumps a running solidify or melt to its end state. */\n\tconst settleTransition = () => {\n\t\ttransitionRef.current?.finish();\n\t};\n\n\tconst runTransition = (\n\t\toptions: Parameters<typeof animate>[2],\n\t\tonFrame: (progress: number) => void,\n\t\tonDone: () => void,\n\t) => {\n\t\tlet done = false;\n\t\tconst finish = () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\ttransitionRef.current = null;\n\t\t\tonFrame(1);\n\t\t\tonDone();\n\t\t};\n\t\t// Paint the first frame now, before the browser does.\n\t\tonFrame(0);\n\t\tconst from: number = 0;\n\t\tconst controls = animate(from, 1, {\n\t\t\t...options,\n\t\t\tonUpdate: onFrame,\n\t\t\tonComplete: finish,\n\t\t} as Parameters<typeof animate>[2]);\n\t\ttransitionRef.current = {\n\t\t\tcontrols,\n\t\t\tfinish: () => {\n\t\t\t\tcontrols.stop();\n\t\t\t\tfinish();\n\t\t\t},\n\t\t};\n\t};\n\n\tconst layerMetrics = () => {\n\t\tconst layer = layerRef.current;\n\t\tif (!layer) return null;\n\t\treturn { rect: layer.getBoundingClientRect(), zoom: cssZoom(layer) };\n\t};\n\n\tconst toLayer = (\n\t\trect: DOMRect,\n\t\tmetrics: { rect: DOMRect; zoom: number },\n\t): Box => ({\n\t\tx: (rect.left - metrics.rect.left) / metrics.zoom,\n\t\ty: (rect.top - metrics.rect.top) / metrics.zoom,\n\t\tw: rect.width / metrics.zoom,\n\t\th: rect.height / metrics.zoom,\n\t});\n\n\tconst isRtl = () =>\n\t\t!!editableRef.current &&\n\t\tgetComputedStyle(editableRef.current).direction === \"rtl\";\n\n\tconst setKind = (kind: string) => {\n\t\tif (kind !== capsuleKind) flushSync(() => setCapsuleKind(kind));\n\t};\n\n\tconst hideGhost = () => {\n\t\tif (ghostRef.current) ghostRef.current.hidden = true;\n\t};\n\n\t/**\n\t * The rest of the best match, flush with the caret, or a spinner while\n\t * loading. Returns the px the completion adds to the capsule.\n\t */\n\tconst updateGhost = (): number => {\n\t\tconst ghost = ghostRef.current;\n\t\tconst ghostText = ghostTextRef.current;\n\t\tconst spinner = spinnerRef.current;\n\t\tconst session = sessionRef.current;\n\t\tconst state = menuRef.current;\n\t\tconst metrics = layerMetrics();\n\t\tif (!ghost || !ghostText || !spinner || !metrics) return 0;\n\t\tif (\n\t\t\t!session?.node.isConnected ||\n\t\t\t!state ||\n\t\t\tphaseRef.current !== \"live\" ||\n\t\t\tcomposingRef.current\n\t\t) {\n\t\t\thideGhost();\n\t\t\treturn 0;\n\t\t}\n\t\t// Only when nothing follows on the line, so it never covers text.\n\t\tconst rest = session.node.data.slice(session.end);\n\t\tconst line = rest.split(\"\\n\")[0];\n\t\tconst next = session.node.nextSibling;\n\t\tconst followed =\n\t\t\tline.trim() !== \"\" ||\n\t\t\t(!rest.includes(\"\\n\") && !!next && next.nodeName !== \"BR\");\n\t\tconst item = state.results[state.active];\n\t\tconst query = state.query;\n\t\tlet text = \"\";\n\t\tif (\n\t\t\titem &&\n\t\t\t!state.loading &&\n\t\t\titem.label.length > query.length &&\n\t\t\titem.label.toLowerCase().startsWith(query.toLowerCase())\n\t\t) {\n\t\t\ttext = item.label.slice(query.length);\n\t\t}\n\t\tif (followed || (!text && !state.loading)) {\n\t\t\thideGhost();\n\t\t\treturn 0;\n\t\t}\n\t\tconst range = document.createRange();\n\t\trange.setStart(session.node, session.start);\n\t\trange.setEnd(session.node, session.end);\n\t\tconst rect = lastRect(range);\n\t\tif (!rect) {\n\t\t\thideGhost();\n\t\t\treturn 0;\n\t\t}\n\t\tconst box = toLayer(rect, metrics);\n\t\t// After bidi reordering, a completion only reads right when the label\n\t\t// runs in the paragraph's direction.\n\t\tconst rtl = isRtl();\n\t\tif (rtl !== RTL_TEXT.test(item?.label ?? query)) {\n\t\t\thideGhost();\n\t\t\treturn 0;\n\t\t}\n\t\tghostText.textContent = text;\n\t\tghostText.hidden = state.loading;\n\t\tspinner.hidden = !state.loading;\n\t\tghost.hidden = false;\n\t\t// The text's own box, so the completion shares the query's baseline.\n\t\tghost.style.lineHeight = `${box.h}px`;\n\t\tghost.style.top = `${box.y}px`;\n\t\tghost.style.left = `${rtl ? box.x : box.x + box.w}px`;\n\t\tghost.style.transform = rtl ? \"translateX(-100%)\" : \"\";\n\t\tconst width = ghost.getBoundingClientRect().width / metrics.zoom;\n\t\t// A completion that would run past the line's end is left out rather\n\t\t// than clipped.\n\t\tconst end = rtl ? box.x - width : box.x + box.w + width;\n\t\tconst limit = metrics.rect.width / metrics.zoom - CAPSULE_PAD;\n\t\tif (end < CAPSULE_PAD - 0.5 || end > limit + 0.5) {\n\t\t\thideGhost();\n\t\t\treturn 0;\n\t\t}\n\t\treturn state.loading ? 0 : width;\n\t};\n\n\t/** Places the live capsule over the trigger and query. */\n\tconst measureCapsule = (mode: \"appear\" | \"grow\" | \"jump\") => {\n\t\tconst session = sessionRef.current;\n\t\tconst editable = editableRef.current;\n\t\tif (!session?.node.isConnected || !editable) return;\n\t\t// A running morph lands first, since it can move the text.\n\t\tif (phaseRef.current !== \"live\") settleTransition();\n\t\tconst metrics = layerMetrics();\n\t\tif (!metrics) return;\n\t\tconst range = document.createRange();\n\t\trange.setStart(session.node, session.start);\n\t\trange.setEnd(session.node, session.end);\n\t\tconst rect = lastRect(range);\n\t\tif (!rect) return;\n\t\tconst box = toLayer(rect, metrics);\n\t\tconst fresh = phaseRef.current !== \"live\";\n\t\tif (fresh) {\n\t\t\tstopGeometry();\n\t\t\tresetOverlay();\n\t\t\tphaseRef.current = \"live\";\n\t\t}\n\t\t// The capsule takes in the completion, so it reads as one word.\n\t\tconst ghost = updateGhost();\n\t\tconst height =\n\t\t\tNumber.parseFloat(getComputedStyle(editable).fontSize) * CHIP_HEIGHT;\n\t\tconst rtl = isRtl();\n\t\tconst target = {\n\t\t\tx: box.x - CAPSULE_PAD - (rtl ? ghost : 0),\n\t\t\ty: box.y + box.h / 2 - height / 2,\n\t\t\tw: box.w + ghost + CAPSULE_PAD * 2,\n\t\t\th: height,\n\t\t};\n\t\tconst zoom = metrics.zoom;\n\t\tanchorRef.current = {\n\t\t\tleft: metrics.rect.left + target.x * zoom,\n\t\t\tright: metrics.rect.left + (target.x + target.w) * zoom,\n\t\t\ttop: metrics.rect.top + target.y * zoom,\n\t\t\tbottom: metrics.rect.top + (target.y + target.h) * zoom,\n\t\t};\n\t\tif (!fresh && mode !== \"appear\") {\n\t\t\tconst wrapped = Math.abs(boxY.get() - target.y) > 2;\n\t\t\tif (mode === \"jump\" || wrapped || reducedMotion) {\n\t\t\t\tstopGeometry();\n\t\t\t\tboxX.jump(target.x);\n\t\t\t\tboxW.jump(target.w);\n\t\t\t} else {\n\t\t\t\tstopGeometry();\n\t\t\t\tgeometryRef.current = [\n\t\t\t\t\tanimate(boxX, target.x, growSpring),\n\t\t\t\t\tanimate(boxW, target.w, growSpring),\n\t\t\t\t];\n\t\t\t}\n\t\t\tboxY.jump(target.y);\n\t\t\tboxH.jump(target.h);\n\t\t\treturn;\n\t\t}\n\t\tif (fresh) {\n\t\t\t// A new capsule fades in, scaled from 0.9 at the trigger.\n\t\t\tboxX.jump(target.x);\n\t\t\tboxY.jump(target.y);\n\t\t\tboxW.jump(target.w);\n\t\t\tboxH.jump(target.h);\n\t\t\tboxOrigin.jump(rtl ? 1 : 0);\n\t\t\tstopFade();\n\t\t\tsetBoxOpacity(0);\n\t\t\tboxScale.jump(reducedMotion ? 1 : 0.9);\n\t\t\tconst duration = (reducedMotion ? FADE_MS : APPEAR_MS) / 1000;\n\t\t\tfadeRef.current = [\n\t\t\t\tfadeBox(1, reducedMotion ? FADE_MS : APPEAR_MS),\n\t\t\t\t...(reducedMotion\n\t\t\t\t\t? []\n\t\t\t\t\t: [animate(boxScale, 1, { duration, ease: \"easeOut\" })]),\n\t\t\t];\n\t\t}\n\t};\n\n\tconst hideCapsule = () => {\n\t\thideGhost();\n\t\tif (phaseRef.current !== \"live\") return;\n\t\tphaseRef.current = \"idle\";\n\t\tstopGeometry();\n\t\tstopFade();\n\t\tfadeRef.current = [fadeBox(0, HIDE_MS)];\n\t};\n\n\t// --- Suggestions ---------------------------------------------------------\n\n\tconst remember = (kind: string, items: readonly PromptChipItem[]) => {\n\t\tfor (const item of items) {\n\t\t\titemCacheRef.current.set(`${kind}\\u0000${item.id}`, item);\n\t\t}\n\t};\n\n\tconst announceCount = (state: MenuState) => {\n\t\tif (!announceCountRef.current || state.loading) return;\n\t\tannounceCountRef.current = false;\n\t\tconst count = state.results.length;\n\t\tannounce(\n\t\t\tcount === 0\n\t\t\t\t? \"No matches\"\n\t\t\t\t: `${count} ${count === 1 ? \"suggestion\" : \"suggestions\"}`,\n\t\t);\n\t};\n\n\tconst load = (\n\t\ttriggerIndex: number,\n\t\tquery: string,\n\t\tkeep: MenuState | null,\n\t\tactiveId?: string,\n\t) => {\n\t\tconst trigger = triggers[triggerIndex];\n\t\tif (!trigger) return;\n\t\tconst id = ++requestRef.current;\n\t\tconst activeFor = (results: PromptChipItem[]) =>\n\t\t\tMath.max(\n\t\t\t\t0,\n\t\t\t\tactiveId ? results.findIndex((item) => item.id === activeId) : 0,\n\t\t\t);\n\t\tconst settle = (items: PromptChipItem[]) => {\n\t\t\tconst results = items.slice(0, MAX_RESULTS);\n\t\t\tremember(trigger.kind, results);\n\t\t\tconst next = {\n\t\t\t\ttriggerIndex,\n\t\t\t\tquery,\n\t\t\t\tresults,\n\t\t\t\tloading: false,\n\t\t\t\tactive: activeFor(results),\n\t\t\t};\n\t\t\tsetMenu(next);\n\t\t\tannounceCount(next);\n\t\t};\n\t\tconst source = trigger.items;\n\t\tif (typeof source !== \"function\") {\n\t\t\tsettle(rankItems(source, query));\n\t\t\treturn;\n\t\t}\n\t\tlet out: PromptChipItem[] | Promise<PromptChipItem[]>;\n\t\ttry {\n\t\t\tout = source(query);\n\t\t} catch {\n\t\t\tout = [];\n\t\t}\n\t\tif (!(out instanceof Promise) && !(\"then\" in out)) {\n\t\t\tsettle(out);\n\t\t\treturn;\n\t\t}\n\t\t// Earlier results stay up while the next ones load.\n\t\tconst previous = keep?.triggerIndex === triggerIndex ? keep.results : [];\n\t\tsetMenu({\n\t\t\ttriggerIndex,\n\t\t\tquery,\n\t\t\tresults: previous,\n\t\t\tloading: true,\n\t\t\tactive: Math.min(keep?.active ?? 0, Math.max(previous.length - 1, 0)),\n\t\t});\n\t\tPromise.resolve(out).then(\n\t\t\t(items) => {\n\t\t\t\tif (id === requestRef.current && sessionRef.current) settle(items);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (id === requestRef.current && sessionRef.current) settle([]);\n\t\t\t},\n\t\t);\n\t};\n\n\tconst closeMenu = () => {\n\t\tsessionRef.current = null;\n\t\trequestRef.current++;\n\t\tannounceCountRef.current = false;\n\t\tif (menuRef.current) setMenu(null);\n\t\thideCapsule();\n\t};\n\n\tconst dismiss = () => {\n\t\tconst session = sessionRef.current;\n\t\tif (session) {\n\t\t\tdismissedRef.current = { node: session.node, start: session.start };\n\t\t}\n\t\tcloseMenu();\n\t};\n\n\t/** The character before a text node, as seen by the word-boundary check. */\n\tconst charBefore = (node: Text) => {\n\t\tlet previous = node.previousSibling;\n\t\twhile (isText(previous) && previous.data === \"\") {\n\t\t\tprevious = previous.previousSibling;\n\t\t}\n\t\tif (!previous) return \"\\n\";\n\t\tif (previous.nodeName === \"BR\") return \"\\n\";\n\t\tif (isText(previous)) return previous.data.slice(-1);\n\t\treturn \" \";\n\t};\n\n\t/** The trigger and query that end at the caret, if any. */\n\tconst findToken = (): Session | null => {\n\t\tconst caret = getCaret();\n\t\tif (!caret || !isText(caret.node)) return null;\n\t\tconst node = caret.node;\n\t\tconst end = caret.offset;\n\t\tconst data = node.data;\n\t\tconst session = sessionRef.current;\n\t\tif (session && session.node === node && session.start < end) {\n\t\t\tconst trigger = triggers[session.triggerIndex];\n\t\t\tif (trigger && data.startsWith(trigger.char, session.start)) {\n\t\t\t\tconst query = data.slice(session.start + trigger.char.length, end);\n\t\t\t\tif (\n\t\t\t\t\t!query.includes(\"\\n\") &&\n\t\t\t\t\t(trigger.allowSpaces || session.melted || !/\\s/.test(query))\n\t\t\t\t) {\n\t\t\t\t\treturn { ...session, end };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (let index = end - 1; index >= 0; index--) {\n\t\t\tif (/\\s/.test(data[index])) return null;\n\t\t\tconst triggerIndex = triggers.findIndex(\n\t\t\t\t(trigger) => trigger.char && data.startsWith(trigger.char, index),\n\t\t\t);\n\t\t\tif (triggerIndex === -1) continue;\n\t\t\tconst trigger = triggers[triggerIndex];\n\t\t\tif (index + trigger.char.length > end) continue;\n\t\t\tconst before = index > 0 ? data[index - 1] : charBefore(node);\n\t\t\tconst lineStart = before === \"\\n\";\n\t\t\t// \"a@b.com\" never opens: a trigger needs a word boundary before it.\n\t\t\tif (!lineStart && !/\\s/.test(before) && !OPENERS.includes(before)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (triggerPosition(trigger) === \"start\" && !lineStart) return null;\n\t\t\treturn { node, start: index, end, triggerIndex, melted: false };\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst detect = () => {\n\t\tconst dismissed = dismissedRef.current;\n\t\tif (dismissed) {\n\t\t\tconst stillThere =\n\t\t\t\tdismissed.node.isConnected &&\n\t\t\t\ttriggers.some((trigger) =>\n\t\t\t\t\tdismissed.node.data.startsWith(trigger.char, dismissed.start),\n\t\t\t\t);\n\t\t\tif (!stillThere) dismissedRef.current = null;\n\t\t}\n\t\tconst token = findToken();\n\t\tif (\n\t\t\t!token ||\n\t\t\t(dismissedRef.current &&\n\t\t\t\ttoken.node === dismissedRef.current.node &&\n\t\t\t\ttoken.start === dismissedRef.current.start)\n\t\t) {\n\t\t\tcloseMenu();\n\t\t\treturn;\n\t\t}\n\t\tconst previous = sessionRef.current;\n\t\tconst fresh =\n\t\t\t!previous ||\n\t\t\tprevious.node !== token.node ||\n\t\t\tprevious.start !== token.start ||\n\t\t\tprevious.triggerIndex !== token.triggerIndex;\n\t\tsessionRef.current = token;\n\t\tconst trigger = triggers[token.triggerIndex];\n\t\tconst query = token.node.data.slice(\n\t\t\ttoken.start + trigger.char.length,\n\t\t\ttoken.end,\n\t\t);\n\t\tif (fresh) {\n\t\t\tannounceCountRef.current = true;\n\t\t\tsideRef.current = null;\n\t\t\tsetKind(trigger.kind);\n\t\t}\n\t\tconst state = menuRef.current;\n\t\tif (fresh || !state || state.query !== query) {\n\t\t\tload(token.triggerIndex, query, fresh ? null : state);\n\t\t}\n\t\tmeasureCapsule(fresh ? \"appear\" : \"grow\");\n\t};\n\n\t// --- Commit and melt -----------------------------------------------------\n\n\tconst cue = (kind: \"commit\" | \"melt\", touch: boolean) => {\n\t\tif (document.visibilityState === \"hidden\") return;\n\t\tconst now = performance.now();\n\t\tif (now - lastCueRef.current < CUE_THROTTLE_MS) return;\n\t\tlastCueRef.current = now;\n\t\tif (sound) (kind === \"commit\" ? playCommit : playMelt)();\n\t\tif (haptics && kind === \"commit\" && touch) void haptic(\"light\");\n\t};\n\n\tconst prepareClone = (chip: HTMLElement) => {\n\t\tconst clone = chip.cloneNode(true) as HTMLElement;\n\t\tclone.removeAttribute(\"contenteditable\");\n\t\tclone.removeAttribute(\"data-slot\");\n\t\tclone.style.cssText =\n\t\t\t\"position:absolute;left:0;top:0;margin:0;background:transparent\";\n\t\treturn clone;\n\t};\n\n\t/**\n\t * The capsule morphs into the chip's rect while the typed letters blur out\n\t * and the label fades in. The real chip stays hidden underneath and widens\n\t * on the same spring, so text after it glides along instead of being\n\t * covered, and the chip is revealed in place at the end.\n\t */\n\tconst solidify = (\n\t\tchip: HTMLElement,\n\t\traw: { rect: DOMRect; text: string } | null,\n\t\tfrom: Box | null,\n\t) => {\n\t\tconst metrics = layerMetrics();\n\t\tconst label = labelRef.current;\n\t\tconst typed = typedRef.current;\n\t\tconst live = liveRef.current;\n\t\tconst solid = solidRef.current;\n\t\tif (!metrics || !label || !typed || !live || !solid) return;\n\t\tconst target = toLayer(chip.getBoundingClientRect(), metrics);\n\t\tif (reducedMotion || !raw || !from) {\n\t\t\tchip.animate([{ opacity: 0 }, { opacity: 1 }], {\n\t\t\t\tduration: FADE_MS,\n\t\t\t\teasing: \"ease-out\",\n\t\t\t});\n\t\t\thideCapsule();\n\t\t\treturn;\n\t\t}\n\t\tconst clone = prepareClone(chip);\n\t\tconst rawBox = toLayer(raw.rect, metrics);\n\t\tchip.style.width = `${rawBox.w}px`;\n\t\tchip.style.opacity = \"0\";\n\t\tphaseRef.current = \"solid\";\n\t\tstopGeometry();\n\t\tstopFade();\n\t\thideGhost();\n\t\tlabel.replaceChildren(clone);\n\t\ttyped.textContent = raw.text;\n\t\ttyped.style.lineHeight = `${rawBox.h}px`;\n\t\tsetBoxOpacity(1);\n\t\tboxScale.jump(1);\n\t\tconst icon = clone.querySelector<HTMLElement>(\n\t\t\t'[data-slot=\"prompt-chip-icon\"]',\n\t\t);\n\t\tconst slide = isRtl() ? ICON_SLIDE : -ICON_SLIDE;\n\t\trunTransition(\n\t\t\tsolidifySpring,\n\t\t\t(progress) => {\n\t\t\t\tconst t = clamp(progress);\n\t\t\t\tconst x = lerp(from.x, target.x, progress);\n\t\t\t\tconst y = lerp(from.y, target.y, progress);\n\t\t\t\tboxX.jump(x);\n\t\t\t\tboxY.jump(y);\n\t\t\t\tboxW.jump(lerp(from.w, target.w, progress));\n\t\t\t\tboxH.jump(lerp(from.h, target.h, progress));\n\t\t\t\tchip.style.width = `${lerp(rawBox.w, target.w, progress).toFixed(2)}px`;\n\t\t\t\tlive.style.opacity = String(1 - t);\n\t\t\t\tsolid.style.opacity = String(t);\n\t\t\t\ttyped.style.left = `${rawBox.x - x}px`;\n\t\t\t\ttyped.style.top = `${rawBox.y - y}px`;\n\t\t\t\ttyped.style.opacity = String(1 - clamp(t * 1.6));\n\t\t\t\ttyped.style.filter = `blur(${(t * 2).toFixed(2)}px)`;\n\t\t\t\tclone.style.left = `${target.x - x}px`;\n\t\t\t\tclone.style.top = `${target.y - y}px`;\n\t\t\t\tclone.style.opacity = String(clamp((t - 0.2) / 0.6));\n\t\t\t\tif (icon) {\n\t\t\t\t\tconst shown = clamp((t - 0.3) / 0.7);\n\t\t\t\t\ticon.style.opacity = String(shown);\n\t\t\t\t\ticon.style.transform = `translateX(${(slide * (1 - shown)).toFixed(2)}px)`;\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tchip.style.removeProperty(\"width\");\n\t\t\t\tchip.style.removeProperty(\"opacity\");\n\t\t\t\tif (chip.getAttribute(\"style\") === \"\") chip.removeAttribute(\"style\");\n\t\t\t\tsetBoxOpacity(0);\n\t\t\t\tphaseRef.current = \"idle\";\n\t\t\t\tresetOverlay();\n\t\t\t\t// A trigger typed during the morph gets its capsule now.\n\t\t\t\tif (sessionRef.current) measureCapsule(\"appear\");\n\t\t\t},\n\t\t);\n\t};\n\n\tconst commit = (item: PromptChipItem, touch: boolean) => {\n\t\tconst session = sessionRef.current;\n\t\tconst trigger = session ? triggers[session.triggerIndex] : undefined;\n\t\tif (!session?.node.isConnected || !trigger) return;\n\t\tsettleTransition();\n\t\trecord(\"op\");\n\t\tconst kind = kindFor(trigger.kind);\n\t\tremember(trigger.kind, [item]);\n\t\tconst range = document.createRange();\n\t\trange.setStart(session.node, session.start);\n\t\trange.setEnd(session.node, session.end);\n\t\tconst rect = lastRect(range);\n\t\tconst raw = rect\n\t\t\t? { rect, text: session.node.data.slice(session.start, session.end) }\n\t\t\t: null;\n\t\tconst from =\n\t\t\tphaseRef.current === \"live\"\n\t\t\t\t? { x: boxX.get(), y: boxY.get(), w: boxW.get(), h: boxH.get() }\n\t\t\t\t: null;\n\t\tstopGeometry();\n\t\t// Swap the trigger and query for the chip and a single space.\n\t\tconst after = session.node.splitText(session.end);\n\t\tconst token = session.node.splitText(session.start);\n\t\tconst chip = createChip({\n\t\t\tkind: trigger.kind,\n\t\t\ttrigger: trigger.char,\n\t\t\tid: item.id,\n\t\t\tlabel: item.label,\n\t\t\tvalue: item.value ?? item.label,\n\t\t\tavatar: item.avatar,\n\t\t\ticon: item.icon,\n\t\t});\n\t\ttoken.replaceWith(chip);\n\t\tif (!/^[ \\u00a0]/.test(after.data)) after.insertData(0, \" \");\n\t\tplaceCaret(after, 1);\n\t\tsessionRef.current = null;\n\t\trequestRef.current++;\n\t\tsetMenu(null);\n\t\t// Icons render now, so the morph's copy of the chip has them.\n\t\tsyncIconSlots(true);\n\t\ttidy();\n\t\tlastCommitRef.current = chip;\n\t\temit();\n\t\tcue(\"commit\", touch);\n\t\tannounce(`${item.label} ${kind.action}`);\n\t\tsolidify(chip, raw, from);\n\t};\n\n\t/**\n\t * The chip turns back into its raw \"@label\" text with the caret at its\n\t * end and the menu open, and the tint drains to the live capsule.\n\t */\n\tconst melt = (chip: HTMLElement) => {\n\t\tconst editable = editableRef.current;\n\t\tconst metrics = layerMetrics();\n\t\tif (!editable || !metrics) return;\n\t\tsettleTransition();\n\t\trecord(\"op\");\n\t\tconst data = chip.dataset;\n\t\tconst kindName = data.kind ?? \"\";\n\t\tconst kind = kindFor(kindName);\n\t\tconst triggerChar = data.trigger ?? \"\";\n\t\tconst label = data.label ?? \"\";\n\t\tconst triggerIndex = Math.max(\n\t\t\ttriggers.findIndex(\n\t\t\t\t(trigger) => trigger.kind === kindName && trigger.char === triggerChar,\n\t\t\t),\n\t\t\ttriggers.findIndex((trigger) => trigger.kind === kindName),\n\t\t);\n\t\tconst chipBox = toLayer(chip.getBoundingClientRect(), metrics);\n\t\tconst clone = prepareClone(chip);\n\t\tconst rawText = triggerChar + label;\n\t\tconst text = document.createTextNode(rawText);\n\t\tchip.replaceWith(text);\n\t\tplaceCaret(text, rawText.length);\n\t\tlastCommitRef.current = null;\n\t\ttidy();\n\t\tconst caret = getCaret();\n\t\temit();\n\t\tcue(\"melt\", false);\n\t\tannounce(`${kind.label} removed, editing ${label}`);\n\t\tif (!caret || !isText(caret.node) || triggerIndex === -1) {\n\t\t\tcloseMenu();\n\t\t\treturn;\n\t\t}\n\t\tstopGeometry();\n\t\tstopFade();\n\t\tresetOverlay();\n\t\tsetKind(kindName);\n\t\tsessionRef.current = {\n\t\t\tnode: caret.node,\n\t\t\tstart: caret.offset - rawText.length,\n\t\t\tend: caret.offset,\n\t\t\ttriggerIndex,\n\t\t\tmelted: true,\n\t\t};\n\t\tannounceCountRef.current = false;\n\t\tsideRef.current = null;\n\t\tload(triggerIndex, label, null, data.id);\n\n\t\t// Where the live capsule lands, over the raw text.\n\t\tphaseRef.current = \"melt\";\n\t\tconst range = document.createRange();\n\t\trange.setStart(caret.node, caret.offset - rawText.length);\n\t\trange.setEnd(caret.node, caret.offset);\n\t\tconst rect = lastRect(range);\n\t\tconst typed = typedRef.current;\n\t\tconst labelLayer = labelRef.current;\n\t\tconst live = liveRef.current;\n\t\tconst solid = solidRef.current;\n\t\tif (!rect || !typed || !labelLayer || !live || !solid) {\n\t\t\tphaseRef.current = \"idle\";\n\t\t\tmeasureCapsule(\"appear\");\n\t\t\treturn;\n\t\t}\n\t\tconst rawBox = toLayer(rect, metrics);\n\t\tconst height = chipBox.h;\n\t\tconst target = {\n\t\t\tx: rawBox.x - CAPSULE_PAD,\n\t\t\ty: rawBox.y + rawBox.h / 2 - height / 2,\n\t\t\tw: rawBox.w + CAPSULE_PAD * 2,\n\t\t\th: height,\n\t\t};\n\t\tboxOrigin.jump(isRtl() ? 1 : 0);\n\t\tboxScale.jump(1);\n\t\tsetBoxOpacity(1);\n\t\tif (reducedMotion) {\n\t\t\tboxX.jump(target.x);\n\t\t\tboxY.jump(target.y);\n\t\t\tboxW.jump(target.w);\n\t\t\tboxH.jump(target.h);\n\t\t\tsetBoxOpacity(0);\n\t\t\tphaseRef.current = \"live\";\n\t\t\tfadeRef.current = [fadeBox(1, FADE_MS)];\n\t\t\tmeasureCapsule(\"jump\");\n\t\t\treturn;\n\t\t}\n\t\tlabelLayer.replaceChildren(clone);\n\t\ttyped.textContent = rawText;\n\t\ttyped.style.lineHeight = `${rawBox.h}px`;\n\t\tCSS.highlights?.set(HIDDEN_HIGHLIGHT, new Highlight(range));\n\t\t// A spacer holds the chip's extra width and shrinks away, so text after\n\t\t// the chip glides back instead of jumping.\n\t\tconst extra = chipBox.w - rawBox.w;\n\t\tconst spacer = document.createElement(\"span\");\n\t\tspacer.contentEditable = \"false\";\n\t\tspacer.setAttribute(\"aria-hidden\", \"true\");\n\t\tspacer.style.cssText = \"display:inline-block;height:1px\";\n\t\tif (extra > 0.5) {\n\t\t\tcaret.node.parentNode?.insertBefore(\n\t\t\t\tspacer,\n\t\t\t\tcaret.node.splitText(caret.offset),\n\t\t\t);\n\t\t\tplaceCaret(caret.node, caret.offset);\n\t\t}\n\t\tconst icon = clone.querySelector<HTMLElement>(\n\t\t\t'[data-slot=\"prompt-chip-icon\"]',\n\t\t);\n\t\tconst slide = isRtl() ? ICON_SLIDE : -ICON_SLIDE;\n\t\trunTransition(\n\t\t\t{ duration: MELT_MS / 1000, ease: \"linear\" },\n\t\t\t(progress) => {\n\t\t\t\tconst t = easeOut(progress);\n\t\t\t\tconst x = lerp(chipBox.x, target.x, t);\n\t\t\t\tconst y = lerp(chipBox.y, target.y, t);\n\t\t\t\tboxX.jump(x);\n\t\t\t\tboxY.jump(y);\n\t\t\t\tboxW.jump(lerp(chipBox.w, target.w, t));\n\t\t\t\tboxH.jump(lerp(chipBox.h, target.h, t));\n\t\t\t\tsolid.style.opacity = String(1 - t);\n\t\t\t\tlive.style.opacity = String(t);\n\t\t\t\tclone.style.left = `${chipBox.x - x}px`;\n\t\t\t\tclone.style.top = `${chipBox.y - y}px`;\n\t\t\t\tclone.style.opacity = String(1 - clamp(t * 2));\n\t\t\t\tclone.style.filter = `blur(${(t * 1.5).toFixed(2)}px)`;\n\t\t\t\tif (icon) {\n\t\t\t\t\ticon.style.transform = `translateX(${(slide * t).toFixed(2)}px)`;\n\t\t\t\t}\n\t\t\t\ttyped.style.left = `${rawBox.x - x}px`;\n\t\t\t\ttyped.style.top = `${rawBox.y - y}px`;\n\t\t\t\ttyped.style.opacity = String(clamp((t - 0.4) / 0.6));\n\t\t\t\tspacer.style.width = `${(Math.max(extra, 0) * (1 - t)).toFixed(2)}px`;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (spacer.isConnected) {\n\t\t\t\t\tspacer.remove();\n\t\t\t\t\ttidy();\n\t\t\t\t}\n\t\t\t\tresetOverlay();\n\t\t\t\tphaseRef.current = \"live\";\n\t\t\t\tif (sessionRef.current) measureCapsule(\"jump\");\n\t\t\t\telse hideCapsule();\n\t\t\t},\n\t\t);\n\t};\n\n\tconst removeChip = (chip: HTMLElement) => {\n\t\trecord(\"op\");\n\t\tconst label = chip.dataset.label ?? \"\";\n\t\tconst parent = chip.parentNode;\n\t\tconst index = parent\n\t\t\t? Array.prototype.indexOf.call(parent.childNodes, chip)\n\t\t\t: -1;\n\t\tchip.remove();\n\t\tif (parent && index >= 0) placeCaret(parent, index);\n\t\tlastCommitRef.current = null;\n\t\ttidy();\n\t\tsyncIconSlots();\n\t\temit();\n\t\tannounce(`${label} removed`);\n\t};\n\n\t/** Puts text and chips at the selection, replacing it. */\n\tconst insertSegments = (segments: Segment[]) => {\n\t\tconst editable = editableRef.current;\n\t\tif (!editable) return;\n\t\tsettleTransition();\n\t\trecord(\"op\");\n\t\tlet range = selectionRange();\n\t\tif (!range) {\n\t\t\teditable.focus({ preventScroll: true });\n\t\t\tsetCaretOffset(Number.MAX_SAFE_INTEGER);\n\t\t\trange = selectionRange();\n\t\t}\n\t\tif (!range) return;\n\t\trange.deleteContents();\n\t\tconst fragment = buildFragment(segments);\n\t\tconst last = fragment.lastChild;\n\t\tif (last) {\n\t\t\trange.insertNode(fragment);\n\t\t\tif (isText(last)) placeCaret(last, last.data.length);\n\t\t\telse if (last.parentNode) {\n\t\t\t\tplaceCaret(\n\t\t\t\t\tlast.parentNode,\n\t\t\t\t\tArray.from(last.parentNode.childNodes).indexOf(last as ChildNode) + 1,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tlastCommitRef.current = null;\n\t\tcloseMenu();\n\t\tsyncIconSlots();\n\t\ttidy();\n\t\temit();\n\t};\n\n\tconst clear = () => {\n\t\tsettleTransition();\n\t\trecord(\"op\");\n\t\tcloseMenu();\n\t\tdismissedRef.current = null;\n\t\tlastCommitRef.current = null;\n\t\trender([]);\n\t\tif (document.activeElement === editableRef.current) setCaretOffset(0);\n\t\temit();\n\t};\n\n\tconst restore = (snap: Snapshot) => {\n\t\tsettleTransition();\n\t\tcloseMenu();\n\t\trender(snap.segments);\n\t\tif (snap.caret !== null && document.activeElement === editableRef.current) {\n\t\t\tsetCaretOffset(snap.caret);\n\t\t}\n\t\temit();\n\t};\n\n\tconst undo = () => {\n\t\tconst history = historyRef.current;\n\t\tconst previous = history.past.pop();\n\t\tif (!previous) return;\n\t\thistory.future.push(snapshot());\n\t\thistory.lastKind = \"op\";\n\t\trestore(previous);\n\t};\n\n\tconst redo = () => {\n\t\tconst history = historyRef.current;\n\t\tconst next = history.future.pop();\n\t\tif (!next) return;\n\t\thistory.past.push(snapshot());\n\t\thistory.lastKind = \"op\";\n\t\trestore(next);\n\t};\n\n\tconst submit = () => {\n\t\tconst value = toValue(read());\n\t\tif (!value.text.trim() && value.chips.length === 0) return;\n\t\tonSubmit?.(value);\n\t\tif (clearOnSubmit) clear();\n\t};\n\n\tconst insertChipAt = (kindName: string, item: PromptChipItem) => {\n\t\tconst editable = editableRef.current;\n\t\tif (!editable || disabled) return;\n\t\tsettleTransition();\n\t\tcloseMenu();\n\t\tif (!selectionRange()) {\n\t\t\teditable.focus({ preventScroll: true });\n\t\t\tsetCaretOffset(Number.MAX_SAFE_INTEGER);\n\t\t}\n\t\tconst range = selectionRange();\n\t\tif (!range) return;\n\t\trecord(\"op\");\n\t\tremember(kindName, [item]);\n\t\trange.deleteContents();\n\t\tconst chip = createChip({\n\t\t\tkind: kindName,\n\t\t\ttrigger:\n\t\t\t\ttriggers.find((trigger) => trigger.kind === kindName)?.char ?? \"\",\n\t\t\tid: item.id,\n\t\t\tlabel: item.label,\n\t\t\tvalue: item.value ?? item.label,\n\t\t\tavatar: item.avatar,\n\t\t\ticon: item.icon,\n\t\t});\n\t\trange.insertNode(chip);\n\t\tconst next = chip.nextSibling;\n\t\tif (isText(next) && /^[ \\u00a0]/.test(next.data)) {\n\t\t\tplaceCaret(next, 1);\n\t\t} else {\n\t\t\tconst space = document.createTextNode(\" \");\n\t\t\tchip.parentNode?.insertBefore(space, chip.nextSibling);\n\t\t\tplaceCaret(space, 1);\n\t\t}\n\t\tsyncIconSlots(true);\n\t\ttidy();\n\t\tlastCommitRef.current = chip;\n\t\temit();\n\t\tchip.animate([{ opacity: 0 }, { opacity: 1 }], {\n\t\t\tduration: reducedMotion ? FADE_MS : 160,\n\t\t\teasing: \"ease-out\",\n\t\t});\n\t};\n\n\tuseImperativeHandle(ref, () => ({\n\t\tfocus: () => {\n\t\t\teditableRef.current?.focus({ preventScroll: true });\n\t\t\tsetCaretOffset(Number.MAX_SAFE_INTEGER);\n\t\t},\n\t\tclear,\n\t\tinsertChip: insertChipAt,\n\t\tgetValue: () => toValue(read()),\n\t}));\n\n\t// --- Event handlers ------------------------------------------------------\n\n\tconst afterInput = () => {\n\t\tlastCommitRef.current = null;\n\t\ttidy();\n\t\tsyncIconSlots();\n\t\temit();\n\t\tdetect();\n\t};\n\n\tconst handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n\t\tif (disabled) return;\n\t\t// IME composition owns Enter, Tab, and the arrows.\n\t\tif (\n\t\t\tcomposingRef.current ||\n\t\t\tevent.nativeEvent.isComposing ||\n\t\t\tevent.keyCode === 229\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\ttouchRef.current = false;\n\t\tconst mod = event.metaKey || event.ctrlKey;\n\t\tconst key = event.key;\n\t\tif (mod && !event.altKey && (key === \"z\" || key === \"Z\" || key === \"y\")) {\n\t\t\tevent.preventDefault();\n\t\t\tif (key === \"y\" || event.shiftKey) redo();\n\t\t\telse undo();\n\t\t\treturn;\n\t\t}\n\t\tconst state = menuRef.current;\n\t\tif (state) {\n\t\t\tconst count = state.results.length;\n\t\t\tconst down = key === \"ArrowDown\" || (event.ctrlKey && key === \"n\");\n\t\t\tconst up = key === \"ArrowUp\" || (event.ctrlKey && key === \"p\");\n\t\t\tif (down || up) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tsetMenu({\n\t\t\t\t\t\t...state,\n\t\t\t\t\t\tactive: (state.active + (down ? 1 : -1) + count) % count,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ((key === \"Enter\" || key === \"Tab\") && !event.shiftKey && !mod) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tconst item = state.results[state.active];\n\t\t\t\tif (item) commit(item, false);\n\t\t\t\t// No match: the typed text stays as plain text.\n\t\t\t\telse if (!state.loading) dismiss();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (key === \"Escape\") {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tevent.stopPropagation();\n\t\t\t\tdismiss();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (key === \" \" && !triggers[state.triggerIndex]?.allowSpaces) {\n\t\t\t\tconst query = state.query.toLowerCase();\n\t\t\t\tconst exact = state.results.filter(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\titem.label.toLowerCase() === query ||\n\t\t\t\t\t\t(item.value ?? \"\").toLowerCase() === query,\n\t\t\t\t);\n\t\t\t\tif (query && exact.length === 1) {\n\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\tcommit(exact[0], false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcloseMenu();\n\t\t\t}\n\t\t}\n\t\tif (key === \"Enter\" && !event.shiftKey) {\n\t\t\tevent.preventDefault();\n\t\t\tsubmit();\n\t\t\treturn;\n\t\t}\n\t\tif (key === \"Backspace\" && !event.altKey && !mod) {\n\t\t\tconst chip = chipBeforeCaret(meltOnBackspace);\n\t\t\tif (!chip) return;\n\t\t\tevent.preventDefault();\n\t\t\tif (meltOnBackspace) melt(chip);\n\t\t\telse removeChip(chip);\n\t\t\treturn;\n\t\t}\n\t\tif (key === \"Delete\" && !event.altKey && !mod) {\n\t\t\tconst chip = chipAfterCaret();\n\t\t\tif (!chip) return;\n\t\t\tevent.preventDefault();\n\t\t\tremoveChip(chip);\n\t\t}\n\t};\n\n\tconst handleBeforeInput = (event: InputEvent) => {\n\t\tif (disabled) {\n\t\t\tevent.preventDefault();\n\t\t\treturn;\n\t\t}\n\t\tconst type = event.inputType;\n\t\tif (type === \"insertParagraph\" || type === \"insertLineBreak\") {\n\t\t\tevent.preventDefault();\n\t\t\tinsertSegments([{ type: \"text\", text: \"\\n\" }]);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"historyUndo\" || type === \"historyRedo\") {\n\t\t\tevent.preventDefault();\n\t\t\tif (type === \"historyUndo\") undo();\n\t\t\telse redo();\n\t\t\treturn;\n\t\t}\n\t\tif (type.startsWith(\"format\")) {\n\t\t\tevent.preventDefault();\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"insertFromDrop\" || type.startsWith(\"insertFromPaste\")) return;\n\t\tif (type.startsWith(\"delete\")) record(\"delete\");\n\t\telse if (type.startsWith(\"insert\") && !composingRef.current) record(\"type\");\n\t};\n\n\tconst writeClipboard = (data: DataTransfer, segments: Segment[]) => {\n\t\tdata.setData(\"text/plain\", serialize(segments, \"label\"));\n\t\tdata.setData(\n\t\t\tCLIPBOARD_TYPE,\n\t\t\tJSON.stringify(\n\t\t\t\tsegments.map((segment) =>\n\t\t\t\t\tsegment.type === \"text\"\n\t\t\t\t\t\t? segment\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\ttype: \"chip\",\n\t\t\t\t\t\t\t\tkind: segment.kind,\n\t\t\t\t\t\t\t\ttrigger: segment.trigger,\n\t\t\t\t\t\t\t\tid: segment.id,\n\t\t\t\t\t\t\t\tlabel: segment.label,\n\t\t\t\t\t\t\t\tvalue: segment.value,\n\t\t\t\t\t\t\t\tavatar: segment.avatar,\n\t\t\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t};\n\n\tconst handleCopy = (event: ClipboardEvent<HTMLDivElement>) => {\n\t\tconst range = selectionRange();\n\t\tif (!range || range.collapsed) return;\n\t\tevent.preventDefault();\n\t\twriteClipboard(\n\t\t\tevent.clipboardData,\n\t\t\treadSegments(range.cloneContents(), chipIconsRef.current),\n\t\t);\n\t};\n\n\tconst handleCut = (event: ClipboardEvent<HTMLDivElement>) => {\n\t\tconst range = selectionRange();\n\t\tif (!range || range.collapsed) return;\n\t\tevent.preventDefault();\n\t\tif (disabled) return;\n\t\twriteClipboard(\n\t\t\tevent.clipboardData,\n\t\t\treadSegments(range.cloneContents(), chipIconsRef.current),\n\t\t);\n\t\trecord(\"op\");\n\t\trange.deleteContents();\n\t\tcloseMenu();\n\t\ttidy();\n\t\tsyncIconSlots();\n\t\temit();\n\t};\n\n\t/** Chips from our own clipboard type; anything else pastes as plain text. */\n\tconst pastedSegments = (data: DataTransfer): Segment[] => {\n\t\tconst json = data.getData(CLIPBOARD_TYPE);\n\t\tif (json) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(json) as unknown;\n\t\t\t\tif (Array.isArray(parsed)) {\n\t\t\t\t\tconst segments: PromptChipSegment[] = [];\n\t\t\t\t\tfor (const entry of parsed) {\n\t\t\t\t\t\tif (entry?.type === \"text\" && typeof entry.text === \"string\") {\n\t\t\t\t\t\t\tsegments.push({ type: \"text\", text: entry.text });\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\tentry?.type === \"chip\" &&\n\t\t\t\t\t\t\ttypeof entry.id === \"string\" &&\n\t\t\t\t\t\t\ttypeof entry.label === \"string\" &&\n\t\t\t\t\t\t\ttypeof entry.kind === \"string\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst item = lookupItem(entry.kind, entry.id);\n\t\t\t\t\t\t\tsegments.push({\n\t\t\t\t\t\t\t\ttype: \"chip\",\n\t\t\t\t\t\t\t\tkind: entry.kind,\n\t\t\t\t\t\t\t\ttrigger:\n\t\t\t\t\t\t\t\t\ttypeof entry.trigger === \"string\" ? entry.trigger : undefined,\n\t\t\t\t\t\t\t\tid: entry.id,\n\t\t\t\t\t\t\t\tlabel: entry.label,\n\t\t\t\t\t\t\t\tvalue:\n\t\t\t\t\t\t\t\t\ttypeof entry.value === \"string\" ? entry.value : undefined,\n\t\t\t\t\t\t\t\tavatar:\n\t\t\t\t\t\t\t\t\ttypeof entry.avatar === \"string\"\n\t\t\t\t\t\t\t\t\t\t? entry.avatar\n\t\t\t\t\t\t\t\t\t\t: item?.avatar,\n\t\t\t\t\t\t\t\ticon: item?.icon,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn normalizeSegments(segments, triggers);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Fall back to the plain text below.\n\t\t\t}\n\t\t}\n\t\tconst text = data.getData(\"text/plain\").replace(/\\r\\n?/g, \"\\n\");\n\t\treturn text ? [{ type: \"text\", text }] : [];\n\t};\n\n\tconst handlePaste = (event: ClipboardEvent<HTMLDivElement>) => {\n\t\tevent.preventDefault();\n\t\tif (disabled) return;\n\t\tinsertSegments(pastedSegments(event.clipboardData));\n\t};\n\n\tconst handleDrop = (event: DragEvent<HTMLDivElement>) => {\n\t\tevent.preventDefault();\n\t\tif (disabled) return;\n\t\tconst segments = pastedSegments(event.dataTransfer);\n\t\tconst position = document.caretPositionFromPoint?.(\n\t\t\tevent.clientX,\n\t\t\tevent.clientY,\n\t\t);\n\t\tif (position && editableRef.current?.contains(position.offsetNode)) {\n\t\t\teditableRef.current.focus({ preventScroll: true });\n\t\t\tplaceCaret(position.offsetNode, position.offset);\n\t\t}\n\t\tinsertSegments(segments);\n\t};\n\n\tconst handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {\n\t\ttouchRef.current = event.pointerType === \"touch\";\n\t\tlastCommitRef.current = null;\n\t};\n\n\t// A click on a chip puts the caret beside it, on the nearer side.\n\tconst handleMouseDown = (event: MouseEvent<HTMLDivElement>) => {\n\t\tconst chip = (event.target as Element).closest?.(\n\t\t\t'[data-slot=\"prompt-chip\"]',\n\t\t);\n\t\tconst editable = editableRef.current;\n\t\tif (!chip || !editable || disabled || chip.parentNode !== editable) return;\n\t\tevent.preventDefault();\n\t\teditable.focus({ preventScroll: true });\n\t\tconst rect = chip.getBoundingClientRect();\n\t\tconst after = event.clientX > rect.left + rect.width / 2 !== isRtl();\n\t\tconst index = Array.from(editable.childNodes).indexOf(chip as ChildNode);\n\t\tplaceCaret(editable, index + (after ? 1 : 0));\n\t};\n\n\tconst handleRowPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n\t\t// Keeps focus, and the caret, in the field.\n\t\tevent.preventDefault();\n\t\tpointerTypeRef.current = event.pointerType;\n\t};\n\n\tconst handleCompositionStart = () => {\n\t\tcomposingRef.current = true;\n\t\trecord(\"type\");\n\t\thideGhost();\n\t};\n\n\tconst handleCompositionEnd = () => {\n\t\tcomposingRef.current = false;\n\t\tafterInput();\n\t};\n\n\tconst handleFocus = () => setFocused(true);\n\n\tconst handleBlur = () => {\n\t\tsetFocused(false);\n\t\tcloseMenu();\n\t};\n\n\t// --- Effects -------------------------------------------------------------\n\n\t// Event listeners and timers call through refs to see the latest render.\n\tconst handlers = useRef({\n\t\tbeforeInput: handleBeforeInput,\n\t\tselectionChange: () => {},\n\t\tremeasure: () => {},\n\t\tposition: () => {},\n\t});\n\tconst positionPopover = () => {\n\t\tconst list = listRef.current;\n\t\tconst root = rootRef.current;\n\t\tconst anchor = anchorRef.current;\n\t\tif (!list || !root || !anchor) return;\n\t\tconst zoom = cssZoom(root);\n\t\tconst rootRect = root.getBoundingClientRect();\n\t\tconst width = list.offsetWidth * zoom;\n\t\tconst height = list.offsetHeight * zoom;\n\t\tconst viewportWidth = document.documentElement.clientWidth;\n\t\tconst viewportHeight = window.innerHeight;\n\t\tconst gap = POPOVER_GAP * zoom;\n\t\tconst below = anchor.bottom + gap;\n\t\tconst above = anchor.top - gap - height;\n\t\tconst fitsBelow = below + height <= viewportHeight - VIEWPORT_PAD;\n\t\tconst fitsAbove = above >= VIEWPORT_PAD;\n\t\t// Keep the side the list opened on while the query changes.\n\t\tlet side = sideRef.current;\n\t\tif (!side || (side === \"bottom\" && !fitsBelow && fitsAbove)) {\n\t\t\tside = fitsBelow || !fitsAbove ? \"bottom\" : \"top\";\n\t\t}\n\t\tsideRef.current = side;\n\t\tconst top = side === \"bottom\" ? below : above;\n\t\tconst preferred = isRtl() ? anchor.right - width : anchor.left;\n\t\tconst left = clamp(\n\t\t\tpreferred,\n\t\t\tVIEWPORT_PAD,\n\t\t\tMath.max(VIEWPORT_PAD, viewportWidth - VIEWPORT_PAD - width),\n\t\t);\n\t\tlist.style.left = `${(left - rootRect.left) / zoom}px`;\n\t\tlist.style.top = `${(top - rootRect.top) / zoom}px`;\n\t\tlist.dataset.side = side;\n\t};\n\n\tuseLayoutEffect(() => {\n\t\thandlers.current = {\n\t\t\tbeforeInput: handleBeforeInput,\n\t\t\tselectionChange: () => {\n\t\t\t\tif (composingRef.current) return;\n\t\t\t\tconst session = sessionRef.current;\n\t\t\t\tif (!session) return;\n\t\t\t\tconst caret = getCaret();\n\t\t\t\tif (caret?.node !== session.node || caret.offset !== session.end) {\n\t\t\t\t\tcloseMenu();\n\t\t\t\t}\n\t\t\t},\n\t\t\tremeasure: () => {\n\t\t\t\tif (sessionRef.current && phaseRef.current === \"live\") {\n\t\t\t\t\tmeasureCapsule(\"jump\");\n\t\t\t\t\tpositionPopover();\n\t\t\t\t}\n\t\t\t},\n\t\t\tposition: positionPopover,\n\t\t};\n\t});\n\n\t// Builds the field from its segments once mounted, so chips carry their\n\t// data and icons. The server already rendered the same markup.\n\t// biome-ignore lint/correctness/useExhaustiveDependencies: mount only\n\tuseLayoutEffect(() => {\n\t\trender(initial);\n\t\tconst editable = editableRef.current;\n\t\tconst onBeforeInput = (event: InputEvent) =>\n\t\t\thandlers.current.beforeInput(event);\n\t\teditable?.addEventListener(\"beforeinput\", onBeforeInput);\n\t\treturn () => {\n\t\t\teditable?.removeEventListener(\"beforeinput\", onBeforeInput);\n\t\t\ttransitionRef.current?.finish();\n\t\t};\n\t}, []);\n\n\t// A controlled value re-renders the field only when it differs from what\n\t// the field last reported.\n\tconst controlledKey =\n\t\tvalueProp === undefined\n\t\t\t? null\n\t\t\t: segmentsKey(normalizeSegments(valueProp, triggers));\n\t// biome-ignore lint/correctness/useExhaustiveDependencies: keyed by content\n\tuseLayoutEffect(() => {\n\t\tif (controlledKey === null || controlledKey === lastKeyRef.current) return;\n\t\tsettleTransition();\n\t\tcloseMenu();\n\t\trender(normalizeSegments(valueProp, triggers));\n\t\tlastKeyRef.current = controlledKey;\n\t\tsetEmpty(controlledKey === \"[]\");\n\t\tif (document.activeElement === editableRef.current) {\n\t\t\tsetCaretOffset(Number.MAX_SAFE_INTEGER);\n\t\t}\n\t}, [controlledKey]);\n\n\t// Listeners exist only while the field has focus.\n\tuseEffect(() => {\n\t\tconst editable = editableRef.current;\n\t\tif (!focused || !editable) return;\n\t\tconst onSelectionChange = () => handlers.current.selectionChange();\n\t\tdocument.addEventListener(\"selectionchange\", onSelectionChange);\n\t\tconst observer = new ResizeObserver(() => handlers.current.remeasure());\n\t\tobserver.observe(editable);\n\t\treturn () => {\n\t\t\tdocument.removeEventListener(\"selectionchange\", onSelectionChange);\n\t\t\tobserver.disconnect();\n\t\t};\n\t}, [focused]);\n\n\tconst open = menu !== null;\n\tuseEffect(() => {\n\t\tif (!open) return;\n\t\tconst onResize = () => handlers.current.remeasure();\n\t\twindow.addEventListener(\"resize\", onResize);\n\t\treturn () => window.removeEventListener(\"resize\", onResize);\n\t}, [open]);\n\n\t// biome-ignore lint/correctness/useExhaustiveDependencies: follows the menu\n\tuseLayoutEffect(() => {\n\t\t// A new best match changes the completion the capsule spans.\n\t\tif (sessionRef.current && phaseRef.current === \"live\") {\n\t\t\tmeasureCapsule(\"grow\");\n\t\t} else updateGhost();\n\t\tif (!menu) {\n\t\t\thighlightShownRef.current = false;\n\t\t\treturn;\n\t\t}\n\t\tpositionPopover();\n\t\tconst row = rowRefs.current[menu.active];\n\t\tif (!row || menu.results.length === 0) {\n\t\t\thighlightShownRef.current = false;\n\t\t\treturn;\n\t\t}\n\t\tif (!highlightShownRef.current || reducedMotion) {\n\t\t\thighlightY.jump(row.offsetTop);\n\t\t\thighlightH.jump(row.offsetHeight);\n\t\t} else {\n\t\t\tanimate(highlightY, row.offsetTop, highlightSpring);\n\t\t\tanimate(highlightH, row.offsetHeight, highlightSpring);\n\t\t}\n\t\thighlightShownRef.current = true;\n\t}, [menu]);\n\n\t// --- Render --------------------------------------------------------------\n\n\tconst kind = kindFor(capsuleKind);\n\tconst menuTrigger = menu ? triggers[menu.triggerIndex] : undefined;\n\tconst menuKind = menuTrigger ? kindFor(menuTrigger.kind) : kind;\n\tconst activeItem = menu?.results[menu.active];\n\n\treturn (\n\t\t<LazyMotion features={domAnimation}>\n\t\t\t<div\n\t\t\t\tref={rootRef}\n\t\t\t\tdata-slot=\"prompt-chip-input\"\n\t\t\t\tdata-disabled={disabled || undefined}\n\t\t\t\tdata-open={open || undefined}\n\t\t\t\tclassName={cn(\n\t\t\t\t\t\"relative flex w-full min-w-0 flex-col gap-2 rounded-2xl border border-border bg-background px-4 py-3 pointer-coarse:text-base text-[15px] text-foreground leading-6 transition-[border-color,box-shadow] duration-150 has-[[data-slot=prompt-chip-input-editable]:focus-visible]:border-ring/60 has-[[data-slot=prompt-chip-input-editable]:focus-visible]:ring-3 has-[[data-slot=prompt-chip-input-editable]:focus-visible]:ring-ring/15 data-disabled:opacity-60\",\n\t\t\t\t\tclassName,\n\t\t\t\t)}\n\t\t\t\t{...props}\n\t\t\t>\n\t\t\t\t<style href=\"tentui-prompt-chip-input\" precedence=\"default\">\n\t\t\t\t\t{STYLES}\n\t\t\t\t</style>\n\t\t\t\t<div data-slot=\"prompt-chip-input-field\" className=\"relative\">\n\t\t\t\t\t{/* Capsule and ghost text sit behind the transparent text layer. It\n\t\t\t\t\toverhangs the text by the capsule's padding and clips lines\n\t\t\t\t\tscrolled out of view. */}\n\t\t\t\t\t<div\n\t\t\t\t\t\tref={layerRef}\n\t\t\t\t\t\taria-hidden\n\t\t\t\t\t\tdata-slot=\"prompt-chip-input-overlay\"\n\t\t\t\t\t\tclassName=\"pointer-events-none absolute inset-y-0 overflow-hidden\"\n\t\t\t\t\t\tstyle={{ left: -CAPSULE_PAD, right: -CAPSULE_PAD }}\n\t\t\t\t\t>\n\t\t\t\t\t\t<m.span\n\t\t\t\t\t\t\tref={boxRef}\n\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-capsule\"\n\t\t\t\t\t\t\tdata-kind={capsuleKind}\n\t\t\t\t\t\t\tclassName=\"absolute top-0 left-0 overflow-hidden rounded-md opacity-0\"\n\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\tx: boxX,\n\t\t\t\t\t\t\t\ty: boxY,\n\t\t\t\t\t\t\t\twidth: boxW,\n\t\t\t\t\t\t\t\theight: boxH,\n\t\t\t\t\t\t\t\tscaleX: boxScale,\n\t\t\t\t\t\t\t\toriginX: boxOrigin,\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tref={liveRef}\n\t\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-capsule-live\"\n\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\tkind.className,\n\t\t\t\t\t\t\t\t\t\"absolute inset-0 rounded-[inherit] bg-transparent\",\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{/* A lighter wash of the chip's own tint, so committing\n\t\t\t\t\t\t\t\treads as the capsule settling in. */}\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\tkind.className,\n\t\t\t\t\t\t\t\t\t\t\"absolute inset-0 rounded-[inherit] opacity-80\",\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tref={solidRef}\n\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\"absolute inset-0 rounded-[inherit] opacity-0\",\n\t\t\t\t\t\t\t\t\tkind.className,\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tref={typedRef}\n\t\t\t\t\t\t\t\tclassName=\"absolute top-0 left-0 whitespace-pre text-foreground\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t<span ref={labelRef} className=\"absolute inset-0\" />\n\t\t\t\t\t\t</m.span>\n\t\t\t\t\t\t<span\n\t\t\t\t\t\t\tref={ghostRef}\n\t\t\t\t\t\t\thidden\n\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-ghost\"\n\t\t\t\t\t\t\tclassName=\"absolute top-0 left-0 whitespace-pre\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span ref={ghostTextRef} className=\"text-foreground/40\" />\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tref={spinnerRef}\n\t\t\t\t\t\t\t\thidden\n\t\t\t\t\t\t\t\tstyle={{ marginInlineStart: CAPSULE_PAD + SPINNER_GAP }}\n\t\t\t\t\t\t\t\tclassName=\"inline-block size-3 animate-spin rounded-full border-[1.5px] border-foreground/15 border-t-foreground/50 align-[-0.1em] motion-reduce:animate-none\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t{/* biome-ignore lint/a11y/useAriaPropsSupportedByRole: ARIA has no multiline combobox, so the textbox carries the combobox state screen readers follow. */}\n\t\t\t\t\t<div\n\t\t\t\t\t\tref={editableRef}\n\t\t\t\t\t\trole=\"textbox\"\n\t\t\t\t\t\ttabIndex={disabled ? undefined : 0}\n\t\t\t\t\t\tcontentEditable={!disabled}\n\t\t\t\t\t\tsuppressContentEditableWarning\n\t\t\t\t\t\tspellCheck={false}\n\t\t\t\t\t\tautoCorrect=\"off\"\n\t\t\t\t\t\tautoCapitalize=\"off\"\n\t\t\t\t\t\taria-multiline\n\t\t\t\t\t\taria-label={ariaLabelledBy ? ariaLabel : (ariaLabel ?? \"Message\")}\n\t\t\t\t\t\taria-labelledby={ariaLabelledBy}\n\t\t\t\t\t\taria-placeholder={placeholder}\n\t\t\t\t\t\taria-disabled={disabled || undefined}\n\t\t\t\t\t\taria-autocomplete=\"list\"\n\t\t\t\t\t\taria-expanded={open || undefined}\n\t\t\t\t\t\taria-controls={open ? listId : undefined}\n\t\t\t\t\t\taria-activedescendant={\n\t\t\t\t\t\t\topen && activeItem ? optionId(menu.active) : undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdata-slot=\"prompt-chip-input-editable\"\n\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\"relative min-h-12 overflow-y-auto whitespace-pre-wrap break-words outline-none [overflow-wrap:anywhere]\",\n\t\t\t\t\t\t\tdisabled && \"cursor-not-allowed\",\n\t\t\t\t\t\t\teditableClassName,\n\t\t\t\t\t\t)}\n\t\t\t\t\t\tstyle={{ maxHeight: `${maxRows * 1.5}rem` }}\n\t\t\t\t\t\tdangerouslySetInnerHTML={initialHtml}\n\t\t\t\t\t\tonKeyDown={handleKeyDown}\n\t\t\t\t\t\tonInput={() => {\n\t\t\t\t\t\t\tif (!composingRef.current) afterInput();\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tonCompositionStart={handleCompositionStart}\n\t\t\t\t\t\tonCompositionEnd={handleCompositionEnd}\n\t\t\t\t\t\tonCopy={handleCopy}\n\t\t\t\t\t\tonCut={handleCut}\n\t\t\t\t\t\tonPaste={handlePaste}\n\t\t\t\t\t\tonDrop={handleDrop}\n\t\t\t\t\t\tonDragStart={(event) => event.preventDefault()}\n\t\t\t\t\t\tonPointerDown={handlePointerDown}\n\t\t\t\t\t\tonMouseDown={handleMouseDown}\n\t\t\t\t\t\tonScroll={() => handlers.current.remeasure()}\n\t\t\t\t\t\tonFocus={handleFocus}\n\t\t\t\t\t\tonBlur={handleBlur}\n\t\t\t\t\t/>\n\t\t\t\t\t{empty && placeholder ? (\n\t\t\t\t\t\t<span\n\t\t\t\t\t\t\taria-hidden\n\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-placeholder\"\n\t\t\t\t\t\t\tclassName=\"pointer-events-none absolute inset-x-0 top-0 truncate text-muted-foreground\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{placeholder}\n\t\t\t\t\t\t</span>\n\t\t\t\t\t) : null}\n\t\t\t\t</div>\n\t\t\t\t{children}\n\t\t\t\t<AnimatePresence>\n\t\t\t\t\t{menu ? (\n\t\t\t\t\t\t<m.div\n\t\t\t\t\t\t\tkey=\"list\"\n\t\t\t\t\t\t\tref={listRef}\n\t\t\t\t\t\t\tid={listId}\n\t\t\t\t\t\t\trole=\"listbox\"\n\t\t\t\t\t\t\taria-label={`${menuKind.label} suggestions`}\n\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-list\"\n\t\t\t\t\t\t\tinitial={reducedMotion ? false : { opacity: 0, y: 4 }}\n\t\t\t\t\t\t\tanimate={{\n\t\t\t\t\t\t\t\topacity: 1,\n\t\t\t\t\t\t\t\ty: 0,\n\t\t\t\t\t\t\t\ttransition: { duration: APPEAR_MS / 1000, ease: \"easeOut\" },\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\texit={{\n\t\t\t\t\t\t\t\topacity: 0,\n\t\t\t\t\t\t\t\ttransition: { duration: reducedMotion ? 0 : 0.08 },\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t// Keeps the fade on motion's frame loop, which video capture steps.\n\t\t\t\t\t\t\tonUpdate={() => {}}\n\t\t\t\t\t\t\tonPointerDown={handleRowPointerDown}\n\t\t\t\t\t\t\tonMouseDown={(event) => event.preventDefault()}\n\t\t\t\t\t\t\tclassName=\"absolute top-0 left-0 z-50 w-64 max-w-[calc(100vw-16px)] rounded-xl border border-border bg-popover p-1 text-popover-foreground text-sm leading-5 shadow-sm\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<m.div\n\t\t\t\t\t\t\t\taria-hidden\n\t\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-highlight\"\n\t\t\t\t\t\t\t\tclassName=\"absolute inset-x-1 top-0 rounded-lg bg-accent\"\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\ty: highlightY,\n\t\t\t\t\t\t\t\t\theight: highlightH,\n\t\t\t\t\t\t\t\t\topacity: menu.results.length > 0 ? 1 : 0,\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{menu.results.map((item, index) => {\n\t\t\t\t\t\t\t\tconst itemKind = menuTrigger\n\t\t\t\t\t\t\t\t\t? kindFor(menuTrigger.kind)\n\t\t\t\t\t\t\t\t\t: menuKind;\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tkey={item.id}\n\t\t\t\t\t\t\t\t\t\tref={(node) => {\n\t\t\t\t\t\t\t\t\t\t\trowRefs.current[index] = node;\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tid={optionId(index)}\n\t\t\t\t\t\t\t\t\t\trole=\"option\"\n\t\t\t\t\t\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\t\t\t\t\t\taria-selected={index === menu.active}\n\t\t\t\t\t\t\t\t\t\tdata-active={index === menu.active || undefined}\n\t\t\t\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-option\"\n\t\t\t\t\t\t\t\t\t\tclassName=\"relative flex min-h-9 pointer-coarse:min-h-10 cursor-pointer select-none items-center gap-2.5 rounded-lg px-2 py-1.5\"\n\t\t\t\t\t\t\t\t\t\tonPointerMove={(event) => {\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tevent.pointerType === \"mouse\" &&\n\t\t\t\t\t\t\t\t\t\t\t\tmenuRef.current &&\n\t\t\t\t\t\t\t\t\t\t\t\tmenuRef.current.active !== index\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\tsetMenu({ ...menuRef.current, active: index });\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tonClick={() =>\n\t\t\t\t\t\t\t\t\t\t\tcommit(item, pointerTypeRef.current === \"touch\")\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<ItemIcon\n\t\t\t\t\t\t\t\t\t\t\tspec={iconSpec(item, itemKind)}\n\t\t\t\t\t\t\t\t\t\t\tlabel={item.label}\n\t\t\t\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\t\t\t\"me-0 size-5 shrink-0 align-middle\",\n\t\t\t\t\t\t\t\t\t\t\t\titemKind.className,\n\t\t\t\t\t\t\t\t\t\t\t\t\"bg-transparent font-normal\",\n\t\t\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\t\tinitialsClassName=\"text-[9px]\"\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\t\t\t\"min-w-0 truncate font-medium\",\n\t\t\t\t\t\t\t\t\t\t\t\titemKind.showTrigger && \"font-mono\",\n\t\t\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{menuTrigger && itemKind.showTrigger\n\t\t\t\t\t\t\t\t\t\t\t\t? menuTrigger.char + item.label\n\t\t\t\t\t\t\t\t\t\t\t\t: item.label}\n\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t{item.description ? (\n\t\t\t\t\t\t\t\t\t\t\t<span className=\"ms-auto shrink-0 truncate ps-2 text-muted-foreground text-xs\">\n\t\t\t\t\t\t\t\t\t\t\t\t{item.description}\n\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t{menu.results.length === 0 ? (\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\trole=\"option\"\n\t\t\t\t\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\t\t\t\t\taria-selected={false}\n\t\t\t\t\t\t\t\t\taria-disabled\n\t\t\t\t\t\t\t\t\tdata-slot=\"prompt-chip-input-empty\"\n\t\t\t\t\t\t\t\t\tclassName=\"flex min-h-9 items-center px-2 py-1.5 text-muted-foreground\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{menu.loading ? \"Searching…\" : \"No matches\"}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t</m.div>\n\t\t\t\t\t) : null}\n\t\t\t\t</AnimatePresence>\n\t\t\t\t<span aria-live=\"polite\" aria-atomic className=\"sr-only\">\n\t\t\t\t\t{announcement}\n\t\t\t\t</span>\n\t\t\t\t{iconSlots.map((slot) => createPortal(slot.icon, slot.el, slot.key))}\n\t\t\t</div>\n\t\t</LazyMotion>\n\t);\n}\n\nexport default PromptChipInput;\n",
      "type": "registry:component",
      "target": "@components/prompt-chip-input.tsx"
    }
  ],
  "meta": {
    "createdAt": "2026-11-13",
    "image": "https://cdn.tentui.com/images/components/prompt-chip-input?v=2",
    "video": "https://cdn.tentui.com/videos/components/prompt-chip-input?v=2"
  },
  "docs": "https://tentui.com/components/prompt-chip-input",
  "categories": [
    "inputs"
  ],
  "type": "registry:component"
}