Chat conversation
A conversation with one person: a header with their name and online status, the history split by day, bubbles on either side grouped when one person sends several in a row, a read receipt on your latest message, a shared file in a small Card, a typing indicator, and a Textarea composer with a send Button.
Maya Okafor
Online · Trail crew leadYesterday
Maya Okafor:
The permit office says Larch Creek trailhead reopens Friday 🎉
They need the crew list by Thursday noon, though.
You:
Great news. I’ll pull the roster tonight.
Do they want vehicle plates too?
Maya Okafor:
Yes, plates and one emergency contact per person.
Today
Maya Okafor:
Here’s the form. Pages 2 and 3 are ours.
You:
Got it, filling it in now.
Maya is typing
Source · recipes/chat-conversation.tsx
'use client'
import { Button, Card, Heading, Stack, Text, Textarea } from '@blocks/design-system'
import { Check, CheckCheck, Download, FileText, SendHorizontal } from 'lucide-react'
import { type FormEvent, type KeyboardEvent, useEffect, useId, useRef, useState } from 'react'
import styles from './chat-conversation.module.css'
type Sender = 'me' | 'maya'
interface Message {
id: string
from: Sender
day: string
time: string
text: string
attachment?: { name: string; detail: string }
status?: 'sent' | 'read'
}
const initialMessages: Message[] = [
{ id: 'm1', from: 'maya', day: 'Yesterday', time: '4:12 pm', text: 'The permit office says Larch Creek trailhead reopens Friday 🎉' },
{ id: 'm2', from: 'maya', day: 'Yesterday', time: '4:12 pm', text: 'They need the crew list by Thursday noon, though.' },
{ id: 'm3', from: 'me', day: 'Yesterday', time: '4:30 pm', text: 'Great news. I’ll pull the roster tonight.', status: 'read' },
{ id: 'm4', from: 'me', day: 'Yesterday', time: '4:31 pm', text: 'Do they want vehicle plates too?', status: 'read' },
{ id: 'm5', from: 'maya', day: 'Yesterday', time: '4:45 pm', text: 'Yes, plates and one emergency contact per person.' },
{
id: 'm6',
from: 'maya',
day: 'Today',
time: '9:02 am',
text: 'Here’s the form. Pages 2 and 3 are ours.',
attachment: { name: 'larch-creek-permit.pdf', detail: 'PDF · 2.4 MB' },
},
{ id: 'm7', from: 'me', day: 'Today', time: '9:20 am', text: 'Got it, filling it in now.', status: 'read' },
]
const replies = ['Perfect, thank you!', 'Sounds good 👍', 'See you at the trailhead Friday.']
const names: Record<Sender, string> = { me: 'You', maya: 'Maya Okafor' }
// Consecutive messages from one sender on one day share a group.
function groupMessages(messages: Message[]) {
const groups: { day: string; from: Sender; messages: Message[] }[] = []
for (const message of messages) {
const last = groups.at(-1)
if (last && last.from === message.from && last.day === message.day) last.messages.push(message)
else groups.push({ day: message.day, from: message.from, messages: [message] })
}
return groups
}
// A messaging view. The history is a role="log" region, so new messages are
// announced; Enter sends and Shift+Enter adds a line. Maya's replies are
// simulated with timers so the read receipt and typing indicator move.
export default function ChatConversation() {
const [messages, setMessages] = useState(initialMessages)
const [draft, setDraft] = useState('')
const [typing, setTyping] = useState(true)
const logRef = useRef<HTMLDivElement>(null)
const timers = useRef<number[]>([])
const id = useId()
// Keep the newest message in view.
useEffect(() => {
const log = logRef.current
if (log && messages.length > 0) log.scrollTop = log.scrollHeight
}, [messages])
useEffect(() => () => timers.current.forEach(clearTimeout), [])
function later(callback: () => void, delay: number) {
timers.current.push(window.setTimeout(callback, delay))
}
function send(event?: FormEvent<HTMLFormElement>) {
event?.preventDefault()
const text = draft.trim()
if (!text) return
const messageId = `m${messages.length + 1}`
const time = new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' }).toLowerCase()
const reply = replies[messages.filter((message) => message.from === 'me').length % replies.length] ?? 'Thanks!'
setMessages((current) => [...current, { id: messageId, from: 'me', day: 'Today', time, text, status: 'sent' }])
setDraft('')
setTyping(false)
later(() => {
setMessages((current) => current.map((message) => (message.id === messageId ? { ...message, status: 'read' } : message)))
setTyping(true)
}, 1200)
later(() => {
setTyping(false)
setMessages((current) => [...current, { id: `${messageId}-reply`, from: 'maya', day: 'Today', time, text: reply }])
}, 3200)
}
function sendOnEnter(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
event.preventDefault()
send()
}
}
const groups = groupMessages(messages)
const lastMine = messages.findLast((message) => message.from === 'me')
return (
<Card as="section" aria-labelledby={`${id}-name`} padding="none" borderRadius="xl" dangerouslySetClassName={styles.chat}>
<header className={styles.header}>
<span className={styles.avatar} aria-hidden>
MO
<span className={styles.presence} />
</span>
<Stack gap="none">
<Heading as="h2" id={`${id}-name`} fontSize="md">
Maya Okafor
</Heading>
<Text fontSize="xs" color="text-muted">
Online · Trail crew lead
</Text>
</Stack>
</header>
<div ref={logRef} role="log" aria-label="Messages with Maya Okafor" className={styles.log}>
{groups.map((group, index) => (
<div key={group.messages[0]?.id} className={styles.groupWrap}>
{group.day !== groups[index - 1]?.day && (
<p className={styles.day}>
<span>{group.day}</span>
</p>
)}
<div className={group.from === 'me' ? styles.mine : styles.theirs}>
<span className={styles.visuallyHidden}>{names[group.from]}:</span>
{group.messages.map((message) => (
<div key={message.id} className={styles.bubble}>
{message.attachment && (
<Card padding="sm" backgroundColor="bg-subtle" borderWidth="none" borderRadius="md" dangerouslySetClassName={styles.attachment}>
<Stack direction="row" gap="sm" align="center">
<FileText aria-hidden className={styles.fileIcon} />
<Stack gap="none" flex="1" dangerouslySetClassName={styles.fileText}>
<Text fontSize="sm" fontWeight="semibold" title={message.attachment.name} dangerouslySetClassName={styles.fileName}>
{message.attachment.name}
</Text>
<Text fontSize="xs" color="text-muted">
{message.attachment.detail}
</Text>
</Stack>
<Button
as="a"
href="#chat-conversation-file"
variant="ghost"
size="sm"
aria-label={`Download ${message.attachment.name}`}
dangerouslySetClassName={styles.download}
>
<Download aria-hidden />
</Button>
</Stack>
</Card>
)}
{message.text}
</div>
))}
<Text fontSize="xs" color="text-muted" dangerouslySetClassName={styles.meta}>
{group.messages.at(-1)?.time}
{lastMine && group.messages.includes(lastMine) && (
<>
{' · '}
{lastMine.status === 'read' ? <CheckCheck aria-hidden /> : <Check aria-hidden />}
{lastMine.status === 'read' ? 'Read' : 'Sent'}
</>
)}
</Text>
</div>
</div>
))}
</div>
<div className={styles.typingRow} aria-live="polite">
{typing && (
<span className={styles.typing}>
<span aria-hidden className={styles.dots}>
<span />
<span />
<span />
</span>
<span className={styles.visuallyHidden}>Maya is typing</span>
</span>
)}
</div>
<form onSubmit={send} className={styles.composer}>
<Textarea
rows={1}
value={draft}
aria-label="Message Maya Okafor"
aria-describedby={`${id}-hint`}
placeholder="Message Maya"
onChange={(event) => setDraft(event.target.value)}
onKeyDown={sendOnEnter}
dangerouslySetClassName={styles.input}
/>
<Button type="submit" variant="primary" aria-label="Send" disabled={!draft.trim()} dangerouslySetClassName={styles.send}>
<SendHorizontal aria-hidden />
</Button>
<span id={`${id}-hint`} className={styles.visuallyHidden}>
Enter sends, Shift+Enter adds a new line.
</span>
</form>
</Card>
)
}How it works
- The history is a
role="log"region, so a screen reader announces messages as they arrive. Each group starts with hidden text naming the sender, because which side a bubble sits on is only visual. The view scrolls to the newest message whenever the list changes. - Consecutive messages from one person on one day form a group: the bubbles stack closely, their inner corners tuck together, and the time and status appear once, under the last bubble. Read receipts say “Sent” or “Read” in words beside the icon.
- In the composer, Enter sends and Shift+Enter starts a new line; the check skips Enter while an input method is composing text. The send button is disabled until there is something to send, and the hint is attached with
aria-describedby. - Maya’s side is simulated with timers so the demo moves: your message turns from Sent to Read, the typing indicator appears, and a reply lands. The indicator sits outside the log in its own polite live region, and its dots stop moving under
prefers-reduced-motion. - The shared file’s name is one line with an ellipsis, and the download is an icon button whose name includes the full file name.
- The presence dot repeats the word “Online” in the header, so status never relies on color.
App-owned CSS
.chat {
display: flex;
flex-direction: column;
overflow: hidden;
--avatar: var(--ds-control-height-lg);
}
.header {
display: flex;
align-items: center;
gap: var(--ds-space-md);
padding: var(--ds-space-md) var(--ds-space-lg);
border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}
.avatar {
position: relative;
display: grid;
flex-shrink: 0;
place-items: center;
width: var(--avatar);
height: var(--avatar);
font-size: var(--ds-font-size-sm);
font-weight: var(--ds-font-weight-semibold);
color: var(--ds-color-accent-text);
background-color: var(--ds-color-accent-subtle);
border-radius: var(--ds-border-radius-circle);
}
/* The dot repeats "Online", which the header also says in words. */
.presence {
position: absolute;
right: 0;
bottom: 0;
width: var(--ds-space-md);
height: var(--ds-space-md);
background-color: var(--ds-color-success);
border: var(--ds-border-width-md) solid var(--ds-color-bg);
border-radius: var(--ds-border-radius-circle);
box-sizing: content-box;
}
/* The scrolling history. */
.log {
display: flex;
flex-direction: column;
gap: var(--ds-space-lg);
height: 24rem;
overflow-y: auto;
padding: var(--ds-space-lg);
background-color: var(--ds-color-bg-subtle);
}
.groupWrap {
display: flex;
flex-direction: column;
gap: var(--ds-space-lg);
}
.day {
display: flex;
align-items: center;
gap: var(--ds-space-md);
margin: 0;
font-size: var(--ds-font-size-xs);
font-weight: var(--ds-font-weight-semibold);
color: var(--ds-color-text-muted);
&::before,
&::after {
content: "";
flex: 1;
border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}
}
/* A group of bubbles, aligned to its sender's side. */
.mine,
.theirs {
display: flex;
flex-direction: column;
gap: var(--ds-space-xs);
max-width: min(85%, 26rem);
}
.mine {
align-self: flex-end;
align-items: flex-end;
}
.theirs {
align-self: flex-start;
align-items: flex-start;
}
.bubble {
padding: var(--ds-space-md) var(--ds-space-lg);
font-size: var(--ds-font-size-sm);
line-height: var(--ds-line-height-body);
white-space: pre-wrap;
overflow-wrap: anywhere;
border-radius: var(--ds-border-radius-xxl);
}
.mine .bubble {
color: var(--ds-color-accent-fg);
background-color: var(--ds-color-accent);
}
.theirs .bubble {
color: var(--ds-color-text);
background-color: var(--ds-color-bg);
border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}
/* Bubbles in a run tuck their inner corners together. Bubbles are the
group's only <div>s, so the -of-type selectors count just them. */
.mine .bubble:not(:last-of-type) {
border-bottom-right-radius: var(--ds-border-radius-sm);
}
.mine .bubble:not(:first-of-type) {
border-top-right-radius: var(--ds-border-radius-sm);
}
.theirs .bubble:not(:last-of-type) {
border-bottom-left-radius: var(--ds-border-radius-sm);
}
.theirs .bubble:not(:first-of-type) {
border-top-left-radius: var(--ds-border-radius-sm);
}
.meta {
display: inline-flex;
align-items: center;
gap: var(--ds-space-xs);
padding-inline: var(--ds-space-sm);
& svg {
width: var(--ds-icon-size-sm);
height: var(--ds-icon-size-sm);
color: var(--ds-color-accent-text);
}
}
.attachment {
margin-bottom: var(--ds-space-sm);
white-space: normal;
}
.fileIcon {
flex-shrink: 0;
width: var(--ds-icon-size-md);
height: var(--ds-icon-size-md);
color: var(--ds-color-danger-text);
}
.fileText {
min-width: 0;
}
/* One line, ending in an ellipsis; the full name is in the title and the
download button's label. */
.fileName {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* An icon-only link button. Links are content-box, so size it explicitly. */
.attachment .download {
box-sizing: border-box;
flex-shrink: 0;
width: var(--ds-control-height-sm);
padding: 0;
& svg {
width: var(--ds-icon-size-sm);
height: var(--ds-icon-size-sm);
}
}
/* Typing indicator */
.typingRow {
min-height: calc(var(--ds-space-xl) + var(--ds-space-md));
padding: 0 var(--ds-space-lg) var(--ds-space-sm);
background-color: var(--ds-color-bg-subtle);
}
.typing {
display: inline-flex;
padding: var(--ds-space-md) var(--ds-space-lg);
background-color: var(--ds-color-bg);
border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
border-radius: var(--ds-border-radius-xxl);
}
.dots {
display: inline-flex;
gap: var(--ds-space-sm);
& span {
width: var(--ds-space-md);
height: var(--ds-space-md);
background-color: var(--ds-color-text-muted);
border-radius: var(--ds-border-radius-circle);
animation: bounce 1.2s var(--ds-easing-standard) infinite;
}
& span:nth-child(2) {
animation-delay: 0.15s;
}
& span:nth-child(3) {
animation-delay: 0.3s;
}
}
@keyframes bounce {
0%,
60%,
100% {
opacity: 0.4;
translate: 0 0;
}
30% {
opacity: 1;
translate: 0 calc(var(--ds-space-sm) * -1);
}
}
/* Composer */
.composer {
display: flex;
align-items: flex-end;
gap: var(--ds-space-sm);
padding: var(--ds-space-md);
border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}
.input {
min-height: var(--ds-control-height-lg);
max-height: 8rem;
resize: none;
field-sizing: content;
}
.send {
flex-shrink: 0;
width: var(--ds-control-height-lg);
height: var(--ds-control-height-lg);
padding: 0;
& svg {
width: var(--ds-icon-size-md);
height: var(--ds-icon-size-md);
}
}
.visuallyHidden {
position: absolute;
width: var(--ds-space-xxs);
height: var(--ds-space-xxs);
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@media (prefers-reduced-motion: reduce) {
.dots span {
animation: none;
}
}