Date Range Picker
SaveA trigger that opens two months with presets and optional start and end times, where the picked range fills in as one band that sweeps from the first day to the last.
- Category
- Forms
- Version
- 0.1.1
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Date Range Picker preview
Installation
npx @shakenui/cli add date-range-pickerReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add date-range-picker --dry-runUsage
date-range-picker-example.tsx
"use client";
import { addDays, startOfDay } from "@/components/shaken/ui/calendar";
import { DateRangePicker } from "@/components/shaken/ui/date-range-picker";
// Usage exports can only go back 90 days; weekends are frozen for the maintenance window.
const today = startOfDay(new Date());
export default function DateRangePickerExample() {
return (
<div className="flex flex-wrap items-end justify-center gap-6">
<div className="grid gap-1.5">
<label htmlFor="export-range" className="text-sm font-medium text-zinc-950 dark:text-white">
Export usage for
</label>
<DateRangePicker
id="export-range"
defaultValue={{ from: addDays(today, -6), to: today }}
minDate={addDays(today, -90)}
maxDate={today}
/>
</div>
<div className="grid gap-1.5">
<label htmlFor="maintenance-window" className="text-sm font-medium text-zinc-950 dark:text-white">
Maintenance window
</label>
<DateRangePicker
id="maintenance-window"
withTime
presets={[]}
minDate={today}
isDateDisabled={(date) => date.getDay() === 0 || date.getDay() === 6}
defaultTimes={{ start: "22:00", end: "23:30" }}
placeholder="Schedule downtime"
/>
</div>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| value / defaultValue / onValueChange | { from: Date | null; to: Date | null } | — | The applied range, controlled or not. onValueChange fires on Apply. |
| presets | { label, range: (today) => { from, to } }[] | defaultRangePresets | Quick ranges in the side column: Today, Last 7 days, Last 30 days, This month, Last month. Custom is always added. Pass [] to hide the column. |
| minDate / maxDate | Date | — | Bounds for picking and month navigation. Presets that fall outside are turned off. |
| isDateDisabled | (date) => boolean | — | Days that cannot be picked. A range never spans one. |
| withTime | boolean | false | Adds Starts and Ends time fields; the applied dates carry the times. |
| defaultTimes | { start: string; end: string } | { start: "09:00", end: "17:00" } | Times for a fresh range, as HH:mm. |
| hourCycle | 12 | 24 | — | Hour cycle of the time fields and trigger. Defaults to the locale. |
| numberOfMonths | 1 | 2 | 2 | Months side by side on wide screens; under 640px it is always one. |
| weekStartsOn / locale / today | number / string / Date | — | First weekday (defaults to the locale's), BCP 47 locale for names and formatting, and an override for today. |
| placeholder / disabled / id / aria-label / className / align | string / boolean / string / string / string / "start" | "center" | "end" | — | Trigger text, state, attributes and classes, and the popover alignment. |
Accessibility
- The trigger is a Base UI Popover trigger (aria-expanded, aria-controls) showing the applied range; opening moves focus to the start day (or today) in the grid, and Escape closes and returns focus to the trigger.
- Each month is a role="grid" with rows and gridcells; aria-selected marks days in the range and aria-current="date" marks today. Days have full date labels such as "Tuesday, November 17, 2026".
- Arrow keys move by day and week, Home and End to the ends of the week, Page Up and Page Down by month (with Shift, by year), crossing into hidden months as needed. Enter or Space picks a day.
- Disabled days stay focusable with aria-disabled so arrow keys can pass them, and they are struck through, not only dimmed.
- Presets are toggle buttons with aria-pressed; Custom is pressed when the range matches no preset and moves focus into the grid.
- The footer summary is a polite live region ("Nov 17 to 19, 3 days", or "Pick an end date"); Apply stays disabled until the range is complete and the times are valid.
- The band sweep and the popover scale play only with motion allowed; with reduced motion the band appears filled at once.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/date-range-picker.tsxdate-range-picker- Also installs calendar@0.1.0registry dependency
- Also installs popover@0.2.2registry dependency
- Also installs button@0.2.1registry dependency
- Also installs time-picker@0.1.1registry dependency
- npm packages: motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/date-range-picker/0.1.1.json.
ui/date-range-picker.tsxShowHide
ui/date-range-picker.tsx
"use client";
import { motion, useReducedMotion } from "motion/react";
import { type KeyboardEvent, type ReactNode, useEffect, useId, useMemo, useRef, useState } from "react";
import { Button } from "./button";
import { addDays, addMonths, countDays, type DateRange, isSameDay, startOfDay } from "./calendar";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { TimePicker } from "./time-picker";
export type { DateRange } from "./calendar";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const startOfMonth = (date: Date) => new Date(date.getFullYear(), date.getMonth(), 1);
const isSameMonth = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth();
const dayKey = (date: Date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
const lastOfMonth = (date: Date) => new Date(date.getFullYear(), date.getMonth() + 1, 0);
function localeWeekStart(locale?: string): number {
try {
const info = new Intl.Locale(locale ?? navigator.language) as Intl.Locale & {
getWeekInfo?: () => { firstDay: number };
weekInfo?: { firstDay: number };
};
const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay;
if (firstDay) return firstDay % 7;
} catch {
// Older engines: fall through to Sunday.
}
return 0;
}
function useWide() {
const [wide, setWide] = useState(true);
useEffect(() => {
const query = window.matchMedia("(min-width: 640px)");
const update = () => setWide(query.matches);
update();
query.addEventListener("change", update);
return () => query.removeEventListener("change", update);
}, []);
return wide;
}
export interface RangePreset {
label: string;
/** Computes the range from today when the preset is shown or picked. */
range: (today: Date) => { from: Date; to: Date };
}
/** Today, Last 7 days, Last 30 days, This month, and Last month. */
export const defaultRangePresets: RangePreset[] = [
{ label: "Today", range: (today) => ({ from: today, to: today }) },
{ label: "Last 7 days", range: (today) => ({ from: addDays(today, -6), to: today }) },
{ label: "Last 30 days", range: (today) => ({ from: addDays(today, -29), to: today }) },
{ label: "This month", range: (today) => ({ from: startOfMonth(today), to: today }) },
{
label: "Last month",
range: (today) => {
const start = addMonths(startOfMonth(today), -1);
return { from: start, to: lastOfMonth(start) };
},
},
];
const timeOf = (date: Date | null, fallback: string) =>
date && (date.getHours() || date.getMinutes()) ? `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}` : fallback;
function withTime(date: Date | null, time: string | null) {
if (!date) return null;
const [hours, minutes] = (time ?? "00:00").split(":").map(Number);
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours ?? 0, minutes ?? 0);
}
export interface DateRangePickerProps {
/** The applied range. With `withTime`, `from` and `to` carry their times. */
value?: DateRange;
defaultValue?: DateRange;
/** Called when Apply is pressed. */
onValueChange?: (range: DateRange) => void;
/** Quick ranges in the side column, followed by Custom. Pass `[]` to hide the column. */
presets?: RangePreset[];
/** Earliest pickable day. Navigation stops at its month. */
minDate?: Date;
/** Latest pickable day. Navigation stops at its month. */
maxDate?: Date;
/** Days that cannot be picked. A range never spans one. */
isDateDisabled?: (date: Date) => boolean;
/** Adds start and end time fields under the months. */
withTime?: boolean;
/** 12 or 24 for the time fields. Defaults to the locale. */
hourCycle?: 12 | 24;
/** Default times for a fresh range, "HH:mm". */
defaultTimes?: { start: string; end: string };
/** Months side by side on wide screens. Narrow screens always show one. */
numberOfMonths?: 1 | 2;
/** First column, 0 for Sunday. Defaults to the locale's first day. */
weekStartsOn?: number;
/** BCP 47 locale for names and formatting. Defaults to the browser's. */
locale?: string;
/** Overrides "today". */
today?: Date;
/** Trigger text when nothing is applied. */
placeholder?: string;
/** Turns the trigger off. */
disabled?: boolean;
"aria-label"?: string;
id?: string;
/** Classes for the trigger. */
className?: string;
align?: "start" | "center" | "end";
}
/**
* A trigger that opens two months side by side (one on narrow screens) with a preset column and
* optional start and end times. Picks are a draft until Apply; Escape or Cancel drops them. The
* committed range fills in as one band that sweeps from the start day to the end day.
*/
export function DateRangePicker({
value: valueProp,
defaultValue,
onValueChange,
presets = defaultRangePresets,
minDate,
maxDate,
isDateDisabled,
withTime: timed = false,
hourCycle,
defaultTimes = { start: "09:00", end: "17:00" },
numberOfMonths = 2,
weekStartsOn: weekStartsOnProp,
locale,
today: todayProp,
placeholder = "Pick a date range",
disabled = false,
id,
className,
align = "start",
...aria
}: DateRangePickerProps) {
const wide = useWide();
const months = wide ? numberOfMonths : 1;
const [inner, setInner] = useState<DateRange>(defaultValue ?? { from: null, to: null });
const value = valueProp ?? inner;
const [open, setOpen] = useState(false);
const [today, setToday] = useState(() => startOfDay(todayProp ?? new Date()));
const [draft, setDraft] = useState<DateRange>({ from: null, to: null });
const [times, setTimes] = useState<{ start: string | null; end: string | null }>({ start: defaultTimes.start, end: defaultTimes.end });
const [month, setMonth] = useState(() => startOfMonth(value.from ?? today));
const [sweep, setSweep] = useState(0);
const [weekStartsOn, setWeekStartsOn] = useState(weekStartsOnProp ?? 0);
const gridRef = useRef<HTMLDivElement>(null);
useEffect(() => setWeekStartsOn(weekStartsOnProp ?? localeWeekStart(locale)), [weekStartsOnProp, locale]);
const min = minDate ? startOfDay(minDate) : null;
const max = maxDate ? startOfDay(maxDate) : null;
const blocked = (date: Date) => (min !== null && date < min) || (max !== null && date > max) || (isDateDisabled?.(date) ?? false);
function onOpenChange(next: boolean) {
if (next) {
const now = startOfDay(todayProp ?? new Date());
setToday(now);
const from = value.from ? startOfDay(value.from) : null;
const to = value.to ? startOfDay(value.to) : null;
setDraft({ from, to });
setTimes({ start: timeOf(value.from, defaultTimes.start), end: timeOf(value.to, defaultTimes.end) });
setMonth(from && to ? fitMonths(from, to, now) : startOfMonth(from ?? now));
}
setOpen(next);
}
/**
* The first visible month for a range: the end is always on screen, and a short range leans
* toward today's month rather than an empty month after it.
*/
function fitMonths(from: Date, to: Date, now = today) {
const toMonth = startOfMonth(to);
let right = addMonths(startOfMonth(from), months - 1);
const ceiling = startOfMonth(now) > toMonth ? startOfMonth(now) : toMonth;
if (right > ceiling) right = ceiling;
if (right < toMonth) right = toMonth;
return addMonths(right, -(months - 1));
}
function commitDraft(next: DateRange, animate: boolean) {
setDraft(next);
if (animate && next.from && next.to) setSweep((count) => count + 1);
}
function pickPreset(preset: RangePreset) {
const range = preset.range(today);
commitDraft({ from: startOfDay(range.from), to: startOfDay(range.to) }, true);
setMonth(fitMonths(range.from, range.to));
}
function apply() {
const next = timed ? { from: withTime(draft.from, times.start), to: withTime(draft.to, times.end) } : draft;
if (valueProp === undefined) setInner(next);
onValueChange?.(next);
setOpen(false);
}
const presetState = presets.map((preset) => {
const range = preset.range(today);
const outside = blocked(startOfDay(range.from)) || blocked(startOfDay(range.to));
const active = isSameDay(range.from, draft.from) && isSameDay(range.to, draft.to);
return { preset, outside, active };
});
const customActive = !!draft.from && !presetState.some((item) => item.active);
const longFormat = useMemo(
() => new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: "numeric", ...(timed ? { hour: "numeric", minute: "2-digit", hourCycle: hourCycle === 12 ? "h12" : hourCycle === 24 ? "h23" : undefined } : {}) }),
[locale, timed, hourCycle],
);
const shortFormat = useMemo(() => new Intl.DateTimeFormat(locale, { month: "short", day: "numeric" }), [locale]);
const triggerLabel = value.from && value.to ? longFormat.formatRange(value.from, value.to) : null;
const days = draft.from && draft.to ? countDays(draft.from, draft.to) : 0;
const summary = draft.from && draft.to ? `${shortFormat.formatRange(draft.from, draft.to)}, ${days} ${days === 1 ? "day" : "days"}` : draft.from ? "Pick an end date" : "Pick a start date";
const timesValid = !timed || (times.start !== null && times.end !== null && !(draft.from && draft.to && isSameDay(draft.from, draft.to) && times.start > times.end));
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger
id={id}
disabled={disabled}
aria-label={aria["aria-label"] ? `${aria["aria-label"]}${triggerLabel ? `, ${triggerLabel}` : ""}` : undefined}
render={<Button variant="secondary" />}
className={cx(
"min-w-60 justify-start px-3 font-normal tabular-nums data-[popup-open]:border-zinc-950/20 dark:data-[popup-open]:border-white/25",
className,
)}
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="text-zinc-500">
<rect x="2.25" y="3.25" width="11.5" height="10.5" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M2.5 6.75h11M5.5 1.75v3M10.5 1.75v3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
{/* Intl output can differ by a space between server and browser. */}
<span suppressHydrationWarning className={cx("truncate", !triggerLabel && "text-zinc-500")}>
{triggerLabel ?? placeholder}
</span>
</PopoverTrigger>
<PopoverContent
align={align}
initialFocus={() => gridRef.current?.querySelector<HTMLElement>('button[tabindex="0"]') ?? true}
className="w-auto max-w-[calc(100vw-2rem)] p-0"
>
<div className={cx("flex", presets.length > 0 && "max-sm:flex-col")}>
{presets.length > 0 ? (
<div
role="group"
aria-label="Presets"
className={cx(
"flex gap-0.5 border-zinc-950/[0.07] p-2 dark:border-white/[0.08]",
"max-sm:w-0 max-sm:min-w-full max-sm:overflow-x-auto max-sm:border-b sm:w-36 sm:flex-col sm:border-r",
)}
>
{presetState.map(({ preset, outside, active }) => (
<PresetButton key={preset.label} active={active} disabled={outside} onClick={() => pickPreset(preset)}>
{preset.label}
</PresetButton>
))}
<PresetButton
active={customActive}
onClick={() => gridRef.current?.querySelector<HTMLElement>('button[tabindex="0"]')?.focus()}
>
Custom
</PresetButton>
</div>
) : null}
<div className="grid min-w-0">
<div ref={gridRef} className="p-3">
<RangeMonths
month={month}
onMonthChange={setMonth}
count={months}
draft={draft}
onDraftChange={commitDraft}
blocked={blocked}
min={min}
max={max}
today={today}
weekStartsOn={weekStartsOn}
locale={locale}
sweep={sweep}
/>
</div>
{timed ? (
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-zinc-950/[0.07] px-4 py-3 dark:border-white/[0.08]">
<TimeRow label="Starts" value={times.start} hourCycle={hourCycle} locale={locale} onChange={(start) => setTimes((t) => ({ ...t, start }))} />
<TimeRow
label="Ends"
value={times.end}
hourCycle={hourCycle}
locale={locale}
invalid={!timesValid}
onChange={(end) => setTimes((t) => ({ ...t, end }))}
/>
</div>
) : null}
<div className="flex items-center gap-2 border-t border-zinc-950/[0.07] py-2.5 ps-4 pe-2.5 dark:border-white/[0.08]">
<p aria-live="polite" className="min-w-0 truncate text-xs text-zinc-500 tabular-nums">
{!timesValid && draft.from && draft.to ? <span className="text-red-600 dark:text-red-400">End time is before the start</span> : summary}
</p>
<Button variant="ghost" size="sm" className="ms-auto" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button size="sm" disabled={!draft.from || !draft.to || !timesValid} onClick={apply}>
Apply
</Button>
</div>
</div>
</div>
</PopoverContent>
</Popover>
);
}
function TimeRow({
label,
value,
hourCycle,
locale,
invalid,
onChange,
}: {
label: string;
value: string | null;
hourCycle?: 12 | 24;
locale?: string;
invalid?: boolean;
onChange: (value: string | null) => void;
}) {
const labelId = useId();
return (
<div className="flex items-center gap-2.5">
<span id={labelId} className="w-11 text-xs font-medium text-zinc-500">
{label}
</span>
<TimePicker aria-labelledby={labelId} value={value} onValueChange={onChange} hourCycle={hourCycle} locale={locale} invalid={invalid} className="h-8" />
</div>
);
}
function PresetButton({
active,
disabled,
onClick,
className,
children,
}: {
active: boolean;
disabled?: boolean;
onClick: () => void;
className?: string;
children: ReactNode;
}) {
return (
<button
type="button"
aria-pressed={active}
disabled={disabled}
onClick={onClick}
className={cx(
"h-8 shrink-0 rounded-md px-2.5 text-left text-sm whitespace-nowrap",
"transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
"disabled:pointer-events-none disabled:opacity-40",
active
? "bg-zinc-950/[0.06] font-medium text-zinc-950 dark:bg-white/[0.09] dark:text-white"
: "text-zinc-600 hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
className,
)}
>
{children}
</button>
);
}
const EASE = [0.23, 1, 0.32, 1] as const;
function RangeMonths({
month,
onMonthChange,
count,
draft,
onDraftChange,
blocked,
min,
max,
today,
weekStartsOn,
locale,
sweep,
}: {
month: Date;
onMonthChange: (month: Date) => void;
count: number;
draft: DateRange;
onDraftChange: (range: DateRange, animate: boolean) => void;
blocked: (date: Date) => boolean;
min: Date | null;
max: Date | null;
today: Date;
weekStartsOn: number;
locale?: string;
sweep: number;
}) {
const reduce = useReducedMotion();
const [focused, setFocused] = useState<Date>(() => draft.from ?? today);
const [hovered, setHovered] = useState<Date | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const shouldFocus = useRef(false);
// The sweep plays once per commit; rows that mount later (after paging) appear filled.
const played = useRef(sweep);
const playing = sweep !== played.current;
useEffect(() => {
played.current = sweep;
});
useEffect(() => {
if (!shouldFocus.current) return;
shouldFocus.current = false;
rootRef.current?.querySelector<HTMLButtonElement>('button[tabindex="0"]')?.focus();
});
const visible = Array.from({ length: count }, (_, index) => addMonths(month, index));
const firstVisible = visible[0]!;
const lastVisible = lastOfMonth(visible[visible.length - 1]!);
const canPrev = !min || startOfMonth(min) < month;
const canNext = !max || startOfMonth(max) > visible[visible.length - 1]!;
function select(date: Date) {
if (blocked(date)) return;
setFocused(date);
let next: DateRange;
if (!draft.from || draft.to) next = { from: date, to: null };
else if (date < draft.from) next = { from: date, to: draft.from };
else next = { from: draft.from, to: date };
if (next.from && next.to) {
for (let day = next.from; day <= next.to; day = addDays(day, 1)) {
if (blocked(day)) {
next = { from: date, to: null };
break;
}
}
}
onDraftChange(next, true);
}
function moveFocus(target: Date) {
let next = target;
if (min && next < min) next = min;
if (max && next > max) next = max;
setFocused(next);
if (next < firstVisible) onMonthChange(startOfMonth(next));
else if (next > lastVisible) onMonthChange(addMonths(startOfMonth(next), -(count - 1)));
shouldFocus.current = true;
}
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
const column = (focused.getDay() - weekStartsOn + 7) % 7;
const moves: Record<string, () => Date> = {
ArrowLeft: () => addDays(focused, -1),
ArrowRight: () => addDays(focused, 1),
ArrowUp: () => addDays(focused, -7),
ArrowDown: () => addDays(focused, 7),
Home: () => addDays(focused, -column),
End: () => addDays(focused, 6 - column),
PageUp: () => addMonths(focused, event.shiftKey ? -12 : -1),
PageDown: () => addMonths(focused, event.shiftKey ? 12 : 1),
};
const move = moves[event.key];
if (!move) return;
event.preventDefault();
moveFocus(move());
}
const monthFormat = useMemo(() => new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }), [locale]);
const dayFormat = useMemo(() => new Intl.DateTimeFormat(locale, { weekday: "long", month: "long", day: "numeric", year: "numeric" }), [locale]);
const weekdays = useMemo(() => {
const short = new Intl.DateTimeFormat(locale, { weekday: "short" });
const long = new Intl.DateTimeFormat(locale, { weekday: "long" });
return Array.from({ length: 7 }, (_, index) => {
const date = new Date(2023, 0, 1 + ((index + weekStartsOn) % 7));
return { short: short.format(date).slice(0, 2), long: long.format(date) };
});
}, [locale, weekStartsOn]);
// Hovering a day the range could not reach (a disabled day in between) previews nothing.
let preview = draft.from && !draft.to && hovered ? (hovered < draft.from ? { from: hovered, to: draft.from } : { from: draft.from, to: hovered }) : null;
if (preview) {
for (let day = preview.from; day <= preview.to; day = addDays(day, 1)) {
if (blocked(day)) {
preview = null;
break;
}
}
}
const committed = draft.from && draft.to ? { from: draft.from, to: draft.to } : null;
const span = preview ?? committed;
// The visible part of the committed range sets the sweep's pace: about 14ms a day, 480ms at most.
const sweepFrom = committed ? (committed.from < firstVisible ? firstVisible : committed.from) : null;
const sweepTo = committed ? (committed.to > lastVisible ? lastVisible : committed.to) : null;
const sweepDays = sweepFrom && sweepTo && sweepFrom <= sweepTo ? countDays(sweepFrom, sweepTo) : 0;
const sweepTotal = Math.min(480, 200 + sweepDays * 14) / 1000;
const focusTarget = visible.some((m) => isSameMonth(m, focused)) ? focused : draft.from && visible.some((m) => isSameMonth(m, draft.from!)) ? draft.from : firstVisible;
return (
<div
ref={rootRef}
data-slot="range-months"
className={cx("grid gap-4 text-sm text-zinc-950 dark:text-white", count === 2 && "sm:grid-cols-2 sm:gap-6")}
>
{visible.map((shown, monthIndex) => {
const first = startOfMonth(shown);
const offset = (first.getDay() - weekStartsOn + 7) % 7;
const gridStart = addDays(first, -offset);
const weeks = Array.from({ length: 6 }, (_, row) => Array.from({ length: 7 }, (_, col) => addDays(gridStart, row * 7 + col)));
const titleId = `range-${dayKey(first)}-title`;
return (
<div key={dayKey(first)} className="grid w-[15.75rem] content-start gap-2">
<div className="relative flex h-8 items-center justify-center">
{monthIndex === 0 ? (
<NavButton label="Previous month" disabled={!canPrev} onClick={() => onMonthChange(addMonths(month, -1))} className="absolute left-0">
<path d="M10 3.5 5.5 8l4.5 4.5" />
</NavButton>
) : null}
<h2 id={titleId} aria-live="polite" className="text-sm font-semibold">
{monthFormat.format(shown)}
</h2>
{monthIndex === count - 1 ? (
<NavButton label="Next month" disabled={!canNext} onClick={() => onMonthChange(addMonths(month, 1))} className="absolute right-0">
<path d="M6 3.5 10.5 8 6 12.5" />
</NavButton>
) : null}
</div>
<div role="grid" aria-labelledby={titleId} aria-multiselectable onKeyDown={onKeyDown} onPointerLeave={() => setHovered(null)} className="grid gap-0.5">
<div role="row" className="grid grid-cols-7">
{weekdays.map((weekday) => (
<div key={weekday.long} role="columnheader" aria-label={weekday.long} className="flex h-8 items-center justify-center text-xs text-zinc-500">
{weekday.short}
</div>
))}
</div>
{weeks.map((week, row) => {
// This row's slice of the span, inside the month.
const inRow = week.map((date, col) => ({ date, col })).filter(({ date }) => isSameMonth(date, shown) && span && date >= span.from && date <= span.to);
const band = inRow.length > 0 ? { start: inRow[0]!, end: inRow[inRow.length - 1]! } : null;
if (week.every((date) => !isSameMonth(date, shown)) && row > 3) return <div key={row} role="row" aria-hidden="true" className="h-9" />;
let bandNode: ReactNode = null;
if (band) {
const style = { left: `${(band.start.col / 7) * 100}%`, width: `${((band.end.col - band.start.col + 1) / 7) * 100}%` };
if (preview) {
bandNode = <span aria-hidden="true" className="absolute inset-y-0 rounded-lg bg-zinc-950/[0.035] dark:bg-white/[0.05]" style={style} />;
} else {
const delay = sweepFrom && sweepDays ? ((countDays(sweepFrom, band.start.date) - 1) / sweepDays) * sweepTotal : 0;
const duration = (inRow.length / Math.max(1, sweepDays)) * sweepTotal;
const isLast = sweepTo !== null && isSameDay(band.end.date, sweepTo);
const isFirst = sweepFrom !== null && isSameDay(band.start.date, sweepFrom);
bandNode = (
<motion.span
key={`${sweep}-${dayKey(band.start.date)}`}
aria-hidden="true"
className="absolute inset-y-0 rounded-lg bg-zinc-950/[0.06] dark:bg-white/[0.09]"
style={style}
initial={playing && !reduce ? { clipPath: "inset(0 100% 0 0 round 8px)" } : false}
animate={{ clipPath: "inset(0 0% 0 0 round 8px)" }}
transition={{ duration, delay, ease: isFirst && isLast ? EASE : isLast ? "easeOut" : "linear" }}
/>
);
}
}
return (
<div key={row} role="row" className="relative grid grid-cols-7">
{bandNode}
{week.map((date) => {
const outside = !isSameMonth(date, shown);
if (outside) return <div key={dayKey(date)} role="gridcell" aria-hidden="true" className="h-9" />;
const isBlocked = blocked(date);
const isToday = isSameDay(date, today);
const isEndpoint = isSameDay(date, draft.from) || isSameDay(date, draft.to) || (!!preview && isSameDay(date, hovered));
const solid = isSameDay(date, draft.from) || isSameDay(date, draft.to);
const inCommitted = !!committed && date >= committed.from && date <= committed.to;
return (
<div key={dayKey(date)} role="gridcell" aria-selected={inCommitted} className="relative z-[1] flex h-9 items-center justify-center">
<button
type="button"
tabIndex={isSameDay(date, focusTarget) ? 0 : -1}
aria-label={dayFormat.format(date)}
aria-current={isToday ? "date" : undefined}
aria-disabled={isBlocked || undefined}
onClick={() => select(date)}
onPointerEnter={() => setHovered(date)}
onFocus={() => setFocused(date)}
className={cx(
"relative flex size-9 items-center justify-center rounded-lg text-sm tabular-nums",
"transition-[background-color,color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-1 focus-visible:outline-sky-500",
solid
? "bg-zinc-950 font-medium text-white dark:bg-white dark:text-black"
: isBlocked
? "cursor-not-allowed text-zinc-400 line-through decoration-zinc-950/25 dark:text-zinc-600 dark:decoration-white/25"
: cx(
span && date >= span.from && date <= span.to ? "text-zinc-950 dark:text-white" : "text-zinc-700 dark:text-zinc-300",
isEndpoint && "shadow-[inset_0_0_0_1px_rgb(9_9_11/0.25)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.3)]",
"hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
),
isToday && !solid && "font-semibold",
)}
>
{date.getDate()}
{isToday ? <span aria-hidden="true" className={cx("absolute bottom-1.5 size-1 rounded-full", solid ? "bg-white dark:bg-black" : "bg-sky-500")} /> : null}
</button>
</div>
);
})}
</div>
);
})}
</div>
</div>
);
})}
</div>
);
}
function NavButton({ label, disabled, onClick, className, children }: { label: string; disabled?: boolean; onClick: () => void; className?: string; children: ReactNode }) {
return (
<button
type="button"
aria-label={label}
disabled={disabled}
onClick={onClick}
className={cx(
"inline-flex size-8 items-center justify-center rounded-lg text-zinc-600 dark:text-zinc-400",
"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
"disabled:pointer-events-none disabled:opacity-35",
className,
)}
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
{children}
</svg>
</button>
);
}