An open source design system that's fully customizable and agent ready
TypeScript
fix(core): announce PowerSearch result counts to screen readers (#3726)
Baraa Hamodi2b3ac0f9d46a
diff --git a/.changeset/powersearch-results-announce.md b/.changeset/powersearch-results-announce.mdnew file mode 100644index 0000000000..0237fce384--- /dev/null+++ b/.changeset/powersearch-results-announce.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] PowerSearch: changes to the visible result count are now announced to screen readers via a polite live region, mirroring Typeahead's wording. Previously the count only updated visually. (#3726)+@bhamodidiff --git a/packages/core/src/PowerSearch/PowerSearch.doc.mjs b/packages/core/src/PowerSearch/PowerSearch.doc.mjsindex 0f561a4a5a..792c294b61 100644--- a/packages/core/src/PowerSearch/PowerSearch.doc.mjs+++ b/packages/core/src/PowerSearch/PowerSearch.doc.mjs@@ -120,7 +120,7 @@ export const docs = {name: 'resultCount',type: 'number | string',description:- 'Number of results matching the current filters. When a number, formatted as "N results". When a string, displayed as-is.',+ 'Number of results matching the current filters. When a number, formatted as "N results". When a string, displayed as-is. Changes are announced to screen readers via a polite live region.',},{name: 'size',@@ -261,7 +261,7 @@ export const docsZh = {name: 'resultCount',type: 'number | string',description:- '匹配当前过滤器的结果数量。数字类型时格式化为"N results"。字符串类型时按原样显示。',+ '匹配当前过滤器的结果数量。数字类型时格式化为"N results"。字符串类型时按原样显示。数量变化会通过 polite 实时区域向屏幕阅读器播报。',},{name: 'size',diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsxindex 2caa1b614a..a0c5a368d0 100644--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx@@ -10,10 +10,11 @@*/import {useState} from 'react';-import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';+import {describe, it, expect, vi, beforeAll, afterAll, afterEach} from 'vitest';import {render, screen, act, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {PowerSearch} from './PowerSearch';+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import type {PowerSearchConfig, PowerSearchFilter} from './types';// =============================================================================@@ -59,6 +60,12 @@ afterAll(() => {(HTMLElement.prototype as any).matches = originalMatches;});+// Reset the singleton live regions between tests so result-count+// announcements from one test don't leak into the next.+afterEach(() => {+ __resetLiveRegionsForTest();+});+// =============================================================================// Fixtures// =============================================================================@@ -295,4 +302,105 @@ describe('PowerSearch', () => {expect(screen.getByRole('combobox')).toBeDisabled();});});++ describe('result count announcements', () => {+ const politeRegion = () =>+ document.querySelector('[data-astryx-live-region="polite"]');++ it('announces the result count to a polite live region when it changes', async () => {+ const {rerender} = render(+ <PowerSearch+ config={config}+ filters={[]}+ onChange={() => {}}+ resultCount={0}+ />,+ );+ rerender(+ <PowerSearch+ config={config}+ filters={[]}+ onChange={() => {}}+ resultCount={5}+ />,+ );+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('5 results');+ });+ });++ it('announces "1 result" (singular) for a single match', async () => {+ const {rerender} = render(+ <PowerSearch+ config={config}+ filters={[]}+ onChange={() => {}}+ resultCount={0}+ />,+ );+ rerender(+ <PowerSearch+ config={config}+ filters={[]}+ onChange={() => {}}+ resultCount={1}+ />,+ );+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('1 result');+ });+ expect(politeRegion()?.textContent).not.toMatch(/results/);+ });++ it('announces a string result count verbatim', async () => {+ const {rerender} = render(+ <PowerSearch+ config={config}+ filters={[]}+ onChange={() => {}}+ resultCount="0 items"+ />,+ );+ rerender(+ <PowerSearch+ config={config}+ filters={[]}+ onChange={() => {}}+ resultCount="Showing 1.2k matches"+ />,+ );+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Showing 1.2k matches');+ });+ });++ it('does not announce the result count present on initial mount', async () => {+ render(+ <PowerSearch+ config={config}+ filters={[]}+ onChange={() => {}}+ resultCount={42}+ />,+ );+ // Flush effects and any pending live-region rAF writes.+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 50));+ });+ expect(politeRegion()?.textContent ?? '').not.toContain('42');+ });++ it('leaves Typeahead dropdown announcements intact and stays silent when no resultCount is set', async () => {+ const user = userEvent.setup();+ render(<PowerSearchWrapper config={config} />);+ const input = screen.getByRole('combobox');+ await user.click(input);+ await user.type(input, 'Status');+ // BaseTypeahead announces the dropdown suggestion count; PowerSearch adds+ // no result-count announcement because resultCount is unset.+ await waitFor(() => {+ expect(politeRegion()?.textContent).toMatch(/\d+ results?/);+ });+ });+ });});diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsxindex 67ed258227..39fda05658 100644--- a/packages/core/src/PowerSearch/PowerSearch.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.tsx@@ -16,6 +16,7 @@import React, {useCallback,+ useEffect,useImperativeHandle,useMemo,useRef,@@ -38,6 +39,7 @@ import type {IconType} from '../Icon';import type {IconName} from '../Icon/globalIconRegistry';import type {InputStatus} from '../Field';import {usePopover} from '../Popover/usePopover';+import {useAnnounce} from '../hooks/useAnnounce';import {spacingVars,colorVars,@@ -945,23 +947,42 @@ export function PowerSearch({isReadOnly,]);+ // Plain-text form of the result count, shared by the visible label and the+ // screen-reader announcement so the two never drift.+ const resultCountText = useMemo((): string | null => {+ if (resultCount == null) {+ return null;+ }+ if (typeof resultCount === 'number') {+ const formatted = new Intl.NumberFormat().format(resultCount);+ return `${formatted} ${resultCount === 1 ? 'result' : 'results'}`;+ }+ return resultCount;+ }, [resultCount]);++ // Announce result-count changes to screen readers through a polite live+ // region, mirroring the way Typeahead announces its dropdown result count.+ // The count is otherwise only shown visually and stays silent to assistive+ // tech. Skip the first run so the count already present on mount isn't+ // announced unprompted — only user-driven changes are spoken.+ const announce = useAnnounce();+ const hasMountedRef = useRef(false);+ useEffect(() => {+ if (!hasMountedRef.current) {+ hasMountedRef.current = true;+ return;+ }+ if (resultCountText != null) {+ announce(resultCountText);+ }+ }, [resultCountText, announce]);+// Build combined endContent from resultCount + endContent propsconst combinedEndContent = useMemo((): React.ReactNode => {- let resultCountNode: React.ReactNode = null;- if (resultCount != null) {- if (typeof resultCount === 'number') {- const formatted = new Intl.NumberFormat().format(resultCount);- resultCountNode = (- <span {...stylex.props(resultCountStyles.text)}>- {formatted} {resultCount === 1 ? 'result' : 'results'}- </span>- );- } else {- resultCountNode = (- <span {...stylex.props(resultCountStyles.text)}>{resultCount}</span>- );- }- }+ const resultCountNode =+ resultCountText != null ? (+ <span {...stylex.props(resultCountStyles.text)}>{resultCountText}</span>+ ) : null;if (resultCountNode && endContent) {return (@@ -972,7 +993,7 @@ export function PowerSearch({);}return resultCountNode || endContent || undefined;- }, [resultCount, endContent]);+ }, [resultCountText, endContent]);return (<>