Aadi

Message Actions

AI chats

About

The toolbar under a chat message: copy, rate, retry, share and more, pinned on the latest reply and revealed on hover for older ones.

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

Code

How Message Actions 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 { Popover } from "@base-ui/react/popover"
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
import { Button, Icon, IconNode, MessageAction, MessageActionCopy, MessageActionMenu, MessageActions, MessageContext, MessageContextValue, MessageLayout, MessageRole, MessageState, Tooltip, createIcon, useMessage } from "@/components/ui/message-actions"

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

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

const REPLIES = [
  "Moved the cleanup job to 03:30 UTC, so it no longer overlaps the nightly backup, which starts at 02:00 and takes about 70 minutes.",
  "Moved the cleanup job to 04:00 UTC. The backup starts at 02:00 and finishes by 03:15, which leaves a 45 minute gap before cleanup runs.",
]

const WORD_MS = 55

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

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

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

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

const older =
  "The cleanup job runs at 02:00 UTC because that is when traffic is lowest across all regions."

const iconNode: IconNode = [
  ["path", {"d":"M5.49 17.46A8.5 8.5 0 1 0 6.54 5.49"}],
  ["path", {"d":"m8.21 8.65-2.94-.26a2 2 0 0 1-1.82-2.16l.26-2.94"}],
]

const RotateCcwIcon: Icon = /* @__PURE__ */ createIcon("rotate-ccw", iconNode)

const ask = "It overlaps the nightly backup. Move it later."

const iconNode2: IconNode = [
  ["path", {"d":"m3.79 18.63.87-2.6a1.5 1.5 0 0 1 .36-.58l9.65-9.65a2.5 2.5 0 0 1 3.53 0 2.5 2.5 0 0 1 0 3.53l-9.65 9.65a1.5 1.5 0 0 1-.58.36l-2.6.87a1.25 1.25 0 0 1-1.58-1.58"}],
  ["path", {"d":"m13.25 7.21 3.54 3.54"}],
]

const PencilIcon: Icon = /* @__PURE__ */ createIcon("pencil", iconNode2)

const DEFAULT_REASONS = [
  "Not factually correct",
  "Didn’t follow instructions",
  "Code doesn’t work",
  "Too long",
  "Something else",
]

type FeedbackValue = "up" | "down"

interface MessageFeedbackProps extends Omit<React.ComponentProps<"div">, "defaultValue"> {
  /** Controlled rating. `null` means not rated. */
  value?: FeedbackValue | null
  defaultValue?: FeedbackValue | null
  onValueChange?: (value: FeedbackValue | null) => void
  /** Reasons offered after a thumbs down. Pass an empty array to skip the question. */
  reasons?: string[]
  /** `chips` asks inline under the toolbar, `popover` asks in a popover with a note field. */
  reasonMode?: "chips" | "popover"
  /** Called when the user picks reasons (and, in the popover, writes a note). */
  onReason?: (reasons: string[], note?: string) => void
  /** Confirmation shown after a rating. Defaults to "Thanks for the feedback". */
  thanks?: string
}

const iconNode3: IconNode = [
  ["path", {"d":"M9.5 19.5v-9.06a1 1 0 0 1 .07-.37l1.85-4.71a1.75 1.75 0 0 1 2.66-.78l.14.1a1.5 1.5 0 0 1 .59 1.51l-.57 2.86a1 1 0 0 0 .98 1.2h2.12a2 2 0 0 1 1.97 2.37l-1.26 6.75A2 2 0 0 1 16.09 21H11a1.5 1.5 0 0 1-1.5-1.5"}],
  ["path", {"d":"M4.25 10.25H5a1.5 1.5 0 0 1 1.5 1.5v7.75A1.5 1.5 0 0 1 5 21h-.75a1.5 1.5 0 0 1-1.5-1.5v-7.75a1.5 1.5 0 0 1 1.5-1.5"}],
]

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

