Skip to content

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

TypeScript

feat(core): make custom ChatComposer inputs first-class (#4285)

Cindy Zhang82b530aab476
diff --git a/.changeset/chat-composer-input-composition.md b/.changeset/chat-composer-input-composition.md
new file mode 100644
index 0000000000..df2e36d1f9
--- /dev/null
+++ b/.changeset/chat-composer-input-composition.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] ChatComposer: make custom inputs first-class. `useChatComposerContext()` and its types are now public, so any input in the `input` slot can read `value`/`onChange`/`onSubmit`/`canSend`/`placeholder`/`isDisabled` and drive the shell's send button. Inputs can register a focus control on `inputControlRef` so click-to-focus works for any input shape (not just `contenteditable`/`textarea`); the shell keeps a DOM-query fallback for uninstrumented inputs.
+@ejc3
diff --git a/apps/storybook/stories/ChatComposerCustomInput.stories.tsx b/apps/storybook/stories/ChatComposerCustomInput.stories.tsx
new file mode 100644
index 0000000000..0b81b40420
--- /dev/null
+++ b/apps/storybook/stories/ChatComposerCustomInput.stories.tsx
@@ -0,0 +1,226 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useEffect, useRef, useState} from 'react';
+import {ChatComposer, useChatComposerContext} from '@astryxdesign/core/Chat';
+
+// Lexical (optional peer of the OSS rich-text work) — imported directly here to
+// demonstrate that an arbitrary editor, with its own value/focus model, can be
+// a first-class composer input purely through the public composition contract.
+import {LexicalComposer} from '@lexical/react/LexicalComposer';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {PlainTextPlugin} from '@lexical/react/LexicalPlainTextPlugin';
+import {ContentEditable} from '@lexical/react/LexicalContentEditable';
+import {LexicalErrorBoundary} from '@lexical/react/LexicalErrorBoundary';
+import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';
+import {$getRoot, type EditorState} from 'lexical';
+
+const meta: Meta<typeof ChatComposer> = {
+ title: 'Components/ChatComposer/Custom Input',
+ component: ChatComposer,
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'The composer body is a shell of slots; the input is just one of them. ' +
+ 'Any input can be a first-class citizen by wiring to the public ' +
+ 'composition contract: read `value`/`onChange`/`onSubmit`/`placeholder`/' +
+ '`isDisabled` from `useChatComposerContext()`, and register a focus ' +
+ 'control on `inputControlRef` so clicking empty space in the body focuses ' +
+ 'it — no matter the input’s DOM shape. `ChatSendButton` reads the same ' +
+ 'context, so the shell’s send button “just works”.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+type Story = StoryObj<typeof ChatComposer>;
+
+// =============================================================================
+// Example 1 — a plain <textarea> as a first-class composer input
+// =============================================================================
+
+/**
+ * A bare controlled `<textarea>` in the input slot. It reads state from
+ * `useChatComposerContext()`, submits on Enter, and registers a focus control
+ * so body-click-to-focus works. No `ChatComposerInput`, no contentEditable.
+ */
+function TextareaInput() {
+ const ctx = useChatComposerContext();
+ const ref = useRef<HTMLTextAreaElement>(null);
+
+ // Register how the shell should focus us (body-click-to-focus).
+ const controlRef = ctx?.inputControlRef;
+ useEffect(() => {
+ if (!controlRef) {
+ return;
+ }
+ controlRef.current = {focus: () => ref.current?.focus()};
+ return () => {
+ controlRef.current = null;
+ };
+ }, [controlRef]);
+
+ if (!ctx) {
+ return null;
+ }
+ return (
+ <textarea
+ ref={ref}
+ rows={1}
+ value={ctx.value}
+ placeholder={ctx.placeholder}
+ disabled={ctx.isDisabled}
+ onChange={e => ctx.onChange(e.target.value)}
+ onKeyDown={e => {
+ // Enter submits; Shift+Enter inserts a newline. IME-safe.
+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ if (ctx.canSend) {
+ ctx.onSubmit(ctx.value);
+ }
+ }
+ }}
+ style={{
+ all: 'unset',
+ width: '100%',
+ resize: 'none',
+ fontFamily: 'var(--font-family-body)',
+ fontSize: 'var(--text-body-size)',
+ lineHeight: 'var(--text-body-leading)',
+ color: 'var(--color-text-primary)',
+ caretColor: 'var(--color-accent)',
+ }}
+ />
+ );
+}
+
+export const PlainTextarea: Story = {
+ render: () => {
+ const [value, setValue] = useState('');
+ return (
+ <ChatComposer
+ value={value}
+ onChange={setValue}
+ onSubmit={submitted => {
+ console.log('Submit:', submitted);
+ setValue('');
+ }}
+ placeholder="Plain textarea input…"
+ input={<TextareaInput />}
+ />
+ );
+ },
+};
+
+// =============================================================================
+// Example 2 — a raw Lexical editor as a first-class composer input
+// =============================================================================
+
+/** Bridges Lexical's EditorState to the composer's string value + focus. */
+function LexicalBridge() {
+ const ctx = useChatComposerContext();
+ const [editor] = useLexicalComposerContext();
+
+ // Register focus with the shell (Lexical owns focus, not a raw DOM node).
+ const controlRef = ctx?.inputControlRef;
+ useEffect(() => {
+ if (!controlRef) {
+ return;
+ }
+ controlRef.current = {focus: () => editor.focus()};
+ return () => {
+ controlRef.current = null;
+ };
+ }, [controlRef, editor]);
+
+ const handleChange = (state: EditorState) => {
+ state.read(() => ctx?.onChange($getRoot().getTextContent()));
+ };
+
+ return <OnChangePlugin onChange={handleChange} ignoreSelectionChange />;
+}
+
+function LexicalInput() {
+ const ctx = useChatComposerContext();
+ return (
+ <LexicalComposer
+ initialConfig={{
+ namespace: 'astryx-composer-example',
+ onError: (error: Error) => {
+ throw error;
+ },
+ }}>
+ <PlainTextPlugin
+ contentEditable={
+ <ContentEditable
+ aria-label={ctx?.placeholder ?? 'Message'}
+ onKeyDown={e => {
+ // Enter submits; Shift+Enter newline; never mid-composition.
+ if (
+ e.key === 'Enter' &&
+ !e.shiftKey &&
+ !e.nativeEvent.isComposing
+ ) {
+ e.preventDefault();
+ if (ctx?.canSend) {
+ ctx.onSubmit(ctx.value);
+ }
+ }
+ }}
+ style={{
+ outline: 'none',
+ minHeight: '1.5rem',
+ fontFamily: 'var(--font-family-body)',
+ fontSize: 'var(--text-body-size)',
+ lineHeight: 'var(--text-body-leading)',
+ color: 'var(--color-text-primary)',
+ caretColor: 'var(--color-accent)',
+ }}
+ />
+ }
+ placeholder={
+ <div
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ pointerEvents: 'none',
+ color: 'var(--color-text-secondary)',
+ fontFamily: 'var(--font-family-body)',
+ fontSize: 'var(--text-body-size)',
+ lineHeight: 'var(--text-body-leading)',
+ }}>
+ {ctx?.placeholder}
+ </div>
+ }
+ ErrorBoundary={LexicalErrorBoundary}
+ />
+ <LexicalBridge />
+ </LexicalComposer>
+ );
+}
+
+export const RawLexical: Story = {
+ render: () => {
+ const [value, setValue] = useState('');
+ return (
+ <ChatComposer
+ value={value}
+ onChange={setValue}
+ onSubmit={submitted => {
+ console.log('Submit:', submitted);
+ setValue('');
+ }}
+ placeholder="Raw Lexical editor input…"
+ input={
+ <div style={{position: 'relative', width: '100%'}}>
+ <LexicalInput />
+ </div>
+ }
+ />
+ );
+ },
+};
diff --git a/packages/core/src/Chat/ChatComposer.doc.mjs b/packages/core/src/Chat/ChatComposer.doc.mjs
index 974e732dd3..8bf4f05cc8 100644
--- a/packages/core/src/Chat/ChatComposer.doc.mjs
+++ b/packages/core/src/Chat/ChatComposer.doc.mjs
@@ -109,7 +109,7 @@ export const docs = {
{
name: 'input',
type: 'ReactNode',
- description: 'Slot: custom input element. Replaces the default textarea. Use ChatComposerInput for trigger menus.',
+ description: 'Slot: custom input element. Replaces the default input. Use ChatComposerInput for trigger menus/tokens, or wire any input (plain textarea, rich editor) to the composition contract via useChatComposerContext() — read value/onChange/onSubmit/canSend and register a focus control on inputControlRef so body-click-to-focus works.',
slotElements: [
{
__element: 'TextInput',
@@ -196,7 +196,7 @@ export const docsZh = {
drawer: '插槽:输入上方的可折叠抽屉——附件、上下文标签等。使用 ChatComposerDrawer。',
headerActions: '插槽:标题左侧操作按钮(附件、提及按钮)。使用仅图标 size="sm" 按钮。',
headerContext: '插槽:标题右侧上下文信息(上下文窗口使用情况、ProgressBar、辅助文本)。',
- input: '插槽:自定义输入元素。替换默认文本区域。使用 ChatComposerInput 实现触发菜单。',
+ input: '插槽:自定义输入元素。替换默认输入。使用 ChatComposerInput 实现触发菜单/标记,或通过 useChatComposerContext() 将任意输入(纯 textarea、富文本编辑器)接入组合契约——读取 value/onChange/onSubmit/canSend,并在 inputControlRef 上注册聚焦控制,使点击空白处聚焦生效。',
footerActions: '插槽:左对齐的页脚操作(模型选择器等)。',
sendActions: '插槽:发送按钮左侧的操作。',
sendButton: '插槽:自定义发送按钮。替换默认的发送/停止按钮。',
@@ -222,7 +222,7 @@ export const docsDense = {
drawer: 'slot: collapsible drawer above input: attachments, context chips, etc.; use ChatComposerDrawer',
headerActions: 'slot: left header actions (attach, mention); icon-only sm buttons',
headerContext: 'slot: right header context info (window usage, ProgressBar, text)',
- input: 'slot: custom input; replaces default textarea; use ChatComposerInput for triggers',
+ input: 'slot: custom input; replaces default. use ChatComposerInput for triggers/tokens, or wire any input via useChatComposerContext() (value/onChange/onSubmit/canSend + register focus on inputControlRef)',
footerActions: 'slot: left footer actions (model selector etc)',
sendActions: 'slot: actions left of send btn',
sendButton: 'slot: custom send btn; replaces default',
diff --git a/packages/core/src/Chat/ChatComposer.test.tsx b/packages/core/src/Chat/ChatComposer.test.tsx
index 4d0837b214..b8d5eded79 100644
--- a/packages/core/src/Chat/ChatComposer.test.tsx
+++ b/packages/core/src/Chat/ChatComposer.test.tsx
@@ -1,8 +1,10 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
-import {render} from '@testing-library/react';
+import {describe, it, expect, vi} from 'vitest';
+import {render, fireEvent} from '@testing-library/react';
+import {useEffect, useRef} from 'react';
import {ChatComposer} from './ChatComposer';
+import {useChatComposerContext} from './ChatContext';
// The composer body — the elevated surface — is the div that wraps the input
// area (styles.body). A custom `input` slot renders inside the inputArea div,
@@ -33,3 +35,81 @@ describe('ChatComposer elevation', () => {
expect(renderBodyClass(undefined)).toBe(renderBodyClass('low'));
});
});
+
+// A custom input that participates in the composer's composition contract:
+// reads value/submit from the exported context, and registers a focus control
+// so the shell can drive body-click-to-focus without knowing its DOM shape.
+function CustomContextInput({focusSpy}: {focusSpy: () => void}) {
+ const ctx = useChatComposerContext();
+ const ref = useRef<HTMLInputElement>(null);
+ const controlRef = ctx?.inputControlRef;
+ useEffect(() => {
+ if (!controlRef) {
+ return;
+ }
+ controlRef.current = {
+ focus: () => {
+ focusSpy();
+ ref.current?.focus();
+ },
+ };
+ return () => {
+ controlRef.current = null;
+ };
+ }, [controlRef, focusSpy]);
+ return (
+ <input
+ ref={ref}
+ data-testid="custom-input"
+ value={ctx?.value ?? ''}
+ placeholder={ctx?.placeholder}
+ disabled={ctx?.isDisabled}
+ onChange={e => ctx?.onChange(e.target.value)}
+ />
+ );
+}
+
+describe('ChatComposer input composition contract', () => {
+ it('exposes value/onChange/placeholder/isDisabled to a custom input via context', () => {
+ const {getByTestId} = render(
+ <ChatComposer
+ onSubmit={() => {}}
+ value="hello"
+ placeholder="Say something"
+ isDisabled
+ input={<CustomContextInput focusSpy={() => {}} />}
+ />,
+ );
+ const input = getByTestId('custom-input') as HTMLInputElement;
+ expect(input.value).toBe('hello');
+ expect(input.placeholder).toBe('Say something');
+ expect(input.disabled).toBe(true);
+ });
+
+ it('focuses a custom input via its registered control on body click', () => {
+ const focusSpy = vi.fn();
+ const {getByTestId} = render(
+ <ChatComposer
+ onSubmit={() => {}}
+ input={<CustomContextInput focusSpy={focusSpy} />}
+ />,
+ );
+ const marker = getByTestId('custom-input');
+ const body = marker.parentElement!.parentElement!;
+ fireEvent.click(body);
+ expect(focusSpy).toHaveBeenCalled();
+ });
+
+ it('falls back to focusing a bare textarea when no control is registered', () => {
+ const {getByTestId} = render(
+ <ChatComposer
+ onSubmit={() => {}}
+ input={<textarea data-testid="bare-textarea" />}
+ />,
+ );
+ const textarea = getByTestId('bare-textarea') as HTMLTextAreaElement;
+ const body = textarea.parentElement!.parentElement!;
+ fireEvent.click(body);
+ expect(document.activeElement).toBe(textarea);
+ });
+});
diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsx
index ead3c4d531..54db759e0d 100644
--- a/packages/core/src/Chat/ChatComposer.tsx
+++ b/packages/core/src/Chat/ChatComposer.tsx
@@ -48,6 +48,7 @@ import {mergeProps} from '../utils';
import {Icon} from '../Icon';
import {ChatComposerInput} from './ChatComposerInput';
import {ChatComposerContext} from './ChatContext';
+import type {ChatComposerInputControl} from './ChatContext';
import {ChatSendButton} from './ChatSendButton';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
@@ -373,6 +374,11 @@ export function ChatComposer(props: ChatComposerProps) {
const bodyRef = useRef<HTMLDivElement>(null);
+ // Input slot registers its focus (and future) control here so the shell can
+ // drive it without knowing its DOM shape. Stable ref — safe in the memoized
+ // context value.
+ const inputControlRef = useRef<ChatComposerInputControl | null>(null);
+
const handleBodyClick = useCallback((e: MouseEvent<HTMLDivElement>) => {
// Focus the input when clicking empty space in the body.
// Skip if the click target is a button, link, or interactive element.
@@ -384,6 +390,14 @@ export function ChatComposer(props: ChatComposerProps) {
) {
return;
}
+ // Prefer the input's registered control (works for any input shape,
+ // including editors whose focusable node isn't a bare
+ // contenteditable/textarea). Fall back to a DOM query so uninstrumented
+ // custom inputs still get click-to-focus.
+ if (inputControlRef.current) {
+ inputControlRef.current.focus();
+ return;
+ }
const editable = bodyRef.current?.querySelector<HTMLElement>(
'[contenteditable="true"], textarea',
);
@@ -418,6 +432,7 @@ export function ChatComposer(props: ChatComposerProps) {
isStopShown,
canSend,
onStop,
+ inputControlRef,
}),
[
currentValue,
diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsx
index 1afc332cbd..020ca4f5f0 100644
--- a/packages/core/src/Chat/ChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx
@@ -155,6 +155,22 @@ describe('ChatComposerInput', () => {
});
});
+ describe('composer focus control', () => {
+ it('registers a focus control so a body click focuses the input', () => {
+ render(
+ <ChatComposer onSubmit={() => {}} input={<ChatComposerInput />} />,
+ );
+ const editable = screen.getByRole('textbox');
+ // Walk to the composer body: editable → input root → inputArea → body.
+ const inputRoot = editable.parentElement!;
+ const inputArea = inputRoot.parentElement!;
+ const body = inputArea.parentElement!;
+ // Click empty space in the body → shell drives the registered control.
+ fireEvent.click(body);
+ expect(document.activeElement).toBe(editable);
+ });
+ });
+
describe('Enter submit behavior', () => {
it('does not submit on Enter while IME composition is in progress', () => {
const onSubmit = vi.fn();
diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsx
index b53d86a93b..008d77d34a 100644
--- a/packages/core/src/Chat/ChatComposerInput.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.tsx
@@ -384,6 +384,20 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
selfRef.current = handle;
useImperativeHandle(handleRef, () => handle);
+ // Register a focus control with the composer shell so body-click-to-focus
+ // works without the shell sniffing the input's DOM shape. Cleared on
+ // unmount so the shell falls back cleanly if the input goes away.
+ const inputControlRef = composerCtx?.inputControlRef;
+ useEffect(() => {
+ if (!inputControlRef) {
+ return;
+ }
+ inputControlRef.current = {focus: () => editableRef.current?.focus()};
+ return () => {
+ inputControlRef.current = null;
+ };
+ }, [inputControlRef]);
+
useEffect(() => {
if (controlledValue === undefined || !editableRef.current) {
return;
diff --git a/packages/core/src/Chat/ChatContext.tsx b/packages/core/src/Chat/ChatContext.tsx
index d930426bf2..56e29f92a3 100644
--- a/packages/core/src/Chat/ChatContext.tsx
+++ b/packages/core/src/Chat/ChatContext.tsx
@@ -5,11 +5,14 @@
/**
* @file ChatContext.tsx
* @input Uses React createContext
- * @output Exports ChatMessageContext for sharing sender/density between Chat components
- * @position Internal context; consumed by ChatMessage and ChatMessageBubble
+ * @output Exports Chat message/list/composer/layout contexts. The composer
+ * context (value + input-control registration) is public composition API,
+ * re-exported from Chat/index.ts for custom inputs.
+ * @position Shared contexts; consumed by ChatMessage, ChatComposer,
+ * ChatComposerInput, ChatSendButton, and custom inputs.
*/
-import {createContext, use} from 'react';
+import {createContext, use, type RefObject} from 'react';
export type ChatMessageSender = 'user' | 'assistant' | 'system';
export type ChatDensity = 'compact' | 'balanced' | 'spacious';
@@ -19,8 +22,9 @@ export interface ChatMessageContextValue {
density: ChatDensity;
}
-export const ChatMessageContext =
- createContext<ChatMessageContextValue | null>(null);
+export const ChatMessageContext = createContext<ChatMessageContextValue | null>(
+ null,
+);
ChatMessageContext.displayName = 'ChatMessageContext';
export function useChatMessageContext(): ChatMessageContextValue | null {
@@ -31,9 +35,7 @@ export interface ChatListContextValue {
density: ChatDensity;
}
-export const ChatListContext = createContext<ChatListContextValue | null>(
- null,
-);
+export const ChatListContext = createContext<ChatListContextValue | null>(null);
ChatListContext.displayName = 'ChatListContext';
export function useChatListContext(): ChatListContextValue | null {
@@ -44,6 +46,21 @@ export function useChatListContext(): ChatListContextValue | null {
// Composer context — shared state between ChatComposer and ChatComposerInput
// =============================================================================
+/**
+ * Imperative surface the composer shell can invoke on its input slot.
+ *
+ * The input is one slot inside the composer body — it does not span the whole
+ * body — so shell-level interactions like "click empty space to focus the
+ * input" must flow shell → input. A custom input registers this control (via
+ * `ChatComposerContextValue.inputControlRef`) so the shell can drive it
+ * without knowing its DOM shape. Optional methods can be added over time;
+ * inputs implement only what they support.
+ */
+export interface ChatComposerInputControl {
+ /** Move keyboard focus into the input. */
+ focus: () => void;
+}
+
export interface ChatComposerContextValue {
value: string;
onChange: (value: string) => void;
@@ -53,6 +70,15 @@ export interface ChatComposerContextValue {
isStopShown: boolean;
canSend: boolean;
onStop?: () => void;
+ /**
+ * Mutable handle the input slot populates with its {@link
+ * ChatComposerInputControl}. The shell reads `.current` to drive the input
+ * (e.g. focus on body click). A custom input assigns
+ * `inputControlRef.current = { focus }` on mount and clears it on unmount.
+ * When unset, the shell falls back to focusing a `contenteditable`/`textarea`
+ * it finds in the body.
+ */
+ inputControlRef?: RefObject<ChatComposerInputControl | null>;
}
export const ChatComposerContext =
@@ -74,8 +100,9 @@ export interface ChatLayoutContextValue {
contentRef: (el: HTMLElement | null) => void;
}
-export const ChatLayoutContext =
- createContext<ChatLayoutContextValue | null>(null);
+export const ChatLayoutContext = createContext<ChatLayoutContextValue | null>(
+ null,
+);
ChatLayoutContext.displayName = 'ChatLayoutContext';
export function useChatLayoutContext(): ChatLayoutContextValue | null {
diff --git a/packages/core/src/Chat/index.ts b/packages/core/src/Chat/index.ts
index 923d20c8ca..7239e182f7 100644
--- a/packages/core/src/Chat/index.ts
+++ b/packages/core/src/Chat/index.ts
@@ -81,7 +81,11 @@ export type {
TokenPortal,
} from './useChatComposerTokens';
export type {ChatMessageSender, ChatDensity} from './ChatContext';
-export {useChatLayoutContext} from './ChatContext';
+export {useChatLayoutContext, useChatComposerContext} from './ChatContext';
+export type {
+ ChatComposerContextValue,
+ ChatComposerInputControl,
+} from './ChatContext';
export {ChatToolCalls} from './ChatToolCalls';
export type {