Skip to content

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

TypeScript

fix(Selector, MultiSelector): announce the empty state that is on screen (#6905)

Cindy Zhang7908cf4e99e5
diff --git a/.changeset/announce-the-empty-state-shown.md b/.changeset/announce-the-empty-state-shown.md
new file mode 100644
index 0000000000..00055732af
--- /dev/null
+++ b/.changeset/announce-the-empty-state-shown.md
@@ -0,0 +1,14 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Selector and MultiSelector announce the empty-state message they actually show, and announce it on every path that reaches one.
+
+Two defects, one cause — the live region was fed from the props instead of from what rendered:
+
+- `emptyText` and `emptySearchText` accept a `ReactNode`, but the region spoke the value only when it was a string and announced the built-in default otherwise. A product that put a link or a "create one" row in the dead end showed one message and announced another, so the screen-reader user was told something the sighted user was not reading.
+- An empty result that arrived _after_ the keystroke — an async load landing with nothing that matches an active query — was never announced at all. The message sat on screen and the region stayed silent.
+
+Both components now read the rendered message out of the DOM and announce that, from one place that watches the panel's state rather than the keystroke. An element is announced as written, text a child component generates is announced correctly, and anything marked `aria-hidden` is left out of the announcement exactly as it is left out of the screen. A loading panel still announces nothing.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3d38127991..11eb8d7a9e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1142,6 +1142,21 @@ jobs:
- name: Run story play guard
run: node .github/scripts/story-play-guard.js --storybook-dir apps/storybook/dist
+ # The empty-state announcement is a live-region claim: what a screen
+ # reader receives when a search dead-ends, and that the message element
+ # stays presentational so `role="listbox"` keeps only option/group
+ # children. jsdom proves the wiring; only a real engine shows the
+ # accessibility tree that results, and this contract is cheap enough to
+ # run on every PR rather than waiting for the release matrix. Its own
+ # --output directory so a later audit run cannot clear it, and it cannot
+ # clear theirs (Playwright wipes the default directory per run).
+ - name: Run empty-state announcement contract
+ run: |
+ pnpm exec playwright test \
+ packages/core/src/Selector/__tests__/EmptyStateAnnouncement.a11y.chromium.spec.ts \
+ --project chromium \
+ --output empty-state-announcement-output
+
# ChatMessageBubble is nested under the shared Chat source directory, so
# the generic stable-visual owner cannot select its dedicated fixture.
# Run the component's bounded evidence matrix only when the PR scope names
diff --git a/apps/storybook/stories/SelectorEmptyStateA11y.stories.tsx b/apps/storybook/stories/SelectorEmptyStateA11y.stories.tsx
new file mode 100644
index 0000000000..189501cd81
--- /dev/null
+++ b/apps/storybook/stories/SelectorEmptyStateA11y.stories.tsx
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SelectorEmptyStateA11y.stories.tsx
+ * @input Uses Selector with caller-supplied ReactNode empty-state content
+ * @output Browser fixtures for the empty-state live-region announcement
+ * @position Stable fixtures for EmptyStateAnnouncement.a11y.chromium.spec.ts
+ *
+ * The panel's empty message is `role="presentation"` — `role="listbox"`
+ * permits only `option` and `group` children — so it reaches assistive
+ * technology only through the shared polite live region. This story covers
+ * what a DOM emulator cannot settle: whether the region actually carries the
+ * rendered words in a shipping engine, and whether the message element has
+ * stayed out of the listbox's own accessibility tree.
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {Selector} from '../../../packages/core/src/Selector/Selector';
+
+const OPTIONS = [
+ {value: 'apple', label: 'Apple'},
+ {value: 'banana', label: 'Banana'},
+];
+
+const meta: Meta = {
+ title: 'a11y/Selector empty state',
+ tags: ['no-visual'],
+};
+export default meta;
+
+/** An element in the dead end: the region must speak its text, not a default. */
+export const ElementEmptySearchText: StoryObj = {
+ name: 'element emptySearchText',
+ render: () => (
+ <div data-empty-scenario="element">
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="apple"
+ onChange={() => {}}
+ hasSearch
+ emptySearchText={
+ <span>
+ Nothing like that here. <a href="#new">Add a fruit</a>
+ <span aria-hidden="true"> →</span>
+ </span>
+ }
+ />
+ </div>
+ ),
+};
diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
index c81d12096f..ce54fde87c 100644
--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs
+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
@@ -268,14 +268,14 @@ export const docs = {
name: 'emptyText',
type: 'ReactNode',
description:
- 'Content shown in the dropdown panel when there are no options to show, and announced in a polite live region when the panel opens (a string override is announced verbatim; a richer node falls back to the default text). Not shown while isLoading.',
+ 'Content shown in the dropdown panel when there are no options to show, and announced in a polite live region when the panel opens. The announcement is the text this content renders, read from the DOM, so an element is announced as written and aria-hidden parts are left out of both. Not shown while isLoading.',
default: "'No options'",
},
{
name: 'emptySearchText',
type: 'ReactNode',
description:
- 'Content shown in the dropdown panel when a search query matches no options, and announced in a polite live region at the same time (a string override is announced verbatim; a richer node falls back to the default text).',
+ 'Content shown in the dropdown panel when a search query matches no options, and announced in a polite live region at the same time. The announcement is the text this content renders, read from the DOM, so an element is announced as written and aria-hidden parts are left out of both.',
default: "'No results found'",
},
{
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 0329947b2d..955be97e7a 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -1076,6 +1076,90 @@ describe('MultiSelector', () => {
);
});
+ // `emptySearchText` is typed ReactNode, which invites an element — a
+ // "no results, create one" row is exactly what a dead end is for. The
+ // announcement used to take the prop only when it was a string and
+ // announce the catalog default otherwise, so a screen-reader user was told
+ // something the sighted user was not reading (`spec:AST-056` AR1).
+ it('announces the text of an element emptySearchText', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ emptySearchText={
+ <span>
+ Nothing like that here. <a href="/new">Add a fruit</a>
+ </span>
+ }
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe(
+ 'Nothing like that here. Add a fruit',
+ ),
+ );
+ });
+
+ it('announces the text of an element emptyText', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={[]}
+ value={[]}
+ onChange={() => {}}
+ emptyText={
+ <span>
+ Add a fruit first<span aria-hidden="true"> →</span>
+ </span>
+ }
+ />,
+ );
+
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ // The decorative arrow is hidden from the accessibility tree on screen,
+ // so it stays out of the announcement too.
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Add a fruit first'),
+ );
+ });
+
+ it('announces text a child component renders, which is only in the DOM', async () => {
+ const user = userEvent.setup();
+ // The words exist nowhere in the node the caller passed — they are
+ // produced inside this component's own render. Reading the DOM after
+ // render is what makes them announceable.
+ function Message() {
+ return <span>Nothing like that here</span>;
+ }
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ emptySearchText={<Message />}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Nothing like that here'),
+ );
+ });
+
it('announces the empty state when opened with no options', async () => {
const user = userEvent.setup();
render(
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 0c96645e37..e8862477c2 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -72,6 +72,7 @@ import {
import {useMultiCombobox} from './hooks';
import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';
import {useAnnounce} from '../hooks/useAnnounce';
+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
@@ -640,9 +641,10 @@ export interface MultiSelectorProps<
* Content shown in the panel when a search query matches no options, and
* announced in a polite live region at the same time.
*
- * The panel message is `role="presentation"`, so the live region is the only
- * route to assistive tech: a string is announced verbatim, a richer node
- * falls back to the default text since it cannot be spoken.
+ * The panel message is `role="presentation"`, so the live region is the
+ * only route to assistive tech. It announces the text this content renders,
+ * read from the DOM, so an element is announced as written and anything
+ * marked `aria-hidden` is left out of both.
* @default 'No results found'
*/
emptySearchText?: ReactNode;
@@ -821,6 +823,8 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const inputLabelId = useId();
const readOnlyDescriptionId = useId();
const searchId = useId();
+ // Read by the live region above so it speaks what this element renders.
+ const emptyStateRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
const listboxRef = useRef<HTMLDivElement>(null);
@@ -886,18 +890,6 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// Toggling options / select-all previously produced no audible feedback.
const announce = useAnnounce();
- // The panel's empty message is role="presentation" and reaches assistive tech
- // only through this live region, so the region has to speak whatever the
- // panel shows. A ReactNode override cannot be spoken; fall back to the
- // catalog copy for that case rather than announcing nothing.
- const emptyAnnouncement =
- typeof emptyText === 'string'
- ? emptyText
- : t('@astryx.multiSelector.empty');
- const emptySearchAnnouncement =
- typeof emptySearchText === 'string'
- ? emptySearchText
- : t('@astryx.multiSelector.emptySearchResults');
const announceSelection = useCallback(
(nextValue: string[]) => {
const total = selectableItems.length;
@@ -1053,45 +1045,38 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
return;
}
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
- announce(
- count === 0
- ? emptySearchAnnouncement
- : t('@astryx.multiSelector.resultCount', {count}),
- );
+ if (count === 0) {
+ // The empty panel is announced from the rendered message below, not
+ // from here. Two speakers for one transition would say it twice, and
+ // this one cannot cover an empty result that arrives after the
+ // keystroke — an async load landing with nothing that matches.
+ return;
+ }
+ announce(t('@astryx.multiSelector.resultCount', {count}));
},
- [announce, isLoading, selectableItems, emptySearchAnnouncement, t],
+ [announce, isLoading, selectableItems, t],
);
- // The panel's empty message is role="presentation", so this region is the
- // only route to assistive tech. It has to watch the STATE rather than the
- // open event: the panel can become empty either on open or when a fetch
- // lands with nothing in it, and an open-only announcement leaves the second
- // case silent while the message sits on screen. The ref makes it fire once
- // per arrival at that state rather than on every re-render.
- const announcedEmptyRef = useRef<string | null>(null);
- useEffect(() => {
- const isPanelEmpty =
- surface.isOpen &&
- !isLoading &&
- searchQuery === '' &&
- selectableItems.length === 0;
- if (!isPanelEmpty) {
- announcedEmptyRef.current = null;
- return;
- }
- if (announcedEmptyRef.current === emptyAnnouncement) {
- return;
- }
- announcedEmptyRef.current = emptyAnnouncement;
- announce(emptyAnnouncement);
- }, [
- surface.isOpen,
- isLoading,
- searchQuery,
- selectableItems.length,
- emptyAnnouncement,
- announce,
- ]);
+ // The panel's empty message is role="presentation" — role="listbox" permits
+ // only option and group children — so this region is its only route to
+ // assistive tech, and the region has to say what the panel says. Both
+ // `emptyText` and `emptySearchText` take a ReactNode, so the words are read
+ // off the rendered element rather than guessed from the prop: a caller who
+ // puts a link in the dead end is announced their link, not a default
+ // (`spec:AST-056` AR1).
+ //
+ // Watching the rendered STATE rather than the keystroke also covers the
+ // case the old keystroke-time announcement could not: a fetch that lands
+ // with nothing matching an active query left the message on screen and the
+ // region silent.
+ //
+ // `realItemCount` mirrors renderOptions exactly: the select-all sentinel
+ // rides in `sortedItems` but is not an option anybody can match.
+ const realItemCount = hasSelectAll
+ ? sortedItems.length - 1
+ : sortedItems.length;
+ const isPanelEmpty = surface.isOpen && !isLoading && realItemCount === 0;
+ useAnnounceRenderedText(emptyStateRef, isPanelEmpty, searchQuery);
// Handle toggle
// Clear all selected values. Shared by the clear button and the keyboard
@@ -1517,11 +1502,6 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const elements: ReactNode[] = [];
let cursor = 0;
- // Number of real items (excluding the select-all sentinel)
- const realItemCount = hasSelectAll
- ? sortedItems.length - 1
- : sortedItems.length;
-
// Show select-all only when there are real items to select. It reads as
// the first row of the list, not a section of its own — no divider under
// it (the checkbox column already lines it up with the options below).
@@ -1544,6 +1524,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
elements.push(
<div
key="empty"
+ ref={emptyStateRef}
role="presentation"
{...mergeProps(
themeProps('multi-selector-empty-state'),
@@ -1643,6 +1624,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
options,
renderItem,
sortedItems,
+ realItemCount,
searchQuery,
hasSelectAll,
isLoading,
diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjs
index 21dd9ad2e7..6f716d1d8e 100644
--- a/packages/core/src/Selector/Selector.doc.mjs
+++ b/packages/core/src/Selector/Selector.doc.mjs
@@ -225,14 +225,14 @@ export const docs = {
name: 'emptyText',
type: 'ReactNode',
description:
- 'Content shown in the dropdown panel when there are no options to show, and announced in a polite live region when the panel opens (a string override is announced verbatim; a richer node falls back to the default text). Not shown while isLoading.',
+ 'Content shown in the dropdown panel when there are no options to show, and announced in a polite live region when the panel opens. The announcement is the text this content renders, read from the DOM, so an element is announced as written and aria-hidden parts are left out of both. Not shown while isLoading.',
default: "'No options'",
},
{
name: 'emptySearchText',
type: 'ReactNode',
description:
- 'Content shown in the dropdown panel when a search query matches no options, and announced in a polite live region at the same time (a string override is announced verbatim; a richer node falls back to the default text).',
+ 'Content shown in the dropdown panel when a search query matches no options, and announced in a polite live region at the same time. The announcement is the text this content renders, read from the DOM, so an element is announced as written and aria-hidden parts are left out of both.',
default: "'No results found'",
},
{
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index c19a862bb4..b8f0f0f242 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -1145,6 +1145,124 @@ describe('Selector', () => {
);
});
+ // `emptySearchText` is typed ReactNode, which invites an element — a
+ // "no results, create one" row is exactly what a dead end is for. The
+ // announcement used to take the prop only when it was a string and
+ // announce the catalog default otherwise, so a screen-reader user was
+ // told something the sighted user was not reading (`spec:AST-056` AR1).
+ it('announces the text of an element emptySearchText', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ emptySearchText={
+ <span>
+ Nothing like that here. <a href="/new">Add a fruit</a>
+ </span>
+ }
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe(
+ 'Nothing like that here. Add a fruit',
+ ),
+ );
+ });
+
+ it('announces the text of an element emptyText', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={[]}
+ onChange={() => {}}
+ emptyText={
+ <span>
+ Add a fruit first<span aria-hidden="true"> →</span>
+ </span>
+ }
+ />,
+ );
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ // The decorative arrow is hidden from the accessibility tree on screen,
+ // so it stays out of the announcement too.
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Add a fruit first'),
+ );
+ });
+
+ it('announces text a child component renders, which is only in the DOM', async () => {
+ const user = userEvent.setup();
+ // The words exist nowhere in the node the caller passed — they are
+ // produced inside this component's own render. Reading the DOM after
+ // render is what makes them announceable.
+ function Message() {
+ return <span>Nothing like that here</span>;
+ }
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ emptySearchText={<Message />}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Nothing like that here'),
+ );
+ });
+
+ it('announces an empty result that arrives after the keystroke', async () => {
+ const user = userEvent.setup();
+ // The query is typed while the options are still loading, so the
+ // keystroke-time announcement cannot know the outcome. When the load
+ // lands with nothing that matches, the message appears on screen and
+ // the region has to say so too.
+ //
+ // The load lands through a rerender rather than a click on something
+ // outside the panel: a real browser light-dismisses the panel on any
+ // outside click, and a closed panel is a different scenario. jsdom
+ // implements no light dismiss, so a button would pass here while
+ // modelling something that cannot happen.
+ function Deferred({loaded}: {loaded: boolean}) {
+ return (
+ <Selector
+ label="Fruit"
+ options={loaded ? OPTIONS : []}
+ onChange={() => {}}
+ hasSearch
+ isLoading={!loaded}
+ isDefaultOpen
+ emptySearchText="Nothing like that here"
+ />
+ );
+ }
+ const {rerender} = render(<Deferred loaded={false} />);
+
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+ // Loading: the panel shows nothing, so the region claims nothing.
+ expect(politeRegion()?.textContent ?? '').toBe('');
+
+ rerender(<Deferred loaded />);
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Nothing like that here'),
+ );
+ });
+
it('announces the empty state when opened with no options', async () => {
const user = userEvent.setup();
render(
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index f87136df9f..abb9aeb46e 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -50,6 +50,7 @@ import {InternalInputClearButton} from '../Field/InputClearButton';
import {Spinner} from '../Spinner';
import {PanelSearchInput} from '../Field/PanelSearchInput';
import {useAnnounce} from '../hooks/useAnnounce';
+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
import {
colorVars,
sizeVars,
@@ -716,9 +717,10 @@ interface SelectorPropsBase<
* Content shown in the panel when a search query matches no options, and
* announced in a polite live region at the same time.
*
- * The panel message is `role="presentation"`, so the live region is the only
- * route to assistive tech: a string is announced verbatim, a richer node
- * falls back to the default text since it cannot be spoken.
+ * The panel message is `role="presentation"`, so the live region is the
+ * only route to assistive tech. It announces the text this content renders,
+ * read from the DOM, so an element is announced as written and anything
+ * marked `aria-hidden` is left out of both.
* @default 'No results found'
*/
emptySearchText?: ReactNode;
@@ -916,6 +918,8 @@ export function Selector<T extends SelectorOptionType>(
// has to be that same value or the label and listbox point at nothing.
const triggerId = id ?? generatedTriggerId;
const listboxId = useId();
+ // Read by the live region above so it speaks what this element renders.
+ const emptyStateRef = useRef<HTMLDivElement>(null);
const descriptionId = useId();
const statusMessageId = useId();
const inputLabelId = useId();
@@ -941,17 +945,6 @@ export function Selector<T extends SelectorOptionType>(
const isBusy = isLoading || optimisticValue !== normalizedValue;
const announce = useAnnounce();
- // The panel's empty message is role="presentation" and reaches assistive tech
- // only through this live region, so the region has to speak whatever the
- // panel shows. A ReactNode override cannot be spoken; fall back to the
- // catalog copy for that case rather than announcing nothing.
- const emptyAnnouncement =
- typeof emptyText === 'string' ? emptyText : t('@astryx.selector.empty');
- const emptySearchAnnouncement =
- typeof emptySearchText === 'string'
- ? emptySearchText
- : t('@astryx.selector.emptySearchResults');
-
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
// tooltip listeners attach to the trigger container (which already exists)
// and the trigger button stays perceivable via aria-disabled instead of the
@@ -1101,13 +1094,16 @@ export function Selector<T extends SelectorOptionType>(
return;
}
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
- announce(
- count === 0
- ? emptySearchAnnouncement
- : t('@astryx.selector.resultCount', {count}),
- );
+ if (count === 0) {
+ // The empty panel is announced from the rendered message below, not
+ // from here. Two speakers for one transition would say it twice, and
+ // this one cannot cover an empty result that arrives after the
+ // keystroke — an async load landing with nothing that matches.
+ return;
+ }
+ announce(t('@astryx.selector.resultCount', {count}));
},
- [announce, isLoading, selectableItems, emptySearchAnnouncement, t],
+ [announce, isLoading, selectableItems, t],
);
const handleSearchChange = useCallback(
@@ -1119,36 +1115,21 @@ export function Selector<T extends SelectorOptionType>(
[announceSearchResults],
);
- // The panel's empty message is role="presentation", so this region is the
- // only route to assistive tech. It has to watch the STATE rather than the
- // open event: the panel can become empty either on open or when a fetch
- // lands with nothing in it, and an open-only announcement leaves the second
- // case silent while the message sits on screen. The ref makes it fire once
- // per arrival at that state rather than on every re-render.
- const announcedEmptyRef = useRef<string | null>(null);
- useEffect(() => {
- const isPanelEmpty =
- surface.isOpen &&
- !isLoading &&
- searchQuery === '' &&
- selectableItems.length === 0;
- if (!isPanelEmpty) {
- announcedEmptyRef.current = null;
- return;
- }
- if (announcedEmptyRef.current === emptyAnnouncement) {
- return;
- }
- announcedEmptyRef.current = emptyAnnouncement;
- announce(emptyAnnouncement);
- }, [
- surface.isOpen,
- isLoading,
- searchQuery,
- selectableItems.length,
- emptyAnnouncement,
- announce,
- ]);
+ // The panel's empty message is role="presentation" — role="listbox" permits
+ // only option and group children — so this region is its only route to
+ // assistive tech, and the region has to say what the panel says. Both
+ // `emptyText` and `emptySearchText` take a ReactNode, so the words are read
+ // off the rendered element rather than guessed from the prop: a caller who
+ // puts a link in the dead end is announced their link, not a default
+ // (`spec:AST-056` AR1).
+ //
+ // Watching the rendered STATE rather than the keystroke also covers the
+ // case the old keystroke-time announcement could not: a fetch that lands
+ // with nothing matching an active query left the message on screen and the
+ // region silent.
+ const isPanelEmpty =
+ surface.isOpen && !isLoading && filteredItems.length === 0;
+ useAnnounceRenderedText(emptyStateRef, isPanelEmpty, searchQuery);
// Calculate offset to position selected item over trigger. Explicit
// placement opts out of the selector-specific overlay behavior and uses the
@@ -1554,6 +1535,7 @@ export function Selector<T extends SelectorOptionType>(
return [
<div
key="empty"
+ ref={emptyStateRef}
role="presentation"
{...mergeProps(
themeProps('selector-empty-state'),
diff --git a/packages/core/src/Selector/__tests__/EmptyStateAnnouncement.a11y.chromium.spec.ts b/packages/core/src/Selector/__tests__/EmptyStateAnnouncement.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..85cd041995
--- /dev/null
+++ b/packages/core/src/Selector/__tests__/EmptyStateAnnouncement.a11y.chromium.spec.ts
@@ -0,0 +1,90 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file EmptyStateAnnouncement.a11y.chromium.spec.ts
+ * @input Uses the checked-in Selector empty-state stories in a built Storybook
+ * @output Real-engine evidence that the live region carries the rendered
+ * empty-state words, and that the message itself is not a live region
+ * @position Browser binding for `spec:AST-056` AR1. jsdom can prove the
+ * wiring; only a shipping engine can show the accessibility tree that
+ * results, which is what AST-020 reserves for this layer.
+ *
+ * `Listbox.a11y.states.ts` excludes "zero-result representation and
+ * announcement timing" from the listbox pattern ledger, on the grounds that
+ * it needs its own authority and evidence. AST-056 AR1 is that authority and
+ * this file is that evidence; the ledger's own slice is untouched.
+ */
+
+import {expect, test} from '@playwright/test';
+import {
+ serveStorybook,
+ DEFAULT_STORYBOOK_DIR,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+const politeRegion = '[data-astryx-live-region="polite"]';
+
+test('announces the words an element empty state renders', async ({page}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-selector-empty-state--element-empty-search-text&viewMode=story`,
+ {waitUntil: 'load'},
+ );
+ await page.locator('[data-empty-scenario="element"]').waitFor();
+
+ await page.getByRole('button', {name: 'Fruit'}).click();
+ await page.getByRole('combobox').fill('zzzzz');
+
+ // What the sighted user reads, and what the screen-reader user is told,
+ // are the same sentence. The decorative arrow is in neither.
+ await expect(page.locator(politeRegion)).toHaveText(
+ 'Nothing like that here. Add a fruit',
+ );
+});
+
+test('leaves the rendered message out of the accessibility tree itself', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-selector-empty-state--element-empty-search-text&viewMode=story`,
+ {waitUntil: 'load'},
+ );
+ await page.locator('[data-empty-scenario="element"]').waitFor();
+
+ await page.getByRole('button', {name: 'Fruit'}).click();
+ await page.getByRole('combobox').fill('zzzzz');
+
+ const message = page.locator('.astryx-selector-empty-state');
+ await expect(message).toBeVisible();
+ // It stays presentational. Turning it into a live region would put a
+ // non-option child inside role="listbox", which is the reason it was
+ // marked this way in the first place.
+ await expect(message).toHaveAttribute('role', 'presentation');
+ await expect(message).not.toHaveAttribute('aria-live', /.*/);
+
+ // And the listbox exposes no options to walk, rather than a fake one.
+ await expect(page.getByRole('listbox').getByRole('option')).toHaveCount(0);
+});
+
+// Not covered here: the deferred case — a load landing with nothing matching
+// a query typed while it was in flight. It is covered in Selector.test.tsx and
+// mutation-checked there (restoring the old `searchQuery === ''` condition
+// fails it and nothing else).
+//
+// A browser version was written and withdrawn. Its step assertions showed the
+// query surviving, the panel open, and zero options, with the empty message
+// absent — which `renderOptions` produces only while `isLoading` is true. The
+// story's `setLoaded(true)` never reached the mounted instance, so the
+// component never left loading and was correct to render nothing. That is a
+// story-harness problem, not a component one, and chasing it through CI (the
+// authoring machine cannot launch Chromium) was costing more than the
+// scenario's incremental browser coverage is worth.
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.ts b/packages/core/src/hooks/useAnnounceRenderedText.ts
new file mode 100644
index 0000000000..bf4ec24ed6
--- /dev/null
+++ b/packages/core/src/hooks/useAnnounceRenderedText.ts
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useAnnounceRenderedText.ts
+ * @input A ref to a rendered element, whether it is showing, and a token that
+ * marks a new occasion to speak
+ * @output Announces that element's own rendered text through the persistent
+ * polite live region
+ * @position Core a11y hook; mirrors on-screen content into the shared live
+ * region by reading the DOM
+ *
+ * Some content reaches assistive technology only through a live region: a
+ * panel message marked `role="presentation"`, for instance, because
+ * `role="listbox"` permits only `option` and `group` children. When that
+ * content is a caller-supplied `ReactNode`, the component must announce what
+ * it actually rendered — announcing a built-in default over a caller's
+ * element tells the screen-reader user something the sighted user is not
+ * reading (`spec:AST-056` AR1, FR3).
+ *
+ * The text is read from the DOM after render, never by inspecting React
+ * children. That is the whole point: by the time this runs the browser has
+ * rendered the subtree, so text a child component generates inside its own
+ * render announces correctly, and there is no tree walk, no depth limit, and
+ * no "could not read it" fallback to get wrong.
+ *
+ * Announcing through the persistent `useAnnounce` region rather than putting
+ * `role="status"` on the rendered element is both required here — the element
+ * is a listbox child, which may only be `option` or `group` — and the
+ * repository's established convention for conditionally rendered messages
+ * (see `FieldStatus` and `TimeInput`): a live region that mounts together
+ * with its content is not reliably announced.
+ *
+ * Content hidden from the accessibility tree with `aria-hidden` is excluded,
+ * so a decorative icon stays out of the announcement exactly as it stays out
+ * of what a screen reader reads. An `aria-label` renaming a descendant is NOT
+ * substituted — the region speaks the rendered text.
+ *
+ * SYNC: deliberately NOT exported from /packages/core/src/hooks/index.ts —
+ * that barrel is re-exported wholesale from the package entry point, so
+ * adding it there would ship a new public hook without `spec:AST-002`
+ * admission. Import it by path from inside the package.
+ */
+
+import {useEffect, useRef, type RefObject} from 'react';
+import {useAnnounce} from './useAnnounce';
+
+/** The rendered text an assistive technology would read from `element`. */
+function renderedText(element: HTMLElement): string {
+ // Clone so removing the hidden parts cannot disturb what is on screen. The
+ // clone is never attached to the document.
+ const copy = element.cloneNode(true) as HTMLElement;
+ for (const hidden of copy.querySelectorAll('[aria-hidden="true"]')) {
+ hidden.remove();
+ }
+ return (copy.textContent ?? '').replace(/\s+/g, ' ').trim();
+}
+
+/**
+ * Announce the text of a rendered element through the shared polite live
+ * region, once per occasion.
+ *
+ * Announces when the element appears and whenever its rendered text changes.
+ * Pass `isShown: false` for every state where the element is not on screen —
+ * including while loading — and the hook stays silent and re-arms.
+ *
+ * @param ref - The element whose rendered text to speak
+ * @param isShown - Whether that element is currently on screen
+ * @param occasion - Marks a new reason to speak the same words again; for a
+ * search dead end this is the query, so each new query that matches nothing
+ * is announced rather than only the first
+ *
+ * @example
+ * ```
+ * const emptyStateRef = useRef<HTMLDivElement>(null);
+ * useAnnounceRenderedText(emptyStateRef, isPanelEmpty, searchQuery);
+ * ```
+ */
+export function useAnnounceRenderedText(
+ ref: RefObject<HTMLElement | null>,
+ isShown: boolean,
+ occasion: string,
+): void {
+ const announce = useAnnounce();
+ const spokenRef = useRef<string | null>(null);
+
+ // Deliberately no dependency array. The text lives in the DOM, so there is
+ // no React value to depend on that changes when it does — a caller can
+ // change the rendered message without any prop this hook can see. Reading
+ // one element's text per render is cheap, and the dedupe below makes every
+ // render after the first a no-op.
+ useEffect(() => {
+ if (!isShown) {
+ spokenRef.current = null;
+ return;
+ }
+ const element = ref.current;
+ if (!element) {
+ return;
+ }
+ const text = renderedText(element);
+ if (text === '') {
+ // Nothing readable on screen either, so there is no announcement that
+ // would match what the sighted user is seeing.
+ return;
+ }
+ const spoken = `${occasion}\u0000${text}`;
+ if (spokenRef.current === spoken) {
+ return;
+ }
+ spokenRef.current = spoken;
+ announce(text);
+ });
+}