{"slug":"drawer","name":"Drawer","description":"Side panel that slides in from the left or right with a spring, backdrop blur, body scroll lock and esc-to-close.","category":"motion","source_url":"https://beui.dev/r/drawer/raw","detail_url":"https://beui.dev/r/drawer","raw_url":"https://beui.dev/r/drawer/raw","page_url":"https://beui.dev/components/motion/drawer","markdown_url":"https://beui.dev/components/motion/drawer.md","published_at":"2026-06-22","updated_at":"2026-11-25","dependencies":["clsx","motion","react","tailwind-merge"],"internal":["@/components/motion/drawer","@/lib/ease","@/lib/focusable","@/lib/hooks/use-focus-trap","@/lib/i18n","@/lib/layers","@/lib/presence-gate","@/lib/scroll-lock","@/lib/utils"],"install_slugs":["drawer"],"requires_theme":false,"props":[{"displayName":"Drawer","props":[{"name":"open","type":"boolean","required":true,"defaultValue":null,"description":"Whether the drawer is shown."},{"name":"onOpenChange","type":"(open: boolean) => void","required":true,"defaultValue":null,"description":"Called with false when the backdrop, Escape or a swipe closes the drawer."},{"name":"side","type":"\"left\" | \"right\"","required":false,"defaultValue":"right","description":"Edge of the viewport the panel slides in from. Default: \"right\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Class for the panel surface."},{"name":"backdropClassName","type":"string","required":false,"defaultValue":null,"description":"Class for the backdrop."},{"name":"ariaLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the dialog panel."},{"name":"dismissable","type":"boolean","required":false,"defaultValue":"true","description":"Close when the backdrop is clicked, Escape is pressed, or the panel is\nswiped toward its edge. Default true. Mark content that must keep its own\nhorizontal gestures with `data-drawer-no-drag`."},{"name":"labels","type":"Partial<{ close: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]}],"types":[],"files":[{"path":"components/motion/drawer.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/drawer\n\nimport {\n  AnimatePresence,\n  motion,\n  type PanInfo,\n  useDragControls,\n  useReducedMotion,\n} from \"motion/react\";\nimport { type PointerEvent, type ReactNode, useRef } from \"react\";\nimport { EASE_DRAWER, EASE_OUT } from \"@/lib/ease\";\nimport { useFocusTrap } from \"@/lib/hooks/use-focus-trap\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { PresenceGate } from \"@/lib/presence-gate\";\nimport { useScrollLock } from \"@/lib/scroll-lock\";\nimport { cn } from \"@/lib/utils\";\n\n// The iOS sheet curve: one clean deceleration in, and a shorter one out, so\n// the panel leaves faster than it arrives.\nconst SLIDE_IN = { duration: 0.45, ease: EASE_DRAWER } as const;\nconst SLIDE_OUT = { duration: 0.3, ease: EASE_DRAWER } as const;\n// A flick this fast (px/s) toward the edge closes it, however short.\nconst FLING = 500;\n// Or a drag past this share of the panel's width.\nconst DISMISS_SHARE = 0.35;\n// A swipe never starts on something the finger is using.\nconst NO_DRAG = \"input, textarea, select, [contenteditable='true'], [role='slider'], [data-drawer-no-drag]\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const drawerMessages = {\n  close: \"Close\",\n};\n\nexport type DrawerMessages = typeof drawerMessages;\n\nexport interface DrawerProps {\n  /** Whether the drawer is shown. */\n  open: boolean;\n  /** Called with false when the backdrop, Escape or a swipe closes the drawer. */\n  onOpenChange: (open: boolean) => void;\n  /** Edge of the viewport the panel slides in from. Default: \"right\" */\n  side?: \"left\" | \"right\";\n  children: ReactNode;\n  /** Class for the panel surface. */\n  className?: string;\n  /** Class for the backdrop. */\n  backdropClassName?: string;\n  /** Accessible name for the dialog panel. */\n  ariaLabel?: string;\n  /**\n   * Close when the backdrop is clicked, Escape is pressed, or the panel is\n   * swiped toward its edge. Default true. Mark content that must keep its own\n   * horizontal gestures with `data-drawer-no-drag`.\n   */\n  dismissable?: boolean;\n  /** Override any built-in string. */\n  labels?: Partial<DrawerMessages>;\n}\n\nexport function Drawer({\n  open,\n  onOpenChange,\n  side = \"right\",\n  children,\n  className,\n  backdropClassName,\n  ariaLabel,\n  dismissable = true,\n  labels,\n}: DrawerProps) {\n  const t = useMessages(\"drawer\", drawerMessages, labels);\n  const reduce = useReducedMotion();\n  const panelRef = useRef<HTMLDivElement>(null);\n  const dragControls = useDragControls();\n\n  // Focus moves into the panel on open, Tab stays inside it, and focus returns\n  // to the opener on close.\n  useFocusTrap(open, panelRef, {\n    onEscape: dismissable ? () => onOpenChange(false) : undefined,\n  });\n\n  useScrollLock(open);\n\n  const offscreen = side === \"right\" ? \"100%\" : \"-100%\";\n  // Positive means toward the edge the drawer leaves by.\n  const toward = side === \"right\" ? 1 : -1;\n\n  // Only a finger or pen swipes the panel shut; a mouse drag over it selects\n  // text, as it should on a desktop.\n  const startSwipe = (event: PointerEvent<HTMLDivElement>) => {\n    if (!dismissable || event.pointerType === \"mouse\") return;\n    if ((event.target as Element).closest(NO_DRAG)) return;\n    dragControls.start(event);\n  };\n\n  const endSwipe = (_: unknown, info: PanInfo) => {\n    const distance = info.offset.x * toward;\n    const speed = info.velocity.x * toward;\n    const width = panelRef.current?.offsetWidth ?? 320;\n    // A quick flick is enough; a slow drag has to go a third of the way.\n    if (speed > FLING || distance > width * DISMISS_SHARE) onOpenChange(false);\n  };\n\n  // Two fixed siblings, no wrapper: the backdrop spans the viewport edges but\n  // paints the scrim, and the panel is inset off one side and paints its own\n  // surface, so neither is a transparent edge-spanning layer. Both hang off\n  // `PresenceGate`, so interaction releases in the same commit that starts the\n  // exit rather than when it ends.\n  return (\n    <AnimatePresence>\n      {open ? (\n        <PresenceGate key=\"backdrop\">\n          {({ gate }) => (\n            <motion.button\n              type=\"button\"\n              aria-label={t(\"close\")}\n              // Outside the panel, so the focus trap never lands on it; it is\n              // a pointer target only.\n              tabIndex={-1}\n              onClick={() => dismissable && onOpenChange(false)}\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              // The scrim clears faster than it settles, like the panel.\n              exit={{ opacity: 0, transition: { duration: 0.2, ease: EASE_OUT } }}\n              transition={{ duration: 0.25, ease: EASE_OUT }}\n              {...gate}\n              className={cn(\n                \"fixed inset-0 z-50 h-full w-full cursor-default bg-black/40 backdrop-blur-sm\",\n                backdropClassName,\n              )}\n            />\n          )}\n        </PresenceGate>\n      ) : null}\n      {open ? (\n        <PresenceGate key=\"panel\">\n          {({ gate }) => (\n            <motion.div\n              ref={panelRef}\n              tabIndex={-1}\n              role=\"dialog\"\n              aria-modal=\"true\"\n              aria-label={ariaLabel}\n              initial={reduce ? { opacity: 0 } : { x: offscreen }}\n              animate={reduce ? { opacity: 1 } : { x: 0 }}\n              exit={\n                reduce\n                  ? { opacity: 0, transition: { duration: 0.15, ease: EASE_OUT } }\n                  : { x: offscreen, transition: SLIDE_OUT }\n              }\n              transition={reduce ? { duration: 0.2, ease: EASE_OUT } : SLIDE_IN}\n              // Swipe toward the edge to close. Toward the page it meets\n              // friction instead of a wall, and a short swipe springs back.\n              drag=\"x\"\n              dragControls={dragControls}\n              dragListener={false}\n              dragConstraints={{ left: 0, right: 0 }}\n              dragElastic={side === \"right\" ? { left: 0.04, right: 1 } : { left: 1, right: 0.04 }}\n              dragMomentum={false}\n              onPointerDown={startSwipe}\n              onDragEnd={endSwipe}\n              {...gate}\n              className={cn(\n                // Vertical scrolling stays native; only a sideways swipe drags.\n                \"fixed inset-y-0 z-50 flex w-80 max-w-[85vw] touch-pan-y flex-col bg-background shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none\",\n                // Only the corners facing the page are rounded; the edge\n                // against the viewport stays square.\n                side === \"right\"\n                  ? \"right-0 rounded-l-2xl border-l border-border\"\n                  : \"left-0 rounded-r-2xl border-r border-border\",\n                className,\n              )}\n            >\n              {children}\n            </motion.div>\n          )}\n        </PresenceGate>\n      ) : null}\n    </AnimatePresence>\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-focus-trap.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport { cycleTab, focusFirstIn } from \"@/lib/focusable\";\nimport { inLayerAbove, type Layer, openLayer, ownsEscape, trapAbove } from \"@/lib/layers\";\n\nexport interface FocusTrapOptions {\n  /** Called on Escape while this is the innermost open layer. */\n  onEscape?: () => void;\n}\n\n/**\n * Moves focus into `panel` when `open` turns true, keeps Tab cycling inside it,\n * pulls focus back if it lands outside, and returns focus to whatever held it\n * before opening once `open` turns false.\n *\n * Layers opened on top (a menu portaled out of a drawer, a sheet opened from\n * it) keep focus and Escape until they close: see `lib/layers.ts`.\n *\n * For overlays rendered in place, where `useModalScope` cannot inert the rest\n * of the page. Pass `open` rather than presence: an exiting panel is already\n * inert through `PresenceGate`, so the trap releases with the same commit.\n * Give the panel `tabIndex={-1}` so it can take focus when it holds nothing\n * focusable.\n */\nexport function useFocusTrap(\n  open: boolean,\n  panel: RefObject<HTMLElement | null>,\n  { onEscape }: FocusTrapOptions = {},\n) {\n  const escapeRef = useRef(onEscape);\n  useLayoutEffect(() => {\n    escapeRef.current = onEscape;\n  });\n\n  useEffect(() => {\n    if (!open || !panel.current) return;\n    const layer: Layer = {\n      contains: (target) => Boolean(panel.current?.contains(target)),\n      traps: true,\n      get escape() {\n        return Boolean(escapeRef.current);\n      },\n    };\n    const closeLayer = openLayer(layer);\n    const returnFocus =\n      document.activeElement instanceof HTMLElement\n        ? document.activeElement\n        : null;\n    if (!panel.current.contains(document.activeElement)) focusFirstIn(panel.current);\n\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (!(target instanceof Node) || !panel.current) return;\n      if (panel.current.closest(\"[inert]\") || panel.current.contains(target)) return;\n      if (inLayerAbove(layer, target) || trapAbove(layer)) return;\n      focusFirstIn(panel.current);\n    };\n    const onKey = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") {\n        if (!escapeRef.current || !ownsEscape(layer, event)) return;\n        event.preventDefault();\n        escapeRef.current();\n        return;\n      }\n      const active = document.activeElement;\n      if (event.defaultPrevented || (active && inLayerAbove(layer, active))) return;\n      cycleTab(event, panel.current);\n    };\n    document.addEventListener(\"focusin\", onFocus);\n    document.addEventListener(\"keydown\", onKey);\n    return () => {\n      document.removeEventListener(\"focusin\", onFocus);\n      document.removeEventListener(\"keydown\", onKey);\n      closeLayer();\n      if (returnFocus?.isConnected && !returnFocus.closest(\"[inert]\"))\n        returnFocus.focus({ preventScroll: true });\n    };\n  }, [open, panel]);\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/presence-gate.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PresenceGateRenderProps {\n  /**\n   * False from the render that starts the exit animation onward. An overlay\n   * kept in the tree by `AnimatePresence` is still the topmost thing on the\n   * page, so anything it decides from `open` alone stays true for the whole\n   * exit - this is the boolean that already knows the overlay is leaving.\n   */\n  isPresent: boolean;\n  /**\n   * Spread onto every layer that takes pointer events while the overlay is\n   * open. Interaction releases in the same commit that starts the exit while\n   * the visual exit keeps playing: pointer events stop landing, and `inert`\n   * drops the subtree from focus order, from tab order and from the\n   * accessibility tree - an exiting dialog is not a dialog you can still type\n   * into. A layer that never takes pointer events (a wrapper that only centres\n   * the panel) takes `inert={!isPresent}` alone, so its own\n   * `pointer-events-none` is not overwritten.\n   */\n  gate: {\n    inert: boolean;\n    style: { pointerEvents: \"auto\" | \"none\" };\n  };\n}\n\nexport interface PresenceGateProps {\n  children: (props: PresenceGateRenderProps) => ReactNode;\n}\n\n/**\n * Reads the presence of the subtree it renders and hands it down.\n *\n * `useIsPresent` only answers inside the `AnimatePresence` subtree, and the\n * components that own an overlay render the `AnimatePresence` themselves, so\n * the boolean has to be read one component further down: this is that\n * component, and the render prop is how it reaches the layers.\n */\nexport function PresenceGate({ children }: PresenceGateProps) {\n  const isPresent = useIsPresent();\n\n  return children({\n    isPresent,\n    gate: {\n      inert: !isPresent,\n      style: { pointerEvents: isPresent ? \"auto\" : \"none\" },\n    },\n  });\n}\n"},{"path":"lib/scroll-lock.ts","type":"util","content":"\"use client\";\n\nimport { useEffect } from \"react\";\n\nexport interface ScrollLockOptions {\n  /**\n   * Pin the body with `position: fixed` and restore the scroll offset on\n   * release. iOS Safari still scrolls an `overflow: hidden` body under a\n   * touch drag, so full-screen sheets that take touch gestures need this.\n   */\n  fixed?: boolean;\n}\n\n// Reference-counted, so overlays that close out of order never unlock the\n// page under one that is still open. The first lock picks the technique.\nlet owners = 0;\nlet restore: (() => void) | null = null;\n\nfunction apply({ fixed = false }: ScrollLockOptions) {\n  const root = document.documentElement;\n  const body = document.body;\n  const scrollY = window.scrollY;\n  const previous = {\n    rootOverflow: root.style.overflow,\n    overflow: body.style.overflow,\n    position: body.style.position,\n    top: body.style.top,\n    left: body.style.left,\n    right: body.style.right,\n  };\n  root.style.overflow = \"hidden\";\n  body.style.overflow = \"hidden\";\n  if (fixed) {\n    body.style.position = \"fixed\";\n    body.style.top = `-${scrollY}px`;\n    body.style.left = \"0\";\n    body.style.right = \"0\";\n  }\n  return () => {\n    root.style.overflow = previous.rootOverflow;\n    body.style.overflow = previous.overflow;\n    if (!fixed) return;\n    body.style.position = previous.position;\n    body.style.top = previous.top;\n    body.style.left = previous.left;\n    body.style.right = previous.right;\n    window.scrollTo(0, scrollY);\n  };\n}\n\n/** Locks page scroll. Call the returned function to release this lock. */\nexport function lockScroll(options: ScrollLockOptions = {}) {\n  if (owners++ === 0) restore = apply(options);\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    if (--owners === 0) {\n      restore?.();\n      restore = null;\n    }\n  };\n}\n\n/** Locks page scroll while `locked` is true. */\nexport function useScrollLock(locked: boolean, { fixed = false }: ScrollLockOptions = {}) {\n  useEffect(() => {\n    if (!locked) return;\n    return lockScroll({ fixed });\n  }, [locked, fixed]);\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"lib/focusable.ts","type":"util","content":"/**\n * Elements that can usually take keyboard focus. The selector cannot see\n * everything focus() checks (an element under `display: none`, say), so a\n * caller that needs certainty tries focus() and checks where it landed.\n */\nexport const FOCUSABLE_SELECTOR = [\n  \"a[href]\",\n  \"button:not(:disabled)\",\n  \"input:not(:disabled):not([type='hidden'])\",\n  \"select:not(:disabled)\",\n  \"textarea:not(:disabled)\",\n  \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n\n/** Elements inside `container` that Tab can reach, in DOM order. */\nexport function focusablesIn(container: Element | null | undefined) {\n  return Array.from(\n    container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],\n  ).filter((element) => element.tabIndex >= 0 && !element.closest(\"[inert]\"));\n}\n\n/** Focuses the first tabbable element in `panel`, or the panel itself. */\nexport function focusFirstIn(panel: HTMLElement | null | undefined) {\n  (focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });\n}\n\n/**\n * Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element\n * to the first and back. Give the panel `tabIndex={-1}` so it can hold focus\n * when it has nothing tabbable.\n */\nexport function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {\n  if (event.key !== \"Tab\" || !panel) return;\n  const elements = focusablesIn(panel);\n  const first = elements[0];\n  const last = elements[elements.length - 1];\n  const active = document.activeElement;\n  if (!first || !last) {\n    event.preventDefault();\n    panel.focus({ preventScroll: true });\n  } else if (event.shiftKey && (active === first || active === panel)) {\n    event.preventDefault();\n    last.focus();\n  } else if (!event.shiftKey && active === last) {\n    event.preventDefault();\n    first.focus();\n  }\n}\n"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"components/previews/motion/drawer.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { useState } from \"react\";\nimport { Drawer } from \"@/components/motion/drawer\";\n\nexport function DrawerPreview() {\n  const [open, setOpen] = useState(false);\n  const [side, setSide] = useState<\"left\" | \"right\">(\"right\");\n\n  const openWith = (s: \"left\" | \"right\") => {\n    setSide(s);\n    setOpen(true);\n  };\n\n  return (\n    <div className=\"flex items-center gap-3\">\n      <button\n        type=\"button\"\n        onClick={() => openWith(\"left\")}\n        className=\"inline-flex h-10 items-center rounded-full border border-border bg-card px-5 text-sm font-medium text-foreground transition-colors hover:bg-card/70\"\n      >\n        Open left\n      </button>\n      <button\n        type=\"button\"\n        onClick={() => openWith(\"right\")}\n        className=\"inline-flex h-10 items-center rounded-full bg-primary px-5 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90\"\n      >\n        Open right\n      </button>\n\n      <Drawer\n        open={open}\n        onOpenChange={setOpen}\n        side={side}\n        ariaLabel=\"Demo drawer\"\n        className=\"gap-4 p-6\"\n      >\n        <h2 className=\"text-sm font-medium text-foreground\">Drawer</h2>\n        <p className=\"text-sm text-muted-foreground\">\n          Slides in from the {side}. Press Esc or click outside to close.\n        </p>\n        <button\n          type=\"button\"\n          onClick={() => setOpen(false)}\n          className=\"mt-auto inline-flex h-10 items-center justify-center rounded-full border border-border bg-card px-5 text-sm font-medium text-foreground transition-colors hover:bg-card/70\"\n        >\n          Close\n        </button>\n      </Drawer>\n    </div>\n  );\n}\n"}]}