Skip to content

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

TypeScript

fix(inputs): silence the busy Spinner and announce the busy start once (TextInput, TextArea, Selector, MultiSelector) (#7920)

Cindy Zhang2b60fa6fde9a
diff --git a/.changeset/busy-fields-announce-their-busy-start.md b/.changeset/busy-fields-announce-their-busy-start.md
new file mode 100644
index 0000000000..33b9bba090
--- /dev/null
+++ b/.changeset/busy-fields-announce-their-busy-start.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `TextInput`, `TextArea`, `Selector` and `MultiSelector` announce "Loading" once, politely, through the shared announcement channel when they become busy, and the Spinner they show while busy is hidden from assistive technology (`spec:AST-086` FR6, FR8). Before, the Spinner mounted as its own `role="status"` region already holding its name, which screen readers often skip, and it competed with the control's own `aria-busy` as a second owner of the same feedback. A rerender or StrictMode replay does not repeat the announcement; settling and becoming busy again announces again. Tests that found the busy Spinner with `getByRole('status', {name: 'Loading'})` should check the control's `aria-busy` instead.
+
+@cixzhang
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index e1da4a52f5..8061cd6f1a 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1169,7 +1169,7 @@
},
"@astryx.spinner.loading": {
"defaultMessage": "Loading",
- "description": "Screen-reader-only default name for a standalone Spinner's role=\"status\" element, used when the consumer supplies neither `aria-label` nor a visible string label. Present-progressive form. Kept separate from `button.loading` and `typeahead.loading` — translations may diverge."
+ "description": "Screen-reader-only default name for a standalone Spinner's role=\"status\" element, used when the consumer supplies neither `aria-label` nor a visible string label; also announced once when a busy field or selector (TextInput, TextArea, Selector, MultiSelector) starts loading, in place of its decorative Spinner. Present-progressive form. Kept separate from `button.loading` and `typeahead.loading` — translations may diverge."
},
"@astryx.chatComposerDrawer.expand": {
"defaultMessage": "Expand {label}",
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index e4fb8dffb3..3019121caa 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -105,6 +105,14 @@ afterEach(() => {
// "visible" in the accessibility tree. Use hidden: true to find it.
const h = {hidden: true} as const;
+/** A busy control's Spinner is decorative and silent (spec:AST-086 FR8). */
+function expectSilentBusySpinner() {
+ const spinner = document.querySelector('.astryx-spinner');
+ expect(spinner).not.toBeNull();
+ expect(spinner).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.queryByRole('status', {name: 'Loading'})).toBeNull();
+}
+
describe('MultiSelector', () => {
const defaultOptions = ['Apple', 'Banana', 'Orange'];
@@ -1303,7 +1311,10 @@ describe('MultiSelector', () => {
// component cannot make; the trigger's spinner carries the state.
const listbox = screen.getByRole('listbox', h);
expect(within(listbox).queryByText('No options')).not.toBeInTheDocument();
- expect(politeRegion()?.textContent ?? '').toBe('');
+ // Only the busy start is spoken (spec:AST-086 FR8), never an empty or
+ // no-results message the panel is suppressing.
+ // (The channel clears its text on a timer, so it may already be empty.)
+ expect(['', 'Loading']).toContain(politeRegion()?.textContent ?? '');
});
it('announces nothing while isLoading, matching the silent panel', async () => {
@@ -1337,7 +1348,10 @@ describe('MultiSelector', () => {
expect(
within(listbox).queryByText('Nothing like that here'),
).not.toBeInTheDocument();
- expect(politeRegion()?.textContent ?? '').toBe('');
+ // Only the busy start is spoken (spec:AST-086 FR8), never an empty or
+ // no-results message the panel is suppressing.
+ // (The channel clears its text on a timer, so it may already be empty.)
+ expect(['', 'Loading']).toContain(politeRegion()?.textContent ?? '');
});
it('renders emptyText when there are no options and no search input', async () => {
@@ -1555,7 +1569,7 @@ describe('MultiSelector', () => {
/>,
);
expect(screen.getByRole('combobox')).toHaveAttribute('aria-busy', 'true');
- expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+ expectSilentBusySpinner();
});
it('renders with custom selectAllLabel', async () => {
@@ -2250,7 +2264,7 @@ describe('MultiSelector', () => {
const trigger = screen.getByRole('combobox', {name: 'Fruit'});
expect(trigger).toHaveAttribute('aria-busy', 'true');
- expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+ expectSilentBusySpinner();
await user.click(trigger);
expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 9f1e827fbe..bffc2774c3 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -92,6 +92,7 @@ import {useDevWarning} from '../hooks/useDevWarning';
import {composeEventHandlers} from '../utils/composeEventHandlers';
import {mergeRefs} from '../utils/mergeRefs';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
import type {SizeValue} from '../utils/types';
import {useSize} from '../SizeContext/SizeContext';
import {themeProps} from '../utils/themeProps';
@@ -1203,6 +1204,9 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ // The busy Spinner is decorative; this control announces its busy start
+ // (spec:AST-086 FR8).
+ useBusyAnnouncement(isBusy, t('@astryx.spinner.loading'), triggerRef);
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
// tooltip listeners attach to the trigger container (which already exists)
@@ -2643,7 +2647,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
value.map(v => (
<input key={v} type="hidden" name={htmlName} value={v} />
))}
- {isBusy && <Spinner size="sm" />}
+ {isBusy && <Spinner size="sm" aria-hidden="true" />}
{hasClear &&
value.length > 0 &&
!isDisabled &&
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 7b40a39ede..cb402c8a43 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -253,6 +253,14 @@ function mockSelectorRects({
};
}
+/** A busy control's Spinner is decorative and silent (spec:AST-086 FR8). */
+function expectSilentBusySpinner() {
+ const spinner = document.querySelector('.astryx-spinner');
+ expect(spinner).not.toBeNull();
+ expect(spinner).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.queryByRole('status', {name: 'Loading'})).toBeNull();
+}
+
describe('Selector', () => {
it('uses a bottom sheet and closes after a selection when requested', async () => {
const user = userEvent.setup();
@@ -1388,7 +1396,7 @@ describe('Selector', () => {
<Selector label="Fruit" options={[]} onChange={() => {}} isLoading />,
);
const trigger = screen.getByRole('combobox', {name: 'Fruit'});
- expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+ expectSilentBusySpinner();
await user.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
@@ -1404,7 +1412,10 @@ describe('Selector', () => {
// component cannot make; the trigger's spinner carries the state.
const listbox = screen.getByRole('listbox', h);
expect(within(listbox).queryByText('No options')).not.toBeInTheDocument();
- expect(politeRegion()?.textContent ?? '').toBe('');
+ // Only the busy start is spoken (spec:AST-086 FR8), never an empty or
+ // no-results message the panel is suppressing.
+ // (The channel clears its text on a timer, so it may already be empty.)
+ expect(['', 'Loading']).toContain(politeRegion()?.textContent ?? '');
});
it('announces nothing while isLoading, matching the silent panel', async () => {
@@ -1437,7 +1448,10 @@ describe('Selector', () => {
expect(
within(listbox).queryByText('Nothing like that here'),
).not.toBeInTheDocument();
- expect(politeRegion()?.textContent ?? '').toBe('');
+ // Only the busy start is spoken (spec:AST-086 FR8), never an empty or
+ // no-results message the panel is suppressing.
+ // (The channel clears its text on a timer, so it may already be empty.)
+ expect(['', 'Loading']).toContain(politeRegion()?.textContent ?? '');
});
it('announces the seeded query from type-to-open', async () => {
@@ -1490,7 +1504,10 @@ describe('Selector', () => {
async () =>
void (await new Promise(resolve => requestAnimationFrame(resolve))),
);
- expect(politeRegion()?.textContent ?? '').toBe('');
+ // Only the busy start is spoken (spec:AST-086 FR8), never an empty or
+ // no-results message the panel is suppressing.
+ // (The channel clears its text on a timer, so it may already be empty.)
+ expect(['', 'Loading']).toContain(politeRegion()?.textContent ?? '');
// The fetch lands empty while the panel is open. The message appears, so
// the region owes the same words — an open-only announcement misses this.
@@ -2896,7 +2913,7 @@ describe('Selector', () => {
const trigger = screen.getByRole('combobox', {name: 'Fruit'});
expect(trigger).toHaveAttribute('aria-busy', 'true');
- expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+ expectSilentBusySpinner();
await user.click(trigger);
expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 81e4a1aeb2..6e84970591 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -87,6 +87,7 @@ import {
} from '../Field/fieldParts';
import {composeEventHandlers} from '../utils/composeEventHandlers';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
@@ -1047,6 +1048,9 @@ export function Selector<T extends SelectorOptionType>(
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(normalizedValue);
const isBusy = isLoading || optimisticValue !== normalizedValue;
+ // The busy Spinner is decorative; this control announces its busy start
+ // (spec:AST-086 FR8).
+ useBusyAnnouncement(isBusy, t('@astryx.spinner.loading'), triggerRef);
const announce = useAnnounce();
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
@@ -2038,7 +2042,7 @@ export function Selector<T extends SelectorOptionType>(
{htmlName != null && !isDisabled && (
<input type="hidden" name={htmlName} value={value ?? ''} />
)}
- {isBusy && <Spinner size="sm" />}
+ {isBusy && <Spinner size="sm" aria-hidden="true" />}
{hasClear && value != null && !isDisabled && !isEffectivelyReadOnly && (
<InternalInputClearButton
{...keepOpenProps}
diff --git a/packages/core/src/TextArea/TextArea.test.tsx b/packages/core/src/TextArea/TextArea.test.tsx
index d6f33a8d7c..ec05feab9b 100644
--- a/packages/core/src/TextArea/TextArea.test.tsx
+++ b/packages/core/src/TextArea/TextArea.test.tsx
@@ -55,6 +55,14 @@ beforeEach(() => {
// accessibility tree. Use hidden: true to find it.
const h = {hidden: true} as const;
+/** A busy control's Spinner is decorative and silent (spec:AST-086 FR8). */
+function expectSilentBusySpinner() {
+ const spinner = document.querySelector('.astryx-spinner');
+ expect(spinner).not.toBeNull();
+ expect(spinner).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.queryByRole('status', {name: 'Loading'})).toBeNull();
+}
+
describe('TextArea', () => {
it('renders with label', () => {
render(<TextArea label="Description" value="" onChange={() => {}} />);
@@ -348,7 +356,7 @@ describe('TextArea', () => {
);
// Matches the other inputs: spinner (role="status") and the status icon
// render side by side in the end slot, not mutually exclusively.
- expect(screen.getByRole('status')).toBeInTheDocument();
+ expectSilentBusySpinner();
// Status icon svg is also present alongside the spinner.
expect(container.querySelectorAll('svg').length).toBeGreaterThan(0);
});
diff --git a/packages/core/src/TextArea/TextArea.tsx b/packages/core/src/TextArea/TextArea.tsx
index acd78d23f3..bcb02cb8fe 100644
--- a/packages/core/src/TextArea/TextArea.tsx
+++ b/packages/core/src/TextArea/TextArea.tsx
@@ -63,6 +63,7 @@ import {characterCount} from '../utils/characters';
import {useTranslator} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
const COUNTER_WARNING_THRESHOLD = 0.8;
const styles = stylex.create({
@@ -438,6 +439,9 @@ export function TextArea({
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ // The busy Spinner is decorative; this control announces its busy start
+ // (spec:AST-086 FR8).
+ useBusyAnnouncement(isBusy, t('@astryx.spinner.loading'), containerRef);
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
// tooltip listeners attach to the textarea container (which already exists)
@@ -660,7 +664,7 @@ export function TextArea({
/>
{(isBusy || statusIcon) && (
<span {...stylex.props(styles.endSlot)}>
- {isBusy && <Spinner size="sm" />}
+ {isBusy && <Spinner size="sm" aria-hidden="true" />}
{statusIcon}
</span>
)}
diff --git a/packages/core/src/TextInput/TextInput.tsx b/packages/core/src/TextInput/TextInput.tsx
index b35e354cb9..d503a843bf 100644
--- a/packages/core/src/TextInput/TextInput.tsx
+++ b/packages/core/src/TextInput/TextInput.tsx
@@ -118,6 +118,7 @@ import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
export type TextInputType = 'text' | 'password' | 'email';
export interface TextInputProps extends Omit<
@@ -344,6 +345,9 @@ export function TextInput({
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ // The busy Spinner is decorative; this control announces its busy start
+ // (spec:AST-086 FR8).
+ useBusyAnnouncement(isBusy, t('@astryx.spinner.loading'), containerRef);
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
// tooltip listeners attach to the input container (which already exists) and
@@ -506,7 +510,7 @@ export function TextInput({
onClick={handleClear}
/>
)}
- {isBusy && <Spinner size="sm" />}
+ {isBusy && <Spinner size="sm" aria-hidden="true" />}
{statusIcon}
</div>
);
diff --git a/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx b/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx
new file mode 100644
index 0000000000..9c35b74482
--- /dev/null
+++ b/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx
@@ -0,0 +1,190 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file BusyOwnerAnnouncement.test.tsx
+ * @input Uses vitest, @testing-library/react, and the busy controls under test
+ * @output Pins spec:AST-086 FR8 and FR6 for controls that show a busy Spinner
+ * @position Shared contract test: the composed Spinner is silent and the
+ * owning control announces each busy start once through the shared channel
+ */
+
+import {StrictMode, useEffect, useRef, type ReactElement} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {act, render, screen} from '@testing-library/react';
+import {TextInput} from '../TextInput';
+import {TextArea} from '../TextArea';
+import {Selector} from '../Selector';
+import {MultiSelector} from '../MultiSelector';
+
+const announce = vi.fn();
+vi.mock('../hooks/useAnnounce', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useAnnounce: () => announce,
+}));
+
+const OPTIONS = [
+ {label: 'Apple', value: 'apple'},
+ {label: 'Banana', value: 'banana'},
+];
+
+const OWNERS: ReadonlyArray<
+ readonly [string, (isLoading: boolean) => ReactElement]
+> = [
+ [
+ 'TextInput',
+ isLoading => (
+ <TextInput
+ label="Email"
+ value=""
+ onChange={() => {}}
+ isLoading={isLoading}
+ />
+ ),
+ ],
+ [
+ 'TextArea',
+ isLoading => (
+ <TextArea
+ label="Notes"
+ value=""
+ onChange={() => {}}
+ isLoading={isLoading}
+ />
+ ),
+ ],
+ [
+ 'Selector',
+ isLoading => (
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ onChange={() => {}}
+ isLoading={isLoading}
+ />
+ ),
+ ],
+ [
+ 'MultiSelector',
+ isLoading => (
+ <MultiSelector
+ label="Fruits"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ isLoading={isLoading}
+ />
+ ),
+ ],
+];
+
+/** Calls that announced the busy start, ignoring each control's other messages. */
+function busyAnnouncements() {
+ return announce.mock.calls.filter(([message]) => message === 'Loading');
+}
+
+/** The hook picks its route a frame after the busy start; wait for it. */
+async function nextFrame() {
+ await act(
+ async () =>
+ void (await new Promise(resolve => requestAnimationFrame(resolve))),
+ );
+}
+
+function strict(element: ReactElement) {
+ return <StrictMode>{element}</StrictMode>;
+}
+
+beforeEach(() => {
+ announce.mockClear();
+});
+
+describe.each(OWNERS)('%s busy state (spec:AST-086)', (_name, renderOwner) => {
+ it('keeps its Spinner silent: hidden from assistive technology, no live role exposed (FR8)', () => {
+ const {container} = render(renderOwner(true));
+ const spinner = container.querySelector('.astryx-spinner');
+ expect(spinner).not.toBeNull();
+ expect(spinner).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.queryByRole('status', {name: 'Loading'})).toBeNull();
+ });
+
+ it('announces its busy start once through the polite channel, even under StrictMode (FR6, FR8)', async () => {
+ const {rerender} = render(strict(renderOwner(true)));
+ await nextFrame();
+ rerender(strict(renderOwner(true)));
+ await nextFrame();
+ expect(busyAnnouncements()).toEqual([['Loading', 'polite']]);
+ });
+
+ it('announces nothing while idle, and again for each new busy start (FR6)', async () => {
+ const {rerender} = render(renderOwner(false));
+ await nextFrame();
+ expect(busyAnnouncements()).toEqual([]);
+ rerender(renderOwner(true));
+ await nextFrame();
+ rerender(renderOwner(false));
+ rerender(renderOwner(true));
+ await nextFrame();
+ expect(busyAnnouncements()).toEqual([
+ ['Loading', 'polite'],
+ ['Loading', 'polite'],
+ ]);
+ });
+});
+
+describe.each(OWNERS)(
+ '%s busy inside an open native modal (spec:AST-086 Platform support)',
+ (_name, renderOwner) => {
+ // jsdom has no showModal(), so an open dialog never matches `:modal`;
+ // stand in for a dialog opened modally.
+ beforeEach(() => {
+ const matches = Element.prototype.matches;
+ vi.spyOn(Element.prototype, 'matches').mockImplementation(function (
+ this: Element,
+ selector: string,
+ ) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('announces its busy start through a persistent region inside the dialog, not the body-level channel', async () => {
+ const {rerender} = render(<dialog open>{renderOwner(false)}</dialog>);
+ const dialog = document.querySelector('dialog') as HTMLDialogElement;
+ rerender(<dialog open>{renderOwner(true)}</dialog>);
+ await nextFrame();
+ const region = dialog.querySelector('[data-astryx-modal-busy-region]');
+ expect(region).not.toBeNull();
+ expect(region).toHaveAttribute('role', 'status');
+ expect(region).toHaveAttribute('aria-live', 'polite');
+ // Inserted empty, then filled on the next frame (FR3).
+ expect(region).toHaveTextContent('');
+ await nextFrame();
+ expect(region).toHaveTextContent('Loading');
+ expect(busyAnnouncements()).toEqual([]);
+ });
+
+ it('announces inside the dialog when it is already busy as its dialog opens', async () => {
+ // The dialog opens in its own Effect, after the field's Effect has run,
+ // the way Dialog calls showModal().
+ function OpeningDialog() {
+ const ref = useRef<HTMLDialogElement>(null);
+ useEffect(() => {
+ ref.current?.setAttribute('open', '');
+ }, []);
+ return <dialog ref={ref}>{renderOwner(true)}</dialog>;
+ }
+ render(<OpeningDialog />);
+ await nextFrame();
+ await nextFrame();
+ const dialog = document.querySelector('dialog') as HTMLDialogElement;
+ expect(
+ dialog.querySelector('[data-astryx-modal-busy-region]'),
+ ).toHaveTextContent('Loading');
+ expect(busyAnnouncements()).toEqual([]);
+ });
+ },
+);
diff --git a/packages/core/src/hooks/useBusyAnnouncement.ts b/packages/core/src/hooks/useBusyAnnouncement.ts
new file mode 100644
index 0000000000..1279c95775
--- /dev/null
+++ b/packages/core/src/hooks/useBusyAnnouncement.ts
@@ -0,0 +1,100 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useBusyAnnouncement.ts
+ * @input Whether the owning control is busy, the words to announce, and a ref
+ * to an element inside the control
+ * @output Announces each busy start once, through the shared polite channel
+ * or a persistent region inside the open modal dialog holding the control
+ * @position Core a11y hook for controls that show a decorative busy Spinner
+ *
+ * The busy Spinner inside a control is decorative (hidden, no live role); the
+ * control announces its busy state instead (`spec:AST-086` FR8), once per busy
+ * start (FR6): rerenders and StrictMode replay do not repeat it, and settling
+ * re-arms it. While a native modal is open, the body-level channel is not
+ * exposed, so a control inside it announces through one persistent polite
+ * region in that dialog, inserted empty and filled a frame later (Platform
+ * support, FR3).
+ *
+ * SYNC: deliberately NOT exported from /packages/core/src/hooks/index.ts —
+ * this is a shared implementation detail of Astryx's busy controls.
+ */
+
+import {useEffect, useRef, type RefObject} from 'react';
+import {useAnnounce} from './useAnnounce';
+
+const REGION_ATTR = 'data-astryx-modal-busy-region';
+const VISUALLY_HIDDEN_CSS =
+ 'position:absolute;width:1px;height:1px;margin:-1px;padding:0;' +
+ 'overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;';
+const CLEAR_DELAY_MS = 2000; // Matches useAnnounce.
+
+// The pending write and clear of each in-dialog region; a new write cancels
+// them so an earlier message can neither land late nor clear a later one.
+const pendingByRegion = new WeakMap<
+ HTMLElement,
+ {frame: number; timer?: ReturnType<typeof setTimeout>}
+>();
+
+function announceInModal(dialog: HTMLDialogElement, message: string): void {
+ let region = dialog.querySelector<HTMLElement>(`:scope > [${REGION_ATTR}]`);
+ if (region == null) {
+ region = document.createElement('div');
+ region.setAttribute(REGION_ATTR, '');
+ region.setAttribute('role', 'status');
+ region.setAttribute('aria-live', 'polite');
+ region.setAttribute('aria-atomic', 'true');
+ region.style.cssText = VISUALLY_HIDDEN_CSS;
+ dialog.appendChild(region);
+ }
+ const target = region;
+ const previous = pendingByRegion.get(target);
+ if (previous != null) {
+ cancelAnimationFrame(previous.frame);
+ clearTimeout(previous.timer);
+ }
+ target.textContent = '';
+ const pending: {frame: number; timer?: ReturnType<typeof setTimeout>} = {
+ frame: 0,
+ };
+ pending.frame = requestAnimationFrame(() => {
+ target.textContent = message;
+ pending.timer = setTimeout(() => {
+ target.textContent = '';
+ pendingByRegion.delete(target);
+ }, CLEAR_DELAY_MS);
+ });
+ pendingByRegion.set(target, pending);
+}
+
+export function useBusyAnnouncement(
+ isBusy: boolean,
+ message: string,
+ elementRef: RefObject<Element | null>,
+): void {
+ const announce = useAnnounce();
+ const hasAnnouncedRef = useRef(false);
+ useEffect(() => {
+ if (!isBusy) {
+ hasAnnouncedRef.current = false;
+ return;
+ }
+ if (hasAnnouncedRef.current) {
+ return;
+ }
+ // Choose the route a frame later: a Dialog opening in the same commit
+ // calls showModal() in its own Effect, which runs after this one.
+ const frame = requestAnimationFrame(() => {
+ hasAnnouncedRef.current = true;
+ const dialog = elementRef.current?.closest('dialog');
+ if (dialog?.open && dialog.matches(':modal')) {
+ announceInModal(dialog, message);
+ } else {
+ announce(message, 'polite');
+ }
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [announce, elementRef, isBusy, message]);
+}