# Drawer
A panel that slides in from an edge, for people and agents.
Source page: https://dinachi.dev/docs/components/drawer

## Installation
```bash
npx @dinachi/cli@latest add drawer
```
Adds to your project:
- `components/ui/drawer/drawer.tsx`
- `components/ui/drawer/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import { Button } from "@/components/ui/button"
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  DrawerTrigger,
} from "@/components/ui/drawer"

export function Settings() {
  return (
    <Drawer swipeDirection="right">
      <DrawerTrigger render={<Button variant="outline" />}>Open settings</DrawerTrigger>
      <DrawerContent>
        <DrawerHeader>
          <DrawerTitle>Settings</DrawerTitle>
          <DrawerDescription>Changes save as you make them.</DrawerDescription>
        </DrawerHeader>
        <DrawerFooter>
          <DrawerClose render={<Button variant="outline" />}>Done</DrawerClose>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  )
}
```

## Anatomy
```tsx
<Drawer>
  <DrawerTrigger />
  <DrawerContent>
    <DrawerHeader>
      <DrawerTitle />
      <DrawerDescription />
    </DrawerHeader>
    <DrawerFooter>
      <DrawerClose />
    </DrawerFooter>
  </DrawerContent>
  <DrawerSwipeArea />
</Drawer>
```
- `Drawer`: Holds the open and swipe state.
- `DrawerTrigger`: The button that opens the drawer.
- `DrawerContent`: Portal, backdrop and scrolling panel in one.
- `DrawerTitle`: The heading that names the drawer.
- `DrawerDescription`: Supporting text, announced with the title.
- `DrawerClose`: A button that closes the drawer. Unstyled.
- `DrawerHeader`: Stacks the title and description.
- `DrawerFooter`: Bottom actions, in a row from sm.
- `DrawerSwipeArea`: An invisible strip that swipes the drawer open.
- `DrawerPortal`: Portals children to the body. `DrawerContent` includes it.
- `DrawerBackdrop`: The dimmed layer; fades with the swipe.

## Examples

### Default
A form panel that slides in from the right.
```tsx
import {
  Drawer,
  DrawerTrigger,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
  DrawerDescription,
  DrawerFooter,
  DrawerClose,
} from '@/components/ui/drawer';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <Drawer>
      <DrawerTrigger render={<Button variant="outline" />}>
        Open Drawer
      </DrawerTrigger>
      <DrawerContent>
        <DrawerHeader>
          <DrawerTitle>Edit Profile</DrawerTitle>
          <DrawerDescription>Make changes to your profile settings.</DrawerDescription>
        </DrawerHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <label className="text-sm font-medium">Name</label>
            <input defaultValue="John Doe" className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">Email</label>
            <input type="email" defaultValue="john@example.com" className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" />
          </div>
        </div>
        <DrawerFooter>
          <DrawerClose render={<Button variant="outline" />}>Cancel</DrawerClose>
          <Button>Save</Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  );
}
```

### Sides
Enter from any edge with side.
```tsx
import {
  Drawer,
  DrawerTrigger,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
  DrawerDescription,
  DrawerFooter,
  DrawerClose,
} from '@/components/ui/drawer';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <div className="flex gap-2 flex-wrap">
      {(['left', 'right', 'top', 'bottom'] as const).map((side) => (
        <Drawer key={side}>
          <DrawerTrigger render={<Button variant="outline" />}>
            {side.charAt(0).toUpperCase() + side.slice(1)}
          </DrawerTrigger>
          <DrawerContent side={side}>
            <DrawerHeader>
              <DrawerTitle>{side.charAt(0).toUpperCase() + side.slice(1)} Drawer</DrawerTitle>
              <DrawerDescription>This drawer slides in from the {side}.</DrawerDescription>
            </DrawerHeader>
            <DrawerFooter>
              <DrawerClose render={<Button variant="outline" />}>Close</DrawerClose>
            </DrawerFooter>
          </DrawerContent>
        </Drawer>
      ))}
    </div>
  );
}
```

