UI

Chat thread

Two-way team or support conversation with grouped messages, attachments, reactions, gliding read receipts, typing state, and an autosizing composer.

import { ChatThread } from '@uthereal/ui/chat-thread'

Chat thread playground

  1. Sam Lee

    Morning! Did the staging deploy finish with the new checkout copy?
  2. Yes, all checks passed and the preview link is live.
  3. Maya Chen

    release-qa-checklist.pdf180 KB
    Looks crisp on mobile too. Attached the QA sign-off checklist.
  4. Ready to promote to production whenever you are.
  5. Promoting now โ€” will post here once rollout hits 100%.
    Read
Loading interactive previewโ€ฆ

Overview

ChatThread renders a standalone, two-way conversation block for customer support widgets, direct messages, and team channels. Give its parent container an explicit height because the root fills 100% of its available block size with an internal pinned scroller.

CapabilityBehavior
Message groupingConsecutive messages from the same author within groupWindow (default 5 min) share tightened corners.
Day separatorsLocalized Today, Yesterday, weekday, or date dividers formatted via Intl and useLocale().
AttachmentsImage gallery up to 4 tiles with a +N overflow overlay; non-image files render as download rows.
ReactionsPopover emoji picker (SurfacePopover) and toggleable reaction pills with rolling tabular counts.
Delivery & statusStatus line (Sending, Sent, Delivered, Read, Not delivered with Retry) and gliding avatars.
Live navigationTyping indicator dots, auto-pinning bottom scroll, and a jump-to-latest pill with unread count.
Embedded composerAutosizing textarea (up to 6 lines), file attach via button/paste/drop, and animated send button.

Use ChatThread for interactive two-way conversations. Use ChatComposer alone when messages render in a custom layout such as an AI transcript.

Usage

'use client'
import { useRef, useState } from 'react'
import {
  ChatThread,
  type ChatDraft,
  type ChatMessage,
  type ChatThreadHandle,
} from '@uthereal/ui/chat-thread'

const participants = [
  { id: 'me', name: 'Alex Rivera' },
  { id: 'sam', name: 'Sam Lee' },
]

export function SupportChat() {
  const threadRef = useRef<ChatThreadHandle>(null)
  const [messages, setMessages] = useState<ChatMessage[]>([
    {
      id: 'm1',
      authorId: 'sam',
      text: 'Is the release build green?',
      createdAt: '2026-09-23T09:12:00Z',
    },
    {
      id: 'm2',
      authorId: 'me',
      text: 'Yes, promoting to production now.',
      createdAt: '2026-09-23T09:13:00Z',
      status: 'delivered',
    },
  ])

  function handleSend(draft: ChatDraft) {
    setMessages((prev) => [
      ...prev,
      {
        id: `m-${prev.length + 1}`,
        authorId: 'me',
        text: draft.text || undefined,
        createdAt: new Date(),
        status: 'sent',
      },
    ])
  }

  return (
    <div style={{ height: 480 }}>
      <ChatThread
        ref={threadRef}
        participants={participants}
        currentUserId="me"
        messages={messages}
        readBy={{ sam: 'm2' }}
        typing={['sam']}
        onSend={handleSend}
      />
    </div>
  )
}

Omit messages to run ChatThread uncontrolled from defaultMessages (sending messages and toggling reactions updates internal state automatically). Pass messages with onSend, onReact, and onRetry for server-backed threads.

Examples

Use <SchemaPlayground /> above to inspect recipe, motion, theme, composer, and allowAttachments. The examples below show distinct conversation states and composer configurations.

Live states and read-only transcripts

Pass typing participant IDs to display animated breathing dots and announce typers politely. Mark the viewer's latest message status: 'failed' with onRetry (or retryAction) to expose an inline Retry control, or set composer={false} for a read-only conversation log.

  1. Sam Lee

    Error rate spiked on us-east checkout workers right after build #418.
  2. Rolling back to build #417 and capturing the heap snapshot now.
  3. Rollback command queued โ€” waiting for edge nodes to drain.
    Not delivered
Sam is typing
  1. Priya Patel

    Can we increase the webhook retry window on our Enterprise workspace?
  2. Updated your workspace to 72-hour exponential backoff and replayed the two missed events.
    Read
  3. Priya Patel

    Confirmed both deliveries landed cleanly. Thanks for the fast turnaround!

Attachments and standalone composer

Image attachments arrange into a 1โ€“4 tile gallery with an overflow indicator, while documents render as download rows formatted with formatBytes. Export ChatComposer directly when you need the autosizing attachment box outside ChatThread.

  1. Maya Chen

    checkout-tokens-v3.json42 KB
    Uploaded the updated checkout progress preview and token spec.
  2. Looks clean โ€” pulling the JSON tokens into the release branch now.
    Read

