Skip to content
Shaken UI
Sign in

Drawer

Save

A bottom drawer for touch with a drag handle, swipe to dismiss, and optional snap points, built on Base UI Drawer; the handle doubles as a button that steps between heights.

Category
Overlays
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Drawer preview

Installation

npx @shakenui/cli add drawer

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add drawer --dry-run

Usage

drawer-example.tsx
import { Button } from "@/components/shaken/ui/button";
import {
  Drawer,
  DrawerBody,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  DrawerTrigger,
} from "@/components/shaken/ui/drawer";

const steps = [
  { time: "0.4s", text: "Read package.json and the lockfile" },
  { time: "1.2s", text: "Ran pnpm test --filter api: 212 passed" },
  { time: "3.8s", text: "Opened src/limits.ts and src/handler.ts" },
  { time: "6.1s", text: "Edited src/limits.ts: reads the plan limit" },
  { time: "6.9s", text: "Edited src/handler.ts: returns 429 with Retry-After" },
  { time: "9.4s", text: "Ran pnpm test --filter api: 215 passed" },
  { time: "10.2s", text: "Wrote docs/rate-limits.md" },
  { time: "11.0s", text: "Asked for approval to open a pull request" },
  { time: "34.5s", text: "Approved by Mira Okafor" },
  { time: "36.2s", text: "Opened pull request #482" },
];

export default function DrawerExample() {
  return (
    <div className="flex flex-wrap items-center justify-center gap-3">
      <Drawer>
        <DrawerTrigger render={<Button variant="secondary" />}>Share run</DrawerTrigger>
        <DrawerContent>
          <DrawerHeader>
            <DrawerTitle>Share this run</DrawerTitle>
            <DrawerDescription>Anyone with the link can read the transcript. Secrets stay redacted.</DrawerDescription>
          </DrawerHeader>
          <DrawerBody>
            <div className="flex items-center gap-2 rounded-lg border border-zinc-950/[0.07] px-3 py-2.5 dark:border-white/[0.08]">
              <code className="min-w-0 flex-1 truncate font-mono text-xs text-zinc-600 dark:text-zinc-400">
                shaken.dev/runs/r_8f2k4q
              </code>
              <span className="text-xs text-zinc-500">Expires in 7 days</span>
            </div>
          </DrawerBody>
          <DrawerFooter>
            <DrawerClose render={<Button size="lg" />}>Copy link</DrawerClose>
            <DrawerClose render={<Button size="lg" variant="ghost" />}>Cancel</DrawerClose>
          </DrawerFooter>
        </DrawerContent>
      </Drawer>

      <Drawer snapPoints={["21rem", 1]}>
        <DrawerTrigger render={<Button variant="secondary" />}>Open run log</DrawerTrigger>
        <DrawerContent>
          <DrawerHeader className="text-left">
            <DrawerTitle>Run log</DrawerTitle>
            <DrawerDescription>Drag the handle up for the full log, or press it to switch heights.</DrawerDescription>
          </DrawerHeader>
          <DrawerBody>
            <ol className="divide-y divide-zinc-950/[0.07] rounded-lg border border-zinc-950/[0.07] dark:divide-white/[0.08] dark:border-white/[0.08]">
              {steps.map((step) => (
                <li key={step.time} className="flex gap-3 px-3 py-2.5">
                  <span className="w-11 shrink-0 font-mono text-xs leading-5 text-zinc-500 tabular-nums">{step.time}</span>
                  <span className="text-zinc-700 dark:text-zinc-300">{step.text}</span>
                </li>
              ))}
            </ol>
          </DrawerBody>
        </DrawerContent>
      </Drawer>
    </div>
  );
}

API

