Components
Dropdown menu
A button that opens a short list of actions or choices on the #262626 overlay surface: a neutral hairline, the brand corner, rows that take a #262626 fill under the pointer. Arrows, Home, End, Escape and Tab are handled.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add dropdown-menu<script type="module" src="/spyglass-ds/elements/dropdown-menu.js"></script>Usage
A creative's actions, a sort order, account actions: a handful of choices that don't need to stay on screen. Radio rows for one choice from a few.
Never
- Writing your own outside-click or arrow handling
- A shadow under the panel: the hairline and the #262626 fill set it apart
- A spectrum color for a row or its marker
- Two or three views of one thing (use tabs)
MenuItem, MenuLabel and MenuSeparator are the rows of every menu here (the context menu uses them too); they are also exported under shadcn's names (DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator).
Props
The web component takes the same as attributes or properties (<spyglass-dropdown-menu>); title is heading there.
<DropdownMenu>
| Prop | Type | Default |
|---|---|---|
label | string The menu's name for assistive tech. | |
up | boolean Opens upward. | |
align | 'start' | 'end' The panel's edge: start, or end to line up with the trigger's end. | 'start' |
width | string The panel's width. | '240px' |
offset | string Moves the panel in from its edge. | '0px' |
triggerClass | string Classes for the trigger button, in place of the small secondary button. | |
triggerLabel | string The trigger's name, when its content has none (an icon). | |
trigger | ReactNode | ((open: boolean) => ReactNode) The trigger's content, or a function of whether it is open. | |
defaultOpen | boolean Opens with the page. | |
onOpenChange | (open: boolean) => void | |
className | string | |
children | ReactNode |
<MenuItem>
| Prop | Type | Default |
|---|---|---|
href | string Renders a link. | |
current | boolean The current choice, in Medium. | |
danger | boolean The red for leaving or deleting. | |
disabled | boolean | |
keepOpen | boolean Choosing it leaves the menu open. | |
onSelect | () => void | |
role | 'menuitem' | 'menuitemradio' | 'menuitemcheckbox' | 'menuitem' |
aria-checked | boolean | |
className | string | |
children | ReactNode |
<MenuLabel>
| Prop | Type | Default |
|---|---|---|
children | ReactNode |
<MenuSeparator>
| Prop | Type | Default |
|---|
Examples
The same example in React and as web components; both render identically.
import { Bookmark, Download, Ellipsis, Flag, Link } from 'lucide-react'
import { DropdownMenu } from '@/react/components/ui/DropdownMenu'
import { MenuItem } from '@/react/components/ui/MenuItem'
import { MenuLabel } from '@/react/components/ui/MenuLabel'
import { MenuSeparator } from '@/react/components/ui/MenuSeparator'
// A creative's actions, open with the page: save, copy, download, then report on its own.
export default function Actions() {
return (
<div className="flex h-72 w-full items-start justify-center pt-2">
<DropdownMenu label="Creative actions" defaultOpen trigger={<><Ellipsis size={16} strokeWidth={1.5} aria-hidden="true" />Actions</>}>
<MenuLabel>Acme summer UGC</MenuLabel>
<MenuItem><Bookmark size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />Save to board</MenuItem>
<MenuItem><Link size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />Copy link</MenuItem>
<MenuItem><Download size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />Download</MenuItem>
<MenuSeparator />
<MenuItem danger><Flag size={16} strokeWidth={1.5} className="shrink-0" aria-hidden="true" />Report</MenuItem>
</DropdownMenu>
</div>
)
}<!-- A creative's actions, open with the page: save, copy, download, then report on its own. -->
<div class="flex h-72 w-full items-start justify-center pt-2">
<spyglass-dropdown-menu label="Creative actions" open>
<span slot="trigger" class="contents"><i data-lucide="ellipsis" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Actions</span>
<spyglass-menu-label>Acme summer UGC</spyglass-menu-label>
<spyglass-menu-item><i data-lucide="bookmark" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>Save to board</spyglass-menu-item>
<spyglass-menu-item><i data-lucide="link" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>Copy link</spyglass-menu-item>
<spyglass-menu-item><i data-lucide="download" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>Download</spyglass-menu-item>
<spyglass-menu-separator></spyglass-menu-separator>
<spyglass-menu-item danger><i data-lucide="flag" data-size="16" data-stroke-width="1.5" class="shrink-0" aria-hidden="true"></i>Report</spyglass-menu-item>
</spyglass-dropdown-menu>
</div>'use client'
import { useState } from 'react'
import { Check, ChevronDown } from 'lucide-react'
import { DropdownMenu } from '@/react/components/ui/DropdownMenu'
import { MenuItem } from '@/react/components/ui/MenuItem'
// One choice from a few: radio rows, the current one checked. The trigger says what is picked.
const orders = ['Newest', 'Longest running', 'Most engagement']
export default function Sort() {
const [order, setOrder] = useState('Newest')
return (
<div className="flex h-56 w-full items-start justify-center pt-2">
<DropdownMenu label="Sort creatives" width="200px" trigger={<><span>Sort: {order}</span><ChevronDown size={16} strokeWidth={1.5} aria-hidden="true" /></>}>
{orders.map((o) => (
<MenuItem key={o} role="menuitemradio" aria-checked={o === order} onSelect={() => setOrder(o)}>
<span className="min-w-0 flex-1 truncate">{o}</span>
{o === order && <Check size={16} strokeWidth={1.5} className="shrink-0" aria-hidden="true" />}
</MenuItem>
))}
</DropdownMenu>
</div>
)
}<!-- One choice from a few: radio rows, the current one checked. The trigger says what is picked. -->
<div class="flex h-56 w-full items-start justify-center pt-2">
<spyglass-dropdown-menu id="sort-menu" label="Sort creatives" width="200px">
<span slot="trigger" class="contents"><span id="sort-current">Sort: Newest</span><i data-lucide="chevron-down" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></span>
<spyglass-menu-item role="menuitemradio" aria-checked="true" data-order="Newest"><span class="min-w-0 flex-1 truncate">Newest</span><span data-check class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" class="shrink-0" aria-hidden="true"></i></span></spyglass-menu-item>
<spyglass-menu-item role="menuitemradio" aria-checked="false" data-order="Longest running"><span class="min-w-0 flex-1 truncate">Longest running</span><span data-check hidden class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" class="shrink-0" aria-hidden="true"></i></span></spyglass-menu-item>
<spyglass-menu-item role="menuitemradio" aria-checked="false" data-order="Most engagement"><span class="min-w-0 flex-1 truncate">Most engagement</span><span data-check hidden class="contents"><i data-lucide="check" data-size="16" data-stroke-width="1.5" class="shrink-0" aria-hidden="true"></i></span></spyglass-menu-item>
</spyglass-dropdown-menu>
</div>
<script type="module">
const menu = document.getElementById('sort-menu')
menu.addEventListener('select', (e) => {
const row = e.target.closest('[data-order]')
if (!row) return
for (const r of menu.querySelectorAll('[data-order]')) {
r.checked = r === row
r.querySelector('[data-check]').hidden = r !== row
}
document.getElementById('sort-current').textContent = `Sort: ${row.dataset.order}`
})
</script>Source
'use client'
import { createContext, useEffect, useId, useImperativeHandle, useRef, type ReactNode, type Ref } from 'react'
import { useMenu } from '@/react/hooks/useMenu'
import { cn } from '@/react/lib/cn'
// shadcn's dropdown menu in the brand: a button that opens a short list of actions or choices on the #262626 overlay
// surface, a neutral hairline, the 8px corner, no shadow, 4px inside; rows are MenuItem (shadcn's DropdownMenuItem),
// with MenuLabel and MenuSeparator between groups. It comes in over 240ms (a 4px drop and a touch of scale from its
// trigger's edge, ease-out), leaves at once, and does not animate when opened from the keyboard, which is how menus
// are opened most. Arrows, Home, End, Escape, Tab and a click outside are handled (useMenu). The trigger's content is
// `trigger` (a node, or a function of `open`), drawn as a small secondary button unless `triggerClass` says
// otherwise. `defaultOpen` opens it with the page; `ref` gets { open, show, close }; `onOpenChange` hears it.
export const MenuClose = createContext<() => void>(() => {})
export interface DropdownMenuHandle { open: boolean, show: (focus?: 'first' | 'last' | 'none') => void, close: (refocus?: boolean) => void }
export interface DropdownMenuProps {
/** The menu's name for assistive tech. */
label: string
/** Opens upward. */
up?: boolean
/** The panel's edge: start, or end to line up with the trigger's end. */
align?: 'start' | 'end'
/** The panel's width. */
width?: string
/** Moves the panel in from its edge. */
offset?: string
/** Classes for the trigger button, in place of the small secondary button. */
triggerClass?: string
/** The trigger's name, when its content has none (an icon). */
triggerLabel?: string
/** The trigger's content, or a function of whether it is open. */
trigger?: ReactNode | ((open: boolean) => ReactNode)
/** Opens with the page. */
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
className?: string
children?: ReactNode
ref?: Ref<DropdownMenuHandle>
}
export const MENU_TRIGGER = 'inline-flex h-control-sm cursor-pointer items-center gap-1.5 rounded-control bg-action-secondary px-3 type-ui-strong text-action-secondary-fg transition-[background-color] duration-160 ease-standard hover:bg-action-secondary-hover aria-expanded:bg-action-secondary-hover max-md:h-control-touch'
export function DropdownMenu({ label, up, align = 'start', width = '240px', offset = '0px', triggerClass, triggerLabel, trigger: triggerContent, defaultOpen, onOpenChange, className, children, ref }: DropdownMenuProps) {
const { open, root, trigger, show, close, toggle, onTriggerKey, onMenuKey } = useMenu(defaultOpen)
const report = useRef(onOpenChange)
report.current = onOpenChange
const was = useRef(open)
useEffect(() => {
if (was.current === open) return
was.current = open
report.current?.(open)
}, [open])
useImperativeHandle(ref, () => ({ open, show, close }), [open, show, close])
const id = `menu-${useId()}`
return (
<MenuClose.Provider value={() => close(true)}>
<style href="ds-dropdown-menu" precedence="ds">{css}</style>
<div data-ds="dropdown-menu" ref={root} className={cn('relative inline-block', className)}>
<button
ref={trigger}
type="button"
className={triggerClass ?? MENU_TRIGGER}
aria-haspopup="menu"
aria-expanded={open}
aria-controls={id}
aria-label={triggerLabel}
onClick={toggle}
onKeyDown={onTriggerKey}
>
{typeof triggerContent === 'function' ? triggerContent(open) : triggerContent}
</button>
{open && (
<div
id={id}
className="ds-menu"
data-up={up || undefined}
data-align={align}
style={{ width, [align === 'end' ? 'right' : 'left']: offset, [up ? 'bottom' : 'top']: 'calc(100% + 4px)' }}
role="menu"
aria-label={label}
onKeyDown={onMenuKey}
>
{children}
</div>
)}
</div>
</MenuClose.Provider>
)
}
export default DropdownMenu
const css = `
.ds-menu { position: absolute; z-index: 40; display: flex; max-width: calc(100vw - 16px); flex-direction: column; padding: var(--ds-space-xs); 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); transform-origin: top left; animation: ds-menu-in var(--ds-duration-enter) var(--ds-easing-out) both; scroll-margin: 8px; }
.ds-menu[data-align="end"] { transform-origin: top right; }
.ds-menu[data-up] { transform-origin: bottom left; animation-name: ds-menu-up; }
.ds-menu[data-up][data-align="end"] { transform-origin: bottom right; }
/* Opened from the keyboard, focus lands on a row at once: no animation. */
.ds-menu:has(:focus-visible) { animation: none; }
.ds-menu > * { flex-shrink: 0; }
@keyframes ds-menu-in { from { opacity: 0; transform: translateY(-4px) scale(0.98); } }
@keyframes ds-menu-up { from { opacity: 0; transform: translateY(4px) scale(0.98); } }
@media (prefers-reduced-motion: reduce) { .ds-menu, .ds-menu[data-up] { animation-name: ds-menu-fade; } }
@keyframes ds-menu-fade { from { opacity: 0; } }
`'use client'
import { useContext, type ReactNode } from 'react'
import { MenuClose } from '@/react/components/ui/DropdownMenu'
// One row of a dropdown or context menu: 32px (44px on phones), DM Sans 14px, a 4px corner inside the panel's 8px. The
// row under the pointer or focus takes a #262626 fill (160ms, hover only where a pointer hovers). `current` sets it in
// Medium; `danger` is the red for leaving or deleting. Put a 16px Lucide icon first (muted), a shortcut or a check
// last. Choosing it calls `onSelect` and closes the menu, unless `keepOpen`. `role` and `aria-checked` make it a radio
// or checkbox row (role="menuitemradio" aria-checked={picked}).
export interface MenuItemProps {
/** Renders a link. */
href?: string
/** The current choice, in Medium. */
current?: boolean
/** The red for leaving or deleting. */
danger?: boolean
disabled?: boolean
/** Choosing it leaves the menu open. */
keepOpen?: boolean
onSelect?: () => void
role?: 'menuitem' | 'menuitemradio' | 'menuitemcheckbox'
'aria-checked'?: boolean
className?: string
children?: ReactNode
}
export const MENU_ITEM = 'flex h-control-sm w-full shrink-0 cursor-pointer items-center gap-2 rounded-ds-sm px-2 text-left type-ui text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4 aria-[current=true]:font-medium disabled:cursor-not-allowed disabled:text-fg-faint disabled:hover:bg-transparent data-danger:text-fg-danger data-danger:hover:bg-surface-danger data-danger:focus-visible:bg-surface-danger max-md:h-auto max-md:min-h-control-touch'
export function MenuItem({ href, current, danger, disabled, keepOpen, onSelect, role = 'menuitem', 'aria-checked': checked, className, children }: MenuItemProps) {
const close = useContext(MenuClose)
function choose() {
onSelect?.()
if (!keepOpen) close()
}
const shared = { role, 'aria-checked': checked, className: className ? `${MENU_ITEM} ${className}` : MENU_ITEM, 'aria-current': current ? 'true' as const : undefined, 'data-danger': danger || undefined, onClick: choose }
return href ? <a data-ds="menu-item" href={href} {...shared}>{children}</a> : <button data-ds="menu-item" type="button" disabled={disabled} {...shared}>{children}</button>
}
/** shadcn's name for it. */
export { MenuItem as DropdownMenuItem }
export default MenuItemimport type { ReactNode } from 'react'
// A group's name in a dropdown or context menu: a DM Sans Medium label in capitals with 6% tracking, muted.
export function MenuLabel({ children }: { children?: ReactNode }) {
return <p data-ds="menu-label" className="flex items-center justify-between gap-2 px-2 pt-2 pb-1 type-label text-fg-muted">{children}</p>
}
/** shadcn's name for it. */
export { MenuLabel as DropdownMenuLabel }
export default MenuLabel// A neutral hairline between a menu's groups, edge to edge.
export function MenuSeparator() {
return <div data-ds="menu-separator" className="-mx-1 my-1 h-px bg-edge" role="separator" />
}
/** shadcn's name for it. */
export { MenuSeparator as DropdownMenuSeparator }
export default MenuSeparator'use client'
import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from 'react'
/**
* A menu button's behavior: it opens on click, arrows move between items (opening the menu on their end of it from the
* button), Home and End jump, Escape closes and returns focus to the button, Tab and a click outside close it.
*/
export function useMenu(initial = false) {
const [open, setOpen] = useState(initial)
const root = useRef<HTMLDivElement | null>(null)
const trigger = useRef<HTMLButtonElement | null>(null)
const pending = useRef<'first' | 'last' | 'none' | null>(null)
// Each show() renders, so an arrow on the open menu's button still focuses a row (Vue's nextTick runs either way).
const [, setShown] = useState(0)
const items = () => [...(root.current?.querySelectorAll<HTMLElement>('[role^="menuitem"]:not([disabled])') ?? [])]
// After the menu renders: scroll it into view and focus the row asked for (Vue's nextTick).
useEffect(() => {
if (!open || !pending.current) return
const focus = pending.current
pending.current = null
// Opened at the fold it would land out of sight, and the button would seem to do nothing.
items()[0]?.closest('[role="menu"]')?.scrollIntoView({ block: 'nearest' })
if (focus === 'none') return
const list = items()
;(focus === 'last' ? list.at(-1) : list[0])?.focus()
})
const show = useCallback((focus: 'first' | 'last' | 'none' = 'first') => {
pending.current = focus
setOpen(true)
setShown(n => n + 1)
}, [])
const close = useCallback((refocus = false) => {
setOpen(false)
if (refocus) trigger.current?.focus()
}, [])
function toggle() {
if (open) close()
else show('none')
}
function onTriggerKey(event: KeyboardEvent) {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
show(event.key === 'ArrowDown' ? 'first' : 'last')
}
else if (event.key === 'Escape' && open) {
event.preventDefault()
close(true)
}
}
function onMenuKey(event: KeyboardEvent) {
const list = items()
const at = list.indexOf(document.activeElement as HTMLElement)
if (event.key === 'Escape') {
event.preventDefault()
close(true)
}
else if (event.key === 'Tab') {
close()
}
else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
const step = event.key === 'ArrowDown' ? 1 : -1
list[(at + step + list.length) % list.length]?.focus()
}
else if (event.key === 'Home' || event.key === 'End') {
event.preventDefault()
;(event.key === 'Home' ? list[0] : list.at(-1))?.focus()
}
}
useEffect(() => {
function outside(event: PointerEvent) {
if (root.current && !root.current.contains(event.target as Node)) setOpen(false)
}
document.addEventListener('pointerdown', outside)
return () => document.removeEventListener('pointerdown', outside)
}, [])
return { open, root, trigger, show, close, toggle, onTriggerKey, onMenuKey }
}// 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(' ')
}import { html, nothing, type PropertyValues } from 'lit'
import { styleMap } from 'lit/directives/style-map.js'
import { DsElement, define, uid } from '@/elements/lib/element'
import { CloseOnSelect, menuRows } from '@/elements/lib/menu'
import styles from 'virtual:tw'
// DropdownMenu.tsx as <spyglass-dropdown-menu>: a button that opens a short list of actions or choices on the #262626
// overlay surface, a neutral hairline, the 8px corner, no shadow, 4px inside; rows are <spyglass-menu-item>, with
// <spyglass-menu-label> and <spyglass-menu-separator> between groups. It comes in over 240ms (a 4px drop and a touch
// of scale from the trigger's edge), leaves at once, and does not animate when opened from the keyboard. Arrows, Home,
// End, Escape, Tab and a click outside are handled. The trigger: a <button slot="trigger"> you style yourself (React's
// triggerClass), or any other content in the `trigger` slot, drawn as a small secondary button. `open` opens it;
// show() and close() are React's handle.
/**
* @summary A button that opens a short list of choices or actions.
* @slot - The rows: <spyglass-menu-item>, <spyglass-menu-label>, <spyglass-menu-separator>.
* @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 DropdownMenu extends DsElement {
static styles = [DsElement.styles, styles]
static properties = {
label: {},
up: { type: Boolean },
// React's `align`; an `align` attribute is also HTML's old alignment hint, which the browser draws as text-align.
placement: {},
width: {},
offset: {},
triggerLabel: { attribute: 'trigger-label' },
open: { type: Boolean, reflect: true },
instant: { state: true },
}
/** The menu's name for assistive tech. */
label = ''
/** Opens upward. */
up = false
/** The panel's edge: start, or end to line up with the trigger's end (React's `align`). */
placement: 'start' | 'end' = 'start'
width = '240px'
/** Moves the panel in from its edge. */
offset = '0px'
/** The default trigger's name, when its content has none. */
triggerLabel?: string
open = false
private instant = false
private panelId = uid('menu')
private pending: 'first' | 'last' | 'none' | null = null
/** A <button slot="trigger"> the page drew, or the default trigger in the shadow root. */
constructor() {
super()
// A chosen row closes the menu and returns focus to the trigger.
new CloseOnSelect(this, () => this.close(true))
}
private get trigger(): HTMLElement | null {
const own = this.querySelector<HTMLElement>(':scope > button[slot="trigger"]')
return own ?? this.renderRoot.querySelector<HTMLElement>('button[data-trigger]')
}
private items() {
return menuRows(this)
}
show(focus: 'first' | 'last' | 'none' = 'first') {
this.pending = focus
this.instant = focus !== 'none'
this.setOpen(true)
// Already open (an arrow on the open menu's button), it still renders, and the row asked for takes focus.
this.requestUpdate()
}
close(refocus = false) {
this.setOpen(false)
if (refocus) this.trigger?.focus()
}
private setOpen(open: boolean) {
if (this.open === open) return
this.open = open
this.emit('open-change', { value: open })
}
private toggle = () => {
if (this.open) this.close()
else this.show('none')
}
private onTriggerKey = (event: KeyboardEvent) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
this.show(event.key === 'ArrowDown' ? 'first' : 'last')
} else if (event.key === 'Escape' && this.open) {
event.preventDefault()
this.close(true)
}
}
private onMenuKey = (event: KeyboardEvent) => {
const list = this.items()
const at = list.findIndex((i) => i.matches(':focus-within'))
if (event.key === 'Escape') {
event.preventDefault()
this.close(true)
} else if (event.key === 'Tab') {
// React takes the panel out of the page before the browser moves focus, so Tab from a row lands on the
// trigger; here the rows stay in the page (unslotted), so the element puts focus there itself.
if (!event.shiftKey) {
event.preventDefault()
this.close(true)
} else this.close()
} else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
const step = event.key === 'ArrowDown' ? 1 : -1
list[(at + step + list.length) % list.length]?.focus()
} else if (event.key === 'Home' || event.key === 'End') {
event.preventDefault()
;(event.key === 'Home' ? list[0] : list.at(-1))?.focus()
}
}
private outside = (event: PointerEvent) => {
if (this.open && !event.composedPath().includes(this)) this.close()
}
connectedCallback() {
super.connectedCallback()
document.addEventListener('pointerdown', this.outside)
}
disconnectedCallback() {
super.disconnectedCallback()
document.removeEventListener('pointerdown', this.outside)
this.wire(null)
}
// The page's own trigger button gets the menu button's attributes and handlers.
private wired: HTMLElement | null = null
private wire(button: HTMLElement | null) {
if (this.wired && this.wired !== button) {
this.wired.removeEventListener('click', this.toggle)
this.wired.removeEventListener('keydown', this.onTriggerKey)
}
if (button && this.wired !== button) {
button.addEventListener('click', this.toggle)
button.addEventListener('keydown', this.onTriggerKey)
button.setAttribute('aria-haspopup', 'menu')
}
this.wired = button
if (button) {
button.setAttribute('aria-expanded', String(this.open))
if (this.triggerLabel) button.setAttribute('aria-label', this.triggerLabel)
}
}
protected updated(changed: PropertyValues<this>) {
super.updated(changed)
this.wire(this.querySelector<HTMLElement>(':scope > button[slot="trigger"]'))
if (changed.has('open') && !this.open) this.instant = false
const focus = this.pending
this.pending = null
if (!this.open || !focus) return
// Opened at the fold it would land out of sight, and the button would seem to do nothing.
this.renderRoot.querySelector('[role="menu"]')?.scrollIntoView({ block: 'nearest' })
if (focus === 'none') return
const list = this.items()
;(focus === 'last' ? list.at(-1) : list[0])?.focus()
}
render() {
const own = !!this.querySelector(':scope > button[slot="trigger"]')
const panel = this.open
? html`<div id=${this.panelId} class="ds-menu" ?data-up=${this.up} data-align=${this.placement === 'end' ? 'end' : 'start'} ?data-instant=${this.instant} style=${styleMap({ width: this.width, [this.placement === 'end' ? 'right' : 'left']: this.offset, [this.up ? 'bottom' : 'top']: 'calc(100% + 4px)' })} role="menu" aria-label=${this.label} @keydown=${this.onMenuKey}><slot></slot></div>`
: nothing
const trigger = own
? html`<slot name="trigger"></slot>`
: html`<button data-trigger type="button" class="inline-flex h-control-sm cursor-pointer items-center gap-1.5 rounded-control bg-action-secondary px-3 type-ui-strong text-action-secondary-fg transition-[background-color] duration-160 ease-standard hover:bg-action-secondary-hover aria-expanded:bg-action-secondary-hover max-md:h-control-touch" aria-haspopup="menu" aria-expanded=${String(this.open)} aria-label=${this.triggerLabel ?? nothing} @click=${this.toggle} @keydown=${this.onTriggerKey}><slot name="trigger"></slot></button>`
return html`${trigger}${panel}`
}
}
define('dropdown-menu', DropdownMenu)/* The host is the menu's box (DropdownMenu.tsx's root div: relative inline-block), so a class on
<spyglass-dropdown-menu> lands on it as a class on <DropdownMenu> does. */
:host { @apply relative inline-block; }
/* DropdownMenu.tsx's styles. Opened from the keyboard, focus lands on a row at once: no animation. React reads that
from :has(:focus-visible), which cannot see rows slotted from the page, so the element marks the panel data-instant. */
.ds-menu { position: absolute; z-index: 40; display: flex; max-width: calc(100vw - 16px); flex-direction: column; padding: var(--ds-space-xs); 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); transform-origin: top left; animation: ds-menu-in var(--ds-duration-enter) var(--ds-easing-out) both; scroll-margin: 8px; }
.ds-menu[data-align="end"] { transform-origin: top right; }
.ds-menu[data-up] { transform-origin: bottom left; animation-name: ds-menu-up; }
.ds-menu[data-up][data-align="end"] { transform-origin: bottom right; }
.ds-menu:has(:focus-visible) { animation: none; }
.ds-menu > * { flex-shrink: 0; }
@keyframes ds-menu-in { from { opacity: 0; transform: translateY(-4px) scale(0.98); } }
@keyframes ds-menu-up { from { opacity: 0; transform: translateY(4px) scale(0.98); } }
@media (prefers-reduced-motion: reduce) { .ds-menu, .ds-menu[data-up] { animation-name: ds-menu-fade; } }
@keyframes ds-menu-fade { from { opacity: 0; } }
.ds-menu[data-instant] { animation: none; }import { html, LitElement } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define } from '@/elements/lib/element'
import styles from 'virtual:tw'
// MenuItem.tsx as <spyglass-menu-item>: one row of a dropdown or context menu: 32px (44px on phones), DM Sans 14px, a
// 4px corner; the row under the pointer or focus takes a #262626 fill. `current` sets it in Medium; `danger` is the
// red for leaving or deleting. Put a 16px Lucide icon first, a shortcut or a check last. Choosing it fires `select`
// and closes the menu around it (any element with lib/menu's CloseOnSelect), unless `keep-open`. `role` and
// `aria-checked` on the element move to its button (role="menuitemradio" aria-checked="true" for a radio row), or set
// the `itemRole` and `checked` properties.
/**
* @summary One row of a menu.
* @slot - The row: an icon, the label, a count or a check.
* @fires select - The row was chosen.
*/
export class MenuItem extends DsElement {
static styles = [DsElement.styles, styles]
static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
static properties = { href: {}, current: { type: Boolean }, danger: { type: Boolean }, disabled: { type: Boolean, reflect: true }, keepOpen: { type: Boolean, attribute: 'keep-open' }, itemRole: { attribute: false }, checked: { attribute: false } }
// role and aria-checked are read here and moved to the button, so the row is named once (a menuitemradio, checked or
// not) and not twice.
static get observedAttributes() {
return [...super.observedAttributes, 'role', 'aria-checked']
}
href?: string
/** The current choice, in Medium. */
current = false
/** The red for leaving or deleting. */
danger = false
disabled = false
/** Choosing it leaves the menu open. */
keepOpen = false
/** The button's role: menuitem, or menuitemradio and menuitemcheckbox (the `role` attribute). */
itemRole = 'menuitem'
/** A radio or checkbox row's state (the `aria-checked` attribute). */
checked?: boolean
attributeChangedCallback(name: string, old: string | null, value: string | null) {
if (name === 'role' || name === 'aria-checked') {
if (value === null) return
if (name === 'role') this.itemRole = value
else this.checked = value === 'true'
this.removeAttribute(name)
return
}
super.attributeChangedCallback(name, old, value)
}
private choose = () => {
this.emit('select')
}
render() {
const current = this.current ? 'true' : undefined
const checked = this.checked === undefined ? undefined : String(this.checked)
return this.href
? html`<a data-ds="menu-item" href=${this.href} role=${this.itemRole} class="flex h-control-sm w-full shrink-0 cursor-pointer items-center gap-2 rounded-ds-sm px-2 text-left type-ui text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4 aria-[current=true]:font-medium disabled:cursor-not-allowed disabled:text-fg-faint disabled:hover:bg-transparent data-danger:text-fg-danger data-danger:hover:bg-surface-danger data-danger:focus-visible:bg-surface-danger max-md:h-auto max-md:min-h-control-touch" aria-current=${ifDefined(current)} aria-checked=${ifDefined(checked)} ?data-danger=${this.danger} @click=${this.choose}><slot></slot></a>`
: html`<button data-ds="menu-item" type="button" role=${this.itemRole} class="flex h-control-sm w-full shrink-0 cursor-pointer items-center gap-2 rounded-ds-sm px-2 text-left type-ui text-fg outline-none transition-[background-color] duration-160 ease-standard hover:bg-ds-neutral-4 focus-visible:bg-ds-neutral-4 aria-[current=true]:font-medium disabled:cursor-not-allowed disabled:text-fg-faint disabled:hover:bg-transparent data-danger:text-fg-danger data-danger:hover:bg-surface-danger data-danger:focus-visible:bg-surface-danger max-md:h-auto max-md:min-h-control-touch" aria-current=${ifDefined(current)} aria-checked=${ifDefined(checked)} ?data-danger=${this.danger} ?disabled=${this.disabled} @click=${this.choose}><slot></slot></button>`
}
}
define('menu-item', MenuItem)import { html } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import styles from 'virtual:tw'
// MenuLabel.tsx as <spyglass-menu-label>: a group's name in a dropdown or context menu, a DM Sans Medium label in
// capitals with 6% tracking, muted.
/**
* @summary A group's name in a menu.
* @slot - The name.
*/
export class MenuLabel extends DsElement {
static styles = [DsElement.styles, styles]
render() {
return html`<p data-ds="menu-label" class="flex items-center justify-between gap-2 px-2 pt-2 pb-1 type-label text-fg-muted"><slot></slot></p>`
}
}
define('menu-label', MenuLabel)import { html } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import styles from 'virtual:tw'
// MenuSeparator.tsx as <spyglass-menu-separator>: a neutral hairline between a menu's groups, edge to edge.
/** @summary A hairline between a menu's groups. */
export class MenuSeparator extends DsElement {
static styles = [DsElement.styles, styles]
render() {
return html`<div data-ds="menu-separator" class="-mx-1 my-1 h-px bg-edge" role="separator"></div>`
}
}
define('menu-separator', MenuSeparator)Reference: Derived from the guidelines: the #262626 card fill on Black, neutral hairlines, the 10px canvas corner (8px here), DM Sans 14px rows and capital labels at 6%. shadcn's dropdown menu for anatomy and keys..