> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a mentions text box

> Build a headless social media mentions text box with the `connectAutocomplete` connector.

export const customLabel_0 = undefined

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="m6 9 6 6 6-6" />
          </svg>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="js"
    baseHref="/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/examples/mentions"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
]}
  />
</div>

This example builds on the [`autocomplete`](/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/js) widget guide.
Use this guide to build a headless mentions text box with the `connectAutocomplete` connector.

<Callout icon="flask-conical" color="#14b8a6">
  This widget is **{customLabel_0 || "experimental"}** and is subject to change in minor versions.
</Callout>

## Build a custom UI with the connector

The widget renders its own input and panel.
If you need full control over the markup, a custom input element, a different panel structure, or an inline type-ahead like `@` mentions, use the `connectAutocomplete` connector instead.
It turns a render function into a widget, leaving all the markup to you.

Your render function receives the current query, the matching hits per index, and a `refine` function to run a new search:

```js JavaScript icon=code expandable theme={"system"}
import instantsearch from "instantsearch.js";
import { connectAutocomplete } from "instantsearch.js/es/connectors";

// `connectAutocomplete` builds a custom widget from a render function.
const customAutocomplete = connectAutocomplete(
  (renderOptions, isFirstRender) => {
    const { indices, refine, widgetParams } = renderOptions;
    const { input, list } = widgetParams;

    // Connect the input once, so typing doesn't lose focus on re-render
    if (isFirstRender) {
      input.addEventListener("input", (event) => {
        refine(event.currentTarget.value);
      });
      return;
    }

    // Render your own markup from the hits on every result
    const hits = indices[0]?.hits ?? [];
    list.innerHTML = hits
      .map((hit) => `<li>${hit._highlightResult.name.value}</li>`)
      .join("");
  },
);

search.addWidgets([
  customAutocomplete({
    input: document.querySelector("#autocomplete-input"),
    list: document.querySelector("#autocomplete-list"),
  }),
]);
```

Each entry in `indices` has the shape `{ indexName, indexId, hits, results, sendEvent }`.
The connector searches the Algolia indices in your widget tree,
the root index and any nested [`index`](/doc/api-reference/widgets/index-widget/js) widgets,
so you don't pass index names to the connector.

<Note>
  Because you render the markup, you're responsible for keyboard navigation, active-item state, and ARIA attributes.
  If you need the same accessible combobox behavior without building it yourself, use the [`autocomplete`](/doc/api-reference/widgets/autocomplete/js) widget instead of the connector.
</Note>

## Build a rich text box with mentions

Autocomplete can do more than redirect to a search page.
In a text box, it can help people find and insert usernames as they type.
For example, the social media mentions feature lets users mention another user with the `@` character so they can complete the message with the right username.
The text box provides type-ahead suggestions.
The panel doesn't block typing.
Users can keep typing and ignore the suggestions or select one to complete the message.

The compose box doesn't process a query from a search input.
Instead, it parses the content of a text box and detects when you're trying to mention someone.
To replicate this, you need full control over the markup, so you use the `connectAutocomplete` connector rather than the widget.

This example searches the public `autocomplete_twitter_accounts` index, whose records include a `name`, a `handle`, and an `image`.

<img src="https://mintcdn.com/algolia/nyJ2KZzw6bfBNB-S/images/autocomplete/widget-mentions.png?fit=max&auto=format&n=nyJ2KZzw6bfBNB-S&q=85&s=9180ac2e6656de0c2d8ee66905dcabaa" alt="A text box that replicates a social media mentions experience: typing &#x22;@&#x22; opens a panel of matching accounts to complete the mention" width="1190" height="674" data-path="images/autocomplete/widget-mentions.png" />

<Columns>
  <Card title="Open CodeSandbox" icon="codesandbox" href="https://codesandbox.io/s/github/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete-mentions">
    Run and edit the mentions example in CodeSandbox.
  </Card>

  <Card title="Explore source code" icon="github" href="https://github.com/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete-mentions">
    Browse the source code for the mentions example on GitHub.
  </Card>
</Columns>

### Install dependencies