const iconNode4: IconNode = [
  ["path", {"d":"M9.5 4.5v9.06a1 1 0 0 0 .07.37l1.85 4.71a1.75 1.75 0 0 0 2.66.78l.14-.1a1.5 1.5 0 0 0 .59-1.51l-.57-2.86a1 1 0 0 1 .98-1.2h2.12a2 2 0 0 0 1.97-2.37l-1.26-6.75A2 2 0 0 0 16.09 3H11a1.5 1.5 0 0 0-1.5 1.5"}],
  ["path", {"d":"M4.25 13.75H5a1.5 1.5 0 0 0 1.5-1.5V4.5A1.5 1.5 0 0 0 5 3h-.75a1.5 1.5 0 0 0-1.5 1.5v7.75a1.5 1.5 0 0 0 1.5 1.5"}],
]

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

/* -------------------------------------------------------------------------------------------------
 * Thumb
 * -----------------------------------------------------------------------------------------------*/

/** A thumb that swaps outline for filled with a 150 ms blur crossfade, only when clicked. */
const Thumb = React.forwardRef<
  HTMLButtonElement,
  { kind: FeedbackValue; active: boolean; animate: boolean } & React.ComponentProps<"button">
>(function Thumb({ kind, active, animate, className, ...props }, ref) {
  const Icon = kind === "up" ? ThumbsUpIcon : ThumbsDownIcon
  const label = kind === "up" ? "Good response" : "Bad response"
  return (
    <Tooltip content={label}>
      <Button
        ref={ref}
        size="icon-sm"
        aria-label={label}
        aria-pressed={active}
        data-slot="message-feedback-button"
        className={cn(
          "relative",
          active ? "text-(color:--chatcn-fg)" : "text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg)",
          "pointer-coarse:after:absolute pointer-coarse:after:-inset-2 pointer-coarse:after:content-['']",
          className,
        )}
        {...props}
      >
        <span
          key={active ? "on" : "off"}
          className={cn(
            "grid place-items-center",
            animate && "motion-safe:animate-[chatcn-swap_150ms_var(--chatcn-ease-out)]",
          )}
        >
          <Icon fill={active ? "currentColor" : "none"} />
        </span>
      </Button>
    </Tooltip>
  )
})

/* -------------------------------------------------------------------------------------------------
 * Reasons
 * -----------------------------------------------------------------------------------------------*/

function ReasonChip({
  pressed,
  className,
  ...props
}: React.ComponentProps<"button"> & { pressed?: boolean }) {
  return (
    <button
      type="button"
      aria-pressed={pressed}
      className={cn(
        "chatcn-focus chatcn-press text-[0.75rem]/[1rem] inline-flex h-7 items-center rounded-full px-2.5 font-medium whitespace-nowrap select-none",
        "ease-(--chatcn-ease-standard) transition-[background-color,color,box-shadow,scale] duration-150",
        pressed
          ? "bg-(color:--chatcn-accent) text-(color:--chatcn-accent-fg)"
          : "bg-(color:--chatcn-card) text-(color:--chatcn-fg-muted) shadow-(--chatcn-shadow-xs) hover:bg-(color:--chatcn-fill-hover) hover:text-(color:--chatcn-fg)",
        "pointer-coarse:h-9",
        className,
      )}
      {...props}
    />
  )
}

const iconNode5: IconNode = [
  ["path", {"d":"m6 6 12 12"}],
  ["path", {"d":"m18 6-3.88 3.88"}],
  ["path", {"d":"M9.88 14.12 6 18"}],
]

const XIcon: Icon = /* @__PURE__ */ createIcon("x", iconNode5)

/* -------------------------------------------------------------------------------------------------
 * MessageFeedback
 * -----------------------------------------------------------------------------------------------*/

/**
 * Thumbs up and down. Up says thanks. Down asks what went wrong, inline or in a popover, and
 * then says thanks. Place it inside `MessageActions`; its parts join the toolbar row.
 */
