---
title: BaseDialog
description: Compose a modal trigger, backdrop, and content surface.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# BaseDialog

> Compose a modal trigger, backdrop, and content surface.

## Anatomy

```text
BaseDialog [component; no DOM]
├── BaseDialog.Trigger [part]
└── BaseDialog.Portal [part]
    ├── BaseDialog.Overlay [part; slot=overlay]
    └── BaseDialog.Content [part; slot=content]
```

Portal owns the mounted Overlay and Content subtree and preserves it through exit motion.

## Usage

Use BaseDialog when you compose trigger, backdrop, and content yourself. Use [Dialog](https://moraine.subf.dev/components/dialog.md)
for a structured title, description, body, and footer. Use [Sheet](https://moraine.subf.dev/components/sheet.md) for a drawer
from a viewport edge. Use [Popover](https://moraine.subf.dev/components/popover.md) for anchored interactive content.
[Dialog](https://moraine.subf.dev/components/dialog.md) and [Sheet](https://moraine.subf.dev/components/sheet.md) wrap this primitive; their Content
parts include a Portal internally.

```tsx
import { Button, BaseDialog } from 'moraine'

export function Example() {
  return (
    <BaseDialog>
      <BaseDialog.Trigger as={Button}>Open</BaseDialog.Trigger>
      <BaseDialog.Portal>
        <BaseDialog.Overlay />
        <BaseDialog.Content aria-label="Details">
          Modal content
          <BaseDialog.Close as={Button}>Close</BaseDialog.Close>
        </BaseDialog.Content>
      </BaseDialog.Portal>
    </BaseDialog>
  )
}
```

### Composition

Place `BaseDialog.Overlay` and `BaseDialog.Content` inside the same `BaseDialog.Portal`. The Portal mounts them
when open and keeps them present through exit animations. Without it, both parts render in place
and your application controls their mounting. One root owns one active Content; use a nested
BaseDialog root for a second surface.

To scroll content taller than the viewport inside the backdrop, set `scrollable` on `BaseDialog.Overlay`
and nest `BaseDialog.Content` inside it. To render without a backdrop, omit `BaseDialog.Overlay`.

```tsx
<BaseDialog>
  <BaseDialog.Trigger as={Button}>Open</BaseDialog.Trigger>
  <BaseDialog.Portal>
    <BaseDialog.Overlay />
    <BaseDialog.Content aria-label="Custom surface">
      {(context) => (
        <div>
          Custom surface
          <Button onClick={context.close}>Close</Button>
        </div>
      )}
    </BaseDialog.Content>
  </BaseDialog.Portal>
</BaseDialog>
```

`BaseDialog.Content` children may be JSX or a function that receives `close`. Give `BaseDialog.Content` an
accessible name with `aria-label` or `aria-labelledby`.

### Focus and outside interaction

`modal` defaults to `true`: focus stays inside the surface, outside content is hidden from assistive
technology, and native outside pointer actions are prevented. Closing restores focus to the
trigger. Use `initialFocus` to choose the element that receives focus on open, or `false` to skip
the move, and `finalFocus` to choose where focus returns. Both apply only while `modal` is `true`.

Setting `modal={false}` allows focus to leave, but Escape and outside interactions still request
closure. `closeOnOverlayClick` controls outside pointer dismissal and `closeOnEscape` controls
Escape. Both default to `true`. A `false` value blocks that gesture and reports it through
`onClosePrevented`. Scroll locking is independent: `preventScroll` defaults to `true`. To allow
background page interaction, set `preventScroll={false}` and omit `BaseDialog.Overlay`.

### Styling and portal placement

The root renders no element. Apply `class` and object `style` to rendered parts; root `classes`
and `styles` set their slot defaults. See [Customization](https://moraine.subf.dev/docs/customization.md#the-4-layer-override-hierarchy).

Set root `mount` for a chosen container, including controlled surfaces without a Trigger.
`BaseDialog.Portal mount` overrides that default.

### State and exit lifecycle

Use `open` with `onOpenChange` for controlled visibility. `onExitComplete` waits for the overlay
and content exit animations to finish. Root `transition={false}` skips those animations, so the
surfaces unmount as soon as the modal closes and `onExitComplete` runs at once.

```tsx
<BaseDialog open={open()} onOpenChange={setOpen} onExitComplete={() => setLog('Exit complete')}>
  <BaseDialog.Portal>
    <BaseDialog.Overlay />
    <BaseDialog.Content aria-label="Lifecycle">
      {(context) => <Button onClick={context.close}>Dismiss</Button>}
    </BaseDialog.Content>
  </BaseDialog.Portal>
</BaseDialog>
```

### Keyboard interaction

| Key                    | Description                                             |
| ---------------------- | ------------------------------------------------------- |
| <kbd>Escape</kbd>      | Requests dismissal when `closeOnEscape` is not `false`. |
| <kbd>Tab</kbd>         | Moves focus forward within the modal focus scope.       |
| <kbd>Shift + Tab</kbd> | Moves focus backward within the modal focus scope.      |

## Examples

### Compose a custom surface

Mount overlay and content in one Portal. Content children can receive `close` from the render
callback.

```tsx
import { Button, BaseDialog } from 'moraine'

export function BaseDialogComposition() {
  return (
    <BaseDialog>
      <BaseDialog.Trigger as={Button}>Open Modal Surface</BaseDialog.Trigger>
      <BaseDialog.Portal>
        <BaseDialog.Overlay />
        <BaseDialog.Content aria-label="Custom Surface">
          {(context) => (
            <div class="p-4 b-1 b-border rounded-xl bg-background space-y-4">
              <h3 class="text-base font-semibold">Custom Surface</h3>
              <p class="text-xs text-muted-foreground">
                BaseDialog coordinates overlay, focus trap, and portal rendering.
              </p>
              <div class="flex justify-end">
                <Button size="xs" onClick={context.close}>
                  Close
                </Button>
              </div>
            </div>
          )}
        </BaseDialog.Content>
      </BaseDialog.Portal>
    </BaseDialog>
  )
}
```

### Open from parent state

A page button owns `open` through `onOpenChange`. Closing from inside still reports back to the
parent.

```tsx
import { Button, BaseDialog } from 'moraine'
import { createSignal } from 'solid-js'

export function Controlled() {
  const [open, setOpen] = createSignal(false)

  return (
    <div class="flex flex-wrap gap-3">
      <Button variant="outline" onClick={() => setOpen(true)}>
        Open controlled modal
      </Button>
      <BaseDialog open={open()} onOpenChange={setOpen}>
        <BaseDialog.Portal>
          <BaseDialog.Overlay />
          <BaseDialog.Content aria-label="Controlled modal">
            {(context) => (
              <div class="p-4 gap-4 grid">
                <p class="text-sm text-foreground">
                  The parent owns the open state through onOpenChange.
                </p>
                <Button class="justify-self-end" onClick={context.close}>
                  Close
                </Button>
              </div>
            )}
          </BaseDialog.Content>
        </BaseDialog.Portal>
      </BaseDialog>
    </div>
  )
}
```

### Omit the backdrop

Leave `BaseDialog.Overlay` out when the host surface already provides context.

```tsx
import { Button, BaseDialog } from 'moraine'

export function NoOverlay() {
  return (
    <BaseDialog>
      <BaseDialog.Trigger as={Button} variant="outline">
        Open without backdrop
      </BaseDialog.Trigger>
      <BaseDialog.Portal>
        <BaseDialog.Content aria-label="Modal without a backdrop">
          {(context) => (
            <div class="p-4 gap-4 grid">
              <p class="text-sm text-foreground">
                Omit BaseDialog.Overlay when the host surface provides context.
              </p>
              <Button class="justify-self-end" onClick={context.close}>
                Close
              </Button>
            </div>
          )}
        </BaseDialog.Content>
      </BaseDialog.Portal>
    </BaseDialog>
  )
}
```

### Drag a window by its title bar

Compose a custom header that moves the surface. Reset the offset when the modal closes.

```tsx
import { Button, Icon, BaseDialog } from 'moraine'
import { createSignal } from 'solid-js'

export function Draggable() {
  const [position, setPosition] = createSignal({ x: 0, y: 0 })
  const [isDragging, setIsDragging] = createSignal(false)

  const handlePointerDown = (event: PointerEvent) => {
    if (event.button !== 0) {
      return
    }

    const target = event.target as HTMLElement
    if (target.closest('button, a, input, [role="button"]')) {
      return
    }

    event.preventDefault()
    const currentTarget = event.currentTarget as HTMLElement
    currentTarget.setPointerCapture(event.pointerId)

    setIsDragging(true)
    const startX = event.clientX
    const startY = event.clientY
    const startPos = position()

    const handlePointerMove = (moveEvent: PointerEvent) => {
      setPosition({
        x: Math.round(startPos.x + (moveEvent.clientX - startX)),
        y: Math.round(startPos.y + (moveEvent.clientY - startY)),
      })
    }

    const handlePointerUp = (upEvent: PointerEvent) => {
      currentTarget.removeEventListener('pointermove', handlePointerMove)
      currentTarget.removeEventListener('pointerup', handlePointerUp)
      currentTarget.removeEventListener('pointercancel', handlePointerUp)
      try {
        currentTarget.releasePointerCapture(upEvent.pointerId)
      } catch {}
      setIsDragging(false)
    }

    currentTarget.addEventListener('pointermove', handlePointerMove)
    currentTarget.addEventListener('pointerup', handlePointerUp)
    currentTarget.addEventListener('pointercancel', handlePointerUp)
  }

  const resetPosition = () => setPosition({ x: 0, y: 0 })

  return (
    <BaseDialog
      onOpenChange={(open) => {
        if (!open) {
          resetPosition()
        }
      }}
    >
      <BaseDialog.Trigger as={Button} variant="outline" leading="i-lucide:move">
        Open Draggable Modal
      </BaseDialog.Trigger>
      <BaseDialog.Portal>
        <BaseDialog.Overlay />
        <BaseDialog.Content
          aria-label="Draggable Modal"
          style={{
            translate: `calc(-50% + ${position().x}px) calc(-50% + ${position().y}px)`,
            transition: isDragging() ? 'none' : 'translate 150ms ease-out',
          }}
        >
          {(context) => (
            <div class="b-1 b-border rounded-xl bg-card flex flex-col max-w-md w-full shadow-xl overflow-hidden">
              <div
                class="px-4 py-3 border-b border-border bg-muted/50 flex cursor-grab select-none items-center justify-between active:cursor-grabbing"
                onPointerDown={handlePointerDown}
              >
                <div class="flex gap-2 items-center">
                  <Icon name="i-lucide:grip-vertical" class="text-muted-foreground size-4" />
                  <h3 class="text-sm text-foreground font-semibold">Draggable Window</h3>
                </div>
                <Button
                  variant="ghost"
                  size="xs"
                  class="p-0 rounded-md size-6"
                  onClick={context.close}
                  aria-label="Close"
                >
                  <Icon name="i-lucide:x" class="size-3.5" />
                </Button>
              </div>

              <div class="p-4 space-y-3">
                <p class="text-xs text-muted-foreground leading-relaxed">
                  Click and drag the header title bar to reposition this modal dialog across the
                  viewport.
                </p>
                <div class="text-xs text-muted-foreground font-mono p-2.5 rounded-lg bg-muted flex items-center justify-between">
                  <span>Offset:</span>
                  <span>
                    X: {position().x}px, Y: {position().y}px
                  </span>
                </div>
              </div>

              <div class="p-3 border-t border-border bg-card flex items-center justify-between">
                <Button
                  size="xs"
                  variant="ghost"
                  leading="i-lucide:rotate-ccw"
                  onClick={resetPosition}
                  disabled={position().x === 0 && position().y === 0}
                >
                  Reset Position
                </Button>
                <Button size="xs" onClick={context.close}>
                  Done
                </Button>
              </div>
            </div>
          )}
        </BaseDialog.Content>
      </BaseDialog.Portal>
    </BaseDialog>
  )
}
```

### Track exit motion from a managed modal

Own visibility and wait until overlay and content finish their exit animations before treating
the modal as gone.

```tsx
import { Button, BaseDialog } from 'moraine'
import { createSignal } from 'solid-js'

export function BaseDialogLifecycle() {
  const [open, setOpen] = createSignal(false)
  const [log, setLog] = createSignal('Idle')

  return (
    <div class="space-y-3">
      <Button onClick={() => setOpen(true)}>Open Managed Modal</Button>
      <BaseDialog
        open={open()}
        onOpenChange={setOpen}
        onExitComplete={() => setLog('Exit transition fully completed')}
      >
        <BaseDialog.Portal>
          <BaseDialog.Overlay />
          <BaseDialog.Content aria-label="Lifecycle Monitored">
            {(context) => (
              <div class="p-4 b-1 b-border rounded-xl bg-background space-y-4">
                <h3 class="text-base font-semibold">Lifecycle Monitored</h3>
                <p class="text-xs text-muted-foreground">
                  Exit callbacks fire after presence transitions resolve.
                </p>
                <div class="flex justify-end">
                  <Button size="xs" onClick={context.close}>
                    Dismiss
                  </Button>
                </div>
              </div>
            )}
          </BaseDialog.Content>
        </BaseDialog.Portal>
      </BaseDialog>
      <p class="text-xs text-muted-foreground">
        Lifecycle log: <span class="text-foreground font-mono">{log()}</span>
      </p>
    </div>
  )
}
```

### Count completed exits

Open from a page button and increment a counter after exit motion completes.

```tsx
import { Button, BaseDialog } from 'moraine'
import { createSignal } from 'solid-js'

export function ExitLifecycle() {
  const [open, setOpen] = createSignal(false)
  const [exitCount, setExitCount] = createSignal(0)

  return (
    <div class="flex gap-3 items-center">
      <Button onClick={() => setOpen(true)}>Open modal</Button>
      <p class="text-sm text-muted-foreground">Completed exits: {exitCount()}</p>
      <BaseDialog
        open={open()}
        onOpenChange={setOpen}
        onExitComplete={() => setExitCount((count) => count + 1)}
      >
        <BaseDialog.Portal>
          <BaseDialog.Overlay />
          <BaseDialog.Content aria-label="Exit lifecycle example">
            {({ close }) => (
              <div class="p-5 rounded-xl bg-card shadow-xl">
                <p class="text-sm mb-4">
                  Close this modal and watch the count update after exit motion.
                </p>
                <Button onClick={close}>Close</Button>
              </div>
            )}
          </BaseDialog.Content>
        </BaseDialog.Portal>
      </BaseDialog>
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-closed` | `base-dialog-overlay`, `base-dialog-content` | Present when disclosure or transition content is closed. |
| `data-expanded` | `base-dialog-overlay`, `base-dialog-content` | Present when the panel, accordion, or menu is expanded. |
| `data-overlay-scroll` | `base-dialog-overlay` | Present when scrolling is owned by the overlay. |
| `data-transition` | `base-dialog-overlay`, `base-dialog-content` | Present while a target participates in a visibility transition. |

### Props

#### BaseDialog

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| closeOnEscape | boolean \| undefined | true | Whether Escape dismisses the shell.<br>`false` blocks Escape and reports it through `onClosePrevented`. |
| closeOnOverlayClick | boolean \| undefined | true | Whether a pointer press outside the content, such as on the backdrop, dismisses the shell.<br>`false` blocks the press and reports it through `onClosePrevented`. |
| defaultOpen | boolean \| undefined | false | Initial open state when uncontrolled. Ignored while `open` is set. |
| finalFocus | HTMLElement \| (() => HTMLElement \| undefined) \| false \| undefined | — | Element (or accessor resolving to one) that receives focus after the shell closes, or<br>`false` to skip the close-time focus restore. Defaults to the trigger, then the element<br>focused when the shell opened. An accessor that returns `undefined` restores no focus. Only<br>applies while `modal` is `true`. |
| id | string \| undefined | — | Unique identifier used to derive the content id, which becomes `<id>-content`. Generated<br>when omitted. |
| initialFocus | HTMLElement \| (() => HTMLElement \| undefined) \| false \| undefined | — | Element (or accessor resolving to one) that receives focus when the shell opens, or `false`<br>to skip the open-time focus move. Defaults to the first focusable element inside the<br>content, preferring an `[autofocus]` or `[data-autofocus]` descendant, and to the content<br>itself when opened by touch. An accessor that returns `undefined` falls back to the default.<br>Only applies while `modal` is `true`. |
| modal | boolean \| undefined | true | Whether the surface contains focus, restores focus on close, hides outside content from<br>assistive technology, and prevents the native default action of outside pointer events.<br>Outside pointer dismissal is controlled by `closeOnOverlayClick`.<br>Escape dismissal is controlled by `closeOnEscape`. When `false`, focus is neither trapped,<br>moved on open nor restored on close, so `initialFocus` and `finalFocus` have no effect. |
| mount | Node \| undefined | — | DOM node that `BaseDialog.Portal`, and the content of `Dialog`, `Sheet` and `Drawer`, render into,<br>for example a container element or a shadow root. A `mount` on `BaseDialog.Portal` takes<br>precedence. Defaults to the `body` of the trigger's document. |
| onClosePrevented | (() => void) \| undefined | — | Called with no arguments when Escape (`closeOnEscape` is `false`) or an outside press<br>(`closeOnOverlayClick` is `false`) tried to close the shell and was blocked. |
| onExitComplete | (() => void) \| undefined | — | Called once after a close has finished: the exit motion is over and the content is<br>unmounted. With `transition` set to `false` there is no motion to wait for. It is not called<br>when the content is removed while still open. |
| onOpenChange | ((open: boolean) => void) \| undefined | — | Called with the next open state when the trigger, a close part, Escape or an outside press<br>requests a change. It is not called when `open` is changed from outside, and it does not<br>apply the change itself when `open` is controlled: update `open` in the handler. |
| open | boolean \| undefined | — | Controlled open state. Pair it with `onOpenChange`; leave it `undefined` to let the component<br>manage its own state (see `defaultOpen`). |
| preventScroll | boolean \| undefined | true | Whether body scroll should be locked while the shell is present. |
| transition | boolean \| undefined | true | Whether enter and exit transition animations play. When `false`, the content and overlay<br>mount and unmount without waiting for an animation to end. The value is read when content<br>registers, so changes take effect the next time content mounts. |
| children | JSX.Element \| undefined | — | Composed trigger and content primitives. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`finalFocus` example**

```tsx
import { Button, Dialog } from 'moraine'

<Dialog finalFocus={() => document.getElementById('search') ?? undefined}>
  <Dialog.Trigger as={Button}>Open</Dialog.Trigger>
  <Dialog.Content title="Settings">Preferences</Dialog.Content>
</Dialog>
```

**`initialFocus` example**

```tsx
import { Button, Dialog } from 'moraine'
import { createSignal } from 'solid-js'

const [input, setInput] = createSignal<HTMLInputElement>()

<Dialog initialFocus={() => input()}>
  <Dialog.Trigger as={Button}>Rename</Dialog.Trigger>
  <Dialog.Content title="Rename">
    <input ref={setInput} />
  </Dialog.Content>
</Dialog>
```

**`mount` example**

```tsx
import { Button, Dialog } from 'moraine'

const container = document.getElementById('overlay-root') ?? document.body

<Dialog mount={container}>
  <Dialog.Trigger as={Button}>Open</Dialog.Trigger>
  <Dialog.Content title="Settings">Preferences</Dialog.Content>
</Dialog>
```

**`onOpenChange` example**

```tsx
import { Button, Dialog } from 'moraine'
import { createSignal } from 'solid-js'

const [open, setOpen] = createSignal(false)

<Dialog open={open()} onOpenChange={setOpen}>
  <Dialog.Trigger as={Button}>Open</Dialog.Trigger>
  <Dialog.Content title="Settings">Preferences</Dialog.Content>
</Dialog>
```

#### BaseDialog.Trigger

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| disabled | boolean \| undefined | — | Whether this trigger is disabled. |
| as | T \| undefined | 'button' | Element or component to render as. |
| children | JSX.Element \| undefined | — | Trigger label and visual content. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### BaseDialog.Portal

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| mount | Node \| undefined | — | DOM node the overlay and content render into. Takes precedence over `mount` on `BaseDialog`;<br>defaults to the `body` of the trigger's document. |
| children | JSX.Element \| undefined | — | Overlay and content parts rendered in the same portal. |

#### BaseDialog.Overlay

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| ref | ((element: HTMLDivElement) => void) \| undefined | — | Receives the mounted overlay element. |
| scrollable | boolean \| undefined | — | Whether the overlay element itself scrolls, so content taller than the viewport scrolls<br>inside the backdrop (with padding) while `preventScroll` keeps the page itself from<br>scrolling. |
| children | JSX.Element \| undefined | — | Optional elements rendered inside the overlay. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### BaseDialog.Content

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| as | T \| undefined | 'div' | Element or component to render as. |
| children | JSX.Element \| Component<ContentRenderProps> \| undefined | — | Content or render function inside the modal content surface.<br>A render function must declare its parameter, even when unused. A zero-argument<br>function is called as an accessor and is not mounted as a component. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### BaseDialog.Close

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| disabled | boolean \| undefined | — | Whether this trigger is disabled. |
| as | T \| undefined | 'button' | Element or component to render as. |
| children | JSX.Element \| undefined | — | Trigger label and visual content. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
