Components

Combobox

A field-like trigger that opens a list to pick one option from, with a filter over it, on the #262626 overlay panel: the menus' rows, a #262626 fill on the row the arrows or the pointer are on, the pick checked at the end. 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 combobox
<script type="module" src="/spyglass-ds/elements/combobox.js"></script>
With a filter

Search one category at a time.

A plain listbox

Usage

One choice from a list long enough to filter: a category, a brand, a board. With the filter off it is a plain listbox for a handful of options.

Never

  • Many picks at once: it holds one value
  • Writing your own arrow, Escape or outside-press handling
  • A shadow under the panel, or a spectrum color on the highlighted row

The value is value with onValueChange (React) or the value property with change (web component). pinned options stay above a hairline and are never filtered ("All formats").

Adds with it: popover packages lucide-react

Props

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

<Combobox>

PropTypeDefault
optionsComboOption[]
labelstring

The list's name for assistive tech (and the trigger's).

placeholderstring

What the trigger says before a pick.

filterboolean | 'auto'

The filter at the top: on, off (a plain listbox), or 'auto' past six options.

filterLabelstring

The filter's placeholder and name.

widthstring

The panel's width.

sideSide
alignAlign
matchWidthboolean

At least as wide as the trigger.

triggerClassstring

Classes for the trigger, in place of the field look.

disabledboolean
valuestring | number
defaultValuestring | number
onValueChange(value: string | number) => void
onSelect(option: ComboOption) => void
trigger(slot: { selected?: ComboOption, open: boolean }) => ReactNode
option(slot: { option: ComboOption, selected: boolean }) => ReactNode
empty(query: string) => ReactNode
idstring
aria-describedbystring
data-dsstring

Examples

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

react/examples/combobox/Category.tsx
'use client'
import { useState } from 'react'
import { Combobox } from '@/react/components/ui/Combobox'
// Pick a category to search in: type to narrow the list, arrows to move, Enter to pick. Counts are creatives tracked.
const categories = [
  { value: 'skincare', label: 'Skincare', hint: '12.4k' },
  { value: 'supplements', label: 'Supplements', hint: '8.1k' },
  { value: 'apparel', label: 'Apparel', hint: '6.9k' },
  { value: 'beverages', label: 'Beverages', hint: '5.2k' },
  { value: 'fitness', label: 'Fitness', hint: '4.7k' },
  { value: 'home', label: 'Home', hint: '3.3k' },
  { value: 'pets', label: 'Pets', hint: '2.8k' },
]

export default function Category() {
  const [picked, setPicked] = useState('')
  return (
    <div className="flex h-96 w-72 max-w-full flex-col gap-2">
      <label htmlFor="combobox-category" className="type-label text-fg-soft">Category</label>
      <Combobox id="combobox-category" value={picked} onValueChange={(v) => setPicked(String(v))} options={categories} label="Category" placeholder="Choose a category" filterLabel="Filter categories" matchWidth />
      <p className="type-caption text-fg-muted" aria-live="polite">{picked ? `Searching ${categories.find((c) => c.value === picked)?.label} creatives.` : 'Search one category at a time.'}</p>
    </div>
  )
}
elements/examples/combobox/Category.html
<!-- Pick a category to search in: type to narrow the list, arrows to move, Enter to pick. Counts are creatives tracked. -->
<div class="flex h-96 w-72 max-w-full flex-col gap-2">
  <label for="combobox-category" class="type-label text-fg-soft">Category</label>
  <spyglass-combobox id="combobox-category" value="" label="Category" placeholder="Choose a category" filter-label="Filter categories" match-width></spyglass-combobox>
  <p id="combobox-category-note" class="type-caption text-fg-muted" aria-live="polite">Search one category at a time.</p>
</div>
<script type="module">
  await customElements.whenDefined('spyglass-combobox')
  const categories = [
    { value: 'skincare', label: 'Skincare', hint: '12.4k' },
    { value: 'supplements', label: 'Supplements', hint: '8.1k' },
    { value: 'apparel', label: 'Apparel', hint: '6.9k' },
    { value: 'beverages', label: 'Beverages', hint: '5.2k' },
    { value: 'fitness', label: 'Fitness', hint: '4.7k' },
    { value: 'home', label: 'Home', hint: '3.3k' },
    { value: 'pets', label: 'Pets', hint: '2.8k' },
  ]
  const box = document.getElementById('combobox-category')
  box.options = categories
  box.addEventListener('change', () => {
    document.getElementById('combobox-category-note').textContent = `Searching ${categories.find((c) => c.value === box.value)?.label} creatives.`
  })
