An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add onKeyDown seam to ChatComposerInput for platform-specific keys (#4280)
Cindy Zhang0c4d8d74542c
diff --git a/.changeset/chatcomposerinput-enter-behavior.md b/.changeset/chatcomposerinput-enter-behavior.mdnew file mode 100644index 0000000000..9c7840dc32--- /dev/null+++ b/.changeset/chatcomposerinput-enter-behavior.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] ChatComposerInput: add an `onKeyDown` seam so consumers can host platform- or app-specific key handling — e.g. `preventDefault()` Enter to insert a newline on a touch keyboard, or submit on Cmd/Ctrl+Enter. Enter also no longer submits mid-IME-composition.+@ejc3diff --git a/apps/storybook/stories/ChatComposer.stories.tsx b/apps/storybook/stories/ChatComposer.stories.tsxindex 604fab7017..262e7208cb 100644--- a/apps/storybook/stories/ChatComposer.stories.tsx+++ b/apps/storybook/stories/ChatComposer.stories.tsx@@ -4,6 +4,7 @@ import type {Meta, StoryObj} from '@storybook/react';import {ChatComposer,ChatComposerDrawer,+ ChatComposerInput,ChatSendButton,} from '@astryxdesign/core/Chat';import {Token} from '@astryxdesign/core/Token';@@ -93,6 +94,42 @@ export const Simplest: Story = {),};+/**+ * Platform-specific Enter behavior. Pass a custom `ChatComposerInput` in the+ * `input` slot and handle keys through `onKeyDown` — the single seam for+ * platform quirks. Here, on a touch keyboard we `preventDefault()` Enter so a+ * soft-keyboard Return inserts a newline instead of sending (and never strands+ * a multi-line prompt); on a pointer device Enter sends as usual. The same+ * seam covers shortcuts like Cmd/Ctrl+Enter — just call submit yourself.+ * IME composition is always respected regardless.+ */+export const EnterBehavior: Story = {+ render: () => {+ const isCoarsePointer =+ typeof window !== 'undefined' &&+ window.matchMedia?.('(pointer: coarse)').matches;+ return (+ <ChatComposer+ onSubmit={value => console.log('Submit:', value)}+ input={+ <ChatComposerInput+ placeholder={+ isCoarsePointer+ ? 'Enter inserts a newline on touch — use Send'+ : 'Enter sends; Shift+Enter for a newline'+ }+ onKeyDown={e => {+ if (isCoarsePointer && e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ }+ }}+ />+ }+ />+ );+ },+};+/** With streaming state and stop button */export const WithStreaming: Story = {render: () => {diff --git a/packages/core/src/Chat/ChatComposerInput.doc.mjs b/packages/core/src/Chat/ChatComposerInput.doc.mjsindex 717dee0177..99edb1f47c 100644--- a/packages/core/src/Chat/ChatComposerInput.doc.mjs+++ b/packages/core/src/Chat/ChatComposerInput.doc.mjs@@ -80,6 +80,11 @@ export const docs = {type: '(value: string) => void',description: 'Called when the user presses Enter without Shift. The serialized value includes token placeholders.',},+ {+ name: 'onKeyDown',+ type: '(event) => void',+ description: 'Key-down handler invoked before the built-in Enter/history behavior (after any open trigger menu). The seam for platform-specific keys: call event.preventDefault() to suppress the default submit (e.g. newline on a touch keyboard), or act on the event yourself to add behavior (e.g. submit on Cmd/Ctrl+Enter). IME composition is always respected — Enter never submits mid-composition.',+ },],};@@ -102,6 +107,7 @@ export const docsZh = {onPaste: '粘贴文本时调用。用于拦截或转换粘贴内容。',onFiles: '粘贴或拖放文件到输入时调用。用于处理附件。',onSubmit: '用户不按 Shift 按 Enter 时调用。序列化值包含标记占位符。',+ onKeyDown: '在内置 Enter/历史处理之前(在打开的触发菜单之后)调用的按键处理器。平台特定按键的接缝:调用 event.preventDefault() 可抑制默认提交(例如触控键盘上插入换行),或自行处理事件以添加行为(例如 Cmd/Ctrl+Enter 提交)。始终尊重输入法组字状态——组字过程中 Enter 永不提交。',},};@@ -124,5 +130,6 @@ export const docsDense = {onPaste: 'paste handler; intercept/transform pasted content',onFiles: 'file paste/drop handler; use for attachments',onSubmit: 'Enter w/o Shift handler; serialized value includes token placeholders',+ onKeyDown: 'keydown handler before built-in Enter/history (after trigger menu); preventDefault() to suppress default submit (touch newline) or act on event to add behavior (Cmd/Ctrl+Enter). IME composition always respected',},};diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsxindex 5846465280..1afc332cbd 100644--- a/packages/core/src/Chat/ChatComposerInput.test.tsx+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx@@ -155,6 +155,93 @@ describe('ChatComposerInput', () => {});});+ describe('Enter submit behavior', () => {+ it('does not submit on Enter while IME composition is in progress', () => {+ const onSubmit = vi.fn();+ render(<ChatComposerInput onSubmit={onSubmit} />);+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'こんにちは';+ fireEvent.input(textbox);+ // isComposing is surfaced on the native event during IME composition.+ fireEvent.keyDown(textbox, {key: 'Enter', isComposing: true});+ expect(onSubmit).not.toHaveBeenCalled();+ });++ it('does not submit on Enter for the legacy keyCode 229 composing signal', () => {+ const onSubmit = vi.fn();+ render(<ChatComposerInput onSubmit={onSubmit} />);+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'ㅎ';+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter', keyCode: 229});+ expect(onSubmit).not.toHaveBeenCalled();+ });++ it('lets onKeyDown suppress the default submit via preventDefault (touch-newline recipe)', () => {+ // The documented "insert a newline instead of sending" pattern: a+ // consumer preventDefaults Enter (e.g. on a coarse pointer).+ const onSubmit = vi.fn();+ const onKeyDown = vi.fn(e => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ }+ });+ render(<ChatComposerInput onSubmit={onSubmit} onKeyDown={onKeyDown} />);+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'hello';+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter'});+ expect(onKeyDown).toHaveBeenCalled();+ expect(onSubmit).not.toHaveBeenCalled();+ });++ it('lets onKeyDown add behavior (Cmd/Ctrl+Enter submit) without preventDefault', () => {+ // Adding a submit shortcut is just handling the event yourself; the+ // built-in Enter handling still runs for the plain-Enter case.+ const onSubmit = vi.fn();+ const handle = vi.fn();+ const onKeyDown = vi.fn(e => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {+ handle();+ }+ });+ render(<ChatComposerInput onSubmit={onSubmit} onKeyDown={onKeyDown} />);+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'hello';+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter', metaKey: true});+ expect(handle).toHaveBeenCalled();+ // Consumer did not preventDefault, so the built-in submit also fires.+ expect(onSubmit).toHaveBeenCalledWith('hello');+ });++ it('calls onKeyDown before submit and lets preventDefault take over', () => {+ const onSubmit = vi.fn();+ const onKeyDown = vi.fn(e => {+ e.preventDefault();+ });+ render(<ChatComposerInput onSubmit={onSubmit} onKeyDown={onKeyDown} />);+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'hello';+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter'});+ expect(onKeyDown).toHaveBeenCalled();+ expect(onSubmit).not.toHaveBeenCalled();+ });++ it('calls onKeyDown but still submits when the consumer does not preventDefault', () => {+ const onSubmit = vi.fn();+ const onKeyDown = vi.fn();+ render(<ChatComposerInput onSubmit={onSubmit} onKeyDown={onKeyDown} />);+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'hello';+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter'});+ expect(onKeyDown).toHaveBeenCalled();+ expect(onSubmit).toHaveBeenCalledWith('hello');+ });+ });+// Controlled-value sync used to overwrite `textContent` on every// distinct render, which (a) collapsed the caret to offset 0// (visible after a slash-command pick likediff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsxindex b54c75dd06..b53d86a93b 100644--- a/packages/core/src/Chat/ChatComposerInput.tsx+++ b/packages/core/src/Chat/ChatComposerInput.tsx@@ -11,8 +11,10 @@** ContentEditable-based rich input for the chat composer.* Supports trigger menus (@ mentions, / commands) via SearchSource,- * inline token rendering, serialization, Enter/Shift+Enter, message- * history, paste/drop file handling, and mobile-safe touch typography.+ * inline token rendering, serialization, Enter-to-submit with+ * IME-composition guarding and an onKeyDown seam for platform-specific+ * key handling, message history, paste/drop file handling, and+ * mobile-safe touch typography.*** SYNC: When modified, update:@@ -188,6 +190,21 @@ export interface ChatComposerInputProps extends Omit<onFiles?: (files: File[]) => void;/** Submit handler (Enter without Shift) */onSubmit?: (value: string) => void;+ /**+ * Key-down handler invoked before the built-in Enter/history behavior+ * (but after an open trigger menu consumes the event).+ *+ * This is the seam for platform- or app-specific key handling:+ * - Call `event.preventDefault()` to suppress the default submit (e.g.+ * let Enter insert a newline on a touch keyboard).+ * - Add behavior by acting on the event yourself (e.g. submit on+ * Cmd/Ctrl+Enter) without calling `preventDefault()`, so the default+ * handling still runs for other keys.+ *+ * IME composition is always respected regardless of this handler: Enter+ * never submits while a composition is in progress.+ */+ onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => void;}// =============================================================================@@ -299,6 +316,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {pasteAsToken: pasteAsTokenProp,onFiles,onSubmit = composerCtx?.onSubmit,+ onKeyDown: onKeyDownProp,xstyle,className,style,@@ -477,6 +495,13 @@ export function ChatComposerInput(props: ChatComposerInputProps) {return;}+ // Consumer passthrough — runs before built-in Enter/history handling.+ // A consumer can preventDefault() to fully own the keystroke.+ onKeyDownProp?.(e);+ if (e.defaultPrevented) {+ return;+ }+// Handle Backspace near tokens — prevent browser from creating// stray <br> elements or moving the cursor unexpectedly.if (e.key === 'Backspace') {@@ -519,6 +544,13 @@ export function ChatComposerInput(props: ChatComposerInputProps) {}if (e.key === 'Enter' && !e.shiftKey) {+ // Never submit mid-composition — an IME uses Enter to commit a+ // candidate (e.g. Japanese/Chinese/Korean input), and browsers may+ // also surface the legacy keyCode 229 for composing keystrokes.+ if (e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229) {+ return;+ }+e.preventDefault();if (!editableRef.current) {return;@@ -583,7 +615,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {}}},- [hasHistory, onSubmit, onChange, emitChange, triggerMenu],+ [hasHistory, onSubmit, onChange, emitChange, triggerMenu, onKeyDownProp],);const handlePaste = useCallback(