Components

Popover

A panel for any content, opened from a button: the card's #262626 fill on Black, a hairline and the brand corner. It grows from its trigger and flips to the side with room.

Install

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

npx spyglass-ds add popover
<script type="module" src="/spyglass-ds/elements/popover.js"></script>
Save to a board

Usage

A short form or a few settings beside the button that opens them: save to a board, a filter with two fields. Focus moves into it; Escape closes it and returns focus.

Never

  • A list of actions: use Dropdown Menu
  • Content someone must read to go on: put it on the page
  • A shadow or a glow: the fill and the hairline set it apart

Adds with it: button

Props

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

<Popover>

PropTypeDefault
labelstring

The panel's name for assistive tech.

sideSide

The side it opens on (it flips when there is no room).

'bottom'
alignAlign

Where it lines up with the trigger.

'start'
widthstring

The panel's width (a CSS length).

'288px'
triggerClassstring

Classes for the trigger in place of the small secondary button.

triggerLabelstring

The trigger's name, when its content is only an icon.

triggerReactNode | ((open: boolean) => ReactNode)

The trigger's content, or a function of whether it is open.

openboolean

Opens or closes it (with onOpenChange).

onOpenChange(open: boolean) => void
childrenReactNode | ((close: (refocus?: boolean) => void) => ReactNode)

The panel's content, or a function of `close`.

<PopoverPanel>

PropTypeDefault
popPopoverController
tipboolean
childrenReactNode
data-dsstring

Examples

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

react/examples/popover/Board.tsx
'use client'
import { Button } from '@/react/components/ui/Button'
import { Input } from '@/react/components/ui/Input'
import { Popover } from '@/react/components/ui/Popover'
// Save a search to a board: a short form in a panel, opened from a button.

export default function Board() {
  return (
    <Popover label="Save to a board" trigger="Save to board">
      {(close) => (
        <form className="flex flex-col gap-4" onSubmit={(event) => { event.preventDefault(); close() }}>
          <div className="flex flex-col gap-1">
            <p className="type-ui-strong text-fg">Save to a board</p>
            <p className="type-caption text-fg-muted">Keep the creatives from this search in one place.</p>
          </div>
          <div className="flex flex-col gap-2">
            <label htmlFor="popover-board" className="type-label text-fg-soft">Board name</label>
            <Input id="popover-board" name="board" size="sm" defaultValue="Acme hooks" />
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="ghost" size="sm" onClick={() => close()}>Cancel</Button>
            <Button type="submit" size="sm">Save</Button>
          </div>
        </form>
      )}
    </Popover>
  )
}
elements/examples/popover/Board.html
<!-- Save a search to a board: a short form in a panel, opened from a button. -->
<spyglass-popover id="board-popover" label="Save to a board">
  <span slot="trigger">Save to board</span>
  <form id="board-form" class="flex flex-col gap-4">
    <div class="flex flex-col gap-1">
      <p class="type-ui-strong text-fg">Save to a board</p>
      <p class="type-caption text-fg-muted">Keep the creatives from this search in one place.</p>
    </div>
    <div class="flex flex-col gap-2">
      <label for="popover-board" class="type-label text-fg-soft">Board name</label>
      <spyglass-input id="popover-board" name="board" size="sm" value="Acme hooks" aria-label="Board name"></spyglass-input>
    </div>
    <div class="flex justify-end gap-2">
      <spyglass-button id="board-cancel" variant="ghost" size="sm">Cancel</spyglass-button>
      <spyglass-button type="submit" size="sm">Save</spyglass-button>
    </div>
  </form>
</spyglass-popover>
<script type="module">
  const pop = document.getElementById('board-popover')
  document.getElementById('board-form').addEventListener('submit', (event) => { event.preventDefault(); pop.close() })
  document.getElementById('board-cancel').addEventListener('click', () => pop.close())
</script>

Source

react/components/ui/Popover.tsx
'use client'
import { useEffect, useId, useImperativeHandle, useRef, type ReactNode, type Ref, type MouseEvent } from 'react'
import { followGlow } from '@/lib/glow'
import { buttonClasses } from '@/react/components/ui/Button'
import { PopoverPanel } from '@/react/components/ui/PopoverPanel'
import { firstFocusable, usePopover, type Align, type Side } from '@/react/hooks/usePopover'

// A panel for any content (a short form, a few settings, a note), opened from a button: the card's #262626 fill on
// Black with a hairline and the brand corner. The trigger's content is `trigger`, drawn as a small secondary button
// unless `triggerClass` says otherwise. Opening moves focus to the panel's first control (or the panel); Escape, a
// press outside or tabbing away closes it, and Escape returns focus to the trigger. It flips to the side with room and
// stays 8px inside the viewport. children may be a function of `close`. `open` with `onOpenChange` controls it; `ref`
// gets { close }.
export interface PopoverProps {
  /** The panel's name for assistive tech. */
  label: string
  /** The side it opens on (it flips when there is no room). */
  side?: Side
  /** Where it lines up with the trigger. */
  align?: Align
  /** The panel's width (a CSS length). */
  width?: string
  /** Classes for the trigger in place of the small secondary button. */
  triggerClass?: string
  /** The trigger's name, when its content is only an icon. */
  triggerLabel?: string
  /** The trigger's content, or a function of whether it is open. */
  trigger?: ReactNode | ((open: boolean) => ReactNode)
  /** Opens or closes it (with onOpenChange). */
  open?: boolean
  onOpenChange?: (open: boolean) => void
  /** The panel's content, or a function of `close`. */
  children?: ReactNode | ((close: (refocus?: boolean) => void) => ReactNode)
  ref?: Ref<{ close: (refocus?: boolean) => void }>
}

