Date picker
A date field that opens a calendar in a popover: a single date, or a range with presets and two months side by side. With min and max dates, disabled days, a clear button and hidden inputs for forms.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker.json6 examples below; each installs the component with it. They wear whichever DressCode theme you install.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker-single.jsoncomponents/dresscode/date-picker-single.tsx
"use client"
// A due-date field on an invoice: label, hint, payment-term shortcuts, past days disabled,
// and a note when the date falls on a weekend.
import * as React from "react"
import { addDays, differenceInCalendarDays, format, isWeekend, startOfToday, subDays } from "date-fns"
import { Info } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { DatePicker, useToday } from "@/components/ui/date-picker"
const TERMS = [7, 14, 30]
const REMIND_BEFORE = 3
function dueHint(due: Date | undefined, today: Date | undefined) {
if (!due || !today) return `Fernwood Studio sees this date on the invoice. Orbit sends a reminder ${REMIND_BEFORE} days before it.`
const days = differenceInCalendarDays(due, today)
if (days === 0) return "Due today, so no reminder goes out first."
if (days <= REMIND_BEFORE) return `Due in ${days} ${days === 1 ? "day" : "days"}, too soon for a reminder.`
return `Due in ${days} days. Orbit reminds Fernwood Studio on ${format(subDays(due, REMIND_BEFORE), "EEE, MMM d")}.`
}
export default function DatePickerSingle() {
const id = React.useId()
const today = useToday()
const [due, setDue] = React.useState<Date | undefined>()
const term = due && today ? TERMS.find((t) => differenceInCalendarDays(due, today) === t) : undefined
const weekend = due && isWeekend(due)
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>Invoice INV-1043</CardTitle>
<CardDescription>Fernwood Studio · $4,200.00 · issued today</CardDescription>
<CardAction>
<Badge variant="secondary">Draft</Badge>
</CardAction>
</CardHeader>
<CardContent className="grid gap-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<Label id={`${id}-label`} htmlFor={id}>
Due date
</Label>
<ToggleGroup
aria-label="Payment terms"
variant="outline"
size="sm"
spacing={1}
value={term ? [String(term)] : []}
onValueChange={(values: string[]) => {
if (values[0]) setDue(addDays(today ?? startOfToday(), Number(values[0])))
}}
>
{TERMS.map((t) => (
<ToggleGroupItem key={t} value={String(t)} className="px-2 text-xs">
Net {t}
</ToggleGroupItem>
))}
</ToggleGroup>
</div>
<DatePicker
id={id}
aria-labelledby={`${id}-label`}
aria-describedby={weekend ? `${id}-hint ${id}-weekend` : `${id}-hint`}
value={due}
onValueChange={setDue}
min={today}
placeholder="Pick a due date"
displayFormat="EEE, MMM d, yyyy"
/>
<p id={`${id}-hint`} className="text-sm text-muted-foreground">
{dueHint(due, today)}
</p>
{weekend ? (
<p id={`${id}-weekend`} className="flex gap-2 rounded-lg bg-muted px-3 py-2 text-sm">
<Info aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<span>
{format(due, "MMM d")} is a {format(due, "EEEE")}. Bank transfers sent that day usually land on Monday.
</span>
</p>
) : null}
</CardContent>
<CardFooter className="justify-end gap-2">
<Button variant="outline">Save draft</Button>
<Button disabled={!due}>Send invoice</Button>
</CardFooter>
</Card>
)
}npx shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker-range-presets.jsoncomponents/dresscode/date-picker-range-presets.tsx
"use client"
// A payments report: a date range with presets beside the calendar, future days disabled,
// and totals that follow the range, compared with the period just before it.
import * as React from "react"
import { differenceInCalendarDays, eachDayOfInterval, subDays } from "date-fns"
import { ArrowDownRight, ArrowUpRight, Download } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import {
DateRangePicker,
dateRangePresets,
formatDateRange,
useToday,
type DateRange,
} from "@/components/ui/date-picker"
/** The day the workspace was created: nothing to report before it. */
const ACCOUNT_OPENED = new Date(2024, 0, 8)
const EPOCH = new Date(2020, 0, 1)
/** Sample payments for one day, the same every time for the same date. */
function paymentsOn(day: Date) {
const n = differenceInCalendarDays(day, EPOCH)
const r = Math.abs(Math.sin(n * 12.9898) * 43758.5453) % 1
const weekend = day.getDay() === 0 || day.getDay() === 6
const count = weekend ? (r > 0.75 ? 1 : 0) : 1 + Math.floor(r * 4)
return { count, amount: count * (640 + Math.round(r * 2200)), daysToPay: count * (6 + Math.floor(r * 19)) }
}
function totals(range: { from: Date; to: Date }) {
const days = eachDayOfInterval({ start: range.from, end: range.to }).map(paymentsOn)
const count = days.reduce((s, d) => s + d.count, 0)
return {
amount: days.reduce((s, d) => s + d.amount, 0),
count,
avgDays: count ? days.reduce((s, d) => s + d.daysToPay, 0) / count : 0,
}
}
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 })
function Delta({ now, before, lowerIsBetter = false }: { now: number; before: number; lowerIsBetter?: boolean }) {
if (!before) return <span className="text-xs text-muted-foreground">No earlier data</span>
const change = (now - before) / before
const up = change >= 0
const Icon = up ? ArrowUpRight : ArrowDownRight
const good = up !== lowerIsBetter
return (
<span className={good ? "inline-flex items-center gap-0.5 text-xs text-foreground" : "inline-flex items-center gap-0.5 text-xs text-destructive"}>
<Icon aria-hidden="true" className="size-3.5" />
{Math.abs(change * 100).toFixed(1)}%<span className="sr-only">{up ? " up" : " down"}</span>
</span>
)
}
export default function DatePickerRangePresets() {
const id = React.useId()
const today = useToday()
const [picked, setPicked] = React.useState<DateRange | undefined>()
// Last 30 days until someone picks: read through useToday so the prerendered page hydrates cleanly.
const range = picked ?? (today ? dateRangePresets[2].getRange(today) : undefined)
const full = range?.from ? { from: range.from, to: range.to ?? range.from } : undefined
const length = full ? differenceInCalendarDays(full.to, full.from) + 1 : 0
const previous = full ? { from: subDays(full.from, length), to: subDays(full.from, 1) } : undefined
const now = full ? totals(full) : undefined
const before = previous ? totals(previous) : undefined
const stats = now && before
? [
{ label: "Received", value: money.format(now.amount), delta: <Delta now={now.amount} before={before.amount} /> },
{ label: "Invoices paid", value: now.count.toLocaleString("en-US"), delta: <Delta now={now.count} before={before.count} /> },
{
label: "Average time to pay",
value: `${now.avgDays.toFixed(1)} days`,
delta: <Delta now={now.avgDays} before={before.avgDays} lowerIsBetter />,
},
]
: undefined
return (
<Card className="w-full max-w-3xl">
<CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="grid gap-1">
<CardTitle id={`${id}-title`}>Payments</CardTitle>
<CardDescription>Money received from all clients</CardDescription>
</div>
<span id={`${id}-period`} className="sr-only">
Report period
</span>
<DateRangePicker
aria-labelledby={`${id}-period`}
value={range}
onValueChange={setPicked}
presets={dateRangePresets}
min={ACCOUNT_OPENED}
max={today}
clearable={false}
align="end"
className="sm:w-auto"
triggerClassName="sm:min-w-64"
/>
</CardHeader>
<CardContent>
<dl aria-labelledby={`${id}-title`} className="grid gap-3 sm:grid-cols-3">
{stats
? stats.map((s) => (
<div key={s.label} className="grid gap-1 rounded-lg border p-4">
<dt className="text-sm text-muted-foreground">{s.label}</dt>
<dd className="text-2xl font-semibold tabular-nums">{s.value}</dd>
<dd>{s.delta}</dd>
</div>
))
: [0, 1, 2].map((i) => (
<div key={i} className="grid gap-2 rounded-lg border p-4">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-7 w-28" />
<Skeleton className="h-3 w-14" />
</div>
))}
</dl>
</CardContent>
<CardFooter className="flex-wrap justify-between gap-3">
<p className="text-sm text-muted-foreground" aria-live="polite">
{full && previous ? (
<>
{length} {length === 1 ? "day" : "days"}, compared with {formatDateRange(previous)}
</>
) : (
"Loading the period"
)}
</p>
<Button variant="outline" size="sm" disabled={!full}>
<Download aria-hidden="true" />
Export CSV
</Button>
</CardFooter>
</Card>
)
}Date and time
A day plus a time in 15-minute steps for scheduling a reminder, with the result in words.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker-date-time.jsoncomponents/dresscode/date-picker-date-time.tsx
"use client"
// Schedule a reminder: a day, a time in 15-minute steps, quick picks, and the result in words.
// Times that have already passed today are disabled, and the summary keeps counting down.
import * as React from "react"
import { addDays, differenceInCalendarDays, format, formatDistanceStrict, nextMonday, setHours, setMinutes, startOfToday } from "date-fns"
import { BellRing, CircleCheck, Clock } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { DatePicker, useToday } from "@/components/ui/date-picker"
const TIMES = Array.from({ length: 96 }, (_, i) => {
const at = setMinutes(setHours(new Date(2000, 0, 1), Math.floor(i / 4)), (i % 4) * 15)
return { value: format(at, "HH:mm"), label: format(at, "h:mm a") }
})
const subscribeToClock = (onTick: () => void) => {
const timer = window.setInterval(onTick, 15_000)
return () => window.clearInterval(timer)
}
/** The current minute, or undefined while prerendering, so the page hydrates cleanly. */
function useNow() {
const minute = React.useSyncExternalStore(subscribeToClock, () => Math.floor(Date.now() / 60_000), () => 0)
return React.useMemo(() => (minute ? new Date(minute * 60_000) : undefined), [minute])
}
function atTime(day: Date, time: string) {
const [h, m] = time.split(":").map(Number)
return setMinutes(setHours(day, h), m)
}
/** "PST", "GMT+8": the viewer's own time zone at that moment. */
function zoneName(at: Date) {
return new Intl.DateTimeFormat("en-US", { timeZoneName: "short" }).formatToParts(at).find((p) => p.type === "timeZoneName")?.value ?? ""
}
function inWords(at: Date, now: Date) {
const days = differenceInCalendarDays(at, now)
const day = days === 0 ? "today" : days === 1 ? "tomorrow" : days < 7 ? `on ${format(at, "EEEE")}` : `on ${format(at, "EEEE, MMMM d")}`
return `${day} at ${format(at, "h:mm a")}`
}
const QUICK = [
{ label: "Tomorrow morning", day: (today: Date) => addDays(today, 1), time: "09:00" },
{ label: "Monday morning", day: (today: Date) => nextMonday(today), time: "09:00" },
{ label: "In a week", day: (today: Date) => addDays(today, 7), time: "10:00" },
]
export default function DatePickerDateTime() {
const id = React.useId()
const today = useToday()
const now = useNow()
const [picked, setPicked] = React.useState<Date | undefined>()
const [time, setTime] = React.useState("09:00")
const [scheduled, setScheduled] = React.useState(false)
// Tomorrow until someone picks a day.
const day = picked ?? (today ? addDays(today, 1) : undefined)
const at = day ? atTime(day, time) : undefined
const isToday = !!day && !!today && differenceInCalendarDays(day, today) === 0
const passed = !!at && !!now && at <= now
const ready = !!at && !!now && !passed
// Picking today when the time has already gone moves the time to the next free quarter hour.
const pickDay = (next: Date | undefined) => {
setPicked(next)
if (next && now && atTime(next, time) <= now) {
const free = TIMES.find((t) => atTime(next, t.value) > now)
if (free) setTime(free.value)
}
}
if (scheduled && at && now) {
return (
<Card className="w-full max-w-md">
<CardContent className="grid justify-items-center gap-3 py-4 text-center">
<span className="flex size-10 items-center justify-center rounded-full bg-primary text-primary-foreground">
<CircleCheck aria-hidden="true" className="size-5" />
</span>
<div role="status" className="grid gap-1">
<p className="font-medium">Reminder scheduled</p>
<p className="text-sm text-muted-foreground">
Pellucid Health gets it {inWords(at, now)}, {formatDistanceStrict(at, now, { addSuffix: true })}.
</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => setScheduled(false)}>
Change time
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setScheduled(false)
setPicked(undefined)
setTime("09:00")
}}
>
Cancel reminder
</Button>
</div>
</CardContent>
</Card>
)
}
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>Schedule a reminder</CardTitle>
<CardDescription>Orbit emails Pellucid Health about INV-1036, $2,450.00 and 15 days late.</CardDescription>
</CardHeader>
<CardContent className="grid gap-4">
<div role="group" aria-label="Quick picks" className="flex flex-wrap gap-1.5">
{QUICK.map((q) => (
<Button
key={q.label}
variant="outline"
size="sm"
onClick={() => {
setPicked(q.day(today ?? startOfToday()))
setTime(q.time)
}}
>
{q.label}
</Button>
))}
</div>
<div className="grid grid-cols-[minmax(0,1fr)_8.5rem] gap-3">
<div className="grid gap-2">
<Label id={`${id}-day-label`} htmlFor={`${id}-day`}>
Day
</Label>
<DatePicker
id={`${id}-day`}
aria-labelledby={`${id}-day-label`}
value={day}
onValueChange={pickDay}
min={today}
clearable={false}
placeholder="Pick a day"
displayFormat="EEE, MMM d, yyyy"
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${id}-time`}>Time</Label>
<Select items={TIMES} value={time} onValueChange={(v) => v && setTime(v)}>
<SelectTrigger id={`${id}-time`} aria-invalid={passed || undefined} className="w-full">
<Clock aria-hidden="true" className="text-muted-foreground" />
<SelectValue />
</SelectTrigger>
<SelectContent alignItemWithTrigger={false} className="max-h-64">
{TIMES.map((t) => (
<SelectItem key={t.value} value={t.value} disabled={isToday && !!now && !!day && atTime(day, t.value) <= now}>
{t.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div aria-live="polite" className="flex gap-3 rounded-lg bg-muted p-3 text-sm">
<BellRing aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
{at && now ? (
passed ? (
<p className="text-destructive">{format(at, "h:mm a")} has already passed today. Pick a later time.</p>
) : (
<div className="grid gap-0.5">
<p className="font-medium">Sends {inWords(at, now)}</p>
<p className="text-muted-foreground">
{formatDistanceStrict(at, now, { addSuffix: true })} · {format(at, "MMM d, yyyy, h:mm a")}
{` · ${zoneName(at)}`}
</p>
</div>
)
) : (
<p className="text-muted-foreground">Pick a day and a time.</p>
)}
</div>
</CardContent>
<CardFooter className="justify-end gap-2">
<Button variant="ghost">Not now</Button>
<Button disabled={!ready} onClick={() => setScheduled(true)}>
Schedule reminder
</Button>
</CardFooter>
</Card>
)
}Month and year dropdowns
Month and year menus in the caption to jump to a birth date or a date years away.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker-month-year.jsoncomponents/dresscode/date-picker-month-year.tsx
"use client"
// Far-away dates: month and year dropdowns in the calendar caption jump decades in two clicks.
// A date of birth (no future days, an age check) and a passport expiry (warns when it runs out soon).
import * as React from "react"
import { addYears, differenceInMonths, differenceInYears } from "date-fns"
import { TriangleAlert } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { DatePicker, useToday } from "@/components/ui/date-picker"
const EARLIEST_BIRTH = new Date(1920, 0, 1)
const LATEST_EXPIRY = new Date(2046, 11, 31)
const MIN_AGE = 18
const WARN_MONTHS = 6
function plural(n: number, word: string) {
return `${n} ${word}${n === 1 ? "" : "s"}`
}
/** 112 -> "9 years and 4 months" */
function duration(months: number) {
const years = Math.floor(months / 12)
const rest = months % 12
return [years ? plural(years, "year") : "", rest ? plural(rest, "month") : ""].filter(Boolean).join(" and ")
}
export default function DatePickerMonthYear() {
const id = React.useId()
const today = useToday()
const [birth, setBirth] = React.useState<Date | undefined>()
const [expiry, setExpiry] = React.useState<Date | undefined>()
const age = birth && today ? differenceInYears(today, birth) : undefined
const tooYoung = age !== undefined && age < MIN_AGE
const monthsLeft = expiry && today ? differenceInMonths(expiry, today) : undefined
const expiresSoon = monthsLeft !== undefined && monthsLeft < WARN_MONTHS
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>Personal details</CardTitle>
<CardDescription>Needed for payouts over $600 a year. Only you and your accountant can see them.</CardDescription>
</CardHeader>
<CardContent className="grid gap-5">
<div className="grid gap-2">
<Label id={`${id}-birth-label`} htmlFor={`${id}-birth`}>
Date of birth
</Label>
<DatePicker
id={`${id}-birth`}
name="birthDate"
aria-labelledby={`${id}-birth-label`}
aria-describedby={`${id}-birth-hint`}
aria-invalid={tooYoung}
value={birth}
onValueChange={setBirth}
captionLayout="dropdown"
min={EARLIEST_BIRTH}
max={today}
calendarProps={{ defaultMonth: new Date(1990, 0) }}
displayFormat="MMMM d, yyyy"
placeholder="Pick your date of birth"
/>
<p id={`${id}-birth-hint`} className={tooYoung ? "text-sm text-destructive" : "text-sm text-muted-foreground"}>
{age === undefined
? "Use the month and year menus at the top of the calendar to get there fast."
: tooYoung
? `You need to be ${MIN_AGE} or older to receive payouts.`
: `Age ${age}.`}
</p>
</div>
<div className="grid gap-2">
<Label id={`${id}-expiry-label`} htmlFor={`${id}-expiry`}>
Passport expires on
</Label>
<DatePicker
id={`${id}-expiry`}
name="passportExpiry"
aria-labelledby={`${id}-expiry-label`}
aria-describedby={`${id}-expiry-hint`}
value={expiry}
onValueChange={setExpiry}
captionLayout="dropdown"
min={today}
max={LATEST_EXPIRY}
calendarProps={{ defaultMonth: today ? addYears(today, 5) : undefined }}
displayFormat="MMMM d, yyyy"
placeholder="Pick the expiry date"
/>
{expiresSoon ? (
<p id={`${id}-expiry-hint`} className="flex gap-2 rounded-lg bg-muted px-3 py-2 text-sm">
<TriangleAlert aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-destructive" />
<span>
Expires in {monthsLeft === 0 ? "less than a month" : plural(monthsLeft, "month")}. Renew it soon: many countries ask for {WARN_MONTHS} months left.
</span>
</p>
) : (
<p id={`${id}-expiry-hint`} className="text-sm text-muted-foreground">
{monthsLeft === undefined
? "The date printed on the photo page."
: `Valid for ${duration(monthsLeft)}.`}
</p>
)}
</div>
</CardContent>
<CardFooter className="justify-end gap-2">
<Button variant="ghost">Skip for now</Button>
<Button disabled={!birth || !expiry || tooYoung}>Save details</Button>
</CardFooter>
</Card>
)
}In a form
Validation for required dates, dates in the past and an end before the start, with submit disabled until valid.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker-form-field.jsoncomponents/dresscode/date-picker-form-field.tsx
"use client"
// Date pickers in a form: a recurring-invoice schedule with validation messages (required, not in the
// past, end after start), errors shown once a field has been touched, and Start disabled until valid.
import * as React from "react"
import { addDays, addMonths, addWeeks, format } from "date-fns"
import { CircleCheck } from "lucide-react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { DatePicker, useToday } from "@/components/ui/date-picker"
const REPEAT = [
{ value: "weekly", label: "Every week", step: (d: Date, n: number) => addWeeks(d, n) },
{ value: "fortnightly", label: "Every 2 weeks", step: (d: Date, n: number) => addWeeks(d, n * 2) },
{ value: "monthly", label: "Every month", step: (d: Date, n: number) => addMonths(d, n) },
]
const AMOUNT = 1200
/** The draft was saved a while ago, so its first date may have passed since. */
const DRAFT_START = new Date(2026, 10, 2)
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
type Errors = { start?: string; end?: string }
function validate(start: Date | undefined, end: Date | undefined, today: Date | undefined): Errors {
const errors: Errors = {}
if (!start) errors.start = "Pick the date of the first invoice."
else if (today && start < today) errors.start = "This date has passed. Pick today or a later day."
if (!end) errors.end = "Pick the date of the last invoice."
else if (start && end <= start) errors.end = "The last invoice has to come after the first one."
return errors
}
export default function DatePickerFormField() {
const id = React.useId()
const today = useToday()
const [repeat, setRepeat] = React.useState("monthly")
const [start, setStart] = React.useState<Date | undefined>(DRAFT_START)
const [end, setEnd] = React.useState<Date | undefined>()
// The saved start date counts as touched; the empty end date shows its error once it has been opened.
const [touched, setTouched] = React.useState({ start: true, end: false })
const [done, setDone] = React.useState(false)
const errors = validate(start, end, today)
const valid = !!today && !errors.start && !errors.end
const rule = REPEAT.find((r) => r.value === repeat) ?? REPEAT[2]
let count = 0
if (valid && start && end) while (count < 520 && rule.step(start, count) <= end) count++
const last = valid && start ? rule.step(start, count - 1) : undefined
const blocker = errors.start && errors.end ? "Fix both dates to start." : errors.start ? "Fix the first date to start." : errors.end ? "Fix the last date to start." : ""
const blocked = !valid && !!blocker
if (done && start && last) {
return (
<Card className="w-full max-w-lg">
<CardContent>
<Alert>
<CircleCheck aria-hidden="true" />
<AlertTitle>Schedule started</AlertTitle>
<AlertDescription>
{count === 1 ? "1 invoice" : `${count} invoices`} to Fernwood Studio, the first on {format(start, "MMM d, yyyy")} and the last on {format(last, "MMM d, yyyy")}.
</AlertDescription>
</Alert>
</CardContent>
<CardFooter className="justify-end">
<Button variant="outline" onClick={() => setDone(false)}>
Edit schedule
</Button>
</CardFooter>
</Card>
)
}
return (
<Card className="w-full max-w-lg">
<form
noValidate
onSubmit={(e) => {
e.preventDefault()
setTouched({ start: true, end: true })
if (valid) setDone(true)
}}
className="contents"
>
<CardHeader>
<CardTitle>Recurring invoice</CardTitle>
<CardDescription>Fernwood Studio · {money.format(AMOUNT)} each · draft saved Nov 2</CardDescription>
</CardHeader>
<CardContent className="grid gap-5">
<div className="grid gap-2">
<Label htmlFor={`${id}-repeat`}>Repeat</Label>
<Select items={REPEAT} value={repeat} onValueChange={(v) => v && setRepeat(v)}>
<SelectTrigger id={`${id}-repeat`} className="w-full sm:w-48">
<SelectValue />
</SelectTrigger>
<SelectContent>
{REPEAT.map((r) => (
<SelectItem key={r.value} value={r.value}>
{r.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid gap-5 sm:grid-cols-2 sm:gap-3">
<div className="grid content-start gap-2">
<Label id={`${id}-start-label`} htmlFor={`${id}-start`}>
First invoice
</Label>
<DatePicker
id={`${id}-start`}
name="startDate"
aria-labelledby={`${id}-start-label`}
aria-describedby={`${id}-start-msg`}
aria-invalid={touched.start && !!errors.start}
value={start}
onValueChange={setStart}
onOpenChange={(open) => !open && setTouched((t) => ({ ...t, start: true }))}
min={today}
placeholder="Pick a date"
/>
<p id={`${id}-start-msg`} className={touched.start && errors.start ? "text-sm text-destructive" : "text-sm text-muted-foreground"}>
{touched.start && errors.start ? errors.start : "Sent at 9:00 AM on the day."}
</p>
</div>
<div className="grid content-start gap-2">
<Label id={`${id}-end-label`} htmlFor={`${id}-end`}>
Last invoice
</Label>
<DatePicker
id={`${id}-end`}
name="endDate"
aria-labelledby={`${id}-end-label`}
aria-describedby={`${id}-end-msg`}
aria-invalid={touched.end && !!errors.end}
value={end}
onValueChange={(d) => {
setEnd(d)
if (!d) setTouched((t) => ({ ...t, end: true }))
}}
onOpenChange={(open) => !open && setTouched((t) => ({ ...t, end: true }))}
min={start && today && start >= today ? addDays(start, 1) : today}
placeholder="Pick a date"
/>
<p id={`${id}-end-msg`} className={touched.end && errors.end ? "text-sm text-destructive" : "text-sm text-muted-foreground"}>
{touched.end && errors.end ? errors.end : "No invoices go out after this day."}
</p>
</div>
</div>
<p aria-live="polite" className="rounded-lg bg-muted px-3 py-2 text-sm">
{valid && start && last ? (
<>
<span className="font-medium">{count === 1 ? "1 invoice" : `${count} invoices`}</span>, {rule.label.toLowerCase()} from{" "}
{format(start, "MMM d, yyyy")} to {format(last, "MMM d, yyyy")}:{" "}
<span className="font-medium">{money.format(count * AMOUNT)}</span> in total.
</>
) : (
<span className="text-muted-foreground">Pick both dates to see how many invoices go out.</span>
)}
</p>
</CardContent>
<CardFooter className="flex-wrap justify-end gap-x-3 gap-y-2">
{blocked ? (
<p id={`${id}-blockers`} className="mr-auto text-sm text-muted-foreground">
{blocker}
</p>
) : null}
<Button type="button" variant="outline">
Save draft
</Button>
<Button type="submit" disabled={!valid} aria-describedby={blocked ? `${id}-blockers` : undefined}>
Start schedule
</Button>
</CardFooter>
</form>
</Card>
)
}npx shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker-inline-booking.jsoncomponents/dresscode/date-picker-inline-booking.tsx
"use client"
// Booking a call: an inline calendar (no popover) beside the free time slots for the picked day.
// Weekends, fully booked days and anything past six weeks out are disabled.
import * as React from "react"
import { addDays, differenceInCalendarDays, format, isWeekend, setHours, setMinutes } from "date-fns"
import { CalendarCheck, CircleCheck, Clock, Video } from "lucide-react"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { DatePickerCalendar, useToday } from "@/components/ui/date-picker"
const BOOK_AHEAD_DAYS = 42
const EPOCH = new Date(2020, 0, 1)
/** 9:00 to 16:30, every half hour. */
const DAY_SLOTS = Array.from({ length: 16 }, (_, i) => ({ h: 9 + Math.floor(i / 2), m: (i % 2) * 30 }))
/** Sample availability: the same free slots every time for the same day. */
function freeSlots(day: Date) {
if (isWeekend(day)) return []
const n = differenceInCalendarDays(day, EPOCH)
if (Math.abs(Math.sin(n * 1.7) * 1e4) % 1 < 0.18) return [] // fully booked
return DAY_SLOTS.filter((_, i) => Math.abs(Math.sin(n * 7.13 + i * 3.7) * 1e4) % 1 > 0.55).map(({ h, m }) => setMinutes(setHours(day, h), m))
}
function firstFreeDay(today: Date) {
for (let i = 1; i <= BOOK_AHEAD_DAYS; i++) if (freeSlots(addDays(today, i)).length) return addDays(today, i)
}
export default function DatePickerInlineBooking() {
const id = React.useId()
const today = useToday()
const [picked, setPicked] = React.useState<Date | undefined>()
const [slot, setSlot] = React.useState<string>()
const [booked, setBooked] = React.useState(false)
// Tomorrow or the first day after it with a free slot, until someone picks.
const day = picked ?? (today ? firstFreeDay(today) : undefined)
const slots = day ? freeSlots(day) : []
const chosen = slots.find((s) => format(s, "HH:mm") === slot)
if (booked && chosen) {
return (
<Card className="w-full max-w-md items-center gap-3 px-6 py-8 text-center">
<span className="flex size-10 items-center justify-center rounded-full bg-primary text-primary-foreground">
<CircleCheck aria-hidden="true" className="size-5" />
</span>
<div role="status" className="grid gap-1">
<p className="text-base font-medium">You are booked</p>
<p className="text-sm text-muted-foreground">
{format(chosen, "EEEE, MMMM d")} at {format(chosen, "h:mm a")} with Ada Lin, 30 minutes. A calendar invite with the video link is on its way.
</p>
</div>
<Button variant="outline" size="sm" onClick={() => setBooked(false)}>
Pick another time
</Button>
</Card>
)
}
return (
<Card className="w-full max-w-4xl gap-0 py-0 md:flex-row">
<div className="grid content-start gap-4 border-b p-5 md:w-60 md:shrink-0 md:border-r md:border-b-0">
<div className="flex items-center gap-3">
<Avatar>
<AvatarFallback>AL</AvatarFallback>
</Avatar>
<div className="grid">
<span className="text-sm font-medium">Ada Lin</span>
<span className="text-xs text-muted-foreground">Customer success, Orbit</span>
</div>
</div>
<div className="grid gap-1">
<h2 className="text-lg font-semibold">Onboarding call</h2>
<p className="text-sm text-muted-foreground">Set up your first invoice, payment reminders and the client portal together.</p>
</div>
<ul className="grid gap-2 text-sm text-muted-foreground">
<li className="flex items-center gap-2">
<Clock aria-hidden="true" className="size-4" />
30 minutes
</li>
<li className="flex items-center gap-2">
<Video aria-hidden="true" className="size-4" />
Video call, link by email
</li>
<li className="flex items-center gap-2">
<CalendarCheck aria-hidden="true" className="size-4" />
Times in your time zone
</li>
</ul>
</div>
<div className="flex justify-center border-b p-3 md:border-r md:border-b-0">
{today && day ? (
<DatePickerCalendar
mode="single"
required
selected={day}
onSelect={(d) => {
setPicked(d)
setSlot(undefined)
}}
defaultMonth={day}
startMonth={today}
endMonth={addDays(today, BOOK_AHEAD_DAYS)}
disabled={[{ before: addDays(today, 1) }, { after: addDays(today, BOOK_AHEAD_DAYS) }, (d) => freeSlots(d).length === 0]}
aria-label="Pick a day"
className="bg-transparent p-2 sm:[--cell-size:--spacing(9)]"
/>
) : (
<div className="grid w-[268px] gap-3 p-2" aria-hidden="true">
<Skeleton className="mx-auto h-5 w-32" />
<Skeleton className="h-64 w-full" />
</div>
)}
</div>
<div className="flex min-w-0 flex-1 flex-col gap-3 p-5">
{day ? (
<>
<h3 className="text-sm font-medium" id={`${id}-slots`}>
{format(day, "EEEE, MMM d")}
<span className="block text-xs font-normal text-muted-foreground">
{slots.length} {slots.length === 1 ? "time" : "times"} free
</span>
</h3>
<ToggleGroup
aria-labelledby={`${id}-slots`}
orientation="vertical"
variant="outline"
spacing={1.5}
value={slot ? [slot] : []}
onValueChange={(values: string[]) => setSlot(values[0])}
className="grid w-full grid-cols-3 sm:grid-cols-4 md:flex md:max-h-72 md:overflow-y-auto md:p-0.5"
>
{slots.map((s) => (
<ToggleGroupItem
key={s.getTime()}
value={format(s, "HH:mm")}
className="w-full tabular-nums aria-pressed:border-primary aria-pressed:bg-primary aria-pressed:text-primary-foreground aria-pressed:hover:bg-primary"
>
{format(s, "h:mm a")}
</ToggleGroupItem>
))}
</ToggleGroup>
<Button className="mt-auto w-full" disabled={!chosen} onClick={() => setBooked(true)}>
{chosen ? `Book ${format(chosen, "h:mm a")}` : "Pick a time"}
</Button>
</>
) : (
<div className="grid gap-2" aria-hidden="true">
<Skeleton className="h-4 w-32" />
{[0, 1, 2, 3, 4].map((i) => (
<Skeleton key={i} className="h-8 w-full" />
))}
</div>
)}
</div>
</Card>
)
}The component
What shadcn@latest add https://dresscodeui.com/r/dresscode/date-picker.json writes. It uses only shadcn/ui's variables, so it follows the theme.
components/ui/date-picker.tsx
"use client"
// Date picker: a field-sized button that opens a calendar in a popover.
// DatePicker picks one day. DateRangePicker picks a range: two months side by side on wide screens and
// one on phones, an optional list of presets, and an Apply step so a half-picked range never leaks out.
// Both take min/max and disabled days, show a clear button once there is a value (Backspace or Delete
// on the trigger clears too), and write ISO dates to a hidden input when given a `name`.
// Pass `aria-labelledby` with your label's id: the picked date is appended to the accessible name.
// DatePickerCalendar is the calendar inside them, for inline use: roomier cells, arrow keys that move
// focus, and a grid that is not rebuilt each time the parent renders.
// Built on the shadcn/ui Calendar (react-day-picker) and Popover; reads only the theme's variables.
import * as React from "react"
import { differenceInCalendarDays, differenceInCalendarMonths, endOfMonth, format, isSameDay, startOfDay, startOfMonth, startOfYear, subDays, subMonths } from "date-fns"
import { CalendarIcon, CheckIcon, XIcon } from "lucide-react"
import { getDefaultClassNames, type DateRange, type DayButtonProps, type Matcher, type PropsBase, type RootProps } from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Calendar, CalendarDayButton } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
/** Calendar options you can pass through; selection, month and disabled days are the picker's own. */
type CalendarOptions = Omit<PropsBase, "mode" | "required" | "disabled" | "month" | "onMonthChange" | "numberOfMonths">
// ---------------------------------------------------------------------------------------------
// Clock and helpers
const subscribeToMinutes = (onTick: () => void) => {
const timer = window.setInterval(onTick, 60_000)
return () => window.clearInterval(timer)
}
/**
* Today at midnight, or undefined on the server and during hydration. Read "today" through this hook
* when it shows up in what you render, so a page prerendered on another day (or in another time zone)
* hydrates without a mismatch. It rolls over at midnight.
*/
function useToday() {
const time = React.useSyncExternalStore(subscribeToMinutes, () => startOfDay(new Date()).getTime(), () => 0)
return React.useMemo(() => (time ? new Date(time) : undefined), [time])
}
function useMediaQuery(query: string) {
const subscribe = React.useCallback(
(onChange: () => void) => {
const list = window.matchMedia(query)
list.addEventListener("change", onChange)
return () => list.removeEventListener("change", onChange)
},
[query],
)
return React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false)
}
/** Controlled when the `value` prop is passed at all (even as undefined), uncontrolled otherwise. */
function useValue<T>(props: object, value: T | undefined, defaultValue: T | undefined, onChange?: (next: T | undefined) => void) {
const controlled = "value" in props
const [own, setOwn] = React.useState(defaultValue)
const set = (next: T | undefined) => {
if (!controlled) setOwn(next)
onChange?.(next)
}
return [controlled ? value : own, set] as const
}
function toMatchers(min?: Date, max?: Date, disabledDays?: Matcher | Matcher[]): Matcher[] {
const extra = disabledDays === undefined ? [] : Array.isArray(disabledDays) ? disabledDays : [disabledDays]
return [...(min ? [{ before: startOfDay(min) }] : []), ...(max ? [{ after: startOfDay(max) }] : []), ...extra]
}
const rdp = getDefaultClassNames()
/** Month and year dropdowns that look like small select fields (the native select stays on top, invisible). */
const DROPDOWN_CLASSNAMES = {
dropdown_root: cn(
"relative rounded-md border border-input shadow-xs has-focus-visible:border-ring has-focus-visible:ring-3 has-focus-visible:ring-ring/50",
rdp.dropdown_root,
),
dropdown: cn("absolute inset-0 cursor-pointer bg-popover opacity-0", rdp.dropdown),
caption_label: cn(
"flex h-7 items-center gap-1 rounded-md pr-1.5 pl-2 text-sm font-medium select-none [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
rdp.caption_label,
),
}
// ---------------------------------------------------------------------------------------------
// DatePickerCalendar
// Stable parts for the stock Calendar. It defines its Root and DayButton inline, so every render of
// the Calendar is a new component type and React rebuilds the grid (dropping keyboard focus); and its
// day button never moves DOM focus when the arrow keys move the focused day.
function CalendarRoot({ className, rootRef, ...props }: RootProps) {
return <div data-slot="calendar" ref={rootRef} className={className} {...props} />
}
function CalendarFocusDayButton(props: DayButtonProps) {
const ref = React.useRef<HTMLSpanElement>(null)
const focused = props.modifiers.focused
React.useEffect(() => {
if (focused) ref.current?.querySelector("button")?.focus()
}, [focused])
return (
<span ref={ref} className="contents">
<CalendarDayButton {...props} />
</span>
)
}
/** The pickers' calendar, for inline use too. Takes every Calendar (react-day-picker) prop. */
function DatePickerCalendar({ className, components, formatters, ...props }: React.ComponentProps<typeof Calendar>) {
return (
<Calendar
// Roomier day cells than the stock calendar, and finger-sized on phones.
className={cn("p-3 [--cell-size:--spacing(9)] sm:[--cell-size:--spacing(8)]", className)}
components={{ Root: CalendarRoot, DayButton: CalendarFocusDayButton, ...components }}
// Month names in the calendar's own locale (the stock dropdown uses the browser's).
formatters={{ formatMonthDropdown: (month, dateLib) => (dateLib ? dateLib.format(month, "LLL") : format(month, "LLL")), ...formatters }}
{...props}
/>
)
}
/** "Nov 3, 2026", "Oct 26 – Nov 24, 2026" or "Dec 15, 2025 – Jan 14, 2026". */
function formatDateRange(range: DateRange | undefined, placeholder = "") {
if (!range?.from) return placeholder
const { from, to } = range
if (!to || isSameDay(from, to)) return format(from, "MMM d, yyyy")
if (from.getFullYear() === to.getFullYear()) return `${format(from, "MMM d")} – ${format(to, "MMM d, yyyy")}`
return `${format(from, "MMM d, yyyy")} – ${format(to, "MMM d, yyyy")}`
}
const sameRange = (a?: DateRange, b?: DateRange) =>
!!a?.from && !!b?.from && !!a.to && !!b.to && isSameDay(a.from, b.from) && isSameDay(a.to, b.to)
function clampRange(range: DateRange, min?: Date, max?: Date): DateRange | undefined {
let { from, to } = range
if (from && min && from < startOfDay(min)) from = startOfDay(min)
if (to && max && to > startOfDay(max)) to = startOfDay(max)
if (!from || (to && from > to)) return undefined
return { from, to }
}
// ---------------------------------------------------------------------------------------------
// The field: trigger button, clear button and hidden input
type PickerBaseProps = {
id?: string
/** Writes the value to a hidden input: yyyy-MM-dd, or yyyy-MM-dd/yyyy-MM-dd for a range. */
name?: string
placeholder?: string
disabled?: boolean
/** Show a button that clears the value. Default true. */
clearable?: boolean
clearLabel?: string
/** The earliest day that can be picked; also where month navigation stops. */
min?: Date
/** The latest day that can be picked; also where month navigation stops. */
max?: Date
/** More days that cannot be picked: dates, ranges, { dayOfWeek: [0, 6] }, a function... */
disabledDays?: Matcher | Matcher[]
align?: "start" | "center" | "end"
open?: boolean
onOpenChange?: (open: boolean) => void
/** The field wrapper. */
className?: string
triggerClassName?: string
calendarProps?: CalendarOptions
"aria-invalid"?: boolean
"aria-describedby"?: string
"aria-labelledby"?: string
"aria-label"?: string
}
type PickerFieldProps = Pick<
PickerBaseProps,
"id" | "name" | "disabled" | "clearLabel" | "className" | "triggerClassName" | "aria-invalid" | "aria-describedby" | "aria-labelledby" | "aria-label"
> & {
slot: string
hasValue: boolean
showClear: boolean
hiddenValue: string
onClear: () => void
triggerRef: React.RefObject<HTMLButtonElement | null>
children: React.ReactNode
}
function PickerField({ slot, hasValue, showClear, hiddenValue, onClear, triggerRef, clearLabel, className, triggerClassName, children, ...props }: PickerFieldProps) {
const valueId = React.useId()
const clear = () => {
onClear()
triggerRef.current?.focus()
}
return (
<div data-slot={slot} className={cn("relative w-full", className)}>
<PopoverTrigger
ref={triggerRef}
id={props.id}
disabled={props.disabled}
aria-invalid={props["aria-invalid"] || undefined}
aria-describedby={props["aria-describedby"]}
aria-label={props["aria-label"]}
aria-labelledby={props["aria-labelledby"] ? `${props["aria-labelledby"]} ${valueId}` : undefined}
onKeyDown={(e) => {
if (showClear && (e.key === "Backspace" || e.key === "Delete")) {
e.preventDefault()
onClear()
}
}}
render={
<Button
variant="outline"
data-slot={`${slot}-trigger`}
className={cn(
// Looks like the other fields (border-input, no fill); the open state keeps the button's muted fill.
"w-full justify-start gap-2 border-input bg-transparent px-2.5 text-left font-normal hover:bg-transparent",
showClear && "pr-9",
!hasValue && "text-muted-foreground hover:text-muted-foreground aria-expanded:text-muted-foreground",
triggerClassName,
)}
/>
}
>
<CalendarIcon aria-hidden="true" className="text-muted-foreground" />
<span id={valueId} className="min-w-0 flex-1 truncate">
{children}
</span>
</PopoverTrigger>
{showClear ? (
<Button
type="button"
variant="ghost"
size="icon-xs"
data-slot={`${slot}-clear`}
aria-label={clearLabel}
onClick={clear}
className="absolute inset-y-0 right-1 my-auto text-muted-foreground hover:text-foreground"
>
<XIcon />
</Button>
) : null}
{props.name ? <input type="hidden" name={props.name} value={hiddenValue} /> : null}
</div>
)
}
/** On keyboard open, focus the picked day (or today) so the arrow keys move through the grid at once. */
function useDayFocus() {
const bodyRef = React.useRef<HTMLDivElement>(null)
const initialFocus = (openType: string) =>
openType === "keyboard" ? (bodyRef.current?.querySelector<HTMLElement>('[role="grid"] button[tabindex="0"]') ?? true) : true
return { bodyRef, initialFocus }
}
// ---------------------------------------------------------------------------------------------
// DatePicker
type DatePickerProps = PickerBaseProps & {
value?: Date | undefined
defaultValue?: Date
onValueChange?: (date: Date | undefined) => void
/** date-fns format for the button text. Default "MMM d, yyyy" (Nov 24, 2026). */
displayFormat?: string
/** "dropdown" puts month and year selects in the caption, for birth dates and far-off dates. */
captionLayout?: PropsBase["captionLayout"]
/** Close the popover once a day is picked. Default true. */
closeOnSelect?: boolean
/** Rendered in the popover under the calendar. */
footer?: React.ReactNode
}
function DatePicker(props: DatePickerProps) {
const {
defaultValue,
onValueChange,
placeholder = "Pick a date",
displayFormat = "MMM d, yyyy",
min,
max,
disabledDays,
captionLayout = "label",
closeOnSelect = true,
footer,
clearable = true,
clearLabel = "Clear date",
disabled,
align = "start",
open: openProp,
onOpenChange,
calendarProps,
...field
} = props
const [value, setValue] = useValue(props, props.value, defaultValue, onValueChange)
const [ownOpen, setOwnOpen] = React.useState(false)
const open = openProp ?? ownOpen
const setOpen = (next: boolean) => {
setOwnOpen(next)
onOpenChange?.(next)
}
const triggerRef = React.useRef<HTMLButtonElement>(null)
const { bodyRef, initialFocus } = useDayFocus()
const dropdowns = captionLayout !== "label"
return (
<Popover open={open} onOpenChange={setOpen}>
<PickerField
{...field}
slot="date-picker"
disabled={disabled}
clearLabel={clearLabel}
hasValue={!!value}
showClear={clearable && !!value && !disabled}
hiddenValue={value ? format(value, "yyyy-MM-dd") : ""}
onClear={() => setValue(undefined)}
triggerRef={triggerRef}
>
{value ? format(value, displayFormat) : placeholder}
</PickerField>
<PopoverContent align={align} initialFocus={initialFocus} className="max-h-(--available-height) w-auto gap-0 overflow-y-auto p-0">
<div ref={bodyRef} data-slot="date-picker-content">
<DatePickerCalendar
{...calendarProps}
mode="single"
required
selected={value}
onSelect={(day) => {
setValue(day)
if (closeOnSelect) setOpen(false)
}}
defaultMonth={value ?? calendarProps?.defaultMonth}
startMonth={calendarProps?.startMonth ?? min}
endMonth={calendarProps?.endMonth ?? max}
disabled={toMatchers(min, max, disabledDays)}
captionLayout={captionLayout}
classNames={dropdowns ? { ...DROPDOWN_CLASSNAMES, ...calendarProps?.classNames } : calendarProps?.classNames}
/>
{footer ? (
<div data-slot="date-picker-footer" className="border-t p-3">
{footer}
</div>
) : null}
</div>
</PopoverContent>
</Popover>
)
}
// ---------------------------------------------------------------------------------------------
// DateRangePicker
type DateRangePreset = {
label: string
/** The preset's range, given today at midnight. */
getRange: (today: Date) => DateRange
}
/** Report-style presets. "This month" and "This year" run up to today. */
const dateRangePresets: DateRangePreset[] = [
{ label: "Today", getRange: (today) => ({ from: today, to: today }) },
{ label: "Last 7 days", getRange: (today) => ({ from: subDays(today, 6), to: today }) },
{ label: "Last 30 days", getRange: (today) => ({ from: subDays(today, 29), to: today }) },
{ label: "This month", getRange: (today) => ({ from: startOfMonth(today), to: today }) },
{
label: "Last month",
getRange: (today) => {
const month = subMonths(today, 1)
return { from: startOfMonth(month), to: startOfDay(endOfMonth(month)) }
},
},
{ label: "This year", getRange: (today) => ({ from: startOfYear(today), to: today }) },
]
type DateRangePickerProps = PickerBaseProps & {
value?: DateRange | undefined
defaultValue?: DateRange
onValueChange?: (range: DateRange | undefined) => void
/** Shortcuts beside the calendar (above it on phones). See `dateRangePresets`. */
presets?: DateRangePreset[]
/** Default: 2 on screens 768px and wider, 1 below. */
numberOfMonths?: number
/** Keep the change as a draft until Apply (default). false: commit as soon as both ends are picked. */
confirm?: boolean
/** The shortest and longest range, in days. */
minDays?: number
maxDays?: number
/** Start over when a range would include a disabled day. */
excludeDisabled?: boolean
applyLabel?: string
}
function DateRangePicker(props: DateRangePickerProps) {
const {
defaultValue,
onValueChange,
placeholder = "Pick a date range",
presets,
numberOfMonths,
confirm = true,
minDays,
maxDays,
excludeDisabled,
applyLabel = "Apply",
min,
max,
disabledDays,
clearable = true,
clearLabel = "Clear dates",
disabled,
align = "start",
open: openProp,
onOpenChange,
calendarProps,
...field
} = props
const [value, setValue] = useValue(props, props.value, defaultValue, onValueChange)
const today = useToday()
const wide = useMediaQuery("(min-width: 768px)")
const months = numberOfMonths ?? (wide ? 2 : 1)
const [ownOpen, setOwnOpen] = React.useState(false)
const open = openProp ?? ownOpen
const [draft, setDraft] = React.useState<DateRange | undefined>(value)
const [month, setMonth] = React.useState<Date>()
const triggerRef = React.useRef<HTMLButtonElement>(null)
const { bodyRef, initialFocus } = useDayFocus()
const presetRange = (preset: DateRangePreset) => (today ? clampRange(preset.getRange(today), min, max) : undefined)
const activePreset = value ? presets?.find((p) => sameRange(presetRange(p), value)) : undefined
// The first month to show: where the range starts if it fits, else so it ends on the last month shown;
// then kept inside the navigable months (a report ending today shows last month and this one).
const monthFor = (range: DateRange | undefined) => {
const end = range?.to ?? range?.from ?? today ?? new Date()
const start = range?.from ?? end
let first = startOfMonth(differenceInCalendarMonths(end, start) < months ? start : subMonths(end, months - 1))
const lastMonth = calendarProps?.endMonth ?? max
const firstMonth = calendarProps?.startMonth ?? min
if (lastMonth && differenceInCalendarMonths(lastMonth, first) < months - 1) first = startOfMonth(subMonths(lastMonth, months - 1))
if (firstMonth && first < startOfMonth(firstMonth)) first = startOfMonth(firstMonth)
return first
}
const setOpen = (next: boolean) => {
if (next) {
setDraft(value)
setMonth(monthFor(value))
}
setOwnOpen(next)
onOpenChange?.(next)
}
const commit = (range: DateRange | undefined) => {
setValue(range?.from ? { from: range.from, to: range.to ?? range.from } : undefined)
setOpen(false)
}
const pickPreset = (range: DateRange) => {
if (!confirm) return commit(range)
setDraft(range)
setMonth(monthFor(range))
}
const days = draft?.from && draft.to ? differenceInCalendarDays(draft.to, draft.from) + 1 : 0
return (
<Popover open={open} onOpenChange={setOpen}>
<PickerField
{...field}
slot="date-range-picker"
disabled={disabled}
clearLabel={clearLabel}
hasValue={!!value?.from}
showClear={clearable && !!value?.from && !disabled}
hiddenValue={value?.from ? `${format(value.from, "yyyy-MM-dd")}/${format(value.to ?? value.from, "yyyy-MM-dd")}` : ""}
onClear={() => setValue(undefined)}
triggerRef={triggerRef}
>
{activePreset ? <span className="hidden text-muted-foreground sm:inline">{activePreset.label} · </span> : null}
{formatDateRange(value, placeholder)}
</PickerField>
<PopoverContent
align={align}
initialFocus={initialFocus}
className="max-h-(--available-height) w-auto max-w-[calc(100vw-1rem)] gap-0 overflow-y-auto p-0"
>
<div ref={bodyRef} data-slot="date-range-picker-content" className="flex flex-col sm:flex-row">
{presets?.length ? (
<div
role="group"
aria-label="Presets"
data-slot="date-range-picker-presets"
className="grid grid-cols-2 gap-1 border-b p-2 sm:flex sm:w-36 sm:shrink-0 sm:flex-col sm:border-r sm:border-b-0"
>
{presets.map((preset) => {
const range = presetRange(preset)
const active = sameRange(range, draft)
return (
<Button
key={preset.label}
type="button"
variant="ghost"
size="sm"
aria-pressed={active}
disabled={!range}
onClick={() => range && pickPreset(range)}
className="justify-between font-normal aria-pressed:bg-muted aria-pressed:font-medium aria-pressed:text-foreground"
>
{preset.label}
{active ? <CheckIcon aria-hidden="true" /> : null}
</Button>
)
})}
</div>
) : null}
<DatePickerCalendar
{...calendarProps}
mode="range"
resetOnSelect
selected={draft}
onSelect={(range) => {
setDraft(range)
if (!confirm && range?.from && range.to) commit(range)
}}
month={month}
onMonthChange={setMonth}
numberOfMonths={months}
min={minDays}
max={maxDays}
excludeDisabled={excludeDisabled}
startMonth={calendarProps?.startMonth ?? min}
endMonth={calendarProps?.endMonth ?? max}
disabled={toMatchers(min, max, disabledDays)}
className={cn("max-sm:mx-auto", calendarProps?.className)}
/>
</div>
{confirm ? (
<div data-slot="date-range-picker-footer" className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t p-3">
<p aria-live="polite" className="text-sm">
{!draft?.from ? (
<span className="text-muted-foreground">Pick a start date</span>
) : !draft.to ? (
<>
<span className="font-medium">{format(draft.from, "MMM d, yyyy")}</span>
<span className="text-muted-foreground"> – pick an end date</span>
</>
) : (
<>
<span className="font-medium">{formatDateRange(draft)}</span>
<span className="text-muted-foreground">
{" "}
· {days} {days === 1 ? "day" : "days"}
</span>
</>
)}
</p>
<div className="ml-auto flex gap-2">
<Button type="button" variant="ghost" size="sm" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button type="button" size="sm" disabled={!draft?.from} onClick={() => commit(draft)}>
{applyLabel}
</Button>
</div>
</div>
) : null}
</PopoverContent>
</Popover>
)
}
export { DatePicker, DatePickerCalendar, DateRangePicker, dateRangePresets, formatDateRange, useToday }
export type { DatePickerProps, DateRange, DateRangePickerProps, DateRangePreset }