### Navigation
A left drawer used as site navigation.
```tsx
import {
  Drawer,
  DrawerTrigger,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from '@/components/ui/drawer';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <Drawer>
      <DrawerTrigger render={<Button variant="outline" />}>
        Navigation
      </DrawerTrigger>
      <DrawerContent side="left">
        <DrawerHeader>
          <DrawerTitle>Navigation</DrawerTitle>
        </DrawerHeader>
        <nav className="flex flex-col gap-1">
          {['Dashboard', 'Projects', 'Team', 'Settings', 'Help'].map((item) => (
            <a key={item} href="#" className="rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors">
              {item}
            </a>
          ))}
        </nav>
      </DrawerContent>
    </Drawer>
  );
}
```

## Notes

### Swipe direction
`side` only places the panel. The dismiss swipe comes from `swipeDirection` on `Drawer`, default `down`. For the default right-hand panel, pass `swipeDirection="right"`; for `side="left"`, pass `"left"`.

### Swiping
- The backdrop dims with the drag.
- A flick closes faster than a slow release past the threshold.
- A click close takes the normal duration.

## API reference
Props marked **agent** change what an agent reads or may do.

### Drawer
Holds the open and swipe state.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `open` | `boolean` | - | Controlled open state. |
| `defaultOpen` | `boolean` | `false` | Starting open state when uncontrolled. |
| `onOpenChange` **agent** | `(open, details) => void` | - | Runs on open and close, from either side. `details.cancel()` refuses it. |
| `swipeDirection` | `"up" \| "down" \| "left" \| "right"` | `"down"` | The swipe that dismisses the drawer. Match it to `side`. |
| `modal` | `boolean \| "trap-focus"` | `true` | Traps focus, locks page scroll and blocks outside clicks. `trap-focus` only traps focus. |
| `disablePointerDismissal` | `boolean` | `false` | Keeps the drawer open on an outside click. |
| `snapPoints` | `(number \| string)[]` | - | Resting heights. Fractions of the viewport, pixels, or px and rem strings. |

### DrawerTrigger
The button that opens the drawer.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | - | Swap the element, keep the behaviour. |
| `children` **agent** | `ReactNode` | - | Also the name the agent reads while the drawer is closed. |

### DrawerContent
Portal, backdrop and scrolling panel in one.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `side` | `"top" \| "right" \| "bottom" \| "left"` | `"right"` | The edge the panel enters from. |
| `initialFocus` | `boolean \| RefObject \| (type) => element` | - | Where focus goes on open. |
| `finalFocus` | `boolean \| RefObject \| (type) => element` | - | Where focus goes on close. |

### DrawerTitle
The heading that names the drawer.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Also the name the agent reads while open. |

### DrawerDescription
Supporting text, announced with the title.

Takes the props of the element it renders.

### DrawerClose
A button that closes the drawer. Unstyled.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | - | Swap the element, such as a Button. |

### DrawerHeader
Stacks the title and description.

Takes the props of the element it renders.

### DrawerFooter
Bottom actions, in a row from sm.

Takes the props of the element it renders.

### DrawerSwipeArea
An invisible strip that swipes the drawer open.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `swipeDirection` | `"up" \| "down" \| "left" \| "right"` | - | The swipe that opens it. Defaults to the opposite of the Drawer's. |
| `disabled` | `boolean` | `false` | Stops the strip from opening the drawer. |

### DrawerPortal
Portals children to the body. `DrawerContent` includes it.

Takes the props of the element it renders.

### DrawerBackdrop
The dimmed layer; fades with the swipe.

Takes the props of the element it renders.

