# Drawer

A panel that slides in from an edge of the screen and is swiped away, with snap points and nesting.

- Page: https://www.effectcn.com/components/drawer
- Kind: Headless component with parts
- File: `src/ui/drawer.ts`
- Built on: `Drawer` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/drawer.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/drawer.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { Drawer, DrawerProvider } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What a `Drawer`'s `view` closure receives. */
export type DrawerParts = Component.Headless.Parts<typeof Drawer>

/** What a `DrawerProvider`'s `view` closure receives. */
export type DrawerProviderParts = Component.Headless.Parts<typeof DrawerProvider>

interface ClassOption {
  readonly class?: string | undefined
}

interface LayerOptions extends ClassOption {
  /** Fill the nearest positioned ancestor instead of the screen, for a drawer with `topLayer: false`. */
  readonly contained?: boolean | undefined
}

// Where the viewport puts the popup, by the direction a swipe dismisses it in.
const viewports = {
  down: "items-end justify-center",
  up: "items-start justify-center",
  left: "items-stretch justify-start",
  right: "items-stretch justify-end"
} as const

// The edge the popup sits on, where it slides in from, and a strip of its own
// colour past that edge, so a swipe the other way shows no gap.
const edges = {
  down: "w-full max-h-[calc(100%-3rem)] rounded-t-xl border-t " +
    "data-[ending-style]:translate-y-full data-[starting-style]:translate-y-full " +
    "after:inset-x-0 after:top-full after:h-[50vh] " +
    "data-[nested-drawer-open]:translate-y-[calc(var(--nested-drawers)*-14px)]",
  up: "w-full max-h-[calc(100%-3rem)] rounded-b-xl border-b " +
    "data-[ending-style]:-translate-y-full data-[starting-style]:-translate-y-full " +
    "after:inset-x-0 after:bottom-full after:h-[50vh]",
  left: "h-full w-[min(24rem,85%)] border-r " +
    "data-[ending-style]:-translate-x-full data-[starting-style]:-translate-x-full " +
    "after:inset-y-0 after:right-full after:w-[50vw]",
  right: "h-full w-[min(24rem,85%)] border-l " +
    "data-[ending-style]:translate-x-full data-[starting-style]:translate-x-full " +
    "after:inset-y-0 after:left-full after:w-[50vw]"
} as const

/** The layer that dims the page. It fades with a swipe, and with snap points shows only near full height. */
export const DrawerBackdrop = <Msg>(h: Html.H<Msg>, drawer: DrawerParts, options: LayerOptions = {}) =>
  drawer.backdrop(
    h.div.class(cn(
      options.contained === true ? "absolute" : "fixed",
      "inset-0 bg-[color-mix(in_oklab,var(--shadow-color)_45%,transparent)]",
      "opacity-[calc(1-var(--drawer-swipe-progress))] transition-opacity duration-300",
      "data-[ending-style]:opacity-0 data-[starting-style]:opacity-0 data-[swiping]:duration-0",
      options.class
    ))
  )

/** Puts the popup on the drawer's edge. Presses pass through it to the backdrop or the page. */
export const DrawerViewport = <Msg>(h: Html.H<Msg>, drawer: DrawerParts, options: LayerOptions = {}) =>
  drawer.viewport(
    h.div.class(cn(
      options.contained === true ? "absolute" : "fixed",
      "pointer-events-none inset-0 flex",
      viewports[drawer.swipeDirection],
      options.class
    ))
  )

/**
 * The drawer's panel, on the edge named by the drawer's `swipeDirection`.
 * `size: "full"` gives a bottom sheet its full height, which snap points need.
 */
