Data display
Chat
Free22.0 KB gzippedA chat interface for an AI assistant (or a person), with no backend of its own: onSend connects it to any API and can stream the reply. Includes a scrolling conversation that follows new messages, an auto-growing message box (Enter sends, Shift+Enter adds a line), Stop and Retry, copy buttons, suggested prompts, and screen reader announcements of each reply.
Accessibility: WCAG 2.2 AA · No A or AA violations in light or dark mode · Keys: Tab, Arrow keys, Page Up and 5 more · Full report
Import
import { Chat } from "@vjdesigns/vjdesigns-ui";
Importing only Chat adds about 22.0 KB of minified, gzipped JavaScript to your app (React not included). The stylesheet is shared by every component and loaded once: 75.1 KB gzipped.
Examples
Basic
onSend connects the Chat to your backend. Return the reply as an AsyncIterable<string> (an async function*) to stream it in. While it streams, Send becomes Stop (Escape works too), and the finished reply is announced to screen readers. Enter sends; Shift+Enter adds a line. Give the Chat a height: it fills the space it's given.
import { Box, Chat, type ChatSendContext } from "@vjdesigns/vjdesigns-ui";
const fakeStream = async function* (_text: string, { signal }: ChatSendContext) {
// A stand-in for your API: waits a moment, then streams a reply word by word.
const reply =
"Start with your footwork: square your feet to the rim, bend your knees, and keep your elbow under the ball.\n\nThen follow through, and hold it until the ball hits the rim.";
await new Promise((resolve) => setTimeout(resolve, 600));
for (const word of reply.split(/(?<=\s)/)) {
if (signal.aborted) return;
await new Promise((resolve) => setTimeout(resolve, 40));
yield word;
}
};
export function Basic() {
return (
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "30rem" }}>
<Chat
assistantName="Coach AI"
onSend={fakeStream}
suggestions={["Fix my free throw", "Plan a 60-minute practice", "Explain the pick and roll"]}
disclaimer="Coach AI can make mistakes. Check important info."
/>
</Box>
);
}
String reply
onSend can also return the whole reply as a string, or a promise of one.
import { Box, Chat } from "@vjdesigns/vjdesigns-ui";
export function StringReply() {
return (
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "24rem" }}>
<Chat
onSend={async (text) => {
await new Promise((resolve) => setTimeout(resolve, 600));
return `You asked: "${text}". Here's a full reply, returned in one piece.`;
}}
/>
</Box>
);
}
Connecting abackend
Most AI APIs stream server-sent events. readEventStream turns a fetch response into each event's data; parse it and yield the text. Pass signal to fetch so Stop cancels the request. Keep API keys on your server: call your own route, which calls the model provider. (This example fakes the server response in memory.)
import { Box, Chat, readEventStream } from "@vjdesigns/vjdesigns-ui";
export function ConnectingABackend() {
return (
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "26rem" }}>
<Chat
assistantName="Coach AI"
onSend={async function* (text, { signal }) {
// In your app: const res = await fetch("/api/chat", { method: "POST", body: JSON.stringify({ messages }), signal });
const events = `Here's how I'd answer "${text}" from a streaming API.`
.split(" ")
.map((word) => `data: ${JSON.stringify({ text: `${word} ` })}\n\n`)
.join("");
const res = new Response(`${events}data: [DONE]\n\n`);
for await (const data of readEventStream(res)) {
if (signal.aborted || data === "[DONE]") break;
await new Promise((resolve) => setTimeout(resolve, 60));
yield JSON.parse(data).text ?? "";
}
}}
/>
</Box>
);
}
With avatars
Avatars sit beside each speaker. They're decorative: each message starts with hidden text ("Coach AI said:") so screen readers know who's talking. system messages are centered notes. Finished replies get a Copy button (copyable).
import {
Avatar,
Box,
Chat,
type ChatMessage,
type ChatSendContext,
} from "@vjdesigns/vjdesigns-ui";
const fakeStream = async function* (_text: string, { signal }: ChatSendContext) {
// A stand-in for your API: waits a moment, then streams a reply word by word.
const reply =
"Start with your footwork: square your feet to the rim, bend your knees, and keep your elbow under the ball.\n\nThen follow through, and hold it until the ball hits the rim.";
await new Promise((resolve) => setTimeout(resolve, 600));
for (const word of reply.split(/(?<=\s)/)) {
if (signal.aborted) return;
await new Promise((resolve) => setTimeout(resolve, 40));
yield word;
}
};
const conversation: ChatMessage[] = [
{ id: "1", role: "system", content: "Coach AI joined the conversation" },
{ id: "2", role: "user", content: "How often should a 12U team practice?" },
{
id: "3",
role: "assistant",
content:
"Two practices a week of about 75 minutes works well. Spend the first 15 on ball handling, then shooting, then a short scrimmage so they get to play.",
},
];
export function WithAvatars() {
return (
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "30rem" }}>
<Chat
assistantName="Coach AI"
assistantAvatar={<Avatar name="Coach AI" size="sm" tone="primary" variant="solid" decorative />}
userAvatar={<Avatar name="Dana Hernandez" size="sm" decorative />}
defaultMessages={conversation}
onSend={fakeStream}
/>
</Box>
);
}
Error and retry
When onSend throws, the reply shows an error with a Retry button, and the error is announced. This backend fails the first time. onError receives what was thrown, for logging.
import { useState } from "react";
import { Box, Chat } from "@vjdesigns/vjdesigns-ui";
export function ErrorAndRetry() {
const [calls, setCalls] = useState(0);
return (
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "24rem" }}>
<Chat
defaultDraft="Is the gym open on Sunday?"
onSend={async () => {
setCalls((n) => n + 1);
await new Promise((resolve) => setTimeout(resolve, 400));
if (calls === 0) throw new Error("503 Service Unavailable");
return "Yes, from noon to 6 pm.";
}}
onError={(error) => console.warn(error)}
/>
</Box>
);
}
Controlled
Controlled: the parent owns messages, so it can save, clear or seed the conversation. Here onSend returns nothing and the parent adds the reply itself, the way a WebSocket or a human agent would.
Support (0)
import { useState } from "react";
import {
Box,
Button,
Chat,
Flex,
Icon,
Text,
type ChatMessage,
} from "@vjdesigns/vjdesigns-ui";
export function Controlled() {
const [messages, setMessages] = useState<ChatMessage[]>([]);
return (
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "30rem" }}>
<Flex direction="column" style={{ height: "100%" }}>
<Flex align="center" justify="between" gap={3} style={{ padding: "0.75rem 1rem" }}>
<Text weight="bold">Support ({messages.filter((m) => m.role !== "system").length})</Text>
<Button
size="sm"
variant="ghost"
tone="neutral"
startIcon={<Icon name="trash" />}
disabled={messages.length === 0}
onClick={() => setMessages([])}
>
Clear chat
</Button>
</Flex>
<Box style={{ flex: "1 1 auto", minHeight: 0 }}>
<Chat
messages={messages}
onMessagesChange={setMessages}
onSend={(text) => {
setTimeout(() => {
setMessages((prev) => [
...prev,
{ id: String(Date.now()), role: "assistant", content: `An agent got your message: "${text}"` },
]);
}, 800);
}}
/>
</Box>
</Flex>
</Box>
);
}
Custom rendering
renderContent renders messages your way, for example through your Markdown renderer. This one turns **bold** into <strong> and keeps paragraphs. Never render unsanitized HTML from a model or a user.
import { Box, Chat } from "@vjdesigns/vjdesigns-ui";
export function CustomRendering() {
return (
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "26rem" }}>
<Chat
defaultDraft="Plan a 60-minute practice"
onSend={async () => "**Warm-up:** 10 minutes\n\n**Shooting:** 20 minutes\n\n**Scrimmage:** 30 minutes"}
renderContent={(message) =>
message.content.split(/\n{2,}/).map((paragraph, i) => (
<p key={i} style={{ margin: 0, marginTop: i ? "0.5rem" : 0 }}>
{paragraph.split(/(\*\*[^*]+\*\*)/).map((part, j) =>
part.startsWith("**") ? <strong key={j}>{part.slice(2, -2)}</strong> : part,
)}
</p>
))
}
/>
</Box>
);
}
Limits and disabled
maxLength limits a message and shows a character counter near the limit. disabled turns off the message box and suggestions, for example when a chat is closed.
import { Box, Chat, Flex, type ChatSendContext } from "@vjdesigns/vjdesigns-ui";
const fakeStream = async function* (_text: string, { signal }: ChatSendContext) {
// A stand-in for your API: waits a moment, then streams a reply word by word.
const reply =
"Start with your footwork: square your feet to the rim, bend your knees, and keep your elbow under the ball.\n\nThen follow through, and hold it until the ball hits the rim.";
await new Promise((resolve) => setTimeout(resolve, 600));
for (const word of reply.split(/(?<=\s)/)) {
if (signal.aborted) return;
await new Promise((resolve) => setTimeout(resolve, 40));
yield word;
}
};
export function LimitsAndDisabled() {
return (
<Flex gap={4} wrap="wrap" style={{ width: "100%" }}>
<Box surface="surface" radius="xl" border overflow="hidden" style={{ flex: "1 1 18rem", height: "18rem" }}>
<Chat aria-label="Limited chat" maxLength={120} defaultDraft="A long question about zone defense, " onSend={fakeStream} />
</Box>
<Box surface="surface" radius="xl" border overflow="hidden" style={{ flex: "1 1 18rem", height: "18rem" }}>
<Chat aria-label="Closed chat" disabled placeholder="Chat is closed for this game" />
</Box>
</Flex>
);
}
Translated
In Arabic, user messages sit on the left (the end of the line), and every built-in label, hint and announcement comes from the locale. The messages are your own text.
import { Box, Chat, LocaleProvider } from "@vjdesigns/vjdesigns-ui";
import ar from "@vjdesigns/vjdesigns-ui/locales/ar";
export function Translated() {
return (
<LocaleProvider locale="ar" messages={ar}>
<Box surface="surface" radius="xl" border overflow="hidden" style={{ width: "100%", height: "24rem" }}>
<Chat
defaultMessages={[
{ id: "1", role: "user", content: "كيف أحسّن رميتي الحرة؟" },
{ id: "2", role: "assistant", content: "ابدأ بقدميك: وجّههما نحو السلة، واثنِ ركبتيك، وأبقِ مرفقك تحت الكرة." },
]}
/>
</Box>
</LocaleProvider>
);
}
Usage notes
<Chat
style={{ blockSize: 560 }}
onSend={async function* (text, { messages, signal }) {
const res = await fetch("/api/chat", {
method: "POST",
body: JSON.stringify({ messages }),
signal,
});
yield* readTextStream(res);
}}
/>
API reference
Chat
New in 2.1.0| Prop | Type | Default |
|---|---|---|
messagesControlled conversation. | ChatMessage[] | — |
defaultMessagesInitial conversation when uncontrolled. | ChatMessage[] | — |
onMessagesChangeCalled with the whole conversation whenever it changes (new messages, every streamed chunk, status changes). | (messages: ChatMessage[]) => void | — |
onSendConnects the Chat to your backend. Called with the user's text when they send a message (or retry). Return the reply as a string, stream it as an | (text: string, context: ChatSendContext) => ChatSendResult | Promise<ChatSendResult> | — |
onStopCalled when the user stops a reply, after its | () => void | — |
onErrorCalled with whatever | (error: unknown) => void | — |
draftControlled text of the message box. | string | — |
defaultDraftInitial text of the message box when uncontrolled. | string | — |
onDraftChangeCalled with the message box text on every edit. | (draft: string) => void | — |
suggestionsPrompts offered as buttons while the conversation is empty. Pressing one sends it. | string[] | — |
emptyStateShown while the conversation is empty, above the suggestions. Defaults to a short greeting ( | ReactNode | — |
renderContentRenders a message's content, e.g. through your Markdown renderer. Defaults to plain text with line breaks kept, which is always safe. Security: treat every message as untrusted, including the model's replies (a prompt injection can make a model write anything). When you render it yourself:
| (message: ChatMessage) => ReactNode | — |
assistantNameName of the assistant, read to screen readers ("Coach said:"). Defaults to | string | — |
assistantAvatarShown beside assistant messages (e.g. an | ReactNode | — |
userAvatarShown beside user messages. Decorative: hidden from assistive technology. | ReactNode | — |
copyableShow a Copy button under finished assistant messages. | boolean | true |
disclaimerSmall print under the message box, e.g. "AI can make mistakes." | ReactNode | — |
placeholderPlaceholder of the message box. Defaults to | string | — |
maxLengthMaximum length of a message, in characters. Shows a counter near the limit. | number | — |
disabledDisables the message box and the suggestions. | boolean | — |
labelsOverrides for the built-in text. | Partial<ChatLabels> | — |
Also accepts native <section> attributes, plus className, style and ref.
See what changed in each version in the Changelog.
Accessibility report
Chat targets WCAG 2.2 AA. Below: a live axe-core audit of this page's examples, Lighthouse scores for the page in both modes, the accessibility behavior built into the component, and the checks only a person can do.
axe-core audit (live)
Checking the examples above…
Lighthouse audit
Light mode
Score 10036 passed · 0 failed · 29 not applicable · 10 to check by hand
Dark mode
Score 10036 passed · 0 failed · 29 not applicable · 10 to check by hand
Lighthouse 13.5.0 audits the whole docs page (header and sidebar included), not just the examples, in English. Last run 11/27/2026. Some failed audits carry no weight in the score, so a page can score 100 and still list one.
Built-in behavior
Keyboard
| Key | Action |
|---|---|
| Tab | Moves to the conversation, the suggestions and each reply's Copy and Retry buttons, Jump to latest message, the message box, and Send (or Stop). |
| Arrow keysPage UpPage Down | On the focused conversation: scroll it. |
| Enter | In the message box: sends the message. |
| Shift+Enter | In the message box: adds a new line. Enter while composing with an input method editor also adds text instead of sending. |
| Escape | In the message box, while a reply streams: stops it. |
| EnterSpace | Activates the focused button. |
Focus returns to the message box after Stop, Retry and Jump to latest message. New messages scroll into view only while the conversation is scrolled to the end, so reading earlier messages isn't interrupted.
Roles and states
| Element | Role | States and properties |
|---|---|---|
<section> | region | aria-label ("Chat"), or your aria-label / aria-labelledby |
| Conversation | region | aria-label ("Conversation"), tabindex="0", aria-busy while a reply streams |
| Each message | article | Starts with hidden text ("You said:", "Coach AI said:"); aria-busy while streaming |
| Typing indicator | none | Dots are aria-hidden; hidden text reads "Coach AI is typing" |
| Suggestions | group | aria-label ("Suggested prompts") |
| Message box | textbox (multi-line) | aria-label ("Message"), aria-describedby → the Enter / Shift+Enter hint |
| Send / Stop | button | aria-label ("Send message" / "Stop response"); Send is disabled while the box is empty |
| Copy / Retry / Jump to latest | button | aria-label on icon-only buttons; Copy changes to "Copied" |
| Avatars | none | aria-hidden="true" (decorative) |
| Announcements | status | Shared aria-live="polite" region: typing, each finished reply, stopped, errors, copied |
Manual checks
Automated tools find roughly a third of accessibility issues. Test these in your app, with your content.
| Check | What to test | WCAG 2.2 |
|---|---|---|
| Keyboard | Every action works with Tab, Shift+Tab, Enter, Space and the arrow keys, and focus never gets stuck. | 2.1.1 (A), 2.1.2 (A) |
| Focus | Focus moves in a logical order, is always visible, and isn't hidden behind sticky headers. | 2.4.3 (A), 2.4.7 (AA), 2.4.11 (AA), 2.4.13 (AAA) |
| Screen readers | Names, roles and states are announced correctly, and status changes are announced without moving focus. | 1.3.1 (A), 4.1.2 (A), 4.1.3 (AA) |
| Color | Meaning never depends on color alone; your own colors meet contrast in both modes. | 1.4.1 (A), 1.4.3 (AA), 1.4.11 (AA), 1.4.6 (AAA) |
| Zoom and reflow | At 200% text size and at 320px wide (400% zoom), nothing is cut off and no sideways scrolling is needed. | 1.4.4 (AA), 1.4.10 (AA), 1.4.12 (AA) |
| Pointer targets | Click and tap targets are at least 24×24px (44×44px for AAA), or spaced so they don't overlap. | 2.5.8 (AA), 2.5.5 (AAA) |
| Motion | Animations respect the reduced-motion setting. | 2.3.3 (AAA) |