## Agent
Inside an `AgentProvider`, Drawer appears in `agent.snapshot()` as `dialog`.
Reads:
- `label`: The `DrawerTitle` while open. The trigger's name while closed, or while open with no title.
- `open`: Whether the drawer is showing. Open drawers are listed first.
Actions:
- `open()`: While closed. act returns the opened drawer under `appeared`.
- `close()`: While open.
An agent's open or close runs through `onOpenChange`. `isAgentChange(details)` is true for it, and `details.cancel()` refuses it; the agent is told the app refused. Controls inside report the drawer's title as `in`.
```ts
await agent.act({
  steps: [{ ref: "Open Drawer", action: "open" }],
})
```

## Accessibility
- The panel is a dialog named by `DrawerTitle` and described by `DrawerDescription`.
- Give every drawer a `DrawerTitle`. The agent reads the same name.
- While modal, focus is trapped and the page cannot scroll or take clicks.
- Focus returns to the trigger when the drawer closes.
- Reduced motion fades the panel in place instead of sliding.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Opens the drawer from the trigger |
| `Tab` | Moves focus, kept inside the drawer while modal |
| `Esc` | Closes and returns focus to the trigger |

## Source
`components/ui/drawer/drawer.tsx`
```tsx
"use client"

import * as React from "react"
import { Drawer as DrawerPrimitive } from "@base-ui/react/drawer"
import { cn } from "@/lib/utils"
import { type AgentOpenParts, useAgentOpen, useHasAgent, useMergedRef } from "@/components/ui/agent"

const DrawerAgentContext = React.createContext<AgentOpenParts | null>(null)

/** Base UI's root, holding its own open state so an agent can open and close it. */
function Drawer<Payload>({ open, defaultOpen, onOpenChange, ...props }: DrawerPrimitive.Root.Props<Payload>) {
  const [state, change, parts] = useAgentOpen("dialog", open, defaultOpen, onOpenChange)
  return (
    <DrawerAgentContext.Provider value={useHasAgent() ? parts : null}>
      <DrawerPrimitive.Root<Payload> {...props} open={state} onOpenChange={change} />
    </DrawerAgentContext.Provider>
  )
}

function DrawerTrigger<Payload>({ ref, ...props }: DrawerPrimitive.Trigger.Props<Payload> & React.RefAttributes<HTMLElement>) {
  const parts = React.useContext(DrawerAgentContext)
  return <DrawerPrimitive.Trigger<Payload> ref={useMergedRef(ref, parts?.trigger)} data-slot="drawer-trigger" {...props} />
}

function DrawerPortal(props: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
  return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
}

function DrawerClose(props: React.ComponentProps<typeof DrawerPrimitive.Close>) {
  return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
}

function DrawerSwipeArea(props: React.ComponentProps<typeof DrawerPrimitive.SwipeArea>) {
  return <DrawerPrimitive.SwipeArea data-slot="drawer-swipe-area" {...props} />
}

const DrawerBackdrop = React.forwardRef<
  React.ComponentRef<typeof DrawerPrimitive.Backdrop>,
  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Backdrop>
>(({ className, ...props }, ref) => (
  <DrawerPrimitive.Backdrop
    ref={ref}
    className={cn(
      "fixed inset-0 z-50 bg-black/50",
      // Base UI writes --drawer-swipe-progress on this element as the drag runs: 0 while
      // the drawer is open, 1 once it has travelled far enough to be gone. Reading it
      // here is what makes the dim follow the finger instead of holding full strength
      // until the drawer lets go.
      "opacity-[calc(1_-_var(--drawer-swipe-progress,0))]",
      "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",
      "transition-opacity duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-drawer,cubic-bezier(0.32,0.72,0,1))]",
      // During the drag the opacity is the finger's to set, not a transition's.
      "data-[swiping]:transition-none",
      className
    )}
    data-slot="drawer-backdrop"
    {...props}
  />
))
DrawerBackdrop.displayName = "DrawerBackdrop"

type DrawerSide = "top" | "right" | "bottom" | "left"

const DrawerContent = React.forwardRef<
  React.ComponentRef<typeof DrawerPrimitive.Popup>,
  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Popup> & {
    side?: DrawerSide
  }
>(({ className, side = "right", children, ...props }, ref) => (
  <DrawerPortal>
    <DrawerBackdrop />
    <DrawerPrimitive.Viewport>
      <DrawerPrimitive.Popup
        ref={useMergedRef(ref, React.useContext(DrawerAgentContext)?.popup)}
        className={cn(
          "fixed z-50 flex flex-col gap-4 border bg-background p-6 shadow-lg",
          // A surface that travels in from an edge gets the drawer curve, which decays
          // more slowly than the standard one and reads as weight rather than snap.
          "transition-transform duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-drawer,cubic-bezier(0.32,0.72,0,1))]",
          // Base UI resolves a flick into --drawer-swipe-strength, a multiplier on how
          // long the rest of the journey should take: below 1 for a fast flick, above 1
          // for a slow drag released past the threshold. Without it every dismissal
          // takes the same 200ms and the drawer ignores how hard it was thrown. It is
          // registered with an initial value of 1, so a click-driven close is unchanged.
          "data-[ending-style]:duration-[calc(var(--motion-duration-base,200ms)_*_var(--drawer-swipe-strength,1))]",
          side === "top" &&
            "inset-x-0 top-0 border-b data-[starting-style]:-translate-y-full data-[ending-style]:-translate-y-full",
          side === "bottom" &&
            "inset-x-0 bottom-0 border-t data-[starting-style]:translate-y-full data-[ending-style]:translate-y-full",
          side === "left" &&
            "inset-y-0 left-0 h-full w-3/4 max-w-sm border-r data-[starting-style]:-translate-x-full data-[ending-style]:-translate-x-full",
          side === "right" &&
            "inset-y-0 right-0 h-full w-3/4 max-w-sm border-l data-[starting-style]:translate-x-full data-[ending-style]:translate-x-full",
          // A drawer's whole entrance is travel, so there is nothing left once the
          // movement is dropped. It fades in place instead, which still marks the
          // arrival without sweeping a full panel across the viewport.
          "motion-reduce:transition-opacity",
          "motion-reduce:data-[starting-style]:translate-x-0 motion-reduce:data-[starting-style]:translate-y-0 motion-reduce:data-[starting-style]:opacity-0",
          "motion-reduce:data-[ending-style]:translate-x-0 motion-reduce:data-[ending-style]:translate-y-0 motion-reduce:data-[ending-style]:opacity-0",
          className
        )}
        data-slot="drawer-content"
        {...props}
      >
        <DrawerPrimitive.Content className="size-full overflow-y-auto">
          {children}
        </DrawerPrimitive.Content>
      </DrawerPrimitive.Popup>
    </DrawerPrimitive.Viewport>
  </DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"

function DrawerTitle({
  className,
  ...props
}: React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>) {
  return (
    <DrawerPrimitive.Title
      className={cn("text-lg font-medium leading-none tracking-tight", className)}
      data-slot="drawer-title"
      {...props}
    />
  )
}

function DrawerDescription({
  className,
  ...props
}: React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>) {
  return (
    <DrawerPrimitive.Description
      className={cn("text-sm text-muted-foreground", className)}
      data-slot="drawer-description"
      {...props}
    />
  )
}

const DrawerHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
  <div className={cn("flex flex-col gap-1.5 text-center sm:text-left", className)} data-slot="drawer-header" {...props} />
)
DrawerHeader.displayName = "DrawerHeader"

const DrawerFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
  <div className={cn("mt-auto flex flex-col gap-2 sm:flex-row sm:justify-end", className)} data-slot="drawer-footer" {...props} />
)
DrawerFooter.displayName = "DrawerFooter"

export {
  Drawer,
  DrawerTrigger,
  DrawerPortal,
  DrawerBackdrop,
  DrawerContent,
  DrawerTitle,
  DrawerDescription,
  DrawerClose,
  DrawerSwipeArea,
  DrawerHeader,
  DrawerFooter,
}
```
