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

Status: Stable. Group: Overlays.

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

## When not to use

- It asks for a yes or no decision. Use Modal instead.
- The content is the main thing on the page. Use its own page instead.

## Scenarios

### 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 avoid

- Do: Keep one Drawer at a time; replace its content for the next item.
- Avoid: Stack a Drawer on a Drawer.
- Do: Use the bottom side on narrow screens.
- Avoid: Squeeze an end Drawer below 320 px wide.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `title` | `string` |  | Required. Names the dialog. |
| `description` | `string` |  | One line under the title; describes the dialog. |
| `children` | `ReactNode` |  | The body; scrolls on its own. |
| `footer` | `ReactNode` |  | Buttons at the bottom end. |
| `side` | `'end' \| 'bottom'` | `'end'` | The edge it slides from. end follows the reading direction (right in English). |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | End side width: 320, 416 or 512 px, always leaving 48 px of page. Bottom is full width. |
| `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. |
| `className` | `string` |  | DrawerPanel: extra classes for the panel. |
| `onClose` | `() => void` |  | DrawerPanel: called by its close button, for static previews. |

## Anatomy

1. Panel (`data-part="panel"`): Raised surface, full height, radius xl on the start corners, shadow 4.
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.
5. Body (`data-part="body"`): Body text in fg; scrolls on its own.
6. Footer (`data-part="footer"`): A 1 px line-subtle rule and the 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 (slides in from its edge on the drawer curve, cubic-bezier(.32, .72, 0, 1), no overshoot); scrim opacity over a 6 px blur | gentle | out | Opened from a focused trigger: opacity only. |
| Close | transform (slides back to its edge); scrim opacity | base | out | Esc or a focused button: opacity only. |
| Drag toward the edge | transform follows the pointer 1:1; the other way, friction (square root of the distance) | none | linear | Esc or Close instead. |
| Let go | faster than 0.11 px/ms or past a third: closes from where it is; else settles back on the drawer curve | base | out | None. |

## Accessibility

| Keys | Action |
| --- | --- |
| 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. |

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

## Code

### Drawer.tsx

```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>
  )
}
```

## HTML

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

```html
<dialog data-part="root" data-side="end" aria-labelledby="_R_0_-title" aria-describedby="_R_0_-desc" class="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 ">
  <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 flex-col overflow-hidden bg-raised text-fg shadow-4 touch-pan-y ms-auto h-full rounded-s-xl w-[min(26rem,calc(100%_-_3rem))] ">
    <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">Write launch notes</h2>
      <p id="_R_0_-desc" data-part="description" class="text-body text-fg-muted">Task in Q3 launch, due Friday.</p>
    </div>
    <div data-part="body" class="min-h-0 flex-1 overflow-y-auto px-6 pb-6 text-body text-fg">Draft the notes for the Q3 launch email: what changed, who it helps and one screenshot per feature. Ana reviews them on Thursday.</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 ">Close</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-action text-on-action enabled:hover:bg-action-hover 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 ">Mark as done</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

- [Tabs](https://enxm.me/services/design-systems/nacre/components/tabs)
- [Modal](https://enxm.me/services/design-systems/nacre/components/modal)
- [Table](https://enxm.me/services/design-systems/nacre/components/table)
