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.json

Install dependencies:

$ pnpm add motion lucide-react calligraph

Add the utility function for class merging:

lib/utils.ts
tsx
import { ClassValue, clsx } from "clsx";import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {  return twMerge(clsx(inputs));}

Add the shared animated label:

components/ui/animated-label.tsx
tsx
"use client";
import { useSyncExternalStore } from "react";import { Calligraph } from "calligraph";import { useReducedMotion } from "motion/react";import { cn } from "@/lib/utils";
// One input-modality subscription shared by every animated label on the page.let keyboardInput = false;const listeners = new Set<() => void>();function notifyKeyboard(event: Event) {  const next = event.type === "keydown";  if (next === keyboardInput) return;  keyboardInput = next;  listeners.forEach((notify) => notify());}function subscribe(notify: () => void) {  if (listeners.size === 0) {    window.addEventListener("keydown", notifyKeyboard, true);    window.addEventListener("pointerdown", notifyKeyboard, true);  }  listeners.add(notify);  return () => {    listeners.delete(notify);    if (listeners.size === 0) {      window.removeEventListener("keydown", notifyKeyboard, true);      window.removeEventListener("pointerdown", notifyKeyboard, true);    }  };}const getSnapshot = () => keyboardInput;const getServerSnapshot = () => false;
export function useKeyboardInput() {  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);}
/** A stable accessible label with decorative character morphing. */export function AnimatedLabel({  children,  className,  variant = "text",  autoSize = true,}: {  children: string | number;  className?: string;  variant?: "text" | "number";  autoSize?: boolean;}) {  const reduce = useReducedMotion();  const keyboard = useKeyboardInput();  return (    <span className={cn("inline-flex items-center", className)}>      <span className="sr-only">{children}</span>      <span aria-hidden="true" className="inline-flex">        {reduce || keyboard ? (          <span>{children}</span>        ) : (          <Calligraph            variant={variant}            animation="smooth"            initial={false}            autoSize={autoSize}            drift={{ x: 0, y: 2 }}            stagger={0}          >            {children}          </Calligraph>        )}      </span>    </span>  );}

Copy the component code into your project:

