An open source design system that's fully customizable and agent ready
TypeScript
fix(core): announce CommandPalette result, empty, and loading states (#4351)
Baraa Hamodi39da490e81ee
diff --git a/.changeset/a11y-command-palette-status.md b/.changeset/a11y-command-palette-status.mdnew file mode 100644index 0000000000..83c416020d--- /dev/null+++ b/.changeset/a11y-command-palette-status.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] CommandPalette: announce result counts, empty, and loading states to screen readers via the shared polite live region (WCAG 4.1.3)+@bhamodidiff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 4e74ab8bca..763043ccc6 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -315,6 +315,18 @@"defaultMessage": "Type to search","description": "Onboarding empty-state text shown inside a CommandPalette on first open, before the user has typed anything. Imperative sentence fragment."},+ "@astryx.commandPalette.resultCount": {+ "defaultMessage": "{count, number} {count, plural, one {result} other {results}}",+ "description": "Screen-reader-only announcement of how many commands match the CommandPalette query as the user types. Example: `12 results`, `1 result`; keep compact."+ },+ "@astryx.commandPalette.noResultsFor": {+ "defaultMessage": "No results for {query}",+ "description": "Screen-reader-only announcement when a CommandPalette query matches nothing. `{query}` is the user's verbatim search text; keep it last if your language allows so truncation-by-AT still conveys the outcome."+ },+ "@astryx.commandPalette.loading": {+ "defaultMessage": "Loading",+ "description": "Screen-reader-only announcement that a CommandPalette search has started and results are being fetched. Present-progressive form; matches the visible spinner."+ },"@astryx.dateRangeInput.presetDateRanges": {"defaultMessage": "Preset date ranges","description": "Screen-reader-only accessible name for the sidebar of quick-pick preset ranges inside a DateRangeInput popover (e.g. \"Last 7 days\", \"This month\")."diff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsxindex 530be637fe..9231dd236a 100644--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx@@ -8,10 +8,11 @@*/import {describe, it, expect, vi, beforeEach} from 'vitest';-import {render, screen, waitFor, fireEvent} from '@testing-library/react';+import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';import {CommandPalette} from './CommandPalette';import {createStaticSource} from '@astryxdesign/core/Typeahead';import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';const simpleSource = createStaticSource([{id: 'home', label: 'Home'},@@ -35,6 +36,9 @@ beforeEach(() => {HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {this.removeAttribute('open');});+ // The live regions are module-level singletons; reset them so+ // announcements from one test don't leak into the next.+ __resetLiveRegionsForTest();});describe('CommandPalette', () => {@@ -269,4 +273,94 @@ describe('CommandPalette', () => {expect(screen.getByText('No results')).toBeInTheDocument(),);});++ describe('screen reader announcements', () => {+ const politeRegion = () =>+ document.querySelector('[data-astryx-live-region="polite"]');++ it('announces the result count politely after typing a query', async () => {+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={simpleSource}+ />,+ );+ await waitFor(() => expect(screen.getByText('Home')).toBeInTheDocument());+ // "e" matches both Home and Settings.+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'e'}});+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('2 results');+ });+ });++ it('announces the singular form when one item matches', async () => {+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={simpleSource}+ />,+ );+ await waitFor(() => expect(screen.getByText('Home')).toBeInTheDocument());+ // "set" matches only Settings. Anchored so it cannot pass on "1 results".+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'set'}});+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent(/^1 result$/);+ });+ });++ it('announces the empty state with the query when nothing matches', async () => {+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={simpleSource}+ />,+ );+ await waitFor(() => expect(screen.getByText('Home')).toBeInTheDocument());+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('No results for zzz');+ });+ });++ it('announces loading politely while a search is in flight', async () => {+ // A source whose searches never resolve, so the palette stays busy and+ // only the loading announcement can reach the live region.+ const source: SearchSource = {+ bootstrap: () => [],+ async search(): Promise<SearchableItem[]> {+ return new Promise<SearchableItem[]>(() => {});+ },+ };+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={source}+ />,+ );+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'z'}});+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Loading');+ });+ });++ it('does not announce on initial open (bootstrap)', async () => {+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={simpleSource}+ />,+ );+ await waitFor(() => expect(screen.getByText('Home')).toBeInTheDocument());+ // Flush effects and any pending live-region rAF writes.+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 50));+ });+ expect(politeRegion()?.textContent ?? '').toBe('');+ });+ });});diff --git a/packages/core/src/CommandPalette/CommandPalette.tsx b/packages/core/src/CommandPalette/CommandPalette.tsxindex 689b206a25..d59806ce08 100644--- a/packages/core/src/CommandPalette/CommandPalette.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.tsx@@ -3,7 +3,7 @@'use client';/*** @file CommandPalette.tsx- * @input Uses React, Dialog, Layout, CommandPaletteContext, SearchSource, useCombobox+ * @input Uses React, Dialog, Layout, CommandPaletteContext, SearchSource, useCombobox, useAnnounce* @output Exports CommandPalette root component and props* @position Core root component; dialog shell with searchSource-driven items*@@ -36,6 +36,7 @@ import {CommandPaletteInput} from './CommandPaletteInput';import {CommandPaletteFooter} from './CommandPaletteFooter';import {CommandPaletteEmpty} from './CommandPaletteEmpty';import type {BaseProps} from '../BaseProps';+import {useAnnounce} from '../hooks/useAnnounce';import {useTranslator} from '../i18n';export interface CommandPaletteProps<@@ -291,6 +292,13 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({const isBusy = isPending;const searchVersionRef = useRef(0);+ // Announce search status to screen readers through the shared polite live+ // region (comboboxes-7 announce path, mirroring Selector / BaseTypeahead).+ // The busy spinner and the empty states are otherwise purely visual, so a+ // screen-reader user typing a query would hear nothing when loading starts+ // or results disappear.+ const announce = useAnnounce();+const value = controlledValue ?? internalValue;const setValue = useCallback(@@ -318,8 +326,12 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({setInternalValue('');}searchSource.cancel?.();+ // Clear any lingering result / loading announcement when the palette+ // closes so stale status text does not linger in the a11y tree+ // (matching Selector's onHide).+ announce('');onOpenChange(false);- }, [onOpenChange, searchSource, controlledValue]);+ }, [onOpenChange, searchSource, controlledValue, announce]);const selectItem = useCallback((itemValue: string) => {@@ -355,6 +367,14 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({startTransition(async () => {const isBootstrap = query === '';+ // Loading started for a user query: tell screen-reader users the+ // spinner appeared. The polite region coalesces rapid updates, so for+ // fast sources the result-count announcement below simply replaces+ // this instead of stacking one "Loading" per keystroke.+ if (!isBootstrap) {+ announce(t('@astryx.commandPalette.loading'));+ }+// Client-filter previous results for instant narrowing while fetch is in flightif (!isBootstrap && searchResults.length > 0) {const lower = query.toLowerCase().trim();@@ -377,6 +397,23 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({setOptimisticResults(items);setSearchResults(items);+ // Announce the outcome from the search commit (not a reactive+ // effect), matching Selector / BaseTypeahead: exactly one+ // announcement per committed query, and the version check above+ // already discards stale keystrokes. Bootstrap stays silent — the+ // same role PowerSearch's mount guard plays — so opening the+ // palette announces nothing; clearing the query only clears any+ // lingering status text.+ if (isBootstrap) {+ announce('');+ } else if (items.length === 0) {+ announce(t('@astryx.commandPalette.noResultsFor', {query}));+ } else {+ announce(+ t('@astryx.commandPalette.resultCount', {count: items.length}),+ );+ }+// When opening with a preselected value, highlight it once// bootstrap results arrive. No value → highlight stays at -1// and ArrowDown naturally moves to the first item.@@ -396,6 +433,8 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({value,combobox,setOptimisticResults,+ announce,+ t,],);