Components / OverlaysStable

Modal

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

View as Markdown

Playground

Delete Q3 launch?

This moves the project and its 24 tasks to Trash.

Members lose access right away. You can restore the project from Trash within 30 days.

Code

Modal.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>
  )
}

Usage

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.

Choose something else when

In the Nacre workspace

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 don't

  • DoTitle it with the question: Delete Q3 launch?

    Don'tTitle it Are you sure?

  • DoName the buttons by what they do: Delete project.

    Don'tUse OK and Cancel for a destructive choice.

Anatomy

Delete Q3 launch?

This moves the project and its 24 tasks to Trash.

Members lose access right away. You can restore the project from Trash within 30 days.
  1. Panel. Raised surface, radius xl, shadow 4, centred with 16 px around it.
  2. Header. 24 px padding, 64 px at the end to clear the close button.
  3. Title. Heading 3 in fg-strong, an h2.
  4. Description. Body in fg-muted, 4 px under the title.
  5. Body. Body text in fg; scrolls on its own when tall.
  6. Footer. A 1 px line-subtle rule, 16 by 24 px padding, buttons at the end.
  7. 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.

API

titleType stringDefault -Required. The question or task; names the dialog.
descriptionType stringDefault -One sentence under the title; describes the dialog.
childrenType ReactNodeDefault -The body. It scrolls when the content is taller than the screen.
footerType ReactNodeDefault -Buttons at the bottom end, most important last.
sizeType 'sm' | 'md' | 'lg'Default 'md'Panel width up to 384, 512 or 640 px.
closeLabelType stringDefault 'Close'Accessible name of the close button.
openType booleanDefault -Controlled open state. Pair with onOpenChange.
defaultOpenType booleanDefault falseOpen on first render when uncontrolled.
onOpenChangeType (open: boolean) => voidDefault -Called with false on Esc, a scrim click or the close button. Footer buttons call your own handler.
keyboardType booleanDefault falseSet it when a keyboard shortcut opens the dialog: only opacity animates. Without it, Modal reads the focused element.
classNameType stringDefault -ModalPanel: extra classes for the panel.
onCloseType () => voidDefault -ModalPanel: called by its close button, for static previews.

Motion

OpenProperty transform (scale .96 to 1, centred), opacity; settles with a small overshootDuration gentle 360Easing springKeyboard Opened from a focused trigger: opacity only.
ScrimProperty opacity of the overlay colour over a 6 px blur of the pageDuration gentle 360Easing outKeyboard Same, opacity only.
CloseProperty transform (scale 1 to .96), opacity; scrim opacityDuration quick 160Easing outKeyboard Esc or a focused button: opacity only.

Delete Q3 launch?

This moves the project and its 24 tasks to Trash.

Members lose access right away. You can restore the project from Trash within 30 days.

Accessibility

Keyboard

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.

ARIA and semantics

  • 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.

Contrast

Titlefg-strong on raisedLight 19.01:1Dark 14.96:1Needs 4.5:1
Bodyfg on raisedLight 14.89:1Dark 11.32:1Needs 4.5:1
Descriptionfg-muted on raisedLight 5.57:1Dark 6.14:1Needs 4.5:1
Close iconicon on raisedLight 14.89:1Dark 11.32:1Needs 3:1