Aadi

Chat Header

AI chats 1

About

The bar above a chat: a title that generates itself and renames in place, the model picker, Share and a More menu.

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

Code

How Chat Header 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 { Menu as MenuPrimitive } from "@base-ui/react/menu"
import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
import { ChatHeader, Icon, IconNode, createIcon, popupMotion, popupSurface } from "@/components/ui/chat-header"

interface GhostState {
  x: number
  y: number
  shown: boolean
  down: boolean
}

/**
 * A pointer that walks a demo through its clicks, so a preview shows what each control does.
 * `stage` is the positioned box the pointer moves in; targets are found inside it. Sizes come
 * from layout boxes, so a scaled FitFrame never throws the aim off.
 */
function useGhost(stage: React.RefObject<HTMLElement | null>) {
  const [ghost, setGhost] = React.useState<GhostState>({ x: 0, y: 0, shown: false, down: false })

  const find = React.useCallback(
    (target: string | HTMLElement) =>
      typeof target === "string"
        ? stage.current?.querySelector<HTMLElement>(target) ?? null
        : target,
    [stage],
  )

  const moveTo = React.useCallback(
    (target: string | HTMLElement, dx = 0.5, dy = 0.6) => {
      const root = stage.current
      const el = find(target)
      if (!root || !el) return null
      const rr = root.getBoundingClientRect()
      const scale = root.offsetWidth ? rr.width / root.offsetWidth : 1
      const er = el.getBoundingClientRect()
      const x = (er.left - rr.left + er.width * dx) / scale
      const y = (er.top - rr.top + er.height * dy) / scale
      // A hidden pointer fades in a short way off its first target instead of flying in from
      // wherever it was last.
      setGhost((g) => (g.shown ? { x, y, shown: true, down: false } : { x: x + 70, y: y + 46, shown: false, down: false }))
      window.requestAnimationFrame(() =>
        window.requestAnimationFrame(() => setGhost({ x, y, shown: true, down: false })),
      )
      return el
    },
    [stage, find],
  )

  const press = React.useCallback((down: boolean) => setGhost((g) => ({ ...g, down })), [])
  const hide = React.useCallback(() => setGhost((g) => ({ ...g, shown: false, down: false })), [])

  return { ghost, moveTo, press, hide, find }
}

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

const STOP = Symbol("stop")

/**
 * Runs `script` in a loop with a `wait(ms)` that stops cleanly on unmount or once `active` turns
 * false. Reduced motion never starts it.
 */
function useLoop(
  script: (wait: (ms: number) => Promise<void>) => Promise<void>,
  active = true,
) {
  const ref = React.useRef(script)
  ref.current = script
  React.useEffect(() => {
    if (!active || reducedMotion()) return
    let alive = true
    const timers = new Set<number>()
    const wait = (ms: number) =>
      new Promise<void>((resolve, reject) => {
        const id = window.setTimeout(() => {
          timers.delete(id)
          if (alive) resolve()
          else reject(STOP)
        }, ms)
        timers.add(id)
      })
    ;(async () => {
      try {
        while (alive) await ref.current(wait)
      } catch (error) {
        if (error !== STOP) throw error
      }
    })()
    return () => {
      alive = false
      for (const id of timers) window.clearTimeout(id)
    }
  }, [active])
}

const ASK = "Why does the runs page take two seconds to load?"

const CHAR_MS = 28

const GENERATED = "Slow runs page"

const REPLY =
  "The runs query sorts 40,000 rows by created_at with no index, so every load scans the whole table. An index on created_at brings it under 50 ms. The page also fetches every run's logs up front; loading them when a row opens saves another 600 ms."

const WORD_MS = 42

/** Moves to a target, presses and clicks it. Returns the element, or null if it is gone. */
async function tap(
  g: ReturnType<typeof useGhost>,
  target: string | HTMLElement,
  wait: (ms: number) => Promise<void>,
  travel = 700,
) {
  if (!g.moveTo(target)) return null
  await wait(travel)
  g.press(true)
  await wait(130)
  const el = g.find(target)
  el?.click()
  g.press(false)
  return el
}

/**
 * Types into an uncontrolled field a component owns (a rename input, an inline editor), one
 * character at a time. It sets the value through the native setter and fires `input`, so React
 * sees each keystroke as if it were typed.
 */
function setFieldValue(el: HTMLInputElement | HTMLTextAreaElement, value: string) {
  const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype
  Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(el, value)
  el.dispatchEvent(new Event("input", { bubbles: true }))
}

const RENAMED = "Runs page: missing index"

/** Presses a key on a field, for Enter to save or Escape to cancel. */
function pressKey(el: HTMLElement, key: string) {
  el.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }))
}

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>
  )
}

/**
 * Wrap the app once. After the first tooltip opens, the next ones open instantly, the way
 * native toolbars behave.
 */
