Components

Dialog

A modal window on the #262626 overlay surface over a Black scrim: a Funnel Display title, a line under it, a ghost close button, a short form or an offer, and buttons at the foot.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add dialog
<script type="module" src="/spyglass-ds/elements/dialog.js"></script>
A short form

Boards keep the creatives you save.

New board

Save creatives to it from any search.

Buttons at the foot

Creator

$10 for your first month, then $20/month.

  • Search every ad by what it says and shows.
  • Track any brand or creator.
  • Unlimited boards.

Usage

A short task that needs the whole attention for a moment: naming a new board, an offer, a setting with a few fields. Escape, the close button and the scrim close it.

Never

  • A long flow or a whole page in a window
  • Two primary buttons in the foot
  • A shadow or a glow around the window
  • Opening one with the page

Adds with it: button packages lucide-react

Props

The web component takes the same as attributes or properties (<spyglass-dialog>); title is heading there.

<Dialog>

PropTypeDefault
titlestring

The title, and the window's name.

descriptionstring

A line under the title.

wideboolean

640px instead of 480px.

lockedboolean

The scrim does nothing (the window holds what can't be shown again).

openboolean
defaultOpenbooleanfalse
onOpenChange(open: boolean) => void
footReactNode

Buttons at the end, under the body.

childrenReactNode

Examples

The same example in React and as web components; both render identically.

react/examples/dialog/NewBoard.tsx
'use client'
import { useState } from 'react'
import { Button } from '@/react/components/ui/Button'
import { Dialog } from '@/react/components/ui/Dialog'
import { Input } from '@/react/components/ui/Input'
// A new board in a short form: the button opens it on the Name field, Enter creates it, Escape or the scrim closes it.

export default function NewBoard() {
  const [open, setOpen] = useState(false)
  const [note, setNote] = useState('Boards keep the creatives you save.')
  return (
    <div className="flex min-h-96 flex-col items-center justify-center gap-3">
      <Button onClick={() => setOpen(true)}>New board</Button>
      <p className="type-caption text-fg-muted" aria-live="polite">{note}</p>
      <Dialog open={open} onOpenChange={setOpen} title="New board" description="Save creatives to it from any search.">
        <form
          className="flex flex-col gap-6"
          onSubmit={(e) => {
            e.preventDefault()
            const name = new FormData(e.currentTarget).get('name') || 'Untitled board'
            setNote(`Created ${name}.`)
            setOpen(false)
          }}
        >
          <div className="flex flex-col gap-2">
            <label htmlFor="new-board-name" className="type-label text-fg-soft">Name</label>
            <Input id="new-board-name" name="name" placeholder="Acme summer ads" />
          </div>
          <div className="flex flex-wrap justify-end gap-2">
            <Button variant="secondary" onClick={() => setOpen(false)}>Cancel</Button>
            <Button type="submit">Create board</Button>
          </div>
        </form>
      </Dialog>
    </div>
  )
}
elements/examples/dialog/NewBoard.html
<!-- A new board in a short form: the button opens it on the Name field, Enter creates it, Escape or the scrim closes it. -->
<div class="flex min-h-96 flex-col items-center justify-center gap-3">
  <spyglass-button id="new-board">New board</spyglass-button>
  <p id="new-board-note" class="type-caption text-fg-muted" aria-live="polite">Boards keep the creatives you save.</p>
  <spyglass-dialog id="new-board-dialog" heading="New board" description="Save creatives to it from any search.">
    <form class="flex flex-col gap-6">
      <div class="flex flex-col gap-2">
        <label for="new-board-name" class="type-label text-fg-soft">Name</label>
        <spyglass-input id="new-board-name" name="name" placeholder="Acme summer ads" aria-label="Name"></spyglass-input>
      </div>
      <div class="flex flex-wrap justify-end gap-2">
        <spyglass-button variant="secondary" data-close>Cancel</spyglass-button>
        <spyglass-button type="submit">Create board</spyglass-button>
      </div>
    </form>
  </spyglass-dialog>
</div>
<script type="module">
  const dialog = document.getElementById('new-board-dialog')
  document.getElementById('new-board').addEventListener('click', () => { dialog.open = true })
  dialog.querySelector('[data-close]').addEventListener('click', () => { dialog.open = false })
  dialog.querySelector('form').addEventListener('submit', (event) => {
    event.preventDefault()
    const name = new FormData(event.currentTarget).get('name') || 'Untitled board'
    document.getElementById('new-board-note').textContent = `Created ${name}.`
    dialog.open = false
  })
</script>
react/examples/dialog/Plan.tsx
'use client'
import { useState } from 'react'
import { Button } from '@/react/components/ui/Button'
import { Dialog } from '@/react/components/ui/Dialog'
// An offer with its buttons in the foot: the White primary for the one action, secondary for the way out.

export default function Plan() {
  const [open, setOpen] = useState(false)
  return (
    <div className="flex min-h-96 items-center justify-center">
      <Button variant="secondary" onClick={() => setOpen(true)}>See the Creator plan</Button>
      <Dialog
        open={open}
        onOpenChange={setOpen}
        title="Creator"
        description="$10 for your first month, then $20/month."
        foot={<><Button variant="secondary" onClick={() => setOpen(false)}>Not now</Button><Button onClick={() => setOpen(false)}>Start Creator for 50% off</Button></>}
      >
        <ul className="flex list-disc flex-col gap-2 pl-5 type-ui text-fg-soft">
          <li>Search every ad by what it says and shows.</li>
          <li>Track any brand or creator.</li>
          <li>Unlimited boards.</li>
        </ul>
      </Dialog>
    </div>
  )
}
elements/examples/dialog/Plan.html
<!-- An offer with its buttons in the foot: the White primary for the one action, secondary for the way out. -->
<div class="flex min-h-96 items-center justify-center">
  <spyglass-button id="plan-open" variant="secondary">See the Creator plan</spyglass-button>
  <spyglass-dialog id="plan-dialog" heading="Creator" description="$10 for your first month, then $20/month.">
    <ul class="flex list-disc flex-col gap-2 pl-5 type-ui text-fg-soft">
      <li>Search every ad by what it says and shows.</li>
      <li>Track any brand or creator.</li>
      <li>Unlimited boards.</li>
    </ul>
    <spyglass-button slot="foot" variant="secondary" data-close>Not now</spyglass-button>
    <spyglass-button slot="foot" data-close>Start Creator for 50% off</spyglass-button>
  </spyglass-dialog>
</div>
<script type="module">
  const dialog = document.getElementById('plan-dialog')
  document.getElementById('plan-open').addEventListener('click', () => { dialog.open = true })
  for (const b of dialog.querySelectorAll('[data-close]')) b.addEventListener('click', () => { dialog.open = false })
</script>

Source

react/components/ui/Dialog.tsx
'use client'
import { useEffect, useRef, type ReactNode } from 'react'
import { X } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { useControllable } from '@/react/hooks/useControllable'

// shadcn's dialog in the brand: a native modal window on the #262626 overlay surface in a neutral hairline with the
// brand corner and no shadow, over a Black scrim. A Funnel Display title, an optional line under it, a ghost close
// button, the body (a short form), and `foot` for the buttons. Focus stays inside; Escape, the close button and the
// scrim close it (`locked`: the scrim does nothing). It starts in the first field; with none, focus rests on the window.
// It comes in over 360ms (a fade and a scale from 0.96, centered, ease-out) and leaves at once; reduced motion keeps
// the fade. `open` with `onOpenChange` (or `defaultOpen` alone).
export interface DialogProps {
  /** The title, and the window's name. */
  title: string
  /** A line under the title. */
  description?: string
  /** 640px instead of 480px. */
  wide?: boolean
  /** The scrim does nothing (the window holds what can't be shown again). */
  locked?: boolean
  open?: boolean
  defaultOpen?: boolean
  onOpenChange?: (open: boolean) => void
  /** Buttons at the end, under the body. */
  foot?: ReactNode
  children?: ReactNode
}

export function Dialog({ title, description, wide, locked, open: openProp, defaultOpen = false, onOpenChange, foot, children }: DialogProps) {
  const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)
  const dialog = useRef<HTMLDialogElement | null>(null)

  useEffect(() => {
    const d = dialog.current
    if (!d) return
    if (open && !d.open) {
      d.showModal()
      const field = d.querySelector<HTMLElement>('.ds-dialog-body :is(input:not([type="hidden"], [type="file"]), textarea, select):not(:disabled)')
      ;(field && field.getBoundingClientRect().bottom <= d.getBoundingClientRect().bottom ? field : d).focus()
    }
    else if (!open && d.open) d.close()
  }, [open])

  return (
    <>
      <style href="ds-dialog" precedence="ds">{css}</style>
      <dialog
        data-ds="dialog"
        ref={dialog}
        className="ds-dialog"
        data-wide={wide || undefined}
        tabIndex={-1}
        aria-label={title}
        onClose={() => setOpen(false)}
        // A click on the scrim lands on the dialog element itself.
        onClick={(event) => { if (event.target === dialog.current && !locked) setOpen(false) }}
      >
        <div className="flex items-start justify-between gap-4 pt-5 pr-4 pl-6">
          <div className="flex min-w-0 flex-1 flex-col gap-2 pt-1.5">
            <h2 className="type-heading-3">{title}</h2>
            {description && <p className="type-ui text-fg-muted">{description}</p>}
          </div>
          <Button variant="ghost" size="sm" icon aria-label="Close" onClick={() => setOpen(false)}><X size={16} strokeWidth={1.5} aria-hidden="true" /></Button>
        </div>
        <div className="ds-dialog-body px-6 pt-5 pb-6">
          {children}
        </div>
        {foot && <div className="flex flex-wrap justify-end gap-2 px-6 pb-6">{foot}</div>}
      </dialog>
    </>
  )
}

