# Drawer

A drawer (a sheet) is a `<dialog>` on an edge of the screen: a bottom sheet of filters on a phone, a navigation panel from the side. It is a [Dialog](dialog.md), with one prop that says which edge and one gesture: drag it toward that edge and let go past a quarter of its size, or flick it, and it slides out and closes. The library tracks the pointer and writes where it is; your stylesheet places the drawer and moves it.

## Anatomy

```tsx
import { Drawer } from "@funstack/ui/drawer";

<Drawer.Root>                                    {/* no DOM: ids, mode, state */}
  <Drawer.Trigger>Filters</Drawer.Trigger>
  <Drawer.Popup side="bottom">                   {/* dialog[data-side=bottom] */}
    <div className="grabber" aria-hidden />      {/* decoration, yours */}
    <Drawer.Title>Filters</Drawer.Title>
    <div className="drawer-body">…</div>         {/* scrolls; a press here never drags */}
    <Drawer.Close>Done</Drawer.Close>
  </Drawer.Popup>
</Drawer.Root>
```

- **Every part is a Dialog part.** Root, Trigger, Popup, Title, Description, Close and Form run the code of the Dialog parts of the same name. Everything the [Dialog](dialog.md) page says applies unless this page says otherwise: the two modes, focus and focus return, Escape, `keepMounted`, `initialFocus`, `transition`, `render`, the Form. A `Dialog.Close` inside a `Drawer.Popup` closes the drawer, and an [AlertDialog](alert-dialog.md) nested in a drawer is its confirm.
- **What it adds.** `side` (the edge, rendered as `data-side`), `swipeDismiss` (on by default), and `lightDismiss` on by default for a modal drawer.
- **What it does not.** No handle, backdrop, portal or viewport part (a grabber is a `<div aria-hidden>`: the whole drawer is the grab area; the backdrop is `::backdrop`), no snap points, no swipe from the screen edge to open, no scaling of the page behind it. The library ships no CSS and writes no inset, size or transform.
- **Always render a Close.** It is the way to close the drawer before hydration on a phone, and the alternative to the swipe that WCAG 2.5.1 asks for. Development warns when a drawer with the swipe has shown without one.

```tsx title="DrawerFilters.tsx"
"use client";
import { startTransition, useState } from "react";
import { Drawer } from "@funstack/ui/drawer";
import { fakeSave } from "./fake-api.js";

const brands = [
  "Acme",
  "Borealis",
  "Cobalt",
  "Dune",
  "Ember",
  "Fjord",
  "Granite",
  "Harbor",
  "Iris",
  "Juniper",
  "Kestrel",
  "Lumen",
];

// A bottom sheet. Drag the grabber, the title or the footer down to close it (mouse, pen or
// touch): past a quarter of its height or with a flick it slides out and closes, which
// `onOpenChange` hears as a dismissal; a short drag returns. The list scrolls in its own
// `overflow-y: auto` body, where a press scrolls and never drags. "Apply" is a Close with an
// `action`: pending while the fake request runs, then the sheet closes.
export function DrawerFilters() {
  const [applied, setApplied] = useState<readonly string[]>([]);
  const [draft, setDraft] = useState<readonly string[]>([]);
  const [lastClose, setLastClose] = useState("");

  return (
    <div className="demo-row">
      <Drawer.Root
        defaultOpen={false}
        openChangeAction={(open) => {
          if (open) setDraft(applied);
        }}
        onOpenChange={(_open, { event }) =>
          setLastClose(event?.type === "pointerup" ? "swiped away" : "dismissed")
        }
      >
        <Drawer.Trigger className="demo-button">Filters ({applied.length})</Drawer.Trigger>
        <Drawer.Popup className="demo-drawer" side="bottom">
          <div className="demo-drawer-grabber" aria-hidden />
          <Drawer.Title>Brands</Drawer.Title>
          <div className="demo-drawer-body">
            {brands.map((brand) => (
              <label key={brand} className="demo-drawer-row">
                <input
                  type="checkbox"
                  checked={draft.includes(brand)}
                  onChange={(event) =>
                    setDraft((current) =>
                      event.target.checked
                        ? [...current, brand]
                        : current.filter((b) => b !== brand),
                    )
                  }
                />
                {brand}
              </label>
            ))}
          </div>
          <div className="demo-drawer-footer">
            <Drawer.Close className="demo-button">Cancel</Drawer.Close>
            <Drawer.Close
              className="demo-button demo-primary"
              action={async () => {
                await fakeSave("filters", { ms: 700 });
                // After an await: wrap the update yourself (React limitation).
                startTransition(() => {
                  setApplied(draft);
                  setLastClose("applied");
                });
              }}
            >
              {({ pending }) => (
                <>
                  {pending && <span className="demo-spinner" aria-hidden />}
                  Apply
                </>
              )}
            </Drawer.Close>
          </div>
        </Drawer.Popup>
      </Drawer.Root>
      <output className="demo-readout">
        {applied.length === 0 ? "All brands" : applied.join(", ")}
        {lastClose !== "" && ` (last close: ${lastClose})`}
      </output>
    </div>
  );
}
```

