Components
Date picker
A date in a field: a button drawn as the text field that opens the calendar on the #262626 overlay panel under it. Opening puts focus on the picked day, picking closes it and returns focus, Escape closes it unchanged.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add date-picker<script type="module" src="/spyglass-ds/elements/date-picker.js"></script>Usage
A single date in a form: when a report starts, when a campaign ends. The field reads the day in words.
Never
- A shadow under the panel: the hairline and the #262626 fill set it apart
- Typing a date into the button: it is picked from the calendar
- A red edge for anything but an error
The web component is form-associated: give it a name and the form sends the day as an ISO date (2026-11-03).
Props
The web component takes the same as attributes or properties (<spyglass-date-picker>); title is heading there.
<DatePicker>
| Prop | Type | Default |
|---|---|---|
id | string | |
placeholder | string What the field says before a day is picked. | 'Pick a date' |
min | Date The first day that can be picked. | |
max | Date The last day that can be picked. | |
disabled | (day: Date) => boolean Days that can't be picked. | |
invalid | boolean A red edge. | |
locale | string | 'en-US' |
format | Intl.DateTimeFormatOptions How the picked day reads in the field. | FORMAT |
value | Date | null | |
defaultValue | Date | null | null |
onValueChange | (day: Date | null) => void | |
className | string | |
aria-describedby | string |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useState } from 'react'
import { DatePicker } from '@/react/components/ui/DatePicker'
// A report's start date in a form: a label over the field, a hint under it.
export default function Field() {
const [day, setDay] = useState<Date | null>(null)
return (
<div className="flex h-110 w-full max-w-80 flex-col gap-2">
<label htmlFor="report-start" className="type-label text-fg-muted">Report starts</label>
<DatePicker id="report-start" value={day} onValueChange={setDay} aria-describedby="report-start-hint" />
<p id="report-start-hint" className="type-caption text-fg-muted">{day ? `Creatives running since ${day.toLocaleDateString('en-US', { month: 'long', day: 'numeric' })}.` : 'Creatives running since this day.'}</p>
</div>
)
}<!-- A report's start date in a form: a label over the field, a hint under it. -->
<div class="flex h-110 w-full max-w-80 flex-col gap-2">
<label for="report-start" class="type-label text-fg-muted">Report starts</label>
<spyglass-date-picker id="report-start" aria-label="Report starts" aria-description="Creatives running since this day."></spyglass-date-picker>
<p id="report-start-hint" class="type-caption text-fg-muted">Creatives running since this day.</p>
</div>
<script type="module">
const picker = document.getElementById('report-start')
picker.addEventListener('change', () => {
document.getElementById('report-start-hint').textContent = picker.value ? `Creatives running since ${picker.value.toLocaleDateString('en-US', { month: 'long', day: 'numeric' })}.` : 'Creatives running since this day.'
})
</script>import { DatePicker } from '@/react/components/ui/DatePicker'
// A day already picked, read in full; days after today can't be picked.
export default function Picked() {
return (
<div className="h-110 w-full max-w-80">
<DatePicker defaultValue={new Date(2026, 10, 3)} max={new Date(2026, 10, 17)} format={{ weekday: 'short', month: 'long', day: 'numeric', year: 'numeric' }} />
</div>
)
}<!-- A day already picked, read in full; days after today can't be picked. -->
<div class="h-110 w-full max-w-80">
<spyglass-date-picker value="2026-11-03" max="2026-11-17" format='{"weekday":"short","month":"long","day":"numeric","year":"numeric"}'></spyglass-date-picker>
</div>Source
'use client'
import { useId, type KeyboardEvent, type MouseEvent } from 'react'
import { CalendarDays } from 'lucide-react'
import { Calendar } from '@/react/components/ui/Calendar'
import { PopoverPanel } from '@/react/components/ui/PopoverPanel'
import { cn } from '@/react/lib/cn'
import { useControllable } from '@/react/hooks/useControllable'
import { usePopover } from '@/react/hooks/usePopover'
// shadcn's date picker in the brand: a button drawn as the text field (40px, the 8px corner, a #666666 hairline that
// turns White while it is open or focused, the placeholder muted) that opens a Calendar on the #262626 overlay panel
// under it. Opening puts focus on the picked day (or today); picking a day closes it and returns focus to the field;
// Escape closes it unchanged. `value` with `onValueChange` (or `defaultValue` alone).
export interface DatePickerProps {
id?: string
/** What the field says before a day is picked. */
placeholder?: string
/** The first day that can be picked. */
min?: Date
/** The last day that can be picked. */
max?: Date
/** Days that can't be picked. */
disabled?: (day: Date) => boolean
/** A red edge. */
invalid?: boolean
locale?: string
/** How the picked day reads in the field. */
format?: Intl.DateTimeFormatOptions
value?: Date | null
defaultValue?: Date | null
onValueChange?: (day: Date | null) => void
className?: string
'aria-describedby'?: string
}
const FORMAT: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric' }
export function DatePicker({ id, placeholder = 'Pick a date', min, max, disabled, invalid, locale = 'en-US', format = FORMAT, value, defaultValue = null, onValueChange, className, 'aria-describedby': describedBy }: DatePickerProps) {
const [model, setModel] = useControllable<Date | null>(value, defaultValue, onValueChange)
const pop = usePopover({ side: 'bottom', align: 'start', gap: 4 })
const panelId = `date-${useId()}`
const text = model?.toLocaleDateString(locale, format)
async function onClick(event: MouseEvent | { detail: number }) {
if (pop.open) return pop.hide(event.detail === 0, event.detail === 0)
await pop.show({ keyboard: event.detail === 0 })
pop.panel.current?.querySelector<HTMLElement>('.ds-day[tabindex="0"]')?.focus({ preventScroll: true })
}
function onKey(event: KeyboardEvent) {
if (event.key === 'ArrowDown' && !pop.open) {
event.preventDefault()
void onClick({ detail: 0 })
}
}
function picked() {
pop.hide(true)
}
return (
<>
<button
data-ds="date-picker"
id={id}
ref={(el) => { pop.anchor.current = el }}
type="button"
className={cn('flex h-control-md w-full 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 aria-invalid:border-action-danger disabled:cursor-not-allowed disabled:text-fg-faint max-md:text-input', className)}
aria-haspopup="dialog"
aria-expanded={pop.open}
aria-controls={pop.open ? panelId : undefined}
aria-invalid={invalid || undefined}
aria-describedby={describedBy}
onClick={onClick}
onKeyDown={onKey}
>
<CalendarDays size={16} strokeWidth={1.5} className="shrink-0 text-fg-muted" aria-hidden="true" />
<span className={cn('min-w-0 flex-1 truncate', !text && 'text-fg-muted')}>{text ?? placeholder}</span>
</button>
<PopoverPanel data-ds="date-picker" id={panelId} pop={pop} role="dialog" aria-label="Choose a date" tabIndex={-1} className="p-3">
<Calendar value={model} onValueChange={setModel} min={min} max={max} disabled={disabled} locale={locale} onSelect={picked} />
</PopoverPanel>
</>
)
}
export default DatePicker// 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(' ')
}'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, LitElement, nothing, type PropertyValues } from 'lit'
import { html as staticHtml } from 'lit/static-html.js'
import { CalendarDays } from 'lucide'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsFormElement, define, tag, uid } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import { PopoverController, popoverStyles } from '@/elements/lib/popover'
import '@/elements/components/ui/calendar'
import styles from 'virtual:tw'
// DatePicker.tsx as <spyglass-date-picker>: a button drawn as the text field (40px, the 8px corner, a #363636
// hairline that turns White while it is open or focused, the placeholder muted) that opens a <spyglass-calendar> on
// the #262626 overlay panel under it, in the top layer. Opening puts focus on the picked day (or today); picking a day
// closes it and returns focus to the field; Escape closes it unchanged. `value` (a Date, or an ISO date attribute)
// with `input` and `change`. `min` and `max` are Dates (or ISO date attributes); `disabled` is a function of the day,
// set as a property. Form-associated: its `name` goes with the form as the day's ISO date (2026-11-13). aria-label
// and aria-description pass to the button.
const dateAttr = { fromAttribute: (v: string | null) => (v ? new Date(`${v}T00:00:00`) : null) }
const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
/**
* @summary A date in a field, picked from a calendar.
* @fires input - A day was picked (read `value`).
* @fires change - A day was picked (read `value`).
*/
export class DatePicker extends DsFormElement {
static styles = [DsFormElement.styles, popoverStyles, styles]
static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
static dsField = true
static properties = {
value: { converter: dateAttr },
name: {},
placeholder: {},
min: { converter: dateAttr },
max: { converter: dateAttr },
disabled: { attribute: false },
invalid: { type: Boolean, reflect: true },
required: { type: Boolean },
locale: {},
format: { type: Object },
label: { attribute: 'aria-label' },
description: { attribute: 'aria-description' },
}
value: Date | null = null
name?: string
placeholder = 'Pick a date'
min?: Date | null
max?: Date | null
/** Days that can't be picked (a property: picker.disabled = (d) => d.getDay() === 0). */
disabled?: (day: Date) => boolean
/** A red edge. */
invalid = false
/** A day must be picked for its form to send. */
required = false
locale = 'en-US'
/** How the picked day reads in the field (Intl.DateTimeFormat options). */
format: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric' }
/** The name for assistive tech, passed to the button (a field sets it). */
label?: string
/** The hint or error, passed to the button (a field sets it). */
description?: string
private panelId = uid('date')
private pop = new PopoverController(this, {
side: 'bottom',
align: 'start',
gap: 4,
anchor: () => this.renderRoot.querySelector<HTMLElement>('button[data-ds="date-picker"]'),
panel: () => this.renderRoot.querySelector<HTMLElement>('.ds-pop'),
})
protected updated(changed: PropertyValues) {
super.updated(changed)
if (changed.has('value')) this.internals.setFormValue(this.value ? iso(this.value) : null)
}
// No native control: a required picker with no day is missing its value, as a required field is.
syncValidity() {
this.setMissing(this.required && !this.value, 'input', this.renderRoot.querySelector<HTMLElement>('button[data-ds="date-picker"]'))
}
formResetCallback() {
this.value = dateAttr.fromAttribute(this.getAttribute('value'))
}
private onClick = async (event: MouseEvent | { detail: number }) => {
if (this.pop.open) return this.pop.hide(event.detail === 0, event.detail === 0)
await this.pop.show({ keyboard: event.detail === 0 })
// The picked day (or today) in the calendar's own shadow root.
const calendar = this.renderRoot.querySelector('.ds-pop')?.firstElementChild as HTMLElement | null
await (calendar as unknown as { updateComplete?: Promise<unknown> })?.updateComplete
calendar?.shadowRoot?.querySelector<HTMLElement>('.ds-day[tabindex="0"]')?.focus({ preventScroll: true })
}
private onKey(event: KeyboardEvent) {
if (event.key === 'ArrowDown' && !this.pop.open) {
event.preventDefault()
void this.onClick({ detail: 0 })
}
}
private onChange(event: Event) {
event.stopPropagation()
this.commit((event.target as HTMLElement & { value: Date | null }).value)
}
// The calendar's own select stays inside: the picker emits only its value.
private picked(event: Event) {
event.stopPropagation()
this.pop.hide(true)
}
render() {
const text = this.value?.toLocaleDateString(this.locale, this.format)
const calendar = tag('calendar')
return html`<button
data-ds="date-picker"
type="button"
class="flex h-control-md w-full 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 aria-invalid:border-action-danger disabled:cursor-not-allowed disabled:text-fg-faint max-md:text-input"
?disabled=${this.inactive}
aria-haspopup="dialog"
aria-expanded=${String(this.pop.open)}
aria-controls=${ifDefined(this.pop.open ? this.panelId : undefined)}
aria-invalid=${ifDefined(this.invalid ? 'true' : undefined)}
aria-label=${ifDefined(this.label)}
aria-description=${ifDefined(this.description)}
@click=${this.onClick}
@keydown=${this.onKey}
>${icon(CalendarDays, 'calendar-days', { size: 16, strokeWidth: 1.5, class: 'shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}<span class=${text ? 'min-w-0 flex-1 truncate' : 'min-w-0 flex-1 truncate text-fg-muted'}>${text ?? this.placeholder}</span></button>
${this.pop.rendered
? html`<div data-ds="date-picker" id=${this.panelId} popover="manual" class="ds-pop p-3 fade-y" role="dialog" aria-label="Choose a date" 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}>${staticHtml`<${calendar} .value=${this.value} .min=${this.min} .max=${this.max} .disabled=${this.disabled} .locale=${this.locale} @input=${(e: Event) => e.stopPropagation()} @change=${this.onChange} @select=${this.picked}></${calendar}>`}</div>`
: nothing}`
}
}
define('date-picker', DatePicker)Reference: Derived from the guidelines: the input's field (40px, the 8px corner, a #666666 hairline that turns White on focus), the #262626 card fill for the overlay. shadcn's date picker (a popover holding a calendar) for anatomy and keys..