Components

Calendar

A month to pick a day from: 40px day cells with the 4px corner, the picked day a White fill with a Black figure, today in a neutral hairline ring, the months either side faint. Arrows, Home, End and Page Up and Down move; Enter picks.

Install

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

npx spyglass-ds add calendar
<script type="module" src="/spyglass-ds/elements/calendar.js"></script>
A launch day

November 2026

SuMoTuWeThFrSa

Goes live Friday, November 20.

Bounds, Monday start and blocked days

November 2026

MoTuWeThFrSaSu

Usage

Picking a launch day, a flight start or a report's range on a page with room for the month. In a field, use the date picker.

Never

  • A spectrum color for the picked day or today
  • Animating the change of month: it is pressed many times in a row
  • A calendar where a typed date would do (a birthday)

Adds with it: button packages lucide-react

Props

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

<Calendar>

PropTypeDefault
labelstring

The calendar's name for assistive tech.

'Calendar'
minDate

The first day that can be picked.

maxDate

The last day that can be picked.

disabled(day: Date) => boolean

Days that can't be picked.

weekStartsOn0 | 1

0 for Sunday, 1 for Monday.

0
localestring'en-US'
valueDate | null
defaultValueDate | nullnull
onValueChange(day: Date | null) => void
onSelect(day: Date) => void

A day was picked.

classNamestring

Examples

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

react/examples/calendar/Single.tsx
'use client'
import { useState } from 'react'
import { Calendar } from '@/react/components/ui/Calendar'
// The day a campaign goes live; the picked day reads under the month.

export default function Single() {
  const [day, setDay] = useState<Date | null>(new Date(2026, 10, 20))
  return (
    <div className="flex flex-col items-center gap-3">
      <Calendar label="Launch day" value={day} onValueChange={setDay} />
      <p className="type-caption text-fg-muted" aria-live="polite">{day ? `Goes live ${day.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}.` : 'Pick a day.'}</p>
    </div>
  )
}
elements/examples/calendar/Single.html
<!-- The day a campaign goes live; the picked day reads under the month. -->
<div class="flex flex-col items-center gap-3">
  <spyglass-calendar id="launch-day" label="Launch day" value="2026-11-20"></spyglass-calendar>
  <p id="launch-day-line" class="type-caption text-fg-muted" aria-live="polite">Goes live Friday, November 20.</p>
</div>
<script type="module">
  const cal = document.getElementById('launch-day')
  cal.addEventListener('change', () => {
    document.getElementById('launch-day-line').textContent = cal.value ? `Goes live ${cal.value.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}.` : 'Pick a day.'
  })
</script>
react/examples/calendar/Window.tsx
'use client'
import { Calendar } from '@/react/components/ui/Calendar'
// A flight window: weeks start on Monday, only days from November 9 to December 11 can be picked, and never a Sunday.

export default function Window() {
  return <Calendar label="Flight start" weekStartsOn={1} defaultValue={new Date(2026, 10, 24)} min={new Date(2026, 10, 9)} max={new Date(2026, 11, 11)} disabled={(d) => d.getDay() === 0} />
}
elements/examples/calendar/Window.html
<!-- A flight window: weeks start on Monday, only days from November 9 to December 11 can be picked, and never a Sunday. -->
<spyglass-calendar id="flight-start" label="Flight start" week-starts-on="1" value="2026-11-24" min="2026-11-09" max="2026-12-11"></spyglass-calendar>
<script type="module">
  document.getElementById('flight-start').disabled = (d) => d.getDay() === 0
</script>

Source

react/components/ui/Calendar.tsx
'use client'
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { cn } from '@/react/lib/cn'
import { useControllable } from '@/react/hooks/useControllable'

