{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "template-input",
  "title": "Template Input",
  "description": "A textarea for templates with {{variables}}: typing {{ suggests variables, inserted ones are highlighted and unknown ones are flagged.",
  "dependencies": [
    "radix-ui"
  ],
  "registryDependencies": [
    "utils",
    "popover",
    "@drift-ui/use-controllable-state",
    "@drift-ui/shape"
  ],
  "files": [
    {
      "path": "registry/default/ui/template-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { flushSync } from \"react-dom\"\n\nimport { cn } from \"@/registry/default/lib/utils\"\nimport {\n  filterMentionOptions,\n  type MentionOption,\n} from \"@/registry/default/lib/mention\"\nimport {\n  findActiveVariable,\n  findTemplateVariables,\n  findUnknownVariables,\n  insertVariable,\n} from \"@/registry/default/lib/template-input-utils\"\nimport { useControllableState } from \"@/registry/default/hooks/use-controllable-state\"\nimport {\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n} from \"@/registry/default/ui/popover\"\n\nconst TEXT_BOX =\n  \"px-3 py-2 text-base break-words whitespace-pre-wrap md:text-sm\"\n\nfunction TemplateInput({\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  variables,\n  ref,\n  onKeyDown,\n  onScroll,\n  className,\n  \"aria-describedby\": ariaDescribedBy,\n  ...props\n}: Omit<\n  React.ComponentProps<\"textarea\">,\n  \"value\" | \"defaultValue\" | \"onChange\" | \"onSelect\"\n> & {\n  value?: string\n  defaultValue?: string\n  onValueChange?: (value: string) => void\n  variables: MentionOption[]\n}) {\n  const listId = React.useId()\n  const unknownId = React.useId()\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const textareaRef = React.useRef<HTMLTextAreaElement>(null)\n  const highlightsRef = React.useRef<HTMLDivElement>(null)\n  React.useImperativeHandle(\n    ref,\n    () => textareaRef.current as HTMLTextAreaElement\n  )\n  const { value: text, setValue: setText } = useControllableState({\n    value,\n    defaultValue,\n    onChange: onValueChange,\n  })\n  const [caret, setCaret] = React.useState(0)\n  const [dismissedStart, setDismissedStart] = React.useState<number | null>(\n    null\n  )\n  const [highlightedIndex, setHighlightedIndex] = React.useState(0)\n\n  const active = findActiveVariable(text, caret)\n  const options = active ? filterMentionOptions(variables, active.query) : []\n  const isOpen =\n    active !== null && active.start !== dismissedStart && options.length > 0\n  const activeIndex = Math.min(\n    highlightedIndex,\n    Math.max(0, options.length - 1)\n  )\n  const activeKey = active ? `${active.start}:${active.query}` : \"\"\n  const [previousKey, setPreviousKey] = React.useState(activeKey)\n\n  if (activeKey !== previousKey) {\n    setPreviousKey(activeKey)\n    setHighlightedIndex(0)\n    if (!active) setDismissedStart(null)\n  }\n\n  const unknown = findUnknownVariables(text, variables)\n  const highlights: React.ReactNode[] = []\n  let index = 0\n  for (const variable of findTemplateVariables(text)) {\n    highlights.push(\n      text.slice(index, variable.start),\n      <span\n        key={variable.start}\n        data-slot=\"template-input-variable\"\n        data-unknown={unknown.includes(variable.name) || undefined}\n        className=\"rounded-sm bg-primary/15 data-unknown:bg-destructive/15 data-unknown:underline data-unknown:decoration-destructive data-unknown:decoration-wavy\"\n      >\n        {text.slice(variable.start, variable.end)}\n      </span>\n    )\n    index = variable.end\n  }\n  highlights.push(`${text.slice(index)} `)\n\n  function selectOption(option: MentionOption) {\n    if (!active) return\n    const next = insertVariable(text, active, caret, option)\n    flushSync(() => {\n      setText(next.text)\n      setCaret(next.caret)\n    })\n    textareaRef.current?.setSelectionRange(next.caret, next.caret)\n  }\n\n  function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n    onKeyDown?.(event)\n    if (event.defaultPrevented || !isOpen) return\n    if (event.nativeEvent.isComposing || event.keyCode === 229) return\n    switch (event.key) {\n      case \"ArrowDown\":\n      case \"ArrowUp\": {\n        event.preventDefault()\n        const delta = event.key === \"ArrowDown\" ? 1 : -1\n        setHighlightedIndex(\n          (activeIndex + delta + options.length) % options.length\n        )\n        return\n      }\n      case \"Enter\":\n      case \"Tab\":\n        event.preventDefault()\n        selectOption(options[activeIndex])\n        return\n    }\n  }\n\n  const describedBy =\n    [ariaDescribedBy, unknown.length > 0 ? unknownId : undefined]\n      .filter(Boolean)\n      .join(\" \") || undefined\n\n  return (\n    <Popover\n      open={isOpen}\n      onOpenChange={(open) => {\n        if (!open && active) setDismissedStart(active.start)\n      }}\n    >\n      <PopoverAnchor asChild>\n        <div\n          ref={rootRef}\n          data-slot=\"template-input\"\n          className={cn(\n            \"relative flex w-full rounded-box border border-input bg-transparent shadow-control transition-[color,box-shadow] dark:bg-input/30\",\n            \"has-[textarea:focus-visible]:border-ring has-[textarea:focus-visible]:ring-[3px] has-[textarea:focus-visible]:ring-ring/50\",\n            \"has-aria-invalid:border-destructive has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50\",\n            className\n          )}\n        >\n          <div\n            ref={highlightsRef}\n            aria-hidden\n            data-slot=\"template-input-highlights\"\n            className={cn(\n              TEXT_BOX,\n              \"pointer-events-none absolute inset-0 overflow-hidden text-transparent select-none\"\n            )}\n          >\n            {highlights}\n          </div>\n          <textarea\n            ref={textareaRef}\n            aria-autocomplete=\"list\"\n            aria-haspopup=\"listbox\"\n            aria-controls={isOpen ? listId : undefined}\n            aria-activedescendant={\n              isOpen ? `${listId}-${activeIndex}` : undefined\n            }\n            aria-describedby={describedBy}\n            value={text}\n            onChange={(event) => {\n              setText(event.target.value)\n              setCaret(event.target.selectionStart)\n            }}\n            onSelect={(event) => setCaret(event.currentTarget.selectionStart)}\n            onKeyDown={handleKeyDown}\n            onScroll={(event) => {\n              highlightsRef.current?.scrollTo(\n                event.currentTarget.scrollLeft,\n                event.currentTarget.scrollTop\n              )\n              onScroll?.(event)\n            }}\n            className={cn(\n              TEXT_BOX,\n              \"relative field-sizing-content min-h-16 w-full resize-none bg-transparent outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n            )}\n            {...props}\n          />\n          {unknown.length > 0 && (\n            <span id={unknownId} className=\"sr-only\">\n              Unknown {unknown.length === 1 ? \"variable\" : \"variables\"}:{\" \"}\n              {unknown.join(\", \")}\n            </span>\n          )}\n        </div>\n      </PopoverAnchor>\n      <PopoverContent\n        align=\"start\"\n        onOpenAutoFocus={(event) => event.preventDefault()}\n        onCloseAutoFocus={(event) => event.preventDefault()}\n        onInteractOutside={(event) => {\n          if (rootRef.current?.contains(event.target as Node)) {\n            event.preventDefault()\n          }\n        }}\n        className=\"w-64 p-1\"\n      >\n        <ul id={listId} role=\"listbox\" data-slot=\"template-input-list\">\n          {options.map((option, optionIndex) => (\n            <li\n              key={option.value}\n              id={`${listId}-${optionIndex}`}\n              role=\"option\"\n              aria-selected={optionIndex === activeIndex}\n              onPointerDown={(event) => event.preventDefault()}\n              onPointerMove={() => setHighlightedIndex(optionIndex)}\n              onClick={() => selectOption(option)}\n              className=\"flex cursor-default flex-col rounded-sm px-2 py-1.5 text-sm aria-selected:bg-accent aria-selected:text-accent-foreground\"\n            >\n              <span className=\"flex items-baseline justify-between gap-2\">\n                {option.label}\n                <span className=\"font-mono text-xs text-muted-foreground\">\n                  {option.value}\n                </span>\n              </span>\n              {option.description && (\n                <span className=\"text-xs text-muted-foreground\">\n                  {option.description}\n                </span>\n              )}\n            </li>\n          ))}\n        </ul>\n      </PopoverContent>\n    </Popover>\n  )\n}\n\nexport { TemplateInput }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/default/lib/template-input-utils.ts",
      "content": "import type { MentionOption } from \"@/registry/default/lib/mention\"\n\nexport type ActiveVariable = {\n  query: string\n  start: number\n}\n\nexport type TemplateVariable = {\n  name: string\n  start: number\n  end: number\n}\n\nconst OPEN = \"{{\"\nconst CLOSE = \"}}\"\nconst PARTIAL_NAME = /^\\s*([^{}\\s]*)$/\nconst TOKEN_REST = /^[^{}\\s]*(\\s*\\}\\})?/\nconst VARIABLE = /\\{\\{\\s*([^{}\\s]+)\\s*\\}\\}/g\n\nexport function findActiveVariable(\n  text: string,\n  caret: number\n): ActiveVariable | null {\n  const before = text.slice(0, caret)\n  const start = before.lastIndexOf(OPEN)\n  if (start === -1) return null\n  const match = PARTIAL_NAME.exec(before.slice(start + OPEN.length))\n  if (!match) return null\n  return { query: match[1], start }\n}\n\nexport function insertVariable(\n  text: string,\n  active: ActiveVariable,\n  caret: number,\n  option: MentionOption\n) {\n  const inserted = `${OPEN}${option.value}${CLOSE}`\n  const after = text.slice(caret)\n  return {\n    text:\n      text.slice(0, active.start) + inserted + after.replace(TOKEN_REST, \"\"),\n    caret: active.start + inserted.length,\n  }\n}\n\nexport function findTemplateVariables(text: string): TemplateVariable[] {\n  return Array.from(text.matchAll(VARIABLE), (match) => ({\n    name: match[1],\n    start: match.index,\n    end: match.index + match[0].length,\n  }))\n}\n\nexport function findUnknownVariables(text: string, variables: MentionOption[]) {\n  const known = new Set(variables.map((variable) => variable.value))\n  return [\n    ...new Set(\n      findTemplateVariables(text)\n        .map((variable) => variable.name)\n        .filter((name) => !known.has(name))\n    ),\n  ]\n}\n",
      "type": "registry:lib"
    },
    {
      "path": "registry/default/lib/mention.ts",
      "content": "export type MentionOption = {\n  value: string\n  label: string\n  description?: string\n}\n\nexport type ActiveMention = {\n  trigger: string\n  query: string\n  start: number\n}\n\nconst TRAILING_TOKEN = /(^|\\s)(\\S)(\\S*)$/\nconst MAX_VISIBLE_OPTIONS = 8\n\nexport function findActiveMention(\n  text: string,\n  caret: number,\n  triggers: string[]\n): ActiveMention | null {\n  const match = TRAILING_TOKEN.exec(text.slice(0, caret))\n  if (!match) return null\n  const [, , trigger, query] = match\n  if (!triggers.includes(trigger)) return null\n  return { trigger, query, start: caret - query.length - 1 }\n}\n\nexport function filterMentionOptions(options: MentionOption[], query: string) {\n  const needle = query.toLowerCase()\n  return options\n    .filter(\n      (option) =>\n        option.value.toLowerCase().includes(needle) ||\n        option.label.toLowerCase().includes(needle)\n    )\n    .slice(0, MAX_VISIBLE_OPTIONS)\n}\n\nexport function insertMention(\n  text: string,\n  mention: ActiveMention,\n  caret: number,\n  option: MentionOption\n) {\n  const inserted = `${mention.trigger}${option.value} `\n  return {\n    text: text.slice(0, mention.start) + inserted + text.slice(caret),\n    caret: mention.start + inserted.length,\n  }\n}\n\nexport type MentionSearch = (\n  query: string,\n  options: { signal: AbortSignal }\n) => Promise<MentionOption[]>\n\nexport type MentionSource = MentionOption[] | MentionSearch\n\nexport type MentionRange = { start: number; end: number }\n\n// Same boundary findActiveMention uses, so anything that opens the list can\n// also become a mention.\nconst BEFORE_MENTION = /\\s/\nconst CLOSING_PUNCTUATION = /[.,!?;:)\\]}\"']/\nconst WORD_CHARACTER = /[\\p{L}\\p{N}_]/u\n\n// A mention ends at whitespace, the end, or closing punctuation. Only \".\" can\n// continue a handle, so \"@ana,\" and \"@ana.\" end there but \"@ana.leex\" does not.\nfunction closesMention(text: string, index: number) {\n  if (index === text.length || /\\s/.test(text[index])) return true\n  if (!CLOSING_PUNCTUATION.test(text[index])) return false\n  if (text[index] !== \".\") return true\n  const next = text.codePointAt(index + 1)\n  return next === undefined || !WORD_CHARACTER.test(String.fromCodePoint(next))\n}\n\nexport function limitMentionOptions(options: MentionOption[]) {\n  return options.slice(0, MAX_VISIBLE_OPTIONS)\n}\n\n// Every known \"@value\" in the text, matched whole. Longer tokens win, so\n// \"@ana.lee\" is not read as \"@ana\" followed by \".lee\".\nexport function findMentionRanges(\n  text: string,\n  tokens: ReadonlySet<string>\n): MentionRange[] {\n  if (tokens.size === 0) return []\n  const triggers = new Set<string>()\n  let longest = 0\n  for (const token of tokens) {\n    triggers.add(token[0])\n    longest = Math.max(longest, token.length)\n  }\n\n  const ranges: MentionRange[] = []\n  let index = 0\n  while (index < text.length) {\n    const atBoundary = index === 0 || BEFORE_MENTION.test(text[index - 1])\n    if (!atBoundary || !triggers.has(text[index])) {\n      index++\n      continue\n    }\n    let end = -1\n    const limit = Math.min(text.length, index + longest)\n    for (let candidate = limit; candidate > index + 1; candidate--) {\n      if (\n        closesMention(text, candidate) &&\n        tokens.has(text.slice(index, candidate))\n      ) {\n        end = candidate\n        break\n      }\n    }\n    if (end === -1) {\n      index++\n      continue\n    }\n    ranges.push({ start: index, end })\n    index = end\n  }\n  return ranges\n}\n\nfunction rangeAround(ranges: MentionRange[], position: number) {\n  return ranges.find((range) => range.start < position && position < range.end)\n}\n\n// Keeps the caret out of mentions. An arrow-key step jumps over the mention in\n// the direction of travel; a click or anything else goes to the nearest edge.\nexport function snapCaret(\n  ranges: MentionRange[],\n  position: number,\n  previous: number,\n  stepped = false\n) {\n  const range = rangeAround(ranges, position)\n  if (!range) return position\n  if (stepped) {\n    return previous <= range.start ? range.end : range.start\n  }\n  return position - range.start <= range.end - position\n    ? range.start\n    : range.end\n}\n\n// Grows a selection so it never cuts a mention in half.\nexport function expandSelection(\n  ranges: MentionRange[],\n  start: number,\n  end: number\n) {\n  return {\n    start: rangeAround(ranges, start)?.start ?? start,\n    end: rangeAround(ranges, end)?.end ?? end,\n  }\n}\n\n// Backspace right after a mention, or Delete right before one, removes all of it.\nexport function deleteMention(\n  text: string,\n  ranges: MentionRange[],\n  caret: number,\n  direction: \"backward\" | \"forward\"\n) {\n  const range = ranges.find((candidate) =>\n    direction === \"backward\"\n      ? candidate.end === caret\n      : candidate.start === caret\n  )\n  if (!range) return null\n  return {\n    text: text.slice(0, range.start) + text.slice(range.end),\n    caret: range.start,\n  }\n}\n",
      "type": "registry:lib"
    }
  ],
  "type": "registry:ui"
}