When to use
- Picking one day for a form: a due date, a start date, a review. The field also takes typed dates, so keyboard users never need the grid.
- Picking a span: time off, a stay, a reporting period. Range mode previews the span as you hover and never spans a disabled day.
- An always-visible calendar on a page or in a panel: use
Calendardirectly.
When not to use
- Dates far in the past, such as a birthday: paging month by month is slow; use three Selects or a plain Input.
- A date and a time together: pair this with a time Select, or build a scheduler on calendar-core's
timeGrid. - Relative choices ("in 3 days", "next Monday"): a Select or Segmented control is faster.
Installation
pnpm dlx shadcn add https://eased.dev/r/date-picker.jsonnpx shadcn add https://eased.dev/r/date-picker.jsonyarn dlx shadcn add https://eased.dev/r/date-picker.jsonbunx --bun shadcn add https://eased.dev/r/date-picker.jsonThe command adds Date Picker, everything it builds on and Eased’s tokens to your project.
Install the dependencies
pnpm add @base-ui/react motionnpm install @base-ui/react motionyarn add @base-ui/react motionbun add @base-ui/react motionAdd the Eased pieces it builds on
Copy each item’s files the same way, or install them with the CLI:
Copy the source into your project
components/eased/date-picker/date-picker.tsxTSX "use client";import { Input as BaseInput } from "@base-ui/react/input";import { Popover } from "@base-ui/react/popover";import { useMemo, useRef, useState, type ComponentProps } from "react";import { addDays, startOfDay, type WeekStart } from "../_primitives/calendar-core/calendar-core";import { InputGroup, InputGroupAddon, controlClass, controlPadClass, type ControlSize } from "../_primitives/field/field";import { FloatingLayer, floatingSurface } from "../_primitives/floating/floating";import { pressIcon } from "../lib/press";import { Calendar, useToday, type DateRange } from "./calendar";export { Calendar, useToday, type CalendarProps, type CalendarRangeProps, type CalendarSingleProps, type DateRange } from "./calendar";type InputProps = Omit<ComponentProps<typeof BaseInput>, "size" | "className" | "value" | "defaultValue" | "onValueChange" | "type" | "min" | "max">;type DatePickerBaseProps = { /** Locale for parsing, formatting and the calendar. Default: the runtime's. */ locale?: string; /** How the value is written in the field. Default `{ day: "numeric", month: "short", year: "numeric" }`. */ formatOptions?: Intl.DateTimeFormatOptions; /** 0 Sunday … 6 Saturday. Default: the locale's. */ weekStartsOn?: WeekStart; min?: Date; max?: Date; /** Days that can't be picked or typed. */ isDateDisabled?: (date: Date) => boolean; /** "Today", for the today mark and for typed words like "tomorrow". Default: now. */ today?: Date; /** sm 32px, md 36px (default), lg 40px. */ size?: ControlSize; placeholder?: string; disabled?: boolean; /** Controlled popover state. */ open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; /** Close the calendar once a day (or a range's second end) is picked. Default true. */ closeOnSelect?: boolean; /** Popover alignment against the field. Default "start". */ align?: "start" | "center" | "end"; /** Classes for the bordered box. */ className?: string; /** Stacking order of the popover. Default 50; raise it inside a dialog. */ zIndex?: number;};export type DatePickerSingleProps = DatePickerBaseProps & Omit<InputProps, keyof DatePickerBaseProps> & { mode?: "single"; value?: Date | null; defaultValue?: Date | null; onValueChange?: (date: Date | null) => void; /** Accessible name for the calendar button. Default "Choose date". */ calendarLabel?: string; /** Called with the text when a typed date can't be read or isn't allowed. */ onInvalidInput?: (text: string) => void; };export type DatePickerRangeProps = DatePickerBaseProps & { mode: "range"; value?: DateRange | null; defaultValue?: DateRange | null; onValueChange?: (range: DateRange | null) => void; minLength?: number; maxLength?: number; id?: string; name?: string; "aria-label"?: string; "aria-labelledby"?: string;};export type DatePickerProps = DatePickerSingleProps | DatePickerRangeProps;const DEFAULT_FORMAT: Intl.DateTimeFormatOptions = { day: "numeric", month: "short", year: "numeric" };/** * A date field with a calendar in a popover (Base UI Popover; the grid is calendar-core). * Single mode is a text input that reads typed dates in the field's locale ("24 Oct", "10/24", * "2026-10-24", "tomorrow") with a calendar button beside it; range mode is a button showing * the span. The popover grows from the field; the calendar inside pages with a directional * slide and its selection springs between days. */export function DatePicker(props: DatePickerProps) { return props.mode === "range" ? <RangePicker {...props} /> : <SinglePicker {...props} />;}function usePopoverState(open: boolean | undefined, defaultOpen: boolean | undefined, onOpenChange?: (open: boolean) => void) { const [own, setOwn] = useState(defaultOpen ?? false); const isOpen = open ?? own; const setOpen = (next: boolean) => { if (open === undefined) setOwn(next); onOpenChange?.(next); }; return [isOpen, setOpen] as const;}function SinglePicker({ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- kept off the input mode: _mode, value: valueProp, defaultValue = null, onValueChange, locale, formatOptions = DEFAULT_FORMAT, weekStartsOn, min, max, isDateDisabled, today: todayProp, size = "md", placeholder, disabled, open, defaultOpen, onOpenChange, closeOnSelect = true, align = "start", className = "", zIndex, calendarLabel = "Choose date", onInvalidInput, onBlur, onKeyDown, ...inputProps}: DatePickerSingleProps) { const [own, setOwn] = useState<Date | null>(defaultValue); const value = valueProp !== undefined ? valueProp : own; const [isOpen, setOpen] = usePopoverState(open, defaultOpen, onOpenChange); const now = useToday(); const today = todayProp ?? now ?? undefined; const anchor = useRef<HTMLDivElement>(null); const inputRef = useRef<HTMLInputElement>(null); const fmt = useMemo(() => new Intl.DateTimeFormat(locale, formatOptions), [locale, formatOptions]); const shown = value ? plainSpaces(fmt.format(value)) : ""; // What the person is typing; null while the field shows the formatted value. const [draft, setDraft] = useState<string | null>(null); const allowed = (d: Date) => !((min && d < startOfDay(min)) || (max && d > startOfDay(max)) || isDateDisabled?.(d)); const commit = (next: Date | null) => { if (valueProp === undefined) setOwn(next); if ((next?.getTime() ?? null) !== (value?.getTime() ?? null)) onValueChange?.(next); }; /** Reads the draft; a date that can't be read or picked reverts to the last good value. */ const commitDraft = () => { if (draft === null) return; const text = draft.trim(); setDraft(null); if (!text) return commit(null); const parsed = parseDate(text, { locale, today }); if (parsed && allowed(parsed)) commit(parsed); else onInvalidInput?.(text); }; return ( <Popover.Root open={isOpen} onOpenChange={(next) => { if (next) commitDraft(); setOpen(next); }} > <div ref={anchor} className="flex w-full min-w-0"> <InputGroup size={size} className={className}> <BaseInput {...inputProps} ref={inputRef} value={draft ?? shown} onValueChange={(v) => setDraft(v)} placeholder={placeholder ?? (today ? plainSpaces(fmt.format(today)) : undefined)} disabled={disabled} autoComplete="off" spellCheck={false} onBlur={(e) => { commitDraft(); onBlur?.(e); }} onKeyDown={(e) => { onKeyDown?.(e); if (e.defaultPrevented) return; if (e.key === "Enter") commitDraft(); else if (e.key === "Escape" && draft !== null) { e.preventDefault(); setDraft(null); } else if (e.key === "ArrowDown" && (e.altKey || !draft)) { e.preventDefault(); commitDraft(); setOpen(true); } }} className={controlClass} /> <Popover.Trigger aria-label={calendarLabel} disabled={disabled} className={`-me-1.5 inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-control-xs text-text-muted hover-fine:not-disabled:bg-surface-hover hover-fine:not-disabled:text-text active:not-disabled:bg-surface-active data-popup-open:bg-surface-active data-popup-open:text-text disabled:cursor-not-allowed disabled:text-text-disabled ${pressIcon} active:scale-100`} > <CalendarIcon /> </Popover.Trigger> </InputGroup> </div> <CalendarPopover anchor={anchor} align={align} zIndex={zIndex}> <Calendar value={value} onValueChange={commit} onSelectComplete={() => { if (!closeOnSelect) return; setOpen(false); }} locale={locale} weekStartsOn={weekStartsOn} min={min} max={max} isDateDisabled={isDateDisabled} today={today} /> </CalendarPopover> </Popover.Root> );}function RangePicker({ value: valueProp, defaultValue = null, onValueChange, locale, formatOptions = DEFAULT_FORMAT, weekStartsOn, min, max, isDateDisabled, minLength, maxLength, today, size = "md", placeholder = "Pick dates", disabled, open, defaultOpen, onOpenChange, closeOnSelect = true, align = "start", className = "", zIndex, id, name, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy,}: DatePickerRangeProps) { const [own, setOwn] = useState<DateRange | null>(defaultValue); const value = valueProp !== undefined ? valueProp : own; const [isOpen, setOpen] = usePopoverState(open, defaultOpen, onOpenChange); const anchor = useRef<HTMLDivElement>(null); // Escape while a range is half-picked drops the half-pick and keeps the calendar open. const fmt = useMemo(() => new Intl.DateTimeFormat(locale, formatOptions), [locale, formatOptions]); const label = value ? plainSpaces(fmt.formatRange(value.start, value.end)) : ""; const commit = (r: DateRange | null) => { if (valueProp === undefined) setOwn(r); onValueChange?.(r); }; return ( <Popover.Root open={isOpen} onOpenChange={(next, details) => { if (!next && details.reason === "escape-key" && details.event.defaultPrevented) return details.cancel(); setOpen(next); }} > <div ref={anchor} className="flex w-full min-w-0"> <InputGroup size={size} className={`px-0! ${className}`}> <Popover.Trigger id={id} disabled={disabled} aria-label={ariaLabel} aria-labelledby={ariaLabelledBy} className={`flex min-w-0 flex-1 cursor-pointer items-center gap-2 self-stretch rounded-[inherit] text-left outline-none disabled:cursor-not-allowed ${controlPadClass[size]}`} > <span className={`min-w-0 flex-1 truncate tabular-nums ${label ? "text-text" : "text-text-muted"} in-disabled:text-text-disabled`}> {label || placeholder} </span> <InputGroupAddon> <CalendarIcon /> </InputGroupAddon> </Popover.Trigger> {name && <input type="hidden" name={name} value={value ? `${toIso(value.start)}/${toIso(value.end)}` : ""} />} </InputGroup> </div> <CalendarPopover anchor={anchor} align={align} zIndex={zIndex}> <Calendar mode="range" value={value} onValueChange={commit} onSelectComplete={() => { if (closeOnSelect) setOpen(false); }} locale={locale} weekStartsOn={weekStartsOn} min={min} max={max} isDateDisabled={isDateDisabled} minLength={minLength} maxLength={maxLength} today={today} /> </CalendarPopover> </Popover.Root> );}function CalendarPopover({ anchor, align, zIndex, children,}: { anchor: React.RefObject<HTMLDivElement | null>; align: "start" | "center" | "end"; zIndex?: number; children: React.ReactNode;}) { const body = useRef<HTMLDivElement>(null); return ( <FloatingLayer parts={Popover} role="popover" side="bottom" align={align} zIndex={zIndex} positionerProps={{ anchor }} // Open on the active day (the selection, else today), the grid's roving tab stop. popupProps={{ initialFocus: () => body.current?.querySelector<HTMLElement>('[role="gridcell"][tabindex="0"]') ?? true }} className={`${floatingSurface} rounded-panel p-3 [--pad:12px] [--radius-outer:var(--eased-radius-panel)]`} > <div ref={body}>{children}</div> </FloatingLayer> );}/** Intl's thin and narrow no-break spaces differ between Node's ICU and the browser's; plain ones hydrate. */const plainSpaces = (s: string) => s.replace(/[\u2009\u202f]/g, " ");const toIso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;/* ---------- Typed dates ----------------------------------------------------- */const WORDS: Record<string, number> = { today: 0, tod: 0, tomorrow: 1, tmr: 1, tom: 1, yesterday: -1 };/** * Reads a typed date in the locale's order: "2026-10-24", "24/10" or "10/24" (the locale * decides), "24 Oct", "Oct 24 2026", "October 24", and today / tomorrow / yesterday. A missing * year is the year of `today`; two-digit years are 20xx. Null when it can't be read or the day * doesn't exist (31 Feb). */export function parseDate(text: string, { locale, today = new Date() }: { locale?: string; today?: Date } = {}): Date | null { const t = text.trim().toLowerCase(); if (!t) return null; if (t in WORDS) return addDays(startOfDay(today), WORDS[t]); const make = (y: number, m: number, d: number) => { if (y < 100) y += 2000; const date = new Date(y, m, d); return date.getFullYear() === y && date.getMonth() === m && date.getDate() === d ? date : null; }; const iso = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(t); if (iso) return make(+iso[1], +iso[2] - 1, +iso[3]); const year = today.getFullYear(); const tokens = t.split(/[\s,./-]+/).filter(Boolean); // A month written as a word. const names = monthNames(locale); const wordIndex = tokens.findIndex((tok) => /\p{L}/u.test(tok)); if (wordIndex >= 0) { const word = tokens[wordIndex].replace(/\.$/, ""); const m = names.findIndex((n) => n.some((name) => word.length >= 3 && name.startsWith(word))); if (m < 0) return null; const nums = tokens.filter((_, i) => i !== wordIndex).map(Number); if (nums.some(Number.isNaN) || nums.length === 0 || nums.length > 2) return null; const [a, b] = nums; // "Oct 24 2026", "24 Oct 2026", "2026 Oct 24". if (nums.length === 1) return make(year, m, a); return a > 31 ? make(a, m, b) : make(b, m, a); } // All numbers, in the locale's day/month/year order. const nums = tokens.map(Number); if (nums.some(Number.isNaN) || nums.length < 2 || nums.length > 3) return null; const order = numericOrder(locale); const parts: Record<"day" | "month" | "year", number> = { day: NaN, month: NaN, year }; const fields = nums.length === 3 ? order : order.filter((f) => f !== "year"); fields.forEach((f, i) => (parts[f] = nums[i])); return make(parts.year, parts.month - 1, parts.day);}const monthCache = new Map<string, string[][]>();function monthNames(locale?: string): string[][] { const key = locale ?? ""; const hit = monthCache.get(key); if (hit) return hit; const long = new Intl.DateTimeFormat(locale, { month: "long" }); const short = new Intl.DateTimeFormat(locale, { month: "short" }); const en = new Intl.DateTimeFormat("en", { month: "long" }); const names = Array.from({ length: 12 }, (_, m) => { const d = new Date(2000, m, 1); return [long.format(d), short.format(d), en.format(d)].map((s) => s.toLowerCase().replace(/\.$/, "")); }); monthCache.set(key, names); return names;}function numericOrder(locale?: string): ("day" | "month" | "year")[] { const parts = new Intl.DateTimeFormat(locale, { day: "numeric", month: "numeric", year: "numeric" }).formatToParts(new Date(2000, 10, 22)); const order = parts.map((p) => p.type).filter((t): t is "day" | "month" | "year" => t === "day" || t === "month" || t === "year"); return order.length === 3 ? order : ["month", "day", "year"];}function CalendarIcon() { return ( <svg viewBox="0 0 16 16" fill="none" aria-hidden className="size-4"> <rect x="2.25" y="3.25" width="11.5" height="10.5" rx="2.25" stroke="currentColor" strokeWidth="1.5" /> <path d="M2.5 6.75h11M5.5 1.75v2.5M10.5 1.75v2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /> </svg> );}components/eased/date-picker/calendar.tsxTSX "use client";import { AnimatePresence, motion } from "motion/react";import { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent } from "react";import { addMonths, isSameDay, localeWeekStart, monthGrid, nextFocusDate, startOfDay, startOfMonth, toDayKey, useRangeSelection, type CalendarDay, type DateRange, type WeekStart,} from "../_primitives/calendar-core/calendar-core";import { TextSwap } from "../_primitives/text-swap/text-swap";import { enter, exitFast, reducedFade, smooth, snappy, useSafeReducedMotion } from "../lib/motion";import { pressIcon } from "../lib/press";export type { DateRange };export type CalendarBaseProps = { /** Locale for the month title, weekday names and day labels. Default: the runtime's. */ locale?: string; /** 0 Sunday … 6 Saturday. Default: the locale's first day of the week. */ weekStartsOn?: WeekStart; /** Earliest selectable day. */ min?: Date; /** Latest selectable day. */ max?: Date; /** Days that can't be picked: weekends, booked nights, holidays. A range never spans one. */ isDateDisabled?: (date: Date) => boolean; /** "Today", for the today mark. Pass a fixed date for deterministic demos. Default: now. */ today?: Date; /** The month shown first. Default: the selected day's month, else today's. */ defaultMonth?: Date; /** Fires when the shown month changes (the first of that month). */ onMonthChange?: (month: Date) => void; /** Focus the active day on mount (a popover opening). Default false. */ autoFocus?: boolean; /** Called after a pick that finishes a selection: one day, or a range's second end. */ onSelectComplete?: () => void; className?: string;};export type CalendarSingleProps = CalendarBaseProps & { mode?: "single"; value?: Date | null; defaultValue?: Date | null; onValueChange?: (date: Date | null) => void;};export type CalendarRangeProps = CalendarBaseProps & { mode: "range"; value?: DateRange | null; defaultValue?: DateRange | null; onValueChange?: (range: DateRange | null) => void; /** Fewest days in a range. Default 1. */ minLength?: number; /** Most days in a range. */ maxLength?: number;};export type CalendarProps = CalendarSingleProps | CalendarRangeProps;const SERVER_DAY = new Date(2000, 0, 1);let todayCache: Date | null = null;const readToday = () => { const d = startOfDay(Date.now()); if (!todayCache || +todayCache !== +d) todayCache = d; return todayCache;};const noSubscribe = () => () => {};/** Local midnight today, read on the client only (null on the server and during hydration). */export function useToday(): Date | null { return useSyncExternalStore(noSubscribe, readToday, () => null);}const CELL = "h-9"; // 36px rows: 7 × 36 = 252px wide, so the popover fits a 320px screen.const monthKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}`;/** * A month grid on calendar-core: one day or a range, arrow keys, Home/End and PageUp/PageDown * (Shift for years). Paging slides the days the way you moved while the title swaps; the * selected day's fill glides between days on the snappy spring, and a range's ends pop in. */export function Calendar(props: CalendarProps) { const { locale, weekStartsOn: weekStartsOnProp, min, max, isDateDisabled, today: todayProp, defaultMonth, onMonthChange, autoFocus = false, onSelectComplete, className = "", } = props; const range = props.mode === "range"; const reduced = useSafeReducedMotion(); const uid = useId(); const now = useToday(); // Before hydration there is no clock to read; a fixed day keeps the server render stable. const today = todayProp ?? now ?? SERVER_DAY; const weekStartsOn = weekStartsOnProp ?? localeWeekStart(locale); const isDisabled = (d: Date) => (min !== undefined && d < startOfDay(min)) || (max !== undefined && d > startOfDay(max)) || !!isDateDisabled?.(d); // Single selection. const [singleOwn, setSingleOwn] = useState<Date | null>(!range ? (props.defaultValue ?? null) : null); const single = !range ? (props.value !== undefined ? props.value : singleOwn) : null; const pickSingle = (d: Date) => { if (range) return; if (props.value === undefined) setSingleOwn(d); props.onValueChange?.(d); onSelectComplete?.(); }; // Range selection: calendar-core owns click-click, drag, preview and the constraints. const sel = useRangeSelection({ value: range ? props.value : undefined, defaultValue: range ? props.defaultValue : null, onChange: (r) => { if (!range) return; props.onValueChange?.(r); if (r) onSelectComplete?.(); }, isDisabled, minLength: range ? props.minLength : undefined, maxLength: range ? props.maxLength : undefined, }); const anchorDate = range ? (sel.value?.start ?? null) : single; const [month, setMonthState] = useState(() => startOfMonth(defaultMonth ?? anchorDate ?? today)); const [dir, setDir] = useState<1 | -1>(1); const [focusKey, setFocusKey] = useState(() => toDayKey(anchorDate ?? today)); const pendingFocus = useRef(autoFocus); const gridRef = useRef<HTMLDivElement>(null); const grid = useMemo(() => monthGrid(month, { weekStartsOn, today, locale }), [month, weekStartsOn, today, locale]); const dayLabel = useMemo(() => new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long", year: "numeric" }), [locale]); const goTo = (next: Date) => { const m = startOfMonth(next); if (+m === +month) return; setDir(+m > +month ? 1 : -1); setMonthState(m); onMonthChange?.(m); }; const prevDisabled = min !== undefined && +addMonths(month, -1) < +startOfMonth(min); const nextDisabled = max !== undefined && +addMonths(month, 1) > +startOfMonth(max); // The roving tab stop stays on a day of the shown month. const focusInMonth = grid.days.some((d) => d.inMonth && d.key === focusKey); const tabKey = focusInMonth ? focusKey : (grid.days.find((d) => d.inMonth && !isDisabled(d.date))?.key ?? grid.days.find((d) => d.inMonth)!.key); useEffect(() => { if (!pendingFocus.current) return; pendingFocus.current = false; gridRef.current?.querySelector<HTMLElement>(`[data-month="${monthKey(month)}"] [data-date="${tabKey}"][data-in-month]`)?.focus({ preventScroll: true }); }, [month, tabKey]); const moveFocus = (date: Date) => { pendingFocus.current = true; setFocusKey(toDayKey(date)); goTo(date); if (range) sel.hover(date); }; const onCellKey = (e: KeyboardEvent<HTMLElement>, day: CalendarDay, rangeKey?: (e: KeyboardEvent<HTMLElement>) => void) => { const next = nextFocusDate(day.date, e.key, { weekStartsOn, shift: e.shiftKey }); if (next) { e.preventDefault(); if (min && next < startOfDay(min)) return moveFocus(startOfDay(min)); if (max && next > startOfDay(max)) return moveFocus(startOfDay(max)); return moveFocus(next); } if (rangeKey) return rangeKey(e); if ((e.key === "Enter" || e.key === " ") && !isDisabled(day.date)) { e.preventDefault(); pickSingle(day.date); } }; const slide = reduced ? 0 : 28; return ( <div className={`flex w-63 flex-col gap-2 select-none ${className}`}> <div className="flex h-8 items-center justify-between"> <TextSwap direction={dir} className="text-ui font-medium text-text" aria-live="polite"> {grid.title} </TextSwap> <div className="-me-2 flex items-center"> <NavButton label="Previous month" disabled={prevDisabled} onClick={() => goTo(addMonths(month, -1))} dir="left" /> <NavButton label="Next month" disabled={nextDisabled} onClick={() => goTo(addMonths(month, 1))} dir="right" /> </div> </div> <div ref={gridRef} role="grid" aria-label={grid.title} aria-multiselectable={range || undefined} className="flex flex-col" onPointerLeave={range ? () => sel.hover(null) : undefined} > <div role="row" className="grid grid-cols-7 pb-1"> {grid.weekdays.map((w) => ( <span key={w.weekday} role="columnheader" aria-label={w.long} className="flex h-6 items-center justify-center text-ui-xs text-text-muted"> {w.short} </span> ))} </div> <div className="relative overflow-hidden" style={{ height: `calc(6 * var(--spacing) * 9 + 5 * var(--spacing) * 0.5)` }}> <AnimatePresence initial={false} mode="popLayout" custom={dir}> <motion.div key={monthKey(month)} role="rowgroup" data-month={monthKey(month)} custom={dir} variants={{ enter: (d: number) => ({ x: d * slide, opacity: 0 }), center: { x: 0, opacity: 1 }, exit: (d: number) => ({ x: d * -slide * 0.5, opacity: 0, transition: reduced ? reducedFade : { x: smooth, opacity: exitFast } }), }} initial="enter" animate="center" exit="exit" transition={reduced ? reducedFade : { x: smooth, opacity: enter }} className={`flex w-full flex-col gap-0.5 ${range ? "touch-none" : ""}`} > {grid.weeks.map((week) => ( <div key={week[0].key} role="row" className="grid grid-cols-7"> {week.map((day, col) => { const disabled = isDisabled(day.date); const label = dayLabel.format(day.date); const common = { role: "gridcell", "aria-label": label, "aria-current": day.isToday ? ("date" as const) : undefined, "data-date": day.key, "data-in-month": day.inMonth ? "" : undefined, tabIndex: day.inMonth && day.key === tabKey ? 0 : -1, }; if (range) { const cell = sel.cellProps(day.date); const s = sel.stateOf(day.date); return ( <div key={day.key} {...common} {...cell} onFocus={() => { setFocusKey(day.key); cell.onFocus(); }} onKeyDown={(e) => onCellKey(e, day, cell.onKeyDown)} className={`group/day relative flex ${CELL} items-center justify-center outline-none ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`} > <RangeBand position={s.position} col={col} preview={s.previewing && !s.selected} /> <DayFace day={day} disabled={disabled} filled={s.position !== null && s.position !== "middle"} preview={s.previewing} reduced={reduced} pop /> </div> ); } const selected = !!single && isSameDay(single, day.date); return ( <div key={day.key} {...common} aria-selected={selected} aria-disabled={disabled || undefined} onClick={() => !disabled && pickSingle(day.date)} onFocus={() => setFocusKey(day.key)} onKeyDown={(e) => onCellKey(e, day)} className={`group/day relative flex ${CELL} items-center justify-center outline-none ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`} > {selected && day.inMonth && ( <motion.span layoutId={`${uid}-selected-${monthKey(month)}`} transition={reduced ? { duration: 0 } : snappy} className="absolute inset-y-0 left-1/2 w-9 -translate-x-1/2 rounded-control-sm bg-brand" /> )} <DayFace day={day} disabled={disabled} filled={selected && day.inMonth} reduced={reduced} /> </div> ); })} </div> ))} </motion.div> </AnimatePresence> </div> </div> </div> );}/** The light band behind a range: square in the middle, open towards the inside at each end, rounded at row edges. */function RangeBand({ position, col, preview }: { position: "single" | "start" | "middle" | "end" | null; col: number; preview: boolean }) { if (position === null || position === "single") return null; const left = position === "start" ? "left-1/2" : "left-0"; const right = position === "end" ? "right-1/2" : "right-0"; const roundL = col === 0 && position !== "start" ? "rounded-l-control-sm" : ""; const roundR = col === 6 && position !== "end" ? "rounded-r-control-sm" : ""; return ( <span aria-hidden className={`absolute inset-y-0 ${left} ${right} ${roundL} ${roundR} bg-brand-subtle transition-opacity duration-(--eased-duration-fast) ease-standard ${preview ? "opacity-60" : "opacity-100"}`} /> );}function DayFace({ day, disabled, filled, preview = false, reduced, pop = false,}: { day: CalendarDay; disabled: boolean; filled: boolean; preview?: boolean; reduced: boolean; pop?: boolean;}) { const tone = filled ? "text-text-on-brand" : disabled ? "text-text-disabled" : day.isToday ? "text-brand-text font-medium" : day.inMonth ? "text-text" : "text-text-muted"; return ( <span className={`relative z-1 flex size-9 items-center justify-center rounded-control-sm text-ui-sm tabular-nums [transition:color_150ms_var(--eased-ease-standard),background-color_150ms_var(--eased-ease-standard),box-shadow_var(--eased-duration-focus)_var(--eased-ease-standard)] group-focus-visible/day:z-10 group-focus-visible/day:shadow-[0_0_0_2px_var(--eased-bg),0_0_0_4px_var(--eased-ring)] ${tone} ${ !filled && !disabled ? "group-hover-fine/day:bg-surface-hover group-active/day:bg-surface-active" : "" }`} > {pop && filled && ( <motion.span key={day.key} aria-hidden initial={reduced ? { opacity: 0 } : { scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: preview ? 0.75 : 1 }} transition={reduced ? reducedFade : { scale: snappy, opacity: enter }} className="absolute inset-0 rounded-[inherit] bg-brand" /> )} <span className="relative">{day.day}</span> {day.isToday && <span aria-hidden className="absolute bottom-1 left-1/2 size-1 -translate-x-1/2 rounded-pill bg-current" />} </span> );}function NavButton({ label, onClick, disabled, dir }: { label: string; onClick: () => void; disabled: boolean; dir: "left" | "right" }) { return ( <button type="button" aria-label={label} disabled={disabled} onClick={onClick} className={`inline-flex size-8 cursor-pointer items-center justify-center rounded-control-sm text-text-muted hover-fine:not-disabled:bg-surface-hover hover-fine:not-disabled:text-text active:not-disabled:bg-surface-active disabled:cursor-not-allowed disabled:text-text-disabled ${pressIcon}`} > <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" aria-hidden className="size-4"> <path d={dir === "left" ? "M9.5 3.5 5 8l4.5 4.5" : "M6.5 3.5 11 8l-4.5 4.5"} /> </svg> </button> );}Keep the folder layout
The files import each other by relative path (
../lib/motion), so keep each one at the path shown, undercomponents/eased/.
Usage
import { useState } from "react";import { DatePicker } from "@/components/eased/date-picker/date-picker";import { Field } from "@/components/eased/field/field";export function Example() { const [due, setDue] = useState<Date | null>(null); return ( <Field label="Due date" description="Type a date like “Oct 24” or pick one."> <DatePicker value={due} onValueChange={setDue} min={new Date()} /> </Field> );}Examples
A range
The trigger shows the span ("Oct 26 – 30, 2026"); click a start and an end, or drag across days. Label it with aria-labelledby, since a range has no text input for a Field label to point at.
<span id="away-label">Away</span><DatePicker mode="range" aria-labelledby="away-label" value={away} onValueChange={setAway} maxLength={21} />Weekdays only
isDateDisabled blocks days in the grid and rejects them when typed.
<DatePicker value={day} onValueChange={setDay} isDateDisabled={(d) => d.getDay() === 0 || d.getDay() === 6} />An inline calendar
import { Calendar } from "@/components/eased/date-picker/date-picker";<Calendar mode="range" value={stay} onValueChange={setStay} isDateDisabled={(d) => booked.has(toDayKey(d))} />API reference
DatePicker
| Prop | Type | Default | Description |
|---|---|---|---|
mode | "single" | "range" | "single" | One day in a text field, or a span on a button. |
value | Date | null or DateRange | null | Controlled value. A DateRange is { start, end }, both local midnight, inclusive. | |
defaultValue | same as value | null | Uncontrolled starting value. |
onValueChange | (value) => void | Fires when a day is picked or a typed date is committed (on blur or Enter). | |
onInvalidInput | (text: string) => void | Called with the text when a typed date can't be read or isn't allowed; the field shows the last value again. | |
min / max | Date | First and last selectable day. | |
isDateDisabled | (date: Date) => boolean | Days that can't be picked. A range never spans one. | |
minLength / maxLength | number | Range mode: fewest and most days. | |
locale | string | runtime | Parsing, formatting, month and weekday names. |
formatOptions | Intl.DateTimeFormatOptions | { day, month: "short", year } | How the value is written in the field. |
weekStartsOn | 0–6 | the locale's | First column of the grid. |
today | Date | now | The today mark, and the base for "tomorrow". Pass a fixed day for stable demos. |
closeOnSelect | boolean | true | Close after a day, or a range's second end, is picked. |
open / defaultOpen / onOpenChange | Control the popover. | ||
size | "sm" | "md" | "lg" | "md" | 32, 36 or 40px. |
align | "start" | "center" | "end" | "start" | Popover alignment against the field. |
zIndex | number | 50 | Raise it inside a dialog. |
className | string | "" | Classes for the bordered box. |
Single mode passes any other Base UI Input prop (name, id, required, aria-*) to the text input and takes calendarLabel (default "Choose date") for the calendar button. Range mode takes id, name (submits YYYY-MM-DD/YYYY-MM-DD), aria-label and aria-labelledby.
Calendar
The same props as the picker's selection (mode, value, defaultValue, onValueChange, min, max, isDateDisabled, minLength, maxLength, locale, weekStartsOn, today), plus defaultMonth, onMonthChange, autoFocus and onSelectComplete.
parseDate
parseDate(text, { locale, today }) returns the local Date the field would read from text, or null. It accepts ISO dates, numeric dates in the locale's order ("24/10" in en-GB, "10/24" in en-US), month names in the locale or English ("24 Oct", "October 24 2026") and today, tomorrow or yesterday.
Keyboard
| Key | Action |
|---|---|
↓ or Alt ↓ in the field | Opens the calendar on the selected day, or today. |
Enter in the field | Reads the typed date. |
Escape in the field | Drops what was typed. |
← → ↑ ↓ | Moves a day or a week; crossing a month edge pages the grid. |
Home / End | First or last day of the week. |
PageUp / PageDown | Previous or next month; with Shift, a year. |
Enter / Space | Picks the focused day (range: starts, then ends the span). |
Escape | Range: drops a half-picked span and keeps the calendar open. Otherwise closes and returns focus. |
Accessibility
- The grid is
role="grid"named by the month, withrow,columnheader(full weekday names) andgridcellparts. Each day is named in full ("Friday, October 23, 2026"), witharia-selected,aria-disabledandaria-current="date"for today. - One day is in the tab order (the selected day, else today); the popover opens with focus on it and returns focus to the trigger when it closes.
- The month title is a polite live region, so paging is announced.
- Disabled days stay focusable, so arrowing across a booked night doesn't skip silently.
Motion
Paging slides the outgoing month 14px out and the new one 28px in from the side you moved towards, on the smooth spring with a 200ms fade in and a 150ms fade out, while the title swaps up or down with a blur; paging again mid-slide redirects. The selected day's fill is one shared-layout element that glides to the new day on the snappy spring. A range's ends pop from 0.8 scale on snappy and the band between them fills in 150ms; a hovered preview shows at lower opacity until it's committed. The popover grows from the field on Eased's floating motion. Reduced motion: no slide, glide or pop; changes fade in 100ms.
Notes for AI
Pick DatePicker for any form field that holds a date or a span of dates; pick Calendar when the grid should always be visible. Set min, max and isDateDisabled rather than validating after the fact: they gate the grid and typed input alike. Pass locale explicitly when rendering on the server, and a fixed today in demos and tests.
Don't wrap it in another Popover or add your own text parsing; the single field already reads typed dates and the range button already formats the span. Values are local midnight Dates; convert to UTC yourself if your API needs it.
Related components
- Animated Text Input: the text field the single picker is built on.
- Animated Select: for short lists of dates or relative choices.
- Animated Popover: the floating layer the calendar opens in.