# Dialog

> Modal and modeless dialogs on the native dialog element, with trigger and close parts, cancellable dismissal, placement and position, sizes, full-screen sheets and opt-in drag and resize loaded on demand.

Canonical: https://salmonui.dev/docs/layout/dialog

`Dialog` is the native `<dialog>` element opened with `showModal()` (or
`show()` for a modeless dialog). The platform provides the top layer, the
`::backdrop`, the inert background and Tab containment; Salmon UI adds the
open state, labelling, dismissal rules, placement and optional drag and
resize. It lives in `@salmonui/overlays/dialog` with
[AlertDialog](https://salmonui.dev/docs/layout/alert-dialog); [Drawer](https://salmonui.dev/docs/layout/dialog#drawer) shares its core from
`@salmonui/overlays/drawer`.

```tsx
import { Dialog } from '@salmonui/overlays/dialog';
import { Button } from '@salmonui/buttons/button';
import '@salmonui/overlays/dialog/styles.css';
import '@salmonui/buttons/button/styles.css';

export function EditOrder() {
  return (
    <Dialog trigger={<Dialog.Trigger render={(p) => <Button {...p}>Edit</Button>} />} closeButton>
      <Dialog.Title>Edit order</Dialog.Title>
      <Dialog.Description>Changes are saved on submit.</Dialog.Description>
      <form method="dialog">
        <Dialog.Body>…fields…</Dialog.Body>
        <Dialog.Footer>
          <Dialog.Close render={(p) => <Button {...p} variant="outline" />}>Cancel</Dialog.Close>
          <Button type="submit" value="save" tone="primary">Save</Button>
        </Dialog.Footer>
      </form>
    </Dialog>
  );
}
```

### Live demo: Dialog

Live demo: https://salmonui.dev/demos/layout/dialog

A modal edit Dialog with a title, description, form body and footer, closed by Cancel, Save, Escape or the close button.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Dialog } from '@salmonui/overlays/dialog';
import { TextField } from '@salmonui/inputs/text-field';