export const DrawerPopup = <Msg>(
  h: Html.H<Msg>,
  drawer: DrawerParts,
  options: ClassOption & { readonly size?: "auto" | "full" | undefined } = {}
) =>
  drawer.popup(
    h.div.class(cn(
      "pointer-events-auto relative flex touch-none flex-col bg-popover text-sm text-foreground shadow-float outline-none",
      "translate-x-[var(--drawer-swipe-movement-x)]",
      "translate-y-[calc(var(--drawer-snap-point-offset)+var(--drawer-swipe-movement-y))]",
      "scale-[calc(1-0.04*var(--nested-drawers))] data-[nested-drawer-open]:brightness-95",
      "transition-[translate,scale,filter] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]",
      "data-[ending-style]:duration-[calc(var(--drawer-swipe-strength)*300ms)]",
      "after:pointer-events-none after:absolute after:bg-inherit",
      edges[drawer.swipeDirection],
      options.size === "full" && "h-[calc(100%-3rem)]",
      options.class
    ))
  )

/** The grab bar at the top of a bottom sheet. */
export const DrawerHandle = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("mx-auto mt-3 h-1 w-10 shrink-0 rounded-full bg-border", options.class))

/** The grab bar as a button that moves the sheet to its next snap point. Give it an `aria-label`. */
export const DrawerSnapHandle = <Msg>(h: Html.H<Msg>, drawer: DrawerParts, options: ClassOption = {}) =>
  drawer.snapTrigger(
    h.button.class(cn(
      "mx-auto mt-1 flex h-7 w-16 shrink-0 items-center justify-center rounded-sm",
      "after:h-1 after:w-10 after:rounded-full after:bg-border after:transition-colors hover:after:bg-muted-foreground",
      options.class
    ))
  )

/** A live region that reads the current snap point to screen readers. It shows nothing. */
export const DrawerSnapStatus = <Msg>(h: Html.H<Msg>, drawer: DrawerParts) => drawer.snapStatus(h.div.class("sr-only"))

/** The column inside the popup, kept to a readable width on a wide screen. */
export const DrawerContent = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("mx-auto flex min-h-0 w-full max-w-md flex-1 flex-col gap-4 p-5", options.class))

export const DrawerHeader = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("flex flex-col gap-1.5", options.class))

export const DrawerTitle = <Msg>(h: Html.H<Msg>, drawer: DrawerParts, options: ClassOption = {}) =>
  drawer.title(h.h2.class(cn("m-0 border-0 p-0 text-[16px] leading-snug font-semibold tracking-tight", options.class)))

export const DrawerDescription = <Msg>(h: Html.H<Msg>, drawer: DrawerParts, options: ClassOption = {}) =>
  drawer.description(h.p.class(cn("m-0 text-[13px] leading-normal text-muted-foreground", options.class)))

/** A scrolling area in the popup. Inside it a mouse drag selects text and a touch scrolls, instead of swiping. */
export const DrawerScrollArea = <Msg>(h: Html.H<Msg>, drawer: DrawerParts, options: ClassOption = {}) =>
  drawer.content(h.div.class(cn("-mx-5 min-h-0 flex-1 touch-pan-y overflow-y-auto border-t px-5 py-3", options.class)))

export const DrawerFooter = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("mt-auto flex flex-wrap items-center justify-end gap-2", options.class))

/** The page around the drawers of a `DrawerProvider`: it steps back while one is open, and follows a swipe. */
export const DrawerIndent = <Msg>(h: Html.H<Msg>, drawerProvider: DrawerProviderParts, options: ClassOption = {}) =>
  drawerProvider.indent(
    h.div.class(cn(
      "relative h-full origin-top bg-background",
      "transition-[scale,translate,border-radius] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]",
      "data-[active]:translate-y-[calc(10px*(1-var(--drawer-swipe-progress)))]",
      "data-[active]:scale-[calc(0.94+0.06*var(--drawer-swipe-progress))] data-[active]:rounded-xl",
      options.class
    ))
  )