</script>
react/examples/combobox/Format.tsx
import { Combobox } from '@/react/components/ui/Combobox'
// A short list needs no filter: a plain listbox. Typing a letter jumps to the format it starts.
const formats = [
  { value: 'all', label: 'All formats', pinned: true },
  { value: 'video', label: 'Video' },
  { value: 'image', label: 'Image' },
  { value: 'carousel', label: 'Carousel' },
  { value: 'ugc', label: 'UGC' },
]

export default function Format() {
  return (
    <div className="h-72 w-56 max-w-full">
      <Combobox defaultValue="all" options={formats} label="Format" filter={false} matchWidth />
    </div>
  )
}
elements/examples/combobox/Format.html
<!-- A short list needs no filter: a plain listbox. Typing a letter jumps to the format it starts. -->
<div class="h-72 w-56 max-w-full">
  <spyglass-combobox value="all" label="Format" filter="false" match-width options='[{"value":"all","label":"All formats","pinned":true},{"value":"video","label":"Video"},{"value":"image","label":"Image"},{"value":"carousel","label":"Carousel"},{"value":"ugc","label":"UGC"}]'></spyglass-combobox>
</div>

Source

react/components/ui/Combobox.tsx
'use client'
import { Fragment, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react'
import { Check, ChevronsUpDown, Search } from 'lucide-react'
import { PopoverPanel } from '@/react/components/ui/PopoverPanel'
import { usePopover, type Align, type Side } from '@/react/hooks/usePopover'
import { useControllable } from '@/react/hooks/useControllable'

// shadcn's combobox in the brand: a field-like trigger (the input's #666666 hairline, White on focus, the brand
// corner) that opens a list to pick one option from, with a filter over it, on the #262626 overlay panel. Rows are the
// menus' rows: 32px, DM Sans 14px, a 4px corner and a #262626 fill on the row the arrows or the pointer are on (the
// highlight follows both, so hover draws nothing of its own), the pick checked at the end. The filter sits at the top
// over a neutral hairline; `filter: 'auto'` shows it past six options, and `false` makes it a plain listbox. `pinned`
// options stay above a hairline and are never filtered. Arrows, Home and End move, Enter picks, typing filters (or,
// with no filter, jumps to the option it starts), Escape closes and returns focus to the trigger. The panel portals,
// flips and stays inside the viewport. Render props: `trigger` ({ selected, open }), `option` ({ option, selected }),
// `empty` (query). The value is `value` with `onValueChange` (or `defaultValue`); `onSelect` gets the option. Other
// props (id, aria-describedby) land on the trigger.
export interface ComboOption {
  value: string | number
  label: string
  /** A count or a note at the end of the row. */
  hint?: string
  disabled?: boolean
  /** Stays above a hairline and is never filtered. */
  pinned?: boolean
}
export interface ComboboxProps {
  options: ComboOption[]
  /** The list's name for assistive tech (and the trigger's). */
  label: string
  /** What the trigger says before a pick. */
  placeholder?: string
  /** The filter at the top: on, off (a plain listbox), or 'auto' past six options. */
  filter?: boolean | 'auto'
  /** The filter's placeholder and name. */
  filterLabel?: string
  /** The panel's width. */
  width?: string
  side?: Side
  align?: Align
  /** At least as wide as the trigger. */
  matchWidth?: boolean
  /** Classes for the trigger, in place of the field look. */
  triggerClass?: string
  disabled?: boolean
  value?: string | number
  defaultValue?: string | number
  onValueChange?: (value: string | number) => void
  onSelect?: (option: ComboOption) => void
  trigger?: (slot: { selected?: ComboOption, open: boolean }) => ReactNode
  option?: (slot: { option: ComboOption, selected: boolean }) => ReactNode
  empty?: (query: string) => ReactNode
  id?: string
  'aria-describedby'?: string
  'data-ds'?: string
}

export function Combobox(props: ComboboxProps) {
  const { options, label, placeholder = 'Choose', filter = true, filterLabel = 'Filter', width, side = 'bottom', align = 'start', matchWidth, triggerClass, disabled, value, defaultValue = '', onValueChange, onSelect, trigger, option, empty, 'data-ds': ds = 'combobox', ...attrs } = props
  const [model, setModel] = useControllable(value, defaultValue, onValueChange)
  const pop = usePopover({ side, align, matchWidth, gap: 4 })
  const id = `combobox-${useId()}`
  const [query, setQuery] = useState('')
  const [active, setActive] = useState(0)
  const input = useRef<HTMLInputElement | null>(null)
  const list = useRef<HTMLDivElement | null>(null)

  const filtering = filter === 'auto' ? options.filter(o => !o.pinned).length > 6 : filter
  const selected = options.find(o => o.value === model)
  const pinned = options.filter(o => o.pinned)
  const rest = useMemo(() => {
    const q = query.trim().toLowerCase()
    const all = options.filter(o => !o.pinned)
    return q ? all.filter(o => o.label.toLowerCase().includes(q)) : all
  }, [options, query])
  const visible = [...pinned, ...rest]
  const optionId = (i: number) => `${id}-${i}`

  const enabled = (i: number) => !visible[i]?.disabled
  function move(to: number, step = 1, among = visible) {
    const n = among.length
    if (!n) return
    for (let k = 0; k < n; k++) {
      const i = ((to + k * step) % n + n) % n
      if (!among[i]?.disabled) {
        setActive(i)
        requestAnimationFrame(() => document.getElementById(optionId(i))?.scrollIntoView({ block: 'nearest' }))
        return
      }
    }
  }
  const firstQuery = useRef(true)
  useEffect(() => {
    if (firstQuery.current) { firstQuery.current = false; return }
    move(0)
  }, [query]) // eslint-disable-line react-hooks/exhaustive-deps

  async function open(keyboard: boolean) {
    setQuery('')
    await pop.show({ keyboard })
    const all = [...pinned, ...options.filter(o => !o.pinned)]
    const at = all.findIndex(o => o.value === model)
    move(at >= 0 ? at : 0, 1, all)
    ;(filtering ? input.current : list.current)?.focus({ preventScroll: true })
  }
  function pick(o: ComboOption | undefined, keyboard: boolean) {
    if (!o || o.disabled) return
    setModel(o.value)
    onSelect?.(o)
    pop.hide(true, keyboard)
  }
  function onTrigger(event: MouseEvent) {
    if (pop.open) pop.hide(false, event.detail === 0)
    else void open(event.detail === 0)
  }
  function onTriggerKey(event: KeyboardEvent) {
    if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && !pop.open) {
      event.preventDefault()
      void open(true)
    }
  }
  // With no filter, typing jumps to the option that starts with what was typed in the last half second.
  const typed = useRef({ text: '', at: 0 })
  function onKey(event: KeyboardEvent) {
    const k = event.key
    if (k === 'ArrowDown' || k === 'ArrowUp') {
      event.preventDefault()
      move(active + (k === 'ArrowDown' ? 1 : -1), k === 'ArrowDown' ? 1 : -1)
    }
    else if ((k === 'Home' || k === 'End') && !filtering) {
      event.preventDefault()
      move(k === 'Home' ? 0 : visible.length - 1, k === 'Home' ? 1 : -1)
    }
    else if (k === 'Enter' || (k === ' ' && !filtering)) {
      event.preventDefault()
      pick(visible[active], true)
    }
    else if (!filtering && k.length === 1 && !event.metaKey && !event.ctrlKey && !event.altKey) {
      const now = Date.now()
      typed.current.text = now - typed.current.at > 500 ? k.toLowerCase() : typed.current.text + k.toLowerCase()
      typed.current.at = now
      const i = visible.findIndex(o => !o.disabled && o.label.toLowerCase().startsWith(typed.current.text))
      if (i >= 0) move(i)
    }
  }
  const activeId = pop.open && visible.length ? optionId(active) : undefined

  return (
    <>
      <button
        data-ds={ds}
        {...attrs}
        ref={(el) => { pop.anchor.current = el }}
        type="button"
        className={triggerClass ?? 'group inline-flex h-control-md w-full min-w-0 cursor-pointer items-center gap-2 rounded-control border border-edge-strong bg-surface-subtle px-3 text-left type-ui text-fg outline-none transition-[border-color] duration-160 ease-standard hover:not-disabled:border-action-secondary-edge-hover focus-visible:border-edge-focus aria-expanded:border-edge-focus disabled:cursor-not-allowed disabled:text-fg-faint max-md:h-control-touch max-md:text-input pointer-coarse:h-control-touch'}
        aria-haspopup="listbox"
        aria-expanded={pop.open}
        aria-controls={pop.open ? `${id}-list` : undefined}
        aria-label={label}
        disabled={disabled}
        onClick={onTrigger}
        onKeyDown={onTriggerKey}
      >
        {trigger
          ? trigger({ selected, open: pop.open })
          : (
              <>
                <span className={selected ? 'min-w-0 flex-1 truncate' : 'min-w-0 flex-1 truncate text-fg-muted'}>{selected?.label ?? placeholder}</span>
                <ChevronsUpDown size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />
              </>
            )}
      </button>
      <PopoverPanel data-ds="combobox" pop={pop} className="flex flex-col p-1" style={{ width }}>
        {filtering && (
          <label className="-mx-1 -mt-1 mb-1 flex h-control-md items-center gap-2 border-b border-edge px-3">
            <Search size={16} strokeWidth={1.5} className="pointer-events-none shrink-0 text-fg-muted" aria-hidden="true" />
            <input
              ref={input}
              value={query}
              onChange={e => setQuery(e.target.value)}
              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={filterLabel}
              placeholder={filterLabel}
              aria-autocomplete="list"
              aria-expanded="true"
              aria-controls={`${id}-list`}
              aria-activedescendant={activeId}
              autoComplete="off"
              spellCheck={false}
              onKeyDown={onKey}
            />
          </label>
        )}
        <div
          id={`${id}-list`}
          ref={list}
          role="listbox"
          aria-label={label}
          tabIndex={filtering ? -1 : 0}
          aria-activedescendant={filtering ? undefined : activeId}
          className="flex max-h-65 flex-col overflow-y-auto outline-none fade-y"
          onKeyDown={onKey}
        >
          {visible.map((o, i) => (
            <Fragment key={`${o.pinned ? 'p' : 'o'}-${o.value}`}>
              {i === pinned.length && pinned.length > 0 && rest.length > 0 && <div className="-mx-1 my-1 h-px shrink-0 bg-edge" role="separator" />}
              <div
                id={optionId(i)}
                role="option"
                className="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"
                aria-selected={o.value === model}
                aria-disabled={o.disabled || undefined}
                data-active={i === active || undefined}
                onPointerMove={() => { if (!o.disabled) setActive(i) }}
                onMouseDown={e => e.preventDefault()}
                onClick={() => pick(o, false)}
              >
                {option
                  ? option({ option: o, selected: o.value === model })
                  : (
                      <>
                        <span className="min-w-0 flex-1 truncate">{o.label}</span>
                        {o.hint && <span className="min-w-10 text-right type-caption text-fg-muted tabular-nums">{o.hint}</span>}
                        <Check size={16} strokeWidth={1.5} className={o.value !== model ? 'shrink-0 invisible' : 'shrink-0'} aria-hidden="true" />
                      </>
                    )}
              </div>
            </Fragment>
          ))}
          {!rest.length && query && <p className="px-2 py-2 type-ui text-fg-muted">{empty ? empty(query) : `Nothing matches "${query}".`}</p>}
        </div>
      </PopoverPanel>
    </>
  )
}

