← Components

Selection and input · Material 3: Date pickers (calendar)

Calendar

A month grid for a date or range. The selected pill slides to the new day; a range band stretches to the hovered day; months slide in the direction of travel.

Examples and variants

Single date

Click days or use the arrow keys.

January 2000
MTWTFSS
Example
function CalendarSingle() {
  const [date, setDate] = useState<Date | undefined>()
  return <Calendar value={date} onChange={setDate} />
}

Range

Pick a start, hover to see the band, pick an end.

January 2000
MTWTFSS
Example
function CalendarRangeExample() {
  const [range, setRange] = useState<CalendarRange>({})
  return <Calendar mode="range" value={range} onChange={setRange} />
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/calendar.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install @base-ui/react class-variance-authority cn lucide-react
  2. Copy these 2 files to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/button.tsxbutton
      components/ui/button.tsx
      "use client"
      
      import { useRef, useState } from "react"
      import { Button as ButtonPrimitive } from "@base-ui/react/button"
      import { CheckIcon, XIcon } from "lucide-react"
      import { tokenMs } from "@/lib/motion/token-ms"
      import { cva, type VariantProps } from "class-variance-authority"
      import { cn } from "cn"
      
      // Minimal: no strokes on controls (DESIGN.md rule 11), token sizes, token focus ring,
      // liquid press squash instead of shadcn's translate-y nudge.
      // Every visual spec reads a component token (styles/tokens/components.css, --button-*).
      // Sizes: sm | md | lg (default = md). Variants: primary (default) | secondary | outline | ghost | link.
      const filled = {
        primary:
          "bg-(--button-primary-container) text-(--button-primary-label) hover:bg-(--button-primary-container-hover) active:bg-(--button-primary-container-pressed)",
        secondary:
          "bg-(--button-secondary-container) text-(--button-secondary-label) hover:bg-(--button-secondary-container-hover) active:bg-(--button-secondary-container-pressed) aria-expanded:bg-(--button-secondary-container-hover)",
      }
      
      const buttonVariants = cva(
        "liquid-press group/button relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-(--button-corner) border-solid border-(length:--button-stroke-width) border-(--stroke-color-default) bg-clip-padding text-(length:--button-label-size) [font-weight:var(--button-label-weight)] whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring) disabled:pointer-events-none disabled:bg-(--button-container-disabled) disabled:text-(--button-label-disabled) disabled:shadow-none aria-invalid:shadow-(--focus-ring-invalid) [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--button-icon-size)",
        {
          variants: {
            variant: {
              primary: filled.primary,
              default: filled.primary,
              secondary: filled.secondary,
              outline:
                "bg-(--button-outline-container) text-(--button-secondary-label) shadow-(--button-outline-elevation) hover:bg-(--button-outline-container-hover) active:bg-(--button-outline-container-pressed) aria-expanded:bg-(--button-outline-container-hover)",
              ghost: "text-(--button-secondary-label) hover:bg-(--button-ghost-container-hover) active:bg-(--button-ghost-container-pressed) aria-expanded:bg-(--button-ghost-container-hover) disabled:bg-transparent",
              destructive: "",
              link: "text-(--button-link-label) underline-offset-4 hover:underline disabled:bg-transparent",
            },
            size: {
              xs: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-xs) gap-(--button-gap-sm) px-(--button-padding-x-xs) text-(length:--button-label-size-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              sm: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-sm) gap-(--button-gap-sm) px-(--button-padding-x-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              md: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)",
              default: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)",
              lg: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-lg) gap-(--button-gap) px-(--button-padding-x-lg) has-data-[icon=inline-end]:pe-(--button-padding-x-md) has-data-[icon=inline-start]:ps-(--button-padding-x-md) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)",
              icon: "size-(--icon-button-size-md) rounded-(--icon-button-corner)",
              "icon-xs": "size-(--button-height-xs) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              "icon-sm": "size-(--icon-button-size-sm) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              "icon-md": "size-(--icon-button-size-md) rounded-(--icon-button-corner)",
              "icon-lg": "size-(--icon-button-size-lg) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)",
            },
            tone: {
              neutral: "",
              danger: "",
              success: "",
            },
          },
          // tone: colour intent on any variant (component-model.md §7). destructive = tone danger.
          compoundVariants: [
            {
              tone: "danger",
              variant: ["primary", "default", "secondary", "outline", "destructive"],
              className:
                "bg-(--button-danger-container) text-(--button-danger-label) shadow-none hover:bg-(--button-danger-container-hover) active:bg-(--button-danger-container-pressed) [--focus-ring-color:var(--color-danger)]",
            },
            {
              tone: "danger",
              variant: ["ghost", "link"],
              className: "text-(--button-danger-label) hover:bg-(--button-danger-container) active:bg-(--button-danger-container-hover) [--focus-ring-color:var(--color-danger)]",
            },
            {
              tone: "success",
              variant: ["primary", "default", "secondary", "outline"],
              className: "bg-(--button-success-container) text-(--button-success-label) shadow-none hover:bg-(--button-success-container-hover) active:bg-(--button-success-container-pressed)",
            },
          ],
          defaultVariants: {
            variant: "primary",
            size: "md",
            tone: "neutral",
          },
        }
      )
      
      type Wash = { id: number; x: number; y: number }
      type Status = "idle" | "loading" | "success" | "error"
      type ButtonProps = ButtonPrimitive.Props &
        VariantProps<typeof buttonVariants> & {
          /**
           * The button shows its own result inside a fixed width: spinner, then a
           * check or a cross. Prefer this to a toast (component-model.md §5).
           */
          status?: Status
          /** "hold": the click only happens after holding for --duration-fill (pointer, Space or Enter). */
          confirm?: "hold"
          /** Screen reader text for the success and error states. */
          statusLabel?: { success?: string; error?: string }
          /** @deprecated use status="loading" */
          loading?: boolean
          /** @deprecated use status="success" */
          success?: boolean
        }
      
      function Button({
        className,
        variant = "primary",
        size = "md",
        tone = "neutral",
        status: statusProp,
        confirm,
        statusLabel,
        loading = false,
        success = false,
        children,
        onClick,
        onPointerUp,
        onPointerDown,
        onPointerLeave,
        onKeyDown,
        onKeyUp,
        ...props
      }: ButtonProps) {
        const status: Status = statusProp ?? (loading ? "loading" : success ? "success" : "idle")
        const busy = status === "loading"
        const [wash, setWash] = useState<Wash | null>(null)
        const [held, setHeld] = useState(false)
        const holdTimer = useRef(0)
        const allowClick = useRef(false)
        const self = useRef<HTMLElement | null>(null)
        const resolvedTone = variant === "destructive" ? "danger" : tone
      
        function startHold(element: HTMLElement) {
          if (confirm !== "hold" || busy) return
          self.current = element
          setHeld(true)
          window.clearTimeout(holdTimer.current)
          holdTimer.current = window.setTimeout(() => {
            setHeld(false)
            allowClick.current = true
            self.current?.click()
            allowClick.current = false
          }, tokenMs("--duration-fill", element))
        }
      
        function stopHold() {
          if (confirm !== "hold") return
          setHeld(false)
          window.clearTimeout(holdTimer.current)
        }
      
        function handleClick(event: Parameters<NonNullable<ButtonProps["onClick"]>>[0]) {
          if (busy || (confirm === "hold" && !allowClick.current)) {
            event.preventDefault()
            return
          }
          onClick?.(event)
        }
      
        function handlePointerUp(event: Parameters<NonNullable<ButtonProps["onPointerUp"]>>[0]) {
          onPointerUp?.(event)
          stopHold()
          if (event.defaultPrevented || busy || confirm === "hold") return
          if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
          const motion = event.currentTarget.closest<HTMLElement>("[data-motion]")?.dataset.motion
          if (motion === "calm" || motion === "still") return
          const rect = event.currentTarget.getBoundingClientRect()
          setWash({
            id: Date.now(),
            x: event.clientX - rect.left,
            y: event.clientY - rect.top,
          })
        }
      
        const showResult = status === "success" || status === "error"
      
        return (
          <ButtonPrimitive
            data-slot="button"
            data-icon={typeof size === "string" && size.startsWith("icon") ? "" : undefined}
            data-tone={resolvedTone}
            data-status={status}
            data-confirm={confirm}
            aria-busy={busy || undefined}
            aria-disabled={busy || undefined}
            {...props}
            className={cn(
              buttonVariants({ variant, size, tone: resolvedTone, className }),
              status === "error" && "animate-[isotope-nudge_var(--duration-fast)_var(--ease-out)]"
            )}
            onClick={handleClick}
            onPointerUp={handlePointerUp}
            onPointerDown={(event) => {
              onPointerDown?.(event)
              if (event.button === 0) startHold(event.currentTarget)
            }}
            onPointerLeave={(event) => {
              onPointerLeave?.(event)
              stopHold()
            }}
            onKeyDown={(event) => {
              onKeyDown?.(event)
              if (confirm === "hold" && (event.key === " " || event.key === "Enter") && !event.repeat) {
                startHold(event.currentTarget)
              }
            }}
            onKeyUp={(event) => {
              onKeyUp?.(event)
              if (event.key === " " || event.key === "Enter") stopHold()
            }}
          >
            {confirm === "hold" ? (
              <span
                aria-hidden
                data-held={held ? "" : undefined}
                className="hold-fill pointer-events-none absolute inset-y-0 left-0 w-full bg-current opacity-20"
              />
            ) : null}
            <span
              className={cn(
                "button-label relative inline-flex items-center justify-center gap-[inherit]",
                (busy || showResult) &&
                  "opacity-0 blur-(--motion-blur-enter) transition-[opacity,filter] duration-(--duration-fast) ease-(--ease-out)"
              )}
            >
              {children}
              {confirm === "hold" ? <span className="sr-only">(hold to confirm)</span> : null}
            </span>
            {showResult ? (
              <span className="button-success absolute inset-0 inline-flex items-center justify-center" role="status">
                <span className="sr-only">
                  {status === "success" ? statusLabel?.success ?? "Done" : statusLabel?.error ?? "Failed"}
                </span>
                {status === "success" ? <CheckIcon aria-hidden /> : <XIcon aria-hidden />}
              </span>
            ) : null}
            {busy ? (
              <span className="absolute inset-0 inline-flex items-center justify-center gap-inline-xs">
                <span className="sr-only">Loading</span>
                {[0, 1, 2].map((dot) => (
                  <span
                    key={dot}
                    aria-hidden
                    className="size-inline-xs rounded-full bg-current animate-[isotope-pulse_var(--duration-pulse)_var(--ease-out)_infinite]"
                    style={{ animationDelay: `calc(var(--duration-stagger) * ${dot})` }}
                  />
                ))}
              </span>
            ) : null}
            {wash ? (
              <span
                key={wash.id}
                aria-hidden
                onAnimationEnd={() => setWash(null)}
                className="pointer-events-none absolute size-[calc(var(--size-control-lg)*4)] rounded-full bg-current animate-[isotope-wash_var(--duration-settle)_var(--ease-out)_both]"
                style={{ left: wash.x, top: wash.y }}
              />
            ) : null}
          </ButtonPrimitive>
        )
      }
      
      export { Button, buttonVariants }
      export type { ButtonProps }
      
    • components/ui/calendar.tsxcalendar
      components/ui/calendar.tsx
      "use client"
      
      import * as React from "react"
      import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"
      import { cn } from "cn"
      import { Button } from "@/components/ui/button"
      
      /*
        Calendar: a month grid for picking a date or a range.
        - The selected day is a pill that slides to the new day (single).
        - In range mode, after picking the start, hovering stretches a band to the
          hovered day; picking the end settles it.
        - Changing month slides the grid in the direction of travel.
        Keyboard: arrows move by day and week, Page Up/Down by month, Home/End to
        the week's ends, Enter or Space picks.
      */
      type Range = { from?: Date; to?: Date }
      
      // "Today" is read on the client only (pre-rendered HTML can't know it).
      let cachedToday: Date | null = null
      function todaySnapshot() {
        const now = new Date()
        if (!cachedToday || cachedToday.toDateString() !== now.toDateString()) {
          cachedToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        }
        return cachedToday
      }
      const noopSubscribe = () => () => {}
      function useToday() {
        return React.useSyncExternalStore(noopSubscribe, todaySnapshot, () => null)
      }
      
      const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate())
      const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n)
      const addMonths = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth() + n, Math.min(d.getDate(), 28))
      const sameDay = (a?: Date, b?: Date) => !!a && !!b && a.toDateString() === b.toDateString()
      const between = (d: Date, a: Date, b: Date) => {
        const [lo, hi] = a <= b ? [a, b] : [b, a]
        return d > lo && d < hi
      }
      
      type CalendarProps = {
        weekStartsOn?: 0 | 1
        locale?: string
        disabled?: (date: Date) => boolean
        className?: string
        defaultMonth?: Date
      } & (
        | { mode?: "single"; value?: Date; onChange?: (date: Date) => void }
        | { mode: "range"; value?: Range; onChange?: (range: Range) => void }
      )
      
      function Calendar(props: CalendarProps) {
        const { weekStartsOn = 1, locale, disabled, className } = props
        const today = useToday()
        const given = props.mode === "range" ? props.value?.from ?? props.defaultMonth : (props.value as Date | undefined) ?? props.defaultMonth
        const [chosenMonth, setChosenMonth] = React.useState<Date | null>(given ? new Date(given.getFullYear(), given.getMonth(), 1) : null)
        const [chosenFocus, setFocused] = React.useState<Date | null>(given ? startOfDay(given) : null)
        const fallback = React.useMemo(() => today ?? new Date(2000, 0, 1), [today])
        const month = React.useMemo(
          () => chosenMonth ?? new Date(fallback.getFullYear(), fallback.getMonth(), 1),
          [chosenMonth, fallback]
        )
        const focused = chosenFocus ?? fallback
        const setMonth = (next: Date | ((m: Date) => Date)) => setChosenMonth(typeof next === "function" ? next(month) : next)
        const [hover, setHover] = React.useState<Date | null>(null)
        const [dir, setDir] = React.useState(0)
        const gridRef = React.useRef<HTMLDivElement>(null)
        const pillRef = React.useRef<HTMLSpanElement>(null)
      
        const single = props.mode !== "range" ? (props.value as Date | undefined) : undefined
        const range = props.mode === "range" ? props.value ?? {} : {}
      
        const first = new Date(month.getFullYear(), month.getMonth(), 1)
        const offset = (first.getDay() - weekStartsOn + 7) % 7
        const days = Array.from({ length: 42 }, (_, i) => addDays(first, i - offset))
        const weekdays = Array.from({ length: 7 }, (_, i) =>
          new Intl.DateTimeFormat(locale, { weekday: "narrow" }).format(addDays(new Date(2024, 0, 7 + weekStartsOn), i))
        )
        const title = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(month)
        const full = new Intl.DateTimeFormat(locale, { dateStyle: "full" })
      
        function go(n: number) {
          setDir(Math.sign(n))
          setMonth((m) => new Date(m.getFullYear(), m.getMonth() + n, 1))
        }
      
        function focusDay(d: Date) {
          setFocused(d)
          if (d.getMonth() !== month.getMonth() || d.getFullYear() !== month.getFullYear()) {
            setDir(d > month ? 1 : -1)
            setMonth(new Date(d.getFullYear(), d.getMonth(), 1))
          }
        }
      
        function pick(d: Date) {
          if (disabled?.(d)) return
          focusDay(d)
          if (props.mode === "range") {
            const { from, to } = range
            if (!from || to) props.onChange?.({ from: d, to: undefined })
            else props.onChange?.(d < from ? { from: d, to: from } : { from, to: d })
          } else {
            props.onChange?.(d)
          }
        }
      
        // Keep keyboard focus on the focused day.
        React.useEffect(() => {
          const el = gridRef.current?.querySelector<HTMLButtonElement>(`[data-day="${focused.toDateString()}"]`)
          if (el && gridRef.current?.contains(document.activeElement)) el.focus()
        }, [focused, month])
      
        // Single mode: the selected pill slides to the selected day (positioned directly, no re-render).
        React.useLayoutEffect(() => {
          const pill = pillRef.current
          const grid = gridRef.current
          if (!pill) return
          const place = () => {
            const button = single ? grid?.querySelector<HTMLElement>(`[data-day="${single.toDateString()}"]`) : null
            // The day sits in a positioned cell, so the button's offset is inside that
            // cell. The pill is positioned on the grid, so it follows the cell.
            const el = button?.closest<HTMLElement>("[role=gridcell]") ?? null
            if (!el) {
              pill.style.opacity = "0"
              return
            }
            pill.style.opacity = "1"
            pill.style.left = `${el.offsetLeft}px`
            pill.style.top = `${el.offsetTop}px`
            pill.style.width = `${el.offsetWidth}px`
            pill.style.height = `${el.offsetHeight}px`
          }
          place()
          if (!grid) return
          const observer = new ResizeObserver(place)
          observer.observe(grid)
          return () => observer.disconnect()
        }, [single, month])
      
        function onKeyDown(event: React.KeyboardEvent) {
          const moves: Record<string, () => Date> = {
            ArrowLeft: () => addDays(focused, -1),
            ArrowRight: () => addDays(focused, 1),
            ArrowUp: () => addDays(focused, -7),
            ArrowDown: () => addDays(focused, 7),
            PageUp: () => addMonths(focused, -1),
            PageDown: () => addMonths(focused, 1),
            Home: () => addDays(focused, -((focused.getDay() - weekStartsOn + 7) % 7)),
            End: () => addDays(focused, 6 - ((focused.getDay() - weekStartsOn + 7) % 7)),
          }
          if (moves[event.key]) {
            event.preventDefault()
            focusDay(moves[event.key]())
          }
        }
      
        const pendingEnd = props.mode === "range" && range.from && !range.to ? hover : null
      
        return (
          <div data-slot="calendar" className={cn("w-(--calendar-width) select-none", className)}>
            <div className="mb-2 flex items-center justify-between">
              <Button size="icon-sm" variant="ghost" aria-label="Previous month" onClick={() => go(-1)}>
                <ChevronLeftIcon />
              </Button>
              <div aria-live="polite" className="calendar-title overflow-hidden text-sm font-medium">
                <span key={title} data-dir={dir > 0 ? "next" : dir < 0 ? "prev" : undefined} className="calendar-roll inline-block">
                  {title}
                </span>
              </div>
              <Button size="icon-sm" variant="ghost" aria-label="Next month" onClick={() => go(1)}>
                <ChevronRightIcon />
              </Button>
            </div>
            <div role="grid" aria-label={title} onKeyDown={onKeyDown} onMouseLeave={() => setHover(null)}>
              <div role="row" className="grid grid-cols-7">
                {weekdays.map((d, i) => (
                  <span key={i} role="columnheader" className="flex h-(--calendar-day-size) items-center justify-center text-caption text-ink-subtle">
                    {d}
                  </span>
                ))}
              </div>
              <div ref={gridRef} key={month.toDateString()} data-dir={dir > 0 ? "next" : dir < 0 ? "prev" : undefined} className="calendar-grid relative grid grid-cols-7">
                {props.mode !== "range" ? (
                  <span
                    ref={pillRef}
                    aria-hidden
                    className="calendar-pill pointer-events-none absolute rounded-(--calendar-day-corner) bg-(--calendar-selected) opacity-0"
                  />
                ) : null}
                {days.map((d) => {
                  const outside = d.getMonth() !== month.getMonth()
                  const isToday = sameDay(d, today ?? undefined)
                  const start = sameDay(d, range.from)
                  const end = sameDay(d, range.to) || (pendingEnd ? sameDay(d, pendingEnd) : false)
                  const inBand =
                    (range.from && range.to && between(d, range.from, range.to)) ||
                    (range.from && pendingEnd && between(d, range.from, pendingEnd))
                  const selected = sameDay(d, single) || start || sameDay(d, range.to)
                  const off = disabled?.(d) ?? false
                  return (
                    <div
                      key={d.toDateString()}
                      role="gridcell"
                      aria-selected={selected || undefined}
                      data-band={inBand ? "" : undefined}
                      data-start={start || undefined}
                      data-end={end && !start ? "" : undefined}
                      className="calendar-cell relative flex items-center justify-center"
                    >
                      <button
                        type="button"
                        data-day={d.toDateString()}
                        tabIndex={sameDay(d, focused) ? 0 : -1}
                        disabled={off}
                        aria-label={full.format(d)}
                        aria-current={isToday ? "date" : undefined}
                        onClick={() => pick(d)}
                        onMouseEnter={() => setHover(d)}
                        className={cn(
                          "calendar-day relative z-[1] inline-flex size-(--calendar-day-size) items-center justify-center rounded-(--calendar-day-corner) text-sm tabular-nums outline-none hover:bg-(--calendar-day-container-hover) focus-visible:shadow-(--focus-ring) disabled:text-(--calendar-day-label-disabled)",
                          outside && "text-ink-subtle",
                          selected && "font-medium text-(--calendar-selected-label) hover:bg-transparent",
                          (start || (end && !start)) && props.mode === "range" && "bg-(--calendar-selected)"
                        )}
                      >
                        {d.getDate()}
                        {isToday ? <span aria-hidden className="absolute bottom-1 size-1 rounded-full bg-current" /> : null}
                      </button>
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        )
      }
      
      export { Calendar }
      export type { Range as CalendarRange }
      

Imports

What the examples on this page import:

Imports
import { CopyIcon, FileIcon, MoonIcon, PlusIcon, SettingsIcon, TrashIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Calendar, type CalendarRange } from "@/components/ui/calendar"
import { Carousel } from "@/components/ui/carousel"
import { CommandDialog, type CommandItem } from "@/components/ui/command"
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "@/components/ui/context-menu"
import { DatePicker } from "@/components/ui/date-picker"
import { DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut } from "@/components/ui/dropdown-menu"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { Menubar, MenubarMenu, MenubarTrigger } from "@/components/ui/menubar"
import { Search } from "@/components/ui/search"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { TimePicker } from "@/components/ui/time-picker"

Anatomy

  1. 1Header · Previous and next month buttons; the month title rolls.
  2. 2Weekdays · Narrow names from the locale.
  3. 3Day · --calendar-day-size, --calendar-day-corner; today has a dot.
  4. 4Selection · --calendar-selected pill; range band --calendar-band.

Props

PropTypeDefaultDescription
mode"single" | "range""single"One date or a range.
value / onChangeDate | { from?: Date; to?: Date }—Controlled value.
weekStartsOn0 | 11Sunday or Monday.
localestring—Intl locale for names.
disabled(date: Date) => boolean—Days that can't be picked.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--calendar-day-sizevar(--size-control-md)40pxsame
--calendar-day-cornervar(--shape-full)999pxsame
--calendar-day-container-hovervar(--color-bg-hover)oklch(0.965 0.005 95)oklch(0.22 0 0)
--calendar-day-label-disabledvar(--color-fg-disabled)oklch(0.62 0.01 95)oklch(0.53 0 0)
--calendar-widthcalc(var(--calendar-day-size) * 7)calc(var(--calendar-day-size) * 7)same
--calendar-selectedvar(--color-brand)oklch(0.18 0.008 260)oklch(0.98 0 0)
--calendar-selected-labelvar(--color-fg-on-accent)oklch(0.97 0.004 95)oklch(0.14 0 0)
--calendar-bandvar(--color-bg-selected)color-mix(in oklch, var(--ref-select) 12%, transparent)color-mix(in oklch, var(--ref-select) 16%, transparent)

Motion

TriggerWhat happensTokens
PickThe pill slides to the new day on a spring.--spring-snappy
Range hoverThe band stretches from the start to the hovered day.--duration-fast
Change monthThe grid slides in; the title rolls.--duration-settle

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • grid role; arrows by day and week, Page Up/Down by month, Home/End to week ends.
  • Each day has its full date as a label; today has aria-current=date.

Usage

Do

  • Use when seeing the month helps.

Don’t

  • Don't use for birthdays (typing is faster).

Code

components/ui/calendar.tsx
"use client"

import * as React from "react"
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"

/*
  Calendar: a month grid for picking a date or a range.
  - The selected day is a pill that slides to the new day (single).
  - In range mode, after picking the start, hovering stretches a band to the
    hovered day; picking the end settles it.
  - Changing month slides the grid in the direction of travel.
  Keyboard: arrows move by day and week, Page Up/Down by month, Home/End to
  the week's ends, Enter or Space picks.
*/
type Range = { from?: Date; to?: Date }

// "Today" is read on the client only (pre-rendered HTML can't know it).
let cachedToday: Date | null = null
function todaySnapshot() {
  const now = new Date()
  if (!cachedToday || cachedToday.toDateString() !== now.toDateString()) {
    cachedToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  }
  return cachedToday
}
const noopSubscribe = () => () => {}
function useToday() {
  return React.useSyncExternalStore(noopSubscribe, todaySnapshot, () => null)
}

const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate())
const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n)
const addMonths = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth() + n, Math.min(d.getDate(), 28))
const sameDay = (a?: Date, b?: Date) => !!a && !!b && a.toDateString() === b.toDateString()
const between = (d: Date, a: Date, b: Date) => {
  const [lo, hi] = a <= b ? [a, b] : [b, a]
  return d > lo && d < hi
}

type CalendarProps = {
  weekStartsOn?: 0 | 1
  locale?: string
  disabled?: (date: Date) => boolean
  className?: string
  defaultMonth?: Date
} & (
  | { mode?: "single"; value?: Date; onChange?: (date: Date) => void }
  | { mode: "range"; value?: Range; onChange?: (range: Range) => void }
)

function Calendar(props: CalendarProps) {
  const { weekStartsOn = 1, locale, disabled, className } = props
  const today = useToday()
  const given = props.mode === "range" ? props.value?.from ?? props.defaultMonth : (props.value as Date | undefined) ?? props.defaultMonth
  const [chosenMonth, setChosenMonth] = React.useState<Date | null>(given ? new Date(given.getFullYear(), given.getMonth(), 1) : null)
  const [chosenFocus, setFocused] = React.useState<Date | null>(given ? startOfDay(given) : null)
  const fallback = React.useMemo(() => today ?? new Date(2000, 0, 1), [today])
  const month = React.useMemo(
    () => chosenMonth ?? new Date(fallback.getFullYear(), fallback.getMonth(), 1),
    [chosenMonth, fallback]
  )
  const focused = chosenFocus ?? fallback
  const setMonth = (next: Date | ((m: Date) => Date)) => setChosenMonth(typeof next === "function" ? next(month) : next)
  const [hover, setHover] = React.useState<Date | null>(null)
  const [dir, setDir] = React.useState(0)
  const gridRef = React.useRef<HTMLDivElement>(null)
  const pillRef = React.useRef<HTMLSpanElement>(null)

  const single = props.mode !== "range" ? (props.value as Date | undefined) : undefined
  const range = props.mode === "range" ? props.value ?? {} : {}

  const first = new Date(month.getFullYear(), month.getMonth(), 1)
  const offset = (first.getDay() - weekStartsOn + 7) % 7
  const days = Array.from({ length: 42 }, (_, i) => addDays(first, i - offset))
  const weekdays = Array.from({ length: 7 }, (_, i) =>
    new Intl.DateTimeFormat(locale, { weekday: "narrow" }).format(addDays(new Date(2024, 0, 7 + weekStartsOn), i))
  )
  const title = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(month)
  const full = new Intl.DateTimeFormat(locale, { dateStyle: "full" })

  function go(n: number) {
    setDir(Math.sign(n))
    setMonth((m) => new Date(m.getFullYear(), m.getMonth() + n, 1))
  }

  function focusDay(d: Date) {
    setFocused(d)
    if (d.getMonth() !== month.getMonth() || d.getFullYear() !== month.getFullYear()) {
      setDir(d > month ? 1 : -1)
      setMonth(new Date(d.getFullYear(), d.getMonth(), 1))
    }
  }

  function pick(d: Date) {
    if (disabled?.(d)) return
    focusDay(d)
    if (props.mode === "range") {
      const { from, to } = range
      if (!from || to) props.onChange?.({ from: d, to: undefined })
      else props.onChange?.(d < from ? { from: d, to: from } : { from, to: d })
    } else {
      props.onChange?.(d)
    }
  }

  // Keep keyboard focus on the focused day.
  React.useEffect(() => {
    const el = gridRef.current?.querySelector<HTMLButtonElement>(`[data-day="${focused.toDateString()}"]`)
    if (el && gridRef.current?.contains(document.activeElement)) el.focus()
  }, [focused, month])

  // Single mode: the selected pill slides to the selected day (positioned directly, no re-render).
  React.useLayoutEffect(() => {
    const pill = pillRef.current
    const grid = gridRef.current
    if (!pill) return
    const place = () => {
      const button = single ? grid?.querySelector<HTMLElement>(`[data-day="${single.toDateString()}"]`) : null
      // The day sits in a positioned cell, so the button's offset is inside that
      // cell. The pill is positioned on the grid, so it follows the cell.
      const el = button?.closest<HTMLElement>("[role=gridcell]") ?? null
      if (!el) {
        pill.style.opacity = "0"
        return
      }
      pill.style.opacity = "1"
      pill.style.left = `${el.offsetLeft}px`
      pill.style.top = `${el.offsetTop}px`
      pill.style.width = `${el.offsetWidth}px`
      pill.style.height = `${el.offsetHeight}px`
    }
    place()
    if (!grid) return
    const observer = new ResizeObserver(place)
    observer.observe(grid)
    return () => observer.disconnect()
  }, [single, month])

  function onKeyDown(event: React.KeyboardEvent) {
    const moves: Record<string, () => Date> = {
      ArrowLeft: () => addDays(focused, -1),
      ArrowRight: () => addDays(focused, 1),
      ArrowUp: () => addDays(focused, -7),
      ArrowDown: () => addDays(focused, 7),
      PageUp: () => addMonths(focused, -1),
      PageDown: () => addMonths(focused, 1),
      Home: () => addDays(focused, -((focused.getDay() - weekStartsOn + 7) % 7)),
      End: () => addDays(focused, 6 - ((focused.getDay() - weekStartsOn + 7) % 7)),
    }
    if (moves[event.key]) {
      event.preventDefault()
      focusDay(moves[event.key]())
    }
  }

  const pendingEnd = props.mode === "range" && range.from && !range.to ? hover : null

  return (
    <div data-slot="calendar" className={cn("w-(--calendar-width) select-none", className)}>
      <div className="mb-2 flex items-center justify-between">
        <Button size="icon-sm" variant="ghost" aria-label="Previous month" onClick={() => go(-1)}>
          <ChevronLeftIcon />
        </Button>
        <div aria-live="polite" className="calendar-title overflow-hidden text-sm font-medium">
          <span key={title} data-dir={dir > 0 ? "next" : dir < 0 ? "prev" : undefined} className="calendar-roll inline-block">
            {title}
          </span>
        </div>
        <Button size="icon-sm" variant="ghost" aria-label="Next month" onClick={() => go(1)}>
          <ChevronRightIcon />
        </Button>
      </div>
      <div role="grid" aria-label={title} onKeyDown={onKeyDown} onMouseLeave={() => setHover(null)}>
        <div role="row" className="grid grid-cols-7">
          {weekdays.map((d, i) => (
            <span key={i} role="columnheader" className="flex h-(--calendar-day-size) items-center justify-center text-caption text-ink-subtle">
              {d}
            </span>
          ))}
        </div>
        <div ref={gridRef} key={month.toDateString()} data-dir={dir > 0 ? "next" : dir < 0 ? "prev" : undefined} className="calendar-grid relative grid grid-cols-7">
          {props.mode !== "range" ? (
            <span
              ref={pillRef}
              aria-hidden
              className="calendar-pill pointer-events-none absolute rounded-(--calendar-day-corner) bg-(--calendar-selected) opacity-0"
            />
          ) : null}
          {days.map((d) => {
            const outside = d.getMonth() !== month.getMonth()
            const isToday = sameDay(d, today ?? undefined)
            const start = sameDay(d, range.from)
            const end = sameDay(d, range.to) || (pendingEnd ? sameDay(d, pendingEnd) : false)
            const inBand =
              (range.from && range.to && between(d, range.from, range.to)) ||
              (range.from && pendingEnd && between(d, range.from, pendingEnd))
            const selected = sameDay(d, single) || start || sameDay(d, range.to)
            const off = disabled?.(d) ?? false
            return (
              <div
                key={d.toDateString()}
                role="gridcell"
                aria-selected={selected || undefined}
                data-band={inBand ? "" : undefined}
                data-start={start || undefined}
                data-end={end && !start ? "" : undefined}
                className="calendar-cell relative flex items-center justify-center"
              >
                <button
                  type="button"
                  data-day={d.toDateString()}
                  tabIndex={sameDay(d, focused) ? 0 : -1}
                  disabled={off}
                  aria-label={full.format(d)}
                  aria-current={isToday ? "date" : undefined}
                  onClick={() => pick(d)}
                  onMouseEnter={() => setHover(d)}
                  className={cn(
                    "calendar-day relative z-[1] inline-flex size-(--calendar-day-size) items-center justify-center rounded-(--calendar-day-corner) text-sm tabular-nums outline-none hover:bg-(--calendar-day-container-hover) focus-visible:shadow-(--focus-ring) disabled:text-(--calendar-day-label-disabled)",
                    outside && "text-ink-subtle",
                    selected && "font-medium text-(--calendar-selected-label) hover:bg-transparent",
                    (start || (end && !start)) && props.mode === "range" && "bg-(--calendar-selected)"
                  )}
                >
                  {d.getDate()}
                  {isToday ? <span aria-hidden className="absolute bottom-1 size-1 rounded-full bg-current" /> : null}
                </button>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export { Calendar }
export type { Range as CalendarRange }