function TooltipProvider({
  delay = 500,
  ...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
  return <TooltipPrimitive.Provider delay={delay} closeDelay={0} {...props} />
}

/* -------------------------------------------------------------------------------------------------
 * Types
 * -----------------------------------------------------------------------------------------------*/

type ModelCapability = "vision" | "tools" | "reasoning"

interface ModelOption {
  id: string
  /** Display name, for example `Claude Sonnet 5.5`. */
  name: string
  /** Provider id. Models are grouped by it. */
  provider: string
  /** One line: what the model is good at, or its context size. */
  description?: string
  capabilities?: ModelCapability[]
  /** Adds a quiet New tag. */
  isNew?: boolean
  disabled?: boolean
  /** Why it is unavailable, for example "Upgrade to use". Replaces the description. */
  disabledReason?: string
}

interface ModelProvider {
  id: string
  name: string
}

interface ModelPickerProps {
  models: ModelOption[]
  /** Provider names and group order. Defaults to provider ids in order of appearance. */
  providers?: ModelProvider[]
  value?: string
  defaultValue?: string
  onValueChange?: (id: string) => void
  /**
   * Provider marks are yours to supply: chatcn bundles no third-party logos. Return a 16 px
   * node; it shows in the trigger and the group labels.
   */
  renderProviderMark?: (providerId: string) => React.ReactNode
  loading?: boolean
  disabled?: boolean
  /** `sm` is a 28 px trigger for dense toolbars. */
  size?: "sm" | "md"
  side?: "top" | "bottom"
  align?: "start" | "center" | "end"
  searchPlaceholder?: string
  /** Capability legend under the list. Default true. */
  showLegend?: boolean
  open?: boolean
  onOpenChange?: (open: boolean) => void
  className?: string
}

const iconNode: IconNode = [
  ["path", {"d":"M2.77 11.36a10.19 10.19 0 0 1 18.46 0 1.5 1.5 0 0 1 0 1.28 10.19 10.19 0 0 1-18.46 0 1.5 1.5 0 0 1 0-1.28"}],
  ["path", {"d":"M9 12a3 3 0 1 0 6 0 3 3 0 1 0-6 0"}],
]

const EyeIcon: Icon = /* @__PURE__ */ createIcon("eye", iconNode)

const iconNode2: IconNode = [
  ["path", {"d":"M19.76 6.79a5.25 5.25 0 0 1-7.16 6.88l-6.22 6.21a1.6 1.6 0 0 1-2.26-2.26l6.21-6.22a5.25 5.25 0 0 1 6.88-7.16l-2.42 2.43 2.54 2.54Z"}],
]

const ToolIcon: Icon = /* @__PURE__ */ createIcon("tool", iconNode2)

const iconNode3: IconNode = [
  ["path", {"d":"M4 18a2 2 0 1 0 4 0 2 2 0 1 0-4 0"}],
  ["path", {"d":"M9.5 18h4a3 3 0 0 0 0-6h-3a3 3 0 0 1 0-6h4"}],
  ["path", {"d":"M17.25 4h1.5A1.25 1.25 0 0 1 20 5.25v1.5A1.25 1.25 0 0 1 18.75 8h-1.5A1.25 1.25 0 0 1 16 6.75v-1.5A1.25 1.25 0 0 1 17.25 4"}],
]

const ReasoningIcon: Icon = /* @__PURE__ */ createIcon("reasoning", iconNode3)

const CAPABILITIES: Record<
  ModelCapability,
  { label: string; Icon: React.ComponentType<{ className?: string }> }
> = {
  vision: { label: "Vision", Icon: EyeIcon },
  tools: { label: "Tools", Icon: ToolIcon },
  reasoning: { label: "Reasoning", Icon: ReasoningIcon },
}

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

function matches(model: ModelOption, providerName: string, query: string) {
  if (!query) return true
  const haystack = [
    model.name,
    providerName,
    model.description ?? "",
    ...(model.capabilities ?? []).map((c) => CAPABILITIES[c].label),
  ]
    .join(" ")
    .toLowerCase()
  return query
    .toLowerCase()
    .split(/\s+/)
    .filter(Boolean)
    .every((word) => haystack.includes(word))
}

/* -------------------------------------------------------------------------------------------------
 * ModelPicker
 * -----------------------------------------------------------------------------------------------*/

/**
 * Model menu for the composer footer. The trigger shows the current model; the popover groups
 * models by provider with capability glyphs, a New tag and a check on the current one. Typing
 * filters by name, provider, description or capability ("vision"). Arrow keys move, Enter picks.
 */
/**
 * Which edges of a scroll box hide content, so only those edges fade. A callback ref, because the
 * list mounts with the popover; re-measured on scroll, resize and whenever `content` changes.
 */
function useScrollFade(content: unknown) {
  const node = React.useRef<HTMLElement | null>(null)
  const observer = React.useRef<ResizeObserver | null>(null)
  const [edges, setEdges] = React.useState({ top: false, bottom: false })
  const update = React.useCallback(() => {
    const el = node.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 }))
  }, [])
  const ref = React.useCallback(
    (el: HTMLElement | null) => {
      observer.current?.disconnect()
      node.current = el
      if (el && typeof ResizeObserver !== "undefined") {
        observer.current = new ResizeObserver(update)
        observer.current.observe(el)
      }
      update()
    },
    [update],
  )
  React.useLayoutEffect(update, [update, content])
  return { ...edges, update, ref }
}