export default Combobox
react/hooks/useControllable.ts
'use client'
import { useCallback, useRef, useState } from 'react'

// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
	const [inner, setInner] = useState<T>(defaultValue)
	const controlled = value !== undefined
	const current = controlled ? value : inner
	const ref = useRef(onChange)
	ref.current = onChange
	const set = useCallback((next: T) => {
		if (!controlled) setInner(next)
		ref.current?.(next)
	}, [controlled])
	return [current, set] as const
}
elements/components/ui/combobox.ts
import { html, LitElement, nothing, type PropertyValues, type TemplateResult } from 'lit'
import { repeat } from 'lit/directives/repeat.js'
import { Check, ChevronsUpDown, Search } from 'lucide'
import { DsFormElement, define, uid } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import { PopoverController, popoverStyles, type Align, type Side } from '@/elements/lib/popover'
import styles from 'virtual:tw'

// Combobox.tsx as <spyglass-combobox>: a field-like trigger that opens a list to pick one option from, with a filter
// over it, on the #262626 overlay panel; rows are the menus' rows with a #262626 fill on the row the arrows or the
// pointer are on, the pick checked at the end. `filter="auto"` shows the filter past six options, `filter="false"`
// makes it a plain listbox. `pinned` options stay above a hairline and are never filtered. Arrows, Home and End move,
// Enter picks, typing filters (or, with no filter, jumps to the option it starts), Escape closes and returns focus to
// the trigger. The panel opens in the top layer, flips and stays inside the viewport. The value is `value` with
// `input` and `change`; `select` fires with the option. Form-associated. React's `trigger` and `option` render props
// are methods a subclass overrides (renderTrigger, renderOption).
export interface ComboOption { value: string | number, label: string, hint?: string, disabled?: boolean, pinned?: boolean }

