{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"stacked-drawer","type":"registry:component","title":"Stacked drawer","description":"Stacks iOS sheets that push the page back and drag down to dismiss.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/stacked-drawer.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  motionValue,\n  useMotionValue,\n  useTransform,\n  type MotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst FRAME_H = 560;\n// The first sheet stops this far below the frame's top, and each nested one\n// a step lower, so every layer behind keeps a sliver showing above the next.\nconst FIRST_TOP = 40;\nconst STEP = 18;\n// Pushed back: the page drops by one step so its top peeks out above the\n// first sheet, the way iOS tucks the presenting screen behind a sheet.\nconst BASE_DROP = 18;\nconst PUSH_SCALE = 0.94;\nconst DIM = 0.2;\n// Past the frame's bottom edge, so the sheet's shadow is hidden too.\nconst OFFSCREEN = 24;\n// Upward overdrag tops out here. Sheets extend this far below the frame, so\n// rubber-banding up never opens a gap underneath.\nconst RUBBER = 36;\n// Movement below this still counts as a tap on whatever was pressed.\nconst DRAG_START = 4;\n// Released past 30% of its height, or flicked down faster than this (px/s),\n// the sheet dismisses; otherwise it settles back.\nconst DISMISS_DISTANCE = 0.3;\nconst DISMISS_VELOCITY = 500;\n\nconst EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n// Longer than most UI motion because a sheet travels the whole frame; at\n// 300ms it reads as a jump. Closing is quicker, since it gets out of the way.\nconst OPEN = { duration: 0.45, ease: EASE_DRAWER };\nconst CLOSE = { duration: 0.32, ease: EASE_DRAWER };\n// After a drag, a spring picks up the finger's release speed. Near critical\n// damping (2 * sqrt(380) is about 39), so it settles without a wobble.\nconst RELEASE = { type: \"spring\", stiffness: 380, damping: 38 } as const;\nconst FADE = { duration: 0.2, ease: [0.23, 1, 0.32, 1] } as const;\n\ntype Sheet = {\n  title: string;\n  description: string;\n  // Label for the button that opens the next sheet in the stack.\n  next?: string;\n};\n\ntype Values = { y: MotionValue<number>; opacity: MotionValue<number> };\n\nconst topOf = (i: number) => FIRST_TOP + i * STEP;\nconst heightOf = (i: number) => FRAME_H - topOf(i);\nconst closedAt = (i: number) => heightOf(i) + OFFSCREEN;\n\nfunction rubberBand(overdrag: number) {\n  // Half the cap is reached after 120px of pull, so resistance builds slowly.\n  return RUBBER * (1 - 1 / (1 + overdrag / 120));\n}\n\n// How far the layer above has come in, from 0 (gone) to 1 (fully open). Also\n// capped by its opacity, which is what moves under reduced motion.\nfunction usePush(above: Values, height: number) {\n  return useTransform(() =>\n    Math.min(\n      Math.max(1 - above.y.get() / height, 0),\n      Math.min(above.opacity.get(), 1),\n    ),\n  );\n}\n\nexport function StackedDrawer({\n  sheets,\n  trigger,\n  children,\n  className,\n}: {\n  sheets: Sheet[];\n  trigger: string;\n  children?: React.ReactNode;\n  className?: string;\n}) {\n  const reduce = !!useReducedMotion();\n  const [depth, setDepth] = useState(0);\n  const depthRef = useRef(0);\n  const frameRef = useRef<HTMLDivElement>(null);\n  const sheetRefs = useRef<(HTMLDivElement | null)[]>([]);\n  // triggers[i] opened sheet i, and gets focus back when it closes.\n  const triggers = useRef<(HTMLButtonElement | null)[]>([]);\n  const [values] = useState<Values[]>(() =>\n    sheets.map((_, i) => ({\n      y: motionValue(closedAt(i)),\n      opacity: motionValue(1),\n    })),\n  );\n  // Stands in above the top sheet, which nothing ever covers.\n  const [nothing] = useState<Values>(() => ({\n    y: motionValue(FRAME_H),\n    opacity: motionValue(0),\n  }));\n\n  const setStack = (next: number) => {\n    depthRef.current = next;\n    setDepth(next);\n  };\n\n  const open = (i: number) => {\n    setStack(i + 1);\n    const { y, opacity } = values[i];\n    if (reduce) {\n      y.jump(0);\n      opacity.jump(0);\n      animate(opacity, 1, FADE);\n    } else {\n      opacity.jump(1);\n      animate(y, 0, OPEN);\n    }\n  };\n\n  // Closing hands control back at once: the layer behind is live again while\n  // the sheet is still on its way out.\n  const close = (i: number, velocity?: number) => {\n    setStack(i);\n    const { y, opacity } = values[i];\n    if (velocity !== undefined) {\n      animate(y, closedAt(i), { ...RELEASE, velocity });\n    } else if (reduce) {\n      animate(opacity, 0, {\n        ...FADE,\n        // Parked offscreen once invisible, unless it was reopened meanwhile.\n        onComplete: () => {\n          if (depthRef.current <= i) y.jump(closedAt(i));\n        },\n      });\n    } else {\n      animate(y, closedAt(i), CLOSE);\n    }\n  };\n\n  const settle = (i: number, velocity: number) =>\n    animate(values[i].y, 0, { ...RELEASE, velocity });\n\n  // Focus follows the stack: into a sheet as it opens, back to whatever\n  // opened it as it closes. Only reclaimed if focus was in the demo, or was\n  // dropped to the body when the sheet went inert.\n  const shown = useRef(0);\n  useEffect(() => {\n    const before = shown.current;\n    shown.current = depth;\n    if (depth > before) {\n      sheetRefs.current[depth - 1]?.focus({ preventScroll: true });\n    } else if (depth < before) {\n      const active = document.activeElement;\n      if (\n        !active ||\n        active === document.body ||\n        frameRef.current?.contains(active)\n      ) {\n        triggers.current[depth]?.focus({ preventScroll: true });\n      }\n    }\n  }, [depth]);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (depthRef.current === 0) return;\n    if (e.key === \"Escape\") {\n      e.preventDefault();\n      close(depthRef.current - 1);\n      return;\n    }\n    if (e.key !== \"Tab\") return;\n    // Keeps Tab inside the open sheet, as a modal should.\n    const sheet = sheetRefs.current[depthRef.current - 1];\n    const focusable = sheet?.querySelectorAll<HTMLElement>(\"button\");\n    if (!sheet || !focusable?.length) return;\n    const first = focusable[0];\n    const last = focusable[focusable.length - 1];\n    if (\n      e.shiftKey &&\n      (document.activeElement === first || document.activeElement === sheet)\n    ) {\n      e.preventDefault();\n      last.focus();\n    } else if (!e.shiftKey && document.activeElement === last) {\n      e.preventDefault();\n      first.focus();\n    }\n  };\n\n  const one = useMotionValue(1);\n  const zero = useMotionValue(0);\n  const basePush = usePush(values[0] ?? nothing, heightOf(0));\n  const baseScale = useTransform(basePush, [0, 1], [1, PUSH_SCALE]);\n  const baseY = useTransform(basePush, [0, 1], [0, BASE_DROP]);\n  const baseDim = useTransform(basePush, [0, 1], [0, DIM]);\n\n  return (\n    <div\n      ref={frameRef}\n      onKeyDown={onKeyDown}\n      style={{ height: FRAME_H }}\n      // The backdrop only shows once the page is pushed back: darker than\n      // the page in both themes, like the black behind an iOS sheet.\n      className={cn(\n        \"relative w-[320px] max-w-full overflow-hidden rounded-[40px] bg-border shadow-raised dark:bg-background\",\n        className,\n      )}\n    >\n      <motion.div\n        inert={depth > 0}\n        style={{\n          y: reduce ? zero : baseY,\n          scale: reduce ? one : baseScale,\n        }}\n        className=\"absolute inset-0 flex origin-top flex-col rounded-[40px] bg-muted p-7\"\n      >\n        {children}\n        <button\n          ref={(el) => {\n            triggers.current[0] = el;\n          }}\n          type=\"button\"\n          onClick={() => open(0)}\n          className=\"mt-auto h-11 touch-manipulation rounded-full bg-foreground text-[15px] font-medium text-background outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n        >\n          {trigger}\n        </button>\n        <Scrim opacity={baseDim} className=\"rounded-[40px]\" />\n      </motion.div>\n\n      {sheets.map((sheet, i) => (\n        <SheetLayer\n          key={i}\n          index={i}\n          sheet={sheet}\n          values={values[i]}\n          above={values[i + 1] ?? nothing}\n          isTop={i === depth - 1}\n          reduce={reduce}\n          one={one}\n          setRef={(el) => {\n            sheetRefs.current[i] = el;\n          }}\n          setNextRef={(el) => {\n            triggers.current[i + 1] = el;\n          }}\n          hasNext={i + 1 < sheets.length}\n          onNext={() => open(i + 1)}\n          onClose={(velocity) => close(i, velocity)}\n          onSettle={(velocity) => settle(i, velocity)}\n        />\n      ))}\n    </div>\n  );\n}\n\nfunction SheetLayer({\n  index,\n  sheet,\n  values,\n  above,\n  isTop,\n  reduce,\n  one,\n  setRef,\n  setNextRef,\n  hasNext,\n  onNext,\n  onClose,\n  onSettle,\n}: {\n  index: number;\n  sheet: Sheet;\n  values: Values;\n  above: Values;\n  isTop: boolean;\n  reduce: boolean;\n  one: MotionValue<number>;\n  setRef: (el: HTMLDivElement | null) => void;\n  setNextRef: (el: HTMLButtonElement | null) => void;\n  hasNext: boolean;\n  onNext: () => void;\n  onClose: (velocity?: number) => void;\n  onSettle: (velocity: number) => void;\n}) {\n  const titleId = useId();\n  const push = usePush(above, heightOf(index + 1));\n  const scale = useTransform(push, [0, 1], [1, PUSH_SCALE]);\n  const dim = useTransform(push, [0, 1], [0, DIM]);\n  const drag = useRef<{\n    pointer: number;\n    startY: number;\n    from: number;\n    active: boolean;\n  } | null>(null);\n  const dragged = useRef(false);\n\n  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    // One finger at a time; a second touch mid-drag is ignored.\n    if (!isTop || drag.current || (e.pointerType === \"mouse\" && e.button !== 0))\n      return;\n    dragged.current = false;\n    values.y.stop();\n    drag.current = {\n      pointer: e.pointerId,\n      startY: e.clientY,\n      from: values.y.get(),\n      active: false,\n    };\n  };\n\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || e.pointerId !== d.pointer) return;\n    const delta = e.clientY - d.startY;\n    if (!d.active) {\n      if (Math.abs(delta) < DRAG_START) return;\n      d.active = true;\n      dragged.current = true;\n      e.currentTarget.setPointerCapture(e.pointerId);\n    }\n    const raw = d.from + delta;\n    values.y.set(raw < 0 ? -rubberBand(-raw) : raw);\n  };\n\n  const onPointerEnd = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || e.pointerId !== d.pointer) return;\n    drag.current = null;\n    if (!d.active) return;\n    const velocity = values.y.getVelocity();\n    const offset = values.y.get();\n    if (\n      offset > heightOf(index) * DISMISS_DISTANCE ||\n      velocity > DISMISS_VELOCITY\n    ) {\n      onClose(velocity);\n    } else {\n      onSettle(velocity);\n    }\n  };\n\n  return (\n    <motion.div\n      ref={setRef}\n      role=\"dialog\"\n      aria-modal\n      aria-labelledby={titleId}\n      tabIndex={-1}\n      inert={!isTop}\n      style={{\n        top: topOf(index),\n        bottom: -RUBBER,\n        paddingBottom: RUBBER,\n        y: values.y,\n        opacity: values.opacity,\n        scale: reduce ? one : scale,\n      }}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerEnd}\n      onPointerCancel={onPointerEnd}\n      // A drag that began on a button shouldn't also press it.\n      onClickCapture={(e) => {\n        if (!dragged.current) return;\n        dragged.current = false;\n        e.preventDefault();\n        e.stopPropagation();\n      }}\n      className={cn(\n        \"absolute inset-x-0 flex origin-top touch-none flex-col rounded-t-[28px] bg-background shadow-raised outline-hidden select-none\",\n        isTop && \"cursor-grab active:cursor-grabbing\",\n      )}\n    >\n      <div\n        aria-hidden\n        className=\"mx-auto mt-2.5 h-1.5 w-11 shrink-0 rounded-full bg-border\"\n      />\n      <div className=\"flex flex-1 flex-col px-6 pt-5 pb-6\">\n        <h2 id={titleId} className=\"text-xl font-medium tracking-tight\">\n          {sheet.title}\n        </h2>\n        <p className=\"mt-1.5 text-[15px] text-pretty text-muted-foreground\">\n          {sheet.description}\n        </p>\n        <div className=\"mt-auto flex flex-col gap-2.5\">\n          {hasNext && sheet.next && (\n            <button\n              ref={setNextRef}\n              type=\"button\"\n              onClick={onNext}\n              className=\"h-11 touch-manipulation rounded-full bg-foreground text-[15px] font-medium text-background outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n            >\n              {sheet.next}\n            </button>\n          )}\n          <button\n            type=\"button\"\n            onClick={() => onClose()}\n            className=\"h-11 touch-manipulation rounded-full bg-muted text-[15px] font-medium text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n          >\n            Done\n          </button>\n        </div>\n      </div>\n      <Scrim opacity={dim} className=\"rounded-t-[28px]\" />\n    </motion.div>\n  );\n}\n\n// Scales and rounds with its layer. Pure black dims both themes the same way,\n// where a foreground tint would lighten the dark one.\nfunction Scrim({\n  opacity,\n  className,\n}: {\n  opacity: MotionValue<number>;\n  className?: string;\n}) {\n  return (\n    <motion.div\n      aria-hidden\n      style={{ opacity }}\n      className={cn(\n        \"pointer-events-none absolute inset-0 bg-[oklch(0_0_0)]\",\n        className,\n      )}\n    />\n  );\n}\n\nconst SHEETS: Sheet[] = [\n  {\n    title: \"Share draft\",\n    description:\n      \"Anyone with the link can view. Invite people to let them edit.\",\n    next: \"Invite people\",\n  },\n  {\n    title: \"Invite people\",\n    description: \"They'll get an email and can edit right away.\",\n  },\n];\n\nexport default function StackedDrawerDemo() {\n  return (\n    <StackedDrawer sheets={SHEETS} trigger=\"Share\">\n      <p className=\"text-[13px] text-muted-foreground\">Drafts</p>\n      <p className=\"mt-1.5 text-2xl font-medium tracking-tight\">Launch notes</p>\n      <p className=\"mt-4 text-[15px] text-pretty text-muted-foreground\">\n        Three fixes, one new component, and a faster index. Ship Thursday after\n        review.\n      </p>\n    </StackedDrawer>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/stacked-drawer"}