Skip to content

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

TypeScript

feat(Chat): trigger menu system for XDSChatComposerInput (#1193)

Cindy Zhang98e960c56552
diff --git a/apps/storybook/stories/ChatComposerInput.stories.tsx b/apps/storybook/stories/ChatComposerInput.stories.tsx
new file mode 100644
index 0000000000..a4f42d74cc
--- /dev/null
+++ b/apps/storybook/stories/ChatComposerInput.stories.tsx
@@ -0,0 +1,574 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSChatComposer,
+ XDSChatComposerInput,
+ type XDSChatComposerTrigger,
+} from '@xds/core/Chat';
+import {createStaticSource} from '@xds/core/Typeahead';
+import {XDSBadge} from '@xds/core/Badge';
+import {XDSTypeaheadItem} from '@xds/core/Typeahead';
+import type {XDSSearchableItem, XDSSearchSource} from '@xds/core/Typeahead';
+import {useState} from 'react';
+
+const meta: Meta = {
+ title: 'Chat/XDSChatComposerInput',
+ component: XDSChatComposerInput,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'centered',
+ },
+ decorators: [
+ Story => (
+ <div style={{width: 600, padding: 40}}>
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj;
+
+// =============================================================================
+// Mock data
+// =============================================================================
+
+const USERS: XDSSearchableItem<{role: string}>[] = [
+ {id: 'cindy', label: 'Cindy Zhang', auxiliaryData: {role: 'Design Systems'}},
+ {id: 'alex', label: 'Alex Johnson', auxiliaryData: {role: 'Frontend'}},
+ {id: 'sam', label: 'Sam Rivera', auxiliaryData: {role: 'Backend'}},
+ {id: 'jordan', label: 'Jordan Lee', auxiliaryData: {role: 'Product'}},
+ {id: 'taylor', label: 'Taylor Kim', auxiliaryData: {role: 'Design'}},
+ {id: 'morgan', label: 'Morgan Chen', auxiliaryData: {role: 'Infrastructure'}},
+];
+
+const COMMANDS: XDSSearchableItem<{description: string}>[] = [
+ {id: 'summarize', label: 'summarize', auxiliaryData: {description: 'Summarize the conversation'}},
+ {id: 'translate', label: 'translate', auxiliaryData: {description: 'Translate text to another language'}},
+ {id: 'search', label: 'search', auxiliaryData: {description: 'Search the web or documents'}},
+ {id: 'code', label: 'code', auxiliaryData: {description: 'Generate or explain code'}},
+ {id: 'help', label: 'help', auxiliaryData: {description: 'Show available commands'}},
+];
+
+const userSource = createStaticSource(USERS);
+const commandSource = createStaticSource(COMMANDS);
+
+const asyncUserSource: XDSSearchSource = {
+ search(query: string) {
+ return new Promise(resolve => {
+ setTimeout(() => {
+ const lower = query.toLowerCase();
+ resolve(USERS.filter(u => u.label.toLowerCase().includes(lower)));
+ }, 300);
+ });
+ },
+ bootstrap() {
+ return USERS;
+ },
+};
+
+// =============================================================================
+// Basic input stories
+// =============================================================================
+
+/** Controlled value — shows the serialized value below */
+export const Controlled: Story = {
+ render: () => {
+ const [value, setValue] = useState('');
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
+ <XDSChatComposer
+ onSubmit={v => {
+ alert(`Submitted: ${v}`);
+ setValue('');
+ }}
+ value={value}
+ onChange={setValue}
+ input={
+ <XDSChatComposerInput
+ value={value}
+ onChange={setValue}
+ placeholder="Type a message..."
+ />
+ }
+ />
+ <div style={{fontSize: 12, fontFamily: 'monospace', color: '#888'}}>
+ Value: {JSON.stringify(value)}
+ </div>
+ </div>
+ );
+ },
+};
+
+/** Custom placeholder */
+export const CustomPlaceholder: Story = {
+ render: () => (
+ <XDSChatComposer
+ onSubmit={v => alert(v)}
+ input={
+ <XDSChatComposerInput placeholder="Ask me anything about XDS..." />
+ }
+ />
+ ),
+};
+
+/** Disabled state */
+export const Disabled: Story = {
+ render: () => (
+ <XDSChatComposer
+ onSubmit={() => {}}
+ isDisabled
+ input={
+ <XDSChatComposerInput isDisabled placeholder="Input is disabled" />
+ }
+ />
+ ),
+};
+
+/** Max rows — scrolls after 3 lines */
+export const MaxRows: Story = {
+ render: () => (
+ <XDSChatComposer
+ onSubmit={v => alert(v)}
+ input={
+ <XDSChatComposerInput
+ maxRows={3}
+ placeholder="Type a long message — scrolls after 3 lines..."
+ />
+ }
+ />
+ ),
+};
+
+/** Message history — submit a few messages, then ArrowUp/Down to recall */
+export const MessageHistory: Story = {
+ render: () => {
+ const [log, setLog] = useState<string[]>([]);
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
+ <XDSChatComposer
+ onSubmit={v => setLog(prev => [...prev, v])}
+ input={
+ <XDSChatComposerInput
+ placeholder="Submit messages, then ArrowUp to recall..."
+ />
+ }
+ />
+ {log.length > 0 && (
+ <div style={{fontSize: 12, fontFamily: 'monospace', color: '#666'}}>
+ {log.map((msg, i) => (
+ <div key={i}>→ {msg}</div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ },
+};
+
+/** File paste handler */
+export const FilePaste: Story = {
+ render: () => {
+ const [files, setFiles] = useState<string[]>([]);
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
+ <XDSChatComposer
+ onSubmit={v => alert(v)}
+ input={
+ <XDSChatComposerInput
+ onFiles={f => setFiles(prev => [...prev, ...f.map(x => x.name)])}
+ placeholder="Paste files here (Ctrl+V)..."
+ />
+ }
+ />
+ {files.length > 0 && (
+ <div style={{fontSize: 12, color: '#666'}}>
+ Files: {files.join(', ')}
+ </div>
+ )}
+ </div>
+ );
+ },
+};
+
+// =============================================================================
+// Trigger stories
+// =============================================================================
+
+/** Static @ mentions — type @ to see the menu */
+export const MentionTrigger: Story = {
+ render: () => {
+ const [value, setValue] = useState('');
+ const [log, setLog] = useState<string[]>([]);
+ const mentionTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: userSource,
+ renderItem: item => (
+ <XDSTypeaheadItem
+ item={item}
+ description={(item.auxiliaryData as {role: string})?.role}
+ />
+ ),
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: item.label,
+ variant: 'blue' as const,
+ }),
+ };
+
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
+ <XDSChatComposer
+ onSubmit={v => {
+ setLog(prev => [...prev, v]);
+ setValue('');
+ }}
+ input={
+ <XDSChatComposerInput
+ value={value}
+ onChange={setValue}
+ triggers={[mentionTrigger]}
+ placeholder="Type @ to mention someone..."
+ />
+ }
+ />
+ <div style={{fontSize: 12, fontFamily: 'monospace', color: '#888'}}>
+ Value: {JSON.stringify(value)}
+ </div>
+ {log.length > 0 && (
+ <div style={{fontSize: 12, fontFamily: 'monospace', color: '#666'}}>
+ {log.map((msg, i) => (
+ <div key={i}>→ {msg}</div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ },
+};
+
+/** Static / commands — type / to see commands */
+export const SlashCommands: Story = {
+ render: () => {
+ const commandTrigger: XDSChatComposerTrigger = {
+ character: '/',
+ searchSource: commandSource,
+ renderItem: item => (
+ <XDSTypeaheadItem
+ item={item}
+ description={(item.auxiliaryData as {description: string})?.description}
+ />
+ ),
+ onSelect: item => ({
+ value: `/${item.label}`,
+ label: `/${item.label}`,
+ variant: 'yellow' as const,
+ }),
+ };
+
+ return (
+ <XDSChatComposer
+ onSubmit={value => alert(`Sent: ${value}`)}
+ input={
+ <XDSChatComposerInput
+ triggers={[commandTrigger]}
+ placeholder="Type / for commands..."
+ />
+ }
+ />
+ );
+ },
+};
+
+/** Async search source — type @ to trigger a simulated API search */
+export const AsyncSearch: Story = {
+ render: () => {
+ const asyncTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: asyncUserSource,
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: item.label,
+ variant: 'blue' as const,
+ }),
+ loadingText: 'Searching users…',
+ emptySearchResultsText: 'No users found',
+ };
+
+ return (
+ <XDSChatComposer
+ onSubmit={value => alert(`Sent: ${value}`)}
+ input={
+ <XDSChatComposerInput
+ triggers={[asyncTrigger]}
+ placeholder="Type @ for async user search (300ms delay)..."
+ />
+ }
+ />
+ );
+ },
+};
+
+/** Multiple triggers — @ for mentions, / for commands */
+export const MultipleTriggers: Story = {
+ render: () => {
+ const [value, setValue] = useState('');
+ const mentionTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: userSource,
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: item.label,
+ variant: 'blue' as const,
+ }),
+ };
+ const commandTrigger: XDSChatComposerTrigger = {
+ character: '/',
+ searchSource: commandSource,
+ onSelect: item => ({
+ value: `/${item.label}`,
+ label: `/${item.label}`,
+ variant: 'yellow' as const,
+ }),
+ };
+
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
+ <XDSChatComposer
+ onSubmit={v => {
+ alert(`Sent: ${v}`);
+ setValue('');
+ }}
+ input={
+ <XDSChatComposerInput
+ value={value}
+ onChange={setValue}
+ triggers={[mentionTrigger, commandTrigger]}
+ placeholder="Type @ or / ..."
+ />
+ }
+ />
+ <div style={{fontSize: 12, fontFamily: 'monospace', color: '#888'}}>
+ Value: {JSON.stringify(value)}
+ </div>
+ </div>
+ );
+ },
+};
+
+/** Custom item rendering in the trigger menu */
+export const CustomRenderItem: Story = {
+ render: () => {
+ const mentionTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: userSource,
+ renderItem: item => (
+ <XDSTypeaheadItem
+ item={item}
+ description={(item.auxiliaryData as {role: string})?.role}
+ icon={
+ <div
+ style={{
+ width: 24,
+ height: 24,
+ borderRadius: '50%',
+ backgroundColor: '#e8d5f5',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: 11,
+ fontWeight: 600,
+ color: '#7c3aed',
+ }}>
+ {item.label.charAt(0)}
+ </div>
+ }
+ />
+ ),
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: item.label,
+ variant: 'purple' as const,
+ icon: (
+ <span
+ style={{
+ width: 14,
+ height: 14,
+ borderRadius: '50%',
+ backgroundColor: '#e8d5f5',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: 8,
+ fontWeight: 700,
+ color: '#7c3aed',
+ }}>
+ {item.label.charAt(0)}
+ </span>
+ ),
+ }),
+ };
+
+ return (
+ <XDSChatComposer
+ onSubmit={value => alert(`Sent: ${value}`)}
+ input={
+ <XDSChatComposerInput
+ triggers={[mentionTrigger]}
+ placeholder="Type @ — tokens have icons via badge config..."
+ />
+ }
+ />
+ );
+ },
+};
+
+/** Token color variants — different badge colors per trigger */
+export const TokenVariants: Story = {
+ render: () => {
+ const mentionTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: userSource,
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: item.label,
+ variant: 'blue' as const,
+ }),
+ };
+ const commandTrigger: XDSChatComposerTrigger = {
+ character: '/',
+ searchSource: commandSource,
+ onSelect: item => ({
+ value: `/${item.label}`,
+ label: `/${item.label}`,
+ variant: 'purple' as const,
+ }),
+ };
+
+ return (
+ <XDSChatComposer
+ onSubmit={value => alert(`Sent: ${value}`)}
+ input={
+ <XDSChatComposerInput
+ triggers={[mentionTrigger, commandTrigger]}
+ placeholder="@ for blue mentions, / for purple commands..."
+ />
+ }
+ />
+ );
+ },
+};
+
+
+/** Custom render — full control via render() for rich token content */
+export const CustomRender: Story = {
+ render: () => {
+ const mentionTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: userSource,
+ renderItem: item => (
+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
+ <div
+ style={{
+ width: 24,
+ height: 24,
+ borderRadius: '50%',
+ backgroundColor: '#e0e0e0',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: 11,
+ fontWeight: 600,
+ }}>
+ {item.label.charAt(0)}
+ </div>
+ <span>{item.label}</span>
+ </div>
+ ),
+ onSelect: item => ({
+ value: `@${item.id}`,
+ render: () => (
+ <span
+ title={`Click to view ${item.label}'s profile`}
+ style={{cursor: 'pointer'}}
+ onClick={() => alert(`Profile: ${item.label}`)}>
+ <XDSBadge
+ variant="blue"
+ label={item.label}
+ icon={
+ <span
+ style={{
+ width: 14,
+ height: 14,
+ borderRadius: '50%',
+ backgroundColor: '#c4d4f0',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: 8,
+ fontWeight: 700,
+ }}>
+ {item.label.charAt(0)}
+ </span>
+ }
+ />
+ </span>
+ ),
+ }),
+ };
+
+ return (
+ <XDSChatComposer
+ onSubmit={value => alert(`Sent: ${value}`)}
+ input={
+ <XDSChatComposerInput
+ triggers={[mentionTrigger]}
+ placeholder="Type @ — tokens are clickable with avatars..."
+ />
+ }
+ />
+ );
+ },
+};
+
+/** Grouped menu items — items with auxiliaryData.group render under headings */
+export const GroupedItems: Story = {
+ render: () => {
+ const groupedUsers = createStaticSource([
+ {id: 'cindy', label: 'Cindy Zhang', auxiliaryData: {group: 'Design', role: 'Design Systems'}},
+ {id: 'taylor', label: 'Taylor Kim', auxiliaryData: {group: 'Design', role: 'Product Design'}},
+ {id: 'alex', label: 'Alex Johnson', auxiliaryData: {group: 'Engineering', role: 'Frontend'}},
+ {id: 'sam', label: 'Sam Rivera', auxiliaryData: {group: 'Engineering', role: 'Backend'}},
+ {id: 'morgan', label: 'Morgan Chen', auxiliaryData: {group: 'Engineering', role: 'Infrastructure'}},
+ {id: 'jordan', label: 'Jordan Lee', auxiliaryData: {group: 'Product', role: 'Product Manager'}},
+ ] as XDSSearchableItem[]);
+
+ const mentionTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: groupedUsers,
+ renderItem: item => (
+ <XDSTypeaheadItem
+ item={item}
+ description={(item.auxiliaryData as {role?: string})?.role}
+ />
+ ),
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: item.label,
+ variant: 'blue' as const,
+ }),
+ };
+
+ return (
+ <XDSChatComposer
+ onSubmit={value => alert(`Sent: ${value}`)}
+ input={
+ <XDSChatComposerInput
+ triggers={[mentionTrigger]}
+ placeholder="Type @ to see grouped mentions..."
+ />
+ }
+ />
+ );
+ },
+};
diff --git a/packages/core/src/Button/XDSButton.tsx b/packages/core/src/Button/XDSButton.tsx
index 8856739441..f65b0af81f 100644
--- a/packages/core/src/Button/XDSButton.tsx
+++ b/packages/core/src/Button/XDSButton.tsx
@@ -52,8 +52,8 @@ const styles = stylex.create({
paddingInline: spacingVars['--spacing-3'],
borderWidth: 0,
borderStyle: 'none',
- '--button-radius': radiusVars['--radius-element'],
- borderRadius: 'var(--button-radius)',
+
+ borderRadius: `var(--button-radius, ${radiusVars['--radius-element']})`,
fontFamily: 'inherit',
fontSize: typeScaleVars['--text-label-size'],
lineHeight: typeScaleVars['--text-label-leading'],
diff --git a/packages/core/src/Chat/Chat.doc.mjs b/packages/core/src/Chat/Chat.doc.mjs
index ab1d6833fa..c9eb064886 100644
--- a/packages/core/src/Chat/Chat.doc.mjs
+++ b/packages/core/src/Chat/Chat.doc.mjs
@@ -3,8 +3,8 @@
export const docs = {
name: 'Chat',
description:
- 'Chat layout components for AI chat interfaces. Composition model: XDSChatMessageList wraps XDSChatMessage and XDSChatSystemMessage. Messages contain optional XDSChatMessageBubble for styled content.',
- keywords: ['chat', 'message', 'bubble', 'conversation', 'ai', 'assistant', 'thread', 'system-message'],
+ 'Chat components for AI chat interfaces. Layout (MessageList, Message, Bubble, SystemMessage) + Composer (Composer, ComposerInput with trigger menus, ComposerAttachments).',
+ keywords: ['chat', 'message', 'bubble', 'conversation', 'ai', 'assistant', 'thread', 'system-message', 'composer', 'mention', 'trigger', 'typeahead', 'token'],
features: [
'Composition model — MessageList > Message > Bubble',
'Sender-aware styling (user, assistant, system) via context',
@@ -16,7 +16,23 @@ export const docs = {
'Timestamp display: hover or header',
'Message status indicators (sending, sent, delivered, read, error)',
'role="log" with aria-live="polite" for accessibility',
+ 'Composer layout shell with named semantic slots',
+ 'ContentEditable input with @ mention and / command trigger menus',
+ 'XDSSearchSource integration — reuses Typeahead search sources',
+ 'Concentric radius — inner elements follow outer shell curvature',
+ 'Themeable via --composer-radius and --composer-padding CSS vars',
],
+ theming: {
+ targets: [
+ {className: 'xds-chat-composer', visualProps: ['density']},
+ {className: 'xds-chat-composer-input'},
+ ],
+ vars: [
+ {name: '--composer-radius', description: 'Border radius of the composer body. Inner elements derive their radius concentrically.', default: 'var(--radius-page)'},
+ {name: '--composer-padding', description: 'Padding of the composer body. Used in the concentric radius calculation.', default: 'var(--spacing-3)'},
+ {name: '--button-radius', description: 'Concentric button radius inside the composer.', default: 'max(var(--radius-element), calc(var(--composer-radius) - var(--composer-padding)))', derived: true, formula: 'max(var(--radius-element), calc(var(--composer-radius) - var(--composer-padding)))'},
+ ],
+ },
examples: [
{
label: 'Basic conversation',
@@ -92,5 +108,66 @@ export const docs = {
{label: 'Status notice', code: `<XDSChatSystemMessage>Cindy shared a file</XDSChatSystemMessage>`},
],
},
+ {
+ name: 'XDSChatComposer',
+ description: 'Layout shell for a chat composer. Arranges named slots (attachments, toolbar, input, footer, send) with page-radius container, hover/focus shadows, and concentric inner radius for child elements.',
+ props: [
+ {name: 'onSubmit', type: '(value: string) => void', description: 'Called when the user submits a message.', required: true},
+ {name: 'onStop', type: '() => void', description: 'Called when the user requests to stop generation.'},
+ {name: 'isStreaming', type: 'boolean', description: 'Whether the assistant is currently streaming.', default: 'false'},
+ {name: 'value', type: 'string', description: 'Controlled input value.'},
+ {name: 'onChange', type: '(value: string) => void', description: 'Change handler for controlled mode.'},
+ {name: 'placeholder', type: 'string', description: 'Placeholder text.', default: "'Type a message\u2026'"},
+ {name: 'isDisabled', type: 'boolean', description: 'Disables the composer.', default: 'false'},
+ {name: 'density', type: "'compact' | 'balanced' | 'spacious'", description: 'Visual density.', default: "'balanced'"},
+ {name: 'attachments', type: 'ReactNode', description: 'Slot: attachment chips above the input. Use XDSChatComposerAttachments.'},
+ {name: 'contextToolbar', type: 'ReactNode', description: 'Slot: toolbar between attachments and input. Use XDSToolbar.'},
+ {name: 'input', type: 'ReactNode', description: 'Slot: custom input element. Replaces the default textarea. Use XDSChatComposerInput for trigger menus.'},
+ {name: 'footerActions', type: 'ReactNode', description: 'Slot: left-aligned footer actions (model selector, etc).'},
+ {name: 'sendActions', type: 'ReactNode', description: 'Slot: actions to the left of the send button.'},
+ {name: 'sendButton', type: 'ReactNode', description: 'Slot: custom send button. Replaces the default send/stop button.'},
+ {name: 'status', type: "{ type: 'error' | 'warning'; message?: string }", description: 'Status message below (or above) the composer.'},
+ {name: 'statusPosition', type: "'top' | 'bottom'", description: 'Where to render the status.', default: "'bottom'"},
+ ],
+
+ examples: [
+ {label: 'Simplest', code: '<XDSChatComposer onSubmit={handleSubmit} />'},
+ {label: 'With trigger menus', code: '<XDSChatComposer onSubmit={handleSubmit} input={<XDSChatComposerInput triggers={triggers} />} />'},
+ {label: 'Theme override', code: "defineTheme({ components: { 'chat-composer': { base: { '--composer-radius': '20px' } } } })"},
+ ],
+ },
+ {
+ name: 'XDSChatComposerInput',
+ description: 'ContentEditable-based rich input with trigger menus (@ mentions, / commands), inline tokens, serialization, message history, and paste/drop file handling. Uses XDSSearchSource for search.',
+ props: [
+ {name: 'ref', type: 'React.Ref<HTMLDivElement>', description: 'Ref to the root element.'},
+ {name: 'value', type: 'string', description: 'Controlled value.'},
+ {name: 'onChange', type: '(value: string) => void', description: 'Change handler.'},
+ {name: 'placeholder', type: 'string', description: 'Placeholder text.', default: "'Type a message\u2026'"},
+ {name: 'maxRows', type: 'number', description: 'Max rows before scrolling.', default: '8'},
+ {name: 'triggers', type: 'XDSChatComposerTrigger[]', description: 'Trigger definitions for menus. Each trigger has a character, searchSource, and onSelect.'},
+ {name: 'debounceMs', type: 'number', description: 'Debounce for async search sources.', default: '150'},
+ {name: 'hasHistory', type: 'boolean', description: 'Enable ArrowUp/Down message recall.', default: 'true'},
+ {name: 'label', type: 'string', description: 'Accessible label.', default: "'Message input'"},
+ {name: 'isDisabled', type: 'boolean', description: 'Disabled state.', default: 'false'},
+ {name: 'onPaste', type: '(event, text) => void', description: 'Paste handler.'},
+ {name: 'onFiles', type: '(files: File[]) => void', description: 'File drop/paste handler.'},
+ {name: 'onSubmit', type: '(value: string) => void', description: 'Submit handler (Enter without Shift).'},
+ ],
+ examples: [
+ {label: 'With mentions', code: `<XDSChatComposerInput triggers={[{ character: '@', searchSource: createStaticSource(users), onSelect: (item) => ({ value: '@' + item.id, render: () => <span>@{item.label}</span> }) }]} />`},
+ ],
+ },
+ {
+ name: 'XDSChatComposerAttachments',
+ description: 'Flex-wrap container for attachment items (tokens, thumbnails, previews) inside the composer.',
+ props: [
+ {name: 'children', type: 'ReactNode', description: 'Attachment items to render.', required: true},
+ {name: 'count', type: 'number', description: 'Total attachment count. When provided and exceeds visible children, shows a collapse/expand toggle.'},
+ ],
+ examples: [
+ {label: 'With tokens', code: `<XDSChatComposerAttachments>\n <XDSToken label="report.pdf" onDismiss={() => {}} />\n</XDSChatComposerAttachments>`},
+ ],
+ },
],
};
diff --git a/packages/core/src/Chat/README.md b/packages/core/src/Chat/README.md
index e7bed7aa1e..a7eee00510 100644
--- a/packages/core/src/Chat/README.md
+++ b/packages/core/src/Chat/README.md
@@ -1,26 +1,37 @@
# Chat
-Chat layout components for AI chat interfaces.
+Chat components for AI chat interfaces — layout (messages, bubbles) and composer (input, trigger menus, attachments).
## Files
-| File | Purpose |
-| -------------------------- | ----------------------------------------------------------------- |
-| `XDSChatMessageList.tsx` | Scrollable message container with auto-scroll and infinite scroll |
-| `XDSChatMessage.tsx` | Sender context wrapper — avatar, name, alignment by role |
-| `XDSChatMessageBubble.tsx` | Styled bubble container — reads sender from context |
-| `XDSChatSystemMessage.tsx` | Centered system/notice messages with optional divider |
-| `XDSChatContext.tsx` | Internal React contexts for sender and density propagation |
-| `index.ts` | Public exports |
+| File | Purpose |
+|------|---------|
+| `XDSChatMessageList.tsx` | Scrollable message container with auto-scroll and infinite scroll |
+| `XDSChatMessage.tsx` | Sender context wrapper — avatar, name, alignment by role |
+| `XDSChatMessageBubble.tsx` | Styled bubble container — reads sender from context |
+| `XDSChatMessageMetadata.tsx` | Timestamp + status display for bubbles |
+| `XDSChatSystemMessage.tsx` | Centered system/notice messages with optional divider |
+| `XDSChatComposer.tsx` | Layout shell with named slots, concentric radius, hover shadows |
+| `XDSChatComposerInput.tsx` | ContentEditable with trigger menus, tokens, history, paste/drop |
+| `XDSChatComposerAttachments.tsx` | Flex-wrap container for attachment items |
+| `useTriggerMenu.tsx` | Internal hook — trigger detection, popover, keyboard nav, search |
+| `useAutoScroll.ts` | Internal hook — auto-scroll and "new messages" detection |
+| `XDSChatContext.tsx` | Internal React contexts for sender and density propagation |
+| `index.ts` | Public exports |
## Architecture
```
-XDSChatMessageList — scrollable container, auto-scroll
- XDSChatSystemMessage — date separators, status notices
- XDSChatMessage — sender context (avatar, name, alignment)
- XDSChatMessageBubble — styled bubble (optional per content)
- (any other content) — asset lists, tool calls, images
+XDSChatMessageList — scrollable container, auto-scroll
+ XDSChatSystemMessage — date separators, status notices
+ XDSChatMessage — sender context (avatar, name, alignment)
+ XDSChatMessageBubble — styled bubble (optional per content)
+ (any other content) — asset lists, tool calls, images
+
+XDSChatComposer — layout shell with named slots
+ XDSChatComposerAttachments — attachment tokens/thumbnails
+ XDSChatComposerInput — contentEditable with trigger menus
+ useTriggerMenu — @ mentions, / commands via XDSSearchSource
```
## Context Flow
@@ -29,3 +40,47 @@ XDSChatMessageList — scrollable container, auto-scroll
- `XDSChatMessageContext` — sender + density from message to bubbles
Both contexts are internal (not exported). Only types are public.
+
+## Theming
+
+### Component CSS Vars
+
+| Var | Default | Description |
+|-----|---------|-------------|
+| `--composer-radius` | `var(--radius-page)` | Border radius of the composer body |
+| `--composer-padding` | `var(--spacing-3)` | Padding of the composer body |
+
+### Concentric Radius
+
+Inner elements (buttons, tokens) derive their radius from the container:
+
+```css
+--radius-element: calc(var(--composer-radius) - var(--composer-padding));
+```
+
+Default: `28px - 12px = 16px`, which fully rounds 32px buttons.
+
+Only `--radius-element` is overridden — `--radius-container` is left alone
+so popovers, hovercards, and tooltips keep their normal surface radius.
+
+### Theme Override Example
+
+```ts
+defineTheme({
+ components: {
+ 'chat-composer': {
+ base: {
+ '--composer-radius': '20px',
+ '--composer-padding': '16px',
+ },
+ },
+ },
+});
+```
+
+### Theming Targets
+
+| Class | Variants | States |
+|-------|----------|--------|
+| `xds-chat-composer` | density | — |
+| `xds-chat-composer-input` | — | — |
diff --git a/packages/core/src/Chat/XDSChatComposer.tsx b/packages/core/src/Chat/XDSChatComposer.tsx
index b518eef78c..915b50e980 100644
--- a/packages/core/src/Chat/XDSChatComposer.tsx
+++ b/packages/core/src/Chat/XDSChatComposer.tsx
@@ -8,11 +8,20 @@
*
* Layout shell for a chat composer. Arranges slots (attachments, toolbar,
* input, footer actions, send button, status) in a vertical stack with
- * page-radius container, hover/focus shadows, and scoped pill-radius
- * override for child elements.
+ * page-radius container, hover/focus shadows, and concentric inner radius.
+ *
+ * Component CSS vars (themeable via defineTheme):
+ * - `--composer-radius` (default: --radius-page) — outer border radius
+ * - `--composer-padding` (default: --spacing-3) — body padding
+ * - Inner element radius = calc(--composer-radius - --composer-padding)
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Chat/Chat.doc.mjs
+ * - /packages/core/src/Chat/README.md
+ * - /apps/storybook/stories/ChatComposer.stories.tsx
*/
-import {useState, useRef, useCallback, type ReactNode} from 'react';
+import {useState, useCallback, useMemo, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -27,6 +36,8 @@ import {
} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
import {XDSIcon} from '../Icon';
+import {XDSChatComposerInput} from './XDSChatComposerInput';
+import {XDSChatComposerContext} from './XDSChatContext';
// =============================================================================
// Types
@@ -91,9 +102,14 @@ const styles = stylex.create({
isolation: 'isolate',
display: 'flex',
flexDirection: 'column',
- // Scoped radius override: child buttons/tokens get pill shape
- [radiusVars['--radius-element'] as string]: radiusVars['--radius-full'],
- [radiusVars['--radius-container'] as string]: radiusVars['--radius-full'],
+ // Component CSS vars — themeable via defineTheme({ components: { 'chat-composer': { base: {...} } } })
+ '--composer-radius': radiusVars['--radius-page'],
+ '--composer-padding': spacingVars['--spacing-3'],
+ // Concentric radius: buttons follow the outer shell's curvature.
+ // Sets --button-radius (not --radius-element) so only buttons are
+ // affected — other components in slots keep their own radius.
+ // Default: 28px - 12px = 16px (fully rounds a 32px button).
+ '--button-radius': `max(${radiusVars['--radius-element']}, calc(var(--composer-radius) - var(--composer-padding)))`,
},
rootDisabled: {
@@ -105,9 +121,9 @@ const styles = stylex.create({
zIndex: 2,
display: 'flex',
flexDirection: 'column',
- padding: spacingVars['--spacing-3'],
+ padding: 'var(--composer-padding)',
gap: spacingVars['--spacing-2'],
- borderRadius: radiusVars['--radius-page'],
+ borderRadius: 'var(--composer-radius)',
backgroundColor: colorVars['--color-background-popover'],
boxShadow: {
default: shadowVars['--shadow-low'],
@@ -121,7 +137,6 @@ const styles = stylex.create({
inputArea: {
display: 'flex',
flexDirection: 'column',
- minHeight: '40px',
},
textarea: {
all: 'unset',
@@ -163,7 +178,7 @@ const styles = stylex.create({
justifyContent: 'center',
width: '32px',
height: '32px',
- borderRadius: radiusVars['--radius-full'],
+ borderRadius: 'var(--button-radius, var(--radius-full))',
border: 'none',
cursor: 'pointer',
transition: `opacity ${durationVars['--duration-fast']} ${easeVars['--ease-standard']}`,
@@ -193,18 +208,18 @@ const styles = stylex.create({
fontFamily: typographyVars['--font-family-body'],
},
statusTop: {
- paddingBlockStart: spacingVars['--spacing-3'],
- paddingBlockEnd: `calc(${spacingVars['--spacing-3']} + ${radiusVars['--radius-page']})`,
- marginBlockEnd: `calc(-1 * ${radiusVars['--radius-page']})`,
- borderTopLeftRadius: radiusVars['--radius-page'],
- borderTopRightRadius: radiusVars['--radius-page'],
+ paddingBlockStart: 'var(--composer-padding)',
+ paddingBlockEnd: 'calc(var(--composer-padding) + var(--composer-radius))',
+ marginBlockEnd: 'calc(-1 * var(--composer-radius))',
+ borderTopLeftRadius: 'var(--composer-radius)',
+ borderTopRightRadius: 'var(--composer-radius)',
},
statusBottom: {
- paddingBlockStart: `calc(${spacingVars['--spacing-3']} + ${radiusVars['--radius-page']})`,
- paddingBlockEnd: spacingVars['--spacing-3'],
- marginBlockStart: `calc(-1 * ${radiusVars['--radius-page']})`,
- borderBottomLeftRadius: radiusVars['--radius-page'],
- borderBottomRightRadius: radiusVars['--radius-page'],
+ paddingBlockStart: 'calc(var(--composer-padding) + var(--composer-radius))',
+ paddingBlockEnd: 'var(--composer-padding)',
+ marginBlockStart: 'calc(-1 * var(--composer-radius))',
+ borderBottomLeftRadius: 'var(--composer-radius)',
+ borderBottomRightRadius: 'var(--composer-radius)',
},
statusError: {
backgroundColor: colorVars['--color-error-muted'],
@@ -275,7 +290,6 @@ export function XDSChatComposer(props: XDSChatComposerProps) {
} = props;
const [internalValue, setInternalValue] = useState('');
- const textareaRef = useRef<HTMLTextAreaElement>(null);
const isControlled = controlledValue !== undefined;
const currentValue = isControlled ? controlledValue : internalValue;
@@ -295,30 +309,8 @@ export function XDSChatComposer(props: XDSChatComposerProps) {
if (!trimmed || isDisabled) return;
onSubmit(trimmed);
updateValue('');
- if (textareaRef.current) {
- textareaRef.current.style.height = 'auto';
- }
- }, [currentValue, isDisabled, onSubmit, updateValue]);
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- handleSubmit();
- }
- },
- [handleSubmit],
- );
- const handleInput = useCallback(
- (e: React.ChangeEvent<HTMLTextAreaElement>) => {
- const el = e.target;
- updateValue(el.value);
- el.style.height = 'auto';
- el.style.height = `${el.scrollHeight}px`;
- },
- [updateValue],
- );
+ }, [currentValue, isDisabled, onSubmit, updateValue]);
const canSend = currentValue.trim().length > 0 && !isDisabled;
@@ -355,7 +347,19 @@ export function XDSChatComposer(props: XDSChatComposerProps) {
</div>
) : null;
+ const composerContext = useMemo(
+ () => ({
+ value: currentValue,
+ onChange: updateValue,
+ onSubmit: handleSubmit,
+ placeholder,
+ isDisabled,
+ }),
+ [currentValue, updateValue, handleSubmit, placeholder, isDisabled],
+ );
+
return (
+ <XDSChatComposerContext.Provider value={composerContext}>
<div
{...mergeProps(
xdsClassName('chat-composer', {density}),
@@ -372,18 +376,7 @@ export function XDSChatComposer(props: XDSChatComposerProps) {
{contextToolbar}
<div {...stylex.props(styles.inputArea)}>
- {input ?? (
- <textarea
- ref={textareaRef}
- rows={1}
- value={currentValue}
- placeholder={placeholder}
- disabled={isDisabled}
- onKeyDown={handleKeyDown}
- onChange={handleInput}
- {...stylex.props(styles.textarea)}
- />
- )}
+ {input ?? <XDSChatComposerInput />}
</div>
<div {...stylex.props(styles.footer)}>
@@ -397,6 +390,7 @@ export function XDSChatComposer(props: XDSChatComposerProps) {
{statusPosition === 'bottom' && statusEl}
</div>
+ </XDSChatComposerContext.Provider>
);
}
diff --git a/packages/core/src/Chat/XDSChatComposerInput.test.tsx b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
new file mode 100644
index 0000000000..98c031968d
--- /dev/null
+++ b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
@@ -0,0 +1,236 @@
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {XDSChatComposerInput} from './XDSChatComposerInput';
+import type {XDSChatComposerTrigger} from './XDSChatComposerInput';
+import {createStaticSource} from '../Typeahead/createStaticSource';
+import type {XDSSearchableItem} from '../Typeahead/types';
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+const USERS: XDSSearchableItem[] = [
+ {id: 'cindy', label: 'Cindy Zhang'},
+ {id: 'alex', label: 'Alex Johnson'},
+ {id: 'sam', label: 'Sam Rivera'},
+];
+
+const COMMANDS: XDSSearchableItem[] = [
+ {id: 'summarize', label: 'summarize'},
+ {id: 'translate', label: 'translate'},
+ {id: 'search', label: 'search'},
+];
+
+function createMentionTrigger(
+ overrides?: Partial<XDSChatComposerTrigger>,
+): XDSChatComposerTrigger {
+ return {
+ character: '@',
+ searchSource: createStaticSource(USERS),
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: `@${item.label}`,
+ variant: 'blue' as const,
+ }),
+ ...overrides,
+ };
+}
+
+function createCommandTrigger(
+ overrides?: Partial<XDSChatComposerTrigger>,
+): XDSChatComposerTrigger {
+ return {
+ character: '/',
+ searchSource: createStaticSource(COMMANDS),
+ onSelect: item => `/${item.label} `,
+ ...overrides,
+ };
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('XDSChatComposerInput', () => {
+ describe('basic rendering', () => {
+ it('renders with placeholder', () => {
+ render(<XDSChatComposerInput placeholder="Type here..." />);
+ expect(screen.getByText('Type here...')).toBeInTheDocument();
+ });
+
+ it('renders with default placeholder', () => {
+ render(<XDSChatComposerInput />);
+ expect(screen.getByText(/Type a message/)).toBeInTheDocument();
+ });
+
+ it('renders a textbox role', () => {
+ render(<XDSChatComposerInput label="Test input" />);
+ expect(
+ screen.getByRole('textbox', {name: 'Test input'}),
+ ).toBeInTheDocument();
+ });
+
+ it('renders disabled state', () => {
+ render(<XDSChatComposerInput isDisabled />);
+ const textbox = screen.getByRole('textbox');
+ expect(textbox).toHaveAttribute('contenteditable', 'false');
+ });
+ });
+
+ describe('change and submit', () => {
+ it('calls onChange on input', () => {
+ const onChange = vi.fn();
+ render(<XDSChatComposerInput onChange={onChange} />);
+ const textbox = screen.getByRole('textbox');
+ textbox.textContent = 'hello';
+ fireEvent.input(textbox);
+ expect(onChange).toHaveBeenCalledWith('hello');
+ });
+
+ it('calls onSubmit on Enter', () => {
+ const onSubmit = vi.fn();
+ render(<XDSChatComposerInput onSubmit={onSubmit} />);
+ const textbox = screen.getByRole('textbox');
+ textbox.textContent = 'hello world';
+ fireEvent.input(textbox);
+ fireEvent.keyDown(textbox, {key: 'Enter'});
+ expect(onSubmit).toHaveBeenCalledWith('hello world');
+ });
+
+ it('does not submit on Shift+Enter', () => {
+ const onSubmit = vi.fn();
+ render(<XDSChatComposerInput onSubmit={onSubmit} />);
+ const textbox = screen.getByRole('textbox');
+ textbox.textContent = 'hello';
+ fireEvent.input(textbox);
+ fireEvent.keyDown(textbox, {key: 'Enter', shiftKey: true});
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it('clears input after submit', () => {
+ const onChange = vi.fn();
+ render(<XDSChatComposerInput onSubmit={() => {}} onChange={onChange} />);
+ const textbox = screen.getByRole('textbox');
+ textbox.textContent = 'hello';
+ fireEvent.input(textbox);
+ fireEvent.keyDown(textbox, {key: 'Enter'});
+ expect(onChange).toHaveBeenLastCalledWith('');
+ });
+
+ it('does not submit empty input', () => {
+ const onSubmit = vi.fn();
+ render(<XDSChatComposerInput onSubmit={onSubmit} />);
+ const textbox = screen.getByRole('textbox');
+ fireEvent.keyDown(textbox, {key: 'Enter'});
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('file handling', () => {
+ it('calls onFiles on paste with files', () => {
+ const onFiles = vi.fn();
+ render(<XDSChatComposerInput onFiles={onFiles} />);
+ const textbox = screen.getByRole('textbox');
+
+ const file = new File(['content'], 'test.txt', {type: 'text/plain'});
+ fireEvent.paste(textbox, {
+ clipboardData: {
+ files: [file],
+ getData: () => '',
+ },
+ });
+ expect(onFiles).toHaveBeenCalledWith([file]);
+ });
+ });
+
+ describe('triggers', () => {
+ it('accepts triggers with searchSource', () => {
+ const triggers = [createMentionTrigger()];
+ const {container} = render(<XDSChatComposerInput triggers={triggers} />);
+ expect(container).toBeTruthy();
+ });
+
+ it('accepts multiple triggers', () => {
+ const triggers = [createMentionTrigger(), createCommandTrigger()];
+ const {container} = render(<XDSChatComposerInput triggers={triggers} />);
+ expect(container).toBeTruthy();
+ });
+
+ it('accepts async searchSource trigger', () => {
+ const asyncTrigger: XDSChatComposerTrigger = {
+ character: '@',
+ searchSource: {
+ async search(query: string) {
+ return USERS.filter(u =>
+ u.label.toLowerCase().includes(query.toLowerCase()),
+ );
+ },
+ async bootstrap() {
+ return USERS;
+ },
+ cancel() {},
+ },
+ onSelect: item => ({
+ value: `@${item.id}`,
+ label: `@${item.label}`,
+ variant: 'blue' as const,
+ }),
+ };
+ const {container} = render(
+ <XDSChatComposerInput triggers={[asyncTrigger]} />,
+ );
+ expect(container).toBeTruthy();
+ });
+
+ it('renders with custom renderItem', () => {
+ const trigger = createMentionTrigger({
+ renderItem: item => <div data-testid="custom-item">{item.label}</div>,
+ });
+ const {container} = render(<XDSChatComposerInput triggers={[trigger]} />);
+ expect(container).toBeTruthy();
+ });
+
+ it('supports configurable empty/loading text', () => {
+ const trigger = createMentionTrigger({
+ emptySearchResultsText: 'Nobody found',
+ loadingText: 'Looking up...',
+ menuLabel: 'People',
+ });
+ const {container} = render(<XDSChatComposerInput triggers={[trigger]} />);
+ expect(container).toBeTruthy();
+ });
+ });
+
+ describe('accessibility', () => {
+ it('has aria-haspopup on the textbox', () => {
+ const triggers = [createMentionTrigger()];
+ render(<XDSChatComposerInput triggers={triggers} />);
+ const textbox = screen.getByRole('textbox');
+ expect(textbox).toHaveAttribute('aria-haspopup', 'listbox');
+ });
+
+ it('has aria-expanded=false when menu is closed', () => {
+ const triggers = [createMentionTrigger()];
+ render(<XDSChatComposerInput triggers={triggers} />);
+ const textbox = screen.getByRole('textbox');
+ expect(textbox).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+
+ describe('ref', () => {
+ it('forwards ref to root element', () => {
+ const ref = vi.fn();
+ render(<XDSChatComposerInput ref={ref} />);
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLDivElement));
+ });
+ });
+
+ describe('xds class names', () => {
+ it('has xds-chat-composer-input class', () => {
+ const {container} = render(<XDSChatComposerInput />);
+ expect(
+ container.querySelector('.xds-chat-composer-input'),
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsx
index 8f803844a8..5aa6321237 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx
@@ -2,11 +2,20 @@
/**
* @file XDSChatComposerInput.tsx
+ * @input Uses React, StyleX, useTriggerMenu, XDSSearchSource
+ * @output Exports XDSChatComposerInput rich input + trigger types
+ * @position Core implementation; consumed by index.ts, XDSChatComposer
+ *
* ContentEditable-based rich input for the chat composer.
- * Supports token rendering, serialization, Enter/Shift+Enter,
- * message history (ArrowUp/Down), paste/drop file handling.
+ * Supports trigger menus (@ mentions, / commands) via XDSSearchSource,
+ * inline token rendering, serialization, Enter/Shift+Enter, message
+ * history, paste/drop file handling.
+ *
*
- * NOTE: Trigger menu popover (@ mentions, / commands) is NOT yet implemented.
+ * SYNC: When modified, update:
+ * - /packages/core/src/Chat/index.ts
+ * - /apps/storybook/stories/ChatComposer.stories.tsx
+ * - /apps/storybook/stories/ChatComposerTriggers.stories.tsx
*/
import {
@@ -17,58 +26,131 @@ import {
type ReactNode,
type KeyboardEvent,
type ClipboardEvent,
- type DragEvent,
} from 'react';
+import {createPortal} from 'react-dom';
import type {XDSBaseProps} from '../XDSBaseProps';
+import type {XDSSearchableItem, XDSSearchSource} from '../Typeahead/types';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
spacingVars,
radiusVars,
- durationVars,
- easeVars,
- fontWeightVars,
typeScaleVars,
typographyVars,
} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
+import {useTriggerMenu} from './useTriggerMenu';
+import {XDSBadge, type XDSBadgeProps} from '../Badge';
// =============================================================================
// Types
// =============================================================================
-export type XDSChatComposerToken = {
+/** Badge config for the common case \u2014 structured, simple, autocomplete-friendly */
+export type XDSChatComposerTokenBadge = {
+ /** Serialized value \u2014 what this token becomes in the onSubmit string */
value: string;
+} & Omit<XDSBadgeProps, 'ref' | 'xstyle' | 'className' | 'style'>;
+
+/** Custom render for the escape hatch \u2014 tooltips, hovercards, rich content */
+export type XDSChatComposerTokenCustom = {
+ /** Serialized value \u2014 what this token becomes in the onSubmit string */
+ value: string;
+ /** Full control over the token\u2019s rendered content */
render: () => ReactNode;
};
-export type XDSChatComposerTriggerItem = {
- id: string;
- label: string;
- [key: string]: unknown;
-};
+/**
+ * Token inserted into the contentEditable by a trigger menu.
+ *
+ * Two forms:
+ * - **Badge config** (recommended): `{ value, label, variant?, icon? }` \u2014
+ * renders an XDSBadge. Structured, themeable, autocomplete-friendly.
+ * - **Custom render**: `{ value, render }` \u2014 full control via ReactNode.
+ * Use for tooltips, hovercards, or any content beyond a badge.
+ */
+export type XDSChatComposerToken =
+ | XDSChatComposerTokenBadge
+ | XDSChatComposerTokenCustom;
+
+export type XDSChatComposerTriggerItem = XDSSearchableItem;
export type XDSChatComposerTrigger = {
+ /** Character that activates this trigger menu (e.g. '@', '/') */
character: string;
- items?: XDSChatComposerTriggerItem[];
- queryItemsAction?: (query: string) => Promise<XDSChatComposerTriggerItem[]>;
- renderItem?: (item: XDSChatComposerTriggerItem) => ReactNode;
- onSelect: (item: XDSChatComposerTriggerItem) => XDSChatComposerToken;
+ /**
+ * Search source providing items for this trigger.
+ * Reuses the same XDSSearchSource interface as XDSTypeahead \u2014
+ * supports sync/async search, bootstrap, and cancel().
+ *
+ * Use `createStaticSource()` for static item lists,
+ * or implement XDSSearchSource for API-backed search.
+ *
+ * @example
+ * ```
+ * import {createStaticSource} from '@xds/core/Typeahead';
+ *
+ * const mentionTrigger = {
+ * character: '@',
+ * searchSource: createStaticSource(users),
+ * onSelect: (item) => ({ value: `@${item.id}`, render: () => ... }),
+ * };
+ * ```
+ */
+ searchSource: XDSSearchSource;
+ /** How to render each item in the trigger menu */
+ renderItem?: (item: XDSSearchableItem) => ReactNode;
+ /**
+ * What to insert when an item is selected.
+ * Return a string for plain text, or a Token for an inline chip.
+ */
+ onSelect: (item: XDSSearchableItem) => string | XDSChatComposerToken;
+ /**
+ * Parse serialized tokens back into rendered tokens.
+ * Used when loading a previous message for editing.
+ */
deserialize?: (value: string) => XDSChatComposerToken | null;
+ /** Text shown when no results found. @default 'No results' */
+ emptySearchResultsText?: string;
+ /** Text shown during async search. @default 'Searching\u2026' */
+ loadingText?: string;
+ /** Accessible label for the menu. @default 'Suggestions' */
+ menuLabel?: string;
};
-export interface XDSChatComposerInputProps
- extends Omit<XDSBaseProps<HTMLDivElement>, 'onChange' | 'onPaste' | 'onSubmit'> {
+export interface XDSChatComposerInputProps extends Omit<
+ XDSBaseProps<HTMLDivElement>,
+ 'onChange' | 'onPaste' | 'onSubmit'
+> {
+ /** Ref to the root element */
+ ref?: React.Ref<HTMLDivElement>;
+ /** Controlled value */
value?: string;
+ /** Change handler */
onChange?: (value: string) => void;
+ /** Placeholder text. @default 'Type a message\u2026' */
placeholder?: string;
+ /** Max rows before scrolling. @default 8 */
maxRows?: number;
+ /** Trigger definitions for @ menus, / commands, etc. */
triggers?: XDSChatComposerTrigger[];
+ /**
+ * Debounce delay in ms before triggering async search.
+ * Set to 0 for immediate search.
+ * @default 150
+ */
+ debounceMs?: number;
+ /** Enable message history recall. @default true */
hasHistory?: boolean;
+ /** Accessible label. @default 'Message input' */
label?: string;
+ /** Disabled state. @default false */
isDisabled?: boolean;
+ /** Paste handler */
onPaste?: (event: ClipboardEvent<HTMLDivElement>, text: string) => void;
+ /** File drop/paste handler */
onFiles?: (files: File[]) => void;
+ /** Submit handler (Enter without Shift) */
onSubmit?: (value: string) => void;
}
@@ -95,6 +177,7 @@ const styles = stylex.create({
fontFamily: typographyVars['--font-family-body'],
color: colorVars['--color-text-primary'],
caretColor: colorVars['--color-accent'],
+ padding: spacingVars['--spacing-1'],
},
placeholder: {
position: 'absolute',
@@ -102,36 +185,42 @@ const styles = stylex.create({
left: 0,
right: 0,
pointerEvents: 'none',
- color: colorVars['--color-text-disabled'],
+ color: colorVars['--color-text-secondary'],
fontSize: typeScaleVars['--text-body-size'],
lineHeight: `${LINE_HEIGHT_PX}px`,
fontFamily: typographyVars['--font-family-body'],
userSelect: 'none',
+ padding: spacingVars['--spacing-1'],
},
disabled: {
opacity: 0.5,
pointerEvents: 'none' as const,
},
- token: {
- display: 'inline-flex',
- alignItems: 'center',
- borderRadius: radiusVars['--radius-full'],
- backgroundColor: colorVars['--color-accent-muted'],
- color: colorVars['--color-text-accent'],
- fontWeight: fontWeightVars['--font-weight-medium'],
- paddingInline: spacingVars['--spacing-1-5'],
- paddingBlock: spacingVars['--spacing-0-5'],
- fontSize: typeScaleVars['--text-label-size'],
- lineHeight: typeScaleVars['--text-label-leading'],
- verticalAlign: 'baseline',
- userSelect: 'all',
- },
+
});
// =============================================================================
// Helpers
// =============================================================================
+
+/** Type guard: does this token use the custom render path? */
+function isCustomToken(
+ token: XDSChatComposerToken,
+): token is XDSChatComposerTokenCustom {
+ return 'render' in token && typeof token.render === 'function';
+}
+
+/** Select all text in a contentEditable element. */
+function selectAll(el: HTMLElement): void {
+ const selection = window.getSelection();
+ if (!selection) return;
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ selection.removeAllRanges();
+ selection.addRange(range);
+}
+
function serialize(node: Node): string {
let result = '';
for (const child of Array.from(node.childNodes)) {
@@ -150,17 +239,37 @@ function serialize(node: Node): string {
return result;
}
+/** Insert plain text at the current selection using the Selection API. */
+function insertTextAtCursor(text: string): void {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) return;
+
+ const range = selection.getRangeAt(0);
+ range.deleteContents();
+
+ const textNode = document.createTextNode(text);
+ range.insertNode(textNode);
+
+ // Move cursor after inserted text
+ range.setStartAfter(textNode);
+ range.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(range);
+}
+
// =============================================================================
// Component
// =============================================================================
export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const {
+ ref,
value: controlledValue,
onChange,
placeholder = 'Type a message\u2026',
maxRows = 8,
triggers,
+ debounceMs = 150,
hasHistory = true,
label = 'Message input',
isDisabled = false,
@@ -194,14 +303,80 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const text = serialize(editableRef.current);
setIsEmpty(text.length === 0);
onChange?.(text);
+ // Clean up portals for tokens no longer in the DOM
+ setTokenPortals(prev =>
+ prev.filter(p => editableRef.current?.contains(p.span)),
+ );
}, [onChange]);
+ // --- Token insertion ---
+ // Track inserted token spans for portal rendering
+ const [tokenPortals, setTokenPortals] = useState<
+ Array<{id: string; span: HTMLSpanElement; token: XDSChatComposerToken}>
+ >([]);
+
+ const insertToken = useCallback((token: XDSChatComposerToken) => {
+ const editable = editableRef.current;
+ if (!editable) return;
+
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) return;
+
+ const range = selection.getRangeAt(0);
+
+ // Create a non-editable container — React will portal the Badge into it
+ const span = document.createElement('span');
+ const id = `token-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ span.setAttribute('data-xds-token', '');
+ span.setAttribute('data-xds-token-value', token.value);
+ span.setAttribute('data-xds-token-id', id);
+ span.contentEditable = 'false';
+ span.style.display = 'inline-flex';
+ span.style.verticalAlign = 'baseline';
+
+ range.deleteContents();
+ range.insertNode(span);
+
+ // Add a non-breaking space after the token and move cursor there
+ const space = document.createTextNode('\u00A0');
+ span.after(space);
+
+ const newRange = document.createRange();
+ newRange.setStartAfter(space);
+ newRange.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(newRange);
+
+ // Register for portal rendering
+ setTokenPortals(prev => [...prev, {id, span, token}]);
+ }, []);
+
+ const insertText = useCallback((text: string) => {
+ insertTextAtCursor(text);
+ }, []);
+
+ // --- Trigger menu ---
+ const triggerMenu = useTriggerMenu({
+ triggers,
+ editableRef,
+ onInsertToken: insertToken,
+ onInsertText: insertText,
+ onEmitChange: emitChange,
+ debounceMs,
+ });
+
const handleInput = useCallback(() => {
emitChange();
- }, [emitChange]);
+ triggerMenu.handleInput();
+ }, [emitChange, triggerMenu]);
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLDivElement>) => {
+ // Let trigger menu consume the event first
+ if (triggerMenu.handleKeyDown(e)) {
+ return;
+ }
+
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!editableRef.current) return;
@@ -221,16 +396,13 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
return;
}
- // History navigation
+ // History navigation (only when trigger menu is not active)
if (hasHistory && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
if (!editableRef.current) return;
const text = serialize(editableRef.current);
const history = historyRef.current;
if (history.length === 0) return;
- const selection = window.getSelection();
- if (!selection || selection.rangeCount === 0) return;
-
if (e.key === 'ArrowUp') {
if (historyIndexRef.current === -1) {
currentDraftRef.current = text;
@@ -241,6 +413,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
: Math.max(0, historyIndexRef.current - 1);
historyIndexRef.current = nextIndex;
editableRef.current.textContent = history[nextIndex];
+ selectAll(editableRef.current);
emitChange();
e.preventDefault();
} else if (e.key === 'ArrowDown' && historyIndexRef.current !== -1) {
@@ -248,16 +421,18 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
if (nextIndex >= history.length) {
historyIndexRef.current = -1;
editableRef.current.textContent = currentDraftRef.current;
+ if (currentDraftRef.current) selectAll(editableRef.current);
} else {
historyIndexRef.current = nextIndex;
editableRef.current.textContent = history[nextIndex];
+ selectAll(editableRef.current);
}
emitChange();
e.preventDefault();
}
}
},
- [hasHistory, onSubmit, onChange, emitChange],
+ [hasHistory, onSubmit, onChange, emitChange, triggerMenu],
);
const handlePaste = useCallback(
@@ -271,7 +446,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
- document.execCommand('insertText', false, text);
+ insertTextAtCursor(text);
onPasteProp?.(e, text);
emitChange();
@@ -279,33 +454,18 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
[onFiles, onPasteProp, emitChange],
);
- const handleDrop = useCallback(
- (e: DragEvent<HTMLDivElement>) => {
- const files = Array.from(e.dataTransfer.files);
- if (files.length > 0) {
- e.preventDefault();
- onFiles?.(files);
- }
- },
- [onFiles],
- );
-
const maxHeight = maxRows * LINE_HEIGHT_PX;
return (
<div
+ ref={ref}
{...mergeProps(
xdsClassName('chat-composer-input'),
- stylex.props(
- styles.root,
- isDisabled && styles.disabled,
- xstyle,
- ),
+ stylex.props(styles.root, isDisabled && styles.disabled, xstyle),
className,
style,
)}
- {...rest}
- >
+ {...rest}>
{isEmpty && (
<div {...stylex.props(styles.placeholder)} aria-hidden="true">
{placeholder}
@@ -321,10 +481,26 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
onInput={handleInput}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
- onDrop={handleDrop}
+ {...triggerMenu.ariaProps}
{...stylex.props(styles.editable)}
style={{maxHeight: `${maxHeight}px`}}
/>
+ {triggerMenu.renderMenu()}
+ {tokenPortals.map(({id, span, token}) =>
+ createPortal(
+ isCustomToken(token) ? (
+ <span key={id}>{token.render()}</span>
+ ) : (
+ <XDSBadge
+ key={id}
+ label={token.label}
+ variant={token.variant}
+ icon={token.icon}
+ />
+ ),
+ span,
+ ),
+ )}
</div>
);
}
@@ -332,7 +508,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
XDSChatComposerInput.displayName = 'XDSChatComposerInput';
// =============================================================================
-// Token element helper
+// Token element helper (for custom rendering in stories/consumers)
// =============================================================================
export function XDSChatComposerTokenElement({
@@ -345,9 +521,16 @@ export function XDSChatComposerTokenElement({
data-xds-token=""
data-xds-token-value={token.value}
contentEditable={false}
- {...stylex.props(styles.token)}
- >
- {token.render()}
+ style={{display: 'inline-flex', verticalAlign: 'baseline'}}>
+ {isCustomToken(token) ? (
+ token.render()
+ ) : (
+ <XDSBadge
+ label={token.label}
+ variant={token.variant}
+ icon={token.icon}
+ />
+ )}
</span>
);
}
diff --git a/packages/core/src/Chat/XDSChatContext.tsx b/packages/core/src/Chat/XDSChatContext.tsx
index 4c28c4139c..223296f536 100644
--- a/packages/core/src/Chat/XDSChatContext.tsx
+++ b/packages/core/src/Chat/XDSChatContext.tsx
@@ -35,3 +35,22 @@ export const XDSChatListContext = createContext<XDSChatListContextValue | null>(
export function useXDSChatListContext(): XDSChatListContextValue | null {
return useContext(XDSChatListContext);
}
+
+// =============================================================================
+// Composer context — shared state between XDSChatComposer and XDSChatComposerInput
+// =============================================================================
+
+export interface XDSChatComposerContextValue {
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: (value: string) => void;
+ placeholder: string;
+ isDisabled: boolean;
+}
+
+export const XDSChatComposerContext =
+ createContext<XDSChatComposerContextValue | null>(null);
+
+export function useXDSChatComposerContext(): XDSChatComposerContextValue | null {
+ return useContext(XDSChatComposerContext);
+}
diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsx
new file mode 100644
index 0000000000..e7453113b1
--- /dev/null
+++ b/packages/core/src/Chat/useTriggerMenu.tsx
@@ -0,0 +1,615 @@
+'use client';
+
+/**
+ * @file useTriggerMenu.tsx
+ * @input Uses React, useXDSPopover, XDSSearchSource
+ * @output Exports useTriggerMenu hook for trigger-based menus in contentEditable
+ * @position Internal hook; consumed by XDSChatComposerInput
+ *
+ * Detects trigger characters (@ / etc.) typed inside a contentEditable,
+ * opens a popover at the cursor position with filtered items, handles
+ * keyboard navigation, and inserts tokens or text on selection.
+ *
+ * Reuses XDSSearchSource from Typeahead for async/sync search with
+ * cancel() support and debounce.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Chat/XDSChatComposerInput.tsx
+ * - /packages/core/src/Chat/index.ts
+ */
+
+import {
+ useState,
+ useCallback,
+ useRef,
+ useEffect,
+ useId,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {useXDSPopover} from '../Popover/useXDSPopover';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ typeScaleVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
+import {xdsClassName, mergeProps, groupItems} from '../utils';
+import type {XDSSearchableItem, XDSSearchSource} from '../Typeahead/types';
+import type {
+ XDSChatComposerTrigger,
+ XDSChatComposerToken,
+} from './XDSChatComposerInput';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface TriggerMenuState {
+ isActive: boolean;
+ activeTrigger: XDSChatComposerTrigger | null;
+ query: string;
+ items: XDSSearchableItem[];
+ highlightedIndex: number;
+ isLoading: boolean;
+}
+
+export interface UseTriggerMenuOptions {
+ triggers?: XDSChatComposerTrigger[];
+ editableRef: React.RefObject<HTMLDivElement | null>;
+ onInsertToken: (token: XDSChatComposerToken) => void;
+ onInsertText: (text: string) => void;
+ onEmitChange: () => void;
+ /**
+ * Debounce delay in ms before triggering search after typing.
+ * @default 150
+ */
+ debounceMs?: number;
+}
+
+export interface UseTriggerMenuReturn {
+ state: TriggerMenuState;
+ /** Call on every input event to check for trigger activation */
+ handleInput: () => void;
+ /** Call on keydown \u2014 returns true if the event was consumed */
+ handleKeyDown: (e: React.KeyboardEvent) => boolean;
+ /** Render the trigger menu popover */
+ renderMenu: () => ReactNode;
+ /** Reset/close the trigger menu */
+ reset: () => void;
+ /** ARIA props to spread onto the textbox element */
+ ariaProps: {
+ 'aria-expanded'?: boolean;
+ 'aria-controls'?: string;
+ 'aria-activedescendant'?: string;
+ 'aria-haspopup'?: 'listbox';
+ };
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ dropdown: {
+ boxSizing: 'border-box',
+ maxHeight: '240px',
+ overflowY: 'auto',
+ padding: spacingVars['--spacing-1'],
+ minWidth: '180px',
+ },
+ popoverSurface: {
+ minWidth: '180px',
+ },
+ popoverGap: {
+ marginBlockStart: spacingVars['--spacing-1'],
+ marginBlockEnd: spacingVars['--spacing-1'],
+ },
+ item: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ alignItems: 'center',
+ width: '100%',
+ padding: spacingVars['--spacing-2'],
+ borderRadius: radiusVars['--radius-element'],
+ cursor: 'pointer',
+ outline: 'none',
+ backgroundColor: 'transparent',
+ border: 'none',
+ textAlign: 'left' as const,
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-body-size'],
+ lineHeight: typeScaleVars['--text-body-leading'],
+ color: colorVars['--color-text-primary'],
+ },
+ itemHighlighted: {
+ backgroundColor: colorVars['--color-overlay-hover'],
+ },
+ itemLabel: {
+ flex: 1,
+ minWidth: 0,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ emptyState: {
+ padding: spacingVars['--spacing-3'],
+ textAlign: 'center' as const,
+ fontSize: typeScaleVars['--text-supporting-size'],
+ color: colorVars['--color-text-secondary'],
+ },
+ loadingState: {
+ padding: spacingVars['--spacing-3'],
+ textAlign: 'center' as const,
+ fontSize: typeScaleVars['--text-supporting-size'],
+ color: colorVars['--color-text-secondary'],
+ },
+ groupHeading: {
+ paddingInline: spacingVars['--spacing-2'],
+ paddingBlockStart: spacingVars['--spacing-2'],
+ paddingBlockEnd: spacingVars['--spacing-1'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ color: colorVars['--color-text-secondary'],
+ userSelect: 'none',
+ },
+});
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function getTextBeforeCursor(editable: HTMLDivElement): string | null {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) return null;
+
+ const range = selection.getRangeAt(0);
+ if (!range.collapsed) return null;
+ if (!editable.contains(range.startContainer)) return null;
+
+ const node = range.startContainer;
+ if (node.nodeType === Node.TEXT_NODE) {
+ return (node.textContent ?? '').slice(0, range.startOffset);
+ }
+
+ return null;
+}
+
+function findActiveTrigger(
+ textBeforeCursor: string,
+ triggers: XDSChatComposerTrigger[],
+): {
+ trigger: XDSChatComposerTrigger;
+ query: string;
+ triggerStart: number;
+} | null {
+ for (let i = textBeforeCursor.length - 1; i >= 0; i--) {
+ const char = textBeforeCursor[i];
+
+ if (char === ' ' || char === '\n') {
+ return null;
+ }
+
+ for (const trigger of triggers) {
+ if (char === trigger.character) {
+ const prevChar = i > 0 ? textBeforeCursor[i - 1] : null;
+ if (prevChar === null || prevChar === ' ' || prevChar === '\n') {
+ const query = textBeforeCursor.slice(i + 1);
+ return {trigger, query, triggerStart: i};
+ }
+ }
+ }
+ }
+
+ return null;
+}
+
+function deleteTriggerText(
+ editable: HTMLDivElement,
+ triggerStart: number,
+): void {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) return;
+
+ const range = selection.getRangeAt(0);
+ const node = range.startContainer;
+ if (node.nodeType !== Node.TEXT_NODE) return;
+
+ const text = node.textContent ?? '';
+ const cursorOffset = range.startOffset;
+
+ const before = text.slice(0, triggerStart);
+ const after = text.slice(cursorOffset);
+ node.textContent = before + after;
+
+ const newRange = document.createRange();
+ newRange.setStart(node, triggerStart);
+ newRange.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(newRange);
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+export function useTriggerMenu(
+ options: UseTriggerMenuOptions,
+): UseTriggerMenuReturn {
+ const {
+ triggers,
+ editableRef,
+ onInsertToken,
+ onInsertText,
+ onEmitChange,
+ debounceMs = 150,
+ } = options;
+
+ const listboxId = useId();
+ const [state, setState] = useState<TriggerMenuState>({
+ isActive: false,
+ activeTrigger: null,
+ query: '',
+ items: [],
+ highlightedIndex: 0,
+ isLoading: false,
+ });
+
+ const triggerStartRef = useRef<number>(-1);
+ const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const popover = useXDSPopover({
+ onHide: useCallback(() => {
+ setState(prev => ({
+ ...prev,
+ isActive: false,
+ activeTrigger: null,
+ query: '',
+ items: [],
+ highlightedIndex: 0,
+ isLoading: false,
+ }));
+ }, []),
+ hasLightDismiss: true,
+ hasCloseButton: false,
+ hasAutoFocus: false,
+ });
+
+ // Cleanup on unmount
+ useEffect(() => {
+ return () => {
+ if (searchTimeoutRef.current) {
+ clearTimeout(searchTimeoutRef.current);
+ }
+ };
+ }, []);
+
+ const reset = useCallback(() => {
+ if (searchTimeoutRef.current) {
+ clearTimeout(searchTimeoutRef.current);
+ searchTimeoutRef.current = null;
+ }
+ // Cancel any in-flight search on the active trigger's searchSource
+ const trigger = state.activeTrigger;
+ if (trigger?.searchSource) {
+ trigger.searchSource.cancel?.();
+ }
+ popover.hide();
+ triggerStartRef.current = -1;
+ }, [popover, state.activeTrigger]);
+
+ const setAnchor = useCallback(() => {
+ const editable = editableRef.current;
+ if (!editable) return;
+ popover.triggerRef(editable);
+ }, [editableRef, popover]);
+
+ const searchItems = useCallback(
+ (trigger: XDSChatComposerTrigger, query: string) => {
+ // Clear any pending debounce
+ if (searchTimeoutRef.current) {
+ clearTimeout(searchTimeoutRef.current);
+ searchTimeoutRef.current = null;
+ }
+
+ const doSearch = () => {
+ if (trigger.searchSource) {
+ // Use XDSSearchSource \u2014 cancel previous, then search
+ trigger.searchSource.cancel?.();
+ setState(prev => ({...prev, isLoading: true}));
+ const result = trigger.searchSource.search(query);
+ Promise.resolve(result).then(
+ items => {
+ setState(prev => ({
+ ...prev,
+ items,
+ highlightedIndex: items.length > 0 ? 0 : -1,
+ isLoading: false,
+ }));
+ },
+ () => {
+ setState(prev => ({
+ ...prev,
+ items: [],
+ highlightedIndex: -1,
+ isLoading: false,
+ }));
+ },
+ );
+ }
+ };
+
+ // Debounce async sources, immediate for sync
+ if (trigger.searchSource) {
+ // Check if search is likely sync (returns array, not promise)
+ const testResult = trigger.searchSource.search('');
+ const isAsync = testResult instanceof Promise;
+ if (isAsync && debounceMs > 0) {
+ setState(prev => ({...prev, isLoading: true}));
+ searchTimeoutRef.current = setTimeout(doSearch, debounceMs);
+ } else {
+ doSearch();
+ }
+ }
+ },
+ [debounceMs],
+ );
+
+ const selectItem = useCallback(
+ (item: XDSSearchableItem) => {
+ const trigger = state.activeTrigger;
+ if (!trigger) return;
+
+ const editable = editableRef.current;
+ if (!editable) return;
+
+ deleteTriggerText(editable, triggerStartRef.current);
+
+ const result = trigger.onSelect(item);
+ if (typeof result === 'string') {
+ onInsertText(result);
+ } else {
+ onInsertToken(result);
+ }
+
+ onEmitChange();
+ reset();
+ },
+ [
+ state.activeTrigger,
+ editableRef,
+ onInsertText,
+ onInsertToken,
+ onEmitChange,
+ reset,
+ ],
+ );
+
+ const handleInput = useCallback(() => {
+ if (!triggers || triggers.length === 0) return;
+
+ const editable = editableRef.current;
+ if (!editable) return;
+
+ const textBefore = getTextBeforeCursor(editable);
+ if (textBefore === null) {
+ if (state.isActive) reset();
+ return;
+ }
+
+ const found = findActiveTrigger(textBefore, triggers);
+ if (!found) {
+ if (state.isActive) reset();
+ return;
+ }
+
+ const {trigger, query, triggerStart} = found;
+
+ if (!state.isActive || state.activeTrigger !== trigger) {
+ triggerStartRef.current = triggerStart;
+ setState(prev => ({
+ ...prev,
+ isActive: true,
+ activeTrigger: trigger,
+ query,
+ highlightedIndex: 0,
+ }));
+ setAnchor();
+ searchItems(trigger, query);
+ popover.show();
+ } else if (state.query !== query) {
+ setState(prev => ({...prev, query}));
+ searchItems(trigger, query);
+ }
+ }, [
+ triggers,
+ editableRef,
+ state.isActive,
+ state.activeTrigger,
+ state.query,
+ reset,
+ setAnchor,
+ searchItems,
+ popover,
+ ]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent): boolean => {
+ if (!state.isActive || !popover.isOpen) return false;
+
+ switch (e.key) {
+ case 'ArrowDown': {
+ e.preventDefault();
+ setState(prev => ({
+ ...prev,
+ highlightedIndex:
+ prev.highlightedIndex < prev.items.length - 1
+ ? prev.highlightedIndex + 1
+ : 0,
+ }));
+ return true;
+ }
+ case 'ArrowUp': {
+ e.preventDefault();
+ setState(prev => ({
+ ...prev,
+ highlightedIndex:
+ prev.highlightedIndex > 0
+ ? prev.highlightedIndex - 1
+ : prev.items.length - 1,
+ }));
+ return true;
+ }
+ case 'Enter':
+ case 'Tab': {
+ if (
+ state.highlightedIndex >= 0 &&
+ state.highlightedIndex < state.items.length
+ ) {
+ e.preventDefault();
+ selectItem(state.items[state.highlightedIndex]);
+ return true;
+ }
+ return false;
+ }
+ case 'Escape': {
+ e.preventDefault();
+ reset();
+ return true;
+ }
+ default:
+ return false;
+ }
+ },
+ [
+ state.isActive,
+ state.highlightedIndex,
+ state.items,
+ popover.isOpen,
+ selectItem,
+ reset,
+ ],
+ );
+
+ const getItemId = useCallback(
+ (index: number) => `${listboxId}-option-${index}`,
+ [listboxId],
+ );
+
+ // Scroll highlighted item into view on keyboard navigation
+ useEffect(() => {
+ if (!popover.isOpen || state.highlightedIndex < 0) return;
+ const el = document.getElementById(getItemId(state.highlightedIndex));
+ el?.scrollIntoView({block: 'nearest'});
+ }, [state.highlightedIndex, popover.isOpen, getItemId]);
+
+ // ARIA props for the textbox element
+ const ariaProps =
+ state.isActive && popover.isOpen
+ ? {
+ 'aria-expanded': true as const,
+ 'aria-controls': listboxId,
+ 'aria-activedescendant':
+ state.highlightedIndex >= 0
+ ? getItemId(state.highlightedIndex)
+ : undefined,
+ 'aria-haspopup': 'listbox' as const,
+ }
+ : {
+ 'aria-expanded': false as const,
+ 'aria-haspopup': 'listbox' as const,
+ };
+
+ const renderMenu = useCallback((): ReactNode => {
+ const trigger = state.activeTrigger;
+ const emptyText = trigger?.emptySearchResultsText ?? 'No results';
+ const loadingText = trigger?.loadingText ?? 'Searching\u2026';
+
+ return popover.render(
+ <div
+ id={listboxId}
+ role="listbox"
+ aria-label={trigger?.menuLabel ?? 'Suggestions'}
+ {...mergeProps(
+ xdsClassName('trigger-menu'),
+ stylex.props(styles.dropdown),
+ )}>
+ {state.isLoading ? (
+ <div role="status" {...stylex.props(styles.loadingState)}>
+ {loadingText}
+ </div>
+ ) : state.items.length === 0 && state.isActive ? (
+ <div {...stylex.props(styles.emptyState)}>{emptyText}</div>
+ ) : (
+ (() => {
+ const groups = groupItems(state.items);
+ let flatIndex = 0;
+ return groups.map(group => {
+ const groupItems = group.items.map(item => {
+ const idx = flatIndex++;
+ return (
+ <div
+ key={item.id}
+ id={getItemId(idx)}
+ role="option"
+ aria-selected={idx === state.highlightedIndex}
+ tabIndex={-1}
+ onMouseDown={e => {
+ e.preventDefault(); // Keep focus in the editable
+ selectItem(item);
+ }}
+ onMouseEnter={() =>
+ setState(prev => ({...prev, highlightedIndex: idx}))
+ }
+ {...stylex.props(
+ styles.item,
+ idx === state.highlightedIndex && styles.itemHighlighted,
+ )}>
+ {trigger?.renderItem ? (
+ trigger.renderItem(item)
+ ) : (
+ <span {...stylex.props(styles.itemLabel)}>
+ {item.label}
+ </span>
+ )}
+ </div>
+ );
+ });
+ if (group.heading) {
+ return (
+ <div
+ key={`group-${group.heading}`}
+ role="group"
+ aria-label={group.heading}>
+ <div
+ aria-hidden="true"
+ {...stylex.props(styles.groupHeading)}>
+ {group.heading}
+ </div>
+ {groupItems}
+ </div>
+ );
+ }
+ return groupItems;
+ });
+ })()
+ )}
+ </div>,
+ {
+ placement: 'above',
+ alignment: 'start',
+ xstyle: [styles.popoverSurface, styles.popoverGap],
+ },
+ );
+ }, [popover, listboxId, state, selectItem, getItemId]);
+
+ return {
+ state,
+ handleInput,
+ handleKeyDown,
+ renderMenu,
+ reset,
+ ariaProps,
+ };
+}
diff --git a/packages/core/src/utils/groupItems.ts b/packages/core/src/utils/groupItems.ts
new file mode 100644
index 0000000000..8b510de48d
--- /dev/null
+++ b/packages/core/src/utils/groupItems.ts
@@ -0,0 +1,87 @@
+/**
+ * @file groupItems.ts
+ * @input Array of XDSSearchableItem with optional auxiliaryData.group
+ * @output Grouped structure preserving insertion order
+ * @position Shared utility; used by CommandPalette, trigger menu, and
+ * any future component that needs to group search results by category.
+ */
+
+import type {XDSSearchableItem} from '../Typeahead/types';
+
+/**
+ * A group of items with an optional heading.
+ * `heading` is null for ungrouped items.
+ */
+export interface ItemGroup<T extends XDSSearchableItem = XDSSearchableItem> {
+ heading: string | null;
+ items: T[];
+}
+
+/**
+ * Extract the group string from an item's auxiliaryData.
+ */
+export function getItemGroup(item: XDSSearchableItem): string | undefined {
+ const aux = item.auxiliaryData as Record<string, unknown> | undefined;
+ return typeof aux?.group === 'string' ? aux.group : undefined;
+}
+
+/**
+ * Group items by `auxiliaryData.group`, preserving insertion order of groups.
+ * Ungrouped items are collected into a final group with `heading: null`.
+ *
+ * If no items have a group, returns a single entry with `heading: null`.
+ *
+ * @example
+ * ```
+ * const items = [
+ * {id: '1', label: 'Home', auxiliaryData: {group: 'Navigation'}},
+ * {id: '2', label: 'Settings', auxiliaryData: {group: 'Navigation'}},
+ * {id: '3', label: 'Dark mode', auxiliaryData: {group: 'Preferences'}},
+ * {id: '4', label: 'Help'},
+ * ];
+ *
+ * groupItems(items)
+ * // [
+ * // {heading: 'Navigation', items: [{id:'1',...}, {id:'2',...}]},
+ * // {heading: 'Preferences', items: [{id:'3',...}]},
+ * // {heading: null, items: [{id:'4',...}]},
+ * // ]
+ * ```
+ */
+export function groupItems<T extends XDSSearchableItem>(
+ items: T[],
+): ItemGroup<T>[] {
+ const hasGroups = items.some(item => getItemGroup(item) != null);
+
+ if (!hasGroups) {
+ return [{heading: null, items}];
+ }
+
+ const groupOrder: string[] = [];
+ const groups = new Map<string, T[]>();
+ const ungrouped: T[] = [];
+
+ for (const item of items) {
+ const group = getItemGroup(item);
+ if (group != null) {
+ if (!groups.has(group)) {
+ groupOrder.push(group);
+ groups.set(group, []);
+ }
+ groups.get(group)!.push(item);
+ } else {
+ ungrouped.push(item);
+ }
+ }
+
+ const result: ItemGroup<T>[] = groupOrder.map(heading => ({
+ heading,
+ items: groups.get(heading)!,
+ }));
+
+ if (ungrouped.length > 0) {
+ result.push({heading: null, items: ungrouped});
+ }
+
+ return result;
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index d3c617bb0a..10748871b2 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -34,3 +34,5 @@ export {parseStyleKey} from './parseStyleKey';
export {xdsClassName} from './xdsClassName';
export {mergeProps} from './mergeProps';
+export {groupItems, getItemGroup} from './groupItems';
+export type {ItemGroup} from './groupItems';