{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "drawer-spring",
  "title": "Spring drawer",
  "description": "A bottom sheet with half and full snap points plus side drawers on a spring; drag the handle and the release speed picks the snap point or closes it, while the backdrop fades with the drag.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/overlays/drawer-spring.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { animate, motion, useMotionValue, useMotionValueEvent, useReducedMotion, useTransform, type PanInfo, type Transition } from \"motion/react\"\nimport { X } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, ease, spring as springs } from \"@/lib/goodui-motion\"\n\nconst FOCUSABLE =\n  'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex=\"-1\"])'\nconst SPRING: Transition = springs.sheet\n/** Button and backdrop moves glide on the vaul curve; a release keeps the finger's velocity on a spring instead. */\nconst GLIDE: Transition = { duration: 0.5, ease: ease.drawer }\nconst GLIDE_OUT: Transition = { duration: 0.35, ease: ease.drawer }\n/** px/s and fraction of the travel: the same thresholds as vaul. */\nconst FLICK_VELOCITY = 400\nconst CLOSE_FRACTION = 0.25\nconst WRAPPER = \"[data-drawer-wrapper]\"\n/** Off-screen starting offset, so the first paint never shows the panel in place. */\nconst FAR = 10000\n\nfunction useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v: T) => void) {\n  const [inner, setInner] = React.useState(defaultValue)\n  const controlled = value !== undefined\n  const current = controlled ? value : inner\n  const set = React.useCallback(\n    (v: T) => {\n      if (!controlled) setInner(v)\n      onChange?.(v)\n    },\n    [controlled, onChange],\n  )\n  return [current, set] as const\n}\n\nexport type DrawerSide = \"bottom\" | \"right\" | \"left\"\n\nexport type DrawerSpringLabels = { close: string; expand: string; collapse: string }\nconst DEFAULT_LABELS: DrawerSpringLabels = { close: \"Close\", expand: \"Expand sheet\", collapse: \"Collapse sheet\" }\n\nexport type DrawerSpringProps = {\n  /** Controlled open state. Pair with onOpenChange. */\n  open?: boolean\n  /** Initial open state when uncontrolled. */\n  defaultOpen?: boolean\n  /** Called with false on Esc, the close button, a backdrop click or a drag past the lowest point. */\n  onOpenChange?: (open: boolean) => void\n  /** \"bottom\" is a sheet with optional snap points; \"right\" and \"left\" are full-height side drawers. */\n  side?: DrawerSide\n  /** Bottom sheet only: visible fractions of the sheet height, e.g. [0.5, 1] for half and full. */\n  snapPoints?: number[]\n  /** Snap point index used when the sheet opens. */\n  defaultSnap?: number\n  /** Called with the index into the sorted snapPoints after a drag or a handle press moves the sheet. */\n  onSnapChange?: (index: number) => void\n  /** Heading of the drawer; it is also the dialog's accessible name. */\n  title: React.ReactNode\n  /** Line under the title, linked to the dialog with aria-describedby. */\n  description?: React.ReactNode\n  /** Sticky area under the scrolling body, for actions. */\n  footer?: React.ReactNode\n  /**\n   * When true (default), Esc, the close button, a backdrop click and dragging past the lowest point close the drawer.\n   * When false, none of them do and the close button is hidden: close it from your own controls (e.g. the footer).\n   */\n  dismissible?: boolean\n  /**\n   * Bottom sheet without snapPoints: the sheet morphs to the height of its content, so a multi-step flow keeps one\n   * surface. Swap the children and it follows.\n   */\n  animateHeight?: boolean\n  /**\n   * The page behind scales down and rounds while the drawer is open, following the drag. true targets\n   * `[data-drawer-wrapper]`, a string is your own selector. Render the drawer outside that element.\n   */\n  scaleBackground?: boolean | string\n  /** Classes for the panel (width, height, radius). */\n  className?: string\n  /** Classes for the scrolling body that wraps children. */\n  bodyClassName?: string\n  children?: React.ReactNode\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<DrawerSpringLabels>\n}\n\n/**\n * Bottom sheet or side drawer on a spring. Drag the header to move it: the release velocity picks the snap point\n * or closes it, and the backdrop fades with the distance. Esc closes and focus is trapped while open.\n *\n * It renders `position: fixed` without a portal, so keep it out of ancestors that set `transform`/`filter`.\n */\nexport function DrawerSpring({\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  side = \"bottom\",\n  snapPoints,\n  defaultSnap = 0,\n  onSnapChange,\n  title,\n  description,\n  footer,\n  dismissible = true,\n  animateHeight = false,\n  scaleBackground = false,\n  className,\n  bodyClassName,\n  children,\n  labels,\n}: DrawerSpringProps) {\n  const l = useLabels(\"drawer-spring\", DEFAULT_LABELS, labels)\n  const reduce = useReducedMotion() ?? false\n  const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)\n  const [present, setPresent] = React.useState(open)\n  if (open && !present) setPresent(true)\n\n  const uid = React.useId()\n  const panelRef = React.useRef<HTMLDivElement>(null)\n  const restoreRef = React.useRef<HTMLElement | null>(null)\n  const size = React.useRef(0)\n  const velocity = React.useRef(0)\n  const dragged = React.useRef(false)\n  const panStart = React.useRef(0)\n  const bodyRef = React.useRef<HTMLDivElement>(null)\n  const contentRef = React.useRef<HTMLDivElement>(null)\n  const backgroundRef = React.useRef<HTMLElement | null>(null)\n  const bodyHeight = useMotionValue<number | string>(\"auto\")\n\n  const points = React.useMemo(\n    () => (side === \"bottom\" && snapPoints?.length ? [...snapPoints].sort((a, b) => a - b) : [1]),\n    [side, snapPoints],\n  )\n  const [snap, setSnapState] = React.useState(Math.min(defaultSnap, points.length - 1))\n  const snapRef = React.useRef(snap)\n  const setSnap = (i: number) => {\n    snapRef.current = i\n    setSnapState(i)\n    onSnapChange?.(i)\n  }\n\n  const sign = side === \"left\" ? -1 : 1\n  // Distance from the fully open position toward closed. Positive = closing.\n  const off = useMotionValue(FAR)\n  const translate = useTransform(off, (v) => v * sign)\n  const snapOffset = React.useCallback((i: number) => (1 - (points[i] ?? 1)) * size.current, [points])\n  const closedOffset = () => size.current + 24\n  const backdrop = useTransform(off, (v) => {\n    if (!size.current) return 0\n    const low = snapOffset(0)\n    return Math.min(1, Math.max(0, 1 - (v - low) / Math.max(1, size.current + 24 - low)))\n  })\n  const spring = (v = 0): Transition => (reduce ? { duration: 0 } : v ? { ...SPRING, velocity: v } : GLIDE)\n  const morphHeight = animateHeight && side === \"bottom\" && !snapPoints?.length\n\n  // Body height follows the content. The first measure goes straight to the element, so the panel size read below is right.\n  React.useLayoutEffect(() => {\n    const body = bodyRef.current\n    const content = contentRef.current\n    if (!present || !morphHeight || !body || !content) return\n    const read = () => {\n      const cs = getComputedStyle(body)\n      return content.offsetHeight + parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom)\n    }\n    const first = read()\n    bodyHeight.jump(first)\n    body.style.height = `${first}px`\n    const ro = new ResizeObserver(() => {\n      const h = read()\n      if (h !== bodyHeight.get()) animate(bodyHeight, h, reduce ? { duration: 0 } : springs.morph)\n    })\n    ro.observe(content)\n    return () => ro.disconnect()\n  }, [present, morphHeight, reduce, bodyHeight])\n\n  React.useEffect(() => {\n    if (!present || !scaleBackground || reduce) return\n    const el = document.querySelector<HTMLElement>(typeof scaleBackground === \"string\" ? scaleBackground : WRAPPER)\n    if (!el) return\n    const { transform, transformOrigin, borderRadius, overflow } = el.style\n    backgroundRef.current = el\n    el.style.transformOrigin = \"50% 0\"\n    el.style.overflow = \"hidden\"\n    return () => {\n      backgroundRef.current = null\n      Object.assign(el.style, { transform, transformOrigin, borderRadius, overflow })\n    }\n  }, [present, scaleBackground, reduce])\n\n  useMotionValueEvent(backdrop, \"change\", (p) => {\n    const el = backgroundRef.current\n    if (!el) return\n    el.style.transform = `translateY(${(p * 8).toFixed(2)}px) scale(${(1 - p * 0.04).toFixed(4)})`\n    el.style.borderRadius = `${(p * 14).toFixed(1)}px`\n  })\n\n  React.useLayoutEffect(() => {\n    if (!present) return\n    const el = panelRef.current\n    if (!el) return\n    size.current = side === \"bottom\" ? el.offsetHeight : el.offsetWidth\n    let cancelled = false\n    const v = velocity.current\n    velocity.current = 0\n    if (open) {\n      if (off.get() >= FAR) {\n        // Fresh open: start below the edge at the default snap point.\n        off.set(size.current + 24)\n        snapRef.current = Math.min(defaultSnap, points.length - 1)\n        setSnapState(snapRef.current)\n      }\n      const ctl = animate(off, snapOffset(snapRef.current), spring(v))\n      return () => ctl.stop()\n    }\n    const ctl = animate(off, size.current + 24, reduce ? { duration: 0 } : v ? { ...SPRING, velocity: v } : GLIDE_OUT)\n    ctl.then(() => {\n      if (cancelled) return\n      off.jump(FAR)\n      setPresent(false)\n    })\n    return () => {\n      cancelled = true\n      ctl.stop()\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, present])\n\n  // Focus in on open, back to the opener on close, Esc, scroll lock and re-measure on resize.\n  React.useEffect(() => {\n    if (!open) return\n    restoreRef.current = document.activeElement as HTMLElement | null\n    const el = panelRef.current\n    // Skip the snap handle: focus the first real control (close button or content) instead.\n    const first =\n      el?.querySelector<HTMLElement>(\"[data-autofocus]\") ??\n      Array.from(el?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []).find((node) => !node.hasAttribute(\"data-drawer-handle\"))\n    ;(first ?? el)?.focus({ preventScroll: true })\n    const prevOverflow = document.body.style.overflow\n    document.body.style.overflow = \"hidden\"\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\" && dismissible) {\n        e.preventDefault()\n        setOpen(false)\n      }\n    }\n    const onResize = () => {\n      const node = panelRef.current\n      if (!node) return\n      size.current = side === \"bottom\" ? node.offsetHeight : node.offsetWidth\n      off.set(snapOffset(snapRef.current))\n    }\n    document.addEventListener(\"keydown\", onKey)\n    window.addEventListener(\"resize\", onResize)\n    return () => {\n      document.body.style.overflow = prevOverflow\n      document.removeEventListener(\"keydown\", onKey)\n      window.removeEventListener(\"resize\", onResize)\n      restoreRef.current?.focus({ preventScroll: true })\n    }\n  }, [open, setOpen, side, off, snapOffset, dismissible])\n\n  const axis = (info: PanInfo, key: \"offset\" | \"velocity\") => (side === \"bottom\" ? info[key].y : info[key].x) * sign\n\n  const onPan = (_: PointerEvent, info: PanInfo) => {\n    let next = panStart.current + axis(info, \"offset\")\n    if (next < 0) next = -Math.pow(-next, 0.7) // rubber band past fully open\n    off.set(next)\n  }\n\n  const onPanEnd = (_: PointerEvent, info: PanInfo) => {\n    const v = axis(info, \"velocity\")\n    const cur = off.get()\n    const offsets = points.map((_, i) => snapOffset(i))\n    const candidates = dismissible ? [...offsets, closedOffset()] : offsets\n    const projected = cur + v * 0.2\n    let target = candidates.reduce((a, b) => (Math.abs(b - projected) < Math.abs(a - projected) ? b : a))\n    if (Math.abs(v) > FLICK_VELOCITY) {\n      // A flick always moves at least one step in its direction.\n      const ahead = v > 0 ? candidates.filter((c) => c > cur + 4).sort((a, b) => a - b)[0] : candidates.filter((c) => c < cur - 4).sort((a, b) => b - a)[0]\n      if (ahead !== undefined) target = ahead\n    }\n    // Past a quarter of the way down from the lowest point, a release closes it unless it was flicked back up.\n    const low = offsets[0] ?? 0\n    if (dismissible && v > -FLICK_VELOCITY && cur - low > (closedOffset() - low) * CLOSE_FRACTION) target = closedOffset()\n    if (dismissible && target === closedOffset()) {\n      velocity.current = v\n      setOpen(false)\n      return\n    }\n    const i = offsets.indexOf(target)\n    setSnap(i)\n    animate(off, target, spring(v))\n  }\n\n  const cycleSnap = () => {\n    if (dragged.current) return\n    const next = snapRef.current >= points.length - 1 ? 0 : snapRef.current + 1\n    setSnap(next)\n    animate(off, snapOffset(next), spring())\n  }\n\n  const trap = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    if (e.key !== \"Tab\" || !panelRef.current) return\n    const items = Array.from(panelRef.current.querySelectorAll<HTMLElement>(FOCUSABLE))\n    if (!items.length) return e.preventDefault()\n    const first = items[0]!\n    const last = items[items.length - 1]!\n    const active = document.activeElement\n    if (e.shiftKey && (active === first || active === panelRef.current)) {\n      e.preventDefault()\n      last.focus()\n    } else if (!e.shiftKey && active === last) {\n      e.preventDefault()\n      first.focus()\n    }\n  }\n\n  if (!present) return null\n\n  const isBottom = side === \"bottom\"\n  const snapping = points.length > 1\n  const expanded = snap === points.length - 1\n\n  return (\n    <>\n      <GooduiTokens />\n      <motion.div\n        aria-hidden=\"true\"\n        className=\"fixed inset-0 z-50 bg-black/35 dark:bg-black/60\"\n        style={{ opacity: backdrop }}\n        onClick={() => dismissible && setOpen(false)}\n      />\n      <motion.div\n        ref={panelRef}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-labelledby={`${uid}-title`}\n        aria-describedby={description ? `${uid}-desc` : undefined}\n        tabIndex={-1}\n        onKeyDown={trap}\n        style={isBottom ? { y: translate } : { x: translate }}\n        className={cn(\n          \"fixed z-50 flex flex-col bg-card text-card-foreground shadow-[var(--pc-e3)] outline-none after:absolute after:bg-card\",\n          isBottom &&\n            \"inset-x-0 bottom-0 mx-auto w-full max-w-xl rounded-t-[20px] after:inset-x-0 after:top-full after:h-[50vh]\",\n          isBottom && (snapping ? \"h-[min(88dvh,760px)]\" : \"max-h-[88dvh]\"),\n          side === \"right\" && \"inset-y-0 right-0 w-[min(400px,calc(100vw-2.5rem))] rounded-l-[20px] after:inset-y-0 after:left-full after:w-[50vw]\",\n          side === \"left\" && \"inset-y-0 left-0 w-[min(340px,calc(100vw-2.5rem))] rounded-r-[20px] after:inset-y-0 after:right-full after:w-[50vw]\",\n          className,\n        )}\n      >\n        <motion.div\n          onPointerDown={() => (dragged.current = false)}\n          onPanStart={() => {\n            dragged.current = true\n            off.stop()\n            const panel = panelRef.current\n            if (panel) size.current = isBottom ? panel.offsetHeight : panel.offsetWidth\n            panStart.current = off.get()\n          }}\n          onPan={onPan}\n          onPanEnd={onPanEnd}\n          className={cn(\"shrink-0 cursor-grab touch-none px-5 pb-3 select-none active:cursor-grabbing\", isBottom ? \"pt-2\" : \"pt-5\")}\n        >\n          {isBottom && (\n            <button\n              type=\"button\"\n              data-drawer-handle=\"\"\n              onClick={snapping ? cycleSnap : undefined}\n              tabIndex={snapping ? 0 : -1}\n              aria-label={snapping ? (expanded ? l.collapse : l.expand) : undefined}\n              aria-hidden={snapping ? undefined : true}\n              className=\"pc-press group/handle mx-auto mb-2 flex h-5 w-16 cursor-grab items-center justify-center rounded-full outline-none focus-visible:ring-3 focus-visible:ring-ring/50\"\n            >\n              <span className=\"h-1 w-9 rounded-full bg-foreground/20 transition-colors group-hover/handle:bg-foreground/35\" />\n            </button>\n          )}\n          <div className=\"flex items-start gap-3\">\n            <div className=\"min-w-0 flex-1\">\n              <h2 id={`${uid}-title`} className=\"text-base font-semibold tracking-tight\">\n                {title}\n              </h2>\n              {description && (\n                <p id={`${uid}-desc`} className=\"mt-0.5 text-sm text-muted-foreground\">\n                  {description}\n                </p>\n              )}\n            </div>\n            {dismissible && (\n              <button\n                type=\"button\"\n                aria-label={l.close}\n                onClick={() => setOpen(false)}\n                className=\"pc-press -me-1.5 -mt-0.5 inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50\"\n              >\n                <X className=\"size-4\" />\n              </button>\n            )}\n          </div>\n        </motion.div>\n        <motion.div\n          ref={bodyRef}\n          style={morphHeight ? { height: bodyHeight } : undefined}\n          className={cn(\"min-h-0 overflow-x-hidden overflow-y-auto overscroll-contain px-5 pb-5\", morphHeight ? \"flex-initial\" : \"flex-1\", bodyClassName)}\n        >\n          {morphHeight ? <div ref={contentRef}>{children}</div> : children}\n        </motion.div>\n        {footer && <div className=\"relative z-10 shrink-0 border-t border-[var(--pc-hair)] bg-card px-5 py-3\">{footer}</div>}\n      </motion.div>\n    </>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/drawer-spring.tsx"
    }
  ],
  "categories": [
    "components",
    "overlays"
  ],
  "type": "registry:component"
}