{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "streaming-text",
  "title": "Streaming text",
  "description": "Reveals an answer token by token at a steady speed with a cursor that blinks while waiting for more, stop and resume, word or character mode, and smooth catch-up when uneven SSE chunks arrive; reduced motion shows sentence chunks.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/ai/streaming-text.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens } from \"@/lib/goodui-motion\"\n\n/*\n * Reveals text the way a model streams it: tokens arrive at a steady rate and settle out of a 4px blur, with no caret\n * by default (a cursor is a prop). Pass the full text you have so far; as the string grows (SSE chunks) the reveal\n * catches up smoothly, so jittery chunk sizes read like one calm stream. The rest of the current word is laid out\n * invisibly, so a word never starts on one line and jumps to the next.\n */\n\nconst CSS = `\n@keyframes pc-stream-blink{0%,45%{opacity:1}50%,95%{opacity:0}100%{opacity:1}}\n@keyframes pc-stream-in{from{opacity:0;filter:blur(4px)}to{opacity:1;filter:blur(0)}}\n@keyframes pc-stream-pulse{0%,100%{transform:scale(.7);opacity:.5}50%{transform:scale(1);opacity:1}}\n.pc-stream-tail{animation:pc-stream-in .42s var(--pc-ease-out) both}\n.pc-stream-cursor{animation:pc-stream-blink 1s step-end infinite}\n.pc-stream-cursor[data-busy]{animation:none;opacity:1}\n.pc-stream-cursor[data-style=dot][data-busy]{animation:pc-stream-pulse .9s ease-in-out infinite}\n@media (prefers-reduced-motion:reduce){.pc-stream-tail,.pc-stream-cursor,.pc-stream-cursor[data-style=dot][data-busy]{animation:none;opacity:1;transform:none}}\n`\n\nexport type StreamingTextLabels = { streaming: string }\nconst DEFAULT_LABELS: StreamingTextLabels = { streaming: \"Streaming\" }\n\nexport type StreamingTextProps = Omit<React.ComponentProps<\"span\">, \"children\"> & {\n  /** All the text received so far. Growing it continues the stream; a different string starts over. */\n  text: string\n  /** Characters per second at a steady state. When a lot of text is waiting the reveal speeds up so it catches up within about a second. */\n  speed?: number\n  /** Reveal unit: single characters or whole words. */\n  by?: \"char\" | \"word\"\n  /** false pauses the reveal where it is (a Stop button); true resumes. */\n  playing?: boolean\n  /** More text may still arrive: the cursor stays and blinks while waiting. Set false once the response is complete. */\n  streaming?: boolean\n  /** Cursor style, or false for none (the default). */\n  cursor?: \"bar\" | \"block\" | \"dot\" | false\n  /** Keep the cursor after the text is complete and not streaming. */\n  cursorWhenDone?: boolean\n  /** New tokens fade in from a 4px blur instead of popping. */\n  fade?: boolean\n  /** Characters already visible at mount, or \"all\" to show restored history without replaying it. */\n  initialRevealed?: number | \"all\"\n  /** Change it to replay from the start. */\n  resetKey?: React.Key\n  /** Called when every character of `text` is visible and `streaming` is false. */\n  onComplete?: () => void\n  /** Called as the reveal advances, with visible and total character counts. */\n  onProgress?: (revealed: number, total: number) => void\n  /** Text for screen readers; pass translations here. */\n  labels?: Partial<StreamingTextLabels>\n}\n\nconst SPACE = /\\s/\n\n// Index just past the next word (leading spaces + the word) starting at `from`.\nfunction wordEnd(chars: string[], from: number) {\n  let i = from\n  while (i < chars.length && SPACE.test(chars[i] ?? \"\")) i++\n  while (i < chars.length && !SPACE.test(chars[i] ?? \"\")) i++\n  return i\n}\n\n// Reduced motion: whole sentences (or ~70-character chunks) appear at once.\nfunction chunkEnd(chars: string[], from: number) {\n  const limit = Math.min(chars.length, from + 110)\n  for (let i = from + 1; i < limit; i++) {\n    const c = chars[i] ?? \"\"\n    if (c === \"\\n\" || ((c === \".\" || c === \"!\" || c === \"?\") && SPACE.test(chars[i + 1] ?? \" \"))) return i + 1\n  }\n  return Math.min(chars.length, from + 70)\n}\n\n/** Token-by-token text reveal with a soft blur, stop/resume and smooth catch-up for live streams. */\nexport function StreamingText({\n  text,\n  speed = 60,\n  by = \"char\",\n  playing = true,\n  streaming = false,\n  cursor = false,\n  cursorWhenDone = false,\n  fade = true,\n  initialRevealed = 0,\n  resetKey,\n  onComplete,\n  onProgress,\n  labels,\n  className,\n  ...props\n}: StreamingTextProps) {\n  const l = useLabels(\"streaming-text\", DEFAULT_LABELS, labels)\n  const prefersReduced = useReducedMotion()\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  const reduce = mounted && !!prefersReduced\n\n  const chars = React.useMemo(() => Array.from(text), [text])\n  const total = chars.length\n  const [revealed, setRevealed] = React.useState(() => (initialRevealed === \"all\" ? total : Math.min(initialRevealed, total)))\n  const revealedRef = React.useRef(revealed)\n\n  // A text that no longer starts with what was shown is a new message: start over.\n  const [prevText, setPrevText] = React.useState(text)\n  if (prevText !== text) {\n    setPrevText(text)\n    const shownSoFar = Array.from(prevText).slice(0, revealed).join(\"\")\n    if (!text.startsWith(shownSoFar)) setRevealed(0)\n    else if (revealed > total) setRevealed(total)\n  }\n\n  const firstReset = React.useRef(true)\n  React.useEffect(() => {\n    if (firstReset.current) {\n      firstReset.current = false\n      return\n    }\n    setRevealed(0)\n  }, [resetKey])\n\n  React.useEffect(() => {\n    revealedRef.current = revealed\n  }, [revealed])\n\n  const progressRef = React.useRef(onProgress)\n  progressRef.current = onProgress\n  React.useEffect(() => {\n    progressRef.current?.(Math.min(revealed, total), total)\n  }, [revealed, total])\n\n  React.useEffect(() => {\n    if (!playing || revealedRef.current >= total) return\n    const commit = (next: number) => {\n      revealedRef.current = next\n      setRevealed(next)\n    }\n    if (reduce) {\n      const id = window.setInterval(() => {\n        if (document.hidden) return\n        const next = chunkEnd(chars, revealedRef.current)\n        commit(next)\n        if (next >= total) window.clearInterval(id)\n      }, 140)\n      return () => window.clearInterval(id)\n    }\n    let raf = 0\n    let last = 0\n    let budget = 0\n    const tick = (now: number) => {\n      if (last) {\n        const dt = Math.min(0.1, (now - last) / 1000)\n        const backlog = total - revealedRef.current\n        // Steady speed, but never more than about a second behind a live stream.\n        budget += dt * Math.max(speed, backlog / 0.9)\n        const cur = revealedRef.current\n        let next = cur\n        if (by === \"word\") {\n          for (;;) {\n            const e = wordEnd(chars, next)\n            if (e === next || e - cur > budget) break\n            next = e\n          }\n        } else next = Math.min(total, cur + Math.floor(budget))\n        if (next > cur) {\n          budget -= next - cur\n          commit(next)\n        }\n      }\n      last = now\n      if (revealedRef.current < total) raf = requestAnimationFrame(tick)\n    }\n    raf = requestAnimationFrame(tick)\n    return () => cancelAnimationFrame(raf)\n  }, [playing, total, chars, speed, by, reduce])\n\n  const shown = Math.min(revealed, total)\n  const done = shown >= total\n  const completeRef = React.useRef(onComplete)\n  completeRef.current = onComplete\n  const announced = React.useRef<string | null>(null)\n  React.useEffect(() => {\n    if (done && !streaming && announced.current !== text) {\n      announced.current = text\n      completeRef.current?.()\n    }\n    if (!done) announced.current = null\n  }, [done, streaming, text])\n\n  const busy = playing && (!done || streaming)\n  const showCursor = cursor && (busy || !done || (cursorWhenDone && done))\n  const animated = !done || streaming\n  // The tail is what is still fading, about 0.45s of text at the current pace, so catching up never cuts a fade short.\n  const TAIL = Math.min(96, Math.max(24, Math.ceil(Math.max(speed, (total - shown) / 0.9) * 0.45)))\n  const settledEnd = fade && !reduce ? Math.max(0, shown - TAIL) : shown\n\n  return (\n    <span className={cn(\"whitespace-pre-wrap\", className)} {...props}>\n      <GooduiTokens />\n      <style href=\"pc-streaming-text\" precedence=\"default\">\n        {CSS}\n      </style>\n      {animated && <span className=\"sr-only\">{text}</span>}\n      <span aria-hidden={animated ? true : undefined}>\n        {chars.slice(0, settledEnd).join(\"\")}\n        {settledEnd < shown &&\n          chars.slice(settledEnd, shown).map((ch, i) => (\n            <span key={settledEnd + i} className=\"pc-stream-tail\">\n              {ch}\n            </span>\n          ))}\n        {!done && !showCursor && !SPACE.test(chars[shown - 1] ?? \" \") && <span className=\"invisible\">{chars.slice(shown, wordEnd(chars, shown)).join(\"\")}</span>}\n      </span>\n      {showCursor && (\n        <span\n          aria-hidden=\"true\"\n          data-busy={busy ? \"\" : undefined}\n          data-style={cursor}\n          className={cn(\n            \"pc-stream-cursor ms-[0.1em] inline-block bg-current align-text-bottom\",\n            cursor === \"bar\" && \"h-[1.1em] w-[2px] rounded-full\",\n            cursor === \"block\" && \"h-[1.1em] w-[0.55em] rounded-[2px] opacity-80\",\n            cursor === \"dot\" && \"mb-[0.15em] size-[0.55em] rounded-full\",\n          )}\n        />\n      )}\n      {busy && <span className=\"sr-only\">{l.streaming}</span>}\n    </span>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/streaming-text.tsx"
    }
  ],
  "categories": [
    "components",
    "ai"
  ],
  "type": "registry:component"
}