/* -------------------------------------------------------------------------------------------------
 * Parts
 * -----------------------------------------------------------------------------------------------*/

/**
 * Root. Controlled with `open` and `onOpenChange`, or uncontrolled with `defaultOpen`.
 * Not modal by default: the page stays scrollable and clickable.
 */
function Popover(props: PopoverPrimitive.Root.Props) {
  return <PopoverPrimitive.Root {...props} />
}

/** The button that toggles the popover. Pass `render={<Button />}` to use your own element. */
function PopoverTrigger(props: PopoverPrimitive.Trigger.Props) {
  return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}

/** The kit's one spinner. 0.8 s per turn, slowed to 1.2 s under reduced motion. */
function Spinner({ className, label }: { className?: string; label?: string }) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="none"
      role={label ? "img" : undefined}
      aria-label={label}
      aria-hidden={label ? undefined : true}
      data-slot="spinner"
      className={cn("chatcn-spin size-3.5 shrink-0", className)}
    >
      <circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeOpacity="0.2" strokeWidth="1.5" />
      <path
        d="M8 1.75A6.25 6.25 0 0 1 14.25 8"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
      />
    </svg>
  )
}

const iconNode4: IconNode = [
  ["path", {"d":"m6 9.25 4.23 4.23a2.5 2.5 0 0 0 3.54 0L18 9.25"}],
]

const ChevronDownIcon: Icon = /* @__PURE__ */ createIcon("chevron-down", iconNode4)

interface PopoverContentProps extends PopoverPrimitive.Popup.Props {
  /** Side of the trigger to open on. Flips when there is no room. Default `bottom`. */
  side?: PopoverPrimitive.Positioner.Props["side"]
  /** Alignment along that side. Default `center`. */
  align?: PopoverPrimitive.Positioner.Props["align"]
  /** Gap to the trigger in px. Default 6. */
  sideOffset?: PopoverPrimitive.Positioner.Props["sideOffset"]
  alignOffset?: PopoverPrimitive.Positioner.Props["alignOffset"]
  /** Element to position against instead of the trigger. */
  anchor?: PopoverPrimitive.Positioner.Props["anchor"]
  /** Portal container. Defaults to `document.body`. */
  container?: PopoverPrimitive.Portal.Props["container"]
}

/**
 * The floating panel. Portalled and positioned for you. Padding defaults to 4 px, the right inset
 * for lists; pass `className="p-3"` for text content.
 */
function PopoverContent({
  side = "bottom",
  align = "center",
  sideOffset = 6,
  alignOffset = 0,
  anchor,
  container,
  className,
  ...props
}: PopoverContentProps) {
  return (
    <PopoverPrimitive.Portal container={container}>
      <PopoverPrimitive.Positioner
        side={side}
        align={align}
        sideOffset={sideOffset}
        alignOffset={alignOffset}
        anchor={anchor}
        className="z-50 outline-none"
      >
        <PopoverPrimitive.Popup
          data-slot="popover-content"
          className={cn(
            popupSurface,
            popupMotion,
            "text-[0.875rem]/[1.25rem] tracking-[-0.003em] chatcn-scroll overflow-auto p-1",
            className,
          )}
          {...props}
        />
      </PopoverPrimitive.Positioner>
    </PopoverPrimitive.Portal>
  )
}

const iconNode5: IconNode = [
  ["path", {"d":"M4 10.75a6.75 6.75 0 1 0 13.5 0 6.75 6.75 0 1 0-13.5 0"}],
  ["path", {"d":"m15.75 15.75 4.5 4.5"}],
]

const SearchIcon: Icon = /* @__PURE__ */ createIcon("search", iconNode5)

const iconNode6: IconNode = [
  ["path", {"d":"M4 10.75a6.75 6.75 0 1 0 13.5 0 6.75 6.75 0 1 0-13.5 0"}],
  ["path", {"d":"m15.75 15.75 4.5 4.5"}],
  ["path", {"d":"m8.25 8.25 5 5"}],
  ["path", {"d":"m13.25 8.25-5 5"}],
]

const SearchXIcon: Icon = /* @__PURE__ */ createIcon("search-x", iconNode6)