export default function DialogDemo() {
  const [result, setResult] = useState('No changes');
  return (
    <div>
      <Dialog
        trigger={<Dialog.Trigger render={(p) => <Button {...p}>Edit order</Button>} />}
        closeButton
        onOpenChange={(open, e) => !open && setResult(e.reason === 'submit' ? 'Saved' : `Closed (${e.reason})`)}
      >
        <Dialog.Title>Edit order</Dialog.Title>
        <Dialog.Description>Changes are saved on submit.</Dialog.Description>
        <form method="dialog">
          <Dialog.Body>
            <TextField label="Customer" name="customer" data-autofocus="" defaultValue="Ada Lovelace" style={{ inlineSize: '100%' }} />
          </Dialog.Body>
          <Dialog.Footer>
            <Dialog.Close render={(p) => <Button {...p} variant="outline" />}>Cancel</Dialog.Close>
            <Button type="submit" value="save" tone="primary">
              Save
            </Button>
          </Dialog.Footer>
        </form>
      </Dialog>
      <p>
        <output>{result}</output>
      </p>
    </div>
  );
}
```

## Parts

| Part | Element | Notes |
| --- | --- | --- |
| `Dialog` | the open state and `<dialog class="salmon-dialog">` | `ref` is the `HTMLDialogElement` |
| `Dialog.Trigger` | `<button type="button">` | Pass it in `trigger` (it is rendered before the dialog with its context); `aria-haspopup="dialog"`, `aria-expanded`; `render` swaps the element |
| `Dialog.Title` | `<h2>` | Labels the dialog (`aria-labelledby`); the `title` prop is a shorthand |
| `Dialog.Description` | `<p>` | Describes the dialog (`aria-describedby`) |
| `Dialog.Body` | `<div>` | The scrolling region |
| `Dialog.Footer` | `<div>` | The action row: put `Button` elements here |
| `Dialog.Close` | `<button type="button">` | Closes with `reason: 'close'` |

Every part is also exported flat (`DialogTrigger`, `DialogTitle`, ...).
Footer buttons are ordinary `Button` elements in `Dialog.Footer` rather
than a button configuration array: they take every Button prop,
their own handlers and loading state, and `Dialog.Close` wraps a cancel
button. The application holds refs to its own footer buttons and
measures the dialog through `ref` with `getBoundingClientRect()`, or reads
`onResizeEnd`.

## Open state and dismissal

- `open` / `defaultOpen` / `onOpenChange(open, event)`. `event.reason` is
  `'trigger' | 'close' | 'closeButton' | 'escape' | 'outside' | 'submit'`
  (AlertDialog adds `'confirm'` and `'cancel'`); `event.source` is
  `'pointer'`, `'keyboard'`, `'touch'` or `'api'`. `event.preventDefault()` keeps an uncontrolled dialog as it is,
  which cancels an open or a close. A controlled dialog vetoes by not
  updating `open`.
- `dismissible` (default `{ escape: true, outside: false }`): `true` also
  closes on a backdrop press, `false` never closes on either.
  `onOverlayPress` reports backdrop presses either way.
- A `<form method="dialog">` inside closes the dialog with
  `reason: 'submit'` and its submitter's `returnValue`.
- `closeButton` adds a close button in the corner; its label is
  `localeText.close` (default "Close").
- `onAfterOpen` fires after the open transition, `onAfterClose` after the
  dialog closed. Mounting and unmounting the dialog is its lifecycle; there
  are no create or destroy events.

## Focus

On open, focus moves to `initialFocus` (a ref), else to the element with
`data-autofocus`, else to the first focusable element (the platform
default). On close it returns to the element that opened the dialog
(`returnFocus={false}` keeps it where it is). A modal dialog keeps Tab
inside; a modeless dialog (`modal={false}`) keeps the page's Tab order, and
Escape closes it from inside.

## Popups inside a dialog

A modal dialog makes the rest of the page inert, so Select, Combobox,
TreeSelect, the date and time pickers, menus, Tooltip, Popover, Mention and
ColorPicker opened inside a modal `Dialog` or `Drawer` render inside the
`<dialog>` element and stack above it in the top layer: they stay clickable
and keep their placement, flip and shift against the viewport.
Escape closes the open popup first and the dialog on the next press; a
press on the backdrop while a popup is open only closes the popup. An
explicit `container` prop on a popup still wins. Toasts are not anchored and
stay in the page: while a modal dialog is open they are announced but cannot
be operated until it closes.

## Placement, position and size

- `placement`: `'center'` (default) or `'top'`. Centering is CSS, so the
  position never needs refreshing.
- `position` / `defaultPosition` / `onPositionChange` (`{ x, y }`, `x` along
  the inline axis, mirrored in RTL) offset the dialog from its placement.
- `width`, `height`, `minHeight`: numbers (px) or CSS lengths.
- `fullScreen`: `true`, or `'mobile'` to fill the screen below 640 px (the
  Data Grid adaptive sheet rule).
- Modal dialogs live in the top layer, which the browser stacks above the
  whole page in opening order, so there is no z-index setting.
- A modal dialog cannot be confined to a target element: the
  platform makes the whole page inert, so a modal limited to one region
  would still block the rest. A modeless dialog (`modal={false}`) accepts
  `container` and is rendered and positioned inside that element (mounted
  after hydration); for a panel-local modal, render the content inline in
  the panel instead.

### Live demo: Dialog placement, size and dismissal

Live demo: https://salmonui.dev/demos/layout/dialog-options

A modal task Dialog with placement, width, full-screen and backdrop-dismissal controls, a close request vetoed while the notes are edited, initial focus, a Select and a Tooltip inside the modal, right-to-left and an event log.

`Demo.tsx`:

```tsx
'use client';
import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Dialog } from '@salmonui/overlays/dialog';
import { Select, type SelectValue } from '@salmonui/dropdowns/select';
import { TextArea } from '@salmonui/inputs/text-field';
import { Tooltip } from '@salmonui/overlays/tooltip';
import { EventLog, useEventLog } from '../../components/demo-kit';

const help = (
  <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
    <circle cx="8" cy="8" r="6.25" fill="none" stroke="currentColor" strokeWidth="1.5" />
    <path d="M6.4 6.3a1.7 1.7 0 1 1 2.3 1.6c-.5.2-.7.6-.7 1.1v.3" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    <circle cx="8" cy="11.4" r=".9" fill="currentColor" />
  </svg>
);

