# Sheet

> Bottom sheet on phones that pushes the screen back and can be dragged or flung away, a centered dialog from 640px, an optional photo header the row's thumbnail flies into, and a confirm for destructive actions.

Docs: https://plumbago.ochotzas.com/components/sheet

## Installation

```sh
npx plumbago add sheet
```

This copies `components/ui/sheet.tsx` into your project, along with `cn`, `morph`, `spring`, `button`, and installs `@base-ui/react`.

## Usage

```tsx
import { Sheet, SheetContent, SheetHeader, SheetPhoto, SheetPushBack, SheetTitle, SheetTrigger } from "@/components/ui/sheet"

<Sheet>
  <SheetTrigger render={<Button />}>Edit dish</SheetTrigger>
  <SheetContent title="Edit dish" description="Changes show on the menu right away.">
    ...
  </SheetContent>
</Sheet>

<Sheet open={open} onOpenChange={setOpen} photoSource={rowElement}>
  <SheetContent>
    <SheetPhoto>
      <img src={dish.photo} alt={dish.name} />
    </SheetPhoto>
    <SheetHeader>
      <SheetTitle>{dish.name}</SheetTitle>
    </SheetHeader>
  </SheetContent>
</Sheet>

<SheetPushBack>
  <App />
</SheetPushBack>
```

## Examples

### Preview

```tsx
import { BlurSwap } from "@/lib/blur-swap"
import { Button } from "@/components/ui/button"
import { TextField } from "@/components/ui/input"
import { Island, IslandLabel, ListRow, ListRowSubtitle, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { Sheet, SheetContent, SheetFooter, SheetPushBack, SheetTrigger } from "@/components/ui/sheet"
import { Switch } from "@/components/ui/switch"
import { type FormEvent, useState } from "react"

export default function SheetDemo() {
  const [open, setOpen] = useState(false)
  const [dish, setDish] = useState({ name: "Burrata with blood orange", price: "14.50", soldOut: false })
  const save = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    const form = new FormData(event.currentTarget)
    setDish({
      name: String(form.get("name")),
      price: Number(String(form.get("price")).replace(",", ".")).toFixed(2),
      soldOut: form.get("soldOut") === "on",
    })
    setOpen(false)
  }
  return (
    <div className="w-full max-w-[390px] overflow-hidden rounded-xl border border-line">
      <SheetPushBack className="flex h-[560px] flex-col gap-4 p-gutter pt-8">
        <h2 className="text-title2 font-semibold">Menu</h2>
        <div>
          <IslandLabel>Starters</IslandLabel>
          <Island variant="list">
            <ListRow>
              <ListRowText>
                <ListRowTitle>
                  <BlurSwap text={dish.name} />
                </ListRowTitle>
                <ListRowSubtitle>
                  <BlurSwap text={dish.soldOut ? "Sold out today" : "On the menu"} />
                </ListRowSubtitle>
              </ListRowText>
              <ListRowValue className="tabular-nums">
                <BlurSwap text={`€${dish.price}`} />
              </ListRowValue>
            </ListRow>
            <ListRow>
              <ListRowText>
                <ListRowTitle>Beef tartare</ListRowTitle>
                <ListRowSubtitle>On the menu</ListRowSubtitle>
              </ListRowText>
              <ListRowValue>€16.00</ListRowValue>
            </ListRow>
          </Island>
        </div>
        <Sheet open={open} onOpenChange={setOpen}>
          <SheetTrigger render={<Button />}>Edit dish</SheetTrigger>
          <SheetContent title="Edit dish" description="Changes show on the menu right away.">
            <form onSubmit={save} className="flex flex-col gap-4">
              <TextField label="Name" name="name" defaultValue={dish.name} required />
              <TextField label="Price (€)" name="price" defaultValue={dish.price} inputMode="decimal" pattern="[0-9]+([.,][0-9]{1,2})?" required />
              <Island variant="list">
                <ListRow render={<label />}>
                  <ListRowText>
                    <ListRowTitle>Sold out today</ListRowTitle>
                  </ListRowText>
                  <Switch name="soldOut" defaultChecked={dish.soldOut} />
                </ListRow>
              </Island>
              <SheetFooter className="mt-2">
                <Button type="submit" size="lg">
                  Save
                </Button>
              </SheetFooter>
            </form>
          </SheetContent>
        </Sheet>
      </SheetPushBack>
    </div>
  )
}
```

### Photo fly in

```tsx
import { Button } from "@/components/ui/button"
import { Island, IslandLabel, ListRow, ListRowChevron, ListRowSubtitle, ListRowText, ListRowThumb, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetPhoto, SheetPushBack, SheetTitle } from "@/components/ui/sheet"
import { useState } from "react"

const dishes = [
  {
    name: "Burrata with blood orange",
    note: "Basil oil, black pepper",
    price: "€14.50",
    photo: "/dishes/burrata.webp",
    description: "Creamy burrata on blood orange, finished with basil oil and cracked pepper.",
  },
  {
    name: "Beef tartare",
    note: "Egg yolk, capers",
    price: "€16.00",
    photo: "/dishes/tartare.webp",
    description: "Hand-cut beef with egg yolk and capers, served with warm toasted bread.",
  },
  {
    name: "Roasted beet salad",
    note: "Goat cheese, walnuts",
    price: "€11.00",
    photo: "/dishes/beet-salad.webp",
    description: "Roasted beets with soft goat cheese, walnuts and bitter leaves.",
  },
  {
    name: "Tagliatelle al pomodoro",
    note: "Parmesan, basil",
    price: "€15.00",
    photo: "/dishes/tagliatelle.webp",
    description: "Fresh tagliatelle in slow-cooked tomato sauce with parmesan and basil.",
  },
]

export default function SheetPhotoFlyIn() {
  const [open, setOpen] = useState(false)
  const [dish, setDish] = useState<(typeof dishes)[number] | null>(null)
  const [source, setSource] = useState<HTMLElement | null>(null)
  return (
    <div className="w-full max-w-[390px] overflow-hidden rounded-xl border border-line">
      <SheetPushBack className="flex h-[560px] flex-col gap-4 p-gutter pt-8">
        <h2 className="text-title2 font-semibold">Menu</h2>
        <div>
          <IslandLabel>Starters and pasta</IslandLabel>
          <Island variant="list">
            {dishes.map((item) => (
              <ListRow
                key={item.name}
                render={<button type="button" />}
                onClick={(event) => {
                  setDish(item)
                  setSource(event.currentTarget)
                  setOpen(true)
                }}
              >
                <ListRowThumb>
                  <img src={item.photo} alt="" />
                </ListRowThumb>
                <ListRowText>
                  <ListRowTitle>{item.name}</ListRowTitle>
                  <ListRowSubtitle>{item.note}</ListRowSubtitle>
                </ListRowText>
                <ListRowValue>{item.price}</ListRowValue>
                <ListRowChevron />
              </ListRow>
            ))}
          </Island>
        </div>
        <Sheet open={open} onOpenChange={setOpen} photoSource={source}>
          <SheetContent>
            {dish && (
              <>
                <SheetPhoto>
                  <img src={dish.photo} alt={dish.name} />
                </SheetPhoto>
                <SheetHeader>
                  <SheetTitle>{dish.name}</SheetTitle>
                  <SheetDescription>{dish.price}</SheetDescription>
                </SheetHeader>
                <p className="text-body text-ink-2">{dish.description}</p>
                <SheetFooter>
                  <SheetClose render={<Button size="lg" />}>Add to order</SheetClose>
                </SheetFooter>
              </>
            )}
          </SheetContent>
        </Sheet>
      </SheetPushBack>
    </div>
  )
}
```

