{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"drawer","type":"registry:ui","title":"Drawer","description":"Bottom sheet on the native <dialog> that springs up, drags with a rubber-band feel, snaps to heights, and flicks down to dismiss while the backdrop fades with it.","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"registry/ui/drawer.tsx","type":"registry:ui","content":"\"use client\";\n\nimport {\n  createContext,\n  useContext,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type ButtonHTMLAttributes,\n  type HTMLAttributes,\n  type KeyboardEvent,\n  type ReactNode,\n} from \"react\";\nimport { animate, motion, useDragControls, useMotionValue, useReducedMotion, useTransform, type PanInfo } from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nconst css = `html:has(.ui-drawer:modal){overflow:hidden}.ui-drawer::backdrop{background:transparent}`;\n\nconst FOCUSABLE =\n  'a[href],button:not(:disabled),input:not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex]:not([tabindex=\"-1\"])';\nconst SPRING = { type: \"spring\", stiffness: 380, damping: 38, mass: 0.9 } as const;\n\ntype Ctx = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  position: \"fixed\" | \"absolute\";\n  snapPoints: number[];\n  defaultSnap: number;\n  dismissible: boolean;\n  ids: { trigger: string; content: string; title: string; description: string };\n};\nconst DrawerContext = createContext<Ctx | null>(null);\n\nfunction useDrawer() {\n  const ctx = useContext(DrawerContext);\n  if (!ctx) throw new Error(\"Drawer parts must be rendered inside <Drawer>.\");\n  return ctx;\n}\n\nexport interface DrawerProps {\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /**\n   * `fixed` opens a true modal bottom sheet (showModal: top layer, inert page).\n   * `absolute` renders inside the nearest positioned ancestor, for previews and embeds.\n   */\n  position?: \"fixed\" | \"absolute\";\n  /** Resting heights as fractions of the sheet's height that stay visible, e.g. [0.5, 1]. */\n  snapPoints?: number[];\n  /** Index into snapPoints to open at. Defaults to the last (tallest). */\n  defaultSnap?: number;\n  /** Allow closing by dragging down, the backdrop or Escape. */\n  dismissible?: boolean;\n  children?: ReactNode;\n}\n\nexport function Drawer({\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  position = \"fixed\",\n  snapPoints = [1],\n  defaultSnap,\n  dismissible = true,\n  children,\n}: DrawerProps) {\n  const [inner, setInner] = useState(defaultOpen);\n  const open = openProp ?? inner;\n  const id = useId();\n  const setOpen = (next: boolean) => {\n    if (next === open) return;\n    if (openProp === undefined) setInner(next);\n    onOpenChange?.(next);\n  };\n  const points = [...snapPoints].sort((a, b) => a - b);\n  const ids = { trigger: `${id}-trigger`, content: `${id}-content`, title: `${id}-title`, description: `${id}-desc` };\n  return (\n    <DrawerContext\n      value={{ open, setOpen, position, snapPoints: points, defaultSnap: defaultSnap ?? points.length - 1, dismissible, ids }}\n    >\n      {children}\n    </DrawerContext>\n  );\n}\n\nconst buttonBase =\n  \"inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-border px-4 text-sm font-medium text-foreground outline-none transition-[background-color,scale] hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/60 active:scale-[0.97] [&_svg]:size-4\";\n\nexport function DrawerTrigger({ className, onClick, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {\n  const { open, setOpen, ids } = useDrawer();\n  return (\n    <button\n      type=\"button\"\n      id={ids.trigger}\n      aria-haspopup=\"dialog\"\n      aria-expanded={open}\n      aria-controls={ids.content}\n      {...props}\n      onClick={(e) => {\n        onClick?.(e);\n        if (!e.defaultPrevented) setOpen(true);\n      }}\n      className={cn(buttonBase, \"bg-card shadow-sm\", className)}\n    />\n  );\n}\n\nexport interface DrawerContentProps extends HTMLAttributes<HTMLDivElement> {\n  /** Show the grab handle. */\n  handle?: boolean;\n}\n\nexport function DrawerContent({ handle = true, className, children, ...props }: DrawerContentProps) {\n  const { open, setOpen, position, snapPoints, defaultSnap, dismissible, ids } = useDrawer();\n  const modal = position === \"fixed\";\n  const dialog = useRef<HTMLDialogElement>(null);\n  const sheet = useRef<HTMLDivElement>(null);\n  const returnTo = useRef<HTMLElement | null>(null);\n  const mounted = useRef(false);\n  const [snap, setSnap] = useState(defaultSnap);\n  const reduce = useReducedMotion();\n  const controls = useDragControls();\n  const y = useMotionValue(0);\n  const height = useMotionValue(1);\n  // Backdrop fades with how much of the sheet is showing.\n  const backdrop = useTransform([y, height], ([yv, hv]: number[]) => Math.min(1, Math.max(0, 1 - yv / Math.max(1, hv))));\n  const target = (i: number) => (1 - (snapPoints[i] ?? 1)) * height.get();\n  const settle = (i: number) => animate(y, target(i), reduce ? { duration: 0 } : SPRING);\n\n  useEffect(() => {\n    const d = dialog.current;\n    const el = sheet.current;\n    const firstRun = !mounted.current;\n    mounted.current = true;\n    if (!d || !el) return;\n\n    if (open) {\n      const opening = !d.open;\n      if (opening) {\n        returnTo.current = document.activeElement as HTMLElement | null;\n        if (modal) d.showModal();\n        else {\n          d.open = true; // attribute only: no focus steal when rendered open on page load\n          // preventScroll: the sheet is still translated off-screen, so a scrolling focus would shift the whole dialog.\n          if (!firstRun) (d.querySelector<HTMLElement>(\"[autofocus]\") ?? d.querySelector<HTMLElement>(FOCUSABLE))?.focus({ preventScroll: true });\n        }\n        d.scrollTop = 0; // undo any scroll the native autofocus caused\n        height.set(el.offsetHeight);\n        y.jump(el.offsetHeight); // start fully below, then spring up\n      }\n      const ctrl = animate(y, (1 - (snapPoints[snap] ?? 1)) * height.get(), reduce ? { duration: 0 } : SPRING);\n      return () => ctrl.stop();\n    }\n\n    if (!d.open) return;\n    let cancelled = false;\n    const ctrl = animate(y, height.get(), reduce ? { duration: 0 } : { duration: 0.28, ease: [0.4, 0, 0.9, 0.6] });\n    ctrl.then(() => {\n      if (cancelled) return;\n      d.close();\n      setSnap(defaultSnap); // next open starts at the default height again\n      const back = returnTo.current?.isConnected && returnTo.current !== document.body ? returnTo.current : document.getElementById(ids.trigger);\n      back?.focus({ preventScroll: true });\n    });\n    return () => {\n      cancelled = true;\n      ctrl.stop();\n    };\n    // snapPoints is re-created by the parent each render; its values are covered by `snap`.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, snap, modal, reduce]);\n\n  // Track content size changes (e.g. async content) while open.\n  useEffect(() => {\n    const el = sheet.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => height.set(el.offsetHeight));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [height]);\n\n  const onDragEnd = (_: unknown, info: PanInfo) => {\n    const projected = y.get() + info.velocity.y * 0.2;\n    const options = snapPoints.map((_, i) => ({ i, at: target(i) }));\n    if (dismissible) options.push({ i: -1, at: height.get() });\n    const best = options.reduce((a, b) => (Math.abs(b.at - projected) < Math.abs(a.at - projected) ? b : a));\n    if (best.i === -1) setOpen(false);\n    else if (best.i === snap) settle(best.i);\n    else setSnap(best.i);\n  };\n\n  const onKey = (e: KeyboardEvent<HTMLDialogElement>) => {\n    if (modal) return;\n    if (e.key === \"Escape\") {\n      e.stopPropagation();\n      if (dismissible) setOpen(false);\n    } else if (e.key === \"Tab\") {\n      const items = [...e.currentTarget.querySelectorAll<HTMLElement>(FOCUSABLE)];\n      const first = items[0];\n      const last = items[items.length - 1];\n      if (document.activeElement === (e.shiftKey ? first : last)) {\n        e.preventDefault();\n        (e.shiftKey ? last : first)?.focus({ preventScroll: true });\n      }\n    }\n  };\n\n  const cycle = snapPoints.length > 1;\n\n  return (\n    <>\n      <style href=\"ui-drawer\" precedence=\"default\">\n        {css}\n      </style>\n      <dialog\n        ref={dialog}\n        id={ids.content}\n        aria-labelledby={ids.title}\n        aria-describedby={ids.description}\n        aria-modal={modal ? undefined : true}\n        onCancel={(e) => {\n          e.preventDefault(); // let state drive the close so the slide-out runs\n          if (dismissible) setOpen(false);\n        }}\n        onKeyDown={onKey}\n        className={cn(\n          \"ui-drawer z-50 m-0 size-full max-h-none max-w-none overflow-hidden bg-transparent p-0 outline-none\",\n          modal ? \"fixed inset-0\" : \"absolute inset-0\",\n        )}\n      >\n        <motion.div aria-hidden style={{ opacity: backdrop }} onClick={() => dismissible && setOpen(false)} className=\"absolute inset-0 bg-black/55 backdrop-blur-[3px]\" />\n        <motion.div\n          {...(props as Record<string, unknown>)}\n          ref={sheet}\n          drag=\"y\"\n          dragControls={controls}\n          dragListener={false}\n          dragMomentum={false}\n          dragConstraints={{ top: 0 }}\n          dragElastic={{ top: 0.12, bottom: 1 }}\n          onDragEnd={onDragEnd}\n          onPointerDown={(e) => {\n            // Drag from anywhere that isn't a control, so text fields and buttons behave normally.\n            if (!(e.target as HTMLElement).closest(\"input,textarea,select,button,a,[data-no-drag]\")) controls.start(e);\n          }}\n          style={{ y }}\n          className={cn(\n            \"absolute inset-x-0 bottom-0 mx-auto flex max-h-[88%] w-full max-w-lg flex-col rounded-t-3xl border border-b-0 border-border bg-card text-card-foreground shadow-[0_-12px_40px_-12px_rgb(0_0_0/0.45)] outline-none\",\n            // Skirt below the sheet so an upward overshoot never shows a gap.\n            \"after:absolute after:inset-x-[-1px] after:top-full after:h-24 after:border-x after:border-border after:bg-card\",\n            className,\n          )}\n        >\n          {handle && (\n            <div className=\"grid touch-none place-items-center pt-3 pb-1\">\n              {cycle ? (\n                <button\n                  type=\"button\"\n                  aria-label=\"Change drawer height\"\n                  onClick={() => setSnap((s) => (s + 1) % snapPoints.length)}\n                  className=\"group grid h-5 w-16 cursor-grab place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/60 active:cursor-grabbing\"\n                >\n                  <span className=\"h-1.5 w-11 rounded-full bg-muted-foreground/35 transition-[width,background-color] duration-200 group-hover:w-14 group-hover:bg-muted-foreground/60\" />\n                </button>\n              ) : (\n                <span aria-hidden className=\"h-1.5 w-11 cursor-grab rounded-full bg-muted-foreground/35\" />\n              )}\n            </div>\n          )}\n          <div className=\"min-h-0 flex-1 overflow-y-auto px-6 pt-3 pb-6\">{children}</div>\n        </motion.div>\n      </dialog>\n    </>\n  );\n}\n\nexport function DrawerHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>) {\n  return <div {...props} className={cn(\"mb-5 flex cursor-grab flex-col gap-1 text-center sm:text-left\", className)} />;\n}\n\nexport function DrawerTitle({ className, ...props }: HTMLAttributes<HTMLHeadingElement>) {\n  const { ids } = useDrawer();\n  return <h2 id={ids.title} {...props} className={cn(\"text-lg font-semibold leading-tight tracking-tight\", className)} />;\n}\n\nexport function DrawerDescription({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {\n  const { ids } = useDrawer();\n  return <p id={ids.description} {...props} className={cn(\"text-sm text-muted-foreground\", className)} />;\n}\n\nexport function DrawerFooter({ className, ...props }: HTMLAttributes<HTMLDivElement>) {\n  return <div {...props} className={cn(\"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\", className)} />;\n}\n\nexport function DrawerClose({ className, onClick, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {\n  const { setOpen } = useDrawer();\n  return (\n    <button\n      type=\"button\"\n      {...props}\n      onClick={(e) => {\n        onClick?.(e);\n        if (!e.defaultPrevented) setOpen(false);\n      }}\n      className={cn(buttonBase, \"bg-transparent\", className)}\n    />\n  );\n}\n"}]}