const PRIORITIES = [
  { value: 'low', label: 'Low' },
  { value: 'normal', label: 'Normal' },
  { value: 'high', label: 'High' },
];

// A modal task dialog whose placement, size, dismissal and direction come from
// the controls, with a cancellable close request, initial focus on the notes,
// and a Select and a Tooltip that stay usable inside the modal dialog.
export default function DialogOptionsDemo() {
  const [placement, setPlacement] = useState<'center' | 'top'>('center');
  const [width, setWidth] = useState(420);
  const [fullScreen, setFullScreen] = useState<'off' | 'mobile' | 'always'>('off');
  const [outside, setOutside] = useState(false);
  const [guard, setGuard] = useState(true);
  const [rtl, setRtl] = useState(false);
  const [dirty, setDirty] = useState(false);
  const [priority, setPriority] = useState<SelectValue | null>('normal');
  const [log, record] = useEventLog(6);
  const notes = useRef<HTMLTextAreaElement>(null);
  return (
    <div>
      <div className="demo-toolbar">
        <label>
          Placement
          <Select aria-label="Placement" data={[{ value: 'center', label: 'Center' }, { value: 'top', label: 'Top' }]} value={placement} onValueChange={(value) => value != null && setPlacement(value as 'center' | 'top')} />
        </label>
        <label>
          Width
          <Select aria-label="Width" data={[{ value: 320, label: '320 px' }, { value: 420, label: '420 px' }, { value: 560, label: '560 px' }]} value={width} onValueChange={(value) => value != null && setWidth(Number(value))} />
        </label>
        <label>
          Full screen
          <Select aria-label="Full screen" data={[{ value: 'off', label: 'Off' }, { value: 'mobile', label: 'Below 640 px' }, { value: 'always', label: 'Always' }]} value={fullScreen} onValueChange={(value) => value != null && setFullScreen(value as 'off' | 'mobile' | 'always')} />
        </label>
        <Checkbox checked={outside} onCheckedChange={(checked) => setOutside(checked)}>
          Close on a backdrop press
        </Checkbox>
        <Checkbox checked={guard} onCheckedChange={(checked) => setGuard(checked)}>
          Keep open while edited
        </Checkbox>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          Right to left
        </Checkbox>
      </div>
      <div dir={rtl ? 'rtl' : 'ltr'}>
        <Dialog
          trigger={<Dialog.Trigger render={(p) => <Button {...p}>New task</Button>} />}
          title="New task"
          closeButton
          placement={placement}
          width={width}
          minHeight={240}
          fullScreen={fullScreen === 'off' ? false : fullScreen === 'mobile' ? 'mobile' : true}
          dismissible={{ escape: true, outside }}
          initialFocus={notes}
          style={{ borderBlockStart: '4px solid var(--salmon-color-primary)' }}
          localeText={{ close: 'Close the task dialog' }}
          onOverlayPress={() => record('backdrop pressed')}
          onOpenChange={(open, event) => {
            if (!open && guard && dirty && event.reason !== 'submit') {
              event.preventDefault();
              record(`close (${event.reason}) prevented: unsaved notes`);
              return;
            }
            record(`${open ? 'open' : 'close'} requested (${event.reason})`);
            if (!open) setDirty(false);
          }}
          onAfterOpen={() => record('after open')}
          onAfterClose={() => record('after close')}
        >
          <Dialog.Description>The notes field takes the initial focus.</Dialog.Description>
          <form method="dialog">
            <Dialog.Body>
              <div style={{ display: 'grid', gap: 12 }}>
                <TextArea label="Notes" ref={notes} name="notes" rows={3} onChange={() => setDirty(true)} />
                <div style={{ display: 'grid', gap: 4 }}>
                  <span id="demo-dialog-priority" className="salmon-field-label">
                    Priority
                  </span>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    <Select aria-labelledby="demo-dialog-priority" data={PRIORITIES} value={priority} onValueChange={setPriority} />
                    <Tooltip content="High priority tasks are listed first">
                      <Button type="button" variant="ghost" iconOnly aria-label="About priority">
                        {help}
                      </Button>
                    </Tooltip>
                  </div>
                </div>
              </div>
            </Dialog.Body>
            <Dialog.Footer>
              <Dialog.Close render={(p) => <Button {...p} variant="outline" />}>Cancel</Dialog.Close>
              <Button type="submit" value="create" tone="primary">
                Create
              </Button>
            </Dialog.Footer>
          </form>
        </Dialog>
      </div>
      <EventLog entries={log} label="Dialog events" />
    </div>
  );
}
```

## Drag and resize

`draggable` moves the dialog by its title (`dragHandle`: another selector);
`resizable` adds a bottom-end handle (`true`) or the given logical edges
(`['bottomEnd', 'end', 'top', ...]`). Their code is a separate chunk loaded
the first time either prop is true, so dialogs that never move pay nothing.

- During a drag the dialog's position variables are written once per
  animation frame; React renders only when the drag ends. `onMoveStart`,
  `onMove` (per frame, not for React state) and `onMoveEnd({ x, y })`;
  `onResizeStart`, `onResize` and `onResizeEnd({ width, height })`.
- Escape during a pointer drag cancels it.
- Keyboard: the drag handle and resize handles
  are focusable; arrow keys move or resize by 10 px (Shift: 50 px) and a
  polite live region announces the result (`localeText.moved`,
  `localeText.resized`). Each resize handle is named by
  `localeText.resizeEdge(edge)`, by default `localeText.resize` and the
  edge in words ("Resize (bottom end)").
- In RTL, horizontal drags and arrow keys follow the reading direction.

### Live demo: Draggable Dialog

Live demo: https://salmonui.dev/demos/layout/dialog-draggable

A modeless Dialog moved by its title and resized from its corner, with arrow-key moves on the focused title, a controlled position and size, and a log of the move and resize events.

`Demo.tsx`:

```tsx
'use client';
import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Dialog, type DialogPosition, type DialogSize } from '@salmonui/overlays/dialog';
import { EventLog, useEventLog } from '../../components/demo-kit';

