{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "thread",
  "type": "registry:ui",
  "title": "Thread",
  "description": "The scrolling log of a conversation: it follows the newest content while the person is at the bottom, stops the moment they scroll up, and offers a way back down.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/ui/thread.tsx",
      "type": "registry:ui",
      "target": "components/ui/thread.tsx",
      "content": "\"use client\";\n/**\n * @name thread\n * @category ui\n * @description The scrolling log of a conversation: it follows the newest content while the person is at the bottom, stops the moment they scroll up, and offers a way back down.\n * @when A conversation with an assistant or between people, where messages arrive over time. It holds no messages and no transport: render them inside it (message, streaming-text, part-frame). The log is deliberately silent (`aria-live=\"off\"`): say what is happening through one status-line beside it, and the finished reply once through streaming-text's `announceWhenDone`. For a list that does not grow at the bottom use scroll-area.\n * @example\n * <Thread aria-label=\"Conversation with the assistant\" className=\"h-[32rem]\">\n *   <ThreadContent>\n *     {messages.length === 0 ? <ThreadEmpty>Ask anything to begin.</ThreadEmpty> : null}\n *     {messages.map((message) => (\n *       <ThreadTurn key={message.id} label={message.from === \"user\" ? \"You\" : \"Assistant\"}>\n *         <Message from={message.from}>\n *           <MessageBody><MessageContent>{message.text}</MessageContent></MessageBody>\n *         </Message>\n *       </ThreadTurn>\n *     ))}\n *   </ThreadContent>\n *   <ThreadJump>Jump to latest</ThreadJump>\n * </Thread>\n *\n * // Always show what the person just sent, even if they had scrolled up\n * <Thread aria-label=\"Conversation\" resumeKey={lastOwnMessageId}>…</Thread>\n */\nimport { ArrowDown } from \"lucide-react\";\nimport {\n  createContext,\n  use,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent,\n  type ReactNode,\n  type RefObject,\n} from \"react\";\nimport { cn } from \"@/lib/cn\";\n\n/** How close to the end, in pixels, still counts as \"at the bottom\". */\nconst NEAR_BOTTOM = 32;\n/** Keys that scroll a focused region up. */\nconst UP_KEYS = new Set([\"ArrowUp\", \"PageUp\", \"Home\"]);\n\ntype ThreadContextValue = {\n  viewportRef: RefObject<HTMLDivElement | null>;\n  /** Whether the view is at the newest content. */\n  atBottom: boolean;\n  /** Whether content has arrived since the person scrolled up. */\n  unseen: boolean;\n  /** Goes to the newest content and follows it again. */\n  scrollToBottom: (options?: { focus?: boolean }) => void;\n  label: { \"aria-label\"?: string | undefined; \"aria-labelledby\"?: string | undefined };\n  /** For ThreadContent: the person scrolled up by their own act. */\n  release: () => void;\n  onScroll: () => void;\n  onGrow: () => void;\n};\n\nconst ThreadContext = createContext<ThreadContextValue | null>(null);\n\nfunction useThreadContext(part: string): ThreadContextValue {\n  const context = use(ThreadContext);\n  if (!context) throw new Error(`<${part}> must be used inside <Thread>.`);\n  return context;\n}\n\n/** Where the thread is: for a project's own \"new messages\" marker or a custom jump control. */\nexport function useThread(): Pick<ThreadContextValue, \"atBottom\" | \"unseen\" | \"scrollToBottom\"> {\n  const { atBottom, unseen, scrollToBottom } = useThreadContext(\"useThread\");\n  return { atBottom, unseen, scrollToBottom };\n}\n\nexport type ThreadProps = ComponentProps<\"div\"> & {\n  /**\n   * When this value changes, the thread goes to the newest content and follows it again, wherever the person\n   * had scrolled to. Pass the id of the person's own latest message, so that what they send is always shown.\n   */\n  resumeKey?: string | number | null;\n};\n\n/**\n * The frame: give it a height (or let a flex parent do so) and a name with `aria-label` or\n * `aria-labelledby`, which is handed to the log inside. It never moves focus when content arrives.\n */\nexport function Thread({ className, children, resumeKey, \"aria-label\": ariaLabel, \"aria-labelledby\": ariaLabelledBy, ...props }: ThreadProps) {\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const [atBottom, setAtBottom] = useState(true);\n  const [unseen, setUnseen] = useState(false);\n  /** Whether new content pulls the view down. A ref: it is read in observers between renders. */\n  const following = useRef(true);\n  /** The last scroll position seen, to tell a scroll up (the person's) from content growing or a jump on its way down. */\n  const lastTop = useRef(0);\n\n  const scrollToBottom = useCallback((options?: { focus?: boolean }): void => {\n    const viewport = viewportRef.current;\n    if (!viewport) return;\n    following.current = true;\n    const smooth = !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    viewport.scrollTo({ top: viewport.scrollHeight, behavior: smooth ? \"smooth\" : \"instant\" });\n    setUnseen(false);\n    if (options?.focus) viewport.focus({ preventScroll: true });\n  }, []);\n\n  // The person sent something: show it. The scroll event that follows brings the state up to date.\n  const resumed = useRef(resumeKey);\n  useEffect(() => {\n    if (Object.is(resumed.current, resumeKey)) return;\n    resumed.current = resumeKey;\n    const viewport = viewportRef.current;\n    if (!viewport) return;\n    following.current = true;\n    viewport.scrollTop = viewport.scrollHeight;\n  }, [resumeKey]);\n\n  const release = useCallback((): void => {\n    following.current = false;\n  }, []);\n\n  const onScroll = useCallback((): void => {\n    const viewport = viewportRef.current;\n    if (!viewport) return;\n    const top = viewport.scrollTop;\n    const bottom = viewport.scrollHeight - top - viewport.clientHeight <= NEAR_BOTTOM;\n    if (bottom) {\n      following.current = true;\n      setUnseen(false);\n    } else if (top < lastTop.current - 1) {\n      // Growing content and a jump on its way only ever move the view down: a move up is the person's.\n      following.current = false;\n    }\n    lastTop.current = top;\n    setAtBottom(bottom);\n  }, []);\n\n  const onGrow = useCallback((): void => {\n    const viewport = viewportRef.current;\n    if (!viewport) return;\n    if (following.current) {\n      // Also ends a smooth jump that was aimed at where the end used to be.\n      viewport.scrollTop = viewport.scrollHeight;\n    } else if (viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight > NEAR_BOTTOM) {\n      setUnseen(true);\n      setAtBottom(false);\n    }\n  }, []);\n\n  const value = useMemo<ThreadContextValue>(\n    () => ({ viewportRef, atBottom, unseen, scrollToBottom, label: { \"aria-label\": ariaLabel, \"aria-labelledby\": ariaLabelledBy }, release, onScroll, onGrow }),\n    [atBottom, unseen, scrollToBottom, ariaLabel, ariaLabelledBy, release, onScroll, onGrow],\n  );\n\n  return (\n    <ThreadContext value={value}>\n      <div\n        data-slot=\"thread\"\n        data-at-bottom={atBottom ? \"\" : undefined}\n        data-unseen={unseen ? \"\" : undefined}\n        className={cn(\"relative flex min-h-0 min-w-0 flex-col\", className)}\n        {...props}\n      >\n        {children}\n      </div>\n    </ThreadContext>\n  );\n}\n\nexport type ThreadContentProps = ComponentProps<\"div\">;\n\n/**\n * The log itself and its scroll container. `role=\"log\"` with `aria-live=\"off\"`: a screen reader can browse\n * it, but words that stream in are not read out as they land. It takes keyboard focus (a scrollable region\n * must), so arrow keys and Page Up scroll it; scrolling up by wheel, touch or keyboard stops it following.\n */\nexport function ThreadContent({ className, children, onWheel, onTouchMove, onKeyDown, onScroll, ...props }: ThreadContentProps) {\n  const context = useThreadContext(\"ThreadContent\");\n  const { viewportRef, onGrow, onScroll: track, release } = context;\n  const innerRef = useRef<HTMLDivElement>(null);\n\n  // Start at the newest content, before the first paint.\n  useLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    if (viewport) viewport.scrollTop = viewport.scrollHeight;\n  }, [viewportRef]);\n\n  // Content that grows (a new message, a streamed word, an image that loads) or a frame that resizes.\n  useEffect(() => {\n    const viewport = viewportRef.current;\n    const inner = innerRef.current;\n    if (!viewport || !inner || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(() => onGrow());\n    observer.observe(inner);\n    observer.observe(viewport);\n    return () => observer.disconnect();\n  }, [viewportRef, onGrow]);\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    onKeyDown?.(event);\n    if (event.target === event.currentTarget && (UP_KEYS.has(event.key) || (event.key === \" \" && event.shiftKey))) release();\n  };\n\n  return (\n    <div\n      ref={viewportRef}\n      data-slot=\"thread-content\"\n      role=\"log\"\n      aria-live=\"off\"\n      tabIndex={0}\n      {...context.label}\n      onScroll={(event) => {\n        onScroll?.(event);\n        track();\n      }}\n      onWheel={(event) => {\n        onWheel?.(event);\n        if (event.deltaY < 0) release();\n      }}\n      onTouchMove={(event) => {\n        onTouchMove?.(event);\n        release();\n      }}\n      onKeyDown={handleKeyDown}\n      className={cn(\"min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain rounded-surface [overflow-anchor:none]\", className)}\n      {...props}\n    >\n      <div ref={innerRef} data-slot=\"thread-inner\" className=\"flex min-h-full flex-col gap-6 p-4\">\n        {children}\n      </div>\n    </div>\n  );\n}\n\nexport type ThreadTurnProps = Omit<ComponentProps<\"div\">, \"role\"> & {\n  /** Who is speaking, in the project's words (\"You\", \"Assistant\", a person's name). Read by screen readers, not shown. */\n  label: ReactNode;\n  /** The level of the hidden heading, so the turn fits the page's outline. Default 3. */\n  headingLevel?: 2 | 3 | 4 | 5 | 6;\n};\n\n/**\n * One speaker's turn: a group named by a visually hidden heading, so a screen-reader user can move from\n * turn to turn by heading and always knows who is speaking.\n */\nexport function ThreadTurn({ className, label, headingLevel = 3, children, ...props }: ThreadTurnProps) {\n  const id = useId();\n  const Heading = `h${headingLevel}` as const;\n  return (\n    <div data-slot=\"thread-turn\" role=\"group\" aria-labelledby={id} className={cn(\"flex min-w-0 flex-col gap-3\", className)} {...props}>\n      <Heading id={id} className=\"sr-only\">\n        {label}\n      </Heading>\n      {children}\n    </div>\n  );\n}\n\nexport type ThreadJumpProps = Omit<ComponentProps<\"button\">, \"type\"> & {\n  /** \"unseen\" (default): shown when the person has scrolled up and something new arrived. \"away\": shown whenever they are not at the bottom. */\n  show?: \"unseen\" | \"away\";\n};\n\n/**\n * The way back down. It is in the page only while it is useful, sits outside the log, and on press goes to\n * the newest content (smoothly, or at once under reduced motion) and hands focus to the log, so focus is not\n * lost when the button goes away. Its children are its name: \"Jump to latest\", in the project's language.\n */\nexport function ThreadJump({ className, show = \"unseen\", children = \"Jump to latest\", onClick, ...props }: ThreadJumpProps) {\n  const { atBottom, unseen, scrollToBottom } = useThreadContext(\"ThreadJump\");\n  if (atBottom || (show === \"unseen\" && !unseen)) return null;\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"thread-jump\"\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) scrollToBottom({ focus: true });\n      }}\n      className={cn(\n        \"absolute inset-x-0 bottom-3 z-10 mx-auto inline-flex h-control-sm w-fit max-w-[calc(100%-2rem)] items-center gap-1.5 rounded-control border border-border-strong bg-background px-3 text-sm font-medium text-foreground transition-[background-color,opacity] duration-instant ease-out animation-duration-(--duration-base) animate-in fade-in-0 hover:bg-accent motion-reduce:animate-none motion-reduce:transition-none pointer-coarse:h-control [&_svg]:size-4 [&_svg]:shrink-0\",\n        className,\n      )}\n      {...props}\n    >\n      <ArrowDown aria-hidden=\"true\" strokeWidth={1.5} />\n      <span className=\"truncate\">{children}</span>\n    </button>\n  );\n}\n\n/** What the thread shows before the first message: centred in the space, with room for suggestions. */\nexport function ThreadEmpty({ className, ...props }: ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"thread-empty\"\n      className={cn(\"flex flex-1 flex-col items-center justify-center gap-3 px-4 py-10 text-center text-base text-muted-foreground\", className)}\n      {...props}\n    />\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "A conversation with an assistant or between people, where messages arrive over time. It holds no messages and no transport: render them inside it (message, streaming-text, part-frame). The log is deliberately silent (`aria-live=\"off\"`): say what is happening through one status-line beside it, and the finished reply once through streaming-text's `announceWhenDone`. For a list that does not grow at the bottom use scroll-area.",
    "example": "<Thread aria-label=\"Conversation with the assistant\" className=\"h-[32rem]\">\n  <ThreadContent>\n    {messages.length === 0 ? <ThreadEmpty>Ask anything to begin.</ThreadEmpty> : null}\n    {messages.map((message) => (\n      <ThreadTurn key={message.id} label={message.from === \"user\" ? \"You\" : \"Assistant\"}>\n        <Message from={message.from}>\n          <MessageBody><MessageContent>{message.text}</MessageContent></MessageBody>\n        </Message>\n      </ThreadTurn>\n    ))}\n  </ThreadContent>\n  <ThreadJump>Jump to latest</ThreadJump>\n</Thread>\n\n// Always show what the person just sent, even if they had scrolled up\n<Thread aria-label=\"Conversation\" resumeKey={lastOwnMessageId}>…</Thread>",
    "client": true
  }
}