export default Dialog

const css = `
.ds-dialog { width: min(480px, calc(100vw - 32px)); margin: auto; padding: 0; border: var(--ds-border-hairline) solid var(--ds-color-edge); border-radius: var(--ds-radius-container); 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); }
.ds-dialog[data-wide] { width: min(640px, calc(100vw - 32px)); }
.ds-dialog:focus { outline: none; }
.ds-dialog::backdrop { background: var(--ds-color-scrim); }
.ds-dialog[open] { animation: ds-dialog-in var(--ds-duration-entrance) var(--ds-easing-out); }
.ds-dialog[open]::backdrop { animation: ds-dialog-fade var(--ds-duration-entrance) var(--ds-easing-out); }
@keyframes ds-dialog-in { from { opacity: 0; transform: scale(0.96); } }
@keyframes ds-dialog-fade { from { opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-dialog[open] { animation-name: ds-dialog-fade; } }
`
react/hooks/useControllable.ts
'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
}
elements/components/ui/dialog.ts
import { html, nothing, type PropertyValues } from 'lit'
import { X } from 'lucide'
import { DsElement, define } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import '@/elements/components/ui/button'
import styles from 'virtual:tw'

// Dialog.tsx as <spyglass-dialog>: a native modal window on the #262626 overlay surface in a neutral hairline with the
// brand corner, over a Black scrim. A Funnel Display heading, an optional line under it, a ghost close button, the body
// (a short form) and the `foot` slot for buttons. Focus stays inside; Escape, the close button and the scrim close it
// (`locked`: the scrim does nothing). It starts in the first field; with none, focus rests on the window. It comes in
// over 360ms (a fade and a scale from 0.96) and leaves at once. React's `open` with `onOpenChange` is the `open`
// attribute with an `open-change` event, and `close` fires as it closes; React's `title` is `heading` (title is HTML's
// tooltip attribute).