export function Popover({ label, side = 'bottom', align = 'start', width = '288px', triggerClass, triggerLabel, trigger, open, onOpenChange, children, ref }: PopoverProps) {
  const pop = usePopover({ side, align, gap: 8 })
  const id = `popover-${useId()}`
  const close = (refocus = true) => pop.hide(refocus)
  useImperativeHandle(ref, () => ({ close }))

  async function show(keyboard = false) {
    await pop.show({ keyboard })
    ;(firstFocusable(pop.panel.current) ?? pop.panel.current)?.focus({ preventScroll: true })
  }
  useEffect(() => {
    if (open && !pop.open) void show()
    if (open === false && pop.open) pop.hide()
  }, [open]) // eslint-disable-line react-hooks/exhaustive-deps
  const report = useRef(onOpenChange)
  report.current = onOpenChange
  const was = useRef(pop.open)
  useEffect(() => {
    if (was.current !== pop.open) report.current?.(pop.open)
    was.current = pop.open
  }, [pop.open])
  // A click from the keyboard has no pointer detail: the panel opens and closes at once.
  function onClick(event: MouseEvent) {
    const keyboard = event.detail === 0
    if (pop.open) pop.hide(keyboard, keyboard)
    else void show(keyboard)
  }
  return (
    <>
      <button
        data-ds="popover"
        ref={(el) => { pop.anchor.current = el }}
        type="button"
        className={triggerClass ?? buttonClasses({ variant: 'secondary', size: 'sm' })}
        aria-haspopup="dialog"
        aria-expanded={pop.open}
        aria-controls={pop.open ? id : undefined}
        aria-label={triggerLabel}
        onClick={onClick}
        onPointerMove={(event) => followGlow(event.currentTarget, event)}
      >
        {typeof trigger === 'function' ? trigger(pop.open) : trigger}
      </button>
      <PopoverPanel data-ds="popover" id={id} pop={pop} role="dialog" aria-label={label} tabIndex={-1} className="p-4" style={{ width }}>
        {typeof children === 'function' ? children(close) : children}
      </PopoverPanel>
    </>
  )
}