const iconNode7: IconNode = [
  ["path", {"d":"M7 10.5h10a3 3 0 0 1 3 3V18a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3v-4.5a3 3 0 0 1 3-3"}],
  ["path", {"d":"M8 7.5V7a4 4 0 0 1 4-4 4 4 0 0 1 4 4v.5"}],
]

const LockIcon: Icon = /* @__PURE__ */ createIcon("lock", iconNode7)

const iconNode8: IconNode = [
  ["path", {"d":"m4.5 12.75 3.23 3.23a2.5 2.5 0 0 0 3.54 0l8.48-8.48"}],
]

const CheckIcon: Icon = /* @__PURE__ */ createIcon("check", iconNode8)

function ModelPicker({
  models,
  providers,
  value: valueProp,
  defaultValue,
  onValueChange,
  renderProviderMark,
  loading = false,
  disabled = false,
  size = "md",
  side = "bottom",
  align = "start",
  searchPlaceholder = "Search models…",
  showLegend = true,
  open: openProp,
  onOpenChange,
  className,
}: ModelPickerProps) {
  const id = React.useId()
  const [openState, setOpenState] = React.useState(false)
  const open = openProp ?? openState
  const setOpen = (next: boolean) => {
    if (openProp === undefined) setOpenState(next)
    onOpenChange?.(next)
  }

  const [valueState, setValueState] = React.useState(defaultValue ?? models[0]?.id)
  const value = valueProp ?? valueState
  const selected = models.find((m) => m.id === value)

  const [query, setQuery] = React.useState("")
  const [active, setActive] = React.useState<string>()
  const inputRef = React.useRef<HTMLInputElement>(null)
  const listRef = React.useRef<HTMLDivElement>(null)

  const providerList = React.useMemo(() => {
    const list: ModelProvider[] = [...(providers ?? [])]
    for (const m of models) {
      if (!list.some((p) => p.id === m.provider)) list.push({ id: m.provider, name: m.provider })
    }
    return list
  }, [models, providers])

  const groups = React.useMemo(
    () =>
      providerList
        .map((provider) => ({
          provider,
          models: models.filter(
            (m) => m.provider === provider.id && matches(m, provider.name, query.trim()),
          ),
        }))
        .filter((g) => g.models.length > 0),
    [providerList, models, query],
  )
  const flat = React.useMemo(() => groups.flatMap((g) => g.models), [groups])
  const fade = useScrollFade(groups)
  const { ref: fadeRef } = fade
  const setListRef = React.useCallback(
    (el: HTMLDivElement | null) => {
      listRef.current = el
      fadeRef(el)
    },
    [fadeRef],
  )
  const enabled = React.useMemo(() => flat.filter((m) => !m.disabled), [flat])

  // Keep the active option valid as the filter changes.
  React.useEffect(() => {
    if (!open) return
    if (active && enabled.some((m) => m.id === active)) return
    setActive(enabled.find((m) => m.id === value)?.id ?? enabled[0]?.id)
  }, [open, enabled, active, value])

  // Keep it in view. `nearest` never scrolls when it already shows.
  React.useEffect(() => {
    if (!open || !active) return
    const el = listRef.current?.querySelector<HTMLElement>(
      `[data-model-id="${CSS.escape(active)}"]`,
    )
    el?.scrollIntoView({ block: "nearest" })
  }, [open, active])

  const choose = (model: ModelOption) => {
    if (model.disabled) return
    if (valueProp === undefined) setValueState(model.id)
    onValueChange?.(model.id)
    setOpen(false)
  }

  const move = (delta: number) => {
    if (enabled.length === 0) return
    const index = enabled.findIndex((m) => m.id === active)
    const next = (index + delta + enabled.length) % enabled.length
    setActive(enabled[next]?.id)
  }

  const optionId = (modelId: string) => `${id}-option-${modelId}`
  const listId = `${id}-list`

  return (
    <Popover
      open={open}
      onOpenChange={(next) => {
        setOpen(next)
        if (!next) setQuery("")
      }}
    >
      <PopoverTrigger
        disabled={disabled}
        data-slot="model-picker-trigger"
        aria-label={
          selected ? `Model: ${selected.name}` : loading ? "Loading models" : "Choose a model"
        }
        aria-busy={loading || undefined}
        className={cn(
          "chatcn-focus group/model-trigger inline-flex min-w-0 shrink items-center gap-1.5 font-medium whitespace-nowrap select-none",
          "text-(color:--chatcn-fg-muted) hover:bg-(color:--chatcn-fill-hover) hover:text-(color:--chatcn-fg) data-[popup-open]:bg-(color:--chatcn-fill-hover) data-[popup-open]:text-(color:--chatcn-fg)",
          "ease-(--chatcn-ease-standard) transition-[background-color,color,scale] duration-150 active:scale-(--chatcn-press-scale) active:duration-100",
          "disabled:pointer-events-none disabled:opacity-50",
          size === "sm"
            ? "rounded-(--chatcn-radius-sm) text-[0.8125rem]/[1.25rem] h-7 ps-2 pe-1.5"
            : "rounded-(--chatcn-radius-md) text-[0.8125rem]/[1.25rem] h-8 ps-2.5 pe-2",
          "pointer-coarse:h-11",
          className,
        )}
      >
        {selected && renderProviderMark ? (
          <span aria-hidden="true" className="grid size-4 shrink-0 place-items-center">
            {renderProviderMark(selected.provider)}
          </span>
        ) : null}
        {loading && !selected ? <Spinner className="text-(color:--chatcn-fg-subtle)" /> : null}
        <span className="truncate">
          {selected?.name ?? (loading ? "Loading models" : "Choose a model")}
        </span>
        <ChevronDownIcon
          aria-hidden="true"
          className="text-(color:--chatcn-fg-subtle) group-hover/model-trigger:text-(color:--chatcn-fg) size-3.5 shrink-0"
        />
      </PopoverTrigger>

      <PopoverContent
        aria-label="Models"
        side={side}
        align={align}
        // Touch opens on the list so the keyboard does not cover it; everything else searches.
        initialFocus={(type) => (type === "touch" ? true : inputRef.current)}
        data-slot="model-picker-content"
        className="flex w-88 max-w-[calc(100vw-1rem)] flex-col overflow-hidden p-0"
      >
        <div className="border-(color:--chatcn-border) flex h-10 shrink-0 items-center gap-2 border-b px-3">
          <SearchIcon aria-hidden="true" className="text-(color:--chatcn-fg-subtle) size-4 shrink-0" />
          <input
            ref={inputRef}
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            onKeyDown={(event) => {
              if (event.nativeEvent.isComposing) return
              if (event.key === "ArrowDown") {
                event.preventDefault()
                move(1)
              } else if (event.key === "ArrowUp") {
                event.preventDefault()
                move(-1)
              } else if (event.key === "Enter") {
                event.preventDefault()
                const model = enabled.find((m) => m.id === active)
                if (model) choose(model)
              }
            }}
            role="combobox"
            aria-expanded="true"
            aria-controls={listId}
            aria-autocomplete="list"
            aria-activedescendant={active ? optionId(active) : undefined}
            aria-label="Search models"
            placeholder={searchPlaceholder}
            autoComplete="off"
            spellCheck={false}
            className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) placeholder:text-(color:--chatcn-fg-subtle) pointer-coarse:text-[1rem]/[1.5rem] pointer-coarse:tracking-[-0.01em] h-full min-w-0 flex-1 bg-transparent outline-none"
          />
        </div>

        <div
          ref={setListRef}
          id={listId}
          role="listbox"
          aria-label="Models"
          onScroll={fade.update}
          data-fade-top={fade.top ? "" : undefined}
          data-fade-bottom={fade.bottom ? "" : undefined}
          className={cn(
            "chatcn-scroll max-h-80 min-h-0 flex-1 scroll-py-1 overflow-y-auto overscroll-contain p-1",
            // The row cut by an edge fades out instead of ending mid-glyph.
            "data-[fade-bottom]:[--chatcn-fade-bottom:24px] data-[fade-top]:[--chatcn-fade-top:24px]",
            "[mask-image:linear-gradient(to_bottom,transparent,#000_var(--chatcn-fade-top,0px),#000_calc(100%-var(--chatcn-fade-bottom,0px)),transparent)]",
          )}
        >
          {loading ? (
            <div className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-subtle) flex h-24 items-center justify-center gap-2">
              <Spinner />
              Loading models
            </div>
          ) : groups.length === 0 ? (
            <div className="flex flex-col items-center gap-1 px-6 py-8 text-center">
              <SearchXIcon aria-hidden="true" className="text-(color:--chatcn-fg-subtle) mb-1 size-5" />
              <p className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg) font-medium">
                No models match “{query.trim()}”
              </p>
              <p className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) text-pretty">
                Try a provider or a capability, like vision.
              </p>
            </div>
          ) : (
            groups.map(({ provider, models: groupModels }) => {
              const labelId = `${id}-group-${provider.id}`
              return (
                // biome-ignore lint/a11y/useSemanticElements: option groups inside a listbox
                <div
                  key={provider.id}
                  role="group"
                  aria-labelledby={labelId}
                  className="not-first:mt-1"
                >
                  <div
                    id={labelId}
                    className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) flex h-7 items-center gap-1.5 px-2 font-medium select-none"
                  >
                    {renderProviderMark ? (
                      <span aria-hidden="true" className="grid size-3.5 place-items-center">
                        {renderProviderMark(provider.id)}
                      </span>
                    ) : null}
                    {provider.name}
                  </div>
                  {groupModels.map((model) => {
                    const isSelected = model.id === value
                    const isActive = model.id === active
                    return (
                      // biome-ignore lint/a11y/useKeyWithClickEvents: keys are handled on the combobox input
                      <div
                        key={model.id}
                        id={optionId(model.id)}
                        role="option"
                        aria-selected={isSelected}
                        aria-disabled={model.disabled || undefined}
                        data-model-id={model.id}
                        data-active={isActive ? "" : undefined}
                        tabIndex={-1}
                        onPointerMove={() => {
                          if (!model.disabled && !isActive) setActive(model.id)
                        }}
                        onClick={() => choose(model)}
                        className={cn(
                          "group/model-option rounded-(--chatcn-radius-md) flex cursor-default items-center gap-3 px-2 py-1.5 select-none",
                          "data-[active]:bg-(color:--chatcn-fill-hover) pointer-coarse:min-h-11",
                          model.disabled && "opacity-55",
                        )}
                      >
                        <span className="flex min-w-0 flex-1 flex-col">
                          <span className="flex min-w-0 items-center gap-1.5">
                            <span className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) truncate">
                              {model.name}
                            </span>
                            {model.isNew ? (
                              <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-muted) bg-(color:--chatcn-fill) rounded-(--chatcn-radius-xs) shrink-0 px-1.5 leading-[18px] font-medium">
                                New
                              </span>
                            ) : null}
                          </span>
                          {model.disabledReason || model.description ? (
                            <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) flex min-w-0 items-center gap-1">
                              {model.disabled ? (
                                <LockIcon aria-hidden="true" className="size-3 shrink-0" />
                              ) : null}
                              <span className="truncate">
                                {model.disabled
                                  ? (model.disabledReason ?? model.description)
                                  : model.description}
                              </span>
                            </span>
                          ) : null}
                        </span>
                        {/* Fixed slots, so each capability lines up in its own column. */}
                        {/* Quiet until the row is active: names read first, the footer holds the key. */}
                        <span className="text-(color:--chatcn-fg-faint) group-data-[active]/model-option:text-(color:--chatcn-fg-subtle) flex shrink-0 items-center gap-1.5">
                          {(Object.keys(CAPABILITIES) as ModelCapability[]).map((c) => {
                            const { Icon, label } = CAPABILITIES[c]
                            const has = model.capabilities?.includes(c)
                            return (
                              <span
                                key={c}
                                title={has ? label : undefined}
                                className="grid size-3.5 place-items-center"
                              >
                                {has ? (
                                  <>
                                    <Icon aria-hidden="true" className="size-3.5" />
                                    <span className="sr-only">{label}</span>
                                  </>
                                ) : null}
                              </span>
                            )
                          })}
                        </span>
                        <span
                          aria-hidden="true"
                          className="grid size-4 shrink-0 place-items-center"
                        >
                          {isSelected ? <CheckIcon className="text-(color:--chatcn-fg) size-4" /> : null}
                        </span>
                      </div>
                    )
                  })}
                </div>
              )
            })
          )}
        </div>

        {showLegend ? (
          <div
            aria-hidden="true"
            className="border-(color:--chatcn-border) text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) flex h-9 shrink-0 items-center gap-3 border-t px-3"
          >
            {(Object.keys(CAPABILITIES) as ModelCapability[]).map((c) => {
              const { Icon, label } = CAPABILITIES[c]
              return (
                <span key={c} className="flex items-center gap-1.5">
                  <Icon className="size-3.5" />
                  {label}
                </span>
              )
            })}
          </div>
        ) : null}
      </PopoverContent>
    </Popover>
  )
}

