Skip to content

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

TypeScript

fix(core): preserve caret in XDSChatComposerInput on controlled-value updates (#2397)

Alexander Blom5bafec3ba2ad
diff --git a/.changeset/chat-composer-caret-preservation.md b/.changeset/chat-composer-caret-preservation.md
new file mode 100644
index 0000000000..fbbb990b12
--- /dev/null
+++ b/.changeset/chat-composer-caret-preservation.md
@@ -0,0 +1,5 @@
+---
+'@xds/core': patch
+---
+
+`XDSChatComposerInput`: preserve the caret when the parent updates the controlled `value`. Previously the controlled-value sync effect wrote `textContent = value` on every change, which collapsed the caret to offset 0 — visible after a slash-command pick like `setValue('/feedback ')`, where the next keystroke landed at the start of the input. The effect now skips echoes of its own emission (no redundant DOM rebuild) and restores the caret to the end of the new content when the editable is focused.
diff --git a/packages/core/src/Chat/XDSChatComposerInput.test.tsx b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
index 1ab2b53b82..0b2139703c 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
@@ -131,6 +131,97 @@ describe('XDSChatComposerInput', () => {
});
});
+ // 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 like
+ // `setValue('/feedback ')` — the next keystroke landed at the
+ // start of the input) and (b) ran a redundant DOM rebuild on every
+ // echo of our own `onChange` emission. The effect now skips echoes
+ // of its own emission and restores the caret to the end of the new
+ // content when the editable is focused.
+ describe('controlled value sync', () => {
+ it('places caret at end after a programmatic value change while focused', () => {
+ const {rerender} = render(
+ <XDSChatComposerInput value="/" onChange={() => {}} />,
+ );
+ const textbox = screen.getByRole('textbox');
+ textbox.focus();
+
+ rerender(<XDSChatComposerInput value="/feedback " onChange={() => {}} />);
+
+ expect(textbox.textContent).toBe('/feedback ');
+ const selection = window.getSelection();
+ expect(selection).not.toBeNull();
+ expect(selection?.rangeCount).toBe(1);
+ const range = selection!.getRangeAt(0);
+ expect(range.collapsed).toBe(true);
+ // Caret is at the end of the editable's contents — the next
+ // keystroke will append, not prepend.
+ expect(
+ range.endContainer === textbox ||
+ range.endContainer.parentNode === textbox,
+ ).toBe(true);
+ expect(textbox.textContent?.length).toBe(10);
+ expect(range.endOffset).toBe(
+ range.endContainer.nodeType === Node.TEXT_NODE
+ ? (range.endContainer.textContent?.length ?? 0)
+ : textbox.childNodes.length,
+ );
+ });
+
+ it('does not touch the DOM when controlled value echoes our own emission', () => {
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <XDSChatComposerInput value="" onChange={onChange} />,
+ );
+ const textbox = screen.getByRole('textbox');
+ textbox.focus();
+ // User types `hello` — emitted via onChange.
+ textbox.textContent = 'hello';
+ fireEvent.input(textbox);
+ expect(onChange).toHaveBeenLastCalledWith('hello');
+ // Parent commits the echo. The effect must not rebuild the DOM,
+ // otherwise the caret would jump back to offset 0.
+ const textNodeBefore = textbox.firstChild;
+ rerender(<XDSChatComposerInput value="hello" onChange={onChange} />);
+ expect(textbox.firstChild).toBe(textNodeBefore);
+ expect(textbox.textContent).toBe('hello');
+ });
+
+ it('writes textContent on a true external value change while unfocused', () => {
+ const {rerender} = render(
+ <XDSChatComposerInput value="hello" onChange={() => {}} />,
+ );
+ const textbox = screen.getByRole('textbox');
+ expect(textbox.textContent).toBe('hello');
+ // Unfocused programmatic change — still applied, no caret work.
+ rerender(<XDSChatComposerInput value="world" onChange={() => {}} />);
+ expect(textbox.textContent).toBe('world');
+ });
+
+ it('does not stale-cache an emitted value across an external override', () => {
+ // Regression: a permanent cache of "last emitted" would
+ // incorrectly skip a later external set back to the emitted
+ // string. The marker is one-shot — consumed by the first
+ // matching commit or invalidated by any non-echoing update.
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <XDSChatComposerInput value="" onChange={onChange} />,
+ );
+ const textbox = screen.getByRole('textbox');
+ textbox.focus();
+ textbox.textContent = 'hello';
+ fireEvent.input(textbox);
+ // External override — clears the pending echo marker.
+ rerender(<XDSChatComposerInput value="world" onChange={onChange} />);
+ expect(textbox.textContent).toBe('world');
+ // Parent now sets the value back to what we previously emitted.
+ // The effect must apply this — the stale marker is gone.
+ rerender(<XDSChatComposerInput value="hello" onChange={onChange} />);
+ expect(textbox.textContent).toBe('hello');
+ });
+ });
+
describe('file handling', () => {
it('calls onFiles on paste with files', () => {
const onFiles = vi.fn();
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsx
index 32f27b1b33..528963958d 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx
@@ -311,6 +311,16 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const historyRef = useRef<string[]>([]);
const historyIndexRef = useRef(-1);
const currentDraftRef = useRef('');
+ // One-shot marker: when set, holds the value we expect the parent
+ // to echo back as `controlledValue` after our latest `onChange`
+ // emission. We use it to skip a single `useEffect` resync, because
+ // resyncing would (a) collapse the caret to offset 0 and (b)
+ // discard any characters the user typed between the emit and the
+ // resulting commit. Cleared on consumption — either when the echo
+ // arrives or when a non-echoing external update overwrites it — so
+ // a later external set back to the same string is never
+ // incorrectly skipped.
+ const pendingEchoValueRef = useRef<string | undefined>(undefined);
// Stable refs for imperative handle callbacks (avoid re-creating handle on every render)
const insertTokenRef = useRef<
@@ -337,12 +347,44 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
useImperativeHandle(handleRef, () => handle);
useEffect(() => {
- if (controlledValue !== undefined && editableRef.current) {
- const current = serialize(editableRef.current);
- if (current !== controlledValue) {
- editableRef.current.textContent = controlledValue;
- setIsEmpty(controlledValue.length === 0);
+ if (controlledValue === undefined || !editableRef.current) {
+ return;
+ }
+ // Skip exactly one echo of our most recent `onChange` emission:
+ // the DOM is already authoritative for that value, and the user
+ // may have typed more characters between the emit and this
+ // effect running. Consume the marker so a later external set to
+ // the same string is still applied.
+ if (controlledValue === pendingEchoValueRef.current) {
+ pendingEchoValueRef.current = undefined;
+ return;
+ }
+ const editable = editableRef.current;
+ if (serialize(editable) !== controlledValue) {
+ // Genuine external override — invalidate any stale pending
+ // echo before we rewrite the DOM.
+ pendingEchoValueRef.current = undefined;
+ const wasFocused = document.activeElement === editable;
+ editable.textContent = controlledValue;
+ // Setting `textContent` tears down the existing text node,
+ // which collapses any Selection inside this editable to
+ // offset 0. If the user was focused (e.g. a programmatic
+ // insert from a slash-menu pick), restore the caret to the
+ // end of the new content so the next keystroke appends rather
+ // than prepends.
+ if (wasFocused) {
+ const selection = window.getSelection();
+ if (selection) {
+ const range = document.createRange();
+ range.selectNodeContents(editable);
+ range.collapse(false);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ }
}
+ setIsEmpty(controlledValue.length === 0);
+ } else {
+ pendingEchoValueRef.current = undefined;
}
}, [controlledValue]);
@@ -360,8 +402,10 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
'[data-xds-token], [data-xds-dictation-interim]',
) != null;
const trimmedEmpty = text.trim().length === 0 && !hasTokens;
+ const nextValue = trimmedEmpty ? '' : text;
+ pendingEchoValueRef.current = nextValue;
setIsEmpty(trimmedEmpty);
- onChange?.(trimmedEmpty ? '' : text);
+ onChange?.(nextValue);
cleanupPortalsRef.current?.();
}, [onChange]);