Aadi

Mention Menu

AI chats

About

An at mention menu for prompts that suggests files, folders, agents and people at the caret, with fuzzy search and keyboard picking.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Mention Menu to your project and fits it to your theme.

Code

How Mention Menu is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { cn } from "@/lib/utils"
import { Icon, IconNode, MentionItem, MentionMenu, MentionMenuHandle, Spinner, createIcon } from "@/components/ui/mention-menu"

const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

/** The script: text to type, pauses, and Enter to pick the highlighted row. */
type Step = { type: string } | { wait: number } | { pick: true } | { down: true }

const SCRIPT: Step[] = [
  { wait: 500 },
  { type: "Ask " },
  { type: "@" },
  { wait: 900 },
  { type: "rev" },
  { wait: 700 },
  { pick: true },
  { type: "to check " },
  { type: "@" },
  { wait: 500 },
  { type: "pag" },
  { wait: 800 },
  { pick: true },
  { type: "for repeated rows" },
  { wait: 2600 },
]

const CHAR_MS = 70

/** Where the end of the text sits inside `wrap`, in layout pixels (FitFrame scales the box). */
function caretIn(wrap: HTMLElement, el: HTMLTextAreaElement, index: number) {
  const style = window.getComputedStyle(el)
  const mirror = document.createElement("div")
  for (const prop of [
    "boxSizing", "width", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft",
    "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "fontFamily",
    "fontSize", "fontWeight", "letterSpacing", "lineHeight", "wordSpacing",
  ] as const)
    mirror.style[prop] = style[prop]
  Object.assign(mirror.style, {
    position: "absolute", visibility: "hidden", top: "0", left: "-9999px",
    whiteSpace: "pre-wrap", overflowWrap: "anywhere",
  })
  mirror.textContent = el.value.slice(0, index)
  const marker = document.createElement("span")
  marker.textContent = "​"
  mirror.appendChild(marker)
  document.body.appendChild(mirror)
  const w = wrap.getBoundingClientRect()
  const t = el.getBoundingClientRect()
  const scale = w.width / wrap.offsetWidth || 1
  const x = (t.left - w.left) / scale + marker.offsetLeft - el.scrollLeft
  const y = (t.top - w.top) / scale + marker.offsetTop - el.scrollTop
  const h = marker.offsetHeight
  document.body.removeChild(mirror)
  return { x, y, h }
}

const MENU_W = 300

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

/* -------------------------------------------------------------------------------------------------
 * Types and context
 * -----------------------------------------------------------------------------------------------*/

type MessageRole = "user" | "assistant" | "system"

type MessageLayout = "auto" | "bubble" | "flat" | "compact"

type MessageState = "streaming" | "done" | "edited" | "error" | "stopped" | "queued"

/* -------------------------------------------------------------------------------------------------
 * Message
 * -----------------------------------------------------------------------------------------------*/

interface MessageProps extends React.ComponentProps<"div"> {
  /** Who wrote it. Named `from` so the ARIA `role` attribute stays free. */
  from: MessageRole
  /**
   * `auto` gives users a subtle bubble and assistants a flat, document-style block. `compact`
   * is the dense log style for agent traces and side panels. Defaults to `auto`.
   */
  layout?: MessageLayout
  /** Lifecycle state. Defaults to `done`. */
  state?: MessageState
  /** Follows a message from the same author: tightens the gap and hides the avatar. */
  grouped?: boolean
  /** The newest message. Keeps its actions visible instead of revealing them on hover. */
  latest?: boolean
  /**
   * Enter animation. Defaults to animating only messages that arrive after the conversation
   * mounted, so restored history appears at once.
   */
  animate?: boolean
  /** Announce the text to screen readers when streaming finishes. Defaults to true. */
  announce?: boolean
}

/** Scroll behavior for imperative calls. `smooth` falls back to instant under reduced motion. */
type ChatcnScrollBehavior = "smooth" | "instant"

/* -------------------------------------------------------------------------------------------------
 * Context
 * -----------------------------------------------------------------------------------------------*/

interface ConversationContextValue {
  scrollRef: (element: HTMLElement | null) => void
  contentRef: (element: HTMLElement | null) => void
  spacerRef: (element: HTMLElement | null) => void
  /** Within the threshold of the bottom. */
  isAtBottom: boolean
  /** Following new content. */
  isSticky: boolean
  /** More than one viewport from the bottom. */
  isFar: boolean
  /** Messages that arrived below while the reader was scrolled up. */
  unread: number
  scrollToBottom: (options?: { behavior?: ChatcnScrollBehavior }) => void
  scrollToTurn: (element: HTMLElement, options?: { behavior?: ChatcnScrollBehavior }) => void
  /** Read text to screen readers through the conversation's polite live region. */
  announce: (text: string) => void
  /** False during the first render, so restored history does not animate in. */
  ready: boolean
}

const ConversationContext = React.createContext<ConversationContextValue | null>(null)

/** Scroll state and controls of the nearest `Conversation`. Returns null outside one. */
function useConversation() {
  return React.useContext(ConversationContext)
}

interface MessageContextValue {
  from: MessageRole
  /** Resolved layout: `auto` becomes `bubble` for users and `flat` for everyone else. */
  layout: Exclude<MessageLayout, "auto">
  state: MessageState
  /** The newest message: its actions stay visible. */
  latest: boolean
}

const MessageContext = React.createContext<MessageContextValue | null>(null)

/**
 * One turn in the conversation. Compose `MessageAvatar`, `MessageContent`, `MessageMeta`,
 * `MessageStatus` and `MessageActions` inside it.
 */
function Message({
  from,
  layout: layoutProp = "auto",
  state = "done",
  grouped = false,
  latest = false,
  animate,
  announce = true,
  className,
  children,
  ...props
}: MessageProps) {
  const conversation = useConversation()
  const layout: MessageContextValue["layout"] =
    layoutProp === "auto" ? (from === "user" ? "bubble" : "flat") : layoutProp
  const [enter] = React.useState(() => animate ?? conversation?.ready ?? false)
  const ref = React.useRef<HTMLDivElement>(null)

  // Screen readers hear the finished reply once, never token by token.
  const previous = React.useRef(state)
  React.useEffect(() => {
    const was = previous.current
    previous.current = state
    if (!announce || was !== "streaming" || state === "streaming") return
    const text = ref.current?.querySelector('[data-slot="message-content"]')?.textContent?.trim()
    if (text) conversation?.announce(text)
  }, [state, announce, conversation])

  const value = React.useMemo(
    () => ({ from, layout, state, latest }),
    [from, layout, state, latest],
  )

  return (
    <MessageContext.Provider value={value}>
      <div
        ref={ref}
        data-slot="message"
        data-role={from}
        data-layout={layout}
        data-message-state={state}
        data-grouped={grouped ? "" : undefined}
        data-latest={latest ? "" : undefined}
        aria-busy={state === "streaming" || undefined}
        className={cn(
          "group/message relative flex min-w-0 flex-col",
          layout === "compact" ? "gap-1" : "gap-2",
          layout === "bubble" ? "items-end" : "items-start",
          from === "system" && layout !== "compact" && "items-center text-center",
          grouped && (layout === "compact" ? "-mt-2" : "-mt-4"),
          // An avatar sits in the start gutter (the end gutter for bubbles).
          layout === "bubble"
            ? "has-[>[data-slot=message-avatar]]:pe-9"
            : "has-[>[data-slot=message-avatar]]:ps-9",
          enter &&
            (from === "user"
              ? "ease-(--chatcn-ease-out-soft) transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0 motion-reduce:starting:translate-y-0"
              : "ease-(--chatcn-ease-out-soft) transition-opacity duration-150 starting:opacity-0"),
          className,
        )}
        {...props}
      >
        {children}
      </div>
    </MessageContext.Provider>
  )
}