export default function DialogDraggableDemo() {
  const [pos, setPos] = useState<DialogPosition>({ x: 0, y: 0 });
  const [size, setSize] = useState<DialogSize | null>(null);
  const [log, record] = useEventLog(6);
  // onMove / onResize run once per animation frame: write the DOM, not React state.
  const live = useRef<HTMLSpanElement>(null);
  return (
    <div>
      <div className="demo-toolbar">
        <Dialog
          trigger={<Dialog.Trigger render={(p) => <Button {...p}>Open palette</Button>} />}
          modal={false}
          draggable
          resizable
          position={pos}
          onPositionChange={setPos}
          width={size?.width ?? 320}
          height={size?.height}
          closeButton
          onMoveStart={() => record('move start')}
          onMove={(p) => {
            if (live.current) live.current.textContent = `moving ${Math.round(p.x)}, ${Math.round(p.y)}`;
          }}
          onMoveEnd={(p) => record(`move end ${Math.round(p.x)}, ${Math.round(p.y)}`)}
          onResizeStart={() => record('resize start')}
          onResize={(s) => {
            if (live.current) live.current.textContent = `resizing ${Math.round(s.width)} x ${Math.round(s.height)}`;
          }}
          onResizeEnd={(s) => {
            setSize(s);
            record(`resize end ${Math.round(s.width)} x ${Math.round(s.height)}`);
          }}
        >
          <Dialog.Title>Palette</Dialog.Title>
          <Dialog.Body>Drag the title, or focus it and use the arrow keys. Resize from the corner.</Dialog.Body>
        </Dialog>
        <Button
          variant="outline"
          onClick={() => {
            setPos({ x: 0, y: 0 });
            setSize(null);
          }}
        >
          Reset position and size
        </Button>
      </div>
      <p>
        <output>
          Offset {pos.x}, {pos.y}
          {size ? ` · size ${Math.round(size.width)} x ${Math.round(size.height)}` : ''}
        </output>{' '}
        <span ref={live} className="demo-status" />
      </p>
      <EventLog entries={log} label="Move and resize events" />
    </div>
  );
}
```

Persist position and size by storing what `onPositionChange` and
`onResizeEnd` report and passing them back as `position` and
`width` / `height`. There is no built-in persistence:
`localStorage` is not readable on the server, so a restored position would
not hydrate. Content is `ReactNode`; HTML strings are not parsed, so there
is nothing to sanitize. Dialogs have one fade transition, off
under `prefers-reduced-motion`, rather than a set of animation effects:
more effects would add bytes to every dialog; restyle the
transition with CSS on `.salmon-dialog` if needed.

## SSR

A closed dialog renders only its trigger. `keepMounted` renders the closed
`<dialog>` too (content in the HTML). A modal `defaultOpen` dialog renders
`<dialog>` without `open` and calls `showModal()` after hydration; a
modeless one renders `<dialog open>`, visible without JavaScript.

## Drawer

`Drawer` is a dialog docked to an edge: navigation on a phone, a filter
panel, a details pane. It shares the dialog host, parts and props of
Dialog and lives in its own subpath, `@salmonui/overlays/drawer`, with its
own stylesheet (the dialog core plus the drawer rules; it does not load
AlertDialog or Button). The Navigation category's Sidebar overlay mode
renders the same drawer core without importing `@salmonui/overlays`, and
needs this stylesheet too.

```tsx
import { Drawer } from '@salmonui/overlays/drawer';
import '@salmonui/overlays/drawer/styles.css';