/** What shows around the indent while it has stepped back. */
export const DrawerIndentBackground = <Msg>(
  h: Html.H<Msg>,
  drawerProvider: DrawerProviderParts,
  options: ClassOption = {}
) => drawerProvider.indentBackground(h.div.class(cn("absolute inset-0 bg-[var(--shadow-color)]", options.class)))
```

```ts
import { DrawerBackdrop, DrawerViewport, DrawerPopup, DrawerHandle, DrawerSnapHandle, DrawerSnapStatus, DrawerContent, DrawerHeader, DrawerTitle, DrawerDescription, DrawerScrollArea, DrawerFooter, DrawerIndent, DrawerIndentBackground } from "#ui/drawer"
```

## Usage

Swipe it down, press Escape or press outside to dismiss it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Drawer } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
  DrawerBackdrop,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHandle,
  DrawerHeader,
  DrawerPopup,
  DrawerTitle,
  DrawerViewport
} from "#ui/drawer"

const DrawerBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenDrawer: {},
  RequestedCloseDrawer: {},
  ClickedDecrease: {},
  ClickedIncrease: {}
})

export const DrawerBasic = Html.component({
  name: "DrawerBasic",
  model: Schema.Struct({ open: Schema.Boolean, goal: Schema.Number }),
  message: DrawerBasicMessage
}).make({
  init: () => ({ open: false, goal: 350 }),
  update: {
    RequestedOpenDrawer: ($) => $.evolve({ open: true }),
    RequestedCloseDrawer: ($) => $.evolve({ open: false }),
    ClickedDecrease: ($) => $.evolve({ goal: (goal) => Math.max(200, goal - 10) }),
    ClickedIncrease: ($) => $.evolve({ goal: (goal) => Math.min(500, goal + 10) })
  },
  view: (h, model) =>
    Drawer(h, {
      props: { open: model.open },
      onEmit: {
        RequestedOpen: () => DrawerBasicMessage.RequestedOpenDrawer(),
        RequestedClose: () => DrawerBasicMessage.RequestedCloseDrawer(),
        Settled: () => undefined,
        Snapped: () => undefined
      },
      view: (drawer) =>
        h.div.class("flex flex-col items-center gap-3.5").children(
          drawer.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Open drawer"),
          h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(`Goal: ${model.goal} kcal a day`),
          drawer.portal(h.dialog)?.children(
            DrawerBackdrop(h, drawer),
            DrawerViewport(h, drawer).children(
              DrawerPopup(h, drawer).children(
                DrawerHandle(h),
                DrawerContent(h).children(
                  DrawerHeader(h).children(
                    DrawerTitle(h, drawer).children("Move goal"),
                    DrawerDescription(h, drawer).children(
                      "Set your daily activity goal. Swipe down to dismiss."
                    )
                  ),
                  h.div.class("flex items-center justify-center gap-6 py-2").children(
                    h.button.class(buttonVariants({ variant: "outline", size: "icon" })).attrs({ "aria-label": "Decrease" })
                      .disabled(model.goal <= 200)
                      .on("click", DrawerBasicMessage.ClickedDecrease())
                      .children("−"),
                    h.div.class("flex w-28 flex-col items-center").children(
                      h.strong.class("text-5xl leading-none font-semibold tracking-tighter tabular-nums").children(
                        String(model.goal)
                      ),
                      h.span.class("mt-1 text-xs text-muted-foreground uppercase").children("kcal / day")
                    ),
                    h.button.class(buttonVariants({ variant: "outline", size: "icon" })).attrs({ "aria-label": "Increase" })
                      .disabled(model.goal >= 500)
                      .on("click", DrawerBasicMessage.ClickedIncrease())
                      .children("+")
                  ),
                  DrawerFooter(h).children(
                    drawer.close(h.button.class(buttonVariants())).children("Done")
                  )
                )
              )
            )
          )
        )
    })
})
```

## Examples

### Sides

swipeDirection is the edge the drawer sits on and the way a swipe dismisses it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Drawer, DrawerSwipeDirection } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
  DrawerBackdrop,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerPopup,
  DrawerTitle,
  DrawerViewport
} from "#ui/drawer"

