Skip to content

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

TypeScript

fix(ChatComposerInput): announce the trigger menu's loading text through the shared channel (#7900)

Ojas Mutreja51ad2f40dc72
diff --git a/.changeset/trigger-menu-loading-announcement.md b/.changeset/trigger-menu-loading-announcement.md
new file mode 100644
index 0000000000..2a9eab0e48
--- /dev/null
+++ b/.changeset/trigger-menu-loading-announcement.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ChatComposerInput: the trigger menu's loading row no longer mounts as a `role="status"` region already holding its text, which screen readers could skip. The loading text is announced once per pending search through the shared polite channel instead, and a search that returns its results before the loading row is painted, such as `createStaticSource` or a cached result, announces nothing; the visible row and its `loadingText` are unchanged.
+
+Fixes #7859.
+
+@HelloOjasMutreja
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 8061cd6f1a..72c90cb2a4 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1231,6 +1231,10 @@
"defaultMessage": "{count} tool calls",
"description": "Summary label shown in the group header when multiple tool calls are expanded. {count} is the number of calls."
},
+ "@astryx.chatTriggerMenu.searching": {
+ "defaultMessage": "Searching…",
+ "description": "Shown, and announced politely to screen readers, while a chat composer's @-mention or slash-command menu waits for async search results. Present participle; trailing `…` is one character."
+ },
"@astryx.chatTriggerMenu.suggestions": {
"defaultMessage": "Suggestions",
"description": "Screen-reader-only fallback label for the popover listbox opened by a trigger character (`@`, `/`) in the chat composer when the trigger provides no specific label."
diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsx
index ae0455074e..d7143511e2 100644
--- a/packages/core/src/Chat/ChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx
@@ -1,6 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect, vi, afterEach} from 'vitest';
+import {StrictMode} 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';
import {ChatComposer} from './ChatComposer';
@@ -13,6 +14,9 @@ import type {
import {createStaticSource} from '../Typeahead/createStaticSource';
import type {SearchableItem, SearchSource} from '../Typeahead/types';
+const announce = vi.hoisted(() => vi.fn());
+vi.mock('../hooks/useAnnounce', () => ({useAnnounce: () => announce}));
+
// =============================================================================
// Helpers
// =============================================================================
@@ -1824,3 +1828,165 @@ describe('ChatComposerInput', () => {
});
});
});
+
+describe('ChatComposerInput trigger loading announcement (spec:AST-086)', () => {
+ function typeAtEnd(editable: HTMLElement, text: string) {
+ editable.textContent = text;
+ const node = editable.firstChild!;
+ const range = document.createRange();
+ range.setStart(node, text.length);
+ range.collapse(true);
+ const sel = window.getSelection()!;
+ sel.removeAllRanges();
+ sel.addRange(range);
+ fireEvent.input(editable);
+ }
+
+ /**
+ * Lets a settled search apply, as the browser would before the next frame,
+ * then lets the loading announcement's two frames run.
+ */
+ async function nextFrame() {
+ await act(async () => {});
+ await act(async () => {
+ for (let frame = 0; frame < 2; frame++) {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ }
+ });
+ }
+
+ /** An async source whose searches resolve only when the test says so. */
+ function createPendingSource() {
+ const resolvers: ((items: SearchableItem[]) => void)[] = [];
+ const source: SearchSource = {
+ bootstrap: async () => [],
+ search: async () =>
+ new Promise<SearchableItem[]>(resolve => {
+ resolvers.push(resolve);
+ }),
+ };
+ return {source, resolvers};
+ }
+
+ beforeEach(() => {
+ announce.mockClear();
+ });
+
+ it('shows the loading row without a live role (FR2)', () => {
+ const {source} = createPendingSource();
+ render(
+ <ChatComposerInput
+ triggers={[createMentionTrigger({searchSource: source})]}
+ debounceMs={0}
+ />,
+ );
+ const editable = screen.getByRole('combobox');
+ editable.focus();
+ typeAtEnd(editable, '@c');
+
+ const row = screen.getByText('Searching…');
+ expect(row).not.toHaveAttribute('role');
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+
+ it('announces the loading text once per search, not on every keystroke (FR2, FR6)', async () => {
+ const {source, resolvers} = createPendingSource();
+ render(
+ <StrictMode>
+ <ChatComposerInput
+ triggers={[createMentionTrigger({searchSource: source})]}
+ debounceMs={0}
+ />
+ </StrictMode>,
+ );
+ const editable = screen.getByRole('combobox');
+ editable.focus();
+
+ typeAtEnd(editable, '@c');
+ await nextFrame();
+ typeAtEnd(editable, '@ci');
+ await nextFrame();
+ expect(announce.mock.calls).toEqual([['Searching…', 'polite']]);
+
+ await act(async () => {
+ resolvers.forEach(resolve =>
+ resolve([{id: 'cindy', label: 'Cindy Zhang'}]),
+ );
+ });
+ expect(screen.queryByText('Searching…')).toBeNull();
+
+ typeAtEnd(editable, '@cin');
+ await nextFrame();
+ expect(announce.mock.calls).toEqual([
+ ['Searching…', 'polite'],
+ ['Searching…', 'polite'],
+ ]);
+ });
+
+ it('announces nothing for a synchronous source, whose results are already listed (FR7)', async () => {
+ render(
+ <ChatComposerInput triggers={[createMentionTrigger()]} debounceMs={0} />,
+ );
+ const editable = screen.getByRole('combobox');
+ editable.focus();
+
+ typeAtEnd(editable, '@c');
+ await act(async () => {});
+ typeAtEnd(editable, '@ci');
+ await act(async () => {});
+
+ // jsdom gives the popover no semantics, so query the menu by its id.
+ const menu = document.getElementById(
+ editable.getAttribute('aria-controls')!,
+ );
+ expect(menu?.querySelector('[role="option"]')).toHaveTextContent(
+ 'Cindy Zhang',
+ );
+ expect(screen.queryByText('Searching…')).toBeNull();
+ expect(announce).not.toHaveBeenCalled();
+ });
+
+ it('announces nothing for a search that settles before the row shows (FR7)', async () => {
+ const settled: SearchSource = {
+ bootstrap: async () => [],
+ search: async () => [{id: 'cindy', label: 'Cindy Zhang'}],
+ };
+ render(
+ <ChatComposerInput
+ triggers={[createMentionTrigger({searchSource: settled})]}
+ debounceMs={0}
+ />,
+ );
+ const editable = screen.getByRole('combobox');
+ editable.focus();
+
+ typeAtEnd(editable, '@c');
+ await nextFrame();
+ typeAtEnd(editable, '@ci');
+ await nextFrame();
+
+ expect(screen.queryByText('Searching…')).toBeNull();
+ expect(announce).not.toHaveBeenCalled();
+ });
+
+ it("announces a trigger's own loadingText", async () => {
+ const {source} = createPendingSource();
+ render(
+ <ChatComposerInput
+ triggers={[
+ createMentionTrigger({
+ searchSource: source,
+ loadingText: 'Looking up people…',
+ }),
+ ]}
+ debounceMs={0}
+ />,
+ );
+ const editable = screen.getByRole('combobox');
+ editable.focus();
+ typeAtEnd(editable, '@c');
+ await nextFrame();
+
+ expect(announce.mock.calls).toEqual([['Looking up people…', 'polite']]);
+ });
+});
diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsx
index 923bd75300..68ae119d32 100644
--- a/packages/core/src/Chat/useTriggerMenu.tsx
+++ b/packages/core/src/Chat/useTriggerMenu.tsx
@@ -32,6 +32,7 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import {usePopover} from '../Popover/usePopover';
+import {useAnnounce} from '../hooks/useAnnounce';
import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import {
colorVars,
@@ -353,6 +354,38 @@ export function useTriggerMenu(
isHidden: false,
});
+ // The loading row carries no live role: it mounts already holding its text
+ // and is removed when results arrive, so it would be skipped. The shared
+ // channel announces each loading episode once instead (spec:AST-086 FR2,
+ // FR6), once the row has been painted: the second animation frame runs
+ // after the first paint, and a search that settles before then never shows
+ // the row, so it announces nothing (FR7). The flag clears when the loading
+ // row goes away, so the next search is a new occasion.
+ const announce = useAnnounce();
+ const hasAnnouncedLoadingRef = useRef(false);
+ // Mirrors renderMenu: no row exists without an active trigger or while hidden.
+ const isLoadingRowShown =
+ state.isLoading && !state.isHidden && state.activeTrigger !== null;
+ // One catalog string serves the row and the announcement (FR7).
+ const loadingText =
+ state.activeTrigger?.loadingText ?? t('@astryx.chatTriggerMenu.searching');
+ useEffect(() => {
+ if (!isLoadingRowShown) {
+ hasAnnouncedLoadingRef.current = false;
+ return;
+ }
+ if (hasAnnouncedLoadingRef.current) {
+ return;
+ }
+ let frame = requestAnimationFrame(() => {
+ frame = requestAnimationFrame(() => {
+ hasAnnouncedLoadingRef.current = true;
+ announce(loadingText, 'polite');
+ });
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [announce, isLoadingRowShown, loadingText]);
+
const triggerStartRef = useRef<number>(-1);
const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const searchRequestIdRef = useRef<number>(0);
@@ -382,6 +415,12 @@ export function useTriggerMenu(
if (isMenuSuppressedRef.current) {
return;
}
+ // A search still waiting out its debounce must not start for a menu
+ // that is gone.
+ if (searchTimeoutRef.current) {
+ clearTimeout(searchTimeoutRef.current);
+ searchTimeoutRef.current = null;
+ }
searchRequestIdRef.current++;
removeAnchorSpan();
setState(prev => ({
@@ -555,8 +594,12 @@ export function useTriggerMenu(
if (trigger.searchSource) {
// Use SearchSource — cancel previous, then search
trigger.searchSource.cancel?.();
- setState(prev => ({...prev, isLoading: true}));
const result = trigger.searchSource.search(query);
+ // A synchronous source already has its results, so it never shows
+ // or announces the loading row (spec:AST-086 FR7).
+ if (!Array.isArray(result)) {
+ setState(prev => ({...prev, isLoading: true}));
+ }
Promise.resolve(result).then(
items => {
if (!isCurrent()) {
@@ -873,14 +916,11 @@ export function useTriggerMenu(
}
const emptyText = activeTrigger.emptySearchText ?? 'No results';
- const loadingText = activeTrigger.loadingText ?? 'Searching\u2026';
let listContent: ReactNode;
if (state.isLoading) {
listContent = (
- <div role="status" {...stylex.props(styles.loadingState)}>
- {loadingText}
- </div>
+ <div {...stylex.props(styles.loadingState)}>{loadingText}</div>
);
} else if (state.items.length === 0 && state.isActive) {
listContent = <div {...stylex.props(styles.emptyState)}>{emptyText}</div>;
@@ -951,7 +991,16 @@ export function useTriggerMenu(
xstyle: styles.popoverSurface,
},
);
- }, [popover, listboxId, state, selectItem, getItemId, highlightOnHover, t]);
+ }, [
+ popover,
+ listboxId,
+ state,
+ selectItem,
+ getItemId,
+ highlightOnHover,
+ t,
+ loadingText,
+ ]);
return {
state,