/** Role, layout and state of the nearest `Message`. Returns null outside one. */
function useMessage() {
  return React.useContext(MessageContext)
}

/* -------------------------------------------------------------------------------------------------
 * MessageContent
 * -----------------------------------------------------------------------------------------------*/

/**
 * The text of a message, capped at a 68ch measure. Plain text keeps its line breaks. Markdown
 * renderers drop in as children and inherit the 15/24 prose size.
 */
function MessageContent({ className, children, ...props }: React.ComponentProps<"div">) {
  const ctx = useMessage()
  const layout = ctx?.layout ?? "flat"
  const from = ctx?.from ?? "assistant"
  const state = ctx?.state ?? "done"
  const plain = typeof children === "string"

  return (
    <div
      data-slot="message-content"
      className={cn(
        "text-(color:--chatcn-fg) min-w-0 [overflow-wrap:anywhere]",
        // Bubbles fill their lines: pretty wrapping would leave a wide, half-empty bubble.
        layout !== "bubble" && "text-pretty",
        plain && "whitespace-pre-wrap",
        layout === "bubble" &&
          "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] rounded-(--chatcn-radius-xl) bg-(color:--chatcn-fill) max-w-[80%] px-4 py-2.5 text-start",
        layout === "flat" && "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] w-full max-w-[68ch]",
        layout === "compact" &&
          (from === "user"
            ? "text-[0.875rem]/[1.25rem] tracking-[-0.003em] rounded-(--chatcn-radius-md) bg-(color:--chatcn-fill) max-w-full px-3 py-1.5"
            : "text-[0.875rem]/[1.25rem] tracking-[-0.003em] w-full max-w-[68ch]"),
        from === "system" && "text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) max-w-[60ch]",
        // Queued turns are not sent yet: an outline instead of a fill says "pending".
        state === "queued" &&
          from === "user" &&
          "text-(color:--chatcn-fg-muted) border-(color:--chatcn-border-strong) border border-dashed bg-transparent",
        state === "error" && from === "user" && "text-(color:--chatcn-fg-muted)",
        className,
      )}
      {...props}
    >
      {children}
    </div>
  )
}

/* -------------------------------------------------------------------------------------------------
 * Types and context
 * -----------------------------------------------------------------------------------------------*/

type PromptInputStatus = "idle" | "submitting" | "streaming"

type PromptInputVariant = "default" | "floating" | "minimal" | "hero"

type FileSource = "paste" | "drop" | "picker"

interface FileRejection {
  file: File
  reason: "type" | "size" | "count"
}

type SubmitOn = "enter" | "mod-enter" | "auto"

/* -------------------------------------------------------------------------------------------------
 * PromptInput
 * -----------------------------------------------------------------------------------------------*/

interface PromptInputProps
  extends Omit<React.ComponentProps<"form">, "onSubmit" | "onChange" | "defaultValue"> {
  value?: string
  defaultValue?: string
  onValueChange?: (value: string) => void
  /** Enter, Cmd/Ctrl+Enter or the send button. Not called while empty, disabled or busy. */
  onSubmit?: (message: { text: string }) => void
  /** `streaming` turns Send into Stop and makes Escape call `onStop`. */
  status?: PromptInputStatus
  onStop?: () => void
  disabled?: boolean
  /**
   * - `default`: card with a toolbar row under the text.
   * - `floating`: translucent with a background blur, for composers over content.
   * - `minimal`: one row, text and actions inline.
   * - `hero`: larger type and padding for empty states.
   */
  variant?: PromptInputVariant
  /** Files from paste, drop or the attach button, already filtered by `accept` and limits. */
  onFiles?: (files: File[], source: FileSource) => void
  /** Files refused by `accept`, `maxFileSize` or `maxFiles`, with the reason. */
  onFilesRejected?: (rejections: FileRejection[]) => void
  /** Same syntax as `<input accept>`. */
  accept?: string
  maxFileSize?: number
  maxFiles?: number
  /** Pasted text this long or longer becomes a `Pasted text.txt` file. Off by default. */
  pasteTextAsFileAt?: number
  /** Allow sending with empty text, for example when files are attached. */
  hasContent?: boolean
  submitOn?: SubmitOn
  /** Clear the text after sending in uncontrolled mode. Default true. */
  clearOnSubmit?: boolean
  /** Drop overlay copy. */
  dropLabel?: React.ReactNode
  dropHint?: React.ReactNode
}

interface UseChatcnFileDropOptions {
  /** Same syntax as `<input accept>`: `image/*,.pdf,application/json`. Empty accepts anything. */
  accept?: string
  /** Largest file in bytes. */
  maxSize?: number
  /** Most files in one drop. */
  maxFiles?: number
  disabled?: boolean
  onFiles?: (files: File[]) => void
  onReject?: (rejections: FileRejection[]) => void
  /**
   * `element` (default): spread `rootProps` on the drop target.
   * `window`: listen on the whole page, for a full-page overlay.
   */
  target?: "element" | "window"
}

/** Extensions mapped to MIME types, so `.pdf` can be judged while dragging, before names exist. */
const EXT_MIME: Record<string, string> = {
  ".pdf": "application/pdf",
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".gif": "image/gif",
  ".webp": "image/webp",
  ".svg": "image/svg+xml",
  ".csv": "text/csv",
  ".txt": "text/plain",
  ".md": "text/markdown",
  ".json": "application/json",
  ".zip": "application/zip",
}

/**
 * Whether a file (or a dragged item, which has a type but no name yet) matches an accept string.
 * Unknown types pass while dragging and are judged again by name on drop.
 */
function matchesAccept(file: { type: string; name?: string }, accept?: string) {
  if (!accept) return true
  const rules = accept
    .split(",")
    .map((r) => r.trim().toLowerCase())
    .filter(Boolean)
  if (rules.length === 0) return true
  const type = file.type.toLowerCase()
  const name = file.name?.toLowerCase()
  if (!type && !name) return true
  return rules.some((rule) => {
    if (rule.startsWith(".")) {
      if (name) return name.endsWith(rule)
      return EXT_MIME[rule] === type
    }
    if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1))
    return type === rule
  })
}

/** Splits dropped or pasted files into accepted and rejected, with a reason for each rejection. */
function sortFiles(
  files: File[],
  { accept, maxSize, maxFiles }: Pick<UseChatcnFileDropOptions, "accept" | "maxSize" | "maxFiles">,
) {
  const accepted: File[] = []
  const rejected: FileRejection[] = []
  for (const file of files) {
    if (!matchesAccept(file, accept)) rejected.push({ file, reason: "type" })
    else if (maxSize !== undefined && file.size > maxSize) rejected.push({ file, reason: "size" })
    else if (maxFiles !== undefined && accepted.length >= maxFiles)
      rejected.push({ file, reason: "count" })
    else accepted.push(file)
  }
  return { accepted, rejected }
}

