Skip to content

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

TypeScript

fix(MultiSelector): a search status the next keystroke replaces is withdrawn, not joined (#8640)

Christopher Chedeaudb5a9936fb47
diff --git a/.changeset/announce-has-replace.md b/.changeset/announce-has-replace.md
new file mode 100644
index 0000000000..af82854a15
--- /dev/null
+++ b/.changeset/announce-has-replace.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] useAnnounce takes an optional `{hasReplace: true}`. An instance created with it states one current state, such as a search's result count: each message it writes withdraws that instance's previous message while it has not been spoken yet, whatever their politeness, and is spoken at its own politeness, so input faster than a frame (a barcode scanner, dictation, automation) says only the latest. Messages from other instances, and from instances without it, still join. MultiSelector sends its result count, its create row and its empty-search message through such an instance, so fast typing no longer says `1 result Create "Urg" Create "Urge" …`; its selection changes keep their own instance and still join. This follows spec:AST-086 FR9 and FR13 (#9070).
+
+@vjeux
diff --git a/packages/core/src/MultiSelector/CreateRow.a11y.chromium.spec.ts b/packages/core/src/MultiSelector/CreateRow.a11y.chromium.spec.ts
index 037ecd463c..66c349048d 100644
--- a/packages/core/src/MultiSelector/CreateRow.a11y.chromium.spec.ts
+++ b/packages/core/src/MultiSelector/CreateRow.a11y.chromium.spec.ts
@@ -78,10 +78,11 @@ async function politeSince(page: Page, since: number): Promise<string> {
}
/**
- * Matches a polite region whose newest message is `message`. Messages written
- * before the region exposes the previous one are joined in order
- * (spec:AST-086 FR9), so typing faster than a frame can leave the previous
- * keystroke's message ahead of the one under test.
+ * Matches a polite region whose newest message is `message`. Messages from
+ * different announcers written before the region exposes the previous one are
+ * joined in order (spec:AST-086 FR9), so the creation can follow a search
+ * status still waiting. The search's own statuses replace each other instead
+ * (its `hasReplace` announcer), so they are read whole.
*/
function newestMessage(message: string): RegExp {
const escaped = message.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -108,9 +109,7 @@ test('the create row is announced as it appears and the highlight survives it va
// "Bu": a partial match plus the create row above it.
await search.pressSequentially('Bu');
await expect(page.getByRole('option')).toHaveText(['Create "Bu"', 'Bug']);
- await expect
- .poll(async () => politeSince(page, 0))
- .toMatch(newestMessage('1 result'));
+ await expect.poll(async () => politeSince(page, 0)).toBe('1 result');
// Highlight the create row, then type the letter that makes it vanish: the
// highlight must not be left pointing at a row that no longer exists.
@@ -132,7 +131,7 @@ test('the create row is announced as it appears and the highlight survives it va
await expect(page.getByRole('option')).toHaveText(['Create "Urgent"']);
await expect
.poll(async () => politeSince(page, beforeUrgent))
- .toMatch(newestMessage('Create "Urgent"'));
+ .toBe('Create "Urgent"');
// Enter commits: the caller adds the option, the search clears, and the new
// label is a real row.
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index b4bf70c0f2..9070e58ac2 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -34,6 +34,7 @@ import {
type MultiSelectorChange,
} from './MultiSelector';
import {useRef, useState} from 'react';
+import {Dialog} from '../Dialog/Dialog';
import {Icon} from '../Icon';
import {InternationalizationProvider} from '../i18n';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
@@ -3837,6 +3838,157 @@ describe('MultiSelector hasCreate', () => {
expect(search).toHaveValue('');
});
+ it('says only the latest status when several keystrokes land in one frame (spec:AST-086 FR9)', async () => {
+ // A barcode scanner, dictation or automation types faster than a frame:
+ // each keystroke states the panel's status through the search's
+ // `hasReplace` announcer, so a status the next keystroke replaces before
+ // it is exposed is withdrawn, not joined.
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={['bug']}
+ onChange={() => {}}
+ hasSearch
+ hasCreate
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ for (const value of ['Ur', 'Urg', 'Urge', 'Urgent']) {
+ fireEvent.change(search, {target: {value}});
+ }
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+ expect(politeRegion()?.textContent).toBe('Create "Urgent"');
+ });
+
+ it('says only the empty panel’s message when the next keystroke in the frame empties the panel (spec:AST-086 FR13)', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ // "Fe" matches Feature; "Fex" matches nothing, in the same frame.
+ fireEvent.change(search, {target: {value: 'Fe'}});
+ fireEvent.change(search, {target: {value: 'Fex'}});
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+ expect(politeRegion()?.textContent).toBe('No results found');
+ });
+
+ it('says only the count when the next keystroke in the frame fills an empty panel (spec:AST-086 FR13)', async () => {
+ // The empty panel's message comes from the search's `hasReplace`
+ // announcer too, so the count that follows it in the frame replaces it.
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ fireEvent.change(search, {target: {value: 'Fex'}});
+ fireEvent.change(search, {target: {value: 'Fe'}});
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+ expect(politeRegion()?.textContent).toBe('1 result');
+ });
+
+ it('says only the empty panel’s message from inside a modal when the next keystroke in the frame empties the panel (spec:AST-086 FR14)', async () => {
+ // Inside an open modal the search's announcer writes to the modal's own
+ // container, which replaces the same way.
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ this.dataset.modal = 'true';
+ });
+ // The file's own `matches` stand-in (for :popover-open) sits on
+ // HTMLElement.prototype; :modal is added on top of it.
+ const matches = HTMLElement.prototype.matches;
+ vi.spyOn(HTMLElement.prototype, 'matches').mockImplementation(function (
+ this: HTMLElement,
+ selector: string,
+ ) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement &&
+ this.open &&
+ this.dataset.modal === 'true'
+ : matches.call(this, selector);
+ });
+ const user = userEvent.setup();
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit labels">
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Edit labels'});
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ fireEvent.change(search, {target: {value: 'Fe'}});
+ fireEvent.change(search, {target: {value: 'Fex'}});
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+ expect(
+ dialog.querySelector(':scope > [data-astryx-modal-live-region="polite"]')
+ ?.textContent,
+ ).toBe('No results found');
+ });
+
+ it('still says a selection change and a result count from the same frame: each has its own announcer (spec:AST-086 FR9)', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+ fireEvent.click(screen.getByRole('option', {name: 'Bug', hidden: true}));
+ fireEvent.change(screen.getByRole('combobox', h), {
+ target: {value: 'Fe'},
+ });
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+ expect(politeRegion()?.textContent).toBe('1 of 3 selected 1 result');
+ });
+
it('a plain toggle passes no descriptor, so a one-argument handler is unchanged', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 47114eb19c..f185a08203 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -1547,21 +1547,27 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// Announce the filtered result count from the query-change handler (matching
// BaseTypeahead) rather than a reactive effect: computing the count for the
// next query here fires the announcement exactly once per keystroke and does
- // not re-speak on unrelated re-renders. Reuses the announce instance shared
- // with the selection-count announcements above.
+ // not re-speak on unrelated re-renders. The count, the create row and the
+ // empty panel's message state one thing, how the search ended, so they go
+ // through the search's own `hasReplace` announcer: one the next keystroke
+ // replaces before it is exposed is withdrawn rather than joined
+ // (`spec:AST-086` FR9, FR13), and keystrokes arriving within one frame,
+ // from a scanner, dictation or automation, say only the last query's.
+ // Selection changes keep the plain announcer above, so they still join.
+ const announceSearch = useAnnounce({hasReplace: true});
const handleSearchChange = useCallback(
(nextQuery: string) => {
setSearchQuery(nextQuery);
if (nextQuery.length === 0) {
// Emptying the query clears the region rather than announcing a count.
- announce('');
+ announceSearch('');
return;
}
// While isLoading the panel deliberately shows nothing, so announcing a
// result would put a claim in the one channel the screen has gone quiet
// for.
if (isLoading) {
- announce('');
+ announceSearch('');
return;
}
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
@@ -1571,7 +1577,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// The create row is the one result on screen, so the panel is not
// empty and the rendered-message route below stays silent; say the
// row.
- announce(
+ announceSearch(
t('@astryx.multiSelector.createOption', {query: nextCreateQuery}),
);
return;
@@ -1582,9 +1588,9 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// keystroke — an async load landing with nothing that matches.
return;
}
- announce(t('@astryx.multiSelector.resultCount', {count}));
+ announceSearch(t('@astryx.multiSelector.resultCount', {count}));
},
- [announce, isLoading, selectableItems, getCreateQuery, t],
+ [announceSearch, isLoading, selectableItems, getCreateQuery, t],
);
// The panel's empty message is role="presentation" — role="listbox" permits
@@ -1609,7 +1615,12 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const realItemCount = sortedItems.length - leadingCount;
const isPanelEmpty =
surface.isOpen && !isLoading && realItemCount === 0 && !hasCreateRow;
- useAnnounceRenderedText(emptyStateRef, isPanelEmpty, searchQuery);
+ // Through the search's announcer: the empty panel is how the search ended,
+ // so it and the count replace each other while not yet exposed
+ // (`spec:AST-086` FR13).
+ useAnnounceRenderedText(emptyStateRef, isPanelEmpty, searchQuery, {
+ announce: announceSearch,
+ });
// Handle toggle
// Clear all selected values. Shared by the clear button and the keyboard
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 5ee93b5cb4..051bca2be4 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -15,7 +15,11 @@ export {hasActiveFocusTrapEscape, useFocusTrap} from './useFocusTrap';
export type {UseFocusTrapOptions, UseFocusTrapReturn} from './useFocusTrap';
export {useAnnounce} from './useAnnounce';
-export type {AnnounceFn, AnnouncePoliteness} from './useAnnounce';
+export type {
+ AnnounceFn,
+ AnnouncePoliteness,
+ UseAnnounceOptions,
+} from './useAnnounce';
export {useClipboard} from './useClipboard';
export type {UseClipboardOptions, UseClipboardReturn} from './useClipboard';
diff --git a/packages/core/src/hooks/modalAnnounce.ts b/packages/core/src/hooks/modalAnnounce.ts
index 24c944d847..4f52efc695 100644
--- a/packages/core/src/hooks/modalAnnounce.ts
+++ b/packages/core/src/hooks/modalAnnounce.ts
@@ -14,7 +14,11 @@
* handed to the channel exposed then, or held while an exiting modal still
* covers everything, and released at its real close; a covered modal is
* not written to; a caller inside a modal being presented in this commit
- * waits one frame for the route. Loaded only by ModalAnnounceProvider, so
+ * waits one frame for the route. Words move with their announcers'
+ * receipts, one delivery per announcer, so an announcer can take back its
+ * own share while it waits wherever it went: a `hasReplace` instance's
+ * next message (FR9), a busy start overtaken by its outcome (FR8). Loaded
+ * only by ModalAnnounceProvider, so
* a component that calls useAnnounce and renders no modal does not carry
* it.
*
@@ -25,14 +29,18 @@ import {
announceMessage,
clearModalRegion,
clearRegion,
+ forwardWaiting,
+ handleOf,
installModalRoute,
isOpenModal,
modalRegion,
- unexposedMessages,
- withdrawFromModalRegion,
+ unexposedWords,
writeModalRegion,
type AnnouncePoliteness,
+ type AnnounceReceipt,
type ModalAnnounceScope,
+ type WaitingWords,
+ type WithdrawAnnouncement,
} from './useAnnounce';
/**
@@ -153,20 +161,58 @@ function isAnyModalOpen(): boolean {
// the accessibility tree for its exit but is still an open native modal, or
// such a dialog covers the channel they would go to, so nothing is exposed
// yet. They are delivered when a dialog closes (or theirs is exposed again).
-const held = new Map<HTMLDialogElement, Record<AnnouncePoliteness, string[]>>();
+// Each text keeps its announcers' receipts, so one taking its share back
+// leaves it for the others, and a receipt follows the words when they are
+// released; an entry is gone once delivered, so a receipt never reaches
+// equal words held later.
+interface HeldWords extends WaitingWords {
+ readonly receipts: AnnounceReceipt[];
+}
+const held = new Map<
+ HTMLDialogElement,
+ Record<AnnouncePoliteness, HeldWords[]>
+>();
+/** Hold `message` for `dialog`, for the announcer `receipt` stands for. */
function hold(
dialog: HTMLDialogElement,
message: string,
politeness: AnnouncePoliteness,
+ receipt: AnnounceReceipt,
): void {
let slot = held.get(dialog);
if (slot == null) {
slot = {polite: [], assertive: []};
held.set(dialog, slot);
}
- if (!slot[politeness].includes(message)) {
- slot[politeness].push(message);
+ let words = slot[politeness].find(entry => entry.text === message);
+ if (words == null) {
+ words = {text: message, receipts: []};
+ slot[politeness].push(words);
+ }
+ words.receipts.push(receipt);
+ const entry = words;
+ receipt.withdraw = () => dropHeldShare(dialog, politeness, entry, receipt);
+}
+
+/** One announcer takes back its share of `words`, while they are held. */
+function dropHeldShare(
+ dialog: HTMLDialogElement,
+ politeness: AnnouncePoliteness,
+ words: HeldWords,
+ receipt: AnnounceReceipt,
+): void {
+ const slot = held.get(dialog);
+ const at = words.receipts.indexOf(receipt);
+ if (slot == null || !slot[politeness].includes(words) || at < 0) {
+ return;
+ }
+ words.receipts.splice(at, 1);
+ if (words.receipts.length === 0) {
+ slot[politeness] = slot[politeness].filter(entry => entry !== words);
+ if (slot.polite.length === 0 && slot.assertive.length === 0) {
+ held.delete(dialog);
+ }
}
}
@@ -193,15 +239,13 @@ function releaseHeld(dialog: HTMLDialogElement): void {
}
held.delete(dialog);
for (const politeness of ['polite', 'assertive'] as const) {
- if (slot[politeness].length > 0) {
- const message = slot[politeness].join(' ');
- if (isExposed(dialog)) {
- announceInModalRouted(dialog, message, politeness);
- } else {
- // Holds again if still nothing is exposed.
- deliverBeyond(dialog, message, politeness);
- }
- }
+ // One delivery per announcer, so each receipt follows its words.
+ forwardWaiting(slot[politeness], text =>
+ isExposed(dialog)
+ ? announceInModalRouted(dialog, text, politeness)
+ : // Holds again if still nothing is exposed.
+ deliverBeyond(dialog, text, politeness),
+ );
}
}
@@ -221,20 +265,20 @@ function deliverBeyond(
dialog: HTMLDialogElement,
message: string,
politeness: AnnouncePoliteness,
-): void {
+): WithdrawAnnouncement | null {
const next = nextExposedChannel(dialog);
if (next === 'covered' || (next == null && isAnyModalOpen())) {
// An exiting modal — this one, or one above the next candidate — is
// still open and covers what is beneath it: nothing is exposed until
// it closes.
- hold(dialog, message, politeness);
- return;
+ const receipt: AnnounceReceipt = {withdraw: null};
+ hold(dialog, message, politeness, receipt);
+ return handleOf(receipt);
}
if (next != null) {
- announceInModalRouted(next, message, politeness);
- return;
+ return announceInModalRouted(next, message, politeness);
}
- announceMessage(message, politeness);
+ return announceMessage(message, politeness);
}
/**
@@ -245,10 +289,11 @@ function deliverBeyond(
*/
export function handOffUnexposed(dialog: HTMLDialogElement): void {
for (const politeness of ['polite', 'assertive'] as const) {
- const waiting = takeUnexposed(dialog, politeness);
- if (waiting.length > 0) {
- deliverBeyond(dialog, waiting.join(' '), politeness);
- }
+ // One delivery per announcer, so each receipt follows its words and a
+ // `hasReplace` instance's next message can still take its own back.
+ forwardWaiting(takeUnexposed(dialog, politeness), text =>
+ deliverBeyond(dialog, text, politeness),
+ );
}
}
@@ -267,16 +312,19 @@ function withdrawFromModal(
dropHeld(dialog, politeness);
}
-/** Take the unexposed messages out of a dialog's region, clearing it. */
+/**
+ * Take the unexposed words out of a dialog's region, with their receipts,
+ * clearing it.
+ */
function takeUnexposed(
dialog: HTMLDialogElement,
politeness: AnnouncePoliteness,
-): string[] {
+): WaitingWords[] {
const region = modalRegion(dialog, politeness);
if (region == null) {
return [];
}
- const waiting = unexposedMessages(region);
+ const waiting = unexposedWords(region);
clearModalRegion(dialog, politeness);
return waiting;
}
@@ -285,10 +333,9 @@ function announceInModalRouted(
dialog: HTMLDialogElement,
message: string,
politeness: AnnouncePoliteness = 'polite',
-): void {
+): WithdrawAnnouncement | null {
if (!isExposed(dialog)) {
- deliverBeyond(dialog, message, politeness);
- return;
+ return deliverBeyond(dialog, message, politeness);
}
const top = topExposedModal();
if (top != null && top !== dialog && presented.includes(dialog)) {
@@ -296,35 +343,23 @@ function announceInModalRouted(
// one closes, and a message announced meanwhile is not heard — the
// container is clear before this modal is on top again.
clearModalRegion(dialog, politeness);
- return;
+ return null;
}
- writeModalRegion(dialog, message, politeness, {
+ return writeModalRegion(dialog, message, politeness, {
isExposed: () => isExposed(dialog),
- redirect: joined => deliverBeyond(dialog, joined, politeness),
+ redirect: waiting =>
+ forwardWaiting(waiting, text => deliverBeyond(dialog, text, politeness)),
});
}
-function withdrawFromModalPendingRouted(
- dialog: HTMLDialogElement,
- message: string,
- politeness: AnnouncePoliteness,
-): void {
- withdrawFromModalRegion(dialog, message, politeness);
- const slot = held.get(dialog);
- if (slot != null) {
- slot[politeness] = slot[politeness].filter(text => text !== message);
- if (slot.polite.length === 0 && slot.assertive.length === 0) {
- held.delete(dialog);
- }
- }
-}
-
// Messages from callers whose enclosing modal is being presented in this
// commit, waiting one frame for the route; an empty message among them
// withdraws the earlier ones of its urgency, as it would on a channel.
+// Each message keeps a receipt per announcer: before the frame, taking it
+// back drops that announcer's share; the frame points it at its write.
interface Deferred {
frame: number;
- messages: Record<AnnouncePoliteness, string[]>;
+ words: Record<AnnouncePoliteness, HeldWords[]>;
clears: Record<AnnouncePoliteness, boolean>;
}
const deferredByScope = new WeakMap<ModalAnnounceScope, Deferred>();
@@ -333,7 +368,7 @@ function deferUntilPresented(
scope: ModalAnnounceScope,
message: string,
politeness: AnnouncePoliteness,
-): void {
+): WithdrawAnnouncement | null {
let deferred = deferredByScope.get(scope);
if (deferred == null) {
const created: Deferred = {
@@ -348,29 +383,54 @@ function deferUntilPresented(
clearRegion(urgency);
}
}
- for (const text of created.messages[urgency]) {
- if (opened != null) {
- announceInModalRouted(opened, text, urgency);
- } else {
- announceMessage(text, urgency);
- }
- }
+ // One write per announcer, so each can take back its own share.
+ forwardWaiting(created.words[urgency], text =>
+ opened != null
+ ? announceInModalRouted(opened, text, urgency)
+ : announceMessage(text, urgency),
+ );
}
}),
- messages: {polite: [], assertive: []},
+ words: {polite: [], assertive: []},
clears: {polite: false, assertive: false},
};
deferred = created;
deferredByScope.set(scope, deferred);
}
+ const waiting = deferred;
if (!message) {
- deferred.messages[politeness] = [];
- deferred.clears[politeness] = true;
- return;
+ // Taken back: the receipts of what waited have nothing left to take.
+ for (const words of waiting.words[politeness]) {
+ for (const receipt of words.receipts) {
+ receipt.withdraw = null;
+ }
+ }
+ waiting.words[politeness] = [];
+ waiting.clears[politeness] = true;
+ return null;
}
- if (!deferred.messages[politeness].includes(message)) {
- deferred.messages[politeness].push(message);
+ let words = waiting.words[politeness].find(entry => entry.text === message);
+ if (words == null) {
+ words = {text: message, receipts: []};
+ waiting.words[politeness].push(words);
}
+ const entry = words;
+ const receipt: AnnounceReceipt = {withdraw: null};
+ receipt.withdraw = () => {
+ // Before the frame: drop this announcer's share of the waiting words.
+ const at = entry.receipts.indexOf(receipt);
+ if (at < 0) {
+ return;
+ }
+ entry.receipts.splice(at, 1);
+ if (entry.receipts.length === 0) {
+ waiting.words[politeness] = waiting.words[politeness].filter(
+ other => other !== entry,
+ );
+ }
+ };
+ entry.receipts.push(receipt);
+ return handleOf(receipt);
}
/**
@@ -400,7 +460,7 @@ function announceFromScope(
scope: ModalAnnounceScope,
message: string,
politeness: AnnouncePoliteness,
-): void {
+): WithdrawAnnouncement | null {
if (isBeingPresented(scope)) {
// Announced in the commit that opens the enclosing modal — a field error
// inside `{isOpen && <Dialog isOpen>}`, alone or inside an already-open
@@ -411,8 +471,7 @@ function announceFromScope(
// (FR9). A caller inside a modal that is meant to be closed (its content
// stays mounted) is not waiting for anything: it takes the route of
// where it is now, joined with the frame's other messages.
- deferUntilPresented(scope, message, politeness);
- return;
+ return deferUntilPresented(scope, message, politeness);
}
const dialog = enclosingOpenModal(scope);
if (!message) {
@@ -423,17 +482,15 @@ function announceFromScope(
} else {
clearRegion(politeness);
}
- return;
+ return null;
}
if (dialog != null) {
- announceInModalRouted(dialog, message, politeness);
- return;
+ return announceInModalRouted(dialog, message, politeness);
}
- announceMessage(message, politeness);
+ return announceMessage(message, politeness);
}
installModalRoute({
announce: announceFromScope,
announceInModal: announceInModalRouted,
- withdrawFromModalPending: withdrawFromModalPendingRouted,
});
diff --git a/packages/core/src/hooks/useAnnounce.doc.mjs b/packages/core/src/hooks/useAnnounce.doc.mjs
index 395c523251..3a11bc7913 100644
--- a/packages/core/src/hooks/useAnnounce.doc.mjs
+++ b/packages/core/src/hooks/useAnnounce.doc.mjs
@@ -17,14 +17,31 @@ export const docs = {
'assertive',
'visually hidden',
'wcag',
+ 'replace',
+ 'result count',
+ ],
+ params: [
+ {
+ name: 'options',
+ type: 'UseAnnounceOptions',
+ description: 'Configuration object.',
+ required: false,
+ },
+ {
+ name: 'options.hasReplace',
+ type: 'boolean',
+ description:
+ "The instance states one current state, such as a search's result count: each message it writes withdraws the instance's previous message while that one has not been spoken yet, whatever their politeness, and is spoken at its own politeness. A message already spoken stays. Messages from other instances, and from instances without hasReplace, still join. Give each state a component reports its own instance, for example one for the result count and one for selection changes.",
+ default: 'false',
+ required: false,
+ },
],
- params: [],
returns: [
{
name: 'announce',
type: '(message: string, politeness?: "polite" | "assertive") => void',
description:
- 'Speaks a message through the live region the caller can be heard from: the shared one on the page body, or, when the calling component is rendered inside an open Astryx modal (Dialog, modal BottomSheet, modal Drawer, Lightbox, MobileNav, CommandPalette), a persistent region inside that modal, since a native modal hides the page-body region from assistive technology. Politeness defaults to "polite"; messages announced in the same frame are joined, in order, into one announcement, and an identical repeat is kept once. An empty message clears any lingering status, including joined messages not yet spoken, instead of announcing.',
+ 'Speaks a message through the live region the caller can be heard from: the shared one on the page body, or, when the calling component is rendered inside an open Astryx modal (Dialog, modal BottomSheet, modal Drawer, Lightbox, MobileNav, CommandPalette), a persistent region inside that modal, since a native modal hides the page-body region from assistive technology. Politeness defaults to "polite"; messages announced in the same frame are joined, in order, into one announcement, and an identical repeat is kept once, except that each message from a hasReplace instance replaces the previous message of that instance not yet spoken. An empty message clears any lingering status, including joined messages not yet spoken, instead of announcing.',
},
],
usage: {
@@ -46,6 +63,11 @@ export const docs = {
description:
'Announce the outcome, not the interaction; "12 results" rather than "search ran".',
},
+ {
+ guidance: true,
+ description:
+ 'Send a value that keeps changing, such as a result count as the user types, through its own useAnnounce({hasReplace: true}) instance, so input faster than a frame says only the latest count.',
+ },
{
guidance: false,
description:
@@ -63,9 +85,14 @@ export const docs = {
export const docsDense = {
description:
'Imperative screen-reader announcements via a visually-hidden live region: the page-body one, or one inside the open Astryx modal the caller is rendered in (a native modal hides the body region). Polite + assertive regions created empty on first use + kept mounted, so announcements are reliable (most AT ignore a live region inserted together w/ its content). Messages auto-clear after ~2s.',
+ paramDescriptions: {
+ options: 'config object.',
+ 'options.hasReplace':
+ "instance states one current state (e.g. a search's result count): each message withdraws the instance's previous one not yet spoken, whatever politeness, spoken at its own; spoken messages stay; other instances + instances w/o hasReplace still join. Default false.",
+ },
returnDescriptions: {
announce:
- 'speaks message through the live region the caller is heard from: page body, or inside the open Astryx modal (Dialog, modal BottomSheet/Drawer, Lightbox, MobileNav, CommandPalette) the calling component is rendered in. politeness defaults "polite"; same-frame messages join in order, identical repeat kept once; empty message clears lingering + not-yet-spoken status.',
+ 'speaks message through the live region the caller is heard from: page body, or inside the open Astryx modal (Dialog, modal BottomSheet/Drawer, Lightbox, MobileNav, CommandPalette) the calling component is rendered in. politeness defaults "polite"; same-frame messages join in order, identical repeat kept once, except a hasReplace instance replaces its own not-yet-spoken message; empty message clears lingering + not-yet-spoken status.',
},
usage: {
description:
@@ -86,6 +113,11 @@ export const docsDense = {
description:
'Announce outcome, not interaction; "12 results", not "search ran".',
},
+ {
+ guidance: true,
+ description:
+ 'Changing value (result count while typing): own useAnnounce({hasReplace: true}) instance, so faster-than-a-frame input says only the latest.',
+ },
{
guidance: false,
description:
diff --git a/packages/core/src/hooks/useAnnounce.replace.test.tsx b/packages/core/src/hooks/useAnnounce.replace.test.tsx
new file mode 100644
index 0000000000..1244d0ce60
--- /dev/null
+++ b/packages/core/src/hooks/useAnnounce.replace.test.tsx
@@ -0,0 +1,516 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useAnnounce.replace.test.tsx
+ * @input Uses vitest, Testing Library, useAnnounce, and an Astryx Dialog and
+ * BottomSheet
+ * @output Proof of spec:AST-086 FR9 and FR14 for `useAnnounce({hasReplace})`:
+ * each message such an instance writes withdraws its previous one while it
+ * is not yet exposed, whatever their urgencies, on the shared channel,
+ * inside an open modal and in the commit that presents one; messages from
+ * other instances, and from instances without `hasReplace`, still join; a
+ * share another instance holds stays; an exposed message is left alone, and
+ * taking it back later touches no other announcer's words, in a modal's
+ * container or held for its close; the instance's hold on its message
+ * follows the words when a modal hands them on (it leaves the
+ * accessibility tree, exits, closes, or a step is left) or its write frame
+ * finds it unexposed; an empty message clears
+ * @position Core a11y tests beside the hook
+ */
+
+import {
+ act,
+ fireEvent,
+ render,
+ renderHook,
+ screen,
+} from '@testing-library/react';
+import {useEffect, useState} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
+import {Dialog} from '../Dialog/Dialog';
+import {__resetLiveRegionsForTest, useAnnounce} from './useAnnounce';
+
+const shared = (politeness = 'polite') =>
+ document.querySelector(`[data-astryx-live-region="${politeness}"]`);
+const regionIn = (dialog: Element, politeness = 'polite') =>
+ dialog.querySelector(
+ `:scope > [data-astryx-modal-live-region="${politeness}"]`,
+ );
+
+async function nextFrame() {
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+}
+
+/** jsdom has no showModal(); stand in for a dialog opened modally. */
+function stubDialogs() {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ this.dataset.modal = 'true';
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ delete this.dataset.modal;
+ this.dispatchEvent(new Event('close'));
+ });
+ const matches = Element.prototype.matches;
+ vi.spyOn(Element.prototype, 'matches').mockImplementation(function (
+ this: Element,
+ selector: string,
+ ) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement &&
+ this.open &&
+ this.dataset.modal === 'true'
+ : matches.call(this, selector);
+ });
+}
+
+const REPLACE = {hasReplace: true} as const;
+
+beforeEach(() => {
+ __resetLiveRegionsForTest();
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ __resetLiveRegionsForTest();
+});
+
+describe('useAnnounce({hasReplace}) on the shared channel (spec:AST-086 FR9)', () => {
+ it('says only the latest of its messages written in one frame', async () => {
+ const {result} = renderHook(() => useAnnounce(REPLACE));
+ result.current('1 result');
+ result.current('Create "Urg"');
+ result.current('Create "Urgent"');
+ await nextFrame();
+ expect(shared()?.textContent).toBe('Create "Urgent"');
+ });
+
+ it('still joins another instance’s message written in the same frame', async () => {
+ const {result} = renderHook(() => ({
+ count: useAnnounce(REPLACE),
+ other: useAnnounce(),
+ }));
+ result.current.other('Filter applied');
+ result.current.count('3 results');
+ result.current.count('2 results');
+ await nextFrame();
+ expect(shared()?.textContent).toBe('Filter applied 2 results');
+ });
+
+ it('keeps joining the messages of an instance without hasReplace', async () => {
+ const {result} = renderHook(() => useAnnounce());
+ result.current('Added Design');
+ result.current('Removed Eng');
+ await nextFrame();
+ expect(shared()?.textContent).toBe('Added Design Removed Eng');
+ });
+
+ it('withdraws only its own share of words another instance also wrote', async () => {
+ const {result} = renderHook(() => ({
+ first: useAnnounce(REPLACE),
+ second: useAnnounce(REPLACE),
+ }));
+ result.current.first('1 result');
+ result.current.second('1 result');
+ result.current.first('2 results');
+ await nextFrame();
+ // The second instance still holds "1 result".
+ expect(shared()?.textContent).toBe('1 result 2 results');
+ });
+
+ it('leaves a message that was already exposed: the next one starts fresh', async () => {
+ const {result} = renderHook(() => useAnnounce(REPLACE));
+ result.current('1 result');
+ await nextFrame();
+ expect(shared()?.textContent).toBe('1 result');
+ result.current('2 results');
+ await nextFrame();
+ expect(shared()?.textContent).toBe('2 results');
+ });
+
+ it('leaves another announcer’s equal words written after its own message was exposed', async () => {
+ const {result} = renderHook(() => ({
+ count: useAnnounce(REPLACE),
+ other: useAnnounce(),
+ }));
+ result.current.count('1 result');
+ await nextFrame();
+ result.current.other('1 result');
+ result.current.count('2 results');
+ await nextFrame();
+ expect(shared()?.textContent).toBe('1 result 2 results');
+ });
+
+ it('withdraws its polite message for an assertive one, which is spoken in the assertive region', async () => {
+ const {result} = renderHook(() => useAnnounce(REPLACE));
+ result.current('3 results');
+ result.current('Search failed', 'assertive');
+ await nextFrame();
+ expect(shared('polite')?.textContent ?? '').toBe('');
+ expect(shared('assertive')?.textContent).toBe('Search failed');
+ });
+
+ it('clears the region on an empty message', async () => {
+ const {result} = renderHook(() => useAnnounce(REPLACE));
+ result.current('1 result');
+ await nextFrame();
+ result.current('');
+ await nextFrame();
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+});
+
+describe('useAnnounce({hasReplace}) inside an Astryx modal (spec:AST-086 FR14)', () => {
+ beforeEach(() => {
+ stubDialogs();
+ });
+
+ function Typist({
+ messages,
+ }: {
+ messages: ReadonlyArray<readonly [string, 'polite' | 'assertive']>;
+ }) {
+ const announce = useAnnounce(REPLACE);
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ for (const [message, politeness] of messages) {
+ announce(message, politeness);
+ }
+ }}>
+ Type
+ </button>
+ );
+ }
+
+ it('withdraws its unexposed message in the modal’s container', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <Typist
+ messages={[
+ ['1 result', 'polite'],
+ ['Create "Urgent"', 'polite'],
+ ]}
+ />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Type'}));
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('Create "Urgent"');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('withdraws across the modal’s two containers', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <Typist
+ messages={[
+ ['3 results', 'polite'],
+ ['Search failed', 'assertive'],
+ ]}
+ />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Type'}));
+ await nextFrame();
+ expect(regionIn(dialog, 'polite')?.textContent ?? '').toBe('');
+ expect(regionIn(dialog, 'assertive')?.textContent).toBe('Search failed');
+ });
+
+ // A `hasReplace` count and a plain announcer that may say the same words.
+ function CountAndOther() {
+ const count = useAnnounce(REPLACE);
+ const other = useAnnounce();
+ return (
+ <>
+ <button type="button" onClick={() => count('1 result')}>
+ Count
+ </button>
+ <button type="button" onClick={() => count('2 results')}>
+ Recount
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ other('1 result');
+ count('1 result');
+ }}>
+ Both
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ other('1 result');
+ count('2 results');
+ }}>
+ Next
+ </button>
+ </>
+ );
+ }
+
+ it('leaves another announcer’s equal words in the container after its own message was exposed', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <CountAndOther />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Count'}));
+ // Written, then taken by assistive technology a frame later.
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('1 result');
+ // The plain announcer's "1 result" is not the count's spoken one.
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('1 result 2 results');
+ });
+
+ /** A sheet that runs its exit with the announcers inside it. */
+ function ExitingSheet() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label="Sheet">
+ <CountAndOther />
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Done
+ </button>
+ </BottomSheet>
+ );
+ }
+
+ it('takes back only its own share of words held while its sheet exits', async () => {
+ render(<ExitingSheet />);
+ const sheet = document.querySelector<HTMLDialogElement>('dialog')!;
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // Open but inert and aria-hidden through its exit: the words are held
+ // for the real close (reach the controls by element).
+ expect(sheet).toHaveAttribute('inert');
+ fireEvent.click(screen.getByText('Both'));
+ fireEvent.click(screen.getByText('Next'));
+ act(() => {
+ sheet.close();
+ });
+ await nextFrame();
+ await nextFrame();
+ // The plain announcer still holds "1 result"; the count's was taken back.
+ expect(shared()?.textContent).toBe('1 result 2 results');
+ });
+
+ it('leaves words held later when its own held words were already delivered', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <CountAndOther />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ // Out of the accessibility tree, as through an exit, and back.
+ const setHidden = async (hidden: boolean) => {
+ await act(async () => {
+ if (hidden) {
+ dialog.setAttribute('aria-hidden', 'true');
+ } else {
+ dialog.removeAttribute('aria-hidden');
+ }
+ });
+ };
+ await setHidden(true);
+ fireEvent.click(screen.getByText('Count'));
+ // Exposed again: the held words are delivered and spoken.
+ await setHidden(false);
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('1 result');
+ // Hidden again: the plain announcer's "1 result" is held now, and the
+ // count's delivered one is not among the held words.
+ await setHidden(true);
+ fireEvent.click(screen.getByText('Next'));
+ await setHidden(false);
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('1 result 2 results');
+ });
+
+ it('withdraws its message handed off as its Dialog leaves the accessibility tree, once the Dialog is back', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <CountAndOther />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ // Written, then the Dialog leaves the tree before the words are exposed:
+ // they are handed off, and held while the Dialog still covers the page.
+ fireEvent.click(screen.getByRole('button', {name: 'Count'}));
+ await act(async () => {
+ dialog.setAttribute('aria-hidden', 'true');
+ });
+ fireEvent.click(screen.getByText('Recount'));
+ await act(async () => {
+ dialog.removeAttribute('aria-hidden');
+ });
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('2 results');
+ });
+
+ it('withdraws its message handed off as its sheet exits, once the sheet has closed', async () => {
+ render(<ExitingSheet />);
+ const sheet = document.querySelector<HTMLDialogElement>('dialog')!;
+ await nextFrame();
+ // Written, and the sheet starts its exit before the words are exposed.
+ fireEvent.click(screen.getByRole('button', {name: 'Count'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ expect(sheet).toHaveAttribute('inert');
+ // The sheet's provider sees the exit and hands the words off.
+ await act(async () => {});
+ fireEvent.click(screen.getByText('Recount'));
+ act(() => {
+ sheet.close();
+ });
+ await nextFrame();
+ await nextFrame();
+ expect(shared()?.textContent).toBe('2 results');
+ });
+
+ it('withdraws its message handed to the entering step when its step is left before the words are exposed', async () => {
+ function Flow() {
+ const [step, setStep] = useState(1);
+ return (
+ <>
+ <Dialog isOpen={step === 1} onOpenChange={() => {}} aria-label="One">
+ <CountAndOther />
+ <button type="button" onClick={() => setStep(2)}>
+ Continue
+ </button>
+ </Dialog>
+ <Dialog isOpen={step === 2} onOpenChange={() => {}} aria-label="Two">
+ <span>Step two</span>
+ </Dialog>
+ </>
+ );
+ }
+ render(<Flow />);
+ await nextFrame();
+ // The count is written from step one, which closes in the same update
+ // that opens step two, before the words are exposed.
+ fireEvent.click(screen.getByRole('button', {name: 'Count'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));
+ // Step one's provider sees the close and hands the words to step two.
+ await act(async () => {});
+ const two = screen.getByRole('dialog', {name: 'Two'});
+ // The count's next message (step one's content stays mounted, closed)
+ // takes back its words from step two, and is heard on the page.
+ fireEvent.click(screen.getByText('Recount'));
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(two)?.textContent ?? '').toBe('');
+ expect(shared()?.textContent).toBe('2 results');
+ });
+
+ it('withdraws its message handed to the page as its Dialog closes before the words are exposed', async () => {
+ function Host() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <Dialog isOpen={isOpen} onOpenChange={setIsOpen} aria-label="Modal">
+ <CountAndOther />
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Close
+ </button>
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Count'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ // The provider sees the close and hands the words to the page.
+ await act(async () => {});
+ // The count's next message (the closed Dialog's content stays mounted)
+ // takes back its words from the page channel.
+ fireEvent.click(screen.getByText('Recount'));
+ await nextFrame();
+ expect(shared()?.textContent).toBe('2 results');
+ });
+
+ it('withdraws its message redirected in the write frame when its Dialog stopped being exposed unseen', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <CountAndOther />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ const exposed: string[] = [];
+ const record = new MutationObserver(() => {
+ const text = shared()?.textContent ?? '';
+ if (text !== '' && text !== exposed.at(-1)) {
+ exposed.push(text);
+ }
+ });
+ record.observe(document.body, {
+ subtree: true,
+ childList: true,
+ characterData: true,
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Count'}));
+ // No longer a modal, through no attribute its provider watches: the
+ // write frame finds it unexposed and sends the words to the page.
+ delete dialog.dataset.modal;
+ await nextFrame();
+ fireEvent.click(screen.getByText('Recount'));
+ await nextFrame();
+ await nextFrame();
+ await nextFrame();
+ record.disconnect();
+ expect(exposed).toEqual(['2 results']);
+ });
+
+ it('withdraws a message deferred in the commit that presents the Dialog', async () => {
+ function OpeningCount() {
+ const announce = useAnnounce(REPLACE);
+ useEffect(() => {
+ // Both before the Dialog's own Effect has presented it.
+ announce('1 result');
+ announce('2 results');
+ }, [announce]);
+ return <span>Results</span>;
+ }
+ function Host() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open
+ </button>
+ {isOpen && (
+ <Dialog isOpen onOpenChange={setIsOpen} aria-label="Edit">
+ <OpeningCount />
+ </Dialog>
+ )}
+ </>
+ );
+ }
+ render(<Host />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ const dialog = screen.getByRole('dialog', {name: 'Edit'});
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('2 results');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+});
diff --git a/packages/core/src/hooks/useAnnounce.ts b/packages/core/src/hooks/useAnnounce.ts
index 6e20522852..5c9059fefd 100644
--- a/packages/core/src/hooks/useAnnounce.ts
+++ b/packages/core/src/hooks/useAnnounce.ts
@@ -7,10 +7,11 @@
* @input Uses React context and useCallback; DOM APIs and cancellable
* animation frames for a singleton live-region pair on the page body and
* one persistent polite/assertive pair inside each open Astryx modal
- * @output Exports useAnnounce hook and AnnouncePoliteness type; the internal
- * modal context, the in-dialog region writer the busy-announcement hook
- * uses, and the hook the modal route (`modalAnnounce.ts`, loaded only with
- * an Astryx modal) installs itself through
+ * @output Exports useAnnounce hook (with its `hasReplace` option),
+ * AnnouncePoliteness and UseAnnounceOptions types; the internal modal
+ * context, the in-dialog region writer the busy-announcement hook uses, and
+ * the hook the modal route (`modalAnnounce.ts`, loaded only with an Astryx
+ * modal) installs itself through
* @position Core a11y hook; provides imperative screen-reader announcements.
* A message follows the nearest open native modal enclosing its caller
* (`spec:AST-086` FR14): inside an Astryx modal it is written to that
@@ -18,16 +19,20 @@
* while a native modal is open; otherwise to the shared page-body pair.
* Containers are created empty (FR3), carry the two urgencies (FR5), join
* messages written before the previous is exposed and say an identical
- * same-frame repeat once (FR9), and clear shortly after each announcement;
+ * same-frame repeat once (FR9), except that a `hasReplace` instance's
+ * message withdraws that instance's previous one not yet exposed, and clear
+ * shortly after each announcement;
* the route in `modalAnnounce.ts` hands a message still unexposed when its
* modal stops being exposed to the channel exposed after it — the modal
- * then on top, or the page body once no modal is open.
+ * then on top, or the page body once no modal is open. Each write keeps a
+ * receipt per announcer beside the words, which follows them wherever
+ * they are moved, so the announcer can take back its own share.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
*/
-import {createContext, use, useCallback, type RefObject} from 'react';
+import {createContext, use, useCallback, useRef, type RefObject} from 'react';
/**
* Announcement urgency:
@@ -46,6 +51,73 @@ export type AnnounceFn = (
politeness?: AnnouncePoliteness,
) => void;
+/** Options for `useAnnounce`. */
+export interface UseAnnounceOptions {
+ /**
+ * The instance states one current state of its owner, such as a search's
+ * result count: each message it writes withdraws the instance's previous
+ * message while that one is not yet exposed, whatever their urgencies, and
+ * is spoken in the region of its own urgency; a message already exposed has
+ * been heard and stays. Messages from other instances, and from instances
+ * without `hasReplace`, still join (`spec:AST-086` FR9). Give each state a
+ * component reports its own instance.
+ * @default false
+ */
+ hasReplace?: boolean;
+}
+
+/**
+ * Takes back one announcer's share of a message while it is not yet exposed,
+ * wherever the route put it. @internal
+ */
+export type WithdrawAnnouncement = () => void;
+
+/**
+ * One announcer's share of words on their way to being exposed. Whatever
+ * holds the words keeps the receipt beside them; when the words move — a
+ * modal hands them to the channel exposed after it, or releases words it
+ * held through an exit — the mover points the receipt at the new place, so
+ * the announcer's handle follows its words. @internal
+ */
+export interface AnnounceReceipt {
+ withdraw: WithdrawAnnouncement | null;
+}
+
+/** Words waiting to be exposed, with their announcers' receipts. @internal */
+export interface WaitingWords {
+ readonly text: string;
+ readonly receipts: ReadonlyArray<AnnounceReceipt>;
+}
+
+/**
+ * The announcer's handle to `receipt`: it takes back the words wherever they
+ * are now, once. @internal
+ */
+export function handleOf(receipt: AnnounceReceipt): WithdrawAnnouncement {
+ return () => {
+ const withdraw = receipt.withdraw;
+ receipt.withdraw = null;
+ withdraw?.();
+ };
+}
+
+/**
+ * Move `waiting` words elsewhere, one delivery per announcer and in order,
+ * and point each receipt at its delivery, so every announcer can still take
+ * back its own share (`spec:AST-086` FR9, FR14). The deliveries join where
+ * they land, so the words are spoken once. @internal
+ */
+export function forwardWaiting(
+ waiting: ReadonlyArray<WaitingWords>,
+ deliver: (text: string) => WithdrawAnnouncement | null,
+): void {
+ for (const {text, receipts} of waiting) {
+ for (const receipt of receipts) {
+ receipt.withdraw = deliver(text);
+ }
+ }
+}
+
const CONTAINER_ATTR = 'data-astryx-live-region';
// Visually-hidden clip block (matches the VisuallyHidden primitive). Applied
@@ -165,13 +237,17 @@ function getRegions(): LiveRegions | null {
return regions;
}
+/**
+ * Write `message` to the shared region for `politeness`, joining the messages
+ * not yet exposed. Returns how to take this write back while it waits.
+ */
export function announceMessage(
message: string,
politeness: AnnouncePoliteness,
-): void {
+): WithdrawAnnouncement | null {
const r = getRegions();
if (!r) {
- return;
+ return null;
}
const target = politeness === 'assertive' ? r.assertive : r.polite;
const repeat = pendingMessages[politeness].find(
@@ -180,7 +256,7 @@ export function announceMessage(
if (repeat != null) {
repeat.holders += 1;
lastJoined = repeat;
- return;
+ return () => withdrawPendingAnnouncement(repeat, politeness);
}
const pending = {text: message, holders: 1};
pendingMessages[politeness].push(pending);
@@ -203,6 +279,7 @@ export function announceMessage(
// indefinitely. Scheduled per announce, so a newer announcement always
// resets the countdown (the delay comfortably outlasts the rAF re-set).
scheduleClear(politeness, target);
+ return () => withdrawPendingAnnouncement(pending, politeness);
}
/**
@@ -233,6 +310,12 @@ export function clearRegion(politeness: AnnouncePoliteness): void {
* announced, so users browsing the DOM later do not encounter stale status
* text; announcing again before the clear simply resets the countdown.
*
+ * An instance created with `hasReplace` states one current state, such as a
+ * search's result count: each message it writes withdraws its previous one
+ * while that one is not yet exposed, so typing faster than a frame says only
+ * the latest count (`spec:AST-086` FR9).
+ *
+ * @param options - `hasReplace` (default false)
* @example
* ```
* function Search() {
@@ -244,27 +327,40 @@ export function clearRegion(politeness: AnnouncePoliteness): void {
* }
* ```
*/
-export function useAnnounce(): AnnounceFn {
+export function useAnnounce({
+ hasReplace = false,
+}: UseAnnounceOptions = {}): AnnounceFn {
const modal = use(ModalAnnounceContext);
+ // A `hasReplace` instance's latest write, which its next message takes back
+ // if assistive technology has not had it yet.
+ const withdrawPreviousRef = useRef<WithdrawAnnouncement | null>(null);
return useCallback(
(message: string, politeness: AnnouncePoliteness = 'polite') => {
+ if (hasReplace) {
+ const withdrawPrevious = withdrawPreviousRef.current;
+ withdrawPreviousRef.current = null;
+ withdrawPrevious?.();
+ }
+ let written: WithdrawAnnouncement | null;
// Inside an Astryx modal's provider: the modal route decides, per call,
// where the caller is heard — `modal` is non-null only where a provider
// rendered, and rendering one loads the route.
if (modal != null && modalRoute != null) {
- modalRoute.announce(modal, message, politeness);
- return;
- }
- if (!message) {
+ written = modalRoute.announce(modal, message, politeness);
+ } else if (!message) {
// An empty message clears any lingering status from the region,
// including messages joined but not yet exposed — useful when the
// triggering context ends.
clearRegion(politeness);
- return;
+ written = null;
+ } else {
+ written = announceMessage(message, politeness);
+ }
+ if (hasReplace) {
+ withdrawPreviousRef.current = written;
}
- announceMessage(message, politeness);
},
- [modal],
+ [hasReplace, modal],
);
}
@@ -305,24 +401,25 @@ ModalAnnounceContext.displayName = 'ModalAnnounceContext';
/** The modal route `modalAnnounce.ts` installs when a provider loads it. */
export interface ModalRoute {
- /** `useAnnounce` from inside `scope`: route `message` by where it is. */
+ /**
+ * `useAnnounce` from inside `scope`: route `message` by where it is, and
+ * return how to take this write back while it waits (a `hasReplace`
+ * instance's next message does).
+ */
announce(
scope: ModalAnnounceScope,
message: string,
politeness: AnnouncePoliteness,
- ): void;
- /** Speak inside `dialog` with the exposure, covered and hold rules. */
+ ): WithdrawAnnouncement | null;
+ /**
+ * Speak inside `dialog` with the exposure, covered and hold rules, and
+ * return how to take this write back while it waits.
+ */
announceInModal(
dialog: HTMLDialogElement,
message: string,
politeness: AnnouncePoliteness,
- ): void;
- /** Withdraw an announcer's share, written or held. */
- withdrawFromModalPending(
- dialog: HTMLDialogElement,
- message: string,
- politeness: AnnouncePoliteness,
- ): void;
+ ): WithdrawAnnouncement | null;
}
let modalRoute: ModalRoute | null = null;
@@ -364,47 +461,30 @@ export function enclosingModalDialog(
* exposure, covered and hold rules; without it — a native modal an app
* renders without Astryx, and no Astryx modal anywhere — the words are
* written to the dialog while it is open as a modal, else to the shared
- * channel. Internal: used by the busy-announcement hook.
+ * channel. Returns how to take the words back while they wait, wherever they
+ * move, so a busy start overtaken by its own outcome is never heard ahead of
+ * it inside a modal (`spec:AST-086` FR8). Internal: used by the
+ * busy-announcement hook.
*/
export function announceInModal(
dialog: HTMLDialogElement,
message: string,
politeness: AnnouncePoliteness = 'polite',
-): void {
+): WithdrawAnnouncement | null {
if (modalRoute != null) {
- modalRoute.announceInModal(dialog, message, politeness);
- return;
+ return modalRoute.announceInModal(dialog, message, politeness);
}
if (isOpenModal(dialog)) {
- writeModalRegion(dialog, message, politeness);
- } else {
- announceMessage(message, politeness);
- }
-}
-
-/**
- * Withdraw one announcer's share of `message` from `dialog` before it is
- * exposed, written to its region or held by the route for the dialog's
- * close, so a busy start overtaken by its own outcome is never heard ahead
- * of it inside a modal (`spec:AST-086` FR8). Internal: used by the
- * busy-announcement hook's settle function.
- */
-export function withdrawFromModalPending(
- dialog: HTMLDialogElement,
- message: string,
- politeness: AnnouncePoliteness = 'polite',
-): void {
- if (modalRoute != null) {
- modalRoute.withdrawFromModalPending(dialog, message, politeness);
- return;
+ return writeModalRegion(dialog, message, politeness);
}
- withdrawFromModalRegion(dialog, message, politeness);
+ return announceMessage(message, politeness);
}
/** What the route asks of the writer in the write frame. @internal */
export interface ModalWriteGuard {
isExposed: () => boolean;
- redirect: (joinedMessage: string) => void;
+ /** Deliver the waiting words elsewhere, forwarding their receipts. */
+ redirect: (waiting: ReadonlyArray<WaitingWords>) => void;
}
// Each in-dialog region's pending state: the messages written since its text
@@ -414,9 +494,12 @@ export interface ModalWriteGuard {
// rather than wiping the words), and the timer that clears them afterwards.
interface ModalPending {
messages: string[];
- // Announcers waiting on each message, by text: one withdrawing a message
- // (a busy start overtaken by its outcome) leaves it for the others.
- holders: Map<string, number>;
+ // The announcers waiting on each message, one receipt each: one taking its
+ // share back (a busy start overtaken by its outcome, a `hasReplace`
+ // instance's next message) leaves the message for the others. A fresh map
+ // once the words are exposed, so a receipt never reaches equal words
+ // written after its own were exposed.
+ receipts: Map<string, AnnounceReceipt[]>;
frame: number | null;
settleFrame: number | null;
timer: ReturnType<typeof setTimeout> | null;
@@ -438,12 +521,27 @@ function cancelPending(pending: ModalPending): void {
/** Words written to `target` that assistive technology has not had yet. */
export function unexposedMessages(target: HTMLElement): string[] {
+ return unexposedWords(target).map(words => words.text);
+}
+
+function waitingIn(pending: ModalPending): WaitingWords[] {
+ return pending.messages.map(text => ({
+ text,
+ receipts: pending.receipts.get(text) ?? [],
+ }));
+}
+
+/**
+ * The words written to `target` that assistive technology has not had yet,
+ * with their announcers' receipts, for a hand-off that forwards them.
+ */
+export function unexposedWords(target: HTMLElement): WaitingWords[] {
const pending = pendingByRegion.get(target);
if (pending == null) {
return [];
}
return pending.frame != null || pending.settleFrame != null
- ? pending.messages
+ ? waitingIn(pending)
: [];
}
@@ -484,29 +582,32 @@ function ensureModalRegion(
/**
* Write `message` to the modal `dialog`'s own live region for `politeness`,
* joining it to messages written there that are not yet exposed and saying
- * an identical repeat once; a holder count per text lets one announcer take
- * its share back (`withdrawFromModalPending`). The region-writing core,
- * shared by the full modal route and by the busy-announcement hook's fallback
- * for a native modal an app renders without Astryx. `guard`, supplied by the
- * route, re-checks exposure in the write frame and redirects the joined words
- * when the dialog stopped being exposed meanwhile.
+ * an identical repeat once. The region-writing core, shared by the full
+ * modal route and by the busy-announcement hook's fallback for a native
+ * modal an app renders without Astryx. `guard`, supplied by the route,
+ * re-checks exposure in the write frame and redirects the waiting words when
+ * the dialog stopped being exposed meanwhile. Returns this announcer's
+ * handle: it takes back only its own share, only while the words wait, and
+ * follows them when the route moves them.
*/
export function writeModalRegion(
dialog: HTMLDialogElement,
message: string,
politeness: AnnouncePoliteness,
guard?: ModalWriteGuard,
-): void {
+): WithdrawAnnouncement {
const target = ensureModalRegion(dialog, politeness);
const unexposed = unexposedMessages(target);
const messages = unexposed.includes(message)
? unexposed
: [...unexposed, message];
const previous = pendingByRegion.get(target);
- const holders = new Map(
- unexposed.length > 0 && previous != null ? previous.holders : [],
- );
- holders.set(message, (holders.get(message) ?? 0) + 1);
+ const receipts =
+ unexposed.length > 0 && previous != null
+ ? previous.receipts
+ : new Map<string, AnnounceReceipt[]>();
+ const receipt: AnnounceReceipt = {withdraw: null};
+ receipts.set(message, [...(receipts.get(message) ?? []), receipt]);
if (previous != null) {
cancelPending(previous);
}
@@ -515,7 +616,7 @@ export function writeModalRegion(
target.textContent = '';
const pending: ModalPending = {
messages,
- holders,
+ receipts,
frame: null,
settleFrame: null,
timer: null,
@@ -524,9 +625,9 @@ export function writeModalRegion(
pending.frame = null;
if (guard != null && !guard.isExposed()) {
// Stopped being exposed between the call and this frame: the words go
- // where they will be heard.
+ // where they will be heard, their receipts with them.
pendingByRegion.delete(target);
- guard.redirect(pending.messages.join(' '));
+ guard.redirect(waitingIn(pending));
return;
}
target.textContent = pending.messages.join(' ');
@@ -539,43 +640,49 @@ export function writeModalRegion(
}, CLEAR_DELAY_MS);
});
pendingByRegion.set(target, pending);
+ receipt.withdraw = () => withdrawFromRegion(target, message, receipt);
+ return handleOf(receipt);
}
/**
- * Withdraw one announcer's share of `message` from `dialog`'s region before
- * it is exposed — written but not yet spoken — so a busy start overtaken by
- * its own outcome is never heard ahead of it (`spec:AST-086` FR8). The
- * message stays while another announcer holds it. The region half of
- * `withdrawFromModalPending`; the route also drops words it holds for the
- * dialog's close.
+ * Withdraw one announcer's share of `message` from `target` while it is not
+ * yet exposed — written but not yet spoken — so a busy start overtaken by its
+ * own outcome is never heard ahead of it (`spec:AST-086` FR8), and a
+ * `hasReplace` instance's next message replaces its previous one (FR9,
+ * FR14). The message stays while another announcer holds it; a receipt not
+ * among the waiting words (they were exposed, cleared, or moved) takes back
+ * nothing.
*/
-export function withdrawFromModalRegion(
- dialog: HTMLDialogElement,
+function withdrawFromRegion(
+ target: HTMLElement,
message: string,
- politeness: AnnouncePoliteness = 'polite',
+ receipt: AnnounceReceipt,
): void {
- const region = modalRegion(dialog, politeness);
- const pending = region == null ? undefined : pendingByRegion.get(region);
+ const pending = pendingByRegion.get(target);
if (
- region != null &&
- pending != null &&
- (pending.frame != null || pending.settleFrame != null)
+ pending == null ||
+ (pending.frame == null && pending.settleFrame == null)
) {
- const count = pending.holders.get(message) ?? 0;
- if (count > 1) {
- pending.holders.set(message, count - 1);
- } else if (count === 1) {
- pending.holders.delete(message);
- pending.messages = pending.messages.filter(text => text !== message);
- if (pending.messages.length === 0) {
- cancelPending(pending);
- pendingByRegion.delete(region);
- region.textContent = '';
- } else if (pending.frame == null) {
- // Already written this frame, not yet taken: show the rest.
- region.textContent = pending.messages.join(' ');
- }
- }
+ return;
+ }
+ const receipts = pending.receipts.get(message);
+ const at = receipts?.indexOf(receipt) ?? -1;
+ if (receipts == null || at < 0) {
+ return;
+ }
+ receipts.splice(at, 1);
+ if (receipts.length > 0) {
+ return;
+ }
+ pending.receipts.delete(message);
+ pending.messages = pending.messages.filter(text => text !== message);
+ if (pending.messages.length === 0) {
+ cancelPending(pending);
+ pendingByRegion.delete(target);
+ target.textContent = '';
+ } else if (pending.frame == null) {
+ // Already written this frame, not yet taken: show the rest.
+ target.textContent = pending.messages.join(' ');
}
}
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.ts b/packages/core/src/hooks/useAnnounceRenderedText.ts
index c59117114c..d21cccb6eb 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.ts
+++ b/packages/core/src/hooks/useAnnounceRenderedText.ts
@@ -7,7 +7,7 @@
* @input A ref to a rendered element, whether it is showing, and a token that
* marks a new occasion to speak
* @output Announces that element's own rendered text through the persistent
- * polite live region
+ * polite live region, or through the announcer the owner passes
* @position Core a11y hook; mirrors on-screen content into the shared live
* region by reading the DOM
*
@@ -44,7 +44,11 @@
*/
import {useEffect, useRef, useState, type RefObject} from 'react';
-import {useAnnounce, type AnnouncePoliteness} from './useAnnounce';
+import {
+ useAnnounce,
+ type AnnounceFn,
+ type AnnouncePoliteness,
+} from './useAnnounce';
import {useIsHydrating} from './useIsHydrating';
const LIVE_CONTAINER =
@@ -89,6 +93,14 @@ export interface AnnounceRenderedTextOptions {
* every other message polite (`spec:AST-086` FR5). Defaults to polite.
*/
politeness?: AnnouncePoliteness;
+ /**
+ * The owner's announcer to speak through, when the rendered text states
+ * the next value of a state that announcer states: a picker's empty-panel
+ * message goes through its search's `hasReplace` instance, so the two
+ * replace each other while not yet exposed (`spec:AST-086` FR13).
+ * Defaults to this hook's own instance.
+ */
+ announce?: AnnounceFn;
}
/** The rendered text an assistive technology would read from `element`. */
@@ -128,9 +140,11 @@ export function useAnnounceRenderedText(
{
skipFirstRender = false,
politeness = 'polite',
+ announce: ownerAnnounce,
}: AnnounceRenderedTextOptions = {},
): void {
- const announce = useAnnounce();
+ const ownAnnounce = useAnnounce();
+ const announce = ownerAnnounce ?? ownAnnounce;
const spokenRef = useRef<string | null>(null);
const isHydrating = useIsHydrating();
// Captured once: an owner rendered before the document finished loading, or
diff --git a/packages/core/src/hooks/useBusyAnnouncement.ts b/packages/core/src/hooks/useBusyAnnouncement.ts
index e3ae84478e..eb39a53630 100644
--- a/packages/core/src/hooks/useBusyAnnouncement.ts
+++ b/packages/core/src/hooks/useBusyAnnouncement.ts
@@ -32,8 +32,8 @@ import {
enclosingModalDialog,
takeJoinedAnnouncement,
useAnnounce,
- withdrawFromModalPending,
withdrawPendingAnnouncement,
+ type WithdrawAnnouncement,
} from './useAnnounce';
export function useBusyAnnouncement(
@@ -47,11 +47,9 @@ export function useBusyAnnouncement(
// This busy start's share of the shared channel's pending text, until it
// settles.
const channelMessageRef = useRef<object | null>(null);
- // Or its write inside a modal's container, until it settles.
- const modalMessageRef = useRef<{
- dialog: HTMLDialogElement;
- message: string;
- } | null>(null);
+ // Or how to take back its write inside a modal, wherever the modal moves
+ // it, until it settles.
+ const modalMessageRef = useRef<WithdrawAnnouncement | null>(null);
useEffect(() => {
if (!isBusy) {
hasAnnouncedRef.current = false;
@@ -74,8 +72,7 @@ export function useBusyAnnouncement(
// nearest Astryx modal around this hook's caller.
const dialog = enclosingModalDialog(elementRef.current);
if (dialog != null) {
- announceInModal(dialog, message);
- modalMessageRef.current = {dialog, message};
+ modalMessageRef.current = announceInModal(dialog, message);
} else {
announce(message, 'polite');
channelMessageRef.current = takeJoinedAnnouncement();
@@ -102,9 +99,9 @@ export function useBusyAnnouncement(
channelMessageRef.current = null;
}
if (modalMessageRef.current != null) {
- const {dialog, message} = modalMessageRef.current;
- withdrawFromModalPending(dialog, message, 'polite');
+ const withdraw = modalMessageRef.current;
modalMessageRef.current = null;
+ withdraw();
}
}, []);
}