{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "drawer",
  "type": "registry:ui",
  "title": "Drawer",
  "description": "A temporary side surface for focused work.",
  "categories": [
    "disclosure"
  ],
  "dependencies": [
    "@radix-ui/react-dialog",
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://irisui.dev/r/foundation.json",
    "https://irisui.dev/r/utils.json",
    "https://irisui.dev/r/motion-tokens.json"
  ],
  "files": [
    {
      "path": "src/registry/components/drawer/drawer.tsx",
      "content": "\"use client\";\n\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\";\nimport { createContext, useCallback, useContext, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, ReactNode, RefObject } from \"react\";\nimport { AnimatePresence, animate, motion, useMotionValue, useReducedMotion } from \"motion/react\";\nimport type { PanInfo, Transition } from \"motion/react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\nimport { motionTokens } from \"../lib/motion-tokens\";\n\ntype Side = \"left\" | \"right\" | \"top\" | \"bottom\";\n\n/* While a layer leaves it lets clicks through, so pressing the trigger again during the close reopens the drawer from wherever it is.\n   Radix writes pointer-events inline on the overlay, so the closing state has to win over it. */\nconst overlayClass =\n  \"fixed inset-0 z-50 bg-[oklch(10%_0_0/.38)] backdrop-blur-[4px] data-[state=closed]:pointer-events-none!\";\n/* Inside a container the layers anchor to that element instead of the viewport. */\nconst overlayContained = \"absolute z-1 bg-[oklch(10%_0_0/.16)] backdrop-blur-none\";\nconst panelClass =\n  \"fixed z-51 flex max-h-dvh w-(--drawer-size) max-w-screen flex-col overflow-hidden border-line bg-surface text-ink shadow-floating focus:outline-none data-[state=closed]:pointer-events-none!\";\n/* Each edge anchors the panel, rounds its free corners and names the off-screen start (--drawer-from) for the keyframes. */\nconst panelSides: Record<Side, string> = {\n  right:\n    \"inset-[0_0_0_auto] rounded-[22px_0_0_22px] [--drawer-from:translateX(100%)] max-[40rem]:rounded-[18px_0_0_18px]\",\n  left: \"inset-[0_auto_0_0] rounded-[0_22px_22px_0] [--drawer-from:translateX(-100%)] max-[40rem]:rounded-[0_18px_18px_0]\",\n  top: \"inset-[0_0_auto] max-h-[min(32rem,100dvh)] w-full max-w-none rounded-[0_0_22px_22px] [--drawer-from:translateY(-100%)] max-[40rem]:rounded-[0_0_18px_18px]\",\n  bottom:\n    \"inset-[auto_0_0] max-h-[min(32rem,100dvh)] w-full max-w-none rounded-[22px_22px_0_0] [--drawer-from:translateY(100%)] max-[40rem]:rounded-[18px_18px_0_0] before:absolute before:top-[9px] before:left-1/2 before:h-1 before:w-9 before:-translate-x-1/2 before:rounded-full before:bg-line-strong before:opacity-75 before:content-['']\",\n};\n/* On the page the panel draws every edge but the one it is anchored to; in a container the container draws the outer edges, so only the inner edge keeps a border. */\nconst panelBorders: Record<Side, [string, string]> = {\n  right: [\"[border-width:1px_0_1px_1px]\", \"[border-width:0_0_0_1px]\"],\n  left: [\"[border-width:1px_1px_1px_0]\", \"[border-width:0_1px_0_0]\"],\n  top: [\"[border-width:0_0_1px]\", \"[border-width:0_0_1px]\"],\n  bottom: [\"[border-width:1px_0_0]\", \"[border-width:1px_0_0]\"],\n};\n/* Motion springs the panel from its edge. These keyframes only run when DrawerContent sits under a bare Radix root. */\nconst overlayKeyframes =\n  \"data-[state=closed]:animate-drawer-overlay-out data-[state=open]:animate-drawer-overlay-in motion-reduce:data-[state=closed]:animate-drawer-overlay-fade-out motion-reduce:data-[state=open]:animate-drawer-overlay-fade-in\";\nconst panelKeyframes =\n  \"data-[state=closed]:animate-drawer-out data-[state=open]:animate-drawer-in motion-reduce:data-[state=closed]:animate-drawer-fade-out motion-reduce:data-[state=open]:animate-drawer-fade-in\";\n/* A compact icon button centred on the first line of the title rather than its top edge: quick press, spring release. */\nconst closeClass =\n  \"mt-[calc((var(--text-lg)_*_var(--leading-body)_-_var(--space-8))_/_2)] grid size-8 flex-none cursor-pointer place-items-center rounded-button border border-line bg-[color-mix(in_oklab,var(--hover)_65%,transparent)] text-ink-2 [transition:background-color_var(--duration-fast)_var(--ease-standard),color_var(--duration-fast)_var(--ease-standard),transform_var(--duration-spring)_var(--ease-spring)] hover:bg-hover hover:text-ink active:[transform:scale(.96)] active:[transition:background-color_var(--duration-fast)_var(--ease-standard),color_var(--duration-fast)_var(--ease-standard),transform_var(--duration-instant)_var(--ease-standard)] motion-reduce:transition-none motion-reduce:active:transform-none motion-reduce:active:transition-none\";\n\n/**\n * The last item a drawer showed. Pass the selected item (or null when nothing is open) and render the drawer's content\n * from the result, so the content stays on screen while the panel slides out instead of vanishing the moment it closes.\n */\nexport function useDrawerItem<T>(item: T | null | undefined): T | null | undefined {\n  const [last, setLast] = useState(item);\n  if (item != null && item !== last) setLast(item);\n  return item ?? last;\n}\n\n/** Mirrors the open state so the panel can stay mounted while it slides out, retarget mid-flight, and close itself after a drag. */\nconst DrawerContext = createContext<{\n  open: boolean;\n  flung: boolean;\n  setOpen: (open: boolean) => void;\n  fling: () => void;\n  openedAt: RefObject<number>;\n} | null>(null);\n\nexport function Drawer({\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  ...props\n}: ComponentPropsWithoutRef<typeof DialogPrimitive.Root>) {\n  const [uncontrolled, setUncontrolled] = useState(defaultOpen);\n  // A drag that dismisses the panel hands its velocity to the exit spring; every other close uses the shorter tween.\n  const [flung, setFlung] = useState(false);\n  // When the drawer last opened, so a click that reopens it mid-close is not also read as a click outside the leaving panel.\n  const openedAt = useRef(0);\n  const open = openProp ?? uncontrolled;\n  const setOpen = useCallback(\n    (next: boolean) => {\n      setFlung(false);\n      if (next) openedAt.current = performance.now();\n      if (openProp === undefined) setUncontrolled(next);\n      onOpenChange?.(next);\n    },\n    [openProp, onOpenChange],\n  );\n  const fling = useCallback(() => {\n    setOpen(false);\n    setFlung(true);\n  }, [setOpen]);\n  const value = useMemo(() => ({ open, flung, setOpen, fling, openedAt }), [open, flung, setOpen, fling]);\n  return (\n    <DrawerContext.Provider value={value}>\n      <DialogPrimitive.Root {...props} open={open} onOpenChange={setOpen} />\n    </DrawerContext.Provider>\n  );\n}\n\nexport const DrawerTrigger = DialogPrimitive.Trigger;\nexport const DrawerClose = DialogPrimitive.Close;\n\nexport interface DrawerContentProps extends ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {\n  title: string;\n  description?: string;\n  children: ReactNode;\n  side?: Side;\n  /** Renders the drawer inside this element instead of the page body, anchored to its edges. The element needs position: relative and overflow: hidden. */\n  container?: HTMLElement | null;\n}\n\nconst fade: Transition = { duration: motionTokens.duration.instant };\n/* A click or Escape returns the panel quickly; a flick keeps its velocity in a spring of the same length. The shadow fades over the last stretch so it leaves with the panel instead of popping away at unmount. */\nconst shadowOut: Transition = { duration: motionTokens.duration.standard, times: [0, 0.65, 1], ease: \"linear\" };\nconst leave: Transition = {\n  default: { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.standard] },\n  opacity: shadowOut,\n};\nconst flingOut: Transition = {\n  default: { ...motionTokens.spring.smooth, visualDuration: motionTokens.duration.standard },\n  opacity: shadowOut,\n};\n\n/** When the title or description changes while open, the new copy rises in and the old copy leaves upward. */\nfunction SwapText({ text }: { text: string }) {\n  const reduced = useReducedMotion();\n  return (\n    <AnimatePresence mode=\"popLayout\" initial={false}>\n      <motion.span\n        key={text}\n        className=\"block leading-body\"\n        initial={reduced ? false : { opacity: 0, y: \"0.3em\", filter: `blur(${motionTokens.blur.soft}px)` }}\n        animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n        exit={\n          reduced\n            ? { opacity: 0, transition: { duration: 0 } }\n            : {\n                opacity: 0,\n                y: \"-0.3em\",\n                filter: `blur(${motionTokens.blur.subtle}px)`,\n                transition: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] },\n              }\n        }\n        transition={{ duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }}\n      >\n        {text}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\nexport function DrawerContent({\n  title,\n  description,\n  children,\n  side = \"right\",\n  container,\n  className,\n  onInteractOutside,\n  ...props\n}: DrawerContentProps) {\n  const drawer = useContext(DrawerContext);\n  const reduced = useReducedMotion();\n  const panelRef = useRef<HTMLDivElement>(null);\n  const offset = useMotionValue<number | string>(0);\n  const pan = useRef<number | null>(null);\n  const axis = side === \"left\" || side === \"right\" ? \"x\" : \"y\";\n  const sign = side === \"right\" || side === \"bottom\" ? 1 : -1;\n  const offscreen = { [axis]: `${sign * 100}%` };\n  const contained = !!container;\n  const classes = cn(\n    panelClass,\n    panelSides[side],\n    panelBorders[side][contained ? 1 : 0],\n    contained\n      ? cn(\n          \"absolute z-2 max-h-full shadow-none [--drawer-size:min(22rem,calc(100%_-_var(--space-8)))]\",\n          (side === \"top\" || side === \"bottom\") && \"max-h-[min(32rem,calc(100%_-_var(--space-8)))]\",\n        )\n      : \"[--drawer-size:min(30rem,calc(100vw_-_var(--space-4)))] max-[40rem]:[--drawer-size:calc(100vw_-_var(--space-3))]\",\n    className,\n  );\n  const draggable = drawer !== null && !reduced;\n\n  const panelSize = () => (axis === \"x\" ? panelRef.current?.offsetWidth : panelRef.current?.offsetHeight) ?? 480;\n\n  // The header is the grab handle. It follows the pointer toward the edge and rubber-bands the other way.\n  function panStart(event: PointerEvent) {\n    const target = event.target instanceof Element ? event.target : null;\n    if (!draggable || target?.closest(\"button, a, input, select, textarea, [role='button']\")) return;\n    // The entrance animates in percent of the panel, so a grab mid-flight converts it to pixels.\n    const value = offset.get();\n    pan.current = typeof value === \"number\" ? value : (parseFloat(value) / 100) * panelSize();\n    offset.stop();\n  }\n  function panMove(_: PointerEvent, info: PanInfo) {\n    if (pan.current === null) return;\n    const toward = (pan.current + info.offset[axis]) * sign;\n    offset.set(sign * (toward >= 0 ? toward : -Math.sqrt(-toward)));\n  }\n  // Past a third of the panel, or on a quick flick toward the edge, the drawer closes and keeps its velocity; otherwise it springs back.\n  function panEnd(_: PointerEvent, info: PanInfo) {\n    if (pan.current === null) return;\n    pan.current = null;\n    const toward = Number(offset.get()) * sign;\n    if (toward > panelSize() / 3 || (toward > 0 && info.velocity[axis] * sign > 500)) drawer?.fling();\n    else animate(offset, 0, motionTokens.spring.snappy);\n  }\n\n  const inner = (\n    <>\n      {/* The header doubles as the drag handle, so touch drags move the panel instead of the page. */}\n      <motion.div\n        className={cn(\n          \"flex flex-none items-start justify-between gap-5 border-b border-line p-6 max-[40rem]:p-5\",\n          draggable && \"touch-none select-none\",\n          draggable && (side === \"top\" || side === \"bottom\") && \"cursor-grab\",\n        )}\n        onPanStart={panStart}\n        onPan={panMove}\n        onPanEnd={panEnd}\n      >\n        <div>\n          <DialogPrimitive.Title className=\"relative m-0 font-body text-lg leading-body font-medium tracking-body\">\n            <SwapText text={title} />\n          </DialogPrimitive.Title>\n          {description ? (\n            <DialogPrimitive.Description className=\"relative mt-2 mb-0 max-w-lg text-sm leading-body text-ink-2\">\n              <SwapText text={description} />\n            </DialogPrimitive.Description>\n          ) : null}\n        </div>\n        <DialogPrimitive.Close className={closeClass} aria-label=\"Close drawer\">\n          <X size={16} strokeWidth={1.75} aria-hidden=\"true\" />\n        </DialogPrimitive.Close>\n      </motion.div>\n      <div className=\"min-h-0 overflow-auto overscroll-contain p-6 text-sm leading-body [scrollbar-width:thin] max-[40rem]:p-5\">\n        {children}\n      </div>\n    </>\n  );\n\n  // Under a bare Radix root the open state is unknown here, so CSS keyframes keyed off data-state animate the layers instead.\n  if (drawer === null) {\n    return (\n      <DialogPrimitive.Portal container={container}>\n        <DialogPrimitive.Overlay\n          className={cn(overlayClass, contained && overlayContained, overlayKeyframes)}\n          data-contained={container ? \"\" : undefined}\n        />\n        <DialogPrimitive.Content\n          {...props}\n          onInteractOutside={onInteractOutside}\n          data-side={side}\n          data-contained={container ? \"\" : undefined}\n          className={cn(classes, panelKeyframes)}\n        >\n          {inner}\n        </DialogPrimitive.Content>\n      </DialogPrimitive.Portal>\n    );\n  }\n\n  // The panel springs fully opaque from its own edge and returns to it faster than it arrived, from wherever it is.\n  return (\n    <AnimatePresence custom={drawer.flung}>\n      {drawer.open && (\n        <DialogPrimitive.Portal key=\"drawer\" forceMount container={container}>\n          <DialogPrimitive.Overlay asChild forceMount>\n            <motion.div\n              className={cn(overlayClass, contained && overlayContained)}\n              data-contained={container ? \"\" : undefined}\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{\n                opacity: 0,\n                transition: reduced\n                  ? fade\n                  : { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] },\n              }}\n              transition={\n                reduced ? fade : { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }\n              }\n            />\n          </DialogPrimitive.Overlay>\n          <DialogPrimitive.Content\n            {...props}\n            asChild\n            forceMount\n            // Radix reads a click outside on click, so the press that reopens a closing drawer would dismiss it again.\n            onInteractOutside={(event) => {\n              onInteractOutside?.(event);\n              if (event.detail.originalEvent.timeStamp < drawer.openedAt.current) event.preventDefault();\n            }}\n          >\n            <motion.div\n              ref={panelRef}\n              className={classes}\n              data-side={side}\n              data-contained={container ? \"\" : undefined}\n              style={{ [axis]: offset }}\n              variants={{\n                exit: (flung: boolean) =>\n                  reduced\n                    ? { opacity: 0, transition: fade }\n                    : { ...offscreen, opacity: [1, 1, 0], transition: flung ? flingOut : leave },\n              }}\n              initial={reduced ? { opacity: 0 } : { ...offscreen, opacity: 1 }}\n              animate={reduced ? { opacity: 1 } : { [axis]: 0, opacity: 1 }}\n              exit=\"exit\"\n              transition={reduced ? fade : motionTokens.spring.smooth}\n            >\n              {inner}\n            </motion.div>\n          </DialogPrimitive.Content>\n        </DialogPrimitive.Portal>\n      )}\n    </AnimatePresence>\n  );\n}\n\nexport default Drawer;\n",
      "type": "registry:component",
      "target": "@components/iris/drawer/drawer.tsx"
    }
  ],
  "docs": "Docs and live preview: https://irisui.dev/components/drawer",
  "meta": {
    "kind": "component",
    "group": "Overlays & disclosure",
    "export": "Drawer",
    "tags": [
      "overlay",
      "surface"
    ],
    "docs": "https://irisui.dev/components/drawer"
  }
}