type DropState = "idle" | "accept" | "reject"

function hasFiles(event: DragEvent | React.DragEvent) {
  return Array.from(event.dataTransfer?.types ?? []).includes("Files")
}

/** Judges the drag from what the browser exposes before the drop: item kinds and MIME types. */
function judgeDrag(event: DragEvent | React.DragEvent, accept?: string, maxFiles?: number) {
  const items = Array.from(event.dataTransfer?.items ?? []).filter((i) => i.kind === "file")
  if (maxFiles !== undefined && items.length > maxFiles) return "reject" as const
  return items.every((i) => matchesAccept({ type: i.type }, accept)) ? "accept" : "reject"
}

/**
 * Drag and drop for files. Tracks whether files are over the target and whether they would be
 * accepted, so the overlay can say so before the drop. Text drags pass through untouched, so
 * dragging a snippet into a textarea still works.
 */
function useChatcnFileDrop(options: UseChatcnFileDropOptions = {}) {
  const optionsRef = React.useRef(options)
  optionsRef.current = options
  const [state, setState] = React.useState<DropState>("idle")
  const depth = React.useRef(0)

  const handlers = React.useMemo(() => {
    const enter = (event: DragEvent | React.DragEvent) => {
      const { disabled, accept, maxFiles } = optionsRef.current
      if (disabled || !hasFiles(event)) return
      event.preventDefault()
      depth.current += 1
      setState(judgeDrag(event, accept, maxFiles))
    }
    const over = (event: DragEvent | React.DragEvent) => {
      if (optionsRef.current.disabled || !hasFiles(event)) return
      event.preventDefault()
      if (event.dataTransfer) event.dataTransfer.dropEffect = "copy"
    }
    const leave = (event: DragEvent | React.DragEvent) => {
      if (optionsRef.current.disabled || !hasFiles(event)) return
      depth.current = Math.max(0, depth.current - 1)
      if (depth.current === 0) setState("idle")
    }
    const drop = (event: DragEvent | React.DragEvent) => {
      const { disabled, onFiles, onReject } = optionsRef.current
      if (disabled || !hasFiles(event)) return
      event.preventDefault()
      depth.current = 0
      setState("idle")
      const files = Array.from(event.dataTransfer?.files ?? [])
      const { accepted, rejected } = sortFiles(files, optionsRef.current)
      if (accepted.length) onFiles?.(accepted)
      if (rejected.length) onReject?.(rejected)
    }
    return { enter, over, leave, drop }
  }, [])

  const target = options.target ?? "element"
  React.useEffect(() => {
    if (target !== "window") return
    const { enter, over, leave, drop } = handlers
    window.addEventListener("dragenter", enter)
    window.addEventListener("dragover", over)
    window.addEventListener("dragleave", leave)
    window.addEventListener("drop", drop)
    return () => {
      window.removeEventListener("dragenter", enter)
      window.removeEventListener("dragover", over)
      window.removeEventListener("dragleave", leave)
      window.removeEventListener("drop", drop)
    }
  }, [target, handlers])

  React.useEffect(() => {
    if (options.disabled) {
      depth.current = 0
      setState("idle")
    }
  }, [options.disabled])

  const rootProps = React.useMemo(
    () => ({
      onDragEnter: handlers.enter as (event: React.DragEvent) => void,
      onDragOver: handlers.over as (event: React.DragEvent) => void,
      onDragLeave: handlers.leave as (event: React.DragEvent) => void,
      onDrop: handlers.drop as (event: React.DragEvent) => void,
    }),
    [handlers],
  )

  return { state, rootProps }
}

interface PromptInputContextValue {
  value: string
  setValue: (value: string) => void
  submit: () => void
  stop: () => void
  status: PromptInputStatus
  disabled: boolean
  /** Nothing to send: no text and no `hasContent`. */
  empty: boolean
  variant: PromptInputVariant
  submitOn: SubmitOn
  textareaRef: React.RefObject<HTMLTextAreaElement | null>
  openFilePicker: () => void
  /** False when no `onFiles` handler is set. */
  acceptsFiles: boolean
  handlePaste: (event: React.ClipboardEvent<HTMLTextAreaElement>) => void
}

const PromptInputContext = React.createContext<PromptInputContextValue | null>(null)

const surface: Record<PromptInputVariant, string> = {
  default: "rounded-(--chatcn-radius-xl) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm)",
  // Floating chrome is the one place translucency is allowed. Solid where blur is unsupported.
  floating: cn(
    "rounded-(--chatcn-radius-xl) shadow-(--chatcn-shadow-lg) bg-(color:--chatcn-card)",
    "supports-[backdrop-filter:blur(0)]:bg-[color-mix(in_oklch,var(--chatcn-card)_80%,transparent)] supports-[backdrop-filter:blur(0)]:backdrop-blur-lg",
  ),
  minimal: "rounded-(--chatcn-radius-2xl) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm) flex-row items-end gap-1 p-1.5",
  hero: "rounded-(--chatcn-radius-2xl) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm)",
}

/** The input-focus ring from the spec: 1 px ink edge plus a 3 px soft halo. Never animated. */
const focusRing =
  "focus-within:shadow-[0_0_0_1px_var(--chatcn-gray-900),0_0_0_4px_var(--chatcn-alpha-300)]"

/* -------------------------------------------------------------------------------------------------
 * Overlay
 * -----------------------------------------------------------------------------------------------*/

interface DropZoneOverlayProps extends React.ComponentProps<"div"> {
  state: DropState
  /** Accept title. Default "Drop files to attach". */
  label?: React.ReactNode
  /** Second line under the title, for example the accepted types and size limit. */
  hint?: React.ReactNode
  /** Reject title. Default says which types are accepted, built from `accept`. */
  rejectLabel?: React.ReactNode
  accept?: string
  /** Files in the drag, so the default copy can count them: "Drop 3 files to attach". */
  count?: number
  /** The most files one drop takes. With `count` above it, the reject copy says so. */
  maxFiles?: number
  /** `contained` fills its positioned parent; `page` covers the viewport. */
  variant?: "contained" | "page"
}

/* -------------------------------------------------------------------------------------------------
 * Helpers
 * -----------------------------------------------------------------------------------------------*/

const KINDS: [RegExp, string][] = [
  [/^image\/\*$/, "images"],
  [/^(\.pdf|application\/pdf)$/, "PDFs"],
  [/^video\/\*$/, "videos"],
  [/^audio\/\*$/, "audio"],
  [/^text\/\*$/, "text files"],
  [/^(\.csv|text\/csv)$/, "CSV files"],
  [/^(\.md|text\/markdown)$/, "Markdown files"],
  [/^(\.txt|text\/plain)$/, "text files"],
  [/^(\.json|application\/json)$/, "JSON files"],
]

function joinWords(words: string[]) {
  if (words.length <= 1) return words[0] ?? ""
  return `${words.slice(0, -1).join(", ")} and ${words[words.length - 1]}`
}

