Components
Select
One choice from a short list, drawn as the field is: a Black field, a hairline that turns White while open, a chevron. The list opens in the card's #262626 panel, the chosen row checked. A long list scrolls with fading edges.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add select<script type="module" src="/spyglass-ds/elements/select.js"></script>Usage
Picking one of a few known values in a form or a filter: a platform, an order, a plan. Label it as any field.
Never
- A list that needs a filter: use Combobox
- Options that do something at once: use Dropdown Menu
- A colored or glowing focus ring: the hairline turns White
Adds with it: popover packages lucide-react
Props
The web component takes the same as attributes or properties (<spyglass-select>); title is heading there.
<Select>
| Prop | Type | Default |
|---|---|---|
options | SelectOption[] The choices. | |
value | string The chosen value (with onValueChange). | |
defaultValue | string | '' |
onValueChange | (value: string) => void | |
placeholder | string Shown, muted, until something is chosen. | 'Select' |
size | SelectSize sm (32px), md (40px) or lg (48px), as Input. | 'md' |
label | string The field's name for assistive tech, when no <label> names it. | |
id | string The id a <label for> points at. | |
name | string Sends the value with a form. | |
disabled | boolean | |
invalid | boolean A red hairline (with the message beside it). | |
className | string |
Examples
The same example in React and as web components; both render identically.
import { Select } from '@/react/components/ui/Select'
// Two filters for a search: a platform to pick (a placeholder until then) and the order, already chosen.
const platforms = [
{ value: 'meta', label: 'Meta' },
{ value: 'tiktok', label: 'TikTok' },
{ value: 'youtube', label: 'YouTube' },
{ value: 'linkedin', label: 'LinkedIn', disabled: true },
]
const orders = [
{ value: 'newest', label: 'Newest first' },
{ value: 'longest', label: 'Longest running' },
{ value: 'saved', label: 'Most saved' },
]
export default function Filters() {
return (
<div className="flex min-h-72 w-72 max-w-full flex-col gap-6">
<div className="flex flex-col gap-2">
<label htmlFor="select-platform" className="type-label text-fg-soft">Platform</label>
<Select id="select-platform" label="Platform" name="platform" options={platforms} placeholder="Any platform" />
</div>
<div className="flex flex-col gap-2">
<label htmlFor="select-order" className="type-label text-fg-soft">Sort by</label>
<Select id="select-order" label="Sort by" name="order" options={orders} defaultValue="longest" />
<p className="type-caption text-fg-muted">Ads that run longer are the ones that work.</p>
</div>
</div>
)
}<!-- Two filters for a search: a platform to pick (a placeholder until then) and the order, already chosen. -->
<div class="flex min-h-72 w-72 max-w-full flex-col gap-6">
<div class="flex flex-col gap-2">
<label for="select-platform" class="type-label text-fg-soft">Platform</label>
<spyglass-select id="select-platform" aria-label="Platform" name="platform" placeholder="Any platform" options='[{"value":"meta","label":"Meta"},{"value":"tiktok","label":"TikTok"},{"value":"youtube","label":"YouTube"},{"value":"linkedin","label":"LinkedIn","disabled":true}]'></spyglass-select>
</div>
<div class="flex flex-col gap-2">
<label for="select-order" class="type-label text-fg-soft">Sort by</label>
<spyglass-select id="select-order" aria-label="Sort by" name="order" value="longest" options='[{"value":"newest","label":"Newest first"},{"value":"longest","label":"Longest running"},{"value":"saved","label":"Most saved"}]'></spyglass-select>
<p class="type-caption text-fg-muted">Ads that run longer are the ones that work.</p>
</div>
</div>Source
'use client'
import { useId, useRef, type KeyboardEvent, type MouseEvent } from 'react'
import { Check, ChevronDown } from 'lucide-react'
import { PopoverPanel } from '@/react/components/ui/PopoverPanel'
import { useControllable } from '@/react/hooks/useControllable'
import { onMenuRows, usePopover } from '@/react/hooks/usePopover'
import { cn } from '@/react/lib/cn'
// One choice from a short list, drawn as the field is (shadcn's select): a Black field with a #666666 hairline that
// turns White while open, the chosen label (or a muted placeholder) and a chevron. The list opens in the card's #262626
// panel, as wide as the field, focus on the chosen row; the chosen row has a check. Arrow keys, Home, End and the first
// letter move through it, Enter or Space picks, Escape closes and returns focus. Opened from the keyboard it shows at
// once; from a click it grows from the field. `value` with `onValueChange`; `name` sends the value with a form.
export type SelectSize = 'sm' | 'md' | 'lg'
export interface SelectOption {
value: string
label: string
disabled?: boolean
}
export interface SelectProps {
/** The choices. */
options: SelectOption[]
/** The chosen value (with onValueChange). */
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
/** Shown, muted, until something is chosen. */
placeholder?: string
/** sm (32px), md (40px) or lg (48px), as Input. */
size?: SelectSize
/** The field's name for assistive tech, when no <label> names it. */
label?: string
/** The id a <label for> points at. */
id?: string
/** Sends the value with a form. */
name?: string
disabled?: boolean
/** A red hairline (with the message beside it). */
invalid?: boolean
className?: string
}
const SIZES: Record<SelectSize, string> = { sm: 'h-control-sm pr-2 pl-2.5', md: 'h-control-md pr-3 pl-3', lg: 'h-control-lg pr-4 pl-4' }
export function Select({ options, value: given, defaultValue = '', onValueChange, placeholder = 'Select', size = 'md', label, id, name, disabled, invalid, className }: SelectProps) {
const [value, setValue] = useControllable(given, defaultValue, onValueChange)
const pop = usePopover({ side: 'bottom', align: 'start', matchWidth: true, gap: 4 })
const listId = `select-${useId()}`
const typed = useRef({ text: '', at: 0 })
const chosen = options.find((o) => o.value === value)
const rows = () => [...(pop.panel.current?.querySelectorAll<HTMLElement>('[role="option"]:not([aria-disabled="true"])') ?? [])]
async function open(keyboard: boolean, at: 'chosen' | 'first' | 'last' = 'chosen') {
await pop.show({ keyboard })
const all = rows()
const target = at === 'first' ? all[0] : at === 'last' ? all.at(-1) : all.find((r) => r.dataset.value === value) ?? all[0]
;(target ?? pop.panel.current)?.focus({ preventScroll: true })
}
function pick(v: string, keyboard: boolean) {
setValue(v)
pop.hide(true, keyboard)
}
// A click from the keyboard has no pointer detail: the list opens and closes at once.
function onClick(event: MouseEvent) {
const keyboard = event.detail === 0
if (pop.open) pop.hide(keyboard, keyboard)
else void open(keyboard)
}
function onTriggerKey(event: KeyboardEvent) {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
if (!pop.open) void open(true, value ? 'chosen' : event.key === 'ArrowDown' ? 'first' : 'last')
}
}
// The first letters typed in a moment find the next row that starts with them.
function typeahead(key: string) {
const now = Date.now()
typed.current = { text: now - typed.current.at < 500 ? typed.current.text + key.toLowerCase() : key.toLowerCase(), at: now }
const all = rows()
const from = all.indexOf(document.activeElement as HTMLElement)
const order = [...all.slice(from + 1), ...all.slice(0, from + 1)]
order.find((r) => r.textContent?.trim().toLowerCase().startsWith(typed.current.text))?.focus()
}
function onListKey(event: KeyboardEvent) {
const row = (event.target as HTMLElement).closest<HTMLElement>('[role="option"]')
if ((event.key === 'Enter' || event.key === ' ') && row) {
event.preventDefault()
if (row.getAttribute('aria-disabled') !== 'true') pick(row.dataset.value ?? '', true)
}
else if (event.key.length === 1 && /\S/.test(event.key)) typeahead(event.key)
else onMenuRows(event, pop.panel.current, (refocus) => pop.hide(refocus))
}
return (
<>
<button
data-ds="select"
ref={(el) => { pop.anchor.current = el }}
id={id}
type="button"
role="combobox"
aria-haspopup="listbox"
aria-expanded={pop.open}
aria-controls={pop.open ? listId : undefined}
aria-label={label}
aria-invalid={invalid || undefined}
disabled={disabled}
className={cn('flex w-full min-w-0 cursor-pointer items-center justify-between gap-2 rounded-control border border-edge-strong bg-surface-subtle 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 aria-invalid:border-action-danger disabled:cursor-not-allowed disabled:text-fg-faint max-md:text-input pointer-coarse:text-input', SIZES[size], className)}
onClick={onClick}
onKeyDown={onTriggerKey}
>
<span className={cn('min-w-0 truncate text-left', chosen ? 'text-fg' : 'text-fg-muted')}>{chosen ? chosen.label : placeholder}</span>
<ChevronDown size={16} strokeWidth={1.5} aria-hidden="true" className="shrink-0 text-fg-muted" />
</button>
{name && <input type="hidden" name={name} value={value} />}
<PopoverPanel data-ds="select" id={listId} pop={pop} role="listbox" aria-label={label} tabIndex={-1} className="p-1" onKeyDown={onListKey}>
{options.map((o) => (
<div
key={o.value}
role="option"
tabIndex={-1}
data-value={o.value}
aria-selected={o.value === value}
aria-disabled={o.disabled || undefined}
className="flex h-control-sm cursor-pointer items-center justify-between gap-3 rounded-ds-sm px-2 type-ui text-fg-soft outline-none transition-[background-color,color] duration-160 ease-standard focus:bg-action-secondary focus:text-fg aria-disabled:cursor-not-allowed aria-disabled:text-fg-faint aria-selected:text-fg max-md:h-control-touch"
onPointerMove={(event) => { if (!o.disabled && document.activeElement !== event.currentTarget) event.currentTarget.focus({ preventScroll: true }) }}
onClick={(event) => { if (!o.disabled) pick(o.value, event.detail === 0) }}
>
<span className="min-w-0 truncate">{o.label}</span>
{o.value === value && <Check size={16} strokeWidth={1.5} aria-hidden="true" className="shrink-0" />}
</div>
))}
</PopoverPanel>
</>
)
}
export default Select'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
}// 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, LitElement, nothing, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { repeat } from 'lit/directives/repeat.js'
import { Check, ChevronDown } from 'lucide'
import { DsFormElement, define, HostLayoutController, uid } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import { onMenuRows } from '@/elements/lib/menu'
import { PopoverController, popoverStyles } from '@/elements/lib/popover'
import styles from 'virtual:tw'
// Select.tsx as <spyglass-select>: one choice from a short list, drawn as the field is: a Black field with a hairline
// that turns White while open, the chosen label (or a muted placeholder) and a chevron. The list opens in the card's
// #262626 panel, as wide as the field, focus on the chosen row, which has a check. Arrow keys, Home, End and the first
// letter move through it, Enter or Space picks, Escape closes. Opened from the keyboard it shows at once. `options` is
// a JSON list of { value, label, disabled }; `value` with `input` and `change`; form-associated under `name`.
export type SelectSize = 'sm' | 'md' | 'lg'
export interface SelectOption { value: string, label: string, disabled?: boolean }
const SIZES: Record<SelectSize, string> = { sm: 'h-control-sm pr-2 pl-2.5', md: 'h-control-md pr-3 pl-3', lg: 'h-control-lg pr-4 pl-4' }
/**
* @summary One choice from a short list, drawn as a field.
* @fires input - A row was picked (read `value`).
* @fires change - A row was picked (read `value`).
*/
export class Select extends DsFormElement {
static styles = [DsFormElement.styles, popoverStyles, styles]
static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('button[role="combobox"]'))
static properties = {
options: { type: Array },
value: {},
placeholder: {},
size: { reflect: true },
label: { attribute: 'aria-label' },
name: {},
disabled: { type: Boolean, reflect: true },
invalid: { type: Boolean, reflect: true },
}
/** The choices. */
options: SelectOption[] = []
value = ''
/** Shown, muted, until something is chosen. */
placeholder = 'Select'
/** sm (32px), md (40px) or lg (48px), as Input. */
size: SelectSize = 'md'
/** The field's name for assistive tech. */
label?: string
name?: string
disabled = false
/** A red hairline (with the message beside it). */
invalid = false
private listId = uid('select')
private typed = { text: '', at: 0 }
private pop = new PopoverController(this, {
side: 'bottom',
align: 'start',
matchWidth: true,
gap: 4,
anchor: () => this.renderRoot.querySelector<HTMLElement>('button[role="combobox"]'),
panel: () => this.renderRoot.querySelector<HTMLElement>('.ds-pop'),
})
connectedCallback() {
super.connectedCallback()
if (!this.value && this.getAttribute('value')) this.value = this.getAttribute('value')!
}
protected updated(changed: PropertyValues) {
super.updated(changed)
if (changed.has('value')) this.internals.setFormValue(this.value)
}
formResetCallback() {
this.value = this.getAttribute('value') ?? ''
}
private rows() {
return [...this.renderRoot.querySelectorAll<HTMLElement>('[role="option"]:not([aria-disabled="true"])')]
}
private async open(keyboard: boolean, at: 'chosen' | 'first' | 'last' = 'chosen') {
await this.pop.show({ keyboard })
const all = this.rows()
const target = at === 'first' ? all[0] : at === 'last' ? all.at(-1) : all.find((r) => r.dataset.value === this.value) ?? all[0]
;(target ?? this.renderRoot.querySelector<HTMLElement>('.ds-pop'))?.focus({ preventScroll: true })
}
private pick(v: string, keyboard: boolean) {
this.commit(v)
this.pop.hide(true, keyboard)
}
// A click from the keyboard has no pointer detail: the list opens and closes at once.
private onClick = (event: MouseEvent) => {
const keyboard = event.detail === 0
if (this.pop.open) this.pop.hide(keyboard, keyboard)
else void this.open(keyboard)
}
private onTriggerKey = (event: KeyboardEvent) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
if (!this.pop.open) void this.open(true, this.value ? 'chosen' : event.key === 'ArrowDown' ? 'first' : 'last')
}
}
// The first letters typed in a moment find the next row that starts with them.
private typeahead(key: string) {
const now = Date.now()
this.typed = { text: now - this.typed.at < 500 ? this.typed.text + key.toLowerCase() : key.toLowerCase(), at: now }
const all = this.rows()
const from = all.indexOf((this.renderRoot as ShadowRoot).activeElement as HTMLElement)
const order = [...all.slice(from + 1), ...all.slice(0, from + 1)]
order.find((r) => r.textContent?.trim().toLowerCase().startsWith(this.typed.text))?.focus()
}
private onListKey = (event: KeyboardEvent) => {
const row = (event.composedPath()[0] as HTMLElement).closest?.<HTMLElement>('[role="option"]')
if ((event.key === 'Enter' || event.key === ' ') && row) {
event.preventDefault()
if (row.getAttribute('aria-disabled') !== 'true') this.pick(row.dataset.value ?? '', true)
} else if (event.key.length === 1 && /\S/.test(event.key)) this.typeahead(event.key)
else onMenuRows(event, this.rows(), (refocus) => this.pop.hide(refocus))
}
render() {
const options = Array.isArray(this.options) ? this.options : []
const chosen = options.find((o) => o.value === this.value)
const size = SIZES[this.size] ? this.size : 'md'
const classes = ['flex w-full min-w-0 cursor-pointer items-center justify-between gap-2 rounded-control border border-edge-strong bg-surface-subtle 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 aria-invalid:border-action-danger disabled:cursor-not-allowed disabled:text-fg-faint max-md:text-input pointer-coarse:text-input', SIZES[size]].join(' ')
const panel = this.pop.rendered
? html`<div data-ds="select" id=${this.listId} popover="manual" class="ds-pop p-1 fade-y" role="listbox" aria-label=${ifDefined(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()} @focusout=${this.pop.onFocusOut} @keydown=${this.onListKey}>${repeat(
options,
(o) => o.value,
(o) => html`<div role="option" tabindex="-1" data-value=${o.value} aria-selected=${String(o.value === this.value)} aria-disabled=${ifDefined(o.disabled ? 'true' : undefined)} class="flex h-control-sm cursor-pointer items-center justify-between gap-3 rounded-ds-sm px-2 type-ui text-fg-soft outline-none transition-[background-color,color] duration-160 ease-standard focus:bg-action-secondary focus:text-fg aria-disabled:cursor-not-allowed aria-disabled:text-fg-faint aria-selected:text-fg max-md:h-control-touch" @pointermove=${(event: PointerEvent) => { const el = event.currentTarget as HTMLElement; if (!o.disabled && (this.renderRoot as ShadowRoot).activeElement !== el) el.focus({ preventScroll: true }) }} @click=${(event: MouseEvent) => { if (!o.disabled) this.pick(o.value, event.detail === 0) }}><span class="min-w-0 truncate">${o.label}</span>${o.value === this.value ? icon(Check, 'check', { size: 16, strokeWidth: 1.5, class: 'shrink-0', attrs: { 'aria-hidden': 'true' } }) : nothing}</div>`,
)}</div>`
: nothing
return html`<button data-ds="select" type="button" role="combobox" aria-haspopup="listbox" aria-expanded=${String(this.pop.open)} aria-controls=${ifDefined(this.pop.open ? this.listId : undefined)} aria-label=${ifDefined(this.label)} aria-invalid=${ifDefined(this.invalid ? 'true' : undefined)} ?disabled=${this.inactive} class=${classes} @click=${this.onClick} @keydown=${this.onTriggerKey}><span class=${`min-w-0 truncate text-left ${chosen ? 'text-fg' : 'text-fg-muted'}`}>${chosen ? chosen.label : this.placeholder}</span>${icon(ChevronDown, 'chevron-down', { size: 16, strokeWidth: 1.5, class: 'shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}</button>${panel}`
}
}
define('select', Select)Reference: Derived from the brand guidelines (no select in the brand assets): the Input's Black field and hairline, the plan card's #262626 fill for the list.