Skip to content

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

TypeScript

fix(core): announce Selector search result counts to screen readers (#3725)

Baraa Hamodi6469b19c36a3
diff --git a/.changeset/selector-results-announce.md b/.changeset/selector-results-announce.md
new file mode 100644
index 0000000000..211795a50e
--- /dev/null
+++ b/.changeset/selector-results-announce.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Selector: searching within the options popover now announces the number of matching results ("3 results" / "No results found") to screen readers, mirroring Typeahead. Previously filtering happened silently. (#3725)
+@bhamodi
diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjs
index cbf046e36a..9cb8718c5a 100644
--- a/packages/core/src/Selector/Selector.doc.mjs
+++ b/packages/core/src/Selector/Selector.doc.mjs
@@ -36,7 +36,8 @@ export const docs = {
{
name: 'options',
type: 'SelectorOption[]',
- description: 'Array of items: strings, objects with value/label/icon/disabled, dividers ({type: "divider"}), or sections ({type: "section", title, items}).',
+ description:
+ 'Array of items: strings, objects with value/label/icon/disabled, dividers ({type: "divider"}), or sections ({type: "section", title, items}).',
required: true,
},
{
@@ -59,7 +60,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.',
default: 'false',
},
{
@@ -135,7 +137,8 @@ export const docs = {
{
name: 'xstyle',
type: 'StyleXStyles',
- description: 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value: not an inline style object like style={{}}.',
+ description:
+ 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value: not an inline style object like style={{}}.',
},
],
components: [{name: 'SelectorOption'}],
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index dbb81c8877..db67ed985c 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -9,12 +9,17 @@
* SYNC: When Selector.tsx API changes, update these tests.
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Selector} from './Selector';
import {SelectorOption} from './SelectorOption';
import {InputGroup, InputGroupText} from '../InputGroup';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+function politeRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="polite"]');
+}
// Mock showPopover and hidePopover methods since they're not implemented in jsdom
beforeEach(() => {
@@ -42,6 +47,10 @@ beforeEach(() => {
};
});
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
+
// Helper: jsdom popover content is in the DOM but may not be
// "visible" in the accessibility tree. Use hidden: true to find it.
const h = {hidden: true} as const;
@@ -599,6 +608,82 @@ describe('Selector', () => {
screen.getByPlaceholderText('Find a fruit...'),
).toBeInTheDocument();
});
+
+ describe('result announcements', () => {
+ it('announces the match count politely while searching', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ // "a" matches Apple and Banana.
+ await user.type(screen.getByRole('combobox', h), 'a');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('2 results');
+ });
+ });
+
+ it('announces the singular form when one option matches', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ // "ban" matches only Banana. Anchored so it cannot pass on "1 results".
+ await user.type(screen.getByRole('combobox', h), 'ban');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent(/^1 result$/);
+ });
+ });
+
+ it('announces "No results found" when nothing matches', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ 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(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ 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('');
+ });
+ });
});
describe('keyboard accessibility', () => {
@@ -869,7 +954,12 @@ describe('Selector', () => {
it('submits the selected value under htmlName', () => {
const {container} = render(
<form>
- <Selector label="Fruit" htmlName="fruit" options={OPTIONS} value="Banana" />
+ <Selector
+ label="Fruit"
+ htmlName="fruit"
+ options={OPTIONS}
+ value="Banana"
+ />
</form>,
);
const data = new FormData(container.querySelector('form')!);
@@ -889,10 +979,18 @@ describe('Selector', () => {
it('is excluded from form data when disabled', () => {
const {container} = render(
<form>
- <Selector label="Fruit" htmlName="fruit" options={OPTIONS} value="Banana" isDisabled />
+ <Selector
+ label="Fruit"
+ htmlName="fruit"
+ options={OPTIONS}
+ value="Banana"
+ isDisabled
+ />
</form>,
);
- expect([...new FormData(container.querySelector('form')!).keys()]).toEqual([]);
+ expect([
+ ...new FormData(container.querySelector('form')!).keys(),
+ ]).toEqual([]);
});
});
});
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 09cc005ca3..e177ce34ad 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -42,6 +42,7 @@ import {Divider} from '../Divider';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import type {LayerPlacement} from '../Layer/useLayer';
import {Spinner} from '../Spinner';
+import {useAnnounce} from '../hooks/useAnnounce';
import {
colorVars,
sizeVars,
@@ -536,6 +537,23 @@ function DefaultOption({option}: {option: SelectorOptionData}) {
);
}
+// 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: SelectorOptionData[],
+ query: string,
+): SelectorOptionData[] {
+ if (!query) {
+ return items;
+ }
+ const q = query.toLowerCase();
+ return items.filter(item =>
+ (item.label ?? item.value).toLowerCase().includes(q),
+ );
+}
+
/**
* A selector/dropdown component for choosing from a list of options.
*
@@ -641,15 +659,10 @@ export function Selector<T extends SelectorOptionType>(
);
// 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],
+ );
// Find selected item and its index for positioning
const selectedItemIndex = useMemo(() => {
@@ -665,11 +678,20 @@ export function Selector<T extends SelectorOptionType>(
// Ref for listbox to measure selected item position
const listboxRef = useRef<HTMLDivElement>(null);
+ // Announce match counts / "No results found" politely as the user types, so
+ // screen-reader users hear how many options remain. Filtering was previously
+ // silent (comboboxes-7). Mirrors BaseTypeahead, which announces from its
+ // query-change callback (not a reactive effect) via the same useAnnounce hook.
+ const announce = useAnnounce();
+
// Layer for dropdown positioning
const handleLayerHide = useCallback(() => {
setSearchQuery('');
+ // 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({
onHide: handleLayerHide,
@@ -689,6 +711,29 @@ export function Selector<T extends SelectorOptionType>(
// 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.
+ 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],
+ );
+
// Calculate offset to position selected item over trigger. Explicit
// placement opts out of the selector-specific overlay behavior and uses the
// standard layer positioning API instead.
@@ -810,7 +855,7 @@ export function Selector<T extends SelectorOptionType>(
aria-label={t('@astryx.selector.searchOptions')}
type="text"
value={searchQuery}
- onChange={e => setSearchQuery(e.target.value)}
+ onChange={handleSearchChange}
onKeyDown={e => {
// Arrow keys navigate options; Enter selects; Escape/Tab close.
// Home/End are left to the input for caret movement.
@@ -835,6 +880,7 @@ export function Selector<T extends SelectorOptionType>(
listboxId,
searchQuery,
searchPlaceholder,
+ handleSearchChange,
onKeyDown,
popover.isOpen,
highlightedIndex,