/** Made up models, so no real product is quoted. */
const MODELS: ModelOption[] = [
  { id: "atlas-pro", name: "Atlas Pro", provider: "atlas", description: "Strongest at code" },
  { id: "atlas-lite", name: "Atlas Lite", provider: "atlas", description: "Fast everyday answers" },
]

/* -------------------------------------------------------------------------------------------------
 * Items
 * -----------------------------------------------------------------------------------------------*/

interface MenuItemProps extends MenuPrimitive.Item.Props {
  /** Indent the label to line up with items that have an icon. */
  inset?: boolean
}

/* -------------------------------------------------------------------------------------------------
 * Geometry: a 12 px container with 4 px padding holds 8 px items, so the radii stay concentric.
 * Highlight is instant: menus are used too often for an animated hover.
 * -----------------------------------------------------------------------------------------------*/

const item = cn(
  "group/menu-item rounded-(--chatcn-radius-md) relative flex min-h-8 w-full cursor-default items-center gap-2 px-2 py-1.5",
  "text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) text-start outline-none select-none",
  "data-[highlighted]:bg-(color:--chatcn-fill-hover) data-[popup-open]:bg-(color:--chatcn-fill)",
  "data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
  "[&>svg]:text-(color:--chatcn-fg-subtle) data-[highlighted]:[&>svg]:text-(color:--chatcn-fg) [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  "pointer-coarse:min-h-11",
)