/**
 * @summary A list to pick one option from, with a filter over it.
 * @fires input - The pick changed (read `value`).
 * @fires change - The pick changed (read `value`).
 * @fires select - An option was picked (detail: the option).
 */
export class Combobox extends DsFormElement {
	static styles = [DsFormElement.styles, popoverStyles, styles]
	static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
	static properties = {
		value: {},
		options: { type: Array },
		label: {},
		placeholder: {},
		filter: { converter: (v: string | null) => (v === 'auto' ? 'auto' : v !== 'false') },
		filterLabel: { attribute: 'filter-label' },
		width: {},
		side: {},
		align: {},
		matchWidth: { type: Boolean, attribute: 'match-width' },
		disabled: { type: Boolean, reflect: true },
		name: {},
		required: { type: Boolean },
		description: { attribute: 'aria-description' },
		query: { state: true },
		active: { state: true },
	}

	value: string | number = ''
	/** { value, label, hint, disabled, pinned } (a JSON attribute or the property). */
	options: ComboOption[] = []
	/** The list's name for assistive tech, on the trigger. */
	label = ''
	placeholder = 'Choose'
	/** true, false (a plain listbox) or "auto" (past six options). */
	filter: boolean | 'auto' = true
	filterLabel = 'Filter'
	/** The panel's width (it is at least the trigger's with match-width). */
	width?: string
	side: Side = 'bottom'
	align: Align = 'start'
	matchWidth = false
	disabled = false
	name?: string
	/** An option must be picked for its form to send. */
	required = false
	/** A hint or error for the trigger (a field sets it). */
	description?: string
	protected query = ''
	protected active = 0
	protected uidBase = uid('combobox')
	protected pop = new PopoverController(this, {
		anchor: () => this.renderRoot.querySelector<HTMLElement>('button[data-trigger]'),
		panel: () => this.renderRoot.querySelector<HTMLElement>('.ds-pop'),
		gap: 4,
	})

