About
A jump to latest pill for a chat thread that counts the messages landing below and scrolls back down when pressed.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Scroll To Bottom to your project and fits it to your theme.
Code
How Scroll To Bottom is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { ChatcnScrollBehavior, ConversationContext, ConversationContextValue, ScrollToBottom, useConversation } from "@/components/ui/scroll-to-bottom"
interface GhostState {
x: number
y: number
shown: boolean
down: boolean
}
/**
* A pointer that walks a demo through its clicks, so a preview shows what each control does.
* `stage` is the positioned box the pointer moves in; targets are found inside it. Sizes come
* from layout boxes, so a scaled FitFrame never throws the aim off.
*/
function useGhost(stage: React.RefObject<HTMLElement | null>) {
const [ghost, setGhost] = React.useState<GhostState>({ x: 0, y: 0, shown: false, down: false })
const find = React.useCallback(
(target: string | HTMLElement) =>
typeof target === "string"
? stage.current?.querySelector<HTMLElement>(target) ?? null
: target,
[stage],
)
const moveTo = React.useCallback(
(target: string | HTMLElement, dx = 0.5, dy = 0.6) => {
const root = stage.current
const el = find(target)
if (!root || !el) return null
const rr = root.getBoundingClientRect()
const scale = root.offsetWidth ? rr.width / root.offsetWidth : 1
const er = el.getBoundingClientRect()
const x = (er.left - rr.left + er.width * dx) / scale
const y = (er.top - rr.top + er.height * dy) / scale
// A hidden pointer fades in a short way off its first target instead of flying in from
// wherever it was last.
setGhost((g) => (g.shown ? { x, y, shown: true, down: false } : { x: x + 70, y: y + 46, shown: false, down: false }))
window.requestAnimationFrame(() =>
window.requestAnimationFrame(() => setGhost({ x, y, shown: true, down: false })),
)
return el
},
[stage, find],
)
const press = React.useCallback((down: boolean) => setGhost((g) => ({ ...g, down })), [])
const hide = React.useCallback(() => setGhost((g) => ({ ...g, shown: false, down: false })), [])
return { ghost, moveTo, press, hide, find }
}
const reducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches
const STOP = Symbol("stop")
/**
* Runs `script` in a loop with a `wait(ms)` that stops cleanly on unmount or once `active` turns
* false. Reduced motion never starts it.
*/
function useLoop(
script: (wait: (ms: number) => Promise<void>) => Promise<void>,
active = true,
) {
const ref = React.useRef(script)
ref.current = script
React.useEffect(() => {
if (!active || reducedMotion()) return
let alive = true
const timers = new Set<number>()
const wait = (ms: number) =>
new Promise<void>((resolve, reject) => {
const id = window.setTimeout(() => {
timers.delete(id)
if (alive) resolve()
else reject(STOP)
}, ms)
timers.add(id)
})
;(async () => {
try {
while (alive) await ref.current(wait)
} catch (error) {
if (error !== STOP) throw error
}
})()
return () => {
alive = false
for (const id of timers) window.clearTimeout(id)
}
}, [active])
}
/** Updates that land below the reader while they read. */
const UPDATES = [
"Archived all 1.2 million rows and dropped legacy_logs.",
"Both migrations finished in 4 min 12 s.",
"All 24 smoke tests pass on the migrated copy. Safe to run in production.",
]
/** Moves to a target, presses and clicks it. Returns the element, or null if it is gone. */
async function tap(
g: ReturnType<typeof useGhost>,
target: string | HTMLElement,
wait: (ms: number) => Promise<void>,
travel = 700,
) {
if (!g.moveTo(target)) return null
await wait(travel)
g.press(true)
await wait(130)
const el = g.find(target)
el?.click()
g.press(false)
return el
}
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
el.style.transform = scale < 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
/**
* Stick-to-bottom scrolling for chat transcripts.
*
* - Follows growing content only while the reader is within `threshold` px of the bottom.
* - Any upward wheel, touch, key or scrollbar drag releases it in the same event. It never fights.
* - Scrolling back down into the threshold, or calling `scrollToBottom`, re-engages it.
* - A new user turn scrolls near the top of the viewport, with a spacer below it so the reply
* streams into empty space instead of pushing the turn away (`anchor`).
* - Content inserted above the viewport keeps the reading position (native `overflow-anchor`,
* with a manual fallback for engines without it).
* - A ResizeObserver follows content that grows after render: images, code blocks, tool output.
* - Follows with a critically damped chase, not a fixed-duration tween, because streamed content
* grows at unpredictable rates. Instant under reduced motion.
*/
/** Options for `useChatcnStickToBottom`. */
interface UseChatcnStickToBottomOptions {
/** Distance from the bottom, in px, that still counts as at the bottom. Defaults to 64. */
threshold?: number
/**
* Scroll each new user turn near the top of the viewport. `true` matches
* `[data-slot="message"][data-role="user"]`; pass a selector to match something else, or
* `false` to always stick to the bottom instead. Defaults to true.
*/
anchor?: boolean | string
/** Space kept above an anchored turn, in px. Defaults to 24. */
anchorOffset?: number
/** Start at the bottom on mount. Defaults to true. */
initial?: boolean
}
/* -------------------------------------------------------------------------------------------------
* Conversation
* -----------------------------------------------------------------------------------------------*/
interface ConversationProps extends React.ComponentProps<"div">, UseChatcnStickToBottomOptions {}
/** Return value of `useChatcnStickToBottom`. */
interface ChatcnStickToBottom {
/** Attach to the scrolling element. */
scrollRef: (element: HTMLElement | null) => void
/** Attach to the element that wraps the messages (its size is observed). */
contentRef: (element: HTMLElement | null) => void
/** Attach to an empty element placed after the content, inside the scroller. */
spacerRef: (element: HTMLElement | null) => void
/** Within `threshold` px of the bottom. */
isAtBottom: boolean
/** Following new content. False from the first upward scroll until the reader returns. */
isSticky: boolean
/** More than one viewport away from the bottom. */
isFar: boolean
/** Messages that arrived below while the reader was scrolled up. Resets at the bottom. */
unread: number
/** Scroll to the bottom and stick again. */
scrollToBottom: (options?: { behavior?: ChatcnScrollBehavior }) => void
/** Scroll an element near the top of the viewport, keeping room below it for a reply. */
scrollToTurn: (element: HTMLElement, options?: { behavior?: ChatcnScrollBehavior }) => void
}
const prefersReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches
/** True when a nested element between `target` and `root` can still scroll in `dy`'s direction. */
function nestedCanScroll(target: EventTarget | null, root: HTMLElement, dy: number) {
let node = target instanceof Element ? target : null
while (node && node !== root) {
if (node instanceof HTMLElement && node.scrollHeight > node.clientHeight) {
const overflow = getComputedStyle(node).overflowY
if (overflow === "auto" || overflow === "scroll") {
if (dy < 0 && node.scrollTop > 0) return true
if (dy > 0 && node.scrollTop + node.clientHeight < node.scrollHeight - 1) return true
}
}
node = node.parentElement
}
return false
}
function isEditable(target: EventTarget | null) {
return (
target instanceof HTMLElement &&
(target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))
)
}
const UP_KEYS = new Set(["ArrowUp", "PageUp", "Home"])
const USER_TURN = '[data-slot="message"][data-role="user"]'
const MESSAGE = '[data-slot="message"]'
/** Stick-to-bottom scroll state and refs for a chat transcript. */
function useChatcnStickToBottom({
threshold = 64,
anchor = true,
anchorOffset = 24,
initial = true,
}: UseChatcnStickToBottomOptions = {}): ChatcnStickToBottom {
const [scroller, setScroller] = React.useState<HTMLElement | null>(null)
const [content, setContent] = React.useState<HTMLElement | null>(null)
const spacer = React.useRef<HTMLElement | null>(null)
const [isAtBottom, setAtBottom] = React.useState(true)
const [isSticky, setSticky] = React.useState(true)
const [isFar, setFar] = React.useState(false)
const [unread, setUnread] = React.useState(0)
// Mutable engine state. Lives in a ref so scroll handlers never re-render to read it.
const s = React.useRef({
sticky: true,
/** Last scrollTop we wrote. Scroll events that land on it are ours, not the reader's. */
written: -1,
lastTop: 0,
lastHeight: 0,
raf: 0,
target: null as null | (() => number),
anchorEl: null as HTMLElement | null,
mounted: false,
unread: 0,
touchY: 0,
/** Manual scroll anchoring for engines without `overflow-anchor`. */
keep: null as null | { node: Element; top: number },
}).current
const options = React.useRef({ threshold, anchor, anchorOffset })
options.current = { threshold, anchor, anchorOffset }
// Imperative helpers are created once per scroller and kept in a ref so the public functions
// stay referentially stable.
const api = React.useRef<{
toBottom: (behavior?: ChatcnScrollBehavior) => void
toTurn: (el: HTMLElement, behavior?: ChatcnScrollBehavior) => void
} | null>(null)
React.useEffect(() => {
const el = scroller
if (!el) return
const nativeAnchoring =
typeof CSS !== "undefined" && CSS.supports?.("overflow-anchor", "auto") === true
const maxTop = () => Math.max(0, el.scrollHeight - el.clientHeight)
const distance = () => maxTop() - el.scrollTop
const write = (top: number) => {
el.scrollTop = top
s.written = el.scrollTop
s.lastTop = el.scrollTop
}
const sync = () => {
const d = distance()
const atBottom = d <= options.current.threshold
if (atBottom && s.unread) {
s.unread = 0
setUnread(0)
}
setAtBottom(atBottom)
setFar(d > el.clientHeight)
setSticky(s.sticky)
}
const stop = () => {
if (s.raf) cancelAnimationFrame(s.raf)
s.raf = 0
s.target = null
}
const release = () => {
stop()
if (!s.sticky) return
s.sticky = false
setSticky(false)
}
/** Chase a moving target with exponential smoothing: fast, settles without overshoot. */
const chase = (target: () => number, behavior: ChatcnScrollBehavior) => {
s.target = target
if (behavior === "instant" || prefersReducedMotion()) {
stop()
write(Math.min(target(), maxTop()))
sync()
return
}
if (s.raf) return
let last = performance.now()
const step = (now: number) => {
const goal = s.target
if (!goal) return
const dt = Math.min(64, now - last)
last = now
const to = Math.min(goal(), maxTop())
const from = el.scrollTop
const gap = to - from
if (Math.abs(gap) < 1) {
write(to)
s.raf = 0
s.target = null
sync()
return
}
// Time constant of 70 ms: about 200 ms to cover most of any distance. scrollTop snaps to
// whole pixels, so every frame moves at least one pixel or the chase would stall.
const move = gap * (1 - Math.exp(-dt / 70))
write(from + (Math.abs(move) < 1 ? Math.sign(gap) : move))
s.raf = requestAnimationFrame(step)
}
s.raf = requestAnimationFrame(step)
}
const turnTop = (turn: HTMLElement) =>
turn.getBoundingClientRect().top -
el.getBoundingClientRect().top +
el.scrollTop -
options.current.anchorOffset
/** Size the spacer so the anchored turn can reach the top while its reply is short. */
const fitSpacer = () => {
const pad = spacer.current
if (!pad) return
const turn = s.anchorEl
if (!turn?.isConnected || !content) {
s.anchorEl = null
if (pad.style.height !== "0px") pad.style.height = "0px"
return
}
const box = el.getBoundingClientRect()
const contentBottom = content.getBoundingClientRect().bottom - box.top + el.scrollTop
const need = Math.max(0, Math.ceil(turnTop(turn) + el.clientHeight - contentBottom))
pad.style.height = `${need}px`
// Once the reply fills the viewport the spacer is no longer needed.
if (need === 0) s.anchorEl = null
}
const remember = () => {
if (nativeAnchoring || !content) return
const top = el.getBoundingClientRect().top
for (const child of Array.from(content.children)) {
const r = child.getBoundingClientRect()
if (r.bottom > top) {
s.keep = { node: child, top: r.top - top }
return
}
}
s.keep = null
}
const toBottom = (behavior: ChatcnScrollBehavior = "smooth") => {
s.sticky = true
setSticky(true)
chase(maxTop, behavior)
}
const toTurn = (turn: HTMLElement, behavior: ChatcnScrollBehavior = "smooth") => {
s.anchorEl = turn
fitSpacer()
s.sticky = true
setSticky(true)
chase(() => turnTop(turn), behavior)
}
api.current = { toBottom, toTurn }
const onScroll = () => {
const top = el.scrollTop
const height = el.scrollHeight
const ours = Math.abs(top - s.written) < 1.5
if (!ours) {
const movedUp = top < s.lastTop - 0.5
// Content that shrinks clamps scrollTop upward; that is not the reader scrolling.
const clamped = distance() < 1 && height < s.lastHeight
if (movedUp && !clamped) release()
else if (!movedUp && distance() <= options.current.threshold && !s.sticky) {
s.sticky = true
}
s.written = -1
}
s.lastTop = top
s.lastHeight = height
remember()
sync()
}
const onWheel = (event: WheelEvent) => {
if (event.deltaY < 0 && el.scrollTop > 0 && !nestedCanScroll(event.target, el, -1)) release()
}
const onTouchStart = (event: TouchEvent) => {
s.touchY = event.touches[0]?.clientY ?? 0
}
const onTouchMove = (event: TouchEvent) => {
const y = event.touches[0]?.clientY ?? 0
// Finger moving down scrolls the content up.
if (y - s.touchY > 4 && !nestedCanScroll(event.target, el, -1)) release()
s.touchY = y
}
const onKeyDown = (event: KeyboardEvent) => {
if (isEditable(event.target)) return
if (UP_KEYS.has(event.key) || (event.key === " " && event.shiftKey)) release()
}
const onResize = () => {
fitSpacer()
if (!nativeAnchoring && !s.sticky && s.keep?.node.isConnected) {
const now = s.keep.node.getBoundingClientRect().top - el.getBoundingClientRect().top
const delta = now - s.keep.top
if (Math.abs(delta) > 0.5) write(el.scrollTop + delta)
}
// Streamed growth is a few lines at a time and glides. A jump of more than a viewport is
// a history load or a layout change, so it lands instantly instead of scrolling past.
if (s.sticky && !s.target) {
chase(maxTop, s.mounted && distance() <= el.clientHeight ? "smooth" : "instant")
}
// Record growth only. On a shrink the browser clamps scrollTop and fires a scroll event;
// onScroll needs the old, larger height to recognise that clamp and keep following.
if (el.scrollHeight > s.lastHeight) s.lastHeight = el.scrollHeight
remember()
sync()
}
const ro = new ResizeObserver(onResize)
ro.observe(el)
if (content) ro.observe(content)
const mo = new MutationObserver((records) => {
if (!content) return
const selector =
options.current.anchor === false
? null
: typeof options.current.anchor === "string"
? options.current.anchor
: USER_TURN
let turn: HTMLElement | null = null
let added = 0
for (const record of records) {
for (const node of Array.from(record.addedNodes)) {
if (!(node instanceof HTMLElement)) continue
const isMessage = node.matches(MESSAGE) || node.querySelector(MESSAGE)
if (isMessage) added++
if (!selector) continue
const match = node.matches(selector)
? node
: (node.querySelector<HTMLElement>(selector) ?? null)
if (match) turn = match
}
}
if (!s.mounted) return
// Only a freshly sent turn anchors. A batch of many messages is history being restored,
// and an older turn is history being prepended: neither moves the reader.
if (turn && selector && added <= 2) {
const all = content.querySelectorAll<HTMLElement>(selector)
if (all[all.length - 1] === turn) {
toTurn(turn)
return
}
}
if (added && !s.sticky) {
s.unread += added
setUnread(s.unread)
}
})
if (content) mo.observe(content, { childList: true, subtree: true })
el.addEventListener("scroll", onScroll, { passive: true })
el.addEventListener("wheel", onWheel, { passive: true })
el.addEventListener("touchstart", onTouchStart, { passive: true })
el.addEventListener("touchmove", onTouchMove, { passive: true })
el.addEventListener("keydown", onKeyDown)
if (!s.mounted) {
if (initial) write(maxTop())
// Starting elsewhere means following only once the reader reaches the bottom.
else s.sticky = distance() <= options.current.threshold
}
s.lastHeight = el.scrollHeight
remember()
sync()
// Messages present at mount never anchor and never count as unread.
const ready = requestAnimationFrame(() => {
s.mounted = true
})
return () => {
cancelAnimationFrame(ready)
stop()
ro.disconnect()
mo.disconnect()
el.removeEventListener("scroll", onScroll)
el.removeEventListener("wheel", onWheel)
el.removeEventListener("touchstart", onTouchStart)
el.removeEventListener("touchmove", onTouchMove)
el.removeEventListener("keydown", onKeyDown)
}
}, [scroller, content, initial, s])
const scrollToBottom = React.useCallback(
(opts?: { behavior?: ChatcnScrollBehavior }) => api.current?.toBottom(opts?.behavior),
[],
)
const scrollToTurn = React.useCallback(
(element: HTMLElement, opts?: { behavior?: ChatcnScrollBehavior }) =>
api.current?.toTurn(element, opts?.behavior),
[],
)
const spacerRef = React.useCallback((element: HTMLElement | null) => {
spacer.current = element
}, [])
return {
scrollRef: setScroller,
contentRef: setContent,
spacerRef,
isAtBottom,
isSticky,
isFar,
unread,
scrollToBottom,
scrollToTurn,
}
}
/**
* The thread. Owns stick-to-bottom scrolling, the reply anchor and the live region.
* Give it a height (or put it in a flex column) and place `ConversationContent` and
* `ScrollToBottom` inside.
*/
function Conversation({
threshold,
anchor,
anchorOffset,
initial,
className,
children,
...props
}: ConversationProps) {
const stick = useChatcnStickToBottom({ threshold, anchor, anchorOffset, initial })
const [message, setMessage] = React.useState("")
const [ready, setReady] = React.useState(false)
React.useEffect(() => setReady(true), [])
const announce = React.useCallback((text: string) => {
// Clearing first makes repeated identical text announce again.
setMessage("")
requestAnimationFrame(() => setMessage(text))
}, [])
const value = React.useMemo<ConversationContextValue>(
() => ({ ...stick, announce, ready }),
[stick, announce, ready],
)
return (
<ConversationContext.Provider value={value}>
<div
data-slot="conversation"
data-at-bottom={stick.isAtBottom ? "" : undefined}
className={cn("relative flex min-h-0 flex-col overflow-hidden", className)}
{...props}
>
{children}
<div aria-live="polite" aria-atomic="true" className="sr-only">
{message}
</div>
</div>
</ConversationContext.Provider>
)
}
/* -------------------------------------------------------------------------------------------------
* ConversationContent
* -----------------------------------------------------------------------------------------------*/
interface ConversationContentProps extends React.ComponentProps<"div"> {
/** Class names for the scrolling viewport. `className` styles the message column. */
viewportClassName?: string
/** Accessible name of the transcript. */
label?: string
}
/**
* The scrolling transcript. The viewport is a focusable `log` so keyboard users can scroll it;
* the column inside is capped at 720 px with a 24 px gap between messages.
*/
function ConversationContent({
viewportClassName,
label = "Conversation",
className,
children,
...props
}: ConversationContentProps) {
const ctx = useConversation()
if (!ctx) throw new Error("ConversationContent must be used inside Conversation.")
return (
<div
ref={ctx.scrollRef}
role="log"
aria-label={label}
// The log is silent: tokens are never read one by one. Finished replies are announced
// through the conversation's live region instead.
aria-live="off"
// biome-ignore lint/a11y/noNoninteractiveTabindex: scrollable regions must be focusable
tabIndex={0}
data-slot="conversation-viewport"
className={cn(
"chatcn-scroll chatcn-scroll-fade min-h-0 flex-1 overflow-y-auto outline-none [overflow-anchor:auto]",
"focus-visible:outline-(color:--chatcn-accent) focus-visible:outline-2 focus-visible:-outline-offset-2",
viewportClassName,
)}
>
<div
ref={ctx.contentRef}
data-slot="conversation-content"
className={cn(
"mx-auto flex w-full max-w-[720px] flex-col gap-6 px-4 pt-8 pb-6 sm:px-6",
className,
)}
{...props}
>
{children}
</div>
<div
ref={ctx.spacerRef}
aria-hidden="true"
data-slot="conversation-spacer"
className="pointer-events-none shrink-0 [overflow-anchor:none]"
/>
</div>
)
}
/* -------------------------------------------------------------------------------------------------
* Types and context
* -----------------------------------------------------------------------------------------------*/
type MessageRole = "user" | "assistant" | "system"
type MessageLayout = "auto" | "bubble" | "flat" | "compact"
type MessageState = "streaming" | "done" | "edited" | "error" | "stopped" | "queued"
/* -------------------------------------------------------------------------------------------------
* Message
* -----------------------------------------------------------------------------------------------*/
interface MessageProps extends React.ComponentProps<"div"> {
/** Who wrote it. Named `from` so the ARIA `role` attribute stays free. */
from: MessageRole
/**
* `auto` gives users a subtle bubble and assistants a flat, document-style block. `compact`
* is the dense log style for agent traces and side panels. Defaults to `auto`.
*/
layout?: MessageLayout
/** Lifecycle state. Defaults to `done`. */
state?: MessageState
/** Follows a message from the same author: tightens the gap and hides the avatar. */
grouped?: boolean
/** The newest message. Keeps its actions visible instead of revealing them on hover. */
latest?: boolean
/**
* Enter animation. Defaults to animating only messages that arrive after the conversation
* mounted, so restored history appears at once.
*/
animate?: boolean
/** Announce the text to screen readers when streaming finishes. Defaults to true. */
announce?: boolean
}
interface MessageContextValue {
from: MessageRole
/** Resolved layout: `auto` becomes `bubble` for users and `flat` for everyone else. */
layout: Exclude<MessageLayout, "auto">
state: MessageState
/** The newest message: its actions stay visible. */
latest: boolean
}
const MessageContext = React.createContext<MessageContextValue | null>(null)
/**
* One turn in the conversation. Compose `MessageAvatar`, `MessageContent`, `MessageMeta`,
* `MessageStatus` and `MessageActions` inside it.
*/
function Message({
from,
layout: layoutProp = "auto",
state = "done",
grouped = false,
latest = false,
animate,
announce = true,
className,
children,
...props
}: MessageProps) {
const conversation = useConversation()
const layout: MessageContextValue["layout"] =
layoutProp === "auto" ? (from === "user" ? "bubble" : "flat") : layoutProp
const [enter] = React.useState(() => animate ?? conversation?.ready ?? false)
const ref = React.useRef<HTMLDivElement>(null)
// Screen readers hear the finished reply once, never token by token.
const previous = React.useRef(state)
React.useEffect(() => {
const was = previous.current
previous.current = state
if (!announce || was !== "streaming" || state === "streaming") return
const text = ref.current?.querySelector('[data-slot="message-content"]')?.textContent?.trim()
if (text) conversation?.announce(text)
}, [state, announce, conversation])
const value = React.useMemo(
() => ({ from, layout, state, latest }),
[from, layout, state, latest],
)
return (
<MessageContext.Provider value={value}>
<div
ref={ref}
data-slot="message"
data-role={from}
data-layout={layout}
data-message-state={state}
data-grouped={grouped ? "" : undefined}
data-latest={latest ? "" : undefined}
aria-busy={state === "streaming" || undefined}
className={cn(
"group/message relative flex min-w-0 flex-col",
layout === "compact" ? "gap-1" : "gap-2",
layout === "bubble" ? "items-end" : "items-start",
from === "system" && layout !== "compact" && "items-center text-center",
grouped && (layout === "compact" ? "-mt-2" : "-mt-4"),
// An avatar sits in the start gutter (the end gutter for bubbles).
layout === "bubble"
? "has-[>[data-slot=message-avatar]]:pe-9"
: "has-[>[data-slot=message-avatar]]:ps-9",
enter &&
(from === "user"
? "ease-(--chatcn-ease-out-soft) transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0 motion-reduce:starting:translate-y-0"
: "ease-(--chatcn-ease-out-soft) transition-opacity duration-150 starting:opacity-0"),
className,
)}
{...props}
>
{children}
</div>
</MessageContext.Provider>
)
}
/** Role, layout and state of the nearest `Message`. Returns null outside one. */
function useMessage() {
return React.useContext(MessageContext)
}
/* -------------------------------------------------------------------------------------------------
* MessageContent
* -----------------------------------------------------------------------------------------------*/
/**
* The text of a message, capped at a 68ch measure. Plain text keeps its line breaks. Markdown
* renderers drop in as children and inherit the 15/24 prose size.
*/
function MessageContent({ className, children, ...props }: React.ComponentProps<"div">) {
const ctx = useMessage()
const layout = ctx?.layout ?? "flat"
const from = ctx?.from ?? "assistant"
const state = ctx?.state ?? "done"
const plain = typeof children === "string"
return (
<div
data-slot="message-content"
className={cn(
"text-(color:--chatcn-fg) min-w-0 [overflow-wrap:anywhere]",
// Bubbles fill their lines: pretty wrapping would leave a wide, half-empty bubble.
layout !== "bubble" && "text-pretty",
plain && "whitespace-pre-wrap",
layout === "bubble" &&
"text-[0.9375rem]/[1.5rem] tracking-[-0.006em] rounded-(--chatcn-radius-xl) bg-(color:--chatcn-fill) max-w-[80%] px-4 py-2.5 text-start",
layout === "flat" && "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] w-full max-w-[68ch]",
layout === "compact" &&
(from === "user"
? "text-[0.875rem]/[1.25rem] tracking-[-0.003em] rounded-(--chatcn-radius-md) bg-(color:--chatcn-fill) max-w-full px-3 py-1.5"
: "text-[0.875rem]/[1.25rem] tracking-[-0.003em] w-full max-w-[68ch]"),
from === "system" && "text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) max-w-[60ch]",
// Queued turns are not sent yet: an outline instead of a fill says "pending".
state === "queued" &&
from === "user" &&
"text-(color:--chatcn-fg-muted) border-(color:--chatcn-border-strong) border border-dashed bg-transparent",
state === "error" && from === "user" && "text-(color:--chatcn-fg-muted)",
className,
)}
{...props}
>
{children}
</div>
)
}
/** The run so far. The reader is scrolled up to the top of it, reading the plan. */
const LOG = [
"Plan: restore a copy of production, run both migrations on it, then run the smoke tests.",
"Snapshot restored: 41 tables, 2.3 GB.",
"Applying 0042_runs_created_at_index, built concurrently so writes keep flowing.",
"Index built in 38 s. The runs page query now uses runs_created_at_idx.",
"Applying 0043_archive_legacy_logs: 1.2 million rows move to the archive table first.",
"Archived 600,000 of 1.2 million rows.",
]
/** The pointer itself. Put it last inside the stage, which must be `relative`. */
function Ghost({ ghost }: { ghost: GhostState }) {
return (
<div
aria-hidden
className="pointer-events-none absolute top-0 left-0 z-20"
style={{
transform: `translate(${ghost.x}px, ${ghost.y}px)`,
opacity: ghost.shown ? 1 : 0,
// Hidden, it jumps; shown, it glides.
transition: ghost.shown
? "transform 620ms cubic-bezier(0.4, 0, 0.2, 1), opacity 220ms ease-out"
: "opacity 220ms ease-out",
}}
>
<svg
width="18"
height="20"
viewBox="0 0 18 20"
className="drop-shadow-[0_1px_2px_rgb(0_0_0/0.25)]"
style={{
transform: ghost.down ? "scale(0.86)" : "scale(1)",
transformOrigin: "2px 2px",
transition: "transform 120ms ease-out",
}}
>
<path
d="M2 1.5 L2 16 L5.9 12.4 L8.6 18.3 L11.2 17.1 L8.6 11.3 L13.9 11.1 Z"
className="fill-[oklch(0.2_0_0)] stroke-white dark:fill-white dark:stroke-[oklch(0.2_0_0)]"
strokeWidth="1.3"
strokeLinejoin="round"
/>
</svg>
</div>
)
}
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/**
* An agent's migration run. The reader has scrolled up to the plan, updates keep landing below,
* and the pill opens into "1 new", "2 new", "3 new". The pointer takes it back down to the latest.
* Loops. Scroll the thread yourself to stop the tour.
*/
export default function ScrollToBottomPreview() {
const stage = React.useRef<HTMLDivElement>(null)
const g = useGhost(stage)
const [run, setRun] = React.useState(0)
const [count, setCount] = React.useState(0)
const [touring, setTouring] = React.useState(true)
useLoop(async (wait) => {
setRun((n) => n + 1)
setCount(0)
await wait(800)
for (let n = 1; n <= UPDATES.length; n += 1) {
setCount(n)
await wait(900)
}
await wait(900)
await tap(g, '[data-slot="scroll-to-bottom"]', wait)
await wait(500)
g.hide()
await wait(3600)
}, touring)
const stop = () => {
if (!touring) return
setTouring(false)
g.hide()
}
return (
<FitFrame minWidth="36rem">
<div className="flex w-full flex-col items-center justify-center gap-4 p-6">
<div
ref={stage}
className="border-(color:--chatcn-border) rounded-(--chatcn-radius-xl) bg-(color:--chatcn-bg) relative w-full max-w-xl overflow-hidden border"
onWheelCapture={stop}
onTouchStartCapture={stop}
>
<Conversation key={run} initial={false} className="h-[20rem] w-full">
<ConversationContent className="gap-4 px-5 pt-5 pb-14">
<Message from="user">
<MessageContent className="text-[0.9375rem]/[1.5rem] tracking-[-0.006em]">
Run the migrations on a copy first and tell me how it goes.
</MessageContent>
</Message>
{[...LOG, ...UPDATES.slice(0, count)].map((line) => (
<Message
key={line}
from="assistant"
className="transition-opacity duration-300 starting:opacity-0"
>
<MessageContent className="text-[0.9375rem]/[1.5rem] tracking-[-0.006em]">{line}</MessageContent>
</Message>
))}
</ConversationContent>
<ScrollToBottom />
</Conversation>
<Ghost ghost={g.ghost} />
</div>
<MoreOn slug="scroll-to-bottom">A jump to latest pill that counts what landed below. On</MoreOn>
</div>
</FitFrame>
)
}
