### Confirm dialog

```tsx
import { cn } from "@/lib/cn"
import { Button } from "@/components/ui/button"
import { ConfirmDialog } from "@/components/ui/sheet"
import { useRef, useState } from "react"

const swap = "col-start-1 row-start-1 justify-self-center transition-[opacity,filter,translate,scale]"
const shown = "delay-[120ms] duration-spring ease-spring"
const hidden = "pointer-events-none opacity-0 duration-[160ms] ease-in motion-safe:-translate-y-1 motion-safe:scale-98 motion-safe:blur-[8px]"

export default function SheetConfirmDialog() {
  const [deleted, setDeleted] = useState(false)
  const restoreRef = useRef<HTMLButtonElement | null>(null)
  return (
    <div className="grid">
      <div className={cn(swap, deleted ? hidden : shown)} inert={deleted}>
        <ConfirmDialog
          trigger={<Button variant="destructive">Delete dish</Button>}
          title="Delete dish?"
          description="Lamb shoulder disappears from the menu and from today's orders."
          confirmLabel="Delete dish"
          onConfirm={() => setDeleted(true)}
          onOpenChangeComplete={(open) => {
            if (!open && deleted) restoreRef.current?.focus()
          }}
        />
      </div>
      <Button ref={restoreRef} variant="secondary" className={cn(swap, deleted ? shown : hidden)} inert={!deleted} onClick={() => setDeleted(false)}>
        Restore dish
      </Button>
    </div>
  )
}
```

## Built on Base UI

Sheet wraps these Base UI parts and keeps their props:

