import type { HTMLAttributes, ReactNode } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { cx } from '../../utils/cx'
import { useKeyboardInset } from '../../hooks/useKeyboardInset'
import type { MayFooterLayout, MaySize } from '../../types'
import { useIsDesktop } from '../../hooks/useIsDesktop'
import { useReducedMotion } from '../../hooks/useReducedMotion'
import { useAutoId } from '../../utils/useId'
import { clampWithRubber, draggable, projectFlick } from '../../motion/gesture'
import { overlayTrigger, useExitDelay, useOpenState, useOverlay } from '../../overlay'
/** Matches the exit transition in Sheet.css. */
const EXIT_MS = 150
/**
* Extends `HTMLAttributes` so a consumer can attach the things every other
* component already allows: `data-testid` for e2e, an `id`, extra `aria-*`,
* a `ref`. `title` is omitted because this component means a heading by it,
* not the HTML tooltip attribute.
*/
export interface SheetProps extends Omit, 'title'> {
/** Controlled state. Omit it and the sheet owns its own. */
open?: boolean
/** Starting state when uncontrolled. @default false */
defaultOpen?: boolean
/** Fires on every change, controlled or not. */
onOpenChange?: (open: boolean) => void
/**
* The control that opens it. A React element is cloned; your onClick still runs.
*
* Overlays render inline rather than through a portal, so do not put a
* trigger inside an ARIA-structured container — a `role="list"`, `tablist`,
* `radiogroup` or `menu`. The scrim would become a child the container's
* role does not allow, which axe reports as aria-required-children. Drive it
* with `open` from outside instead.
*/
trigger?: ReactNode
/** Called when the sheet closes. Optional: an uncontrolled sheet closes itself. */
onClose?: () => void
children?: ReactNode
title?: ReactNode
description?: ReactNode
footer?: ReactNode
/**
* How the footer lays its actions out. `'end'` (the default) is today's
* behaviour: content-sized, pinned to the trailing edge. `'stack'` is the
* native phone shape — a column of full-width actions, primary first, which
* is what a single "Save" almost always wants instead of a small pill in the
* corner. `'fill'` keeps one row and shares the width equally.
* @default 'end'
*/
footerLayout?: MayFooterLayout
/** @default 'md' */
/**
* The shared scale plus `'full'`, which the scale has no step for: a sheet
* that takes the whole viewport is a different intent, not a fourth size.
*/
size?: Exclude | 'full'
/** Show the drag grabber on the phone presentation. @default true */
grabber?: boolean
/**
* Which edge the sheet comes from. `'bottom'` (the default) is the phone
* sheet, and becomes a centred dialog at the desktop breakpoint. `'start'`
* and `'end'` are edge drawers — the standard desktop editor shape — and
* stay drawers at every width, so they do not reshape under you.
* @default 'bottom'
*/
side?: 'bottom' | 'start' | 'end'
/** Allow dragging the sheet down to dismiss it. @default true */
dismissible?: boolean
closeOnScrimClick?: boolean
className?: string
}
/** Past this fraction of its own height, releasing dismisses rather than snapping back. */
const DISMISS_RATIO = 0.35
/** A decisive downward flick dismisses even from near the top. */
const DISMISS_VELOCITY = 0.5
/**
* A sheet.
*
* One component, two shapes: it rises from the bottom edge on phones, with a
* grabber and drag-to-dismiss, and presents as a centred dialog on desktop.
* The consumer writes it once.
*
* The drag is real: the sheet tracks the finger with rubber-band resistance
* upward, and on release it decides using both distance and projected flick
* velocity, so a short fast swipe dismisses the way it does natively.
*/
export function Sheet({
open: openProp,
defaultOpen,
onOpenChange,
trigger,
onClose,
children,
title,
description,
footer,
footerLayout = 'end',
side = 'bottom',
size = 'md',
grabber = true,
dismissible = true,
closeOnScrimClick = true,
className,
...rest
}: SheetProps) {
const id = useAutoId()
const { open, setOpen } = useOpenState({ open: openProp, defaultOpen, onOpenChange })
const close = useCallback(() => {
setOpen(false)
onClose?.()
}, [setOpen, onClose])
const isDesktop = useIsDesktop()
const reducedMotion = useReducedMotion()
const mounted = useExitDelay(open, reducedMotion ? 0 : EXIT_MS)
const [dragging, setDragging] = useState(false)
// Only while open: the measurement is cheap but the listeners are not free,
// and a closed sheet has no footer to keep above the keys.
useKeyboardInset(open)
/*
* Keyed to `mounted`, not `open`. Releasing the scroll lock and handing focus
* back the moment `open` flips does it at the START of the exit animation:
* the scrollbar returns, the viewport narrows under a panel that is still on
* screen, and its width snaps mid-dismiss.
*
* Escape is the layer stack's now. This component used to register a
* CAPTURE-phase listener on `document`, which beat every nested layer to the
* key regardless of what was on top — a Popover opened inside a Sheet took
* the Sheet down with it.
*/
const { panelRef } = useOverlay({
open: mounted,
onClose: close,
})
/* Drag-to-dismiss. The phone sheet only — a centred dialog has no edge to
* drag from, and an edge drawer's axis is horizontal, so a downward drag
* would dismiss it in a direction it never travels. */
useEffect(() => {
const panel = panelRef.current
if (!open || !panel || presentation !== 'sheet' || !dismissible || reducedMotion) return
let height = panel.offsetHeight
return draggable(panel, {
axis: 'y',
onStart: () => {
height = panel.offsetHeight
setDragging(true)
panel.style.transition = 'none'
},
onMove: ({ dy }) => {
// Downward is free; upward meets rubber-band resistance so the sheet
// never detaches from the bottom edge.
panel.style.transform = `translateY(${clampWithRubber(dy, 0, Number.POSITIVE_INFINITY)}px)`
},
onEnd: ({ dy, vy }) => {
setDragging(false)
panel.style.transition = ''
const projected = dy + projectFlick(vy)
const dismiss = projected > height * DISMISS_RATIO || vy > DISMISS_VELOCITY
panel.style.transform = ''
if (dismiss) close()
},
})
}, [open, isDesktop, dismissible, reducedMotion, close])
/*
* A drawer is a drawer at every width: reshaping an edge drawer into a
* centred dialog halfway across a breakpoint is exactly the surprise the
* adaptive story is meant to avoid. Only the default bottom sheet adapts.
*/
const presentation = side !== 'bottom' ? 'drawer' : isDesktop ? 'dialog' : 'sheet'
const triggerNode =
trigger === undefined
? null
: overlayTrigger(trigger, {
open,
onToggle: () => setOpen(!open),
controls: mounted ? `${id}-panel` : undefined,
className: 'may-overlay__trigger may-pressable may-hoverable',
})
// Stays mounted for the length of its exit, so a dismissal animates instead
// of blinking off the screen next to an entrance that rises.
return (
<>
{triggerNode}
{mounted && (
{
if (closeOnScrimClick && event.target === event.currentTarget) close()
}}
>