/** Readable list from an accept string: `image/*,.pdf` becomes "images and PDFs". */
function describeAccept(accept?: string) {
  if (!accept) return ""
  const words: string[] = []
  for (const raw of accept.split(",")) {
    const rule = raw.trim().toLowerCase()
    if (!rule) continue
    const kind =
      KINDS.find(([re]) => re.test(rule))?.[1] ??
      (rule.startsWith(".") ? `${rule.slice(1).toUpperCase()} files` : rule)
    if (!words.includes(kind)) words.push(kind)
  }
  return joinWords(words)
}

function capitalize(text: string) {
  return text.charAt(0).toUpperCase() + text.slice(1)
}

const iconNode: IconNode = [
  ["path", {"d":"M3 12a9 9 0 1 0 18 0 9 9 0 1 0-18 0"}],
  ["path", {"d":"m7.76 7.76 8.48 8.48"}],
]

const BanIcon: Icon = /* @__PURE__ */ createIcon("ban", iconNode)

const iconNode2: IconNode = [
  ["path", {"d":"M3.5 15v2.5a3 3 0 0 0 3 3h11a3 3 0 0 0 3-3V15"}],
  ["path", {"d":"m16.5 8-3.09-3.09a2 2 0 0 0-2.82 0L7.5 8"}],
  ["path", {"d":"M12 15.5V8"}],
]

const UploadIcon: Icon = /* @__PURE__ */ createIcon("upload", iconNode2)

/**
 * What the user sees while dragging files. Fades in over 150 ms with the content settling from
 * scale 0.98; says before the drop what will happen, counted ("Drop 3 files to attach"), or that
 * the files will be refused, and why: the wrong type, or more than one drop takes.
 */
function DropZoneOverlay({
  state,
  label,
  hint,
  rejectLabel,
  accept,
  count,
  maxFiles,
  variant = "contained",
  className,
  ...props
}: DropZoneOverlayProps) {
  const visible = state !== "idle"
  const reject = state === "reject"
  const types = describeAccept(accept)
  const page = variant === "page"
  const tooMany = count !== undefined && maxFiles !== undefined && count > maxFiles
  const what = !count ? "files" : count === 1 ? "the file" : `${count.toLocaleString()} files`
  const title = reject
    ? (rejectLabel ??
      (tooMany
        ? `Attach up to ${maxFiles} ${maxFiles === 1 ? "file" : "files"} at a time`
        : types
          ? `Only ${types} can be attached`
          : "These files can’t be attached"))
    : (label ?? `Drop ${what} ${page ? "anywhere " : ""}to attach`)
  const sub = reject
    ? tooMany && !rejectLabel
      ? `You’re dragging ${count?.toLocaleString()}.`
      : null
    : (hint ?? (types ? capitalize(types) : null))

  return (
    <div
      aria-hidden="true"
      data-slot="drop-zone-overlay"
      data-drop-state={state}
      data-variant={variant}
      className={cn(
        "pointer-events-none grid place-items-center",
        page ? "fixed inset-0 z-50 p-3" : "absolute inset-0 z-10 rounded-[inherit] p-2",
        page
          ? "bg-[color-mix(in_oklch,var(--chatcn-bg)_88%,transparent)]"
          : "bg-[color-mix(in_oklch,var(--chatcn-card)_94%,transparent)]",
        "ease-(--chatcn-ease-out) transition-[opacity,visibility] duration-150 motion-reduce:duration-100",
        visible ? "visible opacity-100" : "invisible opacity-0",
        className,
      )}
      {...props}
    >
      <div
        className={cn(
          "border-(color:--chatcn-border-strong) grid size-full place-items-center border border-dashed",
          // Concentric: 12 px inset plus 12 px radius fits a 24 px window corner; 8 plus 8 fits 16.
          page ? "rounded-(--chatcn-radius-lg) border-2" : "rounded-(--chatcn-radius-md)",
          reject && "border-solid",
        )}
      >
        <div
          className={cn(
            "flex flex-col items-center gap-1.5 px-4 text-center",
            "ease-(--chatcn-ease-out) transition-[scale] duration-150 motion-reduce:scale-none!",
            visible ? "scale-100" : "scale-98",
          )}
        >
          <span
            key={reject ? "reject" : "accept"}
            className={cn(
              "grid place-items-center motion-safe:animate-[chatcn-swap_150ms_var(--chatcn-ease-out)]",
              page ? "mb-1 [&_svg]:size-6" : "[&_svg]:size-5",
              reject ? "text-(color:--chatcn-red)" : "text-(color:--chatcn-fg)",
            )}
          >
            {reject ? <BanIcon /> : <UploadIcon />}
          </span>
          <p
            className={cn(
              "text-(color:--chatcn-fg) font-medium text-balance!",
              page ? "text-[1.25rem]/[1.75rem] tracking-[-0.018em]" : "text-[0.875rem]/[1.25rem] tracking-[-0.003em]",
            )}
          >
            {title}
          </p>
          {sub ? (
            <p
              className={cn(
                "text-(color:--chatcn-fg-subtle) tabular-nums",
                page ? "text-[0.875rem]/[1.25rem] tracking-[-0.003em]" : "text-[0.8125rem]/[1.25rem]",
              )}
            >
              {sub}
            </p>
          ) : null}
        </div>
      </div>
    </div>
  )
}

/**
 * The composer. A form with a growing textarea, slots for attachments and tools, and the send
 * button. Enter sends, Shift+Enter adds a line, Cmd/Ctrl+Enter also sends, IME composition never
 * sends, Escape stops a streaming response. Images pasted or dropped become files, never a lost
 * paste.
 */
