Components
Sheet
A modal panel at an edge of the screen: the card's #262626 fill with a hairline on its inner edge, a Funnel Display title, the body scrolling on its own and buttons at the foot. It slides in on the drawer curve; Escape closes it at once. 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 sheet<script type="module" src="/spyglass-ds/elements/sheet.js"></script>Usage
Details, filters or settings beside what someone is doing: a search's filters, a brand's details. Right is the default; left, top and bottom when the layout asks for it.
Never
- A short question or a confirmation: use Dialog or Alert Dialog
- A shadow or a glow: the fill, the hairline and the scrim set it apart
- Two sheets open at once
Adds with it: popover packages lucide-react
Props
The web component takes the same as attributes or properties (<spyglass-sheet>); title is heading there.
<Sheet>
| Prop | Type | Default |
|---|---|---|
title | string The title, and the panel's name. | |
description | string A line under the title. | |
side | SheetSide The edge it comes from. | 'right' |
open | boolean Whether it is showing (with onOpenChange). | |
defaultOpen | boolean | false |
onOpenChange | (open: boolean) => void | |
foot | ReactNode Buttons at the foot. | |
children | ReactNode The body. |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useState } from 'react'
import { SlidersHorizontal } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { Input } from '@/react/components/ui/Input'
import { Sheet } from '@/react/components/ui/Sheet'
// A search's filters in a sheet at the right edge: two fields and the buttons at the foot. Escape, Close or the dimmed
// page closes it.
export default function Filters() {
const [open, setOpen] = useState(false)
return (
<div className="flex min-h-40 items-center justify-center">
<Button variant="secondary" onClick={() => setOpen(true)}><SlidersHorizontal size={16} strokeWidth={1.5} aria-hidden="true" />Filters</Button>
<Sheet
open={open}
onOpenChange={setOpen}
title="Filter creatives"
description="Narrow this search to the brands and dates you care about."
foot={(
<>
<Button variant="ghost" onClick={() => setOpen(false)}>Reset</Button>
<Button onClick={() => setOpen(false)}>Show results</Button>
</>
)}
>
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-2">
<label htmlFor="sheet-brand" className="type-label text-fg-soft">Brand</label>
<Input id="sheet-brand" name="brand" defaultValue="Acme Studio" />
</div>
<div className="flex flex-col gap-2">
<label htmlFor="sheet-days" className="type-label text-fg-soft">Running for at least</label>
<Input id="sheet-days" name="days" defaultValue="30 days" />
<p className="type-caption text-fg-muted">Ads that run longer are the ones that work.</p>
</div>
</div>
</Sheet>
</div>
)
}<!-- A search's filters in a sheet at the right edge: two fields and the buttons at the foot. Escape, Close or the
dimmed page closes it. -->
<div class="flex min-h-40 items-center justify-center">
<spyglass-button id="filters-open" variant="secondary"><i data-lucide="sliders-horizontal" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Filters</spyglass-button>
<spyglass-sheet id="filters-sheet" heading="Filter creatives" description="Narrow this search to the brands and dates you care about.">
<div class="flex flex-col gap-6">
<div class="flex flex-col gap-2">
<label for="sheet-brand" class="type-label text-fg-soft">Brand</label>
<spyglass-input id="sheet-brand" name="brand" value="Acme Studio" aria-label="Brand"></spyglass-input>
</div>
<div class="flex flex-col gap-2">
<label for="sheet-days" class="type-label text-fg-soft">Running for at least</label>
<spyglass-input id="sheet-days" name="days" value="30 days" aria-label="Running for at least"></spyglass-input>
<p class="type-caption text-fg-muted">Ads that run longer are the ones that work.</p>
</div>
</div>
<spyglass-button slot="foot" variant="ghost" data-close>Reset</spyglass-button>
<spyglass-button slot="foot" data-close>Show results</spyglass-button>
</spyglass-sheet>
</div>
<script type="module">
const sheet = document.getElementById('filters-sheet')
document.getElementById('filters-open').addEventListener('click', () => { sheet.open = true })
for (const b of sheet.querySelectorAll('[data-close]')) b.addEventListener('click', () => { sheet.open = false })
</script>'use client'
import { useState } from 'react'
import { Button } from '@/react/components/ui/Button'
import { Sheet, type SheetSide } from '@/react/components/ui/Sheet'
// The four edges a sheet comes from: right and left for details beside the page, top and bottom for a short row.
const sides: SheetSide[] = ['top', 'right', 'bottom', 'left']
export default function Sides() {
const [side, setSide] = useState<SheetSide | null>(null)
return (
<div className="flex min-h-40 flex-wrap items-center justify-center gap-2">
{sides.map((s) => <Button key={s} variant="secondary" onClick={() => setSide(s)}>{s[0].toUpperCase() + s.slice(1)}</Button>)}
{sides.map((s) => (
<Sheet key={s} side={s} open={side === s} onOpenChange={(o) => { if (!o) setSide(null) }} title="Acme Studio" description="128 active ads on Meta and TikTok, 14 new this week.">
<p className="type-ui text-fg-soft">Save the brand to a board to follow every new ad it launches.</p>
</Sheet>
))}
</div>
)
}<!-- The four edges a sheet comes from: right and left for details beside the page, top and bottom for a short row. -->
<div class="flex min-h-40 flex-wrap items-center justify-center gap-2">
<spyglass-button variant="secondary" data-side="top">Top</spyglass-button>
<spyglass-button variant="secondary" data-side="right">Right</spyglass-button>
<spyglass-button variant="secondary" data-side="bottom">Bottom</spyglass-button>
<spyglass-button variant="secondary" data-side="left">Left</spyglass-button>
<spyglass-sheet side="top" heading="Acme Studio" description="128 active ads on Meta and TikTok, 14 new this week."><p class="type-ui text-fg-soft">Save the brand to a board to follow every new ad it launches.</p></spyglass-sheet>
<spyglass-sheet side="right" heading="Acme Studio" description="128 active ads on Meta and TikTok, 14 new this week."><p class="type-ui text-fg-soft">Save the brand to a board to follow every new ad it launches.</p></spyglass-sheet>
<spyglass-sheet side="bottom" heading="Acme Studio" description="128 active ads on Meta and TikTok, 14 new this week."><p class="type-ui text-fg-soft">Save the brand to a board to follow every new ad it launches.</p></spyglass-sheet>
<spyglass-sheet side="left" heading="Acme Studio" description="128 active ads on Meta and TikTok, 14 new this week."><p class="type-ui text-fg-soft">Save the brand to a board to follow every new ad it launches.</p></spyglass-sheet>
</div>
<script type="module">
for (const b of document.querySelectorAll('spyglass-button[data-side]')) {
b.addEventListener('click', () => { document.querySelector(`spyglass-sheet[side="${b.dataset.side}"]`).open = true })
}
</script>Source
'use client'
import { X } from 'lucide-react'
import { useEffect, useRef, useState, type ReactNode, type RefObject } from 'react'
import { useControllable } from '@/react/hooks/useControllable'
import { firstFocusable } from '@/react/hooks/usePopover'
// A panel at an edge of the screen over the page, for details, filters or settings beside what someone is doing: the
// card's #262626 fill with a #666666 hairline on its inner edge, no shadow. 384px wide at the right (the default) or
// left, the screen on a phone; full width at the top or bottom. A Funnel Display title and a muted line, a close
// button, the body scrolling on its own, and buttons at the foot. It is modal: the page dims under the scrim and stays
// inert, focus stays inside. It slides in from its edge over 360ms on the drawer curve and leaves in 240ms; Escape
// closes it at once; focus returns to what opened it. Reduced motion fades it instead. `open` with `onOpenChange`.
export type SheetSide = 'right' | 'left' | 'top' | 'bottom'
export interface SheetProps {
/** The title, and the panel's name. */
title: string
/** A line under the title. */
description?: string
/** The edge it comes from. */
side?: SheetSide
/** Whether it is showing (with onOpenChange). */
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
/** Buttons at the foot. */
foot?: ReactNode
/** The body. */
children?: ReactNode
}
export function Sheet({ title, description, side = 'right', open: given, defaultOpen = false, onOpenChange, foot, children }: SheetProps) {
const [open, setOpen] = useControllable(given, defaultOpen, onOpenChange)
const dialog = useRef<HTMLDialogElement | null>(null)
const { shown, onCancel, onClick } = useSheet(dialog, open, setOpen)
return (
<dialog data-ds="sheet" ref={dialog} className="ds-sheet" data-side={side} data-shown={shown || undefined} aria-label={title} tabIndex={-1} onCancel={onCancel} onClick={onClick}>
<style href="ds-sheet" precedence="ds">{css}</style>
<div className="flex shrink-0 items-start gap-4 px-6 pt-6 pb-4">
<div className="flex min-w-0 flex-1 flex-col gap-2">
<h2 className="type-heading-4 text-fg">{title}</h2>
{description && <p className="type-ui text-fg-muted">{description}</p>}
</div>
<button type="button" className="-mt-1.5 -mr-2 inline-flex size-control-sm shrink-0 cursor-pointer items-center justify-center rounded-control text-fg-muted transition-[background-color,color] duration-160 ease-standard hover:bg-action-ghost-hover hover:text-fg max-md:size-control-touch" aria-label="Close" onClick={() => setOpen(false)}><X size={16} strokeWidth={1.5} aria-hidden="true" /></button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-6 pb-6 fade-y" data-sheet-body="">
{children}
</div>
{foot && <div className="flex shrink-0 justify-end gap-2 border-t border-edge px-6 py-4">{foot}</div>}
</dialog>
)
}
/**
* The sheet's native modal dialog: 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.
*/
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, 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
// 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 }
}
export default Sheet
const css = `
.ds-sheet { position: fixed; margin: 0; padding: 0; max-width: none; max-height: none; border: 0 solid var(--ds-color-edge-strong); 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), opacity var(--ds-duration-enter) var(--ds-easing-drawer); }
.ds-sheet[open] { display: flex; flex-direction: column; }
.ds-sheet:focus { outline: none; }
.ds-sheet[data-side="right"] { inset: 0 0 0 auto; width: min(24rem, 100vw); height: 100dvh; border-left-width: var(--ds-border-hairline); transform: translateX(100%); }
.ds-sheet[data-side="left"] { inset: 0 auto 0 0; width: min(24rem, 100vw); height: 100dvh; border-right-width: var(--ds-border-hairline); transform: translateX(-100%); }
.ds-sheet[data-side="top"] { inset: 0 0 auto 0; width: 100vw; max-height: 100dvh; border-bottom-width: var(--ds-border-hairline); transform: translateY(-100%); }
.ds-sheet[data-side="bottom"] { inset: auto 0 0 0; width: 100vw; max-height: 100dvh; border-top-width: var(--ds-border-hairline); transform: translateY(100%); }
.ds-sheet[data-shown] { transform: none; transition-duration: var(--ds-duration-entrance); }
.ds-sheet::backdrop { background: var(--ds-color-scrim); opacity: 0; transition: opacity var(--ds-duration-enter) var(--ds-easing-standard); }
.ds-sheet[data-shown]::backdrop { opacity: 1; transition-duration: var(--ds-duration-entrance); }
@media (prefers-reduced-motion: reduce) {
.ds-sheet[data-side] { transform: none; opacity: 0; }
.ds-sheet[data-side][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
}import { html, nothing, type PropertyValues, type ReactiveController, type ReactiveControllerHost } 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 { firstFocusable } from '@/elements/lib/popover'
import styles from 'virtual:tw'
// Sheet.tsx as <spyglass-sheet>: a panel at an edge of the screen over the page: the card's #262626 fill with a
// hairline on its inner edge, 384px at the right (the default) or left, full width at the top or bottom. A Funnel
// Display title and a muted line, a close button, the body scrolling on its own, buttons at the foot. It is modal: the
// page dims under the scrim and stays inert. It slides in over 360ms on the drawer curve and leaves in 240ms; Escape
// closes it at once; focus returns to what opened it. `open` (reflected) with `open-change`; React's `title` is
// `heading`.
export type SheetSide = 'right' | 'left' | 'top' | 'bottom'
/**
* @summary A modal panel at an edge of the screen.
* @slot - The body.
* @slot foot - Buttons at the foot.
* @fires open-change - It opened or closed (detail.value; read `open`).
*/
export class Sheet 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 title. */
description?: string
/** The edge it comes from. */
side: SheetSide = 'right'
/** Whether it is showing. */
open = false
private sheet = new SheetController(this, () => this.renderRoot.querySelector('dialog'), (open) => this.setOpen(open))
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() {
const side = ['right', 'left', 'top', 'bottom'].includes(this.side) ? this.side : 'right'
return html`<dialog data-ds="sheet" class="ds-sheet" data-side=${side} data-shown=${ifDefined(this.sheet.shown ? 'true' : undefined)} aria-label=${this.heading} tabindex="-1" @cancel=${this.sheet.onCancel} @click=${this.sheet.onClick}>
<div class="flex shrink-0 items-start gap-4 px-6 pt-6 pb-4">
<div class="flex min-w-0 flex-1 flex-col gap-2">
<h2 class="type-heading-4 text-fg">${this.heading}</h2>
${this.description ? html`<p class="type-ui text-fg-muted">${this.description}</p>` : nothing}
</div>
<button type="button" class="-mt-1.5 -mr-2 inline-flex size-control-sm shrink-0 cursor-pointer items-center justify-center rounded-control text-fg-muted transition-[background-color,color] duration-160 ease-standard hover:bg-action-ghost-hover hover:text-fg max-md:size-control-touch" aria-label="Close" @click=${() => this.setOpen(false)}>${icon(X, 'x', { size: 16, strokeWidth: 1.5 })}</button>
</div>
<div class="min-h-0 flex-1 overflow-y-auto overscroll-contain px-6 pb-6 fade-y" data-sheet-body>
<slot></slot>
</div>
${this.hasSlot('foot') ? html`<div class="flex shrink-0 justify-end gap-2 border-t border-edge px-6 py-4"><slot name="foot"></slot></div>` : nothing}
</dialog>`
}
}
/**
* The sheet's native modal dialog: 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.
*/
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)
}
}
define('sheet', Sheet).ds-sheet { position: fixed; margin: 0; padding: 0; max-width: none; max-height: none; border: 0 solid var(--ds-color-edge-strong); 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), opacity var(--ds-duration-enter) var(--ds-easing-drawer); }
.ds-sheet[open] { display: flex; flex-direction: column; }
.ds-sheet:focus { outline: none; }
.ds-sheet[data-side="right"] { inset: 0 0 0 auto; width: min(24rem, 100vw); height: 100dvh; border-left-width: var(--ds-border-hairline); transform: translateX(100%); }
.ds-sheet[data-side="left"] { inset: 0 auto 0 0; width: min(24rem, 100vw); height: 100dvh; border-right-width: var(--ds-border-hairline); transform: translateX(-100%); }
.ds-sheet[data-side="top"] { inset: 0 0 auto 0; width: 100vw; max-height: 100dvh; border-bottom-width: var(--ds-border-hairline); transform: translateY(-100%); }
.ds-sheet[data-side="bottom"] { inset: auto 0 0 0; width: 100vw; max-height: 100dvh; border-top-width: var(--ds-border-hairline); transform: translateY(100%); }
.ds-sheet[data-shown] { transform: none; transition-duration: var(--ds-duration-entrance); }
.ds-sheet::backdrop { background: var(--ds-color-scrim); opacity: 0; transition: opacity var(--ds-duration-enter) var(--ds-easing-standard); }
.ds-sheet[data-shown]::backdrop { opacity: 1; transition-duration: var(--ds-duration-entrance); }
@media (prefers-reduced-motion: reduce) {
.ds-sheet[data-side] { transform: none; opacity: 0; }
.ds-sheet[data-side][data-shown] { opacity: 1; }
}Reference: Derived from the brand guidelines (no sheet in the brand assets): the plan card's #262626 fill, Funnel Display for its title, the neutral steps for the hairline and the scrim.