- [Alert dialog](https://base-ui.com/react/components/alert-dialog)
- [Dialog](https://base-ui.com/react/components/dialog)

## Source

```tsx
import { AlertDialog } from "@base-ui/react/alert-dialog"
import { Dialog } from "@base-ui/react/dialog"
import { cn } from "@/lib/cn"
import { isVisibleColor } from "@/lib/morph"
import { createVelocityTracker, type Settle, settleSpring } from "@/lib/spring"
import { Button } from "@/components/ui/button"
import { type ComponentProps, createContext, type ReactElement, type ReactNode, type RefObject, useCallback, useContext, useRef } from "react"

type Closer = { close: () => void }

type SheetContextValue = {
  actions: RefObject<Closer | null>
  onClosed: RefObject<(() => void) | null>
  photoSource?: RefObject<HTMLElement | null | undefined>
  trigger?: RefObject<HTMLElement | null>
}

const SheetContext = createContext<SheetContextValue | null>(null)

const flingSpeed = 700
const pullUpResistance = 4
const dragIgnoredTargets = "input, textarea, select, button, a, label, [contenteditable], [data-sheet-no-drag]"

const scrimClasses = cn(
  "fixed inset-0 z-50 bg-scrim sm:backdrop-blur-[6px] sm:[@media(prefers-reduced-transparency:reduce)]:backdrop-blur-none",
  "transition-opacity duration-base ease-out data-starting-style:opacity-0 data-ending-style:opacity-0 data-ending-style:ease-in",
)

const mobilePanelClasses = cn(
  "max-sm:max-h-[calc(100dvh-40px)] max-sm:rounded-t-xl max-sm:px-gutter max-sm:pt-3 max-sm:pb-[calc(32px+env(safe-area-inset-bottom))]",
  "max-sm:cursor-grab max-sm:touch-none max-sm:data-scrollable:touch-pan-y max-sm:data-dragging:cursor-grabbing max-sm:data-dragging:select-none",
  "max-sm:group-data-[morph=fade]/morph:fixed max-sm:group-data-[morph=fade]/morph:z-50 max-sm:group-data-[morph=fade]/morph:inset-x-0 max-sm:group-data-[morph=fade]/morph:bottom-0",
  "max-sm:group-data-[morph=grow]/morph:relative",
  "max-sm:group-data-[morph=fade]/morph:shadow-[0_var(--sheet-lift,0px)_0_0_var(--pb-bg),var(--pb-shadow-float)]",
  "max-sm:group-data-[morph=fade]/morph:data-starting-style:translate-y-[105%] max-sm:group-data-[morph=fade]/morph:data-ending-style:translate-y-[105%] max-sm:group-data-[morph=fade]/morph:data-ending-style:duration-[250ms] max-sm:group-data-[morph=fade]/morph:data-ending-style:ease-in",
  "max-sm:group-data-[morph=fade]/morph:motion-reduce:data-starting-style:translate-y-0 max-sm:group-data-[morph=fade]/morph:motion-reduce:data-starting-style:opacity-0 max-sm:group-data-[morph=fade]/morph:motion-reduce:data-ending-style:translate-y-0 max-sm:group-data-[morph=fade]/morph:motion-reduce:data-ending-style:opacity-0",
)

const dialogShellClasses = cn(
  "group/morph sm:fixed sm:top-1/2 sm:left-1/2 sm:z-50 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:[--morph-radius-end:var(--pb-radius-xl)] sm:[--morph-radius-start:var(--pb-radius-xl)] [--morph-shape-start:squircle]",
  "max-sm:data-[morph=fade]:contents max-sm:data-[morph=grow]:fixed max-sm:data-[morph=grow]:inset-x-0 max-sm:data-[morph=grow]:bottom-0 max-sm:data-[morph=grow]:z-50 max-sm:[--morph-radius-end:var(--pb-radius-xl)_var(--pb-radius-xl)_0_0] max-sm:[--morph-clip-end:calc(var(--pb-radius-xl)/var(--pb-corner-scale,1))_calc(var(--pb-radius-xl)/var(--pb-corner-scale,1))_0_0]",
  "before:pointer-events-none before:absolute before:inset-0 before:rounded-(--morph-radius-end) before:[corner-shape:squircle] before:bg-(--morph-color-end) before:shadow-float before:content-['']",
  "before:transition-[inset,border-radius,corner-shape,opacity,background-color] before:duration-spring before:ease-spring data-[morph=fade]:before:hidden",
  "has-[>[data-starting-style]]:before:[inset:var(--morph-top)_var(--morph-right)_var(--morph-bottom)_var(--morph-left)] has-[>[data-starting-style]]:before:rounded-(--morph-radius-start) has-[>[data-starting-style]]:before:[corner-shape:var(--morph-shape-start)] has-[>[data-starting-style]]:before:bg-[var(--morph-color-start,var(--morph-color-end))] has-[>[data-starting-style]]:before:transition-none",
  "has-[>[data-ending-style]]:before:[inset:var(--morph-top)_var(--morph-right)_var(--morph-bottom)_var(--morph-left)] has-[>[data-ending-style]]:before:rounded-(--morph-radius-start) has-[>[data-ending-style]]:before:[corner-shape:var(--morph-shape-start)] has-[>[data-ending-style]]:before:bg-[var(--morph-color-start,var(--morph-color-end))] has-[>[data-ending-style]]:before:opacity-0",
  "has-[>[data-ending-style]]:before:[transition:inset_350ms_var(--pb-ease-out),border-radius_350ms_var(--pb-ease-out),corner-shape_350ms_var(--pb-ease-out),background-color_350ms_var(--pb-ease-out),opacity_80ms_linear_270ms]",
)

const dialogPanelClasses = cn(
  "sm:relative sm:max-h-[calc(100dvh-48px)] sm:w-full sm:rounded-xl sm:p-6",
  "transition-[clip-path,opacity,filter,translate,scale] duration-spring ease-spring [clip-path:inset(0_round_var(--morph-clip-end,calc(var(--morph-radius-end)/var(--pb-corner-scale,1))))]",
  "group-data-[morph=grow]/morph:bg-transparent group-data-[morph=grow]/morph:shadow-none group-data-[morph=grow]/morph:[&>*]:animate-content-in",
  "group-data-[morph=grow]/morph:data-starting-style:[clip-path:inset(var(--morph-top)_var(--morph-right)_var(--morph-bottom)_var(--morph-left)_round_var(--morph-clip-start,calc(var(--morph-radius-start)/var(--pb-corner-scale,1))))] group-data-[morph=grow]/morph:data-starting-style:transition-none",
  "group-data-[morph=grow]/morph:data-ending-style:[clip-path:inset(var(--morph-top)_var(--morph-right)_var(--morph-bottom)_var(--morph-left)_round_var(--morph-clip-start,calc(var(--morph-radius-start)/var(--pb-corner-scale,1))))] group-data-[morph=grow]/morph:data-ending-style:opacity-0 group-data-[morph=grow]/morph:data-ending-style:blur-[4px]",
  "group-data-[morph=grow]/morph:data-ending-style:[transition:clip-path_350ms_var(--pb-ease-out),opacity_140ms_var(--pb-ease-out),filter_140ms_var(--pb-ease-out)]",
  "group-data-[morph=fade]/morph:[clip-path:none]",
  "sm:group-data-[morph=fade]/morph:data-starting-style:translate-y-[4%] sm:group-data-[morph=fade]/morph:data-starting-style:scale-96 sm:group-data-[morph=fade]/morph:data-starting-style:opacity-0 sm:group-data-[morph=fade]/morph:motion-safe:data-starting-style:blur-[8px]",
  "sm:group-data-[morph=fade]/morph:data-ending-style:-translate-y-1 sm:group-data-[morph=fade]/morph:data-ending-style:scale-96 sm:group-data-[morph=fade]/morph:data-ending-style:opacity-0 sm:group-data-[morph=fade]/morph:motion-safe:data-ending-style:blur-[8px]",
  "sm:group-data-[morph=fade]/morph:data-ending-style:duration-[220ms] sm:group-data-[morph=fade]/morph:data-ending-style:ease-in",
  "sm:group-data-[morph=fade]/morph:motion-reduce:data-starting-style:translate-y-0 sm:group-data-[morph=fade]/morph:motion-reduce:data-starting-style:scale-100 sm:group-data-[morph=fade]/morph:motion-reduce:data-ending-style:translate-y-0 sm:group-data-[morph=fade]/morph:motion-reduce:data-ending-style:scale-100",
)

const closeHitArea = "after:absolute after:-inset-1.5"

const photoSourceSelector = "[data-sheet-photo-source], [data-slot=list-row-thumb]"
const photoGhostLayer = 60
const photoInViewTolerance = 8

export type SheetProps = Dialog.Root.Props & {
  photoSource?: HTMLElement | null
}

export function Sheet({ actionsRef, onOpenChangeComplete, photoSource, ...props }: SheetProps) {
  const ownActions = useRef<Dialog.Root.Actions | null>(null)
  const onClosed = useRef<(() => void) | null>(null)
  const photoSourceRef = useRef(photoSource)
  photoSourceRef.current = photoSource
  const trigger = useRef<HTMLElement | null>(null)
  const actions = actionsRef ?? ownActions
  const handleOpenChangeComplete = (open: boolean) => {
    if (!open) {
      onClosed.current?.()
      trigger.current = null
    }
    onOpenChangeComplete?.(open)
  }
  return (
    <SheetContext value={{ actions, onClosed, photoSource: photoSourceRef, trigger }}>
      <Dialog.Root actionsRef={actions} onOpenChangeComplete={handleOpenChangeComplete} {...props} />
    </SheetContext>
  )
}

export type SheetPushBackProps = Omit<ComponentProps<"div">, "className"> & { className?: string }

export function SheetPushBack({ className, children, ...props }: SheetPushBackProps) {
  return (
    <div data-slot="sheet-push-back" className="bg-black" {...props}>
      <div
        data-slot="sheet-push-back-screen"
        className={cn(
          "relative origin-top overflow-clip bg-bg",
          "max-sm:transition-[transform,border-radius] max-sm:duration-spring max-sm:ease-spring",
          "max-sm:in-data-sheet-open:[transform:translateY(14px)_scale(0.92)] max-sm:in-data-sheet-open:rounded-[26px]",
          "max-sm:motion-reduce:in-data-sheet-open:transform-none max-sm:motion-reduce:in-data-sheet-open:rounded-none max-sm:motion-reduce:duration-base",
          className,
        )}
      >
        {children}
        <div
          data-slot="sheet-push-back-dim"
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 z-40 bg-black opacity-0 max-sm:transition-opacity max-sm:duration-spring max-sm:ease-spring max-sm:in-data-sheet-open:opacity-25 max-sm:motion-reduce:duration-base"
        />
      </div>
    </div>
  )
}

export type SheetTriggerProps = Omit<Dialog.Trigger.Props, "className"> & { className?: string }

export function SheetTrigger({ className, onClick, ...props }: SheetTriggerProps) {
  const context = useContext(SheetContext)
  return (
    <Dialog.Trigger
      data-slot="sheet-trigger"
      className={className}
      onClick={(event) => {
        if (context?.trigger) context.trigger.current = event.currentTarget
        onClick?.(event)
      }}
      {...props}
    />
  )
}

export type SheetContentProps = Omit<Dialog.Popup.Props, "className" | "title"> & {
  title?: ReactNode
  description?: ReactNode
  showClose?: boolean
  className?: string
}

export function SheetContent({ title, description, showClose = true, className, children, ...props }: SheetContentProps) {
  const context = useContext(SheetContext)
  const { scrimRef, panelRef } = useDragToDismiss(context)
  return (
    <Dialog.Portal>
      <Dialog.Backdrop ref={scrimRef} data-slot="sheet-scrim" className={scrimClasses} />
      <DialogShell
        findOrigin={(compact) => sheetOrigin(context, compact)}
        className="sm:w-[min(440px,calc(100%-48px))] [--morph-color-end:var(--pb-bg)] max-sm:data-[morph=grow]:before:shadow-[0_var(--sheet-lift,0px)_0_0_var(--morph-color-end),var(--pb-shadow-float)]"
      >
        <Dialog.Popup
          {...props}
          ref={panelRef}
          data-slot="sheet"
          className={cn(
            "group/sheet [--pb-fill-field:var(--pb-surface)] [--pb-fill-secondary:var(--pb-track)] flex flex-col overflow-y-auto overscroll-contain bg-bg text-ink shadow-float outline-none",
            mobilePanelClasses,
            dialogPanelClasses,
            className,
          )}
        >
          <div
            data-slot="sheet-grabber"
            aria-hidden="true"
            className="relative z-10 mx-auto mb-4 h-[5px] w-9 shrink-0 touch-none rounded-full bg-track group-has-data-[slot=sheet-photo]/sheet:bg-surface/80 sm:hidden"
          />
          {title !== undefined && (
            <SheetHeader showClose={showClose}>
              <SheetTitle>{title}</SheetTitle>
              {description !== undefined && <SheetDescription>{description}</SheetDescription>}
            </SheetHeader>
          )}
          {children}
        </Dialog.Popup>
      </DialogShell>
    </Dialog.Portal>
  )
}

type MorphOrigin = { element: HTMLElement | null | undefined; inheritColor: boolean }

type DialogShellProps = {
  findOrigin: (compact: boolean) => MorphOrigin | null
  className: string
  children: ReactNode
}

function sheetOrigin(context: SheetContextValue | null, compact: boolean): MorphOrigin | null {
  const row = context?.photoSource?.current
  const trigger = context?.trigger?.current
  if (compact) return row ? { element: row, inheritColor: true } : null
  if (trigger) return { element: trigger, inheritColor: false }
  return row ? { element: row, inheritColor: true } : null
}

function DialogShell({ findOrigin, className, children }: DialogShellProps) {
  const shellRef = useDialogMorph(findOrigin)
  return (
    <div ref={shellRef} data-slot="dialog-shell" className={cn(dialogShellClasses, className)}>
      {children}
    </div>
  )
}

export type SheetPhotoProps = Omit<ComponentProps<"div">, "className"> & { className?: string }

export function SheetPhoto({ className, ...props }: SheetPhotoProps) {
  return (
    <div
      data-slot="sheet-photo"
      className={cn(
        "relative mb-4 aspect-[16/10] shrink-0 overflow-hidden bg-track [&_img]:pointer-events-none [&_img]:size-full [&_img]:object-cover [&_img]:select-none max-sm:-mx-gutter max-sm:-mt-[33px] sm:-mx-6 sm:-mt-6",
        className,
      )}
      {...props}
    />
  )
}

export type SheetHeaderProps = Omit<ComponentProps<"div">, "className"> & {
  showClose?: boolean
  className?: string
}

export function SheetHeader({ showClose = true, className, children, ...props }: SheetHeaderProps) {
  return (
    <div data-slot="sheet-header" className={cn("mb-5 flex shrink-0 items-start gap-3 max-sm:touch-none", className)} {...props}>
      <div className="flex min-w-0 flex-1 flex-col gap-1 pt-[5px]">{children}</div>
      {showClose && (
        <Dialog.Close
          data-slot="sheet-close"
          aria-label="Close"
          render={<Button variant="secondary" size="icon-sm" className={cn("size-8 [&_svg]:size-4", closeHitArea)} />}
        >
          <CloseIcon />
        </Dialog.Close>
      )}
    </div>
  )
}

export type SheetTitleProps = Omit<Dialog.Title.Props, "className"> & { className?: string }

export function SheetTitle({ className, ...props }: SheetTitleProps) {
  return <Dialog.Title data-slot="sheet-title" className={cn("text-headline font-semibold text-ink", className)} {...props} />
}

export type SheetDescriptionProps = Omit<Dialog.Description.Props, "className"> & { className?: string }

export function SheetDescription({ className, ...props }: SheetDescriptionProps) {
  return <Dialog.Description data-slot="sheet-description" className={cn("text-footnote text-ink-2", className)} {...props} />
}

export type SheetFooterProps = Omit<ComponentProps<"div">, "className"> & { className?: string }

export function SheetFooter({ className, ...props }: SheetFooterProps) {
  return <div data-slot="sheet-footer" className={cn("mt-6 flex shrink-0 flex-col gap-2 *:w-full", className)} {...props} />
}

export type SheetCloseProps = Omit<Dialog.Close.Props, "className"> & { className?: string }

export function SheetClose({ className, ...props }: SheetCloseProps) {
  return <Dialog.Close data-slot="sheet-close" className={className} {...props} />
}

export type ConfirmDialogProps = Omit<AlertDialog.Root.Props, "children"> & {
  trigger?: ReactElement
  title: ReactNode
  description?: ReactNode
  confirmLabel: ReactNode
  cancelLabel?: ReactNode
  onConfirm: () => void
  className?: string
}

export function ConfirmDialog({ trigger, title, description, confirmLabel, cancelLabel = "Cancel", onConfirm, className, ...props }: ConfirmDialogProps) {
  const cancelRef = useRef<HTMLButtonElement | null>(null)
  const triggerRef = useRef<HTMLElement | null>(null)
  const ownActions = useRef<AlertDialog.Root.Actions | null>(null)
  const onClosed = useRef<(() => void) | null>(null)
  const { actionsRef, onOpenChangeComplete, ...rootProps } = props
  const actions = actionsRef ?? ownActions
  const handleOpenChangeComplete = (open: boolean) => {
    if (!open) onClosed.current?.()
    onOpenChangeComplete?.(open)
  }
  return (
    <AlertDialog.Root actionsRef={actions} onOpenChangeComplete={handleOpenChangeComplete} {...rootProps}>
      {trigger && (
        <AlertDialog.Trigger
          data-slot="confirm-dialog-trigger"
          render={trigger}
          onClick={(event) => {
            triggerRef.current = event.currentTarget
          }}
        />
      )}
      <AlertDialog.Portal>
        <ConfirmPanel actions={actions} onClosed={onClosed} cancelRef={cancelRef} triggerRef={triggerRef} className={className}>
          <AlertDialog.Title data-slot="confirm-dialog-title" className="text-headline font-semibold text-ink">
            {title}
          </AlertDialog.Title>
          {description !== undefined && (
            <AlertDialog.Description data-slot="confirm-dialog-description" className="text-body text-ink-2">
              {description}
            </AlertDialog.Description>
          )}
          <div className="mt-4 flex flex-col gap-2">
            <AlertDialog.Close render={<Button variant="destructive-solid" size="lg" className="w-full" />} onClick={onConfirm}>
              {confirmLabel}
            </AlertDialog.Close>
            <AlertDialog.Close ref={cancelRef} render={<Button variant="plain" className="w-full" />}>
              {cancelLabel}
            </AlertDialog.Close>
          </div>
        </ConfirmPanel>
      </AlertDialog.Portal>
    </AlertDialog.Root>
  )
}

type ConfirmPanelProps = {
  actions: RefObject<Closer | null>
  onClosed: RefObject<(() => void) | null>
  cancelRef: RefObject<HTMLButtonElement | null>
  triggerRef: RefObject<HTMLElement | null>
  className?: string
  children: ReactNode
}

function ConfirmPanel({ actions, onClosed, cancelRef, triggerRef, className, children }: ConfirmPanelProps) {
  const { scrimRef, panelRef } = useDragToDismiss({ actions, onClosed })
  return (
    <>
      <AlertDialog.Backdrop ref={scrimRef} data-slot="confirm-dialog-scrim" className={scrimClasses} />
      <DialogShell
        findOrigin={(compact) => (compact ? null : { element: triggerRef.current, inheritColor: false })}
        className="sm:w-[min(400px,calc(100%-48px))] [--morph-color-end:var(--pb-surface)]"
      >
        <AlertDialog.Popup
          ref={panelRef}
          data-slot="confirm-dialog"
          initialFocus={cancelRef}
          className={cn("on-surface flex flex-col gap-2 bg-surface text-ink shadow-float outline-none", mobilePanelClasses, dialogPanelClasses, className)}
        >
          <div data-slot="confirm-dialog-grabber" aria-hidden="true" className="mx-auto mb-2 h-[5px] w-9 shrink-0 touch-none rounded-full bg-track sm:hidden" />
          {children}
        </AlertDialog.Popup>
      </DialogShell>
    </>
  )
}

function CloseIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="fill-none stroke-current" strokeWidth="1.75" strokeLinecap="round">
      <path d="M6 6l12 12M18 6L6 18" />
    </svg>
  )
}

type Rect = { x: number; y: number; w: number; h: number }

const rectOf = (element: Element): Rect => {
  const rect = element.getBoundingClientRect()
  return { x: rect.left, y: rect.top, w: rect.width, h: rect.height }
}

const lerp = (from: number, to: number, progress: number) => from + (to - from) * progress

const lerpRect = (from: Rect, to: Rect, progress: number): Rect => ({
  x: lerp(from.x, to.x, progress),
  y: lerp(from.y, to.y, progress),
  w: lerp(from.w, to.w, progress),
  h: lerp(from.h, to.h, progress),
})

const cornerScale = () => Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--pb-corner-scale")) || 1

const isSquircle = (element: Element) => /squircle|superellipse/.test(getComputedStyle(element).getPropertyValue("corner-top-left-shape"))

const cornerRadius = (element: Element) => {
  const radius = Number.parseFloat(getComputedStyle(element).borderTopLeftRadius) || 0
  return isSquircle(element) ? radius / cornerScale() : radius
}

type MorphCorners = { radius: string; clip: string; shape: "round" | "squircle" }

const cornersOf = (radii: number[], squircle: boolean): MorphCorners => ({
  radius: radii.map((radius) => `${radius}px`).join(" "),
  clip: radii.map((radius) => `${squircle ? radius / cornerScale() : radius}px`).join(" "),
  shape: squircle ? "squircle" : "round",
})

function findPhotoSource(origin: HTMLElement | null | undefined) {
  if (!origin?.isConnected) return null
  return origin.matches(photoSourceSelector) ? origin : origin.querySelector<HTMLElement>(photoSourceSelector)
}

type PhotoFlight = {
  close: () => void
  grab: () => void
  abort: () => void
}

function startPhotoFlight(panel: HTMLElement, source: HTMLElement, photo: HTMLElement, image: HTMLImageElement): PhotoFlight {
  const base = { w: photo.offsetWidth, h: photo.offsetHeight }
  const sourceRadius = cornerRadius(source)
  const photoRadius = cornerRadius(panel)
  let lastSource = rectOf(source)
  let lastPhoto = rectOf(photo)
  let progress = 0
  let ghost: HTMLImageElement | null = null
  let settling: Settle | null = null
  let closing = false

  const setPhotoVisible = (visible: boolean) => {
    photo.style.visibility = visible ? "" : "hidden"
  }

  const setSourceVisible = (visible: boolean) => {
    source.style.visibility = visible ? "" : "hidden"
  }

  const readRects = () => {
    if (source.isConnected) lastSource = rectOf(source)
    if (photo.isConnected) lastPhoto = rectOf(photo)
  }

  const place = () => {
    if (!ghost) return
    readRects()
    const t = Math.min(1, Math.max(0, progress))
    const rect = lerpRect(lastSource, lastPhoto, t)
    const scale = Math.max(rect.w / base.w, rect.h / base.h)
    const cropX = (base.w * scale - rect.w) / 2
    const cropY = (base.h * scale - rect.h) / 2
    const top = lerp(sourceRadius, photoRadius, t) / scale
    const bottom = lerp(sourceRadius, 0, t) / scale
    ghost.style.transform = `translate(${rect.x - cropX}px, ${rect.y - cropY}px) scale(${scale})`
    ghost.style.clipPath = `inset(${cropY / scale}px ${cropX / scale}px round ${top}px ${top}px ${bottom}px ${bottom}px)`
  }

  const addGhost = () => {
    const clone = image.cloneNode() as HTMLImageElement
    clone.removeAttribute("class")
    clone.removeAttribute("id")
    clone.alt = ""
    clone.setAttribute("aria-hidden", "true")
    clone.setAttribute("data-slot", "sheet-photo-ghost")
    Object.assign(clone.style, {
      position: "fixed",
      left: "0",
      top: "0",
      margin: "0",
      maxWidth: "none",
      width: `${base.w}px`,
      height: `${base.h}px`,
      objectFit: "cover",
      transformOrigin: "0 0",
      pointerEvents: "none",
      willChange: "transform, clip-path",
      zIndex: String(photoGhostLayer),
    })
    document.body.appendChild(clone)
    ghost = clone
  }

  const dropGhost = () => {
    settling?.stop()
    settling = null
    ghost?.remove()
    ghost = null
  }

  const flyTo = (target: number, onLanded: () => void) => {
    settling?.stop()
    settling = settleSpring(
      progress,
      target,
      0,
      (value) => {
        progress = value
        place()
      },
      () => {
        progress = target
        if (target === 1) followUntilStill(onLanded)
        else {
          dropGhost()
          onLanded()
        }
      },
      { restSpeed: 0.002, restDistance: 0.001 },
    )
  }

  const followUntilStill = (onLanded: () => void) => {
    let previous = lastPhoto
    let frame = 0
    const step = () => {
      place()
      const moved = Math.abs(lastPhoto.x - previous.x) + Math.abs(lastPhoto.y - previous.y) + Math.abs(lastPhoto.w - previous.w)
      previous = lastPhoto
      frame += 1
      if (moved > 0.05 && frame < 60) {
        settling = { stop: () => cancelAnimationFrame(handle) }
        handle = requestAnimationFrame(step)
        return
      }
      dropGhost()
      onLanded()
    }
    let handle = requestAnimationFrame(step)
    settling = { stop: () => cancelAnimationFrame(handle) }
  }

  setPhotoVisible(false)
  setSourceVisible(false)
  addGhost()
  place()
  flyTo(1, () => setPhotoVisible(true))

  return {
    grab() {
      if (closing || !ghost) return
      dropGhost()
      progress = 1
      setPhotoVisible(true)
    },
    close() {
      if (closing) return
      closing = true
      const stillInView = !photo.isConnected || rectOf(photo).y >= rectOf(panel).y - photoInViewTolerance
      if (!stillInView) {
        dropGhost()
        setPhotoVisible(true)
        setSourceVisible(true)
        return
      }
      setPhotoVisible(false)
      if (!ghost) {
        progress = 1
        addGhost()
      }
      place()
      flyTo(0, () => setSourceVisible(true))
    },
    abort() {
      if (closing) return
      dropGhost()
      setPhotoVisible(true)
      setSourceVisible(true)
    },
  }
}

const root = () => document.documentElement

const pushBackFade = 0.25
const pushBackLift = 14
const pushBackShrink = 0.08
const layerReleaseDelay = 500

const layerTimers = new WeakMap<HTMLElement, number>()

const holdLayer = (element: HTMLElement) => {
  window.clearTimeout(layerTimers.get(element))
  element.style.willChange = "transform"
}

const releaseLayer = (element: HTMLElement, delay = layerReleaseDelay) => {
  window.clearTimeout(layerTimers.get(element))
  layerTimers.set(
    element,
    window.setTimeout(() => {
      element.style.willChange = ""
    }, delay),
  )
}

type PushBackLayers = { screens: HTMLElement[]; dims: HTMLElement[] }

const findPushBackLayers = (): PushBackLayers => ({
  screens: Array.from(document.querySelectorAll<HTMLElement>("[data-slot=sheet-push-back-screen]")),
  dims: Array.from(document.querySelectorAll<HTMLElement>("[data-slot=sheet-push-back-dim]")),
})

const setPushBackActive = (active: boolean) => root().toggleAttribute("data-sheet-open", active)

const pushBackTransform = (progress: number) => `translateY(${progress * pushBackLift}px) scale(${1 - progress * pushBackShrink})`

const writePushBack = ({ screens, dims }: PushBackLayers, progress: number) => {
  const transform = pushBackTransform(progress)
  const opacity = String(progress * pushBackFade)
  for (const screen of screens) screen.style.transform = transform
  for (const dim of dims) dim.style.opacity = opacity
}

const freezePushBack = ({ screens, dims }: PushBackLayers) => {
  for (const element of [...screens, ...dims]) {
    holdLayer(element)
    element.style.transition = "none"
  }
}

const unwindPushBack = (layers: PushBackLayers, radiusTransition = "") => {
  for (const screen of layers.screens) {
    screen.style.transition = radiusTransition
    screen.style.borderRadius = "0px"
  }
  for (const dim of layers.dims) dim.style.transition = ""
  writePushBack(layers, 0)
}

const clearPushBack = ({ screens, dims }: PushBackLayers) => {
  for (const screen of screens) {
    screen.style.transition = ""
    screen.style.transform = ""
    screen.style.borderRadius = ""
    releaseLayer(screen)
  }
  for (const dim of dims) {
    dim.style.transition = ""
    dim.style.opacity = ""
    releaseLayer(dim)
  }
}

const resistPullUp = (offset: number) => (offset >= 0 ? offset : -Math.sqrt(-offset) * pullUpResistance)

const reducedMotionQuery = "(prefers-reduced-motion: reduce)"
const compactQuery = "(max-width: 639.98px)"

function growTarget(origin: HTMLElement | null | undefined) {
  if (!origin?.isConnected || origin.closest("[inert]")) return null
  if (window.matchMedia(reducedMotionQuery).matches) return null
  const rect = unscaledRect(origin)
  const visible = rect.width > 0 && rect.height > 0 && rect.bottom > 0 && rect.right > 0 && rect.top < window.innerHeight && rect.left < window.innerWidth
  return visible ? rect : null
}

function unscaledRect(element: HTMLElement) {
  const rect = element.getBoundingClientRect()
  const screen = element.closest<HTMLElement>("[data-slot=sheet-push-back-screen]")
  if (!screen) return rect
  const matrix = new DOMMatrix(getComputedStyle(screen).transform)
  const scale = matrix.a || 1
  if (Math.abs(scale - 1) < 0.001 && Math.abs(matrix.f) < 0.01) return rect
  const frame = screen.getBoundingClientRect()
  const centerX = frame.left + frame.width / 2
  const screenTop = frame.top
  const left = centerX + (rect.left - centerX) / scale
  const right = centerX + (rect.right - centerX) / scale
  const top = screenTop - matrix.f + (rect.top - screenTop) / scale
  const bottom = screenTop - matrix.f + (rect.bottom - screenTop) / scale
  return new DOMRect(left, top, right - left, bottom - top)
}

function triggerCorners(origin: HTMLElement, rect: DOMRect) {
  const capsuleRadius = Math.min(rect.width, rect.height) / 2
  const radius = Math.min(Number.parseFloat(getComputedStyle(origin).borderTopLeftRadius) || 0, capsuleRadius)
  return cornersOf([radius], radius < capsuleRadius && isSquircle(origin))
}

function rowCorners(row: HTMLElement, rect: DOMRect) {
  const own = Number.parseFloat(getComputedStyle(row).borderTopLeftRadius) || 0
  let clip = row.parentElement
  while (clip && clip !== document.body) {
    const style = getComputedStyle(clip)
    const radius = Number.parseFloat(style.borderTopLeftRadius) || 0
    if (radius > 0 && style.overflow !== "visible") {
      const frame = unscaledRect(clip)
      const top = rect.top - frame.top < 1 ? radius : own
      const bottom = frame.bottom - rect.bottom < 1 ? radius : own
      return cornersOf([top, top, bottom, bottom], isSquircle(clip))
    }
    clip = clip.parentElement
  }
  return cornersOf([own], isSquircle(row))
}

function surfaceColor(origin: HTMLElement, inherit: boolean) {
  let element: HTMLElement | null = origin
  while (element) {
    const color = getComputedStyle(element).backgroundColor
    if (isVisibleColor(color)) return color
    if (!inherit) return null
    element = element.parentElement
  }
  return null
}

function applyMorph(shell: HTMLElement, origin: MorphOrigin | null | undefined) {
  const element = origin?.element
  const target = growTarget(element)
  if (!target || !element) {
    shell.dataset.morph = "fade"
    return
  }
  const box = shell.getBoundingClientRect()
  shell.style.setProperty("--morph-top", `${target.top - box.top}px`)
  shell.style.setProperty("--morph-right", `${box.right - target.right}px`)
  shell.style.setProperty("--morph-bottom", `${box.bottom - target.bottom}px`)
  shell.style.setProperty("--morph-left", `${target.left - box.left}px`)
  const corners = origin.inheritColor ? rowCorners(element, target) : triggerCorners(element, target)
  shell.style.setProperty("--morph-radius-start", corners.radius)
  shell.style.setProperty("--morph-clip-start", corners.clip)
  shell.style.setProperty("--morph-shape-start", corners.shape)
  const color = surfaceColor(element, origin.inheritColor)
  if (color) shell.style.setProperty("--morph-color-start", color)
  else shell.style.removeProperty("--morph-color-start")
  shell.dataset.morph = "grow"
}

function holdMorphInPlace(shell: HTMLElement) {
  for (const side of ["top", "right", "bottom", "left"]) shell.style.setProperty(`--morph-${side}`, "0px")
  shell.style.setProperty("--morph-radius-start", "var(--morph-radius-end)")
  shell.style.removeProperty("--morph-clip-start")
  shell.style.setProperty("--morph-shape-start", "squircle")
  shell.style.removeProperty("--morph-color-start")
  shell.dataset.held = ""
}

function useDialogMorph(findOrigin: (compact: boolean) => MorphOrigin | null) {
  const finder = useRef(findOrigin)
  finder.current = findOrigin
  return useCallback((shell: HTMLDivElement | null) => {
    if (!shell) return
    const compact = window.matchMedia(compactQuery)
    applyMorph(shell, finder.current(compact.matches))
    const popup = shell.querySelector('[role="dialog"], [role="alertdialog"]')
    if (!popup) return
    const observer = new MutationObserver(() => {
      if (popup.hasAttribute("data-ending-style") && !shell.hasAttribute("data-held")) applyMorph(shell, finder.current(compact.matches))
    })
    observer.observe(popup, { attributes: true, attributeFilter: ["data-ending-style"] })
    return () => observer.disconnect()
  }, [])
}

function useDragToDismiss(context: SheetContextValue | null) {
  const scrim = useRef<HTMLDivElement | null>(null)
  const contextRef = useRef(context)
  contextRef.current = context

  const scrimRef = useCallback((element: HTMLDivElement | null) => {
    scrim.current = element
  }, [])

  const panelRef = useCallback((panel: HTMLDivElement | null) => {
    if (!panel) return
    const compact = window.matchMedia(compactQuery)
    const reducedMotion = window.matchMedia(reducedMotionQuery)
    const pushBack = compact.matches ? findPushBackLayers() : { screens: [], dims: [] }
    let pointerId: number | null = null
    let startY = 0
    let offset = 0
    let height = 0
    let pendingY: number | null = null
    let paintFrame = 0
    let tracker = createVelocityTracker()
    let settling: Settle | null = null

    const mover = () => {
      const shell = panel.closest<HTMLElement>("[data-slot=dialog-shell]")
      return compact.matches && shell?.dataset.morph === "grow" ? shell : panel
    }

    const paint = (y: number) => {
      const progress = Math.min(1, Math.max(0, y / height))
      const moving = mover()
      moving.style.translate = `0 ${y}px`
      moving.style.setProperty("--sheet-lift", `${Math.max(0, -y)}px`)
      if (scrim.current) scrim.current.style.opacity = String(1 - progress)
      writePushBack(pushBack, 1 - progress)
    }

    const schedulePaint = (y: number) => {
      pendingY = y
      if (paintFrame) return
      paintFrame = requestAnimationFrame(() => {
        paintFrame = 0
        if (pendingY === null) return
        paint(pendingY)
        pendingY = null
      })
    }

    const cancelScheduledPaint = () => {
      cancelAnimationFrame(paintFrame)
      paintFrame = 0
      pendingY = null
    }

    const freezeStyles = () => {
      const moving = mover()
      holdLayer(moving)
      moving.style.transition = "none"
      if (scrim.current) scrim.current.style.transition = "none"
      freezePushBack(pushBack)
    }

    const reset = () => {
      cancelScheduledPaint()
      const moving = mover()
      moving.style.transition = ""
      moving.style.translate = ""
      moving.style.removeProperty("--sheet-lift")
      releaseLayer(moving)
      if (scrim.current) {
        scrim.current.style.transition = ""
        scrim.current.style.opacity = ""
      }
      clearPushBack(pushBack)
    }

    const close = () => {
      const shell = panel.closest<HTMLElement>("[data-slot=dialog-shell]")
      if (shell && mover() === shell) holdMorphInPlace(shell)
      const actions = contextRef.current?.actions.current
      if (actions) actions.close()
      else reset()
    }

    if (contextRef.current)
      contextRef.current.onClosed.current = () => {
        reset()
        setPushBackActive(false)
      }

    const startFlight = () => {
      if (reducedMotion.matches) return null
      const photo = panel.querySelector<HTMLElement>("[data-slot=sheet-photo]")
      const source = findPhotoSource(contextRef.current?.photoSource?.current ?? contextRef.current?.trigger?.current)
      if (!photo || !source) return null
      const loaded = (image: HTMLImageElement | null | undefined) => (image?.complete && image.naturalWidth > 0 ? image : null)
      const image = loaded(photo.querySelector("img")) ?? loaded(source instanceof HTMLImageElement ? source : source.querySelector("img"))
      return image ? startPhotoFlight(panel, source, photo, image) : null
    }
    let flight: PhotoFlight | null = null
    let flightStarted = false
    const waitingPhoto = reducedMotion.matches ? null : panel.querySelector<HTMLElement>("[data-slot=sheet-photo]")
    if (waitingPhoto) waitingPhoto.style.visibility = "hidden"
    const releaseWaitingPhoto = () => {
      if (waitingPhoto && !flight) waitingPhoto.style.visibility = ""
    }
    const beginFlight = () => {
      flightStarted = true
      if (!panel.hasAttribute("data-ending-style")) flight = startFlight()
      releaseWaitingPhoto()
    }
    const startingWatcher = new MutationObserver(() => {
      if (panel.hasAttribute("data-starting-style")) return
      startingWatcher.disconnect()
      beginFlight()
    })
    const flightFrame = requestAnimationFrame(() => {
      if (panel.hasAttribute("data-starting-style")) startingWatcher.observe(panel, { attributes: true, attributeFilter: ["data-starting-style"] })
      else beginFlight()
    })

    const pushBackWhileOpen = new MutationObserver(() => {
      if (!panel.hasAttribute("data-ending-style")) return
      flight?.close()
      if (panel.hasAttribute("data-dragging")) return
      holdLayer(panel)
      releaseLayer(panel, 400)
      unwindPushBack(pushBack)
    })
    pushBackWhileOpen.observe(panel, { attributes: true, attributeFilter: ["data-ending-style"] })
    if (compact.matches) {
      setPushBackActive(true)
      holdLayer(panel)
      releaseLayer(panel)
      for (const element of [...pushBack.screens, ...pushBack.dims]) {
        holdLayer(element)
        releaseLayer(element)
      }
    }

    const markScrollable = () => {
      panel.toggleAttribute("data-scrollable", panel.scrollHeight > panel.clientHeight + 1)
    }
    const sizeObserver = new ResizeObserver(markScrollable)
    sizeObserver.observe(panel)
    for (const child of Array.from(panel.children)) sizeObserver.observe(child)

    const onPointerDown = (event: PointerEvent) => {
      if (!compact.matches || !event.isPrimary || event.button !== 0) return
      if (panel.hasAttribute("data-ending-style")) return
      if (event.target instanceof Element && event.target.closest(dragIgnoredTargets)) return
      if (panel.scrollTop > 0) return
      settling?.stop()
      settling = null
      height = panel.offsetHeight
      const moving = mover()
      const visibleOffset = Math.max(0, moving.getBoundingClientRect().top - moving.offsetTop)
      offset = visibleOffset
      startY = event.clientY - visibleOffset
      tracker = createVelocityTracker()
      tracker.add(event.clientY)
      pointerId = event.pointerId
      flight?.grab()
      panel.setPointerCapture(event.pointerId)
      panel.setAttribute("data-dragging", "")
      freezeStyles()
      paint(visibleOffset)
    }

    const onPointerMove = (event: PointerEvent) => {
      if (event.pointerId !== pointerId) return
      tracker.add(event.clientY)
      offset = event.clientY - startY
      schedulePaint(resistPullUp(offset))
    }

    const onPointerEnd = (event: PointerEvent) => {
      if (event.pointerId !== pointerId) return
      pointerId = null
      cancelScheduledPaint()
      panel.removeAttribute("data-dragging")
      const velocity = tracker.velocity()
      const flungDown = velocity > flingSpeed
      const pulledFarEnough = offset > height / 3 && velocity > -flingSpeed
      const dismiss = event.type === "pointerup" && (flungDown || pulledFarEnough)
      const from = resistPullUp(offset)
      if (dismiss) {
        flight?.close()
        for (const screen of pushBack.screens) {
          screen.style.transition = "border-radius 250ms var(--pb-ease-out)"
          screen.style.borderRadius = "0px"
        }
      }
      if (reducedMotion.matches) {
        if (dismiss) {
          unwindPushBack(pushBack)
          close()
        } else {
          reset()
        }
        return
      }
      settling = settleSpring(
        from,
        dismiss ? height + 24 : 0,
        velocity,
        paint,
        () => {
          settling = null
          if (dismiss) close()
          else reset()
        },
        { stopPastTarget: dismiss },
      )
    }

    panel.addEventListener("pointerdown", onPointerDown)
    panel.addEventListener("pointermove", onPointerMove)
    panel.addEventListener("pointerup", onPointerEnd)
    panel.addEventListener("pointercancel", onPointerEnd)
    return () => {
      settling?.stop()
      if (!flightStarted) cancelAnimationFrame(flightFrame)
      startingWatcher.disconnect()
      releaseWaitingPhoto()
      flight?.abort()
      pushBackWhileOpen.disconnect()
      cancelScheduledPaint()
      clearPushBack(pushBack)
      setPushBackActive(false)
      sizeObserver.disconnect()
      panel.removeEventListener("pointerdown", onPointerDown)
      panel.removeEventListener("pointermove", onPointerMove)
      panel.removeEventListener("pointerup", onPointerEnd)
      panel.removeEventListener("pointercancel", onPointerEnd)
    }
  }, [])

  return { scrimRef, panelRef }
}
```
