An open source design system that's fully customizable and agent ready
TypeScript
fix(Field): announce a tooltip-placed field status (#7191)
Cindy Zhang349c479bc399
diff --git a/.changeset/field-tooltip-status-announced.md b/.changeset/field-tooltip-status-announced.mdnew file mode 100644index 0000000000..d18841e427--- /dev/null+++ b/.changeset/field-tooltip-status-announced.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] A field status shown with `statusVariant="tooltip"` is now announced to screen readers when it appears or changes, the same way the attached and detached message boxes are: errors assertively, warnings and successes politely.++Before, the tooltip placement only described the control, so a screen-reader user was not told that a validation message had appeared until they left and re-entered the field. This affects every input that offers the tooltip placement. The attached and detached placements are unchanged and are still announced once.++@cixzhangdiff --git a/packages/core/src/Field/Field.test.tsx b/packages/core/src/Field/Field.test.tsxindex 6a20c80110..967bdbd35e 100644--- a/packages/core/src/Field/Field.test.tsx+++ b/packages/core/src/Field/Field.test.tsx@@ -337,6 +337,129 @@ describe('Field', () => {});});+ // The tooltip placement renders no FieldStatus, so Field itself must speak+ // the message; otherwise a screen-reader user is never told it appeared.+ describe('tooltip status placement', () => {+ /** Every non-empty text written into a live region, in order. */+ function recordAnnouncements(): string[] {+ const spoken: string[] = [];+ const observer = new MutationObserver(records => {+ for (const record of records) {+ const target =+ record.target instanceof HTMLElement+ ? record.target+ : record.target.parentElement;+ const text = target+ ?.closest('[data-astryx-live-region]')+ ?.textContent?.trim();+ if (text) {+ spoken.push(text);+ }+ }+ });+ observer.observe(document.body, {+ childList: true,+ characterData: true,+ subtree: true,+ });+ return spoken;+ }++ it('announces a warning that appears after mount, politely', async () => {+ const {rerender} = render(+ <Field label="Email" inputID="email-input" statusVariant="tooltip">+ <input id="email-input" />+ </Field>,+ );+ expect(politeRegion()).toBeNull();++ rerender(+ <Field+ label="Email"+ inputID="email-input"+ statusVariant="tooltip"+ status={{type: 'warning', message: 'Check this'}}>+ <input id="email-input" />+ </Field>,+ );+ // No message box renders for this placement; the text lives only in+ // the live region (and in the member's tooltip, which Field does not own).+ expect(screen.queryByText('Check this')).toBeNull();+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Check this');+ });+ expect(assertiveRegion()).toHaveTextContent('');+ });++ it('announces an error assertively, matching the message box placements', async () => {+ render(+ <Field+ label="Email"+ inputID="email-input"+ statusVariant="tooltip"+ status={{type: 'error', message: 'Email is required'}}>+ <input id="email-input" />+ </Field>,+ );+ await waitFor(() => {+ expect(assertiveRegion()).toHaveTextContent('Email is required');+ });+ });++ it('speaks a message once, and again only when it changes', async () => {+ const spoken = recordAnnouncements();+ const field = (message: string) => (+ <Field+ label="Email"+ inputID="email-input"+ statusVariant="tooltip"+ status={{type: 'warning', message}}>+ <input id="email-input" />+ </Field>+ );+ const {rerender} = render(field('First'));+ await waitFor(() => expect(spoken).toEqual(['First']));++ rerender(field('First'));+ rerender(field('Second'));+ await waitFor(() => expect(spoken).toEqual(['First', 'Second']));+ });++ it.each(['attached', 'detached'] as const)(+ 'does not add a second announcement to the %s message box',+ async statusVariant => {+ const spoken = recordAnnouncements();+ render(+ <Field+ label="Email"+ inputID="email-input"+ statusVariant={statusVariant}+ status={{type: 'warning', message: 'Check this'}}>+ <input id="email-input" />+ </Field>,+ );+ await waitFor(() => expect(spoken).toEqual(['Check this']));+ // Give a duplicate announcement's animation frame time to land.+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(spoken).toEqual(['Check this']);+ },+ );++ it('does not announce a status without a message', () => {+ render(+ <Field+ label="Email"+ inputID="email-input"+ statusVariant="tooltip"+ status={{type: 'error'}}>+ <input id="email-input" />+ </Field>,+ );+ expect(assertiveRegion()).toBeNull();+ expect(politeRegion()).toBeNull();+ });+ });+it('auto-generates description ID as {inputID}-desc when descriptionID is not provided', () => {render(<Field label="Email" inputID="my-input" description="Help text">diff --git a/packages/core/src/Field/Field.tsx b/packages/core/src/Field/Field.tsxindex 0c4778d155..b1c725c26b 100644--- a/packages/core/src/Field/Field.tsx+++ b/packages/core/src/Field/Field.tsx@@ -4,7 +4,7 @@/*** @file Field.tsx- * @input Uses React, HTMLAttributes, ReactNode, FieldLabel, IconType+ * @input Uses React, HTMLAttributes, ReactNode, FieldLabel, IconType, useFieldStatusAnnouncement* @output Exports Field component, FieldProps* @position Core implementation; consumed by index.ts, tested by Field.test.tsx*@@ -23,6 +23,7 @@ import type {SizeValue} from '../utils/types';import {FieldLabel} from './FieldLabel';import {FieldStatus} from '../FieldStatus/FieldStatus';import type {FieldStatusVariant} from '../FieldStatus/FieldStatus';+import {useFieldStatusAnnouncement} from '../FieldStatus/useFieldStatusAnnouncement';import {spacingVars, borderVars, sizeVars} from '../theme/tokens.stylex';import type {IconType} from '../Icon';import {mergeProps} from '../utils';@@ -267,7 +268,14 @@ export function Field({);// The 'tooltip' variant surfaces status through the input's on-field icon- // tooltip, so Field renders no message box for it.+ // tooltip, so Field renders no message box for it. Without a FieldStatus+ // nothing would speak the message, so Field announces it on the same+ // channel and timing FieldStatus uses: placement changes where the message+ // is shown, not whether a screen-reader user hears it.+ useFieldStatusAnnouncement(+ statusVariant === 'tooltip' ? status?.message : undefined,+ status?.type,+ );const statusNode =status?.message && statusVariant !== 'tooltip' ? (<FieldStatusdiff --git a/packages/core/src/FieldStatus/FieldStatus.tsx b/packages/core/src/FieldStatus/FieldStatus.tsxindex 5160dd5c72..2eda5ec918 100644--- a/packages/core/src/FieldStatus/FieldStatus.tsx+++ b/packages/core/src/FieldStatus/FieldStatus.tsx@@ -2,7 +2,7 @@/*** @file FieldStatus.tsx- * @input Uses React, stylex, theme tokens, useAnnounce, Icon+ * @input Uses React, stylex, theme tokens, useFieldStatusAnnouncement, Icon* @output Exports FieldStatus component, FieldStatusProps* @position Core implementation; consumed by Field, Switch, CheckboxInput, and the FieldStatus entrypoint*@@ -10,16 +10,16 @@* - /packages/core/src/FieldStatus/FieldStatus.doc.mjs (props table, features, implementation notes)* - /packages/core/src/Field/Field.doc.mjs (compat docs when public API changes)* - /packages/core/src/FieldStatus/index.ts (exports if types change)+ * - /packages/core/src/FieldStatus/useFieldStatusAnnouncement.ts (announcement timing shared with Field)* - /packages/core/src/Field/index.ts (compat re-export if public API changes)* - /packages/cli/assets/templates/blocks/components/FieldStatus/ (showcase blocks)*/'use client';-import React, {useEffect} from 'react';+import React from 'react';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';-import {useAnnounce} from '../hooks/useAnnounce';import {mergeProps} from '../utils';import {colorVars,@@ -34,6 +34,7 @@ import {themeProps} from '../utils/themeProps';import {Icon} from '../Icon';import type {IconName} from '../Icon';import type {FieldStatusVariantMap} from './index';+import {useFieldStatusAnnouncement} from './useFieldStatusAnnouncement';/*** Maps each status type to its status glyph. Mirrors the mapping the input@@ -171,17 +172,10 @@ export function FieldStatus({...rest}: FieldStatusProps) {const entryStyle = useEntryAnimation('slideDown');- const announce = useAnnounce();-- // Announce the message through the persistently-mounted live regions.// Announce-on-mount is intentional: callers conditionally mount FieldStatus// when a status appears (and whole forms can mount with a server-side// validation error already present), and both cases must be heard.- useEffect(() => {- if (message) {- announce(message, type === 'error' ? 'assertive' : 'polite');- }- }, [announce, message, type]);+ useFieldStatusAnnouncement(message, type);return (<divdiff --git a/packages/core/src/FieldStatus/useFieldStatusAnnouncement.ts b/packages/core/src/FieldStatus/useFieldStatusAnnouncement.tsnew file mode 100644index 0000000000..884957326e--- /dev/null+++ b/packages/core/src/FieldStatus/useFieldStatusAnnouncement.ts@@ -0,0 +1,44 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useFieldStatusAnnouncement.ts+ * @input Uses React useEffect and useAnnounce+ * @output Exports the internal useFieldStatusAnnouncement hook+ * @position Internal to the field family; the one place that decides when and+ * how loudly a field status message is spoken. FieldStatus calls it for the+ * attached and detached message boxes, and Field calls it for the tooltip+ * placement, which renders no FieldStatus. Not exported from the package.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/FieldStatus/FieldStatus.tsx+ * - /packages/core/src/Field/Field.tsx+ */++import {useEffect} from 'react';+import {useAnnounce} from '../hooks/useAnnounce';+import type {InputStatusType} from '../Field/types';++/**+ * Speaks a field status message through the persistent live regions:+ * errors assertively, warnings and successes politely. It speaks when a+ * message is first present, including on mount, and again whenever the+ * message or its type changes. An absent or empty message is never spoken.+ *+ * The persistent regions are used instead of `role`/`aria-live` on the+ * rendered message because a live region mounted together with its content is+ * not reliably announced, and field status is almost always conditionally+ * rendered.+ */+export function useFieldStatusAnnouncement(+ message: string | undefined,+ type: InputStatusType | undefined,+): void {+ const announce = useAnnounce();+ useEffect(() => {+ if (message) {+ announce(message, type === 'error' ? 'assertive' : 'polite');+ }+ }, [announce, message, type]);+}