{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-thread",
  "type": "registry:component",
  "title": "Chat Thread",
  "description": "A scrolling conversation with user and assistant bubbles, avatars, timestamps, a streaming last reply, a typing indicator and auto-scroll to the newest message.",
  "author": "Hyperblur <hello@hyperblur.dev>",
  "dependencies": [],
  "registryDependencies": [],
  "categories": [
    "agent-kit",
    "chat",
    "messages",
    "assistant",
    "thread",
    "streaming",
    "agent"
  ],
  "docs": "https://hyperblur.dev/effects/chat-thread",
  "files": [
    {
      "path": "registry/hyperblur/chat-thread.tsx",
      "type": "registry:component",
      "target": "components/hyperblur/chat-thread.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface ChatMessage {\n  id: string;\n  role: \"user\" | \"assistant\" | \"system\";\n  content: string;\n  time?: string;\n  streaming?: boolean;\n}\n\nexport interface ChatThreadProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  messages?: ChatMessage[];\n  userName?: string;\n  assistantName?: string;\n  avatars?: { user?: React.ReactNode; assistant?: React.ReactNode };\n  maxHeight?: number;\n  typing?: boolean;\n  color?: string;\n  speed?: number;\n}\n\nconst css = `\n@keyframes hb-ct-blink {\n  0%, 49.9% { opacity: 1; }\n  50%, 100% { opacity: 0; }\n}\n@keyframes hb-ct-dot {\n  0%, 80%, 100% { opacity: .3; transform: scale(.75); }\n  40% { opacity: 1; transform: scale(1); }\n}\n@keyframes hb-ct-in {\n  from { opacity: 0; transform: translateY(6px); }\n  to { opacity: 1; transform: none; }\n}\n.hb-ct {\n  box-sizing: border-box;\n  width: 100%;\n  overflow-y: auto;\n  border: 1px solid #262626;\n  border-radius: 14px;\n  color: #ededed;\n  font-family: var(--font-sans), ui-sans-serif, system-ui, sans-serif;\n  font-size: 13px;\n  line-height: 1.5;\n  background: #111111;\n  scrollbar-width: thin;\n  scrollbar-color: #2e2e2e transparent;\n}\n.hb-ct:focus-visible { outline: 2px solid var(--hb-ct-accent, #2f7bff); outline-offset: -2px; }\n.hb-ct-list { display: flex; flex-direction: column; gap: 12px; padding: 12px; }\n.hb-ct-row { display: flex; align-items: flex-end; gap: 8px; animation: hb-ct-in .3s ease both; }\n.hb-ct-row[data-role=\"user\"] { flex-direction: row-reverse; }\n.hb-ct-avatar {\n  display: grid;\n  flex: 0 0 auto;\n  place-items: center;\n  width: 24px;\n  height: 24px;\n  overflow: hidden;\n  border-radius: 50%;\n  font-size: 10px;\n  font-weight: 600;\n  letter-spacing: .02em;\n  color: #ffffff;\n  background: var(--hb-ct-accent, #2f7bff);\n}\n.hb-ct-avatar[data-role=\"assistant\"] { background: #8b5cf6; }\n.hb-ct-avatar > * { max-width: 100%; max-height: 100%; }\n.hb-ct-col { display: flex; flex-direction: column; gap: 3px; min-width: 0; max-width: calc(100% - 34px); }\n.hb-ct-row[data-role=\"user\"] .hb-ct-col { align-items: flex-end; }\n.hb-ct-bubble {\n  position: relative;\n  margin: 0;\n  padding: 8px 12px;\n  border: 1px solid #262626;\n  border-radius: 14px;\n  white-space: pre-wrap;\n  overflow-wrap: anywhere;\n  background: #171717;\n}\n.hb-ct-row[data-role=\"assistant\"] .hb-ct-bubble { border-bottom-left-radius: 4px; }\n.hb-ct-row[data-role=\"user\"] .hb-ct-bubble {\n  border-color: transparent;\n  border-bottom-right-radius: 4px;\n  color: #ffffff;\n  background: var(--hb-ct-accent, #2f7bff);\n}\n.hb-ct-time { padding: 0 4px; color: #8f8f8f; font-size: 10.5px; }\n.hb-ct-system { align-self: center; color: #8f8f8f; font-size: 11.5px; text-align: center; animation: hb-ct-in .3s ease both; }\n.hb-ct-b { font-weight: 600; color: #ffffff; }\n.hb-ct-c {\n  padding: 1px 5px;\n  border-radius: 5px;\n  font-family: var(--font-mono), ui-monospace, SFMono-Regular, Menlo, monospace;\n  font-size: .88em;\n  background: rgba(255,255,255,.1);\n}\n.hb-ct-row[data-role=\"assistant\"] .hb-ct-c { border: 1px solid #262626; background: #0d0d0d; }\n.hb-ct-caret {\n  display: inline-block;\n  width: 2px;\n  height: 1.05em;\n  margin-left: 2px;\n  vertical-align: -0.18em;\n  border-radius: 1px;\n  background: #8b5cf6;\n  animation: hb-ct-blink 1s linear infinite;\n}\n.hb-ct-typing { display: inline-flex; gap: 4px; align-items: center; padding: 6px 0; }\n.hb-ct-typing i {\n  width: 6px;\n  height: 6px;\n  border-radius: 50%;\n  background: #8f8f8f;\n  animation: hb-ct-dot 1.2s ease-in-out infinite;\n}\n.hb-ct-typing i:nth-child(2) { animation-delay: .15s; }\n.hb-ct-typing i:nth-child(3) { animation-delay: .3s; }\n.hb-ct-sr {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  overflow: hidden;\n  clip-path: inset(50%);\n  white-space: nowrap;\n}\n@media (prefers-reduced-motion: reduce) {\n  .hb-ct-row, .hb-ct-system { animation: none; }\n  .hb-ct-caret, .hb-ct-typing i { animation: none; }\n  .hb-ct-typing i { opacity: .7; }\n}\n`;\n\ntype Kind = \"t\" | \"b\" | \"c\" | \"n\";\n\ninterface Unit {\n  s: string;\n  k: Kind;\n}\n\nfunction parse(text: string): Unit[] {\n  const out: Unit[] = [];\n  text.split(\"\\n\").forEach((line, li) => {\n    if (li > 0) out.push({ s: \"\\n\", k: \"n\" });\n    line.split(/(\\*\\*[^*]+\\*\\*|`[^`]+`)/).forEach((seg) => {\n      if (!seg) return;\n      let k: Kind = \"t\";\n      let body = seg;\n      if (seg.length > 4 && seg.startsWith(\"**\") && seg.endsWith(\"**\")) {\n        k = \"b\";\n        body = seg.slice(2, -2);\n      } else if (seg.length > 2 && seg.startsWith(\"`\") && seg.endsWith(\"`\")) {\n        k = \"c\";\n        body = seg.slice(1, -1);\n      }\n      (body.match(/\\S+\\s*|\\s+/g) ?? []).forEach((s) => out.push({ s, k }));\n    });\n  });\n  return out;\n}\n\nfunction render(units: Unit[], count: number): React.ReactNode[] {\n  const nodes: React.ReactNode[] = [];\n  const end = Math.min(count, units.length);\n  let i = 0;\n  while (i < end) {\n    const k = units[i].k;\n    const from = i;\n    if (k === \"n\") {\n      nodes.push(<br key={from} />);\n      i += 1;\n      continue;\n    }\n    let s = \"\";\n    while (i < end && units[i].k === k) {\n      s += units[i].s;\n      i += 1;\n    }\n    if (k === \"b\") nodes.push(<strong key={from} className=\"hb-ct-b\">{s}</strong>);\n    else if (k === \"c\") nodes.push(<code key={from} className=\"hb-ct-c\">{s}</code>);\n    else nodes.push(<React.Fragment key={from}>{s}</React.Fragment>);\n  }\n  return nodes;\n}\n\nconst subscribe = () => () => {};\nconst getAnimate = () => !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\nconst getServerAnimate = () => false;\n\nfunction useStream(text: string, total: number, speed: number) {\n  const animate = React.useSyncExternalStore(subscribe, getAnimate, getServerAnimate);\n  const [count, setCount] = React.useState(0);\n  const [prev, setPrev] = React.useState(text);\n\n  if (prev !== text) {\n    setPrev(text);\n    setCount(0);\n  }\n\n  React.useEffect(() => {\n    if (!animate) return;\n    let n = 0;\n    let timer = 0;\n    const step = () => {\n      n += 1;\n      if (n >= total) {\n        setCount(total);\n        return;\n      }\n      setCount(n);\n      timer = window.setTimeout(step, speed);\n    };\n    timer = window.setTimeout(() => {\n      setCount(0);\n      timer = window.setTimeout(step, speed);\n    }, 0);\n    return () => window.clearTimeout(timer);\n  }, [animate, text, total, speed]);\n\n  if (!animate) return { shown: total, active: false };\n  const shown = Math.min(count, total);\n  return { shown, active: shown < total };\n}\n\nfunction StaticBody({ text }: { text: string }) {\n  const units = React.useMemo(() => parse(text), [text]);\n  return <>{render(units, units.length)}</>;\n}\n\nfunction StreamBody({ text, speed }: { text: string; speed: number }) {\n  const units = React.useMemo(() => parse(text), [text]);\n  const { shown, active } = useStream(text, units.length, speed);\n  return (\n    <>\n      {render(units, shown)}\n      {active ? <span className=\"hb-ct-caret\" aria-hidden=\"true\" /> : null}\n    </>\n  );\n}\n\nfunction initials(name: string) {\n  const parts = name.trim().split(/\\s+/).filter(Boolean);\n  if (parts.length === 0) return \"?\";\n  const first = Array.from(parts[0])[0] ?? \"?\";\n  const last = parts.length > 1 ? (Array.from(parts[parts.length - 1])[0] ?? \"\") : \"\";\n  return (first + last).toUpperCase();\n}\n\nexport function ChatThread({\n  messages = [],\n  userName = \"You\",\n  assistantName = \"Assistant\",\n  avatars,\n  maxHeight = 360,\n  typing = false,\n  color = \"#2f7bff\",\n  speed = 24,\n  className = \"\",\n  style,\n  ...rest\n}: ChatThreadProps) {\n  const scroller = React.useRef<HTMLDivElement>(null);\n  const content = React.useRef<HTMLDivElement>(null);\n  const stick = React.useRef(true);\n\n  let lastAssistant = -1;\n  messages.forEach((m, i) => {\n    if (m.role === \"assistant\") lastAssistant = i;\n  });\n\n  const scrollToEnd = React.useCallback(() => {\n    const el = scroller.current;\n    if (el) el.scrollTop = el.scrollHeight;\n  }, []);\n\n  React.useEffect(() => {\n    const box = content.current;\n    if (!box || typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver(() => {\n      if (stick.current) scrollToEnd();\n    });\n    ro.observe(box);\n    return () => ro.disconnect();\n  }, [scrollToEnd]);\n\n  React.useEffect(() => {\n    stick.current = true;\n    scrollToEnd();\n  }, [messages.length, typing, scrollToEnd]);\n\n  function onScroll() {\n    const el = scroller.current;\n    if (el) stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;\n  }\n\n  const avatarFor = (role: \"user\" | \"assistant\") => {\n    const custom = role === \"user\" ? avatars?.user : avatars?.assistant;\n    if (custom) return custom;\n    return initials(role === \"user\" ? userName : assistantName);\n  };\n\n  return (\n    <div\n      ref={scroller}\n      className={`hb-ct ${className}`}\n      style={{ maxHeight, \"--hb-ct-accent\": color, ...style } as React.CSSProperties}\n      role=\"log\"\n      aria-live=\"polite\"\n      aria-label=\"Conversation\"\n      tabIndex={0}\n      onScroll={onScroll}\n      {...rest}\n    >\n      <style href=\"hb-chat-thread\" precedence=\"default\">{css}</style>\n      <div ref={content} className=\"hb-ct-list\">\n        {messages.map((m, i) => {\n          if (m.role === \"system\") {\n            return (\n              <div key={m.id} className=\"hb-ct-system\">\n                {m.content}\n              </div>\n            );\n          }\n          const name = m.role === \"user\" ? userName : assistantName;\n          const live = m.role === \"assistant\" && m.streaming === true && i === lastAssistant && i === messages.length - 1;\n          return (\n            <div key={m.id} className=\"hb-ct-row\" data-role={m.role}>\n              <span className=\"hb-ct-avatar\" data-role={m.role} aria-hidden=\"true\">\n                {avatarFor(m.role)}\n              </span>\n              <div className=\"hb-ct-col\">\n                <p className=\"hb-ct-bubble\" aria-busy={live}>\n                  <span className=\"hb-ct-sr\">{name}: </span>\n                  {live ? <StreamBody text={m.content} speed={speed} /> : <StaticBody text={m.content} />}\n                </p>\n                {m.time ? <span className=\"hb-ct-time\">{m.time}</span> : null}\n              </div>\n            </div>\n          );\n        })}\n        {typing ? (\n          <div className=\"hb-ct-row\" data-role=\"assistant\">\n            <span className=\"hb-ct-avatar\" data-role=\"assistant\" aria-hidden=\"true\">\n              {avatarFor(\"assistant\")}\n            </span>\n            <div className=\"hb-ct-col\">\n              <div className=\"hb-ct-bubble\" role=\"status\" aria-label={`${assistantName} is typing`}>\n                <span className=\"hb-ct-typing\" aria-hidden=\"true\">\n                  <i />\n                  <i />\n                  <i />\n                </span>\n              </div>\n            </div>\n          </div>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n"
    }
  ]
}