export default Popover
react/components/ui/PopoverPanel.tsx
'use client'
import { useEffect, useState, type CSSProperties, type HTMLAttributes, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { Transition } from '@/react/lib/transition'
import { cn } from '@/react/lib/cn'
import type { PopoverController } from '@/react/hooks/usePopover'

// The floating panel every overlay draws (usePopover places it): portalled to the body, fixed where it fits, the
// card's #262626 fill on Black with a #666666 hairline and the brand corner, no shadow. It grows from its anchor, 4px
// and a touch of scale, over 240ms on the strong ease-out, and leaves in 160ms; opened or closed from the keyboard it
// does neither. `tip` is the tooltip's White fill with Black caption text, 2px over 160ms. Reduced motion keeps the
// fade. className, style and other props land on the panel.
export interface PopoverPanelProps extends HTMLAttributes<HTMLDivElement> { pop: PopoverController, tip?: boolean, children?: ReactNode, 'data-ds'?: string }

export function PopoverPanel({ pop, tip, className, style, children, ...rest }: PopoverPanelProps) {
  // Portalled after mount, so the server's render and the first client render agree.
  const [mounted, setMounted] = useState(false)
  useEffect(() => setMounted(true), [])
  const target = mounted ? pop.target ?? document.body : null
  if (!target) return <style href="ds-popover-panel" precedence="ds">{css}</style>
  const placed: CSSProperties = { left: `${pop.pos.x}px`, top: `${pop.pos.y}px`, transformOrigin: pop.pos.origin, minWidth: pop.pos.minWidth ? `${pop.pos.minWidth}px` : undefined }
  return (
    <>
      <style href="ds-popover-panel" precedence="ds">{css}</style>
      {createPortal(
        <Transition show={pop.open} name="ds-pop" css={!pop.instant}>
          <div
            data-ds="popover-panel"
            {...rest}
            ref={(el) => { pop.panel.current = el }}
            className={cn('ds-pop', !tip && 'fade-y', className)}
            data-tip={tip || undefined}
            data-side={pop.pos.side}
            data-instant={pop.instant || undefined}
            data-placed={pop.pos.placed || undefined}
            style={{ ...style, ...placed }}
            onBlur={pop.onFocusOut}
          >
            {children}
          </div>
        </Transition>,
        target,
      )}
    </>
  )
}

export default PopoverPanel

const css = `
.ds-pop { position: fixed; z-index: 60; max-width: calc(100vw - 16px); max-height: calc(100vh - 16px); overflow: auto; overscroll-behavior: contain; border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); 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); text-align: left; outline: none; }
.ds-pop:not([data-placed]) { visibility: hidden; }
.ds-pop[data-tip] { z-index: 70; overflow: visible; padding: var(--ds-space-xs) var(--ds-space-sm); border-color: var(--ds-color-surface-inverse); border-radius: var(--ds-radius-sm); background: var(--ds-color-surface-inverse); color: var(--ds-color-fg-inverse); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); white-space: nowrap; pointer-events: none; }
.ds-pop-enter-active { transition: opacity var(--ds-duration-enter) var(--ds-easing-out), transform var(--ds-duration-enter) var(--ds-easing-out); }
.ds-pop-leave-active { transition: opacity var(--ds-duration-exit) var(--ds-easing-out), transform var(--ds-duration-exit) var(--ds-easing-out); }
.ds-pop-enter-from, .ds-pop-leave-to { opacity: 0; }
.ds-pop-enter-from[data-side="bottom"], .ds-pop-leave-to[data-side="bottom"] { transform: translateY(-4px) scale(0.98); }
.ds-pop-enter-from[data-side="top"], .ds-pop-leave-to[data-side="top"] { transform: translateY(4px) scale(0.98); }
.ds-pop-enter-from[data-side="right"], .ds-pop-leave-to[data-side="right"] { transform: translateX(-4px) scale(0.98); }
.ds-pop-enter-from[data-side="left"], .ds-pop-leave-to[data-side="left"] { transform: translateX(4px) scale(0.98); }
.ds-pop[data-tip].ds-pop-enter-active, .ds-pop[data-tip].ds-pop-leave-active { transition: opacity var(--ds-duration-micro) var(--ds-easing-out), transform var(--ds-duration-micro) var(--ds-easing-out); }
.ds-pop[data-tip].ds-pop-enter-from[data-side="bottom"], .ds-pop[data-tip].ds-pop-leave-to[data-side="bottom"] { transform: translateY(-2px); }
.ds-pop[data-tip].ds-pop-enter-from[data-side="top"], .ds-pop[data-tip].ds-pop-leave-to[data-side="top"] { transform: translateY(2px); }
.ds-pop[data-tip].ds-pop-enter-from[data-side="right"], .ds-pop[data-tip].ds-pop-leave-to[data-side="right"] { transform: translateX(-2px); }
.ds-pop[data-tip].ds-pop-enter-from[data-side="left"], .ds-pop[data-tip].ds-pop-leave-to[data-side="left"] { transform: translateX(2px); }
.ds-pop[data-instant].ds-pop-enter-active, .ds-pop[data-instant].ds-pop-leave-active { transition: none; }
@media (prefers-reduced-motion: reduce) {
  .ds-pop.ds-pop-enter-from, .ds-pop.ds-pop-leave-to { transform: none; }
}
`
react/hooks/usePopover.ts
'use client'
import { useCallback, useEffect, useMemo, useRef, useState, type FocusEvent } from 'react'

/**
 * A floating panel's behavior, shared by Popover, Tooltip, HoverCard, ContextMenu, Menubar, DatePicker and the
 * listboxes: where it sits (beside its anchor or at a point, flipping to the side with room and kept 8px inside the
 * viewport), where it grows from (its anchor), and how it leaves (a press outside, Escape, focus moving away). Escape
 * closes only the topmost open panel and returns focus to what opened it. PopoverPanel draws the panel.
 */
export type Side = 'top' | 'right' | 'bottom' | 'left'
export type Align = 'start' | 'center' | 'end'
export interface PopoverOptions {
  side?: Side
  align?: Align
  /** Space between the anchor and the panel (4px, as Menu's panel). */
  gap?: number
  /** The panel at least as wide as its anchor (selects, the date field). */
  matchWidth?: boolean
  /** A press outside, or focus leaving, keeps it open (a tooltip closes itself). */
  sticky?: boolean
}
interface Box { left: number, top: number, right: number, bottom: number, width: number, height: number }

const MARGIN = 8
const OPPOSITE: Record<Side, Side> = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }
const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(n, hi))

/** Where a w by h panel goes beside `a` in a vw by vh viewport: the side asked for, or its opposite when only that fits. */
export function place(a: Box, w: number, h: number, vw: number, vh: number, side: Side, align: Align, gap: number) {
  const room: Record<Side, number> = { top: a.top - MARGIN, bottom: vh - a.bottom - MARGIN, left: a.left - MARGIN, right: vw - a.right - MARGIN }
  const need = (side === 'top' || side === 'bottom' ? h : w) + gap
  const s = room[side] < need && room[OPPOSITE[side]] > room[side] ? OPPOSITE[side] : side
  let x: number
  let y: number
  if (s === 'top' || s === 'bottom') {
    y = s === 'bottom' ? a.bottom + gap : a.top - gap - h
    x = align === 'start' ? a.left : align === 'end' ? a.right - w : a.left + a.width / 2 - w / 2
  }
  else {
    x = s === 'right' ? a.right + gap : a.left - gap - w
    y = align === 'start' ? a.top : align === 'end' ? a.bottom - h : a.top + a.height / 2 - h / 2
  }
  x = Math.max(MARGIN, Math.min(x, vw - w - MARGIN))
  y = Math.max(MARGIN, Math.min(y, vh - h - MARGIN))
  // It grows from the anchor: the edge facing it, at the anchor's middle.
  const ox = s === 'left' ? w : s === 'right' ? 0 : clamp(a.left + a.width / 2 - x, 0, w)
  const oy = s === 'top' ? h : s === 'bottom' ? 0 : clamp(a.top + a.height / 2 - y, 0, h)
  return { x: Math.round(x), y: Math.round(y), side: s, origin: `${Math.round(ox)}px ${Math.round(oy)}px` }
}

