Components

Context menu

The dropdown menu's rows on the #262626 overlay panel, opened where the pointer right-clicks, or under the focused row with Shift+F10 or the menu key. Arrows, Home, End and Escape are handled; focus returns to what was clicked.

Install

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

npx spyglass-ds add context-menu
<script type="module" src="/spyglass-ds/elements/context-menu.js"></script>
A board's saved creatives
  • Acme summer UGC, before and afterVideo
  • Acme serum launch, carouselCarousel
  • Acme founder story, 30 secondsVideo

Right-click a creative, or focus it and press Shift+F10.

Usage

Shortcuts for a row in a dense list (open, copy a link, save, remove), alongside a visible way to do the same.

Never

  • The only way to an action: right-clicks are hidden; keep a dropdown menu or a button in the row
  • Destructive actions that don't confirm: confirm with an alert dialog
  • A shadow under the panel

Put data-context="<id>" on each row; onOpen (React) or the open event (web component) gets the id of the row that was clicked, so one menu serves the list. PopoverPanel is the floating panel every overlay here draws (the context menu, the combobox, the date picker): portalled, placed beside its anchor or the pointer, flipped to the side with room.

Adds with it: dropdown-menu, popover

Props

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

<ContextMenu>

PropTypeDefault
labelstring

The menu's name for assistive tech.

widthstring

The panel's width.

menuReactNode

The rows: MenuItem, MenuLabel, MenuSeparator.

onOpen(context: string | undefined) => void

It is opening, with the closest [data-context] value under the pointer.

childrenReactNode

Examples

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

react/examples/context-menu/Board.tsx
'use client'
import { useState } from 'react'
import { Bookmark, Copy, ExternalLink, Image, Trash2 } from 'lucide-react'
import { ContextMenu } from '@/react/components/ui/ContextMenu'
import { MenuItem } from '@/react/components/ui/MenuItem'
import { MenuLabel } from '@/react/components/ui/MenuLabel'
import { MenuSeparator } from '@/react/components/ui/MenuSeparator'
// A board's saved creatives: right-click a row, or focus it and press Shift+F10, for what you can do with it.
const creatives = [
  { id: 'cr_8f2k1', title: 'Acme summer UGC, before and after', format: 'Video' },
  { id: 'cr_3m9q7', title: 'Acme serum launch, carousel', format: 'Carousel' },
  { id: 'cr_5t0x2', title: 'Acme founder story, 30 seconds', format: 'Video' },
]

export default function Board() {
  const [picked, setPicked] = useState<string>()
  const [last, setLast] = useState('')
  const creative = creatives.find((c) => c.id === picked)
  const act = (what: string) => () => setLast(`${what}: ${creative?.title ?? ''}`)
  return (
    <div className="min-h-80 w-full max-w-120">
      <ContextMenu
        label="Creative"
        onOpen={setPicked}
        menu={(
          <>
            <MenuLabel><span className="truncate">{creative?.format}</span></MenuLabel>
            <MenuItem onSelect={act('Opened')}><ExternalLink size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />Open</MenuItem>
            <MenuItem onSelect={act('Copied link')}><Copy size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />Copy link</MenuItem>
            <MenuItem onSelect={act('Saved')}><Bookmark size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />Save to another board</MenuItem>
            <MenuSeparator />
            <MenuItem danger onSelect={act('Removed')}><Trash2 size={16} strokeWidth={1.5} className="shrink-0" aria-hidden="true" />Remove from board</MenuItem>
          </>
        )}
      >
        <ul className="flex flex-col gap-1">
          {creatives.map((c) => (
            <li key={c.id} data-context={c.id} tabIndex={0} className="flex h-row items-center gap-3 rounded-control px-3 outline-none transition-[background-color] duration-160 ease-standard hover:bg-surface-raised focus-visible:bg-surface-raised focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-edge-focus">
              <Image size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />
              <span className="min-w-0 flex-1 truncate type-ui">{c.title}</span>
              <span className="type-caption text-fg-muted max-sm:hidden">{c.format}</span>
            </li>
          ))}
        </ul>
      </ContextMenu>
      <p className="mt-3 type-caption text-fg-muted" aria-live="polite">{last || 'Right-click a creative, or focus it and press Shift+F10.'}</p>
    </div>
  )
}
elements/examples/context-menu/Board.html
<!-- A board's saved creatives: right-click a row, or focus it and press Shift+F10, for what you can do with it. -->
<div class="min-h-80 w-full max-w-120">
  <spyglass-context-menu label="Creative" id="creative-menu">
    <ul class="flex flex-col gap-1">
      <li data-context="cr_8f2k1" tabindex="0" class="flex h-row items-center gap-3 rounded-control px-3 outline-none transition-[background-color] duration-160 ease-standard hover:bg-surface-raised focus-visible:bg-surface-raised focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-edge-focus">
        <i data-lucide="image" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>
        <span class="min-w-0 flex-1 truncate type-ui">Acme summer UGC, before and after</span>
        <span class="type-caption text-fg-muted max-sm:hidden">Video</span>
      </li>
      <li data-context="cr_3m9q7" tabindex="0" class="flex h-row items-center gap-3 rounded-control px-3 outline-none transition-[background-color] duration-160 ease-standard hover:bg-surface-raised focus-visible:bg-surface-raised focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-edge-focus">
        <i data-lucide="image" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>
        <span class="min-w-0 flex-1 truncate type-ui">Acme serum launch, carousel</span>
        <span class="type-caption text-fg-muted max-sm:hidden">Carousel</span>
      </li>
      <li data-context="cr_5t0x2" tabindex="0" class="flex h-row items-center gap-3 rounded-control px-3 outline-none transition-[background-color] duration-160 ease-standard hover:bg-surface-raised focus-visible:bg-surface-raised focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-edge-focus">
        <i data-lucide="image" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>
        <span class="min-w-0 flex-1 truncate type-ui">Acme founder story, 30 seconds</span>
        <span class="type-caption text-fg-muted max-sm:hidden">Video</span>
      </li>
    </ul>
    <spyglass-menu-label slot="menu"><span class="truncate" data-format></span></spyglass-menu-label>
    <spyglass-menu-item slot="menu" data-note="Opened"><i data-lucide="external-link" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>Open</spyglass-menu-item>
    <spyglass-menu-item slot="menu" data-note="Copied link"><i data-lucide="copy" 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 slot="menu" data-note="Saved"><i data-lucide="bookmark" data-size="16" data-stroke-width="1.5" class="shrink-0 text-fg-muted" aria-hidden="true"></i>Save to another board</spyglass-menu-item>
    <spyglass-menu-separator slot="menu"></spyglass-menu-separator>
    <spyglass-menu-item slot="menu" danger data-note="Removed"><i data-lucide="trash-2" data-size="16" data-stroke-width="1.5" class="shrink-0" aria-hidden="true"></i>Remove from board</spyglass-menu-item>
  </spyglass-context-menu>
  <p id="creative-last" class="mt-3 type-caption text-fg-muted" aria-live="polite">Right-click a creative, or focus it and press Shift+F10.</p>
