Drawer for Astro
Astro panel that slides into view from the screen edge, with swipe gestures, snapping, and nested interfaces.
Installation
bunx --bun shadcn@latest add @gnostic/drawernpx shadcn@latest add @gnostic/drawerpnpm dlx shadcn@latest add @gnostic/drawerComponent classes: Default Gnostic.
Complete the Installation guide first. Then copy the component files below.
Install component packages
bun add @data-slot/drawerCopy the files
src/components/ui/drawer/drawer-backdrop.astro
---
import type { HTMLAttributes } from "astro/types"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
data-slot="drawer-backdrop"
class="fixed inset-0 z-50 w-full bg-black/12 opacity-[calc(1-var(--drawer-swipe-progress,0))] backdrop-blur-sm transition-opacity duration-450 ease-[cubic-bezier(0.32,0.72,0,1)] data-starting-style:opacity-0 data-ending-style:opacity-0 data-swiping:transition-none has-[+[data-slot=drawer-viewport]>[data-nested]]:hidden motion-reduce:transition-none [[hidden]]:hidden"
hidden
/>
src/components/ui/drawer/drawer-close.astro
---
import type { HTMLAttributes, HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
/**
* Element that closes the current drawer.
* Pass `class={cn(buttonVariants())}` when the control should look like a button.
*/
type Props<Tag extends HTMLTag = "button"> = Polymorphic<{ as: Tag }> &
HTMLAttributes<Tag>
const {
as: Tag = "href" in Astro.props ? "a" : "button",
class: className,
"aria-label": ariaLabel = "Close drawer",
...props
} = Astro.props
// Props validates the selected tag at the call site. The render tag is dynamic.
const elementProps: Record<string, unknown> = {
...(Tag === "button" ? { type: "button" } : {}),
...props,
}
---
<Tag
data-slot="drawer-close"
class={cn(className)}
aria-label={ariaLabel}
{...elementProps}
>
<slot />
</Tag>
src/components/ui/drawer/drawer-description.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"p">
const { class: className, ...props } = Astro.props
---
<p
data-slot="drawer-description"
class={cn("text-muted-foreground text-sm", className)}
{...props}
>
<slot />
</p>
src/components/ui/drawer/drawer-footer.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div"> & {
variant?: "default" | "bare"
allowSelection?: boolean
}
const {
class: className,
variant = "default",
allowSelection = true,
...props
} = Astro.props
---
<div
data-slot="drawer-footer"
data-variant={variant}
class={cn(
"flex pt-4 pb-[calc(env(safe-area-inset-bottom,0px)+1rem)] flex-col-reverse gap-2 px-6 @min-2xl/drawer:flex-row @min-2xl/drawer:justify-end",
!allowSelection && "cursor-default",
variant === "default" && "border-t bg-muted/72 pt-4 pb-[calc(env(safe-area-inset-bottom,0px)+(--spacing(4)))]",
variant === "bare" && "in-[[data-slot=drawer-popup]:has([data-slot=drawer-panel])]:pt-3 pt-4 pb-[calc(env(safe-area-inset-bottom,0px)+(--spacing(6)))]",
className,
)}
{...props}
>
<slot />
</div>
src/components/ui/drawer/drawer-header.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div"> & {
allowSelection?: boolean
}
const { class: className, allowSelection = true, ...props } = Astro.props
---
<div
data-slot="drawer-header"
class={cn(
"flex flex-col gap-2 p-6 in-[[data-slot=drawer-popup]:has([data-slot=drawer-panel])]:pb-3 max-sm:pb-4",
!allowSelection && "cursor-default",
className,
)}
{...props}
>
<slot />
</div>
src/components/ui/drawer/drawer-menu-group-label.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
data-slot="drawer-menu-group-label"
class={cn("px-2 py-2 text-xs font-medium text-muted-foreground", className)}
{...props}
>
<slot />
</div>
src/components/ui/drawer/drawer-menu-group.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import DrawerMenuGroupLabel from "./drawer-menu-group-label.astro"
import type { DrawerMenuGroupProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & DrawerMenuGroupProps
const { label, class: className, ...props } = Astro.props
---
<div
data-slot="drawer-menu-group"
role="group"
aria-label={label}
class={cn("flex flex-col gap-1", className)}
{...props}
>
{label && <DrawerMenuGroupLabel>{label}</DrawerMenuGroupLabel>}
<slot />
</div>
src/components/ui/drawer/drawer-menu-item.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { DrawerMenuItemProps } from "./types.ts"
type Props = HTMLAttributes<"button"> &
HTMLAttributes<"a"> &
DrawerMenuItemProps & {
as?: "button" | "a"
}
const {
as: Tag = "href" in Astro.props ? "a" : "button",
class: className,
closeOnSelect = false,
variant = "default",
...props
} = Astro.props
---
<Tag
{...(Tag === "button" ? { type: "button" as const } : {})}
data-slot={closeOnSelect === true ? "drawer-close" : "drawer-menu-item"}
data-drawer-close-all={closeOnSelect === "all" || undefined}
data-variant={variant}
class={cn(
"hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:ring-ring/50 aria-[current=page]:bg-accent aria-[current=page]:text-accent-foreground flex min-h-11 w-full items-center gap-2 rounded-sm px-2 py-2 text-left text-base outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 @min-2xl/drawer:min-h-9 @min-2xl/drawer:text-sm [&>svg]:pointer-events-none [&>svg]:size-4 [&>svg]:shrink-0",
variant === "destructive" && "text-destructive",
className,
)}
{...props}
>
<slot />
</Tag>
src/components/ui/drawer/drawer-menu-trigger.astro
---
import { ChevronRightIcon } from "@lucide/astro"
import type { HTMLAttributes } from "astro/types"
import DrawerMenuItem from "./drawer-menu-item.astro"
type Props = HTMLAttributes<"button"> &
HTMLAttributes<"a"> & {
as?: "button" | "a"
}
const { as = "button", ...props } = Astro.props
---
<!-- The runtime uses the trigger slot to open this item's drawer. -->
<DrawerMenuItem as={as} data-slot="drawer-trigger" {...props}>
<slot />
<ChevronRightIcon class="ml-auto" aria-hidden="true" />
</DrawerMenuItem>
src/components/ui/drawer/drawer-menu.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"nav">
const { class: className, ...props } = Astro.props
---
<nav
data-slot="drawer-menu"
class={cn("-mx-2 flex flex-col gap-1", className)}
{...props}
>
<slot />
</nav>
src/components/ui/drawer/drawer-panel.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import ScrollArea from "../scroll-area/scroll-area.astro"
type Props = HTMLAttributes<"div"> & {
allowSelection?: boolean
scrollable?: boolean
scrollFade?: boolean
}
const {
class: className,
allowSelection = true,
scrollable = true,
scrollFade = true,
...props
} = Astro.props
---
<div
data-slot="drawer-panel"
class={cn(
// Position the scrollbar in the panel padding, clear of the content.
"relative min-h-0 p-6 in-[[data-slot=drawer-popup]:has([data-slot=drawer-header])]:pt-1 in-[[data-slot=drawer-popup]:has([data-slot=drawer-footer]:not(.border-t))]:pb-1",
scrollable && "flex flex-col",
!allowSelection && "cursor-default",
className,
)}
{...props}
>
{scrollable ? (
<ScrollArea class="static flex-1" scrollFade={scrollFade} overscrollContain>
<slot />
</ScrollArea>
) : (
<slot />
)}
</div>
src/components/ui/drawer/drawer-popup.astro
---
import type { HTMLAttributes } from "astro/types"
import X from "@lucide/astro/icons/x"
import { cn } from "cn"
import { buttonVariants } from "../button/button-variants.ts"
import DrawerClose from "./drawer-close.astro"
import type { DrawerPopupProps } from "./types.ts"
import DrawerBackdrop from "./drawer-backdrop.astro"
type Props = HTMLAttributes<"div"> & DrawerPopupProps
const {
class: className,
variant = "default",
showCloseButton = false,
showBar = false,
showBackdrop = true,
keepMounted,
container,
initialFocus,
finalFocus,
...props
} = Astro.props
// data-swipe-direction gets added by `@data-slot/drawer` to the drawer-popup slot
---
<div
data-slot="drawer-portal"
data-keep-mounted={keepMounted}
data-container={container}
>
{showBackdrop && <DrawerBackdrop />}
<div
data-slot="drawer-viewport"
data-variant={variant}
class="pointer-events-none fixed inset-0 z-50 flex w-full overflow-hidden p-(--drawer-viewport-inset) [--drawer-viewport-inset:0px] data-[swipe-direction=down]:items-end data-[swipe-direction=down]:pt-12 data-[swipe-direction=up]:items-start data-[swipe-direction=up]:pb-12 data-[swipe-direction=left]:justify-start data-[swipe-direction=right]:justify-end sm:data-[variant=inset]:[--drawer-viewport-inset:--spacing(4)] [[hidden]]:hidden"
hidden
>
<div
data-slot="drawer-popup"
data-variant={variant}
data-show-bar={showBar || undefined}
data-initial-focus={initialFocus}
data-final-focus={finalFocus}
class={cn(
"bg-popover text-popover-foreground border-border not-dark:bg-clip-padding text-sm shadow-lg/5 @container/drawer pointer-events-auto flex min-h-0 min-w-0 flex-col outline-none group/drawer-popup relative m-0 max-h-full transition-transform duration-450 ease-[cubic-bezier(0.32,0.72,0,1)] will-change-transform data-ending-style:duration-[calc(var(--drawer-swipe-strength,1)*400ms)] data-swiping:transition-none data-swiping:select-none data-nested-swiping:transition-none data-nested-drawer-open:overflow-hidden data-nested-drawer-open:pointer-events-none data-nested-drawer-open:brightness-95 motion-reduce:transition-none [[hidden]]:hidden",
// Scale only across the swipe axis. data-slot measures transformed
// bounds, so the swipe dimension must keep its natural size.
"[--drawer-stack-progress:clamp(0,var(--drawer-swipe-progress,0),1)] [--drawer-stack-scale:1] [--drawer-stack-step:0.05] [--drawer-scale-x:1] [--drawer-scale-y:1] [--drawer-stack-offset:calc(max(0,var(--nested-drawers,0)-var(--drawer-stack-progress))*(--spacing(6)))] data-nested-drawer-open:[--drawer-stack-scale:clamp(0,calc(1-(var(--nested-drawers,0)-var(--drawer-stack-progress))*var(--drawer-stack-step)),1)]",
"[--drawer-x:var(--drawer-swipe-amount-x,0px)] [--drawer-y:var(--drawer-swipe-amount-y,0px)] transform-[translate(var(--drawer-x),var(--drawer-y))_scale(var(--drawer-scale-x),var(--drawer-scale-y))] data-starting-style:transform-(--drawer-exit) data-ending-style:transform-(--drawer-exit)",
"data-[swipe-direction=down]:w-full data-[swipe-direction=down]:[--drawer-scale-x:var(--drawer-stack-scale)] data-[swipe-direction=down]:origin-bottom data-[swipe-direction=down]:border-t data-[swipe-direction=down]:[--drawer-exit:translateY(calc(100%+var(--drawer-viewport-inset)))] data-[swipe-direction=down]:[--drawer-y:calc(var(--drawer-snap-point-offset,0px)+var(--drawer-swipe-amount-y,0px))] data-[swipe-direction=down]:data-nested-drawer-open:[--drawer-y:calc(100%-var(--drawer-front-height,0px)-var(--drawer-stack-offset))]",
"data-[swipe-direction=up]:w-full data-[swipe-direction=up]:[--drawer-scale-x:var(--drawer-stack-scale)] data-[swipe-direction=up]:origin-top data-[swipe-direction=up]:border-b data-[swipe-direction=up]:[--drawer-exit:translateY(calc(-100%-var(--drawer-viewport-inset)))] data-[swipe-direction=up]:[--drawer-y:calc(var(--drawer-snap-point-offset,0px)+var(--drawer-swipe-amount-y,0px))] data-[swipe-direction=up]:data-nested-drawer-open:[--drawer-y:calc(var(--drawer-front-height,0px)-100%+var(--drawer-stack-offset))]",
"data-[swipe-direction=left]:h-full data-[swipe-direction=left]:[--drawer-scale-y:var(--drawer-stack-scale)] data-[swipe-direction=left]:w-[calc(100%-3rem)] data-[swipe-direction=left]:max-w-md data-[swipe-direction=left]:origin-right data-[swipe-direction=left]:border-r data-[swipe-direction=left]:[--drawer-exit:translateX(calc(-100%-var(--drawer-viewport-inset)))] data-[swipe-direction=left]:[--drawer-x:calc(var(--drawer-snap-point-offset,0px)+var(--drawer-swipe-amount-x,0px))] data-[swipe-direction=left]:data-nested-drawer-open:[--drawer-x:var(--drawer-stack-offset)] data-[swipe-direction=left]:data-show-bar:pr-4",
"data-[swipe-direction=right]:h-full data-[swipe-direction=right]:[--drawer-scale-y:var(--drawer-stack-scale)] data-[swipe-direction=right]:w-[calc(100%-3rem)] data-[swipe-direction=right]:max-w-md data-[swipe-direction=right]:origin-left data-[swipe-direction=right]:border-l data-[swipe-direction=right]:[--drawer-exit:translateX(calc(100%+var(--drawer-viewport-inset)))] data-[swipe-direction=right]:[--drawer-x:calc(var(--drawer-snap-point-offset,0px)+var(--drawer-swipe-amount-x,0px))] data-[swipe-direction=right]:data-nested-drawer-open:[--drawer-x:calc(-1*var(--drawer-stack-offset))] data-[swipe-direction=right]:data-show-bar:pl-4",
// Keep a direct panel inside the visible part of a snapped popup.
"data-[swipe-direction=down]:*:data-[slot=drawer-panel]:max-h-[calc(100%-var(--drawer-snap-point-offset,0px))] data-[swipe-direction=up]:*:data-[slot=drawer-panel]:max-h-[calc(100%+var(--drawer-snap-point-offset,0px))] data-[swipe-direction=up]:*:data-[slot=drawer-panel]:-translate-y-(--drawer-snap-point-offset,0px)",
"data-[swipe-direction=right]:*:data-[slot=drawer-panel]:max-w-[calc(100%-var(--drawer-snap-point-offset,0px))] data-[swipe-direction=left]:*:data-[slot=drawer-panel]:max-w-[calc(100%+var(--drawer-snap-point-offset,0px))] data-[swipe-direction=left]:*:data-[slot=drawer-panel]:-translate-x-(--drawer-snap-point-offset,0px)",
// ScrollArea inherits max-height; reset it to the panel's visible size.
"[&>[data-slot=drawer-panel]>[data-slot=scroll-area]]:max-h-full",
// Keep the edge shadow outside the popup's padding box.
"before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] after:pointer-events-none after:absolute after:bg-popover dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// leave space for the bar
"has-data-[slot=drawer-bar]:data-[swipe-direction=down]:pt-2",
"has-data-[slot=drawer-bar]:data-[swipe-direction=up]:pb-2",
"has-data-[slot=drawer-bar]:data-[swipe-direction=left]:pr-2",
"has-data-[slot=drawer-bar]:data-[swipe-direction=right]:pl-2",
variant === "default" && "data-[swipe-direction=down]:before:rounded-t-[calc(var(--radius-2xl)-1px)] data-[swipe-direction=up]:before:rounded-b-[calc(var(--radius-2xl)-1px)] data-[swipe-direction=left]:before:rounded-e-[calc(var(--radius-2xl)-1px)] data-[swipe-direction=right]:before:rounded-s-[calc(var(--radius-2xl)-1px)]",
variant === "inset" && "before:hidden sm:rounded-2xl sm:border sm:after:bg-transparent sm:before:rounded-[calc(var(--radius-2xl)-1px)] sm:**:data-[slot=drawer-footer]:rounded-b-[calc(var(--radius-2xl)-1px)]",
variant === "straight"
? "rounded-none [--drawer-stack-step:0]"
: "data-[swipe-direction=down]:rounded-t-2xl data-[swipe-direction=up]:rounded-b-2xl data-[swipe-direction=left]:rounded-r-2xl data-[swipe-direction=right]:rounded-l-2xl data-[swipe-direction=up]:**:data-[slot=drawer-footer]:rounded-b-[calc(var(--radius-2xl)-1px)] data-[swipe-direction=left]:**:data-[slot=drawer-footer]:rounded-br-[calc(var(--radius-2xl)-1px)] data-[swipe-direction=right]:**:data-[slot=drawer-footer]:rounded-bl-[calc(var(--radius-2xl)-1px)]",
className,
)}
hidden
{...props}
>
{showBar && (
<div
data-slot="drawer-bar"
class="absolute flex top-0 inset-x-0 shrink-0 touch-none items-center justify-center p-3 group-data-[swipe-direction=up]/drawer-popup:order-1 group-data-[swipe-direction=left]/drawer-popup:absolute group-data-[swipe-direction=left]/drawer-popup:inset-y-0 group-data-[swipe-direction=left]/drawer-popup:right-0 group-data-[swipe-direction=left]/drawer-popup:p-2 group-data-[swipe-direction=right]/drawer-popup:absolute group-data-[swipe-direction=right]/drawer-popup:inset-y-0 group-data-[swipe-direction=right]/drawer-popup:left-0 group-data-[swipe-direction=right]/drawer-popup:p-2"
aria-hidden="true"
>
<span class="h-1 w-12 rounded-full bg-input group-data-[swipe-direction=left]/drawer-popup:h-12 group-data-[swipe-direction=left]/drawer-popup:w-1 group-data-[swipe-direction=right]/drawer-popup:h-12 group-data-[swipe-direction=right]/drawer-popup:w-1" />
</div>
)}
<slot />
{showCloseButton && (
<DrawerClose
data-drawer-dismiss
class={cn(
buttonVariants({
variant: "ghost",
size: "icon-sm",
}),
"absolute top-2 right-2",
)}
aria-label="Close"
>
<X />
</DrawerClose>
)}
</div>
</div>
</div>
src/components/ui/drawer/drawer-title.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"h2">
const { class: className, ...props } = Astro.props
---
<h2
data-slot="drawer-title"
class={cn("text-xl leading-none font-semibold", className)}
{...props}
>
<slot />
</h2>
src/components/ui/drawer/drawer-trigger.astro
---
import type { HTMLAttributes } from "astro/types"
import { Button } from "../button/index.ts"
import type { ButtonVariantProps } from "../button/button-variants.ts"
import type { DrawerTriggerProps } from "./types.ts"
type Props = HTMLAttributes<"button"> & ButtonVariantProps & DrawerTriggerProps
const { target, payload, ...props } = Astro.props
---
<Button
type="button"
data-slot="drawer-trigger"
data-drawer-target={target}
data-payload={payload}
{...props}
>
<slot />
</Button>
src/components/ui/drawer/drawer.astro
---
import type { HTMLAttributes } from "astro/types"
import type { DrawerProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & DrawerProps
const {
position = "bottom",
defaultOpen,
triggerId,
defaultTriggerId,
modal,
closeOnEscape,
disablePointerDismissal,
closeOnMedia,
snapPoint,
defaultSnapPoint,
...props
} = Astro.props
const direction = { bottom: "down", top: "up", left: "left", right: "right" }
---
<div
data-slot="drawer"
data-snap-point={snapPoint}
data-trigger-id={triggerId}
data-default-trigger-id={defaultTriggerId}
data-default-snap-point={defaultSnapPoint}
data-swipe-direction={direction[position]}
data-default-open={defaultOpen}
data-modal={modal}
data-close-on-escape={closeOnEscape}
data-disable-pointer-dismissal={disablePointerDismissal}
data-close-on-media={closeOnMedia}
{...props}
>
<slot />
</div>
<script>
import { createDrawer, type DrawerController } from "@data-slot/drawer"
const drawers = new Map<
HTMLElement,
{
popup: HTMLElement
parent?: HTMLElement
controller: DrawerController
destroy: () => void
}
>()
const suspendedParents = new Map<
HTMLElement,
{ children: Set<HTMLElement>; inert: boolean }
>()
function closeChildren(root: HTMLElement) {
for (const entry of Array.from(drawers.values()).reverse()) {
if (entry.parent !== root) continue
entry.controller.close()
if (entry.controller.isOpen) return false
}
return true
}
function setParentOpen(
parent: HTMLElement,
root: HTMLElement,
open: boolean,
) {
let state = suspendedParents.get(parent)
if (open) {
if (!state) {
state = { children: new Set(), inert: parent.inert }
suspendedParents.set(parent, state)
}
state.children.add(root)
parent.inert = true
} else if (state) {
state.children.delete(root)
if (state.children.size === 0) {
parent.inert = state.inert
suspendedParents.delete(parent)
}
}
}
function initDrawers() {
document
.querySelectorAll<HTMLElement>('[data-slot="drawer"]')
.forEach((root) => {
if (drawers.has(root)) return
const popup = root.querySelector<HTMLElement>(
'[data-slot="drawer-popup"]',
)!
const parent = root.parentElement?.closest<HTMLElement>(
'[data-slot="drawer-popup"]',
)
// Keep the parent relation when portals move outside their roots.
const parentRoot = Array.from(drawers.entries()).find(
([, entry]) => entry.popup === parent,
)?.[0]
// A non-modal child keeps the page active, but its covered parent must
// leave the tab order. Restore the parent before focus returns on close.
const parentState =
parent && root.dataset.modal === "false"
? (open: boolean) => setParentOpen(parent, root, open)
: undefined
const drawer = createDrawer(root, {
onOpenChange(open, details) {
if (!open && !closeChildren(root)) {
details.cancel()
return
}
parentState?.(open)
},
})
const closeOnSelect = (event: MouseEvent) => {
const control =
event.target instanceof Element
? event.target.closest<HTMLElement>("[data-drawer-close-all]")
: null
if (
event.defaultPrevented ||
!control ||
control.closest('[data-slot="drawer-popup"]') !== popup ||
control.matches(':disabled, [aria-disabled="true"]')
)
return
let outerRoot = root
let ancestor = drawers.get(outerRoot)?.parent
while (ancestor) {
outerRoot = ancestor
ancestor = drawers.get(outerRoot)?.parent
}
drawers.get(outerRoot)?.controller.close()
}
popup.addEventListener("click", closeOnSelect)
const media = root.dataset.closeOnMedia
? window.matchMedia(root.dataset.closeOnMedia)
: undefined
const closeOnMedia = () => {
if (media?.matches) drawer.close()
}
media?.addEventListener("change", closeOnMedia)
closeOnMedia()
drawers.set(root, {
popup,
parent: parentRoot,
controller: drawer,
destroy() {
media?.removeEventListener("change", closeOnMedia)
popup.removeEventListener("click", closeOnSelect)
parentState?.(false)
drawer.destroy()
},
})
})
}
initDrawers()
document.addEventListener("astro:page-load", initDrawers)
document.addEventListener("astro:before-swap", () => {
// Close children before parents so nested portals restore in order.
Array.from(drawers.values())
.reverse()
.forEach((entry) => entry.destroy())
drawers.clear()
})
</script>
src/components/ui/drawer/index.ts
export { default as Drawer } from './drawer.astro'
export { default as DrawerTrigger } from './drawer-trigger.astro'
export { default as DrawerClose } from './drawer-close.astro'
export { default as DrawerPopup } from './drawer-popup.astro'
export { default as DrawerHeader } from './drawer-header.astro'
export { default as DrawerTitle } from './drawer-title.astro'
export { default as DrawerDescription } from './drawer-description.astro'
export { default as DrawerPanel } from './drawer-panel.astro'
export { default as DrawerFooter } from './drawer-footer.astro'
export { default as DrawerMenu } from './drawer-menu.astro'
export { default as DrawerMenuGroup } from './drawer-menu-group.astro'
export { default as DrawerMenuGroupLabel } from './drawer-menu-group-label.astro'
export { default as DrawerMenuItem } from './drawer-menu-item.astro'
export { default as DrawerMenuTrigger } from './drawer-menu-trigger.astro'
export type {
DrawerProps,
DrawerPopupProps,
DrawerMenuGroupProps,
DrawerMenuItemProps,
} from './types.ts'
src/components/ui/drawer/types.ts
import type { DrawerOptions, DrawerSnapPoint } from '@data-slot/drawer'
/** Initial state and screen edge for a drawer. */
export type DrawerProps = Pick<
DrawerOptions,
| 'defaultOpen'
| 'triggerId'
| 'defaultTriggerId'
| 'modal'
| 'closeOnEscape'
| 'disablePointerDismissal'
> & {
/**
* Initial single open position. Use a viewport fraction, pixel number,
* or CSS length in `px` or `rem`. The popup size limits this value.
* Omit both snap props to use the popup's full size.
*/
snapPoint?: DrawerSnapPoint | null
/**
* Initial open position when `snapPoint` is not set.
*/
defaultSnapPoint?: DrawerSnapPoint | null
/**
* The position of the drawer.
* @default "bottom"
*/
position?: 'bottom' | 'top' | 'left' | 'right'
/**
* A media query string that will be used to close the drawer when the media query matches.
* @example "(max-width: 768px)"
*/
closeOnMedia?: string
}
/**
* Configuration for the drawer portal and popup.
*/
export type DrawerPopupProps = Pick<DrawerOptions, 'keepMounted'> & {
/**
* CSS selector for the portal destination.
* @default "body"
*/
container?: string
/**
* CSS selector for focus when the drawer opens. Use `true` for the
* autofocus target or first focusable element, or `false` to skip focus.
* Omit this prop to focus the popup.
*/
initialFocus?: boolean | string
/**
* CSS selector for focus when the drawer closes. Use `true` for the
* trigger or previous focus, or `false` to skip focus restoration.
* When omitted, the controller can preserve focus outside the drawer.
*/
finalFocus?: boolean | string
/**
* The variant of the drawer
*
* - `straight` - standard drawer attached to the edge of the viewport
* - `inset` - drawer inset from the top/side edges of the viewport, aka `floating`.
*
* @default 'default'
*/
variant?: 'default' | 'straight' | 'inset'
/**
* Show a close button in the top right corner of the drawer
*
* @default false
*/
showCloseButton?: boolean
/**
* Show a drawer handle bar at the drawer edge, used for swipe gestures
*
* @default false
*/
showBar?: boolean
/**
* Show a dark backdrop behind the drawer, overlaying the content
*
* @default true
*/
showBackdrop?: boolean
}
/** A group of drawer menu controls with an optional visible label. */
export interface DrawerMenuGroupProps {
/** Text displayed above the controls and used to name the group. */
label?: string
}
/** Behavior and style for a drawer menu link or button. */
export interface DrawerMenuItemProps {
/**
* Close the current drawer on selection. Use `"all"` to close it and
* all its parent drawers. Link navigation keeps its normal behavior.
* @default false
*/
closeOnSelect?: boolean | 'all'
/**
* Style for a standard or destructive action.
* @default 'default'
*/
variant?: 'default' | 'destructive'
}
export interface DrawerTriggerProps {
/**
* The id of the drawer to target if using it from outside the drawer root
*/
target?: string
/**
* JSON serializable payload that willl be forwarded to the event listeners `drawer:beforeChange` and `drawer:change`
*/
payload?: Record<string, unknown>
}
Usage
---
import { buttonVariants } from "@/components/ui/button"
import {
Drawer, DrawerTrigger, DrawerPopup, DrawerHeader, DrawerTitle,
DrawerDescription, DrawerPanel, DrawerFooter, DrawerClose,
DrawerMenu, DrawerMenuItem,
} from "@/components/ui/drawer"
---
<Drawer position="right">
<DrawerTrigger>Open menu</DrawerTrigger>
<DrawerPopup variant="inset" showCloseButton>
<DrawerHeader>
<DrawerTitle>Menu</DrawerTitle>
</DrawerHeader>
<DrawerPanel>
<DrawerMenu aria-label="Site navigation">
<DrawerMenuItem as="a" href="/about" closeOnSelect>About</DrawerMenuItem>
<DrawerMenuItem as="a" href="/contact" closeOnSelect>Contact</DrawerMenuItem>
</DrawerMenu>
</DrawerPanel>
</DrawerPopup>
</Drawer>
Always include DrawerTitle. Use class="sr-only" to hide the title visually.
Use Astro’s as prop for link controls. DrawerClose is a plain element.
Pass class={buttonVariants()} when it should look like a button.
DrawerMenuItem keeps the drawer open unless closeOnSelect is set.
Use closeOnSelect="all" to close the current drawer and its parent drawers.
Links keep their normal navigation behavior.
Positions and styles
The root sets both the screen edge and the swipe direction. DrawerPopup
includes the portal, backdrop, and viewport.
Scrollable content
The panel scrolls while the title and footer stay in place. Native scrolling keeps long menus usable on small screens.
Snap point
Set snapPoint={0.6} to open a bottom drawer at 60% of the viewport height.
The popup’s CSS height limits the open size, so give it a larger height such as
h-[80dvh]. For a side drawer, use a length such as snapPoint="20rem".
The popup keeps a direct DrawerPanel within the visible area. A drawer has
one open snap point. A drag returns it to that point or closes it.
Nested drawers
Place a complete drawer inside the parent panel. Escape and swipe dismiss the front drawer first. Focus returns to its trigger. Rear drawers move back by one step per open child. Rounded drawers also become smaller. The front drawer’s height sets the visible edge, so drawers with different content heights keep the same spacing. Nested drawers share the outer drawer’s backdrop.
Nesting does not need a DrawerProvider or an extra wrapper around Drawer.
The data-slot controller tracks nested roots and supplies --nested-drawers,
--drawer-front-height, and --drawer-swipe-progress to the popup styles.
The optional data-slot drawer-provider slot controls a separate effect: it
moves the page surface inside drawer-indent when a drawer opens.
Drawer menus
Place DrawerMenuTrigger inside a nested Drawer to open a submenu panel.
It uses the drawer-trigger slot and adds a trailing chevron. Each submenu
uses the same drawer behavior: swipe, Escape, or Back closes the front panel
and returns focus to its trigger.
Use DrawerMenuGroup to group related items. Its optional label appears
above the items. Use DrawerMenuGroupLabel when the label needs its own
attributes. Keep a DrawerTitle and a close control in each panel.
No backdrop
Use modal={false} and showBackdrop={false} to keep the page visible and
usable. Add disablePointerDismissal when users need to use the page while
the drawer stays open. Keep a close button available.
<Drawer position="right" modal={false} disablePointerDismissal>
<DrawerTrigger>Design</DrawerTrigger>
<DrawerPopup showBackdrop={false} showCloseButton>
<DrawerHeader>
<DrawerTitle>Design</DrawerTitle>
</DrawerHeader>
<DrawerPanel>Design controls</DrawerPanel>
</DrawerPopup>
</Drawer>
Props
DrawerProps
defaultOpen?boolean
Initial open state when `open` is omitted (default: `data-default-open`, then `false`).
booleantriggerId?string | null
Initial associated trigger ID, taking precedence over `defaultTriggerId` when non-null.
string | nulldefaultTriggerId?string | null
Fallback initial trigger ID, before root trigger-ID attributes. Defaults to no associated trigger.
string | nullmodal?boolean | 'trap-focus'
`true` traps focus, makes outside content inert, and locks scrolling (default). `"trap-focus"` traps focus without inertness or scroll locking; `false` is non-modal. Also configurable with root `data-modal`.
boolean | 'trap-focus'closeOnEscape?boolean
Allow Escape to dismiss the drawer (default: `true`).
booleandisablePointerDismissal?boolean
Ignore outside pointer presses and non-modal focus-out dismissal (default: `false`).
booleansnapPoint?DrawerSnapPoint | null
Initial single open position. Use a viewport fraction, pixel number, or CSS length in `px` or `rem`. The popup size limits this value. Omit both snap props to use the popup's full size.
DrawerSnapPoint | nulldefaultSnapPoint?DrawerSnapPoint | null
Initial open position when `snapPoint` is not set.
DrawerSnapPoint | nullposition?'bottom' | 'top' | 'left' | 'right'
The position of the drawer.
'bottom' | 'top' | 'left' | 'right'"bottom"closeOnMedia?string
A media query string that will be used to close the drawer when the media query matches.
stringDrawerTriggerProps
target?string
The id of the drawer to target if using it from outside the drawer root
stringpayload?Record<string, unknown>
JSON serializable payload that willl be forwarded to the event listeners `drawer:beforeChange` and `drawer:change`
Record<string, unknown>DrawerPopupProps
keepMounted?boolean
Keep content at its portal destination while closed and hidden (default: `false`; portal `data-keep-mounted`).
booleancontainer?string
CSS selector for the portal destination.
string"body"initialFocus?boolean | string
CSS selector for focus when the drawer opens. Use `true` for the autofocus target or first focusable element, or `false` to skip focus. Omit this prop to focus the popup.
boolean | stringfinalFocus?boolean | string
CSS selector for focus when the drawer closes. Use `true` for the trigger or previous focus, or `false` to skip focus restoration. When omitted, the controller can preserve focus outside the drawer.
boolean | stringvariant?'default' | 'straight' | 'inset'
The variant of the drawer - `straight` - standard drawer attached to the edge of the viewport - `inset` - drawer inset from the top/side edges of the viewport, aka `floating`.
'default' | 'straight' | 'inset''default'showCloseButton?boolean
Show a close button in the top right corner of the drawer
booleanfalseshowBar?boolean
Show a drawer handle bar at the drawer edge, used for swipe gestures
booleanfalseshowBackdrop?boolean
Show a dark backdrop behind the drawer, overlaying the content
booleantrueDrawerMenuGroupProps
label?string
Text displayed above the controls and used to name the group.
stringDrawerMenuItemProps
closeOnSelect?boolean | 'all'
Close the current drawer on selection. Use `"all"` to close it and all its parent drawers. Link navigation keeps its normal behavior.
boolean | 'all'falsevariant?'default' | 'destructive'
Style for a standard or destructive action.
'default' | 'destructive''default'Events
Dispatch these events on the drawer root. The root emits the outbound events.
Outbound events
| Event | Detail |
|---|---|
drawer:beforechange |
{ open: boolean, reason: DrawerChangeReason, trigger: HTMLElement | null, payload: unknown, originalEvent?: Event, cancel(): void, preventUnmountOnClose(): void } |
drawer:change |
{ open: boolean, reason: DrawerChangeReason, trigger: HTMLElement | null, payload: unknown, originalEvent?: Event, cancel(): void, preventUnmountOnClose(): void } |
drawer:change-complete |
{ open: boolean } |
drawer:beforesnapchange |
{ snapPoint: number | string | null, reason: DrawerChangeReason, originalEvent?: Event, cancel(): void } |
drawer:snapchange |
{ snapPoint: number | string | null, reason: DrawerChangeReason, originalEvent?: Event, cancel(): void } |
drawer:beforechange and drawer:beforesnapchange are cancelable. Call event.preventDefault() or detail.cancel() to stop the change. DrawerChangeReason is trigger-press, close-press, outside-press, escape-key, focus-out, imperative-action, swipe, or none.
Inbound events
| Event | Detail |
|---|---|
drawer:set |
{ open?: boolean, snapPoint?: number | string | null, triggerId?: string } |
drawer:open |
none |
drawer:close |
none |
drawer:toggle |
none |
drawer:unmount |
none |
For a complete navigation block, see Mobile Menu.
When to use Drawer
Use Drawer for a short task or detail view that enters from a screen edge. Keep a title and explicit close control. Choose the direction that fits the page; a bottom drawer can work well for short mobile actions.
Keyboard and behavior
The current controller handles dragging, Escape, and modal focus. Keep a close button available so dragging is never the only way out. Each drawer has one open snap point.
Theme and layout
The drawer uses shared dialog colors and direction-specific motion. Test long content while dragging and scrolling on touch screens. A larger drawer needs a constrained body so controls remain reachable.