// shadcn's calendar in the brand: a month to pick a day from. 40px day cells (44px on phones) with the 4px corner,
// weekday heads in DM Sans 12px muted, the month in DM Sans Medium between two ghost arrow buttons. The picked day is a
// White fill with a Black figure; today carries a neutral hairline ring; the days of the months either side are faint;
// days that can't be picked are faint and struck through. Arrows move a day or a week, Home and End to the week's
// ends, Page Up and Page Down a month (with Shift a year), Enter or Space picks. Changing month doesn't animate: it is
// pressed many times in a row. `value` with `onValueChange` (or `defaultValue` alone); `onSelect` fires on every pick.
export interface CalendarProps {
  /** The calendar's name for assistive tech. */
  label?: 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
  /** 0 for Sunday, 1 for Monday. */
  weekStartsOn?: 0 | 1
  locale?: string
  value?: Date | null
  defaultValue?: Date | null
  onValueChange?: (day: Date | null) => void
  /** A day was picked. */
  onSelect?: (day: Date) => void
  className?: string
}

const day0 = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate())
const same = (a: Date | null | undefined, b: Date | null | undefined) => !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n)
function addMonths(d: Date, n: number) {
  const last = new Date(d.getFullYear(), d.getMonth() + n + 1, 0).getDate()
  return new Date(d.getFullYear(), d.getMonth() + n, Math.min(d.getDate(), last))
}

export const DAY = 'inline-flex size-control-md cursor-pointer items-center justify-center rounded-ds-sm border border-transparent type-ui tabular-nums text-fg outline-none transition-[background-color,color] duration-160 ease-standard hover:not-data-picked:not-aria-disabled:bg-ds-neutral-4 aria-[current=date]:border-fg-faint data-outside:text-fg-faint data-picked:bg-action-primary data-picked:font-medium data-picked:text-action-primary-fg aria-disabled:cursor-not-allowed aria-disabled:text-fg-faint aria-disabled:line-through focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-edge-focus data-picked:focus-visible:outline-fg-inverse max-md:size-control-touch'

