Skip to content

Commit 831cbcc

Browse files
committed
fix(core): one in-dialog live-region route for owners inside a native modal
Adds useModalAwareAnnounce(elementRef), an internal hook that returns the same announce(message, politeness?) as useAnnounce but, when the element sits inside an open native modal dialog, speaks through a persistent polite or assertive live region inside that dialog (spec:AST-086 FR14), and withdraws from it on an empty message, as useAnnounce does on the shared channel. The shared page-body channel is not exposed to assistive technology while a native modal is open, so an owner that announces its own events from inside a modal sheet needs this route; the first adopter is Tokenizer's experimental touch sheet, in its own change. useBusyAnnouncement, which already announced busy starts this way, now builds on the same announceInModal / enclosingModalDialog; its region attribute becomes data-astryx-modal-live-region="polite". Behavior is unchanged; two test files follow the attribute.
1 parent 2cdf4da commit 831cbcc

6 files changed

Lines changed: 418 additions & 56 deletions

File tree

‎.changeset/modal-aware-announce.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[chore] Busy controls inside an open native modal dialog announce their busy start through a live region the hook that owns it now shares with other in-dialog announcements. The region's internal marker changes from `data-astryx-modal-busy-region` to `data-astryx-modal-live-region="polite"`; no public API and no announced text change.
6+
7+
@imdreamrunner