components/ui/calendar-month.tsx
tsx
"use client";
import React, { useEffect, useId, useMemo, useRef, useState } from "react";import {  AnimatePresence,  motion,  useReducedMotion,  type PanInfo,} from "motion/react";import { ChevronLeft, ChevronRight } from "lucide-react";import {  AnimatedLabel,  useKeyboardInput,} from "@/components/ui/animated-label";import { cn } from "@/lib/utils";
export type CalendarMonthProps = {  value?: Date;  defaultValue?: Date;  onChange?: (date: Date) => void;  min?: Date;  max?: Date;  /** 0 = Sunday (default), 1 = Monday. */  weekStartsOn?: 0 | 1;  /** Show the trailing/leading days of neighbouring months. */  showOutsideDays?: boolean;  className?: string;};
const SPRING = { type: "spring" as const, bounce: 0, duration: 0.28 };const EASE_OUT = [0.23, 1, 0.32, 1] as const;const DAY_NAMES = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
function startOfDay(d: Date) {  return new Date(d.getFullYear(), d.getMonth(), d.getDate());}
function addDays(d: Date, n: number) {  return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);}
/** Same day-of-month in another month, clamped (Jan 31 → Feb 28). */function addMonths(d: Date, n: number) {  const target = new Date(d.getFullYear(), d.getMonth() + n, 1);  const last = new Date(    target.getFullYear(),    target.getMonth() + 1,    0,  ).getDate();  return new Date(    target.getFullYear(),    target.getMonth(),    Math.min(d.getDate(), last),  );}
function sameDay(a?: Date | null, b?: Date | null) {  return (    !!a &&    !!b &&    a.getFullYear() === b.getFullYear() &&    a.getMonth() === b.getMonth() &&    a.getDate() === b.getDate()  );}
function monthKey(d: Date) {  return d.getFullYear() * 12 + d.getMonth();}
function dayKey(d: Date) {  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;}
/** Always six weeks, so the card never changes height between months. */function buildWeeks(year: number, month: number, weekStartsOn: 0 | 1) {  const first = new Date(year, month, 1);  const offset = (first.getDay() - weekStartsOn + 7) % 7;  const start = addDays(first, -offset);  return Array.from({ length: 6 }, (_, w) =>    Array.from({ length: 7 }, (_, d) => addDays(start, w * 7 + d)),  );}
export function CalendarMonth({  value: valueProp,  defaultValue,  onChange,  min,  max,  weekStartsOn = 0,  showOutsideDays = true,  className,}: CalendarMonthProps) {  const reducedMotion = useReducedMotion();  const keyboard = useKeyboardInput();  const reduce = !!reducedMotion || keyboard;  const uid = useId();  const labelId = `${uid}-label`;
  const isControlled = valueProp !== undefined;  const [uncontrolled, setUncontrolled] = useState(    defaultValue ? startOfDay(defaultValue) : undefined,  );  const selected = isControlled    ? valueProp      ? startOfDay(valueProp)      : undefined    : uncontrolled;
  const [today, setToday] = useState(() => startOfDay(new Date()));  // Refresh "today" after hydration so a server-rendered date can't go stale.  useEffect(() => setToday(startOfDay(new Date())), []);
  const minD = min ? startOfDay(min) : null;  const maxD = max ? startOfDay(max) : null;  const clamp = (d: Date) => {    if (minD && d < minD) return minD;    if (maxD && d > maxD) return maxD;    return d;  };  const isDisabled = (d: Date) => (!!minD && d < minD) || (!!maxD && d > maxD);
  const [view, setView] = useState(() => {    const d = selected ?? today;    return new Date(d.getFullYear(), d.getMonth(), 1);  });  const [direction, setDirection] = useState<1 | -1>(1);  // The roving tab stop: one day in the grid is tabbable at a time.  const [focusDay, setFocusDay] = useState<Date>(() => selected ?? today);  const moveFocus = useRef(false);  const gridRef = useRef<HTMLDivElement>(null);
  // Follow external value changes to another month.  const selectedKey = selected ? dayKey(selected) : "";  useEffect(() => {    if (!selected) return;    setFocusDay(selected);    if (monthKey(selected) !== monthKey(view)) {      setDirection(monthKey(selected) > monthKey(view) ? 1 : -1);      setView(new Date(selected.getFullYear(), selected.getMonth(), 1));    }    // eslint-disable-next-line react-hooks/exhaustive-deps  }, [selectedKey]);
  const goToMonth = (target: Date) => {    const next = new Date(target.getFullYear(), target.getMonth(), 1);    if (monthKey(next) === monthKey(view)) return;    setDirection(monthKey(next) > monthKey(view) ? 1 : -1);    setView(next);  };
  const canPrev = !minD || monthKey(minD) < monthKey(view);  const canNext = !maxD || monthKey(maxD) > monthKey(view);
  const shift = (n: -1 | 1) => {    if ((n < 0 && !canPrev) || (n > 0 && !canNext)) return;    goToMonth(new Date(view.getFullYear(), view.getMonth() + n, 1));    setFocusDay((d) => clamp(addMonths(d, n)));  };
  const select = (d: Date) => {    if (isDisabled(d)) return;    const next = startOfDay(d);    if (!isControlled) setUncontrolled(next);    onChange?.(next);    setFocusDay(next);    goToMonth(next);  };
  const jumpToday = () => {    const t = clamp(today);    goToMonth(t);    setFocusDay(t);  };
  const onGridKeyDown = (e: React.KeyboardEvent) => {    let next: Date | null = null;    const d = focusDay;    const dow = (d.getDay() - weekStartsOn + 7) % 7;    switch (e.key) {      case "ArrowLeft":        next = addDays(d, -1);        break;      case "ArrowRight":        next = addDays(d, 1);        break;      case "ArrowUp":        next = addDays(d, -7);        break;      case "ArrowDown":        next = addDays(d, 7);        break;      case "Home":        next = addDays(d, -dow);        break;      case "End":        next = addDays(d, 6 - dow);        break;      case "PageUp":        next = addMonths(d, e.shiftKey ? -12 : -1);        break;      case "PageDown":        next = addMonths(d, e.shiftKey ? 12 : 1);        break;      case "Enter":      case " ":        e.preventDefault();        select(d);        return;      default:        return;    }    e.preventDefault();    next = clamp(next);    moveFocus.current = true;    setFocusDay(next);    goToMonth(next);  };
  // After a keyboard move (possibly into a newly mounted month), focus the day.  useEffect(() => {    if (!moveFocus.current) return;    moveFocus.current = false;    gridRef.current      ?.querySelector<HTMLButtonElement>(`[data-day="${dayKey(focusDay)}"]`)      ?.focus({ preventScroll: true });  }, [focusDay, view]);
  // Horizontal swipe on touch pages months.  const onPanEnd = (_: unknown, info: PanInfo) => {    if (      Math.abs(info.offset.x) < 40 ||      Math.abs(info.offset.x) < Math.abs(info.offset.y)    )      return;    shift(info.offset.x < 0 ? 1 : -1);  };
  const weeks = useMemo(    () => buildWeeks(view.getFullYear(), view.getMonth(), weekStartsOn),    [view, weekStartsOn],  );  const dayNames =    weekStartsOn === 1 ? [...DAY_NAMES.slice(1), DAY_NAMES[0]] : DAY_NAMES;
  const label = view.toLocaleString("en-US", { month: "long" });  const year = view.getFullYear();  const showingToday = monthKey(view) === monthKey(today);  const viewKey = monthKey(view);
  const slide = {    enter: (dir: number) =>      reduce        ? { opacity: 0 }        : { x: `${dir * 28}%`, opacity: 0, filter: "blur(2px)" },    center: { x: "0%", opacity: 1, filter: "blur(0px)" },    exit: (dir: number) =>      reduce        ? { opacity: 0 }        : { x: `${dir * -28}%`, opacity: 0, filter: "blur(2px)" },  };
  return (    <div      className={cn(        "w-full max-w-[20rem] rounded-[20px] border border-(--color-rule) bg-(--color-paper) p-3",        "shadow-[0_1px_2px_rgba(0,0,0,0.04),0_8px_24px_rgba(0,0,0,0.05)] dark:shadow-none",        className,      )}    >      {/* Header */}      <div className="mb-2 flex items-center gap-1 pl-2">        <div          id={labelId}          aria-live="polite"          className="relative h-6 min-w-0 flex-1 overflow-hidden text-[15px] font-semibold tracking-[-0.01em] text-(--color-ink)"        >          <span className="inline-flex h-full items-center gap-1.5 whitespace-nowrap">            <AnimatedLabel>{label}</AnimatedLabel>            <AnimatedLabel              variant="number"              className="font-normal text-(--color-neutral) tabular-nums"            >              {year}            </AnimatedLabel>          </span>        </div>
        <AnimatePresence initial={false}>          {!showingToday && (            <motion.button              type="button"              onClick={jumpToday}              initial={{ opacity: 0, scale: 0.9 }}              animate={{ opacity: 1, scale: 1 }}              exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.12 } }}              transition={{ duration: 0.18, ease: EASE_OUT }}              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)"            >              Today            </motion.button>          )}        </AnimatePresence>
        <NavButton          label="Previous month"          disabled={!canPrev}          onClick={() => shift(-1)}          reduce={reduce}        >          <ChevronLeft className="size-4" strokeWidth={1.75} aria-hidden />        </NavButton>        <NavButton          label="Next month"          disabled={!canNext}          onClick={() => shift(1)}          reduce={reduce}        >          <ChevronRight className="size-4" strokeWidth={1.75} aria-hidden />        </NavButton>      </div>
      <div role="grid" aria-labelledby={labelId} onKeyDown={onGridKeyDown}>        <div role="row" className="grid grid-cols-7">          {dayNames.map((d) => (            <div              key={d}              role="columnheader"              aria-label={d}              className="grid h-8 place-items-center text-[11px] font-medium text-(--color-neutral)"            >              {d}            </div>          ))}        </div>
        <motion.div          ref={gridRef}          onPanEnd={onPanEnd}          className="relative touch-pan-y overflow-hidden"        >          <AnimatePresence initial={false} custom={direction} mode="popLayout">            <motion.div              key={viewKey}              custom={direction}              variants={slide}              initial="enter"              animate="center"              exit="exit"              transition={{ duration: keyboard ? 0 : 0.28, ease: EASE_OUT }}              role="rowgroup"            >              {weeks.map((week, w) => (                <div key={w} role="row" className="grid grid-cols-7">                  {week.map((d) => {                    const outside = d.getMonth() !== view.getMonth();                    const isSelected = sameDay(d, selected);                    const isToday = sameDay(d, today);                    const disabled = isDisabled(d);                    const tabbable = sameDay(d, focusDay) && !outside;                    if (outside && !showOutsideDays) {                      return (                        <div key={dayKey(d)} role="gridcell" className="h-10" />                      );                    }                    return (                      <div                        key={dayKey(d)}                        role="gridcell"                        aria-selected={isSelected}                        className="grid h-10 place-items-center"                      >                        <button                          type="button"                          data-day={dayKey(d)}                          tabIndex={tabbable ? 0 : -1}                          disabled={disabled}                          aria-label={d.toLocaleDateString("en-US", {                            weekday: "long",                            month: "long",                            day: "numeric",                            year: "numeric",                          })}                          aria-current={isToday ? "date" : undefined}                          onClick={() => select(d)}                          onFocus={() => setFocusDay(d)}                          className={cn(                            "group relative grid size-9 place-items-center rounded-full text-[13px] tabular-nums outline-none",                            "transition-[color,background-color,transform] duration-150 ease-out active:scale-[0.94]",                            "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-1 focus-visible:ring-offset-(--color-paper)",                            isSelected                              ? "font-semibold text-(--color-paper)"                              : outside                                ? "text-(--color-neutral)/45 hover:bg-(--color-paper-2) hover:text-(--color-ink-2)"                                : "text-(--color-ink) hover:bg-(--color-paper-2)",                            isToday && !isSelected && "font-semibold",                            disabled &&                              "pointer-events-none text-(--color-neutral)/35",                          )}                        >                          {isSelected && (                            <motion.span                              layoutId={`${uid}-selected`}                              transition={reduce ? { duration: 0 } : SPRING}                              className="absolute inset-0 rounded-full bg-(--color-ink)"                            />                          )}                          {isToday && !isSelected && (                            <span className="absolute inset-0 rounded-full ring-1 ring-(--color-ink)/25 ring-inset" />                          )}                          <span className="relative">{d.getDate()}</span>                        </button>                      </div>                    );                  })}                </div>              ))}            </motion.div>          </AnimatePresence>        </motion.div>      </div>    </div>  );}