function MessageFeedback({
  value: valueProp,
  defaultValue = null,
  onValueChange,
  reasons = DEFAULT_REASONS,
  reasonMode = "chips",
  onReason,
  thanks = "Thanks for the feedback",
  className,
  ...props
}: MessageFeedbackProps) {
  const [valueState, setValueState] = React.useState<FeedbackValue | null>(defaultValue)
  const value = valueProp !== undefined ? valueProp : valueState
  const [asking, setAsking] = React.useState(false)
  const [picked, setPicked] = React.useState<string[]>([])
  const [note, setNote] = React.useState("")
  const [thanksPhase, setThanksPhase] = React.useState<"hidden" | "in" | "out">("hidden")
  // Animate the icon swap only for pointer clicks. Keyboard-triggered changes are instant.
  const [animate, setAnimate] = React.useState(false)
  const pointer = React.useRef(false)
  const titleId = React.useId()

  React.useEffect(() => {
    if (thanksPhase === "hidden") return
    const id = window.setTimeout(
      () => setThanksPhase(thanksPhase === "in" ? "out" : "hidden"),
      thanksPhase === "in" ? 2400 : 150,
    )
    return () => window.clearTimeout(id)
  }, [thanksPhase])

  const set = (next: FeedbackValue | null) => {
    setAnimate(pointer.current)
    pointer.current = false
    if (valueProp === undefined) setValueState(next)
    onValueChange?.(next)
  }

  const choose = (kind: FeedbackValue) => {
    const next = value === kind ? null : kind
    set(next)
    setPicked([])
    setNote("")
    if (next === "down" && reasons.length > 0) {
      setAsking(true)
      setThanksPhase("hidden")
    } else {
      setAsking(false)
      setThanksPhase(next ? "in" : "hidden")
    }
  }

  const submit = (list: string[], text?: string) => {
    onReason?.(list, text?.trim() || undefined)
    setAsking(false)
    setThanksPhase("in")
  }

  const markPointer = () => {
    pointer.current = true
  }

  const group = (
    // biome-ignore lint/a11y/useSemanticElements: a pair of toggles, not a form fieldset
    <div
      role="group"
      aria-label="Rate this response"
      data-slot="message-feedback"
      data-feedback={value ?? undefined}
      // `contents` lets the thumbs and the reason row join the toolbar's flex row.
      className={cn("contents", className)}
      {...props}
    >
      <Thumb
        kind="up"
        active={value === "up"}
        animate={animate}
        onPointerDown={markPointer}
        onClick={() => choose("up")}
      />
      {reasonMode === "popover" ? (
        <Popover.Trigger
          render={
            <Thumb
              kind="down"
              active={value === "down"}
              animate={animate}
              onPointerDown={markPointer}
              onClick={() => choose("down")}
            />
          }
        />
      ) : (
        <Thumb
          kind="down"
          active={value === "down"}
          animate={animate}
          onPointerDown={markPointer}
          onClick={() => choose("down")}
        />
      )}

      {/* After every other action in the row, so saying thanks never pushes a button aside. */}
      <span
        aria-live="polite"
        data-slot="message-feedback-thanks"
        className={cn(
          "text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) order-last ms-1.5",
          "ease-(--chatcn-ease-out) transition-opacity duration-150 starting:opacity-0",
          thanksPhase === "out" && "opacity-0 duration-110",
          thanksPhase === "hidden" && "sr-only",
        )}
      >
        {thanksPhase === "hidden" ? "" : thanks}
      </span>

      {asking && reasonMode === "chips" ? (
        <div
          data-slot="message-feedback-reasons"
          className={cn(
            "order-last ms-1.5 mt-1.5 flex basis-full flex-wrap items-center gap-1.5",
            "motion-safe:animate-[chatcn-enter_180ms_var(--chatcn-ease-out)]",
          )}
        >
          <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) me-0.5">What went wrong?</span>
          {reasons.map((reason) => (
            <ReasonChip key={reason} onClick={() => submit([reason])}>
              {reason}
            </ReasonChip>
          ))}
          <Button
            size="icon-xs"
            aria-label="Skip"
            onClick={() => setAsking(false)}
            className="text-(color:--chatcn-fg-subtle)"
          >
            <XIcon />
          </Button>
        </div>
      ) : null}

      {reasonMode === "popover" ? (
        <Popover.Portal>
          <Popover.Positioner
            side="bottom"
            align="start"
            sideOffset={6}
            className="z-50 outline-none"
          >
            <Popover.Popup
              aria-labelledby={`${titleId}`}
              data-slot="message-feedback-popover"
              className={cn(
                "rounded-(--chatcn-radius-xl) bg-(color:--chatcn-surface) shadow-(--chatcn-shadow-lg) w-80 max-w-[calc(100vw-2rem)] origin-(--transform-origin) p-3 outline-none",
                "ease-(--chatcn-ease-out) transition-[opacity,scale] duration-180",
                "data-[starting-style]:scale-96 data-[starting-style]:opacity-0",
                "data-[ending-style]:scale-98 data-[ending-style]:opacity-0 data-[ending-style]:duration-140",
                "data-[instant]:transition-none motion-reduce:transition-none",
              )}
            >
              <form
                className="flex flex-col gap-3"
                onSubmit={(event) => {
                  event.preventDefault()
                  submit(picked, note)
                }}
              >
                <h2 id={titleId} className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) font-medium">
                  What went wrong?
                </h2>
                <div className="flex flex-wrap gap-1.5">
                  {reasons.map((reason) => (
                    <ReasonChip
                      key={reason}
                      pressed={picked.includes(reason)}
                      onClick={() =>
                        setPicked((list) =>
                          list.includes(reason)
                            ? list.filter((r) => r !== reason)
                            : [...list, reason],
                        )
                      }
                    >
                      {reason}
                    </ReasonChip>
                  ))}
                </div>
                <textarea
                  value={note}
                  onChange={(event) => setNote(event.target.value)}
                  onKeyDown={(event) => {
                    if (event.key !== "Enter" || event.shiftKey) return
                    if (event.nativeEvent.isComposing || event.keyCode === 229) return
                    event.preventDefault()
                    event.currentTarget.form?.requestSubmit()
                  }}
                  rows={2}
                  aria-label="Details"
                  placeholder="What should the answer have said…"
                  className={cn(
                    "rounded-(--chatcn-radius-md) bg-(color:--chatcn-inset) text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg) w-full resize-none px-2.5 py-2",
                    "placeholder:text-(color:--chatcn-fg-subtle) shadow-(--chatcn-shadow-border) outline-none",
                    "focus-visible:shadow-[0_0_0_1px_var(--chatcn-border-strong)]",
                  )}
                />
                <div className="flex items-center justify-end gap-1.5">
                  <Popover.Close render={<Button size="sm">Cancel</Button>} />
                  <Button
                    type="submit"
                    size="sm"
                    variant="solid"
                    disabled={picked.length === 0 && note.trim() === ""}
                  >
                    Send feedback
                  </Button>
                </div>
              </form>
            </Popover.Popup>
          </Popover.Positioner>
        </Popover.Portal>
      ) : null}
    </div>
  )

  if (reasonMode !== "popover") return group
  return (
    // Opening is driven by `choose`; the popover only reports dismissals (outside press, Esc).
    <Popover.Root open={asking} onOpenChange={(open) => (open ? undefined : setAsking(false))}>
      {group}
    </Popover.Root>
  )
}