```css title="drawer.css"
/* Drawer: the Popup is the <dialog> itself, with `data-side`. The library places nothing and
   moves nothing: these rules put it on its edge, slide it in and out, and follow the swipe
   through `--drawer-swipe-x` / `-y` / `-progress`, which the library writes while a pointer
   drags (with `data-swiping`). One `transition` on `translate` is the enter, the exit, the
   release of a swipe and the return of a cancelled one. */

.demo-drawer {
  position: fixed;
  margin: 0;
  padding: 0 20px 16px;
  border: 0;
  box-sizing: border-box;
  max-inline-size: none;
  max-block-size: none;
  flex-direction: column;
  gap: 8px;
  background: var(--color-bg);
  color: var(--color-text);
  box-shadow: 0 0 40px rgb(0 0 0 / 0.3);
  transition:
    translate 300ms cubic-bezier(0.32, 0.72, 0, 1),
    display 300ms allow-discrete,
    overlay 300ms allow-discrete;
}

.demo-drawer h2 {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 1.1rem;
}

/* Placement per side. `:where()` keeps the closed positions at the specificity of
   `.demo-drawer`, below the `:open` rule. */
.demo-drawer:where([data-side="bottom"]) {
  inset: auto 0 0 0;
  inline-size: 100%;
  max-block-size: min(70dvh, 32rem);
  border-radius: 14px 14px 0 0;
  translate: 0 100%;
  /* The dialog does not scroll: its body does (a bottom drawer's swipe owns the vertical axis
     for touch, so the dialog itself could not be scrolled by touch). */
  overflow: hidden;
}

.demo-drawer:where([data-side="inline-start"]) {
  inset-block: 0;
  inset-inline: 0 auto;
  block-size: 100dvh;
  inline-size: min(18rem, 85vw);
  padding-block-start: 16px;
  /* A side drawer scrolls in the Popup itself; its swipe is horizontal. */
  overflow-y: auto;
}

.demo-drawer:where([data-side="inline-start"]:dir(ltr)) {
  translate: -100% 0;
}

.demo-drawer:where([data-side="inline-start"]:dir(rtl)) {
  translate: 100% 0;
}

/* Open: rest at the edge, moved by the swipe while a pointer drags. `display` only here: a
   closed <dialog> keeps the browser's `display: none`. */
.demo-drawer:open {
  display: flex;
  translate: var(--drawer-swipe-x, 0px) var(--drawer-swipe-y, 0px);
}

@starting-style {
  .demo-drawer[data-side="bottom"]:open {
    translate: 0 100%;
  }
  .demo-drawer[data-side="inline-start"]:dir(ltr):open {
    translate: -100% 0;
  }
  .demo-drawer[data-side="inline-start"]:dir(rtl):open {
    translate: 100% 0;
  }
}

/* The backdrop fades with the drag: `::backdrop` inherits the custom properties. */
.demo-drawer::backdrop {
  background: rgb(0 0 0 / 0.45);
  opacity: 0;
  transition:
    opacity 300ms,
    display 300ms allow-discrete,
    overlay 300ms allow-discrete;
}

.demo-drawer:open::backdrop {
  opacity: calc(1 - var(--drawer-swipe-progress, 0));
}

@starting-style {
  .demo-drawer:open::backdrop {
    opacity: 0;
  }
}

/* The finger leads while dragging: no transition, on the drawer and its backdrop. */
.demo-drawer[data-swiping],
.demo-drawer[data-swiping]::backdrop {
  transition: none;
}

/* Reduced motion: no slide. A swipe still follows the pointer (direct manipulation); its
   release closes at once or snaps back. */
@media (prefers-reduced-motion: reduce) {
  .demo-drawer,
  .demo-drawer::backdrop {
    transition: none;
  }
}

/* CSS-only scroll lock while a modal drawer is open (Dialog's recipe). */
html:has(.demo-drawer:modal) {
  overflow: hidden;
}

.demo-drawer-grabber {
  align-self: center;
  inline-size: 40px;
  block-size: 5px;
  margin-block: 10px 4px;
  border-radius: 3px;
  background: var(--color-border);
}

/* The body scrolls; a press in it is the scroller's, for every pointer type. */
.demo-drawer-body {
  overflow-y: auto;
  overscroll-behavior: contain;
  min-block-size: 0;
  flex: 1;
  display: grid;
  gap: 2px;
}

.demo-drawer-row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 4px;
}

.demo-drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-block-start: 8px;
  border-block-start: 1px solid var(--color-border);
  /* A drag that starts here moves the drawer instead of selecting the buttons' text. */
  user-select: none;
}

.demo-drawer-nav {
  list-style: none;
  margin: 0;
  padding: 0;
  flex: 1;
}

.demo-drawer-nav a {
  display: block;
  padding: 10px 8px;
  border-radius: 6px;
  color: inherit;
  text-decoration: none;
}

.demo-drawer-nav a:hover {
  background: var(--color-bg-secondary, rgb(127 127 127 / 0.12));
}
```