function NavButton({  label,  disabled,  onClick,  reduce,  children,}: {  label: string;  disabled: boolean;  onClick: () => void;  reduce: boolean | null;  children: React.ReactNode;}) {  return (    <motion.button      type="button"      aria-label={label}      disabled={disabled}      whileTap={reduce || disabled ? undefined : { scale: 0.92 }}      onClick={onClick}      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"    >      {children}    </motion.button>  );}

Adjust import paths according to your folder structure.


Basic Usage

tsx
import { CalendarMonth } from "@/components/ui/calendar-month";
<CalendarMonth value={date} onChange={setDate} min={today} />;

Props

PropTypeRequiredDefaultDescription
valueDateNo—Controlled selected day.
onChange(date: Date) => voidNo—Fires when a day is picked.
defaultValueDateNo—Uncontrolled initial day.
weekStartsOn0 | 1No0First column: 0 for Sunday, 1 for Monday.
showOutsideDaysbooleanNotrueShow and allow picking days from the neighbouring months.
minDateNo—Disable days before this date.
maxDateNo—Disable days after this date.

Best Practices

  1. Normalize to start-of-day before comparing with your data layer.
  2. Pair with a text field for typed dates; this is the visual pick surface.
  3. Don’t animate month changes under reduced motion — opacity only.
  4. Keep the grid a fixed six rows so surrounding layout never shifts.
  5. Use one roving tab stop for the days, not one per day.