# Modal

Asks for a decision or a short task that must be finished or dismissed before going on, on top of a dimmed page.

Status: Stable. Group: Overlays.

## When to use

- Confirming something that is hard to undo: delete a project, remove a member.
- A short form that belongs to the current page: rename a project, invite one person.

## When not to use

- People need the page in view while they work on it. Use Drawer instead.
- It only reports that something happened. Use Alert and toast instead.
- It is a full flow with several screens. Use its own page with Progress and steps instead.

## Scenarios

### Delete a project

Delete Q3 launch opens a small Modal that says what goes to Trash and for how long. Cancel is focused first, so Enter never deletes by accident.

### Rename

Rename in the project menu opens a Modal with one Input and Save. The field is focused when it opens, and Esc puts focus back on the menu button.

## Do and avoid

- Do: Title it with the question: Delete Q3 launch?
- Avoid: Title it Are you sure?
- Do: Name the buttons by what they do: Delete project.
- Avoid: Use OK and Cancel for a destructive choice.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `title` | `string` |  | Required. The question or task; names the dialog. |
| `description` | `string` |  | One sentence under the title; describes the dialog. |
| `children` | `ReactNode` |  | The body. It scrolls when the content is taller than the screen. |
| `footer` | `ReactNode` |  | Buttons at the bottom end, most important last. |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Panel width up to 384, 512 or 640 px. |
| `closeLabel` | `string` | `'Close'` | Accessible name of the close button. |
| `open` | `boolean` |  | Controlled open state. Pair with onOpenChange. |
| `defaultOpen` | `boolean` | `false` | Open on first render when uncontrolled. |
| `onOpenChange` | `(open: boolean) => void` |  | Called with false on Esc, a scrim click or the close button. Footer buttons call your own handler. |
| `keyboard` | `boolean` | `false` | Set it when a keyboard shortcut opens the dialog: only opacity animates. Without it, Modal reads the focused element. |
| `className` | `string` |  | ModalPanel: extra classes for the panel. |
| `onClose` | `() => void` |  | ModalPanel: called by its close button, for static previews. |

## Anatomy

1. Panel (`data-part="panel"`): Raised surface, radius xl, shadow 4, centred with 16 px around it.
2. Header (`data-part="header"`): 24 px padding, 64 px at the end to clear the close button.
3. Title (`data-part="title"`): Heading 3 in fg-strong, an h2.
4. Description (`data-part="description"`): Body in fg-muted, 4 px under the title.
5. Body (`data-part="body"`): Body text in fg; scrolls on its own when tall.
6. Footer (`data-part="footer"`): A 1 px line-subtle rule, 16 by 24 px padding, buttons at the end.
7. Close (`data-part="close"`): Round 40 px icon button (white, hairline ring, shadow 1, the same as Button shape round) at the top end, last in tab order.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Open | transform (scale .96 to 1, centred), opacity; settles with a small overshoot | gentle | spring | Opened from a focused trigger: opacity only. |
| Scrim | opacity of the overlay colour over a 6 px blur of the page | gentle | out | Same, opacity only. |
| Close | transform (scale 1 to .96), opacity; scrim opacity | quick | out | Esc or a focused button: opacity only. |

## Accessibility

| Keys | Action |
| --- | --- |
| Tab / Shift+Tab | Moves between the controls inside; focus never leaves the dialog. |
| Esc | Closes it and returns focus to the element that opened it. |

- A native dialog opened with showModal(): the page behind is inert and the dialog is named by its title and described by its description.
- Focus goes to the first control (Cancel or a field); the close button is last in tab order.
- Page scroll is locked while it is open and restored when it closes.

## Code

### Modal.tsx

