{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "autocomplete",
  "title": "Autocomplete",
  "description": "Suggestions at the text caret: typing a trigger character, such as `@` for people or `:` for emoji, in a `TextArea` or `TextField` opens a list beside the caret, filtered by what follows the character.",
  "dependencies": [
    "@base-ui/react@^1.8.0"
  ],
  "registryDependencies": [
    "@ouro/avatar",
    "@ouro/emoji",
    "@ouro/lib-announce",
    "@ouro/lib-cn",
    "@ouro/lib-dev",
    "@ouro/lib-env",
    "@ouro/lib-floating",
    "@ouro/lib-insert-text",
    "@ouro/lib-portal-container",
    "@ouro/lib-refs",
    "@ouro/lib-server-element",
    "@ouro/lib-use-dev-messages"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/autocomplete/autocomplete-styles.ts",
      "content": "export { caretRect, filterItems, findMatch, matchAt };\nexport type { AutocompleteMatch };\n\n// The caret arithmetic and DOM edits Autocomplete uses, apart from the component so its file\n// exports only components and types (React Fast Refresh).\n\n/**\n * A trigger the caret is in: which trigger, where its character is, and what follows it.\n *\n * @internal\n */\ninterface AutocompleteMatch {\n  /** The trigger's index in `triggers`. */\n  trigger: number;\n  /** The index of the trigger character in the text. */\n  start: number;\n  /** The text between the trigger character and the caret. */\n  query: string;\n}\n\n/**\n * The trigger the caret is in, or null: the nearest trigger character before the caret that\n * starts the text or follows a space or an opening bracket or quote, with no line break, and no\n * space unless `allowSpaces`, between it and the caret, and at least `minQueryLength`\n * characters after it.\n *\n * @internal\n * @claim \"The trigger the caret is in, or null\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete text helpers > finds the nearest trigger before the caret, with its query)\n * @claim \"The trigger the caret is in, or null\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete text helpers > finds none inside a word, across a line break or a space, before the shortest query, or after a space at the start)\n */\nfunction findMatch(\n  text: string,\n  caret: number,\n  triggers: ReadonlyArray<{ char: string; allowSpaces?: boolean | undefined; minQueryLength?: number | undefined }>,\n): AutocompleteMatch | null {\n  for (let start = caret - 1; start >= 0; start -= 1) {\n    const character = text[start]!;\n    if (character === \"\\n\") return null;\n    const trigger = triggers.findIndex((candidate) => candidate.char === character);\n    if (trigger !== -1 && (start === 0 || /[\\s([{\"'“‘]/.test(text[start - 1]!))) {\n      const { allowSpaces, minQueryLength = 0 } = triggers[trigger]!;\n      const query = text.slice(start + 1, caret);\n      if (/^\\s/.test(query) || (!allowSpaces && /\\s/.test(query)) || query.length < minQueryLength) return null;\n      return { trigger, start, query };\n    }\n  }\n  return null;\n}\n\n/**\n * The items for `query` from a list: those whose label, a word of it, or whose value starts\n * with it, ignoring case, in their order.\n *\n * @internal\n */\nfunction filterItems<T extends { value: string; label: string }>(items: readonly T[], query: string): T[] {\n  const needle = query.toLocaleLowerCase();\n  return items.filter(\n    (item) =>\n      item.value.toLocaleLowerCase().startsWith(needle) ||\n      item.label.toLocaleLowerCase().startsWith(needle) ||\n      item.label.toLocaleLowerCase().split(/\\s/).some((word) => word.startsWith(needle)),\n  );\n}\n\n/**\n * Where `query` matches `label` for showing in bold: at its start or the start of one of its\n * words, ignoring case. A negative index means it matches neither.\n *\n * @internal\n */\nfunction matchAt(label: string, query: string): number {\n  if (query === \"\") return -1;\n  const needle = query.toLocaleLowerCase();\n  // Stryker disable next-line EqualityOperator: past the end the slice is empty, which no query (empty returned already) equals.\n  for (let index = 0; index < label.length; index += 1) {\n    if ((index === 0 || /\\s/.test(label[index - 1]!)) && label.slice(index, index + query.length).toLocaleLowerCase() === needle) return index;\n  }\n  return -1;\n}\n\n/** The styles that decide where a character lands in a text control, copied to the mirror. */\nconst mirrored = [\n  \"boxSizing\",\n  \"width\",\n  \"borderTopWidth\",\n  \"borderRightWidth\",\n  \"borderBottomWidth\",\n  \"borderLeftWidth\",\n  \"borderStyle\",\n  \"paddingTop\",\n  \"paddingRight\",\n  \"paddingBottom\",\n  \"paddingLeft\",\n  \"fontStyle\",\n  \"fontVariant\",\n  \"fontWeight\",\n  \"fontStretch\",\n  \"fontSize\",\n  \"fontFamily\",\n  \"lineHeight\",\n  \"letterSpacing\",\n  \"wordSpacing\",\n  \"textTransform\",\n  \"textIndent\",\n  \"tabSize\",\n  \"direction\",\n] as const;\n\n/**\n * Where the character at `index` sits in a textarea or input, in viewport coordinates: a\n * zero-width box one line tall. It lays the text out again in a hidden copy of the control\n * with the same box and font, and measures a marker at `index` that holds the word starting\n * there, so a word that wraps takes the marker with it.\n *\n * @internal\n * @claim \"Where the character at `index` sits\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete text helpers > measures the caret on a wrapped line and in a scrolled field)\n */\nfunction caretRect(control: HTMLTextAreaElement | HTMLInputElement, index: number): DOMRect {\n  const document = control.ownerDocument;\n  const style = getComputedStyle(control);\n  const textarea = control.tagName === \"TEXTAREA\";\n  const mirror = document.createElement(\"div\");\n  // Out of sight and out of the page's flow; the marker's offsets are from the mirror's box.\n  mirror.style.cssText = \"position: absolute; top: 0; left: -9999px; visibility: hidden; overflow: hidden\";\n  for (const property of mirrored) mirror.style[property] = style[property];\n  // A textarea wraps, and breaks a word too long for a line; an input keeps one line.\n  mirror.style.whiteSpace = textarea ? \"pre-wrap\" : \"pre\";\n  mirror.style.overflowWrap = \"break-word\";\n  mirror.textContent = control.value.slice(0, index);\n  const marker = document.createElement(\"span\");\n  // The word that starts at `index`, so the marker wraps to the next line where that word does,\n  // or a dot, so it has a line box even at the end of the text.\n  marker.textContent = control.value.slice(index).split(/\\s/, 1)[0] || \".\";\n  mirror.append(marker);\n  document.body.append(mirror);\n  const box = control.getBoundingClientRect();\n  const top = box.top + marker.offsetTop - control.scrollTop;\n  const left = box.left + marker.offsetLeft - control.scrollLeft;\n  const height = marker.offsetHeight;\n  mirror.remove();\n  return new DOMRect(left, top, 0, height);\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/autocomplete/autocomplete-styles.ts"
    },
    {
      "path": "registry/ouro/components/ouro/autocomplete/autocomplete.tsx",
      "content": "\"use client\";\n\nimport { Popover as BasePopover } from \"@base-ui/react/popover\";\nimport {\n  cloneElement,\n  isValidElement,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type FocusEvent,\n  type FormEvent,\n  type JSX,\n  type KeyboardEvent,\n  type MouseEvent,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type SyntheticEvent,\n} from \"react\";\nimport { Avatar } from \"@/registry/ouro/components/ouro/avatar/avatar\";\nimport { Emoji, type EmojiCatalogue, type EmojiItem, type EmojiSkinTone } from \"@/registry/ouro/components/ouro/emoji/emoji\";\nimport { emojiToken, searchCatalogue, toneOf } from \"@/registry/ouro/components/ouro/emoji/emoji-styles\";\nimport { announce } from \"@/registry/ouro/lib/ouro/announce\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { devThrow } from \"@/registry/ouro/lib/ouro/dev\";\nimport { floatingMotionClass, floatingPortalClass, floatingSurfaceClass } from \"@/registry/ouro/lib/ouro/floating\";\nimport { PortalScope, usePortalContainer } from \"@/registry/ouro/lib/ouro/portal-container\";\nimport { useMergedRef } from \"@/registry/ouro/lib/ouro/refs\";\nimport { serverElement } from \"@/registry/ouro/lib/ouro/server-element\";\nimport { useDevWarnings, type DevWarning } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { caretRect, filterItems, findMatch, matchAt, type AutocompleteMatch } from \"@/registry/ouro/components/ouro/autocomplete/autocomplete-styles\";\nimport { insertText } from \"@/registry/ouro/lib/ouro/insert-text\";\n\n/** One suggestion in the list a trigger opens. */\nexport interface AutocompleteItem {\n  /** Identifies the suggestion, such as a person's id. Unique within one list. */\n  value: string;\n  /** The suggestion's name, shown in the list and read by screen readers. */\n  label: string;\n  /** Quieter text at the end of the row, such as a role or the shortcode `:tada:`. */\n  description?: string | undefined;\n  /** Shows an `Avatar` for the label, with its picture when `src` is set and its initials otherwise: `avatar: { src }`. */\n  avatar?: { src?: string | undefined; initials?: string | undefined } | undefined;\n  /** A small picture before the label instead of an avatar, such as an emoji: `glyph: \"🎉\"`. */\n  glyph?: ReactNode;\n  /**\n   * An image catalogue's emoji, drawn before the label instead of an avatar or glyph; an\n   * animated one plays while the suggestion is active. A trigger with `catalogue` sets it.\n   */\n  emoji?: EmojiItem | undefined;\n  /** The skin tone `emoji` is drawn in, for an emoji with `skinTones`. A trigger with `catalogue` and `skinTone` sets it. @default \"default\" */\n  skinTone?: EmojiSkinTone | (string & { 'Use \"default\", \"light\", \"medium-light\", \"medium\", \"medium-dark\" or \"dark\"': never }) | undefined;\n  /**\n   * The text that replaces the trigger and what follows it when the suggestion is picked.\n   * @default the trigger character, the label and a space: \"@Avery Kim \"\n   */\n  insert?: string | undefined;\n}\n\n/** A character that opens suggestions, such as `@` for people or `:` for emoji. */\nexport interface AutocompleteTrigger {\n  /** The character, such as \"@\". It opens the list at the start of the text or after a space or an opening bracket. */\n  char: string;\n  /** Names the list for screen readers: \"People\", \"Emoji\". */\n  label: string;\n  /**\n   * An image emoji catalogue to suggest from instead of `items`: the emoji whose shortcode,\n   * name or keyword starts with what follows the character, shortcodes first, at most eight,\n   * each drawn as its image with its `:shortcode:` token. Picking one inserts the token and a\n   * space, which `EmojiText` draws as the image once the message is sent.\n   *\n   * @claim \"shortcodes first, at most eight\" registry/ouro/components/ouro/autocomplete/autocomplete.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.catalogue.test.tsx::Autocomplete with a catalogue > suggests emoji by shortcode, name and keyword, shortcodes first, drawn as images)\n   * @claim \"Picking one inserts the token and a space\" registry/ouro/components/ouro/autocomplete/autocomplete.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.catalogue.test.tsx::Autocomplete with a catalogue > inserts the picked emoji's token and a space in a Composer, which EmojiText draws as its image)\n   */\n  catalogue?: EmojiCatalogue | undefined;\n  /**\n   * The skin tone a `catalogue`'s emoji with tones are suggested and inserted in: the tone the\n   * person chose in EmojiPicker. Keep it in one place and give it to both, the picker's\n   * `skinTone` and `onSkinToneChange` and this, so a `:` suggestion inserts the same tone the\n   * picker does (`:thumbs-up-tone3:`). Emoji without tones are unchanged.\n   *\n   * @claim \"a `:` suggestion inserts the same tone\" registry/ouro/components/ouro/autocomplete/autocomplete.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.catalogue.test.tsx::Autocomplete with a catalogue > suggests and inserts emoji in the skin tone the trigger gives, the one the person chose in EmojiPicker)\n   * @default \"default\"\n   */\n  skinTone?: EmojiSkinTone | (string & { 'Use \"default\", \"light\", \"medium-light\", \"medium\", \"medium-dark\" or \"dark\"': never }) | undefined;\n  /**\n   * The suggestions: a list, which shows the items whose label, a word of it, or whose value\n   * starts with what follows the character, or a function of that text (`query`, \"\" just\n   * after the character) that filters and caps them itself. The list closes when none match.\n   * @claim \"The list closes when none match\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete > filters by what follows the trigger, and closes when nothing matches)\n   */\n  items?: readonly AutocompleteItem[] | ((query: string) => readonly AutocompleteItem[]) | undefined;\n  /** Called after a suggestion is inserted, with the suggestion and the query it replaced. */\n  onPick?: ((item: AutocompleteItem, query: string) => void) | undefined;\n  /** How many characters must follow the trigger before the list opens: a couple for emoji shortcodes, so a colon in a time stays quiet. @default 0 */\n  minQueryLength?: number | undefined;\n  /** Keeps the list open across spaces, for names with a first and last name. A line break still closes it. */\n  allowSpaces?: boolean | undefined;\n}\n\n/** Props for {@link Autocomplete}. */\nexport interface AutocompleteProps {\n  /** The characters that open suggestions, such as `@` for people and `:` for emoji, with their lists. */\n  triggers: readonly AutocompleteTrigger[];\n  /**\n   * The text control: one `TextArea`, `TextField`, `Composer`, `<textarea>` or `<input>`. Autocomplete\n   * gives it the list's ARIA, its keys while the list is open, and its ref.\n   */\n  children: ReactElement;\n  /**\n   * What screen readers hear when the list opens or its length changes.\n   * @default (count) => \"1 suggestion\" or \"{count} suggestions\"\n   */\n  resultsLabel?: ((count: number, trigger: AutocompleteTrigger) => string) | undefined;\n\n  /** Not a prop. Ouro UI takes a list: `<Autocomplete triggers={[{ char: \"@\", label: \"People\", items }]}>`. */\n  trigger?: { 'Use triggers={[{ char: \"@\", label: \"People\", items }]}': never };\n  /** Not a prop. A trigger's `items` holds its suggestions. */\n  suggestions?: { 'Use triggers={[{ char: \"@\", label: \"People\", items: (query) => [...] }]}': never };\n  /** Not a prop. A trigger takes `onPick`: `{ char: \"@\", onPick: (item) => ... }`. */\n  onSelect?: { 'Use onPick on the trigger: { char: \"@\", onPick: (item) => ... }': never };\n}\n\n/** The props Autocomplete sets on the text control and reads back from it. */\ntype ControlProps = {\n  ref?: Ref<HTMLTextAreaElement | HTMLInputElement>;\n  onKeyDown?: (event: KeyboardEvent<HTMLTextAreaElement | HTMLInputElement>) => void;\n  onSelect?: (event: SyntheticEvent<HTMLTextAreaElement | HTMLInputElement>) => void;\n  onInput?: (event: FormEvent<HTMLTextAreaElement | HTMLInputElement>) => void;\n  onFocus?: (event: FocusEvent<HTMLTextAreaElement | HTMLInputElement>) => void;\n  onBlur?: (event: FocusEvent<HTMLTextAreaElement | HTMLInputElement>) => void;\n};\n\nconst defaultResultsLabel = (count: number) => (count === 1 ? \"1 suggestion\" : `${count} suggestions`);\nconst preventDefault = (event: MouseEvent) => event.preventDefault();\nconst sameMatch = (a: AutocompleteMatch | null, b: AutocompleteMatch | null) =>\n  a !== null && b !== null && a.trigger === b.trigger && a.start === b.start && a.query === b.query;\n\nconst popupClass = cn(\n  floatingSurfaceClass,\n  floatingMotionClass,\n  \"relative max-h-[min(16rem,var(--available-height))] w-max min-w-56 max-w-[min(22rem,var(--available-width))] overflow-y-auto overscroll-contain p-1 scroll-py-1\",\n);\n\nconst optionClass =\n  \"box-border flex min-h-11 cursor-default items-center gap-2 rounded-ouro-md px-2 py-1.5 text-base leading-5 outline-none select-none \" +\n  \"sm:pointer-fine:min-h-9 sm:pointer-fine:text-sm \" +\n  \"data-highlighted:bg-accent data-highlighted:text-accent-foreground \" +\n  // Forced colours drop the fill, so the active option takes the system's pair.\n  \"forced-colors:data-highlighted:bg-[Highlight] forced-colors:data-highlighted:text-[HighlightText]\";\n\n/**\n * Suggestions at the text caret: typing a trigger character, such as `@` for people or `:` for\n * emoji, in a `TextArea` or `TextField` opens a list beside the caret, filtered by what follows\n * the character. The arrow keys move through it, Enter or Tab inserts the suggestion in place\n * of the trigger and its query, and Escape closes it. Focus stays in the text throughout: the\n * text control points at the active suggestion with `aria-activedescendant`, and screen readers\n * hear how many suggestions there are. Only the list scrolls to show the active suggestion,\n * never a box around it or the page. The typed part of a suggestion's label shows in bold\n * where it starts the label or one of its words. One control can have several triggers.\n *\n * Insertion goes through the browser's own text editing, so Undo takes it back and the\n * control's `onChange` and `onValueChange` run, controlled or not. `TextArea`'s `autoGrow`\n * grows with it. In a `Composer`, the Enter that picks a suggestion does not send. The text a\n * pick inserted keeps the list closed, even after the caret leaves it and comes back, until the\n * person edits it, so the next Enter sends. A trigger\n * with an image emoji `catalogue` suggests its emoji as images and inserts their `:shortcode:`\n * tokens, which `EmojiText` draws as images in the sent message.\n *\n * Use `Combobox` instead to choose one value for a field from a list, and `Command` for a\n * command palette.\n *\n * @group Forms\n * @see https://ui.ouroboros.bot/docs/autocomplete\n * @claim \"In a `Composer`, the Enter that picks\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete > picks with Enter in a Composer without sending, and leaves the next Enter to send)\n * @claim \"Only the list scrolls to show\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete > scrolls only its own list to the active suggestion, never a box around it)\n * @claim \"The text a pick inserted keeps\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete > keeps a picked name closed when a selection change leaves it and comes back, as an app's update of the text can make, so the next Enter sends)\n * @claim \"The text a pick inserted keeps\" registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx verify:testExists(registry/ouro/components/ouro/autocomplete/autocomplete.test.tsx::Autocomplete > opens again once the person edits a picked name)\n *\n * @example\n * <Autocomplete\n *   triggers={[\n *     { char: \"@\", label: \"People\", allowSpaces: true, items: (query) => people.filter((p) => p.label.toLowerCase().includes(query.toLowerCase())).slice(0, 6) },\n *     { char: \":\", label: \"Emoji\", minQueryLength: 2, catalogue },\n *   ]}\n * >\n *   <TextArea label=\"Message\" hideLabel autoGrow rows={1} maxRows={8} value={text} onValueChange={setText} />\n * </Autocomplete>\n */\nexport function Autocomplete(props: AutocompleteProps): JSX.Element {\n  const { triggers, children, resultsLabel = defaultResultsLabel } = props;\n  // A Server Component's field can arrive as a lazy wrapper; resolve it before cloning.\n  const child = serverElement(children);\n  useAutocompleteChecks(props, child);\n\n  const control = child as ReactElement<ControlProps>;\n  const controlRef = useRef<HTMLTextAreaElement | HTMLInputElement | null>(null);\n  const setRef = useMergedRef(control.props.ref, controlRef);\n  const listId = useId();\n  const state = useSuggestions(triggers);\n  const { match, trigger, items, open, current } = state;\n\n  const pick = (item: AutocompleteItem, element: HTMLTextAreaElement | HTMLInputElement) => {\n    state.setPicked({ start: match!.start, query: insertPick(element, match!, trigger!, item) });\n  };\n\n  useAnnouncedCount(open ? resultsLabel(items.length, trigger!) : null);\n  useActiveInView(open ? `${listId}-${current}` : undefined);\n\n  const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement | HTMLInputElement>) => {\n    const action = open ? keyAction(event, current, items.length) : null;\n    if (action === null) {\n      control.props.onKeyDown?.(event);\n      return;\n    }\n    event.preventDefault();\n    if (action === \"pick\") pick(items[current]!, event.currentTarget);\n    else if (action === \"dismiss\") {\n      // The list's Escape: a dialog around the field stays open.\n      event.stopPropagation();\n      state.setDismissed(match!.start);\n    } else state.setActive(action);\n  };\n\n  // The list's anchor: the trigger character, measured each time the list is placed. It\n  // keeps the last trigger while the list closes, so the list leaves from where it was.\n  // A web font that loads moves the trigger without resizing the field, and only a new\n  // anchor object makes Base UI place the list again.\n  const { anchorAt } = state;\n  const [fontsLoaded, setFontsLoaded] = useState(0);\n  useEffect(() => {\n    if (!open) return;\n    // Stryker disable next-line ArithmeticOperator,ArrowFunction: the count is never read; any change rebuilds the anchor, and a font load after the first moves the list through the tracking that rebuild set up.\n    const onFontLoad = () => setFontsLoaded((count) => count + 1);\n    document.fonts.addEventListener(\"loadingdone\", onFontLoad);\n    return () => document.fonts.removeEventListener(\"loadingdone\", onFontLoad);\n  }, [open]);\n  const anchor = useMemo(\n    () => ({\n      getBoundingClientRect: () => caretRect(controlRef.current!, anchorAt),\n      get contextElement() {\n        return controlRef.current!;\n      },\n    }),\n    // A font load changes no value the anchor reads; it makes a new object, which Base UI places again.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [anchorAt, fontsLoaded],\n  );\n\n  return (\n    <>\n      {cloneElement(control, {\n        ref: setRef,\n        \"aria-autocomplete\": \"list\",\n        \"aria-controls\": open ? listId : undefined,\n        \"aria-activedescendant\": open ? `${listId}-${current}` : undefined,\n        onKeyDown,\n        ...watchedHandlers(control.props, state),\n      } as ControlProps & Record<string, unknown>)}\n      <SuggestionList\n        open={open}\n        listId={listId}\n        label={trigger?.label}\n        query={match?.query}\n        items={items}\n        current={current}\n        anchor={anchor}\n        onHover={state.setActive}\n        onPick={(item) => pick(item, controlRef.current!)}\n      />\n    </>\n  );\n}\n\n/** Throws unless children is one element, and warns in development about unusable triggers and props. */\nfunction useAutocompleteChecks(props: AutocompleteProps, child: unknown): void {\n  if (!isValidElement(child)) {\n    devThrow(\n      \"Autocomplete\",\n      \"children is not one element, so there is no text control to watch\",\n      process.env.NODE_ENV !== \"production\"\n        ? '<Autocomplete triggers={…}><TextArea label=\"Message\" /></Autocomplete>'\n        : // Stryker disable next-line StringLiteral: production only; the check never runs there.\n          /* istanbul ignore next @preserve -- production only */ \"\",\n    );\n  }\n  useDevWarnings(\n    \"Autocomplete\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [...triggerWarnings(props.triggers), ...hintWarnings(props)]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n}\n\n/** The development warnings for Autocomplete's triggers, with their fixes. */\nfunction triggerWarnings(triggers: readonly AutocompleteTrigger[]): DevWarning[] {\n  const chars = triggers.map((candidate) => candidate.char);\n  const long = triggers.find((candidate) => [...candidate.char].length !== 1);\n  const repeated = chars.find((char, index) => chars.indexOf(char) !== index);\n  const unnamed = triggers.find((candidate) => !candidate.label);\n  const empty = triggers.find((candidate) => !candidate.items && !candidate.catalogue);\n  return [\n    triggers.length === 0 && [\"triggers is empty, so nothing opens suggestions\", '<Autocomplete triggers={[{ char: \"@\", label: \"People\", items }]}>'],\n    long && [`char \"${long.char}\" is not one character`, `{ char: \"${[...long.char][0] ?? \"@\"}\", label: \"${long.label}\", items }`],\n    repeated !== undefined && [`two triggers use \"${repeated}\"`, \"give each trigger its own char\"],\n    unnamed && [`the \"${unnamed.char}\" trigger's label is empty, so its list has no name`, `{ char: \"${unnamed.char}\", label: \"People\", items }`],\n    empty && [`the \"${empty.char}\" trigger has neither items nor catalogue, so it suggests nothing`, `{ char: \"${empty.char}\", label: \"${empty.label}\", items }`],\n  ];\n}\n\n/** The development warnings for props Autocomplete does not take, with their fixes. */\nfunction hintWarnings(props: AutocompleteProps): DevWarning[] {\n  const { trigger: triggerHint, suggestions, onSelect } = props;\n  return [\n    triggerHint !== undefined && [\"trigger is not a prop; Autocomplete takes a list\", '<Autocomplete triggers={[{ char: \"@\", label: \"People\", items }]}>'],\n    suggestions !== undefined && [\"suggestions is not a prop; a trigger's items holds them\", '{ char: \"@\", label: \"People\", items: (query) => […] }'],\n    onSelect !== undefined && [\"onSelect is not a prop; a trigger takes onPick\", '{ char: \"@\", label: \"People\", items, onPick: (item) => … }'],\n  ];\n}\n\n/** A suggestion's text where it was inserted: its trigger's position and what follows the trigger. */\ninterface PickedText {\n  start: number;\n  query: string;\n}\n\n/** What Autocomplete knows about the caret: the trigger it is in, its suggestions, and whether the list is open. */\ninterface SuggestionState {\n  match: AutocompleteMatch | null;\n  trigger: AutocompleteTrigger | undefined;\n  items: readonly AutocompleteItem[];\n  open: boolean;\n  current: number;\n  anchorAt: number;\n  setActive: (index: number) => void;\n  setFocused: (focused: boolean) => void;\n  setDismissed: (start: number) => void;\n  setPicked: (picked: PickedText) => void;\n  evaluate: (element: HTMLTextAreaElement | HTMLInputElement) => void;\n}\n\nfunction useSuggestions(triggers: readonly AutocompleteTrigger[]): SuggestionState {\n  const [match, setMatch] = useState<AutocompleteMatch | null>(null);\n  const [active, setActive] = useState(0);\n  const [focused, setFocused] = useState(false);\n  // The trigger the person closed with Escape: it stays closed until the caret leaves it.\n  const [dismissed, setDismissed] = useState<number | null>(null);\n  // The suggestion last inserted: its own text stays closed, though a selection change (the app\n  // updating the text, the caret moving away and back) leaves it, until the person edits it.\n  const [picked, setPicked] = useState<PickedText | null>(null);\n  const [anchorAt, setAnchorAt] = useState(0);\n\n  const trigger = match ? triggers[match.trigger] : undefined;\n  const items = useMemo(() => {\n    // No trigger without a match, or when `triggers` no longer has the match's.\n    if (!trigger) return [];\n    const { query } = match!;\n    if (trigger.catalogue) return searchCatalogue(trigger.catalogue, query, 8).map((item) => emojiSuggestion(item, trigger.skinTone as EmojiSkinTone | undefined));\n    return typeof trigger.items === \"function\" ? trigger.items(query) : filterItems(trigger.items ?? [], query);\n  }, [match, trigger]);\n  const finished = picked !== null && match !== null && picked.start === match.start && picked.query === match.query;\n  const open = focused && match !== null && dismissed !== match.start && !finished && items.length > 0;\n  const current = Math.min(active, items.length - 1);\n\n  const evaluate = (element: HTMLTextAreaElement | HTMLInputElement) => {\n    // Null for an input type with no caret (email, number), which finds no match.\n    const caret = element.selectionStart!;\n    const next = element.selectionEnd === caret ? findMatch(element.value, caret, triggers) : null;\n    setMatch((previous) => (sameMatch(previous, next) ? previous : next));\n    if (next) setAnchorAt(next.start);\n    if (!sameMatch(match, next)) setActive(0);\n    if (next?.start !== dismissed) setDismissed(null);\n  };\n\n  return { match, trigger, items, open, current, anchorAt, setActive, setFocused, setDismissed, setPicked, evaluate };\n}\n\n/** A catalogue's emoji as a suggestion in a skin tone: its name, its token as the description and what it inserts, and its image. */\nfunction emojiSuggestion(item: EmojiItem, skinTone: EmojiSkinTone | undefined): AutocompleteItem {\n  const token = emojiToken(item, skinTone);\n  return { value: toneOf(item, skinTone).id, label: item.name, description: token, emoji: item, skinTone, insert: `${token} ` };\n}\n\n/**\n * Inserts the pick in place of the trigger and its query, then tells the trigger's `onPick`.\n * Returns what now follows the trigger: the pick's text after the trigger character.\n */\nfunction insertPick(element: HTMLTextAreaElement | HTMLInputElement, match: AutocompleteMatch, trigger: AutocompleteTrigger, item: AutocompleteItem): string {\n  const { start, query } = match;\n  const text = item.insert ?? `${trigger.char}${item.label} `;\n  insertText(element, start, start + 1 + query.length, text);\n  trigger.onPick?.(item, query);\n  return text.slice(trigger.char.length);\n}\n\n/**\n * What a key does while the list is open: the index the arrow keys move to, \"pick\" for Enter\n * and Tab, \"dismiss\" for Escape, or null to leave the key to the field (with Alt, Control,\n * Meta or Shift held, or while an input method is composing).\n */\nfunction keyAction(event: KeyboardEvent, current: number, count: number): number | \"pick\" | \"dismiss\" | null {\n  if (event.altKey || event.ctrlKey || event.metaKey || event.nativeEvent.isComposing) return null;\n  if (event.key === \"Escape\") return \"dismiss\";\n  if (event.shiftKey) return null;\n  if (event.key === \"Enter\" || event.key === \"Tab\") return \"pick\";\n  const step = event.key === \"ArrowDown\" ? 1 : event.key === \"ArrowUp\" ? -1 : 0;\n  return step === 0 ? null : (current + step + count) % count;\n}\n\n/** Speaks `message` when the list opens and when it changes, and leaves the last one when the list closes. */\nfunction useAnnouncedCount(message: string | null): void {\n  useEffect(() => {\n    if (message !== null) announce(message);\n  }, [message]);\n}\n\n/** Keeps the active suggestion in view as the arrow keys move. */\nfunction useActiveInView(activeId: string | undefined): void {\n  useEffect(() => {\n    // Stryker disable next-line ConditionalExpression: with no active suggestion, no element has the id, and nothing scrolls.\n    if (activeId === undefined) return;\n    const option = document.getElementById(activeId);\n    const list = option?.closest<HTMLElement>('[role=\"listbox\"]');\n    // Stryker disable next-line ConditionalExpression,LogicalOperator: the active id is always an option in the list.\n    if (!option || !list) return;\n    // Only the list scrolls, to its scroll padding: scrollIntoView would scroll every box around it, and the page.\n    // The list is its options' offset parent, so these are layout positions, which its opening scale does not change.\n    const style = getComputedStyle(list);\n    const top = list.scrollTop + parseFloat(style.scrollPaddingTop);\n    const bottom = list.scrollTop + list.clientHeight - parseFloat(style.scrollPaddingBottom);\n    // Stryker disable next-line EqualityOperator: at the edge exactly, the scroll would move by 0.\n    if (option.offsetTop < top) {\n      list.scrollTop -= top - option.offsetTop;\n      return;\n    }\n    // Stryker disable next-line EqualityOperator: at the edge exactly, the scroll would move by 0. Its own if: a disable comment does not reach an else-if.\n    if (option.offsetTop + option.offsetHeight > bottom) list.scrollTop += option.offsetTop + option.offsetHeight - bottom;\n  }, [activeId]);\n}\n\n/** The field's handlers that look for a trigger at the caret, or open and close the list, then run its own. */\nfunction watchedHandlers(own: ControlProps, state: SuggestionState): ControlProps {\n  return {\n    onInput: (event) => {\n      state.evaluate(event.currentTarget);\n      own.onInput?.(event);\n    },\n    onSelect: (event) => {\n      state.evaluate(event.currentTarget);\n      own.onSelect?.(event);\n    },\n    onFocus: (event) => {\n      state.setFocused(true);\n      own.onFocus?.(event);\n    },\n    onBlur: (event) => {\n      state.setFocused(false);\n      own.onBlur?.(event);\n    },\n  };\n}\n\ninterface SuggestionListProps {\n  open: boolean;\n  listId: string;\n  label: string | undefined;\n  query: string | undefined;\n  items: readonly AutocompleteItem[];\n  current: number;\n  anchor: { getBoundingClientRect: () => DOMRect; contextElement: Element };\n  onHover: (index: number) => void;\n  onPick: (item: AutocompleteItem) => void;\n}\n\n// The listbox beside the caret. Focus stays in the text, so its blur closes the list on a press elsewhere.\nfunction SuggestionList({ open, listId, label, query, items, current, anchor, onHover, onPick }: SuggestionListProps): JSX.Element {\n  const portal = usePortalContainer(\"Autocomplete\");\n  return (\n    <BasePopover.Root open={open}>\n      <BasePopover.Portal {...portal} data-ouro=\"autocomplete-portal\" className={floatingPortalClass}>\n        <PortalScope>\n          <BasePopover.Positioner anchor={anchor} side=\"bottom\" align=\"start\" sideOffset={4} collisionPadding={8} data-ouro=\"autocomplete-positioner\">\n            <BasePopover.Popup initialFocus={false} finalFocus={false} role=\"listbox\" id={listId} aria-label={label} data-ouro=\"autocomplete\" className={popupClass}>\n              {items.map((item, index) => (\n                <div\n                  key={item.value}\n                  id={`${listId}-${index}`}\n                  role=\"option\"\n                  aria-selected={index === current}\n                  data-highlighted={index === current ? \"\" : undefined}\n                  data-ouro-control=\"autocomplete\"\n                  data-ouro-part=\"option\"\n                  className={optionClass}\n                  onMouseDown={preventDefault}\n                  onMouseMove={() => onHover(index)}\n                  onClick={() => onPick(item)}\n                >\n                  <OptionContent item={item} query={query!} active={index === current} />\n                </div>\n              ))}\n            </BasePopover.Popup>\n          </BasePopover.Positioner>\n        </PortalScope>\n      </BasePopover.Portal>\n    </BasePopover.Root>\n  );\n}\n\n/** A suggestion's row: its avatar, emoji or glyph, its label with the typed part in bold, and its description. */\nfunction OptionContent({ item, query, active }: { item: AutocompleteItem; query: string; active: boolean }): JSX.Element {\n  const at = matchAt(item.label, query);\n  return (\n    <>\n      {item.emoji ? (\n        <span aria-hidden=\"true\" className=\"inline-flex size-6 shrink-0 items-center justify-center text-lg leading-none\">\n          <Emoji item={item.emoji} skinTone={item.skinTone} play={active} />\n        </span>\n      ) : item.avatar ? (\n        <Avatar name={item.label} alt=\"\" size=\"xs\" src={item.avatar.src} initials={item.avatar.initials} className=\"shrink-0\" />\n      ) : item.glyph !== undefined ? (\n        <span aria-hidden=\"true\" className=\"inline-flex size-6 shrink-0 items-center justify-center text-lg leading-none\">\n          {item.glyph}\n        </span>\n      ) : null}\n      <span className=\"min-w-0 flex-1 truncate\">\n        {at < 0 ? (\n          item.label\n        ) : (\n          <>\n            {item.label.slice(0, at)}\n            <span data-ouro-autocomplete-match=\"\" className=\"font-semibold\">\n              {item.label.slice(at, at + query.length)}\n            </span>\n            {item.label.slice(at + query.length)}\n          </>\n        )}\n      </span>\n      {item.description && (\n        <span className=\"ms-2 shrink-0 text-sm text-[color-mix(in_oklab,var(--muted-foreground)_80%,var(--foreground))] sm:pointer-fine:text-xs\">{item.description}</span>\n      )}\n    </>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/autocomplete/autocomplete.tsx"
    }
  ],
  "docs": "Suggestions at the text caret: typing a trigger character, such as `@` for people or `:` for emoji, in a `TextArea` or `TextField` opens a list beside the caret, filtered by what follows the character. Import: import { Autocomplete } from \"@/components/ouro/autocomplete/autocomplete\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: avatar, emoji, skeleton, the helpers they import in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/autocomplete.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}