/** An action. Put an icon first and a `MenuShortcut` last; both are styled for you. */
function MenuItem({ className, inset, ...props }: MenuItemProps) {
  return (
    <MenuPrimitive.Item
      data-slot="menu-item"
      className={cn(item, inset && "ps-8", className)}
      {...props}
    />
  )
}

const iconNode9: IconNode = [
  ["path", {"d":"M9 2.75h6a1.5 1.5 0 0 1 1.5 1.5v.5a1 1 0 0 1-1 1h.25a1 1 0 0 0-1 1v2.8a1.5 1.5 0 0 0 .24.82l2 3.06a1.5 1.5 0 0 1-1.26 2.32H8.27a1.5 1.5 0 0 1-1.26-2.32l2-3.06a1.5 1.5 0 0 0 .24-.82v-2.8a1 1 0 0 0-1-1h.25a1 1 0 0 1-1-1v-.5A1.5 1.5 0 0 1 9 2.75"}],
  ["path", {"d":"M12 15.75v5.5"}],
]

const PinIcon: Icon = /* @__PURE__ */ createIcon("pin", iconNode9)

const iconNode10: IconNode = [
  ["path", {"d":"M3.5 15v2.5a3 3 0 0 0 3 3h11a3 3 0 0 0 3-3V15"}],
  ["path", {"d":"m7.5 10.5 3.09 3.09a2 2 0 0 0 2.82 0l3.09-3.09"}],
  ["path", {"d":"M12 3.5v7"}],
]

