Skip to content

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

TypeScript

fix(ChatComposerInput): anchor programmatic carets into trailing text nodes for IME composition (#6411) (#6423)

Manohar Paturi1e95e11ad29c
diff --git a/.changeset/chat-composer-ime-caret-anchor.md b/.changeset/chat-composer-ime-caret-anchor.md
new file mode 100644
index 0000000000..86bc9c8240
--- /dev/null
+++ b/.changeset/chat-composer-ime-caret-anchor.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ChatComposerInput: composing with an input method (for example Japanese or Chinese) right after picking a mention, inserting a token, or inserting text after a token now commits only the composed text. The composer places its caret inside the trailing text, not on an element boundary, so the first raw letter of the composition is no longer committed. Right after a mention pick, one Backspace now removes the mention with its space, and no stray line break is left.
+
+@ManoharPaturi
diff --git a/docs/specs/components/Chat/ChatComposerInput.spec.md b/docs/specs/components/Chat/ChatComposerInput.spec.md
index 61768043bb..629115e101 100644
--- a/docs/specs/components/Chat/ChatComposerInput.spec.md
+++ b/docs/specs/components/Chat/ChatComposerInput.spec.md
@@ -119,6 +119,7 @@ imperative editing handle.
| FR15 | Keys pressed during IME composition MUST NOT pick a row or move the highlighted row. | DEC-1; FR7. |
| FR16 | Escape on a visible menu dismisses it, and the menu stays hidden while the same query keeps growing from the same trigger. While open, the menu stays open for a press on the editor or in the menu and closes for a press elsewhere (`architecture:layer-runtime`). | DEC-1. |
| FR17 | The editor carries `enterkeyhint`: the `enterKeyHint` value when one is set, otherwise `send`, because Enter sends (FR2). `enterKeyHint` takes the closed union `EnterKeyHint` (`component:TextInput` FR16), so TypeScript rejects any other value. The hint only labels the key: FR2 and FR3 decide what Enter and Shift+Enter do whatever it says, so a composer whose `onKeyDown` makes Enter insert a line break passes `enter`. ChatComposer's default input carries the same default. | DEC-2; `component:TextInput` DEC-1 |
+| FR18 | Backspace with the caret in or right after a token's trailing space, when no text follows that space, removes the token and that space in one step, and leaves the text as it was before the token was inserted, with no extra line break; an emptied last line keeps the browser's placeholder. | Current source and tests |
### Allowed variation
@@ -193,6 +194,7 @@ add a theming target or decide a new visual state.
| AR1, AR4 | role/name/ARIA tests plus exact-head accessibility and visual gates | textbox; combobox; disabled; keyboard focus | Name, role, multiline, expanded, disabled, or visible focus semantics regress. | `audit:ChatComposerInput/accessibility` |
| FR9 | ref, target, package, and repository checks | ref; BaseProps; xstyle; className; style | Root ownership or a styling seam moves or disappears. | `audit:ChatComposerInput/api` |
| FR17 | `ChatComposerInput.test.tsx` touch keyboard Return key suite (`send` by default, the set value, `send` inside ChatComposer's default input, Enter submits under every label); `ChatComposerInput.public.test.ts`, run by `pnpm typecheck`, for `EnterKeyHint` rejecting an arbitrary or unnarrowed string; `ChatComposerReturnKey.a11y.chromium.spec.ts` for the attribute on the editor a tap focuses | default; `enter`; inside ChatComposer; a phone viewport with touch emulation | A missing or wrong `enterkeyhint`, a label that stops Enter from submitting, or a type that accepts `string` fails. | `audit:ChatComposerInput/api` |
+| FR18 | `ChatComposerInput.test.tsx` "one Backspace after a token removes the token and its space" and "one Backspace on a token that starts the last line keeps that line for the caret"; `ChatComposerImeCaret.a11y.chromium.spec.ts` | after an inserted token, with no text after its space; a token that starts the last line | A token or its trailing space left after one Backspace, a line break added beyond the text before the token, or an emptied last line that loses its line, fails. | `audit:ChatComposerInput/api` |
## Decision log
diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsx
index e5ce6ea7df..0ba1958022 100644
--- a/packages/core/src/Chat/ChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx
@@ -11,6 +11,7 @@ import type {
ChatComposerTrigger,
ChatComposerInputHandle,
} from './ChatComposerInput';
+import {placeCaretAtEnd, insertTextAtCursor} from './chatComposerSelection';
import {createStaticSource} from '../Typeahead/createStaticSource';
import type {SearchableItem, SearchSource} from '../Typeahead/types';
@@ -2142,6 +2143,175 @@ describe('ChatComposerInput', () => {
expect(spy.mock.calls.length).toBeGreaterThan(callsAfterOpen);
});
});
+
+ describe('IME caret anchoring into text nodes', () => {
+ it('anchors placeCaretAtEnd inside a Text node when content is present', () => {
+ render(
+ <ChatComposer onSubmit={() => {}} input={<ChatComposerInput />} />,
+ );
+ const textbox = screen.getByRole('textbox');
+ textbox.textContent = 'hello world';
+ placeCaretAtEnd(textbox);
+
+ const selection = window.getSelection()!;
+ expect(selection.rangeCount).toBeGreaterThan(0);
+ expect(selection.anchorNode?.nodeType).toBe(Node.TEXT_NODE);
+ expect(selection.anchorOffset).toBe('hello world'.length);
+ });
+
+ it('anchors insertTextAtCursor inside the inserted text node', () => {
+ render(
+ <ChatComposer onSubmit={() => {}} input={<ChatComposerInput />} />,
+ );
+ const textbox = screen.getByRole('textbox');
+ insertTextAtCursor(textbox, 'inserted text');
+
+ const selection = window.getSelection()!;
+ expect(selection.rangeCount).toBeGreaterThan(0);
+ expect(selection.anchorNode?.nodeType).toBe(Node.TEXT_NODE);
+ expect(selection.anchorNode?.textContent).toBe('inserted text');
+ expect(selection.anchorOffset).toBe('inserted text'.length);
+ });
+
+ it('one Backspace after a token removes the token and its space', () => {
+ let handle: ChatComposerInputHandle | null = null;
+ render(
+ <ChatComposer
+ onSubmit={() => {}}
+ input={
+ <ChatComposerInput
+ handleRef={h => {
+ handle = h;
+ }}
+ />
+ }
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+ act(() => textbox.focus());
+ act(() => {
+ handle?.insertToken({
+ value: '@cindy',
+ label: '@Cindy Zhang',
+ variant: 'blue',
+ });
+ });
+ expect(textbox.querySelector('[data-astryx-token]')).not.toBeNull();
+
+ fireEvent.keyDown(textbox, {key: 'Backspace'});
+
+ expect(textbox.querySelector('[data-astryx-token]')).toBeNull();
+ expect(textbox.textContent).toBe('');
+ expect(textbox.querySelector('br')).toBeNull();
+ });
+
+ it('after one Backspace removes a token, the caret is inside the text before it', () => {
+ let handle: ChatComposerInputHandle | null = null;
+ render(
+ <ChatComposer
+ onSubmit={() => {}}
+ input={
+ <ChatComposerInput
+ handleRef={h => {
+ handle = h;
+ }}
+ />
+ }
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+ act(() => textbox.focus());
+ act(() => handle?.insertText('hey '));
+ act(() => {
+ handle?.insertToken({
+ value: '@cindy',
+ label: '@Cindy Zhang',
+ variant: 'blue',
+ });
+ });
+
+ fireEvent.keyDown(textbox, {key: 'Backspace'});
+
+ const selection = window.getSelection()!;
+ expect(textbox.textContent).toBe('hey ');
+ expect(selection.anchorNode?.nodeType).toBe(Node.TEXT_NODE);
+ expect(selection.anchorNode?.textContent).toBe('hey ');
+ expect(selection.anchorOffset).toBe('hey '.length);
+ });
+
+ it('one Backspace on a token that starts the last line keeps that line for the caret', () => {
+ let handle: ChatComposerInputHandle | null = null;
+ render(
+ <ChatComposer
+ onSubmit={() => {}}
+ input={
+ <ChatComposerInput
+ handleRef={h => {
+ handle = h;
+ }}
+ />
+ }
+ />,
+ );
+ const textbox = screen.getByRole('textbox');
+ act(() => textbox.focus());
+ act(() => handle?.insertText('hey\n'));
+ // Chromium leaves an empty text node between a line break and a token.
+ act(() => {
+ textbox.append(document.createTextNode(''));
+ const range = document.createRange();
+ range.selectNodeContents(textbox);
+ range.collapse(false);
+ window.getSelection()!.removeAllRanges();
+ window.getSelection()!.addRange(range);
+ });
+ act(() => {
+ handle?.insertToken({
+ value: '@cindy',
+ label: '@Cindy Zhang',
+ variant: 'blue',
+ });
+ });
+
+ fireEvent.keyDown(textbox, {key: 'Backspace'});
+
+ // The emptied line keeps a placeholder, as the browser's own delete
+ // does, and the caret sits on it, not at the end of the line above.
+ expect(textbox.querySelector('[data-astryx-token]')).toBeNull();
+ expect(textbox.lastChild?.nodeName).toBe('BR');
+ const selection = window.getSelection()!;
+ expect(selection.anchorNode?.nodeType).toBe(Node.TEXT_NODE);
+ expect(selection.anchorNode?.nextSibling?.nodeName).toBe('BR');
+ expect(selection.anchorOffset).toBe(0);
+ });
+
+ it('anchors caret inside trailing text node after inserting a token', async () => {
+ let handle: ChatComposerInputHandle | null = null;
+ render(
+ <ChatComposer
+ onSubmit={() => {}}
+ input={
+ <ChatComposerInput
+ handleRef={h => {
+ handle = h;
+ }}
+ />
+ }
+ />,
+ );
+ act(() => {
+ handle?.insertToken({
+ value: '@cindy',
+ label: '@Cindy Zhang',
+ variant: 'blue',
+ });
+ });
+
+ const selection = window.getSelection()!;
+ expect(selection.rangeCount).toBeGreaterThan(0);
+ expect(selection.anchorNode?.nodeType).toBe(Node.TEXT_NODE);
+ });
+ });
});
describe('ChatComposerInput trigger loading announcement (spec:AST-086)', () => {
diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsx
index 4a9d26cbc6..04e099b48e 100644
--- a/packages/core/src/Chat/ChatComposerInput.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.tsx
@@ -561,14 +561,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
// 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);
- }
+ placeCaretAtEnd(editable);
}
setIsEmpty(controlledValue.length === 0);
} else {
@@ -605,6 +598,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
onEmitChange: emitChange,
});
cleanupPortalsRef.current = tokens.cleanupPortals;
+ const handleTokenKeyDown = tokens.handleKeyDown;
// --- Paste-as-token (internal default) ---
const defaultPasteAsToken = useChatPasteAsToken({inputRef: selfRef});
@@ -713,45 +707,9 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
return;
}
- // Handle Backspace near tokens — prevent browser from creating
- // stray <br> elements or moving the cursor unexpectedly.
- if (e.key === 'Backspace') {
- const selection = window.getSelection();
- if (selection && selection.isCollapsed && selection.rangeCount > 0) {
- const range = selection.getRangeAt(0);
- const {startContainer, startOffset} = range;
-
- // Case 1: Cursor is in a text node right after a token.
- // If the text node is just the trailing NBSP, remove it
- // and place cursor after the token.
- if (
- startContainer.nodeType === Node.TEXT_NODE &&
- startOffset === 0 &&
- startContainer.previousSibling instanceof HTMLElement &&
- startContainer.previousSibling.hasAttribute('data-astryx-token')
- ) {
- // Cursor is at start of text node right after a token — let
- // the browser handle it normally (it will select/delete the token)
- } else if (
- startContainer.nodeType === Node.TEXT_NODE &&
- startContainer.textContent === ' ' &&
- startOffset <= 1 &&
- startContainer.previousSibling instanceof HTMLElement &&
- startContainer.previousSibling.hasAttribute('data-astryx-token')
- ) {
- // Cursor is in or after the trailing NBSP — remove the NBSP
- // and the token in one action
- e.preventDefault();
- const tokenSpan = startContainer.previousSibling;
- const parent = startContainer.parentNode;
- if (parent) {
- parent.removeChild(startContainer);
- parent.removeChild(tokenSpan);
- }
- emitChange();
- return;
- }
- }
+ // Backspace next to a token: the token hook owns it.
+ if (handleTokenKeyDown(e)) {
+ return;
}
if (e.key === 'Enter' && !e.shiftKey) {
@@ -862,6 +820,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
emitChange,
triggerMenu,
onKeyDownProp,
+ handleTokenKeyDown,
],
);
diff --git a/packages/core/src/Chat/__tests__/ChatComposerImeCaret.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/ChatComposerImeCaret.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..77581c5086
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatComposerImeCaret.a11y.chromium.spec.ts
@@ -0,0 +1,130 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^(packages/core/src/Chat/(ChatComposerInput|chatComposerSelection|useChatComposerTokens)|apps/storybook/stories/ChatComposerInput)
+
+/**
+ * @file ChatComposerImeCaret.a11y.chromium.spec.ts
+ * @input The `Core/ChatComposerInput` MentionTrigger story in a built
+ * Storybook, and Chromium's input-method protocol (`Input.imeSetComposition`
+ * and `Input.insertText`).
+ * @output Real-browser proof that composing right after a mention pick commits
+ * only the composed text, not the first raw letter of the composition.
+ * @position Runs in pr-a11y when the composer input, its selection helpers or
+ * their story change. jsdom has no input method, so only a browser shows
+ * where a composition anchors after the composer places the caret.
+ */
+
+import {expect, test} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+test('a composition right after a mention pick commits only the composed text', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-chatcomposerinput--mention-trigger&viewMode=story`,
+ );
+ const textbox = page.getByRole('combobox');
+ await textbox.click();
+ await page.keyboard.type('@');
+ const option = page.getByRole('option').first();
+ await expect(option).toBeVisible();
+ await page.keyboard.press('Enter');
+ const value = page.getByText(/^Value: /);
+ // The space after a token may be a no-break space.
+ await expect(value).toHaveText(/^Value: "@\S+\s"$/);
+
+ // A Japanese input method: the first key shows its raw letter as preedit
+ // text, the next turns it into kana, and the commit inserts the kana.
+ const session = await page.context().newCDPSession(page);
+ await session.send('Input.imeSetComposition', {
+ text: 'n',
+ selectionStart: 1,
+ selectionEnd: 1,
+ });
+ await session.send('Input.imeSetComposition', {
+ text: 'な',
+ selectionStart: 1,
+ selectionEnd: 1,
+ });
+ await session.send('Input.insertText', {text: 'な'});
+
+ await expect(value).toHaveText(/^Value: "@\S+\sな"$/);
+});
+
+test('a composition after one Backspace removes a just-picked mention commits only the composed text', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-chatcomposerinput--mention-trigger&viewMode=story`,
+ );
+ const textbox = page.getByRole('combobox');
+ await textbox.click();
+ await page.keyboard.type('hey @');
+ await expect(page.getByRole('option').first()).toBeVisible();
+ await page.keyboard.press('Enter');
+ const value = page.getByText(/^Value: /);
+ await expect(value).toHaveText(/^Value: "hey @\S+\s"$/);
+ await page.keyboard.press('Backspace');
+ await expect(value).toHaveText(/^Value: "hey\s"$/);
+
+ const session = await page.context().newCDPSession(page);
+ await session.send('Input.imeSetComposition', {
+ text: 'k',
+ selectionStart: 1,
+ selectionEnd: 1,
+ });
+ await session.send('Input.imeSetComposition', {
+ text: 'か',
+ selectionStart: 1,
+ selectionEnd: 1,
+ });
+ await session.send('Input.insertText', {text: 'か'});
+
+ await expect(value).toHaveText(/^Value: "hey\sか"$/);
+});
+
+test('a composition after one Backspace removes a mention that starts a line stays on that line', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-chatcomposerinput--mention-trigger&viewMode=story`,
+ );
+ const textbox = page.getByRole('combobox');
+ await textbox.click();
+ await page.keyboard.type('hey');
+ await page.keyboard.press('Shift+Enter');
+ await page.keyboard.type('@');
+ await expect(page.getByRole('option').first()).toBeVisible();
+ await page.keyboard.press('Enter');
+ const value = page.getByText(/^Value: /);
+ await expect(value).toHaveText(/^Value: "hey\\n@\S+\s"$/);
+ await page.keyboard.press('Backspace');
+
+ const session = await page.context().newCDPSession(page);
+ await session.send('Input.imeSetComposition', {
+ text: 'k',
+ selectionStart: 1,
+ selectionEnd: 1,
+ });
+ await session.send('Input.imeSetComposition', {
+ text: 'か',
+ selectionStart: 1,
+ selectionEnd: 1,
+ });
+ await session.send('Input.insertText', {text: 'か'});
+
+ await expect(value).toHaveText('Value: "hey\\nか"');
+});
diff --git a/packages/core/src/Chat/chatComposerSelection.ts b/packages/core/src/Chat/chatComposerSelection.ts
index 0f31ca85e9..e04e643bc7 100644
--- a/packages/core/src/Chat/chatComposerSelection.ts
+++ b/packages/core/src/Chat/chatComposerSelection.ts
@@ -69,6 +69,135 @@ export function restoreSelectionRange(range: Range): void {
selection.addRange(range);
}
+/**
+ * When a collapsed range sits on an element boundary, walk it into the preceding
+ * text node if one exists. Chromium anchors an IME composition to the DOM boundary
+ * where it starts; from an element boundary, the first preedit commits as raw
+ * letters instead of composing. A preceding editable element counts too: the
+ * range lands at the end of its last text node. Otherwise the range stays where
+ * it is.
+ */
+export function landInsideTrailingTextNode(
+ editable: HTMLElement,
+ range: Range,
+): void {
+ if (range.startContainer !== editable) {
+ return;
+ }
+ const offset = range.startOffset;
+ const childBefore = offset > 0 ? editable.childNodes[offset - 1] : null;
+ if (childBefore && childBefore.nodeType === Node.TEXT_NODE) {
+ const textNode = childBefore as Text;
+ range.setStart(textNode, textNode.nodeValue?.length ?? 0);
+ range.collapse(true);
+ return;
+ }
+ if (childBefore && childBefore.nodeType === Node.ELEMENT_NODE) {
+ const el = childBefore as HTMLElement;
+ if (el.isContentEditable) {
+ let current: Node = el;
+ while (current.lastChild) {
+ current = current.lastChild;
+ if (current.nodeType === Node.TEXT_NODE) {
+ const textNode = current as Text;
+ range.setStart(textNode, textNode.nodeValue?.length ?? 0);
+ range.collapse(true);
+ return;
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Collapse the Selection right after `node`, a child of `editable`, or at the
+ * start of `editable` when `node` is null. The caret lands inside the preceding
+ * text, so a composition that starts there composes.
+ */
+export function placeCaretAfterNode(
+ editable: HTMLElement,
+ node: Node | null,
+): void {
+ const selection = window.getSelection();
+ if (!selection) {
+ return;
+ }
+ const range = document.createRange();
+ if (node) {
+ range.setStartAfter(node);
+ } else {
+ range.setStart(editable, 0);
+ }
+ range.collapse(true);
+ landInsideTrailingTextNode(editable, range);
+ selection.removeAllRanges();
+ selection.addRange(range);
+}
+
+/**
+ * Whether the content up to `node` ends a line: the last non-empty node at or
+ * before it is a line break element, or text that ends in one.
+ */
+function endsLine(node: Node | null): boolean {
+ let current = node;
+ while (
+ current != null &&
+ current.nodeType === Node.TEXT_NODE &&
+ current.textContent === ''
+ ) {
+ current = current.previousSibling;
+ }
+ if (current == null) {
+ return false;
+ }
+ if (current.nodeName === 'BR') {
+ return true;
+ }
+ return (
+ current.nodeType === Node.TEXT_NODE &&
+ (current.textContent ?? '').endsWith('\n')
+ );
+}
+
+/** Whether `node` or a later sibling holds content; empty text holds none. */
+function hasContentFrom(node: Node | null): boolean {
+ for (let current = node; current != null; current = current.nextSibling) {
+ if (current.nodeType !== Node.TEXT_NODE || current.textContent !== '') {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Place the caret where a removed token was. `before` and `after` are the
+ * nodes that were next to the token and its trailing space. When the removal
+ * empties the last line, the line keeps a `<br>` placeholder, as the browser's
+ * own delete keeps it, and the caret lands in an empty text node before it, so
+ * a composition there composes. Otherwise the caret lands after `before`.
+ */
+export function placeCaretAfterRemovedToken(
+ editable: HTMLElement,
+ before: Node | null,
+ after: Node | null,
+): void {
+ if (!hasContentFrom(after) && endsLine(before)) {
+ const selection = window.getSelection();
+ if (!selection) {
+ return;
+ }
+ const text = document.createTextNode('');
+ editable.append(text, document.createElement('br'));
+ const range = document.createRange();
+ range.setStart(text, 0);
+ range.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ return;
+ }
+ placeCaretAfterNode(editable, before);
+}
+
/**
* Collapse the Selection to the very end of `editable`'s content,
* replacing whatever the Selection held before.
@@ -89,6 +218,7 @@ export function placeCaretAtEnd(editable: HTMLElement): boolean {
const range = document.createRange();
range.selectNodeContents(editable);
range.collapse(false); // collapse to end
+ landInsideTrailingTextNode(editable, range);
selection.removeAllRanges();
selection.addRange(range);
return true;
@@ -123,6 +253,7 @@ export function ensureCaretInside(editable: HTMLElement): Selection | null {
const range = document.createRange();
range.selectNodeContents(editable);
range.collapse(false); // collapse to end
+ landInsideTrailingTextNode(editable, range);
selection.removeAllRanges();
selection.addRange(range);
return selection;
@@ -262,7 +393,7 @@ export function insertTextAtCursor(
const textNode = document.createTextNode(text);
range.insertNode(textNode);
- range.setStartAfter(textNode);
+ range.setStart(textNode, text.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
diff --git a/packages/core/src/Chat/useChatComposerTokens.ts b/packages/core/src/Chat/useChatComposerTokens.ts
index 70855177ea..01c1457a52 100644
--- a/packages/core/src/Chat/useChatComposerTokens.ts
+++ b/packages/core/src/Chat/useChatComposerTokens.ts
@@ -21,7 +21,11 @@
*/
import {useCallback, useState} from 'react';
-import {ensureCaretInside, insertTextAtCursor} from './chatComposerSelection';
+import {
+ ensureCaretInside,
+ insertTextAtCursor,
+ placeCaretAfterRemovedToken,
+} from './chatComposerSelection';
import type {
ChatComposerToken,
ChatComposerTokenCustom,
@@ -132,7 +136,7 @@ export function useChatComposerTokens({
span.after(space);
const newRange = document.createRange();
- newRange.setStartAfter(space);
+ newRange.setStart(space, space.length);
newRange.collapse(true);
selection.removeAllRanges();
selection.addRange(newRange);
@@ -181,10 +185,15 @@ export function useChatComposerTokens({
) {
e.preventDefault();
const tokenSpan = startContainer.previousSibling;
+ const before = tokenSpan.previousSibling;
+ const after = startContainer.nextSibling;
const parent = startContainer.parentNode;
if (parent) {
parent.removeChild(startContainer);
parent.removeChild(tokenSpan);
+ if (parent instanceof HTMLElement) {
+ placeCaretAfterRemovedToken(parent, before, after);
+ }
}
onEmitChange();
return true;
@@ -221,7 +230,8 @@ export function useChatComposerTokens({
const space = tokenEl.nextSibling;
const newRange = document.createRange();
if (space && space.nodeType === Node.TEXT_NODE) {
- newRange.setStartAfter(space);
+ const textNode = space as Text;
+ newRange.setStart(textNode, textNode.nodeValue?.length ?? 0);
} else {
newRange.setStartAfter(tokenEl);
}
@@ -268,7 +278,7 @@ export function useChatComposerTokens({
const selection = window.getSelection();
if (selection) {
const range = document.createRange();
- range.setStartAfter(textNode);
+ range.setStart(textNode, textNode.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);