const DrawerSidesMessage = UiSchema.TaggedEnum({
  RequestedOpenDrawer: { direction: DrawerSwipeDirection },
  RequestedCloseDrawer: {}
})

const sides = [
  { direction: "up", label: "Top" },
  { direction: "right", label: "Right" },
  { direction: "down", label: "Bottom" },
  { direction: "left", label: "Left" }
] as const

export const DrawerSides = Html.component({
  name: "DrawerSides",
  model: Schema.Struct({ open: Schema.NullOr(DrawerSwipeDirection) }),
  message: DrawerSidesMessage
}).make({
  init: () => ({ open: null }),
  update: {
    RequestedOpenDrawer: ($, { direction }) => $.evolve({ open: direction }),
    RequestedCloseDrawer: ($) => $.evolve({ open: null })
  },
  view: (h, model) =>
    h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
      // swipeDirection is the edge the drawer sits on and the way a swipe dismisses it.
      ...sides.map(({ direction, label }) =>
        Drawer(h, {
          key: direction,
          props: { open: model.open === direction, swipeDirection: direction },
          onEmit: {
            RequestedOpen: () => DrawerSidesMessage.RequestedOpenDrawer({ direction }),
            RequestedClose: () => DrawerSidesMessage.RequestedCloseDrawer(),
            Settled: () => undefined,
            Snapped: () => undefined
          },
          view: (drawer) =>
            h.div(
              drawer.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children(label),
              drawer.portal(h.dialog)?.children(
                DrawerBackdrop(h, drawer),
                DrawerViewport(h, drawer).children(
                  DrawerPopup(h, drawer).children(
                    DrawerContent(h).children(
                      DrawerHeader(h).children(
                        DrawerTitle(h, drawer).children(`${label} drawer`),
                        DrawerDescription(h, drawer).children(
                          `Swipe ${direction} to dismiss it, or press Escape.`
                        )
                      ),
                      DrawerFooter(h).children(
                        drawer.close(h.button.class(buttonVariants({ variant: "outline" }))).children("Close")
                      )
                    )
                  )
                )
              )
            )
        })
      )
    )
})
```

### Snap points

The sheet rests at 180px, half and full height. The handle is the snapTrigger.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Drawer, DrawerSnapPoint } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
  DrawerBackdrop,
  DrawerContent,
  DrawerDescription,
  DrawerHeader,
  DrawerPopup,
  DrawerScrollArea,
  DrawerSnapHandle,
  DrawerSnapStatus,
  DrawerTitle,
  DrawerViewport
} from "#ui/drawer"

const DrawerSnapPointsMessage = UiSchema.TaggedEnum({
  RequestedOpenDrawer: {},
  RequestedCloseDrawer: {},
  SnappedDrawer: { snapPoint: DrawerSnapPoint }
})

const snapPoints: ReadonlyArray<DrawerSnapPoint> = ["180px", 0.5, 1]

const stops = [
  "Oslo S", "Nationaltheatret", "Skøyen", "Lysaker", "Sandvika", "Asker", "Drammen", "Hokksund", "Kongsberg",
  "Nordagutu", "Bø", "Lunde", "Drangedal", "Neslandsvatn", "Gjerstad", "Vegårshei", "Nelaug", "Vennesla",
  "Kristiansand"
]

export const DrawerSnapPoints = Html.component({
  name: "DrawerSnapPoints",
  model: Schema.Struct({ open: Schema.Boolean, snapPoint: DrawerSnapPoint }),
  message: DrawerSnapPointsMessage
}).make({
  init: () => ({ open: false, snapPoint: "180px" }),
  update: {
    RequestedOpenDrawer: ($) => $.evolve({ open: true, snapPoint: "180px" }),
    RequestedCloseDrawer: ($) => $.evolve({ open: false }),
    SnappedDrawer: ($, { snapPoint }) => $.evolve({ snapPoint })
  },
  view: (h, model) =>
    Drawer(h, {
      props: { open: model.open, snapPoints, snapPoint: model.snapPoint },
      onEmit: {
        RequestedOpen: () => DrawerSnapPointsMessage.RequestedOpenDrawer(),
        RequestedClose: () => DrawerSnapPointsMessage.RequestedCloseDrawer(),
        Settled: () => undefined,
        Snapped: ({ snapPoint }) => DrawerSnapPointsMessage.SnappedDrawer({ snapPoint })
      },
      view: (drawer) =>
        h.div(
          drawer.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Show the route"),
          drawer.portal(h.dialog)?.children(
            // The backdrop fades in only as the drawer leaves its lower snap points.
            DrawerBackdrop(h, drawer),
            DrawerViewport(h, drawer).children(
              DrawerPopup(h, drawer, { size: "full" }).children(
                // The handle is a button: a press moves the drawer to its next snap point.
                DrawerSnapHandle(h, drawer).attr("aria-label", "Resize the route"),
                DrawerSnapStatus(h, drawer).children(
                  model.snapPoint === 1 ? "Full height" : model.snapPoint === 0.5 ? "Half height" : "Collapsed"
                ),
                DrawerContent(h).children(
                  DrawerHeader(h).children(
                    DrawerTitle(h, drawer).children("Oslo to Kristiansand"),
                    DrawerDescription(h, drawer).children(
                      `${stops.length} stops · 4 h 31 min. Drag the sheet up for the stops.`
                    )
                  ),
                  // Inside `content`, a mouse drag selects text instead of swiping, and a touch scrolls.
                  DrawerScrollArea(h, drawer).children(
                    h.ol.class("m-0 flex list-decimal flex-col gap-2 pl-5 text-[13px] marker:text-muted-foreground").children(
                      ...stops.map((stop) => h.li(stop))
                    )
                  )
                )
              )
            )
          )
        )
    })
})
```

