Skip to content
Shaken UI
Sign in

Calendar

Save

A month grid with single and range selection, full keyboard navigation, disabled dates, and a today marker, with Intl labels and no date library.

Category
Data display
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Calendar preview

November 2026

Su
Mo
Tu
We
Th
Fr
Sa

Deploy on Nov 18

November 2026

Su
Mo
Tu
We
Th
Fr
Sa

Logs from Nov 13 to Nov 19

Installation

npx @shakenui/cli add calendar

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add calendar --dry-run

Usage

calendar-example.tsx
"use client";

import { useState } from "react";
import { addDays, Calendar, type DateRange, startOfDay } from "@/components/shaken/ui/calendar";

export default function CalendarExample() {
  const today = startOfDay(new Date());
  const [date, setDate] = useState<Date | null>(addDays(today, 2));
  const [range, setRange] = useState<DateRange>({ from: addDays(today, -3), to: addDays(today, 3) });
  // Weekends are closed for scheduled deploys.
  const weekend = (day: Date) => day.getDay() === 0 || day.getDay() === 6;
  const format = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric" });

  return (
    <div className="flex flex-wrap items-start justify-center gap-6">
      <div className="grid gap-2 rounded-xl border border-zinc-950/10 p-3 dark:border-white/10">
        <Calendar value={date} onValueChange={setDate} disabled={weekend} />
        <p className="px-1 text-xs text-zinc-500">{date ? `Deploy on ${format.format(date)}` : "Pick a weekday to deploy"}</p>
      </div>
      <div className="grid gap-2 rounded-xl border border-zinc-950/10 p-3 dark:border-white/10">
        <Calendar mode="range" value={range} onValueChange={setRange} />
        <p className="px-1 text-xs text-zinc-500">
          {range.from && range.to ? `Logs from ${format.format(range.from)} to ${format.format(range.to)}` : "Pick an end date"}
        </p>
      </div>
    </div>
  );
}

API

PropTypeDefaultDescription
mode"single" | "range""single"Pick one day, or a from and to range.
value / defaultValue / onValueChangeDate | null, or { from, to }—Selection, controlled or not.
month / defaultMonth / onMonthChangeDate—The month on screen.
disabled(date) => boolean | Date[]—Days that cannot be picked. They stay focusable so arrow keys pass over them.
minDate / maxDateDate—Pickable bounds; navigation stops at their months.
weekStartsOn0 to 6—First column. Defaults to the locale's first day from Intl.Locale week info.
localestring—BCP 47 locale for month and weekday names.
numberOfMonths1 | 21Months side by side.
showOutsideDaysboolean—Shows neighbouring months' days, dimmed. On for one month.
todayDate—Overrides today, for example to match a server clock.
autoFocusbooleanfalseFocuses the selected day or today on mount.

Accessibility

  • Each month is a grid named by its month heading; days are buttons with full spoken dates ("Friday, November 14, 2026") and today carries aria-current="date".
  • One roving tab stop: arrows move by day and week, Home and End to the week's edges, Page Up and Page Down by month, with Shift by year; focus follows into the next month.
  • Disabled days use aria-disabled, are struck through as well as dimmed, and remain reachable by arrow keys.
  • Selected days set aria-selected on their grid cells; a range never spans a disabled day.
  • Clicking the month arrows cross-fades the grid in 150ms; keyboard paging switches instantly, and reduced motion removes the fade.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/calendar.tsxcalendar
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/calendar/0.1.0.json.

ui/calendar.tsxShow
ui/calendar.tsx
"use client";

