Calendar
A month on graph paper to pick from: one day, several, or a range. Today is ringed, the chosen day shaded in with the pen, a range hatched between its ends.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
"use client";
import { useState } from "react";
import { Calendar } from "@/components/ui/calendar";
export default function CalendarDemo() {
const [date, setDate] = useState<Date | undefined>(new Date(2026, 9, 17));
return <Calendar mode="single" selected={date} onSelect={setDate} defaultMonth={new Date(2026, 9, 1)} seed="cal-demo" />;
}Installation
pnpm dlx shadcn@latest add @ballpoint/ calendar"use client";
import { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent } from "react";
import { cn } from "@/lib/utils";
import { penStyle, useInkFrame, useInkSeed, usePen, type Pen } from "@/hooks/use-ink-box";
import { InkSvg, Stroke } from "@/lib/ink";
import { InkGlyph } from "@/lib/ink-glyphs";
import { hatchStrokes, ringStroke } from "@/lib/ink-sketch";
import { Button } from "@/components/ui/button";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
// A month on graph paper, with no date library: plain Date arithmetic and
// Intl for the names, so the same calendar renders in any locale. Days are
// always local midnight, so the day you click is the day you get back.
export type DateRange = { from?: Date; to?: Date };
/** Days to switch off: a test, a date, a span, days of the week (0 is Sunday), or a list of any of these. */
export type DayMatcher =
| boolean
| ((date: Date) => boolean)
| Date
| { before?: Date; after?: Date; from?: Date; to?: Date; dayOfWeek?: number | number[] }
| DayMatcher[];
const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
const startOfMonth = (d: Date) => new Date(d.getFullYear(), d.getMonth(), 1);
const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
const addMonths = (d: Date, n: number) => {
const target = new Date(d.getFullYear(), d.getMonth() + n, 1);
// Keep the day of the month, stopping at the end of a shorter one.
const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
return new Date(target.getFullYear(), target.getMonth(), Math.min(d.getDate(), last));
};
const sameDay = (a?: Date, b?: Date) => !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
const sameMonth = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth();
const dayKey = (d: Date) => `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
const time = (d: Date) => startOfDay(d).getTime();
// Today comes from the browser's clock: the server's can be a different day.
// useSyncExternalStore takes the server's reading first, then the browser's,
// so hydration agrees and the browser's day wins straight after.
const subscribeNever = () => () => {};
const localDay = () => {
const now = new Date();
return `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
};
const utcDay = () => {
const now = new Date();
return `${now.getUTCFullYear()}-${now.getUTCMonth() + 1}-${now.getUTCDate()}`;
};
function matches(matcher: DayMatcher | undefined, date: Date): boolean {
if (matcher === undefined || matcher === false) return false;
if (matcher === true) return true;
if (typeof matcher === "function") return matcher(date);
if (matcher instanceof Date) return sameDay(matcher, date);
if (Array.isArray(matcher)) return matcher.some((m) => matches(m, date));
const t = time(date);
if (matcher.before && t < time(matcher.before)) return true;
if (matcher.after && t > time(matcher.after)) return true;
if (matcher.from && matcher.to && t >= time(matcher.from) && t <= time(matcher.to)) return true;
if (matcher.dayOfWeek !== undefined) return [matcher.dayOfWeek].flat().includes(date.getDay());
return false;
}
/** The days of a month as rows of seven, starting on `weekStartsOn`, with the days of its neighbours that share a row. */
function weeksOf(month: Date, weekStartsOn: number) {
const first = startOfMonth(month);
const lead = (first.getDay() - weekStartsOn + 7) % 7;
const days = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
const rows = Math.ceil((lead + days) / 7);
return Array.from({ length: rows }, (_, row) => Array.from({ length: 7 }, (_, col) => addDays(first, row * 7 + col - lead)));
}
type Common = {
className?: string;
/** How many months to show side by side. */
numberOfMonths?: number;
/** The month shown first, when `month` isn't controlling it. */
defaultMonth?: Date;
month?: Date;
onMonthChange?: (month: Date) => void;
/** The first and last month it can be taken to. */
startMonth?: Date;
endMonth?: Date;
disabled?: DayMatcher;
showOutsideDays?: boolean;
/** 0 is Sunday. */
weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
/** A BCP 47 tag, for the names of months and days. */
locale?: string;
/** "label" is the month and year in words; "dropdown" lets you pick both. */
captionLayout?: "label" | "dropdown";
seed?: string | number;
} & Pick<Pen, "roughness" | "draw" | "weight" | "speed">;
export type CalendarProps = Common &
(
| { mode?: "single"; selected?: Date; defaultSelected?: Date; onSelect?: (date: Date | undefined) => void }
| { mode: "multiple"; selected?: Date[]; defaultSelected?: Date[]; onSelect?: (dates: Date[] | undefined) => void }
| { mode: "range"; selected?: DateRange; defaultSelected?: DateRange; onSelect?: (range: DateRange | undefined) => void }
);
/**
* A month of days to pick from: one day, several, or a range. Today is
* ringed, the chosen day is shaded in with the pen, and a range is hatched
* between its ends. Arrow keys move between days, Page Up and Page Down
* between months (with Shift, years), Home and End to the ends of the week.
*/
function Calendar(props: CalendarProps) {
const {
className,
numberOfMonths = 1,
defaultMonth,
month: monthProp,
onMonthChange,
startMonth,
endMonth,
disabled,
showOutsideDays = true,
weekStartsOn = 0,
locale = "en-US",
captionLayout = "label",
seed,
roughness,
draw,
weight,
speed,
} = props;
const mode = props.mode ?? "single";
const pen = usePen({ roughness, draw, weight, speed });
const uid = useId();
// The selection: the caller's, or ours when they only want to hear about changes.
const [own, setOwn] = useState<Date | Date[] | DateRange | undefined>(props.defaultSelected);
const selected = (props.selected !== undefined ? props.selected : own) as Date | Date[] | DateRange | undefined;
const select = (next: Date | Date[] | DateRange | undefined) => {
if (props.selected === undefined) setOwn(next);
(props.onSelect as ((value: typeof next) => void) | undefined)?.(next);
};
const todayKey = useSyncExternalStore(subscribeNever, localDay, utcDay);
const today = useMemo(() => {
const [y, m, d] = todayKey.split("-").map(Number);
return new Date(y, m - 1, d);
}, [todayKey]);
const firstSelected = Array.isArray(selected) ? selected[0] : selected instanceof Date ? selected : selected?.from;
const [shown, setShown] = useState<Date | null>(null);
const month = startOfMonth(monthProp ?? shown ?? defaultMonth ?? firstSelected ?? today);
const goTo = (target: Date) => {
let next = startOfMonth(target);
if (startMonth && next < startOfMonth(startMonth)) next = startOfMonth(startMonth);
if (endMonth && next > startOfMonth(endMonth)) next = startOfMonth(endMonth);
setShown(next);
onMonthChange?.(next);
};
const canPrev = !startMonth || addMonths(month, -1) >= startOfMonth(startMonth);
const canNext = !endMonth || addMonths(month, numberOfMonths) <= startOfMonth(endMonth);
// The one day that can be tabbed to; arrow keys move it.
const [focused, setFocused] = useState<Date | null>(null);
const wantsFocus = useRef(false);
const months = Array.from({ length: numberOfMonths }, (_, i) => addMonths(month, i));
const inView = (d: Date) => months.some((m) => sameMonth(m, d));
const anchor = focused && inView(focused) ? focused : firstSelected && inView(firstSelected) && !matches(disabled, firstSelected) ? firstSelected : inView(today) ? today : month;
useEffect(() => {
if (!wantsFocus.current || !focused) return;
wantsFocus.current = false;
document.getElementById(`${uid}-${dayKey(focused)}`)?.focus();
}, [focused, uid, month]);
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
const from = anchor;
const moves: Record<string, Date> = {
ArrowLeft: addDays(from, -1),
ArrowRight: addDays(from, 1),
ArrowUp: addDays(from, -7),
ArrowDown: addDays(from, 7),
PageUp: addMonths(from, event.shiftKey ? -12 : -1),
PageDown: addMonths(from, event.shiftKey ? 12 : 1),
Home: addDays(from, -((from.getDay() - weekStartsOn + 7) % 7)),
End: addDays(from, 6 - ((from.getDay() - weekStartsOn + 7) % 7)),
};
const target = moves[event.key];
if (!target) return;
event.preventDefault();
if (startMonth && target < startOfMonth(startMonth)) return;
if (endMonth && target > addDays(startOfMonth(addMonths(endMonth, 1)), -1)) return;
wantsFocus.current = true;
setFocused(target);
if (!months.some((m) => sameMonth(m, target))) goTo(target < month ? target : addMonths(target, -(numberOfMonths - 1)));
};
const pick = (date: Date) => {
setFocused(date);
if (mode === "single") {
select(sameDay(selected as Date | undefined, date) ? undefined : date);
} else if (mode === "multiple") {
const list = (selected as Date[] | undefined) ?? [];
const next = list.some((d) => sameDay(d, date)) ? list.filter((d) => !sameDay(d, date)) : [...list, date];
select(next.length ? next : undefined);
} else {
const range = (selected as DateRange | undefined) ?? {};
if (!range.from || range.to) select({ from: date });
else select(date < range.from ? { from: date, to: range.from } : { from: range.from, to: date });
}
};
const names = useMemo(() => {
const weekday = new Intl.DateTimeFormat(locale, { weekday: "short" });
const long = new Intl.DateTimeFormat(locale, { weekday: "long" });
// 2023-01-01 was a Sunday.
const days = Array.from({ length: 7 }, (_, i) => new Date(2023, 0, 1 + ((i + weekStartsOn) % 7)));
return {
weekdays: days.map((d) => ({ short: weekday.format(d).slice(0, 2), long: long.format(d) })),
month: new Intl.DateTimeFormat(locale, { month: "long" }),
caption: new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }),
label: new Intl.DateTimeFormat(locale, { weekday: "long", month: "long", day: "numeric", year: "numeric" }),
};
}, [locale, weekStartsOn]);
const range = mode === "range" ? (selected as DateRange | undefined) : undefined;
const isSelected = (d: Date) =>
mode === "single" ? sameDay(selected as Date | undefined, d) : mode === "multiple" ? ((selected as Date[] | undefined) ?? []).some((x) => sameDay(x, d)) : sameDay(range?.from, d) || sameDay(range?.to, d);
const inRange = (d: Date) => !!range?.from && !!range.to && time(d) > time(range.from) && time(d) < time(range.to);
const thisYear = month.getFullYear();
const years = Array.from({ length: (endMonth?.getFullYear() ?? thisYear + 10) - (startMonth?.getFullYear() ?? thisYear - 100) + 1 }, (_, i) => (startMonth?.getFullYear() ?? thisYear - 100) + i);
return (
<div data-slot="calendar" className={cn("relative inline-flex w-fit gap-6 p-3 text-base max-sm:flex-col", className)} style={penStyle(pen)}>
{months.map((m, index) => (
<div key={dayKey(m)} data-slot="calendar-month" className="flex flex-col gap-2">
<div className="relative flex h-10 items-center justify-center">
{index === 0 && (
<Button variant="ghost" size="icon-sm" aria-label="Go to the previous month" disabled={!canPrev} onClick={() => goTo(addMonths(month, -1))} className="absolute left-0" seed={`${seed ?? uid}-prev`}>
<InkGlyph name="chevron-left" className="rtl:-scale-x-100" />
</Button>
)}
{captionLayout === "dropdown" && numberOfMonths === 1 ? (
<div className="flex items-center gap-3">
<NativeSelect size="sm" aria-label="Month" value={m.getMonth()} onChange={(e) => goTo(new Date(m.getFullYear(), Number(e.target.value), 1))} seed={`${seed ?? uid}-month`}>
{Array.from({ length: 12 }, (_, i) => (
<NativeSelectOption key={i} value={i}>
{names.month.format(new Date(2023, i, 1))}
</NativeSelectOption>
))}
</NativeSelect>
<NativeSelect size="sm" aria-label="Year" value={m.getFullYear()} onChange={(e) => goTo(new Date(Number(e.target.value), m.getMonth(), 1))} seed={`${seed ?? uid}-year`}>
{years.map((y) => (
<NativeSelectOption key={y} value={y}>
{y}
</NativeSelectOption>
))}
</NativeSelect>
</div>
) : (
<div role="status" aria-live="polite" className="text-lg font-bold">
{names.caption.format(m)}
</div>
)}
{index === numberOfMonths - 1 && (
<Button variant="ghost" size="icon-sm" aria-label="Go to the next month" disabled={!canNext} onClick={() => goTo(addMonths(month, 1))} className="absolute right-0" seed={`${seed ?? uid}-next`}>
<InkGlyph name="chevron-right" className="rtl:-scale-x-100" />
</Button>
)}
</div>
<table role="grid" aria-label={names.caption.format(m)} className="border-collapse" onKeyDown={onKeyDown}>
<thead>
<tr>
{names.weekdays.map((day) => (
<th key={day.long} scope="col" abbr={day.long} className="size-10 text-sm font-normal text-ink-3">
{day.short}
</th>
))}
</tr>
</thead>
<tbody>
{weeksOf(m, weekStartsOn).map((week) => (
<tr key={dayKey(week[0])}>
{week.map((date) => {
const outside = !sameMonth(date, m);
if (outside && !showOutsideDays) return <td key={dayKey(date)} className="size-10" />;
const off = matches(disabled, date);
const chosen = isSelected(date);
const isToday = sameDay(date, today);
const middle = inRange(date);
const tabbable = sameDay(date, anchor) && !outside;
return (
<td key={dayKey(date)} role="gridcell" aria-selected={chosen || middle || undefined} className="relative size-10 p-0 text-center">
{/* A day outside the month is shown for company; it isn't tabbed to, but can be picked. */}
<button
type="button"
id={`${uid}-${dayKey(date)}`}
data-day={dayKey(date)}
data-selected={chosen ? "" : undefined}
data-today={isToday ? "" : undefined}
data-outside={outside ? "" : undefined}
data-range={middle ? "" : undefined}
aria-label={`${isToday ? "Today, " : ""}${names.label.format(date)}${chosen ? ", selected" : ""}`}
aria-pressed={chosen}
tabIndex={tabbable ? 0 : -1}
disabled={off}
onClick={() => pick(date)}
onFocus={() => setFocused(date)}
className={cn(
"relative isolate flex size-10 cursor-pointer items-center justify-center text-base tabular-nums transition-colors duration-(--dur-hover) outline-none",
"hover:text-ink focus-visible:outline-solid focus-visible:outline-[1.5px] focus-visible:outline-offset-[-2px] focus-visible:outline-ring focus-visible:[border-radius:var(--hand-radius)]",
outside ? "text-ink-3/60" : "text-ink-2",
middle && "text-ink",
chosen && "text-primary-foreground hover:text-primary-foreground",
"disabled:pointer-events-none disabled:opacity-35",
)}
>
{(chosen || isToday || middle) && <DayMark kind={chosen ? "selected" : middle ? "range" : "today"} seed={`${seed ?? uid}-${dayKey(date)}`} draw={pen.draw} roughness={pen.roughness} />}
{date.getDate()}
</button>
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
))}
</div>
);
}
/** What is drawn on a day: a shaded ring for the chosen one, a lighter ring for today, hatching between the ends of a range. */
function DayMark({ kind, seed, draw, roughness }: { kind: "selected" | "today" | "range"; seed: string; draw: Pen["draw"]; roughness: Pen["roughness"] }) {
const s = useInkSeed(seed);
const { ref, w, h, frame } = useInkFrame([40, 40], { pad: 4 });
const d = Math.min(w, h) - 4;
const rough = roughness ?? 1;
const strokes = useMemo(() => {
if (kind === "range") return { wash: hatchStrokes(s, w, h, { gap: 4.4, angle: -50, jitter: 0.4 * rough, inset: 0 }).join("") };
const ring = (n: number, turns: number) => ringStroke(s + n, d, { turns });
return { rings: kind === "selected" ? [ring(0, 1.08), ring(1, 1.14)] : [ring(2, 1.06)] };
}, [kind, s, w, h, d, rough]);
const mode = draw ?? "mount";
return (
<InkSvg ref={ref} {...frame} pending={mode === "auto"} className={cn("-z-10", kind === "selected" ? "text-primary" : "text-ink-3")} style={frame.style}>
{kind === "selected" && <circle cx={w / 2} cy={h / 2} r={d / 2} className="ink-fill" />}
{strokes.wash && <Stroke d={strokes.wash} draw={mode} duration={420} width={0.9} opacity={0.4} />}
{strokes.rings?.map((path, i) => (
<g key={i} transform={`translate(${(w - d) / 2} ${(h - d) / 2})`}>
<Stroke d={path} draw={mode} delay={i * 140} duration={360} width={kind === "selected" ? [1.4, 1][i] : 1.2} opacity={i === 0 ? 1 : 0.7} />
</g>
))}
</InkSvg>
);
}
export { Calendar };Usage
import { Calendar } from "@/components/ui/calendar"
const [date, setDate] = useState<Date | undefined>(new Date())
<Calendar mode="single" selected={date} onSelect={setDate} />Examples
Range
Two months side by side, with the days between the ends hatched.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
"use client";
import { useState } from "react";
import { Calendar, type DateRange } from "@/components/ui/calendar";
export default function CalendarRange() {
const [range, setRange] = useState<DateRange | undefined>({ from: new Date(2026, 9, 8), to: new Date(2026, 9, 15) });
return <Calendar mode="range" numberOfMonths={2} selected={range} onSelect={setRange} defaultMonth={new Date(2026, 9, 1)} seed="cal-range" />;
}Multiple days
Each click adds a day or takes it away.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
3 days picked.
"use client";
import { useState } from "react";
import { Calendar } from "@/components/ui/calendar";
export default function CalendarMultiple() {
const [days, setDays] = useState<Date[] | undefined>([new Date(2026, 9, 5), new Date(2026, 9, 12), new Date(2026, 9, 19)]);
return (
<div className="flex flex-col items-start gap-2">
<Calendar mode="multiple" selected={days} onSelect={setDays} defaultMonth={new Date(2026, 9, 1)} seed="cal-multi" />
<p className="px-3 text-ink-2" aria-live="polite">
{days?.length ? `${days.length} day${days.length === 1 ? "" : "s"} picked.` : "Pick the days you can make."}
</p>
</div>
);
}Disabled days
No weekends and nothing before the 5th; weeks start on Monday and days from other months are left out.
| Mo | Tu | We | Th | Fr | Sa | Su |
|---|---|---|---|---|---|---|
"use client";
import { useState } from "react";
import { Calendar } from "@/components/ui/calendar";
export default function CalendarDisabled() {
const [date, setDate] = useState<Date | undefined>();
return (
<Calendar
mode="single"
selected={date}
onSelect={setDate}
defaultMonth={new Date(2026, 9, 1)}
weekStartsOn={1}
showOutsideDays={false}
// No weekends, and nothing before the 5th.
disabled={[{ dayOfWeek: [0, 6] }, { before: new Date(2026, 9, 5) }]}
seed="cal-disabled"
/>
);
}Month and year dropdowns
For dates far from today, such as a date of birth.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
"use client";
import { useState } from "react";
import { Calendar } from "@/components/ui/calendar";
export default function CalendarDropdown() {
const [date, setDate] = useState<Date | undefined>(new Date(1994, 4, 21));
return <Calendar mode="single" selected={date} onSelect={setDate} captionLayout="dropdown" startMonth={new Date(1940, 0)} endMonth={new Date(2026, 11)} seed="cal-drop" />;
}Another language
Names of months and days come from Intl, so any locale works.
| lu | ma | me | je | ve | sa | di |
|---|---|---|---|---|---|---|
"use client";
import { useState } from "react";
import { Calendar } from "@/components/ui/calendar";
export default function CalendarLocale() {
const [date, setDate] = useState<Date | undefined>(new Date(2026, 9, 17));
return <Calendar mode="single" selected={date} onSelect={setDate} defaultMonth={new Date(2026, 9, 1)} locale="fr-FR" weekStartsOn={1} seed="cal-fr" />;
}API reference
- modedefault
"single" "single" | "multiple" | "range"One day, many, or a start and an end. `selected` and `onSelect` take a Date, a Date[], or { from, to } to match.
- selected / defaultSelected / onSelect
Date | Date[] | DateRangeThe selection, controlled or not. Clicking the chosen day again clears a single selection.
- numberOfMonthsdefault
1 numberMonths shown side by side.
- month / defaultMonth / onMonthChange
DateWhich month is showing.
- startMonth / endMonth
DateThe first and last month it can be taken to.
- disabled
boolean | (date) => boolean | Date | { before, after, from, to, dayOfWeek } | listDays that can't be picked.
- weekStartsOndefault
0 0 | 1 | 2 | 3 | 4 | 5 | 6The first day of the week; 0 is Sunday.
- showOutsideDaysdefault
true booleanShow the days of neighbouring months that share a row.
- captionLayoutdefault
"label" "label" | "dropdown"The month and year in words, or two dropdowns to pick them.
- localedefault
"en-US" stringA BCP 47 tag for the names of months and days.
- seed
string | numberPins the drawing.
Pen settings
The drawing also takes draw, roughness, weight and speed, as props or from the nearest InkProvider. What each one does.