Skip to content

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

TypeScript

fix(Toast): the viewport is each toast's only announcement owner (#7871)

Cindy Zhanga04d2e6bf733
diff --git a/.changeset/toast-one-announcement-owner.md b/.changeset/toast-one-announcement-owner.md
new file mode 100644
index 0000000000..c28bee9bad
--- /dev/null
+++ b/.changeset/toast-one-announcement-owner.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Toast: the viewport is each toast's only announcement owner. While an open modal hosts a top-layer viewport (the default), it announces each toast through that modal's own live regions, so a toast shown over a Dialog is announced once. Elsewhere it announces through the shared channel. A viewport rendered in place announces through `useAnnounce`, which delivers inside an enclosing Astryx modal. The toast card is no longer a live region inside a viewport, including while a modal hosts it.
+
+@cixzhang
diff --git a/apps/storybook/stories/StatusMessageA11y.stories.tsx b/apps/storybook/stories/StatusMessageA11y.stories.tsx
index 0edb9da8da..313b176c94 100644
--- a/apps/storybook/stories/StatusMessageA11y.stories.tsx
+++ b/apps/storybook/stories/StatusMessageA11y.stories.tsx
@@ -60,6 +60,12 @@ export default meta;
export const ToastInfoAnnouncement = coreStory('toast-info-announcement');
export const ToastErrorAnnouncement = coreStory('toast-error-announcement');
+export const ToastInfoAnnouncementTopLayer = coreStory(
+ 'toast-info-announcement-top-layer',
+);
+export const ToastErrorAnnouncementTopLayer = coreStory(
+ 'toast-error-announcement-top-layer',
+);
export const ToastInfoCardMounted = coreStory('toast-info-card-mounted');
export const ToastErrorCardMounted = coreStory('toast-error-card-mounted');
export const FieldStatusErrorAttached = coreStory(
diff --git a/docs/specs/AST-086-status-announcements/spec.md b/docs/specs/AST-086-status-announcements/spec.md
index b4ff63da88..fcd05ebb7b 100644
--- a/docs/specs/AST-086-status-announcements/spec.md
+++ b/docs/specs/AST-086-status-announcements/spec.md
@@ -132,11 +132,11 @@ announcement channel.
yet exposed.
`useAnnounce` is the public way to reach it. When an open native modal encloses the
caller, it follows FR14 instead.
-- **FR10 — Modal-hosted owners keep their own channel.** While the shared
- channel is not admitted to modal hosting, a globally hosted owner that
- `spec:AST-003` rehosts above native modals (FR16, FR18) announces through its
- own persistent polite and assertive containers, which move with it. FR3, FR5,
- and FR6 apply to those containers.
+- **FR10 — Rehosted owners speak through the modal they are in.** While the
+ shared channel is not admitted to modal hosting, a globally hosted owner that
+ `spec:AST-003` rehosts above native modals (FR16, FR18) announces through the
+ containers of the modal its host sits in (FR14), otherwise through the shared
+ channel. It adds no live container of its own.
- **FR11 — A message announces when it appears after the page loads.** Page
load covers everything committed until the document finishes loading,
including the page's first render from the server or the client. A message
@@ -206,8 +206,8 @@ announcement channel.
container of each urgency per modal for these messages; an owner's own
persistent FR3 region — Button's loading region, an input's invalid-entry
region — keeps its role and urgency inside the modal as FR4 says, and an
- owner that `spec:AST-003` rehosts above the modal keeps FR10's own
- containers. FR14's containers are direct children of the modal's dialog
+ owner that `spec:AST-003` rehosts above the modal writes to these containers
+ (FR10). FR14's containers are direct children of the modal's dialog
element, created empty on first use (FR3), carry `status` and `alert`
respectively (FR5), and clear shortly after each announcement; messages
written to one before the previous is exposed are joined in order, except that
@@ -234,7 +234,7 @@ announcement channel.
no-op and renders nothing.
- While a native modal dialog is open, the shared channel on the page body is
not exposed to assistive technology until `spec:AST-003` admits it to modal
- hosting. Owners rehosted above the modal use their own containers (FR10),
+ hosting. Owners rehosted above the modal use that modal's containers (FR10),
and an owner rendered inside the modal — a busy control (FR8), a picker's
selection and result messages, a sheet's search outcome — announces through
the persistent containers inside that modal (FR14). Delivery from an owner
@@ -252,11 +252,6 @@ announcement channel.
mounted live container; elsewhere they already match FR2, FR5, and FR7.
- `architecture:react-component-runtime` INV5 gains the authority it requires
for the document-owned channel (FR9). INV2 and INV3 already require FR6.
-- Toast: the viewport announces each toast through the body-level channel, and
- each visible card also carries `role="status"`/`role="alert"` with
- `aria-live`. Under FR1 and FR10 the viewport's own persistent live containers,
- which `spec:AST-003` rehosts above native modals, is the one owner, and the
- card drops its live role. A toast shown over a Dialog stays announced.
- Switch: busy is announced through the channel, and the thumb Spinner also
mounts with `role="status"`. Under FR8 the thumb Spinner is silent. Under FR6
StrictMode replay does not repeat the busy announcement.
@@ -362,7 +357,7 @@ announcement channel.
| FR7 | Accessibility-tree check of the visible message | FieldStatus attached/detached, toast card | Hiding the visible text or a word mismatch fails |
| FR8 | Shared test: no live role inside a busy owner; channel spy on the owner | Busy TextInput, Selector, Switch thumb, ChatMessageList loader, busy CommandPalette (region inside its dialog), operation that settles before its busy announcement is exposed | A composed indicator with a live role or its own announcement, or a busy owner that announces nothing, fails, or a busy start announced after its outcome, fails |
| FR9 | `useAnnounce` tests | First use, many components, region removed, server render, two messages in one frame, clear after a joined message, the same message twice in one frame, a `hasReplace` instance's messages written in one frame, two pickers' result counts in one frame, a result count followed by its picker's empty-panel message and the reverse, a `hasReplace` message already exposed when the next is written, messages from instances without `hasReplace` in one frame, one picker's result count and selection message in one frame (separate instances), a polite message followed by an assertive one from one `hasReplace` instance | A second document-level region pair, stale text after the clear delay, a dropped same-frame message from another instance or from an instance without `hasReplace`, a `hasReplace` instance's superseded message spoken with its next one, its polite message still spoken after its assertive one, the newer spoken at the older's urgency, an exposed message taken back, or a joined message surviving a clear fails, or an identical same-frame repeat announced twice, fails |
-| FR10 | Accessibility-tree check with a Dialog open | Info and error toast shown over an open Dialog | A toast that reaches only the body-level channel, or no exposed live container, fails |
+| FR10 | Accessibility-tree check with a Dialog open | Info and error toast shown over an open Dialog | A toast that reaches only the body-level channel, no exposed live container, or a live container the viewport adds of its own, fails |
| FR14 | Hook tests and an accessibility-tree check with an Astryx modal open | Owner outside any modal, inside an open non-modal dialog, inside an open modal (polite and assertive, repeat of the same words, empty message), busy start inside a modal, busy start inside a native modal an app renders without Astryx, alone and opened inside an Astryx Dialog; a modal sheet's row toggle in a real engine, app code calling `useAnnounce` inside a Dialog, CommandPalette result count and Lightbox position message while each is open, a message followed by closing its Dialog before it is exposed (inside another open modal and on the page), a message pending when a CommandPalette opened over a Dialog closes, app code calling `useAnnounce` outside the Dialog it renders (body-level channel); a search's result counts written in one frame inside a modal sheet; a polite then an assertive message from one `hasReplace` instance inside a modal; a result count followed by its picker's empty-panel message inside a modal sheet | A channel message from inside an open modal that reaches only the body-level channel, an FR14 container mounted holding its text, a second FR14 container of one urgency in one dialog, an FR14 container the engine's accessibility tree omits, a dropped message of two from different instances written before the first is exposed, a `hasReplace` instance's superseded message spoken from an FR14 container, its polite message still spoken from the modal's polite container after its assertive one, or a count spoken with its picker's empty-panel message from an FR14 container, an empty message that leaves text in the modal's FR14 container, an app `useAnnounce` message from inside an Astryx modal that reaches only the body-level channel, a CommandPalette or Lightbox message about its open modal that reaches only the body-level channel, a message lost when its modal closes before it is exposed, or a pending message handed to a channel still inert after the close, a busy start inside an app-rendered native modal that reaches only the body-level channel, or one inside an app-rendered native modal nested in an Astryx Dialog that is delivered to the Dialog's FR14 container fails |
| FR11, FR12 | Helper and component tests | EmptyState present at page load, server-rendered, inserted later, text changed, hidden and shown again, brought in by a client-rendered route change, inside a chat log, empty Selector panel open at page load, server-rendered message inserted by client navigation, message inserted after first render but before the document finishes loading (silent) | Announcing at page load or during a server render (other than an announcement-only message), missing a later insertion or a server-rendered message inserted by client navigation, a client-rendered route change, or an empty Selector panel at page load, repeating one occasion, or also using the channel inside a live container fails |
| FR12 (server) | Server-safe component boundary check plus a server render of each adopter | EmptyState rendered on the server and hydrated | An adopter that fails the boundary check, or emits an announcement or live role from a server render, fails |
@@ -381,8 +376,9 @@ mount a live region already holding its text. Screen-reader users then hear a
message twice or not at all. One owner and one shared, always-mounted channel
removes both failures with a single rule, and matches the delivery
`component:FieldStatus` already uses.
-Owners that `spec:AST-003` rehosts above native modals keep their own containers
-until the shared channel can be hosted there (FR10).
+Owners that `spec:AST-003` rehosts above native modals write to the
+containers of the modal they sit in (FR10, FR14), so no page carries a second
+set of empty live containers.
Rejected: delivering transient messages through each component's own live
region — the page gains many competing regions and two-owner duplicates recur.
diff --git a/docs/specs/components/Toast/Toast.spec.md b/docs/specs/components/Toast/Toast.spec.md
index ed27be7882..bd55dc283a 100644
--- a/docs/specs/components/Toast/Toast.spec.md
+++ b/docs/specs/components/Toast/Toast.spec.md
@@ -55,7 +55,7 @@ system_specs:
| Behavior | A stack of non-modal notification cards at one viewport corner. Each toast is announced once, can auto-hide (pausing while hovered, focused, touched, or the window is blurred), and dismisses by its button, a vertical swipe toward its edge, or code. F6 moves focus into the newest toast. |
| End-user impact | Users get brief notices without losing their place; screen-reader users hear each toast once; keyboard users reach toast controls with F6 and land somewhere sensible after dismissing; touch users swipe toasts away. |
| Builder impact | None. |
-| Compatibility/readiness | Records shipped behavior; no public change. Seventeen implementation gaps, listed under Current-state impact. |
+| Compatibility/readiness | Records shipped behavior; no public change. Sixteen implementation gaps, listed under Current-state impact. |
| Review checks | Reject a toast announced more than once per show, a dismissal that drops focus to the body, an auto-hide that runs while the user is reading or interacting, or a swipe as the only way to dismiss. |
| Governing rules | `spec:AST-086` FR1; `spec:AST-003` (modal rehosting); `spec:AST-094`; `spec:AST-100`; `spec:AST-059` FR6; `architecture:layer-runtime`; `design:bidirectionality`; `design:reduced-motion`. |
@@ -84,10 +84,6 @@ Consumer migration instructions belong in consumer docs and release notes.
own top layer and runs its own exit collapse. `architecture:layer-runtime`
INV14 has a layer use the runtime's top-layer mounting and shared exit copy
rather than building its own.
-- **Announcements go through the body-level channel.** The viewport announces
- through the shared body-level channel, which a native modal hides, instead
- of its own persistent containers. `spec:AST-086` FR10 has a modal-hosted
- owner keep its own channel.
- **The swipe decides on net travel.** A swipe dismisses on net travel past a
distance threshold, or on a fast flick timed by its own average speed, even
when the finger moves back before release. `spec:AST-094` FR36–FR37 decide
@@ -196,7 +192,7 @@ FR4's first-move rule has two accepted tradeoffs, which are not gaps:
| FR6 | The viewport stacks toasts at `position`, newest nearest the configured edge, with an 8 px gap and no extra space at the edge beyond the safe-area gutter it keeps; it spans the inline axis within its inset, honoring start and end insets in either direction. The bottom gutter is 16 px beyond the bottom safe-area inset; under a coarse pointer it is 16 px beyond the larger of that inset and 34 px (`16px + max(env(safe-area-inset-bottom), 34px)`), so a toast clears the home indicator even where the page reports no inset. With a fine pointer and no inset it is 16 px. The 34 px floor is the iPhone home indicator's height; it applies on every coarse-pointer device, since browsers report the inset only when a page opts in. Each edge sits at the provider's `layerInset`, and a `toast.inset` edge, when set, replaces it (`spec:AST-059` FR6). Implementation gaps: a `toast.inset` edge set to 0 does not replace the provider's value, and an edge opposite the position, such as `top` for a bottom stack, moves the stack to that edge (Current-state impact). | Current source and tests |
| FR7 | With `maxVisible` of 1 or more, at most that many toasts show; when more are raised, the oldest wait hidden and return as visible toasts leave. `maxVisible={0}` shows every toast. | Current source and tests |
| FR8 | A toast whose `uniqueID` matches a toast the viewport holds, whether shown, hidden by the cap, or exiting, replaces it in place under `overwrite` (and is announced again; the card updates in place under the same key, so focus inside it stays on the same control, or moves per FR10 when that control no longer exists), and is dropped unshown and unannounced under `ignore`, even when both are raised before the first renders. Implementation gap: overwriting a toast hidden by the cap announces it while it is not shown, and nothing is announced when it surfaces (Current-state impact). | Current source and tests |
-| FR9 | Each shown toast has one announcement owner (`spec:AST-086` FR1): the viewport announces it once, when it is shown, `error` assertively and `info` politely, using the toast's text content, through its own persistent polite and assertive containers, which move with it into a modal (`spec:AST-086` FR10). Unrelated renders do not re-announce. Implementation gaps: the viewport announces through the shared body-level channel, which a modal hides, and announces at dispatch rather than when a toast appears (Current-state impact). | `spec:AST-086`; tests |
+| FR9 | Each shown toast has one announcement owner (`spec:AST-086` FR1): the viewport announces it once, when it is shown, `error` assertively and `info` politely, using the toast's text content. A top-layer viewport hosted in an open modal delivers through that modal's containers (`spec:AST-086` FR14); otherwise through the shared channel. A viewport the caller renders in place announces through `useAnnounce`, which delivers through an enclosing modal's containers (`spec:AST-086` FR14). The card never holds a live role. Unrelated renders do not re-announce. Implementation gap: the viewport announces at dispatch rather than when a toast appears (Current-state impact). | `spec:AST-086`; tests |
| FR10 | F6 moves focus to the first control in the newest toast. Focus entering the viewport, by F6, Tab or a click, records where it was. Dismissing a toast that holds focus moves focus to a control in a remaining toast, or back to the remembered element when none remain. When focus reached the viewport by Tab or a click, dismissing the focused toast follows the same handoff: a control in a remaining toast, else the remembered element; with no control in the target toast, F6 leaves focus where it was, and a handoff never drops focus to the page body. | Current source and tests |
| FR11 | While a toast is visible the viewport is a `region` landmark named by `@astryx.toast.viewport`, without `aria-modal`; it exposes no landmark when empty, so an empty nested viewport adds none. Implementation gap: nested viewports that each hold a toast expose two landmarks (Current-state impact). | Current source and tests |
| FR12 | A top-layer viewport moves into the latest open Dialog, modal Drawer, scrim sheet, or modal flow step, following the top of a stack and handing back to the one beneath when it closes, and returns to its place when none remains, keeping each toast, its timer, and focus inside the viewport. It re-enters the top layer in place when a non-modal sheet or a drawer without a scrim opens after it, and stays in place when rendered in place, or when an inline dialog, a sheet without a scrim, or a non-modal flow opens. | `spec:AST-003`; tests |
@@ -282,8 +278,9 @@ Read from source, with no focused test yet:
0.01 ms transitions.
- FR6: a set `toast.inset` edge replacing the provider's value at 0.
- FR7: the default cap of 5, and `maxVisible={0}` showing every toast.
-- FR9: delivery through the viewport's own polite and assertive containers;
- the announcement tests read the shared body-level channel.
+- FR9: delivery through an open modal's containers by a top-layer viewport
+ hosted in that modal; the modal-host test covers an in-place viewport
+ inside a Dialog, and the announcement tests read the shared channel.
## Decision log
diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders.tsx b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders.tsx
index a57e3e45f7..6d55c2a78e 100644
--- a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders.tsx
+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders.tsx
@@ -116,6 +116,20 @@ function ToastAnnouncementHarness({type}: {type: 'info' | 'error'}) {
);
}
+function ToastTopLayerAnnouncementHarness({type}: {type: 'info' | 'error'}) {
+ // Outside a modal a top-layer viewport speaks through the shared channel.
+ const politeness = type === 'error' ? 'assertive' : 'polite';
+ return (
+ <ToastViewport>
+ <PrimeLiveRegion politeness={politeness} />
+ <button data-a11y-relation="focus-anchor" type="button">
+ Keep focus
+ </button>
+ <ToastAnnouncementButtons type={type} />
+ </ToastViewport>
+ );
+}
+
function ToastCardHarness({type}: {type: 'info' | 'error'}) {
const message = type === 'error' ? 'Upload failed' : 'Changes saved';
const replacement =
@@ -242,6 +256,12 @@ export const CORE_STATUS_MESSAGE_STATE_RENDERS: Record<
> = {
'toast-info-announcement': () => <ToastAnnouncementHarness type="info" />,
'toast-error-announcement': () => <ToastAnnouncementHarness type="error" />,
+ 'toast-info-announcement-top-layer': () => (
+ <ToastTopLayerAnnouncementHarness type="info" />
+ ),
+ 'toast-error-announcement-top-layer': () => (
+ <ToastTopLayerAnnouncementHarness type="error" />
+ ),
'toast-info-card-mounted': () => <ToastCardHarness type="info" />,
'toast-error-card-mounted': () => <ToastCardHarness type="error" />,
'field-status-error-attached': () => (
diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts
index 8f20c54896..fca55a1ea8 100644
--- a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts
+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts
@@ -83,6 +83,34 @@ export const CORE_STATUS_MESSAGE_BINDING_STATES = [
}),
storyId: 'a11y-status-message-pattern--toast-error-announcement',
},
+ {
+ id: 'toast-info-announcement-top-layer',
+ binding: 'Toast announcement channel',
+ summary:
+ 'a top-layer viewport outside a modal announces an info toast once through the shared polite region, and adds no region of its own',
+ facts: liveFacts({
+ role: 'status',
+ politeness: 'polite',
+ message: 'Changes saved',
+ replacement: 'Profile updated',
+ semanticTransitions: ['show', 'replace', 'repeat'],
+ }),
+ storyId: 'a11y-status-message-pattern--toast-info-announcement-top-layer',
+ },
+ {
+ id: 'toast-error-announcement-top-layer',
+ binding: 'Toast announcement channel',
+ summary:
+ 'a top-layer viewport outside a modal announces an error toast once through the shared assertive region, and adds no region of its own',
+ facts: liveFacts({
+ role: 'alert',
+ politeness: 'assertive',
+ message: 'Upload failed',
+ replacement: 'Connection failed',
+ semanticTransitions: ['show', 'replace', 'repeat'],
+ }),
+ storyId: 'a11y-status-message-pattern--toast-error-announcement-top-layer',
+ },
{
id: 'toast-info-card-mounted',
binding: 'Toast card',
diff --git a/packages/core/src/Toast/Toast.doc.mjs b/packages/core/src/Toast/Toast.doc.mjs
index c0cf92d900..cc3c9ddc1a 100644
--- a/packages/core/src/Toast/Toast.doc.mjs
+++ b/packages/core/src/Toast/Toast.doc.mjs
@@ -89,7 +89,7 @@ export const docs = {
name: 'renderContent',
type: '(toast: ToastContentRenderProps) => ReactNode',
description:
- "Replaces the content of this toast's card with your own layout. Astryx keeps the card, its astryx-toast theme target and auto-hide behavior (inside a ToastViewport the viewport announces the toast, and while a modal hosts the viewport the card announces itself), then hands the renderer the message, endContent, resolved toast settings and a dismiss callback. The custom renderer owns every control in its layout: compose the control you want and call dismiss from it. Astryx does not inject a fallback close into custom content. Per-toast: an app shares one layout by wrapping useToast and passing it on every call, while a toast raised by library code that never passes it renders as an ordinary Astryx toast. The argument is {body, endContent, type, isAutoHide, autoHideDuration, dismiss}, where type is 'info' | 'error'.",
+ "Replaces the content of this toast's card with your own layout. Astryx keeps the card, its astryx-toast theme target and auto-hide behavior (inside a ToastViewport the viewport announces the toast, over a modal too, and the card itself is not a live region), then hands the renderer the message, endContent, resolved toast settings and a dismiss callback. The custom renderer owns every control in its layout: compose the control you want and call dismiss from it. Astryx does not inject a fallback close into custom content. Per-toast: an app shares one layout by wrapping useToast and passing it on every call, while a toast raised by library code that never passes it renders as an ordinary Astryx toast. The argument is {body, endContent, type, isAutoHide, autoHideDuration, dismiss}, where type is 'info' | 'error'.",
},
],
theming: {
diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
index 61694efbb0..301113d057 100644
--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx
@@ -18,13 +18,14 @@
import {useLayoutEffect, useRef, useState, type ReactNode} from 'react';
import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';
-import {act, fireEvent, render, screen} from '@testing-library/react';
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {ToastViewport} from './ToastViewport';
import {useToast} from './useToast';
import {BottomSheet, BottomSheetSwitcher} from '../BottomSheet';
import {Dialog} from '../Dialog';
import {Drawer} from '../Drawer/Drawer';
import {getActiveModalOutlet} from '../Layer/modalOutlet';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import type {ToastDismissReason} from './types';
// jsdom reports no window focus until an element is focused, but a test page
@@ -54,6 +55,9 @@ beforeEach(() => {
afterEach(() => {
vi.restoreAllMocks();
+ // The page's shared live regions outlive a test; clear them so a count of
+ // announcements sees only this test's words.
+ __resetLiveRegionsForTest();
});
function ToastButton({label = 'Show toast'}: {label?: string}) {
@@ -263,37 +267,75 @@ function trackPopoverState() {
}
describe('ToastViewport modal hosting', () => {
- // spec:AST-086 FR10: an open modal hides the body-level channel, so while
- // the viewport is hosted in one each card announces itself; outside a modal
- // the cards carry no live region and the viewport's channel announces once.
- it('gives each card its own live region only while a modal hosts the viewport', () => {
- render(
- <ToastViewport>
- <ToastButton />
- <DialogFixture label="Edit">
- <ToastButton label="Show toast from dialog" />
- </DialogFixture>
- </ToastViewport>,
- );
- // The live region the toast's own text sits in, inside its row.
- const liveRegionOf = (text: string) => {
- const node = screen.getByText(text);
- const row = node.closest('[data-toast-id]');
- const region = node.closest(
+ // The live region the toast's own text sits in, inside its row.
+ const cardLiveRegionOf = (text: string) => {
+ const node = screen.getByText(text, {selector: '[data-toast-id] *'});
+ const row = node.closest('[data-toast-id]');
+ const region = node.closest('[aria-live], [role="status"], [role="alert"]');
+ return region != null && row?.contains(region) ? region : null;
+ };
+ // Every live element whose text includes `text`.
+ const liveRegionsWith = (text: string) =>
+ [
+ ...document.querySelectorAll<HTMLElement>(
'[aria-live], [role="status"], [role="alert"]',
+ ),
+ ].filter(region => region.textContent?.includes(text));
+
+ it("announces each toast once: through the shared channel on the page, and through the modal's container once its host is in a modal; the card has no live role", async () => {
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(
+ <ToastViewport>
+ <ToastButton />
+ <DialogFixture label="Edit">
+ <ToastButton label="Show toast from dialog" />
+ </DialogFixture>
+ </ToastViewport>,
);
- return region != null && row?.contains(region) ? region : null;
- };
-
- fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
- expect(liveRegionOf('Saved')).toBeNull();
- fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
- expect(getDialog('Edit').contains(getViewport())).toBe(true);
- expect(liveRegionOf('Saved')).toHaveAttribute('aria-live', 'polite');
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+ expect(cardLiveRegionOf('Saved')).toBeNull();
+ await waitFor(() => expect(liveRegionsWith('Saved')).toHaveLength(1));
+ const [pageRegion] = liveRegionsWith('Saved');
+ expect(pageRegion).toHaveAttribute('data-astryx-live-region', 'polite');
+ expect(getViewport().contains(pageRegion)).toBe(false);
- fireEvent.click(screen.getByRole('button', {name: 'Close Edit'}));
- expect(liveRegionOf('Saved')).toBeNull();
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle Edit'}));
+ const dialog = getDialog('Edit');
+ expect(dialog.contains(getViewport())).toBe(true);
+ fireEvent.click(
+ screen.getByRole('button', {name: 'Show toast from dialog'}),
+ );
+ await waitFor(() =>
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).toHaveTextContent('Saved'),
+ );
+ // The viewport adds no live region of its own, on the page or in the
+ // modal, and no card is live.
+ expect(
+ getViewport().querySelector(
+ ':scope > [aria-live], :scope > [role="status"], :scope > [role="alert"]',
+ ),
+ ).toBeNull();
+ for (const card of document.querySelectorAll('[data-toast-id]')) {
+ expect(
+ card.closest('[aria-live], [role="status"], [role="alert"]'),
+ ).toBeNull();
+ }
+ } finally {
+ spy.mockRestore();
+ }
});
it('moves into an open Dialog and back when it closes, keeping the toast', () => {
@@ -487,6 +529,41 @@ describe('ToastViewport modal hosting', () => {
expect(document.activeElement).toBe(dismiss);
});
+ it('announces a toast once through the modal container when an in-place viewport sits inside a Dialog', async () => {
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Edit">
+ <ToastViewport isTopLayer={false}>
+ <ToastButton />
+ </ToastViewport>
+ </Dialog>,
+ );
+ const dialog = screen.getByRole('dialog', {name: 'Edit'});
+
+ fireEvent.click(screen.getByRole('button', {name: 'Show toast'}));
+
+ await waitFor(() =>
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).toHaveTextContent('Saved'),
+ );
+ expect(liveRegionsWith('Saved')).toHaveLength(1);
+ expect(cardLiveRegionOf('Saved')).toBeNull();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
it('stays in place when the caller renders it in place', () => {
render(
<DialogFixture label="Edit">
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index dee6b18926..4cb41451b7 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -8,7 +8,8 @@
* boundary, useAnnounce and viewport tokens. It also uses the shared layer
* text reset, the active modal outlet, the layer toast host registry and
* placement-derived motion variables
- * @output Exports the ToastViewport provider, stack, live announcement dispatch,
+ * @output Exports the ToastViewport provider, stack, live announcement dispatch
+ * (an open modal's containers when hosted in one, else the shared channel),
* focus handoff, safe-area-aware edge gutters, modal rehosting, and motion context
* @position Core provider/imperative viewport for useToast()
*
@@ -23,7 +24,6 @@ import {
useMemo,
useRef,
useState,
- useSyncExternalStore,
} from 'react';
import type {ReactNode} from 'react';
import {createPortal} from 'react-dom';
@@ -37,7 +37,12 @@ import {
type FocusWithin,
} from '../utils/focusReturn';
import {INTERACTIVE_SELECTORS} from '../hooks/useClickableContainer';
-import {useAnnounce} from '../hooks/useAnnounce';
+import {
+ announceInModal,
+ enclosingModalDialog,
+ useAnnounce,
+ type AnnouncePoliteness,
+} from '../hooks/useAnnounce';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
@@ -367,9 +372,6 @@ function ToastRow({
}
ToastRow.displayName = 'ToastRow';
-const hasActiveModalOutlet = (): boolean => getActiveModalOutlet() != null;
-const hasNoModalOutlet = (): boolean => false;
-
/**
* Container that renders and manages toast notifications. Place at the root
* of your app to enable useToast(). Toasts stack with enter/exit
@@ -475,17 +477,26 @@ export function ToastViewport({
// double-render/double-effect, viewport remounts, and unrelated list
// re-renders never re-announce). It is client-only (addToast never runs
// during SSR), so it is SSR-safe.
- const announce = useAnnounce();
- // An open native modal hides the body-level channel above from assistive
- // technology, so while the viewport is hosted in one, each card announces
- // itself through its own live region instead. Outside a modal the cards
- // carry none, so a card updated in place is announced once.
- const hasModalOutlet = useSyncExternalStore(
- subscribeModalOutlets,
- hasActiveModalOutlet,
- hasNoModalOutlet,
+ // The viewport is each toast's only announcement owner; the card carries no
+ // live role. A top-layer viewport's host moves into the latest open native
+ // modal, where the page's shared channel is not exposed, so it writes
+ // through the containers of the modal its host sits in. A
+ // viewport rendered in place uses `useAnnounce`, which finds an enclosing
+ // modal through its context.
+ const announceShared = useAnnounce();
+ // The top-layer host (below), read at write time for the modal it sits in.
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ const announce = useCallback(
+ (text: string, politeness: AnnouncePoliteness) => {
+ const modal = isTopLayer ? enclosingModalDialog(hostRef.current) : null;
+ if (modal != null) {
+ announceInModal(modal, text, politeness);
+ return;
+ }
+ announceShared(text, politeness);
+ },
+ [announceShared, isTopLayer],
);
- const isModalHosted = isTopLayer && hasModalOutlet;
const addToast = useCallback(
(entry: ToastEntry) => {
@@ -800,10 +811,12 @@ export function ToastViewport({
}
const element = document.createElement('div');
element.style.display = 'contents';
+ hostRef.current = element;
// eslint-disable-next-line @eslint-react/set-state-in-effect -- the host exists only on the client, so server and hydration markup carry no portal
setHost(element);
return () => {
element.remove();
+ hostRef.current = null;
setHost(null);
};
}, [isTopLayer]);
@@ -975,7 +988,7 @@ export function ToastViewport({
isReversed={isReversed}
onExited={handleExited}
onDismiss={removeToast}
- isLiveRegion={isModalHosted}
+ isLiveRegion={false}
/>
))}
</LayerContentBoundary>
diff --git a/packages/core/src/Toast/types.ts b/packages/core/src/Toast/types.ts
index 74623d349e..f1e7223655 100644
--- a/packages/core/src/Toast/types.ts
+++ b/packages/core/src/Toast/types.ts
@@ -39,8 +39,8 @@ export interface ToastOptions {
* Replaces the content of this toast's card with your own layout.
*
* Astryx keeps the card and its auto-hide behavior (inside a
- * `ToastViewport` the viewport announces the toast, and while a modal hosts
- * the viewport the card announces itself), then hands the
+ * `ToastViewport` the viewport announces the toast, over a modal too, and
+ * the card itself is not a live region), then hands the
* renderer this toast's content, resolved settings and `dismiss` callback. The renderer owns every control inside its layout; call
* `dismiss` from the control that should close the toast. Astryx does not
* inject a fallback control into custom content.