</div>
<script type="module">
  // The menu names the format of the creative it opened for; each row says what it did under the list.
  const menu = document.getElementById('creative-menu')
  let row
  menu.addEventListener('open', (event) => {
    row = menu.querySelector(`[data-context="${event.detail.context}"]`)
    menu.querySelector('[data-format]').textContent = row?.querySelector('.type-caption')?.textContent ?? ''
  })
  for (const item of menu.querySelectorAll('[data-note]')) {
    item.addEventListener('select', () => {
      document.getElementById('creative-last').textContent = `${item.dataset.note}: ${row?.querySelector('.truncate')?.textContent ?? ''}`
    })
  }
</script>

Source

react/components/ui/ContextMenu.tsx
'use client'
import type { KeyboardEvent, MouseEvent, ReactNode } from 'react'
import { MenuClose } from '@/react/components/ui/DropdownMenu'
import { PopoverPanel } from '@/react/components/ui/PopoverPanel'
import { onMenuRows, usePopover } from '@/react/hooks/usePopover'

// shadcn's context menu in the brand: the dropdown menu's rows (MenuItem, MenuLabel, MenuSeparator) on the #262626
// overlay panel, opened at the pointer: a right-click (or a long press on
// Android) on children opens `menu` where it landed, flipped and kept inside the viewport. From the keyboard,
// Shift+F10 or the context menu key opens it under the focused element, at once, on its first row. Arrows, Home and
// End move; Escape closes and returns focus; choosing a row closes it. `onOpen` gets what was clicked (the closest
// [data-context] value), so one menu serves a list.
export interface ContextMenuProps {
  /** The menu's name for assistive tech. */
  label: string
  /** The panel's width. */
  width?: string
  /** The rows: MenuItem, MenuLabel, MenuSeparator. */
  menu?: ReactNode
  /** It is opening, with the closest [data-context] value under the pointer. */
  onOpen?: (context: string | undefined) => void
  children?: ReactNode
}

function context(target: EventTarget | null) {
  return (target as HTMLElement | null)?.closest<HTMLElement>('[data-context]')?.dataset.context
}