function PromptInput({
  value: valueProp,
  defaultValue = "",
  onValueChange,
  onSubmit,
  status = "idle",
  onStop,
  disabled = false,
  variant = "default",
  onFiles,
  onFilesRejected,
  accept,
  maxFileSize,
  maxFiles,
  pasteTextAsFileAt,
  hasContent = false,
  submitOn = "auto",
  clearOnSubmit = true,
  dropLabel,
  dropHint,
  className,
  children,
  onKeyDown,
  onPointerDown,
  ...props
}: PromptInputProps) {
  const [valueState, setValueState] = React.useState(defaultValue)
  const controlled = valueProp !== undefined
  const value = controlled ? valueProp : valueState
  const textareaRef = React.useRef<HTMLTextAreaElement>(null)
  const fileInputRef = React.useRef<HTMLInputElement>(null)

  const setValue = React.useCallback(
    (next: string) => {
      if (!controlled) setValueState(next)
      onValueChange?.(next)
    },
    [controlled, onValueChange],
  )

  const empty = value.trim().length === 0 && !hasContent

  const submit = () => {
    if (disabled || status !== "idle" || empty) return
    onSubmit?.({ text: value })
    if (!controlled && clearOnSubmit) setValueState("")
  }

  const stop = () => {
    if (status === "streaming") onStop?.()
  }

  const limits = { accept, maxSize: maxFileSize, maxFiles }
  const deliver = (files: File[], source: FileSource) => {
    const { accepted, rejected } = sortFiles(files, limits)
    if (accepted.length) onFiles?.(accepted, source)
    if (rejected.length) onFilesRejected?.(rejected)
  }

  const drop = useChatcnFileDrop({
    ...limits,
    disabled: disabled || !onFiles,
    onFiles: (files) => onFiles?.(files, "drop"),
    onReject: onFilesRejected,
  })

  const handlePaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
    if (!onFiles) return
    const data = event.clipboardData
    const files = Array.from(data.files)
    const text = data.getData("text/plain")
    // Only take over when the paste would otherwise be lost (files, no text) or when the text is
    // long enough to be a document. Ordinary text pastes are never blocked.
    if (files.length > 0 && text.length === 0) {
      event.preventDefault()
      deliver(files, "paste")
    } else if (pasteTextAsFileAt !== undefined && text.length >= pasteTextAsFileAt) {
      event.preventDefault()
      deliver([new File([text], "Pasted text.txt", { type: "text/plain" })], "paste")
    }
  }

  const context: PromptInputContextValue = {
    value,
    setValue,
    submit,
    stop,
    status,
    disabled,
    empty,
    variant,
    submitOn,
    textareaRef,
    openFilePicker: () => fileInputRef.current?.click(),
    acceptsFiles: Boolean(onFiles),
    handlePaste,
  }

  // Announce the switch to Stop once, not every token.
  const [announcement, setAnnouncement] = React.useState("")
  const prevStatus = React.useRef(status)
  React.useEffect(() => {
    if (prevStatus.current === status) return
    if (status === "streaming") setAnnouncement("Generating. Press Escape to stop.")
    else if (prevStatus.current === "streaming") setAnnouncement("")
    prevStatus.current = status
  }, [status])

  return (
    <PromptInputContext.Provider value={context}>
      <form
        data-slot="prompt-input"
        data-variant={variant}
        data-prompt-state={status}
        data-disabled={disabled ? "" : undefined}
        aria-disabled={disabled || undefined}
        className={cn(
          "group/prompt-input @container/prompt-input relative flex w-full min-w-0 cursor-text flex-col",
          "forced-colors:border forced-colors:border-[CanvasText]",
          surface[variant],
          !disabled && focusRing,
          disabled && "bg-(color:--chatcn-bg-subtle) shadow-(--chatcn-shadow-border) cursor-not-allowed",
          className,
        )}
        onSubmit={(event) => {
          event.preventDefault()
          if (status === "streaming") return
          submit()
        }}
        onKeyDown={(event) => {
          onKeyDown?.(event)
          // Escape from anywhere in the composer (not from portalled menus) stops the response.
          if (
            event.key === "Escape" &&
            !event.defaultPrevented &&
            status === "streaming" &&
            event.currentTarget.contains(event.target as Node)
          ) {
            event.preventDefault()
            stop()
          }
        }}
        onPointerDown={(event) => {
          onPointerDown?.(event)
          // A click on the surface (not a control or editable text) puts the caret in the textarea.
          const target = event.target as HTMLElement
          if (
            event.button === 0 &&
            !disabled &&
            !target.closest(
              "button,a,input,textarea,select,[role=button],[data-slot=attachment],[contenteditable=true]",
            )
          ) {
            event.preventDefault()
            textareaRef.current?.focus()
          }
        }}
        {...drop.rootProps}
        {...props}
      >
        {children}
        {onFiles ? (
          <>
            <input
              ref={fileInputRef}
              type="file"
              multiple={maxFiles !== 1}
              accept={accept}
              tabIndex={-1}
              aria-hidden="true"
              className="hidden"
              onChange={(event) => {
                deliver(Array.from(event.target.files ?? []), "picker")
                event.target.value = ""
              }}
            />
            <DropZoneOverlay state={drop.state} accept={accept} label={dropLabel} hint={dropHint} />
          </>
        ) : null}
        <span aria-live="polite" className="sr-only">
          {announcement}
        </span>
      </form>
    </PromptInputContext.Provider>
  )
}

interface PromptInputTextareaProps
  extends Omit<React.ComponentProps<"textarea">, "value" | "defaultValue"> {}

/** Reads the composer state from inside a `PromptInput`, for custom tools and actions. */
function usePromptInput() {
  const context = React.useContext(PromptInputContext)
  if (!context) throw new Error("usePromptInput must be used inside <PromptInput>.")
  return context
}

interface UseChatcnAutoResizeOptions {
  /** The controlled value. Pass it so the textarea re-measures when the value changes in code. */
  value?: string
  /** Turn sizing off, for example for a fixed-height variant. Default true. */
  enabled?: boolean
}

const useIsoLayoutEffect = typeof window === "undefined" ? React.useEffect : React.useLayoutEffect

let fieldSizing: boolean | undefined

/** True where the browser sizes textareas to their content on its own (`field-sizing: content`). */
function supportsFieldSizing() {
  if (fieldSizing === undefined) {
    fieldSizing = typeof CSS !== "undefined" && CSS.supports?.("field-sizing", "content") === true
  }
  return fieldSizing
}

/**
 * Sizes a textarea to its content. Pair it with a CSS `max-height` (chatcn uses 40vh) and
 * `overflow-y: auto`: past the cap the textarea scrolls instead of growing.
 */
function resizeTextarea(el: HTMLTextAreaElement) {
  // Measuring resets the scroll position; put it back so the caret stays where the user is.
  const { scrollTop } = el
  const style = window.getComputedStyle(el)
  const borders =
    Number.parseFloat(style.borderTopWidth) + Number.parseFloat(style.borderBottomWidth)
  el.style.height = "auto"
  el.style.height = `${el.scrollHeight + borders}px`
  el.scrollTop = scrollTop
}

/**
 * Grows a textarea with its content and shrinks it back when cleared. Uses native
 * `field-sizing: content` where supported (no JS, no layout reads) and measures `scrollHeight`
 * elsewhere, on input, on value changes and when the width changes the wrapping.
 */
function useChatcnAutoResize(
  ref: React.RefObject<HTMLTextAreaElement | null>,
  { value, enabled = true }: UseChatcnAutoResizeOptions = {},
) {
  // Value changes made in code (clear after send, insert a transcript).
  useIsoLayoutEffect(() => {
    const el = ref.current
    if (!el || !enabled || supportsFieldSizing()) return
    resizeTextarea(el)
  }, [ref, value, enabled])

  // Typing in uncontrolled mode, and width changes that re-wrap the text.
  React.useEffect(() => {
    const el = ref.current
    if (!el || !enabled || supportsFieldSizing()) return
    const onInput = () => resizeTextarea(el)
    el.addEventListener("input", onInput)
    let width = el.offsetWidth
    const observer = new ResizeObserver(() => {
      if (el.offsetWidth === width) return
      width = el.offsetWidth
      resizeTextarea(el)
    })
    observer.observe(el)
    return () => {
      el.removeEventListener("input", onInput)
      observer.disconnect()
      el.style.height = ""
    }
  }, [ref, enabled])
}

/**
 * Which edges of a scrolled textarea hide text. Read on scroll, on value changes and on resize;
 * the attributes only change when an edge flips, so typing never re-renders for it.
 */
function useScrollEdges(ref: React.RefObject<HTMLTextAreaElement | null>, value: string) {
  const [edges, setEdges] = React.useState({ top: false, bottom: false })
  const update = React.useCallback(() => {
    const el = ref.current
    if (!el) return
    const top = el.scrollTop > 1
    const bottom = el.scrollHeight - el.clientHeight - el.scrollTop > 1
    setEdges((prev) => (prev.top === top && prev.bottom === bottom ? prev : { top, bottom }))
  }, [ref])
  React.useLayoutEffect(update, [update, value])
  React.useEffect(() => {
    const el = ref.current
    if (!el || typeof ResizeObserver === "undefined") return
    const observer = new ResizeObserver(update)
    observer.observe(el)
    return () => observer.disconnect()
  }, [ref, update])
  return { ...edges, update }
}