const iconNode6: IconNode = [
  ["path", {"d":"M4.5 11v6.75a3 3 0 0 0 3 3h9a3 3 0 0 0 3-3V11"}],
  ["path", {"d":"m16 7.25-2.59-2.59a2 2 0 0 0-2.82 0L8 7.25"}],
  ["path", {"d":"M12 15.25v-7.5"}],
]

const ShareIcon: Icon = /* @__PURE__ */ createIcon("share", iconNode6)

const iconNode7: IconNode = [
  ["path", {"d":"M6 2.75V15"}],
  ["path", {"d":"M3 18a3 3 0 1 0 6 0 3 3 0 1 0-6 0"}],
  ["path", {"d":"M15 6a3 3 0 1 0 6 0 3 3 0 1 0-6 0"}],
  ["path", {"d":"M15 6a9 9 0 0 0-9 9"}],
]

const GitBranchIcon: Icon = /* @__PURE__ */ createIcon("git-branch", iconNode7)

const iconNode8: IconNode = [
  ["path", {"d":"M4.5 8.5h1.63a1.5 1.5 0 0 0 1.06-.44l1.68-1.68a1.25 1.25 0 0 1 2.13.89v9.46a1.25 1.25 0 0 1-2.13.89l-1.68-1.68a1.5 1.5 0 0 0-1.06-.44H4.5A1.5 1.5 0 0 1 3 14v-4a1.5 1.5 0 0 1 1.5-1.5"}],
  ["path", {"d":"M14.93 9.03a4 4 0 0 1 0 5.94"}],
  ["path", {"d":"M17.18 5.7a8 8 0 0 1 0 12.6"}],
]

const Volume2Icon: Icon = /* @__PURE__ */ createIcon("volume-2", iconNode8)

