Skip to content

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

TypeScript

fix(core): useAnnounce delivers inside the open Astryx modal that encloses its caller (#8009)

Xinzi Zhouc22cbe2fddf4
diff --git a/.changeset/announce-inside-modals.md b/.changeset/announce-inside-modals.md
new file mode 100644
index 0000000000..94dcc23d58
--- /dev/null
+++ b/.changeset/announce-inside-modals.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `useAnnounce` now delivers a message by where its caller is. Inside an open Astryx modal — a Dialog, a modal BottomSheet (standalone or a switcher step), a modal Drawer, a Lightbox, MobileNav, or CommandPalette's dialog — the message reaches a persistent live region inside that dialog, which assistive technology hears while the modal is open, instead of the page-body region the modal hides; outside a modal nothing changes. Component and app code rendered inside a modal that calls `useAnnounce` is heard without any change to it. Delivery follows exposure, in top-layer order: a message sent as a switcher step hands over reaches the entering step, forward or back; a message sent as a modal BottomSheet closes, or just before an open Dialog is unmounted, waits while the leaving modal still covers the page and is delivered at its real close to whatever is exposed then — the Dialog it was opened over, or the page body — instead of being lost; a message a modal receives while a later modal covers it is not written and its region is clear before it is on top again. Busy controls inside a modal announce their busy start through the same region, including inside a native modal an app renders without Astryx; messages written to one region before the first is exposed are joined, and an identical repeat in the same frame is said once. The region's internal marker is `data-astryx-modal-live-region="polite"` or `"assertive"` (the busy region's former `data-astryx-modal-busy-region` is gone). Not in this change: CommandPalette's own result-count messages, Lightbox's own position and zoom messages, and Selector's and MultiSelector's selection and result-count messages in their `bottom-sheet` presentation are sent from the component that renders each dialog, above it, and still use the page-body channel while that dialog is open; each component's own change follows. This meets the in-modal delivery requirement in spec:AST-086 (FR14).
+
+@imdreamrunner
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsx
index d0d29ae649..dea4a225ca 100644
--- a/apps/storybook/stories/BottomSheet.stories.tsx
+++ b/apps/storybook/stories/BottomSheet.stories.tsx
@@ -13,6 +13,8 @@ import * as stylex from '@stylexjs/stylex';
import {expect, waitFor, within} from 'storybook/test';
import {useState, type ComponentProps} from 'react';
import {BottomSheet} from '@astryxdesign/core/BottomSheet';
+import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
+import {useAnnounce} from '@astryxdesign/core/hooks';
import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';
import {Button} from '@astryxdesign/core/Button';
import {Divider} from '@astryxdesign/core/Divider';
@@ -297,6 +299,61 @@ export const Showcase: Story = {
},
};
+/**
+ * Done announces and closes in one tap. Rendered inside the sheet, so
+ * `useAnnounce` follows the sheet's dialog; while the sheet fades out over
+ * the Dialog it still covers it, so the words wait and reach the Dialog's
+ * own live region at the sheet's real close (spec:AST-086 FR14).
+ */
+function SaveAndDone({onDone}: {onDone: () => void}) {
+ const announce = useAnnounce();
+ return (
+ <Button
+ label="Done"
+ onClick={() => {
+ announce('Saved');
+ onDone();
+ }}
+ />
+ );
+}
+
+export const SheetOverDialog: Story = {
+ name: 'Sheet over a Dialog',
+ render: () => {
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ return (
+ <>
+ <Button label="Open dialog" onClick={() => setIsDialogOpen(true)} />
+ <Dialog
+ isOpen={isDialogOpen}
+ onOpenChange={setIsDialogOpen}
+ aria-label="Edit item">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <DialogHeader title="Edit item" onOpenChange={setIsDialogOpen} />
+ <Button label="Open sheet" onClick={() => setIsSheetOpen(true)} />
+ <BottomSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ label="Options">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Options</Heading>
+ <CheckboxInput label="Notify me" value={false} />
+ <SaveAndDone onDone={() => setIsSheetOpen(false)} />
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </VStack>
+ </Section>
+ </Dialog>
+ </>
+ );
+ },
+};
+
export const FormPurpose: Story = {
name: 'Form purpose',
render: () => {
diff --git a/apps/storybook/stories/BottomSheetSwitcher.stories.tsx b/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
index d999a7ff3e..0297d118d1 100644
--- a/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
+++ b/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
@@ -4,6 +4,7 @@ import type {Meta, StoryObj} from '@storybook/react';
import {useState} from 'react';
import {BottomSheet, BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
+import {useAnnounce} from '@astryxdesign/core/hooks';
import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
import {Divider} from '@astryxdesign/core/Divider';
@@ -47,6 +48,41 @@ interface NotificationOverviewSheetProps {
onContinue: () => void;
}
+/**
+ * A status message sent as the step hands over. Rendered inside the step's
+ * sheet, so `useAnnounce` follows that sheet's dialog (spec:AST-086 FR14): the
+ * words are delivered inside the open modal rather than to the page body the
+ * modal hides, and a close that is really a hand-over keeps them there.
+ */
+function ContinueWithStatus({onContinue}: {onContinue: () => void}) {
+ const announce = useAnnounce();
+ return (
+ <Button
+ label="Continue"
+ onClick={() => {
+ announce('Overview saved');
+ onContinue();
+ }}
+ />
+ );
+}
+
+/**
+ * A status message that leaves the person on this step: after going back to
+ * it while the next step still fades out, this step is the modal on top and
+ * the words are heard inside it (spec:AST-086 FR14).
+ */
+function SaveDraft() {
+ const announce = useAnnounce();
+ return (
+ <Button
+ label="Save draft"
+ variant="ghost"
+ onClick={() => announce('Draft saved')}
+ />
+ );
+}
+
function NotificationOverviewSheet({
height,
onCancel,
@@ -91,8 +127,9 @@ function NotificationOverviewSheet({
</VStack>
</VStack>
<HStack gap={2} hAlign="end">
+ <SaveDraft />
<Button label="Cancel" variant="secondary" onClick={onCancel} />
- <Button label="Continue" onClick={onContinue} />
+ <ContinueWithStatus onContinue={onContinue} />
</HStack>
</VStack>
</Section>
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index 29cfb4256a..4e702d0c34 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -62,6 +62,7 @@ import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';
import {useDevWarning, useScrollLock} from '../hooks';
import {mergeProps} from '../utils';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {useModalOutlet} from '../Layer/modalOutlet';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {focusForLastInput} from '../utils/focusReturn';
@@ -510,10 +511,16 @@ function StandaloneBottomSheet({
onScrimOpacity={handleScrimOpacity}
onElementChange={handlePanelElementChange}
onMotionComplete={handleMotionComplete}>
- <LayerDepthProvider>
- {/* A sheet opened inside this one starts from Escape on. */}
- <BottomSheetEscapeContext value>{children}</BottomSheetEscapeContext>
- </LayerDepthProvider>
+ <ModalAnnounceProvider
+ dialogRef={dialogRef}
+ isOpen={isOpen && hasScrim}>
+ <LayerDepthProvider>
+ {/* A sheet opened inside this one starts from Escape on. */}
+ <BottomSheetEscapeContext value>
+ {children}
+ </BottomSheetEscapeContext>
+ </LayerDepthProvider>
+ </ModalAnnounceProvider>
</BottomSheetPanel>
{/* Its own element, outside the panel's transform, so it stays flush
with the viewport's bottom edge at every detent; only while the
@@ -823,12 +830,16 @@ function SwitcherBottomSheetItem({
fresh ownership scope so a nested BottomSheet is standalone unless
it establishes a nested BottomSheetSwitcher of its own. */}
<BottomSheetSwitcherContext value={null}>
- <LayerDepthProvider>
- {/* A sheet opened inside this one starts from Escape on. */}
- <BottomSheetEscapeContext value>
- {children}
- </BottomSheetEscapeContext>
- </LayerDepthProvider>
+ <ModalAnnounceProvider
+ dialogRef={dialogRef}
+ isOpen={isPresented && hasScrim}>
+ <LayerDepthProvider>
+ {/* A sheet opened inside this one starts from Escape on. */}
+ <BottomSheetEscapeContext value>
+ {children}
+ </BottomSheetEscapeContext>
+ </LayerDepthProvider>
+ </ModalAnnounceProvider>
</BottomSheetSwitcherContext>
</BottomSheetPanel>
</div>
diff --git a/packages/core/src/DateInput/DateInputTouch.test.tsx b/packages/core/src/DateInput/DateInputTouch.test.tsx
index b6f139ba9e..a241025106 100644
--- a/packages/core/src/DateInput/DateInputTouch.test.tsx
+++ b/packages/core/src/DateInput/DateInputTouch.test.tsx
@@ -701,7 +701,7 @@ describe('DateInput — field parity', () => {
expect(sheet).not.toBeNull();
await waitFor(() => {
expect(
- sheet!.querySelector('[data-astryx-modal-busy-region]'),
+ sheet!.querySelector('[data-astryx-modal-live-region="polite"]'),
).toHaveTextContent('Loading');
});
expect(
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index a15506a3ea..2f1e5806bd 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -78,6 +78,7 @@ import type {DialogVariantMap} from './index';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useInteractionModalityTracking} from '../utils/interactionModality';
import {focusForLastInput} from '../utils/focusReturn';
+import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {useMergedRefs} from '../hooks/useMergedRefs';
/**
@@ -820,9 +821,11 @@ export function Dialog({
// imperatively in `attachDialog`; a consumer-provided aria-labelledby
// flows through {...safeProps} above and wins.
{...(purpose === 'required' ? {role: 'alertdialog'} : undefined)}>
- <LayerDepthProvider>
- <LayerContentBoundary>{innerContent}</LayerContentBoundary>
- </LayerDepthProvider>
+ <ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen}>
+ <LayerDepthProvider>
+ <LayerContentBoundary>{innerContent}</LayerContentBoundary>
+ </LayerDepthProvider>
+ </ModalAnnounceProvider>
</dialog>
);
}
diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsx
index 67f99819e4..7fa39e041d 100644
--- a/packages/core/src/Drawer/Drawer.tsx
+++ b/packages/core/src/Drawer/Drawer.tsx
@@ -74,6 +74,7 @@ import {LayerDepthProvider, useLayerDismissal} from '../Layer';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
import {container, overlayPaddingReset} from '../Layout';
import {
@@ -570,42 +571,44 @@ export function Drawer({
onClick={composeEventHandlers(onClickProp, handleClick)}
onKeyDown={onKeyDownProp}
onCancel={handleCancel}>
- <LayerDepthProvider>
- <LayerContentBoundary>
- {/* Scrollable content area — tabIndex so the dialog's focusing steps
+ <ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen && hasScrim}>
+ <LayerDepthProvider>
+ <LayerContentBoundary>
+ {/* Scrollable content area — tabIndex so the dialog's focusing steps
land on the panel body rather than the first button inside. */}
- <div
- tabIndex={-1}
- {...stylex.props(
- styles.content,
- ...container(
- usesThemePadding
- ? {useThemeDefault: 'drawer'}
- : {
- paddingInnerX: paddingToken,
- paddingInnerY: paddingToken,
- paddingOuterX: paddingToken,
- paddingOuterY: paddingToken,
- },
- ),
- !usesThemePadding &&
- effectivePadding !== 4 &&
- paddingStyles[effectivePadding],
- !usesThemePadding &&
- effectivePadding !== 4 &&
- containerPaddingInlineVarStyles[effectivePadding],
- !usesThemePadding &&
- effectivePadding !== 4 &&
- containerPaddingBlockStartVarStyles[effectivePadding],
- !usesThemePadding &&
- effectivePadding !== 4 &&
- containerPaddingBlockEndVarStyles[effectivePadding],
- styles.contentSafeArea,
- )}>
- {children}
- </div>
- </LayerContentBoundary>
- </LayerDepthProvider>
+ <div
+ tabIndex={-1}
+ {...stylex.props(
+ styles.content,
+ ...container(
+ usesThemePadding
+ ? {useThemeDefault: 'drawer'}
+ : {
+ paddingInnerX: paddingToken,
+ paddingInnerY: paddingToken,
+ paddingOuterX: paddingToken,
+ paddingOuterY: paddingToken,
+ },
+ ),
+ !usesThemePadding &&
+ effectivePadding !== 4 &&
+ paddingStyles[effectivePadding],
+ !usesThemePadding &&
+ effectivePadding !== 4 &&
+ containerPaddingInlineVarStyles[effectivePadding],
+ !usesThemePadding &&
+ effectivePadding !== 4 &&
+ containerPaddingBlockStartVarStyles[effectivePadding],
+ !usesThemePadding &&
+ effectivePadding !== 4 &&
+ containerPaddingBlockEndVarStyles[effectivePadding],
+ styles.contentSafeArea,
+ )}>
+ {children}
+ </div>
+ </LayerContentBoundary>
+ </LayerDepthProvider>
+ </ModalAnnounceProvider>
</dialog>
);
}
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 376ed067b6..5ccc26fcc2 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -41,6 +41,7 @@ import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {overlayPaddingReset} from '../Layout/padding.stylex';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
@@ -654,129 +655,131 @@ export function Lightbox({
)}
{...props}>
<LayerDepthProvider>
- <LayerContentBoundary>
- <div ref={containerRef} {...stylex.props(styles.container)}>
- {/* Close button */}
- <IconButton
- icon={<Icon icon="close" size="sm" color="inherit" />}
- label={t('@astryx.lightbox.close')}
- variant="ghost"
- onClick={handleClose}
- xstyle={[styles.closeButton, styles.controlButton]}
- />
-
- {/* Gallery nav: prev — stays mounted and is disabled at the start of
- the range so pressing/arrowing to the boundary doesn't unmount the
- focused control and drop focus to <body>. */}
- {isGallery && (
+ <ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen}>
+ <LayerContentBoundary>
+ <div ref={containerRef} {...stylex.props(styles.container)}>
+ {/* Close button */}
<IconButton
- icon={
- <Icon
- icon="chevronLeft"
- size="sm"
- color="inherit"
- xstyle={rtlStyles.mirror}
- />
- }
- label={t('@astryx.lightbox.previous')}
+ icon={<Icon icon="close" size="sm" color="inherit" />}
+ label={t('@astryx.lightbox.close')}
variant="ghost"
- isDisabled={!canPrev}
- onClick={goToPrev}
- xstyle={[
- styles.navButton,
- styles.navPrev,
- styles.controlButton,
- ]}
+ onClick={handleClose}
+ xstyle={[styles.closeButton, styles.controlButton]}
/>
- )}
-
- {/* Media + caption group (centered together) */}
- <div {...stylex.props(styles.mediaGroup)}>
- <div
- ref={imageWrapperRef}
- // The wrapper is a keyboard-operable zoom toggle when zoom is
- // enabled: Enter/Space toggles, aria-pressed reflects state.
- role={isZoomTarget ? 'button' : undefined}
- tabIndex={isZoomTarget ? 0 : undefined}
- aria-pressed={isZoomTarget ? isZoomed : undefined}
- aria-label={
- isZoomTarget ? t('@astryx.lightbox.zoom') : undefined
- }
- {...stylex.props(
- styles.imageWrapper,
- isZoomTarget && focusOutlineStyles.focusVisible,
- !isVideo &&
- hasZoom &&
- !isZoomed &&
- styles.imageWrapperZoomable,
- !isVideo && isZoomed && styles.imageWrapperZoomed,
- !isVideo && isDragging && styles.imageWrapperDragging,
- )}
- onDoubleClick={isVideo ? undefined : handleDoubleClick}
- onKeyDown={isZoomTarget ? handleImageKeyDown : undefined}
- onPointerDown={isVideo ? undefined : handlePointerDown}>
- {isVideo ? (
- <video
- src={currentItem.src}
- aria-label={currentItem.alt}
- controls
- autoPlay={hasAutoPlay}
- {...stylex.props(styles.video)}
- />
- ) : (
- <img
- src={currentItem.src}
- alt={currentItem.alt}
- draggable={false}
- {...stylex.props(
- styles.image,
- isDragging && styles.imageDragging,
- imageTransform != null &&
- dynamicStyles.imageTransform(imageTransform),
- )}
- />
+
+ {/* Gallery nav: prev — stays mounted and is disabled at the start of
+ the range so pressing/arrowing to the boundary doesn't unmount the
+ focused control and drop focus to <body>. */}
+ {isGallery && (
+ <IconButton
+ icon={
+ <Icon
+ icon="chevronLeft"
+ size="sm"
+ color="inherit"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ label={t('@astryx.lightbox.previous')}
+ variant="ghost"
+ isDisabled={!canPrev}
+ onClick={goToPrev}
+ xstyle={[
+ styles.navButton,
+ styles.navPrev,
+ styles.controlButton,
+ ]}
+ />
+ )}
+
+ {/* Media + caption group (centered together) */}
+ <div {...stylex.props(styles.mediaGroup)}>
+ <div
+ ref={imageWrapperRef}
+ // The wrapper is a keyboard-operable zoom toggle when zoom is
+ // enabled: Enter/Space toggles, aria-pressed reflects state.
+ role={isZoomTarget ? 'button' : undefined}
+ tabIndex={isZoomTarget ? 0 : undefined}
+ aria-pressed={isZoomTarget ? isZoomed : undefined}
+ aria-label={
+ isZoomTarget ? t('@astryx.lightbox.zoom') : undefined
+ }
+ {...stylex.props(
+ styles.imageWrapper,
+ isZoomTarget && focusOutlineStyles.focusVisible,
+ !isVideo &&
+ hasZoom &&
+ !isZoomed &&
+ styles.imageWrapperZoomable,
+ !isVideo && isZoomed && styles.imageWrapperZoomed,
+ !isVideo && isDragging && styles.imageWrapperDragging,
+ )}
+ onDoubleClick={isVideo ? undefined : handleDoubleClick}
+ onKeyDown={isZoomTarget ? handleImageKeyDown : undefined}
+ onPointerDown={isVideo ? undefined : handlePointerDown}>
+ {isVideo ? (
+ <video
+ src={currentItem.src}
+ aria-label={currentItem.alt}
+ controls
+ autoPlay={hasAutoPlay}
+ {...stylex.props(styles.video)}
+ />
+ ) : (
+ <img
+ src={currentItem.src}
+ alt={currentItem.alt}
+ draggable={false}
+ {...stylex.props(
+ styles.image,
+ isDragging && styles.imageDragging,
+ imageTransform != null &&
+ dynamicStyles.imageTransform(imageTransform),
+ )}
+ />
+ )}
+ </div>
+
+ {currentItem.caption && (
+ <div {...stylex.props(styles.caption)}>
+ {currentItem.caption}
+ </div>
)}
</div>
- {currentItem.caption && (
- <div {...stylex.props(styles.caption)}>
- {currentItem.caption}
+ {/* Gallery nav: next — see "prev" above; stays mounted and disabled at
+ the end of the range instead of unmounting. */}
+ {isGallery && (
+ <IconButton
+ icon={
+ <Icon
+ icon="chevronRight"
+ size="sm"
+ color="inherit"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ label={t('@astryx.lightbox.next')}
+ variant="ghost"
+ isDisabled={!canNext}
+ onClick={goToNext}
+ xstyle={[
+ styles.navButton,
+ styles.navNext,
+ styles.controlButton,
+ ]}
+ />
+ )}
+
+ {/* Gallery counter */}
+ {isGallery && mediaArray.length > 1 && (
+ <div {...stylex.props(styles.counter)}>
+ {index + 1} / {mediaArray.length}
</div>
)}
</div>
-
- {/* Gallery nav: next — see "prev" above; stays mounted and disabled at
- the end of the range instead of unmounting. */}
- {isGallery && (
- <IconButton
- icon={
- <Icon
- icon="chevronRight"
- size="sm"
- color="inherit"
- xstyle={rtlStyles.mirror}
- />
- }
- label={t('@astryx.lightbox.next')}
- variant="ghost"
- isDisabled={!canNext}
- onClick={goToNext}
- xstyle={[
- styles.navButton,
- styles.navNext,
- styles.controlButton,
- ]}
- />
- )}
-
- {/* Gallery counter */}
- {isGallery && mediaArray.length > 1 && (
- <div {...stylex.props(styles.counter)}>
- {index + 1} / {mediaArray.length}
- </div>
- )}
- </div>
- </LayerContentBoundary>
+ </LayerContentBoundary>
+ </ModalAnnounceProvider>
</LayerDepthProvider>
</dialog>
);
diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsx
index b32cf6e979..0da8e0abd7 100644
--- a/packages/core/src/MobileNav/MobileNav.tsx
+++ b/packages/core/src/MobileNav/MobileNav.tsx
@@ -72,6 +72,7 @@ import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
import {overlayPaddingReset} from '../Layout/padding.stylex';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
@@ -699,43 +700,48 @@ export function MobileNav({
}
onClick={composeEventHandlers(onClickProp, handleDialogClick)}
onCancel={handleCancel}>
- <LayerDepthProvider>
- <LayerContentBoundary>
- {/* Drawer panel — tabIndex so showModal() focuses the drawer, not the close button */}
- <div
- tabIndex={-1}
- {...stylex.props(
- styles.drawer,
- dynamicStyles.width(width),
- isStart && styles.drawerStart,
- isStart && isOpen && styles.drawerStartOpen,
- !isStart && styles.drawerEnd,
- !isStart && isOpen && styles.drawerEndOpen,
- )}>
- {/* Header — content + close button */}
+ <ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen}>
+ <LayerDepthProvider>
+ <LayerContentBoundary>
+ {/* Drawer panel — tabIndex so showModal() focuses the drawer, not the close button */}
<div
- {...stylex.props(styles.header, !header && styles.headerNoTitle)}>
- {typeof header === 'string' ? (
- <Heading level={2} xstyle={styles.headerText}>
- {header}
- </Heading>
- ) : (
- (header ?? null)
- )}
- <Button
- variant="ghost"
- label={t('@astryx.mobileNav.closeNavigation')}
- icon={<Icon icon="close" color="inherit" />}
- onClick={() => onOpenChange(false)}
- isIconOnly
- />
+ tabIndex={-1}
+ {...stylex.props(
+ styles.drawer,
+ dynamicStyles.width(width),
+ isStart && styles.drawerStart,
+ isStart && isOpen && styles.drawerStartOpen,
+ !isStart && styles.drawerEnd,
+ !isStart && isOpen && styles.drawerEndOpen,
+ )}>
+ {/* Header — content + close button */}
+ <div
+ {...stylex.props(
+ styles.header,
+ !header && styles.headerNoTitle,
+ )}>
+ {typeof header === 'string' ? (
+ <Heading level={2} xstyle={styles.headerText}>
+ {header}
+ </Heading>
+ ) : (
+ (header ?? null)
+ )}
+ <Button
+ variant="ghost"
+ label={t('@astryx.mobileNav.closeNavigation')}
+ icon={<Icon icon="close" color="inherit" />}
+ onClick={() => onOpenChange(false)}
+ isIconOnly
+ />
+ </div>
+
+ {/* Scrollable content */}
+ <div {...stylex.props(styles.content)}>{children}</div>
</div>
-
- {/* Scrollable content */}
- <div {...stylex.props(styles.content)}>{children}</div>
- </div>
- </LayerContentBoundary>
- </LayerDepthProvider>
+ </LayerContentBoundary>
+ </LayerDepthProvider>
+ </ModalAnnounceProvider>
</dialog>
);
}
diff --git a/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx b/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx
index 81213603cf..45d65d4a91 100644
--- a/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx
+++ b/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx
@@ -344,7 +344,9 @@ describe.each(OWNERS)(
const dialog = document.querySelector('dialog') as HTMLDialogElement;
rerender(<dialog open>{renderOwner(true)}</dialog>);
await nextFrame();
- const region = dialog.querySelector('[data-astryx-modal-busy-region]');
+ const region = dialog.querySelector(
+ '[data-astryx-modal-live-region="polite"]',
+ );
expect(region).not.toBeNull();
expect(region).toHaveAttribute('role', 'status');
expect(region).toHaveAttribute('aria-live', 'polite');
@@ -370,7 +372,7 @@ describe.each(OWNERS)(
await nextFrame();
const dialog = document.querySelector('dialog') as HTMLDialogElement;
expect(
- dialog.querySelector('[data-astryx-modal-busy-region]'),
+ dialog.querySelector('[data-astryx-modal-live-region="polite"]'),
).toHaveTextContent('Loading');
expect(busyAnnouncements()).toEqual([]);
});
@@ -436,7 +438,7 @@ describe.each(SEARCH_OWNERS)(
await nextFrame();
const dialog = document.querySelector('dialog') as HTMLDialogElement;
expect(
- dialog.querySelector('[data-astryx-modal-busy-region]'),
+ dialog.querySelector('[data-astryx-modal-live-region="polite"]'),
).toHaveTextContent('Loading');
expect(busyAnnouncements()).toEqual([]);
vi.restoreAllMocks();
@@ -570,7 +572,7 @@ describe.each(SHEET_OWNERS)(
await nextFrame();
await nextFrame();
expect(
- sheet!.querySelector('[data-astryx-modal-busy-region]'),
+ sheet!.querySelector('[data-astryx-modal-live-region="polite"]'),
).toHaveTextContent('Loading');
expect(busyAnnouncements()).toEqual([]);
});
@@ -801,7 +803,7 @@ describe('CommandPalette busy start inside its modal (spec:AST-086 FR8, FR3)', (
return (
document
.querySelector('dialog[open]')
- ?.querySelector('[data-astryx-modal-busy-region]') ?? null
+ ?.querySelector('[data-astryx-modal-live-region="polite"]') ?? null
);
}
diff --git a/packages/core/src/hooks/ModalAnnounceProvider.tsx b/packages/core/src/hooks/ModalAnnounceProvider.tsx
new file mode 100644
index 0000000000..4453193e6e
--- /dev/null
+++ b/packages/core/src/hooks/ModalAnnounceProvider.tsx
@@ -0,0 +1,155 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file ModalAnnounceProvider.tsx
+ * @input Uses React context, effects and the exposure and delivery
+ * internals of useAnnounce
+ * @output Exports ModalAnnounceProvider, the element every Astryx component
+ * that owns a native <dialog> renders around its content
+ * @position Core a11y internal (spec:AST-086 FR14). Its own module so only
+ * the modals' bundles carry it: a component that calls useAnnounce but
+ * renders no modal does not load the provider.
+ *
+ * SYNC: not exported from /packages/core/src/hooks/index.ts.
+ */
+
+import {
+ use,
+ useEffect,
+ useMemo,
+ useRef,
+ type ReactNode,
+ type RefObject,
+} from 'react';
+import {
+ forgetPresented,
+ handOffUnexposed,
+ isExposed,
+ notePresented,
+ releaseAllHeld,
+} from './modalAnnounce';
+import {ModalAnnounceContext, type ModalAnnounceScope} from './useAnnounce';
+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
+
+/**
+ * Rendered by every Astryx component that owns a native `<dialog>` (Dialog,
+ * BottomSheet, Drawer, Lightbox; CommandPalette through Dialog), around the
+ * dialog's content, so `useAnnounce` beneath it routes into that dialog while
+ * it is open as a modal. The provider watches the dialog's `open`, `inert`
+ * and `aria-hidden` attributes: when the dialog stops being exposed, any
+ * message its containers hold that assistive technology has not had yet is
+ * handed to the channel exposed then — the modal on top, or the shared
+ * channel — and the same happens when the provider unmounts with the dialog
+ * still open. A dialog closed and shown again in one task is exposed again
+ * by the time the change is seen, so its words stay (a hand-over, not a
+ * close).
+ *
+ * Internal: imported by path inside the package; not exported from the hooks
+ * barrel or the package entry.
+ */
+export function ModalAnnounceProvider({
+ dialogRef,
+ isOpen,
+ children,
+}: {
+ dialogRef: RefObject<HTMLDialogElement | null>;
+ /**
+ * The owner's intent for this render: open as a modal (or presented as a
+ * modal step). A non-modal surface — a scrimless Drawer shown with
+ * `showPopover()`, a scrimless sheet — passes `false`: it is not an FR14
+ * modal, and callers inside it route as the page does.
+ */
+ isOpen: boolean;
+ children: ReactNode;
+}): ReactNode {
+ const parent = use(ModalAnnounceContext);
+ const scope = useMemo<ModalAnnounceScope>(
+ () => ({dialogRef, isOpen: false, parent}),
+ [dialogRef, parent],
+ );
+ // The intent is read at call time, not rendered: the scope keeps its
+ // identity across opens and closes, so `useAnnounce`'s function does too.
+ // A layout effect runs before any content's passive effect, so a message
+ // announced from a mount effect in the opening commit sees the intent.
+ useIsomorphicLayoutEffect(() => {
+ scope.isOpen = isOpen;
+ }, [scope, isOpen]);
+ // The presentation watch is a session: it starts when the owner intends
+ // the dialog open (or finds it already open), follows `open`, `inert` and
+ // `aria-hidden` through the exit, and ends once the dialog has really
+ // closed, or when the provider unmounts. A closed dialog at rest — a
+ // preloaded sheet, a Drawer never shown — holds no observer
+ // (`architecture:react-component-runtime` INV5).
+ const sessionRef = useRef<{
+ dialog: HTMLDialogElement;
+ stop: () => void;
+ } | null>(null);
+ useEffect(() => {
+ const dialog = dialogRef.current;
+ if (dialog == null || sessionRef.current != null) {
+ return;
+ }
+ if (!isOpen && !dialog.open) {
+ return;
+ }
+ notePresented(dialog);
+ let wasOpen = dialog.open;
+ const end = () => {
+ presentation.disconnect();
+ forgetPresented(dialog);
+ sessionRef.current = null;
+ };
+ const stop = () => presentation.disconnect();
+ const onPresentationChange = () => {
+ // The order is the top-layer order: only `open` being set moves a
+ // dialog up it. A dialog turning inert or aria-hidden for its exit
+ // keeps its place, so the step the person went back to stays on top.
+ if (dialog.open !== wasOpen) {
+ wasOpen = dialog.open;
+ notePresented(dialog);
+ }
+ if (!isExposed(dialog)) {
+ handOffUnexposed(dialog);
+ }
+ // Closed for real, or exposed again after an exit that was called
+ // off: whatever waited for this moment — held by this dialog, or by
+ // one this dialog was covering — goes out.
+ if (!dialog.open || isExposed(dialog)) {
+ releaseAllHeld();
+ }
+ // Closed for real: the session is over until the next open intent. A
+ // dialog closed and shown again in one task is open again by the time
+ // the change is seen, so its session goes on.
+ if (!dialog.open) {
+ end();
+ }
+ };
+ const presentation = new MutationObserver(onPresentationChange);
+ presentation.observe(dialog, {
+ attributes: true,
+ attributeFilter: ['open', 'inert', 'aria-hidden'],
+ });
+ sessionRef.current = {dialog, stop};
+ }, [dialogRef, isOpen]);
+ useEffect(
+ () => () => {
+ const session = sessionRef.current;
+ if (session == null) {
+ return;
+ }
+ sessionRef.current = null;
+ session.stop();
+ // Unmounted while open: no close event, no attribute change — the
+ // words would otherwise stay in a detached container. Handed off
+ // before this dialog leaves the order, so the next channel is found
+ // from where it stood.
+ handOffUnexposed(session.dialog);
+ forgetPresented(session.dialog);
+ releaseAllHeld();
+ },
+ [],
+ );
+ return <ModalAnnounceContext value={scope}>{children}</ModalAnnounceContext>;
+}
diff --git a/packages/core/src/hooks/modalAnnounce.ts b/packages/core/src/hooks/modalAnnounce.ts
new file mode 100644
index 0000000000..24c944d847
--- /dev/null
+++ b/packages/core/src/hooks/modalAnnounce.ts
@@ -0,0 +1,439 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file modalAnnounce.ts
+ * @input Uses the live-region internals of useAnnounce and DOM dialog state
+ * @output Installs the modal route into useAnnounce as it loads, and exports
+ * the presentation bookkeeping ModalAnnounceProvider drives
+ * @position Core a11y internal (spec:AST-086 FR14): where a message from
+ * inside an Astryx modal is heard. A dialog is exposed when it is open as
+ * a modal and neither inert nor aria-hidden; the top-layer order is kept
+ * by `open` alone; a message a dialog holds when it stops being exposed is
+ * 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
+ * a component that calls useAnnounce and renders no modal does not carry
+ * it.
+ *
+ * SYNC: not exported from /packages/core/src/hooks/index.ts.
+ */
+
+import {
+ announceMessage,
+ clearModalRegion,
+ clearRegion,
+ installModalRoute,
+ isOpenModal,
+ modalRegion,
+ unexposedMessages,
+ withdrawFromModalRegion,
+ writeModalRegion,
+ type AnnouncePoliteness,
+ type ModalAnnounceScope,
+} from './useAnnounce';
+
+/**
+ * Whether what is written inside `dialog` reaches assistive technology: open
+ * as a modal, and not taken out of the accessibility tree by `inert` or
+ * `aria-hidden` — a BottomSheet, standalone or a switcher step, stays open
+ * through its exit motion in exactly that state.
+ */
+export function isExposed(dialog: HTMLDialogElement): boolean {
+ return (
+ isOpenModal(dialog) &&
+ !dialog.inert &&
+ dialog.getAttribute('aria-hidden') !== 'true'
+ );
+}
+
+/**
+ * The nearest open native modal dialog among the Astryx modals enclosing a
+ * caller: a scrimless BottomSheet or Drawer is a dialog that is open but not
+ * modal, so the walk continues to the modal above it.
+ */
+function enclosingOpenModal(
+ scope: ModalAnnounceScope | null,
+): HTMLDialogElement | null {
+ for (let s = scope; s != null; s = s.parent) {
+ const dialog = s.dialogRef.current;
+ if (isOpenModal(dialog)) {
+ return dialog;
+ }
+ }
+ return null;
+}
+
+// The dialogs the providers have seen open, in the order they were last
+// presented. `showModal()` sets `open` as it is called, so the order of the
+// attribute records is the top-layer order, and the last one still open as a
+// modal is the modal on top.
+const presented: HTMLDialogElement[] = [];
+
+export function notePresented(dialog: HTMLDialogElement): void {
+ const at = presented.indexOf(dialog);
+ if (at !== -1) {
+ presented.splice(at, 1);
+ }
+ if (dialog.open) {
+ presented.push(dialog);
+ }
+}
+
+export function forgetPresented(dialog: HTMLDialogElement): void {
+ const at = presented.indexOf(dialog);
+ if (at !== -1) {
+ presented.splice(at, 1);
+ }
+}
+
+/**
+ * The modal on top among the ones Astryx renders: the last presented that is
+ * open, modal and exposed. One above it that is exiting (open, not exposed)
+ * is on its way out and does not count — the step the person went back to
+ * is on top while the step they left fades.
+ */
+function topExposedModal(): HTMLDialogElement | null {
+ for (let i = presented.length - 1; i >= 0; i -= 1) {
+ if (isExposed(presented[i])) {
+ return presented[i];
+ }
+ }
+ return null;
+}
+
+/**
+ * The channel exposed to the person right now, other than `except`, read
+ * down the top-layer order: the first dialog that is exposed is it; a dialog
+ * still open as a modal but not exposed — one running its exit above the
+ * rest — covers everything beneath it, so nothing is exposed yet
+ * (`'covered'`); the page body (`null`) is exposed once no native modal is
+ * open.
+ */
+function nextExposedChannel(
+ except: HTMLDialogElement,
+): HTMLDialogElement | 'covered' | null {
+ for (let i = presented.length - 1; i >= 0; i -= 1) {
+ const dialog = presented[i];
+ if (dialog !== except && isExposed(dialog)) {
+ return dialog;
+ }
+ // `except` itself, still an open modal through its exit, covers what is
+ // beneath it as any other exiting modal does.
+ if (isOpenModal(dialog)) {
+ return 'covered';
+ }
+ }
+ // A modal presented in this same task is not in the list yet (its
+ // attribute record is delivered after the task): the document still knows
+ // it. With no presentation order to go by, the last such dialog in the
+ // document stands for the one on top.
+ let fallback: HTMLDialogElement | null = null;
+ for (const dialog of document.querySelectorAll('dialog')) {
+ if (dialog !== except && !presented.includes(dialog) && isExposed(dialog)) {
+ fallback = dialog;
+ }
+ }
+ return fallback;
+}
+
+/** Whether any native modal dialog is open in the document right now. */
+function isAnyModalOpen(): boolean {
+ for (const dialog of document.querySelectorAll('dialog')) {
+ if (isOpenModal(dialog)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Words waiting for an exiting modal's real close: their dialog has left
+// 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[]>>();
+
+function hold(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness,
+): 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);
+ }
+}
+
+/** Drop what `dialog` holds for `politeness`: the owner took it back. */
+function dropHeld(
+ dialog: HTMLDialogElement,
+ politeness: AnnouncePoliteness,
+): void {
+ const slot = held.get(dialog);
+ if (slot == null) {
+ return;
+ }
+ slot[politeness] = [];
+ if (slot.polite.length === 0 && slot.assertive.length === 0) {
+ held.delete(dialog);
+ }
+}
+
+/** Deliver what `dialog` held, now that a channel may be exposed. */
+function releaseHeld(dialog: HTMLDialogElement): void {
+ const slot = held.get(dialog);
+ if (slot == null) {
+ return;
+ }
+ 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);
+ }
+ }
+ }
+}
+
+export function releaseAllHeld(): void {
+ for (const dialog of [...held.keys()]) {
+ releaseHeld(dialog);
+ }
+}
+
+/**
+ * Deliver `message` through the channel exposed now that `dialog` is not:
+ * the modal on top, the page body once no modal is open, or — while the
+ * dialog is still an open modal through its exit, with nothing exposed —
+ * held until it closes.
+ */
+function deliverBeyond(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness,
+): void {
+ 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;
+ }
+ if (next != null) {
+ announceInModalRouted(next, message, politeness);
+ return;
+ }
+ announceMessage(message, politeness);
+}
+
+/**
+ * Move whatever `dialog`'s containers hold that assistive technology has not
+ * had yet to the channel exposed now. Called when the dialog stops being
+ * exposed — closed, taken inert or `aria-hidden` for its exit, or unmounted
+ * while open — so a message sent just before is not lost (FR14).
+ */
+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);
+ }
+ }
+}
+
+/**
+ * An empty message from inside `dialog`: withdraw the words its region for
+ * `politeness` holds or is about to hold, and the words of that urgency
+ * waiting for the dialog's real close, so a status taken back while the
+ * dialog exits ("3 results", then the query is cleared) is not delivered
+ * after all once the dialog has closed.
+ */
+function withdrawFromModal(
+ dialog: HTMLDialogElement,
+ politeness: AnnouncePoliteness,
+): void {
+ clearModalRegion(dialog, politeness);
+ dropHeld(dialog, politeness);
+}
+
+/** Take the unexposed messages out of a dialog's region, clearing it. */
+function takeUnexposed(
+ dialog: HTMLDialogElement,
+ politeness: AnnouncePoliteness,
+): string[] {
+ const region = modalRegion(dialog, politeness);
+ if (region == null) {
+ return [];
+ }
+ const waiting = unexposedMessages(region);
+ clearModalRegion(dialog, politeness);
+ return waiting;
+}
+
+function announceInModalRouted(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness = 'polite',
+): void {
+ if (!isExposed(dialog)) {
+ deliverBeyond(dialog, message, politeness);
+ return;
+ }
+ const top = topExposedModal();
+ if (top != null && top !== dialog && presented.includes(dialog)) {
+ // Covered by a later Astryx modal: the owner is not operable until that
+ // 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;
+ }
+ writeModalRegion(dialog, message, politeness, {
+ isExposed: () => isExposed(dialog),
+ redirect: joined => deliverBeyond(dialog, joined, 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.
+interface Deferred {
+ frame: number;
+ messages: Record<AnnouncePoliteness, string[]>;
+ clears: Record<AnnouncePoliteness, boolean>;
+}
+const deferredByScope = new WeakMap<ModalAnnounceScope, Deferred>();
+
+function deferUntilPresented(
+ scope: ModalAnnounceScope,
+ message: string,
+ politeness: AnnouncePoliteness,
+): void {
+ let deferred = deferredByScope.get(scope);
+ if (deferred == null) {
+ const created: Deferred = {
+ frame: requestAnimationFrame(() => {
+ deferredByScope.delete(scope);
+ const opened = enclosingOpenModal(scope);
+ for (const urgency of ['polite', 'assertive'] as const) {
+ if (created.clears[urgency]) {
+ if (opened != null) {
+ withdrawFromModal(opened, urgency);
+ } else {
+ clearRegion(urgency);
+ }
+ }
+ for (const text of created.messages[urgency]) {
+ if (opened != null) {
+ announceInModalRouted(opened, text, urgency);
+ } else {
+ announceMessage(text, urgency);
+ }
+ }
+ }
+ }),
+ messages: {polite: [], assertive: []},
+ clears: {polite: false, assertive: false},
+ };
+ deferred = created;
+ deferredByScope.set(scope, deferred);
+ }
+ if (!message) {
+ deferred.messages[politeness] = [];
+ deferred.clears[politeness] = true;
+ return;
+ }
+ if (!deferred.messages[politeness].includes(message)) {
+ deferred.messages[politeness].push(message);
+ }
+}
+
+/**
+ * Whether a provider nearer than the first open modal in the chain is meant
+ * to be open but its dialog is not open yet: the caller sits inside a modal
+ * being presented in this commit, which will be the one on top.
+ */
+function isBeingPresented(scope: ModalAnnounceScope | null): boolean {
+ for (let s = scope; s != null; s = s.parent) {
+ const dialog = s.dialogRef.current;
+ if (isOpenModal(dialog)) {
+ return false;
+ }
+ if (s.isOpen && (dialog == null || !dialog.open)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * `useAnnounce` from inside `scope`, resolved per call: the same owner is
+ * sometimes inside a modal and sometimes not, and the modal it is in may have
+ * just opened or closed.
+ */
+function announceFromScope(
+ scope: ModalAnnounceScope,
+ message: string,
+ politeness: AnnouncePoliteness,
+): void {
+ 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
+ // Dialog — before the Dialog's own Effect, which runs after its
+ // content's, has called showModal(). Choose the route a frame later,
+ // when it has, rather than the modal beneath, which the new one is about
+ // to cover; an empty message in the same commit withdraws what waits
+ // (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;
+ }
+ const dialog = enclosingOpenModal(scope);
+ if (!message) {
+ // An empty message clears any lingering status, including messages
+ // joined but not yet exposed and words held for the dialog's close.
+ if (dialog != null) {
+ withdrawFromModal(dialog, politeness);
+ } else {
+ clearRegion(politeness);
+ }
+ return;
+ }
+ if (dialog != null) {
+ announceInModalRouted(dialog, 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 522f3ddfda..395c523251 100644
--- a/packages/core/src/hooks/useAnnounce.doc.mjs
+++ b/packages/core/src/hooks/useAnnounce.doc.mjs
@@ -24,12 +24,12 @@ export const docs = {
name: 'announce',
type: '(message: string, politeness?: "polite" | "assertive") => void',
description:
- 'Speaks a message through the shared live region. 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. An empty message clears any lingering status, including joined messages not yet spoken, instead of announcing.',
},
],
usage: {
description:
- 'Imperatively announces a message to screen readers through a visually-hidden live region. Use it for state that is only conveyed visually; search result counts, "no results", loading and saved confirmations, validation errors (WCAG 4.1.3 Status Messages). The polite and assertive regions are created empty on first use and stay mounted, which is what makes announcements reliable: most screen readers ignore a live region that is inserted together with its content. Each message is cleared a couple of seconds after it is announced so stale status does not linger in the accessibility tree.',
+ 'Imperatively announces a message to screen readers through a visually-hidden live region. Use it for state that is only conveyed visually; search result counts, "no results", loading and saved confirmations, validation errors (WCAG 4.1.3 Status Messages). The polite and assertive regions are created empty on first use and stay mounted, which is what makes announcements reliable: most screen readers ignore a live region that is inserted together with its content. Each message is cleared a couple of seconds after it is announced so stale status does not linger in the accessibility tree. A message is delivered where its caller is: from inside an open Astryx modal it goes to a region inside that modal and is heard there with no change to the calling code; a message sent just as the modal is dismissed is delivered through whatever is exposed afterwards rather than lost. A call made outside the modal, even by the component that renders it, uses the page-body region.',
bestPractices: [
{
guidance: true,
@@ -62,10 +62,10 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
description:
- 'Imperative screen-reader announcements via a visually-hidden live 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.',
+ '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.',
returnDescriptions: {
announce:
- 'speaks message through shared live region. 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; empty message clears lingering + not-yet-spoken status.',
},
usage: {
description:
diff --git a/packages/core/src/hooks/useAnnounce.modal.test.tsx b/packages/core/src/hooks/useAnnounce.modal.test.tsx
new file mode 100644
index 0000000000..2110a97dbf
--- /dev/null
+++ b/packages/core/src/hooks/useAnnounce.modal.test.tsx
@@ -0,0 +1,1291 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file useAnnounce.modal.test.tsx
+ * @input Uses vitest, Testing Library, useAnnounce, and the Astryx modals
+ * @output Proof of spec:AST-086 FR14: a message follows the nearest open
+ * native modal enclosing its caller — inside an Astryx Dialog, modal
+ * BottomSheet, modal Drawer or Lightbox it reaches that dialog's own
+ * persistent containers; a caller outside, or inside a non-modal sheet
+ * with no modal above it, keeps the shared channel; a non-modal sheet
+ * nested in a modal routes to the modal; a modal over a modal routes to
+ * the top one; a message unexposed when its modal closes is handed to the
+ * channel exposed after the close; join, identical-repeat and empty-message
+ * rules hold inside the dialog
+ * @position Core a11y tests beside the hook
+ */
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
+import {Dialog} from '../Dialog/Dialog';
+import {Drawer} from '../Drawer/Drawer';
+import {BottomSheetSwitcher} from '../BottomSheet/BottomSheetSwitcher';
+import {Lightbox} from '../Lightbox/Lightbox';
+import {MobileNav} from '../MobileNav/MobileNav';
+import {Popover} from '../Popover/Popover';
+import {DropdownMenu} from '../DropdownMenu/DropdownMenu';
+import {useBusyAnnouncement} from './useBusyAnnouncement';
+import {ModalAnnounceProvider} from './ModalAnnounceProvider';
+import {__resetLiveRegionsForTest, useAnnounce} from './useAnnounce';
+
+function Owner({
+ message = 'Added Design',
+ urgency,
+ label = 'Say',
+}: {
+ message?: string;
+ urgency?: 'assertive';
+ label?: string;
+}) {
+ const announce = useAnnounce();
+ return (
+ <button type="button" onClick={() => announce(message, urgency)}>
+ {label}
+ </button>
+ );
+}
+
+function TwoMessageOwner() {
+ const announce = useAnnounce();
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => {
+ announce('Added Design');
+ announce('Removed Eng');
+ }}>
+ Both
+ </button>
+ <button type="button" onClick={() => announce('Loading')}>
+ Busy
+ </button>
+ <button type="button" onClick={() => announce('')}>
+ Withdraw
+ </button>
+ </>
+ );
+}
+
+/** 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.show = vi.fn(function (this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ delete this.dataset.modal;
+ });
+ 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);
+ });
+}
+
+async function nextFrame() {
+ await act(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+}
+
+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}"]`,
+ );
+
+beforeEach(() => {
+ __resetLiveRegionsForTest();
+ stubDialogs();
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('useAnnounce inside Astryx modals (spec:AST-086 FR14)', () => {
+ it('uses the shared channel outside any modal', async () => {
+ render(<Owner />);
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(shared()).toHaveTextContent('Added Design');
+ expect(
+ document.querySelector('[data-astryx-modal-live-region]'),
+ ).toBeNull();
+ });
+
+ it.each([
+ [
+ 'Dialog',
+ (children: ReactNode) => (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ {children}
+ </Dialog>
+ ),
+ ],
+ [
+ 'modal BottomSheet',
+ (children: ReactNode) => (
+ <BottomSheet isOpen onOpenChange={() => {}} label="Modal">
+ {children}
+ </BottomSheet>
+ ),
+ ],
+ [
+ 'modal Drawer',
+ (children: ReactNode) => (
+ <Drawer isOpen onOpenChange={() => {}} label="Modal">
+ {children}
+ </Drawer>
+ ),
+ ],
+ ] as const)(
+ 'routes a caller inside an open %s into that dialog, not the shared channel',
+ async (_name, wrap) => {
+ render(wrap(<Owner />));
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ expect(dialog.matches(':modal')).toBe(true);
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ // Inserted empty (FR3), filled on the next frame.
+ const region = regionIn(dialog);
+ expect(region).not.toBeNull();
+ expect(region).toHaveAttribute('role', 'status');
+ expect(region).toHaveAttribute('aria-live', 'polite');
+ expect(region).toHaveTextContent('');
+ await nextFrame();
+ expect(region).toHaveTextContent('Added Design');
+ expect(shared()?.textContent ?? '').toBe('');
+ },
+ );
+
+ it("routes a caller inside a Popover's bottom-sheet presentation into that sheet", async () => {
+ // Popover's `presentation="bottom-sheet"` lazily renders the shared
+ // BottomSheet, so the provider BottomSheet renders covers it.
+ render(
+ <Popover label="Filters" presentation="bottom-sheet" content={<Owner />}>
+ <button type="button">Filter</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Filter'}));
+ const dialog = await screen.findByRole('dialog', {name: 'Filters'});
+ await screen.findByRole('button', {name: 'Say'});
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(regionIn(dialog)).toHaveTextContent('Added Design');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it("routes a caller inside a DropdownMenu's bottom-sheet presentation into that sheet", async () => {
+ render(
+ <DropdownMenu
+ button={{label: 'Project actions'}}
+ presentation="bottom-sheet"
+ items={[{label: 'Edit project', onClick: () => {}}]}
+ footer={<Owner />}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: /Project actions/}));
+ const dialog = await screen.findByRole('dialog', {name: 'Project actions'});
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(regionIn(dialog)).toHaveTextContent('Added Design');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('holds no MutationObserver for a dialog closed at rest; observes from the open intent until the real close (runtime INV5)', async () => {
+ // The provider's watch is the one filtering on open/inert/aria-hidden.
+ const isPresentationWatch = (options?: MutationObserverInit) =>
+ options?.attributeFilter?.join() === 'open,inert,aria-hidden';
+ const observed: Node[] = [];
+ const disconnected: number[] = [];
+ const Original = globalThis.MutationObserver;
+ class Counting extends Original {
+ #isWatch = false;
+ observe(target: Node, options?: MutationObserverInit) {
+ if (isPresentationWatch(options)) {
+ this.#isWatch = true;
+ observed.push(target);
+ }
+ super.observe(target, options);
+ }
+ disconnect() {
+ if (this.#isWatch) {
+ disconnected.push(1);
+ }
+ super.disconnect();
+ }
+ }
+ vi.stubGlobal('MutationObserver', Counting);
+ try {
+ function Closed({isOpen}: {isOpen: boolean}) {
+ return (
+ <BottomSheet isOpen={isOpen} onOpenChange={() => {}} label="Rest">
+ <Owner />
+ </BottomSheet>
+ );
+ }
+ const {rerender} = render(<Closed isOpen={false} />);
+ expect(observed).toHaveLength(0);
+ rerender(<Closed isOpen />);
+ await nextFrame();
+ expect(observed).toHaveLength(1);
+ expect(observed[0]).toBe(screen.getByRole('dialog', {name: 'Rest'}));
+ const before = disconnected.length;
+ rerender(<Closed isOpen={false} />);
+ // The sheet runs its exit, then closes the dialog for real.
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ await nextFrame();
+ await nextFrame();
+ expect(disconnected.length).toBeGreaterThan(before);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('routes a caller inside an open Lightbox into its dialog', async () => {
+ // Lightbox renders no children; a caption is content inside its dialog.
+ render(
+ <Lightbox
+ isOpen
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo', caption: <Owner />}}
+ />,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Photo'});
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(regionIn(dialog)).toHaveTextContent('Added Design');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('keeps the shared channel inside a non-modal sheet with no modal above it', async () => {
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ hasScrim={false}
+ label="Sheet">
+ <Owner />
+ </BottomSheet>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Sheet'});
+ expect(dialog.matches(':modal')).toBe(false);
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(shared()).toHaveTextContent('Added Design');
+ expect(regionIn(dialog)).toBeNull();
+ });
+
+ it('routes a caller inside a non-modal sheet nested in a Dialog to the Dialog', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ hasScrim={false}
+ label="Sheet">
+ <Owner />
+ </BottomSheet>
+ </Dialog>,
+ );
+ const modal = screen.getByRole('dialog', {name: 'Modal'});
+ const sheet = screen.getByRole('dialog', {name: 'Sheet'});
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(regionIn(modal)).toHaveTextContent('Added Design');
+ expect(regionIn(sheet)).toBeNull();
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('routes a caller inside a modal over a modal to the top one', async () => {
+ function Host() {
+ const [isUpperOpen, setIsUpperOpen] = useState(false);
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Lower">
+ <Owner label="Lower say" message="Lower words" />
+ <button type="button" onClick={() => setIsUpperOpen(true)}>
+ Open upper
+ </button>
+ <Dialog
+ isOpen={isUpperOpen}
+ onOpenChange={setIsUpperOpen}
+ aria-label="Upper">
+ <Owner label="Upper say" message="Upper words" />
+ </Dialog>
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ const lower = screen.getByRole('dialog', {name: 'Lower'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Open upper'}));
+ const upper = screen.getByRole('dialog', {name: 'Upper'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Upper say'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Lower say'}));
+ await nextFrame();
+ expect(regionIn(upper)).toHaveTextContent('Upper words');
+ // The lower modal is covered: its owner is not operable until the upper
+ // one closes, and a message it announces meanwhile is not heard — its
+ // container is clear before it is on top again (FR14).
+ expect(regionIn(lower)?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('clears words a modal received while covered before it is on top again (FR14)', async () => {
+ function Host() {
+ const [isUpperOpen, setIsUpperOpen] = useState(false);
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Lower">
+ <Owner label="Lower say" message="Lower words" />
+ <button type="button" onClick={() => setIsUpperOpen(true)}>
+ Cover
+ </button>
+ <Dialog
+ isOpen={isUpperOpen}
+ onOpenChange={setIsUpperOpen}
+ aria-label="Upper">
+ <button type="button" onClick={() => setIsUpperOpen(false)}>
+ Uncover
+ </button>
+ </Dialog>
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ const lower = screen.getByRole('dialog', {name: 'Lower'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Cover'}));
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Lower say'}));
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Uncover'}));
+ await nextFrame();
+ await nextFrame();
+ // On top again within the clear delay, holding nothing from the time it
+ // was covered.
+ expect(lower.matches(':modal')).toBe(true);
+ expect(regionIn(lower)?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ // Heard again now that it is on top.
+ fireEvent.click(screen.getByRole('button', {name: 'Lower say'}));
+ await nextFrame();
+ expect(regionIn(lower)).toHaveTextContent('Lower words');
+ });
+
+ it('routes a message announced in the commit that opens its Dialog into the Dialog (the field error a mounting form announces)', async () => {
+ function FieldError() {
+ const announce = useAnnounce();
+ useEffect(() => {
+ // The Dialog presents from its own Effect, which runs after this one.
+ announce('Name is required', 'assertive');
+ }, [announce]);
+ return <span>Name is required</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">
+ <FieldError />
+ </Dialog>
+ )}
+ </>
+ );
+ }
+ render(<Host />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ const dialog = screen.getByRole('dialog', {name: 'Edit'});
+ expect(dialog.matches(':modal')).toBe(true);
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog, 'assertive')).toHaveTextContent('Name is required');
+ expect(shared('assertive')?.textContent ?? '').toBe('');
+ });
+
+ it('lets an empty message in the commit that opens the Dialog withdraw a message deferred in that commit (FR9)', async () => {
+ function FieldError() {
+ const announce = useAnnounce();
+ useEffect(() => {
+ announce('Name is required', 'assertive');
+ // Taken back in the same commit, before the Dialog has presented.
+ announce('', 'assertive');
+ }, [announce]);
+ return <span>Name</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">
+ <FieldError />
+ </Dialog>
+ )}
+ </>
+ );
+ }
+ render(<Host />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ const dialog = screen.getByRole('dialog', {name: 'Edit'});
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog, 'assertive')?.textContent ?? '').toBe('');
+ expect(shared('assertive')?.textContent ?? '').toBe('');
+ });
+
+ it('lets an empty message withdraw a message announced in the same commit inside an already-open Dialog (FR9)', async () => {
+ function Pair() {
+ const announce = useAnnounce();
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ announce('3 results');
+ announce('');
+ }}>
+ Pair
+ </button>
+ );
+ }
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <Pair />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Pair'}));
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it("routes a caller inside a closed Dialog (content still mounted) to the shared channel at once, joined with the frame's other messages (FR9)", async () => {
+ function Announcer({message}: {message: string}) {
+ const announce = useAnnounce();
+ useEffect(() => {
+ announce(message);
+ }, [announce, message]);
+ return null;
+ }
+ render(
+ <>
+ <Announcer message="Page loaded" />
+ <Dialog isOpen={false} onOpenChange={() => {}} aria-label="Closed">
+ <Announcer message="Inside closed" />
+ </Dialog>
+ </>,
+ );
+ await nextFrame();
+ await nextFrame();
+ // Both written in one commit, both exposed, in order: neither dropped.
+ expect(shared()?.textContent).toBe('Page loaded Inside closed');
+ expect(
+ document.querySelector('[data-astryx-modal-live-region]'),
+ ).toBeNull();
+ });
+
+ it.each([
+ [
+ 'Dialog',
+ (children: ReactNode) => (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Inner">
+ {children}
+ </Dialog>
+ ),
+ ],
+ [
+ 'modal BottomSheet',
+ (children: ReactNode) => (
+ <BottomSheet isOpen onOpenChange={() => {}} label="Inner">
+ {children}
+ </BottomSheet>
+ ),
+ ],
+ ] as const)(
+ 'routes a message announced in the commit that opens a %s inside an already-open Dialog into the inner modal, not the outer one',
+ async (_name, wrapInner) => {
+ function FieldError() {
+ const announce = useAnnounce();
+ useEffect(() => {
+ announce('Name is required', 'assertive');
+ }, [announce]);
+ return <span>Name</span>;
+ }
+ function Host() {
+ const [isInnerOpen, setIsInnerOpen] = useState(false);
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Outer">
+ <button type="button" onClick={() => setIsInnerOpen(true)}>
+ Open inner
+ </button>
+ {isInnerOpen && wrapInner(<FieldError />)}
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ const outer = screen.getByRole('dialog', {name: 'Outer'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Open inner'}));
+ const inner = screen.getByRole('dialog', {name: 'Inner'});
+ expect(inner.matches(':modal')).toBe(true);
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(inner, 'assertive')).toHaveTextContent(
+ 'Name is required',
+ );
+ expect(regionIn(outer, 'assertive')).toBeNull();
+ expect(shared('assertive')?.textContent ?? '').toBe('');
+ },
+ );
+
+ it('is heard from app code rendered inside a Dialog', async () => {
+ function AppForm() {
+ const announce = useAnnounce();
+ return (
+ <form
+ onSubmit={event => {
+ event.preventDefault();
+ announce('Saved');
+ }}>
+ <button type="submit">Save</button>
+ </form>
+ );
+ }
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit">
+ <AppForm />
+ </Dialog>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+ await nextFrame();
+ expect(
+ regionIn(screen.getByRole('dialog', {name: 'Edit'})),
+ ).toHaveTextContent('Saved');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('joins different messages written before the previous is exposed, says an identical repeat once, and clears on an empty message (FR9, FR5)', async () => {
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <TwoMessageOwner />
+ <Owner urgency="assertive" message="Failed" label="Fail" />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ fireEvent.click(screen.getByRole('button', {name: 'Both'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Both'}));
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('Added Design Removed Eng');
+ // A message in the frame the words were written still joins.
+ fireEvent.click(screen.getByRole('button', {name: 'Busy'}));
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe(
+ 'Added Design Removed Eng Loading',
+ );
+ // A frame later the words count as exposed: a new message starts fresh.
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Busy'}));
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('Loading');
+ // Assertive has its own container.
+ fireEvent.click(screen.getByRole('button', {name: 'Fail'}));
+ await nextFrame();
+ expect(regionIn(dialog, 'assertive')).toHaveAttribute('role', 'alert');
+ expect(regionIn(dialog, 'assertive')).toHaveTextContent('Failed');
+ expect(regionIn(dialog)?.textContent).toBe('Loading');
+ // An empty message withdraws the pending and shown polite text at once.
+ fireEvent.click(screen.getByRole('button', {name: 'Both'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Withdraw'}));
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('hands a message unexposed when its Dialog closes to the shared channel', async () => {
+ function SaveAndClose({onDone}: {onDone: () => void}) {
+ const announce = useAnnounce();
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ announce('Saved');
+ onDone();
+ }}>
+ Save and close
+ </button>
+ );
+ }
+ function Host() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <Dialog isOpen={isOpen} onOpenChange={setIsOpen} aria-label="Edit">
+ <SaveAndClose onDone={() => setIsOpen(false)} />
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ fireEvent.click(screen.getByRole('button', {name: 'Save and close'}));
+ await nextFrame();
+ await nextFrame();
+ // Not lost in the closed dialog: the page-body channel has it.
+ expect(shared()).toHaveTextContent('Saved');
+ });
+
+ it('hands a message unexposed when an upper modal closes to the modal then on top', async () => {
+ function Palette({onDone}: {onDone: () => void}) {
+ const announce = useAnnounce();
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ announce('3 results');
+ onDone();
+ }}>
+ Pick
+ </button>
+ );
+ }
+ function Host() {
+ const [isUpperOpen, setIsUpperOpen] = useState(true);
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Lower">
+ <Dialog
+ isOpen={isUpperOpen}
+ onOpenChange={setIsUpperOpen}
+ aria-label="Upper">
+ <Palette onDone={() => setIsUpperOpen(false)} />
+ </Dialog>
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ const lower = screen.getByRole('dialog', {name: 'Lower'});
+ fireEvent.click(screen.getByRole('button', {name: 'Pick'}));
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(lower)).toHaveTextContent('3 results');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('keeps a waiting message in a dialog that is closed and shown again in one task (a hand-over, not a close)', async () => {
+ // A switcher moves one shared dialog between steps: close() then
+ // showModal() in the same task. The native close event must not hand the
+ // step's words to the page body the person cannot hear.
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <Owner message="80 results" />
+ </Dialog>,
+ );
+ const dialog = document.querySelector<HTMLDialogElement>('dialog')!;
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ act(() => {
+ dialog.close();
+ dialog.showModal();
+ });
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)).toHaveTextContent('80 results');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('keeps a waiting message when the dialog is re-presented from a later layout effect', async () => {
+ // The entering step is presented in a layout effect of a later commit,
+ // not in the task that closed the leaving step.
+ function Steps() {
+ const [step, setStep] = useState(1);
+ const dialogRef = useRef<HTMLDialogElement>(null);
+ useLayoutEffect(() => {
+ const dialog = dialogRef.current;
+ if (dialog != null && !dialog.open) {
+ dialog.showModal();
+ }
+ }, [step]);
+ return (
+ <Dialog
+ ref={dialogRef}
+ isOpen
+ onOpenChange={() => {}}
+ aria-label="Modal">
+ <Owner message={`Step ${step} words`} />
+ <button
+ type="button"
+ onClick={() => {
+ // Close the dialog as the leaving step would, and move on; the
+ // next commit's layout effect presents the entering step.
+ dialogRef.current?.close();
+ setStep(2);
+ }}>
+ Next
+ </button>
+ </Dialog>
+ );
+ }
+ render(<Steps />);
+ const dialog = document.querySelector<HTMLDialogElement>('dialog')!;
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ expect(dialog.open).toBe(true);
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)).toHaveTextContent('Step 1 words');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('hands a message unexposed when a step closes to the sibling step opened in its place (the modal then on top)', async () => {
+ // A flow of sibling modals, as a switcher presents its steps: the leaving
+ // step announces and closes in the same update that opens the entering
+ // step. The entering step is not an ancestor of the leaving one; it is
+ // the modal on top after the close, so the words are delivered there.
+ function Flow() {
+ const [step, setStep] = useState(1);
+ return (
+ <>
+ <Dialog isOpen={step === 1} onOpenChange={() => {}} aria-label="One">
+ <Owner message="Step one saved" label="Say" />
+ <button type="button" onClick={() => setStep(2)}>
+ Next
+ </button>
+ </Dialog>
+ <Dialog isOpen={step === 2} onOpenChange={() => {}} aria-label="Two">
+ <span>Step two</span>
+ </Dialog>
+ </>
+ );
+ }
+ render(<Flow />);
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Next'}));
+ const two = screen.getByRole('dialog', {name: 'Two'});
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(two)).toHaveTextContent('Step one saved');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('holds words sent as a modal BottomSheet closes — open but inert and aria-hidden through its exit — and delivers them to the page body at the real close', async () => {
+ function Host() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label="Sheet">
+ <Owner message="Saved" />
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Done
+ </button>
+ </BottomSheet>
+ );
+ }
+ render(<Host />);
+ const sheet = document.querySelector<HTMLDialogElement>('dialog')!;
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // The sheet keeps its dialog open and modal while it leaves, but takes
+ // it out of the accessibility tree; the page body is behind an active
+ // modal until the dialog closes, so nothing is exposed yet and the
+ // words wait.
+ expect(sheet.open).toBe(true);
+ expect(sheet).toHaveAttribute('aria-hidden', 'true');
+ expect(sheet).toHaveAttribute('inert');
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(sheet)?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ // The exit motion ends: the dialog closes and the page body is exposed.
+ act(() => {
+ sheet.close();
+ });
+ await nextFrame();
+ await nextFrame();
+ expect(shared()).toHaveTextContent('Saved');
+ });
+ it('drops held words when an empty message withdraws them while the sheet exits, so nothing is delivered after the close', async () => {
+ function Host() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label="Sheet">
+ <TwoMessageOwner />
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Done
+ </button>
+ </BottomSheet>
+ );
+ }
+ render(<Host />);
+ const sheet = document.querySelector<HTMLDialogElement>('dialog')!;
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Busy'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // Held for the real close, as the sheet-exit test shows...
+ expect(sheet).toHaveAttribute('inert');
+ await nextFrame();
+ // ...until the owner takes the words back with an empty message (the
+ // exiting sheet is aria-hidden, so reach its control by element).
+ fireEvent.click(screen.getByText('Withdraw'));
+ act(() => {
+ sheet.close();
+ });
+ await nextFrame();
+ await nextFrame();
+ expect(shared()?.textContent ?? '').toBe('');
+ expect(regionIn(sheet)?.textContent ?? '').toBe('');
+ });
+
+ it('hands words sent as a switcher step hands over to the entering step', async () => {
+ window.scrollTo = vi.fn();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockReturnValue({
+ matches: false,
+ media: '',
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }),
+ );
+ function Flow() {
+ const [activeSheet, setActiveSheet] = useState<string | null>('one');
+ return (
+ <BottomSheetSwitcher
+ activeSheet={activeSheet}
+ onActiveSheetChange={setActiveSheet}>
+ <BottomSheet sheetId="one" label="One">
+ <Owner message="Overview saved" />
+ <button type="button" onClick={() => setActiveSheet('two')}>
+ Continue
+ </button>
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ <span>Step two</span>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ );
+ }
+ render(<Flow />);
+ const one = screen.getByRole('dialog', {name: 'One'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));
+ const two = screen.getByRole('dialog', {name: 'Two'});
+ // The leaving step stays open but inert through its exit; the entering
+ // step is the exposed modal.
+ expect(one).toHaveAttribute('open');
+ expect(one).toHaveAttribute('inert');
+ expect(two.matches(':modal')).toBe(true);
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(two)).toHaveTextContent('Overview saved');
+ expect(regionIn(one)?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ vi.unstubAllGlobals();
+ });
+
+ it('hands words sent just before an open Dialog is unmounted to the shared channel', async () => {
+ function Host() {
+ const [isOpen, setIsOpen] = useState(true);
+ return isOpen ? (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit">
+ <Owner message="Saved" />
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Remove
+ </button>
+ </Dialog>
+ ) : null;
+ }
+ render(<Host />);
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Remove'}));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ await nextFrame();
+ await nextFrame();
+ expect(shared()).toHaveTextContent('Saved');
+ });
+
+ it('announces a busy start inside a native modal an app renders without Astryx, opened inside a Dialog, in the app modal (FR14)', async () => {
+ function BusyThing({isBusy}: {isBusy: boolean}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useBusyAnnouncement(isBusy, 'Loading', ref);
+ return <div ref={ref}>thing</div>;
+ }
+ function Host() {
+ const appDialogRef = useRef<HTMLDialogElement>(null);
+ const [isBusy, setIsBusy] = useState(false);
+ useLayoutEffect(() => {
+ appDialogRef.current?.showModal();
+ }, []);
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Outer">
+ <dialog ref={appDialogRef} aria-label="App">
+ <BusyThing isBusy={isBusy} />
+ <button type="button" onClick={() => setIsBusy(true)}>
+ Start
+ </button>
+ </dialog>
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ const outer = screen.getByRole('dialog', {name: 'Outer'});
+ const app = screen.getByRole('dialog', {name: 'App'});
+ expect(app.matches(':modal')).toBe(true);
+ fireEvent.click(screen.getByRole('button', {name: 'Start'}));
+ // The busy hook chooses its route a frame later and the region fills a
+ // frame after that.
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(app)).toHaveTextContent('Loading');
+ expect(regionIn(outer)).toBeNull();
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('routes a caller inside an open MobileNav into its dialog', async () => {
+ render(
+ <MobileNav isOpen onOpenChange={() => {}} label="Menu">
+ <Owner />
+ </MobileNav>,
+ );
+ const nav = screen.getByRole('dialog', {name: 'Menu'});
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(regionIn(nav)).toHaveTextContent('Added Design');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('keeps the step the person went back to on top while the leaving step exits, so its messages are heard', async () => {
+ window.scrollTo = vi.fn();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockReturnValue({
+ matches: false,
+ media: '',
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }),
+ );
+ function Flow() {
+ const [activeSheet, setActiveSheet] = useState<string | null>('one');
+ return (
+ <BottomSheetSwitcher
+ activeSheet={activeSheet}
+ onActiveSheetChange={setActiveSheet}>
+ <BottomSheet sheetId="one" label="One">
+ <Owner message="Back on one" />
+ <button type="button" onClick={() => setActiveSheet('two')}>
+ Continue
+ </button>
+ </BottomSheet>
+ <BottomSheet sheetId="two" label="Two">
+ <button type="button" onClick={() => setActiveSheet('one')}>
+ Back
+ </button>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ );
+ }
+ render(<Flow />);
+ const one = screen.getByRole('dialog', {name: 'One'});
+ // Hidden steps are out of the accessibility tree; reach it by element.
+ const two = document.querySelector<HTMLDialogElement>(
+ 'dialog[aria-label="Two"]',
+ )!;
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Back'}));
+ await nextFrame();
+ // Two is leaving: still open, inert; one is the exposed step again.
+ expect(two).toHaveAttribute('open');
+ expect(two).toHaveAttribute('inert');
+ expect(one.matches(':modal')).toBe(true);
+ expect(one).not.toHaveAttribute('inert');
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(regionIn(one)).toHaveTextContent('Back on one');
+ expect(shared()?.textContent ?? '').toBe('');
+ vi.unstubAllGlobals();
+ });
+
+ it('holds words sent as a modal BottomSheet over a Dialog closes and delivers them to the Dialog at the real close', async () => {
+ function Host() {
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Edit">
+ <button type="button" onClick={() => setIsSheetOpen(true)}>
+ Open sheet
+ </button>
+ <BottomSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ label="Sheet">
+ <Owner message="Saved" />
+ <button type="button" onClick={() => setIsSheetOpen(false)}>
+ Done
+ </button>
+ </BottomSheet>
+ </Dialog>
+ );
+ }
+ render(<Host />);
+ const edit = screen.getByRole('dialog', {name: 'Edit'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Open sheet'}));
+ const sheet = screen.getByRole('dialog', {name: 'Sheet'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // The sheet, still an open modal through its exit, covers the Dialog:
+ // nothing is exposed yet, so the words wait rather than being written
+ // to the covered Dialog (which would clear them).
+ expect(sheet).toHaveAttribute('inert');
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(sheet)?.textContent ?? '').toBe('');
+ expect(regionIn(edit)?.textContent ?? '').toBe('');
+ expect(shared()?.textContent ?? '').toBe('');
+ act(() => {
+ (sheet as HTMLDialogElement).close();
+ });
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(edit)).toHaveTextContent('Saved');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+ it('withdraws a busy start written inside a modal but not yet exposed when its owner settles with its outcome (AST-086 FR8)', async () => {
+ function Search() {
+ const ref = useRef<HTMLDivElement>(null);
+ const announce = useAnnounce();
+ const [isBusy, setIsBusy] = useState(false);
+ const settle = useBusyAnnouncement(isBusy, 'Loading', ref);
+ return (
+ <div ref={ref}>
+ <button type="button" onClick={() => setIsBusy(true)}>
+ Start
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ settle();
+ setIsBusy(false);
+ announce('3 results');
+ }}>
+ Outcome
+ </button>
+ </div>
+ );
+ }
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <Search />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Start'}));
+ // The busy hook chooses its route a frame later and writes "Loading" to
+ // the dialog's container, to be exposed a frame after that...
+ await nextFrame();
+ // ...but the outcome arrives first and the owner settles.
+ fireEvent.click(screen.getByRole('button', {name: 'Outcome'}));
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('3 results');
+ expect(shared()?.textContent ?? '').toBe('');
+ });
+
+ it('withdraws only its own busy start inside a modal when another owner wrote the same words (AST-086 FR8, FR9)', async () => {
+ function Busy({label}: {label: string}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [isBusy, setIsBusy] = useState(false);
+ const settle = useBusyAnnouncement(isBusy, 'Loading', ref);
+ return (
+ <div ref={ref}>
+ <button type="button" onClick={() => setIsBusy(true)}>
+ Start {label}
+ </button>
+ <button type="button" onClick={() => settle()}>
+ Settle {label}
+ </button>
+ </div>
+ );
+ }
+ render(
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Modal">
+ <Busy label="one" />
+ <Busy label="two" />
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Start one'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Start two'}));
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Settle one'}));
+ await nextFrame();
+ await nextFrame();
+ expect(regionIn(dialog)?.textContent).toBe('Loading');
+ });
+
+ describe('a non-modal Drawer (hasScrim={false}, shown with showPopover(), never `open`)', () => {
+ beforeEach(() => {
+ // The real showPopover() leaves the dialog's `open` attribute unset.
+ HTMLElement.prototype.showPopover = vi.fn();
+ HTMLElement.prototype.hidePopover = vi.fn();
+ });
+
+ it('routes a caller inside it to the shared channel at once, joined with a page message from the same task (FR9)', async () => {
+ function Announcer({message}: {message: string}) {
+ const announce = useAnnounce();
+ useEffect(() => {
+ announce(message);
+ }, [announce, message]);
+ return null;
+ }
+ render(
+ <>
+ <Announcer message="Page loaded" />
+ <Drawer isOpen onOpenChange={() => {}} hasScrim={false} label="Side">
+ <Announcer message="Inside drawer" />
+ </Drawer>
+ </>,
+ );
+ const drawer = document.querySelector<HTMLDialogElement>('dialog')!;
+ expect(drawer.open).toBe(false);
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ await nextFrame();
+ await nextFrame();
+ expect(shared()?.textContent).toBe('Page loaded Inside drawer');
+ expect(regionIn(drawer)).toBeNull();
+ });
+
+ it('lets a busy start inside it be withdrawn by its outcome (FR8)', async () => {
+ function Search() {
+ const ref = useRef<HTMLDivElement>(null);
+ const announce = useAnnounce();
+ const [isBusy, setIsBusy] = useState(false);
+ const settle = useBusyAnnouncement(isBusy, 'Loading', ref);
+ return (
+ <div ref={ref}>
+ <button type="button" onClick={() => setIsBusy(true)}>
+ Start
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ settle();
+ setIsBusy(false);
+ announce('3 results');
+ }}>
+ Outcome
+ </button>
+ </div>
+ );
+ }
+ render(
+ <Drawer isOpen onOpenChange={() => {}} hasScrim={false} label="Side">
+ <Search />
+ </Drawer>,
+ );
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Start'}));
+ await nextFrame();
+ fireEvent.click(screen.getByRole('button', {name: 'Outcome'}));
+ await nextFrame();
+ await nextFrame();
+ expect(shared()?.textContent).toBe('3 results');
+ });
+ });
+
+ it('takes the route of where the call is: a component that renders a Dialog but announces from above it uses the shared channel', async () => {
+ function Opener() {
+ const announce = useAnnounce();
+ const dialogRef = useRef<HTMLDialogElement>(null);
+ return (
+ <>
+ <button type="button" onClick={() => announce('From above')}>
+ Above
+ </button>
+ <Dialog
+ ref={dialogRef}
+ isOpen
+ onOpenChange={() => {}}
+ aria-label="Modal">
+ <Owner message="From inside" label="Inside" />
+ </Dialog>
+ </>
+ );
+ }
+ render(<Opener />);
+ const dialog = screen.getByRole('dialog', {name: 'Modal'});
+ fireEvent.click(screen.getByRole('button', {name: 'Above'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Inside'}));
+ await nextFrame();
+ expect(shared()).toHaveTextContent('From above');
+ expect(regionIn(dialog)).toHaveTextContent('From inside');
+ });
+
+ it('lets a component that owns a modal route its own messages into it through the provider it renders', async () => {
+ // The FR14 route for CommandPalette's counts and Lightbox's position:
+ // the owner renders the provider around the part of itself that
+ // announces about the modal's content.
+ function OwnerOfModal() {
+ const dialogRef = useRef<HTMLDialogElement>(null);
+ return (
+ <Dialog
+ ref={dialogRef}
+ isOpen
+ onOpenChange={() => {}}
+ aria-label="Modal">
+ <ModalAnnounceProvider dialogRef={dialogRef} isOpen>
+ <Owner message="Routed in" />
+ </ModalAnnounceProvider>
+ </Dialog>
+ );
+ }
+ render(<OwnerOfModal />);
+ fireEvent.click(screen.getByRole('button', {name: 'Say'}));
+ await nextFrame();
+ expect(
+ regionIn(screen.getByRole('dialog', {name: 'Modal'})),
+ ).toHaveTextContent('Routed in');
+ });
+});
diff --git a/packages/core/src/hooks/useAnnounce.ts b/packages/core/src/hooks/useAnnounce.ts
index e1092afeaf..6e20522852 100644
--- a/packages/core/src/hooks/useAnnounce.ts
+++ b/packages/core/src/hooks/useAnnounce.ts
@@ -4,18 +4,30 @@
/**
* @file useAnnounce.ts
- * @input Uses React useCallback; DOM APIs and one cancellable animation frame per region for a singleton live-region pair
- * @output Exports useAnnounce hook and AnnouncePoliteness type
- * @position Core a11y hook; provides imperative screen-reader announcements
- * via persistently-mounted polite/assertive live regions; regions are
- * auto-cleared shortly after announcing so stale status text does not
- * linger in the accessibility tree
+ * @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
+ * @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
+ * dialog's own containers, since the page-body channel is not exposed
+ * 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;
+ * 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.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
*/
-import {useCallback} from 'react';
+import {createContext, use, useCallback, type RefObject} from 'react';
/**
* Announcement urgency:
@@ -153,7 +165,7 @@ function getRegions(): LiveRegions | null {
return regions;
}
-function announceMessage(
+export function announceMessage(
message: string,
politeness: AnnouncePoliteness,
): void {
@@ -198,7 +210,7 @@ function announceMessage(
* Used when the triggering context goes away (e.g. a search query is cleared),
* so stale status text does not linger in the accessibility tree.
*/
-function clearRegion(politeness: AnnouncePoliteness): void {
+export function clearRegion(politeness: AnnouncePoliteness): void {
cancelPendingFrames(politeness);
cancelScheduledClear(politeness);
if (!regions) {
@@ -233,8 +245,16 @@ function clearRegion(politeness: AnnouncePoliteness): void {
* ```
*/
export function useAnnounce(): AnnounceFn {
+ const modal = use(ModalAnnounceContext);
return useCallback(
(message: string, politeness: AnnouncePoliteness = 'polite') => {
+ // 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) {
// An empty message clears any lingering status from the region,
// including messages joined but not yet exposed — useful when the
@@ -244,10 +264,342 @@ export function useAnnounce(): AnnounceFn {
}
announceMessage(message, politeness);
},
- [],
+ [modal],
);
}
+// =============================================================================
+// Inside an Astryx modal (spec:AST-086 FR14)
+// =============================================================================
+//
+// `useAnnounce` reads the nearest ModalAnnounceProvider's scope. The route a
+// scope implies — exposure, the top-layer order, hand-off and hold on close,
+// the covered rule, deferral while a modal is being presented — lives in
+// `modalAnnounce.ts`, which ModalAnnounceProvider imports and which installs
+// itself here when it loads. A context value is non-null only where a
+// provider rendered, so the route is installed before it is needed, and a
+// component that calls `useAnnounce` but renders no modal never loads it.
+// What stays in this module is what a caller without any Astryx modal still
+// needs: the region writer the busy-announcement hook uses inside a native
+// modal an app renders without Astryx, and the DOM walk that finds it.
+
+const MODAL_REGION_ATTR = 'data-astryx-modal-live-region';
+
+/**
+ * What an Astryx modal tells the hooks beneath it: where its dialog element
+ * is, and the modal above it, so a caller inside a non-modal sheet nested in
+ * a modal still finds the modal.
+ */
+export interface ModalAnnounceScope {
+ dialogRef: RefObject<HTMLDialogElement | null>;
+ // The owner's intent: open (or presented) in this render. A dialog meant
+ // to be open that is not open yet is being presented in this commit.
+ isOpen: boolean;
+ parent: ModalAnnounceScope | null;
+}
+
+export const ModalAnnounceContext = createContext<ModalAnnounceScope | null>(
+ null,
+);
+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. */
+ announce(
+ scope: ModalAnnounceScope,
+ message: string,
+ politeness: AnnouncePoliteness,
+ ): void;
+ /** Speak inside `dialog` with the exposure, covered and hold rules. */
+ announceInModal(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness,
+ ): void;
+ /** Withdraw an announcer's share, written or held. */
+ withdrawFromModalPending(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness,
+ ): void;
+}
+
+let modalRoute: ModalRoute | null = null;
+
+/** Called once by `modalAnnounce.ts` as it loads. @internal */
+export function installModalRoute(route: ModalRoute): void {
+ modalRoute = route;
+}
+
+/** Whether `dialog` is open as a native modal right now. */
+export function isOpenModal(
+ dialog: HTMLDialogElement | null | undefined,
+): boolean {
+ return dialog != null && dialog.open && dialog.matches(':modal');
+}
+
+/**
+ * The nearest open native modal dialog enclosing `element` in the DOM, Astryx
+ * or app-rendered. Internal: the busy-announcement hook routes by its owner's
+ * element so a busy start inside a native modal an app renders without Astryx
+ * is still heard inside it (`spec:AST-086` FR14, last sentence).
+ */
+export function enclosingModalDialog(
+ element: Element | null | undefined,
+): HTMLDialogElement | null {
+ let dialog = element?.closest('dialog') ?? null;
+ while (dialog != null) {
+ if (isOpenModal(dialog)) {
+ return dialog;
+ }
+ dialog = dialog.parentElement?.closest('dialog') ?? null;
+ }
+ return null;
+}
+
+/**
+ * Speak `message` through the modal `dialog`'s own live region. With the
+ * modal route loaded (an Astryx modal is in the tree) the route applies its
+ * 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.
+ */
+export function announceInModal(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness = 'polite',
+): void {
+ if (modalRoute != null) {
+ modalRoute.announceInModal(dialog, message, politeness);
+ return;
+ }
+ 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;
+ }
+ withdrawFromModalRegion(dialog, message, politeness);
+}
+
+/** What the route asks of the writer in the write frame. @internal */
+export interface ModalWriteGuard {
+ isExposed: () => boolean;
+ redirect: (joinedMessage: string) => void;
+}
+
+// Each in-dialog region's pending state: the messages written since its text
+// was last exposed, the frame that will expose them joined, the frame after
+// that (text set in one frame is not yet taken by assistive technology in
+// that same frame, so a message arriving before this frame runs still joins
+// 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>;
+ frame: number | null;
+ settleFrame: number | null;
+ timer: ReturnType<typeof setTimeout> | null;
+}
+
+const pendingByRegion = new WeakMap<HTMLElement, ModalPending>();
+
+function cancelPending(pending: ModalPending): void {
+ if (pending.frame != null) {
+ cancelAnimationFrame(pending.frame);
+ }
+ if (pending.settleFrame != null) {
+ cancelAnimationFrame(pending.settleFrame);
+ }
+ if (pending.timer != null) {
+ clearTimeout(pending.timer);
+ }
+}
+
+/** Words written to `target` that assistive technology has not had yet. */
+export function unexposedMessages(target: HTMLElement): string[] {
+ const pending = pendingByRegion.get(target);
+ if (pending == null) {
+ return [];
+ }
+ return pending.frame != null || pending.settleFrame != null
+ ? pending.messages
+ : [];
+}
+
+export function modalRegion(
+ dialog: HTMLDialogElement,
+ politeness: AnnouncePoliteness,
+): HTMLElement | null {
+ return dialog.querySelector<HTMLElement>(
+ `:scope > [${MODAL_REGION_ATTR}="${politeness}"]`,
+ );
+}
+
+/**
+ * The dialog's own live region for one urgency, created empty on first use
+ * and kept as a direct child of the dialog so it survives the dialog's
+ * content re-rendering.
+ */
+function ensureModalRegion(
+ dialog: HTMLDialogElement,
+ politeness: AnnouncePoliteness,
+): HTMLElement {
+ let region = modalRegion(dialog, politeness);
+ if (region == null) {
+ region = document.createElement('div');
+ region.setAttribute(MODAL_REGION_ATTR, politeness);
+ region.setAttribute(
+ 'role',
+ politeness === 'assertive' ? 'alert' : 'status',
+ );
+ region.setAttribute('aria-live', politeness);
+ region.setAttribute('aria-atomic', 'true');
+ region.style.cssText = VISUALLY_HIDDEN_CSS;
+ dialog.appendChild(region);
+ }
+ return region;
+}
+
+/**
+ * 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.
+ */
+export function writeModalRegion(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness,
+ guard?: ModalWriteGuard,
+): void {
+ 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);
+ if (previous != null) {
+ cancelPending(previous);
+ }
+ // Clearing first guarantees the mutation is observed even when the new
+ // message equals the current text — some AT deduplicate identical content.
+ target.textContent = '';
+ const pending: ModalPending = {
+ messages,
+ holders,
+ frame: null,
+ settleFrame: null,
+ timer: null,
+ };
+ pending.frame = requestAnimationFrame(() => {
+ 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.
+ pendingByRegion.delete(target);
+ guard.redirect(pending.messages.join(' '));
+ return;
+ }
+ target.textContent = pending.messages.join(' ');
+ pending.settleFrame = requestAnimationFrame(() => {
+ pending.settleFrame = null;
+ });
+ pending.timer = setTimeout(() => {
+ target.textContent = '';
+ pendingByRegion.delete(target);
+ }, CLEAR_DELAY_MS);
+ });
+ pendingByRegion.set(target, pending);
+}
+
+/**
+ * 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.
+ */
+export function withdrawFromModalRegion(
+ dialog: HTMLDialogElement,
+ message: string,
+ politeness: AnnouncePoliteness = 'polite',
+): void {
+ const region = modalRegion(dialog, politeness);
+ const pending = region == null ? undefined : pendingByRegion.get(region);
+ if (
+ region != 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(' ');
+ }
+ }
+ }
+}
+
+/**
+ * Withdraw whatever the dialog's region for `politeness` holds or is about to
+ * hold, as an empty message does on the shared channel. A dialog that never
+ * announced has no region and nothing to clear.
+ */
+export function clearModalRegion(
+ dialog: HTMLDialogElement,
+ politeness: AnnouncePoliteness,
+): void {
+ const region = modalRegion(dialog, politeness);
+ if (region == null) {
+ return;
+ }
+ const pending = pendingByRegion.get(region);
+ if (pending != null) {
+ cancelPending(pending);
+ pendingByRegion.delete(region);
+ }
+ region.textContent = '';
+}
+
/**
* Takes the pending message the latest announce joined, so that announcer can
* withdraw its own share of it later. Shared with useBusyAnnouncement; not
diff --git a/packages/core/src/hooks/useBusyAnnouncement.ts b/packages/core/src/hooks/useBusyAnnouncement.ts
index e63a592d8b..e3ae84478e 100644
--- a/packages/core/src/hooks/useBusyAnnouncement.ts
+++ b/packages/core/src/hooks/useBusyAnnouncement.ts
@@ -16,9 +16,11 @@
* re-arms it. The returned function is called by an owner announcing the
* busy operation's outcome: a busy start not yet announced is dropped, so it
* never follows its own outcome (FR8). 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).
+ * exposed, so a control inside it announces through that dialog's polite
+ * container, the one `useAnnounce` uses for every message from inside the
+ * modal (FR14), inserted empty and filled a frame later (FR3); the control's
+ * own element locates the modal, so a busy start inside a native modal an app
+ * renders without Astryx is heard inside it too.
*
* SYNC: deliberately NOT exported from /packages/core/src/hooks/index.ts —
* this is a shared implementation detail of Astryx's busy controls.
@@ -26,55 +28,14 @@
import {useCallback, useEffect, useRef, type RefObject} from 'react';
import {
+ announceInModal,
+ enclosingModalDialog,
takeJoinedAnnouncement,
useAnnounce,
+ withdrawFromModalPending,
withdrawPendingAnnouncement,
} 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,
@@ -86,10 +47,16 @@ 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);
useEffect(() => {
if (!isBusy) {
hasAnnouncedRef.current = false;
channelMessageRef.current = null;
+ modalMessageRef.current = null;
return;
}
if (hasAnnouncedRef.current) {
@@ -100,9 +67,15 @@ export function useBusyAnnouncement(
const frame = requestAnimationFrame(() => {
frameRef.current = null;
hasAnnouncedRef.current = true;
- const dialog = elementRef.current?.closest('dialog');
- if (dialog?.open && dialog.matches(':modal')) {
+ // The nearest open native modal around the control's own element,
+ // Astryx or app-rendered, so a busy start inside a modal an app renders
+ // without Astryx is still heard inside it (`spec:AST-086` FR14); the
+ // shared `useAnnounce` route otherwise, which itself follows the
+ // nearest Astryx modal around this hook's caller.
+ const dialog = enclosingModalDialog(elementRef.current);
+ if (dialog != null) {
announceInModal(dialog, message);
+ modalMessageRef.current = {dialog, message};
} else {
announce(message, 'polite');
channelMessageRef.current = takeJoinedAnnouncement();
@@ -122,10 +95,16 @@ export function useBusyAnnouncement(
// Still busy until the settled state commits; do not schedule again.
hasAnnouncedRef.current = true;
}
- // Written to the channel but not yet exposed: withdraw it too.
+ // Written to the channel, or inside the modal, but not yet exposed:
+ // withdraw it too.
if (channelMessageRef.current != null) {
withdrawPendingAnnouncement(channelMessageRef.current, 'polite');
channelMessageRef.current = null;
}
+ if (modalMessageRef.current != null) {
+ const {dialog, message} = modalMessageRef.current;
+ withdrawFromModalPending(dialog, message, 'polite');
+ modalMessageRef.current = null;
+ }
}, []);
}