Skip to content

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

TypeScript

fix(EmptyState): announce once when it appears after load, not as a live root (#8294)

Cindy Zhang8b74911937bd
diff --git a/.changeset/empty-state-no-live-role.md b/.changeset/empty-state-no-live-role.md
new file mode 100644
index 0000000000..e91057e0df
--- /dev/null
+++ b/.changeset/empty-state-no-live-role.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] EmptyState's root no longer carries `role="status"`, so it is not a live region that mounts already holding its text, which screen readers announce unreliably (`spec:AST-086` FR2). Apps need no code change. An EmptyState rendered or changed while the page loads announces nothing; one that appears later, or whose title or description changes later, announces its title and description once through the shared polite live region; inside a live container such as `ChatMessageList`'s log, the container announces it (`spec:AST-086` FR4). A `role` you pass now reaches the root instead of being replaced; tests that found EmptyState with `getByRole('status')` need another selector.
+
+@harjothkhara
diff --git a/packages/core/src/EmptyState/EmptyState.announce.test.tsx b/packages/core/src/EmptyState/EmptyState.announce.test.tsx
new file mode 100644
index 0000000000..34fa50c662
--- /dev/null
+++ b/packages/core/src/EmptyState/EmptyState.announce.test.tsx
@@ -0,0 +1,200 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file EmptyState.announce.test.tsx
+ * @input A fresh EmptyState module with the document's load held back
+ * @output spec:AST-086 FR11/FR12 tests for EmptyState's announcement
+ * @position Component test for EmptyState's announcement
+ */
+
+import {act, StrictMode, useState} from 'react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {createRoot, hydrateRoot} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+import {renderedText} from '../hooks/useAnnounceRenderedText';
+
+// The document is "loading" until `paint()`; a render before it is part of the
+// page load, one after it is inserted later (spec:AST-086 FR11).
+async function importEmptyState() {
+ let readyState: DocumentReadyState = 'loading';
+ vi.spyOn(document, 'readyState', 'get').mockImplementation(() => readyState);
+ const {EmptyState} = await import('./EmptyState');
+ return {EmptyState, paint: () => (readyState = 'complete')};
+}
+
+const nextFrame = async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
+const settle = async () => {
+ await act(nextFrame);
+ await act(nextFrame);
+};
+
+const POLITE = '[data-astryx-live-region="polite"]';
+
+/** Every write to the shared polite region, one entry per write. */
+function recordPolite() {
+ const spoken: string[] = [];
+ const observer = new MutationObserver(records => {
+ for (const {target, addedNodes} of records) {
+ const text = addedNodes.length ? target.textContent?.trim() : '';
+ if (text && (target as Element).matches?.(POLITE)) {
+ spoken.push(text);
+ }
+ }
+ });
+ observer.observe(document.body, {subtree: true, childList: true});
+ return {spoken, stop: () => observer.disconnect()};
+}
+
+const mount = () =>
+ createRoot(document.body.appendChild(document.createElement('div')));
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.replaceChildren();
+});
+
+describe('EmptyState announcement (spec:AST-086 FR2)', () => {
+ it('announces nothing when it renders with the page', async () => {
+ const {EmptyState, paint} = await importEmptyState();
+ const polite = recordPolite();
+ const root = mount();
+ await act(async () => {
+ root.render(<EmptyState title="No projects" description="Create one." />);
+ });
+ paint();
+ await settle();
+ polite.stop();
+ expect(polite.spoken).toEqual([]);
+ await act(async () => root.unmount());
+ });
+
+ it('announces its message once when it appears later', async () => {
+ const {EmptyState, paint} = await importEmptyState();
+ paint();
+ let showEmpty!: () => void;
+ function Results() {
+ const [isEmpty, setIsEmpty] = useState(false);
+ showEmpty = () => setIsEmpty(true);
+ return isEmpty ? (
+ <EmptyState
+ icon={<span>icon</span>}
+ title="No results"
+ description="Try another search."
+ actions={<button type="button">Clear filters</button>}
+ />
+ ) : (
+ <p>Searching</p>
+ );
+ }
+ const polite = recordPolite();
+ const root = mount();
+ await act(async () => {
+ root.render(
+ <StrictMode>
+ <Results />
+ </StrictMode>,
+ );
+ });
+ await act(async () => showEmpty());
+ await settle();
+ polite.stop();
+ expect(polite.spoken).toEqual(['No results Try another search.']);
+ await act(async () => root.unmount());
+ });
+
+ it('leaves an empty state inside a live container to that container (spec:AST-086 FR4)', async () => {
+ const {EmptyState, paint} = await importEmptyState();
+ paint();
+ let showEmpty!: () => void;
+ function Log() {
+ const [isEmpty, setIsEmpty] = useState(false);
+ showEmpty = () => setIsEmpty(true);
+ return (
+ <div role="log" aria-live="polite">
+ {isEmpty ? <EmptyState title="No messages yet" /> : null}
+ </div>
+ );
+ }
+ const polite = recordPolite();
+ const root = mount();
+ await act(async () => root.render(<Log />));
+ await act(async () => showEmpty());
+ await settle();
+ polite.stop();
+ expect(polite.spoken).toEqual([]);
+ await act(async () => root.unmount());
+ });
+
+ it('announces once when the message changes after the page loaded, not while it loads', async () => {
+ const {EmptyState, paint} = await importEmptyState();
+ let setTitle!: (title: string) => void;
+ function Search() {
+ const [title, set] = useState('No saved searches');
+ setTitle = set;
+ return <EmptyState title={title} />;
+ }
+ const polite = recordPolite();
+ const root = mount();
+ await act(async () => root.render(<Search />));
+ await act(async () => setTitle('No matches yet'));
+ paint();
+ await act(async () => setTitle('No results'));
+ await settle();
+ polite.stop();
+ expect(polite.spoken).toEqual(['No results']);
+ await act(async () => root.unmount());
+ });
+
+ it('announces nothing from a server render or its hydration (FR12)', async () => {
+ const {EmptyState, paint} = await importEmptyState();
+ const tree = <EmptyState title="No projects" />;
+ const container = document.createElement('div');
+ container.innerHTML = renderToString(tree);
+ document.body.appendChild(container);
+ paint();
+ const polite = recordPolite();
+ const root = await act(async () => hydrateRoot(container, tree));
+ await settle();
+ polite.stop();
+ expect(polite.spoken).toEqual([]);
+ await act(async () => root.unmount());
+ });
+
+ it('reads blocks apart and leaves hidden text out of the message', () => {
+ const element = document.createElement('div');
+ element.innerHTML = '<p>Try again.</p><p>Later.</p><b hidden>No</b>';
+ expect(renderedText(element)).toBe('Try again. Later.');
+ });
+
+ it('stays silent while hidden (attribute or CSS) or revealed during load; announces once when shown later (FR12)', async () => {
+ const {EmptyState, paint} = await importEmptyState();
+ // jsdom has no checkVisibility; this one honors an inline display: none.
+ HTMLElement.prototype.checkVisibility = function (this: HTMLElement) {
+ return this.closest('[style*="none"]') == null;
+ };
+ const polite = recordPolite();
+ const root = mount();
+ const show = async (hidden: boolean, display?: string) =>
+ act(async () =>
+ root.render(
+ <div style={{display}}>
+ <EmptyState title="No results" hidden={hidden} />
+ </div>,
+ ),
+ );
+ await show(true);
+ await show(false);
+ paint();
+ await show(true);
+ await show(false, 'none');
+ await act(nextFrame);
+ expect(polite.spoken).toEqual([]);
+ await show(false);
+ await settle();
+ polite.stop();
+ expect(polite.spoken).toEqual(['No results']);
+ delete (HTMLElement.prototype as Partial<HTMLElement>).checkVisibility;
+ await act(async () => root.unmount());
+ });
+});
diff --git a/packages/core/src/EmptyState/EmptyState.doc.mjs b/packages/core/src/EmptyState/EmptyState.doc.mjs
index d0f75308e4..383e566398 100644
--- a/packages/core/src/EmptyState/EmptyState.doc.mjs
+++ b/packages/core/src/EmptyState/EmptyState.doc.mjs
@@ -81,7 +81,7 @@ export const docs = {
{ guidance: false, description: 'Use an EmptyState for error messages that require immediate action; use a Banner instead.' },
],
anatomy: [
- {name: 'Container', required: true, description: 'The centered status region that owns spacing, reading order, and the compact layout variant.'},
+ {name: 'Container', required: true, description: 'The centered root that owns spacing, reading order, and the compact layout variant.'},
{name: 'Icon', required: false, description: 'A visual cue above the title that reinforces the context, like a search icon for no results.'},
{name: 'Title', required: true, description: 'Primary message explaining what is empty: "No projects yet" not "No data".'},
{name: 'Description', required: false, description: 'Additional context explaining why it is empty or what the user can do.'},
diff --git a/packages/core/src/EmptyState/EmptyState.spec.md b/packages/core/src/EmptyState/EmptyState.spec.md
index f03b9d4580..2dad2a7c2d 100644
--- a/packages/core/src/EmptyState/EmptyState.spec.md
+++ b/packages/core/src/EmptyState/EmptyState.spec.md
@@ -26,7 +26,8 @@ architecture:
architecture:component-test-sufficiency,
]
contributing: []
-system_specs: [spec:AST-020/FR1, spec:AST-029/FR3]
+system_specs:
+ [spec:AST-020/FR1, spec:AST-029/FR3, spec:AST-086/FR2, spec:AST-086/FR11]
---
# EmptyState component contract
@@ -35,11 +36,11 @@ system_specs: [spec:AST-020/FR1, spec:AST-029/FR3]
| Area | Contract |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Public contract | `EmptyState` renders a required title plus optional description, decorative icon, and caller-owned actions in one status region; callers choose heading level and compact layout. |
+| Public contract | `EmptyState` renders a required title plus optional description, decorative icon, and caller-owned actions in one root without a live role; callers choose heading level and compact layout. |
| Behavior | Null, undefined, boolean, and empty-string optional values create no slot wrapper. Rendered content follows icon, text, then actions order; compact layout reduces spacing and stacks actions. |
| End-user impact | A person reaches a named empty-content message and any next action without blank gaps from shallow-empty optional values; the title fits the surrounding document outline. |
| Builder impact | Callers supply content and actions, select heading semantics, and may compose supported root props and styling. No additional setup is required. |
-| Compatibility/readiness | The released default is preserved. This draft observes shipped behavior plus the narrow scalar-slot remediation; it adds no API, default, or compatibility promise. |
+| Compatibility/readiness | No live role on the root; an EmptyState that appears after load announces once (`spec:AST-086` FR2). Otherwise this draft observes shipped behavior and the scalar-slot remediation. |
| Review checks | Reject a missing heading, an informative icon hidden as decorative, a shallow-empty optional scalar that still changes layout, a dropped root prop/ref/style, or a theme target without anatomy. |
| Governing rules | `architecture:public-component-api` INV1 and INV5–INV9; `architecture:component-theming-surface` INV2–INV6; `architecture:component-test-sufficiency` INV1–INV7, INV10–INV11; WCAG 2.2. |
@@ -52,10 +53,10 @@ context, optional decorative visual, and optional caller-owned next actions.
## Compatibility and migration
-- Released default preserved: yes
-- Compatibility class: observational and additive documentation; runtime remediation removes wrappers for nullish, boolean, and empty-string optional values
+- Released default preserved: no; EmptyState adds no live role to the root
+- Compatibility class: observational and additive documentation; runtime remediation removes wrappers for nullish, boolean, and empty-string optional values and removes the root's live role
- Controlled/uncontrolled behavior: not applicable
-- Migration decision: none
+- Migration decision: none; an EmptyState rendered with the page announces nothing, and one that appears later announces its message once through the shared polite channel, so apps need no change (`spec:AST-086` FR2)
Consumer migration instructions belong in consumer docs and release notes.
@@ -63,7 +64,7 @@ Consumer migration instructions belong in consumer docs and release notes.
**Owns**
-- the status-region root, content order, heading element, and default/compact layout;
+- the root, content order, heading element, and default/compact layout;
- hiding the icon slot from assistive technology as decorative; and
- whether optional slots create component-owned wrappers and spacing.
@@ -91,11 +92,11 @@ intentional decision. A `current` contract contains no unresolved rows.
| ID | Candidate invariant | Basis | Draft review state |
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ------------------ |
-| FR1 | The component MUST render one status-region root containing the icon, text group, and actions in that reading order when present. | Current implementation and consumer docs; WCAG 2.2 SC 1.3.2 and SC 4.1.3 | verify |
+| FR1 | The component MUST render one root containing the icon, text group, and actions in that reading order when present. The component MUST NOT add a live role or `aria-live` to the root. | Current implementation and consumer docs; `spec:AST-086` FR2; WCAG 2.2 SC 1.3.2 | verify |
| FR2 | The required title MUST render at the caller-selected heading level without changing the component's visual type role. | Current implementation, tests, and consumer docs; WCAG 2.2 SC 1.3.1 and SC 2.4.6 | verify |
| FR3 | Null, undefined, boolean, and empty-string optional values MUST NOT create a wrapper, layout gap, or assistive-technology node; containers that are shallowly non-empty remain wrapped. | React's direct-child rendering semantics; established public optional-slot interface | verify |
| FR4 | The decorative icon wrapper MUST be absent when the slot is absent and hidden from assistive technology when rendered. | Current implementation and tests; WCAG 2.2 SC 1.1.1 | verify |
-| FR5 | Root DOM/data/ARIA/event props, ref, `className`, `style`, and `xstyle` MUST reach and compose on the status-region root. | `architecture:public-component-api` INV5–INV8 | verify |
+| FR5 | Root DOM/data/ARIA/event props, ref, `className`, `style`, and `xstyle` MUST reach and compose on the root. | `architecture:public-component-api` INV5–INV8 | verify |
| FR6 | Compact layout MUST reduce component spacing and stack the actions slot while preserving content order and root semantics. | Current implementation, tests, and consumer docs | verify |
### Allowed variation
@@ -109,7 +110,7 @@ intentional decision. A `current` contract contains no unresolved rows.
| State | Required invariant | Allowed variation |
| ----------------------------- | --------------------------------------------------------- | -------------------------------------- |
-| title only | status root and selected heading level remain present | message wording |
+| title only | root and selected heading level remain present | message wording |
| description | supporting text follows the title | text length and wrapping |
| decorative icon | visual precedes text and is hidden from assistive tech | artwork supplied by the caller |
| actions | caller controls follow the text group | one or more caller-owned controls |
@@ -120,7 +121,8 @@ intentional decision. A `current` contract contains no unresolved rows.
- **ORD1 — Root composition.** Component semantics and theme metadata combine
with component styles, then consumer `xstyle`, `className`, and `style` under
- the shared merge contract; component-owned `role="status"` remains authoritative.
+ the shared merge contract. The component sets no role, so a caller's `role`
+ reaches the root unchanged.
### Performance and resources
@@ -132,8 +134,14 @@ intentional decision. A `current` contract contains no unresolved rows.
- **AR1 — Heading semantics.** The title is a heading at the caller-selected level.
- **AR2 — Decorative visual.** The icon slot is hidden from assistive technology;
callers keep all necessary meaning in the title or description.
-- **AR3 — Status exposure.** The root exposes the empty message as a status region
- without moving focus; action controls keep their own names, roles, and behavior.
+- **AR3 — No live region; announced when it appears.** EmptyState adds no live
+ role or `aria-live` to the root and does not move focus. Rendered or changed
+ before the document finished loading (or while hydrating), it announces
+ nothing. When it appears, or its message changes, later, it announces its
+ message once through the shared polite channel (`spec:AST-086` FR2, FR11).
+ The message is the title and description, without content hidden from
+ assistive technology; action labels are not part of it. Action controls keep
+ their own names, roles, and behavior.
## Design relationships
@@ -170,7 +178,7 @@ No current family record owns EmptyState-specific behavior.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| -------------- | ------------------------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------------------------- | ------------------------- |
-| FR1–FR4, AR1–3 | focused DOM tests plus required exact-head accessibility evidence | title only, all slots, absent/shallow-empty slots | order, heading, status, or decorative treatment regresses | `audit:EmptyState/a11y` |
+| FR1–FR4, AR1–3 | focused DOM tests plus required exact-head accessibility evidence | title only, all slots, absent/shallow-empty slots | order, heading, live role, or decorative treatment regresses | `audit:EmptyState/a11y` |
| FR5, ORD1 | focused root composition tests plus shared API guards | DOM/data/event/style inputs, ref, root target | accepted input is dropped or component semantics/styles are replaced | `audit:EmptyState/api` |
| FR6 | compact target/DOM tests plus required exact-head rendered evidence | default and compact, wide and narrow | compact state, spacing, or action direction no longer applies | `audit:EmptyState/layout` |
| PR1 | source review | every render path | a retained resource appears without a named owner | `audit:EmptyState/code` |
diff --git a/packages/core/src/EmptyState/EmptyState.test.tsx b/packages/core/src/EmptyState/EmptyState.test.tsx
index e473394bc7..31eef2532d 100644
--- a/packages/core/src/EmptyState/EmptyState.test.tsx
+++ b/packages/core/src/EmptyState/EmptyState.test.tsx
@@ -117,14 +117,13 @@ describe('EmptyState', () => {
expect(divs).toHaveLength(2); // container + text group
});
- it('has role="status" on the container', () => {
- render(<EmptyState title="No results" />);
- expect(screen.getByRole('status')).toBeInTheDocument();
+ it('does not make the root a live region', () => {
+ const {container} = render(<EmptyState title="No results" />);
+ expect(container.querySelector('[role], [aria-live]')).toBeNull();
});
it('renders compact variant', () => {
render(<EmptyState title="No results" isCompact />);
- expect(screen.getByRole('status')).toBeInTheDocument();
expect(screen.getByText('No results')).toBeInTheDocument();
});
@@ -143,7 +142,7 @@ describe('EmptyState', () => {
const {container} = render(
<EmptyState title="No results" description="" icon={false} actions="" />,
);
- const root = screen.getByRole('status');
+ const root = container.firstElementChild as HTMLElement;
expect(root).toHaveTextContent('No results');
expect(root).toHaveTextContent(/^No results$/);
expect(root.children).toHaveLength(1);
@@ -153,7 +152,7 @@ describe('EmptyState', () => {
).toBeNull();
});
- it('composes root props and keeps component semantics authoritative', () => {
+ it('composes root props, including a caller role', () => {
const onClick = vi.fn();
const expectedXstyleClass = stylex.props(testStyles.root).className;
if (expectedXstyleClass == null) {
@@ -171,7 +170,7 @@ describe('EmptyState', () => {
/>,
);
- const root = screen.getByRole('status');
+ const root = screen.getByRole('region');
expect(root).toHaveClass('astryx-empty-state', 'consumer-class');
expect(root).toHaveClass(expectedXstyleClass);
expect(root).toHaveAttribute('data-owner', 'consumer');
@@ -188,10 +187,11 @@ describe('EmptyState', () => {
icon={<span data-testid="icon">Icon</span>}
actions={<button type="button">Retry</button>}
isCompact
+ data-testid="empty-state"
/>,
);
- const root = screen.getByRole('status');
+ const root = screen.getByTestId('empty-state');
expect(root).toHaveAttribute('data-variant', 'compact');
expect(root.children).toHaveLength(3);
expect(root.children[0]).toContainElement(screen.getByTestId('icon'));
diff --git a/packages/core/src/EmptyState/EmptyState.tsx b/packages/core/src/EmptyState/EmptyState.tsx
index 7675cf5043..667a4413d5 100644
--- a/packages/core/src/EmptyState/EmptyState.tsx
+++ b/packages/core/src/EmptyState/EmptyState.tsx
@@ -2,7 +2,7 @@
/**
* @file EmptyState.tsx
- * @input Uses React, HTMLAttributes
+ * @input Uses React, HTMLAttributes, AnnounceRenderedText
* @output Exports EmptyState component, EmptyStateProps type
* @position Core implementation; consumed by index.ts
*
@@ -23,6 +23,7 @@ import {
typeScaleVars,
} from '../theme/tokens.stylex';
import type {BaseProps} from '../BaseProps';
+import {AnnounceRenderedText} from '../hooks/AnnounceRenderedText';
import {isRenderable, mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
@@ -123,7 +124,9 @@ export interface EmptyStateProps extends BaseProps<HTMLDivElement> {
* An empty state placeholder for content areas with no data.
* Displays an icon or illustration, title, optional description, and action buttons.
*
- * Uses `role="status"` to announce content to screen readers.
+ * Not a live region. Its title and description are announced once when they
+ * appear or change after the page loaded, never when the page first renders
+ * with them (`spec:AST-086` FR2).
* Styles use Astryx theme tokens via StyleX. Wrap your app in <Theme> to apply a theme.
*
* @example
@@ -158,7 +161,6 @@ export function EmptyState({
<div
ref={ref}
{...props}
- role="status"
{...mergeProps(
themeProps('empty-state', {variant: isCompact ? 'compact' : null}),
stylex.props(
@@ -170,7 +172,7 @@ export function EmptyState({
style,
)}>
{isRenderable(icon) && <div aria-hidden="true">{icon}</div>}
- <div {...stylex.props(styles.textGroup)}>
+ <AnnounceRenderedText {...stylex.props(styles.textGroup)}>
{createElement(
HeadingTag,
mergeProps(
@@ -195,7 +197,7 @@ export function EmptyState({
{description}
</div>
)}
- </div>
+ </AnnounceRenderedText>
{isRenderable(actions) && (
<div
{...stylex.props(styles.actions, isCompact && styles.actionsCompact)}>
diff --git a/packages/core/src/hooks/AnnounceRenderedText.tsx b/packages/core/src/hooks/AnnounceRenderedText.tsx
new file mode 100644
index 0000000000..d646727e08
--- /dev/null
+++ b/packages/core/src/hooks/AnnounceRenderedText.tsx
@@ -0,0 +1,27 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file AnnounceRenderedText.tsx
+ * @input Uses React, useAnnounceRenderedText
+ * @output Exports AnnounceRenderedText (internal; not re-exported from
+ * hooks/index.ts, so it ships no public API without `spec:AST-002`)
+ * @position Internal client island that lets a presentational, server-safe
+ * component announce its own content; rendered by EmptyState around its
+ * message. On the server it only renders its `div`: effects never run there.
+ */
+
+import {useRef, type HTMLAttributes} from 'react';
+import {useAnnounceRenderedText} from './useAnnounceRenderedText';
+
+/**
+ * A `div` whose rendered text is announced once through the shared polite
+ * live region when it appears or changes after the page loaded, and never for
+ * text present when the page first rendered (`spec:AST-086` FR11).
+ */
+export function AnnounceRenderedText(props: HTMLAttributes<HTMLDivElement>) {
+ const ref = useRef<HTMLDivElement>(null);
+ useAnnounceRenderedText(ref, true, '', {skipFirstRender: true});
+ return <div ref={ref} {...props} />;
+}
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.ts b/packages/core/src/hooks/useAnnounceRenderedText.ts
index bf4ec24ed6..c7b548ecba 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.ts
+++ b/packages/core/src/hooks/useAnnounceRenderedText.ts
@@ -32,7 +32,7 @@
* (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,
+ * Content hidden with `aria-hidden` or `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.
@@ -43,17 +43,41 @@
* admission. Import it by path from inside the package.
*/
-import {useEffect, useRef, type RefObject} from 'react';
+import {useEffect, useRef, useState, type RefObject} from 'react';
import {useAnnounce} from './useAnnounce';
+import {useIsHydrating} from './useIsHydrating';
+
+const LIVE_CONTAINER =
+ '[role="log"], [role="status"], [role="alert"], [aria-live="polite"], [aria-live="assertive"]';
+const HIDDEN = '[aria-hidden="true"], [hidden]';
+const BLOCKS = 'p, div, li, br, h1, h2, h3, h4, h5, h6';
+
+/** Each child element's rendered text as its own block, joined by spaces. */
+function blockText(element: HTMLElement): string {
+ return Array.from(element.children)
+ .filter(child => !child.matches(HIDDEN))
+ .map(child => renderedText(child as HTMLElement))
+ .filter(part => part !== '')
+ .join(' ');
+}
+
+export interface AnnounceRenderedTextOptions {
+ /**
+ * Text present or changed while the document loads or hydrates is silent;
+ * text that appears or changes later is announced once (`spec:AST-086`
+ * FR11). A mounted live container speaks its own content (FR4); each child is
+ * a block; a reveal without a re-render is read on the next render (FR13).
+ */
+ skipFirstRender?: boolean;
+}
/** The rendered text an assistive technology would read from `element`. */
-function renderedText(element: HTMLElement): string {
+export 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();
- }
+ copy.querySelectorAll(HIDDEN).forEach(node => node.remove());
+ copy.querySelectorAll(BLOCKS).forEach(node => node.after(' ')); // blocks apart
return (copy.textContent ?? '').replace(/\s+/g, ' ').trim();
}
@@ -81,9 +105,17 @@ export function useAnnounceRenderedText(
ref: RefObject<HTMLElement | null>,
isShown: boolean,
occasion: string,
+ {skipFirstRender = false}: AnnounceRenderedTextOptions = {},
): void {
const announce = useAnnounce();
const spokenRef = useRef<string | null>(null);
+ const isHydrating = useIsHydrating();
+ // Captured once: an owner rendered before the document finished loading, or
+ // hydrated from server HTML, is part of the page the person arrived at.
+ const [renderedWithPage] = useState(
+ () => isHydrating || document.readyState !== 'complete',
+ );
+ const isFirstRunRef = useRef(true);
// 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
@@ -91,15 +123,24 @@ export function useAnnounceRenderedText(
// one element's text per render is cheap, and the dedupe below makes every
// render after the first a no-op.
useEffect(() => {
- if (!isShown) {
+ const isFirstRun = isFirstRunRef.current;
+ isFirstRunRef.current = false;
+ const element = ref.current;
+ if (
+ !isShown ||
+ element?.closest(HIDDEN) ||
+ element?.checkVisibility?.() === false
+ ) {
spokenRef.current = null;
return;
}
- const element = ref.current;
if (!element) {
return;
}
- const text = renderedText(element);
+ if (skipFirstRender && element.parentElement?.closest(LIVE_CONTAINER)) {
+ return;
+ }
+ const text = skipFirstRender ? blockText(element) : renderedText(element);
if (text === '') {
// Nothing readable on screen either, so there is no announcement that
// would match what the sighted user is seeing.
@@ -110,6 +151,12 @@ export function useAnnounceRenderedText(
return;
}
spokenRef.current = spoken;
+ const isPageLoad =
+ (isFirstRun && renderedWithPage) || document.readyState !== 'complete';
+ if (skipFirstRender && isPageLoad) {
+ // Part of the page the person arrived at: remember it, say nothing.
+ return;
+ }
announce(text);
});
}
diff --git a/packages/core/src/serverSafeComponents.test.ts b/packages/core/src/serverSafeComponents.test.ts
index 71956d2a95..9ec19bc0ff 100644
--- a/packages/core/src/serverSafeComponents.test.ts
+++ b/packages/core/src/serverSafeComponents.test.ts
@@ -71,6 +71,13 @@ const CLIENT_APIS = new Set([
const EXTENSIONS = ['.tsx', '.ts', '.mjs', '.js', '.jsx'];
+/**
+ * `'use client'` modules a server-safe component may render as a client
+ * island: each does nothing on the server, so the component's server output
+ * is unchanged. The walk stops at them.
+ */
+const CLIENT_ISLANDS = new Set(['hooks/AnnounceRenderedText.tsx']);
+
const isSourceFile = (name: string) =>
/\.[jt]sx?$/.test(name) &&
!/\.(test|test-violations|stories|doc|perf)\./.test(name) &&
@@ -357,6 +364,9 @@ function findClientSurfaces(
continue;
}
visited.add(key);
+ if (CLIENT_ISLANDS.has(relative(SRC_DIR, file))) {
+ continue;
+ }
const info = parseModule(file);
const chain = via.join(' -> ');
diff --git a/packages/lab/src/Comments/Comments.test.tsx b/packages/lab/src/Comments/Comments.test.tsx
index 66b36cd6f4..f40ae76966 100644
--- a/packages/lab/src/Comments/Comments.test.tsx
+++ b/packages/lab/src/Comments/Comments.test.tsx
@@ -82,6 +82,12 @@ import type {
CommentUser,
} from './types';
+// The page's shared live regions are not the component's error Banner.
+const errorBanner = () =>
+ screen
+ .queryAllByRole('alert')
+ .find(element => !element.hasAttribute('data-astryx-live-region'));
+
const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};
const OTHER: CommentUser = {id: 'maya', name: 'Maya Chen'};
const AGENT: CommentUser = {
@@ -900,12 +906,12 @@ describe('Comments threads', () => {
}),
);
await flush();
- const banner = screen.getByRole('alert');
+ const banner = errorBanner()!;
expect(banner.textContent).toContain("Your reaction couldn't be saved.");
await click(within(banner).getByRole('button', {name: 'Retry'}));
await flush();
expect(onReact).toHaveBeenCalledTimes(2);
- expect(screen.queryByRole('alert')).toBeNull();
+ expect(errorBanner()).toBeUndefined();
});
it('copies a link to the comment', async () => {
@@ -999,7 +1005,7 @@ describe('Comments threads', () => {
/>
</Sized>,
);
- const banner = screen.getByRole('alert');
+ const banner = errorBanner()!;
expect(banner.textContent).toContain("Couldn't post this comment.");
await click(within(banner).getByRole('button', {name: 'Retry'}));
await flush();
@@ -1022,7 +1028,7 @@ describe('Comments threads', () => {
);
await click(screen.getByRole('button', {name: 'Load earlier comments'}));
await flush();
- const banner = screen.getByRole('alert');
+ const banner = errorBanner()!;
expect(banner.textContent).toContain("Earlier comments couldn't load");
await click(within(banner).getByRole('button', {name: 'Retry'}));
await flush();
diff --git a/packages/lab/src/ListInput/ListInput.test.tsx b/packages/lab/src/ListInput/ListInput.test.tsx
index 2829fe8fd0..311a39016f 100644
--- a/packages/lab/src/ListInput/ListInput.test.tsx
+++ b/packages/lab/src/ListInput/ListInput.test.tsx
@@ -660,10 +660,13 @@ describe('ListInput', () => {
expect(animate).not.toHaveBeenCalled();
expect(screen.queryByDisplayValue('Ada')).not.toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Add guest'})).toHaveFocus();
+ // The removal and the empty state that appears join in one frame (FR9).
await waitFor(() => {
expect(
Array.from(document.querySelectorAll('[aria-live="polite"]')).some(
- node => node.textContent === 'Removed guest 1.',
+ node =>
+ node.textContent ===
+ 'Removed guest 1. No guests yet Add a guest to get started.',
),
).toBe(true);
});
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
index 38cc47ce9c..4b4985486a 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
@@ -112,8 +112,10 @@ beforeEach(() => {
window.scrollTo = vi.fn();
vi.stubGlobal(
'requestAnimationFrame',
+ // Next microtask, not synchronously: a real frame never runs before
+ // requestAnimationFrame returns, and callers may rely on its id.
vi.fn((cb: FrameRequestCallback) => {
- cb(0);
+ queueMicrotask(() => cb(0));
return 1;
}),
);
@@ -309,7 +311,7 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
const title = await screen.findByRole('heading', {
name: 'No results found',
});
- const emptyState = title.closest('[role="status"]');
+ const emptyState = title.closest('.astryx-empty-state');
expect(emptyState).toHaveTextContent('Try a different search.');
expect(emptyState?.querySelector('.astryx-icon')).toHaveAttribute(
'data-size',