PropTypeDefaultDescription
Drawer open / defaultOpen / onOpenChangeboolean / boolean / (open, details) => void—Root state. Leave open unset for an uncontrolled drawer.
Drawer snapPoints(number | string)[]—Resting heights: fractions of the viewport (0 to 1), pixel numbers, or px/rem strings. Without them the drawer sizes to its content.
Drawer snapPoint / defaultSnapPoint / onSnapPointChangeSnapPoint | null / SnapPoint | null / (point, details?) => void—Active snap point. Defaults to the first one and resets to it after closing when uncontrolled. details is absent when the handle button caused the change.
DrawerTrigger / DrawerCloseBase UI Drawer.Trigger / Drawer.Close props—Unstyled buttons that open and close the drawer. Pass className, or render={<Button />}.
DrawerContent showHandlebooleantrueRenders the drag handle at the top.
DrawerHeader / DrawerBody / DrawerFooterdiv / Base UI Drawer.Content / div props—Layout: the body scrolls; the footer stacks full-width actions and pads for the home indicator.
DrawerTitle / DrawerDescriptionBase UI Title / Description props—Heading and supporting text, wired to aria-labelledby and aria-describedby.

Accessibility

  • The panel has role="dialog" and aria-modal, named by DrawerTitle and described by DrawerDescription; focus is trapped while open and returns to the trigger on close.
  • Escape and a tap on the backdrop dismiss it, so swiping is never required.
  • Without snap points the handle is decorative and hidden from assistive tech. With snap points it is a button named Expand drawer or Collapse drawer that steps to the next height, so keyboard and switch users can resize it.
  • With reduced motion the slide and backdrop fade are removed; dragging still tracks the finger.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/drawer.tsxdrawer
  • Also installs button@0.2.1registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/drawer/0.1.0.json.

ui/drawer.tsxShow
ui/drawer.tsx
"use client";

import { Drawer as BaseDrawer } from "@base-ui/react/drawer";
import { type ComponentProps, createContext, useCallback, useContext, useMemo, useState } from "react";

type ClassName<State> = string | ((state: State) => string | undefined) | undefined;

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
  return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}

export type DrawerSnapPoint = BaseDrawer.Root.SnapPoint;

interface SnapContextValue {
  snapPoints: readonly DrawerSnapPoint[] | undefined;
  snapPoint: DrawerSnapPoint | null;
  setSnapPoint: (point: DrawerSnapPoint | null) => void;
}

const SnapContext = createContext<SnapContextValue>({ snapPoints: undefined, snapPoint: null, setSnapPoint: () => {} });

export interface DrawerProps extends Omit<BaseDrawer.Root.Props, "swipeDirection" | "onSnapPointChange"> {
  /**
   * Called when the drawer settles at a new snap point, after a drag or a press on the handle.
   * `details` is absent when the handle button caused the change.
   */
  onSnapPointChange?: (snapPoint: DrawerSnapPoint | null, details?: BaseDrawer.Root.SnapPointChangeEventDetails) => void;
}

/**
 * Groups the drawer parts and holds its open state. Pass `open`/`onOpenChange` to control it.
 * The drawer rises from the bottom edge and is dismissed by swiping it down. Pass `snapPoints`
 * (fractions of the viewport height, pixel numbers, or `px`/`rem` strings) to let it rest at
 * several heights; without them it simply sizes to its content.
 */
export function Drawer({
  snapPoints,
  snapPoint: snapPointProp,
  defaultSnapPoint,
  onSnapPointChange,
  onOpenChangeComplete,
  ...props
}: DrawerProps) {
  const [uncontrolled, setUncontrolled] = useState<DrawerSnapPoint | null>(defaultSnapPoint ?? snapPoints?.[0] ?? null);
  const snapPoint = snapPointProp !== undefined ? snapPointProp : uncontrolled;

  const setSnapPoint = useCallback(
    (point: DrawerSnapPoint | null, details?: BaseDrawer.Root.SnapPointChangeEventDetails) => {
      if (snapPointProp === undefined) setUncontrolled(point);
      onSnapPointChange?.(point, details);
    },
    [snapPointProp, onSnapPointChange],
  );

  const value = useMemo<SnapContextValue>(
    () => ({ snapPoints, snapPoint, setSnapPoint: (point) => setSnapPoint(point) }),
    [snapPoints, snapPoint, setSnapPoint],
  );

  return (
    <SnapContext.Provider value={value}>
      <BaseDrawer.Root
        swipeDirection="down"
        {...(snapPoints ? { snapPoints, snapPoint, onSnapPointChange: setSnapPoint } : null)}
        onOpenChangeComplete={(open) => {
          // Reopen at the first resting height rather than wherever it was dismissed from.
          if (!open && snapPoints && snapPointProp === undefined) setUncontrolled(defaultSnapPoint ?? snapPoints[0] ?? null);
          onOpenChangeComplete?.(open);
        }}
        {...props}
      />
    </SnapContext.Provider>
  );
}

