Skip to content

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

TypeScript

fix(ChatTypingIndicator): announce through the shared channel, not a live region born with its text (#7867)

Cindy Zhang8a801f70a48e
diff --git a/apps/storybook/stories/StatusMessageA11y.stories.tsx b/apps/storybook/stories/StatusMessageA11y.stories.tsx
index 682bbf201a..809cf85bd1 100644
--- a/apps/storybook/stories/StatusMessageA11y.stories.tsx
+++ b/apps/storybook/stories/StatusMessageA11y.stories.tsx
@@ -89,4 +89,3 @@ export const ProgressMarkFocusedUpdate = coreStory(
export const ChatTypingEmptyToMessage = labStory(
'chat-typing-empty-to-message',
);
-export const ChatTypingNameMounted = labStory('chat-typing-name-mounted');
diff --git a/packages/lab/src/Chat/ChatTypingIndicator.doc.mjs b/packages/lab/src/Chat/ChatTypingIndicator.doc.mjs
index f9d3912261..b584b88b87 100644
--- a/packages/lab/src/Chat/ChatTypingIndicator.doc.mjs
+++ b/packages/lab/src/Chat/ChatTypingIndicator.doc.mjs
@@ -8,7 +8,7 @@ export const docs = {
group: 'Chat',
category: 'Chat',
displayName: 'Chat Typing Indicator',
- description: 'Animated three-dot typing hint with a localized, grammar-aware label: "Ana is typing...", "Ana and Ben are typing...", or "Ana and 2 others are typing...". Dots bounce with staggered stylex.keyframes delays, disabled under prefers-reduced-motion; the label is announced politely via role="status".',
+ description: 'Animated three-dot typing hint with a localized, grammar-aware label: "Ana is typing...", "Ana and Ben are typing...", or "Ana and 2 others are typing...". Dots bounce with staggered stylex.keyframes delays, disabled under prefers-reduced-motion. Each new label is announced once, politely, through the shared announcement channel (useAnnounce); inside a chat log the log announces it instead. The indicator itself carries no live role, so it can mount conditionally without being skipped or heard twice.',
props: [
{
name: 'names',
@@ -21,7 +21,7 @@ export const docs = {
export const docsZh = {
name: 'ChatTypingIndicator',
displayName: 'Chat Typing Indicator',
- description: '带语法感知标签的三点跳动输入提示:"Ana is typing..."、"Ana and Ben are typing..." 或 "Ana and 2 others are typing..."。圆点用 stylex.keyframes 交错跳动,prefers-reduced-motion 下禁用;标签通过 role="status" 礼貌播报。',
+ description: '带语法感知标签的三点跳动输入提示:"Ana is typing..."、"Ana and Ben are typing..." 或 "Ana and 2 others are typing..."。圆点用 stylex.keyframes 交错跳动,prefers-reduced-motion 下禁用。每个新标签通过共享播报通道(useAnnounce)礼貌播报一次;位于聊天记录(role="log")内时由记录负责播报。指示器本身不带 live 角色,因此可按条件挂载,既不会被跳过,也不会重复播报。',
propDescriptions: {
names: '正在输入的人名。一个名字渲染 "is typing",两个渲染双名,更多折叠为 "and N others"。语句取自 i18n 词条,人名由 Intl.ListFormat 按当前语言拼接,因此措辞与连接词随语言而变。省略或为空时仅渲染动画圆点。',
},
@@ -30,7 +30,7 @@ export const docsZh = {
export const docsDense = {
name: 'ChatTypingIndicator',
displayName: 'Chat Typing Indicator',
- description: 'bouncing three-dot typing hint; label grammar 1/2/N names; reduced-motion safe keyframes; role=status polite announce; dots-only when names empty',
+ description: 'bouncing three-dot typing hint; label grammar 1/2/N names; reduced-motion safe keyframes; announces each new label once via useAnnounce (polite), or leaves it to an enclosing role=log; no live role on the element; dots-only when names empty',
propDescriptions: {
names:
"string[]; 1='X is typing', 2='X and Y', 3+='X and N others'; phrases from i18n catalog, names joined by Intl.ListFormat; empty=dots only",
diff --git a/packages/lab/src/Chat/ChatTypingIndicator.test.tsx b/packages/lab/src/Chat/ChatTypingIndicator.test.tsx
index 04fdd78235..f38f7f5af8 100644
--- a/packages/lab/src/Chat/ChatTypingIndicator.test.tsx
+++ b/packages/lab/src/Chat/ChatTypingIndicator.test.tsx
@@ -1,10 +1,21 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
+import {StrictMode} from 'react';
+import {beforeEach, describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import {ChatTypingIndicator} from './ChatTypingIndicator';
import {InternationalizationProvider} from '@astryxdesign/core/i18n';
+const announce = vi.fn();
+vi.mock('@astryxdesign/core/hooks', async importOriginal => ({
+ ...(await importOriginal<typeof import('@astryxdesign/core/hooks')>()),
+ useAnnounce: () => announce,
+}));
+
+beforeEach(() => {
+ announce.mockClear();
+});
+
describe('ChatTypingIndicator', () => {
it('renders "X is typing…" for one name', () => {
render(<ChatTypingIndicator names={['Ana']} />);
@@ -84,4 +95,58 @@ describe('ChatTypingIndicator', () => {
'astryx-chat-typing-indicator',
);
});
+
+ describe('status announcement (spec:AST-086)', () => {
+ it('mounts with its label but carries no live role (FR2)', () => {
+ const {container} = render(<ChatTypingIndicator names={['Ana']} />);
+ const root = container.firstElementChild as HTMLElement;
+ expect(root).toHaveTextContent('Ana is typing…');
+ expect(root).not.toHaveAttribute('role');
+ expect(root).not.toHaveAttribute('aria-live');
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+
+ it('announces a mounted label once through the polite channel, even under StrictMode (FR2, FR6)', () => {
+ const {rerender} = render(
+ <StrictMode>
+ <ChatTypingIndicator names={['Ana']} />
+ </StrictMode>,
+ );
+ rerender(
+ <StrictMode>
+ <ChatTypingIndicator names={['Ana']} />
+ </StrictMode>,
+ );
+ expect(announce.mock.calls).toEqual([['Ana is typing…', 'polite']]);
+ });
+
+ it('announces each new label, nothing on clear, and the same people again as a new occasion (FR6)', () => {
+ const {rerender} = render(<ChatTypingIndicator names={[]} />);
+ expect(announce).not.toHaveBeenCalled();
+ rerender(<ChatTypingIndicator names={['Ana']} />);
+ rerender(<ChatTypingIndicator names={['Ana', 'Ben']} />);
+ rerender(<ChatTypingIndicator names={[]} />);
+ rerender(<ChatTypingIndicator names={['Ana', 'Ben']} />);
+ expect(announce.mock.calls).toEqual([
+ ['Ana is typing…', 'polite'],
+ ['Ana and Ben are typing…', 'polite'],
+ ['Ana and Ben are typing…', 'polite'],
+ ]);
+ });
+
+ it('leaves delivery to an enclosing chat log (FR4)', () => {
+ const {rerender} = render(
+ <div role="log">
+ <ChatTypingIndicator names={['Ana']} />
+ </div>,
+ );
+ rerender(
+ <div role="log">
+ <ChatTypingIndicator names={['Ana', 'Ben']} />
+ </div>,
+ );
+ expect(announce).not.toHaveBeenCalled();
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+ });
});
diff --git a/packages/lab/src/Chat/ChatTypingIndicator.tsx b/packages/lab/src/Chat/ChatTypingIndicator.tsx
index a0622c526b..95c4249b8d 100644
--- a/packages/lab/src/Chat/ChatTypingIndicator.tsx
+++ b/packages/lab/src/Chat/ChatTypingIndicator.tsx
@@ -10,8 +10,10 @@
*
* Three staggered bouncing dots (stylex.keyframes, reduced-motion safe)
* with a grammar-aware label: "Ana is typing…", "Ana and Ben are typing…",
- * or "Ana and 2 others are typing…". Announced politely via role="status".
- * Renders dots only when no names are provided.
+ * or "Ana and 2 others are typing…". The label is announced once per change
+ * through the shared polite channel (`useAnnounce`), or left to an enclosing
+ * live container such as a chat log; the element itself carries no live role
+ * (spec:AST-086 FR2, FR4). Renders dots only when no names are provided.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/lab/src/Chat/index.ts (exports)
@@ -19,7 +21,7 @@
* - /apps/storybook/stories/ChatAdditions.stories.tsx (examples)
*/
-import {useMemo} from 'react';
+import {useEffect, useMemo, useRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -30,7 +32,8 @@ import {
typeScaleVars,
} from '@astryxdesign/core/theme/tokens.stylex';
import type {BaseProps} from '@astryxdesign/core';
-import {mergeProps} from '@astryxdesign/core/utils';
+import {mergeProps, mergeRefs} from '@astryxdesign/core/utils';
+import {useAnnounce} from '@astryxdesign/core/hooks';
import {themeProps} from '@astryxdesign/core/utils';
import {useLocale, useTranslator} from '@astryxdesign/core/i18n';
import type {TranslatorFn} from '@astryxdesign/core/i18n';
@@ -132,6 +135,14 @@ function typingLabel(
});
}
+/**
+ * An enclosing live container (a chat transcript's role="log", or any element
+ * the page made live) already delivers content added inside it, so the
+ * indicator must not announce the same words again (spec:AST-086 FR4).
+ */
+const LIVE_CONTAINER_SELECTOR =
+ '[role="log"], [role="status"], [role="alert"], [aria-live="polite"], [aria-live="assertive"]';
+
// =============================================================================
// Component
// =============================================================================
@@ -140,8 +151,9 @@ function typingLabel(
* Animated three-dot typing hint with a name-aware label.
*
* The dots bounce with staggered delays (disabled under
- * prefers-reduced-motion) and the label is announced politely to
- * screen readers via role="status".
+ * prefers-reduced-motion). Each new label is announced politely to screen
+ * readers through the shared announcement channel, unless an enclosing live
+ * container such as a chat log delivers it.
*
* @example
* ```
@@ -164,11 +176,33 @@ export function ChatTypingIndicator({
[locale],
);
const label = typingLabel(names, t, listFormat);
+
+ const rootRef = useRef<HTMLDivElement>(null);
+ const mergedRef = useMemo(() => mergeRefs(rootRef, ref), [ref]);
+ const announce = useAnnounce();
+ // The label last announced, so a rerender or a StrictMode effect replay does
+ // not repeat it; cleared when nobody is typing, so the same people starting
+ // again is a new occasion (spec:AST-086 FR6).
+ const announcedLabelRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (label == null) {
+ announcedLabelRef.current = null;
+ return;
+ }
+ if (announcedLabelRef.current === label) {
+ return;
+ }
+ announcedLabelRef.current = label;
+ const isInsideLiveContainer =
+ rootRef.current?.parentElement?.closest(LIVE_CONTAINER_SELECTOR) != null;
+ if (!isInsideLiveContainer) {
+ announce(label, 'polite');
+ }
+ }, [announce, label]);
+
return (
<div
- ref={ref}
- role="status"
- aria-live="polite"
+ ref={mergedRef}
data-testid={testId}
{...mergeProps(
themeProps('chat-typing-indicator'),
diff --git a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders.tsx b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders.tsx
index 9aff973d8c..e17612fb8d 100644
--- a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders.tsx
+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders.tsx
@@ -4,7 +4,8 @@
/** Shared jsdom and Storybook renderings for ChatTypingIndicator status states. */
-import {useState, type ReactElement} from 'react';
+import {useEffect, useState, type ReactElement} from 'react';
+import {useAnnounce} from '@astryxdesign/core/hooks';
import {ChatTypingIndicator} from '../ChatTypingIndicator';
import type {ChatTypingStatusStateId} from './ChatTypingIndicator.a11y.states';
@@ -27,12 +28,35 @@ function TransitionButton({
);
}
-function TypingHarness({startsNamed}: {startsNamed: boolean}) {
- const initial = startsNamed ? ['Ana'] : [];
- const [names, setNames] = useState<string[]>(initial);
+/**
+ * Establishes the singleton polite channel the indicator announces through,
+ * then clears the seed, so the binding inspects the pre-existing empty region.
+ */
+function PrimePoliteChannel() {
+ const announce = useAnnounce();
+ const [isReady, setIsReady] = useState(false);
+ useEffect(() => {
+ let secondFrame = 0;
+ announce('Preparing status channel', 'polite');
+ const firstFrame = requestAnimationFrame(() => {
+ secondFrame = requestAnimationFrame(() => {
+ announce('', 'polite');
+ setIsReady(true);
+ });
+ });
+ return () => {
+ cancelAnimationFrame(firstFrame);
+ cancelAnimationFrame(secondFrame);
+ };
+ }, [announce]);
+ return <span data-a11y-ready={String(isReady)} hidden />;
+}
+
+function TypingHarness() {
+ const [names, setNames] = useState<string[]>([]);
return (
<div>
- <span data-a11y-ready="true" hidden />
+ <PrimePoliteChannel />
<button data-a11y-relation="focus-anchor" type="button">
Keep focus
</button>
@@ -53,8 +77,7 @@ export const CHAT_TYPING_STATUS_STATE_RENDERS: Record<
ChatTypingStatusStateId,
ChatTypingStatusStateRender
> = {
- 'chat-typing-empty-to-message': () => <TypingHarness startsNamed={false} />,
- 'chat-typing-name-mounted': () => <TypingHarness startsNamed />,
+ 'chat-typing-empty-to-message': () => <TypingHarness />,
};
export {transitionTestId};
diff --git a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states.ts b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states.ts
index 541822feff..ab2d8890d9 100644
--- a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states.ts
+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states.ts
@@ -9,12 +9,11 @@
import type {StatusMessageStateFacts} from '@astryxdesign/a11y-spec';
-export type ChatTypingStatusStateId =
- 'chat-typing-empty-to-message' | 'chat-typing-name-mounted';
+export type ChatTypingStatusStateId = 'chat-typing-empty-to-message';
export interface ChatTypingStatusBindingDefinition {
readonly id: ChatTypingStatusStateId;
- readonly binding: 'ChatTypingIndicator';
+ readonly binding: 'ChatTypingIndicator announcement channel';
readonly summary: string;
readonly facts: StatusMessageStateFacts;
readonly storyId: string;
@@ -28,30 +27,19 @@ const LIFECYCLE_FACTS: StatusMessageStateFacts = {
initialMessage: '',
message: 'Ana is typing…',
replacement: 'Ana and Ben are typing…',
- semanticTransitions: ['show', 'replace', 'clear'],
+ semanticTransitions: ['show', 'replace'],
};
export const CHAT_TYPING_STATUS_BINDING_STATES: ReadonlyArray<ChatTypingStatusBindingDefinition> =
[
{
id: 'chat-typing-empty-to-message',
- binding: 'ChatTypingIndicator',
+ binding: 'ChatTypingIndicator announcement channel',
summary:
- 'the mounted empty indicator receives one name, replaces it with two, then clears',
+ 'one name, then two, reach the persistent polite channel as the indicator updates',
facts: LIFECYCLE_FACTS,
storyId: 'a11y-status-message-pattern--chat-typing-empty-to-message',
},
- {
- id: 'chat-typing-name-mounted',
- binding: 'ChatTypingIndicator',
- summary: 'the documented named indicator is mounted with its status text',
- facts: {
- ...LIFECYCLE_FACTS,
- initialMessage: 'Ana is typing…',
- semanticTransitions: ['replace'],
- },
- storyId: 'a11y-status-message-pattern--chat-typing-name-mounted',
- },
];
export type ChatTypingStatusBindingState = ChatTypingStatusBindingDefinition;
@@ -61,7 +49,19 @@ export const CHAT_TYPING_STATUS_EXCLUSIONS = [
owner: 'ChatTypingIndicator',
part: 'omitted names',
reason:
- 'Omitted names and an empty names array render the same empty persistent status state, so one binding row covers both inputs.',
+ 'Omitted names and an empty names array render the same dots-only indicator and announce nothing, so one binding row covers both inputs.',
+ },
+ {
+ owner: 'ChatTypingIndicator',
+ part: 'indicator mounted with names',
+ reason:
+ 'A named indicator that mounts announces its label once through the same channel; the channel text clears on its own timer, so the mount occasion is asserted with a channel spy in ChatTypingIndicator.test.tsx rather than as a bound initial state.',
+ },
+ {
+ owner: 'useAnnounce',
+ part: 'clearing the names',
+ reason:
+ 'Clearing removes the visible label and announces nothing; the channel clears its own text after each announcement, so no clear transition is observable on it.',
},
{
owner: 'ChatTypingIndicator and theme',
@@ -73,6 +73,6 @@ export const CHAT_TYPING_STATUS_EXCLUSIONS = [
owner: 'ChatMessageList',
part: 'transcript log announcements',
reason:
- 'The parent role=log owns sequential message updates and stream batching, which are distinct from this one atomic typing status.',
+ 'Inside a role=log the indicator announces nothing and the log delivers the label as added content (spec:AST-086 FR4), asserted in ChatTypingIndicator.test.tsx.',
},
] as const;
diff --git a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsx b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsx
index 61d66cbb81..c920af23f1 100644
--- a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsx
+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsx
@@ -71,6 +71,8 @@ describe('ChatTypingIndicator status-message binding — jsdom lane', () => {
it('records equivalent and separately owned states explicitly', () => {
expect(CHAT_TYPING_STATUS_EXCLUSIONS.map(entry => entry.part)).toEqual([
'omitted names',
+ 'indicator mounted with names',
+ 'clearing the names',
'typing-dot animation and reduced motion',
'transcript log announcements',
]);
diff --git a/packages/lab/src/Comments/Comments.test.tsx b/packages/lab/src/Comments/Comments.test.tsx
index fcf3d1a958..66b36cd6f4 100644
--- a/packages/lab/src/Comments/Comments.test.tsx
+++ b/packages/lab/src/Comments/Comments.test.tsx
@@ -402,9 +402,7 @@ describe('Comments rendering', () => {
it('removes the fading New badge from layout when its animation ends', () => {
render(
<Sized>
- <Comments
- comments={[{...COMMENTS[0], isUnread: true, replies: []}]}
- />
+ <Comments comments={[{...COMMENTS[0], isUnread: true, replies: []}]} />
</Sized>,
);
const badge = document.querySelector('[data-comment-unread-badge="true"]');
@@ -586,8 +584,9 @@ describe('Comments live collaboration seams', () => {
await click(screen.getByRole('button', {name: 'Thread by Avery Kim'}));
const typingStatus = screen
.getByText('Maya Chen and Release Assistant are typing…')
- .closest('[role="status"]');
+ .closest('.astryx-chat-typing-indicator');
expect(typingStatus).not.toBeNull();
+ expect(typingStatus).not.toHaveAttribute('role');
expect(
(typingStatus as HTMLElement).style.getPropertyValue(
'--astryx-chat-typing-indicator-dots-column-width',
@@ -867,11 +866,7 @@ describe('Comments threads', () => {
const onReact = vi.fn().mockResolvedValue(undefined);
render(
<Sized>
- <Comments
- comments={COMMENTS}
- currentUser={VIEWER}
- onReact={onReact}
- />
+ <Comments comments={COMMENTS} currentUser={VIEWER} onReact={onReact} />
</Sized>,
);
const article = articleByAuthor('Avery Kim');
@@ -896,11 +891,7 @@ describe('Comments threads', () => {
.mockResolvedValue(undefined);
render(
<Sized>
- <Comments
- comments={COMMENTS}
- currentUser={VIEWER}
- onReact={onReact}
- />
+ <Comments comments={COMMENTS} currentUser={VIEWER} onReact={onReact} />
</Sized>,
);
await click(