API reference

Serializable schema arguments and defaults come directly from chatThreadConfigSchema.

ArgumentType / defaultDescription
participantsChatParticipant[]Default: [{"id":"me","name":"Alex Rivera"},{"id":"sam","name":"Sam Lee"},{"id":"maya","name":"Maya Chen"}]People in the thread: id, display name, and optional avatar URL. Initials display when avatar is omitted.
currentUserIdstringDefault: "me"Participant ID of the current viewer. Their messages align to the inline end in the accent color.
defaultMessagesChatMessage[]Default: [{"id":"m1","authorId":"sam","text":"Morning! Did the staging deploy finish with the new checkout copy?","createdAt":"2026-09-22T15:10:00Z"},{"id":"m2","authorId":"me","text":"Yes, all checks passed and the preview link is live.","createdAt":"2026-09-22T15:12:00Z","status":"read"},{"id":"m3","authorId":"maya","text":"Looks crisp on mobile too. Attached the QA sign-off checklist.","createdAt":"2026-09-23T09:12:00Z","attachments":[{"id":"att-qa","name":"release-qa-checklist.pdf","kind":"file","size":184320}],"reactions":[{"emoji":"๐ŸŽ‰","count":2,"mine":true}]},{"id":"m4","authorId":"maya","text":"Ready to promote to production whenever you are.","createdAt":"2026-09-23T09:13:00Z"},{"id":"m5","authorId":"me","text":"Promoting now โ€” will post here once rollout hits 100%.","createdAt":"2026-09-23T09:14:30Z","status":"delivered"}]Initial messages oldest first for uncontrolled threads. Later schema edits do not reset a mounted instance.
typingstring[]Default: []Participant IDs currently typing. The current user is ignored automatically.
readByRecord<string, string>Default: {"sam":"m5","maya":"m5"}Map of participant ID to the last message ID they read. Reader avatars glide beneath the latest read message.
reactionsstring[]Default: ["๐Ÿ‘","โค๏ธ","๐Ÿ˜‚","๐ŸŽ‰","๐Ÿ‘€","๐Ÿ™"]Emoji glyphs offered inside the reaction picker popover.
placeholderstringDefault: "Message"Placeholder text and accessible label for the composer textarea.
composerbooleanDefault: trueShow the embedded message composer. Set to false for a read-only conversation transcript.
allowAttachmentsbooleanDefault: trueAllow attaching images and files via button, paste, or drag-and-drop in the composer.
acceptstringโ€”Comma-separated MIME types or file extensions forwarded to the hidden file input.
groupWindowintegerDefault: 300000Maximum milliseconds between consecutive messages from the same author to share a bubble group (default 300000, five minutes).
labelstringDefault: "Conversation"Accessible name of the message log region.
sendActionstringโ€”Registered host action name sent to onAction when the viewer submits a message.
reactActionstringโ€”Registered host action name sent to onAction with the message ID when a reaction is picked or toggled.
retryActionstringโ€”Registered host action name sent to onAction with the message ID when Retry is activated on a failed message.
localestringโ€”BCP 47 locale for message timestamps and day separators; inherited from UtherealProvider when omitted.
recipestudio | softDefault: "studio"Visual treatment. Both recipes preserve identical behavior.
themeChatThreadThemeโ€”Color mode, accent, and semantic design token overrides including bubbleSurface and bubbleRadius.
motionnone | subtle | expressiveDefault: "subtle"Animation preset. System reduced-motion preferences take precedence.
motionOptionsChatThreadMotionOptionsโ€”Reaction picker stagger and message arrival fade duration overrides, in milliseconds.
dirltr | rtlโ€”Reading direction; omit to inherit the page direction.

React integration

PropPurpose
messagesControlled message array, oldest first (ChatMessage[]). Accepts Date, ISO string, or epoch ms.
onSend(draft)Called with { text, files } on submit. Uncontrolled threads also append a local sent message.
onReact(messageId, emoji)Called when an emoji is picked or toggled. Uncontrolled threads also update counts locally.
onRetry(messageId)Displays the Retry button under a failed latest own message and runs when activated.
onAction(action, itemId?)Host action callback fired for sendAction, reactAction (with message ID), and retryAction.
labelsPartial ChatThreadLabels object overriding UI copy and plural formatters (typing, readByโ€ฆ).
portalContainerCustom DOM mount target for the portalled reaction picker popover.
presetApplication defaults merged below explicit instance props.
tokens--ui-* CSS variables applied after the typed theme on the root and reaction picker portal.
refImperative ChatThreadHandle exposing scrollToBottom(smooth?) and focusComposer().
className, styleAdded to the root <div>. style takes precedence over motion and theme tokens.