// Open panels, the newest last: Escape belongs to the last.
const stack: object[] = []

export interface PopoverPosition { x: number, y: number, side: Side, origin: string, minWidth: number, placed: boolean }

export function usePopover(options: PopoverOptions = {}) {
  const [open, setOpen] = useState(false)
  const anchor = useRef<HTMLElement | null>(null)
  const panel = useRef<HTMLElement | null>(null)
  /** Opened from the keyboard (or closed by it): no animation. */
  const [instant, setInstant] = useState(false)
  /** Where the panel is portalled: the body, or the open modal dialog its anchor sits in (outside one is inert). */
  const [target, setTarget] = useState<HTMLElement | null>(null)
  const [pos, setPos] = useState<PopoverPosition>({ x: 0, y: 0, side: options.side ?? 'bottom', origin: '0px 0px', minWidth: 0, placed: false })
  const me = useMemo(() => ({}), [])
  const point = useRef<{ x: number, y: number } | null>(null)
  const returnTo = useRef<HTMLElement | null>(null)
  const frame = useRef(0)
  const opts = useRef(options)
  opts.current = options
  const resolveShown = useRef<(() => void) | null>(null)
  const openRef = useRef(open)
  openRef.current = open

  const update = useCallback(() => {
    const el = panel.current
    const p = point.current
    const a = p ? { left: p.x, top: p.y, right: p.x, bottom: p.y, width: 0, height: 0 } : anchor.current?.getBoundingClientRect()
    if (!el || !a) return
    const o = opts.current
    const minWidth = o.matchWidth && !p ? a.width : 0
    const w = Math.max(el.offsetWidth, minWidth)
    const placed = place(a, w, el.offsetHeight, document.documentElement.clientWidth, window.innerHeight, o.side ?? 'bottom', o.align ?? 'start', o.gap ?? 4)
    setPos({ ...placed, minWidth, placed: true })
  }, [])
  const schedule = useCallback(() => {
    cancelAnimationFrame(frame.current)
    frame.current = requestAnimationFrame(update)
  }, [update])

  /** Opens it; `at` puts it at a point (a context menu), `keyboard` skips the animation. It resolves once the panel is
   * placed and visible, so focus can move into it. */
  const show = useCallback((how: { keyboard?: boolean, at?: { x: number, y: number } } = {}) => {
    returnTo.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
    point.current = how.at ?? null
    setInstant(!!how.keyboard)
    setTarget((anchor.current?.closest('dialog[open]') as HTMLElement | null) ?? document.body)
    setPos(p => ({ ...p, placed: false }))
    setOpen(true)
    return new Promise<void>((resolve) => { resolveShown.current = resolve })
  }, [])
  /** Closes it; `refocus` returns focus to what opened it, `keyboard` closes at once. */
  const hide = useCallback((refocus = false, keyboard = false) => {
    if (!openRef.current) return
    setInstant(keyboard)
    setOpen(false)
    if (refocus) (point.current ? returnTo.current : anchor.current ?? returnTo.current)?.focus({ preventScroll: true })
  }, [])
  const toggle = useCallback((how: { keyboard?: boolean } = {}) => {
    if (openRef.current) hide(how.keyboard, how.keyboard)
    else void show(how)
  }, [hide, show])

  // Once the panel is in the page: place it, then let show() resolve after the placed render.
  useEffect(() => {
    if (!open) return
    if (!pos.placed) update()
    else if (resolveShown.current) {
      resolveShown.current()
      resolveShown.current = null
    }
  }, [open, pos.placed, update])

  useEffect(() => {
    if (!open) return
    stack.push(me)
    function onPointerDown(event: PointerEvent) {
      const t = event.target as Node
      if (panel.current?.contains(t) || anchor.current?.contains(t)) return
      hide()
    }
    function onKey(event: KeyboardEvent) {
      if (event.key !== 'Escape' || stack.at(-1) !== me) return
      // A dialog under the panel would take Escape too: it is the panel's.
      event.preventDefault()
      event.stopPropagation()
      hide(true, true)
    }
    if (!opts.current.sticky) document.addEventListener('pointerdown', onPointerDown, true)
    document.addEventListener('keydown', onKey, true)
    window.addEventListener('scroll', schedule, true)
    window.addEventListener('resize', schedule)
    const ro = new ResizeObserver(schedule)
    if (panel.current) ro.observe(panel.current)
    return () => {
      const i = stack.indexOf(me)
      if (i >= 0) stack.splice(i, 1)
      document.removeEventListener('pointerdown', onPointerDown, true)
      document.removeEventListener('keydown', onKey, true)
      window.removeEventListener('scroll', schedule, true)
      window.removeEventListener('resize', schedule)
      cancelAnimationFrame(frame.current)
      ro.disconnect()
    }
  }, [open, hide, schedule, me])

  /** Focus moving to somewhere outside the panel and its anchor closes it (Tab out of a popover). */
  const onFocusOut = useCallback((event: FocusEvent) => {
    const next = event.relatedTarget as Node | null
    if (opts.current.sticky || !next || panel.current?.contains(next) || anchor.current?.contains(next)) return
    hide()
  }, [hide])

  return { open, anchor, panel, instant, target, pos, show, hide, toggle, update, onFocusOut }
}
export type PopoverController = ReturnType<typeof usePopover>

