An open source design system that's fully customizable and agent ready
TypeScript
fix(Toast): a leaving toast pushed past the cap leaves the stack (#8051)
Christopher Chedeau83df3777075a
diff --git a/.changeset/toast-leaving-past-cap.md b/.changeset/toast-leaving-past-cap.mdnew file mode 100644index 0000000000..4caacd75f5--- /dev/null+++ b/.changeset/toast-leaving-past-cap.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A toast that is closing when a new toast takes its visible place under `maxVisible`, or that the same handler pushes out and then dismisses, leaves the stack at once. Before, it came back later as an invisible, empty row that kept the notifications landmark, took one of the visible places, and let F6 move focus to its hidden dismiss button. A second `collisionBehavior: 'ignore'` toast with the same `uniqueID`, raised in the same handler as the first, is now dropped unannounced, as it already was once the first had rendered. When a control inside a toast raises toasts and then dismisses its own toast, focus moves to a toast that shows, the new one included, instead of to the notifications region.++@vjeuxdiff --git a/packages/core/src/Toast/Toast.spec.md b/packages/core/src/Toast/Toast.spec.mdindex 27ff5ee122..41e391a49e 100644--- a/packages/core/src/Toast/Toast.spec.md+++ b/packages/core/src/Toast/Toast.spec.md@@ -50,7 +50,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. Twenty-one implementation gaps, listed under Current-state impact. |+| Compatibility/readiness | Records shipped behavior; no public change. Twenty 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`. |@@ -121,9 +121,9 @@ Consumer migration instructions belong in consumer docs and release notes.- **Some modals supply no outlet.** A modal Drawer, Lightbox, or MobileNavopens without supplying an outlet, so toasts stay behind it; `spec:AST-003`FR18 rehosts globally hosted layers above every native modal.-- **A toast pushed out mid-collapse can linger.** A toast that a new toast- pushes past the cap during its collapse, or that is still collapsing when- its viewport moves into or out of any outlet FR12 names, comes back as an invisible zero-height row that never unmounts: it+- **A toast collapsing through an outlet move can linger.** A toast that is+ still collapsing when its viewport moves into or out of any outlet FR12+ names comes back as an invisible zero-height row that never unmounts: itkeeps the notifications landmark exposed and F6 focuses its hidden dismissbutton, and it holds one of the `maxVisible` places. With no providerabove the caller a dismissal called before the fallback viewport@@ -143,9 +143,6 @@ Consumer migration instructions belong in consumer docs and release notes.- **The action row does not track a held pointer.** A press that slides acrossthe row's sibling actions does not act on the action it lifts on;`family:action-groups` has the row use the shared press tracking.-- **Same-handler `ignore` toasts both announce.** Two `ignore` toasts with one- `uniqueID` raised before the first renders are both announced, and the- second replaces the first (FR8, ORD1).- **Nested viewports can show two landmarks.** An outer and an inner viewportthat each hold a toast expose two notifications landmarks (FR11).- **Reduced motion is instant on every pointer.** Under reduced motion the@@ -198,7 +195,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR5 | A new card slides in from its edge and fades in; a dismissed card collapses and fades before it unmounts; both slide only along the block axis. A dismissal without a swipe uses theme timing; a swipe's commit and snap-back start at the release velocity (`spec:AST-094` FR38). Under reduced motion the entrance and dismissal are an opacity-only fade of 200 ms or less on a coarse pointer or after a touch release (`design:reduced-motion` DR2) and immediate otherwise (DR3), and the card still unmounts. Implementation gaps: a swipe's settle is a CSS transition at theme timing, and under reduced motion every transition, including the row collapse and the swipe's throw, runs for 0.01 ms on every pointer (Current-state impact). | Current source and tests || 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. 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 remounts, so focus inside it drops to the page body), and is dropped unshown and unannounced under `ignore` once the first has rendered. Implementation gaps: two `ignore` toasts with one `uniqueID` raised before the first renders are both announced and the second replaces the first; 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 |+| 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 remounts, so focus inside it drops to the page body), 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 || FR10 | F6 moves focus to the first control in the newest toast and remembers where focus 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. Implementation gap: with no control in the target toast, F6 leaves focus where it was and the handoff drops focus to the page, and dismissing the last toast after reaching it with Tab rather than F6 also drops focus to the page (Current-state impact). | 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 |@@ -221,8 +218,8 @@ Consumer migration instructions belong in consumer docs and release notes.### Transformation and precedence order-- **ORD1 — Collision.** `ignore` drops a matching toast before announcement,- apart from FR8's same-handler gap; `overwrite` replaces it, then announces.+- **ORD1 — Collision.** `ignore` drops a matching toast before announcement;+ `overwrite` replaces it, then announces.### Performance and resourcesdiff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxindex 98305eac4d..060d14b0ac 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -30,7 +30,7 @@ import {waitFor,within,} from '@testing-library/react';-import React from 'react';+import React, {useRef} from 'react';import {readFileSync} from 'node:fs';import {type AnnounceFn, __resetLiveRegionsForTest} from '../hooks/useAnnounce';import {Button} from '../Button';@@ -602,6 +602,173 @@ describe('ToastViewport keyboard reach + focus', () => {expect(document.activeElement).toBe(dismiss);});+ it('moves focus to the neighbour when a control inside a toast raises its repeat and dismisses it', () => {+ function OfflineFlow() {+ const toast = useToast();+ const dismissOfflineRef = useRef<(() => void) | null>(null);+ const showOffline = (body: string) => {+ dismissOfflineRef.current = toast({+ uniqueID: 'offline',+ isAutoHide: false,+ body,+ endContent: (+ <button+ type="button"+ onClick={() => {+ // A retry reports the state again, then closes the toast it+ // was pressed in.+ const dismissPressed = dismissOfflineRef.current;+ showOffline('Still offline');+ dismissPressed?.();+ }}>+ Retry+ </button>+ ),+ });+ };+ return (+ <>+ <button+ type="button"+ onClick={() => {+ toast({isAutoHide: false, body: 'Alpha'});+ toast({isAutoHide: false, body: 'Bravo'});+ }}>+ Show two+ </button>+ <button type="button" onClick={() => showOffline('Offline')}>+ Show offline+ </button>+ </>+ );+ }+ render(+ <ToastViewport isTopLayer={false} maxVisible={2}>+ <OfflineFlow />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show two'));+ });+ act(() => {+ fireEvent.click(screen.getByText('Show offline'));+ });+ // Alpha waits hidden; Bravo and Offline show.+ const retry = within(getToastWrapperByText('Offline')).getByRole('button', {+ name: 'Retry',+ });+ retry.focus();+ act(() => {+ fireEvent.click(retry);+ });+ // Toast.spec.md FR10: focus moves to a control in a remaining toast, the+ // neighbour of the dismissed one, not to the hidden oldest toast or the+ // region.+ expect(+ getToastWrapperByText('Bravo').contains(document.activeElement),+ ).toBe(true);+ });++ it('moves focus into the replacement when a control inside the only toast raises its repeat and dismisses it', () => {+ function OfflineFlow() {+ const toast = useToast();+ const dismissOfflineRef = useRef<(() => void) | null>(null);+ const showOffline = (body: string) => {+ dismissOfflineRef.current = toast({+ uniqueID: 'offline',+ isAutoHide: false,+ body,+ endContent: (+ <button+ type="button"+ onClick={() => {+ const dismissPressed = dismissOfflineRef.current;+ showOffline('Still offline');+ dismissPressed?.();+ }}>+ Retry+ </button>+ ),+ });+ };+ return (+ <button type="button" onClick={() => showOffline('Offline')}>+ Show offline+ </button>+ );+ }+ render(+ <ToastViewport isTopLayer={false}>+ <OfflineFlow />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show offline'));+ });+ const retry = within(getToastWrapperByText('Offline')).getByRole('button', {+ name: 'Retry',+ });+ retry.focus();+ act(() => {+ fireEvent.click(retry);+ });+ // FR10: the replacement is the remaining toast, so focus goes into it.+ expect(+ getToastWrapperByText('Still offline').contains(document.activeElement),+ ).toBe(true);+ });++ it('moves focus to a toast that shows when a control inside a toast raises two toasts at the cap and dismisses its own', () => {+ function UploadFlow() {+ const toast = useToast();+ const dismissSavedRef = useRef<(() => void) | null>(null);+ return (+ <button+ type="button"+ onClick={() => {+ dismissSavedRef.current = toast({+ isAutoHide: false,+ body: 'Saved',+ endContent: (+ <button+ type="button"+ onClick={() => {+ toast({isAutoHide: false, body: 'Uploading'});+ toast({isAutoHide: false, body: 'Uploaded'});+ dismissSavedRef.current?.();+ }}>+ Upload+ </button>+ ),+ });+ }}>+ Save+ </button>+ );+ }+ render(+ <ToastViewport isTopLayer={false} maxVisible={1}>+ <UploadFlow />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Save'));+ });+ const upload = within(getToastWrapperByText('Saved')).getByRole('button', {+ name: 'Upload',+ });+ upload.focus();+ act(() => {+ fireEvent.click(upload);+ });+ // FR10: with one visible place, "Uploaded" shows and "Uploading" waits+ // hidden, so focus goes to "Uploaded", not to the hidden toast or the+ // region.+ expect(+ getToastWrapperByText('Uploaded').contains(document.activeElement),+ ).toBe(true);+ });+it('dismissing a focused toast moves focus to a remaining toast, not body', () => {renderViewport(<>@@ -2061,6 +2228,413 @@ describe('toast announcements via singleton live regions', () => {expect(within(viewport).getByText('Kept')).toBeInTheDocument();expect(within(viewport).queryByText('Dropped')).not.toBeInTheDocument();});++ it('drops an ignored-collision toast while its namesake is still leaving', () => {+ renderViewport(+ <>+ <ShowToastButton+ options={{+ uniqueID: 'offline',+ collisionBehavior: 'ignore',+ isAutoHide: false,+ body: 'You are offline',+ }}+ triggerLabel="Show 1"+ />+ <ShowToastButton+ options={{+ uniqueID: 'offline',+ collisionBehavior: 'ignore',+ isAutoHide: false,+ body: 'Still offline',+ }}+ triggerLabel="Show 2"+ />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show 1'));+ });+ const first = getToastWrapperByText('You are offline');+ act(() => {+ fireEvent.click(+ within(first).getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ // Toast.spec.md FR8: a leaving toast still holds its uniqueID, so the+ // ignored namesake is neither shown nor announced.+ act(() => {+ fireEvent.click(screen.getByText('Show 2'));+ });+ expect(announceSpy).toHaveBeenCalledTimes(1);+ expect(screen.queryByText('Still offline')).toBeNull();+ act(() => {+ completeExit(first.dataset.toastId ?? '');+ });+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(0);+ });++ it('lets a leaving toast finish its exit when a new toast arrives with no cap', () => {+ render(+ <ToastViewport isTopLayer={false} maxVisible={0}>+ <ShowToastButton+ options={{isAutoHide: false, body: 'Saved'}}+ triggerLabel="Show 1"+ />+ <ShowToastButton+ options={{isAutoHide: false, body: 'Uploaded'}}+ triggerLabel="Show 2"+ />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show 1'));+ });+ const first = getToastWrapperByText('Saved');+ const firstId = first.dataset.toastId ?? '';+ act(() => {+ fireEvent.click(+ within(first).getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ // maxVisible={0} shows every toast (Toast.spec.md FR7), so the closing+ // toast keeps its row and collapses (FR5) while the new one arrives.+ act(() => {+ fireEvent.click(screen.getByText('Show 2'));+ });+ expect(getToastWrapperByText('Saved').dataset.toastId).toBe(firstId);+ expect(screen.getByText('Uploaded')).toBeInTheDocument();+ act(() => {+ completeExit(firstId);+ });+ expect(screen.queryByText('Saved')).toBeNull();+ expect(screen.getByText('Uploaded')).toBeInTheDocument();+ });++ it('drops a second ignore toast with the same uniqueID raised in the same handler', () => {+ function ShowTwoIgnored() {+ const toast = useToast();+ return (+ <button+ type="button"+ onClick={() => {+ toast({+ uniqueID: 'offline',+ collisionBehavior: 'ignore',+ isAutoHide: false,+ body: 'You are offline',+ });+ toast({+ uniqueID: 'offline',+ collisionBehavior: 'ignore',+ isAutoHide: false,+ body: 'Still offline',+ });+ }}>+ Show twice+ </button>+ );+ }+ render(+ <ToastViewport isTopLayer={false}>+ <ShowTwoIgnored />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show twice'));+ });+ // Toast.spec.md FR8 and ORD1: the ignored namesake is neither shown nor+ // announced, even before the first toast renders.+ expect(announceSpy).toHaveBeenCalledTimes(1);+ expect(announceSpy).toHaveBeenLastCalledWith('You are offline', 'polite');+ const rows = [...document.querySelectorAll('[data-toast-id]')];+ expect(rows).toHaveLength(1);+ expect(rows[0].textContent).toContain('You are offline');+ });++ it('leaves no row behind when a new toast takes the last visible slot from a leaving one', () => {+ render(+ <ToastViewport isTopLayer={false} maxVisible={1}>+ <ShowToastButton+ options={{isAutoHide: false, body: 'Saved'}}+ triggerLabel="Show 1"+ />+ <ShowToastButton+ options={{isAutoHide: false, body: 'Uploaded'}}+ triggerLabel="Show 2"+ />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show 1'));+ });+ const first = getToastWrapperByText('Saved');+ act(() => {+ fireEvent.click(+ within(first).getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ // A new toast arrives at once; with one visible slot it takes the place of+ // the leaving toast, which can no longer finish its exit on screen.+ act(() => {+ fireEvent.click(screen.getByText('Show 2'));+ });+ const second = getToastWrapperByText('Uploaded');+ act(() => {+ fireEvent.click(+ within(second).getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ act(() => {+ completeExit(second.dataset.toastId ?? '');+ });+ // Nothing is left: no row comes back, and the landmark is gone.+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(0);+ expect(screen.queryByRole('region', {name: 'Notifications'})).toBeNull();+ });++ it('reports the namesake once when one handler shows a repeat and dismisses the namesake', () => {+ const onHide = vi.fn();+ function RepeatAndDismiss() {+ const toast = useToast();+ const dismissFirstRef = useRef<(() => void) | null>(null);+ return (+ <>+ <button+ type="button"+ onClick={() => {+ dismissFirstRef.current = toast({+ uniqueID: 'offline',+ isAutoHide: false,+ body: 'Offline',+ onHide,+ });+ }}>+ Show first+ </button>+ <button+ type="button"+ onClick={() => {+ toast({+ uniqueID: 'offline',+ isAutoHide: false,+ body: 'Still offline',+ });+ dismissFirstRef.current?.();+ }}>+ Repeat and dismiss+ </button>+ </>+ );+ }+ render(+ <ToastViewport isTopLayer={false}>+ <RepeatAndDismiss />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show first'));+ });+ act(() => {+ fireEvent.click(screen.getByText('Repeat and dismiss'));+ });+ // As on `main`: the repeat replaces its namesake in place, and the+ // namesake's dismissal reports it once.+ expect(onHide).toHaveBeenCalledTimes(1);+ const rows = [...document.querySelectorAll('[data-toast-id]')];+ expect(rows).toHaveLength(1);+ expect(rows[0].textContent).toContain('Still offline');+ });++ it('leaves no row behind when one handler raises a toast at the cap and dismisses the one it pushed out', () => {+ const onHide = vi.fn();+ function UndoFlow() {+ const toast = useToast();+ const dismissDeletedRef = useRef<(() => void) | null>(null);+ return (+ <>+ <button+ type="button"+ onClick={() => {+ dismissDeletedRef.current = toast({+ isAutoHide: false,+ body: 'Deleted',+ onHide,+ });+ }}>+ Delete+ </button>+ <button+ type="button"+ onClick={() => {+ // An undo shows its confirmation, then dismisses its own toast.+ toast({isAutoHide: false, body: 'Restored'});+ dismissDeletedRef.current?.();+ }}>+ Undo+ </button>+ </>+ );+ }+ render(+ <ToastViewport isTopLayer={false} maxVisible={1}>+ <UndoFlow />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Delete'));+ });+ act(() => {+ fireEvent.click(screen.getByText('Undo'));+ });+ expect(onHide).toHaveBeenCalledTimes(1);+ const restored = getToastWrapperByText('Restored');+ act(() => {+ fireEvent.click(+ within(restored).getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ act(() => {+ completeExit(restored.dataset.toastId ?? '');+ });+ // Nothing is left: no row comes back, and the landmark is gone.+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(0);+ expect(screen.queryByRole('region', {name: 'Notifications'})).toBeNull();+ });++ it('reports a leaving toast once when it is dismissed again after a new toast pushed it out of view', () => {+ const onHide = vi.fn();+ function ShowPushDismiss() {+ const toast = useToast();+ const dismissFirstRef = useRef<(() => void) | null>(null);+ return (+ <>+ <button+ type="button"+ onClick={() => {+ dismissFirstRef.current = toast({+ isAutoHide: false,+ body: 'Saved',+ onHide,+ });+ }}>+ Show first+ </button>+ <button+ type="button"+ onClick={() => {+ toast({isAutoHide: false, body: 'Uploaded'});+ }}>+ Show second+ </button>+ <button type="button" onClick={() => dismissFirstRef.current?.()}>+ Dismiss first+ </button>+ </>+ );+ }+ render(+ <ToastViewport isTopLayer={false} maxVisible={1}>+ <ShowPushDismiss />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show first'));+ });+ // It starts leaving, and reports it.+ act(() => {+ fireEvent.click(screen.getByText('Dismiss first'));+ });+ expect(onHide).toHaveBeenCalledTimes(1);+ // A new toast takes the only visible slot: the leaving one leaves the list.+ act(() => {+ fireEvent.click(screen.getByText('Show second'));+ });+ // Its dismissal again reports nothing more.+ act(() => {+ fireEvent.click(screen.getByText('Dismiss first'));+ });+ expect(onHide).toHaveBeenCalledTimes(1);+ const rows = [...document.querySelectorAll('[data-toast-id]')];+ expect(rows).toHaveLength(1);+ expect(rows[0].textContent).toContain('Uploaded');+ });++ it('reports nothing for a toast replaced before it rendered, however often one handler dismisses it', () => {+ const onHide = vi.fn();+ function ShowReplaceDismiss() {+ const toast = useToast();+ return (+ <button+ type="button"+ onClick={() => {+ const dismissFirst = toast({+ uniqueID: 'offline',+ isAutoHide: false,+ body: 'Offline',+ onHide,+ });+ toast({+ uniqueID: 'offline',+ isAutoHide: false,+ body: 'Still offline',+ });+ dismissFirst();+ dismissFirst();+ }}>+ Show, replace and dismiss+ </button>+ );+ }+ render(+ <ToastViewport isTopLayer={false}>+ <ShowReplaceDismiss />+ </ToastViewport>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show, replace and dismiss'));+ });+ // Toast.spec.md FR3: a toast replaced through uniqueID is not dismissed+ // and reports no onHide.+ expect(onHide).not.toHaveBeenCalled();+ const rows = [...document.querySelectorAll('[data-toast-id]')];+ expect(rows).toHaveLength(1);+ expect(rows[0].textContent).toContain('Still offline');+ });++ it('replaces a leaving namesake in place under overwrite and announces it again', () => {+ renderViewport(+ <>+ <ShowToastButton+ options={{uniqueID: 'upload', isAutoHide: false, body: 'Upload 30%'}}+ triggerLabel="Show 1"+ />+ <ShowToastButton+ options={{uniqueID: 'upload', isAutoHide: false, body: 'Upload 31%'}}+ triggerLabel="Show 2"+ />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show 1'));+ });+ const first = getToastWrapperByText('Upload 30%');+ act(() => {+ fireEvent.click(+ within(first).getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ // Toast.spec.md FR8: an overwrite replaces its namesake in place even+ // while it is leaving, and is announced again.+ act(() => {+ fireEvent.click(screen.getByText('Show 2'));+ });+ expect(announceSpy).toHaveBeenLastCalledWith('Upload 31%', 'polite');+ expect(screen.queryByText('Upload 30%')).toBeNull();+ const rows = [...document.querySelectorAll('[data-toast-id]')];+ expect(rows).toHaveLength(1);+ expect(rows[0].textContent).toContain('Upload 31%');+ });});describe('toast timer lifecycle (#3589)', () => {diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsxindex 210ea3f9fe..a1dfdd9ff6 100644--- a/packages/core/src/Toast/ToastViewport.tsx+++ b/packages/core/src/Toast/ToastViewport.tsx@@ -344,6 +344,19 @@ export function ToastViewport({const [exitingIds, setExitingIds] = useState<Set<string>>(new Set());const toastsRef = useRef(toasts);toastsRef.current = toasts;+ // The list as last rendered: addToast moves toastsRef ahead of it within+ // a batch, so this tells a rendered toast from one raised since.+ const renderedToastsRef = useRef(toasts);+ renderedToastsRef.current = toasts;+ // Read by removeToast, which keeps one identity across renders.+ const maxVisibleRef = useRef(maxVisible);+ maxVisibleRef.current = maxVisible;+ // Rendered entries a repeat has replaced in this batch: still found by a+ // dismissal in the same handler, as before the swap. One replaced before it+ // rendered was never shown and reports no onHide (Toast.spec.md FR3). A+ // render starts a new batch.+ const replacedRef = useRef<Map<string, ToastEntry>>(new Map());+ replacedRef.current.clear();const viewportRef = useRef<HTMLDivElement>(null);// Toast ids whose exit has begun — guards onHide from double-firing (see@@ -410,6 +423,10 @@ export function ToastViewport({const addToast = useCallback((entry: ToastEntry) => {const {uniqueID, collisionBehavior = 'overwrite'} = entry.options;+ // A toast holds its uniqueID until it unmounts, leaving included+ // (Toast.spec.md FR8): an overwrite replaces it in place, and an ignored+ // namesake is dropped.+ const holdsUniqueID = (t: ToastEntry) => t.options.uniqueID === uniqueID;// Resolve an ignored collision synchronously against the committed list// so a suppressed toast is neither shown nor announced. The remaining// announce + setToasts run outside the setToasts updater, which React may@@ -417,7 +434,7 @@ export function ToastViewport({if (uniqueID &&collisionBehavior === 'ignore' &&- toastsRef.current.some(t => t.options.uniqueID === uniqueID)+ toastsRef.current.some(holdsUniqueID)) {return;}@@ -427,6 +444,35 @@ export function ToastViewport({// else to the polite region (role="status") — mirrors Toast.tsx.announce(text, entry.options.type === 'error' ? 'assertive' : 'polite');}+ // A leaving toast that a new one pushes out of the visible window can no+ // longer finish its exit on screen, so it leaves the list now (it+ // already reported onHide); otherwise its row would come back collapsed+ // when the window reached it again, holding a slot and the landmark.+ const committed = toastsRef.current;+ const overwritten = uniqueID ? committed.find(holdsUniqueID) : undefined;+ if (overwritten && renderedToastsRef.current.includes(overwritten)) {+ replacedRef.current.set(overwritten.id, overwritten);+ }+ const projected = overwritten+ ? committed.map(t => (t === overwritten ? entry : t))+ : [...committed, entry];+ // `maxVisible={0}` shows every toast (FR7): nothing leaves the window.+ const firstVisible = maxVisible > 0 ? projected.length - maxVisible : 0;+ const cutIds = new Set(+ projected+ .filter((t, i) => i < firstVisible && exitingIdsRef.current.has(t.id))+ .map(t => t.id),+ );+ if (cutIds.size > 0) {+ // Gone from every list, so a later dismissal reports nothing more.+ for (const id of cutIds) {+ exitingIdsRef.current.delete(id);+ pendingEntriesRef.current.delete(id);+ }+ setExitingIds(prev => new Set([...prev].filter(id => !cutIds.has(id))));+ }+ // Later toasts in the same batch see this one before the next render.+ toastsRef.current = projected.filter(t => !cutIds.has(t.id));const pending = pendingEntriesRef.current;if (uniqueID) {// An overwrite replaces a toast that has not rendered yet too.@@ -442,17 +488,17 @@ export function ToastViewport({// dismissed. Its settled id is dropped by the prune below, which covers// every silent exit with one rule rather than one branch per path.setToasts(prev => {- if (uniqueID) {- const existing = prev.find(t => t.options.uniqueID === uniqueID);- if (existing) {- // An ignored collision already returned above; overwrite in place.- return prev.map(t => (t.options.uniqueID === uniqueID ? entry : t));- }- }- return [...prev, entry];+ // The cut entries go first, then the choice the projection above made+ // (by identity): a dismissal in the same handler may have marked the+ // replaced namesake as leaving since, which must not turn the+ // overwrite into an append. An ignored collision already returned.+ const kept = prev.filter(t => !cutIds.has(t.id));+ return overwritten && kept.includes(overwritten)+ ? kept.map(t => (t === overwritten ? entry : t))+ : [...kept, entry];});},- [announce],+ [announce, maxVisible],);const removeToast = useCallback((id: string, reason: ToastDismissReason) => {@@ -465,6 +511,7 @@ export function ToastViewport({}const entry =toastsRef.current.find(t => t.id === id) ??+ replacedRef.current.get(id) ??pendingEntriesRef.current.get(id);if (entry == null) {// Already gone: nothing to hide or report.@@ -485,29 +532,54 @@ export function ToastViewport({dismissedNode.contains(active)) {focusHandoffIdRef.current = id;- // Pick the neighbor to receive focus while the DOM is still intact:- // prefer the next toast, then the previous, else restore.- const remaining = toastsRef.current.filter(t => t.id !== id);- if (remaining.length > 0) {- const dismissedIndex = toastsRef.current.findIndex(t => t.id === id);- const next =- toastsRef.current[dismissedIndex + 1] ??- toastsRef.current[dismissedIndex - 1];- pendingFocusRef.current = next ? next.id : 'restore';- } else {- pendingFocusRef.current = 'restore';- }+ // Pick the toast to receive focus while the DOM is still intact: the+ // nearest one after it, then before it, that shows once it is gone+ // (FR10), else restore. The list may already run ahead of the render+ // within this handler: a toast a repeat replaced has left it, and the+ // replacement holds its place, so the neighbors are taken around the+ // replacement, which takes focus only when no neighbor shows.+ const list = toastsRef.current;+ const {uniqueID} = entry.options;+ const ownIndex = list.findIndex(t => t.id === id);+ const placeIndex =+ ownIndex >= 0 || uniqueID == null+ ? ownIndex+ : list.findIndex(t => t.options.uniqueID === uniqueID);+ const remaining = list.filter(t => t.id !== id);+ const max = maxVisibleRef.current;+ const shown = new Set(max > 0 ? remaining.slice(-max) : remaining);+ const isShown = (t: ToastEntry) => shown.has(t);+ const replacement = ownIndex < 0 ? list[placeIndex] : undefined;+ const next =+ placeIndex < 0+ ? undefined+ : (list.slice(placeIndex + 1).find(isShown) ??+ list.slice(0, placeIndex).reverse().find(isShown) ??+ (replacement != null && isShown(replacement)+ ? replacement+ : undefined));+ pendingFocusRef.current = next ? next.id : 'restore';}- if (dismissedNode == null) {- // No row is mounted for it: it is hidden past `maxVisible`, or it has- // not rendered yet. Nothing animates out, so it leaves the list now.+ // A toast this handler has already pushed out of the visible window still+ // has its row now, but loses it when the batch renders.+ const index = toastsRef.current.findIndex(t => t.id === id);+ const isPushedOut =+ maxVisibleRef.current > 0 &&+ index >= 0 &&+ index < toastsRef.current.length - maxVisibleRef.current;+ if (dismissedNode == null || isPushedOut) {+ // No row is mounted for it, or none will be: it is hidden past+ // `maxVisible`, or it has not rendered yet. Nothing animates out, so it+ // leaves the list now.// Waiting for its row to finish exiting would keep it forever: when it// surfaced, its row would mount already collapsed, with no transition// left to end, and hold a visible slot as an empty row.// It leaves the committed list now too, so a second dismissal before- // the next render finds nothing to report.+ // the next render finds nothing to report (nor does a toast a repeat+ // replaced in this batch).exitingIdsRef.current.delete(id);pendingEntriesRef.current.delete(id);+ replacedRef.current.delete(id);toastsRef.current = toastsRef.current.filter(t => t.id !== id);setToasts(prev => prev.filter(t => t.id !== id));return;