{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "murmur",
  "type": "registry:ui",
  "title": "Murmur",
  "description": "Streaming assistant message — each arriving word fades up into place behind a breathing caret, with paragraphs, bullet lists and inline code chips, plus a shimmering \"Thinking\" disclosure that springs closed to \"Thought for Ns\". Announces completed paragraphs politely; ships a seeded useScriptedStream hook for prototyping.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/default/ai/murmur/murmur.tsx",
      "type": "registry:ui",
      "target": "components/crucible/murmur.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\n\n/* -------------------------------------------------------------------------- */\n/*                                   Parsing                                  */\n/* -------------------------------------------------------------------------- */\n\ntype Token =\n  | { kind: \"space\"; text: string }\n  | { kind: \"word\"; text: string; index: number }\n  | { kind: \"code\"; text: string; index: number };\n\ntype Block =\n  | { type: \"p\"; tokens: Token[]; plain: string }\n  | { type: \"ul\"; items: Token[][]; plain: string };\n\n/** Splits one line into prose words, whitespace and `code` spans. Unclosed\n *  backticks (mid-stream) render as code so the chip doesn't flicker. */\nfunction tokenizeLine(line: string, counter: { n: number }): Token[] {\n  const tokens: Token[] = [];\n  const parts = line.split(\"`\");\n  parts.forEach((part, i) => {\n    if (i % 2 === 1) {\n      if (part.length) tokens.push({ kind: \"code\", text: part, index: counter.n++ });\n      return;\n    }\n    for (const piece of part.split(/(\\s+)/)) {\n      if (!piece) continue;\n      if (/^\\s+$/.test(piece)) tokens.push({ kind: \"space\", text: \" \" });\n      else tokens.push({ kind: \"word\", text: piece, index: counter.n++ });\n    }\n  });\n  return tokens;\n}\n\n/** Lightweight block parser: blank lines split paragraphs, `- ` lines form a\n *  bullet list, inline `code` becomes a chip. Deliberately not markdown. */\nfunction parseBlocks(text: string): { blocks: Block[]; words: number } {\n  const counter = { n: 0 };\n  const blocks: Block[] = [];\n  let para: string[] = [];\n  let list: string[] = [];\n\n  const flushPara = () => {\n    if (!para.length) return;\n    const joined = para.join(\" \");\n    blocks.push({ type: \"p\", tokens: tokenizeLine(joined, counter), plain: joined.replace(/`/g, \"\") });\n    para = [];\n  };\n  const flushList = () => {\n    if (!list.length) return;\n    blocks.push({\n      type: \"ul\",\n      items: list.map((l) => tokenizeLine(l, counter)),\n      plain: list.map((l) => l.replace(/`/g, \"\")).join(\". \"),\n    });\n    list = [];\n  };\n\n  for (const raw of text.split(\"\\n\")) {\n    const line = raw.trim();\n    if (!line) {\n      flushPara();\n      flushList();\n    } else if (/^- /.test(line)) {\n      flushPara();\n      list.push(line.slice(2));\n    } else {\n      flushList();\n      para.push(line);\n    }\n  }\n  flushPara();\n  flushList();\n  return { blocks, words: counter.n };\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Component                                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface MurmurProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  /** The message text received so far. Blank lines split paragraphs, lines starting with `- ` become bullets, and `backticks` become inline code chips. */\n  text: string;\n  /** True while more text is still arriving. Shows the breathing caret and animates newly arrived words. @default false */\n  streaming?: boolean;\n  /** Optional reasoning text, shown in a collapsible \"Thinking\" section above the answer. */\n  reasoning?: string;\n  /** True while the assistant is still thinking. Keeps the section open, shimmers the label and counts seconds. When it turns false the section collapses to \"Thought for Ns\". @default false */\n  thinking?: boolean;\n  /** When thinking started, in epoch ms. Drives the elapsed counter. Defaults to the moment `thinking` became true. */\n  thinkingStartedAt?: number;\n  /** How long the thinking took, in seconds. Overrides the measured duration in the \"Thought for Ns\" label, useful when rendering a finished message. */\n  thinkingDuration?: number;\n  /** Accent for the caret, the thinking shimmer and focus rings. @default \"#a78bfa\" (ion violet) */\n  accentColor?: string;\n  /** How many trailing words get an animated span. Older words render as plain text. @default 40 */\n  trailingWords?: number;\n}\n\nconst STYLES = `\n@keyframes crucible-murmur-settle {\n  from { opacity: 0; transform: translateY(2px); }\n  to { opacity: 1; transform: translateY(0); }\n}\n@keyframes crucible-murmur-breathe {\n  0%, 100% { opacity: 1; }\n  50% { opacity: 0.35; }\n}\n@keyframes crucible-murmur-shimmer {\n  from { background-position: 100% 0; }\n  to { background-position: -100% 0; }\n}\n[data-crucible=\"murmur\"] .murmur-word {\n  display: inline-block;\n  animation: crucible-murmur-settle 280ms cubic-bezier(0.22, 1, 0.36, 1) both;\n}\n[data-crucible=\"murmur\"] .murmur-breathe {\n  animation: crucible-murmur-breathe 1s ease-in-out infinite;\n}\n[data-crucible=\"murmur\"] .murmur-shimmer {\n  background-image: linear-gradient(90deg, #a3a3a3 0%, #a3a3a3 35%, var(--murmur-accent) 50%, #a3a3a3 65%, #a3a3a3 100%);\n  background-size: 200% 100%;\n  -webkit-background-clip: text;\n  background-clip: text;\n  color: transparent;\n  animation: crucible-murmur-shimmer 1.8s linear infinite;\n}\n@media (prefers-reduced-motion: reduce) {\n  [data-crucible=\"murmur\"] .murmur-word,\n  [data-crucible=\"murmur\"] .murmur-breathe,\n  [data-crucible=\"murmur\"] .murmur-shimmer { animation: none; }\n}\n`;\n\nconst CODE_CHIP =\n  \"rounded-md border border-white/10 bg-white/[0.06] px-1.5 py-px font-mono text-[0.85em] text-neutral-100\";\n\nfunction renderTokens(tokens: Token[], animateFrom: number): React.ReactNode[] {\n  const out: React.ReactNode[] = [];\n  let plain = \"\";\n  const flush = () => {\n    if (plain) out.push(plain);\n    plain = \"\";\n  };\n  for (const t of tokens) {\n    if (t.kind === \"space\") {\n      plain += t.text;\n    } else if (t.kind === \"code\") {\n      flush();\n      out.push(\n        <code key={`c${t.index}`} className={cn(CODE_CHIP, t.index >= animateFrom && \"murmur-word\")}>\n          {t.text}\n        </code>\n      );\n    } else if (t.index >= animateFrom) {\n      flush();\n      out.push(\n        <span key={`w${t.index}`} className=\"murmur-word\">\n          {t.text}\n        </span>\n      );\n    } else {\n      plain += t.text;\n    }\n  }\n  flush();\n  return out;\n}\n\nfunction Caret({ reducedMotion }: { reducedMotion: boolean }) {\n  return (\n    <motion.span\n      aria-hidden\n      initial={{ opacity: 0, scaleY: 0.4 }}\n      animate={{ opacity: 1, scaleY: 1 }}\n      exit={{ opacity: 0, scaleY: 0 }}\n      transition={reducedMotion ? { duration: 0.12 } : { duration: 0.16, ease: \"easeOut\" }}\n      className=\"ml-0.5 inline-block h-[1.05em] w-[2px] origin-bottom translate-y-[0.18em] rounded-full align-baseline\"\n      style={{ backgroundColor: \"var(--murmur-accent)\", boxShadow: \"0 0 8px var(--murmur-accent)\" }}\n    >\n      <span className={cn(\"block h-full w-full rounded-full\", !reducedMotion && \"murmur-breathe\")} />\n    </motion.span>\n  );\n}\n\n/**\n * Murmur — an assistant message that streams in. Each newly arrived word\n * fades up from a 2px offset (only the trailing ~40 words carry spans, the rest\n * is plain text), and a soft accent caret breathes at the end of the line\n * until the stream ends, then shrinks away. Paragraphs, `- ` bullet lists and\n * inline `code` chips are supported without a markdown parser. An optional\n * \"Thinking\" disclosure sits above the answer: the label shimmers and counts\n * seconds while thinking, then springs closed to \"Thought for Ns\".\n *\n * Accessibility: the text is real and selectable. A polite live region\n * announces each paragraph once it is complete, never per token; the message\n * is `aria-busy` while streaming. The disclosure is a button with\n * `aria-expanded`. Under reduced motion words appear without the settle, the\n * caret and label stay static, and the disclosure uses a short fade.\n */\nexport function Murmur({\n  text,\n  streaming = false,\n  reasoning,\n  thinking = false,\n  thinkingStartedAt,\n  thinkingDuration,\n  accentColor = \"#a78bfa\",\n  trailingWords = 40,\n  className,\n  style,\n  ...props\n}: MurmurProps) {\n  const reducedMotion = useReducedMotion();\n  const panelId = React.useId();\n  const { blocks, words } = React.useMemo(() => parseBlocks(text), [text]);\n\n  // Only animate words once this instance has seen a live stream, so static\n  // messages don't fade their tail in on mount.\n  const [hasStreamed, setHasStreamed] = React.useState(streaming);\n  if (streaming && !hasStreamed) setHasStreamed(true);\n  const animateFrom = hasStreamed && !reducedMotion ? words - trailingWords : Number.POSITIVE_INFINITY;\n\n  /* ---------------------------- thinking state ---------------------------- */\n  const [open, setOpen] = React.useState(thinking);\n  const [prevThinking, setPrevThinking] = React.useState(thinking);\n  if (thinking !== prevThinking) {\n    setPrevThinking(thinking);\n    setOpen(thinking);\n  }\n\n  const [elapsed, setElapsed] = React.useState(0);\n  const [measured, setMeasured] = React.useState<number | null>(null);\n  React.useEffect(() => {\n    if (!thinking) return;\n    const start = thinkingStartedAt ?? Date.now();\n    const tick = () => setElapsed(Math.max(0, Math.floor((Date.now() - start) / 1000)));\n    tick();\n    const id = window.setInterval(tick, 250);\n    return () => {\n      window.clearInterval(id);\n      setMeasured(Math.max(1, Math.round((Date.now() - start) / 1000)));\n    };\n  }, [thinking, thinkingStartedAt]);\n\n  const duration = thinkingDuration ?? measured;\n  const showThinking = thinking || reasoning != null;\n\n  /* ------------------------------ announcer ------------------------------- */\n  // Announce completed blocks only: while streaming, the last block is still\n  // in flight. Static messages (never streamed) announce nothing.\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const announcedRef = React.useRef(0);\n  const completed = streaming ? Math.max(0, blocks.length - 1) : blocks.length;\n  React.useEffect(() => {\n    if (completed < announcedRef.current || text.length === 0) {\n      announcedRef.current = 0;\n      setAnnouncement(\"\");\n      return;\n    }\n    if (!hasStreamed || completed === announcedRef.current) return;\n    const fresh = blocks\n      .slice(announcedRef.current, completed)\n      .map((b) => b.plain)\n      .join(\" \");\n    announcedRef.current = completed;\n    setAnnouncement(fresh);\n  }, [blocks, completed, hasStreamed, text.length]);\n\n  /* -------------------------------- render -------------------------------- */\n  const caret = <AnimatePresence>{streaming && <Caret key=\"caret\" reducedMotion={reducedMotion} />}</AnimatePresence>;\n  const lastBlock = blocks.length - 1;\n\n  const panelTransition = reducedMotion\n    ? { height: { duration: 0 }, opacity: { duration: 0.15 } }\n    : { type: \"spring\" as const, stiffness: 320, damping: 34, mass: 0.8 };\n\n  return (\n    <div\n      data-crucible=\"murmur\"\n      className={cn(\"w-full text-[15px] leading-relaxed text-neutral-200\", className)}\n      style={{ \"--murmur-accent\": accentColor, ...style } as React.CSSProperties}\n      {...props}\n    >\n      <style>{STYLES}</style>\n\n      {showThinking && (\n        <div className=\"mb-3\">\n          <button\n            type=\"button\"\n            aria-expanded={open}\n            aria-controls={panelId}\n            onClick={() => setOpen((o) => !o)}\n            className=\"group -mx-1.5 inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-sm text-neutral-400 outline-none transition-colors hover:text-neutral-200 focus-visible:ring-2 focus-visible:ring-[color:var(--murmur-accent)]\"\n          >\n            <span className={cn(\"font-medium\", thinking && !reducedMotion && \"murmur-shimmer\")}>\n              {thinking ? \"Thinking…\" : duration != null ? `Thought for ${duration}s` : \"Thought process\"}\n            </span>\n            {thinking && <span className=\"tabular-nums text-neutral-500\">{elapsed}s</span>}\n            <svg\n              aria-hidden\n              viewBox=\"0 0 16 16\"\n              className={cn(\n                \"size-3.5 text-neutral-500\",\n                !reducedMotion && \"transition-transform duration-200\",\n                open && \"rotate-90\"\n              )}\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth=\"1.6\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n            >\n              <path d=\"M6 3.5 10.5 8 6 12.5\" />\n            </svg>\n          </button>\n          <AnimatePresence initial={false}>\n            {open && (\n              <motion.div\n                key=\"panel\"\n                id={panelId}\n                initial={{ height: 0, opacity: 0 }}\n                animate={{ height: \"auto\", opacity: 1 }}\n                exit={{ height: 0, opacity: 0 }}\n                transition={panelTransition}\n                className=\"overflow-hidden\"\n              >\n                <div className=\"mt-2 max-h-48 overflow-y-auto whitespace-pre-line border-l border-white/10 pl-3 text-sm leading-relaxed text-neutral-500\">\n                  {reasoning || (thinking ? \"…\" : \"\")}\n                </div>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n      )}\n\n      <div aria-busy={streaming || undefined} className=\"space-y-3\">\n        {blocks.map((block, bi) => {\n          const isLast = bi === lastBlock;\n          if (block.type === \"p\") {\n            return (\n              <p key={`p${bi}`}>\n                {renderTokens(block.tokens, animateFrom)}\n                {isLast && caret}\n              </p>\n            );\n          }\n          return (\n            <ul key={`ul${bi}`} className=\"list-disc space-y-1 pl-5 marker:text-neutral-500\">\n              {block.items.map((item, ii) => (\n                <li key={ii}>\n                  {renderTokens(item, animateFrom)}\n                  {isLast && ii === block.items.length - 1 && caret}\n                </li>\n              ))}\n            </ul>\n          );\n        })}\n        {blocks.length === 0 && streaming && <p>{caret}</p>}\n      </div>\n\n      <div aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n        {announcement}\n      </div>\n    </div>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                              useScriptedStream                             */\n/* -------------------------------------------------------------------------- */\n\nexport interface ScriptedStreamOptions {\n  /** Average characters per second. @default 48 */\n  cps?: number;\n  /** Delay before the first character, in ms. @default 0 */\n  startDelay?: number;\n  /** Start streaming on mount. When false, call `restart()` to begin. @default true */\n  autoStart?: boolean;\n  /** Seed for the deterministic chunk sizes and cadence. @default 7 */\n  seed?: number;\n  /** Pauses playback while true. @default false */\n  paused?: boolean;\n  /** Element to watch: playback pauses while it is offscreen. */\n  viewportRef?: React.RefObject<Element | null>;\n}\n\nexport interface ScriptedStream {\n  /** The portion of the text revealed so far. */\n  text: string;\n  /** True while characters are still being revealed. */\n  streaming: boolean;\n  /** Clears the text and plays it again from the start (after `startDelay`). */\n  restart: () => void;\n}\n\n/** Deterministic integer hash of (seed, position) — no Math.random. */\nfunction hash(seed: number, n: number): number {\n  let h = (seed * 374761393 + n * 668265263) | 0;\n  h = Math.imul(h ^ (h >>> 13), 1274126177);\n  return (h ^ (h >>> 16)) >>> 0;\n}\n\n/**\n * Plays `fullText` out in token-sized chunks on a seeded, deterministic\n * cadence — for demos and for prototyping streaming UI without a backend.\n * Pauses offscreen (via `viewportRef`), on hidden tabs and on `paused`; tears down all timers\n * on unmount. Under reduced motion it returns the full text immediately.\n */\nexport function useScriptedStream(fullText: string, options: ScriptedStreamOptions = {}): ScriptedStream {\n  const { cps = 48, startDelay = 0, autoStart = true, seed = 7, paused = false, viewportRef } = options;\n  const reducedMotion = useReducedMotion();\n\n  const [pos, setPos] = React.useState(0);\n  const posRef = React.useRef(0);\n  const [stage, setStage] = React.useState<\"idle\" | \"delay\" | \"run\" | \"done\">(autoStart ? \"delay\" : \"idle\");\n  const [runId, setRunId] = React.useState(0);\n  const [inView, setInView] = React.useState(true);\n\n  // Restart when the script itself changes.\n  const [prevText, setPrevText] = React.useState(fullText);\n  if (prevText !== fullText) {\n    setPrevText(fullText);\n    posRef.current = 0;\n    setPos(0);\n    setStage(autoStart ? \"delay\" : \"idle\");\n  }\n\n  React.useEffect(() => {\n    const node = viewportRef?.current;\n    if (!node || typeof IntersectionObserver === \"undefined\") return;\n    const io = new IntersectionObserver(([entry]) => setInView(!!entry?.isIntersecting));\n    io.observe(node);\n    return () => io.disconnect();\n  }, [viewportRef]);\n\n  // Hidden tabs pause playback too, so a backgrounded demo doesn't finish unseen.\n  const [tabHidden, setTabHidden] = React.useState(false);\n  React.useEffect(() => {\n    const sync = () => setTabHidden(document.hidden);\n    sync();\n    document.addEventListener(\"visibilitychange\", sync);\n    return () => document.removeEventListener(\"visibilitychange\", sync);\n  }, []);\n\n  const halted = paused || !inView || tabHidden || reducedMotion;\n\n  React.useEffect(() => {\n    if (stage !== \"delay\" || halted) return;\n    const t = window.setTimeout(() => setStage(\"run\"), startDelay);\n    return () => window.clearTimeout(t);\n  }, [stage, runId, startDelay, halted]);\n\n  React.useEffect(() => {\n    if (stage !== \"run\" || halted) return;\n    const len = fullText.length;\n    let timer = 0;\n    const step = () => {\n      const p = posRef.current;\n      if (p >= len) {\n        setStage(\"done\");\n        return;\n      }\n      const h = hash(seed, p);\n      const k = 1 + (h % 5); // 1–5 chars per chunk, token-ish\n      const next = Math.min(len, p + k);\n      posRef.current = next;\n      setPos(next);\n      // Jitter 0.6×–1.4× around the target rate, plus a beat at line breaks.\n      const jitter = 0.6 + ((h >>> 8) % 1000) / 1250;\n      const pause = fullText.slice(p, next).includes(\"\\n\") ? 140 : 0;\n      timer = window.setTimeout(step, (k / Math.max(1, cps)) * 1000 * jitter + pause);\n    };\n    timer = window.setTimeout(step, 0);\n    return () => window.clearTimeout(timer);\n  }, [stage, runId, halted, fullText, cps, seed]);\n\n  const restart = React.useCallback(() => {\n    posRef.current = 0;\n    setPos(0);\n    setStage(\"delay\");\n    setRunId((r) => r + 1);\n  }, []);\n\n  if (reducedMotion) return { text: fullText, streaming: false, restart };\n  return { text: fullText.slice(0, pos), streaming: stage === \"run\" && pos < fullText.length, restart };\n}\n"
    }
  ]
}