export function Calendar({ label = 'Calendar', min, max, disabled, weekStartsOn = 0, locale = 'en-US', value, defaultValue = null, onValueChange, onSelect, className }: CalendarProps) {
  const [model, setModel] = useControllable<Date | null>(value, defaultValue, onValueChange)
  const today = day0(new Date())
  const [focused, setFocused] = useState(() => day0(model ?? today))
  const month = new Date(focused.getFullYear(), focused.getMonth(), 1)
  useEffect(() => {
    if (model && !same(model, focused)) setFocused(day0(model))
  }, [model]) // eslint-disable-line react-hooks/exhaustive-deps

  const caption = month.toLocaleDateString(locale, { month: 'long', year: 'numeric' })
  const weekdays = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(2026, 1, 1 + ((i + weekStartsOn) % 7)) // 1 February 2026 is a Sunday.
    return { short: d.toLocaleDateString(locale, { weekday: 'short' }).slice(0, 2), long: d.toLocaleDateString(locale, { weekday: 'long' }) }
  })
  // Whole weeks: the days of the months either side fill the first and last rows.
  const lead = (month.getDay() - weekStartsOn + 7) % 7
  const count = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate()
  const cells = Array.from({ length: Math.ceil((lead + count) / 7) * 7 }, (_, i) => new Date(month.getFullYear(), month.getMonth(), i - lead + 1))
  const weeks = Array.from({ length: cells.length / 7 }, (_, w) => cells.slice(w * 7, w * 7 + 7))
  const blocked = (d: Date) => (!!min && d < day0(min)) || (!!max && d > day0(max)) || !!disabled?.(d)
  const dayLabel = (d: Date) => d.toLocaleDateString(locale, { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })

  const grid = useRef<HTMLTableElement | null>(null)
  // The roving day takes focus once the move has rendered.
  const [pendingFocus, setPendingFocus] = useState(0)
  useEffect(() => {
    if (pendingFocus) grid.current?.querySelector<HTMLElement>('[tabindex="0"]')?.focus()
  }, [pendingFocus])
  function moveTo(d: Date) {
    setFocused(d)
    setPendingFocus(n => n + 1)
  }
  function pick(d: Date) {
    if (blocked(d)) return
    setFocused(d)
    setModel(d)
    onSelect?.(d)
  }
  function onKey(event: KeyboardEvent<HTMLTableElement>) {
    const d = focused
    const start = addDays(d, -((d.getDay() - weekStartsOn + 7) % 7))
    const moves: Record<string, () => Date> = {
      ArrowLeft: () => addDays(d, -1),
      ArrowRight: () => addDays(d, 1),
      ArrowUp: () => addDays(d, -7),
      ArrowDown: () => addDays(d, 7),
      Home: () => start,
      End: () => addDays(start, 6),
      PageUp: () => addMonths(d, event.shiftKey ? -12 : -1),
      PageDown: () => addMonths(d, event.shiftKey ? 12 : 1),
    }
    const move = moves[event.key]
    if (move) {
      event.preventDefault()
      moveTo(move())
    }
    else if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault()
      pick(d)
    }
  }

  return (
    <div data-ds="calendar" className={cn('inline-flex flex-col gap-2 type-ui text-fg', className)} role="group" aria-label={label}>
      <div className="flex items-center gap-1">
        <Button variant="ghost" size="sm" icon aria-label="Previous month" onClick={() => setFocused(addMonths(focused, -1))}><ChevronLeft size={16} strokeWidth={1.5} aria-hidden="true" /></Button>
        <p className="min-w-0 flex-1 text-center type-ui-strong" aria-live="polite">{caption}</p>
        <Button variant="ghost" size="sm" icon aria-label="Next month" onClick={() => setFocused(addMonths(focused, 1))}><ChevronRight size={16} strokeWidth={1.5} aria-hidden="true" /></Button>
      </div>
      <table ref={grid} role="grid" aria-label={caption} className="border-collapse" onKeyDown={onKey}>
        <thead>
          <tr>
            {weekdays.map(w => (
              <th key={w.long} scope="col" abbr={w.long} className="h-8 w-control-md p-0 text-center type-caption font-regular text-fg-muted max-md:w-control-touch">{w.short}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {weeks.map((week, i) => (
            <tr key={i}>
              {week.map((d) => {
                const outside = d.getMonth() !== month.getMonth()
                return (
                  <td key={d.getTime()} className="p-0" role="gridcell" aria-selected={same(d, model)}>
                    <button
                      type="button"
                      className={DAY}
                      tabIndex={same(d, focused) ? 0 : -1}
                      aria-label={dayLabel(d)}
                      aria-current={same(d, today) ? 'date' : undefined}
                      aria-disabled={blocked(d) || undefined}
                      data-picked={same(d, model) || undefined}
                      data-outside={outside || undefined}
                      onClick={() => pick(d)}
                      onFocus={outside ? undefined : () => setFocused(d)}
                    >
                      {d.getDate()}
                    </button>
                  </td>
                )
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

export default Calendar
react/lib/cn.ts
// 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(' ')
}
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/calendar.ts
import { html as staticHtml } from 'lit/static-html.js'
import { type PropertyValues } from 'lit'
import { ChevronLeft, ChevronRight } from 'lucide'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define, tag } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import '@/elements/components/ui/button'
import styles from 'virtual:tw'

// Calendar.tsx as <spyglass-calendar>: a month to pick a day from. 40px day cells (44px on phones) with the 4px
// corner, weekday heads in DM Sans 12px muted, the month in DM Sans Medium between two ghost arrow buttons. The picked
// day is a White fill with a Black figure; today carries a neutral hairline ring; the days of the months either side
// are faint; days that can't be picked are faint and struck through. Arrows move a day or a week, Home and End to the
// week's ends, Page Up and Page Down a month (with Shift a year), Enter or Space picks. Changing month doesn't
// animate. `value` (a Date, or an ISO date attribute) with `input` and `change`, and `select` fires on every pick.
// `min` and `max` are Dates (or ISO date attributes); `disabled` is a function of the day, set as a property.

const day0 = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate())
const same = (a: Date | null | undefined, b: Date | null | undefined) => !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n)
function addMonths(d: Date, n: number) {
	const last = new Date(d.getFullYear(), d.getMonth() + n + 1, 0).getDate()
	return new Date(d.getFullYear(), d.getMonth() + n, Math.min(d.getDate(), last))
}
const DAY = 'inline-flex size-control-md cursor-pointer items-center justify-center rounded-ds-sm border border-transparent type-ui tabular-nums text-fg outline-none transition-[background-color,color] duration-160 ease-standard hover:not-data-picked:not-aria-disabled:bg-ds-neutral-4 aria-[current=date]:border-fg-faint data-outside:text-fg-faint data-picked:bg-action-primary data-picked:font-medium data-picked:text-action-primary-fg aria-disabled:cursor-not-allowed aria-disabled:text-fg-faint aria-disabled:line-through focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-edge-focus data-picked:focus-visible:outline-fg-inverse max-md:size-control-touch'
// "2026-11-13" is that day where the page is, not midnight UTC.
const dateAttr = { fromAttribute: (v: string | null) => (v ? new Date(`${v}T00:00:00`) : null) }

/**
 * @summary A month to pick a day from.
 * @fires input - A day was picked (read `value`).
 * @fires change - A day was picked (read `value`).
 * @fires select - A day was picked; detail.value is the day.
 */
export class Calendar extends DsElement {
	static styles = [DsElement.styles, styles]
	static properties = {
		value: { converter: dateAttr },
		label: {},
		min: { converter: dateAttr },
		max: { converter: dateAttr },
		disabled: { attribute: false },
		weekStartsOn: { type: Number, attribute: 'week-starts-on' },
		locale: {},
		focused: { state: true },
	}

	value: Date | null = null
	/** The calendar's name for assistive tech. */
	label = 'Calendar'
	min?: Date | null
	max?: Date | null
	/** Days that can't be picked (a property: cal.disabled = (d) => d.getDay() === 0). */
	disabled?: (day: Date) => boolean
	/** 0 for Sunday, 1 for Monday. */
	weekStartsOn: 0 | 1 = 0
	locale = 'en-US'
	private focused = day0(new Date())
	private today = day0(new Date())
	private pendingFocus = false

	protected willUpdate(changed: PropertyValues) {
		super.willUpdate(changed)
		if (changed.has('value') && this.value && !same(this.value, this.focused)) this.focused = day0(this.value)
	}
	protected updated(changed: PropertyValues) {
		super.updated(changed)
		// The roving day takes focus once the move has rendered.
		if (this.pendingFocus) {
			this.pendingFocus = false
			this.renderRoot.querySelector<HTMLElement>('table [tabindex="0"]')?.focus()
		}
	}

	private blocked(d: Date) {
		return (!!this.min && d < day0(this.min)) || (!!this.max && d > day0(this.max)) || !!this.disabled?.(d)
	}
	private dayLabel(d: Date) {
		return d.toLocaleDateString(this.locale, { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })
	}
	private moveTo(d: Date) {
		this.focused = d
		this.pendingFocus = true
	}
	private pick(d: Date) {
		if (this.blocked(d)) return
		this.focused = d
		this.commit(d)
		this.emit('select', { value: d })
	}
	private onKey(event: KeyboardEvent) {
		const d = this.focused
		const start = addDays(d, -((d.getDay() - this.weekStartsOn + 7) % 7))
		const moves: Record<string, () => Date> = {
			ArrowLeft: () => addDays(d, -1),
			ArrowRight: () => addDays(d, 1),
			ArrowUp: () => addDays(d, -7),
			ArrowDown: () => addDays(d, 7),
			Home: () => start,
			End: () => addDays(start, 6),
			PageUp: () => addMonths(d, event.shiftKey ? -12 : -1),
			PageDown: () => addMonths(d, event.shiftKey ? 12 : 1),
		}
		const move = moves[event.key]
		if (move) {
			event.preventDefault()
			this.moveTo(move())
		} else if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault()
			this.pick(d)
		}
	}

	render() {
		const month = new Date(this.focused.getFullYear(), this.focused.getMonth(), 1)
		const caption = month.toLocaleDateString(this.locale, { month: 'long', year: 'numeric' })
		const weekdays = Array.from({ length: 7 }, (_, i) => {
			const d = new Date(2026, 1, 1 + ((i + this.weekStartsOn) % 7)) // 1 February 2026 is a Sunday.
			return { short: d.toLocaleDateString(this.locale, { weekday: 'short' }).slice(0, 2), long: d.toLocaleDateString(this.locale, { weekday: 'long' }) }
		})
		// Whole weeks: the days of the months either side fill the first and last rows.
		const lead = (month.getDay() - this.weekStartsOn + 7) % 7
		const count = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate()
		const cells = Array.from({ length: Math.ceil((lead + count) / 7) * 7 }, (_, i) => new Date(month.getFullYear(), month.getMonth(), i - lead + 1))
		const weeks = Array.from({ length: cells.length / 7 }, (_, w) => cells.slice(w * 7, w * 7 + 7))
		const button = tag('button')
		return staticHtml`<div data-ds="calendar" class="inline-flex flex-col gap-2 type-ui text-fg" role="group" aria-label=${this.label}>
			<div class="flex items-center gap-1">
				<${button} variant="ghost" size="sm" icon aria-label="Previous month" @click=${() => { this.focused = addMonths(this.focused, -1) }}>${icon(ChevronLeft, 'chevron-left', { size: 16, strokeWidth: 1.5, attrs: { 'aria-hidden': 'true' } })}</${button}>
				<p class="min-w-0 flex-1 text-center type-ui-strong" aria-live="polite">${caption}</p>
				<${button} variant="ghost" size="sm" icon aria-label="Next month" @click=${() => { this.focused = addMonths(this.focused, 1) }}>${icon(ChevronRight, 'chevron-right', { size: 16, strokeWidth: 1.5, attrs: { 'aria-hidden': 'true' } })}</${button}>
			</div>
			<table role="grid" aria-label=${caption} class="border-collapse" @keydown=${this.onKey}>
				<thead>
					<tr>${weekdays.map((w) => staticHtml`<th scope="col" abbr=${w.long} class="h-8 w-control-md p-0 text-center type-caption font-regular text-fg-muted max-md:w-control-touch">${w.short}</th>`)}</tr>
				</thead>
				<tbody>${weeks.map((week) => staticHtml`<tr>${week.map((d) => {
					const outside = d.getMonth() !== month.getMonth()
					return staticHtml`<td class="p-0" role="gridcell" aria-selected=${String(same(d, this.value))}><button
							type="button"
							class=${DAY}
							tabindex=${same(d, this.focused) ? '0' : '-1'}
							aria-label=${this.dayLabel(d)}
							aria-current=${ifDefined(same(d, this.today) ? 'date' : undefined)}
							aria-disabled=${ifDefined(this.blocked(d) ? 'true' : undefined)}
							data-picked=${ifDefined(same(d, this.value) ? 'true' : undefined)}
							data-outside=${ifDefined(outside ? 'true' : undefined)}
							@click=${() => this.pick(d)}
							@focus=${() => { if (!outside) this.focused = d }}
						>${d.getDate()}</button></td>`
				})}</tr>`)}</tbody>
			</table>
		</div>`
	}
}

define('calendar', Calendar)

Reference: Derived from the guidelines: White on Black for the one choice, neutral hairlines, DM Sans for figures and labels, the 10px canvas corner scaled to the product (4px inside small cells). shadcn's calendar for anatomy, keys and ARIA (a grid with a roving day)..