Swipe sheet

A panel that slides in from any edge (bottom, top, left or right) with a grab handle and is dismissed by dragging it back. Releasing past 35% of its size or with enough speed closes it; otherwise it springs back, and dragging the wrong way meets rubber-band resistance. Bottom sheets can rest at snap points such as 30%, 60% and 92%, the backdrop fades with the drag, and an optional stack target scales the page behind for a layered feel. Modal sheets trap focus, lock page scroll and return focus to the trigger; non-modal sheets leave the page usable, which suits a mini player. The handle is a button: arrow keys move between snap points and Escape closes. Scrollable content only starts a drag from the top, and reduced motion swaps the spring for a short linear slide.

Modals & overlaysComponentTailwind v4

Source

"use client";

import {
  useEffect, useId, useLayoutEffect, useRef, useState,
  type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode, type RefObject,
} from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils";

export type SheetSide = "bottom" | "top" | "left" | "right";
/** A snap height: a number of pixels or a percentage of the viewport height such as "60%". */
export type SheetSnapPoint = number | `${number}%`;

export interface SwipeSheetProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  side?: SheetSide;
  /** Bottom sheets only: heights the sheet rests at, smallest first, e.g. ["30%", "60%", "92%"]. */
  snapPoints?: SheetSnapPoint[];
  /** Index into snapPoints to open at. Defaults to the first (the peek). */
  defaultSnap?: number;
  /** Allow closing by dragging, Escape and backdrop clicks. */
  dismissible?: boolean;
  /** true: backdrop, focus trap and scroll lock. false: the page behind stays usable. */
  modal?: boolean;
  /** Element behind the sheet that scales back slightly while it is open (modal only). */
  stack?: RefObject<HTMLElement | null>;
  title: ReactNode;
  description?: ReactNode;
  /** Visually hide the title (it still labels the dialog). */
  hideTitle?: boolean;
  children?: ReactNode;
  footer?: ReactNode;
  className?: string;
}

const FOCUSABLE = "a[href],button:not([disabled]),input:not([disabled]):not([type=hidden]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex='-1'])";
const NO_DRAG = "input,textarea,select,[contenteditable=true],[data-sheet-no-drag]";

const geometry: Record<SheetSide, { axis: "X" | "Y"; sign: 1 | -1; style: CSSProperties }> = {
  bottom: { axis: "Y", sign: 1, style: { left: 0, right: 0, bottom: 0 } },
  top: { axis: "Y", sign: -1, style: { left: 0, right: 0, top: 0 } },
  right: { axis: "X", sign: 1, style: { top: 0, bottom: 0, right: 0 } },
  left: { axis: "X", sign: -1, style: { top: 0, bottom: 0, left: 0 } },
};

function snapPx(point: SheetSnapPoint, viewport: number) {
  return typeof point === "number" ? point : (parseFloat(point) / 100) * viewport;
}

// Resistance past an edge: follows the finger at first, then gives less and less.
function rubber(distance: number, dimension = 180) {
  return (1 - 1 / ((distance * 0.55) / dimension + 1)) * dimension;
}

function reducedMotion() {
  return typeof window !== "undefined" && !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
}

let lockCount = 0;
let savedOverflow = "";
function lockScroll() {
  if (lockCount++ === 0) {
    savedOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
  }
}
function unlockScroll() {
  if (--lockCount === 0) document.body.style.overflow = savedOverflow;
}

