An open source design system that's fully customizable and agent ready
TypeScript
fix(ChatComposerInput): an imperative insertToken reports its value through onChange (#10167)
Cindy Zhange40adf9aa60a
diff --git a/.changeset/chat-insert-token-onchange.md b/.changeset/chat-insert-token-onchange.mdnew file mode 100644index 0000000000..d47951802f--- /dev/null+++ b/.changeset/chat-insert-token-onchange.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[fix] Inserting a token through `ChatComposerInput`'s handle (`insertToken`) now reports the new value through `onChange` once, as typing does, and hides the placeholder. Before, a controlled host's Send button stayed disabled or sent a stale prompt. The `ai-chat-landing` page template drops the input-event workaround it used to sync the composer after an insert.++@cixzhangdiff --git a/docs/specs/components/Chat/ChatComposerInput.spec.md b/docs/specs/components/Chat/ChatComposerInput.spec.mdindex 53d7b39699..61768043bb 100644--- a/docs/specs/components/Chat/ChatComposerInput.spec.md+++ b/docs/specs/components/Chat/ChatComposerInput.spec.md@@ -41,7 +41,7 @@ system_specs: [spec:AST-002, spec:AST-029]| Behavior | Every edit path keeps the serialized draft observable. Files pasted or dropped reach `onFiles`; consumer `onPaste` receives first refusal over plain text before optional paste-as-token conversion. || End-user impact | Dictated or otherwise programmatically inserted text is sendable and never hidden behind the empty placeholder; dropped files reach the product attachment flow. On a phone, the Return key says Send, which is what Enter does. || Builder impact | Existing props, callback signatures, exports, and token serialization are unchanged. Builders relying on the documented `onPaste` and `onFiles` paths receive those callbacks except where FR5 and FR6 record implementation gaps; `hasMultiWordQuery` is an added optional trigger field, and `enterKeyHint` an added optional prop whose `send` default a composer that makes Enter insert a line break replaces with `enter` (FR17). Every trigger receives the trigger-key corrections listed under Compatibility and migration (FR10, FR13, FR15, FR16). |-| Compatibility/readiness | Patch-compatible. One additive optional trigger field (DEC-1), one additive optional prop with a keyboard-hint default (DEC-2, a patch `[feat]` under `spec:AST-017` FR5, FR7), plus trigger-key corrections that apply to every trigger (FR10, FR13, FR15, FR16); no visual decision. Implementation gaps are recorded inline on FR1, FR5, FR6, FR10, and PR2. |+| Compatibility/readiness | Patch-compatible. One additive optional trigger field (DEC-1), one additive optional prop with a keyboard-hint default (DEC-2, a patch `[feat]` under `spec:AST-017` FR5, FR7), plus trigger-key corrections that apply to every trigger (FR10, FR13, FR15, FR16); no visual decision. Implementation gaps are recorded inline on FR5, FR6, FR10, and PR2. || Review checks | Reject an edit path that mutates the DOM without updating the serialized draft, a file drop that can navigate away or bypass `onFiles`, a text paste that bypasses consumer interception, changed submit/token semantics, a trigger query that alters typed text, a key that picks a row from an earlier trigger query, a menu that reopens after a send, a Return key label that changes what Enter does, or an `enterKeyHint` type that accepts any string. || Governing rules | `architecture:public-component-api/INV1`, `INV2`–`INV4`, `INV25`; `architecture:interaction-modality/INV1–INV4`; `architecture:knowledge-contracts/INV11, INV16`; `spec:AST-002`; `spec:AST-029`; `component:TextInput/FR16, DEC-1`; rubric B15. |@@ -102,7 +102,7 @@ imperative editing handle.| ID | Invariant | Basis || ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |-| FR1 | Every user or imperative edit that changes serialized content MUST update empty state and emit the effective value through the active `onChange` channel. Implementation gap: `handleRef.insertToken` inserts the token without emitting the value through `onChange` or updating empty state, so the placeholder stays visible. | Shipped `onChange` contract, imperative handle, and ChatDictation callsite. |+| FR1 | Every user or imperative edit that changes serialized content MUST update empty state and emit the effective value through the active `onChange` channel. An imperative `handleRef.insertToken` emits once, as typing does. | Shipped `onChange` contract, imperative handle, and ChatDictation callsite. || FR2 | Enter without Shift MUST submit one trimmed non-empty draft and clear it unless the event is composing, the trigger menu consumes it, or a consumer prevents default. | Shipped implementation and consumer docs. || FR3 | Shift+Enter and mid-text history arrows MUST retain native multiline editing behavior. | Shipped implementation and focused tests. || FR4 | `value` supplied directly on ChatComposerInput MUST win over ChatComposer context, while an emitted echo MUST NOT rebuild the DOM or move the caret. | Shipped controlled precedence and regression tests. |@@ -131,7 +131,7 @@ imperative editing handle.| State | Required invariant | Allowed variation || ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------- || empty | Placeholder is visible and the serialized value is empty. | Placeholder copy. |-| typed or imperatively inserted text | Placeholder is absent and the same serialized value is observable to ChatComposer and callbacks (FR1 records an implementation gap). | Draft content. |+| typed or imperatively inserted text | Placeholder is absent and the same serialized value is observable to ChatComposer and callbacks, an imperative token included (FR1). | Draft content. || controlled update | External value is reflected without corrupting a live caret or treating a stale echo as authoritative. | Parent update timing. || trigger menu open | Combobox semantics and active option wiring are exposed; menu interaction owns its keys. | Search source and item rendering. || trigger search pending | Enter submits the draft as typed; no earlier query's row can be picked. | Loading copy and source latency. |@@ -185,7 +185,7 @@ add a theming target or decide a new visual state.| Contract | Verification | Representative states | Mutation or failure expectation | Audit section || --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- |-| FR1, ORD1–ORD2 | focused imperative insertion and controlled-sync tests; `ImperativeInsertion` play | empty → inserted text; controlled echo; external override | Text appears only in the DOM, placeholder remains, callback is stale, or the caret jumps. | `audit:ChatComposerInput/behavior` |+| FR1, ORD1–ORD2 | focused imperative insertion (text and token) and controlled-sync tests; `ImperativeInsertion` play | empty → inserted text; controlled echo; external override | Text appears only in the DOM, placeholder remains, callback is stale, or the caret jumps. | `audit:ChatComposerInput/behavior` || FR2–FR3, FR7–FR8, AR3 | focused keyboard, IME, trigger, and history tests | Enter; Shift+Enter; composition; cancelled key; boundary and mid-text arrows | A key submits twice, submits during composition, or steals native editing. | `audit:ChatComposerInput/interaction` || FR10–FR16, AR5 | focused trigger-query and trigger keyboard tests; "keeps the trigger menu open on a press in the editor or the menu, closes it on a press elsewhere" | single-token; multi-word; line break; length bound; pending search; no matches; IME; Escape | A query ends early or alters text, Enter picks an earlier query's row or fails to submit while a search is pending, a late result reopens the menu after a send, or a hidden menu consumes keys. | `audit:ChatComposerInput/interaction` || FR5, ORD4 | focused long-paste interception tests | consumer handled; token conversion; plain insertion | Consumer interception is skipped or multiple insertion paths run. | `audit:ChatComposerInput/behavior` |diff --git a/packages/cli/assets/templates/pages/ai-chat-landing/page.tsx b/packages/cli/assets/templates/pages/ai-chat-landing/page.tsxindex 36b162ca93..5cdace9cd6 100644--- a/packages/cli/assets/templates/pages/ai-chat-landing/page.tsx+++ b/packages/cli/assets/templates/pages/ai-chat-landing/page.tsx@@ -252,12 +252,6 @@ export default function AIChatTemplate() {const activeMode = MODE_OPTIONS.find(m => m.key === mode) ?? MODE_OPTIONS[0];const suggestions = category ? CATEGORY_SUGGESTIONS[category] : null;- // The composer's imperative insert methods mutate the DOM without emitting a- // change, so dispatch an input event to sync its value and clear the placeholder.- const syncComposerValue = () => {- document.activeElement?.dispatchEvent(new Event('input', {bubbles: true}));- };-const applySuggestion = (prompt: string) => {const input = composerInputRef.current;if (!input) {@@ -268,7 +262,6 @@ export default function AIChatTemplate() {window.getSelection()?.selectAllChildren(document.activeElement);}input.insertText(prompt);- syncComposerValue();};const insertMention = (item: (typeof MENTION_ITEMS)[number]) => {@@ -287,7 +280,6 @@ export default function AIChatTemplate() {label: item.label,variant: 'blue',});- syncComposerValue();};const insertModeToken = (label: string) => {@@ -297,7 +289,6 @@ export default function AIChatTemplate() {label,variant: 'orange',});- syncComposerValue();};return (diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsxindex 214c82374d..c0ff6c17fa 100644--- a/packages/core/src/Chat/ChatComposerInput.test.tsx+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {createRef, StrictMode, useLayoutEffect} from 'react';+import {createRef, StrictMode, useLayoutEffect, useState} from 'react';import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -276,6 +276,46 @@ describe('ChatComposerInput', () => {expect(onChange).toHaveBeenCalledWith('hello');});+ it('reports an imperative insertToken through onChange once, as typing does (FR1)', () => {+ const onChange = vi.fn();+ const handleRef = createRef<ChatComposerInputHandle>();+ render(<ChatComposerInput onChange={onChange} handleRef={handleRef} />);+ const textbox = screen.getByRole('textbox');+ textbox.focus();+ act(() => {+ handleRef.current!.insertToken({value: '@sam', label: 'Sam'});+ });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(handleRef.current!.getValue());+ expect(onChange.mock.lastCall?.[0]).toContain('@sam');+ });++ it('enables Send and sends the token after an imperative insertToken in a controlled composer (FR1)', () => {+ const onSubmit = vi.fn();+ const handleRef = createRef<ChatComposerInputHandle>();+ function Host() {+ const [value, setValue] = useState('');+ return (+ <ChatComposer+ value={value}+ onChange={setValue}+ onSubmit={onSubmit}+ input={<ChatComposerInput handleRef={handleRef} />}+ />+ );+ }+ render(<Host />);+ expect(screen.getByRole('button', {name: 'Send'})).toBeDisabled();+ screen.getByRole('textbox').focus();+ act(() => {+ handleRef.current!.insertToken({value: '@sam', label: 'Sam'});+ });+ const send = screen.getByRole('button', {name: 'Send'});+ expect(send).toBeEnabled();+ fireEvent.click(send);+ expect(onSubmit.mock.lastCall?.[0]).toContain('@sam');+ });+it('calls onSubmit on Enter', () => {const onSubmit = vi.fn();render(<ChatComposerInput onSubmit={onSubmit} />);@@ -837,7 +877,8 @@ describe('ChatComposerInput', () => {});it('paste inserts a token chip for long pastes after a focus() with no selection range', () => {- render(<ChatComposerInput />);+ const onChange = vi.fn();+ render(<ChatComposerInput onChange={onChange} />);const textbox = screen.getByRole('textbox');textbox.focus();@@ -853,6 +894,7 @@ describe('ChatComposerInput', () => {});expect(textbox.querySelector('[data-astryx-token]')).toBeInTheDocument();+ expect(onChange).toHaveBeenCalledTimes(1);});it('imperative insertToken works after a focus() with no selection range', () => {diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsxindex 384f7ce17a..51c7ff8def 100644--- a/packages/core/src/Chat/ChatComposerInput.tsx+++ b/packages/core/src/Chat/ChatComposerInput.tsx@@ -620,9 +620,21 @@ export function ChatComposerInput(props: ChatComposerInputProps) {[emitChange, insertTextWithoutEmit],);+ const insertTokenWithoutEmit = tokens.insertToken;+ const insertToken = useCallback(+ (token: ChatComposerToken) => {+ const id = insertTokenWithoutEmit(token);+ if (id != null) {+ emitChange();+ }+ return id;+ },+ [emitChange, insertTokenWithoutEmit],+ );+// A caller may retain a handle across renders. Resolve mutation permission// through the latest callbacks rather than the render that created it.- insertTokenRef.current = isDisabled ? () => undefined : tokens.insertToken;+ insertTokenRef.current = isDisabled ? () => undefined : insertToken;insertTextRef.current = isDisabled ? () => {} : insertText;expandTokenRef.current = isDisabled ? () => {} : tokens.expandToken;@@ -888,9 +900,13 @@ export function ChatComposerInput(props: ChatComposerInputProps) {return;}- // Paste-as-token: convert long pastes to token chips.+ // Paste-as-token: convert long pastes to token chips. The default+ // converter inserts through the handle, which publishes the change.+ const versionBeforeToken = emitChangeVersionRef.current;if (pasteAsToken?.onPaste(e, text)) {- emitChange();+ if (emitChangeVersionRef.current === versionBeforeToken) {+ emitChange();+ }return;}