An open source design system that's fully customizable and agent ready
TypeScript
XDSDialog (#99)
Andrey Goder95d8c53ccbf3
diff --git a/apps/storybook/stories/Dialog.stories.tsx b/apps/storybook/stories/Dialog.stories.tsxnew file mode 100644index 0000000000..77cb6b5676--- /dev/null+++ b/apps/storybook/stories/Dialog.stories.tsx@@ -0,0 +1,574 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSDialog} from '@xds/core/Dialog';+import {+ XDSLayout,+ XDSLayoutHeader,+ XDSLayoutContent,+ XDSLayoutFooter,+ XDSHStack,+} from '@xds/core/Layout';+import {XDSButton} from '@xds/core/Button';+import {XDSHeading, XDSText} from '@xds/core/Text';++const meta: Meta<typeof XDSDialog> = {+ title: 'Core/XDSDialog',+ component: XDSDialog,+ tags: ['autodocs'],+ argTypes: {+ isShown: {+ control: 'boolean',+ description: 'Whether the dialog is shown',+ },+ width: {+ control: 'number',+ description: 'Width of the dialog (default: 400)',+ },+ maxHeight: {+ control: 'text',+ description: 'Maximum height of the dialog (default: 75vh)',+ },+ variant: {+ control: 'select',+ options: ['standard', 'fullscreen'],+ description: 'Dialog variant',+ },+ purpose: {+ control: 'select',+ options: ['required', 'form', 'info'],+ description: 'Dismissal behavior configuration',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSDialog>;++/**+ * Basic modal example with XDSLayout+ */+function BasicModalExample() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton+ label="Open Modal"+ variant="primary"+ onClick={() => setIsShown(true)}+ />+ <XDSDialog isShown={isShown} onHide={() => setIsShown(false)}>+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Modal Title</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ This is a modal using the native <dialog> element with+ XDSLayout for structured content. Click outside or press Escape+ to close.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack gap="space2" hAlign="end">+ <XDSButton+ label="Cancel"+ variant="secondary"+ onClick={() => setIsShown(false)}+ />+ <XDSButton+ label="Confirm"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const Default: Story = {+ render: () => <BasicModalExample />,+};++/**+ * Custom width example+ */+function WideModalExample() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton+ label="Open Wide Modal (600px)"+ variant="secondary"+ onClick={() => setIsShown(true)}+ />+ <XDSDialog isShown={isShown} onHide={() => setIsShown(false)} width={600}>+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Wide Modal</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ This modal has a custom width of 600px.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack hAlign="end">+ <XDSButton+ label="Close"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const CustomWidth: Story = {+ render: () => <WideModalExample />,+};++/**+ * Fullscreen variant+ */+function FullscreenModalExample() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton+ label="Open Fullscreen Modal"+ variant="secondary"+ onClick={() => setIsShown(true)}+ />+ <XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ variant="fullscreen">+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Fullscreen Modal</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ This modal takes up the entire viewport. The width, maxHeight,+ and position props are ignored in fullscreen mode.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack hAlign="end">+ <XDSButton+ label="Close"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const Fullscreen: Story = {+ render: () => <FullscreenModalExample />,+};++/**+ * Purpose: required - cannot be dismissed+ */+function RequiredModalExample() {+ const [isShown, setIsShown] = useState(false);+ const [accepted, setAccepted] = useState(false);++ const handleAccept = () => {+ setAccepted(true);+ setIsShown(false);+ };++ return (+ <>+ <XDSButton+ label="Open Required Modal"+ variant="destructive"+ onClick={() => setIsShown(true)}+ />+ {accepted && (+ <XDSText type="body" color="primary" xstyle={{marginTop: 12}}>+ ✓ Terms accepted+ </XDSText>+ )}+ <XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ purpose="required">+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Accept Terms</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ This is a required modal. You cannot dismiss it by clicking+ outside or pressing Escape. You must complete the action.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack hAlign="end">+ <XDSButton+ label="I Accept"+ variant="primary"+ onClick={handleAccept}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const PurposeRequired: Story = {+ render: () => <RequiredModalExample />,+};++/**+ * Purpose: form - prevents backdrop click+ */+function FormModalExample() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton+ label="Open Form Modal"+ variant="secondary"+ onClick={() => setIsShown(true)}+ />+ <XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ purpose="form"+ width={500}>+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Edit Profile</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ This modal uses purpose="form". Clicking outside+ won't close it (to prevent accidental data loss), but you+ can still press Escape. Try clicking outside vs pressing Escape.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack gap="space2" hAlign="end">+ <XDSButton+ label="Cancel"+ variant="secondary"+ onClick={() => setIsShown(false)}+ />+ <XDSButton+ label="Save"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const PurposeForm: Story = {+ render: () => <FormModalExample />,+};++/**+ * Purpose: info - allows all dismissals+ */+function InfoModalExample() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton+ label="Open Info Modal"+ variant="secondary"+ onClick={() => setIsShown(true)}+ />+ <XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ purpose="info">+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Information</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ This modal uses purpose="info" (default). You can+ close it by clicking outside, pressing Escape, or using the+ button.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack hAlign="end">+ <XDSButton+ label="Got it"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const PurposeInfo: Story = {+ render: () => <InfoModalExample />,+};++/**+ * Custom position example+ */+function PositionedModalExample() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton+ label="Open Positioned Modal"+ variant="secondary"+ onClick={() => setIsShown(true)}+ />+ <XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ position={{top: 100, right: 20}}+ width={350}>+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Positioned Modal</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ This modal is positioned at top: 100px, right: 20px instead of+ being centered.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack hAlign="end">+ <XDSButton+ label="Close"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const CustomPosition: Story = {+ render: () => <PositionedModalExample />,+};++/**+ * Scrolling content example+ */+function ScrollingModalExample() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton+ label="Open Scrolling Modal"+ variant="secondary"+ onClick={() => setIsShown(true)}+ />+ <XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ maxHeight="50vh">+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Terms and Conditions</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <div+ style={{display: 'flex', flexDirection: 'column', gap: '12px'}}>+ {Array.from({length: 10}, (_, i) => (+ <XDSText type="body" key={i}>+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed+ do eiusmod tempor incididunt ut labore et dolore magna+ aliqua. Ut enim ad minim veniam, quis nostrud exercitation+ ullamco laboris nisi ut aliquip ex ea commodo consequat.+ </XDSText>+ ))}+ </div>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack gap="space2" hAlign="end">+ <XDSButton+ label="Decline"+ variant="secondary"+ onClick={() => setIsShown(false)}+ />+ <XDSButton+ label="Accept"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}++export const ScrollingContent: Story = {+ render: () => <ScrollingModalExample />,+};++/**+ * Confirmation dialog pattern+ */+function ConfirmationModalExample() {+ const [isShown, setIsShown] = useState(false);+ const [deleted, setDeleted] = useState(false);++ const handleDelete = () => {+ setDeleted(true);+ setIsShown(false);+ };++ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: '12px'}}>+ <XDSButton+ label="Delete Item"+ variant="destructive"+ onClick={() => setIsShown(true)}+ />+ {deleted && (+ <XDSText type="body" color="primary">+ ✓ Item deleted (demo)+ </XDSText>+ )}+ <XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ width={350}+ purpose="form">+ <XDSLayout+ header={+ <XDSLayoutHeader hasDivider>+ <XDSHeading level={2}>Confirm Delete</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSText type="body">+ Are you sure you want to delete this item? This action cannot be+ undone.+ </XDSText>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSHStack gap="space2" hAlign="end">+ <XDSButton+ label="Cancel"+ variant="secondary"+ onClick={() => setIsShown(false)}+ />+ <XDSButton+ label="Delete"+ variant="destructive"+ onClick={handleDelete}+ />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </div>+ );+}++export const ConfirmationDialog: Story = {+ render: () => <ConfirmationModalExample />,+};++/**+ * All purpose variants side by side+ */+export const AllPurposes: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '12px', flexWrap: 'wrap'}}>+ <RequiredModalExample />+ <FormModalExample />+ <InfoModalExample />+ </div>+ ),+};diff --git a/packages/core/src/Dialog/README.md b/packages/core/src/Dialog/README.mdnew file mode 100644index 0000000000..b5a289eb5d--- /dev/null+++ b/packages/core/src/Dialog/README.md@@ -0,0 +1,116 @@+# /packages/core/src/Dialog++XDSDialog component using the native `<dialog>` element for modal dialogs.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Native `<dialog>`**: Uses browser's built-in modal behavior+- **Automatic focus trap**: Focus is trapped within the dialog when open+- **Backdrop**: Native `::backdrop` pseudo-element with blur effect+- **Variants**: `standard` (configurable dimensions), `fullscreen` (full viewport)+- **Purpose-based dismissal**: `required`, `form`, `info` control exit behavior+- **Custom positioning**: Static position support via `position` prop+- **Accessible**: Proper ARIA attributes and keyboard navigation++## Usage++XDSDialog is designed to be used with XDSLayout as its child:++```tsx+import {XDSDialog} from '@xds/core/Dialog';+import {+ XDSLayout,+ XDSLayoutHeader,+ XDSLayoutContent,+ XDSLayoutFooter,+} from '@xds/core/Layout';+import {XDSButton} from '@xds/core/Button';+import {useState} from 'react';++function Example() {+ const [isShown, setIsShown] = useState(false);++ return (+ <>+ <XDSButton label="Open Dialog" onClick={() => setIsShown(true)} />++ <XDSDialog isShown={isShown} onHide={() => setIsShown(false)}>+ <XDSLayout+ header={<XDSLayoutHeader hasDivider>Title</XDSLayoutHeader>}+ content={<XDSLayoutContent>Content goes here</XDSLayoutContent>}+ footer={+ <XDSLayoutFooter hasDivider>+ <XDSButton+ label="Cancel"+ variant="secondary"+ onClick={() => setIsShown(false)}+ />+ <XDSButton+ label="Confirm"+ variant="primary"+ onClick={() => setIsShown(false)}+ />+ </XDSLayoutFooter>+ }+ />+ </XDSDialog>+ </>+ );+}+```++## Props++| Prop | Type | Default | Description |+| ----------- | -------------------------------- | ------------ | ------------------------------------------------ |+| `isShown` | `boolean` | — | Whether the dialog is shown (required) |+| `onHide` | `() => unknown` | — | Callback when dialog requests to hide (required) |+| `width` | `number \| string` | `400` | Width of the dialog (px or CSS value) |+| `maxHeight` | `number \| string` | `'75vh'` | Maximum height of the dialog |+| `position` | `XDSDialogPosition` | — | Static position (centered by default) |+| `variant` | `'standard' \| 'fullscreen'` | `'standard'` | Dialog variant |+| `purpose` | `'required' \| 'form' \| 'info'` | `'info'` | Dismissal behavior |+| `children` | `ReactNode` | — | Dialog content (required) |++## Purpose Prop++The `purpose` prop controls how users can dismiss the dialog:++| Purpose | Escape Key | Backdrop Click | Use Case |+| ---------- | ----------- | -------------- | ------------------------------------------ |+| `required` | ❌ Disabled | ❌ Disabled | Mandatory flows (security, permissions) |+| `form` | ✅ Allowed | ❌ Disabled\* | Forms where accidental dismiss = data loss |+| `info` | ✅ Allowed | ✅ Allowed | Informational content, low-cost dismissal |++\*For `form` purpose, backdrop click is only allowed before user interaction.++## Position Prop++Configure a static position instead of centering:++```tsx+<XDSDialog+ isShown={isShown}+ onHide={() => setIsShown(false)}+ position={{top: 100, right: 20}}>+ {/* content */}+</XDSDialog>+```++## Files++| File | Role | Purpose |+| -------------------- | ----- | ------------------------------------- |+| `index.ts` | Entry | Exports XDSDialog component and types |+| `XDSDialog.tsx` | Core | XDSDialog component implementation |+| `XDSDialog.test.tsx` | Test | Unit tests for XDSDialog component |++## Implementation Notes++- Uses native `<dialog>` element with `showModal()` for proper modal behavior+- Height is `unset` (grows with content) and constrained by `maxHeight`+- Focus is automatically trapped by the browser when using `showModal()`+- Escape key and backdrop clicks are controlled by the `purpose` prop+- When `variant="fullscreen"`, the `width`, `maxHeight`, and `position` props are ignoreddiff --git a/packages/core/src/Dialog/XDSDialog.test.tsx b/packages/core/src/Dialog/XDSDialog.test.tsxnew file mode 100644index 0000000000..167e379419--- /dev/null+++ b/packages/core/src/Dialog/XDSDialog.test.tsx@@ -0,0 +1,218 @@+/**+ * @file XDSDialog.test.tsx+ * @input Uses vitest, @testing-library/react, XDSDialog component+ * @output Unit tests for XDSDialog component behavior+ * @position Testing; validates XDSDialog.tsx implementation+ *+ * SYNC: When XDSDialog.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi, beforeEach} from 'vitest';+import {render, screen} from '@testing-library/react';+import {XDSDialog} from './XDSDialog';++// Mock showModal and close methods since they're not fully implemented in jsdom+beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+});++describe('XDSDialog', () => {+ it('renders when isShown is true', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}}>+ Dialog content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ expect(screen.getByText('Dialog content')).toBeInTheDocument();+ });++ it('calls showModal when opened', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}}>+ Content+ </XDSDialog>,+ );+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalled();+ });++ it('does not show when isShown is false', () => {+ render(+ <XDSDialog isShown={false} onHide={() => {}}>+ Hidden content+ </XDSDialog>,+ );+ const dialog = screen.getByRole('dialog', {hidden: true});+ expect(dialog).not.toHaveAttribute('open');+ });++ it('has aria-modal attribute', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}}>+ Content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toHaveAttribute('aria-modal', 'true');+ });++ describe('purpose: info (default)', () => {+ it('calls onHide when Escape is pressed', () => {+ const handleHide = vi.fn();++ render(+ <XDSDialog isShown={true} onHide={handleHide} purpose="info">+ Content+ </XDSDialog>,+ );++ const dialog = screen.getByRole('dialog');+ const escapeEvent = new KeyboardEvent('keydown', {+ key: 'Escape',+ bubbles: true,+ cancelable: true,+ });+ dialog.dispatchEvent(escapeEvent);+ expect(handleHide).toHaveBeenCalledTimes(1);+ });+ });++ describe('purpose: form', () => {+ it('calls onHide when Escape is pressed', () => {+ const handleHide = vi.fn();++ render(+ <XDSDialog isShown={true} onHide={handleHide} purpose="form">+ Content+ </XDSDialog>,+ );++ const dialog = screen.getByRole('dialog');+ const escapeEvent = new KeyboardEvent('keydown', {+ key: 'Escape',+ bubbles: true,+ cancelable: true,+ });+ dialog.dispatchEvent(escapeEvent);+ expect(handleHide).toHaveBeenCalledTimes(1);+ });+ });++ describe('purpose: required', () => {+ it('does not call onHide when Escape is pressed', () => {+ const handleHide = vi.fn();++ render(+ <XDSDialog isShown={true} onHide={handleHide} purpose="required">+ Content+ </XDSDialog>,+ );++ const dialog = screen.getByRole('dialog');+ const escapeEvent = new KeyboardEvent('keydown', {+ key: 'Escape',+ bubbles: true,+ cancelable: true,+ });+ dialog.dispatchEvent(escapeEvent);+ expect(handleHide).not.toHaveBeenCalled();+ });++ it('prevents default on cancel event', () => {+ const handleHide = vi.fn();+ render(+ <XDSDialog isShown={true} onHide={handleHide} purpose="required">+ Content+ </XDSDialog>,+ );++ const dialog = screen.getByRole('dialog');+ const cancelEvent = new Event('cancel', {cancelable: true});+ dialog.dispatchEvent(cancelEvent);++ expect(cancelEvent.defaultPrevented).toBe(true);+ expect(handleHide).not.toHaveBeenCalled();+ });+ });++ describe('variant: standard', () => {+ it('renders with default variant', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}}>+ Content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ });++ it('accepts custom width', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}} width={600}>+ Content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ });++ it('accepts custom maxHeight', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}} maxHeight="50vh">+ Content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ });+ });++ describe('variant: fullscreen', () => {+ it('renders fullscreen variant', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}} variant="fullscreen">+ Content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ });+ });++ describe('position prop', () => {+ it('accepts position configuration', () => {+ render(+ <XDSDialog+ isShown={true}+ onHide={() => {}}+ position={{top: 100, right: 20}}>+ Content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ });++ it('handles string position values', () => {+ render(+ <XDSDialog+ isShown={true}+ onHide={() => {}}+ position={{top: '10vh', left: '5vw'}}>+ Content+ </XDSDialog>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ });+ });++ it('forwards additional props to dialog element', () => {+ render(+ <XDSDialog isShown={true} onHide={() => {}} data-testid="custom-dialog">+ Content+ </XDSDialog>,+ );+ expect(screen.getByTestId('custom-dialog')).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Dialog/XDSDialog.tsx b/packages/core/src/Dialog/XDSDialog.tsxnew file mode 100644index 0000000000..12d8a82f94--- /dev/null+++ b/packages/core/src/Dialog/XDSDialog.tsx@@ -0,0 +1,342 @@+/**+ * @file XDSDialog.tsx+ * @input Uses React forwardRef, DialogHTMLAttributes, ReactNode+ * @output Exports XDSDialog component, XDSDialogProps, XDSDialogVariant, XDSDialogPurpose types+ * @position Core implementation; consumed by index.ts, tested by XDSDialog.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Dialog/README.md (props table, features, implementation notes)+ * - /packages/core/src/Dialog/XDSDialog.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Dialog/index.ts (exports if types change)+ * - /apps/storybook/stories/Dialog.stories.tsx (storybook stories)+ */++import {+ forwardRef,+ useEffect,+ useRef,+ type DialogHTMLAttributes,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ radiusVars,+ transitionVars,+ elevationVars,+} from '../theme/tokens.stylex';++/**+ * Dialog variant type+ * - standard: Normal dialog with configurable width/height+ * - fullscreen: Takes up the entire viewport+ */+export type XDSDialogVariant = 'standard' | 'fullscreen';++/**+ * Dialog purpose type - controls dismissal behavior+ * - required: Mandatory flows (security, permissions) - disables all exit methods+ * - form: User forms/flows - prevents backdrop click, allows escape+ * - info: Informational flows - allows all exit methods+ */+export type XDSDialogPurpose = 'required' | 'form' | 'info';++/**+ * Position configuration for static dialog positioning+ */+export interface XDSDialogPosition {+ bottom?: number | string;+ left?: number | string;+ right?: number | string;+ top?: number | string;+}++/**+ * Dialog styles using native <dialog> element+ * Uses ::backdrop pseudo-element for overlay+ */+const styles = stylex.create({+ dialog: {+ position: 'fixed',+ margin: 'auto',+ padding: 0,+ border: 'none',+ backgroundColor: colorVars['--color-surface'],+ borderRadius: radiusVars['--radius-container'],+ boxShadow: elevationVars['--elevation-dialog'],+ overflow: 'hidden',+ height: 'fit-content',+ // Animation for opening+ opacity: {+ default: 0,+ ':where([open])': 1,+ },+ transform: {+ default: 'scale(0.95) translateY(8px)',+ ':where([open])': 'scale(1) translateY(0)',+ },+ transition: `opacity ${transitionVars['--transition-normal']}, transform ${transitionVars['--transition-normal']}`,+ outline: {+ default: null,+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-visible': '2px',+ },+ },+ // Backdrop using ::backdrop pseudo-element+ backdrop: {+ '::backdrop': {+ backgroundColor: colorVars['--color-overlay'],+ backdropFilter: 'blur(2px)',+ },+ },+ fullscreen: {+ width: '100vw',+ height: '100vh',+ maxWidth: '100vw',+ maxHeight: '100vh',+ borderRadius: 0,+ margin: 0,+ inset: 0,+ },+});++// Dynamic styles for width, maxHeight, and position+const dynamicStyles = stylex.create({+ sizing: (width: number | string, maxHeight: number | string) => ({+ width: typeof width === 'number' ? `${width}px` : width,+ maxWidth: '90vw',+ maxHeight: typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight,+ }),+ position: (+ top: number | string | undefined,+ right: number | string | undefined,+ bottom: number | string | undefined,+ left: number | string | undefined,+ ) => ({+ // When position is set, disable auto margin and use fixed positioning+ margin: 0,+ top: formatPosition(top),+ right: formatPosition(right),+ bottom: formatPosition(bottom),+ left: formatPosition(left),+ }),+});++/**+ * Format position value - numbers become pixels, strings pass through, undefined becomes null+ */+function formatPosition(value: number | string | undefined): string | null {+ if (value === undefined) return null;+ return typeof value === 'number' ? `${value}px` : value;+}++export interface XDSDialogProps extends Omit<+ DialogHTMLAttributes<HTMLDialogElement>,+ 'children'+> {+ /**+ * Whether the dialog is shown.+ */+ isShown: boolean;++ /**+ * Callback fired when the dialog requests to be hidden.+ * This is called based on the `purpose` prop configuration:+ * - required: Never called automatically+ * - form: Called on Escape key only+ * - info: Called on Escape key and backdrop click+ */+ onHide: () => unknown;++ /**+ * The width of the dialog.+ * Numbers are treated as pixels, strings are used as-is.+ * Ignored when variant is 'fullscreen'.+ * @default 400+ */+ width?: number | string;++ /**+ * The maximum height of the dialog.+ * The actual height will be the height of its content.+ * Numbers are treated as pixels, strings are used as-is.+ * Ignored when variant is 'fullscreen'.+ * @default '75vh'+ */+ maxHeight?: number | string;++ /**+ * Static position for the dialog on screen.+ * By default, the dialog will be centered.+ * Ignored when variant is 'fullscreen'.+ */+ position?: Readonly<XDSDialogPosition>;++ /**+ * The variant of the dialog.+ * - standard: Normal dialog with configurable dimensions+ * - fullscreen: Takes up the entire viewport+ * @default 'standard'+ */+ variant?: XDSDialogVariant;++ /**+ * Configures how the dialog enables dismissals.+ * - required: Disables all exit methods (for mandatory flows)+ * - form: Prevents backdrop click, allows Escape key+ * - info: Allows all exit methods (Escape and backdrop click)+ * @default 'info'+ */+ purpose?: XDSDialogPurpose;++ /**+ * The content of the dialog.+ * Typically an XDSLayout with header, content, and footer slots.+ */+ children: ReactNode;+}++/**+ * A dialog component using the native <dialog> element.+ *+ * Designed to be used with XDSLayout as its child for structured content.+ * Uses the browser's built-in modal behavior for optimal accessibility.+ *+ * @example+ * ```tsx+ * const [isShown, setIsShown] = useState(false);+ *+ * <XDSDialog isShown={isShown} onHide={() => setIsShown(false)}>+ * <XDSLayout+ * header={<XDSLayoutHeader hasDivider>Title</XDSLayoutHeader>}+ * content={<XDSLayoutContent>Content</XDSLayoutContent>}+ * footer={<XDSLayoutFooter hasDivider>Actions</XDSLayoutFooter>}+ * />+ * </XDSDialog>+ * ```+ */+export const XDSDialog = forwardRef<HTMLDialogElement, XDSDialogProps>(+ (+ {+ isShown,+ onHide,+ width = 400,+ maxHeight = '75vh',+ position,+ variant = 'standard',+ purpose = 'info',+ children,+ ...props+ },+ ref,+ ) => {+ const dialogRef = useRef<HTMLDialogElement>(null);++ // Derive dismissal behavior from purpose+ const allowEscape = purpose !== 'required';+ const allowBackdropClick = purpose === 'info';++ // Merge refs+ const setRefs = (element: HTMLDialogElement | null) => {+ (dialogRef as React.MutableRefObject<HTMLDialogElement | null>).current =+ element;+ if (typeof ref === 'function') {+ ref(element);+ } else if (ref) {+ ref.current = element;+ }+ };++ // Handle open/close state+ useEffect(() => {+ const dialog = dialogRef.current;+ if (!dialog) return;++ if (isShown) {+ if (!dialog.open) {+ dialog.showModal();+ }+ } else {+ if (dialog.open) {+ dialog.close();+ }+ }+ }, [isShown]);++ // Handle Escape key+ useEffect(() => {+ const dialog = dialogRef.current;+ if (!dialog || !isShown) return;++ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ if (allowEscape) {+ onHide();+ }+ }+ };++ dialog.addEventListener('keydown', handleKeyDown);+ return () => dialog.removeEventListener('keydown', handleKeyDown);+ }, [isShown, allowEscape, onHide]);++ // Handle backdrop click+ const handleClick = (event: React.MouseEvent<HTMLDialogElement>) => {+ const dialog = dialogRef.current;+ if (!dialog) return;++ // Check if click was on the backdrop (dialog element itself, not content)+ const rect = dialog.getBoundingClientRect();+ const isBackdropClick =+ event.clientX < rect.left ||+ event.clientX > rect.right ||+ event.clientY < rect.top ||+ event.clientY > rect.bottom;++ if (isBackdropClick && allowBackdropClick) {+ onHide();+ }+ };++ // Handle native cancel event (browser Escape handling)+ const handleCancel = (event: React.SyntheticEvent<HTMLDialogElement>) => {+ event.preventDefault();+ if (allowEscape) {+ onHide();+ }+ };++ const isFullscreen = variant === 'fullscreen';+ const hasPosition = position != null && !isFullscreen;++ return (+ <dialog+ ref={setRefs}+ onClick={handleClick}+ onCancel={handleCancel}+ aria-modal="true"+ {...stylex.props(+ styles.dialog,+ styles.backdrop,+ !isFullscreen && dynamicStyles.sizing(width, maxHeight),+ hasPosition &&+ dynamicStyles.position(+ position?.top,+ position?.right,+ position?.bottom,+ position?.left,+ ),+ isFullscreen && styles.fullscreen,+ )}+ {...props}>+ {children}+ </dialog>+ );+ },+);++XDSDialog.displayName = 'XDSDialog';diff --git a/packages/core/src/Dialog/index.ts b/packages/core/src/Dialog/index.tsnew file mode 100644index 0000000000..3fdb22e306--- /dev/null+++ b/packages/core/src/Dialog/index.ts@@ -0,0 +1,16 @@+/**+ * @file index.ts+ * @input Imports XDSDialog component and types from XDSDialog.tsx+ * @output Exports XDSDialog, XDSDialogProps, XDSDialogVariant, XDSDialogPurpose, XDSDialogPosition, XDSDialogRef+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/Dialog/README.md+ */++export {XDSDialog} from './XDSDialog';+export type {+ XDSDialogProps,+ XDSDialogVariant,+ XDSDialogPurpose,+ XDSDialogPosition,+} from './XDSDialog';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a31dcfb9a0..15fc75207e 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -30,6 +30,7 @@ export * from './TextArea';export * from './TimeInput';export * from './NumberInput';export * from './Table';+export * from './Dialog';// Layout utilities and components (includes XDSHStack, XDSVStack)export * from './Layout';