An open source design system that's fully customizable and agent ready
TypeScript
fix(toast): F6 focus-to-viewport, focus handoff on dismiss, blur timer pause (overlays-7) (#3398)
Cindy Zhang1f4108cd74cf
diff --git a/.changeset/toast-keyboard-focus.md b/.changeset/toast-keyboard-focus.mdnew file mode 100644index 0000000000..f7029f1129--- /dev/null+++ b/.changeset/toast-keyboard-focus.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Toast: keyboard users can now reach and manage notifications. Pressing `F6` jumps focus into the toast viewport (the newest toast's first control, or the container). Dismissing a toast that holds focus now hands focus to a remaining toast — or restores the element focused before entering the viewport — instead of dropping to `<body>`. Auto-hide timers also pause while the window is blurred and resume on focus, so a toast no longer silently expires while you're in another window or tab (#3343)+@cixzhangdiff --git a/packages/core/src/Toast/Toast.tsx b/packages/core/src/Toast/Toast.tsxindex 774bd811c2..1d6c804a2b 100644--- a/packages/core/src/Toast/Toast.tsx+++ b/packages/core/src/Toast/Toast.tsx@@ -167,6 +167,20 @@ export function Toast({};}, [autoHideDuration, startTimer]);+ // 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.+ useEffect(() => {+ if (!isAutoHide) {+ return;+ }+ window.addEventListener('blur', pauseTimer);+ window.addEventListener('focus', resumeTimer);+ return () => {+ window.removeEventListener('blur', pauseTimer);+ window.removeEventListener('focus', resumeTimer);+ };+ }, [isAutoHide, pauseTimer, resumeTimer]);+const handleDismiss = useCallback(() => {onDismiss('manual');}, [onDismiss]);diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxnew file mode 100644index 0000000000..a65f233900--- /dev/null+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -0,0 +1,204 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToastViewport.test.tsx+ * @input Uses vitest, @testing-library/react, ToastViewport + useToast+ * @output Unit tests for toast keyboard reach and focus management+ * @position Testing; validates ToastViewport.tsx + Toast.tsx focus behavior+ *+ * SYNC: When ToastViewport.tsx or Toast.tsx focus handling changes, update these tests+ */++import {describe, it, expect, vi, beforeAll} from 'vitest';+import {render, screen, fireEvent, act} from '@testing-library/react';+import React from 'react';+import {ToastViewport} from './ToastViewport';+import {useToast} from './useToast';+import type {ToastOptions} from './types';++// Popover API is not implemented in jsdom.+beforeAll(() => {+ if (typeof HTMLElement.prototype.showPopover === 'undefined') {+ HTMLElement.prototype.showPopover = vi.fn();+ HTMLElement.prototype.hidePopover = vi.fn();+ }+});++// Module-level constant default props (avoids unstable-default-props lint).+const EMPTY_OPTIONS: ToastOptions = {body: 'placeholder'};++function ShowToastButton({+ options = EMPTY_OPTIONS,+ triggerLabel = 'Trigger',+}: {+ options?: ToastOptions;+ triggerLabel?: string;+}) {+ const toast = useToast();+ return (+ <button type="button" onClick={() => toast(options)}>+ {triggerLabel}+ </button>+ );+}++const INFO_A: ToastOptions = {body: 'Toast A'};+const INFO_B: ToastOptions = {body: 'Toast B'};+const AUTO_TOAST: ToastOptions = {body: 'Auto toast', autoHideDuration: 3000};++function renderViewport(children: React.ReactNode) {+ return render(<ToastViewport isTopLayer={false}>{children}</ToastViewport>);+}++// Fire the transition-end that ToastViewport listens for to unmount an+// exiting toast (jsdom does not run CSS transitions).+function completeExit(toastId: string) {+ const node = document.querySelector<HTMLElement>(+ `[data-toast-id="${toastId}"]`,+ );+ if (node) {+ fireEvent.transitionEnd(node, {propertyName: 'grid-template-rows'});+ }+}++describe('ToastViewport keyboard reach + focus', () => {+ it('F6 moves focus into the newest toast', () => {+ renderViewport(+ <ShowToastButton options={INFO_A} triggerLabel="Trigger A" />,+ );+ const trigger = screen.getByText('Trigger A');+ trigger.focus();+ act(() => {+ fireEvent.click(trigger);+ });++ expect(screen.getByText('Toast A')).toBeInTheDocument();+ expect(document.activeElement).toBe(trigger);++ act(() => {+ fireEvent.keyDown(document, {key: 'F6'});+ });++ // Focus lands on the dismiss button of the newest toast.+ const dismiss = screen.getByRole('button', {name: 'Dismiss notification'});+ expect(document.activeElement).toBe(dismiss);+ });++ it('dismissing a focused toast moves focus to a remaining toast, not body', () => {+ renderViewport(+ <>+ <ShowToastButton options={INFO_A} triggerLabel="Trigger A" />+ <ShowToastButton options={INFO_B} triggerLabel="Trigger B" />+ </>,+ );+ act(() => {+ fireEvent.click(screen.getByText('Trigger A'));+ });+ act(() => {+ fireEvent.click(screen.getByText('Trigger B'));+ });++ const dismissButtons = screen.getAllByRole('button', {+ name: 'Dismiss notification',+ });+ expect(dismissButtons).toHaveLength(2);++ // Focus the first toast's dismiss button, then dismiss it.+ const firstToast = document.querySelectorAll('[data-toast-id]')[0];+ const firstToastId = firstToast.getAttribute('data-toast-id')!;+ const firstDismiss = firstToast.querySelector<HTMLElement>(+ 'button[aria-label="Dismiss notification"]',+ )!;+ firstDismiss.focus();+ expect(document.activeElement).toBe(firstDismiss);++ act(() => {+ fireEvent.click(firstDismiss);+ });+ act(() => {+ completeExit(firstToastId);+ });++ // Focus must NOT drop to <body>; it moves to the remaining toast.+ expect(document.activeElement).not.toBe(document.body);+ expect(document.activeElement?.getAttribute('aria-label')).toBe(+ 'Dismiss notification',+ );+ });++ it('dismissing the last focused toast restores the previously-focused element', () => {+ renderViewport(+ <ShowToastButton options={INFO_A} triggerLabel="Trigger A" />,+ );+ const trigger = screen.getByText('Trigger A');+ trigger.focus();+ act(() => {+ fireEvent.click(trigger);+ });++ // F6 into the toast, remembering the trigger as the prior focus.+ act(() => {+ fireEvent.keyDown(document, {key: 'F6'});+ });+ const dismiss = screen.getByRole('button', {name: 'Dismiss notification'});+ expect(document.activeElement).toBe(dismiss);++ const toastId = document+ .querySelector('[data-toast-id]')!+ .getAttribute('data-toast-id')!;++ act(() => {+ fireEvent.click(dismiss);+ });+ act(() => {+ completeExit(toastId);+ });++ // No toasts left — focus returns to the element focused before F6.+ expect(document.activeElement).toBe(trigger);+ });+});++describe('Toast blur timer pause', () => {+ it('pauses the auto-hide timer while the window is blurred', () => {+ vi.useFakeTimers();+ try {+ renderViewport(+ <ShowToastButton options={AUTO_TOAST} triggerLabel="Trigger Auto" />,+ );+ act(() => {+ fireEvent.click(screen.getByText('Trigger Auto'));+ });+ expect(screen.getByText('Auto toast')).toBeInTheDocument();++ // Window loses focus — timer should pause.+ act(() => {+ window.dispatchEvent(new Event('blur'));+ });+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ // Still present because the timer was paused while blurred.+ expect(screen.getByText('Auto toast')).toBeInTheDocument();++ // Window regains focus — timer resumes and the toast dismisses.+ act(() => {+ window.dispatchEvent(new Event('focus'));+ });+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ const toastId = document+ .querySelector('[data-toast-id]')+ ?.getAttribute('data-toast-id');+ if (toastId) {+ act(() => {+ completeExit(toastId);+ });+ }+ expect(screen.queryByText('Auto toast')).not.toBeInTheDocument();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsxindex ba1eb6533a..6ddb25a015 100644--- a/packages/core/src/Toast/ToastViewport.tsx+++ b/packages/core/src/Toast/ToastViewport.tsx@@ -2,17 +2,21 @@'use client';-import {useCallback, useEffect, useMemo, useRef, useState} from 'react';+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import * as stylex from '@stylexjs/stylex';import {spacingVars, durationVars, easeVars} from '../theme/tokens.stylex';import {mergeProps} from '../utils';+import {INTERACTIVE_SELECTORS} from '../hooks/useClickableContainer';import {Toast} from './Toast';import {ToastContext, type ToastContextValue} from './ToastContext';-import type {- ToastEntry,- ToastPosition,- ToastDismissReason,-} from './types';+import type {ToastEntry, ToastPosition, ToastDismissReason} from './types';const styles = stylex.create({viewport: {@@ -108,6 +112,47 @@ export function ToastViewport({const toastsRef = useRef(toasts);toastsRef.current = toasts;+ // Show the popover on mount so it enters the top layer.+ const viewportRef = useRef<HTMLDivElement>(null);+ // 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>.+ const prevFocusRef = useRef<HTMLElement | 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.+ const focusHandoffIdRef = useRef<string | null>(null);+ // 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);++ // Collect a focusable control within a toast node, if any.+ // Reuses the canonical INTERACTIVE_SELECTORS list (native controls plus+ // role-based interactive elements) instead of a hand-rolled subset, then+ // narrows to the first candidate that can actually receive focus —+ // excluding elements opted out with `tabindex="-1"` and disabled controls.+ const getFocusable = useCallback(+ (container: HTMLElement | null): HTMLElement | null => {+ if (!container) {+ return null;+ }+ const candidates =+ container.querySelectorAll<HTMLElement>(INTERACTIVE_SELECTORS);+ for (const candidate of candidates) {+ if (+ candidate.getAttribute('tabindex') === '-1' ||+ candidate.hasAttribute('disabled') ||+ candidate.getAttribute('aria-disabled') === 'true'+ ) {+ continue;+ }+ return candidate;+ }+ return null;+ },+ [],+ );+const addToast = useCallback((entry: ToastEntry) => {setToasts(prev => {const {uniqueID, collisionBehavior = 'overwrite'} = entry.options;@@ -124,21 +169,44 @@ export function ToastViewport({});}, []);- const removeToast = useCallback(- (id: string, reason: ToastDismissReason) => {- const entry = toastsRef.current.find(t => t.id === id);- if (entry) {- entry.options.onHide?.(reason);+ const removeToast = useCallback((id: string, reason: ToastDismissReason) => {+ const entry = toastsRef.current.find(t => t.id === id);+ if (entry) {+ entry.options.onHide?.(reason);+ }+ // If focus currently lives inside the toast being dismissed, remember+ // that its removal must hand focus off to a neighbor (or the element+ // 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;+ if (+ dismissedNode &&+ active instanceof Node &&+ dismissedNode.contains(active)+ ) {+ focusHandoffIdRef.current = id;+ // Pick the neighbor to receive focus while the DOM is still intact:+ // prefer the next toast, then the previous, else restore.+ const remaining = toastsRef.current.filter(t => t.id !== id);+ if (remaining.length > 0) {+ const dismissedIndex = toastsRef.current.findIndex(t => t.id === id);+ const next =+ toastsRef.current[dismissedIndex + 1] ??+ toastsRef.current[dismissedIndex - 1];+ pendingFocusRef.current = next ? next.id : 'restore';+ } else {+ pendingFocusRef.current = 'restore';}- setExitingIds(prev => {- if (prev.has(id)) {- return prev;- }- return new Set(prev).add(id);- });- },- [],- );+ }+ setExitingIds(prev => {+ if (prev.has(id)) {+ return prev;+ }+ return new Set(prev).add(id);+ });+ }, []);const handleExited = useCallback((id: string) => {setExitingIds(prev => {@@ -152,6 +220,43 @@ export function ToastViewport({setToasts(prev => prev.filter(t => t.id !== id));}, []);+ // 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.+ useLayoutEffect(() => {+ const handoffId = focusHandoffIdRef.current;+ const target = pendingFocusRef.current;+ if (handoffId == null || target == null) {+ return;+ }+ // Wait until the dismissed toast is actually gone from the list.+ if (toasts.some(t => t.id === handoffId)) {+ return;+ }+ 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();+ }+ }, [toasts, getFocusable]);+const findByUniqueID = useCallback((uid: string) => {return toastsRef.current.find(t => t.options.uniqueID === uid);}, []);@@ -177,7 +282,6 @@ export function ToastViewport({}// Show the popover on mount so it enters the top layer- const viewportRef = useRef<HTMLDivElement>(null);useEffect(() => {if (!isTopLayer) {return;@@ -192,6 +296,45 @@ export function ToastViewport({}}, [isTopLayer]);+ // F6 jumps focus into the toast viewport — the standard "go to+ // notifications" affordance. Focus the first control in the newest toast,+ // or the viewport container if none. Toasts are non-modal, so this only+ // moves focus in; Shift+Tab / Escape let focus leave naturally.+ const hasToasts = toasts.length > 0;+ useEffect(() => {+ if (!hasToasts) {+ return;+ }+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key !== 'F6') {+ return;+ }+ const el = viewportRef.current;+ if (!el) {+ return;+ }+ // Already inside the viewport — nothing to do.+ const active = document.activeElement;+ if (active instanceof Node && el.contains(active)) {+ return;+ }+ e.preventDefault();+ // Remember where focus was so it can be restored on dismiss.+ if (active instanceof HTMLElement) {+ prevFocusRef.current = active;+ }+ // Newest toast is the last one rendered in the DOM.+ const toastNodes = el.querySelectorAll<HTMLElement>('[data-toast-id]');+ const newest = toastNodes[toastNodes.length - 1] ?? null;+ const focusable = getFocusable(newest) ?? newest ?? el;+ focusable.focus();+ };+ document.addEventListener('keydown', handleKeyDown);+ return () => {+ document.removeEventListener('keydown', handleKeyDown);+ };+ }, [hasToasts, getFocusable]);+const posStyle =position === 'topEnd'? styles.topEnd@@ -208,6 +351,8 @@ export function ToastViewport({ref={viewportRef}role="region"aria-label="Notifications"+ aria-modal={false}+ tabIndex={-1}// popover="manual" promotes to the top layer (above dialogs).// Omitted inside dialogs where the viewport is already in a top layer.popover={isTopLayer ? 'manual' : undefined}@@ -223,6 +368,7 @@ export function ToastViewport({return (<divkey={entry.id}+ data-toast-id={entry.id}{...stylex.props(styles.toastWrapper,isExiting && styles.toastWrapperExiting,diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 4b5b2d593a..6d1506a21c 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -44,7 +44,7 @@ export type {export {useImageMode} from './useImageMode';export type {ImageSampleRegion, UseImageModeOptions} from './useImageMode';-export {useClickableContainer} from './useClickableContainer';+export {useClickableContainer, INTERACTIVE_SELECTORS} from './useClickableContainer';export type {UseClickableContainerOptions,ClickableContainerResult,diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.tsindex ee3ec53a2c..4084d508a5 100644--- a/packages/core/src/hooks/useClickableContainer.ts+++ b/packages/core/src/hooks/useClickableContainer.ts@@ -5,18 +5,30 @@/*** @file useClickableContainer.ts* @input Container ref, interactive element ref, click/href handlers- * @output onClick and onMouseUp handlers for the container+ * @output onClick and onMouseUp handlers for the container; INTERACTIVE_SELECTORS list* @position Core hook for clickable containers that safely handle nested interactive elements** Solves the "nested interactive elements" problem: when a card is clickable* but contains buttons/links, clicking those should NOT trigger the card's action.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts (export)*/import {useCallback, useEffect, type RefObject, type MouseEvent} from 'react';-// Interactive element selectors — clicks on these (or their descendants)-// should NOT bubble to the container's click handler.-const INTERACTIVE_SELECTORS = [+/**+ * Canonical list of interactive element selectors — native controls plus+ * role-based interactive elements. Clicks on these (or their descendants)+ * should NOT bubble to a clickable container's click handler.+ *+ * Exported so other focus/interaction utilities can share one comprehensive+ * definition of "interactive target" rather than hand-rolling divergent lists.+ * Note: this list is about "don't bubble clicks", not focus-eligibility —+ * consumers that need focusable elements must additionally exclude+ * unfocusable/disabled targets (e.g. `[tabindex="-1"]`, `:disabled`).+ */+export const INTERACTIVE_SELECTORS = ['button','a','input',