interface UseChatcnImeSubmitOptions {
  /** Called on Enter (or Cmd/Ctrl+Enter). Never called while an IME is composing. */
  onSubmit: () => void
  /** Called on Escape while `streaming` is true. */
  onStop?: () => void
  streaming?: boolean
  /**
   * Which key sends.
   * - `enter`: Enter sends, Shift+Enter inserts a newline. Cmd/Ctrl+Enter also sends.
   * - `mod-enter`: Enter inserts a newline, Cmd/Ctrl+Enter sends.
   * - `auto` (default): `enter` on fine pointers, `mod-enter` on touch screens, where the
   *   on-screen keyboard has no Shift+Enter and the send button is right there.
   */
  submitOn?: SubmitOn
  /** Swallow Enter without sending. */
  disabled?: boolean
}

function isCoarsePointer() {
  return typeof window !== "undefined" && window.matchMedia?.("(pointer: coarse)").matches === true
}

/**
 * Keyboard handling for chat inputs that is safe with input method editors (Japanese, Chinese,
 * Korean and others). Enter that confirms a composition never sends.
 *
 * Safari fires `compositionend` before the confirming `keydown`, so `isComposing` is already
 * false there. The hook also checks `keyCode === 229` and holds a flag until the next task.
 *
 * Spread the returned handlers on a textarea or input.
 */
function useChatcnImeSubmit(options: UseChatcnImeSubmitOptions) {
  const optionsRef = React.useRef(options)
  optionsRef.current = options
  const composing = React.useRef(false)

  const onCompositionStart = React.useCallback(() => {
    composing.current = true
  }, [])

  const onCompositionEnd = React.useCallback(() => {
    window.setTimeout(() => {
      composing.current = false
    }, 0)
  }, [])

  const onKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLTextAreaElement | HTMLInputElement>) => {
      if (event.defaultPrevented) return
      const native = event.nativeEvent
      // biome-ignore lint/suspicious/noExplicitAny: keyCode 229 is the only Safari IME signal
      if (native.isComposing || composing.current || (native as any).keyCode === 229) return

      const { onSubmit, onStop, streaming, submitOn = "auto", disabled } = optionsRef.current

      if (event.key === "Escape" && streaming && onStop) {
        event.preventDefault()
        onStop()
        return
      }
      if (event.key !== "Enter" || event.shiftKey || event.altKey) return

      const mod = event.metaKey || event.ctrlKey
      const mode = submitOn === "auto" ? (isCoarsePointer() ? "mod-enter" : "enter") : submitOn
      if (mode === "mod-enter" && !mod) return

      event.preventDefault()
      if (disabled) return
      onSubmit()
    },
    [],
  )

  return { onKeyDown, onCompositionStart, onCompositionEnd }
}

/* -------------------------------------------------------------------------------------------------
 * Textarea
 * -----------------------------------------------------------------------------------------------*/

const textareaVariant: Record<PromptInputVariant, string> = {
  default: "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] min-h-12 px-4 pt-3.5 pb-1.5",
  floating: "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] min-h-12 px-4 pt-3.5 pb-1.5",
  minimal: "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] min-h-9 flex-1 px-2.5 py-1.5",
  hero: "text-[1.125rem]/[1.625rem] tracking-[-0.015em] min-h-24 px-5 pt-5 pb-2 tracking-[-0.005em]",
}

/**
 * Grows with its content up to 40% of the viewport, then scrolls. On touch screens the type is
 * at least 16 px so iOS never zooms in on focus.
 */
function PromptInputTextarea({
  className,
  placeholder = "Ask anything…",
  onChange,
  onKeyDown,
  onPaste,
  onScroll,
  onCompositionStart,
  onCompositionEnd,
  ref,
  ...props
}: PromptInputTextareaProps) {
  const {
    value,
    setValue,
    submit,
    stop,
    status,
    disabled,
    variant,
    submitOn,
    textareaRef,
    handlePaste,
  } = usePromptInput()
  useChatcnAutoResize(textareaRef, { value })
  const edges = useScrollEdges(textareaRef, value)
  const ime = useChatcnImeSubmit({
    onSubmit: () => {
      if (status === "idle") submit()
    },
    onStop: stop,
    streaming: status === "streaming",
    submitOn,
    disabled,
  })

  const setRefs = (node: HTMLTextAreaElement | null) => {
    textareaRef.current = node
    if (typeof ref === "function") ref(node)
    else if (ref) ref.current = node
  }

  return (
    <textarea
      ref={setRefs}
      data-slot="prompt-input-textarea"
      name="message"
      rows={1}
      aria-label={props["aria-label"] ?? "Message"}
      autoComplete="off"
      placeholder={placeholder}
      disabled={disabled}
      value={value}
      onChange={(event) => {
        onChange?.(event)
        setValue(event.target.value)
      }}
      onKeyDown={(event) => {
        onKeyDown?.(event)
        ime.onKeyDown(event)
      }}
      onPaste={(event) => {
        onPaste?.(event)
        if (!event.defaultPrevented) handlePaste(event)
      }}
      onScroll={(event) => {
        onScroll?.(event)
        edges.update()
      }}
      data-fade-top={edges.top ? "" : undefined}
      data-fade-bottom={edges.bottom ? "" : undefined}
      onCompositionStart={(event) => {
        onCompositionStart?.(event)
        ime.onCompositionStart()
      }}
      onCompositionEnd={(event) => {
        onCompositionEnd?.(event)
        ime.onCompositionEnd()
      }}
      className={cn(
        "text-(color:--chatcn-fg) placeholder:text-(color:--chatcn-fg-subtle) block w-full resize-none bg-transparent outline-none",
        "chatcn-scroll field-sizing-content max-h-[40vh] overflow-y-auto [overflow-wrap:anywhere]",
        // Past the 40vh cap, the line cut by an edge fades out instead of ending mid-glyph.
        "data-[fade-bottom]:[--chatcn-fade-bottom:20px] data-[fade-top]:[--chatcn-fade-top:20px]",
        "[mask-image:linear-gradient(to_bottom,transparent,#000_var(--chatcn-fade-top,0px),#000_calc(100%-var(--chatcn-fade-bottom,0px)),transparent)]",
        "pointer-coarse:text-[1rem]/[1.5rem] pointer-coarse:tracking-[-0.01em] disabled:cursor-not-allowed disabled:opacity-60",
        textareaVariant[variant],
        className,
      )}
      {...props}
    />
  )
}

/** The row under the text. Put `PromptInputTools` first and `PromptInputActions` last. */
function PromptInputToolbar({ className, ...props }: React.ComponentProps<"div">) {
  const { variant } = usePromptInput()
  return (
    <div
      data-slot="prompt-input-toolbar"
      className={cn(
        "flex min-w-0 items-center gap-1",
        variant === "hero" ? "p-3 pt-1" : "p-2 pt-1",
        className,
      )}
      {...props}
    />
  )
}