### Nested

A drawer inside another's popup. The outer one steps back using --nested-drawers.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Drawer } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
  DrawerBackdrop,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHandle,
  DrawerHeader,
  DrawerPopup,
  DrawerTitle,
  DrawerViewport
} from "#ui/drawer"

const DrawerNestedMessage = UiSchema.TaggedEnum({
  RequestedOpenCart: {},
  RequestedCloseCart: {},
  RequestedOpenPayment: {},
  RequestedClosePayment: {},
  ClickedPay: {}
})

export const DrawerNested = Html.component({
  name: "DrawerNested",
  model: Schema.Struct({ cart: Schema.Boolean, payment: Schema.Boolean, paid: Schema.Boolean }),
  message: DrawerNestedMessage
}).make({
  init: () => ({ cart: false, payment: false, paid: false }),
  update: {
    RequestedOpenCart: ($) => $.evolve({ cart: true, paid: false }),
    RequestedCloseCart: ($) => $.evolve({ cart: false, payment: false }),
    RequestedOpenPayment: ($) => $.evolve({ payment: true }),
    RequestedClosePayment: ($) => $.evolve({ payment: false }),
    ClickedPay: ($) => $.evolve({ cart: false, payment: false, paid: true })
  },
  view: (h, model) =>
    Drawer(h, {
      key: "cart",
      props: { open: model.cart },
      onEmit: {
        RequestedOpen: () => DrawerNestedMessage.RequestedOpenCart(),
        RequestedClose: () => DrawerNestedMessage.RequestedCloseCart(),
        Settled: () => undefined,
        Snapped: () => undefined
      },
      view: (outerDrawer) =>
        h.div.class("flex flex-col items-center gap-3.5").children(
          outerDrawer.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("View cart"),
          h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(model.paid ? "Paid. Thanks!" : "2 items in the cart"),
          outerDrawer.portal(h.dialog)?.children(
            DrawerBackdrop(h, outerDrawer),
            DrawerViewport(h, outerDrawer).children(
              DrawerPopup(h, outerDrawer).children(
                DrawerHandle(h),
                DrawerContent(h).children(
                  DrawerHeader(h).children(
                    DrawerTitle(h, outerDrawer).children("Your cart"),
                    DrawerDescription(h, outerDrawer).children(
                      "Mechanical keyboard, wrist rest · 1 490 kr"
                    )
                  ),
                  DrawerFooter(h).children(
                    // Drawn inside the cart's popup, so it is nested: the cart steps back
                    // by --nested-drawers and stops swiping while this one is open.
                    Drawer(h, {
                      key: "payment",
                      props: { open: model.payment },
                      onEmit: {
                        RequestedOpen: () => DrawerNestedMessage.RequestedOpenPayment(),
                        RequestedClose: () => DrawerNestedMessage.RequestedClosePayment(),
                        Settled: () => undefined,
                        Snapped: () => undefined
                      },
                      view: (innerDrawer) =>
                        h.div(
                          innerDrawer.trigger(h.button.class(buttonVariants())).children("Check out"),
                          innerDrawer.portal(h.dialog)?.children(
                            DrawerViewport(h, innerDrawer).children(
                              DrawerPopup(h, innerDrawer).children(
                                DrawerHandle(h),
                                DrawerContent(h).children(
                                  DrawerHeader(h).children(
                                    DrawerTitle(h, innerDrawer).children("Pay 1 490 kr"),
                                    DrawerDescription(h, innerDrawer).children(
                                      "Visa ending in 4242. Swipe down to go back to the cart."
                                    )
                                  ),
                                  DrawerFooter(h).children(
                                    innerDrawer.close(h.button.class(buttonVariants({ variant: "outline" })))
                                      .children("Back"),
                                    h.button.class(buttonVariants())
                                      .on("click", DrawerNestedMessage.ClickedPay())
                                      .children("Pay now")
                                  )
                                )
                              )
                            )
                          )
                        )
                    }),
                    outerDrawer.close(h.button.class(buttonVariants({ variant: "outline" }))).children(
                      "Keep shopping"
                    )
                  )
                )
              )
            )
          )
        )
    })
})
```

### DrawerProvider

The page behind scales back like under a native sheet. Shown in place, inside a frame.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Drawer, DrawerProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
  DrawerBackdrop,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHandle,
  DrawerHeader,
  DrawerIndent,
  DrawerIndentBackground,
  DrawerPopup,
  DrawerTitle,
  DrawerViewport
} from "#ui/drawer"

const DrawerProviderIndentMessage = UiSchema.TaggedEnum({
  RequestedOpenDrawer: {},
  RequestedCloseDrawer: {}
})

export const DrawerProviderIndent = Html.component({
  name: "DrawerProviderIndent",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: DrawerProviderIndentMessage
}).make({
  init: () => ({ open: false }),
  update: {
    RequestedOpenDrawer: ($) => $.evolve({ open: true }),
    RequestedCloseDrawer: ($) => $.evolve({ open: false })
  },
  view: (h, model) =>
    DrawerProvider(h, {
      props: {},
      view: (drawerProvider) =>
        Drawer(h, {
          // In place and non-modal, the drawer slides in from the edge of the frame,
          // which stands in for a phone's screen. In an app, the provider goes around
          // the whole page and the drawer stays in the top layer.
          props: { open: model.open, topLayer: false, modal: false },
          onEmit: {
            RequestedOpen: () => DrawerProviderIndentMessage.RequestedOpenDrawer(),
            RequestedClose: () => DrawerProviderIndentMessage.RequestedCloseDrawer(),
            Settled: () => undefined,
            Snapped: () => undefined
          },
          view: (drawer) =>
            h.div.class("relative h-80 w-64 overflow-hidden rounded-xl border bg-background shadow-sm").children(
              DrawerIndentBackground(h, drawerProvider),
              // The indent scales back while a drawer is open, and follows a swipe.
              DrawerIndent(h, drawerProvider, { class: "flex flex-col items-start gap-2 border-b p-5" }).children(
                h.strong.class("text-[16px]").children("Inbox"),
                h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children("3 unread conversations"),
                drawer.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Compose")
              ),
              drawer.portal(h.dialog)?.children(
                DrawerBackdrop(h, drawer, { contained: true }),
                DrawerViewport(h, drawer, { contained: true }).children(
                  DrawerPopup(h, drawer).children(
                    DrawerHandle(h),
                    DrawerContent(h).children(
                      DrawerHeader(h).children(
                        DrawerTitle(h, drawer).children("New message"),
                        DrawerDescription(h, drawer).children(
                          "The page behind steps back, as under a native sheet."
                        )
                      ),
                      DrawerFooter(h).children(
                        drawer.close(h.button.class(buttonVariants())).children("Send")
                      )
                    )
                  )
                )
              )
            )
        })
    })
})
```