/** Arrow, Home and End keys over a panel's menu rows; Tab closes. For menus drawn in a PopoverPanel. */
export function onMenuRows(event: KeyboardEvent | React.KeyboardEvent, panel: HTMLElement | null, close: (refocus: boolean) => void) {
  const rows = [...(panel?.querySelectorAll<HTMLElement>('[role^="menuitem"]:not([disabled]), [role="option"]:not([aria-disabled="true"])') ?? [])]
  const at = rows.indexOf(document.activeElement as HTMLElement)
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
    event.preventDefault()
    const step = event.key === 'ArrowDown' ? 1 : -1
    rows[(at + step + rows.length) % rows.length]?.focus()
  }
  else if (event.key === 'Home' || event.key === 'End') {
    event.preventDefault()
    ;(event.key === 'Home' ? rows[0] : rows.at(-1))?.focus()
  }
  else if (event.key === 'Tab') close(false)
}

/** The first thing in `root` that takes focus. */
export function firstFocusable(root: HTMLElement | null) {
  return root?.querySelector<HTMLElement>('button:not(:disabled), [href], input:not(:disabled):not([type="hidden"]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])') ?? null
}
react/lib/transition.tsx
'use client'
import { Children, cloneElement, isValidElement, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode, type Ref } from 'react'
import { flushSync } from 'react-dom'

// Vue's <Transition> and <TransitionGroup> for the React flavor, with the same class names, so a Vue item's CSS
// (.ds-pop-enter-from, .ds-toast-leave-active, .ds-toast-move...) works unchanged:
//
//   <Transition show={open} name="ds-pop">{<div ... />}</Transition>
//   <TransitionGroup name="ds-toast">{toasts.map((t) => <p key={t.id} ... />)}</TransitionGroup>
//
// Entering: <name>-enter-from and -enter-active, then a frame later -enter-to in place of -enter-from, until the
// transition ends. Leaving: the same with -leave-*, and the element stays until it has, then goes in the same task its
// classes come off (flushSync), so it never shows again for a frame. A group also moves the others with <name>-move
// (FLIP), measured once the entering and leaving children have their classes, as Vue's are. `css={false}` skips the classes (Vue's :css="false"); `duration` is Vue's explicit duration
// in ms, a number or { enter, leave }. The child must take a ref (a DOM element) and className.
type Duration = number | { enter: number, leave: number }
type Phase = 'enter' | 'leave'

const ms = (d: Duration | undefined, phase: Phase) => (d === undefined ? undefined : typeof d === 'number' ? d : d[phase])

/** Runs one Vue transition phase on an element and resolves when it has ended. */
export function runTransition(el: HTMLElement, name: string, phase: Phase, duration?: Duration): Promise<void> {
  const from = `${name}-${phase}-from`
  const active = `${name}-${phase}-active`
  const to = `${name}-${phase}-to`
  el.classList.add(from, active)
  return new Promise((resolve) => {
    let done = false
    const finish = () => {
      if (done) return
      done = true
      el.classList.remove(from, active, to)
      el.removeEventListener('transitionend', onEnd)
      el.removeEventListener('animationend', onEnd)
      resolve()
    }
    const onEnd = (event: Event) => { if (event.target === el) finish() }
    requestAnimationFrame(() => requestAnimationFrame(() => {
      el.classList.remove(from)
      el.classList.add(to)
      const explicit = ms(duration, phase)
      if (explicit !== undefined) return void setTimeout(finish, explicit)
      // The longest transition or animation on it, as Vue reads it; none means done now. A scroll-linked animation
      // (the scroll fade: duration auto) is not timed, so it counts as none.
      const cs = getComputedStyle(el)
      const longest = (durations: string, delays: string) => {
        const d = durations.split(',').map(s => (Number.parseFloat(s) || 0) * (s.trim().endsWith('ms') ? 1 : 1000))
        const l = delays.split(',').map(s => (Number.parseFloat(s) || 0) * (s.trim().endsWith('ms') ? 1 : 1000))
        return Math.max(0, ...d.map((x, i) => x + (l[i % l.length] || 0)))
      }
      const total = Math.max(longest(cs.transitionDuration, cs.transitionDelay), longest(cs.animationDuration, cs.animationDelay))
      if (!total) return finish()
      el.addEventListener('transitionend', onEnd)
      el.addEventListener('animationend', onEnd)
      setTimeout(finish, total + 50)
    }))
  })
}

