Skip to content

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

TypeScript

fix(core): announce field status messages via persistent live regions (#4002)

Baraa Hamodi4fe3df010110
diff --git a/.changeset/fieldstatus-live-region.md b/.changeset/fieldstatus-live-region.md
new file mode 100644
index 0000000000..eef33a31d3
--- /dev/null
+++ b/.changeset/fieldstatus-live-region.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Field/FieldStatus: status and error messages are now announced through persistent live regions, so they are reliably read by screen readers regardless of when they appear.
+
+@bhamodi
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
index 22707f4445..25064170df 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
@@ -9,10 +9,15 @@
* SYNC: When CheckboxInput.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {CheckboxInput} from './CheckboxInput';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
// Mock showPopover/hidePopover (not implemented in jsdom) so the tooltip layer
// reflects its open state via a `popover-open` attribute the tests can assert.
@@ -333,6 +338,32 @@ describe('CheckboxInput', () => {
);
});
+ // Regression: the status is conditionally mounted, so it must be announced
+ // through the persistent useAnnounce live region — a live region born
+ // together with its content is not reliably announced.
+ it('announces a status message that appears after mount', async () => {
+ const {rerender} = render(
+ <CheckboxInput label="Accept terms" value={false} onChange={() => {}} />,
+ );
+ expect(
+ document.querySelector('[data-astryx-live-region="assertive"]'),
+ ).toBeNull();
+
+ rerender(
+ <CheckboxInput
+ label="Accept terms"
+ value={false}
+ onChange={() => {}}
+ status={{type: 'error', message: 'Required field'}}
+ />,
+ );
+ await waitFor(() => {
+ expect(
+ document.querySelector('[data-astryx-live-region="assertive"]'),
+ ).toHaveTextContent('Required field');
+ });
+ });
+
describe('disabledMessage', () => {
const h = {hidden: true} as const;
diff --git a/packages/core/src/CheckboxList/CheckboxList.test.tsx b/packages/core/src/CheckboxList/CheckboxList.test.tsx
index 1ff3473389..ed780c050f 100644
--- a/packages/core/src/CheckboxList/CheckboxList.test.tsx
+++ b/packages/core/src/CheckboxList/CheckboxList.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When CheckboxList.tsx or CheckboxListItem.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {
render,
screen,
@@ -20,8 +20,16 @@ import {
import userEvent from '@testing-library/user-event';
import {CheckboxList} from './CheckboxList';
import {CheckboxListItem} from './CheckboxListItem';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {List} from '../List/List';
+// FieldStatus announces status messages through the persistent useAnnounce
+// singletons; remove them between tests so role/aria-live queries in this
+// file never match a leftover region.
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
+
// Mock showPopover/hidePopover (not implemented in jsdom) so the tooltip layer
// reflects its open state via a `popover-open` attribute the tests can assert.
beforeEach(() => {
diff --git a/packages/core/src/Field/Field.test.tsx b/packages/core/src/Field/Field.test.tsx
index 9c739fe0be..1c692d08ae 100644
--- a/packages/core/src/Field/Field.test.tsx
+++ b/packages/core/src/Field/Field.test.tsx
@@ -9,10 +9,22 @@
* SYNC: When Field.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {render, screen, waitFor} from '@testing-library/react';
import {Field} from './Field';
import {FormLayoutContext} from '../FormLayout/FormLayoutContext';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+function politeRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="polite"]');
+}
+function assertiveRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="assertive"]');
+}
+
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
describe('Field', () => {
it('renders with label', () => {
@@ -228,7 +240,11 @@ describe('Field', () => {
expect(document.querySelector('svg')).not.toBeInTheDocument();
});
- it('status has role="alert" and aria-live="assertive" for error type', () => {
+ // The status message is announced through the persistent useAnnounce live
+ // regions rather than role/aria-live on the (conditionally mounted)
+ // FieldStatus element itself — regions born with their content are not
+ // reliably announced by assistive technology.
+ it('announces error status assertively via the persistent live region', async () => {
render(
<Field
label="Email"
@@ -237,12 +253,13 @@ describe('Field', () => {
<input id="email-input" />
</Field>,
);
- const status = screen.getByRole('alert');
- expect(status).toHaveTextContent('Invalid email');
- expect(status).toHaveAttribute('aria-live', 'assertive');
+ expect(screen.getByText('Invalid email')).not.toHaveAttribute('role');
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('Invalid email');
+ });
});
- it('status has role="status" and aria-live="polite" for warning type', () => {
+ it('announces warning status politely via the persistent live region', async () => {
render(
<Field
label="Email"
@@ -251,9 +268,34 @@ describe('Field', () => {
<input id="email-input" />
</Field>,
);
- const status = screen.getByRole('status');
- expect(status).toHaveTextContent('Check this');
- expect(status).toHaveAttribute('aria-live', 'polite');
+ expect(screen.getByText('Check this')).not.toHaveAttribute('aria-live');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Check this');
+ });
+ });
+
+ // Regression: the status live region must NOT be born together with its
+ // content. A message that appears after mount (the common validation flow)
+ // has to land in the persistent announce region.
+ it('announces a status message that appears after mount', async () => {
+ const {rerender} = render(
+ <Field label="Email" inputID="email-input">
+ <input id="email-input" />
+ </Field>,
+ );
+ expect(assertiveRegion()).toBeNull();
+
+ rerender(
+ <Field
+ label="Email"
+ inputID="email-input"
+ status={{type: 'error', message: 'Email is required'}}>
+ <input id="email-input" />
+ </Field>,
+ );
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('Email is required');
+ });
});
it('auto-generates description ID as {inputID}-desc when descriptionID is not provided', () => {
@@ -277,7 +319,10 @@ describe('Field', () => {
<input id="my-input" />
</Field>,
);
- expect(screen.getByRole('alert')).toHaveAttribute('id', 'my-input-status');
+ expect(screen.getByText('Required')).toHaveAttribute(
+ 'id',
+ 'my-input-status',
+ );
});
it('warns when isOptional and isRequired are both set', () => {
@@ -421,7 +466,7 @@ describe('Field', () => {
</Field>,
{wrapper: horizontalLabelsWrapper},
);
- const statusEl = screen.getByRole('alert');
+ const statusEl = screen.getByText('Required');
const inputEl = screen.getByTestId('email');
// Both status and input should be inside the same wrapper div (column 2)
expect(statusEl.parentElement).toBe(inputEl.parentElement);
diff --git a/packages/core/src/FieldStatus/FieldStatus.doc.mjs b/packages/core/src/FieldStatus/FieldStatus.doc.mjs
index 77109aed8e..744788eb0a 100644
--- a/packages/core/src/FieldStatus/FieldStatus.doc.mjs
+++ b/packages/core/src/FieldStatus/FieldStatus.doc.mjs
@@ -8,7 +8,7 @@ export const docs = {
category: 'Data Input',
isHiddenFromOverview: true,
description:
- 'Status message component for form field validation feedback.',
+ 'Status message component for form field validation feedback. Messages are announced to screen readers through persistent live regions (assertive for errors, polite otherwise), so conditional mounting is safe.',
theming: {
targets: [
{className: 'astryx-field-status', visualProps: ['type', 'variant']},
@@ -66,12 +66,24 @@ export const docs = {
/** @type {import('../docs-types').TranslationDoc} */
export const docsDense = {
description:
- 'Validation feedback message for fields/custom controls. Supports error, warning, success and attached/detached variants.',
+ 'Validation feedback message for fields/custom controls. Supports error, warning, success and attached/detached variants. Announced via persistent live regions (assertive for errors, polite otherwise).',
usage: {
bestPractices: [
- {guidance: true, description: 'Use attached status below bordered inputs when message belongs to that input.'},
- {guidance: true, description: 'Use detached status for checkboxes, switches, and custom controls where overlap is visually awkward.'},
- {guidance: false, description: 'Use FieldStatus for general alerts or page-level notices; use Banner or Toast instead.'},
+ {
+ guidance: true,
+ description:
+ 'Use attached status below bordered inputs when message belongs to that input.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use detached status for checkboxes, switches, and custom controls where overlap is visually awkward.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use FieldStatus for general alerts or page-level notices; use Banner or Toast instead.',
+ },
],
},
propDescriptions: {
diff --git a/packages/core/src/FieldStatus/FieldStatus.test.tsx b/packages/core/src/FieldStatus/FieldStatus.test.tsx
index 7a29e0bbce..e41b8809b5 100644
--- a/packages/core/src/FieldStatus/FieldStatus.test.tsx
+++ b/packages/core/src/FieldStatus/FieldStatus.test.tsx
@@ -9,15 +9,27 @@
* SYNC: When FieldStatus.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {render, screen, waitFor} from '@testing-library/react';
import * as stylex from '@stylexjs/stylex';
import {FieldStatus} from './FieldStatus';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
const testStyles = stylex.create({
custom: {color: 'rebeccapurple'},
});
+function politeRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="polite"]');
+}
+function assertiveRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="assertive"]');
+}
+
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
+
describe('FieldStatus', () => {
it('renders the message text', () => {
render(<FieldStatus type="error" message="This field is required" />);
@@ -29,47 +41,75 @@ describe('FieldStatus', () => {
expect(screen.getByTestId('fs').tagName).toBe('DIV');
});
- describe('role semantics', () => {
- // Errors are urgent — they get role="alert" so assistive tech interrupts.
- it('uses role="alert" for error status', () => {
- render(<FieldStatus type="error" message="msg" />);
- expect(screen.getByRole('alert')).toHaveTextContent('msg');
+ describe('screen-reader announcements', () => {
+ // The rendered element is NOT itself a live region: FieldStatus is
+ // conditionally mounted by every caller, and live regions born together
+ // with their content are not reliably announced. Announcements go through
+ // the persistent useAnnounce singletons instead.
+ it('does not carry role or aria-live on the rendered element', () => {
+ render(<FieldStatus type="error" message="msg" data-testid="fs" />);
+ const el = screen.getByTestId('fs');
+ expect(el).not.toHaveAttribute('role');
+ expect(el).not.toHaveAttribute('aria-live');
});
- // Non-error statuses are advisory — role="status" is a polite live region.
- it('uses role="status" for warning status', () => {
- render(<FieldStatus type="warning" message="msg" data-testid="fs" />);
- expect(screen.getByTestId('fs')).toHaveAttribute('role', 'status');
- expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ // Errors are urgent — they interrupt via the assertive channel.
+ it('announces error messages assertively, including on first mount', async () => {
+ render(<FieldStatus type="error" message="This field is required" />);
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('This field is required');
+ });
+ expect(politeRegion()).toHaveTextContent('');
});
- it('uses role="status" for success status', () => {
- render(<FieldStatus type="success" message="msg" data-testid="fs" />);
- expect(screen.getByTestId('fs')).toHaveAttribute('role', 'status');
+ it('announces warning messages politely', async () => {
+ render(<FieldStatus type="warning" message="Check this value" />);
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Check this value');
+ });
+ expect(assertiveRegion()).toHaveTextContent('');
});
- });
- describe('aria-live politeness', () => {
- // Error → assertive so screen readers announce immediately.
- it('sets aria-live="assertive" for error', () => {
- render(<FieldStatus type="error" message="msg" data-testid="fs" />);
- expect(screen.getByTestId('fs')).toHaveAttribute(
- 'aria-live',
- 'assertive',
- );
+ it('announces success messages politely', async () => {
+ render(<FieldStatus type="success" message="Looks good" />);
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Looks good');
+ });
});
- it('sets aria-live="polite" for warning', () => {
- render(<FieldStatus type="warning" message="msg" data-testid="fs" />);
- expect(screen.getByTestId('fs')).toHaveAttribute('aria-live', 'polite');
+ it('announces message changes', async () => {
+ const {rerender} = render(<FieldStatus type="error" message="First" />);
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('First');
+ });
+ rerender(<FieldStatus type="error" message="Second" />);
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('Second');
+ });
});
- it('sets aria-live="polite" for success', () => {
- render(<FieldStatus type="success" message="msg" data-testid="fs" />);
- expect(screen.getByTestId('fs')).toHaveAttribute('aria-live', 'polite');
+ // Severity changes re-route the announcement to the matching channel.
+ it('re-routes to the polite channel when type changes from error', async () => {
+ const {rerender} = render(<FieldStatus type="error" message="msg" />);
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('msg');
+ });
+ rerender(<FieldStatus type="success" message="msg" />);
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('msg');
+ });
});
- // The element is a live region, never hidden from assistive tech.
+ it('does not announce an empty message', () => {
+ render(<FieldStatus type="error" message="" />);
+ // The live regions are created lazily on first announce; an empty
+ // message must not trigger one.
+ expect(assertiveRegion()).toBeNull();
+ expect(politeRegion()).toBeNull();
+ });
+
+ // The visible message stays perceivable by assistive tech (it is the
+ // aria-describedby target for the input).
it('does not mark itself aria-hidden', () => {
render(<FieldStatus type="error" message="msg" data-testid="fs" />);
expect(screen.getByTestId('fs')).not.toHaveAttribute('aria-hidden');
@@ -245,20 +285,18 @@ describe('FieldStatus', () => {
expect(screen.getByTestId('fs')).toHaveTextContent('Second');
});
- // Switching from error to a non-error type must relax both the role and
- // the live-region politeness in lockstep.
- it('relaxes role and aria-live when type changes from error', () => {
+ // The element must never regain live-region semantics when the type
+ // changes — announcements always flow through the persistent regions.
+ it('keeps the element role-free when type changes from error', () => {
const {rerender} = render(
<FieldStatus type="error" message="msg" data-testid="fs" />,
);
- let el = screen.getByTestId('fs');
- expect(el).toHaveAttribute('role', 'alert');
- expect(el).toHaveAttribute('aria-live', 'assertive');
+ expect(screen.getByTestId('fs')).not.toHaveAttribute('role');
rerender(<FieldStatus type="success" message="msg" data-testid="fs" />);
- el = screen.getByTestId('fs');
- expect(el).toHaveAttribute('role', 'status');
- expect(el).toHaveAttribute('aria-live', 'polite');
+ const el = screen.getByTestId('fs');
+ expect(el).not.toHaveAttribute('role');
+ expect(el).not.toHaveAttribute('aria-live');
});
});
diff --git a/packages/core/src/FieldStatus/FieldStatus.tsx b/packages/core/src/FieldStatus/FieldStatus.tsx
index 673ed67496..9e9a800127 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
+ * @input Uses React, stylex, theme tokens, useAnnounce
* @output Exports FieldStatus component, FieldStatusProps
* @position Core implementation; consumed by Field, Switch, CheckboxInput, and the FieldStatus entrypoint
*
@@ -16,9 +16,10 @@
'use client';
-import React from 'react';
+import React, {useEffect} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
+import {useAnnounce} from '../hooks/useAnnounce';
import {mergeProps} from '../utils';
import {
colorVars,
@@ -113,6 +114,14 @@ export interface FieldStatusProps extends BaseProps<HTMLDivElement> {
/**
* A status message component for form fields.
*
+ * Screen-reader announcements go through the persistent `useAnnounce` live
+ * regions (assertive for errors, polite otherwise) rather than `role`/
+ * `aria-live` on the rendered element. Live regions that mount together with
+ * their content are not reliably announced by assistive technology, and
+ * FieldStatus is almost always conditionally rendered by its callers. The
+ * message is announced whenever it appears — including on first mount — and
+ * whenever it changes.
+ *
* @example
* ```
* <FieldStatus
@@ -138,13 +147,22 @@ 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]);
return (
<div
ref={ref}
id={id}
- role={type === 'error' ? 'alert' : 'status'}
- aria-live={type === 'error' ? 'assertive' : 'polite'}
{...rest}
{...mergeProps(
themeProps('field-status', {type, variant}),
diff --git a/packages/core/src/FileInput/FileInput.test.tsx b/packages/core/src/FileInput/FileInput.test.tsx
index 192e6260ae..71f7ef8d54 100644
--- a/packages/core/src/FileInput/FileInput.test.tsx
+++ b/packages/core/src/FileInput/FileInput.test.tsx
@@ -348,9 +348,10 @@ describe('FileInput', () => {
fireEvent.change(fileInputEl(), {
target: {files: [createFile('note.txt', 100)]},
});
- // A rejected selection creates no polite region (only the error goes to
- // the existing role="status" region).
- expect(politeRegion()).toBeNull();
+ // A rejected selection announces nothing politely. (The region pair may
+ // exist because the validation error itself is announced assertively via
+ // FieldStatus, but the polite channel must stay empty.)
+ expect(politeRegion()?.textContent ?? '').toBe('');
});
});
diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsx
index 310aa2a5de..656a62d8b5 100644
--- a/packages/core/src/NumberInput/NumberInput.test.tsx
+++ b/packages/core/src/NumberInput/NumberInput.test.tsx
@@ -9,11 +9,19 @@
* SYNC: When NumberInput.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {TestIcon} from '../__tests__/TestIcon';
import {NumberInput} from './NumberInput';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+// FieldStatus announces status messages through the persistent useAnnounce
+// singletons; remove them between tests so role/aria-live queries in this
+// file never match a leftover region.
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
// Mock showPopover/hidePopover since jsdom does not implement them. Used by the
// disabledMessage tooltip.
@@ -871,9 +879,7 @@ describe('NumberInput', () => {
describe('keyboard clearing with hasClear (#3599)', () => {
it('commits null when the input is emptied and blurred', () => {
const onChange = vi.fn();
- render(
- <NumberInput label="Qty" hasClear value={42} onChange={onChange} />,
- );
+ render(<NumberInput label="Qty" hasClear value={42} onChange={onChange} />);
const input = screen.getByLabelText('Qty');
fireEvent.change(input, {target: {value: ''}});
fireEvent.blur(input);
@@ -882,9 +888,7 @@ describe('keyboard clearing with hasClear (#3599)', () => {
it('commits null when the input is emptied and Enter is pressed', () => {
const onChange = vi.fn();
- render(
- <NumberInput label="Qty" hasClear value={42} onChange={onChange} />,
- );
+ render(<NumberInput label="Qty" hasClear value={42} onChange={onChange} />);
const input = screen.getByLabelText('Qty');
fireEvent.change(input, {target: {value: ''}});
fireEvent.keyDown(input, {key: 'Enter'});
diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsx
index 05c9c71cb5..fea564c91c 100644
--- a/packages/core/src/Switch/Switch.test.tsx
+++ b/packages/core/src/Switch/Switch.test.tsx
@@ -9,10 +9,15 @@
* SYNC: When Switch.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Switch} from './Switch';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
// Mock showPopover/hidePopover (not implemented in jsdom) so the tooltip layer
// reflects its open state via a `popover-open` attribute the tests can assert.
@@ -324,6 +329,32 @@ describe('Switch', () => {
expect(describedBy).toBeTruthy();
});
+ // Regression: the status is conditionally mounted, so it must be announced
+ // through the persistent useAnnounce live region — a live region born
+ // together with its content is not reliably announced.
+ it('announces a status message that appears after mount', async () => {
+ const {rerender} = render(
+ <Switch label="Enable notifications" value={false} onChange={() => {}} />,
+ );
+ expect(
+ document.querySelector('[data-astryx-live-region="assertive"]'),
+ ).toBeNull();
+
+ rerender(
+ <Switch
+ label="Enable notifications"
+ value={false}
+ onChange={() => {}}
+ status={{type: 'error', message: 'Failed to save setting'}}
+ />,
+ );
+ await waitFor(() => {
+ expect(
+ document.querySelector('[data-astryx-live-region="assertive"]'),
+ ).toHaveTextContent('Failed to save setting');
+ });
+ });
+
it('calls onFocus and onBlur callbacks', async () => {
const user = userEvent.setup();
const handleFocus = vi.fn();
diff --git a/packages/core/src/TextArea/TextArea.test.tsx b/packages/core/src/TextArea/TextArea.test.tsx
index 864f3d5418..7168035280 100644
--- a/packages/core/src/TextArea/TextArea.test.tsx
+++ b/packages/core/src/TextArea/TextArea.test.tsx
@@ -10,11 +10,19 @@
*/
import {useState} from 'react';
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {TestIcon} from '../__tests__/TestIcon';
import {TextArea} from './TextArea';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+// FieldStatus announces status messages through the persistent useAnnounce
+// singletons; remove them between tests so role/aria-live queries in this
+// file never match a leftover region.
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
// Mock showPopover/hidePopover since jsdom does not implement them. Used by the
// disabledMessage tooltip.
diff --git a/packages/core/src/TimeInput/TimeInput.test.tsx b/packages/core/src/TimeInput/TimeInput.test.tsx
index e6c0d7e9c9..bbc0510ac4 100644
--- a/packages/core/src/TimeInput/TimeInput.test.tsx
+++ b/packages/core/src/TimeInput/TimeInput.test.tsx
@@ -9,12 +9,24 @@
* SYNC: When TimeInput.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {TimeInput} from './TimeInput';
import {InputGroup, InputGroupText} from '../InputGroup';
import type {ISOTimeString} from '../utils';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+
+function politeRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="polite"]');
+}
+function assertiveRegion(): HTMLElement | null {
+ return document.querySelector('[data-astryx-live-region="assertive"]');
+}
+
+afterEach(() => {
+ __resetLiveRegionsForTest();
+});
describe('TimeInput', () => {
it('renders with label', () => {
@@ -352,6 +364,69 @@ describe('TimeInput', () => {
// duplicated.
expect(container.querySelectorAll('svg')).toHaveLength(1);
});
+
+ // The grouped status node exists only for aria-describedby; announcing
+ // happens through the persistent useAnnounce regions because a live
+ // region mounted together with its content is not reliably announced.
+ it('keeps the grouped status node role-free while announcing via the persistent region', async () => {
+ render(
+ <InputGroup label="Schedule">
+ <InputGroupText>Starts</InputGroupText>
+ <TimeInput
+ label="Start time"
+ isLabelHidden
+ value={'09:00' as ISOTimeString}
+ onChange={() => {}}
+ status={{type: 'error', message: 'Start time is required'}}
+ />
+ </InputGroup>,
+ );
+
+ const input = screen.getByRole('textbox', {
+ name: 'Schedule Start time',
+ });
+ const describedByIDs =
+ input.getAttribute('aria-describedby')?.split(' ') ?? [];
+ const statusNode = describedByIDs
+ .map(id => document.getElementById(id))
+ .find(el => el?.textContent === 'Start time is required');
+ expect(statusNode).toBeTruthy();
+ expect(statusNode).not.toHaveAttribute('role');
+ expect(statusNode).not.toHaveAttribute('aria-live');
+
+ await waitFor(() => {
+ expect(assertiveRegion()).toHaveTextContent('Start time is required');
+ });
+ });
+
+ // Regression: a grouped status message appearing after mount (the common
+ // validation flow) must land in the persistent announce region.
+ it('announces a grouped status message that appears after mount', async () => {
+ const grouped = (status?: {
+ type: 'error' | 'warning';
+ message: string;
+ }) => (
+ <InputGroup label="Schedule">
+ <InputGroupText>Starts</InputGroupText>
+ <TimeInput
+ label="Start time"
+ isLabelHidden
+ value={'09:00' as ISOTimeString}
+ onChange={() => {}}
+ status={status}
+ />
+ </InputGroup>
+ );
+ const {rerender} = render(grouped());
+ expect(politeRegion()).toBeNull();
+
+ rerender(grouped({type: 'warning', message: 'Schedule is unusual'}));
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Schedule is unusual');
+ });
+ // Non-error statuses stay on the polite channel.
+ expect(assertiveRegion()).toHaveTextContent('');
+ });
});
describe('disabledMessage', () => {
diff --git a/packages/core/src/TimeInput/TimeInput.tsx b/packages/core/src/TimeInput/TimeInput.tsx
index 173437ab85..519b3f2a43 100644
--- a/packages/core/src/TimeInput/TimeInput.tsx
+++ b/packages/core/src/TimeInput/TimeInput.tsx
@@ -4,7 +4,7 @@
/**
* @file TimeInput.tsx
- * @input Uses React, useId, useState, useCallback, useRef, Field, Icon, InputGroupContext
+ * @input Uses React, useId, useState, useCallback, useRef, Field, Icon, InputGroupContext, useAnnounce
* @output Exports TimeInput component, TimeInputProps
* @position Core implementation; consumed by index.ts, tested by TimeInput.test.tsx
*
@@ -20,6 +20,7 @@ import {
useId,
useState,
useCallback,
+ useEffect,
useRef,
useMemo,
useOptimistic,
@@ -64,6 +65,7 @@ import {
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {useSize} from '../SizeContext/SizeContext';
+import {useAnnounce} from '../hooks/useAnnounce';
import {useInputContainer} from '../hooks/useInputContainer';
import {useInputGroup} from '../InputGroup/InputGroupContext';
import {groupStyles} from '../InputGroup/groupStyles';
@@ -369,6 +371,21 @@ export function TimeInput({
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ // In grouped mode the status message renders as a visually-hidden node that
+ // exists only for aria-describedby. Announce it through the persistent
+ // useAnnounce live regions instead of role/aria-live on that node — a live
+ // region mounted together with its content is not reliably announced.
+ // Ungrouped mode delegates to Field -> FieldStatus, which announces itself.
+ const announce = useAnnounce();
+ useEffect(() => {
+ if (inputGroup && status?.message) {
+ announce(
+ status.message,
+ status.type === 'error' ? 'assertive' : 'polite',
+ );
+ }
+ }, [announce, inputGroup, status?.message, status?.type]);
+
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
// tooltip listeners attach to the input container (which already exists) and
// the input stays perceivable via aria-disabled instead of the disabled
@@ -611,11 +628,7 @@ export function TimeInput({
</VisuallyHidden>
)}
{inputGroup && status?.message && (
- <VisuallyHidden
- as="div"
- id={statusMessageID}
- role={status.type === 'error' ? 'alert' : 'status'}
- aria-live={status.type === 'error' ? 'assertive' : 'polite'}>
+ <VisuallyHidden as="div" id={statusMessageID}>
{status.message}
</VisuallyHidden>
)}