```tsx
'use client'
import { useEffect, useId, useRef, useState, type ReactNode } from 'react'

// Nacre Modal: a decision or a short task that must be finished or dismissed before going on. A native <dialog>
// opened with showModal(): the browser keeps focus inside, makes the page inert and turns Esc into a cancel event.
// React plus Tailwind classes only; needs nacre-theme.css. Motion (WAAPI): the panel scales from .96 and fades in on the
// spring curve (gentle 360, it settles with a small overshoot) and leaves in quick 160 out; the scrim, a light blur of
// the page under the overlay colour, fades with it. It stays centred (a modal has no trigger to grow from). Opened or
// closed from the keyboard, only opacity animates: Modal reads the focused element, or set keyboard when a shortcut
// opens it. Reduced motion or [data-nacre-motion="off"]: no animation. Focus stays inside: showModal() makes the page
// inert, and the first field or Cancel takes focus.

export type ModalSize = 'sm' | 'md' | 'lg'

export type ModalPanelProps = {
  title: string
  description?: string
  children?: ReactNode
  footer?: ReactNode
  size?: ModalSize
  closeLabel?: string
  onClose?: () => void
  titleId?: string
  descriptionId?: string
  className?: string
}

export type ModalProps = Omit<ModalPanelProps, 'onClose' | 'titleId' | 'descriptionId'> & {
  open?: boolean
  defaultOpen?: boolean
  onOpenChange?: (open: boolean) => void
  keyboard?: boolean
}

// The scrim blurs the page a little. Set inline (prefixed first) so no CSS minifier can drop either line.
const SCRIM = { WebkitBackdropFilter: 'blur(6px)', backdropFilter: 'blur(6px)' }

const widths: Record<ModalSize, string> = { sm: 'max-w-[24rem]', md: 'max-w-[32rem]', lg: 'max-w-[40rem]' }

/** Reads a duration token (240ms or .24s) in ms from the element, so slow motion stretches it too. */
function tokenMs(el: Element, name: string, fallback: number): number {
  const v = getComputedStyle(el).getPropertyValue(name).trim()
  const n = parseFloat(v)
  if (!Number.isFinite(n)) return fallback
  return v.endsWith('ms') ? n : v.endsWith('s') ? n * 1000 : n
}

/** Reduced motion (OS) or the Nacre Motion switch off: no movement. */
function motionOk(el: Element): boolean {
  return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}

function animateModal(d: HTMLDialogElement, enter: boolean, keyboard: boolean): Promise<unknown> {
  if (!motionOk(d)) return Promise.resolve()
  const ms = enter ? tokenMs(d, '--nx-dur-gentle', 360) : tokenMs(d, '--nx-dur-quick', 160)
  const style = getComputedStyle(d)
  const out = style.getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
  const spring = style.getPropertyValue('--nx-ease-spring').trim() || out
  const opts: KeyframeAnimationOptions = { duration: ms, easing: out, fill: enter ? 'none' : 'forwards' }
  const fade = enter ? [{ opacity: 0 }, { opacity: 1 }] : [{ opacity: 1 }, { opacity: 0 }]
  const scaleFrames = enter
    ? [{ opacity: 0, transform: 'scale(.96)' }, { opacity: 1, transform: 'none' }]
    : [{ opacity: 1, transform: 'none' }, { opacity: 0, transform: 'scale(.96)' }]
  const backdrop = d.querySelector('[data-part="backdrop"]')
  const panel = d.querySelector('[data-part="panel"]')
  return Promise.all([
    backdrop?.animate(fade, opts).finished.catch(() => undefined),
    panel?.animate(keyboard ? fade : scaleFrames, enter && !keyboard ? { ...opts, easing: spring } : opts).finished.catch(() => undefined),
  ])
}

/** The visible sheet. Used inside Modal, and on its own for static previews. Close is last in DOM order, so the
 *  dialog focuses the first real control (a field or Cancel) when it opens. */
export function ModalPanel({ title, description, children, footer, size = 'md', closeLabel = 'Close', onClose, titleId, descriptionId, className = '' }: ModalPanelProps) {
  const auto = useId()
  const tid = titleId ?? `${auto}-title`
  const did = descriptionId ?? `${auto}-desc`
  return (
    <div data-part="panel" className={`relative flex max-h-full w-full flex-col overflow-hidden rounded-xl bg-raised text-fg shadow-4 ${widths[size]} ${className}`}>
      <div data-part="header" className="flex flex-col gap-1 p-6 pe-16">
        <h2 id={tid} data-part="title" className="text-heading-3 text-fg-strong">{title}</h2>
        {description && <p id={did} data-part="description" className="text-body text-fg-muted">{description}</p>}
      </div>
      {children && <div data-part="body" className="min-h-0 flex-1 overflow-y-auto px-6 pb-6 text-body text-fg">{children}</div>}
      {footer && <div data-part="footer" className="flex flex-wrap justify-end gap-2 border-t border-line-subtle px-6 py-4">{footer}</div>}
      <button
        type="button"
        data-part="close"
        aria-label={closeLabel}
        onClick={onClose}
        className="absolute end-4 top-4 inline-flex size-10 cursor-pointer items-center justify-center rounded-full border border-line-subtle bg-secondary text-icon-strong shadow-1 transition-colors duration-(--nx-dur-quick) ease-out hover:border-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus"
      >
        <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-4">
          <path d="M4 4l8 8M12 4l-8 8" />
        </svg>
      </button>
    </div>
  )
}

export function Modal({ open: openProp, defaultOpen = false, onOpenChange, keyboard = false, ...panel }: ModalProps) {
  const id = useId()
  const [inner, setInner] = useState(defaultOpen)
  const open = openProp ?? inner
  const setOpen = (next: boolean) => {
    // Already closing (scrim, Close and Esc in a row during the exit): onOpenChange(false) fires once.
    if (!next && !want.current) return
    if (openProp === undefined) {
      setInner(next)
      if (!next) want.current = false
    }
    onOpenChange?.(next)
  }
  const dialog = useRef<HTMLDialogElement>(null)
  const want = useRef(open)
  const kbd = useRef(false)
  const kbdOpen = useRef(keyboard)
  const returnTo = useRef<HTMLElement | null>(null)
  const prevOverflow = useRef('')

  useEffect(() => {
    kbdOpen.current = keyboard
  })

  useEffect(() => {
    want.current = open
    const d = dialog.current
    if (!d) return
    // Keyboard rule: Esc, a focus-visible trigger or button, or the keyboard prop on opening: only opacity animates.
    const keys = kbd.current || Boolean(document.activeElement?.matches(':focus-visible'))
    kbd.current = false
    if (open) {
      if (d.open) {
        // Reopened during its exit: drop the exit and stay open.
        for (const a of d.getAnimations({ subtree: true })) a.cancel()
        return
      }
      returnTo.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
      prevOverflow.current = document.documentElement.style.overflow
      document.documentElement.style.overflow = 'hidden'
      d.showModal()
      void animateModal(d, true, keys || kbdOpen.current)
    } else if (d.open) {
      void animateModal(d, false, keys).then(() => {
        if (!want.current && d.open) d.close()
      })
    }
  }, [open])

  // Unmounted while open: give the page its scroll back.
  useEffect(() => {
    const d = dialog.current
    return () => {
      if (d?.open) document.documentElement.style.overflow = prevOverflow.current
    }
  }, [])

  return (
    <dialog
      ref={dialog}
      aria-labelledby={`${id}-title`}
      aria-describedby={panel.description ? `${id}-desc` : undefined}
      onCancel={(e) => {
        e.preventDefault()
        kbd.current = true
        setOpen(false)
      }}
      onClose={() => {
        document.documentElement.style.overflow = prevOverflow.current
        for (const a of dialog.current?.getAnimations({ subtree: true }) ?? []) a.cancel()
        returnTo.current?.focus()
        if (want.current) setOpen(false)
      }}
      data-part="root"
      className="fixed inset-0 m-0 size-full max-h-none max-w-none items-center justify-center border-0 bg-transparent p-4 text-fg backdrop:bg-transparent open:flex"
    >
      <div data-part="backdrop" aria-hidden="true" onClick={() => setOpen(false)} style={SCRIM} className="fixed inset-0 bg-overlay/60" />
      <ModalPanel {...panel} onClose={() => setOpen(false)} titleId={`${id}-title`} descriptionId={`${id}-desc`} />
    </dialog>
  )
}
```

