Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(Chat): add XDSChatLayout with fixed composer dock and container queries (#1249)

Cindy Zhang7d93bc02cf09
diff --git a/apps/storybook/stories/Chat.stories.tsx b/apps/storybook/stories/Chat.stories.tsx
index 8182514d95..70c6f118e2 100644
--- a/apps/storybook/stories/Chat.stories.tsx
+++ b/apps/storybook/stories/Chat.stories.tsx
@@ -13,6 +13,7 @@ import {XDSHStack} from '@xds/core/Stack';
import {XDSCodeBlock} from '@xds/core/CodeBlock';
import {XDSButton} from '@xds/core/Button';
import {XDSIcon} from '@xds/core/Icon';
+import {XDSEmptyState} from '@xds/core/EmptyState';
import {XDSTimestamp} from '@xds/core/Timestamp';
import {HandThumbUpIcon, HandThumbDownIcon} from '@heroicons/react/24/outline';
import {ClipboardDocumentIcon} from '@heroicons/react/24/outline';
@@ -357,10 +358,10 @@ export const EmptyState: StoryObj = {
<div style={{height: 400, display: 'flex', flexDirection: 'column'}}>
<XDSChatMessageList
emptyState={
- <div style={{textAlign: 'center', opacity: 0.5}}>
- <div style={{fontSize: 32, marginBottom: 8}}>💬</div>
- <div>No messages yet. Start a conversation!</div>
- </div>
+ <XDSEmptyState
+ title="No messages yet"
+ description="Start a conversation!"
+ />
}>
{[]}
</XDSChatMessageList>
diff --git a/apps/storybook/stories/ChatComposition.stories.tsx b/apps/storybook/stories/ChatLayout.stories.tsx
similarity index 54%
rename from apps/storybook/stories/ChatComposition.stories.tsx
rename to apps/storybook/stories/ChatLayout.stories.tsx
index 8b9eb4911c..76d290a171 100644
--- a/apps/storybook/stories/ChatComposition.stories.tsx
+++ b/apps/storybook/stories/ChatLayout.stories.tsx
@@ -1,5 +1,6 @@
import type {Meta, StoryObj} from '@storybook/react';
import {
+ XDSChatLayout,
XDSChatMessageList,
XDSChatMessage,
XDSChatMessageBubble,
@@ -7,7 +8,7 @@ import {
XDSChatComposer,
XDSChatComposerAttachments,
XDSChatComposerInput,
- XDSChatMessageTokenizedText,
+ XDSChatTokenizedText,
XDSChatToolCalls,
type XDSChatComposerInputHandle,
type XDSChatComposerToken,
@@ -19,18 +20,24 @@ import {XDSToken} from '@xds/core/Token';
import {XDSButton} from '@xds/core/Button';
import {XDSCodeBlock} from '@xds/core/CodeBlock';
import {XDSProgressBar} from '@xds/core/ProgressBar';
+import {XDSAvatar} from '@xds/core/Avatar';
import {useXDSTooltip} from '@xds/core/Tooltip';
import {createStaticSource} from '@xds/core/Typeahead';
+import {XDSEmptyState} from '@xds/core/EmptyState';
import {useState, useCallback, useRef} from 'react';
-const meta: Meta = {
- title: 'Chat/Compositions',
+const meta: Meta<typeof XDSChatLayout> = {
+ title: 'Chat/XDSChatLayout',
+ component: XDSChatLayout,
tags: ['autodocs'],
parameters: {layout: 'fullscreen'},
};
export default meta;
+// =============================================================================
// Icons
+// =============================================================================
+
const PaperclipIcon = (
<svg
width="1em"
@@ -74,7 +81,10 @@ const MicIcon = (
</svg>
);
+// =============================================================================
// Data
+// =============================================================================
+
const CONTACTS = [
{id: 'cindy', label: 'Cindy Zhang'},
{id: 'alex', label: 'Alex Rivera'},
@@ -164,7 +174,11 @@ const SEED_MESSAGES: Message[] = [
{id: 5, role: 'user', text: 'Nice, can you also check the Card component?'},
];
-/** Full AI chat — message list + composer with streaming, tool calls, triggers, attachments, and interactive modals */
+// =============================================================================
+// Stories
+// =============================================================================
+
+/** Full AI chat with streaming, tool calls, triggers, attachments, and frosted glass composer dock */
export const FullAIChat: StoryObj = {
name: 'Full AI Chat',
render: () => {
@@ -175,6 +189,12 @@ export const FullAIChat: StoryObj = {
const inputRef = useRef<XDSChatComposerInputHandle>(null);
const contextTooltip = useXDSTooltip({placement: 'above'});
+ const mentionTokens = CONTACTS.map(c => ({
+ value: `@${c.id}`,
+ label: `@${c.label}`,
+ variant: 'blue' as const,
+ }));
+
const triggers: XDSChatComposerTrigger[] = [
{
character: '@',
@@ -192,7 +212,6 @@ export const FullAIChat: StoryObj = {
},
];
- // Simulates: stream intro text → run tool calls → stream result text
const streamResponse = useCallback(
(
introText: string,
@@ -202,18 +221,11 @@ export const FullAIChat: StoryObj = {
const msgId = Date.now();
setIsStreaming(true);
- // Start with empty message
setMessages(prev => [
...prev,
- {
- id: msgId,
- role: 'assistant',
- text: '',
- isStreaming: true,
- },
+ {id: msgId, role: 'assistant', text: '', isStreaming: true},
]);
- // Phase 1: stream intro text
let i = 0;
streamRef.current = setInterval(() => {
i += 2 + Math.floor(Math.random() * 4);
@@ -223,7 +235,6 @@ export const FullAIChat: StoryObj = {
prev.map(m => (m.id === msgId ? {...m, text: introText} : m)),
);
- // Phase 2: tool calls appear as running
if (toolCalls) {
setTimeout(() => {
setMessages(prev =>
@@ -241,7 +252,6 @@ export const FullAIChat: StoryObj = {
),
);
- // Phase 2b: tool calls complete
setTimeout(() => {
setMessages(prev =>
prev.map(m =>
@@ -251,7 +261,6 @@ export const FullAIChat: StoryObj = {
),
);
- // Phase 3: stream result text
setTimeout(() => {
let j = 0;
const fullText = introText + '\n\n' + resultText;
@@ -282,7 +291,6 @@ export const FullAIChat: StoryObj = {
}, 1800);
}, 400);
} else {
- // No tool calls — just finish
setMessages(prev =>
prev.map(m =>
m.id === msgId ? {...m, isStreaming: false} : m,
@@ -373,14 +381,88 @@ export const FullAIChat: StoryObj = {
);
}, []);
+ const composerEl = (
+ <XDSChatComposer
+ onSubmit={handleSubmit}
+ onStop={handleStop}
+ isStreaming={isStreaming}
+ attachments={
+ files.length > 0 ? (
+ <XDSChatComposerAttachments>
+ {files.map(f => (
+ <XDSToken
+ key={f}
+ label={f}
+ onRemove={() => setFiles(prev => prev.filter(x => x !== f))}
+ />
+ ))}
+ </XDSChatComposerAttachments>
+ ) : undefined
+ }
+ headerActions={
+ <>
+ <XDSButton
+ label="Mention"
+ variant="ghost"
+ size="sm"
+ icon={AtSignIcon}
+ isIconOnly
+ onClick={() => {
+ inputRef.current?.focus();
+ inputRef.current?.insertText('@');
+ }}
+ />
+ <XDSButton
+ label="Attach"
+ variant="ghost"
+ size="sm"
+ icon={PaperclipIcon}
+ isIconOnly
+ onClick={() =>
+ setFiles(prev => [...prev, `file-${prev.length + 1}.tsx`])
+ }
+ />
+ </>
+ }
+ headerContext={
+ <>
+ <XDSProgressBar
+ ref={contextTooltip.ref}
+ aria-describedby={contextTooltip.describedBy}
+ label="Context"
+ value={12}
+ variant="neutral"
+ isLabelHidden
+ style={{marginInlineEnd: 8}}
+ />
+ {contextTooltip.renderTooltip('3k / 100k tokens used')}
+ </>
+ }
+ input={
+ <XDSChatComposerInput
+ ref={inputRef}
+ triggers={triggers}
+ placeholder="Ask about the codebase..."
+ />
+ }
+ footerActions={
+ <XDSButton label="Claude Opus" variant="ghost" size="md" />
+ }
+ sendActions={
+ <XDSButton
+ label="Microphone"
+ variant="ghost"
+ size="md"
+ icon={MicIcon}
+ isIconOnly
+ />
+ }
+ />
+ );
+
return (
- <>
- <div
- style={{
- maxWidth: 800,
- margin: '0 auto',
- paddingBottom: 120,
- }}>
+ <div style={{height: '100vh', display: 'flex', flexDirection: 'column'}}>
+ <XDSChatLayout composer={composerEl}>
<XDSChatMessageList>
{messages.map(msg => {
if (msg.role === 'system') {
@@ -401,9 +483,9 @@ export const FullAIChat: StoryObj = {
</XDSChatComposerAttachments>
)}
<XDSChatMessageBubble>
- <XDSChatMessageTokenizedText tokens={msg.tokens}>
+ <XDSChatTokenizedText tokens={mentionTokens}>
{msg.text}
- </XDSChatMessageTokenizedText>
+ </XDSChatTokenizedText>
</XDSChatMessageBubble>
</XDSChatMessage>
);
@@ -420,117 +502,241 @@ export const FullAIChat: StoryObj = {
);
})}
</XDSChatMessageList>
- </div>
-
- {/* Frosted glass layer — sits behind the composer */}
- <div
- style={{
- position: 'fixed',
- bottom: 0,
- left: 0,
- right: 0,
- height: 120,
- pointerEvents: 'none',
- backdropFilter: 'blur(12px)',
- WebkitBackdropFilter: 'blur(12px)',
- maskImage: 'linear-gradient(to bottom, transparent, black 48px)',
- WebkitMaskImage:
- 'linear-gradient(to bottom, transparent, black 48px)',
- }}
- />
- {/* Composer dock */}
- <div
- style={{
- position: 'fixed',
- bottom: 0,
- left: 0,
- right: 0,
- padding: '0 16px 12px',
- }}>
- <div style={{maxWidth: 800, margin: '0 auto'}}>
- <XDSChatComposer
- onSubmit={handleSubmit}
- onStop={handleStop}
- isStreaming={isStreaming}
- attachments={
- files.length > 0 ? (
- <XDSChatComposerAttachments>
- {files.map(f => (
- <XDSToken
- key={f}
- label={f}
- onRemove={() =>
- setFiles(prev => prev.filter(x => x !== f))
- }
- />
- ))}
- </XDSChatComposerAttachments>
- ) : undefined
- }
- headerActions={
- <>
- <XDSButton
- label="Mention"
- variant="ghost"
- size="sm"
- icon={AtSignIcon}
- isIconOnly
- onClick={() => {
- inputRef.current?.focus();
- inputRef.current?.insertText('@');
- }}
- />
- <XDSButton
- label="Attach"
- variant="ghost"
- size="sm"
- icon={PaperclipIcon}
- isIconOnly
- onClick={() =>
- setFiles(prev => [...prev, `file-${prev.length + 1}.tsx`])
- }
- />
- </>
- }
- headerContext={
- <>
- <div
- ref={contextTooltip.ref}
- aria-describedby={contextTooltip.describedBy}
- style={{paddingInlineEnd: 8}}>
- <XDSProgressBar
- label="Context"
- value={12}
- variant="neutral"
- isLabelHidden
- />
- </div>
- {contextTooltip.renderTooltip('3k / 100k tokens used')}
- </>
- }
- input={
- <XDSChatComposerInput
- ref={inputRef}
- triggers={triggers}
- placeholder="Ask about the codebase..."
+ </XDSChatLayout>
+ </div>
+ );
+ },
+};
+
+/** Panel view — same full features in a narrow sidebar container */
+export const PanelView: StoryObj = {
+ name: 'Panel View',
+ render: () => {
+ const [messages, setMessages] = useState<Message[]>(SEED_MESSAGES);
+ const [files, setFiles] = useState<string[]>([]);
+ const [isStreaming, setIsStreaming] = useState(false);
+ const streamRef = useRef<ReturnType<typeof setInterval>>(undefined);
+ const inputRef = useRef<XDSChatComposerInputHandle>(null);
+
+ const mentionTokens = CONTACTS.map(c => ({
+ value: `@${c.id}`,
+ label: `@${c.label}`,
+ variant: 'blue' as const,
+ }));
+
+ const triggers: XDSChatComposerTrigger[] = [
+ {
+ character: '@',
+ searchSource: createStaticSource(CONTACTS),
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: `@${item.label}`,
+ variant: 'blue' as const,
+ }),
+ },
+ {
+ character: '/',
+ searchSource: createStaticSource(COMMANDS),
+ onSelect: item => `/${item.label} `,
+ },
+ ];
+
+ const streamResponse = useCallback(
+ (introText: string, resultText: string) => {
+ const msgId = Date.now();
+ setIsStreaming(true);
+
+ setMessages(prev => [
+ ...prev,
+ {id: msgId, role: 'assistant', text: '', isStreaming: true},
+ ]);
+
+ let i = 0;
+ const fullText = introText + '\n\n' + resultText;
+ streamRef.current = setInterval(() => {
+ i += 3 + Math.floor(Math.random() * 5);
+ if (i >= fullText.length) {
+ clearInterval(streamRef.current);
+ setMessages(prev =>
+ prev.map(m =>
+ m.id === msgId ? {...m, text: fullText, isStreaming: false} : m,
+ ),
+ );
+ setIsStreaming(false);
+ return;
+ }
+ setMessages(prev =>
+ prev.map(m =>
+ m.id === msgId ? {...m, text: fullText.slice(0, i)} : m,
+ ),
+ );
+ }, 30);
+ },
+ [],
+ );
+
+ const handleSubmit = useCallback(
+ (value: string) => {
+ setMessages(prev => [
+ ...prev,
+ {
+ id: Date.now(),
+ role: 'user',
+ text: value,
+ files: files.length ? [...files] : undefined,
+ },
+ ]);
+ setFiles([]);
+ setTimeout(() => {
+ streamResponse(
+ 'Checking the component now.',
+ 'Found the issue — the border radius was hardcoded. Replaced with the theme token.',
+ );
+ }, 800);
+ },
+ [files, streamResponse],
+ );
+
+ const handleStop = useCallback(() => {
+ clearInterval(streamRef.current);
+ setIsStreaming(false);
+ setMessages(prev =>
+ prev.map(m =>
+ m.role === 'assistant' && m.isStreaming
+ ? {...m, isStreaming: false}
+ : m,
+ ),
+ );
+ }, []);
+
+ const composerEl = (
+ <XDSChatComposer
+ onSubmit={handleSubmit}
+ onStop={handleStop}
+ isStreaming={isStreaming}
+ attachments={
+ files.length > 0 ? (
+ <XDSChatComposerAttachments>
+ {files.map(f => (
+ <XDSToken
+ key={f}
+ label={f}
+ onRemove={() => setFiles(prev => prev.filter(x => x !== f))}
/>
+ ))}
+ </XDSChatComposerAttachments>
+ ) : undefined
+ }
+ headerActions={
+ <>
+ <XDSButton
+ label="Mention"
+ variant="ghost"
+ size="sm"
+ icon={AtSignIcon}
+ isIconOnly
+ onClick={() => {
+ inputRef.current?.focus();
+ inputRef.current?.insertText('@');
+ }}
+ />
+ <XDSButton
+ label="Attach"
+ variant="ghost"
+ size="sm"
+ icon={PaperclipIcon}
+ isIconOnly
+ onClick={() =>
+ setFiles(prev => [...prev, `file-${prev.length + 1}.tsx`])
}
- footerActions={
- <XDSButton label="Claude Opus" variant="ghost" size="md" />
+ />
+ </>
+ }
+ input={
+ <XDSChatComposerInput
+ ref={inputRef}
+ triggers={triggers}
+ placeholder="Ask something..."
+ />
+ }
+ />
+ );
+
+ return (
+ <div
+ style={{
+ width: 400,
+ height: 600,
+ border: '1px solid #ccc',
+ borderRadius: 8,
+ overflow: 'hidden',
+ }}>
+ <XDSChatLayout composer={composerEl}>
+ <XDSChatMessageList>
+ {messages.map(msg => {
+ if (msg.role === 'system') {
+ return (
+ <XDSChatSystemMessage key={msg.id} variant="divider">
+ {msg.text}
+ </XDSChatSystemMessage>
+ );
}
- sendActions={
- <XDSButton
- label="Microphone"
- variant="ghost"
- size="md"
- icon={MicIcon}
- isIconOnly
- />
+ if (msg.role === 'user') {
+ return (
+ <XDSChatMessage key={msg.id} sender="user">
+ {msg.files && (
+ <XDSChatComposerAttachments>
+ {msg.files.map(f => (
+ <XDSToken key={f} label={f} />
+ ))}
+ </XDSChatComposerAttachments>
+ )}
+ <XDSChatMessageBubble>
+ <XDSChatTokenizedText tokens={mentionTokens}>
+ {msg.text}
+ </XDSChatTokenizedText>
+ </XDSChatMessageBubble>
+ </XDSChatMessage>
+ );
}
- />
- </div>
- </div>
- </>
+ return (
+ <XDSChatMessage key={msg.id} sender="assistant">
+ {msg.text && (
+ <XDSMarkdown density="compact">{msg.text}</XDSMarkdown>
+ )}
+ {msg.toolCalls && msg.toolCalls.length > 0 && (
+ <XDSChatToolCalls calls={msg.toolCalls ?? []} />
+ )}
+ </XDSChatMessage>
+ );
+ })}
+ </XDSChatMessageList>
+ </XDSChatLayout>
+ </div>
);
},
};
+
+/** Empty state using XDSEmptyState */
+export const WithEmptyState: StoryObj = {
+ name: 'Empty State',
+ render: () => (
+ <div style={{height: '100vh', display: 'flex', flexDirection: 'column'}}>
+ <XDSChatLayout
+ composer={
+ <XDSChatComposer
+ onSubmit={() => {}}
+ placeholder="Start a conversation…"
+ />
+ }
+ emptyState={
+ <XDSEmptyState
+ title="No messages yet"
+ description="Start a conversation by typing below."
+ />
+ }>
+ {[]}
+ </XDSChatLayout>
+ </div>
+ ),
+};
diff --git a/apps/storybook/stories/ChatTokenizedText.stories.tsx b/apps/storybook/stories/ChatTokenizedText.stories.tsx
index 3e135aebf4..bb2d1b103f 100644
--- a/apps/storybook/stories/ChatTokenizedText.stories.tsx
+++ b/apps/storybook/stories/ChatTokenizedText.stories.tsx
@@ -1,10 +1,10 @@
import type {Meta, StoryObj} from '@storybook/react';
-import {XDSChatMessageTokenizedText} from '@xds/core/Chat';
+import {XDSChatTokenizedText} from '@xds/core/Chat';
import {XDSChatMessage, XDSChatMessageBubble} from '@xds/core/Chat';
-const meta: Meta<typeof XDSChatMessageTokenizedText> = {
- title: 'Chat/XDSChatMessageTokenizedText',
- component: XDSChatMessageTokenizedText,
+const meta: Meta<typeof XDSChatTokenizedText> = {
+ title: 'Chat/XDSChatTokenizedText',
+ component: XDSChatTokenizedText,
tags: ['autodocs'],
parameters: {layout: 'centered'},
decorators: [
@@ -17,7 +17,7 @@ const meta: Meta<typeof XDSChatMessageTokenizedText> = {
};
export default meta;
-type Story = StoryObj<typeof XDSChatMessageTokenizedText>;
+type Story = StoryObj<typeof XDSChatTokenizedText>;
const mentionTokens = [
{value: '@cindy', label: '@Cindy Zhang', variant: 'blue' as const},
@@ -30,9 +30,9 @@ export const SingleToken: Story = {
render: () => (
<XDSChatMessage sender="user">
<XDSChatMessageBubble>
- <XDSChatMessageTokenizedText tokens={mentionTokens}>
+ <XDSChatTokenizedText tokens={mentionTokens}>
Hey @cindy can you review this?
- </XDSChatMessageTokenizedText>
+ </XDSChatTokenizedText>
</XDSChatMessageBubble>
</XDSChatMessage>
),
@@ -43,9 +43,9 @@ export const MultipleTokens: Story = {
render: () => (
<XDSChatMessage sender="user">
<XDSChatMessageBubble>
- <XDSChatMessageTokenizedText tokens={mentionTokens}>
+ <XDSChatTokenizedText tokens={mentionTokens}>
@cindy and @alex can @navi help with the review?
- </XDSChatMessageTokenizedText>
+ </XDSChatTokenizedText>
</XDSChatMessageBubble>
</XDSChatMessage>
),
@@ -56,9 +56,9 @@ export const PlainText: Story = {
render: () => (
<XDSChatMessage sender="user">
<XDSChatMessageBubble>
- <XDSChatMessageTokenizedText>
+ <XDSChatTokenizedText>
Just a regular message with no mentions.
- </XDSChatMessageTokenizedText>
+ </XDSChatTokenizedText>
</XDSChatMessageBubble>
</XDSChatMessage>
),
@@ -69,14 +69,14 @@ export const MixedVariants: Story = {
render: () => (
<XDSChatMessage sender="user">
<XDSChatMessageBubble>
- <XDSChatMessageTokenizedText
+ <XDSChatTokenizedText
tokens={[
{value: '@cindy', label: '@Cindy', variant: 'blue'},
{value: '#bug', label: '#bug', variant: 'red'},
{value: '#feat', label: '#feature', variant: 'green'},
]}>
@cindy filed #bug and #feat for the sprint
- </XDSChatMessageTokenizedText>
+ </XDSChatTokenizedText>
</XDSChatMessageBubble>
</XDSChatMessage>
),
@@ -87,9 +87,9 @@ export const TokensAtEdges: Story = {
render: () => (
<XDSChatMessage sender="user">
<XDSChatMessageBubble>
- <XDSChatMessageTokenizedText tokens={mentionTokens}>
+ <XDSChatTokenizedText tokens={mentionTokens}>
@cindy this is for @navi
- </XDSChatMessageTokenizedText>
+ </XDSChatTokenizedText>
</XDSChatMessageBubble>
</XDSChatMessage>
),
diff --git a/apps/storybook/stories/ProgressBar.stories.tsx b/apps/storybook/stories/ProgressBar.stories.tsx
index 8828e326ed..cca5291ebd 100644
--- a/apps/storybook/stories/ProgressBar.stories.tsx
+++ b/apps/storybook/stories/ProgressBar.stories.tsx
@@ -98,6 +98,12 @@ export const Variants: Story = {
variant="negative"
hasValueLabel
/>
+ <XDSProgressBar
+ value={35}
+ label="Neutral"
+ variant="neutral"
+ hasValueLabel
+ />
</div>
),
};
@@ -186,6 +192,7 @@ export const IndeterminateVariants: Story = {
<XDSProgressBar isIndeterminate label="Positive" variant="positive" />
<XDSProgressBar isIndeterminate label="Warning" variant="warning" />
<XDSProgressBar isIndeterminate label="Negative" variant="negative" />
+ <XDSProgressBar isIndeterminate label="Neutral" variant="neutral" />
</div>
),
};
diff --git a/packages/core/src/Chat/Chat.doc.mjs b/packages/core/src/Chat/Chat.doc.mjs
index 41a939d421..563829af43 100644
--- a/packages/core/src/Chat/Chat.doc.mjs
+++ b/packages/core/src/Chat/Chat.doc.mjs
@@ -19,7 +19,7 @@ export const docs = {
'Composer layout shell with named semantic slots',
'ContentEditable input with @ mention and / command trigger menus',
'Imperative handle on ComposerInput for programmatic token/text insertion',
- 'Tokenized text rendering in message bubbles via XDSChatMessageTokenizedText',
+ 'Tokenized text rendering in message bubbles via XDSChatTokenizedText',
'XDSSearchSource integration — reuses Typeahead search sources',
'Concentric radius — inner elements follow outer shell curvature',
'Themeable via --composer-radius and --composer-padding CSS vars',
@@ -62,11 +62,9 @@ export const docs = {
components: [
{
name: 'XDSChatMessageList',
- description: 'Scrollable message container with auto-scroll and infinite scroll support.',
+ description: 'Presentational message container with density context and infinite scroll support. Auto-scroll is owned by XDSChatLayout.',
props: [
{name: 'children', type: 'ReactNode', description: 'Message elements — typically XDSChatMessage or XDSChatSystemMessage.', required: true},
- {name: 'hasAutoScroll', type: 'boolean', description: 'Enables auto-scroll to bottom on new content when near the bottom.', default: 'true'},
- {name: 'scrollThreshold', type: 'number', description: 'Distance from bottom (px) within which new content triggers auto-scroll.', default: '50'},
{name: 'emptyState', type: 'ReactNode', description: 'Content shown when the list has no messages.'},
{name: 'onScrollToTopAction', type: '() => Promise<void>', description: 'Async action fired when user scrolls to top. Use for loading older messages.'},
{name: 'density', type: "'compact' | 'balanced' | 'spacious'", description: 'Visual density — flows to child messages via context.', default: "'balanced'"},
@@ -180,22 +178,41 @@ export const docs = {
],
},
{
- name: 'XDSChatMessageTokenizedText',
+ name: 'XDSChatTokenizedText',
description: 'Renders text with token patterns replaced by inline XDSBadge components. Use inside XDSChatMessageBubble to display @mentions or other tokens as styled badges.',
props: [
{name: 'children', type: 'string', description: 'The message text containing token patterns.', required: true},
{name: 'tokens', type: 'XDSChatMessageTokenConfig[]', description: 'Token definitions. Each has pattern (string to match), label (display text), and optional variant.'},
],
examples: [
- {label: 'With mentions', code: `<XDSChatMessageBubble>\n <XDSChatMessageTokenizedText\n tokens={[{pattern: '@cindy', label: '@Cindy Zhang', variant: 'blue'}]}\n >\n Hey @cindy, can you review this?\n </XDSChatMessageTokenizedText>\n</XDSChatMessageBubble>`},
+ {label: 'With mentions', code: `<XDSChatMessageBubble>\n <XDSChatTokenizedText\n tokens={[{pattern: '@cindy', label: '@Cindy Zhang', variant: 'blue'}]}\n >\n Hey @cindy, can you review this?\n </XDSChatTokenizedText>\n</XDSChatMessageBubble>`},
],
},
],
usage: {
- summary: 'Chat components for building AI chat interfaces, including message lists, message bubbles, and a composer.',
+ summary: 'Chat components for building AI chat interfaces, including message lists, message bubbles, a composer, and a layout shell.',
},
};
+// Append XDSChatLayout to all doc variants
+const chatLayoutComponent = {
+ name: 'XDSChatLayout',
+ description: 'Layout shell for full chat interfaces. Messages flow in normal page flow, composer is fixed to the bottom with a frosted glass dock. Adapts spacing via container width observation. By default the layout root is the scroll container; pass scrollRef to delegate scrolling to a parent element or the document body.',
+ props: [
+ {name: 'children', type: 'ReactNode', description: 'Message content — flows naturally in the page, scrolls with the page.', required: true},
+ {name: 'composer', type: 'ReactNode', description: 'Composer element fixed to the bottom with frosted glass dock.', required: true},
+ {name: 'emptyState', type: 'ReactNode', description: 'Content shown when children is empty.'},
+ {name: 'scrollRef', type: 'React.RefObject<HTMLElement | null>', description: 'External scroll container ref. When provided, auto-scroll and scroll-to-bottom target this element instead of the layout root. Use when the chat is embedded in a page where a parent element or the document body scrolls.'},
+ {name: 'hasAutoScroll', type: 'boolean', description: 'Whether auto-scroll behavior is enabled.', default: 'true'},
+ {name: 'newMessagesLabel', type: 'string', description: 'Label shown in the scroll-to-bottom button when new messages arrive.', default: "'New messages'"},
+ ],
+ examples: [
+ {label: 'Basic (self-scrolling)', code: `<XDSChatLayout composer={<XDSChatComposer onSubmit={handleSubmit} />}>\n {messages.map(msg => <XDSChatMessage key={msg.id} {...msg} />)}\n</XDSChatLayout>`},
+ {label: 'Page body scrolling', code: `const scrollRef = useRef(document.documentElement);\n<XDSChatLayout scrollRef={scrollRef} composer={<XDSChatComposer onSubmit={handleSubmit} />}>\n {messages.map(msg => <XDSChatMessage key={msg.id} {...msg} />)}\n</XDSChatLayout>`},
+ ],
+};
+docs.components.push(chatLayoutComponent);
+
/** @type {import('../docs-types').TranslationDoc} */
export const docsZh = {
description:
@@ -214,7 +231,7 @@ export const docsZh = {
'编写器布局外壳,具有命名语义插槽',
'ContentEditable 输入框,支持 @ 提及和 / 命令触发菜单',
'ComposerInput 命令式句柄,支持编程式插入标记/文本',
- '通过 XDSChatMessageTokenizedText 在消息气泡中渲染标记文本',
+ '通过 XDSChatTokenizedText 在消息气泡中渲染标记文本',
'XDSSearchSource 集成 — 复用 Typeahead 搜索源',
'同心圆角 — 内部元素跟随外部外壳曲率',
'通过 --composer-radius 和 --composer-padding CSS 变量实现主题化',
@@ -222,11 +239,9 @@ export const docsZh = {
components: [
{
name: 'XDSChatMessageList',
- description: '可滚动的消息容器,支持自动滚动和无限滚动。',
+ description: '消息展示容器,支持密度上下文和无限滚动。自动滚动由 XDSChatLayout 管理。',
propDescriptions: {
children: '消息元素,通常是 XDSChatMessage 或 XDSChatSystemMessage。',
- hasAutoScroll: '在接近底部时,新内容触发自动滚动到底部。',
- scrollThreshold: '距底部的距离(像素),在此范围内新内容触发自动滚动。',
emptyState: '列表无消息时显示的内容。',
onScrollToTopAction: '用户滚动到顶部时触发的异步操作。用于加载更早的消息。',
density: '视觉密度,通过上下文传递给子消息。',
@@ -315,13 +330,23 @@ export const docsZh = {
},
},
{
- name: 'XDSChatMessageTokenizedText',
+name: 'XDSChatTokenizedText',
description: '渲染带有标记模式的文本,将匹配的模式替换为内联 XDSBadge 组件。在 XDSChatMessageBubble 内使用,以徽章样式显示 @提及或其他标记。',
propDescriptions: {
children: '包含标记模式的消息文本。',
tokens: '标记定义。每个包含 pattern(匹配字符串)、label(显示文本)和可选 variant。',
},
},
+ {
+ name: 'XDSChatLayout',
+ description: '完整聊天界面的布局外壳。消息在页面中自然流动,编写器固定在底部,带有毛玻璃效果。默认布局根元素为滚动容器;传入 scrollRef 可将滚动委托给父元素或文档主体。',
+ propDescriptions: {
+ children: '消息内容,在页面中自然流动,随页面滚动。',
+ composer: '固定在底部的编写器元素,带有毛玻璃底座。',
+ emptyState: '子元素为空时显示的内容。',
+ scrollRef: '外部滚动容器引用。提供时,自动滚动和滚动到底部将目标指向此元素。',
+ },
+ },
],
};
@@ -342,7 +367,7 @@ export const docsDense = {
'composer layout shell w/ named semantic slots',
'ContentEditable input w/ @ mention + / command trigger menus',
'imperative handle on ComposerInput for programmatic token/text insert',
- 'tokenized text rendering in msg bubbles via XDSChatMessageTokenizedText',
+ 'tokenized text rendering in msg bubbles via XDSChatTokenizedText',
'XDSSearchSource integration; reuses Typeahead search sources',
'concentric radius; inner elements follow outer shell curvature',
'themeable via --composer-radius + --composer-padding CSS vars',
@@ -350,11 +375,9 @@ export const docsDense = {
components: [
{
name: 'XDSChatMessageList',
- description: 'scrollable msg container w/ auto-scroll + infinite scroll',
+ description: 'presentational msg container w/ density context + infinite scroll; auto-scroll owned by XDSChatLayout',
propDescriptions: {
children: 'msg elements (XDSChatMessage or XDSChatSystemMessage)',
- hasAutoScroll: 'auto-scroll to bottom on new content near bottom',
- scrollThreshold: 'px from bottom to trigger auto-scroll',
emptyState: 'content when no msgs',
onScrollToTopAction: 'async action at scroll top; load older msgs',
density: 'visual density; flows to children via context',
@@ -443,12 +466,22 @@ export const docsDense = {
},
},
{
- name: 'XDSChatMessageTokenizedText',
+name: 'XDSChatTokenizedText',
description: 'renders text w/ token patterns replaced by inline badges; use in bubble for @mentions',
propDescriptions: {
children: 'msg text w/ token patterns',
tokens: 'token defs: pattern+label+variant',
},
},
+ {
+ name: 'XDSChatLayout',
+ description: 'layout shell for full chat; msgs in page flow, composer fixed bottom w/ frosted glass dock; scrollRef delegates scrolling to parent/body',
+ propDescriptions: {
+ children: 'msg content; flows in page, scrolls w/ page',
+ composer: 'composer element; fixed bottom w/ frosted glass',
+ emptyState: 'content when children empty',
+ scrollRef: 'external scroll container ref; targets parent/body instead of layout root',
+ },
+ },
],
};
diff --git a/packages/core/src/Chat/XDSChatComposer.tsx b/packages/core/src/Chat/XDSChatComposer.tsx
index 3e2bf1ca4b..87d858a1bd 100644
--- a/packages/core/src/Chat/XDSChatComposer.tsx
+++ b/packages/core/src/Chat/XDSChatComposer.tsx
@@ -161,7 +161,6 @@ const styles = stylex.create({
alignItems: 'center',
gap: spacingVars['--spacing-2'],
marginInlineStart: 'auto',
- minWidth: '80px',
fontSize: typeScaleVars['--text-supporting-size'],
lineHeight: typeScaleVars['--text-supporting-leading'],
color: colorVars['--color-text-secondary'],
diff --git a/packages/core/src/Chat/XDSChatComposerInput.test.tsx b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
index 5ab7d74a1a..80ee8afbd3 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
@@ -247,6 +247,104 @@ describe('XDSChatComposerInput', () => {
});
});
+ describe('token backspace handling', () => {
+ it('removes token and trailing NBSP on backspace', () => {
+ let handle: XDSChatComposerInputHandle | null = null;
+ const onChange = vi.fn();
+ render(
+ <XDSChatComposerInput
+ ref={h => {
+ handle = h;
+ }}
+ onChange={onChange}
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+
+ // Focus and set a collapsed selection so insertToken has a valid range
+ textbox.focus();
+ const sel = window.getSelection()!;
+ const range = document.createRange();
+ range.selectNodeContents(textbox);
+ range.collapse(false);
+ sel.removeAllRanges();
+ sel.addRange(range);
+
+ // Insert a token programmatically
+ handle!.insertToken({
+ value: '@sam',
+ label: '@Sam Rivera',
+ variant: 'blue' as const,
+ });
+ fireEvent.input(textbox);
+
+ // The DOM should have a token span + trailing NBSP
+ const tokenSpan = textbox.querySelector('[data-xds-token]');
+ expect(tokenSpan).toBeInTheDocument();
+
+ const nbsp = tokenSpan!.nextSibling;
+ expect(nbsp).toBeTruthy();
+ expect(nbsp!.textContent).toBe('\u00A0');
+
+ // Position cursor at end of NBSP text node
+ const r2 = document.createRange();
+ r2.setStart(nbsp!, 1);
+ r2.collapse(true);
+ sel.removeAllRanges();
+ sel.addRange(r2);
+
+ // Fire backspace
+ fireEvent.keyDown(textbox, {key: 'Backspace'});
+
+ // Both the NBSP and the token should be removed
+ expect(textbox.querySelector('[data-xds-token]')).toBeNull();
+ });
+
+ it('serializes to empty after token backspace', () => {
+ let handle: XDSChatComposerInputHandle | null = null;
+ const onChange = vi.fn();
+ render(
+ <XDSChatComposerInput
+ ref={h => {
+ handle = h;
+ }}
+ onChange={onChange}
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+
+ // Focus and set selection
+ textbox.focus();
+ const sel = window.getSelection()!;
+ const range = document.createRange();
+ range.selectNodeContents(textbox);
+ range.collapse(false);
+ sel.removeAllRanges();
+ sel.addRange(range);
+
+ handle!.insertToken({
+ value: '@sam',
+ label: '@Sam Rivera',
+ variant: 'blue' as const,
+ });
+ fireEvent.input(textbox);
+
+ const tokenSpan = textbox.querySelector('[data-xds-token]')!;
+ const nbsp = tokenSpan.nextSibling!;
+
+ // Position cursor in the NBSP
+ const r2 = document.createRange();
+ r2.setStart(nbsp, 1);
+ r2.collapse(true);
+ sel.removeAllRanges();
+ sel.addRange(r2);
+
+ // Backspace should remove token + NBSP and fire onChange
+ fireEvent.keyDown(textbox, {key: 'Backspace'});
+ expect(onChange).toHaveBeenLastCalledWith('');
+ });
+ });
+
describe('xds class names', () => {
it('has xds-chat-composer-input class', () => {
const {container} = render(<XDSChatComposerInput />);
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsx
index 128d6a9b4d..5e1af4511b 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx
@@ -410,6 +410,47 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
return;
}
+ // Handle Backspace near tokens — prevent browser from creating
+ // stray <br> elements or moving the cursor unexpectedly.
+ if (e.key === 'Backspace') {
+ const selection = window.getSelection();
+ if (selection && selection.isCollapsed && selection.rangeCount > 0) {
+ const range = selection.getRangeAt(0);
+ const {startContainer, startOffset} = range;
+
+ // Case 1: Cursor is in a text node right after a token.
+ // If the text node is just the trailing NBSP, remove it
+ // and place cursor after the token.
+ if (
+ startContainer.nodeType === Node.TEXT_NODE &&
+ startOffset === 0 &&
+ startContainer.previousSibling instanceof HTMLElement &&
+ startContainer.previousSibling.hasAttribute('data-xds-token')
+ ) {
+ // Cursor is at start of text node right after a token — let
+ // the browser handle it normally (it will select/delete the token)
+ } else if (
+ startContainer.nodeType === Node.TEXT_NODE &&
+ startContainer.textContent === ' ' &&
+ startOffset <= 1 &&
+ startContainer.previousSibling instanceof HTMLElement &&
+ startContainer.previousSibling.hasAttribute('data-xds-token')
+ ) {
+ // Cursor is in or after the trailing NBSP — remove the NBSP
+ // and the token in one action
+ e.preventDefault();
+ const tokenSpan = startContainer.previousSibling;
+ const parent = startContainer.parentNode;
+ if (parent) {
+ parent.removeChild(startContainer);
+ parent.removeChild(tokenSpan);
+ }
+ emitChange();
+ return;
+ }
+ }
+ }
+
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!editableRef.current) return;
diff --git a/packages/core/src/Chat/XDSChatContext.tsx b/packages/core/src/Chat/XDSChatContext.tsx
index 223296f536..40df650091 100644
--- a/packages/core/src/Chat/XDSChatContext.tsx
+++ b/packages/core/src/Chat/XDSChatContext.tsx
@@ -54,3 +54,21 @@ export const XDSChatComposerContext =
export function useXDSChatComposerContext(): XDSChatComposerContextValue | null {
return useContext(XDSChatComposerContext);
}
+
+// =============================================================================
+// Layout context — shared between XDSChatLayout and XDSChatMessageList
+// =============================================================================
+
+export interface XDSChatLayoutContextValue {
+ /** Ref to the scrollable container element that wraps the message area. */
+ scrollContainerRef: React.RefObject<HTMLElement | null>;
+ /** Callback ref for the message list content element — layout observes it for size changes. */
+ contentRef: (el: HTMLElement | null) => void;
+}
+
+export const XDSChatLayoutContext =
+ createContext<XDSChatLayoutContextValue | null>(null);
+
+export function useXDSChatLayoutContext(): XDSChatLayoutContextValue | null {
+ return useContext(XDSChatLayoutContext);
+}
diff --git a/packages/core/src/Chat/XDSChatLayout.test.tsx b/packages/core/src/Chat/XDSChatLayout.test.tsx
new file mode 100644
index 0000000000..11cd46884e
--- /dev/null
+++ b/packages/core/src/Chat/XDSChatLayout.test.tsx
@@ -0,0 +1,101 @@
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {XDSChatLayout} from './XDSChatLayout';
+
+class FakeResizeObserver {
+ callback: ResizeObserverCallback;
+ constructor(cb: ResizeObserverCallback) {
+ this.callback = cb;
+ }
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+}
+
+beforeEach(() => {
+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);
+});
+
+describe('XDSChatLayout', () => {
+ it('renders children', () => {
+ render(
+ <XDSChatLayout composer={<div>composer</div>}>
+ <div>Hello message</div>
+ </XDSChatLayout>,
+ );
+ expect(screen.getByText('Hello message')).toBeTruthy();
+ });
+
+ it('renders composer in fixed dock', () => {
+ render(
+ <XDSChatLayout composer={<div data-testid="composer">Compose</div>}>
+ <div>msg</div>
+ </XDSChatLayout>,
+ );
+ const composer = screen.getByTestId('composer');
+ expect(composer).toBeTruthy();
+ // The dock (parent of the composer's wrapper) should have position: fixed
+ const dock = composer.parentElement?.parentElement;
+ expect(dock).toBeTruthy();
+ const dockStyle = window.getComputedStyle(dock!);
+ // StyleX applies classes, so check the element exists in the DOM structure
+ expect(dock?.tagName).toBe('DIV');
+ });
+
+ it('renders empty state when children is empty', () => {
+ render(
+ <XDSChatLayout
+ composer={<div>composer</div>}
+ emptyState={<div>No messages yet</div>}>
+ {[]}
+ </XDSChatLayout>,
+ );
+ expect(screen.getByText('No messages yet')).toBeTruthy();
+ });
+
+ it('does not render empty state when children exist', () => {
+ render(
+ <XDSChatLayout
+ composer={<div>composer</div>}
+ emptyState={<div>No messages yet</div>}>
+ <div>A message</div>
+ </XDSChatLayout>,
+ );
+ expect(screen.getByText('A message')).toBeTruthy();
+ expect(screen.queryByText('No messages yet')).toBeNull();
+ });
+
+ it('has container-type on root', () => {
+ render(
+ <XDSChatLayout
+ composer={<div>composer</div>}
+ data-testid="layout-root">
+ <div>msg</div>
+ </XDSChatLayout>,
+ );
+ const root = screen.getByTestId('layout-root');
+ expect(root).toBeTruthy();
+ expect(root.className).toContain('xds-chat-layout');
+ });
+
+ it('applies data-testid', () => {
+ render(
+ <XDSChatLayout
+ composer={<div>composer</div>}
+ data-testid="my-layout">
+ <div>msg</div>
+ </XDSChatLayout>,
+ );
+ expect(screen.getByTestId('my-layout')).toBeTruthy();
+ });
+
+ it('renders scroll-to-bottom button', () => {
+ render(
+ <XDSChatLayout composer={<div>composer</div>}>
+ <div>msg</div>
+ </XDSChatLayout>,
+ );
+ const button = screen.getByRole('button', {name: /Scroll to bottom/});
+ expect(button).toBeTruthy();
+ });
+});
diff --git a/packages/core/src/Chat/XDSChatLayout.tsx b/packages/core/src/Chat/XDSChatLayout.tsx
new file mode 100644
index 0000000000..458264d455
--- /dev/null
+++ b/packages/core/src/Chat/XDSChatLayout.tsx
@@ -0,0 +1,600 @@
+'use client';
+
+/**
+ * @file XDSChatLayout.tsx
+ * @input Uses React, StyleX, theme tokens, useAutoScroll
+ * @output Exports XDSChatLayout component and XDSChatLayoutProps
+ * @position Layout shell for full chat interfaces — messages in page flow, composer fixed to bottom
+ *
+ * Arranges a chat page: messages flow naturally in the page, composer is
+ * fixed to the bottom with a frosted glass backdrop. Owns auto-scroll
+ * behavior and the scroll-to-bottom button. Uses ResizeObserver on the
+ * message content area to detect new content.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Chat/index.ts (exports)
+ * - /apps/storybook/stories/ChatLayout.stories.tsx
+ */
+
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ shadowVars,
+ durationVars,
+ easeVars,
+} from '../theme/tokens.stylex';
+import {xdsClassName, mergeProps} from '../utils';
+import {XDSChatLayoutContext} from './XDSChatContext';
+import {useAutoScroll} from './useAutoScroll';
+import {XDSIcon} from '../Icon';
+import {XDSButton} from '../Button';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+type Density = 'compact' | 'balanced' | 'spacious';
+
+export interface XDSChatLayoutProps {
+ /** Ref forwarded to the root element. */
+ ref?: React.Ref<HTMLDivElement>;
+
+ /**
+ * Message content — flows naturally in the page, scrolls with the page.
+ * Typically XDSChatMessageList with XDSChatMessage children.
+ */
+ children: ReactNode;
+
+ /**
+ * Composer element — fixed to the bottom with a frosted glass dock.
+ * Typically XDSChatComposer.
+ */
+ composer: ReactNode;
+
+ /**
+ * Content shown when children is empty.
+ */
+ emptyState?: ReactNode;
+
+ /**
+ * External scroll container ref. When provided, auto-scroll and
+ * scroll-to-bottom target this element instead of the layout root.
+ *
+ * @example
+ * ```
+ * // Scroll with the page body
+ * const scrollRef = useRef(document.documentElement);
+ * <XDSChatLayout scrollRef={scrollRef} composer={...}>...</XDSChatLayout>
+ * ```
+ *
+ * When omitted, the layout root itself is the scroll container
+ * (`overflow-y: auto`). This is the default for full-page and
+ * panel chat layouts.
+ */
+ scrollRef?: React.RefObject<HTMLElement | null>;
+
+ /**
+ * Whether auto-scroll behavior is enabled.
+ * @default true
+ */
+ hasAutoScroll?: boolean;
+
+ /**
+ * Label shown in the scroll-to-bottom button when new messages arrive.
+ * @default 'New messages'
+ */
+ newMessagesLabel?: string;
+
+ /** StyleX overrides. */
+ xstyle?: StyleXStyles;
+ /** CSS class name(s) appended to the root element. */
+ className?: string;
+ /** Inline styles. */
+ style?: React.CSSProperties;
+ /** Test ID. */
+ 'data-testid'?: string;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ root: {
+ position: 'relative',
+ containerType: 'inline-size',
+ minHeight: 0,
+ flex: 1,
+ },
+ rootScrollable: {
+ overflowY: 'auto',
+ overflowX: 'hidden',
+ },
+
+ // --- Message area ---
+ messageArea: {
+ display: 'flex',
+ flexDirection: 'column',
+ marginInline: 'auto',
+ minHeight: '100%',
+ paddingBlockEnd: spacingVars['--spacing-6'],
+ },
+ messageAreaCompact: {
+ maxWidth: '100%',
+ },
+ messageAreaBalanced: {
+ maxWidth: '100%',
+ },
+ messageAreaSpacious: {
+ maxWidth: 800,
+ paddingInline: spacingVars['--spacing-4'],
+ },
+
+ // --- Empty state ---
+ emptyState: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flex: 1,
+ minHeight: 200,
+ },
+
+ // --- Dock container — holds blur layer + composer as siblings ---
+ dockContainer: {
+ bottom: 0,
+ left: 0,
+ right: 0,
+ zIndex: 0,
+ isolation: 'isolate',
+ pointerEvents: 'none',
+ },
+ dockContainerFixed: {
+ position: 'fixed',
+ },
+ dockContainerSticky: {
+ position: 'sticky',
+ },
+
+ // --- Blur layer (absolute within dock container) ---
+ blurLayer: {
+ position: 'absolute',
+ bottom: 0,
+ left: 0,
+ right: 0,
+ pointerEvents: 'none',
+ backdropFilter: 'blur(12px)',
+ WebkitBackdropFilter: 'blur(12px)',
+ },
+
+ blurLayerCompact: {
+ height: 80,
+ maskImage: 'linear-gradient(to bottom, transparent, black 24px)',
+ WebkitMaskImage: 'linear-gradient(to bottom, transparent, black 24px)',
+ },
+ blurLayerBalanced: {
+ height: 100,
+ maskImage: 'linear-gradient(to bottom, transparent, black 36px)',
+ WebkitMaskImage: 'linear-gradient(to bottom, transparent, black 36px)',
+ },
+ blurLayerSpacious: {
+ height: 120,
+ maskImage: 'linear-gradient(to bottom, transparent, black 48px)',
+ WebkitMaskImage: 'linear-gradient(to bottom, transparent, black 48px)',
+ },
+
+ // --- Composer dock ---
+ dock: {
+ position: 'relative',
+ zIndex: 1,
+ pointerEvents: 'auto',
+ },
+
+ dockCompact: {
+ paddingInline: spacingVars['--spacing-2'],
+ paddingBlockEnd: spacingVars['--spacing-2'],
+ },
+ dockBalanced: {
+ paddingInline: spacingVars['--spacing-3'],
+ paddingBlockEnd: spacingVars['--spacing-3'],
+ },
+ dockSpacious: {
+ paddingInline: spacingVars['--spacing-4'],
+ paddingBlockEnd: spacingVars['--spacing-3'],
+ },
+
+ // --- Dock inner wrapper ---
+ dockInner: {
+ marginInline: 'auto',
+ },
+ dockInnerCompact: {
+ maxWidth: '100%',
+ },
+ dockInnerBalanced: {
+ maxWidth: '100%',
+ },
+ dockInnerSpacious: {
+ maxWidth: 800,
+ },
+
+ // --- Scroll-to-bottom button ---
+ // Wrapper centers the button above the composer inside the dock container.
+ scrollButtonWrapper: {
+ display: 'flex',
+ justifyContent: 'center',
+ paddingBlockEnd: spacingVars['--spacing-3'],
+ },
+ scrollButtonContainer: {
+ pointerEvents: 'auto',
+ contain: 'layout style',
+ overflow: 'hidden',
+ borderRadius: radiusVars['--radius-full'],
+ backgroundColor: colorVars['--color-background-popover'],
+ boxShadow: shadowVars['--shadow-med'],
+ height: '32px',
+ transitionProperty: 'opacity, transform, max-width',
+ transitionTimingFunction: easeVars['--ease-standard'],
+ transitionDuration: durationVars['--duration-fast-max'],
+ },
+ scrollButtonContainerHidden: {
+ opacity: 0,
+ pointerEvents: 'none',
+ maxWidth: '32px',
+ },
+ scrollButtonContainerVisible: {
+ opacity: 1,
+ pointerEvents: 'auto',
+ },
+ scrollButtonCollapsed: {
+ maxWidth: '32px',
+ },
+ scrollButtonExpanded: {
+ maxWidth: '200px',
+ },
+ scrollButton: {
+ [radiusVars['--radius-element'] as string]: radiusVars['--radius-full'],
+ whiteSpace: 'nowrap',
+ paddingInline: spacingVars['--spacing-2'],
+ },
+});
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function getDensity(width: number): Density {
+ if (width < 480) return 'compact';
+ if (width <= 768) return 'balanced';
+ return 'spacious';
+}
+
+function hasVisibleContent(children: ReactNode): boolean {
+ if (children == null || children === false) return false;
+ if (Array.isArray(children) && children.length === 0) return false;
+ return true;
+}
+
+// =============================================================================
+// Sub-components
+// =============================================================================
+
+function ScrollToBottomButton({
+ isScrolledUp,
+ hasNewMessages,
+ label,
+ onClick,
+}: {
+ isScrolledUp: boolean;
+ hasNewMessages: boolean;
+ label: string;
+ onClick: () => void;
+}) {
+ const isVisible = isScrolledUp || hasNewMessages;
+
+ return (
+ <div
+ {...stylex.props(styles.scrollButtonWrapper)}>
+ <div
+ {...stylex.props(
+ styles.scrollButtonContainer,
+ isVisible
+ ? styles.scrollButtonContainerVisible
+ : styles.scrollButtonContainerHidden,
+ hasNewMessages
+ ? styles.scrollButtonExpanded
+ : styles.scrollButtonCollapsed,
+ )}>
+ <XDSButton
+ label={hasNewMessages ? label : 'Scroll to bottom'}
+ aria-label={hasNewMessages ? label : 'Scroll to bottom'}
+ icon={<XDSIcon icon="chevronDown" size="md" />}
+ variant="ghost"
+ size="md"
+ onClick={onClick}
+ xstyle={styles.scrollButton}>
+ {hasNewMessages ? label : undefined}
+ </XDSButton>
+ </div>
+ </div>
+ );
+}
+
+// =============================================================================
+// Component
+// =============================================================================
+
+/**
+ * Layout shell for full chat interfaces.
+ *
+ * Messages flow naturally in the page. The composer is fixed to
+ * the bottom with a frosted glass dock. The layout owns auto-scroll
+ * behavior — it observes the message content area via ResizeObserver
+ * and scrolls to bottom when new content arrives (if the user is
+ * near the bottom). Shows a scroll-to-bottom button when scrolled up.
+ *
+ * @example
+ * ```
+ * <XDSChatLayout
+ * composer={<XDSChatComposer onSubmit={handleSubmit} />}
+ * emptyState={<EmptyState />}
+ * >
+ * <XDSChatMessageList>
+ * {messages.map(msg => <XDSChatMessage key={msg.id} {...msg} />)}
+ * </XDSChatMessageList>
+ * </XDSChatLayout>
+ * ```
+ */
+export function XDSChatLayout({
+ children,
+ composer,
+ emptyState,
+ scrollRef: externalScrollRef,
+ hasAutoScroll = true,
+ newMessagesLabel = 'New messages',
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ ref,
+}: XDSChatLayoutProps) {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const dockRef = useRef<HTMLDivElement>(null);
+ const scrollListenerRef = useRef<(() => void) | null>(null);
+ const contentElRef = useRef<HTMLElement | null>(null);
+ const contentObserverRef = useRef<ResizeObserver | null>(null);
+
+ const scrollContainerRef =
+ externalScrollRef ?? (rootRef as React.RefObject<HTMLElement | null>);
+ const isSelfScrolling = !externalScrollRef;
+
+ const [density, setDensity] = useState<Density>('balanced');
+
+ // --- Auto-scroll ---
+ const {
+ scrollRef,
+ isScrolledUp,
+ hasNewMessages,
+ handleScroll,
+ handleScrollEnd,
+ handleUserScroll,
+ scrollToBottom,
+ dismissNewMessages,
+ onContentChange,
+ scrollToBottomIfLocked,
+ } = useAutoScroll({
+ enabled: hasAutoScroll,
+ scrollContainerRef,
+ });
+
+
+
+ // Single ResizeObserver for both density (root width) and content
+ // changes (new messages). Checks entry.target to dispatch.
+ const lastMessageRef = useRef<Element | null>(null);
+
+ // Density observer — watches root width for breakpoints.
+ useEffect(() => {
+ const root = rootRef.current;
+ if (!root) return;
+ const observer = new ResizeObserver(() => {
+ setDensity(getDensity(root.clientWidth));
+ });
+ observer.observe(root);
+ return () => observer.disconnect();
+ }, []);
+
+ // Content ref callback — observe the message list for height changes.
+ // Two behaviors:
+ // - New message appended (last element changed) → onContentChange
+ // (auto-scrolls if near bottom, shows "new messages" if scrolled up)
+ // - Existing message growing (streaming) → just auto-scroll if near
+ // bottom, but don't flag "new messages"
+ const contentRef = useCallback(
+ (el: HTMLElement | null) => {
+ if (contentObserverRef.current) {
+ contentObserverRef.current.disconnect();
+ contentObserverRef.current = null;
+ }
+ contentElRef.current = el;
+ if (el) {
+ const observer = new ResizeObserver(() => {
+ const messages = el.getElementsByClassName('xds-chat-message');
+ const last =
+ messages.length > 0 ? messages[messages.length - 1] : null;
+ if (last && last !== lastMessageRef.current) {
+ // New message — auto-scroll or show "new messages"
+ lastMessageRef.current = last;
+ onContentChange();
+ } else {
+ // Existing content growing (streaming) — auto-scroll only,
+ // don't flag "new messages"
+ scrollToBottomIfLocked();
+ }
+ });
+ observer.observe(el);
+ contentObserverRef.current = observer;
+ }
+ },
+ [onContentChange, scrollToBottomIfLocked],
+ );
+
+ // --- Layout context ---
+ const layoutContextValue = useMemo(
+ () => ({
+ scrollContainerRef,
+ contentRef,
+ }),
+ [scrollContainerRef, contentRef],
+ );
+
+
+
+ // --- Merge refs ---
+ // Callback ref attaches scroll listener and triggers initial scroll.
+ const setRootRef = useCallback(
+ (el: HTMLDivElement | null) => {
+ // Detach previous listener
+ if (scrollListenerRef.current) {
+ scrollListenerRef.current();
+ scrollListenerRef.current = null;
+ }
+
+ (rootRef as React.MutableRefObject<HTMLDivElement | null>).current = el;
+
+ if (el) {
+ const scrollEl = scrollRef.current;
+ if (scrollEl) {
+ scrollEl.addEventListener('scroll', handleScroll, {passive: true});
+ scrollEl.addEventListener('scrollend', handleScrollEnd);
+ scrollEl.addEventListener('wheel', handleUserScroll, {passive: true});
+ scrollEl.addEventListener('touchstart', handleUserScroll, {passive: true});
+ scrollListenerRef.current = () => {
+ scrollEl.removeEventListener('scroll', handleScroll);
+ scrollEl.removeEventListener('scrollend', handleScrollEnd);
+ scrollEl.removeEventListener('wheel', handleUserScroll);
+ scrollEl.removeEventListener('touchstart', handleUserScroll);
+ };
+ // Defer to next frame so content has laid out
+ requestAnimationFrame(() => scrollToBottom(false));
+ }
+ }
+
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLDivElement | null>).current = el;
+ }
+ },
+ [ref, scrollRef, handleScroll, handleScrollEnd, handleUserScroll, scrollToBottom],
+ );
+
+ // --- Scroll button handler ---
+ const handleButtonClick = useCallback(() => {
+ if (hasNewMessages) {
+ dismissNewMessages();
+ } else {
+ scrollToBottom();
+ }
+ }, [hasNewMessages, dismissNewMessages, scrollToBottom]);
+
+ // --- Derived styles ---
+ const showEmpty = !hasVisibleContent(children);
+
+ const messageAreaStyle =
+ density === 'compact'
+ ? styles.messageAreaCompact
+ : density === 'spacious'
+ ? styles.messageAreaSpacious
+ : styles.messageAreaBalanced;
+
+ const blurLayerStyle =
+ density === 'compact'
+ ? styles.blurLayerCompact
+ : density === 'spacious'
+ ? styles.blurLayerSpacious
+ : styles.blurLayerBalanced;
+
+ const dockStyle =
+ density === 'compact'
+ ? styles.dockCompact
+ : density === 'spacious'
+ ? styles.dockSpacious
+ : styles.dockBalanced;
+
+ const dockInnerStyle =
+ density === 'compact'
+ ? styles.dockInnerCompact
+ : density === 'spacious'
+ ? styles.dockInnerSpacious
+ : styles.dockInnerBalanced;
+
+ return (
+ <XDSChatLayoutContext.Provider value={layoutContextValue}>
+ <div
+ ref={setRootRef}
+ data-testid={testId}
+ data-density={density}
+ {...mergeProps(
+ xdsClassName('chat-layout', {density}),
+ stylex.props(
+ styles.root,
+ isSelfScrolling && styles.rootScrollable,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {/* Message area */}
+ <div
+ {...stylex.props(styles.messageArea, messageAreaStyle)}
+>
+ {showEmpty && emptyState ? (
+ <div {...stylex.props(styles.emptyState)}>{emptyState}</div>
+ ) : (
+ children
+ )}
+ </div>
+
+ {/* Dock container — sticky/fixed, holds blur + scroll button + composer */}
+ <div
+ ref={dockRef}
+ {...stylex.props(
+ styles.dockContainer,
+ isSelfScrolling
+ ? styles.dockContainerSticky
+ : styles.dockContainerFixed,
+ )}>
+ {/* Frosted glass layer — behind composer */}
+ <div {...stylex.props(styles.blurLayer, blurLayerStyle)} />
+
+ {/* Scroll-to-bottom button */}
+ <ScrollToBottomButton
+ isScrolledUp={isScrolledUp}
+ hasNewMessages={hasNewMessages}
+ label={newMessagesLabel}
+ onClick={handleButtonClick}
+ />
+
+ {/* Composer */}
+ <div {...stylex.props(styles.dock, dockStyle)}>
+ <div {...stylex.props(styles.dockInner, dockInnerStyle)}>
+ {composer}
+ </div>
+ </div>
+ </div>
+ </div>
+ </XDSChatLayoutContext.Provider>
+ );
+}
+
+XDSChatLayout.displayName = 'XDSChatLayout';
diff --git a/packages/core/src/Chat/XDSChatMessageList.test.tsx b/packages/core/src/Chat/XDSChatMessageList.test.tsx
index 075a540eef..e7013e3fca 100644
--- a/packages/core/src/Chat/XDSChatMessageList.test.tsx
+++ b/packages/core/src/Chat/XDSChatMessageList.test.tsx
@@ -54,13 +54,4 @@ describe('XDSChatMessageList', () => {
expect(screen.getByTestId('chat-list')).toBeTruthy();
});
- it('has scroll-to-bottom button (hidden by default)', () => {
- render(
- <XDSChatMessageList>
- <div>msg</div>
- </XDSChatMessageList>,
- );
- const button = screen.getByRole('button', {name: /Scroll to bottom/});
- expect(button).toBeTruthy();
- });
});
diff --git a/packages/core/src/Chat/XDSChatMessageList.tsx b/packages/core/src/Chat/XDSChatMessageList.tsx
index b2c9afc31d..1ca5f7d6a6 100644
--- a/packages/core/src/Chat/XDSChatMessageList.tsx
+++ b/packages/core/src/Chat/XDSChatMessageList.tsx
@@ -2,14 +2,17 @@
/**
* @file XDSChatMessageList.tsx
- * @input Uses React, StyleX, XDSChatListContext, XDSIcon, theme tokens, useAutoScroll
+ * @input Uses React, StyleX, XDSChatListContext, theme tokens
* @output Exports XDSChatMessageList component and XDSChatMessageListProps
- * @position Scrollable message container — holds XDSChatMessage children with auto-scroll
+ * @position Presentational message container — holds XDSChatMessage children
*
- * Renders a scrollable container with role="log" for chat message histories.
- * Handles auto-scroll (pins to bottom during streaming), a floating
- * scroll-to-bottom button when scrolled up, and a "New messages" label
- * that expands into the button via width animation when new content arrives.
+ * Renders a container with role="log" for chat message histories.
+ * Handles density context, empty state, a spacer that pushes messages
+ * to the bottom, and an infinite scroll sentinel.
+ *
+ * Auto-scroll and the scroll-to-bottom button are owned by
+ * XDSChatLayout. When used standalone (without a layout), the list
+ * is purely presentational — compose useAutoScroll yourself if needed.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Chat/index.ts (exports)
@@ -26,23 +29,13 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
-import {
- colorVars,
- spacingVars,
- radiusVars,
- durationVars,
- easeVars,
- shadowVars,
-} from '../theme/tokens.stylex';
-import {XDSChatListContext, type XDSChatDensity} from './XDSChatContext';
+import {spacingVars} from '../theme/tokens.stylex';
+import {XDSChatListContext, type XDSChatDensity, useXDSChatLayoutContext} from './XDSChatContext';
import {xdsClassName, mergeProps} from '../utils';
import {XDSSpinner} from '../Spinner';
-import {XDSIcon} from '../Icon';
-import {XDSButton} from '../Button';
-import {useAutoScroll} from './useAutoScroll';
export interface XDSChatMessageListProps {
- /** Ref forwarded to the scrollable container element */
+ /** Ref forwarded to the root element */
ref?: React.Ref<HTMLDivElement>;
/**
@@ -51,35 +44,6 @@ export interface XDSChatMessageListProps {
*/
children: ReactNode;
- /**
- * Whether auto-scroll behavior is enabled.
- * When true (default), the list scrolls to bottom on new content
- * if the user is near the bottom. When false, no auto-scrolling
- * occurs — useful for static/view-only conversation history.
- * @default true
- */
- hasAutoScroll?: boolean;
-
- /**
- * Distance from bottom (in px) within which new content triggers auto-scroll.
- * Only applies when `hasAutoScroll` is true.
- * @default 12
- */
- scrollThreshold?: number;
-
- /**
- * Distance from bottom (in px) beyond which the scroll-to-bottom button appears.
- * @default 100
- */
- scrollUpThreshold?: number;
-
- /**
- * Label shown in the scroll-to-bottom button when new messages arrive.
- * Revealed via a width animation on the button.
- * @default 'New messages'
- */
- newMessagesLabel?: string;
-
/**
* Custom content when the list has no messages.
*/
@@ -116,19 +80,9 @@ export interface XDSChatMessageListProps {
// =============================================================================
const styles = stylex.create({
- outer: {
- position: 'relative',
- display: 'flex',
- flexDirection: 'column',
- flex: 1,
- minHeight: 0,
- },
root: {
display: 'flex',
flexDirection: 'column',
- overflowY: 'auto',
- overflowX: 'hidden',
- overflowAnchor: 'auto',
flex: 1,
minHeight: 0,
},
@@ -162,52 +116,6 @@ const styles = stylex.create({
justifyContent: 'center',
paddingBlock: spacingVars['--spacing-3'],
},
-
- // --- Scroll-to-bottom button ---
- // Container controls dimensions and clips content. The XDSButton inside
- // is always full-size; the container's width transition reveals the label.
- // Opaque popover bg on the container prevents hover tint bleed-through.
- // `contain: layout style` isolates reflow from the scroll area.
- scrollButtonContainer: {
- position: 'absolute',
- bottom: spacingVars['--spacing-3'],
- left: '50%',
- contain: 'layout style',
- overflow: 'hidden',
- borderRadius: radiusVars['--radius-full'],
- backgroundColor: colorVars['--color-background-popover'],
- boxShadow: shadowVars['--shadow-med'],
- height: '32px',
- zIndex: 1,
- transitionProperty: 'opacity, transform, max-width',
- transitionTimingFunction: easeVars['--ease-standard'],
- transitionDuration: durationVars['--duration-fast-max'],
- },
- scrollButtonContainerHidden: {
- opacity: 0,
- pointerEvents: 'none',
- maxWidth: '32px',
- transform: 'translate(-50%, 8px)',
- transitionDelay: '0ms',
- },
- scrollButtonContainerVisible: {
- opacity: 1,
- pointerEvents: 'auto',
- transform: 'translate(-50%, 0)',
- transitionDelay: '150ms',
- },
- scrollButtonCollapsed: {
- maxWidth: '32px',
- },
- scrollButtonExpanded: {
- maxWidth: '200px',
- },
- scrollButton: {
- [radiusVars['--radius-element'] as string]: radiusVars['--radius-full'],
- whiteSpace: 'nowrap',
- paddingInline: spacingVars['--spacing-2'],
- },
-
emptyState: {
display: 'flex',
alignItems: 'center',
@@ -217,71 +125,19 @@ const styles = stylex.create({
},
});
-// =============================================================================
-// Sub-components
-// =============================================================================
-
-/**
- * Animated scroll-to-bottom button.
- *
- * - Icon-only ghost XDSButton (chevron down) when the user is scrolled up
- * - Expands via max-width animation to reveal label when new messages arrive
- * - Container provides opaque popover surface so ghost hover tint doesn't bleed
- *
- * Structure: container (positioning, fade, opaque surface) → XDSButton (ghost)
- * The label is always in the DOM but clipped by `max-width: 0` + `overflow: hidden`.
- * `contain: layout style` on the container isolates reflow from the scroll area.
- */
-function ScrollToBottomButton({
- isScrolledUp,
- hasNewMessages,
- label,
- onClick,
-}: {
- isScrolledUp: boolean;
- hasNewMessages: boolean;
- label: string;
- onClick: () => void;
-}) {
- const isVisible = isScrolledUp || hasNewMessages;
-
- return (
- <div
- {...stylex.props(
- styles.scrollButtonContainer,
- isVisible
- ? styles.scrollButtonContainerVisible
- : styles.scrollButtonContainerHidden,
- hasNewMessages
- ? styles.scrollButtonExpanded
- : styles.scrollButtonCollapsed,
- )}>
- <XDSButton
- label={hasNewMessages ? label : 'Scroll to bottom'}
- aria-label={hasNewMessages ? label : 'Scroll to bottom'}
- icon={<XDSIcon icon="chevronDown" size="md" />}
- variant="ghost"
- size="md"
- onClick={onClick}
- xstyle={styles.scrollButton}>
- {hasNewMessages ? label : undefined}
- </XDSButton>
- </div>
- );
-}
-
// =============================================================================
// Component
// =============================================================================
/**
- * Scrollable container for chat messages with auto-scroll and infinite scroll support.
+ * Presentational container for chat messages.
*
- * Pins to the bottom when the user is near the end. Shows a muted
- * scroll-to-bottom icon button when scrolled up. When new messages
- * arrive while scrolled up, the button expands to show a
- * "New messages" label. Supports loading older messages via
- * `onScrollToTopAction`.
+ * Renders messages in a flex column with density-based spacing.
+ * A spacer pushes content to the bottom when the list isn't full.
+ * Supports loading older messages via `onScrollToTopAction`.
+ *
+ * Auto-scroll and the scroll-to-bottom button are owned by
+ * XDSChatLayout. Use useAutoScroll for standalone scroll control.
*
* @example
* ```
@@ -289,18 +145,11 @@ function ScrollToBottomButton({
* <XDSChatMessage sender="assistant" name="Navi" avatar={<XDSAvatar name="Navi" size="md" />}>
* <XDSChatMessageBubble>Hello!</XDSChatMessageBubble>
* </XDSChatMessage>
- * <XDSChatMessage sender="user" name="Cindy">
- * <XDSChatMessageBubble>Hey there!</XDSChatMessageBubble>
- * </XDSChatMessage>
* </XDSChatMessageList>
* ```
*/
export function XDSChatMessageList({
children,
- hasAutoScroll = true,
- scrollThreshold = 12,
- scrollUpThreshold = 100,
- newMessagesLabel = 'New messages',
emptyState,
onScrollToTopAction,
density = 'balanced',
@@ -310,38 +159,28 @@ export function XDSChatMessageList({
'data-testid': testId,
ref,
}: XDSChatMessageListProps) {
- const {
- scrollRef,
- isScrolledUp,
- hasNewMessages,
- handleScroll,
- scrollToBottom,
- dismissNewMessages,
- onContentChange,
- } = useAutoScroll({
- enabled: hasAutoScroll,
- threshold: scrollThreshold,
- scrollUpThreshold,
- });
-
+ const layoutContext = useXDSChatLayoutContext();
const sentinelRef = useRef<HTMLDivElement>(null);
+ const innerRef = useRef<HTMLDivElement>(null);
const [isLoadingTop, startTransition] = useTransition();
- // Track whether children exist (for empty state)
+ // Register inner content element with the layout for height observation
+ useEffect(() => {
+ if (layoutContext?.contentRef && innerRef.current) {
+ layoutContext.contentRef(innerRef.current);
+ return () => layoutContext.contentRef(null);
+ }
+ }, [layoutContext]);
+
const hasChildren =
children != null &&
children !== false &&
!(Array.isArray(children) && children.length === 0);
- // Auto-scroll on new content (children change)
- useEffect(() => {
- onContentChange();
- }, [children, onContentChange]);
-
// IntersectionObserver for scroll-to-top infinite scroll
useEffect(() => {
- if (!onScrollToTopAction || !sentinelRef.current || !scrollRef.current)
- return;
+ const scrollContainer = layoutContext?.scrollContainerRef?.current;
+ if (!onScrollToTopAction || !sentinelRef.current) return;
const observer = new IntersectionObserver(
entries => {
@@ -351,12 +190,12 @@ export function XDSChatMessageList({
});
}
},
- {root: scrollRef.current, threshold: 0},
+ {root: scrollContainer ?? null, threshold: 0},
);
observer.observe(sentinelRef.current);
return () => observer.disconnect();
- }, [onScrollToTopAction, scrollRef]);
+ }, [onScrollToTopAction, layoutContext]);
const contextValue = useMemo(() => ({density}), [density]);
@@ -367,74 +206,41 @@ export function XDSChatMessageList({
? styles.gapSpacious
: styles.gapBalanced;
- // Merge refs
- const setRefs = useCallback(
- (el: HTMLDivElement | null) => {
- (scrollRef as React.MutableRefObject<HTMLDivElement | null>).current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- (ref as React.MutableRefObject<HTMLDivElement | null>).current = el;
- }
- },
- [ref, scrollRef],
- );
-
- // Click handler: dismiss new messages (scrolls to bottom) or just scroll
- const handleButtonClick = useCallback(() => {
- if (hasNewMessages) {
- dismissNewMessages();
- } else {
- scrollToBottom();
- }
- }, [hasNewMessages, dismissNewMessages, scrollToBottom]);
-
return (
<XDSChatListContext.Provider value={contextValue}>
- <div {...stylex.props(styles.outer)}>
- <div
- ref={setRefs}
- role="log"
- aria-live="polite"
- tabIndex={0}
- data-testid={testId}
- onScroll={handleScroll}
- {...mergeProps(
- xdsClassName('chat-message-list', {density}),
- stylex.props(styles.root, xstyle),
- className,
- style,
- )}>
- <div {...stylex.props(styles.inner, gapStyle)}>
- {/* Sentinel for infinite scroll */}
- {onScrollToTopAction && <div ref={sentinelRef} aria-hidden />}
-
- {/* Loading spinner at top */}
- {isLoadingTop && (
- <div {...stylex.props(styles.loadingTop)}>
- <XDSSpinner size="md" />
- </div>
- )}
-
- {/* Spacer pushes messages to bottom when list isn't full */}
- <div {...stylex.props(styles.spacer)} aria-hidden />
-
- {/* Messages or empty state */}
- {hasChildren ? (
- children
- ) : emptyState ? (
- <div {...stylex.props(styles.emptyState)}>{emptyState}</div>
- ) : null}
- </div>
+ <div
+ ref={ref}
+ role="log"
+ aria-live="polite"
+ tabIndex={0}
+ data-testid={testId}
+ {...mergeProps(
+ xdsClassName('chat-message-list', {density}),
+ stylex.props(styles.root, xstyle),
+ className,
+ style,
+ )}>
+ <div ref={innerRef} {...stylex.props(styles.inner, gapStyle)}>
+ {/* Sentinel for infinite scroll */}
+ {onScrollToTopAction && <div ref={sentinelRef} aria-hidden />}
+
+ {/* Loading spinner at top */}
+ {isLoadingTop && (
+ <div {...stylex.props(styles.loadingTop)}>
+ <XDSSpinner size="md" />
+ </div>
+ )}
+
+ {/* Spacer pushes messages to bottom when list isn't full */}
+ <div {...stylex.props(styles.spacer)} aria-hidden />
+
+ {/* Messages or empty state */}
+ {hasChildren ? (
+ children
+ ) : emptyState ? (
+ <div {...stylex.props(styles.emptyState)}>{emptyState}</div>
+ ) : null}
</div>
-
- {/* Scroll-to-bottom button: icon-only when scrolled up, expands with label on new messages */}
- <ScrollToBottomButton
- isScrolledUp={isScrolledUp}
- hasNewMessages={hasNewMessages}
- label={newMessagesLabel}
- onClick={handleButtonClick}
- />
</div>
</XDSChatListContext.Provider>
);
diff --git a/packages/core/src/Chat/XDSChatMessageTokenizedText.test.tsx b/packages/core/src/Chat/XDSChatTokenizedText.test.tsx
similarity index 75%
rename from packages/core/src/Chat/XDSChatMessageTokenizedText.test.tsx
rename to packages/core/src/Chat/XDSChatTokenizedText.test.tsx
index 8acbe34cda..a1b9942c4e 100644
--- a/packages/core/src/Chat/XDSChatMessageTokenizedText.test.tsx
+++ b/packages/core/src/Chat/XDSChatTokenizedText.test.tsx
@@ -1,30 +1,30 @@
import {describe, it, expect} from 'vitest';
import {render, screen} from '@testing-library/react';
-import {XDSChatMessageTokenizedText} from './XDSChatMessageTokenizedText';
+import {XDSChatTokenizedText} from './XDSChatTokenizedText';
-describe('XDSChatMessageTokenizedText', () => {
+describe('XDSChatTokenizedText', () => {
it('renders plain text when no tokens provided', () => {
render(
- <XDSChatMessageTokenizedText>Hello world</XDSChatMessageTokenizedText>,
+ <XDSChatTokenizedText>Hello world</XDSChatTokenizedText>,
);
expect(screen.getByText('Hello world')).toBeInTheDocument();
});
it('renders plain text when tokens array is empty', () => {
render(
- <XDSChatMessageTokenizedText tokens={[]}>
+ <XDSChatTokenizedText tokens={[]}>
Hello world
- </XDSChatMessageTokenizedText>,
+ </XDSChatTokenizedText>,
);
expect(screen.getByText('Hello world')).toBeInTheDocument();
});
it('replaces a single token with a badge', () => {
render(
- <XDSChatMessageTokenizedText
+ <XDSChatTokenizedText
tokens={[{value: '@cindy', label: '@Cindy Zhang', variant: 'blue'}]}>
Hey @cindy!
- </XDSChatMessageTokenizedText>,
+ </XDSChatTokenizedText>,
);
expect(screen.getByText('@Cindy Zhang')).toBeInTheDocument();
expect(screen.queryByText('@cindy')).not.toBeInTheDocument();
@@ -32,13 +32,13 @@ describe('XDSChatMessageTokenizedText', () => {
it('replaces multiple different tokens', () => {
render(
- <XDSChatMessageTokenizedText
+ <XDSChatTokenizedText
tokens={[
{value: '@cindy', label: '@Cindy Zhang', variant: 'blue'},
{value: '@navi', label: '@Navi', variant: 'blue'},
]}>
Hey @cindy, can @navi help?
- </XDSChatMessageTokenizedText>,
+ </XDSChatTokenizedText>,
);
expect(screen.getByText('@Cindy Zhang')).toBeInTheDocument();
expect(screen.getByText('@Navi')).toBeInTheDocument();
@@ -46,30 +46,30 @@ describe('XDSChatMessageTokenizedText', () => {
it('handles repeated occurrences of the same token', () => {
render(
- <XDSChatMessageTokenizedText
+ <XDSChatTokenizedText
tokens={[{value: '@cindy', label: '@Cindy Zhang'}]}>
@cindy and @cindy again
- </XDSChatMessageTokenizedText>,
+ </XDSChatTokenizedText>,
);
expect(screen.getAllByText('@Cindy Zhang')).toHaveLength(2);
});
it('renders text with no matching tokens as plain text', () => {
render(
- <XDSChatMessageTokenizedText
+ <XDSChatTokenizedText
tokens={[{value: '@cindy', label: '@Cindy Zhang'}]}>
Hello world
- </XDSChatMessageTokenizedText>,
+ </XDSChatTokenizedText>,
);
expect(screen.getByText('Hello world')).toBeInTheDocument();
});
it('handles tokens with special regex characters in pattern', () => {
render(
- <XDSChatMessageTokenizedText
+ <XDSChatTokenizedText
tokens={[{value: '/search', label: '/search'}]}>
Run /search now
- </XDSChatMessageTokenizedText>,
+ </XDSChatTokenizedText>,
);
// The badge should render with the label
expect(screen.getByText('/search')).toBeInTheDocument();
@@ -77,10 +77,10 @@ describe('XDSChatMessageTokenizedText', () => {
it('preserves surrounding text', () => {
const {container} = render(
- <XDSChatMessageTokenizedText
+ <XDSChatTokenizedText
tokens={[{value: '@cindy', label: '@Cindy Zhang'}]}>
Before @cindy after
- </XDSChatMessageTokenizedText>,
+ </XDSChatTokenizedText>,
);
expect(container.textContent).toContain('Before');
expect(container.textContent).toContain('after');
diff --git a/packages/core/src/Chat/XDSChatMessageTokenizedText.tsx b/packages/core/src/Chat/XDSChatTokenizedText.tsx
similarity index 86%
rename from packages/core/src/Chat/XDSChatMessageTokenizedText.tsx
rename to packages/core/src/Chat/XDSChatTokenizedText.tsx
index 87f4d3ae22..7be0808b24 100644
--- a/packages/core/src/Chat/XDSChatMessageTokenizedText.tsx
+++ b/packages/core/src/Chat/XDSChatTokenizedText.tsx
@@ -1,9 +1,9 @@
'use client';
/**
- * @file XDSChatMessageTokenizedText.tsx
+ * @file XDSChatTokenizedText.tsx
* @input Uses React, XDSBadge, XDSChatComposerToken
- * @output Exports XDSChatMessageTokenizedText component
+ * @output Exports XDSChatTokenizedText component
* @position Utility component for rendering tokenized text in message bubbles
*
* Parses a plain text string and replaces token values with inline badges.
@@ -22,7 +22,7 @@ import type {XDSChatComposerToken} from './XDSChatComposerInput';
// Types
// =============================================================================
-export interface XDSChatMessageTokenizedTextProps {
+export interface XDSChatTokenizedTextProps {
/** The message text containing serialized token values */
children: string;
/**
@@ -37,9 +37,14 @@ export interface XDSChatMessageTokenizedTextProps {
* label: `@${c.label}`,
* variant: 'blue' as const,
* }));
- * <XDSChatMessageTokenizedText tokens={mentionTokens}>
+ *
+ * // Input trigger
+ * { character: '@', onSelect: (item) => mentionTokens.find(...) }
+ *
+ * // Display
+ * <XDSChatTokenizedText tokens={mentionTokens}>
* {message.text}
- * </XDSChatMessageTokenizedText>
+ * </XDSChatTokenizedText>
* ```
*/
tokens?: XDSChatComposerToken[];
@@ -69,19 +74,19 @@ function escapeRegExp(str: string): string {
* Accepts the same `XDSChatComposerToken` type used by input triggers,
* so you can share a single token definition between input and display.
*/
-export function XDSChatMessageTokenizedText({
+export function XDSChatTokenizedText({
children,
tokens,
-}: XDSChatMessageTokenizedTextProps) {
- if (!tokens || tokens.length === 0) {
- return <span style={{display: 'inline'}}>{children}</span>;
+}: XDSChatTokenizedTextProps) {
+ if (!children || !tokens || tokens.length === 0) {
+ return <span style={{display: 'inline'}}>{children ?? ''}</span>;
}
const parts = renderTokens(children, tokens);
return <span style={{display: 'inline'}}>{parts}</span>;
}
-XDSChatMessageTokenizedText.displayName = 'XDSChatMessageTokenizedText';
+XDSChatTokenizedText.displayName = 'XDSChatTokenizedText';
// =============================================================================
// Render
diff --git a/packages/core/src/Chat/index.ts b/packages/core/src/Chat/index.ts
index bf6767becd..e7f9c649dd 100644
--- a/packages/core/src/Chat/index.ts
+++ b/packages/core/src/Chat/index.ts
@@ -28,8 +28,9 @@ export type {
XDSChatComposerTriggerItem,
} from './XDSChatComposerInput';
-export {XDSChatMessageTokenizedText} from './XDSChatMessageTokenizedText';
-export type {XDSChatMessageTokenizedTextProps} from './XDSChatMessageTokenizedText';
+export {XDSChatTokenizedText} from './XDSChatTokenizedText';
+export type {XDSChatTokenizedTextProps} from './XDSChatTokenizedText';
+
export {XDSChatMessageList} from './XDSChatMessageList';
export type {XDSChatMessageListProps} from './XDSChatMessageList';
@@ -66,3 +67,6 @@ export type {
XDSChatToolCallItem,
XDSChatToolCallStatus,
} from './XDSChatToolCalls';
+
+export {XDSChatLayout} from './XDSChatLayout';
+export type {XDSChatLayoutProps} from './XDSChatLayout';
diff --git a/packages/core/src/Chat/useAutoScroll.ts b/packages/core/src/Chat/useAutoScroll.ts
index 2e4d2cccf0..c1c9ca9e84 100644
--- a/packages/core/src/Chat/useAutoScroll.ts
+++ b/packages/core/src/Chat/useAutoScroll.ts
@@ -4,18 +4,20 @@
* @file useAutoScroll.ts
* @input Uses React refs, state, and effects
* @output Exports useAutoScroll hook for scroll-pinning behavior
- * @position Utility hook — used by XDSChatMessageList, also usable standalone
+ * @position Utility hook — used by XDSChatLayout, also usable standalone
*
- * Exposes two scroll states:
- * - `isScrolledUp` — true when the user has scrolled away from the bottom
- * (beyond `scrollUpThreshold`), regardless of whether new content arrived.
- * Drives a scroll-to-bottom affordance.
- * - `hasNewMessages` — true when new content arrived while scrolled up.
- * Layers on top of isScrolledUp to add a "new messages" notification.
+ * Scroll-lock model:
+ * - **Locked** (default): content changes auto-scroll to bottom
+ * - **Unlocked**: user manually scrolled, auto-scroll stops
+ * - **Re-locked**: user clicks scroll-to-bottom button
+ *
+ * Uses `scrollend` to distinguish user scrolls from programmatic ones.
+ * Programmatic scrolls (scrollToBottom) set a flag before scrolling;
+ * when `scrollend` fires without that flag, it was a user scroll → unlock.
*
* SYNC: When modified, update:
* - /packages/core/src/Chat/index.ts (exports)
- * - /packages/core/src/Chat/XDSChatMessageList.tsx (consumer)
+ * - /packages/core/src/Chat/XDSChatLayout.tsx (consumer)
*/
import {useCallback, useEffect, useRef, useState} from 'react';
@@ -28,76 +30,79 @@ export interface UseAutoScrollOptions {
enabled?: boolean;
/**
- * Distance from bottom (in px) within which new content triggers auto-scroll.
- * @default 12
+ * Distance from bottom (in px) beyond which the scroll-to-bottom
+ * button becomes visible.
+ * @default 100
*/
- threshold?: number;
+ scrollUpThreshold?: number;
/**
- * Distance from bottom (in px) beyond which `isScrolledUp` becomes true.
- * Controls when the scroll-to-bottom button appears.
- * @default 100
+ * External scroll container ref. When provided, scroll logic targets
+ * this element instead of creating its own.
*/
- scrollUpThreshold?: number;
+ scrollContainerRef?: React.RefObject<HTMLElement | null>;
}
export interface UseAutoScrollReturn {
/** Ref to attach to the scrollable container element. */
scrollRef: React.RefObject<HTMLDivElement | null>;
- /** Whether the user has scrolled up beyond `scrollUpThreshold`. */
+ /** Whether the user has scrolled up (shows scroll-to-bottom button). */
isScrolledUp: boolean;
- /** Whether new content arrived while the user is scrolled up. */
+ /** Whether new content arrived while unlocked. */
hasNewMessages: boolean;
- /** Scroll handler — attach to onScroll on the scrollable element. */
+ /** Scroll handler — attach to onScroll. */
handleScroll: () => void;
+ /** Scrollend handler — attach to scrollend. */
+ handleScrollEnd: () => void;
+
+ /** User input handler — attach to wheel/touchstart to interrupt programmatic scrolls. */
+ handleUserScroll: () => void;
+
/** Scroll to the bottom of the container. */
scrollToBottom: (smooth?: boolean) => void;
- /** Dismiss the new messages indicator and scroll to bottom. */
+ /** Dismiss the new messages indicator, re-lock, and scroll to bottom. */
dismissNewMessages: () => void;
- /** Notify the hook that content changed (triggers auto-scroll check). */
+ /** New message appended — flag "new messages" if unlocked. */
onContentChange: () => void;
+
+ /** Content grew — auto-scroll if locked, no flag. */
+ scrollToBottomIfLocked: () => void;
}
/**
- * Hook that manages auto-scroll behavior for scrollable containers.
- *
- * Pins to the bottom when the user is near the end. Tracks two
- * orthogonal states: whether the user has scrolled up (for a
- * scroll-to-bottom affordance) and whether new content arrived
- * while scrolled up (for a "new messages" notification).
+ * Hook that manages scroll-lock auto-scroll behavior.
*
- * @example
- * ```
- * const {scrollRef, isScrolledUp, hasNewMessages, handleScroll, scrollToBottom, dismissNewMessages} = useAutoScroll();
- *
- * return (
- * <div ref={scrollRef} onScroll={handleScroll}>
- * {messages}
- * {isScrolledUp && <button onClick={scrollToBottom}>↓</button>}
- * {hasNewMessages && <button onClick={dismissNewMessages}>New messages</button>}
- * </div>
- * );
- * ```
+ * Starts locked (pinned to bottom). User scrolling unlocks (detected
+ * via `scrollend` without the programmatic flag). Clicking the
+ * scroll-to-bottom button re-locks.
*/
export function useAutoScroll({
enabled = true,
- threshold = 12,
scrollUpThreshold = 100,
+ scrollContainerRef,
}: UseAutoScrollOptions = {}): UseAutoScrollReturn {
- const scrollRef = useRef<HTMLDivElement | null>(null);
+ const internalRef = useRef<HTMLDivElement | null>(null);
+ const scrollRef = (scrollContainerRef ??
+ internalRef) as React.RefObject<HTMLDivElement | null>;
+
const [hasNewMessages, setHasNewMessages] = useState(false);
const [isScrolledUp, setIsScrolledUp] = useState(false);
- const isNearBottomRef = useRef(true);
+
+ // Scroll lock: true = auto-scroll follows content
+ const lockedRef = useRef(true);
+ // Flag set before programmatic scrolls, cleared on scrollend
+ const isProgrammaticRef = useRef(false);
const scrollToBottom = useCallback((smooth = true) => {
const el = scrollRef.current;
if (!el) return;
+ isProgrammaticRef.current = true;
if (typeof el.scrollTo === 'function') {
el.scrollTo({
top: el.scrollHeight,
@@ -108,33 +113,58 @@ export function useAutoScroll({
}
}, []);
+ // User input (wheel/touch) interrupts any in-progress programmatic scroll
+ const handleUserScroll = useCallback(() => {
+ isProgrammaticRef.current = false;
+ }, []);
+
+ // On scroll: unlock if user scrolled past threshold
const handleScroll = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
- const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
- const nearBottom = distanceFromBottom <= threshold;
- isNearBottomRef.current = nearBottom;
-
- // Track whether user is scrolled up beyond the visible threshold
+ const distanceFromBottom =
+ el.scrollHeight - el.scrollTop - el.clientHeight;
setIsScrolledUp(distanceFromBottom > scrollUpThreshold);
- if (nearBottom) {
+ if (!isProgrammaticRef.current && distanceFromBottom > scrollUpThreshold) {
+ lockedRef.current = false;
+ }
+ }, [scrollUpThreshold]);
+
+ // On scroll end: lock if at bottom, clear programmatic flag
+ const handleScrollEnd = useCallback(() => {
+ isProgrammaticRef.current = false;
+
+ const el = scrollRef.current;
+ if (!el) return;
+ const distanceFromBottom =
+ el.scrollHeight - el.scrollTop - el.clientHeight;
+ if (distanceFromBottom <= scrollUpThreshold) {
+ lockedRef.current = true;
setHasNewMessages(false);
}
- }, [threshold, scrollUpThreshold]);
+ }, [scrollUpThreshold]);
const onContentChange = useCallback(() => {
if (!enabled) return;
- if (isNearBottomRef.current) {
- scrollToBottom(true);
- } else {
+ if (!lockedRef.current) {
setHasNewMessages(true);
}
+ }, [enabled]);
+
+ const scrollToBottomIfLocked = useCallback(() => {
+ if (!enabled) return;
+ if (lockedRef.current) {
+ scrollToBottom(true);
+ }
}, [enabled, scrollToBottom]);
const dismissNewMessages = useCallback(() => {
- scrollToBottom();
+ lockedRef.current = true;
+ isProgrammaticRef.current = true;
+ setIsScrolledUp(false);
setHasNewMessages(false);
+ scrollToBottom();
}, [scrollToBottom]);
// Scroll to bottom on mount
@@ -147,8 +177,11 @@ export function useAutoScroll({
isScrolledUp,
hasNewMessages,
handleScroll,
+ handleScrollEnd,
+ handleUserScroll,
scrollToBottom,
dismissNewMessages,
onContentChange,
+ scrollToBottomIfLocked,
};
}
diff --git a/packages/core/src/ProgressBar/XDSProgressBar.tsx b/packages/core/src/ProgressBar/XDSProgressBar.tsx
index 7ca4b10cc2..3028effc38 100644
--- a/packages/core/src/ProgressBar/XDSProgressBar.tsx
+++ b/packages/core/src/ProgressBar/XDSProgressBar.tsx
@@ -131,6 +131,7 @@ const styles = stylex.create({
flexDirection: 'column',
gap: spacingVars['--spacing-1'],
width: '100%',
+ minWidth: '48px',
},
header: {
display: 'flex',
@@ -246,6 +247,7 @@ export function XDSProgressBar({
style,
'data-testid': dataTestId,
ref,
+ ...rest
}: XDSProgressBarProps) {
const labelId = useId();
const clampedValue = Math.min(Math.max(0, value), max);
@@ -264,7 +266,8 @@ export function XDSProgressBar({
className,
style,
)}
- data-testid={dataTestId}>
+ data-testid={dataTestId}
+ {...rest}>
{/* Label row */}
{!isLabelHidden || showValueLabel ? (
<div {...stylex.props(styles.header)}>