Skip to content

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

TypeScript

fix(ChatComposerInput): retain focus while disabled (#8431)

zakelstorm0cbddeac0270
diff --git a/.changeset/ast-085-chat-composer-input.md b/.changeset/ast-085-chat-composer-input.md
new file mode 100644
index 0000000000..a0b9c9f5ac
--- /dev/null
+++ b/.changeset/ast-085-chat-composer-input.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ChatComposerInput keeps focus and its Tab stop when disabled instead of moving focus to the page. Disabled editors block editing, paste/drop, trigger selection, imperative mutations, and submission while retaining their draft and accessible description.
+@korkt-kim
diff --git a/packages/core/src/Chat/ChatComposer.test.tsx b/packages/core/src/Chat/ChatComposer.test.tsx
index 75e36e51f3..6d9f0fc052 100644
--- a/packages/core/src/Chat/ChatComposer.test.tsx
+++ b/packages/core/src/Chat/ChatComposer.test.tsx
@@ -5,7 +5,9 @@ import {act, render, fireEvent, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {StrictMode, useEffect, useRef} from 'react';
import {ChatComposer} from './ChatComposer';
+import {ChatComposerInput} from './ChatComposerInput';
import {useChatComposerContext} from './ChatContext';
+import {createStaticSource} from '../Typeahead/createStaticSource';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import type * as AnnounceModule from '../hooks/useAnnounce';
@@ -74,6 +76,36 @@ describe('ChatComposer focus indication', () => {
expect(body.className).not.toBe(restingClass);
});
+ it('adds the composer ring when Tab enters a disabled trigger editor', async () => {
+ const user = userEvent.setup();
+ render(
+ <ChatComposer
+ isDisabled
+ onSubmit={() => {}}
+ input={
+ <ChatComposerInput
+ triggers={[
+ {
+ character: '@',
+ searchSource: createStaticSource([]),
+ onSelect: () => '',
+ },
+ ]}
+ />
+ }
+ />,
+ );
+ const editor = screen.getByRole('combobox');
+ const body = editor.parentElement!.parentElement!.parentElement!;
+ const restingClass = body.className;
+ expect(editor).toHaveAttribute('aria-disabled', 'true');
+
+ await user.tab();
+
+ expect(editor).toHaveFocus();
+ expect(body.className).not.toBe(restingClass);
+ });
+
it('does not add the composer ring when pointer focus enters the editor', () => {
const {body, editor} = renderComposer();
const restingClass = body.className;
diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsx
index f89ef73ee9..bdff0dd2f4 100644
--- a/packages/core/src/Chat/ChatComposer.tsx
+++ b/packages/core/src/Chat/ChatComposer.tsx
@@ -340,7 +340,7 @@ function isComposerEditor(target: EventTarget | null): target is HTMLElement {
return (
target instanceof HTMLElement &&
target.matches(
- 'textarea, [contenteditable="true"], [role="textbox"], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="password"]',
+ 'textarea, [contenteditable="true"], [role="textbox"], [role="combobox"][contenteditable], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="password"]',
)
);
}
diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsx
index d7143511e2..2694d2d8f1 100644
--- a/packages/core/src/Chat/ChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx
@@ -1,6 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {StrictMode} from 'react';
+import {createRef, StrictMode, useLayoutEffect} from 'react';
import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';
import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -82,12 +82,6 @@ describe('ChatComposerInput', () => {
).toBeInTheDocument();
});
- it('renders disabled state', () => {
- render(<ChatComposerInput isDisabled />);
- const textbox = screen.getByRole('textbox');
- expect(textbox).toHaveAttribute('contenteditable', 'false');
- });
-
it('marks the textbox as multiline', () => {
render(<ChatComposerInput />);
expect(screen.getByRole('textbox')).toHaveAttribute(
@@ -105,6 +99,170 @@ describe('ChatComposerInput', () => {
});
});
+ describe('disabled editing', () => {
+ it('keeps focus, draft, description, and Tab entry when the composer disables it', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const view = (isDisabled: boolean, value = 'Draft') => (
+ <>
+ <button type="button">Before</button>
+ <p id="reason">Unavailable while sending</p>
+ <ChatComposer
+ isDisabled={isDisabled}
+ value={value}
+ onChange={onChange}
+ onSubmit={() => {}}
+ input={<ChatComposerInput aria-describedby="reason" />}
+ />
+ </>
+ );
+ const {rerender} = render(view(false));
+ await user.tab();
+ await user.tab();
+ const editor = screen.getByRole('textbox');
+ expect(editor).toHaveFocus();
+
+ rerender(view(true));
+ expect(screen.getByRole('textbox')).toBe(editor);
+ expect(editor).toHaveFocus();
+ expect(editor).toHaveTextContent('Draft');
+ expect(editor).toHaveAttribute('contenteditable', 'false');
+ expect(editor).toHaveAttribute('aria-disabled', 'true');
+ expect(editor).toHaveAccessibleDescription('Unavailable while sending');
+ screen.getByRole('button', {name: 'Before'}).focus();
+ await user.tab();
+ expect(editor).toHaveFocus();
+
+ rerender(view(true, 'External update'));
+ expect(editor).toHaveTextContent('External update');
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('blocks input, submission, paste, drop, and consumer callbacks', () => {
+ const onInteraction = vi.fn();
+ render(
+ <ChatComposerInput
+ isDisabled
+ value="Draft"
+ onChange={onInteraction}
+ onSubmit={onInteraction}
+ onKeyDown={onInteraction}
+ onKeyDownCapture={onInteraction}
+ onInput={onInteraction}
+ onPaste={onInteraction}
+ onFiles={onInteraction}
+ onDrop={onInteraction}
+ />,
+ );
+ const editor = screen.getByRole('textbox');
+ fireEvent.keyDown(editor, {key: 'Enter'});
+ fireEvent.input(editor);
+ fireEvent.paste(editor, {
+ clipboardData: {files: [], getData: () => 'blocked'},
+ });
+ const file = new File(['content'], 'blocked.txt', {type: 'text/plain'});
+ fireEvent.paste(editor, {
+ clipboardData: {files: [file], getData: () => ''},
+ });
+ expect(
+ fireEvent.drop(editor, {
+ dataTransfer: {files: [file], types: ['Files']},
+ }),
+ ).toBe(false);
+ expect(editor).toHaveTextContent('Draft');
+ expect(onInteraction).not.toHaveBeenCalled();
+ });
+
+ it('blocks retained-handle mutations and token deletion until re-enabled', () => {
+ const handleRef = createRef<ChatComposerInputHandle>();
+ const onChange = vi.fn();
+ const view = (isDisabled: boolean) => (
+ <ChatComposerInput
+ isDisabled={isDisabled}
+ handleRef={handleRef}
+ onChange={onChange}
+ />
+ );
+ const {rerender} = render(view(false));
+ const editor = screen.getByRole('textbox');
+ const handle = handleRef.current!;
+ let tokenId: string | undefined;
+ act(() => {
+ tokenId = handle.insertToken({value: '@sam', label: 'Sam'});
+ });
+ window.getSelection()!.collapse(editor.lastChild, 1);
+ rerender(view(true));
+ onChange.mockClear();
+ // emitChange is itself silent while disabled, so the draft is checked
+ // directly: neither the value nor the editor's markup (the token) may
+ // change.
+ const valueBefore = handle.getValue();
+ const markupBefore = editor.innerHTML;
+
+ act(() => {
+ handle.insertText('blocked');
+ expect(
+ handle.insertToken({value: '@alex', label: 'Alex'}),
+ ).toBeUndefined();
+ handle.expandToken(tokenId!);
+ });
+ fireEvent.keyDown(editor, {key: 'Backspace'});
+ expect(onChange).not.toHaveBeenCalled();
+ expect(handle.getValue()).toBe(valueBefore);
+ expect(editor.innerHTML).toBe(markupBefore);
+ handle.focus();
+ expect(editor).toHaveFocus();
+
+ rerender(view(false));
+ act(() => handle.insertText('enabled'));
+ expect(handle.getValue()).toContain('enabled');
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('closes suggestions without selecting or reopening after re-enabling', async () => {
+ const user = userEvent.setup();
+ const onSelect = vi.fn(() => '@sam ');
+ const triggers = [createMentionTrigger({onSelect})];
+ const onDisabledCommit = vi.fn();
+ function Example({isDisabled = false}: {isDisabled?: boolean}) {
+ useLayoutEffect(() => {
+ if (isDisabled) {
+ const editor = screen.getByRole('combobox');
+ onDisabledCommit({
+ expanded: editor.getAttribute('aria-expanded'),
+ controls: editor.getAttribute('aria-controls'),
+ activeDescendant: editor.getAttribute('aria-activedescendant'),
+ });
+ }
+ }, [isDisabled]);
+ return (
+ <ChatComposerInput isDisabled={isDisabled} triggers={triggers} />
+ );
+ }
+ const {rerender} = render(<Example />);
+ const editor = screen.getByRole('combobox');
+ await user.type(editor, '@');
+ await screen.findByText('Cindy Zhang');
+ expect(editor).toHaveAttribute('aria-expanded', 'true');
+
+ rerender(<Example isDisabled />);
+ expect(onDisabledCommit).toHaveBeenCalledExactlyOnceWith({
+ expanded: 'false',
+ controls: null,
+ activeDescendant: null,
+ });
+ expect(
+ screen.queryByRole('option', {hidden: true}),
+ ).not.toBeInTheDocument();
+ await user.keyboard('{Enter}');
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(editor).toHaveTextContent('@');
+
+ rerender(<Example />);
+ expect(editor).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+
describe('change and submit', () => {
it('calls onChange on input', () => {
const onChange = vi.fn();
@@ -587,20 +745,6 @@ describe('ChatComposerInput', () => {
expect(allowed).toBe(false);
expect(onFiles).toHaveBeenCalledWith([file]);
});
-
- it('does not emit dropped files while disabled', () => {
- const onFiles = vi.fn();
- render(<ChatComposerInput isDisabled onFiles={onFiles} />);
- const textbox = screen.getByRole('textbox');
- const file = new File(['content'], 'blocked.txt', {type: 'text/plain'});
-
- const allowed = fireEvent.drop(textbox, {
- dataTransfer: {files: [file], types: ['Files']},
- });
-
- expect(allowed).toBe(false);
- expect(onFiles).not.toHaveBeenCalled();
- });
});
// Paste / insert paths used to bail silently when the contenteditable
diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsx
index 754f1abfa1..2ec516375a 100644
--- a/packages/core/src/Chat/ChatComposerInput.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.tsx
@@ -372,6 +372,15 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
style,
...rest
} = props;
+ // Keep focus/blur observation available, but do not forward activation or
+ // editing callbacks from the disabled root (including capture handlers).
+ const rootProps = isDisabled
+ ? Object.fromEntries(
+ Object.entries(rest).filter(
+ ([key]) => !/^on[A-Z]/.test(key) || /^on(Focus|Blur)/.test(key),
+ ),
+ )
+ : rest;
const label = labelFromProps ?? t('@astryx.chat.composerInput.label');
const placeholder =
placeholderFromProps ??
@@ -415,6 +424,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
(token: ChatComposerToken) => string | undefined
>(() => undefined);
const insertTextRef = useRef<(text: string) => void>(() => {});
+ const expandTokenRef = useRef<(id: string) => void>(() => {});
// A single handle object shared between the forwarded ref (via
// `useImperativeHandle`) and `selfRef` (used by internal consumers
@@ -480,7 +490,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
const handle: ChatComposerInputHandle = {
insertToken: (token: ChatComposerToken) => insertTokenRef.current(token),
- expandToken: (id: string) => tokens.expandToken(id),
+ expandToken: (id: string) => expandTokenRef.current(id),
insertText: (text: string) => insertTextRef.current(text),
focus: focusEditable,
getValue: () =>
@@ -549,7 +559,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
const emitChangeVersionRef = useRef(0);
const emitChange = useCallback(() => {
- if (!editableRef.current) {
+ if (isDisabled || !editableRef.current) {
return;
}
const text = serialize(editableRef.current);
@@ -566,7 +576,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
emitChangeVersionRef.current += 1;
onChange?.(nextValue);
cleanupPortalsRef.current?.();
- }, [onChange]);
+ }, [isDisabled, onChange]);
// --- Token management (via hook) ---
const tokens = useChatComposerTokens({
@@ -598,9 +608,11 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
[emitChange, insertTextWithoutEmit],
);
- // Keep stable refs in sync for imperative handle
- insertTokenRef.current = tokens.insertToken;
- insertTextRef.current = insertText;
+ // A caller may retain a handle across renders. Resolve mutation permission
+ // through the latest callbacks rather than the render that created it.
+ insertTokenRef.current = isDisabled ? () => undefined : tokens.insertToken;
+ insertTextRef.current = isDisabled ? () => {} : insertText;
+ expandTokenRef.current = isDisabled ? () => {} : tokens.expandToken;
// --- Trigger menu ---
const triggerMenu = useTriggerMenu({
@@ -612,13 +624,41 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
debounceMs,
});
+ const editorAriaProps =
+ isDisabled && triggerMenu.ariaProps.role === 'combobox'
+ ? {
+ ...triggerMenu.ariaProps,
+ 'aria-expanded': false,
+ 'aria-controls': undefined,
+ 'aria-activedescendant': undefined,
+ }
+ : triggerMenu.ariaProps;
+
+ useEffect(() => {
+ if (isDisabled && triggerMenu.state.isActive) {
+ // Reset also cancels pending searches, so late results cannot reopen
+ // suggestions after disablement or a subsequent re-enable.
+ triggerMenu.reset();
+ }
+ }, [isDisabled, triggerMenu]);
+
const handleInput = useCallback(() => {
+ if (isDisabled) {
+ return;
+ }
emitChange();
triggerMenu.handleInput();
- }, [emitChange, triggerMenu]);
+ }, [isDisabled, emitChange, triggerMenu]);
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLDivElement>) => {
+ if (isDisabled) {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ }
+ // Native selection, copying, and Tab navigation remain available.
+ return;
+ }
// Let trigger menu consume the event first
if (triggerMenu.handleKeyDown(e)) {
return;
@@ -772,11 +812,23 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
}
}
},
- [hasHistory, onSubmit, onChange, emitChange, triggerMenu, onKeyDownProp],
+ [
+ isDisabled,
+ hasHistory,
+ onSubmit,
+ onChange,
+ emitChange,
+ triggerMenu,
+ onKeyDownProp,
+ ],
);
const handlePaste = useCallback(
(e: ClipboardEvent<HTMLDivElement>) => {
+ if (isDisabled) {
+ e.preventDefault();
+ return;
+ }
const editable = editableRef.current;
if (!editable) {
return;
@@ -824,7 +876,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
insertTextAtCursor(editable, text);
emitChange();
},
- [onFiles, onPasteProp, emitChange, tokens, pasteAsToken],
+ [isDisabled, onFiles, onPasteProp, emitChange, tokens, pasteAsToken],
);
const handleDragOver = useCallback((e: DragEvent<HTMLDivElement>) => {
@@ -835,6 +887,10 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
const handleDrop = useCallback(
(e: DragEvent<HTMLDivElement>) => {
+ if (isDisabled) {
+ e.preventDefault();
+ return;
+ }
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) {
return;
@@ -842,9 +898,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
// File drops navigate the page by default. The input owns that drop
// target even when no callback is supplied, so keep the user in place.
e.preventDefault();
- if (!isDisabled) {
- onFiles?.(files);
- }
+ onFiles?.(files);
},
[isDisabled, onFiles],
);
@@ -860,7 +914,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
className,
style,
)}
- {...rest}>
+ {...rootProps}>
{isEmpty && (
<div {...stylex.props(styles.placeholder)} aria-hidden="true">
{placeholder}
@@ -869,6 +923,9 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
<div
ref={editableRef}
aria-label={label}
+ aria-describedby={rest['aria-describedby']}
+ // Explicit in both states: losing editability must not lose focus.
+ tabIndex={0}
contentEditable={!isDisabled}
suppressContentEditableWarning
onInput={handleInput}
@@ -876,13 +933,13 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
onPaste={handlePaste}
onDragOver={handleDragOver}
onDrop={handleDrop}
- {...triggerMenu.ariaProps}
+ {...editorAriaProps}
aria-disabled={isDisabled || undefined}
{...mergeProps(stylex.props(styles.editable), {
style: {maxHeight: `${maxHeight}px`},
})}
/>
- {triggerMenu.renderMenu()}
+ {!isDisabled && triggerMenu.renderMenu()}
{tokens.tokenPortals
.filter(({span}) => span.isConnected)
.map(({id, span, token}) =>
@@ -894,7 +951,7 @@ export function ChatComposerInput(props: ChatComposerInputProps) {
<ChatPastedTextToken
key={id}
text={token.value}
- onExpand={() => tokens.expandToken(id)}
+ onExpand={() => expandTokenRef.current(id)}
/>
) : (
<Badge