{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bottom-sheet",
  "type": "registry:ui",
  "title": "Bottom Sheet",
  "description": "A panel that rises from the bottom edge, rests at one of several heights (snap points), and can be dragged between them or down to dismiss, with a keyboard handle that does the same.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "radix-ui"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/bottom-sheet.tsx",
      "type": "registry:ui",
      "target": "components/ui/bottom-sheet.tsx",
      "content": "\"use client\";\n/**\n * @name bottom-sheet\n * @category ui\n * @description A panel that rises from the bottom edge, rests at one of several heights (snap points), and can be dragged between them or down to dismiss, with a keyboard handle that does the same.\n * @when Phones first: details, filters, a picker or a secondary task that should stay within reach of the thumb and may be peeked at before it is opened fully. With `modal={false}` it stays open while the page behind is used (a player, a route summary). For a panel from a side edge, or one with no snap points on a desktop, use sheet; for a short decision use dialog; beside the content on wide screens use dock. Always give it a BottomSheetTitle (add className=\"sr-only\" to hide it). Opened by state with no BottomSheetTrigger, focus does not return on close: refocus the opener in `onCloseAutoFocus` on BottomSheetContent.\n * @example\n * <BottomSheet snapPoints={[0.4, 0.9]}>\n *   <BottomSheetTrigger asChild><Button variant=\"outline\">Details</Button></BottomSheetTrigger>\n *   <BottomSheetContent>\n *     <BottomSheetHandle />\n *     <BottomSheetHeader>\n *       <BottomSheetTitle>Saturday</BottomSheetTitle>\n *       <BottomSheetDescription>Three things planned.</BottomSheetDescription>\n *     </BottomSheetHeader>\n *     <BottomSheetBody>…</BottomSheetBody>\n *     <BottomSheetFooter>\n *       <BottomSheetClose asChild><Button>Done</Button></BottomSheetClose>\n *     </BottomSheetFooter>\n *   </BottomSheetContent>\n * </BottomSheet>\n *\n * // Controlled, in pixels and rems, staying open while the page is used\n * <BottomSheet open={open} onOpenChange={setOpen} snapPoints={[\"6rem\", \"320px\", 1]} snap={snap} onSnapChange={setSnap} modal={false} dismissible={false}>\n *   …\n * </BottomSheet>\n */\nimport { Dialog as SheetPrimitive } from \"radix-ui\";\nimport { createContext, use, useEffect, useRef, type ComponentProps, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\n/**\n * A height the sheet rests at: a number is a fraction of the viewport height (0.5 is half), a string is any\n * CSS length (\"320px\", \"20rem\"). The sheet is never taller than the viewport, whatever is asked.\n */\nexport type BottomSheetSnap = number | string;\n\nconst snapCss = (snap: BottomSheetSnap): string => (typeof snap === \"number\" ? `${snap * 100}dvh` : snap);\n\n/** A snap point in pixels, measured by the browser so that any CSS length works. */\nfunction snapPx(snap: BottomSheetSnap): number {\n  if (typeof snap === \"number\") return snap * window.innerHeight;\n  const probe = document.createElement(\"div\");\n  probe.style.cssText = \"position:fixed;visibility:hidden;pointer-events:none;inset-block-start:0;inline-size:0\";\n  probe.style.height = snap;\n  document.body.append(probe);\n  const height = probe.getBoundingClientRect().height;\n  probe.remove();\n  return height;\n}\n\ntype SheetContextValue = {\n  snapPoints: BottomSheetSnap[];\n  /** The index of the snap point the sheet rests at. 0 when there are none. */\n  index: number;\n  setIndex: (index: number) => void;\n  modal: boolean;\n  dismissible: boolean;\n  close: () => void;\n};\n\nconst SheetContext = createContext<SheetContextValue | null>(null);\n\nfunction useSheet(part: string): SheetContextValue {\n  const context = use(SheetContext);\n  if (!context) throw new Error(`<${part}> must be used inside <BottomSheet>.`);\n  return context;\n}\n\n/** Moving the sheet by hand: the handle drives it with a pointer, the body with a finger. */\ntype DragEngine = {\n  begin: (y: number) => void;\n  move: (y: number) => void;\n  /** Lets go. Returns how far the sheet was moved, in pixels, so that a press without a drag can be told apart. */\n  end: () => number;\n};\n\nconst DragContext = createContext<DragEngine | null>(null);\n\nexport type BottomSheetProps = {\n  children?: ReactNode;\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /**\n   * The heights the sheet rests at, lowest first. Left out, the sheet is as tall as its content and has one\n   * position. The sheet opens at the first one.\n   */\n  snapPoints?: BottomSheetSnap[];\n  /** The controlled snap point: one of `snapPoints`. */\n  snap?: BottomSheetSnap;\n  /** The snap point it opens at when uncontrolled. Default: the first. */\n  defaultSnap?: BottomSheetSnap;\n  onSnapChange?: (snap: BottomSheetSnap) => void;\n  /** true (default): a veil covers the page and focus stays in the sheet. false: the page behind stays usable. */\n  modal?: boolean;\n  /** false: Escape, a press outside and a drag down do not close it; only a BottomSheetClose or the state does. */\n  dismissible?: boolean;\n};\n\nexport function BottomSheet({ children, open, defaultOpen = false, onOpenChange, snapPoints, snap, defaultSnap, onSnapChange, modal = true, dismissible = true }: BottomSheetProps) {\n  const points = snapPoints ?? [];\n  const [isOpen, setOpen] = useControllableState({ value: open, defaultValue: defaultOpen, onChange: onOpenChange });\n  const [active, setActive] = useControllableState<BottomSheetSnap | null>({\n    value: snap,\n    defaultValue: defaultSnap ?? points[0] ?? null,\n    onChange: (next) => {\n      if (next !== null) onSnapChange?.(next);\n    },\n  });\n  const index = Math.max(\n    0,\n    points.findIndex((point) => point === active),\n  );\n\n  return (\n    <SheetContext\n      value={{\n        snapPoints: points,\n        index,\n        setIndex: (next) => {\n          const point = points[Math.min(points.length - 1, Math.max(0, next))];\n          if (point !== undefined) setActive(point);\n        },\n        modal,\n        dismissible,\n        close: () => setOpen(false),\n      }}\n    >\n      <SheetPrimitive.Root open={isOpen} onOpenChange={setOpen} modal={modal}>\n        {children}\n      </SheetPrimitive.Root>\n    </SheetContext>\n  );\n}\n\nexport function BottomSheetTrigger(props: ComponentProps<typeof SheetPrimitive.Trigger>) {\n  return <SheetPrimitive.Trigger data-slot=\"bottom-sheet-trigger\" {...props} />;\n}\n\nexport function BottomSheetClose(props: ComponentProps<typeof SheetPrimitive.Close>) {\n  return <SheetPrimitive.Close data-slot=\"bottom-sheet-close\" {...props} />;\n}\n\nexport function BottomSheetOverlay({ className, ...props }: ComponentProps<typeof SheetPrimitive.Overlay>) {\n  return (\n    <SheetPrimitive.Overlay\n      data-slot=\"bottom-sheet-overlay\"\n      className={cn(\n        \"fixed inset-0 z-50 bg-overlay ease-out animation-duration-(--duration-base) fade-in-0 fade-out-0 data-[state=closed]:animate-out data-[state=open]:animate-in motion-reduce:animate-none!\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\n/** How far ahead a release is projected from its speed, in milliseconds: a flick carries the sheet on. */\nconst PROJECTION = 140;\n/** Speed, in pixels a millisecond, above which a downward flick at the lowest position dismisses. */\nconst FLICK = 0.6;\n\nexport type BottomSheetContentProps = Omit<ComponentProps<typeof SheetPrimitive.Content>, \"ref\">;\n\n/**\n * The panel, with its portal and (when modal) its veil. Its height is the tallest snap point, and it is\n * pushed down so that only the current one shows: a move between snap points is one transform, and nothing\n * is laid out again. Under reduced motion it changes position without travelling.\n */\nexport function BottomSheetContent({ className, style, children, onInteractOutside, onEscapeKeyDown, ...props }: BottomSheetContentProps) {\n  const context = useSheet(\"BottomSheetContent\");\n  const { snapPoints, index, setIndex, dismissible, close, modal } = context;\n  const element = useRef<HTMLDivElement>(null);\n  const drag = useRef<{ startY: number; delta: number; samples: { y: number; time: number }[] } | null>(null);\n  const current = snapPoints[index];\n\n  /** The height of the sheet that shows at a snap point, in pixels: never more than the sheet itself. */\n  const visibleAt = (point: BottomSheetSnap | undefined, full: number): number => (point === undefined ? full : Math.min(snapPx(point), full));\n\n  const engine: DragEngine = {\n    begin(y) {\n      const node = element.current;\n      if (!node) return;\n      drag.current = { startY: y, delta: 0, samples: [{ y, time: performance.now() }] };\n      node.dataset[\"dragging\"] = \"\";\n    },\n    move(y) {\n      const node = element.current;\n      const state = drag.current;\n      if (!node || !state) return;\n      const full = node.offsetHeight;\n      // Up is negative. The sheet cannot be pulled higher than its own height.\n      state.delta = Math.max(y - state.startY, visibleAt(current, full) - full);\n      state.samples = [...state.samples.slice(-5), { y, time: performance.now() }];\n      node.style.setProperty(\"--rui-sheet-drag\", `${state.delta}px`);\n    },\n    end() {\n      const node = element.current;\n      const state = drag.current;\n      drag.current = null;\n      if (!node || !state) return 0;\n      delete node.dataset[\"dragging\"];\n      const full = node.offsetHeight;\n      const first = state.samples[0];\n      const last = state.samples.at(-1);\n      const elapsed = first && last ? last.time - first.time : 0;\n      // Pixels a millisecond, positive downwards.\n      const speed = first && last && elapsed > 0 && performance.now() - last.time < 80 ? (last.y - first.y) / elapsed : 0;\n      const showing = visibleAt(current, full) - state.delta;\n      const projected = showing - speed * PROJECTION;\n      const heights = snapPoints.length > 0 ? snapPoints.map((point) => visibleAt(point, full)) : [full];\n      const lowest = Math.min(...heights);\n      if (dismissible && Math.abs(state.delta) > 4 && (projected < lowest / 2 || (speed > FLICK && showing < lowest))) {\n        // The offset is kept, so that the sheet leaves from where the finger let go.\n        close();\n        return state.delta;\n      }\n      node.style.removeProperty(\"--rui-sheet-drag\");\n      let nearest = 0;\n      heights.forEach((height, at) => {\n        if (Math.abs(height - projected) < Math.abs((heights[nearest] ?? 0) - projected)) nearest = at;\n      });\n      if (snapPoints.length > 0) setIndex(nearest);\n      return state.delta;\n    },\n  };\n\n  const tallest = snapPoints.length > 0 ? `min(100dvh, max(${snapPoints.map(snapCss).join(\", \")}))` : undefined;\n\n  return (\n    <SheetPrimitive.Portal>\n      {modal ? <BottomSheetOverlay /> : null}\n      <SheetPrimitive.Content\n        ref={element}\n        data-slot=\"bottom-sheet-content\"\n        data-snap-index={index}\n        data-top={index >= snapPoints.length - 1 ? \"\" : undefined}\n        className={cn(\n          \"fixed inset-x-0 bottom-0 z-50 mx-auto flex w-full max-w-2xl flex-col rounded-t-surface border border-b-0 border-border bg-card pb-[env(safe-area-inset-bottom)] text-card-foreground transition-[translate] duration-slow ease-out animation-duration-(--duration-slow) slide-in-from-bottom slide-out-to-bottom data-[dragging]:transition-none data-[state=closed]:animate-out data-[state=open]:animate-in motion-reduce:animate-none! motion-reduce:transition-none\",\n          snapPoints.length === 0 && \"h-fit max-h-[calc(100dvh-3rem)]\",\n          className,\n        )}\n        style={\n          {\n            \"--rui-sheet-snap\": current === undefined ? \"100%\" : snapCss(current),\n            height: tallest,\n            translate: \"0 calc(100% - min(var(--rui-sheet-snap), 100%) + var(--rui-sheet-drag, 0px))\",\n            ...style,\n          } as CSSProperties\n        }\n        onInteractOutside={(event) => {\n          onInteractOutside?.(event);\n          // A sheet the page is used behind does not close when the page is used.\n          if (!dismissible || !modal) event.preventDefault();\n        }}\n        onEscapeKeyDown={(event) => {\n          onEscapeKeyDown?.(event);\n          if (!dismissible) event.preventDefault();\n        }}\n        {...props}\n      >\n        <DragContext value={engine}>{children}</DragContext>\n      </SheetPrimitive.Content>\n    </SheetPrimitive.Portal>\n  );\n}\n\nexport type BottomSheetHandleProps = Omit<ComponentProps<\"div\">, \"children\"> & {\n  /** What a screen reader says for a position. Default: \"Position 2 of 3\". Translate it with the interface. */\n  snapLabel?: (index: number, count: number) => string;\n};\n\n/**\n * The grab bar. With a pointer or a finger: drag it to move the sheet (a flick carries it on; a flick down\n * from the lowest position dismisses), or press it to go to the next position. With a keyboard it is a\n * slider: Up and Down move between the positions, Home and End go to the lowest and the highest, Enter and\n * Space go to the next. It says its position, so nothing here needs a drag. Its name (\"Sheet height\") is\n * an `aria-label`: translate it. With a single position there is nothing to set, and it is only a grab bar.\n */\nexport function BottomSheetHandle({\n  className,\n  snapLabel = (index, count) => `Position ${index + 1} of ${count}`,\n  \"aria-label\": ariaLabel = \"Sheet height\",\n  onKeyDown,\n  onPointerDown,\n  ...props\n}: BottomSheetHandleProps) {\n  const { snapPoints, index, setIndex } = useSheet(\"BottomSheetHandle\");\n  const engine = use(DragContext);\n  const count = snapPoints.length;\n  const adjustable = count > 1;\n  const next = (): void => setIndex((index + 1) % count);\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || !adjustable) return;\n    const moves: Record<string, number | undefined> = {\n      ArrowUp: index + 1,\n      ArrowDown: index - 1,\n      Home: 0,\n      End: count - 1,\n      Enter: (index + 1) % count,\n      \" \": (index + 1) % count,\n    };\n    const target = moves[event.key];\n    if (target === undefined) return;\n    event.preventDefault();\n    setIndex(target);\n  };\n\n  const handlePointerDown = (event: PointerEvent<HTMLDivElement>): void => {\n    onPointerDown?.(event);\n    if (event.defaultPrevented || event.button !== 0 || !engine) return;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    engine.begin(event.clientY);\n  };\n  const release = (event: PointerEvent<HTMLDivElement>): void => {\n    if (!engine || !event.currentTarget.hasPointerCapture(event.pointerId)) return;\n    event.currentTarget.releasePointerCapture(event.pointerId);\n    const moved = engine.end();\n    if (event.type === \"pointerup\" && Math.abs(moved) <= 4 && adjustable) next();\n  };\n\n  return (\n    <div\n      data-slot=\"bottom-sheet-handle\"\n      {...(adjustable\n        ? {\n            role: \"slider\",\n            tabIndex: 0,\n            \"aria-label\": ariaLabel,\n            \"aria-orientation\": \"vertical\" as const,\n            \"aria-valuemin\": 0,\n            \"aria-valuemax\": count - 1,\n            \"aria-valuenow\": index,\n            \"aria-valuetext\": snapLabel(index, count),\n          }\n        : { \"aria-hidden\": true })}\n      onKeyDown={handleKeyDown}\n      onPointerDown={handlePointerDown}\n      onPointerMove={(event) => {\n        if (event.currentTarget.hasPointerCapture(event.pointerId)) engine?.move(event.clientY);\n      }}\n      onPointerUp={release}\n      onPointerCancel={release}\n      className={cn(\n        \"flex h-7 w-full shrink-0 cursor-grab touch-none items-center justify-center rounded-t-surface select-none active:cursor-grabbing pointer-coarse:h-10\",\n        className,\n      )}\n      {...props}\n    >\n      <span aria-hidden=\"true\" className=\"h-1 w-10 rounded-full bg-border-strong\" />\n    </div>\n  );\n}\n\nexport function BottomSheetHeader({ className, ...props }: ComponentProps<\"div\">) {\n  return <div data-slot=\"bottom-sheet-header\" className={cn(\"flex shrink-0 flex-col gap-1.5 px-5 pb-4 text-start\", className)} {...props} />;\n}\n\nexport function BottomSheetTitle({ className, ...props }: ComponentProps<typeof SheetPrimitive.Title>) {\n  return <SheetPrimitive.Title data-slot=\"bottom-sheet-title\" className={cn(\"text-base font-medium leading-tight\", className)} {...props} />;\n}\n\nexport function BottomSheetDescription({ className, ...props }: ComponentProps<typeof SheetPrimitive.Description>) {\n  return <SheetPrimitive.Description data-slot=\"bottom-sheet-description\" className={cn(\"text-sm text-muted-foreground\", className)} {...props} />;\n}\n\nexport type BottomSheetBodyProps = Omit<ComponentProps<\"div\">, \"ref\">;\n\n/**\n * The part that scrolls. It scrolls only at the highest position; lower down, a finger on it moves the\n * sheet instead, and at the highest position a pull down from the top of the scroll moves the sheet too.\n * (With a mouse the body scrolls and selects text as usual: the handle moves the sheet.)\n */\nexport function BottomSheetBody({ className, ...props }: BottomSheetBodyProps) {\n  const { snapPoints, index } = useSheet(\"BottomSheetBody\");\n  const engine = use(DragContext);\n  const top = index >= snapPoints.length - 1;\n  const node = useRef<HTMLDivElement>(null);\n  const latest = useRef({ engine, top });\n  useEffect(() => {\n    latest.current = { engine, top };\n  });\n\n  useEffect(() => {\n    const body = node.current;\n    if (!body) return;\n    let mode: \"sheet\" | \"scroll\" | null = null;\n    let startY = 0;\n    const start = (event: TouchEvent): void => {\n      mode = null;\n      startY = event.touches[0]?.clientY ?? 0;\n    };\n    const move = (event: TouchEvent): void => {\n      const touch = event.touches[0];\n      const { engine: current, top: atTop } = latest.current;\n      if (!touch || !current || event.touches.length > 1) return;\n      const distance = touch.clientY - startY;\n      if (mode === null) {\n        if (!atTop || (body.scrollTop <= 0 && distance > 4)) mode = \"sheet\";\n        else if (Math.abs(distance) > 4) mode = \"scroll\";\n        if (mode === \"sheet\") current.begin(touch.clientY);\n      }\n      if (mode === \"sheet\") {\n        if (event.cancelable) event.preventDefault();\n        current.move(touch.clientY);\n      }\n    };\n    const end = (): void => {\n      if (mode === \"sheet\") latest.current.engine?.end();\n      mode = null;\n    };\n    body.addEventListener(\"touchstart\", start, { passive: true });\n    body.addEventListener(\"touchmove\", move, { passive: false });\n    body.addEventListener(\"touchend\", end);\n    body.addEventListener(\"touchcancel\", end);\n    return () => {\n      body.removeEventListener(\"touchstart\", start);\n      body.removeEventListener(\"touchmove\", move);\n      body.removeEventListener(\"touchend\", end);\n      body.removeEventListener(\"touchcancel\", end);\n    };\n  }, []);\n\n  return (\n    <div\n      ref={node}\n      data-slot=\"bottom-sheet-body\"\n      className={cn(\"min-h-0 flex-1 overscroll-contain px-5 pb-5\", top ? \"overflow-y-auto\" : \"touch-none overflow-hidden\", className)}\n      {...props}\n    />\n  );\n}\n\n/** Actions under the body. It is at the bottom of the sheet, so it shows at the highest position. */\nexport function BottomSheetFooter({ className, ...props }: ComponentProps<\"div\">) {\n  return <div data-slot=\"bottom-sheet-footer\" className={cn(\"flex shrink-0 flex-col gap-2 border-t border-border p-5\", className)} {...props} />;\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Phones first: details, filters, a picker or a secondary task that should stay within reach of the thumb and may be peeked at before it is opened fully. With `modal={false}` it stays open while the page behind is used (a player, a route summary). For a panel from a side edge, or one with no snap points on a desktop, use sheet; for a short decision use dialog; beside the content on wide screens use dock. Always give it a BottomSheetTitle (add className=\"sr-only\" to hide it). Opened by state with no BottomSheetTrigger, focus does not return on close: refocus the opener in `onCloseAutoFocus` on BottomSheetContent.",
    "example": "<BottomSheet snapPoints={[0.4, 0.9]}>\n  <BottomSheetTrigger asChild><Button variant=\"outline\">Details</Button></BottomSheetTrigger>\n  <BottomSheetContent>\n    <BottomSheetHandle />\n    <BottomSheetHeader>\n      <BottomSheetTitle>Saturday</BottomSheetTitle>\n      <BottomSheetDescription>Three things planned.</BottomSheetDescription>\n    </BottomSheetHeader>\n    <BottomSheetBody>…</BottomSheetBody>\n    <BottomSheetFooter>\n      <BottomSheetClose asChild><Button>Done</Button></BottomSheetClose>\n    </BottomSheetFooter>\n  </BottomSheetContent>\n</BottomSheet>\n\n// Controlled, in pixels and rems, staying open while the page is used\n<BottomSheet open={open} onOpenChange={setOpen} snapPoints={[\"6rem\", \"320px\", 1]} snap={snap} onSnapChange={setSnap} modal={false} dismissible={false}>\n  …\n</BottomSheet>",
    "client": true
  }
}