export function ContextMenu({ label, width, menu, onOpen, children }: ContextMenuProps) {
  const pop = usePopover({ side: 'bottom', align: 'start', gap: 0 })

  async function onContextMenu(event: MouseEvent) {
    event.preventDefault()
    onOpen?.(context(event.target))
    await pop.show({ at: { x: event.clientX, y: event.clientY } })
    pop.panel.current?.focus({ preventScroll: true })
  }
  async function onKey(event: KeyboardEvent) {
    if (event.key !== 'ContextMenu' && !(event.shiftKey && event.key === 'F10')) return
    event.preventDefault()
    const r = (event.target as HTMLElement).getBoundingClientRect()
    onOpen?.(context(event.target))
    await pop.show({ keyboard: true, at: { x: r.left + 8, y: r.bottom } })
    pop.panel.current?.querySelector<HTMLElement>('[role^="menuitem"]:not([disabled])')?.focus()
  }
  return (
    <MenuClose.Provider value={() => pop.hide(true)}>
      <div data-ds="context-menu" onContextMenu={onContextMenu} onKeyDown={onKey}>
        {children}
      </div>
      <PopoverPanel data-ds="context-menu" pop={pop} role="menu" aria-label={label} tabIndex={-1} className="flex flex-col p-1" style={{ width: width ?? '224px' }} onKeyDown={event => onMenuRows(event, pop.panel.current, pop.hide)}>
        {menu}
      </PopoverPanel>
    </MenuClose.Provider>
  )
}

export default ContextMenu
elements/components/ui/context-menu.ts
import { html, nothing } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import { CloseOnSelect, menuRows, onMenuRows } from '@/elements/lib/menu'
import { PopoverController, popoverStyles } from '@/elements/lib/popover'
import styles from 'virtual:tw'

// ContextMenu.tsx as <spyglass-context-menu>: the dropdown menu's rows (<spyglass-menu-item>, <spyglass-menu-label>,
// <spyglass-menu-separator>, each with slot="menu") on the #262626 overlay panel, opened at the pointer: a right-click
// (or a long press on Android) on the default slot opens the `menu` slot where it landed, flipped and kept inside the
// viewport, in the top layer. From the keyboard, Shift+F10 or the context menu key opens it under the focused element,
// at once, on its first row. Arrows, Home and End move; Escape closes and returns focus; choosing a row closes it.
// `open` fires with what was clicked (detail.context: the closest [data-context] value), so one menu serves a list.

/**
 * @summary A menu opened at the pointer by a right-click or Shift+F10.
 * @slot - What the menu is for (a list whose rows carry data-context).
 * @slot menu - The rows: <spyglass-menu-item slot="menu">, labels and separators.
 * @fires open - It is opening (detail.context: the closest [data-context] value).
 */
export class ContextMenu extends DsElement {
	static styles = [DsElement.styles, popoverStyles, styles]
	static properties = { label: {}, width: {} }

	/** The menu's name for assistive tech. */
	label = ''
	width?: string
	private pop = new PopoverController(this, {
		side: 'bottom',
		align: 'start',
		gap: 0,
		anchor: () => null,
		panel: () => this.renderRoot.querySelector<HTMLElement>('.ds-pop'),
	})

	constructor() {
		super()
		// A chosen row closes the menu, focus back where it was.
		new CloseOnSelect(this, () => this.pop.hide(true))
	}

	private rows() {
		return menuRows(this, 'menu')
	}
	private context(event: Event) {
		return (event.composedPath()[0] as HTMLElement | null)?.closest?.<HTMLElement>('[data-context]')?.dataset.context
	}
	private onContextMenu = async (event: MouseEvent) => {
		event.preventDefault()
		this.emit('open', { context: this.context(event) })
		await this.pop.show({ at: { x: event.clientX, y: event.clientY } })
		this.renderRoot.querySelector<HTMLElement>('.ds-pop')?.focus({ preventScroll: true })
	}
	private onKey = async (event: KeyboardEvent) => {
		if (event.key !== 'ContextMenu' && !(event.shiftKey && event.key === 'F10')) return
		event.preventDefault()
		const r = (event.composedPath()[0] as HTMLElement).getBoundingClientRect()
		this.emit('open', { context: this.context(event) })
		await this.pop.show({ keyboard: true, at: { x: r.left + 8, y: r.bottom } })
		await this.updateComplete
		this.rows()[0]?.focus()
	}
	private onMenuKey = (event: KeyboardEvent) => {
		onMenuRows(event, this.rows(), (refocus) => this.pop.hide(refocus))
	}

	render() {
		const panel = this.pop.rendered
			? html`<div data-ds="context-menu" popover="manual" class="ds-pop flex flex-col p-1 fade-y" role="menu" 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 ?? '224px'}`)} @keydown=${this.onMenuKey} @focusout=${this.pop.onFocusOut}><slot name="menu"></slot></div>`
			: nothing
		return html`<div data-ds="context-menu" @contextmenu=${this.onContextMenu} @keydown=${this.onKey}><slot></slot></div>${panel}`
	}
}

define('context-menu', ContextMenu)

Reference: Derived from the guidelines: the #262626 card fill on Black, neutral hairlines, the 10px canvas corner (8px here). shadcn's context menu for anatomy and keys..