## HTML

The default example as plain HTML, for any stack. Needs nacre-theme.css.

```html
<dialog aria-labelledby="_R_0_-title" aria-describedby="_R_0_-desc" data-part="root" class="fixed inset-0 m-0 size-full max-h-none max-w-none items-center justify-center border-0 bg-transparent p-4 text-fg backdrop:bg-transparent open:flex">
  <div data-part="backdrop" aria-hidden="true" style="-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)" class="fixed inset-0 bg-overlay/60"></div>
  <div data-part="panel" class="relative flex max-h-full w-full flex-col overflow-hidden rounded-xl bg-raised text-fg shadow-4 max-w-[32rem] ">
    <div data-part="header" class="flex flex-col gap-1 p-6 pe-16">
      <h2 id="_R_0_-title" data-part="title" class="text-heading-3 text-fg-strong">Delete Q3 launch?</h2>
      <p id="_R_0_-desc" data-part="description" class="text-body text-fg-muted">This moves the project and its 24 tasks to Trash.</p>
    </div>
    <div data-part="body" class="min-h-0 flex-1 overflow-y-auto px-6 pb-6 text-body text-fg">Members lose access right away. You can restore the project from Trash within 30 days.</div>
    <div data-part="footer" class="flex flex-wrap justify-end gap-2 border-t border-line-subtle px-6 py-4">
      <button type="button" data-part="root" class="group/button relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center rounded-full font-ui font-[600] whitespace-nowrap transition-[color,background-color,border-color,scale] duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:not-focus-visible:scale-[.97] disabled:cursor-not-allowed aria-disabled:cursor-progress border border-line bg-secondary text-fg-strong enabled:hover:border-line-strong disabled:border-line-subtle disabled:text-fg-disabled h-10 px-4 text-label ">
        <span data-part="label" class="inline-flex items-center gap-2 transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ">Cancel</span>
      </button>
      <button type="button" data-part="root" class="group/button relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center rounded-full font-ui font-[600] whitespace-nowrap transition-[color,background-color,border-color,scale] duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:not-focus-visible:scale-[.97] disabled:cursor-not-allowed aria-disabled:cursor-progress bg-error-strong text-on-action enabled:hover:bg-error disabled:bg-sunken disabled:text-fg-disabled disabled:shadow-[inset_0_0_0_1px_var(--nx-line-subtle)] h-10 px-4 text-label ">
        <span data-part="label" class="inline-flex items-center gap-2 transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ">Delete project</span>
      </button>
    </div>
    <button type="button" data-part="close" aria-label="Close" class="absolute end-4 top-4 inline-flex size-10 cursor-pointer items-center justify-center rounded-full border border-line-subtle bg-secondary text-icon-strong shadow-1 transition-colors duration-(--nx-dur-quick) ease-out hover:border-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" class="size-4">
        <path d="M4 4l8 8M12 4l-8 8"></path>
      </svg>
    </button>
  </div>
</dialog>
```

## Related

- [Button](https://enxm.me/services/design-systems/nacre/components/button)
- [Alert and toast](https://enxm.me/services/design-systems/nacre/components/alert)
- [Drawer](https://enxm.me/services/design-systems/nacre/components/drawer)
