Components / OverlaysStable

Drawer

Opens details or a side task in a panel from the edge of the screen, so people keep their place on the page behind it.

View as Markdown

Playground

Write launch notes

Task in Q3 launch, due Friday.

Draft the notes for the Q3 launch email: what changed, who it helps and one screenshot per feature. Ana reviews them on Thursday.

Code

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

// Nacre Drawer: a panel that slides in from the end edge (or from the bottom: the consumer picks `side`, e.g. bottom on
// phones; it is not automatic) for details or a side task while the page stays in view. A native <dialog> opened with
// showModal(), so focus stays inside and the page is inert. React plus Tailwind classes only; needs nacre-theme.css.
// Motion (WAAPI): the panel slides in from its edge on the drawer curve (gentle 360, fast start, long soft landing, no
// overshoot so no gap opens at the edge) and leaves in base 240 out; the scrim, a light blur of the page under the
// overlay colour, fades with it. Drag the panel toward its edge to dismiss: it follows the pointer, a flick faster
// than 0.11 px/ms or a drag past a third of its size closes it from where it is, anything less settles back; dragging
// the other way meets friction that grows with distance. Opened or closed from the keyboard, only opacity animates.
// Reduced motion or [data-nacre-motion="off"]: no animation (dragging still works, it just snaps).

export type DrawerSide = 'end' | 'bottom'
export type DrawerSize = 'sm' | 'md' | 'lg'

export type DrawerPanelProps = {
  /** Pointer handlers for drag to dismiss (Drawer passes them; a static preview leaves them out). */
  onDragStart?: (e: PointerEvent<HTMLDivElement>) => void
  title: string
  description?: string
  children?: ReactNode
  footer?: ReactNode
  side?: DrawerSide
  size?: DrawerSize
  closeLabel?: string
  onClose?: () => void
  titleId?: string
  descriptionId?: string
  className?: string
}

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

// End side: 320, 416 or 512 px, always leaving 48 px of page visible. Bottom side: full width, up to 85% tall.
const endWidths: Record<DrawerSize, string> = {
  sm: 'w-[min(20rem,calc(100%_-_3rem))]',
  md: 'w-[min(26rem,calc(100%_-_3rem))]',
  lg: 'w-[min(32rem,calc(100%_-_3rem))]',
}

/** 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"]')
}

const DRAWER_EASE = 'cubic-bezier(.32, .72, 0, 1)'
const FLICK = 0.11
// 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)' }

/** Slides the panel in or out. `from` is where a drag left it (a transform), so a dismiss continues from there. */
function animateDrawer(d: HTMLDialogElement, enter: boolean, keyboard: boolean, from?: string): Promise<unknown> {
  if (!motionOk(d)) return Promise.resolve()
  const ms = enter ? tokenMs(d, '--nx-dur-gentle', 360) : tokenMs(d, '--nx-dur-base', 240)
  const style = getComputedStyle(d)
  const easing = enter ? DRAWER_EASE : style.getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
  const opts: KeyframeAnimationOptions = { duration: ms, easing, fill: enter ? 'none' : 'forwards' }
  const away = d.dataset.side === 'bottom' ? 'translateY(100%)' : style.direction === 'rtl' ? 'translateX(-100%)' : 'translateX(100%)'
  const fade = enter ? [{ opacity: 0 }, { opacity: 1 }] : [{ opacity: 1 }, { opacity: 0 }]
  const slide = enter ? [{ transform: away }, { transform: 'none' }] : [{ transform: from ?? 'none' }, { transform: away }]
  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 : slide, opts).finished.catch(() => undefined),
  ])
}

