Skip to content

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

TypeScript

feat(Selector, MultiSelector): configurable panel empty states (#5462)

Cindy Zhang8985bb93276d
diff --git a/.changeset/selector-configurable-empty-state.md b/.changeset/selector-configurable-empty-state.md
new file mode 100644
index 0000000000..8bf2201d5d
--- /dev/null
+++ b/.changeset/selector-configurable-empty-state.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Selector and MultiSelector: configurable panel empty states via `emptyText` and `emptySearchText`, announced to screen readers as well as shown; a panel with no options now says so instead of rendering blank, and says nothing while `isLoading`
+
+@cixzhang
diff --git a/apps/storybook/stories/MultiSelector.stories.tsx b/apps/storybook/stories/MultiSelector.stories.tsx
index 150edd5f7c..03fae7dc17 100644
--- a/apps/storybook/stories/MultiSelector.stories.tsx
+++ b/apps/storybook/stories/MultiSelector.stories.tsx
@@ -182,6 +182,50 @@ export const Searchable: Story = {
decorators: [Story => <Story />],
};
+// Empty states
+export const EmptyStates: Story = {
+ render: () => {
+ const [a, setA] = useState<string[]>([]);
+ const [b, setB] = useState<string[]>([]);
+ const [c, setC] = useState<string[]>([]);
+ const [d, setD] = useState<string[]>([]);
+ return (
+ <div
+ style={{display: 'flex', flexDirection: 'column', gap: 16, width: 300}}>
+ <MultiSelector
+ label="No options (default)"
+ options={[]}
+ value={a}
+ onChange={setA}
+ />
+ <MultiSelector
+ label="No options (custom)"
+ options={[]}
+ value={b}
+ onChange={setB}
+ emptyText="No countries loaded yet"
+ />
+ <MultiSelector
+ label="Search for xyz (custom)"
+ options={['Canada', 'France', 'Japan']}
+ value={c}
+ onChange={setC}
+ hasSearch
+ emptySearchText="Nothing matches that country"
+ />
+ <MultiSelector
+ label="Loading (no message)"
+ options={[]}
+ value={d}
+ onChange={setD}
+ isLoading
+ />
+ </div>
+ );
+ },
+ decorators: [Story => <Story />],
+};
+
// Trigger display modes
export const TriggerModes: Story = {
render: () => {
diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsx
index 6ac9ea482a..717cae8961 100644
--- a/apps/storybook/stories/Selector.stories.tsx
+++ b/apps/storybook/stories/Selector.stories.tsx
@@ -374,6 +374,50 @@ export const Searchable: Story = {
},
};
+// Empty states
+export const EmptyStates: Story = {
+ render: () => {
+ const [a, setA] = useState<string | undefined>(undefined);
+ const [b, setB] = useState<string | undefined>(undefined);
+ const [c, setC] = useState<string | undefined>(undefined);
+ const [d, setD] = useState<string | undefined>(undefined);
+ return (
+ <div
+ style={{display: 'flex', flexDirection: 'column', gap: 16, width: 300}}>
+ <Selector
+ label="No options (default)"
+ options={[]}
+ value={a}
+ onChange={v => setA(v)}
+ />
+ <Selector
+ label="No options (custom)"
+ options={[]}
+ value={b}
+ onChange={v => setB(v)}
+ emptyText="No fruit in season yet"
+ />
+ <Selector
+ label="Search for xyz (custom)"
+ options={['Apple', 'Banana', 'Cherry']}
+ value={c}
+ onChange={v => setC(v)}
+ hasSearch
+ emptySearchText="Nothing matches that fruit"
+ />
+ <Selector
+ label="Loading (no message)"
+ options={[]}
+ value={d}
+ onChange={v => setD(v)}
+ isLoading
+ />
+ </div>
+ );
+ },
+ decorators: [Story => <Story />],
+};
+
// Custom render
export const CustomRender: Story = {
render: args => {
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 503a3e0120..9d26a3b6cf 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -511,6 +511,10 @@
"defaultMessage": "Search options",
"description": "Screen-reader-only accessible name for that same search input inside a MultiSelector."
},
+ "@astryx.multiSelector.empty": {
+ "defaultMessage": "No options",
+ "description": "Shown in a MultiSelector's dropdown panel when it was given no options at all, and announced in a polite live region on open. Very short (2 words); neutral tone, not error-y."
+ },
"@astryx.multiSelector.selectAllPartiallySelected": {
"defaultMessage": "{label}, partially selected",
"description": "Accessible name for the MultiSelector select-all option while only some options are selected. `{label}` is the visible select-all label (e.g. \"Select all\"). ARIA forbids aria-selected=\"mixed\" on options, so the indeterminate state is conveyed through the name instead. \"Partially\" = some but not all."
@@ -527,6 +531,10 @@
"defaultMessage": "Search options",
"description": "\"Options\" = the list of choices in the dropdown. Screen-reader-only accessible name for the search input inside a Selector."
},
+ "@astryx.selector.empty": {
+ "defaultMessage": "No options",
+ "description": "Shown in a Selector's dropdown panel when it was given no options at all, and announced in a polite live region on open. Very short (2 words); neutral tone, not error-y."
+ },
"@astryx.sideNav.label": {
"defaultMessage": "Side navigation",
"description": "Screen-reader-only accessible name for the primary vertical sidebar nav (usually on the left)."
@@ -1205,7 +1213,7 @@
},
"@astryx.multiSelector.emptySearchResults": {
"defaultMessage": "No results found",
- "description": "Polite screen-reader announcement when a MultiSelector search query matches no options. Live-region text, never shown on screen; neutral tone (not error-y)."
+ "description": "Shown in a MultiSelector's dropdown panel when the search query matches no options, and announced in a polite live region at the same time. Short; neutral tone (not error-y)."
},
"@astryx.multiSelector.resultCount": {
"defaultMessage": "{count, number} {count, plural, one {result} other {results}}",
@@ -1213,7 +1221,7 @@
},
"@astryx.selector.emptySearchResults": {
"defaultMessage": "No results found",
- "description": "Polite screen-reader announcement when a Selector search query matches no options. Live-region text, never shown on screen; neutral tone (not error-y)."
+ "description": "Shown in a Selector's dropdown panel when the search query matches no options, and announced in a polite live region at the same time. Short; neutral tone (not error-y)."
},
"@astryx.selector.resultCount": {
"defaultMessage": "{count, number} {count, plural, one {result} other {results}}",
diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
index b6ac0a032b..9e4f6fb573 100644
--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs
+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
@@ -25,7 +25,10 @@ export const docs = {
visualProps: ['variant', 'size', 'status'],
states: ['disabled'],
},
- {className: 'astryx-multi-selector-clear-icon', deprecatedFor: 'input-clear-icon'},
+ {
+ className: 'astryx-multi-selector-clear-icon',
+ deprecatedFor: 'input-clear-icon',
+ },
{className: 'astryx-multi-selector-empty-state'},
{className: 'astryx-multi-selector-search'},
{className: 'astryx-multi-selector-section-heading'},
@@ -139,6 +142,20 @@ export const docs = {
description: 'Placeholder text for the search input.',
default: "'Search...'",
},
+ {
+ 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.',
+ 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).',
+ default: "'No results found'",
+ },
{
name: 'isDisabled',
type: 'boolean',
@@ -315,6 +332,8 @@ export const docsZh = {
selectAllLabel: '全选复选框的标签。',
hasSearch: '是否显示用于过滤选项的搜索输入。',
searchPlaceholder: '搜索输入的占位文本。',
+ emptyText: '没有可显示的选项时,下拉面板中显示的内容。',
+ emptySearchText: '搜索查询未匹配到任何选项时,下拉面板中显示的内容。',
isDisabled: '禁用选择器。',
htmlName:
'用于表单提交的 HTML name 属性。为每个已选值渲染一个隐藏输入,类似原生多选。',
@@ -452,6 +471,8 @@ export const docsDense = {
selectAllLabel: 'select-all label',
hasSearch: 'show search input',
searchPlaceholder: 'search placeholder',
+ emptyText: 'panel content when there are no options',
+ emptySearchText: 'panel content when the query matches nothing',
isDisabled: 'disables selector',
htmlName: 'HTML name attr; one hidden input per selected value.',
disabledMessage:
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index adb3570d34..1718dc6481 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -11,6 +11,7 @@
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {
+ act,
render,
screen,
fireEvent,
@@ -911,6 +912,176 @@ describe('MultiSelector', () => {
expect(empty).toHaveAttribute('role', 'presentation');
});
+ it('renders emptySearchText in place of the default message', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ emptySearchText="Nothing like that here"
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ const listbox = screen.getByRole('listbox', h);
+ expect(
+ within(listbox).getByText('Nothing like that here'),
+ ).toBeInTheDocument();
+ expect(
+ within(listbox).queryByText('No results found'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders emptyText, not emptySearchText, with no options and no query', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={[]}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ emptySearchText="Nothing like that here"
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+
+ const listbox = screen.getByRole('listbox', h);
+ expect(within(listbox).getByText('No options')).toBeInTheDocument();
+ expect(
+ within(listbox).queryByText('Nothing like that here'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('announces emptySearchText, not the catalog default', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ emptySearchText="Nothing like that here"
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ // The panel message is role="presentation", so the live region is the
+ // only thing a screen reader gets — it has to say the same words.
+ 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(
+ <MultiSelector
+ label="Fruit"
+ options={[]}
+ value={[]}
+ onChange={() => {}}
+ emptyText="Add a fruit first"
+ />,
+ );
+
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Add a fruit first'),
+ );
+ });
+
+ it('shows and announces nothing while isLoading', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={[]}
+ value={[]}
+ onChange={() => {}}
+ isLoading
+ />,
+ );
+
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ // useAnnounce writes on the next animation frame, so an immediate read
+ // would pass whether or not anything was announced.
+ await act(
+ async () =>
+ void (await new Promise(resolve => requestAnimationFrame(resolve))),
+ );
+
+ // The options have not arrived, so "No options" would be a claim the
+ // component cannot make; the trigger's spinner carries the state.
+ const listbox = screen.getByRole('listbox', h);
+ expect(within(listbox).queryByText('No options')).not.toBeInTheDocument();
+ expect(politeRegion()?.textContent ?? '').toBe('');
+ });
+
+ it('announces nothing while isLoading, matching the silent panel', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ isLoading
+ emptySearchText="Nothing like that here"
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ // useAnnounce writes on the next animation frame, so an immediate read
+ // would pass whether or not anything was announced.
+ await act(
+ async () =>
+ void (await new Promise(resolve => requestAnimationFrame(resolve))),
+ );
+
+ // The panel is deliberately blank while loading; the live region is the
+ // only channel left, so a result there would be a claim the screen
+ // refuses to make.
+ const listbox = screen.getByRole('listbox', h);
+ expect(
+ within(listbox).queryByText('Nothing like that here'),
+ ).not.toBeInTheDocument();
+ expect(politeRegion()?.textContent ?? '').toBe('');
+ });
+
+ it('renders emptyText when there are no options and no search input', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={[]}
+ value={[]}
+ onChange={() => {}}
+ emptyText="Add a fruit first"
+ />,
+ );
+
+ // Without hasSearch the trigger itself is the combobox.
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ const listbox = screen.getByRole('listbox', h);
+ expect(within(listbox).getByText('Add a fruit first')).toBeInTheDocument();
+ });
+
describe('result announcements', () => {
it('announces the match count politely while searching', async () => {
const user = userEvent.setup();
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 403a929bc3..579c4d4377 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -604,6 +604,25 @@ export interface MultiSelectorProps<
*/
searchPlaceholder?: string;
+ /**
+ * Content shown in the panel when there are no options to show, and
+ * announced in a polite live region when the panel opens. Not shown while
+ * `isLoading` — the options have not arrived yet.
+ * @default 'No options'
+ */
+ emptyText?: ReactNode;
+
+ /**
+ * 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.
+ * @default 'No results found'
+ */
+ emptySearchText?: ReactNode;
+
/**
* How to display selected items in the trigger.
* - 'count': "3 selected"
@@ -726,6 +745,8 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
selectAllLabel: selectAllLabelFromProps,
hasSearch = false,
searchPlaceholder: searchPlaceholderFromProps,
+ emptyText: emptyTextFromProps,
+ emptySearchText: emptySearchTextFromProps,
triggerDisplay = 'count',
formatValue,
maxBadges = 3,
@@ -747,6 +768,9 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
selectAllLabelFromProps ?? t('@astryx.multiSelector.selectAll');
const searchPlaceholder =
searchPlaceholderFromProps ?? t('@astryx.multiSelector.searchPlaceholder');
+ const emptyText = emptyTextFromProps ?? t('@astryx.multiSelector.empty');
+ const emptySearchText =
+ emptySearchTextFromProps ?? t('@astryx.multiSelector.emptySearchResults');
const size = useSize(sizeProp, 'md');
const effectiveStatusVariant =
variant === 'ghost' && statusVariant === 'attached'
@@ -821,6 +845,19 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// Announce selection-count changes politely (comboboxes-7 announce path).
// 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;
@@ -940,16 +977,54 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
announce('');
return;
}
+ // While isLoading the panel deliberately shows nothing, so announcing a
+ // result would put a claim in the one channel the screen has gone quiet
+ // for.
+ if (isLoading) {
+ announce('');
+ return;
+ }
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
announce(
count === 0
- ? t('@astryx.multiSelector.emptySearchResults')
+ ? emptySearchAnnouncement
: t('@astryx.multiSelector.resultCount', {count}),
);
},
- [announce, selectableItems, t],
+ [announce, isLoading, selectableItems, emptySearchAnnouncement, 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 =
+ popover.isOpen &&
+ !isLoading &&
+ searchQuery === '' &&
+ selectableItems.length === 0;
+ if (!isPanelEmpty) {
+ announcedEmptyRef.current = null;
+ return;
+ }
+ if (announcedEmptyRef.current === emptyAnnouncement) {
+ return;
+ }
+ announcedEmptyRef.current = emptyAnnouncement;
+ announce(emptyAnnouncement);
+ }, [
+ popover.isOpen,
+ isLoading,
+ searchQuery,
+ selectableItems.length,
+ emptyAnnouncement,
+ announce,
+ ]);
+
// Handle toggle
// Clear all selected values. Shared by the clear button and the keyboard
// Delete/Backspace path so clearing is reachable without a mouse.
@@ -1416,7 +1491,10 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// message out of the listbox's accessibility tree (role="listbox" only
// permits option/group children); the no-results outcome is announced
// via the result-count live region instead.
- if (realItemCount === 0) {
+ // While isLoading the options have not arrived yet, so asserting either
+ // message would be a claim the component cannot make; the trigger's
+ // spinner covers it.
+ if (realItemCount === 0 && !isLoading) {
elements.push(
<div
key="empty"
@@ -1425,7 +1503,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
themeProps('multi-selector-empty-state'),
stylex.props(styles.emptyState),
)}>
- No results found
+ {searchQuery ? emptySearchText : emptyText}
</div>,
);
return elements;
@@ -1515,7 +1593,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
flushPending();
return elements;
- }, [options, renderItem, sortedItems, searchQuery, hasSelectAll]);
+ }, [
+ options,
+ renderItem,
+ sortedItems,
+ searchQuery,
+ hasSelectAll,
+ isLoading,
+ emptyText,
+ emptySearchText,
+ ]);
// The detached message box renders its own leading status icon, so the
// on-field icon would duplicate it — keep the chevron indicator instead.
diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjs
index 01ac8b6d4d..6c67d2efa0 100644
--- a/packages/core/src/Selector/Selector.doc.mjs
+++ b/packages/core/src/Selector/Selector.doc.mjs
@@ -89,6 +89,20 @@ export const docs = {
description: 'Placeholder text for the search input.',
default: "'Search...'",
},
+ {
+ 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.',
+ 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).',
+ default: "'No results found'",
+ },
{
name: 'placeholder',
type: 'string',
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index f281eabf78..1e09eea49f 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -11,6 +11,7 @@
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {
+ act,
render,
screen,
fireEvent,
@@ -943,6 +944,222 @@ describe('Selector', () => {
expect(empty).toHaveAttribute('role', 'presentation');
});
+ it('renders emptySearchText in place of the default message', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ emptySearchText="Nothing like that here"
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ const listbox = screen.getByRole('listbox', h);
+ expect(
+ within(listbox).getByText('Nothing like that here'),
+ ).toBeInTheDocument();
+ expect(
+ within(listbox).queryByText('No results found'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders emptyText, not emptySearchText, with no options and no query', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={[]}
+ onChange={() => {}}
+ hasSearch
+ emptySearchText="Nothing like that here"
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+
+ const listbox = screen.getByRole('listbox', h);
+ expect(within(listbox).getByText('No options')).toBeInTheDocument();
+ expect(
+ within(listbox).queryByText('Nothing like that here'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('announces emptySearchText, not the catalog default', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ emptySearchText="Nothing like that here"
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ // The panel message is role="presentation", so the live region is the
+ // only thing a screen reader gets — it has to say the same words.
+ 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(
+ <Selector
+ label="Fruit"
+ options={[]}
+ onChange={() => {}}
+ emptyText="Add a fruit first"
+ />,
+ );
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Add a fruit first'),
+ );
+ });
+
+ it('shows and announces nothing while isLoading', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector label="Fruit" options={[]} onChange={() => {}} isLoading />,
+ );
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ // useAnnounce writes on the next animation frame, so an immediate read
+ // would pass whether or not anything was announced.
+ await act(
+ async () =>
+ void (await new Promise(resolve => requestAnimationFrame(resolve))),
+ );
+
+ // The options have not arrived, so "No options" would be a claim the
+ // component cannot make; the trigger's spinner carries the state.
+ const listbox = screen.getByRole('listbox', h);
+ expect(within(listbox).queryByText('No options')).not.toBeInTheDocument();
+ expect(politeRegion()?.textContent ?? '').toBe('');
+ });
+
+ it('announces nothing while isLoading, matching the silent panel', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ isLoading
+ emptySearchText="Nothing like that here"
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await user.type(screen.getByRole('combobox', h), 'xyz');
+
+ // useAnnounce writes on the next animation frame, so an immediate read
+ // would pass whether or not anything was announced.
+ await act(
+ async () =>
+ void (await new Promise(resolve => requestAnimationFrame(resolve))),
+ );
+
+ // The panel is deliberately blank while loading; the live region is the
+ // only channel left, so a result there would be a claim the screen
+ // refuses to make.
+ const listbox = screen.getByRole('listbox', h);
+ expect(
+ within(listbox).queryByText('Nothing like that here'),
+ ).not.toBeInTheDocument();
+ expect(politeRegion()?.textContent ?? '').toBe('');
+ });
+
+ it('announces the seeded query from type-to-open', async () => {
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ emptySearchText="Nothing like that here"
+ />,
+ );
+ // Typing on the closed trigger opens the popup and seeds the query. That
+ // path bypasses the search input's own change handler, so it has to
+ // announce for itself.
+ const trigger = screen.getByRole('button', {name: 'Fruit'});
+ trigger.focus();
+ fireEvent.keyDown(trigger, {key: 'z'});
+
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Nothing like that here'),
+ );
+ });
+
+ it('announces the empty state when a load finishes with no options', async () => {
+ const user = userEvent.setup();
+ function Fetching() {
+ const [isLoading, setIsLoading] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsLoading(false)}>
+ land
+ </button>
+ <Selector
+ label="Fruit"
+ options={[]}
+ onChange={() => {}}
+ isLoading={isLoading}
+ emptyText="Add a fruit first"
+ />
+ </>
+ );
+ }
+ render(<Fetching />);
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ // Open while loading: nothing on screen, nothing spoken.
+ await act(
+ async () =>
+ void (await new Promise(resolve => requestAnimationFrame(resolve))),
+ );
+ expect(politeRegion()?.textContent ?? '').toBe('');
+
+ // The fetch lands empty while the panel is open. The message appears, so
+ // the region owes the same words — an open-only announcement misses this.
+ await user.click(screen.getByRole('button', {name: 'land'}));
+ await waitFor(() =>
+ expect(politeRegion()?.textContent).toBe('Add a fruit first'),
+ );
+ });
+
+ it('renders emptyText when there are no options and no search input', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={[]}
+ onChange={() => {}}
+ emptyText="Add a fruit first"
+ />,
+ );
+ // Without hasSearch the trigger itself is the combobox.
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+
+ const listbox = screen.getByRole('listbox', h);
+ expect(
+ within(listbox).getByText('Add a fruit first'),
+ ).toBeInTheDocument();
+ });
+
it('calls onChange when selecting a filtered option', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 5ebc4cdd15..c60813d0cd 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -648,6 +648,25 @@ interface SelectorPropsBase<
*/
searchPlaceholder?: string;
+ /**
+ * Content shown in the panel when there are no options to show, and
+ * announced in a polite live region when the panel opens. Not shown while
+ * `isLoading` — the options have not arrived yet.
+ * @default 'No options'
+ */
+ emptyText?: ReactNode;
+
+ /**
+ * 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.
+ * @default 'No results found'
+ */
+ emptySearchText?: ReactNode;
+
/**
* Position placement relative to the trigger.
*
@@ -794,6 +813,8 @@ export function Selector<T extends SelectorOptionType>(
indicatorPosition = 'end',
hasSearch = false,
searchPlaceholder: searchPlaceholderFromProps,
+ emptyText: emptyTextFromProps,
+ emptySearchText: emptySearchTextFromProps,
placement,
isDefaultOpen = false,
'data-testid': testId,
@@ -808,6 +829,9 @@ export function Selector<T extends SelectorOptionType>(
const placeholder = placeholderFromProps ?? t('@astryx.selector.placeholder');
const searchPlaceholder =
searchPlaceholderFromProps ?? t('@astryx.selector.searchPlaceholder');
+ const emptyText = emptyTextFromProps ?? t('@astryx.selector.empty');
+ const emptySearchText =
+ emptySearchTextFromProps ?? t('@astryx.selector.emptySearchResults');
const hasClear = hasClearProp === true;
const size = useSize(sizeProp, 'md');
const effectiveStatusVariant =
@@ -831,6 +855,9 @@ export function Selector<T extends SelectorOptionType>(
const inputGroup = useInputGroup();
const [searchQuery, setSearchQuery] = useState('');
+ // Mirrors searchQuery for the seed path, which runs before focus reaches the
+ // input and so cannot read the rendered state.
+ const searchQueryRef = useRef('');
// A typed query shows the search row's clear (✕) button, which becomes
// the next tab stop after the search input.
const hasQuery = searchQuery.length > 0;
@@ -840,6 +867,17 @@ 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
@@ -907,6 +945,7 @@ export function Selector<T extends SelectorOptionType>(
// Layer for dropdown positioning
const handleLayerHide = useCallback(() => {
setSearchQuery('');
+ searchQueryRef.current = '';
resetTypeaheadRef.current();
// Clear any lingering result count when the popover closes so stale status
// text does not linger in the a11y tree.
@@ -935,28 +974,76 @@ 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
+ // Announce the filtered result count from the query-change handlers (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(
+ // not re-speak on unrelated re-renders. Split out from handleSearchChange so
+ // the type-to-open seed below reaches the same live region — a query the user
+ // typed is a query however it arrived.
+ const announceSearchResults = useCallback(
(nextQuery: string) => {
- setSearchQuery(nextQuery);
if (nextQuery.length === 0) {
// Emptying the query clears the region rather than announcing a count.
announce('');
return;
}
+ // While isLoading the panel deliberately shows nothing, so announcing a
+ // result would put a claim in the one channel the screen has gone quiet
+ // for.
+ if (isLoading) {
+ announce('');
+ return;
+ }
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
announce(
count === 0
- ? t('@astryx.selector.emptySearchResults')
+ ? emptySearchAnnouncement
: t('@astryx.selector.resultCount', {count}),
);
},
- [announce, selectableItems, t],
+ [announce, isLoading, selectableItems, emptySearchAnnouncement, t],
+ );
+
+ const handleSearchChange = useCallback(
+ (nextQuery: string) => {
+ setSearchQuery(nextQuery);
+ searchQueryRef.current = nextQuery;
+ announceSearchResults(nextQuery);
+ },
+ [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 =
+ popover.isOpen &&
+ !isLoading &&
+ searchQuery === '' &&
+ selectableItems.length === 0;
+ if (!isPanelEmpty) {
+ announcedEmptyRef.current = null;
+ return;
+ }
+ if (announcedEmptyRef.current === emptyAnnouncement) {
+ return;
+ }
+ announcedEmptyRef.current = emptyAnnouncement;
+ announce(emptyAnnouncement);
+ }, [
+ popover.isOpen,
+ isLoading,
+ searchQuery,
+ selectableItems.length,
+ emptyAnnouncement,
+ announce,
+ ]);
+
// 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.
@@ -992,10 +1079,20 @@ export function Selector<T extends SelectorOptionType>(
}, [onChange, changeAction, startTransition, setOptimisticValue]);
// Type-to-find appends to the query rather than replacing it: characters
- // typed before focus reaches the search input must not be dropped.
- const appendSearchQuery = useCallback((char: string) => {
- setSearchQuery(query => query + char);
- }, []);
+ // typed before focus reaches the search input must not be dropped. The ref
+ // is what makes that safe without a state updater — it advances
+ // synchronously, so a second character seeded in the same tick still sees
+ // the first, and the announcement can be computed here rather than inside a
+ // setState callback.
+ const appendSearchQuery = useCallback(
+ (char: string) => {
+ const nextQuery = searchQueryRef.current + char;
+ searchQueryRef.current = nextQuery;
+ setSearchQuery(nextQuery);
+ announceSearchResults(nextQuery);
+ },
+ [announceSearchResults],
+ );
const commitValue = useCallback(
(newValue: string) => {
@@ -1313,8 +1410,11 @@ export function Selector<T extends SelectorOptionType>(
const renderOptions = useCallback(() => {
const isSearching = hasSearch && Boolean(searchQuery);
- // Nothing matched across every group/option: show the empty state.
- if (isSearching && filteredItems.length === 0) {
+ // Nothing to show — either the query matched nothing, or no options were
+ // given at all. Both render the same slot with different copy. While
+ // isLoading the options have not arrived yet, so asserting either would be
+ // a claim the component cannot make; the trigger's spinner covers it.
+ if (filteredItems.length === 0 && !isLoading) {
// role="presentation" keeps the message out of the listbox's
// accessibility tree (role="listbox" only permits option/group
// children); the no-results outcome is announced via the
@@ -1327,7 +1427,7 @@ export function Selector<T extends SelectorOptionType>(
themeProps('selector-empty-state'),
stylex.props(styles.emptyState),
)}>
- No results found
+ {isSearching ? emptySearchText : emptyText}
</div>,
];
}
@@ -1401,7 +1501,16 @@ export function Selector<T extends SelectorOptionType>(
}
return elements;
- }, [options, renderItem, hasSearch, searchQuery, filteredItems]);
+ }, [
+ options,
+ renderItem,
+ hasSearch,
+ searchQuery,
+ filteredItems,
+ isLoading,
+ emptyText,
+ emptySearchText,
+ ]);
// The detached message box renders its own leading status icon, so the
// on-field icon would duplicate it — keep the chevron indicator instead.