export function SwipeSheet({
  open, onOpenChange, side = "bottom", snapPoints, defaultSnap = 0, dismissible = true, modal = true, stack,
  title, description, hideTitle, children, footer, className,
}: SwipeSheetProps) {
  const id = useId();
  const titleId = `${id}-title`;
  const descriptionId = `${id}-description`;
  const { axis, sign, style: edgeStyle } = geometry[side];
  const snaps = side === "bottom" && snapPoints?.length ? snapPoints : null;

  const [mounted, setMounted] = useState(false);
  const [present, setPresent] = useState(open);
  const [snap, setSnap] = useState(defaultSnap);
  const [viewportH, setViewportH] = useState(0);

  const panelRef = useRef<HTMLDivElement>(null);
  const backdropRef = useRef<HTMLDivElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const footerRef = useRef<HTMLDivElement>(null);
  const returnFocus = useRef<HTMLElement | null>(null);
  const motion = useRef({ value: Number.NaN, velocity: 0, target: 0, frame: 0, done: null as null | (() => void) });
  const size = useRef(0);
  const drag = useRef<null | { pointer: number; x: number; y: number; start: number; active: boolean; inScroll: boolean; samples: { t: number; v: number }[] }>(null);
  const suppressClick = useRef(false);
  const openedOnMount = useRef(open);
  const live = useRef({ open, snap });
  live.current = { open, snap };

  useEffect(() => setMounted(true), []);
  useEffect(() => {
    if (open) {
      setPresent(true);
      setSnap(defaultSnap);
    }
  }, [open, defaultSnap]);

  useEffect(() => {
    const update = () => setViewportH(window.innerHeight);
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, []);

  const maxSnapPx = snaps ? Math.max(...snaps.map((point) => snapPx(point, viewportH || 800))) : 0;

  // Offsets are distances pushed toward the closed edge: 0 is fully out, size is fully hidden.
  function offsetFor(index: number) {
    if (!snaps) return 0;
    const height = snapPx(snaps[Math.min(Math.max(index, 0), snaps.length - 1)], window.innerHeight);
    return Math.max(0, size.current - height);
  }
  function openOffset() {
    return snaps ? Math.min(...snaps.map((_, i) => offsetFor(i))) : 0;
  }
  function restOffset() {
    return snaps ? Math.max(...snaps.map((_, i) => offsetFor(i))) : 0;
  }

  function apply(value: number) {
    const panel = panelRef.current;
    if (!panel) return;
    motion.current.value = value;
    panel.style.transform = `translate${axis}(${sign * value}px)`;
    const full = size.current || 1;
    const top = openOffset();
    const progress = Math.min(1, Math.max(0, 1 - (value - top) / Math.max(1, full - top)));
    if (backdropRef.current) backdropRef.current.style.opacity = String(progress);
    if (snaps) {
      // Keep the footer on screen and let the content scroll to its end at every snap height.
      const hidden = Math.max(0, Math.min(value, restOffset()));
      if (footerRef.current) footerRef.current.style.transform = `translateY(${-hidden}px)`;
      if (scrollRef.current) scrollRef.current.style.paddingBottom = `${hidden}px`;
    }
    const behind = modal ? stack?.current : null;
    if (behind) {
      behind.style.transformOrigin = "50% 0";
      behind.style.transform = progress > 0.001 ? `translateY(${progress * 10}px) scale(${1 - progress * 0.05})` : "";
      behind.style.borderRadius = progress > 0.001 ? `${progress * 16}px` : "";
      behind.style.overflow = progress > 0.001 ? "hidden" : "";
    }
  }

  function stop() {
    cancelAnimationFrame(motion.current.frame);
    motion.current.frame = 0;
    motion.current.done = null;
  }

  // A critically-damped-ish spring stepped in requestAnimationFrame, or a short linear slide with reduced motion.
  function animateTo(target: number, done?: () => void) {
    stop();
    const m = motion.current;
    m.target = target;
    m.done = done ?? null;
    if (Number.isNaN(m.value)) m.value = target;
    if (reducedMotion()) {
      const from = m.value;
      const start = performance.now();
      const step = (now: number) => {
        const p = Math.min(1, (now - start) / 140);
        apply(from + (m.target - from) * p);
        if (p < 1) m.frame = requestAnimationFrame(step);
        else finish();
      };
      m.frame = requestAnimationFrame(step);
      return;
    }
    let last = performance.now();
    const step = (now: number) => {
      const dt = Math.min(0.032, (now - last) / 1000);
      last = now;
      const stiffness = 520;
      const damping = 2 * Math.sqrt(stiffness) * 0.9;
      const force = -stiffness * (m.value - m.target) - damping * m.velocity;
      m.velocity += force * dt;
      const next = m.value + m.velocity * dt;
      if (Math.abs(next - m.target) < 0.4 && Math.abs(m.velocity) < 8) {
        apply(m.target);
        finish();
        return;
      }
      apply(next);
      m.frame = requestAnimationFrame(step);
    };
    m.frame = requestAnimationFrame(step);
  }

  function finish() {
    const m = motion.current;
    m.velocity = 0;
    m.frame = 0;
    const done = m.done;
    m.done = null;
    done?.();
  }

  // Slide in when opened, out when closed; re-target when the panel or viewport changes size.
  useLayoutEffect(() => {
    const panel = panelRef.current;
    if (!present || !panel) return;
    const measure = () => (axis === "Y" ? panel.offsetHeight : panel.offsetWidth);
    size.current = measure();
    if (open) {
      // Already open on first paint: rest in place. Otherwise slide in from the edge.
      if (Number.isNaN(motion.current.value) && openedOnMount.current) apply(offsetFor(snap));
      else if (Number.isNaN(motion.current.value)) apply(size.current);
      openedOnMount.current = false;
      animateTo(offsetFor(snap));
    } else {
      animateTo(size.current, () => {
        motion.current.value = Number.NaN;
        setPresent(false);
      });
    }
    if (typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(() => {
      const next = measure();
      if (next === size.current) return;
      size.current = next;
      if (drag.current?.active) return;
      const target = live.current.open ? offsetFor(live.current.snap) : next;
      if (motion.current.frame) motion.current.target = target;
      else apply(target);
    });
    observer.observe(panel);
    return () => observer.disconnect();
  }, [mounted, present, open, snap, viewportH]);

  // Clear the stacked background when the sheet goes away.
  useEffect(() => {
    if (present) return;
    const behind = stack?.current;
    if (behind) {
      behind.style.transform = "";
      behind.style.borderRadius = "";
      behind.style.overflow = "";
    }
  }, [present, stack]);

  useEffect(() => () => cancelAnimationFrame(motion.current.frame), []);

  // Modal: focus in, trap, lock scroll, return focus. Non-modal sheets leave focus where it is.
  useLayoutEffect(() => {
    if (!open || !mounted || !modal) return;
    const panel = panelRef.current;
    if (!panel) return;
    returnFocus.current = document.activeElement as HTMLElement | null;
    // The sheet itself takes focus, so its title is announced and no control inside changes by accident.
    panel.focus({ preventScroll: true });
    lockScroll();
    function keepInside(event: FocusEvent) {
      if (panel && event.target instanceof Node && !panel.contains(event.target)) panel.focus({ preventScroll: true });
    }
    document.addEventListener("focusin", keepInside);
    return () => {
      document.removeEventListener("focusin", keepInside);
      unlockScroll();
      const previous = returnFocus.current;
      returnFocus.current = null;
      if (previous?.isConnected) previous.focus({ preventScroll: true });
    };
  }, [open, mounted, modal]);

  function close() {
    if (dismissible) onOpenChange(false);
  }

  function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
    if (event.key === "Escape" && dismissible) {
      event.stopPropagation();
      onOpenChange(false);
      return;
    }
    if (event.key !== "Tab" || !modal || !panelRef.current) return;
    const items = Array.from(panelRef.current.querySelectorAll<HTMLElement>(FOCUSABLE)).filter((el) => el.getClientRects().length > 0);
    if (!items.length) return;
    const first = items[0];
    const last = items[items.length - 1];
    if (event.shiftKey && (document.activeElement === first || document.activeElement === panelRef.current)) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  }

  // Handle keys: arrows move between snap points (or close toward the edge); click cycles snaps.
  function onHandleKeyDown(event: ReactKeyboardEvent<HTMLButtonElement>) {
    const grow = { bottom: "ArrowUp", top: "ArrowDown", left: "ArrowRight", right: "ArrowLeft" }[side];
    const shrink = { bottom: "ArrowDown", top: "ArrowUp", left: "ArrowLeft", right: "ArrowRight" }[side];
    if (event.key !== grow && event.key !== shrink) return;
    event.preventDefault();
    if (!snaps) {
      if (event.key === shrink) close();
      return;
    }
    if (event.key === grow) setSnap((s) => Math.min(snaps.length - 1, s + 1));
    else if (snap > 0) setSnap(snap - 1);
    else close();
  }

  function onHandleClick() {
    if (suppressClick.current) return;
    if (snaps) setSnap((s) => (s + 1) % snaps.length);
    else close();
  }

  function onPointerDown(event: ReactPointerEvent<HTMLDivElement>) {
    if (event.button !== 0 || !(event.target instanceof Element)) return;
    if (event.target.closest(NO_DRAG)) return;
    const scroller = scrollRef.current;
    const inScroll = !!scroller && scroller.contains(event.target) && scroller.scrollHeight > scroller.clientHeight;
    if (inScroll && scroller && (side === "bottom" ? scroller.scrollTop > 0 : false)) return;
    drag.current = { pointer: event.pointerId, x: event.clientX, y: event.clientY, start: motion.current.value, active: false, inScroll, samples: [] };
  }

  function onPointerMove(event: ReactPointerEvent<HTMLDivElement>) {
    const d = drag.current;
    if (!d || d.pointer !== event.pointerId) return;
    const along = sign * (axis === "Y" ? event.clientY - d.y : event.clientX - d.x);
    const across = axis === "Y" ? event.clientX - d.x : event.clientY - d.y;
    if (!d.active) {
      if (Math.abs(along) < 6) return;
      // Sideways moves and opening drags over scrollable content belong to the content.
      if (Math.abs(across) > Math.abs(along) || (d.inScroll && along < 0 && motion.current.value <= openOffset() + 1)) {
        drag.current = null;
        return;
      }
      d.active = true;
      stop();
      d.start = motion.current.value;
      event.currentTarget.setPointerCapture(event.pointerId);
    }
    event.preventDefault();
    let value = d.start + along;
    const top = openOffset();
    const bottom = restOffset();
    if (value < top) value = top - rubber(top - value);
    else if (!dismissible && value > bottom) value = bottom + rubber(value - bottom);
    apply(value);
    d.samples.push({ t: event.timeStamp, v: value });
    if (d.samples.length > 6) d.samples.shift();
  }

  function onPointerUp(event: ReactPointerEvent<HTMLDivElement>) {
    const d = drag.current;
    drag.current = null;
    if (!d || !d.active || d.pointer !== event.pointerId) return;
    suppressClick.current = true;
    setTimeout(() => (suppressClick.current = false), 0);
    const first = d.samples[0];
    const last = d.samples[d.samples.length - 1];
    const velocity = first && last && last.t > first.t ? ((last.v - first.v) / (last.t - first.t)) * 1000 : 0;
    motion.current.velocity = velocity;
    const value = motion.current.value;
    const rest = restOffset();
    const restHeight = size.current - rest;
    const passed = value - rest > restHeight * 0.35 || (velocity > 900 && value > rest - 4);
    if (dismissible && passed) {
      onOpenChange(false);
      return;
    }
    if (!snaps) {
      animateTo(0);
      return;
    }
    const projected = value + velocity * 0.15;
    let best = 0;
    snaps.forEach((_, i) => {
      if (Math.abs(offsetFor(i) - projected) < Math.abs(offsetFor(best) - projected)) best = i;
    });
    if (best === snap) animateTo(offsetFor(best));
    else setSnap(best);
  }

  if (!mounted || !present) return null;

  const vertical = axis === "Y";
  const handle = (
    <button
      type="button"
      aria-label={snaps ? "Resize sheet" : "Close sheet"}
      onClick={onHandleClick}
      onKeyDown={onHandleKeyDown}
      className={cn(
        "group flex shrink-0 cursor-grab touch-none items-center justify-center outline-hidden active:cursor-grabbing",
        "rounded-md focus-visible:ring-[3px] focus-visible:ring-ring/50",
        vertical ? "mx-auto h-6 w-16" : "absolute inset-y-0 my-auto h-16 w-6",
        side === "right" && "left-0",
        side === "left" && "right-0",
      )}
    >
      <span
        aria-hidden="true"
        className={cn(
          "rounded-full bg-muted-foreground/35 transition-colors group-hover:bg-muted-foreground/60",
          vertical ? "h-1.5 w-10" : "h-10 w-1.5",
        )}
      />
    </button>
  );

  const panelSize: CSSProperties = vertical
    ? snaps ? { height: maxSnapPx } : { maxHeight: "88dvh" }
    : { width: "min(420px, 92vw)" };

  return createPortal(
    <div className={cn("fixed inset-0 z-50", !modal && "pointer-events-none")}>
      {modal && (
        <div
          ref={backdropRef}
          aria-hidden="true"
          onClick={close}
          style={{ opacity: 0 }}
          className="absolute inset-0 bg-black/40 dark:bg-black/60"
        />
      )}
      <div
        ref={panelRef}
        role="dialog"
        aria-modal={modal ? true : undefined}
        aria-labelledby={titleId}
        aria-describedby={description ? descriptionId : undefined}
        tabIndex={-1}
        onKeyDown={onKeyDown}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        onPointerCancel={onPointerUp}
        onClickCapture={(event) => {
          if (suppressClick.current) event.stopPropagation();
        }}
        style={{
          position: "absolute",
          ...edgeStyle,
          ...panelSize,
          transform: `translate${axis}(${sign * 100}%)`,
        }}
        className={cn(
          "pointer-events-auto flex flex-col border-border bg-popover text-popover-foreground outline-hidden",
          "shadow-[0_-12px_48px_-16px_rgb(0_0_0/0.35)]",
          side === "bottom" && "mx-auto max-w-2xl rounded-t-2xl border border-b-0",
          side === "top" && "mx-auto max-w-2xl rounded-b-2xl border border-t-0",
          side === "right" && "rounded-l-2xl border-l pl-3",
          side === "left" && "rounded-r-2xl border-r pr-3",
          !modal && side === "bottom" && "inset-x-3 bottom-3 rounded-2xl border-b sm:inset-x-auto sm:w-[400px]",
          className,
        )}
      >
        {side === "bottom" && handle}
        {!vertical && handle}
        <div className={cn("shrink-0 px-5", side === "bottom" ? "pb-3" : "pb-3 pt-5", hideTitle && "sr-only")}>
          <h2 id={titleId} className="text-base font-semibold tracking-tight">{title}</h2>
          {description && <p id={descriptionId} className="mt-1 text-sm text-muted-foreground">{description}</p>}
        </div>
        <div
          ref={scrollRef}
          className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-5"
        >
          {children}
        </div>
        {footer && (
          <div ref={footerRef} className="shrink-0 border-t border-border bg-popover px-5 py-3.5">
            {footer}
          </div>
        )}
        {side === "top" && handle}
      </div>
    </div>,
    document.body,
  );
}