## How it works

| | Drawer |
| - | - |
| Edge | `side`: `"top"`, `"bottom"` (default), `"left"`, `"right"`, `"inline-start"`, `"inline-end"`; rendered as `data-side` in every mode and in the server HTML. Your CSS places the drawer from it |
| Swipe | Mouse, pen or touch, one pointer, after hydration. A drag toward the edge sets `data-swiping` and the inline `--drawer-swipe-x`, `--drawer-swipe-y`, `--drawer-swipe-progress`; your `translate` follows them |
| Release | Past 25% of the drawer's extent, or faster than 0.5 px/ms toward the edge: the library writes the full extent, waits for your transition to carry the drawer off, then calls `requestClose()`. Moving back at the release, or short of the threshold: the properties are removed and your transition brings it back |
| The close | A dismissal, a fact: `onOpenChange(false, { reason: "dismiss", event: <the pointerup>, returnValue: "" })`. Never `openChangeAction`, never pending, never a view transition |
| Scroll | A press inside a scroll container along the drawer's axis scrolls it and never drags. The Popup renders an inline `touch-action` that leaves that axis to the gesture |
| Backdrop press | Closes a modal drawer (`lightDismiss` defaults to the Root's `modal`), a dismissal; a non-modal drawer stays open |
| Escape, Close, Form | Dialog's |
| Modes | Dialog's: JS-free without open-state props on the Root, library mode with any. The swipe works in both after hydration |

## The swipe

A press is only recorded: no capture, no `preventDefault()`, so a tap, a click and a text field are untouched. The press becomes a drag when the pointer has moved 6 px, more along the drawer's axis than across it and toward the edge; a first move in another direction drops it for good. From then on the pointer is captured on the dialog, and the offset (never below 0) is written on every move, with no React render. The numbers are fixed: 25% of the extent (the distance that takes the drawer fully off its edge, measured when the drag starts), 0.5 px/ms measured over the last 100 ms, and a return when the pointer was moving back faster than 0.1 px/ms.

| A press that never drags | Why |
| - | - |
| On the `::backdrop` | It is a press outside (light dismiss) |
| Inside a nested `<dialog>` or an open popover | The press is that layer's |
| On an `input`, `textarea`, `select` or `[contenteditable]` | Text entry and range controls keep their pointer |
| Inside a scroll container along the drawer's axis | By computed `overflow` (`auto` or `scroll`), whether or not it overflows now: the scroller's (see below) |
| Its `pointerdown` was `preventDefault()`-ed | Your opt-out, read when the drag would start, so a React handler counts. It also stops a mouse press from focusing or selecting there: use it on non-focusable regions |
| Another element captured the pointer | A slider thumb, a map, a canvas |
| On an element you made `draggable="true"` | It keeps its drag-and-drop. Links and images, draggable by default, do drag the drawer: their native drag is prevented from the press to its release, and a link dragged 6 px or more without moving the drawer is not followed (a shorter wobble still clicks) |
| While the drawer slides out after a release | One gesture at a time |

A mouse drag moves the drawer and does not select text: a selection the press made is removed while it drags. The `click` that follows a mouse drag lands on the dialog, so the button the drag started on is not activated. `pointercancel`, a lost capture, a second pointer's press, or the dialog closing for another reason (Escape, a Form settling) ends the drag: the drawer returns, or closes with that other cause.

> **The drag needs a CSS transition on translate**
>
> The release is your `transition` on `translate`: it carries the drawer off its edge (the library waits for it, in Firefox too, which has no CSS exit for a `<dialog>`) and brings a cancelled drag back. A drawer with only a `transition` prop (a view transition) and no CSS transition jumps at the release: a swipe never starts a view transition. Both may be set.

## Scroll inside the drawer

A press inside a scroll container along the drawer's axis is that container's, for every pointer type: the body scrolls; the header, the grabber, the footer and the padding drag. The Popup renders `touch-action: pan-x pinch-zoom` (top and bottom) or `pan-y pinch-zoom` (the side drawers), so a touch drag on the drawer's axis reaches the gesture instead of panning the page; a `style` of yours overrides it.

- **A top or bottom drawer scrolls in a child.** Give the body `overflow-y: auto` and the dialog `overflow: hidden`. The dialog itself cannot be scrolled by touch while the swipe owns the vertical axis; development warns when a top or bottom drawer is its own scroller and its content overflows.
- **A side drawer scrolls in the Popup.** Its content scrolls vertically, natively; a horizontal drag is the swipe. Note that `overflow-y: auto` on a child also makes it a horizontal scroll container (CSS computes the other axis to `auto`), so a press in a scrolling child of a side drawer does not drag. To drag from such a list, give it `overflow-x: hidden` and `touch-action: pan-y pinch-zoom` (as in the starter stylesheet). Development warns once when a press in a side drawer is refused by such a list.
- Add `overscroll-behavior: contain` on the scrolling body so a scroll that reaches its end does not move the page, and lock the page's scroll with the CSS recipe in the example (`html:has(.drawer:modal) { overflow: hidden }`).
- Pulling a list that is scrolled to its top to drag the sheet down (the phone idiom) is not in this version.

## Props

### `Drawer.Root`

| Prop | Type | Default | Description |
| - | - | - | - |
| `open` | `boolean` | – | Controlled open state. undefined means uncontrolled. Selects library mode. Pass `onOpenChange` too: Escape, a backdrop press and a swipe close the drawer without asking (development warns). |
| `defaultOpen` | `boolean` | – | Initial open state in uncontrolled library mode. `defaultOpen={false}` selects library mode without an action. |
| `openChangeAction` | `ChangeAction<boolean, DrawerOpenChangeDetails>` | – | Requests only: the Trigger (`true`), a Close, a Form submit or settle, a foreign close command (`false`, with `details.returnValue` the part's `value`). Awaited; the drawer opens or closes when it resolves; a controlled parent that keeps `open` vetoes a close. Never called for a swipe, Escape or a backdrop press. Runs in the Root's transition; may be a Server Function; rejections reach the nearest Error Boundary above the Root. Selects library mode. |
| `onOpenChange` | `UrgentChangeHandler<boolean, DrawerOpenChangeDetails>` | – | Facts only: a swipe released past the threshold, Escape, a backdrop press, Android back, a script `close()` / `requestClose()`. Always `false`, with `reason: "dismiss"` and `returnValue` as the browser left it (`""`). A swipe's `details.event` is its `pointerup`: tell it from Escape with `details.event?.type`. Called synchronously in the `close` event, outside any transition. In controlled mode set state directly here (`onOpenChange={setOpen}`); a parent that keeps `open={true}` gets the drawer shown again at once, and your CSS enter slides it back in. Selects library mode. On a controlled Root with no `openChangeAction`, also a part's close (a Close part, a Form submission): the library performs it at once and calls this with `"activate"` ([nothing waits](../concepts/action-props.md#urgent-open)). |
| `modal` | `boolean` | `true` | `showModal()` (top layer, backdrop, inert page, Escape) or `show()`: a non-modal drawer is a side panel next to a page that stays usable. A non-modal drawer needs JavaScript to open (there is no `show` command). |
| `children` | `ReactNode \| ((state: DrawerRootState) => ReactNode)` | – | The parts. The function form receives the optimistic state and must not suspend. |

- **State**: `DrawerRootState` is `{ open, pending, modal }` (Dialog's).
- **Owned**: none: the Root renders no element (no `ref`, `className` or `style`).

### `Drawer.Trigger`

`Dialog.Trigger`, unchanged: `<button command="show-modal">` in JS-free mode, a request through the Root with `data-open` and `data-pending` in library mode. Props: `disabled`, `className`, `style`, `children` (functions of `DrawerTriggerState`, `{ open, pending, disabled }`), `render`. In JS-free mode `data-open` follows the dialog; inside a`Toolbar.Root` a disabled Trigger is `aria-disabled` and stays focusable. See [Dialog.Trigger](dialog.md#props).

### `Drawer.Popup`

| Prop | Type | Default | Description |
| - | - | - | - |
| `side` | `"top" \| "bottom" \| "left" \| "right" \| "inline-start" \| "inline-end"` | `"bottom"` | The edge the drawer is attached to. Rendered as `data-side` (a prop echo, also in the server HTML) and `state.side`; the swipe goes toward it. `inline-start` / `inline-end` follow the drawer's own `direction` (read at the press). The library places nothing: style `[data-side]`. |
| `swipeDismiss` | `boolean` | `true` | Let the user drag the drawer toward its edge to close it (mouse, pen, touch; after hydration). The close is a dismissal: `onOpenChange`, never `openChangeAction`. While dragging the drawer has `data-swiping` and the `--drawer-swipe-*` properties. Also renders the inline `touch-action`. `false`: a drawer only its buttons, Escape and the backdrop close. |
| `lightDismiss` | `boolean` | `` the Root's `modal` `` | Close on a press outside the drawer (the `::backdrop` of a modal one): Dialog's JS `pointerdown` and `click` baseline, or native `closedby="any"` with `experimental_closedBy`. On for a modal drawer, off for a non-modal one (a side panel must survive clicks on the page). Before hydration, without the flag, a backdrop press does nothing. |
| `experimental_closedBy` | `boolean` | `false` | As on `Dialog.Popup`: renders `closedby` (`"any"` with `lightDismiss`, else `"closerequest"`) and skips the JS dismiss listeners where the browser implements it. See [Experimental features](../concepts/experimental.md). |
| `initialFocus` | `RefObject<HTMLElement \| null> \| string` | – | As on `Dialog.Popup`: the element to focus on open. |
| `keepMounted` | `boolean` | `false` | Library mode: keep the children in `<Activity mode="hidden">` while closed instead of unmounting them. Ignored in JS-free mode (always mounted). |
| `transition` | `ViewTransitionClass` | – | Library mode only. The class of the `<ViewTransition>` around the dialog; without it no boundary is rendered. A string animates this drawer's own open and its library-driven closes (Close, Form) and its own mount and unmount ([only as the top of what is inserted or removed](../concepts/transitions.md#mount-unmount)), in all engines; nothing else (not another drawer, not an unrelated transition, not content that changes inside). A controlled `open` you change in your own transition needs a map keyed on `fsui-drawer-open` / `fsui-drawer-close` plus `addTransitionType` ([recipe](../concepts/transitions.md#controlled)). A type map is React's: it names every drawer that has it and that a commit with its types reaches, and each plays the class; end it with `default: "none"` ([Type maps](../concepts/transitions.md#type-maps)). A swipe, Escape and a backdrop press animate with CSS only. A closed Popup renders its element one commit after its mount, before paint, so placing it starts no view transition and its `ref` is still empty in the mount effects of the component that renders it ([two-step mount](../concepts/transitions.md#closed-popups)). |
| `className` | `string \| ((state: DrawerPopupState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: DrawerPopupState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: DrawerPopupState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: DrawerPopupState) => ReactNode)` | – | Replace the default \<dialog> (element form) or take over rendering (function form). |

- **State**: `DrawerPopupState` is `{ open, modal, side }`; `open` is committed (`false` in JS-free mode; `:open` is the DOM truth). A drag is not in the state: it is `data-swiping` and the custom properties.
- **Owned**: Dialog.Popup's (`id`, `open`, `closedby`, `data-modal`, `suppressHydrationWarning`; `aria-labelledby` and `aria-describedby` while the Title and the Description are mounted, merged with yours), `data-side`, `data-swiping`. The inline `touch-action` is merged under your `style`. The `--drawer-swipe-*` properties are written through the DOM and are not part of the rendered `style`: do not set them yourself.

`role`, `onCancel` and the other `<dialog>` props pass through.

### `Drawer.Close`

`Dialog.Close`, unchanged: `<button command="request-close">` in JS-free mode, a close request through the Root in library mode; with an `action`, the action runs first in the button's own transition (`data-pending`) and a rejection leaves the drawer open. With or without `action`, the button has `data-pending` until the close it asked for has committed. Props: `action` (details: `DrawerCloseActionDetails & Rejectable`), `whilePending`, `value`, `disabled`, `className`, `style`, `children` (functions of `DrawerCloseState`, `{ pending, disabled }`), `render`. See [Dialog.Close](dialog.md#props).

### `Drawer.Form`, `Drawer.Title`, `Drawer.Description`

`Dialog.Form`, `Dialog.Title` and `Dialog.Description`, unchanged: the same props, state types (`DrawerFormState` is `{ pending }`; Title and Description get the Popup's `{ open, modal }`) and owned keys. See [the Dialog props](dialog.md#props).

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `:open`, `:modal`, `::backdrop` | Popup | As on a Dialog. |
| `data-side` | Popup | The `side` prop, in every mode and in the server HTML. Never flipped. |
| `data-modal` | Popup | The Root's `modal` is `true`. |
| `data-swiping` | Popup | A pointer is dragging the drawer, from the drag's start to its release. Written by the gesture, never server-rendered, not in the state. Turn your transitions off under it. |
| `--drawer-swipe-x`, `--drawer-swipe-y` | Popup (inline) | The offset as a physical vector in px: `0px 120px` for a bottom drawer pulled down 120 px, `-80px 0px` for a left one. Absent when nothing has moved the drawer; set to the full extent during a release's slide; removed by the close or the return. |
| `--drawer-swipe-progress` | Popup (inline) | Offset / extent, from 0 to 1. `::backdrop` inherits it. |
| `data-open` | Trigger | As on a Dialog: optimistic in library mode; in JS-free mode whether the dialog is open, written from its `toggle` event. |
| `data-pending` | Trigger | Library mode: as on a Dialog. |
| `data-pending` | Close | From the click until the close it asked for has committed: its `action`, then the Root's close (library mode, also without `action`). |
| `data-disabled` | Trigger, Close | The `disabled` prop. |

## Keyboard and ARIA

A drawer is a dialog: the role, the name (the Title), the description, the focus moves and the keys are [Dialog's](dialog.md#keyboard-and-aria). Escape closes a modal drawer (and, through the library, a non-modal one). The swipe is a path-based gesture, so it always has an alternative: Escape, the backdrop of a modal drawer, and the Close part. A grabber is decoration (`aria-hidden`), not a button: no key could perform its action.

## Transition types

Concept: [Transitions & ViewTransition](../concepts/transitions.md#transition-types)

Library mode tags an open with `fsui-drawer` plus `fsui-drawer-open`, a Close or Form close with `fsui-drawer` plus `fsui-drawer-close`. Not Dialog's types: a drawer slides where a dialog fades, so a page-level `:active-view-transition-type()` rule can tell them apart. A swipe, Escape and a backdrop press are facts and carry none. These types are public API: key a `transition` map on them, and add them with `addTransitionType` for a controlled change ([Transitions](../concepts/transitions.md#controlled)). A string `transition` is keyed on an internal per-instance type instead, which this component's own dispatch adds.

## Optimistic and pending

Concept: [Pending & optimistic state](../concepts/pending-and-optimistic.md)

As a Dialog's: the Trigger is pending while an open is in flight, a Close is pending from the click until the close it asked for has committed (its `action`, then the Root's close; also without `action`). A swipe is never pending: it is a fact, reported the moment the browser closes the dialog, and it supersedes a close a part asked for. A Close action that is still running keeps running; its close is then a no-op.

### Walkthrough: a swipe

1. Press on the header and drag down: `data-swiping` appears and `--drawer-swipe-y` follows the pointer; your `translate` moves the drawer and your backdrop fades with `--drawer-swipe-progress`.
2. Release at 40%: `data-swiping` goes, the properties jump to the full extent, and your transition slides the drawer off its edge.
3. When that transition has finished (at once with `transition: none`), the library calls `requestClose()`. Your `onCancel` sees it: preventing it keeps the drawer open, and it slides back. Otherwise the dialog closes, focus returns to the Trigger, and `onOpenChange(false, { reason: "dismiss", event })` is called with the `pointerup`.

## Suspense

Concept: [Suspense](../concepts/suspense.md)

As a Dialog's: content that suspends holds the open, the Trigger is pending, and the drawer slides in complete. A child that re-renders or suspends while a pointer drags changes nothing: the gesture holds no React state.

## Browser-owned state

Concept: [Browser-owned state](../concepts/browser-owned-state.md)

JS-free mode: the browser owns everything, and the swipe closes the dialog with `requestClose()` after hydration. Library mode: the Trigger, Close and Form are requests (`openChangeAction`); a swipe, Escape and a backdrop press are the browser's facts (`onOpenChange`). Pass the same setter to both props of a controlled Root.

## Before hydration

Concept: [Server Components](../concepts/server-components.md#before-hydration)

JS-free mode: the Trigger (`command="show-modal"`), the Close (`command="request-close"`), Escape, the content, `data-side` and the `touch-action` are in the server HTML, and the CSS enter and exit run; it works from a Server Component. Before hydration a backdrop press does nothing (without `experimental_closedBy`) and a swipe does nothing (the drawer's axis does not pan the page either): the Close is what closes it on a phone. After hydration the swipe works in JS-free mode too.

```tsx title="DrawerNavigation.tsx"
import { Drawer } from "@funstack/ui/drawer";

const pages = [
  ["Dialog", "/components/dialog"],
  ["AlertDialog", "/components/alert-dialog"],
  ["Drawer", "/components/drawer"],
  ["Popover", "/components/popover"],
  ["Menu", "/components/menu"],
  ["Tooltip", "/components/tooltip"],
  ["HoverCard", "/components/hover-card"],
  ["Toast", "/components/toast"],
] as const;

// A side navigation drawer, written as a Server Component: the Root has no open-state props,
// so the Drawer is JS-free. The Trigger and the Close are Invoker Commands, the content and
// `data-side` are in the server HTML, CSS slides it in and out, and Escape closes it before
// hydration. After hydration a drag toward its edge closes it too (no callback exists in this
// mode). `inline-start` follows the page's direction: on the left here, on the right in a
// right-to-left page. The Popup itself scrolls: a side drawer's swipe is horizontal.
export function DrawerNavigation() {
  return (
    <div className="demo-row">
      <Drawer.Root>
        <Drawer.Trigger className="demo-button">Menu</Drawer.Trigger>
        <Drawer.Popup className="demo-drawer" side="inline-start">
          <Drawer.Title>Overlays</Drawer.Title>
          <nav aria-label="Overlay components">
            <ul className="demo-drawer-nav">
              {pages.map(([label, href]) => (
                <li key={href}>
                  <a href={href}>{label}</a>
                </li>
              ))}
            </ul>
          </nav>
          <Drawer.Close className="demo-button">Close</Drawer.Close>
        </Drawer.Popup>
      </Drawer.Root>
    </div>
  );
}
```

`drawer.css`: the same file as above.

This navigation drawer is a Server Component, on `side="inline-start"`: on the left in a left-to-right page, on the right in a right-to-left one, with no script.

## Recipes

### The starter stylesheet

One `transition` on `translate` is the enter, the exit, the release of a swipe and the return of a cancelled one. Closed positions go in `:where()` so that the `:open` rule wins whatever the side selector's specificity:

```css
.drawer {
  position: fixed; margin: 0; border: 0;
  max-inline-size: none; max-block-size: none;
  transition: translate 300ms cubic-bezier(.32, .72, 0, 1),
              display 300ms allow-discrete, overlay 300ms allow-discrete;
}
.drawer:where([data-side="bottom"]) {
  inset: auto 0 0 0; inline-size: 100%; max-block-size: 90dvh;
  overflow: hidden;                     /* scroll in a child */
  translate: 0 100%;                    /* closed: off its edge */
}
.drawer:where([data-side="inline-end"]) {
  inset-block: 0; inset-inline: auto 0; block-size: 100dvh; inline-size: min(24rem, 90vw);
}
.drawer:where([data-side="inline-end"]:dir(ltr)) { translate: 100% 0; }
.drawer:where([data-side="inline-end"]:dir(rtl)) { translate: -100% 0; }
.drawer:where([data-side="inline-start"]) {
  inset-block: 0; inset-inline: 0 auto; block-size: 100dvh; inline-size: min(20rem, 85vw);
}
.drawer:where([data-side="inline-start"]:dir(ltr)) { translate: -100% 0; }
.drawer:where([data-side="inline-start"]:dir(rtl)) { translate: 100% 0; }

/* Open: at the edge, moved by the swipe. */
.drawer:open { translate: var(--drawer-swipe-x, 0px) var(--drawer-swipe-y, 0px); }
@starting-style {
  .drawer[data-side="bottom"]:open { translate: 0 100%; }
  .drawer[data-side="inline-end"]:dir(ltr):open { translate: 100% 0; }
  .drawer[data-side="inline-end"]:dir(rtl):open { translate: -100% 0; }
  .drawer[data-side="inline-start"]:dir(ltr):open { translate: -100% 0; }
  .drawer[data-side="inline-start"]:dir(rtl):open { translate: 100% 0; }
  /* … one line per side you use */
}

/* While a pointer drags, the pointer leads. */
.drawer[data-swiping], .drawer[data-swiping]::backdrop { transition: none; }

/* A side drawer's vertical list that the swipe may start in (see Scroll inside the drawer). */
.drawer:where(:not([data-side="top"], [data-side="bottom"])) .drawer-list {
  overflow-x: hidden; overflow-y: auto; touch-action: pan-y pinch-zoom;
}
```

### The backdrop follows the drag

`::backdrop` inherits custom properties from its dialog in every engine, so the backdrop can fade as the drawer goes:

```css
.drawer::backdrop {
  background: rgb(0 0 0 / .45);
  opacity: 0;
  transition: opacity 300ms, display 300ms allow-discrete, overlay 300ms allow-discrete;
}
.drawer:open::backdrop { opacity: calc(1 - var(--drawer-swipe-progress, 0)); }
@starting-style { .drawer:open::backdrop { opacity: 0; } }
```

### Using the swipe variables

The two physical components serve every side with one rule. Anything else can read them too, inside the drawer:

```css
/* Rounder corners as the sheet is pulled down. */
.drawer[data-side="bottom"] {
  border-radius: calc(12px + 12px * var(--drawer-swipe-progress, 0))
                 calc(12px + 12px * var(--drawer-swipe-progress, 0)) 0 0;
}

/* A slight resistance: the drawer moves at 80% of the pointer. */
.drawer.stiff[data-swiping] {
  translate: calc(var(--drawer-swipe-x, 0px) * .8) calc(var(--drawer-swipe-y, 0px) * .8);
}
```

Do not set the properties yourself: the library writes and removes them. Scale them only under `[data-swiping]`: the release writes the full extent, which an always-scaled rule would stop short of the edge. Scaling changes only how far the drawer moves during the drag, not where the release decides: the threshold is measured on the pointer.

### Reduced motion

The library makes no `matchMedia` check. The drag is direct manipulation and stays; turn off the slides, and the release closes the drawer at once (there is nothing to wait for) or puts it back in one frame:

```css
@media (prefers-reduced-motion: reduce) {
  .drawer, .drawer::backdrop { transition: none; }
}
```

### Scaling the page behind it

Not a feature: the element is yours, outside the component. The static effect is one rule; it does not follow the finger (the properties are on the dialog, not on its ancestors).

```css
.app { transition: scale 300ms, border-radius 300ms; transform-origin: top; }
html:has(.drawer:modal) .app { scale: .96; border-radius: 12px; }

/* A drawer that steps back while a nested one is open (the inner one is in the top layer). */
.drawer:has(dialog:open) { scale: .96; }
```

### Tell a swipe from Escape

```tsx
<Drawer.Root
  defaultOpen={false}
  onOpenChange={(_open, { event }) => {
    track(event?.type === "pointerup" ? "drawer swiped" : "drawer dismissed");
  }}
>
```

### A side panel that only its buttons close

```tsx
<Drawer.Root defaultOpen={false} modal={false}>
  <Drawer.Trigger>Inspector</Drawer.Trigger>
  <Drawer.Popup side="inline-end" swipeDismiss={false}>   {/* no swipe, no light dismiss */}
    <Drawer.Title>Inspector</Drawer.Title>
    …
    <Drawer.Close>Close</Drawer.Close>
  </Drawer.Popup>
</Drawer.Root>
```

### <a id="navigation-drawer"></a>A navigation drawer that closes on client navigation

A site's navigation should work before hydration, so its drawer is in JS-free mode: no open-state props on the Root (see [Before hydration](#before-hydration)). In that mode the drawer has no `transition` and no callback, and nothing closes it when a client-side router changes the page without loading a new document: the drawer stays open over the new page. Close it from the link's click. The Popup is the `<dialog>`, and in JS-free mode the browser owns its state, so `close()` is all it takes (`data-open` on the Trigger follows the dialog's `toggle` event). Before hydration the handler is not attached, and a click loads a new document, which has no open drawer.

```tsx
import { NavLink } from "react-router"; // any router's link
import { Drawer } from "@funstack/ui/drawer";

function closeDrawer(event: React.MouseEvent<HTMLAnchorElement>) {
  event.currentTarget.closest("dialog")?.close();
}

<Drawer.Root>
  <Drawer.Trigger aria-label="Open navigation">☰</Drawer.Trigger>
  <Drawer.Popup side="inline-start">
    <Drawer.Title>Inbox</Drawer.Title>
    <nav aria-label="Folders">
      <NavLink to="/folder/inbox" onClick={closeDrawer}>Inbox</NavLink>
      <NavLink to="/folder/archive" onClick={closeDrawer}>Archive</NavLink>
    </nav>
    <Drawer.Close>Close</Drawer.Close>
  </Drawer.Popup>
</Drawer.Root>
```

The close runs the CSS exit of the starter stylesheet, as Escape does. A drawer in library mode would close with `setOpen(false)` in the same handler instead, but before hydration its content is not in the HTML: its Trigger opens an empty drawer.

### Opt a region out of the swipe

```tsx
{/* A map or a canvas with its own drag: prevent the press. */}
<div className="map" onPointerDown={(event) => event.preventDefault()} />
```

Preventing the `pointerdown` also cancels the compatibility `mousedown`: a mouse press in that region no longer moves focus or starts a text selection. Use it on regions that are not focusable and hold no text to select (a map, a canvas, a custom slider that handles its own focus), not on a form or a list of links.

### Toasts over a bottom drawer

A [Toast](toast.md) region stays in the top layer above an open drawer (inside a modal one, so that an Undo stays clickable). Toasts placed at the bottom of the screen therefore cover a bottom drawer's buttons. Move them while the drawer is open:

```css
html:has(dialog[data-side="bottom"][open]) .toasts {
  inset-block: 1rem auto;
}
```

The other effects of the move (inherited styles, `textContent`) are on the [Toast page](toast.md#styling).
