Skip to content

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

TypeScript

fix(Chat): anchor trigger menu to cursor position (#1354)

Cindy Zhang58558fee6b2d
diff --git a/packages/core/src/Chat/XDSChatComposerInput.test.tsx b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
index 80ee8afbd3..a8295cfa8c 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.test.tsx
@@ -353,4 +353,161 @@ describe('XDSChatComposerInput', () => {
).toBeInTheDocument();
});
});
+
+ describe('trigger menu cursor anchor', () => {
+ // The trigger menu anchors its popover to the cursor position, not the
+ // entire input element. In real browsers this creates a fixed-position
+ // span on document.body at the cursor rect. In jsdom (no layout engine)
+ // it falls back to anchoring on the editable element.
+ //
+ // These tests verify:
+ // 1. No anchor spans leak inside the contentEditable (text nodes stay intact)
+ // 2. The fallback path works (popover opens without errors)
+ // 3. selectItem cleans up properly — trigger text is fully replaced
+ // 4. No orphaned spans on document.body after menu dismiss
+
+ const BODY_ANCHOR_SELECTOR = 'span[data-xds-trigger-anchor]';
+
+ function setupTriggerInput(triggers: XDSChatComposerTrigger[]) {
+ const onChange = vi.fn();
+ const result = render(
+ <XDSChatComposerInput triggers={triggers} onChange={onChange} />,
+ );
+ const textbox = screen.getByRole('textbox');
+ textbox.focus();
+ return {...result, textbox, onChange};
+ }
+
+ function setCursorAfterText(textbox: HTMLElement, text: string): Text {
+ const textNode = document.createTextNode(text);
+ textbox.appendChild(textNode);
+ const sel = window.getSelection()!;
+ const range = document.createRange();
+ range.setStart(textNode, text.length);
+ range.collapse(true);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ return textNode;
+ }
+
+ afterEach(() => {
+ // Clean up any orphaned anchor spans from document.body
+ document
+ .querySelectorAll(BODY_ANCHOR_SELECTOR)
+ .forEach(el => el.remove());
+ });
+
+ it('does not insert spans inside the contentEditable', () => {
+ const {textbox} = setupTriggerInput([createMentionTrigger()]);
+
+ setCursorAfterText(textbox, 'hello @');
+ fireEvent.input(textbox);
+
+ // No stray spans inside the editable — text nodes stay intact
+ const spans = textbox.querySelectorAll('span[aria-hidden="true"]');
+ expect(spans.length).toBe(0);
+ });
+
+ it('opens trigger menu without errors in jsdom fallback path', () => {
+ const {textbox} = setupTriggerInput([createMentionTrigger()]);
+
+ // jsdom returns zero-rect from getBoundingClientRect, so the
+ // fallback anchors on the editable. No crash.
+ setCursorAfterText(textbox, '@');
+ fireEvent.input(textbox);
+
+ // The popover opened — ARIA says expanded
+ expect(textbox.getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('does not throw when Escape dismisses the menu', () => {
+ const {textbox} = setupTriggerInput([createMentionTrigger()]);
+
+ setCursorAfterText(textbox, '@');
+ fireEvent.input(textbox);
+ expect(textbox.getAttribute('aria-expanded')).toBe('true');
+
+ // Escape should not throw — popover hide works in jsdom even
+ // if aria-expanded doesn't update synchronously
+ expect(() => fireEvent.keyDown(textbox, {key: 'Escape'})).not.toThrow();
+ });
+
+ it('does not throw when trigger text is cleared', () => {
+ const {textbox} = setupTriggerInput([createMentionTrigger()]);
+
+ setCursorAfterText(textbox, '@');
+ fireEvent.input(textbox);
+ expect(textbox.getAttribute('aria-expanded')).toBe('true');
+
+ // Clearing text removes the trigger — should not throw
+ textbox.textContent = '';
+ expect(() => fireEvent.input(textbox)).not.toThrow();
+ });
+
+ it('does not create body anchor when no trigger is active', () => {
+ const {textbox} = setupTriggerInput([createMentionTrigger()]);
+
+ setCursorAfterText(textbox, 'hello');
+ fireEvent.input(textbox);
+
+ expect(textbox.getAttribute('aria-expanded')).toBe('false');
+ expect(document.querySelector(BODY_ANCHOR_SELECTOR)).toBeNull();
+ });
+
+ it('serialized output is clean — no anchor artifacts', () => {
+ let handle: XDSChatComposerInputHandle | null = null;
+ const triggers = [createMentionTrigger()];
+ const onChange = vi.fn();
+ render(
+ <XDSChatComposerInput
+ ref={h => {
+ handle = h;
+ }}
+ triggers={triggers}
+ onChange={onChange}
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+ textbox.focus();
+
+ setCursorAfterText(textbox, 'hello @');
+ fireEvent.input(textbox);
+
+ expect(handle!.getValue()).toBe('hello @');
+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1];
+ expect(lastCall[0]).toBe('hello @');
+ });
+
+ it('text nodes stay contiguous — no splits from anchor insertion', () => {
+ const {textbox} = setupTriggerInput([createMentionTrigger()]);
+
+ setCursorAfterText(textbox, 'hello @cin');
+ fireEvent.input(textbox);
+
+ // All text is in a single text node — no splitting
+ const textNodes = Array.from(textbox.childNodes).filter(
+ n => n.nodeType === Node.TEXT_NODE,
+ );
+ expect(textNodes.length).toBe(1);
+ expect(textNodes[0].textContent).toBe('hello @cin');
+ });
+
+ it('cleans up on unmount without errors', () => {
+ const {textbox, unmount} = setupTriggerInput([createMentionTrigger()]);
+
+ setCursorAfterText(textbox, '@');
+ fireEvent.input(textbox);
+
+ expect(() => unmount()).not.toThrow();
+ });
+
+ it('works with / command trigger', () => {
+ const {textbox} = setupTriggerInput([createCommandTrigger()]);
+
+ setCursorAfterText(textbox, '/');
+ fireEvent.input(textbox);
+
+ expect(textbox.getAttribute('aria-expanded')).toBe('true');
+ });
+ });
});
diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsx
index e7453113b1..b43d783345 100644
--- a/packages/core/src/Chat/useTriggerMenu.tsx
+++ b/packages/core/src/Chat/useTriggerMenu.tsx
@@ -258,9 +258,18 @@ export function useTriggerMenu(
const triggerStartRef = useRef<number>(-1);
const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const anchorSpanRef = useRef<HTMLSpanElement | null>(null);
+
+ const removeAnchorSpan = useCallback(() => {
+ if (anchorSpanRef.current) {
+ anchorSpanRef.current.remove();
+ anchorSpanRef.current = null;
+ }
+ }, []);
const popover = useXDSPopover({
onHide: useCallback(() => {
+ removeAnchorSpan();
setState(prev => ({
...prev,
isActive: false,
@@ -270,7 +279,7 @@ export function useTriggerMenu(
highlightedIndex: 0,
isLoading: false,
}));
- }, []),
+ }, [removeAnchorSpan]),
hasLightDismiss: true,
hasCloseButton: false,
hasAutoFocus: false,
@@ -282,8 +291,9 @@ export function useTriggerMenu(
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
+ removeAnchorSpan();
};
- }, []);
+ }, [removeAnchorSpan]);
const reset = useCallback(() => {
if (searchTimeoutRef.current) {
@@ -295,15 +305,62 @@ export function useTriggerMenu(
if (trigger?.searchSource) {
trigger.searchSource.cancel?.();
}
+ removeAnchorSpan();
popover.hide();
triggerStartRef.current = -1;
- }, [popover, state.activeTrigger]);
+ }, [popover, state.activeTrigger, removeAnchorSpan]);
+ // Anchor the popover to the cursor position (not the entire input).
+ // We append a zero-size span to document.body positioned at the cursor
+ // rect — outside the contentEditable to avoid splitting text nodes.
const setAnchor = useCallback(() => {
const editable = editableRef.current;
if (!editable) return;
- popover.triggerRef(editable);
- }, [editableRef, popover]);
+
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) {
+ popover.triggerRef(editable);
+ return;
+ }
+
+ removeAnchorSpan();
+
+ const range = selection.getRangeAt(0).cloneRange();
+ range.collapse(true);
+
+ // getBoundingClientRect is unavailable in some environments (e.g. jsdom)
+ const rect =
+ typeof range.getBoundingClientRect === 'function'
+ ? range.getBoundingClientRect()
+ : null;
+
+ // Fall back to the editable when layout info is unavailable
+ if (
+ !rect ||
+ (rect.width === 0 &&
+ rect.height === 0 &&
+ rect.top === 0 &&
+ rect.left === 0)
+ ) {
+ popover.triggerRef(editable);
+ return;
+ }
+
+ const span = document.createElement('span');
+ span.setAttribute('aria-hidden', 'true');
+ span.setAttribute('data-xds-trigger-anchor', '');
+ span.style.position = 'fixed';
+ span.style.left = `${rect.left}px`;
+ span.style.top = `${rect.top}px`;
+ span.style.width = `${Math.max(rect.width, 1)}px`;
+ span.style.height = `${rect.height}px`;
+ span.style.pointerEvents = 'none';
+ span.style.opacity = '0';
+ document.body.appendChild(span);
+
+ anchorSpanRef.current = span;
+ popover.triggerRef(span);
+ }, [editableRef, popover, removeAnchorSpan]);
const searchItems = useCallback(
(trigger: XDSChatComposerTrigger, query: string) => {
@@ -364,6 +421,11 @@ export function useTriggerMenu(
const editable = editableRef.current;
if (!editable) return;
+ // Clean up anchor span before modifying DOM — if the span were
+ // inside the editable it would split text nodes and break offsets.
+ // With the body-appended approach this is just bookkeeping.
+ removeAnchorSpan();
+
deleteTriggerText(editable, triggerStartRef.current);
const result = trigger.onSelect(item);
@@ -379,6 +441,7 @@ export function useTriggerMenu(
[
state.activeTrigger,
editableRef,
+ removeAnchorSpan,
onInsertText,
onInsertToken,
onEmitChange,
@@ -556,9 +619,9 @@ export function useTriggerMenu(
aria-selected={idx === state.highlightedIndex}
tabIndex={-1}
onMouseDown={e => {
- e.preventDefault(); // Keep focus in the editable
- selectItem(item);
- }}
+ e.preventDefault(); // Keep focus in the editable
+ selectItem(item);
+ }}
onMouseEnter={() =>
setState(prev => ({...prev, highlightedIndex: idx}))
}