Skip to content
Vertical Jump Designs-uiFront-End Studio
Get Pro

v3.9 is out.

Data display

Chat

Free22.0 KB gzipped

A 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

tsx
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.

How can I help?

Press Enter to send, or Shift+Enter for a new line.

Coach AI can make mistakes. Check important info.

tsx
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.

How can I help?

Press Enter to send, or Shift+Enter for a new line.
tsx
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.)

How can I help?

Press Enter to send, or Shift+Enter for a new line.
tsx
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).

Coach AI joined the conversation

You said:

How often should a 12U team practice?

Coach AI said:

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.

Press Enter to send, or Shift+Enter for a new line.
tsx
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.

How can I help?

Press Enter to send, or Shift+Enter for a new line.
tsx
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)

How can I help?

Press Enter to send, or Shift+Enter for a new line.
tsx
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.

How can I help?

Press Enter to send, or Shift+Enter for a new line.
tsx
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.

How can I help?

36 of 120 characters used
Press Enter to send, or Shift+Enter for a new line.

How can I help?

Press Enter to send, or Shift+Enter for a new line.
tsx
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.

قلت:

كيف أحسّن رميتي الحرة؟

قال المساعد:

ابدأ بقدميك: وجّههما نحو السلة، واثنِ ركبتيك، وأبقِ مرفقك تحت الكرة.

اضغط Enter للإرسال، أو Shift+Enter لسطر جديد.
tsx
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

tsx
<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
Chat props
PropTypeDefault
messages

Controlled conversation.

ChatMessage[]—
defaultMessages

Initial conversation when uncontrolled.

ChatMessage[]—
onMessagesChange

Called with the whole conversation whenever it changes (new messages, every streamed chunk, status changes).

(messages: ChatMessage[]) => void—
onSend

Connects 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 AsyncIterable<string>, or return nothing and add it yourself through controlled messages. Throwing (or rejecting) turns the reply into an error with a Retry button.

(text: string, context: ChatSendContext) => ChatSendResult | Promise<ChatSendResult>—
onStop

Called when the user stops a reply, after its signal is aborted.

() => void—
onError

Called with whatever onSend threw, for logging. The user sees labels.error (or the message's error).

(error: unknown) => void—
draft

Controlled text of the message box.

string—
defaultDraft

Initial text of the message box when uncontrolled.

string—
onDraftChange

Called with the message box text on every edit.

(draft: string) => void—
suggestions

Prompts offered as buttons while the conversation is empty. Pressing one sends it.

string[]—
emptyState

Shown while the conversation is empty, above the suggestions. Defaults to a short greeting (labels.emptyTitle).

ReactNode—
renderContent

Renders 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:

  • Render to React elements, not an HTML string. Don't pass content to dangerouslySetInnerHTML, and don't enable raw HTML in your Markdown renderer. If you must render HTML, sanitize it first (e.g. DOMPurify).
  • Allow only http:, https:, and mailto: link URLs (no javascript: or data:), and give external links rel="noopener noreferrer".
  • Don't load remote images from message content automatically: an image URL can leak data from the conversation to another server.
(message: ChatMessage) => ReactNode—
assistantName

Name of the assistant, read to screen readers ("Coach said:"). Defaults to labels.assistant.

string—
assistantAvatar

Shown beside assistant messages (e.g. an Avatar or Icon). Decorative: hidden from assistive technology.

ReactNode—
userAvatar

Shown beside user messages. Decorative: hidden from assistive technology.

ReactNode—
copyable

Show a Copy button under finished assistant messages.

booleantrue
disclaimer

Small print under the message box, e.g. "AI can make mistakes."

ReactNode—
placeholder

Placeholder of the message box. Defaults to labels.placeholder.

string—
maxLength

Maximum length of a message, in characters. Shows a counter near the limit.

number—
disabled

Disables the message box and the suggestions.

boolean—
labels

Overrides 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)

Running accessibility audit

Checking the examples above…

Lighthouse audit

Light mode

Score 100

36 passed · 0 failed · 29 not applicable · 10 to check by hand

Dark mode

Score 100

36 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

Keyboard
KeyAction
TabMoves 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 DownOn the focused conversation: scroll it.
EnterIn the message box: sends the message.
Shift+EnterIn the message box: adds a new line. Enter while composing with an input method editor also adds text instead of sending.
EscapeIn the message box, while a reply streams: stops it.
EnterSpaceActivates 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

Roles and states
ElementRoleStates and properties
<section>regionaria-label ("Chat"), or your aria-label / aria-labelledby
Conversationregionaria-label ("Conversation"), tabindex="0", aria-busy while a reply streams
Each messagearticleStarts with hidden text ("You said:", "Coach AI said:"); aria-busy while streaming
Typing indicatornoneDots are aria-hidden; hidden text reads "Coach AI is typing"
Suggestionsgrouparia-label ("Suggested prompts")
Message boxtextbox (multi-line)aria-label ("Message"), aria-describedby → the Enter / Shift+Enter hint
Send / Stopbuttonaria-label ("Send message" / "Stop response"); Send is disabled while the box is empty
Copy / Retry / Jump to latestbuttonaria-label on icon-only buttons; Copy changes to "Copied"
Avatarsnonearia-hidden="true" (decorative)
AnnouncementsstatusShared 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.

Manual accessibility checks
CheckWhat to testWCAG 2.2
KeyboardEvery 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)
FocusFocus 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 readersNames, 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)
ColorMeaning 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 reflowAt 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 targetsClick 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)
MotionAnimations respect the reduced-motion setting.2.3.3 (AAA)