function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
  return (node: T) => {
    for (const r of refs) {
      if (typeof r === 'function') r(node)
      else if (r) (r as { current: T }).current = node
    }
  }
}
type Child = ReactElement<{ ref?: Ref<HTMLElement>, className?: string }>

export interface TransitionProps { show: boolean, name: string, css?: boolean, duration?: Duration, appear?: boolean, children: ReactNode }

/** Vue's <Transition> around one element: it enters when `show` turns true and leaves before it unmounts. */
export function Transition({ show, name, css = true, duration, appear, children }: TransitionProps) {
  // Whether the element is in the page: from the render where `show` turns true until its leave has ended.
  const [present, setPresent] = useState(show)
  const el = useRef<HTMLElement | null>(null)
  const was = useRef<boolean | null>(null)
  const last = useRef<ReactNode>(children)
  if (show) last.current = children
  if (show && !present) setPresent(true)
  useLayoutEffect(() => {
    const before = was.current
    was.current = show
    const node = el.current
    if (before === show) return
    if (show) {
      if (node && css && (before !== null || appear)) void runTransition(node, name, 'enter', duration)
    }
    // Gone in the same task its leave classes come off, as Vue removes it, so no frame shows it whole again.
    else if (node && css && before) void runTransition(node, name, 'leave', duration).then(() => { if (!was.current) flushSync(() => setPresent(false)) })
    else setPresent(false)
  }, [show]) // eslint-disable-line react-hooks/exhaustive-deps
  const child = (show ? children : last.current) as Child
  if (!(show || present) || !isValidElement(child)) return null
  return cloneElement(child, { ref: mergeRefs(child.props.ref, (n: HTMLElement | null) => { el.current = n }) })
}

export interface TransitionGroupProps { name: string, children: ReactNode }

/** Vue's <TransitionGroup>: keyed children enter and leave as <Transition> does, and the rest move with <name>-move. */
export function TransitionGroup({ name, children }: TransitionGroupProps) {
  const nodes = useRef(new Map<string, HTMLElement>())
  const rects = useRef(new Map<string, DOMRect>())
  const seen = useRef(new Set<string>())
  const firstRender = useRef(true)
  const current = Children.toArray(children).filter(isValidElement) as Child[]
  const [leaving, setLeaving] = useState<Map<string, { child: Child, index: number }>>(new Map())
  const prev = useRef<Child[]>([])

  // Children that went away stay, leaving, where they were.
  const keys = new Set(current.map(c => c.key!))
  const gone = prev.current.filter(c => !keys.has(c.key!) && !leaving.has(c.key!))
  if (gone.length) {
    const next = new Map(leaving)
    for (const c of gone) next.set(c.key!, { child: c, index: prev.current.indexOf(c) })
    setLeaving(next)
  }
  prev.current = current
  const list = [...current]
  for (const [key, { child, index }] of leaving) if (!keys.has(key)) list.splice(Math.min(index, list.length), 0, child)

  // Before the DOM changes: where every child is now (for the move).
  for (const [key, node] of nodes.current) rects.current.set(key, node.getBoundingClientRect())

  useLayoutEffect(() => {
    // First every entering and leaving child takes its classes, so the measures for the move below see each as Vue does
    // (an entering one at its enter-from, a leaving one out of the flow): measuring first would fix an entering child's
    // style as it is, fully shown, and its transition would start from the end.
    const entered = new Set<string>()
    for (const c of list) {
      const key = c.key!
      const node = nodes.current.get(key)
      if (!node) continue
      if (leaving.has(key)) {
        if (!node.classList.contains(`${name}-leave-active`)) {
          // Gone in the same task its leave classes come off, so no frame shows it whole again.
          void runTransition(node, name, 'leave').then(() => flushSync(() => setLeaving((m) => {
            const n = new Map(m)
            n.delete(key)
            return n
          })))
        }
        continue
      }
      if (!seen.current.has(key)) {
        seen.current.add(key)
        entered.add(key)
        if (!firstRender.current) void runTransition(node, name, 'enter')
      }
    }
    // Then the move: from where each stayed child was to where it is.
    for (const c of list) {
      const key = c.key!
      const node = nodes.current.get(key)
      if (!node || leaving.has(key) || entered.has(key)) continue
      const before = rects.current.get(key)
      if (!before) continue
      const after = node.getBoundingClientRect()
      if (before.left !== after.left || before.top !== after.top) {
        node.style.transitionDuration = '0s'
        node.style.transform = `translate(${before.left - after.left}px, ${before.top - after.top}px)`
        void node.offsetWidth
        node.classList.add(`${name}-move`)
        node.style.transitionDuration = ''
        node.style.transform = ''
        const end = () => {
          node.classList.remove(`${name}-move`)
          node.removeEventListener('transitionend', end)
        }
        node.addEventListener('transitionend', end)
      }
    }
    firstRender.current = false
    for (const key of [...seen.current]) if (!list.some(c => c.key === key)) seen.current.delete(key)
  })

  return (
    <>
      {list.map(c => cloneElement(c, {
        key: c.key,
        ref: mergeRefs(c.props.ref, (n: HTMLElement | null) => {
          if (n) nodes.current.set(c.key!, n)
          else nodes.current.delete(c.key!)
        }),
      }))}
    </>
  )
}
react/lib/cn.ts
// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]

