{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "drawer",
  "type": "registry:ui",
  "title": "Drawer",
  "description": "An accessible React drawer for Next.js and Tailwind CSS: an iOS bottom sheet on phones that drags to close and works with the keyboard, a dialog on larger screens.",
  "author": "FewTone <https://fewtone.com>",
  "dependencies": [
    "lucide-react@^1.52.0",
    "motion@^14.0.0",
    "vaul@1.1.2"
  ],
  "registryDependencies": [
    "https://ui.fewtone.com/r/tokens.json",
    "https://ui.fewtone.com/r/motion.json",
    "https://ui.fewtone.com/r/button.json",
    "https://ui.fewtone.com/r/dialog.json"
  ],
  "files": [
    {
      "path": "registry/fewtone/ui/drawer.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport { Button } from \"@/components/ui/button\";\nimport {\n  Dialog,\n  DialogClose,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n  DialogTrigger,\n  useMergedRef,\n} from \"@/components/ui/dialog\";\nimport { duration } from \"@/lib/motion\";\nimport { cn } from \"@/lib/utils\";\nimport { XIcon } from \"lucide-react\";\nimport { useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type CSSProperties,\n  createContext,\n  type ReactNode,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\nimport { Drawer as Vaul } from \"vaul\";\n\n/*\n * Drawer: on phones, an iOS bottom sheet (owner's brief, 2026-10-26); on larger screens, our centred Dialog.\n * The sheet is Vaul (a drawer on Radix Dialog): drag it down to close, and the page behind steps back.\n * - Which one is chosen as it opens and kept while it's open, so it never swaps mid-use (a keyboard or a turn of\n *   the phone can change the screen's size). `mode` can force either.\n * - The sheet never scrolls itself. Vaul hangs an invisible filler under it, so a scrolling sheet scrolls into\n *   blank space: the sheet is a fixed shell, and its children scroll in a body inside it, one column that can't\n *   grow wider than the screen. A footer sticks to the bottom, above the home indicator.\n * - The keyboard is ours, not Vaul's: the visual viewport says how much of the screen it covers. The sheet sits\n *   on top of it and fits what's left; the focused field scrolls into view above the footer. While it's up, only\n *   the grabber drags the sheet, so scrolling while typing never closes it, and a pull down at the top of the\n *   content hides the keyboard first, as iOS does.\n * - Fields are 16px on phones inside it, so iOS doesn't zoom in when one is focused.\n * - A drawer opened from a sheet is a sheet on a sheet: the one behind steps back, also when code opens it\n *   (Vaul only does that for a press on its trigger).\n * - Opening doesn't focus the first field (that would raise the keyboard): focus goes to the sheet itself.\n * - Motion: Vaul's own (its iOS curve and drag). Reduced motion: the sheet only fades and the page doesn't step\n *   back. Clean up: a quick open and close can leave the page untouchable, black or scaled, so it's put back\n *   once no dialog is open.\n */\n\n/** Phones: below Tailwind's md breakpoint */\nconst PHONE = \"(max-width: 767px)\";\n\n/** Vaul's own timing and step back (vaul/src/constants.ts), so a sheet pushed back by code moves like one\n * pushed back by Vaul */\nconst VAUL_TRANSITION = \"transform 0.5s cubic-bezier(0.32, 0.72, 0, 1)\";\nconst VAUL_NESTED_STEP = 16;\n\n/** How far a pull down at the top of the content goes before it hides the keyboard: a deliberate fingertip */\nconst PULL_TO_HIDE_KEYBOARD = 48;\n\ntype Shown = \"sheet\" | \"dialog\";\n\n/** How much of the screen the keyboard covers: its top edge from the bottom, and the height left above it */\ntype Keyboard = { bottom: number; height: number };\n\ntype DrawerState = {\n  shown: Shown;\n  open: boolean;\n  keyboard: Keyboard | null;\n  /** The sheet's own node, so a sheet opened from it can push it back */\n  node: RefObject<HTMLDivElement | null>;\n};\n\nconst DrawerContext = createContext<DrawerState | null>(null);\n\nfunction useDrawer(part: string) {\n  const drawer = useContext(DrawerContext);\n  if (!drawer) throw new Error(`${part} must be used inside Drawer`);\n  return drawer;\n}\n\nfunction subscribePhone(onChange: () => void) {\n  const query = window.matchMedia(PHONE);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n}\n\n/** Whether the screen is phone-sized; false on the server, so the first paint matches it */\nfunction usePhone() {\n  return useSyncExternalStore(\n    subscribePhone,\n    () => window.matchMedia(PHONE).matches,\n    () => false,\n  );\n}\n\nconst isField = (node: unknown): node is HTMLElement =>\n  node instanceof HTMLElement &&\n  (node.isContentEditable ||\n    node.matches(\"input:not([type=checkbox]):not([type=radio]):not([type=range]), textarea, select\"));\n\n/** The keyboard, read from the visual viewport while a field has focus; null while it's down */\nfunction useKeyboard(active: boolean) {\n  const [keyboard, setKeyboard] = useState<Keyboard | null>(null);\n\n  useEffect(() => {\n    const viewport = window.visualViewport;\n    if (!active || !viewport) {\n      setKeyboard(null);\n      return;\n    }\n    const update = () => {\n      const bottom = Math.max(0, Math.round(window.innerHeight - viewport.height - viewport.offsetTop));\n      const height = Math.round(viewport.height);\n      const up = isField(document.activeElement) && bottom > 0;\n      setKeyboard((was) =>\n        !up ? null : was?.bottom === bottom && was.height === height ? was : { bottom, height },\n      );\n    };\n    update();\n    viewport.addEventListener(\"resize\", update);\n    viewport.addEventListener(\"scroll\", update);\n    document.addEventListener(\"focusin\", update);\n    document.addEventListener(\"focusout\", update);\n    return () => {\n      viewport.removeEventListener(\"resize\", update);\n      viewport.removeEventListener(\"scroll\", update);\n      document.removeEventListener(\"focusin\", update);\n      document.removeEventListener(\"focusout\", update);\n    };\n  }, [active]);\n\n  return keyboard;\n}\n\n/**\n * A quick open and close can leave Vaul's page styles behind: clicks blocked, a black background, the page\n * scaled or fixed in place. Once no dialog is open, put them back (and the scroll position with them).\n */\nfunction unstick() {\n  if (document.querySelector('[role=\"dialog\"][data-state=\"open\"]')) return;\n  const { body } = document;\n  body.style.removeProperty(\"pointer-events\");\n  body.style.removeProperty(\"background\");\n  if (body.style.position === \"fixed\") {\n    const x = -Number.parseFloat(body.style.left || \"0\");\n    const y = -Number.parseFloat(body.style.top || \"0\");\n    for (const property of [\"position\", \"top\", \"left\", \"right\", \"height\"])\n      body.style.removeProperty(property);\n    window.scrollTo(x, y);\n  }\n  const wrapper = document.querySelector<HTMLElement>(\"[data-vaul-drawer-wrapper]\");\n  wrapper?.style.removeProperty(\"transform\");\n  wrapper?.style.removeProperty(\"border-radius\");\n}\n\nexport type DrawerProps = {\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** A sheet on phones and a dialog on larger screens (auto), or always one of them */\n  mode?: \"auto\" | \"sheet\" | \"dialog\";\n  children?: ReactNode;\n};\n\nfunction Drawer({ open, defaultOpen, onOpenChange, mode = \"auto\", children }: DrawerProps) {\n  const parent = useContext(DrawerContext);\n  const reduce = useReducedMotion() ?? false;\n  const phone = usePhone();\n  const node = useRef<HTMLDivElement | null>(null);\n\n  const [own, setOwn] = useState(defaultOpen ?? false);\n  const current = open ?? own;\n  const setOpen = useCallback(\n    (next: boolean) => {\n      setOwn(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange],\n  );\n\n  // Chosen while closed and kept while open, so it never swaps mid-use\n  const wanted: Shown = mode === \"auto\" ? (phone ? \"sheet\" : \"dialog\") : mode;\n  const [shown, setShown] = useState<Shown>(wanted);\n  if (!current && shown !== wanted) setShown(wanted);\n\n  const sheet = shown === \"sheet\";\n  const nested = sheet && parent?.shown === \"sheet\";\n  const keyboard = useKeyboard(sheet && current);\n\n  // A sheet on a sheet: the one behind steps back while this one is open\n  useEffect(() => {\n    const behind = parent?.node.current;\n    if (!nested || !current || !behind) return;\n    const width = behind.offsetWidth;\n    behind.style.transition = VAUL_TRANSITION;\n    behind.style.transform = `scale(${(width - VAUL_NESTED_STEP) / width}) translate3d(0, -${VAUL_NESTED_STEP}px, 0)`;\n    return () => {\n      behind.style.transform = \"translate3d(0, 0, 0)\";\n    };\n  }, [nested, current, parent]);\n\n  // Leaving the page with a sheet open (or mid-exit) must not leave its styles behind\n  useEffect(\n    () => () => {\n      requestAnimationFrame(unstick);\n    },\n    [],\n  );\n\n  const state = useMemo<DrawerState>(\n    () => ({ shown, open: current, keyboard, node }),\n    [shown, current, keyboard],\n  );\n\n  if (!sheet) {\n    return (\n      <DrawerContext.Provider value={state}>\n        <Dialog open={current} onOpenChange={setOpen}>\n          {children}\n        </Dialog>\n      </DrawerContext.Provider>\n    );\n  }\n\n  const Root = nested ? Vaul.NestedRoot : Vaul.Root;\n  return (\n    <DrawerContext.Provider value={state}>\n      <Root\n        open={current}\n        onOpenChange={setOpen}\n        // The page steps back (it needs a wrapper with data-vaul-drawer-wrapper); a nested sheet pushes the\n        // sheet behind instead\n        shouldScaleBackground={!nested && !reduce}\n        setBackgroundColorOnScale\n        repositionInputs={false}\n        handleOnly={keyboard !== null}\n        onAnimationEnd={(isOpen) => {\n          if (!isOpen) unstick();\n        }}\n      >\n        {children}\n      </Root>\n    </DrawerContext.Provider>\n  );\n}\n\nfunction DrawerTrigger(props: ComponentProps<typeof Vaul.Trigger>) {\n  const { shown } = useDrawer(\"DrawerTrigger\");\n  if (shown === \"dialog\") return <DialogTrigger {...props} />;\n  return <Vaul.Trigger data-slot=\"drawer-trigger\" {...props} />;\n}\n\nfunction DrawerClose(props: ComponentProps<typeof Vaul.Close>) {\n  const { shown } = useDrawer(\"DrawerClose\");\n  if (shown === \"dialog\") return <DialogClose {...props} />;\n  return <Vaul.Close data-slot=\"drawer-close\" {...props} />;\n}\n\nexport type DrawerContentProps = ComponentProps<typeof Vaul.Content> & {\n  /** Show a close button in the top corner */\n  showCloseButton?: boolean;\n};\n\nfunction DrawerContent({ showCloseButton = true, ...props }: DrawerContentProps) {\n  const { shown } = useDrawer(\"DrawerContent\");\n  // The dialog's parts keep Dialog's own slots, which its styles rely on\n  if (shown === \"dialog\") return <DialogContent showCloseButton={showCloseButton} {...props} />;\n  return <SheetContent showCloseButton={showCloseButton} {...props} />;\n}\n\nfunction SheetContent({\n  className,\n  children,\n  style,\n  ref,\n  showCloseButton,\n  onOpenAutoFocus,\n  ...props\n}: DrawerContentProps) {\n  const { open, keyboard, node } = useDrawer(\"DrawerContent\");\n  const reduce = useReducedMotion() ?? false;\n  const setRef = useMergedRef(node, ref);\n  const body = useRef<HTMLDivElement | null>(null);\n  const touch = useRef<{ y: number; top: boolean } | null>(null);\n\n  // As the keyboard comes up (or changes size), the focused field scrolls into view above the footer\n  const bottom = keyboard?.bottom;\n  const height = keyboard?.height;\n  useEffect(() => {\n    const scroller = body.current;\n    if (bottom === undefined || height === undefined || !scroller) return;\n    const footer = scroller.querySelector<HTMLElement>(\"[data-slot=drawer-footer]\");\n    scroller.style.scrollPaddingBottom = footer ? `${footer.offsetHeight}px` : \"\";\n    const frame = requestAnimationFrame(() => {\n      const field = document.activeElement;\n      if (field instanceof HTMLElement && scroller.contains(field)) {\n        field.scrollIntoView({ block: \"nearest\", behavior: reduce ? \"auto\" : \"smooth\" });\n      }\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [bottom, height, reduce]);\n\n  // On the keyboard: lifted by its height and no taller than the screen left above it\n  const lift: CSSProperties | undefined = keyboard\n    ? { bottom: keyboard.bottom, maxHeight: `calc(${keyboard.height}px - var(--size-sheet-top-gap))` }\n    : undefined;\n  // Reduced motion: Vaul's slide becomes its fade (its own keyframes)\n  const calm: CSSProperties | undefined = reduce\n    ? { animationName: open ? \"fadeIn\" : \"fadeOut\", animationDuration: `${duration.base}s` }\n    : undefined;\n\n  return (\n    <Vaul.Portal>\n      <Vaul.Overlay data-slot=\"drawer-overlay\" className=\"fixed inset-0 z-(--z-overlay) bg-overlay\" />\n      <Vaul.Content\n        data-slot=\"drawer-content\"\n        ref={setRef}\n        className={cn(\n          // A fixed shell that never scrolls; on a large screen (mode=\"sheet\") it keeps a phone's width\n          \"fixed inset-x-0 bottom-0 z-(--z-modal) mx-auto flex max-h-(--size-sheet-max) w-full max-w-lg flex-col rounded-t-2xl bg-background text-foreground shadow-lg outline-hidden\",\n          // Fields at 16px on phones, so iOS doesn't zoom in on focus\n          \"max-md:[&_:is(input,select,textarea)]:text-base\",\n          // The header stops short of the close button, so a long title never runs under it\n          showCloseButton && \"**:data-[slot=drawer-header]:pe-10\",\n          className,\n        )}\n        style={{ ...lift, ...calm, ...style }}\n        onOpenAutoFocus={(event) => {\n          onOpenAutoFocus?.(event);\n          if (event.defaultPrevented) return;\n          // Into the sheet, but not into its first field: that would raise the keyboard\n          event.preventDefault();\n          node.current?.focus({ preventScroll: true });\n        }}\n        {...props}\n      >\n        {/* The grabber: Vaul's handle, which stays draggable while the keyboard is up. Its own styles are\n            unlayered, so ours need !important. */}\n        <Vaul.Handle\n          data-slot=\"drawer-handle\"\n          className=\"absolute! inset-x-0! top-2! mx-auto! h-1.25! w-9! rounded-full! bg-foreground/20! opacity-100!\"\n        />\n        <div\n          ref={body}\n          data-slot=\"drawer-body\"\n          className={cn(\n            // One column that can't grow wider than the screen; the room under the last row clears the home\n            // indicator, unless a footer already does\n            \"grid min-h-0 flex-1 auto-rows-max grid-cols-1 gap-4 overflow-x-hidden overflow-y-auto overscroll-contain px-6 pt-6 pb-(--size-sheet-inset-bottom)\",\n            \"has-data-[slot=drawer-footer]:pb-0\",\n          )}\n          onTouchStart={(event) => {\n            touch.current = { y: event.touches[0]?.clientY ?? 0, top: event.currentTarget.scrollTop <= 0 };\n          }}\n          onTouchMove={(event) => {\n            // With the keyboard up, a pull down at the top hides it first, as iOS does\n            const start = touch.current;\n            if (!keyboard || !start?.top) return;\n            if ((event.touches[0]?.clientY ?? 0) - start.y > PULL_TO_HIDE_KEYBOARD) {\n              if (document.activeElement instanceof HTMLElement) document.activeElement.blur();\n              touch.current = null;\n            }\n          }}\n        >\n          {children}\n        </div>\n        {showCloseButton ? (\n          <Vaul.Close asChild>\n            {/* iOS's close: an ✕ in a grey circle, centred on the title's line */}\n            <Button\n              data-slot=\"drawer-close\"\n              variant=\"secondary\"\n              size=\"icon-sm\"\n              aria-label=\"Close\"\n              className=\"absolute end-4 top-5 rounded-full text-muted-foreground hover:text-foreground\"\n            >\n              <XIcon />\n            </Button>\n          </Vaul.Close>\n        ) : null}\n      </Vaul.Content>\n    </Vaul.Portal>\n  );\n}\n\nfunction DrawerHeader({ className, ...props }: ComponentProps<\"div\">) {\n  const { shown } = useDrawer(\"DrawerHeader\");\n  if (shown === \"dialog\") return <DialogHeader className={className} {...props} />;\n  return <div data-slot=\"drawer-header\" className={cn(\"grid gap-1.5\", className)} {...props} />;\n}\n\n/**\n * Actions. In the sheet they're pinned to its bottom, full width with the main one on top, above the home\n * indicator; in the dialog, a row at the end. Put the main action last, as in Dialog.\n */\nfunction DrawerFooter({ className, ...props }: ComponentProps<\"div\">) {\n  const { shown } = useDrawer(\"DrawerFooter\");\n  if (shown === \"dialog\") return <DialogFooter className={className} {...props} />;\n  return (\n    <div\n      data-slot=\"drawer-footer\"\n      className={cn(\n        \"sticky bottom-0 -mx-6 flex flex-col-reverse gap-2 bg-background px-6 pt-3 pb-(--size-sheet-inset-bottom)\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nfunction DrawerTitle({ className, ...props }: ComponentProps<typeof Vaul.Title>) {\n  const { shown } = useDrawer(\"DrawerTitle\");\n  if (shown === \"dialog\") return <DialogTitle className={className} {...props} />;\n  return (\n    <Vaul.Title data-slot=\"drawer-title\" className={cn(\"text-base font-semibold\", className)} {...props} />\n  );\n}\n\nfunction DrawerDescription({ className, ...props }: ComponentProps<typeof Vaul.Description>) {\n  const { shown } = useDrawer(\"DrawerDescription\");\n  if (shown === \"dialog\") {\n    return <DialogDescription className={className} {...props} />;\n  }\n  return (\n    <Vaul.Description\n      data-slot=\"drawer-description\"\n      className={cn(\"text-sm text-muted-foreground\", className)}\n      {...props}\n    />\n  );\n}\n\nexport {\n  Drawer,\n  DrawerClose,\n  DrawerContent,\n  DrawerDescription,\n  DrawerFooter,\n  DrawerHeader,\n  DrawerTitle,\n  DrawerTrigger,\n};\n"
    }
  ],
  "categories": [
    "overlays"
  ],
  "docs": "Usage and examples: https://ui.fewtone.com/components/drawer"
}