/**
 * @summary A modal dialog for a short form.
 * @slot - The body (a form).
 * @slot foot - Buttons at the end, under the body.
 * @fires open-change - It opened or closed (detail.value; read `open`).
 * @fires close - It closed (Escape, the scrim, the close button, or open set to false).
 */
export class Dialog extends DsElement {
	static styles = [DsElement.styles, styles]
	static properties = { heading: {}, description: {}, wide: { type: Boolean }, locked: { type: Boolean }, open: { type: Boolean, reflect: true } }

	/** The title, and the window's name (React's `title`). */
	heading = ''
	/** A line under the heading. */
	description?: string
	/** 640px instead of 480px. */
	wide = false
	/** The scrim does nothing (the window holds what can't be shown again). */
	locked = false
	/** Whether it is showing. */
	open = false

	private get dialog() {
		return this.renderRoot.querySelector('dialog')
	}

	private show() {
		const d = this.dialog
		if (!d || d.open) return
		d.showModal()
		// The first field in the body (a native field, or an element that declares itself a field), else the window.
		const field = [...this.querySelectorAll<HTMLElement>('*')].find((el) => (el.matches('input:not([type="hidden"], [type="file"]), textarea, select') || (el.constructor as { dsField?: boolean }).dsField) && !(el as HTMLInputElement).disabled && !el.closest('[slot="foot"]'))
		const box = field?.shadowRoot?.querySelector('input, textarea, select, button') ?? field
		;(field && box && box.getBoundingClientRect().bottom <= d.getBoundingClientRect().bottom ? field : d).focus()
	}

