{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "streaming-message",
  "title": "Streaming message",
  "description": "Assistant message that streams in word by word with a soft fade, light markdown (bold, inline code, lists, fenced code), code blocks that hold their frame while code arrives, a Stop button while streaming and Copy / Regenerate when done.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/components/streaming-message.tsx",
      "content": "\"use client\";\n\nimport { Fragment, useEffect, useRef, useState } from \"react\";\nimport { Check, Copy, RotateCcw, Square } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\n/** The fields this message reads from an AI SDK text part (`{ type: \"text\", text, state }`). */\nexport type TextPartLike = { type: string; text: string; state?: \"streaming\" | \"done\" };\n\nexport type StreamingMessageProps = {\n  /** Markdown-ish text: paragraphs, **bold**, `code`, \"- \" lists and ``` fenced code. */\n  text?: string;\n  /** True while tokens are still arriving. */\n  streaming?: boolean;\n  /** An AI SDK text part; fills text and streaming. */\n  part?: TextPartLike;\n  /** Shows a Stop button while streaming. */\n  onStop?: () => void;\n  /** Shows a Regenerate button once done. */\n  onRegenerate?: () => void;\n  /** Play a scripted reply on a loop while on screen, for demos. */\n  autoPlay?: boolean;\n  className?: string;\n};\n\nconst DEMO = `Here's a debounced value hook for your agent's search box. It waits **300 ms** after the last keystroke, so the model only sees finished queries.\n\n\\`\\`\\`tsx\nexport function useDebounce<T>(value: T, ms = 300) {\n  const [debounced, setDebounced] = useState(value);\n  useEffect(() => {\n    const id = setTimeout(() => setDebounced(value), ms);\n    return () => clearTimeout(id);\n  }, [value, ms]);\n  return debounced;\n}\n\\`\\`\\`\n\n- Send the debounced value to \\`useChat\\`, not the raw input\n- Keep the input itself controlled so typing never lags`;\n\n// Demo loop, in ms.\nconst START = 500;\nconst CHAR_MS = 7;\nconst HOLD = 3600;\nconst TICK = 40;\n\ntype Block =\n  | { kind: \"p\"; text: string; at: number }\n  | { kind: \"ul\"; items: { text: string; at: number }[] }\n  | { kind: \"code\"; lang: string; code: string; at: number; open: boolean };\n\n/** Split markdown-ish text into blocks. An unclosed fence stays a code block, so streaming code never jumps. */\nexport function parseBlocks(src: string): Block[] {\n  const blocks: Block[] = [];\n  const lines = src.split(\"\\n\");\n  let offset = 0;\n  let para: { text: string; at: number } | null = null;\n  let list: { text: string; at: number }[] | null = null;\n  const flush = () => {\n    if (para) blocks.push({ kind: \"p\", ...para });\n    if (list) blocks.push({ kind: \"ul\", items: list });\n    para = null;\n    list = null;\n  };\n\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i];\n    const lineAt = offset;\n    offset += line.length + 1;\n\n    const fence = line.match(/^```(\\w*)/);\n    if (fence) {\n      flush();\n      const lang = fence[1];\n      const start = offset;\n      let j = i + 1;\n      const body: string[] = [];\n      while (j < lines.length && !lines[j].startsWith(\"```\")) {\n        body.push(lines[j]);\n        offset += lines[j].length + 1;\n        j++;\n      }\n      const open = j >= lines.length;\n      if (!open) offset += lines[j].length + 1;\n      blocks.push({ kind: \"code\", lang, code: body.join(\"\\n\"), at: start, open });\n      i = j;\n      continue;\n    }\n    if (line.trim() === \"\") {\n      flush();\n      continue;\n    }\n    const item = line.match(/^\\s*[-*] (.*)$/);\n    if (item) {\n      if (para) flush();\n      list ??= [];\n      list.push({ text: item[1], at: lineAt + line.indexOf(item[1]) });\n      continue;\n    }\n    if (list) flush();\n    if (para) para.text += \" \" + line;\n    else para = { text: line, at: lineAt };\n  }\n  flush();\n  return blocks;\n}\n\ntype Seg = { text: string; at: number; style?: \"bold\" | \"code\" };\n\n/** **bold** and `code`; an unclosed marker at the end styles the rest, so text doesn't flash raw asterisks. */\nfunction inline(text: string, at: number): Seg[] {\n  const segs: Seg[] = [];\n  const re = /\\*\\*([^*]+)\\*\\*|`([^`]+)`/g;\n  let last = 0;\n  for (let m = re.exec(text); m; m = re.exec(text)) {\n    if (m.index > last) segs.push({ text: text.slice(last, m.index), at: at + last });\n    const inner = m[1] ?? m[2];\n    segs.push({ text: inner, at: at + m.index + 2, style: m[1] ? \"bold\" : \"code\" });\n    last = m.index + m[0].length;\n  }\n  let rest = text.slice(last);\n  let restAt = at + last;\n  const open = rest.match(/(\\*\\*|`)([^*`]*)$/);\n  if (open && open.index !== undefined) {\n    if (open.index > 0) segs.push({ text: rest.slice(0, open.index), at: restAt });\n    if (open[2]) segs.push({ text: open[2], at: restAt + open.index + open[1].length, style: open[1] === \"`\" ? \"code\" : \"bold\" });\n    rest = \"\";\n    restAt = 0;\n  }\n  if (rest) segs.push({ text: rest, at: restAt });\n  return segs;\n}\n\n/** Each word is keyed by its offset in the source, so only words that just arrived play the fade. */\nfunction Words({ segs, animate }: { segs: Seg[]; animate: boolean }) {\n  return (\n    <>\n      {segs.map((s) => {\n        const parts = s.text.split(/(\\s+)/);\n        let local = 0;\n        const words = parts.map((w) => {\n          // A segment that starts with a space splits into \"\" then \" \": both would get the same key.\n          if (!w) return null;\n          const key = s.at + local;\n          local += w.length;\n          if (!w.trim()) return <Fragment key={key}>{w}</Fragment>;\n          return (\n            <span key={key} className={animate ? \"streaming-message-word\" : undefined}>\n              {w}\n            </span>\n          );\n        });\n        if (s.style === \"bold\") return <strong key={s.at} className=\"font-semibold\">{words}</strong>;\n        if (s.style === \"code\")\n          return (\n            <code key={s.at} className=\"rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]\">\n              {words}\n            </code>\n          );\n        return <Fragment key={s.at}>{words}</Fragment>;\n      })}\n    </>\n  );\n}\n\nfunction CopyButton({ text, label, className }: { text: string; label: string; className?: string }) {\n  const [copied, setCopied] = useState(false);\n  return (\n    <button\n      type=\"button\"\n      aria-label={copied ? \"Copied\" : label}\n      onClick={async () => {\n        try {\n          await navigator.clipboard.writeText(text);\n          setCopied(true);\n          setTimeout(() => setCopied(false), 1600);\n        } catch {\n          // Clipboard can be blocked; nothing to undo.\n        }\n      }}\n      className={cn(\n        \"grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n        className,\n      )}\n    >\n      {copied ? <Check className=\"size-3.5\" aria-hidden /> : <Copy className=\"size-3.5\" aria-hidden />}\n    </button>\n  );\n}\n\n/** An assistant message that streams in word by word, with markdown, steady code blocks and actions when done. */\nexport function StreamingMessage({\n  text: textProp,\n  streaming: streamingProp,\n  part,\n  onStop,\n  onRegenerate,\n  autoPlay = false,\n  className,\n}: StreamingMessageProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotion();\n  const [visible, setVisible] = useState(false);\n  const [tick, setTick] = useState(0);\n\n  const STREAM_END = START + DEMO.length * CHAR_MS;\n  const LOOP = STREAM_END + HOLD;\n\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || !autoPlay) return;\n    const io = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    io.observe(el);\n    return () => io.disconnect();\n  }, [autoPlay]);\n\n  useEffect(() => {\n    if (!autoPlay || !visible || reduce) return;\n    const id = setInterval(() => setTick((t) => (t + TICK) % LOOP), TICK);\n    return () => clearInterval(id);\n  }, [autoPlay, visible, reduce, LOOP]);\n\n  let text = textProp ?? part?.text ?? DEMO;\n  let streaming = streamingProp ?? (part ? part.state === \"streaming\" : false);\n  if (autoPlay) {\n    const t = reduce ? LOOP - 1 : tick;\n    streaming = t < STREAM_END;\n    if (streaming) {\n      // Cut at a word boundary, the way tokens arrive.\n      const chars = Math.max(0, Math.floor((t - START) / CHAR_MS));\n      const cut = DEMO.slice(0, chars);\n      const space = Math.max(cut.lastIndexOf(\" \"), cut.lastIndexOf(\"\\n\"));\n      text = space > 0 ? cut.slice(0, space + 1) : \"\";\n    } else {\n      text = DEMO;\n    }\n  }\n\n  const animate = !reduce;\n  const blocks = parseBlocks(text);\n  const caret = streaming && !reduce && (\n    <span aria-hidden className=\"ml-0.5 inline-block h-[1em] w-1.5 translate-y-[0.15em] animate-pulse rounded-sm bg-foreground/70\" />\n  );\n  const lastIndex = blocks.length - 1;\n  const showStop = streaming && (onStop || autoPlay);\n  const showActions = !streaming && text.length > 0;\n\n  return (\n    <div ref={ref} className={cn(\"w-full max-w-lg text-foreground\", className)}>\n      <div className=\"space-y-3 text-sm leading-relaxed\" aria-busy={streaming}>\n        {blocks.length === 0 && caret}\n        {blocks.map((b, i) => {\n          const end = i === lastIndex ? caret : null;\n          if (b.kind === \"p\")\n            return (\n              <p key={b.at}>\n                <Words segs={inline(b.text, b.at)} animate={animate} />\n                {end}\n              </p>\n            );\n          if (b.kind === \"ul\")\n            return (\n              <ul key={b.items[0].at} className=\"list-disc space-y-1 pl-5 marker:text-muted-foreground\">\n                {b.items.map((it, k) => (\n                  <li key={it.at}>\n                    <Words segs={inline(it.text, it.at)} animate={animate} />\n                    {k === b.items.length - 1 && end}\n                  </li>\n                ))}\n              </ul>\n            );\n          return (\n            <div key={b.at} className=\"overflow-hidden rounded-lg border bg-muted/50\">\n              <div className=\"flex items-center justify-between border-b px-3 py-1\">\n                <span className=\"font-mono text-[11px] text-muted-foreground\">{b.lang || \"code\"}</span>\n                {!b.open && <CopyButton text={b.code} label=\"Copy code\" className=\"size-6\" />}\n              </div>\n              <pre className=\"overflow-x-auto px-3 py-2.5 font-mono text-[12px] leading-[1.6] [scrollbar-width:thin]\">\n                <code>\n                  <Words segs={[{ text: b.code, at: b.at }]} animate={animate} />\n                  {b.open && end}\n                </code>\n              </pre>\n            </div>\n          );\n        })}\n      </div>\n\n      <div className=\"mt-2 h-7\">\n        <AnimatePresence mode=\"wait\" initial={false}>\n          {showStop ? (\n            <motion.button\n              key=\"stop\"\n              type=\"button\"\n              onClick={onStop}\n              initial={reduce ? false : { opacity: 0, y: 4 }}\n              animate={{ opacity: 1, y: 0 }}\n              exit={reduce ? undefined : { opacity: 0 }}\n              transition={{ duration: 0.2 }}\n              className=\"flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-xs font-medium text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              <Square className=\"size-2.5 fill-current\" aria-hidden />\n              Stop\n            </motion.button>\n          ) : showActions ? (\n            <motion.div\n              key=\"actions\"\n              initial={reduce ? false : { opacity: 0, y: 4 }}\n              animate={{ opacity: 1, y: 0 }}\n              exit={reduce ? undefined : { opacity: 0 }}\n              transition={{ duration: 0.25 }}\n              className=\"flex items-center gap-0.5\"\n            >\n              <CopyButton text={text} label=\"Copy message\" />\n              {(onRegenerate || autoPlay) && (\n                <button\n                  type=\"button\"\n                  onClick={onRegenerate}\n                  aria-label=\"Regenerate\"\n                  className=\"grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n                >\n                  <RotateCcw className=\"size-3.5\" aria-hidden />\n                </button>\n              )}\n            </motion.div>\n          ) : null}\n        </AnimatePresence>\n      </div>\n\n      <style>{`\n        .streaming-message-word { animation: streaming-message-in 0.45s ease-out both; }\n        @keyframes streaming-message-in {\n          from { opacity: 0; filter: blur(2px); }\n          to { opacity: 1; filter: blur(0); }\n        }\n        @media (prefers-reduced-motion: reduce) {\n          .streaming-message-word { animation: none; }\n        }\n      `}</style>\n    </div>\n  );\n}\n\nexport default function StreamingMessageDemo() {\n  return <StreamingMessage autoPlay />;\n}\n",
      "type": "registry:component",
      "target": "components/nextui/streaming-message.tsx"
    }
  ],
  "meta": {
    "kind": "component",
    "category": "ai",
    "previewHeight": 480,
    "new": true,
    "free": true,
    "openSource": true,
    "added": "2026-10-31"
  },
  "categories": [
    "ai"
  ],
  "type": "registry:component"
}