Selection and input · Material 3: Date pickers (docked)
Date picker
A date field with a calendar in a popover. Typing a date works too.
Examples and variants
Basic
Type 2026-12-24, or open the calendar.
function DatePickerExample() {
const [date, setDate] = useState<Date | undefined>()
return <DatePicker label="Start date" value={date} onChange={setDate} />
}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.
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/date-picker.json
npx shadcn@latest add https://isotopi.com/r/calendar.json
npx shadcn@latest add https://isotopi.com/r/popover.jsonBy hand
No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.
Install the packages it uses.
Terminalnpm install @base-ui/react class-variance-authority cn lucide-reactCopy these 4 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 }components/ui/popover.tsxpopover
components/ui/popover.tsx"use client" import * as React from "react" import { Popover as PopoverPrimitive } from "@base-ui/react/popover" import { cn } from "cn" import { GooLayer } from "@/components/motion/goo-layer" import { tokenMs } from "@/lib/motion/token-ms" import { activeTrigger, motionLevel, usePortalMotion } from "@/lib/overlay" const BridgeContext = React.createContext(false) function Popover({ onOpenChange, ...props }: PopoverPrimitive.Root.Props) { const [bridge, setBridge] = React.useState(false) const timer = React.useRef(0) return ( <BridgeContext.Provider value={bridge}> <PopoverPrimitive.Root {...props} onOpenChange={(open, details) => { onOpenChange?.(open, details) window.clearTimeout(timer.current) const level = motionLevel() if (level === "calm" || level === "still") { setBridge(false) return } setBridge(true) timer.current = window.setTimeout( () => setBridge(false), tokenMs(open ? "--duration-fast" : "--duration-quick") ) }} /> </BridgeContext.Provider> ) } function PopoverTrigger(props: PopoverPrimitive.Trigger.Props) { return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} /> } function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) { return <PopoverPrimitive.Title className={cn("text-sm font-medium", className)} {...props} /> } function PopoverDescription({ className, ...props }: PopoverPrimitive.Description.Props) { return ( <PopoverPrimitive.Description className={cn("text-sm text-muted-foreground", className)} {...props} /> ) } function PopoverContent({ className, children, ...props }: PopoverPrimitive.Popup.Props) { const ref = React.useRef<HTMLDivElement>(null) const bridge = React.useContext(BridgeContext) usePortalMotion(ref) return ( <PopoverPrimitive.Portal> <PopoverPrimitive.Positioner className="z-overlay" sideOffset={8}> <PopoverPrimitive.Popup ref={ref} data-slot="popover-content" className={cn( "overlay-surface overlay-grow w-(--popover-width) rounded-(--popover-corner) p-(--popover-padding) text-foreground", className )} {...props} > {bridge ? <PopoverBridge popupRef={ref} /> : null} {children} </PopoverPrimitive.Popup> </PopoverPrimitive.Positioner> </PopoverPrimitive.Portal> ) } function PopoverBridge({ popupRef }: { popupRef: React.RefObject<HTMLElement | null> }) { const [geom, setGeom] = React.useState({ left: 0, top: 0, width: 48, height: 48, neckX: 16, neckY: 16, edgeX: 32, edgeY: 32, ready: false, }) React.useLayoutEffect(() => { let frame = 0 let tries = 0 const measure = () => { const popup = popupRef.current const trigger = activeTrigger("popover-trigger") if (!popup || !trigger || popup.getBoundingClientRect().width === 0) { if (tries++ < 20) frame = requestAnimationFrame(measure) return } const panel = popup.getBoundingClientRect() const button = trigger.getBoundingClientRect() const buttonX = button.left + button.width / 2 const buttonY = button.top + button.height / 2 const panelX = panel.left + panel.width / 2 const panelY = panel.top + panel.height / 2 const horizontal = Math.abs(panelX - buttonX) > Math.abs(panelY - buttonY) const neckX = (horizontal ? buttonX + Math.sign(panelX - buttonX) * (button.width / 2) : buttonX) - panel.left const neckY = (horizontal ? buttonY : buttonY + Math.sign(panelY - buttonY) * (button.height / 2)) - panel.top const edgeX = (horizontal ? panelX - Math.sign(panelX - buttonX) * (panel.width / 2) : panelX) - panel.left const edgeY = (horizontal ? panelY : panelY - Math.sign(panelY - buttonY) * (panel.height / 2)) - panel.top const pad = 28 const left = Math.min(neckX, edgeX) - pad const top = Math.min(neckY, edgeY) - pad setGeom({ left, top, width: Math.max(neckX, edgeX) + pad - left, height: Math.max(neckY, edgeY) + pad - top, neckX: neckX - left, neckY: neckY - top, edgeX: edgeX - left, edgeY: edgeY - top, ready: true, }) } measure() return () => cancelAnimationFrame(frame) }, [popupRef]) return ( <span className="popover-bridge pointer-events-none absolute" style={{ left: geom.left, top: geom.top, width: geom.width, height: geom.height }} > <GooLayer width="100%" height="100%" viewBox={`0 0 ${geom.width} ${geom.height}`} className="overflow-visible"> <circle cx={geom.neckX} cy={geom.neckY} r="11" fill="var(--color-surface-raised)" /> <circle cx={geom.edgeX} cy={geom.edgeY} r="16" fill="var(--color-surface-raised)" /> </GooLayer> </span> ) } export { Popover, PopoverTrigger, PopoverContent, PopoverTitle, PopoverDescription }components/ui/date-picker.tsxdate-picker
components/ui/date-picker.tsx"use client" import * as React from "react" import { CalendarIcon } from "lucide-react" import { cn } from "cn" import { Calendar, type CalendarRange } from "@/components/ui/calendar" import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" /* Date picker: a date field with a calendar in a Popover. Typing a date also works (blur or Enter to apply). The value rolls into the field after a pick. mode="range" picks two dates. */ function parse(text: string): Date | undefined { const iso = text.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/) const date = iso ? new Date(+iso[1], +iso[2] - 1, +iso[3]) : new Date(text) return Number.isNaN(date.getTime()) ? undefined : new Date(date.getFullYear(), date.getMonth(), date.getDate()) } type DatePickerProps = { label?: string placeholder?: string locale?: string className?: string id?: string } & ( | { mode?: "single"; value?: Date; onChange?: (date?: Date) => void } | { mode: "range"; value?: CalendarRange; onChange?: (range: CalendarRange) => void } ) function DatePicker(props: DatePickerProps) { const { label = "Date", placeholder = "Pick a date", locale, className, id } = props const [open, setOpen] = React.useState(false) const fmt = React.useMemo(() => new Intl.DateTimeFormat(locale, { dateStyle: "medium" }), [locale]) const shown = props.mode === "range" ? props.value?.from ? `${fmt.format(props.value.from)} – ${props.value.to ? fmt.format(props.value.to) : "…"}` : "" : props.value ? fmt.format(props.value) : "" const [text, setText] = React.useState(shown) const [lastShown, setLastShown] = React.useState(shown) if (shown !== lastShown) { setLastShown(shown) setText(shown) } function commit() { if (props.mode === "range") return setText(shown) const date = parse(text) if (date) props.onChange?.(date) else if (!text) props.onChange?.(undefined) else setText(shown) } return ( <div data-slot="date-picker" className={cn("relative flex w-full max-w-(--date-picker-width) items-center", className)}> <input id={id} aria-label={label} value={text} placeholder={placeholder} readOnly={props.mode === "range"} onChange={(event) => setText(event.target.value)} onBlur={commit} onKeyDown={(event) => { if (event.key === "Enter") commit() }} key={lastShown} className="date-picker-value h-(--field-height-md) w-full rounded-(--field-corner) border-solid border-(length:--field-stroke-width) border-(--field-stroke-color) bg-(--field-container) ps-(--field-padding-x) pe-(--space-10) text-sm text-(--field-label) shadow-(--field-elevation) outline-none placeholder:text-(--field-placeholder) focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)" /> <Popover open={open} onOpenChange={setOpen}> <PopoverTrigger aria-label="Open calendar" className="liquid-press absolute end-1 inline-flex size-(--size-control-sm) items-center justify-center rounded-(--shape-full) text-(--field-action-label) outline-none hover:bg-(--field-action-container-hover) hover:text-(--field-action-label-hover) active:bg-(--field-action-container-pressed) focus-visible:shadow-(--focus-ring)" > <CalendarIcon className="size-(--size-icon-md)" /> </PopoverTrigger> <PopoverContent className="w-auto"> {props.mode === "range" ? ( <Calendar mode="range" value={props.value} onChange={(range) => { props.onChange?.(range) if (range.from && range.to) setOpen(false) }} locale={locale} /> ) : ( <Calendar value={props.value} onChange={(date) => { props.onChange?.(date) setOpen(false) }} locale={locale} /> )} </PopoverContent> </Popover> </div> ) } export { DatePicker }
Imports
What the examples on this page import:
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
- 1Field · Text field tokens; --date-picker-width.
- 2Calendar button · Opens the popover.
- 3Calendar · In a Popover that grows from the button.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
mode | "single" | "range" | "single" | Range shows from – to. |
value / onChange | Date | range | — | Controlled value. |
label, placeholder, locale | string | — | Text and formatting. |
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.
| Token | Points to | Light | Dark |
|---|---|---|---|
--calendar-day-size | var(--size-control-md) | 40px | same |
--calendar-day-corner | var(--shape-full) | 999px | same |
--calendar-day-container-hover | var(--color-bg-hover) | oklch(0.965 0.005 95) | oklch(0.22 0 0) |
--calendar-day-label-disabled | var(--color-fg-disabled) | oklch(0.62 0.01 95) | oklch(0.53 0 0) |
--calendar-width | calc(var(--calendar-day-size) * 7) | calc(var(--calendar-day-size) * 7) | same |
--calendar-selected | var(--color-brand) | oklch(0.18 0.008 260) | oklch(0.98 0 0) |
--calendar-selected-label | var(--color-fg-on-accent) | oklch(0.97 0.004 95) | oklch(0.14 0 0) |
--calendar-band | var(--color-bg-selected) | color-mix(in oklch, var(--ref-select) 12%, transparent) | color-mix(in oklch, var(--ref-select) 16%, transparent) |
--date-picker-width | var(--layout-popover-max) | 320px | same |
Motion
| Trigger | What happens | Tokens |
|---|---|---|
| Pick | The popover closes and the new value fades into the field. | --duration-fast |
Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.
Accessibility
- Escape closes and focus returns to the trigger.
- The field accepts typed dates; Enter applies.
Usage
Do
- Show the format in the placeholder if typing is expected.
Don’t
- Don't force the calendar for far-away dates.
Code
"use client"
import * as React from "react"
import { CalendarIcon } from "lucide-react"
import { cn } from "cn"
import { Calendar, type CalendarRange } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
/*
Date picker: a date field with a calendar in a Popover. Typing a date also
works (blur or Enter to apply). The value rolls into the field after a pick.
mode="range" picks two dates.
*/
function parse(text: string): Date | undefined {
const iso = text.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/)
const date = iso ? new Date(+iso[1], +iso[2] - 1, +iso[3]) : new Date(text)
return Number.isNaN(date.getTime()) ? undefined : new Date(date.getFullYear(), date.getMonth(), date.getDate())
}
type DatePickerProps = {
label?: string
placeholder?: string
locale?: string
className?: string
id?: string
} & (
| { mode?: "single"; value?: Date; onChange?: (date?: Date) => void }
| { mode: "range"; value?: CalendarRange; onChange?: (range: CalendarRange) => void }
)
function DatePicker(props: DatePickerProps) {
const { label = "Date", placeholder = "Pick a date", locale, className, id } = props
const [open, setOpen] = React.useState(false)
const fmt = React.useMemo(() => new Intl.DateTimeFormat(locale, { dateStyle: "medium" }), [locale])
const shown =
props.mode === "range"
? props.value?.from
? `${fmt.format(props.value.from)} – ${props.value.to ? fmt.format(props.value.to) : "…"}`
: ""
: props.value
? fmt.format(props.value)
: ""
const [text, setText] = React.useState(shown)
const [lastShown, setLastShown] = React.useState(shown)
if (shown !== lastShown) {
setLastShown(shown)
setText(shown)
}
function commit() {
if (props.mode === "range") return setText(shown)
const date = parse(text)
if (date) props.onChange?.(date)
else if (!text) props.onChange?.(undefined)
else setText(shown)
}
return (
<div data-slot="date-picker" className={cn("relative flex w-full max-w-(--date-picker-width) items-center", className)}>
<input
id={id}
aria-label={label}
value={text}
placeholder={placeholder}
readOnly={props.mode === "range"}
onChange={(event) => setText(event.target.value)}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === "Enter") commit()
}}
key={lastShown}
className="date-picker-value h-(--field-height-md) w-full rounded-(--field-corner) border-solid border-(length:--field-stroke-width) border-(--field-stroke-color) bg-(--field-container) ps-(--field-padding-x) pe-(--space-10) text-sm text-(--field-label) shadow-(--field-elevation) outline-none placeholder:text-(--field-placeholder) focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)"
/>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
aria-label="Open calendar"
className="liquid-press absolute end-1 inline-flex size-(--size-control-sm) items-center justify-center rounded-(--shape-full) text-(--field-action-label) outline-none hover:bg-(--field-action-container-hover) hover:text-(--field-action-label-hover) active:bg-(--field-action-container-pressed) focus-visible:shadow-(--focus-ring)"
>
<CalendarIcon className="size-(--size-icon-md)" />
</PopoverTrigger>
<PopoverContent className="w-auto">
{props.mode === "range" ? (
<Calendar
mode="range"
value={props.value}
onChange={(range) => {
props.onChange?.(range)
if (range.from && range.to) setOpen(false)
}}
locale={locale}
/>
) : (
<Calendar
value={props.value}
onChange={(date) => {
props.onChange?.(date)
setOpen(false)
}}
locale={locale}
/>
)}
</PopoverContent>
</Popover>
</div>
)
}
export { DatePicker }