Skip to content

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

TypeScript

fix(chat): paste silently dropped when XDSChatComposerInput has no forwarded ref (#2179)

Alexander Blom5e58a51ef8e6
diff --git a/packages/core/src/Chat/XDSChatComposerInput.test.tsx b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
index a8295cfa8c..7f7fec6b22 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
@@ -146,6 +146,117 @@ describe('XDSChatComposerInput', () => {
});
});
+ // Paste / insert paths used to bail silently when the contenteditable
+ // was programmatically focused but no Selection range existed inside
+ // it — the common case after `XDSChatComposer.handleBodyClick` calls
+ // `editable.focus()`. Browsers do not create a Range on bare focus.
+ // See `chatComposerSelection.ts`.
+ describe('selection recovery (no range inside editable)', () => {
+ function clearSelection() {
+ window.getSelection()?.removeAllRanges();
+ }
+
+ it('paste inserts plain text after a focus() with no selection range', () => {
+ const onChange = vi.fn();
+ render(<XDSChatComposerInput onChange={onChange} />);
+ const textbox = screen.getByRole('textbox');
+
+ textbox.focus();
+ clearSelection();
+ expect(window.getSelection()?.rangeCount ?? 0).toBe(0);
+
+ fireEvent.paste(textbox, {
+ clipboardData: {
+ files: [],
+ getData: (type: string) => (type === 'text/plain' ? 'hello' : ''),
+ },
+ });
+
+ expect(textbox.textContent).toBe('hello');
+ expect(onChange).toHaveBeenLastCalledWith('hello');
+ });
+
+ it('paste inserts a token chip for long pastes after a focus() with no selection range', () => {
+ render(<XDSChatComposerInput />);
+ const textbox = screen.getByRole('textbox');
+
+ textbox.focus();
+ clearSelection();
+
+ // Default pasteAsToken threshold is 200 chars.
+ const long = 'a'.repeat(250);
+ fireEvent.paste(textbox, {
+ clipboardData: {
+ files: [],
+ getData: (type: string) => (type === 'text/plain' ? long : ''),
+ },
+ });
+
+ expect(textbox.querySelector('[data-xds-token]')).toBeInTheDocument();
+ });
+
+ it('imperative insertToken works after a focus() with no selection range', () => {
+ let handle: XDSChatComposerInputHandle | null = null;
+ render(
+ <XDSChatComposerInput
+ ref={h => {
+ handle = h;
+ }}
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+
+ textbox.focus();
+ clearSelection();
+
+ handle!.insertToken({
+ value: '@sam',
+ label: '@Sam Rivera',
+ variant: 'blue' as const,
+ });
+
+ expect(textbox.querySelector('[data-xds-token]')).toBeInTheDocument();
+ });
+
+ it('imperative insertText works after a focus() with no selection range', () => {
+ let handle: XDSChatComposerInputHandle | null = null;
+ render(
+ <XDSChatComposerInput
+ ref={h => {
+ handle = h;
+ }}
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+
+ textbox.focus();
+ clearSelection();
+
+ handle!.insertText('hello');
+ expect(textbox.textContent).toContain('hello');
+ });
+
+ it('paste falls through to plain-text path when pasteAsToken={false}', () => {
+ const onChange = vi.fn();
+ render(<XDSChatComposerInput pasteAsToken={false} onChange={onChange} />);
+ const textbox = screen.getByRole('textbox');
+
+ textbox.focus();
+ clearSelection();
+
+ const long = 'b'.repeat(250);
+ fireEvent.paste(textbox, {
+ clipboardData: {
+ files: [],
+ getData: (type: string) => (type === 'text/plain' ? long : ''),
+ },
+ });
+
+ expect(textbox.querySelector('[data-xds-token]')).not.toBeInTheDocument();
+ expect(textbox.textContent).toBe(long);
+ });
+ });
+
describe('triggers', () => {
it('accepts triggers with searchSource', () => {
const triggers = [createMentionTrigger()];
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsx
index d6e166011e..ac9fbc612e 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx
@@ -45,6 +45,7 @@ import {
useXDSChatComposerTokens,
isCustomToken,
} from './useXDSChatComposerTokens';
+import {ensureCaretInside, insertTextAtCursor} from './chatComposerSelection';
import {XDSChatPastedTextToken} from './XDSChatPastedTextToken';
import {
useXDSChatPasteAsToken,
@@ -263,24 +264,6 @@ function serialize(node: Node): string {
return result;
}
-/** Insert plain text at the current selection using the Selection API. */
-function insertTextAtCursor(text: string): void {
- const selection = window.getSelection();
- if (!selection || selection.rangeCount === 0) return;
-
- const range = selection.getRangeAt(0);
- range.deleteContents();
-
- const textNode = document.createTextNode(text);
- range.insertNode(textNode);
-
- // Move cursor after inserted text
- range.setStartAfter(textNode);
- range.collapse(true);
- selection.removeAllRanges();
- selection.addRange(range);
-}
-
// =============================================================================
// Component
// =============================================================================
@@ -322,19 +305,23 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
>(() => undefined);
const insertTextRef = useRef<(text: string) => void>(() => {});
- useImperativeHandle(ref, () => {
- const h: XDSChatComposerInputHandle = {
- insertToken: (token: XDSChatComposerToken) =>
- insertTokenRef.current(token),
- expandToken: (id: string) => tokens.expandToken(id),
- insertText: (text: string) => insertTextRef.current(text),
- focus: () => editableRef.current?.focus(),
- getValue: () =>
- serialize(editableRef.current ?? document.createElement('div')),
- };
- selfRef.current = h;
- return h;
- });
+ // A single handle object shared between the forwarded ref (via
+ // `useImperativeHandle`) and `selfRef` (used by internal consumers
+ // like paste-as-token). We can't rely on `useImperativeHandle`'s
+ // factory to populate `selfRef` because React only runs that factory
+ // when a parent attaches a ref — without this, paste-as-token would
+ // silently no-op whenever `XDSChatComposerInput` is rendered without
+ // a forwarded ref (e.g. inside `XDSChatComposer`).
+ const handle: XDSChatComposerInputHandle = {
+ insertToken: (token: XDSChatComposerToken) => insertTokenRef.current(token),
+ expandToken: (id: string) => tokens.expandToken(id),
+ insertText: (text: string) => insertTextRef.current(text),
+ focus: () => editableRef.current?.focus(),
+ getValue: () =>
+ serialize(editableRef.current ?? document.createElement('div')),
+ };
+ selfRef.current = handle;
+ useImperativeHandle(ref, () => handle);
useEffect(() => {
if (controlledValue !== undefined && editableRef.current) {
@@ -375,7 +362,9 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
: (pasteAsTokenProp ?? defaultPasteAsToken);
const insertText = useCallback((text: string) => {
- insertTextAtCursor(text);
+ const editable = editableRef.current;
+ if (!editable) return;
+ insertTextAtCursor(editable, text);
}, []);
// Keep stable refs in sync for imperative handle
@@ -505,6 +494,14 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const handlePaste = useCallback(
(e: ClipboardEvent<HTMLDivElement>) => {
+ const editable = editableRef.current;
+ if (!editable) return;
+
+ // Place a caret at the end of the editable if the Selection has
+ // no Range inside it — programmatic focus alone doesn't create
+ // one in Chromium/Firefox.
+ ensureCaretInside(editable);
+
// Handle paste near/into tokens first
if (tokens.handlePaste(e)) {
return;
@@ -533,7 +530,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
return;
}
- insertTextAtCursor(text);
+ insertTextAtCursor(editable, text);
emitChange();
},
[onFiles, onPasteProp, emitChange, tokens, pasteAsToken],
diff --git a/packages/core/src/Chat/chatComposerSelection.ts b/packages/core/src/Chat/chatComposerSelection.ts
new file mode 100644
index 0000000000..919b05328b
--- /dev/null
+++ b/packages/core/src/Chat/chatComposerSelection.ts
@@ -0,0 +1,84 @@
+'use client';
+
+/**
+ * @file chatComposerSelection.ts
+ * @input Uses DOM Selection / Range APIs
+ * @output Exports selection helpers used by the chat composer
+ * @position Internal helper module shared by XDSChatComposerInput and useXDSChatComposerTokens
+ *
+ * Selection helpers for the contentEditable chat input. Both the
+ * imperative `insertToken` / `insertText` APIs and the paste pipeline
+ * need a valid Range inside the editable before they can mutate the
+ * DOM. Browsers do NOT create a Selection range when an element is
+ * programmatically focused — a Range only exists once the user has
+ * clicked inside the editable or we've created one explicitly.
+ *
+ * `ensureCaretInside` centralizes the fallback: if the current
+ * Selection has no Range inside the given editable, place a collapsed
+ * caret at the end of the editable. Callers can then read
+ * `selection.getRangeAt(0)` safely.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Chat/XDSChatComposerInput.tsx (consumer)
+ * - /packages/core/src/Chat/useXDSChatComposerTokens.ts (consumer)
+ */
+
+/**
+ * Ensure the current Selection has a Range inside `editable`.
+ *
+ * If `window.getSelection()` already has a Range whose `startContainer`
+ * is inside `editable`, this is a no-op. Otherwise a collapsed caret
+ * is placed at the end of `editable` and the Selection is updated.
+ *
+ * Returns the live `Selection` on success, or `null` if no Selection
+ * is available at all (e.g. detached document, JSDOM without selection
+ * support).
+ */
+export function ensureCaretInside(editable: HTMLElement): Selection | null {
+ const selection = window.getSelection();
+ if (!selection) return null;
+
+ if (selection.rangeCount > 0) {
+ const existing = selection.getRangeAt(0);
+ if (editable.contains(existing.startContainer)) {
+ return selection;
+ }
+ }
+
+ const range = document.createRange();
+ range.selectNodeContents(editable);
+ range.collapse(false); // collapse to end
+ selection.removeAllRanges();
+ selection.addRange(range);
+ return selection;
+}
+
+/**
+ * Insert plain text at the current selection, scoped to `editable`.
+ *
+ * Ensures a caret exists inside `editable` first (see `ensureCaretInside`)
+ * so callers don't have to manage Selection state to make insertion work
+ * — e.g. after a programmatic focus that didn't create a Range.
+ *
+ * Returns `true` if text was inserted, `false` only if the Selection
+ * API is unavailable.
+ */
+export function insertTextAtCursor(
+ editable: HTMLElement,
+ text: string,
+): boolean {
+ const selection = ensureCaretInside(editable);
+ if (!selection || selection.rangeCount === 0) return false;
+
+ const range = selection.getRangeAt(0);
+ range.deleteContents();
+
+ const textNode = document.createTextNode(text);
+ range.insertNode(textNode);
+
+ range.setStartAfter(textNode);
+ range.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ return true;
+}
diff --git a/packages/core/src/Chat/useXDSChatComposerTokens.ts b/packages/core/src/Chat/useXDSChatComposerTokens.ts
index f0c1c90209..5fbe7fa46c 100644
--- a/packages/core/src/Chat/useXDSChatComposerTokens.ts
+++ b/packages/core/src/Chat/useXDSChatComposerTokens.ts
@@ -19,6 +19,7 @@
*/
import {useCallback, useState} from 'react';
+import {ensureCaretInside, insertTextAtCursor} from './chatComposerSelection';
import type {
XDSChatComposerToken,
XDSChatComposerTokenCustom,
@@ -67,20 +68,6 @@ export function isCustomToken(
return 'render' in token && typeof token.render === 'function';
}
-/** Insert plain text at the current selection. */
-function insertTextAtCursor(text: string): void {
- const selection = window.getSelection();
- if (!selection || selection.rangeCount === 0) return;
- const range = selection.getRangeAt(0);
- range.deleteContents();
- const textNode = document.createTextNode(text);
- range.insertNode(textNode);
- range.setStartAfter(textNode);
- range.collapse(true);
- selection.removeAllRanges();
- selection.addRange(range);
-}
-
/** Check if a node is inside or is a token span. */
function isInsideToken(node: Node): HTMLElement | null {
let current: Node | null = node;
@@ -112,7 +99,9 @@ export function useXDSChatComposerTokens({
const editable = editableRef.current;
if (!editable) return;
- const selection = window.getSelection();
+ // Place a caret at the end of the editable if there's no Range
+ // inside it (programmatic focus does not create one).
+ const selection = ensureCaretInside(editable);
if (!selection || selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
@@ -199,7 +188,10 @@ export function useXDSChatComposerTokens({
// --- Paste near tokens ---
const handlePaste = useCallback(
(e: React.ClipboardEvent): boolean => {
- const selection = window.getSelection();
+ const editable = editableRef.current;
+ if (!editable) return false;
+
+ const selection = ensureCaretInside(editable);
if (!selection || selection.rangeCount === 0) return false;
const range = selection.getRangeAt(0);
@@ -223,14 +215,14 @@ export function useXDSChatComposerTokens({
selection.removeAllRanges();
selection.addRange(newRange);
- insertTextAtCursor(text);
+ insertTextAtCursor(editable, text);
onEmitChange();
return true;
}
return false;
},
- [onEmitChange],
+ [editableRef, onEmitChange],
);
// --- Expand token (replace with text) ---