	/** The trigger button's classes (React's triggerClass); a subclass returns its own. */
	protected triggerClasses() {
		return 'group inline-flex h-control-md w-full min-w-0 cursor-pointer items-center gap-2 rounded-control border border-edge-strong bg-surface-subtle px-3 text-left type-ui text-fg outline-none transition-[border-color] duration-160 ease-standard hover:not-disabled:border-action-secondary-edge-hover focus-visible:border-edge-focus aria-expanded:border-edge-focus disabled:cursor-not-allowed disabled:text-fg-faint max-md:h-control-touch max-md:text-input pointer-coarse:h-control-touch'
	}
	/** The trigger's content (React's `trigger`). */
	protected renderTrigger(selected: ComboOption | undefined, _open: boolean): TemplateResult {
		return html`<span class=${selected ? 'min-w-0 flex-1 truncate' : 'min-w-0 flex-1 truncate text-fg-muted'}>${selected?.label ?? this.placeholder}</span>${icon(ChevronsUpDown, 'chevrons-up-down', { size: 16, strokeWidth: 1.5, class: 'shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}`
	}
	/** One row's content (React's `option`). */
	protected renderOption(o: ComboOption, selected: boolean): TemplateResult {
		return html`<span class="min-w-0 flex-1 truncate">${o.label}</span>${o.hint ? html`<span class="min-w-10 text-right type-caption text-fg-muted tabular-nums">${o.hint}</span>` : nothing}${icon(Check, 'check', { size: 16, strokeWidth: 1.5, class: selected ? 'shrink-0' : 'shrink-0 invisible', attrs: { 'aria-hidden': 'true' } })}`
	}
	/** What shows when nothing matches (React's `empty`). */
	protected renderEmpty(query: string): TemplateResult | string {
		return `Nothing matches "${query}".`
	}
	/** The data-ds of the trigger (a subclass's own name, as React's data-ds prop gives it). */
	protected triggerName() {
		return (this.constructor as typeof Combobox).dsName
	}

