An open source design system that's fully customizable and agent ready
TypeScript
fix(Toast): each auto-hide pause condition holds the timer on its own (#9016)
Cindy Zhang743906fa9fb9
diff --git a/.changeset/toast-pause-sources.md b/.changeset/toast-pause-sources.mdnew file mode 100644index 0000000000..3ae8588737--- /dev/null+++ b/.changeset/toast-pause-sources.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Toast: a toast's auto-hide timer stays paused while any pause condition still holds. Before, the pointer leaving the card, focus leaving it, or the window regaining focus resumed the timer even if another condition was still active, so a toast could hide while focus was on its action or the pointer was over it. Focus moving between the toast's own controls also keeps it paused.++@cixzhangdiff --git a/packages/core/src/Toast/Toast.spec.md b/packages/core/src/Toast/Toast.spec.mdindex 41e391a49e..6f50de6bc4 100644--- a/packages/core/src/Toast/Toast.spec.md+++ b/packages/core/src/Toast/Toast.spec.md@@ -93,12 +93,9 @@ 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.-- **The auto-hide pause is one flag.** Any pause condition ending, the pointer- leaving, focus leaving, or the window regaining focus, resumes the timer- while another still holds, so a toast can auto-hide with focus on its action- or with the pointer over it. A toast raised while the window is already- blurred starts its timer and can auto-hide unseen, since only a later blur- pauses it.+- **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.@@ -189,7 +186,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). Implementation gaps: the pause is one flag, so any pause condition ending resumes the timer while another still holds, and 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. Implementation gap: a toast raised while the window is already blurred starts its timer (Current-state impact). | 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 |@@ -262,7 +259,7 @@ button), so no anatomy part can own the `toast` target.| 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 tests | Window blur, new toast during pause | A timer running while paused 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` |@@ -271,8 +268,8 @@ button), so no anatomy part can own the `toast` target.Read from source, with no focused test yet:- FR1: the `toast` target and its `type` state.-- FR2: pausing while the pointer is over the card, focus is inside it, or a- touch gesture is active, and the 1 s minimum on resume.+- FR2: pausing while a touch gesture is active, and the 1 s minimum on+ resume.- FR4: a mouse drag dismissing, and a release moving back cancelling; thegesture tests assert today's touch-and-pen-only, net-travel rule.- FR5: a swipe's settle starting at the release velocity, and thediff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsxindex 6a6774df10..5b263e7573 100644--- a/packages/core/src/Toast/Toast.tsx+++ b/packages/core/src/Toast/Toast.tsx@@ -18,7 +18,7 @@*/import {useCallback, useEffect, useRef} from 'react';-import type {ReactNode} from 'react';+import type {FocusEvent, ReactNode, RefObject} from 'react';import * as stylex from '@stylexjs/stylex';import {Button} from '../Button';import {Icon} from '../Icon';@@ -172,6 +172,9 @@ export function Toast(props: ToastProps) {return <ToastSurface {...props} gestureDirection={1} />;}+/** A condition that holds a toast's auto-hide timer. */+type PauseSource = 'pointer' | 'focus' | 'gesture' | 'window';+export function ToastSurface({type,body,@@ -185,7 +188,13 @@ export function ToastSurface({}: ToastSurfaceProps) {const t = useTranslator();const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const isPausedRef = useRef(false);+ // Every condition that holds the auto-hide timer (pointer over the card,+ // focus inside it, a touch or pen gesture, the window blurred) is tracked on+ // its own, so one ending resumes the timer only when no other still holds.+ const pauseSourcesRef = useRef<Set<PauseSource>>(new Set());+ // The card's root, read when a hold ends to drop a focus hold whose focused+ // control was removed: an unmounting control fires no blur.+ const cardRootRef = useRef<RefObject<HTMLDivElement | null> | null>(null);const remainingRef = useRef(autoHideDuration);// Will be initialized by startTimer when actually usedconst startTimeRef = useRef<number | null>(null);@@ -197,7 +206,7 @@ export function ToastSurface({onDismissRef.current = onDismiss;const startTimer = useCallback(() => {- if (!isAutoHide || isPausedRef.current) {+ if (!isAutoHide || pauseSourcesRef.current.size > 0) {return;}if (timerRef.current) {@@ -209,28 +218,53 @@ export function ToastSurface({}, remainingRef.current);}, [isAutoHide]);- const pauseTimer = useCallback(() => {- if (!isAutoHide || isPausedRef.current) {- return;- }- isPausedRef.current = true;- if (timerRef.current) {- clearTimeout(timerRef.current);- timerRef.current = null;- }- if (startTimeRef.current != null) {- const elapsed = Date.now() - startTimeRef.current;- remainingRef.current = Math.max(remainingRef.current - elapsed, 1000);- }- }, [isAutoHide]);+ const pauseTimer = useCallback(+ (source: PauseSource) => {+ if (!isAutoHide) {+ return;+ }+ const sources = pauseSourcesRef.current;+ const wasRunning = sources.size === 0;+ sources.add(source);+ if (!wasRunning) {+ return;+ }+ if (timerRef.current) {+ clearTimeout(timerRef.current);+ timerRef.current = null;+ }+ if (startTimeRef.current != null) {+ const elapsed = Date.now() - startTimeRef.current;+ remainingRef.current = Math.max(remainingRef.current - elapsed, 1000);+ }+ },+ [isAutoHide],+ );- const resumeTimer = useCallback(() => {- if (!isAutoHide || !isPausedRef.current) {- return;- }- isPausedRef.current = false;- startTimer();- }, [isAutoHide, startTimer]);+ const resumeTimer = useCallback(+ (source: PauseSource) => {+ if (!isAutoHide) {+ return;+ }+ const sources = pauseSourcesRef.current;+ if (!sources.delete(source)) {+ return;+ }+ const root = cardRootRef.current?.current;+ if (+ sources.has('focus') &&+ root != null &&+ !root.contains(document.activeElement)+ ) {+ sources.delete('focus');+ }+ if (sources.size > 0) {+ return;+ }+ startTimer();+ },+ [isAutoHide, startTimer],+ );useEffect(() => {remainingRef.current = autoHideDuration;@@ -250,15 +284,48 @@ export function ToastSurface({if (!isAutoHide) {return;}- window.addEventListener('blur', pauseTimer);- window.addEventListener('focus', resumeTimer);+ const pauseForWindow = () => pauseTimer('window');+ const resumeForWindow = () => resumeTimer('window');+ window.addEventListener('blur', pauseForWindow);+ window.addEventListener('focus', resumeForWindow);return () => {- window.removeEventListener('blur', pauseTimer);- window.removeEventListener('focus', resumeTimer);+ window.removeEventListener('blur', pauseForWindow);+ window.removeEventListener('focus', resumeForWindow);};}, [isAutoHide, pauseTimer, resumeTimer]);- const isTimerPaused = useCallback(() => isPausedRef.current, []);+ const isGesturePausing = useCallback(+ () => pauseSourcesRef.current.has('gesture'),+ [],+ );+ const pauseForGesture = useCallback(+ () => pauseTimer('gesture'),+ [pauseTimer],+ );+ const resumeForGesture = useCallback(+ () => resumeTimer('gesture'),+ [resumeTimer],+ );+ const pauseForPointer = useCallback(+ () => pauseTimer('pointer'),+ [pauseTimer],+ );+ const resumeForPointer = useCallback(+ () => resumeTimer('pointer'),+ [resumeTimer],+ );+ const pauseForFocus = useCallback(() => pauseTimer('focus'), [pauseTimer]);+ const resumeForFocus = useCallback(+ (event: FocusEvent<HTMLDivElement>) => {+ // Focus moving between controls inside the card keeps it held.+ const next = event.relatedTarget;+ if (next instanceof Node && event.currentTarget.contains(next)) {+ return;+ }+ resumeTimer('focus');+ },+ [resumeTimer],+ );const dismissFromGesture = useCallback(() => {onDismissRef.current('manual');}, []);@@ -266,12 +333,13 @@ export function ToastSurface({direction: gestureDirection,enabled: !isExiting,canPauseTimer: isAutoHide,- isTimerPaused,- pauseTimer,- resumeTimer,+ isTimerPaused: isGesturePausing,+ pauseTimer: pauseForGesture,+ resumeTimer: resumeForGesture,dismiss: dismissFromGesture,shouldIgnoreTarget: isInteractiveTarget,});+ cardRootRef.current = rootRef;const handleDismiss = useCallback(() => {onDismiss('manual');@@ -290,10 +358,10 @@ export function ToastSurface({role={isError ? 'alert' : 'status'}aria-live={isError ? 'assertive' : 'polite'}aria-atomic="true"- onMouseEnter={pauseTimer}- onMouseLeave={resumeTimer}- onFocusCapture={pauseTimer}- onBlurCapture={resumeTimer}+ onMouseEnter={pauseForPointer}+ onMouseLeave={resumeForPointer}+ onFocusCapture={pauseForFocus}+ onBlurCapture={resumeForFocus}{...gestureBindings}{...mergeProps(themeProps('toast', {type}),diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxindex 060d14b0ac..daa7b5c120 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -2658,6 +2658,150 @@ describe('toast timer lifecycle (#3589)', () => {expect(onHide).toHaveBeenCalledTimes(1);});+ // spec:Toast FR2/AR3: each pause condition is held on its own, so one+ // ending never resumes the timer while another still holds.+ function showPausableToast(onHide: () => void) {+ renderViewport(+ <ShowToastButton+ options={{+ body: 'Held',+ autoHideDuration: 3000,+ endContent: <Button label="Undo" />,+ onHide,+ }}+ triggerLabel="Show held"+ />,+ );+ act(() => {+ fireEvent.click(screen.getByText('Show held'));+ });+ const viewport = screen.getByRole('region', {name: 'Notifications'});+ const card = within(viewport).getByText('Held').closest('[role="status"]');+ if (!(card instanceof HTMLElement)) {+ throw new Error('toast card not found');+ }+ return {card, action: within(card).getByRole('button', {name: 'Undo'})};+ }++ it('keeps the timer paused while focus is inside after the pointer leaves', () => {+ vi.useFakeTimers();+ try {+ const onHide = vi.fn();+ const {card, action} = showPausableToast(onHide);+ act(() => {+ fireEvent.mouseEnter(card);+ });+ act(() => {+ action.focus();+ });+ act(() => {+ fireEvent.mouseLeave(card);+ });+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onHide).not.toHaveBeenCalled();+ // Focus leaving the card releases the last hold.+ act(() => {+ action.blur();+ });+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onHide).toHaveBeenCalledWith('auto');+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps the timer paused while the pointer is over it after the window regains focus', () => {+ vi.useFakeTimers();+ try {+ const onHide = vi.fn();+ const {card} = showPausableToast(onHide);+ act(() => {+ fireEvent.blur(window);+ });+ act(() => {+ fireEvent.mouseEnter(card);+ });+ act(() => {+ fireEvent.focus(window);+ });+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onHide).not.toHaveBeenCalled();+ act(() => {+ fireEvent.mouseLeave(card);+ });+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onHide).toHaveBeenCalledWith('auto');+ } finally {+ vi.useRealTimers();+ }+ });++ it('releases the focus hold when the focused control is removed', () => {+ vi.useFakeTimers();+ try {+ const onHide = vi.fn();+ const {card, action} = showPausableToast(onHide);+ act(() => {+ fireEvent.mouseEnter(card);+ });+ act(() => {+ action.focus();+ });+ // A control that unmounts while focused fires no blur.+ act(() => {+ action.remove();+ });+ act(() => {+ fireEvent.mouseLeave(card);+ });+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onHide).toHaveBeenCalledWith('auto');+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps the timer paused while focus moves between controls inside the card', () => {+ vi.useFakeTimers();+ try {+ const onHide = vi.fn();+ const {card, action} = showPausableToast(onHide);+ const dismiss = within(card)+ .getAllByRole('button')+ .find(button => button !== action);+ if (!dismiss) {+ throw new Error('dismiss button not found');+ }+ act(() => {+ action.focus();+ });+ act(() => {+ vi.advanceTimersByTime(2_000);+ });+ act(() => {+ dismiss.focus();+ });+ // Moving between the card's own controls neither restarts nor resumes+ // the timer.+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onHide).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+it('keeps a window-blur pause alive when another toast arrives', () => {vi.useFakeTimers();try {