An open source design system that's fully customizable and agent ready
TypeScript
fix(Toast): an update through uniqueID keeps focus on the toast's controls (#9624)
Cindy Zhangeaa9968af332
diff --git a/.changeset/toast-overwrite-in-place-focus.md b/.changeset/toast-overwrite-in-place-focus.mdnew file mode 100644index 0000000000..2f01b31902--- /dev/null+++ b/.changeset/toast-overwrite-in-place-focus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Toast`: a toast updated through `uniqueID` (`collisionBehavior: 'overwrite'`) now updates in place, so focus on its controls stays put instead of dropping to the page. If the update removes the focused control, focus moves to a control in the toasts (such as a dismiss button) or, with none, back to where it was before entering the toasts. Dismissing a focused toast when only toasts without controls remain also returns focus there. An update that makes a toast auto-hide keeps its timer held while focus is inside it. Outside a modal, toasts in a `ToastViewport` no longer carry their own live region, so each toast and each update is announced once, by the viewport; while a modal hosts the viewport, each toast announces itself, because the modal hides the viewport's channel.++@cixzhang @duytbpdiff --git a/docs/specs/components/Toast/Toast.spec.md b/docs/specs/components/Toast/Toast.spec.mdindex 79b1223719..31505266b9 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. Eighteen 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`. |@@ -75,10 +75,6 @@ Consumer migration instructions belong in consumer docs and release notes.## Current-state impact-- **Each card is a second live region.** The viewport announces every toast- through the shared announcement channel, and each visible card also carries- `role="status"` or `role="alert"` with `aria-live`. `spec:AST-086` FR1 requires- exactly one announcement owner per message.- **The viewport builds its own top layer and exit.** ToastViewport mounts itsown 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@@ -93,9 +89,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 control-free toast cannot take focus.** With no control in the newest- toast, F6 leaves focus where it was; dismissing a focused toast beside a- control-free one drops focus to the page body.- **The swipe ignores a mouse.** Only touch and pen drags are recognized; amouse drag does nothing. `spec:AST-094` FR43 attaches gestures to everypointer.@@ -186,9 +179,9 @@ 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`, 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 |+| 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 |-| 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. Implementation gap: with no control in the target toast, F6 leaves focus where it was and the handoff drops focus to the page (Current-state impact). | Current source and 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 |@@ -250,14 +243,16 @@ 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, 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` |+| 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` |+| FR2, FR8–FR10 | `ToastViewport.test.tsx` "keeps focus on a control inside a toast that an overwrite updates", "hands focus off when an overwrite removes the focused control", "updates a settled toast in place when an overwrite replaces it through uniqueID", "announces an overwrite once, through the viewport only", "auto-hides a control-free replacement after the update removes the focused control" | Overwrite with focus inside; overwrite that removes the focused control | A remounted card, or focus dropping to the page body, fails. | `audit:Toast/accessibility` |+| FR10 | `ToastViewport.test.tsx` "restores focus after a toast reached with Tab rather than F6 is dismissed", "restores the remembered element when only a control-free toast remains" | Tab- or click-reached toast dismissed; a control-free toast remaining | Focus dropping to the page body after a dismissal 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.doc.mjs b/packages/core/src/Toast/Toast.doc.mjsindex 1bdb79e405..c0cf92d900 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, the live-region role and auto-hide behavior, 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, 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'.",},],theming: {@@ -211,7 +211,7 @@ export const docsZh = {collisionBehavior: '当已存在相同 uniqueID 的 toast 时的行为。',onHide: '当 toast 被移除时触发的回调。',renderContent:- "用你自己的布局替换该 toast 卡片内部的内容。Astryx 保留卡片本身、astryx-toast 主题目标、实时区域角色和自动关闭行为,并把消息、endContent、解析后的 toast 设置和 dismiss 回调交给渲染函数。自定义渲染函数完全拥有布局中的控件:请组合所需的控件并通过它调用 dismiss。Astryx 不会向自定义内容注入后备关闭按钮。按 toast 单独设置:应用可通过封装 useToast 并在每次调用时传入来共享同一套布局;而由库代码发起、从不传入该参数的 toast 会渲染为普通的 Astryx toast。传入参数为 {body, endContent, type, isAutoHide, autoHideDuration, dismiss},其中 type 为 'info' | 'error'。",+ "用你自己的布局替换该 toast 卡片内部的内容。Astryx 保留卡片本身、astryx-toast 主题目标和自动关闭行为(在 ToastViewport 中由视口播报该 toast;当模态框承载视口时由卡片自行播报),并把消息、endContent、解析后的 toast 设置和 dismiss 回调交给渲染函数。自定义渲染函数完全拥有布局中的控件:请组合所需的控件并通过它调用 dismiss。Astryx 不会向自定义内容注入后备关闭按钮。按 toast 单独设置:应用可通过封装 useToast 并在每次调用时传入来共享同一套布局;而由库代码发起、从不传入该参数的 toast 会渲染为普通的 Astryx toast。传入参数为 {body, endContent, type, isAutoHide, autoHideDuration, dismiss},其中 type 为 'info' | 'error'。",},usage: {description:@@ -328,6 +328,7 @@ export const docsDense = {uniqueID: 'unique id for dedup',collisionBehavior: 'behavior when matching uniqueID exists',onHide: 'callback when toast removed',- renderContent: 'custom inner layout; receives content, resolved settings + dismiss callback; no injected fallback control',+ renderContent:+ 'custom inner layout; receives content, resolved settings + dismiss callback; no injected fallback control',},};diff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsxindex 45b87314dd..e9a0f95932 100644--- a/packages/core/src/Toast/Toast.tsx+++ b/packages/core/src/Toast/Toast.tsx@@ -154,6 +154,16 @@ export interface ToastProps {interface ToastSurfaceProps extends ToastProps {gestureDirection: ToastGestureDirection;+ /**+ * Changes when a uniqueID overwrite updates this card in place: the new+ * toast's auto-hide timer starts over.+ */+ timerKey?: string;+ /**+ * False when the viewport announces the toast: the card then carries no+ * live region of its own, so an update in place is announced once.+ */+ isLiveRegion?: boolean;}/**@@ -193,6 +203,8 @@ export function ToastSurface({onDismiss,renderContent,gestureDirection,+ timerKey,+ isLiveRegion = true,}: ToastSurfaceProps) {const t = useComponentTranslator();const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -226,34 +238,28 @@ export function ToastSurface({}, remainingRef.current);}, [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],- );+ // Pointer, focus and gesture holds are tracked whatever isAutoHide is: an+ // overwrite can turn a toast that does not auto-hide into one that does+ // while a hold is in place. The window hold leaves with its listeners.+ const pauseTimer = useCallback((source: PauseSource) => {+ 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);+ }+ }, []);const resumeTimer = useCallback((source: PauseSource) => {- if (!isAutoHide) {- return;- }const sources = pauseSourcesRef.current;if (!sources.delete(source)) {return;@@ -271,20 +277,31 @@ export function ToastSurface({}startTimer();},- [isAutoHide, startTimer],+ [startTimer],);useEffect(() => {remainingRef.current = autoHideDuration;+ // An update in place can remove the focused control, which fires no blur:+ // a focus hold whose focus has left the card is stale.+ const root = cardRootRef.current?.current;+ if (+ pauseSourcesRef.current.has('focus') &&+ root != null &&+ !root.contains(root.ownerDocument.activeElement)+ ) {+ pauseSourcesRef.current.delete('focus');+ }startTimer();return () => {if (timerRef.current) {clearTimeout(timerRef.current);}};- // startTimer's identity is stable per isAutoHide, so this runs on mount- // and on a genuine duration change — not on unrelated viewport renders.- }, [autoHideDuration, startTimer]);+ // startTimer's identity is stable per isAutoHide, so this runs on mount,+ // on a genuine duration change and on an overwrite (timerKey), not on+ // unrelated viewport renders.+ }, [autoHideDuration, startTimer, timerKey]);// Pause the auto-hide timer while the window is not focused, so a toast// doesn't silently expire while the user is in another window or tab.@@ -292,6 +309,7 @@ export function ToastSurface({if (!isAutoHide) {return;}+ const pauseSources = pauseSourcesRef.current;const pauseForWindow = () => pauseTimer('window');const resumeForWindow = () => resumeTimer('window');window.addEventListener('blur', pauseForWindow);@@ -304,6 +322,8 @@ export function ToastSurface({return () => {window.removeEventListener('blur', pauseForWindow);window.removeEventListener('focus', resumeForWindow);+ // With the listeners gone, no focus event would clear the window hold.+ pauseSources.delete('window');};}, [isAutoHide, pauseTimer, resumeTimer]);@@ -368,9 +388,9 @@ export function ToastSurface({return (<divref={rootRef}- role={isError ? 'alert' : 'status'}- aria-live={isError ? 'assertive' : 'polite'}- aria-atomic="true"+ role={isLiveRegion ? (isError ? 'alert' : 'status') : undefined}+ aria-live={isLiveRegion ? (isError ? 'assertive' : 'polite') : undefined}+ aria-atomic={isLiveRegion ? 'true' : undefined}onMouseEnter={pauseForPointer}onMouseLeave={resumeForPointer}onFocusCapture={pauseForFocus}diff --git a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx b/packages/core/src/Toast/ToastViewport.modalHost.test.tsxindex 1b600c1281..82b5bddf98 100644--- a/packages/core/src/Toast/ToastViewport.modalHost.test.tsx+++ b/packages/core/src/Toast/ToastViewport.modalHost.test.tsx@@ -241,6 +241,39 @@ 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(+ '[aria-live], [role="status"], [role="alert"]',+ );+ 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: 'Close Edit'}));+ expect(liveRegionOf('Saved')).toBeNull();+ });+it('moves into an open Dialog and back when it closes, keeping the toast', () => {const {container} = render(<ToastViewport>diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxindex 6563fef531..0960d273d8 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -614,7 +614,7 @@ 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', () => {+ it('keeps focus in the replacement when a control inside a toast raises its repeat and dismisses it', () => {function OfflineFlow() {const toast = useToast();const dismissOfflineRef = useRef<(() => void) | null>(null);@@ -673,12 +673,13 @@ describe('ToastViewport keyboard reach + 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);+ // Toast.spec.md FR8: the repeat updates the card in place, so the pressed+ // Retry stays focused in it; dismissing the replaced toast leaves the row+ // to the replacement, and focus does not jump to a neighbour.+ const replacement = getToastWrapperByText('Still offline');+ expect(document.activeElement).toBe(retry);+ expect(replacement.contains(retry)).toBe(true);+ expect(screen.queryByText('Offline')).toBeNull();});it('moves focus into the replacement when a control inside the only toast raises its repeat and dismisses it', () => {@@ -883,6 +884,310 @@ describe('ToastViewport keyboard reach + focus', () => {expect(document.activeElement).toBe(trigger);});+ // FR8: an overwrite updates the card in place under the same key, so focus+ // inside it stays on the same control.+ it('keeps focus on a control inside a toast that an overwrite updates', () => {+ const upload = (percent: number): ToastOptions => ({+ body: `Uploading ${percent}%`,+ uniqueID: 'upload',+ collisionBehavior: 'overwrite',+ isAutoHide: false,+ endContent: <button type="button">Cancel upload</button>,+ });+ renderViewport(+ <>+ <ShowToastButton options={upload(10)} triggerLabel="Start" />+ <ShowToastButton options={upload(60)} triggerLabel="Progress" />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Start'));+ });+ const cancel = screen.getByRole('button', {name: 'Cancel upload'});+ act(() => {+ cancel.focus();+ });++ act(() => {+ fireEvent.click(screen.getByText('Progress'));+ });++ const viewport = screen.getByRole('region', {name: 'Notifications'});+ expect(within(viewport).getByText('Uploading 60%')).toBeInTheDocument();+ expect(cancel).toBeInTheDocument();+ expect(document.activeElement).toBe(cancel);+ });++ // FR2, FR8: an overwrite that turns the card into one that auto-hides keeps+ // the timer held while focus is inside it.+ it('keeps an overwritten toast held while focus is inside when it starts auto-hiding', () => {+ vi.useFakeTimers();+ const onHide = vi.fn();+ try {+ renderViewport(+ <>+ <ShowToastButton+ options={{+ body: 'Uploading',+ uniqueID: 'upload',+ isAutoHide: false,+ endContent: <button type="button">Cancel upload</button>,+ }}+ triggerLabel="Start"+ />+ <ShowToastButton+ options={{+ body: 'Upload done',+ uniqueID: 'upload',+ autoHideDuration: 2000,+ onHide,+ endContent: <button type="button">Cancel upload</button>,+ }}+ triggerLabel="Finish"+ />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Start'));+ });+ const cancel = screen.getByRole('button', {name: 'Cancel upload'});+ act(() => {+ cancel.focus();+ });++ act(() => {+ fireEvent.click(screen.getByText('Finish'));+ });+ act(() => {+ vi.advanceTimersByTime(5000);+ });++ expect(onHide).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(cancel);+ } finally {+ vi.useRealTimers();+ }+ });++ // FR2: an update that removes the focused control drops its focus hold, so+ // a control-free, auto-hiding replacement still hides on time.+ it('auto-hides a control-free replacement after the update removes the focused control', () => {+ vi.useFakeTimers();+ const onHide = vi.fn();+ try {+ renderViewport(+ <>+ <ShowToastButton+ options={{+ body: 'Uploading',+ uniqueID: 'upload',+ isAutoHide: false,+ endContent: <button type="button">Cancel upload</button>,+ }}+ triggerLabel="Start"+ />+ <ShowToastButton+ options={{+ body: 'Uploaded',+ uniqueID: 'upload',+ autoHideDuration: 2000,+ renderContent: () => <span>Uploaded</span>,+ onHide,+ }}+ triggerLabel="Finish"+ />+ </>,+ );+ const start = screen.getByText('Start');+ act(() => {+ start.focus();+ fireEvent.click(start);+ });+ act(() => {+ screen.getByRole('button', {name: 'Cancel upload'}).focus();+ });++ act(() => {+ fireEvent.click(screen.getByText('Finish'));+ });+ act(() => {+ vi.advanceTimersByTime(2500);+ });++ expect(onHide).toHaveBeenCalledWith('auto');+ } finally {+ vi.useRealTimers();+ }+ });++ // FR2: a window hold taken while the toast auto-hid does not outlive the+ // listeners an update that turns auto-hide off removes.+ it('auto-hides again after an update turns auto-hide off and on across a window blur', () => {+ vi.useFakeTimers();+ const onHide = vi.fn();+ try {+ const status = (body: string, options: Partial<ToastOptions>) => ({+ body,+ uniqueID: 'network',+ ...options,+ });+ renderViewport(+ <>+ <ShowToastButton+ options={status('Syncing', {autoHideDuration: 2000})}+ triggerLabel="Sync"+ />+ <ShowToastButton+ options={status('Offline', {type: 'error'})}+ triggerLabel="Lose network"+ />+ <ShowToastButton+ options={status('Back online', {autoHideDuration: 2000, onHide})}+ triggerLabel="Reconnect"+ />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Sync'));+ });+ act(() => {+ fireEvent.blur(window);+ });+ act(() => {+ fireEvent.click(screen.getByText('Lose network'));+ });+ act(() => {+ fireEvent.focus(window);+ });+ act(() => {+ fireEvent.click(screen.getByText('Reconnect'));+ });+ act(() => {+ vi.advanceTimersByTime(2500);+ });++ expect(onHide).toHaveBeenCalledWith('auto');+ } finally {+ vi.useRealTimers();+ }+ });++ // FR9: the viewport is the one announcement owner, so a card updated in+ // place carries no live region of its own and is announced once.+ it('announces an overwrite once, through the viewport only', () => {+ const upload = (percent: number): ToastOptions => ({+ body: `Uploading ${percent}%`,+ uniqueID: 'upload',+ isAutoHide: false,+ });+ renderViewport(+ <>+ <ShowToastButton options={upload(10)} triggerLabel="Start" />+ <ShowToastButton options={upload(60)} triggerLabel="Progress" />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Start'));+ });+ act(() => {+ fireEvent.click(screen.getByText('Progress'));+ });++ // The toast's text sits in no live region inside its row: only the+ // viewport's own announcer speaks it.+ const row = getToastWrapperByText('Uploading 60%');+ const liveAncestor = within(row)+ .getByText('Uploading 60%')+ .closest('[aria-live], [role="status"], [role="alert"]');+ expect(liveAncestor == null || !row.contains(liveAncestor)).toBe(true);+ });++ // FR8, FR10: when the overwrite removes the focused control, focus moves as+ // FR10 hands it off, never to the page body.+ it('hands focus off when an overwrite removes the focused control', () => {+ renderViewport(+ <>+ <ShowToastButton+ options={{+ body: 'Uploading',+ uniqueID: 'upload',+ isAutoHide: false,+ endContent: <button type="button">Cancel upload</button>,+ }}+ triggerLabel="Start"+ />+ <ShowToastButton+ options={{+ body: 'Uploaded',+ uniqueID: 'upload',+ isAutoHide: false,+ renderContent: () => <span>Uploaded</span>,+ }}+ triggerLabel="Finish"+ />+ </>,+ );+ const start = screen.getByText('Start');+ act(() => {+ start.focus();+ fireEvent.click(start);+ });+ act(() => {+ screen.getByRole('button', {name: 'Cancel upload'}).focus();+ });++ act(() => {+ fireEvent.click(screen.getByText('Finish'));+ });++ expect(document.activeElement).not.toBe(document.body);+ expect(document.activeElement).toBe(start);+ });++ // FR10: dismissing a focused toast beside a control-free one never drops+ // focus to the page body; with no control to take it, the remembered+ // element does.+ it('restores the remembered element when only a control-free toast remains', () => {+ renderViewport(+ <>+ <ShowToastButton+ options={{+ body: 'Synced',+ isAutoHide: false,+ renderContent: () => <span>Synced</span>,+ }}+ triggerLabel="Trigger quiet"+ />+ <ShowToastButton options={INFO_B} triggerLabel="Trigger B" />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Trigger quiet'));+ });+ const trigger = screen.getByText('Trigger B');+ act(() => {+ trigger.focus();+ fireEvent.click(trigger);+ });+ const dismiss = screen.getByRole('button', {name: 'Dismiss notification'});+ act(() => {+ dismiss.focus();+ });+ const toastId = dismiss+ .closest('[data-toast-id]')!+ .getAttribute('data-toast-id')!;++ act(() => {+ fireEvent.click(dismiss);+ });+ act(() => {+ completeExit(toastId);+ });++ expect(document.activeElement).not.toBe(document.body);+ expect(document.activeElement).toBe(trigger);+ });+it('keeps the return target while focus visits portaled toast content', () => {renderViewport(<ShowToastButton@@ -1127,13 +1432,10 @@ describe('Toast native motion contract', () => {expect(getComputedStyle(wrapper).pointerEvents).toBe('auto');});- it('settles a toast that replaced another through uniqueID', () => {- // An overwrite unmounts the replaced row and mounts a new one with a new- // id, so the new row runs its own entry transition and has to release the- // clip on its own. The replaced id is dropped at the same time: nothing- // dismisses it, so neither removeToast nor handleExited would ever prune- // it, and a viewport overwriting one uniqueID on a schedule would collect- // a dead id per update for as long as it lives.+ it('updates a settled toast in place when an overwrite replaces it through uniqueID', () => {+ // FR8: an overwrite keeps the replaced toast's row, so the card updates in+ // place: the row stays settled (no second entry transition) and carries+ // the new toast's id.render(<ToastViewport isTopLayer={false} position="bottomEnd" maxVisible={3}><ShowToastButton@@ -1163,19 +1465,12 @@ describe('Toast native motion contract', () => {fireEvent.click(screen.getByText('Show v2'));});const second = getToastWrapperByText('Changes saved');- // A different row, so the settled state of the one it replaced says- // nothing about it: it starts clipped.+ expect(second).toBe(first);expect(second.getAttribute('data-toast-id')).not.toBe(firstId);- expect(- getComputedStyle(second.firstElementChild as HTMLElement).overflow,- ).toBe('hidden');-- act(() => {- fireEvent.transitionEnd(second, {propertyName: 'grid-template-rows'});- });expect(getComputedStyle(second.firstElementChild as HTMLElement).overflow,).toBe('visible');+ expect(document.querySelectorAll('[data-toast-id]')).toHaveLength(1);});it('drops settled state when a toast is evicted and later resurfaces', () => {@@ -2819,7 +3114,9 @@ describe('toast timer lifecycle (#3589)', () => {fireEvent.click(screen.getByText('Show held'));});const viewport = screen.getByRole('region', {name: 'Notifications'});- const card = within(viewport).getByText('Held').closest('[role="status"]');+ // The row's wrapper holds the clip, which holds the card.+ const card =+ getToastWrapperByText('Held').firstElementChild?.firstElementChild;if (!(card instanceof HTMLElement)) {throw new Error('toast card not found');}diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsxindex daf859aad4..dd4caeb4fb 100644--- a/packages/core/src/Toast/ToastViewport.tsx+++ b/packages/core/src/Toast/ToastViewport.tsx@@ -21,6 +21,7 @@ import {useMemo,useRef,useState,+ useSyncExternalStore,} from 'react';import type {ReactNode} from 'react';import {createPortal} from 'react-dom';@@ -28,6 +29,11 @@ import * as stylex from '@stylexjs/stylex';import {spacingVars, durationVars, easeVars} from '../theme/tokens.stylex';import {mergeProps} from '../utils';import {getNodeText} from '../utils/getNodeText';+import {+ moveFocusLeftBehind,+ noteFocusWithin,+ type FocusWithin,+} from '../utils/focusReturn';import {INTERACTIVE_SELECTORS} from '../hooks/useClickableContainer';import {useAnnounce} from '../hooks/useAnnounce';import {layerTextReset} from '../Layer/layerTextReset.stylex';@@ -224,6 +230,8 @@ interface ToastRowProps {isReversed: boolean;onExited: (id: string) => void;onDismiss: (id: string, reason: ToastDismissReason) => void;+ /** Whether the card carries its own live region (see ToastViewport). */+ isLiveRegion: boolean;}/**@@ -246,6 +254,7 @@ function ToastRow({isReversed,onExited,onDismiss,+ isLiveRegion,}: ToastRowProps) {const o = entry.options;const type = o.type ?? 'info';@@ -296,6 +305,8 @@ function ToastRow({gestureDirection={isReversed ? -1 : 1}onDismiss={reason => onDismiss(entry.id, reason)}renderContent={o.renderContent}+ timerKey={entry.id}+ isLiveRegion={isLiveRegion}/></div></div>@@ -303,6 +314,9 @@ 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@@ -363,6 +377,13 @@ export function ToastViewport({// The next toast id that should receive focus once the dismissed toast has// unmounted, or 'restore' to fall back to the previously-focused element.const pendingFocusRef = useRef<string | 'restore' | null>(null);+ // The id of a toast whose overwrite updated a row that held focus. If the+ // update removed the focused control, the commit hands focus off.+ const overwriteFocusRef = useRef<{id: string; note: FocusWithin} | null>(+ null,+ );+ // Where focus was inside a toast whose dismissal hands focus off.+ const dismissFocusNoteRef = useRef<FocusWithin | null>(null);// Collect a focusable control within a toast node, if any.// Reuses the canonical INTERACTIVE_SELECTORS list (native controls plus@@ -392,13 +413,9 @@ export function ToastViewport({[],);- // Announce toasts through the persistent singleton live regions. Each- // <Toast> also renders its own role="status"/"alert" region, but that region- // is "born with content" — mounted together with its text — which many- // screen readers do not announce (see useAnnounce.ts); the singleton regions- // are mounted empty and only mutated afterwards, so they are what actually- // guarantees the announcement (the per-toast markup is kept for browse-mode- // discoverability). The announcement happens in addToast — the imperative+ // Announce toasts through the persistent singleton live regions. They are+ // mounted empty and only mutated afterwards, which screen readers announce+ // (see useAnnounce.ts). The announcement happens in addToast — the imperative// dispatch path invoked once per useToast() call from an event handler,// never from render — so each toast is announced exactly once by// construction, independent of the React render lifecycle (StrictMode@@ -406,6 +423,16 @@ export function ToastViewport({// 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,+ );+ const isModalHosted = isTopLayer && hasModalOutlet;const addToast = useCallback((entry: ToastEntry) => {@@ -441,9 +468,29 @@ export function ToastViewport({if (overwritten && renderedToastsRef.current.includes(overwritten)) {replacedRef.current.set(overwritten.id, overwritten);}+ // An overwrite of a toast that is not leaving keeps its row, so the card+ // updates in place and focus inside it stays. A leaving namesake+ // is replaced by a new row, which enters again.+ const keepsRow =+ overwritten != null && !exitingIdsRef.current.has(overwritten.id);+ const placed: ToastEntry = keepsRow+ ? {...entry, rowKey: overwritten.rowKey ?? overwritten.id}+ : entry;+ if (keepsRow) {+ // If the update removes the focused control, the commit hands focus+ // off as a dismissal does.+ const note = noteFocusWithin(+ viewportRef.current?.querySelector<HTMLElement>(+ `[data-toast-id="${overwritten.id}"]`,+ ),+ );+ if (note != null) {+ overwriteFocusRef.current = {id: placed.id, note};+ }+ }const projected = overwritten- ? committed.map(t => (t === overwritten ? entry : t))- : [...committed, entry];+ ? committed.map(t => (t === overwritten ? placed : t))+ : [...committed, placed];// `maxVisible={0}` shows every toast (FR7): nothing leaves the window.const firstVisible = maxVisible > 0 ? projected.length - maxVisible : 0;const cutIds = new Set(@@ -470,7 +517,7 @@ export function ToastViewport({}}}- pending.set(entry.id, entry);+ pending.set(entry.id, placed);// An overwrite swaps a new entry, with a new id, into the replaced// toast's place, so the old row leaves the DOM without ever being// dismissed. Its settled id is dropped by the prune below, which covers@@ -482,8 +529,8 @@ export function ToastViewport({// 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];+ ? kept.map(t => (t === overwritten ? placed : t))+ : [...kept, placed];});},[announce, maxVisible],@@ -512,14 +559,23 @@ export function ToastViewport({// focused before the user entered the viewport) rather than <body>.const el = viewportRef.current;const active = document.activeElement;- const dismissedNode =- el?.querySelector<HTMLElement>(`[data-toast-id="${id}"]`) ?? null;+ // A toast an overwrite replaced in place no longer owns its row: the+ // replacement does, so dismissing the replaced toast leaves the row, and+ // focus in it, to the replacement.+ const rowKey = entry.rowKey ?? entry.id;+ const isReplacedInPlace =+ !toastsRef.current.some(t => t.id === id) &&+ toastsRef.current.some(t => t.rowKey === rowKey);+ const dismissedNode = isReplacedInPlace+ ? null+ : (el?.querySelector<HTMLElement>(`[data-toast-id="${id}"]`) ?? null);if (dismissedNode &&active instanceof Node &&dismissedNode.contains(active)) {focusHandoffIdRef.current = id;+ dismissFocusNoteRef.current = noteFocusWithin(dismissedNode);// 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@@ -587,6 +643,41 @@ export function ToastViewport({setToasts(prev => prev.filter(t => t.id !== id));}, []);+ // Moves focus to a control in the target toast, else in another toast that+ // shows (newest first), else back to the element focused before focus+ // entered the viewport, so a handoff never drops focus to <body>.+ const handOffFocus = useCallback(+ (note: FocusWithin | null, targetId: string | null) => {+ const el = viewportRef.current;+ const rowFor = (id: string) =>+ el?.querySelector<HTMLElement>(`[data-toast-id="${id}"]`) ?? null;+ const shownIds = toastsRef.current+ .slice(maxVisibleRef.current > 0 ? -maxVisibleRef.current : 0)+ .map(t => t.id)+ .reverse();+ const candidates =+ targetId == null+ ? []+ : [targetId, ...shownIds.filter(id => id !== targetId)];+ let target: HTMLElement | null = null;+ for (const id of candidates) {+ target = getFocusable(rowFor(id));+ if (target != null) {+ break;+ }+ }+ const prev = prevFocusRef.current;+ const isReturning = target == null && prev != null && prev.isConnected;+ if (target == null) {+ target = isReturning ? prev : el;+ }+ if (moveFocusLeftBehind(note, target) && isReturning) {+ prevFocusRef.current = null;+ }+ },+ [getFocusable],+ );+// After a dismissed toast unmounts, hand focus off so it never falls to// <body>. Runs in a layout effect once the toast list no longer contains// the dismissed toast.@@ -602,27 +693,21 @@ export function ToastViewport({}focusHandoffIdRef.current = null;pendingFocusRef.current = null;- const el = viewportRef.current;- if (target !== 'restore' && el) {- const nextNode = el.querySelector<HTMLElement>(- `[data-toast-id="${target}"]`,- );- const focusable = getFocusable(nextNode) ?? nextNode;- if (focusable) {- focusable.focus();- return;- }- }- // No remaining toast to receive focus — restore the previously-focused- // element if it's still connected, else fall back to the container.- const prev = prevFocusRef.current;- prevFocusRef.current = null;- if (prev && prev.isConnected) {- prev.focus();- } else if (el) {- el.focus();+ const note = dismissFocusNoteRef.current;+ dismissFocusNoteRef.current = null;+ handOffFocus(note, target === 'restore' ? null : target);+ }, [toasts, handOffFocus]);++ // After an overwrite updated a row that held focus: focus stays on the same+ // control, or, if the update removed it, moves as a dismissal hands it off.+ useLayoutEffect(() => {+ const overwrite = overwriteFocusRef.current;+ if (overwrite == null) {+ return;}- }, [toasts, getFocusable]);+ overwriteFocusRef.current = null;+ handOffFocus(overwrite.note, overwrite.id);+ }, [toasts, handOffFocus]);const findByUniqueID = useCallback((uid: string) => {return toastsRef.current.find(t => t.options.uniqueID === uid);@@ -830,12 +915,13 @@ export function ToastViewport({<LayerContentBoundary>{visibleToasts.map(entry => (<ToastRow- key={entry.id}+ key={entry.rowKey ?? entry.id}entry={entry}isExiting={exitingIds.has(entry.id)}isReversed={isReversed}onExited={handleExited}onDismiss={removeToast}+ isLiveRegion={isModalHosted}/>))}</LayerContentBoundary>diff --git a/packages/core/src/Toast/types.ts b/packages/core/src/Toast/types.tsindex ba12b8d507..74623d349e 100644--- a/packages/core/src/Toast/types.ts+++ b/packages/core/src/Toast/types.ts@@ -38,9 +38,10 @@ export interface ToastOptions {/*** Replaces the content of this toast's card with your own layout.*- * Astryx keeps the card, live-region role and auto-hide behavior, then hands- * the renderer this toast's content, resolved settings and `dismiss`- * callback. The renderer owns every control inside its layout; call+ * 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+ * 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.*@@ -100,4 +101,9 @@ export interface ToastEntry {id: string;options: ToastOptions;createdAt: number;+ /**+ * The row's identity in the stack. A uniqueID overwrite keeps the replaced+ * toast's, so the card updates in place and focus inside it stays.+ */+ rowKey?: string;}