Skip to content

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

TypeScript

fix(Toast): focus entering by Tab or a click is remembered, so dismissing the last toast returns it (#9039)

Cindy Zhangcebf4a9527e8
diff --git a/.changeset/toast-tab-focus-return.md b/.changeset/toast-tab-focus-return.md
new file mode 100644
index 0000000000..56c7baaed1
--- /dev/null
+++ b/.changeset/toast-tab-focus-return.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Toast: dismissing the last toast after reaching it with Tab or a click returns focus to where it was before, instead of dropping it to the page.
+
+@cixzhang
diff --git a/packages/core/src/Toast/Toast.spec.md b/packages/core/src/Toast/Toast.spec.md
index 6f50de6bc4..231a87bb68 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 implementation gaps, listed under Current-state impact. |
+| Compatibility/readiness | Records shipped behavior; no public change. Nineteen 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`. |
@@ -108,9 +108,6 @@ Consumer migration instructions belong in consumer docs and release notes.
- **A hidden toast's overwrite is announced unseen.** Overwriting, through
`uniqueID`, a toast hidden by the cap announces the new text while it is not
shown, and nothing is announced when it surfaces.
-- **Focus can drop after Tab entry.** Dismissing the last toast after reaching
- it with Tab rather than F6 leaves no remembered element, so focus lands on
- the page body.
- **Custom content without a control has only the swipe.** A `renderContent`
toast that renders no control can be dismissed only by a swipe, and an error
toast does not auto-hide. `spec:AST-094` FR39 keeps every drag action
@@ -194,7 +191,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| 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 |
| 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 |
+| 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 |
| 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, 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 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 |
diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsx
index daa7b5c120..39a62e2a7b 100644
--- a/packages/core/src/Toast/ToastViewport.test.tsx
+++ b/packages/core/src/Toast/ToastViewport.test.tsx
@@ -31,6 +31,7 @@ import {
within,
} from '@testing-library/react';
import React, {useRef} from 'react';
+import {createPortal} from 'react-dom';
import {readFileSync} from 'node:fs';
import {type AnnounceFn, __resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {Button} from '../Button';
@@ -842,6 +843,84 @@ describe('ToastViewport keyboard reach + focus', () => {
// No toasts left — focus returns to the element focused before F6.
expect(document.activeElement).toBe(trigger);
});
+
+ it('restores focus after a toast reached with Tab rather than F6 is dismissed', () => {
+ renderViewport(
+ <ShowToastButton options={INFO_A} triggerLabel="Trigger A" />,
+ );
+ const trigger = screen.getByText('Trigger A');
+ trigger.focus();
+ act(() => {
+ fireEvent.click(trigger);
+ });
+ const dismiss = screen.getByRole('button', {name: 'Dismiss notification'});
+ // Tab (or a click) moves focus straight to the toast's control.
+ act(() => {
+ dismiss.focus();
+ });
+ const toastId = document
+ .querySelector('[data-toast-id]')!
+ .getAttribute('data-toast-id')!;
+
+ act(() => {
+ fireEvent.click(dismiss);
+ });
+ act(() => {
+ completeExit(toastId);
+ });
+
+ expect(document.activeElement).toBe(trigger);
+ });
+
+ it('keeps the return target while focus visits portaled toast content', () => {
+ renderViewport(
+ <ShowToastButton
+ options={{
+ body: 'With a portal',
+ isAutoHide: false,
+ renderContent: ({body, dismiss}) => (
+ <div>
+ {body}
+ {createPortal(
+ <button type="button">Portaled</button>,
+ document.body,
+ )}
+ <Button label="Close" onClick={dismiss} />
+ </div>
+ ),
+ }}
+ triggerLabel="Trigger P"
+ />,
+ );
+ const trigger = screen.getByText('Trigger P');
+ trigger.focus();
+ act(() => {
+ fireEvent.click(trigger);
+ });
+ act(() => {
+ fireEvent.keyDown(document, {key: 'F6'});
+ });
+ // Focus visits the toast's portaled control, then comes back.
+ act(() => {
+ screen.getByRole('button', {name: 'Portaled'}).focus();
+ });
+ const close = screen.getByRole('button', {name: 'Close'});
+ act(() => {
+ close.focus();
+ });
+ const toastId = document
+ .querySelector('[data-toast-id]')!
+ .getAttribute('data-toast-id')!;
+
+ act(() => {
+ fireEvent.click(close);
+ });
+ act(() => {
+ completeExit(toastId);
+ });
+
+ expect(document.activeElement).toBe(trigger);
+ });
});
describe('Toast blur timer pause', () => {
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index 58d31223d5..87363af02a 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -342,10 +342,13 @@ export function ToastViewport({
// Toasts dispatched since the last commit, by id: a dismiss() called
// before the toast first renders still finds it (and its onHide).
const pendingEntriesRef = useRef<Map<string, ToastEntry>>(new Map());
- // The element that was focused before the user jumped into the viewport
- // (via F6). Used to restore focus once all toasts are dismissed so focus
- // never falls to <body>.
+ // The element that was focused before focus entered the viewport, by F6,
+ // Tab or a click. Used to restore focus once all toasts are dismissed so
+ // focus never falls to <body> (FR10).
const prevFocusRef = useRef<HTMLElement | null>(null);
+ // The element focus last reached inside the viewport's React tree,
+ // portaled toast content included.
+ const lastFocusedWithinRef = useRef<EventTarget | null>(null);
// When a toast is dismissed while focus lives inside it, we need to move
// focus to a sensible neighbor after that toast unmounts. This holds the
// id of the toast whose removal should trigger a focus handoff.
@@ -781,6 +784,21 @@ export function ToastViewport({
const viewport = (
<div
ref={viewportRef}
+ onFocus={event => {
+ // Focus entering from outside, however it came, is where a dismissal
+ // of the last toast returns it. React also delivers focus inside a
+ // toast's portaled content here, so focus coming back from the last
+ // element focused within is not an entry, though it sits outside
+ // this element.
+ const from = event.relatedTarget;
+ const fromWithin =
+ from === lastFocusedWithinRef.current ||
+ (from instanceof Node && event.currentTarget.contains(from));
+ lastFocusedWithinRef.current = event.target;
+ if (from instanceof HTMLElement && !fromWithin) {
+ prevFocusRef.current = from;
+ }
+ }}
role={hasToasts ? 'region' : undefined}
aria-label={hasToasts ? t('@astryx.toast.viewport') : undefined}
tabIndex={hasToasts ? -1 : undefined}