Components / Conversation

Composer menu

The picker a composer opens for slash commands and @ mentions, anchored above the textarea.

Type / for commands or @ to mention; Escape closes the menu.

pnpm exec shadcn add @intelligo/ai-composer-menu

Inside an app made by intelligo create, or any shadcn project that names the registry.

Source

What shadcn add writes to components/ui/ai-composer-menu.tsx. It is yours from then on.

"use client";

/*
 * The picker a composer opens for `/` commands and `@` mentions: a Command
 * list that sits above the textarea, filtered by what was typed after the
 * trigger. Presentation only — the trigger detection lives with the
 * composer. Positioned in flow (absolute, above its `relative` parent)
 * rather than in a popup, so focus never leaves the textarea while the
 * reader keeps typing.
 */

import * as React from "react";

import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { cn } from "@/lib/utils";

export type ComposerMenuOption = {
  value: string;
  label: string;
  description?: string;
  icon?: React.ReactNode;
  /** Grouped under this heading when given. */
  group?: string;
};

/** The options `query` leaves, under their headings, in the order the menu shows them. */
function groupedComposerOptions(
  options: ComposerMenuOption[],
  query: string
): [string, ComposerMenuOption[]][] {
  const needle = query.trim().toLowerCase();
  const map = new Map<string, ComposerMenuOption[]>();
  for (const option of options) {
    if (
      needle &&
      !option.label.toLowerCase().includes(needle) &&
      !option.value.toLowerCase().includes(needle) &&
      !option.description?.toLowerCase().includes(needle)
    ) {
      continue;
    }
    const key = option.group ?? "";
    map.set(key, [...(map.get(key) ?? []), option]);
  }
  return [...map.entries()];
}

/**
 * The options the menu shows for `query`, top to bottom: what a caller
 * that moves the highlight from the keyboard steps through.
 */
function visibleComposerOptions(
  options: ComposerMenuOption[],
  query: string
): ComposerMenuOption[] {
  return groupedComposerOptions(options, query).flatMap(([, items]) => items);
}

/** The ids of the menu's list and of its highlighted option, for the field that controls it. */
export type ComposerMenuElements = {
  listId: string | null;
  activeId: string | null;
};

const NO_ELEMENTS: ComposerMenuElements = { listId: null, activeId: null };

function ComposerMenu({
  open,
  options,
  query,
  onSelect,
  emptyLabel,
  className,
  activeValue,
  onActiveChange,
  onElements,
}: {
  open: boolean;
  options: ComposerMenuOption[];
  /** What was typed after the trigger, for the filter. */
  query: string;
  onSelect: (option: ComposerMenuOption) => void;
  emptyLabel: string;
  className?: string;
  /**
   * The highlighted option's `value`, when the composer moves the
   * highlight itself: focus stays in its textarea, so the keys arrive
   * there and not here. Unset, the pointer alone moves it.
   */
  activeValue?: string | null;
  /** The pointer moved the highlight. */
  onActiveChange?: (value: string) => void;
  /**
   * The ids to put on the textarea as `aria-controls` and
   * `aria-activedescendant`; both null while the menu is closed.
   */
  onElements?: (elements: ComposerMenuElements) => void;
}) {
  const rootRef = React.useRef<HTMLDivElement | null>(null);
  const groups = React.useMemo(
    () => groupedComposerOptions(options, query),
    [options, query]
  );

  React.useEffect(() => {
    if (!onElements) return;
    const root = open ? rootRef.current : null;
    if (!root) {
      onElements(NO_ELEMENTS);
      return;
    }
    const active = activeValue
      ? [...root.querySelectorAll("[cmdk-item]")].find(
          (item) => item.getAttribute("data-value") === activeValue
        )
      : undefined;
    onElements({
      listId: root.querySelector("[cmdk-list]")?.id ?? null,
      activeId: active?.id ?? null,
    });
  }, [open, activeValue, groups, onElements]);

  if (!open) return null;

  return (
    <div
      ref={rootRef}
      data-slot="composer-menu"
      role="presentation"
      className={cn(
        "absolute bottom-full left-0 z-50 mb-2 w-80 max-w-full overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md",
        className
      )}
    >
      <Command
        shouldFilter={false}
        loop
        {...(activeValue !== undefined
          ? { value: activeValue ?? "", onValueChange: onActiveChange }
          : {})}
      >
        <CommandList className="max-h-64">
          <CommandEmpty>{emptyLabel}</CommandEmpty>
          {groups.map(([group, items]) => (
            <CommandGroup key={group} heading={group || undefined}>
              {items.map((option) => (
                <CommandItem
                  key={option.value}
                  value={option.value}
                  onSelect={() => onSelect(option)}
                  onMouseDown={(event) => event.preventDefault()}
                >
                  {option.icon}
                  <span className="flex min-w-0 flex-col">
                    <span className="truncate">{option.label}</span>
                    {option.description ? (
                      <span className="truncate text-xs text-muted-foreground">
                        {option.description}
                      </span>
                    ) : null}
                  </span>
                </CommandItem>
              ))}
            </CommandGroup>
          ))}
        </CommandList>
      </Command>
    </div>
  );
}

export { ComposerMenu, visibleComposerOptions };

Ready to try it? Three commands and the app runs against a stub model.