const DownloadIcon: Icon = /* @__PURE__ */ createIcon("download", iconNode10)

const iconNode11: IconNode = [
  ["path", {"d":"M4.75 3.5h14.5a2 2 0 0 1 2 2v1a2 2 0 0 1-2 2H4.75a2 2 0 0 1-2-2v-1a2 2 0 0 1 2-2"}],
  ["path", {"d":"M4.5 11.5v6.75a2.5 2.5 0 0 0 2.5 2.5h10a2.5 2.5 0 0 0 2.5-2.5V11.5"}],
  ["path", {"d":"M10 12.75h4"}],
]

const ArchiveIcon: Icon = /* @__PURE__ */ createIcon("archive", iconNode11)

function MenuSeparator({
  className,
  ...props
}: React.ComponentProps<typeof MenuPrimitive.Separator>) {
  return (
    <MenuPrimitive.Separator
      data-slot="menu-separator"
      className={cn("bg-(color:--chatcn-border) -mx-1 my-1 h-px", className)}
      {...props}
    />
  )
}

const iconNode12: IconNode = [
  ["path", {"d":"M3.5 6h17"}],
  ["path", {"d":"M10 3h4"}],
  ["path", {"d":"m5.75 9.25.6 9.41A2.5 2.5 0 0 0 8.85 21h6.3a2.5 2.5 0 0 0 2.5-2.34l.6-9.41"}],
  ["path", {"d":"M10 11.5V17"}],
  ["path", {"d":"M14 11.5V17"}],
]

const Trash2Icon: Icon = /* @__PURE__ */ createIcon("trash-2", iconNode12)

const menu = (
  <>
    <MenuItem>
      <PinIcon />
      Pin
    </MenuItem>
    <MenuItem>
      <DownloadIcon />
      Export as Markdown
    </MenuItem>
    <MenuItem>
      <ArchiveIcon />
      Archive
    </MenuItem>
    <MenuSeparator />
    <MenuItem className="text-(color:--chatcn-red) [&>svg]:text-(color:--chatcn-red)">
      <Trash2Icon />
      Delete
    </MenuItem>
  </>
)

/* -------------------------------------------------------------------------------------------------
 * 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 iconNode13: 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", iconNode13)

const iconNode14: 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", iconNode14)

/**
 * 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 iconNode15: 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", iconNode15)

/**
 * 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}
    />
  )
}

/** The pointer itself. Put it last inside the stage, which must be `relative`. */
function Ghost({ ghost }: { ghost: GhostState }) {
  return (
    <div
      aria-hidden
      className="pointer-events-none absolute top-0 left-0 z-20"
      style={{
        transform: `translate(${ghost.x}px, ${ghost.y}px)`,
        opacity: ghost.shown ? 1 : 0,
        // Hidden, it jumps; shown, it glides.
        transition: ghost.shown
          ? "transform 620ms cubic-bezier(0.4, 0, 0.2, 1), opacity 220ms ease-out"
          : "opacity 220ms ease-out",
      }}
    >
      <svg
        width="18"
        height="20"
        viewBox="0 0 18 20"
        className="drop-shadow-[0_1px_2px_rgb(0_0_0/0.25)]"
        style={{
          transform: ghost.down ? "scale(0.86)" : "scale(1)",
          transformOrigin: "2px 2px",
          transition: "transform 120ms ease-out",
        }}
      >
        <path
          d="M2 1.5 L2 16 L5.9 12.4 L8.6 18.3 L11.2 17.1 L8.6 11.3 L13.9 11.1 Z"
          className="fill-[oklch(0.2_0_0)] stroke-white dark:fill-white dark:stroke-[oklch(0.2_0_0)]"
          strokeWidth="1.3"
          strokeLinejoin="round"
        />
      </svg>
    </div>
  )
}

