Skip to content

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

TypeScript

feat(core): add useAnnounce live-region hook + wire into Typeahead (#3382)

Cindy Zhange7d922b957c6
diff --git a/.changeset/use-announce.md b/.changeset/use-announce.md
new file mode 100644
index 0000000000..76f32ab87e
--- /dev/null
+++ b/.changeset/use-announce.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Add `useAnnounce` — an accessibility hook that speaks messages to screen readers through persistently-mounted, visually-hidden polite/assertive live regions. Because the regions are created once (not together with their content), announcements are reliable. Wired into `Typeahead`/`BaseTypeahead` to announce result counts and "no results found" during search, which were previously silent (#3343).
+@cixzhang
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index df13014e4b..bf6c87643f 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -29,6 +29,7 @@ import React, {
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {usePopover} from '../Popover/usePopover';
+import {useAnnounce} from '../hooks/useAnnounce';
import {TypeaheadItem} from './TypeaheadItem';
import {Icon} from '../Icon';
import {
@@ -310,6 +311,11 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
const inputRef = useRef<HTMLInputElement>(null);
const fallbackAnchorRef = useRef<HTMLInputElement>(null);
+ // Announce result counts / "no results" to screen readers via a persistent
+ // live region (comboboxes-6). The combobox's own popup carries no working
+ // live region, so highlight/result changes were previously silent.
+ const announce = useAnnounce();
+
const [query, setQuery] = useState('');
const [results, setResults] = useState<T[]>([]);
const [highlightedIndex, setHighlightedIndex] = useState(-1);
@@ -396,11 +402,21 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
return;
}
resultsGenRef.current = gen;
- setResults(searchResults.slice(0, maxMenuItems));
+ const shown = searchResults.slice(0, maxMenuItems);
+ setResults(shown);
setHighlightedIndex(searchResults.length > 0 ? 0 : -1);
if (searchResults.length > 0 || searchQuery.length > 0) {
showLayer();
}
+ // Announce the outcome only for an active query (not the initial
+ // focus-open), so screen-reader users hear result counts / no-results.
+ if (searchQuery.length > 0) {
+ announce(
+ shown.length === 0
+ ? emptySearchResultsText
+ : `${shown.length} ${shown.length === 1 ? 'result' : 'results'}`,
+ );
+ }
} catch {
if (searchGenRef.current !== gen) {
return;
@@ -413,7 +429,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
}
},
- [searchSource, maxMenuItems, showLayer],
+ [searchSource, maxMenuItems, showLayer, announce, emptySearchResultsText],
);
// Perform bootstrap
@@ -458,6 +474,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
searchSource.cancel?.();
setResults([]);
setHasSearched(false);
+ // Clear any lingering result-count / no-results announcement.
+ announce('');
popover.hide();
return;
}
@@ -484,6 +502,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
popover,
debounceMs,
searchSource,
+ announce,
],
);
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index 810d973e46..e7fca3eb0f 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -122,6 +122,47 @@ describe('BaseTypeahead', () => {
});
});
+ it('announces the result count to a live region (comboboxes-6)', async () => {
+ render(
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: 'Ap'}});
+
+ await waitFor(() => {
+ const region = document.querySelector(
+ '[data-astryx-live-region="polite"]',
+ );
+ expect(region?.textContent).toMatch(/\d+ results?/);
+ });
+ });
+
+ it('announces "no results found" when the search is empty (comboboxes-6)', async () => {
+ render(
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ emptySearchResultsText="No results found"
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: 'zzzzz'}});
+
+ await waitFor(() => {
+ const region = document.querySelector(
+ '[data-astryx-live-region="polite"]',
+ );
+ expect(region).toHaveTextContent('No results found');
+ });
+ });
+
it('disables input when isDisabled', () => {
render(
<BaseTypeahead
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index d061becfdf..4b5b2d593a 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -14,6 +14,9 @@
export {useFocusTrap} from './useFocusTrap';
export type {UseFocusTrapOptions, UseFocusTrapReturn} from './useFocusTrap';
+export {useAnnounce} from './useAnnounce';
+export type {AnnounceFn, AnnouncePoliteness} from './useAnnounce';
+
export {useGridFocus} from './useGridFocus';
export type {UseGridFocusOptions, UseGridFocusReturn} from './useGridFocus';
diff --git a/packages/core/src/hooks/useAnnounce.test.tsx b/packages/core/src/hooks/useAnnounce.test.tsx
new file mode 100644
index 0000000000..6f3e11d289
--- /dev/null
+++ b/packages/core/src/hooks/useAnnounce.test.tsx
@@ -0,0 +1,101 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useAnnounce.test.tsx
+ * @input Uses vitest, @testing-library/react, useAnnounce hook
+ * @output Unit tests for useAnnounce live-region announcements
+ * @position Testing; validates useAnnounce.ts
+ *
+ * SYNC: When useAnnounce.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, afterEach} from 'vitest';
+import {renderHook, waitFor} from '@testing-library/react';
+import {useAnnounce, __resetLiveRegionsForTest} from './useAnnounce';
+
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
+
+function politeRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="polite"]');
+}
+function assertiveRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="assertive"]');
+}
+
+describe('useAnnounce', () => {
+ it('mounts empty polite and assertive live regions on first announce', async () => {
+ const {result} = renderHook(() => useAnnounce());
+ // Regions do not exist until first use.
+ expect(politeRegion()).toBeNull();
+
+ result.current('Saved');
+
+ // Both regions exist after the first announce, before content settles.
+ expect(politeRegion()).not.toBeNull();
+ expect(assertiveRegion()).not.toBeNull();
+ expect(politeRegion()).toHaveAttribute('aria-live', 'polite');
+ expect(politeRegion()).toHaveAttribute('aria-atomic', 'true');
+ expect(politeRegion()).toHaveAttribute('role', 'status');
+ expect(assertiveRegion()).toHaveAttribute('aria-live', 'assertive');
+ expect(assertiveRegion()).toHaveAttribute('role', 'alert');
+ });
+
+ it('announces a polite message into the polite region', async () => {
+ const {result} = renderHook(() => useAnnounce());
+ result.current('12 results');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('12 results');
+ });
+ // Assertive region stays empty.
+ expect(assertiveRegion()).toHaveTextContent('');
+ });
+
+ it('routes assertive messages to the assertive region', async () => {
+ const {result} = renderHook(() => useAnnounce());
+ result.current('Upload failed', 'assertive');
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('Upload failed');
+ });
+ expect(politeRegion()).toHaveTextContent('');
+ });
+
+ it('re-announces an identical message (clears then re-sets)', async () => {
+ const {result} = renderHook(() => useAnnounce());
+ result.current('No results found');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('No results found');
+ });
+ // Second identical announce should still land (region is cleared first).
+ result.current('No results found');
+ expect(politeRegion()).toHaveTextContent('');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('No results found');
+ });
+ });
+
+ it('ignores empty messages', () => {
+ const {result} = renderHook(() => useAnnounce());
+ result.current('');
+ // No regions created for an empty announce.
+ expect(politeRegion()).toBeNull();
+ });
+
+ it('reuses the same singleton regions across hook instances', async () => {
+ const {result: a} = renderHook(() => useAnnounce());
+ a.current('first');
+ const region = politeRegion();
+
+ const {result: b} = renderHook(() => useAnnounce());
+ b.current('second');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('second');
+ });
+ // Same DOM node, not a duplicate.
+ expect(politeRegion()).toBe(region);
+ expect(
+ document.querySelectorAll('[data-astryx-live-region="polite"]').length,
+ ).toBe(1);
+ });
+});
diff --git a/packages/core/src/hooks/useAnnounce.ts b/packages/core/src/hooks/useAnnounce.ts
new file mode 100644
index 0000000000..6e2c3b1a52
--- /dev/null
+++ b/packages/core/src/hooks/useAnnounce.ts
@@ -0,0 +1,168 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useAnnounce.ts
+ * @input Uses React useCallback; DOM APIs for a singleton live-region pair
+ * @output Exports useAnnounce hook and AnnouncePoliteness type
+ * @position Core a11y hook; provides imperative screen-reader announcements
+ * via persistently-mounted polite/assertive live regions
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts
+ */
+
+import {useCallback} from 'react';
+
+/**
+ * Announcement urgency:
+ * - `'polite'` (default): announced when the screen reader is idle. Use for
+ * status updates, result counts, "no results", non-urgent confirmations.
+ * - `'assertive'`: interrupts the current announcement. Reserve for errors and
+ * time-sensitive alerts.
+ */
+export type AnnouncePoliteness = 'polite' | 'assertive';
+
+/**
+ * Imperative screen-reader announcement function.
+ */
+export type AnnounceFn = (
+ message: string,
+ politeness?: AnnouncePoliteness,
+) => void;
+
+const CONTAINER_ATTR = 'data-astryx-live-region';
+
+// Visually-hidden clip block (matches the VisuallyHidden primitive). Applied
+// inline so the regions work without any stylesheet being present.
+const VISUALLY_HIDDEN_CSS =
+ 'position:absolute;width:1px;height:1px;margin:-1px;padding:0;' +
+ 'overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;' +
+ 'inset-block-start:0;inset-inline-start:0;pointer-events:none;' +
+ 'user-select:none;';
+
+interface LiveRegions {
+ polite: HTMLElement;
+ assertive: HTMLElement;
+}
+
+// Singleton: the live regions are created ONCE and stay mounted for the
+// lifetime of the document. This is the crux of reliable announcements — many
+// screen readers will not announce content injected into a live region that is
+// created together with its content ("born with content"). By mounting empty
+// regions up front and only mutating their text later, updates are announced.
+let regions: LiveRegions | null = null;
+
+function createRegion(politeness: AnnouncePoliteness): HTMLElement {
+ const el = document.createElement('div');
+ el.setAttribute(CONTAINER_ATTR, politeness);
+ el.setAttribute('aria-live', politeness);
+ el.setAttribute('aria-atomic', 'true');
+ el.setAttribute('role', politeness === 'assertive' ? 'alert' : 'status');
+ el.style.cssText = VISUALLY_HIDDEN_CSS;
+ document.body.appendChild(el);
+ return el;
+}
+
+function getRegions(): LiveRegions | null {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+ if (regions) {
+ // Re-attach if a region was removed from the DOM (e.g. by a test cleanup).
+ if (!regions.polite.isConnected) {
+ document.body.appendChild(regions.polite);
+ }
+ if (!regions.assertive.isConnected) {
+ document.body.appendChild(regions.assertive);
+ }
+ return regions;
+ }
+ regions = {
+ polite: createRegion('polite'),
+ assertive: createRegion('assertive'),
+ };
+ return regions;
+}
+
+function announceMessage(
+ message: string,
+ politeness: AnnouncePoliteness,
+): void {
+ const r = getRegions();
+ if (!r) {
+ return;
+ }
+ const target = politeness === 'assertive' ? r.assertive : r.polite;
+ // Clearing first guarantees the mutation is observed even when the new
+ // message equals the current text — some AT deduplicate identical content.
+ target.textContent = '';
+ // A microtask/rAF-free re-set in the next frame is more reliable across AT
+ // than an immediate re-set, which can be coalesced with the clear.
+ requestAnimationFrame(() => {
+ target.textContent = message;
+ });
+}
+
+/**
+ * Clear any pending announcement from a region without announcing anything new.
+ * Used when the triggering context goes away (e.g. a search query is cleared),
+ * so stale status text does not linger in the accessibility tree.
+ */
+function clearRegion(politeness: AnnouncePoliteness): void {
+ if (!regions) {
+ return;
+ }
+ const target =
+ politeness === 'assertive' ? regions.assertive : regions.polite;
+ target.textContent = '';
+}
+
+/**
+ * Returns an imperative `announce(message, politeness?)` function that speaks a
+ * message through a persistently-mounted, visually-hidden live region.
+ *
+ * The polite and assertive regions are created once on first use and kept
+ * mounted, so announcements are reliable even for messages that appear
+ * immediately (unlike a live region rendered together with its content).
+ *
+ * @example
+ * ```
+ * function Search() {
+ * const announce = useAnnounce();
+ * const onResults = (n: number) => {
+ * announce(n === 0 ? 'No results found' : `${n} results`);
+ * };
+ * // ...
+ * }
+ * ```
+ */
+export function useAnnounce(): AnnounceFn {
+ return useCallback(
+ (message: string, politeness: AnnouncePoliteness = 'polite') => {
+ if (!message) {
+ // An empty message clears any lingering status from the region rather
+ // than announcing nothing — useful when the triggering context ends.
+ clearRegion(politeness);
+ return;
+ }
+ announceMessage(message, politeness);
+ },
+ [],
+ );
+}
+
+/**
+ * Test-only helper: removes the singleton live regions and resets state so
+ * each test starts clean. Not part of the public runtime API.
+ *
+ * @internal
+ */
+export function __resetLiveRegionsForTest(): void {
+ if (regions) {
+ regions.polite.remove();
+ regions.assertive.remove();
+ regions = null;
+ }
+}