Install InstantSearch.js, the Algolia API client, and [`textarea-caret`](https://www.npmjs.com/package/textarea-caret) (used later to position the panel at the caret):

<CodeGroup>
  ```sh npm theme={"system"}
  npm install instantsearch.js algoliasearch textarea-caret
  ```

  ```sh yarn theme={"system"}
  yarn add instantsearch.js algoliasearch textarea-caret
  ```
</CodeGroup>

### Render the text box

Render a `<textarea>` for the message and an empty container for the suggestions panel.

<Info>
  This example uses a `<textarea>` element instead of an `<input>`, which is better for free-form plain text spanning multiple lines.
</Info>

```html HTML icon=code-xml theme={"system"}
<div class="mentions">
  <textarea id="compose" placeholder="What's happening?" maxlength="280"></textarea>
  <ul id="mentions-panel" hidden></ul>
</div>
```

### Detect a mention

If you pass the full text box value to `refine`, Algolia searches the entire message.
You only want to search when the caret sits inside a mention, and you only want to send the mention itself, not the whole message.

To do that, tokenize the text and find the word under the caret, then check whether it's a valid username:

```js JavaScript icon=code expandable theme={"system"}
// The word under the caret, with its [start, end] range in the text.
function getActiveToken(input, cursor) {
  const re = /\S+/g;
  let match;

  while ((match = re.exec(input))) {
    const [start, end] = [match.index, match.index + match[0].length];

    if (start <= cursor && cursor <= end) {
      return { word: match[0], range: [start, end] };
    }
  }

  return null;
}

// A mention is "@" followed by 1–15 word characters.
const isMention = (word) => /^@\w{1,15}$/.test(word);
```

### Position the panel

When users mention someone, the panel should follow the caret instead of sitting at the bottom of the text box.
Use `getCaretCoordinates(textarea, position)` from [`textarea-caret`](https://www.npmjs.com/package/textarea-caret) to get the caret's `top`, `left`, and `height` at a given offset.
Use it to place the panel just below the `@` of the active mention.

### Search for accounts and render the panel

Attach `connectAutocomplete` to the text box.
On every input, find the active token.
If it's a mention, call `refine` with the text after `@` and show the matching accounts.
Otherwise, hide the panel.
The connector gives you `indices[0].hits` and a `refine` function.
You manage the remaining behavior, including the active token, panel state, and selection handling.

This excerpt shows the connector wiring. The setup (search client and instance, element references) and the `renderHits`, `positionPanel`, and `hidePanel` helpers are in [the complete `src/app.js`](https://github.com/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete-mentions/src/app.js).

```js JavaScript icon=code expandable theme={"system"}
// Only search when the caret sits inside a mention.
function onInput() {
  activeToken = getActiveToken(textarea.value, textarea.selectionEnd);

  if (activeToken && isMention(activeToken.word)) {
    refine(activeToken.word.slice(1));
  } else {
    hidePanel();
  }
}

const customAutocomplete = connectAutocomplete(
  (renderOptions, isFirstRender) => {
    refine = renderOptions.refine;

    if (isFirstRender) {
      textarea.addEventListener("input", onInput);
      textarea.addEventListener("click", onInput);
      textarea.addEventListener("keyup", onInput);
      return;
    }

    const hits = renderOptions.indices[0]?.hits ?? [];

    if (!activeToken || !isMention(activeToken.word) || hits.length === 0) {
      hidePanel();
      return;
    }

    // `positionPanel` places the panel at the caret; `renderHits` builds the
    // suggestion rows with DOM APIs
    positionPanel();
    panel.hidden = false;
    renderHits(hits);
  },
);

search.addWidgets([customAutocomplete({})]);
search.start();
```

When users type `@` followed by a name, highlighted results appear.

### Show a loading state

On slow connections, the panel can appear empty while results load.
The InstantSearch instance exposes a `status` (`"idle"`, `"loading"`, `"stalled"`, or `"error"`), and it re-renders your widget when the search stalls.
Show an indicator when the search is stalled and the caret is inside a mention:

```js JavaScript icon=code theme={"system"}
// Inside the connectAutocomplete render function, before rendering the hits:
if (activeToken && isMention(activeToken.word) && search.status === "stalled") {
  positionPanel();
  panel.hidden = false;
  const loading = document.createElement("li");
  loading.className = "account-loading";
  loading.textContent = "Searching…";
  panel.replaceChildren(loading);
  return;
}
```

### Select an account

The goal of the mention feature is to help users find an account and autocomplete its handle.
For example, when users type a few letters after `@`,
the panel opens with matching accounts.
Selecting an account replaces the typed text with the account's handle, such as "@jwestlakedc", and closes the panel.

When the user picks an account, replace the active token with the correct handle and move the caret after it.
Use `mousedown` (with `preventDefault`) rather than `click` so the `<textarea>` keeps focus:

```js JavaScript icon=code theme={"system"}
const [start, end] = activeToken.range;
const replacement = `@${button.dataset.handle} `;
textarea.value =
  textarea.value.slice(0, start) + replacement + textarea.value.slice(end);
const caret = start + replacement.length;
textarea.setSelectionRange(caret, caret);
textarea.focus();
hidePanel();
```

### Navigate in the text box

Typing isn't the only action in a text box.
Users can also edit their text or move the caret to a different position.
When the caret lands on a mention, the panel should open.
When it leaves a mention, the panel should close.

Listen for `click` and `keyup` in addition to `input`, and run the same active-token check again:

```js JavaScript icon=code theme={"system"}
textarea.addEventListener("input", onInput);
textarea.addEventListener("click", onInput);
textarea.addEventListener("keyup", onInput);
```

### Add styles

Style the text box, the suggestions panel, and the account rows with your own CSS.
For a complete style sheet, see [`src/app.css`](https://github.com/algolia/doc-code-samples/tree/master/instantsearch.js/autocomplete-mentions/src/app.css).

Users can move the caret through the text, and the panel updates when the caret enters or leaves a mention.

### Next steps

This pattern also applies to collaborative editing (such as Google Docs), email composition (such as Gmail), and chat apps (such as Slack).
To extend this pattern:

* Reuse the same logic to add hashtags by changing the `isMention` function to detect hashtags and search a hashtag index instead.
* Add [synonyms](/doc/guides/managing-results/optimize-search-results/adding-synonyms) or [Algolia Rules](/doc/guides/managing-results/rules/rules-overview) so people are found by their nicknames.
* Render mentions and hashtags as interactive tokens with [`contenteditable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable).

## See also

* [`autocomplete`](/doc/api-reference/widgets/autocomplete/js) widget reference for the full list of options.
* [Autocomplete](/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/js) guide for the widget basics.
* [Federated two-column autocomplete](/doc/guides/building-search-ui/ui-and-ux-patterns/autocomplete/examples/federated/js) for an example of a widget-based, multi-source panel.