const iconNode9: IconNode = [
  ["path", {"d":"M4.5 21.25V4c3-2.25 5.25-1.5 7.5-.25s4.5 2 7.5 0v10c-3 2-5.25 1.25-7.5 0s-4.5-2-7.5.25"}],
]

const FlagIcon: Icon = /* @__PURE__ */ createIcon("flag", iconNode9)

/** 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 short thread. The pointer hovers the older reply to reveal its toolbar, rates the latest one,
 * then retries it: the reply streams again with its toolbar hidden until it lands. Loops. Click
 * anything to stop the tour and use the actions yourself.
 */
export default function MessageActionsPreview() {
  const stage = React.useRef<HTMLDivElement>(null)
  const g = useGhost(stage)
  const [touring, setTouring] = React.useState(true)
  const [hoverOlder, setHoverOlder] = React.useState(false)
  const [reply, setReply] = React.useState(0)
  const [shown, setShown] = React.useState<string | null>(null)
  const [round, setRound] = React.useState(0)
  const streamId = React.useRef(0)
  React.useEffect(() => () => window.clearInterval(streamId.current), [])

  useLoop(async (wait) => {
    setRound((r) => r + 1)
    setHoverOlder(false)
    await wait(900)
    g.moveTo('[data-demo="older"]', 0.55, 0.45)
    await wait(650)
    setHoverOlder(true)
    await wait(1500)
    setHoverOlder(false)
    await tap(g, '[data-demo="latest"] button[aria-label="Good response"]', wait)
    await wait(1500)
    await tap(g, '[data-demo="latest"] button[aria-label="Retry response"]', wait)
    await wait(200)
    g.hide()
    await wait(5000)
  }, touring)

  const text = REPLIES[reply]!
  const streaming = shown !== null

  // Retry: stream the other answer in word by word, then hand back the toolbar.
  const retry = () => {
    const next = (reply + 1) % REPLIES.length
    const words = REPLIES[next]!.split(" ")
    setReply(next)
    setRound((r) => r + 1)
    setShown("")
    let n = 0
    window.clearInterval(streamId.current)
    const id = window.setInterval(() => {
      n += 1
      if (n > words.length) {
        window.clearInterval(id)
        setShown(null)
        return
      }
      setShown(words.slice(0, n).join(" "))
    }, WORD_MS)
    streamId.current = id
  }

  return (
    <FitFrame minWidth="38rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <TooltipProvider>
          <div
            ref={stage}
            className="relative flex w-full max-w-2xl flex-col gap-5 overflow-hidden"
            onPointerDown={() => {
              if (!touring) return
              setTouring(false)
              setHoverOlder(false)
              g.hide()
            }}
          >
            <div data-demo="older">
              <Message from="assistant">
                <MessageContent>{older}</MessageContent>
                <MessageActions visible={hoverOlder || undefined}>
                  <MessageActionCopy value={older} label="Copy response" />
                  <MessageAction label="Retry response">
                    <RotateCcwIcon />
                  </MessageAction>
                </MessageActions>
              </Message>
            </div>

            <Message from="user">
              <MessageContent>{ask}</MessageContent>
              <MessageActions>
                <MessageActionCopy value={ask} label="Copy message" />
                <MessageAction label="Edit message">
                  <PencilIcon />
                </MessageAction>
              </MessageActions>
            </Message>

            <div data-demo="latest" className="min-h-[6.75rem]">
              <Message from="assistant" latest state={streaming ? "streaming" : "done"}>
                <MessageContent>{streaming ? shown : text}</MessageContent>
                <MessageActions>
                  <MessageActionCopy value={text} label="Copy response" />
                  <MessageFeedback key={round} />
                  <MessageAction label="Retry response" onClick={retry}>
                    <RotateCcwIcon />
                  </MessageAction>
                  <MessageAction label="Share response">
                    <ShareIcon />
                  </MessageAction>
                  <MessageActionMenu
                    items={[
                      { label: "Branch in new chat", icon: <GitBranchIcon /> },
                      { label: "Read aloud", icon: <Volume2Icon /> },
                      { label: "Report a problem", icon: <FlagIcon /> },
                    ]}
                  />
                </MessageActions>
              </Message>
            </div>
            <Ghost ghost={g.ghost} />
          </div>
        </TooltipProvider>
        <MoreOn slug="message-actions">Copy, rate, retry and more under each message. 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