An open source design system that's fully customizable and agent ready
TypeScript
fix(Toast): a toast raised while the window is in the background starts with its timer paused (#9615)
Cindy Zhang2de3888fe914
diff --git a/.changeset/toast-raised-while-blurred-held.md b/.changeset/toast-raised-while-blurred-held.mdnew file mode 100644index 0000000000..154872e537--- /dev/null+++ b/.changeset/toast-raised-while-blurred-held.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Toast`: a toast raised while the window is in the background now starts with its auto-hide timer paused, so it can no longer disappear before the user returns to the tab.++@cixzhang @duytbpdiff --git a/docs/specs/components/Toast/Toast.spec.md b/docs/specs/components/Toast/Toast.spec.mdindex 0c4a314606..79b1223719 100644--- a/docs/specs/components/Toast/Toast.spec.md+++ b/docs/specs/components/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. Nineteen implementation gaps, listed under Current-state impact. |+| Compatibility/readiness | Records shipped behavior; no public change. Eighteen 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`. |@@ -93,9 +93,6 @@ Consumer migration instructions belong in consumer docs and release notes.once at release on projected travel and cancel a release moving back, and`spec:AST-100` FR1, FR2, and FR4 take the release velocity from the sharedtracker.-- **A toast raised while the window is blurred runs its timer.** Only a later- blur pauses it, so a toast raised while the user is in another window can- auto-hide unseen.- **A control-free toast cannot take focus.** With no control in the newesttoast, F6 leaves focus where it was; dismissing a focused toast beside acontrol-free one drops focus to the page body.@@ -183,7 +180,7 @@ Consumer migration instructions belong in consumer docs and release notes.| ID | Invariant | Basis || ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ || FR1 | A card carries `toast` with `type` and shows `body` and, on its first line, `endContent` then a dismiss Button named by `@astryx.toast.dismiss`; long body text wraps below. `renderContent` replaces that layout, receives `body`, `endContent`, `type`, timing, and a `dismiss` function, and gets no injected dismiss control. | Current source and tests |-| FR2 | With auto-hide on (the default for `info`, off for `error`), the card dismisses with reason `auto` after `autoHideDuration` ms. The timer pauses while the pointer is over the card, focus is inside it, a touch or pen gesture is active, or the window is blurred, and resumes with the remaining time (at least 1 s). Each pause condition holds the timer on its own: one ending resumes it only when no other still holds, and focus moving between the card's own controls keeps it held. Implementation gap: a toast raised while the window is already blurred starts its timer (Current-state impact). | Current source and tests |+| FR2 | With auto-hide on (the default for `info`, off for `error`), the card dismisses with reason `auto` after `autoHideDuration` ms. The timer pauses while the pointer is over the card, focus is inside it, a touch or pen gesture is active, or the window is blurred, and resumes with the remaining time (at least 1 s). Each pause condition holds the timer on its own: one ending resumes it only when no other still holds, and focus moving between the card's own controls keeps it held. A toast raised while the window is already blurred starts with its timer held. | Current source and tests || FR3 | The dismiss button, a swipe, a `dismiss` call, or the returned dismiss function dismiss with reason `manual`; `onHide` fires at most once, when the toast is dismissed, even when dismissed twice during its exit. Implementation gap: with no provider above the caller, a dismissal called before the fallback viewport mounts does nothing, so the toast shows and stays unless it auto-hides (Current-state impact). A toast replaced through `uniqueID` is not dismissed and reports no `onHide`. | Current source and tests || FR4 | A drag toward the position's block edge, from any pointer (`spec:AST-094` FR43), decides once, at release, per `spec:AST-094` FR36–FR37: projected travel past the commit point dismisses, and a release moving back toward the start cancels. A short drag snaps back; horizontal intent, a second touch, or a gesture starting on an interactive descendant does not dismiss. Native page scrolling continues until touch intent matches the dismiss edge. In the default layout the visible dismiss button stays as a non-gesture alternative; custom content supplies its own. Implementation gaps: the shipped rule dismisses on net travel past a distance threshold or a fast flick timed by its own average speed, even after the finger moves back, and recognizes only touch and pen drags, not a mouse (Current-state impact). | Current source and tests || 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 |@@ -253,14 +250,14 @@ button), so no anatomy part can own the `toast` target.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| -------- | ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------- |-| FR1, FR3 | `ToastViewport.test.tsx` layout, custom content, and onHide tests | Default, custom content, double dismiss | Dropped controls or a repeated `onHide` fails. | `audit:Toast/behavior` |-| FR2 | `ToastViewport.test.tsx` blur-pause and pause-source tests | Window blur, new toast during pause, overlapping pointer/focus/window holds, focus moving inside | A timer running while paused, or resuming while another hold remains, fails. | `audit:Toast/behavior` |-| FR4, FR5 | `ToastViewport.test.tsx` gesture and motion tests | Pen and touch thresholds, short drag, horizontal intent, second touch, interactive descendant, RTL | A dismissal from a rejected gesture, a lost snap-back, or off-axis drift fails. | `audit:Toast/behavior` |-| FR6–FR8 | `ToastViewport.test.tsx` placement, cap, and uniqueID tests; `Layer/LayerProvider.test.tsx` inset tests | Each position, cap 1 and an explicit cap, overwrite, ignore | Wrong order, cap, or collision fails. | `audit:Toast/layout` |-| FR9–FR11 | `ToastViewport.test.tsx` announcement, F6, focus, landmark tests | Info, error, StrictMode, nested viewports | A repeated or wrong-urgency announcement, or focus to the body after F6 entry, fails. | `audit:Toast/accessibility` |-| FR12 | `ToastViewport.modalHost.test.tsx` | Dialog, nested dialogs, modal and scrimless drawers, sheets and sheet stacks, modal flows | A lost toast, timer, or focus, or the wrong outlet, fails. | `audit:Toast/layering` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| -------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------- |+| FR1, FR3 | `ToastViewport.test.tsx` layout, custom content, and onHide tests | Default, custom content, double dismiss | Dropped controls or a repeated `onHide` fails. | `audit:Toast/behavior` |+| FR2 | `ToastViewport.test.tsx` blur-pause, pause-source and raised-while-blurred tests | Window blur, toast raised while blurred, new toast during pause, overlapping pointer/focus/window holds, focus moving inside | A timer running while paused, or resuming while another hold remains, fails. | `audit:Toast/behavior` |+| FR4, FR5 | `ToastViewport.test.tsx` gesture and motion tests | Pen and touch thresholds, short drag, horizontal intent, second touch, interactive descendant, RTL | A dismissal from a rejected gesture, a lost snap-back, or off-axis drift fails. | `audit:Toast/behavior` |+| FR6–FR8 | `ToastViewport.test.tsx` placement, cap, and uniqueID tests; `Layer/LayerProvider.test.tsx` inset tests | Each position, cap 1 and an explicit cap, overwrite, ignore | Wrong order, cap, or collision fails. | `audit:Toast/layout` |+| FR9–FR11 | `ToastViewport.test.tsx` announcement, F6, focus, landmark tests | Info, error, StrictMode, nested viewports | A repeated or wrong-urgency announcement, or focus to the body after F6 entry, fails. | `audit:Toast/accessibility` |+| FR12 | `ToastViewport.modalHost.test.tsx` | Dialog, nested dialogs, modal and scrimless drawers, sheets and sheet stacks, modal flows | A lost toast, timer, or focus, or the wrong outlet, fails. | `audit:Toast/layering` |Read from source, with no focused test yet:diff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsxindex a012218249..45b87314dd 100644--- a/packages/core/src/Toast/Toast.tsx+++ b/packages/core/src/Toast/Toast.tsx@@ -296,6 +296,11 @@ export function ToastSurface({const resumeForWindow = () => resumeTimer('window');window.addEventListener('blur', pauseForWindow);window.addEventListener('focus', resumeForWindow);+ // A toast raised while the window is already blurred gets no blur event,+ // so it starts held, and the window's next focus resumes it.+ if (!document.hasFocus()) {+ pauseForWindow();+ }return () => {window.removeEventListener('blur', pauseForWindow);window.removeEventListener('focus', resumeForWindow);diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsxindex 254dfc4a67..511e6a0ca2 100644--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx@@ -27,6 +27,16 @@ import {Drawer} from '../Drawer/Drawer';import {getActiveModalOutlet} from '../Layer/modalOutlet';import type {ToastDismissReason} from './types';+// jsdom reports no window focus until an element is focused, but a test page+// stands for a focused window: a toast raised while the window is blurred+// starts held (FR2), which the blur tests set up on purpose.+beforeEach(() => {+ vi.spyOn(document, 'hasFocus').mockReturnValue(true);+});+afterEach(() => {+ vi.mocked(document.hasFocus).mockRestore?.();+});+// jsdom does not implement the native dialog methods.beforeEach(() => {HTMLDialogElement.prototype.showModal = vi.fn(function (diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxindex 39a62e2a7b..6563fef531 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -19,6 +19,7 @@ import {expectTypeOf,vi,beforeAll,+ beforeEach,afterEach,} from 'vitest';import {@@ -40,6 +41,16 @@ import {ToastViewport} from './ToastViewport';import {useToast} from './useToast';import type {ToastOptions} from './types';+// jsdom reports no window focus until an element is focused, but a test page+// stands for a focused window: a toast raised while the window is blurred+// starts held (FR2), which the blur tests set up on purpose.+beforeEach(() => {+ vi.spyOn(document, 'hasFocus').mockReturnValue(true);+});+afterEach(() => {+ vi.mocked(document.hasFocus).mockRestore?.();+});+// Spy on the announcement sink so tests can prove a toast is announced exactly// once. The mock wraps the real useAnnounce, so the singleton live regions are// still populated (the region-content assertions below depend on it) while@@ -972,6 +983,59 @@ describe('Toast blur timer pause', () => {});});+describe('Toast raised while the window is blurred', () => {+ // FR2: a toast raised while the document does not have focus starts held,+ // so it cannot expire before the user returns to the window.+ it('starts its auto-hide timer held until the window regains focus', () => {+ vi.useFakeTimers();+ const hasFocus = vi.spyOn(document, 'hasFocus').mockReturnValue(false);+ try {+ renderViewport(+ <ShowToastButton options={AUTO_TOAST} triggerLabel="Trigger Auto" />,+ );+ act(() => {+ fireEvent.click(screen.getByText('Trigger Auto'));+ });+ const viewport = screen.getByRole('region', {name: 'Notifications'});+ const heldId = document+ .querySelector('[data-toast-id]')+ ?.getAttribute('data-toast-id');+ act(() => {+ vi.advanceTimersByTime(30_000);+ });+ // An exit that had started would finish here and remove the toast.+ if (heldId) {+ act(() => {+ completeExit(heldId);+ });+ }+ expect(within(viewport).getByText('Auto toast')).toBeInTheDocument();++ hasFocus.mockReturnValue(true);+ act(() => {+ window.dispatchEvent(new Event('focus'));+ });+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ const toastId = document+ .querySelector('[data-toast-id]')+ ?.getAttribute('data-toast-id');+ if (toastId) {+ act(() => {+ completeExit(toastId);+ });+ }+ expect(+ within(viewport).queryByText('Auto toast'),+ ).not.toBeInTheDocument();+ } finally {+ hasFocus.mockRestore();+ vi.useRealTimers();+ }+ });+});+describe('Toast native motion contract', () => {function renderMotionToast(position: React.ComponentProps<typeof ToastViewport>['position'],