export function cn(...values: ClassValue[]): string {
	const out: string[] = []
	for (const v of values) {
		if (!v) continue
		if (Array.isArray(v)) {
			const s = cn(...v)
			if (s) out.push(s)
		}
		else out.push(v)
	}
	return out.join(' ')
}
elements/components/ui/popover.ts
import { html, nothing, type PropertyValues } from 'lit'
import { followGlow } from '@/lib/glow'
import { DsElement, define, uid } from '@/elements/lib/element'
import { firstFocusable, PopoverController, popoverStyles, type Align, type Side } from '@/elements/lib/popover'
import styles from 'virtual:tw'

// Popover.tsx as <spyglass-popover>: a panel for any content (a short form, a few settings, a note), opened from a
// button: the card's #262626 fill on Black with a hairline and the brand corner. The trigger: a <button
// slot="trigger"> you style yourself (React's triggerClass), or other content in the `trigger` slot, drawn as a small
// secondary button. Opening moves focus to the panel's first control (or the panel); Escape, a press outside or tabbing
// away closes it, and Escape returns focus to the trigger. It flips to the side with room and stays 8px inside the
// viewport, in the top layer. `open` (reflected) with `open-change`; close() closes it.

// Button.tsx's classes for a small secondary button, in its order.
const TRIGGER = 'inline-flex shrink-0 cursor-pointer items-center justify-center rounded-control whitespace-nowrap select-none transition-[background-color,color] duration-160 ease-out relative isolate overflow-hidden before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:bg-[radial-gradient(circle_var(--ds-glow-radius)_at_var(--glow-x,50%)_var(--glow-y,50%),var(--ds-color-action-glow),transparent)] before:opacity-0 before:transition-opacity before:duration-240 before:ease-out hover:not-disabled:before:opacity-100 disabled:cursor-not-allowed disabled:bg-action-disabled disabled:text-action-disabled-fg h-control-sm gap-1.5 type-ui-strong px-3 bg-action-secondary text-action-secondary-fg shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-action-secondary-edge)] hover:not-disabled:bg-action-secondary-hover'

/**
 * @summary A panel for any content, opened from a button.
 * @slot - The panel's content.
 * @slot trigger - A <button> to use as the trigger, or the default trigger's content.
 * @fires open-change - It opened or closed (detail.value).
 */
export class Popover extends DsElement {
	static styles = [DsElement.styles, popoverStyles, styles]
	static properties = { label: {}, side: {}, align: {}, width: {}, triggerLabel: { attribute: 'trigger-label' }, open: { type: Boolean, reflect: true } }

	/** The panel's name for assistive tech. */
	label = ''
	side: Side = 'bottom'
	align: Align = 'start'
	width = '288px'
	triggerLabel?: string
	open = false
	private panelId = uid('popover')
	private pop = new PopoverController(this, {
		anchor: () => this.trigger,
		panel: () => this.renderRoot.querySelector<HTMLElement>('.ds-pop'),
	})

	private get trigger(): HTMLElement | null {
		return this.querySelector<HTMLElement>(':scope > button[slot="trigger"]') ?? this.renderRoot.querySelector<HTMLElement>('button[data-trigger]')
	}

	/** Closes it; focus returns to the trigger unless refocus is false. */
	close(refocus = true) {
		this.pop.hide(refocus)
	}
	private async show(keyboard = false) {
		await this.pop.show({ keyboard })
		const panel = this.renderRoot.querySelector<HTMLElement>('.ds-pop')
		// Into an element's own control, so a field takes focus as a click gives it (focusing the host selects its text).
		let target = firstFocusable(panel) ?? panel
		while (target?.shadowRoot) {
			const inner = firstFocusable(target.shadowRoot as unknown as Element)
			if (!inner || inner === target) break
			target = inner
		}
		target?.focus({ preventScroll: true })
	}
	// A click from the keyboard has no pointer detail: the panel opens and closes at once.
	private onClick = (event: MouseEvent) => {
		const keyboard = event.detail === 0
		if (this.pop.open) this.pop.hide(keyboard, keyboard)
		else void this.show(keyboard)
	}