ChatThreadHandle

MethodSignatureBehavior
scrollToBottom(smooth?: boolean) => voidScrolls to the newest message and re-pins the thread; instant if reduced motion.
focusComposer() => voidMoves keyboard focus to the embedded composer textarea.

ChatComposer

Standalone export from @uthereal/ui/chat-thread for custom layouts.

PropTypeDefaultPurpose
onSend(draft: ChatDraft) => voidโ€”Required submit callback; composer clears text and files after.
placeholderstring'Message'Textarea placeholder and accessible name.
allowAttachmentsbooleantrueEnables attach button, clipboard paste, and drag-and-drop (โ‰ค10).
acceptstringโ€”MIME types or extensions forwarded to <input type="file">.
disabledbooleanfalseDisables textarea, attach button, paste, and drag-and-drop.
labelsChatComposerLabelsโ€”Localized strings for send, attach, attachments, removeFile.
refRef<ChatComposerHandle>โ€”Exposes focus() for the textarea.

formatBytes

formatBytes(bytes?: number): string formats raw byte counts as B, KB, or MB (for example formatBytes(184320) returns '180 KB').

Keyboard & accessibility

KeyInteraction
Enter (composer)Submits the draft; ignored while an IME composition session is active.
Shift+Enter (composer)Inserts a newline and grows the textarea up to six lines.
Tab, Shift+TabMoves across links, reaction triggers (revealed on row focus), reaction chips, and composer.
ArrowLeft, ArrowRightMoves roving focus across emoji buttons in the open reaction picker (mirrors in RTL).
Home, End (picker)Jumps roving focus to the first or last emoji button in the reaction picker.
Escape (picker)Closes the reaction picker and restores focus to its trigger button.
  • The message list renders as <ol role="log" aria-live="polite" aria-relevant="additions"> labeled by label so new arrivals are announced without interrupting speech.
  • Typing activity announces through a separate pre-mounted role="status" live region ("Sam is typing"); visual breathing dots are marked aria-hidden="true".
  • Reaction chips expose aria-pressed and full labels combining emoji, count, and viewer participation. Visual rolling digits and participant avatars are decorative (aria-hidden="true").
  • Read receipt clusters carry an aria-label listing every reader by name.
  • All layout geometry, grouped bubble radii, avatars, and keyboard arrows use logical CSS properties and mirror in dir="rtl". Under forced-colors: active, bubbles, controls, selected reactions, and focus outlines map to system colors (ButtonText, Highlight, HighlightText).

Motion and theming

New messages arrive from their author's side on a zero-bounce spring while the pinned scroller glides smoothly to absorb the added height. Read-receipt avatars share a scoped layoutId inside LazyMotion (domMax) so avatars travel smoothly to newly read messages. Reaction counts roll with RollingNumber, attachment and reaction trays spring open, the send arrow lifts out on submit, and the jump-to-latest pill morphs width as unread counts appear.

motion="none" sets all springs, CSS transitions, and typing loops to immediate (0ms). prefers-reduced-motion: reduce removes travel, scale, blur, and dot breathing animations while keeping a 120ms opacity crossfade and instant scroll jumps.

Token / GroupRole
--ui-surface, --ui-surface-raisedThread canvas, file rows, jump-to-latest pill, and reaction picker.
--ui-accent, --ui-accent-foregroundOutgoing viewer bubbles, ready send button, and active reaction tint.
--ui-chat-thread-bubble-surfaceIncoming message bubble surface (highlight in light, surfaceRaised in dark).
--ui-chat-thread-bubble-radiusOuter message bubble corner radius (18px studio, 20px soft).
--ui-border, --ui-border-subtle, --ui-border-strongDay separators, file rows, composer shell, and hover edges.
--ui-dangerFailed delivery status copy.

Composition

In agent compositions, ChatThread is a leaf block (group: 'blocks-general'). Register sendAction, reactAction, and retryAction on the host to handle user events cleanly.

{
  "type": "ChatThread",
  "props": {
    "label": "Release coordination",
    "currentUserId": "me",
    "participants": [
      { "id": "me", "name": "Alex Rivera" },
      { "id": "sam", "name": "Sam Lee" }
    ],
    "defaultMessages": [
      {
        "id": "m1",
        "authorId": "sam",
        "text": "Staging deploy is green.",
        "createdAt": "2026-09-23T09:12:00Z"
      }
    ],
    "sendAction": "send_chat_message",
    "reactAction": "toggle_chat_reaction"
  },
  "children": []
}

On this page