Overview
A month picker that behaves like a real grid. It is always six weeks tall, so the card never jumps between months, and neighbouring days are shown and clickable. One day is the tab stop: arrows move by day and week, Home/End go to the week's edges, PageUp/PageDown change month (Shift for year), and focus follows into the next month. Calligraph morphs the month and year heading while the grid slides in the direction you travel, the selection glides between days, a Today button appears when you wander off, and min/max disable days and stop paging. Swipe horizontally on touch.
Installation
Use the CLI to install the component automatically:
$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/calendar-month.jsonInstall dependencies:
$ pnpm add motion lucide-react calligraphAdd the utility function for class merging:
lib/utils.ts
tsx
1import { ClassValue, clsx } from "clsx";2import { twMerge } from "tailwind-merge";3 4export function cn(...inputs: ClassValue[]) {5 return twMerge(clsx(inputs));6}
Add the shared animated label:
tsx
1"use client";2 3import { useSyncExternalStore } from "react";4import { Calligraph } from "calligraph";5import { useReducedMotion } from "motion/react";6import { cn } from "@/lib/utils";7 8// One input-modality subscription shared by every animated label on the page.9let keyboardInput = false;10const listeners = new Set<() => void>();11function notifyKeyboard(event: Event) {12 const next = event.type === "keydown";13 if (next === keyboardInput) return;14 keyboardInput = next;15 listeners.forEach((notify) => notify());16}17function subscribe(notify: () => void) {18 if (listeners.size === 0) {19 window.addEventListener("keydown", notifyKeyboard, true);20 window.addEventListener("pointerdown", notifyKeyboard, true);21 }22 listeners.add(notify);23 return () => {24 listeners.delete(notify);25 if (listeners.size === 0) {26 window.removeEventListener("keydown", notifyKeyboard, true);27 window.removeEventListener("pointerdown", notifyKeyboard, true);28 }29 };30}31const getSnapshot = () => keyboardInput;32const getServerSnapshot = () => false;33 34export function useKeyboardInput() {35 return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);36}37 38/** A stable accessible label with decorative character morphing. */39export function AnimatedLabel({40 children,41 className,42 variant = "text",43 autoSize = true,44}: {45 children: string | number;46 className?: string;47 variant?: "text" | "number";48 autoSize?: boolean;49}) {50 const reduce = useReducedMotion();51 const keyboard = useKeyboardInput();52 return (53 <span className={cn("inline-flex items-center", className)}>54 <span className="sr-only">{children}</span>55 <span aria-hidden="true" className="inline-flex">56 {reduce || keyboard ? (57 <span>{children}</span>58 ) : (59 <Calligraph60 variant={variant}61 animation="smooth"62 initial={false}63 autoSize={autoSize}64 drift={{ x: 0, y: 2 }}65 stagger={0}66 >67 {children}68 </Calligraph>69 )}70 </span>71 </span>72 );73}
Copy the component code into your project:
tsx
1"use client";2 3import React, { useEffect, useId, useMemo, useRef, useState } from "react";4import {5 AnimatePresence,6 motion,7 useReducedMotion,8 type PanInfo,9} from "motion/react";10import { ChevronLeft, ChevronRight } from "lucide-react";11import {12 AnimatedLabel,13 useKeyboardInput,14} from "@/components/ui/animated-label";15import { cn } from "@/lib/utils";16 17export type CalendarMonthProps = {18 value?: Date;19 defaultValue?: Date;20 onChange?: (date: Date) => void;21 min?: Date;22 max?: Date;23 /** 0 = Sunday (default), 1 = Monday. */24 weekStartsOn?: 0 | 1;25 /** Show the trailing/leading days of neighbouring months. */26 showOutsideDays?: boolean;27 className?: string;28};29 30const SPRING = { type: "spring" as const, bounce: 0, duration: 0.28 };31const EASE_OUT = [0.23, 1, 0.32, 1] as const;32const DAY_NAMES = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];33 34function startOfDay(d: Date) {35 return new Date(d.getFullYear(), d.getMonth(), d.getDate());36}37 38function addDays(d: Date, n: number) {39 return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);40}41 42/** Same day-of-month in another month, clamped (Jan 31 → Feb 28). */43function addMonths(d: Date, n: number) {44 const target = new Date(d.getFullYear(), d.getMonth() + n, 1);45 const last = new Date(46 target.getFullYear(),47 target.getMonth() + 1,48 0,49 ).getDate();50 return new Date(51 target.getFullYear(),52 target.getMonth(),53 Math.min(d.getDate(), last),54 );55}56 57function sameDay(a?: Date | null, b?: Date | null) {58 return (59 !!a &&60 !!b &&61 a.getFullYear() === b.getFullYear() &&62 a.getMonth() === b.getMonth() &&63 a.getDate() === b.getDate()64 );65}66 67function monthKey(d: Date) {68 return d.getFullYear() * 12 + d.getMonth();69}70 71function dayKey(d: Date) {72 return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;73}74 75/** Always six weeks, so the card never changes height between months. */76function buildWeeks(year: number, month: number, weekStartsOn: 0 | 1) {77 const first = new Date(year, month, 1);78 const offset = (first.getDay() - weekStartsOn + 7) % 7;79 const start = addDays(first, -offset);80 return Array.from({ length: 6 }, (_, w) =>81 Array.from({ length: 7 }, (_, d) => addDays(start, w * 7 + d)),82 );83}84 85export function CalendarMonth({86 value: valueProp,87 defaultValue,88 onChange,89 min,90 max,91 weekStartsOn = 0,92 showOutsideDays = true,93 className,94}: CalendarMonthProps) {95 const reducedMotion = useReducedMotion();96 const keyboard = useKeyboardInput();97 const reduce = !!reducedMotion || keyboard;98 const uid = useId();99 const labelId = `${uid}-label`;100 101 const isControlled = valueProp !== undefined;102 const [uncontrolled, setUncontrolled] = useState(103 defaultValue ? startOfDay(defaultValue) : undefined,104 );105 const selected = isControlled106 ? valueProp107 ? startOfDay(valueProp)108 : undefined109 : uncontrolled;110 111 const [today, setToday] = useState(() => startOfDay(new Date()));112 // Refresh "today" after hydration so a server-rendered date can't go stale.113 useEffect(() => setToday(startOfDay(new Date())), []);114 115 const minD = min ? startOfDay(min) : null;116 const maxD = max ? startOfDay(max) : null;117 const clamp = (d: Date) => {118 if (minD && d < minD) return minD;119 if (maxD && d > maxD) return maxD;120 return d;121 };122 const isDisabled = (d: Date) => (!!minD && d < minD) || (!!maxD && d > maxD);123 124 const [view, setView] = useState(() => {125 const d = selected ?? today;126 return new Date(d.getFullYear(), d.getMonth(), 1);127 });128 const [direction, setDirection] = useState<1 | -1>(1);129 // The roving tab stop: one day in the grid is tabbable at a time.130 const [focusDay, setFocusDay] = useState<Date>(() => selected ?? today);131 const moveFocus = useRef(false);132 const gridRef = useRef<HTMLDivElement>(null);133 134 // Follow external value changes to another month.135 const selectedKey = selected ? dayKey(selected) : "";136 useEffect(() => {137 if (!selected) return;138 setFocusDay(selected);139 if (monthKey(selected) !== monthKey(view)) {140 setDirection(monthKey(selected) > monthKey(view) ? 1 : -1);141 setView(new Date(selected.getFullYear(), selected.getMonth(), 1));142 }143 // eslint-disable-next-line react-hooks/exhaustive-deps144 }, [selectedKey]);145 146 const goToMonth = (target: Date) => {147 const next = new Date(target.getFullYear(), target.getMonth(), 1);148 if (monthKey(next) === monthKey(view)) return;149 setDirection(monthKey(next) > monthKey(view) ? 1 : -1);150 setView(next);151 };152 153 const canPrev = !minD || monthKey(minD) < monthKey(view);154 const canNext = !maxD || monthKey(maxD) > monthKey(view);155 156 const shift = (n: -1 | 1) => {157 if ((n < 0 && !canPrev) || (n > 0 && !canNext)) return;158 goToMonth(new Date(view.getFullYear(), view.getMonth() + n, 1));159 setFocusDay((d) => clamp(addMonths(d, n)));160 };161 162 const select = (d: Date) => {163 if (isDisabled(d)) return;164 const next = startOfDay(d);165 if (!isControlled) setUncontrolled(next);166 onChange?.(next);167 setFocusDay(next);168 goToMonth(next);169 };170 171 const jumpToday = () => {172 const t = clamp(today);173 goToMonth(t);174 setFocusDay(t);175 };176 177 const onGridKeyDown = (e: React.KeyboardEvent) => {178 let next: Date | null = null;179 const d = focusDay;180 const dow = (d.getDay() - weekStartsOn + 7) % 7;181 switch (e.key) {182 case "ArrowLeft":183 next = addDays(d, -1);184 break;185 case "ArrowRight":186 next = addDays(d, 1);187 break;188 case "ArrowUp":189 next = addDays(d, -7);190 break;191 case "ArrowDown":192 next = addDays(d, 7);193 break;194 case "Home":195 next = addDays(d, -dow);196 break;197 case "End":198 next = addDays(d, 6 - dow);199 break;200 case "PageUp":201 next = addMonths(d, e.shiftKey ? -12 : -1);202 break;203 case "PageDown":204 next = addMonths(d, e.shiftKey ? 12 : 1);205 break;206 case "Enter":207 case " ":208 e.preventDefault();209 select(d);210 return;211 default:212 return;213 }214 e.preventDefault();215 next = clamp(next);216 moveFocus.current = true;217 setFocusDay(next);218 goToMonth(next);219 };220 221 // After a keyboard move (possibly into a newly mounted month), focus the day.222 useEffect(() => {223 if (!moveFocus.current) return;224 moveFocus.current = false;225 gridRef.current226 ?.querySelector<HTMLButtonElement>(`[data-day="${dayKey(focusDay)}"]`)227 ?.focus({ preventScroll: true });228 }, [focusDay, view]);229 230 // Horizontal swipe on touch pages months.231 const onPanEnd = (_: unknown, info: PanInfo) => {232 if (233 Math.abs(info.offset.x) < 40 ||234 Math.abs(info.offset.x) < Math.abs(info.offset.y)235 )236 return;237 shift(info.offset.x < 0 ? 1 : -1);238 };239 240 const weeks = useMemo(241 () => buildWeeks(view.getFullYear(), view.getMonth(), weekStartsOn),242 [view, weekStartsOn],243 );244 const dayNames =245 weekStartsOn === 1 ? [...DAY_NAMES.slice(1), DAY_NAMES[0]] : DAY_NAMES;246 247 const label = view.toLocaleString("en-US", { month: "long" });248 const year = view.getFullYear();249 const showingToday = monthKey(view) === monthKey(today);250 const viewKey = monthKey(view);251 252 const slide = {253 enter: (dir: number) =>254 reduce255 ? { opacity: 0 }256 : { x: `${dir * 28}%`, opacity: 0, filter: "blur(2px)" },257 center: { x: "0%", opacity: 1, filter: "blur(0px)" },258 exit: (dir: number) =>259 reduce260 ? { opacity: 0 }261 : { x: `${dir * -28}%`, opacity: 0, filter: "blur(2px)" },262 };263 264 return (265 <div266 className={cn(267 "w-full max-w-[20rem] rounded-[20px] border border-(--color-rule) bg-(--color-paper) p-3",268 "shadow-[0_1px_2px_rgba(0,0,0,0.04),0_8px_24px_rgba(0,0,0,0.05)] dark:shadow-none",269 className,270 )}271 >272 {/* Header */}273 <div className="mb-2 flex items-center gap-1 pl-2">274 <div275 id={labelId}276 aria-live="polite"277 className="relative h-6 min-w-0 flex-1 overflow-hidden text-[15px] font-semibold tracking-[-0.01em] text-(--color-ink)"278 >279 <span className="inline-flex h-full items-center gap-1.5 whitespace-nowrap">280 <AnimatedLabel>{label}</AnimatedLabel>281 <AnimatedLabel282 variant="number"283 className="font-normal text-(--color-neutral) tabular-nums"284 >285 {year}286 </AnimatedLabel>287 </span>288 </div>289 290 <AnimatePresence initial={false}>291 {!showingToday && (292 <motion.button293 type="button"294 onClick={jumpToday}295 initial={{ opacity: 0, scale: 0.9 }}296 animate={{ opacity: 1, scale: 1 }}297 exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.12 } }}298 transition={{ duration: 0.18, ease: EASE_OUT }}299 className="mr-1 h-7 rounded-full border border-(--color-rule) px-2.5 text-[12px] font-medium text-(--color-ink-2) outline-none hover:bg-(--color-paper-2) hover:text-(--color-ink) focus-visible:ring-2 focus-visible:ring-(--color-focus)"300 >301 Today302 </motion.button>303 )}304 </AnimatePresence>305 306 <NavButton307 label="Previous month"308 disabled={!canPrev}309 onClick={() => shift(-1)}310 reduce={reduce}311 >312 <ChevronLeft className="size-4" strokeWidth={1.75} aria-hidden />313 </NavButton>314 <NavButton315 label="Next month"316 disabled={!canNext}317 onClick={() => shift(1)}318 reduce={reduce}319 >320 <ChevronRight className="size-4" strokeWidth={1.75} aria-hidden />321 </NavButton>322 </div>323 324 <div role="grid" aria-labelledby={labelId} onKeyDown={onGridKeyDown}>325 <div role="row" className="grid grid-cols-7">326 {dayNames.map((d) => (327 <div328 key={d}329 role="columnheader"330 aria-label={d}331 className="grid h-8 place-items-center text-[11px] font-medium text-(--color-neutral)"332 >333 {d}334 </div>335 ))}336 </div>337 338 <motion.div339 ref={gridRef}340 onPanEnd={onPanEnd}341 className="relative touch-pan-y overflow-hidden"342 >343 <AnimatePresence initial={false} custom={direction} mode="popLayout">344 <motion.div345 key={viewKey}346 custom={direction}347 variants={slide}348 initial="enter"349 animate="center"350 exit="exit"351 transition={{ duration: keyboard ? 0 : 0.28, ease: EASE_OUT }}352 role="rowgroup"353 >354 {weeks.map((week, w) => (355 <div key={w} role="row" className="grid grid-cols-7">356 {week.map((d) => {357 const outside = d.getMonth() !== view.getMonth();358 const isSelected = sameDay(d, selected);359 const isToday = sameDay(d, today);360 const disabled = isDisabled(d);361 const tabbable = sameDay(d, focusDay) && !outside;362 if (outside && !showOutsideDays) {363 return (364 <div key={dayKey(d)} role="gridcell" className="h-10" />365 );366 }367 return (368 <div369 key={dayKey(d)}370 role="gridcell"371 aria-selected={isSelected}372 className="grid h-10 place-items-center"373 >374 <button375 type="button"376 data-day={dayKey(d)}377 tabIndex={tabbable ? 0 : -1}378 disabled={disabled}379 aria-label={d.toLocaleDateString("en-US", {380 weekday: "long",381 month: "long",382 day: "numeric",383 year: "numeric",384 })}385 aria-current={isToday ? "date" : undefined}386 onClick={() => select(d)}387 onFocus={() => setFocusDay(d)}388 className={cn(389 "group relative grid size-9 place-items-center rounded-full text-[13px] tabular-nums outline-none",390 "transition-[color,background-color,transform] duration-150 ease-out active:scale-[0.94]",391 "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-1 focus-visible:ring-offset-(--color-paper)",392 isSelected393 ? "font-semibold text-(--color-paper)"394 : outside395 ? "text-(--color-neutral)/45 hover:bg-(--color-paper-2) hover:text-(--color-ink-2)"396 : "text-(--color-ink) hover:bg-(--color-paper-2)",397 isToday && !isSelected && "font-semibold",398 disabled &&399 "pointer-events-none text-(--color-neutral)/35",400 )}401 >402 {isSelected && (403 <motion.span404 layoutId={`${uid}-selected`}405 transition={reduce ? { duration: 0 } : SPRING}406 className="absolute inset-0 rounded-full bg-(--color-ink)"407 />408 )}409 {isToday && !isSelected && (410 <span className="absolute inset-0 rounded-full ring-1 ring-(--color-ink)/25 ring-inset" />411 )}412 <span className="relative">{d.getDate()}</span>413 </button>414 </div>415 );416 })}417 </div>418 ))}419 </motion.div>420 </AnimatePresence>421 </motion.div>422 </div>423 </div>424 );425}426 427function NavButton({428 label,429 disabled,430 onClick,431 reduce,432 children,433}: {434 label: string;435 disabled: boolean;436 onClick: () => void;437 reduce: boolean | null;438 children: React.ReactNode;439}) {440 return (441 <motion.button442 type="button"443 aria-label={label}444 disabled={disabled}445 whileTap={reduce || disabled ? undefined : { scale: 0.92 }}446 onClick={onClick}447 className="grid size-8 place-items-center rounded-full text-(--color-ink-2) outline-none hover:bg-(--color-paper-2) hover:text-(--color-ink) focus-visible:ring-2 focus-visible:ring-(--color-focus) disabled:opacity-30 disabled:hover:bg-transparent"448 >449 {children}450 </motion.button>451 );452}
Adjust import paths according to your folder structure.
Basic Usage
tsx
1import { CalendarMonth } from "@/components/ui/calendar-month";2 3<CalendarMonth value={date} onChange={setDate} min={today} />;
Props
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| value | Date | No | — | Controlled selected day. |
| onChange | (date: Date) => void | No | — | Fires when a day is picked. |
| defaultValue | Date | No | — | Uncontrolled initial day. |
| weekStartsOn | 0 | 1 | No | 0 | First column: 0 for Sunday, 1 for Monday. |
| showOutsideDays | boolean | No | true | Show and allow picking days from the neighbouring months. |
| min | Date | No | — | Disable days before this date. |
| max | Date | No | — | Disable days after this date. |
Best Practices
- Normalize to start-of-day before comparing with your data layer.
- Pair with a text field for typed dates; this is the visual pick surface.
- Don’t animate month changes under reduced motion — opacity only.
- Keep the grid a fixed six rows so surrounding layout never shifts.
- Use one roving tab stop for the days, not one per day.