	protected updated(changed: PropertyValues<this>) {
		super.updated(changed)
		if (!changed.has('open')) return
		if (this.open) this.show()
		else if (this.dialog?.open) this.dialog.close()
	}

	private setOpen(open: boolean) {
		if (this.open === open) return
		this.open = open
		this.emit('open-change', { value: open })
		if (!open) this.emit('close')
	}

	// A click on the scrim lands on the dialog element itself.
	private backdrop(event: MouseEvent) {
		if (event.target === this.dialog && !this.locked) this.setOpen(false)
	}

	render() {
		return html`<dialog data-ds="dialog" class="ds-dialog" ?data-wide=${this.wide} tabindex="-1" aria-label=${this.heading} @close=${() => this.setOpen(false)} @click=${this.backdrop}>
			<div class="flex items-start justify-between gap-4 pt-5 pr-4 pl-6">
				<div class="flex min-w-0 flex-1 flex-col gap-2 pt-1.5">
					<h2 class="type-heading-3">${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.setOpen(false)}>${icon(X, 'x', { size: 16, strokeWidth: 1.5, attrs: { 'aria-hidden': 'true' } })}</spyglass-button>
			</div>
			<div class="ds-dialog-body px-6 pt-5 pb-6"><slot></slot></div>
			${this.hasSlot('foot') ? html`<div class="flex flex-wrap justify-end gap-2 px-6 pb-6"><slot name="foot"></slot></div>` : nothing}
		</dialog>`
	}
}

define('dialog', Dialog)
elements/components/ui/dialog.css
/* Dialog.tsx's styles. */
.ds-dialog { width: min(480px, calc(100vw - 32px)); margin: auto; padding: 0; border: var(--ds-border-hairline) solid var(--ds-color-edge); border-radius: var(--ds-radius-container); 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); }
.ds-dialog[data-wide] { width: min(640px, calc(100vw - 32px)); }
.ds-dialog:focus { outline: none; }
.ds-dialog::backdrop { background: var(--ds-color-scrim); }
.ds-dialog[open] { animation: ds-dialog-in var(--ds-duration-entrance) var(--ds-easing-out); }
.ds-dialog[open]::backdrop { animation: ds-dialog-fade var(--ds-duration-entrance) var(--ds-easing-out); }
@keyframes ds-dialog-in { from { opacity: 0; transform: scale(0.96); } }
@keyframes ds-dialog-fade { from { opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-dialog[open] { animation-name: ds-dialog-fade; } }

Reference: Derived from the guidelines: the #262626 card fill on Black, neutral hairlines, the 10px canvas corner (8px here), Funnel Display titles, DM Sans text, the White primary button; the offer copy from the plan card. shadcn's dialog for anatomy, focus and keys..