/** Trailing group: model picker, dictation, send. Only a truncating model name ever shrinks. */
function PromptInputActions({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="prompt-input-actions"
      className={cn("ms-auto flex min-w-0 items-center gap-1", className)}
      {...props}
    />
  )
}

type SendButtonStatus = "idle" | "submitting" | "streaming"

interface SendButtonProps extends Omit<React.ComponentProps<"button">, "children"> {
  /**
   * - `idle`: Send. Disabled only when `empty`.
   * - `submitting`: a spinner while the request is on its way (or files are still uploading).
   * - `streaming`: Stop. Clicking calls `onStop`.
   */
  status?: SendButtonStatus
  /** Nothing to send. The one reason Send is ever disabled. */
  empty?: boolean
  onStop?: () => void
  shape?: "round" | "square"
  /** 28, 32 or 36 px. Touch screens get a 44 px hit area either way. */
  size?: "sm" | "md" | "lg"
  /** Accessible names. Defaults: Send message, Stop generating, Sending. */
  labels?: { send?: string; stop?: string; submitting?: string }
}

const sizes = {
  sm: { box: "size-7", icon: "size-3.5", square: "size-2" },
  md: { box: "size-8", icon: "size-4", square: "size-2.5" },
  lg: { box: "size-9", icon: "size-4", square: "size-2.5" },
}

// Each glyph is its own layer; state changes crossfade them with a 2 px blur so the button reads
// as one object changing, never as a swap. Same footprint, so nothing around it moves.
const layer = cn(
  "pointer-events-none absolute grid place-items-center",
  "ease-(--chatcn-ease-out) transition-[opacity,scale,translate,filter] duration-150",
  "motion-reduce:translate-none! motion-reduce:scale-none! motion-reduce:blur-none!",
)

const shown = "opacity-100 blur-0 scale-100 translate-y-0"

const iconNode3: IconNode = [
  ["path", {"d":"m18.5 11.5-4.73-4.73a2.5 2.5 0 0 0-3.54 0L5.5 11.5"}],
  ["path", {"d":"M12 19v-9"}],
]

const ArrowUpIcon: Icon = /* @__PURE__ */ createIcon("arrow-up", iconNode3)

/**
 * Send that becomes Stop in the same footprint. The arrow lifts away with the message and blurs
 * out while the kit's signature mark settles in: the same rounded square as the streaming caret,
 * so the thing that is writing is the thing you press to stop it. When the turn ends the next
 * arrow rises in from below, never back down from where the last one left. Escape in the composer
 * does the same as clicking Stop.
 */
function SendButton({
  status = "idle",
  empty = false,
  onStop,
  shape = "round",
  size = "md",
  labels,
  type = "submit",
  className,
  onClick,
  disabled,
  ...props
}: SendButtonProps) {
  const s = sizes[size]
  const streaming = status === "streaming"
  const submitting = status === "submitting"
  const inactive = !streaming && !submitting && empty

  // Count returns to idle. The arrow layer remounts on each one, so its @starting-style places the
  // fresh arrow below the centre and it rises into place: the old one left upward with the message.
  const [seen, setSeen] = React.useState(status)
  const [returns, setReturns] = React.useState(0)
  if (seen !== status) {
    setSeen(status)
    if (status === "idle") setReturns((n) => n + 1)
  }

  const label = streaming
    ? (labels?.stop ?? "Stop generating")
    : submitting
      ? (labels?.submitting ?? "Sending")
      : (labels?.send ?? "Send message")

  return (
    <button
      type={streaming ? "button" : type}
      aria-label={label}
      aria-keyshortcuts={streaming ? "Escape" : "Enter"}
      // Empty stays focusable (aria-disabled, not disabled): after Stop the input is often empty,
      // and a disabled button would drop keyboard focus onto the page.
      aria-disabled={submitting || inactive || undefined}
      disabled={disabled}
      data-slot="send-button"
      data-send-state={status}
      data-empty={inactive ? "" : undefined}
      onClick={(event) => {
        if (submitting || inactive) {
          event.preventDefault()
          return
        }
        if (streaming) {
          event.preventDefault()
          onStop?.()
        }
        onClick?.(event)
      }}
      className={cn(
        "chatcn-focus relative grid shrink-0 place-items-center select-none",
        "ease-(--chatcn-ease-standard) transition-[background-color,color,scale] duration-150",
        "active:scale-(--chatcn-press-scale-icon) active:duration-100",
        "bg-(color:--chatcn-primary) text-(color:--chatcn-primary-fg) hover:bg-(color:--chatcn-primary-hover)",
        "data-[empty]:bg-(color:--chatcn-fill-active) data-[empty]:text-(color:--chatcn-fg-faint) data-[empty]:hover:bg-(color:--chatcn-fill-active) data-[empty]:active:scale-100",
        "disabled:cursor-default disabled:opacity-50 aria-disabled:cursor-default data-[send-state=submitting]:cursor-progress",
        // 44 px hit area on touch without changing the visual size.
        "after:absolute after:-inset-1.5 after:content-[''] pointer-fine:after:hidden",
        "forced-colors:border forced-colors:border-[ButtonText]",
        s.box,
        shape === "round" ? "rounded-full" : "rounded-(--chatcn-radius-md)",
        className,
      )}
      {...props}
    >
      <span
        key={returns}
        aria-hidden="true"
        data-send-layer="arrow"
        className={cn(
          layer,
          streaming || submitting ? "-translate-y-1 scale-90 opacity-0 blur-[2px]" : shown,
          returns > 0 &&
            "starting:translate-y-1 starting:scale-90 starting:opacity-0 starting:blur-[2px]",
        )}
      >
        <ArrowUpIcon strokeWidth={2} className={s.icon} />
      </span>
      <span
        aria-hidden="true"
        className={cn(layer, submitting ? shown : "scale-75 opacity-0 blur-[2px]")}
      >
        {submitting ? <Spinner className={s.icon} /> : null}
      </span>
      <span
        aria-hidden="true"
        className={cn(layer, streaming ? shown : "scale-50 opacity-0 blur-[2px]")}
      >
        {/* 22% corners: the streaming caret's ratio (0.12em on 0.55em), at every size. */}
        <span className={cn("rounded-[22%] bg-current", s.square)} />
      </span>
    </button>
  )
}

/** The send button, wired to the composer: disabled while empty, Stop while streaming. */
function PromptInputSubmit(props: Omit<SendButtonProps, "status" | "empty" | "onStop">) {
  const { status, empty, stop, disabled, variant } = usePromptInput()
  return (
    <SendButton
      status={status}
      empty={empty}
      onStop={stop}
      disabled={disabled}
      size={variant === "hero" ? "lg" : "md"}
      {...props}
    />
  )
}

const ITEMS: MentionItem[] = [
  { id: "runs", kind: "file", label: "runs.ts", detail: "src/server", value: "src/server/runs.ts" },
  { id: "pagination", kind: "file", label: "pagination.ts", detail: "src/lib", value: "src/lib/pagination.ts" },
  { id: "worker", kind: "file", label: "worker.ts", detail: "src/server/queue", value: "src/server/queue/worker.ts" },
  { id: "schema", kind: "file", label: "schema.prisma", detail: "prisma", value: "prisma/schema.prisma" },
  { id: "server", kind: "folder", label: "server", detail: "src", value: "src/server/" },
  { id: "tests", kind: "folder", label: "tests", value: "tests/" },
  { id: "reviewer", kind: "agent", label: "Reviewer", detail: "Reads diffs for regressions", value: "reviewer" },
  { id: "tomas", kind: "person", label: "Tomás Ferreira", detail: "Owns the runs API", value: "tomas" },
  { id: "tracker", kind: "connector", label: "Issue tracker", detail: "Issues and projects", value: "tracker" },
]

