Goal: 350 kcal a day

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/drawer.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)))
    
  3. Import it

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

Usage

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

Snap points

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

Nested

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

2 items in the cart

DrawerProvider

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

Inbox

3 unread conversations

Side panel with a form

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

No filters applied

Anatomy

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

PartDescription
triggerA <button> that opens the drawer.
swipeAreaA <div> outside the portal that a swipe opens the drawer from. Takes { element, swipeDirection, disabled }.
portalThe <dialog> in the top layer, around the parts below.
backdropA <div> that covers the page. It sets --drawer-swipe-progress.
viewportA <div> that positions the popup.
popupA <div> with the drawer's content, which a swipe moves.
contentA <div> inside the popup where a mouse drag selects text instead of swiping.
snapTriggerA <button> that moves the drawer to its next snap point.
snapStatusA <div> live region for the current snap point.
title, description, close, initialFocus, finalFocusAs 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

PropTypeDescription
openbooleanWhether 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.
snapPointsArray<number | string>The heights the drawer rests at, lowest first: a fraction of the viewport up to 1, pixels, or "320px" / "20rem".
snapPointnumber | string | nullThe snap point the drawer rests at, controlled like open.
snapToSequentialPointsbooleanA fast swipe doesn't skip snap points.
modalboolean | "trap-focus"As for a Dialog. true by default.
topLayerbooleanfalse draws the drawer in place, sliding in from an edge of the element its viewport fills.
virtualKeyboardbooleanThe viewport follows the software keyboard.

Events

EventDescription
RequestedOpenCarries the trigger's id and the reason: trigger-press or swipe.
RequestedCloseCarries the reason: a Dialog's reasons, or swipe.
SnappedA swipe or the snapTrigger asks for another snap point. Carries snapPoint.
SettledThe transitions of an open or a close finished.

Data attributes

AttributeDescription
data-swipe-directionOn the popup: up, down, left or right.
data-swipingOn the popup and backdrop while a swipe runs.
data-swipe-dismissOn the popup and backdrop while a swipe's close runs.
data-expandedOn the popup at the snap point 1.
data-nested-drawer-openOn the popup while a nested drawer is open. --nested-drawers counts them.
data-starting-style / data-ending-styleAs for a Dialog, on the backdrop, viewport and popup.
--drawer-swipe-movement-x / -yOn the popup: how far a swipe has moved it.
--drawer-snap-point-offsetOn the popup: how far below its full height it rests.
--drawer-swipe-progressOn the backdrop and the indent: 0 when open, 1 when swiped away.
data-active / data-inactiveOn the provider's indent and indentBackground.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.