Centered Chat Thread
One reading-width column with a scrolling message stream and a composer pinned under it. Use it for a focused one-to-one assistant conversation that needs no history or side panel.
How it differs. One column and nothing else: title bar, stream, composer. Following the reply pauses when the reader scrolls up and resumes through a jump button that floats over the stream.
Install
pnpm dlx shadcn@latest add @hazine/chat-thread-centeredAdds 2 files, 3 shadcn primitives (avatar, button, textarea), 3 Hazine items (@hazine/copy-button, @hazine/heading, @hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/blocks/chat-thread-centered.tsx, 432 lines
"use client"
import * as React from "react"
import {
ArrowDown,
ArrowUp,
CircleAlert,
LoaderCircle,
MessageSquareText,
PenLine,
RotateCw,
Square,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Heading, nextHeadingLevel, type HeadingLevel } from "@/components/hazine/heading"
import { useControllableState } from "@/hooks/use-controllable-state"
import { ChatThreadCenteredMessage, type ChatMessage } from "./chat-thread-centered.message"
export type { ChatMessage }
/** "loading" is the history fetch. The other four follow one request: submitted, streaming, then ready or error. */
export type ChatStatus = "ready" | "loading" | "submitted" | "streaming" | "error"
export interface ChatThreadCenteredProps extends Omit<React.ComponentProps<"section">, "title"> {
messages?: ChatMessage[]
defaultMessages?: ChatMessage[]
onMessagesChange?: (messages: ChatMessage[]) => void
/** Called with the user turn that was just appended. Start the request here. */
onMessageSend?: (message: ChatMessage) => void
status?: ChatStatus
/** Shown when status is "error". Say what happened and what to do next. */
error?: string
/** Called by the Stop button while a reply is pending or streaming. The button is disabled without it. */
onReplyStop?: () => void
/** Called by the retry button in the error state. The button is hidden without it. */
onReplyRetry?: () => void
title?: string
headingLevel?: HeadingLevel
assistantName?: string
/** Starter prompts for the empty state. Choosing one fills the message field and does not send. */
suggestions?: string[]
defaultDraft?: string
/** Longest message in characters. A counter appears from 80 percent of it. */
maxLength?: number
locale?: string
/** IANA time zone for message times. Fixed by default so server and client render the same text. */
timeZone?: string
}
// Distance from the end, in px, inside which the stream still counts as following.
const FOLLOW_THRESHOLD_PX = 48
const COUNTER_FROM = 0.8
const DEFAULT_MESSAGES: ChatMessage[] = [
{
id: "offsite-1",
role: "user",
content: "We have €1,840 for the design offsite in Porto: 8 people, two days. How would you split it?",
createdAt: "2026-11-10T09:41:00Z",
},
{
id: "offsite-2",
role: "assistant",
content:
"Here is a split that keeps a buffer and stays inside €1,840.\n\n- Venue, two days: €620\n- Lunches and one team dinner: €540\n- Airport transfers and local travel: €480\n- Buffer for changes: €200\n\nThat comes to €230 a person. The buffer is 10.9% of the total, close to what your last two offsites kept.",
createdAt: "2026-11-10T09:41:00Z",
},
{
id: "offsite-3",
role: "user",
content: "The venue came back at €700. Take the difference out of the buffer.",
createdAt: "2026-11-10T09:44:00Z",
},
{
id: "offsite-4",
role: "assistant",
content:
"Done. The venue moves to €700 and the buffer drops to €120, so the total stays at €1,840.\n\n- Venue, two days: €700\n- Lunches and one team dinner: €540\n- Airport transfers and local travel: €480\n- Buffer for changes: €120\n\nThe buffer is now 6.5% of the total. Your travel policy asks for at least 5%, so this still goes through without a second approval.",
createdAt: "2026-11-10T09:44:00Z",
},
]
const DEFAULT_SUGGESTIONS = [
"Split a trip budget across venue, food and travel",
"Check a supplier quote against our travel policy",
"Summarise what the design team spent last quarter",
]
const focusClass = "focus-visible:outline-2 focus-visible:outline-foreground"
const jumpButtonClass =
"pointer-events-auto inline-flex h-8 items-center gap-1.5 rounded-md border border-border bg-popover px-3 text-sm font-medium text-popover-foreground shadow-md transition-colors duration-100 hover:bg-accent hover:text-accent-foreground active:bg-muted focus-visible:outline-offset-2"
const suggestionClass =
"flex min-h-11 w-full items-center justify-between gap-3 px-4 py-2 text-start text-sm transition-colors duration-100 hover:bg-muted/50 active:bg-muted focus-visible:-outline-offset-2"
const skeletonClass = "rounded-md bg-muted motion-safe:animate-pulse"
export function ChatThreadCentered({
messages: messagesProp,
defaultMessages = DEFAULT_MESSAGES,
onMessagesChange,
onMessageSend,
status = "ready",
error = "The reply did not arrive. Check your connection, then retry.",
onReplyStop,
onReplyRetry,
title = "Porto offsite budget",
headingLevel = 2,
assistantName = "Marlow",
suggestions = DEFAULT_SUGGESTIONS,
defaultDraft = "",
maxLength = 2000,
locale = "en-US",
timeZone = "UTC",
className,
...props
}: ChatThreadCenteredProps) {
const baseId = React.useId()
const [messages, setMessages] = useControllableState({
value: messagesProp,
defaultValue: defaultMessages,
onChange: onMessagesChange,
})
const [draft, setDraft] = React.useState(defaultDraft)
const [following, setFollowing] = React.useState(true)
const [notice, setNotice] = React.useState("")
const scrollerRef = React.useRef<HTMLDivElement>(null)
const fieldRef = React.useRef<HTMLTextAreaElement>(null)
const actionRef = React.useRef<HTMLButtonElement>(null)
const sequence = React.useRef(0)
const timeFormat = React.useMemo(
() => new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit", timeZone }),
[locale, timeZone]
)
const numberFormat = React.useMemo(() => new Intl.NumberFormat(locale), [locale])
const loading = status === "loading"
const replying = status === "submitted" || status === "streaming"
const overBy = draft.length - maxLength
const lastMessage = messages.at(-1)
// The reply being written sits outside the log and joins it once complete,
// so a screen reader hears the finished turn once and not every chunk.
const writingMessage = status === "streaming" && lastMessage?.role === "assistant" ? lastMessage : undefined
const settledMessages = writingMessage ? messages.slice(0, -1) : messages
const latestReplyId = messages.findLast((message) => message.role === "assistant")?.id
const jumpShown = !following && !loading && messages.length > 0
// Runs before paint so a growing reply never shows a frame below the fold.
// It does nothing once the reader has scrolled up, which is what pauses auto-scroll.
React.useLayoutEffect(() => {
const scroller = scrollerRef.current
if (following && scroller) scroller.scrollTop = scroller.scrollHeight
}, [following, messages, status])
// A focused Stop becomes a disabled Send when the reply ends on an empty draft, so focus moves to the field.
React.useEffect(() => {
const action = actionRef.current
if (!replying && action?.disabled && document.activeElement === action) fieldRef.current?.focus()
}, [replying])
function handleScroll(event: React.UIEvent<HTMLDivElement>) {
// Scrolling the skeleton must not leave the loaded history paused at its start.
if (loading) return
const { scrollHeight, scrollTop, clientHeight } = event.currentTarget
setFollowing(scrollHeight - scrollTop - clientHeight <= FOLLOW_THRESHOLD_PX)
}
// The button unmounts once the stream follows again, so focus goes to the field.
function jumpToLatest() {
setFollowing(true)
fieldRef.current?.focus()
}
function send() {
const text = draft.trim()
if (text === "" || replying || loading) return
fieldRef.current?.focus()
if (overBy > 0) return
sequence.current += 1
const now = new Date()
const message: ChatMessage = {
// Time based, so an id never repeats one from an earlier mount that the consumer kept.
id: `message-${now.getTime().toString(36)}-${sequence.current}`,
role: "user",
content: text,
createdAt: now.toISOString(),
}
setMessages((previous) => [...previous, message])
onMessageSend?.(message)
setDraft("")
setNotice("")
setFollowing(true)
}
function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {
// Enter confirms an IME candidate first, so composition never sends. Safari reports that Enter as key code 229.
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing || event.keyCode === 229) return
event.preventDefault()
send()
}
function fillDraft(suggestion: string) {
setDraft(suggestion)
setNotice("Prompt added to the message field. Edit it, then send.")
fieldRef.current?.focus()
}
// The retry button unmounts when the request restarts, so focus goes to the field.
function retry() {
onReplyRetry?.()
fieldRef.current?.focus()
}
function renderMessage(message: ChatMessage) {
return (
<ChatThreadCenteredMessage
key={message.id}
message={message}
time={timeFormat.format(new Date(message.createdAt))}
assistantName={assistantName}
latest={message.id === latestReplyId}
writing={message === writingMessage}
/>
)
}
let liveText = notice
if (loading) liveText = "Loading conversation."
if (status === "submitted") liveText = `${assistantName} is thinking.`
if (status === "streaming") liveText = `${assistantName} is writing.`
return (
<section
data-slot="chat-thread-centered"
data-status={status}
aria-labelledby={`${baseId}-title`}
{...props}
className={cn("@container flex h-svh min-h-96 flex-col bg-background text-foreground", className)}
>
<header className="border-b border-border">
<div className="mx-auto flex w-full max-w-prose items-baseline justify-between gap-4 px-4 py-3 @3xl:px-6">
<Heading id={`${baseId}-title`} level={headingLevel} title={title} className="truncate text-sm font-semibold">
{title}
</Heading>
{!loading && (
<p className="shrink-0 text-xs text-muted-foreground tabular-nums">
{numberFormat.format(messages.length)} {messages.length === 1 ? "message" : "messages"}
</p>
)}
</div>
</header>
<div className="relative min-h-0 flex-1">
<div
ref={scrollerRef}
data-slot="chat-thread-centered-stream"
role="group"
aria-label="Messages"
aria-busy={loading || undefined}
// Focusable so the arrow and page keys scroll the stream without a pointer.
tabIndex={messages.length > 0 ? 0 : undefined}
onScroll={handleScroll}
// Positioned, so visually hidden text inside a message scrolls with it and cannot stretch the page.
className={cn("relative h-full scroll-pb-14 overflow-y-auto focus-visible:-outline-offset-2", focusClass)}
>
<div className="mx-auto flex min-h-full w-full max-w-prose flex-col gap-6 px-4 py-6 @3xl:px-6">
{loading && (
<div aria-hidden="true" className="flex flex-col gap-6">
<div className={cn(skeletonClass, "ms-auto h-10 w-3/5 rounded-xl")} />
<div className="flex flex-col gap-2">
<div className={cn(skeletonClass, "h-6 w-28")} />
<div className={cn(skeletonClass, "h-4 w-full")} />
<div className={cn(skeletonClass, "h-4 w-11/12")} />
<div className={cn(skeletonClass, "h-4 w-2/3")} />
</div>
<div className={cn(skeletonClass, "ms-auto h-10 w-2/5 rounded-xl")} />
</div>
)}
{!loading && messages.length === 0 && (
<div className="my-auto flex flex-col items-center gap-6 py-6 text-center">
<span className="flex size-9 items-center justify-center rounded-md border border-border bg-background">
<MessageSquareText aria-hidden="true" className="size-5" strokeWidth={1.5} />
</span>
<div>
<Heading level={nextHeadingLevel(headingLevel)} className="text-xl font-semibold tracking-tight">
Ask {assistantName} about team spend
</Heading>
<p className="mx-auto mt-1 max-w-[40ch] text-sm text-muted-foreground">
<span className="font-medium text-foreground">No messages yet.</span> Replies appear here with
the figures they are based on.
</p>
</div>
{suggestions.length > 0 && (
<ul
aria-label="Starter prompts"
className="w-full divide-y divide-border overflow-hidden rounded-xl border border-border"
>
{suggestions.map((suggestion) => (
<li key={suggestion}>
<button
type="button"
onClick={() => fillDraft(suggestion)}
className={cn(suggestionClass, focusClass)}
>
{suggestion}
<PenLine aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
</button>
</li>
))}
</ul>
)}
</div>
)}
<div
role="log"
aria-live="polite"
aria-label={`Conversation with ${assistantName}`}
className="flex flex-col gap-6 empty:hidden"
>
{!loading && settledMessages.map(renderMessage)}
</div>
{!loading && writingMessage && renderMessage(writingMessage)}
{replying && (
<p aria-hidden="true" className="flex items-center gap-1.5 text-sm text-muted-foreground">
<LoaderCircle className="size-3.5 motion-safe:animate-spin" />
{status === "submitted" ? `${assistantName} is thinking` : "Writing"}
</p>
)}
<div role="alert" className="flex flex-wrap items-center justify-between gap-3 empty:hidden">
{status === "error" && (
<>
<p className="flex items-start gap-1.5 text-sm text-destructive">
<CircleAlert aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
{error}
</p>
{onReplyRetry && (
<Button type="button" variant="outline" size="sm" onClick={retry}>
<RotateCw aria-hidden="true" />
Retry reply
</Button>
)}
</>
)}
</div>
</div>
</div>
{jumpShown && (
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center px-4">
<button type="button" onClick={jumpToLatest} className={cn(jumpButtonClass, focusClass)}>
<ArrowDown aria-hidden="true" className="size-4" />
{status === "streaming" ? "Follow the reply" : "Jump to latest"}
</button>
</div>
)}
</div>
<form
data-slot="chat-thread-centered-composer"
aria-label={`Message ${assistantName}`}
onSubmit={(event) => {
event.preventDefault()
send()
}}
className="border-t border-border"
>
<div className="mx-auto flex w-full max-w-prose flex-col gap-2 px-4 py-3 @3xl:px-6">
<label htmlFor={`${baseId}-field`} className="sr-only">
Message to {assistantName}
</label>
<Textarea
ref={fieldRef}
id={`${baseId}-field`}
name="message"
value={draft}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
placeholder={`Message ${assistantName}`}
autoComplete="off"
enterKeyHint="send"
disabled={loading}
aria-invalid={overBy > 0 || undefined}
aria-describedby={`${baseId}-help`}
className="max-h-40 resize-none"
/>
<div className="flex items-center justify-between gap-3">
<div id={`${baseId}-help`} className="min-w-0 flex-1">
{overBy > 0 ? (
<p className="flex items-start gap-1.5 text-sm text-destructive">
<CircleAlert aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
<span>
Shorten the message by <span className="tabular-nums">{numberFormat.format(overBy)}</span>{" "}
{overBy === 1 ? "character" : "characters"} to send it.
</span>
</p>
) : (
<p className="text-xs text-muted-foreground">
Enter sends. Shift+Enter starts a new line.
{draft.length >= maxLength * COUNTER_FROM && (
<span className="tabular-nums">
{" "}
{numberFormat.format(draft.length)} of {numberFormat.format(maxLength)} characters.
</span>
)}
</p>
)}
</div>
<Button
type={replying ? "button" : "submit"}
variant={replying ? "outline" : "default"}
ref={actionRef}
disabled={loading || (replying ? !onReplyStop : draft.trim() === "")}
onClick={replying ? onReplyStop : undefined}
className="w-20"
>
{replying ? <Square aria-hidden="true" /> : <ArrowUp aria-hidden="true" />}
{replying ? "Stop" : "Send"}
</Button>
</div>
</div>
</form>
<p role="status" className="sr-only">
{liveText}
</p>
</section>
)
}
components/blocks/chat-thread-centered.message.tsx, 101 lines
import { cn } from "@/lib/utils"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { CopyButton } from "@/components/hazine/copy-button"
export interface ChatMessage {
id: string
role: "user" | "assistant"
/** Plain text. A blank line starts a paragraph and lines that start with "- " form a list. */
content: string
/** ISO 8601 timestamp. */
createdAt: string
}
function MessageContent({ content }: { content: string }) {
const blocks = content.split(/\n{2,}/).filter((block) => block.trim() !== "")
return (
<div className="flex min-w-0 flex-col gap-3 text-sm leading-relaxed wrap-anywhere">
{blocks.map((block, index) => {
const lines = block.split("\n")
return lines.every((line) => line.startsWith("- ")) ? (
<ul key={index} className="flex list-disc flex-col gap-1 ps-6 tabular-nums marker:text-muted-foreground">
{lines.map((line, row) => (
<li key={row}>{line.slice(2)}</li>
))}
</ul>
) : (
<p key={index} className="whitespace-pre-wrap">
{block}
</p>
)
})}
</div>
)
}
export interface ChatThreadCenteredMessageProps {
message: ChatMessage
time: string
assistantName: string
latest: boolean
writing: boolean
}
export function ChatThreadCenteredMessage({
message,
time,
assistantName,
latest,
writing,
}: ChatThreadCenteredMessageProps) {
if (message.role === "user") {
return (
<article
data-slot="chat-thread-centered-message"
data-role="user"
aria-label={`You, ${time}`}
className="flex flex-col items-end gap-1 ps-10"
>
<div className="max-w-md min-w-0 rounded-xl bg-muted px-4 py-2">
<MessageContent content={message.content} />
</div>
<time dateTime={message.createdAt} className="text-xs text-muted-foreground tabular-nums">
{time}
</time>
</article>
)
}
return (
<article
data-slot="chat-thread-centered-message"
data-role="assistant"
aria-label={`${assistantName}, ${time}`}
className="group flex flex-col gap-2"
>
<div className="flex items-center gap-2">
<Avatar size="sm" aria-hidden="true">
<AvatarFallback className="font-medium text-foreground">{assistantName.slice(0, 1)}</AvatarFallback>
</Avatar>
<span className="truncate text-sm font-semibold">{assistantName}</span>
<time dateTime={message.createdAt} className="shrink-0 text-xs text-muted-foreground tabular-nums">
{time}
</time>
</div>
<MessageContent content={message.content} />
{!writing && (
<div className="-ms-1.5 flex">
<CopyButton
value={message.content}
copyLabel={`Copy reply from ${time}`}
copiedLabel="Reply copied"
// The newest reply keeps its action visible. Older ones show it on hover, focus and touch.
className={cn(
!latest &&
"opacity-0 transition-opacity duration-150 group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100"
)}
/>
</div>
)}
</article>
)
}
The demo in the preview, 220 lines
"use client"
import * as React from "react"
import {
ChatThreadCentered,
type ChatMessage,
type ChatStatus,
} from "@/components/blocks/chat-thread-centered"
const THINKING_MS = 600
const CHUNK_MS = 40
const CHUNK_CHARACTERS = 6
const HISTORY: ChatMessage[] = [
{
id: "offsite-1",
role: "user",
content: "We have €1,840 for the design offsite in Porto: 8 people, two days. How would you split it?",
createdAt: "2026-11-10T09:41:00Z",
},
{
id: "offsite-2",
role: "assistant",
content:
"Here is a split that keeps a buffer and stays inside €1,840.\n\n- Venue, two days: €620\n- Lunches and one team dinner: €540\n- Airport transfers and local travel: €480\n- Buffer for changes: €200\n\nThat comes to €230 a person. The buffer is 10.9% of the total, close to what your last two offsites kept.",
createdAt: "2026-11-10T09:41:00Z",
},
{
id: "offsite-3",
role: "user",
content: "The venue came back at €700. Take the difference out of the buffer.",
createdAt: "2026-11-10T09:44:00Z",
},
]
const REVISED_SPLIT =
"Done. The venue moves to €700 and the buffer drops to €120, so the total stays at €1,840.\n\n- Venue, two days: €700\n- Lunches and one team dinner: €540\n- Airport transfers and local travel: €480\n- Buffer for changes: €120\n\nThe buffer is now 6.5% of the total. Your travel policy asks for at least 5%, so this still goes through without a second approval."
// The preview has no model behind it, so every send plays this reply back in chunks.
const RECORDED_REPLY =
"This preview is not connected to a model, so here is a recorded reply.\n\nThe current split is unchanged:\n\n- Venue, two days: €700\n- Lunches and one team dinner: €540\n- Airport transfers and local travel: €480\n- Buffer for changes: €120\n\nThat is €1,840 in total, or €230 a person. Scroll up while this is still arriving to pause following, then use the button over the stream to catch up."
const OVERFLOW_MESSAGES: ChatMessage[] = [
{
id: "audit-1",
role: "user",
content:
"Paste of the export link for the record: https://northbook.example/workspaces/design/exports/2026-q3/expenses-by-cost-line-and-approver-with-receipts-attached.csv?include=archived¤cy=EUR&group=cost_line",
createdAt: "2026-11-09T14:02:00Z",
},
{
id: "audit-2",
role: "assistant",
content:
"I read 1,284 rows from that export. Third quarter spend for the design team was €48,615.40 against a budget of €52,000.00, which leaves €3,384.60.\n\n- Software subscriptions, 14 vendors: €19,872.15\n- Contractors, 3 people: €16,400.00\n- Travel and offsites: €7,918.25\n- Hardware and repairs: €3,125.00\n- Research incentives: €1,300.00\n\nThe five lines add up to €48,615.40.",
createdAt: "2026-11-09T14:02:00Z",
},
{
id: "audit-3",
role: "user",
content: "Which subscriptions grew the most?",
createdAt: "2026-11-09T14:05:00Z",
},
{
id: "audit-4",
role: "assistant",
content:
"Three vendors account for most of the growth since the second quarter.\n\n- Prototyping seats went from 9 to 14: +€1,125.00\n- The stock imagery plan moved up a tier: +€540.00\n- User testing credits were bought twice in September: +€798.00\n\nTogether that is +€2,463.00. The other 11 vendors changed by less than €50.00 each.",
createdAt: "2026-11-09T14:05:00Z",
},
{
id: "audit-5",
role: "user",
content:
"The double purchase in September looks like a mistake. Draft a note to Ingrid Solheim in finance asking for one of the two to be refunded, and keep it short because she reads these on her phone between meetings.",
createdAt: "2026-11-09T14:09:00Z",
},
{
id: "audit-6",
role: "assistant",
content:
"Here is a draft.\n\nHi Ingrid, we were charged twice for user testing credits in September: €399.00 on the 4th and €399.00 on the 18th, both on the design team card. Only the first was intended. Could you request a refund for the second? The receipt numbers are UT-2026-09-0418 and UT-2026-09-1877. Thank you, Tomasz\n\nI have not sent anything. Say the word and I will attach both receipts.",
createdAt: "2026-11-09T14:09:00Z",
},
{ id: "audit-7", role: "user", content: "Attach them and send.", createdAt: "2026-11-09T14:12:00Z" },
{
id: "audit-8",
role: "assistant",
content: "Sent to Ingrid Solheim with 2 receipts attached. I will tell you here when she replies.",
createdAt: "2026-11-09T14:12:00Z",
},
{ id: "audit-9", role: "user", content: "And hardware?", createdAt: "2026-11-09T14:20:00Z" },
{
id: "audit-10",
role: "assistant",
content:
"Hardware and repairs came to €3,125.00 across 4 purchases.\n\n- Two calibrated monitors: €1,980.00\n- Laptop battery replacement: €245.00\n- Drawing tablet: €620.00\n- Docking station: €280.00\n\nNothing here is above the €2,000.00 line that needs a second approver.",
createdAt: "2026-11-09T14:20:00Z",
},
{
id: "audit-11",
role: "user",
content: "Good. What is left for the fourth quarter if the remainder rolls over?",
createdAt: "2026-11-09T14:24:00Z",
},
{
id: "audit-12",
role: "assistant",
content:
"The fourth quarter budget is €52,000.00. With €3,384.60 rolled over you would have €55,384.60. If the €399.00 refund arrives, that becomes €55,783.60.",
createdAt: "2026-11-09T14:24:00Z",
},
]
const OVER_LIMIT_DRAFT =
"Compare the Porto quote with the Lisbon one line by line, list every difference in venue, catering and transfers, and tell me which city keeps the buffer above 5% for 8 people."
/** Plays a recorded reply back in chunks after each send, with working Stop and Retry. */
function RecordedThread({
initialMessages,
failFirst = false,
}: {
initialMessages: ChatMessage[]
failFirst?: boolean
}) {
const [messages, setMessages] = React.useState(initialMessages)
const [status, setStatus] = React.useState<ChatStatus>(failFirst ? "error" : "ready")
const timer = React.useRef<number | undefined>(undefined)
const replies = React.useRef(0)
const stop = React.useCallback(() => {
window.clearTimeout(timer.current)
window.clearInterval(timer.current)
timer.current = undefined
}, [])
React.useEffect(() => stop, [stop])
// The reply carries the time of the turn it answers, so the thread stays in order.
function reply(text: string, createdAt: string) {
stop()
setStatus("submitted")
timer.current = window.setTimeout(() => {
replies.current += 1
const id = `recorded-${replies.current}`
let shown = 0
setStatus("streaming")
setMessages((previous) => [
...previous,
{ id, role: "assistant", content: "", createdAt },
])
timer.current = window.setInterval(() => {
shown = Math.min(shown + CHUNK_CHARACTERS, text.length)
const content = text.slice(0, shown)
setMessages((previous) =>
previous.map((message) => (message.id === id ? { ...message, content } : message))
)
if (shown === text.length) {
stop()
setStatus("ready")
}
}, CHUNK_MS)
}, THINKING_MS)
}
return (
<ChatThreadCentered
headingLevel={1}
messages={messages}
onMessagesChange={setMessages}
status={status}
onMessageSend={(message) => reply(RECORDED_REPLY, message.createdAt)}
onReplyRetry={() => reply(REVISED_SPLIT, messages.at(-1)?.createdAt ?? "2026-11-10T09:44:00Z")}
onReplyStop={() => {
stop()
setStatus("ready")
}}
/>
)
}
function StreamingThread() {
const [status, setStatus] = React.useState<ChatStatus>("streaming")
return (
<ChatThreadCentered
headingLevel={1}
status={status}
onReplyStop={() => setStatus("ready")}
messages={[
...HISTORY,
{
id: "offsite-4",
role: "assistant",
content: "Done. The venue moves to €700 and the buffer drops to €120, so the total stays at",
createdAt: "2026-11-10T09:44:00Z",
},
]}
/>
)
}
export default function ChatThreadCenteredDemo() {
return (
<RecordedThread
initialMessages={[
...HISTORY,
{ id: "offsite-4", role: "assistant", content: REVISED_SPLIT, createdAt: "2026-11-10T09:44:00Z" },
]}
/>
)
}
export const scenarios = {
empty: () => <RecordedThread initialMessages={[]} />,
loading: () => <ChatThreadCentered headingLevel={1} status="loading" />,
streaming: () => <StreamingThread />,
error: () => <RecordedThread initialMessages={HISTORY} failFirst />,
invalid: () => <ChatThreadCentered headingLevel={1} maxLength={160} defaultDraft={OVER_LIMIT_DRAFT} />,
overflow: () => <RecordedThread initialMessages={OVERFLOW_MESSAGES} />,
}
Props16
- messages
- ChatMessage[]
- defaultMessages
- ChatMessage[] = DEFAULT_MESSAGES
- onMessagesChange
- (messages: ChatMessage[]) => void
- onMessageSend
- (message: ChatMessage) => void
- Called with the user turn that was just appended. Start the request here.
- status
- ChatStatus = "ready"
- error
- string = "The reply did not arrive. Check your connection, then retry."
- Shown when status is "error". Say what happened and what to do next.
- onReplyStop
- () => void
- Called by the Stop button while a reply is pending or streaming. The button is disabled without it.
- onReplyRetry
- () => void
- Called by the retry button in the error state. The button is hidden without it.
- title
- string = "Porto offsite budget"
- headingLevel
- HeadingLevel = 2
- assistantName
- string = "Marlow"
- suggestions
- string[] = DEFAULT_SUGGESTIONS
- Starter prompts for the empty state. Choosing one fills the message field and does not send.
- defaultDraft
- string = ""
- maxLength
- number = 2000
- Longest message in characters. A counter appears from 80 percent of it.
- locale
- string = "en-US"
- timeZone
- string = "UTC"
- IANA time zone for message times. Fixed by default so server and client render the same text.
Also accepts every prop of Omit<React.ComponentProps<"section">, "title">.
Accessibility
- Pattern
- Landmarks and headings, Form with labelled fields, Button (APG, opens in a new tab)
- Keyboard
Keyboard support for Centered Chat Thread Key Effect Tab Moves to the message stream, then the copy button of each reply, retry when a reply failed, the jump button when it is shown, the message field and Send or Stop Arrow Up, Arrow Down, Page Up, Page Down, Home, End on the stream Scrolls the messages. Scrolling up pauses following and shows the jump button Enter or Space on the jump button Scrolls to the newest message, resumes following and moves focus to the message field Enter in the message field Sends the message and keeps focus in the field. Does nothing while a reply is pending, and keeps focus on the field when the message is over the limit Shift+Enter in the message field Starts a new line Enter or Space on Stop Stops the pending reply. Focus moves to the message field when Send is disabled afterwards Enter or Space on Retry reply Requests the reply again and moves focus to the message field Enter or Space on a starter prompt Fills the message field with the prompt without sending and moves focus to the field - Screen reader
Section labelled by its heading. Messages are articles named by author and time inside a polite log that a reply joins once it is complete, the composer is a named form with a labelled field, and progress, errors and the length limit are announced.
- Announces: Loading conversation.
- Announces: {assistant} is thinking.
- Announces: {assistant} is writing.
- Announces: Prompt added to the message field. Edit it, then send.
- Announces: Reply copied
- Announces: {error}
- Reduced motion
- The spinner and the loading skeleton stay still. Scrolling to the latest message is always instant.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies7
- avatar
- button
- textarea
- @hazine/copy-button
- @hazine/heading
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.