An open source design system that's fully customizable and agent ready
TypeScript
feat: XDSChatComposer — chat composer layout + input (#1182)
Cindy Zhang7e944bf54b95
diff --git a/CLAUDE.md b/CLAUDE.mdindex ca5d794d61..00360bf40a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -111,7 +111,7 @@ Look for `<!-- SYNC: ... -->` comments and `SYNC:` in file headers as reminders.|VARS: stylex.defineVars, stylex.createTheme (require .stylex.ts files) — YES|LAYOUT: grid, flex+gap, aspect-ratio, overscrollBehavior, scrollbar-gutter/width — YES|PATTERN: dialog entry animation -> @starting-style (not useState+rAF)-|PATTERN: parent hover child style -> stylex.when.ancestor(':hover') (not CSS nesting)+|PATTERN: parent hover child style -> stylex.when.ancestor(':hover') (not CSS nesting). Ancestor element MUST have stylex.defaultMarker() in its stylex.props() call|PATTERN: hover on touch -> @media (hover: hover) guard|PATTERN: zebra striping -> :nth-child(even) (not index%2 JS)|PATTERN: container responsive -> @container (not ResizeObserver)@@ -123,6 +123,7 @@ Look for `<!-- SYNC: ... -->` comments and `SYNC:` in file headers as reminders.<!-- STYLEX-CAPS:END --><!-- XDS-CLI:START -->+XDS v0.0.4|Always run npx xds component <Name> before writing XDS component code.npx xds component <Name> props, usage, examples for any componentnpx xds component --list 95 components by category@@ -132,4 +133,5 @@ npx xds upgrade --apply run version migration codemods--detail compact|brief less output | --lang dense|zh translationRULE: after @xds/core bump, always run npx xds upgrade --applyRULE: when swizzling, always use --gap to report missing capabilities+<!-- XDS-CLI:END -->diff --git a/apps/storybook/stories/ChatComposer.stories.tsx b/apps/storybook/stories/ChatComposer.stories.tsxnew file mode 100644index 0000000000..dea52cf26d--- /dev/null+++ b/apps/storybook/stories/ChatComposer.stories.tsx@@ -0,0 +1,213 @@+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSChatComposer,+ XDSChatComposerAttachments,+ XDSChatComposerInput,+} from '@xds/core/Chat';+import {XDSToken} from '@xds/core/Token';+import {XDSToolbar} from '@xds/core/Toolbar';+import {XDSButton} from '@xds/core/Button';+import {useState} from 'react';++const meta: Meta<typeof XDSChatComposer> = {+ title: 'Chat/XDSChatComposer',+ component: XDSChatComposer,+ tags: ['autodocs'],+ parameters: {+ layout: 'centered',+ },+ decorators: [+ Story => (+ <div style={{width: 600, padding: 40}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof XDSChatComposer>;++// =============================================================================+// Stories+// =============================================================================++/** Simplest usage — just onSubmit */+export const Simplest: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={value => {+ console.log('Submit:', value);+ alert(`Sent: ${value}`);+ }}+ />+ ),+};++/** With streaming state and stop button */+export const WithStreaming: Story = {+ render: () => {+ const [isStreaming, setIsStreaming] = useState(true);+ return (+ <XDSChatComposer+ onSubmit={value => {+ console.log('Submit:', value);+ setIsStreaming(true);+ }}+ isStreaming={isStreaming}+ onStop={() => {+ console.log('Stopped');+ setIsStreaming(false);+ }}+ />+ );+ },+};++/** With footer actions (model selector, mic button) */+export const WithFooterActions: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={value => console.log('Submit:', value)}+ footerActions={+ <>+ <XDSButton label="GPT-4" variant="ghost" size="md" />+ <XDSButton label="Mic" variant="ghost" size="md" />+ </>+ }+ />+ ),+};++/** With attachment chips and a context toolbar */+export const WithAttachments: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={value => console.log('Submit:', value)}+ attachments={+ <XDSChatComposerAttachments>+ <XDSToken label="report.pdf" onDismiss={() => {}} />+ <XDSToken label="data.csv" onDismiss={() => {}} />+ </XDSChatComposerAttachments>+ }+ contextToolbar={+ <XDSToolbar size="sm">+ <XDSButton label="Add context" variant="ghost" size="sm" />+ </XDSToolbar>+ }+ />+ ),+};++/** Full featured — all slots populated */+export const FullFeatured: Story = {+ render: () => {+ const [isStreaming, setIsStreaming] = useState(false);+ return (+ <XDSChatComposer+ onSubmit={value => {+ console.log('Submit:', value);+ setIsStreaming(true);+ setTimeout(() => setIsStreaming(false), 3000);+ }}+ isStreaming={isStreaming}+ onStop={() => setIsStreaming(false)}+ placeholder="Ask me anything..."+ attachments={+ <XDSChatComposerAttachments>+ <XDSToken label="design-spec.pdf" onDismiss={() => {}} />+ </XDSChatComposerAttachments>+ }+ contextToolbar={+ <XDSToolbar size="sm">+ <XDSButton label="@workspace" variant="ghost" size="sm" />+ </XDSToolbar>+ }+ footerActions={+ <>+ <XDSButton label="Attach" variant="ghost" size="md" />+ <XDSButton label="GPT-4o" variant="ghost" size="md" />+ </>+ }+ sendActions={<XDSButton label="Schedule" variant="ghost" size="md" />}+ />+ );+ },+};++/** Disabled state */+export const Disabled: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={() => {}}+ isDisabled+ placeholder="Composer is disabled"+ />+ ),+};++/** With many attachments and collapsible drawer */+export const WithManyAttachments: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={value => console.log('Submit:', value)}+ attachments={+ <XDSChatComposerAttachments count={6}>+ <XDSToken label="new_feature_prd.docx" onDismiss={() => {}} />+ <XDSToken label="2026_roadmap.docx" onDismiss={() => {}} />+ <XDSToken label="user_flow.pdf" onDismiss={() => {}} />+ <XDSToken label="launch_plan.docx" onDismiss={() => {}} />+ <XDSToken label="user_feedback.csv" onDismiss={() => {}} />+ <XDSToken label="kpis.csv" onDismiss={() => {}} />+ </XDSChatComposerAttachments>+ }+ />+ ),+};++/** With error status */+export const WithError: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={value => console.log('Submit:', value)}+ status={{+ type: 'error',+ message: 'Failed to send message. Please try again.',+ }}+ />+ ),+};++/** With attachments and status on top */+export const WithAttachmentsAndStatusTop: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={value => console.log('Submit:', value)}+ statusPosition="top"+ attachments={+ <XDSChatComposerAttachments count={3}>+ <XDSToken label="report.pdf" onDismiss={() => {}} />+ <XDSToken label="data.csv" onDismiss={() => {}} />+ <XDSToken label="notes.docx" onDismiss={() => {}} />+ </XDSChatComposerAttachments>+ }+ status={{+ type: 'warning',+ message: 'Large files may take longer to process.',+ }}+ />+ ),+};++/** With status on bottom */+export const WithStatusBottom: Story = {+ render: () => (+ <XDSChatComposer+ onSubmit={value => console.log('Submit:', value)}+ status={{+ type: 'error',+ message: 'Failed to send message. Please try again.',+ }}+ />+ ),+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex 340fff7153..87260ad939 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -88,6 +88,12 @@"import": "./dist/Center/index.mjs","require": "./dist/Center/index.js"},+ "./Chat": {+ "source": "./src/Chat/index.ts",+ "types": "./dist/Chat/index.d.ts",+ "import": "./dist/Chat/index.mjs",+ "require": "./dist/Chat/index.js"+ },"./CheckboxInput": {"source": "./src/CheckboxInput/index.ts","types": "./dist/CheckboxInput/index.d.ts",diff --git a/packages/core/src/Chat/XDSChatComposer.tsx b/packages/core/src/Chat/XDSChatComposer.tsxnew file mode 100644index 0000000000..b518eef78c--- /dev/null+++ b/packages/core/src/Chat/XDSChatComposer.tsx@@ -0,0 +1,403 @@+'use client';++/**+ * @file XDSChatComposer.tsx+ * @input Uses React, StyleX, XDSBaseProps+ * @output Exports XDSChatComposer layout shell component+ * @position Core implementation; consumed by index.ts+ *+ * 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.+ */++import {useState, useRef, useCallback, type ReactNode} from 'react';+import type {XDSBaseProps} from '../XDSBaseProps';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ shadowVars,+ durationVars,+ easeVars,+ typeScaleVars,+ typographyVars,+} from '../theme/tokens.stylex';+import {xdsClassName, mergeProps} from '../utils';+import {XDSIcon} from '../Icon';++// =============================================================================+// Types+// =============================================================================++export type XDSChatComposerStatus = {+ type: 'error' | 'warning';+ message?: string;+};++export type XDSChatComposerDensity = 'compact' | 'balanced' | 'spacious';++export interface XDSChatComposerProps extends Omit<+ XDSBaseProps<HTMLDivElement>,+ 'onChange' | 'onSubmit'+> {+ /** Called when the user submits the message */+ onSubmit: (value: string) => void;+ /** Called when the user clicks stop during streaming */+ onStop?: () => void;+ /** Whether the assistant is currently streaming a response */+ isStreaming?: boolean;+ /** Controlled value of the input */+ value?: string;+ /** Called when the input value changes */+ onChange?: (value: string) => void;+ /** Placeholder text for the input */+ placeholder?: string;+ /** Whether the composer is disabled */+ isDisabled?: boolean;+ /** Density variant */+ density?: XDSChatComposerDensity;++ // --- Slot props ---++ /** Attachment chips rendered above the input */+ attachments?: ReactNode;+ /** Toolbar rendered between attachments and input (e.g. context chips) */+ contextToolbar?: ReactNode;+ /** Custom input element — replaces the default textarea */+ input?: ReactNode;+ /** Actions rendered on the left side of the footer. Use `size="md"` buttons to match the send button height. */+ footerActions?: ReactNode;+ /** Actions rendered to the left of the send button. Use `size="md"` buttons to match the send button height. */+ sendActions?: ReactNode;+ /** Custom send button — replaces the default */+ sendButton?: ReactNode;+ /** Status message rendered below the footer */+ status?: XDSChatComposerStatus;+ /** Where to render the status. @default 'bottom' */+ statusPosition?: 'top' | 'bottom';+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ root: {+ position: 'relative',+ zIndex: 0,+ 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'],+ },++ rootDisabled: {+ opacity: 0.6,+ pointerEvents: 'none' as const,+ },+ body: {+ position: 'relative',+ zIndex: 2,+ display: 'flex',+ flexDirection: 'column',+ padding: spacingVars['--spacing-3'],+ gap: spacingVars['--spacing-2'],+ borderRadius: radiusVars['--radius-page'],+ backgroundColor: colorVars['--color-background-popover'],+ boxShadow: {+ default: shadowVars['--shadow-low'],+ ':hover': {'@media (hover: hover)': shadowVars['--shadow-med']},+ },+ transition: `box-shadow ${durationVars['--duration-fast']} ${easeVars['--ease-standard']}`,+ ':focus-within': {+ boxShadow: shadowVars['--shadow-med'],+ },+ },+ inputArea: {+ display: 'flex',+ flexDirection: 'column',+ minHeight: '40px',+ },+ textarea: {+ all: 'unset',+ width: '100%',+ resize: 'none' as const,+ fontSize: typeScaleVars['--text-body-size'],+ lineHeight: typeScaleVars['--text-body-leading'],+ fontFamily: typographyVars['--font-family-body'],+ color: colorVars['--color-text-primary'],+ backgroundColor: 'transparent',+ caretColor: colorVars['--color-accent'],+ overflowY: 'auto' as const,+ maxHeight: '176px',+ '::placeholder': {+ color: colorVars['--color-text-disabled'],+ },+ },+ footer: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: spacingVars['--spacing-2'],+ // Footer buttons should use size="md" to match 32px send button height+ minHeight: '32px',+ },+ footerLeft: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ footerRight: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ },+ sendButton: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '32px',+ height: '32px',+ borderRadius: radiusVars['--radius-full'],+ border: 'none',+ cursor: 'pointer',+ transition: `opacity ${durationVars['--duration-fast']} ${easeVars['--ease-standard']}`,+ flexShrink: 0,+ },+ sendButtonSend: {+ backgroundColor: colorVars['--color-accent'],+ color: 'white',+ },+ sendButtonStop: {+ backgroundColor: colorVars['--color-background-muted'],+ color: colorVars['--color-text-primary'],+ },+ sendButtonDisabled: {+ opacity: 0.4,+ cursor: 'default',+ },+ statusBar: {+ position: 'relative',+ zIndex: 0,+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-4'],+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ 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'],+ },+ 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'],+ },+ statusError: {+ backgroundColor: colorVars['--color-error-muted'],+ color: colorVars['--color-text-red'],+ },+ statusWarning: {+ backgroundColor: colorVars['--color-warning-muted'],+ color: colorVars['--color-text-yellow'],+ },+ compact: {+ padding: spacingVars['--spacing-2'],+ gap: spacingVars['--spacing-1'],+ },+});++// =============================================================================+// Icons+// =============================================================================++function SendIcon() {+ return (+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">+ <path+ d="M8 3L8 13M8 3L4 7M8 3L12 7"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function StopIcon() {+ return (+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">+ <rect width="12" height="12" rx="2" fill="currentColor" />+ </svg>+ );+}++// =============================================================================+// Component+// =============================================================================++export function XDSChatComposer(props: XDSChatComposerProps) {+ const {+ onSubmit,+ onStop,+ isStreaming = false,+ value: controlledValue,+ onChange,+ placeholder = 'Type a message\u2026',+ isDisabled = false,+ density = 'balanced',+ attachments,+ contextToolbar,+ input,+ footerActions,+ sendActions,+ sendButton,+ status,+ statusPosition = 'bottom',+ xstyle,+ className,+ style,+ ...rest+ } = props;++ const [internalValue, setInternalValue] = useState('');+ const textareaRef = useRef<HTMLTextAreaElement>(null);++ const isControlled = controlledValue !== undefined;+ const currentValue = isControlled ? controlledValue : internalValue;++ const updateValue = useCallback(+ (newValue: string) => {+ if (!isControlled) {+ setInternalValue(newValue);+ }+ onChange?.(newValue);+ },+ [isControlled, onChange],+ );++ const handleSubmit = useCallback(() => {+ const trimmed = currentValue.trim();+ 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],+ );++ const canSend = currentValue.trim().length > 0 && !isDisabled;++ const defaultSendButton = (+ <button+ type="button"+ aria-label={isStreaming ? 'Stop' : 'Send'}+ onClick={isStreaming ? onStop : handleSubmit}+ disabled={!isStreaming && !canSend}+ {...stylex.props(+ styles.sendButton,+ isStreaming ? styles.sendButtonStop : styles.sendButtonSend,+ !isStreaming && !canSend && styles.sendButtonDisabled,+ )}>+ {isStreaming ? <StopIcon /> : <SendIcon />}+ </button>+ );++ const statusEl = status ? (+ <div+ role={status.type === 'error' ? 'alert' : 'status'}+ {...stylex.props(+ styles.statusBar,+ statusPosition === 'top' ? styles.statusTop : styles.statusBottom,+ status.type === 'error' && styles.statusError,+ status.type === 'warning' && styles.statusWarning,+ )}>+ <XDSIcon+ icon={status.type === 'error' ? 'xCircle' : 'warning'}+ size="md"+ color={status.type === 'error' ? 'negative' : 'warning'}+ />+ {status.message}+ </div>+ ) : null;++ return (+ <div+ {...mergeProps(+ xdsClassName('chat-composer', {density}),+ stylex.props(styles.root, isDisabled && styles.rootDisabled, xstyle),+ className,+ style,+ )}+ {...rest}>+ {statusPosition === 'top' && statusEl}+ {attachments}++ <div+ {...stylex.props(styles.body, density === 'compact' && styles.compact)}>+ {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)}+ />+ )}+ </div>++ <div {...stylex.props(styles.footer)}>+ <div {...stylex.props(styles.footerLeft)}>{footerActions}</div>+ <div {...stylex.props(styles.footerRight)}>+ {sendActions}+ {sendButton ?? defaultSendButton}+ </div>+ </div>+ </div>++ {statusPosition === 'bottom' && statusEl}+ </div>+ );+}++XDSChatComposer.displayName = 'XDSChatComposer';diff --git a/packages/core/src/Chat/XDSChatComposerAttachments.tsx b/packages/core/src/Chat/XDSChatComposerAttachments.tsxnew file mode 100644index 0000000000..ba2095a7bd--- /dev/null+++ b/packages/core/src/Chat/XDSChatComposerAttachments.tsx@@ -0,0 +1,279 @@+'use client';++/**+ * @file XDSChatComposerAttachments.tsx+ * @input Uses React, StyleX, theme tokens+ * @output Exports XDSChatComposerAttachments component+ * @position Layout container for attachment items inside XDSChatComposer.+ * Supports expanded (full content) and collapsed (count + label) states+ * with animated grid-template-rows transition.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ */++import {useState, type ReactNode} from 'react';+import type {StyleXStyles} from '@stylexjs/stylex';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ durationVars,+ easeVars,+ typeScaleVars,+} from '../theme/tokens.stylex';+import {XDSBadge} from '../Badge';+import {xdsClassName, mergeProps} from '../utils';+import type {XDSBaseProps} from '../XDSBaseProps';++export interface XDSChatComposerAttachmentsProps extends XDSBaseProps<HTMLDivElement> {+ ref?: React.Ref<HTMLDivElement>;+ /**+ * Attachment items — thumbnails, tokens, previews.+ */+ children: ReactNode;+ /**+ * Total attachment count — shown in the collapsed badge.+ * When omitted, the component doesn't support collapse.+ */+ count?: number;+ /**+ * Label shown next to the count in collapsed state.+ * @default 'Attachments'+ */+ label?: string;+ /**+ * Whether the drawer is collapsed.+ * Uncontrolled by default (internal toggle).+ */+ isCollapsed?: boolean;+ /**+ * Default collapsed state for uncontrolled usage.+ * @default false+ */+ defaultIsCollapsed?: boolean;+ /**+ * Callback when collapsed state changes.+ */+ onCollapsedChange?: (isCollapsed: boolean) => void;++ xstyle?: StyleXStyles;+ className?: string;+ style?: React.CSSProperties;+ 'data-testid'?: string;+}++const styles = stylex.create({+ root: {+ position: 'relative',+ zIndex: 1,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ paddingInline: spacingVars['--spacing-4'],+ paddingBlockStart: spacingVars['--spacing-3'],+ paddingBlockEnd: `calc(${spacingVars['--spacing-3']} + ${radiusVars['--radius-page']})`,+ marginBlockEnd: `calc(-1 * ${radiusVars['--radius-page']})`,+ backgroundColor: colorVars['--color-background-surface'],+ '::before': {+ content: '""',+ position: 'absolute',+ inset: 0,+ borderTopLeftRadius: 'inherit',+ borderTopRightRadius: 'inherit',+ backgroundColor: colorVars['--color-background-muted'],+ pointerEvents: 'none',+ },+ borderTopLeftRadius: radiusVars['--radius-page'],+ borderTopRightRadius: radiusVars['--radius-page'],+ },++ // Toggle row — click target area for collapse/expand+ toggleRow: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-4'],+ marginBlockStart: `calc(-1 * ${spacingVars['--spacing-2']})`,+ marginInline: `calc(-1 * ${spacingVars['--spacing-4']})`,+ cursor: 'pointer',+ userSelect: 'none',+ },+ toggleCollapsed: {+ justifyContent: 'flex-start',+ paddingBlockEnd: 0,+ },+ toggleContent: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ borderRadius: radiusVars['--radius-full'],+ opacity: 1,+ transitionProperty: 'opacity',+ transitionDuration: durationVars['--duration-fast'],+ transitionTimingFunction: easeVars['--ease-standard'],+ '@starting-style': {+ opacity: 0,+ },+ },+ collapseLabel: {+ color: {+ default: colorVars['--color-text-secondary'],+ [stylex.when.ancestor(':hover')]: {+ '@media (hover: hover)': colorVars['--color-text-primary'],+ },+ },+ fontSize: typeScaleVars['--text-body-size'],+ lineHeight: typeScaleVars['--text-body-leading'],+ transitionProperty: 'color',+ transitionDuration: durationVars['--duration-fast'],+ transitionTimingFunction: easeVars['--ease-standard'],+ },+ collapseBarHandle: {+ width: '20px',+ height: '2px',+ borderRadius: radiusVars['--radius-full'],+ backgroundColor: {+ default: colorVars['--color-border-emphasized'],+ [stylex.when.ancestor(':hover')]: {+ '@media (hover: hover)': colorVars['--color-text-primary'],+ },+ },+ opacity: 1,+ transitionProperty: 'background-color, opacity',+ transitionDuration: durationVars['--duration-fast'],+ transitionTimingFunction: easeVars['--ease-standard'],+ '@starting-style': {+ opacity: 0,+ },+ },++ // Animated content area+ contentGrid: {+ display: 'grid',+ gridTemplateRows: '1fr',+ transitionProperty: 'grid-template-rows',+ transitionDuration: durationVars['--duration-medium'],+ transitionTimingFunction: easeVars['--ease-standard'],+ },+ contentGridCollapsed: {+ gridTemplateRows: '0fr',+ },+ content: {+ minHeight: 0,+ display: 'flex',+ flexWrap: 'wrap',+ gap: spacingVars['--spacing-2'],+ alignItems: 'flex-start',+ transform: 'translateY(0)',+ transitionProperty: 'transform',+ transitionDuration: durationVars['--duration-medium'],+ transitionTimingFunction: easeVars['--ease-standard'],+ },+ contentCollapsed: {+ transform: `translateY(calc(100% + ${spacingVars['--spacing-3']} + ${radiusVars['--radius-page']}))`,+ },+});++export function XDSChatComposerAttachments({+ ref,+ children,+ count,+ label = 'Attachments',+ isCollapsed: controlledCollapsed,+ defaultIsCollapsed = false,+ onCollapsedChange,+ xstyle,+ className,+ style,+ 'data-testid': testId,+ ...htmlProps+}: XDSChatComposerAttachmentsProps): React.ReactElement {+ const [internalCollapsed, setInternalCollapsed] =+ useState(defaultIsCollapsed);+ const isControlled = controlledCollapsed !== undefined;+ const isCollapsed = isControlled ? controlledCollapsed : internalCollapsed;++ const canCollapse = count != null;++ const toggle = () => {+ const next = !isCollapsed;+ if (!isControlled) setInternalCollapsed(next);+ onCollapsedChange?.(next);+ };++ return (+ <div+ ref={ref}+ data-testid={testId}+ {...mergeProps(+ xdsClassName('chat-composer-attachments', {+ collapsed: isCollapsed ? 'collapsed' : null,+ }),+ stylex.props(styles.root, xstyle),+ className,+ style,+ )}+ {...htmlProps}>+ {canCollapse && (+ <div+ {...stylex.props(+ styles.toggleRow,+ isCollapsed && styles.toggleCollapsed,+ stylex.defaultMarker(),+ )}+ onClick={toggle}>+ {isCollapsed ? (+ <div+ role="button"+ tabIndex={0}+ aria-expanded={false}+ aria-label={`Expand ${label}`}+ onKeyDown={e => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ toggle();+ }+ }}+ {...stylex.props(styles.toggleContent)}>+ <XDSBadge variant="neutral" label={count} />+ <span {...stylex.props(styles.collapseLabel)}>{label}</span>+ </div>+ ) : (+ <div+ role="button"+ tabIndex={0}+ aria-expanded={true}+ aria-label={`Collapse ${label}`}+ onKeyDown={e => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ toggle();+ }+ }}+ {...stylex.props(styles.collapseBarHandle)}+ />+ )}+ </div>+ )}++ <div+ {...stylex.props(+ styles.contentGrid,+ canCollapse && isCollapsed && styles.contentGridCollapsed,+ )}>+ <div+ {...stylex.props(+ styles.content,+ canCollapse && isCollapsed && styles.contentCollapsed,+ )}>+ {children}+ </div>+ </div>+ </div>+ );+}++XDSChatComposerAttachments.displayName = 'XDSChatComposerAttachments';diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsxnew file mode 100644index 0000000000..8f803844a8--- /dev/null+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx@@ -0,0 +1,355 @@+'use client';++/**+ * @file XDSChatComposerInput.tsx+ * ContentEditable-based rich input for the chat composer.+ * Supports token rendering, serialization, Enter/Shift+Enter,+ * message history (ArrowUp/Down), paste/drop file handling.+ *+ * NOTE: Trigger menu popover (@ mentions, / commands) is NOT yet implemented.+ */++import {+ useRef,+ useState,+ useCallback,+ useEffect,+ type ReactNode,+ type KeyboardEvent,+ type ClipboardEvent,+ type DragEvent,+} from 'react';+import type {XDSBaseProps} from '../XDSBaseProps';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ durationVars,+ easeVars,+ fontWeightVars,+ typeScaleVars,+ typographyVars,+} from '../theme/tokens.stylex';+import {xdsClassName, mergeProps} from '../utils';++// =============================================================================+// Types+// =============================================================================++export type XDSChatComposerToken = {+ value: string;+ render: () => ReactNode;+};++export type XDSChatComposerTriggerItem = {+ id: string;+ label: string;+ [key: string]: unknown;+};++export type XDSChatComposerTrigger = {+ character: string;+ items?: XDSChatComposerTriggerItem[];+ queryItemsAction?: (query: string) => Promise<XDSChatComposerTriggerItem[]>;+ renderItem?: (item: XDSChatComposerTriggerItem) => ReactNode;+ onSelect: (item: XDSChatComposerTriggerItem) => XDSChatComposerToken;+ deserialize?: (value: string) => XDSChatComposerToken | null;+};++export interface XDSChatComposerInputProps+ extends Omit<XDSBaseProps<HTMLDivElement>, 'onChange' | 'onPaste' | 'onSubmit'> {+ value?: string;+ onChange?: (value: string) => void;+ placeholder?: string;+ maxRows?: number;+ triggers?: XDSChatComposerTrigger[];+ hasHistory?: boolean;+ label?: string;+ isDisabled?: boolean;+ onPaste?: (event: ClipboardEvent<HTMLDivElement>, text: string) => void;+ onFiles?: (files: File[]) => void;+ onSubmit?: (value: string) => void;+}++// =============================================================================+// Styles+// =============================================================================++const LINE_HEIGHT_PX = 22;++const styles = stylex.create({+ root: {+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ minHeight: `${LINE_HEIGHT_PX}px`,+ },+ editable: {+ outline: 'none',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ overflowY: 'auto',+ fontSize: typeScaleVars['--text-body-size'],+ lineHeight: `${LINE_HEIGHT_PX}px`,+ fontFamily: typographyVars['--font-family-body'],+ color: colorVars['--color-text-primary'],+ caretColor: colorVars['--color-accent'],+ },+ placeholder: {+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ pointerEvents: 'none',+ color: colorVars['--color-text-disabled'],+ fontSize: typeScaleVars['--text-body-size'],+ lineHeight: `${LINE_HEIGHT_PX}px`,+ fontFamily: typographyVars['--font-family-body'],+ userSelect: 'none',+ },+ 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+// =============================================================================++function serialize(node: Node): string {+ let result = '';+ for (const child of Array.from(node.childNodes)) {+ if (child.nodeType === Node.TEXT_NODE) {+ result += child.textContent ?? '';+ } else if (child instanceof HTMLElement) {+ if (child.hasAttribute('data-xds-token')) {+ result += child.getAttribute('data-xds-token-value') ?? '';+ } else if (child.tagName === 'BR') {+ result += '\n';+ } else {+ result += serialize(child);+ }+ }+ }+ return result;+}++// =============================================================================+// Component+// =============================================================================++export function XDSChatComposerInput(props: XDSChatComposerInputProps) {+ const {+ value: controlledValue,+ onChange,+ placeholder = 'Type a message\u2026',+ maxRows = 8,+ triggers,+ hasHistory = true,+ label = 'Message input',+ isDisabled = false,+ onPaste: onPasteProp,+ onFiles,+ onSubmit,+ xstyle,+ className,+ style,+ ...rest+ } = props;++ const editableRef = useRef<HTMLDivElement>(null);+ const [isEmpty, setIsEmpty] = useState(true);+ const historyRef = useRef<string[]>([]);+ const historyIndexRef = useRef(-1);+ const currentDraftRef = useRef('');++ useEffect(() => {+ if (controlledValue !== undefined && editableRef.current) {+ const current = serialize(editableRef.current);+ if (current !== controlledValue) {+ editableRef.current.textContent = controlledValue;+ setIsEmpty(controlledValue.length === 0);+ }+ }+ }, [controlledValue]);++ const emitChange = useCallback(() => {+ if (!editableRef.current) return;+ const text = serialize(editableRef.current);+ setIsEmpty(text.length === 0);+ onChange?.(text);+ }, [onChange]);++ const handleInput = useCallback(() => {+ emitChange();+ }, [emitChange]);++ const handleKeyDown = useCallback(+ (e: KeyboardEvent<HTMLDivElement>) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ if (!editableRef.current) return;+ const text = serialize(editableRef.current).trim();+ if (!text) return;++ if (hasHistory) {+ historyRef.current.push(text);+ historyIndexRef.current = -1;+ currentDraftRef.current = '';+ }++ onSubmit?.(text);+ editableRef.current.textContent = '';+ setIsEmpty(true);+ onChange?.('');+ return;+ }++ // History navigation+ 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;+ }+ const nextIndex =+ historyIndexRef.current === -1+ ? history.length - 1+ : Math.max(0, historyIndexRef.current - 1);+ historyIndexRef.current = nextIndex;+ editableRef.current.textContent = history[nextIndex];+ emitChange();+ e.preventDefault();+ } else if (e.key === 'ArrowDown' && historyIndexRef.current !== -1) {+ const nextIndex = historyIndexRef.current + 1;+ if (nextIndex >= history.length) {+ historyIndexRef.current = -1;+ editableRef.current.textContent = currentDraftRef.current;+ } else {+ historyIndexRef.current = nextIndex;+ editableRef.current.textContent = history[nextIndex];+ }+ emitChange();+ e.preventDefault();+ }+ }+ },+ [hasHistory, onSubmit, onChange, emitChange],+ );++ const handlePaste = useCallback(+ (e: ClipboardEvent<HTMLDivElement>) => {+ const files = Array.from(e.clipboardData.files);+ if (files.length > 0) {+ e.preventDefault();+ onFiles?.(files);+ return;+ }++ e.preventDefault();+ const text = e.clipboardData.getData('text/plain');+ document.execCommand('insertText', false, text);++ onPasteProp?.(e, text);+ emitChange();+ },+ [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+ {...mergeProps(+ xdsClassName('chat-composer-input'),+ stylex.props(+ styles.root,+ isDisabled && styles.disabled,+ xstyle,+ ),+ className,+ style,+ )}+ {...rest}+ >+ {isEmpty && (+ <div {...stylex.props(styles.placeholder)} aria-hidden="true">+ {placeholder}+ </div>+ )}+ <div+ ref={editableRef}+ role="textbox"+ aria-multiline="true"+ aria-label={label}+ contentEditable={!isDisabled}+ suppressContentEditableWarning+ onInput={handleInput}+ onKeyDown={handleKeyDown}+ onPaste={handlePaste}+ onDrop={handleDrop}+ {...stylex.props(styles.editable)}+ style={{maxHeight: `${maxHeight}px`}}+ />+ </div>+ );+}++XDSChatComposerInput.displayName = 'XDSChatComposerInput';++// =============================================================================+// Token element helper+// =============================================================================++export function XDSChatComposerTokenElement({+ token,+}: {+ token: XDSChatComposerToken;+}) {+ return (+ <span+ data-xds-token=""+ data-xds-token-value={token.value}+ contentEditable={false}+ {...stylex.props(styles.token)}+ >+ {token.render()}+ </span>+ );+}++XDSChatComposerTokenElement.displayName = 'XDSChatComposerTokenElement';diff --git a/packages/core/src/Chat/index.ts b/packages/core/src/Chat/index.tsnew file mode 100644index 0000000000..b1a8fdca30--- /dev/null+++ b/packages/core/src/Chat/index.ts@@ -0,0 +1,23 @@+'use client';++/**+ * @file Chat component barrel export+ */++export {XDSChatComposer} from './XDSChatComposer';+export type {+ XDSChatComposerProps,+ XDSChatComposerStatus,+ XDSChatComposerDensity,+} from './XDSChatComposer';++export {XDSChatComposerAttachments} from './XDSChatComposerAttachments';+export type {XDSChatComposerAttachmentsProps} from './XDSChatComposerAttachments';++export {XDSChatComposerInput, XDSChatComposerTokenElement} from './XDSChatComposerInput';+export type {+ XDSChatComposerInputProps,+ XDSChatComposerToken,+ XDSChatComposerTrigger,+ XDSChatComposerTriggerItem,+} from './XDSChatComposerInput';