### Side panel with a form

A drawer on the right holding a filter form whose draft is applied on submit.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Drawer } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import {
  DrawerBackdrop,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerPopup,
  DrawerTitle,
  DrawerViewport
} from "#ui/drawer"

const Filters = Schema.Struct({ query: Schema.String, assignee: Schema.String })

const DrawerFormMessage = UiSchema.TaggedEnum({
  RequestedOpenDrawer: {},
  RequestedCloseDrawer: {},
  UpdatedQuery: { value: Schema.String },
  UpdatedAssignee: { value: Schema.String },
  SubmittedFilters: {},
  ClickedClear: {}
})

const empty = { query: "", assignee: "" }

const labelClass = "flex flex-col gap-1.5 text-[13px] font-medium"
const inputClass =
  "h-8.5 w-full rounded-md border border-input bg-background px-2.5 text-[13px] font-normal shadow-sm outline-none " +
  "transition-[border-color,box-shadow] duration-150 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/20"

export const DrawerForm = Html.component({
  name: "DrawerForm",
  model: Schema.Struct({ open: Schema.Boolean, applied: Filters, draft: Filters }),
  message: DrawerFormMessage
}).make({
  init: () => ({ open: false, applied: empty, draft: empty }),
  update: {
    RequestedOpenDrawer: ($) => $.evolve({ open: true, draft: $.model.applied }),
    RequestedCloseDrawer: ($) => $.evolve({ open: false }),
    UpdatedQuery: ($, { value }) => $.evolve({ draft: { ...$.model.draft, query: value } }),
    UpdatedAssignee: ($, { value }) => $.evolve({ draft: { ...$.model.draft, assignee: value } }),
    SubmittedFilters: ($) => $.evolve({ open: false, applied: $.model.draft }),
    ClickedClear: ($) => $.evolve({ draft: empty })
  },
  view: (h, model) => {
    const count = Object.values(model.applied).filter((value) => value !== "").length
    return Drawer(h, {
      props: { open: model.open, swipeDirection: "right" },
      onEmit: {
        RequestedOpen: () => DrawerFormMessage.RequestedOpenDrawer(),
        RequestedClose: () => DrawerFormMessage.RequestedCloseDrawer(),
        Settled: () => undefined,
        Snapped: () => undefined
      },
      view: (drawer) =>
        h.div.class("flex flex-col items-center gap-3.5").children(
          drawer.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Filters"),
          h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(count === 0 ? "No filters applied" : `${count} filters applied`),
          drawer.portal(h.dialog)?.children(
            DrawerBackdrop(h, drawer),
            DrawerViewport(h, drawer).children(
              DrawerPopup(h, drawer).children(
                h.form.class("flex min-h-0 flex-1 flex-col").on("submit", DrawerFormMessage.SubmittedFilters()).children(
                  DrawerContent(h).children(
                    DrawerHeader(h).children(
                      DrawerTitle(h, drawer).children("Filter issues"),
                      DrawerDescription(h, drawer).children(
                        "Narrow the list down. Swipe right or press Escape to close without applying."
                      )
                    ),
                    h.label.class(labelClass).children(
                      "Title contains",
                      h.input.class(inputClass).attr("placeholder", "login")
                        .value(model.draft.query)
                        .on("input", ({ value }) => DrawerFormMessage.UpdatedQuery({ value }))
                    ),
                    h.label.class(labelClass).children(
                      "Assignee",
                      h.input.class(inputClass).attr("placeholder", "ada")
                        .value(model.draft.assignee)
                        .on("input", ({ value }) => DrawerFormMessage.UpdatedAssignee({ value }))
                    ),
                    DrawerFooter(h).children(
                      h.button.class(buttonVariants({ variant: "ghost" })).attrs({ type: "button" })
                        .on("click", DrawerFormMessage.ClickedClear())
                        .children("Clear"),
                      h.button.class(buttonVariants()).attr("type", "submit").children("Apply filters")
                    )
                  )
                )
              )
            )
          )
        )
    })
  }
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `trigger` | A <button> that opens the drawer. |
| `swipeArea` | A <div> outside the portal that a swipe opens the drawer from. Takes { element, swipeDirection, disabled }. |
| `portal` | The <dialog> in the top layer, around the parts below. |
| `backdrop` | A <div> that covers the page. It sets --drawer-swipe-progress. |
| `viewport` | A <div> that positions the popup. |
| `popup` | A <div> with the drawer's content, which a swipe moves. |
| `content` | A <div> inside the popup where a mouse drag selects text instead of swiping. |
| `snapTrigger` | A <button> that moves the drawer to its next snap point. |
| `snapStatus` | A <div> live region for the current snap point. |
| `title, description, close, initialFocus, finalFocus` | As for a Dialog. |
| `indent (DrawerProvider)` | A <div> around the page, with data-active while a drawer below the provider is open. |
| `indentBackground (DrawerProvider)` | A <div> behind the indent. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `open` | `boolean` | Whether the drawer shows. Required: the consumer owns it. |
| `swipeDirection` | `"up" \| "down" \| "left" \| "right"` | The direction a swipe dismisses the drawer in, and so its edge. "down" by default. |
| `snapPoints` | `Array<number \| string>` | The heights the drawer rests at, lowest first: a fraction of the viewport up to 1, pixels, or "320px" / "20rem". |
| `snapPoint` | `number \| string \| null` | The snap point the drawer rests at, controlled like open. |
| `snapToSequentialPoints` | `boolean` | A fast swipe doesn't skip snap points. |
| `modal` | `boolean \| "trap-focus"` | As for a Dialog. true by default. |
| `topLayer` | `boolean` | false draws the drawer in place, sliding in from an edge of the element its viewport fills. |
| `virtualKeyboard` | `boolean` | The viewport follows the software keyboard. |

### Events

| Event | Description |
| --- | --- |
| `RequestedOpen` | Carries the trigger's id and the reason: trigger-press or swipe. |
| `RequestedClose` | Carries the reason: a Dialog's reasons, or swipe. |
| `Snapped` | A swipe or the snapTrigger asks for another snap point. Carries snapPoint. |
| `Settled` | The transitions of an open or a close finished. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-swipe-direction` | On the popup: up, down, left or right. |
| `data-swiping` | On the popup and backdrop while a swipe runs. |
| `data-swipe-dismiss` | On the popup and backdrop while a swipe's close runs. |
| `data-expanded` | On the popup at the snap point 1. |
| `data-nested-drawer-open` | On the popup while a nested drawer is open. --nested-drawers counts them. |
| `data-starting-style / data-ending-style` | As for a Dialog, on the backdrop, viewport and popup. |
| `--drawer-swipe-movement-x / -y` | On the popup: how far a swipe has moved it. |
| `--drawer-snap-point-offset` | On the popup: how far below its full height it rests. |
| `--drawer-swipe-progress` | On the backdrop and the indent: 0 when open, 1 when swiped away. |
| `data-active / data-inactive` | On the provider's indent and indentBackground. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
