Skip to content

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

TypeScript

fix(AlertDialog): keep actions readable on narrow surfaces (#5343)

rubyycheung955ecef1274c
diff --git a/.changeset/alert-dialog-responsive-actions.md b/.changeset/alert-dialog-responsive-actions.md
new file mode 100644
index 0000000000..0f4b678d7c
--- /dev/null
+++ b/.changeset/alert-dialog-responsive-actions.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] AlertDialog lets Dialog preserve and clamp its preferred width, lets whole actions move to another row when needed, and stacks full-width destructive and Cancel actions at 640px and below while preserving standard single-line Button sizing and labels regardless of pointer type.
+
+@rubyycheung
diff --git a/apps/storybook/stories/AlertDialog.stories.tsx b/apps/storybook/stories/AlertDialog.stories.tsx
index 84bf86904f..5d7665f3d6 100644
--- a/apps/storybook/stories/AlertDialog.stories.tsx
+++ b/apps/storybook/stories/AlertDialog.stories.tsx
@@ -86,32 +86,46 @@ export const Async: Story = {
};
/**
- * Non-destructive confirmation with a primary action button.
+ * Wide reference state. In a wide viewport, Dialog preserves AlertDialog's
+ * preferred 400px surface and AlertDialog renders a horizontal action row.
*/
-export const Informational: Story = {
- render: () => {
- const [isOpen, setIsOpen] = useState(false);
- return (
- <>
- <Button
- label="Show notice"
- variant="secondary"
- onClick={() => setIsOpen(true)}
- />
- <AlertDialog
- isOpen={isOpen}
- onOpenChange={setIsOpen}
- title="Session expired"
- description="Your session has expired. You will be redirected to the login page."
- actionLabel="Sign in"
- actionVariant="primary"
- onAction={() => setIsOpen(false)}
- />
- </>
- );
+export const DesktopFinePointer: Story = {
+ args: {
+ isOpen: true,
+ title: 'Delete item?',
+ description:
+ 'This action cannot be undone. The item and all its data will be permanently removed.',
+ actionLabel: 'Delete',
+ onOpenChange: () => {},
+ onAction: () => {},
},
};
+/**
+ * Narrow reference state. Use a <=640px viewport to see Dialog's width clamp
+ * with AlertDialog's destructive-above-Cancel stacked action order.
+ */
+export const NarrowFinePointer: Story = {
+ args: {
+ isOpen: true,
+ title: 'Permanently delete this workspace?',
+ description:
+ 'Everyone will lose access to its dashboards, saved queries, and sharing links. This cannot be undone.',
+ cancelLabel: 'Keep this workspace',
+ actionLabel: 'Permanently delete workspace',
+ onOpenChange: () => {},
+ onAction: () => {},
+ },
+};
+
+/**
+ * Mobile reference state. Use a <=640px mobile viewport to verify the same
+ * stacked action order; this story does not emulate pointer or hover capability.
+ */
+export const MobileTouch: Story = {
+ args: NarrowFinePointer.args,
+};
+
/**
* Imperative API — no state management needed.
*/
diff --git a/packages/core/src/AlertDialog/AlertDialog.doc.mjs b/packages/core/src/AlertDialog/AlertDialog.doc.mjs
index 67fd1488ed..ed67da8add 100644
--- a/packages/core/src/AlertDialog/AlertDialog.doc.mjs
+++ b/packages/core/src/AlertDialog/AlertDialog.doc.mjs
@@ -21,21 +21,75 @@ 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\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.',
+ '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\nAlertDialog passes its requested width through to Dialog, which clamps the surface to the container and dynamic viewport with token gutters. Generic Dialog footers should wrap, but Dialog does not own action semantics or order; consumer composition controls that. AlertDialog owns its confirmation semantics: above 640px, actions render horizontally and may move onto another row; at 640px and below, the destructive action appears above Cancel and both buttons fill the footer width. Button labels retain their standard single-line behavior. The breakpoint follows available width, not pointer or hover capability. The body scrolls when block space is constrained.\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.'},
+ {
+ 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 as the least-destructive focus target. On narrow screens the destructive action is visually and structurally above Cancel, but Cancel still receives initial focus.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use concise, specific action labels. Above 640px, complete buttons may move onto another row; at 640px and below, the destructive action appears above Cancel and both buttons fill the footer width.',
+ },
+ {
+ 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.'},
+ {
+ 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
@@ -48,11 +102,13 @@ export const docs = {
isInline: true,
onOpenChange: undefined,
title: 'Delete item?',
- description: 'This action cannot be undone. The item and all its data will be permanently removed.',
+ description:
+ 'This action cannot be undone. The item and all its data will be permanently removed.',
actionLabel: 'Delete',
},
},
- description: 'A modal dialog that asks the user to confirm a destructive action.',
+ description:
+ 'A modal dialog that asks the user to confirm a destructive action.',
props: [
{
name: 'isOpen',
@@ -111,38 +167,66 @@ export const docs = {
name: 'width',
type: 'number | string',
default: '400',
- description: 'Dialog width.',
+ description:
+ 'Requested dialog width. Dialog preserves this preferred width and clamps it to the container and dynamic viewport with token gutters.',
},
{
name: 'isInline',
type: 'boolean',
default: 'false',
- 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".',
+ 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: [
- {name: 'useImperativeAlertDialog'},
- ],
+ components: [{name: 'useImperativeAlertDialog'}],
theming: {
- targets: [
- {className: 'astryx-alert-dialog'},
- ],
+ targets: [{className: 'astryx-alert-dialog'}],
},
};
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
- description: 'Confirms destructive/irreversible action before it happens (delete, revoke access, discard unsaved changes).',
+ 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). 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.',
+ '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. Dialog preserves requested width + clamps it to container/dynamic viewport gutters. Generic Dialog footers wrap while consumers own action order. AlertDialog owns confirmation action layout: >640px horizontal buttons may move to another row; <=640px puts the destructive action above Cancel and makes both buttons full width regardless of pointer/hover capability. Button labels remain single-line. Body scrolls when height constrained. 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.'},
+ {
+ 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 as initial focus: least destructive choice is preselected even when narrow visual/DOM order places it after the destructive action.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use concise action labels; >640px complete buttons may move to another row, and <=640px puts the destructive action above Cancel with both buttons full width regardless of pointer type.',
+ },
+ {
+ 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.tsx
index a59bfe6e6c..1ef12a27a2 100644
--- a/packages/core/src/AlertDialog/AlertDialog.test.tsx
+++ b/packages/core/src/AlertDialog/AlertDialog.test.tsx
@@ -9,12 +9,65 @@
* SYNC: When AlertDialog.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
-import {render, screen, fireEvent, waitFor} from '@testing-library/react';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ within,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {AlertDialog} from './AlertDialog';
import {useImperativeAlertDialog} from './useImperativeAlertDialog';
+function stubAlertDialogMedia({
+ smallScreen,
+ coarsePointer,
+ noHover,
+ reduceMotion = false,
+}: {
+ smallScreen: boolean;
+ coarsePointer: boolean;
+ noHover: boolean;
+ reduceMotion?: boolean;
+}): void {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => {
+ let matches = false;
+ if (query.includes('max-width: 640px')) {
+ matches = smallScreen;
+ } else if (query.includes('pointer: coarse')) {
+ matches = coarsePointer;
+ } else if (query.includes('pointer: fine')) {
+ matches = !coarsePointer;
+ } else if (query.includes('hover: none')) {
+ matches = noHover;
+ } else if (query.includes('hover: hover')) {
+ matches = !noHover;
+ } else if (query.includes('prefers-reduced-motion: reduce')) {
+ matches = reduceMotion;
+ } else if (query.includes('prefers-reduced-motion: no-preference')) {
+ matches = !reduceMotion;
+ } else if (query.includes('prefers-reduced-motion')) {
+ matches = reduceMotion;
+ }
+
+ return {
+ matches,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ };
+ }),
+ );
+}
+
beforeEach(() => {
HTMLDialogElement.prototype.showModal = vi.fn(function (
this: HTMLDialogElement,
@@ -26,6 +79,10 @@ beforeEach(() => {
});
});
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
describe('AlertDialog', () => {
const defaultProps = {
isOpen: true,
@@ -109,6 +166,158 @@ describe('AlertDialog', () => {
expect(screen.getByRole('alertdialog')).toBeInTheDocument();
});
+ describe('responsive actions', () => {
+ const longCancelLabel = 'Keep this workspace and all of its dashboards';
+ const longActionLabel =
+ 'Permanently delete this workspace and all dashboards';
+
+ it('preserves the preferred width and horizontal order above the small breakpoint', () => {
+ stubAlertDialogMedia({
+ smallScreen: false,
+ coarsePointer: false,
+ noHover: false,
+ });
+ render(<AlertDialog {...defaultProps} />);
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 640px)');
+ expect(window.matchMedia).not.toHaveBeenCalledWith('(pointer: coarse)');
+ expect(window.matchMedia).not.toHaveBeenCalledWith('(hover: none)');
+ const dialog = screen.getByRole('alertdialog');
+ const buttons = within(dialog).getAllByRole('button');
+ const footerStack = buttons[0].parentElement!;
+ expect(dialog.getAttribute('style')).toContain('--x-width: 400px');
+ expect(dialog.getAttribute('style')).toContain(
+ '--x-maxWidth: min(100%, calc(100dvw - var(--spacing-4) - var(--spacing-4)))',
+ );
+ expect(buttons.map(button => button.textContent)).toEqual([
+ 'Cancel',
+ 'Delete',
+ ]);
+ expect(getComputedStyle(footerStack).flexWrap).toBe('wrap');
+ });
+
+ it('keeps long action buttons within the wide horizontal footer without changing Button sizing', () => {
+ stubAlertDialogMedia({
+ smallScreen: false,
+ coarsePointer: false,
+ noHover: false,
+ });
+ render(
+ <AlertDialog
+ {...defaultProps}
+ cancelLabel={longCancelLabel}
+ actionLabel={longActionLabel}
+ />,
+ );
+
+ const dialog = screen.getByRole('alertdialog');
+ const buttons = within(dialog).getAllByRole('button');
+ const footerStack = buttons[0].parentElement!;
+ expect(buttons.map(button => button.textContent)).toEqual([
+ longCancelLabel,
+ longActionLabel,
+ ]);
+ expect(getComputedStyle(footerStack).flexWrap).toBe('wrap');
+ for (const button of buttons) {
+ const computed = getComputedStyle(button);
+ expect(computed.whiteSpace).toBe('nowrap');
+ expect(computed.height).toBe('var(--size-element-md)');
+ expect(computed.maxWidth).toBe('100%');
+ }
+ });
+
+ it('stacks long destructive action labels above cancel on a narrow fine-pointer screen', () => {
+ stubAlertDialogMedia({
+ smallScreen: true,
+ coarsePointer: false,
+ noHover: false,
+ });
+ render(
+ <AlertDialog
+ {...defaultProps}
+ cancelLabel={longCancelLabel}
+ actionLabel={longActionLabel}
+ />,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 640px)');
+ expect(window.matchMedia).not.toHaveBeenCalledWith('(pointer: coarse)');
+ expect(window.matchMedia).not.toHaveBeenCalledWith('(hover: none)');
+ const dialog = screen.getByRole('alertdialog');
+ const buttons = within(dialog).getAllByRole('button');
+ const footerStack = buttons[0].parentElement!;
+ expect(dialog.getAttribute('style')).toContain('--x-width: 400px');
+ expect(buttons.map(button => button.textContent)).toEqual([
+ longActionLabel,
+ longCancelLabel,
+ ]);
+ expect(getComputedStyle(footerStack).flexDirection).toBe('column');
+ for (const button of buttons) {
+ const computed = getComputedStyle(button);
+ expect(computed.whiteSpace).toBe('nowrap');
+ expect(computed.width).toBe('100%');
+ expect(computed.maxWidth).toBe('100%');
+ }
+ });
+
+ it('uses the same stacked layout on a mobile touch screen', () => {
+ stubAlertDialogMedia({
+ smallScreen: true,
+ coarsePointer: true,
+ noHover: true,
+ });
+ render(
+ <AlertDialog
+ {...defaultProps}
+ cancelLabel="Keep this workspace"
+ actionLabel="Permanently delete workspace"
+ />,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 640px)');
+ expect(window.matchMedia).not.toHaveBeenCalledWith('(pointer: coarse)');
+ expect(window.matchMedia).not.toHaveBeenCalledWith('(hover: none)');
+ const dialog = screen.getByRole('alertdialog');
+ const buttons = within(dialog).getAllByRole('button');
+ expect(dialog.getAttribute('style')).toContain('--x-width: 400px');
+ expect(buttons.map(button => button.textContent)).toEqual([
+ 'Permanently delete workspace',
+ 'Keep this workspace',
+ ]);
+ expect(getComputedStyle(buttons[0]).whiteSpace).toBe('nowrap');
+ expect(getComputedStyle(buttons[0]).width).toBe('100%');
+ expect(getComputedStyle(buttons[1]).whiteSpace).toBe('nowrap');
+ expect(getComputedStyle(buttons[1]).width).toBe('100%');
+ });
+
+ it('keeps narrow visual, DOM, and tab order aligned while autofocus stays on cancel', async () => {
+ const user = userEvent.setup();
+ stubAlertDialogMedia({
+ smallScreen: true,
+ coarsePointer: false,
+ noHover: false,
+ });
+ render(
+ <AlertDialog
+ {...defaultProps}
+ cancelLabel={longCancelLabel}
+ actionLabel={longActionLabel}
+ />,
+ );
+
+ const action = screen.getByRole('button', {name: longActionLabel});
+ const cancel = screen.getByRole('button', {name: longCancelLabel});
+ expect(
+ action.compareDocumentPosition(cancel) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(cancel).toHaveAttribute('data-autofocus');
+ action.focus();
+ await user.tab();
+ expect(cancel).toHaveFocus();
+ });
+ });
+
it('defaults cancel label to Cancel', () => {
render(<AlertDialog {...defaultProps} />);
expect(screen.getByText('Cancel')).toBeInTheDocument();
diff --git a/packages/core/src/AlertDialog/AlertDialog.tsx b/packages/core/src/AlertDialog/AlertDialog.tsx
index 528b0bf58a..838e3b6fb1 100644
--- a/packages/core/src/AlertDialog/AlertDialog.tsx
+++ b/packages/core/src/AlertDialog/AlertDialog.tsx
@@ -4,7 +4,7 @@
/**
* @file AlertDialog.tsx
- * @input Uses React, Dialog, Layout, Heading, Text, Button
+ * @input Uses React, StyleX, Dialog, Layout, Heading, Text, Button
* @output Exports AlertDialog component, AlertDialogProps type
* @position Core implementation; consumed by index.ts, tested by AlertDialog.test.tsx
*
@@ -17,11 +17,12 @@
*/
import React, {useId, useCallback} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {Dialog} from '../Dialog';
import {Layout} from '../Layout/Layout';
import {LayoutContent} from '../Layout/LayoutContent';
import {LayoutFooter} from '../Layout/LayoutFooter';
-import {HStack} from '../Stack';
+import {Stack} from '../Stack';
import {Heading} from '../Heading/Heading';
import {Text} from '../Text/Text';
import {Button, type ButtonVariant} from '../Button';
@@ -29,6 +30,19 @@ import type {BaseProps} from '../BaseProps';
import {mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
+import {useMediaQuery} from '../hooks';
+
+const SMALL_SCREEN_QUERY = '(max-width: 640px)';
+
+const styles = stylex.create({
+ action: {
+ maxWidth: '100%',
+ minWidth: 0,
+ },
+ stackedAction: {
+ width: '100%',
+ },
+});
export interface AlertDialogProps extends BaseProps<HTMLDialogElement> {
ref?: React.Ref<HTMLDialogElement>;
@@ -147,11 +161,44 @@ export function AlertDialog({
const cancelLabel = cancelLabelFromProps ?? t('@astryx.alertDialog.cancel');
const titleId = useId();
const descriptionId = useId();
+ // Width stays delegated to Dialog: this query exists only so AlertDialog can
+ // keep narrow visual, DOM, and tab order aligned for its destructive/cancel
+ // semantics without coupling action order to pointer or hover capability.
+ const isSmallScreen = useMediaQuery(SMALL_SCREEN_QUERY);
const handleCancel = useCallback(() => {
onOpenChange(false);
}, [onOpenChange]);
+ const buttonActionStyle = [
+ styles.action,
+ isSmallScreen && styles.stackedAction,
+ ];
+ const cancelButton = (
+ <Button
+ key="cancel"
+ variant="ghost"
+ label={cancelLabel}
+ onClick={handleCancel}
+ xstyle={buttonActionStyle}
+ // Dialog focuses [data-autofocus] itself after showModal(), because
+ // React's autoFocus runs during commit while the dialog is invisible.
+ // Cancel is least destructive, so it remains the autofocus target even
+ // when small-screen visual order places the destructive action above it.
+ data-autofocus
+ />
+ );
+ const actionButton = (
+ <Button
+ key="action"
+ variant={actionVariant}
+ label={actionLabel}
+ onClick={onAction}
+ isLoading={isActionLoading}
+ xstyle={buttonActionStyle}
+ />
+ );
+
return (
<Dialog
{...rest}
@@ -185,24 +232,19 @@ export function AlertDialog({
}
footer={
<LayoutFooter>
- <HStack gap={2} hAlign="end">
- <Button
- 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
- />
- <Button
- variant={actionVariant}
- label={actionLabel}
- onClick={onAction}
- isLoading={isActionLoading}
- />
- </HStack>
+ {/* Generic Dialog footers should wrap, but their consumers own
+ action semantics and order. AlertDialog keeps this
+ destructive-above-Cancel narrow order because confirmation
+ actions have component-specific meaning here. */}
+ <Stack
+ direction={isSmallScreen ? 'vertical' : 'horizontal'}
+ gap={2}
+ hAlign={isSmallScreen ? 'stretch' : 'end'}
+ wrap={isSmallScreen ? 'nowrap' : 'wrap'}>
+ {isSmallScreen
+ ? [actionButton, cancelButton]
+ : [cancelButton, actionButton]}
+ </Stack>
</LayoutFooter>
}
/>