{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-message",
  "title": "Chat message",
  "description": "User, assistant and system messages with avatars, grouping, a hover actions row (copy, good/bad, retry, edit), markdown-ish rendering of lists, quotes and fenced code into CodeBlocks, and a blinking caret while the answer streams.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/code-block.json",
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/ai/chat-message.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { motion, useReducedMotion } from \"motion/react\"\nimport { Check, CircleAlert, Copy, Pencil, RefreshCw, Sparkles, ThumbsDown, ThumbsUp, User } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { CodeBlock, type CodeLanguage } from \"@/components/goodui/code-block\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\n/*\n * One chat message: user, assistant or system. Assistant text is rendered from a markdown-ish string\n * (paragraphs, headings, lists, quotes, inline code, bold, links and fenced code blocks that become\n * CodeBlocks) and gets a streaming caret while the answer is still arriving. Hover or focus reveals the actions\n * row (copy, good/bad, retry, edit). `grouped` hides the avatar and name for a follow-up message from the same\n * author.\n */\n\nconst CSS = `\n@keyframes pc-chat-blink{0%,45%{opacity:1}50%,95%{opacity:0}100%{opacity:1}}\n.pc-chat-caret{display:inline-block;width:2px;height:1.05em;margin-inline-start:.15em;vertical-align:text-bottom;border-radius:9999px;background:currentColor;animation:pc-chat-blink 1s step-end infinite}\n.pc-chat-actions{opacity:0;transition:opacity .15s}\n.pc-chat:hover .pc-chat-actions,.pc-chat:focus-within .pc-chat-actions,.pc-chat-actions[data-pinned]{opacity:1}\n@media (hover:none){.pc-chat-actions{opacity:1}}\n@media (prefers-reduced-motion:reduce){.pc-chat-caret{animation:none}}\n`\n\n/* ------------------------------------------------------------ markdown-ish */\n\nexport type MarkdownBlock =\n  | { type: \"p\"; text: string }\n  | { type: \"h\"; level: number; text: string }\n  | { type: \"ul\"; items: string[] }\n  | { type: \"ol\"; items: string[]; start: number }\n  | { type: \"code\"; lang: string; code: string }\n  | { type: \"quote\"; text: string }\n  | { type: \"hr\" }\n\nconst UL = /^\\s*[-*+]\\s+/\nconst OL = /^\\s*(\\d+)[.)]\\s+/\nconst HEADING = /^(#{1,4})\\s+(.*)$/\nconst FENCE_OPEN = /^\\s*```\\s*([\\w+#-]*)\\s*$/\nconst FENCE_CLOSE = /^\\s*```\\s*$/\n\n/** Splits a markdown-ish string into blocks. Unterminated fences (while streaming) render as code. */\nexport function parseMarkdown(src: string): MarkdownBlock[] {\n  const lines = src.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\")\n  const blocks: MarkdownBlock[] = []\n  let i = 0\n  const special = (s: string) => !s.trim() || FENCE_OPEN.test(s) || HEADING.test(s) || UL.test(s) || OL.test(s) || /^\\s*>/.test(s)\n  while (i < lines.length) {\n    const line = lines[i] ?? \"\"\n    const fence = FENCE_OPEN.exec(line)\n    if (fence) {\n      const buf: string[] = []\n      i++\n      while (i < lines.length && !FENCE_CLOSE.test(lines[i] ?? \"\")) buf.push(lines[i++] ?? \"\")\n      i++\n      blocks.push({ type: \"code\", lang: fence[1] ?? \"\", code: buf.join(\"\\n\") })\n      continue\n    }\n    if (!line.trim()) {\n      i++\n      continue\n    }\n    const h = HEADING.exec(line)\n    if (h) {\n      blocks.push({ type: \"h\", level: h[1]?.length ?? 1, text: h[2] ?? \"\" })\n      i++\n      continue\n    }\n    if (/^\\s*([-*_])\\1{2,}\\s*$/.test(line)) {\n      blocks.push({ type: \"hr\" })\n      i++\n      continue\n    }\n    if (/^\\s*>/.test(line)) {\n      const buf: string[] = []\n      while (i < lines.length && /^\\s*>/.test(lines[i] ?? \"\")) buf.push((lines[i++] ?? \"\").replace(/^\\s*>\\s?/, \"\"))\n      blocks.push({ type: \"quote\", text: buf.join(\"\\n\") })\n      continue\n    }\n    if (UL.test(line) || OL.test(line)) {\n      const ordered = OL.test(line)\n      const start = ordered ? Number(OL.exec(line)?.[1] ?? 1) : 1\n      const items: string[] = []\n      while (i < lines.length) {\n        const s = lines[i] ?? \"\"\n        if (ordered ? OL.test(s) : UL.test(s)) items.push(s.replace(ordered ? OL : UL, \"\"))\n        else if (s.trim() && /^\\s{2,}/.test(s) && items.length) items[items.length - 1] += \" \" + s.trim()\n        else break\n        i++\n      }\n      blocks.push(ordered ? { type: \"ol\", items, start } : { type: \"ul\", items })\n      continue\n    }\n    const buf = [line]\n    i++\n    while (i < lines.length && !special(lines[i] ?? \"\")) buf.push(lines[i++] ?? \"\")\n    blocks.push({ type: \"p\", text: buf.join(\"\\n\") })\n  }\n  return blocks\n}\n\nconst INLINE = /(`[^`\\n]+`|\\*\\*[^*\\n]+\\*\\*|\\*[^*\\n]+\\*|\\[[^\\]\\n]+\\]\\([^)\\s]+\\)|https?:\\/\\/[^\\s)<]+)/g\n\n/** Renders inline code, bold, italic, links and bare URLs. */\nexport function renderInline(text: string): React.ReactNode[] {\n  return text.split(INLINE).map((part, i) => {\n    if (!part) return null\n    if (i % 2 === 0) return <React.Fragment key={i}>{part}</React.Fragment>\n    if (part.startsWith(\"`\")) {\n      return (\n        <code key={i} className=\"rounded-md bg-muted px-1.5 py-0.5 font-mono text-[0.86em]\">\n          {part.slice(1, -1)}\n        </code>\n      )\n    }\n    if (part.startsWith(\"**\")) return <strong key={i}>{part.slice(2, -2)}</strong>\n    if (part.startsWith(\"*\")) return <em key={i}>{part.slice(1, -1)}</em>\n    const link = /^\\[([^\\]]+)\\]\\(([^)]+)\\)$/.exec(part)\n    const href = link ? (link[2] ?? \"\") : part\n    const label = link ? (link[1] ?? \"\") : part.replace(/^https?:\\/\\//, \"\")\n    return (\n      <a key={i} href={href} target=\"_blank\" rel=\"noreferrer\" className=\"font-medium underline decoration-foreground/30 underline-offset-[3px] transition-colors hover:decoration-foreground\">\n        {label}\n      </a>\n    )\n  })\n}\n\nconst LANGS = new Set([\"ts\", \"tsx\", \"js\", \"jsx\", \"json\", \"bash\", \"sh\", \"python\", \"py\", \"css\", \"html\", \"sql\", \"yaml\", \"yml\"])\nconst toLanguage = (lang: string): CodeLanguage => {\n  const k = lang.toLowerCase()\n  if (k === \"typescript\") return \"ts\"\n  if (k === \"javascript\") return \"js\"\n  if (k === \"shell\" || k === \"zsh\") return \"bash\"\n  return LANGS.has(k) ? (k as CodeLanguage) : \"text\"\n}\n\nexport type MessageMarkdownProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n  /** Markdown-ish text. */\n  text: string\n  /** Appends a blinking caret to the last block. */\n  streaming?: boolean\n}\n\n/** The markdown-ish renderer used by ChatMessage, usable on its own. */\nexport function MessageMarkdown({ text, streaming = false, className, ...props }: MessageMarkdownProps) {\n  const blocks = React.useMemo(() => parseMarkdown(text), [text])\n  const caret = <span className=\"pc-chat-caret\" aria-hidden=\"true\" />\n  return (\n    <div className={cn(\"pc-chat-md flex flex-col gap-3 text-[15px] leading-7 [&_ol]:list-decimal [&_ul]:list-disc\", className)} {...props}>\n      <style href=\"pc-chat-message\" precedence=\"default\">\n        {CSS}\n      </style>\n      {blocks.map((b, i) => {\n        const last = streaming && i === blocks.length - 1\n        switch (b.type) {\n          case \"h\": {\n            const Tag = (`h${Math.min(6, b.level + 2)}`) as \"h3\" | \"h4\" | \"h5\" | \"h6\"\n            return (\n              <Tag key={i} className={cn(\"font-semibold leading-snug\", b.level === 1 ? \"text-lg\" : \"text-base\")}>\n                {renderInline(b.text)}\n                {last && caret}\n              </Tag>\n            )\n          }\n          case \"ul\":\n          case \"ol\":\n            return React.createElement(\n              b.type,\n              { key: i, className: \"flex flex-col gap-1 ps-6\", start: b.type === \"ol\" ? b.start : undefined },\n              b.items.map((it, j) => (\n                <li key={j} className=\"ps-1\">\n                  {renderInline(it)}\n                  {last && j === b.items.length - 1 && caret}\n                </li>\n              )),\n            )\n          case \"code\":\n            return (\n              <React.Fragment key={i}>\n                <CodeBlock code={b.code} language={toLanguage(b.lang)} title={b.lang || undefined} className=\"text-[13px]\" />\n                {last && <span className=\"-mt-2 leading-none\">{caret}</span>}\n              </React.Fragment>\n            )\n          case \"quote\":\n            return (\n              <blockquote key={i} className=\"border-s-2 ps-4 whitespace-pre-wrap text-muted-foreground\">\n                {renderInline(b.text)}\n                {last && caret}\n              </blockquote>\n            )\n          case \"hr\":\n            return <hr key={i} className=\"my-1\" />\n          default:\n            return (\n              <p key={i} className=\"whitespace-pre-wrap\">\n                {renderInline(b.text)}\n                {last && caret}\n              </p>\n            )\n        }\n      })}\n      {blocks.length === 0 && streaming && <p>{caret}</p>}\n    </div>\n  )\n}\n\n/* ------------------------------------------------------------ message */\n\nexport type ChatRole = \"user\" | \"assistant\" | \"system\"\nexport type ChatFeedback = \"up\" | \"down\" | null\n\nexport type ChatMessageLabels = {\n  copy: string\n  copied: string\n  good: string\n  bad: string\n  retry: string\n  edit: string\n  sending: string\n  sent: string\n  failed: string\n  assistant: string\n  you: string\n  system: string\n}\nconst DEFAULT_LABELS: ChatMessageLabels = {\n  copy: \"Copy\",\n  copied: \"Copied\",\n  good: \"Good response\",\n  bad: \"Bad response\",\n  retry: \"Retry\",\n  edit: \"Edit message\",\n  sending: \"Sending…\",\n  sent: \"Sent\",\n  failed: \"Not sent\",\n  assistant: \"Assistant\",\n  you: \"You\",\n  system: \"System\",\n}\n\nexport type ChatMessageProps = Omit<React.ComponentProps<\"div\">, \"content\" | \"onDrag\" | \"onDragStart\" | \"onDragEnd\" | \"onAnimationStart\"> & {\n  role: ChatRole\n  /** Message text, rendered markdown-ish. Children render under it (tool calls, cards, custom content). */\n  content?: string\n  /** Author shown above assistant messages; also the fallback for the avatar initials. */\n  name?: string\n  /** Image URL or any node (icon, initials). Defaults to a sparkle for assistants and the user's initial. */\n  avatar?: React.ReactNode\n  /** Short time or date text, e.g. \"14:32\". */\n  time?: string\n  /** Delivery state for user messages. */\n  status?: \"sending\" | \"sent\" | \"error\"\n  /** The answer is still arriving: shows a caret and hides the actions row. */\n  streaming?: boolean\n  /** A follow-up message from the same author: no avatar or name, tighter spacing. */\n  grouped?: boolean\n  /** flat: assistant text sits on the page, user text in a bubble. bubble: both in bubbles. */\n  variant?: \"flat\" | \"bubble\"\n  /** User bubble color. */\n  tone?: \"neutral\" | \"primary\"\n  /** Show the actions row (copy and the handlers you pass). */\n  actions?: boolean\n  /** Text copied by the copy action; defaults to content. */\n  copyText?: string\n  onCopy?: (text: string) => void\n  /** Thumbs up/down; clicking the active one clears it. */\n  onFeedback?: (value: ChatFeedback) => void\n  /** Controlled feedback state. */\n  feedback?: ChatFeedback\n  /** Shown as a retry button on assistant messages and on failed user messages. */\n  onRetry?: () => void\n  /** Shown as an edit button on user messages. */\n  onEdit?: () => void\n  /** Fade and rise in on mount. */\n  animate?: boolean\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<ChatMessageLabels>\n}\n\nasync function writeClipboard(text: string) {\n  try {\n    await navigator.clipboard.writeText(text)\n    return true\n  } catch {\n    return false\n  }\n}\n\nfunction ActionButton({ label, pressed, className, children, ...props }: React.ComponentProps<\"button\"> & { label: string; pressed?: boolean }) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      title={label}\n      aria-pressed={pressed}\n      className={cn(\n        \"pc-press grid size-7 place-items-center rounded-md text-muted-foreground transition-[background-color,color,transform] outline-none hover:bg-muted hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-90\",\n        pressed && \"bg-muted text-foreground\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </button>\n  )\n}\n\n/** A chat bubble for user, assistant or system messages with markdown-ish content, streaming caret and actions. */\nexport function ChatMessage({\n  role,\n  content,\n  name,\n  avatar,\n  time,\n  status,\n  streaming = false,\n  grouped = false,\n  variant = \"flat\",\n  tone = \"neutral\",\n  actions = true,\n  copyText,\n  onCopy,\n  onFeedback,\n  feedback: feedbackProp,\n  onRetry,\n  onEdit,\n  animate = true,\n  labels,\n  className,\n  children,\n  ...props\n}: ChatMessageProps) {\n  const l = useLabels(\"chat-message\", DEFAULT_LABELS, labels)\n  const reduce = useReducedMotion() ?? false\n  const [copied, setCopied] = React.useState(false)\n  const [fbInner, setFbInner] = React.useState<ChatFeedback>(null)\n  const feedback = feedbackProp === undefined ? fbInner : feedbackProp\n  const user = role === \"user\"\n  const system = role === \"system\"\n  const author = name ?? (user ? l.you : system ? l.system : l.assistant)\n\n  React.useEffect(() => {\n    if (!copied) return\n    const id = window.setTimeout(() => setCopied(false), 1600)\n    return () => window.clearTimeout(id)\n  }, [copied])\n\n  const copy = async () => {\n    const text = copyText ?? content ?? \"\"\n    if (await writeClipboard(text)) setCopied(true)\n    onCopy?.(text)\n  }\n  const rate = (v: Exclude<ChatFeedback, null>) => {\n    const next = feedback === v ? null : v\n    if (feedbackProp === undefined) setFbInner(next)\n    onFeedback?.(next)\n  }\n\n  const avatarNode =\n    typeof avatar === \"string\" ? (\n      // eslint-disable-next-line @next/next/no-img-element\n      <img src={avatar} alt=\"\" className=\"size-full object-cover\" />\n    ) : avatar !== undefined ? (\n      avatar\n    ) : user ? (\n      name ? (\n        <span className=\"text-xs font-semibold\">{name.trim().charAt(0).toUpperCase()}</span>\n      ) : (\n        <User className=\"size-4\" aria-hidden=\"true\" />\n      )\n    ) : (\n      <Sparkles className=\"size-4\" aria-hidden=\"true\" />\n    )\n\n  if (system) {\n    return (\n      <motion.div\n        role=\"note\"\n        className={cn(\"pc-chat flex justify-center\", className)}\n        initial={animate ? { opacity: 0, y: 6 } : false}\n        animate={{ opacity: 1, y: 0 }}\n        transition={reduce ? { duration: 0 } : spring.ui}\n        {...props}\n      >\n        <GooduiTokens />\n        <style href=\"pc-chat-message\" precedence=\"default\">\n          {CSS}\n        </style>\n        <div className=\"max-w-[80%] rounded-full border bg-muted/60 px-3 py-1 text-center text-xs text-muted-foreground\">{content}</div>\n      </motion.div>\n    )\n  }\n\n  const hasCopy = content !== undefined || !!copyText\n  const showActions = actions && !streaming && (hasCopy || (!user && (onFeedback !== undefined || !!onRetry)) || (user && !!onEdit))\n  const bubble = user || variant === \"bubble\"\n\n  return (\n    <motion.div\n      data-role={role}\n      data-grouped={grouped || undefined}\n      className={cn(\"pc-chat group/msg flex gap-3\", user && \"flex-row-reverse\", grouped ? \"mt-1\" : \"mt-4 first:mt-0\", className)}\n      initial={animate ? { opacity: 0, y: 8 } : false}\n      animate={{ opacity: 1, y: 0 }}\n      transition={reduce ? { duration: 0 } : spring.ui}\n      {...props}\n    >\n      <style href=\"pc-chat-message\" precedence=\"default\">\n        {CSS}\n      </style>\n      <div className=\"w-7 shrink-0\">\n        {!grouped && (\n          <div\n            className={cn(\n              \"grid size-7 place-items-center overflow-hidden rounded-full\",\n              user ? \"bg-muted text-foreground\" : \"bg-[linear-gradient(135deg,var(--chart-1),var(--chart-4))] text-white\",\n            )}\n            aria-hidden=\"true\"\n          >\n            {avatarNode}\n          </div>\n        )}\n      </div>\n      <div className={cn(\"flex min-w-0 max-w-[85%] flex-col\", user ? \"items-end\" : \"flex-1 items-start\")}>\n        {!grouped && !user && (\n          <div className=\"mb-1 flex items-baseline gap-2 text-xs\">\n            <span className=\"font-medium\">{author}</span>\n            {time && <span className=\"text-muted-foreground\">{time}</span>}\n          </div>\n        )}\n        {user && <span className=\"sr-only\">{author}</span>}\n        <div\n          className={cn(\n            \"min-w-0\",\n            bubble && \"rounded-2xl px-4 py-2.5\",\n            bubble && user && (tone === \"primary\" ? \"bg-primary text-primary-foreground [&_code]:bg-primary-foreground/15\" : \"bg-muted\"),\n            bubble && !user && \"border bg-card\",\n            bubble && user && !grouped && \"rounded-se-md\",\n            bubble && !user && !grouped && \"rounded-ss-md\",\n            status === \"error\" && \"opacity-70\",\n          )}\n        >\n          {content !== undefined && <MessageMarkdown text={content} streaming={streaming} className={cn(user && \"text-[15px] leading-6\")} />}\n          {children}\n        </div>\n        {(user ? time || status : false) && (\n          <div className={cn(\"mt-1 flex items-center gap-1 text-[11px] text-muted-foreground\", status === \"error\" && \"text-rose-700 dark:text-rose-400\")}>\n            {status === \"error\" && <CircleAlert className=\"size-3\" aria-hidden=\"true\" />}\n            {status === \"sending\" ? l.sending : status === \"error\" ? l.failed : time}\n            {status === \"error\" && onRetry && (\n              <button type=\"button\" onClick={onRetry} className=\"pc-press ms-1 font-medium underline underline-offset-2 outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50\">\n                {l.retry}\n              </button>\n            )}\n          </div>\n        )}\n        {showActions && (\n          <div className={cn(\"pc-chat-actions -ms-1 mt-1 flex items-center gap-0.5\", user && \"-me-1 ms-0 flex-row-reverse\")} data-pinned={feedback ? \"\" : undefined}>\n            {hasCopy && (\n              <ActionButton label={copied ? l.copied : l.copy} onClick={copy}>\n                <span className=\"relative grid size-4 place-items-center\">\n                  <Copy className={cn(\"absolute size-4 transition-[opacity,transform] duration-200\", copied && \"scale-50 opacity-0\")} aria-hidden=\"true\" />\n                  <Check className={cn(\"absolute size-4 text-emerald-600 transition-[opacity,transform] duration-200 dark:text-emerald-400\", copied ? \"scale-100 opacity-100\" : \"scale-50 opacity-0\")} aria-hidden=\"true\" />\n                </span>\n                <span className=\"sr-only\" aria-live=\"polite\">\n                  {copied ? l.copied : \"\"}\n                </span>\n              </ActionButton>\n            )}\n            {!user && onFeedback !== undefined && (\n              <>\n                <ActionButton label={l.good} pressed={feedback === \"up\"} onClick={() => rate(\"up\")} className={cn(feedback === \"up\" && \"text-emerald-600 dark:text-emerald-400\")}>\n                  <motion.span key={feedback === \"up\" ? \"on\" : \"off\"} initial={reduce ? false : { scale: 0.6 }} animate={{ scale: 1 }} transition={spring.play} className=\"grid\">\n                    <ThumbsUp className=\"size-4\" fill={feedback === \"up\" ? \"currentColor\" : \"none\"} aria-hidden=\"true\" />\n                  </motion.span>\n                </ActionButton>\n                <ActionButton label={l.bad} pressed={feedback === \"down\"} onClick={() => rate(\"down\")} className={cn(feedback === \"down\" && \"text-rose-600 dark:text-rose-400\")}>\n                  <motion.span key={feedback === \"down\" ? \"on\" : \"off\"} initial={reduce ? false : { scale: 0.6 }} animate={{ scale: 1 }} transition={spring.play} className=\"grid\">\n                    <ThumbsDown className=\"size-4\" fill={feedback === \"down\" ? \"currentColor\" : \"none\"} aria-hidden=\"true\" />\n                  </motion.span>\n                </ActionButton>\n              </>\n            )}\n            {!user && onRetry && (\n              <ActionButton label={l.retry} onClick={onRetry} className=\"group/retry\">\n                <RefreshCw className=\"size-4 transition-transform duration-300 group-hover/retry:rotate-180\" aria-hidden=\"true\" />\n              </ActionButton>\n            )}\n            {user && onEdit && (\n              <ActionButton label={l.edit} onClick={onEdit}>\n                <Pencil className=\"size-4\" aria-hidden=\"true\" />\n              </ActionButton>\n            )}\n          </div>\n        )}\n      </div>\n    </motion.div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/chat-message.tsx"
    }
  ],
  "categories": [
    "components",
    "ai"
  ],
  "type": "registry:component"
}