import { type KeyboardEvent, type ReactNode, useEffect, useMemo, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

// Date helpers. Every date is a local calendar day at midnight; no date library involved.

/** The same calendar day at 00:00 local time. */
export function startOfDay(date: Date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

export function addDays(date: Date, days: number) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
}

/** Moves by whole months, clamping the day so Jan 31 plus one month is the last day of February. */
export function addMonths(date: Date, months: number) {
  const target = new Date(date.getFullYear(), date.getMonth() + months, 1);
  const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
  return new Date(target.getFullYear(), target.getMonth(), Math.min(date.getDate(), last));
}

export function isSameDay(a: Date | null | undefined, b: Date | null | undefined) {
  return !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

function startOfMonth(date: Date) {
  return new Date(date.getFullYear(), date.getMonth(), 1);
}

function isSameMonth(a: Date, b: Date) {
  return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth();
}

function dayKey(date: Date) {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

/** The number of days from `from` to `to`, counting both ends. */
export function countDays(from: Date, to: Date) {
  return Math.round((startOfDay(to).getTime() - startOfDay(from).getTime()) / 86_400_000) + 1;
}

/** First weekday for a locale (0 = Sunday), from `Intl.Locale` week info where the browser has it. */
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;
}

export type DateRange = { from: Date | null; to: Date | null };

interface CalendarBaseProps {
  /** The month on screen (controlled). Any day in the month works. */
  month?: Date;
  defaultMonth?: Date;
  onMonthChange?: (month: Date) => void;
  /** Days that cannot be picked: a predicate or a list. They stay focusable so arrow keys can pass them. */
  disabled?: ((date: Date) => boolean) | Date[];
  /** Earliest pickable day. Navigation stops at its month. */
  minDate?: Date;
  /** Latest pickable day. Navigation stops at its month. */
  maxDate?: Date;
  /** First column, 0 for Sunday to 6 for Saturday. Defaults to the locale's first day. */
  weekStartsOn?: number;
  /** BCP 47 locale for month and weekday names. Defaults to the browser's. */
  locale?: string;
  /** Months side by side. Two suits range picking. */
  numberOfMonths?: 1 | 2;
  /** Shows the trailing and leading days of the neighbouring months, dimmed. */
  showOutsideDays?: boolean;
  /** Overrides "today", for example to match a server clock. */
  today?: Date;
  /** Focuses the selected day (or today) when the calendar mounts, as inside a popover. */
  autoFocus?: boolean;
  className?: string;
}

export interface CalendarSingleProps extends CalendarBaseProps {
  mode?: "single";
  value?: Date | null;
  defaultValue?: Date | null;
  onValueChange?: (value: Date | null) => void;
}

export interface CalendarRangeProps extends CalendarBaseProps {
  mode: "range";
  value?: DateRange;
  defaultValue?: DateRange;
  onValueChange?: (value: DateRange) => void;
}

export type CalendarProps = CalendarSingleProps | CalendarRangeProps;

/**
 * A month grid with single or range selection. Arrow keys move by day and week, Home and End jump
 * to the week's edges, Page Up and Page Down change month (with Shift, year). Labels come from
 * `Intl`, so weekdays and months follow the locale.
 */
export function Calendar(props: CalendarProps) {
  const {
    mode = "single",
    month: monthProp,
    defaultMonth,
    onMonthChange,
    disabled,
    minDate,
    maxDate,
    weekStartsOn: weekStartsOnProp,
    locale,
    numberOfMonths = 1,
    showOutsideDays = numberOfMonths === 1,
    today: todayProp,
    autoFocus = false,
    className,
  } = props;

  // Selection, controlled or not. Both modes share one state slot.
  const [innerSingle, setInnerSingle] = useState<Date | null>(mode === "single" ? ((props as CalendarSingleProps).defaultValue ?? null) : null);
  const [innerRange, setInnerRange] = useState<DateRange>(
    mode === "range" ? ((props as CalendarRangeProps).defaultValue ?? { from: null, to: null }) : { from: null, to: null },
  );
  const single = mode === "single" ? ((props as CalendarSingleProps).value !== undefined ? (props as CalendarSingleProps).value ?? null : innerSingle) : null;
  const range = mode === "range" ? ((props as CalendarRangeProps).value ?? innerRange) : { from: null, to: null };

  const today = useMemo(() => startOfDay(todayProp ?? new Date()), [todayProp]);
  const anchor = (mode === "single" ? single : range.from) ?? today;
  const [innerMonth, setInnerMonth] = useState(() => startOfMonth(defaultMonth ?? anchor));
  const month = startOfMonth(monthProp ?? innerMonth);
  const [focused, setFocused] = useState<Date>(() => startOfDay(anchor));
  const [hovered, setHovered] = useState<Date | null>(null);
  const [weekStartsOn, setWeekStartsOn] = useState(weekStartsOnProp ?? 0);
  const [input, setInput] = useState<"pointer" | "keyboard">("pointer");
  const rootRef = useRef<HTMLDivElement>(null);
  const shouldFocus = useRef(autoFocus);

  // The locale's week start needs `navigator`, so it resolves after mount.
  useEffect(() => {
    if (weekStartsOnProp === undefined) setWeekStartsOn(localeWeekStart(locale));
    else setWeekStartsOn(weekStartsOnProp);
  }, [weekStartsOnProp, locale]);

  useEffect(() => {
    if (!shouldFocus.current) return;
    shouldFocus.current = false;
    rootRef.current?.querySelector<HTMLButtonElement>('button[tabindex="0"]')?.focus();
  });

  const min = minDate ? startOfDay(minDate) : null;
  const max = maxDate ? startOfDay(maxDate) : null;
  const disabledKeys = useMemo(() => (Array.isArray(disabled) ? new Set(disabled.map(dayKey)) : null), [disabled]);

  function isDisabled(date: Date) {
    if (min && date < min) return true;
    if (max && date > max) return true;
    if (typeof disabled === "function") return disabled(date);
    return disabledKeys?.has(dayKey(date)) ?? false;
  }

  function setMonth(next: Date) {
    const value = startOfMonth(next);
    if (!monthProp) setInnerMonth(value);
    onMonthChange?.(value);
  }

  const lastVisible = addMonths(month, numberOfMonths - 1);
  const canPrev = !min || startOfMonth(min) < month;
  const canNext = !max || startOfMonth(max) > lastVisible;

  function moveFocus(next: Date) {
    let target = next;
    if (min && target < min) target = min;
    if (max && target > max) target = max;
    setFocused(target);
    if (target < month) setMonth(target);
    else if (target > new Date(lastVisible.getFullYear(), lastVisible.getMonth() + 1, 0)) setMonth(addMonths(startOfMonth(target), -(numberOfMonths - 1)));
    shouldFocus.current = true;
  }

  function select(date: Date) {
    if (isDisabled(date)) return;
    setFocused(date);
    if (!isSameMonth(date, month) && !isSameMonth(date, lastVisible)) setMonth(date < month ? date : addMonths(startOfMonth(date), -(numberOfMonths - 1)));
    if (mode === "single") {
      const p = props as CalendarSingleProps;
      if (p.value === undefined) setInnerSingle(date);
      p.onValueChange?.(date);
      return;
    }
    const p = props as CalendarRangeProps;
    let next: DateRange;
    if (!range.from || range.to) next = { from: date, to: null };
    else if (date < range.from) next = { from: date, to: range.from };
    else next = { from: range.from, to: date };
    // A range never spans a disabled day.
    if (next.from && next.to) {
      for (let day = next.from; day <= next.to; day = addDays(day, 1)) {
        if (isDisabled(day)) {
          next = { from: date, to: null };
          break;
        }
      }
    }
    if (p.value === undefined) setInnerRange(next);
    p.onValueChange?.(next);
  }

  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    const step: Record<string, () => Date> = {
      ArrowLeft: () => addDays(focused, -1),
      ArrowRight: () => addDays(focused, 1),
      ArrowUp: () => addDays(focused, -7),
      ArrowDown: () => addDays(focused, 7),
      Home: () => addDays(focused, -((focused.getDay() - weekStartsOn + 7) % 7)),
      End: () => addDays(focused, 6 - ((focused.getDay() - weekStartsOn + 7) % 7)),
      PageUp: () => addMonths(focused, event.shiftKey ? -12 : -1),
      PageDown: () => addMonths(focused, event.shiftKey ? 12 : 1),
    };
    const next = step[event.key];
    if (!next) return;
    event.preventDefault();
    setInput("keyboard");
    moveFocus(next());
  }

  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" });
    // 2023-01-01 was a Sunday.
    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]);

  // While picking the end of a range, hovering previews the span.
  const preview = mode === "range" && range.from && !range.to && hovered ? (hovered < range.from ? { from: hovered, to: range.from } : { from: range.from, to: hovered }) : null;
  const months = Array.from({ length: numberOfMonths }, (_, index) => addMonths(month, index));
  // The roving tab stop stays on a visible day.
  const focusTarget = months.some((visible) => isSameMonth(visible, focused)) ? focused : (single && months.some((m) => isSameMonth(m, single)) ? single : month);

  return (
    <div
      ref={rootRef}
      data-slot="calendar"
      data-mode={mode}
      className={cx("inline-grid gap-4 text-sm text-zinc-950 dark:text-white", numberOfMonths === 2 && "sm:grid-cols-2 sm:gap-6", className)}
      onPointerDown={() => setInput("pointer")}
    >
      {months.map((visible, monthIndex) => {
        const first = startOfMonth(visible);
        const offset = (first.getDay() - weekStartsOn + 7) % 7;
        const gridStart = addDays(first, -offset);
        const days = Array.from({ length: 42 }, (_, index) => addDays(gridStart, index));
        const weeks = Array.from({ length: 6 }, (_, row) => days.slice(row * 7, row * 7 + 7));
        const title = monthFormat.format(visible);
        const titleId = `${dayKey(first)}-title`;
        const isFirst = monthIndex === 0;
        const isLast = monthIndex === numberOfMonths - 1;

        return (
          <div key={dayKey(first)} className="grid w-[17.5rem] gap-2">
            <div className="relative flex h-8 items-center justify-center">
              {isFirst ? (
                <NavButton label="Previous month" disabled={!canPrev} onClick={() => setMonth(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">
                {title}
              </h2>
              {isLast ? (
                <NavButton label="Next month" disabled={!canNext} onClick={() => setMonth(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={mode === "range" || undefined}
              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 font-normal text-zinc-500">
                    {weekday.short}
                  </div>
                ))}
              </div>
              <div
                key={`${dayKey(first)}-body`}
                className={cx(
                  "grid gap-0.5",
                  // Clicking the arrows cross-fades the month; keyboard paging switches instantly.
                  input === "pointer" && "transition-opacity duration-150 ease-out motion-reduce:transition-none starting:opacity-0",
                )}
              >
                {weeks.map((week, row) => (
                  <div key={row} role="row" className="grid grid-cols-7">
                    {week.map((date, column) => {
                      const outside = !isSameMonth(date, visible);
                      if (outside && !showOutsideDays) return <div key={dayKey(date)} role="gridcell" aria-hidden="true" className="h-9" />;
                      const blocked = isDisabled(date);
                      const isToday = isSameDay(date, today);
                      const span = preview ?? (range.from && range.to ? range : null);
                      const isStart = mode === "range" && isSameDay(date, span?.from ?? range.from);
                      const isEnd = mode === "range" && isSameDay(date, span?.to ?? null);
                      const inSpan = !!span?.from && !!span.to && date >= span.from && date <= span.to;
                      const committed = !preview;
                      const isSelected = mode === "single" ? isSameDay(date, single) : isSameDay(date, range.from) || isSameDay(date, range.to);
                      const solid = mode === "single" ? isSelected : (isStart || isEnd) && (committed || isSameDay(date, range.from));
                      const tabbable = isSameDay(date, focusTarget) && !outside;
                      const bandStart = isStart || column === 0 || date.getDate() === 1;
                      const bandEnd = isEnd || column === 6 || isSameDay(date, new Date(date.getFullYear(), date.getMonth() + 1, 0));

                      return (
                        <div
                          key={dayKey(date)}
                          role="gridcell"
                          aria-selected={mode === "range" ? inSpan && committed : isSelected}
                          className={cx(
                            "relative flex h-9 items-center justify-center",
                            inSpan && !outside && cx(
                              "before:absolute before:inset-y-0 before:inset-x-0",
                              committed ? "before:bg-zinc-950/[0.06] dark:before:bg-white/[0.09]" : "before:bg-zinc-950/[0.035] dark:before:bg-white/[0.05]",
                              bandStart && "before:rounded-l-lg",
                              bandEnd && "before:rounded-r-lg",
                            ),
                          )}
                        >
                          <button
                            type="button"
                            tabIndex={tabbable ? 0 : -1}
                            aria-disabled={blocked || undefined}
                            aria-current={isToday ? "date" : undefined}
                            aria-label={dayFormat.format(date)}
                            onClick={() => select(date)}
                            onPointerEnter={() => mode === "range" && setHovered(date)}
                            onFocus={() => setFocused(date)}
                            className={cx(
                              "relative z-[1] flex size-9 flex-col items-center justify-center rounded-lg text-sm tabular-nums",
                              "transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
                              "focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-sky-500",
                              solid
                                ? "bg-zinc-950 font-medium text-white dark:bg-white dark:text-black"
                                : blocked
                                  ? "cursor-not-allowed text-zinc-400 line-through decoration-zinc-950/25 dark:text-zinc-600 dark:decoration-white/25"
                                  : cx(
                                      outside
                                        ? "text-zinc-400 dark:text-zinc-600"
                                        : inSpan || isToday
                                          ? "text-zinc-950 dark:text-white"
                                          : "text-zinc-700 dark:text-zinc-300",
                                      "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>
        );
      })}
    </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-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>
  );
}