Components
Drawer
A panel that slides in from an edge over a Black scrim, on the #262626 overlay surface: from the bottom with the brand corner on its top edge and a grab handle, or from the left or right at full height. The body's edges fade while there is more to scroll.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add drawer<script type="module" src="/spyglass-ds/elements/drawer.js"></script>Usage
A choice or a short list on a phone (a format, a sort, the pages), where a dropdown would be cramped. The scrim, Escape and the close button close it.
Never
- A long form: use a page
- A shadow on its edge: the hairline sets it apart
- Corners on the edge it slides from
Props
The web component takes the same as attributes or properties (<spyglass-drawer>); title is heading there.
<Drawer>
| Prop | Type | Default |
|---|---|---|
title | string The title, and the panel's name. | |
description | string A line under the title. | |
side | 'bottom' | 'left' | 'right' The edge it comes from. | 'bottom' |
open | boolean | |
defaultOpen | boolean | false |
onOpenChange | (open: boolean) => void | |
children | ReactNode | ((close: () => void) => ReactNode) |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useState } from 'react'
import { Check, SlidersHorizontal } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { Drawer } from '@/react/components/ui/Drawer'
// A choice on a phone, from the bottom edge: which format to search. The rows are 44px to land a thumb on.
const formats = ['All formats', 'Video', 'Image', 'Carousel', 'UGC']
export default function Format() {
const [open, setOpen] = useState(false)
const [format, setFormat] = useState('All formats')
return (
<div className="flex min-h-72 items-center justify-center">
<Button variant="secondary" onClick={() => setOpen(true)}><SlidersHorizontal size={16} strokeWidth={1.5} aria-hidden="true" />{format}</Button>
<Drawer open={open} onOpenChange={setOpen} title="Format" description="Search one format, or all of them.">
{(close) => (
<ul className="flex flex-col gap-1">
{formats.map((f) => (
<li key={f}>
<button type="button" aria-pressed={format === f} data-autofocus={format === f || undefined} className="flex h-11 w-full cursor-pointer items-center gap-3 rounded-ds-sm px-3 text-left type-body text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4" onClick={() => { setFormat(f); close() }}>
<span className="min-w-0 flex-1">{f}</span>
{format === f && <Check size={16} strokeWidth={1.5} aria-hidden="true" />}
</button>
</li>
))}
</ul>
)}
</Drawer>
</div>
)
}<!-- A choice on a phone, from the bottom edge: which format to search. The rows are 44px to land a thumb on. -->
<div class="flex min-h-72 items-center justify-center">
<spyglass-button id="format-open" variant="secondary"><i data-lucide="sliders-horizontal" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i><span id="format-current">All formats</span></spyglass-button>
<spyglass-drawer id="format-drawer" heading="Format" description="Search one format, or all of them.">
<ul class="flex flex-col gap-1">
<li><button type="button" aria-pressed="true" data-autofocus data-format="All formats" class="flex h-11 w-full cursor-pointer items-center gap-3 rounded-ds-sm px-3 text-left type-body text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4"><span class="min-w-0 flex-1">All formats</span><span data-check class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></span></button></li>
<li><button type="button" aria-pressed="false" data-format="Video" class="flex h-11 w-full cursor-pointer items-center gap-3 rounded-ds-sm px-3 text-left type-body text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4"><span class="min-w-0 flex-1">Video</span><span data-check hidden class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></span></button></li>
<li><button type="button" aria-pressed="false" data-format="Image" class="flex h-11 w-full cursor-pointer items-center gap-3 rounded-ds-sm px-3 text-left type-body text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4"><span class="min-w-0 flex-1">Image</span><span data-check hidden class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></span></button></li>
<li><button type="button" aria-pressed="false" data-format="Carousel" class="flex h-11 w-full cursor-pointer items-center gap-3 rounded-ds-sm px-3 text-left type-body text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4"><span class="min-w-0 flex-1">Carousel</span><span data-check hidden class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></span></button></li>
<li><button type="button" aria-pressed="false" data-format="UGC" class="flex h-11 w-full cursor-pointer items-center gap-3 rounded-ds-sm px-3 text-left type-body text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4"><span class="min-w-0 flex-1">UGC</span><span data-check hidden class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></span></button></li>
</ul>
</spyglass-drawer>
</div>
<script type="module">
const drawer = document.getElementById('format-drawer')
document.getElementById('format-open').addEventListener('click', () => { drawer.open = true })
for (const b of drawer.querySelectorAll('[data-format]')) {
b.addEventListener('click', () => {
for (const o of drawer.querySelectorAll('[data-format]')) {
const on = o === b
o.setAttribute('aria-pressed', String(on))
o.toggleAttribute('data-autofocus', on)
o.querySelector('[data-check]').hidden = !on
}
document.getElementById('format-current').textContent = b.dataset.format
drawer.close()
})
}
</script>'use client'
import { useState } from 'react'
import { Bookmark, Building2, Menu, Search, Settings } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { Drawer } from '@/react/components/ui/Drawer'
// Navigation on a phone: the menu button slides the pages in from the left. Pick one, press the scrim or Escape to close.
const pages = [
{ label: 'Search', icon: Search },
{ label: 'Boards', icon: Bookmark },
{ label: 'Brands', icon: Building2 },
{ label: 'Settings', icon: Settings },
]
export default function Navigation() {
const [open, setOpen] = useState(false)
const [page, setPage] = useState('Search')
return (
<div className="flex min-h-72 flex-col items-center justify-center gap-3">
<Button variant="secondary" icon aria-label="Open menu" onClick={() => setOpen(true)}><Menu size={16} strokeWidth={1.5} aria-hidden="true" /></Button>
<p className="type-caption text-fg-muted" aria-live="polite">On {page}.</p>
<Drawer open={open} onOpenChange={setOpen} title="Spyglass" side="left">
<nav className="flex flex-col gap-1" aria-label="Pages">
{pages.map(({ label, icon: Icon }) => (
<a key={label} href="#" aria-current={page === label ? 'page' : undefined} className="flex h-10 items-center gap-3 rounded-ds-sm px-3 type-ui text-fg-soft outline-none transition-[background-color,color] duration-160 ease-standard hover:bg-ds-neutral-4 hover:text-fg focus-visible:bg-ds-neutral-4 aria-[current=page]:bg-ds-neutral-4 aria-[current=page]:text-fg" onClick={(e) => { e.preventDefault(); setPage(label); setOpen(false) }}>
<Icon size={16} strokeWidth={1.5} aria-hidden="true" />{label}
</a>
))}
</nav>
</Drawer>
</div>
)
}<!-- Navigation on a phone: the menu button slides the pages in from the left. Pick one, press the scrim or Escape to close. -->
<div class="flex min-h-72 flex-col items-center justify-center gap-3">
<spyglass-button id="nav-open" variant="secondary" icon aria-label="Open menu"><i data-lucide="menu" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></spyglass-button>
<p id="nav-page" class="type-caption text-fg-muted" aria-live="polite">On Search.</p>
<spyglass-drawer id="nav-drawer" heading="Spyglass" side="left">
<nav class="flex flex-col gap-1" aria-label="Pages">
<a href="#" aria-current="page" data-page="Search" class="flex h-10 items-center gap-3 rounded-ds-sm px-3 type-ui text-fg-soft outline-none transition-[background-color,color] duration-160 ease-standard hover:bg-ds-neutral-4 hover:text-fg focus-visible:bg-ds-neutral-4 aria-[current=page]:bg-ds-neutral-4 aria-[current=page]:text-fg"><i data-lucide="search" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Search</a>
<a href="#" data-page="Boards" class="flex h-10 items-center gap-3 rounded-ds-sm px-3 type-ui text-fg-soft outline-none transition-[background-color,color] duration-160 ease-standard hover:bg-ds-neutral-4 hover:text-fg focus-visible:bg-ds-neutral-4 aria-[current=page]:bg-ds-neutral-4 aria-[current=page]:text-fg"><i data-lucide="bookmark" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Boards</a>
<a href="#" data-page="Brands" class="flex h-10 items-center gap-3 rounded-ds-sm px-3 type-ui text-fg-soft outline-none transition-[background-color,color] duration-160 ease-standard hover:bg-ds-neutral-4 hover:text-fg focus-visible:bg-ds-neutral-4 aria-[current=page]:bg-ds-neutral-4 aria-[current=page]:text-fg"><i data-lucide="building-2" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Brands</a>
<a href="#" data-page="Settings" class="flex h-10 items-center gap-3 rounded-ds-sm px-3 type-ui text-fg-soft outline-none transition-[background-color,color] duration-160 ease-standard hover:bg-ds-neutral-4 hover:text-fg focus-visible:bg-ds-neutral-4 aria-[current=page]:bg-ds-neutral-4 aria-[current=page]:text-fg"><i data-lucide="settings" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Settings</a>
</nav>
</spyglass-drawer>
</div>
<script type="module">
const drawer = document.getElementById('nav-drawer')
document.getElementById('nav-open').addEventListener('click', () => { drawer.open = true })
for (const a of drawer.querySelectorAll('[data-page]')) {
a.addEventListener('click', (e) => {
e.preventDefault()
for (const o of drawer.querySelectorAll('[data-page]')) o.toggleAttribute('aria-current', false)
a.setAttribute('aria-current', 'page')
document.getElementById('nav-page').textContent = `On ${a.dataset.page}.`
drawer.open = false
})
}
</script>Source
'use client'
import { X } from 'lucide-react'
import { useRef, type ReactNode } from 'react'
import { Button } from '@/react/components/ui/Button'
import { useControllable } from '@/react/hooks/useControllable'
import { useSheet } from '@/react/hooks/useSheet'
// shadcn's drawer in the brand: a panel that slides in from an edge over a Black scrim, on the #262626 overlay surface
// with a neutral hairline on its inner edge. `bottom` (the default) is the screen's width and up to 85% of its
// height, with the 8px corner on its top edge only and a grab handle; `left` and `right` are min(320px, 85vw) and full
// height. A Funnel Display title, an optional line under it and a ghost close button head it; the children are the
// body. It slides its own size in over 360ms on the drawer curve and out in 240ms; the scrim fades with it. A press on
// the scrim or Escape (at once, keyboard actions don't animate) closes it, and focus returns to what opened it.
// Reduced motion fades instead of sliding. `open` with `onOpenChange`; children may be a function of `close`.
export interface DrawerProps {
/** The title, and the panel's name. */
title: string
/** A line under the title. */
description?: string
/** The edge it comes from. */
side?: 'bottom' | 'left' | 'right'
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
children?: ReactNode | ((close: () => void) => ReactNode)
}
export function Drawer({ title, description, side = 'bottom', open: given, defaultOpen = false, onOpenChange, children }: DrawerProps) {
const [open, setOpen] = useControllable(given, defaultOpen, onOpenChange)
const dialog = useRef<HTMLDialogElement | null>(null)
const { shown, onCancel, onClick } = useSheet(dialog, open, setOpen)
const close = () => setOpen(false)
return (
<dialog data-ds="drawer" ref={dialog} className="ds-drawer" data-side={side} data-shown={shown || undefined} aria-label={title} tabIndex={-1} onCancel={onCancel} onClick={onClick}>
<style href="ds-drawer" precedence="ds">{css}</style>
{side === 'bottom' && <div className="mx-auto mt-3 h-1 w-10 shrink-0 rounded-full bg-ds-neutral-5" aria-hidden="true" />}
<div className="flex shrink-0 items-start gap-4 pt-4 pr-4 pb-2 pl-6">
<div className="flex min-w-0 flex-1 flex-col gap-1.5 pt-1.5">
<h2 className="type-heading-4">{title}</h2>
{description && <p className="type-ui text-fg-muted">{description}</p>}
</div>
<Button variant="ghost" size="sm" icon aria-label="Close" onClick={close}><X size={16} strokeWidth={1.5} aria-hidden="true" /></Button>
</div>
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-3 pb-6 fade-y" data-sheet-body="">
{typeof children === 'function' ? children(close) : children}
</div>
</dialog>
)
}
export default Drawer
const css = `
.ds-drawer { position: fixed; max-width: none; max-height: none; margin: 0; padding: 0; border: 0 solid var(--ds-color-edge); background: var(--ds-color-surface-raised); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); transition: transform var(--ds-duration-enter) var(--ds-easing-drawer); }
.ds-drawer[open] { display: flex; flex-direction: column; }
.ds-drawer:focus { outline: none; }
.ds-drawer[data-side="bottom"] { inset: auto 0 0; width: 100vw; max-height: 85dvh; border-top-width: var(--ds-border-hairline); border-radius: var(--ds-radius-container) var(--ds-radius-container) 0 0; transform: translateY(100%); padding-bottom: env(safe-area-inset-bottom); }
.ds-drawer[data-side="left"] { inset: 0 auto 0 0; width: min(320px, 85vw); height: 100dvh; border-right-width: var(--ds-border-hairline); transform: translateX(-100%); }
.ds-drawer[data-side="right"] { inset: 0 0 0 auto; width: min(320px, 85vw); height: 100dvh; border-left-width: var(--ds-border-hairline); transform: translateX(100%); }
.ds-drawer[data-shown] { transform: none; transition-duration: var(--ds-duration-entrance); }
.ds-drawer::backdrop { background: var(--ds-color-scrim); opacity: 0; transition: opacity var(--ds-duration-enter) var(--ds-easing-drawer); }
.ds-drawer[data-shown]::backdrop { opacity: 1; transition-duration: var(--ds-duration-entrance); }
@media (prefers-reduced-motion: reduce) {
.ds-drawer, .ds-drawer[data-side] { transform: none; opacity: 0; transition: opacity var(--ds-duration-enter) var(--ds-easing-out); }
.ds-drawer[data-shown] { opacity: 1; }
}
`'use client'
import { useCallback, useRef, useState } from 'react'
// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
const [inner, setInner] = useState<T>(defaultValue)
const controlled = value !== undefined
const current = controlled ? value : inner
const ref = useRef(onChange)
ref.current = onChange
const set = useCallback((next: T) => {
if (!controlled) setInner(next)
ref.current?.(next)
}, [controlled])
return [current, set] as const
}'use client'
import { useEffect, useRef, useState, type RefObject } from 'react'
import { firstFocusable } from '@/react/hooks/usePopover'
/**
* A native modal dialog that slides (Sheet, Drawer): showModal keeps focus inside and the page inert; the panel and its
* scrim come in on `data-shown` and leave on its removal, closing once the exit transition has run (read from CSS, so
* reduced motion and the tokens decide). Escape closes at once (keyboard actions don't animate); the scrim closes it;
* focus returns to what opened it. Focus starts on the first control in `[data-autofocus]` or the body, else the panel.
* `open` and `setOpen` are the component's controllable open state (Vue's v-model:open).
*/
export function useSheet(dialog: RefObject<HTMLDialogElement | null>, open: boolean, setOpen: (open: boolean) => void, options: { dismissable?: () => boolean } = {}) {
const [shown, setShownState] = useState(false)
const isShown = useRef(false)
const setShown = (v: boolean) => {
isShown.current = v
setShownState(v)
}
const returnTo = useRef<HTMLElement | null>(null)
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const exiting = useRef(false)
function exitMs(el: HTMLElement) {
const parts = getComputedStyle(el).transitionDuration.split(',').map(s => Number.parseFloat(s) * (s.trim().endsWith('ms') ? 1 : 1000))
return Math.max(0, ...parts.filter(n => !Number.isNaN(n)))
}
async function show() {
const d = dialog.current
if (!d || d.open) return
clearTimeout(timer.current)
returnTo.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
d.showModal()
const start = d.querySelector<HTMLElement>('[data-autofocus]') ?? firstFocusable(d.querySelector<HTMLElement>('[data-sheet-body]'))
;(start ?? d).focus({ preventScroll: true })
// One frame at the closed state, so the transition has somewhere to start.
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))
setShown(true)
}
function finish() {
dialog.current?.close()
returnTo.current?.focus({ preventScroll: true })
returnTo.current = null
}
function hide(instant = false) {
const d = dialog.current
if (!d?.open) return
if (instant) {
setShown(false)
return finish()
}
// ds-latency: the dialog stays in the top layer until its exit has played (timed once the panel has re-rendered
// without data-shown, as Vue's nextTick, so its exit duration is the one read).
if (!isShown.current) timer.current = setTimeout(finish, exitMs(d))
else {
exiting.current = true
setShown(false)
}
}
useEffect(() => {
const d = dialog.current
if (shown || !exiting.current || !d) return
exiting.current = false
timer.current = setTimeout(finish, exitMs(d))
}, [shown]) // eslint-disable-line react-hooks/exhaustive-deps
// Vue's watch(open) and onMounted: show when it opens (or starts open), hide when it closes.
const mounted = useRef(false)
useEffect(() => {
if (!mounted.current) {
mounted.current = true
if (open) void show()
return
}
if (open) void show()
else hide()
}, [open]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => () => clearTimeout(timer.current), [])
/** Escape: at once, no exit motion. */
function onCancel(event: { preventDefault: () => void }) {
event.preventDefault()
if (options.dismissable && !options.dismissable()) return
setOpen(false)
hide(true)
}
/** A press on the scrim lands on the dialog element itself. */
function onClick(event: { target: EventTarget | null }) {
if (event.target === dialog.current && (!options.dismissable || options.dismissable())) setOpen(false)
}
return { shown, onCancel, onClick, hide }
}import { html, nothing, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { X } from 'lucide'
import { DsElement, define } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import { SheetController } from '@/elements/controllers/sheet'
import '@/elements/components/ui/button'
import styles from 'virtual:tw'
// Drawer.tsx as <spyglass-drawer>: a panel that slides in from an edge over a Black scrim, on the #262626 overlay
// surface with a neutral hairline on its inner edge. `bottom` (the default) is the screen's width and up to 85% of its
// height, with the 8px corner on its top edge and a grab handle; `left` and `right` are min(320px, 85vw) and full
// height. A Funnel Display heading, an optional line and a ghost close button head it. It slides in over 360ms on the
// drawer curve and out in 240ms. A press on the scrim or Escape (at once) closes it, and focus returns to what opened
// it. React's `open` with `onOpenChange` is the reflected `open` attribute with an `open-change` event; React's
// `title` is `heading`; React's `close` (children as a function) is the element's close().
/**
* @summary A panel that slides in from an edge over a Black scrim.
* @slot - The panel's body.
* @fires open-change - It opened or closed (detail.value; read `open`).
*/
export class Drawer extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { heading: {}, description: {}, side: { reflect: true }, open: { type: Boolean, reflect: true } }
/** The title, and the panel's name (React's `title`). */
heading = ''
/** A line under the heading. */
description?: string
/** The edge it comes from. */
side: 'bottom' | 'left' | 'right' = 'bottom'
/** Whether it is showing. */
open = false
private sheet = new SheetController(this, () => this.renderRoot.querySelector('dialog'), (open) => this.setOpen(open))
/** Closes it, with its exit. */
close() {
this.setOpen(false)
}
private setOpen(open: boolean) {
if (this.open === open) return
this.open = open
this.emit('open-change', { value: open })
}
// Show when it opens (or starts open), hide when it closes.
protected updated(changed: PropertyValues) {
super.updated(changed)
if (!changed.has('open')) return
if (this.open) void this.sheet.show()
else if (changed.get('open') !== undefined) void this.sheet.hide()
}
render() {
return html`<dialog data-ds="drawer" class="ds-drawer" data-side=${this.side} data-shown=${ifDefined(this.sheet.shown ? 'true' : undefined)} aria-label=${this.heading} tabindex="-1" @cancel=${this.sheet.onCancel} @click=${this.sheet.onClick}>
${this.side === 'bottom' ? html`<div class="mx-auto mt-3 h-1 w-10 shrink-0 rounded-full bg-ds-neutral-5" aria-hidden="true"></div>` : nothing}
<div class="flex shrink-0 items-start gap-4 pt-4 pr-4 pb-2 pl-6">
<div class="flex min-w-0 flex-1 flex-col gap-1.5 pt-1.5">
<h2 class="type-heading-4">${this.heading}</h2>
${this.description ? html`<p class="type-ui text-fg-muted">${this.description}</p>` : nothing}
</div>
<spyglass-button variant="ghost" size="sm" icon aria-label="Close" @click=${() => this.close()}>${icon(X, 'x', { size: 16, strokeWidth: 1.5, attrs: { 'aria-hidden': 'true' } })}</spyglass-button>
</div>
<div class="flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-3 pb-6 fade-y" data-sheet-body><slot></slot></div>
</dialog>`
}
}
define('drawer', Drawer)/* Drawer.tsx's styles. */
.ds-drawer { position: fixed; max-width: none; max-height: none; margin: 0; padding: 0; border: 0 solid var(--ds-color-edge); background: var(--ds-color-surface-raised); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); transition: transform var(--ds-duration-enter) var(--ds-easing-drawer); }
.ds-drawer[open] { display: flex; flex-direction: column; }
.ds-drawer:focus { outline: none; }
.ds-drawer[data-side="bottom"] { inset: auto 0 0; width: 100vw; max-height: 85dvh; border-top-width: var(--ds-border-hairline); border-radius: var(--ds-radius-container) var(--ds-radius-container) 0 0; transform: translateY(100%); padding-bottom: env(safe-area-inset-bottom); }
.ds-drawer[data-side="left"] { inset: 0 auto 0 0; width: min(320px, 85vw); height: 100dvh; border-right-width: var(--ds-border-hairline); transform: translateX(-100%); }
.ds-drawer[data-side="right"] { inset: 0 0 0 auto; width: min(320px, 85vw); height: 100dvh; border-left-width: var(--ds-border-hairline); transform: translateX(100%); }
.ds-drawer[data-shown] { transform: none; transition-duration: var(--ds-duration-entrance); }
.ds-drawer::backdrop { background: var(--ds-color-scrim); opacity: 0; transition: opacity var(--ds-duration-enter) var(--ds-easing-drawer); }
.ds-drawer[data-shown]::backdrop { opacity: 1; transition-duration: var(--ds-duration-entrance); }
@media (prefers-reduced-motion: reduce) {
.ds-drawer, .ds-drawer[data-side] { transform: none; opacity: 0; transition: opacity var(--ds-duration-enter) var(--ds-easing-out); }
.ds-drawer[data-shown] { opacity: 1; }
}import type { ReactiveController, ReactiveControllerHost } from 'lit'
import { firstFocusable } from '@/elements/lib/popover'
/**
* useSheet as a Lit controller: a native modal dialog that slides (Sheet, Drawer): showModal keeps focus inside and
* the page inert; the panel and its scrim come in on `data-shown` and leave on its removal, closing once the exit
* transition has run (read from CSS, so reduced motion and the tokens decide). Escape closes at once (keyboard actions
* don't animate); the scrim closes it; focus returns to what opened it, through shadow roots. Focus starts on the first
* control in `[data-autofocus]` (in the page's content or the panel) or the body, else the panel. The element calls
* show() and hide() when its `open` changes and passes `setOpen` for Escape and the scrim.
*/
export class SheetController implements ReactiveController {
shown = false
private returnTo: HTMLElement | null = null
private timer?: ReturnType<typeof setTimeout>
constructor(
private host: ReactiveControllerHost & HTMLElement,
private dialog: () => HTMLDialogElement | null,
private setOpen: (open: boolean) => void,
private options: { dismissable?: () => boolean } = {},
) {
host.addController(this)
}
hostDisconnected() {
clearTimeout(this.timer)
}
private exitMs(el: HTMLElement) {
const parts = getComputedStyle(el).transitionDuration.split(',').map((s) => Number.parseFloat(s) * (s.trim().endsWith('ms') ? 1 : 1000))
return Math.max(0, ...parts.filter((n) => !Number.isNaN(n)))
}
private setShown(v: boolean) {
this.shown = v
this.host.requestUpdate()
}
async show() {
const d = this.dialog()
if (!d || d.open) return
clearTimeout(this.timer)
// The focused element itself, inside shadow roots, not the host it sits in.
let active = document.activeElement as HTMLElement | null
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement as HTMLElement
this.returnTo = active
d.showModal()
const start = this.host.querySelector<HTMLElement>('[data-autofocus]') ?? d.querySelector<HTMLElement>('[data-autofocus]') ?? firstFocusable(d.querySelector<HTMLElement>('[data-sheet-body]'))
;(start ?? d).focus({ preventScroll: true })
// One frame at the closed state, so the transition has somewhere to start.
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))
this.setShown(true)
}
private finish() {
this.dialog()?.close()
this.returnTo?.focus({ preventScroll: true })
this.returnTo = null
}
async hide(instant = false) {
const d = this.dialog()
if (!d?.open) return
this.setShown(false)
if (instant) return this.finish()
await this.host.updateComplete
// ds-latency: the dialog stays in the top layer until its exit has played.
this.timer = setTimeout(() => this.finish(), this.exitMs(d))
}
/** Escape: at once, no exit motion. */
onCancel = (event: Event) => {
event.preventDefault()
if (this.options.dismissable && !this.options.dismissable()) return
this.setOpen(false)
void this.hide(true)
}
/** A press on the scrim lands on the dialog element itself. */
onClick = (event: MouseEvent) => {
if (event.target === this.dialog() && (!this.options.dismissable || this.options.dismissable())) this.setOpen(false)
}
}Reference: Derived from the guidelines: the #262626 card fill on Black, neutral hairlines, the 10px canvas corner (8px here), Funnel Display titles, 44px touch rows. shadcn's drawer for anatomy and behavior (no drag to dismiss yet)..