	protected get filtering() {
		return this.filter === 'auto' ? this.options.filter((o) => !o.pinned).length > 6 : this.filter
	}
	protected get selected() {
		return this.options.find((o) => o.value === this.value)
	}
	private get pinned() {
		return this.options.filter((o) => o.pinned)
	}
	private get rest() {
		const q = this.query.trim().toLowerCase()
		const all = this.options.filter((o) => !o.pinned)
		return q ? all.filter((o) => o.label.toLowerCase().includes(q)) : all
	}
	private get visible() {
		return [...this.pinned, ...this.rest]
	}
	private optionId = (i: number) => `${this.uidBase}-${i}`

	private move(to: number, step = 1) {
		const list = this.visible
		const n = list.length
		if (!n) return
		for (let k = 0; k < n; k++) {
			const i = (((to + k * step) % n) + n) % n
			if (!list[i]?.disabled) {
				this.active = i
				void this.updateComplete.then(() => this.renderRoot.querySelector(`#${this.optionId(i)}`)?.scrollIntoView({ block: 'nearest' }))
				return
			}
		}
	}

	private async openList(keyboard: boolean) {
		this.query = ''
		this.pop.configure({ side: this.side, align: this.align, matchWidth: this.matchWidth })
		await this.pop.show({ keyboard })
		const at = this.visible.findIndex((o) => o.value === this.value)
		this.move(at >= 0 ? at : 0)
		await this.updateComplete
		this.renderRoot.querySelector<HTMLElement>(this.filtering ? 'input[role="combobox"]' : '[role="listbox"]')?.focus({ preventScroll: true })
	}
	private pick(o: ComboOption | undefined, keyboard: boolean) {
		if (!o || o.disabled) return
		this.commit(o.value)
		this.emit('select', o)
		this.pop.hide(true, keyboard)
	}
	private onTrigger = (event: MouseEvent) => {
		if (this.pop.open) this.pop.hide(false, event.detail === 0)
		else void this.openList(event.detail === 0)
	}
	private onTriggerKey = (event: KeyboardEvent) => {
		if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && !this.pop.open) {
			event.preventDefault()
			void this.openList(true)
		}
	}
	// With no filter, typing jumps to the option that starts with what was typed in the last half second.
	private typed = ''
	private typedAt = 0
	private onKey = (event: KeyboardEvent) => {
		const k = event.key
		const list = this.visible
		if (k === 'ArrowDown' || k === 'ArrowUp') {
			event.preventDefault()
			this.move(this.active + (k === 'ArrowDown' ? 1 : -1), k === 'ArrowDown' ? 1 : -1)
		} else if ((k === 'Home' || k === 'End') && !this.filtering) {
			event.preventDefault()
			this.move(k === 'Home' ? 0 : list.length - 1, k === 'Home' ? 1 : -1)
		} else if (k === 'Enter' || (k === ' ' && !this.filtering)) {
			event.preventDefault()
			this.pick(list[this.active], true)
		} else if (!this.filtering && k.length === 1 && !event.metaKey && !event.ctrlKey && !event.altKey) {
			const now = Date.now()
			this.typed = now - this.typedAt > 500 ? k.toLowerCase() : this.typed + k.toLowerCase()
			this.typedAt = now
			const i = list.findIndex((o) => !o.disabled && o.label.toLowerCase().startsWith(this.typed))
			if (i >= 0) this.move(i)
		}
	}
	private onQuery = (event: Event) => {
		this.query = (event.target as HTMLInputElement).value
		this.move(0)
	}

	// No native control: a required list with no pick is missing its value, as a required select is.
	syncValidity() {
		this.setMissing(this.required && (this.value === '' || this.value === null || this.value === undefined), 'select', this.renderRoot.querySelector<HTMLElement>('button[data-trigger]'))
	}
	protected updated(changed: PropertyValues) {
		super.updated(changed)
		if (changed.has('value')) this.internals.setFormValue(String(this.value ?? ''))
	}
	render() {
		const open = this.pop.open
		const list = this.visible
		const pinned = this.pinned
		const rest = this.rest
		const activeId = open && list.length ? this.optionId(this.active) : undefined
		const listId = `${this.uidBase}-list`
		const filtering = this.filtering
		return html`<button data-ds=${this.triggerName()} data-trigger type="button" class=${this.triggerClasses()} aria-haspopup="listbox" aria-expanded=${String(open)} aria-controls=${open ? listId : nothing} aria-label=${this.label} aria-description=${this.description ?? nothing} ?disabled=${this.inactive} @click=${this.onTrigger} @keydown=${this.onTriggerKey}>${this.renderTrigger(this.selected, open)}</button>${this.pop.rendered
			? html`<div data-ds="combobox" popover="manual" class="ds-pop flex flex-col p-1 fade-y" data-side=${this.pop.pos.side} ?data-instant=${this.pop.instant} ?data-placed=${this.pop.pos.placed} style=${this.pop.style(this.width ? `width: ${this.width}` : '')} @focusout=${this.pop.onFocusOut}>
				${filtering
					? html`<label class="-mx-1 -mt-1 mb-1 flex h-control-md items-center gap-2 border-b border-edge px-3">${icon(Search, 'search', { size: 16, strokeWidth: 1.5, class: 'pointer-events-none shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}<input .value=${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.filterLabel} placeholder=${this.filterLabel} aria-autocomplete="list" aria-expanded="true" aria-controls=${listId} aria-activedescendant=${activeId ?? nothing} autocomplete="off" spellcheck="false" @input=${this.onQuery} @keydown=${this.onKey}></label>`
					: nothing}
				<div id=${listId} role="listbox" aria-label=${this.label} tabindex=${filtering ? '-1' : '0'} aria-activedescendant=${!filtering && activeId ? activeId : nothing} class="flex max-h-65 flex-col overflow-y-auto outline-none fade-y" @keydown=${this.onKey}>
					${repeat(list, (o) => `${o.pinned ? 'p' : 'o'}-${o.value}`, (o, i) => html`${i === pinned.length && pinned.length && rest.length ? html`<div class="-mx-1 my-1 h-px shrink-0 bg-edge" role="separator"></div>` : nothing}<div id=${this.optionId(i)} role="option" class="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" aria-selected=${String(o.value === this.value)} aria-disabled=${o.disabled ? 'true' : nothing} ?data-active=${i === this.active} @pointermove=${() => { if (!o.disabled) this.active = i }} @mousedown=${(e: Event) => e.preventDefault()} @click=${() => this.pick(o, false)}>${this.renderOption(o, o.value === this.value)}</div>`)}
					${!rest.length && this.query ? html`<p class="px-2 py-2 type-ui text-fg-muted">${this.renderEmpty(this.query)}</p>` : nothing}
				</div>
			</div>`
			: nothing}`
	}
}

define('combobox', Combobox)

Reference: Derived from the guidelines: the input's #666666 hairline and the brand corner for the trigger, the #262626 card fill and neutral hairlines for the panel, DM Sans 14px rows. shadcn's combobox (a popover and a command list) for anatomy and keys..