‎packages/core/src/DateInput/DateInputTouch.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -701,7 +701,7 @@ describe('DateInput — field parity', () => {
701701
expect(sheet).not.toBeNull();
702702
await waitFor(() => {
703703
expect(
704-
sheet!.querySelector('[data-astryx-modal-busy-region]'),
704+
sheet!.querySelector('[data-astryx-modal-live-region="polite"]'),
705705
).toHaveTextContent('Loading');
706706
});
707707
expect(

‎packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,9 @@ describe.each(OWNERS)(
344344
const dialog = document.querySelector('dialog') as HTMLDialogElement;
345345
rerender(<dialog open>{renderOwner(true)}</dialog>);
346346
await nextFrame();
347-
const region = dialog.querySelector('[data-astryx-modal-busy-region]');
347+
const region = dialog.querySelector(
348+
'[data-astryx-modal-live-region="polite"]',
349+
);
348350
expect(region).not.toBeNull();
349351
expect(region).toHaveAttribute('role', 'status');
350352
expect(region).toHaveAttribute('aria-live', 'polite');
@@ -370,7 +372,7 @@ describe.each(OWNERS)(
370372
await nextFrame();
371373
const dialog = document.querySelector('dialog') as HTMLDialogElement;
372374
expect(
373-
dialog.querySelector('[data-astryx-modal-busy-region]'),
375+
dialog.querySelector('[data-astryx-modal-live-region="polite"]'),
374376
).toHaveTextContent('Loading');
375377
expect(busyAnnouncements()).toEqual([]);
376378
});
@@ -436,7 +438,7 @@ describe.each(SEARCH_OWNERS)(
436438
await nextFrame();
437439
const dialog = document.querySelector('dialog') as HTMLDialogElement;
438440
expect(
439-
dialog.querySelector('[data-astryx-modal-busy-region]'),
441+
dialog.querySelector('[data-astryx-modal-live-region="polite"]'),
440442
).toHaveTextContent('Loading');
441443
expect(busyAnnouncements()).toEqual([]);
442444
vi.restoreAllMocks();
@@ -511,7 +513,7 @@ describe.each(SHEET_OWNERS)(
511513
await nextFrame();
512514
await nextFrame();
513515
expect(
514-
sheet!.querySelector('[data-astryx-modal-busy-region]'),
516+
sheet!.querySelector('[data-astryx-modal-live-region="polite"]'),
515517
).toHaveTextContent('Loading');
516518
expect(busyAnnouncements()).toEqual([]);
517519
});
@@ -742,7 +744,7 @@ describe('CommandPalette busy start inside its modal (spec:AST-086 FR8, FR3)', (
742744
return (
743745
document
744746
.querySelector('dialog[open]')
745-
?.querySelector('[data-astryx-modal-busy-region]') ?? null
747+
?.querySelector('[data-astryx-modal-live-region="polite"]') ?? null
746748
);
747749
}
748750

‎packages/core/src/hooks/useBusyAnnouncement.ts‎

Lines changed: 8 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
/**
66
* @file useBusyAnnouncement.ts
77
* @input Whether the owning control is busy, the words to announce, and a ref
8-
* to an element inside the control
8+
* to an element inside the control; the in-dialog route from
9+
* useModalAwareAnnounce
910
* @output Announces each busy start once, through the shared polite channel
1011
* or a persistent region inside the open modal dialog holding the control
1112
* @position Core a11y hook for controls that show a decorative busy Spinner
@@ -14,60 +15,17 @@
1415
* control announces its busy state instead (`spec:AST-086` FR8), once per busy
1516
* start (FR6): rerenders and StrictMode replay do not repeat it, and settling
1617
* re-arms it. While a native modal is open, the body-level channel is not
17-
* exposed, so a control inside it announces through one persistent polite
18-
* region in that dialog, inserted empty and filled a frame later (Platform
19-
* support, FR3).
18+
* exposed, so a control inside it announces through the dialog's persistent
19+
* polite region, inserted empty and filled a frame later (Platform support,
20+
* FR3), through the route useModalAwareAnnounce owns.
2021
*
2122
* SYNC: deliberately NOT exported from /packages/core/src/hooks/index.ts —
2223
* this is a shared implementation detail of Astryx's busy controls.
2324
*/
2425

2526
import {useEffect, useRef, type RefObject} from 'react';
2627
import {useAnnounce} from './useAnnounce';
27-
28-
const REGION_ATTR = 'data-astryx-modal-busy-region';
29-
const VISUALLY_HIDDEN_CSS =
30-
'position:absolute;width:1px;height:1px;margin:-1px;padding:0;' +
31-
'overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;';
32-
const CLEAR_DELAY_MS = 2000; // Matches useAnnounce.
33-
34-
// The pending write and clear of each in-dialog region; a new write cancels
35-
// them so an earlier message can neither land late nor clear a later one.
36-
const pendingByRegion = new WeakMap<
37-
HTMLElement,
38-
{frame: number; timer?: ReturnType<typeof setTimeout>}
39-
>();
40-
41-
function announceInModal(dialog: HTMLDialogElement, message: string): void {
42-
let region = dialog.querySelector<HTMLElement>(`:scope > [${REGION_ATTR}]`);
43-
if (region == null) {
44-
region = document.createElement('div');
45-
region.setAttribute(REGION_ATTR, '');
46-
region.setAttribute('role', 'status');
47-
region.setAttribute('aria-live', 'polite');
48-
region.setAttribute('aria-atomic', 'true');
49-
region.style.cssText = VISUALLY_HIDDEN_CSS;
50-
dialog.appendChild(region);
51-
}
52-
const target = region;
53-
const previous = pendingByRegion.get(target);
54-
if (previous != null) {
55-
cancelAnimationFrame(previous.frame);
56-
clearTimeout(previous.timer);
57-
}
58-
target.textContent = '';
59-
const pending: {frame: number; timer?: ReturnType<typeof setTimeout>} = {
60-
frame: 0,
61-
};
62-
pending.frame = requestAnimationFrame(() => {
63-
target.textContent = message;
64-
pending.timer = setTimeout(() => {
65-
target.textContent = '';
66-
pendingByRegion.delete(target);
67-
}, CLEAR_DELAY_MS);
68-
});
69-
pendingByRegion.set(target, pending);
70-
}
28+
import {announceInModal, enclosingModalDialog} from './useModalAwareAnnounce';
7129

7230
export function useBusyAnnouncement(
7331
isBusy: boolean,
@@ -88,8 +46,8 @@ export function useBusyAnnouncement(
8846
// calls showModal() in its own Effect, which runs after this one.
8947
const frame = requestAnimationFrame(() => {
9048
hasAnnouncedRef.current = true;
91-
const dialog = elementRef.current?.closest('dialog');
92-
if (dialog?.open && dialog.matches(':modal')) {
49+
const dialog = enclosingModalDialog(elementRef.current);
50+
if (dialog != null) {
9351
announceInModal(dialog, message);
9452
} else {
9553
announce(message, 'polite');
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
/**
3+
* @file useModalAwareAnnounce.test.tsx
4+
* @input Uses vitest, Testing Library, useModalAwareAnnounce, useAnnounce
5+
* @output Tests the route choice: the shared channel outside a modal, a
6+
* persistent region inside an open native modal dialog (spec:AST-086 FR14)
7+
* @position Core hook tests
8+
*/
9+
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
10+
import {act, fireEvent, render, screen} from '@testing-library/react';
11+
import {useRef} from 'react';
12+
import {useModalAwareAnnounce} from './useModalAwareAnnounce';
13+
import {__resetLiveRegionsForTest} from './useAnnounce';
14+
15+
function Owner({message, urgency}: {message: string; urgency?: 'assertive'}) {
16+
const ref = useRef<HTMLDivElement>(null);
17+
const announce = useModalAwareAnnounce(ref);
18+
return (
19+
<div ref={ref}>
20+
<button type="button" onClick={() => announce(message, urgency)}>
21+
Say
22+
</button>
23+
</div>
24+
);
25+
}
26+
27+
function WithdrawingOwner() {
28+
const ref = useRef<HTMLDivElement>(null);
29+
const announce = useModalAwareAnnounce(ref);
30+
return (
31+
<div ref={ref}>
32+
<button type="button" onClick={() => announce('Added Design')}>
33+
Say
34+
</button>
35+
<button type="button" onClick={() => announce('')}>
36+
Withdraw
37+
</button>
38+
</div>
39+
);
40+
}
41+
42+
const shared = () =>
43+
document.querySelector('[data-astryx-live-region="polite"]');
44+
const sharedAssertive = () =>
45+
document.querySelector('[data-astryx-live-region="assertive"]');
46+
47+
// jsdom has no showModal(), so an open dialog never matches `:modal`; stand
48+
// in for a dialog opened modally.
49+
function standInForModal() {
50+
const matches = Element.prototype.matches;
51+
vi.spyOn(Element.prototype, 'matches').mockImplementation(function (
52+
this: Element,
53+
selector: string,
54+
) {
55+
return selector === ':modal'
56+
? this instanceof HTMLDialogElement && this.open
57+
: matches.call(this, selector);
58+
});
59+
}
60+
61+
async function nextFrame() {
62+
await act(
63+
async () =>
64+
new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
65+
);
66+
}
67+
68+
beforeEach(() => {
69+
__resetLiveRegionsForTest();
70+
});
71+
afterEach(() => {
72+
vi.restoreAllMocks();
73+
});
74+
75+
describe('useModalAwareAnnounce', () => {
76+
it('uses the shared channel outside a modal', async () => {
77+
render(<Owner message="Added Design" />);
78+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
79+
await nextFrame();
80+
expect(shared()).toHaveTextContent('Added Design');
81+
expect(
82+
document.querySelector('[data-astryx-modal-live-region]'),
83+
).toBeNull();
84+
});
85+
86+
it('uses the shared channel inside a dialog that is open but not modal', async () => {
87+
render(
88+
<dialog open>
89+
<Owner message="Added Design" />
90+
</dialog>,
91+
);
92+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
93+
await nextFrame();
94+
expect(shared()).toHaveTextContent('Added Design');
95+
expect(
96+
document.querySelector('[data-astryx-modal-live-region]'),
97+
).toBeNull();
98+
});
99+
100+
it('announces inside an open modal dialog through a persistent polite region, not the shared channel (FR14)', async () => {
101+
standInForModal();
102+
render(
103+
<dialog open>
104+
<Owner message="Added Design" />
105+
</dialog>,
106+
);
107+
const dialog = document.querySelector('dialog')!;
108+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
109+
// Inserted empty (FR3), filled a frame later.
110+
const region = dialog.querySelector(
111+
':scope > [data-astryx-modal-live-region="polite"]',
112+
)!;
113+
expect(region).toBeInTheDocument();
114+
expect(region).toHaveAttribute('role', 'status');
115+
expect(region).toHaveAttribute('aria-live', 'polite');
116+
expect(region).toHaveAttribute('aria-atomic', 'true');
117+
expect(region).toHaveTextContent('');
118+
await nextFrame();
119+
expect(region).toHaveTextContent('Added Design');
120+
expect(shared()?.textContent ?? '').toBe('');
121+
// The region persists across messages (FR3) and repeats the same words
122+
// for a new occasion (FR6).
123+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
124+
expect(region).toHaveTextContent('');
125+
await nextFrame();
126+
expect(region).toHaveTextContent('Added Design');
127+
expect(
128+
dialog.querySelectorAll('[data-astryx-modal-live-region="polite"]'),
129+
).toHaveLength(1);
130+
});
131+
132+
it('keeps an assertive region apart from the polite one (FR5)', async () => {
133+
standInForModal();
134+
render(
135+
<dialog open>
136+
<Owner message="Could not add" urgency="assertive" />
137+
</dialog>,
138+
);
139+
const dialog = document.querySelector('dialog')!;
140+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
141+
await nextFrame();
142+
const region = dialog.querySelector(
143+
':scope > [data-astryx-modal-live-region="assertive"]',
144+
)!;
145+
expect(region).toHaveAttribute('role', 'alert');
146+
expect(region).toHaveTextContent('Could not add');
147+
expect(
148+
dialog.querySelector('[data-astryx-modal-live-region="polite"]'),
149+
).toBeNull();
150+
expect(sharedAssertive()?.textContent ?? '').toBe('');
151+
});
152+
153+
it("announce('') inside a modal withdraws the dialog region's pending and shown text", async () => {
154+
vi.useFakeTimers();
155+
try {
156+
standInForModal();
157+
render(
158+
<dialog open>
159+
<WithdrawingOwner />
160+
</dialog>,
161+
);
162+
const dialog = document.querySelector('dialog')!;
163+
// Pending write cancelled: nothing lands.
164+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
165+
fireEvent.click(screen.getByRole('button', {name: 'Withdraw'}));
166+
await act(async () => {
167+
await vi.advanceTimersByTimeAsync(50);
168+
});
169+
const region = dialog.querySelector(
170+
'[data-astryx-modal-live-region="polite"]',
171+
)!;
172+
expect(region).toHaveTextContent('');
173+
// Shown text cleared at once, not after the two-second delay.
174+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
175+
await act(async () => {
176+
await vi.advanceTimersByTimeAsync(50);
177+
});
178+
expect(region).toHaveTextContent('Added Design');
179+
fireEvent.click(screen.getByRole('button', {name: 'Withdraw'}));
180+
expect(region).toHaveTextContent('');
181+
expect(region).toBeInTheDocument();
182+
// The shared channel was never touched.
183+
expect(shared()?.textContent ?? '').toBe('');
184+
} finally {
185+
vi.useRealTimers();
186+
}
187+
});
188+
189+
it('clears the in-dialog region shortly after announcing', async () => {
190+
vi.useFakeTimers();
191+
try {
192+
standInForModal();
193+
render(
194+
<dialog open>
195+
<Owner message="Added Design" />
196+
</dialog>,
197+
);
198+
const dialog = document.querySelector('dialog')!;
199+
fireEvent.click(screen.getByRole('button', {name: 'Say'}));
200+
await act(async () => {
201+
await vi.advanceTimersByTimeAsync(20);
202+
});
203+
const region = dialog.querySelector(
204+
'[data-astryx-modal-live-region="polite"]',
205+
)!;
206+
expect(region).toHaveTextContent('Added Design');
207+
await act(async () => {
208+
await vi.advanceTimersByTimeAsync(2100);
209+
});
210+
expect(region).toHaveTextContent('');
211+
expect(region).toBeInTheDocument();
212+
} finally {
213+
vi.useRealTimers();
214+
}
215+
});
216+
});

0 commit comments

Comments
 (0)