/** The visible panel. Used inside Drawer, and on its own for static previews. Close is last in DOM order. */
export function DrawerPanel({ title, description, children, footer, side = 'end', size = 'md', closeLabel = 'Close', onClose, onDragStart, titleId, descriptionId, className = '' }: DrawerPanelProps) {
  const auto = useId()
  const tid = titleId ?? `${auto}-title`
  const did = descriptionId ?? `${auto}-desc`
  const shape = side === 'bottom' ? 'mt-auto max-h-[85dvh] w-full rounded-t-xl' : `ms-auto h-full rounded-s-xl ${endWidths[size]}`
  return (
    <div data-part="panel" onPointerDown={onDragStart} className={`relative flex flex-col overflow-hidden bg-raised text-fg shadow-4 ${side === 'bottom' ? '' : 'touch-pan-y'} ${shape} ${className}`}>
      {side === 'bottom' && <div data-part="handle" aria-hidden="true" className="flex shrink-0 touch-none justify-center pt-2"><span className="h-1 w-9 rounded-full bg-line-strong" /></div>}
      <div data-part="header" className={`flex flex-col gap-1 p-6 pe-16 ${side === 'bottom' ? 'touch-none pt-3' : ''}`}>
        <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 Drawer({ open: openProp, defaultOpen = false, onOpenChange, ...panel }: DrawerProps) {
  const id = useId()
  const side = panel.side ?? 'end'
  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 returnTo = useRef<HTMLElement | null>(null)
  const prevOverflow = useRef('')
  const dragged = useRef<string | undefined>(undefined)

  // Drag to dismiss. One pointer; it follows 1:1 toward the edge and with friction the other way. The transform is set
  // on the panel itself (not through a variable on a parent), and a running entry is taken over from where it is.
  const dragStart = (e: PointerEvent<HTMLDivElement>) => {
    const panelEl = e.currentTarget
    const t = e.target as Element
    if (e.button !== 0 || !want.current || t.closest('button, a, input, textarea, select, label, [contenteditable]')) return
    const bottom = side === 'bottom'
    // On a bottom sheet, a body that is scrolled keeps the gesture for scrolling.
    const body = t.closest('[data-part="body"]')
    if (bottom && body && body.scrollTop > 0) return
    const sign = bottom || getComputedStyle(panelEl).direction !== 'rtl' ? 1 : -1
    const size = bottom ? panelEl.offsetHeight : panelEl.offsetWidth
    const running = panelEl.getAnimations()
    const m = running.length ? new DOMMatrix(getComputedStyle(panelEl).transform) : null
    const base = m ? sign * (bottom ? m.m42 : m.m41) : 0
    running.forEach((a) => a.cancel())
    const start = { x: e.clientX, y: e.clientY, t: performance.now() }
    let last = { d: base, t: start.t }
    let prev = last
    let moved = false
    const at = (d: number) => {
      // Past the resting edge the panel slows the further it is pulled.
      const shown = d >= 0 ? d : -Math.sqrt(-d) * 3
      return bottom ? `translateY(${shown}px)` : `translateX(${sign * shown}px)`
    }
    const move = (ev: globalThis.PointerEvent) => {
      if (ev.pointerId !== e.pointerId) return
      const d = base + sign * (bottom ? ev.clientY - start.y : ev.clientX - start.x)
      if (!moved && Math.abs(d - base) < 4) return
      if (!moved) {
        moved = true
        panelEl.setPointerCapture(ev.pointerId)
        // A drag is not a text selection.
        panelEl.style.userSelect = 'none'
        window.getSelection()?.removeAllRanges()
      }
      prev = last
      last = { d, t: performance.now() }
      panelEl.style.transform = at(d)
    }
    const end = (ev: globalThis.PointerEvent) => {
      if (ev.pointerId !== e.pointerId) return
      panelEl.removeEventListener('pointermove', move)
      panelEl.removeEventListener('pointerup', end)
      panelEl.removeEventListener('pointercancel', end)
      if (!moved) return
      panelEl.style.userSelect = ''
      // Speed over the last stretch of the gesture, so a flick at the end counts even after a slow drag.
      const velocity = (last.d - prev.d) / Math.max(1, last.t - prev.t)
      const now = panelEl.style.transform
      if (last.d > 0 && (last.d >= size / 3 || velocity > FLICK)) {
        dragged.current = now
        setOpen(false)
        return
      }
      panelEl.style.transform = ''
      if (motionOk(panelEl)) panelEl.animate([{ transform: now }, { transform: 'none' }], { duration: tokenMs(panelEl, '--nx-dur-base', 240), easing: DRAWER_EASE })
    }
    panelEl.addEventListener('pointermove', move)
    panelEl.addEventListener('pointerup', end)
    panelEl.addEventListener('pointercancel', end)
  }

  useEffect(() => {
    want.current = open
    const d = dialog.current
    if (!d) return
    // Keyboard rule: Esc, or a focus-visible trigger or button, means only opacity animates.
    const keyboard = kbd.current || Boolean(document.activeElement?.matches(':focus-visible'))
    kbd.current = false
    if (open) {
      if (d.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 animateDrawer(d, true, keyboard)
    } else if (d.open) {
      const from = dragged.current
      dragged.current = undefined
      void animateDrawer(d, false, keyboard && !from, from).then(() => {
        if (!want.current && d.open) d.close()
      })
    }
  }, [open])

  useEffect(() => {
    const d = dialog.current
    return () => {
      if (d?.open) document.documentElement.style.overflow = prevOverflow.current
    }
  }, [])

  return (
    <dialog
      ref={dialog}
      data-part="root"
      data-side={side}
      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()
        const p = dialog.current?.querySelector<HTMLElement>('[data-part="panel"]')
        if (p) p.style.transform = ''
        returnTo.current?.focus()
        if (want.current) setOpen(false)
      }}
      className={`fixed inset-0 m-0 size-full max-h-none max-w-none overflow-hidden border-0 bg-transparent p-0 text-fg backdrop:bg-transparent open:flex ${side === 'bottom' ? 'flex-col' : ''}`}
    >
      <div data-part="backdrop" aria-hidden="true" onClick={() => setOpen(false)} style={SCRIM} className="fixed inset-0 bg-overlay/60" />
      <DrawerPanel {...panel} side={side} onClose={() => setOpen(false)} onDragStart={dragStart} titleId={`${id}-title`} descriptionId={`${id}-desc`} />
    </dialog>
  )
}

Usage

When to use

  • Task details from a list or a board: open, read, edit, close, next task.
  • Filters and settings for the current view.
  • On phones, a bottom sheet for the same content.

Choose something else when

  • It asks for a yes or no decision: use Modal.
  • The content is the main thing on the page: use its own page.

In the Nacre workspace

Task details

Clicking Write launch notes on the board opens a Drawer from the end edge with the task, its owner and Mark as done. The board stays visible behind the scrim.

Filters on a phone

At 375 px the Filters button opens a bottom Drawer with the filter controls and Apply; it covers at most 85% of the screen.

Do and don't

  • DoKeep one Drawer at a time; replace its content for the next item.

    Don'tStack a Drawer on a Drawer.

  • DoUse the bottom side on narrow screens.

    Don'tSqueeze an end Drawer below 320 px wide.

Anatomy

Write launch notes

Task in Q3 launch, due Friday.

Draft the notes for the Q3 launch email: what changed, who it helps and one screenshot per feature. Ana reviews them on Thursday.
  1. Panel. Raised surface, full height, radius xl on the start corners, shadow 4.
  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.
  5. Body. Body text in fg; scrolls on its own.
  6. Footer. A 1 px line-subtle rule and the 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. Names the dialog.
descriptionType stringDefault -One line under the title; describes the dialog.
childrenType ReactNodeDefault -The body; scrolls on its own.
footerType ReactNodeDefault -Buttons at the bottom end.
sideType 'end' | 'bottom'Default 'end'The edge it slides from. end follows the reading direction (right in English).
sizeType 'sm' | 'md' | 'lg'Default 'md'End side width: 320, 416 or 512 px, always leaving 48 px of page. Bottom is full width.
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.
classNameType stringDefault -DrawerPanel: extra classes for the panel.
onCloseType () => voidDefault -DrawerPanel: called by its close button, for static previews.

Motion

OpenProperty transform (slides in from its edge on the drawer curve, cubic-bezier(.32, .72, 0, 1), no overshoot); scrim opacity over a 6 px blurDuration gentle 360Easing outKeyboard Opened from a focused trigger: opacity only.
CloseProperty transform (slides back to its edge); scrim opacityDuration base 240Easing outKeyboard Esc or a focused button: opacity only.
Drag toward the edgeProperty transform follows the pointer 1:1; the other way, friction (square root of the distance)Duration none 0Easing linearKeyboard Esc or Close instead.
Let goProperty faster than 0.11 px/ms or past a third: closes from where it is; else settles back on the drawer curveDuration base 240Easing outKeyboard None.

Write launch notes

Task in Q3 launch, due Friday.

Draft the notes for the Q3 launch email: what changed, who it helps and one screenshot per feature. Ana reviews them on Thursday.

Accessibility

Keyboard

Tab / Shift+Tab
Moves between the controls inside; focus never leaves the drawer.
Esc
Closes it and returns focus to the element that opened it. Dragging is a pointer shortcut; Esc and Close always work.

ARIA and semantics

  • A native modal dialog: the page behind is inert, and the drawer is named by its title.
  • Focus goes to the first control; the close button is last in tab order.
  • In right-to-left pages the end side is the left edge, and it slides from there.

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