About
Chat messages with roles, avatars, a streaming caret, queued follow ups and a meta line with model, tokens, time and cost.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Message to your project and fits it to your theme.
Code
How Message 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 { Message, MessageAvatar, MessageContent, MessageMeta, MessageState, MessageStatus } from "@/components/ui/message"
interface Turn {
from: "user" | "assistant"
text: string
state: MessageState
meta?: { tokens: number; durationMs: number; cost: number }
}
const HISTORY: Turn[] = [
{ from: "user", text: "The runs page takes about three seconds to show anything.", state: "done" },
{
from: "assistant",
text: "The page waits for every run before it renders. Streaming the list in pages would show the first rows right away.",
state: "done",
meta: { tokens: 412, durationMs: 1900, cost: 0.0031 },
},
]
const ASK = "Do that, and keep the filters working."
const REPLY =
"Splitting the query into pages of 50 and streaming each one as it lands. The filters move into the URL, so a reload keeps them and every page uses the same ones."
/** The reply being written: the last streaming assistant turn. */
function findStreaming(turns: Turn[]) {
for (let k = turns.length - 1; k >= 0; k -= 1) if (turns[k]!.state === "streaming") return k
return -1
}
const WORD_MS = 70
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])
}
const FOLLOW = "Then add a test for it."
const FOLLOW_REPLY =
"Added a test that loads 120 runs, filters to failed ones and checks the first page renders before the rest arrive."
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>
)
}
type StreamingCaretStatus = "streaming" | "waiting" | "done"
interface StreamingCaretProps extends Omit<React.ComponentProps<"span">, "children"> {
/**
* `streaming` is solid, `waiting` blinks slowly, `done` removes the caret. Defaults to
* `streaming`.
*/
status?: StreamingCaretStatus
/**
* Pass the streamed text (or anything that changes with each token). While it keeps changing
* the caret stays solid; once it holds still for `idleMs` the caret starts to blink.
*/
activity?: unknown
/** Quiet time before the caret switches to blinking. Defaults to 600 ms. */
idleMs?: number
}
/**
* The signature mark: a small rounded square that means "the model is writing here". It sits on
* the text baseline at 0.55em, so it scales with whatever text it follows. Solid while tokens flow,
* a slow 1.2 s blink only while waiting, gone when done. Static under reduced motion.
*/
function StreamingCaret({
status = "streaming",
activity,
idleMs = 600,
className,
...props
}: StreamingCaretProps) {
const [idle, setIdle] = React.useState(false)
const tracking = activity !== undefined && status === "streaming"
React.useEffect(() => {
if (!tracking) return
setIdle(false)
const id = window.setTimeout(() => setIdle(true), idleMs)
return () => window.clearTimeout(id)
}, [activity, tracking, idleMs])
if (status === "done") return null
const blinking = status === "waiting" || (tracking && idle)
return (
<span
aria-hidden="true"
data-slot="streaming-caret"
data-caret-state={blinking ? "waiting" : "streaming"}
className={cn(
"bg-(color:--chatcn-accent) ms-0.5 inline-block size-[0.55em] translate-y-[0.04em] rounded-[0.12em] align-baseline forced-colors:bg-[CanvasText]",
blinking &&
"animate-[chatcn-caret-blink_1.2s_steps(1,end)_infinite] motion-reduce:animate-none",
className,
)}
{...props}
/>
)
}
/** 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>
)
}
/**
* One conversation, turn by turn: your messages in bubbles with your initials, replies as a flat
* document with the assistant mark. A reply streams with a caret, a follow up you send meanwhile
* waits as queued, then it goes out and gets its own answer. Each finished reply shows its model,
* tokens, time and cost. Loops.
*/
export default function MessagePreview() {
const [turns, setTurns] = React.useState<Turn[]>([
...HISTORY,
{ from: "user", text: ASK, state: "done" },
{ from: "assistant", text: REPLY, state: "done", meta: { tokens: 688, durationMs: 3400, cost: 0.0052 } },
])
const stream = async (wait: (ms: number) => Promise<void>, text: string, onWord?: (i: number) => Promise<void>) => {
const words = text.split(" ")
for (let i = 1; i <= words.length; i += 1) {
setTurns((t) => {
const at = findStreaming(t)
return t.map((turn, k) => (k === at ? { ...turn, text: words.slice(0, i).join(" ") } : turn))
})
await wait(WORD_MS)
await onWord?.(i)
}
}
useLoop(async (wait) => {
await wait(4600)
setTurns([...HISTORY])
await wait(700)
setTurns((t) => [...t, { from: "user", text: ASK, state: "done" }])
await wait(700)
setTurns((t) => [...t, { from: "assistant", text: "", state: "streaming" }])
await stream(wait, REPLY, async (i) => {
if (i === 9) setTurns((t) => [...t, { from: "user", text: FOLLOW, state: "queued" }])
})
setTurns((t) =>
t.map((turn) =>
turn.state === "streaming"
? { ...turn, state: "done", meta: { tokens: 688, durationMs: 3400, cost: 0.0052 } }
: turn,
),
)
await wait(900)
// The queued follow up goes out, and its reply streams under it.
setTurns((t) => t.map((turn) => (turn.state === "queued" ? { ...turn, state: "done" } : turn)))
await wait(500)
setTurns((t) => [...t, { from: "assistant", text: "", state: "streaming" }])
await stream(wait, FOLLOW_REPLY)
setTurns((t) =>
t.map((turn) =>
turn.state === "streaming"
? { ...turn, state: "done", meta: { tokens: 305, durationMs: 2100, cost: 0.0024 } }
: turn,
),
)
await wait(2600)
})
return (
<FitFrame minWidth="38rem">
<div className="flex w-full flex-col items-center justify-center gap-3 p-4">
<div className="bg-(color:--chatcn-bg) rounded-(--chatcn-radius-xl) shadow-(--chatcn-shadow-border) flex h-[23.5rem] w-full max-w-2xl flex-col overflow-hidden">
<div className="border-(color:--chatcn-border) flex h-11 shrink-0 items-center gap-2 border-b px-5">
<span className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) font-medium">Speed up the runs page</span>
<span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle)">atlas-pro</span>
</div>
<div className="flex min-h-0 flex-1 flex-col justify-end gap-5 overflow-hidden px-6 pt-4 pb-5 [mask-image:linear-gradient(to_bottom,transparent,black_3rem)]">
{turns.map((turn, k) => (
<Message
key={k}
from={turn.from}
state={turn.state}
latest={k === turns.length - 1}
animate
>
<MessageAvatar name={turn.from === "user" ? "Priya Kumar" : "Atlas"} />
<MessageContent>
<p>
{turn.text}
{turn.state === "streaming" ? <StreamingCaret /> : null}
</p>
</MessageContent>
{turn.meta ? (
<MessageMeta model="atlas-pro" tokens={turn.meta.tokens} durationMs={turn.meta.durationMs} cost={turn.meta.cost} />
) : null}
{turn.state === "queued" ? <MessageStatus /> : null}
</Message>
))}
</div>
</div>
<MoreOn slug="message">Messages with roles, avatars, streaming, queued turns and meta. On</MoreOn>
</div>
</FitFrame>
)
}
















