An open source design system that's fully customizable and agent ready
TypeScript
fix(core): preserve multi-line caret navigation in ChatComposerInput (#4284)
이동욱7adcac5e92e0
diff --git a/.changeset/chatcomposerinput-arrowup-down-only-recall-messa-l6pj.md b/.changeset/chatcomposerinput-arrowup-down-only-recall-messa-l6pj.mdnew file mode 100644index 0000000000..f42a92ebca--- /dev/null+++ b/.changeset/chatcomposerinput-arrowup-down-only-recall-messa-l6pj.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] ChatComposerInput: ArrowUp/Down only recall message history at the text boundaries, so the caret can move between lines of a multi-line draft+@Lee-Dongwookdiff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsxindex 020ca4f5f0..da6b804905 100644--- a/packages/core/src/Chat/ChatComposerInput.test.tsx+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx@@ -349,6 +349,194 @@ describe('ChatComposerInput', () => {});});+ // ArrowUp/ArrowDown recall previously submitted messages, but only at+ // the text boundaries — otherwise the caret can't move between lines+ // of a multi-line draft. ArrowUp recalls at the very start, ArrowDown+ // at the very end; mid-text the browser moves the caret (default not+ // prevented).+ describe('message history navigation', () => {+ function submit(textbox: HTMLElement, value: string) {+ textbox.textContent = value;+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter'});+ }++ function placeCaret(node: Node, offset: number) {+ const sel = window.getSelection()!;+ const range = document.createRange();+ range.setStart(node, offset);+ range.collapse(true);+ sel.removeAllRanges();+ sel.addRange(range);+ }++ it('recalls the previous message on ArrowUp at the start of the draft', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submit(textbox, 'first');+ submit(textbox, 'second');++ // Fresh empty draft — caret is trivially at the start.+ textbox.focus();+ placeCaret(textbox, 0);+ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ expect(prevented).toBe(true);+ expect(textbox.textContent).toBe('second');+ });++ it('recalls from a first-text-node caret without cloning draft contents', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submit(textbox, 'previous message');++ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);+ textbox.focus();+ // Chromium places this caret in the first text node, not on the root.+ placeCaret(textbox.firstChild!, 0);+ const cloneContents = vi.spyOn(Range.prototype, 'cloneContents');++ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ expect(cloneContents).toHaveBeenCalledTimes(0);+ expect(prevented).toBe(true);+ expect(textbox.textContent).toBe('previous message');+ cloneContents.mockRestore();+ });++ it('steps forward from a final-text-node caret without cloning draft contents', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submit(textbox, 'previous message');++ const draft = 'pending draft';+ textbox.textContent = draft;+ fireEvent.input(textbox);+ textbox.focus();+ placeCaret(textbox.firstChild!, 0);+ fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ // The prior ArrowUp selected a recalled message. Put the pending+ // draft back in place, then navigate forward from the final text node.+ textbox.textContent = draft;+ fireEvent.input(textbox);+ placeCaret(textbox.firstChild!, draft.length);+ const cloneContents = vi.spyOn(Range.prototype, 'cloneContents');++ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowDown'});++ expect(cloneContents).toHaveBeenCalledTimes(0);+ expect(prevented).toBe(true);+ expect(textbox.textContent).toBe(draft);+ cloneContents.mockRestore();+ });++ it('does not recall on ArrowUp when the caret is mid-text', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submit(textbox, 'first');++ textbox.textContent = 'aaa';+ fireEvent.input(textbox);+ textbox.focus();+ // Caret between the a's — not at the very start.+ placeCaret(textbox.firstChild!, 1);+ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ // Default is not prevented: the browser moves the caret up a line.+ expect(prevented).toBe(false);+ expect(textbox.textContent).toBe('aaa');+ });++ it('does not recall on ArrowUp from the first line of a multi-line draft when not at the start', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submit(textbox, 'first');++ // Multi-line draft: "aaa" <br> "bbb".+ textbox.innerHTML = 'aaa<br>bbb';+ fireEvent.input(textbox);+ textbox.focus();+ // Caret mid first line.+ placeCaret(textbox.firstChild!, 2);+ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ expect(prevented).toBe(false);+ expect(textbox.querySelector('br')).not.toBeNull();+ });++ it('steps back and forth through history at the boundaries', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submit(textbox, 'first');+ submit(textbox, 'second');++ textbox.focus();+ placeCaret(textbox, 0);++ // Up to the most recent, then further back.+ fireEvent.keyDown(textbox, {key: 'ArrowUp'});+ expect(textbox.textContent).toBe('second');+ // Recalled text is fully selected — Up again steps further back.+ fireEvent.keyDown(textbox, {key: 'ArrowUp'});+ expect(textbox.textContent).toBe('first');+ // Down steps forward again.+ fireEvent.keyDown(textbox, {key: 'ArrowDown'});+ expect(textbox.textContent).toBe('second');+ });++ it('restores the pending draft on ArrowDown past the newest message', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submit(textbox, 'first');++ textbox.textContent = 'draft';+ fireEvent.input(textbox);+ textbox.focus();+ // Caret at the very start — ArrowUp recalls and stashes the draft.+ placeCaret(textbox, 0);++ fireEvent.keyDown(textbox, {key: 'ArrowUp'});+ expect(textbox.textContent).toBe('first');+ // The recalled message is fully selected, so ArrowDown steps+ // forward past the newest entry and restores the stashed draft.+ fireEvent.keyDown(textbox, {key: 'ArrowDown'});+ expect(textbox.textContent).toBe('draft');+ });++ it('does nothing when there is no history', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'hello';+ fireEvent.input(textbox);+ textbox.focus();+ placeCaret(textbox, 0);++ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});+ expect(prevented).toBe(false);+ expect(textbox.textContent).toBe('hello');+ });++ it('does not recall when hasHistory is false', () => {+ render(<ChatComposerInput hasHistory={false} onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ // Even after "submitting", history is disabled.+ textbox.textContent = 'first';+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter'});++ textbox.textContent = 'hello';+ fireEvent.input(textbox);+ textbox.focus();+ placeCaret(textbox.firstChild!, 0);++ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});+ expect(prevented).toBe(false);+ 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/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsxindex 5a6a56b94b..69b5a4f39e 100644--- a/packages/core/src/Chat/ChatComposerInput.tsx+++ b/packages/core/src/Chat/ChatComposerInput.tsx@@ -46,7 +46,12 @@ import {import {mergeProps, isImeKeyEvent} from '../utils';import {useTriggerMenu} from './useTriggerMenu';import {useChatComposerTokens, isCustomToken} from './useChatComposerTokens';-import {ensureCaretInside, insertTextAtCursor} from './chatComposerSelection';+import {+ ensureCaretInside,+ insertTextAtCursor,+ isSelectionAtStart,+ isSelectionAtEnd,+} from './chatComposerSelection';import {ChatPastedTextToken} from './ChatPastedTextToken';import {useChatPasteAsToken,@@ -590,12 +595,30 @@ export function ChatComposerInput(props: ChatComposerInputProps) {return;}- // History navigation (only when trigger menu is not active)+ // History navigation (only when trigger menu is not active).+ // Recall only at the text boundaries so the caret can still move+ // between lines in a multi-line draft: ArrowUp recalls the+ // previous message when the caret is at the very start, ArrowDown+ // steps forward when it's at the very end. A recalled message is+ // shown fully selected (see `selectAll` below); that spans both+ // boundaries at once, so repeated presses keep stepping through+ // history. Mid-text, we bail before `preventDefault` and let the+ // browser move the caret up/down a line.if (hasHistory && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {if (!editableRef.current) {return;}- const text = serialize(editableRef.current);+ const editable = editableRef.current;+ const isCollapsed = window.getSelection()?.isCollapsed ?? true;+ const atStart = isSelectionAtStart(editable);+ const atEnd = isSelectionAtEnd(editable);+ const canRecallPrev = atStart && (isCollapsed || atEnd);+ const canRecallNext = atEnd && (isCollapsed || atStart);+ if (e.key === 'ArrowUp' ? !canRecallPrev : !canRecallNext) {+ return;+ }++ const text = serialize(editable);const history = historyRef.current;if (history.length === 0) {return;diff --git a/packages/core/src/Chat/chatComposerSelection.ts b/packages/core/src/Chat/chatComposerSelection.tsindex 31b52e78b5..8a7bd25ab2 100644--- a/packages/core/src/Chat/chatComposerSelection.ts+++ b/packages/core/src/Chat/chatComposerSelection.ts@@ -57,6 +57,120 @@ export function ensureCaretInside(editable: HTMLElement): Selection | null {return selection;}+/**+ * Whether the current selection's start boundary sits at the very+ * beginning of `editable`'s content.+ *+ * Used by the composer to decide when ArrowUp should recall message+ * history versus move the caret up a line: history is only recalled+ * when the caret is at the very start of the draft. This handles both+ * the editable root and offset 0 of its leading text node without+ * cloning the draft's contents.+ *+ * Returns `false` when there is no selection, the range is not inside+ * `editable`, or the boundary APIs are unavailable — callers treat+ * that as "not at the boundary" and let the browser move the caret.+ */+export function isSelectionAtStart(editable: HTMLElement): boolean {+ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0) {+ return false;+ }+ const range = selection.getRangeAt(0);+ return isBoundaryAtEdge(+ editable,+ range.startContainer,+ range.startOffset,+ 'start',+ );+}++/**+ * Whether the current selection's end boundary sits at the very end of+ * `editable`'s content.+ *+ * The ArrowDown counterpart to {@link isSelectionAtStart}: history is+ * only stepped forward when the caret is at the very end of the draft.+ *+ * Returns `false` under the same conditions as {@link isSelectionAtStart}.+ */+export function isSelectionAtEnd(editable: HTMLElement): boolean {+ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0) {+ return false;+ }+ const range = selection.getRangeAt(0);+ return isBoundaryAtEdge(+ editable,+ range.endContainer,+ range.endOffset,+ 'end',+ );+}++/**+ * Check whether a Range boundary is at an edge of `editable` without+ * materializing the content before or after it. Chromium represents a caret+ * at the start of non-empty contenteditables as the first text node at offset+ * zero (and likewise uses the last text node's length at the end). Those are+ * distinct DOM boundary points from the editable's child offsets, so+ * `compareBoundaryPoints` cannot be used here.+ */+function isBoundaryAtEdge(+ editable: HTMLElement,+ container: Node,+ offset: number,+ edge: 'start' | 'end',+): boolean {+ if (!editable.contains(container) || !isAtNodeEdge(container, offset, edge)) {+ return false;+ }++ for (let node: Node | null = container; node && node !== editable; ) {+ if (hasContentSibling(node, edge)) {+ return false;+ }+ node = node.parentNode;+ }++ return true;+}++function isAtNodeEdge(+ node: Node,+ offset: number,+ edge: 'start' | 'end',+): boolean {+ if (+ node.nodeType === Node.TEXT_NODE ||+ node.nodeType === Node.CDATA_SECTION_NODE+ ) {+ return edge === 'start'+ ? offset === 0+ : offset === (node.nodeValue?.length ?? 0);+ }++ return edge === 'start' ? offset === 0 : offset === node.childNodes.length;+}++function hasContentSibling(node: Node, edge: 'start' | 'end'): boolean {+ for (+ let sibling = edge === 'start' ? node.previousSibling : node.nextSibling;+ sibling;+ sibling = edge === 'start' ? sibling.previousSibling : sibling.nextSibling+ ) {+ // Elements (including <br> and tokens) represent a content boundary even+ // when they have no text. Empty text nodes and comments do not.+ if (+ sibling.nodeType === Node.ELEMENT_NODE ||+ (sibling.nodeType === Node.TEXT_NODE && sibling.nodeValue !== '')+ ) {+ return true;+ }+ }+ return false;+}+/*** Insert plain text at the current selection, scoped to `editable`.*