/** 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 chat window. The header starts as New chat; a question goes out and the title it generates
 * fades in while the reply streams. Then the pointer renames the chat in place: click the title,
 * type, Enter. Loops. Click anything to stop the tour and use it yourself.
 */
export default function ChatHeaderPreview() {
  const stage = React.useRef<HTMLDivElement>(null)
  const g = useGhost(stage)
  const [touring, setTouring] = React.useState(true)
  const [title, setTitle] = React.useState("")
  const [model, setModel] = React.useState("atlas-pro")
  const [value, setValue] = React.useState("")
  const [asked, setAsked] = React.useState<string | null>(null)
  const [reply, setReply] = React.useState("")

  useLoop(async (wait) => {
    setTitle("")
    setAsked(null)
    setReply("")
    setValue("")
    await wait(1200)
    for (let i = 1; i <= ASK.length; i += 1) {
      setValue(ASK.slice(0, i))
      await wait(CHAR_MS)
    }
    await wait(300)
    g.moveTo('[data-slot="prompt-input"] button[type="submit"]')
    await wait(650)
    g.press(true)
    await wait(130)
    g.press(false)
    setAsked(ASK)
    setValue("")
    g.hide()
    await wait(700)
    setTitle(GENERATED)
    const words = REPLY.split(" ")
    for (let i = 1; i <= words.length; i += 1) {
      setReply(words.slice(0, i).join(" "))
      await wait(WORD_MS)
    }
    await wait(900)
    await tap(g, '[data-slot="chat-header-title"] button', wait)
    await wait(350)
    const input = stage.current?.querySelector<HTMLInputElement>('[data-slot="chat-header-title-input"]')
    if (input) {
      setFieldValue(input, "")
      await wait(200)
      for (let i = 1; i <= RENAMED.length; i += 1) {
        setFieldValue(input, RENAMED.slice(0, i))
        await wait(CHAR_MS + 14)
      }
      await wait(450)
      pressKey(input, "Enter")
    }
    await wait(120)
    ;(document.activeElement as HTMLElement | null)?.blur()
    g.hide()
    await wait(2600)
  }, touring)

  return (
    <FitFrame minWidth="38rem">
      <div className="flex w-full flex-col items-center justify-center gap-3 p-4">
        <TooltipProvider>
          <div
            ref={stage}
            className="relative w-full max-w-2xl"
            onPointerDown={() => {
              if (!touring) return
              setTouring(false)
              g.hide()
            }}
          >
            <div className="bg-(color:--chatcn-bg) rounded-(--chatcn-radius-xl) shadow-(--chatcn-shadow-border) flex h-[23rem] w-full flex-col overflow-hidden">
              <ChatHeader
                title={title}
                onTitleChange={setTitle}
                model={
                  <ModelPicker models={MODELS} value={model} onValueChange={setModel} size="sm" />
                }
                onShare={() => {}}
                menu={menu}
              />
              <div className="min-h-0 flex-1 overflow-hidden">
                {asked ? (
                  <div className="flex flex-col gap-5 px-6 pt-3 pb-4">
                    <Message from="user">
                      <MessageContent>{asked}</MessageContent>
                    </Message>
                    {reply ? (
                      <Message from="assistant" animate={false}>
                        <MessageContent>{reply}</MessageContent>
                      </Message>
                    ) : null}
                  </div>
                ) : (
                  <div className="flex h-full items-center justify-center">
                    <h2 className="text-[1.5rem]/[2rem] tracking-[-0.022em] text-(color:--chatcn-fg) font-medium tracking-[-0.01em] transition-opacity duration-200 starting:opacity-0">
                      What are you working on?
                    </h2>
                  </div>
                )}
              </div>
              <div className="px-4 pb-4">
                <PromptInput
                  value={value}
                  onValueChange={setValue}
                  onSubmit={() => {
                    if (!value.trim()) return
                    setAsked(value)
                    setReply(REPLY)
                    setTitle(GENERATED)
                    setValue("")
                  }}
                >
                  <PromptInputTextarea placeholder="Ask anything…" />
                  <PromptInputToolbar>
                    <PromptInputActions>
                      <PromptInputSubmit />
                    </PromptInputActions>
                  </PromptInputToolbar>
                </PromptInput>
              </div>
            </div>
            <Ghost ghost={g.ghost} />
          </div>
        </TooltipProvider>
        <MoreOn slug="chat-header">The bar above a chat: a title you can rename, model, Share and More. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

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.