	private wired: HTMLElement | null = null
	protected willUpdate(changed: PropertyValues<this>) {
		this.pop.configure({ side: this.side, align: this.align, gap: 8 })
		if (changed.has('open') && this.open !== this.pop.open && changed.get('open') !== undefined) {
			if (this.open) void this.show()
			else this.pop.hide()
		}
	}
	protected updated(changed: PropertyValues<this>) {
		super.updated(changed)
		const own = this.querySelector<HTMLElement>(':scope > button[slot="trigger"]')
		if (own && own !== this.wired) {
			own.addEventListener('click', this.onClick)
			own.setAttribute('aria-haspopup', 'dialog')
			this.wired = own
		}
		if (own) {
			own.setAttribute('aria-expanded', String(this.pop.open))
			if (this.triggerLabel) own.setAttribute('aria-label', this.triggerLabel)
		}
		if (this.open !== this.pop.open) {
			this.open = this.pop.open
			this.emit('open-change', { value: this.open })
		}
	}
	protected firstUpdated(changed: PropertyValues<this>) {
		super.firstUpdated(changed)
		if (this.open) void this.show()
	}

	render() {
		const own = !!this.querySelector(':scope > button[slot="trigger"]')
		const trigger = own
			? html`<slot name="trigger"></slot>`
			: html`<button data-ds="popover" data-trigger type="button" class=${TRIGGER} aria-haspopup="dialog" aria-expanded=${String(this.pop.open)} aria-controls=${this.pop.open ? this.panelId : nothing} aria-label=${this.triggerLabel ?? nothing} @click=${this.onClick} @pointermove=${(event: PointerEvent) => followGlow(event.currentTarget as HTMLElement, event)}><slot name="trigger"></slot></button>`
		const panel = this.pop.rendered
			? html`<div data-ds="popover" id=${this.panelId} popover="manual" class="ds-pop p-4 fade-y" role="dialog" aria-label=${this.label} tabindex="-1" data-side=${this.pop.pos.side} ?data-instant=${this.pop.instant} ?data-placed=${this.pop.pos.placed} style=${this.pop.style(`width: ${this.width}`)} @focusout=${this.pop.onFocusOut}><slot></slot></div>`
			: nothing
		return html`${trigger}${panel}`
	}
}

define('popover', Popover)
elements/components/ui/popover-panel.ts
import { html, nothing } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import { PopoverController, popoverStyles, type Align, type Side } from '@/elements/lib/popover'
import styles from 'virtual:tw'

// PopoverPanel.tsx as <spyglass-popover-panel>: the floating panel every overlay draws, on its own, for overlays of
// your own: the card's #262626 fill with a hairline and the brand corner, no shadow, beside the element named by
// `anchor` (an id), flipped to the side with room and kept 8px inside the viewport, in the top layer. It grows from its
// anchor over 240ms and leaves in 160ms; opened or closed from the keyboard it does neither. `tip` is the tooltip's
// White fill. Set `open` (or call show() and hide()); a press outside, Escape and focus leaving close it. The library's
// own overlays draw the same panel inside their shadow roots (lib/popover.ts).

/**
 * @summary A floating panel beside an anchor.
 * @slot - The panel's content.
 * @fires open-change - It opened or closed (detail.value).
 */
export class PopoverPanel extends DsElement {
	static styles = [DsElement.styles, popoverStyles, styles]
	static properties = { anchor: {}, side: {}, align: {}, tip: { type: Boolean }, open: { type: Boolean, reflect: true }, sticky: { type: Boolean }, matchWidth: { type: Boolean, attribute: 'match-width' } }

	/** The id of the element it sits beside. */
	anchor = ''
	side: Side = 'bottom'
	align: Align = 'start'
	/** The tooltip's White fill, 2px over 160ms. */
	tip = false
	open = false
	/** A press outside or focus leaving keeps it open. */
	sticky = false
	/** At least as wide as its anchor. */
	matchWidth = false
	private pop = new PopoverController(this, {
		anchor: () => (this.anchor ? (this.getRootNode() as Document | ShadowRoot).getElementById(this.anchor) : null),
		panel: () => this.renderRoot.querySelector<HTMLElement>('.ds-pop'),
	})

	show(keyboard = false) {
		return this.pop.show({ keyboard })
	}
	hide(refocus = false, keyboard = false) {
		this.pop.hide(refocus, keyboard)
	}
	protected willUpdate(changed: Map<PropertyKey, unknown>) {
		this.pop.configure({ side: this.side, align: this.align, sticky: this.sticky, matchWidth: this.matchWidth })
		if (changed.has('open') && this.open !== this.pop.open) {
			if (this.open) void this.pop.show()
			else this.pop.hide()
		}
	}
	protected updated() {
		if (this.open !== this.pop.open) {
			this.open = this.pop.open
			this.emit('open-change', { value: this.open })
		}
	}

	render() {
		return this.pop.rendered
			? html`<div data-ds="popover-panel" popover="manual" class=${this.tip ? 'ds-pop' : 'ds-pop fade-y'} ?data-tip=${this.tip} data-side=${this.pop.pos.side} ?data-instant=${this.pop.instant} ?data-placed=${this.pop.pos.placed} style=${this.pop.style()} @focusout=${this.pop.onFocusOut}><slot></slot></div>`
			: nothing
	}
}

define('popover-panel', PopoverPanel)

Reference: Derived from the brand guidelines (no popover in the brand assets): the plan card's #262626 fill and corner, the neutral steps for the hairline.