/** A button that opens the drawer. Unstyled; pass `className`, or `render={<Button />}` to reuse your button. */
export const DrawerTrigger = BaseDrawer.Trigger;

/** A button that closes the drawer. Unstyled; pass `className` or `render`. */
export const DrawerClose = BaseDrawer.Close;

export interface DrawerContentProps extends BaseDrawer.Popup.Props {
  /** Renders the drag handle at the top. With snap points it is also a button that steps between heights. */
  showHandle?: boolean;
  /** Classes for the backdrop behind the panel. */
  backdropClassName?: string;
  /** Element to portal into. Defaults to `document.body`. */
  container?: BaseDrawer.Portal.Props["container"];
}

/**
 * The bottom panel, rendered in a portal above a backdrop. On wide screens it stays a centered
 * column instead of spanning the window. Lay it out with DrawerHeader, DrawerBody, and DrawerFooter.
 */
export function DrawerContent({
  showHandle = true,
  backdropClassName,
  container,
  className,
  children,
  ...props
}: DrawerContentProps) {
  const { snapPoints } = useContext(SnapContext);
  const snapping = Boolean(snapPoints?.length);

  return (
    <BaseDrawer.Portal container={container}>
      <BaseDrawer.Backdrop
        className={cx(
          "fixed inset-0 z-50 bg-black/40 dark:bg-black/70",
          // Base UI reports full swipe progress while resting at a lower snap point, so only half the dim follows it.
          "opacity-[calc(1-0.5*var(--drawer-swipe-progress,0))]",
          "transition-opacity duration-400 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none",
          "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-[calc(var(--drawer-swipe-strength,1)*260ms)] data-[swiping]:duration-0",
          backdropClassName,
        )}
      />
      <BaseDrawer.Viewport className="fixed inset-0 z-50 flex items-end justify-center">
        <BaseDrawer.Popup
          data-snapping={snapping || undefined}
          className={withBase(
            cx(
              "relative flex w-full flex-col outline-none sm:max-w-xl",
              "max-h-[calc(100dvh-2rem)] rounded-t-2xl border border-b-0 border-zinc-950/10 bg-white text-zinc-950",
              "shadow-[0_-12px_40px_-12px_rgb(0_0_0/0.22)]",
              "dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[0_-16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
              "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
              // Overscroll fill: a strip below the panel in its own color, so an upward drag never shows a gap.
              "after:pointer-events-none after:absolute after:inset-x-[-1px] after:top-full after:h-12 after:border-x after:border-zinc-950/10 after:bg-inherit dark:after:border-white/15 after:content-['']",
              // Rests at the snap offset; the finger's movement is added while dragging.
              "translate-y-[calc(var(--drawer-snap-point-offset,0px)+var(--drawer-swipe-movement-y,0px))]",
              // With snap points the panel is full height and slides down, so pad the bottom to keep the end of the content reachable.
              "data-[snapping]:h-[calc(100dvh-2rem)] data-[snapping]:pb-[max(0px,var(--drawer-snap-point-offset,0px))]",
              "data-[starting-style]:translate-y-full data-[ending-style]:translate-y-full",
              // Enter: 400ms with a soft landing, like a sheet of paper settling. Exit: faster, faster still after a flick.
              "transition-[translate] duration-400 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none",
              "data-[ending-style]:duration-[calc(var(--drawer-swipe-strength,1)*260ms)]",
              "data-[swiping]:duration-0 data-[swiping]:select-none",
            ),
            className,
          )}
          {...props}
        >
          {showHandle ? <DrawerHandle /> : null}
          {children}
        </BaseDrawer.Popup>
      </BaseDrawer.Viewport>
    </BaseDrawer.Portal>
  );
}

