An open source design system that's fully customizable and agent ready
TypeScript
AlertDialog: night watch component audit, 79.4 C to 89.6 B (#4887)
Cindy Zhangec85ba0b6f5c
diff --git a/.changeset/alertdialog-inline-role.md b/.changeset/alertdialog-inline-role.mdnew file mode 100644index 0000000000..004fdd2975--- /dev/null+++ b/.changeset/alertdialog-inline-role.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] AlertDialog: the `isInline` preview path no longer renders `role="alertdialog"`. That role promises a modal interruption — focus trap, inert page, explicit dismissal — and the inline path is an always-present, non-modal preview with none of it. It now renders `role="group"`, keeping the title and description associated through `aria-labelledby`/`aria-describedby`.++@cixzhangdiff --git a/.changeset/alertdialog-pin-initial-focus.md b/.changeset/alertdialog-pin-initial-focus.mdnew file mode 100644index 0000000000..298e6b525e--- /dev/null+++ b/.changeset/alertdialog-pin-initial-focus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] AlertDialog: the cancel button now carries `data-autofocus`, so the documented "initial focus goes to the cancel button" behavior is pinned instead of depending on cancel happening to be the first focusable node in the footer. Docs now name and link the WAI-ARIA APG Alert Dialog pattern the component implements, and gain an anatomy section.++@cixzhangdiff --git a/apps/storybook/stories/AlertDialog.stories.tsx b/apps/storybook/stories/AlertDialog.stories.tsxindex b6f3449da1..84bf86904f 100644--- a/apps/storybook/stories/AlertDialog.stories.tsx+++ b/apps/storybook/stories/AlertDialog.stories.tsx@@ -137,3 +137,76 @@ export const Imperative: Story = {);},};++/**+ * A task-specific cancel label. Override `cancelLabel` when "Cancel" reads as+ * ambiguous next to the action, for example when both choices are verbs.+ */+export const CustomCancelLabel: Story = {+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <Button+ label="Discard draft"+ variant="secondary"+ onClick={() => setIsOpen(true)}+ />+ <AlertDialog+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ title="Discard this draft?"+ description="Your unsaved edits will be lost."+ cancelLabel="Keep editing"+ actionLabel="Discard"+ onAction={() => setIsOpen(false)}+ />+ </>+ );+ },+};++/**+ * Long title and description. The dialog wraps rather than clipping, and the+ * footer buttons stay on screen; the body scrolls when the viewport is short.+ */+export const LongContent: Story = {+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <Button+ label="Delete workspace"+ variant="destructive"+ onClick={() => setIsOpen(true)}+ />+ <AlertDialog+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ title="Delete the entire Marketing Analytics workspace and everything inside it?"+ description="This removes 1,284 documents, 37 dashboards, every saved query, and all sharing links, for all 62 members of the workspace. Exports already scheduled will stop running. Anyone holding a link will get a 404 instead of the content. This cannot be undone, and support cannot restore it for you afterwards."+ actionLabel="Delete workspace"+ onAction={() => setIsOpen(false)}+ />+ </>+ );+ },+};++/**+ * The inline preview path (`isInline`). Renders the content in place without+ * `showModal()`, for documentation previews and showcases. It is not a modal:+ * it does not trap focus, block the page, or respond to Escape — so it exposes+ * `role="group"` rather than `role="alertdialog"`.+ */+export const Inline: Story = {+ args: {+ isOpen: true,+ isInline: true,+ title: 'Delete item?',+ description: 'This action cannot be undone.',+ actionLabel: 'Delete',+ onOpenChange: () => {},+ onAction: () => {},+ },+};diff --git a/packages/core/src/AlertDialog/AlertDialog.doc.mjs b/packages/core/src/AlertDialog/AlertDialog.doc.mjsindex 406c89047f..67fd1488ed 100644--- a/packages/core/src/AlertDialog/AlertDialog.doc.mjs+++ b/packages/core/src/AlertDialog/AlertDialog.doc.mjs@@ -21,11 +21,21 @@ export const docs = {],usage: {description:- 'AlertDialog asks the user to confirm a destructive or irreversible action before it happens. Use it for things like deleting content, revoking access, or discarding unsaved changes.\n\nFor cases where you want to show an alert without managing open state, use the `useImperativeAlertDialog` hook: call `alert.show(options)` and render `alert.element` in your tree.',+ 'AlertDialog asks the user to confirm a destructive or irreversible action before it happens. Use it for things like deleting content, revoking access, or discarding unsaved changes.\n\nIt implements the WAI-ARIA APG [Alert Dialog pattern](https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/): `role="alertdialog"`, a title linked by `aria-labelledby`, a consequence description linked by `aria-describedby`, focus moved into the dialog on open and returned to the trigger on close, and no dismissal by clicking outside. Escape cancels.\n\nFor cases where you want to show an alert without managing open state, use the `useImperativeAlertDialog` hook: call `alert.show(options)` and render `alert.element` in your tree.',bestPractices: [{guidance: true, description: 'Make the action button label specific: "Delete project" is better than "OK" or "Confirm".'},{guidance: true, description: 'Describe what will happen in the description so the user knows the consequences before confirming.'},+ {guidance: true, description: 'Keep the cancel button first: it takes initial focus, so the least destructive choice is the one already selected when the dialog opens.'},{guidance: false, description: 'Use AlertDialog for non-destructive actions; use a standard Dialog instead.'},+ {guidance: false, description: 'Rely on color alone to signal danger; the action label itself should say what will happen.'},+ {guidance: false, description: 'Close the dialog from onAction before the work finishes; hold it open with isActionLoading and call onOpenChange(false) when the action settles.'},+ ],+ anatomy: [+ {name: 'Title', required: true, description: 'The question being asked. Renders as a level-2 heading and labels the dialog via aria-labelledby.'},+ {name: 'Description', required: true, description: 'What will happen if the user confirms. Linked to the dialog via aria-describedby.'},+ {name: 'Cancel button', required: true, description: 'Ghost button that dismisses without acting. Takes initial focus, and Escape does the same thing.'},+ {name: 'Action button', required: true, description: 'The confirming action. Destructive by default; shows a spinner while isActionLoading is set.'},+ {name: 'Backdrop', required: true, description: 'Overlay behind the dialog that blocks page interaction. Clicking it does not dismiss.'},],},// Intentionally a contained isInline preview, not playground.overlay: the@@ -107,7 +117,7 @@ export const docs = {name: 'isInline',type: 'boolean',default: 'false',- description: 'Renders alert dialog content inline without modal behavior. For documentation previews and showcases only.',+ description: 'Renders alert dialog content inline without modal behavior. For documentation previews and showcases only. Not being a modal, the inline path renders role="group" instead of role="alertdialog".',},],components: [@@ -125,11 +135,14 @@ export const docsDense = {description: 'Confirms destructive/irreversible action before it happens (delete, revoke access, discard unsaved changes).',usage: {description:- 'AlertDialog confirms destructive/irreversible action (delete, revoke access, discard changes). To show w/o managing open state, use useImperativeAlertDialog hook: call alert.show(options) + render alert.element in tree.',+ 'AlertDialog confirms destructive/irreversible action (delete, revoke access, discard changes). Implements WAI-ARIA APG Alert Dialog pattern (https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/): role="alertdialog", aria-labelledby title, aria-describedby description, focus into dialog on open + back to trigger on close, no outside-click dismissal, Escape cancels. To show w/o managing open state, use useImperativeAlertDialog hook: call alert.show(options) + render alert.element in tree.',bestPractices: [{guidance: true, description: 'Make action button label specific: "Delete project" > "OK"/"Confirm".'},{guidance: true, description: 'Describe consequences in description so user knows outcome before confirming.'},+ {guidance: true, description: 'Keep cancel first: it takes initial focus, so least destructive choice is preselected.'},{guidance: false, description: 'Use AlertDialog for non-destructive actions; use standard Dialog instead.'},+ {guidance: false, description: 'Rely on color alone for danger; the action label should say what happens.'},+ {guidance: false, description: 'Close from onAction before work finishes; hold open w/ isActionLoading, call onOpenChange(false) when it settles.'},],},};diff --git a/packages/core/src/AlertDialog/AlertDialog.test.tsx b/packages/core/src/AlertDialog/AlertDialog.test.tsxindex f74a4b7b8b..a59bfe6e6c 100644--- a/packages/core/src/AlertDialog/AlertDialog.test.tsx+++ b/packages/core/src/AlertDialog/AlertDialog.test.tsx@@ -10,8 +10,10 @@*/import {describe, it, expect, vi, beforeEach} from 'vitest';-import {render, screen, fireEvent} from '@testing-library/react';+import {render, screen, fireEvent, waitFor} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {AlertDialog} from './AlertDialog';+import {useImperativeAlertDialog} from './useImperativeAlertDialog';beforeEach(() => {HTMLDialogElement.prototype.showModal = vi.fn(function (@@ -111,4 +113,209 @@ describe('AlertDialog', () => {render(<AlertDialog {...defaultProps} />);expect(screen.getByText('Cancel')).toBeInTheDocument();});++ describe('keyboard', () => {+ it('calls onOpenChange(false) on Escape', async () => {+ const onOpenChange = vi.fn();+ render(<AlertDialog {...defaultProps} onOpenChange={onOpenChange} />);+ fireEvent.keyDown(screen.getByRole('alertdialog'), {key: 'Escape'});+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ });++ it('does not call onAction on Escape', () => {+ const onAction = vi.fn();+ render(<AlertDialog {...defaultProps} onAction={onAction} />);+ fireEvent.keyDown(screen.getByRole('alertdialog'), {key: 'Escape'});+ expect(onAction).not.toHaveBeenCalled();+ });++ it('activates cancel with Enter', async () => {+ const user = userEvent.setup();+ const onOpenChange = vi.fn();+ render(<AlertDialog {...defaultProps} onOpenChange={onOpenChange} />);+ screen.getByRole('button', {name: 'Cancel'}).focus();+ await user.keyboard('{Enter}');+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('activates the action button with Space', async () => {+ const user = userEvent.setup();+ const onAction = vi.fn();+ render(<AlertDialog {...defaultProps} onAction={onAction} />);+ screen.getByRole('button', {name: 'Delete'}).focus();+ await user.keyboard(' ');+ expect(onAction).toHaveBeenCalled();+ });++ it('reaches both buttons by Tab, cancel first', async () => {+ const user = userEvent.setup();+ render(<AlertDialog {...defaultProps} />);+ const cancel = screen.getByRole('button', {name: 'Cancel'});+ const action = screen.getByRole('button', {name: 'Delete'});+ cancel.focus();+ expect(cancel).toHaveFocus();+ await user.tab();+ expect(action).toHaveFocus();+ });+ });++ describe('focus', () => {+ it('marks cancel as the initial focus target', () => {+ render(<AlertDialog {...defaultProps} />);+ // Dialog focuses [data-autofocus] itself after showModal(), so the+ // contract this component owns is which element carries the attribute.+ expect(screen.getByRole('button', {name: 'Cancel'})).toHaveAttribute(+ 'data-autofocus',+ );+ expect(screen.getByRole('button', {name: 'Delete'})).not.toHaveAttribute(+ 'data-autofocus',+ );+ });++ it('keeps the initial focus target on the least destructive action', () => {+ render(<AlertDialog {...defaultProps} cancelLabel="Never mind" />);+ expect(screen.getByRole('button', {name: 'Never mind'})).toHaveAttribute(+ 'data-autofocus',+ );+ });++ it('returns focus to the trigger when it closes', async () => {+ const trigger = document.createElement('button');+ trigger.textContent = 'Open';+ document.body.appendChild(trigger);+ trigger.focus();++ const {rerender} = render(<AlertDialog {...defaultProps} />);+ rerender(<AlertDialog {...defaultProps} isOpen={false} />);++ await waitFor(() => expect(trigger).toHaveFocus());+ trigger.remove();+ });++ it('does not disable the cancel button while the action is loading', () => {+ render(<AlertDialog {...defaultProps} isActionLoading />);+ expect(screen.getByRole('button', {name: 'Cancel'})).toBeEnabled();+ });+ });++ describe('aria', () => {+ it('marks the action button busy while loading', () => {+ render(<AlertDialog {...defaultProps} isActionLoading />);+ expect(screen.getByRole('button', {name: /Delete/})).toHaveAttribute(+ 'aria-busy',+ 'true',+ );+ });++ it('is a modal alertdialog', () => {+ render(<AlertDialog {...defaultProps} />);+ expect(screen.getByRole('alertdialog')).toHaveAttribute(+ 'aria-modal',+ 'true',+ );+ });++ describe('the inline preview path', () => {+ it('does not claim the alertdialog role', () => {+ render(<AlertDialog {...defaultProps} isInline />);+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();+ });++ it('exposes a named group instead, with no aria-modal', () => {+ render(<AlertDialog {...defaultProps} isInline />);+ const group = screen.getByRole('group', {name: 'Delete item?'});+ expect(group).not.toHaveAttribute('aria-modal');+ const describedBy = group.getAttribute('aria-describedby');+ expect(describedBy).toBeTruthy();+ expect(document.getElementById(describedBy!)).toHaveTextContent(+ 'This action cannot be undone.',+ );+ });+ });+ });+});++describe('useImperativeAlertDialog', () => {+ const noop = () => {};++ function Harness({onAction = noop}: {onAction?: () => unknown}) {+ const alert = useImperativeAlertDialog();+ return (+ <>+ <button+ type="button"+ onClick={() =>+ alert.show({+ title: 'Delete item?',+ description: 'This action cannot be undone.',+ actionLabel: 'Delete',+ onAction,+ })+ }>+ Open+ </button>+ <button type="button" onClick={alert.hide}>+ Close it+ </button>+ <span data-testid="is-open">{String(alert.isOpen)}</span>+ {alert.element}+ </>+ );+ }++ it('renders nothing until show is called', () => {+ render(<Harness />);+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();+ expect(screen.getByTestId('is-open')).toHaveTextContent('false');+ });++ it('shows the dialog with the given options', async () => {+ const user = userEvent.setup();+ render(<Harness />);+ await user.click(screen.getByRole('button', {name: 'Open'}));+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();+ expect(screen.getByText('Delete item?')).toBeInTheDocument();+ expect(+ screen.getByText('This action cannot be undone.'),+ ).toBeInTheDocument();+ expect(screen.getByTestId('is-open')).toHaveTextContent('true');+ });++ it('hides on hide()', async () => {+ const user = userEvent.setup();+ render(<Harness />);+ await user.click(screen.getByRole('button', {name: 'Open'}));+ await user.click(screen.getByRole('button', {name: 'Close it'}));+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();+ expect(screen.getByTestId('is-open')).toHaveTextContent('false');+ });++ it('closes when the dialog cancels', async () => {+ const user = userEvent.setup();+ render(<Harness />);+ await user.click(screen.getByRole('button', {name: 'Open'}));+ await user.click(screen.getByRole('button', {name: 'Cancel'}));+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();+ expect(screen.getByTestId('is-open')).toHaveTextContent('false');+ });++ it('forwards onAction and leaves closing to the caller', async () => {+ const user = userEvent.setup();+ const onAction = vi.fn();+ render(<Harness onAction={onAction} />);+ await user.click(screen.getByRole('button', {name: 'Open'}));+ await user.click(screen.getByRole('button', {name: 'Delete'}));+ expect(onAction).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();+ });++ it('can be shown again after being hidden', async () => {+ const user = userEvent.setup();+ render(<Harness />);+ await user.click(screen.getByRole('button', {name: 'Open'}));+ await user.click(screen.getByRole('button', {name: 'Close it'}));+ await user.click(screen.getByRole('button', {name: 'Open'}));+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();+ expect(screen.getByTestId('is-open')).toHaveTextContent('true');+ });});diff --git a/packages/core/src/AlertDialog/AlertDialog.tsx b/packages/core/src/AlertDialog/AlertDialog.tsxindex 0632024ecd..528b0bf58a 100644--- a/packages/core/src/AlertDialog/AlertDialog.tsx+++ b/packages/core/src/AlertDialog/AlertDialog.tsx@@ -39,7 +39,8 @@ export interface AlertDialogProps extends BaseProps<HTMLDialogElement> {/*** Renders alert dialog content inline without modal behavior.- * For documentation previews and showcases only.+ * For documentation previews and showcases only. The inline path is not a+ * modal, so it renders `role="group"` rather than `role="alertdialog"`.* @default false*/isInline?: boolean;@@ -100,9 +101,16 @@ export interface AlertDialogProps extends BaseProps<HTMLDialogElement> {/*** A confirmation dialog for destructive or irreversible actions.*+ * Implements the WAI-ARIA APG Alert Dialog pattern:+ * https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/+ ** Uses `role="alertdialog"` and requires explicit user action to dismiss.* Cannot be dismissed by clicking outside. Escape key triggers cancel.- * Initial focus goes to the cancel button (least destructive action).+ * Initial focus goes to the cancel button (least destructive action), pinned+ * with `data-autofocus` so it survives any change to the footer's order.+ *+ * The `isInline` preview path is not modal, so it renders `role="group"`+ * instead — the alertdialog role would promise modality it does not have.** @example* ```@@ -153,7 +161,12 @@ export function AlertDialog({onOpenChange={onOpenChange}width={width}purpose="form"- role="alertdialog"+ // `alertdialog` is a modal role: it promises an interruption the user+ // has to deal with, a focus trap, and an inert page behind it. The+ // inline path renders a plain always-present div with none of that, so+ // the role would misdescribe it. `group` keeps the title and+ // description associated with a container without claiming a dialog.+ role={isInline ? 'group' : 'alertdialog'}aria-labelledby={titleId}aria-describedby={descriptionId}{...mergeProps(themeProps('alert-dialog'), {className, style})}@@ -177,6 +190,11 @@ export function AlertDialog({variant="ghost"label={cancelLabel}onClick={handleCancel}+ // Dialog focuses [data-autofocus] itself after showModal(),+ // because React's autoFocus runs during commit while the+ // dialog is still invisible. Cancel is the least destructive+ // choice, so it is the one that should be preselected.+ data-autofocus/><Buttonvariant={actionVariant}