<Drawer trigger={<Drawer.Trigger aria-label="Menu">☰</Drawer.Trigger>} side="start" size={280} title="Navigation">
  <Drawer.Body>…links…</Drawer.Body>
</Drawer>;
```

### Live demo: Drawer

Live demo: https://salmonui.dev/demos/layout/drawer

A navigation Drawer docked to the inline start edge.

`Demo.tsx`:

```tsx
'use client';
import { Button } from '@salmonui/buttons/button';
import { Drawer } from '@salmonui/overlays/drawer';

// Placeholder links target this demo's own title, which exists on both the
// docs page and the demo page, so no link dangles in the static export.
const DEMO_ANCHOR = '#demo-drawer-title';

const links = ['Orders', 'Customers', 'Products', 'Reports'];

export default function DrawerDemo() {
  return (
    <Drawer trigger={<Drawer.Trigger render={(p) => <Button {...p}>Menu</Button>} />} side="start" size={280} title="Navigation" closeButton>
      <Drawer.Body>
        <nav aria-label="Main">
          <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
            {links.map((label) => (
              <li key={label}>
                <a href={DEMO_ANCHOR} style={{ display: 'block', paddingBlock: 6 }}>
                  {label}
                </a>
              </li>
            ))}
          </ul>
        </nav>
      </Drawer.Body>
    </Drawer>
  );
}
```

| Prop | Values | Default |
| --- | --- | --- |
| `side` | `'start' \| 'end' \| 'top' \| 'bottom'` (`start` / `end` follow `dir`) | `'start'` |
| `size` | inline size for start / end, block size for top / bottom (number px or CSS length) | 320 px |
| `modal` | `true`: backdrop, inert page, focus containment; `false`: no backdrop | `true` |
| `dismissible` | Escape and backdrop press | `true` (both) |

`open` / `defaultOpen` / `onOpenChange(open, event)`, `closeButton`,
`initialFocus`, `returnFocus`, `keepMounted`, `onAfterOpen` /
`onAfterClose` and the parts (`Drawer.Title`, `Drawer.Body`,
`Drawer.Footer`, `Drawer.Close`, `Drawer.Trigger`) behave as in Dialog.
The panel slides in from its edge (off under `prefers-reduced-motion`);
the hooks are `.salmon-drawer[data-side]`.

API reference: [`@salmonui/overlays/dialog`](https://salmonui.dev/docs/reference/overlays/dialog) and
[`@salmonui/overlays/drawer`](https://salmonui.dev/docs/reference/overlays/drawer).

## Bundle

The initial `@salmonui/overlays/dialog` JavaScript (Dialog, AlertDialog,
DialogProvider, without the `Button` AlertDialog composes) is 4.44 KB gzip;
the drag and resize chunk 2.10 KB; the stylesheet 2.94 KB including the
Button rules. `@salmonui/overlays/drawer` is 3.03 KB (no drag chunk) and
1.45 KB (measured 2026-11-26 with `bundle:check`).