const MENU_H = 232

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/**
 * A prompt where @ mentions files, folders, agents and people. The demo types a request, opens the
 * menu at the caret, narrows it as it types and picks with Enter, the way a coding agent inserts
 * `@src/lib/pagination.ts` as text. Loops. Click into the box to try it yourself.
 */
export default function MentionMenuPreview() {
  const [value, setValue] = React.useState("")
  const [from, setFrom] = React.useState<number | null>(null)
  const [step, setStep] = React.useState({ i: 0, chars: 0 })
  const [paused, setPaused] = React.useState(false)
  const [caret, setCaret] = React.useState<{ x: number; y: number; h: number }>()
  const wrapRef = React.useRef<HTMLDivElement>(null)
  const textareaRef = React.useRef<HTMLTextAreaElement>(null)
  const menuRef = React.useRef<MentionMenuHandle>(null)

  const query = from === null ? "" : value.slice(from + 1)
  const open = from !== null && !/\s/.test(query)

  React.useEffect(() => {
    if (paused || reducedMotion()) return
    const s = SCRIPT[step.i]
    const next = (i: number) => setStep({ i: i % SCRIPT.length, chars: 0 })
    if (!s) return next(0)
    if ("wait" in s) {
      const id = window.setTimeout(() => {
        if (step.i === SCRIPT.length - 1) {
          setValue("")
          setFrom(null)
        }
        next(step.i + 1)
      }, s.wait)
      return () => window.clearTimeout(id)
    }
    if ("pick" in s) {
      const id = window.setTimeout(() => {
        menuRef.current?.onKeyDown(new KeyboardEvent("keydown", { key: "Enter" }))
        next(step.i + 1)
      }, 250)
      return () => window.clearTimeout(id)
    }
    if ("down" in s) {
      const id = window.setTimeout(() => {
        menuRef.current?.onKeyDown(new KeyboardEvent("keydown", { key: "ArrowDown" }))
        next(step.i + 1)
      }, 350)
      return () => window.clearTimeout(id)
    }
    const id = window.setTimeout(() => {
      const ch = s.type[step.chars]!
      setValue((v) => {
        if (ch === "@") setFrom(v.length)
        return v + ch
      })
      if (step.chars + 1 >= s.type.length) next(step.i + 1)
      else setStep({ i: step.i, chars: step.chars + 1 })
    }, CHAR_MS)
    return () => window.clearTimeout(id)
  }, [step, paused])

  React.useLayoutEffect(() => {
    const wrap = wrapRef.current
    const el = textareaRef.current
    if (!wrap || !el) return
    const at = open && from !== null ? from : value.length
    const measured = caretIn(wrap, el, at)
    const end = caretIn(wrap, el, value.length)
    setCaret({ x: measured.x, y: end.y, h: end.h })
    // The end of the text, for the drawn caret.
    wrap.style.setProperty("--caret-x", `${end.x}px`)
    wrap.style.setProperty("--caret-y", `${end.y}px`)
  }, [value, open, from])

  const menuLeft = caret ? Math.max(0, Math.min(caret.x - 12, (wrapRef.current?.offsetWidth ?? 600) - MENU_W)) : 0
  const menuBottom = caret && wrapRef.current ? wrapRef.current.offsetHeight - caret.y + 8 : 0

  return (
    <FitFrame minWidth="36rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div ref={wrapRef} className="relative flex w-full max-w-xl flex-col gap-4">
          {/* Room above the prompt for the menu, filled with the thread so far. */}
          <div className="flex min-h-[15rem] flex-col justify-end gap-4">
            <Message from="user">
              <MessageContent>Why does the runs list show the same run twice?</MessageContent>
            </Message>
            <Message from="assistant">
              <MessageContent>
                The runs list pages with an offset, so a run that finishes while you scroll shifts
                every row after it by one. The next page then starts with a row you already saw.
                Paging by the last run id instead would fix it.
              </MessageContent>
            </Message>
          </div>
          <PromptInput
            value={value}
            onValueChange={(v) => {
              setValue(v)
              const at = v.lastIndexOf("@")
              setFrom(at >= 0 && !/\s/.test(v.slice(at + 1)) ? at : null)
            }}
            onSubmit={() => {
              setValue("")
              setFrom(null)
            }}
          >
            <PromptInputTextarea
              ref={textareaRef}
              rows={1}
              placeholder="Type @ to mention a file, folder, agent or person"
              onFocus={() => setPaused(true)}
              onBlur={() => {
                setPaused(false)
                setValue("")
                setFrom(null)
                setStep({ i: 0, chars: 0 })
              }}
              onKeyDown={(event) => {
                if (open && menuRef.current?.onKeyDown(event)) event.preventDefault()
              }}
            />
            <PromptInputToolbar>
              <PromptInputActions>
                <PromptInputSubmit />
              </PromptInputActions>
            </PromptInputToolbar>
          </PromptInput>
          {!paused && caret ? (
            <span
              aria-hidden
              className="bg-(color:--chatcn-fg) pointer-events-none absolute w-px animate-pulse"
              style={{ left: "var(--caret-x)", top: "var(--caret-y)", height: caret.h }}
            />
          ) : null}
          <MentionMenu
            open={open}
            onOpenChange={(o) => {
              if (!o) setFrom(null)
            }}
            query={query}
            items={ITEMS}
            recent={["runs", "reviewer"]}
            menuRef={menuRef}
            width={MENU_W}
            maxHeight={MENU_H}
            className="absolute z-10"
            style={{ left: menuLeft, bottom: menuBottom }}
            onSelect={(item) => {
              if (from === null) return
              const next = `${value.slice(0, from)}@${item.value ?? item.label} `
              setValue(next)
              setFrom(null)
              textareaRef.current?.setSelectionRange(next.length, next.length)
            }}
          />
        </div>
        <MoreOn slug="mention-menu">Mentions for files, agents and people, at the caret. On</MoreOn>
      </div>
    </FitFrame>
  )
}

More by Aadi

View all
  • Audio Visualizer

    Audio Visualizer

    29
  • Stat Card

    Stat Card

    24
  • Dither Orb

    Dither Orb

    23
  • Voice Orb

    Voice Orb

    17
  • Waveform

    Waveform

    13
  • Message Feedback

    Message Feedback

    12
  • Agent Lanes

    Agent Lanes

    11
  • Voice Controls

    Voice Controls

    10

More in AI chats

View all
  • AI Actions

    AI Actions

    349
  • Aquarium Prompt

    Aquarium Prompt

    95
  • Generation Stats

    Generation Stats

  • Chat Bubble

    Chat Bubble

    202
  • Commit

    Commit

    36
  • Color Picker

    Color Picker

    190
  • Environment Variables

    Environment Variables

    27
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    57

Explore more

Part of chatcn — browse the full library on 21st.dev.