Skip to content

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

TypeScript

fix(ChatComposer): the status bar announces through the shared own-content module (#8363)

Cindy Zhang5b9e43bd04bd
diff --git a/.changeset/chatcomposer-status-own-content.md b/.changeset/chatcomposer-status-own-content.md
new file mode 100644
index 0000000000..94615f84fb
--- /dev/null
+++ b/.changeset/chatcomposer-status-own-content.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `ChatComposer`'s status bar announces through the shared own-content announcement module (`spec:AST-086` FR11–FR13). It still announces errors assertively and warnings politely, once per occasion, but a status that is already showing while the page loads is no longer announced, and it speaks the bar's rendered text without the decorative icon.
+
+@cixzhang
diff --git a/packages/core/src/Chat/ChatComposer.test.tsx b/packages/core/src/Chat/ChatComposer.test.tsx
index 99c03e9720..75e36e51f3 100644
--- a/packages/core/src/Chat/ChatComposer.test.tsx
+++ b/packages/core/src/Chat/ChatComposer.test.tsx
@@ -307,4 +307,26 @@ describe('ChatComposer status announcement (spec:AST-086)', () => {
render(composer({type: 'warning'}));
expect(announce).not.toHaveBeenCalled();
});
+
+ it('is silent for a status shown while the page loads, then announces a later one (FR11)', () => {
+ let readyState: DocumentReadyState = 'loading';
+ const spy = vi
+ .spyOn(document, 'readyState', 'get')
+ .mockImplementation(() => readyState);
+ try {
+ const {rerender} = render(composer({type: 'error', message: 'Offline'}));
+ expect(announce).not.toHaveBeenCalled();
+ readyState = 'complete';
+ rerender(composer({type: 'error', message: 'Send failed'}));
+ expect(announce.mock.calls).toEqual([['Send failed', 'assertive']]);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('announces only the message, not the decorative icon (FR12)', () => {
+ const {rerender} = render(composer());
+ rerender(composer({type: 'warning', message: 'Offline'}));
+ expect(announce.mock.calls).toEqual([['Offline', 'polite']]);
+ });
});
diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsx
index 8d2fb40783..a2e106e7ca 100644
--- a/packages/core/src/Chat/ChatComposer.tsx
+++ b/packages/core/src/Chat/ChatComposer.tsx
@@ -26,7 +26,6 @@
import React, {
useState,
useCallback,
- useEffect,
useRef,
useMemo,
type ReactNode,
@@ -54,7 +53,7 @@ import type {ChatComposerInputControl} from './ChatContext';
import {ChatSendButton} from './ChatSendButton';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
-import {useAnnounce} from '../hooks/useAnnounce';
+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {
getInteractionModality,
@@ -458,30 +457,25 @@ export function ChatComposer(props: ChatComposerProps) {
);
// The status bar mounts together with its message, and a live region born
- // holding its text is not reliably announced, so the message goes through
- // the shared channel instead: errors assertively, warnings politely
- // (spec:AST-086 FR2, FR5). The ref keeps a rerender or a StrictMode effect
- // replay from repeating it; clearing the status re-arms it, so the same
- // message shown again is a new occasion (FR6).
- const announce = useAnnounce();
- const statusType = status?.type;
- const statusMessage = status?.message;
- const announcedStatusRef = useRef<string | null>(null);
- useEffect(() => {
- if (!statusMessage) {
- announcedStatusRef.current = null;
- return;
- }
- const occasion = `${statusType}\u0000${statusMessage}`;
- if (announcedStatusRef.current === occasion) {
- return;
- }
- announcedStatusRef.current = occasion;
- announce(statusMessage, statusType === 'error' ? 'assertive' : 'polite');
- }, [announce, statusType, statusMessage]);
+ // holding its text is not reliably announced, so the shared own-content
+ // module announces what the bar renders: errors assertively, warnings
+ // politely, once per occasion, silent for a status already shown when the
+ // page loads (spec:AST-086 FR2, FR5, FR6, FR11; react-component-runtime
+ // INV10). Changing the status type is a new occasion; clearing it re-arms.
+ const statusRef = useRef<HTMLDivElement>(null);
+ useAnnounceRenderedText(
+ statusRef,
+ Boolean(status?.message),
+ status?.type ?? '',
+ {
+ skipFirstRender: true,
+ politeness: status?.type === 'error' ? 'assertive' : 'polite',
+ },
+ );
const statusEl = status ? (
<div
+ ref={statusRef}
{...stylex.props(
styles.statusBar,
statusPosition === 'top' ? styles.statusTop : styles.statusBottom,
diff --git a/packages/core/src/EmptyState/EmptyState.announce.test.tsx b/packages/core/src/EmptyState/EmptyState.announce.test.tsx
index 34fa50c662..89e13a6dcc 100644
--- a/packages/core/src/EmptyState/EmptyState.announce.test.tsx
+++ b/packages/core/src/EmptyState/EmptyState.announce.test.tsx
@@ -10,6 +10,7 @@
import {act, StrictMode, useState} from 'react';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {createRoot, hydrateRoot} from 'react-dom/client';
+import {createPortal} from 'react-dom';
import {renderToString} from 'react-dom/server';
import {renderedText} from '../hooks/useAnnounceRenderedText';
@@ -103,6 +104,32 @@ describe('EmptyState announcement (spec:AST-086 FR2)', () => {
await act(async () => root.unmount());
});
+ it('announces when it appears later in a same-origin iframe it is portaled into', async () => {
+ const {EmptyState, paint} = await importEmptyState();
+ paint();
+ const frame = document.body.appendChild(document.createElement('iframe'));
+ const frameBody = frame.contentDocument!.body;
+ let showEmpty!: () => void;
+ function Results() {
+ const [isEmpty, setIsEmpty] = useState(false);
+ showEmpty = () => setIsEmpty(true);
+ return isEmpty
+ ? createPortal(
+ <EmptyState title="No results" description="Try another search." />,
+ frameBody,
+ )
+ : null;
+ }
+ const polite = recordPolite();
+ const root = mount();
+ await act(async () => root.render(<Results />));
+ 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();
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
new file mode 100644
index 0000000000..f4a8c6a109
--- /dev/null
+++ b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
@@ -0,0 +1,204 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useAnnounceRenderedText.adopters.test.tsx
+ * @input Every core component that announces its own rendered content, with
+ * the shared own-content module replaced by a recorder
+ * @output architecture:react-component-runtime INV10 test: each adopter hands
+ * its own-content announcement to the shared module and announces none of it
+ * itself
+ * @position Shared adopter test for the own-content announcement module
+ *
+ * With the module replaced by a recorder that never announces, an adopter that
+ * still announced its own content would be holding an Effect, observer, timer
+ * or listener of its own for it, which INV10 rules out. The registry check at
+ * the end keeps this list in step with every file that imports the module, so
+ * a new adopter cannot skip the test.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {useEffect, useRef, type HTMLAttributes, type RefObject} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {fireEvent, render, screen, waitFor} from '@testing-library/react';
+
+interface ModuleCall {
+ isShown: boolean;
+ text: string;
+}
+
+const calls: ModuleCall[] = [];
+const announce = vi.hoisted(() => vi.fn());
+
+vi.mock('./useAnnounceRenderedText', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useAnnounceRenderedText: (
+ ref: RefObject<HTMLElement | null>,
+ isShown: boolean,
+ ) => {
+ // Read after commit, the way the real module does.
+ useEffect(() => {
+ calls.push({isShown, text: ref.current?.textContent ?? ''});
+ });
+ },
+}));
+vi.mock('./AnnounceRenderedText', () => ({
+ AnnounceRenderedText: (props: HTMLAttributes<HTMLDivElement>) => {
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ calls.push({isShown: true, text: ref.current?.textContent ?? ''});
+ });
+ return <div ref={ref} {...props} />;
+ },
+}));
+vi.mock('./useAnnounce', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useAnnounce: () => announce,
+}));
+
+const {EmptyState} = await import('../EmptyState');
+const {ChatComposer} = await import('../Chat');
+const {Selector} = await import('../Selector');
+const {MultiSelector} = await import('../MultiSelector');
+const {CommandPalette} = await import('../CommandPalette');
+const {BaseTypeahead} = await import('../Typeahead/BaseTypeahead');
+const {createStaticSource} = await import('../Typeahead/createStaticSource');
+
+const source = createStaticSource([{id: 'apple', label: 'Apple'}]);
+
+beforeEach(() => {
+ calls.length = 0;
+ announce.mockClear();
+ // jsdom does not implement the modal dialog methods CommandPalette uses.
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+/**
+ * The adopter showed `text` through the module, and announced none of it
+ * through its own channel calls.
+ */
+async function expectDelegated(text: string) {
+ await waitFor(() =>
+ expect(calls.some(call => call.isShown && call.text.includes(text))).toBe(
+ true,
+ ),
+ );
+ const own = announce.mock.calls.filter(([message]) =>
+ String(message).includes(text),
+ );
+ expect(own).toEqual([]);
+}
+
+/** Each adopter, shown in the state where its own content appears. */
+const ADOPTERS: Record<string, () => Promise<void>> = {
+ 'EmptyState/EmptyState.tsx': async () => {
+ render(<EmptyState title="Nothing here" description="Add an item" />);
+ await expectDelegated('Nothing here');
+ },
+ 'Chat/ChatComposer.tsx': async () => {
+ const composer = (status?: {
+ type: 'error' | 'warning';
+ message: string;
+ }) => <ChatComposer onSubmit={() => {}} input={<div />} status={status} />;
+ const {rerender} = render(composer());
+ rerender(composer({type: 'error', message: 'Send failed'}));
+ await expectDelegated('Send failed');
+ rerender(composer({type: 'warning', message: 'Offline'}));
+ await expectDelegated('Offline');
+ },
+ 'Selector/Selector.tsx': async () => {
+ render(
+ <Selector
+ label="Fruit"
+ options={[] as string[]}
+ value=""
+ onChange={() => {}}
+ />,
+ );
+ fireEvent.click(screen.getByRole('combobox'));
+ await expectDelegated('No options');
+ },
+ 'MultiSelector/MultiSelector.tsx': async () => {
+ render(
+ <MultiSelector
+ label="Fruits"
+ options={[] as string[]}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ fireEvent.click(screen.getByRole('combobox'));
+ await expectDelegated('No options');
+ },
+ 'CommandPalette/CommandPalette.tsx': async () => {
+ render(
+ <CommandPalette isOpen onOpenChange={() => {}} searchSource={source} />,
+ );
+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});
+ await expectDelegated('No results');
+ },
+ 'Typeahead/BaseTypeahead.tsx': async () => {
+ render(
+ <BaseTypeahead
+ searchSource={source}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});
+ await expectDelegated('No results found');
+ },
+};
+
+describe('own-content announcement adopters (react-component-runtime INV10)', () => {
+ it.each(Object.entries(ADOPTERS))(
+ '%s hands its own content to the shared module and announces none of it itself',
+ async (_file, run) => {
+ await run();
+ },
+ );
+
+ it('covers every core file that imports the module', () => {
+ const src = path.resolve(import.meta.dirname, '..');
+ const importers: string[] = [];
+ const walk = (dir: string) => {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full);
+ } else if (
+ /\.tsx?$/.test(entry.name) &&
+ !/\.(test|spec|stories)\.tsx?$/.test(entry.name) &&
+ /from '[./]*(hooks\/)?(useAnnounceRenderedText|AnnounceRenderedText)'/.test(
+ fs.readFileSync(full, 'utf8'),
+ )
+ ) {
+ importers.push(path.relative(src, full));
+ }
+ }
+ };
+ walk(src);
+ const modules = [
+ 'hooks/useAnnounceRenderedText.ts',
+ 'hooks/AnnounceRenderedText.tsx',
+ ];
+ expect(
+ importers
+ .filter(file => !modules.includes(file))
+ .map(file => file.split(path.sep).join('/'))
+ .sort(),
+ ).toEqual(Object.keys(ADOPTERS).sort());
+ });
+});
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.ts b/packages/core/src/hooks/useAnnounceRenderedText.ts
index c7b548ecba..c59117114c 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.ts
+++ b/packages/core/src/hooks/useAnnounceRenderedText.ts
@@ -44,7 +44,7 @@
*/
import {useEffect, useRef, useState, type RefObject} from 'react';
-import {useAnnounce} from './useAnnounce';
+import {useAnnounce, type AnnouncePoliteness} from './useAnnounce';
import {useIsHydrating} from './useIsHydrating';
const LIVE_CONTAINER =
@@ -52,11 +52,26 @@ const LIVE_CONTAINER =
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. */
+/**
+ * Each child element's rendered text as its own block, joined by spaces. Text
+ * placed directly in the element, beside its child elements, counts as a block
+ * too (a status bar is an icon followed by its bare message).
+ */
function blockText(element: HTMLElement): string {
- return Array.from(element.children)
- .filter(child => !child.matches(HIDDEN))
- .map(child => renderedText(child as HTMLElement))
+ return Array.from(element.childNodes)
+ .map(child => {
+ if (child.nodeType === Node.TEXT_NODE) {
+ return (child.textContent ?? '').replace(/\s+/g, ' ').trim();
+ }
+ // By node type, not `instanceof`: an element from another document's
+ // window (a portal into a same-origin iframe) fails this window's
+ // constructor checks.
+ if (child.nodeType === Node.ELEMENT_NODE) {
+ const part = child as HTMLElement;
+ return part.matches(HIDDEN) ? '' : renderedText(part);
+ }
+ return '';
+ })
.filter(part => part !== '')
.join(' ');
}
@@ -69,6 +84,11 @@ export interface AnnounceRenderedTextOptions {
* a block; a reveal without a re-render is read on the next render (FR13).
*/
skipFirstRender?: boolean;
+ /**
+ * The channel's urgency: errors and time-critical failures are assertive,
+ * every other message polite (`spec:AST-086` FR5). Defaults to polite.
+ */
+ politeness?: AnnouncePoliteness;
}
/** The rendered text an assistive technology would read from `element`. */
@@ -105,7 +125,10 @@ export function useAnnounceRenderedText(
ref: RefObject<HTMLElement | null>,
isShown: boolean,
occasion: string,
- {skipFirstRender = false}: AnnounceRenderedTextOptions = {},
+ {
+ skipFirstRender = false,
+ politeness = 'polite',
+ }: AnnounceRenderedTextOptions = {},
): void {
const announce = useAnnounce();
const spokenRef = useRef<string | null>(null);
@@ -157,6 +180,6 @@ export function useAnnounceRenderedText(
// Part of the page the person arrived at: remember it, say nothing.
return;
}
- announce(text);
+ announce(text, politeness);
});
}