Components
Command
A box to type in over a list of actions and places, on the #262626 overlay surface: the field on top over a hairline, groups with a capital label, the menus' rows with an icon and a shortcut. On the page, or in a window opened with Cmd+K. The list scrolls with fading edges, so no row is cut off.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add command<script type="module" src="/spyglass-ds/elements/command.js"></script>Team needs an admin.
Press Cmd+K anywhere on the page.
Usage
Jumping anywhere and running anything from the keyboard: searches, boards, brands, settings. CommandDialog for the app-wide Cmd+K menu.
Never
- Motion on opening or closing: it opens many times a day
- Tab between rows: the field keeps focus and the arrows move
- A spectrum color on the highlighted row
- The only way to an action: keep it in the interface too
Rows are data: groups of { heading, items: [{ id, label, keywords, shortcut, icon, disabled }] }. In the web component, a row's icon is page content with slot="icon-<id>".
Adds with it: packages lucide-react
Props
The web component takes the same as attributes or properties (<spyglass-command>); title is heading there.
<Command>
| Prop | Type | Default |
|---|---|---|
groups | CommandGroup[] | |
label | string The list's name for assistive tech. | 'Commands' |
placeholder | string The field's placeholder. | 'Type a command or search' |
empty | string What the list says when nothing matches. | 'No results.' |
autoFocus | boolean Focus the field when it mounts. | |
onSelect | (item: CommandItem) => void | |
className | string |
<CommandDialog>
| Prop | Type | Default |
|---|---|---|
open | boolean | |
defaultOpen | boolean | false |
onOpenChange | (open: boolean) => void | |
shortcut | string | null The letter that opens it with Cmd or Ctrl; null for no shortcut. | 'k' |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useState } from 'react'
import { Bookmark, Building2, CreditCard, Search, Users } from 'lucide-react'
import { Command, type CommandGroup } from '@/react/components/ui/Command'
// The command menu on the page: type to filter, arrows to move, Enter to run. The line under says what ran.
const groups: CommandGroup[] = [
{ heading: 'Go to', items: [
{ id: 'search', label: 'Search creatives', icon: <Search size={16} strokeWidth={1.5} />, shortcut: '/' },
{ id: 'brands', label: 'Track a brand', keywords: ['creator', 'follow'], icon: <Building2 size={16} strokeWidth={1.5} /> },
{ id: 'boards', label: 'Boards', icon: <Bookmark size={16} strokeWidth={1.5} /> },
] },
{ heading: 'Boards', items: [
{ id: 'summer', label: 'Acme summer ads' },
{ id: 'serum', label: 'Acme serum launch' },
] },
{ heading: 'Settings', items: [
{ id: 'billing', label: 'Billing', keywords: ['plan', 'invoice'], icon: <CreditCard size={16} strokeWidth={1.5} />, shortcut: '⌘B' },
{ id: 'team', label: 'Team', icon: <Users size={16} strokeWidth={1.5} />, disabled: true },
] },
]
export default function Menu() {
const [ran, setRan] = useState('')
return (
<div className="flex w-120 max-w-full flex-col gap-3">
<Command groups={groups} label="Commands" placeholder="Type a command or search" onSelect={(item) => setRan(item.label)} />
<p className="type-caption text-fg-muted" aria-live="polite">{ran ? `Ran: ${ran}.` : 'Team needs an admin.'}</p>
</div>
)
}<!-- The command menu on the page: type to filter, arrows to move, Enter to run. The line under says what ran. -->
<div class="flex w-120 max-w-full flex-col gap-3">
<spyglass-command id="command-menu" label="Commands" placeholder="Type a command or search" groups='[{"heading":"Go to","items":[{"id":"search","label":"Search creatives","shortcut":"/"},{"id":"brands","label":"Track a brand","keywords":["creator","follow"]},{"id":"boards","label":"Boards"}]},{"heading":"Boards","items":[{"id":"summer","label":"Acme summer ads"},{"id":"serum","label":"Acme serum launch"}]},{"heading":"Settings","items":[{"id":"billing","label":"Billing","keywords":["plan","invoice"],"shortcut":"⌘B"},{"id":"team","label":"Team","disabled":true}]}]'>
<span slot="icon-search" class="contents"><i data-lucide="search" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-brands" class="contents"><i data-lucide="building-2" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-boards" class="contents"><i data-lucide="bookmark" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-billing" class="contents"><i data-lucide="credit-card" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-team" class="contents"><i data-lucide="users" data-size="16" data-stroke-width="1.5"></i></span>
</spyglass-command>
<p id="command-menu-ran" class="type-caption text-fg-muted" aria-live="polite">Team needs an admin.</p>
</div>
<script type="module">
document.getElementById('command-menu').addEventListener('select', (e) => {
document.getElementById('command-menu-ran').textContent = `Ran: ${e.detail.label}.`
})
</script>'use client'
import { useState } from 'react'
import { Bookmark, Building2, CreditCard, Search, Users } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { CommandDialog } from '@/react/components/ui/CommandDialog'
import type { CommandGroup } from '@/react/components/ui/Command'
// The command menu in a window: the button or Cmd+K opens it at once, Escape closes it, a row runs and closes it.
const groups: CommandGroup[] = [
{ heading: 'Go to', items: [
{ id: 'search', label: 'Search creatives', icon: <Search size={16} strokeWidth={1.5} />, shortcut: '/' },
{ id: 'brands', label: 'Track a brand', keywords: ['creator', 'follow'], icon: <Building2 size={16} strokeWidth={1.5} /> },
{ id: 'boards', label: 'Boards', icon: <Bookmark size={16} strokeWidth={1.5} /> },
] },
{ heading: 'Settings', items: [
{ id: 'billing', label: 'Billing', keywords: ['plan', 'invoice'], icon: <CreditCard size={16} strokeWidth={1.5} />, shortcut: '⌘B' },
{ id: 'team', label: 'Team', icon: <Users size={16} strokeWidth={1.5} /> },
] },
]
export default function Palette() {
const [open, setOpen] = useState(false)
const [ran, setRan] = useState('')
return (
<div className="flex min-h-96 flex-col items-center justify-center gap-3">
<Button variant="secondary" onClick={() => setOpen(true)}><Search size={16} strokeWidth={1.5} aria-hidden="true" />Search Spyglass<span className="type-caption text-fg-muted">⌘K</span></Button>
<p className="type-caption text-fg-muted" aria-live="polite">{ran ? `Ran: ${ran}.` : 'Press Cmd+K anywhere on the page.'}</p>
<CommandDialog open={open} onOpenChange={setOpen} groups={groups} onSelect={(item) => setRan(item.label)} />
</div>
)
}<!-- The command menu in a window: the button or Cmd+K opens it at once, Escape closes it, a row runs and closes it. -->
<div class="flex min-h-96 flex-col items-center justify-center gap-3">
<spyglass-button id="palette-open" variant="secondary"><i data-lucide="search" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Search Spyglass<span class="type-caption text-fg-muted">⌘K</span></spyglass-button>
<p id="palette-ran" class="type-caption text-fg-muted" aria-live="polite">Press Cmd+K anywhere on the page.</p>
<spyglass-command-dialog id="palette" groups='[{"heading":"Go to","items":[{"id":"search","label":"Search creatives","shortcut":"/"},{"id":"brands","label":"Track a brand","keywords":["creator","follow"]},{"id":"boards","label":"Boards"}]},{"heading":"Settings","items":[{"id":"billing","label":"Billing","keywords":["plan","invoice"],"shortcut":"⌘B"},{"id":"team","label":"Team"}]}]'>
<span slot="icon-search" class="contents"><i data-lucide="search" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-brands" class="contents"><i data-lucide="building-2" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-boards" class="contents"><i data-lucide="bookmark" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-billing" class="contents"><i data-lucide="credit-card" data-size="16" data-stroke-width="1.5"></i></span>
<span slot="icon-team" class="contents"><i data-lucide="users" data-size="16" data-stroke-width="1.5"></i></span>
</spyglass-command-dialog>
</div>
<script type="module">
const palette = document.getElementById('palette')
document.getElementById('palette-open').addEventListener('click', () => { palette.open = true })
palette.addEventListener('select', (e) => {
document.getElementById('palette-ran').textContent = `Ran: ${e.detail.label}.`
})
</script>Source
'use client'
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import { Search } from 'lucide-react'
// shadcn's command menu in the brand: a box to type in over a list of actions and places, on the #262626 overlay
// surface in a neutral hairline with the brand corner. The field sits on top over a hairline, DM Sans with a search
// glyph; groups have a capital label; rows are the menus' rows (32px, a 4px corner, a #262626 fill on the row the
// arrows or the pointer are on), an icon first and a shortcut last. The field keeps focus: typing filters (label and
// keywords), arrows move the highlight and wrap, Home and End jump, Enter runs the row, the pointer moves the
// highlight too. Nothing animates: it is used many times a day. `onSelect` gets the row. CommandDialog puts it in a
// window opened with Cmd+K.
export interface CommandItem {
id: string
label: string
/** More words that find it. */
keywords?: string[]
/** A key or chord shown at the end ("⌘B"). */
shortcut?: string
/** A 16px Lucide icon before the label. */
icon?: ReactNode
disabled?: boolean
}
export interface CommandGroup {
/** The group's label, in capitals. */
heading?: string
items: CommandItem[]
}
export interface CommandProps {
groups: CommandGroup[]
/** The list's name for assistive tech. */
label?: string
/** The field's placeholder. */
placeholder?: string
/** What the list says when nothing matches. */
empty?: string
/** Focus the field when it mounts. */
autoFocus?: boolean
onSelect?: (item: CommandItem) => void
className?: string
}
export const COMMAND_ROW = 'flex h-control-sm shrink-0 cursor-pointer items-center gap-2 rounded-ds-sm px-2 type-ui text-fg transition-[background-color] duration-160 ease-standard data-active:bg-ds-neutral-4 aria-disabled:cursor-not-allowed aria-disabled:text-fg-faint max-md:h-auto max-md:min-h-control-touch'
export function matches(item: CommandItem, q: string) {
if (!q) return true
const t = q.toLowerCase()
return item.label.toLowerCase().includes(t) || !!item.keywords?.some((k) => k.toLowerCase().includes(t))
}
export function Command({ groups, label = 'Commands', placeholder = 'Type a command or search', empty = 'No results.', autoFocus, onSelect, className }: CommandProps) {
const id = `command-${useId()}`
const input = useRef<HTMLInputElement | null>(null)
const [query, setQuery] = useState('')
const [activeId, setActiveId] = useState('')
const q = query.trim()
const shown = groups.map((g) => ({ ...g, items: g.items.filter((i) => matches(i, q)) })).filter((g) => g.items.length)
const rows = shown.flatMap((g) => g.items)
const enabled = rows.filter((r) => !r.disabled)
// The highlight is kept by id, so it stays on its row as the list changes; with none, the first enabled row.
const active = enabled.find((r) => r.id === activeId) ?? enabled[0]
const rowId = (item: CommandItem) => `${id}-${rows.indexOf(item)}`
useEffect(() => {
if (autoFocus) input.current?.focus({ preventScroll: true })
}, [autoFocus])
const scroll = useRef(false)
useEffect(() => {
if (!scroll.current || !active) return
scroll.current = false
document.getElementById(rowId(active))?.scrollIntoView({ block: 'nearest' })
})
function move(to: number) {
const n = enabled.length
if (!n) return
setActiveId(enabled[(to % n + n) % n]!.id)
scroll.current = true
}
function run(item: CommandItem | undefined) {
if (!item || item.disabled) return
onSelect?.(item)
}
function onKey(event: KeyboardEvent) {
const at = active ? enabled.indexOf(active) : -1
if (event.key === 'ArrowDown') { event.preventDefault(); move(at + 1) }
else if (event.key === 'ArrowUp') { event.preventDefault(); move(at - 1) }
else if (event.key === 'Home' && !query) { event.preventDefault(); move(0) }
else if (event.key === 'End' && !query) { event.preventDefault(); move(enabled.length - 1) }
else if (event.key === 'Enter') { event.preventDefault(); run(active) }
}
return (
<div data-ds="command" className={className ? `flex w-full flex-col overflow-hidden rounded-container border border-edge bg-surface-raised text-fg ${className}` : 'flex w-full flex-col overflow-hidden rounded-container border border-edge bg-surface-raised text-fg'}>
<label className="flex h-control-lg shrink-0 items-center gap-2 border-b border-edge px-3">
<Search size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />
<input
ref={input}
value={query}
onChange={(e) => { setQuery(e.target.value); setActiveId('') }}
className="h-full min-w-0 flex-1 bg-transparent type-ui text-fg outline-none placeholder:text-fg-muted max-md:text-input"
role="combobox"
aria-label={placeholder}
placeholder={placeholder}
aria-autocomplete="list"
aria-expanded="true"
aria-controls={`${id}-list`}
aria-activedescendant={active ? rowId(active) : undefined}
autoComplete="off"
spellCheck={false}
onKeyDown={onKey}
/>
</label>
<div id={`${id}-list`} role="listbox" aria-label={label} className="max-h-96 overflow-y-auto overscroll-contain p-1 fade-y">
{shown.map((g, gi) => (
<div key={g.heading ?? gi} role="group" aria-label={g.heading} className={gi ? '-mx-1 mt-1 border-t border-edge px-1 pt-1' : ''}>
{g.heading && <p className="px-2 pt-2 pb-1 type-label text-fg-muted" aria-hidden="true">{g.heading}</p>}
{g.items.map((item) => (
<div
key={item.id}
id={rowId(item)}
role="option"
className={COMMAND_ROW}
aria-selected={item === active}
aria-disabled={item.disabled || undefined}
data-active={item === active || undefined}
onPointerMove={() => { if (!item.disabled && item !== active) setActiveId(item.id) }}
onMouseDown={(e) => e.preventDefault()}
onClick={() => run(item)}
>
{item.icon && <span className="flex shrink-0 text-fg-muted" aria-hidden="true">{item.icon}</span>}
<span className="min-w-0 flex-1 truncate">{item.label}</span>
{item.shortcut && <span className="shrink-0 type-caption text-fg-faint">{item.shortcut}</span>}
</div>
))}
</div>
))}
{!rows.length && <p className="px-2 py-6 text-center type-ui text-fg-muted">{empty}</p>}
</div>
</div>
)
}
export default Command'use client'
import { useEffect, useRef, type SyntheticEvent, type MouseEvent } from 'react'
import { Command, type CommandItem, type CommandProps } from '@/react/components/ui/Command'
import { useControllable } from '@/react/hooks/useControllable'
// The command menu in a window, 15vh from the top over a Black scrim: Cmd+K (Ctrl+K) opens and closes it from anywhere
// on the page (`shortcut`, null for none), and so can your own button. It opens and closes at once, with no motion,
// because it opens many times a day. Focus starts in the field; Escape or a press on the scrim closes it and focus
// returns to what opened it; running a row closes it. The field is empty each time it opens. `open` with
// `onOpenChange` (or `defaultOpen` alone).
export interface CommandDialogProps extends Omit<CommandProps, 'autoFocus' | 'className'> {
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
/** The letter that opens it with Cmd or Ctrl; null for no shortcut. */
shortcut?: string | null
}
export function CommandDialog({ open: openProp, defaultOpen = false, onOpenChange, shortcut = 'k', onSelect, ...command }: CommandDialogProps) {
const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)
const dialog = useRef<HTMLDialogElement | null>(null)
const returnTo = useRef<HTMLElement | null>(null)
const toggle = useRef(() => setOpen(!open))
toggle.current = () => setOpen(!open)
useEffect(() => {
if (!shortcut) return
function onKey(event: globalThis.KeyboardEvent) {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === shortcut) {
event.preventDefault()
toggle.current()
}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [shortcut])
const mounted = useRef(false)
useEffect(() => {
const d = dialog.current
const first = !mounted.current
mounted.current = true
if (!d) return
if (open) {
if (d.open) return
returnTo.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
d.showModal()
d.querySelector<HTMLElement>('[role="combobox"]')?.focus()
}
else if (!first) {
if (d.open) d.close()
returnTo.current?.focus({ preventScroll: true })
returnTo.current = null
}
}, [open])
function onCancel(event: SyntheticEvent) {
event.preventDefault()
setOpen(false)
}
// A press on the scrim lands on the dialog element itself.
function onDown(event: MouseEvent) {
if (event.target === dialog.current) setOpen(false)
}
function picked(item: CommandItem) {
onSelect?.(item)
setOpen(false)
}
return (
<>
<style href="ds-command-dialog" precedence="ds">{css}</style>
<dialog data-ds="command-dialog" ref={dialog} className="ds-cmd" aria-label={command.label ?? 'Commands'} onCancel={onCancel} onMouseDown={onDown}>
{open && <Command {...command} onSelect={picked} />}
</dialog>
</>
)
}
export default CommandDialog
const css = `
/* No transition or animation: it opens and closes at once. */
.ds-cmd { position: fixed; inset: 15vh auto auto 50%; width: min(560px, calc(100vw - 32px)); max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: transparent; color: var(--ds-color-fg); font-family: var(--ds-font-text); overscroll-behavior: contain; transform: translateX(-50%); }
.ds-cmd::backdrop { background: var(--ds-color-scrim); }
`'use client'
import { useCallback, useRef, useState } from 'react'
// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
const [inner, setInner] = useState<T>(defaultValue)
const controlled = value !== undefined
const current = controlled ? value : inner
const ref = useRef(onChange)
ref.current = onChange
const set = useCallback((next: T) => {
if (!controlled) setInner(next)
ref.current?.(next)
}, [controlled])
return [current, set] as const
}import { html, nothing, type PropertyValues } from 'lit'
import { repeat } from 'lit/directives/repeat.js'
import { live } from 'lit/directives/live.js'
import { Search } from 'lucide'
import { DsElement, define, uid } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import styles from 'virtual:tw'
// Command.tsx as <spyglass-command>: a box to type in over a list of actions and places, on the #262626 overlay
// surface in a neutral hairline with the brand corner; the field on top over a hairline, groups with a capital label,
// the menus' rows with a #262626 fill on the row the arrows or the pointer are on. The field keeps focus: typing
// filters (label and keywords), arrows move the highlight and wrap, Home and End jump, Enter runs the row. Nothing
// animates. `groups` is a property or a JSON attribute ({ heading, items: [{ id, label, keywords, shortcut,
// disabled }] }); a row's icon is page content with slot="icon-<id>" (React's `icon`). `select` fires with the row.
export interface CommandItem { id: string, label: string, keywords?: string[], shortcut?: string, disabled?: boolean }
export interface CommandGroup { heading?: string, items: CommandItem[] }
const ROW = 'flex h-control-sm shrink-0 cursor-pointer items-center gap-2 rounded-ds-sm px-2 type-ui text-fg transition-[background-color] duration-160 ease-standard data-active:bg-ds-neutral-4 aria-disabled:cursor-not-allowed aria-disabled:text-fg-faint max-md:h-auto max-md:min-h-control-touch'
function matches(item: CommandItem, q: string) {
if (!q) return true
const t = q.toLowerCase()
return item.label.toLowerCase().includes(t) || !!item.keywords?.some((k) => k.toLowerCase().includes(t))
}
/**
* @summary A box to type in over a list of actions and places.
* @slot icon-<id> - The icon of the row with that id (a 16px Lucide icon).
* @fires select - A row was run (detail: the row).
*/
export class Command extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { groups: { type: Array }, label: {}, placeholder: {}, empty: {}, autoFocus: { type: Boolean, attribute: 'auto-focus' }, query: { state: true }, activeId: { state: true } }
groups: CommandGroup[] = []
/** The list's name for assistive tech. */
label = 'Commands'
/** The field's placeholder. */
placeholder = 'Type a command or search'
/** What the list says when nothing matches. */
empty = 'No results.'
/** Focus the field when it first renders (the auto-focus attribute). */
autoFocus = false
private query = ''
private activeId = ''
private listId = uid('command')
private scrollPending = false
/** Focuses the field. */
focus(options?: FocusOptions) {
this.renderRoot.querySelector<HTMLInputElement>('input')?.focus(options)
}
/** Empties the field. */
reset() {
this.query = ''
this.activeId = ''
}
private get shown() {
const q = this.query.trim()
return (this.groups ?? []).map((g) => ({ ...g, items: g.items.filter((i) => matches(i, q)) })).filter((g) => g.items.length)
}
protected firstUpdated() {
if (this.autoFocus) this.focus({ preventScroll: true })
}
protected updated(changed: PropertyValues) {
super.updated(changed)
if (!this.scrollPending) return
this.scrollPending = false
this.renderRoot.querySelector('[data-active]')?.scrollIntoView({ block: 'nearest' })
}
render() {
const shown = this.shown
const rows = shown.flatMap((g) => g.items)
const enabled = rows.filter((r) => !r.disabled)
const active = enabled.find((r) => r.id === this.activeId) ?? enabled[0]
const rowId = (item: CommandItem) => `${this.listId}-${rows.indexOf(item)}`
const move = (to: number) => {
const n = enabled.length
if (!n) return
this.activeId = enabled[(to % n + n) % n]!.id
this.scrollPending = true
}
const run = (item: CommandItem | undefined) => {
if (!item || item.disabled) return
this.emit('select', item)
}
const onKey = (event: KeyboardEvent) => {
const at = active ? enabled.indexOf(active) : -1
if (event.key === 'ArrowDown') { event.preventDefault(); move(at + 1) }
else if (event.key === 'ArrowUp') { event.preventDefault(); move(at - 1) }
else if (event.key === 'Home' && !this.query) { event.preventDefault(); move(0) }
else if (event.key === 'End' && !this.query) { event.preventDefault(); move(enabled.length - 1) }
else if (event.key === 'Enter') { event.preventDefault(); run(active) }
}
return html`<div data-ds="command" class="flex w-full flex-col overflow-hidden rounded-container border border-edge bg-surface-raised text-fg">
<label class="flex h-control-lg shrink-0 items-center gap-2 border-b border-edge px-3">
${icon(Search, 'search', { size: 16, strokeWidth: 1.5, class: 'shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}
<input .value=${live(this.query)} class="h-full min-w-0 flex-1 bg-transparent type-ui text-fg outline-none placeholder:text-fg-muted max-md:text-input" role="combobox" aria-label=${this.placeholder} placeholder=${this.placeholder} aria-autocomplete="list" aria-expanded="true" aria-controls=${`${this.listId}-list`} aria-activedescendant=${active ? rowId(active) : nothing} autocomplete="off" spellcheck="false" @input=${(e: Event) => { this.query = (e.target as HTMLInputElement).value; this.activeId = '' }} @keydown=${onKey}>
</label>
<div id=${`${this.listId}-list`} role="listbox" aria-label=${this.label} class="max-h-96 overflow-y-auto overscroll-contain p-1 fade-y">
${shown.map((g, gi) => html`<div role="group" aria-label=${g.heading ?? nothing} class=${gi ? '-mx-1 mt-1 border-t border-edge px-1 pt-1' : ''}>
${g.heading ? html`<p class="px-2 pt-2 pb-1 type-label text-fg-muted" aria-hidden="true">${g.heading}</p>` : nothing}
${repeat(g.items, (item) => item.id, (item) => html`<div id=${rowId(item)} role="option" class=${ROW} aria-selected=${String(item === active)} aria-disabled=${item.disabled ? 'true' : nothing} ?data-active=${item === active} @pointermove=${() => { if (!item.disabled && item !== active) this.activeId = item.id }} @mousedown=${(e: Event) => e.preventDefault()} @click=${() => run(item)}>${this.hasSlot(`icon-${item.id}`) ? html`<span class="flex shrink-0 text-fg-muted" aria-hidden="true"><slot name=${`icon-${item.id}`}></slot></span>` : nothing}<span class="min-w-0 flex-1 truncate">${item.label}</span>${item.shortcut ? html`<span class="shrink-0 type-caption text-fg-faint">${item.shortcut}</span>` : nothing}</div>`)}
</div>`)}
${!rows.length ? html`<p class="px-2 py-6 text-center type-ui text-fg-muted">${this.empty}</p>` : nothing}
</div>
</div>`
}
}
define('command', Command)import { html, nothing, type PropertyValues } from 'lit'
import { DsElement, define, tag, tagName } from '@/elements/lib/element'
import { html as staticHtml } from 'lit/static-html.js'
import '@/elements/components/ui/command'
import type { CommandGroup } from '@/elements/components/ui/command'
import styles from 'virtual:tw'
// CommandDialog.tsx as <spyglass-command-dialog>: the command menu in a window, 15vh from the top over a Black scrim.
// Cmd+K (Ctrl+K) opens and closes it from anywhere on the page (`shortcut`, "" for none), and so can the `open`
// attribute. It opens and closes at once, with no motion. Focus starts in the field; Escape or a press on the scrim
// closes it and focus returns to what opened it; running a row closes it (the row's `select` event reaches the page).
// The field is empty each time it opens. Row icons are page content with slot="icon-<id>", as on <spyglass-command>.
/**
* @summary The command menu in a window opened with Cmd+K.
* @slot icon-<id> - The icon of the row with that id.
* @fires select - A row was run (detail: the row), from the inner command menu.
* @fires open-change - It opened or closed (detail.value).
*/
export class CommandDialog extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { groups: { type: Array }, label: {}, placeholder: {}, empty: {}, shortcut: {}, open: { type: Boolean, reflect: true } }
groups: CommandGroup[] = []
label = 'Commands'
placeholder = 'Type a command or search'
empty = 'No results.'
/** The letter that opens it with Cmd or Ctrl; "" for no shortcut. */
shortcut = 'k'
open = false
private returnTo: HTMLElement | null = null
private get dialog() {
return this.renderRoot.querySelector('dialog')
}
private setOpen(open: boolean) {
if (this.open === open) return
this.open = open
this.emit('open-change', { value: open })
}
private onKey = (event: KeyboardEvent) => {
if (this.shortcut && (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === this.shortcut) {
event.preventDefault()
this.setOpen(!this.open)
}
}
connectedCallback() {
super.connectedCallback()
document.addEventListener('keydown', this.onKey)
}
disconnectedCallback() {
super.disconnectedCallback()
document.removeEventListener('keydown', this.onKey)
}
protected async updated(changed: PropertyValues<this>) {
super.updated(changed)
if (!changed.has('open')) return
const d = this.dialog
if (!d) return
if (this.open) {
if (d.open) return
let a = document.activeElement as Element | null
while (a?.shadowRoot?.activeElement) a = a.shadowRoot.activeElement
this.returnTo = a instanceof HTMLElement ? a : null
d.showModal()
const command = d.querySelector(tagName('command')) as (HTMLElement & { updateComplete: Promise<unknown> }) | null
await command?.updateComplete
command?.focus()
} else if (changed.get('open') !== undefined) {
if (d.open) d.close()
this.returnTo?.focus({ preventScroll: true })
this.returnTo = null
}
}
private onCancel = (event: Event) => {
event.preventDefault()
this.setOpen(false)
}
// A press on the scrim lands on the dialog element itself.
private onDown = (event: MouseEvent) => {
if (event.target === this.dialog) this.setOpen(false)
}
render() {
const command = tag('command')
// The page's row icons pass through to the inner command menu.
const icons = [...this.children].map((c) => c.getAttribute('slot')).filter((s): s is string => !!s?.startsWith('icon-'))
return html`<dialog data-ds="command-dialog" class="ds-cmd" aria-label=${this.label} @cancel=${this.onCancel} @mousedown=${this.onDown} @select=${() => this.setOpen(false)}>
${this.open ? staticHtml`<${command} .groups=${this.groups} label=${this.label} placeholder=${this.placeholder} empty=${this.empty}>${icons.map((s) => html`<slot name=${s} slot=${s}></slot>`)}</${command}>` : nothing}
</dialog>`
}
}
define('command-dialog', CommandDialog)/* CommandDialog.tsx's styles. No transition or animation: it opens and closes at once. */
.ds-cmd { position: fixed; inset: 15vh auto auto 50%; width: min(560px, calc(100vw - 32px)); max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: transparent; color: var(--ds-color-fg); font-family: var(--ds-font-text); overscroll-behavior: contain; transform: translateX(-50%); }
.ds-cmd::backdrop { background: var(--ds-color-scrim); }Reference: Derived from the guidelines: the #262626 card fill on Black, neutral hairlines, the 10px canvas corner (8px here), DM Sans 14px rows, capital labels at 6%. shadcn's command (cmdk) for anatomy, filtering and keys..