function sameSnap(a: DrawerSnapPoint | null, b: DrawerSnapPoint | null) {
  return a === b || String(a) === String(b);
}

/**
 * The grabber bar. Without snap points it is decoration (hidden from assistive tech), since
 * Escape, the backdrop, and the swipe all dismiss. With snap points it is a real button that
 * steps to the next resting height, so keyboard and switch users can resize the drawer too.
 */
export function DrawerHandle({ className }: { className?: string }) {
  const { snapPoints, snapPoint, setSnapPoint } = useContext(SnapContext);
  const bar = cx(
    "block h-1 w-9 rounded-full bg-zinc-950/15 transition-[background-color,width] duration-150 ease-out motion-reduce:transition-none",
    "dark:bg-white/20",
  );

  if (!snapPoints?.length) {
    return (
      <div aria-hidden="true" className={cx("flex h-6 shrink-0 items-center justify-center", className)}>
        <span className={bar} />
      </div>
    );
  }

  const index = Math.max(
    0,
    snapPoints.findIndex((point) => sameSnap(point, snapPoint)),
  );
  const atLast = index === snapPoints.length - 1;
  const next = atLast ? snapPoints[0] : snapPoints[index + 1];

  return (
    <button
      type="button"
      aria-label={atLast ? "Collapse drawer" : "Expand drawer"}
      onClick={() => setSnapPoint(next ?? null)}
      className={cx(
        "group mx-auto flex h-6 w-16 shrink-0 cursor-grab items-center justify-center rounded-full outline-none active:cursor-grabbing",
        "focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-sky-500",
        className,
      )}
    >
      <span className={cx(bar, "group-hover:bg-zinc-950/25 dark:group-hover:bg-white/30")} />
    </button>
  );
}

/** Wraps the title and description. */
export function DrawerHeader({ className, ...props }: ComponentProps<"div">) {
  return <div className={cx("grid shrink-0 gap-1 px-5 pt-1 pb-4 text-center sm:px-6", className)} {...props} />;
}

/**
 * The scrolling middle of the drawer. Text in it can be selected with a mouse without starting a
 * swipe; mark a horizontal scroller inside it with `data-base-ui-swipe-ignore` to keep its drags.
 */
export function DrawerBody({ className, ...props }: BaseDrawer.Content.Props) {
  return (
    <BaseDrawer.Content
      className={withBase("min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-5 text-sm sm:px-6", className)}
      {...props}
    />
  );
}

/** Holds the actions, full width and stacked, with room for the home indicator on phones. */
export function DrawerFooter({ className, ...props }: ComponentProps<"div">) {
  return (
    <div
      className={cx(
        "grid shrink-0 gap-2 border-t border-zinc-950/[0.07] px-5 pt-4 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6",
        "dark:border-white/[0.08]",
        className,
      )}
      {...props}
    />
  );
}

/** The drawer's heading. Labels the panel with aria-labelledby. */
export function DrawerTitle({ className, ...props }: BaseDrawer.Title.Props) {
  return <BaseDrawer.Title className={withBase("text-base leading-6 font-semibold tracking-[-0.01em]", className)} {...props} />;
}

/** Supporting text. Describes the panel with aria-describedby. */
export function DrawerDescription({ className, ...props }: BaseDrawer.Description.Props) {
  return (
    <BaseDrawer.Description className={withBase("text-sm leading-relaxed text-zinc-600 dark:text-zinc-400", className)} {...props} />
  );
}