An open source design system that's fully customizable and agent ready
TypeScript
fix(core): announce MultiSelector search result counts to screen readers (#3987)
Baraa Hamodi08a09575b531
diff --git a/.changeset/multiselector-results-announce.md b/.changeset/multiselector-results-announce.mdnew file mode 100644index 0000000000..777d4afa0b--- /dev/null+++ b/.changeset/multiselector-results-announce.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] MultiSelector: searching within the options popover now announces the number of matching results ("3 results" / "No results found") to screen readers, mirroring Selector and Typeahead. Previously filtering happened silently.+@bhamodidiff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjsindex 03be0ebf55..e01ba42a78 100644--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs@@ -99,7 +99,8 @@ export const docs = {{name: 'hasSearch',type: 'boolean',- description: 'Whether to show a search input for filtering options.',+ description:+ 'Whether to show a search input for filtering options. As the user types, the match count (or "No results found") is announced to screen readers via a polite live region.',},{name: 'searchPlaceholder',@@ -239,7 +240,8 @@ export const docsZh = {hasSearch: '是否显示用于过滤选项的搜索输入。',searchPlaceholder: '搜索输入的占位文本。',isDisabled: '禁用选择器。',- htmlName: '用于表单提交的 HTML name 属性。为每个已选值渲染一个隐藏输入,类似原生多选。',+ htmlName:+ '用于表单提交的 HTML name 属性。为每个已选值渲染一个隐藏输入,类似原生多选。',disabledMessage:'解释选择器被禁用的原因。与 isDisabled 一起使用时,悬停/键盘聚焦时显示工具提示,并通过 aria-disabled 保持触发器可聚焦(仍无法激活)。请使用此属性,而不是用 Tooltip 包裹被禁用的选择器。',isLabelHidden: '视觉上隐藏标签同时保持其可访问性。',diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsxindex 09b6c4e132..83ae53f8d0 100644--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx@@ -554,6 +554,82 @@ describe('MultiSelector', () => {expect(screen.getByText('No results found')).toBeInTheDocument();});+ describe('result announcements', () => {+ it('announces the match count politely while searching', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={EMPTY_VALUE}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ // "an" matches Banana and Orange.+ await user.type(screen.getByRole('combobox', h), 'an');+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('2 results');+ });+ });++ it('announces the singular form when one option matches', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={EMPTY_VALUE}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ // "app" matches only Apple. Anchored so it cannot pass on "1 results".+ await user.type(screen.getByRole('combobox', h), 'app');+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent(/^1 result$/);+ });+ });++ it('announces "No results found" when nothing matches', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={EMPTY_VALUE}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ await user.type(screen.getByRole('combobox', h), 'xyz');+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('No results found');+ });+ });++ it('does not announce results until the user searches', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={EMPTY_VALUE}+ onChange={() => {}}+ hasSearch+ />,+ );+ // Popover closed: nothing announced.+ expect(politeRegion()?.textContent ?? '').toBe('');+ // Open with an empty query: still nothing announced.+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ expect(politeRegion()?.textContent ?? '').toBe('');+ });+ });+it('renders with description', () => {render(<MultiSelector@@ -1072,7 +1148,9 @@ describe('MultiSelector', () => {/></form>,);- expect([...new FormData(container.querySelector('form')!).keys()]).toEqual([]);+ expect([+ ...new FormData(container.querySelector('form')!).keys(),+ ]).toEqual([]);});});});diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex 014dcf8f1e..1cd072c155 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -562,6 +562,23 @@ export interface MultiSelectorProps<'data-testid'?: string;}+// Case-insensitive substring filter over the selectable options. Shared by the+// `filteredItems` memo (rendering) and the search-change handler, which needs+// the count for the *next* query synchronously to announce it exactly once per+// keystroke rather than reacting to state in an effect.+function filterOptionsByQuery(+ items: MultiSelectorOptionData[],+ query: string,+): MultiSelectorOptionData[] {+ if (!query) {+ return items;+ }+ const q = query.toLowerCase();+ return items.filter(item =>+ (item.label ?? item.value).toLowerCase().includes(q),+ );+}+/*** A multi-select dropdown component with checkboxes for choosing* multiple items from a list of options.@@ -692,15 +709,10 @@ export function MultiSelector<T extends MultiSelectorOptionType>({);// Filter items by search query- const filteredItems = useMemo(() => {- if (!searchQuery) {- return selectableItems;- }- const query = searchQuery.toLowerCase();- return selectableItems.filter(item =>- (item.label ?? item.value).toLowerCase().includes(query),- );- }, [selectableItems, searchQuery]);+ const filteredItems = useMemo(+ () => filterOptionsByQuery(selectableItems, searchQuery),+ [selectableItems, searchQuery],+ );// Single source of truth for item order. Both the hook (keyboard navigation)// and renderOptions (DOM rendering) consume this list — no independent sorting.@@ -772,8 +784,11 @@ export function MultiSelector<T extends MultiSelectorOptionType>({const handleLayerHide = useCallback(() => {setSearchQuery('');setSelectedAtOpen(null);+ // Clear any lingering result count when the popover closes so stale status+ // text does not linger in the a11y tree.+ announce('');triggerRef.current?.focus();- }, []);+ }, [announce]);const popover = usePopover({hasLightDismiss: true,@@ -793,6 +808,30 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// eslint-disable-next-line @eslint-react/exhaustive-deps -- mount-only: isDefaultOpen is not reactive}, []);+ // Announce the filtered result count from the query-change handler (matching+ // BaseTypeahead) rather than a reactive effect: computing the count for the+ // next query here fires the announcement exactly once per keystroke and does+ // not re-speak on unrelated re-renders. Reuses the announce instance shared+ // with the selection-count announcements above.+ const handleSearchChange = useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ const nextQuery = event.target.value;+ setSearchQuery(nextQuery);+ if (nextQuery.length === 0) {+ // Emptying the query clears the region rather than announcing a count.+ announce('');+ return;+ }+ const count = filterOptionsByQuery(selectableItems, nextQuery).length;+ announce(+ count === 0+ ? 'No results found'+ : `${count} result${count === 1 ? '' : 's'}`,+ );+ },+ [announce, selectableItems],+ );+// Handle toggle// Clear all selected values. Shared by the clear button and the keyboard// Delete/Backspace path so clearing is reachable without a mouse.@@ -1041,7 +1080,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({aria-label={t('@astryx.multiSelector.searchOptions')}type="text"value={searchQuery}- onChange={e => setSearchQuery(e.target.value)}+ onChange={handleSearchChange}onKeyDown={e => {// Arrow keys navigate options; Enter toggles; Escape/Tab close.// Space and Home/End are left to the input (type a space / move@@ -1067,6 +1106,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({listboxId,searchQuery,searchPlaceholder,+ handleSearchChange,onKeyDown,popover.isOpen,highlightedIndex,